diff --git a/perf/scenarios.ts b/perf/scenarios.ts index d2dec1043..e25bf2846 100644 --- a/perf/scenarios.ts +++ b/perf/scenarios.ts @@ -758,6 +758,123 @@ const projectTree: Scenario = { }, }; +/** Files in the `combinedDiff` scenarios (`OPENIDEA_PERF_COMBINED_FILES`). */ +const COMBINED_FILES = Number(process.env.OPENIDEA_PERF_COMBINED_FILES ?? 500); +/** Farthest the wheel pass scrolls before turning back: about 100 files of 40 lines. */ +const COMBINED_WHEEL_PX = 100_000; + +/** + * Opens an all-in-one diff of `COMBINED_FILES` files from a key press, then scrolls down and back + * up, for at most 60 s each way. `wheel`: 120 px per 16 ms of wall time (a fast wheel; the + * compositor keeps scrolling through a slow frame), down to the end or `COMBINED_WHEEL_PX`. + * `stress`: a viewport (or 1/300 of the whole height, if more) a frame, down to the end. + * `blankFrames`: frames whose viewport centre shows neither a diff nor a file header. + * `slowFrameMs` / `slowTimePct`: time in frames over 33 ms, and its share of the scroll time: + * shares of frame counts mislead when one side renders far fewer, longer frames. + */ +async function combinedDiffScroll(h: Harness, mode: "wheel" | "stress") { + // Opened from a key press, the measured input (no default shortcut opens it). + await h.page.evaluate((n) => { + const w = window as never as { + __openideaPerf: { openCombinedDiff(n: number): Promise<{ first: string; last: string }> }; + __combinedPaths?: Promise<{ first: string; last: string }>; + }; + addEventListener("keydown", () => (w.__combinedPaths = w.__openideaPerf.openCombinedDiff(n)), { + capture: true, + once: true, + }); + }, COMBINED_FILES); + const openMs = await h.measure( + () => h.page.keyboard.press("Pause"), + "[data-combined-scroll] .cm-content", + null, + 30_000, + ); + const paths = await h.page.evaluate( + () => (window as never as { __combinedPaths: Promise<{ first: string; last: string }> }).__combinedPaths, + ); + await h.page.waitForTimeout(500); + const refresh = await h.refreshMs(); + const t0 = await h.now(); + await h.inPage((p) => p.startFrames()); + const pass = await h.page.locator("[data-combined-scroll]").evaluate( + async (el, { first, last, wheel, maxPx }) => { + const editors = () => el.querySelectorAll(".cm-editor").length; + const box = el.getBoundingClientRect(); + const blank = () => { + const hit = document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2); + return !hit?.closest(".cm-editor, [data-combined-block] > :first-child"); + }; + const shown = (path: string) => !!el.querySelector(`[data-combined-block="${CSS.escape(path)}"]`); + const step = () => Math.max(el.clientHeight, Math.ceil((el.scrollHeight - el.clientHeight) / 300)); + let peakEditors = editors(); + let blankFrames = 0; + let frames = 0; + let reachedEnd = false; + const walk = async (down: boolean) => { + const started = performance.now(); + const from = el.scrollTop; + // The end only once the view has stayed there for 30 frames: blocks loading near the bottom + // still grow the view, so a first touch of the bottom isn't the end of the whole change. + let settled = 0; + while (performance.now() - started < 60_000) { + const atEnd = el.scrollTop + el.clientHeight >= el.scrollHeight - 1 && shown(last); + settled = down && atEnd ? settled + 1 : 0; + if (settled >= 30) reachedEnd = true; + if (down ? reachedEnd || (wheel && el.scrollTop - from >= maxPx) : el.scrollTop <= 0 && shown(first)) + return true; + const moved = wheel ? ((performance.now() - started) * 120) / 16 : 0; + if (wheel) el.scrollTop = down ? Math.min(from + moved, from + maxPx) : Math.max(0, from - moved); + else el.scrollTop = down ? el.scrollTop + step() : Math.max(0, el.scrollTop - step()); + await new Promise(requestAnimationFrame); + frames++; + if (blank()) blankFrames++; + peakEditors = Math.max(peakEditors, editors()); + } + return false; + }; + await walk(true); + const scrolledPx = el.scrollTop; + const backAtTop = await walk(false); + return { reachedEnd, backAtTop, scrolledPx, peakEditors, blankFrames, frames }; + }, + { ...paths, wheel: mode === "wheel", maxPx: COMBINED_WHEEL_PX }, + ); + const frames = await h.inPage((p) => p.stopFrames()); + const tbtMs = totalBlockingTime(await h.longTasksSince(t0)); + const slow = frames.filter((f) => f > 33); + const slowFrameMs = slow.reduce((sum, f) => sum + f, 0); + const totalMs = frames.reduce((sum, f) => sum + f, 0); + return { + openMs, + ...frameSummary(frames, refresh), + slowFramesPct: frames.length ? (100 * slow.length) / frames.length : 0, + slowFrameMs, + slowTimePct: totalMs ? (100 * slowFrameMs) / totalMs : 0, + tbtMs, + peakEditors: pass.peakEditors, + blankFrames: pass.blankFrames, + scrollFrames: pass.frames, + blankPct: pass.frames ? (100 * pass.blankFrames) / pass.frames : 0, + scrolledPx: pass.scrolledPx, + reachedEnd: pass.reachedEnd ? 1 : 0, + backAtTop: pass.backAtTop ? 1 : 0, + domNodes: (await h.counters()).Nodes ?? NaN, + }; +} + +const combinedDiff: Scenario = { + id: "combinedDiff", + title: `Wheel through an all-in-one diff of ${COMBINED_FILES} files`, + run: (h) => combinedDiffScroll(h, "wheel"), +}; + +const combinedDiffStress: Scenario = { + id: "combinedDiffStress", + title: `Scroll an all-in-one diff of ${COMBINED_FILES} files a screen a frame`, + run: (h) => combinedDiffScroll(h, "stress"), +}; + /** Opening and closing editors repeatedly must not grow the heap or the DOM. */ const leaks: Scenario = { id: "leaks", @@ -806,5 +923,7 @@ export const SCENARIOS: Scenario[] = [ popups, toolWindows, projectTree, + combinedDiff, + combinedDiffStress, leaks, ]; diff --git a/src/editor/core/cm/selectionLayer.ts b/src/editor/core/cm/selectionLayer.ts index 50e35dd45..043dd6d53 100644 --- a/src/editor/core/cm/selectionLayer.ts +++ b/src/editor/core/cm/selectionLayer.ts @@ -364,18 +364,18 @@ const snappedSelectionLayer = layer({ update: (u) => u.docChanged || u.selectionSet || u.viewportChanged, }); +// Shared by every editor: a theme made per editor adds its rules to the page each time, restyling all of it. +const seamlessTheme = EditorView.theme({ + ".cm-selectionLayer:not(.cm-openidea-selectionLayer)": { + display: "none", + }, + // drawSelection hides the native selection inside the lines only. WebKit also fills the gaps left of + // selected lines (the text inset) with the content's own ::selection colour, which showed as small + // blocks next to the gutter. + ".cm-content::selection": { backgroundColor: "transparent" }, +}); + /** Use with `drawSelection()`: replaces its selection layer, which is hidden. */ export function seamlessSelection(): Extension { - return [ - snappedSelectionLayer, - EditorView.theme({ - ".cm-selectionLayer:not(.cm-openidea-selectionLayer)": { - display: "none", - }, - // drawSelection hides the native selection inside the lines only. WebKit also fills the gaps left of - // selected lines (the text inset) with the content's own ::selection colour, which showed as small - // blocks next to the gutter. - ".cm-content::selection": { backgroundColor: "transparent" }, - }), - ]; + return [snappedSelectionLayer, seamlessTheme]; } diff --git a/src/editor/core/cm/setup.ts b/src/editor/core/cm/setup.ts index 4a7ff65d6..3747f017a 100644 --- a/src/editor/core/cm/setup.ts +++ b/src/editor/core/cm/setup.ts @@ -179,6 +179,15 @@ export const formatIndentFacet = Facet.define({ combine: (values) => [values.find((v) => v !== null) ?? null], }); +// One theme per set of values: a theme made per call mounts new rules for every editor, and the page restyles. +const fontThemes = new Map(); +function fontVarsTheme(vars: Record): Extension { + const key = JSON.stringify(vars); + let theme = fontThemes.get(key); + if (!theme) fontThemes.set(key, (theme = EditorView.theme({ "&": vars }))); + return theme; +} + export function fontExtension(settings: EditorSettings | undefined): Extension { const vars: Record = {}; const prefs = prefsOf(settings); @@ -203,7 +212,7 @@ export function fontExtension(settings: EditorSettings | undefined): Extension { Object.keys(attrs).length ? EditorView.editorAttributes.of(attrs) : [], // The same variables as a theme: tooltips (completion, parameter info, hover docs) render // in a container outside the editor that carries its theme classes, not its attributes. - entries.length ? EditorView.theme({ "&": vars }) : [], + entries.length ? fontVarsTheme(vars) : [], ]; } diff --git a/src/features/vcs/CombinedDiff.module.css b/src/features/vcs/CombinedDiff.module.css index e4fd98032..e0252130d 100644 --- a/src/features/vcs/CombinedDiff.module.css +++ b/src/features/vcs/CombinedDiff.module.css @@ -39,14 +39,22 @@ overflow-y: auto; padding: var(--space-2) var(--space-3); } +/* Only the blocks near the viewport are rendered, each at its offset in the full height. */ +.blocks { + position: relative; +} +.slot { + position: absolute; + left: 0; + width: 100%; + /* The gap between blocks, inside the measured slot. */ + padding-bottom: 10px; +} .block { border: 1px solid var(--border); border-radius: var(--radius-popup-large); background: var(--bg-editor); } -.block + .block { - margin-top: 10px; -} /* The file's header stays at the top while its diff scrolls by. */ .header { position: sticky; @@ -100,7 +108,6 @@ .body[hidden] { display: none; } -/* Space a block takes before its diff loads, so the scrollbar is roughly right. */ .placeholder { height: 160px; } @@ -120,6 +127,6 @@ :global(:root[data-compact]) .header { padding-block: 7px; } -:global(:root[data-compact]) .block + .block { - margin-top: var(--space-1); +:global(:root[data-compact]) .slot { + padding-bottom: var(--space-1); } diff --git a/src/features/vcs/CombinedDiff.tsx b/src/features/vcs/CombinedDiff.tsx index 80981b515..97b614df0 100644 --- a/src/features/vcs/CombinedDiff.tsx +++ b/src/features/vcs/CombinedDiff.tsx @@ -1,20 +1,22 @@ /** * The all-in-one diff tab (`combined-diff`): one block per file of a change, each a diff - * as tall as its content under a sticky header, in one scrolling view. Blocks load as they - * come near the viewport; a header collapses its block or opens the file's own diff tab. + * as tall as its content under a sticky header, in one scrolling view. Only the blocks near + * the viewport are mounted; a header collapses its block or opens the file's own diff tab. */ -import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { defaultRangeExtractor, elementScroll, useVirtualizer, type Range } from "@tanstack/react-virtual"; import clsx from "clsx"; import { tx } from "@/platform/i18n"; import { relativeDir, useProject } from "@/platform/project"; import { Icon, IconButton, T, fileIconName } from "@/ui"; import { editorService, type EditorInput } from "@/workbench/contributions"; import { combinedDiffDocumentOwner, setAllInOneDiff, type CombinedDiffData } from "./allInOneDiff"; -import { ResolvedDiffEditor } from "./DiffEditor"; +import { ResolvedDiffEditor, type DiffViewState } from "./DiffEditor"; import { diffInput, hasGitlink, openDiff, withChain, type DiffData } from "./diffInput"; import { loadDiffOptions, saveDiffOptions } from "./diffOptions"; -import { useGitDiffEntries } from "./gitDiffEntries"; +import { useGitDiffEntries, type DiffEntriesCache } from "./gitDiffEntries"; import { KIND_COLOR, KIND_LABEL, baseName, fileCount } from "./model"; +import { ownedStagedDocument } from "./stagedDocument"; import styles from "./CombinedDiff.module.css"; type Kind = "added" | "deleted" | "modified"; @@ -25,8 +27,8 @@ export function blockKind(item: DiffData): Kind { return absent(item.left) ? "added" : absent(item.right) ? "deleted" : "modified"; } -/** How far below the viewport a block starts loading (above it, only once scrolled to). */ -const PRELOAD = "0px 0px 800px 0px"; +/** Height of a block not measured yet: its header and a short diff. */ +const ESTIMATE = 200; function Block({ item, @@ -36,6 +38,9 @@ function Block({ onToggle, mode, tabKey, + heights, + viewStates, + entriesCache, }: { item: DiffData; index: number; @@ -44,25 +49,46 @@ function Block({ onToggle: () => void; mode: "split" | "unified"; tabKey: string; + /** Height of each block's loaded diff, by layout and diff, kept while blocks are unmounted. */ + heights: Map; + /** Each block's selection and expanded unchanged lines, by layout and diff, kept the same way. */ + viewStates: Map; + /** Git entries of the blocks, so a block back in view shows without asking Git again. */ + entriesCache: DiffEntriesCache; }) { - const ref = useRef(null); - // Without IntersectionObserver (tests), every block loads at once. - const [near, setNear] = useState(() => typeof IntersectionObserver === "undefined"); - useEffect(() => { - const el = ref.current; - if (!el || near) return; - const io = new IntersectionObserver( - (entries) => { - if (entries.some((e) => e.isIntersecting)) setNear(true); - }, - { root: el.closest("[data-combined-scroll]"), rootMargin: PRELOAD }, - ); - io.observe(el); - return () => io.disconnect(); - }, [near]); + // A block mounted collapsed creates its diff once expanded. + const [loaded, setLoaded] = useState(!collapsed); + if (!collapsed && !loaded) setLoaded(true); const request = useMemo(() => ({ ...item, mode }), [item, mode]); const input = useMemo(() => diffInput(request), [request]); - const diff = useGitDiffEntries(request, near); + const diff = useGitDiffEntries(request, entriesCache); + + // Back in view, the diff loads again: until it is as tall as before (or for a second), the block + // keeps its last height, so the blocks around it don't move while the view scrolls. + const bodyRef = useRef(null); + const heightKey = `${mode}\0${input.key}`; + const [hold, setHold] = useState(() => heights.get(heightKey) ?? 0); + const viewState = useMemo(() => { + if (!viewStates.has(heightKey)) viewStates.set(heightKey, {}); + return viewStates.get(heightKey)!; + }, [viewStates, heightKey]); + useEffect(() => { + const content = bodyRef.current?.firstElementChild; + if (!(content instanceof HTMLElement)) return; + const timer = hold ? setTimeout(() => setHold(0), 1000) : undefined; + const observer = new ResizeObserver(() => { + const height = content.offsetHeight; + // Collapsed (hidden), or still loading. + if (!height || height < hold) return; + if (hold) setHold(0); + else heights.set(heightKey, height); + }); + observer.observe(content); + return () => { + observer.disconnect(); + clearTimeout(timer); + }; + }, [loaded, hold, heightKey, heights]); const gitlink = hasGitlink(diff.data); const kind = blockKind(item); const name = baseName(item.path); @@ -70,7 +96,6 @@ function Block({ const dir = relativeDir(root, item.path); return (
void editorService().openInput(diffInput(withChain(items, index)), { focus: true })} /> - {near && !diff.loading && !gitlink && item.right.type === "worktree" && ( + {!diff.loading && !gitlink && item.right.type === "worktree" && ( {dir}} - {/* A collapsed block keeps its loaded diff, hidden: unmounting it would release the - working-tree document and, with autosave off, drop its unsaved edits. */} - {near ? ( -
); @@ -133,31 +159,61 @@ export function CombinedDiffTab({ input }: { input: EditorInput }) { const [collapsed, setCollapsed] = useState>(() => new Set()); const [mode, setMode] = useState(() => loadDiffOptions().mode); const scrollRef = useRef(null); + const [heights] = useState(() => new Map()); + const [viewStates] = useState(() => new Map()); + const [entriesCache] = useState(() => new Map()); + // A partially staged file is listed twice (staged and unstaged), so blocks go by diff, not path. + const keys = useMemo(() => items.map((item) => diffInput(item).key), [items]); - const blocks = () => [...(scrollRef.current?.querySelectorAll("[data-combined-block]") ?? [])]; - /** The block at the top of the view. */ - const current = () => { - const top = scrollRef.current?.getBoundingClientRect().top ?? 0; - const all = blocks(); - const at = all.findIndex((b) => b.getBoundingClientRect().bottom > top + 1); - return at < 0 ? all.length - 1 : at; - }; - const scrollTo = (path: string) => { - const el = blocks().find((b) => b.dataset.combinedBlock === path); - const scroller = scrollRef.current; - if (el && scroller) { - const inset = Number.parseFloat(getComputedStyle(scroller).paddingTop) || 0; - scroller.scrollTop += el.getBoundingClientRect().top - scroller.getBoundingClientRect().top - inset; - } - }; + // Blocks that stay mounted when scrolled away: the one holding the keyboard focus, so typing still + // reaches it, and with autosave off those with unsaved staged edits, which unmounting would save. + const rangeExtractor = useCallback( + (range: Range) => { + const shown = new Set(defaultRangeExtractor(range)); + const active = document.activeElement; + const slot = scrollRef.current?.contains(active) ? active?.closest("[data-index]") : null; + if (slot) shown.add(Number(slot.dataset.index)); + if (useProject.getState().settings?.files?.autoSave === false) + keys.forEach((key, index) => { + if (ownedStagedDocument(combinedDiffDocumentOwner(input.key, key))?.dirty) shown.add(index); + }); + return [...shown].sort((a, b) => a - b); + }, + [keys, input.key], + ); + const virtualizer = useVirtualizer({ + count: items.length, + getScrollElement: () => scrollRef.current, + getItemKey: (index) => keys[index]!, + estimateSize: () => ESTIMATE, + overscan: 4, + rangeExtractor, + // A correction for a block above moves the view by its delta from wherever it is now: a `scrollTo` + // (the library's offset plus the delta) can drop wheel scrolling still in flight in WebKit. + scrollToFn: (offset, options, instance) => { + if (options.adjustments) + instance.scrollElement?.scrollBy({ top: options.adjustments, behavior: options.behavior }); + else elementScroll(offset, options, instance); + }, + }); + // A block's real height is only known once its diff loads, up to thousands of lines past the + // estimate. The view moves with every block above it that grows, scrolling up too (the library + // skips that), or a reveal, Previous File and scrolling up land blocks early. + virtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item, _delta, instance) => + item.end <= (instance.scrollOffset ?? 0); + + /** Index of the block at the top of the view. */ + const current = () => + virtualizer.getVirtualItemForOffset(scrollRef.current?.scrollTop ?? 0)?.index ?? items.length - 1; const step = (dir: 1 | -1) => { - const next = items[current() + dir]; - if (next) scrollTo(next.path); + const next = current() + dir; + if (next >= 0 && next < items.length) virtualizer.scrollToIndex(next, { align: "start" }); }; // Open at the file the diff was asked for. useLayoutEffect(() => { - if (data.reveal) scrollTo(data.reveal); + const at = data.reveal ? items.findIndex((i) => i.path === data.reveal) : -1; + if (at >= 0) virtualizer.scrollToIndex(at, { align: "start" }); // Once per tab: later revisits keep their scroll position. // eslint-disable-next-line react-hooks/exhaustive-deps }, []); @@ -166,14 +222,14 @@ export function CombinedDiffTab({ input }: { input: EditorInput }) { setMode(next); saveDiffOptions({ ...loadDiffOptions(), mode: next }); }; - const toggle = (path: string) => + const toggle = (key: string) => setCollapsed((c) => { const s = new Set(c); - if (s.has(path)) s.delete(path); - else s.add(path); + if (s.has(key)) s.delete(key); + else s.add(key); return s; }); - const allCollapsed = items.length > 0 && items.every((i) => collapsed.has(i.path)); + const allCollapsed = items.length > 0 && keys.every((key) => collapsed.has(key)); return (
@@ -184,7 +240,7 @@ export function CombinedDiffTab({ input }: { input: EditorInput }) { icon={allCollapsed ? "expand-all" : "collapse-all"} title={allCollapsed ? "Expand All Files" : "Collapse All Files"} size="small" - onClick={() => setCollapsed(allCollapsed ? new Set() : new Set(items.map((i) => i.path)))} + onClick={() => setCollapsed(allCollapsed ? new Set() : new Set(keys))} />
{items.length ? ( - items.map((item, index) => ( - toggle(item.path)} - mode={mode} - tabKey={input.key} - /> - )) +
+ {virtualizer.getVirtualItems().map(({ index, key, start }) => ( +
+ toggle(keys[index]!)} + mode={mode} + tabKey={input.key} + heights={heights} + viewStates={viewStates} + entriesCache={entriesCache} + /> +
+ ))} +
) : (
No changes diff --git a/src/features/vcs/DiffEditor.tsx b/src/features/vcs/DiffEditor.tsx index 934b36c1d..7c7a80cba 100644 --- a/src/features/vcs/DiffEditor.tsx +++ b/src/features/vcs/DiffEditor.tsx @@ -16,7 +16,7 @@ import { } from "react"; import clsx from "clsx"; import { EditorView, keymap } from "@codemirror/view"; -import { Compartment, Prec, Text, type ChangeSet, type Extension } from "@codemirror/state"; +import { Compartment, Prec, Text, type ChangeSet, type EditorSelection, type Extension } from "@codemirror/state"; import { history, historyKeymap } from "@codemirror/commands"; import { MergeView, @@ -233,6 +233,26 @@ function revealPos(v: EditorView, pos: number) { }); } +function keepViewState(state: DiffViewState, side: Side): Extension { + return EditorView.updateListener.of((u) => { + const uncollapsed = u.transactions.flatMap((tr) => + tr.effects.filter((e) => e.is(uncollapseUnchanged)).map((e) => e.value as number), + ); + // A pane nobody touched keeps nothing, so its doc isn't held for the tab's lifetime. + if (!u.docChanged && !u.selectionSet && !uncollapsed.length) return; + const saved = state[side]; + const expanded = saved?.doc === u.startState.doc ? saved.expanded.map((pos) => u.changes.mapPos(pos)) : []; + state[side] = { doc: u.state.doc, selection: u.state.selection, expanded: [...expanded, ...uncollapsed] }; + }); +} + +/** Puts back a pane's selection and expanded lines, if its doc hasn't changed since. */ +function restoreViewState(state: DiffViewState, side: Side, view: EditorView) { + const saved = state[side]; + if (!saved || !saved.doc.eq(view.state.doc)) return; + view.dispatch({ selection: saved.selection, effects: saved.expanded.map((pos) => uncollapseUnchanged.of(pos)) }); +} + /** The panes as diff viewer contributions see them. */ function viewerHost(views: Views, data: DiffData, mode: DiffMode, focused: () => "a" | "b"): DiffViewerHost { const chunks = () => getChunks(views.b.state)?.chunks ?? []; @@ -342,6 +362,16 @@ function typedSidesOf(data: DiffData): { left?: Text; right?: Text } { return typed; } +/** A pane's selection and the unchanged lines expanded in it, for its doc. */ +interface PaneViewState { + doc: Text; + selection: EditorSelection; + expanded: number[]; +} + +/** What a diff's panes keep across rebuilds and remounts, filled in by the diff editor. */ +export type DiffViewState = Partial>; + export interface DiffEditorProps { input: EditorInput; documentOwner?: string; @@ -363,6 +393,8 @@ export interface DiffEditorProps { * toolbar, side-by-side panes always aligned, and not taking the editor tab's focus. */ fit?: boolean; + /** Kept by a host that unmounts the diff (an all-in-one diff block scrolled away) to restore it. */ + viewState?: DiffViewState; } export function DiffEditor(props: DiffEditorProps) { @@ -395,6 +427,7 @@ function TwoPaneDiff({ onJumpToSource, onClose, fit = false, + viewState, gitModes, metadataLoading, }: DiffEditorProps & { gitModes?: [string | null, string | null]; metadataLoading: boolean }) { @@ -728,6 +761,7 @@ function TwoPaneDiff({ notes: "left" | "right", key: Side, ): Extension[] => [ + viewState ? keepViewState(viewState, key) : [], stage && key === indexSide ? stage.extension() : [], stage && key === indexSide ? EditorView.contentAttributes.of({ "aria-label": tx(sideLabel(key === "a" ? left : right)) }) @@ -1004,6 +1038,10 @@ function TwoPaneDiff({ destroyPanes(); }; } + if (viewState && !carry) { + if (views.a) restoreViewState(viewState, "a", views.a); + restoreViewState(viewState, views.a ? "b" : mainSide(views), views.b); + } viewsRef.current = views; const built = viewerHost(views, dataRef.current, viewMode, () => focusedSide.current); const detach = contribs.map((c) => c.attach?.(built)); @@ -1057,6 +1095,7 @@ function TwoPaneDiff({ right, swapped, reload, + viewState, ]); useEffect(() => { diff --git a/src/features/vcs/__tests__/combinedDiff.test.tsx b/src/features/vcs/__tests__/combinedDiff.test.tsx index 4cc7c60d2..de57b02e2 100644 --- a/src/features/vcs/__tests__/combinedDiff.test.tsx +++ b/src/features/vcs/__tests__/combinedDiff.test.tsx @@ -1,5 +1,5 @@ import { act, fireEvent, render, screen } from "@testing-library/react"; -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; vi.mock("../DiffEditor", () => ({ ResolvedDiffEditor: ({ input, fit }: { input: { data: { path: string; mode?: string } }; fit?: boolean }) => ( @@ -136,3 +136,199 @@ describe("the all-in-one diff tab", () => { expect(closeInput).toHaveBeenCalledWith(input.key); }); }); + +describe("the all-in-one diff tab with many files", () => { + // jsdom has no layout: every element is 600 px tall (test setup), the scroller too, so one + // block fills the view. Scrolling is a `scrollTop` the virtualizer reads on `scroll`. + const offsets = new WeakMap(); + beforeEach(() => { + Object.defineProperty(HTMLElement.prototype, "scrollTop", { + configurable: true, + get() { + return offsets.get(this) ?? 0; + }, + set(value: number) { + offsets.set(this, value); + }, + }); + // As tall as its content: the virtualizer clamps where it scrolls to the scroll height. + Object.defineProperty(HTMLElement.prototype, "scrollHeight", { + configurable: true, + get() { + return ( + Number.parseFloat((this as HTMLElement).querySelector("[style*=height]")?.style.height ?? "") || + 0 + ); + }, + }); + HTMLElement.prototype.scrollTo = function (this: HTMLElement, options?: ScrollToOptions | number) { + this.scrollTop = typeof options === "number" ? options : (options?.top ?? 0); + this.dispatchEvent(new Event("scroll")); + }; + HTMLElement.prototype.scrollBy = function (this: HTMLElement, options?: ScrollToOptions | number) { + this.scrollTop += typeof options === "number" ? options : (options?.top ?? 0); + this.dispatchEvent(new Event("scroll")); + }; + }); + afterEach(() => { + delete (HTMLElement.prototype as { scrollTop?: number }).scrollTop; + delete (HTMLElement.prototype as { scrollHeight?: number }).scrollHeight; + }); + + const many = (n: number) => Array.from({ length: n }, (_, i) => diff(`/r/src/File${i}.ts`)); + const scrollBy = (dy: number) => { + const el = document.querySelector("[data-combined-scroll]")!; + act(() => { + el.scrollTop += dy; + el.dispatchEvent(new Event("scroll")); + }); + }; + const mounted = () => screen.queryAllByTestId("block-diff").map((b) => b.dataset.path!); + + it("mounts only the blocks near the view while scrolling, and reaches every file", () => { + const files = many(60); + render(); + const seen = new Set(mounted()); + let peak = seen.size; + for (let i = 0; i < files.length; i++) { + scrollBy(600); + mounted().forEach((p) => seen.add(p)); + peak = Math.max(peak, mounted().length); + } + // A screenful and four blocks on each side, however many files there are. + expect(peak).toBeLessThanOrEqual(12); + expect(seen).toEqual(new Set(files.map((f) => f.path))); + expect(mounted()).toContain("/r/src/File59.ts"); + expect(mounted()).not.toContain("/r/src/File0.ts"); + }); + + /** The block at the top of the view: its slot starts where the view does. */ + const atTop = () => { + const el = document.querySelector("[data-combined-scroll]")!; + const slot = [...el.querySelectorAll("[data-index]")].find( + (s) => Number.parseFloat(s.style.top) === el.scrollTop, + ); + return slot?.querySelector("[data-combined-block]")?.dataset.combinedBlock; + }; + + it("opens at the file asked for, before any block below the first was measured", async () => { + const files = many(60); + render(); + await act(() => new Promise((r) => setTimeout(r, 50))); + expect(atTop()).toBe("/r/src/File40.ts"); + }); + + it("steps to the next and previous file", async () => { + render(); + const click = async (name: string) => { + fireEvent.click(screen.getByRole("button", { name })); + await act(() => new Promise((r) => setTimeout(r, 50))); + }; + await click("Next File"); + expect(atTop()).toBe("/r/src/File1.ts"); + await click("Next File"); + await click("Next File"); + expect(atTop()).toBe("/r/src/File3.ts"); + await click("Previous File"); + expect(atTop()).toBe("/r/src/File2.ts"); + }); + + describe("as blocks above the view grow once their diffs load", () => { + // Slots report their size through the virtualizer's ResizeObserver, the way a loaded diff does. + const observers = new Map>(); + const original = window.ResizeObserver; + beforeEach(() => { + window.ResizeObserver = class { + targets = new Set(); + constructor(callback: ResizeObserverCallback) { + observers.set(callback, this.targets); + } + observe(target: Element) { + this.targets.add(target); + } + unobserve(target: Element) { + this.targets.delete(target); + } + disconnect() { + this.targets.clear(); + } + } as never; + }); + afterEach(() => { + window.ResizeObserver = original; + observers.clear(); + Object.defineProperty(HTMLElement.prototype, "offsetHeight", { configurable: true, get: () => 600 }); + }); + const grow = (index: number, height: number) => { + const slot = document.querySelector(`[data-index="${index}"]`)!; + const [callback] = [...observers].find(([, targets]) => targets.has(slot))!; + act(() => + callback([{ target: slot, borderBoxSize: [{ blockSize: height, inlineSize: 400 }] }] as never, {} as never), + ); + }; + /** How far below the top of the view a file's block starts. */ + const below = (path: string) => { + const el = document.querySelector("[data-combined-scroll]")!; + const block = el.querySelector(`[data-combined-block="${path}"]`)!; + return Number.parseFloat(block.closest("[data-index]")!.style.top) - el.scrollTop; + }; + + it("stays on the file it opened at", async () => { + // Still loading, the blocks are shorter than the estimate. + Object.defineProperty(HTMLElement.prototype, "offsetHeight", { configurable: true, get: () => 40 }); + render(); + await act(() => new Promise((r) => setTimeout(r, 50))); + expect(atTop()).toBe("/r/src/File40.ts"); + grow(38, 3000); + grow(39, 5000); + expect(atTop()).toBe("/r/src/File40.ts"); + }); + + it("keeps what is shown in place while scrolling up", async () => { + render(); + await act(() => new Promise((r) => setTimeout(r, 50))); + scrollBy(-300); + expect(below("/r/src/File40.ts")).toBe(300); + grow(38, 130_000); + expect(below("/r/src/File40.ts")).toBe(300); + }); + + it("keeps the wheel scrolling the view has not reported yet", async () => { + render(); + await act(() => new Promise((r) => setTimeout(r, 50))); + const el = document.querySelector("[data-combined-scroll]")!; + // The wheel moved the view, its scroll event not dispatched yet. + const scrolled = el.scrollTop - 200; + el.scrollTop = scrolled; + grow(38, 1000); + expect(el.scrollTop).toBe(scrolled + 400); + }); + }); + + it("keeps the focused block mounted when it is scrolled away", () => { + render(); + act(() => screen.getAllByRole("button", { name: "Collapse File" })[0]!.focus()); + for (let i = 0; i < 5; i++) scrollBy(600); + // Its neighbours went, it stayed, still holding the focus. + expect(mounted()).not.toContain("/r/src/File1.ts"); + expect(mounted()).toContain("/r/src/File0.ts"); + expect(document.querySelector('[data-combined-block="/r/src/File0.ts"]')).toBe( + document.activeElement!.closest("[data-combined-block]"), + ); + }); + + it("shows both entries of a partially staged file, each collapsing on its own", () => { + const path = "/r/src/Partial.ts"; + const staged = diff(path, { right: { type: "rev", rev: ":0" } }); + const unstaged = diff(path, { left: { type: "rev", rev: ":0" } }); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + render(); + expect(screen.getAllByTestId("block-diff")).toHaveLength(2); + act(() => { + fireEvent.click(screen.getAllByRole("button", { name: "Collapse File" })[0]!); + }); + expect(screen.getAllByRole("button", { name: "Expand File" })).toHaveLength(1); + expect(error.mock.calls.flat().join(" ")).not.toMatch(/same key/); + error.mockRestore(); + }); +}); diff --git a/src/features/vcs/__tests__/combinedDiffUnsaved.test.tsx b/src/features/vcs/__tests__/combinedDiffUnsaved.test.tsx new file mode 100644 index 000000000..7a068e087 --- /dev/null +++ b/src/features/vcs/__tests__/combinedDiffUnsaved.test.tsx @@ -0,0 +1,152 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, render, waitFor } from "@testing-library/react"; +import { EditorView } from "@codemirror/view"; + +const savedStaged: unknown[][] = []; +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + const ok = (data: unknown) => Promise.resolve({ status: "ok", data }); + return { + ...real, + commands: { + ...real.commands, + vcsDiffEntries: (entries: unknown[]) => ok(entries.map(() => ({ mode: "100644", gitlink: null }))), + vcsFileAt: () => ok("one\ntwo\n"), + vcsFileMode: () => ok("100644"), + fsProbe: () => ok({ size: 8, binary: false, tooLarge: false }), + vcsStagedText: () => ok({ text: "one\ntwo\n", version: "v1" }), + vcsSaveStagedText: (...args: unknown[]) => { + savedStaged.push(args); + return ok("v2"); + }, + }, + }; +}); + +// Only the edited file gets a real diff: the others just need to be scrolled past. +vi.mock("../DiffEditor", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + ResolvedDiffEditor: (props: Parameters[0]) => + props.input.path === "/r/File0.txt" ? :
, + }; +}); + +import { _emitEditorEvent, _provideDocumentAttacher } from "@/editor/api"; +import { createMemoryBackend } from "@/editor/core/backend"; +import { attachDocument } from "@/editor/core/model/attachment"; +import { DocumentManager, useDocMeta } from "@/editor/core/model/document"; +import { useProject } from "@/platform/project"; +import { CombinedDiffTab } from "../CombinedDiff"; +import { combinedDiffInput, type DiffData } from "../diffInput"; + +const paths = Array.from({ length: 20 }, (_, i) => `/r/File${i}.txt`); +const items: DiffData[] = paths.map((path) => ({ + path, + left: { type: "rev", rev: "HEAD" }, + right: { type: "worktree" }, +})); + +let manager: DocumentManager; +let backend: ReturnType; +const offsets = new WeakMap(); + +beforeEach(() => { + backend = createMemoryBackend(Object.fromEntries(paths.map((p) => [p, "one\ntwo\n"]))); + manager = new DocumentManager(backend, { settings: () => ({ files: { autoSave: false } }), notify: vi.fn() }); + manager.start(); + _provideDocumentAttacher((p, options) => attachDocument(manager, p, options)); + useProject.setState({ project: { name: "r", root: "/r", trusted: true, isGit: true, settings: {} } as never }); + // jsdom has no layout: every element is 600 px tall (test setup); scrolling is a `scrollTop`. + Object.defineProperty(HTMLElement.prototype, "scrollTop", { + configurable: true, + get() { + return offsets.get(this) ?? 0; + }, + set(value: number) { + offsets.set(this, value); + }, + }); +}); +afterEach(() => { + delete (HTMLElement.prototype as { scrollTop?: number }).scrollTop; + for (const model of manager.byPath.values()) { + model.setMeta({ dirty: false }); + _emitEditorEvent({ type: "docSaved", path: model.path, doc: model.doc }); + } + manager.stop(); + _provideDocumentAttacher(null); + useDocMeta.setState({}, true); +}); + +const block = (path: string) => document.querySelector(`[data-combined-block="${path}"]`); +async function editablePane(path: string): Promise { + return editableSide(path, "b"); +} +async function editableSide(path: string, side: "a" | "b"): Promise { + let view: EditorView | null = null; + await waitFor(() => { + const content = block(path)?.querySelector(`.cm-merge-${side} .cm-content`); + expect(content?.textContent).toContain("two"); + view = EditorView.findFromDOM(content!); + expect(view?.state.readOnly).toBe(false); + }); + return view!; +} +const scrollTo = (top: number) => { + const el = document.querySelector("[data-combined-scroll]")!; + for (let at = el.scrollTop; at !== top;) { + at += Math.sign(top - at) * Math.min(600, Math.abs(top - at)); + act(() => { + el.scrollTop = at; + el.dispatchEvent(new Event("scroll")); + }); + } +}; + +describe("the all-in-one diff, autosave off", () => { + it("keeps a block's unsaved edits when it is scrolled away and back", async () => { + render(); + const view = await editablePane(paths[0]!); + act(() => view.dispatch({ changes: { from: 0, insert: "EDIT " }, userEvent: "input" })); + await act(() => new Promise((r) => setTimeout(r, 20))); + const model = manager.byPath.get(paths[0]!)!; + expect(model.getMeta().dirty).toBe(true); + + scrollTo(15 * 600); + expect(block(paths[0]!)).toBeNull(); + await act(() => new Promise((r) => setTimeout(r, 20))); + expect(backend.files.get(paths[0]!)).toBe("one\ntwo\n"); + + scrollTo(0); + const again = await editablePane(paths[0]!); + expect(again.state.doc.toString()).toBe("EDIT one\ntwo\n"); + expect(manager.byPath.get(paths[0]!)?.getMeta().dirty).toBe(true); + }); +}); + +describe("the all-in-one diff, staged edits", () => { + const staged: DiffData[] = items.map((item) => ({ ...item, right: { type: "rev", rev: ":0" } })); + const editAndScrollAway = async (autoSave: boolean) => { + savedStaged.length = 0; + useProject.setState({ settings: { files: { autoSave } } as never }); + render(); + const view = await editableSide(paths[0]!, "b"); + act(() => view.dispatch({ changes: { from: 0, insert: "EDIT " }, userEvent: "input" })); + scrollTo(15 * 600); + await act(() => new Promise((r) => setTimeout(r, 20))); + }; + + it("with autosave off, keeps them out of the index while scrolled away", async () => { + await editAndScrollAway(false); + expect(savedStaged).toEqual([]); + expect(block(paths[0]!)).not.toBeNull(); + }); + + it("with autosave on, saves them to the index once scrolled away", async () => { + await editAndScrollAway(true); + expect(block(paths[0]!)).toBeNull(); + expect(savedStaged.map((args) => args[2])).toEqual(["EDIT one\ntwo\n"]); + }); +}); diff --git a/src/features/vcs/__tests__/diffStyleRules.test.tsx b/src/features/vcs/__tests__/diffStyleRules.test.tsx new file mode 100644 index 000000000..7908f0889 --- /dev/null +++ b/src/features/vcs/__tests__/diffStyleRules.test.tsx @@ -0,0 +1,49 @@ +import { afterEach, expect, it } from "vitest"; +import { cleanup, render, waitFor } from "@testing-library/react"; +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { fontExtension } from "@/editor/core/cm/setup"; +import type { EditorSettings } from "@/platform/ipc"; +import type { EditorInput } from "@/workbench/contributions"; +import { DiffEditor } from "../DiffEditor"; + +afterEach(cleanup); + +const input = (key: string) => + ({ + kind: "diff", + key, + data: { + path: "", + left: { type: "text", text: "one\ntwo\n", label: "" }, + right: { type: "text", text: "one\nthree\n", label: "" }, + }, + }) as unknown as EditorInput; + +const rules = () => + [...document.styleSheets].reduce((n, sheet) => n + sheet.cssRules.length, 0) + + (document.adoptedStyleSheets ?? []).reduce((n, sheet) => n + sheet.cssRules.length, 0); + +// A theme created per editor adds its rules to the page again, and the browser then restyles every +// element: in the all-in-one diff that was about 90 ms per file block mounted while scrolling. +it.each([false, true])("adds no style rules to the page for another diff (fit: %s)", async (fit) => { + render(); + await waitFor(() => expect(document.querySelectorAll(".cm-editor")).toHaveLength(2)); + const before = rules(); + render(); + render(); + await waitFor(() => expect(document.querySelectorAll(".cm-editor")).toHaveLength(6)); + expect(rules()).toBe(before); +}); + +// Every diff pane carries the editor font settings (`viewerEditorLook`), which the app always has. +it("adds no style rules for another editor with the same font settings", () => { + const settings = { fontSize: 15, lineHeight: 22 } as EditorSettings; + const mount = () => + new EditorView({ state: EditorState.create({ extensions: fontExtension(settings) }), parent: document.body }); + const views = [mount()]; + const before = rules(); + views.push(mount(), mount()); + expect(rules()).toBe(before); + views.forEach((v) => v.destroy()); +}); diff --git a/src/features/vcs/__tests__/diffViewState.test.tsx b/src/features/vcs/__tests__/diffViewState.test.tsx new file mode 100644 index 000000000..8d1133af9 --- /dev/null +++ b/src/features/vcs/__tests__/diffViewState.test.tsx @@ -0,0 +1,58 @@ +import { afterEach, expect, it } from "vitest"; +import { act, cleanup, render, waitFor } from "@testing-library/react"; +import { EditorView } from "@codemirror/view"; +import type { EditorInput } from "@/workbench/contributions"; +import { DiffEditor, type DiffViewState } from "../DiffEditor"; + +afterEach(cleanup); + +const lines = Array.from({ length: 40 }, (_, i) => `line ${i}`); +const inputFor = (mode: "split" | "unified") => + ({ + kind: "diff", + key: `diff:view-state:${mode}`, + data: { + path: "", + mode, + left: { type: "text", text: [...lines, "old end"].join("\n"), label: "" }, + right: { type: "text", text: [...lines, "new end"].join("\n"), label: "" }, + }, + }) as unknown as EditorInput; +const input = inputFor("split"); + +const pane = (index: number) => + EditorView.findFromDOM(document.querySelectorAll(".cm-mergeViewEditor .cm-editor")[index]!)!; +const collapsed = () => document.querySelectorAll(".cm-collapsedLines").length; + +// An all-in-one diff block scrolled away unmounts; back in view it shows the diff as it was left. +it("keeps a remounted diff's selection and expanded unchanged lines", async () => { + const viewState: DiffViewState = {}; + const first = render(); + await waitFor(() => expect(collapsed()).toBe(2)); + act(() => (document.querySelector(".cm-collapsedLines") as HTMLElement).click()); + expect(collapsed()).toBe(0); + act(() => pane(1).dispatch({ selection: { anchor: 3, head: 10 } })); + first.unmount(); + + render(); + await waitFor(() => expect(document.querySelectorAll(".cm-mergeViewEditor .cm-editor")).toHaveLength(2)); + expect(collapsed()).toBe(0); + expect(pane(1).state.selection.main).toMatchObject({ anchor: 3, head: 10 }); +}); + +it("keeps them in the unified viewer too", async () => { + const viewState: DiffViewState = {}; + const unified = inputFor("unified"); + const view = () => EditorView.findFromDOM(document.querySelector(".cm-editor")!)!; + const first = render(); + await waitFor(() => expect(collapsed()).toBe(1)); + act(() => (document.querySelector(".cm-collapsedLines") as HTMLElement).click()); + expect(collapsed()).toBe(0); + act(() => view().dispatch({ selection: { anchor: 3, head: 10 } })); + first.unmount(); + + render(); + await waitFor(() => expect(document.querySelectorAll(".cm-editor")).toHaveLength(1)); + expect(collapsed()).toBe(0); + expect(view().state.selection.main).toMatchObject({ anchor: 3, head: 10 }); +}); diff --git a/src/features/vcs/__tests__/gitDiffEntries.test.tsx b/src/features/vcs/__tests__/gitDiffEntries.test.tsx new file mode 100644 index 000000000..51e6d57bb --- /dev/null +++ b/src/features/vcs/__tests__/gitDiffEntries.test.tsx @@ -0,0 +1,118 @@ +import { act, renderHook, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const { vcsDiffEntries } = vi.hoisted(() => ({ + vcsDiffEntries: vi.fn((entries: unknown[]) => + Promise.resolve({ status: "ok", data: entries.map(() => ({ mode: "160000", gitlink: "abc123" })) }), + ), +})); +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { ...real, commands: { ...real.commands, vcsDiffEntries } }; +}); + +import type { DiffData } from "../diffInput"; +import { useGitDiffEntries, type DiffEntriesCache } from "../gitDiffEntries"; +import { useVcs } from "../store"; + +let n = 0; +const diff = (): DiffData => ({ + path: `/r/sub${++n}`, + left: { type: "rev", rev: "HEAD" }, + right: { type: "worktree" }, +}); + +beforeEach(() => { + vcsDiffEntries.mockClear(); +}); + +describe("useGitDiffEntries", () => { + it("with a host's cache, shows a diff mounted again at once, without asking Git again", async () => { + const data = diff(); + const cache: DiffEntriesCache = new Map(); + const first = renderHook(() => useGitDiffEntries(data, cache)); + expect(first.result.current.loading).toBe(true); + await waitFor(() => expect(first.result.current.loading).toBe(false)); + first.unmount(); + + const again = renderHook(() => useGitDiffEntries(data, cache)); + // Loaded on the first render: a submodule shows as one from the start. + expect(again.result.current.loading).toBe(false); + expect(again.result.current.data.right).toMatchObject({ type: "text", text: "abc123" }); + await act(async () => {}); + expect(vcsDiffEntries).toHaveBeenCalledTimes(1); + }); + + it("keeps showing a block mounted from the cache while the repository change reloads it", async () => { + const data = diff(); + const cache: DiffEntriesCache = new Map(); + const first = renderHook(() => useGitDiffEntries(data, cache)); + await waitFor(() => expect(first.result.current.loading).toBe(false)); + first.unmount(); + + const states: boolean[] = []; + const again = renderHook(() => { + const result = useGitDiffEntries(data, cache); + states.push(result.loading); + return result; + }); + vcsDiffEntries.mockImplementationOnce((entries: unknown[]) => + Promise.resolve({ status: "ok", data: entries.map(() => ({ mode: "160000", gitlink: "def456" })) }), + ); + // A save, an autosave or a file change on disk: the diff must not go back to loading (and rebuild). + act(() => useVcs.setState((s) => ({ version: s.version + 1 }))); + expect(again.result.current.data.right).toMatchObject({ type: "text", text: "abc123" }); + await waitFor(() => expect(again.result.current.data.right).toMatchObject({ type: "text", text: "def456" })); + expect(states).not.toContain(true); + expect(vcsDiffEntries).toHaveBeenCalledTimes(2); + }); + + it("asks Git again once the repository changed", async () => { + const data = diff(); + const cache: DiffEntriesCache = new Map(); + const first = renderHook(() => useGitDiffEntries(data, cache)); + await waitFor(() => expect(first.result.current.loading).toBe(false)); + act(() => useVcs.setState((s) => ({ version: s.version + 1 }))); + await waitFor(() => expect(vcsDiffEntries).toHaveBeenCalledTimes(2)); + first.unmount(); + + useVcs.setState((s) => ({ version: s.version + 1 })); + // Mounted after a change: the last entries show at once, and Git is asked again. + const again = renderHook(() => useGitDiffEntries(data, cache)); + expect(again.result.current.loading).toBe(false); + await waitFor(() => expect(vcsDiffEntries).toHaveBeenCalledTimes(3)); + }); + + it("does not replace newer cached entries when an older request finishes late", async () => { + const data = diff(); + const cache: DiffEntriesCache = new Map(); + let finishOldRequest!: () => void; + vcsDiffEntries.mockImplementationOnce( + (entries) => + new Promise((resolve) => { + finishOldRequest = () => + resolve({ status: "ok", data: entries.map(() => ({ mode: "160000", gitlink: "stale" })) }); + }), + ); + const view = renderHook(() => useGitDiffEntries(data, cache)); + act(() => useVcs.setState((s) => ({ version: s.version + 1 }))); + await waitFor(() => expect(view.result.current.data.right).toMatchObject({ type: "text", text: "abc123" })); + await act(async () => finishOldRequest()); + view.unmount(); + + const reopened = renderHook(() => useGitDiffEntries(data, cache)); + expect(reopened.result.current.data.right).toMatchObject({ type: "text", text: "abc123" }); + expect(vcsDiffEntries).toHaveBeenCalledTimes(2); + }); + + it("without a cache (a diff tab), asks Git on every mount", async () => { + const data = diff(); + for (let i = 1; i <= 2; i++) { + const view = renderHook(() => useGitDiffEntries(data)); + expect(view.result.current.loading).toBe(true); + await waitFor(() => expect(view.result.current.loading).toBe(false)); + view.unmount(); + expect(vcsDiffEntries).toHaveBeenCalledTimes(i); + } + }); +}); diff --git a/src/features/vcs/gitDiffEntries.ts b/src/features/vcs/gitDiffEntries.ts index 4bb7400a3..2cd64998b 100644 --- a/src/features/vcs/gitDiffEntries.ts +++ b/src/features/vcs/gitDiffEntries.ts @@ -49,7 +49,10 @@ export async function gitlinkDiffSides(data: DiffData): Promise<[DiffSide, DiffS return entries ? [resolveSide(sides[0], entries[0]), resolveSide(sides[1], entries[1])] : [data.left, data.right]; } -export function useGitDiffEntries(data: DiffData, enabled = true) { +/** Loaded entries by query, for a host that mounts the same diffs again (the all-in-one diff's blocks). */ +export type DiffEntriesCache = Map; + +export function useGitDiffEntries(data: DiffData, cache?: DiffEntriesCache) { const version = useVcs((s) => s.version); const status = data.middle && statusOf(data.path); const versions = useMemo(() => (status ? stagingVersions(status) : undefined), [status]); @@ -58,20 +61,24 @@ export function useGitDiffEntries(data: DiffData, enabled = true) { const middle = current.middle && diffSideSource(current.middle); const right = diffSideSource(current.right); const requests = [request(data.path, left), request(data.path, middle), request(data.path, right)]; - const query = enabled && requests.some(Boolean) ? JSON.stringify(requests) : ""; + const query = requests.some(Boolean) ? JSON.stringify(requests) : ""; + const hit = query ? cache?.get(query) : undefined; + const cached = hit?.version === version ? hit.entries : undefined; const [loaded, setLoaded] = useState<{ query: string; entries: (DiffEntry | null)[] | null }>(); useEffect(() => { - if (!query) return; + if (!query || cache?.get(query)?.version === version) return; let alive = true; const requests = JSON.parse(query) as (DiffEntryRequest | null)[]; void entriesFor(requests).then((entries) => { + if (entries && cache && useVcs.getState().version === version) cache.set(query, { version, entries }); if (alive) setLoaded({ query, entries }); }); return () => { alive = false; }; - }, [query, version]); - const entries = loaded?.query === query ? loaded.entries : null; + }, [query, version, cache]); + // While a repository change reloads them, the entries of the last version stay shown. + const entries = cached ?? (loaded?.query === query ? loaded.entries : (hit?.entries ?? null)); const resolved = useMemo(() => { if (!entries?.some((entry) => entry?.mode === GITLINK_MODE)) return data; return { @@ -81,5 +88,5 @@ export function useGitDiffEntries(data: DiffData, enabled = true) { right: resolveSide(right, entries[2]), }; }, [data, entries, left, middle, right]); - return { data: resolved, entries, loading: !!query && loaded?.query !== query }; + return { data: resolved, entries, loading: !!query && !hit && loaded?.query !== query }; } diff --git a/src/features/vcs/movedCode.ts b/src/features/vcs/movedCode.ts index 2e1488ce8..75768d15a 100644 --- a/src/features/vcs/movedCode.ts +++ b/src/features/vcs/movedCode.ts @@ -94,24 +94,27 @@ function decorations(view: EditorView, words: boolean): DecorationSet { return Decoration.set(ranges, true); } +// One module for every diff: each new theme adds its rules to the page again, restyling it all. +const movedCodeTheme = EditorView.baseTheme({ + ".cm-diffMoved": { boxShadow: "inset 3px 0 0 color-mix(in srgb, var(--accent) 70%, transparent)" }, + ".cm-diffMoveEdit-deleted": { backgroundColor: "color-mix(in srgb, var(--diff-deleted) 85%, transparent)" }, + ".cm-diffMoveEdit-inserted": { backgroundColor: "color-mix(in srgb, var(--diff-inserted) 85%, transparent)" }, + ".cm-diffMoveLink": { + marginLeft: "12px", + padding: "0 4px", + fontFamily: "var(--font-ui)", + fontSize: "var(--fs-small)", + color: "var(--link)", + background: "var(--bg-app)", + border: "1px solid var(--border)", + borderRadius: "var(--radius-small)", + cursor: "pointer", + }, + ".cm-diffMoveLink:hover": { background: "var(--bg-hover)" }, + ".cm-diffMoveLink:focus-visible": { outline: "2px solid var(--accent)", outlineOffset: "2px" }, +}); + export const movedCodeHighlights = (words: boolean) => [ chunkDecorations((view) => decorations(view, words)), - EditorView.baseTheme({ - ".cm-diffMoved": { boxShadow: "inset 3px 0 0 color-mix(in srgb, var(--accent) 70%, transparent)" }, - ".cm-diffMoveEdit-deleted": { backgroundColor: "color-mix(in srgb, var(--diff-deleted) 85%, transparent)" }, - ".cm-diffMoveEdit-inserted": { backgroundColor: "color-mix(in srgb, var(--diff-inserted) 85%, transparent)" }, - ".cm-diffMoveLink": { - marginLeft: "12px", - padding: "0 4px", - fontFamily: "var(--font-ui)", - fontSize: "var(--fs-small)", - color: "var(--link)", - background: "var(--bg-app)", - border: "1px solid var(--border)", - borderRadius: "var(--radius-small)", - cursor: "pointer", - }, - ".cm-diffMoveLink:hover": { background: "var(--bg-hover)" }, - ".cm-diffMoveLink:focus-visible": { outline: "2px solid var(--accent)", outlineOffset: "2px" }, - }), + movedCodeTheme, ]; diff --git a/src/workbench/perfProbe.ts b/src/workbench/perfProbe.ts index 0637be0a0..3d4eebbb3 100644 --- a/src/workbench/perfProbe.ts +++ b/src/workbench/perfProbe.ts @@ -69,6 +69,11 @@ export interface PerfProbe { * `latencyMs` (a `git log` call). `0` commits removes it. */ fakeGitLog(commits: number, latencyMs?: number): void; + /** + * Opens an all-in-one diff of `files` generated files changed between two revisions, answering + * the Git reads its blocks make: 40 lines each, every 50th file 1,000 lines. + */ + openCombinedDiff(files: number): Promise<{ first: string; last: string }>; } const KINDS: CompletionKind[] = [ @@ -139,6 +144,15 @@ function commit(i: number, count: number): Commit { }; } +/** `lines` lines of a generated source file; the two revisions differ on every 7th line. */ +function revisionText(file: number, lines: number, rev: string): string { + return Array.from({ length: lines }, (_, i) => + i % 7 === 3 + ? `export const v${file}_${i} = compute("${rev}", ${i});` + : `export const v${file}_${i} = compute(${i});`, + ).join("\n"); +} + type Route = (cmd: string, args: unknown) => Promise | null; const routes = new Map(); @@ -253,6 +267,39 @@ export function installPerfProbe(): () => void { : null, ); }, + async openCombinedDiff(files) { + const paths = Array.from( + { length: files }, + (_, i) => `/dev/acme-api/src/gen/pkg${Math.floor(i / 50)}/File${i}.ts`, + ); + const index = new Map(paths.map((path, i) => [path, i])); + setRoute("combinedDiff", (cmd, args) => { + if (cmd === "vcs_diff_entries") + return Promise.resolve( + (args as { entries: { path: string }[] }).entries.map(() => ({ mode: "100644", gitlink: null })), + ); + const { path, rev } = (args ?? {}) as { path?: string; rev?: string }; + const i = path === undefined ? undefined : index.get(path); + if (i === undefined) return null; + if (cmd === "vcs_file_mode") return Promise.resolve("100644"); + if (cmd === "fs_probe") return Promise.resolve({ size: 1024, binary: false, tooLarge: false }); + if (cmd === "vcs_file_at") return Promise.resolve(revisionText(i, i % 50 === 49 ? 1_000 : 40, rev ?? "")); + return null; + }); + await editorService().openInput({ + kind: "combined-diff", + key: `combined-diff:perf:${files}`, + path: paths[0] ?? "", + data: { + items: paths.map((path) => ({ + path, + left: { type: "rev", rev: "HEAD~1" }, + right: { type: "rev", rev: "HEAD" }, + })), + }, + }); + return { first: paths[0] ?? "", last: paths.at(-1) ?? "" }; + }, editorText: (from = 0, to) => activeEditor()?.view.state.doc.sliceString(from, to) ?? null, insertAfter(after, text) { const view = requireView();