From 3735707920634dce95aa20c450c679db10c7bd08 Mon Sep 17 00:00:00 2001 From: Michal Wrzosek Date: Wed, 14 Oct 2026 04:16:06 +0200 Subject: [PATCH 1/6] Make big diffs fast, and add a review progress strip MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a 401-file branch (±90k lines) the files tab took 11.8s to open, built 2.19M DOM nodes, and froze on the first scroll: every change of the active file re-rendered every card and every line. Now it opens in under a second with ~28k nodes and scrolls at ~15ms a frame. - File cards and line rows are memoised, and the tab hands them props that keep their identity (comment mutations, find state, source, mark callback). - A card's rows are built only when it nears the viewport (one shared IntersectionObserver per scroller), with a placeholder of the estimated height until then; built bodies use content-visibility: auto. Syntax highlighting waits for the build too. - A smooth scroll to something more than three screens away becomes instant, so a jump does not build every file it passes. - File tree rows are memoised on primitive props. The progress strip is pinned above the diff: one equal slot per file however long it is, green for reviewed, amber for changed since reviewed, a marker for how far you have scrolled in files, click a slot to jump, hover to see which file it is, a glow on each tick and a flourish at 100%. It replaces the "N of M reviewed" text in the toolbar. The strip measures "the file you are on" from the same line stepping with `]` does (the cards' scroll margin), so the two always name the same file. Co-Authored-By: Claude Opus 5.5 --- .../src/features/comments/use-comments.ts | 31 +- .../reviews/__tests__/review-progress.test.ts | 81 ++++ .../features/reviews/changed-files-tree.tsx | 63 ++- .../src/features/reviews/diff-find-bar.tsx | 27 +- .../src/features/reviews/diff-view.tsx | 138 ++++++- .../src/features/reviews/review-files-tab.tsx | 274 ++++++++----- .../features/reviews/review-progress-model.ts | 122 ++++++ .../src/features/reviews/review-progress.tsx | 382 ++++++++++++++++++ src/renderer/src/index.css | 34 +- src/renderer/src/lib/near-viewport.ts | 78 ++++ src/renderer/src/lib/reveal.ts | 34 +- src/renderer/src/lib/scroll-parent.ts | 17 + tsconfig.node.json | 2 + 13 files changed, 1127 insertions(+), 156 deletions(-) create mode 100644 src/renderer/src/features/reviews/__tests__/review-progress.test.ts create mode 100644 src/renderer/src/features/reviews/review-progress-model.ts create mode 100644 src/renderer/src/features/reviews/review-progress.tsx create mode 100644 src/renderer/src/lib/near-viewport.ts create mode 100644 src/renderer/src/lib/scroll-parent.ts diff --git a/src/renderer/src/features/comments/use-comments.ts b/src/renderer/src/features/comments/use-comments.ts index 6d53194..9bef61c 100644 --- a/src/renderer/src/features/comments/use-comments.ts +++ b/src/renderer/src/features/comments/use-comments.ts @@ -15,7 +15,7 @@ * that moved on while the window was in the background. */ import { useSWRConfig } from 'swr' -import { useCallback } from 'react' +import { useCallback, useMemo } from 'react' import { CACHE_PREFIXES } from '@/lib/api' import { useApi } from '@/lib/host-scope' import { useReviewThreads } from '@/features/reviews/use-reviews' @@ -65,44 +65,51 @@ export function useCommentMutations(): CommentMutations { [mutate] ) - return { - createThread: useCallback( + const createThread: CommentMutations['createThread'] = useCallback( async (input) => { const thread = await api.comments.createThread(input) await revalidate() return thread }, [api, revalidate] - ), - reply: useCallback( + ) + const reply: CommentMutations['reply'] = useCallback( async (input) => { const comment = await api.comments.reply(input) await revalidate() return comment }, [api, revalidate] - ), - edit: useCallback( + ) + const edit: CommentMutations['edit'] = useCallback( async (id, body) => { const comment = await api.comments.update({ id, body }) await revalidate() return comment }, [api, revalidate] - ), - remove: useCallback( + ) + const remove: CommentMutations['remove'] = useCallback( async (id) => { await api.comments.remove({ id }) await revalidate() }, [api, revalidate] - ), - setResolved: useCallback( + ) + const setResolved: CommentMutations['setResolved'] = useCallback( async (threadId, resolved) => { await api.comments.setResolved({ threadId, resolved }) await revalidate() }, [api, revalidate] ) - } + + // One object for as long as the callbacks in it are the same ones. The files + // tab hands it to every file card, and a fresh object on each render would + // re-render all of them - every line of a four-hundred-file diff - whenever + // the reader scrolled onto a new file. + return useMemo( + () => ({ createThread, reply, edit, remove, setResolved }), + [createThread, reply, edit, remove, setResolved] + ) } diff --git a/src/renderer/src/features/reviews/__tests__/review-progress.test.ts b/src/renderer/src/features/reviews/__tests__/review-progress.test.ts new file mode 100644 index 0000000..51748cf --- /dev/null +++ b/src/renderer/src/features/reviews/__tests__/review-progress.test.ts @@ -0,0 +1,81 @@ +/** + * The progress strip counts files, not lines. + * + * Worth pinning down because it is the whole reason the strip exists: a lock + * file regenerated alongside four real changes must be one slot of five, and + * must not swallow the bar. + */ +import assert from 'node:assert/strict' +import { test } from 'node:test' + +import { fileAt, markRuns, readingPosition, type CardBox } from '../review-progress-model.js' + +const PATHS = ['a.ts', 'b.ts', 'package-lock.json', 'c.ts', 'd.ts'] + +test('neighbouring files in the same state are drawn as one run', () => { + const runs = markRuns(PATHS, new Set(['a.ts', 'b.ts', 'package-lock.json', 'd.ts']), new Set()) + assert.deepEqual(runs, [ + { mark: 'reviewed', start: 0, length: 3 }, + { mark: 'reviewed', start: 4, length: 1 } + ]) +}) + +test('a file changed since it was reviewed is a run of its own kind', () => { + const runs = markRuns(PATHS, new Set(['a.ts']), new Set(['b.ts', 'package-lock.json'])) + assert.deepEqual(runs, [ + { mark: 'reviewed', start: 0, length: 1 }, + { mark: 'changed', start: 1, length: 2 } + ]) +}) + +test('nothing reviewed is nothing drawn', () => { + assert.deepEqual(markRuns(PATHS, new Set(), new Set()), []) +}) + +/** Five cards stacked down the page; the lock file is a hundred times taller. */ +const HEIGHTS = [200, 200, 20_000, 200, 200] +function boxes(scrolled: number): (index: number) => CardBox { + return (index) => { + let top = -scrolled + for (let before = 0; before < index; before += 1) top += HEIGHTS[before] ?? 0 + return { top, height: HEIGHTS[index] ?? 0 } + } +} + +test('at the top of the diff the reader is at the start', () => { + assert.equal(readingPosition(5, 0, boxes(0), false), 0) +}) + +test('halfway through a short file is half a slot', () => { + assert.equal(readingPosition(5, 0, boxes(100), false), 0.5) +}) + +test('the lock file is one slot however long it scrolls', () => { + // Two short files read and halfway down a file a hundred times their size. + assert.equal(readingPosition(5, 0, boxes(400 + 10_000), false), 2.5) + // Past it, the reader is on file four - not four-fifths of the way through + // the lines of the branch. + assert.equal(readingPosition(5, 0, boxes(400 + 20_000), false), 3) +}) + +test('a scroller at its end has shown every file', () => { + assert.equal(readingPosition(5, 0, boxes(400), true), 5) +}) + +test('above the first card - the toolbar - is the start', () => { + assert.equal(readingPosition(5, 0, boxes(-50), false), 0) +}) + +test('a card missing from the DOM counts as still below the line', () => { + const box = boxes(250) + assert.equal(readingPosition(5, 0, (index) => (index >= 2 ? null : box(index)), false), 1.25) +}) + +test('a point on the strip lands on the slot under it', () => { + assert.equal(fileAt(5, 0, 500), 0) + assert.equal(fileAt(5, 250, 500), 2) + assert.equal(fileAt(5, 499, 500), 4) + // The far edge itself, and past it, is still the last file. + assert.equal(fileAt(5, 500, 500), 4) + assert.equal(fileAt(5, -10, 500), 0) +}) diff --git a/src/renderer/src/features/reviews/changed-files-tree.tsx b/src/renderer/src/features/reviews/changed-files-tree.tsx index 137ea8f..d4f76e2 100644 --- a/src/renderer/src/features/reviews/changed-files-tree.tsx +++ b/src/renderer/src/features/reviews/changed-files-tree.tsx @@ -18,7 +18,7 @@ * same ranking, the same name-first result row - means the gesture that finds a * file is one gesture in this app rather than one per tab. */ -import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from 'react' +import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from 'react' import { Check, ChevronDown, ChevronRight, History } from 'lucide-react' import { cn } from '@/lib/utils' import { plural } from '@/lib/format' @@ -200,7 +200,7 @@ export function ChangedFilesTree({ key={match.path} file={byPath.get(match.path) as FileDiff} indices={match.indices} - {...rowProps} + {...rowState(match.path, rowProps)} /> ))} {matches.total > matches.shown.length && ( @@ -228,7 +228,8 @@ function TreeRows({ const [open, setOpen] = useState(true) // Indent by nesting depth, but stop growing it before the column runs out of // room; a path fifteen directories deep should still show its file name. - const indent = { paddingLeft: `${Math.min(depth, 6) * 0.75 + 0.25}rem` } + const paddingLeft = `${Math.min(depth, 6) * 0.75 + 0.25}rem` + const indent = { paddingLeft } if (node.kind === 'directory') { return ( @@ -264,36 +265,60 @@ function TreeRows({ } // Always present: the tree was built from these very paths. - return + return ( + + ) +} + +/** + * What one row needs to know, boiled down to values that compare equal when + * nothing about that row changed - which is what lets `FileRow` skip the + * re-render. Scrolling onto a new file moves the highlight between two rows, + * and on a branch of four hundred files the other three hundred and ninety-eight + * have no reason to be drawn again. + */ +function rowState(path: string, props: Omit) { + return { + isActive: path === props.activePath, + isReviewed: props.reviewedPaths.has(path), + hasChangedSince: props.changedSincePaths.has(path), + unresolved: props.unresolvedByFile.get(path) ?? 0, + onSelect: props.onSelect + } } -function FileRow({ +const FileRow = memo(function FileRow({ file, indices, - indent, - activePath, - onSelect, - unresolvedByFile, - reviewedPaths, - changedSincePaths + paddingLeft, + isActive, + isReviewed, + hasChangedSince, + unresolved, + onSelect }: { file: FileDiff /** Set on a filter row: which characters of the path the query hit. */ indices?: number[] /** Set on a tree row, where the depth is what the indent is measuring. */ - indent?: { paddingLeft: string } -} & Omit) { + paddingLeft?: string + isActive: boolean + isReviewed: boolean + hasChangedSince: boolean + unresolved: number + onSelect: (path: string) => void +}) { const path = file.path - const unresolved = unresolvedByFile.get(path) ?? 0 - const isActive = path === activePath - const isReviewed = reviewedPaths.has(path) - const hasChangedSince = changedSincePaths.has(path) return ( ) -} +}) diff --git a/src/renderer/src/features/reviews/diff-find-bar.tsx b/src/renderer/src/features/reviews/diff-find-bar.tsx index 14fa19d..f98cafc 100644 --- a/src/renderer/src/features/reviews/diff-find-bar.tsx +++ b/src/renderer/src/features/reviews/diff-find-bar.tsx @@ -150,20 +150,33 @@ export function useDiffFind(files: readonly FileDiff[]): DiffFind { // eslint-disable-next-line react-hooks/exhaustive-deps }, [activeKey]) - const searchFor = useCallback( - (path: string): DiffSearch | undefined => - term === '' + /** + * The same object for every file the current hit is not in, and one more for + * the file it is. A card is only re-rendered when what it is handed changes, + * so a fresh object per file per render would redraw the whole diff on every + * step through the hits rather than the two files the step moved between. + */ + const passive = useMemo( + () => (term === '' ? undefined : { query: term, active: null }), + [term] + ) + const pointed = useMemo( + () => + term === '' || active === null ? undefined : { query: term, - active: - active !== null && active.filePath === path - ? { side: active.side, line: active.line, occurrence: active.occurrence } - : null + active: { side: active.side, line: active.line, occurrence: active.occurrence } }, [term, active] ) + const searchFor = useCallback( + (path: string): DiffSearch | undefined => + active !== null && active.filePath === path ? pointed : passive, + [active, pointed, passive] + ) + return { open, query, diff --git a/src/renderer/src/features/reviews/diff-view.tsx b/src/renderer/src/features/reviews/diff-view.tsx index de8502a..a25d865 100644 --- a/src/renderer/src/features/reviews/diff-view.tsx +++ b/src/renderer/src/features/reviews/diff-view.tsx @@ -25,7 +25,17 @@ * shown slightly out of place. A file with a collapsed body still shows its * comment count, so a discussion is never hidden behind a fold. */ -import { Fragment, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react' +import { + Fragment, + memo, + useCallback, + useEffect, + useMemo, + useRef, + useState, + type CSSProperties, + type ReactNode +} from 'react' import { Check, ChevronDown, @@ -47,6 +57,7 @@ import { Badge } from '@/components/ui/badge' import { Card } from '@/components/ui/card' import { Checkbox } from '@/components/ui/checkbox' import { Tooltip } from '@/components/ui/tooltip' +import { whenNearViewport } from '@/lib/near-viewport' import { cn } from '@/lib/utils' import { CommentComposer } from '../comments/comment-composer' import { CommentThreadCard } from '../comments/comment-thread-card' @@ -88,6 +99,16 @@ export type DiffLayout = 'unified' | 'split' /** Files longer than this arrive collapsed; see the note above. */ const COLLAPSE_ABOVE_LINES = 600 +/** + * The height of one row of the diff, in rem - `leading-5`. + * + * Only ever used as a guess: the space a body takes before it has been built, + * and the size the browser assumes for one it is skipping. A guess that is a + * little off moves nothing the reader is looking at, because the browser keeps + * the content on screen anchored while what is above it settles. + */ +const ROW_REM = 1.25 + /** How many lines one nudge of an expander reveals. */ const EXPAND_STEP = 20 @@ -233,7 +254,13 @@ function isExpandable(file: FileDiff): boolean { return !file.isUntracked } -export function FileDiffCard({ +/** + * Memoised, because a diff can hold hundreds of these and the tab around them + * re-renders whenever the reader scrolls onto a new file. Every prop the tab + * hands down is kept stable for exactly this reason - see `FileDiffItem` in + * `review-files-tab.tsx`. + */ +export const FileDiffCard = memo(function FileDiffCard({ file, comments, source, @@ -294,6 +321,29 @@ export function FileDiffCard({ const isReviewed = reviewed?.isReviewed ?? false + /** + * Whether the rows have been built yet. + * + * A card draws its header at once and its rows only when the reader is nearly + * at them - see `lib/near-viewport.ts`. Before this, a four-hundred-file + * branch built two million elements before the first one could be seen, and + * every scroll after that dragged all of them along. + * + * Once built, a body stays built. Unmounting on the way past would throw + * away whatever the reader had unfolded or half-typed in it, and the browser + * already skips laying out a body that is off screen - see `content-visibility` + * below - which is most of what unmounting would have saved. + */ + const [bodyBuilt, setBodyBuilt] = useState(false) + // Somewhere is being pointed at inside this file, and it cannot wait for a + // scroll to bring the rows in - the scroll is aiming at one of them. + const mustBuild = search?.active != null || focus !== undefined || marked !== undefined + const built = bodyBuilt || mustBuild + const placeholder = useRef(null) + // Latched during render, the way the find bar resets its walk: being pointed + // at once is reason enough to keep the rows after the pointing moves on. + if (mustBuild && !bodyBuilt) setBodyBuilt(true) + /** * Derived rather than stored, so arriving at a line inside a folded file just * opens it - no effect, no second render, and a card the reviewer has closed @@ -335,12 +385,13 @@ export function FileDiffCard({ const canExpand = source !== undefined && isExpandable(file) const text = useReviewFile(canExpand ? source.reviewId : null, file.path, source?.changes ?? 'all') - // Coloured only while the body is on screen; a folded card asks for nothing. + // Coloured only once the body is built; a folded or far-off card asks for + // nothing, so opening a big branch does not queue a grammar run per file. const highlight = useDiffHighlight( file.path, file.hunks, text.content && !text.content.isBinary ? text.content.lines : null, - expanded && file.hunks.length > 0 + expanded && built && file.hunks.length > 0 ) const reveal = useCallback( @@ -456,6 +507,7 @@ export function FileDiffCard({ function expandEverything(): void { for (const gap of gaps) reveal(gap.start, gap.end ?? gap.start + EXPAND_UNBOUNDED) + setBodyBuilt(true) setExpanded(true) } @@ -474,6 +526,29 @@ export function FileDiffCard({ const showsBinaryNote = expanded && !hasBody && file.isBinary && !showsImage const showsBody = showsOrphans || showsDiff || showsImageDiff || showsBinaryNote + useEffect(() => { + const element = placeholder.current + if (built || !showsDiff || element === null) return + return whenNearViewport(element, () => setBodyBuilt(true)) + }, [built, showsDiff]) + + /** + * Roughly how tall the rows will be: one per line, plus one for each band + * between hunks. Reserved before the body is built so the page is the right + * length from the start - the scrollbar, the file stepping and the progress + * strip all measure it. + */ + const estimatedRem = (lineCount + file.hunks.length + (tailGap ? 1 : 0)) * ROW_REM + /** + * Built bodies the reader has moved away from are skipped by the browser + * until they come back - no layout, no paint. `auto` makes it remember the + * size it last drew rather than fall back to the estimate. + */ + const bodyStyle: CSSProperties = { + contentVisibility: 'auto', + containIntrinsicSize: `auto ${estimatedRem}rem` + } + return ( // `clip` rather than `hidden`: both cut the diff to the card's rounded // corners, but `hidden` makes the card a scroll container of its own, and a @@ -506,7 +581,12 @@ export function FileDiffCard({ read as belonging to it. */}