Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -509,11 +509,13 @@ export function DiffPane({
paneId: context.pane.id,
});

const { options, style } = useDiffCardCodeViewTheme();
const { targetItemId, notifyScroll, releaseScroll } = useDiffCodeViewScroll({
codeViewRef,
data,
fileByItemId,
items,
expandUnchanged: options.expandUnchanged ?? false,
collapsedSet,
setCollapsed,
scrollStateKey,
Expand Down Expand Up @@ -588,7 +590,6 @@ export function DiffPane({
},
[scrollStateKey, notifyScroll],
);
const { options, style } = useDiffCardCodeViewTheme();

// A file past the load cap can't expand or enter edit mode. Mark it, and
// leave the edit mode the click may have started.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { afterEach, describe, expect, mock, test } from "bun:test";
import type { CodeViewItem } from "@pierre/diffs";
import {
type CodeViewItem,
type CodeViewScrollTarget,
parsePatchFiles,
} from "@pierre/diffs";
import type { CodeViewHandle } from "@pierre/diffs/react";
import { cleanup, renderHook } from "@testing-library/react";
import type { ChangesetFile } from "../../../../../useChangeset";
Expand All @@ -16,46 +20,144 @@ const file: ChangesetFile = {
source: { kind: "unstaged" },
};
const ITEM_ID = "diff:unstaged:a.ts";
const itemTarget: CodeViewScrollTarget = {
type: "item",
id: ITEM_ID,
align: "start",
behavior: "smooth-auto",
};

describe("useDiffCodeViewScroll", () => {
test("a line target queues its file first, so a line Pierre cannot place still lands on the file", () => {
const scrollTo = mock((_target: unknown) => {});
const codeViewRef = {
current: {
scrollTo,
getInstance: () => ({ getTopForItem: () => 400 }),
} as unknown as CodeViewHandle<DiffAnnotationMetadata, undefined>,
};
renderHook(() =>
type Item = CodeViewItem<DiffAnnotationMetadata>;
type ScrollOptions = Parameters<typeof useDiffCodeViewScroll>[0];

function diffItem(addition = true): Item {
const patch = [
"diff --git a/a.ts b/a.ts",
"--- a/a.ts",
"+++ b/a.ts",
`@@ -1397,7 +1397,${addition ? 7 : 6} @@`,
" context a",
" context b",
" context c",
"-old line",
...(addition ? ["+new line"] : []),
" context d",
" context e",
" context f",
"",
].join("\n");
return {
id: ITEM_ID,
type: "diff",
fileDiff: parsePatchFiles(patch)[0].files[0],
};
}

function renderScroll(items: Item[], options: Partial<ScrollOptions> = {}) {
const scrollTo = mock((_target: CodeViewScrollTarget) => {});
const codeViewRef = {
current: {
scrollTo,
getInstance: () => ({ getTopForItem: () => 400 }),
} as unknown as CodeViewHandle<DiffAnnotationMetadata, undefined>,
};
const hook = renderHook(
({ items }) =>
useDiffCodeViewScroll({
codeViewRef,
data: {
path: "a.ts",
changeKey: "unstaged:a.ts",
collapsedFiles: [],
focusLine: 22,
focusTick: 1,
},
fileByItemId: new Map([[ITEM_ID, file]]),
items: [
{ id: ITEM_ID, type: "diff" },
] as unknown as CodeViewItem<DiffAnnotationMetadata>[],
items,
expandUnchanged: true,
collapsedSet: new Set(),
setCollapsed: () => {},
scrollStateKey: "pane-1",
...options,
}),
);
{ initialProps: { items } },
);
return {
...hook,
targets: () => scrollTo.mock.calls.map(([target]) => target),
};
}

describe("useDiffCodeViewScroll", () => {
test("an explicit line target queues the file first and takes precedence over the first change", () => {
const { targets } = renderScroll([diffItem()], {
data: {
path: "a.ts",
changeKey: "unstaged:a.ts",
collapsedFiles: [],
focusLine: 22,
focusSide: "deletions",
focusTick: 1,
},
});

expect(scrollTo.mock.calls.map(([target]) => target)).toEqual([
{ type: "item", id: ITEM_ID, align: "start", behavior: "smooth-auto" },
expect(targets()).toEqual([
itemTarget,
{
type: "line",
id: ITEM_ID,
lineNumber: 22,
side: undefined,
side: "deletions",
align: "center",
behavior: "smooth-auto",
},
]);
});

test("targets the first changed line when a pending diff loads at the same top", () => {
const pending: Item = {
id: ITEM_ID,
type: "file",
file: { name: file.path, contents: " " },
};
const { rerender, targets } = renderScroll([pending]);
expect(targets()).toEqual([itemTarget]);

const loaded = diffItem();
rerender({ items: [loaded] });
rerender({ items: [loaded] });
expect(targets()).toEqual([
itemTarget,
itemTarget,
{
type: "line",
id: ITEM_ID,
lineNumber: 1400,
side: "additions",
align: "center",
behavior: "smooth-auto",
},
]);
});

test("targets a deleted line in a hunk with no additions", () => {
const { targets } = renderScroll([diffItem(false)]);

expect(targets()).toEqual([
itemTarget,
{
type: "line",
id: ITEM_ID,
lineNumber: 1400,
side: "deletions",
align: "center",
behavior: "smooth-auto",
},
]);
});

test("keeps the file header as the target when unchanged lines are folded", () => {
const { targets } = renderScroll([diffItem()], { expandUnchanged: false });

expect(targets()).toEqual([itemTarget]);
});
});
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import type { CodeViewItem, CodeViewScrollTarget } from "@pierre/diffs";
import type {
CodeViewItem,
CodeViewLineScrollTarget,
CodeViewScrollTarget,
FileDiffMetadata,
} from "@pierre/diffs";
import type { CodeViewHandle } from "@pierre/diffs/react";
import { type RefObject, useCallback, useEffect, useMemo, useRef } from "react";
import type { DiffPaneData } from "../../../../../../types";
Expand All @@ -21,6 +26,7 @@ interface UseDiffCodeViewScrollOptions {
data: DiffPaneData;
fileByItemId: ReadonlyMap<string, ChangesetFile>;
items: CodeViewItem<DiffAnnotationMetadata>[];
expandUnchanged: boolean;
collapsedSet: ReadonlySet<string>;
setCollapsed: (path: string, value: boolean) => void;
scrollStateKey: string;
Expand All @@ -46,11 +52,34 @@ interface UseDiffCodeViewScrollResult {
// scrollbar.
const PROGRAMMATIC_SCROLL_SETTLE_MS = 700;

function getFirstChangedLine(
fileDiff: FileDiffMetadata,
): Pick<CodeViewLineScrollTarget, "lineNumber" | "side"> | undefined {
const hunk = fileDiff.hunks[0];
if (!hunk) return undefined;
const change = hunk.hunkContent.find((block) => block.type === "change");
if (!change) return undefined;
if (change.additions > 0) {
return {
lineNumber:
hunk.additionStart +
(change.additionLineIndex - hunk.additionLineIndex),
side: "additions",
};
}
return {
lineNumber:
hunk.deletionStart + (change.deletionLineIndex - hunk.deletionLineIndex),
side: "deletions",
};
}

export function useDiffCodeViewScroll({
codeViewRef,
data,
fileByItemId,
items,
expandUnchanged,
collapsedSet,
setCollapsed,
scrollStateKey,
Expand Down Expand Up @@ -121,31 +150,35 @@ export function useDiffCodeViewScroll({

if (!targetItemId) return;
const file = fileByItemId.get(targetItemId);
if (!file) return;
if (!itemById.has(targetItemId)) return;
const targetItem = itemById.get(targetItemId);
if (!file || !targetItem) return;
const changeKey = getChangesetFileKey(file);
if (collapsedSet.has(changeKey)) {
setCollapsed(changeKey, false);
return;
}

const targetItem = itemById.get(targetItemId);
const target: CodeViewScrollTarget =
data.focusLine != null && targetItem?.type === "diff"
? {
type: "line",
id: targetItemId,
lineNumber: data.focusLine,
side: data.focusSide,
align: "center",
behavior: "smooth-auto",
}
: {
type: "item",
id: targetItemId,
align: "start",
behavior: "smooth-auto",
};
let line: Pick<CodeViewLineScrollTarget, "lineNumber" | "side"> | undefined;
if (targetItem.type === "diff") {
if (data.focusLine != null) {
line = { lineNumber: data.focusLine, side: data.focusSide };
} else if (expandUnchanged) {
line = getFirstChangedLine(targetItem.fileDiff);
}
}
const fileTarget = {
type: "item",
id: targetItemId,
align: "start",
behavior: "smooth-auto",
} as const;
const target: CodeViewScrollTarget = line
? { ...fileTarget, type: "line", ...line, align: "center" }
: fileTarget;
// A placeholder can gain a line target without changing the item top.
const assertedScrollKey = line
? `${scrollKey}:${line.side ?? ""}:${line.lineNumber}`
: scrollKey;

// Re-assert only when the target actually moved under us (or this is a
// new request). CodeView suspends pointer events on its pinned header
Expand All @@ -155,27 +188,27 @@ export function useDiffCodeViewScroll({
const targetTop = codeViewRef.current
?.getInstance()
?.getTopForItem(targetItemId);
if (!shouldReassertScroll(lastAssertedRef.current, scrollKey, targetTop))
if (
!shouldReassertScroll(
lastAssertedRef.current,
assertedScrollKey,
targetTop,
)
)
return;

// Pierre drops a line it cannot place (an outdated comment's line, or
// one in folded context); the file scroll queued first then stands.
if (target.type === "line") {
codeViewRef.current?.scrollTo({
type: "item",
id: targetItemId,
align: "start",
behavior: "smooth-auto",
});
}
if (line) codeViewRef.current?.scrollTo(fileTarget);
codeViewRef.current?.scrollTo(target);
lastAssertedRef.current = { scrollKey, targetTop };
lastAssertedRef.current = { scrollKey: assertedScrollKey, targetTop };
lastProgrammaticScrollAtRef.current = Date.now();
}, [
codeViewRef,
data.focusLine,
data.focusSide,
data.focusTick,
expandUnchanged,
initialScrollState,
items,
scrollStateKey,
Expand Down
Loading