perf(diff): parse a patch once and cap the default expansion

This commit is contained in:
Menghuan1918 committed 2026-10-24 02:17:10 +08:00
1 parent b1efd9226b
commit 2237f3787b
3 files changed
+96 -12

No files matched your search

+14 -4
View File
@@ -430,18 +430,27 @@ export function DiffPane({ target, ctx, scope, height, onHeightCommit, onClose,
[htmlOp, scope, contentAbs],
)
// Header stats for git targets come off the parsed patch text.
const gitStats = useMemo(() => {
/**
* ONE parse of the patch per target: the header stats and the file rows both
* read it. Parsing an ≤8MB patch twice on the UI thread (once here for the
* stats, once inside DiffFiles) was visible when a large commit was opened.
*/
const gitParsed = useMemo(() => {
if (target.kind !== 'git' || diffText === null || diffText === '') return null
return parseUnifiedDiff(diffText)
}, [target.kind, diffText])
// Header stats for git targets come off that shared parse.
const gitStats = useMemo(() => {
if (gitParsed === null) return null
let added = 0
let deleted = 0
for (const file of parseUnifiedDiff(diffText).files) {
for (const file of gitParsed.files) {
const stats = diffStats(unifiedSegments(file))
added += stats.added
deleted += stats.deleted
}
return { added, deleted }
}, [target, diffText])
}, [gitParsed])
// ── Resize: drag the top handle; commit on release (persisted by the
// shell). Arrow keys resize by a step for keyboard users. ────────────
@@ -662,6 +671,7 @@ export function DiffPane({ target, ctx, scope, height, onHeightCommit, onClose,
{((diffText !== null && diffText !== '') || untracked !== undefined) && (
<DiffFiles
diff={diffText ?? ''}
parsed={untracked === undefined ? gitParsed ?? undefined : undefined}
resolveFold={resolveFold}
untrackedPath={untracked !== undefined && target.ref.kind === 'worktree' ? target.ref.path : undefined}
untrackedContent={untracked}
+30 -8
View File
@@ -10,7 +10,7 @@
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import clsx from 'clsx'
import { t } from '../locales.ts'
import { diffStats, displayPath, parseUnifiedDiff, unifiedSegments, untrackedFile, type DiffFile, type DiffRow, type FoldSegment } from './rows.ts'
import { diffStats, displayPath, parseUnifiedDiff, unifiedSegments, untrackedFile, type DiffFile, type DiffRow, type FoldSegment, type ParsedDiff } from './rows.ts'
import { langOfPath } from './highlight.ts'
import { DiffRows } from './DiffRows.tsx'
import css from './diff.module.css'
@@ -20,16 +20,32 @@ const DOC_PATH = /(^|\/)(?:docs?|documentation)(?:\/|$)|(^|\/)(?:readme|changelo
const GENERATED_PATH = /(^|\/)(?:dist|build|coverage|generated|vendor|node_modules)(?:\/|$)|(^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|composer\.lock|cargo\.lock|poetry\.lock)$/i
const SOURCE_PATH = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts|py|pyw|rb|php|java|kt|kts|scala|go|rs|swift|c|h|cc|cpp|cxx|hpp|hh|hxx|cs|fs|fsx|vb|dart|lua|r|ex|exs|erl|hrl|clj|cljs|cljc|groovy|sh|bash|zsh|fish|ps1|sql|vue|svelte|astro|html|htm|css|scss|sass|less)$/i
/**
* How many changed lines the default expansion may mount.
*
* Source files open by default, but a commit that rewrites a dozen of them
* used to mount every row at once (each file renders through DiffRows, capped
* at 600 rows). The budget keeps the first screen useful without paying for
* the whole patch: the FIRST source file always opens (an all-folded pane
* reads as empty), and everything past the budget stays folded with its +/−
* stats still on the header, one click away.
*/
const DEFAULT_EXPANDED_LINE_BUDGET = 2_000
/** Source files open by default; tests, docs, generated files and unknown types stay folded. */
function defaultExpandedFiles(files: readonly DiffFile[]): Set<number> {
const expanded = new Set<number>()
let budget = 0
files.forEach((file, index) => {
const path = displayPath(file.newPath === '/dev/null' ? file.oldPath : file.newPath)
if (!file.binary && file.hunks.length > 0
const isSource = !file.binary && file.hunks.length > 0
&& !TEST_PATH.test(path) && !DOC_PATH.test(path) && !GENERATED_PATH.test(path)
&& SOURCE_PATH.test(path)) {
expanded.add(index)
}
&& SOURCE_PATH.test(path)
if (!isSource) return
const changedLines = file.hunks.reduce((total, hunk) => total + hunk.lines.length, 0)
if (expanded.size > 0 && budget + changedLines > DEFAULT_EXPANDED_LINE_BUDGET) return
expanded.add(index)
budget += changedLines
})
return expanded
}
@@ -48,6 +64,12 @@ function fileTag(file: DiffFile): string | null {
export interface DiffFilesProps {
/** Unified diff text (`git.diff` or `git.commit-diff` payloads). */
diff: string
/** A parse the caller ALREADY did for its own header stats: rendering the
* same ≤8MB patch twice on the UI thread was visible on large commits. The
* component trusts it as-is (the changes pane passes the parse it just
* summarized); omit it to parse `diff` here. Ignored for untracked files,
* whose synthetic full-file addition comes from their content. */
parsed?: ParsedDiff
/** Untracked-file content: when present, renders as a full-file addition instead of parsing. */
untrackedPath?: string
untrackedContent?: string
@@ -58,13 +80,13 @@ export interface DiffFilesProps {
resolveFold?: (file: DiffFile, segment: FoldSegment) => Promise<readonly DiffRow[]>
}
export function DiffFiles({ diff, untrackedPath, untrackedContent, resolveFold }: DiffFilesProps) {
export function DiffFiles({ diff, parsed: provided, untrackedPath, untrackedContent, resolveFold }: DiffFilesProps) {
const parsed = useMemo(() => {
if (untrackedPath !== undefined) {
return { files: [untrackedFile(untrackedPath, untrackedContent ?? '')] }
}
return parseUnifiedDiff(diff)
}, [diff, untrackedPath, untrackedContent])
return provided ?? parseUnifiedDiff(diff)
}, [provided, diff, untrackedPath, untrackedContent])
const [expandedFiles, setExpandedFiles] = useState<Set<number>>(() => defaultExpandedFiles(parsed.files))
useEffect(() => { setExpandedFiles(defaultExpandedFiles(parsed.files)) }, [parsed])
+52
View File
@@ -4,6 +4,7 @@ import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { DiffFiles } from '../src/client/diff/DiffFiles.tsx'
import { parseUnifiedDiff } from '../src/client/diff/rows.ts'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
@@ -57,4 +58,55 @@ describe('DiffFiles file folding', () => {
container.remove()
}
})
it('caps the default expansion by changed lines, not by file count', () => {
// Six source files of 600 changed lines each: the first three fill the
// 2000-line budget, so the other three start folded (their headers still
// carry the +/− stats and can be opened one by one).
const parts: string[] = []
for (let file = 0; file < 6; file += 1) {
parts.push(
`diff --git a/src/f${file}.ts b/src/f${file}.ts`,
`--- a/src/f${file}.ts`,
`+++ b/src/f${file}.ts`,
'@@ -1,300 +1,300 @@',
)
for (let line = 0; line < 300; line += 1) parts.push(`-old-${file}-${line}`, `+new-${file}-${line}`)
}
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
try {
act(() => { root.render(createElement(DiffFiles, { diff: parts.join('\n') })) })
const headers = [...container.querySelectorAll<HTMLButtonElement>('button[aria-expanded]')]
expect(headers).toHaveLength(6)
expect(headers.map(header => header.getAttribute('aria-expanded')))
.toEqual(['true', 'true', 'true', 'false', 'false', 'false'])
// Only the three budgeted files mount their rows (600 each; the pairs
// render as `mod`, so count every change class and not just `add`).
expect(container.querySelectorAll('[data-kind="add"], [data-kind="del"], [data-kind="mod"], [data-kind="context"]'))
.toHaveLength(1800)
} finally {
act(() => { root.unmount() })
container.remove()
}
})
it('renders the caller-supplied parse instead of parsing the patch again', () => {
// The changes pane parses one patch for BOTH its header stats and these
// rows; a second parse of an ≤8MB patch on the UI thread was the cost.
const parsed = parseUnifiedDiff(diff)
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
try {
act(() => { root.render(createElement(DiffFiles, { diff: 'not a unified diff', parsed })) })
const headers = [...container.querySelectorAll<HTMLButtonElement>('button[aria-expanded]')]
expect(headers).toHaveLength(3)
expect(container.textContent).toContain('new-a')
} finally {
act(() => { root.unmount() })
container.remove()
}
})
})