Skip to content

Commit 6e6459f

Browse files
fix(web): defer collapsed diff highlighting until expansion
1 parent aedc7fd commit 6e6459f

5 files changed

Lines changed: 221 additions & 109 deletions

File tree

‎apps/web/src/components/diffs/StyledDiffCodeView.browser.test.tsx‎

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
import {
2+
CodeView,
3+
FileDiff,
24
FileRenderer,
35
getSharedHighlighter,
6+
type CodeViewItem,
47
type CodeViewScrollTarget,
58
type FileContents,
69
} from "@pierre/diffs";
710
import { useWorkerPool, type CodeViewProps } from "@pierre/diffs/react";
811
import { WorkerPoolManager, type WorkerRequest, type WorkerResponse } from "@pierre/diffs/worker";
12+
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
13+
import { getDiffLineStat, getRenderablePatch } from "../../lib/diffRendering";
914
import {
1015
act,
1116
StrictMode,
@@ -305,6 +310,157 @@ describe("code-view worker lifecycle", () => {
305310
});
306311
});
307312

313+
describe("collapsed diff content", () => {
314+
let pool: WorkerPoolManager;
315+
let container: HTMLDivElement;
316+
let viewer: FileDiff<string> | CodeView<string> | undefined;
317+
318+
const loadedDiff = () => {
319+
const parsed = getRenderablePatch(
320+
[
321+
"diff --git a/before.ts b/after.ts",
322+
"similarity index 50%",
323+
"rename from before.ts",
324+
"rename to after.ts",
325+
"--- a/before.ts",
326+
"+++ b/after.ts",
327+
"@@ -1,2 +1,2 @@",
328+
" const shared = 1;",
329+
"-const before = 2;",
330+
"+const after = 3;",
331+
].join("\n"),
332+
"collapsed-content",
333+
);
334+
if (parsed?.kind !== "files" || !parsed.files[0]) throw new Error("Expected diff");
335+
return parsed.files[0];
336+
};
337+
const code = () =>
338+
[...container.querySelectorAll("diffs-container")]
339+
.flatMap((element) => [...(element.shadowRoot?.querySelectorAll("[data-line]") ?? [])])
340+
.map((line) => line.textContent)
341+
.join("\n");
342+
343+
beforeEach(async () => {
344+
testState.requests = [];
345+
testState.failWorkers = false;
346+
testState.holdInitialization = false;
347+
pool = new WorkerPoolManager(
348+
{ workerFactory: () => new DiffsWorker(), poolSize: 1 },
349+
{ theme: "pierre-dark", langs: ["typescript"], preferredHighlighter: "shiki-wasm" },
350+
);
351+
await pool.initialize();
352+
container = document.createElement("div");
353+
container.style.cssText = "height: 400px; width: 800px; overflow: auto";
354+
document.body.append(container);
355+
});
356+
357+
afterEach(() => {
358+
viewer?.cleanUp();
359+
viewer = undefined;
360+
pool.terminate();
361+
container.remove();
362+
vi.restoreAllMocks();
363+
});
364+
365+
it("defers plain AST and highlight work across collapsed renders until expansion", async () => {
366+
const fileDiff = loadedDiff();
367+
const highlight = vi.spyOn(pool, "highlightDiffAST");
368+
const plainAST = vi.spyOn(pool, "getPlainDiffAST");
369+
const options = { theme: "pierre-dark", collapsed: true, disableErrorHandling: true } as const;
370+
const file = new FileDiff<string>(options, pool);
371+
viewer = file;
372+
file.render({ fileDiff, containerWrapper: container });
373+
file.render({ fileDiff, forceRender: true });
374+
expect.soft(highlight.mock.calls.length).toBe(0);
375+
expect.soft(plainAST.mock.calls.length).toBe(0);
376+
expect(code()).toBe("");
377+
expect(container.querySelector("diffs-container")?.shadowRoot?.textContent).toContain(
378+
"after.ts",
379+
);
380+
381+
file.setOptions({ ...options, collapsed: false });
382+
file.render({ fileDiff, forceRender: true });
383+
expect(highlight).toHaveBeenCalled();
384+
await pool.primeDiffHighlightCache(fileDiff);
385+
await vi.waitFor(() => expect(code()).toContain("const after = 3;"));
386+
expect(code()).toContain("const before = 2;");
387+
expect(testState.requests.filter((request) => request.type === "diff")).toHaveLength(1);
388+
});
389+
390+
it("finds newly loaded collapsed lines and unfolds the match with its annotation and header", async () => {
391+
const fileDiff = loadedDiff();
392+
const item: CodeViewItem<string> = {
393+
type: "diff",
394+
id: "renamed",
395+
fileDiff,
396+
collapsed: true,
397+
annotations: [{ side: "additions", lineNumber: 2, metadata: "Review this change" }],
398+
};
399+
const view = new CodeView<string>(
400+
{
401+
theme: "pierre-dark",
402+
disableErrorHandling: true,
403+
onRevealSearchMatch: (match) =>
404+
view.setItems([{ ...match, collapsed: false, version: (match.version ?? 0) + 1 }]),
405+
renderHeaderMetadata: (file) => {
406+
if (!("hunks" in file)) return;
407+
const metadata = document.createElement("span");
408+
const { additions, deletions } = getDiffLineStat([file]);
409+
metadata.textContent = "+" + additions + " / -" + deletions;
410+
return metadata;
411+
},
412+
renderAnnotation: (annotation) => {
413+
const note = document.createElement("span");
414+
note.textContent = annotation.metadata ?? "";
415+
return note;
416+
},
417+
},
418+
pool,
419+
);
420+
viewer = view;
421+
view.setup(container);
422+
view.openSearch();
423+
const search = container.querySelector("[data-diffs-search]")!.shadowRoot!;
424+
const input = search.querySelector<HTMLInputElement>("input[data-search]")!;
425+
input.value = "const after";
426+
input.dispatchEvent(new Event("input", { bubbles: true }));
427+
view.setItems([item]);
428+
view.render(true);
429+
expect(code()).toBe("");
430+
expect(search.textContent).toContain("1 results");
431+
expect(container.textContent).toContain("+1 / -1");
432+
433+
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
434+
view.render(true);
435+
await vi.waitFor(() => expect(code()).toContain("const after = 3;"));
436+
expect(search.textContent).toContain("1 of 1");
437+
expect(container.textContent).toContain("Review this change");
438+
expect(container.textContent).toContain("+1 / -1");
439+
expect(container.querySelector("diffs-container")?.shadowRoot?.textContent).toContain(
440+
"after.ts",
441+
);
442+
443+
await pool.primeDiffHighlightCache(fileDiff);
444+
view.render(true);
445+
const highlight = vi.spyOn(pool, "highlightDiffAST");
446+
const plainAST = vi.spyOn(pool, "getPlainDiffAST");
447+
const updatedDiff = { ...fileDiff, name: "updated.ts", cacheKey: "collapsed-update" };
448+
view.setItems([{ ...item, fileDiff: updatedDiff, version: 2 }]);
449+
view.render(true);
450+
expect(highlight).not.toHaveBeenCalled();
451+
expect(plainAST).not.toHaveBeenCalled();
452+
expect(code()).toBe("");
453+
expect(search.textContent).toContain("1 of 1");
454+
expect(container.querySelector("diffs-container")?.shadowRoot?.textContent).toContain(
455+
"updated.ts",
456+
);
457+
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
458+
view.render(true);
459+
await vi.waitFor(() => expect(code()).toContain("const after = 3;"));
460+
expect(container.textContent).toContain("Review this change");
461+
});
462+
});
463+
308464
type RevealHandle = NonNullable<Parameters<typeof useCodeViewFileReveal>[0]>;
309465
const revealCalls: {
310466
scope: string;

‎apps/web/src/lib/diffRendering.test.ts‎

Lines changed: 0 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import {
66
buildFileDiffIdentityKey,
77
buildFileDiffRenderKey,
88
buildPatchCacheKey,
9-
getCollapsedFileDiffStub,
109
getDiffLineStat,
1110
getRenderablePatch,
1211
resolveFileDiffPath,
@@ -428,81 +427,3 @@ describe("a file whose name a patch header cannot carry plainly", () => {
428427
expect(resolveFileDiffPreviousPath(file)).toBe("old\tname.ts");
429428
});
430429
});
431-
432-
describe("getCollapsedFileDiffStub", () => {
433-
const renamedPatch = [
434-
"diff --git a/old-name.ts b/new-name.ts",
435-
"similarity index 50%",
436-
"rename from old-name.ts",
437-
"rename to new-name.ts",
438-
"--- a/old-name.ts",
439-
"+++ b/new-name.ts",
440-
"@@ -1,2 +1,2 @@",
441-
" const shared = 1;",
442-
"-const before = 2;",
443-
"+const after = 3;",
444-
"diff --git a/other.ts b/other.ts",
445-
"--- a/other.ts",
446-
"+++ b/other.ts",
447-
"@@ -1 +1 @@",
448-
"-old",
449-
"+new",
450-
].join("\n");
451-
452-
const parseFiles = () => {
453-
const parsed = getRenderablePatch(renamedPatch, "collapsed-stub");
454-
if (parsed?.kind !== "files") throw new Error("expected parsed files");
455-
const [renamed, other] = parsed.files;
456-
if (!renamed || !other) throw new Error("expected two files");
457-
return { renamed, other };
458-
};
459-
460-
it("drops the content and keeps the header fields", () => {
461-
const { renamed } = parseFiles();
462-
expect(renamed.hunks.length).toBeGreaterThan(0);
463-
464-
const stub = getCollapsedFileDiffStub(renamed);
465-
466-
expect(stub.hunks).toEqual([]);
467-
expect(stub.additionLines).toEqual([]);
468-
expect(stub.deletionLines).toEqual([]);
469-
expect(stub.splitLineCount).toBe(0);
470-
expect(stub.unifiedLineCount).toBe(0);
471-
expect(stub.name).toBe(renamed.name);
472-
expect(stub.prevName).toBe(renamed.prevName);
473-
expect(stub.prevName).toBe("old-name.ts");
474-
expect(stub.type).toBe(renamed.type);
475-
expect(stub.lang).toBe(renamed.lang);
476-
expect(stub.newObjectId).toBe(renamed.newObjectId);
477-
expect(stub.prevObjectId).toBe(renamed.prevObjectId);
478-
});
479-
480-
it("marks the stub collapsed rather than pending", () => {
481-
const { renamed } = parseFiles();
482-
483-
const stub = getCollapsedFileDiffStub(renamed);
484-
485-
expect(stub.cacheKey).toBe(`${renamed.cacheKey}:collapsed`);
486-
expect(stub.cacheKey?.endsWith(":pending")).toBe(false);
487-
});
488-
489-
it("returns the same stub for the same input and a different one for another", () => {
490-
const { renamed, other } = parseFiles();
491-
492-
const first = getCollapsedFileDiffStub(renamed);
493-
const second = getCollapsedFileDiffStub(renamed);
494-
const otherStub = getCollapsedFileDiffStub(other);
495-
496-
expect(second).toBe(first);
497-
expect(otherStub).not.toBe(first);
498-
expect(otherStub.name).toBe("other.ts");
499-
});
500-
501-
it("keeps the file's identity key", () => {
502-
const { renamed } = parseFiles();
503-
504-
const stub = getCollapsedFileDiffStub(renamed);
505-
506-
expect(buildFileDiffIdentityKey(stub)).toBe(buildFileDiffIdentityKey(renamed));
507-
});
508-
});

‎apps/web/src/lib/diffRendering.ts‎

Lines changed: 0 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -211,30 +211,6 @@ export function resolveFileDiffPreviousPath(fileDiff: FileDiffMetadata): string
211211
return fileDiff.prevName ?? fileDiff.name ?? "";
212212
}
213213

214-
const collapsedFileDiffStubs = new WeakMap<FileDiffMetadata, FileDiffMetadata>();
215-
216-
/**
217-
* Header-only stand-in for a collapsed file, so the viewer gets no content and never highlights
218-
* lines it does not display. The `:collapsed` suffix keeps it apart from a `:pending` placeholder,
219-
* which disables the expand control.
220-
*/
221-
export function getCollapsedFileDiffStub(fileDiff: FileDiffMetadata): FileDiffMetadata {
222-
const cached = collapsedFileDiffStubs.get(fileDiff);
223-
if (cached) return cached;
224-
const stub: FileDiffMetadata = {
225-
...fileDiff,
226-
hunks: [],
227-
additionLines: [],
228-
deletionLines: [],
229-
splitLineCount: 0,
230-
unifiedLineCount: 0,
231-
isPartial: true,
232-
cacheKey: `${fileDiff.cacheKey ?? resolveFileDiffPath(fileDiff)}:collapsed`,
233-
};
234-
collapsedFileDiffStubs.set(fileDiff, stub);
235-
return stub;
236-
}
237-
238214
/**
239215
* A type change (regular file to symlink) arrives as a deletion and an addition
240216
* of the same path, so the change type is part of the identity.

‎patches/@pierre%[email protected]‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -694,6 +694,43 @@ index 0000000..29370ad
694694
+export { CodeViewSearch, collectMatches };
695695
+
696696
+//# sourceMappingURL=CodeViewSearch.js.map
697+
diff --git a/dist/components/FileDiff.js b/dist/components/FileDiff.js
698+
index 6f66bd3..3125fac 100644
699+
--- a/dist/components/FileDiff.js
700+
+++ b/dist/components/FileDiff.js
701+
@@ -1,5 +1,6 @@
702+
-import { CUSTOM_HEADER_SLOT_ID, DEFAULT_THEMES, EMPTY_RENDER_RANGE, HEADER_FILENAME_SUFFIX_SLOT_ID, HEADER_METADATA_SLOT_ID, HEADER_PREFIX_SLOT_ID } from "../constants.js";
703+
+import { CUSTOM_HEADER_SLOT_ID, DEFAULT_THEMES, HEADER_FILENAME_SUFFIX_SLOT_ID, HEADER_METADATA_SLOT_ID, HEADER_PREFIX_SLOT_ID } from "../constants.js";
704+
import { getThemes } from "../utils/getThemes.js";
705+
+import { getHighlighterThemeStyles } from "../utils/getHighlighterThemeStyles.js";
706+
import { getHighlighterIfLoaded, getSharedHighlighter } from "../highlighter/shared_highlighter.js";
707+
import { dequeueRender, queueRender } from "../managers/UniversalRenderingManager.js";
708+
import { areThemesEqual } from "../utils/areThemesEqual.js";
709+
@@ -691,11 +692,20 @@ var FileDiff = class {
710+
this.removeRenderedCode();
711+
this.clearAuxiliaryNodes();
712+
try {
713+
- const hunksResult = this.hunksRenderer.renderDiff(latestDiff, EMPTY_RENDER_RANGE);
714+
- if (hunksResult != null) this.applyThemeState(fileContainer, hunksResult.themeStyles, themeType, hunksResult.baseThemeType);
715+
- if (hunksResult?.headerElement != null) this.applyHeaderToDOM(hunksResult.headerElement, fileContainer, hunksResult.fileDiff);
716+
+ // An empty render range still highlights the full diff. Headers only need the theme.
717+
+ const theme = this.getTheme();
718+
+ const highlighter = getHighlighterIfLoaded({ theme, lang: "text" });
719+
+ if (highlighter != null) this.applyThemeState(fileContainer, getHighlighterThemeStyles({ theme, highlighter }), themeType, typeof theme === "string" ? highlighter.getTheme(theme).type : void 0);
720+
+ else getSharedHighlighter({
721+
+ themes: getThemes(theme),
722+
+ langs: ["text"],
723+
+ preferredHighlighter: this.workerManager?.getPreferredHighlighter() ?? this.options.preferredHighlighter
724+
+ }).then(() => {
725+
+ if (this.enabled && this.fileContainer === fileContainer && this.options.collapsed && areThemesEqual(theme, this.getTheme())) this.rerender();
726+
+ }).catch((error) => console.error(error));
727+
+ if (!disableFileHeader) this.applyHeaderToDOM(this.hunksRenderer.renderHeader(latestDiff), fileContainer, latestDiff);
728+
this.renderSeparators([]);
729+
- this.renderedDiff = hunksResult?.fileDiff ?? latestDiff;
730+
+ this.renderedDiff = latestDiff;
731+
this.injectUnsafeCSS();
732+
} catch (error) {
733+
if (disableErrorHandling) throw error;
697734
diff --git a/dist/components/VirtualizedFile.d.ts b/dist/components/VirtualizedFile.d.ts
698735
index 5e68e35..79dcd88 100644
699736
--- a/dist/components/VirtualizedFile.d.ts
@@ -773,6 +810,28 @@ index d1f57cd..5908ad7 100644
773810
const file = this.getRenderedFile();
774811
if (!this.isSimpleMode()) this.computeApproximateSize(true);
775812
else if (shouldUpdateBuffer && previousRenderRange != null && file != null) {
813+
diff --git a/dist/components/VirtualizedFileDiff.js b/dist/components/VirtualizedFileDiff.js
814+
index 96f970f..1bb59c6 100644
815+
--- a/dist/components/VirtualizedFileDiff.js
816+
+++ b/dist/components/VirtualizedFileDiff.js
817+
@@ -552,7 +552,7 @@ var VirtualizedFileDiff = class extends FileDiff {
818+
rerender() {
819+
if (!this.enabled || this.fileDiff == null && this.additionFile == null && this.deletionFile == null) return;
820+
const latestDiff = this.getLatestDiff();
821+
- const nextRenderDiff = latestDiff == null ? void 0 : this.hunksRenderer.getDiffForNextRender(latestDiff);
822+
+ const nextRenderDiff = latestDiff == null || this.options.collapsed === true ? latestDiff : this.hunksRenderer.getDiffForNextRender(latestDiff);
823+
if (this.isSimpleMode()) this.pendingRender = void 0;
824+
this.forceRenderOverride = true;
825+
this.virtualizer.instanceChanged(this, !areDiffTargetsEqual(this.getRenderedDiff(), nextRenderDiff));
826+
@@ -724,7 +724,7 @@ var VirtualizedFileDiff = class extends FileDiff {
827+
const previousRenderedDiff = this.getRenderedDiff();
828+
const { pendingRender } = this;
829+
const previousLayoutDiff = pendingRender?.diff ?? previousRenderedDiff;
830+
- const pendingRenderDiff = this.hunksRenderer.getDiffForNextRender(latestDiff);
831+
+ const pendingRenderDiff = this.options.collapsed === true ? latestDiff : this.hunksRenderer.getDiffForNextRender(latestDiff);
832+
this.pendingRender = {
833+
latestDiff,
834+
diff: pendingRenderDiff
776835
diff --git a/dist/components/web-components.js b/dist/components/web-components.js
777836
index 6e7b486..5b7290f 100644
778837
--- a/dist/components/web-components.js

0 commit comments

Comments
 (0)