[Underscore Migration] Migrate panels/timeline This patch is part of the underscore migration that adds the private keyword to all properties that start with an underscore and removes the underscore. R=tvanderlippe@chromium.org Bug:chromium:1207342 Change-Id: If5bfa1146a3c5874948e5166b1c5fc006a201c20 Reviewed-on: https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3090595 Auto-Submit: Jan Scheffler <janscheffler@chromium.org> Commit-Queue: Tim van der Lippe <tvanderlippe@chromium.org> Reviewed-by: Tim van der Lippe <tvanderlippe@chromium.org>
diff --git a/front_end/legacy_test_runner/performance_test_runner/TimelineTestRunner.js b/front_end/legacy_test_runner/performance_test_runner/TimelineTestRunner.js index 4b083a5..4768841 100644 --- a/front_end/legacy_test_runner/performance_test_runner/TimelineTestRunner.js +++ b/front_end/legacy_test_runner/performance_test_runner/TimelineTestRunner.js
@@ -80,7 +80,7 @@ }; PerformanceTestRunner.tracingModel = function() { - return UI.panels.timeline._performanceModel.tracingModel(); + return UI.panels.timeline.performanceModel.tracingModel(); }; PerformanceTestRunner.invokeWithTracing = function(functionName, callback, additionalCategories, enableJSSampling) { @@ -93,11 +93,11 @@ const timelinePanel = UI.panels.timeline; const timelineController = PerformanceTestRunner.createTimelineController(); - timelinePanel._timelineController = timelineController; - timelineController._startRecordingWithCategories(categories, enableJSSampling).then(tracingStarted); + timelinePanel.timelineController = timelineController; + timelineController.startRecordingWithCategories(categories, enableJSSampling).then(tracingStarted); function tracingStarted() { - timelinePanel._recordingStarted(); + timelinePanel.recordingStarted(); TestRunner.callFunctionInPageAsync(functionName).then(onPageActionsDone); } @@ -108,7 +108,7 @@ }; PerformanceTestRunner.performanceModel = function() { - return UI.panels.timeline._performanceModel; + return UI.panels.timeline.performanceModel; }; PerformanceTestRunner.timelineModel = function() { @@ -125,14 +125,14 @@ tracingModel.tracingComplete(); const performanceModel = new Timeline.PerformanceModel(); performanceModel.setTracingModel(tracingModel); - UI.panels.timeline._performanceModel = performanceModel; - UI.panels.timeline._applyFilters(performanceModel); + UI.panels.timeline.performanceModel = performanceModel; + UI.panels.timeline.applyFilters(performanceModel); return performanceModel; }; PerformanceTestRunner.createTimelineController = function() { const controller = new Timeline.TimelineController(self.SDK.targetManager.mainTarget(), UI.panels.timeline); - controller._tracingManager = TestRunner.tracingManager; + controller.tracingManager = TestRunner.tracingManager; return controller; }; @@ -142,14 +142,14 @@ PerformanceTestRunner.startTimeline = function() { const panel = UI.panels.timeline; - panel._toggleRecording(); + panel.toggleRecording(); return TestRunner.addSnifferPromise(panel, '_recordingStarted'); }; PerformanceTestRunner.stopTimeline = function() { return new Promise(resolve => { PerformanceTestRunner.runWhenTimelineIsReady(resolve); - UI.panels.timeline._toggleRecording(); + UI.panels.timeline.toggleRecording(); }); }; @@ -165,12 +165,12 @@ PerformanceTestRunner.getNetworkFlameChartElement = async function() { const widget = await PerformanceTestRunner.getTimelineWidget(); - return widget._flameChart._networkFlameChart.contentElement; + return widget.flameChart.networkFlameChart.contentElement; }; PerformanceTestRunner.getMainFlameChartElement = async function() { const widget = await PerformanceTestRunner.getTimelineWidget(); - return widget._flameChart._mainFlameChart.contentElement; + return widget.flameChart.mainFlameChart.contentElement; }; PerformanceTestRunner.evaluateWithTimeline = async function(actions) { @@ -212,13 +212,13 @@ }; PerformanceTestRunner.walkTimelineEventTree = async function(callback) { - const view = new Timeline.EventsTimelineTreeView(UI.panels.timeline._filters, null); + const view = new Timeline.EventsTimelineTreeView(UI.panels.timeline.filters, null); view.setModel(PerformanceTestRunner.performanceModel(), PerformanceTestRunner.mainTrack()); const selection = Timeline.TimelineSelection.fromRange( PerformanceTestRunner.timelineModel().minimumRecordTime(), PerformanceTestRunner.timelineModel().maximumRecordTime()); view.updateContents(selection); - await PerformanceTestRunner.walkTimelineEventTreeUnderNode(callback, view._currentTree, 0); + await PerformanceTestRunner.walkTimelineEventTreeUnderNode(callback, view.currentTree, 0); }; PerformanceTestRunner.walkTimelineEventTreeUnderNode = async function(callback, root, level) { @@ -398,7 +398,7 @@ }; PerformanceTestRunner.dumpTimelineFlameChart = function(includeGroups) { - const provider = UI.panels.timeline._flameChart._mainDataProvider; + const provider = UI.panels.timeline.flameChart.mainDataProvider; TestRunner.addResult('Timeline Flame Chart'); PerformanceTestRunner.dumpFlameChartProvider(provider, includeGroups); }; @@ -406,7 +406,7 @@ PerformanceTestRunner.loadTimeline = function(timelineData) { const promise = new Promise(fulfill => PerformanceTestRunner.runWhenTimelineIsReady(fulfill)); - UI.panels.timeline._loadFromFile(new Blob([timelineData], {type: 'text/plain'})); + UI.panels.timeline.loadFromFile(new Blob([timelineData], {type: 'text/plain'})); return promise; };
diff --git a/front_end/panels/elements/StylePropertyTreeElement.ts b/front_end/panels/elements/StylePropertyTreeElement.ts index 8d9c1d9..b140ca8 100644 --- a/front_end/panels/elements/StylePropertyTreeElement.ts +++ b/front_end/panels/elements/StylePropertyTreeElement.ts
@@ -1410,7 +1410,7 @@ this._hasBeenEditedIncrementally = true; // null check for updatedProperty before setting this.property as the code never expects this.property to be undefined or null. - // This occurs when deleting the last index of a StylePropertiesSection as this._style._allProperties array gets updated + // This occurs when deleting the last index of a StylePropertiesSection as this.style._allProperties array gets updated // before we index it when setting the value for updatedProperty const deleteProperty = majorChange && !styleText.length; const section = this.section();
diff --git a/front_end/panels/timeline/CLSLinkifier.ts b/front_end/panels/timeline/CLSLinkifier.ts index b60d87a..3d45479 100644 --- a/front_end/panels/timeline/CLSLinkifier.ts +++ b/front_end/panels/timeline/CLSLinkifier.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import type * as Common from '../../core/common/common.js'; import * as SDK from '../../core/sdk/sdk.js';
diff --git a/front_end/panels/timeline/CountersGraph.ts b/front_end/panels/timeline/CountersGraph.ts index a70209a..b400a6a 100644 --- a/front_end/panels/timeline/CountersGraph.ts +++ b/front_end/panels/timeline/CountersGraph.ts
@@ -28,8 +28,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; @@ -73,91 +71,90 @@ const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class CountersGraph extends UI.Widget.VBox { - _delegate: TimelineModeViewDelegate; - _calculator: Calculator; - _model!: PerformanceModel|null; - _header: UI.Widget.HBox; - _toolbar: UI.Toolbar.Toolbar; - _graphsContainer: UI.Widget.VBox; - _canvasContainer: UI.Widget.WidgetElement; - _canvas: HTMLCanvasElement; - _timelineGrid: PerfUI.TimelineGrid.TimelineGrid; - _counters: Counter[]; - _counterUI: CounterUI[]; - _countersByName: Map<string, Counter>; - _gpuMemoryCounter: Counter; - _track?: TimelineModel.TimelineModel.Track|null; - _currentValuesBar?: HTMLElement; - _markerXPosition?: number; + private readonly delegate: TimelineModeViewDelegate; + private readonly calculator: Calculator; + private model!: PerformanceModel|null; + private readonly header: UI.Widget.HBox; + readonly toolbar: UI.Toolbar.Toolbar; + private graphsContainer: UI.Widget.VBox; + canvasContainer: UI.Widget.WidgetElement; + private canvas: HTMLCanvasElement; + private readonly timelineGrid: PerfUI.TimelineGrid.TimelineGrid; + private readonly counters: Counter[]; + private readonly counterUI: CounterUI[]; + private readonly countersByName: Map<string, Counter>; + private readonly gpuMemoryCounter: Counter; + private track?: TimelineModel.TimelineModel.Track|null; + currentValuesBar?: HTMLElement; + private markerXPosition?: number; constructor(delegate: TimelineModeViewDelegate) { super(); this.element.id = 'memory-graphs-container'; - this._delegate = delegate; - this._calculator = new Calculator(); + this.delegate = delegate; + this.calculator = new Calculator(); // Create selectors - this._header = new UI.Widget.HBox(); - this._header.element.classList.add('timeline-memory-header'); - this._header.show(this.element); - this._toolbar = new UI.Toolbar.Toolbar('timeline-memory-toolbar'); - this._header.element.appendChild(this._toolbar.element); + this.header = new UI.Widget.HBox(); + this.header.element.classList.add('timeline-memory-header'); + this.header.show(this.element); + this.toolbar = new UI.Toolbar.Toolbar('timeline-memory-toolbar'); + this.header.element.appendChild(this.toolbar.element); - this._graphsContainer = new UI.Widget.VBox(); - this._graphsContainer.show(this.element); - const canvasWidget = new UI.Widget.VBoxWithResizeCallback(this._resize.bind(this)); - canvasWidget.show(this._graphsContainer.element); - this._createCurrentValuesBar(); - this._canvasContainer = canvasWidget.element; - this._canvasContainer.id = 'memory-graphs-canvas-container'; - this._canvas = document.createElement('canvas'); - this._canvasContainer.appendChild(this._canvas); - this._canvas.id = 'memory-counters-graph'; + this.graphsContainer = new UI.Widget.VBox(); + this.graphsContainer.show(this.element); + const canvasWidget = new UI.Widget.VBoxWithResizeCallback(this.resize.bind(this)); + canvasWidget.show(this.graphsContainer.element); + this.createCurrentValuesBar(); + this.canvasContainer = canvasWidget.element; + this.canvasContainer.id = 'memory-graphs-canvas-container'; + this.canvas = document.createElement('canvas'); + this.canvasContainer.appendChild(this.canvas); + this.canvas.id = 'memory-counters-graph'; - this._canvasContainer.addEventListener('mouseover', this._onMouseMove.bind(this), true); - this._canvasContainer.addEventListener('mousemove', this._onMouseMove.bind(this), true); - this._canvasContainer.addEventListener('mouseleave', this._onMouseLeave.bind(this), true); - this._canvasContainer.addEventListener('click', this._onClick.bind(this), true); + this.canvasContainer.addEventListener('mouseover', this.onMouseMove.bind(this), true); + this.canvasContainer.addEventListener('mousemove', this.onMouseMove.bind(this), true); + this.canvasContainer.addEventListener('mouseleave', this.onMouseLeave.bind(this), true); + this.canvasContainer.addEventListener('click', this.onClick.bind(this), true); // We create extra timeline grid here to reuse its event dividers. - this._timelineGrid = new PerfUI.TimelineGrid.TimelineGrid(); - this._canvasContainer.appendChild(this._timelineGrid.dividersElement); + this.timelineGrid = new PerfUI.TimelineGrid.TimelineGrid(); + this.canvasContainer.appendChild(this.timelineGrid.dividersElement); - this._counters = []; - this._counterUI = []; + this.counters = []; + this.counterUI = []; - this._countersByName = new Map(); - this._countersByName.set( + this.countersByName = new Map(); + this.countersByName.set( 'jsHeapSizeUsed', - this._createCounter( - i18nString(UIStrings.jsHeap), 'hsl(220, 90%, 43%)', Platform.NumberUtilities.bytesToString)); - this._countersByName.set('documents', this._createCounter(i18nString(UIStrings.documents), 'hsl(0, 90%, 43%)')); - this._countersByName.set('nodes', this._createCounter(i18nString(UIStrings.nodes), 'hsl(120, 90%, 43%)')); - this._countersByName.set( - 'jsEventListeners', this._createCounter(i18nString(UIStrings.listeners), 'hsl(38, 90%, 43%)')); + this.createCounter(i18nString(UIStrings.jsHeap), 'hsl(220, 90%, 43%)', Platform.NumberUtilities.bytesToString)); + this.countersByName.set('documents', this.createCounter(i18nString(UIStrings.documents), 'hsl(0, 90%, 43%)')); + this.countersByName.set('nodes', this.createCounter(i18nString(UIStrings.nodes), 'hsl(120, 90%, 43%)')); + this.countersByName.set( + 'jsEventListeners', this.createCounter(i18nString(UIStrings.listeners), 'hsl(38, 90%, 43%)')); - this._gpuMemoryCounter = this._createCounter( + this.gpuMemoryCounter = this.createCounter( i18nString(UIStrings.gpuMemory), 'hsl(300, 90%, 43%)', Platform.NumberUtilities.bytesToString); - this._countersByName.set('gpuMemoryUsedKB', this._gpuMemoryCounter); + this.countersByName.set('gpuMemoryUsedKB', this.gpuMemoryCounter); } setModel(model: PerformanceModel|null, track: TimelineModel.TimelineModel.Track|null): void { - if (this._model !== model) { - if (this._model) { - this._model.removeEventListener(Events.WindowChanged, this._onWindowChanged, this); + if (this.model !== model) { + if (this.model) { + this.model.removeEventListener(Events.WindowChanged, this.onWindowChanged, this); } - this._model = model; - if (this._model) { - this._model.addEventListener(Events.WindowChanged, this._onWindowChanged, this); + this.model = model; + if (this.model) { + this.model.addEventListener(Events.WindowChanged, this.onWindowChanged, this); } } - this._calculator.setZeroTime(model ? model.timelineModel().minimumRecordTime() : 0); - for (let i = 0; i < this._counters.length; ++i) { - this._counters[i].reset(); - this._counterUI[i].reset(); + this.calculator.setZeroTime(model ? model.timelineModel().minimumRecordTime() : 0); + for (let i = 0; i < this.counters.length; ++i) { + this.counters[i].reset(); + this.counterUI[i].reset(); } this.scheduleRefresh(); - this._track = track; + this.track = track; if (!track) { return; } @@ -173,7 +170,7 @@ return; } for (const name in counters) { - const counter = this._countersByName.get(name); + const counter = this.countersByName.get(name); if (counter) { counter.appendSample(event.startTime, counters[name]); } @@ -181,38 +178,38 @@ const gpuMemoryLimitCounterName = 'gpuMemoryLimitKB'; if (gpuMemoryLimitCounterName in counters) { - this._gpuMemoryCounter.setLimit(counters[gpuMemoryLimitCounterName]); + this.gpuMemoryCounter.setLimit(counters[gpuMemoryLimitCounterName]); } } } - _createCurrentValuesBar(): void { - this._currentValuesBar = this._graphsContainer.element.createChild('div'); - this._currentValuesBar.id = 'counter-values-bar'; + private createCurrentValuesBar(): void { + this.currentValuesBar = this.graphsContainer.element.createChild('div'); + this.currentValuesBar.id = 'counter-values-bar'; } - _createCounter(uiName: string, color: string, formatter?: ((arg0: number) => string)): Counter { + private createCounter(uiName: string, color: string, formatter?: ((arg0: number) => string)): Counter { const counter = new Counter(); - this._counters.push(counter); - this._counterUI.push(new CounterUI(this, uiName, color, counter, formatter)); + this.counters.push(counter); + this.counterUI.push(new CounterUI(this, uiName, color, counter, formatter)); return counter; } resizerElement(): Element|null { - return this._header.element; + return this.header.element; } - _resize(): void { - const parentElement = (this._canvas.parentElement as HTMLElement); - this._canvas.width = parentElement.clientWidth * window.devicePixelRatio; - this._canvas.height = parentElement.clientHeight * window.devicePixelRatio; - this._calculator.setDisplayWidth(this._canvas.width); + private resize(): void { + const parentElement = (this.canvas.parentElement as HTMLElement); + this.canvas.width = parentElement.clientWidth * window.devicePixelRatio; + this.canvas.height = parentElement.clientHeight * window.devicePixelRatio; + this.calculator.setDisplayWidth(this.canvas.width); this.refresh(); } - _onWindowChanged(event: Common.EventTarget.EventTargetEvent): void { + private onWindowChanged(event: Common.EventTarget.EventTargetEvent): void { const window = (event.data.window as Window); - this._calculator.setWindow(window.left, window.right); + this.calculator.setWindow(window.left, window.right); this.scheduleRefresh(); } @@ -221,71 +218,70 @@ } draw(): void { - this._clear(); - for (const counter of this._counters) { - counter._calculateVisibleIndexes(this._calculator); - counter._calculateXValues(this._canvas.width); + this.clear(); + for (const counter of this.counters) { + counter.calculateVisibleIndexes(this.calculator); + counter.calculateXValues(this.canvas.width); } - for (const counterUI of this._counterUI) { - counterUI._drawGraph(this._canvas); + for (const counterUI of this.counterUI) { + counterUI.drawGraph(this.canvas); } } - _onClick(event: Event): void { - const x = (event as MouseEvent).x - this._canvasContainer.totalOffsetLeft(); + private onClick(event: Event): void { + const x = (event as MouseEvent).x - this.canvasContainer.totalOffsetLeft(); let minDistance: number = Infinity; let bestTime; - for (const counterUI of this._counterUI) { + for (const counterUI of this.counterUI) { if (!counterUI.counter.times.length) { continue; } - const index = counterUI._recordIndexAt(x); + const index = counterUI.recordIndexAt(x); const distance = Math.abs(x * window.devicePixelRatio - counterUI.counter.x[index]); if (distance < minDistance) { minDistance = distance; bestTime = counterUI.counter.times[index]; } } - if (bestTime !== undefined && this._track) { - this._delegate.selectEntryAtTime( - this._track.events.length ? this._track.events : this._track.asyncEvents, bestTime); + if (bestTime !== undefined && this.track) { + this.delegate.selectEntryAtTime(this.track.events.length ? this.track.events : this.track.asyncEvents, bestTime); } } - _onMouseLeave(_event: Event): void { - delete this._markerXPosition; - this._clearCurrentValueAndMarker(); + private onMouseLeave(_event: Event): void { + delete this.markerXPosition; + this.clearCurrentValueAndMarker(); } - _clearCurrentValueAndMarker(): void { - for (let i = 0; i < this._counterUI.length; i++) { - this._counterUI[i]._clearCurrentValueAndMarker(); + private clearCurrentValueAndMarker(): void { + for (let i = 0; i < this.counterUI.length; i++) { + this.counterUI[i].clearCurrentValueAndMarker(); } } - _onMouseMove(event: Event): void { - const x = (event as MouseEvent).x - this._canvasContainer.totalOffsetLeft(); - this._markerXPosition = x; - this._refreshCurrentValues(); + private onMouseMove(event: Event): void { + const x = (event as MouseEvent).x - this.canvasContainer.totalOffsetLeft(); + this.markerXPosition = x; + this.refreshCurrentValues(); } - _refreshCurrentValues(): void { - if (this._markerXPosition === undefined) { + private refreshCurrentValues(): void { + if (this.markerXPosition === undefined) { return; } - for (let i = 0; i < this._counterUI.length; ++i) { - this._counterUI[i].updateCurrentValue(this._markerXPosition); + for (let i = 0; i < this.counterUI.length; ++i) { + this.counterUI[i].updateCurrentValue(this.markerXPosition); } } refresh(): void { - this._timelineGrid.updateDividers(this._calculator); + this.timelineGrid.updateDividers(this.calculator); this.draw(); - this._refreshCurrentValues(); + this.refreshCurrentValues(); } - _clear(): void { - const ctx = this._canvas.getContext('2d'); + private clear(): void { + const ctx = this.canvas.getContext('2d'); if (!ctx) { throw new Error('Unable to get canvas context'); } @@ -297,20 +293,20 @@ times: number[]; values: number[]; x: number[]; - _minimumIndex: number; - _maximumIndex: number; - _maxTime: number; - _minTime: number; - _limitValue?: number; + minimumIndex: number; + maximumIndex: number; + private maxTime: number; + private minTime: number; + limitValue?: number; constructor() { this.times = []; this.values = []; this.x = []; - this._minimumIndex = 0; - this._maximumIndex = 0; - this._maxTime = 0; - this._minTime = 0; + this.minimumIndex = 0; + this.maximumIndex = 0; + this.maxTime = 0; + this.minTime = 0; } appendSample(time: number, value: number): void { @@ -327,16 +323,16 @@ } setLimit(value: number): void { - this._limitValue = value; + this.limitValue = value; } - _calculateBounds(): { + calculateBounds(): { min: number, max: number, } { let maxValue; let minValue; - for (let i = this._minimumIndex; i <= this._maximumIndex; i++) { + for (let i = this.minimumIndex; i <= this.maximumIndex; i++) { const value = this.values[i]; if (minValue === undefined || value < minValue) { minValue = value; @@ -347,123 +343,123 @@ } minValue = minValue || 0; maxValue = maxValue || 1; - if (this._limitValue) { - if (maxValue > this._limitValue * 0.5) { - maxValue = Math.max(maxValue, this._limitValue); + if (this.limitValue) { + if (maxValue > this.limitValue * 0.5) { + maxValue = Math.max(maxValue, this.limitValue); } - minValue = Math.min(minValue, this._limitValue); + minValue = Math.min(minValue, this.limitValue); } return {min: minValue, max: maxValue}; } - _calculateVisibleIndexes(calculator: Calculator): void { + calculateVisibleIndexes(calculator: Calculator): void { const start = calculator.minimumBoundary(); const end = calculator.maximumBoundary(); // Maximum index of element whose time <= start. - this._minimumIndex = Platform.NumberUtilities.clamp( + this.minimumIndex = Platform.NumberUtilities.clamp( Platform.ArrayUtilities.upperBound(this.times, start, Platform.ArrayUtilities.DEFAULT_COMPARATOR) - 1, 0, this.times.length - 1); // Minimum index of element whose time >= end. - this._maximumIndex = Platform.NumberUtilities.clamp( + this.maximumIndex = Platform.NumberUtilities.clamp( Platform.ArrayUtilities.lowerBound(this.times, end, Platform.ArrayUtilities.DEFAULT_COMPARATOR), 0, this.times.length - 1); // Current window bounds. - this._minTime = start; - this._maxTime = end; + this.minTime = start; + this.maxTime = end; } - _calculateXValues(width: number): void { + calculateXValues(width: number): void { if (!this.values.length) { return; } - const xFactor = width / (this._maxTime - this._minTime); + const xFactor = width / (this.maxTime - this.minTime); this.x = new Array(this.values.length); - for (let i = this._minimumIndex + 1; i <= this._maximumIndex; i++) { - this.x[i] = xFactor * (this.times[i] - this._minTime); + for (let i = this.minimumIndex + 1; i <= this.maximumIndex; i++) { + this.x[i] = xFactor * (this.times[i] - this.minTime); } } } export class CounterUI { - _countersPane: CountersGraph; + private readonly countersPane: CountersGraph; counter: Counter; - _formatter: (arg0: number) => string; + private readonly formatter: (arg0: number) => string; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _setting: Common.Settings.Setting<any>; - _filter: UI.Toolbar.ToolbarSettingCheckbox; - _range: HTMLElement; - _value: HTMLElement; + private readonly setting: Common.Settings.Setting<any>; + private filter: UI.Toolbar.ToolbarSettingCheckbox; + private range: HTMLElement; + private value: HTMLElement; graphColor: string; limitColor: string|null|undefined; graphYValues: number[]; - _verticalPadding: number; - _currentValueLabel: string; - _marker: HTMLElement; + private readonly verticalPadding: number; + private currentValueLabel: string; + private marker: HTMLElement; constructor( countersPane: CountersGraph, title: string, graphColor: string, counter: Counter, formatter?: (arg0: number) => string) { - this._countersPane = countersPane; + this.countersPane = countersPane; this.counter = counter; - this._formatter = formatter || Platform.NumberUtilities.withThousandsSeparator; + this.formatter = formatter || Platform.NumberUtilities.withThousandsSeparator; - this._setting = Common.Settings.Settings.instance().createSetting('timelineCountersGraph-' + title, true); - this._setting.setTitle(title); - this._filter = new UI.Toolbar.ToolbarSettingCheckbox(this._setting, title); - this._filter.inputElement.classList.add('-theme-preserve-input'); + this.setting = Common.Settings.Settings.instance().createSetting('timelineCountersGraph-' + title, true); + this.setting.setTitle(title); + this.filter = new UI.Toolbar.ToolbarSettingCheckbox(this.setting, title); + this.filter.inputElement.classList.add('-theme-preserve-input'); const parsedColor = Common.Color.Color.parse(graphColor); if (parsedColor) { const colorWithAlpha = parsedColor.setAlpha(0.5).asString(Common.Color.Format.RGBA); - const htmlElement = (this._filter.element as HTMLElement); + const htmlElement = (this.filter.element as HTMLElement); if (colorWithAlpha) { htmlElement.style.backgroundColor = colorWithAlpha; } htmlElement.style.borderColor = 'transparent'; } - this._filter.inputElement.addEventListener('click', this._toggleCounterGraph.bind(this)); - countersPane._toolbar.appendToolbarItem(this._filter); - this._range = this._filter.element.createChild('span', 'range'); + this.filter.inputElement.addEventListener('click', this.toggleCounterGraph.bind(this)); + countersPane.toolbar.appendToolbarItem(this.filter); + this.range = this.filter.element.createChild('span', 'range'); - this._value = (countersPane._currentValuesBar as HTMLElement).createChild('span', 'memory-counter-value'); - this._value.style.color = graphColor; + this.value = (countersPane.currentValuesBar as HTMLElement).createChild('span', 'memory-counter-value'); + this.value.style.color = graphColor; this.graphColor = graphColor; if (parsedColor) { this.limitColor = parsedColor.setAlpha(0.3).asString(Common.Color.Format.RGBA); } this.graphYValues = []; - this._verticalPadding = 10; + this.verticalPadding = 10; - this._currentValueLabel = title; - this._marker = countersPane._canvasContainer.createChild('div', 'memory-counter-marker'); - this._marker.style.backgroundColor = graphColor; - this._clearCurrentValueAndMarker(); + this.currentValueLabel = title; + this.marker = countersPane.canvasContainer.createChild('div', 'memory-counter-marker'); + this.marker.style.backgroundColor = graphColor; + this.clearCurrentValueAndMarker(); } reset(): void { - this._range.textContent = ''; + this.range.textContent = ''; } setRange(minValue: number, maxValue: number): void { - const min = this._formatter(minValue); - const max = this._formatter(maxValue); - this._range.textContent = i18nString(UIStrings.ss, {PH1: min, PH2: max}); + const min = this.formatter(minValue); + const max = this.formatter(maxValue); + this.range.textContent = i18nString(UIStrings.ss, {PH1: min, PH2: max}); } - _toggleCounterGraph(): void { - this._value.classList.toggle('hidden', !this._filter.checked()); - this._countersPane.refresh(); + private toggleCounterGraph(): void { + this.value.classList.toggle('hidden', !this.filter.checked()); + this.countersPane.refresh(); } - _recordIndexAt(x: number): number { + recordIndexAt(x: number): number { return Platform.ArrayUtilities.upperBound( this.counter.x, x * window.devicePixelRatio, Platform.ArrayUtilities.DEFAULT_COMPARATOR, - this.counter._minimumIndex + 1, this.counter._maximumIndex + 1) - + this.counter.minimumIndex + 1, this.counter.maximumIndex + 1) - 1; } @@ -471,32 +467,32 @@ if (!this.visible() || !this.counter.values.length || !this.counter.x) { return; } - const index = this._recordIndexAt(x); + const index = this.recordIndexAt(x); const value = Platform.NumberUtilities.withThousandsSeparator(this.counter.values[index]); - this._value.textContent = `${this._currentValueLabel}: ${value}`; + this.value.textContent = `${this.currentValueLabel}: ${value}`; const y = this.graphYValues[index] / window.devicePixelRatio; - this._marker.style.left = x + 'px'; - this._marker.style.top = y + 'px'; - this._marker.classList.remove('hidden'); + this.marker.style.left = x + 'px'; + this.marker.style.top = y + 'px'; + this.marker.classList.remove('hidden'); } - _clearCurrentValueAndMarker(): void { - this._value.textContent = ''; - this._marker.classList.add('hidden'); + clearCurrentValueAndMarker(): void { + this.value.textContent = ''; + this.marker.classList.add('hidden'); } - _drawGraph(canvas: HTMLCanvasElement): void { + drawGraph(canvas: HTMLCanvasElement): void { const ctx = canvas.getContext('2d'); if (!ctx) { throw new Error('Unable to get canvas context'); } const width = canvas.width; - const height = canvas.height - 2 * this._verticalPadding; + const height = canvas.height - 2 * this.verticalPadding; if (height <= 0) { this.graphYValues = []; return; } - const originY = this._verticalPadding; + const originY = this.verticalPadding; const counter = this.counter; const values = counter.values; @@ -504,7 +500,7 @@ return; } - const bounds = counter._calculateBounds(); + const bounds = counter.calculateBounds(); const minValue = bounds.min; const maxValue = bounds.max; this.setRange(minValue, maxValue); @@ -523,11 +519,11 @@ ctx.translate(0.5, 0.5); } ctx.beginPath(); - let value: number = values[counter._minimumIndex]; + let value: number = values[counter.minimumIndex]; let currentY = Math.round(originY + height - (value - minValue) * yFactor); ctx.moveTo(0, currentY); - let i = counter._minimumIndex; - for (; i <= counter._maximumIndex; i++) { + let i = counter.minimumIndex; + for (; i <= counter.maximumIndex; i++) { const x = Math.round(counter.x[i]); ctx.lineTo(x, currentY); const currentValue = values[i]; @@ -542,8 +538,8 @@ ctx.lineTo(width, currentY); ctx.strokeStyle = this.graphColor; ctx.stroke(); - if (counter._limitValue) { - const limitLineY = Math.round(originY + height - (counter._limitValue - minValue) * yFactor); + if (counter.limitValue) { + const limitLineY = Math.round(originY + height - (counter.limitValue - minValue) * yFactor); ctx.moveTo(0, limitLineY); ctx.lineTo(width, limitLineY); if (this.limitColor) { @@ -556,37 +552,37 @@ } visible(): boolean { - return this._filter.checked(); + return this.filter.checked(); } } export class Calculator implements PerfUI.TimelineGrid.Calculator { - _minimumBoundary: number; - _maximumBoundary: number; - _workingArea: number; - _zeroTime: number; + private minimumBoundaryInternal: number; + private maximumBoundaryInternal: number; + private workingArea: number; + private zeroTimeInternal: number; constructor() { - this._minimumBoundary = 0; - this._maximumBoundary = 0; - this._workingArea = 0; - this._zeroTime = 0; + this.minimumBoundaryInternal = 0; + this.maximumBoundaryInternal = 0; + this.workingArea = 0; + this.zeroTimeInternal = 0; } setZeroTime(time: number): void { - this._zeroTime = time; + this.zeroTimeInternal = time; } computePosition(time: number): number { - return (time - this._minimumBoundary) / this.boundarySpan() * this._workingArea; + return (time - this.minimumBoundaryInternal) / this.boundarySpan() * this.workingArea; } setWindow(minimumBoundary: number, maximumBoundary: number): void { - this._minimumBoundary = minimumBoundary; - this._maximumBoundary = maximumBoundary; + this.minimumBoundaryInternal = minimumBoundary; + this.maximumBoundaryInternal = maximumBoundary; } setDisplayWidth(clientWidth: number): void { - this._workingArea = clientWidth; + this.workingArea = clientWidth; } formatValue(value: number, precision?: number): string { @@ -594,18 +590,18 @@ } maximumBoundary(): number { - return this._maximumBoundary; + return this.maximumBoundaryInternal; } minimumBoundary(): number { - return this._minimumBoundary; + return this.minimumBoundaryInternal; } zeroTime(): number { - return this._zeroTime; + return this.zeroTimeInternal; } boundarySpan(): number { - return this._maximumBoundary - this._minimumBoundary; + return this.maximumBoundaryInternal - this.minimumBoundaryInternal; } }
diff --git a/front_end/panels/timeline/EventsTimelineTreeView.ts b/front_end/panels/timeline/EventsTimelineTreeView.ts index 9227b14..d13f9c7 100644 --- a/front_end/panels/timeline/EventsTimelineTreeView.ts +++ b/front_end/panels/timeline/EventsTimelineTreeView.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import type * as SDK from '../../core/sdk/sdk.js'; @@ -43,28 +41,28 @@ const str_ = i18n.i18n.registerUIStrings('panels/timeline/EventsTimelineTreeView.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class EventsTimelineTreeView extends TimelineTreeView { - _filtersControl: Filters; - _delegate: TimelineModeViewDelegate; - _currentTree!: TimelineModel.TimelineProfileTree.Node; + private readonly filtersControl: Filters; + private readonly delegate: TimelineModeViewDelegate; + private currentTree!: TimelineModel.TimelineProfileTree.Node; constructor(delegate: TimelineModeViewDelegate) { super(); - this._filtersControl = new Filters(); - this._filtersControl.addEventListener(Filters.Events.FilterChanged, this._onFilterChanged, this); + this.filtersControl = new Filters(); + this.filtersControl.addEventListener(Filters.Events.FilterChanged, this.onFilterChanged, this); this.init(); - this._delegate = delegate; + this.delegate = delegate; this.dataGrid.markColumnAsSortedBy('startTime', DataGrid.DataGrid.Order.Ascending); this.splitWidget.showBoth(); } filters(): TimelineModel.TimelineModelFilter.TimelineModelFilter[] { - return [...super.filters(), ...this._filtersControl.filters()]; + return [...super.filters(), ...this.filtersControl.filters()]; } updateContents(selection: TimelineSelection): void { super.updateContents(selection); if (selection.type() === TimelineSelection.Type.TraceEvent) { const event = (selection.object() as SDK.TracingModel.Event); - this._selectEvent(event, true); + this.selectEvent(event, true); } } @@ -72,22 +70,22 @@ return i18nString(UIStrings.filterEventLog); } - _buildTree(): TimelineModel.TimelineProfileTree.Node { - this._currentTree = this.buildTopDownTree(true, null); - return this._currentTree; + buildTree(): TimelineModel.TimelineProfileTree.Node { + this.currentTree = this.buildTopDownTree(true, null); + return this.currentTree; } - _onFilterChanged(): void { + private onFilterChanged(): void { const lastSelectedNode = this.lastSelectedNode(); const selectedEvent = lastSelectedNode && lastSelectedNode.event; this.refreshTree(); if (selectedEvent) { - this._selectEvent(selectedEvent, false); + this.selectEvent(selectedEvent, false); } } - _findNodeWithEvent(event: SDK.TracingModel.Event): TimelineModel.TimelineProfileTree.Node|null { - const iterators = [this._currentTree.children().values()]; + private findNodeWithEvent(event: SDK.TracingModel.Event): TimelineModel.TimelineProfileTree.Node|null { + const iterators = [this.currentTree.children().values()]; while (iterators.length) { // @ts-ignore crbug.com/1011811 there is no common iterator type between Closure and TypeScript @@ -105,8 +103,8 @@ return null; } - _selectEvent(event: SDK.TracingModel.Event, expand?: boolean): void { - const node = this._findNodeWithEvent(event); + private selectEvent(event: SDK.TracingModel.Event, expand?: boolean): void { + const node = this.findNodeWithEvent(event); if (!node) { return; } @@ -135,10 +133,10 @@ populateToolbar(toolbar: UI.Toolbar.Toolbar): void { super.populateToolbar(toolbar); - this._filtersControl.populateToolbar(toolbar); + this.filtersControl.populateToolbar(toolbar); } - _showDetailsForNode(node: TimelineModel.TimelineProfileTree.Node): boolean { + showDetailsForNode(node: TimelineModel.TimelineProfileTree.Node): boolean { const traceEvent = node.event; if (!traceEvent) { return false; @@ -152,30 +150,30 @@ return true; } - _onHover(node: TimelineModel.TimelineProfileTree.Node|null): void { - this._delegate.highlightEvent(node && node.event); + onHover(node: TimelineModel.TimelineProfileTree.Node|null): void { + this.delegate.highlightEvent(node && node.event); } } export class Filters extends Common.ObjectWrapper.ObjectWrapper { - _categoryFilter: Category; - _durationFilter: IsLong; - _filters: (IsLong|Category)[]; + private readonly categoryFilter: Category; + private readonly durationFilter: IsLong; + private readonly filtersInternal: (IsLong|Category)[]; constructor() { super(); - this._categoryFilter = new Category(); - this._durationFilter = new IsLong(); - this._filters = [this._categoryFilter, this._durationFilter]; + this.categoryFilter = new Category(); + this.durationFilter = new IsLong(); + this.filtersInternal = [this.categoryFilter, this.durationFilter]; } filters(): TimelineModel.TimelineModelFilter.TimelineModelFilter[] { - return this._filters; + return this.filtersInternal; } populateToolbar(toolbar: UI.Toolbar.Toolbar): void { const durationFilterUI = new UI.Toolbar.ToolbarComboBox(durationFilterChanged.bind(this), i18nString(UIStrings.durationFilter)); - for (const durationMs of Filters._durationFilterPresetsMs) { + for (const durationMs of Filters.durationFilterPresetsMs) { durationFilterUI.addOption(durationFilterUI.createOption( durationMs ? `≥ ${i18nString(UIStrings.Dms, {PH1: durationMs})}` : i18nString(UIStrings.all), String(durationMs))); @@ -200,25 +198,25 @@ function durationFilterChanged(this: Filters): void { const duration = (durationFilterUI.selectedOption() as HTMLOptionElement).value; const minimumRecordDuration = parseInt(duration, 10); - this._durationFilter.setMinimumRecordDuration(minimumRecordDuration); - this._notifyFiltersChanged(); + this.durationFilter.setMinimumRecordDuration(minimumRecordDuration); + this.notifyFiltersChanged(); } function categoriesFilterChanged(this: Filters, name: string): void { const categories = TimelineUIUtils.categories(); const checkBox = categoryFiltersUI.get(name); categories[name].hidden = !checkBox || !checkBox.checked(); - this._notifyFiltersChanged(); + this.notifyFiltersChanged(); } } - _notifyFiltersChanged(): void { + private notifyFiltersChanged(): void { this.dispatchEventToListeners(Filters.Events.FilterChanged); } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/naming-convention - static readonly _durationFilterPresetsMs = [0, 1, 15]; + private static readonly durationFilterPresetsMs = [0, 1, 15]; } export namespace Filters {
diff --git a/front_end/panels/timeline/ExtensionTracingSession.ts b/front_end/panels/timeline/ExtensionTracingSession.ts index 6f20a38..fbd473f 100644 --- a/front_end/panels/timeline/ExtensionTracingSession.ts +++ b/front_end/panels/timeline/ExtensionTracingSession.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import type * as SDK from '../../core/sdk/sdk.js'; import type * as Extensions from '../../models/extensions/extensions.js'; @@ -12,19 +10,19 @@ import {TimelineLoader} from './TimelineLoader.js'; export class ExtensionTracingSession implements Extensions.ExtensionTraceProvider.TracingSession, Client { - _provider: Extensions.ExtensionTraceProvider.ExtensionTraceProvider; - _performanceModel: PerformanceModel; - _completionCallback!: () => void; - _completionPromise: Promise<void>; - _timeOffset: number; + private readonly provider: Extensions.ExtensionTraceProvider.ExtensionTraceProvider; + private readonly performanceModel: PerformanceModel; + private completionCallback!: () => void; + private readonly completionPromise: Promise<void>; + private timeOffset: number; constructor(provider: Extensions.ExtensionTraceProvider.ExtensionTraceProvider, performanceModel: PerformanceModel) { - this._provider = provider; - this._performanceModel = performanceModel; - this._completionPromise = new Promise(fulfill => { - this._completionCallback = fulfill; + this.provider = provider; + this.performanceModel = performanceModel; + this.completionPromise = new Promise(fulfill => { + this.completionCallback = fulfill; }); - this._timeOffset = 0; + this.timeOffset = 0; } loadingStarted(): void { @@ -40,25 +38,25 @@ if (!tracingModel) { return; } - this._performanceModel.addExtensionEvents(this._provider.longDisplayName(), tracingModel, this._timeOffset); - this._completionCallback(); + this.performanceModel.addExtensionEvents(this.provider.longDisplayName(), tracingModel, this.timeOffset); + this.completionCallback(); } complete(url: string, timeOffsetMicroseconds: number): void { if (!url) { - this._completionCallback(); + this.completionCallback(); return; } - this._timeOffset = timeOffsetMicroseconds; + this.timeOffset = timeOffsetMicroseconds; TimelineLoader.loadFromURL(url, this); } start(): void { - this._provider.start(this); + this.provider.start(this); } stop(): Promise<void> { - this._provider.stop(); - return this._completionPromise; + this.provider.stop(); + return this.completionPromise; } }
diff --git a/front_end/panels/timeline/PerformanceModel.ts b/front_end/panels/timeline/PerformanceModel.ts index 4b07399..ea5be41 100644 --- a/front_end/panels/timeline/PerformanceModel.ts +++ b/front_end/panels/timeline/PerformanceModel.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as SDK from '../../core/sdk/sdk.js'; import type * as Bindings from '../../models/bindings/bindings.js'; @@ -12,74 +10,74 @@ import {TimelineUIUtils} from './TimelineUIUtils.js'; export class PerformanceModel extends Common.ObjectWrapper.ObjectWrapper { - _mainTarget: SDK.Target.Target|null; - _tracingModel: SDK.TracingModel.TracingModel|null; - _filters: TimelineModel.TimelineModelFilter.TimelineModelFilter[]; - _timelineModel: TimelineModel.TimelineModel.TimelineModelImpl; - _frameModel: TimelineModel.TimelineFrameModel.TimelineFrameModel; - _filmStripModel: SDK.FilmStripModel.FilmStripModel|null; - _irModel: TimelineModel.TimelineIRModel.TimelineIRModel; - _window: Window; - _extensionTracingModels: { + private mainTargetInternal: SDK.Target.Target|null; + private tracingModelInternal: SDK.TracingModel.TracingModel|null; + private filtersInternal: TimelineModel.TimelineModelFilter.TimelineModelFilter[]; + private readonly timelineModelInternal: TimelineModel.TimelineModel.TimelineModelImpl; + private readonly frameModelInternal: TimelineModel.TimelineFrameModel.TimelineFrameModel; + private filmStripModelInternal: SDK.FilmStripModel.FilmStripModel|null; + private readonly irModel: TimelineModel.TimelineIRModel.TimelineIRModel; + private windowInternal: Window; + private readonly extensionTracingModels: { title: string, model: SDK.TracingModel.TracingModel, timeOffset: number, }[]; - _recordStartTime?: number; + private recordStartTimeInternal?: number; constructor() { super(); - this._mainTarget = null; - this._tracingModel = null; - this._filters = []; + this.mainTargetInternal = null; + this.tracingModelInternal = null; + this.filtersInternal = []; - this._timelineModel = new TimelineModel.TimelineModel.TimelineModelImpl(); - this._frameModel = new TimelineModel.TimelineFrameModel.TimelineFrameModel( + this.timelineModelInternal = new TimelineModel.TimelineModel.TimelineModelImpl(); + this.frameModelInternal = new TimelineModel.TimelineFrameModel.TimelineFrameModel( event => TimelineUIUtils.eventStyle(event).category.name); - this._filmStripModel = null; - this._irModel = new TimelineModel.TimelineIRModel.TimelineIRModel(); + this.filmStripModelInternal = null; + this.irModel = new TimelineModel.TimelineIRModel.TimelineIRModel(); - this._window = {left: 0, right: Infinity}; + this.windowInternal = {left: 0, right: Infinity}; - this._extensionTracingModels = []; - this._recordStartTime = undefined; + this.extensionTracingModels = []; + this.recordStartTimeInternal = undefined; } setMainTarget(target: SDK.Target.Target): void { - this._mainTarget = target; + this.mainTargetInternal = target; } mainTarget(): SDK.Target.Target|null { - return this._mainTarget; + return this.mainTargetInternal; } setRecordStartTime(time: number): void { - this._recordStartTime = time; + this.recordStartTimeInternal = time; } recordStartTime(): number|undefined { - return this._recordStartTime; + return this.recordStartTimeInternal; } setFilters(filters: TimelineModel.TimelineModelFilter.TimelineModelFilter[]): void { - this._filters = filters; + this.filtersInternal = filters; } filters(): TimelineModel.TimelineModelFilter.TimelineModelFilter[] { - return this._filters; + return this.filtersInternal; } isVisible(event: SDK.TracingModel.Event): boolean { - return this._filters.every(f => f.accept(event)); + return this.filtersInternal.every(f => f.accept(event)); } setTracingModel(model: SDK.TracingModel.TracingModel): void { - this._tracingModel = model; - this._timelineModel.setEvents(model); + this.tracingModelInternal = model; + this.timelineModelInternal.setEvents(model); let inputEvents: SDK.TracingModel.AsyncEvent[]|null = null; let animationEvents: SDK.TracingModel.AsyncEvent[]|null = null; - for (const track of this._timelineModel.tracks()) { + for (const track of this.timelineModelInternal.tracks()) { if (track.type === TimelineModel.TimelineModel.TrackType.Input) { inputEvents = track.asyncEvents; } @@ -88,80 +86,83 @@ } } if (inputEvents || animationEvents) { - this._irModel.populate(inputEvents || [], animationEvents || []); + this.irModel.populate(inputEvents || [], animationEvents || []); } - const mainTracks = this._timelineModel.tracks().filter( + const mainTracks = this.timelineModelInternal.tracks().filter( track => track.type === TimelineModel.TimelineModel.TrackType.MainThread && track.forMainFrame && track.events.length); const threadData = mainTracks.map(track => { const event = track.events[0]; return {thread: event.thread, time: event.startTime}; }); - this._frameModel.addTraceEvents(this._mainTarget, this._timelineModel.inspectedTargetEvents(), threadData); + this.frameModelInternal.addTraceEvents( + this.mainTargetInternal, this.timelineModelInternal.inspectedTargetEvents(), threadData); - for (const entry of this._extensionTracingModels) { + for (const entry of this.extensionTracingModels) { entry.model.adjustTime( - this._tracingModel.minimumRecordTime() + (entry.timeOffset / 1000) - (this._recordStartTime as number)); + this.tracingModelInternal.minimumRecordTime() + (entry.timeOffset / 1000) - + (this.recordStartTimeInternal as number)); } - this._autoWindowTimes(); + this.autoWindowTimes(); } addExtensionEvents(title: string, model: SDK.TracingModel.TracingModel, timeOffset: number): void { - this._extensionTracingModels.push({model: model, title: title, timeOffset: timeOffset}); - if (!this._tracingModel) { + this.extensionTracingModels.push({model: model, title: title, timeOffset: timeOffset}); + if (!this.tracingModelInternal) { return; } - model.adjustTime(this._tracingModel.minimumRecordTime() + (timeOffset / 1000) - (this._recordStartTime as number)); + model.adjustTime( + this.tracingModelInternal.minimumRecordTime() + (timeOffset / 1000) - (this.recordStartTimeInternal as number)); this.dispatchEventToListeners(Events.ExtensionDataAdded); } tracingModel(): SDK.TracingModel.TracingModel { - if (!this._tracingModel) { + if (!this.tracingModelInternal) { throw 'call setTracingModel before accessing PerformanceModel'; } - return this._tracingModel; + return this.tracingModelInternal; } timelineModel(): TimelineModel.TimelineModel.TimelineModelImpl { - return this._timelineModel; + return this.timelineModelInternal; } filmStripModel(): SDK.FilmStripModel.FilmStripModel { - if (this._filmStripModel) { - return this._filmStripModel; + if (this.filmStripModelInternal) { + return this.filmStripModelInternal; } - if (!this._tracingModel) { + if (!this.tracingModelInternal) { throw 'call setTracingModel before accessing PerformanceModel'; } - this._filmStripModel = new SDK.FilmStripModel.FilmStripModel(this._tracingModel); - return this._filmStripModel; + this.filmStripModelInternal = new SDK.FilmStripModel.FilmStripModel(this.tracingModelInternal); + return this.filmStripModelInternal; } frames(): TimelineModel.TimelineFrameModel.TimelineFrame[] { - return this._frameModel.getFrames(); + return this.frameModelInternal.getFrames(); } frameModel(): TimelineModel.TimelineFrameModel.TimelineFrameModel { - return this._frameModel; + return this.frameModelInternal; } interactionRecords(): Common.SegmentedRange.Segment<TimelineModel.TimelineIRModel.Phases>[] { - return this._irModel.interactionRecords(); + return this.irModel.interactionRecords(); } extensionInfo(): { title: string, model: SDK.TracingModel.TracingModel, }[] { - return this._extensionTracingModels; + return this.extensionTracingModels; } dispose(): void { - if (this._tracingModel) { - this._tracingModel.dispose(); + if (this.tracingModelInternal) { + this.tracingModelInternal.dispose(); } - for (const extensionEntry of this._extensionTracingModels) { + for (const extensionEntry of this.extensionTracingModels) { extensionEntry.model.dispose(); } } @@ -169,30 +170,30 @@ filmStripModelFrame(frame: TimelineModel.TimelineFrameModel.TimelineFrame): SDK.FilmStripModel.Frame|null { // For idle frames, look at the state at the beginning of the frame. const screenshotTime = frame.idle ? frame.startTime : frame.endTime; - const filmStripModel = (this._filmStripModel as SDK.FilmStripModel.FilmStripModel); + const filmStripModel = (this.filmStripModelInternal as SDK.FilmStripModel.FilmStripModel); const filmStripFrame = filmStripModel.frameByTimestamp(screenshotTime); return filmStripFrame && filmStripFrame.timestamp - frame.endTime < 10 ? filmStripFrame : null; } save(stream: Common.StringOutputStream.OutputStream): Promise<DOMError|null> { - if (!this._tracingModel) { + if (!this.tracingModelInternal) { throw 'call setTracingModel before accessing PerformanceModel'; } - const backingStorage = (this._tracingModel.backingStorage() as Bindings.TempFile.TempFileBackingStorage); + const backingStorage = (this.tracingModelInternal.backingStorage() as Bindings.TempFile.TempFileBackingStorage); return backingStorage.writeToStream(stream); } setWindow(window: Window, animate?: boolean): void { - this._window = window; + this.windowInternal = window; this.dispatchEventToListeners(Events.WindowChanged, {window, animate}); } window(): Window { - return this._window; + return this.windowInternal; } - _autoWindowTimes(): void { - const timelineModel = this._timelineModel; + private autoWindowTimes(): void { + const timelineModel = this.timelineModelInternal; let tasks: SDK.TracingModel.Event[] = []; for (const track of timelineModel.tracks()) { // Deliberately pick up last main frame's track.
diff --git a/front_end/panels/timeline/TimelineController.ts b/front_end/panels/timeline/TimelineController.ts index 180e129..cbacdbd 100644 --- a/front_end/panels/timeline/TimelineController.ts +++ b/front_end/panels/timeline/TimelineController.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; @@ -37,32 +35,32 @@ const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class TimelineController implements SDK.TargetManager.SDKModelObserver<SDK.CPUProfilerModel.CPUProfilerModel>, SDK.TracingManager.TracingManagerClient { - _target: SDK.Target.Target; - _tracingManager: SDK.TracingManager.TracingManager|null; - _performanceModel: PerformanceModel; - _client: Client; - _tracingModel: SDK.TracingModel.TracingModel; - _extensionSessions: ExtensionTracingSession[]; - _extensionTraceProviders?: Extensions.ExtensionTraceProvider.ExtensionTraceProvider[]; + private readonly target: SDK.Target.Target; + private tracingManager: SDK.TracingManager.TracingManager|null; + private performanceModel: PerformanceModel; + private readonly client: Client; + private readonly tracingModel: SDK.TracingModel.TracingModel; + private extensionSessions: ExtensionTracingSession[]; + private extensionTraceProviders?: Extensions.ExtensionTraceProvider.ExtensionTraceProvider[]; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _tracingCompleteCallback?: ((value: any) => void)|null; - _profiling?: boolean; + private tracingCompleteCallback?: ((value: any) => void)|null; + private profiling?: boolean; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _cpuProfiles?: Map<any, any>|null; + private cpuProfiles?: Map<any, any>|null; constructor(target: SDK.Target.Target, client: Client) { - this._target = target; - this._tracingManager = target.model(SDK.TracingManager.TracingManager); - this._performanceModel = new PerformanceModel(); - this._performanceModel.setMainTarget(target); - this._client = client; + this.target = target; + this.tracingManager = target.model(SDK.TracingManager.TracingManager); + this.performanceModel = new PerformanceModel(); + this.performanceModel.setMainTarget(target); + this.client = client; const backingStorage = new Bindings.TempFile.TempFileBackingStorage(); - this._tracingModel = new SDK.TracingModel.TracingModel(backingStorage); + this.tracingModel = new SDK.TracingModel.TracingModel(backingStorage); - this._extensionSessions = []; + this.extensionSessions = []; SDK.TargetManager.TargetManager.instance().observeModels(SDK.CPUProfilerModel.CPUProfilerModel, this); } @@ -71,13 +69,13 @@ } mainTarget(): SDK.Target.Target { - return this._target; + return this.target; } async startRecording( options: RecordingOptions, providers: Extensions.ExtensionTraceProvider.ExtensionTraceProvider[]): Promise<Protocol.ProtocolResponseWithError> { - this._extensionTraceProviders = Extensions.ExtensionServer.ExtensionServer.instance().traceProviders().slice(); + this.extensionTraceProviders = Extensions.ExtensionServer.ExtensionServer.instance().traceProviders().slice(); function disabledByDefault(category: string): string { return 'disabled-by-default-' + category; @@ -114,38 +112,38 @@ categoriesArray.push(disabledByDefault('devtools.screenshot')); } - this._extensionSessions = providers.map(provider => new ExtensionTracingSession(provider, this._performanceModel)); - this._extensionSessions.forEach(session => session.start()); - this._performanceModel.setRecordStartTime(Date.now()); - const response = await this._startRecordingWithCategories(categoriesArray.join(','), options.enableJSSampling); + this.extensionSessions = providers.map(provider => new ExtensionTracingSession(provider, this.performanceModel)); + this.extensionSessions.forEach(session => session.start()); + this.performanceModel.setRecordStartTime(Date.now()); + const response = await this.startRecordingWithCategories(categoriesArray.join(','), options.enableJSSampling); if (response.getError()) { - await this._waitForTracingToStop(false); + await this.waitForTracingToStop(false); await SDK.TargetManager.TargetManager.instance().resumeAllTargets(); } return response; } async stopRecording(): Promise<PerformanceModel> { - if (this._tracingManager) { - this._tracingManager.stop(); + if (this.tracingManager) { + this.tracingManager.stop(); } - this._client.loadingStarted(); - await this._waitForTracingToStop(true); - this._allSourcesFinished(); - return this._performanceModel; + this.client.loadingStarted(); + await this.waitForTracingToStop(true); + this.allSourcesFinished(); + return this.performanceModel; } - async _waitForTracingToStop(awaitTracingCompleteCallback: boolean): Promise<void> { + private async waitForTracingToStop(awaitTracingCompleteCallback: boolean): Promise<void> { const tracingStoppedPromises = []; - if (this._tracingManager && awaitTracingCompleteCallback) { + if (this.tracingManager && awaitTracingCompleteCallback) { tracingStoppedPromises.push(new Promise(resolve => { - this._tracingCompleteCallback = resolve; + this.tracingCompleteCallback = resolve; })); } - tracingStoppedPromises.push(this._stopProfilingOnAllModels()); + tracingStoppedPromises.push(this.stopProfilingOnAllModels()); - const extensionCompletionPromises = this._extensionSessions.map(session => session.stop()); + const extensionCompletionPromises = this.extensionSessions.map(session => session.stop()); if (extensionCompletionPromises.length) { tracingStoppedPromises.push( Promise.race([Promise.all(extensionCompletionPromises), new Promise(r => setTimeout(r, 5000))])); @@ -154,7 +152,7 @@ } modelAdded(cpuProfilerModel: SDK.CPUProfilerModel.CPUProfilerModel): void { - if (this._profiling) { + if (this.profiling) { cpuProfilerModel.startRecording(); } } @@ -164,39 +162,39 @@ // but it's too late. Backend connection is closed. } - async _startProfilingOnAllModels(): Promise<void> { - this._profiling = true; + private async startProfilingOnAllModels(): Promise<void> { + this.profiling = true; const models = SDK.TargetManager.TargetManager.instance().models(SDK.CPUProfilerModel.CPUProfilerModel); await Promise.all(models.map(model => model.startRecording())); } - _addCpuProfile(targetId: string, cpuProfile: Protocol.Profiler.Profile|null): void { + private addCpuProfile(targetId: string, cpuProfile: Protocol.Profiler.Profile|null): void { if (!cpuProfile) { Common.Console.Console.instance().warn(i18nString(UIStrings.cpuProfileForATargetIsNot)); return; } - if (!this._cpuProfiles) { - this._cpuProfiles = new Map(); + if (!this.cpuProfiles) { + this.cpuProfiles = new Map(); } - this._cpuProfiles.set(targetId, cpuProfile); + this.cpuProfiles.set(targetId, cpuProfile); } - async _stopProfilingOnAllModels(): Promise<void> { + private async stopProfilingOnAllModels(): Promise<void> { const models = - this._profiling ? SDK.TargetManager.TargetManager.instance().models(SDK.CPUProfilerModel.CPUProfilerModel) : []; - this._profiling = false; + this.profiling ? SDK.TargetManager.TargetManager.instance().models(SDK.CPUProfilerModel.CPUProfilerModel) : []; + this.profiling = false; const promises = []; for (const model of models) { const targetId = model.target().id(); - const modelPromise = model.stopRecording().then(this._addCpuProfile.bind(this, targetId)); + const modelPromise = model.stopRecording().then(this.addCpuProfile.bind(this, targetId)); promises.push(modelPromise); } await Promise.all(promises); } - async _startRecordingWithCategories(categories: string, enableJSSampling?: boolean): + private async startRecordingWithCategories(categories: string, enableJSSampling?: boolean): Promise<Protocol.ProtocolResponseWithError> { - if (!this._tracingManager) { + if (!this.tracingManager) { throw new Error(UIStrings.tracingNotSupported); } // There might be a significant delay in the beginning of timeline recording @@ -204,37 +202,37 @@ // all the functions data. await SDK.TargetManager.TargetManager.instance().suspendAllTargets('performance-timeline'); if (enableJSSampling && Root.Runtime.Runtime.queryParam('timelineTracingJSProfileDisabled')) { - await this._startProfilingOnAllModels(); + await this.startProfilingOnAllModels(); } - return this._tracingManager.start(this, categories, ''); + return this.tracingManager.start(this, categories, ''); } traceEventsCollected(events: SDK.TracingManager.EventPayload[]): void { - this._tracingModel.addEvents(events); + this.tracingModel.addEvents(events); } tracingComplete(): void { - if (!this._tracingCompleteCallback) { + if (!this.tracingCompleteCallback) { return; } - this._tracingCompleteCallback(undefined); - this._tracingCompleteCallback = null; + this.tracingCompleteCallback(undefined); + this.tracingCompleteCallback = null; } - _allSourcesFinished(): void { - this._client.processingStarted(); - setTimeout(() => this._finalizeTrace(), 0); + private allSourcesFinished(): void { + this.client.processingStarted(); + setTimeout(() => this.finalizeTrace(), 0); } - async _finalizeTrace(): Promise<void> { - this._injectCpuProfileEvents(); + private async finalizeTrace(): Promise<void> { + this.injectCpuProfileEvents(); await SDK.TargetManager.TargetManager.instance().resumeAllTargets(); - this._tracingModel.tracingComplete(); - this._client.loadingComplete(this._tracingModel); + this.tracingModel.tracingComplete(); + this.client.loadingComplete(this.tracingModel); } - _injectCpuProfileEvent(pid: number, tid: number, cpuProfile: Protocol.Profiler.Profile|null): void { + private injectCpuProfileEvent(pid: number, tid: number, cpuProfile: Protocol.Profiler.Profile|null): void { if (!cpuProfile) { return; } @@ -244,7 +242,7 @@ const cpuProfileEvent = ({ cat: SDK.TracingModel.DevToolsMetadataEventCategory, ph: SDK.TracingModel.Phase.Instant, - ts: this._tracingModel.maximumRecordTime() * 1000, + ts: this.tracingModel.maximumRecordTime() * 1000, pid: pid, tid: tid, name: TimelineModel.TimelineModel.RecordType.CpuProfile, @@ -252,12 +250,12 @@ // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any); - this._tracingModel.addEvents([cpuProfileEvent]); + this.tracingModel.addEvents([cpuProfileEvent]); } - _buildTargetToProcessIdMap(): Map<string, number>|null { + private buildTargetToProcessIdMap(): Map<string, number>|null { const metadataEventTypes = TimelineModel.TimelineModel.TimelineModelImpl.DevToolsMetadataEvent; - const metadataEvents = this._tracingModel.devToolsMetadataEvents(); + const metadataEvents = this.tracingModel.devToolsMetadataEvents(); const browserMetaEvent = metadataEvents.find(e => e.name === metadataEventTypes.TracingStartedInBrowser); if (!browserMetaEvent) { return null; @@ -290,7 +288,7 @@ } const mainFrame = frames.find(frame => !frame.parent); const mainRendererProcessId = mainFrame.processId; - const mainProcess = this._tracingModel.getProcessById(mainRendererProcessId); + const mainProcess = this.tracingModel.getProcessById(mainRendererProcessId); if (mainProcess) { const target = SDK.TargetManager.TargetManager.instance().mainTarget(); if (target) { @@ -300,26 +298,26 @@ return targetIdToPid; } - _injectCpuProfileEvents(): void { - if (!this._cpuProfiles) { + private injectCpuProfileEvents(): void { + if (!this.cpuProfiles) { return; } const metadataEventTypes = TimelineModel.TimelineModel.TimelineModelImpl.DevToolsMetadataEvent; - const metadataEvents = this._tracingModel.devToolsMetadataEvents(); + const metadataEvents = this.tracingModel.devToolsMetadataEvents(); - const targetIdToPid = this._buildTargetToProcessIdMap(); + const targetIdToPid = this.buildTargetToProcessIdMap(); if (targetIdToPid) { - for (const [id, profile] of this._cpuProfiles) { + for (const [id, profile] of this.cpuProfiles) { const pid = targetIdToPid.get(id); if (!pid) { continue; } - const process = this._tracingModel.getProcessById(pid); + const process = this.tracingModel.getProcessById(pid); const thread = process && process.threadByName(TimelineModel.TimelineModel.TimelineModelImpl.RendererMainThreadName); if (thread) { - this._injectCpuProfileEvent(pid, thread.id(), profile); + this.injectCpuProfileEvent(pid, thread.id(), profile); } } } else { @@ -328,18 +326,18 @@ const mainMetaEvent = filteredEvents[filteredEvents.length - 1]; if (mainMetaEvent) { const pid = mainMetaEvent.thread.process().id(); - if (this._tracingManager) { - const mainCpuProfile = this._cpuProfiles.get(this._tracingManager.target().id()); - this._injectCpuProfileEvent(pid, mainMetaEvent.thread.id(), mainCpuProfile); + if (this.tracingManager) { + const mainCpuProfile = this.cpuProfiles.get(this.tracingManager.target().id()); + this.injectCpuProfileEvent(pid, mainMetaEvent.thread.id(), mainCpuProfile); } } else { // Or there was no tracing manager in the main target at all, in this case build the model full // of cpu profiles. let tid = 0; - for (const pair of this._cpuProfiles) { + for (const pair of this.cpuProfiles) { const target = SDK.TargetManager.TargetManager.instance().targetById(pair[0]); const name = target && target.name(); - this._tracingModel.addEvents( + this.tracingModel.addEvents( TimelineModel.TimelineJSProfile.TimelineJSProfileProcessor.buildTraceProfileFromCpuProfile( pair[1], ++tid, /* injectPageEvent */ tid === 1, name)); } @@ -350,19 +348,18 @@ metadataEvents.filter(event => event.name === metadataEventTypes.TracingSessionIdForWorker); for (const metaEvent of workerMetaEvents) { const workerId = metaEvent.args['data']['workerId']; - const cpuProfile = this._cpuProfiles.get(workerId); - this._injectCpuProfileEvent( - metaEvent.thread.process().id(), metaEvent.args['data']['workerThreadId'], cpuProfile); + const cpuProfile = this.cpuProfiles.get(workerId); + this.injectCpuProfileEvent(metaEvent.thread.process().id(), metaEvent.args['data']['workerThreadId'], cpuProfile); } - this._cpuProfiles = null; + this.cpuProfiles = null; } tracingBufferUsage(usage: number): void { - this._client.recordingProgress(usage); + this.client.recordingProgress(usage); } eventsRetrievalProgress(progress: number): void { - this._client.loadingProgress(progress); + this.client.loadingProgress(progress); } }
diff --git a/front_end/panels/timeline/TimelineDetailsView.ts b/front_end/panels/timeline/TimelineDetailsView.ts index bce239d..3d0045a 100644 --- a/front_end/panels/timeline/TimelineDetailsView.ts +++ b/front_end/panels/timeline/TimelineDetailsView.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import type * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as SDK from '../../core/sdk/sdk.js'; @@ -71,76 +69,76 @@ const str_ = i18n.i18n.registerUIStrings('panels/timeline/TimelineDetailsView.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class TimelineDetailsView extends UI.Widget.VBox { - _detailsLinkifier: Components.Linkifier.Linkifier; - _tabbedPane: UI.TabbedPane.TabbedPane; - _defaultDetailsWidget: UI.Widget.VBox; - _defaultDetailsContentElement: HTMLElement; - _rangeDetailViews: Map<string, TimelineTreeView>; - _additionalMetricsToolbar: UI.Toolbar.Toolbar; - _model!: PerformanceModel; - _track?: TimelineModel.TimelineModel.Track|null; - _lazyPaintProfilerView?: TimelinePaintProfilerView|null; - _lazyLayersView?: TimelineLayersView|null; - _preferredTabId?: string; - _selection?: TimelineSelection|null; + private readonly detailsLinkifier: Components.Linkifier.Linkifier; + private tabbedPane: UI.TabbedPane.TabbedPane; + private readonly defaultDetailsWidget: UI.Widget.VBox; + private readonly defaultDetailsContentElement: HTMLElement; + private rangeDetailViews: Map<string, TimelineTreeView>; + private readonly additionalMetricsToolbar: UI.Toolbar.Toolbar; + private model!: PerformanceModel; + private track?: TimelineModel.TimelineModel.Track|null; + private lazyPaintProfilerView?: TimelinePaintProfilerView|null; + private lazyLayersView?: TimelineLayersView|null; + private preferredTabId?: string; + private selection?: TimelineSelection|null; constructor(delegate: TimelineModeViewDelegate) { super(); this.element.classList.add('timeline-details'); - this._detailsLinkifier = new Components.Linkifier.Linkifier(); + this.detailsLinkifier = new Components.Linkifier.Linkifier(); - this._tabbedPane = new UI.TabbedPane.TabbedPane(); - this._tabbedPane.show(this.element); + this.tabbedPane = new UI.TabbedPane.TabbedPane(); + this.tabbedPane.show(this.element); - this._defaultDetailsWidget = new UI.Widget.VBox(); - this._defaultDetailsWidget.element.classList.add('timeline-details-view'); - this._defaultDetailsContentElement = - this._defaultDetailsWidget.element.createChild('div', 'timeline-details-view-body vbox'); - this._appendTab(Tab.Details, i18nString(UIStrings.summary), this._defaultDetailsWidget); + this.defaultDetailsWidget = new UI.Widget.VBox(); + this.defaultDetailsWidget.element.classList.add('timeline-details-view'); + this.defaultDetailsContentElement = + this.defaultDetailsWidget.element.createChild('div', 'timeline-details-view-body vbox'); + this.appendTab(Tab.Details, i18nString(UIStrings.summary), this.defaultDetailsWidget); this.setPreferredTab(Tab.Details); - this._rangeDetailViews = new Map(); + this.rangeDetailViews = new Map(); const bottomUpView = new BottomUpTimelineTreeView(); - this._appendTab(Tab.BottomUp, i18nString(UIStrings.bottomup), bottomUpView); - this._rangeDetailViews.set(Tab.BottomUp, bottomUpView); + this.appendTab(Tab.BottomUp, i18nString(UIStrings.bottomup), bottomUpView); + this.rangeDetailViews.set(Tab.BottomUp, bottomUpView); const callTreeView = new CallTreeTimelineTreeView(); - this._appendTab(Tab.CallTree, i18nString(UIStrings.callTree), callTreeView); - this._rangeDetailViews.set(Tab.CallTree, callTreeView); + this.appendTab(Tab.CallTree, i18nString(UIStrings.callTree), callTreeView); + this.rangeDetailViews.set(Tab.CallTree, callTreeView); const eventsView = new EventsTimelineTreeView(delegate); - this._appendTab(Tab.EventLog, i18nString(UIStrings.eventLog), eventsView); - this._rangeDetailViews.set(Tab.EventLog, eventsView); + this.appendTab(Tab.EventLog, i18nString(UIStrings.eventLog), eventsView); + this.rangeDetailViews.set(Tab.EventLog, eventsView); - this._additionalMetricsToolbar = new UI.Toolbar.Toolbar('timeline-additional-metrics'); - this.element.appendChild(this._additionalMetricsToolbar.element); + this.additionalMetricsToolbar = new UI.Toolbar.Toolbar('timeline-additional-metrics'); + this.element.appendChild(this.additionalMetricsToolbar.element); - this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected, this._tabSelected, this); + this.tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected, this.tabSelected, this); } setModel(model: PerformanceModel|null, track: TimelineModel.TimelineModel.Track|null): void { - if (this._model !== model) { - if (this._model) { - this._model.removeEventListener(Events.WindowChanged, this._onWindowChanged, this); + if (this.model !== model) { + if (this.model) { + this.model.removeEventListener(Events.WindowChanged, this.onWindowChanged, this); } - this._model = (model as PerformanceModel); - if (this._model) { - this._model.addEventListener(Events.WindowChanged, this._onWindowChanged, this); + this.model = (model as PerformanceModel); + if (this.model) { + this.model.addEventListener(Events.WindowChanged, this.onWindowChanged, this); } } - this._track = track; - this._tabbedPane.closeTabs([Tab.PaintProfiler, Tab.LayerViewer], false); - for (const view of this._rangeDetailViews.values()) { + this.track = track; + this.tabbedPane.closeTabs([Tab.PaintProfiler, Tab.LayerViewer], false); + for (const view of this.rangeDetailViews.values()) { view.setModel(model, track); } - this._lazyPaintProfilerView = null; - this._lazyLayersView = null; + this.lazyPaintProfilerView = null; + this.lazyLayersView = null; this.setSelection(null); // Add TBT info to the footer. - this._additionalMetricsToolbar.removeToolbarItems(); + this.additionalMetricsToolbar.removeToolbarItems(); if (model && model.timelineModel()) { const {estimated, time} = model.timelineModel().totalBlockingTime(); const isEstimate = estimated ? ` (${i18nString(UIStrings.estimated)})` : ''; @@ -154,169 +152,169 @@ clsLink.style.marginRight = '2px'; warning.appendChild(clsLink); - this._additionalMetricsToolbar.appendText(message); - this._additionalMetricsToolbar.appendToolbarItem(new UI.Toolbar.ToolbarItem(warning)); + this.additionalMetricsToolbar.appendText(message); + this.additionalMetricsToolbar.appendToolbarItem(new UI.Toolbar.ToolbarItem(warning)); } } - _setContent(node: Node): void { - const allTabs = this._tabbedPane.otherTabs(Tab.Details); + private setContent(node: Node): void { + const allTabs = this.tabbedPane.otherTabs(Tab.Details); for (let i = 0; i < allTabs.length; ++i) { - if (!this._rangeDetailViews.has(allTabs[i])) { - this._tabbedPane.closeTab(allTabs[i]); + if (!this.rangeDetailViews.has(allTabs[i])) { + this.tabbedPane.closeTab(allTabs[i]); } } - this._defaultDetailsContentElement.removeChildren(); - this._defaultDetailsContentElement.appendChild(node); + this.defaultDetailsContentElement.removeChildren(); + this.defaultDetailsContentElement.appendChild(node); } - _updateContents(): void { - const view = this._rangeDetailViews.get(this._tabbedPane.selectedTabId || ''); + private updateContents(): void { + const view = this.rangeDetailViews.get(this.tabbedPane.selectedTabId || ''); if (view) { - const window = this._model.window(); - view.updateContents(this._selection || TimelineSelection.fromRange(window.left, window.right)); + const window = this.model.window(); + view.updateContents(this.selection || TimelineSelection.fromRange(window.left, window.right)); } } - _appendTab(id: string, tabTitle: string, view: UI.Widget.Widget, isCloseable?: boolean): void { - this._tabbedPane.appendTab(id, tabTitle, view, undefined, undefined, isCloseable); - if (this._preferredTabId !== this._tabbedPane.selectedTabId) { - this._tabbedPane.selectTab(id); + private appendTab(id: string, tabTitle: string, view: UI.Widget.Widget, isCloseable?: boolean): void { + this.tabbedPane.appendTab(id, tabTitle, view, undefined, undefined, isCloseable); + if (this.preferredTabId !== this.tabbedPane.selectedTabId) { + this.tabbedPane.selectTab(id); } } headerElement(): Element { - return this._tabbedPane.headerElement(); + return this.tabbedPane.headerElement(); } setPreferredTab(tabId: string): void { - this._preferredTabId = tabId; + this.preferredTabId = tabId; } - _onWindowChanged(_event: Common.EventTarget.EventTargetEvent): void { - if (!this._selection) { - this._updateContentsFromWindow(); + private onWindowChanged(_event: Common.EventTarget.EventTargetEvent): void { + if (!this.selection) { + this.updateContentsFromWindow(); } } - _updateContentsFromWindow(): void { - if (!this._model) { - this._setContent(UI.Fragment.html`<div/>`); + private updateContentsFromWindow(): void { + if (!this.model) { + this.setContent(UI.Fragment.html`<div/>`); return; } - const window = this._model.window(); - this._updateSelectedRangeStats(window.left, window.right); - this._updateContents(); + const window = this.model.window(); + this.updateSelectedRangeStats(window.left, window.right); + this.updateContents(); } setSelection(selection: TimelineSelection|null): void { - this._detailsLinkifier.reset(); - this._selection = selection; - if (!this._selection) { - this._updateContentsFromWindow(); + this.detailsLinkifier.reset(); + this.selection = selection; + if (!this.selection) { + this.updateContentsFromWindow(); return; } - switch (this._selection.type()) { + switch (this.selection.type()) { case TimelineSelection.Type.TraceEvent: { - const event = (this._selection.object() as SDK.TracingModel.Event); - TimelineUIUtils.buildTraceEventDetails(event, this._model.timelineModel(), this._detailsLinkifier, true) - .then(fragment => this._appendDetailsTabsForTraceEventAndShowDetails(event, fragment)); + const event = (this.selection.object() as SDK.TracingModel.Event); + TimelineUIUtils.buildTraceEventDetails(event, this.model.timelineModel(), this.detailsLinkifier, true) + .then(fragment => this.appendDetailsTabsForTraceEventAndShowDetails(event, fragment)); break; } case TimelineSelection.Type.Frame: { - const frame = (this._selection.object() as TimelineModel.TimelineFrameModel.TimelineFrame); - const filmStripFrame = this._model.filmStripModelFrame(frame); - this._setContent(TimelineUIUtils.generateDetailsContentForFrame(frame, filmStripFrame)); + const frame = (this.selection.object() as TimelineModel.TimelineFrameModel.TimelineFrame); + const filmStripFrame = this.model.filmStripModelFrame(frame); + this.setContent(TimelineUIUtils.generateDetailsContentForFrame(frame, filmStripFrame)); if (frame.layerTree) { - const layersView = this._layersView(); + const layersView = this.layersView(); layersView.showLayerTree(frame.layerTree); - if (!this._tabbedPane.hasTab(Tab.LayerViewer)) { - this._appendTab(Tab.LayerViewer, i18nString(UIStrings.layers), layersView); + if (!this.tabbedPane.hasTab(Tab.LayerViewer)) { + this.appendTab(Tab.LayerViewer, i18nString(UIStrings.layers), layersView); } } break; } case TimelineSelection.Type.NetworkRequest: { - const request = (this._selection.object() as TimelineModel.TimelineModel.NetworkRequest); - TimelineUIUtils.buildNetworkRequestDetails(request, this._model.timelineModel(), this._detailsLinkifier) - .then(this._setContent.bind(this)); + const request = (this.selection.object() as TimelineModel.TimelineModel.NetworkRequest); + TimelineUIUtils.buildNetworkRequestDetails(request, this.model.timelineModel(), this.detailsLinkifier) + .then(this.setContent.bind(this)); break; } case TimelineSelection.Type.Range: { - this._updateSelectedRangeStats(this._selection.startTime(), this._selection.endTime()); + this.updateSelectedRangeStats(this.selection.startTime(), this.selection.endTime()); break; } } - this._updateContents(); + this.updateContents(); } - _tabSelected(event: Common.EventTarget.EventTargetEvent): void { + private tabSelected(event: Common.EventTarget.EventTargetEvent): void { if (!event.data.isUserGesture) { return; } this.setPreferredTab(event.data.tabId); - this._updateContents(); + this.updateContents(); } - _layersView(): TimelineLayersView { - if (this._lazyLayersView) { - return this._lazyLayersView; + private layersView(): TimelineLayersView { + if (this.lazyLayersView) { + return this.lazyLayersView; } - this._lazyLayersView = - new TimelineLayersView(this._model.timelineModel(), this._showSnapshotInPaintProfiler.bind(this)); - return this._lazyLayersView; + this.lazyLayersView = + new TimelineLayersView(this.model.timelineModel(), this.showSnapshotInPaintProfiler.bind(this)); + return this.lazyLayersView; } - _paintProfilerView(): TimelinePaintProfilerView { - if (this._lazyPaintProfilerView) { - return this._lazyPaintProfilerView; + private paintProfilerView(): TimelinePaintProfilerView { + if (this.lazyPaintProfilerView) { + return this.lazyPaintProfilerView; } - this._lazyPaintProfilerView = new TimelinePaintProfilerView(this._model.frameModel()); - return this._lazyPaintProfilerView; + this.lazyPaintProfilerView = new TimelinePaintProfilerView(this.model.frameModel()); + return this.lazyPaintProfilerView; } - _showSnapshotInPaintProfiler(snapshot: SDK.PaintProfiler.PaintProfilerSnapshot): void { - const paintProfilerView = this._paintProfilerView(); + private showSnapshotInPaintProfiler(snapshot: SDK.PaintProfiler.PaintProfilerSnapshot): void { + const paintProfilerView = this.paintProfilerView(); paintProfilerView.setSnapshot(snapshot); - if (!this._tabbedPane.hasTab(Tab.PaintProfiler)) { - this._appendTab(Tab.PaintProfiler, i18nString(UIStrings.paintProfiler), paintProfilerView, true); + if (!this.tabbedPane.hasTab(Tab.PaintProfiler)) { + this.appendTab(Tab.PaintProfiler, i18nString(UIStrings.paintProfiler), paintProfilerView, true); } - this._tabbedPane.selectTab(Tab.PaintProfiler, true); + this.tabbedPane.selectTab(Tab.PaintProfiler, true); } - _appendDetailsTabsForTraceEventAndShowDetails(event: SDK.TracingModel.Event, content: Node): void { - this._setContent(content); + private appendDetailsTabsForTraceEventAndShowDetails(event: SDK.TracingModel.Event, content: Node): void { + this.setContent(content); if (event.name === TimelineModel.TimelineModel.RecordType.Paint || event.name === TimelineModel.TimelineModel.RecordType.RasterTask) { - this._showEventInPaintProfiler(event); + this.showEventInPaintProfiler(event); } } - _showEventInPaintProfiler(event: SDK.TracingModel.Event): void { + private showEventInPaintProfiler(event: SDK.TracingModel.Event): void { const paintProfilerModel = SDK.TargetManager.TargetManager.instance().models(SDK.PaintProfiler.PaintProfilerModel)[0]; if (!paintProfilerModel) { return; } - const paintProfilerView = this._paintProfilerView(); + const paintProfilerView = this.paintProfilerView(); const hasProfileData = paintProfilerView.setEvent(paintProfilerModel, event); if (!hasProfileData) { return; } - if (this._tabbedPane.hasTab(Tab.PaintProfiler)) { + if (this.tabbedPane.hasTab(Tab.PaintProfiler)) { return; } - this._appendTab(Tab.PaintProfiler, i18nString(UIStrings.paintProfiler), paintProfilerView); + this.appendTab(Tab.PaintProfiler, i18nString(UIStrings.paintProfiler), paintProfilerView); } - _updateSelectedRangeStats(startTime: number, endTime: number): void { - if (!this._model || !this._track) { + private updateSelectedRangeStats(startTime: number, endTime: number): void { + if (!this.model || !this.track) { return; } - const aggregatedStats = TimelineUIUtils.statsForTimeRange(this._track.syncEvents(), startTime, endTime); - const startOffset = startTime - this._model.timelineModel().minimumRecordTime(); - const endOffset = endTime - this._model.timelineModel().minimumRecordTime(); + const aggregatedStats = TimelineUIUtils.statsForTimeRange(this.track.syncEvents(), startTime, endTime); + const startOffset = startTime - this.model.timelineModel().minimumRecordTime(); + const endOffset = endTime - this.model.timelineModel().minimumRecordTime(); const contentHelper = new TimelineDetailsContentHelper(null, null); contentHelper.addSection(i18nString( @@ -324,7 +322,7 @@ {PH1: i18n.TimeUtilities.millisToString(startOffset), PH2: i18n.TimeUtilities.millisToString(endOffset)})); const pieChart = TimelineUIUtils.generatePieChart(aggregatedStats); contentHelper.appendElementRow('', pieChart); - this._setContent(contentHelper.fragment); + this.setContent(contentHelper.fragment); } }
diff --git a/front_end/panels/timeline/TimelineEventOverview.ts b/front_end/panels/timeline/TimelineEventOverview.ts index 39de5f2..be3f12e 100644 --- a/front_end/panels/timeline/TimelineEventOverview.ts +++ b/front_end/panels/timeline/TimelineEventOverview.ts
@@ -28,8 +28,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; import type * as SDK from '../../core/sdk/sdk.js'; @@ -74,22 +72,22 @@ const str_ = i18n.i18n.registerUIStrings('panels/timeline/TimelineEventOverview.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class TimelineEventOverview extends PerfUI.TimelineOverviewPane.TimelineOverviewBase { - _model: PerformanceModel|null; + protected model: PerformanceModel|null; constructor(id: string, title: string|null) { super(); this.element.id = 'timeline-overview-' + id; this.element.classList.add('overview-strip'); - this._model = null; + this.model = null; if (title) { this.element.createChild('div', 'timeline-overview-strip-title').textContent = title; } } setModel(model: PerformanceModel|null): void { - this._model = model; + this.model = model; } - _renderBar(begin: number, end: number, position: number, height: number, color: string): void { + renderBar(begin: number, end: number, position: number, height: number, color: string): void { const x = begin; const width = end - begin; const ctx = this.context(); @@ -105,7 +103,7 @@ update(): void { super.update(); - if (!this._model) { + if (!this.model) { return; } const height = this.height(); @@ -120,13 +118,13 @@ } const minWidth = 2 * window.devicePixelRatio; - const timeOffset = this._model.timelineModel().minimumRecordTime(); - const timeSpan = this._model.timelineModel().maximumRecordTime() - timeOffset; + const timeOffset = this.model.timelineModel().minimumRecordTime(); + const timeSpan = this.model.timelineModel().maximumRecordTime() - timeOffset; const canvasWidth = this.width(); const scale = canvasWidth / timeSpan; for (let priority = 0; priority <= maxPriority; ++priority) { - for (const track of this._model.timelineModel().tracks()) { + for (const track of this.model.timelineModel().tracks()) { for (let i = 0; i < track.events.length; ++i) { const event = track.events[i]; if (event.name !== TimelineModel.TimelineModel.RecordType.EventDispatch) { @@ -143,7 +141,7 @@ Platform.NumberUtilities.clamp(Math.floor((event.startTime - timeOffset) * scale), 0, canvasWidth); const end = Platform.NumberUtilities.clamp(Math.ceil((event.endTime - timeOffset) * scale), 0, canvasWidth); const width = Math.max(end - start, minWidth); - this._renderBar(start, start + width, 0, height, descriptor.color); + this.renderBar(start, start + width, 0, height, descriptor.color); } } } @@ -157,10 +155,10 @@ update(): void { super.update(); - if (!this._model) { + if (!this.model) { return; } - const timelineModel = this._model.timelineModel(); + const timelineModel = this.model.timelineModel(); const bandHeight = this.height() / 2; const timeOffset = timelineModel.minimumRecordTime(); const timeSpan = timelineModel.maximumRecordTime() - timeOffset; @@ -197,25 +195,25 @@ const categoryToIndex = new WeakMap<TimelineCategory, number>(); export class TimelineEventOverviewCPUActivity extends TimelineEventOverview { - _backgroundCanvas: HTMLCanvasElement; + private backgroundCanvas: HTMLCanvasElement; constructor() { super('cpu-activity', i18nString(UIStrings.cpu)); - this._backgroundCanvas = (this.element.createChild('canvas', 'fill background') as HTMLCanvasElement); + this.backgroundCanvas = (this.element.createChild('canvas', 'fill background') as HTMLCanvasElement); } resetCanvas(): void { super.resetCanvas(); - this._backgroundCanvas.width = this.element.clientWidth * window.devicePixelRatio; - this._backgroundCanvas.height = this.element.clientHeight * window.devicePixelRatio; + this.backgroundCanvas.width = this.element.clientWidth * window.devicePixelRatio; + this.backgroundCanvas.height = this.element.clientHeight * window.devicePixelRatio; } update(): void { super.update(); - if (!this._model) { + if (!this.model) { return; } - const timelineModel = this._model.timelineModel(); - const /** @const */ quantSizePx = 4 * window.devicePixelRatio; + const timelineModel = this.model.timelineModel(); + const quantSizePx = 4 * window.devicePixelRatio; const width = this.width(); const height = this.height(); const baseLine = height; @@ -232,7 +230,7 @@ categoryToIndex.set(categories[categoryOrder[i]], i); } - const backgroundContext = (this._backgroundCanvas.getContext('2d') as CanvasRenderingContext2D | null); + const backgroundContext = (this.backgroundCanvas.getContext('2d') as CanvasRenderingContext2D | null); if (!backgroundContext) { throw new Error('Could not find 2d canvas'); } @@ -312,15 +310,15 @@ update(): void { super.update(); - if (!this._model) { + if (!this.model) { return; } const height = this.height(); - const timeOffset = this._model.timelineModel().minimumRecordTime(); - const timeSpan = this._model.timelineModel().maximumRecordTime() - timeOffset; + const timeOffset = this.model.timelineModel().minimumRecordTime(); + const timeSpan = this.model.timelineModel().maximumRecordTime() - timeOffset; const scale = this.width() / timeSpan; - const frames = this._model.frames(); + const frames = this.model.frames(); const ctx = this.context(); const fillPath = new Path2D(); const markersPath = new Path2D(); @@ -332,7 +330,7 @@ paintWarningDecoration(frame.startTime, frame.duration); } - for (const track of this._model.timelineModel().tracks()) { + for (const track of this.model.timelineModel().tracks()) { const events = track.events; for (let i = 0; i < events.length; ++i) { if (!TimelineModel.TimelineModel.TimelineData.forEvent(events[i]).warning) { @@ -362,32 +360,32 @@ } export class TimelineFilmStripOverview extends TimelineEventOverview { - _frameToImagePromise: Map<SDK.FilmStripModel.Frame, Promise<HTMLImageElement>>; - _lastFrame: SDK.FilmStripModel.Frame|null; - _lastElement: Element|null; - _drawGeneration?: symbol; - _emptyImage?: HTMLImageElement; - _imageWidth?: number; + private frameToImagePromise: Map<SDK.FilmStripModel.Frame, Promise<HTMLImageElement>>; + private lastFrame: SDK.FilmStripModel.Frame|null; + private lastElement: Element|null; + private drawGeneration?: symbol; + private emptyImage?: HTMLImageElement; + private imageWidth?: number; constructor() { super('filmstrip', null); - this._frameToImagePromise = new Map(); - this._lastFrame = null; - this._lastElement = null; + this.frameToImagePromise = new Map(); + this.lastFrame = null; + this.lastElement = null; this.reset(); } update(): void { super.update(); - const frames = this._model ? this._model.filmStripModel().frames() : []; + const frames = this.model ? this.model.filmStripModel().frames() : []; if (!frames.length) { return; } const drawGeneration = Symbol('drawGeneration'); - this._drawGeneration = drawGeneration; - this._imageByFrame(frames[0]).then(image => { - if (this._drawGeneration !== drawGeneration) { + this.drawGeneration = drawGeneration; + this.imageByFrame(frames[0]).then(image => { + if (this.drawGeneration !== drawGeneration) { return; } if (!image || !image.naturalWidth || !image.naturalHeight) { @@ -396,26 +394,26 @@ const imageHeight = this.height() - 2 * TimelineFilmStripOverview.Padding; const imageWidth = Math.ceil(imageHeight * image.naturalWidth / image.naturalHeight); const popoverScale = Math.min(200 / image.naturalWidth, 1); - this._emptyImage = new Image(image.naturalWidth * popoverScale, image.naturalHeight * popoverScale); - this._drawFrames(imageWidth, imageHeight); + this.emptyImage = new Image(image.naturalWidth * popoverScale, image.naturalHeight * popoverScale); + this.drawFrames(imageWidth, imageHeight); }); } - async _imageByFrame(frame: SDK.FilmStripModel.Frame): Promise<HTMLImageElement|null> { - let imagePromise: Promise<HTMLImageElement|null>|undefined = this._frameToImagePromise.get(frame); + private async imageByFrame(frame: SDK.FilmStripModel.Frame): Promise<HTMLImageElement|null> { + let imagePromise: Promise<HTMLImageElement|null>|undefined = this.frameToImagePromise.get(frame); if (!imagePromise) { const data = await frame.imageDataPromise(); imagePromise = UI.UIUtils.loadImageFromData(data); - this._frameToImagePromise.set(frame, (imagePromise as Promise<HTMLImageElement>)); + this.frameToImagePromise.set(frame, (imagePromise as Promise<HTMLImageElement>)); } return imagePromise; } - _drawFrames(imageWidth: number, imageHeight: number): void { - if (!imageWidth || !this._model) { + private drawFrames(imageWidth: number, imageHeight: number): void { + if (!imageWidth || !this.model) { return; } - const filmStripModel = this._model.filmStripModel(); + const filmStripModel = this.model.filmStripModel(); if (!filmStripModel.frames().length) { return; } @@ -425,7 +423,7 @@ const spanTime = filmStripModel.spanTime(); const scale = spanTime / width; const context = this.context(); - const drawGeneration = this._drawGeneration; + const drawGeneration = this.drawGeneration; context.beginPath(); for (let x = padding; x < width; x += imageWidth + 2 * padding) { @@ -435,14 +433,14 @@ continue; } context.rect(x - 0.5, 0.5, imageWidth + 1, imageHeight + 1); - this._imageByFrame(frame).then(drawFrameImage.bind(this, x)); + this.imageByFrame(frame).then(drawFrameImage.bind(this, x)); } context.strokeStyle = '#ddd'; context.stroke(); function drawFrameImage(this: TimelineFilmStripOverview, x: number, image: HTMLImageElement|null): void { // Ignore draws deferred from a previous update call. - if (this._drawGeneration !== drawGeneration || !image) { + if (this.drawGeneration !== drawGeneration || !image) { return; } context.drawImage(image, x, 1, imageWidth, imageHeight); @@ -450,7 +448,7 @@ } async overviewInfoPromise(x: number): Promise<Element|null> { - if (!this._model || !this._model.filmStripModel().frames().length) { + if (!this.model || !this.model.filmStripModel().frames().length) { return null; } @@ -459,27 +457,27 @@ return null; } const time = calculator.positionToTime(x); - const frame = this._model.filmStripModel().frameByTimestamp(time); - if (frame === this._lastFrame) { - return this._lastElement; + const frame = this.model.filmStripModel().frameByTimestamp(time); + if (frame === this.lastFrame) { + return this.lastElement; } - const imagePromise = frame ? this._imageByFrame(frame) : Promise.resolve(this._emptyImage); + const imagePromise = frame ? this.imageByFrame(frame) : Promise.resolve(this.emptyImage); const image = await imagePromise; const element = document.createElement('div'); element.classList.add('frame'); if (image) { element.createChild('div', 'thumbnail').appendChild(image); } - this._lastFrame = frame; - this._lastElement = element; + this.lastFrame = frame; + this.lastElement = element; return element; } reset(): void { - this._lastFrame = null; - this._lastElement = null; - this._frameToImagePromise = new Map(); - this._imageWidth = 0; + this.lastFrame = null; + this.lastElement = null; + this.frameToImagePromise = new Map(); + this.imageWidth = 0; } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration @@ -494,10 +492,10 @@ update(): void { super.update(); - if (!this._model) { + if (!this.model) { return; } - const frames = this._model.frames(); + const frames = this.model.frames(); if (!frames.length) { return; } @@ -505,8 +503,8 @@ const padding = Number(window.devicePixelRatio); const baseFrameDurationMs = 1e3 / 60; const visualHeight = height - 2 * padding; - const timeOffset = this._model.timelineModel().minimumRecordTime(); - const timeSpan = this._model.timelineModel().maximumRecordTime() - timeOffset; + const timeOffset = this.model.timelineModel().minimumRecordTime(); + const timeSpan = this.model.timelineModel().maximumRecordTime() - timeOffset; const scale = this.width() / timeSpan; const baseY = height - padding; const ctx = this.context(); @@ -544,34 +542,34 @@ } export class TimelineEventOverviewMemory extends TimelineEventOverview { - _heapSizeLabel: HTMLElement; + private heapSizeLabel: HTMLElement; constructor() { super('memory', i18nString(UIStrings.heap)); - this._heapSizeLabel = this.element.createChild('div', 'memory-graph-label'); + this.heapSizeLabel = this.element.createChild('div', 'memory-graph-label'); } resetHeapSizeLabels(): void { - this._heapSizeLabel.textContent = ''; + this.heapSizeLabel.textContent = ''; } update(): void { super.update(); const ratio = window.devicePixelRatio; - if (!this._model) { + if (!this.model) { this.resetHeapSizeLabels(); return; } - const tracks = this._model.timelineModel().tracks().filter( + const tracks = this.model.timelineModel().tracks().filter( track => track.type === TimelineModel.TimelineModel.TrackType.MainThread && track.forMainFrame); const trackEvents = tracks.map(track => track.events); const lowerOffset = 3 * ratio; let maxUsedHeapSize = 0; let minUsedHeapSize = 100000000000; - const minTime = this._model.timelineModel().minimumRecordTime(); - const maxTime = this._model.timelineModel().maximumRecordTime(); + const minTime = this.model.timelineModel().minimumRecordTime(); + const maxTime = this.model.timelineModel().maximumRecordTime(); function isUpdateCountersEvent(event: SDK.TracingModel.Event): boolean { return event.name === TimelineModel.TimelineModel.RecordType.UpdateCounters; @@ -651,7 +649,7 @@ ctx.strokeStyle = 'hsl(220, 90%, 70%)'; ctx.stroke(); - this._heapSizeLabel.textContent = i18nString(UIStrings.sSDash, { + this.heapSizeLabel.textContent = i18nString(UIStrings.sSDash, { PH1: Platform.NumberUtilities.bytesToString(minUsedHeapSize), PH2: Platform.NumberUtilities.bytesToString(maxUsedHeapSize), }); @@ -659,53 +657,53 @@ } export class Quantizer { - _lastTime: number; - _quantDuration: number; - _callback: (arg0: Array<number>) => void; - _counters: number[]; - _remainder: number; + private lastTime: number; + private quantDuration: number; + private readonly callback: (arg0: Array<number>) => void; + private counters: number[]; + private remainder: number; constructor(startTime: number, quantDuration: number, callback: (arg0: Array<number>) => void) { - this._lastTime = startTime; - this._quantDuration = quantDuration; - this._callback = callback; - this._counters = []; - this._remainder = quantDuration; + this.lastTime = startTime; + this.quantDuration = quantDuration; + this.callback = callback; + this.counters = []; + this.remainder = quantDuration; } appendInterval(time: number, group: number): void { - let interval = time - this._lastTime; - if (interval <= this._remainder) { - this._counters[group] = (this._counters[group] || 0) + interval; - this._remainder -= interval; - this._lastTime = time; + let interval = time - this.lastTime; + if (interval <= this.remainder) { + this.counters[group] = (this.counters[group] || 0) + interval; + this.remainder -= interval; + this.lastTime = time; return; } - this._counters[group] = (this._counters[group] || 0) + this._remainder; - this._callback(this._counters); - interval -= this._remainder; - while (interval >= this._quantDuration) { + this.counters[group] = (this.counters[group] || 0) + this.remainder; + this.callback(this.counters); + interval -= this.remainder; + while (interval >= this.quantDuration) { const counters = []; - counters[group] = this._quantDuration; - this._callback(counters); - interval -= this._quantDuration; + counters[group] = this.quantDuration; + this.callback(counters); + interval -= this.quantDuration; } - this._counters = []; - this._counters[group] = interval; - this._lastTime = time; - this._remainder = this._quantDuration - interval; + this.counters = []; + this.counters[group] = interval; + this.lastTime = time; + this.remainder = this.quantDuration - interval; } } export class TimelineEventOverviewCoverage extends TimelineEventOverview { - _heapSizeLabel: HTMLElement; - _coverageModel?: Coverage.CoverageModel.CoverageModel|null; + private heapSizeLabel: HTMLElement; + private coverageModel?: Coverage.CoverageModel.CoverageModel|null; constructor() { super('coverage', i18nString(UIStrings.coverage)); - this._heapSizeLabel = this.element.createChild('div', 'timeline-overview-coverage-label'); + this.heapSizeLabel = this.element.createChild('div', 'timeline-overview-coverage-label'); } resetHeapSizeLabels(): void { - this._heapSizeLabel.textContent = ''; + this.heapSizeLabel.textContent = ''; } setModel(model: PerformanceModel|null): void { @@ -713,7 +711,7 @@ if (model) { const mainTarget = model.mainTarget(); if (mainTarget) { - this._coverageModel = mainTarget.model(Coverage.CoverageModel.CoverageModel); + this.coverageModel = mainTarget.model(Coverage.CoverageModel.CoverageModel); } } } @@ -722,7 +720,7 @@ super.update(); const ratio = window.devicePixelRatio; - if (!this._coverageModel) { + if (!this.coverageModel) { return; } @@ -732,7 +730,7 @@ let total_used = 0; const usedByTimestamp = new Map<number, number>(); const totalByTimestamp = new Map<number, Set<Coverage.CoverageModel.CoverageInfo>>(); - for (const urlInfo of this._coverageModel.entries()) { + for (const urlInfo of this.coverageModel.entries()) { for (const info of urlInfo.entries()) { total += info.getSize(); for (const [stamp, used] of info.usedByTimestamp()) { @@ -779,11 +777,11 @@ const lowerOffset = 3 * ratio; const millisecondsPerSecond = 1000; - if (!this._model) { + if (!this.model) { return; } - const minTime = this._model.timelineModel().minimumRecordTime() / millisecondsPerSecond; - const maxTime = this._model.timelineModel().maximumRecordTime() / millisecondsPerSecond; + const minTime = this.model.timelineModel().minimumRecordTime() / millisecondsPerSecond; + const maxTime = this.model.timelineModel().maximumRecordTime() / millisecondsPerSecond; const lineWidth = 1; const width = this.width(); @@ -801,7 +799,7 @@ ctx.lineTo(-lineWidth, height - yOffset); let previous: (number|null)|null = null; - for (const stamp of this._coverageModel.getCoverageUpdateTimes()) { + for (const stamp of this.coverageModel.getCoverageUpdateTimes()) { const coverage: number|null = coverageByTimestamp.get(stamp) || previous; previous = coverage; if (!coverage) { @@ -829,7 +827,7 @@ ctx.stroke(); previous = null; - for (const stamp of this._coverageModel.getCoverageUpdateTimes()) { + for (const stamp of this.coverageModel.getCoverageUpdateTimes()) { const coverage: number|null = coverageByTimestamp.get(stamp) || previous; previous = coverage; if (!coverage) { @@ -845,6 +843,6 @@ ctx.fill(); } - this._heapSizeLabel.textContent = `${percentUsed}% used`; + this.heapSizeLabel.textContent = `${percentUsed}% used`; } }
diff --git a/front_end/panels/timeline/TimelineFilters.ts b/front_end/panels/timeline/TimelineFilters.ts index 4a45a9b..c8e9d57 100644 --- a/front_end/panels/timeline/TimelineFilters.ts +++ b/front_end/panels/timeline/TimelineFilters.ts
@@ -2,27 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import type * as SDK from '../../core/sdk/sdk.js'; import * as TimelineModel from '../../models/timeline_model/timeline_model.js'; import {TimelineUIUtils} from './TimelineUIUtils.js'; export class IsLong extends TimelineModel.TimelineModelFilter.TimelineModelFilter { - _minimumRecordDuration: number; + private minimumRecordDuration: number; constructor() { super(); - this._minimumRecordDuration = 0; + this.minimumRecordDuration = 0; } setMinimumRecordDuration(value: number): void { - this._minimumRecordDuration = value; + this.minimumRecordDuration = value; } accept(event: SDK.TracingModel.Event): boolean { const duration = event.endTime ? event.endTime - event.startTime : 0; - return duration >= this._minimumRecordDuration; + return duration >= this.minimumRecordDuration; } } @@ -37,21 +35,21 @@ } export class TimelineRegExp extends TimelineModel.TimelineModelFilter.TimelineModelFilter { - _regExp!: RegExp|null; + private regExpInternal!: RegExp|null; constructor(regExp?: RegExp) { super(); this.setRegExp(regExp || null); } setRegExp(regExp: RegExp|null): void { - this._regExp = regExp; + this.regExpInternal = regExp; } regExp(): RegExp|null { - return this._regExp; + return this.regExpInternal; } accept(event: SDK.TracingModel.Event): boolean { - return !this._regExp || TimelineUIUtils.testContentMatching(event, this._regExp); + return !this.regExpInternal || TimelineUIUtils.testContentMatching(event, this.regExpInternal); } }
diff --git a/front_end/panels/timeline/TimelineFlameChartDataProvider.ts b/front_end/panels/timeline/TimelineFlameChartDataProvider.ts index a955d04..5f20afb 100644 --- a/front_end/panels/timeline/TimelineFlameChartDataProvider.ts +++ b/front_end/panels/timeline/TimelineFlameChartDataProvider.ts
@@ -28,8 +28,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as Host from '../../core/host/host.js'; import * as i18n from '../../core/i18n/i18n.js'; @@ -163,65 +161,65 @@ const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class TimelineFlameChartDataProvider extends Common.ObjectWrapper.ObjectWrapper implements PerfUI.FlameChart.FlameChartDataProvider { - _font: string; - _timelineData: PerfUI.FlameChart.TimelineData|null; - _currentLevel: number; - _performanceModel: PerformanceModel|null; - _model: TimelineModel.TimelineModel.TimelineModelImpl|null; - _minimumBoundary: number; - _maximumBoundary: number; - _timeSpan: number; - _consoleColorGenerator: Common.Color.Generator; - _extensionColorGenerator: Common.Color.Generator; - _headerLevel1: PerfUI.FlameChart.GroupStyle; - _headerLevel2: PerfUI.FlameChart.GroupStyle; - _staticHeader: PerfUI.FlameChart.GroupStyle; - _framesHeader: PerfUI.FlameChart.GroupStyle; - _collapsibleTimingsHeader: PerfUI.FlameChart.GroupStyle; - _timingsHeader: PerfUI.FlameChart.GroupStyle; - _screenshotsHeader: PerfUI.FlameChart.GroupStyle; - _interactionsHeaderLevel1: PerfUI.FlameChart.GroupStyle; - _interactionsHeaderLevel2: PerfUI.FlameChart.GroupStyle; - _experienceHeader: PerfUI.FlameChart.GroupStyle; - _flowEventIndexById: Map<string, number>; - _entryData!: (SDK.FilmStripModel.Frame|SDK.TracingModel.Event| - TimelineModel.TimelineFrameModel.TimelineFrame|TimelineModel.TimelineIRModel.Phases)[]; - _entryTypeByLevel!: EntryType[]; - _markers!: TimelineFlameChartMarker[]; - _asyncColorByInteractionPhase!: Map<TimelineModel.TimelineIRModel.Phases, string>; - _screenshotImageCache!: Map<SDK.FilmStripModel.Frame, HTMLImageElement|null>; - _extensionInfo!: { + private readonly font: string; + private timelineDataInternal: PerfUI.FlameChart.TimelineData|null; + private currentLevel: number; + private performanceModel: PerformanceModel|null; + private model: TimelineModel.TimelineModel.TimelineModelImpl|null; + private minimumBoundaryInternal: number; + private readonly maximumBoundary: number; + private timeSpan: number; + private readonly consoleColorGenerator: Common.Color.Generator; + private readonly extensionColorGenerator: Common.Color.Generator; + private readonly headerLevel1: PerfUI.FlameChart.GroupStyle; + private readonly headerLevel2: PerfUI.FlameChart.GroupStyle; + private readonly staticHeader: PerfUI.FlameChart.GroupStyle; + private framesHeader: PerfUI.FlameChart.GroupStyle; + private readonly collapsibleTimingsHeader: PerfUI.FlameChart.GroupStyle; + private readonly timingsHeader: PerfUI.FlameChart.GroupStyle; + private readonly screenshotsHeader: PerfUI.FlameChart.GroupStyle; + private readonly interactionsHeaderLevel1: PerfUI.FlameChart.GroupStyle; + private readonly interactionsHeaderLevel2: PerfUI.FlameChart.GroupStyle; + private readonly experienceHeader: PerfUI.FlameChart.GroupStyle; + private readonly flowEventIndexById: Map<string, number>; + private entryData!: (SDK.FilmStripModel.Frame|SDK.TracingModel.Event| + TimelineModel.TimelineFrameModel.TimelineFrame|TimelineModel.TimelineIRModel.Phases)[]; + private entryTypeByLevel!: EntryType[]; + private markers!: TimelineFlameChartMarker[]; + private asyncColorByInteractionPhase!: Map<TimelineModel.TimelineIRModel.Phases, string>; + private screenshotImageCache!: Map<SDK.FilmStripModel.Frame, HTMLImageElement|null>; + private extensionInfo!: { title: string, model: SDK.TracingModel.TracingModel, }[]; - _entryIndexToTitle!: string[]; - _asyncColorByCategory!: Map<TimelineCategory, string>; - _lastInitiatorEntry!: number; - _entryParent!: SDK.TracingModel.Event[]; - _frameGroup?: PerfUI.FlameChart.Group; - _lastSelection?: Selection; - _colorForEvent?: ((arg0: SDK.TracingModel.Event) => string); + private entryIndexToTitle!: string[]; + private asyncColorByCategory!: Map<TimelineCategory, string>; + private lastInitiatorEntry!: number; + private entryParent!: SDK.TracingModel.Event[]; + private frameGroup?: PerfUI.FlameChart.Group; + private lastSelection?: Selection; + private colorForEvent?: ((arg0: SDK.TracingModel.Event) => string); constructor() { super(); this.reset(); - this._font = '11px ' + Host.Platform.fontFamily(); - this._timelineData = null; - this._currentLevel = 0; - this._performanceModel = null; - this._model = null; - this._minimumBoundary = 0; - this._maximumBoundary = 0; - this._timeSpan = 0; + this.font = '11px ' + Host.Platform.fontFamily(); + this.timelineDataInternal = null; + this.currentLevel = 0; + this.performanceModel = null; + this.model = null; + this.minimumBoundaryInternal = 0; + this.maximumBoundary = 0; + this.timeSpan = 0; - this._consoleColorGenerator = new Common.Color.Generator( + this.consoleColorGenerator = new Common.Color.Generator( { min: 30, max: 55, count: undefined, }, {min: 70, max: 100, count: 6}, 50, 0.7); - this._extensionColorGenerator = new Common.Color.Generator( + this.extensionColorGenerator = new Common.Color.Generator( { min: 210, max: 300, @@ -229,24 +227,24 @@ }, {min: 70, max: 100, count: 6}, 70, 0.7); - this._headerLevel1 = this._buildGroupStyle({shareHeaderLine: false}); - this._headerLevel2 = this._buildGroupStyle({padding: 2, nestingLevel: 1, collapsible: false}); - this._staticHeader = this._buildGroupStyle({collapsible: false}); - this._framesHeader = this._buildGroupStyle({useFirstLineForOverview: true}); - this._collapsibleTimingsHeader = - this._buildGroupStyle({shareHeaderLine: true, useFirstLineForOverview: true, collapsible: true}); - this._timingsHeader = - this._buildGroupStyle({shareHeaderLine: true, useFirstLineForOverview: true, collapsible: false}); - this._screenshotsHeader = - this._buildGroupStyle({useFirstLineForOverview: true, nestingLevel: 1, collapsible: false, itemsHeight: 150}); - this._interactionsHeaderLevel1 = this._buildGroupStyle({useFirstLineForOverview: true}); - this._interactionsHeaderLevel2 = this._buildGroupStyle({padding: 2, nestingLevel: 1}); - this._experienceHeader = this._buildGroupStyle({collapsible: false}); + this.headerLevel1 = this.buildGroupStyle({shareHeaderLine: false}); + this.headerLevel2 = this.buildGroupStyle({padding: 2, nestingLevel: 1, collapsible: false}); + this.staticHeader = this.buildGroupStyle({collapsible: false}); + this.framesHeader = this.buildGroupStyle({useFirstLineForOverview: true}); + this.collapsibleTimingsHeader = + this.buildGroupStyle({shareHeaderLine: true, useFirstLineForOverview: true, collapsible: true}); + this.timingsHeader = + this.buildGroupStyle({shareHeaderLine: true, useFirstLineForOverview: true, collapsible: false}); + this.screenshotsHeader = + this.buildGroupStyle({useFirstLineForOverview: true, nestingLevel: 1, collapsible: false, itemsHeight: 150}); + this.interactionsHeaderLevel1 = this.buildGroupStyle({useFirstLineForOverview: true}); + this.interactionsHeaderLevel2 = this.buildGroupStyle({padding: 2, nestingLevel: 1}); + this.experienceHeader = this.buildGroupStyle({collapsible: false}); - this._flowEventIndexById = new Map(); + this.flowEventIndexById = new Map(); } - _buildGroupStyle(extra: Object): PerfUI.FlameChart.GroupStyle { + private buildGroupStyle(extra: Object): PerfUI.FlameChart.GroupStyle { const defaultGroupStyle = { padding: 4, height: 17, @@ -255,7 +253,7 @@ ThemeSupport.ThemeSupport.instance().patchColorText('#222', ThemeSupport.ThemeSupport.ColorUsage.Foreground), backgroundColor: ThemeSupport.ThemeSupport.instance().patchColorText('white', ThemeSupport.ThemeSupport.ColorUsage.Background), - font: this._font, + font: this.font, nestingLevel: 0, shareHeaderLine: true, }; @@ -265,8 +263,8 @@ setModel(performanceModel: PerformanceModel|null): void { this.reset(); - this._performanceModel = performanceModel; - this._model = performanceModel && performanceModel.timelineModel(); + this.performanceModel = performanceModel; + this.model = performanceModel && performanceModel.timelineModel(); } groupTrack(group: PerfUI.FlameChart.Group): TimelineModel.TimelineModel.Track|null { @@ -278,18 +276,18 @@ // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any navStartTimes(): Map<any, any> { - if (!this._model) { + if (!this.model) { return new Map(); } - return this._model.navStartTimes(); + return this.model.navStartTimes(); } entryTitle(entryIndex: number): string|null { const entryTypes = EntryType; - const entryType = this._entryType(entryIndex); + const entryType = this.entryType(entryIndex); if (entryType === entryTypes.Event) { - const event = (this._entryData[entryIndex] as SDK.TracingModel.Event); + const event = (this.entryData[entryIndex] as SDK.TracingModel.Event); if (event.phase === SDK.TracingModel.Phase.AsyncStepInto || event.phase === SDK.TracingModel.Phase.AsyncStepPast) { return event.name + ':' + event.args['step']; @@ -297,19 +295,19 @@ if (eventToDisallowRoot.get(event)) { return i18nString(UIStrings.onIgnoreList); } - if (this._performanceModel && this._performanceModel.timelineModel().isMarkerEvent(event)) { + if (this.performanceModel && this.performanceModel.timelineModel().isMarkerEvent(event)) { return TimelineUIUtils.markerShortTitle(event); } return TimelineUIUtils.eventTitle(event); } if (entryType === entryTypes.ExtensionEvent) { - const event = (this._entryData[entryIndex] as SDK.TracingModel.Event); + const event = (this.entryData[entryIndex] as SDK.TracingModel.Event); return event.name; } if (entryType === entryTypes.Screenshot) { return ''; } - let title: Common.UIString.LocalizedString|string = this._entryIndexToTitle[entryIndex]; + let title: Common.UIString.LocalizedString|string = this.entryIndexToTitle[entryIndex]; if (!title) { title = `Unexpected entryIndex ${entryIndex}`; console.error(title); @@ -318,66 +316,66 @@ } textColor(index: number): string { - const event = this._entryData[index]; + const event = this.entryData[index]; return event && eventToDisallowRoot.get((event as SDK.TracingModel.Event)) ? '#888' : FlameChartStyle.textColor; } entryFont(_index: number): string|null { - return this._font; + return this.font; } reset(): void { - this._currentLevel = 0; - this._timelineData = null; - this._entryData = []; - this._entryParent = []; - this._entryTypeByLevel = []; - this._entryIndexToTitle = []; - this._markers = []; - this._asyncColorByCategory = new Map(); - this._asyncColorByInteractionPhase = new Map(); - this._extensionInfo = []; - this._screenshotImageCache = new Map(); + this.currentLevel = 0; + this.timelineDataInternal = null; + this.entryData = []; + this.entryParent = []; + this.entryTypeByLevel = []; + this.entryIndexToTitle = []; + this.markers = []; + this.asyncColorByCategory = new Map(); + this.asyncColorByInteractionPhase = new Map(); + this.extensionInfo = []; + this.screenshotImageCache = new Map(); } maxStackDepth(): number { - return this._currentLevel; + return this.currentLevel; } timelineData(): PerfUI.FlameChart.TimelineData { - if (this._timelineData) { - return this._timelineData; + if (this.timelineDataInternal) { + return this.timelineDataInternal; } - this._timelineData = new PerfUI.FlameChart.TimelineData([], [], [], []); - if (!this._model) { - return this._timelineData; + this.timelineDataInternal = new PerfUI.FlameChart.TimelineData([], [], [], []); + if (!this.model) { + return this.timelineDataInternal; } - this._flowEventIndexById.clear(); - this._minimumBoundary = this._model.minimumRecordTime(); - this._timeSpan = this._model.isEmpty() ? 1000 : this._model.maximumRecordTime() - this._minimumBoundary; - this._currentLevel = 0; + this.flowEventIndexById.clear(); + this.minimumBoundaryInternal = this.model.minimumRecordTime(); + this.timeSpan = this.model.isEmpty() ? 1000 : this.model.maximumRecordTime() - this.minimumBoundaryInternal; + this.currentLevel = 0; - if (this._model.isGenericTrace()) { - this._processGenericTrace(); + if (this.model.isGenericTrace()) { + this.processGenericTrace(); } else { - this._processInspectorTrace(); + this.processInspectorTrace(); } - return this._timelineData; + return this.timelineDataInternal; } - _processGenericTrace(): void { - const processGroupStyle = this._buildGroupStyle({shareHeaderLine: false}); - const threadGroupStyle = this._buildGroupStyle({padding: 2, nestingLevel: 1, shareHeaderLine: false}); + private processGenericTrace(): void { + const processGroupStyle = this.buildGroupStyle({shareHeaderLine: false}); + const threadGroupStyle = this.buildGroupStyle({padding: 2, nestingLevel: 1, shareHeaderLine: false}); const eventEntryType = EntryType.Event; const tracksByProcess = new Platform.MapUtilities.Multimap<SDK.TracingModel.Process, TimelineModel.TimelineModel.Track>(); - if (!this._model) { + if (!this.model) { return; } - for (const track of this._model.tracks()) { + for (const track of this.model.tracks()) { if (track.thread !== null) { tracksByProcess.set(track.thread.process(), track); } else { @@ -388,23 +386,23 @@ for (const process of tracksByProcess.keysArray()) { if (tracksByProcess.size > 1) { const name = `${process.name()} ${process.id()}`; - this._appendHeader(name, processGroupStyle, false /* selectable */); + this.appendHeader(name, processGroupStyle, false /* selectable */); } for (const track of tracksByProcess.get(process)) { - const group = this._appendSyncEvents( + const group = this.appendSyncEvents( track, track.events, track.name, threadGroupStyle, eventEntryType, true /* selectable */); - if (this._timelineData && - (!this._timelineData.selectedGroup || + if (this.timelineDataInternal && + (!this.timelineDataInternal.selectedGroup || track.name === TimelineModel.TimelineModel.TimelineModelImpl.BrowserMainThreadName)) { - this._timelineData.selectedGroup = group; + this.timelineDataInternal.selectedGroup = group; } } } } - _processInspectorTrace(): void { - this._appendFrames(); - this._appendInteractionRecords(); + private processInspectorTrace(): void { + this.appendFrames(); + this.appendInteractionRecords(); const eventEntryType = EntryType.Event; @@ -435,138 +433,137 @@ } }; - if (!this._model) { + if (!this.model) { return; } - const tracks = this._model.tracks().slice(); + const tracks = this.model.tracks().slice(); tracks.sort((a, b) => weight(a) - weight(b)); let rasterCount = 0; for (const track of tracks) { switch (track.type) { case TimelineModel.TimelineModel.TrackType.Input: { - this._appendAsyncEventsGroup( - track, i18nString(UIStrings.input), track.asyncEvents, this._interactionsHeaderLevel2, eventEntryType, + this.appendAsyncEventsGroup( + track, i18nString(UIStrings.input), track.asyncEvents, this.interactionsHeaderLevel2, eventEntryType, false /* selectable */); break; } case TimelineModel.TimelineModel.TrackType.Animation: { - this._appendAsyncEventsGroup( - track, i18nString(UIStrings.animation), track.asyncEvents, this._interactionsHeaderLevel2, eventEntryType, + this.appendAsyncEventsGroup( + track, i18nString(UIStrings.animation), track.asyncEvents, this.interactionsHeaderLevel2, eventEntryType, false /* selectable */); break; } case TimelineModel.TimelineModel.TrackType.Timings: { - const style = track.asyncEvents.length > 0 ? this._collapsibleTimingsHeader : this._timingsHeader; - const group = this._appendHeader(i18nString(UIStrings.timings), style, true /* selectable */); + const style = track.asyncEvents.length > 0 ? this.collapsibleTimingsHeader : this.timingsHeader; + const group = this.appendHeader(i18nString(UIStrings.timings), style, true /* selectable */); group.track = track; - this._appendPageMetrics(); - this._copyPerfMarkEvents(track); - this._appendSyncEvents(track, track.events, null, null, eventEntryType, true /* selectable */); - this._appendAsyncEventsGroup(track, null, track.asyncEvents, null, eventEntryType, true /* selectable */); + this.appendPageMetrics(); + this.copyPerfMarkEvents(track); + this.appendSyncEvents(track, track.events, null, null, eventEntryType, true /* selectable */); + this.appendAsyncEventsGroup(track, null, track.asyncEvents, null, eventEntryType, true /* selectable */); break; } case TimelineModel.TimelineModel.TrackType.Console: { - this._appendAsyncEventsGroup( - track, i18nString(UIStrings.console), track.asyncEvents, this._headerLevel1, eventEntryType, + this.appendAsyncEventsGroup( + track, i18nString(UIStrings.console), track.asyncEvents, this.headerLevel1, eventEntryType, true /* selectable */); break; } case TimelineModel.TimelineModel.TrackType.MainThread: { if (track.forMainFrame) { - const group = this._appendSyncEvents( + const group = this.appendSyncEvents( track, track.events, track.url ? i18nString(UIStrings.mainS, {PH1: track.url}) : i18nString(UIStrings.main), - this._headerLevel1, eventEntryType, true /* selectable */); - if (group && this._timelineData) { - this._timelineData.selectedGroup = group; + this.headerLevel1, eventEntryType, true /* selectable */); + if (group && this.timelineDataInternal) { + this.timelineDataInternal.selectedGroup = group; } } else { - this._appendSyncEvents( + this.appendSyncEvents( track, track.events, track.url ? i18nString(UIStrings.frameS, {PH1: track.url}) : i18nString(UIStrings.subframe), - this._headerLevel1, eventEntryType, true /* selectable */); + this.headerLevel1, eventEntryType, true /* selectable */); } break; } case TimelineModel.TimelineModel.TrackType.Worker: { - this._appendSyncEvents( - track, track.events, track.name, this._headerLevel1, eventEntryType, true /* selectable */); + this.appendSyncEvents( + track, track.events, track.name, this.headerLevel1, eventEntryType, true /* selectable */); break; } case TimelineModel.TimelineModel.TrackType.Raster: { if (!rasterCount) { - this._appendHeader(i18nString(UIStrings.raster), this._headerLevel1, false /* selectable */); + this.appendHeader(i18nString(UIStrings.raster), this.headerLevel1, false /* selectable */); } ++rasterCount; - this._appendSyncEvents( - track, track.events, i18nString(UIStrings.rasterizerThreadS, {PH1: rasterCount}), this._headerLevel2, + this.appendSyncEvents( + track, track.events, i18nString(UIStrings.rasterizerThreadS, {PH1: rasterCount}), this.headerLevel2, eventEntryType, true /* selectable */); break; } case TimelineModel.TimelineModel.TrackType.GPU: { - this._appendSyncEvents( - track, track.events, i18nString(UIStrings.gpu), this._headerLevel1, eventEntryType, - true /* selectable */); + this.appendSyncEvents( + track, track.events, i18nString(UIStrings.gpu), this.headerLevel1, eventEntryType, true /* selectable */); break; } case TimelineModel.TimelineModel.TrackType.Other: { - this._appendSyncEvents( - track, track.events, track.name || i18nString(UIStrings.thread), this._headerLevel1, eventEntryType, + this.appendSyncEvents( + track, track.events, track.name || i18nString(UIStrings.thread), this.headerLevel1, eventEntryType, true /* selectable */); - this._appendAsyncEventsGroup( - track, track.name, track.asyncEvents, this._headerLevel1, eventEntryType, true /* selectable */); + this.appendAsyncEventsGroup( + track, track.name, track.asyncEvents, this.headerLevel1, eventEntryType, true /* selectable */); break; } case TimelineModel.TimelineModel.TrackType.Experience: { - this._appendSyncEvents( - track, track.events, i18nString(UIStrings.experience), this._experienceHeader, eventEntryType, + this.appendSyncEvents( + track, track.events, i18nString(UIStrings.experience), this.experienceHeader, eventEntryType, true /* selectable */); break; } } } - if (this._timelineData && this._timelineData.selectedGroup) { - this._timelineData.selectedGroup.expanded = true; + if (this.timelineDataInternal && this.timelineDataInternal.selectedGroup) { + this.timelineDataInternal.selectedGroup.expanded = true; } - for (let extensionIndex = 0; extensionIndex < this._extensionInfo.length; extensionIndex++) { - this._innerAppendExtensionEvents(extensionIndex); + for (let extensionIndex = 0; extensionIndex < this.extensionInfo.length; extensionIndex++) { + this.innerAppendExtensionEvents(extensionIndex); } - this._markers.sort((a, b) => a.startTime() - b.startTime()); - if (this._timelineData) { - this._timelineData.markers = this._markers; + this.markers.sort((a, b) => a.startTime() - b.startTime()); + if (this.timelineDataInternal) { + this.timelineDataInternal.markers = this.markers; } - this._flowEventIndexById.clear(); + this.flowEventIndexById.clear(); } minimumBoundary(): number { - return this._minimumBoundary; + return this.minimumBoundaryInternal; } totalTime(): number { - return this._timeSpan; + return this.timeSpan; } search(startTime: number, endTime: number, filter: TimelineModel.TimelineModelFilter.TimelineModelFilter): number[] { const result = []; const entryTypes = EntryType; this.timelineData(); - for (let i = 0; i < this._entryData.length; ++i) { - if (this._entryType(i) !== entryTypes.Event) { + for (let i = 0; i < this.entryData.length; ++i) { + if (this.entryType(i) !== entryTypes.Event) { continue; } - const event = (this._entryData[i] as SDK.TracingModel.Event); + const event = (this.entryData[i] as SDK.TracingModel.Event); if (event.startTime > endTime) { continue; } @@ -579,18 +576,18 @@ } result.sort( (a, b) => SDK.TracingModel.Event.compareStartTime( - (this._entryData[a] as SDK.TracingModel.Event), (this._entryData[b] as SDK.TracingModel.Event))); + (this.entryData[a] as SDK.TracingModel.Event), (this.entryData[b] as SDK.TracingModel.Event))); return result; } - _appendSyncEvents( + private appendSyncEvents( track: TimelineModel.TimelineModel.Track|null, events: SDK.TracingModel.Event[], title: string|null, style: PerfUI.FlameChart.GroupStyle|null, entryType: EntryType, selectable: boolean): PerfUI.FlameChart.Group |null { if (!events.length) { return null; } - if (!this._performanceModel || !this._model) { + if (!this.performanceModel || !this.model) { return null; } const isExtension = entryType === EntryType.ExtensionEvent; @@ -599,15 +596,15 @@ let maxStackDepth = 0; let group: PerfUI.FlameChart.Group|null = null; if (track && track.type === TimelineModel.TimelineModel.TrackType.MainThread) { - group = this._appendHeader((title as string), (style as PerfUI.FlameChart.GroupStyle), selectable); + group = this.appendHeader((title as string), (style as PerfUI.FlameChart.GroupStyle), selectable); group.track = track; } for (let i = 0; i < events.length; ++i) { const e = events[i]; // Skip Layout Shifts and TTI events when dealing with the main thread. - if (this._performanceModel) { - const isInteractiveTime = this._performanceModel.timelineModel().isInteractiveTimeEvent(e); - const isLayoutShift = this._performanceModel.timelineModel().isLayoutShiftEvent(e); + if (this.performanceModel) { + const isInteractiveTime = this.performanceModel.timelineModel().isInteractiveTimeEvent(e); + const isLayoutShift = this.performanceModel.timelineModel().isLayoutShiftEvent(e); const skippableEvent = isInteractiveTime || isLayoutShift; if (track && track.type === TimelineModel.TimelineModel.TrackType.MainThread && skippableEvent) { @@ -615,9 +612,9 @@ } } - if (this._performanceModel && this._performanceModel.timelineModel().isLayoutShiftEvent(e)) { + if (this.performanceModel && this.performanceModel.timelineModel().isLayoutShiftEvent(e)) { // Expand layout shift events to the size of the frame in which it is situated. - for (const frame of this._performanceModel.frames()) { + for (const frame of this.performanceModel.frames()) { // Locate the correct frame and expand the event accordingly. if (typeof e.endTime === 'undefined') { e.setEndTime(e.startTime); @@ -636,9 +633,9 @@ } } - if (!isExtension && this._performanceModel.timelineModel().isMarkerEvent(e)) { - this._markers.push(new TimelineFlameChartMarker( - e.startTime, e.startTime - this._model.minimumRecordTime(), TimelineUIUtils.markerStyleForEvent(e))); + if (!isExtension && this.performanceModel.timelineModel().isMarkerEvent(e)) { + this.markers.push(new TimelineFlameChartMarker( + e.startTime, e.startTime - this.model.minimumRecordTime(), TimelineUIUtils.markerStyleForEvent(e))); } if (!SDK.TracingModel.TracingModel.isFlowPhase(e.phase)) { if (!e.endTime && e.phase !== SDK.TracingModel.Phase.Instant) { @@ -647,7 +644,7 @@ if (SDK.TracingModel.TracingModel.isAsyncPhase(e.phase)) { continue; } - if (!isExtension && !this._performanceModel.isVisible(e)) { + if (!isExtension && !this.performanceModel.isVisible(e)) { continue; } } @@ -658,7 +655,7 @@ openEvents.pop(); } eventToDisallowRoot.set(e, false); - if (ignoreListingEnabled && this._isIgnoreListedEvent(e)) { + if (ignoreListingEnabled && this.isIgnoreListedEvent(e)) { const parent = openEvents[openEvents.length - 1]; if (parent && eventToDisallowRoot.get(parent)) { continue; @@ -666,20 +663,20 @@ eventToDisallowRoot.set(e, true); } if (!group && title) { - group = this._appendHeader(title, (style as PerfUI.FlameChart.GroupStyle), selectable); + group = this.appendHeader(title, (style as PerfUI.FlameChart.GroupStyle), selectable); if (selectable) { group.track = track; } } - const level = this._currentLevel + openEvents.length; - const index = this._appendEvent(e, level); + const level = this.currentLevel + openEvents.length; + const index = this.appendEvent(e, level); if (openEvents.length) { - this._entryParent[index] = (openEvents[openEvents.length - 1] as SDK.TracingModel.Event); + this.entryParent[index] = (openEvents[openEvents.length - 1] as SDK.TracingModel.Event); } - if (!isExtension && this._performanceModel.timelineModel().isMarkerEvent(e)) { + if (!isExtension && this.performanceModel.timelineModel().isMarkerEvent(e)) { // @ts-ignore This is invalid code, but we should keep it for now - this._timelineData.entryTotalTimes[this._entryData.length] = undefined; + this.timelineDataInternal.entryTotalTimes[this.entryData.length] = undefined; } maxStackDepth = Math.max(maxStackDepth, openEvents.length + 1); @@ -687,25 +684,25 @@ openEvents.push(e); } } - this._entryTypeByLevel.length = this._currentLevel + maxStackDepth; - this._entryTypeByLevel.fill(entryType, this._currentLevel); - this._currentLevel += maxStackDepth; + this.entryTypeByLevel.length = this.currentLevel + maxStackDepth; + this.entryTypeByLevel.fill(entryType, this.currentLevel); + this.currentLevel += maxStackDepth; return group; } - _isIgnoreListedEvent(event: SDK.TracingModel.Event): boolean { + private isIgnoreListedEvent(event: SDK.TracingModel.Event): boolean { if (event.name !== TimelineModel.TimelineModel.RecordType.JSFrame) { return false; } const url = event.args['data']['url']; - return url && this._isIgnoreListedURL(url); + return url && this.isIgnoreListedURL(url); } - _isIgnoreListedURL(url: string): boolean { + private isIgnoreListedURL(url: string): boolean { return Bindings.IgnoreListManager.IgnoreListManager.instance().isIgnoreListedURL(url); } - _appendAsyncEventsGroup( + private appendAsyncEventsGroup( track: TimelineModel.TimelineModel.Track|null, title: string|null, events: SDK.TracingModel.AsyncEvent[], style: PerfUI.FlameChart.GroupStyle|null, entryType: EntryType, selectable: boolean): PerfUI.FlameChart.Group |null { @@ -716,11 +713,11 @@ let group: PerfUI.FlameChart.Group|null = null; for (let i = 0; i < events.length; ++i) { const asyncEvent = events[i]; - if (!this._performanceModel || !this._performanceModel.isVisible(asyncEvent)) { + if (!this.performanceModel || !this.performanceModel.isVisible(asyncEvent)) { continue; } if (!group && title) { - group = this._appendHeader(title, (style as PerfUI.FlameChart.GroupStyle), selectable); + group = this.appendHeader(title, (style as PerfUI.FlameChart.GroupStyle), selectable); if (selectable) { group.track = track; } @@ -729,49 +726,49 @@ let level; for (level = 0; level < lastUsedTimeByLevel.length && lastUsedTimeByLevel[level] > startTime; ++level) { } - this._appendAsyncEvent(asyncEvent, this._currentLevel + level); + this.appendAsyncEvent(asyncEvent, this.currentLevel + level); lastUsedTimeByLevel[level] = (asyncEvent.endTime as number); } - this._entryTypeByLevel.length = this._currentLevel + lastUsedTimeByLevel.length; - this._entryTypeByLevel.fill(entryType, this._currentLevel); - this._currentLevel += lastUsedTimeByLevel.length; + this.entryTypeByLevel.length = this.currentLevel + lastUsedTimeByLevel.length; + this.entryTypeByLevel.fill(entryType, this.currentLevel); + this.currentLevel += lastUsedTimeByLevel.length; return group; } - _appendInteractionRecords(): void { - if (!this._performanceModel) { + private appendInteractionRecords(): void { + if (!this.performanceModel) { return; } - const interactionRecords = this._performanceModel.interactionRecords(); + const interactionRecords = this.performanceModel.interactionRecords(); if (!interactionRecords.length) { return; } - this._appendHeader(i18nString(UIStrings.interactions), this._interactionsHeaderLevel1, false /* selectable */); + this.appendHeader(i18nString(UIStrings.interactions), this.interactionsHeaderLevel1, false /* selectable */); for (const segment of interactionRecords) { - const index = this._entryData.length; - this._entryData.push((segment.data as TimelineModel.TimelineIRModel.Phases)); - this._entryIndexToTitle[index] = (segment.data as string); - if (this._timelineData) { - this._timelineData.entryLevels[index] = this._currentLevel; - this._timelineData.entryTotalTimes[index] = segment.end - segment.begin; - this._timelineData.entryStartTimes[index] = segment.begin; + const index = this.entryData.length; + this.entryData.push((segment.data as TimelineModel.TimelineIRModel.Phases)); + this.entryIndexToTitle[index] = (segment.data as string); + if (this.timelineDataInternal) { + this.timelineDataInternal.entryLevels[index] = this.currentLevel; + this.timelineDataInternal.entryTotalTimes[index] = segment.end - segment.begin; + this.timelineDataInternal.entryStartTimes[index] = segment.begin; } } - this._entryTypeByLevel[this._currentLevel++] = EntryType.InteractionRecord; + this.entryTypeByLevel[this.currentLevel++] = EntryType.InteractionRecord; } - _appendPageMetrics(): void { - this._entryTypeByLevel[this._currentLevel] = EntryType.Event; + private appendPageMetrics(): void { + this.entryTypeByLevel[this.currentLevel] = EntryType.Event; - if (!this._performanceModel || !this._model) { + if (!this.performanceModel || !this.model) { return; } const metricEvents: SDK.TracingModel.Event[] = []; const lcpEvents = []; const layoutShifts = []; - const timelineModel = this._performanceModel.timelineModel(); - for (const track of this._model.tracks()) { + const timelineModel = this.performanceModel.timelineModel(); + for (const track of this.model.tracks()) { for (const event of track.events) { if (timelineModel.isLayoutShiftEvent(event)) { layoutShifts.push(event); @@ -843,15 +840,15 @@ } metricEvents.sort(SDK.TracingModel.Event.compareStartTime); - if (this._timelineData) { - const totalTimes = this._timelineData.entryTotalTimes; + if (this.timelineDataInternal) { + const totalTimes = this.timelineDataInternal.entryTotalTimes; for (const event of metricEvents) { - this._appendEvent(event, this._currentLevel); + this.appendEvent(event, this.currentLevel); totalTimes[totalTimes.length - 1] = Number.NaN; } } - ++this._currentLevel; + ++this.currentLevel; } /** @@ -860,12 +857,12 @@ * Performance.mark() are a part of the "blink.user_timing" category alongside * Navigation and Resource Timing events, so we must filter them out before pushing. */ - _copyPerfMarkEvents(timingTrack: TimelineModel.TimelineModel.Track|null): void { - this._entryTypeByLevel[this._currentLevel] = EntryType.Event; - if (!this._performanceModel || !this._model || !timingTrack) { + private copyPerfMarkEvents(timingTrack: TimelineModel.TimelineModel.Track|null): void { + this.entryTypeByLevel[this.currentLevel] = EntryType.Event; + if (!this.performanceModel || !this.model || !timingTrack) { return; } - const timelineModel = this._performanceModel.timelineModel(); + const timelineModel = this.performanceModel.timelineModel(); const ResourceTimingNames = [ 'workerStart', 'redirectStart', @@ -904,7 +901,7 @@ 'loadEventEnd', ]; const IgnoreNames = [...ResourceTimingNames, ...NavTimingNames]; - for (const track of this._model.tracks()) { + for (const track of this.model.tracks()) { if (track.type === TimelineModel.TimelineModel.TrackType.MainThread) { for (const event of track.events) { if (timelineModel.isUserTimingEvent(event)) { @@ -921,53 +918,53 @@ } } - ++this._currentLevel; + ++this.currentLevel; } - _appendFrames(): void { - if (!this._performanceModel || !this._timelineData || !this._model) { + private appendFrames(): void { + if (!this.performanceModel || !this.timelineDataInternal || !this.model) { return; } - const screenshots = this._performanceModel.filmStripModel().frames(); + const screenshots = this.performanceModel.filmStripModel().frames(); const hasFilmStrip = Boolean(screenshots.length); - this._framesHeader.collapsible = hasFilmStrip; - this._appendHeader(i18nString(UIStrings.frames), this._framesHeader, false /* selectable */); - this._frameGroup = this._timelineData.groups[this._timelineData.groups.length - 1]; + this.framesHeader.collapsible = hasFilmStrip; + this.appendHeader(i18nString(UIStrings.frames), this.framesHeader, false /* selectable */); + this.frameGroup = this.timelineDataInternal.groups[this.timelineDataInternal.groups.length - 1]; const style = TimelineUIUtils.markerStyleForFrame(); - this._entryTypeByLevel[this._currentLevel] = EntryType.Frame; - for (const frame of this._performanceModel.frames()) { - this._markers.push( - new TimelineFlameChartMarker(frame.startTime, frame.startTime - this._model.minimumRecordTime(), style)); - this._appendFrame(frame); + this.entryTypeByLevel[this.currentLevel] = EntryType.Frame; + for (const frame of this.performanceModel.frames()) { + this.markers.push( + new TimelineFlameChartMarker(frame.startTime, frame.startTime - this.model.minimumRecordTime(), style)); + this.appendFrame(frame); } - ++this._currentLevel; + ++this.currentLevel; if (!hasFilmStrip) { return; } - this._appendHeader('', this._screenshotsHeader, false /* selectable */); - this._entryTypeByLevel[this._currentLevel] = EntryType.Screenshot; + this.appendHeader('', this.screenshotsHeader, false /* selectable */); + this.entryTypeByLevel[this.currentLevel] = EntryType.Screenshot; let prevTimestamp: number|undefined; for (const screenshot of screenshots) { - this._entryData.push(screenshot); - (this._timelineData.entryLevels as number[]).push(this._currentLevel); - (this._timelineData.entryStartTimes as number[]).push(screenshot.timestamp); + this.entryData.push(screenshot); + (this.timelineDataInternal.entryLevels as number[]).push(this.currentLevel); + (this.timelineDataInternal.entryStartTimes as number[]).push(screenshot.timestamp); if (prevTimestamp) { - (this._timelineData.entryTotalTimes as number[]).push(screenshot.timestamp - prevTimestamp); + (this.timelineDataInternal.entryTotalTimes as number[]).push(screenshot.timestamp - prevTimestamp); } prevTimestamp = screenshot.timestamp; } if (screenshots.length && prevTimestamp !== undefined) { - (this._timelineData.entryTotalTimes as number[]).push(this._model.maximumRecordTime() - prevTimestamp); + (this.timelineDataInternal.entryTotalTimes as number[]).push(this.model.maximumRecordTime() - prevTimestamp); } - ++this._currentLevel; + ++this.currentLevel; } - _entryType(entryIndex: number): EntryType { - return this._entryTypeByLevel[/** @type {!PerfUI.FlameChart.TimelineData} */ ( - this._timelineData as PerfUI.FlameChart.TimelineData) - .entryLevels[entryIndex]]; + private entryType(entryIndex: number): EntryType { + return this.entryTypeByLevel[/** @type {!PerfUI.FlameChart.TimelineData} */ ( + this.timelineDataInternal as PerfUI.FlameChart.TimelineData) + .entryLevels[entryIndex]]; } prepareHighlightedEntryInfo(entryIndex: number): Element|null { @@ -976,9 +973,9 @@ let warning; let nameSpanTimelineInfoTime = 'timeline-info-time'; - const type = this._entryType(entryIndex); + const type = this.entryType(entryIndex); if (type === EntryType.Event) { - const event = (this._entryData[entryIndex] as SDK.TracingModel.Event); + const event = (this.entryData[entryIndex] as SDK.TracingModel.Event); const totalTime = event.duration; const selfTime = event.selfTime; const eps = 1e-6; @@ -990,20 +987,20 @@ }) : i18n.TimeUtilities.millisToString(totalTime, true); } - if (this._performanceModel && this._performanceModel.timelineModel().isMarkerEvent(event)) { + if (this.performanceModel && this.performanceModel.timelineModel().isMarkerEvent(event)) { title = TimelineUIUtils.eventTitle(event); } else { title = this.entryTitle(entryIndex); } warning = TimelineUIUtils.eventWarning(event); - if (this._model && this._model.isLayoutShiftEvent(event)) { + if (this.model && this.model.isLayoutShiftEvent(event)) { // TODO: Update this to be dynamic when the trace data supports it. const occurrences = 1; time = i18nString(UIStrings.occurrencesS, {PH1: occurrences}); } - if (this._model && this._model.isParseHTMLEvent(event)) { + if (this.model && this.model.isParseHTMLEvent(event)) { const startLine = event.args['beginData']['startLine']; const endLine = event.args['endData'] && event.args['endData']['endLine']; const url = Bindings.ResourceUtils.displayNameForURL(event.args['beginData']['url']); @@ -1012,7 +1009,7 @@ } } else if (type === EntryType.Frame) { - const frame = (this._entryData[entryIndex] as TimelineModel.TimelineFrameModel.TimelineFrame); + const frame = (this.entryData[entryIndex] as TimelineModel.TimelineFrameModel.TimelineFrame); time = i18nString( UIStrings.sFfps, {PH1: i18n.TimeUtilities.preciseMillisToString(frame.duration, 1), PH2: (1000 / frame.duration).toFixed(0)}); @@ -1064,34 +1061,34 @@ return color; } - if (!this._performanceModel || !this._model) { + if (!this.performanceModel || !this.model) { return ''; } const entryTypes = EntryType; - const type = this._entryType(entryIndex); + const type = this.entryType(entryIndex); if (type === entryTypes.Event) { - const event = (this._entryData[entryIndex] as SDK.TracingModel.Event); - if (this._model.isGenericTrace()) { - return this._genericTraceEventColor(event); + const event = (this.entryData[entryIndex] as SDK.TracingModel.Event); + if (this.model.isGenericTrace()) { + return this.genericTraceEventColor(event); } - if (this._performanceModel.timelineModel().isMarkerEvent(event)) { + if (this.performanceModel.timelineModel().isMarkerEvent(event)) { return TimelineUIUtils.markerStyleForEvent(event).color; } - if (!SDK.TracingModel.TracingModel.isAsyncPhase(event.phase) && this._colorForEvent) { - return this._colorForEvent(event); + if (!SDK.TracingModel.TracingModel.isAsyncPhase(event.phase) && this.colorForEvent) { + return this.colorForEvent(event); } if (event.hasCategory(TimelineModel.TimelineModel.TimelineModelImpl.Category.Console) || event.hasCategory(TimelineModel.TimelineModel.TimelineModelImpl.Category.UserTiming)) { - return this._consoleColorGenerator.colorForID(event.name); + return this.consoleColorGenerator.colorForID(event.name); } if (event.hasCategory(TimelineModel.TimelineModel.TimelineModelImpl.Category.LatencyInfo)) { const phase = TimelineModel.TimelineIRModel.TimelineIRModel.phaseForEvent(event) || TimelineModel.TimelineIRModel.Phases.Uncategorized; - return patchColorAndCache(this._asyncColorByInteractionPhase, phase, TimelineUIUtils.interactionPhaseColor); + return patchColorAndCache(this.asyncColorByInteractionPhase, phase, TimelineUIUtils.interactionPhaseColor); } const category = TimelineUIUtils.eventStyle(event).category; - return patchColorAndCache(this._asyncColorByCategory, category, () => category.color); + return patchColorAndCache(this.asyncColorByCategory, category, () => category.color); } if (type === entryTypes.Frame) { return 'white'; @@ -1100,22 +1097,22 @@ return 'transparent'; } if (type === entryTypes.ExtensionEvent) { - const event = (this._entryData[entryIndex] as SDK.TracingModel.Event); - return this._extensionColorGenerator.colorForID(event.name); + const event = (this.entryData[entryIndex] as SDK.TracingModel.Event); + return this.extensionColorGenerator.colorForID(event.name); } return ''; } - _genericTraceEventColor(event: SDK.TracingModel.Event): string { + private genericTraceEventColor(event: SDK.TracingModel.Event): string { const key = event.categoriesString || event.name; return key ? `hsl(${Platform.StringUtilities.hashCode(key) % 300 + 30}, 40%, 70%)` : '#ccc'; } - _drawFrame( + private drawFrame( entryIndex: number, context: CanvasRenderingContext2D, text: string|null, barX: number, barY: number, barWidth: number, barHeight: number): void { const hPadding = 1; - const frame = (this._entryData[entryIndex] as TimelineModel.TimelineFrameModel.TimelineFrame); + const frame = (this.entryData[entryIndex] as TimelineModel.TimelineFrameModel.TimelineFrame); barX += hPadding; barWidth -= 2 * hPadding; context.fillStyle = @@ -1130,20 +1127,20 @@ } } - async _drawScreenshot( + private async drawScreenshot( entryIndex: number, context: CanvasRenderingContext2D, barX: number, barY: number, barWidth: number, barHeight: number): Promise<void> { - const screenshot = (this._entryData[entryIndex] as SDK.FilmStripModel.Frame); - if (!this._screenshotImageCache.has(screenshot)) { - this._screenshotImageCache.set(screenshot, null); + const screenshot = (this.entryData[entryIndex] as SDK.FilmStripModel.Frame); + if (!this.screenshotImageCache.has(screenshot)) { + this.screenshotImageCache.set(screenshot, null); const data = await screenshot.imageDataPromise(); const image = await UI.UIUtils.loadImageFromData(data); - this._screenshotImageCache.set(screenshot, image); + this.screenshotImageCache.set(screenshot, image); this.dispatchEventToListeners(Events.DataChanged); return; } - const image = this._screenshotImageCache.get(screenshot); + const image = this.screenshotImageCache.get(screenshot); if (!image) { return; } @@ -1165,17 +1162,17 @@ decorateEntry( entryIndex: number, context: CanvasRenderingContext2D, text: string|null, barX: number, barY: number, barWidth: number, barHeight: number, unclippedBarX: number, timeToPixels: number): boolean { - const data = this._entryData[entryIndex]; - const type = this._entryType(entryIndex); + const data = this.entryData[entryIndex]; + const type = this.entryType(entryIndex); const entryTypes = EntryType; if (type === entryTypes.Frame) { - this._drawFrame(entryIndex, context, text, barX, barY, barWidth, barHeight); + this.drawFrame(entryIndex, context, text, barX, barY, barWidth, barHeight); return true; } if (type === entryTypes.Screenshot) { - this._drawScreenshot(entryIndex, context, barX, barY, barWidth, barHeight); + this.drawScreenshot(entryIndex, context, barX, barY, barWidth, barHeight); return true; } @@ -1224,7 +1221,7 @@ forceDecoration(entryIndex: number): boolean { const entryTypes = EntryType; - const type = this._entryType(entryIndex); + const type = this.entryType(entryIndex); if (type === entryTypes.Frame) { return true; } @@ -1233,7 +1230,7 @@ } if (type === entryTypes.Event) { - const event = (this._entryData[entryIndex] as SDK.TracingModel.Event); + const event = (this.entryData[entryIndex] as SDK.TracingModel.Event); return Boolean(TimelineModel.TimelineModel.TimelineData.forEvent(event).warning); } return false; @@ -1243,14 +1240,14 @@ title: string, model: SDK.TracingModel.TracingModel, }): void { - this._extensionInfo.push(entry); - if (this._timelineData) { - this._innerAppendExtensionEvents(this._extensionInfo.length - 1); + this.extensionInfo.push(entry); + if (this.timelineDataInternal) { + this.innerAppendExtensionEvents(this.extensionInfo.length - 1); } } - _innerAppendExtensionEvents(index: number): void { - const entry = this._extensionInfo[index]; + private innerAppendExtensionEvents(index: number): void { + const entry = this.extensionInfo[index]; const entryType = EntryType.ExtensionEvent; const allThreads = [...entry.model.sortedProcesses().map(process => process.sortedThreads())].flat(); if (!allThreads.length) { @@ -1260,29 +1257,29 @@ const singleTrack = allThreads.length === 1 && (!allThreads[0].events().length || !allThreads[0].asyncEvents().length); if (!singleTrack) { - this._appendHeader(entry.title, this._headerLevel1, false /* selectable */); + this.appendHeader(entry.title, this.headerLevel1, false /* selectable */); } - const style = singleTrack ? this._headerLevel2 : this._headerLevel1; + const style = singleTrack ? this.headerLevel2 : this.headerLevel1; let threadIndex = 0; for (const thread of allThreads) { const title = singleTrack ? entry.title : thread.name() || i18nString(UIStrings.threadS, {PH1: ++threadIndex}); - this._appendAsyncEventsGroup(null, title, thread.asyncEvents(), style, entryType, false /* selectable */); - this._appendSyncEvents(null, thread.events(), title, style, entryType, false /* selectable */); + this.appendAsyncEventsGroup(null, title, thread.asyncEvents(), style, entryType, false /* selectable */); + this.appendSyncEvents(null, thread.events(), title, style, entryType, false /* selectable */); } } - _appendHeader(title: string, style: PerfUI.FlameChart.GroupStyle, selectable: boolean): PerfUI.FlameChart.Group { + private appendHeader(title: string, style: PerfUI.FlameChart.GroupStyle, selectable: boolean): + PerfUI.FlameChart.Group { const group = - ({startLevel: this._currentLevel, name: title, style: style, selectable: selectable} as - PerfUI.FlameChart.Group); - (this._timelineData as PerfUI.FlameChart.TimelineData).groups.push(group); + ({startLevel: this.currentLevel, name: title, style: style, selectable: selectable} as PerfUI.FlameChart.Group); + (this.timelineDataInternal as PerfUI.FlameChart.TimelineData).groups.push(group); return group; } - _appendEvent(event: SDK.TracingModel.Event, level: number): number { - const index = this._entryData.length; - this._entryData.push(event); - const timelineData = (this._timelineData as PerfUI.FlameChart.TimelineData); + private appendEvent(event: SDK.TracingModel.Event, level: number): number { + const index = this.entryData.length; + this.entryData.push(event); + const timelineData = (this.timelineDataInternal as PerfUI.FlameChart.TimelineData); timelineData.entryLevels[index] = level; timelineData.entryTotalTimes[index] = event.duration || InstantEventVisibleDurationMs; timelineData.entryStartTimes[index] = event.startTime; @@ -1290,49 +1287,49 @@ return index; } - _appendAsyncEvent(asyncEvent: SDK.TracingModel.AsyncEvent, level: number): void { + private appendAsyncEvent(asyncEvent: SDK.TracingModel.AsyncEvent, level: number): void { if (SDK.TracingModel.TracingModel.isNestableAsyncPhase(asyncEvent.phase)) { // FIXME: also add steps once we support event nesting in the FlameChart. - this._appendEvent(asyncEvent, level); + this.appendEvent(asyncEvent, level); return; } const steps = asyncEvent.steps; // If we have past steps, put the end event for each range rather than start one. const eventOffset = steps.length > 1 && steps[1].phase === SDK.TracingModel.Phase.AsyncStepPast ? 1 : 0; for (let i = 0; i < steps.length - 1; ++i) { - const index = this._entryData.length; - this._entryData.push(steps[i + eventOffset]); + const index = this.entryData.length; + this.entryData.push(steps[i + eventOffset]); const startTime = steps[i].startTime; - const timelineData = (this._timelineData as PerfUI.FlameChart.TimelineData); + const timelineData = (this.timelineDataInternal as PerfUI.FlameChart.TimelineData); timelineData.entryLevels[index] = level; timelineData.entryTotalTimes[index] = steps[i + 1].startTime - startTime; timelineData.entryStartTimes[index] = startTime; } } - _appendFrame(frame: TimelineModel.TimelineFrameModel.TimelineFrame): void { - const index = this._entryData.length; - this._entryData.push(frame); - this._entryIndexToTitle[index] = i18n.TimeUtilities.millisToString(frame.duration, true); - if (!this._timelineData) { + private appendFrame(frame: TimelineModel.TimelineFrameModel.TimelineFrame): void { + const index = this.entryData.length; + this.entryData.push(frame); + this.entryIndexToTitle[index] = i18n.TimeUtilities.millisToString(frame.duration, true); + if (!this.timelineDataInternal) { return; } - this._timelineData.entryLevels[index] = this._currentLevel; - this._timelineData.entryTotalTimes[index] = frame.duration; - this._timelineData.entryStartTimes[index] = frame.startTime; + this.timelineDataInternal.entryLevels[index] = this.currentLevel; + this.timelineDataInternal.entryTotalTimes[index] = frame.duration; + this.timelineDataInternal.entryStartTimes[index] = frame.startTime; } createSelection(entryIndex: number): TimelineSelection|null { - const type = this._entryType(entryIndex); + const type = this.entryType(entryIndex); let timelineSelection: TimelineSelection|null = null; if (type === EntryType.Event) { - timelineSelection = TimelineSelection.fromTraceEvent((this._entryData[entryIndex] as SDK.TracingModel.Event)); + timelineSelection = TimelineSelection.fromTraceEvent((this.entryData[entryIndex] as SDK.TracingModel.Event)); } else if (type === EntryType.Frame) { timelineSelection = - TimelineSelection.fromFrame((this._entryData[entryIndex] as TimelineModel.TimelineFrameModel.TimelineFrame)); + TimelineSelection.fromFrame((this.entryData[entryIndex] as TimelineModel.TimelineFrameModel.TimelineFrame)); } if (timelineSelection) { - this._lastSelection = new Selection(timelineSelection, entryIndex); + this.lastSelection = new Selection(timelineSelection, entryIndex); } return timelineSelection; } @@ -1350,25 +1347,25 @@ return -1; } - if (this._lastSelection && this._lastSelection.timelineSelection.object() === selection.object()) { - return this._lastSelection.entryIndex; + if (this.lastSelection && this.lastSelection.timelineSelection.object() === selection.object()) { + return this.lastSelection.entryIndex; } - const index = this._entryData.indexOf( + const index = this.entryData.indexOf( (selection.object() as SDK.TracingModel.Event | TimelineModel.TimelineIRModel.Phases | TimelineModel.TimelineFrameModel.TimelineFrame)); if (index !== -1) { - this._lastSelection = new Selection(selection, index); + this.lastSelection = new Selection(selection, index); } return index; } buildFlowForInitiator(entryIndex: number): boolean { - if (this._lastInitiatorEntry === entryIndex) { + if (this.lastInitiatorEntry === entryIndex) { return false; } - this._lastInitiatorEntry = entryIndex; + this.lastInitiatorEntry = entryIndex; let event = this.eventByIndex(entryIndex); - const td = this._timelineData; + const td = this.timelineDataInternal; if (!td) { return false; } @@ -1379,7 +1376,7 @@ while (event) { // Find the closest ancestor with an initiator. let initiator; - for (; event; event = this._eventParent(event)) { + for (; event; event = this.eventParent(event)) { initiator = TimelineModel.TimelineModel.TimelineData.forEvent(event).initiator(); if (initiator) { break; @@ -1399,22 +1396,22 @@ return true; } - _eventParent(event: SDK.TracingModel.Event): SDK.TracingModel.Event|null { + private eventParent(event: SDK.TracingModel.Event): SDK.TracingModel.Event|null { const eventIndex = indexForEvent.get(event); if (eventIndex === undefined) { return null; } - return this._entryParent[eventIndex] || null; + return this.entryParent[eventIndex] || null; } eventByIndex(entryIndex: number): SDK.TracingModel.Event|null { - return entryIndex >= 0 && this._entryType(entryIndex) === EntryType.Event ? - this._entryData[entryIndex] as SDK.TracingModel.Event : + return entryIndex >= 0 && this.entryType(entryIndex) === EntryType.Event ? + this.entryData[entryIndex] as SDK.TracingModel.Event : null; } setEventColorMapping(colorForEvent: (arg0: SDK.TracingModel.Event) => string): void { - this._colorForEvent = colorForEvent; + this.colorForEvent = colorForEvent; } }
diff --git a/front_end/panels/timeline/TimelineFlameChartNetworkDataProvider.ts b/front_end/panels/timeline/TimelineFlameChartNetworkDataProvider.ts index f6f220b..be0a183 100644 --- a/front_end/panels/timeline/TimelineFlameChartNetworkDataProvider.ts +++ b/front_end/panels/timeline/TimelineFlameChartNetworkDataProvider.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as Host from '../../core/host/host.js'; import * as i18n from '../../core/i18n/i18n.js'; @@ -28,8 +26,8 @@ const str_ = i18n.i18n.registerUIStrings('panels/timeline/TimelineFlameChartNetworkDataProvider.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class TimelineFlameChartNetworkDataProvider implements PerfUI.FlameChart.FlameChartDataProvider { - _font: string; - _style: { + private readonly font: string; + private readonly style: { padding: number, height: number, collapsible: boolean, @@ -41,30 +39,30 @@ useDecoratorsForOverview: boolean, shareHeaderLine: boolean, }; - _group: PerfUI.FlameChart.Group; - _minimumBoundary: number; - _maximumBoundary: number; - _timeSpan: number; - _requests: TimelineModel.TimelineModel.NetworkRequest[]; - _maxLevel: number; - _model?: TimelineModel.TimelineModel.TimelineModelImpl|null; + private group: PerfUI.FlameChart.Group; + private minimumBoundaryInternal: number; + private maximumBoundary: number; + private timeSpan: number; + private requests: TimelineModel.TimelineModel.NetworkRequest[]; + private maxLevel: number; + private model?: TimelineModel.TimelineModel.TimelineModelImpl|null; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _timelineData?: any; - _startTime?: number; - _endTime?: number; - _lastSelection?: Selection; - _priorityToValue?: Map<string, number>; + private timelineDataInternal?: any; + private startTime?: number; + private endTime?: number; + private lastSelection?: Selection; + private priorityToValue?: Map<string, number>; constructor() { - this._font = '11px ' + Host.Platform.fontFamily(); + this.font = '11px ' + Host.Platform.fontFamily(); this.setModel(null); - this._style = { + this.style = { padding: 4, height: 17, collapsible: true, color: ThemeSupport.ThemeSupport.instance().patchColorText('#222', ThemeSupport.ThemeSupport.ColorUsage.Foreground), - font: this._font, + font: this.font, backgroundColor: ThemeSupport.ThemeSupport.instance().patchColorText('white', ThemeSupport.ThemeSupport.ColorUsage.Background), nestingLevel: 0, @@ -72,64 +70,64 @@ useDecoratorsForOverview: true, shareHeaderLine: false, }; - this._group = - ({startLevel: 0, name: i18nString(UIStrings.network), expanded: false, style: this._style} as + this.group = + ({startLevel: 0, name: i18nString(UIStrings.network), expanded: false, style: this.style} as PerfUI.FlameChart.Group); - this._minimumBoundary = 0; - this._maximumBoundary = 0; - this._timeSpan = 0; - this._requests = []; - this._maxLevel = 0; + this.minimumBoundaryInternal = 0; + this.maximumBoundary = 0; + this.timeSpan = 0; + this.requests = []; + this.maxLevel = 0; } setModel(performanceModel: PerformanceModel|null): void { - this._model = performanceModel && performanceModel.timelineModel(); - this._timelineData = null; + this.model = performanceModel && performanceModel.timelineModel(); + this.timelineDataInternal = null; } isEmpty(): boolean { this.timelineData(); - return !this._requests.length; + return !this.requests.length; } maxStackDepth(): number { - return this._maxLevel; + return this.maxLevel; } timelineData(): PerfUI.FlameChart.TimelineData { - if (this._timelineData) { - return this._timelineData; + if (this.timelineDataInternal) { + return this.timelineDataInternal; } /** @type {!Array<!TimelineModel.TimelineModel.NetworkRequest>} */ - this._requests = []; - this._timelineData = new PerfUI.FlameChart.TimelineData([], [], [], []); - if (this._model) { - this._appendTimelineData(); + this.requests = []; + this.timelineDataInternal = new PerfUI.FlameChart.TimelineData([], [], [], []); + if (this.model) { + this.appendTimelineData(); } - return this._timelineData; + return this.timelineDataInternal; } minimumBoundary(): number { - return this._minimumBoundary; + return this.minimumBoundaryInternal; } totalTime(): number { - return this._timeSpan; + return this.timeSpan; } setWindowTimes(startTime: number, endTime: number): void { - this._startTime = startTime; - this._endTime = endTime; - this._updateTimelineData(); + this.startTime = startTime; + this.endTime = endTime; + this.updateTimelineData(); } createSelection(index: number): TimelineSelection|null { if (index === -1) { return null; } - const request = this._requests[index]; - this._lastSelection = new Selection(TimelineSelection.fromNetworkRequest(request), index); - return this._lastSelection.timelineSelection; + const request = this.requests[index]; + this.lastSelection = new Selection(TimelineSelection.fromNetworkRequest(request), index); + return this.lastSelection.timelineSelection; } entryIndexForSelection(selection: TimelineSelection|null): number { @@ -137,23 +135,23 @@ return -1; } - if (this._lastSelection && this._lastSelection.timelineSelection.object() === selection.object()) { - return this._lastSelection.entryIndex; + if (this.lastSelection && this.lastSelection.timelineSelection.object() === selection.object()) { + return this.lastSelection.entryIndex; } if (selection.type() !== TimelineSelection.Type.NetworkRequest) { return -1; } const request = (selection.object() as TimelineModel.TimelineModel.NetworkRequest); - const index = this._requests.indexOf(request); + const index = this.requests.indexOf(request); if (index !== -1) { - this._lastSelection = new Selection(TimelineSelection.fromNetworkRequest(request), index); + this.lastSelection = new Selection(TimelineSelection.fromNetworkRequest(request), index); } return index; } entryColor(index: number): string { - const request = (this._requests[index] as TimelineModel.TimelineModel.NetworkRequest); + const request = (this.requests[index] as TimelineModel.TimelineModel.NetworkRequest); const category = TimelineUIUtils.networkRequestCategory(request); return TimelineUIUtils.networkCategoryColor(category); } @@ -163,19 +161,19 @@ } entryTitle(index: number): string|null { - const request = (this._requests[index] as TimelineModel.TimelineModel.NetworkRequest); + const request = (this.requests[index] as TimelineModel.TimelineModel.NetworkRequest); const parsedURL = new Common.ParsedURL.ParsedURL(request.url || ''); return parsedURL.isValid ? `${parsedURL.displayName} (${parsedURL.host})` : request.url || null; } entryFont(_index: number): string|null { - return this._font; + return this.font; } decorateEntry( index: number, context: CanvasRenderingContext2D, text: string|null, barX: number, barY: number, barWidth: number, barHeight: number, unclippedBarX: number, timeToPixelRatio: number): boolean { - const request = (this._requests[index] as TimelineModel.TimelineModel.NetworkRequest); + const request = (this.requests[index] as TimelineModel.TimelineModel.NetworkRequest); if (!request.timing) { return false; } @@ -253,7 +251,7 @@ context.stroke(); if (typeof request.priority === 'string') { - const color = this._colorForPriority(request.priority); + const color = this.colorForPriority(request.priority); if (color) { context.fillStyle = color; context.fillRect(sendStart + 0.5, barY + 0.5, 3.5, 3.5); @@ -287,7 +285,7 @@ prepareHighlightedEntryInfo(index: number): Element|null { const /** @const */ maxURLChars = 80; - const request = (this._requests[index] as TimelineModel.TimelineModel.NetworkRequest); + const request = (this.requests[index] as TimelineModel.TimelineModel.NetworkRequest); if (!request.url) { return null; } @@ -307,15 +305,15 @@ const div = (contents.createChild('span') as HTMLElement); div.textContent = PerfUI.NetworkPriorities.uiLabelForNetworkPriority((request.priority as Protocol.Network.ResourcePriority)); - div.style.color = this._colorForPriority(request.priority) || 'black'; + div.style.color = this.colorForPriority(request.priority) || 'black'; } contents.createChild('span').textContent = Platform.StringUtilities.trimMiddle(request.url, maxURLChars); return element; } - _colorForPriority(priority: string): string|null { - if (!this._priorityToValue) { - this._priorityToValue = new Map([ + private colorForPriority(priority: string): string|null { + if (!this.priorityToValue) { + this.priorityToValue = new Map([ [Protocol.Network.ResourcePriority.VeryLow, 1], [Protocol.Network.ResourcePriority.Low, 2], [Protocol.Network.ResourcePriority.Medium, 3], @@ -323,67 +321,67 @@ [Protocol.Network.ResourcePriority.VeryHigh, 5], ]); } - const value = this._priorityToValue.get(priority); + const value = this.priorityToValue.get(priority); return value ? `hsla(214, 80%, 50%, ${value / 5})` : null; } - _appendTimelineData(): void { - if (this._model) { - this._minimumBoundary = this._model.minimumRecordTime(); - this._maximumBoundary = this._model.maximumRecordTime(); - this._timeSpan = this._model.isEmpty() ? 1000 : this._maximumBoundary - this._minimumBoundary; - this._model.networkRequests().forEach(this._appendEntry.bind(this)); - this._updateTimelineData(); + private appendTimelineData(): void { + if (this.model) { + this.minimumBoundaryInternal = this.model.minimumRecordTime(); + this.maximumBoundary = this.model.maximumRecordTime(); + this.timeSpan = this.model.isEmpty() ? 1000 : this.maximumBoundary - this.minimumBoundaryInternal; + this.model.networkRequests().forEach(this.appendEntry.bind(this)); + this.updateTimelineData(); } } - _updateTimelineData(): void { - if (!this._timelineData) { + private updateTimelineData(): void { + if (!this.timelineDataInternal) { return; } const lastTimeByLevel = []; let maxLevel = 0; - for (let i = 0; i < this._requests.length; ++i) { - const r = this._requests[i]; + for (let i = 0; i < this.requests.length; ++i) { + const r = this.requests[i]; const beginTime = r.beginTime(); - const startTime = (this._startTime as number); - const endTime = (this._endTime as number); + const startTime = (this.startTime as number); + const endTime = (this.endTime as number); const visible = beginTime < endTime && r.endTime > startTime; if (!visible) { - this._timelineData.entryLevels[i] = -1; + this.timelineDataInternal.entryLevels[i] = -1; continue; } while (lastTimeByLevel.length && lastTimeByLevel[lastTimeByLevel.length - 1] <= beginTime) { lastTimeByLevel.pop(); } - this._timelineData.entryLevels[i] = lastTimeByLevel.length; + this.timelineDataInternal.entryLevels[i] = lastTimeByLevel.length; lastTimeByLevel.push(r.endTime); maxLevel = Math.max(maxLevel, lastTimeByLevel.length); } - for (let i = 0; i < this._requests.length; ++i) { - if (this._timelineData.entryLevels[i] === -1) { - this._timelineData.entryLevels[i] = maxLevel; + for (let i = 0; i < this.requests.length; ++i) { + if (this.timelineDataInternal.entryLevels[i] === -1) { + this.timelineDataInternal.entryLevels[i] = maxLevel; } } - this._timelineData = new PerfUI.FlameChart.TimelineData( - this._timelineData.entryLevels, this._timelineData.entryTotalTimes, this._timelineData.entryStartTimes, - [this._group]); - this._maxLevel = maxLevel; + this.timelineDataInternal = new PerfUI.FlameChart.TimelineData( + this.timelineDataInternal.entryLevels, this.timelineDataInternal.entryTotalTimes, + this.timelineDataInternal.entryStartTimes, [this.group]); + this.maxLevel = maxLevel; } - _appendEntry(request: TimelineModel.TimelineModel.NetworkRequest): void { - this._requests.push(request); - this._timelineData.entryStartTimes.push(request.beginTime()); - this._timelineData.entryTotalTimes.push(request.endTime - request.beginTime()); - this._timelineData.entryLevels.push(this._requests.length - 1); + private appendEntry(request: TimelineModel.TimelineModel.NetworkRequest): void { + this.requests.push(request); + this.timelineDataInternal.entryStartTimes.push(request.beginTime()); + this.timelineDataInternal.entryTotalTimes.push(request.endTime - request.beginTime()); + this.timelineDataInternal.entryLevels.push(this.requests.length - 1); } preferredHeight(): number { - return this._style.height * (this._group.expanded ? Platform.NumberUtilities.clamp(this._maxLevel + 1, 4, 8.5) : 1); + return this.style.height * (this.group.expanded ? Platform.NumberUtilities.clamp(this.maxLevel + 1, 4, 8.5) : 1); } isExpanded(): boolean { - return this._group && Boolean(this._group.expanded); + return this.group && Boolean(this.group.expanded); } formatValue(value: number, precision?: number): string { @@ -399,10 +397,10 @@ // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any navStartTimes(): Map<any, any> { - if (!this._model) { + if (!this.model) { return new Map(); } - return this._model.navStartTimes(); + return this.model.navStartTimes(); } }
diff --git a/front_end/panels/timeline/TimelineFlameChartView.ts b/front_end/panels/timeline/TimelineFlameChartView.ts index 6b5d157..aab3aeb 100644 --- a/front_end/panels/timeline/TimelineFlameChartView.ts +++ b/front_end/panels/timeline/TimelineFlameChartView.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; @@ -39,8 +37,8 @@ const str_ = i18n.i18n.registerUIStrings('panels/timeline/TimelineFlameChartView.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); class MainSplitWidget extends UI.SplitWidget.SplitWidget { - _webVitals!: WebVitalsIntegrator; - _model!: PerformanceModel|null; + private webVitals!: WebVitalsIntegrator; + private model!: PerformanceModel|null; constructor( isVertical: boolean, secondIsSidebar: boolean, settingName?: string, defaultSidebarWidth?: number, defaultSidebarHeight?: number, constraintsInDip?: boolean) { @@ -49,18 +47,18 @@ setWebVitals(webVitals: WebVitalsIntegrator): void { /** @type {!WebVitalsIntegrator} */ - this._webVitals = webVitals; - this._webVitals.setMinimumSize(0, 120); + this.webVitals = webVitals; + this.webVitals.setMinimumSize(0, 120); } setWindowTimes(left: number, right: number, animate: boolean): void { - if (!this._webVitals) { + if (!this.webVitals) { return; } - const startTime = left - (this._model ? this._model.timelineModel().minimumRecordTime() : 0); - this._webVitals.chartViewport.setWindowTimes(left, right, animate); - this._webVitals.webVitalsTimeline.data = { + const startTime = left - (this.model ? this.model.timelineModel().minimumRecordTime() : 0); + this.webVitals.chartViewport.setWindowTimes(left, right, animate); + this.webVitals.webVitalsTimeline.data = { startTime: startTime, duration: right - left, fcps: undefined, @@ -73,8 +71,8 @@ } setModelAndUpdateBoundaries(model: PerformanceModel|null): void { - this._model = model; - if (!this._webVitals || !model) { + this.model = model; + if (!this.webVitals || !model) { return; } @@ -106,12 +104,12 @@ events.filter(e => SDK.TracingModel.TracingModel.isCompletePhase(e.phase) && timelineModel.isLongRunningTask(e)) .map(e => ({start: e.startTime - minimumBoundary, duration: e.duration || 0})); - this._webVitals.chartViewport.setBoundaries(left, right - left); + this.webVitals.chartViewport.setBoundaries(left, right - left); - this._webVitals.chartViewport.setWindowTimes(left, right); + this.webVitals.chartViewport.setWindowTimes(left, right); - const startTime = left - (this._model ? this._model.timelineModel().minimumRecordTime() : 0); - this._webVitals.webVitalsTimeline.data = { + const startTime = left - (this.model ? this.model.timelineModel().minimumRecordTime() : 0); + this.webVitals.webVitalsTimeline.data = { startTime: startTime, duration: right - left, maxDuration: timelineModel.maximumRecordTime(), @@ -126,254 +124,252 @@ export class TimelineFlameChartView extends UI.Widget.VBox implements PerfUI.FlameChart.FlameChartDelegate, UI.SearchableView.Searchable { - _delegate: TimelineModeViewDelegate; - _model: PerformanceModel|null; - _searchResults!: number[]|undefined; - _eventListeners: Common.EventTarget.EventDescriptor[]; + private readonly delegate: TimelineModeViewDelegate; + private model: PerformanceModel|null; + private searchResults!: number[]|undefined; + private eventListeners: Common.EventTarget.EventDescriptor[]; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _showMemoryGraphSetting: Common.Settings.Setting<any>; + private readonly showMemoryGraphSetting: Common.Settings.Setting<any>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _showWebVitalsSetting: Common.Settings.Setting<any>; - _networkSplitWidget: UI.SplitWidget.SplitWidget; - _mainDataProvider: TimelineFlameChartDataProvider; - _mainFlameChart: PerfUI.FlameChart.FlameChart; + private readonly showWebVitalsSetting: Common.Settings.Setting<any>; + private readonly networkSplitWidget: UI.SplitWidget.SplitWidget; + private mainDataProvider: TimelineFlameChartDataProvider; + private readonly mainFlameChart: PerfUI.FlameChart.FlameChart; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _networkFlameChartGroupExpansionSetting: Common.Settings.Setting<any>; - _networkDataProvider: TimelineFlameChartNetworkDataProvider; - _networkFlameChart: PerfUI.FlameChart.FlameChart; - _networkPane: UI.Widget.VBox; - _splitResizer: HTMLElement; - _webVitals: WebVitalsIntegrator; - _mainSplitWidget: MainSplitWidget; - _chartSplitWidget: UI.SplitWidget.SplitWidget; - _countersView: CountersGraph; - _detailsSplitWidget: UI.SplitWidget.SplitWidget; - _detailsView: TimelineDetailsView; - _onMainEntrySelected: (event?: Common.EventTarget.EventTargetEvent) => void; - _onNetworkEntrySelected: (event?: Common.EventTarget.EventTargetEvent) => void; - _nextExtensionIndex: number; - _boundRefresh: () => void; - _selectedTrack: TimelineModel.TimelineModel.Track|null; + private readonly networkFlameChartGroupExpansionSetting: Common.Settings.Setting<any>; + private networkDataProvider: TimelineFlameChartNetworkDataProvider; + private readonly networkFlameChart: PerfUI.FlameChart.FlameChart; + private readonly networkPane: UI.Widget.VBox; + private readonly splitResizer: HTMLElement; + private readonly webVitals: WebVitalsIntegrator; + private readonly mainSplitWidget: MainSplitWidget; + private readonly chartSplitWidget: UI.SplitWidget.SplitWidget; + private readonly countersView: CountersGraph; + private readonly detailsSplitWidget: UI.SplitWidget.SplitWidget; + private readonly detailsView: TimelineDetailsView; + private readonly onMainEntrySelected: (event?: Common.EventTarget.EventTargetEvent) => void; + private readonly onNetworkEntrySelected: (event?: Common.EventTarget.EventTargetEvent) => void; + private nextExtensionIndex: number; + private readonly boundRefresh: () => void; + private selectedTrack: TimelineModel.TimelineModel.Track|null; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _groupBySetting: Common.Settings.Setting<any>; - _searchableView!: UI.SearchableView.SearchableView; - _urlToColorCache?: Map<string, string>; - _needsResizeToPreferredHeights?: boolean; - _selectedSearchResult?: number; - _searchRegex?: RegExp; + private readonly groupBySetting: Common.Settings.Setting<any>; + private searchableView!: UI.SearchableView.SearchableView; + private urlToColorCache?: Map<string, string>; + private needsResizeToPreferredHeights?: boolean; + private selectedSearchResult?: number; + private searchRegex?: RegExp; constructor(delegate: TimelineModeViewDelegate) { super(); this.element.classList.add('timeline-flamechart'); - this._delegate = delegate; - this._model = null; - this._eventListeners = []; + this.delegate = delegate; + this.model = null; + this.eventListeners = []; - this._showMemoryGraphSetting = Common.Settings.Settings.instance().createSetting('timelineShowMemory', false); - this._showWebVitalsSetting = Common.Settings.Settings.instance().createSetting('timelineWebVitals', false); + this.showMemoryGraphSetting = Common.Settings.Settings.instance().createSetting('timelineShowMemory', false); + this.showWebVitalsSetting = Common.Settings.Settings.instance().createSetting('timelineWebVitals', false); // Create main and network flamecharts. - this._networkSplitWidget = new UI.SplitWidget.SplitWidget(false, false, 'timelineFlamechartMainView', 150); + this.networkSplitWidget = new UI.SplitWidget.SplitWidget(false, false, 'timelineFlamechartMainView', 150); // Ensure that the network panel & resizer appears above the web vitals / main thread. - this._networkSplitWidget.sidebarElement().style.zIndex = '120'; + this.networkSplitWidget.sidebarElement().style.zIndex = '120'; const mainViewGroupExpansionSetting = Common.Settings.Settings.instance().createSetting('timelineFlamechartMainViewGroupExpansion', {}); - this._mainDataProvider = new TimelineFlameChartDataProvider(); - this._mainDataProvider.addEventListener( - TimelineFlameChartDataProviderEvents.DataChanged, () => this._mainFlameChart.scheduleUpdate()); - this._mainFlameChart = - new PerfUI.FlameChart.FlameChart(this._mainDataProvider, this, mainViewGroupExpansionSetting); - this._mainFlameChart.alwaysShowVerticalScroll(); - this._mainFlameChart.enableRuler(false); + this.mainDataProvider = new TimelineFlameChartDataProvider(); + this.mainDataProvider.addEventListener( + TimelineFlameChartDataProviderEvents.DataChanged, () => this.mainFlameChart.scheduleUpdate()); + this.mainFlameChart = new PerfUI.FlameChart.FlameChart(this.mainDataProvider, this, mainViewGroupExpansionSetting); + this.mainFlameChart.alwaysShowVerticalScroll(); + this.mainFlameChart.enableRuler(false); - this._networkFlameChartGroupExpansionSetting = + this.networkFlameChartGroupExpansionSetting = Common.Settings.Settings.instance().createSetting('timelineFlamechartNetworkViewGroupExpansion', {}); - this._networkDataProvider = new TimelineFlameChartNetworkDataProvider(); - this._networkFlameChart = - new PerfUI.FlameChart.FlameChart(this._networkDataProvider, this, this._networkFlameChartGroupExpansionSetting); - this._networkFlameChart.alwaysShowVerticalScroll(); - this._networkFlameChart.disableRangeSelection(); + this.networkDataProvider = new TimelineFlameChartNetworkDataProvider(); + this.networkFlameChart = + new PerfUI.FlameChart.FlameChart(this.networkDataProvider, this, this.networkFlameChartGroupExpansionSetting); + this.networkFlameChart.alwaysShowVerticalScroll(); + this.networkFlameChart.disableRangeSelection(); - this._networkPane = new UI.Widget.VBox(); - this._networkPane.setMinimumSize(23, 23); - this._networkFlameChart.show(this._networkPane.element); - this._splitResizer = this._networkPane.element.createChild('div', 'timeline-flamechart-resizer'); - this._networkSplitWidget.hideDefaultResizer(true); - this._networkSplitWidget.installResizer(this._splitResizer); + this.networkPane = new UI.Widget.VBox(); + this.networkPane.setMinimumSize(23, 23); + this.networkFlameChart.show(this.networkPane.element); + this.splitResizer = this.networkPane.element.createChild('div', 'timeline-flamechart-resizer'); + this.networkSplitWidget.hideDefaultResizer(true); + this.networkSplitWidget.installResizer(this.splitResizer); - this._webVitals = new WebVitalsIntegrator(this); + this.webVitals = new WebVitalsIntegrator(this); - this._mainSplitWidget = new MainSplitWidget(false, false, 'timelineFlamechartMainAndVitalsView', undefined, 120); - this._mainSplitWidget.setWebVitals(this._webVitals); - this._mainSplitWidget.setMainWidget(this._mainFlameChart); - this._mainSplitWidget.setSidebarWidget(this._webVitals); + this.mainSplitWidget = new MainSplitWidget(false, false, 'timelineFlamechartMainAndVitalsView', undefined, 120); + this.mainSplitWidget.setWebVitals(this.webVitals); + this.mainSplitWidget.setMainWidget(this.mainFlameChart); + this.mainSplitWidget.setSidebarWidget(this.webVitals); this.toggleWebVitalsLane(); - this._networkSplitWidget.setMainWidget(this._mainSplitWidget); - this._networkSplitWidget.setSidebarWidget(this._networkPane); + this.networkSplitWidget.setMainWidget(this.mainSplitWidget); + this.networkSplitWidget.setSidebarWidget(this.networkPane); // Create counters chart splitter. - this._chartSplitWidget = new UI.SplitWidget.SplitWidget(false, true, 'timelineCountersSplitViewState'); - this._countersView = new CountersGraph(this._delegate); - this._chartSplitWidget.setMainWidget(this._networkSplitWidget); - this._chartSplitWidget.setSidebarWidget(this._countersView); - this._chartSplitWidget.hideDefaultResizer(); - this._chartSplitWidget.installResizer((this._countersView.resizerElement() as Element)); - this._updateCountersGraphToggle(); + this.chartSplitWidget = new UI.SplitWidget.SplitWidget(false, true, 'timelineCountersSplitViewState'); + this.countersView = new CountersGraph(this.delegate); + this.chartSplitWidget.setMainWidget(this.networkSplitWidget); + this.chartSplitWidget.setSidebarWidget(this.countersView); + this.chartSplitWidget.hideDefaultResizer(); + this.chartSplitWidget.installResizer((this.countersView.resizerElement() as Element)); + this.updateCountersGraphToggle(); // Create top level properties splitter. - this._detailsSplitWidget = new UI.SplitWidget.SplitWidget(false, true, 'timelinePanelDetailsSplitViewState'); - this._detailsSplitWidget.element.classList.add('timeline-details-split'); - this._detailsView = new TimelineDetailsView(delegate); - this._detailsSplitWidget.installResizer(this._detailsView.headerElement()); - this._detailsSplitWidget.setMainWidget(this._chartSplitWidget); - this._detailsSplitWidget.setSidebarWidget(this._detailsView); - this._detailsSplitWidget.show(this.element); + this.detailsSplitWidget = new UI.SplitWidget.SplitWidget(false, true, 'timelinePanelDetailsSplitViewState'); + this.detailsSplitWidget.element.classList.add('timeline-details-split'); + this.detailsView = new TimelineDetailsView(delegate); + this.detailsSplitWidget.installResizer(this.detailsView.headerElement()); + this.detailsSplitWidget.setMainWidget(this.chartSplitWidget); + this.detailsSplitWidget.setSidebarWidget(this.detailsView); + this.detailsSplitWidget.show(this.element); // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // @ts-expect-error - this._onMainEntrySelected = this._onEntrySelected.bind(this, this._mainDataProvider); + this.onMainEntrySelected = this.onEntrySelected.bind(this, this.mainDataProvider); // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // @ts-expect-error - this._onNetworkEntrySelected = this._onEntrySelected.bind(this, this._networkDataProvider); - this._mainFlameChart.addEventListener(PerfUI.FlameChart.Events.EntrySelected, this._onMainEntrySelected, this); - this._mainFlameChart.addEventListener(PerfUI.FlameChart.Events.EntryInvoked, this._onMainEntrySelected, this); - this._networkFlameChart.addEventListener( - PerfUI.FlameChart.Events.EntrySelected, this._onNetworkEntrySelected, this); - this._networkFlameChart.addEventListener(PerfUI.FlameChart.Events.EntryInvoked, this._onNetworkEntrySelected, this); - this._mainFlameChart.addEventListener(PerfUI.FlameChart.Events.EntryHighlighted, this._onEntryHighlighted, this); - this._nextExtensionIndex = 0; + this.onNetworkEntrySelected = this.onEntrySelected.bind(this, this.networkDataProvider); + this.mainFlameChart.addEventListener(PerfUI.FlameChart.Events.EntrySelected, this.onMainEntrySelected, this); + this.mainFlameChart.addEventListener(PerfUI.FlameChart.Events.EntryInvoked, this.onMainEntrySelected, this); + this.networkFlameChart.addEventListener(PerfUI.FlameChart.Events.EntrySelected, this.onNetworkEntrySelected, this); + this.networkFlameChart.addEventListener(PerfUI.FlameChart.Events.EntryInvoked, this.onNetworkEntrySelected, this); + this.mainFlameChart.addEventListener(PerfUI.FlameChart.Events.EntryHighlighted, this.onEntryHighlighted, this); + this.nextExtensionIndex = 0; - this._boundRefresh = this._refresh.bind(this); - this._selectedTrack = null; + this.boundRefresh = this.refresh.bind(this); + this.selectedTrack = null; - this._mainDataProvider.setEventColorMapping(TimelineUIUtils.eventColor); - this._groupBySetting = Common.Settings.Settings.instance().createSetting( + this.mainDataProvider.setEventColorMapping(TimelineUIUtils.eventColor); + this.groupBySetting = Common.Settings.Settings.instance().createSetting( 'timelineTreeGroupBy', AggregatedTimelineTreeView.GroupBy.None); - this._groupBySetting.addChangeListener(this._updateColorMapper, this); - this._updateColorMapper(); + this.groupBySetting.addChangeListener(this.updateColorMapper, this); + this.updateColorMapper(); } toggleWebVitalsLane(): void { - if (this._showWebVitalsSetting.get()) { - this._mainSplitWidget.showBoth(); - this._mainSplitWidget.setSidebarSize(120); - this._mainSplitWidget.setResizable(false); - this._mainSplitWidget.hideDefaultResizer(true); + if (this.showWebVitalsSetting.get()) { + this.mainSplitWidget.showBoth(); + this.mainSplitWidget.setSidebarSize(120); + this.mainSplitWidget.setResizable(false); + this.mainSplitWidget.hideDefaultResizer(true); } else { - this._mainSplitWidget.hideSidebar(); + this.mainSplitWidget.hideSidebar(); } } - _updateColorMapper(): void { - this._urlToColorCache = new Map(); - if (!this._model) { + private updateColorMapper(): void { + this.urlToColorCache = new Map(); + if (!this.model) { return; } - this._mainDataProvider.setEventColorMapping(TimelineUIUtils.eventColor); - this._mainFlameChart.update(); + this.mainDataProvider.setEventColorMapping(TimelineUIUtils.eventColor); + this.mainFlameChart.update(); } - _onWindowChanged(event: Common.EventTarget.EventTargetEvent): void { + private onWindowChanged(event: Common.EventTarget.EventTargetEvent): void { const window = (event.data.window as Window); const animate = Boolean(event.data.animate); - this._mainFlameChart.setWindowTimes(window.left, window.right, animate); - this._networkFlameChart.setWindowTimes(window.left, window.right, animate); - this._networkDataProvider.setWindowTimes(window.left, window.right); - this._mainSplitWidget.setWindowTimes(window.left, window.right, animate); - this._updateSearchResults(false, false); + this.mainFlameChart.setWindowTimes(window.left, window.right, animate); + this.networkFlameChart.setWindowTimes(window.left, window.right, animate); + this.networkDataProvider.setWindowTimes(window.left, window.right); + this.mainSplitWidget.setWindowTimes(window.left, window.right, animate); + this.updateSearchResults(false, false); } windowChanged(windowStartTime: number, windowEndTime: number, animate: boolean): void { - if (this._model) { - this._model.setWindow({left: windowStartTime, right: windowEndTime}, animate); + if (this.model) { + this.model.setWindow({left: windowStartTime, right: windowEndTime}, animate); } } updateRangeSelection(startTime: number, endTime: number): void { - this._delegate.select(TimelineSelection.fromRange(startTime, endTime)); + this.delegate.select(TimelineSelection.fromRange(startTime, endTime)); } updateSelectedGroup(flameChart: PerfUI.FlameChart.FlameChart, group: PerfUI.FlameChart.Group|null): void { - if (flameChart !== this._mainFlameChart) { + if (flameChart !== this.mainFlameChart) { return; } - const track = group ? this._mainDataProvider.groupTrack(group) : null; - this._selectedTrack = track; - this._updateTrack(); + const track = group ? this.mainDataProvider.groupTrack(group) : null; + this.selectedTrack = track; + this.updateTrack(); } setModel(model: PerformanceModel|null): void { - if (model === this._model) { + if (model === this.model) { return; } - Common.EventTarget.removeEventListeners(this._eventListeners); - this._model = model; - this._selectedTrack = null; - this._mainDataProvider.setModel(this._model); - this._networkDataProvider.setModel(this._model); - if (this._model) { - this._eventListeners = [ - this._model.addEventListener(PerformanceModelEvents.WindowChanged, this._onWindowChanged, this), - this._model.addEventListener(PerformanceModelEvents.ExtensionDataAdded, this._appendExtensionData, this), + Common.EventTarget.removeEventListeners(this.eventListeners); + this.model = model; + this.selectedTrack = null; + this.mainDataProvider.setModel(this.model); + this.networkDataProvider.setModel(this.model); + if (this.model) { + this.eventListeners = [ + this.model.addEventListener(PerformanceModelEvents.WindowChanged, this.onWindowChanged, this), + this.model.addEventListener(PerformanceModelEvents.ExtensionDataAdded, this.appendExtensionData, this), ]; - const window = this._model.window(); - this._mainFlameChart.setWindowTimes(window.left, window.right); - this._networkFlameChart.setWindowTimes(window.left, window.right); - this._networkDataProvider.setWindowTimes(window.left, window.right); - this._mainSplitWidget.setModelAndUpdateBoundaries(model); - this._updateSearchResults(false, false); + const window = this.model.window(); + this.mainFlameChart.setWindowTimes(window.left, window.right); + this.networkFlameChart.setWindowTimes(window.left, window.right); + this.networkDataProvider.setWindowTimes(window.left, window.right); + this.mainSplitWidget.setModelAndUpdateBoundaries(model); + this.updateSearchResults(false, false); } - this._updateColorMapper(); - this._updateTrack(); - this._nextExtensionIndex = 0; - this._appendExtensionData(); - this._refresh(); + this.updateColorMapper(); + this.updateTrack(); + this.nextExtensionIndex = 0; + this.appendExtensionData(); + this.refresh(); } - _updateTrack(): void { - this._countersView.setModel(this._model, this._selectedTrack); - this._detailsView.setModel(this._model, this._selectedTrack); + private updateTrack(): void { + this.countersView.setModel(this.model, this.selectedTrack); + this.detailsView.setModel(this.model, this.selectedTrack); } - _refresh(): void { - if (this._networkDataProvider.isEmpty()) { - this._mainFlameChart.enableRuler(true); - this._networkSplitWidget.hideSidebar(); + private refresh(): void { + if (this.networkDataProvider.isEmpty()) { + this.mainFlameChart.enableRuler(true); + this.networkSplitWidget.hideSidebar(); } else { - this._mainFlameChart.enableRuler(false); - this._networkSplitWidget.showBoth(); + this.mainFlameChart.enableRuler(false); + this.networkSplitWidget.showBoth(); this.resizeToPreferredHeights(); } - this._mainFlameChart.reset(); - this._networkFlameChart.reset(); - this._updateSearchResults(false, false); + this.mainFlameChart.reset(); + this.networkFlameChart.reset(); + this.updateSearchResults(false, false); } - _appendExtensionData(): void { - if (!this._model) { + private appendExtensionData(): void { + if (!this.model) { return; } - const extensions = this._model.extensionInfo(); - while (this._nextExtensionIndex < extensions.length) { - this._mainDataProvider.appendExtensionEvents(extensions[this._nextExtensionIndex++]); + const extensions = this.model.extensionInfo(); + while (this.nextExtensionIndex < extensions.length) { + this.mainDataProvider.appendExtensionEvents(extensions[this.nextExtensionIndex++]); } - this._mainFlameChart.scheduleUpdate(); + this.mainFlameChart.scheduleUpdate(); } - _onEntryHighlighted(commonEvent: Common.EventTarget.EventTargetEvent): void { + private onEntryHighlighted(commonEvent: Common.EventTarget.EventTargetEvent): void { SDK.OverlayModel.OverlayModel.hideDOMNodeHighlight(); const entryIndex = (commonEvent.data as number); - const event = this._mainDataProvider.eventByIndex(entryIndex); + const event = this.mainDataProvider.eventByIndex(entryIndex); if (!event) { return; } - const target = this._model && this._model.timelineModel().targetByEvent(event); + const target = this.model && this.model.timelineModel().targetByEvent(event); if (!target) { return; } @@ -389,96 +385,95 @@ highlightEvent(event: SDK.TracingModel.Event|null): void { const entryIndex = - event ? this._mainDataProvider.entryIndexForSelection(TimelineSelection.fromTraceEvent(event)) : -1; + event ? this.mainDataProvider.entryIndexForSelection(TimelineSelection.fromTraceEvent(event)) : -1; if (entryIndex >= 0) { - this._mainFlameChart.highlightEntry(entryIndex); + this.mainFlameChart.highlightEntry(entryIndex); } else { - this._mainFlameChart.hideHighlight(); + this.mainFlameChart.hideHighlight(); } } willHide(): void { - this._networkFlameChartGroupExpansionSetting.removeChangeListener(this.resizeToPreferredHeights, this); - this._showMemoryGraphSetting.removeChangeListener(this._updateCountersGraphToggle, this); - Bindings.IgnoreListManager.IgnoreListManager.instance().removeChangeListener(this._boundRefresh); + this.networkFlameChartGroupExpansionSetting.removeChangeListener(this.resizeToPreferredHeights, this); + this.showMemoryGraphSetting.removeChangeListener(this.updateCountersGraphToggle, this); + Bindings.IgnoreListManager.IgnoreListManager.instance().removeChangeListener(this.boundRefresh); } wasShown(): void { - this._networkFlameChartGroupExpansionSetting.addChangeListener(this.resizeToPreferredHeights, this); - this._showMemoryGraphSetting.addChangeListener(this._updateCountersGraphToggle, this); - Bindings.IgnoreListManager.IgnoreListManager.instance().addChangeListener(this._boundRefresh); - if (this._needsResizeToPreferredHeights) { + this.networkFlameChartGroupExpansionSetting.addChangeListener(this.resizeToPreferredHeights, this); + this.showMemoryGraphSetting.addChangeListener(this.updateCountersGraphToggle, this); + Bindings.IgnoreListManager.IgnoreListManager.instance().addChangeListener(this.boundRefresh); + if (this.needsResizeToPreferredHeights) { this.resizeToPreferredHeights(); } - this._mainFlameChart.scheduleUpdate(); - this._networkFlameChart.scheduleUpdate(); + this.mainFlameChart.scheduleUpdate(); + this.networkFlameChart.scheduleUpdate(); } - _updateCountersGraphToggle(): void { - if (this._showMemoryGraphSetting.get()) { - this._chartSplitWidget.showBoth(); + private updateCountersGraphToggle(): void { + if (this.showMemoryGraphSetting.get()) { + this.chartSplitWidget.showBoth(); } else { - this._chartSplitWidget.hideSidebar(); + this.chartSplitWidget.hideSidebar(); } } setSelection(selection: TimelineSelection|null): void { - let index = this._mainDataProvider.entryIndexForSelection(selection); - this._mainFlameChart.setSelectedEntry(index); - index = this._networkDataProvider.entryIndexForSelection(selection); - this._networkFlameChart.setSelectedEntry(index); - if (this._detailsView) { - this._detailsView.setSelection(selection); + let index = this.mainDataProvider.entryIndexForSelection(selection); + this.mainFlameChart.setSelectedEntry(index); + index = this.networkDataProvider.entryIndexForSelection(selection); + this.networkFlameChart.setSelectedEntry(index); + if (this.detailsView) { + this.detailsView.setSelection(selection); } } - _onEntrySelected(dataProvider: PerfUI.FlameChart.FlameChartDataProvider, event: Common.EventTarget.EventTargetEvent): - void { + private onEntrySelected( + dataProvider: PerfUI.FlameChart.FlameChartDataProvider, event: Common.EventTarget.EventTargetEvent): void { const entryIndex = (event.data as number); - if (Root.Runtime.experiments.isEnabled('timelineEventInitiators') && dataProvider === this._mainDataProvider) { - if (this._mainDataProvider.buildFlowForInitiator(entryIndex)) { - this._mainFlameChart.scheduleUpdate(); + if (Root.Runtime.experiments.isEnabled('timelineEventInitiators') && dataProvider === this.mainDataProvider) { + if (this.mainDataProvider.buildFlowForInitiator(entryIndex)) { + this.mainFlameChart.scheduleUpdate(); } } - this._delegate.select((dataProvider as TimelineFlameChartNetworkDataProvider).createSelection(entryIndex)); + this.delegate.select((dataProvider as TimelineFlameChartNetworkDataProvider).createSelection(entryIndex)); } resizeToPreferredHeights(): void { if (!this.isShowing()) { - this._needsResizeToPreferredHeights = true; + this.needsResizeToPreferredHeights = true; return; } - this._needsResizeToPreferredHeights = false; - this._networkPane.element.classList.toggle( - 'timeline-network-resizer-disabled', !this._networkDataProvider.isExpanded()); - this._networkSplitWidget.setSidebarSize( - this._networkDataProvider.preferredHeight() + this._splitResizer.clientHeight + PerfUI.FlameChart.HeaderHeight + + this.needsResizeToPreferredHeights = false; + this.networkPane.element.classList.toggle( + 'timeline-network-resizer-disabled', !this.networkDataProvider.isExpanded()); + this.networkSplitWidget.setSidebarSize( + this.networkDataProvider.preferredHeight() + this.splitResizer.clientHeight + PerfUI.FlameChart.HeaderHeight + 2); } setSearchableView(searchableView: UI.SearchableView.SearchableView): void { - this._searchableView = searchableView; + this.searchableView = searchableView; } // UI.SearchableView.Searchable implementation jumpToNextSearchResult(): void { - if (!this._searchResults || !this._searchResults.length) { - return; - } - const index = typeof this._selectedSearchResult !== 'undefined' ? - this._searchResults.indexOf(this._selectedSearchResult) : - -1; - this._selectSearchResult(Platform.NumberUtilities.mod(index + 1, this._searchResults.length)); - } - - jumpToPreviousSearchResult(): void { - if (!this._searchResults || !this._searchResults.length) { + if (!this.searchResults || !this.searchResults.length) { return; } const index = - typeof this._selectedSearchResult !== 'undefined' ? this._searchResults.indexOf(this._selectedSearchResult) : 0; - this._selectSearchResult(Platform.NumberUtilities.mod(index - 1, this._searchResults.length)); + typeof this.selectedSearchResult !== 'undefined' ? this.searchResults.indexOf(this.selectedSearchResult) : -1; + this.selectSearchResult(Platform.NumberUtilities.mod(index + 1, this.searchResults.length)); + } + + jumpToPreviousSearchResult(): void { + if (!this.searchResults || !this.searchResults.length) { + return; + } + const index = + typeof this.selectedSearchResult !== 'undefined' ? this.searchResults.indexOf(this.selectedSearchResult) : 0; + this.selectSearchResult(Platform.NumberUtilities.mod(index - 1, this.searchResults.length)); } supportsCaseSensitiveSearch(): boolean { @@ -489,47 +484,47 @@ return true; } - _selectSearchResult(index: number): void { - this._searchableView.updateCurrentMatchIndex(index); - if (this._searchResults) { - this._selectedSearchResult = this._searchResults[index]; - this._delegate.select(this._mainDataProvider.createSelection(this._selectedSearchResult)); + private selectSearchResult(index: number): void { + this.searchableView.updateCurrentMatchIndex(index); + if (this.searchResults) { + this.selectedSearchResult = this.searchResults[index]; + this.delegate.select(this.mainDataProvider.createSelection(this.selectedSearchResult)); } } - _updateSearchResults(shouldJump: boolean, jumpBackwards?: boolean): void { - const oldSelectedSearchResult = (this._selectedSearchResult as number); - delete this._selectedSearchResult; - this._searchResults = []; - if (!this._searchRegex || !this._model) { + private updateSearchResults(shouldJump: boolean, jumpBackwards?: boolean): void { + const oldSelectedSearchResult = (this.selectedSearchResult as number); + delete this.selectedSearchResult; + this.searchResults = []; + if (!this.searchRegex || !this.model) { return; } - const regExpFilter = new TimelineRegExp(this._searchRegex); - const window = this._model.window(); - this._searchResults = this._mainDataProvider.search(window.left, window.right, regExpFilter); - this._searchableView.updateSearchMatchesCount(this._searchResults.length); - if (!shouldJump || !this._searchResults.length) { + const regExpFilter = new TimelineRegExp(this.searchRegex); + const window = this.model.window(); + this.searchResults = this.mainDataProvider.search(window.left, window.right, regExpFilter); + this.searchableView.updateSearchMatchesCount(this.searchResults.length); + if (!shouldJump || !this.searchResults.length) { return; } - let selectedIndex = this._searchResults.indexOf(oldSelectedSearchResult); + let selectedIndex = this.searchResults.indexOf(oldSelectedSearchResult); if (selectedIndex === -1) { - selectedIndex = jumpBackwards ? this._searchResults.length - 1 : 0; + selectedIndex = jumpBackwards ? this.searchResults.length - 1 : 0; } - this._selectSearchResult(selectedIndex); + this.selectSearchResult(selectedIndex); } searchCanceled(): void { - if (typeof this._selectedSearchResult !== 'undefined') { - this._delegate.select(null); + if (typeof this.selectedSearchResult !== 'undefined') { + this.delegate.select(null); } - delete this._searchResults; - delete this._selectedSearchResult; - delete this._searchRegex; + delete this.searchResults; + delete this.selectedSearchResult; + delete this.searchRegex; } performSearch(searchConfig: UI.SearchableView.SearchConfig, shouldJump: boolean, jumpBackwards?: boolean): void { - this._searchRegex = searchConfig.toSearchRegex(); - this._updateSearchResults(shouldJump, jumpBackwards); + this.searchRegex = searchConfig.toSearchRegex(); + this.updateSearchResults(shouldJump, jumpBackwards); } } @@ -547,46 +542,46 @@ }; export class TimelineFlameChartMarker implements PerfUI.FlameChart.FlameChartMarker { - _startTime: number; - _startOffset: number; - _style: TimelineMarkerStyle; + private readonly startTimeInternal: number; + private readonly startOffset: number; + private style: TimelineMarkerStyle; constructor(startTime: number, startOffset: number, style: TimelineMarkerStyle) { - this._startTime = startTime; - this._startOffset = startOffset; - this._style = style; + this.startTimeInternal = startTime; + this.startOffset = startOffset; + this.style = style; } startTime(): number { - return this._startTime; + return this.startTimeInternal; } color(): string { - return this._style.color; + return this.style.color; } title(): string|null { - if (this._style.lowPriority) { + if (this.style.lowPriority) { return null; } - const startTime = i18n.TimeUtilities.millisToString(this._startOffset); - return i18nString(UIStrings.sAtS, {PH1: this._style.title, PH2: startTime}); + const startTime = i18n.TimeUtilities.millisToString(this.startOffset); + return i18nString(UIStrings.sAtS, {PH1: this.style.title, PH2: startTime}); } draw(context: CanvasRenderingContext2D, x: number, height: number, pixelsPerMillisecond: number): void { const lowPriorityVisibilityThresholdInPixelsPerMs = 4; - if (this._style.lowPriority && pixelsPerMillisecond < lowPriorityVisibilityThresholdInPixelsPerMs) { + if (this.style.lowPriority && pixelsPerMillisecond < lowPriorityVisibilityThresholdInPixelsPerMs) { return; } context.save(); - if (this._style.tall) { - context.strokeStyle = this._style.color; - context.lineWidth = this._style.lineWidth; - context.translate(this._style.lineWidth < 1 || (this._style.lineWidth & 1) ? 0.5 : 0, 0.5); + if (this.style.tall) { + context.strokeStyle = this.style.color; + context.lineWidth = this.style.lineWidth; + context.translate(this.style.lineWidth < 1 || (this.style.lineWidth & 1) ? 0.5 : 0, 0.5); context.beginPath(); context.moveTo(x, 0); - context.setLineDash(this._style.dashStyle); + context.setLineDash(this.style.dashStyle); context.lineTo(x, context.canvas.height); context.stroke(); }
diff --git a/front_end/panels/timeline/TimelineHistoryManager.ts b/front_end/panels/timeline/TimelineHistoryManager.ts index 5567b52..a97fab5 100644 --- a/front_end/panels/timeline/TimelineHistoryManager.ts +++ b/front_end/panels/timeline/TimelineHistoryManager.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; @@ -58,57 +56,57 @@ const str_ = i18n.i18n.registerUIStrings('panels/timeline/TimelineHistoryManager.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class TimelineHistoryManager { - _recordings: PerformanceModel[]; - _action: UI.ActionRegistration.Action; - _nextNumberByDomain: Map<string, number>; - _button: ToolbarButton; - _allOverviews: { + private recordings: PerformanceModel[]; + private readonly action: UI.ActionRegistration.Action; + private readonly nextNumberByDomain: Map<string, number>; + private readonly buttonInternal: ToolbarButton; + private readonly allOverviews: { constructor: typeof TimelineEventOverviewResponsiveness, height: number, }[]; - _totalHeight: number; - _enabled: boolean; - _lastActiveModel: PerformanceModel|null; + private totalHeight: number; + private enabled: boolean; + private lastActiveModel: PerformanceModel|null; constructor() { - this._recordings = []; - this._action = + this.recordings = []; + this.action = (UI.ActionRegistry.ActionRegistry.instance().action('timeline.show-history') as UI.ActionRegistration.Action); - this._nextNumberByDomain = new Map(); - this._button = new ToolbarButton(this._action); + this.nextNumberByDomain = new Map(); + this.buttonInternal = new ToolbarButton(this.action); - UI.ARIAUtils.markAsMenuButton(this._button.element); + UI.ARIAUtils.markAsMenuButton(this.buttonInternal.element); this.clear(); - this._allOverviews = [ + this.allOverviews = [ {constructor: TimelineEventOverviewResponsiveness, height: 3}, {constructor: TimelineEventOverviewFrames, height: 16}, {constructor: TimelineEventOverviewCPUActivity, height: 20}, {constructor: TimelineEventOverviewNetwork, height: 8}, ]; - this._totalHeight = this._allOverviews.reduce((acc, entry) => acc + entry.height, 0); - this._enabled = true; - this._lastActiveModel = null; + this.totalHeight = this.allOverviews.reduce((acc, entry) => acc + entry.height, 0); + this.enabled = true; + this.lastActiveModel = null; } addRecording(performanceModel: PerformanceModel): void { - this._lastActiveModel = performanceModel; - this._recordings.unshift(performanceModel); - this._buildPreview(performanceModel); - const modelTitle = this._title(performanceModel); - this._button.setText(modelTitle); - const buttonTitle = this._action.title(); + this.lastActiveModel = performanceModel; + this.recordings.unshift(performanceModel); + this.buildPreview(performanceModel); + const modelTitle = this.title(performanceModel); + this.buttonInternal.setText(modelTitle); + const buttonTitle = this.action.title(); UI.ARIAUtils.setAccessibleName( - this._button.element, i18nString(UIStrings.currentSessionSS, {PH1: modelTitle, PH2: buttonTitle})); - this._updateState(); - if (this._recordings.length <= maxRecordings) { + this.buttonInternal.element, i18nString(UIStrings.currentSessionSS, {PH1: modelTitle, PH2: buttonTitle})); + this.updateState(); + if (this.recordings.length <= maxRecordings) { return; } - const lruModel = this._recordings.reduce((a, b) => lastUsedTime(a) < lastUsedTime(b) ? a : b); - this._recordings.splice(this._recordings.indexOf(lruModel), 1); + const lruModel = this.recordings.reduce((a, b) => lastUsedTime(a) < lastUsedTime(b) ? a : b); + this.recordings.splice(this.recordings.indexOf(lruModel), 1); lruModel.dispose(); function lastUsedTime(model: PerformanceModel): number { - const data = TimelineHistoryManager._dataForModel(model); + const data = TimelineHistoryManager.dataForModel(model); if (!data) { throw new Error('Unable to find data for model'); } @@ -117,40 +115,40 @@ } setEnabled(enabled: boolean): void { - this._enabled = enabled; - this._updateState(); + this.enabled = enabled; + this.updateState(); } button(): ToolbarButton { - return this._button; + return this.buttonInternal; } clear(): void { - this._recordings.forEach(model => model.dispose()); - this._recordings = []; - this._lastActiveModel = null; - this._updateState(); - this._button.setText(i18nString(UIStrings.noRecordings)); - this._nextNumberByDomain.clear(); + this.recordings.forEach(model => model.dispose()); + this.recordings = []; + this.lastActiveModel = null; + this.updateState(); + this.buttonInternal.setText(i18nString(UIStrings.noRecordings)); + this.nextNumberByDomain.clear(); } async showHistoryDropDown(): Promise<PerformanceModel|null> { - if (this._recordings.length < 2 || !this._enabled) { + if (this.recordings.length < 2 || !this.enabled) { return null; } // DropDown.show() function finishes when the dropdown menu is closed via selection or losing focus const model = - await DropDown.show(this._recordings, (this._lastActiveModel as PerformanceModel), this._button.element); + await DropDown.show(this.recordings, (this.lastActiveModel as PerformanceModel), this.buttonInternal.element); if (!model) { return null; } - const index = this._recordings.indexOf(model); + const index = this.recordings.indexOf(model); if (index < 0) { console.assert(false, 'selected recording not found'); return null; } - this._setCurrentModel(model); + this.setCurrentModel(model); return model; } @@ -159,49 +157,49 @@ } navigate(direction: number): PerformanceModel|null { - if (!this._enabled || !this._lastActiveModel) { + if (!this.enabled || !this.lastActiveModel) { return null; } - const index = this._recordings.indexOf(this._lastActiveModel); + const index = this.recordings.indexOf(this.lastActiveModel); if (index < 0) { return null; } - const newIndex = Platform.NumberUtilities.clamp(index + direction, 0, this._recordings.length - 1); - const model = this._recordings[newIndex]; - this._setCurrentModel(model); + const newIndex = Platform.NumberUtilities.clamp(index + direction, 0, this.recordings.length - 1); + const model = this.recordings[newIndex]; + this.setCurrentModel(model); return model; } - _setCurrentModel(model: PerformanceModel): void { - const data = TimelineHistoryManager._dataForModel(model); + private setCurrentModel(model: PerformanceModel): void { + const data = TimelineHistoryManager.dataForModel(model); if (!data) { throw new Error('Unable to find data for model'); } data.lastUsed = Date.now(); - this._lastActiveModel = model; - const modelTitle = this._title(model); - const buttonTitle = this._action.title(); - this._button.setText(modelTitle); + this.lastActiveModel = model; + const modelTitle = this.title(model); + const buttonTitle = this.action.title(); + this.buttonInternal.setText(modelTitle); UI.ARIAUtils.setAccessibleName( - this._button.element, i18nString(UIStrings.currentSessionSS, {PH1: modelTitle, PH2: buttonTitle})); + this.buttonInternal.element, i18nString(UIStrings.currentSessionSS, {PH1: modelTitle, PH2: buttonTitle})); } - _updateState(): void { - this._action.setEnabled(this._recordings.length > 1 && this._enabled); + private updateState(): void { + this.action.setEnabled(this.recordings.length > 1 && this.enabled); } - static _previewElement(performanceModel: PerformanceModel): Element { - const data = TimelineHistoryManager._dataForModel(performanceModel); + static previewElement(performanceModel: PerformanceModel): Element { + const data = TimelineHistoryManager.dataForModel(performanceModel); if (!data) { throw new Error('Unable to find data for model'); } const startedAt = performanceModel.recordStartTime(); data.time.textContent = - startedAt ? i18nString(UIStrings.sAgo, {PH1: TimelineHistoryManager._coarseAge(startedAt)}) : ''; + startedAt ? i18nString(UIStrings.sAgo, {PH1: TimelineHistoryManager.coarseAge(startedAt)}) : ''; return data.preview; } - static _coarseAge(time: number): string { + private static coarseAge(time: number): string { const seconds = Math.round((Date.now() - time) / 1000); if (seconds < 50) { return i18nString(UIStrings.moments); @@ -214,20 +212,20 @@ return i18nString(UIStrings.sH, {PH1: hours}); } - _title(performanceModel: PerformanceModel): string { - const data = TimelineHistoryManager._dataForModel(performanceModel); + private title(performanceModel: PerformanceModel): string { + const data = TimelineHistoryManager.dataForModel(performanceModel); if (!data) { throw new Error('Unable to find data for model'); } return data.title; } - _buildPreview(performanceModel: PerformanceModel): HTMLDivElement { + private buildPreview(performanceModel: PerformanceModel): HTMLDivElement { const parsedURL = Common.ParsedURL.ParsedURL.fromString(performanceModel.timelineModel().pageURL()); const domain = parsedURL ? parsedURL.host : ''; - const sequenceNumber = this._nextNumberByDomain.get(domain) || 1; + const sequenceNumber = this.nextNumberByDomain.get(domain) || 1; const title = i18nString(UIStrings.sD, {PH1: domain, PH2: sequenceNumber}); - this._nextNumberByDomain.set(domain, sequenceNumber + 1); + this.nextNumberByDomain.set(domain, sequenceNumber + 1); const timeElement = document.createElement('span'); const preview = document.createElement('div'); @@ -236,14 +234,14 @@ const data = {preview: preview, title: title, time: timeElement, lastUsed: Date.now()}; modelToPerformanceData.set(performanceModel, data); - preview.appendChild(this._buildTextDetails(performanceModel, title, timeElement)); + preview.appendChild(this.buildTextDetails(performanceModel, title, timeElement)); const screenshotAndOverview = preview.createChild('div', 'hbox'); - screenshotAndOverview.appendChild(this._buildScreenshotThumbnail(performanceModel)); - screenshotAndOverview.appendChild(this._buildOverview(performanceModel)); + screenshotAndOverview.appendChild(this.buildScreenshotThumbnail(performanceModel)); + screenshotAndOverview.appendChild(this.buildOverview(performanceModel)); return data.preview; } - _buildTextDetails(performanceModel: PerformanceModel, title: string, timeElement: Element): Element { + private buildTextDetails(performanceModel: PerformanceModel, title: string, timeElement: Element): Element { const container = document.createElement('div'); container.classList.add('text-details'); container.classList.add('hbox'); @@ -259,12 +257,12 @@ return container; } - _buildScreenshotThumbnail(performanceModel: PerformanceModel): Element { + private buildScreenshotThumbnail(performanceModel: PerformanceModel): Element { const container = document.createElement('div'); container.classList.add('screenshot-thumb'); const thumbnailAspectRatio = 3 / 2; - container.style.width = this._totalHeight * thumbnailAspectRatio + 'px'; - container.style.height = this._totalHeight + 'px'; + container.style.width = this.totalHeight * thumbnailAspectRatio + 'px'; + container.style.height = this.totalHeight + 'px'; const filmStripModel = performanceModel.filmStripModel(); const frames = filmStripModel.frames(); const lastFrame = frames[frames.length - 1]; @@ -279,18 +277,18 @@ return container; } - _buildOverview(performanceModel: PerformanceModel): Element { + private buildOverview(performanceModel: PerformanceModel): Element { const container = document.createElement('div'); container.style.width = previewWidth + 'px'; - container.style.height = this._totalHeight + 'px'; + container.style.height = this.totalHeight + 'px'; const canvas = (container.createChild('canvas') as HTMLCanvasElement); canvas.width = window.devicePixelRatio * previewWidth; - canvas.height = window.devicePixelRatio * this._totalHeight; + canvas.height = window.devicePixelRatio * this.totalHeight; const ctx = canvas.getContext('2d'); let yOffset = 0; - for (const overview of this._allOverviews) { + for (const overview of this.allOverviews) { const timelineOverview = new overview.constructor(); timelineOverview.setCanvasSize(previewWidth, overview.height); timelineOverview.setModel(performanceModel); @@ -305,7 +303,7 @@ return container; } - static _dataForModel(model: PerformanceModel): PreviewData|null { + private static dataForModel(model: PerformanceModel): PreviewData|null { return modelToPerformanceData.get(model) || null; } } @@ -320,95 +318,95 @@ }>(); export class DropDown implements UI.ListControl.ListDelegate<PerformanceModel> { - _glassPane: UI.GlassPane.GlassPane; - _listControl: UI.ListControl.ListControl<PerformanceModel>; - _focusRestorer: UI.UIUtils.ElementFocusRestorer; - _selectionDone: ((arg0: PerformanceModel|null) => void)|null; + private readonly glassPane: UI.GlassPane.GlassPane; + private readonly listControl: UI.ListControl.ListControl<PerformanceModel>; + private readonly focusRestorer: UI.UIUtils.ElementFocusRestorer; + private selectionDone: ((arg0: PerformanceModel|null) => void)|null; constructor(models: PerformanceModel[]) { - this._glassPane = new UI.GlassPane.GlassPane(); - this._glassPane.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent); - this._glassPane.setOutsideClickCallback(() => this._close(null)); - this._glassPane.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane); - this._glassPane.setAnchorBehavior(UI.GlassPane.AnchorBehavior.PreferBottom); - this._glassPane.element.addEventListener('blur', () => this._close(null)); + this.glassPane = new UI.GlassPane.GlassPane(); + this.glassPane.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent); + this.glassPane.setOutsideClickCallback(() => this.close(null)); + this.glassPane.setPointerEventsBehavior(UI.GlassPane.PointerEventsBehavior.BlockedByGlassPane); + this.glassPane.setAnchorBehavior(UI.GlassPane.AnchorBehavior.PreferBottom); + this.glassPane.element.addEventListener('blur', () => this.close(null)); - const shadowRoot = UI.Utils.createShadowRootWithCoreStyles(this._glassPane.contentElement, { + const shadowRoot = UI.Utils.createShadowRootWithCoreStyles(this.glassPane.contentElement, { cssFile: 'panels/timeline/timelineHistoryManager.css', delegatesFocus: undefined, }); const contentElement = shadowRoot.createChild('div', 'drop-down'); const listModel = new UI.ListModel.ListModel<PerformanceModel>(); - this._listControl = + this.listControl = new UI.ListControl.ListControl<PerformanceModel>(listModel, this, UI.ListControl.ListMode.NonViewport); - this._listControl.element.addEventListener('mousemove', this._onMouseMove.bind(this), false); + this.listControl.element.addEventListener('mousemove', this.onMouseMove.bind(this), false); listModel.replaceAll(models); - UI.ARIAUtils.markAsMenu(this._listControl.element); - UI.ARIAUtils.setAccessibleName(this._listControl.element, i18nString(UIStrings.selectTimelineSession)); - contentElement.appendChild(this._listControl.element); - contentElement.addEventListener('keydown', this._onKeyDown.bind(this), false); - contentElement.addEventListener('click', this._onClick.bind(this), false); + UI.ARIAUtils.markAsMenu(this.listControl.element); + UI.ARIAUtils.setAccessibleName(this.listControl.element, i18nString(UIStrings.selectTimelineSession)); + contentElement.appendChild(this.listControl.element); + contentElement.addEventListener('keydown', this.onKeyDown.bind(this), false); + contentElement.addEventListener('click', this.onClick.bind(this), false); - this._focusRestorer = new UI.UIUtils.ElementFocusRestorer(this._listControl.element); - this._selectionDone = null; + this.focusRestorer = new UI.UIUtils.ElementFocusRestorer(this.listControl.element); + this.selectionDone = null; } static show(models: PerformanceModel[], currentModel: PerformanceModel, anchor: Element): Promise<PerformanceModel|null> { - if (DropDown._instance) { + if (DropDown.instance) { return Promise.resolve((null as PerformanceModel | null)); } const instance = new DropDown(models); - return instance._show(anchor, currentModel); + return instance.show(anchor, currentModel); } static cancelIfShowing(): void { - if (!DropDown._instance) { + if (!DropDown.instance) { return; } - DropDown._instance._close(null); + DropDown.instance.close(null); } - _show(anchor: Element, currentModel: PerformanceModel): Promise<PerformanceModel|null> { - DropDown._instance = this; - this._glassPane.setContentAnchorBox(anchor.boxInWindow()); - this._glassPane.show((this._glassPane.contentElement.ownerDocument as Document)); - this._listControl.element.focus(); - this._listControl.selectItem(currentModel); + private show(anchor: Element, currentModel: PerformanceModel): Promise<PerformanceModel|null> { + DropDown.instance = this; + this.glassPane.setContentAnchorBox(anchor.boxInWindow()); + this.glassPane.show((this.glassPane.contentElement.ownerDocument as Document)); + this.listControl.element.focus(); + this.listControl.selectItem(currentModel); return new Promise(fulfill => { - this._selectionDone = fulfill; + this.selectionDone = fulfill; }); } - _onMouseMove(event: Event): void { + private onMouseMove(event: Event): void { const node = (event.target as HTMLElement).enclosingNodeOrSelfWithClass('preview-item'); - const listItem = node && this._listControl.itemForNode(node); + const listItem = node && this.listControl.itemForNode(node); if (!listItem) { return; } - this._listControl.selectItem(listItem); + this.listControl.selectItem(listItem); } - _onClick(event: Event): void { + private onClick(event: Event): void { // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // @ts-expect-error if (!(event.target).enclosingNodeOrSelfWithClass('preview-item')) { return; } - this._close(this._listControl.selectedItem()); + this.close(this.listControl.selectedItem()); } - _onKeyDown(event: Event): void { + private onKeyDown(event: Event): void { switch ((event as KeyboardEvent).key) { case 'Tab': case 'Escape': - this._close(null); + this.close(null); break; case 'Enter': - this._close(this._listControl.selectedItem()); + this.close(this.listControl.selectedItem()); break; default: return; @@ -416,17 +414,17 @@ event.consume(true); } - _close(model: PerformanceModel|null): void { - if (this._selectionDone) { - this._selectionDone(model); + private close(model: PerformanceModel|null): void { + if (this.selectionDone) { + this.selectionDone(model); } - this._focusRestorer.restore(); - this._glassPane.hide(); - DropDown._instance = null; + this.focusRestorer.restore(); + this.glassPane.hide(); + DropDown.instance = null; } createElementForItem(item: PerformanceModel): Element { - const element = TimelineHistoryManager._previewElement(item); + const element = TimelineHistoryManager.previewElement(item); UI.ARIAUtils.markAsMenuItem(element); element.classList.remove('selected'); return element; @@ -456,18 +454,18 @@ return false; } - static _instance: DropDown|null = null; + private static instance: DropDown|null = null; } export class ToolbarButton extends UI.Toolbar.ToolbarItem { - _contentElement: HTMLElement; + private contentElement: HTMLElement; constructor(action: UI.ActionRegistration.Action) { const element = document.createElement('button'); element.classList.add('history-dropdown-button'); super(element); UI.Utils.appendStyle(this.element, 'panels/timeline/historyToolbarButton.css'); - this._contentElement = this.element.createChild('span', 'content'); + this.contentElement = this.element.createChild('span', 'content'); const dropdownArrowIcon = UI.Icon.Icon.create('smallicon-triangle-down'); this.element.appendChild(dropdownArrowIcon); this.element.addEventListener('click', () => void action.execute(), false); @@ -477,7 +475,7 @@ } setText(text: string): void { - this._contentElement.textContent = text; + this.contentElement.textContent = text; } }
diff --git a/front_end/panels/timeline/TimelineLayersView.ts b/front_end/panels/timeline/TimelineLayersView.ts index 6195a56..3cec5b0 100644 --- a/front_end/panels/timeline/TimelineLayersView.ts +++ b/front_end/panels/timeline/TimelineLayersView.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import type * as Common from '../../core/common/common.js'; import type * as SDK from '../../core/sdk/sdk.js'; import type * as TimelineModel from '../../models/timeline_model/timeline_model.js'; @@ -11,72 +9,72 @@ import * as LayerViewer from '../layer_viewer/layer_viewer.js'; export class TimelineLayersView extends UI.SplitWidget.SplitWidget { - _model: TimelineModel.TimelineModel.TimelineModelImpl; - _showPaintProfilerCallback: (arg0: SDK.PaintProfiler.PaintProfilerSnapshot) => void; - _rightSplitWidget: UI.SplitWidget.SplitWidget; - _layerViewHost: LayerViewer.LayerViewHost.LayerViewHost; - _layers3DView: LayerViewer.Layers3DView.Layers3DView; - _frameLayerTree?: TimelineModel.TimelineFrameModel.TracingFrameLayerTree; - _updateWhenVisible?: boolean; + private readonly model: TimelineModel.TimelineModel.TimelineModelImpl; + private readonly showPaintProfilerCallback: (arg0: SDK.PaintProfiler.PaintProfilerSnapshot) => void; + private readonly rightSplitWidget: UI.SplitWidget.SplitWidget; + private readonly layerViewHost: LayerViewer.LayerViewHost.LayerViewHost; + private readonly layers3DView: LayerViewer.Layers3DView.Layers3DView; + private frameLayerTree?: TimelineModel.TimelineFrameModel.TracingFrameLayerTree; + private updateWhenVisible?: boolean; constructor( model: TimelineModel.TimelineModel.TimelineModelImpl, showPaintProfilerCallback: (arg0: SDK.PaintProfiler.PaintProfilerSnapshot) => void) { super(true, false, 'timelineLayersView'); - this._model = model; - this._showPaintProfilerCallback = showPaintProfilerCallback; + this.model = model; + this.showPaintProfilerCallback = showPaintProfilerCallback; this.element.classList.add('timeline-layers-view'); - this._rightSplitWidget = new UI.SplitWidget.SplitWidget(true, true, 'timelineLayersViewDetails'); - this._rightSplitWidget.element.classList.add('timeline-layers-view-properties'); - this.setMainWidget(this._rightSplitWidget); + this.rightSplitWidget = new UI.SplitWidget.SplitWidget(true, true, 'timelineLayersViewDetails'); + this.rightSplitWidget.element.classList.add('timeline-layers-view-properties'); + this.setMainWidget(this.rightSplitWidget); const vbox = new UI.Widget.VBox(); this.setSidebarWidget(vbox); - this._layerViewHost = new LayerViewer.LayerViewHost.LayerViewHost(); + this.layerViewHost = new LayerViewer.LayerViewHost.LayerViewHost(); - const layerTreeOutline = new LayerViewer.LayerTreeOutline.LayerTreeOutline(this._layerViewHost); + const layerTreeOutline = new LayerViewer.LayerTreeOutline.LayerTreeOutline(this.layerViewHost); vbox.element.appendChild(layerTreeOutline.element); - this._layers3DView = new LayerViewer.Layers3DView.Layers3DView(this._layerViewHost); - this._layers3DView.addEventListener( - LayerViewer.Layers3DView.Events.PaintProfilerRequested, this._onPaintProfilerRequested, this); - this._rightSplitWidget.setMainWidget(this._layers3DView); + this.layers3DView = new LayerViewer.Layers3DView.Layers3DView(this.layerViewHost); + this.layers3DView.addEventListener( + LayerViewer.Layers3DView.Events.PaintProfilerRequested, this.onPaintProfilerRequested, this); + this.rightSplitWidget.setMainWidget(this.layers3DView); - const layerDetailsView = new LayerViewer.LayerDetailsView.LayerDetailsView(this._layerViewHost); - this._rightSplitWidget.setSidebarWidget(layerDetailsView); + const layerDetailsView = new LayerViewer.LayerDetailsView.LayerDetailsView(this.layerViewHost); + this.rightSplitWidget.setSidebarWidget(layerDetailsView); layerDetailsView.addEventListener( - LayerViewer.LayerDetailsView.Events.PaintProfilerRequested, this._onPaintProfilerRequested, this); + LayerViewer.LayerDetailsView.Events.PaintProfilerRequested, this.onPaintProfilerRequested, this); } showLayerTree(frameLayerTree: TimelineModel.TimelineFrameModel.TracingFrameLayerTree): void { - this._frameLayerTree = frameLayerTree; + this.frameLayerTree = frameLayerTree; if (this.isShowing()) { - this._update(); + this.update(); } else { - this._updateWhenVisible = true; + this.updateWhenVisible = true; } } wasShown(): void { - if (this._updateWhenVisible) { - this._updateWhenVisible = false; - this._update(); + if (this.updateWhenVisible) { + this.updateWhenVisible = false; + this.update(); } } - _onPaintProfilerRequested(event: Common.EventTarget.EventTargetEvent): void { + private onPaintProfilerRequested(event: Common.EventTarget.EventTargetEvent): void { const selection = (event.data as LayerViewer.LayerViewHost.Selection); - this._layers3DView.snapshotForSelection(selection).then(snapshotWithRect => { + this.layers3DView.snapshotForSelection(selection).then(snapshotWithRect => { if (snapshotWithRect) { - this._showPaintProfilerCallback(snapshotWithRect.snapshot); + this.showPaintProfilerCallback(snapshotWithRect.snapshot); } }); } - _update(): void { - if (this._frameLayerTree) { - this._frameLayerTree.layerTreePromise().then(layerTree => this._layerViewHost.setLayerTree(layerTree)); + private update(): void { + if (this.frameLayerTree) { + this.frameLayerTree.layerTreePromise().then(layerTree => this.layerViewHost.setLayerTree(layerTree)); } } }
diff --git a/front_end/panels/timeline/TimelineLoader.ts b/front_end/panels/timeline/TimelineLoader.ts index 41422c0..7c662f2 100644 --- a/front_end/panels/timeline/TimelineLoader.ts +++ b/front_end/panels/timeline/TimelineLoader.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as Host from '../../core/host/host.js'; import * as i18n from '../../core/i18n/i18n.js'; @@ -38,42 +36,42 @@ const str_ = i18n.i18n.registerUIStrings('panels/timeline/TimelineLoader.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class TimelineLoader implements Common.StringOutputStream.OutputStream { - _client: Client|null; - _backingStorage: Bindings.TempFile.TempFileBackingStorage; - _tracingModel: SDK.TracingModel.TracingModel|null; - _canceledCallback: (() => void)|null; - _state: State; - _buffer: string; - _firstRawChunk: boolean; - _firstChunk: boolean; - _loadedBytes: number; - _totalSize!: number; - _jsonTokenizer: TextUtils.TextUtils.BalancedJSONTokenizer; + private client: Client|null; + private readonly backingStorage: Bindings.TempFile.TempFileBackingStorage; + private tracingModel: SDK.TracingModel.TracingModel|null; + private canceledCallback: (() => void)|null; + private state: State; + private buffer: string; + private firstRawChunk: boolean; + private firstChunk: boolean; + private loadedBytes: number; + private totalSize!: number; + private readonly jsonTokenizer: TextUtils.TextUtils.BalancedJSONTokenizer; constructor(client: Client) { - this._client = client; + this.client = client; - this._backingStorage = new Bindings.TempFile.TempFileBackingStorage(); - this._tracingModel = new SDK.TracingModel.TracingModel(this._backingStorage); + this.backingStorage = new Bindings.TempFile.TempFileBackingStorage(); + this.tracingModel = new SDK.TracingModel.TracingModel(this.backingStorage); - this._canceledCallback = null; - this._state = State.Initial; - this._buffer = ''; - this._firstRawChunk = true; - this._firstChunk = true; - this._loadedBytes = 0; - this._jsonTokenizer = new TextUtils.TextUtils.BalancedJSONTokenizer(this._writeBalancedJSON.bind(this), true); + this.canceledCallback = null; + this.state = State.Initial; + this.buffer = ''; + this.firstRawChunk = true; + this.firstChunk = true; + this.loadedBytes = 0; + this.jsonTokenizer = new TextUtils.TextUtils.BalancedJSONTokenizer(this.writeBalancedJSON.bind(this), true); } static loadFromFile(file: File, client: Client): TimelineLoader { const loader = new TimelineLoader(client); const fileReader = new Bindings.FileUtils.ChunkedFileReader(file, TransferChunkLengthBytes); - loader._canceledCallback = fileReader.cancel.bind(fileReader); - loader._totalSize = file.size; + loader.canceledCallback = fileReader.cancel.bind(fileReader); + loader.totalSize = file.size; fileReader.read(loader).then(success => { if (!success && fileReader.error()) { // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - loader._reportErrorAndCancelLoading((fileReader.error() as any).message); + loader.reportErrorAndCancelLoading((fileReader.error() as any).message); } }); return loader; @@ -87,7 +85,7 @@ client.loadingStarted(); for (let i = 0; i < events.length; i += eventsPerChunk) { const chunk = events.slice(i, i + eventsPerChunk); - (loader._tracingModel as SDK.TracingModel.TracingModel).addEvents(chunk); + (loader.tracingModel as SDK.TracingModel.TracingModel).addEvents(chunk); client.loadingProgress((i + chunk.length) / events.length); await new Promise(r => setTimeout(r)); // Yield event loop to paint. } @@ -104,84 +102,84 @@ } cancel(): void { - this._tracingModel = null; - this._backingStorage.reset(); - if (this._client) { - this._client.loadingComplete(null); - this._client = null; + this.tracingModel = null; + this.backingStorage.reset(); + if (this.client) { + this.client.loadingComplete(null); + this.client = null; } - if (this._canceledCallback) { - this._canceledCallback(); + if (this.canceledCallback) { + this.canceledCallback(); } } async write(chunk: string): Promise<void> { - if (!this._client) { + if (!this.client) { return Promise.resolve(); } - this._loadedBytes += chunk.length; - if (this._firstRawChunk) { - await this._client.loadingStarted(); + this.loadedBytes += chunk.length; + if (this.firstRawChunk) { + await this.client.loadingStarted(); // Ensure we paint the loading dialog before continuing await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); } else { let progress = undefined; - if (this._totalSize) { - progress = this._loadedBytes / this._totalSize; + if (this.totalSize) { + progress = this.loadedBytes / this.totalSize; // For compressed traces, we can't provide a definite progress percentage. So, just keep it moving. progress = progress > 1 ? progress - Math.floor(progress) : progress; } - await this._client.loadingProgress(progress); + await this.client.loadingProgress(progress); } - this._firstRawChunk = false; + this.firstRawChunk = false; - if (this._state === State.Initial) { + if (this.state === State.Initial) { if (chunk.startsWith('{"nodes":[')) { - this._state = State.LoadingCPUProfileFormat; + this.state = State.LoadingCPUProfileFormat; } else if (chunk[0] === '{') { - this._state = State.LookingForEvents; + this.state = State.LookingForEvents; } else if (chunk[0] === '[') { - this._state = State.ReadingEvents; + this.state = State.ReadingEvents; } else { - this._reportErrorAndCancelLoading(i18nString(UIStrings.malformedTimelineDataUnknownJson)); + this.reportErrorAndCancelLoading(i18nString(UIStrings.malformedTimelineDataUnknownJson)); return Promise.resolve(); } } - if (this._state === State.LoadingCPUProfileFormat) { - this._buffer += chunk; + if (this.state === State.LoadingCPUProfileFormat) { + this.buffer += chunk; return Promise.resolve(); } - if (this._state === State.LookingForEvents) { + if (this.state === State.LookingForEvents) { const objectName = '"traceEvents":'; - const startPos = this._buffer.length - objectName.length; - this._buffer += chunk; - const pos = this._buffer.indexOf(objectName, startPos); + const startPos = this.buffer.length - objectName.length; + this.buffer += chunk; + const pos = this.buffer.indexOf(objectName, startPos); if (pos === -1) { return Promise.resolve(); } - chunk = this._buffer.slice(pos + objectName.length); - this._state = State.ReadingEvents; + chunk = this.buffer.slice(pos + objectName.length); + this.state = State.ReadingEvents; } - if (this._state !== State.ReadingEvents) { + if (this.state !== State.ReadingEvents) { return Promise.resolve(); } - if (this._jsonTokenizer.write(chunk)) { + if (this.jsonTokenizer.write(chunk)) { return Promise.resolve(); } - this._state = State.SkippingTail; - if (this._firstChunk) { - this._reportErrorAndCancelLoading(i18nString(UIStrings.malformedTimelineInputWrongJson)); + this.state = State.SkippingTail; + if (this.firstChunk) { + this.reportErrorAndCancelLoading(i18nString(UIStrings.malformedTimelineInputWrongJson)); } return Promise.resolve(); } - _writeBalancedJSON(data: string): void { + private writeBalancedJSON(data: string): void { let json: string = data + ']'; - if (!this._firstChunk) { + if (!this.firstChunk) { const commaIndex = json.indexOf(','); if (commaIndex !== -1) { json = json.slice(commaIndex + 1); @@ -193,26 +191,26 @@ try { items = (JSON.parse(json) as SDK.TracingManager.EventPayload[]); } catch (e) { - this._reportErrorAndCancelLoading(i18nString(UIStrings.malformedTimelineDataS, {PH1: e.toString()})); + this.reportErrorAndCancelLoading(i18nString(UIStrings.malformedTimelineDataS, {PH1: e.toString()})); return; } - if (this._firstChunk) { - this._firstChunk = false; - if (this._looksLikeAppVersion(items[0])) { - this._reportErrorAndCancelLoading(i18nString(UIStrings.legacyTimelineFormatIsNot)); + if (this.firstChunk) { + this.firstChunk = false; + if (this.looksLikeAppVersion(items[0])) { + this.reportErrorAndCancelLoading(i18nString(UIStrings.legacyTimelineFormatIsNot)); return; } } try { - (this._tracingModel as SDK.TracingModel.TracingModel).addEvents(items); + (this.tracingModel as SDK.TracingModel.TracingModel).addEvents(items); } catch (e) { - this._reportErrorAndCancelLoading(i18nString(UIStrings.malformedTimelineDataS, {PH1: e.toString()})); + this.reportErrorAndCancelLoading(i18nString(UIStrings.malformedTimelineDataS, {PH1: e.toString()})); } } - _reportErrorAndCancelLoading(message?: string): void { + private reportErrorAndCancelLoading(message?: string): void { if (message) { Common.Console.Console.instance().error(message); } @@ -221,38 +219,38 @@ // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _looksLikeAppVersion(item: any): boolean { + private looksLikeAppVersion(item: any): boolean { return typeof item === 'string' && item.indexOf('Chrome') !== -1; } async close(): Promise<void> { - if (!this._client) { + if (!this.client) { return; } - this._client.processingStarted(); - setTimeout(() => this._finalizeTrace(), 0); + this.client.processingStarted(); + setTimeout(() => this.finalizeTrace(), 0); } - _finalizeTrace(): void { - if (this._state === State.LoadingCPUProfileFormat) { - this._parseCPUProfileFormat(this._buffer); - this._buffer = ''; + private finalizeTrace(): void { + if (this.state === State.LoadingCPUProfileFormat) { + this.parseCPUProfileFormat(this.buffer); + this.buffer = ''; } - (this._tracingModel as SDK.TracingModel.TracingModel).tracingComplete(); - (this._client as Client).loadingComplete(this._tracingModel); + (this.tracingModel as SDK.TracingModel.TracingModel).tracingComplete(); + (this.client as Client).loadingComplete(this.tracingModel); } - _parseCPUProfileFormat(text: string): void { + private parseCPUProfileFormat(text: string): void { let traceEvents; try { const profile = JSON.parse(text); traceEvents = TimelineModel.TimelineJSProfile.TimelineJSProfileProcessor.buildTraceProfileFromCpuProfile( profile, /* tid */ 1, /* injectPageEvent */ true); } catch (e) { - this._reportErrorAndCancelLoading(i18nString(UIStrings.malformedCpuProfileFormat)); + this.reportErrorAndCancelLoading(i18nString(UIStrings.malformedCpuProfileFormat)); return; } - (this._tracingModel as SDK.TracingModel.TracingModel).addEvents(traceEvents); + (this.tracingModel as SDK.TracingModel.TracingModel).addEvents(traceEvents); } }
diff --git a/front_end/panels/timeline/TimelinePaintProfilerView.ts b/front_end/panels/timeline/TimelinePaintProfilerView.ts index 4e089f2..0949f3e 100644 --- a/front_end/panels/timeline/TimelinePaintProfilerView.ts +++ b/front_end/panels/timeline/TimelinePaintProfilerView.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import type * as SDK from '../../core/sdk/sdk.js'; import * as TimelineModel from '../../models/timeline_model/timeline_model.js'; import * as UI from '../../ui/legacy/legacy.js'; @@ -11,172 +9,172 @@ import type * as Protocol from '../../generated/protocol.js'; export class TimelinePaintProfilerView extends UI.SplitWidget.SplitWidget { - _frameModel: TimelineModel.TimelineFrameModel.TimelineFrameModel; - _logAndImageSplitWidget: UI.SplitWidget.SplitWidget; - _imageView: TimelinePaintImageView; - _paintProfilerView: LayerViewer.PaintProfilerView.PaintProfilerView; - _logTreeView: LayerViewer.PaintProfilerView.PaintProfilerCommandLogView; - _needsUpdateWhenVisible: boolean; - _pendingSnapshot: SDK.PaintProfiler.PaintProfilerSnapshot|null; - _event: SDK.TracingModel.Event|null; - _paintProfilerModel: SDK.PaintProfiler.PaintProfilerModel|null; - _lastLoadedSnapshot: SDK.PaintProfiler.PaintProfilerSnapshot|null; + private frameModel: TimelineModel.TimelineFrameModel.TimelineFrameModel; + private readonly logAndImageSplitWidget: UI.SplitWidget.SplitWidget; + private readonly imageView: TimelinePaintImageView; + private readonly paintProfilerView: LayerViewer.PaintProfilerView.PaintProfilerView; + private readonly logTreeView: LayerViewer.PaintProfilerView.PaintProfilerCommandLogView; + private needsUpdateWhenVisible: boolean; + private pendingSnapshot: SDK.PaintProfiler.PaintProfilerSnapshot|null; + private event: SDK.TracingModel.Event|null; + private paintProfilerModel: SDK.PaintProfiler.PaintProfilerModel|null; + private lastLoadedSnapshot: SDK.PaintProfiler.PaintProfilerSnapshot|null; constructor(frameModel: TimelineModel.TimelineFrameModel.TimelineFrameModel) { super(false, false); this.element.classList.add('timeline-paint-profiler-view'); this.setSidebarSize(60); this.setResizable(false); - this._frameModel = frameModel; - this._logAndImageSplitWidget = new UI.SplitWidget.SplitWidget(true, false); - this._logAndImageSplitWidget.element.classList.add('timeline-paint-profiler-log-split'); - this.setMainWidget(this._logAndImageSplitWidget); - this._imageView = new TimelinePaintImageView(); - this._logAndImageSplitWidget.setMainWidget(this._imageView); + this.frameModel = frameModel; + this.logAndImageSplitWidget = new UI.SplitWidget.SplitWidget(true, false); + this.logAndImageSplitWidget.element.classList.add('timeline-paint-profiler-log-split'); + this.setMainWidget(this.logAndImageSplitWidget); + this.imageView = new TimelinePaintImageView(); + this.logAndImageSplitWidget.setMainWidget(this.imageView); - this._paintProfilerView = - new LayerViewer.PaintProfilerView.PaintProfilerView(this._imageView.showImage.bind(this._imageView)); - this._paintProfilerView.addEventListener( - LayerViewer.PaintProfilerView.Events.WindowChanged, this._onWindowChanged, this); - this.setSidebarWidget(this._paintProfilerView); + this.paintProfilerView = + new LayerViewer.PaintProfilerView.PaintProfilerView(this.imageView.showImage.bind(this.imageView)); + this.paintProfilerView.addEventListener( + LayerViewer.PaintProfilerView.Events.WindowChanged, this.onWindowChanged, this); + this.setSidebarWidget(this.paintProfilerView); - this._logTreeView = new LayerViewer.PaintProfilerView.PaintProfilerCommandLogView(); - this._logAndImageSplitWidget.setSidebarWidget(this._logTreeView); + this.logTreeView = new LayerViewer.PaintProfilerView.PaintProfilerCommandLogView(); + this.logAndImageSplitWidget.setSidebarWidget(this.logTreeView); - this._needsUpdateWhenVisible = false; - this._pendingSnapshot = null; - this._event = null; - this._paintProfilerModel = null; - this._lastLoadedSnapshot = null; + this.needsUpdateWhenVisible = false; + this.pendingSnapshot = null; + this.event = null; + this.paintProfilerModel = null; + this.lastLoadedSnapshot = null; } wasShown(): void { - if (this._needsUpdateWhenVisible) { - this._needsUpdateWhenVisible = false; - this._update(); + if (this.needsUpdateWhenVisible) { + this.needsUpdateWhenVisible = false; + this.update(); } } setSnapshot(snapshot: SDK.PaintProfiler.PaintProfilerSnapshot): void { - this._releaseSnapshot(); - this._pendingSnapshot = snapshot; - this._event = null; - this._updateWhenVisible(); + this.releaseSnapshot(); + this.pendingSnapshot = snapshot; + this.event = null; + this.updateWhenVisible(); } setEvent(paintProfilerModel: SDK.PaintProfiler.PaintProfilerModel, event: SDK.TracingModel.Event): boolean { - this._releaseSnapshot(); - this._paintProfilerModel = paintProfilerModel; - this._pendingSnapshot = null; - this._event = event; + this.releaseSnapshot(); + this.paintProfilerModel = paintProfilerModel; + this.pendingSnapshot = null; + this.event = event; - this._updateWhenVisible(); - if (this._event.name === TimelineModel.TimelineModel.RecordType.Paint) { + this.updateWhenVisible(); + if (this.event.name === TimelineModel.TimelineModel.RecordType.Paint) { return Boolean(TimelineModel.TimelineModel.TimelineData.forEvent(event).picture); } - if (this._event.name === TimelineModel.TimelineModel.RecordType.RasterTask) { - return this._frameModel.hasRasterTile(this._event); + if (this.event.name === TimelineModel.TimelineModel.RecordType.RasterTask) { + return this.frameModel.hasRasterTile(this.event); } return false; } - _updateWhenVisible(): void { + private updateWhenVisible(): void { if (this.isShowing()) { - this._update(); + this.update(); } else { - this._needsUpdateWhenVisible = true; + this.needsUpdateWhenVisible = true; } } - _update(): void { - this._logTreeView.setCommandLog([]); - this._paintProfilerView.setSnapshotAndLog(null, [], null); + private update(): void { + this.logTreeView.setCommandLog([]); + this.paintProfilerView.setSnapshotAndLog(null, [], null); let snapshotPromise: Promise<{ rect: Protocol.DOM.Rect | null, snapshot: SDK.PaintProfiler.PaintProfilerSnapshot, }|null>; - if (this._pendingSnapshot) { - snapshotPromise = Promise.resolve({rect: null, snapshot: this._pendingSnapshot}); - } else if (this._event && this._event.name === TimelineModel.TimelineModel.RecordType.Paint) { + if (this.pendingSnapshot) { + snapshotPromise = Promise.resolve({rect: null, snapshot: this.pendingSnapshot}); + } else if (this.event && this.event.name === TimelineModel.TimelineModel.RecordType.Paint) { const picture = - (TimelineModel.TimelineModel.TimelineData.forEvent(this._event).picture as SDK.TracingModel.ObjectSnapshot); + (TimelineModel.TimelineModel.TimelineData.forEvent(this.event).picture as SDK.TracingModel.ObjectSnapshot); snapshotPromise = picture.objectPromise() .then( data => // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // @ts-expect-error - (this._paintProfilerModel as SDK.PaintProfiler.PaintProfilerModel).loadSnapshot(data['skp64'])) + (this.paintProfilerModel as SDK.PaintProfiler.PaintProfilerModel).loadSnapshot(data['skp64'])) .then(snapshot => snapshot && {rect: null, snapshot: snapshot}); - } else if (this._event && this._event.name === TimelineModel.TimelineModel.RecordType.RasterTask) { - snapshotPromise = this._frameModel.rasterTilePromise(this._event); + } else if (this.event && this.event.name === TimelineModel.TimelineModel.RecordType.RasterTask) { + snapshotPromise = this.frameModel.rasterTilePromise(this.event); } else { console.assert(false, 'Unexpected event type or no snapshot'); return; } snapshotPromise.then(snapshotWithRect => { - this._releaseSnapshot(); + this.releaseSnapshot(); if (!snapshotWithRect) { - this._imageView.showImage(); + this.imageView.showImage(); return; } const snapshot = snapshotWithRect.snapshot; - this._lastLoadedSnapshot = snapshot; - this._imageView.setMask(snapshotWithRect.rect); + this.lastLoadedSnapshot = snapshot; + this.imageView.setMask(snapshotWithRect.rect); snapshot.commandLog().then(log => onCommandLogDone.call(this, snapshot, snapshotWithRect.rect, log || [])); }); function onCommandLogDone( this: TimelinePaintProfilerView, snapshot: SDK.PaintProfiler.PaintProfilerSnapshot, clipRect: Protocol.DOM.Rect|null, log?: SDK.PaintProfiler.PaintProfilerLogItem[]): void { - this._logTreeView.setCommandLog(log || []); - this._paintProfilerView.setSnapshotAndLog(snapshot, log || [], clipRect); + this.logTreeView.setCommandLog(log || []); + this.paintProfilerView.setSnapshotAndLog(snapshot, log || [], clipRect); } } - _releaseSnapshot(): void { - if (!this._lastLoadedSnapshot) { + private releaseSnapshot(): void { + if (!this.lastLoadedSnapshot) { return; } - this._lastLoadedSnapshot.release(); - this._lastLoadedSnapshot = null; + this.lastLoadedSnapshot.release(); + this.lastLoadedSnapshot = null; } - _onWindowChanged(): void { - this._logTreeView.updateWindow(this._paintProfilerView.selectionWindow()); + private onWindowChanged(): void { + this.logTreeView.updateWindow(this.paintProfilerView.selectionWindow()); } } export class TimelinePaintImageView extends UI.Widget.Widget { - _imageContainer: HTMLElement; - _imageElement: HTMLImageElement; - _maskElement: HTMLElement; - _transformController: LayerViewer.TransformController.TransformController; - _maskRectangle?: Protocol.DOM.Rect|null; + private imageContainer: HTMLElement; + private imageElement: HTMLImageElement; + private readonly maskElement: HTMLElement; + private transformController: LayerViewer.TransformController.TransformController; + private maskRectangle?: Protocol.DOM.Rect|null; constructor() { super(true); this.registerRequiredCSS('panels/timeline/timelinePaintProfiler.css'); this.contentElement.classList.add('fill', 'paint-profiler-image-view'); - this._imageContainer = this.contentElement.createChild('div', 'paint-profiler-image-container'); - this._imageElement = (this._imageContainer.createChild('img') as HTMLImageElement); - this._maskElement = this._imageContainer.createChild('div'); - this._imageElement.addEventListener('load', this._updateImagePosition.bind(this), false); - this._transformController = + this.imageContainer = this.contentElement.createChild('div', 'paint-profiler-image-container'); + this.imageElement = (this.imageContainer.createChild('img') as HTMLImageElement); + this.maskElement = this.imageContainer.createChild('div'); + this.imageElement.addEventListener('load', this.updateImagePosition.bind(this), false); + this.transformController = new LayerViewer.TransformController.TransformController((this.contentElement as HTMLElement), true); - this._transformController.addEventListener( - LayerViewer.TransformController.Events.TransformChanged, this._updateImagePosition, this); + this.transformController.addEventListener( + LayerViewer.TransformController.Events.TransformChanged, this.updateImagePosition, this); } onResize(): void { - if (this._imageElement.src) { - this._updateImagePosition(); + if (this.imageElement.src) { + this.updateImagePosition(); } } - _updateImagePosition(): void { - const width = this._imageElement.naturalWidth; - const height = this._imageElement.naturalHeight; + private updateImagePosition(): void { + const width = this.imageElement.naturalWidth; + const height = this.imageElement.naturalHeight; const clientWidth = this.contentElement.clientWidth; const clientHeight = this.contentElement.clientHeight; @@ -187,40 +185,40 @@ const scaleY = (clientHeight - paddingY) / height; const scale = Math.min(scaleX, scaleY); - if (this._maskRectangle) { - const style = this._maskElement.style; + if (this.maskRectangle) { + const style = this.maskElement.style; style.width = width + 'px'; style.height = height + 'px'; - style.borderLeftWidth = this._maskRectangle.x + 'px'; - style.borderTopWidth = this._maskRectangle.y + 'px'; - style.borderRightWidth = (width - this._maskRectangle.x - this._maskRectangle.width) + 'px'; - style.borderBottomWidth = (height - this._maskRectangle.y - this._maskRectangle.height) + 'px'; + style.borderLeftWidth = this.maskRectangle.x + 'px'; + style.borderTopWidth = this.maskRectangle.y + 'px'; + style.borderRightWidth = (width - this.maskRectangle.x - this.maskRectangle.width) + 'px'; + style.borderBottomWidth = (height - this.maskRectangle.y - this.maskRectangle.height) + 'px'; } - this._transformController.setScaleConstraints(0.5, 10 / scale); + this.transformController.setScaleConstraints(0.5, 10 / scale); let matrix = new WebKitCSSMatrix() - .scale(this._transformController.scale(), this._transformController.scale()) + .scale(this.transformController.scale(), this.transformController.scale()) .translate(clientWidth / 2, clientHeight / 2) .scale(scale, scale) .translate(-width / 2, -height / 2); const bounds = UI.Geometry.boundsForTransformedPoints(matrix, [0, 0, 0, width, height, 0]); - this._transformController.clampOffsets( + this.transformController.clampOffsets( paddingX - bounds.maxX, clientWidth - paddingX - bounds.minX, paddingY - bounds.maxY, clientHeight - paddingY - bounds.minY); matrix = new WebKitCSSMatrix() - .translate(this._transformController.offsetX(), this._transformController.offsetY()) + .translate(this.transformController.offsetX(), this.transformController.offsetY()) .multiply(matrix); - this._imageContainer.style.webkitTransform = matrix.toString(); + this.imageContainer.style.webkitTransform = matrix.toString(); } showImage(imageURL?: string): void { - this._imageContainer.classList.toggle('hidden', !imageURL); + this.imageContainer.classList.toggle('hidden', !imageURL); if (imageURL) { - this._imageElement.src = imageURL; + this.imageElement.src = imageURL; } } setMask(maskRectangle: Protocol.DOM.Rect|null): void { - this._maskRectangle = maskRectangle; - this._maskElement.classList.toggle('hidden', !maskRectangle); + this.maskRectangle = maskRectangle; + this.maskElement.classList.toggle('hidden', !maskRectangle); } }
diff --git a/front_end/panels/timeline/TimelinePanel.ts b/front_end/panels/timeline/TimelinePanel.ts index 6381bea..36d298d 100644 --- a/front_end/panels/timeline/TimelinePanel.ts +++ b/front_end/panels/timeline/TimelinePanel.ts
@@ -33,8 +33,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as Host from '../../core/host/host.js'; import * as i18n from '../../core/i18n/i18n.js'; @@ -257,157 +255,157 @@ let timelinePanelInstance: TimelinePanel; export class TimelinePanel extends UI.Panel.Panel implements Client, TimelineModeViewDelegate { - _dropTarget: UI.DropTarget.DropTarget; - _recordingOptionUIControls: UI.Toolbar.ToolbarItem[]; - _state: State; - _recordingPageReload: boolean; - _millisecondsToRecordAfterLoadEvent: number; - _toggleRecordAction: UI.ActionRegistration.Action; - _recordReloadAction: UI.ActionRegistration.Action; - _historyManager: TimelineHistoryManager; - _performanceModel: PerformanceModel|null; + private readonly dropTarget: UI.DropTarget.DropTarget; + private readonly recordingOptionUIControls: UI.Toolbar.ToolbarItem[]; + private state: State; + private recordingPageReload: boolean; + private readonly millisecondsToRecordAfterLoadEvent: number; + private readonly toggleRecordAction: UI.ActionRegistration.Action; + private readonly recordReloadAction: UI.ActionRegistration.Action; + private readonly historyManager: TimelineHistoryManager; + private performanceModel: PerformanceModel|null; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _viewModeSetting: Common.Settings.Setting<any>; + private readonly viewModeSetting: Common.Settings.Setting<any>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _disableCaptureJSProfileSetting: Common.Settings.Setting<any>; + private disableCaptureJSProfileSetting: Common.Settings.Setting<any>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _captureLayersAndPicturesSetting: Common.Settings.Setting<any>; + private readonly captureLayersAndPicturesSetting: Common.Settings.Setting<any>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _showScreenshotsSetting: Common.Settings.Setting<any>; + private showScreenshotsSetting: Common.Settings.Setting<any>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _startCoverage: Common.Settings.Setting<any>; + private startCoverage: Common.Settings.Setting<any>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _showMemorySetting: Common.Settings.Setting<any>; + private showMemorySetting: Common.Settings.Setting<any>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _showWebVitalsSetting: Common.Settings.Setting<any>; - _panelToolbar: UI.Toolbar.Toolbar; - _panelRightToolbar: UI.Toolbar.Toolbar; - _timelinePane: UI.Widget.VBox; - _overviewPane: PerfUI.TimelineOverviewPane.TimelineOverviewPane; - _overviewControls: TimelineEventOverview[]; - _statusPaneContainer: HTMLElement; - _flameChart: TimelineFlameChartView; - _searchableView: UI.SearchableView.SearchableView; - _showSettingsPaneButton!: UI.Toolbar.ToolbarSettingToggle; - _showSettingsPaneSetting!: Common.Settings.Setting<boolean>; - _settingsPane!: UI.Widget.Widget; - _controller!: TimelineController|null; - _clearButton!: UI.Toolbar.ToolbarButton; - _loadButton!: UI.Toolbar.ToolbarButton; - _saveButton!: UI.Toolbar.ToolbarButton; - _statusPane!: StatusPane|null; - _landingPage!: UI.Widget.Widget; - _loader?: TimelineLoader; - _showScreenshotsToolbarCheckbox?: UI.Toolbar.ToolbarItem; - _showMemoryToolbarCheckbox?: UI.Toolbar.ToolbarItem; - _showWebVitalsToolbarCheckbox?: UI.Toolbar.ToolbarItem; - _startCoverageCheckbox?: UI.Toolbar.ToolbarItem; - _networkThrottlingSelect?: UI.Toolbar.ToolbarComboBox; - _cpuThrottlingSelect?: UI.Toolbar.ToolbarComboBox; - _fileSelectorElement?: HTMLInputElement; - _selection?: TimelineSelection|null; + private showWebVitalsSetting: Common.Settings.Setting<any>; + private readonly panelToolbar: UI.Toolbar.Toolbar; + private readonly panelRightToolbar: UI.Toolbar.Toolbar; + private readonly timelinePane: UI.Widget.VBox; + private readonly overviewPane: PerfUI.TimelineOverviewPane.TimelineOverviewPane; + private overviewControls: TimelineEventOverview[]; + private readonly statusPaneContainer: HTMLElement; + private readonly flameChart: TimelineFlameChartView; + private readonly searchableViewInternal: UI.SearchableView.SearchableView; + private showSettingsPaneButton!: UI.Toolbar.ToolbarSettingToggle; + private showSettingsPaneSetting!: Common.Settings.Setting<boolean>; + private settingsPane!: UI.Widget.Widget; + private controller!: TimelineController|null; + private clearButton!: UI.Toolbar.ToolbarButton; + private loadButton!: UI.Toolbar.ToolbarButton; + private saveButton!: UI.Toolbar.ToolbarButton; + private statusPane!: StatusPane|null; + private landingPage!: UI.Widget.Widget; + private loader?: TimelineLoader; + private showScreenshotsToolbarCheckbox?: UI.Toolbar.ToolbarItem; + private showMemoryToolbarCheckbox?: UI.Toolbar.ToolbarItem; + private showWebVitalsToolbarCheckbox?: UI.Toolbar.ToolbarItem; + private startCoverageCheckbox?: UI.Toolbar.ToolbarItem; + private networkThrottlingSelect?: UI.Toolbar.ToolbarComboBox; + private cpuThrottlingSelect?: UI.Toolbar.ToolbarComboBox; + private fileSelectorElement?: HTMLInputElement; + private selection?: TimelineSelection|null; constructor() { super('timeline'); this.registerRequiredCSS('panels/timeline/timelinePanel.css'); - this.element.addEventListener('contextmenu', this._contextMenu.bind(this), false); - this._dropTarget = new UI.DropTarget.DropTarget( + this.element.addEventListener('contextmenu', this.contextMenu.bind(this), false); + this.dropTarget = new UI.DropTarget.DropTarget( this.element, [UI.DropTarget.Type.File, UI.DropTarget.Type.URI], - i18nString(UIStrings.dropTimelineFileOrUrlHere), this._handleDrop.bind(this)); + i18nString(UIStrings.dropTimelineFileOrUrlHere), this.handleDrop.bind(this)); - this._recordingOptionUIControls = []; - this._state = State.Idle; - this._recordingPageReload = false; - this._millisecondsToRecordAfterLoadEvent = 5000; - this._toggleRecordAction = + this.recordingOptionUIControls = []; + this.state = State.Idle; + this.recordingPageReload = false; + this.millisecondsToRecordAfterLoadEvent = 5000; + this.toggleRecordAction = (UI.ActionRegistry.ActionRegistry.instance().action('timeline.toggle-recording') as UI.ActionRegistration.Action); - this._recordReloadAction = + this.recordReloadAction = (UI.ActionRegistry.ActionRegistry.instance().action('timeline.record-reload') as UI.ActionRegistration.Action); - this._historyManager = new TimelineHistoryManager(); + this.historyManager = new TimelineHistoryManager(); - this._performanceModel = null; + this.performanceModel = null; - this._viewModeSetting = Common.Settings.Settings.instance().createSetting('timelineViewMode', ViewMode.FlameChart); + this.viewModeSetting = Common.Settings.Settings.instance().createSetting('timelineViewMode', ViewMode.FlameChart); - this._disableCaptureJSProfileSetting = + this.disableCaptureJSProfileSetting = Common.Settings.Settings.instance().createSetting('timelineDisableJSSampling', false); - this._disableCaptureJSProfileSetting.setTitle(i18nString(UIStrings.disableJavascriptSamples)); - this._captureLayersAndPicturesSetting = + this.disableCaptureJSProfileSetting.setTitle(i18nString(UIStrings.disableJavascriptSamples)); + this.captureLayersAndPicturesSetting = Common.Settings.Settings.instance().createSetting('timelineCaptureLayersAndPictures', false); - this._captureLayersAndPicturesSetting.setTitle(i18nString(UIStrings.enableAdvancedPaint)); + this.captureLayersAndPicturesSetting.setTitle(i18nString(UIStrings.enableAdvancedPaint)); - this._showScreenshotsSetting = Common.Settings.Settings.instance().createSetting('timelineShowScreenshots', true); - this._showScreenshotsSetting.setTitle(i18nString(UIStrings.screenshots)); - this._showScreenshotsSetting.addChangeListener(this._updateOverviewControls, this); + this.showScreenshotsSetting = Common.Settings.Settings.instance().createSetting('timelineShowScreenshots', true); + this.showScreenshotsSetting.setTitle(i18nString(UIStrings.screenshots)); + this.showScreenshotsSetting.addChangeListener(this.updateOverviewControls, this); - this._startCoverage = Common.Settings.Settings.instance().createSetting('timelineStartCoverage', false); - this._startCoverage.setTitle(i18nString(UIStrings.coverage)); + this.startCoverage = Common.Settings.Settings.instance().createSetting('timelineStartCoverage', false); + this.startCoverage.setTitle(i18nString(UIStrings.coverage)); if (!Root.Runtime.experiments.isEnabled('recordCoverageWithPerformanceTracing')) { - this._startCoverage.set(false); + this.startCoverage.set(false); } - this._showMemorySetting = Common.Settings.Settings.instance().createSetting('timelineShowMemory', false); - this._showMemorySetting.setTitle(i18nString(UIStrings.memory)); - this._showMemorySetting.addChangeListener(this._onModeChanged, this); + this.showMemorySetting = Common.Settings.Settings.instance().createSetting('timelineShowMemory', false); + this.showMemorySetting.setTitle(i18nString(UIStrings.memory)); + this.showMemorySetting.addChangeListener(this.onModeChanged, this); - this._showWebVitalsSetting = Common.Settings.Settings.instance().createSetting('timelineWebVitals', false); - this._showWebVitalsSetting.setTitle(i18nString(UIStrings.webVitals)); - this._showWebVitalsSetting.addChangeListener(this._onWebVitalsChanged, this); + this.showWebVitalsSetting = Common.Settings.Settings.instance().createSetting('timelineWebVitals', false); + this.showWebVitalsSetting.setTitle(i18nString(UIStrings.webVitals)); + this.showWebVitalsSetting.addChangeListener(this.onWebVitalsChanged, this); const timelineToolbarContainer = this.element.createChild('div', 'timeline-toolbar-container'); - this._panelToolbar = new UI.Toolbar.Toolbar('timeline-main-toolbar', timelineToolbarContainer); - this._panelToolbar.makeWrappable(true); - this._panelRightToolbar = new UI.Toolbar.Toolbar('', timelineToolbarContainer); - this._createSettingsPane(); - this._updateShowSettingsToolbarButton(); + this.panelToolbar = new UI.Toolbar.Toolbar('timeline-main-toolbar', timelineToolbarContainer); + this.panelToolbar.makeWrappable(true); + this.panelRightToolbar = new UI.Toolbar.Toolbar('', timelineToolbarContainer); + this.createSettingsPane(); + this.updateShowSettingsToolbarButton(); - this._timelinePane = new UI.Widget.VBox(); - this._timelinePane.show(this.element); - const topPaneElement = this._timelinePane.element.createChild('div', 'hbox'); + this.timelinePane = new UI.Widget.VBox(); + this.timelinePane.show(this.element); + const topPaneElement = this.timelinePane.element.createChild('div', 'hbox'); topPaneElement.id = 'timeline-overview-panel'; // Create top overview component. - this._overviewPane = new PerfUI.TimelineOverviewPane.TimelineOverviewPane('timeline'); - this._overviewPane.addEventListener( - PerfUI.TimelineOverviewPane.Events.WindowChanged, this._onOverviewWindowChanged.bind(this)); - this._overviewPane.show(topPaneElement); - this._overviewControls = []; + this.overviewPane = new PerfUI.TimelineOverviewPane.TimelineOverviewPane('timeline'); + this.overviewPane.addEventListener( + PerfUI.TimelineOverviewPane.Events.WindowChanged, this.onOverviewWindowChanged.bind(this)); + this.overviewPane.show(topPaneElement); + this.overviewControls = []; - this._statusPaneContainer = this._timelinePane.element.createChild('div', 'status-pane-container fill'); + this.statusPaneContainer = this.timelinePane.element.createChild('div', 'status-pane-container fill'); - this._createFileSelector(); + this.createFileSelector(); SDK.TargetManager.TargetManager.instance().addModelListener( - SDK.ResourceTreeModel.ResourceTreeModel, SDK.ResourceTreeModel.Events.Load, this._loadEventFired, this); + SDK.ResourceTreeModel.ResourceTreeModel, SDK.ResourceTreeModel.Events.Load, this.loadEventFired, this); - this._flameChart = new TimelineFlameChartView(this); - this._searchableView = new UI.SearchableView.SearchableView(this._flameChart, null); - this._searchableView.setMinimumSize(0, 100); - this._searchableView.element.classList.add('searchable-view'); - this._searchableView.show(this._timelinePane.element); - this._flameChart.show(this._searchableView.element); - this._flameChart.setSearchableView(this._searchableView); - this._searchableView.hideWidget(); + this.flameChart = new TimelineFlameChartView(this); + this.searchableViewInternal = new UI.SearchableView.SearchableView(this.flameChart, null); + this.searchableViewInternal.setMinimumSize(0, 100); + this.searchableViewInternal.element.classList.add('searchable-view'); + this.searchableViewInternal.show(this.timelinePane.element); + this.flameChart.show(this.searchableViewInternal.element); + this.flameChart.setSearchableView(this.searchableViewInternal); + this.searchableViewInternal.hideWidget(); - this._onModeChanged(); - this._onWebVitalsChanged(); - this._populateToolbar(); - this._showLandingPage(); - this._updateTimelineControls(); + this.onModeChanged(); + this.onWebVitalsChanged(); + this.populateToolbar(); + this.showLandingPage(); + this.updateTimelineControls(); Extensions.ExtensionServer.ExtensionServer.instance().addEventListener( - Extensions.ExtensionServer.Events.TraceProviderAdded, this._appendExtensionsToToolbar, this); + Extensions.ExtensionServer.Events.TraceProviderAdded, this.appendExtensionsToToolbar, this); SDK.TargetManager.TargetManager.instance().addEventListener( - SDK.TargetManager.Events.SuspendStateChanged, this._onSuspendStateChanged, this); + SDK.TargetManager.Events.SuspendStateChanged, this.onSuspendStateChanged, this); } static instance(opts: { @@ -422,7 +420,7 @@ } searchableView(): UI.SearchableView.SearchableView|null { - return this._searchableView; + return this.searchableViewInternal; } wasShown(): void { @@ -433,151 +431,151 @@ willHide(): void { UI.Context.Context.instance().setFlavor(TimelinePanel, null); - this._historyManager.cancelIfShowing(); + this.historyManager.cancelIfShowing(); } loadFromEvents(events: SDK.TracingManager.EventPayload[]): void { - if (this._state !== State.Idle) { + if (this.state !== State.Idle) { return; } - this._prepareToLoadTimeline(); - this._loader = TimelineLoader.loadFromEvents(events, this); + this.prepareToLoadTimeline(); + this.loader = TimelineLoader.loadFromEvents(events, this); } - _onOverviewWindowChanged(event: Common.EventTarget.EventTargetEvent): void { - if (!this._performanceModel) { + private onOverviewWindowChanged(event: Common.EventTarget.EventTargetEvent): void { + if (!this.performanceModel) { return; } const left = event.data.startTime; const right = event.data.endTime; - this._performanceModel.setWindow({left, right}, /* animate */ true); + this.performanceModel.setWindow({left, right}, /* animate */ true); } - _onModelWindowChanged(event: Common.EventTarget.EventTargetEvent): void { + private onModelWindowChanged(event: Common.EventTarget.EventTargetEvent): void { const window = (event.data.window as Window); - this._overviewPane.setWindowTimes(window.left, window.right); + this.overviewPane.setWindowTimes(window.left, window.right); } - _setState(state: State): void { - this._state = state; - this._updateTimelineControls(); + private setState(state: State): void { + this.state = state; + this.updateTimelineControls(); } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _createSettingCheckbox(setting: Common.Settings.Setting<any>, tooltip: string): UI.Toolbar.ToolbarItem { + private createSettingCheckbox(setting: Common.Settings.Setting<any>, tooltip: string): UI.Toolbar.ToolbarItem { const checkboxItem = new UI.Toolbar.ToolbarSettingCheckbox(setting, tooltip); - this._recordingOptionUIControls.push(checkboxItem); + this.recordingOptionUIControls.push(checkboxItem); return checkboxItem; } - _populateToolbar(): void { + private populateToolbar(): void { // Record - this._panelToolbar.appendToolbarItem(UI.Toolbar.Toolbar.createActionButton(this._toggleRecordAction)); - this._panelToolbar.appendToolbarItem(UI.Toolbar.Toolbar.createActionButton(this._recordReloadAction)); - this._clearButton = new UI.Toolbar.ToolbarButton(i18nString(UIStrings.clear), 'largeicon-clear'); - this._clearButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, () => this._onClearButton()); - this._panelToolbar.appendToolbarItem(this._clearButton); + this.panelToolbar.appendToolbarItem(UI.Toolbar.Toolbar.createActionButton(this.toggleRecordAction)); + this.panelToolbar.appendToolbarItem(UI.Toolbar.Toolbar.createActionButton(this.recordReloadAction)); + this.clearButton = new UI.Toolbar.ToolbarButton(i18nString(UIStrings.clear), 'largeicon-clear'); + this.clearButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, () => this.onClearButton()); + this.panelToolbar.appendToolbarItem(this.clearButton); // Load / Save - this._loadButton = new UI.Toolbar.ToolbarButton(i18nString(UIStrings.loadProfile), 'largeicon-load'); - this._loadButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, () => { + this.loadButton = new UI.Toolbar.ToolbarButton(i18nString(UIStrings.loadProfile), 'largeicon-load'); + this.loadButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, () => { Host.userMetrics.actionTaken(Host.UserMetrics.Action.PerfPanelTraceImported); - this._selectFileToLoad(); + this.selectFileToLoad(); }); - this._saveButton = new UI.Toolbar.ToolbarButton(i18nString(UIStrings.saveProfile), 'largeicon-download'); - this._saveButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, _event => { + this.saveButton = new UI.Toolbar.ToolbarButton(i18nString(UIStrings.saveProfile), 'largeicon-download'); + this.saveButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, _event => { Host.userMetrics.actionTaken(Host.UserMetrics.Action.PerfPanelTraceExported); - this._saveToFile(); + this.saveToFile(); }); - this._panelToolbar.appendSeparator(); - this._panelToolbar.appendToolbarItem(this._loadButton); - this._panelToolbar.appendToolbarItem(this._saveButton); + this.panelToolbar.appendSeparator(); + this.panelToolbar.appendToolbarItem(this.loadButton); + this.panelToolbar.appendToolbarItem(this.saveButton); // History - this._panelToolbar.appendSeparator(); - this._panelToolbar.appendToolbarItem(this._historyManager.button()); - this._panelToolbar.appendSeparator(); + this.panelToolbar.appendSeparator(); + this.panelToolbar.appendToolbarItem(this.historyManager.button()); + this.panelToolbar.appendSeparator(); // View - this._panelToolbar.appendSeparator(); - this._showScreenshotsToolbarCheckbox = - this._createSettingCheckbox(this._showScreenshotsSetting, i18nString(UIStrings.captureScreenshots)); - this._panelToolbar.appendToolbarItem(this._showScreenshotsToolbarCheckbox); + this.panelToolbar.appendSeparator(); + this.showScreenshotsToolbarCheckbox = + this.createSettingCheckbox(this.showScreenshotsSetting, i18nString(UIStrings.captureScreenshots)); + this.panelToolbar.appendToolbarItem(this.showScreenshotsToolbarCheckbox); - this._showMemoryToolbarCheckbox = - this._createSettingCheckbox(this._showMemorySetting, i18nString(UIStrings.showMemoryTimeline)); - this._panelToolbar.appendToolbarItem(this._showMemoryToolbarCheckbox); + this.showMemoryToolbarCheckbox = + this.createSettingCheckbox(this.showMemorySetting, i18nString(UIStrings.showMemoryTimeline)); + this.panelToolbar.appendToolbarItem(this.showMemoryToolbarCheckbox); - this._showWebVitalsToolbarCheckbox = - this._createSettingCheckbox(this._showWebVitalsSetting, i18nString(UIStrings.showWebVitals)); - this._panelToolbar.appendToolbarItem(this._showWebVitalsToolbarCheckbox); + this.showWebVitalsToolbarCheckbox = + this.createSettingCheckbox(this.showWebVitalsSetting, i18nString(UIStrings.showWebVitals)); + this.panelToolbar.appendToolbarItem(this.showWebVitalsToolbarCheckbox); if (Root.Runtime.experiments.isEnabled('recordCoverageWithPerformanceTracing')) { - this._startCoverageCheckbox = - this._createSettingCheckbox(this._startCoverage, i18nString(UIStrings.recordCoverageWithPerformance)); - this._panelToolbar.appendToolbarItem(this._startCoverageCheckbox); + this.startCoverageCheckbox = + this.createSettingCheckbox(this.startCoverage, i18nString(UIStrings.recordCoverageWithPerformance)); + this.panelToolbar.appendToolbarItem(this.startCoverageCheckbox); } // GC - this._panelToolbar.appendToolbarItem(UI.Toolbar.Toolbar.createActionButtonForId('components.collect-garbage')); + this.panelToolbar.appendToolbarItem(UI.Toolbar.Toolbar.createActionButtonForId('components.collect-garbage')); // Settings - this._panelRightToolbar.appendSeparator(); - this._panelRightToolbar.appendToolbarItem(this._showSettingsPaneButton); + this.panelRightToolbar.appendSeparator(); + this.panelRightToolbar.appendToolbarItem(this.showSettingsPaneButton); } - _createSettingsPane(): void { - this._showSettingsPaneSetting = + private createSettingsPane(): void { + this.showSettingsPaneSetting = Common.Settings.Settings.instance().createSetting('timelineShowSettingsToolbar', false); - this._showSettingsPaneButton = new UI.Toolbar.ToolbarSettingToggle( - this._showSettingsPaneSetting, 'largeicon-settings-gear', i18nString(UIStrings.captureSettings)); + this.showSettingsPaneButton = new UI.Toolbar.ToolbarSettingToggle( + this.showSettingsPaneSetting, 'largeicon-settings-gear', i18nString(UIStrings.captureSettings)); SDK.NetworkManager.MultitargetNetworkManager.instance().addEventListener( - SDK.NetworkManager.MultitargetNetworkManager.Events.ConditionsChanged, this._updateShowSettingsToolbarButton, + SDK.NetworkManager.MultitargetNetworkManager.Events.ConditionsChanged, this.updateShowSettingsToolbarButton, this); SDK.CPUThrottlingManager.CPUThrottlingManager.instance().addEventListener( - SDK.CPUThrottlingManager.Events.RateChanged, this._updateShowSettingsToolbarButton, this); - this._disableCaptureJSProfileSetting.addChangeListener(this._updateShowSettingsToolbarButton, this); - this._captureLayersAndPicturesSetting.addChangeListener(this._updateShowSettingsToolbarButton, this); + SDK.CPUThrottlingManager.Events.RateChanged, this.updateShowSettingsToolbarButton, this); + this.disableCaptureJSProfileSetting.addChangeListener(this.updateShowSettingsToolbarButton, this); + this.captureLayersAndPicturesSetting.addChangeListener(this.updateShowSettingsToolbarButton, this); - this._settingsPane = new UI.Widget.HBox(); - this._settingsPane.element.classList.add('timeline-settings-pane'); - this._settingsPane.show(this.element); + this.settingsPane = new UI.Widget.HBox(); + this.settingsPane.element.classList.add('timeline-settings-pane'); + this.settingsPane.show(this.element); - const captureToolbar = new UI.Toolbar.Toolbar('', this._settingsPane.element); + const captureToolbar = new UI.Toolbar.Toolbar('', this.settingsPane.element); captureToolbar.element.classList.add('flex-auto'); captureToolbar.makeVertical(); - captureToolbar.appendToolbarItem(this._createSettingCheckbox( - this._disableCaptureJSProfileSetting, i18nString(UIStrings.disablesJavascriptSampling))); - captureToolbar.appendToolbarItem(this._createSettingCheckbox( - this._captureLayersAndPicturesSetting, i18nString(UIStrings.capturesAdvancedPaint))); + captureToolbar.appendToolbarItem(this.createSettingCheckbox( + this.disableCaptureJSProfileSetting, i18nString(UIStrings.disablesJavascriptSampling))); + captureToolbar.appendToolbarItem( + this.createSettingCheckbox(this.captureLayersAndPicturesSetting, i18nString(UIStrings.capturesAdvancedPaint))); const throttlingPane = new UI.Widget.VBox(); throttlingPane.element.classList.add('flex-auto'); - throttlingPane.show(this._settingsPane.element); + throttlingPane.show(this.settingsPane.element); const networkThrottlingToolbar = new UI.Toolbar.Toolbar('', throttlingPane.element); networkThrottlingToolbar.appendText(i18nString(UIStrings.network)); - this._networkThrottlingSelect = this._createNetworkConditionsSelect(); - networkThrottlingToolbar.appendToolbarItem(this._networkThrottlingSelect); + this.networkThrottlingSelect = this.createNetworkConditionsSelect(); + networkThrottlingToolbar.appendToolbarItem(this.networkThrottlingSelect); const cpuThrottlingToolbar = new UI.Toolbar.Toolbar('', throttlingPane.element); cpuThrottlingToolbar.appendText(i18nString(UIStrings.cpu)); - this._cpuThrottlingSelect = MobileThrottling.ThrottlingManager.throttlingManager().createCPUThrottlingSelector(); - cpuThrottlingToolbar.appendToolbarItem(this._cpuThrottlingSelect); + this.cpuThrottlingSelect = MobileThrottling.ThrottlingManager.throttlingManager().createCPUThrottlingSelector(); + cpuThrottlingToolbar.appendToolbarItem(this.cpuThrottlingSelect); - this._showSettingsPaneSetting.addChangeListener(this._updateSettingsPaneVisibility.bind(this)); - this._updateSettingsPaneVisibility(); + this.showSettingsPaneSetting.addChangeListener(this.updateSettingsPaneVisibility.bind(this)); + this.updateSettingsPaneVisibility(); } - _appendExtensionsToToolbar(event: Common.EventTarget.EventTargetEvent): void { + private appendExtensionsToToolbar(event: Common.EventTarget.EventTargetEvent): void { const provider = (event.data as Extensions.ExtensionTraceProvider.ExtensionTraceProvider); - const setting = TimelinePanel._settingForTraceProvider(provider); - const checkbox = this._createSettingCheckbox(setting, provider.longDisplayName()); - this._panelToolbar.appendToolbarItem(checkbox); + const setting = TimelinePanel.settingForTraceProvider(provider); + const checkbox = this.createSettingCheckbox(setting, provider.longDisplayName()); + this.panelToolbar.appendToolbarItem(checkbox); } - static _settingForTraceProvider(traceProvider: Extensions.ExtensionTraceProvider.ExtensionTraceProvider): + private static settingForTraceProvider(traceProvider: Extensions.ExtensionTraceProvider.ExtensionTraceProvider): Common.Settings.Setting<boolean> { let setting = traceProviderToSetting.get(traceProvider); if (!setting) { @@ -589,7 +587,7 @@ return setting; } - _createNetworkConditionsSelect(): UI.Toolbar.ToolbarComboBox { + private createNetworkConditionsSelect(): UI.Toolbar.ToolbarComboBox { const toolbarItem = new UI.Toolbar.ToolbarComboBox(null, i18nString(UIStrings.networkConditions)); toolbarItem.setMaxWidth(140); MobileThrottling.ThrottlingManager.throttlingManager().decorateSelectWithNetworkThrottling( @@ -597,33 +595,33 @@ return toolbarItem; } - _prepareToLoadTimeline(): void { - console.assert(this._state === State.Idle); - this._setState(State.Loading); - if (this._performanceModel) { - this._performanceModel.dispose(); - this._performanceModel = null; + private prepareToLoadTimeline(): void { + console.assert(this.state === State.Idle); + this.setState(State.Loading); + if (this.performanceModel) { + this.performanceModel.dispose(); + this.performanceModel = null; } } - _createFileSelector(): void { - if (this._fileSelectorElement) { - this._fileSelectorElement.remove(); + private createFileSelector(): void { + if (this.fileSelectorElement) { + this.fileSelectorElement.remove(); } - this._fileSelectorElement = UI.UIUtils.createFileSelectorElement(this._loadFromFile.bind(this)); - this._timelinePane.element.appendChild(this._fileSelectorElement); + this.fileSelectorElement = UI.UIUtils.createFileSelectorElement(this.loadFromFile.bind(this)); + this.timelinePane.element.appendChild(this.fileSelectorElement); } - _contextMenu(event: Event): void { + private contextMenu(event: Event): void { const contextMenu = new UI.ContextMenu.ContextMenu(event); contextMenu.appendItemsAtLocation('timelineMenu'); contextMenu.show(); } - async _saveToFile(): Promise<void> { - if (this._state !== State.Idle) { + async saveToFile(): Promise<void> { + if (this.state !== State.Idle) { return; } - const performanceModel = this._performanceModel; + const performanceModel = this.performanceModel; if (!performanceModel) { return; } @@ -649,88 +647,88 @@ i18nString(UIStrings.failedToSaveTimelineSSS, {PH1: error.message, PH2: error.name, PH3: error.code})); } - async _showHistory(): Promise<void> { - const model = await this._historyManager.showHistoryDropDown(); - if (model && model !== this._performanceModel) { - this._setModel(model); + async showHistory(): Promise<void> { + const model = await this.historyManager.showHistoryDropDown(); + if (model && model !== this.performanceModel) { + this.setModel(model); } } - _navigateHistory(direction: number): boolean { - const model = this._historyManager.navigate(direction); - if (model && model !== this._performanceModel) { - this._setModel(model); + navigateHistory(direction: number): boolean { + const model = this.historyManager.navigate(direction); + if (model && model !== this.performanceModel) { + this.setModel(model); } return true; } - _selectFileToLoad(): void { - if (this._fileSelectorElement) { - this._fileSelectorElement.click(); + selectFileToLoad(): void { + if (this.fileSelectorElement) { + this.fileSelectorElement.click(); } } - _loadFromFile(file: File): void { - if (this._state !== State.Idle) { + private loadFromFile(file: File): void { + if (this.state !== State.Idle) { return; } - this._prepareToLoadTimeline(); - this._loader = TimelineLoader.loadFromFile(file, this); - this._createFileSelector(); + this.prepareToLoadTimeline(); + this.loader = TimelineLoader.loadFromFile(file, this); + this.createFileSelector(); } - _loadFromURL(url: string): void { - if (this._state !== State.Idle) { + loadFromURL(url: string): void { + if (this.state !== State.Idle) { return; } - this._prepareToLoadTimeline(); - this._loader = TimelineLoader.loadFromURL(url, this); + this.prepareToLoadTimeline(); + this.loader = TimelineLoader.loadFromURL(url, this); } - _updateOverviewControls(): void { - this._overviewControls = []; - this._overviewControls.push(new TimelineEventOverviewResponsiveness()); + private updateOverviewControls(): void { + this.overviewControls = []; + this.overviewControls.push(new TimelineEventOverviewResponsiveness()); if (Root.Runtime.experiments.isEnabled('inputEventsOnTimelineOverview')) { - this._overviewControls.push(new TimelineEventOverviewInput()); + this.overviewControls.push(new TimelineEventOverviewInput()); } - this._overviewControls.push(new TimelineEventOverviewFrames()); - this._overviewControls.push(new TimelineEventOverviewCPUActivity()); - this._overviewControls.push(new TimelineEventOverviewNetwork()); - if (this._showScreenshotsSetting.get() && this._performanceModel && - this._performanceModel.filmStripModel().frames().length) { - this._overviewControls.push(new TimelineFilmStripOverview()); + this.overviewControls.push(new TimelineEventOverviewFrames()); + this.overviewControls.push(new TimelineEventOverviewCPUActivity()); + this.overviewControls.push(new TimelineEventOverviewNetwork()); + if (this.showScreenshotsSetting.get() && this.performanceModel && + this.performanceModel.filmStripModel().frames().length) { + this.overviewControls.push(new TimelineFilmStripOverview()); } - if (this._showMemorySetting.get()) { - this._overviewControls.push(new TimelineEventOverviewMemory()); + if (this.showMemorySetting.get()) { + this.overviewControls.push(new TimelineEventOverviewMemory()); } - if (this._startCoverage.get()) { - this._overviewControls.push(new TimelineEventOverviewCoverage()); + if (this.startCoverage.get()) { + this.overviewControls.push(new TimelineEventOverviewCoverage()); } - for (const control of this._overviewControls) { - control.setModel(this._performanceModel); + for (const control of this.overviewControls) { + control.setModel(this.performanceModel); } - this._overviewPane.setOverviewControls(this._overviewControls); + this.overviewPane.setOverviewControls(this.overviewControls); } - _onModeChanged(): void { - this._updateOverviewControls(); + private onModeChanged(): void { + this.updateOverviewControls(); this.doResize(); this.select(null); } - _onWebVitalsChanged(): void { - this._flameChart.toggleWebVitalsLane(); + private onWebVitalsChanged(): void { + this.flameChart.toggleWebVitalsLane(); } - _updateSettingsPaneVisibility(): void { - if (this._showSettingsPaneSetting.get()) { - this._settingsPane.showWidget(); + private updateSettingsPaneVisibility(): void { + if (this.showSettingsPaneSetting.get()) { + this.settingsPane.showWidget(); } else { - this._settingsPane.hideWidget(); + this.settingsPane.hideWidget(); } } - _updateShowSettingsToolbarButton(): void { + private updateShowSettingsToolbarButton(): void { const messages: string[] = []; if (SDK.CPUThrottlingManager.CPUThrottlingManager.instance().cpuThrottlingRate() !== 1) { messages.push(i18nString(UIStrings.CpuThrottlingIsEnabled)); @@ -738,106 +736,106 @@ if (SDK.NetworkManager.MultitargetNetworkManager.instance().isThrottling()) { messages.push(i18nString(UIStrings.NetworkThrottlingIsEnabled)); } - if (this._captureLayersAndPicturesSetting.get()) { + if (this.captureLayersAndPicturesSetting.get()) { messages.push(i18nString(UIStrings.SignificantOverheadDueToPaint)); } - if (this._disableCaptureJSProfileSetting.get()) { + if (this.disableCaptureJSProfileSetting.get()) { messages.push(i18nString(UIStrings.JavascriptSamplingIsDisabled)); } - this._showSettingsPaneButton.setDefaultWithRedColor(messages.length > 0); - this._showSettingsPaneButton.setToggleWithRedColor(messages.length > 0); + this.showSettingsPaneButton.setDefaultWithRedColor(messages.length > 0); + this.showSettingsPaneButton.setToggleWithRedColor(messages.length > 0); if (messages.length) { const tooltipElement = document.createElement('div'); messages.forEach(message => { tooltipElement.createChild('div').textContent = message; }); - this._showSettingsPaneButton.setTitle(tooltipElement.textContent || ''); + this.showSettingsPaneButton.setTitle(tooltipElement.textContent || ''); } else { - this._showSettingsPaneButton.setTitle(i18nString(UIStrings.captureSettings)); + this.showSettingsPaneButton.setTitle(i18nString(UIStrings.captureSettings)); } } - _setUIControlsEnabled(enabled: boolean): void { - this._recordingOptionUIControls.forEach(control => control.setEnabled(enabled)); + private setUIControlsEnabled(enabled: boolean): void { + this.recordingOptionUIControls.forEach(control => control.setEnabled(enabled)); } - async _getCoverageViewWidget(): Promise<Coverage.CoverageView.CoverageView> { + private async getCoverageViewWidget(): Promise<Coverage.CoverageView.CoverageView> { const view = (UI.ViewManager.ViewManager.instance().view('coverage') as UI.View.View); return /** @type {!Coverage.CoverageView.CoverageView} */ await view.widget() as Coverage.CoverageView.CoverageView; } - async _startRecording(): Promise<void> { - console.assert(!this._statusPane, 'Status pane is already opened.'); - this._setState(State.StartPending); + private async startRecording(): Promise<void> { + console.assert(!this.statusPane, 'Status pane is already opened.'); + this.setState(State.StartPending); const recordingOptions = { - enableJSSampling: !this._disableCaptureJSProfileSetting.get(), - capturePictures: this._captureLayersAndPicturesSetting.get(), - captureFilmStrip: this._showScreenshotsSetting.get(), - startCoverage: this._startCoverage.get(), + enableJSSampling: !this.disableCaptureJSProfileSetting.get(), + capturePictures: this.captureLayersAndPicturesSetting.get(), + captureFilmStrip: this.showScreenshotsSetting.get(), + startCoverage: this.startCoverage.get(), }; if (recordingOptions.startCoverage) { await UI.ViewManager.ViewManager.instance() .showView('coverage') - .then(() => this._getCoverageViewWidget()) + .then(() => this.getCoverageViewWidget()) .then(widget => widget.ensureRecordingStarted()); } - this._showRecordingStarted(); + this.showRecordingStarted(); const enabledTraceProviders = Extensions.ExtensionServer.ExtensionServer.instance().traceProviders().filter( - provider => TimelinePanel._settingForTraceProvider(provider).get()); + provider => TimelinePanel.settingForTraceProvider(provider).get()); const mainTarget = (SDK.TargetManager.TargetManager.instance().mainTarget() as SDK.Target.Target); if (UIDevtoolsUtils.isUiDevTools()) { - this._controller = new UIDevtoolsController(mainTarget, this); + this.controller = new UIDevtoolsController(mainTarget, this); } else { - this._controller = new TimelineController(mainTarget, this); + this.controller = new TimelineController(mainTarget, this); } - this._setUIControlsEnabled(false); - this._hideLandingPage(); + this.setUIControlsEnabled(false); + this.hideLandingPage(); try { - const response = await this._controller.startRecording(recordingOptions, enabledTraceProviders); + const response = await this.controller.startRecording(recordingOptions, enabledTraceProviders); if (response.getError()) { throw new Error(response.getError()); } else { - this._recordingStarted(); + this.recordingStarted(); } } catch (e) { - this._recordingFailed(e.message); + this.recordingFailed(e.message); } } - async _stopRecording(): Promise<void> { - if (this._statusPane) { - this._statusPane.finish(); - this._statusPane.updateStatus(i18nString(UIStrings.stoppingTimeline)); - this._statusPane.updateProgressBar(i18nString(UIStrings.received), 0); + private async stopRecording(): Promise<void> { + if (this.statusPane) { + this.statusPane.finish(); + this.statusPane.updateStatus(i18nString(UIStrings.stoppingTimeline)); + this.statusPane.updateProgressBar(i18nString(UIStrings.received), 0); } - this._setState(State.StopPending); - if (this._startCoverage.get()) { + this.setState(State.StopPending); + if (this.startCoverage.get()) { await UI.ViewManager.ViewManager.instance() .showView('coverage') - .then(() => this._getCoverageViewWidget()) + .then(() => this.getCoverageViewWidget()) .then(widget => widget.stopRecording()); } - if (this._controller) { - const model = await this._controller.stopRecording(); - this._performanceModel = model; - this._setUIControlsEnabled(true); - this._controller.dispose(); - this._controller = null; + if (this.controller) { + const model = await this.controller.stopRecording(); + this.performanceModel = model; + this.setUIControlsEnabled(true); + this.controller.dispose(); + this.controller = null; } } - _recordingFailed(error: string): void { - if (this._statusPane) { - this._statusPane.hide(); + private recordingFailed(error: string): void { + if (this.statusPane) { + this.statusPane.hide(); } - this._statusPane = new StatusPane( + this.statusPane = new StatusPane( { description: error, buttonText: i18nString(UIStrings.close), @@ -846,143 +844,142 @@ showTimer: undefined, }, () => this.loadingComplete(null)); - this._statusPane.showPane(this._statusPaneContainer); - this._statusPane.updateStatus(i18nString(UIStrings.recordingFailed)); + this.statusPane.showPane(this.statusPaneContainer); + this.statusPane.updateStatus(i18nString(UIStrings.recordingFailed)); - this._setState(State.RecordingFailed); - this._performanceModel = null; - this._setUIControlsEnabled(true); - if (this._controller) { - this._controller.dispose(); - this._controller = null; + this.setState(State.RecordingFailed); + this.performanceModel = null; + this.setUIControlsEnabled(true); + if (this.controller) { + this.controller.dispose(); + this.controller = null; } } - _onSuspendStateChanged(): void { - this._updateTimelineControls(); + private onSuspendStateChanged(): void { + this.updateTimelineControls(); } - _updateTimelineControls(): void { + private updateTimelineControls(): void { const state = State; - this._toggleRecordAction.setToggled(this._state === state.Recording); - this._toggleRecordAction.setEnabled(this._state === state.Recording || this._state === state.Idle); - this._recordReloadAction.setEnabled(this._state === state.Idle); - this._historyManager.setEnabled(this._state === state.Idle); - this._clearButton.setEnabled(this._state === state.Idle); - this._panelToolbar.setEnabled(this._state !== state.Loading); - this._panelRightToolbar.setEnabled(this._state !== state.Loading); - this._dropTarget.setEnabled(this._state === state.Idle); - this._loadButton.setEnabled(this._state === state.Idle); - this._saveButton.setEnabled(this._state === state.Idle && Boolean(this._performanceModel)); + this.toggleRecordAction.setToggled(this.state === state.Recording); + this.toggleRecordAction.setEnabled(this.state === state.Recording || this.state === state.Idle); + this.recordReloadAction.setEnabled(this.state === state.Idle); + this.historyManager.setEnabled(this.state === state.Idle); + this.clearButton.setEnabled(this.state === state.Idle); + this.panelToolbar.setEnabled(this.state !== state.Loading); + this.panelRightToolbar.setEnabled(this.state !== state.Loading); + this.dropTarget.setEnabled(this.state === state.Idle); + this.loadButton.setEnabled(this.state === state.Idle); + this.saveButton.setEnabled(this.state === state.Idle && Boolean(this.performanceModel)); } - _toggleRecording(): void { - if (this._state === State.Idle) { - this._recordingPageReload = false; - this._startRecording(); + toggleRecording(): void { + if (this.state === State.Idle) { + this.recordingPageReload = false; + this.startRecording(); Host.userMetrics.actionTaken(Host.UserMetrics.Action.TimelineStarted); - } else if (this._state === State.Recording) { - this._stopRecording(); + } else if (this.state === State.Recording) { + this.stopRecording(); } } - _recordReload(): void { - if (this._state !== State.Idle) { + recordReload(): void { + if (this.state !== State.Idle) { return; } - this._recordingPageReload = true; - this._startRecording(); + this.recordingPageReload = true; + this.startRecording(); Host.userMetrics.actionTaken(Host.UserMetrics.Action.TimelinePageReloadStarted); } - _onClearButton(): void { - this._historyManager.clear(); - this._clear(); + private onClearButton(): void { + this.historyManager.clear(); + this.clear(); } - _clear(): void { - this._showLandingPage(); - this._reset(); + private clear(): void { + this.showLandingPage(); + this.reset(); } - _reset(): void { + private reset(): void { PerfUI.LineLevelProfile.Performance.instance().reset(); - this._setModel(null); + this.setModel(null); } - _applyFilters(model: PerformanceModel): void { + private applyFilters(model: PerformanceModel): void { if (model.timelineModel().isGenericTrace() || Root.Runtime.experiments.isEnabled('timelineShowAllEvents')) { return; } model.setFilters([TimelineUIUtils.visibleEventsFilter()]); } - _setModel(model: PerformanceModel|null): void { - if (this._performanceModel) { - this._performanceModel.removeEventListener(Events.WindowChanged, this._onModelWindowChanged, this); + private setModel(model: PerformanceModel|null): void { + if (this.performanceModel) { + this.performanceModel.removeEventListener(Events.WindowChanged, this.onModelWindowChanged, this); } - this._performanceModel = model; + this.performanceModel = model; if (model) { - this._searchableView.showWidget(); - this._applyFilters(model); + this.searchableViewInternal.showWidget(); + this.applyFilters(model); } else { - this._searchableView.hideWidget(); + this.searchableViewInternal.hideWidget(); } - this._flameChart.setModel(model); + this.flameChart.setModel(model); - this._updateOverviewControls(); - this._overviewPane.reset(); - if (model && this._performanceModel) { - this._performanceModel.addEventListener(Events.WindowChanged, this._onModelWindowChanged, this); - this._overviewPane.setNavStartTimes(model.timelineModel().navStartTimes()); - this._overviewPane.setBounds( - model.timelineModel().minimumRecordTime(), model.timelineModel().maximumRecordTime()); + this.updateOverviewControls(); + this.overviewPane.reset(); + if (model && this.performanceModel) { + this.performanceModel.addEventListener(Events.WindowChanged, this.onModelWindowChanged, this); + this.overviewPane.setNavStartTimes(model.timelineModel().navStartTimes()); + this.overviewPane.setBounds(model.timelineModel().minimumRecordTime(), model.timelineModel().maximumRecordTime()); PerfUI.LineLevelProfile.Performance.instance().reset(); for (const profile of model.timelineModel().cpuProfiles()) { PerfUI.LineLevelProfile.Performance.instance().appendCPUProfile(profile); } - this._setMarkers(model.timelineModel()); - this._flameChart.setSelection(null); - this._overviewPane.setWindowTimes(model.window().left, model.window().right); + this.setMarkers(model.timelineModel()); + this.flameChart.setSelection(null); + this.overviewPane.setWindowTimes(model.window().left, model.window().right); } - for (const control of this._overviewControls) { + for (const control of this.overviewControls) { control.setModel(model); } - if (this._flameChart) { - this._flameChart.resizeToPreferredHeights(); + if (this.flameChart) { + this.flameChart.resizeToPreferredHeights(); } - this._updateTimelineControls(); + this.updateTimelineControls(); } - _recordingStarted(): void { - if (this._recordingPageReload && this._controller) { - const target = this._controller.mainTarget(); + private recordingStarted(): void { + if (this.recordingPageReload && this.controller) { + const target = this.controller.mainTarget(); const resourceModel = target.model(SDK.ResourceTreeModel.ResourceTreeModel); if (resourceModel) { resourceModel.reloadPage(); } } - this._reset(); - this._setState(State.Recording); - this._showRecordingStarted(); - if (this._statusPane) { - this._statusPane.enableAndFocusButton(); - this._statusPane.updateStatus(i18nString(UIStrings.profiling)); - this._statusPane.updateProgressBar(i18nString(UIStrings.bufferUsage), 0); - this._statusPane.startTimer(); + this.reset(); + this.setState(State.Recording); + this.showRecordingStarted(); + if (this.statusPane) { + this.statusPane.enableAndFocusButton(); + this.statusPane.updateStatus(i18nString(UIStrings.profiling)); + this.statusPane.updateProgressBar(i18nString(UIStrings.bufferUsage), 0); + this.statusPane.startTimer(); } - this._hideLandingPage(); + this.hideLandingPage(); } recordingProgress(usage: number): void { - if (this._statusPane) { - this._statusPane.updateProgressBar(i18nString(UIStrings.bufferUsage), usage * 100); + if (this.statusPane) { + this.statusPane.updateProgressBar(i18nString(UIStrings.bufferUsage), usage * 100); } } - _showLandingPage(): void { - if (this._landingPage) { - this._landingPage.show(this._statusPaneContainer); + private showLandingPage(): void { + if (this.landingPage) { + this.landingPage.show(this.statusPaneContainer); return; } @@ -1002,11 +999,11 @@ 'b', UI.ShortcutRegistry.ShortcutRegistry.instance().shortcutsForAction('timeline.record-reload')[0].title()); const navigateNode = encloseWithTag('b', i18nString(UIStrings.wasd)); - this._landingPage = new UI.Widget.VBox(); - this._landingPage.contentElement.classList.add('timeline-landing-page', 'fill'); - const centered = this._landingPage.contentElement.createChild('div'); + this.landingPage = new UI.Widget.VBox(); + this.landingPage.contentElement.classList.add('timeline-landing-page', 'fill'); + const centered = this.landingPage.contentElement.createChild('div'); - const recordButton = UI.UIUtils.createInlineButton(UI.Toolbar.Toolbar.createActionButton(this._toggleRecordAction)); + const recordButton = UI.UIUtils.createInlineButton(UI.Toolbar.Toolbar.createActionButton(this.toggleRecordAction)); const reloadButton = UI.UIUtils.createInlineButton(UI.Toolbar.Toolbar.createActionButtonForId('timeline.record-reload')); @@ -1019,20 +1016,20 @@ centered.createChild('p').appendChild(i18n.i18n.getFormatLocalizedString( str_, UIStrings.afterRecordingSelectAnAreaOf, {PH1: navigateNode, PH2: learnMoreNode})); - this._landingPage.show(this._statusPaneContainer); + this.landingPage.show(this.statusPaneContainer); } - _hideLandingPage(): void { - this._landingPage.detach(); + private hideLandingPage(): void { + this.landingPage.detach(); } loadingStarted(): void { - this._hideLandingPage(); + this.hideLandingPage(); - if (this._statusPane) { - this._statusPane.hide(); + if (this.statusPane) { + this.statusPane.hide(); } - this._statusPane = new StatusPane( + this.statusPane = new StatusPane( { showProgress: true, showTimer: undefined, @@ -1040,63 +1037,63 @@ buttonText: undefined, description: undefined, }, - () => this._cancelLoading()); - this._statusPane.showPane(this._statusPaneContainer); - this._statusPane.updateStatus(i18nString(UIStrings.loadingProfile)); + () => this.cancelLoading()); + this.statusPane.showPane(this.statusPaneContainer); + this.statusPane.updateStatus(i18nString(UIStrings.loadingProfile)); // FIXME: make loading from backend cancelable as well. - if (!this._loader) { - this._statusPane.finish(); + if (!this.loader) { + this.statusPane.finish(); } this.loadingProgress(0); } loadingProgress(progress?: number): void { - if (typeof progress === 'number' && this._statusPane) { - this._statusPane.updateProgressBar(i18nString(UIStrings.received), progress * 100); + if (typeof progress === 'number' && this.statusPane) { + this.statusPane.updateProgressBar(i18nString(UIStrings.received), progress * 100); } } processingStarted(): void { - if (this._statusPane) { - this._statusPane.updateStatus(i18nString(UIStrings.processingProfile)); + if (this.statusPane) { + this.statusPane.updateStatus(i18nString(UIStrings.processingProfile)); } } loadingComplete(tracingModel: SDK.TracingModel.TracingModel|null): void { - delete this._loader; - this._setState(State.Idle); + delete this.loader; + this.setState(State.Idle); - if (this._statusPane) { - this._statusPane.hide(); + if (this.statusPane) { + this.statusPane.hide(); } - this._statusPane = null; + this.statusPane = null; if (!tracingModel) { - this._clear(); + this.clear(); return; } - if (!this._performanceModel) { - this._performanceModel = new PerformanceModel(); + if (!this.performanceModel) { + this.performanceModel = new PerformanceModel(); } - this._performanceModel.setTracingModel(tracingModel); - this._setModel(this._performanceModel); - this._historyManager.addRecording(this._performanceModel); + this.performanceModel.setTracingModel(tracingModel); + this.setModel(this.performanceModel); + this.historyManager.addRecording(this.performanceModel); - if (this._startCoverage.get()) { + if (this.startCoverage.get()) { UI.ViewManager.ViewManager.instance() .showView('coverage') - .then(() => this._getCoverageViewWidget()) + .then(() => this.getCoverageViewWidget()) .then(widget => widget.processBacklog()) - .then(() => this._updateOverviewControls()); + .then(() => this.updateOverviewControls()); } } - _showRecordingStarted(): void { - if (this._statusPane) { + private showRecordingStarted(): void { + if (this.statusPane) { return; } - this._statusPane = new StatusPane( + this.statusPane = new StatusPane( { showTimer: true, showProgress: true, @@ -1104,18 +1101,18 @@ description: undefined, buttonText: undefined, }, - () => this._stopRecording()); - this._statusPane.showPane(this._statusPaneContainer); - this._statusPane.updateStatus(i18nString(UIStrings.initializingProfiler)); + () => this.stopRecording()); + this.statusPane.showPane(this.statusPaneContainer); + this.statusPane.updateStatus(i18nString(UIStrings.initializingProfiler)); } - _cancelLoading(): void { - if (this._loader) { - this._loader.cancel(); + private cancelLoading(): void { + if (this.loader) { + this.loader.cancel(); } } - _setMarkers(timelineModel: TimelineModel.TimelineModel.TimelineModelImpl): void { + private setMarkers(timelineModel: TimelineModel.TimelineModel.TimelineModelImpl): void { const markers = new Map<number, Element>(); const recordTypes = TimelineModel.TimelineModel.RecordType; const zeroTime = timelineModel.minimumRecordTime(); @@ -1130,28 +1127,28 @@ for (const navStartTimeEvent of timelineModel.navStartTimes().values()) { markers.set(navStartTimeEvent.startTime, TimelineUIUtils.createEventDivider(navStartTimeEvent, zeroTime)); } - this._overviewPane.setMarkers(markers); + this.overviewPane.setMarkers(markers); } - async _loadEventFired( + private async loadEventFired( event: Common.EventTarget .EventTargetEvent<{resourceTreeModel: SDK.ResourceTreeModel.ResourceTreeModel, loadTime: number}>): Promise<void> { - if (this._state !== State.Recording || !this._recordingPageReload || !this._controller || - this._controller.mainTarget() !== event.data.resourceTreeModel.target()) { + if (this.state !== State.Recording || !this.recordingPageReload || !this.controller || + this.controller.mainTarget() !== event.data.resourceTreeModel.target()) { return; } - const controller = this._controller; - await new Promise(r => setTimeout(r, this._millisecondsToRecordAfterLoadEvent)); + const controller = this.controller; + await new Promise(r => setTimeout(r, this.millisecondsToRecordAfterLoadEvent)); // Check if we're still in the same recording session. - if (controller !== this._controller || this._state !== State.Recording) { + if (controller !== this.controller || this.state !== State.Recording) { return; } - this._stopRecording(); + this.stopRecording(); } - _frameForSelection(selection: TimelineSelection): TimelineModel.TimelineFrameModel.TimelineFrame|null { + private frameForSelection(selection: TimelineSelection): TimelineModel.TimelineFrameModel.TimelineFrame|null { switch (selection.type()) { case TimelineSelection.Type.Frame: return /** @type {!TimelineModel.TimelineFrameModel.TimelineFrame} */ selection.object() as @@ -1159,34 +1156,35 @@ case TimelineSelection.Type.Range: return null; case TimelineSelection.Type.TraceEvent: - if (!this._performanceModel) { + if (!this.performanceModel) { return null; } - return this._performanceModel.frameModel().getFramesWithinWindow(selection._endTime, selection._endTime)[0]; + return this.performanceModel.frameModel().getFramesWithinWindow( + selection.endTimeInternal, selection.endTimeInternal)[0]; default: console.assert(false, 'Should never be reached'); return null; } } - _jumpToFrame(offset: number): true|undefined { - const currentFrame = this._selection && this._frameForSelection(this._selection); - if (!currentFrame || !this._performanceModel) { + jumpToFrame(offset: number): true|undefined { + const currentFrame = this.selection && this.frameForSelection(this.selection); + if (!currentFrame || !this.performanceModel) { return; } - const frames = this._performanceModel.frames(); + const frames = this.performanceModel.frames(); let index = frames.indexOf(currentFrame); console.assert(index >= 0, 'Can\'t find current frame in the frame list'); index = Platform.NumberUtilities.clamp(index + offset, 0, frames.length - 1); const frame = frames[index]; - this._revealTimeRange(frame.startTime, frame.endTime); + this.revealTimeRange(frame.startTime, frame.endTime); this.select(TimelineSelection.fromFrame(frame)); return true; } select(selection: TimelineSelection|null): void { - this._selection = selection; - this._flameChart.setSelection(selection); + this.selection = selection; + this.flameChart.setSelection(selection); } selectEntryAtTime(events: SDK.TracingModel.Event[]|null, time: number): void { @@ -1201,7 +1199,7 @@ if (SDK.TracingModel.TracingModel.isTopLevelEvent(event) && endTime < time) { break; } - if (this._performanceModel && this._performanceModel.isVisible(event) && endTime >= time) { + if (this.performanceModel && this.performanceModel.isVisible(event) && endTime >= time) { this.select(TimelineSelection.fromTraceEvent(event)); return; } @@ -1210,24 +1208,24 @@ } highlightEvent(event: SDK.TracingModel.Event|null): void { - this._flameChart.highlightEvent(event); + this.flameChart.highlightEvent(event); } - _revealTimeRange(startTime: number, endTime: number): void { - if (!this._performanceModel) { + private revealTimeRange(startTime: number, endTime: number): void { + if (!this.performanceModel) { return; } - const window = this._performanceModel.window(); + const window = this.performanceModel.window(); let offset = 0; if (window.right < endTime) { offset = endTime - window.right; } else if (window.left > startTime) { offset = startTime - window.left; } - this._performanceModel.setWindow({left: window.left + offset, right: window.right + offset}, /* animate */ true); + this.performanceModel.setWindow({left: window.left + offset, right: window.right + offset}, /* animate */ true); } - _handleDrop(dataTransfer: DataTransfer): void { + private handleDrop(dataTransfer: DataTransfer): void { const items = dataTransfer.items; if (!items.length) { return; @@ -1237,14 +1235,14 @@ if (item.kind === 'string') { const url = dataTransfer.getData('text/uri-list'); if (new Common.ParsedURL.ParsedURL(url).isValid) { - this._loadFromURL(url); + this.loadFromURL(url); } } else if (item.kind === 'file') { const entry = items[0].webkitGetAsEntry(); if (!entry.isFile) { return; } - entry.file(this._loadFromFile.bind(this)); + entry.file(this.loadFromFile.bind(this)); } } } @@ -1275,16 +1273,16 @@ export const headerHeight = 20; export class TimelineSelection { - _type: string; - _startTime: number; - _endTime: number; - _object: Object|null; + private readonly typeInternal: string; + private readonly startTimeInternal: number; + readonly endTimeInternal: number; + private readonly objectInternal: Object|null; constructor(type: string, startTime: number, endTime: number, object?: Object) { - this._type = type; - this._startTime = startTime; - this._endTime = endTime; - this._object = object || null; + this.typeInternal = type; + this.startTimeInternal = startTime; + this.endTimeInternal = endTime; + this.objectInternal = object || null; } static fromFrame(frame: TimelineModel.TimelineFrameModel.TimelineFrame): TimelineSelection { @@ -1306,19 +1304,19 @@ } type(): string { - return this._type; + return this.typeInternal; } object(): Object|null { - return this._object; + return this.objectInternal; } startTime(): number { - return this._startTime; + return this.startTimeInternal; } endTime(): number { - return this._endTime; + return this.endTimeInternal; } } @@ -1339,14 +1337,14 @@ } export class StatusPane extends UI.Widget.VBox { - _status: HTMLElement; - _time!: Element; - _progressLabel!: Element; - _progressBar!: Element; - _description: HTMLElement|undefined; - _button: HTMLButtonElement; - _startTime!: number; - _timeUpdateTimer?: number; + private status: HTMLElement; + private time!: Element; + private progressLabel!: Element; + private progressBar!: Element; + private readonly description: HTMLElement|undefined; + private button: HTMLButtonElement; + private startTime!: number; + private timeUpdateTimer?: number; constructor( options: { @@ -1363,94 +1361,94 @@ const statusLine = this.contentElement.createChild('div', 'status-dialog-line status'); statusLine.createChild('div', 'label').textContent = i18nString(UIStrings.status); - this._status = statusLine.createChild('div', 'content'); - UI.ARIAUtils.markAsStatus(this._status); + this.status = statusLine.createChild('div', 'content'); + UI.ARIAUtils.markAsStatus(this.status); if (options.showTimer) { const timeLine = this.contentElement.createChild('div', 'status-dialog-line time'); timeLine.createChild('div', 'label').textContent = i18nString(UIStrings.time); - this._time = timeLine.createChild('div', 'content'); + this.time = timeLine.createChild('div', 'content'); } if (options.showProgress) { const progressLine = this.contentElement.createChild('div', 'status-dialog-line progress'); - this._progressLabel = progressLine.createChild('div', 'label'); - this._progressBar = progressLine.createChild('div', 'indicator-container').createChild('div', 'indicator'); - UI.ARIAUtils.markAsProgressBar(this._progressBar); + this.progressLabel = progressLine.createChild('div', 'label'); + this.progressBar = progressLine.createChild('div', 'indicator-container').createChild('div', 'indicator'); + UI.ARIAUtils.markAsProgressBar(this.progressBar); } if (typeof options.description === 'string') { const descriptionLine = this.contentElement.createChild('div', 'status-dialog-line description'); descriptionLine.createChild('div', 'label').textContent = i18nString(UIStrings.description); - this._description = descriptionLine.createChild('div', 'content'); - this._description.innerText = options.description; + this.description = descriptionLine.createChild('div', 'content'); + this.description.innerText = options.description; } const buttonText = options.buttonText || i18nString(UIStrings.stop); - this._button = UI.UIUtils.createTextButton(buttonText, buttonCallback, '', true); + this.button = UI.UIUtils.createTextButton(buttonText, buttonCallback, '', true); // Profiling can't be stopped during initialization. - this._button.disabled = !options.buttonDisabled === false; - this.contentElement.createChild('div', 'stop-button').appendChild(this._button); + this.button.disabled = !options.buttonDisabled === false; + this.contentElement.createChild('div', 'stop-button').appendChild(this.button); } finish(): void { - this._stopTimer(); - this._button.disabled = true; + this.stopTimer(); + this.button.disabled = true; } hide(): void { (this.element.parentNode as HTMLElement).classList.remove('tinted'); - this._arrangeDialog((this.element.parentNode as HTMLElement)); + this.arrangeDialog((this.element.parentNode as HTMLElement)); this.element.remove(); } showPane(parent: Element): void { - this._arrangeDialog(parent); + this.arrangeDialog(parent); this.show(parent); parent.classList.add('tinted'); } enableAndFocusButton(): void { - this._button.disabled = false; - this._button.focus(); + this.button.disabled = false; + this.button.focus(); } updateStatus(text: string): void { - this._status.textContent = text; + this.status.textContent = text; } updateProgressBar(activity: string, percent: number): void { - this._progressLabel.textContent = activity; - (this._progressBar as HTMLElement).style.width = percent.toFixed(1) + '%'; - UI.ARIAUtils.setValueNow(this._progressBar, percent); - this._updateTimer(); + this.progressLabel.textContent = activity; + (this.progressBar as HTMLElement).style.width = percent.toFixed(1) + '%'; + UI.ARIAUtils.setValueNow(this.progressBar, percent); + this.updateTimer(); } startTimer(): void { - this._startTime = Date.now(); - this._timeUpdateTimer = window.setInterval(this._updateTimer.bind(this, false), 1000); - this._updateTimer(); + this.startTime = Date.now(); + this.timeUpdateTimer = window.setInterval(this.updateTimer.bind(this, false), 1000); + this.updateTimer(); } - _stopTimer(): void { - if (!this._timeUpdateTimer) { + private stopTimer(): void { + if (!this.timeUpdateTimer) { return; } - clearInterval(this._timeUpdateTimer); - this._updateTimer(true); - delete this._timeUpdateTimer; + clearInterval(this.timeUpdateTimer); + this.updateTimer(true); + delete this.timeUpdateTimer; } - _updateTimer(precise?: boolean): void { - this._arrangeDialog((this.element.parentNode as HTMLElement)); - if (!this._timeUpdateTimer) { + private updateTimer(precise?: boolean): void { + this.arrangeDialog((this.element.parentNode as HTMLElement)); + if (!this.timeUpdateTimer) { return; } - const elapsed = (Date.now() - this._startTime) / 1000; - this._time.textContent = i18nString(UIStrings.ssec, {PH1: elapsed.toFixed(precise ? 1 : 0)}); + const elapsed = (Date.now() - this.startTime) / 1000; + this.time.textContent = i18nString(UIStrings.ssec, {PH1: elapsed.toFixed(precise ? 1 : 0)}); } - _arrangeDialog(parent: Element): void { + private arrangeDialog(parent: Element): void { const isSmallDialog = parent.clientWidth < 325; this.element.classList.toggle('small-dialog', isSmallDialog); this.contentElement.classList.toggle('small-dialog', isSmallDialog); @@ -1473,7 +1471,7 @@ handleQueryParam(value: string): void { UI.ViewManager.ViewManager.instance().showView('timeline').then(() => { - TimelinePanel.instance()._loadFromURL(window.decodeURIComponent(value)); + TimelinePanel.instance().loadFromURL(window.decodeURIComponent(value)); }); } } @@ -1497,31 +1495,31 @@ console.assert(panel && panel instanceof TimelinePanel); switch (actionId) { case 'timeline.toggle-recording': - panel._toggleRecording(); + panel.toggleRecording(); return true; case 'timeline.record-reload': - panel._recordReload(); + panel.recordReload(); return true; case 'timeline.save-to-file': - panel._saveToFile(); + panel.saveToFile(); return true; case 'timeline.load-from-file': - panel._selectFileToLoad(); + panel.selectFileToLoad(); return true; case 'timeline.jump-to-previous-frame': - panel._jumpToFrame(-1); + panel.jumpToFrame(-1); return true; case 'timeline.jump-to-next-frame': - panel._jumpToFrame(1); + panel.jumpToFrame(1); return true; case 'timeline.show-history': - panel._showHistory(); + panel.showHistory(); return true; case 'timeline.previous-recording': - panel._navigateHistory(1); + panel.navigateHistory(1); return true; case 'timeline.next-recording': - panel._navigateHistory(-1); + panel.navigateHistory(-1); return true; } return false;
diff --git a/front_end/panels/timeline/TimelineTreeView.ts b/front_end/panels/timeline/TimelineTreeView.ts index 49b43f4..659bbc3 100644 --- a/front_end/panels/timeline/TimelineTreeView.ts +++ b/front_end/panels/timeline/TimelineTreeView.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; @@ -146,38 +144,38 @@ const str_ = i18n.i18n.registerUIStrings('panels/timeline/TimelineTreeView.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class TimelineTreeView extends UI.Widget.VBox implements UI.SearchableView.Searchable { - _model: PerformanceModel|null; - _track: TimelineModel.TimelineModel.Track|null; - _tree: TimelineModel.TimelineProfileTree.Node|null; - _searchResults: TimelineModel.TimelineProfileTree.Node[]; + modelInternal: PerformanceModel|null; + private track: TimelineModel.TimelineModel.Track|null; + private readonly tree: TimelineModel.TimelineProfileTree.Node|null; + private searchResults: TimelineModel.TimelineProfileTree.Node[]; linkifier!: Components.Linkifier.Linkifier; dataGrid!: DataGrid.SortableDataGrid.SortableDataGrid<GridNode>; - _lastHoveredProfileNode!: TimelineModel.TimelineProfileTree.Node|null; - _textFilter!: TimelineRegExp; - _taskFilter!: TimelineModel.TimelineModelFilter.ExclusiveNameFilter; - _startTime!: number; - _endTime!: number; + private lastHoveredProfileNode!: TimelineModel.TimelineProfileTree.Node|null; + private textFilterInternal!: TimelineRegExp; + private taskFilter!: TimelineModel.TimelineModelFilter.ExclusiveNameFilter; + protected startTime!: number; + protected endTime!: number; splitWidget!: UI.SplitWidget.SplitWidget; detailsView!: UI.Widget.Widget; - _searchableView!: UI.SearchableView.SearchableView; + private searchableView!: UI.SearchableView.SearchableView; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _currentThreadSetting?: Common.Settings.Setting<any>; - _lastSelectedNode?: TimelineModel.TimelineProfileTree.Node|null; - _textFilterUI?: UI.Toolbar.ToolbarInput; - _root?: TimelineModel.TimelineProfileTree.Node; + private currentThreadSetting?: Common.Settings.Setting<any>; + private lastSelectedNodeInternal?: TimelineModel.TimelineProfileTree.Node|null; + private textFilterUI?: UI.Toolbar.ToolbarInput; + private root?: TimelineModel.TimelineProfileTree.Node; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _currentResult?: any; + private currentResult?: any; constructor() { super(); - this._model = null; - this._track = null; - this._tree = null; + this.modelInternal = null; + this.track = null; + this.tree = null; this.element.classList.add('timeline-tree-view'); - this._searchResults = []; + this.searchResults = []; } static eventNameForSorting(event: SDK.TracingModel.Event): string { @@ -189,12 +187,12 @@ } setSearchableView(searchableView: UI.SearchableView.SearchableView): void { - this._searchableView = searchableView; + this.searchableView = searchableView; } setModel(model: PerformanceModel|null, track: TimelineModel.TimelineModel.Track|null): void { - this._model = model; - this._track = track; + this.modelInternal = model; + this.track = track; this.refreshTree(); } @@ -203,18 +201,18 @@ } model(): PerformanceModel|null { - return this._model; + return this.modelInternal; } init(): void { this.linkifier = new Components.Linkifier.Linkifier(); - this._taskFilter = + this.taskFilter = new TimelineModel.TimelineModelFilter.ExclusiveNameFilter([TimelineModel.TimelineModel.RecordType.Task]); - this._textFilter = new TimelineRegExp(); + this.textFilterInternal = new TimelineRegExp(); - this._currentThreadSetting = Common.Settings.Settings.instance().createSetting('timelineTreeCurrentThread', 0); - this._currentThreadSetting.addChangeListener(this.refreshTree, this); + this.currentThreadSetting = Common.Settings.Settings.instance().createSetting('timelineTreeCurrentThread', 0); + this.currentThreadSetting.addChangeListener(this.refreshTree, this); const columns = ([] as DataGrid.DataGrid.ColumnDescriptor[]); this.populateColumns(columns); @@ -232,12 +230,12 @@ editCallback: undefined, deleteCallback: undefined, }); - this.dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged, this._sortingChanged, this); - this.dataGrid.element.addEventListener('mousemove', this._onMouseMove.bind(this), true); + this.dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged, this.sortingChanged, this); + this.dataGrid.element.addEventListener('mousemove', this.onMouseMove.bind(this), true); this.dataGrid.setResizeMethod(DataGrid.DataGrid.ResizeMethod.Last); - this.dataGrid.setRowContextMenuCallback(this._onContextMenu.bind(this)); + this.dataGrid.setRowContextMenuCallback(this.onContextMenu.bind(this)); this.dataGrid.asWidget().show(mainView.element); - this.dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode, this._updateDetailsForSelection, this); + this.dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode, this.updateDetailsForSelection, this); this.detailsView = new UI.Widget.VBox(); this.detailsView.element.classList.add('timeline-details-view', 'timeline-details-view-body'); @@ -245,13 +243,13 @@ this.splitWidget.setSidebarWidget(this.detailsView); this.splitWidget.hideSidebar(); this.splitWidget.show(this.element); - this.splitWidget.addEventListener(UI.SplitWidget.Events.ShowModeChanged, this._onShowModeChanged, this); + this.splitWidget.addEventListener(UI.SplitWidget.Events.ShowModeChanged, this.onShowModeChanged, this); - this._lastSelectedNode; + this.lastSelectedNodeInternal; } lastSelectedNode(): TimelineModel.TimelineProfileTree.Node|null|undefined { - return this._lastSelectedNode; + return this.lastSelectedNodeInternal; } updateContents(selection: TimelineSelection): void { @@ -259,24 +257,24 @@ } setRange(startTime: number, endTime: number): void { - this._startTime = startTime; - this._endTime = endTime; + this.startTime = startTime; + this.endTime = endTime; this.refreshTree(); } filters(): TimelineModel.TimelineModelFilter.TimelineModelFilter[] { - return [this._taskFilter, this._textFilter, ...(this._model ? this._model.filters() : [])]; + return [this.taskFilter, this.textFilterInternal, ...(this.modelInternal ? this.modelInternal.filters() : [])]; } filtersWithoutTextFilter(): TimelineModel.TimelineModelFilter.TimelineModelFilter[] { - return [this._taskFilter, ...(this._model ? this._model.filters() : [])]; + return [this.taskFilter, ...(this.modelInternal ? this.modelInternal.filters() : [])]; } textFilter(): TimelineRegExp { - return this._textFilter; + return this.textFilterInternal; } - _exposePercentages(): boolean { + exposePercentages(): boolean { return false; } @@ -285,29 +283,29 @@ new UI.Toolbar.ToolbarInput(i18nString(UIStrings.filter), this.getToolbarInputAccessiblePlaceHolder()); textFilterUI.addEventListener(UI.Toolbar.ToolbarInput.Event.TextChanged, () => { const searchQuery = textFilterUI.value(); - this._textFilter.setRegExp(searchQuery ? createPlainTextSearchRegex(searchQuery, 'i') : null); + this.textFilterInternal.setRegExp(searchQuery ? createPlainTextSearchRegex(searchQuery, 'i') : null); this.refreshTree(); }, this); - this._textFilterUI = textFilterUI; + this.textFilterUI = textFilterUI; toolbar.appendToolbarItem(textFilterUI); } - _modelEvents(): SDK.TracingModel.Event[] { - return this._track ? this._track.syncEvents() : []; + modelEvents(): SDK.TracingModel.Event[] { + return this.track ? this.track.syncEvents() : []; } - _onHover(_node: TimelineModel.TimelineProfileTree.Node|null): void { + onHover(_node: TimelineModel.TimelineProfileTree.Node|null): void { } - _appendContextMenuItems(_contextMenu: UI.ContextMenu.ContextMenu, _node: TimelineModel.TimelineProfileTree.Node): + appendContextMenuItems(_contextMenu: UI.ContextMenu.ContextMenu, _node: TimelineModel.TimelineProfileTree.Node): void { } - _linkifyLocation(event: SDK.TracingModel.Event): Element|null { - if (!this._model) { + linkifyLocation(event: SDK.TracingModel.Event): Element|null { + if (!this.modelInternal) { return null; } - const target = this._model.timelineModel().targetByEvent(event); + const target = this.modelInternal.timelineModel().targetByEvent(event); if (!target) { return null; } @@ -340,15 +338,15 @@ refreshTree(): void { this.linkifier.reset(); this.dataGrid.rootNode().removeChildren(); - if (!this._model) { - this._updateDetailsForSelection(); + if (!this.modelInternal) { + this.updateDetailsForSelection(); return; } - this._root = this._buildTree(); - const children = this._root.children(); + this.root = this.buildTree(); + const children = this.root.children(); let maxSelfTime = 0; let maxTotalTime = 0; - const totalUsedTime = this._root.totalTime - this._root.selfTime; + const totalUsedTime = this.root.totalTime - this.root.selfTime; for (const child of children.values()) { maxSelfTime = Math.max(maxSelfTime, child.selfTime); maxTotalTime = Math.max(maxTotalTime, child.totalTime); @@ -358,10 +356,10 @@ const gridNode = new TreeGridNode(child, totalUsedTime, maxSelfTime, maxTotalTime, this); this.dataGrid.insertChild(gridNode); } - this._sortingChanged(); - this._updateDetailsForSelection(); - if (this._searchableView) { - this._searchableView.refreshSearch(); + this.sortingChanged(); + this.updateDetailsForSelection(); + if (this.searchableView) { + this.searchableView.refreshSearch(); } const rootNode = this.dataGrid.rootNode(); if (rootNode.children.length > 0) { @@ -369,14 +367,14 @@ } } - _buildTree(): TimelineModel.TimelineProfileTree.Node { + buildTree(): TimelineModel.TimelineProfileTree.Node { throw new Error('Not Implemented'); } buildTopDownTree(doNotAggregate: boolean, groupIdCallback: ((arg0: SDK.TracingModel.Event) => string)|null): TimelineModel.TimelineProfileTree.Node { return new TimelineModel.TimelineProfileTree.TopDownRootNode( - this._modelEvents(), this.filters(), this._startTime, this._endTime, doNotAggregate, groupIdCallback); + this.modelEvents(), this.filters(), this.startTime, this.endTime, doNotAggregate, groupIdCallback); } populateColumns(columns: DataGrid.DataGrid.ColumnDescriptor[]): void { @@ -391,7 +389,7 @@ DataGrid.DataGrid.ColumnDescriptor)); } - _sortingChanged(): void { + private sortingChanged(): void { const columnId = this.dataGrid.sortColumnId(); if (!columnId) { return; @@ -425,7 +423,7 @@ // eslint-disable-next-line @typescript-eslint/no-explicit-any // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - return (nodeA._profileNode as any)[field] - (nodeB._profileNode as any)[field]; + return (nodeA.profileNode as any)[field] - (nodeB.profileNode as any)[field]; } function compareStartTime( @@ -433,8 +431,8 @@ b: DataGrid.SortableDataGrid.SortableDataGridNode<GridNode>): number { const nodeA = (a as TreeGridNode); const nodeB = (b as TreeGridNode); - const eventA = (nodeA._profileNode.event as SDK.TracingModel.Event); - const eventB = (nodeB._profileNode.event as SDK.TracingModel.Event); + const eventA = (nodeA.profileNode.event as SDK.TracingModel.Event); + const eventB = (nodeB.profileNode.event as SDK.TracingModel.Event); return eventA.startTime - eventB.startTime; } @@ -443,67 +441,67 @@ b: DataGrid.SortableDataGrid.SortableDataGridNode<GridNode>): number { const nodeA = (a as TreeGridNode); const nodeB = (b as TreeGridNode); - const eventA = (nodeA._profileNode.event as SDK.TracingModel.Event); - const eventB = (nodeB._profileNode.event as SDK.TracingModel.Event); + const eventA = (nodeA.profileNode.event as SDK.TracingModel.Event); + const eventB = (nodeB.profileNode.event as SDK.TracingModel.Event); const nameA = TimelineTreeView.eventNameForSorting(eventA); const nameB = TimelineTreeView.eventNameForSorting(eventB); return nameA.localeCompare(nameB); } } - _onShowModeChanged(): void { + private onShowModeChanged(): void { if (this.splitWidget.showMode() === UI.SplitWidget.ShowMode.OnlyMain) { return; } - this._lastSelectedNode = undefined; - this._updateDetailsForSelection(); + this.lastSelectedNodeInternal = undefined; + this.updateDetailsForSelection(); } - _updateDetailsForSelection(): void { - const selectedNode = this.dataGrid.selectedNode ? (this.dataGrid.selectedNode as TreeGridNode)._profileNode : null; - if (selectedNode === this._lastSelectedNode) { + private updateDetailsForSelection(): void { + const selectedNode = this.dataGrid.selectedNode ? (this.dataGrid.selectedNode as TreeGridNode).profileNode : null; + if (selectedNode === this.lastSelectedNodeInternal) { return; } - this._lastSelectedNode = selectedNode; + this.lastSelectedNodeInternal = selectedNode; if (this.splitWidget.showMode() === UI.SplitWidget.ShowMode.OnlyMain) { return; } this.detailsView.detachChildWidgets(); this.detailsView.element.removeChildren(); - if (selectedNode && this._showDetailsForNode(selectedNode)) { + if (selectedNode && this.showDetailsForNode(selectedNode)) { return; } const banner = this.detailsView.element.createChild('div', 'full-widget-dimmed-banner'); UI.UIUtils.createTextChild(banner, i18nString(UIStrings.selectItemForDetails)); } - _showDetailsForNode(_node: TimelineModel.TimelineProfileTree.Node): boolean { + showDetailsForNode(_node: TimelineModel.TimelineProfileTree.Node): boolean { return false; } - _onMouseMove(event: Event): void { + private onMouseMove(event: Event): void { const gridNode = event.target && (event.target instanceof Node) ? (this.dataGrid.dataGridNodeFromNode((event.target as Node))) : null; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // @ts-expect-error const profileNode = gridNode && gridNode._profileNode; - if (profileNode === this._lastHoveredProfileNode) { + if (profileNode === this.lastHoveredProfileNode) { return; } - this._lastHoveredProfileNode = profileNode; - this._onHover(profileNode); + this.lastHoveredProfileNode = profileNode; + this.onHover(profileNode); } - _onContextMenu(contextMenu: UI.ContextMenu.ContextMenu, eventGridNode: DataGrid.DataGrid.DataGridNode<GridNode>): - void { + private onContextMenu( + contextMenu: UI.ContextMenu.ContextMenu, eventGridNode: DataGrid.DataGrid.DataGridNode<GridNode>): void { const gridNode = (eventGridNode as GridNode); - if (gridNode._linkElement && !contextMenu.containsTarget(gridNode._linkElement)) { - contextMenu.appendApplicableItems(gridNode._linkElement); + if (gridNode.linkElement && !contextMenu.containsTarget(gridNode.linkElement)) { + contextMenu.appendApplicableItems(gridNode.linkElement); } - const profileNode = gridNode._profileNode; + const profileNode = gridNode.profileNode; if (profileNode) { - this._appendContextMenuItems(contextMenu, profileNode); + this.appendContextMenuItems(contextMenu, profileNode); } } @@ -514,35 +512,35 @@ // UI.SearchableView.Searchable implementation searchCanceled(): void { - this._searchResults = []; - this._currentResult = 0; + this.searchResults = []; + this.currentResult = 0; } performSearch(searchConfig: UI.SearchableView.SearchConfig, _shouldJump: boolean, _jumpBackwards?: boolean): void { - this._searchResults = []; - this._currentResult = 0; - if (!this._root) { + this.searchResults = []; + this.currentResult = 0; + if (!this.root) { return; } const searchRegex = searchConfig.toSearchRegex(); - this._searchResults = this._root.searchTree(event => TimelineUIUtils.testContentMatching(event, searchRegex)); - this._searchableView.updateSearchMatchesCount(this._searchResults.length); + this.searchResults = this.root.searchTree(event => TimelineUIUtils.testContentMatching(event, searchRegex)); + this.searchableView.updateSearchMatchesCount(this.searchResults.length); } jumpToNextSearchResult(): void { - if (!this._searchResults.length) { + if (!this.searchResults.length) { return; } - this.selectProfileNode(this._searchResults[this._currentResult], false); - this._currentResult = Platform.NumberUtilities.mod(this._currentResult + 1, this._searchResults.length); + this.selectProfileNode(this.searchResults[this.currentResult], false); + this.currentResult = Platform.NumberUtilities.mod(this.currentResult + 1, this.searchResults.length); } jumpToPreviousSearchResult(): void { - if (!this._searchResults.length) { + if (!this.searchResults.length) { return; } - this.selectProfileNode(this._searchResults[this._currentResult], false); - this._currentResult = Platform.NumberUtilities.mod(this._currentResult - 1, this._searchResults.length); + this.selectProfileNode(this.searchResults[this.currentResult], false); + this.currentResult = Platform.NumberUtilities.mod(this.currentResult - 1, this.searchResults.length); } supportsCaseSensitiveSearch(): boolean { @@ -555,44 +553,44 @@ } export class GridNode extends DataGrid.SortableDataGrid.SortableDataGridNode<GridNode> { - _populated: boolean; - _profileNode: TimelineModel.TimelineProfileTree.Node; - _treeView: TimelineTreeView; - _grandTotalTime: number; - _maxSelfTime: number; - _maxTotalTime: number; - _linkElement: Element|null; + protected populated: boolean; + profileNode: TimelineModel.TimelineProfileTree.Node; + protected treeView: TimelineTreeView; + protected grandTotalTime: number; + protected maxSelfTime: number; + protected maxTotalTime: number; + linkElement: Element|null; constructor( profileNode: TimelineModel.TimelineProfileTree.Node, grandTotalTime: number, maxSelfTime: number, maxTotalTime: number, treeView: TimelineTreeView) { super(null, false); - this._populated = false; - this._profileNode = profileNode; - this._treeView = treeView; - this._grandTotalTime = grandTotalTime; - this._maxSelfTime = maxSelfTime; - this._maxTotalTime = maxTotalTime; - this._linkElement = null; + this.populated = false; + this.profileNode = profileNode; + this.treeView = treeView; + this.grandTotalTime = grandTotalTime; + this.maxSelfTime = maxSelfTime; + this.maxTotalTime = maxTotalTime; + this.linkElement = null; } createCell(columnId: string): HTMLElement { if (columnId === 'activity') { - return this._createNameCell(columnId); + return this.createNameCell(columnId); } - return this._createValueCell(columnId) || super.createCell(columnId); + return this.createValueCell(columnId) || super.createCell(columnId); } - _createNameCell(columnId: string): HTMLElement { + private createNameCell(columnId: string): HTMLElement { const cell = this.createTD(columnId); const container = cell.createChild('div', 'name-container'); const iconContainer = container.createChild('div', 'activity-icon-container'); const icon = iconContainer.createChild('div', 'activity-icon'); const name = container.createChild('div', 'activity-name'); - const event = this._profileNode.event; - if (this._profileNode.isGroupNode()) { - const treeView = (this._treeView as AggregatedTimelineTreeView); - const info = treeView._displayInfoForGroupNode(this._profileNode); + const event = this.profileNode.event; + if (this.profileNode.isGroupNode()) { + const treeView = (this.treeView as AggregatedTimelineTreeView); + const info = treeView.displayInfoForGroupNode(this.profileNode); name.textContent = info.name; icon.style.backgroundColor = info.color; if (info.icon) { @@ -607,9 +605,9 @@ } name.textContent = TimelineUIUtils.eventTitle(event); - this._linkElement = this._treeView._linkifyLocation(event); - if (this._linkElement) { - container.createChild('div', 'activity-link').appendChild(this._linkElement); + this.linkElement = this.treeView.linkifyLocation(event); + if (this.linkElement) { + container.createChild('div', 'activity-link').appendChild(this.linkElement); } const eventStyle = TimelineUIUtils.eventStyle(event); const eventCategory = eventStyle.category; @@ -619,7 +617,7 @@ return cell; } - _createValueCell(columnId: string): HTMLElement|null { + private createValueCell(columnId: string): HTMLElement|null { if (columnId !== 'self' && columnId !== 'total' && columnId !== 'startTime') { return null; } @@ -629,21 +627,22 @@ let maxTime: number|undefined; let event: SDK.TracingModel.Event|null; switch (columnId) { - case 'startTime': - event = this._profileNode.event; - if (!this._treeView._model) { + case 'startTime': { + event = this.profileNode.event; + const model = this.treeView.model(); + if (!model) { throw new Error('Unable to find model for tree view'); } - value = (event ? event.startTime : 0) - this._treeView._model.timelineModel().minimumRecordTime(); - break; + value = (event ? event.startTime : 0) - model.timelineModel().minimumRecordTime(); + } break; case 'self': - value = this._profileNode.selfTime; - maxTime = this._maxSelfTime; + value = this.profileNode.selfTime; + maxTime = this.maxSelfTime; showPercents = true; break; case 'total': - value = this._profileNode.totalTime; - maxTime = this._maxTotalTime; + value = this.profileNode.totalTime; + maxTime = this.maxTotalTime; showPercents = true; break; default: @@ -654,9 +653,9 @@ const textDiv = cell.createChild('div'); textDiv.createChild('span').textContent = i18nString(UIStrings.fms, {PH1: value.toFixed(1)}); - if (showPercents && this._treeView._exposePercentages()) { + if (showPercents && this.treeView.exposePercentages()) { textDiv.createChild('span', 'percent-column').textContent = - i18nString(UIStrings.percentPlaceholder, {PH1: (value / this._grandTotalTime * 100).toFixed(1)}); + i18nString(UIStrings.percentPlaceholder, {PH1: (value / this.grandTotalTime * 100).toFixed(1)}); } if (maxTime) { textDiv.classList.add('background-percent-bar'); @@ -672,28 +671,27 @@ profileNode: TimelineModel.TimelineProfileTree.Node, grandTotalTime: number, maxSelfTime: number, maxTotalTime: number, treeView: TimelineTreeView) { super(profileNode, grandTotalTime, maxSelfTime, maxTotalTime, treeView); - this.setHasChildren(this._profileNode.hasChildren()); + this.setHasChildren(this.profileNode.hasChildren()); profileNodeToTreeGridNode.set(profileNode, this); } populate(): void { - if (this._populated) { + if (this.populated) { return; } - this._populated = true; - if (!this._profileNode.children) { + this.populated = true; + if (!this.profileNode.children) { return; } - for (const node of this._profileNode.children().values()) { - const gridNode = - new TreeGridNode(node, this._grandTotalTime, this._maxSelfTime, this._maxTotalTime, this._treeView); + for (const node of this.profileNode.children().values()) { + const gridNode = new TreeGridNode(node, this.grandTotalTime, this.maxSelfTime, this.maxTotalTime, this.treeView); this.insertChildOrdered(gridNode); } } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/naming-convention - static readonly _gridNodeSymbol = Symbol('treeGridNode'); + private static readonly gridNodeSymbol = Symbol('treeGridNode'); } const profileNodeToTreeGridNode = new WeakMap<TimelineModel.TimelineProfileTree.Node, TreeGridNode>(); @@ -701,28 +699,27 @@ export class AggregatedTimelineTreeView extends TimelineTreeView { // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _groupBySetting: Common.Settings.Setting<any>; - _stackView: TimelineStackView; - _productByURLCache: Map<string, string>; - _colorByURLCache: Map<string, string>; + protected readonly groupBySetting: Common.Settings.Setting<any>; + private readonly stackView: TimelineStackView; + private readonly productByURLCache: Map<string, string>; + private readonly colorByURLCache: Map<string, string>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any - _executionContextNamesByOrigin: Map<any, any>; + private executionContextNamesByOrigin: Map<any, any>; constructor() { super(); - this._groupBySetting = Common.Settings.Settings.instance().createSetting( + this.groupBySetting = Common.Settings.Settings.instance().createSetting( 'timelineTreeGroupBy', AggregatedTimelineTreeView.GroupBy.None); - this._groupBySetting.addChangeListener(this.refreshTree.bind(this)); + this.groupBySetting.addChangeListener(this.refreshTree.bind(this)); this.init(); - this._stackView = new TimelineStackView(this); - this._stackView.addEventListener( - TimelineStackView.Events.SelectionChanged, this._onStackViewSelectionChanged, this); - this._productByURLCache = new Map(); - this._colorByURLCache = new Map(); - this._executionContextNamesByOrigin = new Map(); + this.stackView = new TimelineStackView(this); + this.stackView.addEventListener(TimelineStackView.Events.SelectionChanged, this.onStackViewSelectionChanged, this); + this.productByURLCache = new Map(); + this.colorByURLCache = new Map(); + this.executionContextNamesByOrigin = new Map(); } setModel(model: PerformanceModel|null, track: TimelineModel.TimelineModel.Track|null): void { @@ -730,7 +727,7 @@ } updateContents(selection: TimelineSelection): void { - this._updateExtensionResolver(); + this.updateExtensionResolver(); super.updateContents(selection); const rootNode = this.dataGrid.rootNode(); if (rootNode.children.length) { @@ -738,27 +735,27 @@ } } - _updateExtensionResolver(): void { - this._executionContextNamesByOrigin = new Map(); + private updateExtensionResolver(): void { + this.executionContextNamesByOrigin = new Map(); for (const runtimeModel of SDK.TargetManager.TargetManager.instance().models(SDK.RuntimeModel.RuntimeModel)) { for (const context of runtimeModel.executionContexts()) { - this._executionContextNamesByOrigin.set(context.origin, context.name); + this.executionContextNamesByOrigin.set(context.origin, context.name); } } } - _beautifyDomainName(this: AggregatedTimelineTreeView, name: string): string { - if (AggregatedTimelineTreeView._isExtensionInternalURL(name)) { + private beautifyDomainName(this: AggregatedTimelineTreeView, name: string): string { + if (AggregatedTimelineTreeView.isExtensionInternalURL(name)) { name = i18nString(UIStrings.chromeExtensionsOverhead); - } else if (AggregatedTimelineTreeView._isV8NativeURL(name)) { + } else if (AggregatedTimelineTreeView.isV8NativeURL(name)) { name = i18nString(UIStrings.vRuntime); } else if (name.startsWith('chrome-extension')) { - name = this._executionContextNamesByOrigin.get(name) || name; + name = this.executionContextNamesByOrigin.get(name) || name; } return name; } - _displayInfoForGroupNode(node: TimelineModel.TimelineProfileTree.Node): { + displayInfoForGroupNode(node: TimelineModel.TimelineProfileTree.Node): { name: string, color: string, icon: (Element|undefined), @@ -770,7 +767,7 @@ const id = typeof node.id === 'symbol' ? undefined : node.id; - switch (this._groupBySetting.get()) { + switch (this.groupBySetting.get()) { case AggregatedTimelineTreeView.GroupBy.Category: { const category = id ? categories[id] || categories['other'] : {title: unattributed, color: unattributed}; return {name: category.title, color: category.color, icon: undefined}; @@ -778,7 +775,7 @@ case AggregatedTimelineTreeView.GroupBy.Domain: case AggregatedTimelineTreeView.GroupBy.Subdomain: { - const domainName = id ? this._beautifyDomainName(id) : undefined; + const domainName = id ? this.beautifyDomainName(id) : undefined; return {name: domainName || unattributed, color: color, icon: undefined}; } @@ -802,10 +799,10 @@ break; case AggregatedTimelineTreeView.GroupBy.Frame: { - if (!this._model) { + if (!this.modelInternal) { throw new Error('Unable to find model for group by frame operation'); } - const frame = id ? this._model.timelineModel().pageFrameById(id) : undefined; + const frame = id ? this.modelInternal.timelineModel().pageFrameById(id) : undefined; const frameName = frame ? TimelineUIUtils.displayNameForFrame(frame, 80) : i18nString(UIStrings.page); return {name: frameName, color: color, icon: undefined}; } @@ -829,13 +826,14 @@ {label: i18nString(UIStrings.groupByUrl), value: groupBy.URL}, ]; toolbar.appendToolbarItem( - new UI.Toolbar.ToolbarSettingComboBox(options, this._groupBySetting, i18nString(UIStrings.groupBy))); + new UI.Toolbar.ToolbarSettingComboBox(options, this.groupBySetting, i18nString(UIStrings.groupBy))); toolbar.appendSpacer(); toolbar.appendToolbarItem(this.splitWidget.createShowHideSidebarButton( i18nString(UIStrings.showHeaviestStack), i18nString(UIStrings.hideHeaviestStack))); } - _buildHeaviestStack(treeNode: TimelineModel.TimelineProfileTree.Node): TimelineModel.TimelineProfileTree.Node[] { + private buildHeaviestStack(treeNode: TimelineModel.TimelineProfileTree.Node): + TimelineModel.TimelineProfileTree.Node[] { console.assert(Boolean(treeNode.parent), 'Attempt to build stack for tree root'); let result: TimelineModel.TimelineProfileTree.Node[] = []; // Do not add root to the stack, as it's the tree itself. @@ -852,25 +850,25 @@ return result; } - _exposePercentages(): boolean { + exposePercentages(): boolean { return true; } - _onStackViewSelectionChanged(): void { - const treeNode = this._stackView.selectedTreeNode(); + private onStackViewSelectionChanged(): void { + const treeNode = this.stackView.selectedTreeNode(); if (treeNode) { this.selectProfileNode(treeNode, true); } } - _showDetailsForNode(node: TimelineModel.TimelineProfileTree.Node): boolean { - const stack = this._buildHeaviestStack(node); - this._stackView.setStack(stack, node); - this._stackView.show(this.detailsView.element); + showDetailsForNode(node: TimelineModel.TimelineProfileTree.Node): boolean { + const stack = this.buildHeaviestStack(node); + this.stackView.setStack(stack, node); + this.stackView.show(this.detailsView.element); return true; } - _groupingFunction(groupBy: string): ((arg0: SDK.TracingModel.Event) => string)|null { + protected groupingFunction(groupBy: string): ((arg0: SDK.TracingModel.Event) => string)|null { const GroupBy = AggregatedTimelineTreeView.GroupBy; switch (groupBy) { case GroupBy.None: @@ -880,9 +878,9 @@ case GroupBy.Category: return (event: SDK.TracingModel.Event): string => TimelineUIUtils.eventStyle(event).category.name; case GroupBy.Subdomain: - return this._domainByEvent.bind(this, false); + return this.domainByEvent.bind(this, false); case GroupBy.Domain: - return this._domainByEvent.bind(this, true); + return this.domainByEvent.bind(this, true); case GroupBy.URL: return (event: SDK.TracingModel.Event): string => TimelineModel.TimelineProfileTree.eventURL(event) || ''; case GroupBy.Frame: @@ -894,16 +892,16 @@ } } - _domainByEvent(groupSubdomains: boolean, event: SDK.TracingModel.Event): string { + private domainByEvent(groupSubdomains: boolean, event: SDK.TracingModel.Event): string { const url = TimelineModel.TimelineProfileTree.eventURL(event); if (!url) { return ''; } - if (AggregatedTimelineTreeView._isExtensionInternalURL(url)) { - return AggregatedTimelineTreeView._extensionInternalPrefix; + if (AggregatedTimelineTreeView.isExtensionInternalURL(url)) { + return AggregatedTimelineTreeView.extensionInternalPrefix; } - if (AggregatedTimelineTreeView._isV8NativeURL(url)) { - return AggregatedTimelineTreeView._v8NativePrefix; + if (AggregatedTimelineTreeView.isV8NativeURL(url)) { + return AggregatedTimelineTreeView.v8NativePrefix; } const parsedURL = Common.ParsedURL.ParsedURL.fromString(url); if (!parsedURL) { @@ -922,37 +920,37 @@ return domainMatch && domainMatch[0] || ''; } - _appendContextMenuItems(contextMenu: UI.ContextMenu.ContextMenu, node: TimelineModel.TimelineProfileTree.Node): void { - if (this._groupBySetting.get() !== AggregatedTimelineTreeView.GroupBy.Frame) { + appendContextMenuItems(contextMenu: UI.ContextMenu.ContextMenu, node: TimelineModel.TimelineProfileTree.Node): void { + if (this.groupBySetting.get() !== AggregatedTimelineTreeView.GroupBy.Frame) { return; } if (!node.isGroupNode()) { return; } - if (!this._model) { + if (!this.modelInternal) { return; } - const frame = this._model.timelineModel().pageFrameById((node.id as string)); + const frame = this.modelInternal.timelineModel().pageFrameById((node.id as string)); if (!frame || !frame.ownerNode) { return; } contextMenu.appendApplicableItems(frame.ownerNode); } - static _isExtensionInternalURL(url: string): boolean { - return url.startsWith(AggregatedTimelineTreeView._extensionInternalPrefix); + private static isExtensionInternalURL(url: string): boolean { + return url.startsWith(AggregatedTimelineTreeView.extensionInternalPrefix); } - static _isV8NativeURL(url: string): boolean { - return url.startsWith(AggregatedTimelineTreeView._v8NativePrefix); + private static isV8NativeURL(url: string): boolean { + return url.startsWith(AggregatedTimelineTreeView.v8NativePrefix); } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/naming-convention - static readonly _extensionInternalPrefix = 'extensions::'; + private static readonly extensionInternalPrefix = 'extensions::'; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/naming-convention - static readonly _v8NativePrefix = 'native '; + private static readonly v8NativePrefix = 'native '; } export namespace AggregatedTimelineTreeView { // TODO(crbug.com/1167717): Make this a const enum again @@ -978,9 +976,9 @@ return i18nString(UIStrings.filterCallTree); } - _buildTree(): TimelineModel.TimelineProfileTree.Node { - const grouping = this._groupBySetting.get(); - return this.buildTopDownTree(false, this._groupingFunction(grouping)); + buildTree(): TimelineModel.TimelineProfileTree.Node { + const grouping = this.groupBySetting.get(); + return this.buildTopDownTree(false, this.groupingFunction(grouping)); } } @@ -994,46 +992,46 @@ return i18nString(UIStrings.filterBottomup); } - _buildTree(): TimelineModel.TimelineProfileTree.Node { + buildTree(): TimelineModel.TimelineProfileTree.Node { return new TimelineModel.TimelineProfileTree.BottomUpRootNode( - this._modelEvents(), this.textFilter(), this.filtersWithoutTextFilter(), this._startTime, this._endTime, - this._groupingFunction(this._groupBySetting.get())); + this.modelEvents(), this.textFilter(), this.filtersWithoutTextFilter(), this.startTime, this.endTime, + this.groupingFunction(this.groupBySetting.get())); } } export class TimelineStackView extends UI.Widget.VBox { - _treeView: TimelineTreeView; - _dataGrid: DataGrid.ViewportDataGrid.ViewportDataGrid<unknown>; + private readonly treeView: TimelineTreeView; + private readonly dataGrid: DataGrid.ViewportDataGrid.ViewportDataGrid<unknown>; constructor(treeView: TimelineTreeView) { super(); const header = this.element.createChild('div', 'timeline-stack-view-header'); header.textContent = i18nString(UIStrings.heaviestStack); - this._treeView = treeView; + this.treeView = treeView; const columns = ([ {id: 'total', title: i18nString(UIStrings.totalTime), fixedWidth: true, width: '110px'}, {id: 'activity', title: i18nString(UIStrings.activity)}, ] as DataGrid.DataGrid.ColumnDescriptor[]); - this._dataGrid = new DataGrid.ViewportDataGrid.ViewportDataGrid({ + this.dataGrid = new DataGrid.ViewportDataGrid.ViewportDataGrid({ displayName: i18nString(UIStrings.timelineStack), columns, deleteCallback: undefined, editCallback: undefined, refreshCallback: undefined, }); - this._dataGrid.setResizeMethod(DataGrid.DataGrid.ResizeMethod.Last); - this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode, this._onSelectionChanged, this); - this._dataGrid.asWidget().show(this.element); + this.dataGrid.setResizeMethod(DataGrid.DataGrid.ResizeMethod.Last); + this.dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode, this.onSelectionChanged, this); + this.dataGrid.asWidget().show(this.element); } setStack(stack: TimelineModel.TimelineProfileTree.Node[], selectedNode: TimelineModel.TimelineProfileTree.Node): void { - const rootNode = this._dataGrid.rootNode(); + const rootNode = this.dataGrid.rootNode(); rootNode.removeChildren(); let nodeToReveal: GridNode|null = null; const totalTime = Math.max.apply(Math, stack.map(node => node.totalTime)); for (const node of stack) { - const gridNode = new GridNode(node, totalTime, totalTime, totalTime, this._treeView); + const gridNode = new GridNode(node, totalTime, totalTime, totalTime, this.treeView); rootNode.appendChild(gridNode); if (node === selectedNode) { nodeToReveal = gridNode; @@ -1045,11 +1043,11 @@ } selectedTreeNode(): TimelineModel.TimelineProfileTree.Node|null { - const selectedNode = this._dataGrid.selectedNode; - return selectedNode && (selectedNode as GridNode)._profileNode; + const selectedNode = this.dataGrid.selectedNode; + return selectedNode && (selectedNode as GridNode).profileNode; } - _onSelectionChanged(): void { + private onSelectionChanged(): void { this.dispatchEventToListeners(TimelineStackView.Events.SelectionChanged); } }
diff --git a/front_end/panels/timeline/TimelineUIUtils.ts b/front_end/panels/timeline/TimelineUIUtils.ts index dc8b0f9..64a42fb 100644 --- a/front_end/panels/timeline/TimelineUIUtils.ts +++ b/front_end/panels/timeline/TimelineUIUtils.ts
@@ -33,8 +33,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; @@ -1235,7 +1233,7 @@ [x: string]: TimelineRecordStyle; } export class TimelineUIUtils { - static _initEventStyles(): EventStylesMap { + private static initEventStyles(): EventStylesMap { if (eventStylesMap) { return eventStylesMap; } @@ -1472,7 +1470,7 @@ } static eventStyle(event: SDK.TracingModel.Event): TimelineRecordStyle { - const eventStyles = TimelineUIUtils._initEventStyles(); + const eventStyles = TimelineUIUtils.initEventStyles(); if (event.hasCategory(TimelineModel.TimelineModel.TimelineModelImpl.Category.Console) || event.hasCategory(TimelineModel.TimelineModel.TimelineModelImpl.Category.UserTiming)) { return new TimelineRecordStyle(event.name, TimelineUIUtils.categories()['scripting']); @@ -1563,7 +1561,7 @@ return title; } - static _interactionPhaseStyles(): Map<TimelineModel.TimelineIRModel.Phases, { + private static interactionPhaseStyles(): Map<TimelineModel.TimelineIRModel.Phases, { color: string, label: string, }> { @@ -1602,7 +1600,7 @@ } static interactionPhaseColor(phase: TimelineModel.TimelineIRModel.Phases): string { - const interactionPhase = TimelineUIUtils._interactionPhaseStyles().get(phase); + const interactionPhase = TimelineUIUtils.interactionPhaseStyles().get(phase); if (!interactionPhase) { throw new Error(`Unknown phase ${phase}`); } @@ -1610,7 +1608,7 @@ } static interactionPhaseLabel(phase: TimelineModel.TimelineIRModel.Phases): string { - const interactionPhase = TimelineUIUtils._interactionPhaseStyles().get(phase); + const interactionPhase = TimelineUIUtils.interactionPhaseStyles().get(phase); if (!interactionPhase) { throw new Error(`Unknown phase ${phase}`); } @@ -2016,7 +2014,7 @@ } const invalidationTrackingEvents = TimelineModel.TimelineModel.InvalidationTracker.invalidationEventsFor(event); if (invalidationTrackingEvents) { - TimelineUIUtils._collectInvalidationNodeIds(nodeIdsToResolve, invalidationTrackingEvents); + TimelineUIUtils.collectInvalidationNodeIds(nodeIdsToResolve, invalidationTrackingEvents); } if (nodeIdsToResolve.size) { const domModel = target.model(SDK.DOMModel.DOMModel); @@ -2438,13 +2436,13 @@ if (initiator || timelineData.stackTraceForSelfOrInitiator() || TimelineModel.TimelineModel.InvalidationTracker.invalidationEventsFor(event)) { - TimelineUIUtils._generateCauses(event, model.targetByEvent(event), relatedNodesMap, contentHelper); + TimelineUIUtils.generateCauses(event, model.targetByEvent(event), relatedNodesMap, contentHelper); } const stats: { [x: string]: number, } = {}; - const showPieChart = detailed && TimelineUIUtils._aggregatedStatsForTraceEvent(stats, model, event); + const showPieChart = detailed && TimelineUIUtils.aggregatedStatsForTraceEvent(stats, model, event); if (showPieChart) { contentHelper.addSection(i18nString(UIStrings.aggregatedTime)); const pieChart = @@ -2704,11 +2702,11 @@ return contentHelper.fragment; } - static _stackTraceFromCallFrames(callFrames: Protocol.Runtime.CallFrame[]): Protocol.Runtime.StackTrace { + static stackTraceFromCallFrames(callFrames: Protocol.Runtime.CallFrame[]): Protocol.Runtime.StackTrace { return {callFrames: callFrames} as Protocol.Runtime.StackTrace; } - static _generateCauses( + private static generateCauses( event: SDK.TracingModel.Event, target: SDK.Target.Target|null, relatedNodesMap: Map<number, SDK.DOMModel.DOMNode|null>|null, contentHelper: TimelineDetailsContentHelper): void { const recordTypes = TimelineModel.TimelineModel.RecordType; @@ -2742,7 +2740,7 @@ contentHelper.addSection(i18nString(UIStrings.callStacks)); contentHelper.appendStackTrace( stackLabel || i18nString(UIStrings.stackTrace), - TimelineUIUtils._stackTraceFromCallFrames(timelineData.stackTrace)); + TimelineUIUtils.stackTraceFromCallFrames(timelineData.stackTrace)); } const initiator = TimelineModel.TimelineModel.TimelineData.forEvent(event).initiator(); @@ -2750,7 +2748,7 @@ if (TimelineModel.TimelineModel.InvalidationTracker.invalidationEventsFor(event) && target) { // Full invalidation tracking (experimental). contentHelper.addSection(i18nString(UIStrings.invalidations)); - TimelineUIUtils._generateInvalidations(event, target, relatedNodesMap, contentHelper); + TimelineUIUtils.generateInvalidations(event, target, relatedNodesMap, contentHelper); } else if (initiator) { // Partial invalidation tracking. const delay = event.startTime - initiator.startTime; contentHelper.appendTextRow(i18nString(UIStrings.pendingFor), i18n.TimeUtilities.preciseMillisToString(delay, 1)); @@ -2775,12 +2773,12 @@ if (initiatorStackTrace) { contentHelper.appendStackTrace( callSiteStackLabel || i18nString(UIStrings.firstInvalidated), - TimelineUIUtils._stackTraceFromCallFrames(initiatorStackTrace)); + TimelineUIUtils.stackTraceFromCallFrames(initiatorStackTrace)); } } } - static _generateInvalidations( + private static generateInvalidations( event: SDK.TracingModel.Event, target: SDK.Target.Target, relatedNodesMap: Map<number, SDK.DOMModel.DOMNode|null>|null, contentHelper: TimelineDetailsContentHelper): void { const invalidationTrackingEvents = TimelineModel.TimelineModel.InvalidationTracker.invalidationEventsFor(event); @@ -2799,11 +2797,11 @@ } Object.keys(invalidations).forEach(function(type) { - TimelineUIUtils._generateInvalidationsForType(type, target, invalidations[type], relatedNodesMap, contentHelper); + TimelineUIUtils.generateInvalidationsForType(type, target, invalidations[type], relatedNodesMap, contentHelper); }); } - static _generateInvalidationsForType( + private static generateInvalidationsForType( type: string, target: SDK.Target.Target, invalidations: TimelineModel.TimelineModel.InvalidationTrackingEvent[], relatedNodesMap: Map<number, SDK.DOMModel.DOMNode|null>|null, contentHelper: TimelineDetailsContentHelper): void { let title; @@ -2860,12 +2858,12 @@ } } - static _collectInvalidationNodeIds( + private static collectInvalidationNodeIds( nodeIds: Set<number>, invalidations: TimelineModel.TimelineModel.InvalidationTrackingEvent[]): void { Platform.SetUtilities.addAll(nodeIds, invalidations.map(invalidation => invalidation.nodeId).filter(id => id)); } - static _aggregatedStatsForTraceEvent( + private static aggregatedStatsForTraceEvent( total: { [x: string]: number, }, @@ -2961,8 +2959,8 @@ return eventDivider; } - static _visibleTypes(): string[] { - const eventStyles = TimelineUIUtils._initEventStyles(); + private static visibleTypes(): string[] { + const eventStyles = TimelineUIUtils.initEventStyles(); const result = []; for (const name in eventStyles) { if (!eventStyles[name].hidden) { @@ -2973,7 +2971,7 @@ } static visibleEventsFilter(): TimelineModel.TimelineModelFilter.TimelineModelFilter { - return new TimelineModel.TimelineModelFilter.TimelineVisibleEventsFilter(TimelineUIUtils._visibleTypes()); + return new TimelineModel.TimelineModelFilter.TimelineVisibleEventsFilter(TimelineUIUtils.visibleTypes()); } static categories(): { @@ -3379,9 +3377,9 @@ export class InvalidationsGroupElement extends UI.TreeOutline.TreeElement { toggleOnClick: boolean; - _relatedNodesMap: Map<number, SDK.DOMModel.DOMNode|null>|null; - _contentHelper: TimelineDetailsContentHelper; - _invalidations: TimelineModel.TimelineModel.InvalidationTrackingEvent[]; + private readonly relatedNodesMap: Map<number, SDK.DOMModel.DOMNode|null>|null; + private readonly contentHelper: TimelineDetailsContentHelper; + private readonly invalidations: TimelineModel.TimelineModel.InvalidationTrackingEvent[]; constructor( target: SDK.Target.Target, relatedNodesMap: Map<number, SDK.DOMModel.DOMNode|null>|null, @@ -3393,30 +3391,30 @@ this.selectable = false; this.toggleOnClick = true; - this._relatedNodesMap = relatedNodesMap; - this._contentHelper = contentHelper; - this._invalidations = invalidations; - this.title = this._createTitle(target); + this.relatedNodesMap = relatedNodesMap; + this.contentHelper = contentHelper; + this.invalidations = invalidations; + this.title = this.createTitle(target); } - _createTitle(target: SDK.Target.Target): Element { - const first = this._invalidations[0]; + private createTitle(target: SDK.Target.Target): Element { + const first = this.invalidations[0]; const reason = first.cause.reason || i18nString(UIStrings.unknownCause); const topFrame = first.cause.stackTrace && first.cause.stackTrace[0]; - const truncatedNodesElement = this._getTruncatedNodesElement(this._invalidations); + const truncatedNodesElement = this.getTruncatedNodesElement(this.invalidations); if (truncatedNodesElement === null) { return i18n.i18n.getFormatLocalizedString(str_, UIStrings.emptyPlaceholder, {PH1: reason}); } const title = i18n.i18n.getFormatLocalizedString(str_, UIStrings.sForS, {PH1: reason, PH2: truncatedNodesElement}); - if (topFrame && this._contentHelper.linkifier()) { + if (topFrame && this.contentHelper.linkifier()) { const stack = document.createElement('span'); stack.classList.add('monospace'); const completeTitle = i18n.i18n.getFormatLocalizedString(str_, UIStrings.sSDot, {PH1: title, PH2: stack}); stack.createChild('span').textContent = TimelineUIUtils.frameDisplayName(topFrame); - const linkifier = this._contentHelper.linkifier(); + const linkifier = this.contentHelper.linkifier(); if (linkifier) { const link = linkifier.maybeLinkifyConsoleCallFrame(target, topFrame); if (link) { @@ -3439,21 +3437,21 @@ const content = document.createElement('div'); content.classList.add('content'); - const first = this._invalidations[0]; + const first = this.invalidations[0]; if (first.cause.stackTrace) { const stack = content.createChild('div'); UI.UIUtils.createTextChild(stack, i18nString(UIStrings.stackTraceColon)); - this._contentHelper.createChildStackTraceElement( - stack, TimelineUIUtils._stackTraceFromCallFrames(first.cause.stackTrace)); + this.contentHelper.createChildStackTraceElement( + stack, TimelineUIUtils.stackTraceFromCallFrames(first.cause.stackTrace)); } UI.UIUtils.createTextChild( - content, this._invalidations.length !== 1 ? i18nString(UIStrings.nodes) : i18nString(UIStrings.node)); + content, this.invalidations.length !== 1 ? i18nString(UIStrings.nodes) : i18nString(UIStrings.node)); const nodeList = content.createChild('div', 'node-list'); let firstNode = true; - for (let i = 0; i < this._invalidations.length; i++) { - const invalidation = this._invalidations[i]; - const invalidationNode = this._createInvalidationNode(invalidation, true); + for (let i = 0; i < this.invalidations.length; i++) { + const invalidation = this.invalidations[i]; + const invalidationNode = this.createInvalidationNode(invalidation, true); if (invalidationNode) { if (!firstNode) { UI.UIUtils.createTextChild(nodeList, ', '); @@ -3488,14 +3486,15 @@ this.appendChild(contentTreeElement); } - _getTruncatedNodesElement(invalidations: TimelineModel.TimelineModel.InvalidationTrackingEvent[]): Element|null { + private getTruncatedNodesElement(invalidations: TimelineModel.TimelineModel.InvalidationTrackingEvent[]): Element + |null { const invalidationNodes = []; const invalidationNodeIdMap: { [x: number]: boolean, } = {}; for (let i = 0; i < invalidations.length; i++) { const invalidation = invalidations[i]; - const invalidationNode = this._createInvalidationNode(invalidation, false); + const invalidationNode = this.createInvalidationNode(invalidation, false); invalidationNode.addEventListener( 'click', @@ -3530,10 +3529,10 @@ return null; } - _createInvalidationNode( + private createInvalidationNode( invalidation: TimelineModel.TimelineModel.InvalidationTrackingEvent, showUnknownNodes: boolean): HTMLSpanElement |Text { - const node = (invalidation.nodeId && this._relatedNodesMap) ? this._relatedNodesMap.get(invalidation.nodeId) : null; + const node = (invalidation.nodeId && this.relatedNodesMap) ? this.relatedNodesMap.get(invalidation.nodeId) : null; if (node) { const nodeSpan = document.createElement('span'); Common.Linkifier.Linkifier.linkify(node).then(link => nodeSpan.appendChild(link)); @@ -3573,7 +3572,7 @@ visible: boolean; childColor: string; color: string; - _hidden?: boolean; + private hiddenInternal?: boolean; constructor(name: string, title: string, visible: boolean, childColor: string, color: string) { super(); @@ -3586,11 +3585,11 @@ } get hidden(): boolean { - return Boolean(this._hidden); + return Boolean(this.hiddenInternal); } set hidden(hidden: boolean) { - this._hidden = hidden; + this.hiddenInternal = hidden; this.dispatchEventToListeners(TimelineCategory.Events.VisibilityChanged, this); } } @@ -3605,25 +3604,25 @@ export class TimelineDetailsContentHelper { fragment: DocumentFragment; - _linkifier: Components.Linkifier.Linkifier|null; - _target: SDK.Target.Target|null; + private linkifierInternal: Components.Linkifier.Linkifier|null; + private target: SDK.Target.Target|null; element: HTMLDivElement; - _tableElement: HTMLElement; + private tableElement: HTMLElement; constructor(target: SDK.Target.Target|null, linkifier: Components.Linkifier.Linkifier|null) { this.fragment = document.createDocumentFragment(); - this._linkifier = linkifier; - this._target = target; + this.linkifierInternal = linkifier; + this.target = target; this.element = document.createElement('div'); this.element.classList.add('timeline-details-view-block'); - this._tableElement = this.element.createChild('div', 'vbox timeline-details-chip-body'); + this.tableElement = this.element.createChild('div', 'vbox timeline-details-chip-body'); this.fragment.appendChild(this.element); } addSection(title: string, swatchColor?: string): void { - if (!this._tableElement.hasChildNodes()) { + if (!this.tableElement.hasChildNodes()) { this.element.removeChildren(); } else { this.element = document.createElement('div'); @@ -3639,22 +3638,22 @@ UI.UIUtils.createTextChild(titleElement, title); } - this._tableElement = this.element.createChild('div', 'vbox timeline-details-chip-body'); + this.tableElement = this.element.createChild('div', 'vbox timeline-details-chip-body'); this.fragment.appendChild(this.element); } linkifier(): Components.Linkifier.Linkifier|null { - return this._linkifier; + return this.linkifierInternal; } appendTextRow(title: string, value: string|number|boolean): void { - const rowElement = this._tableElement.createChild('div', 'timeline-details-view-row'); + const rowElement = this.tableElement.createChild('div', 'timeline-details-view-row'); rowElement.createChild('div', 'timeline-details-view-row-title').textContent = title; rowElement.createChild('div', 'timeline-details-view-row-value').textContent = value.toString(); } appendElementRow(title: string, content: string|Node, isWarning?: boolean, isStacked?: boolean): void { - const rowElement = this._tableElement.createChild('div', 'timeline-details-view-row'); + const rowElement = this.tableElement.createChild('div', 'timeline-details-view-row'); if (isWarning) { rowElement.classList.add('timeline-details-warning'); } @@ -3672,7 +3671,7 @@ } appendLocationRow(title: string, url: string, startLine: number, startColumn?: number): void { - if (!this._linkifier || !this._target) { + if (!this.linkifierInternal || !this.target) { return; } @@ -3687,7 +3686,7 @@ maxLength: undefined, bypassURLTrimming: undefined, }; - const link = this._linkifier.maybeLinkifyScriptLocation(this._target, null, url, startLine, options); + const link = this.linkifierInternal.maybeLinkifyScriptLocation(this.target, null, url, startLine, options); if (!link) { return; } @@ -3695,12 +3694,12 @@ } appendLocationRange(title: string, url: string, startLine: number, endLine?: number): void { - if (!this._linkifier || !this._target) { + if (!this.linkifierInternal || !this.target) { return; } const locationContent = document.createElement('span'); - const link = this._linkifier.maybeLinkifyScriptLocation( - this._target, null, url, startLine, + const link = this.linkifierInternal.maybeLinkifyScriptLocation( + this.target, null, url, startLine, {tabStop: true, className: undefined, inlineFrameIndex: 0, columnNumber: undefined}); if (!link) { return; @@ -3712,24 +3711,24 @@ } appendStackTrace(title: string, stackTrace: Protocol.Runtime.StackTrace): void { - if (!this._linkifier || !this._target) { + if (!this.linkifierInternal || !this.target) { return; } - const rowElement = this._tableElement.createChild('div', 'timeline-details-view-row'); + const rowElement = this.tableElement.createChild('div', 'timeline-details-view-row'); rowElement.createChild('div', 'timeline-details-view-row-title').textContent = title; this.createChildStackTraceElement(rowElement, stackTrace); } createChildStackTraceElement(parentElement: Element, stackTrace: Protocol.Runtime.StackTrace): void { - if (!this._linkifier || !this._target) { + if (!this.linkifierInternal || !this.target) { return; } parentElement.classList.add('timeline-details-stack-values'); const stackTraceElement = parentElement.createChild('div', 'timeline-details-view-row-value timeline-details-view-row-stack-trace'); const callFrameContents = Components.JSPresentationUtils.buildStackTracePreviewContents( - this._target, this._linkifier, {stackTrace, tabStops: true}); + this.target, this.linkifierInternal, {stackTrace, tabStops: true}); stackTraceElement.appendChild(callFrameContents.element); }
diff --git a/front_end/panels/timeline/UIDevtoolsController.ts b/front_end/panels/timeline/UIDevtoolsController.ts index c44334b..a0736f7 100644 --- a/front_end/panels/timeline/UIDevtoolsController.ts +++ b/front_end/panels/timeline/UIDevtoolsController.ts
@@ -28,8 +28,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import type * as SDK from '../../core/sdk/sdk.js'; import type {Client} from './TimelineController.js';
diff --git a/front_end/panels/timeline/UIDevtoolsUtils.ts b/front_end/panels/timeline/UIDevtoolsUtils.ts index 080d45e..7745807 100644 --- a/front_end/panels/timeline/UIDevtoolsUtils.ts +++ b/front_end/panels/timeline/UIDevtoolsUtils.ts
@@ -28,8 +28,6 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -/* eslint-disable rulesdir/no_underscored_properties */ - import * as i18n from '../../core/i18n/i18n.js'; import * as Root from '../../core/root/root.js';
diff --git a/front_end/panels/timeline/WebVitalsTimelineUtils.ts b/front_end/panels/timeline/WebVitalsTimelineUtils.ts index a80e76f..5e64638 100644 --- a/front_end/panels/timeline/WebVitalsTimelineUtils.ts +++ b/front_end/panels/timeline/WebVitalsTimelineUtils.ts
@@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/* eslint-disable rulesdir/no_underscored_properties */ - import * as PerfUI from '../../ui/legacy/components/perf_ui/perf_ui.js'; import * as UI from '../../ui/legacy/legacy.js';
diff --git a/test/webtests/http/tests/devtools/a11y-axe-core/performance/performance-pane-a11y-test.js b/test/webtests/http/tests/devtools/a11y-axe-core/performance/performance-pane-a11y-test.js index 5f87199..ad93799 100644 --- a/test/webtests/http/tests/devtools/a11y-axe-core/performance/performance-pane-a11y-test.js +++ b/test/webtests/http/tests/devtools/a11y-axe-core/performance/performance-pane-a11y-test.js
@@ -40,7 +40,7 @@ const model = PerformanceTestRunner.createPerformanceModelWithEvents(testData); - const detailsView = UI.panels.timeline._flameChart._detailsView; + const detailsView = UI.panels.timeline.flameChart.detailsView; async function testDetailsView() { TestRunner.addResult('Tests accessibility in performance Details view using the axe-core linter'); @@ -48,7 +48,7 @@ // Details pane gets data from the parent TimelineDetails view detailsView.setModel(model, PerformanceTestRunner.mainTrack()); - const tabbedPane = detailsView._tabbedPane; + const tabbedPane = detailsView.tabbedPane; tabbedPane.selectTab(Timeline.TimelineDetailsView.Tab.Details); const detailsTab = tabbedPane.visibleView; @@ -57,7 +57,7 @@ async function testViewWithName(tab) { TestRunner.addResult(`Tests accessibility in performance ${tab} view using the axe-core linter`); - const tabbedPane = detailsView._tabbedPane; + const tabbedPane = detailsView.tabbedPane; tabbedPane.selectTab(tab); const detailsTab = tabbedPane.visibleView;
diff --git a/test/webtests/http/tests/devtools/a11y-axe-core/performance/performance_event_log_a11y_test.js b/test/webtests/http/tests/devtools/a11y-axe-core/performance/performance_event_log_a11y_test.js index 4a31a50..b5a1c6a 100644 --- a/test/webtests/http/tests/devtools/a11y-axe-core/performance/performance_event_log_a11y_test.js +++ b/test/webtests/http/tests/devtools/a11y-axe-core/performance/performance_event_log_a11y_test.js
@@ -9,7 +9,7 @@ await TestRunner.showPanel('timeline'); TestRunner.addResult('Performance panel loaded.'); - const tabbedPane = UI.panels.timeline._flameChart._detailsView._tabbedPane; + const tabbedPane = UI.panels.timeline.flameChart.detailsView.tabbedPane; tabbedPane.selectTab(Timeline.TimelineDetailsView.Tab.EventLog); TestRunner.addResult('Loading a performance model.');