diff --git a/packages/app/e2e/browser/changes-pane.spec.ts b/packages/app/e2e/browser/changes-pane.spec.ts index 3ce36b15e..79ae55092 100644 --- a/packages/app/e2e/browser/changes-pane.spec.ts +++ b/packages/app/e2e/browser/changes-pane.spec.ts @@ -1598,6 +1598,237 @@ test("canvas diff replaces a selection with forward and backward drags", async ( } }); +test("canvas diff double-click selects the grapheme under the pointer, not the nearest caret", async ({ + context, + page, +}) => { + const content = "call(foo bar)"; + const workspace = await createWorkspaceWithExactSelectionDiff(content); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await useUnwrappedDiffLines(page); + await openSelectionWorkspaceChanges(page, workspace); + + await dragAddedTextRange(page, { + lines: [content], + clickCount: 2, + fraction: 0.75, + start: { line: 0, offset: 3 }, + end: { line: 0, offset: 3 }, + }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, "call"); + + await dragAddedTextRange(page, { + lines: [content], + clickCount: 2, + fraction: 0.1, + start: { line: 0, offset: 4 }, + end: { line: 0, offset: 4 }, + }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, "("); +}); + +test("canvas diff double-click selects the clicked word and replaces an existing selection", async ({ + context, + page, +}) => { + const content = "alpha bravo charlie delta"; + const workspace = await createWorkspaceWithExactSelectionDiff(content); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await useUnwrappedDiffLines(page); + await openSelectionWorkspaceChanges(page, workspace); + + await dragAddedTextRange(page, { + lines: [content], + start: { line: 0, offset: 0 }, + end: { line: 0, offset: 4 }, + }); + await dragAddedTextRange(page, { + lines: [content], + clickCount: 2, + start: { line: 0, offset: 8 }, + end: { line: 0, offset: 8 }, + }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, "bravo"); +}); + +test("canvas diff double-click drag extends the selection word by word in both directions", async ({ + context, + page, +}) => { + const content = "alpha bravo charlie delta"; + const workspace = await createWorkspaceWithExactSelectionDiff(content); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await useUnwrappedDiffLines(page); + await openSelectionWorkspaceChanges(page, workspace); + + for (const [start, end, expectedText] of [ + [{ line: 0, offset: 8 }, { line: 0, offset: 14 }, "bravo charlie"], + [{ line: 0, offset: 14 }, { line: 0, offset: 2 }, "alpha bravo charlie"], + ] as const) { + await dragAddedTextRange(page, { lines: [content], clickCount: 2, start, end }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, expectedText); + } +}); + +test("canvas diff double-click drag extends word by word across lines and wrapped lines", async ({ + context, + page, +}) => { + const lines = ["alpha bravo", "charlie delta"]; + const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n")); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await useUnwrappedDiffLines(page); + await openSelectionWorkspaceChanges(page, workspace); + + for (const [start, end, expectedText] of [ + [{ line: 0, offset: 8 }, { line: 1, offset: 10 }, "bravo\ncharlie delta"], + [{ line: 1, offset: 10 }, { line: 0, offset: 2 }, "alpha bravo\ncharlie delta"], + ] as const) { + await dragAddedTextRange(page, { lines, clickCount: 2, start, end }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, expectedText); + } + + const wrapped = `${"alpha ".repeat(40)}bravo charlie`; + const wrappedWorkspace = await createWorkspaceWithExactSelectionDiff(wrapped); + await configureDiffPresentation(page, { layout: "unified", wrapLines: true }); + await openSelectionWorkspaceChanges(page, wrappedWorkspace); + await setOpenChangesPresentation(page, { layout: "unified", wrapLines: true }); + const bravoStart = 40 * "alpha ".length; + await dragAddedTextRange(page, { + lines: [wrapped], + wrapped: true, + clickCount: 2, + start: { line: 0, offset: bravoStart + 2 }, + end: { line: 0, offset: bravoStart + 9 }, + }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, "bravo charlie"); +}); + +test("canvas diff double-click drag keeps word selection on the split side", async ({ + context, + page, +}) => { + const lines = ["RIGHT-ONE", "RIGHT-TWO"]; + const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n")); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await configureDiffPresentation(page, { layout: "split", wrapLines: false }); + await openSelectionWorkspaceChanges(page, workspace); + await setOpenChangesPresentation(page, { layout: "split", wrapLines: false }); + + await dragAddedTextRange(page, { + lines, + side: "right", + clickCount: 2, + start: { line: 0, offset: 7 }, + end: { line: 1, offset: 3 }, + }); + await page.keyboard.press("ControlOrMeta+C"); + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("ONE\nRIGHT"); +}); + +test("canvas diff triple-click selects the whole source line and replaces an existing selection", async ({ + context, + page, +}) => { + const content = "alpha bravo"; + const workspace = await createWorkspaceWithExactSelectionDiff(content); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await useUnwrappedDiffLines(page); + await openSelectionWorkspaceChanges(page, workspace); + + await dragAddedTextRange(page, { + lines: [content], + start: { line: 0, offset: 0 }, + end: { line: 0, offset: 3 }, + }); + await dragAddedTextRange(page, { + lines: [content], + clickCount: 3, + start: { line: 0, offset: 8 }, + end: { line: 0, offset: 8 }, + }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, content); +}); + +test("canvas diff triple-click drag extends whole source lines in both directions", async ({ + context, + page, +}) => { + const lines = ["alpha", "bravo", "charlie"]; + const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n")); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await useUnwrappedDiffLines(page); + await openSelectionWorkspaceChanges(page, workspace); + + for (const [start, end] of [ + [ + { line: 0, offset: 2 }, + { line: 2, offset: 3 }, + ], + [ + { line: 2, offset: 3 }, + { line: 0, offset: 1 }, + ], + ] as const) { + await dragAddedTextRange(page, { lines, clickCount: 3, start, end }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, "alpha\nbravo\ncharlie"); + } +}); + +test("canvas diff triple-click selects every wrapped fragment of a source line", async ({ + context, + page, +}) => { + const content = `${"alpha ".repeat(80)}omega`; + const workspace = await createWorkspaceWithExactSelectionDiff(content); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await configureDiffPresentation(page, { layout: "unified", wrapLines: true }); + await openSelectionWorkspaceChanges(page, workspace); + await setOpenChangesPresentation(page, { layout: "unified", wrapLines: true }); + + await dragAddedTextRange(page, { + lines: [content], + wrapped: true, + clickCount: 3, + start: { line: 0, offset: 20 }, + end: { line: 0, offset: 20 }, + }); + await copyDiffSelectionWithKeyboard(page); + await expectClipboardText(page, content); +}); + +test("canvas diff triple-click drag keeps whole source lines on the split side", async ({ + context, + page, +}) => { + const lines = ["RIGHT-ONE", "RIGHT-TWO"]; + const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n")); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await configureDiffPresentation(page, { layout: "split", wrapLines: false }); + await openSelectionWorkspaceChanges(page, workspace); + await setOpenChangesPresentation(page, { layout: "split", wrapLines: false }); + + await dragAddedTextRange(page, { + lines, + side: "right", + clickCount: 3, + start: { line: 1, offset: 3 }, + end: { line: 0, offset: 4 }, + }); + await page.keyboard.press("ControlOrMeta+C"); + await expect + .poll(() => page.evaluate(() => navigator.clipboard.readText())) + .toBe("RIGHT-ONE\nRIGHT-TWO"); +}); + test("canvas diff copies only the selected split side", async ({ context, page }) => { const lines = ["RIGHT-ONE", "RIGHT-TWO"]; const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n")); @@ -2482,6 +2713,8 @@ async function dragAddedTextRange( side?: "left" | "right"; wrapped?: boolean; horizontalOffset?: number; + clickCount?: 1 | 2 | 3; + fraction?: number; }, ): Promise { const body = page.getByTestId("diff-file-0-body"); @@ -2520,14 +2753,38 @@ async function dragAddedTextRange( columnLeft + gutterWidth + 8 + - localOffset * metrics.characterWidth - + (localOffset + (input.fraction ?? 0)) * metrics.characterWidth - (input.horizontalOffset ?? 0), y: bounds.y + (1 + fragmentsBefore(line) + fragment + 0.5) * lineHeight, }; }; const start = point(input.start); const end = point(input.end); + const clickCount = input.clickCount ?? 1; await page.mouse.move(start.x, start.y); + if (clickCount > 1) { + const isSinglePoint = + input.start.line === input.end.line && input.start.offset === input.end.offset; + if (isSinglePoint && clickCount === 2) { + await page.mouse.dblclick(start.x, start.y); + return; + } + if (isSinglePoint) { + for (let count = 1; count <= clickCount; count += 1) { + await page.mouse.down({ clickCount: count }); + await page.mouse.up({ clickCount: count }); + } + return; + } + for (let count = 1; count < clickCount; count += 1) { + await page.mouse.down({ clickCount: count }); + await page.mouse.up({ clickCount: count }); + } + await page.mouse.down({ clickCount }); + await page.mouse.move(end.x, end.y, { steps: 12 }); + await page.mouse.up({ clickCount }); + return; + } await page.mouse.down(); await page.mouse.move(end.x, end.y, { steps: 12 }); await page.mouse.up(); diff --git a/packages/app/src/git/diff-document/hit-testing.test.ts b/packages/app/src/git/diff-document/hit-testing.test.ts index d728c2f2d..a1a59ad3f 100644 --- a/packages/app/src/git/diff-document/hit-testing.test.ts +++ b/packages/app/src/git/diff-document/hit-testing.test.ts @@ -2,6 +2,7 @@ import type { ParsedDiffFile } from "@getpaseo/protocol/messages"; import { describe, expect, it } from "vitest"; import { characterOffsetAtPoint, + graphemeOffsetAtPoint, hitTestDiffDocument, orderedSelection, selectAllSource, @@ -43,6 +44,49 @@ describe("diff hit testing", () => { ).toBe(combining?.end); }); + it("keeps the nearest caret for character drags but hits the grapheme under word gestures", () => { + const cell = changedCell(buildModel("call(foo)", { wrapLines: false, viewportWidth: 300 })); + const graphemes = cell.fragments[0]!.graphemes; + const lastOfWord = graphemes[3]!; + const punctuation = graphemes[4]!; + const beforeLastOfWord = graphemes + .slice(0, 3) + .reduce((width, grapheme) => width + grapheme.width, 0); + const rightHalfOfWord = beforeLastOfWord + lastOfWord.width * 0.75; + const leftHalfOfPunctuation = beforeLastOfWord + lastOfWord.width + punctuation.width * 0.1; + + expect(characterOffsetAtPoint({ cell, x: rightHalfOfWord, y: 0, lineHeight: 18 })).toBe( + punctuation.start, + ); + expect(graphemeOffsetAtPoint({ cell, x: rightHalfOfWord, y: 0, lineHeight: 18 })).toBe( + lastOfWord.start, + ); + expect(characterOffsetAtPoint({ cell, x: leftHalfOfPunctuation, y: 0, lineHeight: 18 })).toBe( + punctuation.start, + ); + expect(graphemeOffsetAtPoint({ cell, x: leftHalfOfPunctuation, y: 0, lineHeight: 18 })).toBe( + punctuation.start, + ); + }); + + it("keeps wrapped fragment boundaries from stealing the grapheme under the pointer", () => { + const cell = changedCell(buildModel("abcdef", { viewportWidth: 90 })); + const firstFragment = cell.fragments[0]!; + expect(cell.fragments.length).toBeGreaterThan(1); + const lastGrapheme = firstFragment.graphemes.at(-1)!; + const beforeLastGrapheme = firstFragment.graphemes + .slice(0, -1) + .reduce((width, grapheme) => width + grapheme.width, 0); + const rightHalfOfLastGrapheme = beforeLastGrapheme + lastGrapheme.width * 0.75; + + expect(characterOffsetAtPoint({ cell, x: rightHalfOfLastGrapheme, y: 0, lineHeight: 18 })).toBe( + firstFragment.end, + ); + expect(graphemeOffsetAtPoint({ cell, x: rightHalfOfLastGrapheme, y: 0, lineHeight: 18 })).toBe( + lastGrapheme.start, + ); + }); + it("normalizes backwards selection and copies exact source including empty lines", () => { const model = buildModel("", { wrapLines: false }); const cell = changedCell(model); diff --git a/packages/app/src/git/diff-document/hit-testing.ts b/packages/app/src/git/diff-document/hit-testing.ts index ed0519e28..1dba723f6 100644 --- a/packages/app/src/git/diff-document/hit-testing.ts +++ b/packages/app/src/git/diff-document/hit-testing.ts @@ -3,6 +3,7 @@ import type { DiffCell, DiffCharacterPosition, DiffDocumentModel, + DiffFragment, DiffHit, DiffSelection, } from "./types"; @@ -33,12 +34,7 @@ export function hitTestDiffDocument(input: { localX - file.gutterWidth - CODE_LEFT_PADDING + input.horizontalOffset, ); const textY = input.documentY - row.top; - const sourceOffset = characterOffsetAtPoint({ - cell, - x: contentX, - y: textY, - lineHeight: input.model.lineHeight, - }); + const point = { cell, x: contentX, y: textY, lineHeight: input.model.lineHeight }; return { kind: "cell", target: cell.reviewTarget, @@ -47,8 +43,9 @@ export function hitTestDiffDocument(input: { rowIndex: row.index, cellIndex, side: cell.reviewTarget?.side ?? (cellIndex === 0 ? "old" : "new"), - sourceOffset, + sourceOffset: characterOffsetAtPoint(point), }, + graphemeOffset: graphemeOffsetAtPoint(point), }; } @@ -58,11 +55,7 @@ export function characterOffsetAtPoint(input: { y: number; lineHeight: number; }): number { - const fragmentIndex = Math.min( - input.cell.fragments.length - 1, - Math.max(0, Math.floor(input.y / input.lineHeight)), - ); - const fragment = input.cell.fragments[fragmentIndex]; + const fragment = fragmentAtPoint(input); if (!fragment) return 0; let width = 0; for (const grapheme of fragment.graphemes) { @@ -72,6 +65,36 @@ export function characterOffsetAtPoint(input: { return fragment.end; } +/** The grapheme under the pointer, unlike `characterOffsetAtPoint`, which snaps to the nearest caret. */ +export function graphemeOffsetAtPoint(input: { + cell: DiffCell; + x: number; + y: number; + lineHeight: number; +}): number { + const fragment = fragmentAtPoint(input); + if (!fragment) return 0; + let width = 0; + for (const grapheme of fragment.graphemes) { + if (input.x < width + grapheme.width) return grapheme.start; + width += grapheme.width; + } + const lastGrapheme = fragment.graphemes.at(-1); + return lastGrapheme ? lastGrapheme.start : fragment.start; +} + +function fragmentAtPoint(input: { + cell: DiffCell; + y: number; + lineHeight: number; +}): DiffFragment | null { + const fragmentIndex = Math.min( + input.cell.fragments.length - 1, + Math.max(0, Math.floor(input.y / input.lineHeight)), + ); + return input.cell.fragments[fragmentIndex] ?? null; +} + function rowAtOffset( rows: readonly DiffDocumentModel["rows"][number][], start: number, @@ -163,7 +186,7 @@ export function selectAllSource( return first && last ? { anchor: first, focus: last } : null; } -function comparePosition(left: DiffCharacterPosition, right: DiffCharacterPosition): number { +export function comparePosition(left: DiffCharacterPosition, right: DiffCharacterPosition): number { return ( left.rowIndex - right.rowIndex || left.cellIndex - right.cellIndex || diff --git a/packages/app/src/git/diff-document/pointer-gesture.test.ts b/packages/app/src/git/diff-document/pointer-gesture.test.ts index 498712939..4577dd8dd 100644 --- a/packages/app/src/git/diff-document/pointer-gesture.test.ts +++ b/packages/app/src/git/diff-document/pointer-gesture.test.ts @@ -1,5 +1,38 @@ import { describe, expect, it } from "vitest"; -import { hasPointerDragStarted } from "./pointer-gesture"; +import { + hasPointerDragStarted, + lineSelectionForDrag, + wordSelectionForDrag, + type LineAtPosition, + type WordAtPosition, +} from "./pointer-gesture"; +import type { DiffCharacterPosition } from "./types"; + +function positionAt(offset: number, rowIndex = 1, cellIndex = 0): DiffCharacterPosition { + return { fileIndex: 0, rowIndex, cellIndex, side: "new", sourceOffset: offset }; +} + +function wordAt( + input: { offset: number; start: number; end: number }, + rowIndex = 1, + cellIndex = 0, +): WordAtPosition { + return { + position: positionAt(input.offset, rowIndex, cellIndex), + word: { start: input.start, end: input.end }, + }; +} + +function lineAt( + input: { offset: number; end: number }, + rowIndex = 1, + cellIndex = 0, +): LineAtPosition { + return { + position: positionAt(input.offset, rowIndex, cellIndex), + end: input.end, + }; +} describe("diff pointer gesture", () => { it("classifies pointer movement as a drag without requiring a character change", () => { @@ -26,3 +59,99 @@ describe("diff pointer gesture", () => { ).toBe(true); }); }); + +describe("diff word drag selection", () => { + it("extends forward from the start of the anchor word to the end of the focus word", () => { + expect( + wordSelectionForDrag({ + anchor: wordAt({ offset: 8, start: 6, end: 11 }), + focus: wordAt({ offset: 14, start: 12, end: 19 }), + }), + ).toEqual({ + anchor: positionAt(6), + focus: positionAt(19), + }); + }); + + it("extends backward from the end of the anchor word to the start of the focus word", () => { + expect( + wordSelectionForDrag({ + anchor: wordAt({ offset: 15, start: 13, end: 20 }), + focus: wordAt({ offset: 7, start: 6, end: 11 }), + }), + ).toEqual({ + anchor: positionAt(6), + focus: positionAt(20), + }); + }); + + it("keeps the anchor word whole while the pointer stays inside it", () => { + const anchor = wordAt({ offset: 10, start: 6, end: 11 }); + const expected = { anchor: positionAt(6), focus: positionAt(11) }; + expect( + wordSelectionForDrag({ anchor, focus: wordAt({ offset: 7, start: 6, end: 11 }) }), + ).toEqual(expected); + expect( + wordSelectionForDrag({ anchor, focus: wordAt({ offset: 9, start: 6, end: 11 }) }), + ).toEqual(expected); + }); + + it("snaps both ends to word boundaries across rows", () => { + expect( + wordSelectionForDrag({ + anchor: wordAt({ offset: 3, start: 2, end: 5 }, 1), + focus: wordAt({ offset: 2, start: 0, end: 4 }, 3), + }), + ).toEqual({ + anchor: positionAt(2, 1), + focus: positionAt(4, 3), + }); + expect( + wordSelectionForDrag({ + anchor: wordAt({ offset: 2, start: 0, end: 4 }, 3), + focus: wordAt({ offset: 3, start: 2, end: 5 }, 1), + }), + ).toEqual({ + anchor: positionAt(2, 1), + focus: positionAt(4, 3), + }); + }); +}); + +describe("diff line drag selection", () => { + it("selects the whole clicked source line", () => { + expect( + lineSelectionForDrag({ + anchor: lineAt({ offset: 3, end: 12 }), + focus: lineAt({ offset: 3, end: 12 }), + }), + ).toEqual({ + anchor: positionAt(0), + focus: positionAt(12), + }); + }); + + it("extends forward to the end of the focus line while keeping the anchor line", () => { + expect( + lineSelectionForDrag({ + anchor: lineAt({ offset: 3, end: 12 }), + focus: lineAt({ offset: 1, end: 7 }, 3), + }), + ).toEqual({ + anchor: positionAt(0), + focus: positionAt(7, 3), + }); + }); + + it("extends backward from the start of the focus line to the end of the anchor line", () => { + expect( + lineSelectionForDrag({ + anchor: lineAt({ offset: 5, end: 9 }, 3), + focus: lineAt({ offset: 2, end: 12 }, 1), + }), + ).toEqual({ + anchor: positionAt(0, 1), + focus: positionAt(9, 3), + }); + }); +}); diff --git a/packages/app/src/git/diff-document/pointer-gesture.ts b/packages/app/src/git/diff-document/pointer-gesture.ts index e5da48aa0..e0928398b 100644 --- a/packages/app/src/git/diff-document/pointer-gesture.ts +++ b/packages/app/src/git/diff-document/pointer-gesture.ts @@ -1,5 +1,46 @@ +import { comparePosition } from "./hit-testing"; +import type { DiffCharacterPosition, DiffSelection } from "./types"; +import type { SourceWordRange } from "./word-boundaries"; + const DRAG_THRESHOLD = 4; +export interface WordAtPosition { + position: DiffCharacterPosition; + word: SourceWordRange; +} + +export interface LineAtPosition { + position: DiffCharacterPosition; + /** UTF-16 length of the canonical source line. */ + end: number; +} + +export function wordSelectionForDrag(input: { + anchor: WordAtPosition; + focus: WordAtPosition; +}): DiffSelection { + const isBackward = comparePosition(input.focus.position, input.anchor.position) < 0; + const start = isBackward ? input.focus : input.anchor; + const end = isBackward ? input.anchor : input.focus; + return { + anchor: { ...start.position, sourceOffset: start.word.start }, + focus: { ...end.position, sourceOffset: end.word.end }, + }; +} + +export function lineSelectionForDrag(input: { + anchor: LineAtPosition; + focus: LineAtPosition; +}): DiffSelection { + const isBackward = comparePosition(input.focus.position, input.anchor.position) < 0; + const start = isBackward ? input.focus : input.anchor; + const end = isBackward ? input.anchor : input.focus; + return { + anchor: { ...start.position, sourceOffset: 0 }, + focus: { ...end.position, sourceOffset: end.end }, + }; +} + export function hasPointerDragStarted(input: { startX: number; startY: number; diff --git a/packages/app/src/git/diff-document/surface.web.tsx b/packages/app/src/git/diff-document/surface.web.tsx index 393f6dfcd..e4247636b 100644 --- a/packages/app/src/git/diff-document/surface.web.tsx +++ b/packages/app/src/git/diff-document/surface.web.tsx @@ -35,7 +35,13 @@ import { resolveRelayoutScrollTop, } from "./model"; import { paintWebFileHeader, paintWebViewport } from "./paint.web"; -import { hasPointerDragStarted } from "./pointer-gesture"; +import { + hasPointerDragStarted, + lineSelectionForDrag, + wordSelectionForDrag, + type LineAtPosition, + type WordAtPosition, +} from "./pointer-gesture"; import { createMeasuredAdvances, createAdditiveAdvances, @@ -44,6 +50,8 @@ import { } from "./text-measurement"; import { retainDiffViewport } from "./viewport"; import type { + DiffCell, + DiffCharacterPosition, DiffHit, DiffFileSection, DiffSelection, @@ -51,6 +59,7 @@ import type { DiffTypography, TextMeasurer, } from "./types"; +import { wordRangeAtOffset } from "./word-boundaries"; import { useDiffDocumentWorkspaceCache } from "./workspace-cache"; const DEFAULT_MONO_STACK = "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"; @@ -104,6 +113,11 @@ export function DiffSurface(props: DiffSurfaceProps) { startY: number; moved: boolean; dismissSelectionOnClick: boolean; + granularity: + | { kind: "character" } + | { kind: "word"; anchor: WordAtPosition } + | { kind: "line"; anchor: LineAtPosition }; + pointerType: string; } | null>(null); const frameRef = useRef(null); const activeHeaderPathRef = useRef(null); @@ -591,6 +605,31 @@ export function DiffSurface(props: DiffSurfaceProps) { desiredTypography, setSelection, ]); + const cellAt = useCallback((position: DiffCharacterPosition): DiffCell | null => { + const currentModel = modelRef.current; + if (!currentModel) return null; + const row = currentModel.rows[position.rowIndex]; + return row?.kind === "line" ? row.cells[position.cellIndex] : null; + }, []); + const wordAt = useCallback( + (hit: Extract): WordAtPosition | null => { + const cell = cellAt(hit.position); + if (!cell) return null; + return { + position: { ...hit.position, sourceOffset: hit.graphemeOffset }, + word: wordRangeAtOffset(cell.content, hit.graphemeOffset), + }; + }, + [cellAt], + ); + const lineAt = useCallback( + (hit: Extract): LineAtPosition | null => { + const cell = cellAt(hit.position); + if (!cell) return null; + return { position: hit.position, end: cell.content.length }; + }, + [cellAt], + ); const pointerDown = useCallback( (event: React.PointerEvent) => { if (event.button !== 0) return; @@ -602,18 +641,18 @@ export function DiffSurface(props: DiffSurfaceProps) { ) ) return; - const dismissSelectionOnClick = selectionRef.current !== null; - if (dismissSelectionOnClick) { - setSelection(null); - } const hit = pointHit(event); + const hadSelection = selectionRef.current !== null; + if (hadSelection) setSelection(null); if (hit?.kind !== "cell") return; dragRef.current = { anchor: hit.position, startX: event.clientX, startY: event.clientY, moved: false, - dismissSelectionOnClick, + dismissSelectionOnClick: hadSelection, + granularity: { kind: "character" }, + pointerType: event.pointerType, }; setSelection({ anchor: hit.position, focus: hit.position }); event.currentTarget.focus(); @@ -621,6 +660,38 @@ export function DiffSurface(props: DiffSurfaceProps) { }, [pointHit, setSelection], ); + // The native click count honors the OS double-click setting and arrives on the + // second mousedown, after pointerdown has opened the character drag. + const mouseDown = useCallback( + (event: React.MouseEvent) => { + const drag = dragRef.current; + if (!drag || event.button !== 0 || event.detail < 2 || drag.pointerType === "touch") return; + const target = event.target; + if ( + target instanceof Element && + target.closest( + '[data-diff-header="true"], [data-diff-review="true"], [role="menuitem"], button, input, textarea', + ) + ) + return; + const hit = pointHitAt(event.clientX, event.clientY); + if (hit?.kind !== "cell") return; + if (event.detail >= 3) { + const lineAnchor = lineAt(hit); + if (!lineAnchor) return; + drag.granularity = { kind: "line", anchor: lineAnchor }; + drag.dismissSelectionOnClick = false; + setSelection(lineSelectionForDrag({ anchor: lineAnchor, focus: lineAnchor })); + return; + } + const wordAnchor = wordAt(hit); + if (!wordAnchor) return; + drag.granularity = { kind: "word", anchor: wordAnchor }; + drag.dismissSelectionOnClick = false; + setSelection(wordSelectionForDrag({ anchor: wordAnchor, focus: wordAnchor })); + }, + [lineAt, pointHitAt, setSelection, wordAt], + ); const updateActiveHeader = useCallback( (target: EventTarget | null) => { const header = @@ -634,6 +705,32 @@ export function DiffSurface(props: DiffSurfaceProps) { }, [paintStickyHeaderPool, schedulePaint], ); + const updateHoveredAffordance = useCallback( + (hit: Extract, clientX: number) => { + const row = modelRef.current?.rows[hit.position.rowIndex]; + const file = modelRef.current?.files[hit.position.fileIndex]; + const sideIndex = + row?.kind === "line" && row.cells.length === 2 && hit.position.side === "new" ? 1 : 0; + if (row && file) { + const columnWidth = viewport.width / (row.kind === "line" ? row.cells.length : 1); + const gutterBorder = sideIndex * columnWidth + file.gutterWidth; + const rootBounds = rootRef.current?.getBoundingClientRect(); + const pointerX = rootBounds ? clientX - rootBounds.left : Number.NaN; + if (hit.target && Number.isFinite(pointerX)) { + hasHoveredAffordanceRef.current = true; + setHoveredAffordance({ + hit, + left: gutterBorder - 12, + top: row.top - scrollTopRef.current + (modelRef.current!.lineHeight - 22) / 2, + }); + return; + } + } + hasHoveredAffordanceRef.current = false; + setHoveredAffordance(null); + }, + [viewport.width], + ); const pointerMove = useCallback( (event: React.PointerEvent) => { updateActiveHeader(event.target); @@ -649,35 +746,29 @@ export function DiffSurface(props: DiffSurfaceProps) { } const hit = pointHit(event); if (hit?.kind === "cell") { - const row = modelRef.current?.rows[hit.position.rowIndex]; - const file = modelRef.current?.files[hit.position.fileIndex]; - const sideIndex = - row?.kind === "line" && row.cells.length === 2 && hit.position.side === "new" ? 1 : 0; - if (row && file) { - const columnWidth = viewport.width / (row.kind === "line" ? row.cells.length : 1); - const gutterBorder = sideIndex * columnWidth + file.gutterWidth; - const rootBounds = rootRef.current?.getBoundingClientRect(); - const pointerX = rootBounds ? event.clientX - rootBounds.left : Number.NaN; - if (hit.target && Number.isFinite(pointerX)) { - hasHoveredAffordanceRef.current = true; - setHoveredAffordance({ - hit, - left: gutterBorder - 12, - top: row.top - scrollTopRef.current + (modelRef.current!.lineHeight - 22) / 2, - }); - } else { - hasHoveredAffordanceRef.current = false; - setHoveredAffordance(null); - } - } + updateHoveredAffordance(hit, event.clientX); } else { hasHoveredAffordanceRef.current = false; setHoveredAffordance(null); } if (!drag || hit?.kind !== "cell") return; + if (drag.granularity.kind === "word") { + const focusWord = wordAt(hit); + if (focusWord) { + setSelection(wordSelectionForDrag({ anchor: drag.granularity.anchor, focus: focusWord })); + } + return; + } + if (drag.granularity.kind === "line") { + const focusLine = lineAt(hit); + if (focusLine) { + setSelection(lineSelectionForDrag({ anchor: drag.granularity.anchor, focus: focusLine })); + } + return; + } setSelection({ anchor: drag.anchor, focus: hit.position }); }, - [pointHit, setSelection, updateActiveHeader, viewport.width], + [lineAt, pointHit, setSelection, updateActiveHeader, updateHoveredAffordance, wordAt], ); const pointerUp = useCallback( (event: React.PointerEvent) => { @@ -822,6 +913,7 @@ export function DiffSurface(props: DiffSurfaceProps) { data-overlay-scrollbar="true" tabIndex={0} onPointerDown={pointerDown} + onMouseDown={mouseDown} onPointerMove={pointerMove} onPointerUp={pointerUp} onPointerCancel={cancelPointer} diff --git a/packages/app/src/git/diff-document/types.ts b/packages/app/src/git/diff-document/types.ts index d98880eb8..3024fda83 100644 --- a/packages/app/src/git/diff-document/types.ts +++ b/packages/app/src/git/diff-document/types.ts @@ -208,6 +208,8 @@ export type DiffHit = kind: "cell"; target: ReviewableDiffTarget | null; position: DiffCharacterPosition; + /** The grapheme under the pointer, which word gestures select from. */ + graphemeOffset: number; }; export interface DiffSelection { diff --git a/packages/app/src/git/diff-document/word-boundaries.test.ts b/packages/app/src/git/diff-document/word-boundaries.test.ts new file mode 100644 index 000000000..47b905241 --- /dev/null +++ b/packages/app/src/git/diff-document/word-boundaries.test.ts @@ -0,0 +1,70 @@ +import { CharCategory, EditorState } from "@codemirror/state"; +import { describe, expect, it } from "vitest"; +import { wordRangeAtOffset } from "./word-boundaries"; + +describe("diff word boundaries", () => { + it("selects the identifier under the offset", () => { + expect(wordRangeAtOffset("alpha bravo charlie", 8)).toEqual({ start: 6, end: 11 }); + }); + + it("selects the surrounding whitespace when the offset is inside a run of spaces", () => { + expect(wordRangeAtOffset("alpha bravo", 6)).toEqual({ start: 5, end: 8 }); + }); + + it("selects a run of punctuation without merging it into neighboring words", () => { + expect(wordRangeAtOffset("call(foo, bar)", 4)).toEqual({ start: 4, end: 5 }); + expect(wordRangeAtOffset("call(foo, bar)", 6)).toEqual({ start: 5, end: 8 }); + expect(wordRangeAtOffset("fn()", 3)).toEqual({ start: 2, end: 4 }); + expect(wordRangeAtOffset("foo.bar", 3)).toEqual({ start: 3, end: 4 }); + expect(wordRangeAtOffset("foo.bar", 5)).toEqual({ start: 4, end: 7 }); + }); + + it("selects the final word when the offset reaches the end of the line", () => { + expect(wordRangeAtOffset("alpha bravo", 11)).toEqual({ start: 6, end: 11 }); + expect(wordRangeAtOffset("alpha bravo", 99)).toEqual({ start: 6, end: 11 }); + }); + + it("selects the leading word when the offset is clamped at the start", () => { + expect(wordRangeAtOffset("alpha bravo", 0)).toEqual({ start: 0, end: 5 }); + }); + + it("keeps combining sequences and emoji clusters whole", () => { + const combining = "ai\u0301b"; + expect(wordRangeAtOffset(combining, 1)).toEqual({ start: 0, end: 4 }); + expect(wordRangeAtOffset(combining, 2)).toEqual({ start: 0, end: 4 }); + + const emoji = "hi πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ there"; + const emojiStart = emoji.indexOf("πŸ‘¨"); + expect(wordRangeAtOffset(emoji, emojiStart)).toEqual({ + start: emojiStart, + end: emojiStart + "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦".length, + }); + }); + + it("treats tabs as whitespace and returns an empty range for empty content", () => { + expect(wordRangeAtOffset("\tfoo", 0)).toEqual({ start: 0, end: 1 }); + expect(wordRangeAtOffset("", 0)).toEqual({ start: 0, end: 0 }); + }); + + it("matches CodeMirror word runs for offsets inside a word", () => { + const content = "alpha bravo charlie"; + const state = EditorState.create({ doc: content }); + for (const offset of [0, 2, 8, 14, 18]) { + const word = state.wordAt(offset); + expect(word).not.toBeNull(); + expect(wordRangeAtOffset(content, offset)).toEqual({ start: word!.from, end: word!.to }); + } + }); + + it("classifies leading graphemes with CodeMirror character categories", () => { + const categorize = EditorState.create({ doc: "" }).charCategorizer(0); + const clusters = ["a", "1", "_", "δΈ­", "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦", "\u0301", "\ufe0f", "\u00a0"]; + for (const cluster of clusters) { + const isWord = categorize(cluster) === CharCategory.Word; + expect(wordRangeAtOffset(`${cluster}x`, 0)).toEqual({ + start: 0, + end: isWord ? cluster.length + 1 : cluster.length, + }); + } + }); +}); diff --git a/packages/app/src/git/diff-document/word-boundaries.ts b/packages/app/src/git/diff-document/word-boundaries.ts new file mode 100644 index 000000000..705722cc3 --- /dev/null +++ b/packages/app/src/git/diff-document/word-boundaries.ts @@ -0,0 +1,88 @@ +import { CharCategory, EditorState } from "@codemirror/state"; +import { graphemeBoundaries } from "./model"; + +export interface SourceWordRange { + start: number; + end: number; +} + +interface SourceText { + state: EditorState; + boundaries: number[]; + categorize: (cluster: string) => CharCategory; +} + +// Word gestures query the same line repeatedly while dragging. Keep a bounded +// set of parsed sources instead of rebuilding an EditorState on every move. +const SOURCE_CACHE_LIMIT = 8; +const sources = new Map(); + +/** + * The run around `offset` that a double click selects: a word, a run of + * whitespace, or a run of punctuation. Runs never cross grapheme boundaries. + */ +export function wordRangeAtOffset(content: string, offset: number): SourceWordRange { + if (content.length === 0) return { start: 0, end: 0 }; + const source = sourceText(content); + const { boundaries } = source; + const clusterIndex = clusterIndexAt(boundaries, offset); + const category = source.categorize(clusterText(content, boundaries, clusterIndex)); + if (category === CharCategory.Word) { + const word = source.state.wordAt(boundaries[clusterIndex]); + if (word) return { start: word.from, end: word.to }; + } + let first = clusterIndex; + while (first > 0 && categoryAt(source, content, boundaries, first - 1) === category) first -= 1; + let last = clusterIndex; + while ( + last < boundaries.length - 2 && + categoryAt(source, content, boundaries, last + 1) === category + ) + last += 1; + return { start: boundaries[first], end: boundaries[last + 1] }; +} + +function sourceText(content: string): SourceText { + const cached = sources.get(content); + if (cached) { + sources.delete(content); + sources.set(content, cached); + return cached; + } + const state = EditorState.create({ doc: content }); + const source: SourceText = { + state, + boundaries: graphemeBoundaries(content), + categorize: state.charCategorizer(0), + }; + sources.set(content, source); + if (sources.size > SOURCE_CACHE_LIMIT) { + const oldest = sources.keys().next(); + if (!oldest.done) sources.delete(oldest.value); + } + return source; +} + +function clusterIndexAt(boundaries: readonly number[], offset: number): number { + let low = 0; + let high = boundaries.length - 2; + while (low < high) { + const middle = (low + high + 1) >>> 1; + if (boundaries[middle] <= offset) low = middle; + else high = middle - 1; + } + return low; +} + +function categoryAt( + source: SourceText, + content: string, + boundaries: readonly number[], + index: number, +): CharCategory { + return source.categorize(clusterText(content, boundaries, index)); +} + +function clusterText(content: string, boundaries: readonly number[], index: number): string { + return content.slice(boundaries[index], boundaries[index + 1]); +}