_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
angular/devtools/cypress/integration/node-search.e2e.js_0_2980 | /**
* @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 checkSearchedNodesLength(type, length) {
cy.get(`.tree-wrapper:first ${type}`).its('length').should('eq', length);
}
function inputSearchText(text) {
cy.get('.filter-input').type(text, {force: true});
}
function checkComponentName(name) {
cy.get('.component-name').should('have.text', name);
}
function checkEmptyNodes() {
cy.get('.tree-wrapper').find('.matched').should('not.exist');
}
function clickSearchArrows(upwards) {
const buttons = cy.get('.up-down-buttons').find('button');
if (upwards) {
buttons.first().then((btn) => btn[0].click());
} else {
buttons.last().then((btn) => btn[0].click());
}
}
describe('Search items in component tree', () => {
beforeEach(() => {
cy.visit('/');
});
it('should not highlight any node if not present', () => {
inputSearchText('tado');
checkEmptyNodes();
});
it('should highlight correct nodes when searching and clear out', () => {
inputSearchText('todo');
checkSearchedNodesLength('.matched', 4);
// clear search input
inputSearchText('{backspace}{backspace}{backspace}{backspace}');
checkEmptyNodes();
});
it('should highlight correct nodes when searching and using arrow keys', () => {
inputSearchText('todo');
checkSearchedNodesLength('.matched', 4);
// press down arrow
clickSearchArrows(false);
checkSearchedNodesLength('.selected', 1);
checkComponentName('app-todo-demo');
// press up arrow
clickSearchArrows(false);
checkSearchedNodesLength('.selected', 1);
checkComponentName('app-todos');
// press up arrow
clickSearchArrows(true);
checkSearchedNodesLength('.selected', 1);
checkComponentName('app-todo-demo');
// clear search input
inputSearchText('{backspace}{backspace}{backspace}{backspace}');
checkEmptyNodes();
});
it('should select correct node on enter', () => {
inputSearchText('todos{enter}');
checkSearchedNodesLength('.selected', 1);
// should show correct buttons in breadcrumbs
const amountOfBreadcrumbButtons = 4;
const amountOfScrollButtons = 2;
cy.get('ng-breadcrumbs')
.find('button')
.its('length')
.should('eq', amountOfScrollButtons + amountOfBreadcrumbButtons);
// should display correct text in explorer panel
checkComponentName('app-todos');
// should display correct title for properties panel
cy.get('ng-property-view-header').should('have.text', 'app-todos');
// should show correct component properties
cy.get('ng-property-view').find('mat-tree-node');
});
it('should focus search input when search icon is clicked', () => {
cy.get('.filter label .search-icon').click({force: true});
cy.get('.filter label input').should('have.focus');
});
});
| {
"end_byte": 2980,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/cypress/integration/node-search.e2e.js"
} |
angular/devtools/cypress/integration/base.e2e.js_0_998 | /**
* @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
*/
require('cypress-iframe');
describe('Testing the Todo app Demo', () => {
beforeEach(() => {
cy.visit('/');
});
it('should contain the todos application', () => {
cy.enter('#sample-app').then((getBody) => {
getBody().contains('Todos');
getBody().contains('About');
getBody().contains('Clear completed');
getBody().contains('Click to expand');
});
});
it('should contain the "Components" tab', () => {
cy.contains('.mat-tab-links', 'Components');
});
it('should contain the "Profiler" tab', () => {
cy.contains('.mat-tab-links', 'Profiler');
});
it('should contain "app-root" and "app-todo-demo" in the component tree', () => {
cy.contains('.tree-node', 'app-root');
cy.contains('.tree-node', 'app-todo-demo');
});
});
| {
"end_byte": 998,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/cypress/integration/base.e2e.js"
} |
angular/devtools/cypress/integration/view-component-metadata.e2e.js_0_2286 | /**
* @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
*/
const prepareHeaderExpansionPanelForAssertions = (selector) => {
cy.get('.tree-wrapper').find(selector).first().click({force: true});
cy.get('.element-header .component-name').click();
};
describe('Viewing component metadata', () => {
beforeEach(() => {
cy.visit('/');
});
describe('viewing TodoComponent', () => {
beforeEach(() =>
prepareHeaderExpansionPanelForAssertions('.tree-node:contains("app-todo[TooltipDirective]")'),
);
it('should display view encapsulation', () => {
cy.contains('.meta-data-container .mat-button:first', 'View Encapsulation: Emulated');
});
it('should display change detection strategy', () => {
cy.contains('.meta-data-container .mat-button:last', 'Change Detection Strategy: OnPush');
});
});
describe('viewing DemoAppComponent', () => {
beforeEach(() =>
prepareHeaderExpansionPanelForAssertions('.tree-node:contains("app-demo-component")'),
);
it('should display view encapsulation', () => {
cy.contains('.meta-data-container .mat-button:first', 'View Encapsulation: None');
});
it('should display change detection strategy', () => {
cy.contains('.meta-data-container .mat-button:last', 'Change Detection Strategy: Default');
});
it('should display correct set of inputs', () => {
cy.contains('.cy-inputs', '@Inputs');
cy.contains('.cy-inputs mat-tree-node:first span:first', 'inputOne');
cy.contains('.cy-inputs mat-tree-node:last span:first', 'inputTwo');
});
it('should display correct set of outputs', () => {
cy.contains('.cy-outputs', '@Outputs');
cy.contains('.cy-outputs mat-tree-node:first span:first', 'outputOne');
cy.contains('.cy-outputs mat-tree-node:last span:first', 'outputTwo');
});
it('should display correct set of properties', () => {
cy.contains('.cy-properties', 'Properties');
cy.contains('.cy-properties mat-tree-node:first span:first', 'elementRef');
cy.contains('.cy-properties mat-tree-node:last span:first', 'zippy');
});
});
});
| {
"end_byte": 2286,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/cypress/integration/view-component-metadata.e2e.js"
} |
angular/devtools/cypress/integration/node-selection.e2e.js_0_4793 | /**
* @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
*/
require('cypress-iframe');
describe('node selection', () => {
beforeEach(() => {
cy.visit('/');
});
describe('logic after change detection', () => {
it('should deselect node if it is no longer on the page', () => {
cy.get('.tree-wrapper').get('.tree-node.selected').should('not.exist');
cy.get('.tree-wrapper')
.find('.tree-node:contains("app-todo[TooltipDirective]")')
.first()
.click({force: true});
cy.get('.tree-wrapper').find('.tree-node.selected').its('length').should('eq', 1);
cy.enter('#sample-app').then((getBody) => {
getBody().find('a:contains("About")').click();
});
cy.get('.tree-wrapper').get('.tree-node.selected').should('not.exist');
});
it('should reselect the previously selected node if it is still present', () => {
cy.get('.tree-wrapper').get('.tree-node.selected').should('not.exist');
cy.enter('#sample-app').then((getBody) => {
getBody().find('input.new-todo').type('Buy cookies{enter}');
});
cy.get('.tree-wrapper')
.find('.tree-node:contains("app-todo[TooltipDirective]")')
.last()
.click({force: true});
cy.enter('#sample-app').then((getBody) => {
getBody().find('app-todo:contains("Buy milk")').find('.destroy').click();
});
cy.get('.tree-wrapper').find('.tree-node.selected').its('length').should('eq', 1);
});
it('should select nodes with same name', () => {
cy.get('.tree-wrapper')
.find('.tree-node:contains("app-todo[TooltipDirective]")')
.first()
.click({force: true});
cy.get('.tree-wrapper')
.find('.tree-node:contains("app-todo[TooltipDirective]")')
.last()
.click({force: true});
cy.get('ng-property-view').last().find('mat-tree-node:contains("todo")').click();
cy.get('ng-property-view')
.last()
.find('mat-tree-node:contains("Build something fun!")')
.its('length')
.should('eq', 1);
});
});
describe('breadcrumb logic', () => {
it('should overflow when breadcrumb list is long enough', () => {
cy.get('.tree-wrapper')
.find('.tree-node:contains("div[TooltipDirective]")')
.last()
.click({force: true})
.then(() => {
cy.get('ng-breadcrumbs')
.find('.breadcrumbs')
.then((breadcrumbsContainer) => {
const hasOverflowX = () =>
breadcrumbsContainer[0].scrollWidth > breadcrumbsContainer[0].clientWidth;
expect(hasOverflowX()).to.be.true;
});
});
});
it('should scroll right when right scroll button is clicked', () => {
cy.get('.tree-wrapper')
.find('.tree-node:contains("div[TooltipDirective]")')
.last()
.click({force: true})
.then(() => {
cy.get('ng-breadcrumbs')
.find('.breadcrumbs')
.then((el) => {
el[0].style.scrollBehavior = 'auto';
})
.then((breadcrumbsContainer) => {
const scrollLeft = () => breadcrumbsContainer[0].scrollLeft;
expect(scrollLeft()).to.eql(0);
cy.get('ng-breadcrumbs')
.find('.scroll-button')
.last()
.click()
.then(() => {
expect(scrollLeft()).to.be.greaterThan(0);
});
});
});
});
it('should scroll left when left scroll button is clicked', () => {
cy.get('.tree-wrapper')
.find('.tree-node:contains("div[TooltipDirective]")')
.last()
.click({force: true})
.then(() => {
cy.get('ng-breadcrumbs')
.find('.breadcrumbs')
.then((el) => {
el[0].style.scrollBehavior = 'auto';
})
.then((breadcrumbsContainer) => {
const scrollLeft = () => breadcrumbsContainer[0].scrollLeft;
expect(scrollLeft()).to.eql(0);
cy.get('ng-breadcrumbs')
.find('.scroll-button')
.last()
.click()
.then(() => {
expect(scrollLeft()).to.be.greaterThan(0);
cy.get('ng-breadcrumbs')
.find('.scroll-button')
.first()
.click()
.then(() => {
expect(scrollLeft()).to.eql(0);
});
});
});
});
});
});
});
| {
"end_byte": 4793,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/cypress/integration/node-selection.e2e.js"
} |
angular/devtools/cypress/integration/comment-nodes.e2e.js_0_813 | /**
* @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 showComments() {
cy.get('#nav-buttons > button:nth-child(2)').click();
cy.get('#mat-slide-toggle-3 > label > div').click();
}
describe('Comment nodes', () => {
beforeEach(() => {
cy.visit('/');
});
it('should not find any comment nodes by default', () => {
const nodes = cy.$$('.tree-node:contains("#comment")');
expect(nodes.length).to.eql(0);
});
it('should find comment nodes when the setting is enabled', () => {
showComments();
cy.get('.tree-wrapper')
.find('.tree-node:contains("#comment")')
.its('length')
.should('not.eq', 0);
});
});
| {
"end_byte": 813,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/cypress/integration/comment-nodes.e2e.js"
} |
angular/devtools/cypress/support/index.js_0_875 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// ***********************************************************
// This example support/index.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************
// Import commands.js using ES2015 syntax:
import './commands';
// Alternatively you can use CommonJS syntax:
// require('./commands')
| {
"end_byte": 875,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/cypress/support/index.js"
} |
angular/devtools/cypress/support/commands.js_0_1042 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add("login", (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })
| {
"end_byte": 1042,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/cypress/support/commands.js"
} |
angular/devtools/projects/ng-devtools-backend/README.md_0_206 | # Angular DevTools Backend
This directory contains the "backend" of Angular DevTools. This module interacts with the framework debugging APIs and responses to requests from the Angular DevTools extension.
| {
"end_byte": 206,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/README.md"
} |
angular/devtools/projects/ng-devtools-backend/BUILD.bazel_0_452 | load("@build_bazel_rules_nodejs//:index.bzl", "js_library")
load("//devtools/tools:typescript.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "ng_devtools_backend_ts",
srcs = ["index.ts"],
deps = [
"//devtools/projects/ng-devtools-backend/src",
],
)
js_library(
name = "ng-devtools-backend",
package_name = "ng-devtools-backend",
deps = [":ng_devtools_backend_ts"],
)
| {
"end_byte": 452,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/BUILD.bazel"
} |
angular/devtools/projects/ng-devtools-backend/index.ts_0_238 | /**
* @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 * from './src/public-api';
| {
"end_byte": 238,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/index.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/public-api.ts_0_349 | /**
* @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
*/
/*
* Public API Surface of ng-devtools-backend
*/
export * from './lib';
export {findNodeFromSerializedPosition} from './lib/component-tree';
| {
"end_byte": 349,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/public-api.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/BUILD.bazel_0_325 | load("//devtools/tools:typescript.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "src",
srcs = ["public-api.ts"],
deps = [
"//devtools/projects/ng-devtools-backend/src/lib",
"//devtools/projects/ng-devtools-backend/src/lib:component_tree",
],
)
| {
"end_byte": 325,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/BUILD.bazel"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/component-tree.ts_0_7318 | /**
* @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 {
ComponentExplorerViewQuery,
DirectiveMetadata,
DirectivesProperties,
ElementPosition,
PropertyQueryTypes,
SerializedInjectedService,
SerializedInjector,
SerializedProviderRecord,
UpdatedStateData,
} from 'protocol';
import {buildDirectiveTree, getLViewFromDirectiveOrElementInstance} from './directive-forest/index';
import {
ngDebugApiIsSupported,
ngDebugClient,
ngDebugDependencyInjectionApiIsSupported,
} from './ng-debug-api/ng-debug-api';
import {
deeplySerializeSelectedProperties,
serializeDirectiveState,
} from './state-serializer/state-serializer';
// Need to be kept in sync with Angular framework
// We can't directly import it from framework now
// because this also pulls up the security policies
// for Trusted Types, which we reinstantiate.
enum ChangeDetectionStrategy {
OnPush = 0,
Default = 1,
}
import {ComponentTreeNode, DirectiveInstanceType, ComponentInstanceType} from './interfaces';
import type {
ClassProvider,
ExistingProvider,
FactoryProvider,
InjectOptions,
InjectionToken,
Injector,
Type,
ValueProvider,
ɵComponentDebugMetadata as ComponentDebugMetadata,
ɵProviderRecord as ProviderRecord,
} from '@angular/core';
import {isSignal} from './utils';
export const injectorToId = new WeakMap<Injector | HTMLElement, string>();
export const nodeInjectorToResolutionPath = new WeakMap<HTMLElement, SerializedInjector[]>();
export const idToInjector = new Map<string, Injector>();
export const injectorsSeen = new Set<string>();
let injectorId = 0;
export function getInjectorId() {
return `${injectorId++}`;
}
export function getInjectorMetadata(injector: Injector) {
return ngDebugClient().ɵgetInjectorMetadata(injector);
}
export function getInjectorResolutionPath(injector: Injector): Injector[] {
if (!ngDebugApiIsSupported('ɵgetInjectorResolutionPath')) {
return [];
}
return ngDebugClient().ɵgetInjectorResolutionPath(injector);
}
export function getInjectorFromElementNode(element: Node): Injector | null {
return ngDebugClient().getInjector(element);
}
function getDirectivesFromElement(element: HTMLElement): {
component: unknown | null;
directives: unknown[];
} {
let component = null;
if (element instanceof Element) {
component = ngDebugClient().getComponent(element);
}
return {
component,
directives: ngDebugClient().getDirectives(element),
};
}
export const getLatestComponentState = (
query: ComponentExplorerViewQuery,
directiveForest?: ComponentTreeNode[],
): {directiveProperties: DirectivesProperties} | undefined => {
// if a directive forest is passed in we don't have to build the forest again.
directiveForest = directiveForest ?? buildDirectiveForest();
const node = queryDirectiveForest(query.selectedElement, directiveForest);
if (!node) {
return;
}
const directiveProperties: DirectivesProperties = {};
const injector = ngDebugClient().getInjector(node.nativeElement!);
const injectors = getInjectorResolutionPath(injector);
const resolutionPathWithProviders = !ngDebugDependencyInjectionApiIsSupported()
? []
: injectors.map((injector) => ({
injector,
providers: getInjectorProviders(injector),
}));
const populateResultSet = (dir: DirectiveInstanceType | ComponentInstanceType) => {
const {instance, name} = dir;
const metadata = getDirectiveMetadata(instance);
metadata.dependencies = getDependenciesForDirective(
injector,
resolutionPathWithProviders,
instance.constructor,
);
if (query.propertyQuery.type === PropertyQueryTypes.All) {
directiveProperties[dir.name] = {
props: serializeDirectiveState(instance),
metadata,
};
}
if (query.propertyQuery.type === PropertyQueryTypes.Specified) {
directiveProperties[name] = {
props: deeplySerializeSelectedProperties(
instance,
query.propertyQuery.properties[name] || [],
),
metadata,
};
}
};
node.directives.forEach((dir) => populateResultSet(dir));
if (node.component) {
populateResultSet(node.component);
}
return {
directiveProperties,
};
};
function serializeElementInjectorWithId(injector: Injector): SerializedInjector | null {
let id: string;
const element = getElementInjectorElement(injector);
if (!injectorToId.has(element)) {
id = getInjectorId();
injectorToId.set(element, id);
idToInjector.set(id, injector);
}
id = injectorToId.get(element)!;
idToInjector.set(id, injector);
injectorsSeen.add(id);
const serializedInjector = serializeInjector(injector);
if (serializedInjector === null) {
return null;
}
return {id, ...serializedInjector};
}
function serializeInjectorWithId(injector: Injector): SerializedInjector | null {
if (isElementInjector(injector)) {
return serializeElementInjectorWithId(injector);
} else {
return serializeEnvironmentInjectorWithId(injector);
}
}
function serializeEnvironmentInjectorWithId(injector: Injector): SerializedInjector | null {
let id: string;
if (!injectorToId.has(injector)) {
id = getInjectorId();
injectorToId.set(injector, id);
idToInjector.set(id, injector);
}
id = injectorToId.get(injector)!;
idToInjector.set(id, injector);
injectorsSeen.add(id);
const serializedInjector = serializeInjector(injector);
if (serializedInjector === null) {
return null;
}
return {id, ...serializedInjector};
}
const enum DirectiveMetadataKey {
INPUTS = 'inputs',
OUTPUTS = 'outputs',
ENCAPSULATION = 'encapsulation',
ON_PUSH = 'onPush',
}
// Gets directive metadata. For newer versions of Angular (v12+) it uses
// the global `getDirectiveMetadata`. For prior versions of the framework
// the method directly interacts with the directive/component definition.
const getDirectiveMetadata = (dir: any): DirectiveMetadata => {
const getMetadata = ngDebugClient().getDirectiveMetadata;
const metadata = getMetadata?.(dir) as ComponentDebugMetadata;
if (metadata) {
return {
inputs: metadata.inputs,
outputs: metadata.outputs,
encapsulation: metadata.encapsulation,
onPush: metadata.changeDetection === ChangeDetectionStrategy.OnPush,
};
}
// Used in older Angular versions, prior to the introduction of `getDirectiveMetadata`.
const safelyGrabMetadata = (key: DirectiveMetadataKey) => {
try {
return dir.constructor.ɵcmp ? dir.constructor.ɵcmp[key] : dir.constructor.ɵdir[key];
} catch {
console.warn(`Could not find metadata for key: ${key} in directive:`, dir);
return undefined;
}
};
return {
inputs: safelyGrabMetadata(DirectiveMetadataKey.INPUTS),
outputs: safelyGrabMetadata(DirectiveMetadataKey.OUTPUTS),
encapsulation: safelyGrabMetadata(DirectiveMetadataKey.ENCAPSULATION),
onPush: safelyGrabMetadata(DirectiveMetadataKey.ON_PUSH),
};
};
export function getInjectorProviders(injector: Injector) {
if (isNullInjector(injector)) {
return [];
}
return ngDebugClient().ɵgetInjectorProviders(injector);
}
const g | {
"end_byte": 7318,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/component-tree.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/component-tree.ts_7320_15768 | DependenciesForDirective = (
injector: Injector,
resolutionPath: {injector: Injector; providers: ProviderRecord[]}[],
directive: any,
): SerializedInjectedService[] => {
if (!ngDebugApiIsSupported('ɵgetDependenciesFromInjectable')) {
return [];
}
let dependencies =
ngDebugClient().ɵgetDependenciesFromInjectable(injector, directive)?.dependencies ?? [];
const uniqueServices = new Set<string>();
const serializedInjectedServices: SerializedInjectedService[] = [];
let position = 0;
for (const dependency of dependencies) {
const providedIn = dependency.providedIn;
const foundInjectorIndex = resolutionPath.findIndex((node) => node.injector === providedIn);
if (foundInjectorIndex === -1) {
position++;
continue;
}
const providers = resolutionPath[foundInjectorIndex].providers;
const foundProvider = providers.find((provider) => provider.token === dependency.token);
// the dependency resolution path is
// the path from the root injector to the injector that provided the dependency (1)
// +
// the import path from the providing injector to the feature module that provided the
// dependency (2)
const dependencyResolutionPath: SerializedInjector[] = [
// (1)
...resolutionPath
.slice(0, foundInjectorIndex + 1)
.map((node) => serializeInjectorWithId(node.injector)!),
// (2)
// We slice the import path to remove the first element because this is the same
// injector as the last injector in the resolution path.
...(foundProvider?.importPath ?? []).slice(1).map((node) => {
return {type: 'imported-module', name: valueToLabel(node), id: getInjectorId()};
}),
];
let flags = dependency.flags as InjectOptions;
let flagToken = '';
if (flags !== undefined) {
// TODO: We need to remove this once the InjectFlags enum is removed from core
if (typeof flags === 'number') {
flags = {
optional: !!(flags & 8),
skipSelf: !!(flags & 4),
self: !!(flags & 2),
host: !!(flags & 1),
};
}
flagToken = (['optional', 'skipSelf', 'self', 'host'] as (keyof InjectOptions)[])
.filter((key) => flags[key])
.join('-');
}
const serviceKey = `${dependency.token}-${flagToken}`;
if (!uniqueServices.has(serviceKey)) {
uniqueServices.add(serviceKey);
const service = {
token: valueToLabel(dependency.token),
value: valueToLabel(dependency.value),
flags,
position: [position],
resolutionPath: dependencyResolutionPath,
};
if (dependency.token && isInjectionToken(dependency.token)) {
service.token = dependency.token!.toString();
}
serializedInjectedServices.push(service);
}
position++;
}
return serializedInjectedServices;
};
const valueToLabel = (value: any): string => {
if (isInjectionToken(value)) {
return `InjectionToken(${value['_desc']})`;
}
if (typeof value === 'object') {
return stripUnderscore(value.constructor.name);
}
if (typeof value === 'function') {
return stripUnderscore(value.name);
}
return stripUnderscore(value);
};
function stripUnderscore(str: string): string {
if (str.startsWith('_')) {
return str.slice(1);
}
return str;
}
export function serializeInjector(injector: Injector): Omit<SerializedInjector, 'id'> | null {
const metadata = getInjectorMetadata(injector);
if (metadata === null) {
console.error('Angular DevTools: Could not serialize injector.', injector);
return null;
}
const providers = getInjectorProviders(injector).length;
if (metadata.type === 'null') {
return {type: 'null', name: 'Null Injector', providers: 0};
}
if (metadata.type === 'element') {
const source = metadata.source as HTMLElement;
const name = stripUnderscore(elementToDirectiveNames(source)[0]);
return {type: 'element', name, providers};
}
if (metadata.type === 'environment') {
if ((injector as any).scopes instanceof Set) {
if ((injector as any).scopes.has('platform')) {
return {type: 'environment', name: 'Platform', providers};
}
if ((injector as any).scopes.has('root')) {
return {type: 'environment', name: 'Root', providers};
}
}
return {type: 'environment', name: stripUnderscore(metadata.source ?? ''), providers};
}
console.error('Angular DevTools: Could not serialize injector.', injector);
return null;
}
export function serializeProviderRecord(
providerRecord: ProviderRecord,
index: number,
hasImportPath = false,
): SerializedProviderRecord {
let type: 'type' | 'class' | 'value' | 'factory' | 'existing' = 'type';
let multi = false;
if (typeof providerRecord.provider === 'object') {
if ((providerRecord.provider as ClassProvider).useClass !== undefined) {
type = 'class';
} else if ((providerRecord.provider as ValueProvider).useValue !== undefined) {
type = 'value';
} else if ((providerRecord.provider as FactoryProvider).useFactory !== undefined) {
type = 'factory';
} else if ((providerRecord.provider as ExistingProvider).useExisting !== undefined) {
type = 'existing';
}
if (providerRecord.provider.multi !== undefined) {
multi = providerRecord.provider.multi;
}
}
const serializedProvider: {
token: string;
type: typeof type;
multi: boolean;
isViewProvider: boolean;
index: number;
importPath?: string[];
} = {
token: valueToLabel(providerRecord.token),
type,
multi,
isViewProvider: providerRecord.isViewProvider,
index,
};
if (hasImportPath) {
serializedProvider['importPath'] = (providerRecord.importPath ?? []).map((injector) =>
valueToLabel(injector),
);
}
return serializedProvider;
}
function elementToDirectiveNames(element: HTMLElement): string[] {
const {component, directives} = getDirectivesFromElement(element);
return [component, ...directives]
.map((dir) => dir?.constructor?.name ?? '')
.filter((dir) => !!dir);
}
export function getElementInjectorElement(elementInjector: Injector): HTMLElement {
if (!isElementInjector(elementInjector)) {
throw new Error('Injector is not an element injector');
}
return getInjectorMetadata(elementInjector)!.source as HTMLElement;
}
function isInjectionToken(token: Type<unknown> | InjectionToken<unknown>): boolean {
return token.constructor.name === 'InjectionToken';
}
export function isElementInjector(injector: Injector) {
const metadata = getInjectorMetadata(injector);
return metadata !== null && metadata.type === 'element';
}
function isNullInjector(injector: Injector) {
const metadata = getInjectorMetadata(injector);
return metadata !== null && metadata.type === 'null';
}
const getRootLViewsHelper = (element: Element, rootLViews = new Set<any>()): Set<any> => {
if (!(element instanceof HTMLElement)) {
return rootLViews;
}
const lView = getLViewFromDirectiveOrElementInstance(element);
if (lView) {
rootLViews.add(lView);
return rootLViews;
}
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < element.children.length; i++) {
getRootLViewsHelper(element.children[i], rootLViews);
}
return rootLViews;
};
const getRoots = () => {
const roots = Array.from(document.documentElement.querySelectorAll('[ng-version]'));
const isTopLevel = (element: Element) => {
let parent: Element | null = element;
while (parent?.parentElement) {
parent = parent.parentElement;
if (parent.hasAttribute('ng-version')) {
return false;
}
}
return true;
};
return roots.filter(isTopLevel);
};
export const buildDirectiveForest = (): ComponentTreeNode[] => {
const roots = getRoots();
return Array.prototype.concat.apply([], Array.from(roots).map(buildDirectiveTree));
};
// Based on an ElementID we return a specific component node.
// If we can't find any, we return null.
export const queryDirectiveForest = (
position: ElementPosition,
forest: ComponentTreeNode[],
): ComponentTreeNode | null => {
if (!position.length) {
return null;
}
let node: null | ComponentTreeNode = null;
for (const i of position) {
node = forest[i];
if (!node) {
return null;
}
forest = node.children;
}
return node;
};
export co | {
"end_byte": 15768,
"start_byte": 7320,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/component-tree.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/component-tree.ts_15770_18674 | t findNodeInForest = (
position: ElementPosition,
forest: ComponentTreeNode[],
): HTMLElement | null => {
const foundComponent: ComponentTreeNode | null = queryDirectiveForest(position, forest);
return foundComponent ? (foundComponent.nativeElement as HTMLElement) : null;
};
export const findNodeFromSerializedPosition = (
serializedPosition: string,
): ComponentTreeNode | null => {
const position: number[] = serializedPosition.split(',').map((index) => parseInt(index, 10));
return queryDirectiveForest(position, buildDirectiveForest());
};
export const updateState = (updatedStateData: UpdatedStateData): void => {
const ng = ngDebugClient();
const node = queryDirectiveForest(updatedStateData.directiveId.element, buildDirectiveForest());
if (!node) {
console.warn(
'Could not update the state of component',
updatedStateData,
'because the component was not found',
);
return;
}
if (updatedStateData.directiveId.directive !== undefined) {
const directive = node.directives[updatedStateData.directiveId.directive].instance;
mutateComponentOrDirective(updatedStateData, directive);
ng.applyChanges(ng.getOwningComponent(directive)!);
return;
}
if (node.component) {
const comp = node.component.instance;
mutateComponentOrDirective(updatedStateData, comp);
ng.applyChanges(comp);
return;
}
};
const mutateComponentOrDirective = (updatedStateData: UpdatedStateData, compOrDirective: any) => {
const valueKey = updatedStateData.keyPath.pop();
if (valueKey === undefined) {
return;
}
let parentObjectOfValueToUpdate = compOrDirective;
updatedStateData.keyPath.forEach((key) => {
parentObjectOfValueToUpdate = parentObjectOfValueToUpdate[key];
});
if (isSignal(parentObjectOfValueToUpdate)) {
// we don't support updating nested objects in signals yet
return;
}
// When we try to set a property which only has a getter
// the line below could throw an error.
try {
if (isSignal(parentObjectOfValueToUpdate[valueKey])) {
parentObjectOfValueToUpdate[valueKey].set(updatedStateData.newValue);
} else {
parentObjectOfValueToUpdate[valueKey] = updatedStateData.newValue;
}
} catch {}
};
export function serializeResolutionPath(resolutionPath: Injector[]): SerializedInjector[] {
const serializedResolutionPath: SerializedInjector[] = [];
for (const injector of resolutionPath) {
let serializedInjectorWithId: SerializedInjector | null = null;
if (isElementInjector(injector)) {
serializedInjectorWithId = serializeElementInjectorWithId(injector);
} else {
serializedInjectorWithId = serializeEnvironmentInjectorWithId(injector);
}
if (serializedInjectorWithId === null) {
continue;
}
serializedResolutionPath.push(serializedInjectorWithId);
}
return serializedResolutionPath;
}
| {
"end_byte": 18674,
"start_byte": 15770,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/component-tree.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/client-event-subscribers.ts_0_8758 | /**
* @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 {
ComponentExplorerViewQuery,
ComponentType,
DevToolsNode,
DirectivePosition,
DirectiveType,
ElementPosition,
Events,
MessageBus,
ProfilerFrame,
SerializedInjector,
SerializedProviderRecord,
} from 'protocol';
import {debounceTime} from 'rxjs/operators';
import {
appIsAngularInDevMode,
appIsAngularIvy,
appIsSupportedAngularVersion,
getAngularVersion,
isHydrationEnabled,
} from 'shared-utils';
import {ComponentInspector} from './component-inspector/component-inspector';
import {
getElementInjectorElement,
getInjectorFromElementNode,
getInjectorProviders,
getInjectorResolutionPath,
getLatestComponentState,
idToInjector,
injectorsSeen,
isElementInjector,
nodeInjectorToResolutionPath,
queryDirectiveForest,
serializeProviderRecord,
serializeResolutionPath,
updateState,
} from './component-tree';
import {unHighlight} from './highlighter';
import {disableTimingAPI, enableTimingAPI, initializeOrGetDirectiveForestHooks} from './hooks';
import {start as startProfiling, stop as stopProfiling} from './hooks/capture';
import {ComponentTreeNode} from './interfaces';
import {ngDebugDependencyInjectionApiIsSupported} from './ng-debug-api/ng-debug-api';
import {setConsoleReference} from './set-console-reference';
import {serializeDirectiveState} from './state-serializer/state-serializer';
import {runOutsideAngular, unwrapSignal} from './utils';
import {DirectiveForestHooks} from './hooks/hooks';
export const subscribeToClientEvents = (
messageBus: MessageBus<Events>,
depsForTestOnly?: {
directiveForestHooks?: typeof DirectiveForestHooks;
},
): void => {
messageBus.on('shutdown', shutdownCallback(messageBus));
messageBus.on(
'getLatestComponentExplorerView',
getLatestComponentExplorerViewCallback(messageBus),
);
messageBus.on('queryNgAvailability', checkForAngularCallback(messageBus));
messageBus.on('startProfiling', startProfilingCallback(messageBus));
messageBus.on('stopProfiling', stopProfilingCallback(messageBus));
messageBus.on('setSelectedComponent', selectedComponentCallback);
messageBus.on('getNestedProperties', getNestedPropertiesCallback(messageBus));
messageBus.on('getRoutes', getRoutesCallback(messageBus));
messageBus.on('updateState', updateState);
messageBus.on('enableTimingAPI', enableTimingAPI);
messageBus.on('disableTimingAPI', disableTimingAPI);
messageBus.on('getInjectorProviders', getInjectorProvidersCallback(messageBus));
messageBus.on('logProvider', logProvider);
messageBus.on('log', ({message, level}) => {
console[level](`[Angular DevTools]: ${message}`);
});
if (appIsAngularInDevMode() && appIsSupportedAngularVersion() && appIsAngularIvy()) {
setupInspector(messageBus);
// Often websites have `scroll` event listener which triggers
// Angular's change detection. We don't want to constantly send
// update requests, instead we want to request an update at most
// once every 250ms
runOutsideAngular(() => {
initializeOrGetDirectiveForestHooks(depsForTestOnly)
.profiler.changeDetection$.pipe(debounceTime(250))
.subscribe(() => messageBus.emit('componentTreeDirty'));
});
}
};
//
// Callback Definitions
//
const shutdownCallback = (messageBus: MessageBus<Events>) => () => {
messageBus.destroy();
};
const getLatestComponentExplorerViewCallback =
(messageBus: MessageBus<Events>) => (query?: ComponentExplorerViewQuery) => {
// We want to force re-indexing of the component tree.
// Pressing the refresh button means the user saw stuck UI.
initializeOrGetDirectiveForestHooks().indexForest();
const forest = prepareForestForSerialization(
initializeOrGetDirectiveForestHooks().getIndexedDirectiveForest(),
ngDebugDependencyInjectionApiIsSupported(),
);
// cleanup injector id mappings
for (const injectorId of idToInjector.keys()) {
if (!injectorsSeen.has(injectorId)) {
const injector = idToInjector.get(injectorId)!;
if (isElementInjector(injector)) {
const element = getElementInjectorElement(injector);
if (element) {
nodeInjectorToResolutionPath.delete(element);
}
}
idToInjector.delete(injectorId);
}
}
injectorsSeen.clear();
if (!query) {
messageBus.emit('latestComponentExplorerView', [{forest}]);
return;
}
const state = getLatestComponentState(
query,
initializeOrGetDirectiveForestHooks().getDirectiveForest(),
);
if (state) {
const {directiveProperties} = state;
messageBus.emit('latestComponentExplorerView', [{forest, properties: directiveProperties}]);
}
};
const checkForAngularCallback = (messageBus: MessageBus<Events>) => () =>
checkForAngular(messageBus);
const getRoutesCallback = (messageBus: MessageBus<Events>) => () => getRoutes(messageBus);
const startProfilingCallback = (messageBus: MessageBus<Events>) => () =>
startProfiling((frame: ProfilerFrame) => {
messageBus.emit('sendProfilerChunk', [frame]);
});
const stopProfilingCallback = (messageBus: MessageBus<Events>) => () => {
messageBus.emit('profilerResults', [stopProfiling()]);
};
const selectedComponentCallback = (position: ElementPosition) => {
const node = queryDirectiveForest(
position,
initializeOrGetDirectiveForestHooks().getIndexedDirectiveForest(),
);
setConsoleReference({node, position});
};
const getNestedPropertiesCallback =
(messageBus: MessageBus<Events>) => (position: DirectivePosition, propPath: string[]) => {
const emitEmpty = () => messageBus.emit('nestedProperties', [position, {props: {}}, propPath]);
const node = queryDirectiveForest(
position.element,
initializeOrGetDirectiveForestHooks().getIndexedDirectiveForest(),
);
if (!node) {
return emitEmpty();
}
const current =
position.directive === undefined ? node.component : node.directives[position.directive];
if (!current) {
return emitEmpty();
}
let data = current.instance;
for (const prop of propPath) {
data = unwrapSignal(data[prop]);
if (!data) {
console.error('Cannot access the properties', propPath, 'of', node);
}
}
messageBus.emit('nestedProperties', [
position,
{props: serializeDirectiveState(data)},
propPath,
]);
return;
};
//
// Subscribe Helpers
//
// todo: parse router tree with framework APIs after they are developed
const getRoutes = (messageBus: MessageBus<Events>) => {
// Return empty router tree to disable tab.
messageBus.emit('updateRouterTree', [[]]);
};
const checkForAngular = (messageBus: MessageBus<Events>): void => {
const ngVersion = getAngularVersion();
const appIsIvy = appIsAngularIvy();
if (!ngVersion) {
return;
}
if (appIsIvy && appIsAngularInDevMode() && appIsSupportedAngularVersion()) {
initializeOrGetDirectiveForestHooks();
}
messageBus.emit('ngAvailability', [
{
version: ngVersion.toString(),
devMode: appIsAngularInDevMode(),
ivy: appIsIvy,
hydration: isHydrationEnabled(),
},
]);
};
const setupInspector = (messageBus: MessageBus<Events>) => {
const inspector = new ComponentInspector({
onComponentEnter: (id: number) => {
messageBus.emit('highlightComponent', [id]);
},
onComponentLeave: () => {
messageBus.emit('removeComponentHighlight');
},
onComponentSelect: (id: number) => {
messageBus.emit('selectComponent', [id]);
},
});
messageBus.on('inspectorStart', inspector.startInspecting);
messageBus.on('inspectorEnd', inspector.stopInspecting);
messageBus.on('createHighlightOverlay', (position: ElementPosition) => {
inspector.highlightByPosition(position);
});
messageBus.on('removeHighlightOverlay', unHighlight);
messageBus.on('createHydrationOverlay', inspector.highlightHydrationNodes);
messageBus.on('removeHydrationOverlay', inspector.removeHydrationHighlights);
};
export interface SerializableDirectiveInstanceType extends DirectiveType {
id: number;
}
export interface SerializableComponentInstanceType extends ComponentType {
id: number;
}
export interface SerializableComponentTreeNode
extends DevToolsNode<SerializableDirectiveInstanceType, SerializableComponentInstanceType> {
children: SerializableComponentTreeNode[];
}
// Here we drop properties to prepare the tree for serialization.
// We don't need the component instance, so we just traverse the tree | {
"end_byte": 8758,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/client-event-subscribers.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/client-event-subscribers.ts_8759_14028 | // and leave the component name.
const prepareForestForSerialization = (
roots: ComponentTreeNode[],
includeResolutionPath = false,
): SerializableComponentTreeNode[] => {
const serializedNodes: SerializableComponentTreeNode[] = [];
for (const node of roots) {
const serializedNode: SerializableComponentTreeNode = {
element: node.element,
component: node.component
? {
name: node.component.name,
isElement: node.component.isElement,
id: initializeOrGetDirectiveForestHooks().getDirectiveId(node.component.instance)!,
}
: null,
directives: node.directives.map((d) => ({
name: d.name,
id: initializeOrGetDirectiveForestHooks().getDirectiveId(d.instance)!,
})),
children: prepareForestForSerialization(node.children, includeResolutionPath),
hydration: node.hydration,
};
serializedNodes.push(serializedNode);
if (includeResolutionPath) {
serializedNode.resolutionPath = getNodeDIResolutionPath(node);
}
}
return serializedNodes;
};
function getNodeDIResolutionPath(node: ComponentTreeNode): SerializedInjector[] | undefined {
const nodeInjector = getInjectorFromElementNode(node.nativeElement!);
if (!nodeInjector) {
return [];
}
// There are legit cases where an angular node will have non-ElementInjector injectors.
// For example, components created with createComponent require the API consumer to
// pass in an element injector, else it sets the element injector of the component
// to the NullInjector
if (!isElementInjector(nodeInjector)) {
return [];
}
const element = getElementInjectorElement(nodeInjector);
if (!nodeInjectorToResolutionPath.has(element)) {
const resolutionPaths = getInjectorResolutionPath(nodeInjector);
nodeInjectorToResolutionPath.set(element, serializeResolutionPath(resolutionPaths));
}
const serializedPath = nodeInjectorToResolutionPath.get(element)!;
for (const injector of serializedPath) {
injectorsSeen.add(injector.id);
}
return serializedPath;
}
const getInjectorProvidersCallback =
(messageBus: MessageBus<Events>) => (injector: SerializedInjector) => {
if (!idToInjector.has(injector.id)) {
return;
}
const providerRecords = getInjectorProviders(idToInjector.get(injector.id)!);
const allProviderRecords: SerializedProviderRecord[] = [];
const tokenToRecords: Map<any, SerializedProviderRecord[]> = new Map();
for (const [index, providerRecord] of providerRecords.entries()) {
const record = serializeProviderRecord(
providerRecord,
index,
injector.type === 'environment',
);
allProviderRecords.push(record);
const records = tokenToRecords.get(providerRecord.token) ?? [];
records.push(record);
tokenToRecords.set(providerRecord.token, records);
}
const serializedProviderRecords: SerializedProviderRecord[] = [];
for (const [token, records] of tokenToRecords.entries()) {
const multiRecords = records.filter((record) => record.multi);
const nonMultiRecords = records.filter((record) => !record.multi);
for (const record of nonMultiRecords) {
serializedProviderRecords.push(record);
}
const [firstMultiRecord] = multiRecords;
if (firstMultiRecord !== undefined) {
// All multi providers will have the same token, so we can just use the first one.
serializedProviderRecords.push({
token: firstMultiRecord.token,
type: 'multi',
multi: true,
// todo(aleksanderbodurri): implememnt way to differentiate multi providers that
// provided as viewProviders
isViewProvider: firstMultiRecord.isViewProvider,
index: records.map((record) => record.index as number),
});
}
}
messageBus.emit('latestInjectorProviders', [injector, serializedProviderRecords]);
};
const logProvider = (
serializedInjector: SerializedInjector,
serializedProvider: SerializedProviderRecord,
): void => {
if (!idToInjector.has(serializedInjector.id)) {
return;
}
const injector = idToInjector.get(serializedInjector.id)!;
const providerRecords = getInjectorProviders(injector);
console.group(
`%c${serializedInjector.name}`,
`color: ${
serializedInjector.type === 'element' ? '#a7d5a9' : '#f05057'
}; font-size: 1.25rem; font-weight: bold;`,
);
// tslint:disable-next-line:no-console
console.log('injector: ', injector);
if (typeof serializedProvider.index === 'number') {
const provider = providerRecords[serializedProvider.index];
// tslint:disable-next-line:no-console
console.log('provider: ', provider);
// tslint:disable-next-line:no-console
console.log(`value: `, injector.get(provider.token, null, {optional: true}));
} else if (Array.isArray(serializedProvider.index)) {
const providers = serializedProvider.index.map((index) => providerRecords[index]);
// tslint:disable-next-line:no-console
console.log('providers: ', providers);
// tslint:disable-next-line:no-console
console.log(`value: `, injector.get(providers[0].token, null, {optional: true}));
}
console.groupEnd();
}; | {
"end_byte": 14028,
"start_byte": 8759,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/client-event-subscribers.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/highlighter.ts_0_5499 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type {ɵGlobalDevModeUtils as GlobalDevModeUtils, Type} from '@angular/core';
import {HydrationStatus} from 'protocol';
let hydrationOverlayItems: HTMLElement[] = [];
let selectedElementOverlay: HTMLElement | null = null;
declare const ng: GlobalDevModeUtils['ng'];
const DEV_TOOLS_HIGHLIGHT_NODE_ID = '____ngDevToolsHighlight';
const OVERLAY_CONTENT_MARGIN = 4;
const MINIMAL_OVERLAY_CONTENT_SIZE = {
width: 30 + OVERLAY_CONTENT_MARGIN * 2,
height: 20 + OVERLAY_CONTENT_MARGIN * 2,
};
type RgbColor = readonly [red: number, green: number, blue: number];
const COLORS = {
blue: [104, 182, 255],
red: [255, 0, 64],
grey: [128, 128, 128],
} satisfies Record<string, RgbColor>;
// Those are the SVG we inline in case the overlay label is to long for the container component.
const HYDRATION_SVG = `
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000"><rect fill="none" height="24" width="24"/><path d="M12,2c-5.33,4.55-8,8.48-8,11.8c0,4.98,3.8,8.2,8,8.2s8-3.22,8-8.2C20,10.48,17.33,6.55,12,2z M12,20c-3.35,0-6-2.57-6-6.2 c0-2.34,1.95-5.44,6-9.14c4.05,3.7,6,6.79,6,9.14C18,17.43,15.35,20,12,20z M7.83,14c0.37,0,0.67,0.26,0.74,0.62 c0.41,2.22,2.28,2.98,3.64,2.87c0.43-0.02,0.79,0.32,0.79,0.75c0,0.4-0.32,0.73-0.72,0.75c-2.13,0.13-4.62-1.09-5.19-4.12 C7.01,14.42,7.37,14,7.83,14z"/></svg>`;
const HYDRATION_SKIPPED_SVG = `<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><rect fill="none" height="24" width="24"/><path d="M21.19,21.19L2.81,2.81L1.39,4.22l4.2,4.2c-1,1.31-1.6,2.94-1.6,4.7C4,17.48,7.58,21,12,21c1.75,0,3.36-0.56,4.67-1.5 l3.1,3.1L21.19,21.19z M12,19c-3.31,0-6-2.63-6-5.87c0-1.19,0.36-2.32,1.02-3.28L12,14.83V19z M8.38,5.56L12,2l5.65,5.56l0,0 C19.1,8.99,20,10.96,20,13.13c0,1.18-0.27,2.29-0.74,3.3L12,9.17V4.81L9.8,6.97L8.38,5.56z"/></svg>`;
const HYDRATION_ERROR_SVG = `<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M11 15h2v2h-2v-2zm0-8h2v6h-2V7zm.99-5C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/></svg>`;
function createOverlay(color: RgbColor): {overlay: HTMLElement; overlayContent: HTMLElement} {
const overlay = document.createElement('div');
overlay.className = 'ng-devtools-overlay';
overlay.style.backgroundColor = toCSSColor(...color, 0.35);
overlay.style.position = 'fixed';
overlay.style.zIndex = '2147483647';
overlay.style.pointerEvents = 'none';
overlay.style.display = 'flex';
overlay.style.borderRadius = '3px';
overlay.id = DEV_TOOLS_HIGHLIGHT_NODE_ID;
const overlayContent = document.createElement('div');
overlayContent.style.backgroundColor = toCSSColor(...color, 0.9);
overlayContent.style.position = 'absolute';
overlayContent.style.fontFamily = 'monospace';
overlayContent.style.fontSize = '11px';
overlayContent.style.padding = '2px 3px';
overlayContent.style.borderRadius = '3px';
overlayContent.style.color = 'white';
overlay.appendChild(overlayContent);
return {overlay, overlayContent};
}
export function findComponentAndHost(el: Node | undefined): {
component: any;
host: HTMLElement | null;
} {
if (!el) {
return {component: null, host: null};
}
while (el) {
const component = el instanceof HTMLElement && ng.getComponent(el);
if (component) {
return {component, host: el as HTMLElement};
}
if (!el.parentElement) {
break;
}
el = el.parentElement;
}
return {component: null, host: null};
}
// Todo(aleksanderbodurri): this should not be part of the highlighter, move this somewhere else
export function getDirectiveName(dir: Type<unknown> | undefined | null): string {
return dir ? dir.constructor.name : 'unknown';
}
export function highlightSelectedElement(el: Node): void {
unHighlight();
selectedElementOverlay = addHighlightForElement(el);
}
export function highlightHydrationElement(el: Node, status: HydrationStatus) {
let overlay: HTMLElement | null = null;
if (status?.status === 'skipped') {
overlay = addHighlightForElement(el, COLORS.grey, status?.status);
} else if (status?.status === 'mismatched') {
overlay = addHighlightForElement(el, COLORS.red, status?.status);
} else if (status?.status === 'hydrated') {
overlay = addHighlightForElement(el, COLORS.blue, status?.status);
}
if (overlay) {
hydrationOverlayItems.push(overlay);
}
}
export function unHighlight(): void {
if (!selectedElementOverlay) {
return;
}
for (const node of document.body.childNodes) {
if (node === selectedElementOverlay) {
document.body.removeChild(selectedElementOverlay);
break;
}
}
selectedElementOverlay = null;
}
export function removeHydrationHighlights(): void {
hydrationOverlayItems.forEach((overlay) => {
document.body.removeChild(overlay);
});
hydrationOverlayItems = [];
}
export function inDoc(node: any): boolean {
if (!node) {
return false;
}
const doc = node.ownerDocument.documentElement;
const parent = node.parentNode;
return (
doc === node || doc === parent || !!(parent && parent.nodeType === 1 && doc.contains(parent))
);
}
| {
"end_byte": 5499,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/highlighter.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/highlighter.ts_5501_9969 | unction addHighlightForElement(
el: Node,
color: RgbColor = COLORS.blue,
overlayType?: NonNullable<HydrationStatus>['status'],
): HTMLElement | null {
const cmp = findComponentAndHost(el).component;
const rect = getComponentRect(el);
if (rect?.height === 0 || rect?.width === 0) {
// display nothing in case the component is not visible
return null;
}
const {overlay, overlayContent} = createOverlay(color);
if (!rect) return null;
const content: Node[] = [];
const componentName = getDirectiveName(cmp);
// We display an icon inside the overlay if the container computer is wide enough
if (overlayType) {
if (
rect.width > MINIMAL_OVERLAY_CONTENT_SIZE.width &&
rect.height > MINIMAL_OVERLAY_CONTENT_SIZE.height
) {
// 30x20 + 8px margin
const svg = createOverlaySvgElement(overlayType!);
content.push(svg);
}
} else if (componentName) {
const middleText = document.createTextNode(componentName);
const pre = document.createElement('span');
pre.innerText = `<`;
const post = document.createElement('span');
post.innerText = `>`;
content.push(pre, middleText, post);
}
showOverlay(overlay, overlayContent, rect, content, overlayType ? 'inside' : 'outside');
return overlay;
}
function getComponentRect(el: Node): DOMRect | undefined {
if (!(el instanceof HTMLElement)) {
return;
}
if (!inDoc(el)) {
return;
}
return el.getBoundingClientRect();
}
function showOverlay(
overlay: HTMLElement,
overlayContent: HTMLElement,
dimensions: DOMRect,
content: Node[],
labelPosition: 'inside' | 'outside',
): void {
const {width, height, top, left} = dimensions;
overlay.style.width = ~~width + 'px';
overlay.style.height = ~~height + 'px';
overlay.style.top = ~~top + 'px';
overlay.style.left = ~~left + 'px';
positionOverlayContent(overlayContent, dimensions, labelPosition);
overlayContent.replaceChildren();
if (content.length) {
content.forEach((child) => overlayContent.appendChild(child));
} else {
// If the overlay label has no content, remove it from the DOM.
overlay.removeChild(overlayContent);
}
document.body.appendChild(overlay);
}
function positionOverlayContent(
overlayContent: HTMLElement,
dimensions: DOMRect,
labelPosition: 'inside' | 'outside',
) {
const {innerWidth: viewportWidth, innerHeight: viewportHeight} = window;
const style = overlayContent.style;
const yOffset = 23;
const yOffsetValue = `-${yOffset}px`;
if (labelPosition === 'inside') {
style.top = `${OVERLAY_CONTENT_MARGIN}px`;
style.right = `${OVERLAY_CONTENT_MARGIN}px`;
return;
}
// Clear any previous positioning styles.
style.top = style.bottom = style.left = style.right = '';
// Attempt to position the content element so that it's always in the
// viewport along the Y axis. Prefer to position on the bottom.
if (dimensions.bottom + yOffset <= viewportHeight) {
style.bottom = yOffsetValue;
// If it doesn't fit on the bottom, try to position on top.
} else if (dimensions.top - yOffset >= 0) {
style.top = yOffsetValue;
// Otherwise offset from the bottom until it fits on the screen.
} else {
style.bottom = `${Math.max(dimensions.bottom - viewportHeight, 0)}px`;
}
// Attempt to position the content element so that it's always in the
// viewport along the X axis. Prefer to position on the right.
if (dimensions.right <= viewportWidth) {
style.right = '0';
// If it doesn't fit on the right, try to position on left.
} else if (dimensions.left >= 0) {
style.left = '0';
// Otherwise offset from the right until it fits on the screen.
} else {
style.right = `${Math.max(dimensions.right - viewportWidth, 0)}px`;
}
}
function toCSSColor(red: number, green: number, blue: number, alpha = 1): string {
return `rgba(${red},${green},${blue},${alpha})`;
}
function createOverlaySvgElement(type: NonNullable<HydrationStatus>['status']): Node {
let icon: string;
if (type === 'hydrated') {
icon = HYDRATION_SVG;
} else if (type === 'mismatched') {
icon = HYDRATION_ERROR_SVG;
} else if (type === 'skipped') {
icon = HYDRATION_SKIPPED_SVG;
} else {
throw new Error(`No icon specified for type ${type}`);
}
const svg = new DOMParser().parseFromString(icon, 'image/svg+xml').childNodes[0] as SVGElement;
svg.style.fill = 'white';
svg.style.height = '1.5em';
return svg;
}
| {
"end_byte": 9969,
"start_byte": 5501,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/highlighter.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/set-console-reference.ts_0_2087 | /**
* @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 {ElementPosition} from 'protocol';
import {arrayEquals} from 'shared-utils';
import {ComponentTreeNode} from './interfaces';
interface ConsoleReferenceNode {
node: ComponentTreeNode | null;
position: ElementPosition;
}
const CONSOLE_REFERENCE_PREFIX = '$ng';
const CAPACITY = 5;
const nodesForConsoleReference: ConsoleReferenceNode[] = [];
export const setConsoleReference = (referenceNode: ConsoleReferenceNode) => {
if (referenceNode.node === null) {
return;
}
_setConsoleReference(referenceNode);
};
const _setConsoleReference = (referenceNode: ConsoleReferenceNode) => {
prepareCurrentReferencesForInsertion(referenceNode);
nodesForConsoleReference.unshift(referenceNode);
assignConsoleReferencesFrom(nodesForConsoleReference);
};
const prepareCurrentReferencesForInsertion = (referenceNode: ConsoleReferenceNode) => {
const foundIndex = nodesForConsoleReference.findIndex((nodeToLookFor) =>
arrayEquals(nodeToLookFor.position, referenceNode.position),
);
if (foundIndex !== -1) {
nodesForConsoleReference.splice(foundIndex, 1);
} else if (nodesForConsoleReference.length === CAPACITY) {
nodesForConsoleReference.pop();
}
};
const assignConsoleReferencesFrom = (referenceNodes: ConsoleReferenceNode[]) => {
referenceNodes.forEach((referenceNode, index) =>
setDirectiveKey(referenceNode.node, getConsoleReferenceWithIndexOf(index)),
);
};
const setDirectiveKey = (node: ComponentTreeNode | null, key: string) => {
Object.defineProperty(window, key, {
get: () => {
if (node?.component) {
return node.component.instance;
}
if (node?.nativeElement) {
return node.nativeElement;
}
return node;
},
configurable: true,
});
};
const getConsoleReferenceWithIndexOf = (consoleReferenceIndex: number) =>
`${CONSOLE_REFERENCE_PREFIX}${consoleReferenceIndex}`;
| {
"end_byte": 2087,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/set-console-reference.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/utils.ts_0_1693 | /**
* @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 ngDebug = () => (window as any).ng;
export const runOutsideAngular = (f: () => void): void => {
const w = window as any;
if (!w.Zone || !w.Zone.current) {
f();
return;
}
if (w.Zone.current._name !== 'angular') {
w.Zone.current.run(f);
return;
}
const parent = w.Zone.current._parent;
if (parent && parent.run) {
parent.run(f);
return;
}
f();
};
export const isCustomElement = (node: Node) => {
if (typeof customElements === 'undefined') {
return false;
}
if (!(node instanceof HTMLElement)) {
return false;
}
const tagName = node.tagName.toLowerCase();
return !!customElements.get(tagName);
};
export function hasDiDebugAPIs(): boolean {
if (!ngDebugApiIsSupported('ɵgetInjectorResolutionPath')) {
return false;
}
if (!ngDebugApiIsSupported('ɵgetDependenciesFromInjectable')) {
return false;
}
if (!ngDebugApiIsSupported('ɵgetInjectorProviders')) {
return false;
}
if (!ngDebugApiIsSupported('ɵgetInjectorMetadata')) {
return false;
}
return true;
}
export function ngDebugApiIsSupported(api: string): boolean {
const ng = ngDebug();
return typeof ng[api] === 'function';
}
export function isSignal(prop: unknown): prop is (() => unknown) & {set: (value: unknown) => void} {
if (!ngDebugApiIsSupported('isSignal')) {
return false;
}
return (window as any).ng.isSignal(prop);
}
export function unwrapSignal(s: any): any {
return isSignal(s) ? s() : s;
}
| {
"end_byte": 1693,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/utils.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/highlighter.spec.ts_0_7634 | /**
* @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 highlighter from './highlighter';
describe('highlighter', () => {
describe('findComponentAndHost', () => {
it('should return undefined when no node is provided', () => {
expect(highlighter.findComponentAndHost(undefined)).toEqual({component: null, host: null});
});
it('should return same component and host if component exists', () => {
(window as any).ng = {
getComponent: (el: any) => el,
};
const element = document.createElement('div');
const data = highlighter.findComponentAndHost(element as any);
expect(data.component).toBeTruthy();
expect(data.host).toBeTruthy();
expect(data.component).toEqual(data.host);
});
it('should return null component and host if component do not exists', () => {
(window as any).ng = {
getComponent: () => undefined,
};
const element = document.createElement('div');
const data = highlighter.findComponentAndHost(element as any);
expect(data.component).toBeFalsy();
expect(data.host).toBeFalsy();
});
});
describe('getComponentName', () => {
it('should return null when called with null values', () => {
let name = highlighter.getDirectiveName(null);
expect(name).toBe('unknown');
name = highlighter.getDirectiveName(undefined);
expect(name).toBe('unknown');
});
it('should return correct component name', () => {
const MOCK_COMPONENT = {
constructor: {
name: 'mock-component',
},
};
const name = highlighter.getDirectiveName(MOCK_COMPONENT as any);
expect(name).toBe(MOCK_COMPONENT.constructor.name);
});
});
describe('inDoc', () => {
it('should return false if no node is provided', () => {
expect(highlighter.inDoc(undefined)).toBeFalsy();
});
it('should be true if doc and node are equal', () => {
const node = {
parentNode: {},
ownerDocument: {
documentElement: {},
},
};
node.ownerDocument.documentElement = node;
expect(highlighter.inDoc(node)).toBeTruthy();
});
it('should be true if doc and parent are equal', () => {
const node = {
parentNode: 'node',
ownerDocument: {
documentElement: 'node',
},
};
expect(highlighter.inDoc(node)).toBeTruthy();
});
it('should be true if doc contains parent', () => {
const node = {
parentNode: {
nodeType: 1,
},
ownerDocument: {
documentElement: {
contains: () => true,
},
},
};
expect(highlighter.inDoc(node)).toBeTruthy();
});
});
describe('highlightHydrationElement', () => {
afterEach(() => {
document.body.innerHTML = '';
delete (window as any).ng;
});
it('should show hydration overlay with svg', () => {
const appNode = document.createElement('app');
appNode.style.width = '500px';
appNode.style.height = '400px';
appNode.style.display = 'block';
document.body.appendChild(appNode);
(window as any).ng = {
getComponent: (el: any) => el,
};
highlighter.highlightHydrationElement(appNode, {status: 'hydrated'});
expect(document.body.querySelectorAll('div').length).toBe(2);
expect(document.body.querySelectorAll('svg').length).toBe(1);
const overlay = document.body.querySelector('.ng-devtools-overlay');
expect(overlay?.getBoundingClientRect().width).toBe(500);
expect(overlay?.getBoundingClientRect().height).toBe(400);
highlighter.removeHydrationHighlights();
expect(document.body.querySelectorAll('div').length).toBe(0);
expect(document.body.querySelectorAll('svg').length).toBe(0);
});
it('should show hydration overlay without svg (too small)', () => {
const appNode = document.createElement('app');
appNode.style.width = '25px';
appNode.style.height = '20px';
appNode.style.display = 'block';
document.body.appendChild(appNode);
(window as any).ng = {
getComponent: (el: any) => el,
};
highlighter.highlightHydrationElement(appNode, {status: 'hydrated'});
expect(document.body.querySelectorAll('div').length).toBe(1);
expect(document.body.querySelectorAll('svg').length).toBe(0);
const overlay = document.body.querySelector('.ng-devtools-overlay');
expect(overlay?.getBoundingClientRect().width).toBe(25);
expect(overlay?.getBoundingClientRect().height).toBe(20);
highlighter.removeHydrationHighlights();
expect(document.body.querySelectorAll('div').length).toBe(0);
expect(document.body.querySelectorAll('svg').length).toBe(0);
});
it('should show hydration overlay and selected component overlay at the same time ', () => {
const appNode = document.createElement('app');
appNode.style.width = '25px';
appNode.style.height = '20px';
appNode.style.display = 'block';
document.body.appendChild(appNode);
(window as any).ng = {
getComponent: (el: any) => el,
};
highlighter.highlightHydrationElement(appNode, {status: 'hydrated'});
highlighter.highlightSelectedElement(appNode);
expect(document.body.querySelectorAll('.ng-devtools-overlay').length).toBe(2);
highlighter.removeHydrationHighlights();
expect(document.body.querySelectorAll('.ng-devtools-overlay').length).toBe(1);
highlighter.unHighlight();
expect(document.body.querySelectorAll('.ng-devtools-overlay').length).toBe(0);
highlighter.highlightHydrationElement(appNode, {status: 'hydrated'});
highlighter.highlightSelectedElement(appNode);
highlighter.unHighlight();
expect(document.body.querySelectorAll('.ng-devtools-overlay').length).toBe(1);
highlighter.removeHydrationHighlights();
expect(document.body.querySelectorAll('.ng-devtools-overlay').length).toBe(0);
});
});
describe('highlightSelectedElement', () => {
function createElement(name: string) {
const element = document.createElement(name);
element.style.width = '25px';
element.style.height = '20px';
element.style.display = 'block';
document.body.appendChild(element);
return element;
}
it('should show overlay', () => {
const appNode = createElement('app');
(window as any).ng = {
getComponent: (el: any) => new (class FakeComponent {})(),
};
highlighter.highlightSelectedElement(appNode);
const overlay = document.body.querySelectorAll('.ng-devtools-overlay');
expect(overlay.length).toBe(1);
expect(overlay[0].innerHTML).toContain('FakeComponent');
highlighter.unHighlight();
expect(document.body.querySelectorAll('.ng-devtools-overlay').length).toBe(0);
});
it('should remove the previous overlay when calling highlightSelectedElement again', () => {
const appNode = createElement('app');
const appNode2 = createElement('app-two');
(window as any).ng = {
getComponent: (el: any) => new (class FakeComponent {})(),
};
highlighter.highlightSelectedElement(appNode);
highlighter.highlightSelectedElement(appNode2);
const overlay = document.body.querySelectorAll('.ng-devtools-overlay');
expect(overlay.length).toBe(1);
});
});
});
| {
"end_byte": 7634,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/highlighter.spec.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/router-tree.ts_0_2246 | /**
* @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 {Route} from 'protocol';
// todo(aleksanderbodurri): type these properly
type AngularRoute = any;
type Routes = any;
type Router = any;
export function parseRoutes(router: Router): Route {
const rootName = (router as any).rootComponentType?.name || 'no-name';
const rootChildren = router.config;
const root: Route = {
handler: rootName,
name: rootName,
path: '/',
children: rootChildren ? assignChildrenToParent(null, rootChildren) : [],
isAux: false,
specificity: null,
data: null,
hash: null,
};
return root;
}
function assignChildrenToParent(parentPath: string | null, children: Routes): Route[] {
return children.map((child: AngularRoute) => {
const childName = childRouteName(child);
const childDescendents: [any] = (child as any)._loadedConfig?.routes || child.children;
// only found in aux routes, otherwise property will be undefined
const isAuxRoute = !!child.outlet;
const pathFragment = child.outlet ? `(${child.outlet}:${child.path})` : child.path;
const routeConfig: Route = {
handler: childName,
data: [],
hash: null,
specificity: null,
name: childName,
path: `${parentPath ? parentPath : ''}/${pathFragment}`.split('//').join('/'),
isAux: isAuxRoute,
children: [],
};
if (childDescendents) {
routeConfig.children = assignChildrenToParent(routeConfig.path, childDescendents);
}
if (child.data) {
for (const el in child.data) {
if (child.data.hasOwnProperty(el)) {
routeConfig.data.push({
key: el,
value: child.data[el],
});
}
}
}
return routeConfig;
});
}
function childRouteName(child: AngularRoute): string {
if (child.component) {
return child.component.name;
} else if (child.loadChildren) {
return `${child.path} [Lazy]`;
} else if (child.redirectTo) {
return `${child.path} -> redirecting to -> "${child.redirectTo}"`;
} else {
return 'no-name-route';
}
}
| {
"end_byte": 2246,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/router-tree.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/BUILD.bazel_0_3827 | load("//devtools/tools:defaults.bzl", "karma_web_test_suite")
load("//devtools/tools:typescript.bzl", "ts_library", "ts_test_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "lib",
srcs = ["index.ts"],
deps = [
":client_event_subscribers",
"//devtools/projects/ng-devtools-backend/src/lib/component-inspector",
"//devtools/projects/ng-devtools-backend/src/lib/directive-forest",
"//devtools/projects/ng-devtools-backend/src/lib/hooks",
"//devtools/projects/ng-devtools-backend/src/lib/ng-debug-api",
"//devtools/projects/ng-devtools-backend/src/lib/state-serializer",
"//devtools/projects/protocol",
],
)
karma_web_test_suite(
name = "highlighter_test",
deps = [
":highlighter_test_lib",
],
)
ts_test_library(
name = "highlighter_test_lib",
srcs = [
"highlighter.spec.ts",
],
deps = [
":highlighter",
"//packages/core",
"//packages/platform-browser-dynamic",
"@npm//@types",
],
)
ts_library(
name = "highlighter",
srcs = ["highlighter.ts"],
deps = [
"//devtools/projects/protocol",
"//packages/core",
],
)
ts_library(
name = "interfaces",
srcs = ["interfaces.ts"],
deps = [
"//devtools/projects/protocol",
],
)
karma_web_test_suite(
name = "router_tree_test",
deps = [
":router_tree_test_lib",
],
)
ts_test_library(
name = "router_tree_test_lib",
srcs = [
"router-tree.spec.ts",
],
deps = [
":router_tree",
"//devtools/projects/protocol",
"//packages/core",
"//packages/platform-browser-dynamic",
"//packages/router",
"@npm//@types",
],
)
ts_library(
name = "router_tree",
srcs = ["router-tree.ts"],
deps = [
"//devtools/projects/protocol",
],
)
ts_library(
name = "set_console_reference",
srcs = ["set-console-reference.ts"],
deps = [
":interfaces",
"//devtools/projects/protocol",
"//devtools/projects/shared-utils",
],
)
ts_library(
name = "utils",
srcs = ["utils.ts"],
)
ts_library(
name = "version",
srcs = ["version.ts"],
)
karma_web_test_suite(
name = "client_event_subscribers_test",
deps = [
":client_event_subscribers_test_lib",
],
)
ts_test_library(
name = "client_event_subscribers_test_lib",
srcs = [
"client-event-subscribers.spec.ts",
],
deps = [
":client_event_subscribers",
"//devtools/projects/ng-devtools-backend/src/lib/hooks",
"//devtools/projects/protocol",
"//devtools/projects/shared-utils",
"@npm//rxjs",
],
)
ts_library(
name = "client_event_subscribers",
srcs = ["client-event-subscribers.ts"],
deps = [
":component_tree",
":highlighter",
":interfaces",
":set_console_reference",
":utils",
"//devtools/projects/ng-devtools-backend/src/lib/component-inspector",
"//devtools/projects/ng-devtools-backend/src/lib/hooks",
"//devtools/projects/ng-devtools-backend/src/lib/ng-debug-api",
"//devtools/projects/ng-devtools-backend/src/lib/state-serializer",
"//devtools/projects/protocol",
"//devtools/projects/shared-utils",
"@npm//rxjs",
],
)
ts_library(
name = "component_tree",
srcs = ["component-tree.ts"],
deps = [
":interfaces",
":utils",
"//devtools/projects/ng-devtools-backend/src/lib/directive-forest",
"//devtools/projects/ng-devtools-backend/src/lib/ng-debug-api",
"//devtools/projects/ng-devtools-backend/src/lib/state-serializer",
"//devtools/projects/protocol",
"//packages/core",
],
)
| {
"end_byte": 3827,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/BUILD.bazel"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/index.ts_0_435 | /**
* @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 {Events, MessageBus} from 'protocol';
import {subscribeToClientEvents} from './client-event-subscribers';
export const initializeMessageBus = (messageBus: MessageBus<Events>) => {
subscribeToClientEvents(messageBus);
};
| {
"end_byte": 435,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/index.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/version.ts_0_584 | /**
* @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
*/
const versionElement = document.querySelector('[ng-version]');
const versionRe = /(\d+\.\d+\.\d+(-(next|rc)\.\d+)?)/;
const defaultVersion = '0.0.0';
let version = defaultVersion;
if (versionElement) {
version = versionElement.getAttribute('ng-version') ?? defaultVersion;
version = (version.match(versionRe) ?? [''])[0] ?? defaultVersion;
}
export const VERSION = version;
| {
"end_byte": 584,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/version.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/router-tree.spec.ts_0_4320 | /**
* @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 {parseRoutes} from './router-tree';
describe('parseRoutes', () => {
it('should work without any routes', () => {
const routes: any[] = [];
const parsedRoutes = parseRoutes(routes as any);
expect(parsedRoutes).toEqual({
handler: 'no-name',
name: 'no-name',
path: '/',
children: [],
isAux: false,
specificity: null,
data: null,
hash: null,
});
});
it('should work with single route', () => {
const nestedRouter = {
rootComponentType: {
name: 'homeComponent',
},
config: [],
};
const parsedRoutes = parseRoutes(nestedRouter as any);
expect(parsedRoutes).toEqual({
handler: 'homeComponent',
name: 'homeComponent',
path: '/',
children: [],
isAux: false,
specificity: null,
data: null,
hash: null,
});
});
it('should work with nested routes', () => {
const nestedRouter = {
rootComponentType: {
name: 'homeComponent',
},
config: [
{
outlet: 'outlet',
path: 'component-one',
component: {
name: 'component-one',
},
},
{
path: 'component-two',
component: {
name: 'component-two',
},
data: {
name: 'component-two',
},
children: [
{
path: 'component-two-two',
component: {
name: 'component-two-two',
},
_loadedConfig: {
routes: [
{
path: 'component-two-two-two',
component: {
name: 'component-two-two-two',
},
},
],
},
},
],
},
{
loadChildren: true,
path: 'lazy',
},
{
path: 'redirect',
redirectTo: 'redirectTo',
},
],
};
const parsedRoutes = parseRoutes(nestedRouter as any);
expect(parsedRoutes).toEqual({
handler: 'homeComponent',
name: 'homeComponent',
path: '/',
children: [
{
handler: 'component-one',
data: [],
hash: null,
specificity: null,
name: 'component-one',
path: '/(outlet:component-one)',
isAux: true,
children: [],
},
{
handler: 'component-two',
data: [Object({key: 'name', value: 'component-two'})],
hash: null,
specificity: null,
name: 'component-two',
path: '/component-two',
isAux: false,
children: [
{
handler: 'component-two-two',
data: [],
hash: null,
specificity: null,
name: 'component-two-two',
path: '/component-two/component-two-two',
isAux: false,
children: [
{
handler: 'component-two-two-two',
data: [],
hash: null,
specificity: null,
name: 'component-two-two-two',
path: '/component-two/component-two-two/component-two-two-two',
isAux: false,
children: [],
},
],
},
],
},
{
handler: 'lazy [Lazy]',
data: [],
hash: null,
specificity: null,
name: 'lazy [Lazy]',
path: '/lazy',
isAux: false,
children: [],
},
{
handler: 'redirect -> redirecting to -> "redirectTo"',
data: [],
hash: null,
specificity: null,
name: 'redirect -> redirecting to -> "redirectTo"',
path: '/redirect',
isAux: false,
children: [],
},
],
isAux: false,
specificity: null,
data: null,
hash: null,
});
});
});
| {
"end_byte": 4320,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/router-tree.spec.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/client-event-subscribers.spec.ts_0_2527 | /**
* @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 {Events, MessageBus} from 'protocol';
import {subscribeToClientEvents} from './client-event-subscribers';
import {appIsAngular, appIsAngularIvy, appIsSupportedAngularVersion} from 'shared-utils';
import {DirectiveForestHooks} from './hooks/hooks';
import {of} from 'rxjs';
describe('ClientEventSubscriber', () => {
let messageBusMock: MessageBus<Events>;
let appNode: HTMLElement | null = null;
beforeEach(() => {
// mock isAngular et al
appNode = mockAngular();
messageBusMock = jasmine.createSpyObj<MessageBus<Events>>('messageBus', [
'on',
'once',
'emit',
'destroy',
]);
});
afterEach(() => {
// clearing the dom after each test
if (appNode) {
document.body.removeChild(appNode);
appNode = null;
}
});
it('is it Angular ready (testing purposed)', () => {
expect(appIsAngular()).withContext('isAng').toBe(true);
expect(appIsSupportedAngularVersion()).withContext('appIsSupportedAngularVersion').toBe(true);
expect(appIsAngularIvy()).withContext('appIsAngularIvy').toBe(true);
});
it('should setup inspector', () => {
subscribeToClientEvents(messageBusMock, {directiveForestHooks: MockDirectiveForestHooks});
expect(messageBusMock.on).toHaveBeenCalledWith('inspectorStart', jasmine.any(Function));
expect(messageBusMock.on).toHaveBeenCalledWith('inspectorEnd', jasmine.any(Function));
expect(messageBusMock.on).toHaveBeenCalledWith('createHighlightOverlay', jasmine.any(Function));
expect(messageBusMock.on).toHaveBeenCalledWith('removeHighlightOverlay', jasmine.any(Function));
expect(messageBusMock.on).toHaveBeenCalledWith('createHydrationOverlay', jasmine.any(Function));
expect(messageBusMock.on).toHaveBeenCalledWith('removeHydrationOverlay', jasmine.any(Function));
});
});
function mockAngular() {
const appNode = document.createElement('app');
appNode.setAttribute('ng-version', '17.0.0');
(appNode as any).__ngContext__ = true;
document.body.appendChild(appNode);
(window as any) = {
ng: {
getComponent: () => {},
},
};
return appNode;
}
class MockDirectiveForestHooks extends DirectiveForestHooks {
profiler = {
subscribe: () => {},
changeDetection$: of(),
} as any as DirectiveForestHooks['profiler'];
initialize = () => {};
}
| {
"end_byte": 2527,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/client-event-subscribers.spec.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/interfaces.ts_0_705 | /**
* @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 {DevToolsNode} from 'protocol';
export interface DebuggingAPI {
getComponent(node: Node): any;
getDirectives(node: Node): any[];
getHostElement(cmp: any): HTMLElement;
}
export interface DirectiveInstanceType {
instance: any;
name: string;
}
export interface ComponentInstanceType {
instance: any;
name: string;
isElement: boolean;
}
export interface ComponentTreeNode
extends DevToolsNode<DirectiveInstanceType, ComponentInstanceType> {
children: ComponentTreeNode[];
}
| {
"end_byte": 705,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/interfaces.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/directive-forest/render-tree.ts_0_3295 | /**
* @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 {ɵHydratedNode as HydrationNode} from '@angular/core';
import {HydrationStatus} from 'protocol';
import {ComponentTreeNode} from '../interfaces';
import {ngDebugClient} from '../ng-debug-api/ng-debug-api';
import {isCustomElement} from '../utils';
const extractViewTree = (
domNode: Node | Element,
result: ComponentTreeNode[],
getComponent: (element: Element) => {} | null,
getDirectives: (node: Node) => {}[],
): ComponentTreeNode[] => {
// Ignore DOM Node if it came from a different frame. Use instanceof Node to check this.
if (!(domNode instanceof Node)) {
return result;
}
const directives = getDirectives(domNode);
if (!directives.length && !(domNode instanceof Element)) {
return result;
}
const componentTreeNode: ComponentTreeNode = {
children: [],
component: null,
directives: directives.map((dir) => {
return {
instance: dir,
name: dir.constructor.name,
};
}),
element: domNode.nodeName.toLowerCase(),
nativeElement: domNode,
hydration: hydrationStatus(domNode as HydrationNode),
};
if (!(domNode instanceof Element)) {
result.push(componentTreeNode);
return result;
}
const component = getComponent(domNode);
if (component) {
componentTreeNode.component = {
instance: component,
isElement: isCustomElement(domNode),
name: domNode.nodeName.toLowerCase(),
};
}
if (component || componentTreeNode.directives.length) {
result.push(componentTreeNode);
}
if (componentTreeNode.component || componentTreeNode.directives.length) {
domNode.childNodes.forEach((node) =>
extractViewTree(node, componentTreeNode.children, getComponent, getDirectives),
);
} else {
domNode.childNodes.forEach((node) =>
extractViewTree(node, result, getComponent, getDirectives),
);
}
return result;
};
function hydrationStatus(node: HydrationNode): HydrationStatus {
switch (node.__ngDebugHydrationInfo__?.status) {
case 'hydrated':
return {status: 'hydrated'};
case 'skipped':
return {status: 'skipped'};
case 'mismatched':
return {
status: 'mismatched',
expectedNodeDetails: node.__ngDebugHydrationInfo__.expectedNodeDetails,
actualNodeDetails: node.__ngDebugHydrationInfo__.actualNodeDetails,
};
default:
return null;
}
}
export class RTreeStrategy {
supports(): boolean {
return (['getDirectiveMetadata', 'getComponent', 'getDirectives'] as const).every(
(method) => typeof ngDebugClient()[method] === 'function',
);
}
build(element: Element): ComponentTreeNode[] {
// We want to start from the root element so that we can find components which are attached to
// the application ref and which host elements have been inserted with DOM APIs.
while (element.parentElement) {
element = element.parentElement;
}
const getComponent = ngDebugClient().getComponent;
const getDirectives = ngDebugClient().getDirectives;
return extractViewTree(element, [], getComponent, getDirectives);
}
}
| {
"end_byte": 3295,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/directive-forest/render-tree.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/directive-forest/render-tree.spec.ts_0_3824 | /**
* @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 {RTreeStrategy} from './render-tree';
describe('render tree extraction', () => {
let treeStrategy: RTreeStrategy;
let directiveMap: Map<Node, any[]>;
let componentMap: Map<Element, any>;
beforeEach(() => {
treeStrategy = new RTreeStrategy();
directiveMap = new Map();
componentMap = new Map();
(window as any).ng = {
getDirectiveMetadata(): void {},
getComponent(element: Element): any {
return componentMap.get(element);
},
getDirectives(node: Node): any {
return directiveMap.get(node) || [];
},
};
});
afterEach(() => delete (window as any).ng);
it('should detect Angular Ivy apps', () => {
expect(treeStrategy.supports()).toBeTrue();
});
it('should fail with detection of non-Ivy apps', () => {
delete (window as any).ng.getDirectiveMetadata;
expect(treeStrategy.supports()).toBeFalse();
});
it('should extract render tree from an empty element', () => {
expect(treeStrategy.build(document.createElement('div'))).toEqual([]);
});
it('should extract trees without structural directives', () => {
const appNode = document.createElement('app');
const childNode = document.createElement('child');
const childDirectiveNode = document.createElement('div');
appNode.appendChild(childNode);
appNode.appendChild(childDirectiveNode);
const appComponent: any = {};
const childComponent: any = {};
const childDirective: any = {};
componentMap.set(appNode, appComponent);
componentMap.set(childNode, childComponent);
directiveMap.set(childDirectiveNode, [childDirective]);
const rtree = treeStrategy.build(appNode);
expect(rtree.length).toBe(1);
expect(rtree[0].children.length).toBe(2);
expect(rtree[0].children[0].component?.instance).toBe(childComponent);
expect(rtree[0].children[1].component).toBe(null);
expect(rtree[0].children[1].directives[0].instance).toBe(childDirective);
});
it('should skip nodes without directives', () => {
const appNode = document.createElement('app');
const childNode = document.createElement('div');
const childComponentNode = document.createElement('child');
appNode.appendChild(childNode);
childNode.appendChild(childComponentNode);
const appComponent: any = {};
const childComponent: any = {};
componentMap.set(appNode, appComponent);
componentMap.set(childComponentNode, childComponent);
const rtree = treeStrategy.build(appNode);
expect(rtree[0].children.length).toBe(1);
expect(rtree[0].children[0].children.length).toBe(0);
});
it('should go all the way to the root element to look up for nodes', () => {
const rootNode = document.createElement('body');
const siblingNode = document.createElement('section');
const appNode = document.createElement('app');
const childNode = document.createElement('div');
const childComponentNode = document.createElement('child');
rootNode.appendChild(appNode);
rootNode.appendChild(siblingNode);
appNode.appendChild(childNode);
childNode.appendChild(childComponentNode);
const appComponent: any = {};
const childComponent: any = {};
const siblingComponent: any = {};
componentMap.set(siblingNode, siblingComponent);
componentMap.set(appNode, appComponent);
componentMap.set(childComponentNode, childComponent);
const rtree = treeStrategy.build(appNode);
expect(rtree[0].children.length).toBe(1);
expect(rtree[0].children[0].children.length).toBe(0);
expect(rtree[1].component?.instance).toBe(siblingComponent);
});
});
| {
"end_byte": 3824,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/directive-forest/render-tree.spec.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/directive-forest/ltree.ts_0_4290 | /**
* @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 {SemVerDSL} from 'semver-dsl';
import {getDirectiveName} from '../highlighter';
import {ComponentInstanceType, ComponentTreeNode, DirectiveInstanceType} from '../interfaces';
import {isCustomElement} from '../utils';
import {VERSION} from '../version';
let HEADER_OFFSET = 19;
const latest = () => {
HEADER_OFFSET = 20;
};
SemVerDSL(VERSION).gte('10.0.0-next.4', latest);
// In g3 everyone has version 0.0.0, using the currently synced commits in the g3 codebase.
SemVerDSL(VERSION).eq('0.0.0', latest);
const TYPE = 1;
const ELEMENT = 0;
const LVIEW_TVIEW = 1;
// Big oversimplification of the LView structure.
type LView = Array<any>;
export const isLContainer = (value: unknown): boolean => {
return Array.isArray(value) && value[TYPE] === true;
};
const isLView = (value: unknown): value is LView => {
return Array.isArray(value) && typeof value[TYPE] === 'object';
};
export const METADATA_PROPERTY_NAME = '__ngContext__';
export function getLViewFromDirectiveOrElementInstance(dir: any): null | LView {
if (!dir) {
return null;
}
const context = dir[METADATA_PROPERTY_NAME];
if (!context) {
return null;
}
if (isLView(context)) {
return context;
}
return context.lView;
}
export const getDirectiveHostElement = (dir: any) => {
if (!dir) {
return false;
}
const ctx = dir[METADATA_PROPERTY_NAME];
if (!ctx) {
return false;
}
if (ctx[0] !== null) {
return ctx[0];
}
const components = ctx[LVIEW_TVIEW].components;
if (!components || components.length !== 1) {
return false;
}
return ctx[components[0]][0];
};
export class LTreeStrategy {
supports(element: Element): boolean {
return typeof (element as any).__ngContext__ !== 'undefined';
}
private _getNode(lView: LView, data: any, idx: number): ComponentTreeNode {
const directives: DirectiveInstanceType[] = [];
let component: ComponentInstanceType | null = null;
const tNode = data[idx];
const node = lView[idx][ELEMENT];
const element = (node.tagName || node.nodeName).toLowerCase();
if (!tNode) {
return {
nativeElement: node,
children: [],
element,
directives: [],
component: null,
hydration: null, // We know there is no hydration if we use the LTreeStrategy
};
}
for (let i = tNode.directiveStart; i < tNode.directiveEnd; i++) {
const instance = lView[i];
const dirMeta = data[i];
if (dirMeta && dirMeta.template) {
component = {
name: element,
isElement: isCustomElement(node),
instance,
};
} else if (dirMeta) {
directives.push({
name: getDirectiveName(instance),
instance,
});
}
}
return {
nativeElement: node,
children: [],
element,
directives,
component,
hydration: null, // We know there is no hydration if we use the LTreeStrategy
};
}
private _extract(lViewOrLContainer: any, nodes: ComponentTreeNode[] = []): ComponentTreeNode[] {
if (isLContainer(lViewOrLContainer)) {
for (let i = 9; i < lViewOrLContainer.length; i++) {
if (lViewOrLContainer[i]) {
this._extract(lViewOrLContainer[i], nodes);
}
}
return nodes;
}
const lView = lViewOrLContainer;
const tView = lView[LVIEW_TVIEW];
for (let i = HEADER_OFFSET; i < lView.length; i++) {
const lViewItem = lView[i];
if (tView.data && Array.isArray(lViewItem) && lViewItem[ELEMENT] instanceof Node) {
const node = this._getNode(lView, tView.data, i);
// TODO(mgechev): verify if this won't make us skip projected content.
if (node.component || node.directives.length) {
nodes.push(node);
this._extract(lViewItem, node.children);
}
}
}
return nodes;
}
build(element: Element, nodes: ComponentTreeNode[] = []): ComponentTreeNode[] {
const ctx = (element as any).__ngContext__;
const rootLView = ctx.lView ?? ctx;
return this._extract(rootLView);
}
}
| {
"end_byte": 4290,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/directive-forest/ltree.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/directive-forest/BUILD.bazel_0_1168 | load("//devtools/tools:typescript.bzl", "ts_library", "ts_test_library")
load("//devtools/tools:defaults.bzl", "karma_web_test_suite")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "directive-forest",
srcs = glob(
include = ["*.ts"],
exclude = ["*.spec.ts"],
),
deps = [
"//devtools/projects/ng-devtools-backend/src/lib:highlighter",
"//devtools/projects/ng-devtools-backend/src/lib:interfaces",
"//devtools/projects/ng-devtools-backend/src/lib:utils",
"//devtools/projects/ng-devtools-backend/src/lib:version",
"//devtools/projects/ng-devtools-backend/src/lib/ng-debug-api",
"//devtools/projects/protocol",
"//packages/core",
"@npm//semver-dsl",
],
)
karma_web_test_suite(
name = "test",
deps = [
":test_lib",
],
)
ts_test_library(
name = "test_lib",
srcs = [
"render-tree.spec.ts",
],
deps = [
":directive-forest",
"//devtools/projects/ng-devtools-backend/src/lib:interfaces",
"//devtools/projects/ng-devtools-backend/src/lib:utils",
"@npm//@types",
],
)
| {
"end_byte": 1168,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/directive-forest/BUILD.bazel"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/directive-forest/index.ts_0_1020 | /**
* @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 {LTreeStrategy} from './ltree';
import {RTreeStrategy} from './render-tree';
export {
getDirectiveHostElement,
getLViewFromDirectiveOrElementInstance,
METADATA_PROPERTY_NAME,
} from './ltree';
// The order of the strategies matters. Lower indices have higher priority.
const strategies = [new RTreeStrategy(), new LTreeStrategy()];
let strategy: null | RTreeStrategy | LTreeStrategy = null;
const selectStrategy = (element: Element) => {
for (const s of strategies) {
if (s.supports(element)) {
return s;
}
}
return null;
};
export const buildDirectiveTree = (element: Element) => {
if (!strategy) {
strategy = selectStrategy(element);
}
if (!strategy) {
console.error('Unable to parse the component tree');
return [];
}
return strategy.build(element);
};
| {
"end_byte": 1020,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/directive-forest/index.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/ng-debug-api/BUILD.bazel_0_336 | # load("//devtools/tools:typescript.bzl", "ts_library")
load("//devtools/tools:ng_module.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "ng-debug-api",
srcs = glob(
include = ["*.ts"],
exclude = ["*.spec.ts"],
),
deps = [
"//packages/core",
],
)
| {
"end_byte": 336,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/ng-debug-api/BUILD.bazel"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/ng-debug-api/ng-debug-api.ts_0_1248 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type {ɵGlobalDevModeUtils as GlobalDevModeUtils} from '@angular/core';
/**
* Returns a handle to window.ng APIs (global angular debugging).
*
* @returns window.ng
*/
export const ngDebugClient = () => (window as any as GlobalDevModeUtils).ng;
/**
* Checks whether a given debug API is supported within window.ng
*
* @returns boolean
*/
export function ngDebugApiIsSupported(api: keyof GlobalDevModeUtils['ng']): boolean {
const ng = ngDebugClient();
return typeof ng[api] === 'function';
}
/**
* Checks whether Dependency Injection debug API is supported within window.ng
*
* @returns boolean
*/
export function ngDebugDependencyInjectionApiIsSupported(): boolean {
if (!ngDebugApiIsSupported('ɵgetInjectorResolutionPath')) {
return false;
}
if (!ngDebugApiIsSupported('ɵgetDependenciesFromInjectable')) {
return false;
}
if (!ngDebugApiIsSupported('ɵgetInjectorProviders')) {
return false;
}
if (!ngDebugApiIsSupported('ɵgetInjectorMetadata')) {
return false;
}
return true;
}
| {
"end_byte": 1248,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/ng-debug-api/ng-debug-api.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/hooks/capture.ts_0_8191 | /**
* @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 {
DirectiveProfile,
ElementPosition,
ElementProfile,
LifecycleProfile,
ProfilerFrame,
} from 'protocol';
import {getDirectiveName} from '../highlighter';
import {ComponentTreeNode} from '../interfaces';
import {isCustomElement, runOutsideAngular} from '../utils';
import {initializeOrGetDirectiveForestHooks} from '.';
import {DirectiveForestHooks} from './hooks';
import {Hooks} from './profiler';
let inProgress = false;
let inChangeDetection = false;
let eventMap: Map<any, DirectiveProfile>;
let frameDuration = 0;
let hooks: Partial<Hooks> = {};
export const start = (onFrame: (frame: ProfilerFrame) => void): void => {
if (inProgress) {
throw new Error('Recording already in progress');
}
eventMap = new Map<any, DirectiveProfile>();
inProgress = true;
hooks = getHooks(onFrame);
initializeOrGetDirectiveForestHooks().profiler.subscribe(hooks);
};
export const stop = (): ProfilerFrame => {
const directiveForestHooks = initializeOrGetDirectiveForestHooks();
const result = flushBuffer(directiveForestHooks);
initializeOrGetDirectiveForestHooks().profiler.unsubscribe(hooks);
hooks = {};
inProgress = false;
return result;
};
const startEvent = (map: Record<string, number>, directive: any, label: string) => {
const name = getDirectiveName(directive);
const key = `${name}#${label}`;
map[key] = performance.now();
};
const getEventStart = (map: Record<string, number>, directive: any, label: string) => {
const name = getDirectiveName(directive);
const key = `${name}#${label}`;
return map[key];
};
const getHooks = (onFrame: (frame: ProfilerFrame) => void): Partial<Hooks> => {
const timeStartMap: Record<string, number> = {};
return {
// We flush here because it's possible the current node to overwrite
// an existing removed node.
onCreate(
directive: any,
node: Node,
_: number,
isComponent: boolean,
position: ElementPosition,
): void {
eventMap.set(directive, {
isElement: isCustomElement(node),
name: getDirectiveName(directive),
isComponent,
lifecycle: {},
outputs: {},
});
},
onChangeDetectionStart(component: any, node: Node): void {
startEvent(timeStartMap, component, 'changeDetection');
if (!inChangeDetection) {
inChangeDetection = true;
const source = getChangeDetectionSource();
runOutsideAngular(() => {
Promise.resolve().then(() => {
inChangeDetection = false;
onFrame(flushBuffer(initializeOrGetDirectiveForestHooks(), source));
});
});
}
if (!eventMap.has(component)) {
eventMap.set(component, {
isElement: isCustomElement(node),
name: getDirectiveName(component),
isComponent: true,
changeDetection: 0,
lifecycle: {},
outputs: {},
});
}
},
onChangeDetectionEnd(component: any): void {
const profile = eventMap.get(component);
if (profile) {
let current = profile.changeDetection;
if (current === undefined) {
current = 0;
}
const startTimestamp = getEventStart(timeStartMap, component, 'changeDetection');
if (startTimestamp === undefined) {
return;
}
const duration = performance.now() - startTimestamp;
profile.changeDetection = current + duration;
frameDuration += duration;
} else {
console.warn('Could not find profile for', component);
}
},
onDestroy(
directive: any,
node: Node,
_: number,
isComponent: boolean,
__: ElementPosition,
): void {
// Make sure we reflect such directives in the report.
if (!eventMap.has(directive)) {
eventMap.set(directive, {
isElement: isComponent && isCustomElement(node),
name: getDirectiveName(directive),
isComponent,
lifecycle: {},
outputs: {},
});
}
},
onLifecycleHookStart(
directive: any,
hookName: keyof LifecycleProfile,
node: Node,
__: number,
isComponent: boolean,
): void {
startEvent(timeStartMap, directive, hookName);
if (!eventMap.has(directive)) {
eventMap.set(directive, {
isElement: isCustomElement(node),
name: getDirectiveName(directive),
isComponent,
lifecycle: {},
outputs: {},
});
}
},
onLifecycleHookEnd(
directive: any,
hookName: keyof LifecycleProfile,
_: Node,
__: number,
___: boolean,
): void {
const dir = eventMap.get(directive);
const startTimestamp = getEventStart(timeStartMap, directive, hookName);
if (startTimestamp === undefined) {
return;
}
if (!dir) {
console.warn('Could not find directive in onLifecycleHook callback', directive, hookName);
return;
}
const duration = performance.now() - startTimestamp;
dir.lifecycle[hookName] = (dir.lifecycle[hookName] || 0) + duration;
frameDuration += duration;
},
onOutputStart(
componentOrDirective: any,
outputName: string,
node: Node,
isComponent: boolean,
): void {
startEvent(timeStartMap, componentOrDirective, outputName);
if (!eventMap.has(componentOrDirective)) {
eventMap.set(componentOrDirective, {
isElement: isCustomElement(node),
name: getDirectiveName(componentOrDirective),
isComponent,
lifecycle: {},
outputs: {},
});
}
},
onOutputEnd(componentOrDirective: any, outputName: string): void {
const name = outputName;
const entry = eventMap.get(componentOrDirective);
const startTimestamp = getEventStart(timeStartMap, componentOrDirective, name);
if (startTimestamp === undefined) {
return;
}
if (!entry) {
console.warn(
'Could not find directive or component in onOutputEnd callback',
componentOrDirective,
outputName,
);
return;
}
const duration = performance.now() - startTimestamp;
entry.outputs[name] = (entry.outputs[name] || 0) + duration;
frameDuration += duration;
},
};
};
const insertOrMerge = (lastFrame: ElementProfile, profile: DirectiveProfile) => {
let exists = false;
lastFrame.directives.forEach((d) => {
if (d.name === profile.name) {
exists = true;
let current = d.changeDetection;
if (current === undefined) {
current = 0;
}
d.changeDetection = current + (profile.changeDetection ?? 0);
for (const key of Object.keys(profile.lifecycle) as (keyof LifecycleProfile)[]) {
if (!d.lifecycle[key]) {
d.lifecycle[key] = 0;
}
d.lifecycle[key]! += profile.lifecycle[key]!;
}
for (const key of Object.keys(profile.outputs)) {
if (!d.outputs[key]) {
d.outputs[key] = 0;
}
d.outputs[key] += profile.outputs[key];
}
}
});
if (!exists) {
lastFrame.directives.push(profile);
}
};
const insertElementProfile = (
frames: ElementProfile[],
position: ElementPosition,
profile?: DirectiveProfile,
) => {
if (!profile) {
return;
}
const original = frames;
for (let i = 0; i < position.length - 1; i++) {
const pos = position[i];
if (!frames[pos]) {
// TODO(mgechev): consider how to ensure we don't hit this case
console.warn('Unable to find parent node for', profile, original);
return;
}
frames = frames[pos].children;
}
const lastIdx = position[position.length - 1];
let lastFrame: ElementProfile = {
children: [],
directives: [],
};
if (frames[lastIdx]) {
lastFrame = frames[lastIdx];
} else {
frames[lastIdx] = lastFrame;
}
insertOrMerge(lastFrame, profile);
}; | {
"end_byte": 8191,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/hooks/capture.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/hooks/capture.ts_8193_10921 | const prepareInitialFrame = (source: string, duration: number) => {
const frame: ProfilerFrame = {
source,
duration,
directives: [],
};
const directiveForestHooks = initializeOrGetDirectiveForestHooks();
const directiveForest = directiveForestHooks.getIndexedDirectiveForest();
const traverse = (node: ComponentTreeNode, children = frame.directives) => {
let position: ElementPosition | undefined;
if (node.component) {
position = directiveForestHooks.getDirectivePosition(node.component.instance);
} else {
position = directiveForestHooks.getDirectivePosition(node.directives[0].instance);
}
if (position === undefined) {
return;
}
const directives = node.directives.map((d) => {
return {
isComponent: false,
isElement: false,
name: getDirectiveName(d.instance),
outputs: {},
lifecycle: {},
};
});
if (node.component) {
directives.push({
isElement: node.component.isElement,
isComponent: true,
lifecycle: {},
outputs: {},
name: getDirectiveName(node.component.instance),
});
}
const result = {
children: [],
directives,
};
children[position[position.length - 1]] = result;
node.children.forEach((n) => traverse(n, result.children));
};
directiveForest.forEach((n) => traverse(n));
return frame;
};
const flushBuffer = (directiveForestHooks: DirectiveForestHooks, source: string = '') => {
const items = Array.from(eventMap.keys());
const positions: ElementPosition[] = [];
const positionDirective = new Map<ElementPosition, any>();
items.forEach((dir) => {
const position = directiveForestHooks.getDirectivePosition(dir);
if (position === undefined) {
return;
}
positions.push(position);
positionDirective.set(position, dir);
});
positions.sort(lexicographicOrder);
const result = prepareInitialFrame(source, frameDuration);
frameDuration = 0;
positions.forEach((position) => {
const dir = positionDirective.get(position);
insertElementProfile(result.directives, position, eventMap.get(dir));
});
eventMap = new Map<any, DirectiveProfile>();
return result;
};
const getChangeDetectionSource = () => {
const zone = (window as any).Zone;
if (!zone || !zone.currentTask) {
return '';
}
return zone.currentTask.source;
};
const lexicographicOrder = (a: ElementPosition, b: ElementPosition) => {
if (a.length < b.length) {
return -1;
}
if (a.length > b.length) {
return 1;
}
for (let i = 0; i < a.length; i++) {
if (a[i] < b[i]) {
return -1;
}
if (a[i] > b[i]) {
return 1;
}
}
return 0;
}; | {
"end_byte": 10921,
"start_byte": 8193,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/hooks/capture.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/hooks/BUILD.bazel_0_942 | load("//devtools/tools:typescript.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "hooks",
srcs = glob(
include = ["*.ts"],
exclude = [
"*.spec.ts",
"identity-tracker.ts",
],
),
deps = [
":identity_tracker",
"//devtools/projects/ng-devtools-backend/src/lib:highlighter",
"//devtools/projects/ng-devtools-backend/src/lib:interfaces",
"//devtools/projects/ng-devtools-backend/src/lib:utils",
"//devtools/projects/ng-devtools-backend/src/lib/hooks/profiler",
"//devtools/projects/protocol",
],
)
ts_library(
name = "identity_tracker",
srcs = ["identity-tracker.ts"],
deps = [
"//devtools/projects/ng-devtools-backend/src/lib:component_tree",
"//devtools/projects/ng-devtools-backend/src/lib:interfaces",
"//devtools/projects/protocol",
],
)
| {
"end_byte": 942,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/hooks/BUILD.bazel"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/hooks/index.ts_0_3493 | /**
* @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 {LifecycleProfile} from 'protocol';
import {getDirectiveName} from '../highlighter';
import {DirectiveForestHooks} from './hooks';
const markName = (s: string, method: Method) => `🅰️ ${s}#${method}`;
const supportsPerformance =
globalThis.performance && typeof globalThis.performance.getEntriesByName === 'function';
type Method = keyof LifecycleProfile | 'changeDetection' | string;
const recordMark = (s: string, method: Method) => {
if (supportsPerformance) {
// tslint:disable-next-line:ban
performance.mark(`${markName(s, method)}_start`);
}
};
const endMark = (nodeName: string, method: Method) => {
if (supportsPerformance) {
const name = markName(nodeName, method);
const start = `${name}_start`;
const end = `${name}_end`;
if (performance.getEntriesByName(start).length > 0) {
// tslint:disable-next-line:ban
performance.mark(end);
const measureOptions = {
start,
end,
detail: {
devtools: {
dataType: 'track-entry',
color: 'primary',
track: '🅰️ Angular DevTools',
},
},
};
performance.measure(name, measureOptions);
}
performance.clearMarks(start);
performance.clearMarks(end);
performance.clearMeasures(name);
}
};
let timingAPIFlag = false;
export const enableTimingAPI = () => (timingAPIFlag = true);
export const disableTimingAPI = () => (timingAPIFlag = false);
const timingAPIEnabled = () => timingAPIFlag;
let directiveForestHooks: DirectiveForestHooks;
export const initializeOrGetDirectiveForestHooks = (
depsForTestOnly: {
directiveForestHooks?: typeof DirectiveForestHooks;
} = {},
) => {
// Allow for overriding the DirectiveForestHooks implementation for testing purposes.
if (depsForTestOnly.directiveForestHooks) {
directiveForestHooks = new depsForTestOnly.directiveForestHooks();
}
if (directiveForestHooks) {
return directiveForestHooks;
} else {
directiveForestHooks = new DirectiveForestHooks();
}
directiveForestHooks.profiler.subscribe({
onChangeDetectionStart(component: any): void {
if (!timingAPIEnabled()) {
return;
}
recordMark(getDirectiveName(component), 'changeDetection');
},
onChangeDetectionEnd(component: any): void {
if (!timingAPIEnabled()) {
return;
}
endMark(getDirectiveName(component), 'changeDetection');
},
onLifecycleHookStart(component: any, lifecyle: keyof LifecycleProfile): void {
if (!timingAPIEnabled()) {
return;
}
recordMark(getDirectiveName(component), lifecyle);
},
onLifecycleHookEnd(component: any, lifecyle: keyof LifecycleProfile): void {
if (!timingAPIEnabled()) {
return;
}
endMark(getDirectiveName(component), lifecyle);
},
onOutputStart(component: any, output: string): void {
if (!timingAPIEnabled()) {
return;
}
recordMark(getDirectiveName(component), output);
},
onOutputEnd(component: any, output: string): void {
if (!timingAPIEnabled()) {
return;
}
endMark(getDirectiveName(component), output);
},
});
directiveForestHooks.initialize();
return directiveForestHooks;
};
| {
"end_byte": 3493,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/hooks/index.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/hooks/identity-tracker.ts_0_4506 | /**
* @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 {DevToolsNode, ElementPosition} from 'protocol';
import {buildDirectiveForest} from '../component-tree';
import {ComponentInstanceType, ComponentTreeNode, DirectiveInstanceType} from '../interfaces';
export declare interface Type<T> extends Function {
new (...args: any[]): T;
}
interface TreeNode {
parent: TreeNode;
directive?: Type<any>;
children: TreeNode[];
}
export type NodeArray = {
directive: any;
isComponent: boolean;
}[];
export class IdentityTracker {
private static _instance: IdentityTracker;
private _directiveIdCounter = 0;
private _currentDirectivePosition = new Map<any, ElementPosition>();
private _currentDirectiveId = new Map<any, number>();
isComponent = new Map<any, boolean>();
// private constructor for Singleton Pattern
private constructor() {}
static getInstance(): IdentityTracker {
if (!IdentityTracker._instance) {
IdentityTracker._instance = new IdentityTracker();
}
return IdentityTracker._instance;
}
getDirectivePosition(dir: any): ElementPosition | undefined {
return this._currentDirectivePosition.get(dir);
}
getDirectiveId(dir: any): number | undefined {
return this._currentDirectiveId.get(dir);
}
hasDirective(dir: any): boolean {
return this._currentDirectiveId.has(dir);
}
index(): {
newNodes: NodeArray;
removedNodes: NodeArray;
indexedForest: IndexedNode[];
directiveForest: ComponentTreeNode[];
} {
const directiveForest = buildDirectiveForest();
const indexedForest = indexForest(directiveForest);
const newNodes: NodeArray = [];
const removedNodes: NodeArray = [];
const allNodes = new Set<any>();
indexedForest.forEach((root) => this._index(root, null, newNodes, allNodes));
this._currentDirectiveId.forEach((_: number, dir: any) => {
if (!allNodes.has(dir)) {
removedNodes.push({directive: dir, isComponent: !!this.isComponent.get(dir)});
// We can't clean these up because during profiling
// they might be requested for removed components
// this._currentDirectiveId.delete(dir);
// this._currentDirectivePosition.delete(dir);
}
});
return {newNodes, removedNodes, indexedForest, directiveForest};
}
private _index(
node: IndexedNode,
parent: TreeNode | null,
newNodes: {directive: any; isComponent: boolean}[],
allNodes: Set<any>,
): void {
if (node.component) {
allNodes.add(node.component.instance);
this.isComponent.set(node.component.instance, true);
this._indexNode(node.component.instance, node.position, newNodes);
}
(node.directives || []).forEach((dir) => {
allNodes.add(dir.instance);
this.isComponent.set(dir.instance, false);
this._indexNode(dir.instance, node.position, newNodes);
});
node.children.forEach((child) => this._index(child, parent, newNodes, allNodes));
}
private _indexNode(directive: any, position: ElementPosition, newNodes: NodeArray): void {
this._currentDirectivePosition.set(directive, position);
if (!this._currentDirectiveId.has(directive)) {
newNodes.push({directive, isComponent: !!this.isComponent.get(directive)});
this._currentDirectiveId.set(directive, this._directiveIdCounter++);
}
}
destroy(): void {
this._currentDirectivePosition = new Map<any, ElementPosition>();
this._currentDirectiveId = new Map<any, number>();
}
}
export interface IndexedNode extends DevToolsNode<DirectiveInstanceType, ComponentInstanceType> {
position: ElementPosition;
children: IndexedNode[];
}
const indexTree = <T extends DevToolsNode<DirectiveInstanceType, ComponentInstanceType>>(
node: T,
idx: number,
parentPosition: number[] = [],
): IndexedNode => {
const position = parentPosition.concat([idx]);
return {
position,
element: node.element,
component: node.component,
directives: node.directives.map((d) => ({position, ...d})),
children: node.children.map((n, i) => indexTree(n, i, position)),
nativeElement: node.nativeElement,
hydration: node.hydration,
} as IndexedNode;
};
export const indexForest = <T extends DevToolsNode<DirectiveInstanceType, ComponentInstanceType>>(
forest: T[],
): IndexedNode[] => forest.map((n, i) => indexTree(n, i));
| {
"end_byte": 4506,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/hooks/identity-tracker.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/hooks/hooks.ts_0_1785 | /**
* @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 {ElementPosition} from 'protocol';
import {ComponentTreeNode} from '../interfaces';
import {IdentityTracker, IndexedNode} from './identity-tracker';
import {Profiler, selectProfilerStrategy} from './profiler';
/**
* Class to hook into directive forest.
*
* Exposes latest directive forest state.
*
* Delegates profiling to a Profiler instance.
* Delegates forest indexing to IdentityTracker Singleton
*/
export class DirectiveForestHooks {
private _tracker = IdentityTracker.getInstance();
private _forest: ComponentTreeNode[] = [];
private _indexedForest: IndexedNode[] = [];
profiler: Profiler = selectProfilerStrategy();
getDirectivePosition(dir: any): ElementPosition | undefined {
const result = this._tracker.getDirectivePosition(dir);
if (result === undefined) {
console.warn('Unable to find position of', dir);
}
return result;
}
getDirectiveId(dir: any): number | undefined {
const result = this._tracker.getDirectiveId(dir);
if (result === undefined) {
console.warn('Unable to find ID of', result);
}
return result;
}
getIndexedDirectiveForest(): IndexedNode[] {
return this._indexedForest;
}
getDirectiveForest(): ComponentTreeNode[] {
return this._forest;
}
initialize(): void {
this.indexForest();
}
indexForest(): void {
const {newNodes, removedNodes, indexedForest, directiveForest} = this._tracker.index();
this._indexedForest = indexedForest;
this._forest = directiveForest;
this.profiler.onIndexForest(newNodes, removedNodes);
}
}
| {
"end_byte": 1785,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/hooks/hooks.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/hooks/profiler/polyfill.ts_0_5365 | /**
* @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 {
getDirectiveHostElement,
getLViewFromDirectiveOrElementInstance,
METADATA_PROPERTY_NAME,
} from '../../directive-forest';
import {runOutsideAngular} from '../../utils';
import {IdentityTracker, NodeArray} from '../identity-tracker';
import {getLifeCycleName, Profiler} from './shared';
const hookTViewProperties = [
'preOrderHooks',
'preOrderCheckHooks',
'contentHooks',
'contentCheckHooks',
'viewHooks',
'viewCheckHooks',
'destroyHooks',
];
// Only used in older Angular versions prior to the introduction of `getDirectiveMetadata`
const componentMetadata = (instance: any) => instance?.constructor?.ɵcmp;
/**
* Implementation of Profiler that uses monkey patching of directive templates and lifecycle
* methods to fire profiler hooks.
*/
export class PatchingProfiler extends Profiler {
private _patched = new Map<any, () => void>();
private _undoLifecyclePatch: (() => void)[] = [];
private _tracker = IdentityTracker.getInstance();
override destroy(): void {
this._tracker.destroy();
for (const [cmp, template] of this._patched) {
const meta = componentMetadata(cmp);
meta.template = template;
meta.tView.template = template;
}
this._patched = new Map<any, () => void>();
this._undoLifecyclePatch.forEach((p) => p());
this._undoLifecyclePatch = [];
}
override onIndexForest(newNodes: NodeArray, removedNodes: NodeArray): void {
newNodes.forEach((node) => {
this._observeLifecycle(node.directive, node.isComponent);
this._observeComponent(node.directive);
this._fireCreationCallback(node.directive, node.isComponent);
});
removedNodes.forEach((node) => {
this._patched.delete(node.directive);
this._fireDestroyCallback(node.directive, node.isComponent);
});
}
private _fireCreationCallback(component: any, isComponent: boolean): void {
const position = this._tracker.getDirectivePosition(component);
const id = this._tracker.getDirectiveId(component);
this._onCreate(component, getDirectiveHostElement(component), id, isComponent, position);
}
private _fireDestroyCallback(component: any, isComponent: boolean): void {
const position = this._tracker.getDirectivePosition(component);
const id = this._tracker.getDirectiveId(component);
this._onDestroy(component, getDirectiveHostElement(component), id, isComponent, position);
}
private _observeComponent(cmp: any): void {
const declarations = componentMetadata(cmp);
if (!declarations) {
return;
}
const original = declarations.template;
const self = this;
if (original.patched) {
return;
}
declarations.tView.template = function (_: any, component: any): void {
if (!self._inChangeDetection) {
self._inChangeDetection = true;
runOutsideAngular(() => {
Promise.resolve().then(() => {
self.changeDetection$.next();
self._inChangeDetection = false;
});
});
}
const position = self._tracker.getDirectivePosition(component);
const id = self._tracker.getDirectiveId(component);
self._onChangeDetectionStart(component, getDirectiveHostElement(component), id, position);
original.apply(this, arguments);
if (self._tracker.hasDirective(component) && id !== undefined && position !== undefined) {
self._onChangeDetectionEnd(component, getDirectiveHostElement(component), id, position);
}
};
declarations.tView.template.patched = true;
this._patched.set(cmp, original);
}
private _observeLifecycle(directive: any, isComponent: boolean): void {
const ctx = getLViewFromDirectiveOrElementInstance(directive);
if (!ctx) {
return;
}
const tview = ctx[1];
hookTViewProperties.forEach((hook) => {
const current = tview[hook];
if (!Array.isArray(current)) {
return;
}
current.forEach((el: any, idx: number) => {
if (el.patched) {
return;
}
if (typeof el === 'function') {
const self = this;
current[idx] = function (): any {
// We currently don't want to notify the consumer
// for execution of lifecycle hooks of services and pipes.
// These two abstractions don't have `__ngContext__`, and
// currently we won't be able to extract the required
// metadata by the UI.
if (!(this as any)[METADATA_PROPERTY_NAME]) {
return;
}
const id = self._tracker.getDirectiveId(this);
const lifecycleHookName = getLifeCycleName(this, el);
const element = getDirectiveHostElement(this);
self._onLifecycleHookStart(this, lifecycleHookName, element, id, isComponent);
const result = el.apply(this, arguments);
self._onLifecycleHookEnd(this, lifecycleHookName, element, id, isComponent);
return result;
};
current[idx].patched = true;
this._undoLifecyclePatch.push(() => {
current[idx] = el;
});
}
});
});
}
}
| {
"end_byte": 5365,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/hooks/profiler/polyfill.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/hooks/profiler/shared.ts_0_5913 | /**
* @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 {ElementPosition, LifecycleProfile} from 'protocol';
import {Subject} from 'rxjs';
import {NodeArray} from '../identity-tracker';
type CreationHook = (
componentOrDirective: any,
node: Node,
id: number,
isComponent: boolean,
position: ElementPosition,
) => void;
type LifecycleStartHook = (
componentOrDirective: any,
hook: keyof LifecycleProfile,
node: Node,
id: number,
isComponent: boolean,
) => void;
type LifecycleEndHook = (
componentOrDirective: any,
hook: keyof LifecycleProfile,
node: Node,
id: number,
isComponent: boolean,
) => void;
type ChangeDetectionStartHook = (
component: any,
node: Node,
id: number,
position: ElementPosition,
) => void;
type ChangeDetectionEndHook = (
component: any,
node: Node,
id: number,
position: ElementPosition,
) => void;
type DestroyHook = (
componentOrDirective: any,
node: Node,
id: number,
isComponent: boolean,
position: ElementPosition,
) => void;
type OutputStartHook = (
componentOrDirective: any,
outputName: string,
node: Node,
isComponent: boolean,
) => void;
type OutputEndHook = (
componentOrDirective: any,
outputName: string,
node: Node,
isComponent: boolean,
) => void;
export interface Hooks {
onCreate: CreationHook;
onDestroy: DestroyHook;
onChangeDetectionStart: ChangeDetectionStartHook;
onChangeDetectionEnd: ChangeDetectionEndHook;
onLifecycleHookStart: LifecycleStartHook;
onLifecycleHookEnd: LifecycleEndHook;
onOutputStart: OutputStartHook;
onOutputEnd: OutputEndHook;
}
/**
* Class for profiling angular applications. Handles hook subscriptions and emitting change
* detection events.
*/
export abstract class Profiler {
/** @internal */
protected _inChangeDetection = false;
changeDetection$ = new Subject<void>();
private _hooks: Partial<Hooks>[] = [];
constructor(config: Partial<Hooks> = {}) {
this._hooks.push(config);
}
abstract destroy(): void;
abstract onIndexForest(newNodes: NodeArray, removedNodes: NodeArray): void;
subscribe(config: Partial<Hooks>): void {
this._hooks.push(config);
}
unsubscribe(config: Partial<Hooks>): void {
this._hooks.splice(this._hooks.indexOf(config), 1);
}
/** @internal */
protected _onCreate(
_: any,
__: Node,
id: number | undefined,
___: boolean,
position: ElementPosition | undefined,
): void {
if (id === undefined || position === undefined) {
return;
}
this._invokeCallback('onCreate', arguments);
}
/** @internal */
protected _onDestroy(
_: any,
__: Node,
id: number | undefined,
___: boolean,
position: ElementPosition | undefined,
): void {
if (id === undefined || position === undefined) {
return;
}
this._invokeCallback('onDestroy', arguments);
}
/** @internal */
protected _onChangeDetectionStart(
_: any,
__: Node,
id: number | undefined,
position: ElementPosition | undefined,
): void {
if (id === undefined || position === undefined) {
return;
}
this._invokeCallback('onChangeDetectionStart', arguments);
}
/** @internal */
protected _onChangeDetectionEnd(
_: any,
__: Node,
id: number | undefined,
position: ElementPosition | undefined,
): void {
if (id === undefined || position === undefined) {
return;
}
this._invokeCallback('onChangeDetectionEnd', arguments);
}
/** @internal */
protected _onLifecycleHookStart(
_: any,
__: keyof LifecycleProfile | 'unknown',
___: Node,
id: number | undefined,
____: boolean,
): void {
if (id === undefined) {
return;
}
this._invokeCallback('onLifecycleHookStart', arguments);
}
/** @internal */
protected _onLifecycleHookEnd(
_: any,
__: keyof LifecycleProfile | 'unknown',
___: Node,
id: number | undefined,
____: boolean,
): void {
if (id === undefined) {
return;
}
this._invokeCallback('onLifecycleHookEnd', arguments);
}
/** @internal */
protected _onOutputStart(
_: any,
__: string,
___: Node,
id: number | undefined,
____: boolean,
): void {
if (id === undefined) {
return;
}
this._invokeCallback('onOutputStart', arguments);
}
/** @internal */
protected _onOutputEnd(
_: any,
__: string,
___: Node,
id: number | undefined,
____: boolean,
): void {
if (id === undefined) {
return;
}
this._invokeCallback('onOutputEnd', arguments);
}
/** @internal */
private _invokeCallback(name: keyof Hooks, args: IArguments): void {
this._hooks.forEach((config) => {
const cb = config[name];
if (typeof cb === 'function') {
(cb as any).apply(null, args);
}
});
}
}
const hookNames = [
'OnInit',
'OnDestroy',
'OnChanges',
'DoCheck',
'AfterContentInit',
'AfterContentChecked',
'AfterViewInit',
'AfterViewChecked',
];
const hookMethodNames = new Set(hookNames.map((hook) => `ng${hook}`));
export const getLifeCycleName = (obj: {}, fn: any): keyof LifecycleProfile | 'unknown' => {
const proto = Object.getPrototypeOf(obj);
const keys = Object.getOwnPropertyNames(proto);
for (const propName of keys) {
// We don't want to touch random get accessors.
if (!hookMethodNames.has(propName)) {
continue;
}
if (proto[propName] === fn) {
return propName as keyof LifecycleProfile;
}
}
const fnName = fn.name;
if (typeof fnName !== 'string') {
return 'unknown';
}
for (const hookName of hookNames) {
if (fnName.indexOf(hookName) >= 0) {
return `ng${hookName}` as keyof LifecycleProfile;
}
}
return 'unknown';
};
| {
"end_byte": 5913,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/hooks/profiler/shared.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/hooks/profiler/native.ts_0_6247 | /**
* @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 {ɵProfilerEvent} from '@angular/core';
import {getDirectiveHostElement} from '../../directive-forest';
import {ngDebugClient} from '../../ng-debug-api/ng-debug-api';
import {runOutsideAngular} from '../../utils';
import {IdentityTracker, NodeArray} from '../identity-tracker';
import {getLifeCycleName, Hooks, Profiler} from './shared';
type ProfilerCallback = (
event: ɵProfilerEvent,
instanceOrLView: {} | null,
hookOrListener: any,
) => void;
/** Implementation of Profiler that utilizes framework APIs fire profiler hooks. */
export class NgProfiler extends Profiler {
private _tracker = IdentityTracker.getInstance();
private _callbacks: ProfilerCallback[] = [];
private _lastDirectiveInstance: {} | null = null;
constructor(config: Partial<Hooks> = {}) {
super(config);
this._setProfilerCallback(
(event: ɵProfilerEvent, instanceOrLView: {} | null, hookOrListener: any) => {
if (this[event] === undefined) {
return;
}
this[event](instanceOrLView, hookOrListener);
},
);
this._initialize();
}
private _initialize(): void {
ngDebugClient().ɵsetProfiler(
(event: ɵProfilerEvent, instanceOrLView: {} | null, hookOrListener: any) =>
this._callbacks.forEach((cb) => cb(event, instanceOrLView, hookOrListener)),
);
}
private _setProfilerCallback(callback: ProfilerCallback): void {
this._callbacks.push(callback);
}
override destroy(): void {
this._tracker.destroy();
}
override onIndexForest(newNodes: NodeArray, removedNodes: NodeArray): void {
newNodes.forEach((node) => {
const {directive, isComponent} = node;
const position = this._tracker.getDirectivePosition(directive);
const id = this._tracker.getDirectiveId(directive);
this._onCreate(directive, getDirectiveHostElement(directive), id, isComponent, position);
});
removedNodes.forEach((node) => {
const {directive, isComponent} = node;
const position = this._tracker.getDirectivePosition(directive);
const id = this._tracker.getDirectiveId(directive);
this._onDestroy(directive, getDirectiveHostElement(directive), id, isComponent, position);
});
}
[ɵProfilerEvent.TemplateCreateStart](_directive: any, _hookOrListener: any): void {
// todo: implement
return;
}
[ɵProfilerEvent.TemplateCreateEnd](_directive: any, _hookOrListener: any): void {
// todo: implement
return;
}
[ɵProfilerEvent.TemplateUpdateStart](context: any, _hookOrListener: any): void {
if (!this._inChangeDetection) {
this._inChangeDetection = true;
runOutsideAngular(() => {
Promise.resolve().then(() => {
this.changeDetection$.next();
this._inChangeDetection = false;
});
});
}
const position = this._tracker.getDirectivePosition(context);
const id = this._tracker.getDirectiveId(context);
// If we can find the position and the ID we assume that this is a component instance.
// Alternatively, if we can't find the ID or the position, we assume that this is a
// context of an embedded view (for example, NgForOfContext, NgIfContext, or a custom one).
if (position !== undefined && id !== undefined) {
this._lastDirectiveInstance = context;
}
if (id !== undefined && position !== undefined) {
this._onChangeDetectionStart(context, getDirectiveHostElement(context), id, position);
return;
}
this._onChangeDetectionStart(
this._lastDirectiveInstance,
getDirectiveHostElement(this._lastDirectiveInstance),
this._tracker.getDirectiveId(this._lastDirectiveInstance),
this._tracker.getDirectivePosition(this._lastDirectiveInstance),
);
}
[ɵProfilerEvent.TemplateUpdateEnd](context: any, _hookOrListener: any): void {
const position = this._tracker.getDirectivePosition(context);
const id = this._tracker.getDirectiveId(context);
if (this._tracker.hasDirective(context) && id !== undefined && position !== undefined) {
this._onChangeDetectionEnd(context, getDirectiveHostElement(context), id, position);
return;
}
this._onChangeDetectionEnd(
this._lastDirectiveInstance,
getDirectiveHostElement(this._lastDirectiveInstance),
this._tracker.getDirectiveId(this._lastDirectiveInstance),
this._tracker.getDirectivePosition(this._lastDirectiveInstance),
);
}
[ɵProfilerEvent.LifecycleHookStart](directive: any, hook: any): void {
const id = this._tracker.getDirectiveId(directive);
const element = getDirectiveHostElement(directive);
const lifecycleHookName = getLifeCycleName(directive, hook);
const isComponent = !!this._tracker.isComponent.get(directive);
this._onLifecycleHookStart(directive, lifecycleHookName, element, id, isComponent);
}
[ɵProfilerEvent.LifecycleHookEnd](directive: any, hook: any): void {
const id = this._tracker.getDirectiveId(directive);
const element = getDirectiveHostElement(directive);
const lifecycleHookName = getLifeCycleName(directive, hook);
const isComponent = !!this._tracker.isComponent.get(directive);
this._onLifecycleHookEnd(directive, lifecycleHookName, element, id, isComponent);
}
[ɵProfilerEvent.OutputStart](componentOrDirective: any, listener: () => void): void {
const isComponent = !!this._tracker.isComponent.get(componentOrDirective);
const node = getDirectiveHostElement(componentOrDirective);
const id = this._tracker.getDirectiveId(componentOrDirective);
this._onOutputStart(componentOrDirective, listener.name, node, id, isComponent);
}
[ɵProfilerEvent.OutputEnd](componentOrDirective: any, listener: () => void): void {
const isComponent = !!this._tracker.isComponent.get(componentOrDirective);
const node = getDirectiveHostElement(componentOrDirective);
const id = this._tracker.getDirectiveId(componentOrDirective);
this._onOutputEnd(componentOrDirective, listener.name, node, id, isComponent);
}
}
| {
"end_byte": 6247,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/hooks/profiler/native.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/hooks/profiler/BUILD.bazel_0_636 | load("//devtools/tools:typescript.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "profiler",
srcs = glob(
include = ["*.ts"],
exclude = ["*.spec.ts"],
),
deps = [
"//devtools/projects/ng-devtools-backend/src/lib:utils",
"//devtools/projects/ng-devtools-backend/src/lib/directive-forest",
"//devtools/projects/ng-devtools-backend/src/lib/hooks:identity_tracker",
"//devtools/projects/ng-devtools-backend/src/lib/ng-debug-api",
"//devtools/projects/protocol",
"//packages/core",
"@npm//rxjs",
],
)
| {
"end_byte": 636,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/hooks/profiler/BUILD.bazel"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/hooks/profiler/index.ts_0_770 | /**
* @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 {ngDebugClient} from '../../ng-debug-api/ng-debug-api';
import {NgProfiler} from './native';
import {PatchingProfiler} from './polyfill';
import {Profiler} from './shared';
export {Hooks, Profiler} from './shared';
/**
* Factory method for creating profiler object.
* Gives priority to NgProfiler, falls back on PatchingProfiler if framework APIs are not present.
*/
export const selectProfilerStrategy = (): Profiler => {
if (typeof ngDebugClient().ɵsetProfiler === 'function') {
return new NgProfiler();
}
return new PatchingProfiler();
};
| {
"end_byte": 770,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/hooks/profiler/index.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/component-inspector/component-inspector.ts_0_5408 | /**
* @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 {ElementPosition, HydrationStatus} from 'protocol';
import {findNodeInForest} from '../component-tree';
import {
findComponentAndHost,
highlightHydrationElement,
highlightSelectedElement,
removeHydrationHighlights,
unHighlight,
} from '../highlighter';
import {initializeOrGetDirectiveForestHooks} from '../hooks';
import {ComponentTreeNode} from '../interfaces';
interface Type<T> extends Function {
new (...args: any[]): T;
}
export interface ComponentInspectorOptions {
onComponentEnter: (id: number) => void;
onComponentSelect: (id: number) => void;
onComponentLeave: () => void;
}
export class ComponentInspector {
private _selectedComponent!: {component: Type<unknown>; host: HTMLElement | null};
private readonly _onComponentEnter;
private readonly _onComponentSelect;
private readonly _onComponentLeave;
constructor(
componentOptions: ComponentInspectorOptions = {
onComponentEnter: () => {},
onComponentLeave: () => {},
onComponentSelect: () => {},
},
) {
this.bindMethods();
this._onComponentEnter = componentOptions.onComponentEnter;
this._onComponentSelect = componentOptions.onComponentSelect;
this._onComponentLeave = componentOptions.onComponentLeave;
}
startInspecting(): void {
window.addEventListener('mouseover', this.elementMouseOver, true);
window.addEventListener('click', this.elementClick, true);
window.addEventListener('mouseout', this.cancelEvent, true);
}
stopInspecting(): void {
window.removeEventListener('mouseover', this.elementMouseOver, true);
window.removeEventListener('click', this.elementClick, true);
window.removeEventListener('mouseout', this.cancelEvent, true);
}
elementClick(e: MouseEvent): void {
e.stopImmediatePropagation();
e.preventDefault();
if (this._selectedComponent.component && this._selectedComponent.host) {
this._onComponentSelect(
initializeOrGetDirectiveForestHooks().getDirectiveId(this._selectedComponent.component)!,
);
}
}
elementMouseOver(e: MouseEvent): void {
this.cancelEvent(e);
const el = e.target as HTMLElement;
if (el) {
this._selectedComponent = findComponentAndHost(el);
}
unHighlight();
if (this._selectedComponent.component && this._selectedComponent.host) {
highlightSelectedElement(this._selectedComponent.host);
this._onComponentEnter(
initializeOrGetDirectiveForestHooks().getDirectiveId(this._selectedComponent.component)!,
);
}
}
cancelEvent(e: MouseEvent): void {
e.stopImmediatePropagation();
e.preventDefault();
this._onComponentLeave();
}
bindMethods(): void {
this.startInspecting = this.startInspecting.bind(this);
this.stopInspecting = this.stopInspecting.bind(this);
this.elementMouseOver = this.elementMouseOver.bind(this);
this.elementClick = this.elementClick.bind(this);
this.cancelEvent = this.cancelEvent.bind(this);
}
highlightByPosition(position: ElementPosition): void {
const forest: ComponentTreeNode[] = initializeOrGetDirectiveForestHooks().getDirectiveForest();
const elementToHighlight: HTMLElement | null = findNodeInForest(position, forest);
if (elementToHighlight) {
highlightSelectedElement(elementToHighlight);
}
}
highlightHydrationNodes(): void {
const forest: ComponentTreeNode[] = initializeOrGetDirectiveForestHooks().getDirectiveForest();
// drop the root nodes, we don't want to highlight it
const forestWithoutRoots = forest.flatMap((rootNode) => rootNode.children);
const errorNodes = findErrorNodesForHydrationOverlay(forestWithoutRoots);
// We get the first level of hydrated nodes
// nested mismatched nodes nested in hydrated nodes aren't includes
const nodes = findNodesForHydrationOverlay(forestWithoutRoots);
// This ensures top level mismatched nodes are removed as we have a dedicated array
const otherNodes = nodes.filter(({status}) => status?.status !== 'mismatched');
for (const {node, status} of [...otherNodes, ...errorNodes]) {
highlightHydrationElement(node, status);
}
}
removeHydrationHighlights() {
removeHydrationHighlights();
}
}
/**
* Returns the first level of hydrated nodes
* Note: Mismatched nodes nested in hydrated nodes aren't included
*/
function findNodesForHydrationOverlay(
forest: ComponentTreeNode[],
): {node: Node; status: HydrationStatus}[] {
return forest.flatMap((node) => {
if (node?.hydration?.status) {
// We highlight first level
return {node: node.nativeElement!, status: node.hydration};
}
if (node.children.length) {
return findNodesForHydrationOverlay(node.children);
}
return [];
});
}
function findErrorNodesForHydrationOverlay(
forest: ComponentTreeNode[],
): {node: Node; status: HydrationStatus}[] {
return forest.flatMap((node) => {
if (node?.hydration?.status === 'mismatched') {
// We highlight first level
return {node: node.nativeElement!, status: node.hydration};
}
if (node.children.length) {
return findNodesForHydrationOverlay(node.children);
}
return [];
});
}
| {
"end_byte": 5408,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/component-inspector/component-inspector.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/component-inspector/component-inspector.spec.ts_0_2160 | /**
* @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 {initializeOrGetDirectiveForestHooks} from '../hooks';
import {ComponentInspector} from './component-inspector';
describe('ComponentInspector', () => {
it('should create instance from class', () => {
const inspector = new ComponentInspector();
expect(inspector).toBeTruthy();
});
it('should add event listeners to window on start inspecting', () => {
const eventsSpy = spyOn(window, 'addEventListener');
const inspector = new ComponentInspector();
inspector.startInspecting();
expect(eventsSpy).toHaveBeenCalledTimes(3);
expect(eventsSpy).toHaveBeenCalledWith('mouseover', jasmine.any(Function), true);
expect(eventsSpy).toHaveBeenCalledWith('click', jasmine.any(Function), true);
expect(eventsSpy).toHaveBeenCalledWith('mouseout', jasmine.any(Function), true);
});
it('should remove event listeners from window on stop inspecting', () => {
const eventsSpy = spyOn(window, 'removeEventListener');
const inspector = new ComponentInspector();
inspector.stopInspecting();
expect(eventsSpy).toHaveBeenCalledTimes(3);
expect(eventsSpy).toHaveBeenCalledWith('mouseover', jasmine.any(Function), true);
expect(eventsSpy).toHaveBeenCalledWith('click', jasmine.any(Function), true);
expect(eventsSpy).toHaveBeenCalledWith('mouseout', jasmine.any(Function), true);
});
it('should cancel events from mouse after start inspecting', () => {
const inspector = new ComponentInspector();
const mouseEventSpy = jasmine.createSpyObj('e', ['stopImmediatePropagation', 'preventDefault']);
inspector.startInspecting();
inspector.cancelEvent(mouseEventSpy);
expect(mouseEventSpy.stopImmediatePropagation).toHaveBeenCalledTimes(1);
expect(mouseEventSpy.preventDefault).toHaveBeenCalledTimes(1);
});
it('should always retrieve the same forest hook', () => {
expect(initializeOrGetDirectiveForestHooks()).toBe(initializeOrGetDirectiveForestHooks());
});
});
| {
"end_byte": 2160,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/component-inspector/component-inspector.spec.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/component-inspector/BUILD.bazel_0_1278 | load("//devtools/tools:typescript.bzl", "ts_library", "ts_test_library")
load("//devtools/tools:defaults.bzl", "karma_web_test_suite")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "component-inspector",
srcs = ["component-inspector.ts"],
deps = [
"//devtools/projects/ng-devtools-backend/src/lib:component_tree",
"//devtools/projects/ng-devtools-backend/src/lib:highlighter",
"//devtools/projects/ng-devtools-backend/src/lib:interfaces",
"//devtools/projects/ng-devtools-backend/src/lib/hooks",
"//devtools/projects/protocol",
],
)
karma_web_test_suite(
name = "test",
deps = [":test_lib"],
)
ts_test_library(
name = "test_lib",
srcs = [
"component-inspector.spec.ts",
],
deps = [
":component-inspector",
"//devtools/projects/ng-devtools-backend/src/lib:component_tree",
"//devtools/projects/ng-devtools-backend/src/lib:highlighter",
"//devtools/projects/ng-devtools-backend/src/lib:interfaces",
"//devtools/projects/ng-devtools-backend/src/lib:utils",
"//devtools/projects/ng-devtools-backend/src/lib/hooks",
"//devtools/projects/protocol",
"//packages/core",
"@npm//@types",
],
)
| {
"end_byte": 1278,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/component-inspector/BUILD.bazel"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/state-serializer/object-utils.ts_0_1760 | /**
* @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 {unwrapSignal} from '../utils';
// Intentionally do not include all the prototype (Except for getters and setters)
// because it contains inherited methods (hasOwnProperty, etc.). Also ignore symbols
// because it is tricky to pass a path to a symbol.
//
// We'd have to go through a serialization and deserialization logic
// which will add unnecessary complexity.
export function getKeys(obj: {}): string[] {
if (!obj) {
return [];
}
obj = unwrapSignal(obj);
const properties = Object.getOwnPropertyNames(obj);
// Object.getPrototypeOf can return null, on empty objectwithout prototype for example
const prototypeMembers = Object.getOwnPropertyDescriptors(Object.getPrototypeOf(obj) ?? {});
const ignoreList = ['__proto__'];
const gettersAndSetters = Object.keys(prototypeMembers).filter((methodName) => {
if (ignoreList.includes(methodName)) {
return false;
}
const targetMethod = prototypeMembers[methodName];
return targetMethod.get || targetMethod.set;
});
return properties.concat(gettersAndSetters);
}
/**
* This helper function covers the common scenario as well as the getters and setters
* @param instance The target object
* @param propName The string representation of the target property name
* @returns The Descriptor object of the property
*/
export const getDescriptor = (instance: any, propName: string): PropertyDescriptor | undefined =>
Object.getOwnPropertyDescriptor(instance, propName) ||
Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), propName);
| {
"end_byte": 1760,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/state-serializer/object-utils.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/state-serializer/state-serializer.ts_0_4195 | /**
* @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 {ContainerType, Descriptor, NestedProp, PropType} from 'protocol';
import type {Signal} from '@angular/core';
import {isSignal, unwrapSignal} from '../utils';
import {getKeys} from './object-utils';
import {getPropType} from './prop-type';
import {
createLevelSerializedDescriptor,
createNestedSerializedDescriptor,
createShallowSerializedDescriptor,
PropertyData,
} from './serialized-descriptor-factory';
// todo(aleksanderbodurri) pull this out of this file
const METADATA_PROPERTY_NAME = '__ngContext__';
const ignoreList = new Set([METADATA_PROPERTY_NAME, '__ngSimpleChanges__']);
const MAX_LEVEL = 1;
function nestedSerializer(
instance: any,
propName: string | number,
nodes: NestedProp[],
isReadonly: boolean,
currentLevel = 0,
level = MAX_LEVEL,
): Descriptor {
instance = unwrapSignal(instance);
const serializableInstance = instance[propName];
const propData: PropertyData = {
prop: serializableInstance,
type: getPropType(serializableInstance),
containerType: getContainerType(serializableInstance),
};
if (currentLevel < level) {
const continuation = (
instance: any,
propName: string | number,
isReadonly: boolean,
nestedLevel?: number,
_?: number,
) => {
const nodeChildren = nodes.find((v) => v.name === propName)?.children ?? [];
return nestedSerializer(instance, propName, nodeChildren, isReadonly, nestedLevel, level);
};
return levelSerializer(instance, propName, isReadonly, currentLevel, level, continuation);
}
switch (propData.type) {
case PropType.Array:
case PropType.Object:
return createNestedSerializedDescriptor(
instance,
propName,
propData,
{level, currentLevel},
nodes,
nestedSerializer,
);
default:
return createShallowSerializedDescriptor(instance, propName, propData, isReadonly);
}
}
function levelSerializer(
instance: any,
propName: string | number,
isReadonly: boolean,
currentLevel = 0,
level = MAX_LEVEL,
continuation = levelSerializer,
): Descriptor {
const serializableInstance = instance[propName];
const propData: PropertyData = {
prop: serializableInstance,
type: getPropType(serializableInstance),
containerType: getContainerType(serializableInstance),
};
switch (propData.type) {
case PropType.Array:
case PropType.Object:
return createLevelSerializedDescriptor(
instance,
propName,
propData,
{level, currentLevel},
continuation,
);
default:
return createShallowSerializedDescriptor(instance, propName, propData, isReadonly);
}
}
export function serializeDirectiveState(instance: object): Record<string, Descriptor> {
const result: Record<string, Descriptor> = {};
const value = unwrapSignal(instance);
const isReadonly = isSignal(instance);
getKeys(value).forEach((prop) => {
if (typeof prop === 'string' && ignoreList.has(prop)) {
return;
}
result[prop] = levelSerializer(value, prop, isReadonly, 0, 0);
});
return result;
}
export function deeplySerializeSelectedProperties(
instance: object,
props: NestedProp[],
): Record<string, Descriptor> {
const result: Record<string, Descriptor> = {};
const isReadonly = isSignal(instance);
getKeys(instance).forEach((prop) => {
if (ignoreList.has(prop)) {
return;
}
const childrenProps = props.find((v) => v.name === prop)?.children;
if (!childrenProps) {
result[prop] = levelSerializer(instance, prop, isReadonly);
} else {
result[prop] = nestedSerializer(instance, prop, childrenProps, isReadonly);
}
});
return result;
}
function getContainerType(instance: unknown): ContainerType {
if (isSignal(instance)) {
return isWritableSignal(instance) ? 'WritableSignal' : 'ReadonlySignal';
}
return null;
}
function isWritableSignal(s: any): boolean {
return typeof s['set'] === 'function';
}
| {
"end_byte": 4195,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/state-serializer/state-serializer.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/state-serializer/prop-type.spec.ts_0_2068 | /**
* @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 {PropType} from 'protocol';
import {getPropType} from './prop-type';
describe('getPropType', () => {
const testCases = [
{
expression: 123,
propType: PropType.Number,
propTypeName: 'Number',
},
{
expression: 'John Lennon',
propType: PropType.String,
propTypeName: 'String',
},
{
expression: null,
propType: PropType.Null,
propTypeName: 'Null',
},
{
expression: undefined,
propType: PropType.Undefined,
propTypeName: 'Undefined',
},
{
expression: Symbol.iterator,
propType: PropType.Symbol,
propTypeName: 'Symbol',
},
{
expression: true,
propType: PropType.Boolean,
propTypeName: 'Boolean',
},
{
expression: 123n,
propType: PropType.BigInt,
propTypeName: 'BigInt',
},
{
expression: Math.random,
propType: PropType.Function,
propTypeName: 'Function',
},
{
expression: Math,
propType: PropType.Object,
propTypeName: 'Object',
},
{
expression: new Date(),
propType: PropType.Date,
propTypeName: 'Date',
},
{
expression: ['John', 40],
propType: PropType.Array,
propTypeName: 'Array',
},
{
expression: new Set([1, 2, 3, 4, 5]),
propType: PropType.Set,
propTypeName: 'Set',
},
{
expression: new Map<unknown, unknown>([
['name', 'John'],
['age', 40],
[{id: 123}, undefined],
]),
propType: PropType.Map,
propTypeName: 'Map',
},
];
for (const {expression, propType, propTypeName} of testCases) {
it(`should determine ${String(expression)} as PropType:${propTypeName}(${propType})`, () => {
const actual = getPropType(expression);
expect(actual).toBe(actual);
});
}
});
| {
"end_byte": 2068,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/state-serializer/prop-type.spec.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/state-serializer/prop-type.ts_0_1520 | /**
* @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 {PropType} from 'protocol';
import {isSignal} from '../utils';
const commonTypes = {
boolean: PropType.Boolean,
bigint: PropType.BigInt,
function: PropType.Function,
number: PropType.Number,
string: PropType.String,
symbol: PropType.Symbol,
};
/**
* Determines the devtools-PropType of a component's property
* @param prop component's property
* @returns PropType
* @see `devtools/projects/protocol`
*/
export const getPropType = (prop: unknown): PropType => {
if (isSignal(prop)) {
prop = prop();
}
if (prop === undefined) {
return PropType.Undefined;
}
if (prop === null) {
return PropType.Null;
}
if (prop instanceof HTMLElement) {
return PropType.HTMLNode;
}
const type = typeof prop;
if (type in commonTypes) {
return commonTypes[type as keyof typeof commonTypes];
}
if (type === 'object') {
if (Array.isArray(prop)) {
return PropType.Array;
} else if (prop instanceof Set) {
return PropType.Set;
} else if (prop instanceof Map) {
return PropType.Map;
} else if (Object.prototype.toString.call(prop) === '[object Date]') {
return PropType.Date;
} else if (prop instanceof Node) {
return PropType.HTMLNode;
} else {
return PropType.Object;
}
}
return PropType.Unknown;
};
| {
"end_byte": 1520,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/state-serializer/prop-type.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/state-serializer/serialized-descriptor-factory.ts_0_7459 | /**
* @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 {ContainerType, Descriptor, NestedProp, PropType} from 'protocol';
import {isSignal, unwrapSignal} from '../utils';
import {getDescriptor, getKeys} from './object-utils';
// todo(aleksanderbodurri) pull this out of this file
const METADATA_PROPERTY_NAME = '__ngContext__';
type NestedType = PropType.Array | PropType.Object;
export interface CompositeType {
type: Extract<PropType, NestedType>;
prop: any;
containerType: ContainerType;
}
export interface TerminalType {
type: Exclude<PropType, NestedType>;
prop: any;
containerType: ContainerType;
}
export type PropertyData = TerminalType | CompositeType;
export type Formatter<Result> = {
[key in PropType]: (data: any) => Result;
};
interface LevelOptions {
currentLevel: number;
level?: number;
}
const serializable: Set<PropType> = new Set([
PropType.Boolean,
PropType.String,
PropType.Null,
PropType.Number,
PropType.Object,
PropType.Undefined,
PropType.Unknown,
]);
const typeToDescriptorPreview: Formatter<string> = {
[PropType.Array]: (prop: Array<unknown>) => `Array(${prop.length})`,
[PropType.Set]: (prop: Set<unknown>) => `Set(${prop.size})`,
[PropType.Map]: (prop: Map<unknown, unknown>) => `Map(${prop.size})`,
[PropType.BigInt]: (prop: bigint) => truncate(prop.toString()),
[PropType.Boolean]: (prop: boolean) => truncate(prop.toString()),
[PropType.String]: (prop: string) => `"${prop}"`,
[PropType.Function]: (prop: Function) => `${prop.name}(...)`,
[PropType.HTMLNode]: (prop: Node) => prop.constructor.name,
[PropType.Null]: (_: null) => 'null',
[PropType.Number]: (prop: any) => parseInt(prop, 10).toString(),
[PropType.Object]: (prop: Object) => (getKeys(prop).length > 0 ? '{...}' : '{}'),
[PropType.Symbol]: (symbol: symbol) => `Symbol(${symbol.description})`,
[PropType.Undefined]: (_: undefined) => 'undefined',
[PropType.Date]: (prop: unknown) => {
if (prop instanceof Date) {
return `Date(${new Date(prop).toISOString()})`;
}
return `${prop}`;
},
[PropType.Unknown]: (_: any) => 'unknown',
};
type Key = string | number;
type NestedSerializerFn = (
instance: any,
propName: string | number,
nodes: NestedProp[],
isReadonly: boolean,
currentLevel: number,
level?: number,
) => Descriptor;
const ignoreList: Set<Key> = new Set([METADATA_PROPERTY_NAME, '__ngSimpleChanges__']);
const shallowPropTypeToTreeMetaData: Record<
Exclude<PropType, NestedType>,
{editable: boolean; expandable: boolean}
> = {
[PropType.String]: {
editable: true,
expandable: false,
},
[PropType.BigInt]: {
editable: false,
expandable: false,
},
[PropType.Boolean]: {
editable: true,
expandable: false,
},
[PropType.Number]: {
editable: true,
expandable: false,
},
[PropType.Date]: {
editable: false,
expandable: false,
},
[PropType.Null]: {
editable: true,
expandable: false,
},
[PropType.Undefined]: {
editable: true,
expandable: false,
},
[PropType.Symbol]: {
editable: false,
expandable: false,
},
[PropType.Function]: {
editable: false,
expandable: false,
},
[PropType.HTMLNode]: {
editable: false,
expandable: false,
},
[PropType.Unknown]: {
editable: false,
expandable: false,
},
[PropType.Set]: {
editable: false,
expandable: false,
},
[PropType.Map]: {
editable: false,
expandable: false,
},
};
const isEditable = (
descriptor: PropertyDescriptor | undefined,
propName: string | number,
propData: TerminalType,
isGetterOrSetter: boolean,
) => {
if (propData.containerType === 'ReadonlySignal') {
return false;
}
if (typeof propName === 'symbol') {
return false;
}
if (isGetterOrSetter) {
return false;
}
if (descriptor?.writable === false) {
return false;
}
return shallowPropTypeToTreeMetaData[propData.type].editable;
};
const isGetterOrSetter = (descriptor: any): boolean =>
(descriptor?.set || descriptor?.get) && !('value' in descriptor);
const getPreview = (propData: TerminalType | CompositeType, isGetterOrSetter: boolean) => {
if (propData.containerType === 'ReadonlySignal') {
return `Readonly Signal(${typeToDescriptorPreview[propData.type](propData.prop())})`;
} else if (propData.containerType === 'WritableSignal') {
return `Signal(${typeToDescriptorPreview[propData.type](propData.prop())})`;
}
return !isGetterOrSetter
? typeToDescriptorPreview[propData.type](propData.prop)
: typeToDescriptorPreview[PropType.Function]({name: ''});
};
export function createShallowSerializedDescriptor(
instance: any,
propName: string | number,
propData: TerminalType,
isReadonly: boolean,
): Descriptor {
const {type, containerType} = propData;
const descriptor = getDescriptor(instance, propName as string);
const getterOrSetter: boolean = isGetterOrSetter(descriptor);
const shallowSerializedDescriptor: Descriptor = {
type,
expandable: shallowPropTypeToTreeMetaData[type].expandable,
editable: isEditable(descriptor, propName, propData, getterOrSetter) && !isReadonly,
preview: getPreview(propData, getterOrSetter),
containerType,
};
if (propData.prop !== undefined && serializable.has(type)) {
shallowSerializedDescriptor.value = unwrapSignal(propData.prop);
}
return shallowSerializedDescriptor;
}
export function createLevelSerializedDescriptor(
instance: {},
propName: string | number,
propData: CompositeType,
levelOptions: LevelOptions,
continuation: (
instance: any,
propName: string | number,
isReadonly: boolean,
level?: number,
max?: number,
) => Descriptor,
): Descriptor {
const {type, prop, containerType} = propData;
const descriptor = getDescriptor(instance, propName as string);
const getterOrSetter: boolean = isGetterOrSetter(descriptor);
const levelSerializedDescriptor: Descriptor = {
type,
editable: false,
expandable: !getterOrSetter && getKeys(prop).length > 0,
preview: getPreview(propData, getterOrSetter),
containerType,
};
if (levelOptions.level !== undefined && levelOptions.currentLevel < levelOptions.level) {
const value = getLevelDescriptorValue(propData, levelOptions, continuation);
if (value !== undefined) {
levelSerializedDescriptor.value = value;
}
}
return levelSerializedDescriptor;
}
export function createNestedSerializedDescriptor(
instance: {},
propName: string | number,
propData: CompositeType,
levelOptions: LevelOptions,
nodes: NestedProp[],
nestedSerializer: NestedSerializerFn,
): Descriptor {
const {type, prop, containerType} = propData;
const descriptor = getDescriptor(instance, propName as string);
const getterOrSetter: boolean = isGetterOrSetter(descriptor);
const nestedSerializedDescriptor: Descriptor = {
type,
editable: false,
expandable: !getterOrSetter && getKeys(prop).length > 0,
preview: getPreview(propData, getterOrSetter),
containerType,
};
if (nodes?.length) {
const value = getNestedDescriptorValue(propData, levelOptions, nodes, nestedSerializer);
if (value !== undefined) {
nestedSerializedDescriptor.value = value;
}
}
return nestedSerializedDescriptor;
} | {
"end_byte": 7459,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/state-serializer/serialized-descriptor-factory.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/state-serializer/serialized-descriptor-factory.ts_7461_9552 | function getNestedDescriptorValue(
propData: CompositeType,
levelOptions: LevelOptions,
nodes: NestedProp[],
nestedSerializer: NestedSerializerFn,
) {
const {type, prop} = propData;
const {currentLevel} = levelOptions;
const value = unwrapSignal(prop);
switch (type) {
case PropType.Array:
return nodes.map((nestedProp) =>
nestedSerializer(value, nestedProp.name, nestedProp.children, false, currentLevel + 1),
);
case PropType.Object:
return nodes.reduce(
(accumulator, nestedProp) => {
if (prop.hasOwnProperty(nestedProp.name) && !ignoreList.has(nestedProp.name)) {
accumulator[nestedProp.name] = nestedSerializer(
value,
nestedProp.name,
nestedProp.children,
false,
currentLevel + 1,
);
}
return accumulator;
},
{} as Record<string, Descriptor>,
);
}
}
function getLevelDescriptorValue(
propData: CompositeType,
levelOptions: LevelOptions,
continuation: (
instance: any,
propName: string | number,
isReadonly: boolean,
level?: number,
max?: number,
) => Descriptor,
) {
const {type, prop} = propData;
const {currentLevel, level} = levelOptions;
const value = unwrapSignal(prop);
const isReadonly = isSignal(prop);
switch (type) {
case PropType.Array:
return value.map((_: any, idx: number) =>
continuation(value, idx, isReadonly, currentLevel + 1, level),
);
case PropType.Object:
return getKeys(value).reduce(
(accumulator, propName) => {
if (!ignoreList.has(propName)) {
accumulator[propName] = continuation(
value,
propName,
isReadonly,
currentLevel + 1,
level,
);
}
return accumulator;
},
{} as Record<string, Descriptor>,
);
}
}
function truncate(str: string, max = 20): string {
return str.length > max ? str.substring(0, max) + '...' : str;
} | {
"end_byte": 9552,
"start_byte": 7461,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/state-serializer/serialized-descriptor-factory.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/state-serializer/BUILD.bazel_0_820 | load("//devtools/tools:typescript.bzl", "ts_test_library")
load("//devtools/tools:ng_module.bzl", "ng_module")
load("//devtools/tools:defaults.bzl", "karma_web_test_suite")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "state-serializer",
srcs = glob(
include = ["*.ts"],
exclude = ["*.spec.ts"],
),
deps = [
"//devtools/projects/ng-devtools-backend/src/lib/directive-forest",
"//devtools/projects/protocol",
],
)
karma_web_test_suite(
name = "test",
deps = [
":test_lib",
],
)
ts_test_library(
name = "test_lib",
srcs = [
"prop-type.spec.ts",
"state-serializer.spec.ts",
],
deps = [
":state-serializer",
"//devtools/projects/protocol",
"@npm//@types",
],
)
| {
"end_byte": 820,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/state-serializer/BUILD.bazel"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/state-serializer/state-serializer.spec.ts_0_1355 | /**
* @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 {PropType} from 'protocol';
import {getDescriptor, getKeys} from './object-utils';
import {deeplySerializeSelectedProperties} from './state-serializer';
const QUERY_1_1: any[] = [];
const QUERY_1_2 = [
{
name: 'nested',
children: [
{
name: 'arr',
children: [
{
name: 2,
children: [
{
name: 0,
children: [
{
name: 'two',
children: [],
},
],
},
],
},
{
name: 3,
children: [
{
name: 0,
children: [],
},
],
},
],
},
],
},
];
const dir1 = {
one: 1,
nested: {
arr: [
{
obj: 1,
},
2,
[
{
two: 1,
},
],
new Set(['foo', 'bar']),
],
},
};
const dir2 = {
nested: {
arr: [
{
obj: 1,
},
2,
[
{
two: 1,
},
],
],
},
}; | {
"end_byte": 1355,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/state-serializer/state-serializer.spec.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/state-serializer/state-serializer.spec.ts_1357_10778 | describe('deeplySerializeSelectedProperties', () => {
it('should work with empty queries', () => {
const result = deeplySerializeSelectedProperties(dir1, QUERY_1_1);
expect(result).toEqual({
one: {
type: PropType.Number,
expandable: false,
editable: true,
preview: '1',
value: 1,
containerType: null,
},
nested: {
type: PropType.Object,
editable: false,
expandable: true,
preview: '{...}',
value: {
arr: {
type: PropType.Array,
expandable: true,
editable: false,
preview: 'Array(4)',
containerType: null,
},
},
containerType: null,
},
});
});
it('should collect not specified but existing props below level', () => {
const result = deeplySerializeSelectedProperties(dir1, QUERY_1_2);
expect(result).toEqual({
one: {
type: PropType.Number,
expandable: false,
editable: true,
preview: '1',
value: 1,
containerType: null,
},
nested: {
type: PropType.Object,
editable: false,
expandable: true,
preview: '{...}',
value: {
arr: {
type: PropType.Array,
editable: false,
expandable: true,
preview: 'Array(4)',
value: [
{
type: PropType.Array,
editable: false,
expandable: true,
preview: 'Array(1)',
value: [
{
type: PropType.Object,
editable: false,
expandable: true,
preview: '{...}',
value: {
two: {
type: PropType.Number,
expandable: false,
editable: true,
preview: '1',
value: 1,
containerType: null,
},
},
containerType: null,
},
],
containerType: null,
},
{
type: PropType.Set,
editable: false,
expandable: false,
preview: 'Set(2)',
containerType: null,
},
],
containerType: null,
},
},
containerType: null,
},
});
});
it('should handle deletions even of the query asks for such props', () => {
const result = deeplySerializeSelectedProperties(dir2, [
{
name: 'one',
children: [],
},
{
name: 'nested',
children: [],
},
]);
expect(result).toEqual({
nested: {
type: PropType.Object,
editable: false,
expandable: true,
preview: '{...}',
value: {
arr: {
type: PropType.Array,
editable: false,
expandable: true,
preview: 'Array(3)',
containerType: null,
},
},
containerType: null,
},
});
});
it('should work with getters with specified query', () => {
const result = deeplySerializeSelectedProperties(
{
get foo(): any {
return {
baz: {
qux: 3,
},
};
},
},
[
{
name: 'foo',
children: [
{
name: 'baz',
children: [],
},
],
},
],
);
expect(result).toEqual({
foo: {
type: PropType.Object,
editable: false,
expandable: false,
preview: '(...)',
value: {
baz: {
type: PropType.Object,
editable: false,
expandable: true,
preview: '{...}',
containerType: null,
},
},
containerType: null,
},
});
});
it('should work with getters without specified query', () => {
const result = deeplySerializeSelectedProperties(
{
get foo(): any {
return {
baz: {
qux: {
cos: 3,
},
},
};
},
},
[],
);
expect(result).toEqual({
foo: {
type: PropType.Object,
editable: false,
expandable: false,
preview: '(...)',
value: {
baz: {
type: PropType.Object,
editable: false,
expandable: true,
preview: '{...}',
containerType: null,
},
},
containerType: null,
},
});
});
it('both getters and setters should be readonly', () => {
const result = deeplySerializeSelectedProperties(
{
get foo(): number {
return 42;
},
get bar(): number {
return 42;
},
set bar(val: number) {},
},
[],
);
// Neither getter and setter is editable
expect(result).toEqual({
foo: {
type: PropType.Number,
expandable: false,
editable: false,
preview: '(...)',
value: 42,
containerType: null,
},
bar: {
type: PropType.Number,
expandable: false,
editable: false,
preview: '(...)',
value: 42,
containerType: null,
},
});
});
it('should return the precise path requested', () => {
const result = deeplySerializeSelectedProperties(
{
state: {
nested: {
props: {
foo: 1,
bar: 2,
},
[Symbol(3)](): number {
return 1.618;
},
get foo(): number {
return 42;
},
},
},
},
[
{
name: 'state',
children: [
{
name: 'nested',
children: [
{
name: 'props',
children: [
{
name: 'foo',
children: [],
},
{
name: 'bar',
children: [],
},
],
},
{
name: 'foo',
children: [],
},
],
},
],
},
],
);
expect(result).toEqual({
state: {
type: PropType.Object,
editable: false,
expandable: true,
preview: '{...}',
value: {
nested: {
type: PropType.Object,
editable: false,
expandable: true,
preview: '{...}',
value: {
props: {
type: PropType.Object,
editable: false,
expandable: true,
preview: '{...}',
value: {
foo: {
type: PropType.Number,
expandable: false,
editable: true,
preview: '1',
value: 1,
containerType: null,
},
bar: {
type: PropType.Number,
expandable: false,
editable: true,
preview: '2',
value: 2,
containerType: null,
},
},
containerType: null,
},
foo: {
type: PropType.Number,
expandable: false,
editable: false,
preview: '(...)',
value: 42,
containerType: null,
},
},
containerType: null,
},
},
containerType: null,
},
});
});
it('both setter and getter would get a (...) as preview', () => {
const result = deeplySerializeSelectedProperties(
{
set foo(_: any) {},
get bar(): Object {
return {foo: 1};
},
},
[],
);
expect(result).toEqual({
foo: {
type: PropType.Undefined,
editable: false,
expandable: false,
preview: '(...)',
containerType: null,
},
bar: {
type: PropType.Object,
editable: false,
expandable: false,
preview: '(...)',
containerType: null,
value: {
foo: {
type: PropType.Number,
expandable: false,
editable: true,
preview: '1',
value: 1,
containerType: null,
},
},
},
});
});
it('should preview the undefined values correctly', () => {
const result = deeplySerializeSelectedProperties({obj: undefined}, []);
expect(result).toEqual({
obj: {
type: PropType.Undefined,
editable: true,
expandable: false,
preview: 'undefined',
containerType: null,
},
});
}); | {
"end_byte": 10778,
"start_byte": 1357,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/state-serializer/state-serializer.spec.ts"
} |
angular/devtools/projects/ng-devtools-backend/src/lib/state-serializer/state-serializer.spec.ts_10782_13063 | it('getDescriptor should get the descriptors for both getters and setters correctly from the prototype', () => {
const instance = {
__proto__: {
get foo(): number {
return 42;
},
set bar(newNum: number) {},
get baz(): number {
return 42;
},
set baz(newNum: number) {},
},
};
const descriptorFoo = getDescriptor(instance, 'foo');
expect(descriptorFoo).not.toBeNull();
expect(descriptorFoo!.get).not.toBeNull();
expect(descriptorFoo!.set).toBeUndefined();
expect(descriptorFoo!.value).toBeUndefined();
expect(descriptorFoo!.enumerable).toBe(true);
expect(descriptorFoo!.configurable).toBe(true);
const descriptorBar = getDescriptor(instance, 'bar');
expect(descriptorBar).not.toBeNull();
expect(descriptorBar!.get).toBeUndefined();
expect(descriptorBar!.set).not.toBeNull();
expect(descriptorBar!.value).toBeUndefined();
expect(descriptorBar!.enumerable).toBe(true);
expect(descriptorBar!.configurable).toBe(true);
const descriptorBaz = getDescriptor(instance, 'baz');
expect(descriptorBaz).not.toBeNull();
expect(descriptorBaz!.get).not.toBeNull();
expect(descriptorBaz!.set).not.toBeNull();
expect(descriptorBaz!.value).toBeUndefined();
expect(descriptorBaz!.enumerable).toBe(true);
expect(descriptorBaz!.configurable).toBe(true);
});
it('getKeys should all keys including getters and setters', () => {
const instance = {
baz: 2,
__proto__: {
get foo(): number {
return 42;
},
set foo(newNum: number) {},
set bar(newNum: number) {},
},
};
expect(getKeys(instance)).toEqual(['baz', 'foo', 'bar']);
});
it('getKeys should not throw on empty object without prototype', () => {
// creates an object without a prototype
const instance = Object.create(null);
expect(getKeys(instance)).toEqual([]);
});
it('getKeys would ignore getters and setters for "__proto__"', () => {
const instance = {
baz: 2,
__proto__: {
set __proto__(newObj: Object) {},
get __proto__(): Object {
return {};
},
},
};
expect(getKeys(instance)).toEqual(['baz']);
});
}); | {
"end_byte": 13063,
"start_byte": 10782,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools-backend/src/lib/state-serializer/state-serializer.spec.ts"
} |
angular/devtools/projects/demo-no-zone/BUILD.bazel_0_54 | package(default_visibility = ["//visibility:public"])
| {
"end_byte": 54,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-no-zone/BUILD.bazel"
} |
angular/devtools/projects/demo-no-zone/src/index.html_0_400 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Demo No Zone</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<app-root></app-root>
<script src="./angular/packages/zone.js/bundles/zone.umd.js"></script>
<script type="module" src="./bundle/main.js"></script>
</body>
</html>
| {
"end_byte": 400,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-no-zone/src/index.html"
} |
angular/devtools/projects/demo-no-zone/src/main.ts_0_445 | /**
* @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 {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './app/app.module';
platformBrowserDynamic()
.bootstrapModule(AppModule, {
ngZone: 'noop',
})
.catch((err) => console.error(err));
| {
"end_byte": 445,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-no-zone/src/main.ts"
} |
angular/devtools/projects/demo-no-zone/src/styles.css_0_80 | /* You can add global styles to this file, and also import other style files */
| {
"end_byte": 80,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-no-zone/src/styles.css"
} |
angular/devtools/projects/demo-no-zone/src/BUILD.bazel_0_1302 | load("//devtools/tools:ng_module.bzl", "ng_module")
load("@build_bazel_rules_nodejs//:index.bzl", "pkg_web")
load("//tools:defaults.bzl", "esbuild", "http_server")
package(default_visibility = ["//:__subpackages__"])
ng_module(
name = "src",
srcs = ["main.ts"],
deps = [
"//devtools/projects/demo-no-zone/src/app",
"//packages/common",
"//packages/core",
"//packages/platform-browser",
"//packages/platform-browser-dynamic",
"@npm//@types",
"@npm//rxjs",
],
)
esbuild(
name = "bundle",
config = "//devtools/tools/esbuild:esbuild_config_esm",
entry_points = [":main.ts"],
platform = "browser",
splitting = False,
target = "es2016",
deps = [":src"],
)
exports_files([
"index.html",
"styles.css",
])
filegroup(
name = "dev_app_static_files",
srcs = [
":index.html",
":styles.css",
"//packages/zone.js/bundles:zone.umd.js",
],
)
pkg_web(
name = "devapp",
srcs = [
":bundle",
":dev_app_static_files",
],
)
http_server(
name = "devserver",
srcs = [":dev_app_static_files"],
additional_root_paths = ["angular/devtools/projects/demo-no-zone/src/devapp"],
tags = ["manual"],
deps = [
":devapp",
],
)
| {
"end_byte": 1302,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-no-zone/src/BUILD.bazel"
} |
angular/devtools/projects/demo-no-zone/src/app/app.component.html_0_73 | <h1>{{ counter }}</h1>
<button (click)="increment()">Increment</button>
| {
"end_byte": 73,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-no-zone/src/app/app.component.html"
} |
angular/devtools/projects/demo-no-zone/src/app/app.module.ts_0_496 | /**
* @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 {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppComponent} from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
| {
"end_byte": 496,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-no-zone/src/app/app.module.ts"
} |
angular/devtools/projects/demo-no-zone/src/app/app.component.ts_0_537 | /**
* @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 {ChangeDetectorRef, Component} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
standalone: false,
})
export class AppComponent {
counter = 0;
constructor(private _cd: ChangeDetectorRef) {}
increment(): void {
this.counter++;
this._cd.detectChanges();
}
}
| {
"end_byte": 537,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-no-zone/src/app/app.component.ts"
} |
angular/devtools/projects/demo-no-zone/src/app/BUILD.bazel_0_373 | load("//devtools/tools:ng_module.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "app",
srcs = glob(
include = ["*.ts"],
),
angular_assets = ["app.component.html"],
deps = [
"//packages/common",
"//packages/core",
"//packages/platform-browser",
"@npm//rxjs",
],
)
| {
"end_byte": 373,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-no-zone/src/app/BUILD.bazel"
} |
angular/devtools/projects/demo-standalone/BUILD.bazel_0_54 | package(default_visibility = ["//visibility:public"])
| {
"end_byte": 54,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/BUILD.bazel"
} |
angular/devtools/projects/demo-standalone/src/index.html_0_635 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>AngularDevtools</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="assets/icon16.png" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<div>
<app-root></app-root>
</div>
<script src="./angular/packages/zone.js/bundles/zone.umd.js"></script>
<script type="module" src="./bundle/main.js"></script>
</body>
</html>
| {
"end_byte": 635,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/index.html"
} |
angular/devtools/projects/demo-standalone/src/main.ts_0_1318 | /**
* @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 {bootstrapApplication} from '@angular/platform-browser';
import {provideAnimations} from '@angular/platform-browser/animations';
import {provideRouter} from '@angular/router';
import {ApplicationEnvironment, ApplicationOperations} from 'ng-devtools';
import {DemoApplicationEnvironment} from '../../../src/demo-application-environment';
import {DemoApplicationOperations} from '../../../src/demo-application-operations';
import {AppComponent} from './app/app.component';
bootstrapApplication(AppComponent, {
providers: [
provideAnimations(),
provideRouter([
{
path: '',
loadComponent: () =>
import('./app/devtools-app/devtools-app.component').then((m) => m.DemoDevToolsComponent),
pathMatch: 'full',
},
{
path: 'demo-app',
loadChildren: () => import('./app/demo-app/demo-app.component').then((m) => m.ROUTES),
},
]),
{
provide: ApplicationOperations,
useClass: DemoApplicationOperations,
},
{
provide: ApplicationEnvironment,
useClass: DemoApplicationEnvironment,
},
],
});
| {
"end_byte": 1318,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/main.ts"
} |
angular/devtools/projects/demo-standalone/src/styles.scss_0_41 | @use '../../../styles.scss' as devtools;
| {
"end_byte": 41,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/styles.scss"
} |
angular/devtools/projects/demo-standalone/src/BUILD.bazel_0_2023 | load("//devtools/tools:ng_module.bzl", "ng_module")
load("@io_bazel_rules_sass//:defs.bzl", "sass_binary")
load("@build_bazel_rules_nodejs//:index.bzl", "pkg_web")
load("//tools:defaults.bzl", "esbuild", "http_server")
load("//devtools/tools/esbuild:index.bzl", "LINKER_PROCESSED_FW_PACKAGES")
package(default_visibility = ["//visibility:public"])
sass_binary(
name = "demo_styles",
src = "styles.scss",
include_paths = ["external/npm/node_modules"],
sourcemap = False,
deps = ["//devtools:global_styles"],
)
sass_binary(
name = "firefox_styles",
src = "styles/firefox_styles.scss",
)
sass_binary(
name = "chrome_styles",
src = "styles/chrome_styles.scss",
)
ng_module(
name = "demo",
srcs = ["main.ts"],
deps = [
"//devtools/projects/demo-standalone/src/app",
"//devtools/src:demo_application_environment",
"//devtools/src:demo_application_operations",
"//packages/common",
"//packages/common/http",
"//packages/core",
"//packages/core/src/util",
"//packages/platform-browser",
"@npm//@types",
"@npm//rxjs",
],
)
esbuild(
name = "bundle",
config = "//devtools/tools/esbuild:esbuild_config_esm",
entry_points = [":main.ts"],
platform = "browser",
splitting = True,
target = "es2016",
deps = LINKER_PROCESSED_FW_PACKAGES + [":demo"],
)
exports_files(["index.html"])
filegroup(
name = "dev_app_static_files",
srcs = [
":chrome_styles",
":demo_styles",
":firefox_styles",
":index.html",
"//packages/zone.js/bundles:zone.umd.js",
],
)
pkg_web(
name = "devapp",
srcs = [":dev_app_static_files"] + [
":bundle",
"@npm//:node_modules/tslib/tslib.js",
],
)
http_server(
name = "devserver",
srcs = [":dev_app_static_files"],
additional_root_paths = ["angular/devtools/projects/demo-standalone/src/devapp"],
tags = ["manual"],
deps = [
":devapp",
],
)
| {
"end_byte": 2023,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/BUILD.bazel"
} |
angular/devtools/projects/demo-standalone/src/app/app.component.ts_0_504 | /**
* @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 '@angular/core';
import {Router, RouterOutlet} from '@angular/router';
@Component({
selector: 'app-root',
template: `<router-outlet></router-outlet>`,
standalone: true,
imports: [RouterOutlet],
})
export class AppComponent {
constructor(public router: Router) {}
}
| {
"end_byte": 504,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/app.component.ts"
} |
angular/devtools/projects/demo-standalone/src/app/BUILD.bazel_0_527 | load("//devtools/tools:ng_module.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "app",
srcs = [
"app.component.ts",
],
deps = [
"//devtools/projects/demo-standalone/src/app/demo-app",
"//devtools/projects/demo-standalone/src/app/devtools-app",
"//devtools/projects/ng-devtools",
"//packages/core",
"//packages/platform-browser",
"//packages/platform-browser/animations",
"//packages/router",
],
)
| {
"end_byte": 527,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/BUILD.bazel"
} |
angular/devtools/projects/demo-standalone/src/app/devtools-app/devtools-app.component.ts_0_1625 | /**
* @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, ElementRef, ViewChild} from '@angular/core';
import {Events, MessageBus, PriorityAwareMessageBus} from 'protocol';
import {IFrameMessageBus} from '../../../../../src/iframe-message-bus';
import {DevToolsComponent} from 'ng-devtools';
import {FrameManager} from '../../../../../projects/ng-devtools/src/lib/frame_manager';
@Component({
standalone: true,
imports: [DevToolsComponent],
providers: [
{provide: FrameManager, useFactory: () => FrameManager.initialize(null)},
{
provide: MessageBus,
useFactory(): MessageBus<Events> {
return new PriorityAwareMessageBus(
new IFrameMessageBus(
'angular-devtools',
'angular-devtools-backend',
// tslint:disable-next-line: no-non-null-assertion
() => (document.querySelector('#sample-app') as HTMLIFrameElement).contentWindow!,
),
);
},
},
],
styles: [
`
iframe {
height: 340px;
width: 100%;
border: 0;
}
.devtools-wrapper {
height: calc(100vh - 345px);
}
`,
],
template: `
<iframe #ref src="demo-app/todos/app" id="sample-app"></iframe>
<br />
<div class="devtools-wrapper">
<ng-devtools></ng-devtools>
</div>
`,
})
export class DemoDevToolsComponent {
messageBus: IFrameMessageBus | null = null;
@ViewChild('ref') iframe!: ElementRef;
}
| {
"end_byte": 1625,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/devtools-app/devtools-app.component.ts"
} |
angular/devtools/projects/demo-standalone/src/app/devtools-app/BUILD.bazel_0_488 | load("//devtools/tools:ng_module.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "devtools-app",
srcs = ["devtools-app.component.ts"],
deps = [
"//devtools/projects/ng-devtools",
"//devtools/projects/ng-devtools/src/lib:frame_manager",
"//devtools/projects/protocol",
"//devtools/src:iframe_message_bus",
"//packages/common",
"//packages/core",
"//packages/router",
],
)
| {
"end_byte": 488,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/devtools-app/BUILD.bazel"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/zippy.component.ts_0_1010 | /**
* @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, Input} from '@angular/core';
@Component({
selector: 'app-zippy',
standalone: true,
styles: [
`
:host {
user-select: none;
}
header {
max-width: 120px;
border: 1px solid #ccc;
padding-left: 10px;
padding-right: 10px;
cursor: pointer;
}
div {
max-width: 120px;
border-left: 1px solid #ccc;
border-right: 1px solid #ccc;
border-bottom: 1px solid #ccc;
padding: 10px;
}
`,
],
template: `
<section>
<header (click)="visible = !visible">{{ title }}</header>
<div [hidden]="!visible">
<ng-content></ng-content>
</div>
</section>
`,
})
export class ZippyComponent {
@Input() title!: string;
visible = false;
}
| {
"end_byte": 1010,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/zippy.component.ts"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/heavy.component.ts_0_790 | /**
* @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, Input} from '@angular/core';
const fib = (n: number): number => {
if (n === 1 || n === 2) {
return 1;
}
return fib(n - 1) + fib(n - 2);
};
@Component({selector: 'app-heavy', template: `<h1>{{ calculate() }}</h1>`, standalone: true})
export class HeavyComponent {
@Input()
set foo(_: any) {}
state = {
nested: {
props: {
foo: 1,
bar: 2,
},
[Symbol(3)](): number {
return 1.618;
},
get foo(): number {
return 42;
},
},
};
calculate(): number {
return fib(15);
}
}
| {
"end_byte": 790,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/heavy.component.ts"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/BUILD.bazel_0_1022 | load("//devtools/tools:ng_module.bzl", "ng_module")
load("@io_bazel_rules_sass//:defs.bzl", "sass_binary", "sass_library")
package(default_visibility = ["//visibility:public"])
sass_library(
name = "todo_mvc",
srcs = [
"@npm//:node_modules/todomvc-app-css/index.css",
"@npm//:node_modules/todomvc-common/base.css",
],
)
sass_binary(
name = "demo_app_component_styles",
src = "demo-app.component.scss",
deps = [
":todo_mvc",
],
)
ng_module(
name = "demo-app",
srcs = [
"demo-app.component.ts",
"heavy.component.ts",
"zippy.component.ts",
],
angular_assets = [
"demo-app.component.html",
":demo_app_component_styles",
],
deps = [
"//devtools/projects/demo-standalone/src/app/demo-app/todo",
"//devtools/projects/ng-devtools-backend",
"//devtools/src:zone-unaware-iframe_message_bus",
"//packages/core",
"//packages/elements",
"//packages/router",
],
)
| {
"end_byte": 1022,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/BUILD.bazel"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/demo-app.component.html_0_393 | <router-outlet></router-outlet>
<app-zippy [title]="getTitle()">This is my content</app-zippy>
<app-heavy></app-heavy>
<div #elementReference>HTMLElement</div>
<hr/>
<h2>Signals</h2>
<div>Object Signal: {{objectSignal()|json}}</div>
<div>Object Computed: {{objectComputed()|json}}</div>
<div>Editable Signal: {{primitiveSignal()}}</div>
<div>Primitive computed: {{primitiveComputed()}}</div>
| {
"end_byte": 393,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/demo-app.component.html"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/demo-app.component.ts_0_2451 | /**
* @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 {JsonPipe} from '@angular/common';
import {
Component,
computed,
CUSTOM_ELEMENTS_SCHEMA,
ElementRef,
EventEmitter,
inject,
Injector,
Input,
Output,
signal,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import {createCustomElement} from '@angular/elements';
import {RouterOutlet} from '@angular/router';
import {initializeMessageBus} from 'ng-devtools-backend';
import {ZoneUnawareIFrameMessageBus} from '../../../../../src/zone-unaware-iframe-message-bus';
import {HeavyComponent} from './heavy.component';
import {ZippyComponent} from './zippy.component';
@Component({
selector: 'app-demo-component',
templateUrl: './demo-app.component.html',
styleUrls: ['./demo-app.component.scss'],
encapsulation: ViewEncapsulation.None,
standalone: true,
imports: [HeavyComponent, RouterOutlet, JsonPipe],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class DemoAppComponent {
@ViewChild(ZippyComponent) zippy!: ZippyComponent;
@ViewChild('elementReference') elementRef!: ElementRef;
@Input('input_one') inputOne = 'input one';
@Input() inputTwo = 'input two';
@Output() outputOne = new EventEmitter();
@Output('output_two') outputTwo = new EventEmitter();
primitiveSignal = signal(123);
primitiveComputed = computed(() => this.primitiveSignal() ** 2);
objectSignal = signal({name: 'John', age: 40});
objectComputed = computed(() => {
const original = this.objectSignal();
return {...original, age: original.age + 1};
});
test = [signal(3)];
constructor() {
const el = createCustomElement(ZippyComponent, {injector: inject(Injector)});
customElements.define('app-zippy', el as any);
}
getTitle(): '► Click to expand' | '▼ Click to collapse' {
if (!this.zippy || !this.zippy.visible) {
return '► Click to expand';
}
return '▼ Click to collapse';
}
}
export const ROUTES = [
{
path: '',
component: DemoAppComponent,
children: [
{
path: '',
loadChildren: () => import('./todo/todo-app.component').then((m) => m.ROUTES),
},
],
},
];
initializeMessageBus(
new ZoneUnawareIFrameMessageBus(
'angular-devtools-backend',
'angular-devtools',
() => window.parent,
),
);
| {
"end_byte": 2451,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/demo-app.component.ts"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/demo-app.component.scss_0_118 | @use 'external/npm/node_modules/todomvc-app-css/index.css';
@use 'external/npm/node_modules/todomvc-common/base.css';
| {
"end_byte": 118,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/demo-app.component.scss"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/todo/dialog.component.ts_0_1358 | /**
* @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, Inject} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {MAT_DIALOG_DATA, MatDialogModule, MatDialogRef} from '@angular/material/dialog';
import {MatFormField, MatLabel} from '@angular/material/form-field';
export interface DialogData {
animal: string;
name: string;
}
@Component({
selector: 'app-dialog',
standalone: true,
imports: [MatDialogModule, MatFormField, MatLabel, FormsModule],
template: `
<h1 mat-dialog-title>Hi {{ data.name }}</h1>
<div mat-dialog-content>
<p>What's your favorite animal?</p>
<mat-form-field>
<mat-label>Favorite Animal</mat-label>
<input matInput [(ngModel)]="data.animal" />
</mat-form-field>
</div>
<div mat-dialog-actions>
<button mat-button (click)="onNoClick()">No Thanks</button>
<button mat-button [mat-dialog-close]="data.animal" cdkFocusInitial>Ok</button>
</div>
`,
})
export class DialogComponent {
constructor(
public dialogRef: MatDialogRef<DialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: DialogData,
) {}
onNoClick(): void {
this.dialogRef.close();
}
}
| {
"end_byte": 1358,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/todo/dialog.component.ts"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/todo/BUILD.bazel_0_541 | load("//devtools/tools:ng_module.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "todo",
srcs = [
"dialog.component.ts",
"todo-app.component.ts",
],
deps = [
"//devtools/projects/demo-standalone/src/app/demo-app/todo/about",
"//devtools/projects/demo-standalone/src/app/demo-app/todo/home",
"//packages/common",
"//packages/core",
"//packages/forms",
"//packages/router",
"@npm//@angular/material",
],
)
| {
"end_byte": 541,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/todo/BUILD.bazel"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/todo/todo-app.component.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 {Component} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {MatDialog, MatDialogModule} from '@angular/material/dialog';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import {RouterLink, RouterOutlet} from '@angular/router';
import {DialogComponent} from './dialog.component';
@Component({
selector: 'app-todo-demo',
standalone: true,
imports: [RouterLink, RouterOutlet, MatDialogModule, FormsModule],
styles: [
`
nav {
padding-top: 20px;
padding-bottom: 10px;
a {
margin-right: 15px;
text-decoration: none;
}
}
.dialog-open-button {
border: 1px solid #ccc;
padding: 10px;
margin-right: 20px;
}
`,
],
template: `
<nav>
<a routerLink="/demo-app/todos/app">Todos</a>
<a routerLink="/demo-app/todos/about">About</a>
</nav>
<button class="dialog-open-button" (click)="openDialog()">Open dialog</button>
<router-outlet></router-outlet>
`,
})
export class TodoAppComponent {
name!: string;
animal!: string;
constructor(public dialog: MatDialog) {}
openDialog(): void {
const dialogRef = this.dialog.open(DialogComponent, {
width: '250px',
data: {name: this.name, animal: this.animal},
});
dialogRef.afterClosed().subscribe((result) => {
// tslint:disable-next-line:no-console
console.log('The dialog was closed');
this.animal = result;
});
}
}
export const ROUTES = [
{
path: 'todos',
component: TodoAppComponent,
children: [
{
path: 'app',
loadComponent: () => import('./home/todos.component').then((m) => m.TodosComponent),
},
{
path: 'about',
loadComponent: () => import('./about/about.component').then((m) => m.AboutComponent),
},
{
path: '**',
redirectTo: 'app',
},
],
},
{
path: '**',
redirectTo: 'todos',
},
];
| {
"end_byte": 2257,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/todo/todo-app.component.ts"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/todo/home/todo.component.ts_0_1805 | /**
* @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} from '@angular/common';
import {ChangeDetectionStrategy, Component, EventEmitter, Input, Output} from '@angular/core';
import {TooltipDirective} from './tooltip.directive';
export interface Todo {
id: string;
completed: boolean;
label: string;
}
@Component({
selector: 'app-todo',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [TooltipDirective],
styles: [
`
.destroy {
cursor: pointer;
display: unset !important;
}
`,
],
template: `
<li [class.completed]="todo.completed">
<div class="view" appTooltip>
<input class="toggle" type="checkbox" [checked]="todo.completed" (change)="toggle()" />
<label (dblclick)="enableEditMode()" [style.display]="editMode ? 'none' : 'block'">{{
todo.label
}}</label>
<button class="destroy" (click)="delete.emit(todo)"></button>
</div>
<input
class="edit"
[value]="todo.label"
[style.display]="editMode ? 'block' : 'none'"
(keydown.enter)="completeEdit($any($event.target).value)"
/>
</li>
`,
})
export class TodoComponent {
@Input() todo!: Todo;
@Output() update = new EventEmitter();
@Output() delete = new EventEmitter();
editMode = false;
toggle(): void {
this.todo.completed = !this.todo.completed;
this.update.emit(this.todo);
}
completeEdit(label: string): void {
this.todo.label = label;
this.editMode = false;
this.update.emit(this.todo);
}
enableEditMode(): void {
this.editMode = true;
}
}
| {
"end_byte": 1805,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/todo/home/todo.component.ts"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/todo/home/tooltip.directive.ts_0_752 | /**
* @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 {Directive, HostListener} from '@angular/core';
@Directive({selector: '[appTooltip]', standalone: true})
export class TooltipDirective {
visible = false;
nested = {
child: {
grandchild: {
prop: 1,
},
},
};
constructor() {
// setInterval(() => this.nested.child.grandchild.prop++, 500);
}
@HostListener('click')
handleClick(): void {
this.visible = !this.visible;
if (this.visible) {
(this as any).extraProp = true;
} else {
delete (this as any).extraProp;
}
}
}
| {
"end_byte": 752,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/todo/home/tooltip.directive.ts"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/todo/home/BUILD.bazel_0_382 | load("//devtools/tools:ng_module.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "home",
srcs = [
"sample.pipe.ts",
"todo.component.ts",
"todos.component.ts",
"tooltip.directive.ts",
],
deps = [
"//packages/common",
"//packages/core",
"//packages/router",
],
)
| {
"end_byte": 382,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/todo/home/BUILD.bazel"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/todo/home/sample.pipe.ts_0_537 | /**
* @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 {OnDestroy, Pipe, PipeTransform} from '@angular/core';
@Pipe({name: 'sample', pure: false, standalone: true})
export class SamplePipe implements PipeTransform, OnDestroy {
transform(val: unknown) {
return val;
}
ngOnDestroy(): void {
// tslint:disable-next-line:no-console
console.log('Destroying');
}
}
| {
"end_byte": 537,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/todo/home/sample.pipe.ts"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/todo/home/todos.component.ts_0_4452 | /**
* @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 {NgForOf} from '@angular/common';
import {
ChangeDetectorRef,
Component,
EventEmitter,
OnDestroy,
OnInit,
Output,
Pipe,
PipeTransform,
} from '@angular/core';
import {RouterLink} from '@angular/router';
import {SamplePipe} from './sample.pipe';
import {Todo, TodoComponent} from './todo.component';
import {TooltipDirective} from './tooltip.directive';
export const enum TodoFilter {
All = 'all',
Completed = 'completed',
Active = 'active',
}
@Pipe({pure: false, name: 'todosFilter', standalone: true})
export class TodosFilter implements PipeTransform {
transform(todos: Todo[], filter: TodoFilter): Todo[] {
return (todos || []).filter((t) => {
if (filter === TodoFilter.All) {
return true;
}
if (filter === TodoFilter.Active && !t.completed) {
return true;
}
if (filter === TodoFilter.Completed && t.completed) {
return true;
}
return false;
});
}
}
const fib = (n: number): number => {
if (n === 1 || n === 2) {
return 1;
}
return fib(n - 1) + fib(n - 2);
};
@Component({
selector: 'app-todos',
imports: [RouterLink, TodoComponent, SamplePipe, TodosFilter, TooltipDirective],
standalone: true,
template: `
<a [routerLink]="">Home</a>
<a [routerLink]="">Home</a>
<a [routerLink]="">Home</a>
<p>{{ 'Sample text processed by a pipe' | sample }}</p>
<section class="todoapp">
<header class="header">
<h1>todos</h1>
<input
(keydown.enter)="addTodo(input)"
#input
class="new-todo"
placeholder="What needs to be done?"
autofocus
/>
</header>
<section class="main">
<input id="toggle-all" class="toggle-all" type="checkbox" />
<label for="toggle-all">Mark all as complete</label>
<ul class="todo-list">
@for (todo of todos | todosFilter: filterValue; track todo) {
<app-todo
appTooltip
[todo]="todo"
(delete)="onDelete($event)"
(update)="onChange($event)"
/>
}
</ul>
</section>
<footer class="footer">
<span class="todo-count">
<strong>{{ itemsLeft }}</strong> item left
</span>
<button class="clear-completed" (click)="clearCompleted()">Clear completed</button>
</footer>
</section>
`,
})
export class TodosComponent implements OnInit, OnDestroy {
todos: Todo[] = [
{
label: 'Buy milk',
completed: false,
id: '42',
},
{
label: 'Build something fun!',
completed: false,
id: '43',
},
];
@Output() update = new EventEmitter();
@Output() delete = new EventEmitter();
@Output() add = new EventEmitter();
private hashListener!: EventListenerOrEventListenerObject;
constructor(private cdRef: ChangeDetectorRef) {}
ngOnInit(): void {
if (typeof window !== 'undefined') {
window.addEventListener('hashchange', (this.hashListener = () => this.cdRef.markForCheck()));
}
}
ngOnDestroy(): void {
fib(40);
if (typeof window !== 'undefined') {
window.removeEventListener('hashchange', this.hashListener);
}
}
get filterValue(): TodoFilter {
if (typeof window !== 'undefined') {
return (window.location.hash.replace(/^#\//, '') as TodoFilter) || TodoFilter.All;
}
return TodoFilter.All;
}
get itemsLeft(): number {
return (this.todos || []).filter((t) => !t.completed).length;
}
clearCompleted(): void {
(this.todos || []).filter((t) => t.completed).forEach((t) => this.delete.emit(t));
}
addTodo(input: HTMLInputElement): void {
const todo = {
completed: false,
label: input.value,
};
const result: Todo = {...todo, id: Math.random().toString()};
this.todos.push(result);
input.value = '';
}
onChange(todo: Todo): void {
if (!todo.id) {
return;
}
}
onDelete(todo: Todo): void {
if (!todo.id) {
return;
}
const idx = this.todos.findIndex((t) => t.id === todo.id);
if (idx < 0) {
return;
}
// tslint:disable-next-line:no-console
console.log('Deleting', idx);
this.todos.splice(idx, 1);
}
}
| {
"end_byte": 4452,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/todo/home/todos.component.ts"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/todo/about/about.component.ts_0_542 | /**
* @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 '@angular/core';
import {RouterLink} from '@angular/router';
@Component({
selector: 'app-about',
standalone: true,
imports: [RouterLink],
template: `
About component
<a [routerLink]="">Home</a>
<a [routerLink]="">Home</a>
<a [routerLink]="">Home</a>
`,
})
export class AboutComponent {}
| {
"end_byte": 542,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/todo/about/about.component.ts"
} |
angular/devtools/projects/demo-standalone/src/app/demo-app/todo/about/BUILD.bazel_0_252 | load("//devtools/tools:ng_module.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "about",
srcs = ["about.component.ts"],
deps = [
"//packages/core",
"//packages/router",
],
)
| {
"end_byte": 252,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/app/demo-app/todo/about/BUILD.bazel"
} |
angular/devtools/projects/demo-standalone/src/environments/environment.ts_0_257 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export const environment = {
production: false,
};
| {
"end_byte": 257,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/environments/environment.ts"
} |
angular/devtools/projects/demo-standalone/src/environments/BUILD.bazel_0_256 | load("//devtools/tools:typescript.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "environments",
srcs = [
"environment.ts",
],
deps = [
"//packages/platform-browser",
],
)
| {
"end_byte": 256,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/environments/BUILD.bazel"
} |
angular/devtools/projects/demo-standalone/src/styles/chrome_styles.scss_0_42 | /** Specific style for Chrome browser */
| {
"end_byte": 42,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/styles/chrome_styles.scss"
} |
angular/devtools/projects/demo-standalone/src/styles/firefox_styles.scss_0_43 | /** Specific style for Firefox browser */
| {
"end_byte": 43,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/demo-standalone/src/styles/firefox_styles.scss"
} |
angular/devtools/projects/protocol/README.md_0_1154 | # Angular DevTools Communication Protocol
Angular DevTools injects scripts in the user application page that interact with the framework debugging APIs. The injected scripts interact with the extension via message passing using a statically typed protocol.
This subdirectory contains:
- Declaration of a statically typed message bus
- Implementation of priority aware message bus
- Interfaces that declare the messages exchanged between the extension and the page
We use the `PriorityAwareMessageBus` to ensure that certain messages have higher priority than others. Because of the asynchronous nature of the property exchange there's a risk that a message response may overwrite the result from a more recent response.
An example is:
1. We request the state of the component tree
1. We update the state
1. We request the state of the properties of a particular component
We don't have guarantees that the response of 1. will arrive before the response of 3. Often the response of 1. is larger and might be delivered after 3. In such a case, it may contain the application state prior to the update and override the state update we received from 3.
| {
"end_byte": 1154,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/protocol/README.md"
} |
angular/devtools/projects/protocol/BUILD.bazel_0_1083 | load("//devtools/tools:typescript.bzl", "ts_library", "ts_test_library")
load("@build_bazel_rules_nodejs//:index.bzl", "js_library")
load("//devtools/tools:defaults.bzl", "karma_web_test_suite")
package(default_visibility = ["//visibility:public"])
exports_files([
"tsconfig.lib.json",
"tsconfig.spec.json",
])
ts_library(
name = "protocol_ts",
srcs = glob(
["**/*.ts"],
exclude = [
"**/*.spec.ts",
"src/test.ts",
],
),
deps = [
"//packages/core",
"//packages/platform-browser-dynamic",
"@npm//@types",
],
)
ts_test_library(
name = "protocol_test",
srcs = glob(
["**/*.spec.ts"],
),
deps = [
":protocol_ts",
"//packages/core/testing",
"//packages/platform-browser-dynamic/testing",
"@npm//@types",
],
)
js_library(
name = "protocol",
package_name = "protocol",
deps = [":protocol_ts"],
)
karma_web_test_suite(
name = "test",
deps = [
"//devtools/projects/protocol:protocol_test",
],
)
| {
"end_byte": 1083,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/devtools/projects/protocol/BUILD.bazel"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.