refactor(devtools): remove leading underscores of private class members

Remove all prefixes of private members to match the currently followed convention.
Remaining places that still use underscores (excluded from the refactor):
- `tab-update/index.ts`
- `splitArea.directive.ts` (part of the old vendor code)
This commit is contained in:
hawkgs
2026-10-09 17:14:37 -07:00
committed by Alon Mishne
parent 2d0ce996e8
commit 500d8709b7
23 changed files with 448 additions and 454 deletions
@@ -15,10 +15,10 @@ import {ChangeDetectorRef, Component} from '@angular/core';
export class AppComponent {
counter = 0;
constructor(private _cd: ChangeDetectorRef) {}
constructor(private cd: ChangeDetectorRef) {}
increment(): void {
this.counter++;
this._cd.detectChanges();
this.cd.detectChanges();
}
}
@@ -25,10 +25,10 @@ export interface ComponentInspectorOptions {
}
export class ComponentInspector {
private _selectedDirective!: {directive: unknown; host: Element | null};
private readonly _onComponentEnter;
private readonly _onComponentSelect;
private readonly _onComponentLeave;
private selectedDirective!: {directive: unknown; host: Element | null};
private readonly onComponentEnter;
private readonly onComponentSelect;
private readonly onComponentLeave;
private currentHighlight: Highlight | null = null;
constructor(
@@ -39,9 +39,9 @@ export class ComponentInspector {
},
) {
this.bindMethods();
this._onComponentEnter = componentOptions.onComponentEnter;
this._onComponentSelect = componentOptions.onComponentSelect;
this._onComponentLeave = componentOptions.onComponentLeave;
this.onComponentEnter = componentOptions.onComponentEnter;
this.onComponentSelect = componentOptions.onComponentSelect;
this.onComponentLeave = componentOptions.onComponentLeave;
}
startInspecting(): void {
@@ -61,9 +61,9 @@ export class ComponentInspector {
e.stopImmediatePropagation();
e.preventDefault();
if (this._selectedDirective.directive && this._selectedDirective.host) {
this._onComponentSelect(
getDirectiveForestManager().getDirectiveId(this._selectedDirective.directive)!,
if (this.selectedDirective.directive && this.selectedDirective.host) {
this.onComponentSelect(
getDirectiveForestManager().getDirectiveId(this.selectedDirective.directive)!,
);
}
}
@@ -73,14 +73,14 @@ export class ComponentInspector {
const el = e.target;
if (el instanceof Node) {
this._selectedDirective = findDirectiveAndHost(el);
this.selectedDirective = findDirectiveAndHost(el);
}
this.unhighlight();
if (this._selectedDirective.directive && this._selectedDirective.host) {
this.highlightElement(this._selectedDirective.host);
this._onComponentEnter(
getDirectiveForestManager().getDirectiveId(this._selectedDirective.directive)!,
if (this.selectedDirective.directive && this.selectedDirective.host) {
this.highlightElement(this.selectedDirective.host);
this.onComponentEnter(
getDirectiveForestManager().getDirectiveId(this.selectedDirective.directive)!,
);
}
}
@@ -88,7 +88,7 @@ export class ComponentInspector {
cancelEvent(e: MouseEvent): void {
e.stopImmediatePropagation();
e.preventDefault();
this._onComponentLeave();
this.onComponentLeave();
}
bindMethods(): void {
@@ -20,13 +20,13 @@ let directiveForestManager: DirectiveForestManager;
* Delegates forest indexing to IdentityTracker Singleton.
*/
export class DirectiveForestManager {
private _tracker = IdentityTracker.getInstance();
private _forest: ComponentTreeNode[] = [];
private _indexedForest: IndexedNode[] = [];
private _indexForestCbs: ((output: IndexingOutput) => void)[] = [];
private tracker = IdentityTracker.getInstance();
private forest: ComponentTreeNode[] = [];
private indexedForest: IndexedNode[] = [];
private indexForestCbs: ((output: IndexingOutput) => void)[] = [];
getDirectivePosition(dir: DirectiveInstance): ElementPosition | undefined {
const result = this._tracker.getDirectivePosition(dir);
const result = this.tracker.getDirectivePosition(dir);
if (result === undefined) {
debugLog.warn('Unable to find position of', dir);
}
@@ -34,7 +34,7 @@ export class DirectiveForestManager {
}
getDirectiveId(dir: DirectiveInstance): number | undefined {
const result = this._tracker.getDirectiveId(dir);
const result = this.tracker.getDirectiveId(dir);
if (result === undefined) {
debugLog.warn('Unable to find ID of', result);
}
@@ -42,11 +42,11 @@ export class DirectiveForestManager {
}
getIndexedDirectiveForest(): IndexedNode[] {
return this._indexedForest;
return this.indexedForest;
}
getDirectiveForest(): ComponentTreeNode[] {
return this._forest;
return this.forest;
}
initialize(): void {
@@ -54,11 +54,11 @@ export class DirectiveForestManager {
}
indexForest(): void {
const output = this._tracker.index();
this._indexedForest = output.indexedForest;
this._forest = output.directiveForest;
const output = this.tracker.index();
this.indexedForest = output.indexedForest;
this.forest = output.directiveForest;
for (const cb of this._indexForestCbs) {
for (const cb of this.indexForestCbs) {
cb(output);
}
}
@@ -70,12 +70,12 @@ export class DirectiveForestManager {
* @returns An unlisten function.
*/
onIndexForest(cb: (output: IndexingOutput) => void) {
this._indexForestCbs.push(cb);
this.indexForestCbs.push(cb);
return () => {
const idx = this._indexForestCbs.indexOf(cb);
const idx = this.indexForestCbs.indexOf(cb);
if (idx > -1) {
this._indexForestCbs.splice(idx, 1);
this.indexForestCbs.splice(idx, 1);
}
};
}
@@ -85,7 +85,7 @@ export class LTreeStrategy {
return typeof (element as any).__ngContext__ !== 'undefined';
}
private _getNode(lView: LView, data: any, idx: number): ComponentTreeNode {
private getNode(lView: LView, data: any, idx: number): ComponentTreeNode {
const directives: DirectiveInstanceType[] = [];
let component: ComponentInstanceType | null = null;
const tNode = data[idx];
@@ -129,11 +129,11 @@ export class LTreeStrategy {
};
}
private _extract(lViewOrLContainer: any, nodes: ComponentTreeNode[] = []): ComponentTreeNode[] {
private extract(lViewOrLContainer: any, nodes: ComponentTreeNode[] = []): ComponentTreeNode[] {
if (isLContainer(lViewOrLContainer)) {
for (let i = 9; i < lViewOrLContainer.length; i++) {
if (lViewOrLContainer[i]) {
this._extract(lViewOrLContainer[i], nodes);
this.extract(lViewOrLContainer[i], nodes);
}
}
return nodes;
@@ -143,12 +143,12 @@ export class LTreeStrategy {
for (let i = HEADER_OFFSET; i < lView.length; i++) {
const lViewItem = lView[i];
if (tView.data && Array.isArray(lViewItem) && lViewItem[ELEMENT] instanceof Node) {
const node = this._getNode(lView, tView.data, i);
const node = this.getNode(lView, tView.data, i);
// TODO(mgechev): verify if this won't make us skip projected content.
if (node.component || node.directives?.length) {
nodes.push(node);
this._extract(lViewItem, node.children);
this.extract(lViewItem, node.children);
}
}
}
@@ -158,7 +158,7 @@ export class LTreeStrategy {
build(element: Element, _: number): ComponentTreeNode[] {
const ctx = (element as any).__ngContext__;
const rootLView = ctx.lView ?? ctx;
return this._extract(rootLView);
return this.extract(rootLView);
}
}
@@ -19,52 +19,52 @@ type ProfilerCallback = (event: ɵProfilerEvent, instanceOrLView: {} | null, eve
/** Implementation of Profiler that utilizes framework APIs fire profiler hooks. */
export class NgProfiler extends Profiler {
private _tracker = IdentityTracker.getInstance();
private _callbacks: ProfilerCallback[] = [];
private _lastDirectiveInstance: {} | null = null;
private tracker = IdentityTracker.getInstance();
private callbacks: ProfilerCallback[] = [];
private lastDirectiveInstance: {} | null = null;
constructor(config: Partial<Hooks> = {}) {
super(config);
this._setProfilerCallback((event: ɵProfilerEvent, instanceOrLView: {} | null, eventFn: any) => {
this.setProfilerCallback((event: ɵProfilerEvent, instanceOrLView: {} | null, eventFn: any) => {
if (this[event] === undefined) {
return;
}
this[event](instanceOrLView, eventFn);
});
this._initialize();
this.initialize();
}
private _initialize(): void {
private initialize(): void {
ngDebugClient().ɵsetProfiler!(
(event: ɵProfilerEvent, instanceOrLView: {} | null = null, eventFn: any) =>
this._callbacks.forEach((cb) => cb(event, instanceOrLView, eventFn)),
this.callbacks.forEach((cb) => cb(event, instanceOrLView, eventFn)),
);
}
private _setProfilerCallback(callback: ProfilerCallback): void {
this._callbacks.push(callback);
private setProfilerCallback(callback: ProfilerCallback): void {
this.callbacks.push(callback);
}
override destroy(): void {
this._tracker.destroy();
this.tracker.destroy();
}
override onIndexForest(newNodes: NodeArray, removedNodes: NodeArray): void {
newNodes.forEach((node) => {
const {directive, isComponent} = node;
const position = this._tracker.getDirectivePosition(directive);
const id = this._tracker.getDirectiveId(directive);
this._onCreate(directive, getDirectiveHostElement(directive), id, isComponent, position);
const position = this.tracker.getDirectivePosition(directive);
const id = this.tracker.getDirectiveId(directive);
this.onCreate(directive, getDirectiveHostElement(directive), id, isComponent, position);
});
removedNodes.forEach((node) => {
const {directive, isComponent} = node;
const position = this._tracker.getDirectivePosition(directive);
const id = this._tracker.getDirectiveId(directive);
this._onDestroy(directive, getDirectiveHostElement(directive), id, isComponent, position);
const position = this.tracker.getDirectivePosition(directive);
const id = this.tracker.getDirectiveId(directive);
this.onDestroy(directive, getDirectiveHostElement(directive), id, isComponent, position);
});
}
@@ -169,88 +169,88 @@ export class NgProfiler extends Profiler {
}
[ɵProfilerEvent.TemplateUpdateStart](context: DirectiveInstance, _eventFn: any): void {
if (!this._inChangeDetection) {
this._inChangeDetection = true;
if (!this.inChangeDetection) {
this.inChangeDetection = true;
runOutsideAngular(() => {
Promise.resolve().then(() => {
this.changeDetection$.next();
this._inChangeDetection = false;
this.inChangeDetection = false;
});
});
}
const position = this._tracker.getDirectivePosition(context);
const id = this._tracker.getDirectiveId(context);
const position = this.tracker.getDirectivePosition(context);
const id = this.tracker.getDirectiveId(context);
// If we can find the position and the ID we assume that this is a component instance.
// Alternatively, if we can't find the ID or the position, we assume that this is a
// context of an embedded view (for example, NgForOfContext, NgIfContext, or a custom one).
if (position !== undefined && id !== undefined) {
this._lastDirectiveInstance = context;
this.lastDirectiveInstance = context;
}
if (id !== undefined && position !== undefined) {
this._onChangeDetectionStart(context, getDirectiveHostElement(context), id, position);
this.onChangeDetectionStart(context, getDirectiveHostElement(context), id, position);
return;
}
this._onChangeDetectionStart(
this._lastDirectiveInstance,
getDirectiveHostElement(this._lastDirectiveInstance),
this._tracker.getDirectiveId(this._lastDirectiveInstance),
this._tracker.getDirectivePosition(this._lastDirectiveInstance),
this.onChangeDetectionStart(
this.lastDirectiveInstance,
getDirectiveHostElement(this.lastDirectiveInstance),
this.tracker.getDirectiveId(this.lastDirectiveInstance),
this.tracker.getDirectivePosition(this.lastDirectiveInstance),
);
}
[ɵProfilerEvent.TemplateUpdateEnd](context: any, _eventFn: any): void {
const position = this._tracker.getDirectivePosition(context);
const id = this._tracker.getDirectiveId(context);
const position = this.tracker.getDirectivePosition(context);
const id = this.tracker.getDirectiveId(context);
if (this._tracker.hasDirective(context) && id !== undefined && position !== undefined) {
this._onChangeDetectionEnd(context, getDirectiveHostElement(context), id, position);
if (this.tracker.hasDirective(context) && id !== undefined && position !== undefined) {
this.onChangeDetectionEnd(context, getDirectiveHostElement(context), id, position);
return;
}
this._onChangeDetectionEnd(
this._lastDirectiveInstance,
getDirectiveHostElement(this._lastDirectiveInstance),
this._tracker.getDirectiveId(this._lastDirectiveInstance),
this._tracker.getDirectivePosition(this._lastDirectiveInstance),
this.onChangeDetectionEnd(
this.lastDirectiveInstance,
getDirectiveHostElement(this.lastDirectiveInstance),
this.tracker.getDirectiveId(this.lastDirectiveInstance),
this.tracker.getDirectivePosition(this.lastDirectiveInstance),
);
}
[ɵProfilerEvent.LifecycleHookStart](directive: DirectiveInstance, hook: any): void {
const id = this._tracker.getDirectiveId(directive);
const id = this.tracker.getDirectiveId(directive);
const element = getDirectiveHostElement(directive);
const lifecycleHookName = getLifeCycleName(directive, hook);
const isComponent = !!this._tracker.isComponent.get(directive);
const isComponent = !!this.tracker.isComponent.get(directive);
this._onLifecycleHookStart(directive, lifecycleHookName, element, id, isComponent);
this.onLifecycleHookStart(directive, lifecycleHookName, element, id, isComponent);
}
[ɵProfilerEvent.LifecycleHookEnd](directive: DirectiveInstance, hook: any): void {
const id = this._tracker.getDirectiveId(directive);
const id = this.tracker.getDirectiveId(directive);
const element = getDirectiveHostElement(directive);
const lifecycleHookName = getLifeCycleName(directive, hook);
const isComponent = !!this._tracker.isComponent.get(directive);
const isComponent = !!this.tracker.isComponent.get(directive);
this._onLifecycleHookEnd(directive, lifecycleHookName, element, id, isComponent);
this.onLifecycleHookEnd(directive, lifecycleHookName, element, id, isComponent);
}
[ɵProfilerEvent.OutputStart](
componentOrDirective: DirectiveInstance,
listener: () => void,
): void {
const isComponent = !!this._tracker.isComponent.get(componentOrDirective);
const isComponent = !!this.tracker.isComponent.get(componentOrDirective);
const node = getDirectiveHostElement(componentOrDirective);
const id = this._tracker.getDirectiveId(componentOrDirective);
this._onOutputStart(componentOrDirective, listener.name, node, id, isComponent);
const id = this.tracker.getDirectiveId(componentOrDirective);
this.onOutputStart(componentOrDirective, listener.name, node, id, isComponent);
}
[ɵProfilerEvent.OutputEnd](componentOrDirective: DirectiveInstance, listener: () => void): void {
const isComponent = !!this._tracker.isComponent.get(componentOrDirective);
const isComponent = !!this.tracker.isComponent.get(componentOrDirective);
const node = getDirectiveHostElement(componentOrDirective);
const id = this._tracker.getDirectiveId(componentOrDirective);
this._onOutputEnd(componentOrDirective, listener.name, node, id, isComponent);
const id = this.tracker.getDirectiveId(componentOrDirective);
this.onOutputEnd(componentOrDirective, listener.name, node, id, isComponent);
}
}
@@ -34,49 +34,49 @@ const componentMetadata = (instance: ComponentInstance) => instance?.constructor
* methods to fire profiler hooks.
*/
export class PatchingProfiler extends Profiler {
private _patched = new Map<ComponentInstance, () => void>();
private _undoLifecyclePatch: (() => void)[] = [];
private _tracker = IdentityTracker.getInstance();
private patched = new Map<ComponentInstance, () => void>();
private undoLifecyclePatch: (() => void)[] = [];
private tracker = IdentityTracker.getInstance();
override destroy(): void {
this._tracker.destroy();
this.tracker.destroy();
for (const [cmp, template] of this._patched) {
for (const [cmp, template] of this.patched) {
const meta = componentMetadata(cmp);
meta.template = template;
meta.tView.template = template;
}
this._patched = new Map<ComponentInstance, () => void>();
this._undoLifecyclePatch.forEach((p) => p());
this._undoLifecyclePatch = [];
this.patched = new Map<ComponentInstance, () => void>();
this.undoLifecyclePatch.forEach((p) => p());
this.undoLifecyclePatch = [];
}
override onIndexForest(newNodes: NodeArray, removedNodes: NodeArray): void {
newNodes.forEach((node) => {
this._observeLifecycle(node.directive, node.isComponent);
this._observeComponent(node.directive);
this._fireCreationCallback(node.directive, node.isComponent);
this.observeLifecycle(node.directive, node.isComponent);
this.observeComponent(node.directive);
this.fireCreationCallback(node.directive, node.isComponent);
});
removedNodes.forEach((node) => {
this._patched.delete(node.directive);
this._fireDestroyCallback(node.directive, node.isComponent);
this.patched.delete(node.directive);
this.fireDestroyCallback(node.directive, node.isComponent);
});
}
private _fireCreationCallback(component: ComponentInstance, isComponent: boolean): void {
const position = this._tracker.getDirectivePosition(component);
const id = this._tracker.getDirectiveId(component);
this._onCreate(component, getDirectiveHostElement(component), id, isComponent, position);
private fireCreationCallback(component: ComponentInstance, isComponent: boolean): void {
const position = this.tracker.getDirectivePosition(component);
const id = this.tracker.getDirectiveId(component);
this.onCreate(component, getDirectiveHostElement(component), id, isComponent, position);
}
private _fireDestroyCallback(component: ComponentInstance, isComponent: boolean): void {
const position = this._tracker.getDirectivePosition(component);
const id = this._tracker.getDirectiveId(component);
this._onDestroy(component, getDirectiveHostElement(component), id, isComponent, position);
private fireDestroyCallback(component: ComponentInstance, isComponent: boolean): void {
const position = this.tracker.getDirectivePosition(component);
const id = this.tracker.getDirectiveId(component);
this.onDestroy(component, getDirectiveHostElement(component), id, isComponent, position);
}
private _observeComponent(cmp: ComponentInstance): void {
private observeComponent(cmp: ComponentInstance): void {
const declarations = componentMetadata(cmp);
if (!declarations) {
return;
@@ -87,29 +87,29 @@ export class PatchingProfiler extends Profiler {
return;
}
declarations.tView.template = function (_: any, component: ComponentInstance): void {
if (!self._inChangeDetection) {
self._inChangeDetection = true;
if (!self.inChangeDetection) {
self.inChangeDetection = true;
runOutsideAngular(() => {
Promise.resolve().then(() => {
self.changeDetection$.next();
self._inChangeDetection = false;
self.inChangeDetection = false;
});
});
}
const position = self._tracker.getDirectivePosition(component);
const id = self._tracker.getDirectiveId(component);
const position = self.tracker.getDirectivePosition(component);
const id = self.tracker.getDirectiveId(component);
self._onChangeDetectionStart(component, getDirectiveHostElement(component), id, position);
self.onChangeDetectionStart(component, getDirectiveHostElement(component), id, position);
original.apply(this, arguments);
if (self._tracker.hasDirective(component) && id !== undefined && position !== undefined) {
self._onChangeDetectionEnd(component, getDirectiveHostElement(component), id, position);
if (self.tracker.hasDirective(component) && id !== undefined && position !== undefined) {
self.onChangeDetectionEnd(component, getDirectiveHostElement(component), id, position);
}
};
declarations.tView.template.patched = true;
this._patched.set(cmp, original);
this.patched.set(cmp, original);
}
private _observeLifecycle(directive: DirectiveInstance, isComponent: boolean): void {
private observeLifecycle(directive: DirectiveInstance, isComponent: boolean): void {
const ctx = getLViewFromDirectiveOrElementInstance(directive);
if (!ctx) {
return;
@@ -135,16 +135,16 @@ export class PatchingProfiler extends Profiler {
if (!(this as any)[METADATA_PROPERTY_NAME]) {
return;
}
const id = self._tracker.getDirectiveId(this);
const id = self.tracker.getDirectiveId(this);
const lifecycleHookName = getLifeCycleName(this, el);
const element = getDirectiveHostElement(this);
self._onLifecycleHookStart(this, lifecycleHookName, element, id, isComponent);
self.onLifecycleHookStart(this, lifecycleHookName, element, id, isComponent);
const result = el.apply(this, arguments);
self._onLifecycleHookEnd(this, lifecycleHookName, element, id, isComponent);
self.onLifecycleHookEnd(this, lifecycleHookName, element, id, isComponent);
return result;
};
current[idx].patched = true;
this._undoLifecyclePatch.push(() => {
this.undoLifecyclePatch.push(() => {
current[idx] = el;
});
}
@@ -91,14 +91,14 @@ export interface Hooks {
*/
export abstract class Profiler {
/** @internal */
protected _inChangeDetection = false;
protected inChangeDetection = false;
changeDetection$ = new Subject<void>();
private _hooks: Partial<Hooks>[] = [];
private hooks: Partial<Hooks>[] = [];
constructor(config: Partial<Hooks> = {}) {
this._hooks.push(config);
this.hooks.push(config);
}
abstract destroy(): void;
@@ -106,15 +106,15 @@ export abstract class Profiler {
abstract onIndexForest(newNodes: NodeArray, removedNodes: NodeArray): void;
subscribe(config: Partial<Hooks>): void {
this._hooks.push(config);
this.hooks.push(config);
}
unsubscribe(config: Partial<Hooks>): void {
this._hooks.splice(this._hooks.indexOf(config), 1);
this.hooks.splice(this.hooks.indexOf(config), 1);
}
/** @internal */
protected _onCreate(
protected onCreate(
_: DirectiveInstance,
hook: Node,
id: number | undefined,
@@ -124,11 +124,11 @@ export abstract class Profiler {
if (id === undefined || position === undefined) {
return;
}
this._invokeCallback('onCreate', [_, hook, id, node, position]);
this.invokeCallback('onCreate', [_, hook, id, node, position]);
}
/** @internal */
protected _onDestroy(
protected onDestroy(
_: DirectiveInstance,
hook: Node,
id: number | undefined,
@@ -138,11 +138,11 @@ export abstract class Profiler {
if (id === undefined || position === undefined) {
return;
}
this._invokeCallback('onDestroy', [_, hook, id, node, position]);
this.invokeCallback('onDestroy', [_, hook, id, node, position]);
}
/** @internal */
protected _onChangeDetectionStart(
protected onChangeDetectionStart(
_: ComponentInstance,
hook: Node,
id: number | undefined,
@@ -151,11 +151,11 @@ export abstract class Profiler {
if (id === undefined || position === undefined) {
return;
}
this._invokeCallback('onChangeDetectionStart', [_, hook, id, position]);
this.invokeCallback('onChangeDetectionStart', [_, hook, id, position]);
}
/** @internal */
protected _onChangeDetectionEnd(
protected onChangeDetectionEnd(
_: ComponentInstance,
hook: Node,
id: number | undefined,
@@ -164,11 +164,11 @@ export abstract class Profiler {
if (id === undefined || position === undefined) {
return;
}
this._invokeCallback('onChangeDetectionEnd', [_, hook, id, position]);
this.invokeCallback('onChangeDetectionEnd', [_, hook, id, position]);
}
/** @internal */
protected _onLifecycleHookStart(
protected onLifecycleHookStart(
componentOrDirective: DirectiveInstance,
hook: keyof LifecycleProfile | 'unknown',
node: Node,
@@ -179,7 +179,7 @@ export abstract class Profiler {
return;
}
const a = arguments;
this._invokeCallback('onLifecycleHookStart', [
this.invokeCallback('onLifecycleHookStart', [
componentOrDirective,
hook,
node,
@@ -189,7 +189,7 @@ export abstract class Profiler {
}
/** @internal */
protected _onLifecycleHookEnd(
protected onLifecycleHookEnd(
componentOrDirective: DirectiveInstance,
hook: keyof LifecycleProfile | 'unknown',
node: Node,
@@ -199,11 +199,11 @@ export abstract class Profiler {
if (id === undefined || hook === 'unknown') {
return;
}
this._invokeCallback('onLifecycleHookEnd', [componentOrDirective, hook, node, id, isComponent]);
this.invokeCallback('onLifecycleHookEnd', [componentOrDirective, hook, node, id, isComponent]);
}
/** @internal */
protected _onOutputStart(
protected onOutputStart(
componentOrDirective: DirectiveInstance,
hook: string,
node: Node,
@@ -213,11 +213,11 @@ export abstract class Profiler {
if (id === undefined) {
return;
}
this._invokeCallback('onOutputStart', [componentOrDirective, hook, node, id, isComponent]);
this.invokeCallback('onOutputStart', [componentOrDirective, hook, node, id, isComponent]);
}
/** @internal */
protected _onOutputEnd(
protected onOutputEnd(
componentOrDirective: DirectiveInstance,
hook: string,
node: Node,
@@ -227,12 +227,12 @@ export abstract class Profiler {
if (id === undefined) {
return;
}
this._invokeCallback('onOutputEnd', [componentOrDirective, hook, node, id, isComponent]);
this.invokeCallback('onOutputEnd', [componentOrDirective, hook, node, id, isComponent]);
}
/** @internal */
private _invokeCallback<K extends keyof Hooks>(name: K, args: Parameters<Hooks[K]>): void {
this._hooks.forEach((config) => {
private invokeCallback<K extends keyof Hooks>(name: K, args: Parameters<Hooks[K]>): void {
this.hooks.forEach((config) => {
const cb = (config as Hooks)[name];
if (typeof cb === 'function') {
(cb as Function).apply(null, args);
@@ -15,25 +15,25 @@ import {Frame, TOP_LEVEL_FRAME_ID} from '../application-environment';
@Injectable()
export class FrameManager {
private _selectedFrameId = signal<number | null>(null);
private _frames = signal(new Map<number, Frame>());
private _inspectedWindowTabId: number | null = null;
private _frameUrlToFrameIds = new Map<string, Set<number>>();
private _messageBus = inject<MessageBus<Events>>(MessageBus);
private selectedFrameId = signal<number | null>(null);
private framesMap = signal(new Map<number, Frame>());
private inspectedWindowTabId: number | null = null;
private frameUrlToFrameIds = new Map<string, Set<number>>();
private messageBus = inject<MessageBus<Events>>(MessageBus);
readonly frames = computed(() => Array.from(this._frames().values()));
readonly frames = computed(() => Array.from(this.framesMap().values()));
readonly selectedFrame = computed(() => {
const selectedFrameId = this._selectedFrameId();
const selectedFrameId = this.selectedFrameId();
if (selectedFrameId === null) {
return null;
}
return this._frames().get(selectedFrameId) ?? null;
return this.framesMap().get(selectedFrameId) ?? null;
});
readonly topLevelFrameIsActive = computed(() => {
return this._selectedFrameId() === TOP_LEVEL_FRAME_ID;
return this.selectedFrameId() === TOP_LEVEL_FRAME_ID;
});
readonly activeFrameHasUniqueUrl = computed(() => {
@@ -48,18 +48,18 @@ export class FrameManager {
private initialize(inspectedWindowTabIdTestOnly?: number | null): void {
if (inspectedWindowTabIdTestOnly === undefined) {
this._inspectedWindowTabId = globalThis.chrome.devtools.inspectedWindow.tabId;
this.inspectedWindowTabId = globalThis.chrome.devtools.inspectedWindow.tabId;
} else {
this._inspectedWindowTabId = inspectedWindowTabIdTestOnly;
this.inspectedWindowTabId = inspectedWindowTabIdTestOnly;
}
this._messageBus.on('frameConnected', (frameId: number) => {
if (this._frames().has(frameId)) {
this._selectedFrameId.set(frameId);
this.messageBus.on('frameConnected', (frameId: number) => {
if (this.framesMap().has(frameId)) {
this.selectedFrameId.set(frameId);
}
});
this._messageBus.on('contentScriptConnected', (frameId: number, name: string, url: string) => {
this.messageBus.on('contentScriptConnected', (frameId: number, name: string, url: string) => {
// fragments are not considered when doing URL matching on a page
// https://bugs.chromium.org/p/chromium/issues/detail?id=841429
const urlWithoutHash = new URL(url);
@@ -68,12 +68,12 @@ export class FrameManager {
this.addFrame({name, id: frameId, url: urlWithoutHash});
if (this.frames().length === 1) {
this.inspectFrame(this._frames().get(frameId)!);
this.inspectFrame(this.framesMap().get(frameId)!);
}
});
this._messageBus.on('contentScriptDisconnected', (frameId: number) => {
const frame = this._frames().get(frameId);
this.messageBus.on('contentScriptDisconnected', (frameId: number) => {
const frame = this.framesMap().get(frameId);
if (!frame) {
return;
}
@@ -83,35 +83,35 @@ export class FrameManager {
// Defensive check. This case should never happen, since we're always connected to at least
// the top level frame.
if (this.frames().length === 0) {
this._selectedFrameId.set(null);
this.selectedFrameId.set(null);
console.error('Angular DevTools is not connected to any frames.');
return;
}
const selectedFrameId = this._selectedFrameId();
const selectedFrameId = this.selectedFrameId();
if (frameId === selectedFrameId) {
this._selectedFrameId.set(TOP_LEVEL_FRAME_ID);
this.inspectFrame(this._frames().get(TOP_LEVEL_FRAME_ID)!);
this.selectedFrameId.set(TOP_LEVEL_FRAME_ID);
this.inspectFrame(this.framesMap().get(TOP_LEVEL_FRAME_ID)!);
return;
}
});
}
isSelectedFrame(frame: Frame): boolean {
return this._selectedFrameId() === frame.id;
return this.selectedFrameId() === frame.id;
}
inspectFrame(frame: Frame): void {
if (this._inspectedWindowTabId === null) {
if (this.inspectedWindowTabId === null) {
return;
}
if (!this._frames().has(frame.id)) {
if (!this.framesMap().has(frame.id)) {
throw new Error('Attempted to inspect a frame that is not connected to Angular DevTools.');
}
this._selectedFrameId.set(null);
this._messageBus.emit('enableFrameConnection', [frame.id, this._inspectedWindowTabId]);
this.selectedFrameId.set(null);
this.messageBus.emit('enableFrameConnection', [frame.id, this.inspectedWindowTabId]);
}
private frameHasUniqueUrl(frame: Frame | null): boolean {
@@ -119,17 +119,17 @@ export class FrameManager {
return false;
}
const frameUrl = frame.url.toString();
const frameIds = this._frameUrlToFrameIds.get(frameUrl) ?? new Set<number>();
const frameIds = this.frameUrlToFrameIds.get(frameUrl) ?? new Set<number>();
return frameIds.size === 1;
}
private addFrame(frame: Frame): void {
this._frames.update((frames) => {
this.framesMap.update((frames) => {
frames.set(frame.id, frame);
const frameUrl = frame.url.toString();
const frameIdSet = this._frameUrlToFrameIds.get(frameUrl) ?? new Set<number>();
const frameIdSet = this.frameUrlToFrameIds.get(frameUrl) ?? new Set<number>();
frameIdSet.add(frame.id);
this._frameUrlToFrameIds.set(frameUrl, frameIdSet);
this.frameUrlToFrameIds.set(frameUrl, frameIdSet);
return new Map(frames);
});
}
@@ -137,12 +137,12 @@ export class FrameManager {
private removeFrame(frame: Frame): void {
const frameId = frame.id;
const frameUrl = frame.url.toString();
const urlFrameIds = this._frameUrlToFrameIds.get(frameUrl) ?? new Set<number>();
const urlFrameIds = this.frameUrlToFrameIds.get(frameUrl) ?? new Set<number>();
urlFrameIds.delete(frameId);
if (urlFrameIds.size === 0) {
this._frameUrlToFrameIds.delete(frameUrl);
this.frameUrlToFrameIds.delete(frameUrl);
}
this._frames.update((frames) => {
this.framesMap.update((frames) => {
frames.delete(frameId);
return new Map(frames);
});
@@ -119,13 +119,13 @@ export class DirectiveExplorerComponent {
readonly signalsOpen = signal(false);
private _clickedElement: IndexedNode | null = null;
private _refreshRetryTimeout: null | ReturnType<typeof setTimeout> = null;
private clickedElement: IndexedNode | null = null;
private refreshRetryTimeout: null | ReturnType<typeof setTimeout> = null;
private readonly _appOperations = inject(ApplicationOperations);
private readonly _messageBus = inject<MessageBus<Events>>(MessageBus);
private readonly _propResolver = inject(ElementPropertyResolver);
private readonly _frameManager = inject(FrameManager);
private readonly appOperations = inject(ApplicationOperations);
private readonly messageBus = inject<MessageBus<Events>>(MessageBus);
private readonly propResolver = inject(ElementPropertyResolver);
private readonly frameManager = inject(FrameManager);
private readonly settings = inject(Settings);
private readonly platform = inject(Platform);
@@ -176,7 +176,7 @@ export class DirectiveExplorerComponent {
}
private isNonTopLevelFirefoxFrame() {
return this.platform.FIREFOX && !this._frameManager.topLevelFrameIsActive();
return this.platform.FIREFOX && !this.frameManager.topLevelFrameIsActive();
}
handleNodeSelection(node: IndexedNode | null): void {
@@ -185,47 +185,47 @@ export class DirectiveExplorerComponent {
// That's possible if the user has selected an NgForOf and after that
// they select another NgForOf instance. In this case, we don't want to diff the props
// we want to render from scratch.
if (this._clickedElement && !sameDirectives(this._clickedElement, node)) {
this._propResolver.clearProperties();
if (this.clickedElement && !sameDirectives(this.clickedElement, node)) {
this.propResolver.clearProperties();
}
this._clickedElement = node;
this._messageBus.emit('setSelectedComponent', [node.position]);
this.clickedElement = node;
this.messageBus.emit('setSelectedComponent', [node.position]);
this.refresh();
} else {
this._clickedElement = null;
this.clickedElement = null;
this.currentSelectedElement.set(null);
}
}
subscribeToBackendEvents(): void {
this._messageBus.on('latestComponentExplorerView', (view: ComponentExplorerView) => {
this.messageBus.on('latestComponentExplorerView', (view: ComponentExplorerView) => {
this.forest.set(view.forest);
this.currentSelectedElement.set(this._clickedElement);
if (view.properties && this._clickedElement) {
this._propResolver.setProperties(this._clickedElement, view.properties);
this.currentSelectedElement.set(this.clickedElement);
if (view.properties && this.clickedElement) {
this.propResolver.setProperties(this.clickedElement, view.properties);
}
});
this._messageBus.on('componentTreeDirty', () => this.refresh());
this.messageBus.on('componentTreeDirty', () => this.refresh());
this._messageBus.on('latestCdData', (cdData) => this.cdData.set(cdData));
this.messageBus.on('latestCdData', (cdData) => this.cdData.set(cdData));
}
refresh(): void {
const success = this._messageBus.emit('getLatestComponentExplorerView', [
this._constructViewQuery(),
const success = this.messageBus.emit('getLatestComponentExplorerView', [
this.constructViewQuery(),
]);
this._messageBus.emit('getRoutes');
this.messageBus.emit('getRoutes');
// If the event was not throttled, we no longer need to retry.
if (success) {
this._refreshRetryTimeout && clearTimeout(this._refreshRetryTimeout);
this._refreshRetryTimeout = null;
this.refreshRetryTimeout && clearTimeout(this.refreshRetryTimeout);
this.refreshRetryTimeout = null;
return;
}
// If the event was throttled and we haven't scheduled a retry yet.
if (!this._refreshRetryTimeout) {
this._refreshRetryTimeout = setTimeout(() => this.refresh(), 500);
if (!this.refreshRetryTimeout) {
this.refreshRetryTimeout = setTimeout(() => this.refresh(), 500);
}
}
@@ -237,20 +237,20 @@ export class DirectiveExplorerComponent {
const directiveIndex =
selectedEl.directives?.findIndex((directive) => directive.name === directiveName) ?? -1;
const selectedFrame = this._frameManager.selectedFrame();
if (!this._frameManager.activeFrameHasUniqueUrl()) {
const selectedFrame = this.frameManager.selectedFrame();
if (!this.frameManager.activeFrameHasUniqueUrl()) {
const error = `The currently inspected frame does not have a unique url on this page. Cannot view source.`;
this.snackBar.open(error, 'Dismiss', {duration: 5000, horizontalPosition: 'left'});
this._messageBus.emit('log', [{level: 'warn', message: error}]);
this.messageBus.emit('log', [{level: 'warn', message: error}]);
return;
}
if (this.isNonTopLevelFirefoxFrame()) {
const error = `Viewing source is not supported in Firefox when the inspected frame is not the top-level frame.`;
this.snackBar.open(error, 'Dismiss', {duration: 5000, horizontalPosition: 'left'});
this._messageBus.emit('log', [{level: 'warn', message: error}]);
this.messageBus.emit('log', [{level: 'warn', message: error}]);
} else {
this._appOperations.viewSource(
this.appOperations.viewSource(
selectedEl.position,
selectedFrame!,
directiveIndex !== -1 ? directiveIndex : undefined,
@@ -259,20 +259,20 @@ export class DirectiveExplorerComponent {
}
handleSelectDomElement(node: IndexedNode): void {
const selectedFrame = this._frameManager.selectedFrame();
if (!this._frameManager.activeFrameHasUniqueUrl()) {
const selectedFrame = this.frameManager.selectedFrame();
if (!this.frameManager.activeFrameHasUniqueUrl()) {
const error = `The currently inspected frame does not have a unique url on this page. Cannot select DOM element.`;
this.snackBar.open(error, 'Dismiss', {duration: 5000, horizontalPosition: 'left'});
this._messageBus.emit('log', [{level: 'warn', message: error}]);
this.messageBus.emit('log', [{level: 'warn', message: error}]);
return;
}
if (this.isNonTopLevelFirefoxFrame()) {
const error = `Inspecting a component's DOM element is not supported in Firefox when the inspected frame is not the top-level frame.`;
this.snackBar.open(error, 'Dismiss', {duration: 5000, horizontalPosition: 'left'});
this._messageBus.emit('log', [{level: 'warn', message: error}]);
this.messageBus.emit('log', [{level: 'warn', message: error}]);
} else {
this._appOperations.selectDomElement(node.position, selectedFrame!);
this.appOperations.selectDomElement(node.position, selectedFrame!);
}
}
@@ -280,32 +280,32 @@ export class DirectiveExplorerComponent {
if (!node.hasNativeElement) {
return;
}
this._messageBus.emit('createHighlightOverlay', [node.position]);
this.messageBus.emit('createHighlightOverlay', [node.position]);
}
unhighlight(): void {
this._messageBus.emit('removeHighlightOverlay');
this.messageBus.emit('removeHighlightOverlay');
}
private _constructViewQuery(): ComponentExplorerViewQuery | undefined {
if (!this._clickedElement) {
private constructViewQuery(): ComponentExplorerViewQuery | undefined {
if (!this.clickedElement) {
return;
}
return {
selectedElement: this._clickedElement.position,
propertyQuery: this._getPropertyQuery(),
selectedElement: this.clickedElement.position,
propertyQuery: this.getPropertyQuery(),
};
}
private _getPropertyQuery(): PropertyQuery {
private getPropertyQuery(): PropertyQuery {
// Here we handle the case when a given element has already been selected.
// We check if we're dealing with the same instance (i.e., if we have the same
// set of directives and component on it), if we do, we want to get the same
// set of properties which are already expanded.
if (
!this._clickedElement ||
!this.clickedElement ||
!this.currentSelectedElement() ||
!sameDirectives(this._clickedElement, this.currentSelectedElement()!)
!sameDirectives(this.clickedElement, this.currentSelectedElement()!)
) {
return {
type: PropertyQueryTypes.All,
@@ -313,16 +313,16 @@ export class DirectiveExplorerComponent {
}
return {
type: PropertyQueryTypes.Specified,
properties: this._propResolver.getExpandedProperties() || {},
properties: this.propResolver.getExpandedProperties() || {},
};
}
highlightComponent(position: ElementPosition): void {
this._messageBus.emit('createHighlightOverlay', [position]);
this.messageBus.emit('createHighlightOverlay', [position]);
}
removeComponentHighlight(): void {
this._messageBus.emit('removeHighlightOverlay');
this.messageBus.emit('removeHighlightOverlay');
}
handleSelect(node: FlatNode): void {
@@ -342,21 +342,21 @@ export class DirectiveExplorerComponent {
}): void {
const objectPath = constructPathOfKeysToPropertyValue(node.prop);
const selectedFrame = this._frameManager.selectedFrame();
const selectedFrame = this.frameManager.selectedFrame();
if (!this._frameManager.activeFrameHasUniqueUrl()) {
if (!this.frameManager.activeFrameHasUniqueUrl()) {
const error = `The currently inspected frame does not have a unique URL on this page. Cannot inspect object.`;
this.snackBar.open(error, 'Dismiss', {duration: 5000, horizontalPosition: 'left'});
this._messageBus.emit('log', [{level: 'warn', message: error}]);
this.messageBus.emit('log', [{level: 'warn', message: error}]);
return;
}
if (this.isNonTopLevelFirefoxFrame()) {
const error = `Inspecting object is not supported in Firefox when the inspected frame is not the top-level frame.`;
this.snackBar.open(error, 'Dismiss', {duration: 5000, horizontalPosition: 'left'});
this._messageBus.emit('log', [{level: 'warn', message: error}]);
this.messageBus.emit('log', [{level: 'warn', message: error}]);
} else {
this._appOperations.inspect(directivePosition, objectPath, selectedFrame!);
this.appOperations.inspect(directivePosition, objectPath, selectedFrame!);
}
}
@@ -112,29 +112,29 @@ const getVisibleNodes = (nodes: FlatNode[], isExpanded: (node: FlatNode) => bool
};
export class ComponentDataSource extends DataSource<FlatNode> {
private _differ = new DefaultIterableDiffer<FlatNode>(trackBy);
private _expandedData = new BehaviorSubject<FlatNode[]>([]);
private _flattenedData = new BehaviorSubject<FlatNode[]>([]);
private _nodeToFlat = new WeakMap<IndexedNode, FlatNode>();
private differ = new DefaultIterableDiffer<FlatNode>(trackBy);
private expandedData = new BehaviorSubject<FlatNode[]>([]);
private flattenedData = new BehaviorSubject<FlatNode[]>([]);
private nodeToFlat = new WeakMap<IndexedNode, FlatNode>();
constructor(private _expansionModel: ExpansionModel<FlatNode>) {
constructor(private expansionModel: ExpansionModel<FlatNode>) {
super();
}
/** Flattens the forest into a list of nodes in depth-first order. */
private _flattenNodes(nodes: IndexedNode[], level = 0, result: FlatNode[] = []): FlatNode[] {
private flattenNodes(nodes: IndexedNode[], level = 0, result: FlatNode[] = []): FlatNode[] {
for (const node of nodes) {
const flatNode = this._toFlatNode(node, level);
const flatNode = this.toFlatNode(node, level);
result.push(flatNode);
if (flatNode.expandable) {
this._flattenNodes(node.children, level + 1, result);
this.flattenNodes(node.children, level + 1, result);
}
}
return result;
}
private _toFlatNode(node: IndexedNode, level: number): FlatNode {
const existingNode = this._nodeToFlat.get(node);
private toFlatNode(node: IndexedNode, level: number): FlatNode {
const existingNode = this.nodeToFlat.get(node);
if (existingNode) {
return existingNode;
}
@@ -153,20 +153,20 @@ export class ComponentDataSource extends DataSource<FlatNode> {
hasNativeElement: node.hasNativeElement,
collapsedByDefault: node.children.every((n) => n.static),
};
this._nodeToFlat.set(node, flatNode);
this.nodeToFlat.set(node, flatNode);
return flatNode;
}
get data(): FlatNode[] {
return this._flattenedData.value;
return this.flattenedData.value;
}
get expandedDataValues(): FlatNode[] {
return this._expandedData.value;
return this.expandedData.value;
}
getFlatNodeFromIndexedNode(indexedNode: IndexedNode): FlatNode | undefined {
return this._nodeToFlat.get(indexedNode);
return this.nodeToFlat.get(indexedNode);
}
getFlatNodeByPosition(position: number[]): FlatNode | undefined {
@@ -203,46 +203,42 @@ export class ComponentDataSource extends DataSource<FlatNode> {
indexedForest = filterCommentNodes(indexedForest);
}
const flattenedCollection = this._flattenNodes(indexedForest);
const flattenedCollection = this.flattenNodes(indexedForest);
this.data.forEach((i) => (i.newItem = false));
const expandedNodes: Record<string, boolean> = {};
this.data.forEach((item) => {
expandedNodes[item.id] = this._expansionModel.isExpanded(item);
expandedNodes[item.id] = this.expansionModel.isExpanded(item);
});
const {newItems, movedItems, removedItems} = diff<FlatNode>(
this._differ,
this.differ,
this.data,
flattenedCollection,
);
this._flattenedData.next(this.data);
this.flattenedData.next(this.data);
movedItems.forEach((i) => {
this._nodeToFlat.set(i.original, i);
this.nodeToFlat.set(i.original, i);
if (expandedNodes[i.id]) {
this._expansionModel.expand(i);
this.expansionModel.expand(i);
}
});
newItems.forEach((i) => (i.newItem = true));
removedItems.forEach((i) => this._nodeToFlat.delete(i.original));
removedItems.forEach((i) => this.nodeToFlat.delete(i.original));
return {newItems, movedItems, removedItems};
}
override connect(collectionViewer: CollectionViewer): Observable<FlatNode[]> {
const changes = [
collectionViewer.viewChange,
this._expansionModel.changed,
this._flattenedData,
];
const changes = [collectionViewer.viewChange, this.expansionModel.changed, this.flattenedData];
return merge<unknown[]>(...changes).pipe(
map(() => {
this._expandedData.next(
getVisibleNodes(this.data, (node) => this._expansionModel.isExpanded(node)),
this.expandedData.next(
getVisibleNodes(this.data, (node) => this.expansionModel.isExpanded(node)),
);
return this._expandedData.value;
return this.expandedData.value;
}),
);
}
@@ -17,24 +17,24 @@ import {Observable} from 'rxjs';
* deprecated `FlatTreeControl`.
*/
export class ExpansionModel<T> {
private readonly _expanded = new SelectionModel<T>(true);
private readonly expanded = new SelectionModel<T>(true);
/** Emits whenever nodes are expanded or collapsed. */
readonly changed: Observable<SelectionChange<T>> = this._expanded.changed;
readonly changed: Observable<SelectionChange<T>> = this.expanded.changed;
expand(node: T): void {
this._expanded.select(node);
this.expanded.select(node);
}
collapse(node: T): void {
this._expanded.deselect(node);
this.expanded.deselect(node);
}
toggle(node: T): void {
this._expanded.toggle(node);
this.expanded.toggle(node);
}
isExpanded(node: T): boolean {
return this._expanded.isSelected(node);
return this.expanded.isSelected(node);
}
}
@@ -36,10 +36,10 @@ export class PropertyViewComponent {
controller.logValue();
}
private _nestedProps = inject(ElementPropertyResolver);
private nestedProps = inject(ElementPropertyResolver);
protected readonly controller = computed(() =>
this._nestedProps.getDirectiveController(this.directive().name),
this.nestedProps.getDirectiveController(this.directive().name),
);
protected readonly directiveInputControls = computed(
@@ -50,108 +50,108 @@ export const constructPathOfKeysToPropertyValue = (
};
export class DirectivePropertyResolver {
private _treeFlattener = getTreeFlattener();
private treeFlattener = getTreeFlattener();
private _treeControl = new FlatTreeControl<FlatNode>(
private treeControl = new FlatTreeControl<FlatNode>(
(node) => node.level,
(node) => node.expandable,
);
private _inputsDataSource: PropertyDataSource;
private _propsDataSource: PropertyDataSource;
private _outputsDataSource: PropertyDataSource;
private _stateDataSource: PropertyDataSource;
private inputsDataSource: PropertyDataSource;
private propsDataSource: PropertyDataSource;
private outputsDataSource: PropertyDataSource;
private stateDataSource: PropertyDataSource;
constructor(
private _messageBus: MessageBus<Events>,
private _props: Properties,
private _directivePosition: DirectivePosition,
private messageBus: MessageBus<Events>,
private props: Properties,
private directivePos: DirectivePosition,
) {
const {inputs, props, outputs, state} = this._classifyProperties();
const {inputs, props: properties, outputs, state} = this.classifyProperties();
this._inputsDataSource = this._createDataSourceFromProps(inputs);
this._propsDataSource = this._createDataSourceFromProps(props);
this._outputsDataSource = this._createDataSourceFromProps(outputs);
this._stateDataSource = this._createDataSourceFromProps(state);
this.inputsDataSource = this.createDataSourceFromProps(inputs);
this.propsDataSource = this.createDataSourceFromProps(properties);
this.outputsDataSource = this.createDataSourceFromProps(outputs);
this.stateDataSource = this.createDataSourceFromProps(state);
}
get directiveInputControls(): DirectiveTreeData {
return getDirectiveControls(this._inputsDataSource);
return getDirectiveControls(this.inputsDataSource);
}
get directivePropControls(): DirectiveTreeData {
return getDirectiveControls(this._propsDataSource);
return getDirectiveControls(this.propsDataSource);
}
get directiveOutputControls(): DirectiveTreeData {
return getDirectiveControls(this._outputsDataSource);
return getDirectiveControls(this.outputsDataSource);
}
get directiveStateControls(): DirectiveTreeData {
return getDirectiveControls(this._stateDataSource);
return getDirectiveControls(this.stateDataSource);
}
get directiveMetadata(): DirectiveMetadata | undefined {
return this._props.metadata;
return this.props.metadata;
}
get directiveProperties(): {[name: string]: Descriptor} {
return this._props.props;
return this.props.props;
}
get directivePosition(): DirectivePosition {
return this._directivePosition;
return this.directivePos;
}
getExpandedProperties(): NestedProp[] {
return [
...getExpandedDirectiveProperties(this._inputsDataSource.data),
...getExpandedDirectiveProperties(this._propsDataSource.data),
...getExpandedDirectiveProperties(this._outputsDataSource.data),
...getExpandedDirectiveProperties(this._stateDataSource.data),
...getExpandedDirectiveProperties(this.inputsDataSource.data),
...getExpandedDirectiveProperties(this.propsDataSource.data),
...getExpandedDirectiveProperties(this.outputsDataSource.data),
...getExpandedDirectiveProperties(this.stateDataSource.data),
];
}
updateProperties(newProps: Properties): void {
this._props = newProps;
const {inputs, props, outputs, state} = this._classifyProperties();
this.props = newProps;
const {inputs, props, outputs, state} = this.classifyProperties();
this._inputsDataSource.update(inputs);
this._propsDataSource.update(props);
this._outputsDataSource.update(outputs);
this._stateDataSource.update(state);
this.inputsDataSource.update(inputs);
this.propsDataSource.update(props);
this.outputsDataSource.update(outputs);
this.stateDataSource.update(state);
}
updateValue(node: FlatNode, newValue: unknown): void {
const directiveId = this._directivePosition;
const directiveId = this.directivePos;
const keyPath = constructPathOfKeysToPropertyValue(node.prop);
this._messageBus.emit('updateState', [{directiveId, keyPath, newValue}]);
this.messageBus.emit('updateState', [{directiveId, keyPath, newValue}]);
node.prop.descriptor.value = newValue;
}
logValue(node?: FlatNode): void {
const directiveId = this._directivePosition;
const directiveId = this.directivePos;
const keyPath = node ? constructPathOfKeysToPropertyValue(node.prop) : null;
this._messageBus.emit('logValue', [{directiveId, keyPath}]);
this.messageBus.emit('logValue', [{directiveId, keyPath}]);
}
private _createDataSourceFromProps(props: {[name: string]: Descriptor}): PropertyDataSource {
private createDataSourceFromProps(props: {[name: string]: Descriptor}): PropertyDataSource {
return new PropertyDataSource(
props,
this._treeFlattener,
this._treeControl,
this._directivePosition,
this._messageBus,
this.treeFlattener,
this.treeControl,
this.directivePos,
this.messageBus,
);
}
private _classifyProperties(): {
private classifyProperties(): {
inputs: {[name: string]: Descriptor};
props: {[name: string]: Descriptor};
outputs: {[name: string]: Descriptor};
state: {[name: string]: Descriptor};
} {
const metadata = this._props.metadata;
const metadata = this.props.metadata;
if (!metadata) {
return {
inputs: {},
@@ -21,19 +21,19 @@ import {DirectivePropertyResolver} from './directive-property-resolver';
@Injectable()
export class ElementPropertyResolver {
private _directivePropertiesController = new Map<string, DirectivePropertyResolver>();
private directivePropertiesController = new Map<string, DirectivePropertyResolver>();
constructor(private _messageBus: MessageBus<Events>) {}
constructor(private messageBus: MessageBus<Events>) {}
clearProperties(): void {
this._directivePropertiesController = new Map();
this.directivePropertiesController = new Map();
}
setProperties(indexedNode: IndexedNode, data: DirectivesProperties): void {
this._flushDeletedProperties(data);
this.flushDeletedProperties(data);
Object.keys(data).forEach((key) => {
const controller = this._directivePropertiesController.get(key);
const controller = this.directivePropertiesController.get(key);
if (controller) {
controller.updateProperties(data[key]);
return;
@@ -45,27 +45,27 @@ export class ElementPropertyResolver {
if (!indexedNode.component || indexedNode.component.name !== key) {
position.directive = indexedNode.directives?.findIndex((d) => d.name === key) ?? -1;
}
this._directivePropertiesController.set(
this.directivePropertiesController.set(
key,
new DirectivePropertyResolver(this._messageBus, data[key], position),
new DirectivePropertyResolver(this.messageBus, data[key], position),
);
});
}
private _flushDeletedProperties(data: DirectivesProperties): void {
const currentProps = [...this._directivePropertiesController.keys()];
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);
this.directivePropertiesController.delete(prop);
}
}
}
getExpandedProperties(): ComponentExplorerViewProperties {
const result: ComponentExplorerViewProperties = {};
for (const [directive] of this._directivePropertiesController) {
const controller = this._directivePropertiesController.get(directive);
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;
@@ -76,6 +76,6 @@ export class ElementPropertyResolver {
}
getDirectiveController(directive: string): DirectivePropertyResolver | undefined {
return this._directivePropertiesController.get(directive);
return this.directivePropertiesController.get(directive);
}
}
@@ -28,73 +28,71 @@ const trackBy: TrackByFunction<FlatNode> = (_: number, item: FlatNode) =>
`#${item.prop.name}#${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);
private dataStream = 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>,
private treeFlattener: MatTreeFlattener<Property, FlatNode>,
private treeCtrl: FlatTreeControl<FlatNode>,
private entityPosition: DirectivePosition,
private messageBus: MessageBus<Events>,
) {
super();
this._data.next(this._treeFlattener.flattenNodes(arrayifyProps(props)));
this.dataStream.next(this.treeFlattener.flattenNodes(arrayifyProps(props)));
}
get data(): FlatNode[] {
return this._data.value;
return this.dataStream.value;
}
get treeControl(): FlatTreeControl<FlatNode> {
return this._treeControl;
return this.treeCtrl;
}
update(props: {[prop: string]: Descriptor}): void {
const newData = this._treeFlattener.flattenNodes(arrayifyProps(props));
diff(this._differ, this.data, newData);
this._data.next(this.data);
const newData = this.treeFlattener.flattenNodes(arrayifyProps(props));
diff(this.differ, this.data, newData);
this.dataStream.next(this.data);
}
override connect(collectionViewer: CollectionViewer): Observable<FlatNode[]> {
const changed = this._treeControl.expansionModel.changed;
const changed = this.treeCtrl.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));
change.added.forEach((node) => this.toggleNode(node, true));
}
if (change.removed) {
change.removed.reverse().forEach((node) => this._toggleNode(node, false));
change.removed.reverse().forEach((node) => this.toggleNode(node, false));
}
});
this._subscriptions.push(s);
this.subscriptions.push(s);
const changes = [
collectionViewer.viewChange,
this._treeControl.expansionModel.changed,
this._data,
this.treeCtrl.expansionModel.changed,
this.dataStream,
];
return merge<unknown[]>(...changes).pipe(
map(() => {
this._expandedData.next(
this._treeFlattener.expandFlattenedNodes(this.data, this._treeControl),
);
return this._expandedData.value;
this.expandedData.next(this.treeFlattener.expandFlattenedNodes(this.data, this.treeCtrl));
return this.expandedData.value;
}),
);
}
override disconnect(): void {
this._subscriptions.forEach((s) => s.unsubscribe());
this._subscriptions = [];
this.subscriptions.forEach((s) => s.unsubscribe());
this.subscriptions = [];
}
private _toggleNode(node: FlatNode, expand: boolean): void {
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
@@ -114,18 +112,18 @@ export class PropertyDataSource extends DataSource<FlatNode> {
}
parentPath = parentPath.reverse();
this._messageBus.emit('getNestedProperties', [this._entityPosition, parentPath]);
this.messageBus.emit('getNestedProperties', [this.entityPosition, parentPath]);
this._messageBus.once(
this.messageBus.once(
'nestedProperties',
(position: DirectivePosition, data: Properties, _path: string[]) => {
node.prop.descriptor.value = data.props;
this._treeControl.expand(node);
this.treeCtrl.expand(node);
const props = arrayifyProps(data.props, node.prop);
const flatNodes = this._treeFlattener.flattenNodes(props);
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);
this.dataStream.next(this.data);
},
);
}
@@ -36,16 +36,16 @@ export class ProfilerComponent {
stream = new Subject<ProfilerFrame[]>();
// We collect this buffer so we can have it available for export.
private _buffer: ProfilerFrame[] = [];
private buffer: ProfilerFrame[] = [];
private _fileApiService = inject(FileApiService);
private _messageBus = inject<MessageBus<Events>>(MessageBus);
private fileApiService = inject(FileApiService);
private messageBus = inject<MessageBus<Events>>(MessageBus);
public dialog = inject(MatDialog);
constructor() {
// `FileApiService` is provided in root and outlives this component, which is destroyed and
// recreated when another frame is inspected.
this._fileApiService.uploadedData.pipe(takeUntilDestroyed()).subscribe((importedFile) => {
this.fileApiService.uploadedData.pipe(takeUntilDestroyed()).subscribe((importedFile) => {
if (importedFile.error) {
console.error('Could not process uploaded file');
console.error(importedFile.error);
@@ -76,29 +76,29 @@ export class ProfilerComponent {
processDataDialog.afterClosed().subscribe((result) => {
if (result) {
this.state.set('visualizing');
this._buffer = importedFile.buffer;
this.buffer = importedFile.buffer;
setTimeout(() => this.stream.next(importedFile.buffer));
}
});
} else {
this.state.set('visualizing');
this._buffer = importedFile.buffer;
this.buffer = importedFile.buffer;
setTimeout(() => this.stream.next(importedFile.buffer));
}
});
const unlistenProfilerResults = this._messageBus.on('profilerResults', (remainingRecords) => {
const unlistenProfilerResults = this.messageBus.on('profilerResults', (remainingRecords) => {
if (remainingRecords.duration > 0 && remainingRecords.source) {
this.stream.next([remainingRecords]);
this._buffer.push(remainingRecords);
this.buffer.push(remainingRecords);
}
});
const unlistenProfilerChunk = this._messageBus.on(
const unlistenProfilerChunk = this.messageBus.on(
'sendProfilerChunk',
(chunkOfRecords: ProfilerFrame) => {
this.stream.next([chunkOfRecords]);
this._buffer.push(chunkOfRecords);
this.buffer.push(chunkOfRecords);
},
);
@@ -110,30 +110,30 @@ export class ProfilerComponent {
startRecording(): void {
this.state.set('recording');
this._messageBus.emit('startProfiling');
this.messageBus.emit('startProfiling');
}
stopRecording(): void {
this.state.set('visualizing');
this._messageBus.emit('stopProfiling');
this.messageBus.emit('stopProfiling');
this.stream.complete();
}
exportProfilerResults(): void {
const fileToExport = {
version: PROFILER_VERSION,
buffer: this._buffer,
buffer: this.buffer,
};
this._fileApiService.saveObjectAsJSON(fileToExport);
this.fileApiService.saveObjectAsJSON(fileToExport);
}
importProfilerResults(event: Event): void {
this._fileApiService.publishFileUpload(event);
this.fileApiService.publishFileUpload(event);
}
discardRecording(): void {
this.stream = new Subject<ProfilerFrame[]>();
this.state.set('idle');
this._buffer = [];
this.buffer = [];
}
}
@@ -24,13 +24,13 @@ import {SelectedDirective, SelectedEntry} from '../recording-visualizer-types';
export class BargraphVisualizerComponent {
readonly nodeSelect = output<SelectedEntry>();
private readonly _formatter = new BarGraphFormatter();
private readonly formatter = new BarGraphFormatter();
frame = input.required<ProfilerFrame>();
/** The `ElementProfile` that corresponds to a bar graph node to highlight. */
highlighted = input<ElementProfile | null>(null);
profileRecords = computed(() => this._formatter.formatFrame(this.frame()));
profileRecords = computed(() => this.formatter.formatFrame(this.frame()));
formatEntryData(bargraphNode: BargraphNode): SelectedDirective[] {
return formatDirectiveProfile(bargraphNode.directives ?? []);
@@ -28,51 +28,51 @@ import {TreeMapFormatter, TreeMapNode} from '../../record-formatter/tree-map-for
styleUrls: ['./tree-map-visualizer.component.scss'],
})
export class TreeMapVisualizerComponent implements OnDestroy {
private _formatter = new TreeMapFormatter();
private formatter = new TreeMapFormatter();
readonly frame = input.required<ProfilerFrame>();
private resize$ = new Subject<void>();
private _throttledResizeSubscription!: Subscription;
private throttledResizeSubscription!: Subscription;
private _resizeObserver: ResizeObserver = new ResizeObserver(() => this.resize$.next());
private resizeObserver: ResizeObserver = new ResizeObserver(() => this.resize$.next());
private readonly treeMapRecords = computed<TreeMapNode>(() => {
// first element in data is the Application node
return this._formatter.formatFrame(this.frame());
return this.formatter.formatFrame(this.frame());
});
readonly tree = viewChild.required<ElementRef<HTMLElement>>('webTree');
constructor() {
effect(() => {
if (this.tree()) this._renderTree();
if (this.tree()) this.renderTree();
});
afterNextRender({
read: () => {
this._throttledResizeSubscription = this.resize$
this.throttledResizeSubscription = this.resize$
.pipe(debounceTime(100))
.subscribe(() => this._renderTree());
this._resizeObserver.observe(this.tree().nativeElement);
.subscribe(() => this.renderTree());
this.resizeObserver.observe(this.tree().nativeElement);
},
});
}
ngOnDestroy(): void {
this._throttledResizeSubscription.unsubscribe();
this._resizeObserver.unobserve(this.tree().nativeElement);
this.throttledResizeSubscription.unsubscribe();
this.resizeObserver.unobserve(this.tree().nativeElement);
}
private _renderTree(): void {
this._removeTree();
this._createTree();
private renderTree(): void {
this.removeTree();
this.createTree();
}
private _removeTree(): void {
private removeTree(): void {
Array.from(this.tree().nativeElement.children).forEach((child) => child.remove());
}
private _createTree(): void {
private createTree(): void {
render(this.tree().nativeElement, this.treeMapRecords(), {
padding: [20, 5, 5, 5],
caption: (node) => `${node.id}: ${node.size.toFixed(1)} ms`,
@@ -72,8 +72,8 @@ export class SignalDetailsComponent {
}>();
protected readonly close = output<void>();
private readonly _messageBus = inject<MessageBus<Events>>(MessageBus);
private readonly _supportedApis = inject(SUPPORTED_APIS);
private readonly messageBus = inject<MessageBus<Events>>(MessageBus);
private readonly supportedApis = inject(SUPPORTED_APIS);
protected readonly TYPE_CLASS_MAP = TYPE_CLASS_MAP;
protected readonly CLUSTER_TYPE_CLASS_MAP = CLUSTER_TYPE_CLASS_MAP;
@@ -83,7 +83,7 @@ export class SignalDetailsComponent {
protected isWatchable(node: DevtoolsSignalGraphNode): node is DevtoolsSignalNode {
return (
this._supportedApis().signalWatch &&
this.supportedApis().signalWatch &&
isSignalNode(node) &&
(node.kind === 'signal' || node.kind === 'computed' || node.kind === 'linkedSignal')
);
@@ -135,7 +135,7 @@ export class SignalDetailsComponent {
protected toggleIsBeingWatched() {
const selectedNode = this.node();
if (!this.isWatchable(selectedNode)) return;
this._messageBus.emit('toggleWatchSignal', [selectedNode.id]);
this.messageBus.emit('toggleWatchSignal', [selectedNode.id]);
}
private getCompoundNodeValueHof(node: DevtoolsClusterNode) {
@@ -48,67 +48,67 @@ const TOPIC_REQUEST: TopicSequence = {
};
export class PriorityAwareMessageBus extends MessageBus<Events> {
private _throttled: ThrottledTopics = {};
private _inProgress: TopicsInProgress = {};
private throttled: ThrottledTopics = {};
private inProgress: TopicsInProgress = {};
constructor(
private _bus: MessageBus<Events>,
private bus: MessageBus<Events>,
// Binding is necessary to ensure that `setTimeout` is called in the global context.
// an doesn't throw "Illegal invocation" error.
private _setTimeout: typeof setTimeout = setTimeout.bind(globalThis),
private setTimeout: typeof globalThis.setTimeout = globalThis.setTimeout.bind(globalThis),
) {
super();
}
override on<E extends Topic>(topic: E, cb: Events[E]): () => void {
return this._bus.on(topic, (...args: any) => {
return this.bus.on(topic, (...args: any) => {
(cb as any)(...args);
this._afterMessage(topic);
this.afterMessage(topic);
});
}
override once<E extends Topic>(topic: E, cb: Events[E]): void {
return this._bus.once(topic, (...args: any) => {
return this.bus.once(topic, (...args: any) => {
(cb as any)(...args);
this._afterMessage(topic);
this.afterMessage(topic);
});
}
override emit<E extends Topic>(topic: E, args?: Parameters<Events[E]>): boolean {
if (this._throttled[topic]) {
if (this.throttled[topic]) {
return false;
}
if (TOPIC_RESPONSE[topic]) {
this._inProgress[topic] = true;
this.inProgress[topic] = true;
}
const blockedBy = TOPIC_BLOCK_SEQUENCE[topic];
if (blockedBy) {
// The source code here is safe.
// TypeScript type inference ignores the null check here.
for (const blocker of blockedBy!) {
if (this._inProgress[blocker]) {
if (this.inProgress[blocker]) {
return false;
}
}
}
if (THROTTLE_METHODS[topic]) {
this._throttled[topic] = true;
this._setTimeout(() => (this._throttled[topic] = false), THROTTLE_METHODS[topic]);
this.throttled[topic] = true;
this.setTimeout(() => (this.throttled[topic] = false), THROTTLE_METHODS[topic]);
}
return this._bus.emit(topic, args);
return this.bus.emit(topic, args);
}
override destroy(): void {
this._bus.destroy();
this.bus.destroy();
}
private _afterMessage(topic: Topic): void {
private afterMessage(topic: Topic): void {
const request = TOPIC_REQUEST[topic];
if (!request) {
return;
}
if (this._inProgress[request]) {
this._inProgress[request] = false;
if (this.inProgress[request]) {
this.inProgress[request] = false;
}
}
}
@@ -18,23 +18,23 @@ import {Events, MessageBus} from '../../../protocol';
imports: [DevToolsComponent],
})
export class AppComponent implements OnInit, OnDestroy {
private _cd = inject(ChangeDetectorRef);
private readonly _messageBus = inject<MessageBus<Events>>(MessageBus);
private readonly _deepLinkInstanceId = inject(DEEP_LINK_INSTANCE_ID);
private cd = inject(ChangeDetectorRef);
private readonly messageBus = inject<MessageBus<Events>>(MessageBus);
private readonly deepLinkInstanceId = inject(DEEP_LINK_INSTANCE_ID);
private onProfilingStartedListener = () => {
this._messageBus.emit('setConfig', [{performanceTrack: true}]);
this.messageBus.emit('setConfig', [{performanceTrack: true}]);
};
private onProfilingStoppedListener = () => {
this._messageBus.emit('setConfig', [{performanceTrack: false}]);
this.messageBus.emit('setConfig', [{performanceTrack: false}]);
};
private readonly _deepLinkListener = (event: MessageEvent) => {
private readonly deepLinkListener = (event: MessageEvent) => {
if (event.origin !== window.location.origin) return;
if (
event.data?.type === 'angular-devtools-deep-link' &&
typeof event.data.instanceId === 'number'
) {
this._deepLinkInstanceId.set(event.data.instanceId);
this.deepLinkInstanceId.set(event.data.instanceId);
}
};
@@ -47,9 +47,9 @@ export class AppComponent implements OnInit, OnDestroy {
chromeDevToolsPerformance?.onProfilingStopped?.addListener?.(this.onProfilingStoppedListener);
// Listen for deep link messages from the devtools page (devtools.ts)
window.addEventListener('message', this._deepLinkListener);
window.addEventListener('message', this.deepLinkListener);
this._cd.detectChanges();
this.cd.detectChanges();
}
ngOnDestroy(): void {
const chromeDevToolsPerformance = chrome.devtools.performance;
@@ -59,6 +59,6 @@ export class AppComponent implements OnInit, OnDestroy {
chromeDevToolsPerformance?.onProfilingStopped?.removeListener?.(
this.onProfilingStoppedListener,
);
window.removeEventListener('message', this._deepLinkListener);
window.removeEventListener('message', this.deepLinkListener);
}
}
@@ -20,15 +20,15 @@ type AnyEventCallback<Ev> = <E extends keyof Ev>(topic: E, args: Parameters<Ev[E
type ListenerFn = (msg: ChromeMessage<Events, keyof Events>) => void;
export class ChromeMessageBus extends MessageBus<Events> {
private _disconnected = false;
private _listeners: ListenerFn[] = [];
private disconnected = false;
private listeners: ListenerFn[] = [];
constructor(private _port: chrome.runtime.Port) {
constructor(private port: chrome.runtime.Port) {
super();
_port.onDisconnect.addListener(() => {
port.onDisconnect.addListener(() => {
// console.log('Disconnected the port');
this._disconnected = true;
this.disconnected = true;
});
}
@@ -36,11 +36,11 @@ export class ChromeMessageBus extends MessageBus<Events> {
const listener = (msg: ChromeMessage<Events, keyof Events>): void => {
cb(msg.topic, msg.args);
};
this._port.onMessage.addListener(listener);
this._listeners.push(listener);
this.port.onMessage.addListener(listener);
this.listeners.push(listener);
return () => {
this._listeners.splice(this._listeners.indexOf(listener), 1);
this._port.onMessage.removeListener(listener);
this.listeners.splice(this.listeners.indexOf(listener), 1);
this.port.onMessage.removeListener(listener);
};
}
@@ -50,11 +50,11 @@ export class ChromeMessageBus extends MessageBus<Events> {
(cb as any).apply(null, msg.args);
}
};
this._port.onMessage.addListener(listener);
this._listeners.push(listener);
this.port.onMessage.addListener(listener);
this.listeners.push(listener);
return () => {
this._listeners.splice(this._listeners.indexOf(listener), 1);
this._port.onMessage.removeListener(listener);
this.listeners.splice(this.listeners.indexOf(listener), 1);
this.port.onMessage.removeListener(listener);
};
}
@@ -62,17 +62,17 @@ export class ChromeMessageBus extends MessageBus<Events> {
const listener = (msg: ChromeMessage<Events, keyof Events>) => {
if (msg.topic === topic) {
(cb as any).apply(null, msg.args);
this._port.onMessage.removeListener(listener);
this.port.onMessage.removeListener(listener);
}
};
this._port.onMessage.addListener(listener);
this.port.onMessage.addListener(listener);
}
override emit<E extends keyof Events>(topic: E, args?: Parameters<Events[E]>): boolean {
if (this._disconnected) {
if (this.disconnected) {
return false;
}
this._port.postMessage({
this.port.postMessage({
topic,
args,
__ignore_ng_zone__: true,
@@ -82,7 +82,7 @@ export class ChromeMessageBus extends MessageBus<Events> {
}
override destroy(): void {
this._listeners.forEach((l) => this._port.onMessage.removeListener(l));
this._listeners = [];
this.listeners.forEach((l) => this.port.onMessage.removeListener(l));
this.listeners = [];
}
}
@@ -24,12 +24,12 @@ export type BusStatus = 'init' | 'waiting' | 'ready';
*/
export class SamePageMessageBus extends MessageBus<Events> {
private status: BusStatus = 'init';
private _listeners: ListenerFn[] = [];
private listeners: ListenerFn[] = [];
constructor(
private debugName: string,
private _source: string,
private _destination: string,
private source: string,
private destination: string,
) {
super();
}
@@ -38,15 +38,15 @@ export class SamePageMessageBus extends MessageBus<Events> {
const listener: ListenerFn = (e) => {
this.updateStatus(e.data?.topic);
if (e.source !== window || !e.data || !e.data.topic || e.data.source !== this._destination) {
if (e.source !== window || !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);
this.listeners.push(listener);
return () => {
this._listeners.splice(this._listeners.indexOf(listener), 1);
this.listeners.splice(this.listeners.indexOf(listener), 1);
window.removeEventListener('message', listener);
};
}
@@ -55,7 +55,7 @@ export class SamePageMessageBus extends MessageBus<Events> {
const listener: ListenerFn = (e) => {
this.updateStatus(e.data?.topic);
if (e.source !== window || !e.data || e.data.source !== this._destination || !e.data.topic) {
if (e.source !== window || !e.data || e.data.source !== this.destination || !e.data.topic) {
return;
}
if (e.data.topic === topic) {
@@ -63,16 +63,16 @@ export class SamePageMessageBus extends MessageBus<Events> {
}
};
window.addEventListener('message', listener);
this._listeners.push(listener);
this.listeners.push(listener);
return () => {
this._listeners.splice(this._listeners.indexOf(listener), 1);
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: ListenerFn = (e) => {
if (e.source !== window || !e.data || e.data.source !== this._destination || !e.data.topic) {
if (e.source !== window || !e.data || e.data.source !== this.destination || !e.data.topic) {
return;
}
if (e.data.topic === topic) {
@@ -90,7 +90,7 @@ export class SamePageMessageBus extends MessageBus<Events> {
window.postMessage(
{
source: this._source,
source: this.source,
topic,
args,
__ignore_ng_zone__: true,
@@ -102,8 +102,8 @@ export class SamePageMessageBus extends MessageBus<Events> {
}
override destroy(): void {
this._listeners.forEach((l) => window.removeEventListener('message', l));
this._listeners = [];
this.listeners.forEach((l) => window.removeEventListener('message', l));
this.listeners = [];
}
private shouldSkipMessage(topic: string): boolean {