_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-view-header.component.scss_0_518
mat-toolbar { padding-left: 10px; justify-content: space-between; text-overflow: ellipsis; overflow: hidden; line-height: 25px; font-size: 11px; font-weight: 500; height: auto; } .mat-icon-button { font-size:16px; line-height: 10px; } button { padding: 0; background: none; border: none; height: 24px; width: 24px; cursor: pointer; opacity: 0.5; &:hover { opacity: 0.75; } &:active { opacity: 1; } } :host-context(.dark-theme) { button { color: #fff; } }
{ "end_byte": 518, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-view-header.component.scss" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/BUILD.bazel_0_2224
load("@io_bazel_rules_sass//:defs.bzl", "sass_binary") load("//devtools/tools:ng_module.bzl", "ng_module") package(default_visibility = ["//visibility:public"]) _STYLE_SRCS = [ "property-editor.component.scss", "property-preview.component.scss", "property-tab-body.component.scss", "property-view.component.scss", "property-view-body.component.scss", "property-view-header.component.scss", "property-view-tree.component.scss", ] _STYLE_LABELS = [ src[:-len(".component.scss")].replace("-", "_") + "_styles" for src in _STYLE_SRCS ] [ sass_binary( name = label, src = src, ) for label, src in zip(_STYLE_LABELS, _STYLE_SRCS) ] ng_module( name = "property-view", srcs = [ "property-editor.component.ts", "property-preview.component.ts", "property-tab-body.component.ts", "property-view.component.ts", "property-view-body.component.ts", "property-view-header.component.ts", "property-view-tree.component.ts", ], angular_assets = [ "property-view.component.html", "property-view-tree.component.html", "property-view-header.component.html", "property-view-body.component.html", "property-preview.component.html", "property-editor.component.html", "property-tab-body.component.html", ] + _STYLE_LABELS, deps = [ "//devtools/projects/ng-devtools/src/lib:frame_manager", "//devtools/projects/ng-devtools/src/lib/application-environment", "//devtools/projects/ng-devtools/src/lib/devtools-tabs/dependency-injection:injector_tree_visualizer", "//devtools/projects/ng-devtools/src/lib/devtools-tabs/dependency-injection:resolution_path", "//devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/directive-forest/index-forest", "//devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver", "//devtools/projects/protocol", "//packages/common", "//packages/core", "//packages/forms", "@npm//@angular/cdk", "@npm//@angular/material", "@npm//@types", "@npm//rxjs", ], )
{ "end_byte": 2224, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/BUILD.bazel" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-preview.component.html_0_151
<span class="value" [class.function]="isClickableProp()" (click)="isClickableProp() && inspect.emit()"> {{ node().prop.descriptor.preview }} </span>
{ "end_byte": 151, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-preview.component.html" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-view-body.component.html_0_2104
@if (controlsLoaded()) { <mat-accordion cdkDropList (cdkDropListDropped)="drop($event)" [multi]="true"> @if (controller().directiveMetadata?.dependencies.length > 0) { <div class="mat-accordion-content"> <mat-expansion-panel [expanded]="true"> <mat-expansion-panel-header collapsedHeight="25px" expandedHeight="25px"> <mat-panel-title> Injected Services <a href="https://angular.dev/guide/di" target="_blank" class="documentation" matTooltip="Open docs reference" (click)="$event.stopPropagation()" > <mat-icon class="docs-link">open_in_new</mat-icon> </a> </mat-panel-title> </mat-expansion-panel-header> <ng-injected-services [controller]="controller()"/> </mat-expansion-panel> </div> } @for (index of categoryOrder; track $index) { <div class="mat-accordion-content" cdkDrag> @let panel = panels()[index]; @if (!panel.hidden) { <mat-expansion-panel [class]="panel.class" [expanded]="true"> <mat-expansion-panel-header collapsedHeight="25px" expandedHeight="25px"> <mat-panel-title> {{ panel.title }} <a href="{{ panel.documentation }}" target="_blank" class="documentation" matTooltip="Open docs reference" (click)="$event.stopPropagation()" > <mat-icon class="docs-link">open_in_new</mat-icon> </a> </mat-panel-title> </mat-expansion-panel-header> <ng-property-view-tree [dataSource]="panel.controls.dataSource" [treeControl]="panel.controls.treeControl" (updateValue)="updateValue($event)" (inspect)="handleInspect($event)" /> </mat-expansion-panel> } </div> } </mat-accordion> }
{ "end_byte": 2104, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-view-body.component.html" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-tab-body.component.ts_0_1292
/** * @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, computed, input, output} from '@angular/core'; import {DirectivePosition} from 'protocol'; import {IndexedNode} from '../../directive-forest/index-forest'; import {FlatNode} from '../../property-resolver/element-property-resolver'; import {PropertyViewComponent} from './property-view.component'; @Component({ templateUrl: './property-tab-body.component.html', selector: 'ng-property-tab-body', styleUrls: ['./property-tab-body.component.scss'], standalone: true, imports: [PropertyViewComponent], }) export class PropertyTabBodyComponent { readonly currentSelectedElement = input.required<IndexedNode>(); readonly inspect = output<{node: FlatNode; directivePosition: DirectivePosition}>(); readonly viewSource = output<string>(); readonly currentDirectives = computed(() => { const selected = this.currentSelectedElement(); if (!selected) { return; } const directives = selected.directives.map((d) => d.name); if (selected.component) { directives.push(selected.component.name); } return directives; }); }
{ "end_byte": 1292, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-tab-body.component.ts" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-preview.component.ts_0_897
/** * @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, computed, input, output} from '@angular/core'; import {PropType} from 'protocol'; import {FlatNode} from '../../property-resolver/element-property-resolver'; @Component({ selector: 'ng-property-preview', templateUrl: './property-preview.component.html', styleUrls: ['./property-preview.component.scss'], standalone: true, }) export class PropertyPreviewComponent { readonly node = input.required<FlatNode>(); readonly inspect = output<void>(); readonly isClickableProp = computed(() => { const node = this.node(); return ( node.prop.descriptor.type === PropType.Function || node.prop.descriptor.type === PropType.HTMLNode ); }); }
{ "end_byte": 897, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-preview.component.ts" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-view-body.component.scss_0_986
:host { ::ng-deep { mat-expansion-panel { border-radius: unset !important; } .mat-expansion-panel-body { padding: 0; } .mat-expansion-panel-spacing { margin: 0; } .mat-expansion-panel-header { padding: 0 15px; .documentation { display: flex; align-self: center; text-decoration: none; } .docs-link { color: #000000de; height: inherit; width: fit-content; font-size: initial; padding-left: 0.1rem; &:active { color: #1b1aa5; } } } .mat-expansion-panel-header-title { font-size: 0.8em; font-family: Menlo, monospace; } .mat-expansion-indicator { &::after { padding: 2.5px; margin-bottom: 4.5px; } } :host-context(.dark-theme) { .docs-link { color: #bcc5ce; &:active { color: #5caace; } } } } }
{ "end_byte": 986, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-view-body.component.scss" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-preview.component.scss_0_93
.function { &:hover { background: #4da1ff; color: #fff; cursor: pointer; } }
{ "end_byte": 93, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-preview.component.scss" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-view-header.component.ts_0_925
/** * @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, output} from '@angular/core'; import {MatIcon} from '@angular/material/icon'; import {MatTooltip} from '@angular/material/tooltip'; import {MatToolbar} from '@angular/material/toolbar'; @Component({ selector: 'ng-property-view-header', templateUrl: './property-view-header.component.html', styleUrls: ['./property-view-header.component.scss'], standalone: true, imports: [MatToolbar, MatTooltip, MatIcon], }) export class PropertyViewHeaderComponent { readonly directive = input.required<string>(); readonly viewSource = output<void>(); // output that emits directive handleViewSource(event: MouseEvent): void { event.stopPropagation(); this.viewSource.emit(); } }
{ "end_byte": 925, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-tab/property-view/property-view-header.component.ts" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/property-data-source.spec.ts_0_1617
/** * @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 {FlatTreeControl} from '@angular/cdk/tree'; import {PropType} from 'protocol'; import {FlatNode} from './element-property-resolver'; import {getTreeFlattener} from './flatten'; import {PropertyDataSource} from './property-data-source'; const flatTreeControl = new FlatTreeControl<FlatNode>( (node) => node.level, (node) => node.expandable, ); describe('PropertyDataSource', () => { it('should detect changes in the collection', () => { const source = new PropertyDataSource( { foo: { editable: true, expandable: false, preview: '42', type: PropType.Number, value: 42, containerType: null, }, }, getTreeFlattener(), flatTreeControl, {element: [1, 2, 3]}, null as any, ); source.update({ foo: { editable: true, expandable: false, preview: '43', type: PropType.Number, value: 43, containerType: null, }, }); expect(source.data).toEqual([ { expandable: false, level: 0, prop: { descriptor: { editable: true, expandable: false, preview: '43', type: PropType.Number, value: 43, containerType: null, }, name: 'foo', parent: null, }, }, ]); }); });
{ "end_byte": 1617, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/property-data-source.spec.ts" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/element-property-resolver.ts_0_2781
/** * @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 {Injectable} from '@angular/core'; import { ComponentExplorerViewProperties, Descriptor, DirectivePosition, DirectivesProperties, Events, MessageBus, } from 'protocol'; import {IndexedNode} from '../directive-forest/index-forest'; import {DirectivePropertyResolver} from './directive-property-resolver'; export interface FlatNode { expandable: boolean; prop: Property; level: number; } export interface Property { name: string; descriptor: Descriptor; parent: Property | null; } @Injectable() export class ElementPropertyResolver { private _directivePropertiesController = new Map<string, DirectivePropertyResolver>(); constructor(private _messageBus: MessageBus<Events>) {} clearProperties(): void { this._directivePropertiesController = new Map(); } setProperties(indexedNode: IndexedNode, data: DirectivesProperties): void { this._flushDeletedProperties(data); Object.keys(data).forEach((key) => { const controller = this._directivePropertiesController.get(key); if (controller) { controller.updateProperties(data[key]); return; } const position: DirectivePosition = { element: indexedNode.position, directive: undefined, }; if (!indexedNode.component || indexedNode.component.name !== key) { position.directive = indexedNode.directives.findIndex((d) => d.name === key); } this._directivePropertiesController.set( key, new DirectivePropertyResolver(this._messageBus, data[key], position), ); }); } private _flushDeletedProperties(data: DirectivesProperties): void { const currentProps = [...this._directivePropertiesController.keys()]; const incomingProps = new Set(Object.keys(data)); for (const prop of currentProps) { if (!incomingProps.has(prop)) { this._directivePropertiesController.delete(prop); } } } getExpandedProperties(): ComponentExplorerViewProperties { const result: ComponentExplorerViewProperties = {}; for (const [directive] of this._directivePropertiesController) { const controller = this._directivePropertiesController.get(directive); if (!controller) { console.error('Unable to find nested properties controller for', directive); continue; } result[directive] = controller.getExpandedProperties(); } return result; } getDirectiveController(directive: string): DirectivePropertyResolver | undefined { return this._directivePropertiesController.get(directive); } }
{ "end_byte": 2781, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/element-property-resolver.ts" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/directive-property-resolver.spec.ts_0_3755
/** * @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 {Properties, PropType} from 'protocol'; import {DirectivePropertyResolver} from './directive-property-resolver'; const properties: Properties = { props: { o: { editable: false, expandable: true, preview: '', type: PropType.Object, value: { a1: { editable: false, expandable: false, preview: '', type: 1, value: {}, }, b1: { editable: false, expandable: false, preview: '', type: 1, value: {}, }, }, containerType: null, }, i: { editable: false, expandable: true, preview: '', type: PropType.Object, value: { b1: { editable: false, expandable: false, preview: '', type: 1, value: {}, }, a1: { editable: false, expandable: false, preview: '', type: 1, value: {}, }, }, containerType: null, }, p: { editable: false, expandable: true, preview: '', type: PropType.Object, value: { b1: { editable: false, expandable: false, preview: '', type: 1, value: {}, }, a1: { editable: false, expandable: false, preview: '', type: 1, value: {}, }, }, containerType: null, }, i_1: { editable: true, expandable: false, preview: 'input i1', type: PropType.String, value: 'input i1', containerType: null, }, o_1: { editable: false, expandable: true, preview: '', type: PropType.Object, containerType: null, }, }, metadata: { inputs: { i: 'i', i1: 'i_1', }, outputs: { o: 'o', o1: 'o_1', }, encapsulation: 0, onPush: false, }, }; describe('DirectivePropertyResolver', () => { let messageBusMock: any; beforeEach(() => { messageBusMock = jasmine.createSpyObj('messageBus', ['on', 'once', 'emit', 'destroy']); }); it('should register directive inputs, outputs, and state', () => { const resolver = new DirectivePropertyResolver(messageBusMock, properties, { element: [0], directive: 0, }); expect(resolver.directiveInputControls.dataSource.data[0].prop.name).toBe('i'); expect(resolver.directiveInputControls.dataSource.data[1].prop.name).toBe('a1'); expect(resolver.directiveInputControls.dataSource.data[2].prop.name).toBe('b1'); expect(resolver.directiveInputControls.dataSource.data[3].prop.name).toBe('i_1'); expect(resolver.directiveOutputControls.dataSource.data[0].prop.name).toBe('o'); expect(resolver.directiveOutputControls.dataSource.data[1].prop.name).toBe('a1'); expect(resolver.directiveOutputControls.dataSource.data[2].prop.name).toBe('b1'); expect(resolver.directiveOutputControls.dataSource.data[3].prop.name).toBe('o_1'); expect(resolver.directiveStateControls.dataSource.data[0].prop.name).toBe('p'); }); it('should sort properties', () => { const resolver = new DirectivePropertyResolver(messageBusMock, properties, { element: [0], directive: 0, }); const props = resolver.getExpandedProperties(); const propNames = props.map((o) => o.name); // First level properties should be now sorted expect(propNames.join('')).toEqual('ii_1oo_1p'); }); });
{ "end_byte": 3755, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/directive-property-resolver.spec.ts" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/arrayify-props.ts_0_765
/** * @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 {Descriptor} from 'protocol'; import {Property} from './element-property-resolver'; export const arrayifyProps = ( props: {[prop: string]: Descriptor} | Descriptor[], parent: Property | null = null, ): Property[] => Object.entries(props) .map(([name, val]) => ({name, descriptor: val, parent})) .sort((a, b) => { const parsedA = parseInt(a.name, 10); const parsedB = parseInt(b.name, 10); if (isNaN(parsedA) || isNaN(parsedB)) { return a.name > b.name ? 1 : -1; } return parsedA - parsedB; });
{ "end_byte": 765, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/arrayify-props.ts" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/BUILD.bazel_0_1716
load("//devtools/tools:ng_module.bzl", "ng_module") load("//devtools/tools:typescript.bzl", "ts_test_library") load("//devtools/tools:defaults.bzl", "karma_web_test_suite") package(default_visibility = ["//visibility:public"]) ng_module( name = "property-resolver", srcs = [ "arrayify-props.ts", "directive-property-resolver.ts", "element-property-resolver.ts", "flatten.ts", "property-data-source.ts", "property-expanded-directive-properties.ts", ], deps = [ "//devtools/projects/ng-devtools/src/lib/devtools-tabs/diffing", "//devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/directive-forest/index-forest", "//devtools/projects/protocol", "//packages/core", "@npm//@angular/cdk", "@npm//@angular/material", "@npm//@types", "@npm//rxjs", ], ) ts_test_library( name = "property_resolver_test", srcs = [ "arrayify-props.spec.ts", "directive-property-resolver.spec.ts", "element-property-resolver.spec.ts", "property-data-source.spec.ts", ], deps = [ ":property-resolver", "//devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/directive-forest/index-forest", "//devtools/projects/protocol", "@npm//@angular/cdk", "@npm//@angular/material", ], ) # todo(aleksanderbodurri): fix this test suite karma_web_test_suite( name = "test", deps = [ ":property_resolver_test", "//packages/common/http", "//packages/platform-browser", "//packages/platform-browser/animations", "@npm//@angular/material", ], )
{ "end_byte": 1716, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/BUILD.bazel" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/property-expanded-directive-properties.ts_0_1330
/** * @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 {Descriptor, NestedProp, PropType} from 'protocol'; import {FlatNode} from './element-property-resolver'; export const getExpandedDirectiveProperties = (data: FlatNode[]): NestedProp[] => { const getChildren = (prop: Descriptor) => { if ((prop.type === PropType.Object || prop.type === PropType.Array) && prop.value) { return Object.entries(prop.value).map( ([k, v]: [string, any]): {name: number | string; children: NestedProp[]} => { return { name: prop.type === PropType.Array ? parseInt(k, 10) : k, children: getChildren(v), }; }, ); } return []; }; const getExpandedProperties = (props: {[name: string]: Descriptor}) => { return Object.keys(props).map((name) => { return { name, children: getChildren(props[name]), }; }); }; const parents: {[name: string]: Descriptor} = {}; for (const node of data) { let prop = node.prop; while (prop.parent) { prop = prop.parent; } parents[prop.name] = prop.descriptor; } return getExpandedProperties(parents); };
{ "end_byte": 1330, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/property-expanded-directive-properties.ts" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/flatten.ts_0_1386
/** * @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 {MatTreeFlattener} from '@angular/material/tree'; import {Descriptor, PropType} from 'protocol'; import {Observable} from 'rxjs'; import {arrayifyProps} from './arrayify-props'; import {FlatNode, Property} from './element-property-resolver'; export const getTreeFlattener = () => new MatTreeFlattener( (node: Property, level: number): FlatNode => { return { expandable: expandable(node.descriptor), prop: node, level, }; }, (node) => node.level, (node) => node.expandable, (node) => getChildren(node), ); export const expandable = (prop: Descriptor) => { if (!prop) { return false; } if (!prop.expandable) { return false; } return !(prop.type !== PropType.Object && prop.type !== PropType.Array); }; const getChildren = (prop: Property): Property[] | undefined => { const descriptor = prop.descriptor; if ( (descriptor.type === PropType.Object || descriptor.type === PropType.Array) && !(descriptor.value instanceof Observable) ) { return arrayifyProps(descriptor.value || {}, prop); } console.error('Unexpected data type', descriptor, 'in property', prop); return; };
{ "end_byte": 1386, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/flatten.ts" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/element-property-resolver.spec.ts_0_3278
/** * @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 {Properties, PropType} from 'protocol'; import {IndexedNode} from '../directive-forest/index-forest'; import {ElementPropertyResolver} from './element-property-resolver'; const mockIndexedNode: IndexedNode = { component: { name: 'FooCmp', id: 0, isElement: false, }, hydration: null, directives: [ { id: 1, name: 'BarDir', }, { id: 2, name: 'BazDir', }, ], children: [], element: 'foo', position: [0], }; const fooNestedProperties: Properties = { props: { foo: { editable: false, expandable: true, preview: '{...}', type: PropType.Object, value: { bar: { editable: false, expandable: true, preview: '{...}', type: PropType.Object, value: {}, }, baz: { editable: false, expandable: true, preview: '{...}', type: PropType.Object, value: {}, }, }, containerType: null, }, }, }; const barNestedProps: Properties = { props: { bar: { editable: false, expandable: false, preview: 'undefined', type: PropType.Undefined, value: undefined, containerType: null, }, }, }; describe('ElementPropertyResolver', () => { let messageBusMock: any; beforeEach(() => { messageBusMock = jasmine.createSpyObj('messageBus', ['on', 'once', 'emit', 'destroy']); }); it('should register directives', () => { const resolver = new ElementPropertyResolver(messageBusMock); resolver.setProperties(mockIndexedNode, { FooCmp: { props: {}, }, BarDir: { props: {}, }, BazDir: { props: {}, }, }); expect(resolver.getDirectiveController('FooCmp')).not.toBeFalsy(); expect(resolver.getDirectiveController('BarDir')).not.toBeFalsy(); expect(resolver.getDirectiveController('BazDir')).not.toBeFalsy(); }); it('should provide nested props', () => { const resolver = new ElementPropertyResolver(messageBusMock); resolver.setProperties(mockIndexedNode, { FooCmp: fooNestedProperties, BarDir: barNestedProps, BazDir: { props: {}, }, }); const fooController = resolver.getDirectiveController('FooCmp'); expect(fooController).toBeTruthy(); // tslint:disable-next-line: no-non-null-assertion const fooProps = fooController!.getExpandedProperties(); expect(fooProps).toEqual([ { name: 'foo', children: [ { name: 'bar', children: [], }, { name: 'baz', children: [], }, ], }, ]); const barController = resolver.getDirectiveController('BarDir'); expect(barController).toBeTruthy(); // tslint:disable-next-line: no-non-null-assertion const barProps = barController!.getExpandedProperties(); expect(barProps).toEqual([ { name: 'bar', children: [], }, ]); }); });
{ "end_byte": 3278, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/element-property-resolver.spec.ts" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/directive-property-resolver.ts_0_5078
/** * @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 {FlatTreeControl} from '@angular/cdk/tree'; import {ViewEncapsulation} from '@angular/core'; import { Descriptor, DirectiveMetadata, DirectivePosition, Events, MessageBus, NestedProp, Properties, } from 'protocol'; import {FlatNode, Property} from './element-property-resolver'; import {getTreeFlattener} from './flatten'; import {PropertyDataSource} from './property-data-source'; import {getExpandedDirectiveProperties} from './property-expanded-directive-properties'; export interface DirectiveTreeData { dataSource: PropertyDataSource; treeControl: FlatTreeControl<FlatNode>; } const getDirectiveControls = ( dataSource: PropertyDataSource, ): {dataSource: PropertyDataSource; treeControl: FlatTreeControl<FlatNode>} => { const treeControl = dataSource.treeControl; return { dataSource, treeControl, }; }; export const constructPathOfKeysToPropertyValue = ( nodePropToGetKeysFor: Property, keys: string[] = [], ): string[] => { keys.unshift(nodePropToGetKeysFor.name); const parentNodeProp = nodePropToGetKeysFor.parent; if (parentNodeProp) { constructPathOfKeysToPropertyValue(parentNodeProp, keys); } return keys; }; export class DirectivePropertyResolver { private _treeFlattener = getTreeFlattener(); private _treeControl = new FlatTreeControl<FlatNode>( (node) => node.level, (node) => node.expandable, ); private _inputsDataSource: PropertyDataSource; private _outputsDataSource: PropertyDataSource; private _stateDataSource: PropertyDataSource; constructor( private _messageBus: MessageBus<Events>, private _props: Properties, private _directivePosition: DirectivePosition, ) { const {inputProps, outputProps, stateProps} = this._classifyProperties(); this._inputsDataSource = this._createDataSourceFromProps(inputProps); this._outputsDataSource = this._createDataSourceFromProps(outputProps); this._stateDataSource = this._createDataSourceFromProps(stateProps); } get directiveInputControls(): DirectiveTreeData { return getDirectiveControls(this._inputsDataSource); } get directiveOutputControls(): DirectiveTreeData { return getDirectiveControls(this._outputsDataSource); } get directiveStateControls(): DirectiveTreeData { return getDirectiveControls(this._stateDataSource); } get directiveMetadata(): DirectiveMetadata | undefined { return this._props.metadata; } get directiveProperties(): {[name: string]: Descriptor} { return this._props.props; } get directivePosition(): DirectivePosition { return this._directivePosition; } get directiveViewEncapsulation(): ViewEncapsulation | undefined { return this._props.metadata?.encapsulation; } get directiveHasOnPushStrategy(): boolean | undefined { return this._props.metadata?.onPush; } getExpandedProperties(): NestedProp[] { return [ ...getExpandedDirectiveProperties(this._inputsDataSource.data), ...getExpandedDirectiveProperties(this._outputsDataSource.data), ...getExpandedDirectiveProperties(this._stateDataSource.data), ]; } updateProperties(newProps: Properties): void { this._props = newProps; const {inputProps, outputProps, stateProps} = this._classifyProperties(); this._inputsDataSource.update(inputProps); this._outputsDataSource.update(outputProps); this._stateDataSource.update(stateProps); } updateValue(node: FlatNode, newValue: unknown): void { const directiveId = this._directivePosition; const keyPath = constructPathOfKeysToPropertyValue(node.prop); this._messageBus.emit('updateState', [{directiveId, keyPath, newValue}]); node.prop.descriptor.value = newValue; } private _createDataSourceFromProps(props: {[name: string]: Descriptor}): PropertyDataSource { return new PropertyDataSource( props, this._treeFlattener, this._treeControl, this._directivePosition, this._messageBus, ); } private _classifyProperties(): { inputProps: {[name: string]: Descriptor}; outputProps: {[name: string]: Descriptor}; stateProps: {[name: string]: Descriptor}; } { const inputLabels: Set<string> = new Set(Object.values(this._props.metadata?.inputs || {})); const outputLabels: Set<string> = new Set(Object.values(this._props.metadata?.outputs || {})); const inputProps = {}; const outputProps = {}; const stateProps = {}; let propPointer: {[name: string]: Descriptor}; Object.keys(this.directiveProperties).forEach((propName) => { propPointer = inputLabels.has(propName) ? inputProps : outputLabels.has(propName) ? outputProps : stateProps; propPointer[propName] = this.directiveProperties[propName]; }); return { inputProps, outputProps, stateProps, }; } }
{ "end_byte": 5078, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/directive-property-resolver.ts" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/arrayify-props.spec.ts_0_2123
/** * @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 {arrayifyProps} from './arrayify-props'; describe('arrayify', () => { it('should return an array from prop object', () => { const arr = arrayifyProps({ foo: { editable: true, expandable: true, preview: '', type: PropType.Array, containerType: null, }, bar: { editable: true, expandable: true, preview: '', type: PropType.Array, containerType: null, }, }); expect(arr).toEqual([ { name: 'bar', descriptor: { editable: true, expandable: true, preview: '', type: PropType.Array, containerType: null, }, parent: null, }, { name: 'foo', descriptor: { editable: true, expandable: true, preview: '', type: PropType.Array, containerType: null, }, parent: null, }, ]); }); it('should properly sort array objects', () => { const arr = arrayifyProps({ 11: { editable: true, expandable: true, preview: '', type: PropType.Array, containerType: null, }, 2: { editable: true, expandable: true, preview: '', type: PropType.Array, containerType: null, }, }); expect(arr).toEqual([ { name: '2', descriptor: { editable: true, expandable: true, preview: '', type: PropType.Array, containerType: null, }, parent: null, }, { name: '11', descriptor: { editable: true, expandable: true, preview: '', type: PropType.Array, containerType: null, }, parent: null, }, ]); }); });
{ "end_byte": 2123, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/arrayify-props.spec.ts" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/property-data-source.ts_0_4353
/** * @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 {CollectionViewer, DataSource, SelectionChange} from '@angular/cdk/collections'; import {FlatTreeControl} from '@angular/cdk/tree'; import {DefaultIterableDiffer, TrackByFunction} from '@angular/core'; import {MatTreeFlattener} from '@angular/material/tree'; import {Descriptor, DirectivePosition, Events, MessageBus, Properties} from 'protocol'; import {BehaviorSubject, merge, Observable, Subscription} from 'rxjs'; import {map} from 'rxjs/operators'; import {diff} from '../../diffing'; import {arrayifyProps} from './arrayify-props'; import {FlatNode, Property} from './element-property-resolver'; const trackBy: TrackByFunction<FlatNode> = (_: number, item: FlatNode) => `#${item.prop.name}#${item.prop.descriptor.preview}#${item.level}`; export class PropertyDataSource extends DataSource<FlatNode> { private _data = new BehaviorSubject<FlatNode[]>([]); private _subscriptions: Subscription[] = []; private _expandedData = new BehaviorSubject<FlatNode[]>([]); private _differ = new DefaultIterableDiffer<FlatNode>(trackBy); constructor( props: {[prop: string]: Descriptor}, private _treeFlattener: MatTreeFlattener<Property, FlatNode>, private _treeControl: FlatTreeControl<FlatNode>, private _entityPosition: DirectivePosition, private _messageBus: MessageBus<Events>, ) { super(); this._data.next(this._treeFlattener.flattenNodes(arrayifyProps(props))); } get data(): FlatNode[] { return this._data.value; } get treeControl(): FlatTreeControl<FlatNode> { return this._treeControl; } update(props: {[prop: string]: Descriptor}): void { const newData = this._treeFlattener.flattenNodes(arrayifyProps(props)); diff(this._differ, this.data, newData); this._data.next(this.data); } override connect(collectionViewer: CollectionViewer): Observable<FlatNode[]> { const changed = this._treeControl.expansionModel.changed; if (!changed) { throw new Error('Unable to subscribe to the expansion model change'); } const s = changed.subscribe((change: SelectionChange<FlatNode>) => { if (change.added) { change.added.forEach((node) => this._toggleNode(node, true)); } if (change.removed) { change.removed.reverse().forEach((node) => this._toggleNode(node, false)); } }); this._subscriptions.push(s); const changes = [ collectionViewer.viewChange, this._treeControl.expansionModel.changed, this._data, ]; return merge<unknown[]>(...changes).pipe( map(() => { this._expandedData.next( this._treeFlattener.expandFlattenedNodes(this.data, this._treeControl), ); return this._expandedData.value; }), ); } override disconnect(): void { this._subscriptions.forEach((s) => s.unsubscribe()); this._subscriptions = []; } private _toggleNode(node: FlatNode, expand: boolean): void { const index = this.data.indexOf(node); // If we cannot find the current node, or the current node is not expandable // or...if it's expandable but it does have a value, or we're collapsing // we're not interested in fetching its children. if (index < 0 || !node.expandable || node.prop.descriptor.value || !expand) { return; } let parentPath: string[] = []; let current = node.prop; while (current) { parentPath.push(current.name); if (!current.parent) { break; } current = current.parent; } parentPath = parentPath.reverse(); this._messageBus.emit('getNestedProperties', [this._entityPosition, parentPath]); this._messageBus.once( 'nestedProperties', (position: DirectivePosition, data: Properties, _path: string[]) => { node.prop.descriptor.value = data.props; this._treeControl.expand(node); const props = arrayifyProps(data.props, node.prop); const flatNodes = this._treeFlattener.flattenNodes(props); flatNodes.forEach((f) => (f.level += node.level + 1)); this.data.splice(index + 1, 0, ...flatNodes); this._data.next(this.data); }, ); } }
{ "end_byte": 4353, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/directive-explorer/property-resolver/property-data-source.ts" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/dependency-injection/injector-tree-visualizer.ts_0_2021
/** * @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 d3 from 'd3'; import {SerializedInjector} from 'protocol'; let arrowDefId = 0; const injectorTypeToClassMap = new Map<string, string>([ ['imported-module', 'node-imported-module'], ['environment', 'node-environment'], ['element', 'node-element'], ['null', 'node-null'], ]); export interface InjectorTreeNode { injector: SerializedInjector; children: InjectorTreeNode[]; } export type InjectorTreeD3Node = d3.HierarchyPointNode<InjectorTreeNode>; export abstract class GraphRenderer<T, U> { abstract render(graph: T): void; abstract getNodeById(id: string): U | null; abstract snapToNode(node: U): void; abstract snapToRoot(): void; abstract zoomScale(scale: number): void; abstract root: U | null; abstract get graphElement(): HTMLElement; protected nodeClickListeners: ((pointerEvent: PointerEvent, node: U) => void)[] = []; protected nodeMouseoverListeners: ((pointerEvent: PointerEvent, node: U) => void)[] = []; protected nodeMouseoutListeners: ((pointerEvent: PointerEvent, node: U) => void)[] = []; cleanup(): void { this.nodeClickListeners = []; this.nodeMouseoverListeners = []; this.nodeMouseoutListeners = []; } onNodeClick(cb: (pointerEvent: PointerEvent, node: U) => void): void { this.nodeClickListeners.push(cb); } onNodeMouseover(cb: (pointerEvent: PointerEvent, node: U) => void): void { this.nodeMouseoverListeners.push(cb); } onNodeMouseout(cb: (pointerEvent: PointerEvent, node: U) => void): void { this.nodeMouseoutListeners.push(cb); } } interface InjectorTreeVisualizerConfig { orientation: 'horizontal' | 'vertical'; nodeSize: [width: number, height: number]; nodeSeparation: (nodeA: InjectorTreeD3Node, nodeB: InjectorTreeD3Node) => number; nodeLabelSize: [width: number, height: number]; }
{ "end_byte": 2021, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/dependency-injection/injector-tree-visualizer.ts" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/dependency-injection/injector-tree-visualizer.ts_2023_8951
export class InjectorTreeVisualizer extends GraphRenderer<InjectorTreeNode, InjectorTreeD3Node> { public config: InjectorTreeVisualizerConfig; constructor( private _containerElement: HTMLElement, private _graphElement: HTMLElement, { orientation = 'horizontal', nodeSize = [200, 500], nodeSeparation = () => 2, nodeLabelSize = [250, 60], }: Partial<InjectorTreeVisualizerConfig> = {}, ) { super(); this.config = { orientation, nodeSize, nodeSeparation, nodeLabelSize, }; } private d3 = d3; override root: InjectorTreeD3Node | null = null; zoomController: d3.ZoomBehavior<HTMLElement, unknown> | null = null; override zoomScale(scale: number) { if (this.zoomController) { this.zoomController.scaleTo( this.d3.select<HTMLElement, unknown>(this._containerElement), scale, ); } } override snapToRoot(scale = 1): void { if (this.root) { this.snapToNode(this.root, scale); } } override snapToNode(node: InjectorTreeD3Node, scale = 1): void { const svg = this.d3.select(this._containerElement); const halfWidth = this._containerElement.clientWidth / 2; const halfHeight = this._containerElement.clientHeight / 2; const t = d3.zoomIdentity.translate(halfWidth - node.y, halfHeight - node.x).scale(scale); svg.transition().duration(500).call(this.zoomController!.transform, t); } override get graphElement(): HTMLElement { return this._graphElement; } override getNodeById(id: string): InjectorTreeD3Node | null { const selection = this.d3 .select<HTMLElement, InjectorTreeD3Node>(this._containerElement) .select(`.node[data-id="${id}"]`); if (selection.empty()) { return null; } return selection.datum(); } override cleanup(): void { super.cleanup(); this.d3.select(this._graphElement).selectAll('*').remove(); } override render(injectorGraph: InjectorTreeNode): void { // cleanup old graph this.cleanup(); const data = this.d3.hierarchy(injectorGraph, (node: InjectorTreeNode) => node.children); const tree = this.d3.tree<InjectorTreeNode>(); const svg = this.d3.select(this._containerElement); const g = this.d3.select<HTMLElement, InjectorTreeD3Node>(this._graphElement); this.zoomController = this.d3.zoom<HTMLElement, unknown>().scaleExtent([0.1, 2]); this.zoomController.on('start zoom end', (e: {transform: number}) => { g.attr('transform', e.transform); }); svg.call(this.zoomController); // Compute the new tree layout. tree.nodeSize(this.config.nodeSize); tree.separation((a: InjectorTreeD3Node, b: InjectorTreeD3Node) => { return this.config.nodeSeparation(a, b); }); const nodes = tree(data); this.root = nodes; arrowDefId++; svg .append('svg:defs') .selectAll('marker') .data([`end${arrowDefId}`]) // Different link/path types can be defined here .enter() .append('svg:marker') // This section adds in the arrows .attr('id', String) .attr('viewBox', '0 -5 10 10') .attr('refX', 15) .attr('refY', 0) .attr('class', 'arrow') .attr('markerWidth', 6) .attr('markerHeight', 6) .attr('orient', 'auto') .append('svg:path') .attr('d', 'M0,-5L10,0L0,5'); g.selectAll('.link') .data(nodes.descendants().slice(1)) .enter() .append('path') .attr('class', (node: InjectorTreeD3Node) => { const parentId = node.parent?.data?.injector?.id; if (parentId === 'N/A') { return 'link-hidden'; } return `link`; }) .attr('data-id', (node: InjectorTreeD3Node) => { const from = node.data.injector.id; const to = node.parent?.data?.injector?.id; if (from && to) { return `${from}-to-${to}`; } return ''; }) .attr('marker-end', `url(#end${arrowDefId})`) .attr('d', (node: InjectorTreeD3Node) => { const parent = node.parent!; if (this.config.orientation === 'horizontal') { return ` M${node.y},${node.x} C${(node.y + parent.y) / 2}, ${node.x} ${(node.y + parent.y) / 2}, ${parent.x} ${parent.y}, ${parent.x}`; } return ` M${node.x},${node.y} C${(node.x + parent.x) / 2}, ${node.y} ${(node.x + parent.x) / 2}, ${parent.y} ${parent.x}, ${parent.y}`; }); // Declare the nodes const node = g .selectAll('g.node') .data(nodes.descendants()) .enter() .append('g') .attr('class', (node: InjectorTreeD3Node) => { if (node.data.injector.id === 'N/A') { return 'node-hidden'; } return `node`; }) .attr('data-component-id', (node: InjectorTreeD3Node) => { const injector = node.data.injector; if (injector.type === 'element') { return injector.node?.component?.id ?? -1; } return -1; }) .attr('data-id', (node: InjectorTreeD3Node) => { return node.data.injector.id; }) .on('click', (pointerEvent: PointerEvent, node: InjectorTreeD3Node) => { this.nodeClickListeners.forEach((listener) => listener(pointerEvent, node)); }) .on('mouseover', (pointerEvent: PointerEvent, node: InjectorTreeD3Node) => { this.nodeMouseoverListeners.forEach((listener) => listener(pointerEvent, node)); }) .on('mouseout', (pointerEvent: PointerEvent, node: InjectorTreeD3Node) => { this.nodeMouseoutListeners.forEach((listener) => listener(pointerEvent, node)); }) .attr('transform', (node: InjectorTreeD3Node) => { if (this.config.orientation === 'horizontal') { return `translate(${node.y},${node.x})`; } return `translate(${node.x},${node.y})`; }); const [width, height] = this.config.nodeLabelSize!; node .append('foreignObject') .attr('width', width) .attr('height', height) .attr('x', -1 * (width - 10)) .attr('y', -1 * (height / 2)) .append('xhtml:div') .attr('title', (node: InjectorTreeD3Node) => { return node.data.injector.name; }) .attr('class', (node: InjectorTreeD3Node) => { return [injectorTypeToClassMap.get(node.data?.injector?.type) ?? '', 'node-container'].join( ' ', ); }) .html((node: InjectorTreeD3Node) => { const label = node.data.injector.name; const lengthLimit = 25; return label.length > lengthLimit ? label.slice(0, lengthLimit - '...'.length) + '...' : label; }); svg.attr('height', '100%').attr('width', '100%'); } }
{ "end_byte": 8951, "start_byte": 2023, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/dependency-injection/injector-tree-visualizer.ts" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/dependency-injection/BUILD.bazel_0_671
load("//devtools/tools:typescript.bzl", "ts_library") load("//devtools/tools:ng_module.bzl", "ng_module") package(default_visibility = ["//visibility:public"]) ng_module( name = "resolution_path", srcs = ["resolution-path.component.ts"], deps = [ ":injector_tree_visualizer", "//devtools/projects/protocol", "//packages/core", "@npm//@types", "@npm//rxjs", ], ) ts_library( name = "injector_tree_visualizer", srcs = ["injector-tree-visualizer.ts"], deps = [ "//devtools/projects/protocol", "//packages/core", "@npm//@types", "@npm//d3", "@npm//rxjs", ], )
{ "end_byte": 671, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/dependency-injection/BUILD.bazel" }
angular/devtools/projects/ng-devtools/src/lib/devtools-tabs/dependency-injection/resolution-path.component.ts_0_2582
/** * @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 { afterNextRender, Component, computed, effect, ElementRef, input, OnDestroy, viewChild, } from '@angular/core'; import {SerializedInjector} from 'protocol'; import {InjectorTreeNode, InjectorTreeVisualizer} from './injector-tree-visualizer'; @Component({ selector: 'ng-resolution-path', template: ` <section class="injector-graph"> <svg #svgContainer> <g #mainGroup></g> </svg> </section> `, styles: [ ` :host { display: block; } `, ], standalone: true, }) export class ResolutionPathComponent implements OnDestroy { private svgContainer = viewChild.required<ElementRef>('svgContainer'); private g = viewChild.required<ElementRef>('mainGroup'); readonly orientation = input<'horizontal' | 'vertical'>('horizontal'); private injectorTree!: InjectorTreeVisualizer; readonly path = input<SerializedInjector[]>([]); private readonly pathNode = computed(() => { const path = this.path(); const serializedInjectors = path.slice().reverse(); const injectorTreeNodes: InjectorTreeNode[] = []; // map serialized injectors to injector tree nodes for (const serializedInjector of serializedInjectors) { injectorTreeNodes.push({injector: serializedInjector, children: []}); } // set injector tree node children for (const [index, injectorTreeNode] of injectorTreeNodes.entries()) { if (index !== injectorTreeNodes.length - 1) { injectorTreeNode.children = [injectorTreeNodes[index + 1]]; } else { injectorTreeNode.children = []; } } return injectorTreeNodes[0]; }); constructor() { afterNextRender({ read: () => { this.injectorTree = new InjectorTreeVisualizer( this.svgContainer().nativeElement, this.g().nativeElement, { orientation: this.orientation(), }, ); if (this.pathNode()) { this.injectorTree.render(this.pathNode()); } this.injectorTree.onNodeClick((_, node) => { this.injectorTree.snapToNode(node); }); this.injectorTree.snapToRoot(0.7); }, }); effect(() => { this.injectorTree?.render?.(this.pathNode()); }); } ngOnDestroy(): void { if (this.injectorTree) { this.injectorTree.cleanup(); } } }
{ "end_byte": 2582, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/devtools-tabs/dependency-injection/resolution-path.component.ts" }
angular/devtools/projects/ng-devtools/src/lib/application-operations/BUILD.bazel_0_270
load("//devtools/tools:typescript.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "application-operations", srcs = ["index.ts"], deps = [ "//devtools/projects/protocol", "@npm//@types", ], )
{ "end_byte": 270, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/application-operations/BUILD.bazel" }
angular/devtools/projects/ng-devtools/src/lib/application-operations/index.ts_0_585
/** * @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 {DirectivePosition, ElementPosition} from 'protocol'; export abstract class ApplicationOperations { abstract viewSource(position: ElementPosition, directiveIndex?: number, target?: URL): void; abstract selectDomElement(position: ElementPosition, target?: URL): void; abstract inspect(directivePosition: DirectivePosition, objectPath: string[], target?: URL): void; }
{ "end_byte": 585, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/application-operations/index.ts" }
angular/devtools/projects/ng-devtools/src/lib/vendor/memo-decorator/README.md_0_2288
[![Build Status](https://travis-ci.org/mgechev/memo-decorator.svg?branch=master)](https://travis-ci.org/mgechev/memo-decorator) # Memo Decorator This decorator applies memoization to a method of a class. ## Usage Apply the decorator to a method of a class. The cache is local for the method but shared among all instances of the class. Strongly recommend you to **use this decorator only on pure methods.** Installation: ```shell npm i memo-decorator --save ``` ### Configuration ```ts export interface Config { resolver?: Resolver; cache?: MapLike; } ``` - `Resolver` is a function, which returns the key to be used for given set of arguments. By default, the resolver will use the first argument of the method as the key. - `MapLike` is a cache instance. By default, the library would use `Map`. Example: ```typescript import memo from 'memo-decorator'; class Qux { @memo({ resolver: (...args: any[]) => args[1], cache: new WeakMap(), }) foo(a: number, b: number) { return a * b; } } ``` ### Demo ```typescript import memo from 'memo-decorator'; class Qux { @memo() foo(a: number) { console.log('foo: called'); return 42; } @memo({ resolver: (_) => 1, }) bar(a: number) { console.log('bar: called'); return 42; } } const a = new Qux(); // Create a new cache entry and associate `1` with the result `42`. a.foo(1); // Do not invoke the original method `foo` because there's already a cache // entry for the key `1` associated with the result of the method. a.foo(1); // Invoke the original `foo` because the cache doesn't contain an entry // for the key `2`. a.foo(2); // Invoke `bar` and return the result `42` gotten from the original `bar` implementation. a.bar(1); // Does not invoke the original `bar` implementation because of the specified `resolver` // which is passed to `memo`. For any arguments of the function, the resolver will return // result `1` which will be used as the key. a.bar(2); const b = new Qux(); // Does not invoke the method `foo` because there's already an entry // in the cache which associates the key `1` to the result `42` from the // invocation of the method `foo` by the instance `a`. b.foo(1); // Outputs: // foo: called // foo: called // bar: called ``` ## License MIT
{ "end_byte": 2288, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/memo-decorator/README.md" }
angular/devtools/projects/ng-devtools/src/lib/vendor/memo-decorator/BUILD.bazel_0_177
load("//devtools/tools:typescript.bzl", "ts_library") package(default_visibility = ["//:__subpackages__"]) ts_library( name = "memo-decorator", srcs = ["index.ts"], )
{ "end_byte": 177, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/memo-decorator/BUILD.bazel" }
angular/devtools/projects/ng-devtools/src/lib/vendor/memo-decorator/index.ts_0_1299
export type Resolver = (...args: any[]) => any; export interface MapLike<K = unknown, V = unknown> { set(key: K, v: V): MapLike<K, V>; get(key: K): V; has(key: K): boolean; } export interface Config { resolver?: Resolver; cache?: MapLike; } function memoize(func: Function, resolver: Resolver, cache: MapLike) { const memoized = function () { const args = arguments; // @ts-ignore: ignore implicit any type const key = resolver.apply(this, args); const cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } // @ts-ignore: ignore implicit any type const result = func.apply(this, args); memoized.cache = cache.set(key, result) ?? cache; return result; }; memoized.cache = cache; return memoized; } const defaultResolver: Resolver = (...args: any[]) => args[0]; export const memo = (config: Config = {}) => (_: any, __: string, descriptor: PropertyDescriptor): PropertyDescriptor => { if (typeof descriptor.value !== 'function') { throw new Error('Memoization can be applied only to methods'); } const resolver = config.resolver ?? defaultResolver; const cache = config.cache ?? new Map(); descriptor.value = memoize(descriptor.value, resolver, cache); return descriptor; };
{ "end_byte": 1299, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/memo-decorator/index.ts" }
angular/devtools/projects/ng-devtools/src/lib/vendor/webtreemap/LICENSE_0_10173
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS
{ "end_byte": 10173, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/webtreemap/LICENSE" }
angular/devtools/projects/ng-devtools/src/lib/vendor/webtreemap/LICENSE_10175_11357
APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
{ "end_byte": 11357, "start_byte": 10175, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/webtreemap/LICENSE" }
angular/devtools/projects/ng-devtools/src/lib/vendor/webtreemap/README.md_0_1919
# webtreemap > **New 2017-Oct-16**: master is now webtreemap v2, a complete rewrite with > bug fixes, more features, and a different (simpler) API. If you're looking > for the old webtreemap, see the [v1] branch. [v1]: https://github.com/evmar/webtreemap/tree/v1 A simple treemap implementation using web technologies (DOM nodes, CSS styling and transitions) rather than a big canvas/svg/plugin. It's usable as a library as part of a larger web app, but it also includes a command-line app that dumps a self-contained HTML file that displays a map. Play with a [demo]. [demo]: http://evmar.github.io/webtreemap/demo.html ## Usage ### Web The data format is a tree of `Node`, where each node is an object in the shape described at the top of [tree.ts]. [tree.ts]: https://github.com/evmar/webtreemap/blob/master/tree.ts ```html <script src='webtreemap.js'></script> <script> // Container must have its own width/height. const container = document.getElementById('myContainer'); // See typings for full API definition. webtreemap.render(container, data, options); ``` ### Command line ```sh $ webtreemap -o output_file < my_data ``` Command line data format is space-separated lines of "size path", where size is a number and path is a '/'-delimited path. This is exactly the output produced by du, so this works: ```sh $ du -ab some_path | webtreemap -o out.html ``` But note that there's nothing file-system-specific about the data format -- it just uses slash as a nesting delimiter. ## Development ### Web piece Use `npm run dev` to bring up file watchers that keep the demo JS bundle up to date. Then load `demo/demo.html` in a browser. The file generated by `npm run dev` is also used by the command line app. ### Command line app Use `tsc -w` to keep the npm-compatible JS up to date, then run e.g.: ``` $ du -ab node_modules/ | node build/cli.js --title 'node_modules usage' -o demo.html ```
{ "end_byte": 1919, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/webtreemap/README.md" }
angular/devtools/projects/ng-devtools/src/lib/vendor/webtreemap/treemap.ts_0_3525
/** * Copyright 2019 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {Node} from './tree'; const CSS_PREFIX = 'webtreemap-'; const NODE_CSS_CLASS = CSS_PREFIX + 'node'; const DEFAULT_CSS = ` .webtreemap-node { cursor: pointer; position: absolute; border: solid 1px #666; box-sizing: border-box; overflow: hidden; background: white; transition: left .15s, top .15s, width .15s, height .15s; } .webtreemap-node:hover { background: #ddd; } .webtreemap-caption { font-size: 10px; text-align: center; } `; function addCSS(parent: HTMLElement) { const style = document.createElement('style'); style.innerText = DEFAULT_CSS; parent.appendChild(style); } export function isDOMNode(e: Element): boolean { return e.classList.contains(NODE_CSS_CLASS); } /** * Options is the set of user-provided webtreemap configuration. */ export interface Options { padding: [number, number, number, number]; lowerBound: number; applyMutations(node: Node): void; caption(node: Node): string; showNode(node: Node, width: number, height: number): boolean; showChildren(node: Node, width: number, height: number): boolean; } /** * get the index of this node in its parent's children list. * O(n) but we expect n to be small. */ function getNodeIndex(target: Element): number { let index = 0; let node: Element | null = target; while ((node = node.previousElementSibling)) { if (isDOMNode(node)) index++; } return index; } /** * Given a DOM node, compute its address: an array of indexes * into the Node tree. An address [a1,a2,...] refers to * tree.chldren[a1].children[a2].children[...]. */ export function getAddress(el: Element): number[] { let address: number[] = []; let n: Element | null = el; while (n && isDOMNode(n)) { address.unshift(getNodeIndex(n)); n = n.parentElement; } address.shift(); // The first element will be the root, index 0. return address; } /** * Converts a number to a CSS pixel string. */ function px(x: number): string { // Rounding when computing pixel coordinates makes the box edges touch // better than letting the browser do it, because the browser has lots of // heuristics around handling non-integer pixel coordinates. return Math.round(x) + 'px'; } function defaultOptions(options: Partial<Options>): Options { const opts = { padding: options.padding || [14, 3, 3, 3], lowerBound: options.lowerBound === undefined ? 0.1 : options.lowerBound, applyMutations: options.applyMutations || (() => null), caption: options.caption || ((node: Node) => node.id || ''), showNode: options.showNode || ((node: Node, width: number, height: number): boolean => { return width > 20 && height >= opts.padding[0]; }), showChildren: options.showChildren || ((node: Node, width: number, height: number): boolean => { return width > 40 && height > 40; }), }; return opts; }
{ "end_byte": 3525, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/webtreemap/treemap.ts" }
angular/devtools/projects/ng-devtools/src/lib/vendor/webtreemap/treemap.ts_3527_11271
export class TreeMap { readonly options: Options; constructor( public node: Node, options: Partial<Options>, ) { this.options = defaultOptions(options); } /** Creates the DOM for a single node if it doesn't have one already. */ ensureDOM(node: Node): HTMLElement { if (node.dom) return node.dom; const dom = document.createElement('div'); dom.className = NODE_CSS_CLASS; if (this.options.caption) { const caption = document.createElement('div'); caption.className = CSS_PREFIX + 'caption'; caption.innerText = this.options.caption(node); dom.appendChild(caption); } node.dom = dom; this.options.applyMutations(node); return dom; } /** * Given a list of sizes, the 1-d space available * |space|, and a starting rectangle index |start|, compute a span of * rectangles that optimizes a pleasant aspect ratio. * * Returns [end, sum], where end is one past the last rectangle and sum is the * 2-d sum of the rectangles' areas. */ private selectSpan(children: Node[], space: number, start: number): {end: number; sum: number} { // Add rectangles one by one, stopping when aspect ratios begin to go // bad. Result is [start,end) covering the best run for this span. // http://scholar.google.com/scholar?cluster=5972512107845615474 let smin = children[start].size; // Smallest seen child so far. let smax = smin; // Largest child. let sum = 0; // Sum of children in this span. let lastScore = 0; // Best score yet found. let end = start; for (; end < children.length; end++) { const size = children[end].size; if (size < smin) smin = size; if (size > smax) smax = size; // Compute the relative squariness of the rectangles with this // additional rectangle included. const nextSum = sum + size; // Suppose you're laying out along the x axis, so "space"" is the // available width. Then the height of the span of rectangles is // height = sum/space // // The largest rectangle potentially will be too wide. // Its width and width/height ratio is: // width = smax / height // width/height = (smax / (sum/space)) / (sum/space) // = (smax * space * space) / (sum * sum) // // The smallest rectangle potentially will be too narrow. // Its width and height/width ratio is: // width = smin / height // height/width = (sum/space) / (smin / (sum/space)) // = (sum * sum) / (smin * space * space) // // Take the larger of these two ratios as the measure of the // worst non-squarenesss. const score = Math.max( (smax * space * space) / (nextSum * nextSum), (nextSum * nextSum) / (smin * space * space), ); if (lastScore && score > lastScore) { // Including this additional rectangle produces worse squareness than // without it. We're done. break; } lastScore = score; sum = nextSum; } return {end, sum}; } /** Creates and positions child DOM for a node. */ private layoutChildren(node: Node, level: number, width: number, height: number) { const total: number = node.size; const children = node.children; if (!children) return; // We use box-sizing: border-box so CSS 'width' etc include the border. // With 0 padding we want children to perfectly overlap their parent, // so we start with offsets of -1 (to start at the same point as the // parent) and create each box 1px larger than necessary (to make // adjoining borders overlap). let x1 = -1, y1 = -1, x2 = width - 1, y2 = height - 1; const spacing = 0; // TODO: this.options.spacing; const padding = this.options.padding; y1 += padding[0]; if (padding[1]) { // If there's any right-padding, subtract an extra pixel to allow for the // boxes being one pixel wider than necessary. x2 -= padding[1] + 1; } y2 -= padding[2]; x1 += padding[3]; let i: number = 0; if (this.options.showChildren(node, x2 - x1, y2 - y1)) { const scale = Math.sqrt(total / ((x2 - x1) * (y2 - y1))); var x = x1, y = y1; children: for (let start = 0; start < children.length; ) { x = x1; const space = scale * (x2 - x1); const {end, sum} = this.selectSpan(children, space, start); if (sum / total < this.options.lowerBound) break; const height = sum / space; const heightPx = Math.round(height / scale) + 1; for (i = start; i < end; i++) { const child = children[i]; const size = child.size; const width = size / height; const widthPx = Math.round(width / scale) + 1; if (!this.options.showNode(child, widthPx - spacing, heightPx - spacing)) { break children; } const needsAppend = child.dom == null; const dom = this.ensureDOM(child); const style = dom.style; style.left = px(x); style.width = px(widthPx - spacing); style.top = px(y); style.height = px(heightPx - spacing); if (needsAppend) { node.dom!.appendChild(dom); } this.layoutChildren(child, level + 1, widthPx, heightPx); // -1 so inner borders overlap. x += widthPx - 1; } // -1 so inner borders overlap. y += heightPx - 1; start = end; } } // Remove the DOM for any children we didn't visit. // These can be created if we zoomed in then out. for (; i < children.length; i++) { if (!children[i].dom) break; children[i].dom!.parentNode!.removeChild(children[i].dom!); children[i].dom = undefined; } } /** * Creates the full treemap in a container element. * The treemap is sized to the size of the container. */ render(container: HTMLElement) { addCSS(container); const dom = this.ensureDOM(this.node); const width = container.offsetWidth; const height = container.offsetHeight; dom.onclick = (e) => { let node: Element | null = e.target as Element; while (!isDOMNode(node)) { node = node.parentElement; if (!node) return; } let address = getAddress(node); this.zoom(address); }; dom.style.width = width + 'px'; dom.style.height = height + 'px'; container.appendChild(dom); this.layoutChildren(this.node, 0, width, height); } /** * Zooms the treemap to display a specific node. * See getAddress() for a discussion of what address means. */ zoom(address: number[]) { let node = this.node; const [padTop, padRight, padBottom, padLeft] = this.options.padding; let width = node.dom!.offsetWidth; let height = node.dom!.offsetHeight; for (const index of address) { width -= padLeft + padRight; height -= padTop + padBottom; if (!node.children) throw new Error('bad address'); for (const c of node.children) { if (c.dom) c.dom.style.zIndex = '0'; } node = node.children[index]; const style = node.dom!.style; style.zIndex = '1'; // See discussion in layout() about positioning. style.left = px(padLeft - 1); style.width = px(width); style.top = px(padTop - 1); style.height = px(height); } this.layoutChildren(node, 0, width, height); } } /** Main entry point; renders a tree into an HTML container. */ export function render(container: HTMLElement, node: Node, options: Partial<Options>) { new TreeMap(node, options).render(container); }
{ "end_byte": 11271, "start_byte": 3527, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/webtreemap/treemap.ts" }
angular/devtools/projects/ng-devtools/src/lib/vendor/webtreemap/BUILD.bazel_0_209
load("//devtools/tools:typescript.bzl", "ts_library") package(default_visibility = ["//:__subpackages__"]) ts_library( name = "webtreemap", srcs = [ "tree.ts", "treemap.ts", ], )
{ "end_byte": 209, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/webtreemap/BUILD.bazel" }
angular/devtools/projects/ng-devtools/src/lib/vendor/webtreemap/tree.ts_0_2967
/** * Copyright 2019 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Node is the expected shape of input data. */ export interface Node { /** * id is optional but can be used to identify each node. * It should be unique among nodes at the same level. */ id?: string; /** size should be >= the sum of the children's size. */ size: number; /** children should be sorted by size in descending order. */ children?: Node[]; /** dom node will be created and associated with the data. */ dom?: HTMLElement; } /** * treeify converts an array of [path, size] pairs into a tree. * Paths are /-delimited ids. */ export function treeify(data: Array<[string, number]>): Node { const tree: Node = {size: 0}; for (const [path, size] of data) { const parts = path.replace(/\/$/, '').split('/'); let t = tree; while (parts.length > 0) { const id = parts.shift(); if (!t.children) t.children = []; let child = t.children.find((c) => c.id === id); if (!child) { child = {id, size: 0}; t.children.push(child); } if (parts.length === 0) { if (child.size !== 0) { throw new Error(`duplicate path ${path} ${child.size}`); } child.size = size; } t = child; } } return tree; } /** * flatten flattens nodes that have only one child. * @param join If given, a function that joins the names of the parent and * child. */ export function flatten(n: Node, join = (parent: string, child: string) => `${parent}/${child}`) { if (n.children) { for (const c of n.children) { flatten(c, join); } if (n.children.length === 1) { const child = n.children[0]; n.id += '/' + child.id; n.children = child.children; } } } /** * rollup fills in the size attribute for nodes by summing their children. * * Note that it's legal for input data to have a node with a size larger * than the sum of its children, perhaps because some data was left out. */ export function rollup(n: Node) { if (!n.children) return; let total = 0; for (const c of n.children) { rollup(c); total += c.size; } if (total > n.size) n.size = total; } /** * sort sorts a tree by size, descending. */ export function sort(n: Node) { if (!n.children) return; for (const c of n.children) { sort(c); } n.children.sort((a, b) => b.size - a.size); }
{ "end_byte": 2967, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/webtreemap/tree.ts" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/LICENSE_0_10172
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS
{ "end_byte": 10172, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/LICENSE" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/LICENSE_10174_11347
APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2017 Bertrand Gaillard Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
{ "end_byte": 11347, "start_byte": 10174, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/LICENSE" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/BUILD.bazel_0_440
load("//devtools/tools:ng_module.bzl", "ng_module") package(default_visibility = ["//visibility:public"]) ng_module( name = "angular-split", srcs = ["public_api.ts"], deps = [ "//devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib", "//devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component:split", "//packages/core", "@npm//@types", "@npm//rxjs", ], )
{ "end_byte": 440, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/BUILD.bazel" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/public_api.ts_0_201
// tslint:disable /* * Public API Surface of angular-split */ export {SplitComponent} from './lib/component/split.component'; export {SplitAreaDirective} from './lib/component/splitArea.directive';
{ "end_byte": 201, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/public_api.ts" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/BUILD.bazel_0_428
load("//devtools/tools:ng_module.bzl", "ng_module") package(default_visibility = ["//visibility:public"]) ng_module( name = "lib", srcs = glob( include = [ "*.ts", ], ), deps = [ "//devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component:split", "//packages/common", "//packages/core", "@npm//@types", "@npm//rxjs", ], )
{ "end_byte": 428, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/BUILD.bazel" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/split.component.ts_0_3686
// tslint:disable import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, Input, NgZone, OnDestroy, Output, QueryList, Renderer2, ViewChildren, } from '@angular/core'; import {Observable, Subject, Subscriber} from 'rxjs'; import {debounceTime} from 'rxjs/operators'; import { IArea, IAreaSnapshot, IOutputAreaSizes, IOutputData, IPoint, ISplitSnapshot, } from './interface'; import {SplitAreaDirective} from './splitArea.directive'; import { getAreaMaxSize, getAreaMinSize, getElementPixelSize, getGutterSideAbsorptionCapacity, getInputBoolean, getInputPositiveNumber, getPointFromEvent, isUserSizesValid, updateAreaSize, } from './utils'; /** * angular-split * * * PERCENT MODE ([unit]="'percent'") * ___________________________________________________________________________________________ * | A [g1] B [g2] C [g3] D [g4] E | * |-------------------------------------------------------------------------------------------| * | 20 30 20 15 15 | <-- * [size]="x" | 10px 10px 10px 10px | <-- * [gutterSize]="10" |calc(20% - 8px) calc(30% - 12px) calc(20% - 8px) calc(15% - 6px) * calc(15% - 6px)| <-- CSS flex-basis property (with flex-grow&shrink at 0) | 152px 228px 152px * 114px 114px | <-- el.getBoundingClientRect().width * |___________________________________________________________________________________________| * 800px <-- * el.getBoundingClientRect().width flex-basis = calc( { area.size }% - { area.size/100 * * nbGutter*gutterSize }px ); * * * PIXEL MODE ([unit]="'pixel'") * ___________________________________________________________________________________________ * | A [g1] B [g2] C [g3] D [g4] E | * |-------------------------------------------------------------------------------------------| * | 100 250 * 150 100 | <-- * [size]="y" | 10px 10px 10px 10px | <-- * [gutterSize]="10" | 0 0 100px 0 0 250px 1 1 auto 0 0 150px 0 0 * 100px | <-- CSS flex property (flex-grow/flex-shrink/flex-basis) | 100px 250px * 200px 150px 100px | <-- el.getBoundingClientRect().width * |___________________________________________________________________________________________| * 800px <-- * el.getBoundingClientRect().width * */ @Component({ selector: 'as-split', exportAs: 'asSplit', changeDetection: ChangeDetectionStrategy.OnPush, styleUrls: [`./split.component.scss`], template: ` <ng-content></ng-content> @for (_ of displayedAreas; track $index) { @if ($last === false) { <div #gutterEls class="as-split-gutter" [style.flex-basis.px]="gutterSize" [style.order]="$index * 2 + 1" (mousedown)="startDragging($event, $index * 2 + 1, $index + 1)" (touchstart)="startDragging($event, $index * 2 + 1, $index + 1)" (mouseup)="clickGutter($event, $index + 1)" (touchend)="clickGutter($event, $index + 1)" > <div class="as-split-gutter-icon"></div> </div> } }`, standalone: true, }) export
{ "end_byte": 3686, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/split.component.ts" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/split.component.ts_3687_10903
class SplitComponent implements AfterViewInit, OnDestroy { private _direction: 'horizontal' | 'vertical' = 'horizontal'; @Input() set direction(v: 'horizontal' | 'vertical') { this._direction = v === 'vertical' ? 'vertical' : 'horizontal'; this.renderer.addClass(this.elRef.nativeElement, `as-${this._direction}`); this.renderer.removeClass( this.elRef.nativeElement, `as-${this._direction === 'vertical' ? 'horizontal' : 'vertical'}`, ); this.build(false, false); } get direction(): 'horizontal' | 'vertical' { return this._direction; } //// private _unit: 'percent' | 'pixel' = 'percent'; @Input() set unit(v: 'percent' | 'pixel') { this._unit = v === 'pixel' ? 'pixel' : 'percent'; this.renderer.addClass(this.elRef.nativeElement, `as-${this._unit}`); this.renderer.removeClass( this.elRef.nativeElement, `as-${this._unit === 'pixel' ? 'percent' : 'pixel'}`, ); this.build(false, true); } get unit(): 'percent' | 'pixel' { return this._unit; } //// private _gutterSize: number = 11; @Input() set gutterSize(v: number | null) { this._gutterSize = getInputPositiveNumber(v, 11); this.build(false, false); } get gutterSize(): number | null { return this._gutterSize; } //// private _gutterStep: number = 1; @Input() set gutterStep(v: number) { this._gutterStep = getInputPositiveNumber(v, 1); } get gutterStep(): number { return this._gutterStep; } //// private _restrictMove: boolean = false; @Input() set restrictMove(v: boolean) { this._restrictMove = getInputBoolean(v); } get restrictMove(): boolean { return this._restrictMove; } //// private _useTransition: boolean = false; @Input() set useTransition(v: boolean) { this._useTransition = getInputBoolean(v); if (this._useTransition) this.renderer.addClass(this.elRef.nativeElement, 'as-transition'); else this.renderer.removeClass(this.elRef.nativeElement, 'as-transition'); } get useTransition(): boolean { return this._useTransition; } //// private _disabled: boolean = false; @Input() set disabled(v: boolean) { this._disabled = getInputBoolean(v); if (this._disabled) this.renderer.addClass(this.elRef.nativeElement, 'as-disabled'); else this.renderer.removeClass(this.elRef.nativeElement, 'as-disabled'); } get disabled(): boolean { return this._disabled; } //// private _dir: 'ltr' | 'rtl' = 'ltr'; @Input() set dir(v: 'ltr' | 'rtl') { this._dir = v === 'rtl' ? 'rtl' : 'ltr'; this.renderer.setAttribute(this.elRef.nativeElement, 'dir', this._dir); } get dir(): 'ltr' | 'rtl' { return this._dir; } //// private _gutterDblClickDuration: number = 0; @Input() set gutterDblClickDuration(v: number) { this._gutterDblClickDuration = getInputPositiveNumber(v, 0); } get gutterDblClickDuration(): number { return this._gutterDblClickDuration; } //// @Output() dragStart = new EventEmitter<IOutputData>(false); @Output() dragEnd = new EventEmitter<IOutputData>(false); @Output() gutterClick = new EventEmitter<IOutputData>(false); @Output() gutterDblClick = new EventEmitter<IOutputData>(false); private transitionEndSubscriber: Subscriber<IOutputAreaSizes> | null = null; @Output() get transitionEnd(): Observable<IOutputAreaSizes> { return new Observable((subscriber) => (this.transitionEndSubscriber = subscriber)).pipe( debounceTime<any>(20), ); } private dragProgressSubject: Subject<IOutputData> = new Subject(); dragProgress$: Observable<IOutputData> = this.dragProgressSubject.asObservable(); //// private isDragging: boolean = false; private dragListeners: Array<Function> = []; private snapshot: ISplitSnapshot | null = null; private startPoint: IPoint | null = null; private endPoint: IPoint | null = null; public readonly displayedAreas: Array<IArea> = []; private readonly hidedAreas: Array<IArea> = []; @ViewChildren('gutterEls') private gutterEls!: QueryList<ElementRef>; constructor( private ngZone: NgZone, private elRef: ElementRef, private cdRef: ChangeDetectorRef, private renderer: Renderer2, ) { // To force adding default class, could be override by user @Input() or not this.direction = this._direction; } public ngAfterViewInit() { this.ngZone.runOutsideAngular(() => { // To avoid transition at first rendering setTimeout(() => this.renderer.addClass(this.elRef.nativeElement, 'as-init')); }); } private getNbGutters(): number { return this.displayedAreas.length === 0 ? 0 : this.displayedAreas.length - 1; } public addArea(component: SplitAreaDirective): void { const newArea: IArea = { component, order: 0, size: 0, minSize: null, maxSize: null, }; if (component.visible === true) { this.displayedAreas.push(newArea); this.build(true, true); } else { this.hidedAreas.push(newArea); } } public removeArea(component: SplitAreaDirective): void { if (this.displayedAreas.some((a) => a.component === component)) { const area = this.displayedAreas.find((a) => a.component === component); this.displayedAreas.splice(this.displayedAreas.indexOf(area!), 1); this.build(true, true); } else if (this.hidedAreas.some((a) => a.component === component)) { const area = this.hidedAreas.find((a) => a.component === component); this.hidedAreas.splice(this.hidedAreas.indexOf(area!), 1); } } public updateArea( component: SplitAreaDirective, resetOrders: boolean, resetSizes: boolean, ): void { if (component.visible === true) { this.build(resetOrders, resetSizes); } } public showArea(component: SplitAreaDirective): void { const area = this.hidedAreas.find((a) => a.component === component); if (area === undefined) { return; } const areas = this.hidedAreas.splice(this.hidedAreas.indexOf(area), 1); this.displayedAreas.push(...areas); this.build(true, true); } public hideArea(comp: SplitAreaDirective): void { const area = this.displayedAreas.find((a) => a.component === comp); if (area === undefined) { return; } const areas = this.displayedAreas.splice(this.displayedAreas.indexOf(area), 1); areas.forEach((area) => { area.order = 0; area.size = 0; }); this.hidedAreas.push(...areas); this.build(true, true); } public getVisibleAreaSizes(): IOutputAreaSizes { return this.displayedAreas.map((a) => (a.size === null ? '*' : a.size)); } public setVisibleAreaSizes(sizes: IOutputAreaSizes): boolean { if (sizes.length !== this.displayedAreas.length) { return false; } const formattedSizes = sizes.map((s) => getInputPositiveNumber(s, null)); const isValid = isUserSizesValid(this.unit, formattedSizes); if (isValid === false) { return false; } // @ts-ignore this.displayedAreas.forEach((area, i) => (area.component._size = formattedSizes[i])); this.build(false, true); return true; }
{ "end_byte": 10903, "start_byte": 3687, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/split.component.ts" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/split.component.ts_10907_17037
private build(resetOrders: boolean, resetSizes: boolean): void { this.stopDragging(); // ¤ AREAS ORDER if (resetOrders === true) { // If user provided 'order' for each area, use it to sort them. if (this.displayedAreas.every((a) => a.component.order !== null)) { this.displayedAreas.sort((a, b) => <number>a.component.order - <number>b.component.order); } // Then set real order with multiples of 2, numbers between will be used by gutters. this.displayedAreas.forEach((area, i) => { area.order = i * 2; area.component.setStyleOrder(area.order); }); } // ¤ AREAS SIZE if (resetSizes === true) { const useUserSizes = isUserSizesValid( this.unit, this.displayedAreas.map((a) => a.component.size), ); switch (this.unit) { case 'percent': { const defaultSize = 100 / this.displayedAreas.length; this.displayedAreas.forEach((area) => { area.size = useUserSizes ? <number>area.component.size : defaultSize; area.minSize = getAreaMinSize(area); area.maxSize = getAreaMaxSize(area); }); break; } case 'pixel': { if (useUserSizes) { this.displayedAreas.forEach((area) => { area.size = area.component.size; area.minSize = getAreaMinSize(area); area.maxSize = getAreaMaxSize(area); }); } else { const wildcardSizeAreas = this.displayedAreas.filter((a) => a.component.size === null); // No wildcard area > Need to select one arbitrarily > first if (wildcardSizeAreas.length === 0 && this.displayedAreas.length > 0) { this.displayedAreas.forEach((area, i) => { area.size = i === 0 ? null : area.component.size; area.minSize = i === 0 ? null : getAreaMinSize(area); area.maxSize = i === 0 ? null : getAreaMaxSize(area); }); } // More than one wildcard area > Need to keep only one arbitrarily > first else if (wildcardSizeAreas.length > 1) { let alreadyGotOne = false; this.displayedAreas.forEach((area) => { if (area.component.size === null) { if (alreadyGotOne === false) { area.size = null; area.minSize = null; area.maxSize = null; alreadyGotOne = true; } else { area.size = 100; area.minSize = null; area.maxSize = null; } } else { area.size = area.component.size; area.minSize = getAreaMinSize(area); area.maxSize = getAreaMaxSize(area); } }); } } break; } } } this.refreshStyleSizes(); this.cdRef.markForCheck(); } private refreshStyleSizes(): void { /////////////////////////////////////////// // PERCENT MODE if (this.unit === 'percent') { // Only one area > flex-basis 100% if (this.displayedAreas.length === 1) { this.displayedAreas[0].component.setStyleFlex(0, 0, `100%`, false, false); } // Multiple areas > use each percent basis else { // Size in pixels const visibleGutterSize = 1; // Use visible gutter size in calculation instead of the invisible draggable gutter const sumGutterSize = this.getNbGutters() * visibleGutterSize; this.displayedAreas.forEach((area) => { area.component.setStyleFlex( 0, 0, `calc( ${area.size}% - ${(<number>area.size / 100) * sumGutterSize}px )`, area.minSize !== null && area.minSize === area.size ? true : false, area.maxSize !== null && area.maxSize === area.size ? true : false, ); }); } } /////////////////////////////////////////// // PIXEL MODE else if (this.unit === 'pixel') { this.displayedAreas.forEach((area) => { // Area with wildcard size if (area.size === null) { if (this.displayedAreas.length === 1) { area.component.setStyleFlex(1, 1, `100%`, false, false); } else { area.component.setStyleFlex(1, 1, `auto`, false, false); } } // Area with pixel size else { // Only one area > flex-basis 100% if (this.displayedAreas.length === 1) { area.component.setStyleFlex(0, 0, `100%`, false, false); } // Multiple areas > use each pixel basis else { area.component.setStyleFlex( 0, 0, `${area.size}px`, area.minSize !== null && area.minSize === area.size ? true : false, area.maxSize !== null && area.maxSize === area.size ? true : false, ); } } }); } } _clickTimeout: number | null = null; public clickGutter(event: MouseEvent | TouchEvent, gutterNum: number): void { const tempPoint = getPointFromEvent(event); // Be sure mouseup/touchend happened at same point as mousedown/touchstart to trigger // click/dblclick if ( this.startPoint && this.startPoint.x === tempPoint!.x && this.startPoint.y === tempPoint!.y ) { // If timeout in progress and new click > clearTimeout & dblClickEvent if (this._clickTimeout !== null) { window.clearTimeout(this._clickTimeout); this._clickTimeout = null; this.notify('dblclick', gutterNum); this.stopDragging(); } // Else start timeout to call clickEvent at end else { this._clickTimeout = window.setTimeout(() => { this._clickTimeout = null; this.notify('click', gutterNum); this.stopDragging(); }, this.gutterDblClickDuration); } } }
{ "end_byte": 17037, "start_byte": 10907, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/split.component.ts" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/split.component.ts_17041_25048
blic startDragging( event: MouseEvent | TouchEvent, gutterOrder: number, gutterNum: number, ): void { event.preventDefault(); event.stopPropagation(); this.startPoint = getPointFromEvent(event); if (this.startPoint === null || this.disabled === true) { return; } this.snapshot = { gutterNum, lastSteppedOffset: 0, allAreasSizePixel: getElementPixelSize(this.elRef, this.direction) - this.getNbGutters() * this.gutterSize!, allInvolvedAreasSizePercent: 100, areasBeforeGutter: [], areasAfterGutter: [], }; this.displayedAreas.forEach((area) => { const areaSnapshot: IAreaSnapshot = { area, sizePixelAtStart: getElementPixelSize(area.component.elRef, this.direction), sizePercentAtStart: (this.unit === 'percent' ? area.size : -1) as number, // If pixel mode, anyway, will not be used. }; if (area.order < gutterOrder) { if (this.restrictMove === true) { this.snapshot!.areasBeforeGutter = [areaSnapshot]; } else { this.snapshot!.areasBeforeGutter.unshift(areaSnapshot); } } else if (area.order > gutterOrder) { if (this.restrictMove === true) { if (this.snapshot!.areasAfterGutter.length === 0) this.snapshot!.areasAfterGutter = [areaSnapshot]; } else { this.snapshot!.areasAfterGutter.push(areaSnapshot); } } }); this.snapshot.allInvolvedAreasSizePercent = [ ...this.snapshot.areasBeforeGutter, ...this.snapshot.areasAfterGutter, ].reduce((t, a) => t + a.sizePercentAtStart, 0); if ( this.snapshot.areasBeforeGutter.length === 0 || this.snapshot.areasAfterGutter.length === 0 ) { return; } this.dragListeners.push( this.renderer.listen('document', 'mouseup', this.stopDragging.bind(this)), ); this.dragListeners.push( this.renderer.listen('document', 'touchend', this.stopDragging.bind(this)), ); this.dragListeners.push( this.renderer.listen('document', 'touchcancel', this.stopDragging.bind(this)), ); this.ngZone.runOutsideAngular(() => { this.dragListeners.push( this.renderer.listen('document', 'mousemove', this.dragEvent.bind(this)), ); this.dragListeners.push( this.renderer.listen('document', 'touchmove', this.dragEvent.bind(this)), ); }); this.displayedAreas.forEach((area) => area.component.lockEvents()); this.isDragging = true; this.renderer.addClass(this.elRef.nativeElement, 'as-dragging'); this.renderer.addClass( this.gutterEls.toArray()[this.snapshot.gutterNum - 1].nativeElement, 'as-dragged', ); this.notify('start', this.snapshot.gutterNum); } private dragEvent(event: MouseEvent | TouchEvent): void { event.preventDefault(); event.stopPropagation(); if (this._clickTimeout !== null) { window.clearTimeout(this._clickTimeout); this._clickTimeout = null; } if (this.isDragging === false) { return; } this.endPoint = getPointFromEvent(event); if (this.endPoint === null) { return; } // Calculate steppedOffset let offset = this.direction === 'horizontal' ? this.startPoint!.x - this.endPoint.x : this.startPoint!.y - this.endPoint.y; if (this.dir === 'rtl') { offset = -offset; } const steppedOffset = Math.round(offset / this.gutterStep) * this.gutterStep; if (steppedOffset === this.snapshot!.lastSteppedOffset) { return; } this.snapshot!.lastSteppedOffset = steppedOffset; // Need to know if each gutter side areas could reacts to steppedOffset let areasBefore = getGutterSideAbsorptionCapacity( this.unit, this.snapshot!.areasBeforeGutter, -steppedOffset, this.snapshot!.allAreasSizePixel, ); let areasAfter = getGutterSideAbsorptionCapacity( this.unit, this.snapshot!.areasAfterGutter, steppedOffset, this.snapshot!.allAreasSizePixel, ); // Each gutter side areas can't absorb all offset if (areasBefore.remain !== 0 && areasAfter.remain !== 0) { if (Math.abs(areasBefore.remain) === Math.abs(areasAfter.remain)) { } else if (Math.abs(areasBefore.remain) > Math.abs(areasAfter.remain)) { areasAfter = getGutterSideAbsorptionCapacity( this.unit, this.snapshot!.areasAfterGutter, steppedOffset + areasBefore.remain, this.snapshot!.allAreasSizePixel, ); } else { areasBefore = getGutterSideAbsorptionCapacity( this.unit, this.snapshot!.areasBeforeGutter, -(steppedOffset - areasAfter.remain), this.snapshot!.allAreasSizePixel, ); } } // Areas before gutter can't absorbs all offset > need to recalculate sizes for areas after // gutter. else if (areasBefore.remain !== 0) { areasAfter = getGutterSideAbsorptionCapacity( this.unit, this.snapshot!.areasAfterGutter, steppedOffset + areasBefore.remain, this.snapshot!.allAreasSizePixel, ); } // Areas after gutter can't absorbs all offset > need to recalculate sizes for areas before // gutter. else if (areasAfter.remain !== 0) { areasBefore = getGutterSideAbsorptionCapacity( this.unit, this.snapshot!.areasBeforeGutter, -(steppedOffset - areasAfter.remain), this.snapshot!.allAreasSizePixel, ); } if (this.unit === 'percent') { // Hack because of browser messing up with sizes using calc(X% - Ypx) -> // el.getBoundingClientRect() If not there, playing with gutters makes total going down // to 99.99875% then 99.99286%, 99.98986%,.. const all = [...areasBefore.list, ...areasAfter.list]; const areaToReset = all.find( (a) => a.percentAfterAbsorption !== 0 && a.percentAfterAbsorption !== a.areaSnapshot.area.minSize && a.percentAfterAbsorption !== a.areaSnapshot.area.maxSize, ); if (areaToReset) { areaToReset.percentAfterAbsorption = this.snapshot!.allInvolvedAreasSizePercent - all .filter((a) => a !== areaToReset) .reduce((total, a) => total + a.percentAfterAbsorption, 0); } } // Now we know areas could absorb steppedOffset, time to really update sizes areasBefore.list.forEach((item) => updateAreaSize(this.unit, item)); areasAfter.list.forEach((item) => updateAreaSize(this.unit, item)); this.refreshStyleSizes(); this.notify('progress', this.snapshot!.gutterNum); } private stopDragging(event?: Event): void { if (event) { event.preventDefault(); event.stopPropagation(); } if (this.isDragging === false) { return; } this.displayedAreas.forEach((area) => area.component.unlockEvents()); while (this.dragListeners.length > 0) { const fct = this.dragListeners.pop(); if (fct) fct(); } // Warning: Have to be before "notify('end')" // because "notify('end')"" can be linked to "[size]='x'" > "build()" > "stopDragging()" this.isDragging = false; // If moved from starting point, notify end if ( this.endPoint && (this.startPoint!.x !== this.endPoint.x || this.startPoint!.y !== this.endPoint.y) ) { this.notify('end', this.snapshot!.gutterNum); } this.renderer.removeClass(this.elRef.nativeElement, 'as-dragging'); this.renderer.removeClass( this.gutterEls.toArray()[this.snapshot!.gutterNum - 1].nativeElement, 'as-dragged', ); this.snapshot = null; // Needed to let (click)="clickGutter(...)" event run and verify if mouse moved or not this.ngZone.runOutsideAngular(() => { setTimeout(() => { this.startPoint = null; this.endPoint = null; }); }); }
{ "end_byte": 25048, "start_byte": 17041, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/split.component.ts" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/split.component.ts_25052_25985
blic notify( type: 'start' | 'progress' | 'end' | 'click' | 'dblclick' | 'transitionEnd', gutterNum: number, ): void { const sizes = this.getVisibleAreaSizes(); if (type === 'start') { this.dragStart.emit({gutterNum, sizes}); } else if (type === 'end') { this.dragEnd.emit({gutterNum, sizes}); } else if (type === 'click') { this.gutterClick.emit({gutterNum, sizes}); } else if (type === 'dblclick') { this.gutterDblClick.emit({gutterNum, sizes}); } else if (type === 'transitionEnd') { if (this.transitionEndSubscriber) { this.ngZone.run(() => this.transitionEndSubscriber?.next(sizes)); } } else if (type === 'progress') { // Stay outside zone to allow users do what they want about change detection mechanism. this.dragProgressSubject.next({gutterNum, sizes}); } } public ngOnDestroy(): void { this.stopDragging(); } }
{ "end_byte": 25985, "start_byte": 25052, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/split.component.ts" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/splitArea.directive.ts_0_4500
// tslint:disable import {Directive, ElementRef, Input, NgZone, OnDestroy, OnInit, Renderer2} from '@angular/core'; import {SplitComponent} from '../component/split.component'; import {getInputBoolean, getInputPositiveNumber} from './utils'; @Directive({ selector: 'as-split-area, [as-split-area]', exportAs: 'asSplitArea', standalone: true, }) export class SplitAreaDirective implements OnInit, OnDestroy { private _order: number | null = null; @Input() set order(v: number | null) { this._order = getInputPositiveNumber(v, null); this.split.updateArea(this, true, false); } get order(): number | null { return this._order; } //// private _size: number | null = null; @Input() set size(v: number | null) { this._size = getInputPositiveNumber(v, null); this.split.updateArea(this, false, true); } get size(): number | null { return this._size; } //// private _minSize: number | null = null; @Input() set minSize(v: number | null) { this._minSize = getInputPositiveNumber(v, null); this.split.updateArea(this, false, true); } get minSize(): number | null { return this._minSize; } //// private _maxSize: number | null = null; @Input() set maxSize(v: number | null) { this._maxSize = getInputPositiveNumber(v, null); this.split.updateArea(this, false, true); } get maxSize(): number | null { return this._maxSize; } //// private _lockSize: boolean = false; @Input() set lockSize(v: boolean) { this._lockSize = getInputBoolean(v); this.split.updateArea(this, false, true); } get lockSize(): boolean { return this._lockSize; } //// private _visible: boolean = true; @Input() set visible(v: boolean) { this._visible = getInputBoolean(v); if (this._visible) { this.split.showArea(this); this.renderer.removeClass(this.elRef.nativeElement, 'as-hidden'); } else { this.split.hideArea(this); this.renderer.addClass(this.elRef.nativeElement, 'as-hidden'); } } get visible(): boolean { return this._visible; } //// private transitionListener!: Function; private readonly lockListeners: Array<Function> = []; constructor( private ngZone: NgZone, public elRef: ElementRef, private renderer: Renderer2, private split: SplitComponent, ) { this.renderer.addClass(this.elRef.nativeElement, 'as-split-area'); } public ngOnInit(): void { this.split.addArea(this); this.ngZone.runOutsideAngular(() => { this.transitionListener = this.renderer.listen( this.elRef.nativeElement, 'transitionend', (event: TransitionEvent) => { // Limit only flex-basis transition to trigger the event if (event.propertyName === 'flex-basis') { this.split.notify('transitionEnd', -1); } }, ); }); } public setStyleOrder(value: number): void { this.renderer.setStyle(this.elRef.nativeElement, 'order', value); } public setStyleFlex( grow: number, shrink: number, basis: string, isMin: boolean, isMax: boolean, ): void { // Need 3 separated properties to work on IE11 // (https://github.com/angular/flex-layout/issues/323) this.renderer.setStyle(this.elRef.nativeElement, 'flex-grow', grow); this.renderer.setStyle(this.elRef.nativeElement, 'flex-shrink', shrink); this.renderer.setStyle(this.elRef.nativeElement, 'flex-basis', basis); if (isMin === true) this.renderer.addClass(this.elRef.nativeElement, 'as-min'); else this.renderer.removeClass(this.elRef.nativeElement, 'as-min'); if (isMax === true) this.renderer.addClass(this.elRef.nativeElement, 'as-max'); else this.renderer.removeClass(this.elRef.nativeElement, 'as-max'); } public lockEvents(): void { this.ngZone.runOutsideAngular(() => { this.lockListeners.push( this.renderer.listen(this.elRef.nativeElement, 'selectstart', (e: Event) => false), ); this.lockListeners.push( this.renderer.listen(this.elRef.nativeElement, 'dragstart', (e: Event) => false), ); }); } public unlockEvents(): void { while (this.lockListeners.length > 0) { const fct = this.lockListeners.pop(); if (fct) fct(); } } public ngOnDestroy(): void { this.unlockEvents(); if (this.transitionListener) { this.transitionListener(); } this.split.removeArea(this); } }
{ "end_byte": 4500, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/splitArea.directive.ts" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/split.component.scss_0_3399
:host { display: flex; flex-wrap: nowrap; justify-content: flex-start; align-items: stretch; overflow: hidden; width: 100%; height: 100%; & > .as-split-gutter { flex-grow: 0; flex-shrink: 0; display: flex; align-items: center; justify-content: center; // Transparent gutter to mimic chrome devtools invisible gutter technique. background-color: transparent; & > .as-split-gutter-icon { width: 100%; height: 100%; background-position: center center; background-repeat: no-repeat; } } ::ng-deep > .as-split-area { flex-grow: 0; flex-shrink: 0; overflow-x: hidden; overflow-y: hidden; /* When <as-split-area [visible]="false"> force size to 0. */ &.as-hidden { flex: 0 1 0 !important; overflow-x: hidden; overflow-y: hidden; } } &.as-horizontal { flex-direction: row; & > .as-split-gutter { flex-direction: row; cursor: ew-resize; height: 100%; // <- Fix safari bug about gutter height when direction is horizontal. position: relative; left: 5px; // position so that the visible border aligns with the middle pixels of the invisible gutter & > .as-split-gutter-icon { background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAeCAYAAADkftS9AAAAIklEQVQoU2M4c+bMfxAGAgYYmwGrIIiDjrELjpo5aiZeMwF+yNnOs5KSvgAAAABJRU5ErkJggg=='); } } ::ng-deep > .as-split-area { height: 100%; &:not(:last-of-type) { margin-right: -9px; // size of invisible gutter, pushes split area right so that content can be displayed all the way to the visible border } &:not(:first-of-type) { border-left: 1px solid #eeeeee; } } } &.as-vertical { flex-direction: column; & > .as-split-gutter { flex-direction: column; cursor: ns-resize; width: 100%; position: relative; top: 5px; // position so that the visible border aligns with the middle pixels of the invisible gutter .as-split-gutter-icon { background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAFCAMAAABl/6zIAAAABlBMVEUAAADMzMzIT8AyAAAAAXRSTlMAQObYZgAAABRJREFUeAFjYGRkwIMJSeMHlBkOABP7AEGzSuPKAAAAAElFTkSuQmCC'); } } ::ng-deep > .as-split-area { width: 100%; &:not(:last-of-type) { margin-bottom: -9px; // size of invisible gutter, pushes split area down so that content can be displayed all the way to the visible border } &:not(:first-of-type) { border-top: 1px solid #eeeeee; } &.as-hidden { max-width: 0; } } } /* When disabled remove gutters background image and specific cursor. */ &.as-disabled { & > .as-split-gutter { cursor: default; } } /* Add transition only when transition enabled + split initialized + not currently dragging. */ &.as-transition.as-init:not(.as-dragging) { & > .as-split-gutter, ::ng-deep > .as-split-area { transition: flex-basis 0.3s; } } } :host-context(.dark-theme) { &.as-horizontal { ::ng-deep > .as-split-area { &:not(:first-of-type) { border-left: 1px solid #3f3f3f; } } } &.as-vertical { ::ng-deep > .as-split-area { &:not(:first-of-type) { border-top: 1px solid #3f3f3f; } } } }
{ "end_byte": 3399, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/split.component.scss" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/utils.ts_0_6062
// tslint:disable import {ElementRef} from '@angular/core'; import { IArea, IAreaAbsorptionCapacity, IAreaSnapshot, IPoint, ISplitSideAbsorptionCapacity, } from './interface'; export function getPointFromEvent(event: MouseEvent | TouchEvent): IPoint | null { // TouchEvent if ( (<TouchEvent>event).changedTouches !== undefined && (<TouchEvent>event).changedTouches.length > 0 ) { return { x: (<TouchEvent>event).changedTouches[0].clientX, y: (<TouchEvent>event).changedTouches[0].clientY, }; } // MouseEvent else if ((<MouseEvent>event).clientX !== undefined && (<MouseEvent>event).clientY !== undefined) { return { x: (<MouseEvent>event).clientX, y: (<MouseEvent>event).clientY, }; } return null; } export function getElementPixelSize( elRef: ElementRef, direction: 'horizontal' | 'vertical', ): number { const rect = (<HTMLElement>elRef.nativeElement).getBoundingClientRect(); return direction === 'horizontal' ? rect.width : rect.height; } export function getInputBoolean(v: any): boolean { return typeof v === 'boolean' ? v : v === 'false' ? false : true; } export function getInputPositiveNumber<T>(v: any, defaultValue: T): number | T { if (v === null || v === undefined) return defaultValue; v = Number(v); return !isNaN(v) && v >= 0 ? v : defaultValue; } export function isUserSizesValid( unit: 'percent' | 'pixel', sizes: Array<number | null>, ): boolean | undefined | void { // All sizes have to be not null and total should be 100 if (unit === 'percent') { const total = sizes.reduce((total, s) => (s !== null ? total! + s : total), 0); return sizes.every((s) => s !== null) && total! > 99.9 && total! < 100.1; } // A size at null is mandatory but only one. if (unit === 'pixel') { return sizes.filter((s) => s === null).length === 1; } } export function getAreaMinSize(a: IArea): null | number { if (a.size === null) { return null; } if (a.component.lockSize === true) { return a.size; } if (a.component.minSize === null) { return null; } if (a.component.minSize > a.size) { return a.size; } return a.component.minSize; } export function getAreaMaxSize(a: IArea): null | number { if (a.size === null) { return null; } if (a.component.lockSize === true) { return a.size; } if (a.component.maxSize === null) { return null; } if (a.component.maxSize < a.size) { return a.size; } return a.component.maxSize; } export function getGutterSideAbsorptionCapacity( unit: 'percent' | 'pixel', sideAreas: Array<IAreaSnapshot>, pixels: number, allAreasSizePixel: number, ): ISplitSideAbsorptionCapacity { return sideAreas.reduce( (acc, area) => { const res = getAreaAbsorptionCapacity(unit, area, acc.remain, allAreasSizePixel); (acc.list as any).push(res); acc.remain = res!.pixelRemain; return acc; }, {remain: pixels, list: []}, ); } function getAreaAbsorptionCapacity( unit: 'percent' | 'pixel', areaSnapshot: IAreaSnapshot, pixels: number, allAreasSizePixel: number, ): IAreaAbsorptionCapacity | undefined | void { // No pain no gain if (pixels === 0) { return { areaSnapshot, pixelAbsorb: 0, percentAfterAbsorption: areaSnapshot.sizePercentAtStart, pixelRemain: 0, }; } // Area start at zero and need to be reduced, not possible if (areaSnapshot.sizePixelAtStart === 0 && pixels < 0) { return { areaSnapshot, pixelAbsorb: 0, percentAfterAbsorption: 0, pixelRemain: pixels, }; } if (unit === 'percent') { return getAreaAbsorptionCapacityPercent(areaSnapshot, pixels, allAreasSizePixel); } if (unit === 'pixel') { return getAreaAbsorptionCapacityPixel(areaSnapshot, pixels, allAreasSizePixel); } } function getAreaAbsorptionCapacityPercent( areaSnapshot: IAreaSnapshot, pixels: number, allAreasSizePixel: number, ): IAreaAbsorptionCapacity | undefined | void { const tempPixelSize = areaSnapshot.sizePixelAtStart + pixels; const tempPercentSize = (tempPixelSize / allAreasSizePixel) * 100; // ENLARGE AREA if (pixels > 0) { // If maxSize & newSize bigger than it > absorb to max and return remaining pixels if (areaSnapshot.area.maxSize !== null && tempPercentSize > areaSnapshot.area.maxSize) { // Use area.area.maxSize as newPercentSize and return calculate pixels remaining const maxSizePixel = (areaSnapshot.area.maxSize / 100) * allAreasSizePixel; return { areaSnapshot, pixelAbsorb: maxSizePixel, percentAfterAbsorption: areaSnapshot.area.maxSize, pixelRemain: areaSnapshot.sizePixelAtStart + pixels - maxSizePixel, }; } return { areaSnapshot, pixelAbsorb: pixels, percentAfterAbsorption: tempPercentSize > 100 ? 100 : tempPercentSize, pixelRemain: 0, }; } // REDUCE AREA else if (pixels < 0) { // If minSize & newSize smaller than it > absorb to min and return remaining pixels if (areaSnapshot.area.minSize !== null && tempPercentSize < areaSnapshot.area.minSize) { // Use area.area.minSize as newPercentSize and return calculate pixels remaining const minSizePixel = (areaSnapshot.area.minSize / 100) * allAreasSizePixel; return { areaSnapshot, pixelAbsorb: minSizePixel, percentAfterAbsorption: areaSnapshot.area.minSize, pixelRemain: areaSnapshot.sizePixelAtStart + pixels - minSizePixel, }; } // If reduced under zero > return remaining pixels else if (tempPercentSize < 0) { // Use 0 as newPercentSize and return calculate pixels remaining return { areaSnapshot, pixelAbsorb: -areaSnapshot.sizePixelAtStart, percentAfterAbsorption: 0, pixelRemain: pixels + areaSnapshot.sizePixelAtStart, }; } return { areaSnapshot, pixelAbsorb: pixels, percentAfterAbsorption: tempPercentSize, pixelRemain: 0, }; } }
{ "end_byte": 6062, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/utils.ts" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/utils.ts_6064_8159
function getAreaAbsorptionCapacityPixel( areaSnapshot: IAreaSnapshot, pixels: number, containerSizePixel: number, ): IAreaAbsorptionCapacity | undefined | void { const tempPixelSize = areaSnapshot.sizePixelAtStart + pixels; // ENLARGE AREA if (pixels > 0) { // If maxSize & newSize bigger than it > absorb to max and return remaining pixels if (areaSnapshot.area.maxSize !== null && tempPixelSize > areaSnapshot.area.maxSize) { return { areaSnapshot, pixelAbsorb: areaSnapshot.area.maxSize - areaSnapshot.sizePixelAtStart, percentAfterAbsorption: -1, pixelRemain: tempPixelSize - areaSnapshot.area.maxSize, }; } return { areaSnapshot, pixelAbsorb: pixels, percentAfterAbsorption: -1, pixelRemain: 0, }; } // REDUCE AREA else if (pixels < 0) { // If minSize & newSize smaller than it > absorb to min and return remaining pixels if (areaSnapshot.area.minSize !== null && tempPixelSize < areaSnapshot.area.minSize) { return { areaSnapshot, pixelAbsorb: areaSnapshot.area.minSize + pixels - tempPixelSize, percentAfterAbsorption: -1, pixelRemain: tempPixelSize - areaSnapshot.area.minSize, }; } // If reduced under zero > return remaining pixels else if (tempPixelSize < 0) { return { areaSnapshot, pixelAbsorb: -areaSnapshot.sizePixelAtStart, percentAfterAbsorption: -1, pixelRemain: pixels + areaSnapshot.sizePixelAtStart, }; } return { areaSnapshot, pixelAbsorb: pixels, percentAfterAbsorption: -1, pixelRemain: 0, }; } } export function updateAreaSize(unit: 'percent' | 'pixel', item: IAreaAbsorptionCapacity) { if (unit === 'percent') { item.areaSnapshot.area.size = item.percentAfterAbsorption; } else if (unit === 'pixel') { // Update size except for the wildcard size area if (item.areaSnapshot.area.size !== null) { item.areaSnapshot.area.size = item.areaSnapshot.sizePixelAtStart + item.pixelAbsorb; } } }
{ "end_byte": 8159, "start_byte": 6064, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/utils.ts" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/interface.ts_0_1131
// tslint:disable import {SplitAreaDirective} from './splitArea.directive'; export interface IPoint { x: number; y: number; } export interface IArea { component: SplitAreaDirective; order: number; size: number | null; minSize: number | null; maxSize: number | null; } // CREATED ON DRAG START export interface ISplitSnapshot { gutterNum: number; allAreasSizePixel: number; allInvolvedAreasSizePercent: number; lastSteppedOffset: number; areasBeforeGutter: Array<IAreaSnapshot>; areasAfterGutter: Array<IAreaSnapshot>; } export interface IAreaSnapshot { area: IArea; sizePixelAtStart: number; sizePercentAtStart: number; } // CREATED ON DRAG PROGRESS export interface ISplitSideAbsorptionCapacity { remain: number; list: Array<IAreaAbsorptionCapacity>; } export interface IAreaAbsorptionCapacity { areaSnapshot: IAreaSnapshot; pixelAbsorb: number; percentAfterAbsorption: number; pixelRemain: number; } // CREATED TO SEND OUTSIDE export interface IOutputData { gutterNum: number; sizes: IOutputAreaSizes; } export interface IOutputAreaSizes extends Array<number | '*'> {}
{ "end_byte": 1131, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/interface.ts" }
angular/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/BUILD.bazel_0_553
load("//devtools/tools:ng_module.bzl", "ng_module") load("@io_bazel_rules_sass//:defs.bzl", "sass_binary") package(default_visibility = ["//:__subpackages__"]) sass_binary( name = "split_styles", src = "split.component.scss", ) ng_module( name = "split", srcs = [ "interface.ts", "split.component.ts", "splitArea.directive.ts", "utils.ts", ], angular_assets = [ ":split_styles", ], deps = [ "//packages/common", "//packages/core", "@npm//rxjs", ], )
{ "end_byte": 553, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/projects/ng-devtools/src/lib/vendor/angular-split/lib/component/BUILD.bazel" }
angular/devtools/docs/overview.md_0_8921
- [DevTools Overview](#devtools-overview) - [Bug reports](#bug-reports) - [Debug your application](#debug-your-application) - [Explore the application structure](#explore-the-application-structure) - [View properties](#view-properties) - [Navigate to the host node](#navigate-to-the-host-node) - [Navigate to source](#navigate-to-source) - [Update property value](#update-property-value) - [Access selected component or directive in console](#access-selected-component-or-directive-in-console) - [Select a directive or component](#select-a-directive-or-component) - [Profile your application](#profile-your-application) - [Understand your application's execution](#understand-your-applications-execution) - [Understand component execution](#understand-component-execution) - [Hierarchical views](#hierarchical-views) - [Debug OnPush](#debug-onpush) - [Import recording](#import-recording) # DevTools Overview Angular DevTools is a Chrome extension that provides debugging and profiling capabilities for Angular applications. Angular DevTools supports Angular v12 and above. You can find Angular DevTools in the [Chrome Web Store](https://chrome.google.com/webstore/detail/angular-developer-tools/ienfalfjdbdpebioblfackkekamfmbnh). After installing Angular DevTools, you can find the extension under the Angular tab in Chrome DevTools. ![devtools](assets/devtools.png) When you open the extension, you'll see two additional tabs: - [Components](#components) - lets you explore the components and directives in your application and preview or edit their state. - [Profiler](#profiler) - lets you profile your application and understand what the performance bottleneck is during change detection execution. ![devtools tabs](assets/devtools-tabs.png) In the top-right corner of Angular DevTools you'll find which version of Angular is running on the page as well as the latest commit hash for the extension. ## Bug reports You can report issues and feature requests on [GitHub](https://github.com/angular/angular/issues). To report an issue with the Profiler, export the Profiler recording by clicking the **Save Profile** button, and then attaching that export as a file in the issue. > Make sure that the Profiler recording does not contain any confidential information.\*\*\*\* ## Debug your application The **Components** tab lets you explore the structure of your application. You can visualize and inspect the component and directive instances and preview or modify their state. In the next couple of sections we'll look into how you can use this tab effectively to debug your application. ### Explore the application structure ![component-explorer](assets/component-explorer.png) In the preceding screenshot, you can see the component tree of an application. The component tree displays a hierarchical relationship of the _components and directives_ within your application. When you select a component or a directive instance, Angular DevTools presents additional information about that instance. ### View properties Click the individual components or directives in the component explorer to select them and preview their properties. Angular DevTools displays their properties and metadata on the right-hand side of the component tree. You can navigate in the component tree using the mouse or the following keyboard shortcuts: - Up and down arrows select the previous and next nodes. - Left and right arrows collapse and expand a node. To look up a component or directive by name use the search box above the component tree. To navigate to the next search match, press `Enter`. To navigate to the previous search match, press `Shift + Enter`. ![search](assets/search.png) ### Navigate to the host node To go to the host element of a particular component or directive, find it in the component explorer and double-click it. Chrome DevTools opens the Elements tab and selects the associated DOM node. ### Navigate to source For components, Angular DevTools also lets you navigate to the component definition in the source tab. After you select a particular component, click the icon at the top-right of the properties view: ![navigate source](assets/navigate-source.png) ### Update property value Like Chrome DevTools, the properties view allows you to edit the value of an input, output, or another property. Right-click on the property value. If edit functionality is available for this value type, you'll see a text input. Type the new value and press `Enter`. ![update property](assets/update-property.png) ### Access selected component or directive in console As a shortcut in the console, Angular DevTools provides you access to instances of the recently selected components or directives. Type `$ng0` to get a reference to the instance of the currently selected component or directive, and type `$ng1` for the previously selected instance. ![access console](assets/access-console.png) ### Select a directive or component Similar to Chrome DevTools, you can inspect the page to select a particular component or directive. Click the **_Inspect element_** icon at the top left corner within Devtools and hover over a DOM element on the page. Angular DevTools recognizes the associated directives and/or components and lets you select the corresponding element in the Component tree. ![selecting dom node](assets/inspect-element.png) ## Profile your application The **Profiler** tab lets you preview the execution of Angular's change detection. ![profiler](assets/profiler.png) The Profiler lets you start profiling or import an existing profile. To start profiling your application, hover over the circle at the top-left corner within the **Profiler** tab and click **Start recording**. During profiling, Angular DevTools captures execution events, such as change detection and lifecycle hook execution. To finish recording, click the circle again to **Stop recording**. You can also import an existing recording. Read more about this feature in the [Import recording](#) section. ### Understand your application's execution In the following screenshot, you can find the default view of the Profiler after you complete recording. ![default profiler view](assets/default-profiler-view.png) Near the top of the view you can see a sequence of bars, each one of them symbolizing change detection cycles in your app. The taller a bar is, the longer your application has spent in this cycle. When you select a bar, DevTools renders a bar chart with all the components and directives that it captured during this cycle. ![profiler selected bar](assets/profiler-selected-bar.png) Above the change detection timeline, you can find how much time Angular spent in this cycle. Angular DevTools attempts to estimate the frame drop at this point to indicate when the execution of your application might impact the user experience. Angular DevTools also indicates what triggered the change detection (that is, the change detection's source). ### Understand component execution When you click on a bar, you'll find a detailed view about how much time your application spent in the particular directive or component: ![directive details](assets/directive-details.png) Figure shows the total time spent by NgforOf directive and which method was called in it. It also shows the parent hierarchy of the directive selected. ### Hierarchical views ![flame graph view](assets/flame-graph-view.png) You can also preview the change detection execution in a flame graph-like view. Each tile in the graph represents an element on the screen at a specific position in the render tree. For example, if during one change detection cycle at a specific position in the component tree we had `ComponentA`, this component was removed and in its place Angular rendered `ComponentB`, you'll see both components at the same tile. Each tile is colored depending on how much time Angular has spent there. DevTools determines the intensity of the color by the time spent relative to the tile where we've spent the most time in change detection. When you click on a certain tile, you'll see details about it in the panel on the right. Double-clicking the tile zooms it in so you can preview the nested children. ### Debug OnPush To preview the components in which Angular did change detection, select the **Change detection** checkbox at the top, above the flame graph. This view will color all the tiles in which Angular performed change detection in green, and the rest in gray: ![debugging onpush](assets/debugging-onpush.png) ### Import recording Click the **Save Profile** button at the top-left of a recorded profiling session to export it as a JSON file and save it to the disk. Then, you can import the file in the initial view of the profiler by clicking the **Choose file** input: ![save profile](assets/save-profile.png)
{ "end_byte": 8921, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/docs/overview.md" }
angular/devtools/docs/safari.md_0_1154
# Installing Angular DevTools in Safari (experimental) ### Requirements - Xcode 13+ To install Angular DevTools in Safari follow the steps: * Open Safari and make sure the checkbox in `Safari -> Preferences -> Advanced -> Show develop menu in menu bar` is checked. * Make sure the flag in `Develop -> Experimental Features -> Web Inspector Extensions` is checked. * Build Angular DevTools with a chrome configuration with `yarn devtools:build:chrome` this will create an Angular DevTools build in `dist/bin/devtools/projects/shell-browser/src/prodapp`. * Run `xcrun safari-web-extension-converter --macos-only dist/bin/devtools/projects/shell-browser/src/prodapp`. This will convert Angular DevTools into a Safari web extension. This command should open Xcode when it completes. * In Xcode, click the build button and wait for the extension to build. Once this is complete, a system prompt should ask you to open Safari and enable the extension. You'll know the extension is enabled because of an Angular icon present in browser toolbar. * Open any Angular application in dev mode and open Safari DevTools, you should see the Angular Tab there.
{ "end_byte": 1154, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/docs/safari.md" }
angular/devtools/docs/firefox.md_0_982
# Installing Angular DevTools in Firefox To install Angular DevTools in Firefox follow the steps: * Open menu item from top bar `Tools -> Browser Tools -> Remote Debugging`. * After clicking `Remote Debugging` click on `This Firefox` option from left navigation. You will see the below screen with list of extensions. Temporary extensions are unreleased extensions loaded in development mode. * Click on `Load Temporary Add-on` button to select and load the Angular DevTools extension for Firefox. * Select any file from `dist/bin/devtools/projects/shell-browser/src/prodapp` directory to load extension. If you have not built the extension for Firefox yet, you can do it using `yarn devtools:build:firefox` which will generate build for Firefox. * After selecting file and clicking open, you should be able to see Angular DevTools as a temporary Extension in Firefox. * Open any Angular application in dev mode and open Firefox DevTools you should see Angular Tab in there.
{ "end_byte": 982, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/docs/firefox.md" }
angular/devtools/docs/release.md_0_3793
# Publish Angular DevTools Publishing Angular DevTools is a five step process: 1. Sync and update workspace. 1. Update extension version numbers. 1. Publish to Chrome. 1. Publish to Firefox. 1. Commit and merge the updated version numbers. ## 1. Sync workspace Before starting anything, make sure your workspace is up to date with latest changes and dependencies. ```shell git checkout main git pull upstream main nvm install yarn --frozen-lockfile ``` ## 2. Update extension version numbers Bump the version numbers listed in [`manifest.chrome.json`](/devtools/projects/shell-browser/src/manifest/manifest.chrome.json) and [`manifest.firefox.json`](/devtools/projects/shell-browser/src/manifest/manifest.firefox.json). ## 3. Publish to Chrome Chrome To publish Angular DevTools to the Chrome Web Store, first build and package the extension. ```shell # Build the Chrome version. yarn devtools:build:chrome # Package the extension. (cd dist/bin/devtools/projects/shell-browser/src/prodapp && zip -r ~/devtools-chrome.zip *) ``` Then upload it to the Chrome Web Store. 1. Go to the extension [page](https://chrome.google.com/webstore/category/extensions) 1. Make sure your email is part of the Google Group we use for publishing the extension 1. Navigate to "Developer Dashboard" 1. Enter your account credentials 1. You should be able to change the publisher to "Angular" You can choose to either publish immediately or only get approval but hold to publish at a later time. Note that even publishing immediately still requires approval from Chrome Web Store before it is available to users. Historically this has been pretty quick (< 30 minutes), but there is no hard upper limit on how long a review might take: https://developer.chrome.com/docs/webstore/review-process#review-time. ## 4. Publish to Firefox To publish Angular DevTools as a Firefox Add-on, first build and package the extension. ```shell # Build the Firefox version. yarn devtools:build:firefox # Package the extension. (cd dist/bin/devtools/projects/shell-browser/src/prodapp && zip -r ~/devtools-firefox.zip *) ``` Then upload it: 1. Go to the Firefox Addons [page](https://addons.mozilla.org/developers/addons) 1. Find the email and password [on Valentine](http://valentine/#/show/1651707871496288) 1. Setup Google Authenticator with the 2FA QR code. * You can find the QR code [on Valentine as well](http://valentine/#/show/1651792043556329) The Firefox publishing process is slightly more involved than Chrome. In particular, they require extension source code with instructions to build and run it. Since DevTools exists in a monorepo with critical build tooling existing outside the `devtools/` directory, we need to upload the entire monorepo. Package it without dependencies and generated files with the following command and upload it. ```shell zip -r ~/angular-source.zip * -x ".git/*" -x "node_modules/*" -x "**/node_modules/*" -x "dist/" ``` Suggested note to reviewer: > This is a monorepo and includes much more code than just the DevTools extension. The relevant > code is under `devtools/...` and `devtools/README.md` contains instructions for compiling release > builds locally. > > The uploaded source is equivalent to > https://github.com/angular/angular/tree/${permalink to current main}/ with the single change > of a bumped version number in the `manifest.json` file. ### 5. Commit and merge Commit the version bump: ```shell git checkout -b devtools-release git add . && git commit -m "release: bump Angular DevTools version to 1.0.10" git push -u origin devtools-release ``` Then create and merge a PR targeting `patch` with this change. Once the PR merges and both Chrome and Firefox are showing the new version to end users, then the release is complete!
{ "end_byte": 3793, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/docs/release.md" }
angular/devtools/src/zone-unaware-iframe-message-bus.ts_0_1766
/** * @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, Parameters} from 'protocol'; import {IFrameMessageBus} from './iframe-message-bus'; type AnyEventCallback<Ev> = <E extends keyof Ev>(topic: E, args: Parameters<Ev[E]>) => void; const runOutsideAngular = (f: () => any) => { const w = window as any; if (!w.Zone || w.Zone.current._name !== 'angular') { f(); return; } w.Zone.current._parent.run(f); }; export class ZoneUnawareIFrameMessageBus extends MessageBus<Events> { private _delegate: IFrameMessageBus; constructor(source: string, destination: string, docWindow: () => Window) { super(); this._delegate = new IFrameMessageBus(source, destination, docWindow); } onAny(cb: AnyEventCallback<Events>): any { let result: any; runOutsideAngular(() => { result = this._delegate.onAny(cb); }); return result; } override on<E extends keyof Events>(topic: E, cb: Events[E]): any { let result: any; runOutsideAngular(() => { result = this._delegate.on(topic, cb); }); return result; } override once<E extends keyof Events>(topic: E, cb: Events[E]): any { let result: any; runOutsideAngular(() => { result = this._delegate.once(topic, cb); }); return result; } // Need to be run in the zone because otherwise it won't be caught by the // listener in the extension. override emit<E extends keyof Events>(topic: E, args?: Parameters<Events[E]>): boolean { return this._delegate.emit(topic, args); } override destroy(): void { this._delegate.destroy(); } }
{ "end_byte": 1766, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/zone-unaware-iframe-message-bus.ts" }
angular/devtools/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/src/index.html" }
angular/devtools/src/main.ts_0_396
/** * @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 {platformBrowser} from '@angular/platform-browser'; import {AppModule} from './app/app.module'; platformBrowser() .bootstrapModule(AppModule) .catch((err) => console.error(err));
{ "end_byte": 396, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/main.ts" }
angular/devtools/src/styles.scss_0_35
@use '../styles.scss' as devtools;
{ "end_byte": 35, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/styles.scss" }
angular/devtools/src/iframe-message-bus.ts_0_2852
/** * @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, Parameters} from 'protocol'; type AnyEventCallback<Ev> = <E extends keyof Ev>(topic: E, args: Parameters<Ev[E]>) => void; export class IFrameMessageBus extends MessageBus<Events> { private _listeners: any[] = []; constructor( private _source: string, private _destination: string, private _docWindow: () => Window, ) { super(); } onAny(cb: AnyEventCallback<Events>): () => void { const listener = (e: MessageEvent) => { if (!e.data || !e.data.topic || e.data.source !== this._destination) { return; } cb(e.data.topic, e.data.args); }; window.addEventListener('message', listener); this._listeners.push(listener); return () => { this._listeners.splice(this._listeners.indexOf(listener), 1); window.removeEventListener('message', listener); }; } override on<E extends keyof Events>(topic: E, cb: Events[E]): () => void { const listener = (e: MessageEvent) => { if (!e.data || e.data.source !== this._destination || !e.data.topic) { return; } if (e.data.topic === topic) { (cb as () => void).apply(null, e.data.args); } }; window.addEventListener('message', listener); this._listeners.push(listener); return () => { this._listeners.splice(this._listeners.indexOf(listener), 1); window.removeEventListener('message', listener); }; } override once<E extends keyof Events>(topic: E, cb: Events[E]): void { const listener = (e: MessageEvent) => { if (!e.data || e.data.source !== this._destination || !e.data.topic) { return; } if (e.data.topic === topic) { (cb as any).apply(null, e.data.args); window.removeEventListener('message', listener); } }; window.addEventListener('message', listener); } override emit<E extends keyof Events>(topic: E, args?: Parameters<Events[E]>): boolean { this._docWindow().postMessage( { source: this._source, topic, args, // Since both the devtools app and the demo app use IframeMessageBus, // we want to only ignore the ngZone for the demo app. This will let us // prevent infinite change detection loops triggered by message // event listeners but also not prevent the NgZone in the devtools app // from updating its UI. __ignore_ng_zone__: this._source === 'angular-devtools', }, '*', ); return true; } override destroy(): void { this._listeners.forEach((l) => window.removeEventListener('message', l)); this._listeners = []; } }
{ "end_byte": 2852, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/iframe-message-bus.ts" }
angular/devtools/src/demo-application-operations.ts_0_1003
/** * @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 {ApplicationOperations} from 'ng-devtools'; import {DirectivePosition, ElementPosition} from 'protocol'; export class DemoApplicationOperations extends ApplicationOperations { override viewSource(position: ElementPosition): void { console.warn('viewSource() is not implemented because the demo app runs in an Iframe'); throw new Error('Not implemented in demo app.'); } override selectDomElement(position: ElementPosition): void { console.warn('selectDomElement() is not implemented because the demo app runs in an Iframe'); throw new Error('Not implemented in demo app.'); } override inspect(directivePosition: DirectivePosition, keyPath: string[]): void { console.warn('inspect() is not implemented because the demo app runs in an Iframe'); return; } }
{ "end_byte": 1003, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/demo-application-operations.ts" }
angular/devtools/src/BUILD.bazel_0_3092
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/src/app", "//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, # todo(aleksanderbodurri): here we target es2020 explicitly. # We do this because of a bug caused by https://github.com/evanw/esbuild/issues/2950 and an Angular v16 change # to how angular static properties are attached to class constructors. # Targeting esnext or es2022 will cause the static initializer blocks that attach these static properties on class # constructors to reference a class constructor variable that they do not have access to. target = "es2020", 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/src/devapp"], tags = ["manual"], deps = [ ":devapp", ], ) ng_module( name = "demo_application_environment", srcs = ["demo-application-environment.ts"], deps = [ "//devtools/projects/ng-devtools", "//devtools/src/environments", ], ) ng_module( name = "demo_application_operations", srcs = ["demo-application-operations.ts"], deps = [ "//devtools/projects/ng-devtools", "//devtools/projects/protocol", ], ) ng_module( name = "iframe_message_bus", srcs = ["iframe-message-bus.ts"], deps = [ "//devtools/projects/protocol", ], ) ng_module( name = "zone-unaware-iframe_message_bus", srcs = ["zone-unaware-iframe-message-bus.ts"], deps = [ ":iframe_message_bus", "//devtools/projects/protocol", ], )
{ "end_byte": 3092, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/BUILD.bazel" }
angular/devtools/src/demo-application-environment.ts_0_506
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ApplicationEnvironment, Environment} from 'ng-devtools'; import {environment} from './environments/environment'; export class DemoApplicationEnvironment extends ApplicationEnvironment { frameSelectorEnabled = false; override get environment(): Environment { return environment; } }
{ "end_byte": 506, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/demo-application-environment.ts" }
angular/devtools/src/app/app.component.html_0_32
<router-outlet></router-outlet>
{ "end_byte": 32, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/app.component.html" }
angular/devtools/src/app/app.module.ts_0_1350
/** * @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 {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {RouterModule} from '@angular/router'; import {ApplicationEnvironment, ApplicationOperations} from 'ng-devtools'; import {DemoApplicationEnvironment} from '../demo-application-environment'; import {DemoApplicationOperations} from '../demo-application-operations'; import {AppComponent} from './app.component'; @NgModule({ declarations: [AppComponent], imports: [ BrowserAnimationsModule, RouterModule.forRoot([ { path: '', loadChildren: () => import('./devtools-app/devtools-app.module').then((m) => m.DevToolsModule), pathMatch: 'full', }, { path: 'demo-app', loadChildren: () => import('./demo-app/demo-app.module').then((m) => m.DemoAppModule), }, ]), ], providers: [ { provide: ApplicationOperations, useClass: DemoApplicationOperations, }, { provide: ApplicationEnvironment, useClass: DemoApplicationEnvironment, }, ], bootstrap: [AppComponent], }) export class AppModule {}
{ "end_byte": 1350, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/app.module.ts" }
angular/devtools/src/app/app.component.ts_0_495
/** * @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} from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], standalone: false, }) export class AppComponent { constructor(public router: Router) {} }
{ "end_byte": 495, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/app.component.ts" }
angular/devtools/src/app/BUILD.bazel_0_842
load("//devtools/tools:ng_module.bzl", "ng_module") load("@io_bazel_rules_sass//:defs.bzl", "sass_binary") package(default_visibility = ["//visibility:public"]) sass_binary( name = "app_component_styles", src = "app.component.scss", ) ng_module( name = "app", srcs = [ "app.component.ts", "app.module.ts", ], angular_assets = [ "app.component.html", ":app_component_styles", ], deps = [ "//devtools/projects/ng-devtools", "//devtools/src:demo_application_environment", "//devtools/src:demo_application_operations", "//devtools/src/app/demo-app", "//devtools/src/app/devtools-app", "//packages/core", "//packages/platform-browser", "//packages/platform-browser/animations", "//packages/router", ], )
{ "end_byte": 842, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/BUILD.bazel" }
angular/devtools/src/app/devtools-app/devtools-app.module.ts_0_1384
/** * @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 {NgModule} from '@angular/core'; import {RouterModule} from '@angular/router'; import {AppDevToolsComponent} from './devtools-app.component'; import {FrameManager} from '../../../projects/ng-devtools/src/lib/frame_manager'; import {Events, MessageBus, PriorityAwareMessageBus} from 'protocol'; import {IFrameMessageBus} from '../../../src/iframe-message-bus'; @NgModule({ imports: [ CommonModule, RouterModule.forChild([ { path: '', component: AppDevToolsComponent, pathMatch: 'full', }, ]), AppDevToolsComponent, ], providers: [ { 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!, ), ); }, }, {provide: FrameManager, useFactory: () => FrameManager.initialize(null)}, ], }) export class DevToolsModule {}
{ "end_byte": 1384, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/devtools-app/devtools-app.module.ts" }
angular/devtools/src/app/devtools-app/devtools-app.component.ts_0_665
/** * @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 {IFrameMessageBus} from '../../iframe-message-bus'; import {DevToolsComponent} from 'ng-devtools'; @Component({ templateUrl: './devtools-app.component.html', styleUrls: ['./devtools-app.component.scss'], standalone: true, imports: [DevToolsComponent], }) export class AppDevToolsComponent { messageBus: IFrameMessageBus | null = null; @ViewChild('ref') iframe!: ElementRef; }
{ "end_byte": 665, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/devtools-app/devtools-app.component.ts" }
angular/devtools/src/app/devtools-app/devtools-app.component.scss_0_110
iframe { height: 339px; width: 100%; border: 0; } .devtools-wrapper { height: calc(100vh - 344px); }
{ "end_byte": 110, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/devtools-app/devtools-app.component.scss" }
angular/devtools/src/app/devtools-app/devtools-app.component.html_0_157
<iframe #ref src="demo-app/todos/app" id="sample-app" title="todos-app"></iframe> <br /> <div class="devtools-wrapper"> <ng-devtools></ng-devtools> </div>
{ "end_byte": 157, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/devtools-app/devtools-app.component.html" }
angular/devtools/src/app/devtools-app/BUILD.bazel_0_804
load("//devtools/tools:ng_module.bzl", "ng_module") load("@io_bazel_rules_sass//:defs.bzl", "sass_binary") package(default_visibility = ["//visibility:public"]) sass_binary( name = "devtools_app_component_styles", src = "devtools-app.component.scss", ) ng_module( name = "devtools-app", srcs = [ "devtools-app.component.ts", "devtools-app.module.ts", ], angular_assets = [ "devtools-app.component.html", ":devtools_app_component_styles", ], 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": 804, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/devtools-app/BUILD.bazel" }
angular/devtools/src/app/demo-app/zippy.component.ts_0_475
/** * @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', templateUrl: './zippy.component.html', styleUrls: ['./zippy.component.scss'], standalone: false, }) export class ZippyComponent { @Input() title!: string; visible = false; }
{ "end_byte": 475, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/zippy.component.ts" }
angular/devtools/src/app/demo-app/demo-app.module.ts_0_1536
/** * @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 {CUSTOM_ELEMENTS_SCHEMA, Injector, NgModule} from '@angular/core'; import {createCustomElement} from '@angular/elements'; import {RouterModule} from '@angular/router'; import {initializeMessageBus} from 'ng-devtools-backend'; import {ZoneUnawareIFrameMessageBus} from '../../zone-unaware-iframe-message-bus'; import {DemoAppComponent} from './demo-app.component'; import {HeavyComponent} from './heavy.component'; import {SamplePropertiesComponent} from './sample-properties.component'; import {ZippyComponent} from './zippy.component'; @NgModule({ declarations: [DemoAppComponent, HeavyComponent, SamplePropertiesComponent], schemas: [CUSTOM_ELEMENTS_SCHEMA], exports: [DemoAppComponent], imports: [ RouterModule.forChild([ { path: '', component: DemoAppComponent, children: [ { path: '', loadChildren: () => import('./todo/app.module').then((m) => m.AppModule), }, ], }, ]), ], }) export class DemoAppModule { constructor(injector: Injector) { const el = createCustomElement(ZippyComponent, {injector}); customElements.define('app-zippy', el as any); } } initializeMessageBus( new ZoneUnawareIFrameMessageBus( 'angular-devtools-backend', 'angular-devtools', () => window.parent, ), );
{ "end_byte": 1536, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/demo-app.module.ts" }
angular/devtools/src/app/demo-app/heavy.component.ts_0_840
/** * @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', templateUrl: './heavy.component.html', styleUrls: ['./heavy.component.scss'], standalone: false, }) 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": 840, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/heavy.component.ts" }
angular/devtools/src/app/demo-app/heavy.component.html_0_27
<h1>{{ calculate() }}</h1>
{ "end_byte": 27, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/heavy.component.html" }
angular/devtools/src/app/demo-app/BUILD.bazel_0_1488
load("//devtools/tools:ng_module.bzl", "ng_module") load("@io_bazel_rules_sass//:defs.bzl", "sass_binary", "sass_library") package(default_visibility = ["//visibility:public"]) _STYLE_SRCS = [ "heavy.component.scss", "zippy.component.scss", ] _STYLE_LABELS = [ src[:-len(".component.scss")].replace("-", "_") + "_styles" for src in _STYLE_SRCS ] [ sass_binary( name = label, src = src, ) for label, src in zip(_STYLE_LABELS, _STYLE_SRCS) ] 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", "demo-app.module.ts", "heavy.component.ts", "sample.service.ts", "sample-properties.component.ts", "zippy.component.ts", ], angular_assets = [ "demo-app.component.html", "heavy.component.html", "zippy.component.html", ":demo_app_component_styles", ] + _STYLE_LABELS, deps = [ "//devtools/projects/ng-devtools-backend", "//devtools/src:zone-unaware-iframe_message_bus", "//devtools/src/app/demo-app/todo", "//packages/core", "//packages/elements", "//packages/router", ], )
{ "end_byte": 1488, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/BUILD.bazel" }
angular/devtools/src/app/demo-app/demo-app.component.html_0_208
<router-outlet></router-outlet> <app-zippy [title]="getTitle()">This is my content</app-zippy> <app-heavy></app-heavy> <div #elementReference>HTMLElement</div> <app-sample-properties></app-sample-properties>
{ "end_byte": 208, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/demo-app.component.html" }
angular/devtools/src/app/demo-app/zippy.component.scss_0_295
: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; }
{ "end_byte": 295, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/zippy.component.scss" }
angular/devtools/src/app/demo-app/demo-app.component.ts_0_1412
/** * @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, computed, ElementRef, EventEmitter, Input, Output, signal, ViewChild, ViewEncapsulation, } from '@angular/core'; import {ZippyComponent} from './zippy.component'; @Component({ selector: 'app-demo-component', templateUrl: './demo-app.component.html', styleUrls: ['./demo-app.component.scss'], encapsulation: ViewEncapsulation.None, standalone: false, }) 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}; }); getTitle(): '► Click to expand' | '▼ Click to collapse' { if (!this.zippy || !this.zippy.visible) { return '► Click to expand'; } return '▼ Click to collapse'; } }
{ "end_byte": 1412, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/demo-app.component.ts" }
angular/devtools/src/app/demo-app/sample.service.ts_0_1144
/** * @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 {computed, Injectable, signal} from '@angular/core'; @Injectable({providedIn: 'root'}) export class SampleService { exampleBoolean = true; exampleString = 'John'; exampleSymbol = Symbol.iterator; exampleNumber = 40; exampleBigint = 40n; exampleUndefined = undefined; exampleNull = null; exampleObject = {name: 'John', age: 40}; exampleArray = [1, 2, [3, 4], {name: 'John', age: 40, skills: ['JavaScript']}]; exampleSet = new Set([1, 2, 3, 4, 5]); exampleMap = new Map<unknown, unknown>([ ['name', 'John'], ['age', 40], [{id: 123}, undefined], ]); exampleDate = new Date(); exampleFunction = () => 'John'; signalPrimitive = signal(123); computedPrimitive = computed(() => this.signalPrimitive() ** 2); signalObject = signal({name: 'John', age: 40}); computedObject = computed(() => { const original = this.signalObject(); return {...original, age: original.age + 1}; }); }
{ "end_byte": 1144, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/sample.service.ts" }
angular/devtools/src/app/demo-app/sample-properties.component.ts_0_1492
/** * @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, computed, ElementRef, inject, signal, ViewChild} from '@angular/core'; import {SIGNAL} from '@angular/core/primitives/signals'; import {SampleService} from './sample.service'; @Component({ selector: 'app-sample-properties', template: '', styles: [''], standalone: false, }) export class SamplePropertiesComponent { @ViewChild('elementReference') elementRef!: ElementRef; exampleService = inject(SampleService); exampleBoolean = true; exampleString = 'John'; exampleSymbol = Symbol.iterator; exampleNumber = 40; exampleBigint = 40n; exampleUndefined = undefined; exampleNull = null; exampleObject = {name: 'John', age: 40}; exampleArray = [1, 2, [3, 4], {name: 'John', age: 40, skills: ['JavaScript']}]; exampleSet = new Set([1, 2, 3, 4, 5]); exampleMap = new Map<unknown, unknown>([ ['name', 'John'], ['age', 40], [{id: 123}, undefined], ]); exampleDate = new Date(); exampleFunction = () => 'John'; signalPrimitive = signal(123); computedPrimitive = computed(() => this.signalPrimitive() ** 2); signalObject = signal({name: 'John', age: 40}); computedObject = computed(() => { const original = this.signalObject(); return {...original, age: original.age + 1}; }); signalSymbol = SIGNAL; }
{ "end_byte": 1492, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/sample-properties.component.ts" }
angular/devtools/src/app/demo-app/zippy.component.html_0_149
<section> <header (click)="visible = !visible">{{ title }}</header> <div [hidden]="!visible"> <ng-content> </ng-content> </div> </section>
{ "end_byte": 149, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/zippy.component.html" }
angular/devtools/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/src/app/demo-app/demo-app.component.scss" }
angular/devtools/src/app/demo-app/todo/app-todo.component.ts_0_1051
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component, Injectable} from '@angular/core'; import {MatDialog} from '@angular/material/dialog'; import {DialogComponent} from './dialog.component'; @Injectable() export class MyServiceA {} @Component({ selector: 'app-todo-demo', templateUrl: './app-todo.component.html', styleUrls: ['./app-todo.component.scss'], viewProviders: [MyServiceA], standalone: false, }) export class AppTodoComponent { 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; }); } }
{ "end_byte": 1051, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/app-todo.component.ts" }
angular/devtools/src/app/demo-app/todo/app-todo.component.html_0_224
<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>
{ "end_byte": 224, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/app-todo.component.html" }
angular/devtools/src/app/demo-app/todo/app.module.ts_0_1519
/** * @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 {NgModule} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {MatDialogModule} from '@angular/material/dialog'; import {MatFormFieldModule} from '@angular/material/form-field'; import {MatInputModule} from '@angular/material/input'; import {RouterModule} from '@angular/router'; import {AppTodoComponent} from './app-todo.component'; import {DialogComponent} from './dialog.component'; @NgModule({ declarations: [AppTodoComponent], imports: [ MatDialogModule, MatFormFieldModule, FormsModule, MatInputModule, CommonModule, RouterModule.forChild([ { path: 'todos', component: AppTodoComponent, children: [ { path: 'app', loadChildren: () => import('./home/home.module').then((m) => m.HomeModule), }, { path: 'about', loadChildren: () => import('./about/about.module').then((m) => m.AboutModule), }, { path: '**', redirectTo: 'app', }, ], }, { path: '**', redirectTo: 'todos', }, ]), DialogComponent, ], exports: [AppTodoComponent], bootstrap: [AppTodoComponent], }) export class AppModule {}
{ "end_byte": 1519, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/app.module.ts" }
angular/devtools/src/app/demo-app/todo/app-todo.component.scss_0_205
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; }
{ "end_byte": 205, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/app-todo.component.scss" }
angular/devtools/src/app/demo-app/todo/dialog.component.ts_0_1123
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component, Inject} from '@angular/core'; import { MAT_DIALOG_DATA, MatDialogRef, MatDialogTitle, MatDialogContent, MatDialogActions, MatDialogClose, } from '@angular/material/dialog'; import {MatInputModule} from '@angular/material/input'; import {MatFormFieldModule} from '@angular/material/form-field'; import {FormsModule} from '@angular/forms'; export interface DialogData { animal: string; name: string; } @Component({ selector: 'app-dialog', templateUrl: 'dialog.component.html', standalone: true, imports: [ MatDialogTitle, MatDialogContent, MatFormFieldModule, MatInputModule, FormsModule, MatDialogActions, MatDialogClose, ], }) export class DialogComponent { constructor( public dialogRef: MatDialogRef<DialogComponent>, @Inject(MAT_DIALOG_DATA) public data: DialogData, ) {} onNoClick(): void { this.dialogRef.close(); } }
{ "end_byte": 1123, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/dialog.component.ts" }
angular/devtools/src/app/demo-app/todo/BUILD.bazel_0_800
load("//devtools/tools:ng_module.bzl", "ng_module") load("@io_bazel_rules_sass//:defs.bzl", "sass_binary") package(default_visibility = ["//visibility:public"]) sass_binary( name = "app_todo_component_styles", src = "app-todo.component.scss", ) ng_module( name = "todo", srcs = [ "app.module.ts", "app-todo.component.ts", "dialog.component.ts", ], angular_assets = [ "app-todo.component.html", "dialog.component.html", ":app_todo_component_styles", ], deps = [ "//devtools/src/app/demo-app/todo/about", "//devtools/src/app/demo-app/todo/home", "//packages/common", "//packages/core", "//packages/forms", "//packages/router", "@npm//@angular/material", ], )
{ "end_byte": 800, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/BUILD.bazel" }
angular/devtools/src/app/demo-app/todo/dialog.component.html_0_422
<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>
{ "end_byte": 422, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/dialog.component.html" }
angular/devtools/src/app/demo-app/todo/home/todo.ts_0_283
/** * @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 interface Todo { id: string; completed: boolean; label: string; }
{ "end_byte": 283, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/home/todo.ts" }
angular/devtools/src/app/demo-app/todo/home/todos.component.html_0_1467
<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> <!-- {{slowBinding}}--> <ul class="todo-list"> <!-- These are here just to show the structure of the list items --> <!-- List items should get the class `editing` when editing and `completed` when marked as completed --> @for (todo of todos | todosFilter: filterValue; track $index) { <app-todo appTooltip [todo]="todo" (delete)="onDelete($event)" (update)="onChange($event)" /> } </ul> </section> <!-- This footer should hidden by default and shown when there are todos --> <footer class="footer"> <!-- This should be `0 items left` by default --> <span class="todo-count" ><strong>{{ itemsLeft }}</strong> item left</span > <!-- Remove this if you don't implement routing --> <!-- Hidden if no completed items are left ↓ --> <button class="clear-completed" (click)="clearCompleted()">Clear completed</button> </footer> </section>
{ "end_byte": 1467, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/home/todos.component.html" }
angular/devtools/src/app/demo-app/todo/home/home.module.ts_0_909
/** * @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 {NgModule} from '@angular/core'; import {RouterModule} from '@angular/router'; import {TooltipDirective} from './/tooltip.directive'; import {SamplePipe} from './sample.pipe'; import {TodoComponent} from './todo.component'; import {TodosComponent} from './todos.component'; import {TodosFilter} from './todos.pipe'; @NgModule({ imports: [ CommonModule, RouterModule.forChild([ { path: '', component: TodosComponent, pathMatch: 'full', }, ]), SamplePipe, TodosComponent, TodoComponent, TodosFilter, TooltipDirective, ], exports: [TodosComponent], }) export class HomeModule {}
{ "end_byte": 909, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/home/home.module.ts" }
angular/devtools/src/app/demo-app/todo/home/todo.component.ts_0_1057
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ChangeDetectionStrategy, Component, EventEmitter, Input, Output} from '@angular/core'; import {Todo} from './todo'; import {TooltipDirective} from './tooltip.directive'; @Component({ templateUrl: 'todo.component.html', selector: 'app-todo', changeDetection: ChangeDetectionStrategy.OnPush, styleUrls: ['./todo.component.scss'], standalone: true, imports: [TooltipDirective], }) 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": 1057, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/home/todo.component.ts" }
angular/devtools/src/app/demo-app/todo/home/tooltip.directive.ts_0_759
/** * @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": 759, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/home/tooltip.directive.ts" }
angular/devtools/src/app/demo-app/todo/home/todos.pipe.ts_0_880
/** * @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 {Pipe, PipeTransform} from '@angular/core'; import {Todo} from './todo'; 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; }); } }
{ "end_byte": 880, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/home/todos.pipe.ts" }
angular/devtools/src/app/demo-app/todo/home/BUILD.bazel_0_727
load("//devtools/tools:ng_module.bzl", "ng_module") load("@io_bazel_rules_sass//:defs.bzl", "sass_binary") package(default_visibility = ["//visibility:public"]) sass_binary( name = "home_styles", src = "todo.component.scss", ) ng_module( name = "home", srcs = [ "home.module.ts", "sample.pipe.ts", "todo.component.ts", "todo.ts", "todos.component.ts", "todos.pipe.ts", "todos.service.ts", "tooltip.directive.ts", ], angular_assets = [ "todos.component.html", "todo.component.html", ":home_styles", ], deps = [ "//packages/common", "//packages/core", "//packages/router", ], )
{ "end_byte": 727, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/home/BUILD.bazel" }
angular/devtools/src/app/demo-app/todo/home/sample.pipe.ts_0_546
/** * @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": 546, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/devtools/src/app/demo-app/todo/home/sample.pipe.ts" }