diff --git a/apps/review-desktop/code-oss/src/vs/review/services/reviewDiffViewService.ts b/apps/review-desktop/code-oss/src/vs/review/services/reviewDiffViewService.ts index c2fef34d5..af57f25bf 100644 --- a/apps/review-desktop/code-oss/src/vs/review/services/reviewDiffViewService.ts +++ b/apps/review-desktop/code-oss/src/vs/review/services/reviewDiffViewService.ts @@ -411,18 +411,20 @@ class DiffViewController extends Disposable implements ReviewDiffViewHandle { const rendered = new Set(); const renderCurrentState = (change?: StructuralSessionChange) => { if (this.disposed) return; - for (const entry of entries) { - const path = entry.file.path; - if (change && !change.files.has(path)) continue; - const result = entry.file.status === "unchanged" ? {} : session.getFileResult(path); - if (!result) continue; - if (!rendered.has(path) && result.hidden !== undefined) view.hideFile(path, result.hidden); - rendered.add(path); - if (result.diff) view.fileCounts(path, reviewFileCounts(result.diff)); - view.fileLoaded(path, result.error); - } - if (session.error) view.loadingFailed(session.error); - else if (session.complete) view.loadingFailed("diffr did not supply a result for this file."); + view.batch(() => { + for (const entry of entries) { + const path = entry.file.path; + if (change && !change.files.has(path)) continue; + const result = entry.file.status === "unchanged" ? {} : session.getFileResult(path); + if (!result) continue; + if (!rendered.has(path) && result.hidden !== undefined) view.hideFile(path, result.hidden); + rendered.add(path); + if (result.diff) view.fileCounts(path, reviewFileCounts(result.diff)); + view.fileLoaded(path, result.error); + } + if (session.error) view.loadingFailed(session.error); + else if (session.complete) view.loadingFailed("diffr did not supply a result for this file."); + }); }; store.add(session.onDidChange(renderCurrentState)); renderCurrentState(); diff --git a/apps/review-desktop/code-oss/src/vs/review/services/reviewFilesDiffView.ts b/apps/review-desktop/code-oss/src/vs/review/services/reviewFilesDiffView.ts index 969b8931f..2128b1659 100644 --- a/apps/review-desktop/code-oss/src/vs/review/services/reviewFilesDiffView.ts +++ b/apps/review-desktop/code-oss/src/vs/review/services/reviewFilesDiffView.ts @@ -12,12 +12,12 @@ import { disposableTimeout } from "../../base/common/async.js"; import { Emitter, Event } from "../../base/common/event.js"; import { Disposable, DisposableStore, MutableDisposable, toDisposable } from "../../base/common/lifecycle.js"; import { autorun, observableFromEvent, observableValue, type ISettableObservable } from "../../base/common/observable.js"; -import { isEqual } from "../../base/common/resources.js"; +import { getComparisonKey } from "../../base/common/resources.js"; import { URI } from "../../base/common/uri.js"; import { ElementSizeObserver } from "../../editor/browser/config/elementSizeObserver.js"; import { isDiffEditor, type IDiffEditor } from "../../editor/browser/editorBrowser.js"; import { DiffEditorViewModel } from "../../editor/browser/widget/diffEditor/diffEditorViewModel.js"; -import { MultiDiffEditorViewModel } from "../../editor/browser/widget/multiDiffEditor/multiDiffEditorViewModel.js"; +import { MultiDiffEditorViewModel, type DocumentDiffItemViewModel } from "../../editor/browser/widget/multiDiffEditor/multiDiffEditorViewModel.js"; import { MultiDiffEditorWidget, type RevealOptions } from "../../editor/browser/widget/multiDiffEditor/multiDiffEditorWidget.js"; import type { IMultiDiffEditorViewState } from "../../editor/browser/widget/multiDiffEditor/multiDiffEditorWidgetImpl.js"; import { IDiffEditorOptions } from "../../editor/common/config/editorOptions.js"; @@ -40,7 +40,7 @@ import { type ReviewDiffFileWire } from "../common/reviewProtocol.js"; import { binarySizeLabel, isBinaryCounts, type ReviewFileCounts } from "../common/reviewStructuralDiff.js"; import type { DiffFindFolds } from "./reviewDiffFind.js"; import type { ReviewDiffLayoutSetting } from "./reviewDiffLayout.js"; -import { reviewMultiDiffLabelUris, ReviewMultiDiffUIElementFactory } from "./reviewMultiDiff.js"; +import { reviewMultiDiffLabelUris, ReviewMultiDiffUIElementFactory, type ReviewMultiDiffHeaderEntry } from "./reviewMultiDiff.js"; import type { StructuralDiffSession } from "./reviewStructuralDiffSession.js"; const FILE_TREE_MINIMUM_WIDTH = 180; @@ -194,6 +194,11 @@ export class ReviewFilesDiffView extends Disposable { private pendingViewState: IMultiDiffEditorViewState | undefined; private viewModel: MultiDiffEditorViewModel | undefined; private input: ReviewFilesEditorInput | undefined; + /** The input's entries by resource; the first of a repeated resource wins, as a scan would find it. */ + private entriesByResource = new Map(); + private itemsByResource: { items: readonly DocumentDiffItemViewModel[]; map: Map } | undefined; + /** Whole-list work a batch of streamed files owes once it ends. */ + private batched: { ready?: boolean; headers?: boolean; summary?: boolean } | undefined; private readonly readyFiles = new Set(); private readonly loadingFiles = new Set(); private readonly failedFiles = new Map(); @@ -231,7 +236,7 @@ export class ReviewFilesDiffView extends Disposable { private readonly onToggleViewed: ((path: string, sectionId?: string) => void) | undefined, private readonly onToggleSection: ((id: string) => void) | undefined, private readonly document: ReviewDiffViewSpec["document"], - openFile: boolean, + private readonly openFile: boolean, private readonly onscreen: ISettableObservable | undefined, @IInstantiationService private readonly reviewInstantiationService: IInstantiationService, @@ -251,45 +256,13 @@ export class ReviewFilesDiffView extends Disposable { const factory = this.reviewInstantiationService.createInstance( ReviewMultiDiffUIElementFactory, - () => - this.input - ? this.input.entries.map((entry) => ({ - original: entry.original, - modified: entry.modified, - additions: entry.file.status === "unchanged" || this.isBinary(entry) ? undefined : this.entryProgress(entry)?.remaining.additions ?? (this.fileTreeContainer || this.document ? undefined : this.lineCounts(entry.file.path)?.added), - deletions: entry.file.status === "unchanged" || this.isBinary(entry) ? undefined : this.entryProgress(entry)?.remaining.deletions ?? (this.fileTreeContainer || this.document ? undefined : this.lineCounts(entry.file.path)?.removed), - collapseLocked: this.isBinary(entry) || this.failedFiles.has(entry.file.path), - countsTooltip: this.progressTooltip(entry) ?? this.streamStats.get(entry.file.path)?.tooltip, - viewedState: this.entryProgress(entry)?.state, - viewedScope: this.viewedScope, - onToggleViewed: entry.file.status !== "unchanged" && this.onToggleViewed ? () => this.onToggleViewed!(entry.file.path, entry.sectionId) : undefined, - sectionId: entry.sectionId, - sectionCollapsed: !!entry.sectionId && this.collapsedSections.has(entry.sectionId), - onToggleSectionCollapsed: () => { if (entry.sectionId) { if (this.collapsedSections.has(entry.sectionId)) this.collapsedSections.delete(entry.sectionId); else this.collapsedSections.add(entry.sectionId); this.headerFactory.refreshHeaders(); } }, - section: entry.sectionStart ? this.progress?.sections?.find(section => section.id === entry.sectionId) : undefined, - onToggleSection: () => entry.sectionId && this.onToggleSection?.(entry.sectionId), - // A binary is folded like a hidden file, with its size as the reason. - note: this.failedFiles.get(entry.file.path) ?? (entry.file.status === "unchanged" ? (this.document ? undefined : "Unchanged") : this.isBinary(entry) ? this.binaryNote(entry.file.path) : this.hiddenFiles.get(entry.file.path)), - noteTooltip: this.failedFiles.has(entry.file.path) ? { label: this.failedFiles.get(entry.file.path)! } : this.isBinary(entry) ? { label: "No text to show · binary files stay folded" } : undefined, - failed: this.failedFiles.has(entry.file.path), - commit: document?.commit, - // A binary has no text to open. - onDidOpen: this.isBinary(entry) || !(document ? document.onDidOpen : openFile) ? undefined : () => { - if (document?.onDidOpen) { document.onDidOpen(); return; } - const target = this.widget.tryGetCodeEditor(entry.goToFileResource); - const change = isDiffEditor(target?.diffEditor) ? target.diffEditor.getDiffComputationResult()?.changes2[0] : undefined; - const line = change && (entry.modified ? change.modified : change.original).startLineNumber; - const selection = line === undefined ? undefined : target?.editor.getModel()?.validateRange(new Range(line, 1, line, 1)); - void this.editorService.openEditor( - { - resource: entry.goToFileResource, - options: { pinned: true, revealIfVisible: true, selection }, - }, - this.editorGroupService.mainPart.activeGroup, - ); - }, - })) - : [], + { + entry: uris => { + const entry = this.entriesByResource.get(resourceKey(uris)); + return entry && this.headerEntry(entry); + }, + section: id => this.progress?.sections?.find(section => section.id === id), + }, "auto", // Hover and definition widgets must escape the canvas root, whose // container-query containment clips position: fixed descendants. @@ -392,11 +365,56 @@ export class ReviewFilesDiffView extends Disposable { this._register(toDisposable(() => this.root.remove())); } + private headerEntry(entry: ReviewFilesEditorEntry): ReviewMultiDiffHeaderEntry { + const document = this.document; + return { + original: entry.original, + modified: entry.modified, + additions: entry.file.status === "unchanged" || this.isBinary(entry) ? undefined : this.entryProgress(entry)?.remaining.additions ?? (this.fileTreeContainer || this.document ? undefined : this.lineCounts(entry.file.path)?.added), + deletions: entry.file.status === "unchanged" || this.isBinary(entry) ? undefined : this.entryProgress(entry)?.remaining.deletions ?? (this.fileTreeContainer || this.document ? undefined : this.lineCounts(entry.file.path)?.removed), + collapseLocked: this.isBinary(entry) || this.failedFiles.has(entry.file.path), + countsTooltip: this.progressTooltip(entry) ?? this.streamStats.get(entry.file.path)?.tooltip, + viewedState: this.entryProgress(entry)?.state, + viewedScope: this.viewedScope, + onToggleViewed: entry.file.status !== "unchanged" && this.onToggleViewed ? () => this.onToggleViewed!(entry.file.path, entry.sectionId) : undefined, + sectionId: entry.sectionId, + sectionCollapsed: !!entry.sectionId && this.collapsedSections.has(entry.sectionId), + onToggleSectionCollapsed: () => { if (entry.sectionId) { if (this.collapsedSections.has(entry.sectionId)) this.collapsedSections.delete(entry.sectionId); else this.collapsedSections.add(entry.sectionId); this.headerFactory.refreshHeaders(); } }, + section: entry.sectionStart ? this.progress?.sections?.find(section => section.id === entry.sectionId) : undefined, + onToggleSection: () => entry.sectionId && this.onToggleSection?.(entry.sectionId), + // A binary is folded like a hidden file, with its size as the reason. + note: this.failedFiles.get(entry.file.path) ?? (entry.file.status === "unchanged" ? (this.document ? undefined : "Unchanged") : this.isBinary(entry) ? this.binaryNote(entry.file.path) : this.hiddenFiles.get(entry.file.path)), + noteTooltip: this.failedFiles.has(entry.file.path) ? { label: this.failedFiles.get(entry.file.path)! } : this.isBinary(entry) ? { label: "No text to show · binary files stay folded" } : undefined, + failed: this.failedFiles.has(entry.file.path), + commit: document?.commit, + // A binary has no text to open. + onDidOpen: this.isBinary(entry) || !(document ? document.onDidOpen : this.openFile) ? undefined : () => { + if (document?.onDidOpen) { document.onDidOpen(); return; } + const target = this.widget.tryGetCodeEditor(entry.goToFileResource); + const change = isDiffEditor(target?.diffEditor) ? target.diffEditor.getDiffComputationResult()?.changes2[0] : undefined; + const line = change && (entry.modified ? change.modified : change.original).startLineNumber; + const selection = line === undefined ? undefined : target?.editor.getModel()?.validateRange(new Range(line, 1, line, 1)); + void this.editorService.openEditor( + { + resource: entry.goToFileResource, + options: { pinned: true, revealIfVisible: true, selection }, + }, + this.editorGroupService.mainPart.activeGroup, + ); + }, + }; + } + async setInput(input: ReviewFilesEditorInput, viewState: IMultiDiffEditorViewState | undefined): Promise { this.settleHold.clear(); this.documentLayout.clear(); this.pendingViewState = viewState; this.input = input; + this.entriesByResource = new Map(); + for (const entry of input.entries) { + const key = resourceKey(entry); + if (!this.entriesByResource.has(key)) this.entriesByResource.set(key, entry); + } this.changedFilesTree?.setFiles(Array.from(new Map(input.entries.map(entry => [entry.file.path, entry.file])).values())); const viewModel = await input.getViewModel(); if (this._store.isDisposed) return; @@ -407,7 +425,7 @@ export class ReviewFilesDiffView extends Disposable { this.documentLayout.value = autorun(reader => { const items = viewModel.items.read(reader); const onePane = items.length > 0 && items.every(item => { - const entry = input.entries.find(entry => sameResource(item.originalUri, entry.original) && sameResource(item.modifiedUri, entry.modified)); + const entry = this.entriesByResource.get(itemKey(item)); if (!entry || entry.file.binary) return false; if (entry.file.status === "added" || entry.file.status === "deleted" || entry.file.status === "unchanged") return true; const comparison = item.diffEditorViewModel; @@ -433,18 +451,11 @@ export class ReviewFilesDiffView extends Disposable { item.collapsed.set(this.documentCollapsed, undefined); } this.applyViewedFiles(); - const entry = this.input?.entries.find( - (e) => e.file.path === this.pendingPath, - ); - if (!entry || !this.readyFiles.has(entry.file.path)) return; - if ( - !items.some( - (item) => - sameResource(item.originalUri, entry.original) && - sameResource(item.modifiedUri, entry.modified), - ) - ) - return; + const pending = this.pendingPath; + if (pending === undefined || !this.readyFiles.has(pending)) return; + const entry = this.input?.entries.find((e) => e.file.path === pending); + if (!entry) return; + if (!this.itemFor(entry)) return; this.pendingPath = undefined; this.showStreamStatus(); queueMicrotask(() => { @@ -514,11 +525,31 @@ export class ReviewFilesDiffView extends Disposable { if (error) this.failedFiles.set(path, error); else this.failedFiles.delete(path); this.changedFilesTree?.setFileState(path, error ? "error" : undefined, error); - this.input?.setReadyFiles(this.readyFiles, this.loadingFiles.size > 0); + if (this.batched) this.batched.ready = true; + else this.input?.setReadyFiles(this.readyFiles, this.loadingFiles.size > 0); this.showStreamStatus(); } - refreshHeaders(): void { this.headerFactory.refreshHeaders(); } + /** + * Files stream in many at a time, and a finished comparison reports them all + * at once. Each one owes work over the whole list — the ready set, live + * headers, the summary — so a batch does that work once, not once per file. + */ + batch(update: () => void): void { + if (this.batched) { update(); return; } + const batched: NonNullable = this.batched = {}; + try { update(); } finally { + this.batched = undefined; + if (batched.ready) this.input?.setReadyFiles(this.readyFiles, this.loadingFiles.size > 0); + if (batched.headers) this.headerFactory.refreshHeaders(); + if (batched.summary) this.renderSummary(); + } + } + + refreshHeaders(): void { + if (this.batched) this.batched.headers = true; + else this.headerFactory.refreshHeaders(); + } /** Coverage counts are independent of fold state. */ fileCounts(path: string, counts: ReviewFileCounts): void { @@ -529,8 +560,9 @@ export class ReviewFilesDiffView extends Disposable { }); // Coverage owns line counts in a hosted tree; a binary's size has no other source. if (!this.fileTreeContainer || isBinaryCounts(counts)) this.changedFilesTree?.setCounts(path, counts); - this.headerFactory.refreshHeaders(); - this.renderSummary(); + this.refreshHeaders(); + if (this.batched) this.batched.summary = true; + else this.renderSummary(); } private lineCounts(path: string) { @@ -574,7 +606,7 @@ export class ReviewFilesDiffView extends Disposable { /** The root's default-collapse reason, displayed on its file header. */ hideFile(path: string, label: string): void { this.hiddenFiles.set(path, label); - this.headerFactory.refreshHeaders(); + this.refreshHeaders(); } private readonly collapsedSections = new Set(); @@ -670,7 +702,7 @@ export class ReviewFilesDiffView extends Disposable { } loadingFailed(message: string): void { - for (const path of this.loadingFiles) this.fileLoaded(path, message); + this.batch(() => { for (const path of this.loadingFiles) this.fileLoaded(path, message); }); this.showStreamStatus(); } @@ -762,18 +794,26 @@ export class ReviewFilesDiffView extends Disposable { } private itemFor(resource: { original: URI | undefined; modified: URI | undefined }) { - return this.viewModel?.items.get().find(item => sameResource(item.originalUri, resource.original) && sameResource(item.modifiedUri, resource.modified)); + const items = this.viewModel?.items.get(); + if (!items) return undefined; + // Every streamed file replaces the list; index each list once, not once per lookup. + if (this.itemsByResource?.items !== items) { + const map = new Map(); + for (const item of items) { + const key = itemKey(item); + if (!map.has(key)) map.set(key, item); + } + this.itemsByResource = { items, map }; + } + return this.itemsByResource.map.get(resourceKey(resource)); } private syncFileSelectionFromWidget(): void { const resource = this.widget.getActiveItem(); const input = this.input; if (!resource || !input || this.pendingPath) return; - const index = input.entries.findIndex( - (entry) => sameResource(entry.original, resource.original) && sameResource(entry.modified, resource.modified), - ); - if (index === -1) return; - this.changedFilesTree?.setActiveFile(input.entries[index].file.path); + const entry = this.entriesByResource.get(resourceKey(resource)); + if (entry) this.changedFilesTree?.setActiveFile(entry.file.path); } } export interface RevealSourceOptions { @@ -781,6 +821,20 @@ export interface RevealSourceOptions { select?: boolean; } -function sameResource(left: URI | undefined, right: URI | undefined): boolean { - return left === undefined ? right === undefined : !!right && isEqual(left, right); +const comparisonKeys = new WeakMap(); + +/** The key `isEqual` compares by, computed once per URI: deriving it encodes the URI anew. */ +function comparisonKey(uri: URI | undefined): string { + if (!uri) return ""; + let key = comparisonKeys.get(uri); + if (key === undefined) comparisonKeys.set(uri, key = getComparisonKey(uri)); + return key; +} + +function resourceKey(resource: { readonly original: URI | undefined; readonly modified: URI | undefined }): string { + return `${comparisonKey(resource.original)}\n${comparisonKey(resource.modified)}`; +} + +function itemKey(item: DocumentDiffItemViewModel): string { + return resourceKey({ original: item.originalUri, modified: item.modifiedUri }); } diff --git a/apps/review-desktop/code-oss/src/vs/review/services/reviewMultiDiff.ts b/apps/review-desktop/code-oss/src/vs/review/services/reviewMultiDiff.ts index b6097106a..333456fef 100644 --- a/apps/review-desktop/code-oss/src/vs/review/services/reviewMultiDiff.ts +++ b/apps/review-desktop/code-oss/src/vs/review/services/reviewMultiDiff.ts @@ -7,7 +7,6 @@ import type { ReviewDiffProgressState, ReviewDiffSection } from "../common/revie *--------------------------------------------------------------------------------------------*/ import { Button } from "../../base/browser/ui/button/button.js"; -import { isEqual } from "../../base/common/resources.js"; import { URI } from "../../base/common/uri.js"; import type { IResourceLabel, @@ -50,6 +49,12 @@ export interface ReviewMultiDiffHeaderEntry { readonly onToggleViewed?: () => void; } +/** Answers for one resource at a time: a header refresh must not walk every file. */ +export interface ReviewMultiDiffHeaderSource { + entry(uris: { readonly original: URI | undefined; readonly modified: URI | undefined }): ReviewMultiDiffHeaderEntry | undefined; + section(id: string): ReviewDiffSection | undefined; +} + export class ReviewMultiDiffUIElementFactory implements IWorkbenchUIElementFactory { @@ -70,7 +75,7 @@ export class ReviewMultiDiffUIElementFactory } constructor( - private readonly entries: () => readonly ReviewMultiDiffHeaderEntry[], + private readonly source: ReviewMultiDiffHeaderSource, readonly horizontalScrollbar: "auto" | "hidden", readonly overflowWidgetsDomNode: HTMLElement | undefined, readonly hideResourceHeader = false, @@ -81,7 +86,7 @@ export class ReviewMultiDiffUIElementFactory ) {} isResourceCollapseLocked(uris: Parameters[0]): boolean { - return !!uris && !!this.entries().find(entry => sameResource(entry.original, uris.original) && sameResource(entry.modified, uris.modified))?.collapseLocked; + return !!uris && !!this.source.entry(uris)?.collapseLocked; } getResourceSectionId(uris: Parameters[0]): string | undefined { @@ -98,10 +103,8 @@ export class ReviewMultiDiffUIElementFactory const countsTooltip = new ReviewTooltip(this.hoverService, counts); const viewed = new ReviewViewedCheckbox(this.hoverService, element.ownerDocument, () => current?.onToggleSection?.()); const refresh = () => { - const entry = current = uris && this.entries().find(entry => sameResource(entry.original, uris!.original) && sameResource(entry.modified, uris!.modified)); - const section = sticky && entry?.sectionId - ? this.entries().find(candidate => candidate.sectionId === entry.sectionId && candidate.section)?.section - : entry?.section; + const entry = current = uris && this.source.entry(uris); + const section = sticky && entry?.sectionId ? this.source.section(entry.sectionId) : entry?.section; bodyHidden.set(entry?.sectionCollapsed ?? false, undefined); element.replaceChildren(); element.className = 'review-diff-group'; element.hidden = !section; height.set(section ? 48 : 0, undefined); @@ -208,13 +211,7 @@ export class ReviewMultiDiffUIElementFactory const setUris: IResourceHeaderMetadata["setUris"] = (uris) => { lastUris = uris; - current = uris - ? this.entries().find( - (entry) => - sameResource(entry.original, uris.original) && - sameResource(entry.modified, uris.modified), - ) - : undefined; + current = uris ? this.source.entry(uris) : undefined; element.hidden = !current; if (!current) return; const hasCounts = @@ -272,12 +269,6 @@ export class ReviewMultiDiffUIElementFactory } } -function sameResource(left: URI | undefined, right: URI | undefined): boolean { - return left === undefined - ? right === undefined - : !!right && isEqual(left, right); -} - export function reviewMultiDiffLabelUris(file: ReviewDiffFileWire): { readonly original: URI | undefined; readonly modified: URI | undefined; diff --git a/apps/review-desktop/code-oss/src/vs/review/services/reviewStructuralDiff.ts b/apps/review-desktop/code-oss/src/vs/review/services/reviewStructuralDiff.ts index 1da9dd9ce..76fbcd766 100644 --- a/apps/review-desktop/code-oss/src/vs/review/services/reviewStructuralDiff.ts +++ b/apps/review-desktop/code-oss/src/vs/review/services/reviewStructuralDiff.ts @@ -53,7 +53,7 @@ export function createStructuralDiffEditors( const languages = instantiation.invokeFunction((a) => a.get(ILanguageService)); const viewId = ++structuralViewId; const sources = new Map(); - const snapshots = new Map(); + const snapshots = new Map(); const unchangedTexts = new Map>(); const snapshotUri = (uri: URI, path: string, side: "lhs" | "rhs", unchangedBase?: URI) => { const query = new URLSearchParams(uri.query); @@ -85,7 +85,7 @@ export function createStructuralDiffEditors( // diffr's binary check is stricter than git's. text = result.diff?.type === "text" ? result.diff[source.side]?.text ?? "" : ""; } - if (!source.unchangedBase) snapshots.set(uri.toString(), uri); + if (!source.unchangedBase) snapshots.set(uri.toString(), { uri, path: source.path, side: source.side }); return modelService.getModel(uri) ?? modelService.createModel(text, languages.createByFilepathOrFirstLine(uri, text.split("\n", 1)[0]), uri); }, })); @@ -104,11 +104,10 @@ export function createStructuralDiffEditors( const willEdit = lifetime.add(new Emitter()); lifetime.add(session.onDidChange(change => { // A refreshed diff edits its snapshots before any diff is recomputed against them. - const edits = [...snapshots.values()].flatMap(uri => { - const source = sources.get(uri.with({ fragment: "" }).toString())!; - const diff = change.files.has(source.path) ? session.getFileResult(source.path)?.diff : undefined; + const edits = [...snapshots.values()].flatMap(({ uri, path, side }) => { + const diff = change.files.has(path) ? session.getFileResult(path)?.diff : undefined; const model = diff && modelService.getModel(uri); - return model ? [{ model, text: diff.type === "text" ? diff[source.side]?.text ?? "" : "" }] : []; + return model ? [{ model, text: diff.type === "text" ? diff[side]?.text ?? "" : "" }] : []; }); if (edits.length) willEdit.fire(); for (const { model, text } of edits) replaceText(model, text); diff --git a/apps/review-desktop/code-oss/src/vs/review/services/reviewStructuralViewed.ts b/apps/review-desktop/code-oss/src/vs/review/services/reviewStructuralViewed.ts index 0bd0d0007..504e2593e 100644 --- a/apps/review-desktop/code-oss/src/vs/review/services/reviewStructuralViewed.ts +++ b/apps/review-desktop/code-oss/src/vs/review/services/reviewStructuralViewed.ts @@ -19,7 +19,7 @@ export class StructuralViewedState extends Disposable { readonly onDidChange = this.changed.event; private readonly scopes = new Map>(); private readonly states = new Map(); - private memo: { files: Map; values: Map> } | undefined; + private memo: { files: Map; values: Map>> } | undefined; constructor( private readonly session: StructuralDiffSession, @@ -28,11 +28,11 @@ export class StructuralViewedState extends Disposable { onProgress: Event, ) { super(); - const reset = () => { this.memo = undefined; this.sync(); }; - this._register(onProgress(reset)); + this._register(onProgress(() => { this.memo = undefined; this.sync(); })); + // A streamed batch changes only its own files; the rest keep their scopes and progress. this._register(session.onDidChange(change => { - for (const path of change.files) this.scopes.delete(path); - reset(); + for (const path of change.files) { this.scopes.delete(path); this.memo?.values.delete(path); } + this.sync(change.files); })); this.sync(); } @@ -49,9 +49,10 @@ export class StructuralViewedState extends Disposable { get(path: string, id: number) { const { files, values } = this.current(); - const key = `${path}:${id}`; - let value = values.get(key); - if (!value) values.set(key, value = structuralViewedProgress(this.getScopes(path)?.get(id) ?? [], files.get(path))); + let ofFile = values.get(path); + if (!ofFile) values.set(path, ofFile = new Map()); + let value = ofFile.get(id); + if (!value) ofFile.set(id, value = structuralViewedProgress(this.getScopes(path)?.get(id) ?? [], files.get(path))); return value; } @@ -63,11 +64,12 @@ export class StructuralViewedState extends Disposable { return this.memo ??= { files: new Map(this.progress()?.files.map(file => [file.path, file])), values: new Map() }; } - private sync(): void { + private sync(paths?: ReadonlySet): void { const initialized = initializedScopes.get(this.session) ?? new Set(); initializedScopes.set(this.session, initialized); for (const entry of this.entries) { const path = entry.file.path; + if (paths && !paths.has(path)) continue; if (!this.current().files.has(path)) continue; const scopes = this.getScopes(path); const viewed = [...scopes ?? []].filter(([id]) => this.get(path, id).state === 'viewed'); diff --git a/packages/review/app/src/DiffView.tsx b/packages/review/app/src/DiffView.tsx index f83a582de..1e3f576bc 100644 --- a/packages/review/app/src/DiffView.tsx +++ b/packages/review/app/src/DiffView.tsx @@ -128,51 +128,38 @@ export function ReviewDiffView({ const [lensTree, setLensTree] = useState(null); const [scopeTree, setScopeTree] = useState(null); - const fullProgress = useMemo( - () => - lenses?.progress - ? { - files: lenses.progress.files.map((file) => ({ - path: file.path, - ...coverageProgress([file]), - viewedRanges: coverageSources(file), - changedRanges: coverageSources(file, file.changed), - unfoldRanges: lenses.unfoldRanges.filter( - (source) => - source.file === - (source.side === "base" - ? (file.previousPath ?? file.path) - : file.path), - ), - })), - changedPaths: lenses.changedPaths, - } - : undefined, - [lenses?.progress, lenses?.changedPaths, lenses?.unfoldRanges], - ); - - const lensProgress = useMemo( - () => - lenses?.progress && lens - ? { - files: lenses.progress.files.map((file) => ({ - path: file.path, - ...coverageProgress([file], lens.ranges), - viewedRanges: coverageSources(file), - changedRanges: coverageSources(file, file.changed), - unfoldRanges: lenses.unfoldRanges.filter( - (source) => - source.file === - (source.side === "base" - ? (file.previousPath ?? file.path) - : file.path), - ), - })), - changedPaths: lenses.changedPaths, - } - : undefined, - [lenses?.progress, lenses?.changedPaths, lenses?.unfoldRanges, lens], - ); + const fullProgress = useMemo(() => { + if (!lenses?.progress) return undefined; + const unfold = rangesByFile(lenses.unfoldRanges); + + return { + files: lenses.progress.files.map((file) => ({ + path: file.path, + ...coverageProgress([file]), + viewedRanges: coverageSources(file), + changedRanges: coverageSources(file, file.changed), + unfoldRanges: unfold(file), + })), + changedPaths: lenses.changedPaths, + }; + }, [lenses?.progress, lenses?.changedPaths, lenses?.unfoldRanges]); + + const lensProgress = useMemo(() => { + if (!lenses?.progress || !lens) return undefined; + const unfold = rangesByFile(lenses.unfoldRanges); + const scope = rangesByFile(lens.ranges); + + return { + files: lenses.progress.files.map((file) => ({ + path: file.path, + ...coverageProgress([file], scope(file)), + viewedRanges: coverageSources(file), + changedRanges: coverageSources(file, file.changed), + unfoldRanges: unfold(file), + })), + changedPaths: lenses.changedPaths, + }; + }, [lenses?.progress, lenses?.changedPaths, lenses?.unfoldRanges, lens]); const markFile = (path: string, scoped: boolean) => { const file = lenses?.progress?.files.find((file) => file.path === path); @@ -180,13 +167,7 @@ export function ReviewDiffView({ if (!file || !lenses) return; const sources = scoped - ? lens?.ranges.filter( - (source) => - source.file === - (source.side === "base" - ? (file.previousPath ?? file.path) - : file.path), - ) + ? lens && rangesByFile(lens.ranges)(file) : coverageSources(file, file.changed); void lenses.mark(sources, lenses.stats(sources).state !== "viewed"); @@ -450,18 +431,48 @@ export function ReviewDiffView({ ); } +type FileRange = ReviewDiffLens["ranges"][number]; + +/** + * Each file's own ranges, grouped once. A large diff has thousands of files + * and ranges; filtering every range for every file is quadratic. + */ +function rangesByFile(ranges: readonly FileRange[]) { + const byFile = Map.groupBy(ranges, (source) => source.file); + + return (file: { path: string; previousPath?: string }): FileRange[] => { + const base = file.previousPath ?? file.path; + + const named = + base === file.path + ? (byFile.get(base) ?? []) + : [...(byFile.get(base) ?? []), ...(byFile.get(file.path) ?? [])]; + + return named.filter( + (source) => source.file === (source.side === "base" ? base : file.path), + ); + }; +} + /** How many changed files a lens covers. */ function lensFileCount(lenses: ReviewLenses, lens: ReviewDiffLens): number { + // The first file with a name owns it, as a scan of the files would find it. + const owners = { + base: new Map(), + head: new Map(), + }; + + for (const file of lenses.progress?.files ?? []) { + const base = file.previousPath ?? file.path; + + if (!owners.base.has(base)) owners.base.set(base, file.path); + + if (!owners.head.has(file.path)) owners.head.set(file.path, file.path); + } + return new Set( lens.ranges.map( - (source) => - lenses.progress?.files.find( - (file) => - source.file === - (source.side === "base" - ? (file.previousPath ?? file.path) - : file.path), - )?.path ?? source.file, + (source) => owners[source.side].get(source.file) ?? source.file, ), ).size; } diff --git a/packages/review/app/src/review-lenses.tsx b/packages/review/app/src/review-lenses.tsx index 36f0b3941..791a82470 100644 --- a/packages/review/app/src/review-lenses.tsx +++ b/packages/review/app/src/review-lenses.tsx @@ -350,7 +350,10 @@ export function ReviewLensesProvider({ ? source.comparison : undefined; - groups.set(key, [...(groups.get(key) ?? []), source]); + const group = groups.get(key); + + if (group) group.push(source); + else groups.set(key, [source]); } return mergeCoverageProgress(