From 36ecb53159c9cf66dbfb9629f2cac04232ae955c Mon Sep 17 00:00:00 2001 From: Mansur Akhmadi Date: Fri, 20 Nov 2026 09:15:00 +0700 Subject: [PATCH 01/14] feat(run): Fold Lines Like This in the Run console's context menu (#4635) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Run console's context menu gets Fold Lines Like This: it opens Settings › Build, Execution, Deployment › Console with the selected single-line text, or the right-clicked line, added to the fold patterns. Verified with full vitest, typecheck, and in the app (pattern added, Cancel leaves settings unchanged). Co-authored-by: mansur-akhmadi <10739460+mansur-akhmadi@users.noreply.github.com> --- docs/en/guide/run.mdx | 2 +- docs/zh/guide/run.mdx | 2 +- src/features/run/ConsoleView.tsx | 25 ++++ src/features/run/consoleFoldLines.test.tsx | 129 ++++++++++++++++++ .../__tests__/consoleFoldPatterns.test.tsx | 107 +++++++++++++++ src/features/settings/pages/execution.tsx | 19 ++- src/platform/locales/text/en.json | 3 +- src/platform/locales/text/zh.json | 1 + 8 files changed, 284 insertions(+), 4 deletions(-) create mode 100644 src/features/run/consoleFoldLines.test.tsx create mode 100644 src/features/settings/__tests__/consoleFoldPatterns.test.tsx diff --git a/docs/en/guide/run.mdx b/docs/en/guide/run.mdx index 4633737789..f214cb3893 100644 --- a/docs/en/guide/run.mdx +++ b/docs/en/guide/run.mdx @@ -160,7 +160,7 @@ A **Compound** configuration starts several configurations at once. Run it to st Each launch opens a tab in the **Run** tool window (bottom). The toolbar has **Rerun**, **Debug**, **Rerun Failed Tests** (for test runs), **Update Application**, **Find…**, **Scroll to End**, **Soft-Wrap**, **Clear All** and **Edit Configurations…**. - File paths and stack trace frames in the output are links. -- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding. +- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding. **Fold Lines Like This** in the console's context menu opens that page with the selected text (or the clicked line) added as a pattern. - Log lines can take the colour of their level (`ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`); colours the program prints itself are kept. Turn it on and pick the colours in **Settings › Build, Execution, Deployment › Console**. - For test runs the tab shows a test tree next to the output. See [Testing](/en/guide/testing). diff --git a/docs/zh/guide/run.mdx b/docs/zh/guide/run.mdx index 5f4ede0c66..123742294e 100644 --- a/docs/zh/guide/run.mdx +++ b/docs/zh/guide/run.mdx @@ -156,7 +156,7 @@ Maven 模块在 **自动** 和 **构建(Make)** 时由 jdtls(ECJ)构建 每次启动都会在底部的 **运行** 工具窗口里开一个标签页。工具栏有 **重新运行**、**调试**、**重新运行失败的测试**(测试运行时)、**更新应用**、**查找…**、**滚动到末尾**、**软换行**、**全部清除** 和 **编辑配置…**。 - 输出里的文件路径和堆栈帧都可以点击跳转。 -- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。 +- 重复的行可以折叠。折叠规则、缓冲区大小和控制台编码在 **设置 › 构建、执行、部署 › 控制台** 中配置。控制台右键菜单中的 **折叠与此类似的行** 会打开该页面,并把选中的文本(或右键所在的行)添加为折叠规则。 - 日志行可按级别着色(`ERROR`、`WARN`、`INFO`、`DEBUG`、`TRACE`);程序自行输出的颜色保持不变。默认关闭,可在 **设置 › 构建、执行、部署 › 控制台** 开启并修改颜色。 - 测试运行时,标签页会在输出旁显示测试树,参见[测试](/zh/guide/testing)。 diff --git a/src/features/run/ConsoleView.tsx b/src/features/run/ConsoleView.tsx index 7aeb93e5d2..bbd53475a0 100644 --- a/src/features/run/ConsoleView.tsx +++ b/src/features/run/ConsoleView.tsx @@ -29,6 +29,7 @@ import { useConsoleSelection } from "./useConsoleSelection"; import { hostBinding, formatBinding, hasPrimaryModifier, registerKeyClaim } from "@/platform/keymap"; import { WidestColumns } from "@/platform/consoleColumns"; import { tx } from "@/platform/i18n"; +import { executeAction } from "@/platform/actions"; import { ConsoleFindBar } from "@/ui/ConsoleFindBar"; import { DEFAULT_FIND_OPTIONS, findInLines, type FindOptions } from "@/ui/consoleFind"; @@ -115,6 +116,15 @@ export interface Fold { */ export type DisplayRow = { kind: "line"; index: number; fold?: Fold } | { kind: "fold"; fold: Fold }; +/** + * IDEA's Fold Lines Like This: the selection when it stays on one line, else the clicked line; + * trimmed, and `null` when that leaves nothing to fold on. + */ +export function foldLineText(selection: string, line: string | null): string | null { + const text = (selection || (line ?? "")).trim(); + return text && !/[\r\n]/.test(text) ? text : null; +} + /** * Folds runs of consecutive output lines (one or more) that contain one of * `patterns`; runs whose first line id is in `expanded` stay open. @@ -421,9 +431,18 @@ export function ConsoleView({ /** The selected text; after Select All the whole buffer, including rows that are not mounted. */ const selectedOutput = () => (allSelected() ? model.text() : (window.getSelection()?.toString() ?? "")); + /** The output line a context menu opened on; folds and the input row have none. */ + const lineAt = (target: EventTarget) => { + const index = (target as Element).closest?.("[data-index]")?.getAttribute("data-index"); + const row = index == null ? undefined : rows[Number(index)]; + const line = row?.kind === "line" ? lines[row.index] : undefined; + return line && line.kind !== "system" ? line.text : null; + }; + const onContextMenu = (e: MouseEvent) => { e.preventDefault(); const selection = selectedOutput(); + const foldText = foldLineText(selection, lineAt(e.target)); showContextMenu(e, [ { label: "Copy", @@ -441,6 +460,12 @@ export function ConsoleView({ run: openFind, }, { kind: "separator" }, + { + label: "Fold Lines Like This", + disabled: !foldText, + // Opens Settings › Console with the text added to the fold patterns, for OK / Cancel there. + run: () => void executeAction("file.settings", `build.console#${foldText}`), + }, { label: "Clear All", icon: "trash", disabled: !onClear, run: () => onClear?.() }, ...(input ? [{ kind: "separator" } as const, { label: "Send EOF", shortcut: "⌃D", run: () => input.onEof() }] diff --git a/src/features/run/consoleFoldLines.test.tsx b/src/features/run/consoleFoldLines.test.tsx new file mode 100644 index 0000000000..8c1323d733 --- /dev/null +++ b/src/features/run/consoleFoldLines.test.tsx @@ -0,0 +1,129 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, fireEvent, render, within } from "@testing-library/react"; +import { useProject } from "@/platform/project"; +import { hideContextMenu, useContextMenuStore } from "@/ui"; +import { ConsoleModel } from "./console"; +import { ConsoleView, foldLineText } from "./ConsoleView"; + +const actions = vi.hoisted(() => ({ executeAction: vi.fn(async () => {}) })); +vi.mock("@/platform/actions", async (orig) => ({ ...(await orig()), executeAction: actions.executeAction })); + +vi.mock("@tanstack/react-virtual", () => ({ + useVirtualizer: ({ count }: { count: number }) => ({ + getTotalSize: () => count * 20, + getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 20, key: index })), + scrollToIndex: () => {}, + measureElement: () => {}, + measure: () => {}, + }), +})); + +beforeEach(() => { + actions.executeAction.mockClear(); + useProject.setState({ settings: null }); + window.getSelection()?.removeAllRanges(); +}); + +afterEach(() => act(hideContextMenu)); + +function setup(chunks: { kind: "stdout" | "stderr" | "system"; text: string }[]) { + const model = new ConsoleModel(); + for (const c of chunks) model.append(c); + model.flush(); + const { container } = render( + {}} cwd="/" />, + ); + return within(container).getByRole("log"); +} + +function foldItem(target: Element) { + fireEvent.contextMenu(target); + const items = useContextMenuStore.getState().menu?.items ?? []; + return items.find((i) => "label" in i && i.label === "Fold Lines Like This") as + | { disabled?: boolean; run?: () => void } + | undefined; +} + +function select(node: Node, start: number, end: number) { + const range = document.createRange(); + range.setStart(node, start); + range.setEnd(node, end); + window.getSelection()!.removeAllRanges(); + window.getSelection()!.addRange(range); +} + +describe("foldLineText", () => { + it("takes a one-line selection, else the clicked line, trimmed", () => { + expect(foldLineText(" at org.junit.Assert ", "ignored")).toBe("at org.junit.Assert"); + expect(foldLineText("", "\tat java.base/Thread.run(Thread.java:1583) ")).toBe( + "at java.base/Thread.run(Thread.java:1583)", + ); + // A whole row picked by a triple click ends in its line break. + expect(foldLineText("DEBUG pool\n", null)).toBe("DEBUG pool"); + }); + + it("has nothing for a selection across lines, a blank selection or a blank line", () => { + expect(foldLineText("first\nsecond", "first")).toBeNull(); + expect(foldLineText("first\r\nsecond", "first")).toBeNull(); + expect(foldLineText(" ", "a line")).toBeNull(); + expect(foldLineText("", " ")).toBeNull(); + expect(foldLineText("", null)).toBeNull(); + }); +}); + +describe("Fold Lines Like This", () => { + it("opens Settings › Console with the clicked line to add as a fold pattern", () => { + const log = setup([ + { + kind: "stdout", + text: "start\n at org.springframework.test.context.TestContextManager.prepare(TestContextManager.java:248)\n", + }, + ]); + const row = log.querySelectorAll("[data-index]")[1]!; + const item = foldItem(row.firstElementChild ?? row)!; + expect(item.disabled).toBeFalsy(); + item.run!(); + expect(actions.executeAction).toHaveBeenCalledWith( + "file.settings", + "build.console#at org.springframework.test.context.TestContextManager.prepare(TestContextManager.java:248)", + ); + }); + + it("uses the selected part of a line rather than the whole line", () => { + const log = setup([{ kind: "stdout", text: "12:00 DEBUG pool: idle\n" }]); + const row = log.querySelector("[data-index]")!; + const text = document.createTreeWalker(row, NodeFilter.SHOW_TEXT).nextNode()!; + select(text, 6, 11); + foldItem(row)!.run!(); + expect(actions.executeAction).toHaveBeenCalledWith("file.settings", "build.console#DEBUG"); + }); + + it("is disabled for a selection over several lines", () => { + const log = setup([{ kind: "stdout", text: "one\ntwo\n" }]); + const rows = log.querySelectorAll("[data-index]"); + const range = document.createRange(); + range.setStart(rows[0]!, 0); + range.setEnd(rows[1]!, rows[1]!.childNodes.length); + window.getSelection()!.removeAllRanges(); + window.getSelection()!.addRange(range); + expect(foldItem(rows[0]!)!.disabled).toBe(true); + }); + + it("is disabled on a blank line, the IDE's own messages and a folded run", () => { + useProject.setState({ settings: { console: { foldPatterns: ["at org."] } } as never }); + const log = setup([ + { kind: "stdout", text: "\n" }, + { kind: "system", text: "Process finished with exit code 0\n" }, + ]); + const rows = log.querySelectorAll("[data-index]"); + expect(foldItem(rows[0]!)!.disabled).toBe(true); + expect(foldItem(rows[1]!)!.disabled).toBe(true); + act(hideContextMenu); + + const folded = setup([{ kind: "stdout", text: "at org.a\nat org.b\n" }]); + const fold = folded.querySelector("[data-index]")!; + expect(fold.textContent).toContain("internal lines"); + expect(foldItem(fold)!.disabled).toBe(true); + expect(actions.executeAction).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/settings/__tests__/consoleFoldPatterns.test.tsx b/src/features/settings/__tests__/consoleFoldPatterns.test.tsx new file mode 100644 index 0000000000..df5cd4cdca --- /dev/null +++ b/src/features/settings/__tests__/consoleFoldPatterns.test.tsx @@ -0,0 +1,107 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { act, fireEvent, render, screen, within } from "@testing-library/react"; +import { type Settings } from "@/platform/ipc"; + +const settingsSet = vi.fn(); +const settingsGet = vi.fn(); +const settingsGetGlobal = vi.fn(); + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + isTauri: () => true, + commands: { + ...real.commands, + settingsSet: (...a: unknown[]) => settingsSet(...a), + settingsGet: () => settingsGet(), + settingsGetGlobal: () => settingsGetGlobal(), + }, + }; +}); + +import { executeAction } from "@/platform/actions"; +import { useProject } from "@/platform/project"; +import { DEFAULT_SETTINGS, setAt } from "../model/schema"; +import { useSettingsDialog } from "../model/staging"; +import { SettingsDialog } from "../dialog/SettingsDialog"; +import { activate } from ".."; + +let current: Settings; +let dispose: () => void = () => {}; + +beforeEach(() => { + current = setAt(structuredClone(DEFAULT_SETTINGS) as Settings, "console.foldPatterns", ["at org.junit."]); + settingsSet.mockReset().mockImplementation(async (_scope: string, key: string, json: string) => { + current = setAt(current, key, JSON.parse(json)); + return { status: "ok", data: current }; + }); + settingsGet.mockReset().mockImplementation(async () => current); + settingsGetGlobal.mockReset().mockImplementation(async () => current); + useProject.setState({ settings: current, project: null }); + dispose = activate(); +}); + +afterEach(() => { + act(() => useSettingsDialog.setState({ open: false })); + dispose(); +}); + +/** Settings › Console as the console's Fold Lines Like This opens it. */ +async function openWith(text: string) { + render(); + await act(async () => { + await executeAction("file.settings", `build.console#${text}`); + }); + const dialog = screen.getByRole("dialog", { name: "Settings" }); + const list = await within(dialog).findByRole("listbox", { name: "Fold console lines that contain" }); + return { + dialog, + patterns: () => + within(list) + .getAllByRole("option") + .map((o) => o.textContent), + }; +} + +it("adds the console's line to the fold patterns, written on OK", async () => { + const { dialog, patterns } = await openWith("at com.example.Retry#call"); + expect(patterns()).toEqual(["at org.junit.", "at com.example.Retry#call"]); + expect(settingsSet).not.toHaveBeenCalled(); + await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "OK" }))); + expect(settingsSet).toHaveBeenCalledWith( + "global", + "console.foldPatterns", + JSON.stringify(["at org.junit.", "at com.example.Retry#call"]), + ); +}); + +it("writes nothing when the dialog is cancelled", async () => { + const { dialog } = await openWith("DEBUG"); + await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }))); + expect(settingsSet).not.toHaveBeenCalled(); +}); + +it("does not add a pattern the list already has", async () => { + const { dialog, patterns } = await openWith("at org.junit."); + expect(patterns()).toEqual(["at org.junit."]); + await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "OK" }))); + expect(settingsSet).not.toHaveBeenCalled(); +}); + +it("adds to the global list, not the project's own, while the global settings load", async () => { + const global = current; + settingsGetGlobal.mockImplementation(async () => global); + useProject.setState({ + settings: setAt(global, "console.foldPatterns", ["at com.acme.internal."]), + project: { root: "/p", name: "p" } as never, + }); + const { dialog, patterns } = await openWith("DEBUG"); + expect(patterns()).toEqual(["at org.junit.", "DEBUG"]); + await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "OK" }))); + expect(settingsSet).toHaveBeenCalledWith( + "global", + "console.foldPatterns", + JSON.stringify(["at org.junit.", "DEBUG"]), + ); +}); diff --git a/src/features/settings/pages/execution.tsx b/src/features/settings/pages/execution.tsx index e817c63898..2819b366b9 100644 --- a/src/features/settings/pages/execution.tsx +++ b/src/features/settings/pages/execution.tsx @@ -3,10 +3,15 @@ * Stepping), Python Debugger and Run/Debug. Consumed by the run and debugger * features (and `ide-run` for encoding / termination timeout). */ +import { useEffect } from "react"; import { WORKFLOW_LIMITS } from "@/platform/workflowSettings"; +import { useSettingsPageFocus } from "@/workbench/contributions"; +import { isTauri } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; import type { SelectOption } from "@/ui"; import { ColorSwatches, FormGroup, GlobListEditor, NumberInput, Row, Toggle } from "../components/Form"; -import { useSetting } from "../components/context"; +import { usePageContext, useSetting } from "../components/context"; +import { useSettingsDialog } from "../model/staging"; import { lazyPage } from "./lazyPage"; import type { PageSpec } from "./spec"; import { Indented, ToggleNumber } from "./workflowControls"; @@ -53,6 +58,18 @@ function BufferRow() { function FoldPatterns() { const [patterns, set] = useSetting("console.foldPatterns"); + // Opened as `build.console#` by the console's Fold Lines Like This: add it as a pattern. + const { focus, consume } = useSettingsPageFocus(); + // With a project open, the Global list arrives after the dialog opens (until then it is the project's). + const { scope } = usePageContext(); + const globalPending = useSettingsDialog((s) => s.globalBase === s.base); + const hasProject = useProject((s) => !!s.project); + const waiting = scope === "global" && globalPending && hasProject && isTauri(); + useEffect(() => { + if (!focus || waiting) return; + consume(); + if (!patterns.includes(focus)) set([...patterns, focus]); + }, [focus, consume, waiting, patterns, set]); return ( ": "", "Shelve Silently": "Shelve Silently", - "Unshelve Silently": "Unshelve Silently" + "Unshelve Silently": "Unshelve Silently", + "Fold Lines Like This": "Fold Lines Like This" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index ce397cf50c..8effb4217b 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -3349,6 +3349,7 @@ "Hold Shift to Debug, F4 to edit, Delete to remove": "按住 Shift 调试,F4 编辑,Delete 删除", "Hold Shift to Run, F4 to edit, Delete to remove": "按住 Shift 运行,F4 编辑,Delete 删除", "Send EOF": "发送 EOF", + "Fold Lines Like This": "折叠与此类似的行", "Collapse folded lines": "折叠行", "Close Tool Window Tab": "关闭工具窗口标签页", "No open files": "没有打开的文件", From 3dd5c75fa00cdf299895f2c3969c76234b034455 Mon Sep 17 00:00:00 2001 From: Mansur Akhmadi Date: Fri, 20 Nov 2026 09:15:56 +0700 Subject: [PATCH 02/14] feat(debugger): Remove All Watches in the Variables view's context menu (#4647) A watch row's context menu in the Variables view gets Remove All Watches next to Remove Watch; it empties the project's stored watch list. Verified with debugger and locale vitest and typecheck; main merged in (locale conflict resolved). Co-authored-by: mansur-akhmadi <10739460+mansur-akhmadi@users.noreply.github.com> --- docs/en/guide/debugging.mdx | 2 +- docs/zh/guide/debugging.mdx | 2 +- .../debugger/__tests__/toolWindow.test.tsx | 26 +++++++++++++++++++ .../debugger/__tests__/watchStorage.test.ts | 19 +++++++++++++- src/features/debugger/state.ts | 5 ++++ src/features/debugger/ui/VariablesView.tsx | 16 ++++++++++-- src/platform/locales/text/en.json | 3 ++- src/platform/locales/text/zh.json | 3 ++- 8 files changed, 69 insertions(+), 7 deletions(-) diff --git a/docs/en/guide/debugging.mdx b/docs/en/guide/debugging.mdx index 1bb96f1fd8..371c73fdbf 100644 --- a/docs/en/guide/debugging.mdx +++ b/docs/en/guide/debugging.mdx @@ -123,7 +123,7 @@ These commands are in the **Run** menu and on the Debug tool window toolbar. While the program is suspended: - The **Variables** view shows the variables of the selected frame. Right-click a value for **Set Value…** (`F2`), **Copy Value**, **Copy Name**, **Jump to Source** (`F4`) and **Add to Watches**. -- **Watches** appear at the top of the Variables view and are re-evaluated on every stop and frame change. Add one with **Add to Watches**; remove it with **Remove Watch**. +- **Watches** appear at the top of the Variables view and are re-evaluated on every stop and frame change. Add one with **Add to Watches**; remove it with **Remove Watch**, or all of them with **Remove All Watches**. - Hovering a variable in the editor shows its value. `⌥`-click (`Alt`-click) or **Quick Evaluate Expression** (`⌘⌥F8` / `Ctrl+Alt+F8`) evaluates the expression under the mouse or the selection. - Values of local variables are shown inline after the lines that use them. - **Evaluate Expression…** (`⌥F8` / `Alt+F8`) opens a dialog that evaluates any expression in the selected frame, keeps a history, and can add the expression to watches. diff --git a/docs/zh/guide/debugging.mdx b/docs/zh/guide/debugging.mdx index bc1566e2fb..cdae5193b5 100644 --- a/docs/zh/guide/debugging.mdx +++ b/docs/zh/guide/debugging.mdx @@ -125,7 +125,7 @@ C 和 C++ 的配置也可以改用 GDB 14 及以上版本(`gdb -i dap`): 程序挂起时: - **变量** 视图显示选中帧的变量。右键点击某个值,可以 **设置值…**(`F2`)、**复制值**、**复制名称**、**跳转到源代码**(`F4`)和 **添加到监视**。 -- 监视表达式显示在变量视图顶部,每次停下或切换帧时重新计算。用 **添加到监视** 添加,用 **移除监视** 删除。 +- 监视表达式显示在变量视图顶部,每次停下或切换帧时重新计算。用 **添加到监视** 添加,用 **移除监视** 删除,用 **移除所有监视** 一次全部删除。 - 在编辑器里悬停变量会显示它的值。`⌥` 点击(`Alt` 点击)或 **快速计算表达式**(`⌘⌥F8` / `Ctrl+Alt+F8`)计算鼠标下的表达式或选中的内容。 - 局部变量的值会内联显示在使用它们的行尾。 - **计算表达式…**(`⌥F8` / `Alt+F8`)打开对话框,在选中帧里计算任意表达式,带历史记录,也能把表达式加入监视。 diff --git a/src/features/debugger/__tests__/toolWindow.test.tsx b/src/features/debugger/__tests__/toolWindow.test.tsx index cf291552be..99abdee4d7 100644 --- a/src/features/debugger/__tests__/toolWindow.test.tsx +++ b/src/features/debugger/__tests__/toolWindow.test.tsx @@ -396,6 +396,32 @@ describe("variables the adapter computes after the stop", () => { } }); + it("offers Remove All Watches on a watch's context menu", async () => { + useDebug.setState({ watches: ["count + 1", "label.upper()"] }); + const menu = (text: string) => { + fireEvent.contextMenu(screen.getByText(text).closest("[role=treeitem]")!); + const items = useContextMenuStore.getState().menu?.items ?? []; + act(() => hideContextMenu()); + return items.flatMap((i) => ("label" in i && i.label ? [i] : [])); + }; + try { + setup(); + await screen.findByText("label.upper()"); + await screen.findByText("'hi'"); + expect(menu("label").map((i) => i.label)).not.toContain("Remove All Watches"); + const items = menu("count + 1"); + expect(items.map((i) => i.label)).toContain("Remove Watch"); + const removeAll = items.find((i) => i.label === "Remove All Watches"); + expect(removeAll).toBeTruthy(); + act(() => (removeAll as { run: () => void }).run()); + expect(useDebug.getState().watches).toEqual([]); + await waitFor(() => expect(screen.queryByText("label.upper()")).toBeNull()); + expect(screen.getByText("'hi'")).toBeTruthy(); + } finally { + useDebug.setState({ watches: [] }); + } + }); + it("reloads after Set Value", async () => { setup(); await screen.findByText("Collecting data…"); diff --git a/src/features/debugger/__tests__/watchStorage.test.ts b/src/features/debugger/__tests__/watchStorage.test.ts index 48386436fa..ce477b9432 100644 --- a/src/features/debugger/__tests__/watchStorage.test.ts +++ b/src/features/debugger/__tests__/watchStorage.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it } from "vitest"; -import { addWatch, loadWatches, useDebug } from "../state"; +import { addWatch, loadWatches, removeAllWatches, useDebug } from "../state"; const SHARED = "openidea.debugger.watches"; const of = (root: string) => `${SHARED}:${root}`; @@ -41,6 +41,23 @@ describe("watch storage", () => { expect(watches()).toEqual([]); }); + it("Remove All Watches empties the project's stored list", () => { + localStorage.setItem(SHARED, '["legacy"]'); + loadWatches("/a"); + addWatch("x"); + addWatch("y"); + loadWatches("/b"); + addWatch("z"); + loadWatches("/a"); + removeAllWatches(); + expect(watches()).toEqual([]); + expect(localStorage.getItem(of("/a"))).toBe("[]"); + loadWatches("/a"); + expect(watches()).toEqual([]); + loadWatches("/b"); + expect(watches()).toEqual(["legacy", "z"]); + }); + it("without a project nothing is stored", () => { loadWatches(null); addWatch("z"); diff --git a/src/features/debugger/state.ts b/src/features/debugger/state.ts index 9014a529f6..6c20e4f84e 100644 --- a/src/features/debugger/state.ts +++ b/src/features/debugger/state.ts @@ -1221,6 +1221,11 @@ export function removeWatch(expression: string) { persistWatches(); } +export function removeAllWatches() { + useDebug.setState({ watches: [] }); + persistWatches(); +} + /** Watches used to be one list for every project; it is only read now, as a project's first list. */ const SHARED_WATCH_KEY = "openidea.debugger.watches"; const watchKey = (root: string) => `${SHARED_WATCH_KEY}:${root}`; diff --git a/src/features/debugger/ui/VariablesView.tsx b/src/features/debugger/ui/VariablesView.tsx index 214e69a92f..82ae6a1fde 100644 --- a/src/features/debugger/ui/VariablesView.tsx +++ b/src/features/debugger/ui/VariablesView.tsx @@ -9,7 +9,15 @@ import { activeEditor } from "@/editor/api"; import { notifications } from "@/workbench/contributions"; import { addFieldWatchpoint } from "../breakpoints/special"; import { methodAt } from "../breakpoints/symbols"; -import { activeSession, addWatch, removeWatch, revealFrame, sessionSupports, setVariableValue } from "../state"; +import { + activeSession, + addWatch, + removeAllWatches, + removeWatch, + revealFrame, + sessionSupports, + setVariableValue, +} from "../state"; import { blurDebugView, focusDebugView } from "./focusedView"; import { classifyValue, oneLine, shownValue, sortVariables } from "../values"; import { valueText } from "../valueText"; @@ -300,7 +308,11 @@ export function VariablesView({ { label: "Set Value…", icon: "edit", shortcut: "F2", run: () => startEdit(node) }, { kind: "separator" }, ); - if (node.kind === "watch") items.push({ label: "Remove Watch", icon: "minus", run: () => removeWatch(node.name) }); + if (node.kind === "watch") + items.push( + { label: "Remove Watch", icon: "minus", run: () => removeWatch(node.name) }, + { label: "Remove All Watches", run: removeAllWatches }, + ); if (node.kind !== "scope") { items.push({ label: "Copy Value", icon: "copy", run: () => void copyValue(node) }); items.push({ label: "Copy Name", run: () => void writeClipboardText(node.name) }); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 021658d21b..421a4ae7d7 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2706,5 +2706,6 @@ "": "", "Shelve Silently": "Shelve Silently", "Unshelve Silently": "Unshelve Silently", - "Fold Lines Like This": "Fold Lines Like This" + "Fold Lines Like This": "Fold Lines Like This", + "Remove All Watches": "Remove All Watches" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 8effb4217b..4b38660dcd 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -9073,5 +9073,6 @@ "Resize shelf panes": "调整搁置记录和文件窗格大小", "Database and schema": "数据库和 schema", "Shelve Silently": "静默搁置", - "Unshelve Silently": "静默取消搁置" + "Unshelve Silently": "静默取消搁置", + "Remove All Watches": "移除所有监视" } From 7850429174076e4b3a20121a0c39bf3f10dc4fbb Mon Sep 17 00:00:00 2001 From: leen Date: Fri, 20 Nov 2026 10:17:09 +0800 Subject: [PATCH 03/14] fix(vcs): open existing worktrees over SSH (#4465) Opening a linked worktree from an SSH or WSL project treated the remote directory as a local path. The Worktrees toolbar, row double-click and the checkout prompt's Open now go through openWorktree, which reuses the session's remote target and opens a remote window; local projects are unchanged. Verified with vcs and remote-dev vitest and typecheck on macOS (local path); the SSH flow was verified by the author in the native Linux app. Co-authored-by: leen2175 <22676327+leen2175@users.noreply.github.com> --- src/features/vcs/__tests__/branchOps.test.ts | 42 +++++++++++++- .../vcs/__tests__/worktreesPanel.test.tsx | 55 ++++++++++++++++++- src/features/vcs/branchOps.ts | 3 +- src/features/vcs/gitMenuDialogs.tsx | 6 +- src/features/vcs/openWorktree.ts | 29 ++++++++++ 5 files changed, 127 insertions(+), 8 deletions(-) create mode 100644 src/features/vcs/openWorktree.ts diff --git a/src/features/vcs/__tests__/branchOps.test.ts b/src/features/vcs/__tests__/branchOps.test.ts index 6966b2a5a0..44f9286be5 100644 --- a/src/features/vcs/__tests__/branchOps.test.ts +++ b/src/features/vcs/__tests__/branchOps.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; import type { Branch, BranchInfo, ProjectInfo, Worktree } from "@/bindings"; const mocks = vi.hoisted(() => ({ prompt: vi.fn(), @@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({ ask: vi.fn(), checkout: vi.fn(), executeAction: vi.fn(), + windowOpenRemote: vi.fn(), })); vi.mock("../dialogs", async (original) => ({ ...(await original()), @@ -41,12 +42,14 @@ vi.mock("@/platform/ipc", async (original) => { vcsBranches: mocks.branches, vcsRenameBranch: mocks.rename, vcsCheckout: mocks.checkout, + windowOpenRemote: mocks.windowOpenRemote, }, }; }); import { checkoutBranch, deleteBranch, deleteBranches, newBranch, newBranchInRepos, renameBranch } from "../branchOps"; import { useVcs } from "../store"; import { useProject } from "@/platform/project"; +import { useRemote } from "@/platform/remote"; const branch = (head: string | null): BranchInfo => ({ head, @@ -386,3 +389,40 @@ it("refreshes tracking branches in the deletion repository without replacing the notification.actions.find((a: { label: string }) => a.label === "Restore").run(); await vi.waitFor(() => expect(mocks.restoreBranch).toHaveBeenCalledWith("/p/back", expect.anything())); }); + +afterEach(() => useRemote.setState({ session: null })); + +it.each(["focused", "failed"])("opens a checked-out SSH branch without retrying checkout: %s", async (outcome) => { + const target = { kind: "ssh", config: "connected-host" } as const; + const path = "/p/front feature"; + useRemote.setState({ session: { target, root: "/p/front", host: "demo-linux", os: "linux", commands: [] } }); + mocks.checkout.mockReset().mockResolvedValue(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path })); + mocks.ask.mockReset().mockResolvedValue({ button: "open" }); + mocks.windowOpenRemote + .mockReset() + .mockResolvedValue( + outcome === "focused" + ? ok({ kind: "focused", label: "existing-window" }) + : { status: "error", error: { kind: "unavailable", message: "SSH unavailable", detail: null } }, + ); + mocks.executeAction.mockClear(); + mocks.notify.mockClear(); + await checkoutBranch("feature/wt"); + expect(mocks.windowOpenRemote).toHaveBeenCalledExactlyOnceWith(target, path, true); + expect(mocks.checkout).toHaveBeenCalledTimes(1); + expect(mocks.executeAction).not.toHaveBeenCalledWith("file.openProjectPath", expect.anything()); + if (outcome === "failed") { + expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ level: "error", body: "SSH unavailable" })); + } +}); + +it("keeps the local open action when another worktree holds the branch", async () => { + const path = "C:/src/project-worktree"; + useRemote.setState({ session: null }); + mocks.checkout.mockResolvedValue(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path })); + mocks.ask.mockResolvedValue({ button: "open" }); + await checkoutBranch("feature/wt"); + expect(mocks.executeAction).toHaveBeenCalledExactlyOnceWith("file.openProjectPath", path); + expect(mocks.windowOpenRemote).not.toHaveBeenCalled(); + expect(mocks.checkout).toHaveBeenCalledTimes(1); +}); diff --git a/src/features/vcs/__tests__/worktreesPanel.test.tsx b/src/features/vcs/__tests__/worktreesPanel.test.tsx index 4e7610f0dd..1285c57823 100644 --- a/src/features/vcs/__tests__/worktreesPanel.test.tsx +++ b/src/features/vcs/__tests__/worktreesPanel.test.tsx @@ -1,18 +1,25 @@ -import { beforeEach, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; -const { list, move, remove, open, confirm } = vi.hoisted(() => ({ +const { list, move, remove, open, confirm, windowOpenRemote } = vi.hoisted(() => ({ list: vi.fn(), move: vi.fn(), remove: vi.fn(), open: vi.fn(), confirm: vi.fn(), + windowOpenRemote: vi.fn(), })); vi.mock("@/platform/ipc", async (original) => { const real = await original(); return { ...real, - commands: { ...real.commands, vcsWorktrees: list, vcsMoveWorktree: move, vcsRemoveWorktree: remove }, + commands: { + ...real.commands, + vcsWorktrees: list, + vcsMoveWorktree: move, + vcsRemoveWorktree: remove, + windowOpenRemote, + }, }; }); vi.mock("@/platform/dialog", () => ({ open })); @@ -24,11 +31,15 @@ vi.mock("../dialogs", async (original) => ({ import { WorktreesPanel } from "../gitMenuDialogs"; import { useVcs } from "../store"; import { useProject } from "@/platform/project"; +import { useRemote } from "@/platform/remote"; +import { registerAction } from "@/platform/actions"; const worktrees = [ { path: "/work/app", branch: "main", head: "12345678", main: true, locked: false, prunable: false }, { path: "/work/app-feature", branch: "feature", head: "12345678", main: false, locked: false, prunable: false }, ]; +const ssh = { kind: "ssh", config: "test-linux" } as const; +const wsl = { kind: "wsl", distro: "Ubuntu" } as const; const ok = (data: T) => ({ status: "ok" as const, data }); const fail = (message: string) => ({ status: "error", error: { kind: "invalidInput", message, detail: null } }); @@ -130,3 +141,41 @@ it("keeps the error and selected worktree after force removal fails", async () = expect(await screen.findByRole("alert")).toHaveTextContent(failure); expect(screen.getByRole("treeitem", { name: /feature/ })).toHaveAttribute("aria-selected", "true"); }); + +afterEach(() => useRemote.setState({ session: null })); + +it.each([ + ["toolbar", ssh], + ["double click", ssh], + ["toolbar", wsl], +] as const)("opens a remote worktree via %s with the current target", async (entry, target) => { + useRemote.setState({ + session: { target, root: "/work/app-feature", host: "demo-linux", os: "linux", commands: [] }, + }); + windowOpenRemote.mockReset().mockResolvedValue(ok({ kind: "opened", label: "git-main" })); + render(); + const row = await screen.findByRole("treeitem", { name: /main/ }); + fireEvent.mouseDown(row); + if (entry === "toolbar") fireEvent.click(screen.getByRole("button", { name: "Open in New Window" })); + else fireEvent.doubleClick(row); + await waitFor(() => expect(windowOpenRemote).toHaveBeenCalledExactlyOnceWith(target, "/work/app", true)); + expect(useProject.getState().project?.root).toBe("/work/app-feature"); +}); + +it.each(["toolbar", "double click"])("preserves the local project open via %s", async (entry) => { + useRemote.setState({ session: null }); + windowOpenRemote.mockReset(); + const run = vi.fn(); + const dispose = registerAction({ id: "file.openProjectPath", title: "Open Project Path", run }); + try { + render(); + const row = await screen.findByRole("treeitem", { name: /main/ }); + fireEvent.mouseDown(row); + if (entry === "toolbar") fireEvent.click(screen.getByRole("button", { name: "Open in New Window" })); + else fireEvent.doubleClick(row); + await waitFor(() => expect(run).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ arg: "/work/app" }))); + expect(windowOpenRemote).not.toHaveBeenCalled(); + } finally { + dispose(); + } +}); diff --git a/src/features/vcs/branchOps.ts b/src/features/vcs/branchOps.ts index 93401a2399..c6a1e0a054 100644 --- a/src/features/vcs/branchOps.ts +++ b/src/features/vcs/branchOps.ts @@ -5,6 +5,7 @@ import type { Branch, BranchInfo, BranchUpdateStatus, CheckoutOptions, Worktree import { executeAction } from "@/platform/actions"; import { call, commands } from "@/platform/ipc"; import { notifications } from "@/workbench/contributions"; +import { openWorktree } from "./openWorktree"; import { ask } from "@/workbench/messages"; import { branchNamePrefixes, isFavoriteBranch, pushRecent, shortRemoteName } from "./branches"; import { showCommitRange } from "./CompareBranches"; @@ -154,7 +155,7 @@ async function performCheckout( options = { ...options, ignoreOtherWorktrees: true }; continue; } - if (r.button === "open") await executeAction("file.openProjectPath", path); + if (r.button === "open") await openWorktree(path); return false; } } diff --git a/src/features/vcs/gitMenuDialogs.tsx b/src/features/vcs/gitMenuDialogs.tsx index 68c30b4450..589e0752d6 100644 --- a/src/features/vcs/gitMenuDialogs.tsx +++ b/src/features/vcs/gitMenuDialogs.tsx @@ -2,9 +2,9 @@ import { useEffect, useMemo, useRef, useState } from "react"; import clsx from "clsx"; import type { Branch, BranchInfo, MergeOptions, Remote, Worktree } from "@/bindings"; -import { executeAction } from "@/platform/actions"; import { call, commands } from "@/platform/ipc"; import { notifications } from "@/workbench/contributions"; +import { openWorktree } from "./openWorktree"; import { Button, Checkbox, @@ -890,7 +890,7 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin title="Open in New Window" size="small" disabled={!current} - onClick={() => current && void executeAction("file.openProjectPath", current.path)} + onClick={() => current && void openWorktree(current.path)} /> @@ -912,7 +912,7 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin selected={selectedKeys} multiSelect={false} onSelectionChange={(selection) => setSelected([...selection][0] ?? null)} - onActivate={(n) => n.worktree && void executeAction("file.openProjectPath", n.worktree.path)} + onActivate={(n) => n.worktree && void openWorktree(n.worktree.path)} className={listClassName ?? styles.worktreeListDialog} aria-label="Worktrees" /> diff --git a/src/features/vcs/openWorktree.ts b/src/features/vcs/openWorktree.ts new file mode 100644 index 0000000000..c456c4a0a4 --- /dev/null +++ b/src/features/vcs/openWorktree.ts @@ -0,0 +1,29 @@ +import { executeAction } from "@/platform/actions"; +import { t } from "@/platform/i18n"; +import { call, commands, isCancelled } from "@/platform/ipc"; +import { useRemote } from "@/platform/remote"; +import { notifications } from "@/workbench/contributions"; + +/** + * Opens worktree `path` in a new window. In an SSH or WSL session the path is on that + * machine, so the window connects there instead of opening it as a local folder. + */ +export async function openWorktree(path: string): Promise { + const target = useRemote.getState().session?.target; + if (target?.kind !== "ssh" && target?.kind !== "wsl") { + await executeAction("file.openProjectPath", path); + return; + } + try { + await call(commands.windowOpenRemote(target, path, true)); + } catch (error) { + if (isCancelled(error)) return; + notifications().notify({ + level: "error", + group: "vcs", + userInitiated: true, + title: t("app.window.openFailed", { name: path }), + body: error instanceof Error ? error.message : String(error), + }); + } +} From aa1326496b5e10a373a863184f6aaecd51aefaf4 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 10:20:51 +0800 Subject: [PATCH 04/14] Show both commit ranges in Git branch comparisons (#4642) Git branch comparison shows both commit ranges side by side in resizable panes. Verified with e2e branchCompareLayout, full vitest and typecheck. --- e2e/branchCompareLayout.spec.ts | 71 +++++++++++++ src/features/vcs/CompareBranches.module.css | 81 ++++++++++++++ src/features/vcs/CompareBranches.tsx | 111 ++++++++++++-------- src/platform/locales/text/en.json | 1 + src/platform/locales/text/es.json | 1 - src/platform/locales/text/fr.json | 1 - src/platform/locales/text/ko.json | 1 - src/platform/locales/text/pl.json | 1 - src/platform/locales/text/pt.json | 1 - src/platform/locales/text/zh.json | 2 +- 10 files changed, 224 insertions(+), 47 deletions(-) create mode 100644 e2e/branchCompareLayout.spec.ts create mode 100644 src/features/vcs/CompareBranches.module.css diff --git a/e2e/branchCompareLayout.spec.ts b/e2e/branchCompareLayout.spec.ts new file mode 100644 index 0000000000..9137af23ba --- /dev/null +++ b/e2e/branchCompareLayout.spec.ts @@ -0,0 +1,71 @@ +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +test("Branch comparison keeps both commit ranges and the diff action visible", async ({ workbench: page }) => { + const branch = "feature/settlement-reconciliation-and-international-ledger-reporting"; + const current = "feature/review-quarterly-settlement-audit"; + const incomingSubject = "Keep regional settlement references stable during the report export"; + const outgoingSubject = "Preserve the audit trail for settlement retries"; + await page.setViewportSize({ width: 1120, height: 760 }); + await stubDesktop(page); + await page.evaluate( + async ({ branch, current, incomingSubject, outgoingSubject }) => { + const root = "/dev/acme-api"; + const branchInfo = { + head: current, + headCommit: "b".repeat(40), + upstream: null, + ahead: 0, + behind: 0, + operation: null, + }; + const entry = (letter: string, summary: string) => ({ + id: letter.repeat(40), + shortId: letter.repeat(8), + parents: ["a".repeat(40)], + refs: [], + summary, + message: summary + "\n\nUpdate the audit report context.", + author: "Sam Rivera", + email: "sam@example.invalid", + timeMs: 1795100000000, + }); + const h = window.__ipc.handlers; + h.vcs_roots = () => [{ root, ...branchInfo }]; + h.vcs_branch_info = () => branchInfo; + h.vcs_status = () => []; + h.vcs_log = ({ query }) => + (query as { range: string }).range === `HEAD..${branch}` + ? [entry("c", incomingSubject)] + : [entry("b", outgoingSubject)]; + h.window_open_comparison = () => null; + const store = "/src/features/vcs/store.ts"; + const { useVcs } = await import(/* @vite-ignore */ store); + useVcs.setState({ available: true, root, repo: root, roots: [root], branch: branchInfo }); + const path = "/src/features/vcs/CompareBranches.tsx"; + (await import(/* @vite-ignore */ path)).showCompareBranches(branch); + }, + { branch, current, incomingSubject, outgoingSubject }, + ); + const dialog = page.getByRole("dialog", { name: new RegExp(`Compare ${current}`) }); + await expect(dialog.getByRole("listbox")).toHaveCount(2); + const incoming = dialog.getByRole("listbox", { name: `In ${branch}, not in ${current}` }); + const outgoing = dialog.getByRole("listbox", { name: `In ${current}, not in ${branch}` }); + await expect(incoming.getByText(incomingSubject, { exact: true })).toBeVisible(); + await expect(outgoing.getByText(outgoingSubject, { exact: true })).toBeVisible(); + const divider = dialog.getByRole("separator", { name: "Resize branch comparison panes" }); + await expect(divider).toHaveAttribute("aria-orientation", "horizontal"); + const start = (await divider.boundingBox())!.y; + await divider.focus(); + await page.keyboard.press("ArrowDown"); + await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThan(start + 1); + + await page.setViewportSize({ width: 440, height: 660 }); + const heading = dialog.getByRole("heading", { name: new RegExp(`In ${branch}`) }); + await expect.poll(() => heading.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + await expect(incoming.getByRole("option")).toBeVisible(); + await expect(outgoing.getByRole("option")).toBeVisible(); + await dialog.getByRole("button", { name: "Show Diff", exact: true }).click(); + await expect + .poll(() => ipcCalls(page, "window_open_comparison")) + .toMatchObject([{ comparison: { from: { rev: branch }, to: { rev: "HEAD" }, repo: "/dev/acme-api" } }]); +}); diff --git a/src/features/vcs/CompareBranches.module.css b/src/features/vcs/CompareBranches.module.css new file mode 100644 index 0000000000..f1d008109a --- /dev/null +++ b/src/features/vcs/CompareBranches.module.css @@ -0,0 +1,81 @@ +.dialog { + height: min(540px, calc(100vh - 48px)); +} + +.ranges { + flex: 1; + min-height: 0; +} + +.range, +.list { + display: flex; + flex-direction: column; + min-height: 0; +} + +.range { + height: 100%; +} + +.list { + flex: 1; +} + +.rangeHeader { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--space-2); + padding: var(--space-2) var(--space-3); + border-bottom: 1px solid var(--border-strong); + background: var(--bg-elev); +} + +.rangeHeader h3 { + min-width: 0; + margin: 0; + overflow-wrap: anywhere; + font-size: var(--fs-ui); + font-weight: 500; +} + +.count, +.metadata { + color: var(--fg-secondary); + font-size: var(--fs-small); +} + +.count { + font-variant-numeric: tabular-nums; +} + +.commit { + display: flex; + flex: 1; + flex-direction: column; + gap: var(--space-0-5); + min-width: 0; +} + +.subject, +.author { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.metadata { + display: flex; + align-items: baseline; + gap: var(--space-2); +} + +.date { + flex-shrink: 0; +} + +.error { + padding: var(--space-3); + overflow-wrap: anywhere; +} diff --git a/src/features/vcs/CompareBranches.tsx b/src/features/vcs/CompareBranches.tsx index 461cd55529..71f503bd21 100644 --- a/src/features/vcs/CompareBranches.tsx +++ b/src/features/vcs/CompareBranches.tsx @@ -3,12 +3,13 @@ import { useEffect, useState } from "react"; import type { Commit } from "@/bindings"; import { executeAction } from "@/platform/actions"; import { call, commands } from "@/platform/ipc"; -import { Dialog, List, Spinner, Tabs, T, tooltipAttrs } from "@/ui"; +import { Dialog, List, Spinner, SplitGroup, SplitHandle, SplitPanel, T, tooltipAttrs } from "@/ui"; import { openDialog } from "./dialogs"; import { formatTime } from "./model"; import { showCompareRevisions } from "./operations"; import { currentRepo, useVcs } from "./store"; import styles from "./common.module.css"; +import compareStyles from "./CompareBranches.module.css"; import { tx } from "@/platform/i18n"; import { useRowHeight } from "@/ui/density"; @@ -69,16 +70,18 @@ function RangeDialog(props: { title: string; from: string; to: string; repo: str function CommitList({ commits, - error, + error = null, + rangeLabel, onClose, }: { commits: Commit[] | null; - error: string | null; + error?: string | null; + rangeLabel?: string; onClose: () => void; }) { - const rowHeight = useRowHeight(22); + const rowHeight = useRowHeight(rangeLabel ? 42 : 22); return ( -
+
{error ? (
{error} @@ -92,7 +95,7 @@ function CommitList({ items={commits} getKey={(c) => c.id} rowHeight={rowHeight} - aria-label="Commits" + aria-label={rangeLabel ?? "Commits"} className={styles.grow} empty={ @@ -103,27 +106,53 @@ function CommitList({ onClose(); void executeAction("vcs.showCommit", c); }} - renderItem={(c) => ( - - {c.shortId} - - {c.summary} + renderItem={(c) => + rangeLabel ? ( +
+ + {c.summary} + +
+ {c.shortId} + {c.author} + {formatTime(c.timeMs)} +
+
+ ) : ( + + {c.shortId} + + {c.summary} + + {c.author} + {formatTime(c.timeMs)} - {c.author} - {formatTime(c.timeMs)} -
- )} + ) + } /> )}
); } +function CompareRange({ label, commits, onClose }: { label: string; commits: Commit[] | null; onClose: () => void }) { + return ( + +
+
+

{label}

+ {commits && {commits.length}} +
+ +
+
+ ); +} + function CompareDialog({ branch, current, onClose }: { branch: string; current: string; onClose: () => void }) { const [repo] = useState(currentRepo); const [data, setData] = useState<{ incoming: Commit[]; outgoing: Commit[] } | null>(null); const [error, setError] = useState(null); - const [tab, setTab] = useState("incoming"); useEffect(() => { let alive = true; Promise.all([commitsBetween("HEAD", branch, repo), commitsBetween(branch, "HEAD", repo)]) @@ -134,17 +163,17 @@ function CompareDialog({ branch, current, onClose }: { branch: string; current: return () => { alive = false; }; - }, [branch]); - const list = data ? (tab === "incoming" ? data.incoming : data.outgoing) : []; + }, [branch, repo]); return ( { onClose(); // Whole-project diff: every file that differs between the branches. - showCompareRevisions(branch, "HEAD", branch, current); + showCompareRevisions(branch, "HEAD", branch, current, repo); }, }, { label: "Close", role: "cancel" }, ]} > - - + {error ? ( +
+ {error} +
+ ) : ( + + + + + + )}
); } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 421a4ae7d7..39ef960503 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1,6 +1,7 @@ { "Inspection details": "Inspection details", "Resize inspection panes": "Resize inspection panes", + "Resize branch comparison panes": "Resize branch comparison panes", "Resize inspection description": "Resize inspection description", "Table actions": "Table actions", "Table pages": "Table pages", diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 43d982ebf1..300ba6cfa0 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -679,7 +679,6 @@ "Detecting…": "Detectando…", "Diff": "Diferencias", "Different tool window background": "Fondo diferente para las ventanas de herramientas", - "Direction": "Dirección", "Directory": "Directorio", "Staging State": "Estado de preparación (stage)", "Staged Changes": "Cambios preparados (staged)", diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index e036b0da4a..03a87d167d 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -620,7 +620,6 @@ "Detecting…": "Détection…", "Diff": "Diff", "Different tool window background": "Arrière-plan distinct pour les fenêtres d'outils", - "Direction": "Sens", "Directory": "Répertoire", "Directory (relative to project root)": "Répertoire (relatif à la racine du projet)", "Directory Mappings": "Associations de répertoires", diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 6ea769967b..922fec95ca 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -715,7 +715,6 @@ "Detecting installations": "설치 항목 감지 중", "Detecting…": "감지 중…", "Different tool window background": "도구 창 배경을 다르게 표시", - "Direction": "방향", "Directory": "디렉터리", "Staging State": "스테이징 상태", "Staged Changes": "스테이징된 변경 사항", diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 987f9fe1f7..e2f8cbce10 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -671,7 +671,6 @@ "Detecting…": "Wykrywanie…", "Diff": "Różnice (Diff)", "Different tool window background": "Inne tło okien narzędziowych", - "Direction": "Kierunek", "Directory": "Katalog", "Staging State": "Stan poczekalni (Staging)", "Staged Changes": "Zmiany w poczekalni (Staged)", diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index e3a2b804e6..f037ffa181 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -671,7 +671,6 @@ "Detecting…": "Detectando…", "Diff": "Diff", "Different tool window background": "Plano de fundo diferente para janelas de ferramentas", - "Direction": "Direção", "Directory": "Diretório", "Staging State": "Estado de staging", "Staged Changes": "Alterações no stage", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 4b38660dcd..54835292f5 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1,6 +1,7 @@ { "Inspection details": "检查详情", "Resize inspection panes": "调整检查窗格大小", + "Resize branch comparison panes": "调整分支比较窗格大小", "Resize inspection description": "调整检查说明窗格大小", "Table actions": "表数据操作", "Table pages": "表数据分页", @@ -1272,7 +1273,6 @@ "Detecting…": "正在检测…", "Diff": "差异", "Different tool window background": "不同的工具窗口背景", - "Direction": "方向", "Directory": "目录", "Staging State": "暂存状态", "Staged Changes": "已暂存的更改", From 1b47bc2c14f6adc9d7bbee27c9d00f782a676af3 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 10:20:59 +0800 Subject: [PATCH 05/14] Keep the editor font preview visible while changing settings (#4649) The editor font preview stays visible while changing font settings. Verified with e2e editorFontLayout, full vitest and typecheck. --- e2e/editorFontLayout.spec.ts | 42 +++++++ .../settings/pages/editor/Editor.module.css | 58 ++++++++-- src/features/settings/pages/editor/font.tsx | 103 +++++++++++++----- src/platform/locales/text/en.json | 2 + src/platform/locales/text/zh.json | 2 + 5 files changed, 169 insertions(+), 38 deletions(-) create mode 100644 e2e/editorFontLayout.spec.ts diff --git a/e2e/editorFontLayout.spec.ts b/e2e/editorFontLayout.spec.ts new file mode 100644 index 0000000000..95cb9e44b5 --- /dev/null +++ b/e2e/editorFontLayout.spec.ts @@ -0,0 +1,42 @@ +import { expect, test } from "./fixtures"; + +test("Editor Font keeps the preview in view while editing and resizing the controls", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1200, height: 760 }); + await page.keyboard.press("Meta+,"); + const settings = page.getByRole("dialog", { name: "Settings", exact: true }); + const search = settings.getByRole("textbox", { name: "Search settings" }); + await search.fill("Show only monospaced fonts"); + await settings.getByRole("treeitem", { name: "Font", exact: true, level: 2 }).click(); + await search.clear(); + + const divider = settings.getByRole("separator", { name: "Resize font preview" }); + const options = settings.getByRole("region", { name: "Font options", exact: true }); + const preview = settings.getByRole("textbox", { name: "Font preview", exact: true }); + const font = options.getByRole("combobox", { name: "Font", exact: true }); + await expect(divider).toHaveAttribute("aria-orientation", "vertical"); + expect((await font.boundingBox())!.x).toBeLessThan((await preview.boundingBox())!.x); + await expect.poll(() => preview.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + + await preview.fill("function main() { return 42; }"); + await options.getByRole("textbox", { name: "Size", exact: true }).fill("18"); + await options.getByRole("textbox", { name: "Line height", exact: true }).fill("25"); + await expect(preview).toHaveCSS("font-size", "18px"); + await expect(preview).toHaveCSS("line-height", "25px"); + + await page.setViewportSize({ width: 520, height: 620 }); + await expect(divider).toHaveAttribute("aria-orientation", "horizontal"); + expect((await font.boundingBox())!.y).toBeLessThan((await preview.boundingBox())!.y); + await expect(preview).toHaveValue("function main() { return 42; }"); + const y = (await divider.boundingBox())!.y; + await divider.press("ArrowDown"); + await expect.poll(async () => (await divider.boundingBox())!.y).toBeGreaterThan(y + 1); + + await search.fill("Fallback font"); + const fallback = options.getByRole("combobox", { name: "Fallback font", exact: true }); + await fallback.scrollIntoViewIfNeeded(); + await expect(fallback).toBeInViewport(); + await fallback.fill("Consolas"); + await expect(preview).toHaveCSS("font-family", /Consolas/); + await expect(preview).toBeInViewport(); + await expect.poll(() => options.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); +}); diff --git a/src/features/settings/pages/editor/Editor.module.css b/src/features/settings/pages/editor/Editor.module.css index 2a9a864162..33456d6148 100644 --- a/src/features/settings/pages/editor/Editor.module.css +++ b/src/features/settings/pages/editor/Editor.module.css @@ -121,6 +121,24 @@ } /* Font page */ +.fontPage { + height: 100%; + min-height: 240px; + min-width: 0; + overflow: hidden; + border: 1px solid var(--border); + border-radius: var(--radius-small); +} +.fontSplit { + height: 100%; +} +.fontOptions { + container: font-options / inline-size; + height: 100%; + min-height: 0; + overflow-y: auto; + padding: var(--space-2) var(--space-3) var(--space-3); +} .fontFamily { display: flex; align-items: center; @@ -128,29 +146,51 @@ gap: var(--space-2); min-width: 0; } -.fontSelect { +.fontSelect, +.fontWeight { width: 240px; max-width: 100%; } +@container font-options (max-width: 380px) { + .fontRow { + display: flex; + flex-direction: column; + align-items: stretch; + gap: var(--space-1); + margin-bottom: var(--space-1); + } + .fontRow > label { + padding-top: 0; + overflow-wrap: anywhere; + white-space: normal; + } +} .previewTitle { - margin: 18px 0 6px; - color: var(--fg-strong); + flex: none; + padding: var(--space-1) var(--space-3); + border-bottom: 1px solid var(--border); + color: var(--fg-secondary); + font-size: var(--fs-small); } .previewArea { + flex: 1; font-weight: var(--fw-code); width: 100%; - min-height: 240px; - resize: vertical; + min-height: 0; + resize: none; box-sizing: border-box; - padding: 8px 10px; + padding: var(--space-2) var(--space-3); border: none; - border-radius: var(--radius-small); - box-shadow: inset 0 0 0 1px var(--border-strong); background: var(--bg-editor, var(--bg-island)); color: var(--fg-editor, var(--fg)); - white-space: pre; + white-space: pre-wrap; + overflow-wrap: anywhere; outline: none; } +.previewArea:focus-visible { + outline: 1px solid var(--focus-ring); + outline-offset: -1px; +} /* Color Scheme page */ .schemeRow { diff --git a/src/features/settings/pages/editor/font.tsx b/src/features/settings/pages/editor/font.tsx index 318beb85a7..812d8b2c56 100644 --- a/src/features/settings/pages/editor/font.tsx +++ b/src/features/settings/pages/editor/font.tsx @@ -4,14 +4,15 @@ */ import { FontPicker } from "../../components/FontPicker"; -import { useId, useState } from "react"; -import { Checkbox, type SelectOption, T } from "@/ui"; +import { useId, useLayoutEffect, useRef, useState } from "react"; +import { Checkbox, type SelectOption, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui"; import { monoFontFamily } from "@/platform/fonts"; import { NumberInput, Row, SearchLabel, Select } from "../../components/Form"; import { useLabelMatch, usePageContext, useSetting } from "../../components/context"; import { FONT_WEIGHTS, fontWeightOf, fontWeightVars } from "@/platform/editorSettings"; import { LIMITS } from "../../model/schema"; -import { editorPage } from "./kit"; +import type { PageSpec } from "../spec"; +import { EditorSections, type EditorSection, sectionLabels } from "./kit"; import styles from "./Editor.module.css"; import { tx } from "@/platform/i18n"; @@ -20,11 +21,12 @@ function FontRow() { const [monoSetting, setMonoOnly] = useSetting("editor.onlyMonospacedFonts"); const monoOnly = monoSetting !== false; const matched = useLabelMatch("Show only monospaced fonts"); + const id = useId(); return ( - + - + ("editor.fontSize"); const [line, setLine] = useSetting("editor.lineHeight"); + const sizeId = useId(); const lineId = useId(); return ( - - + +