From db1fff2f6ada178775ce344f017f5a6e446aa5f4 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 19:41:23 +0800 Subject: [PATCH] Align inline Git change previews with the editor (#4780) Inline Git change previews from the gutter now use the editor's font, line height and widths, so the previewed lines line up with the editor. --- e2e/gutterChangeLayout.spec.ts | 75 +++++++++++++++++++ src/features/vcs/HunkPopup.module.css | 64 ++++++++-------- src/features/vcs/HunkPopup.tsx | 102 +++++++++++++++----------- src/features/vcs/gutter.ts | 11 ++- src/platform/locales/text/en.json | 1 + src/platform/locales/text/zh.json | 1 + 6 files changed, 174 insertions(+), 80 deletions(-) create mode 100644 e2e/gutterChangeLayout.spec.ts diff --git a/e2e/gutterChangeLayout.spec.ts b/e2e/gutterChangeLayout.spec.ts new file mode 100644 index 000000000..bddfed451 --- /dev/null +++ b/e2e/gutterChangeLayout.spec.ts @@ -0,0 +1,75 @@ +import type { EditorView } from "@codemirror/view"; +import { expect, stubDesktop, test } from "./fixtures"; + +test("an inline change keeps its actions and original code readable at the editor zoom", async ({ + workbench: page, +}) => { + await page.setViewportSize({ width: 445, height: 520 }); + await stubDesktop(page); + const original = "const routingPolicy = 'use the legacy regional settlement cutoff before reconciliation';"; + const current = "const routingPolicy = 'use the current policy';"; + const content = Array.from({ length: 22 }, (_, i) => { + if (i === 4) return current; + if (i === 11) return "const settlementWindow = 12;"; + return `// context ${i + 1}`; + }).join("\n"); + + await page.evaluate(async (text) => { + const service = "/src/workbench/contributions.ts"; + window.__ipc.handlers.fs_probe = () => ({ size: text.length, binary: false, tooLarge: false }); + window.__ipc.handlers.fs_read_text = () => text; + await (await import(/* @vite-ignore */ service)).editorService().openFile("/dev/acme-api/settlement.ts"); + }, content); + const editor = page.locator(".cm-editor"); + await expect(editor.locator(".cm-content")).toBeVisible(); + + await editor.evaluate( + async (el, { original, content }) => { + const { view } = (el.querySelector(".cm-content") as HTMLElement & { cmTile: { view: EditorView } }).cmTile; + view.dom.style.setProperty("--openidea-editor-font-size", "18px"); + view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: content }, selection: { anchor: 0 } }); + window.__ipc.handlers.vcs_line_hunks = () => [ + { kind: "modified", start: 4, lines: 1, oldStart: 4, oldLines: 1, oldText: original + "\n" }, + { kind: "added", start: 11, lines: 1, oldStart: 11, oldLines: 0, oldText: "" }, + { kind: "deleted", start: 15, lines: 0, oldStart: 14, oldLines: 1, oldText: "// obsolete window\n" }, + ]; + const storeModule = "/src/features/vcs/store.ts"; + const { useVcs } = await import(/* @vite-ignore */ storeModule); + useVcs.setState({ available: true, version: useVcs.getState().version + 1 }); + }, + { original, content }, + ); + await editor.getByTitle("Modified lines (click to show)", { exact: true }).click(); + const modified = page.getByRole("dialog", { name: "Modified lines" }); + await expect(modified).toBeVisible(); + const originalText = modified.getByText(original, { exact: false }); + await expect(originalText).toHaveCSS("font-size", "18px"); + await expect(modified.getByText(current, { exact: false })).toHaveCount(0); + await expect(editor.getByText(current, { exact: true })).toBeVisible(); + + const preview = modified.getByRole("region", { name: "Original text" }); + await expect(preview.locator(".tok-keyword")).toHaveText("const"); + const toolbar = modified.getByRole("toolbar", { name: "Change actions" }); + expect(await preview.evaluate((el) => el.scrollWidth > el.clientWidth)).toBe(true); + const previewBox = (await preview.boundingBox())!; + const toolbarBox = (await toolbar.boundingBox())!; + const currentBox = (await editor.getByText(current, { exact: true }).boundingBox())!; + expect(previewBox.y).toBeGreaterThanOrEqual(toolbarBox.y + toolbarBox.height - 1); + expect( + toolbarBox.y >= currentBox.y + currentBox.height - 1 || previewBox.y + previewBox.height <= currentBox.y + 1, + ).toBe(true); + expect(previewBox.x).toBeGreaterThanOrEqual(0); + expect(previewBox.x + previewBox.width).toBeLessThanOrEqual(445); + await toolbar.getByRole("button", { name: "Next Change" }).click(); + const added = page.getByRole("dialog", { name: "Added lines" }); + await expect(added).toBeVisible(); + await expect(added.getByRole("region", { name: "Original text" })).toHaveCount(0); + await expect(added.getByRole("button", { name: "Copy Original Text" })).toBeDisabled(); + + await added.getByRole("button", { name: "Next Change" }).click(); + const deleted = page.getByRole("dialog", { name: "Deleted lines" }); + await expect(deleted.getByRole("region", { name: "Original text" })).toHaveText("// obsolete window"); + await deleted.getByRole("button", { name: "Rollback" }).click(); + await expect(deleted).toBeHidden(); + await expect(editor.getByText("// obsolete window", { exact: true })).toBeVisible(); +}); diff --git a/src/features/vcs/HunkPopup.module.css b/src/features/vcs/HunkPopup.module.css index a85649d55..7c4652b9a 100644 --- a/src/features/vcs/HunkPopup.module.css +++ b/src/features/vcs/HunkPopup.module.css @@ -1,58 +1,56 @@ .popup { - min-width: 320px; - max-width: min(720px, 80vw); + --hunk-surface-width: min(720px, var(--hunk-popup-width), calc(100vw - var(--space-4))); display: flex; flex-direction: column; + width: max-content; overflow: hidden; } .toolbar { flex: none; display: flex; + flex-wrap: wrap; align-items: center; - gap: var(--space-0-5); - height: 28px; - padding: 0 4px; - border-bottom: 1px solid var(--border-popup); + align-self: flex-start; + max-width: var(--hunk-surface-width); + gap: var(--space-0-5) var(--space-1); + padding: var(--space-1) var(--space-2); + background: var(--bg-popup); + border: 1px solid var(--border-popup); + border-radius: var(--radius-small); +} +.toolbar:has(+ .preview) { + border-bottom: 0; + border-end-start-radius: 0; + border-end-end-radius: 0; } .title { - flex: 1; display: flex; + flex-wrap: wrap; gap: var(--space-2); - padding: 0 8px; + min-width: 0; + padding-inline: var(--space-1); color: var(--fg-subtle); font-size: var(--fs-small); - white-space: nowrap; + overflow-wrap: anywhere; } .counter { color: var(--fg-faint); } -.body { +.preview { + max-width: var(--hunk-surface-width); + min-height: 0; max-height: 280px; + margin: 0; + padding: var(--space-1) var(--space-2) var(--space-1) 0; overflow: auto; - padding: 4px 0; - font-family: var(--font-mono); - font-size: var(--fs-code); - line-height: var(--lh-code); - -webkit-user-select: text; - user-select: text; -} -.removed, -.added { - padding: 0 12px 0 4px; + overscroll-behavior: contain; white-space: pre; color: var(--fg); + background: color-mix(in srgb, var(--gutter-deleted) 12%, var(--bg-editor)); + border: 1px solid var(--border-popup); + border-radius: 0 var(--radius-small) var(--radius-small) var(--radius-small); } -.removed { - background: color-mix(in srgb, var(--gutter-deleted) 14%, transparent); - color: var(--fg-muted); -} -.added { - background: color-mix(in srgb, var(--gutter-added) 16%, transparent); -} -.sign { - display: inline-block; - width: 16px; - color: var(--fg-faint); - -webkit-user-select: none; - user-select: none; +.preview:focus-visible { + outline: 2px solid var(--focus-ring); + outline-offset: -2px; } diff --git a/src/features/vcs/HunkPopup.tsx b/src/features/vcs/HunkPopup.tsx index 0e7bbc788..49629252b 100644 --- a/src/features/vcs/HunkPopup.tsx +++ b/src/features/vcs/HunkPopup.tsx @@ -1,11 +1,13 @@ /** Inline change popup shown when clicking a gutter change marker. */ import { writeClipboardText } from "@/platform/clipboard"; -import { useState } from "react"; +import { useEffect, useState, type CSSProperties } from "react"; import { createRoot, type Root } from "react-dom/client"; import type { EditorView } from "@codemirror/view"; import { executeAction } from "@/platform/actions"; import { shortcutLabel } from "@/platform/keymap"; -import { IconButton, Popup } from "@/ui"; +import { previewColors, tokenSpans, type CodeToken } from "@/editor/lineTokens"; +import { IconButton, Popup, selectableText } from "@/ui"; +import type { PopupAnchor } from "@/ui/Popup"; import { editorHunks, gotoChange, setHunkPopupHooks, type EditorHunk } from "./gutter"; import styles from "./HunkPopup.module.css"; import { tx } from "@/platform/i18n"; @@ -14,8 +16,8 @@ interface PopupState { view: EditorView; hunk: EditorHunk; path: string; - x: number; - y: number; + anchor: PopupAnchor; + width: number; id: number; } @@ -42,13 +44,25 @@ export function closeHunkPopup() { export function openHunkPopup(view: EditorView, hunk: EditorHunk, path: string) { const doc = view.state.doc; - const endPos = hunk.to > hunk.from ? Math.max(hunk.from, hunk.to - 1) : Math.min(hunk.from, doc.length); - const coords = view.coordsAtPos(doc.lineAt(endPos).from); - const gutterRect = view.dom.querySelector(".cm-openidea-lane")?.getBoundingClientRect(); - const x = gutterRect ? gutterRect.right : (coords?.left ?? 0); - const y = coords ? (hunk.to > hunk.from ? coords.bottom : coords.top) : 0; + const from = Math.min(hunk.from, doc.length); + const to = Math.min(Math.max(from, hunk.to - 1), doc.length); + const anchor = { + contextElement: view.scrollDOM, + getBoundingClientRect: () => { + const start = view.coordsAtPos(from); + const visible = view.scrollDOM.getBoundingClientRect(); + const gutter = view.dom.querySelector(".cm-openidea-lane")?.getBoundingClientRect(); + const x = Math.max(start?.left ?? visible.left, gutter?.right ?? visible.left); + const top = view.documentTop + view.lineBlockAt(from).top; + const bottom = hunk.to > hunk.from ? view.documentTop + view.lineBlockAt(to).bottom : top; + const clampY = (y: number) => Math.min(visible.bottom, Math.max(visible.top, y)); + // Flipping above the change leaves the current lines in the editor visible. + return new DOMRect(x, clampY(top), 0, Math.max(0, clampY(bottom) - clampY(top))); + }, + }; + const width = Math.max(240, view.scrollDOM.getBoundingClientRect().right - anchor.getBoundingClientRect().left); openFor = view; - render({ view, hunk, path, x, y, id: ++seq }); + render({ view, hunk, path, anchor, width, id: ++seq }); } export function installHunkPopup(): () => void { @@ -67,21 +81,40 @@ export function installHunkPopup(): () => void { }; } -function splitLines(text: string): string[] { - if (!text) return []; - const lines = text.split("\n"); - if (lines[lines.length - 1] === "") lines.pop(); - return lines; -} - const KIND_TITLE = { added: "Added lines", modified: "Modified lines", deleted: "Deleted lines" } as const; +function OriginalText({ view, path, text }: { view: EditorView; path: string; text: string }) { + const [tokens, setTokens] = useState(null); + const [font] = useState(() => { + const { fontFamily, fontSize, fontWeight, lineHeight, fontVariantLigatures } = getComputedStyle(view.contentDOM); + return { fontFamily, fontSize, fontWeight, lineHeight, fontVariantLigatures, tabSize: view.state.tabSize }; + }); + useEffect(() => { + if (text.length > 100_000) return; + let alive = true; + void previewColors(text, path).then((colorize) => { + if (alive && colorize) setTokens(colorize(0, text.length)); + }); + return () => { + alive = false; + }; + }, [text, path]); + return ( +
+      {tokenSpans(text, 0, text.length, tokens)}
+    
+ ); +} + function HunkPopupView({ state }: { state: PopupState }) { const { view, hunk, path } = state; const [copied, setCopied] = useState(false); - const current = view.state.sliceDoc(hunk.from, hunk.to); - const oldLines = splitLines(hunk.oldText); - const newLines = splitLines(current); const all = editorHunks(view.state); const index = all.findIndex((h) => h.start === hunk.start && h.oldStart === hunk.oldStart); @@ -97,7 +130,7 @@ function HunkPopupView({ state }: { state: PopupState }) { }; const step = (dir: 1 | -1) => { - const target = gotoChange(view, dir); + const target = gotoChange(view, dir, hunk.from); if (target) requestAnimationFrame(() => openHunkPopup(view, target, path)); else closeHunkPopup(); }; @@ -105,12 +138,14 @@ function HunkPopupView({ state }: { state: PopupState }) { return (
- {(oldLines.length > 0 || newLines.length > 0) && ( -
- {oldLines.map((l, i) => ( -
- - - - - {l || " "} -
- ))} - {newLines.map((l, i) => ( -
- - + - - {l || " "} -
- ))} -
- )} + {hunk.oldText && }
); } diff --git a/src/features/vcs/gutter.ts b/src/features/vcs/gutter.ts index cc19be40d..2fd30ea88 100644 --- a/src/features/vcs/gutter.ts +++ b/src/features/vcs/gutter.ts @@ -278,11 +278,14 @@ export function changeMarkers(ctx: EditorDocContext): Extension { } /** Moves the caret to the next / previous change in `view`. Returns whether it moved. */ -export function gotoChange(view: EditorView, dir: 1 | -1): EditorHunk | undefined { +export function gotoChange( + view: EditorView, + dir: 1 | -1, + from = view.state.selection.main.head, +): EditorHunk | undefined { const hunks = editorHunks(view.state); if (!hunks.length) return undefined; - const head = view.state.selection.main.head; - const lineFrom = view.state.doc.lineAt(head).from; + const lineFrom = view.state.doc.lineAt(from).from; const sorted = [...hunks].sort((a, b) => a.from - b.from); let target: EditorHunk | undefined; if (dir === 1) target = sorted.find((h) => h.from > lineFrom && view.state.doc.lineAt(h.from).from > lineFrom); @@ -292,7 +295,7 @@ export function gotoChange(view: EditorView, dir: 1 | -1): EditorHunk | undefine .find( (h) => view.state.doc.lineAt(Math.min(h.from, view.state.doc.length)).from < lineFrom && - !(h.from <= head && head < h.to), + !(h.from <= from && from < h.to), ); target ??= dir === 1 ? sorted[0] : sorted[sorted.length - 1]; if (!target) return undefined; diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 3af72e6b9..be5031c6f 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4,6 +4,7 @@ "{modified} modified": "{modified} modified", "{deleted} deleted": "{deleted} deleted", "Rollback discards uncommitted changes in the selected files.": "Rollback discards uncommitted changes in the selected files.", + "Original text": "Original text", "MCP server instructions": "MCP server instructions", "MCP tools (deferred)": "MCP tools (deferred)", "System tools (deferred)": "System tools (deferred)", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 86ca3840e..417803585 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1170,6 +1170,7 @@ "Copy Image Name": "复制镜像名称", "Copy Name": "复制名称", "Copy Original Text": "复制原始文本", + "Original text": "原始文本", "Copy Path": "复制路径", "Copy Path from Project Root": "复制项目根目录起的路径", "Copy Path/Reference…": "复制路径/引用…",