GeezerVison is showing github.com — perf(web): diff panel no longer re-renders every file header each time a patch arrives by stevan-borus · Pull Request #16033 · pingdotgg/t3code
perf(web): diff panel no longer re-renders every file header each time a patch arrives
#16033
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter
Filter by extension
.ts
(1)
.tsx
(2)
All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
fix(web): diff panel no longer re-renders every file header each time…
… a patch arrives
Progressive loading delivers patches four at a time while the reader
scrolls, and each arrival re-rendered the header content of every
visible file through the viewer's portal slots: a tooltip, a button, a
copy control and a status per header, 30 to 40 headers at a time. On a
139-file diff that was about 40 ms of main-thread work per arrival and
the source of the scroll stutter. Header content now lives in its own
components fed primitive props and stable callbacks, so the compiler
keeps an untouched header's elements and React skips its subtree. No
React.memo: measured, it adds nothing on top of the compiler here.
Loading branch information
Uh oh!
There was an error while loading. Please reload this page.
commit 0e10842751520cad21ab6ef92635630b8b7c348c
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -118,6 +118,79 @@ interface CollapsedDiffFilesState {
const EMPTY_COLLAPSED_DIFF_FILE_KEYS: ReadonlySet<string> = new Set();
// Header content re-renders only when its own file changes.
function DiffFileCollapseToggle({
filePath,
fileKey,
collapsed,
unavailable,
iconClassName,
onToggle,
}: {
filePath: string;
fileKey: string;
collapsed: boolean;
unavailable: boolean;
iconClassName: string;
onToggle: (fileKey: string) => void;
}) {
return (
<Tooltip>
<TooltipTrigger
render={
<Button
size="icon-micro"
variant="ghost"
className="-ms-0.5"
aria-label={collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`}
aria-expanded={!collapsed}
disabled={unavailable}
onClick={(event) => {
event.stopPropagation();
onToggle(fileKey);
}}
/>
}
>
<MorphIcon
className={cn("size-4", iconClassName)}
icon={collapsed ? ChevronRight : ChevronDown}
/>
</TooltipTrigger>
<TooltipPopup side="top">{collapsed ? "Expand diff" : "Collapse diff"}</TooltipPopup>
</Tooltip>
);
}
// Header content re-renders only when its own file changes.
function DiffFileHeaderSuffix({
filePath,
hasStat,
error,
truncated,
onRetry,
}: {
filePath: string;
hasStat: boolean;
error: boolean;
truncated: boolean;
onRetry: (path: string) => void;
}) {
return (
<>
<DiffFilePathCopyButton filePath={filePath} />
{hasStat ? (
<DiffFileStatus error={error} truncated={truncated} retry={() => onRetry(filePath)} />
) : null}
</>
);
}
// Header content re-renders only when its own file changes.
function DiffFileHeaderStat({ additions, deletions }: { additions: number; deletions: number }) {
return <DiffStatLabel additions={additions} deletions={deletions} />;
}
interface DiffPanelProps {
mode?: DiffPanelMode;
composerDraftTarget: ScopedThreadRef | DraftId;
Expand Down
Expand Up
@@ -598,22 +671,22 @@ export default function DiffPanel({
},
[activeCwd, activeRepositoryRoot, openInPreferredEditor, routeThreadRef],
);
const toggleDiffFileCollapsed = useCallback(
(fileKey: string) => {
setCollapsedDiffFiles((current ) => {
const next = new Set(
current.scopeKey === collapseScopeKey ? current.fileKeys : defaultCollapsedDiffFileKeys,
);
if (next.has(fileKey)) {
next.delete(fileKey );
} else {
next.add (fileKey);
}
return { scopeKey: collapseScopeKey, fileKeys: next } ;
});
},
[collapseScopeKey, defaultCollapsedDiffFileKeys],
);
const collapseDefaultsRef = useRef({ collapseScopeKey, defaultCollapsedDiffFileKeys });
collapseDefaultsRef.current = { collapseScopeKey, defaultCollapsedDiffFileKeys };
const toggleDiffFileCollapsed = useCallback((fileKey: string ) => {
const { collapseScopeKey, defaultCollapsedDiffFileKeys } = collapseDefaultsRef.current;
setCollapsedDiffFiles(( current) => {
const next = new Set(
current.scopeKey === collapseScopeKey ? current.fileKeys : defaultCollapsedDiffFileKeys,
);
if (next.has(fileKey)) {
next.delete (fileKey);
} else {
next.add(fileKey) ;
}
return { scopeKey: collapseScopeKey, fileKeys: next };
});
}, [] );
const toggleDiffFileCollapse = useCallback(() => {
setCodeViewRevision((current) => current + 1);
Expand Down
Expand Up
@@ -1082,14 +1155,15 @@ export default function DiffPanel({
composerDraftTarget={composerDraftTarget}
renderHeaderFilenameSuffix={(fileDiff) => {
const path = resolveFileDiffPath(fileDiff);
const stat = fileStats .get(path);
const state = fileStates .get(path);
return (
<>
<DiffFilePathCopyButton filePath={path} />
{stat ? (
<DiffFileStatus {...fileStates.get(path)} retry={() => retry(path)} />
) : null}
</>
<DiffFileHeaderSuffix
filePath={path}
hasStat={fileStats.has(path)}
error={state?.error ?? false}
truncated={state?.truncated ?? false}
onRetry={retry}
/>
);
}}
{...(lazySource
Expand All
@@ -1099,7 +1173,7 @@ export default function DiffPanel({
renderHeaderMetadata: (fileDiff: FileDiffMetadata) => {
const stat = fileStats.get(resolveFileDiffPath(fileDiff));
return stat ? (
<DiffStatLabel
<DiffFileHeaderStat
additions={stat.additions}
deletions={stat.deletions}
/>
Expand All
@@ -1109,37 +1183,15 @@ export default function DiffPanel({
: {})}
renderHeaderPrefix={(fileDiff, fileKey) => {
const unavailable = fileDiff.cacheKey?.endsWith(":pending") === true;
const collapsed = unavailable || collapsedDiffFileKeys.has(fileKey);
const filePath = resolveFileDiffPath(fileDiff);
return (
<Tooltip>
<TooltipTrigger
render={
<Button
size="icon-micro"
variant="ghost"
className="-ms-0.5"
aria-label={
collapsed ? `Expand ${filePath}` : `Collapse ${filePath}`
}
aria-expanded={!collapsed}
disabled={unavailable}
onClick={(event) => {
event.stopPropagation();
toggleDiffFileCollapsed(fileKey);
}}
/>
}
>
<MorphIcon
className={cn("size-4", getDiffCollapseIconClassName(fileDiff))}
icon={collapsed ? ChevronRight : ChevronDown}
/>
</TooltipTrigger>
<TooltipPopup side="top">
{collapsed ? "Expand diff" : "Collapse diff"}
</TooltipPopup>
</Tooltip>
<DiffFileCollapseToggle
filePath={resolveFileDiffPath(fileDiff)}
fileKey={fileKey}
collapsed={unavailable || collapsedDiffFileKeys.has(fileKey)}
unavailable={unavailable}
iconClassName={getDiffCollapseIconClassName(fileDiff)}
onToggle={toggleDiffFileCollapsed}
/>
);
}}
options={{
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -8,7 +8,7 @@ import type {
} from "@pierre/diffs";
import type { CodeViewHandle } from "@pierre/diffs/react";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { useCallback, useMemo, useState, type ReactNode, type Ref } from "react";
import { useCallback, useMemo, useRef, useState, type ReactNode, type Ref } from "react";
import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
import { fnv1a32 } from "~/lib/diffRendering";
Expand Down
Expand Up
@@ -132,6 +132,8 @@ export function AnnotatableCodeView({
const [draftText, setDraftText] = useState("");
const filesByKey = useMemo(() => new Map(files.map((file) => [file.fileKey, file])), [files]);
const filesByKeyRef = useRef(filesByKey);
filesByKeyRef.current = filesByKey;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
const items = useMemo<CodeViewDiffItem<DiffCommentAnnotationGroup>[]>(
() =>
files.map(({ fileDiff, filePath, fileKey, fileVersion, collapsed }) => {
Expand Down
Expand Up
@@ -217,7 +219,7 @@ export function AnnotatableCodeView({
if (!range) return;
const item = context.item;
if (item.type !== "diff") return;
const file = filesByKey .get(item.id);
const file = filesByKeyRef.current .get(item.id);
if (!file) return;
const id = nextFileCommentId();
const comment = buildDiffReviewComment({
Expand All
@@ -242,7 +244,7 @@ export function AnnotatableCodeView({
},
});
},
[filesByKey, sectionId, sectionTitle],
[sectionId, sectionTitle],
);
const hasOpenComment = draft !== null;
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -146,12 +146,15 @@ export function useReviewFilePatches({
[requestFiles, settledFileCount],
);
const requestFile = useCallback((index: number) => requestFiles([index]), [requestFiles]);
const retryInputsRef = useRef({ queries, files });
retryInputsRef.current = { queries, files };
const retry = useCallback(
(path: string) => {
const { queries, files } = retryInputsRef.current;
const query = queries.find(({ index }) => files[index]?.path === path)?.query;
if (query) registry.refresh(query);
},
[queries, files, registry],
[registry],
);
const renderableFiles = useMemo(
() =>
Expand Down
Expand Up
@@ -185,23 +188,27 @@ export function useReviewFilePatches({
),
[source, files, patches, scope, preview],
);
const fileStates = new Map(
files.map((file, index) => {
const patch = patches.get(index);
return [
file.path,
{
error:
patch?._tag === "Failure" ||
(patch?._tag === "Success" &&
(patch.value.patch?.kind !== "files" ||
!patch.value.patch.files.some(
(candidate) => resolveFileDiffPath(candidate) === file.path,
))),
truncated: patch?._tag === "Success" && patch.value.source.truncated,
},
] as const;
}),
const fileStates = useMemo(
() =>
new Map(
files.map((file, index) => {
const patch = patches.get(index);
return [
file.path,
{
error:
patch?._tag === "Failure" ||
(patch?._tag === "Success" &&
(patch.value.patch?.kind !== "files" ||
!patch.value.patch.files.some(
(candidate) => resolveFileDiffPath(candidate) === file.path,
))),
truncated: patch?._tag === "Success" && patch.value.source.truncated,
},
] as const;
}),
),
[files, patches],
);
const readyFilePaths = useMemo(
() =>
Expand Down
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.