@devries-cameron20 / t3code Mirror · read-only / commits / b96a511067
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 13:30 UTC

fix(web): repeated diff blocks no longer crash the viewer (#35304)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Jake Leventhal committed Nov 14, 2026 at 13:53 UTC b96a5110677c3ccd9c33ebcecbe7ff41f0789de1
5 files changed +251 -47
apps/web/src/components/DiffPanel.tsx
+8 -47
@@ -52,8 +52,7 @@ import { useHideTestFiles } from "./diffs/useHideTestFiles";
52 import { useRenderedAppearance } from "../hooks/useTheme";
53 import { useStableCallback } from "../hooks/useStableCallback";
54 import {
55 - buildFileDiffContentVersion,
56 - buildFileDiffIdentityKey,
55 + buildFileDiffEntries,
56 getDiffLineStat,
57 getRenderablePatch,
58 resolveDiffThemeName,
@@ -77,6 +76,7 @@ import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/Ann
76 import { DiffFileTree } from "./diffs/DiffFileTree";
77 import { FileExplorerPane } from "./files/FileExplorerPane";
78 import { diffFileTreeEntries } from "./diffs/diffFileTree.logic";
79 +import { getDiffHeaderClickAction } from "./diffs/diffHeaderClick";
80 import { Button } from "./ui/button";
81 import { ToggleGroup, Toggle } from "./ui/toggle-group";
82 import { Switch } from "./ui/switch";
@@ -120,22 +120,6 @@ import { useOpenLink } from "../browser/useOpenLink";
120 type DiffThemeType = "light" | "dark";
121 const AUTOMATIC_BASE_REF = "__automatic_base_ref__";
122 const DIFF_FILE_TREE_STORAGE_KEY = "t3code.diffFileTreeOpen";
123 -const fileEntryCache = new WeakMap<
124 - FileDiffMetadata,
125 - { fileDiff: FileDiffMetadata; fileKey: string; fileVersion: number }
126 ->();
127 -
128 -function getCachedFileEntry(fileDiff: FileDiffMetadata) {
129 - const cached = fileEntryCache.get(fileDiff);
130 - if (cached) return cached;
131 - const entry = {
132 - fileDiff,
133 - fileKey: buildFileDiffIdentityKey(fileDiff),
134 - fileVersion: buildFileDiffContentVersion(fileDiff),
135 - };
136 - fileEntryCache.set(fileDiff, entry);
137 - return entry;
138 -}
123
124 const EMPTY_COLLAPSED_DIFF_FILE_KEYS: ReadonlySet<string> = new Set();
125
@@ -172,6 +156,7 @@ function DiffFileCollapseToggle({
156 { rootMargin: "600px" },
157 );
158 }}
159 + data-diff-file-key={fileKey}
160 onClick={(event) => {
161 event.stopPropagation();
162 onToggle(fileKey);
@@ -651,9 +636,9 @@ export default function DiffPanel({
636
637 const isRefreshingDiff = branchDiffPreview.isPending || areFilePatchesPending;
638 const pathOccurrences = new Map<string, number>();
654 - const renderableFileEntries = renderableFiles.map((fileDiff) => {
655 - const entry = getCachedFileEntry(fileDiff);
639 + const renderableFileEntries = buildFileDiffEntries(renderableFiles).map((entry) => {
640 if (!isGitSelection) return entry;
641 + const { fileDiff } = entry;
642 // Metadata's change type can be missing or differ from the patch's; key each path's identity by path.
643 const pathKey = JSON.stringify([fileDiff.prevName ?? fileDiff.name, fileDiff.name]);
644 const occurrence = pathOccurrences.get(pathKey) ?? 0;
@@ -1407,33 +1392,9 @@ export default function DiffPanel({
1392 <div
1393 className="min-h-0 min-w-0 flex-1"
1394 onClickCapture={(event) => {
1410 - const composedPath = event.nativeEvent.composedPath?.() ?? [];
1411 - for (const node of composedPath) {
1412 - if (!(node instanceof HTMLElement)) continue;
1413 - // Header buttons own their clicks; bubbling a chevron click would toggle twice.
1414 - if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {
1415 - return;
1416 - }
1417 - }
1418 - const title = composedPath.find(
1419 - (node): node is HTMLElement =>
1420 - node instanceof HTMLElement && node.hasAttribute("data-title"),
1421 - );
1422 - const filePath = title?.textContent;
1423 - if (filePath) {
1424 - openDiffFile(filePath);
1425 - return;
1426 - }
1427 - const header = composedPath.find(
1428 - (node): node is HTMLElement =>
1429 - node instanceof HTMLElement && node.hasAttribute("data-diffs-header"),
1430 - );
1431 - const headerFilePath = header?.querySelector("[data-title]")?.textContent;
1432 - if (!headerFilePath) return;
1433 - const file = codeViewFiles.find(
1434 - (candidate) => candidate.filePath === headerFilePath,
1435 - );
1436 - if (file) toggleDiffFileCollapsed(file.fileKey);
1395 + const action = getDiffHeaderClickAction(event.nativeEvent);
1396 + if (action?.type === "open") openDiffFile(action.filePath);
1397 + else if (action?.type === "toggle") toggleDiffFileCollapsed(action.fileKey);
1398 }}
1399 onContextMenuCapture={(event) => {
1400 const composedPath = event.nativeEvent.composedPath?.() ?? [];
apps/web/src/components/diffs/StyledDiffCodeView.browser.test.tsx new
+151
@@ -0,0 +1,151 @@
1 +import type { CodeViewHandle } from "@pierre/diffs/react";
2 +import { WorkerPoolManager } from "@pierre/diffs/worker";
3 +import { useState, type Ref } from "react";
4 +import { describe, expect, it, vi } from "vite-plus/test";
5 +
6 +import { act, render } from "../../../test/render";
7 +
8 +vi.mock(import("../../hooks/useTheme"), async (original) => ({
9 + ...(await original()),
10 + useRenderedAppearance: (() => "dark") as never,
11 +}));
12 +
13 +import { buildFileDiffEntries, getRenderablePatch } from "../../lib/diffRendering";
14 +import { getDiffHeaderClickAction } from "./diffHeaderClick";
15 +import { StyledDiffCodeView } from "./StyledDiffCodeView";
16 +
17 +/** Records each worker pool's initialization so the test can wait for highlighting. */
18 +function captureWorkerPools() {
19 + const pools = new Map<WorkerPoolManager, Promise<void>>();
20 + const initialize = WorkerPoolManager.prototype.initialize;
21 + const spy = vi.spyOn(WorkerPoolManager.prototype, "initialize").mockImplementation(function (
22 + this: WorkerPoolManager,
23 + ...args
24 + ) {
25 + const pending = initialize.apply(this, args);
26 + pools.set(this, pending);
27 + return pending;
28 + });
29 + return { pools, [Symbol.dispose]: () => spy.mockRestore() };
30 +}
31 +
32 +// Exercises the production click helper against Pierre's real shadow DOM.
33 +function RepeatedDiffs({
34 + entries,
35 + viewerRef,
36 + onOpen,
37 +}: {
38 + entries: ReturnType<typeof buildFileDiffEntries>;
39 + viewerRef: Ref<CodeViewHandle<undefined, undefined>>;
40 + onOpen: (path: string) => void;
41 +}) {
42 + const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());
43 + const toggle = (key: string) =>
44 + setCollapsed((current) => {
45 + const next = new Set(current);
46 + if (next.has(key)) next.delete(key);
47 + else next.add(key);
48 + return next;
49 + });
50 + return (
51 + <div
52 + onClickCapture={(event) => {
53 + const action = getDiffHeaderClickAction(event.nativeEvent);
54 + if (action?.type === "open") onOpen(action.filePath);
55 + else if (action?.type === "toggle") toggle(action.fileKey);
56 + }}
57 + >
58 + <StyledDiffCodeView
59 + viewerRef={viewerRef}
60 + className="h-[600px] w-[800px]"
61 + items={entries.map(({ fileDiff, fileKey, fileVersion }) => ({
62 + type: "diff",
63 + id: fileKey,
64 + fileDiff,
65 + version: fileVersion + Number(collapsed.has(fileKey)),
66 + collapsed: collapsed.has(fileKey),
67 + }))}
68 + options={{ theme: "pierre-dark", diffStyle: "unified" }}
69 + renderHeaderPrefix={(item) => (
70 + <button data-diff-file-key={item.id} onClick={() => toggle(item.id)}>
71 + Chevron
72 + </button>
73 + )}
74 + />
75 + </div>
76 + );
77 +}
78 +
79 +describe("repeated diff blocks", () => {
80 + it("renders every repeated block and collapses only the clicked one", async () => {
81 + const parsed = getRenderablePatch(
82 + ["first", "second", "second"]
83 + .map((content) =>
84 + [
85 + "diff --git a/same.ts b/same.ts",
86 + "--- a/same.ts",
87 + "+++ b/same.ts",
88 + "@@ -1 +1 @@",
89 + "-before",
90 + `+${content}`,
91 + "",
92 + ].join("\n"),
93 + )
94 + .join(""),
95 + );
96 + if (parsed?.kind !== "files") throw new Error("Expected file diffs");
97 + using captured = captureWorkerPools();
98 + const { pools } = captured;
99 + const entries = buildFileDiffEntries(parsed.files);
100 + const onOpen = vi.fn();
101 + let viewer: CodeViewHandle<undefined, undefined> | null = null;
102 + await using _screen = await render(
103 + <RepeatedDiffs
104 + entries={entries}
105 + viewerRef={(value) => {
106 + viewer = value;
107 + }}
108 + onOpen={onOpen}
109 + />,
110 + // This viewer fixture does not navigate or read router state.
111 + { router: false },
112 + );
113 + const pool = [...pools.keys()][0]!;
114 + await act(async () => {
115 + await pools.get(pool);
116 + await Promise.all(parsed.files.map((file) => pool.primeDiffHighlightCache(file)));
117 + });
118 + const flush = () => act(async () => viewer?.getInstance()?.render(true));
119 + await flush();
120 + const blocks = () => [...document.querySelectorAll("diffs-container")];
121 + const body = (index: number) => blocks()[index]!.shadowRoot!.querySelector("[data-diff]");
122 + const click = async (element: Element) => {
123 + await act(async () =>
124 + element.dispatchEvent(new MouseEvent("click", { bubbles: true, composed: true })),
125 + );
126 + await flush();
127 + };
128 + const expectExpanded = async (expanded: boolean[]) => {
129 + await vi.waitFor(() => {
130 + expect(blocks()).toHaveLength(3);
131 + expect(blocks().map((_, index) => body(index) !== null)).toEqual(expanded);
132 + });
133 + };
134 + await expectExpanded([true, true, true]);
135 + await vi.waitFor(() => {
136 + expect(body(0)?.textContent).toContain("first");
137 + expect(body(1)?.textContent).toContain("second");
138 + expect(body(2)?.textContent).toContain("second");
139 + });
140 +
141 + await click(blocks()[1]!.shadowRoot!.querySelector("[data-diffs-header]")!);
142 + await expectExpanded([true, false, true]);
143 + await click(blocks()[1]!.shadowRoot!.querySelector("[data-title] bdi")!);
144 + expect(onOpen).toHaveBeenCalledExactlyOnceWith("same.ts");
145 + await expectExpanded([true, false, true]);
146 + await click(blocks()[1]!.querySelector("button")!);
147 + await expectExpanded([true, true, true]);
148 + await click(blocks()[0]!.shadowRoot!.querySelector("[data-diffs-header]")!);
149 + await expectExpanded([false, true, true]);
150 + });
151 +});
apps/web/src/components/diffs/diffHeaderClick.ts new
+23
@@ -0,0 +1,23 @@
1 +export function getDiffHeaderClickAction(event: MouseEvent) {
2 + const path = event.composedPath();
3 + // Controls own their actions; handling the chevron here too would toggle twice.
4 + for (const node of path) {
5 + if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) return null;
6 + }
7 + const title = path.find(
8 + (node): node is HTMLElement => node instanceof HTMLElement && node.hasAttribute("data-title"),
9 + );
10 + if (title?.textContent) return { type: "open" as const, filePath: title.textContent };
11 +
12 + const header = path.find(
13 + (node): node is HTMLElement =>
14 + node instanceof HTMLElement && node.hasAttribute("data-diffs-header"),
15 + );
16 + const root = header?.getRootNode();
17 + // Pierre renders the prefix through a slot; its React controls live on the shadow host.
18 + const fileKey =
19 + root instanceof ShadowRoot
20 + ? root.host.querySelector("[data-diff-file-key]")?.getAttribute("data-diff-file-key")
21 + : null;
22 + return fileKey ? { type: "toggle" as const, fileKey } : null;
23 +}
apps/web/src/lib/diffRendering.test.ts
+45
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test";
3 import { resolveDiffReviewPosition } from "../reviewCommentContext";
4 import {
5 buildFileDiffContentVersion,
6 + buildFileDiffEntries,
7 buildFileDiffIdentityKey,
8 buildFileDiffRenderKey,
9 getDiffLineStat,
@@ -266,6 +267,50 @@ describe("getRenderablePatch", () => {
267 });
268
269 describe("diff file reconciliation", () => {
270 + it("retains repeated blocks and their keys when content changes or other files appear", () => {
271 + const parse = (blocks: [string, string][]) => {
272 + const parsed = getRenderablePatch(
273 + blocks
274 + .map(([path, content]) =>
275 + [
276 + `diff --git a/${path} b/${path}`,
277 + `--- a/${path}`,
278 + `+++ b/${path}`,
279 + "@@ -1 +1 @@",
280 + "-before",
281 + `+${content}`,
282 + "",
283 + ].join("\n"),
284 + )
285 + .join(""),
286 + );
287 + if (parsed?.kind !== "files") throw new Error("Expected file diffs");
288 + return parsed.files;
289 + };
290 + const files = parse([
291 + ["same.ts", "first"],
292 + ["same.ts", "second"],
293 + ]);
294 + const before = buildFileDiffEntries([...files, files[1]!]);
295 + expect(before.map((entry) => entry.fileDiff)).toEqual([...files, files[1]]);
296 + expect(new Set(before.map((entry) => entry.fileKey)).size).toBe(3);
297 + expect(before[0]?.fileKey).toBe(buildFileDiffIdentityKey(files[0]!));
298 + expect(buildFileDiffEntries([...files, files[1]!])).toEqual(before);
299 +
300 + const after = buildFileDiffEntries(
301 + parse([
302 + ["unrelated.ts", "new"],
303 + ["same.ts", "first"],
304 + ["same.ts", "updated second"],
305 + ["same.ts", "second"],
306 + ]),
307 + ).slice(1);
308 + expect(after.map((entry) => entry.fileKey)).toEqual(before.map((entry) => entry.fileKey));
309 + expect(after[0]?.fileVersion).toBe(before[0]?.fileVersion);
310 + expect(after[1]?.fileVersion).not.toBe(before[1]?.fileVersion);
311 + expect(after[2]?.fileVersion).toBe(before[2]?.fileVersion);
312 + });
313 +
314 it("keeps Pierre's render key stable when a partial diff hydrates", () => {
315 const patch = [
316 "diff --git a/example.ts b/example.ts",
apps/web/src/lib/diffRendering.ts
+24
@@ -266,6 +266,30 @@ export function buildFileDiffContentVersion(fileDiff: FileDiffMetadata): number
266 return hash;
267 }
268
269 +const fileEntryCache = new WeakMap<
270 + FileDiffMetadata,
271 + { fileDiff: FileDiffMetadata; fileKey: string; fileVersion: number }
272 +>();
273 +
274 +/** Give repeated blocks independent viewer state without tying identity to patch content. */
275 +export function buildFileDiffEntries(files: ReadonlyArray<FileDiffMetadata>) {
276 + const occurrences = new Map<string, number>();
277 + return files.map((fileDiff) => {
278 + let entry = fileEntryCache.get(fileDiff);
279 + if (!entry) {
280 + entry = {
281 + fileDiff,
282 + fileKey: buildFileDiffIdentityKey(fileDiff),
283 + fileVersion: buildFileDiffContentVersion(fileDiff),
284 + };
285 + fileEntryCache.set(fileDiff, entry);
286 + }
287 + const occurrence = occurrences.get(entry.fileKey) ?? 0;
288 + occurrences.set(entry.fileKey, occurrence + 1);
289 + return occurrence === 0 ? entry : { ...entry, fileKey: `${entry.fileKey}\u0000${occurrence}` };
290 + });
291 +}
292 +
293 export const DIFF_SURFACE_THEME_UNSAFE_CSS = `
294 [data-diffs-header],
295 [data-diff],