From efd4e454ee96937982f0c6d65ad1a31c22374e76 Mon Sep 17 00:00:00 2001 From: Chris Schofield <40196330+ChildishForces@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:26:32 +0000 Subject: [PATCH 01/12] feat(appearance): make Compact Mode match IntelliJ's compact density (#4593) Compact Mode only lowered the title bar and narrowed the stripes: row heights, toolbar widgets and icons were fixed in code, and nothing in JS (where virtualised list row heights are set) could tell whether the mode was on. A small density store now mirrors the setting for JS, and Compact Mode uses IntelliJ's *.compact theme values: tree/list rows 22 (VCS log 24), toolbar widgets 26, toolbar and stripe icons 16, status bar 24, island gap 4, and chrome text 1px smaller. Co-authored-by: ChildishForces <40196330+ChildishForces@users.noreply.github.com> --- docs/en/guide/themes.mdx | 2 +- docs/zh/guide/themes.mdx | 2 +- e2e/compactMode.spec.ts | 48 +++++++++++++++++ src/features/agents/ImportSessionsDialog.tsx | 4 +- src/features/build-tools/ExecutePopup.tsx | 1 - src/features/code-insight/UsagesPopup.tsx | 6 ++- src/features/database/ColumnsPopup.tsx | 4 +- src/features/database/Grid.test.tsx | 1 + src/features/debugger/heap/HeapClasses.tsx | 4 +- .../debugger/heap/editor/BiggestObjects.tsx | 4 +- src/features/debugger/memory/MemoryView.tsx | 4 +- .../github/clone/GitHubCloneSource.tsx | 4 +- src/features/github/create/ChangesPanel.tsx | 4 +- .../github/create/DirectionSelector.tsx | 1 - src/features/github/details/BranchWidget.tsx | 1 - src/features/macros/MacrosDialog.tsx | 1 - src/features/project-tree/NewPopup.tsx | 1 - src/features/run-anything/RunAnything.tsx | 1 - src/features/run/AddConfigPopup.tsx | 6 ++- src/features/run/ConfigChooser.tsx | 10 ++-- src/features/run/Run.module.css | 10 ++-- src/features/run/RunWidget.tsx | 16 +++--- src/features/scratch/ScratchChooser.tsx | 1 - .../search/bookmarks/BookmarkPopups.tsx | 5 +- .../search/everywhere/SearchEverywhere.tsx | 12 +++-- src/features/search/find/FindInFiles.tsx | 6 ++- src/features/search/recent/RecentPopups.tsx | 2 - .../search/structure/StructureView.tsx | 6 ++- .../settings/__tests__/behavior.test.ts | 11 ++++ src/features/settings/appearanceRuntime.ts | 2 + .../settings/dialog/SettingsDialog.tsx | 1 - .../templates/files/NewFileDialog.tsx | 1 - src/features/templates/popup/Chooser.tsx | 4 +- src/features/vcs/BranchFilterPopup.tsx | 6 ++- src/features/vcs/BranchWidget.module.css | 4 +- src/features/vcs/BranchWidget.tsx | 17 +++--- src/features/vcs/CommitChooser.tsx | 4 +- src/features/vcs/CommitView.tsx | 4 +- src/features/vcs/CompareBranches.tsx | 4 +- src/features/vcs/DirectoryCompare.tsx | 5 +- src/features/vcs/MergeRebaseWidget.module.css | 6 +-- src/features/vcs/RevisionChooser.tsx | 1 - src/features/vcs/SyncCommitsPopup.tsx | 4 +- src/features/vcs/TargetBranchInput.tsx | 6 ++- src/features/vcs/conflictsUi.tsx | 4 +- src/features/vcs/dialogs.tsx | 1 - src/features/vcs/log/CommitList.tsx | 15 ++++-- src/features/vcs/log/CommitRow.tsx | 4 +- src/features/vcs/log/GraphCell.tsx | 10 ++-- src/features/vcs/patches.tsx | 4 +- src/features/vcs/remoteUi.tsx | 7 ++- src/styles/tokens.css | 24 +++++++-- src/ui/BarButton.module.css | 8 +-- src/ui/List.tsx | 9 +++- src/ui/Select.tsx | 1 - src/ui/Tabs.module.css | 5 +- src/ui/Tree.tsx | 5 +- src/ui/density.test.tsx | 54 +++++++++++++++++++ src/ui/density.ts | 27 ++++++++++ src/workbench/MainMenu.tsx | 4 +- src/workbench/MainToolbarDialog.tsx | 2 - src/workbench/StatusBar.module.css | 6 ++- src/workbench/TitleBar.module.css | 15 ++++-- src/workbench/TitleBar.tsx | 7 ++- src/workbench/inputDialogs.tsx | 2 - .../toolwindows/ToolWindows.module.css | 6 +++ src/workbench/toolwindows/ToolWindows.tsx | 7 ++- 67 files changed, 356 insertions(+), 118 deletions(-) create mode 100644 e2e/compactMode.spec.ts create mode 100644 src/ui/density.test.tsx create mode 100644 src/ui/density.ts diff --git a/docs/en/guide/themes.mdx b/docs/en/guide/themes.mdx index 5e57627e7..4172563c1 100644 --- a/docs/en/guide/themes.mdx +++ b/docs/en/guide/themes.mdx @@ -26,7 +26,7 @@ The same page also has: - **Different tool window background**: set tool windows apart from the editor. - **Background Image**: an image shown through the project window, with its **Opacity**, **Fill** (scale, original size or tile) and **Anchor**. - **Accessibility**: **Use contrast scrollbars** and **Adjust colors for red-green vision deficiency** (for protanopia and deuteranopia). -- **Compact mode** under **UI Options**. +- **Compact mode** under **UI Options**, also in **View › Appearance**. As in IntelliJ IDEA, it uses shorter tree and list rows, a smaller main toolbar, tool window stripes and status bar, 16px toolbar and stripe icons, and 1px smaller text in the toolbar, status bar, editor tabs and tool window headers. ## Editor color scheme diff --git a/docs/zh/guide/themes.mdx b/docs/zh/guide/themes.mdx index 2ec7e51a2..9e65ba18e 100644 --- a/docs/zh/guide/themes.mdx +++ b/docs/zh/guide/themes.mdx @@ -26,7 +26,7 @@ description: "选择界面主题和编辑器配色方案,导入 IntelliJ 主 - **不同的工具窗口背景**:让工具窗口与编辑器区分开。 - **背景图像**:透过项目窗口显示的图像,可设置 **不透明度**、**填充**(缩放、原始大小或平铺)和 **位置**。 - **辅助功能**:**使用对比度滚动条** 和 **针对红绿色觉缺陷调整颜色**(适用于红色盲和绿色盲)。 -- **UI 选项** 下的 **紧凑模式**。 +- **UI 选项** 下的 **紧凑模式**,也可在 **视图 › 外观** 中切换。与 IntelliJ IDEA 一致:树和列表的行更矮,主工具栏、工具窗口栏和状态栏更紧凑,工具栏和工具窗口栏图标为 16px,工具栏、状态栏、编辑器标签页和工具窗口标题的文字小 1px。 ## 编辑器配色方案 diff --git a/e2e/compactMode.spec.ts b/e2e/compactMode.spec.ts new file mode 100644 index 000000000..33ebe2bea --- /dev/null +++ b/e2e/compactMode.spec.ts @@ -0,0 +1,48 @@ +import { expect, test } from "./fixtures"; + +/** Heights IDEA's Islands theme uses in compact mode (`*.compact` keys), against the defaults. */ +const SIZES = { + normal: { titleBar: 40, treeRow: 24, stripeIcon: 20, statusBar: 34, runButton: 30 }, + compact: { titleBar: 32, treeRow: 22, stripeIcon: 16, statusBar: 24, runButton: 26 }, +}; + +async function measure(page: import("@playwright/test").Page) { + return page.evaluate(() => { + const height = (selector: string) => document.querySelector(selector)?.getBoundingClientRect().height ?? null; + return { + titleBar: height("header"), + treeRow: height('[role="tree"][aria-label="Project"] [role="treeitem"]'), + stripeIcon: height("[data-stripe-button] svg"), + statusBar: height('footer[aria-label="Status bar"]'), + runButton: height("[data-run-chooser] + * button"), + }; + }); +} + +test("Compact Mode shrinks rows, toolbars, stripes and the status bar like IDEA", async ({ workbench: page }, info) => { + // Plain-browser mode has no settings backend: set what the toggle action would store. + const setCompact = (compactMode: boolean) => + page.evaluate(async (compactMode) => { + const projectPath = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ projectPath); + const settings = useProject.getState().settings; + useProject.setState({ + settings: { + ...settings, + appearance: { ...settings?.appearance, theme: "dark", syncWithOs: false, compactMode }, + }, + }); + }, compactMode); + + await setCompact(false); + await expect.poll(() => measure(page)).toEqual(SIZES.normal); + await info.attach("normal", { body: await page.screenshot({ animations: "disabled" }), contentType: "image/png" }); + + await setCompact(true); + await expect(page.locator("html")).toHaveAttribute("data-compact", ""); + await expect.poll(() => measure(page)).toEqual(SIZES.compact); + await info.attach("compact", { body: await page.screenshot({ animations: "disabled" }), contentType: "image/png" }); + + await setCompact(false); + await expect.poll(() => measure(page)).toEqual(SIZES.normal); +}); diff --git a/src/features/agents/ImportSessionsDialog.tsx b/src/features/agents/ImportSessionsDialog.tsx index 20ff9d9b0..74b77d34e 100644 --- a/src/features/agents/ImportSessionsDialog.tsx +++ b/src/features/agents/ImportSessionsDialog.tsx @@ -1,6 +1,7 @@ /** Import Sessions from Other Apps: pick sessions a scan found now, and import them as tasks. */ import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from "react"; import { Button, Dialog, Icon, List, SearchField, Spinner, T, listNavigate, rowSelectionMode, selectRow } from "@/ui"; +import { useRowHeight } from "@/ui/density"; import { hasPrimaryModifier } from "@/platform/keymap"; import { relativePath, useProject } from "@/platform/project"; import { useTx } from "@/platform/i18n"; @@ -41,6 +42,7 @@ function folderOf(cwd: string | null, root: string | undefined): string { function ImportSessionsDialog() { const tx = useTx(); + const rowHeight = useRowHeight(ROW); const listId = useId(); const root = useProject((s) => s.project?.root); const external = useAgents((s) => s.external); @@ -216,7 +218,7 @@ function ImportSessionsDialog() { activeIndex={lead} onSelect={select} isSelected={(r) => !!sel.keys?.has(r.key)} - rowHeight={ROW} + rowHeight={rowHeight} aria-label={tx("Sessions from other apps")} empty={
diff --git a/src/features/build-tools/ExecutePopup.tsx b/src/features/build-tools/ExecutePopup.tsx index fbac2b5cd..f4ce3716e 100644 --- a/src/features/build-tools/ExecutePopup.tsx +++ b/src/features/build-tools/ExecutePopup.tsx @@ -176,7 +176,6 @@ function ExecutePopup({ tool }: { tool: BuildTool }) { }} focusable={false} hoverSelects={false} - rowHeight={24} sectionHeight={28} className={styles.completions} aria-label="Completions" diff --git a/src/features/code-insight/UsagesPopup.tsx b/src/features/code-insight/UsagesPopup.tsx index 3a5fee831..cf1ec02b7 100644 --- a/src/features/code-insight/UsagesPopup.tsx +++ b/src/features/code-insight/UsagesPopup.tsx @@ -12,6 +12,7 @@ import { codePreviewExtensions } from "@/editor/api"; import { basename } from "@/platform/project"; import { shortcutLabel } from "@/platform/keymap"; import { Icon, IconButton, List, Popup, Select, Spinner, fileIconName, listNavigate } from "@/ui"; +import { useRowHeight } from "@/ui/density"; import { openLocation, readFileLines } from "./ipc"; import { dismissUsagesPopup, @@ -83,6 +84,7 @@ const ROW = 24; function UsagesPopupInner() { const { anchor, symbol, groups, note, loading, scope } = useUsagesPopup(); const preview = useUsagesPopupPreview((s) => s.preview); + const rowHeight = useRowHeight(ROW); const all = useMemo(() => groups.flatMap((g) => g.usages), [groups]); const [filter, setFilter] = useState(""); const accessOptions = useUsageAccessOptions(); @@ -210,7 +212,7 @@ function UsagesPopupInner() { )}
void; onClose: () => void; }) { + const rowHeight = useRowHeight(22); const [query, setQuery] = useState(""); const [active, setActive] = useState(0); const shown = filterColumns(props.columns, query); @@ -72,7 +74,7 @@ export function ColumnsPopup(props: { onActivate={(_, i) => pick(i)} focusable={false} hoverSelects - rowHeight={22} + rowHeight={rowHeight} aria-label={tx("Columns")} className={styles.columnsList} empty={{tx("No matching columns")}} diff --git a/src/features/database/Grid.test.tsx b/src/features/database/Grid.test.tsx index 3615906f3..50585a2ba 100644 --- a/src/features/database/Grid.test.tsx +++ b/src/features/database/Grid.test.tsx @@ -30,6 +30,7 @@ vi.mock("@tanstack/react-virtual", () => ({ getTotalSize: () => count * 24, getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 24, key: index })), scrollToIndex: () => {}, + measure: () => {}, }), })); diff --git a/src/features/debugger/heap/HeapClasses.tsx b/src/features/debugger/heap/HeapClasses.tsx index d99cf385c..046d9e951 100644 --- a/src/features/debugger/heap/HeapClasses.tsx +++ b/src/features/debugger/heap/HeapClasses.tsx @@ -14,6 +14,7 @@ import { type ClassSort, } from "./editor/classRows"; import styles from "./HeapSnapshotEditor.module.css"; +import { useRowHeight } from "@/ui/density"; const COLUMNS: ReadonlyArray<{ key: ClassSort; label: string; numeric: boolean; diff?: boolean }> = [ { key: "name", label: "Class", numeric: false }, @@ -66,6 +67,7 @@ export function HeapClasses({ selected: number | null; onSelect: (row: HeapClassRow | null) => void; }) { + const rowHeight = useRowHeight(22); const tx = useTx(); const [query, setQuery] = useState(DEFAULT_CLASS_QUERY); const compared = changes !== null; @@ -124,7 +126,7 @@ export function HeapClasses({ renderItem={(r) => } activeIndex={selected === null ? -1 : rows.findIndex((r) => r.classIndex === selected)} onActiveChange={(i) => onSelect(rows[i] ?? null)} - rowHeight={22} + rowHeight={rowHeight} tableBody={{ headerRows: 1 }} empty={{tx("No matches")}} /> diff --git a/src/features/debugger/heap/editor/BiggestObjects.tsx b/src/features/debugger/heap/editor/BiggestObjects.tsx index 7c92362b5..6f1a0dcbd 100644 --- a/src/features/debugger/heap/editor/BiggestObjects.tsx +++ b/src/features/debugger/heap/editor/BiggestObjects.tsx @@ -6,6 +6,7 @@ import { formatBytes } from "../../memory/rows"; import { useHeapQuery } from "./heapQuery"; import { ObjectText } from "./ObjectText"; import styles from "../HeapSnapshotEditor.module.css"; +import { useRowHeight } from "@/ui/density"; const LIMIT = 100; @@ -21,6 +22,7 @@ export function BiggestObjects({ selected: number | null; onSelect: (object: HeapObjectRow) => void; }) { + const rowHeight = useRowHeight(22); const tx = useTx(); const page = useHeapQuery(`${snapshot}:${cls.classIndex}`, () => call(commands.debugHeapDominators(snapshot, null, cls.classIndex, 0, LIMIT)), @@ -70,7 +72,7 @@ export function BiggestObjects({ )} activeIndex={selected === null ? -1 : rows.findIndex((o) => o.object === selected)} onActiveChange={(i) => rows[i] && onSelect(rows[i])} - rowHeight={22} + rowHeight={rowHeight} tableBody={{ headerRows: 1 }} />
diff --git a/src/features/debugger/memory/MemoryView.tsx b/src/features/debugger/memory/MemoryView.tsx index 62ae0238f..5a15421a2 100644 --- a/src/features/debugger/memory/MemoryView.tsx +++ b/src/features/debugger/memory/MemoryView.tsx @@ -24,6 +24,7 @@ import { keepKeysOnButton } from "./rowButtonKeys"; import { columnsOf, formatBytes, formatCount, formatDelta, queryFor, visibleRows, type SortKey } from "./rows"; import { unavailableText } from "./unavailableText"; import styles from "./MemoryView.module.css"; +import { useRowHeight } from "@/ui/density"; const COLUMNS: ReadonlyArray<{ key: SortKey; label: string; numeric: boolean }> = [ { key: "name", label: "Class", numeric: false }, @@ -105,6 +106,7 @@ function ClassRow({ } export function MemoryView({ session }: { session: DebugSession }) { + const rowHeight = useRowHeight(22); // Also re-renders the reason text, which reads the catalog when called. const tx = useTx(); const id = session.id; @@ -248,7 +250,7 @@ export function MemoryView({ session }: { session: DebugSession }) { onActivate={(r, _i, e) => { if (e.type === "keydown" && listsInstances && paused) showInstancesOf(r.name); }} - rowHeight={22} + rowHeight={rowHeight} tableBody={{ headerRows: 1 }} empty={{tx("No matches")}} /> diff --git a/src/features/github/clone/GitHubCloneSource.tsx b/src/features/github/clone/GitHubCloneSource.tsx index 81844e866..1bec8493f 100644 --- a/src/features/github/clone/GitHubCloneSource.tsx +++ b/src/features/github/clone/GitHubCloneSource.tsx @@ -18,6 +18,7 @@ import { import type { CloneSourceProps } from "@/workbench/contributions"; import { openInBrowser } from "../data/local"; import styles from "./GitHubCloneSource.module.css"; +import { useRowHeight } from "@/ui/density"; type Row = { repo: GhAccountRepo; indices: number[] | null }; @@ -32,6 +33,7 @@ export function matchRepos(repos: readonly GhAccountRepo[], query: string): Row[ } export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSourceProps) { + const rowHeight = useRowHeight(26); const [state, setState] = useState(null); const [query, setQuery] = useState(""); const [attempt, setAttempt] = useState(0); @@ -140,7 +142,7 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource activeIndex={active} onActiveChange={pick} focusable={false} - rowHeight={26} + rowHeight={rowHeight} empty={ {state.repos.length ? "No matching repositories" : "No repositories"} diff --git a/src/features/github/create/ChangesPanel.tsx b/src/features/github/create/ChangesPanel.tsx index a1b2e3212..e657be580 100644 --- a/src/features/github/create/ChangesPanel.tsx +++ b/src/features/github/create/ChangesPanel.tsx @@ -16,6 +16,7 @@ import { prettyDate } from "../ui/prettyDate"; import { commitDescription } from "./model"; import { selectCommit, useCreatePr, type CreateChange } from "./store"; import styles from "./Create.module.css"; +import { useRowHeight } from "@/ui/density"; function Centered({ children, error }: { children: ReactNode; error?: boolean }) { return
{children}
; @@ -170,6 +171,7 @@ function showDiff(all: readonly CreateChange[], first: CreateChange) { } function ChangesTree() { + const rowHeight = useRowHeight(22); const changes = useCreatePr((s) => s.changes); const files = changes?.state === "ok" ? changes.value : null; const roots = useMemo(() => (files ? buildFileTree(files, (f) => f.path) : []), [files]); @@ -219,7 +221,7 @@ function ChangesTree() { selected={selection} onSelectionChange={setSelection} multiSelect - rowHeight={22} + rowHeight={rowHeight} aria-label="Changes" speedSearch onActivate={(n) => n.file && showDiff(ordered, n.file)} diff --git a/src/features/github/create/DirectionSelector.tsx b/src/features/github/create/DirectionSelector.tsx index 275dd37d0..490dbbcbf 100644 --- a/src/features/github/create/DirectionSelector.tsx +++ b/src/features/github/create/DirectionSelector.tsx @@ -178,7 +178,6 @@ function HeadPopup(props: { anchor: HTMLElement; initialRepo: GHRemote; onClose: onActivate={(r) => choose(r)} focusable={false} hoverSelects - rowHeight={24} className={styles.headList} aria-label="Branches" empty={
{tx("Nothing to show")}
} diff --git a/src/features/github/details/BranchWidget.tsx b/src/features/github/details/BranchWidget.tsx index 77d9faa69..551b0fca2 100644 --- a/src/features/github/details/BranchWidget.tsx +++ b/src/features/github/details/BranchWidget.tsx @@ -78,7 +78,6 @@ export function BranchWidget({ getKey={(a) => a} onActivate={(a) => run(a)} hoverSelects - rowHeight={24} aria-label={tx("Branches")} renderItem={(a, state) => (
diff --git a/src/features/macros/MacrosDialog.tsx b/src/features/macros/MacrosDialog.tsx index 17e2f9a42..6842a82d2 100644 --- a/src/features/macros/MacrosDialog.tsx +++ b/src/features/macros/MacrosDialog.tsx @@ -86,7 +86,6 @@ function EditMacrosDialog({ onClose }: { onClose: () => void }) { getKey={(m) => m.name} activeIndex={Math.min(active, saved.length - 1)} onActiveChange={setActive} - rowHeight={24} className={styles.list} aria-label="Macros" empty={ diff --git a/src/features/project-tree/NewPopup.tsx b/src/features/project-tree/NewPopup.tsx index 38167c9b3..4d0e85238 100644 --- a/src/features/project-tree/NewPopup.tsx +++ b/src/features/project-tree/NewPopup.tsx @@ -79,7 +79,6 @@ function NewPopup({ at, items }: { at: { x: number; y: number }; items: MenuItem onActivate={(r) => pick(r)} focusable={false} hoverSelects - rowHeight={24} className={styles.list} aria-label="File types" empty={ diff --git a/src/features/run-anything/RunAnything.tsx b/src/features/run-anything/RunAnything.tsx index aeec1dae7..ecbab5803 100644 --- a/src/features/run-anything/RunAnything.tsx +++ b/src/features/run-anything/RunAnything.tsx @@ -149,7 +149,6 @@ function RunAnythingPopup({ root }: { root: string }) { onActivate={(r) => run(r)} focusable={false} hoverSelects={false} - rowHeight={24} className={styles.rows} aria-label="Run Anything entries" empty={ diff --git a/src/features/run/AddConfigPopup.tsx b/src/features/run/AddConfigPopup.tsx index d26da2316..6eed4fd1d 100644 --- a/src/features/run/AddConfigPopup.tsx +++ b/src/features/run/AddConfigPopup.tsx @@ -1,6 +1,7 @@ import { useMemo, useState, type KeyboardEvent } from "react"; import clsx from "clsx"; import { HighlightedText, Icon, List, Popup, SearchField, fuzzyMatch, listNavigate, T, type PopupAnchor } from "@/ui"; +import { useRowHeight } from "@/ui/density"; import { useRunConfigTypes, runConfigTypes, type RunConfigTypeContribution } from "@/workbench/contributions"; import styles from "./Run.module.css"; @@ -59,6 +60,7 @@ export function AddConfigPopup({ onClose: () => void; }) { const types = useRunConfigTypes((s) => s.types); + const rowHeight = useRowHeight(ROW); const [query, setQuery] = useState(""); const rows = useMemo(() => typeRows(runConfigTypes(types), query), [types, query]); const isSection = (r: TypeRow) => r.kind === "group"; @@ -115,7 +117,7 @@ export function AddConfigPopup({ variant="bare" />
-
+
aria-label="Configuration types" className={styles.chooserList} @@ -127,7 +129,7 @@ export function AddConfigPopup({ onActiveChange={setActive} focusable={false} hoverSelects - rowHeight={ROW} + rowHeight={rowHeight} onActivate={(r) => pick(r)} empty={ diff --git a/src/features/run/ConfigChooser.tsx b/src/features/run/ConfigChooser.tsx index 4c8cf1833..038900719 100644 --- a/src/features/run/ConfigChooser.tsx +++ b/src/features/run/ConfigChooser.tsx @@ -16,6 +16,7 @@ import { T, type MenuItem, } from "@/ui"; +import { useRowHeight } from "@/ui/density"; import type { RunConfig } from "@/platform/ipc"; import { useWorkflowSettings } from "@/platform/workflowSettings"; import { useDebugRunSessions } from "@/workbench/contributions"; @@ -99,7 +100,7 @@ export function buildRows( return rows; } -const rowHeight = (r: Row) => (r.type === "section" && !r.label ? SEPARATOR : ROW); +const heightOf = (r: Row, rowHeight: number) => (r.type === "section" && !r.label ? SEPARATOR : rowHeight); let closedAt = 0; /** The chooser closed within the last moment (a click on its own anchor shouldn't reopen it). */ @@ -145,6 +146,7 @@ export function mnemonics(rows: readonly Row[]): Map { function ConfigChooser() { const mode = useRun((s) => s.chooserMode); + const rowHeight = useRowHeight(ROW); const configs = useRun((s) => s.configs); const selectedId = useRun((s) => s.selectedId); const temporary = useRun((s) => s.temporary); @@ -285,8 +287,8 @@ function ConfigChooser() { }; const height = Math.min( - rows.reduce((sum, r) => sum + rowHeight(r), 0), - 14 * ROW, + rows.reduce((sum, r) => sum + heightOf(r, rowHeight), 0), + 14 * rowHeight, ); // IDEA: a configuration's submenu lists its executors, then Edit and Pin. @@ -366,7 +368,7 @@ function ConfigChooser() { onActiveChange={setActive} focusable={false} hoverSelects - rowHeight={ROW} + rowHeight={rowHeight} onActivate={(r) => activate(r)} renderItem={(r, { active: isActive }) => { if (r.type === "save") { diff --git a/src/features/run/Run.module.css b/src/features/run/Run.module.css index b330f6e3e..113d36018 100644 --- a/src/features/run/Run.module.css +++ b/src/features/run/Run.module.css @@ -338,17 +338,17 @@ align-items: center; gap: var(--space-1); max-width: 260px; - height: 30px; - border-radius: 6px; + height: var(--h-toolbar-widget); + border-radius: var(--radius-toolbar-dropdown); } .widgetDevice { composes: widgetChooser; max-width: 180px; } .widgetButton { - width: 30px; - height: 30px; - border-radius: 6px; + width: var(--titlebar-tool-button); + height: var(--titlebar-tool-button); + border-radius: var(--radius-toolbar-button); } .widgetLoading { display: inline-flex; diff --git a/src/features/run/RunWidget.tsx b/src/features/run/RunWidget.tsx index f8dc1a364..05e1a50f3 100644 --- a/src/features/run/RunWidget.tsx +++ b/src/features/run/RunWidget.tsx @@ -12,9 +12,11 @@ import { CURRENT_FILE, useRun, isLive } from "./store"; import { compoundTargets, selectedTarget } from "./sessionTargets"; import { isDebugOnly } from "./types"; import styles from "./Run.module.css"; +import { useChromeIconSize } from "@/ui/density"; /** Title bar: configuration chooser, Run / Debug, and Rerun / Stop while running. */ export function RunWidget() { + const iconSize = useChromeIconSize(); const tx = useTx(); const label = useRemoteLabel(); const configs = useRun((s) => s.configs); @@ -92,20 +94,20 @@ export function RunWidget() { )} - + {!debugging && ( pick(r)} focusable={false} hoverSelects - rowHeight={24} className={styles.list} aria-label="Languages" empty={ diff --git a/src/features/search/bookmarks/BookmarkPopups.tsx b/src/features/search/bookmarks/BookmarkPopups.tsx index f30b1c1f0..52ad86f56 100644 --- a/src/features/search/bookmarks/BookmarkPopups.tsx +++ b/src/features/search/bookmarks/BookmarkPopups.tsx @@ -29,6 +29,7 @@ import { type PathBookmark, } from "./store"; import styles from "./BookmarkPopups.module.css"; +import { useRowHeight } from "@/ui/density"; export function BookmarkPopupsOverlay() { const chooser = useBookmarkPopups((s) => s.chooser); @@ -186,6 +187,7 @@ export function bookmarkRows( const isSectionRow = (r: Row) => r.kind === "file" || r.kind === "list"; function BookmarksPopup() { + const rowHeight = useRowHeight(22); const items = useBookmarks((s) => s.items); const paths = useBookmarks((s) => s.paths); const lists = useBookmarks((s) => s.lists); @@ -247,8 +249,7 @@ function BookmarksPopup() { jump(r); }} aria-label="Bookmarks" - rowHeight={22} - sectionHeight={24} + rowHeight={rowHeight} empty={{items.length || paths.length ? null : No bookmarks}} renderSection={(r) => r.kind === "file" ? ( diff --git a/src/features/search/everywhere/SearchEverywhere.tsx b/src/features/search/everywhere/SearchEverywhere.tsx index ee507a951..8c9c06f0b 100644 --- a/src/features/search/everywhere/SearchEverywhere.tsx +++ b/src/features/search/everywhere/SearchEverywhere.tsx @@ -1,6 +1,7 @@ import { writeClipboardText } from "@/platform/clipboard"; import { onSearchCategoriesChanged, onEndpointsChanged } from "@/workbench/contributions"; import { useFilePresentation } from "@/ui/filePresentation"; +import { useRowHeight } from "@/ui/density"; import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from "react"; import clsx from "clsx"; import { actionToggled, executeAction, executeActionFrom, getAction } from "@/platform/actions"; @@ -87,7 +88,7 @@ export function claimSearchKeys(input: () => HTMLElement | null): () => void { return registerKeyClaim((e) => e.target === input() && SEARCH_KEYS.has(e.key)); } const ROW = 24; -const MIN_LIST = 10 * ROW; +const MIN_LIST_ROWS = 10; const DEBOUNCE_MS = 60; export function SearchEverywhereOverlay() { @@ -100,6 +101,7 @@ const INITIAL_SELECTION: Selection = { key: null, anchorKey: null, lead: -1, anc function SearchEverywhereDialog() { const tx = useTx(); + const rowHeight = useRowHeight(ROW); const tab = useSearchEverywhere((s) => s.tab); const hint = hintFor(tab, tx); const [tabs, setTabs] = useState(searchTabs); @@ -472,8 +474,8 @@ function SearchEverywhereDialog() { }; // While a query is typed the list keeps a minimum height so the popup doesn't jump with every keystroke. - const minList = parsed.text.trim() && !listing ? MIN_LIST : 0; - const listHeight = Math.max(minList, rows.length * ROW); + const minList = parsed.text.trim() && !listing ? MIN_LIST_ROWS * rowHeight : 0; + const listHeight = Math.max(minList, rows.length * rowHeight); const previewTarget = previewOf(activeRow); const emptyQuery = !parsed.text.trim(); const showEmpty = !rows.length && snap && !snap.loading && (!emptyQuery || tab !== "all"); @@ -521,8 +523,8 @@ function SearchEverywhereDialog() { isSelected={(r) => !!sel.keys?.has(r.key)} onActivate={(r, _i, e) => activate(r, (e as MouseEvent).shiftKey)} focusable={false} - rowHeight={ROW} - sectionHeight={ROW} + rowHeight={rowHeight} + sectionHeight={rowHeight} className={styles.list} aria-label={tx("Results")} renderItem={(r, state) => ( diff --git a/src/features/search/find/FindInFiles.tsx b/src/features/search/find/FindInFiles.tsx index 9cb96adb5..e7c36a4b5 100644 --- a/src/features/search/find/FindInFiles.tsx +++ b/src/features/search/find/FindInFiles.tsx @@ -37,6 +37,7 @@ import { type MenuItem, T, } from "@/ui"; +import { useRowHeight } from "@/ui/density"; import { maybeEditorService, notifications } from "@/workbench/contributions"; import { confirm } from "@/workbench/messages"; import { basename, dirname, openLocation } from "../common/open"; @@ -144,6 +145,7 @@ function displayDirectory(dir: string, root: string | null): string { function FindInFilesDialog() { const s = useFindPopup(); + const rowHeight = useRowHeight(ROW); const txt = useTxTemplate(); const project = useProject((p) => p.project); const root = project?.workspace?.projects[0] ?? (project?.workspace ? null : (project?.root ?? null)); @@ -591,7 +593,7 @@ function FindInFilesDialog() { openRow(r, e.shiftKey); }} focusable={false} - rowHeight={ROW} + rowHeight={rowHeight} aria-label="Matches" empty={ query ? ( @@ -864,7 +866,7 @@ function FindInFilesDialog() {
{rows.length ? ( - + {resultsBox} diff --git a/src/features/search/recent/RecentPopups.tsx b/src/features/search/recent/RecentPopups.tsx index b4fbac567..5067540ff 100644 --- a/src/features/search/recent/RecentPopups.tsx +++ b/src/features/search/recent/RecentPopups.tsx @@ -387,7 +387,6 @@ function RecentFilesDialog() { }} onActivate={(t) => openTool(t.tw)} focusable={false} - rowHeight={24} aria-label="Tool windows" renderItem={(t) => } /> @@ -414,7 +413,6 @@ function RecentFilesDialog() { isSelected={(f) => effectiveColumn === "files" && !!fileSelection.keys?.has(f.path)} onActivate={(f, _i, e) => openFile(f, e.shiftKey)} focusable={false} - rowHeight={24} aria-label={switcher ? "Open files" : "Recent files"} empty={ paths && ( diff --git a/src/features/search/structure/StructureView.tsx b/src/features/search/structure/StructureView.tsx index d8385c9a7..518685260 100644 --- a/src/features/search/structure/StructureView.tsx +++ b/src/features/search/structure/StructureView.tsx @@ -17,6 +17,7 @@ import { type TreeHandle, T, } from "@/ui"; +import { useRowHeight } from "@/ui/density"; import type { OutlineItem } from "@/platform/ipc"; import { useShownLine } from "@/editor/api"; import { badgeKind, basename, openLocation } from "../common/open"; @@ -364,6 +365,7 @@ const POPUP_ROW = 22; function FileStructureDialog() { useLiveOutline(); + const rowHeight = useRowHeight(POPUP_ROW); const path = useOutline((s) => s.path); const items = useOutline((s) => s.items); const loading = useOutline((s) => s.loading); @@ -466,7 +468,7 @@ function FileStructureDialog() { e.preventDefault(); }; - const height = Math.min(420, Math.max(1, visibleCount(filter.nodes, collapsed)) * POPUP_ROW + 8); + const height = Math.min(420, Math.max(1, visibleCount(filter.nodes, collapsed)) * rowHeight + 8); return ( choose(n)} - rowHeight={POPUP_ROW} + rowHeight={rowHeight} indent={16} empty={ diff --git a/src/features/settings/__tests__/behavior.test.ts b/src/features/settings/__tests__/behavior.test.ts index 6e9d76645..15dd3cc72 100644 --- a/src/features/settings/__tests__/behavior.test.ts +++ b/src/features/settings/__tests__/behavior.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { formatPattern, formatTimestamp } from "@/platform/dateFormat"; import { resolveThemeId } from "@/workbench/theme"; +import { useCompactMode } from "@/ui/density"; import { applyAppearanceOptions, nextZoom, SMALL_TREE_INDENT } from "../appearanceRuntime"; import { validateSettings } from "../model/schema"; import { validateGeneralExtras, validateAppearanceExtras, validateNotifications } from "../model/behaviorSchema"; @@ -106,6 +107,16 @@ describe("appearance & behavior settings", () => { expect(validateAppearanceExtras({ navigationBar: "everywhere" }).navigationBar).toBe("statusBar"); }); + it("applies Compact mode to the root attribute and the JS density store", () => { + const root = document.createElement("div"); + applyAppearanceOptions(validateSettings({ appearance: { compactMode: true } }), root); + expect(root.dataset.compact).toBe(""); + expect(useCompactMode.getState()).toBe(true); + applyAppearanceOptions(validateSettings({}), root); + expect(root.dataset.compact).toBeUndefined(); + expect(useCompactMode.getState()).toBe(false); + }); + it("defaults Use smaller indents in trees to off and applies the indent variable", () => { expect(validateAppearanceExtras({}).smallTreeIndents).toBe(false); expect(validateAppearanceExtras({ smallTreeIndents: true }).smallTreeIndents).toBe(true); diff --git a/src/features/settings/appearanceRuntime.ts b/src/features/settings/appearanceRuntime.ts index e03892bce..16d4497b0 100644 --- a/src/features/settings/appearanceRuntime.ts +++ b/src/features/settings/appearanceRuntime.ts @@ -13,6 +13,7 @@ import { usePlatform } from "@/platform/platformInfo"; import { useProject } from "@/platform/project"; import { loadSystemFonts, useSystemFontStore } from "@/platform/systemFonts"; import { setDragRequiresAlt } from "@/ui"; +import { setCompactMode } from "@/ui/density"; import { ZOOM_LIMITS } from "@/platform/zoom"; import { DEFAULT_SETTINGS, validateSettings, type ValidSettings } from "./model/schema"; import type { BackgroundImageValid } from "./model/behaviorSchema"; @@ -45,6 +46,7 @@ export function applyAppearanceOptions(s: ValidSettings, root: HTMLElement = doc } else root.style.removeProperty("--font-ui"); flag(root, "compact", a.compactMode); + setCompactMode(a.compactMode); flag(root, "contrastScrollbars", a.contrastScrollbars); flag(root, "redGreen", a.redGreenVision); flag(root, "toolWindowBg", a.differentToolWindowBackground, "different"); diff --git a/src/features/settings/dialog/SettingsDialog.tsx b/src/features/settings/dialog/SettingsDialog.tsx index 277accaea..be2fc87a7 100644 --- a/src/features/settings/dialog/SettingsDialog.tsx +++ b/src/features/settings/dialog/SettingsDialog.tsx @@ -356,7 +356,6 @@ export function SettingsLayout() { onSelectionChange={(_sel, node) => node && selectPage(node.key)} multiSelect={false} speedSearch={false} - rowHeight={24} empty={
No matches diff --git a/src/features/templates/files/NewFileDialog.tsx b/src/features/templates/files/NewFileDialog.tsx index bac729b97..c248cc74c 100644 --- a/src/features/templates/files/NewFileDialog.tsx +++ b/src/features/templates/files/NewFileDialog.tsx @@ -93,7 +93,6 @@ function TemplateStep({ onActivate={(t) => onPick(t)} focusable={false} hoverSelects - rowHeight={24} className={styles.templateList} aria-label="File templates" renderItem={(t) => ( diff --git a/src/features/templates/popup/Chooser.tsx b/src/features/templates/popup/Chooser.tsx index 274230747..0a1cb8e52 100644 --- a/src/features/templates/popup/Chooser.tsx +++ b/src/features/templates/popup/Chooser.tsx @@ -4,6 +4,7 @@ import { HighlightedText, List, Popup, fuzzyMatch, listNavigate } from "@/ui"; import { closeChooser, useChooser, type ChooserItem, type ChooserRequest } from "./store"; import styles from "./Chooser.module.css"; import { tx } from "@/platform/i18n"; +import { useRowHeight } from "@/ui/density"; /** Overlay contribution: renders the pending chooser, if any. */ export function ChooserHost() { @@ -57,6 +58,7 @@ function MnemonicLabel({ item }: { item: ChooserItem }) { } function ChooserPopup({ request }: { request: ChooserRequest }) { + const rowHeight = useRowHeight(22); const [filter, setFilter] = useState(request.filter ?? ""); const rows = useMemo(() => filterChooserItems(request.items, filter), [request.items, filter]); const [active, setActive] = useState(() => @@ -129,7 +131,7 @@ function ChooserPopup({ request }: { request: ChooserRequest }) { renderSection={(r) =>
{r.item.label}
} focusable={false} hoverSelects - rowHeight={22} + rowHeight={rowHeight} className={styles.list} aria-label={request.title} empty={
{request.emptyText ?? tx("Nothing to show")}
} diff --git a/src/features/vcs/BranchFilterPopup.tsx b/src/features/vcs/BranchFilterPopup.tsx index 99f3e7376..2e4ca58b2 100644 --- a/src/features/vcs/BranchFilterPopup.tsx +++ b/src/features/vcs/BranchFilterPopup.tsx @@ -2,6 +2,7 @@ import clsx from "clsx"; import { useEffect, useMemo, useState, type KeyboardEvent } from "react"; import type { Branch } from "@/bindings"; import { HighlightedText, Icon, List, Popup, SearchField, T, firstSelectable, fuzzyMatch, listNavigate } from "@/ui"; +import { useRowHeight } from "@/ui/density"; import { tx } from "@/platform/i18n"; import { isFavoriteBranch, sortLocal, sortRemote } from "./branches"; import { loadFavoriteBranches, useFavoriteBranches } from "./branchOps"; @@ -91,6 +92,7 @@ export function BranchFilterPopup({ onSelectMany: () => void; onClose: () => void; }) { + const rowHeight = useRowHeight(ROW_HEIGHT); const [query, setQuery] = useState(""); const [active, setActive] = useState(0); const [expanded, setExpanded] = useState>(new Set()); @@ -127,7 +129,7 @@ export function BranchFilterPopup({ setActive(next); } }; - const height = Math.min(MAX_LIST_HEIGHT, Math.max(ROW_HEIGHT * 3, rows.length * ROW_HEIGHT)); + const height = Math.min(MAX_LIST_HEIGHT, Math.max(rowHeight * 3, rows.length * rowHeight)); return ( +const listHeight = (rows: readonly { type: string; key: string }[], rowHeight: number) => Math.min( 440, Math.max( - ROW_HEIGHT * 3, + rowHeight * 3, rows.reduce( - (h, r) => h + (r.type === "section" && r.key.startsWith("separator:") ? SEPARATOR_HEIGHT : ROW_HEIGHT), + (h, r) => h + (r.type === "section" && r.key.startsWith("separator:") ? SEPARATOR_HEIGHT : rowHeight), 0, ), ), @@ -422,6 +423,7 @@ interface BranchesPanelProps { /** Search, actions and the branches of one repository (the selected one, or `root`). */ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack }: BranchesPanelProps) { + const rowHeight = useRowHeight(ROW_HEIGHT); const selected = useVcs((s) => s.repo); const live = root === undefined || selected === root; const storeBranches = useVcs((s) => s.branches); @@ -555,7 +557,7 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack } {!root && } {!root && 0} />}
-
+
r.key} @@ -573,7 +575,7 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack } onActivate={(_r, i) => activate(i)} focusable={false} hoverSelects - rowHeight={ROW_HEIGHT} + rowHeight={rowHeight} aria-label="Branches" className={styles.list} empty={{loaded ? tx("No matching branches") : tx("Loading…")}} @@ -618,6 +620,7 @@ function SubMenu({ * (acting on all of them) or, when their branches differ, the current repository's. */ function MultiRepoPanel({ onClose, actions: popupActions }: { onClose: () => void; actions: readonly PopupAction[] }) { + const rowHeight = useRowHeight(ROW_HEIGHT); const roots = useVcs((s) => s.roots); const heads = useVcs((s) => s.heads); const operations = useVcs((s) => s.operations); @@ -805,7 +808,7 @@ function MultiRepoPanel({ onClose, actions: popupActions }: { onClose: () => voi 0} />
-
+
r.key} @@ -823,7 +826,7 @@ function MultiRepoPanel({ onClose, actions: popupActions }: { onClose: () => voi onActivate={(_r, i) => activate(i)} focusable={false} hoverSelects - rowHeight={ROW_HEIGHT} + rowHeight={rowHeight} aria-label="Repositories and branches" className={styles.list} empty={ diff --git a/src/features/vcs/CommitChooser.tsx b/src/features/vcs/CommitChooser.tsx index 90115f3f3..a7eaf894c 100644 --- a/src/features/vcs/CommitChooser.tsx +++ b/src/features/vcs/CommitChooser.tsx @@ -3,6 +3,7 @@ import type { Commit } from "@/bindings"; import { Dialog, List, SearchField } from "@/ui"; import { openDialog } from "./dialogs"; import { commitKey } from "./multiRoot"; +import { useRowHeight } from "@/ui/density"; export function chooseLogCommit(commits: Commit[], title: string): Promise { return new Promise((resolve) => { @@ -28,6 +29,7 @@ function CommitChooser({ title: string; onDone: (commit: Commit | null) => void; }) { + const rowHeight = useRowHeight(26); const [query, setQuery] = useState(""); const shown = commits.filter((c) => `${c.id} ${c.summary} ${c.author}`.toLocaleLowerCase().includes(query.toLocaleLowerCase()), @@ -41,7 +43,7 @@ function CommitChooser({ getKey={commitKey} renderItem={(c) => `${c.shortId} ${c.summary} — ${c.author}`} onActivate={onDone} - rowHeight={26} + rowHeight={rowHeight} aria-label={title} />
diff --git a/src/features/vcs/CommitView.tsx b/src/features/vcs/CommitView.tsx index 89e56df56..e3e6d16dc 100644 --- a/src/features/vcs/CommitView.tsx +++ b/src/features/vcs/CommitView.tsx @@ -112,6 +112,7 @@ import { ShelfPanel, loadShelves, useShelf } from "./shelf"; import { existsOnDisk, refreshNow, repoName, selectRepo, useVcs } from "./store"; import { saveVcsSetting } from "./settingsUi"; import styles from "./CommitView.module.css"; +import { useRowHeight } from "@/ui/density"; /** MIME type of files dragged onto a change list (absolute paths, newline-separated). */ const CHANGES_MIME = "application/x-openidea-changes"; @@ -1381,6 +1382,7 @@ async function stashFileChanges(stash: StashEntry): Promise { } export function StashesPanel() { + const rowHeight = useRowHeight(22); const repo = useVcs((s) => s.repo); const repos = useVcs((s) => s.roots); const version = useVcs((s) => s.version); @@ -1491,7 +1493,7 @@ export function StashesPanel() { loadChildren={loadFiles} selected={useMemo(() => new Set(selectedKey ? [selectedKey] : []), [selectedKey])} multiSelect={false} - rowHeight={22} + rowHeight={rowHeight} aria-label="Stashes" className={styles.stashList} empty={{error ?? (loaded ? tx("No stashes") : tx("Loading…"))}} diff --git a/src/features/vcs/CompareBranches.tsx b/src/features/vcs/CompareBranches.tsx index c62eb5b57..461cd5552 100644 --- a/src/features/vcs/CompareBranches.tsx +++ b/src/features/vcs/CompareBranches.tsx @@ -10,6 +10,7 @@ import { showCompareRevisions } from "./operations"; import { currentRepo, useVcs } from "./store"; import styles from "./common.module.css"; import { tx } from "@/platform/i18n"; +import { useRowHeight } from "@/ui/density"; const LIMIT = 2000; @@ -75,6 +76,7 @@ function CommitList({ error: string | null; onClose: () => void; }) { + const rowHeight = useRowHeight(22); return (
{error ? ( @@ -89,7 +91,7 @@ function CommitList({ c.id} - rowHeight={22} + rowHeight={rowHeight} aria-label="Commits" className={styles.grow} empty={ diff --git a/src/features/vcs/DirectoryCompare.tsx b/src/features/vcs/DirectoryCompare.tsx index 83e2463f2..1cd2b4933 100644 --- a/src/features/vcs/DirectoryCompare.tsx +++ b/src/features/vcs/DirectoryCompare.tsx @@ -28,6 +28,7 @@ import { compareFilesData, displayPath } from "./compareData"; import type { DirectoryCompareData } from "./directoryCompareKind"; import { formatSize, formatTime } from "./model"; import styles from "./DirectoryCompare.module.css"; +import { useRowHeight } from "@/ui/density"; const DiffEditor = lazyComponent(() => import("./DiffEditor").then((m) => m.DiffEditor)); @@ -153,6 +154,7 @@ function Side({ entry, side, folder }: { entry: DirectoryCompareEntry; side: "le } export function DirectoryCompare({ left, right }: { left: string; right: string }) { + const rowHeight = useRowHeight(22); const t = useTx(); const [entries, setEntries] = useState([]); const [current, setCurrent] = useState(null); @@ -338,8 +340,7 @@ export function DirectoryCompare({ left, right }: { left: string; right: string onActivate={(r, _i, e) => { if ("entry" in r && e.type === "keydown") open(r.entry); }} - rowHeight={22} - sectionHeight={24} + rowHeight={rowHeight} tableBody={{ headerRows: 1 }} empty={ !busy && !cancelled && !error ? ( diff --git a/src/features/vcs/MergeRebaseWidget.module.css b/src/features/vcs/MergeRebaseWidget.module.css index f44996f34..8ccec5e02 100644 --- a/src/features/vcs/MergeRebaseWidget.module.css +++ b/src/features/vcs/MergeRebaseWidget.module.css @@ -9,11 +9,11 @@ display: inline-flex; align-items: center; justify-content: center; - width: 30px; - height: 30px; + width: var(--titlebar-tool-button); + height: var(--titlebar-tool-button); padding: 0; border: 0; - border-radius: 6px; + border-radius: var(--radius-toolbar-button); cursor: pointer; } .go { diff --git a/src/features/vcs/RevisionChooser.tsx b/src/features/vcs/RevisionChooser.tsx index 9269e5bb1..a62c4371a 100644 --- a/src/features/vcs/RevisionChooser.tsx +++ b/src/features/vcs/RevisionChooser.tsx @@ -193,7 +193,6 @@ function Chooser({ renderSection={(i) => {i.rev}} focusable={false} hoverSelects - rowHeight={24} aria-label="Revisions" className={styles.grow} renderItem={(i) => ( diff --git a/src/features/vcs/SyncCommitsPopup.tsx b/src/features/vcs/SyncCommitsPopup.tsx index 64255e109..d9a7909c6 100644 --- a/src/features/vcs/SyncCommitsPopup.tsx +++ b/src/features/vcs/SyncCommitsPopup.tsx @@ -18,6 +18,7 @@ import { currentRepo, useVcs } from "./store"; import { syncRow, syncSections, type SyncBranch, type SyncDirection, type SyncSection } from "./syncCommits"; import styles from "./SyncCommitsPopup.module.css"; import common from "./common.module.css"; +import { useRowHeight } from "@/ui/density"; /** A commit range can be long; the popup shows what git lists, bounded like Compare Branches. */ const LIMIT = 2000; @@ -96,6 +97,7 @@ function SyncCommitsPopup({ anchor: PopupAnchor; onClose: () => void; }) { + const rowHeight = useRowHeight(22); const sections = useMemo(() => syncSections(source.branch, source.direction), [source.branch, source.direction]); const [lists, setLists] = useState(null); const [error, setError] = useState(null); @@ -223,7 +225,7 @@ function SyncCommitsPopup({ onActivate={(row) => { if (row.type === "commit") openDiff(row.commit); }} - rowHeight={22} + rowHeight={rowHeight} aria-label={title} className={styles.list} /> diff --git a/src/features/vcs/TargetBranchInput.tsx b/src/features/vcs/TargetBranchInput.tsx index f9644e384..dd8fcd94e 100644 --- a/src/features/vcs/TargetBranchInput.tsx +++ b/src/features/vcs/TargetBranchInput.tsx @@ -6,6 +6,7 @@ */ import { useMemo, useRef, useState, type KeyboardEvent } from "react"; import { HighlightedText, Icon, Input, List, Popup, fuzzyMatch, listNavigate } from "@/ui"; +import { useRowHeight } from "@/ui/density"; import { useTx } from "@/platform/i18n"; import styles from "./common.module.css"; @@ -75,6 +76,7 @@ export function TargetBranchInput({ remote: string | null; }) { const tx = useTx(); + const rowHeight = useRowHeight(ROW_HEIGHT); const input = useRef(null); const [open, setOpen] = useState(false); // No row is chosen until the user moves in the list: Enter keeps pushing the typed name. @@ -139,7 +141,7 @@ export function TargetBranchInput({ {s.name} ))}
-
+
s.name} @@ -148,7 +150,7 @@ export function TargetBranchInput({ onActivate={(s) => choose(s)} focusable={false} hoverSelects - rowHeight={ROW_HEIGHT} + rowHeight={rowHeight} aria-label={tx("Remote branches")} className={styles.targetList} empty={{tx("No matching remote branches")}} diff --git a/src/features/vcs/conflictsUi.tsx b/src/features/vcs/conflictsUi.tsx index 69d803381..480bcbef3 100644 --- a/src/features/vcs/conflictsUi.tsx +++ b/src/features/vcs/conflictsUi.tsx @@ -15,6 +15,7 @@ import { executeAction } from "@/platform/actions"; import { conflictedFiles, useVcs } from "./store"; import styles from "./common.module.css"; import { tx } from "@/platform/i18n"; +import { useRowHeight } from "@/ui/density"; /** * The stopped rebase / cherry-pick / revert whose conflicts are being resolved from the @@ -64,6 +65,7 @@ export async function acceptSide(f: FileStatus, side: "ours" | "theirs") { } function ConflictsDialog({ onClose }: { onClose: () => void }) { + const rowHeight = useRowHeight(22); const files = useVcs((s) => s.status).filter((f) => f.unstaged === "conflicted"); const root = useVcs((s) => s.root) ?? ""; const op = useVcs((s) => inProgress(s.branch?.operation)); @@ -141,7 +143,7 @@ function ConflictsDialog({ onClose }: { onClose: () => void }) { getKey={(f) => f.path} activeIndex={Math.min(active, files.length - 1)} onActiveChange={setActive} - rowHeight={22} + rowHeight={rowHeight} aria-label="Conflicted files" className={styles.boxList} empty={ diff --git a/src/features/vcs/dialogs.tsx b/src/features/vcs/dialogs.tsx index d31d93473..49234ecae 100644 --- a/src/features/vcs/dialogs.tsx +++ b/src/features/vcs/dialogs.tsx @@ -204,7 +204,6 @@ function PromptDialog(props: PromptOptions & { onDone: (r: PromptResult | null) activeIndex={active} onActivate={acceptPrefix} focusable={false} - rowHeight={24} aria-label={tx("Branch name prefixes")} className={styles.prefixList} renderItem={(prefix, state) => ( diff --git a/src/features/vcs/log/CommitList.tsx b/src/features/vcs/log/CommitList.tsx index 939503e4c..4e1618ebc 100644 --- a/src/features/vcs/log/CommitList.tsx +++ b/src/features/vcs/log/CommitList.tsx @@ -3,6 +3,7 @@ import { setContext } from "@/platform/context"; import { tx } from "@/platform/i18n"; import { call, commands } from "@/platform/ipc"; import { Scrollbar, Spinner, T, hideNativeScrollbar } from "@/ui"; +import { useRowHeight } from "@/ui/density"; import { useGitLogChecks } from "@/workbench/contributions"; import { useVirtualizer } from "@tanstack/react-virtual"; import clsx from "clsx"; @@ -219,6 +220,8 @@ export function CommitList() { const selectedSet = useMemo(() => new Set(selection), [selection]); const revealTick = useGitLog((s) => s.revealTick); const scrollRef = useRef(null); + // Commit rows shrink in compact mode; the column header (the scroll margin) keeps ROW. + const row = useRowHeight(ROW); const selectedIndex = useMemo( () => (selected ? commits.findIndex((c) => commitKey(c) === selected) : -1), [commits, selected], @@ -232,23 +235,24 @@ export function CommitList() { const previous = previousRows.current; previousRows.current = commits; if (!element || previous === commits || (revealTick !== lastRevealed.current && selectedIndex >= 0)) return; - const top = Math.max(0, Math.floor((element.scrollTop - ROW) / ROW)); + const top = Math.max(0, Math.floor((element.scrollTop - ROW) / row)); // Preserve the first surviving visible commit and its pixel offset. for (let i = top; i < previous.length; i++) { const next = commits.findIndex((c) => commitKey(c) === commitKey(previous[i]!)); if (next < 0) continue; - element.scrollTop += (next - i) * ROW; + element.scrollTop += (next - i) * row; break; } - }, [commits, revealTick, selectedIndex]); + }, [commits, revealTick, selectedIndex, row]); const finished = done; const virtualizer = useVirtualizer({ count: commits.length + (finished ? 0 : 1), getScrollElement: () => scrollRef.current, - estimateSize: () => ROW, + estimateSize: () => row, overscan: 8, scrollMargin: ROW, }); + useEffect(() => virtualizer.measure(), [virtualizer, row]); const items = virtualizer.getVirtualItems(); const last = items[items.length - 1]; @@ -581,7 +585,7 @@ export function CommitList() { const c = commits[v.index]; if (!c) return ( -
+
{" "} Loading… @@ -598,6 +602,7 @@ export function CommitList() { fileHistoryTarget={fileHistoryTarget} graph={rows[v.index]} top={v.start - ROW} + height={row} selected={selectedSet.has(commitKey(c))} head={headKeys.has(commitKey(c))} mine={opts.highlightMine && isMine(c, user)} diff --git a/src/features/vcs/log/CommitRow.tsx b/src/features/vcs/log/CommitRow.tsx index 2a853501d..6d18603cf 100644 --- a/src/features/vcs/log/CommitRow.tsx +++ b/src/features/vcs/log/CommitRow.tsx @@ -22,6 +22,7 @@ function CommitRowView({ fileHistoryTarget, graph, top, + height, selected, head, mine, @@ -45,6 +46,7 @@ function CommitRowView({ fileHistoryTarget: string | null; graph: GraphRow | undefined; top: number; + height: number; selected: boolean; head: boolean; mine: boolean; @@ -162,7 +164,7 @@ function CommitRowView({ selected && styles.selected, opts.showColumnDividers && styles.showDividers, )} - style={{ top }} + style={{ top, height }} onMouseDown={(e) => { if (e.shiftKey) e.preventDefault(); // no text selection on range clicks onPick(commitKey(c), e); diff --git a/src/features/vcs/log/GraphCell.tsx b/src/features/vcs/log/GraphCell.tsx index a5150baad..3a365175d 100644 --- a/src/features/vcs/log/GraphCell.tsx +++ b/src/features/vcs/log/GraphCell.tsx @@ -1,4 +1,5 @@ import { tx } from "@/platform/i18n"; +import { useRowHeight } from "@/ui/density"; import { Fragment } from "react"; import styles from "../GitLog.module.css"; import { laneColor, type GraphRow, type GraphSegment } from "../graph"; @@ -38,14 +39,15 @@ export function GraphCell({ onNode?: () => void; interactive?: boolean; }) { - const cy = ROW / 2; + const height = useRowHeight(ROW); + const cy = height / 2; const width = row.width * LANE; const draw = (s: GraphSegment, i: number, up: boolean) => { const fromX = x(s.fromX ?? s.from); const toX = x(s.toX ?? s.to); const path = - seg(fromX, up ? 0 : cy, toX, up ? cy : ROW) + - (s.arrow ? arrowHead(up ? fromX : toX, up ? 0 : ROW, up ? -1 : 1) : ""); + seg(fromX, up ? 0 : cy, toX, up ? cy : height) + + (s.arrow ? arrowHead(up ? fromX : toX, up ? 0 : height, up ? -1 : 1) : ""); const line = ( onHover?.(null)} > diff --git a/src/features/vcs/patches.tsx b/src/features/vcs/patches.tsx index bf70cd790..cd06e201e 100644 --- a/src/features/vcs/patches.tsx +++ b/src/features/vcs/patches.tsx @@ -18,6 +18,7 @@ import { activeList, useChangelists } from "./changelists"; import { currentRepoRoot, useVcs } from "./store"; import styles from "./common.module.css"; import { tx } from "@/platform/i18n"; +import { useRowHeight } from "@/ui/density"; export type PatchOrigin = | { kind: "changes"; files: FileStatus[] } @@ -259,6 +260,7 @@ export async function showApplyPatch(from: "file" | "clipboard", path?: string) } function ApplyPatchDialog({ patch, source, onClose }: { patch: string; source: string; onClose: () => void }) { + const rowHeight = useRowHeight(22); const [repo] = useState(currentRepoRoot); const [files, setFiles] = useState(null); const [error, setError] = useState(null); @@ -316,7 +318,7 @@ function ApplyPatchDialog({ patch, source, onClose }: { patch: string; source: s f.path} - rowHeight={22} + rowHeight={rowHeight} aria-label="Patch files" className={styles.boxList} empty={ diff --git a/src/features/vcs/remoteUi.tsx b/src/features/vcs/remoteUi.tsx index fab20c7de..838ff2cfb 100644 --- a/src/features/vcs/remoteUi.tsx +++ b/src/features/vcs/remoteUi.tsx @@ -30,6 +30,7 @@ import { pushOperation, splitTracked, type PushChoice } from "./pushTarget"; import { currentRepo, currentRepoRoot, loadBranches, refreshNow, repoName, useVcs } from "./store"; import { stripRemotePrefix, TargetBranchInput } from "./TargetBranchInput"; import styles from "./common.module.css"; +import { useRowHeight } from "@/ui/density"; /** Update Project… scope: one repository (`null`: the selected one), else every repository. */ export interface UpdateTarget { @@ -256,6 +257,7 @@ interface MultiPushDialogProps { } function MultiPushDialog({ only, onClose }: MultiPushDialogProps) { + const rowHeight = useRowHeight(22); const allRoots = useVcs((s) => s.roots); const roots = useMemo(() => (only === undefined ? allRoots : allRoots.filter((r) => r === only)), [allRoots, only]); const [repos, setRepos] = useState(null); @@ -474,7 +476,7 @@ function MultiPushDialog({ only, onClose }: MultiPushDialogProps) { selected={new Set(shown ? [shown.key] : [])} multiSelect={false} onSelectionChange={(_sel, lead) => setShown(lead)} - rowHeight={22} + rowHeight={rowHeight} aria-label="Outgoing commits" className={styles.boxList} empty={ @@ -604,6 +606,7 @@ function PushRowTarget(props: { } function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClose: () => void }) { + const rowHeight = useRowHeight(22); const [repo] = useState(currentRepo); const [branch] = useState(() => useVcs.getState().branch); const [branches] = useState(() => useVcs.getState().branches); @@ -737,7 +740,7 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo getKey={(c) => c.id} activeIndex={shownCommit} onActiveChange={setShownCommit} - rowHeight={22} + rowHeight={rowHeight} aria-label="Outgoing commits" className={styles.boxList} empty={{upstream ? tx("Everything is up to date") : tx("No commits")}} diff --git a/src/styles/tokens.css b/src/styles/tokens.css index 11f388efa..2e50f32b5 100644 --- a/src/styles/tokens.css +++ b/src/styles/tokens.css @@ -295,6 +295,8 @@ html { --fs-tiny: 11px; --fs-code: 13px; --fs-input-large: 15px; + /* main toolbar, status bar, tool window headers and editor tabs (IDEA fontSizeOffset) */ + --fs-chrome: var(--fs-ui); --lh-code: 22px; /* metrics (theme JSON at 100%) */ @@ -302,6 +304,8 @@ html { /* IDEA's compact header (HEADER_HEIGHT_DFM), the same in compact mode. */ --h-compact-header: 30px; --titlebar-tool-button: 30px; + /* main toolbar dropdowns: project, VCS branch, run configuration */ + --h-toolbar-widget: 30px; /* tool window stripe button, icons only */ --stripe-icon-button: 30px; --stripe-outer-padding: 4px; @@ -324,6 +328,8 @@ html { --radius-control: 4px; --radius-tab: 6px; --radius-toolbar-button: 6px; + /* main toolbar dropdowns (MainToolbar.Dropdown.arc 12): unchanged in compact mode */ + --radius-toolbar-dropdown: 6px; --radius-floating-toolbar: 3px; --h-floating-toolbar-button: 22px; --floating-toolbar-top: 25px; @@ -1496,18 +1502,30 @@ html { * Appearance options (Settings › Appearance), applied as attributes on :root * by the settings runtime. */ -/* Compact mode: smaller rows, toolbars and tabs. */ +/* + * Compact mode: smaller rows, toolbars and tabs. Values follow IDEA's `*.compact` + * theme keys (Islands): Tree/List.rowHeight 22, MainToolbar.Button.size and + * RunWidget.toolbarHeight 26, Island.borderWidth 4, chrome fontSizeOffset -1. + * Swing `arc` is a diameter, so radii here are half of it. + */ :root[data-compact] { --h-titlebar: 32px; + --titlebar-tool-button: 26px; + --h-toolbar-widget: 26px; --h-header: 32px; --h-tabbar: 32px; --h-tab: 24px; - --h-row: 20px; - --h-list-row: 20px; + --h-row: 22px; + --h-list-row: 22px; --h-statusbar: 24px; --stripe-icon-button: 24px; --h-field: 24px; --h-button: 24px; + --fs-chrome: calc(var(--fs-ui) - 1px); + --island-gap: 4px; + --island-radius: 8px; + --radius-control: 3px; + --radius-toolbar-button: 4px; } /* Use contrast scrollbars. */ :root[data-contrast-scrollbars] { diff --git a/src/ui/BarButton.module.css b/src/ui/BarButton.module.css index 8e453529c..a0be1c16d 100644 --- a/src/ui/BarButton.module.css +++ b/src/ui/BarButton.module.css @@ -23,18 +23,18 @@ } /* Status bar widget (StatusBar.Widget): UI font, secondary text, rounded hover. */ .status { - height: 22px; + height: max(var(--h-statusbar) - 8px, var(--h-control-small)); margin: 0 -2px; padding: 0 6px; color: var(--fg-secondary); - font-size: var(--fs-ui); + font-size: var(--fs-chrome); } /* Main toolbar widget (project / VCS / run configuration). */ .title { - height: 28px; + height: var(--h-toolbar-widget); margin: 0 -4px; padding: 0 8px; - border-radius: var(--radius-toolbar-button, 6px); + border-radius: var(--radius-toolbar-dropdown); color: var(--fg-strong); } .mono { diff --git a/src/ui/List.tsx b/src/ui/List.tsx index e5d9d5e49..dc46d24af 100644 --- a/src/ui/List.tsx +++ b/src/ui/List.tsx @@ -16,6 +16,7 @@ import { } from "react"; import clsx from "clsx"; import { useVirtualizer } from "@tanstack/react-virtual"; +import { useRowHeight } from "./density"; import { rowSelectionMode } from "./rowSelection"; import styles from "./List.module.css"; @@ -133,8 +134,8 @@ export function List({ isSelected, onActivate, onContextMenu, - rowHeight = 24, - sectionHeight = 24, + rowHeight: fixedRowHeight, + sectionHeight: fixedSectionHeight, sectionHeightOf, focusable = true, hoverSelects = false, @@ -154,6 +155,9 @@ export function List({ const scrollRef = useRef(null); const generatedId = useId(); const baseId = id ?? generatedId; + const defaultRowHeight = useRowHeight(); + const rowHeight = fixedRowHeight ?? defaultRowHeight; + const sectionHeight = fixedSectionHeight ?? defaultRowHeight; const virtualizer = useVirtualizer({ count: items.length, getScrollElement: () => scrollRef.current, @@ -161,6 +165,7 @@ export function List({ overscan, getItemKey: (i) => getKey(items[i]!, i), }); + useEffect(() => virtualizer.measure(), [virtualizer, rowHeight, sectionHeight]); const viewportHeight = virtualizer.scrollRect?.height; useEffect(() => { diff --git a/src/ui/Select.tsx b/src/ui/Select.tsx index a452c090b..51312b877 100644 --- a/src/ui/Select.tsx +++ b/src/ui/Select.tsx @@ -253,7 +253,6 @@ export function SelectListbox({ onActivate={(o) => choose(o)} focusable={false} hoverSelects - rowHeight={24} aria-label={given(aria["aria-label"])} className={clsx(styles.list, listClassName)} renderItem={(o) => { diff --git a/src/ui/Tabs.module.css b/src/ui/Tabs.module.css index 6e9ff26b5..498b2e6e2 100644 --- a/src/ui/Tabs.module.css +++ b/src/ui/Tabs.module.css @@ -15,12 +15,13 @@ .editor { --tab-inline-padding: var(--space-2); height: var(--h-header); + font-size: var(--fs-chrome); padding: 0 4px; } .compact { /* Shrinks inside tool window headers so the overflow dropdown can take over. */ flex: 0 1 auto; - height: 28px; + height: var(--h-tab); } .scroller { display: flex; @@ -41,7 +42,7 @@ align-items: stretch; height: calc(100% - 6px); min-height: 22px; - max-height: 28px; + max-height: var(--h-tab); border-radius: var(--radius-tab, 6px); color: var(--fg-strong); transition: diff --git a/src/ui/Tree.tsx b/src/ui/Tree.tsx index 3c57d128b..ac70d5aaa 100644 --- a/src/ui/Tree.tsx +++ b/src/ui/Tree.tsx @@ -38,9 +38,9 @@ import { useGivenTx } from "@/platform/i18n"; import { useTreeReorder, type TreeReorder } from "./treeReorder"; import { startPointerDrag, type DragData } from "./pointerDrag"; import { useTreeDirectoryContext } from "./treeDirectoryContext"; +import { useRowHeight } from "./density"; import { useIconRowHeight } from "./iconAppearance"; -const DEFAULT_ROW_HEIGHT = 24; export type { TreeReorder } from "./treeReorder"; export interface TreeRowState { @@ -353,7 +353,8 @@ export function Tree(props: TreeProps) { const leadIndex = lead != null ? (indexOfKey.get(lead) ?? -1) : -1; const themedRowHeight = useIconRowHeight(); - const rowHeight = fixedRowHeight ?? themedRowHeight ?? DEFAULT_ROW_HEIGHT; + const defaultRowHeight = useRowHeight(); + const rowHeight = fixedRowHeight ?? themedRowHeight ?? defaultRowHeight; const virtualizer = useVirtualizer({ count: rows.length, getScrollElement: () => scrollRef.current, diff --git a/src/ui/density.test.tsx b/src/ui/density.test.tsx new file mode 100644 index 000000000..2c90012a1 --- /dev/null +++ b/src/ui/density.test.tsx @@ -0,0 +1,54 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { act, render, renderHook } from "@testing-library/react"; +import { List } from "./List"; +import { Tree } from "./Tree"; +import { compactRowHeight, setCompactMode, useChromeIconSize, useRowHeight } from "./density"; +import { setIconAppearance } from "./iconAppearance"; + +afterEach(() => { + setCompactMode(false); + setIconAppearance(null); +}); + +describe("compact mode density", () => { + it("takes 2px off row heights and 4px off chrome icons, like IDEA's compact theme keys", () => { + expect(compactRowHeight(24, false)).toBe(24); + expect(compactRowHeight(24, true)).toBe(22); + expect(compactRowHeight(26, true)).toBe(24); + const rows = renderHook(() => [useRowHeight(), useRowHeight(26), useChromeIconSize()]); + expect(rows.result.current).toEqual([24, 26, 20]); + act(() => setCompactMode(true)); + expect(rows.result.current).toEqual([22, 24, 16]); + }); + + it("shrinks default tree rows, keeping a theme or explicit row height", () => { + const tree = (rowHeight?: number) => ( + n.key} + getLabel={(n) => n.key} + getChildren={() => undefined} + isExpandable={() => false} + rowHeight={rowHeight} + aria-label="t" + /> + ); + const { container, rerender } = render(tree()); + const row = () => container.querySelector('[role="treeitem"]'); + expect(row()?.style.height).toBe("24px"); + act(() => setCompactMode(true)); + expect(row()?.style.height).toBe("22px"); + act(() => setIconAppearance({ rowHeight: 30 })); + expect(row()?.style.height).toBe("30px"); + rerender(tree(40)); + expect(row()?.style.height).toBe("40px"); + }); + + it("shrinks default list rows", () => { + const { container } = render( s} renderItem={(s) => s} aria-label="l" />); + const option = () => container.querySelector('[role="option"]'); + expect(option()?.style.height).toBe("24px"); + act(() => setCompactMode(true)); + expect(option()?.style.height).toBe("22px"); + }); +}); diff --git a/src/ui/density.ts b/src/ui/density.ts new file mode 100644 index 000000000..14df0bf74 --- /dev/null +++ b/src/ui/density.ts @@ -0,0 +1,27 @@ +import { create } from "zustand"; + +/** + * Settings › Appearance › Compact mode, for sizes set from JS (virtualised rows, + * icon props). CSS reads the same switch from `:root[data-compact]` (tokens.css). + * Steps follow IDEA's Islands theme `*.compact` keys: rows −2 (Tree/List 24 → 22, + * VCS log 26 → 24), main-toolbar and stripe icons 20 → 16. + */ +export const useCompactMode = create(() => false); + +export function setCompactMode(on: boolean): void { + useCompactMode.setState(on, true); +} + +export function compactRowHeight(base: number, compact: boolean): number { + return compact ? base - 2 : base; +} + +/** Height of a list / tree row whose regular height is `base`. */ +export function useRowHeight(base = 24): number { + return compactRowHeight(base, useCompactMode()); +} + +/** Icon size for window chrome: main toolbar, run widget, tool window stripes. */ +export function useChromeIconSize(base = 20): number { + return useCompactMode() ? base - 4 : base; +} diff --git a/src/workbench/MainMenu.tsx b/src/workbench/MainMenu.tsx index 72ac965f4..f3a58030e 100644 --- a/src/workbench/MainMenu.tsx +++ b/src/workbench/MainMenu.tsx @@ -6,6 +6,7 @@ import { lookup, t, useI18n } from "@/platform/i18n"; import { commands, type MenuNode } from "@/platform/ipc"; import { usePlatform } from "@/platform/platformInfo"; import { Icon, MenuList, Popup, type MenuItem } from "@/ui"; +import { useChromeIconSize } from "@/ui/density"; import menuStyles from "@/ui/Menu.module.css"; import { isDistractionFree } from "./distractionFree"; import { toolWindowsRestorable } from "./toolwindows/store"; @@ -94,6 +95,7 @@ export function MainMenu({ row = false, ...props }: MainMenuProps) { function MainMenuBar({ merged, row, onExpandedChange }: MainMenuProps & { merged: boolean; row: boolean }) { useI18n((s) => s.locale); + const iconSize = useChromeIconSize(); const [menus, setMenus] = useState([]); const [expanded, setExpanded] = useState(false); const [open, setOpen] = useState(null); @@ -249,7 +251,7 @@ function MainMenuBar({ merged, row, onExpandedChange }: MainMenuProps & { merged } }} > - + ); const titles = ( diff --git a/src/workbench/MainToolbarDialog.tsx b/src/workbench/MainToolbarDialog.tsx index cf1909b2b..c93d50423 100644 --- a/src/workbench/MainToolbarDialog.tsx +++ b/src/workbench/MainToolbarDialog.tsx @@ -101,7 +101,6 @@ function CustomizeDialog({ onClose }: { onClose: () => void }) { getKey={(id) => id} activeIndex={sel.side === side ? sel.index : -1} onActiveChange={(index) => setSel({ side, index })} - rowHeight={24} className={styles.list} aria-label={side === "left" ? "Left group" : "Right group"} empty={ @@ -212,7 +211,6 @@ function AddPicker({ hidden, present, onPick }: { hidden: string[]; present: str activeIndex={active} onActiveChange={setActive} onActivate={(c) => onPick(c.id)} - rowHeight={24} className={styles.pickerList} aria-label="Actions and widgets to add" renderItem={(c, state) => ( diff --git a/src/workbench/StatusBar.module.css b/src/workbench/StatusBar.module.css index 6f4dc7028..3b90028fb 100644 --- a/src/workbench/StatusBar.module.css +++ b/src/workbench/StatusBar.module.css @@ -7,12 +7,16 @@ gap: var(--space-1); padding: 0 10px 0 12px; font-family: var(--font-ui); - font-size: var(--fs-ui); + font-size: var(--fs-chrome); color: var(--fg-muted); white-space: nowrap; overflow: hidden; position: relative; } +/* IDEA's compact status bar is just its widgets' height (StatusBar.Widget.widgetInsets 4,8,3,8). */ +:global(:root[data-compact]) .bar { + height: var(--h-statusbar); +} /* Widgets read as plain UI text like IDEA's, whatever their own font. */ .item { font-family: var(--font-ui); diff --git a/src/workbench/TitleBar.module.css b/src/workbench/TitleBar.module.css index 9654e975a..5ace4b85b 100644 --- a/src/workbench/TitleBar.module.css +++ b/src/workbench/TitleBar.module.css @@ -9,6 +9,7 @@ -webkit-user-select: none; user-select: none; color: var(--fg-strong); + font-size: var(--fs-chrome); } /* Room for the native macOS traffic lights (Overlay title bar). */ .overlay { @@ -68,12 +69,12 @@ /* Main toolbar dropdown widgets. */ .widget { min-width: 0; - height: 30px; + height: var(--h-toolbar-widget); margin: 0; padding: 0 8px; - border-radius: var(--radius-popup); + border-radius: var(--radius-toolbar-dropdown); color: var(--fg-strong); - font-size: var(--fs-ui); + font-size: var(--fs-chrome); } .widget { gap: var(--space-1-5); @@ -106,6 +107,12 @@ font-weight: 600; letter-spacing: 0.02em; } +/* IDEA compact: the avatar follows MainToolbar.Button.iconSize (20 → 16). */ +:global(:root[data-compact]) .avatar { + width: 16px; + height: 16px; + font-size: 9px; +} .drag { flex: 1; align-self: stretch; @@ -120,7 +127,7 @@ .tool { width: var(--titlebar-tool-button); height: var(--titlebar-tool-button); - border-radius: var(--radius-popup); + border-radius: var(--radius-toolbar-button); color: var(--fg-secondary); } diff --git a/src/workbench/TitleBar.tsx b/src/workbench/TitleBar.tsx index 96a631bf1..91a7bff2f 100644 --- a/src/workbench/TitleBar.tsx +++ b/src/workbench/TitleBar.tsx @@ -5,6 +5,7 @@ import { useActions } from "@/platform/actions"; import { shortcutLabel, useKeymap } from "@/platform/keymap"; import { useProject } from "@/platform/project"; import { BarButton, Icon, IconButton, Menu, type MenuItem, showContextMenu, T } from "@/ui"; +import { useChromeIconSize } from "@/ui/density"; import { useContributions, useWorkbenchSlots, type TitleItemContribution } from "./contributions"; import { ErrorBoundary, Slot } from "./ErrorBoundary"; import { MainMenu } from "./MainMenu"; @@ -213,6 +214,7 @@ function useToolbar() { } function GearButton({ customize }: { customize: MenuItem[] }) { + const iconSize = useChromeIconSize(); const [open, setOpen] = useState(false); const ref = useRef(null); const settings = useProject((s) => s.settings); @@ -241,7 +243,7 @@ function GearButton({ customize }: { customize: MenuItem[] }) { ref={ref} icon="settings" title="IDE and Project Settings" - iconSize={20} + iconSize={iconSize} className={styles.tool} aria-haspopup="menu" aria-expanded={open} @@ -255,6 +257,7 @@ function GearButton({ customize }: { customize: MenuItem[] }) { /** One main toolbar entry: a built-in widget, a contributed one or an added action. */ function ToolbarEntry({ id, items }: { id: string; items: ReadonlyMap }) { const actions = useActions((s) => s.actions); + const iconSize = useChromeIconSize(); if (id === PROJECT_WIDGET) return ; const item = items.get(id); if (item) return ; @@ -269,7 +272,7 @@ function ToolbarEntry({ id, items }: { id: string; items: ReadonlyMap
diff --git a/src/workbench/inputDialogs.tsx b/src/workbench/inputDialogs.tsx index 5880737e1..349f9272e 100644 --- a/src/workbench/inputDialogs.tsx +++ b/src/workbench/inputDialogs.tsx @@ -268,7 +268,6 @@ function ChooseDialog({ options, done }: { options: ChooseItemOptions; done: (v: activeIndex={active} onActiveChange={setActive} onActivate={(item) => done(item)} - rowHeight={24} className={styles.list} aria-label={options.title} empty={ @@ -474,7 +473,6 @@ function PathDialog({ options, done }: { options: ChoosePathOptions; done: (v: s }} // A click selects; a double click or Enter opens the folder or chooses the file. onActivate={(entry, _i, e) => (e.type !== "click" || e.detail > 1) && choose(entry)} - rowHeight={24} className={styles.pathList} aria-label={dir ?? options.title} empty={ diff --git a/src/workbench/toolwindows/ToolWindows.module.css b/src/workbench/toolwindows/ToolWindows.module.css index 7804ce249..c39a4e832 100644 --- a/src/workbench/toolwindows/ToolWindows.module.css +++ b/src/workbench/toolwindows/ToolWindows.module.css @@ -343,6 +343,11 @@ min-height: 44px; padding: 6px 2px 5px; } +/* IDEA compact: StripeToolbar.Button.*IconWithName.padding 4 → 3, text padding 6 → 4. */ +:global(:root[data-compact]) .stripeNamed { + min-height: 40px; + padding: 4px 2px 3px; +} .stripeMore { height: var(--stripe-icon-button); } @@ -440,6 +445,7 @@ gap: var(--space-1-5); padding: 0 6px 0 8px; color: var(--fg-emphasis); + font-size: var(--fs-chrome); } .headerTabbed { border-bottom: 1px solid var(--border); diff --git a/src/workbench/toolwindows/ToolWindows.tsx b/src/workbench/toolwindows/ToolWindows.tsx index c808bdff2..a52a2ce9d 100644 --- a/src/workbench/toolwindows/ToolWindows.tsx +++ b/src/workbench/toolwindows/ToolWindows.tsx @@ -28,6 +28,7 @@ import { tooltipAttrs, type MenuItem, } from "@/ui"; +import { useChromeIconSize } from "@/ui/density"; import { FOCUSABLE } from "@/ui/popupState"; import { TabStripRegistry } from "@/ui/Tabs"; import { @@ -441,6 +442,7 @@ function StripeButton({ side: "left" | "right"; showName: boolean; }) { + const iconSize = useChromeIconSize(); const shortcut = shortcutLabel(`toolwindow.${tw.id}`); const dragged = useStripeDrag((s) => s.id === tw.id); return ( @@ -469,7 +471,7 @@ function StripeButton({ {...tooltipAttrs(toolWindowTitle(tw), shortcut, true)} > - + {tw.useBadge && } {showName && ( @@ -483,6 +485,7 @@ function StripeButton({ /** Stripe "…": tool windows without a stripe button; opening one adds its button (IDEA). */ function StripeMore({ windows }: { windows: ToolWindowContribution[] }) { + const iconSize = useChromeIconSize(); const [open, setOpen] = useState(false); const ref = useRef(null); const items = useMemo( @@ -512,7 +515,7 @@ function StripeMore({ windows }: { windows: ToolWindowContribution[] }) { data-tooltip-stripe="left" {...tooltipAttrs("More Tool Windows")} > - + Date: Fri, 20 Nov 2026 03:39:37 +0800 Subject: [PATCH 02/12] fix(run): keep Run Anything controls visible on short windows (#4581) Run Anything had a fixed 620px popup with a 360px list cap and a footer that could fall off short windows. The popup now fits the viewport as a column whose list shrinks, uses the shared search field with combobox semantics, shows the completion of the selected entry in the field, pages by the visible row count (compact-aware), and keeps a wrapping footer with the navigation hints. --- e2e/runAnything.spec.ts | 79 +++++++++++ .../run-anything/RunAnything.module.css | 72 ++++++---- src/features/run-anything/RunAnything.tsx | 133 +++++++++++------- src/platform/locales/text/es.json | 2 - src/platform/locales/text/fr.json | 2 - src/platform/locales/text/ko.json | 2 - src/platform/locales/text/pl.json | 2 - src/platform/locales/text/pt.json | 2 - src/platform/locales/text/zh.json | 2 - 9 files changed, 210 insertions(+), 86 deletions(-) create mode 100644 e2e/runAnything.spec.ts diff --git a/e2e/runAnything.spec.ts b/e2e/runAnything.spec.ts new file mode 100644 index 000000000..862859696 --- /dev/null +++ b/e2e/runAnything.spec.ts @@ -0,0 +1,79 @@ +import { expect, test } from "./fixtures"; + +test("Run Anything keeps its command field and shortcuts visible as its results scroll", async ({ + workbench: page, +}) => { + await page.setViewportSize({ width: 1080, height: 740 }); + await page.evaluate(async () => { + const projectModule = "/src/platform/project.ts"; + const contributionsModule = "/src/workbench/contributions.ts"; + const historyModule = "/src/features/run-anything/model.ts"; + const [{ useProject }, { registerRunAnythingProvider }, { pushHistory }] = await Promise.all([ + import(/* @vite-ignore */ projectModule), + import(/* @vite-ignore */ contributionsModule), + import(/* @vite-ignore */ historyModule), + ]); + const root = useProject.getState().project.root; + for (const command of ["git status", "git diff --stat", "pnpm lint", "pnpm test"]) pushHistory(root, command); + const tasks = Array.from({ length: 8 }, (_, i) => { + const command = `npm run verify-${i + 1}`; + return { + key: command, + label: `Verify checkout configuration ${i + 1}`, + detail: "checkout-service / workspace verification", + completion: command, + run: () => { + document.body.dataset.runAnythingCommand = command; + }, + }; + }); + registerRunAnythingProvider({ + id: "test-verify", + order: -100, + group: "Run Configurations", + items: (line: string) => tasks.filter((task) => task.completion.includes(line)), + }); + }); + await page.keyboard.press("Control"); + await page.keyboard.press("Control"); + + const popup = page.getByRole("dialog", { name: "Run Anything", exact: true }); + const field = popup.getByLabel("Command line", { exact: true }); + const results = popup.getByRole("listbox", { name: "Run Anything entries" }); + const hint = popup.getByText(/Enter to run, Tab to complete|Tab to complete, Enter to run/); + await expect(field).toBeFocused(); + await page.setViewportSize({ width: 560, height: 340 }); + await expect + .poll(async () => { + const [shell, footer] = await Promise.all([popup.boundingBox(), hint.boundingBox()]); + return ( + !!shell && + !!footer && + Math.abs(shell.x - (560 - shell.width) / 2) < 2 && + shell.x >= 14 && + footer.y + footer.height <= shell.y + shell.height + 1 + ); + }) + .toBe(true); + await expect.poll(() => results.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true); + + await field.fill("verify"); + await field.press("ArrowDown"); + await expect(field).toHaveValue("npm run verify-1"); + const selected = results.getByRole("option", { selected: true }); + await expect(selected).toContainText("Verify checkout configuration 1"); + await expect(field).toHaveAttribute("aria-activedescendant", (await selected.getAttribute("id"))!); + await field.press("Tab"); + await expect(field).toHaveValue("npm run verify-1"); + await expect(field).toBeFocused(); + await field.press("Shift+Tab"); + const history = popup.getByRole("button", { name: "Clear History" }); + await expect(history).toBeFocused(); + await history.press("Enter"); + await expect(history).toBeHidden(); + await expect(field).toBeFocused(); + await field.press("ArrowDown"); + await field.press("Enter"); + await expect(popup).toBeHidden(); + await expect(page.locator("body")).toHaveAttribute("data-run-anything-command", "npm run verify-1"); +}); diff --git a/src/features/run-anything/RunAnything.module.css b/src/features/run-anything/RunAnything.module.css index f8d0778a6..b93e43a0f 100644 --- a/src/features/run-anything/RunAnything.module.css +++ b/src/features/run-anything/RunAnything.module.css @@ -1,61 +1,67 @@ .popup { - width: 620px; - max-width: calc(100vw - 32px); + display: flex; + flex-direction: column; + width: min(670px, calc(100vw - 32px)); overflow: hidden; } .body { + flex: 1 1 auto; display: flex; flex-direction: column; + min-height: 0; + font-family: var(--font-ui); } .header { + flex: none; display: flex; align-items: center; gap: var(--space-2); - height: var(--h-row); - padding: 4px 10px 0; - font-size: var(--fs-small); - color: var(--fg-subtle); + min-height: var(--h-field); + padding: var(--space-0-5) var(--space-3); + border-bottom: 1px solid var(--border-popup); + background: var(--bg-frame, var(--bg-app)); } .title { flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: var(--fs-ui); font-weight: 600; color: var(--fg-strong); } .link { + flex: none; + max-width: 50%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; padding: 0; border: 0; background: none; color: var(--link); - font: inherit; + font-size: var(--fs-small); cursor: pointer; } .link:hover { color: var(--link-hover); } -.inputRow { - display: flex; - align-items: center; - gap: var(--space-1-5); - padding: 6px 10px; - border-bottom: 1px solid var(--border-popup); -} -.inputIcon { +.query { flex: none; - color: var(--fg-subtle); -} -.input { - flex: 1; - font-family: var(--font-ui); + padding: var(--space-2); } .rows { - max-height: 360px; - height: auto; + flex: 1 1 auto; + min-height: var(--h-row); + max-height: 600px; + overflow-x: hidden; } .section { display: flex; align-items: center; width: 100%; - gap: 10px; + gap: var(--space-3); padding: 0; font-size: var(--fs-small); color: var(--fg-subtle); @@ -93,23 +99,35 @@ .detail { flex: 0 1 auto; min-width: 0; - max-width: 45%; + max-width: min(36%, 26ch); overflow: hidden; text-overflow: ellipsis; - font-style: italic; margin-left: auto; color: var(--fg-subtle); font-size: var(--fs-small); white-space: nowrap; } +.activeRow .detail { + color: var(--fg); +} .empty { - padding: 6px 10px; + padding: var(--space-1) var(--space-3) var(--space-2); color: var(--fg-subtle); font-size: var(--fs-small); } .footer { - padding: 6px 10px; + flex: none; + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-0-5) var(--space-3); + padding: var(--space-1-5) var(--space-3); border-top: 1px solid var(--border-popup); font-size: var(--fs-small); color: var(--fg-subtle); } +.navigationHint { + display: inline-flex; + align-items: center; + gap: var(--space-1); +} diff --git a/src/features/run-anything/RunAnything.tsx b/src/features/run-anything/RunAnything.tsx index ecbab5803..8cc10dd00 100644 --- a/src/features/run-anything/RunAnything.tsx +++ b/src/features/run-anything/RunAnything.tsx @@ -4,14 +4,15 @@ * the selected entry, or the line itself: a provider that claims it, else the * shell in the project directory, its output in the Run tool window. */ -import { useMemo, useState, type KeyboardEvent } from "react"; +import { useId, useMemo, useRef, useState, type KeyboardEvent } from "react"; import clsx from "clsx"; import { create } from "zustand"; import { executeAction } from "@/platform/actions"; import { usePlatform } from "@/platform/platformInfo"; import { useProject } from "@/platform/project"; -import { Icon, Input, List, Popup, T, listNavigate } from "@/ui"; +import { Icon, Kbd, List, Popup, SearchField, T, firstSelectable, listNavigate } from "@/ui"; import { runAnythingProviderList } from "@/workbench/contributions"; +import { useRowHeight } from "@/ui/density"; import { buildRows, clearHistory, pushHistory, readHistory, shellRunConfig, type Row } from "./model"; import styles from "./RunAnything.module.css"; @@ -44,8 +45,13 @@ export function RunAnythingHost() { } const isSection = (r: Row) => r.kind === "section"; +const ROW_HEIGHT = 24; +const commandAnchor = { getBoundingClientRect: () => new DOMRect(window.innerWidth / 2, 72, 0, 0) }; function RunAnythingPopup({ root }: { root: string }) { + const field = useRef(null); + const rowHeight = useRowHeight(ROW_HEIGHT); + const listId = useId(); const [line, setLine] = useState(""); const [active, setActive] = useState(-1); const [history, setHistory] = useState(() => readHistory(root)); @@ -57,6 +63,10 @@ function RunAnythingPopup({ root }: { root: string }) { }), [line, history], ); + const selected = rows[active]; + const first = firstSelectable(rows, isSection); + const hasRows = first >= 0; + const command = selected?.kind === "item" ? (selected.item.completion ?? selected.item.label) : line; const run = (row: Row | undefined) => { if (!row || row.kind !== "item") return; @@ -75,21 +85,25 @@ function RunAnythingPopup({ root }: { root: string }) { setActive(-1); }; - const onKeyDown = (e: KeyboardEvent) => { + const onKeyDown = (e: KeyboardEvent) => { + if (e.nativeEvent.isComposing || e.altKey || e.ctrlKey || e.metaKey) return; if (["ArrowDown", "ArrowUp", "PageDown", "PageUp"].includes(e.key)) { - const next = listNavigate(e.key, { items: rows, active: Math.max(active, 0), wrap: true, isSection }); - if (next !== null) { + const height = e.currentTarget.ownerDocument.getElementById(listId)?.clientHeight ?? rowHeight; + const pageSize = Math.max(1, Math.floor(height / rowHeight) - 1); + const next = listNavigate(e.key, { items: rows, active, wrap: true, isSection, pageSize }); + if (next !== null && hasRows) { e.preventDefault(); - setActive(active < 0 && e.key === "ArrowDown" ? rows.findIndex((r) => !isSection(r)) : next); + setActive(next < 0 ? first : next); } return; } - if (e.key === "Tab") { + if (e.key === "Tab" && !e.shiftKey && hasRows) { e.preventDefault(); - complete(rows[active >= 0 ? active : rows.findIndex((r) => !isSection(r))]); + e.stopPropagation(); + complete(selected ?? rows[first]); } else if (e.key === "Enter") { e.preventDefault(); - if (active >= 0) run(rows[active]); + if (selected) run(selected); else runLine(); } }; @@ -97,7 +111,7 @@ function RunAnythingPopup({ root }: { root: string }) { return ( { clearHistory(root); setHistory([]); + setActive(-1); + field.current?.focus(); }} > Clear History )}
-
- - + { - setLine(e.target.value); + onChange={(value) => { + setLine(value); setActive(-1); }} onKeyDown={onKeyDown} />
- r.key} - isSection={isSection} - renderSection={(r) =>
{r.kind === "section" && {r.label}}
} - activeIndex={active} - onActiveChange={setActive} - onActivate={(r) => run(r)} - focusable={false} - hoverSelects={false} - className={styles.rows} - aria-label="Run Anything entries" - empty={ -
- {line.trim() ? Press Enter to run the command in the project directory : Type a command} + {hasRows ? ( + <> + r.key} + isSection={isSection} + renderSection={(r) =>
{r.kind === "section" && {r.label}}
} + activeIndex={active} + onActiveChange={setActive} + onActivate={(r) => run(r)} + focusable={false} + hoverSelects={false} + rowHeight={rowHeight} + className={styles.rows} + aria-label="Run Anything entries" + renderItem={(r, state) => + r.kind === "item" ? ( +
+ + + {r.item.label} + + {r.item.detail && ( + + {r.item.detail} + + )} +
+ ) : null + } + /> +
+ + ↑ + ↓ + Navigate + + Tab to complete, Enter to run
- } - renderItem={(r, state) => - r.kind === "item" ? ( -
- - {r.item.label} - {r.item.detail && {r.item.detail}} -
- ) : null - } - /> -
- Enter to run, Tab to complete. Other commands run in the project directory. -
+ + ) : ( + line.trim() && ( +
+ Press Enter to run the command in the project directory +
+ ) + )}
); diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 9de9fc00e..43d982ebf 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -2915,8 +2915,6 @@ "Run a command, configuration or goal": "Ejecutar un comando, configuración o meta", "Run Anything entries": "Entradas de Ejecutar cualquier cosa", "Press Enter to run the command in the project directory": "Presiona Enter para ejecutar el comando en el directorio del proyecto", - "Type a command": "Escribe un comando", - "Enter to run, Tab to complete. Other commands run in the project directory.": "Enter para ejecutar, Tab para completar. Otros comandos se ejecutan en el directorio del proyecto.", "Recent": "Recientes", "Search types": "Buscar tipos", "Search configuration types": "Buscar tipos de configuración", diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index 21153c4d1..e036b0da4 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -2815,8 +2815,6 @@ "Run a command, configuration or goal": "Exécuter une commande, une configuration ou un goal", "Run Anything entries": "Entrées d'Exécuter n'importe quoi", "Press Enter to run the command in the project directory": "Appuyez sur Entrée pour exécuter la commande dans le répertoire du projet", - "Type a command": "Saisissez une commande", - "Enter to run, Tab to complete. Other commands run in the project directory.": "Entrée pour exécuter, Tab pour compléter. Les autres commandes s'exécutent dans le répertoire du projet.", "Recent": "Récents", "Search types": "Rechercher des types", "Search configuration types": "Rechercher des types de configuration", diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 97675b7e8..6ea769967 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -2965,8 +2965,6 @@ "Run a command, configuration or goal": "명령, 구성 또는 목표 실행", "Run Anything entries": "무엇이든 실행 항목", "Press Enter to run the command in the project directory": "Enter를 눌러 프로젝트 디렉터리에서 명령을 실행하세요", - "Type a command": "명령 입력", - "Enter to run, Tab to complete. Other commands run in the project directory.": "Enter로 실행, Tab으로 완성합니다. 그 밖의 명령은 프로젝트 디렉터리에서 실행됩니다.", "Recent": "최근", "Search types": "유형 검색", "Search configuration types": "구성 유형 검색", diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 761694715..987f9fe1f 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -2887,8 +2887,6 @@ "Run a command, configuration or goal": "Uruchom polecenie, konfigurację lub cel", "Run Anything entries": "Wpisy funkcji 'Uruchom cokolwiek'", "Press Enter to run the command in the project directory": "Naciśnij Enter, aby uruchomić polecenie w katalogu projektu", - "Type a command": "Wpisz polecenie", - "Enter to run, Tab to complete. Other commands run in the project directory.": "Enter, aby uruchomić, Tab, aby uzupełnić. Inne polecenia uruchamiają się w katalogu projektu.", "Recent": "Niedawne", "Search types": "Szukaj typów", "Search configuration types": "Szukaj typów konfiguracji", diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index 2046f7789..e3a2b804e 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -2888,8 +2888,6 @@ "Run a command, configuration or goal": "Executar um comando, configuração ou meta", "Run Anything entries": "Entradas de Executar qualquer coisa", "Press Enter to run the command in the project directory": "Pressione Enter para executar o comando no diretório do projeto", - "Type a command": "Digite um comando", - "Enter to run, Tab to complete. Other commands run in the project directory.": "Enter para executar, Tab para completar. Outros comandos são executados no diretório do projeto.", "Recent": "Recentes", "Search types": "Pesquisar tipos", "Search configuration types": "Pesquisar tipos de configuração", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index fd3dbdb31..cab44ad2b 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -3706,8 +3706,6 @@ "Run a command, configuration or goal": "运行命令、配置或目标", "Run Anything entries": "“运行任何内容”条目", "Press Enter to run the command in the project directory": "按 Enter 在项目目录中运行命令", - "Type a command": "输入命令", - "Enter to run, Tab to complete. Other commands run in the project directory.": "按 Enter 运行,按 Tab 补全。其他命令将在项目目录中运行。", "Recent": "最近", "Search types": "搜索类型", "Search configuration types": "搜索配置类型", From 1cfc71ae58af8070e79f28c49cb97e2c1d77b45f Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 03:56:29 +0800 Subject: [PATCH 03/12] fix(editor): make symbol rename and its preview readable in narrow windows (#4583) The symbol rename prompt was a caret-anchored popup that could be clipped in narrow windows, and its preview truncated long names. When in-place rename isn't available, Rename now opens a dialog with the symbol context, a New name field in the editor font, and an optional note; the refactoring preview keeps the context, wraps occurrence snippets in the editor font and theme, and truncates long file names with the full path in the tooltip. --- e2e/codeInsight.spec.ts | 75 +++++++++++++++++++++++++++ src/editor/lsp/Popups.module.css | 70 +++++++++++++++++++++++++ src/editor/lsp/Popups.tsx | 68 ++++++++++++++++++++++-- src/editor/lsp/popupStore.ts | 10 ++++ src/editor/lsp/rename.ts | 15 +++--- src/editor/lsp/syntaxFallback.test.ts | 12 ++--- 6 files changed, 232 insertions(+), 18 deletions(-) diff --git a/e2e/codeInsight.spec.ts b/e2e/codeInsight.spec.ts index 74ee676b5..721c6e632 100644 --- a/e2e/codeInsight.spec.ts +++ b/e2e/codeInsight.spec.ts @@ -562,6 +562,81 @@ test("indexed single-file rename previews all anchors and applies only after con expect(apply.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] }); }); +test("rename keeps the typed name, uses the editor font and shows long preview names in a narrow dialog", async ({ + workbench: page, +}) => { + const editor = await openSample(page); + await page.evaluate( + async ({ file, prepared }) => { + const projectModule = "/src/platform/project.ts"; + const schemaModule = "/src/features/settings/model/schema.ts"; + const [{ useProject }, { DEFAULT_SETTINGS }] = await Promise.all([ + import(/* @vite-ignore */ projectModule), + import(/* @vite-ignore */ schemaModule), + ]); + const base = useProject.getState().settings ?? DEFAULT_SETTINGS; + useProject.setState({ settings: { ...base, editor: { ...base.editor, fontSize: 17 } } }); + window.__ipc.handlers.lsp_prepare_rename = () => prepared; + window.__ipc.handlers.lsp_rename = (args) => ({ + preview: true, + incomplete: null, + edit: { + files: [ + { + kind: "edit", + path: file, + edits: [{ range: prepared, new_text: args.newName }], + }, + ], + }, + }); + window.__ipc.handlers.apply_workspace_edit = () => null; + }, + { file: FILE, prepared: range(20, 12, 17) }, + ); + + await caretAt(editor, page, "val order: Order", "order"); + await page.keyboard.press("Shift+F6"); + await expect(page.getByText(/Press ⇧F6 to show dialog/)).toBeVisible(); + const name = "checkoutOrderWithDeliveryInstructionsAndInventoryReservation"; + await page.keyboard.insertText(name); + await page.keyboard.press("Shift+F6"); + await page.setViewportSize({ width: 440, height: 520 }); + const dialog = page.getByRole("dialog", { name: "Rename 'order'", exact: true }); + const input = dialog.getByRole("textbox", { name: "New name" }); + await expect(input).toBeFocused(); + await expect(input).toHaveValue(name); + await expect(input).toHaveCSS("font-size", "17px"); + const [label, field] = await Promise.all([ + dialog.getByText("New name", { exact: true }).boundingBox(), + input.boundingBox(), + ]); + expect(label!.x + label!.width).toBeLessThan(field!.x); + const rename = dialog.getByRole("button", { name: "Rename", exact: true }); + + await input.fill(""); + await expect(rename).toBeDisabled(); + await input.press("Enter"); + await expect(dialog).toBeVisible(); + expect(await ipcCalls(page, "lsp_rename")).toHaveLength(0); + await input.fill(name); + await input.press("Enter"); + + const summary = `Rename 'order' to '${name}'`; + const preview = page.getByRole("dialog", { name: summary, exact: true }); + const context = preview.getByText(summary, { exact: true }); + await expect(context).toBeVisible(); + const geometry = await context.evaluate((element) => ({ + client: element.clientWidth, + content: element.scrollWidth, + })); + expect(geometry.content).toBeLessThanOrEqual(geometry.client + 1); + await expect(preview.getByText("1 occurrence in 1 file")).toBeVisible(); + expect(await ipcCalls(page, "apply_workspace_edit")).toHaveLength(0); + await preview.getByRole("button", { name: "Do Refactor" }).click(); + await expect.poll(() => ipcCalls(page, "apply_workspace_edit")).toHaveLength(1); +}); + test("intention previews fit narrow windows and wrap long code lines", async ({ workbench: page }) => { await page.setViewportSize({ width: 1600, height: 900 }); const editor = await openSample(page); diff --git a/src/editor/lsp/Popups.module.css b/src/editor/lsp/Popups.module.css index a3215c0bf..5fa6997c8 100644 --- a/src/editor/lsp/Popups.module.css +++ b/src/editor/lsp/Popups.module.css @@ -261,6 +261,34 @@ font-size: var(--fs-tiny); color: var(--fg-faint); } +.symbolRename { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + align-items: center; + gap: var(--space-2) var(--space-3); + padding: var(--space-3); + font-family: var(--font-ui); + font-size: var(--fs-ui); +} +.renameContext, +.symbolRenameNote { + grid-column: 1 / -1; + min-width: 0; + overflow-wrap: anywhere; +} +.renameContext { + color: var(--fg-emphasis); +} +.symbolRename .renameField { + width: 100%; + height: max(var(--h-field), calc(var(--openidea-editor-font-size, var(--fs-code)) + var(--space-2))); + font-family: var(--openidea-editor-font, var(--font-mono)); + font-size: var(--openidea-editor-font-size, var(--fs-code)); +} +.symbolRenameNote { + color: var(--fg-muted); + font-size: var(--fs-small); +} /* Fits its content up to a cap; resized (`data-resized`), it keeps that size and the body scrolls. */ .docPopup { @@ -398,6 +426,36 @@ flex-direction: column; overflow: hidden; } +.renamePreview [data-dialog-body] { + display: block; + overflow: auto; +} +.previewContext { + padding: var(--space-2) 14px 0; + overflow-wrap: anywhere; + color: var(--fg-emphasis); + font-size: var(--fs-ui); +} +.renamePreview .previewList { + overflow: visible; +} +.renamePreview .previewName { + min-width: 0; + max-width: 55%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.renamePreview .previewOp { + flex: 0 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.renamePreview .previewWarning { + overflow-wrap: anywhere; +} .previewSummary { flex: none; padding: 10px 14px 6px; @@ -469,6 +527,18 @@ font-size: var(--fs-small); color: var(--fg-editor); } +.renamePreview .previewOccurrences .previewRow { + min-height: var(--h-row); + height: auto; + align-items: baseline; + padding-block: var(--space-1); +} +.renamePreview .previewCode { + font-family: var(--openidea-editor-font, var(--font-mono)); + font-size: var(--openidea-editor-font-size, var(--fs-code)); + white-space: pre-wrap; + overflow-wrap: anywhere; +} .previewMatch { background: var(--bg-search-match); color: var(--fg-search-match, inherit); diff --git a/src/editor/lsp/Popups.tsx b/src/editor/lsp/Popups.tsx index 2fe99609d..551543628 100644 --- a/src/editor/lsp/Popups.tsx +++ b/src/editor/lsp/Popups.tsx @@ -1,5 +1,5 @@ /** React popups for LSP editor features, rendered as a workbench overlay. */ -import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react"; +import { useEffect, useId, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react"; import clsx from "clsx"; import { Checkbox, @@ -392,6 +392,54 @@ function RenamePopup({ popup }: { popup: Extract } ); } +function SymbolRenameDialog({ popup }: { popup: Extract }) { + const [value, setValue] = useState(popup.initial); + const field = useId(); + const name = value.trim(); + return ( + { + closePopup(); + popup.onSubmit(name); + }, + }, + { label: "Cancel", role: "cancel" }, + ]} + > +
+
+
{popup.title}
+ + setValue(e.target.value)} + invalid={!name} + /> + {popup.note &&
{popup.note}
} +
+
+
+ ); +} + function DocPopup({ popup }: { popup: Extract }) { const focusSeq = useLspPopup((s) => s.focusSeq); const scope = useRef(null); @@ -536,6 +584,7 @@ function savePreviewSize(size: { w: number; h: number }) { } function PreviewDialog({ popup }: { popup: Extract }) { + const rename = popup.renameThemeClasses !== undefined; const root = useProject((s) => s.project?.root ?? ""); const { summary } = popup; const [initialSize] = useState(loadPreviewSize); @@ -543,8 +592,9 @@ function PreviewDialog({ popup }: { popup: Extract + {rename &&
{popup.title}
} {popup.warnings?.map((w) => (
@@ -573,7 +624,10 @@ function PreviewDialog({ popup }: { popup: Extract{describeSummary(summary)}
{popup.occurrences ? ( -
    +
      {popup.occurrences.map((o, i) => { const lead = o.text.length - o.text.trimStart().length; const text = o.text.trim(); @@ -596,7 +650,9 @@ function PreviewDialog({ popup }: { popup: Extract (
    • - {basename(e.path)} + + {basename(e.path)} + {relativePath(root, e.path)} @@ -742,6 +798,8 @@ export function LspPopups() { return ; case "rename": return ; + case "symbolRename": + return ; case "doc": return ; case "definition": diff --git a/src/editor/lsp/popupStore.ts b/src/editor/lsp/popupStore.ts index 2402517c0..2b4a1a8a9 100644 --- a/src/editor/lsp/popupStore.ts +++ b/src/editor/lsp/popupStore.ts @@ -130,6 +130,14 @@ export type LspPopup = hint?: string; onSubmit: (name: string) => void; } + | { + kind: "symbolRename"; + title: string; + initial: string; + note?: string; + themeClasses: string; + onSubmit: (name: string) => void; + } | { kind: "preview"; title: string; @@ -140,6 +148,8 @@ export type LspPopup = warnings?: string[]; /** Individual occurrences with line previews (single-file syntax-based renames). */ occurrences?: PreviewOccurrence[]; + /** The editor theme for a symbol rename and its occurrence snippets. */ + renameThemeClasses?: string; }; export interface PreviewOccurrence { diff --git a/src/editor/lsp/rename.ts b/src/editor/lsp/rename.ts index e71ff0da8..0a59c6d4a 100644 --- a/src/editor/lsp/rename.ts +++ b/src/editor/lsp/rename.ts @@ -27,9 +27,9 @@ import { executeAction } from "@/platform/actions"; import { whenAllSynced, whenSynced, type EditorDocContext } from "@/editor/api"; import { structure } from "@/editor/structure"; import { docOf, incompleteNote, isUnavailable, lspRequest, reportLspError } from "./lsp"; -import { comparePos, offsetToPos, rangeToOffsets } from "./positions"; +import { offsetToPos, rangeToOffsets } from "./positions"; import { showHint } from "./hint"; -import { caretAnchor, openPopup, type PreviewOccurrence } from "./popupStore"; +import { openPopup, type PreviewOccurrence } from "./popupStore"; import { needsPreview, summarizeWorkspaceEdit } from "./workspaceEdit"; import { endInplaceRename, inplaceSession, startInplaceRename, type Span } from "./inplaceRename"; import { shortcutLabel } from "@/platform/keymap"; @@ -127,10 +127,10 @@ export async function startRename(view: EditorView) { const oldName = view.state.sliceDoc(from, to); const dialog = (initial: string) => openPopup({ - kind: "rename", - anchor: caretAnchor(view, from), + kind: "symbolRename", title: tx`Rename '${oldName}'`, initial, + themeClasses: view.themeClasses, onSubmit: (newName) => void finishRename(view, doc, pos, oldName, newName), }); if (from === to) { @@ -304,6 +304,7 @@ async function finishRename(view: EditorView, doc: EditorDocContext, pos: Pos, o kind: "preview", title: tx`Rename '${oldName}' to '${newName}'`, summary, + renameThemeClasses: view.themeClasses, ...(note ? { warnings: [note] } : {}), confirmLabel: note ? "Rename Anyway" : "Do Refactor", onConfirm: () => void applyEdit(view, edit), @@ -350,13 +351,12 @@ async function startSyntaxRename( return true; } const { plan } = result; - const at = plan.occurrences.find((o) => comparePos(o.range.start, pos) <= 0 && comparePos(pos, o.range.end) <= 0); openPopup({ - kind: "rename", - anchor: caretAnchor(view, rangeToOffsets(view.state.doc, (at ?? plan.occurrences[0]!).range).from), + kind: "symbolRename", title: tx`Rename '${plan.symbol.name}'`, initial: plan.symbol.name, note: `${SYNTAX_NOTE}: local occurrences only`, + themeClasses: view.themeClasses, onSubmit: (newName) => void commitSyntaxRename(view, doc, plan, newName), }); return true; @@ -418,6 +418,7 @@ export async function commitSyntaxRename( }, warnings: [...risks, `${SYNTAX_NOTE}. Only the occurrences below will be renamed.`], occurrences, + renameThemeClasses: view.themeClasses, confirmLabel: "Rename Anyway", onConfirm: apply, }); diff --git a/src/editor/lsp/syntaxFallback.test.ts b/src/editor/lsp/syntaxFallback.test.ts index 733192129..e22799d7f 100644 --- a/src/editor/lsp/syntaxFallback.test.ts +++ b/src/editor/lsp/syntaxFallback.test.ts @@ -646,8 +646,8 @@ describe("rename wiring", () => { const view = editor("const x = 1;\nf({ x });", "typescript", 6); await startRename(view); const popup = useLspPopup.getState().popup; - expect(popup?.kind).toBe("rename"); - if (popup?.kind !== "rename") return; + expect(popup?.kind).toBe("symbolRename"); + if (popup?.kind !== "symbolRename") return; expect(popup.note).toContain("Based on syntax"); popup.onSubmit("y"); await vi.waitFor(() => expect(view.state.doc.toString()).toBe("const y = 1;\nf({ x: y });")); @@ -661,7 +661,7 @@ describe("rename wiring", () => { const view = editor("const x = 1;\nx;\nvar x;", "typescript", 6); await startRename(view); const popup = useLspPopup.getState().popup; - if (popup?.kind !== "rename") throw new Error("no rename popup"); + if (popup?.kind !== "symbolRename") throw new Error("no rename dialog"); popup.onSubmit("y"); await vi.waitFor(() => expect(useLspPopup.getState().popup?.kind).toBe("preview")); const preview = useLspPopup.getState().popup; @@ -860,12 +860,12 @@ describe("rename wiring", () => { await startRename(view); expect(inplaceSession(view.state)?.oldName).toBe("x"); await startRename(view); - expect(useLspPopup.getState().popup?.kind).toBe("rename"); + expect(useLspPopup.getState().popup?.kind).toBe("symbolRename"); if (finish === "cancel") closePopup(); release({ status: "ok", data: r(0, 6, 7) }); await older; expect(inplaceSession(view.state)).toBeNull(); - expect(useLspPopup.getState().popup?.kind ?? null).toBe(finish === "dialog" ? "rename" : null); + expect(useLspPopup.getState().popup?.kind ?? null).toBe(finish === "dialog" ? "symbolRename" : null); }); it.each(["text", "document"])("drops pending preparation when the editor %s changes", async (change) => { @@ -938,7 +938,7 @@ describe("rename wiring", () => { ); cmd.syntaxLocals.mockReturnValueOnce(ok(local({ references: [] }))); await startRename(view); - expect(useLspPopup.getState().popup?.kind).toBe("rename"); + expect(useLspPopup.getState().popup?.kind).toBe("symbolRename"); }); }); From 04611c038810c9ee345cf7e6d3378aa34d63e6c5 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 04:06:41 +0800 Subject: [PATCH 04/12] fix(database): show a running SQL statement in the editor and results (#4601) The console tracked the running request only for Run and Cancel; statement marks and result tabs arrived after it ended, and the Results view said "No results" meanwhile. While a request runs, the submitted statements are highlighted with a gutter spinner and a ticking elapsed time, and the Results view opens with an executing bar above the previous result. Edits during the run move the marks and the outcomes land on their statements; cancel or an error clears the indication and keeps the previous result. Fixes #4565 --- src/features/database/Database.module.css | 28 ++++ src/features/database/ResultsView.tsx | 40 ++++- src/features/database/console.tsx | 138 ++++++++++++++++-- .../database/inEditorResults.test.tsx | 60 +++++++- src/features/database/index.ts | 1 + .../database/requestLifecycle.test.ts | 3 + src/features/database/resultView.ts | 7 +- src/features/database/results-view.test.tsx | 63 ++++++++ src/features/database/store.ts | 23 ++- src/platform/locales/text/en.json | 4 + src/platform/locales/text/zh.json | 4 + src/ui/iconNode.ts | 14 ++ 12 files changed, 368 insertions(+), 17 deletions(-) diff --git a/src/features/database/Database.module.css b/src/features/database/Database.module.css index 0fc9d749d..773eb21ea 100644 --- a/src/features/database/Database.module.css +++ b/src/features/database/Database.module.css @@ -154,6 +154,28 @@ flex: 1; min-height: 0; } +/* A console's request in flight; the previous result stays below it. */ +.executing { + flex: none; + display: flex; + align-items: center; + gap: var(--space-2); + min-width: 0; + padding: var(--space-1) var(--space-3); + border-bottom: 1px solid var(--border); + color: var(--fg-muted); + font-size: var(--fs-small); +} +.executingText { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.executingTime { + flex: none; + font-variant-numeric: tabular-nums; +} /* Gives way before the name does. */ .treeDetail { color: var(--fg-muted); @@ -657,6 +679,12 @@ } /* Console run feedback: timing after a statement, gutter check / error, error banner. */ +:global(.cm-openidea-db-executing) { + background: var(--accent-soft); +} +:global(.cm-openidea-db-elapsed) { + font-variant-numeric: tabular-nums; +} :global(.cm-openidea-db-timing) { margin-left: 1.5em; color: var(--fg-muted); diff --git a/src/features/database/ResultsView.tsx b/src/features/database/ResultsView.tsx index 7389066bf..bd09faeec 100644 --- a/src/features/database/ResultsView.tsx +++ b/src/features/database/ResultsView.tsx @@ -16,6 +16,8 @@ import { type MouseEvent, } from "react"; import clsx from "clsx"; +import { useShallow } from "zustand/react/shallow"; +import { basename } from "@/platform/project"; import { call, commands, type DbPlanNode, type DbQueryResult } from "@/platform/ipc"; import { shortcutLabel } from "@/platform/keymap"; import { setContext } from "@/platform/context"; @@ -35,7 +37,7 @@ import { resolveTarget, type EditBlockReason, } from "./resultEditing"; -import { pageWindow } from "./resultView"; +import { formatElapsed, pageWindow } from "./resultView"; import { resultTabMenu } from "./resultTabActions"; import { analyze } from "./sql/analyze"; import { nameMatcher } from "./sql/dialect"; @@ -55,6 +57,7 @@ import { rerunResult, useDatabase, withConnection, + type ConsoleExecution, type OutputLine, type ResultTab, } from "./store"; @@ -744,8 +747,40 @@ function PinButton({ tab }: { tab: ResultTab }) { ); } +/** The most recently started console request, while it runs. */ +function useLatestExecution(): [string, ConsoleExecution] | undefined { + return useDatabase( + useShallow((s) => { + let latest: [string, ConsoleExecution] | undefined; + for (const entry of Object.entries(s.executions)) + if (!latest || entry[1].startedAt > latest[1].startedAt) latest = entry; + return latest; + }), + ); +} + +function ExecutingBar({ path, execution }: { path: string; execution: ConsoleExecution }) { + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + const timer = setInterval(() => setNow(Date.now()), 100); + return () => clearInterval(timer); + }, [execution.startedAt]); + const name = basename(path); + const count = execution.statements; + return ( +
      + + + {count > 1 ? tx`Executing ${count} statements in ${name}…` : tx`Executing in ${name}…`} + + {formatElapsed(Math.max(0, now - execution.startedAt))} +
      + ); +} + export function ResultsView() { const results = useDatabase((s) => s.results); + const execution = useLatestExecution(); const active = useDatabase((s) => s.activeResult); const hasOutput = useDatabase((s) => s.output.length > 0); const root = useRef(null); @@ -772,6 +807,8 @@ export function ResultsView() { owner: e.currentTarget, }); }; + const executing = execution && ; + if (!results.length && !hasOutput && executing) return
      {executing}
      ; if (!results.length && !hasOutput) return ( @@ -825,6 +862,7 @@ export function ResultsView() { ]} /> + {executing}
      (); const runField = StateField.define({ - create: () => ({ marks: [], banner: null }), + create: () => ({ marks: [], banner: null, executing: null }), update(value, tr) { for (const e of tr.effects) if (e.is(setRun)) return e.value; if (!tr.docChanged) return value; + // The request runs the text it was sent; edits only move where that shows. + const ex = value.executing; + const executing = ex && { + ...ex, + spans: ex.spans.map((r) => ({ from: tr.changes.mapPos(r.from, 1), to: tr.changes.mapPos(r.to, -1) })), + at: tr.changes.mapPos(ex.at), + }; // Editing a statement drops its mark. const marks: RunMark[] = []; for (const m of value.marks) { @@ -135,12 +165,18 @@ const runField = StateField.define({ timingAt: tr.changes.mapPos(m.timingAt), }); } - return { ...value, marks }; + return { ...value, marks, executing }; }, provide: (f) => [ EditorView.decorations.from(f, (st) => { const ranges = []; + const ex = st.executing; + for (const r of ex?.spans ?? []) + if (r.from < r.to) ranges.push(Decoration.mark({ class: "cm-openidea-db-executing" }).range(r.from, r.to)); + if (ex) ranges.push(Decoration.widget({ widget: new ElapsedWidget(ex.startedAt), side: 1 }).range(ex.at)); for (const m of st.marks) { + // The new run takes the place of a statement's last outcome. + if (ex?.spans.some((r) => r.from <= m.to && m.from <= r.to)) continue; if (m.error) ranges.push( Decoration.mark({ class: "cm-openidea-db-error", attributes: { title: m.error } }).range(m.from, m.to), @@ -164,11 +200,47 @@ class TimingWidget extends WidgetType { toDOM() { const span = document.createElement("span"); span.className = "cm-openidea-db-timing"; - span.textContent = this.ms < 1000 ? `${Math.round(this.ms)} ms` : `${(this.ms / 1000).toFixed(1)} s`; + span.textContent = formatElapsed(this.ms); return span; } } +/** The running time of the request, ticking until it ends. */ +class ElapsedWidget extends WidgetType { + private timer: ReturnType | undefined; + constructor(readonly startedAt: number) { + super(); + } + eq(other: ElapsedWidget) { + return other.startedAt === this.startedAt; + } + toDOM() { + const span = document.createElement("span"); + span.className = "cm-openidea-db-timing cm-openidea-db-elapsed"; + const tick = () => { + const elapsed = formatElapsed(Date.now() - this.startedAt); + span.textContent = tx`Executing… ${elapsed}`; + }; + tick(); + this.timer = setInterval(tick, 100); + return span; + } + destroy() { + clearInterval(this.timer); + } +} + +class ExecutingMarker extends GutterMarker { + eq(other: GutterMarker) { + return other instanceof ExecutingMarker; + } + toDOM() { + const el = spinnerNode(12, "cm-openidea-db-run-executing"); + el.title = tx("Executing"); + return el; + } +} + class RunMarker extends GutterMarker { constructor(readonly error: string | null) { super(); @@ -192,9 +264,12 @@ const runGutter = gutter({ markers: (view) => { const st = view.state.field(runField); const doc = view.state.doc; - const ranges = st.marks - .filter((m) => m.from <= doc.length) + const ex = st.executing; + const ranges: Range[] = st.marks + .filter((m) => m.from <= doc.length && !ex?.spans.some((r) => r.from <= m.to && m.from <= r.to)) .map((m) => new RunMarker(m.error).range(doc.lineAt(m.from).from)); + const first = ex?.spans[0]; + if (first && first.from <= doc.length) ranges.push(new ExecutingMarker().range(doc.lineAt(first.from).from)); return RangeSet.of(ranges, true); }, }); @@ -233,20 +308,59 @@ export function markOutcomes(view: EditorView, outcomes: readonly DbStatementOut })); const failed = outcomes.find((o) => o.error); const name = failed ? (sourceById(consoleSource(view.state.facet(consolePath)))?.name ?? "") : ""; - view.dispatch({ effects: setRun.of({ marks, banner: failed ? `[${name}] ${failed.error}` : null }) }); + view.dispatch({ + effects: setRun.of({ ...view.state.field(runField), marks, banner: failed ? `[${name}] ${failed.error}` : null }), + }); +} + +let nextExecution = 0; + +/** `outcomes` at where their statements are now, when the text was edited while they ran. */ +function placed( + executing: Executing | null, + token: number, + outcomes: readonly DbStatementOutcome[], +): readonly DbStatementOutcome[] { + if (executing?.token !== token) return outcomes; + return outcomes.map((o) => { + const i = executing.sent.findIndex((r) => r.from === o.statement.from && r.to === o.statement.to); + const now = executing.spans[i]; + return now ? { ...o, statement: { ...o.statement, from: now.from, to: now.to } } : o; + }); +} + +/** Runs `from`–`to` of `view`, showing the submitted statements as executing until the request ends. */ +async function executeRange(view: EditorView, path: string, from: number, to: number) { + const token = ++nextExecution; + const sent = view.state.doc; + const start = (statements: readonly SqlStatement[]) => { + // The offsets are into the text sent; an edit since (while asking for parameters) leaves them unplaced. + if (view.state.doc !== sent) return; + const spans = statements.map((st) => ({ from: st.from, to: st.to })); + const last = spans.at(-1); + if (!last) return; + const at = view.state.sliceDoc(last.to, last.to + 1) === ";" ? last.to + 1 : last.to; + const executing = { token, sent: spans, spans, at, startedAt: Date.now() }; + view.dispatch({ effects: setRun.of({ ...view.state.field(runField), executing }) }); + }; + try { + const outcomes = await executeConsole(path, sent.toString(), from, to, start); + if (outcomes.length) markOutcomes(view, placed(view.state.field(runField).executing, token, outcomes)); + } finally { + const st = view.state.field(runField, false); + if (st?.executing?.token === token) view.dispatch({ effects: setRun.of({ ...st, executing: null }) }); + } } /** Runs the statement at the caret (or the selected ones) of `view`. */ export async function executeInView(view: EditorView, path: string) { const sel = view.state.selection.main; - const outcomes = await executeConsole(path, view.state.doc.toString(), sel.from, sel.to); - if (outcomes.length) markOutcomes(view, outcomes); + await executeRange(view, path, sel.from, sel.to); } /** Runs every statement of `view`, in order (stops at the first that fails). */ export async function executeScriptInView(view: EditorView, path: string) { - const outcomes = await executeConsole(path, view.state.doc.toString(), 0, view.state.doc.length); - if (outcomes.length) markOutcomes(view, outcomes); + await executeRange(view, path, 0, view.state.doc.length); } /** Explain Plan of the statement at the caret (or the first selected one) of `view`. */ diff --git a/src/features/database/inEditorResults.test.tsx b/src/features/database/inEditorResults.test.tsx index a882ae55e..dd2c68436 100644 --- a/src/features/database/inEditorResults.test.tsx +++ b/src/features/database/inEditorResults.test.tsx @@ -3,9 +3,10 @@ import { EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { useProject } from "@/platform/project"; -import { consoleExtension } from "./console"; +import { consoleExtension, executeScriptInView } from "./console"; import { SQL_LANGUAGE } from "./sqlLanguage"; import { executeConsole, rerunResult, useDatabase } from "./store"; +import { provideToolWindowService } from "@/workbench/contributions"; const backend = vi.hoisted(() => ({ execute: vi.fn(), statements: vi.fn() })); @@ -30,6 +31,7 @@ const initial = useDatabase.getState(); let runs = 0; beforeEach(() => { + provideToolWindowService({ show: () => {} } as never); runs = 0; useProject.setState({ project: { name: "p", root: "/p", trusted: true } as never, @@ -134,3 +136,59 @@ describe("In-Editor Results", () => { view.destroy(); }); }); + +describe("statements in flight", () => { + it("marks what was submitted with its running time, then the outcome", async () => { + const parent = document.createElement("div"); + document.body.append(parent); + const doc = "SELECT 1;\nSELECT 2;\n"; + const view = new EditorView({ + parent, + state: EditorState.create({ + doc, + extensions: consoleExtension({ language: SQL_LANGUAGE, path: PATH } as never), + }), + }); + let finish!: () => void; + const gate = new Promise((resolve) => { + finish = resolve; + }); + const execute = backend.execute.getMockImplementation()!; + backend.execute.mockImplementationOnce(async (...args: unknown[]) => { + await gate; + return execute(...(args as Parameters)); + }); + const executing = () => [...view.dom.querySelectorAll(".cm-openidea-db-executing")].map((e) => e.textContent); + const elapsed = () => view.dom.querySelector(".cm-openidea-db-elapsed")?.textContent; + + let pending!: Promise; + await act(async () => { + pending = executeScriptInView(view, PATH); + await vi.waitFor(() => expect(backend.execute).toHaveBeenCalled()); + }); + expect(executing()).toEqual(["SELECT 1", "SELECT 2"]); + expect(elapsed()).toMatch(/^Executing… \d+ ms$/); + expect(view.dom.querySelector(".cm-openidea-db-run-executing")).not.toBeNull(); + + // Typing above moves the marks with their text. + act(() => view.dispatch({ changes: { from: 0, insert: "-- a longer note above\n" } })); + expect(executing()).toEqual(["SELECT 1", "SELECT 2"]); + + await act(async () => { + finish(); + await pending; + }); + expect(executing()).toEqual([]); + expect(elapsed()).toBeUndefined(); + // The outcomes land on the statements, not on where they were when sent. + const lines = [...view.dom.querySelectorAll(".cm-openidea-db-gutter .cm-gutterElement")] + .filter((e) => e.querySelector(".cm-openidea-db-run-ok")) + .map((e) => e.getBoundingClientRect().top); + expect(lines).toHaveLength(2); + expect(view.dom.querySelectorAll(".cm-openidea-db-timing")).toHaveLength(2); + expect(view.state.doc.lineAt(view.posAtDOM(view.dom.querySelector(".cm-openidea-db-timing")!)).text).toBe( + "SELECT 1;", + ); + view.destroy(); + }); +}); diff --git a/src/features/database/index.ts b/src/features/database/index.ts index f1212adab..2419dc64d 100644 --- a/src/features/database/index.ts +++ b/src/features/database/index.ts @@ -157,6 +157,7 @@ export function activate(): () => void { manualCommit: new Set(), pendingTx: new Set(), running: {}, + executions: {}, dialog: null, newMenuOpen: false, }); diff --git a/src/features/database/requestLifecycle.test.ts b/src/features/database/requestLifecycle.test.ts index 74bddfecf..1a8db190b 100644 --- a/src/features/database/requestLifecycle.test.ts +++ b/src/features/database/requestLifecycle.test.ts @@ -67,6 +67,7 @@ import { useDatabase, withConnection, } from "./store"; +import { provideToolWindowService } from "@/workbench/contributions"; const initial = useDatabase.getState(); const initialProject = useProject.getState(); @@ -129,6 +130,8 @@ function switchProject(project: ProjectInfo) { } beforeEach(() => { + // `showServiceView` reaches the real service, not the mocked accessor above. + provideToolWindowService({ show: ui.show } as never); vi.resetAllMocks(); useProject.setState({ project: projectA }); savedSources = [pg, other]; diff --git a/src/features/database/resultView.ts b/src/features/database/resultView.ts index 56b16052c..6c779c6e8 100644 --- a/src/features/database/resultView.ts +++ b/src/features/database/resultView.ts @@ -1,7 +1,7 @@ /** * Pure helpers of the result views: IDEA's local filter and client-side sort * of loaded rows, search in the grid, paging of console results, the - * Aggregates of a selection, and the series of the chart. + * Aggregates of a selection, the series of the chart, and how long a statement took. */ import type { Cell } from "./model"; @@ -462,3 +462,8 @@ export function pageWindow({ page, pageSize, rows, hasMore, total }: PageState): export function pageFetch(page: number, pageSize: number): { maxRows: number; skip: number } { return { maxRows: pageSize, skip: page * pageSize }; } + +/** A statement's run time as IDEA shows it: `840 ms`, `3.2 s`. */ +export function formatElapsed(ms: number): string { + return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`; +} diff --git a/src/features/database/results-view.test.tsx b/src/features/database/results-view.test.tsx index 050173e80..cc8c33045 100644 --- a/src/features/database/results-view.test.tsx +++ b/src/features/database/results-view.test.tsx @@ -9,6 +9,7 @@ import { ResultsView } from "./ResultsView"; import { executeConsole, explainConsole, pinResult, rerunResult, useDatabase, type ResultTab } from "./store"; import { registerResultTabActions } from "./resultTabActions"; import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus"; +import { provideToolWindowService } from "@/workbench/contributions"; const backend = vi.hoisted(() => ({ driver: "postgres" as DbDriver, @@ -95,6 +96,7 @@ function show(text: string, columns: Array<{ name: string }>, rows: (string | nu } beforeEach(() => { + provideToolWindowService({ show: () => {} } as never); vi.clearAllMocks(); backend.statements.mockImplementation((_id: unknown, text: string) => Promise.resolve({ status: "ok", data: [{ from: 0, to: text.length, text }] }), @@ -809,3 +811,64 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab expect(useDatabase.getState().activeResult).toBe(fresh); }); }); + +describe("a console request in flight", () => { + const hold = () => { + let finish!: () => void; + const gate = new Promise((resolve) => { + finish = resolve; + }); + const execute = backend.execute.getMockImplementation()!; + backend.execute.mockImplementationOnce(async (...args: unknown[]) => { + await gate; + return execute(...(args as Parameters)); + }); + return () => finish(); + }; + + it("shows that it is executing instead of No results on a first run", async () => { + show("SELECT 1", [{ name: "id" }], [["1"]]); + useDatabase.setState({ results: [], activeResult: null, consoles: { "console.sql": "pg" } }); + const finish = hold(); + await act(async () => render()); + let pending!: Promise; + await act(async () => { + pending = executeConsole("console.sql", "SELECT pg_sleep(5)", 0, 0); + await vi.waitFor(() => expect(backend.execute).toHaveBeenCalled()); + }); + expect(screen.queryByText("No results")).toBeNull(); + expect(screen.getByText("Executing in console.sql…").parentElement).toHaveTextContent(/\d+ ms$/); + await act(async () => { + finish(); + await pending; + }); + expect(screen.queryByText(/Executing in/)).toBeNull(); + expect(useDatabase.getState().executions).toEqual({}); + }); + + it("keeps the previous result visible while the next run executes", async () => { + show("SELECT * FROM users", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]); + useDatabase.setState({ consoles: { "console.sql": "pg" } }); + backend.statements.mockResolvedValueOnce({ + status: "ok", + data: [ + { from: 0, to: 8, text: "SELECT 1" }, + { from: 10, to: 18, text: "SELECT 2" }, + ], + }); + const finish = hold(); + await act(async () => render()); + let pending!: Promise; + await act(async () => { + pending = executeConsole("console.sql", "SELECT 1; SELECT 2", 0, 18); + await vi.waitFor(() => expect(backend.execute).toHaveBeenCalled()); + }); + expect(screen.getByText("Executing 2 statements in console.sql…")).toBeTruthy(); + expect(screen.getByText("Ann")).toBeTruthy(); + await act(async () => { + finish(); + await pending; + }); + expect(screen.queryByText(/Executing/)).toBeNull(); + }); +}); diff --git a/src/features/database/store.ts b/src/features/database/store.ts index 212917e72..b1e386dd1 100644 --- a/src/features/database/store.ts +++ b/src/features/database/store.ts @@ -174,6 +174,12 @@ export interface SourceCatalog { databases: Record; } +export interface ConsoleExecution { + startedAt: number; + /** Statements submitted (a batch runs them in order; the backend doesn't say which one is current). */ + statements: number; +} + interface DatabaseState { sources: DataSource[]; loaded: boolean; @@ -205,6 +211,8 @@ interface DatabaseState { output: OutputLine[]; /** Console path → running request. */ running: Record; + /** Console path → what its running request submitted, and since when (ms since the epoch). */ + executions: Record; maxRows: number; dialog: DialogState | null; /** Target of the tree's lead node. */ @@ -271,6 +279,7 @@ export const useDatabase = create(() => ({ activeResult: null, output: [], running: {}, + executions: {}, maxRows: 500, dialog: null, selectedSource: null, @@ -1233,6 +1242,8 @@ export async function executeConsole( text: string, from: number, to: number, + /** Called once the statements are submitted, with what was submitted. */ + onStart?: (statements: readonly SqlStatement[]) => void, ): Promise { const id = consoleSource(path); if (!id) { @@ -1252,8 +1263,14 @@ export async function executeConsole( const prev = useDatabase.getState().running[path]; if (prev) void commands.cancelRequest(prev); const request = nextRequestId(); - useDatabase.setState((s) => ({ running: { ...s.running, [path]: request } })); + useDatabase.setState((s) => ({ + running: { ...s.running, [path]: request }, + executions: { ...s.executions, [path]: { startedAt: Date.now(), statements: statements.length } }, + })); + onStart?.(statements); try { + // IDEA brings the results up as the run starts, showing it executing. + if (!inEditorResults()) showServiceView(RESULTS_VIEW, false); const pageSize = useDatabase.getState().maxRows; const schema = consoleSchema(path) || (await loadCompletion(id))?.defaultSchema || ""; if (!current()) return []; @@ -1296,7 +1313,9 @@ export async function executeConsole( if (s.running[path] !== request) return s; const running = { ...s.running }; delete running[path]; - return { running }; + const executions = { ...s.executions }; + delete executions[path]; + return { running, executions }; }); } } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 70d196419..92a13c909 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -166,6 +166,10 @@ "Select Next Tab": "Select Next Tab", "Select Previous Tab": "Select Previous Tab", "Result {n}-{index}": "Result {n}-{index}", + "Executing": "Executing", + "Executing {count} statements in {name}…": "Executing {count} statements in {name}…", + "Executing in {name}…": "Executing in {name}…", + "Executing… {elapsed}": "Executing… {elapsed}", "Absolute": "Absolute", "Relative": "Relative", "Hybrid": "Hybrid", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index cab44ad2b..42830a83b 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -4861,6 +4861,10 @@ "Remove data source '{name}'? Its query console file stays on disk.": "是否移除数据源 '{name}'?其查询控制台文件将保留在磁盘上。", "Result {n}": "结果 {n}", "Result {n}-{index}": "结果 {n}-{index}", + "Executing": "正在执行", + "Executing {count} statements in {name}…": "正在 {name} 中执行 {count} 条语句…", + "Executing in {name}…": "正在 {name} 中执行…", + "Executing… {elapsed}": "正在执行… {elapsed}", "{name} has uncommitted changes. Commit or roll them back before switching to auto-commit?": "{name} 有未提交的更改。是否在切换到自动提交前提交或回滚这些更改?", "Cannot copy the name": "无法复制名称", "Cannot copy the reference": "无法复制引用", diff --git a/src/ui/iconNode.ts b/src/ui/iconNode.ts index d20f4937e..b0ce7698a 100644 --- a/src/ui/iconNode.ts +++ b/src/ui/iconNode.ts @@ -1,5 +1,6 @@ /** Design-system icons as DOM nodes for CodeMirror widgets. */ import { iconMarkupOrFallback, type IconName } from "./icons"; +import spinnerStyles from "./Spinner.module.css"; export function iconNode(name: IconName | (string & {}), size = 16, className?: string): HTMLElement { const span = document.createElement("span"); @@ -8,3 +9,16 @@ export function iconNode(name: IconName | (string & {}), size = 16, className?: span.innerHTML = iconMarkupOrFallback(name, size); return span; } + +/** The ring `Spinner` as a DOM node for CodeMirror widgets and gutters. */ +export function spinnerNode(size = 14, className?: string): HTMLElement { + const span = document.createElement("span"); + span.className = className ? `cm-openidea-icon ${className}` : "cm-openidea-icon"; + span.setAttribute("aria-hidden", "true"); + span.innerHTML = + `` + + '' + + '' + + ""; + return span; +} From f0273690b98ed5871fff6e8b78d130723883e512 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 04:07:52 +0800 Subject: [PATCH 05/12] fix(run): keep test results readable in narrow panes (#4586) The test tree's header held the counts, duration and every toolbar action in one 28px row, so narrow Run panes clipped the counts and buttons. As in IDEA's new layout, the status (icon, counts, total duration) now sits above the console, Expand All, Collapse All and Export Test Results move into a More Actions menu, and the tree and console stack vertically below 560px with their own remembered split. --- e2e/run.spec.ts | 79 ++++++++++++++++++- src/features/run/Run.module.css | 37 +++++++-- src/features/run/RunView.tsx | 47 +++++++++-- src/features/run/TestTreeView.test.tsx | 30 ++++--- src/features/run/TestTreeView.tsx | 103 ++++++++++++++++++------- 5 files changed, 239 insertions(+), 57 deletions(-) diff --git a/e2e/run.spec.ts b/e2e/run.spec.ts index 0d6edf708..b2fd1ff95 100644 --- a/e2e/run.spec.ts +++ b/e2e/run.spec.ts @@ -3,15 +3,21 @@ * the process. Processes are stubbed at the IPC layer; `crates/ide-run` covers spawning them. */ import type { Page } from "@playwright/test"; +import type { RunConfig } from "../src/bindings"; import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; const RUN_ID = 7; /** One saved `npm run dev` configuration; `run_start` prints `output` and exits with `exit` unless null. */ -async function stubRun(page: Page, output: { kind: string; text: string }[], exit: number | null) { +async function stubRun( + page: Page, + output: { kind: string; text: string }[], + exit: number | null, + overrides: Partial = {}, +) { await stubDesktop(page); await page.evaluate( - async ({ output, exit, runId }) => { + async ({ output, exit, runId, overrides }) => { const config = { id: "npm:dev", name: "dev", @@ -23,6 +29,7 @@ async function stubRun(page: Page, output: { kind: string; text: string }[], exi detected: false, isTest: false, debugAdapter: null, + ...overrides, }; const h = window.__ipc.handlers; h.run_configs = () => [config]; @@ -43,7 +50,7 @@ async function stubRun(page: Page, output: { kind: string; text: string }[], exi await loadConfigs(); selectConfig(config.id); }, - { output, exit, runId: RUN_ID }, + { output, exit, runId: RUN_ID, overrides }, ); } @@ -177,6 +184,72 @@ test("Go reruns keep each package's exact failures and the original configuratio ]); }); +test("test results keep counts, actions and selected output visible as the pane narrows", async ({ + workbench: page, +}) => { + await page.setViewportSize({ width: 1060, height: 740 }); + const goPackage = "example.com/checkout"; + const name = "TestCheckoutTotalsWithDiscountsAndPendingInventoryReservations"; + const message = "expected subtotal 42, got 37"; + const records = [ + { Action: "run", Test: name }, + { Action: "output", Test: name, Output: message + "\n" }, + { Action: "fail", Test: name, Elapsed: 0.125 }, + { Action: "pass", Test: "TestPayment", Elapsed: 0.02 }, + { Action: "skip", Test: "TestDelayedShipping" }, + { Action: "fail", Elapsed: 0.17 }, + ]; + await stubRun( + page, + records.map((record) => ({ kind: "stdout", text: JSON.stringify({ Package: goPackage, ...record }) + "\n" })), + 1, + { + id: "go:checkout-tests", + name: "Checkout tests", + kind: "go", + command: "go", + args: ["test", "-json"], + isTest: true, + }, + ); + await page.keyboard.press("Control+r"); + const run = page.getByRole("region", { name: "Run", exact: true }); + const tree = run.getByRole("tree", { name: "Test results" }); + const row = tree.getByRole("treeitem", { name: new RegExp(name) }); + await row.click(); + const output = run.getByRole("log"); + await expect(output).toContainText(message); + await expect.poll(async () => (await output.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true); + await page.setViewportSize({ width: 540, height: 740 }); + await expect + .poll(async () => { + const [list, console] = await Promise.all([tree.boundingBox(), output.boundingBox()]); + return !!list && !!console && console.y >= list.y + list.height - 1; + }) + .toBe(true); + const summary = run.getByRole("status").filter({ hasText: "1 failing" }); + for (const count of ["1 failing", "1 passed", "1 ignored"]) await expect(summary.getByText(count)).toBeVisible(); + await expect(row).toHaveAttribute("aria-selected", "true"); + await expect(row.getByText("125 ms")).toBeVisible(); + await expect(output).toContainText(message); + const toolbar = run.getByRole("toolbar", { name: "Test results" }); + await toolbar.getByRole("button", { name: "More Actions" }).click(); + await expect(page.getByRole("menuitem", { name: "Collapse All" })).toBeVisible(); + await expect(page.getByRole("menuitem", { name: "Export Test Results…" })).toBeVisible(); + await page.keyboard.press("Escape"); + const divider = run.getByRole("separator"); + const treeHeight = async () => (await tree.boundingBox())!.height; + const beforeResize = await treeHeight(); + await divider.press("ArrowDown"); + await expect.poll(treeHeight).toBeGreaterThan(beforeResize + 1); + const customizedHeight = await treeHeight(); + await page.setViewportSize({ width: 1060, height: 740 }); + await expect.poll(async () => (await output.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true); + await page.setViewportSize({ width: 540, height: 740 }); + await expect.poll(async () => Math.abs((await treeHeight()) - customizedHeight)).toBeLessThan(2); + await expect(output).toContainText(message); +}); + test("CMake builds the selected target in Build before starting only the application in Run", async ({ workbench: page, }) => { diff --git a/src/features/run/Run.module.css b/src/features/run/Run.module.css index 113d36018..bcc40ebb2 100644 --- a/src/features/run/Run.module.css +++ b/src/features/run/Run.module.css @@ -253,26 +253,44 @@ flex-direction: column; height: 100%; min-width: 0; - border-right: 1px solid var(--border); } -.testHeader { +.testToolbar, +.testStatusBar { flex: none; display: flex; + flex-wrap: wrap; align-items: center; - gap: var(--space-2); - height: 28px; - padding: 0 4px 0 10px; + min-height: 28px; border-bottom: 1px solid var(--border); +} +.testToolbar { + gap: var(--space-0-5); + padding: var(--space-0-5) var(--space-1); +} +.testStatusBar { + gap: var(--space-0-5) var(--space-2); + padding: var(--space-0-5) var(--space-2); font-size: var(--fs-ui); color: var(--fg-secondary); } .testCounts { + flex: 1 1 auto; display: flex; - gap: 10px; + flex-wrap: wrap; + gap: var(--space-0-5) var(--space-2); min-width: 0; - overflow: hidden; white-space: nowrap; } +.testStatus, +.testTotalDuration { + flex: none; +} +.testTotalDuration { + margin-left: auto; + color: var(--fg-subtle); + font-size: var(--fs-small); + font-variant-numeric: tabular-nums; +} .testTree { flex: 1; min-height: 0; @@ -299,8 +317,11 @@ flex: none; padding-right: 8px; color: var(--fg-subtle); - font-family: var(--font-mono); font-size: var(--fs-small); + font-variant-numeric: tabular-nums; +} +.testTree [aria-selected="true"] .testDuration { + color: var(--fg); } .testEmpty { padding: 12px; diff --git a/src/features/run/RunView.tsx b/src/features/run/RunView.tsx index eb77d7a7a..f1051c480 100644 --- a/src/features/run/RunView.tsx +++ b/src/features/run/RunView.tsx @@ -1,5 +1,6 @@ -import { useEffect, useMemo, useRef, useState } from "react"; +import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import clsx from "clsx"; +import type { GroupImperativeHandle, Layout } from "react-resizable-panels"; import type { RunConfig } from "@/platform/ipc"; import type { RunTargetValid } from "@/platform/remoteSettings"; import { useAgentRunSettings, useWorkflowSettings } from "@/platform/workflowSettings"; @@ -47,7 +48,7 @@ import { } from "./store"; import { rerunFailedConfigs } from "./testing/rerun"; import { formatDuration, nodeOutput } from "./testing"; -import { TestTreeView } from "./TestTreeView"; +import { TestStatusBar, TestTreeView } from "./TestTreeView"; import { StackTracePanel, useStackTraces, type StackTraceTab } from "./stackTrace"; import { closeRunTab, runTabMenu } from "./runTabs"; import { showApplicationUpdate, useApplicationUpdates } from "./applicationUpdate"; @@ -59,6 +60,11 @@ import { archivedAgentSessions, closeAgentArchive } from "./agentRuns"; import styles from "./Run.module.css"; import { tx } from "@/platform/i18n"; +const TEST_SPLIT_DEFAULTS = { + horizontal: { tests: 34, console: 66 }, + vertical: { tests: 48, console: 52 }, +}; + function failed(s: RunSession): boolean { return s.status === "failed" || (s.status === "finished" && s.exitCode !== 0 && !s.stopped); } @@ -93,6 +99,25 @@ export function SessionPanel({ const softWrap = wrapOverride ?? defaultWrap; const [selectedTest, setSelectedTest] = useState(null); const [findOpen, setFindOpen] = useState(false); + const body = useRef(null); + const [stackedTests, setStackedTests] = useState(false); + const testSplit = useRef(null); + const testLayouts = useRef>({ ...TEST_SPLIT_DEFAULTS }); + const testOrientation = stackedTests ? "vertical" : "horizontal"; + const hasTests = !!rt?.tests; + useLayoutEffect(() => { + const pane = body.current; + if (!hasTests || !pane) return; + const measure = () => setStackedTests(pane.clientWidth < 560); + measure(); + if (typeof ResizeObserver === "undefined") return; + const resize = new ResizeObserver(measure); + resize.observe(pane); + return () => resize.disconnect(); + }, [hasTests]); + useLayoutEffect(() => { + if (hasTests) testSplit.current?.setLayout(testLayouts.current[testOrientation]); + }, [hasTests, testOrientation]); const running = isLive(session); const cwd = runDirectory(session.config.cwd); const baseConfig = useRun(() => baseConfigOf(session)); @@ -136,6 +161,7 @@ export function SessionPanel({ const consoleColumn = (
      + {rt.tests && } {rt.console.dropped > 0 && !testModel && (
      {tx`${rt.console.dropped.toLocaleString()} earlier lines were discarded`}
      )} @@ -279,10 +305,19 @@ export function SessionPanel({ />
      -
      +
      {rt.tests ? ( - - + { + if (meta.isUserInteraction) testLayouts.current[testOrientation] = meta.requestedLayout ?? layout; + }} + > + - + {consoleColumn} diff --git a/src/features/run/TestTreeView.test.tsx b/src/features/run/TestTreeView.test.tsx index be22eeef8..c77b5ee5e 100644 --- a/src/features/run/TestTreeView.test.tsx +++ b/src/features/run/TestTreeView.test.tsx @@ -49,6 +49,12 @@ function Host(props: { ); } +function moreItem(name: string) { + const trigger = screen.getByRole("button", { name: "More Actions" }); + if (trigger.getAttribute("aria-expanded") !== "true") fireEvent.click(trigger); + return screen.getByRole("menuitem", { name }); +} + describe("TestTreeView", () => { beforeEach(() => localStorage.clear()); afterEach(() => vi.clearAllMocks()); @@ -264,17 +270,17 @@ describe("Expand All / Collapse All", () => { expect(rows()).toContain("reuses()"); }); - it("the buttons run the actions, and are unavailable without suites", () => { + it("the menu runs the actions, and they are unavailable without suites", () => { const dispose = registerActions([ { id: "run.expandAllTests", title: "Expand All", run: () => {} }, { id: "run.collapseAllTests", title: "Collapse All", run: () => {} }, ]); onTestFinished(dispose); const { unmount } = render(view(nested())); - fireEvent.click(screen.getByRole("button", { name: "Expand All" })); - expect(actions.executeAction).toHaveBeenCalledWith("run.expandAllTests", undefined); - fireEvent.click(screen.getByRole("button", { name: "Collapse All" })); - expect(actions.executeAction).toHaveBeenCalledWith("run.collapseAllTests", undefined); + fireEvent.click(moreItem("Expand All")); + expect(actions.executeAction).toHaveBeenCalledWith("run.expandAllTests"); + fireEvent.click(moreItem("Collapse All")); + expect(actions.executeAction).toHaveBeenCalledWith("run.collapseAllTests"); unmount(); expect(testTree.expandAll).toBeNull(); @@ -282,8 +288,8 @@ describe("Expand All / Collapse All", () => { flat.apply([{ type: "result", path: ["main_test"], status: "failed" }]); flat.finish(1); render(view(flat)); - expect(screen.getByRole("button", { name: "Expand All" })).toBeDisabled(); - expect(screen.getByRole("button", { name: "Collapse All" })).toBeDisabled(); + expect(moreItem("Expand All")).toHaveAttribute("aria-disabled", "true"); + expect(moreItem("Collapse All")).toHaveAttribute("aria-disabled", "true"); }); }); @@ -306,9 +312,9 @@ describe("Export Test Results", () => { /> ); - it("the button and the action open the dialog for the finished run", () => { + it("the menu and the action open the dialog for the finished run", () => { const { unmount } = render(view(finished(), false)); - fireEvent.click(screen.getByRole("button", { name: "Export Test Results…" })); + fireEvent.click(moreItem("Export Test Results…")); expect(screen.getByRole("dialog", { name: "Export Test Results" })).toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: "Cancel" })); act(() => testTree.exportResults!()); @@ -322,13 +328,13 @@ describe("Export Test Results", () => { it("is unavailable while the tests run and without results", () => { const { rerender } = render(view(finished(), true)); - expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeDisabled(); + expect(moreItem("Export Test Results…")).toHaveAttribute("aria-disabled", "true"); expect(testTree.exportResults).toBeNull(); rerender(view(new TestResults(), false)); - expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeDisabled(); + expect(moreItem("Export Test Results…")).toHaveAttribute("aria-disabled", "true"); expect(testTree.exportResults).toBeNull(); rerender(view(finished(), false)); - expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeEnabled(); + expect(moreItem("Export Test Results…")).not.toHaveAttribute("aria-disabled", "true"); expect(testTree.exportResults).not.toBeNull(); }); }); diff --git a/src/features/run/TestTreeView.tsx b/src/features/run/TestTreeView.tsx index 3f3b221d0..21467c36a 100644 --- a/src/features/run/TestTreeView.tsx +++ b/src/features/run/TestTreeView.tsx @@ -9,6 +9,7 @@ import { showContextMenu, useContextMenuStore, Spinner, + Toolbar, Tree, type MenuItem, type TreeHandle, @@ -83,6 +84,41 @@ export function StatusIcon({ status }: { status: TestStatus | null }) { } } +export function TestStatusBar({ + results, + version, + running, +}: { + results: TestResults; + version: number; + running: boolean; +}) { + const counts = useMemo(() => results.counts(), [results, version]); // eslint-disable-line react-hooks/exhaustive-deps + const status = running + ? "running" + : counts.failed + ? "failed" + : counts.passed + ? "passed" + : counts.skipped + ? "skipped" + : null; + const duration = results.summary.durationMs; + + return ( +
      + + + {counts.failed > 0 && {tx`${counts.failed} failing`}} + {counts.passed > 0 && {tx`${counts.passed} passed`}} + {counts.skipped > 0 && {tx`${counts.skipped} ignored`}} + {counts.total === 0 && {running ? tx("Running…") : tx("No tests")}} + + {duration !== undefined && {formatDuration(duration)}} +
      + ); +} + const isFailedTest = (n: TestNode) => n.children.length === 0 && nodeStatus(n) === "failed"; const treeModel = { @@ -163,6 +199,8 @@ export function TestTreeView({ }); const sortButton = useRef(null); const [sortMenu, setSortMenu] = useState(false); + const moreButton = useRef(null); + const [moreMenu, setMoreMenu] = useState(false); const [expanded, setExpanded] = useState | null>(null); const [exporting, setExporting] = useState(false); const [selection, setSelection] = useState>(new Set()); @@ -226,7 +264,6 @@ export function TestTreeView({ } }; - const counts = useMemo(() => results.counts(), [results, version]); // eslint-disable-line react-hooks/exhaustive-deps // Like IDEA, Sort by Duration applies once the run has finished, so rows don't jump while tests report. const byDuration = sortByDuration && !running; const roots = useMemo(() => { @@ -276,21 +313,9 @@ export function TestTreeView({ const hasPrevFailed = findOccurrence(roots, selected, -1, treeModel) !== null; const hasNextFailed = findOccurrence(roots, selected, 1, treeModel) !== null; - const status = running ? "running" : counts.failed > 0 ? "failed" : counts.total > 0 ? "passed" : null; - const duration = results.summary.durationMs; - return (
      -
      - - - {counts.failed > 0 && {tx`${counts.failed} failing`}} - {counts.passed > 0 && {tx`${counts.passed} passed`}} - {counts.skipped > 0 && {tx`${counts.skipped} ignored`}} - {counts.total === 0 && {running ? tx("Running…") : tx("No tests")}} - {duration !== undefined && {formatDuration(duration)}} - - + setSortMenu(false)} /> - - setExporting(true)} + title="More Actions" + aria-haspopup="menu" + aria-expanded={moreMenu} + onClick={() => setMoreMenu((open) => !open)} /> -
      + setMoreMenu(false)} + items={[ + { + icon: "expand-all", + label: "Expand All", + disabled: !hasSuites, + run: () => void executeAction("run.expandAllTests"), + }, + { + icon: "collapse-all", + label: "Collapse All", + disabled: !hasSuites, + run: () => void executeAction("run.collapseAllTests"), + }, + { kind: "separator" }, + { + icon: "export", + label: "Export Test Results…", + disabled: !canExport, + run: () => setExporting(true), + }, + ]} + /> + {exporting && ( setExporting(false)} /> )} @@ -396,7 +441,9 @@ export function TestTreeView({ return ( - {n.name} + + {n.name} + {d !== undefined && {formatDuration(d)}} ); From 750d35dd6ecf811e2e3ecb5df185b7e6d0433141 Mon Sep 17 00:00:00 2001 From: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:10:23 +0200 Subject: [PATCH 06/12] fix(vcs): discard stale status after project switch (#4598) The VCS store reset on project switch, but replies to refreshes started for the previous project still wrote to it, restoring its branch, changed files and decorations and firing conflict notifications. A project generation, bumped on every switch (also when reopening the same folder), now gates full and incremental refresh results, errors and discovered roots; queued paths are dropped on switch, and the refresh queue still drains for the active project. Closes #4596 Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> --- src/features/vcs/store.switch.test.ts | 208 ++++++++++++++++++++++++++ src/features/vcs/store.ts | 25 +++- src/test/deferred.ts | 9 ++ 3 files changed, 236 insertions(+), 6 deletions(-) create mode 100644 src/features/vcs/store.switch.test.ts create mode 100644 src/test/deferred.ts diff --git a/src/features/vcs/store.switch.test.ts b/src/features/vcs/store.switch.test.ts new file mode 100644 index 000000000..72ad8f01e --- /dev/null +++ b/src/features/vcs/store.switch.test.ts @@ -0,0 +1,208 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { BranchInfo, FileStatus, ProjectInfo, VcsRoot } from "@/bindings"; +import { commands, isTauri } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { deferred } from "@/test/deferred"; +import { getFileDecoration } from "@/workbench/contributions"; +import { + discoverRoots, + installVcsStore, + onConflictsAppeared, + onConflictsCleared, + refreshNow, + refreshPathsNow, + useVcs, +} from "./store"; + +vi.mock(import("@/platform/ipc"), async (original) => ({ + ...(await original()), + isTauri: vi.fn(() => false), +})); + +const git: ProjectInfo = { root: "/a", name: "a", isGit: true, trusted: true, settings: {} }; +const nonGit: ProjectInfo = { root: "/b", name: "b", isGit: false, trusted: true, settings: {} }; +const branch: BranchInfo = { + head: "feature-a", + headCommit: "abc1234", + upstream: null, + ahead: 0, + behind: 0, + operation: "merge", +}; +const roots: VcsRoot[] = [{ root: git.root, head: branch.head, headCommit: branch.headCommit, operation: "merge" }]; +const conflicted: FileStatus = { + path: "/a/src/conflict.ts", + relPath: "src/conflict.ts", + staged: null, + unstaged: "conflicted", + renamedFrom: null, +}; +const modified: FileStatus = { + ...conflicted, + path: "/a/src/edited.ts", + relPath: "src/edited.ts", + unstaged: "modified", +}; +const status = [conflicted, modified]; + +type Ok = { status: "ok"; data: T }; +const ok = (data: T): Ok => ({ status: "ok", data }); + +let dispose: () => void; +const appeared = vi.fn(); +const cleared = vi.fn(); + +beforeEach(() => { + vi.spyOn(commands, "vcsRoots").mockResolvedValue(ok(roots)); + vi.spyOn(commands, "vcsStatus").mockResolvedValue(ok(status)); + vi.spyOn(commands, "vcsBranchInfo").mockResolvedValue(ok(branch)); + onConflictsAppeared(appeared); + onConflictsCleared(cleared); + dispose = installVcsStore(); +}); + +afterEach(() => { + dispose(); + onConflictsAppeared(() => undefined); + onConflictsCleared(() => undefined); + appeared.mockClear(); + cleared.mockClear(); + vi.restoreAllMocks(); + vi.mocked(isTauri).mockReset(); + useProject.setState(useProject.getInitialState(), true); + useVcs.setState(useVcs.getInitialState(), true); +}); + +describe("VCS status ownership", () => { + it.each([ + { command: "status", reopen: false }, + { command: "roots", reopen: false }, + { command: "status", reopen: true }, + ])("drops a late $command response after switching projects (reopen: $reopen)", async ({ command, reopen }) => { + const response = deferred(); + const request = + command === "status" + ? vi.mocked(commands.vcsStatus).mockReturnValueOnce(response.promise.then(() => ok(status))) + : vi.mocked(commands.vcsRoots).mockReturnValueOnce(response.promise.then(() => ok(roots))); + useProject.setState({ project: git }); + const refreshing = refreshNow(); + try { + await vi.waitFor(() => expect(request).toHaveBeenCalledOnce()); + // Emulate desktop discovery of nested roots for the non-Git project; there are none. + vi.mocked(isTauri).mockReturnValueOnce(true); + vi.mocked(commands.vcsRoots).mockResolvedValueOnce(ok([])); + useProject.setState({ project: nonGit }); + const current = reopen ? { ...git } : nonGit; + if (reopen) useProject.setState({ project: current }); + const reset = useVcs.getState(); + expect(reset).toMatchObject({ root: current.root, status: [], branch: null, statusLoaded: false }); + + response.resolve(); + await refreshing; + + expect(useProject.getState().project).toBe(current); + expect.soft(useVcs.getState()).toEqual(reset); + expect.soft(getFileDecoration(conflicted.path)).toBeUndefined(); + expect.soft(getFileDecoration(modified.path)).toBeUndefined(); + expect.soft(appeared).not.toHaveBeenCalled(); + expect.soft(cleared).not.toHaveBeenCalled(); + } finally { + response.resolve(); + await refreshing; + } + }); + + it("does not publish an old refresh error in the new project", async () => { + const reply = deferred>(); + const request = vi.mocked(commands.vcsStatus).mockReturnValueOnce(reply.promise); + useProject.setState({ project: git }); + const refreshing = refreshNow(); + try { + await vi.waitFor(() => expect(request).toHaveBeenCalledOnce()); + useProject.setState({ project: nonGit }); + const reset = useVcs.getState(); + + reply.reject(new Error("project A's Git status failed")); + await refreshing; + + expect(useVcs.getState()).toEqual(reset); + } finally { + reply.resolve(ok(status)); + await refreshing; + } + }); + + it("does not enable VCS from a discovery started before reopening the same folder", async () => { + const reply = deferred>(); + const request = vi.mocked(commands.vcsRoots).mockReturnValueOnce(reply.promise); + const folder = { ...git, isGit: false }; + useProject.setState({ project: folder }); + vi.mocked(isTauri).mockReturnValueOnce(true); + const discovering = discoverRoots(); + // Drain any incorrectly started full refresh before disposing. + const refreshed = deferred(); + const offRefresh = useVcs.subscribe((s, prev) => { + if (prev.loading && !s.loading) refreshed.resolve(); + }); + try { + await vi.waitFor(() => expect(request).toHaveBeenCalledOnce()); + useProject.setState({ project: nonGit }); + useProject.setState({ project: { ...folder } }); + + reply.resolve(ok(roots)); + await discovering; + if (useVcs.getState().loading) await refreshed.promise; + + expect.soft(useVcs.getState()).toMatchObject({ root: folder.root, available: false, roots: [], status: [] }); + expect.soft(commands.vcsStatus).not.toHaveBeenCalled(); + } finally { + reply.resolve(ok([])); + await discovering; + if (useVcs.getState().loading) await refreshed.promise; + offRefresh(); + } + }); + + it("drains a queued refresh for the new project without retrying the old incremental refresh", async () => { + useProject.setState({ project: git }); + await refreshNow(); + const reply = deferred>(); + const request = vi.spyOn(commands, "vcsStatusPaths").mockReturnValueOnce(reply.promise); + const refreshing = refreshPathsNow([conflicted.path]); + let next: Promise | undefined; + try { + await vi.waitFor(() => expect(request).toHaveBeenCalledWith([conflicted.path])); + const nextBranch = { ...branch, head: "main", operation: null }; + vi.mocked(commands.vcsRoots).mockResolvedValue( + ok([{ root: nonGit.root, head: nextBranch.head, headCommit: nextBranch.headCommit, operation: null }]), + ); + vi.mocked(commands.vcsStatus).mockResolvedValue(ok([])); + vi.mocked(commands.vcsBranchInfo).mockResolvedValue(ok(nextBranch)); + vi.mocked(isTauri).mockReturnValueOnce(true); + useProject.setState({ project: { ...nonGit, isGit: true } }); + next = refreshNow(); + + reply.resolve(ok([conflicted])); + await Promise.all([refreshing, next]); + + expect(useVcs.getState()).toMatchObject({ root: nonGit.root, status: [], branch: nextBranch }); + expect(getFileDecoration(conflicted.path)).toBeUndefined(); + expect(commands.vcsStatus).toHaveBeenCalledTimes(2); + } finally { + reply.resolve(ok([])); + await Promise.all([refreshing, next]); + } + }); + + it("applies branch, changed files, decorations and conflict notifications for the active project", async () => { + useProject.setState({ project: git }); + await refreshNow(); + + expect(useVcs.getState()).toMatchObject({ root: git.root, roots: [git.root], branch, status, statusLoaded: true }); + expect(useVcs.getState().byPath).toEqual(new Map(status.map((file) => [file.path, file]))); + expect(getFileDecoration(conflicted.path)?.color).toBe("var(--vcs-conflict)"); + expect(getFileDecoration(modified.path)?.color).toBe("var(--vcs-modified)"); + expect(appeared).toHaveBeenCalledExactlyOnceWith([conflicted]); + expect(cleared).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/vcs/store.ts b/src/features/vcs/store.ts index 584f8a891..afba340f3 100644 --- a/src/features/vcs/store.ts +++ b/src/features/vcs/store.ts @@ -152,6 +152,9 @@ export function conflictedFiles(status: readonly FileStatus[] = useVcs.getState( return status.filter((f) => effectiveKind(f) === "conflicted"); } +// Reopening the same root starts a new lifetime. +let projectGeneration = 0; + let timer: ReturnType | undefined; /** A full refresh is queued; it answers for every path an incremental one would. */ let pendingFull = false; @@ -221,6 +224,7 @@ export function refreshNow(): Promise { }); return followUp; } + const generation = projectGeneration; inflight = (async () => { useVcs.setState({ loading: true }); try { @@ -238,6 +242,7 @@ export function refreshNow(): Promise { call(commands.vcsStatus()), scoped, ]); + if (generation !== projectGeneration) return; const roots = vcsRoots.map((r) => r.root); if ("error" in selected) { // The selected repository is gone (removed since the last scan): fall back to the primary one. @@ -263,9 +268,13 @@ export function refreshNow(): Promise { void refreshNow(); } } catch (e) { - useVcs.setState({ error: e instanceof Error ? e.message : String(e) }); + if (generation === projectGeneration) { + useVcs.setState({ error: e instanceof Error ? e.message : String(e) }); + } } finally { - useVcs.setState((st) => ({ loading: false, version: st.version + 1 })); + if (generation === projectGeneration) { + useVcs.setState((st) => ({ loading: false, version: st.version + 1 })); + } inflight = null; } })(); @@ -292,9 +301,11 @@ export function refreshPathsNow(paths: readonly string[]): Promise { }); return followUp; } + const generation = projectGeneration; const run = (async () => { try { const fresh = await call(commands.vcsStatusPaths([...paths])); + if (generation !== projectGeneration) return false; const current = useVcs.getState(); if (!current.statusLoaded || pairsRenames(current.status, paths, fresh)) return false; applyStatus(mergeStatus(current.status, paths, fresh), current.branch); @@ -306,7 +317,7 @@ export function refreshPathsNow(paths: readonly string[]): Promise { })(); const done = run.then((ok) => { inflight = null; - return ok ? undefined : refreshNow(); + return ok || generation !== projectGeneration ? undefined : refreshNow(); }); inflight = done; return done; @@ -396,10 +407,10 @@ export function statusOf(path: string): FileStatus | undefined { /** Repositories found below a project that is not itself under git (scanned in the background). */ export async function discoverRoots() { - const root = useVcs.getState().root; - if (!root || !isTauri()) return; + if (!useVcs.getState().root || !isTauri()) return; + const generation = projectGeneration; const roots = await call(commands.vcsRoots()).catch(() => []); - if (!roots.length || useVcs.getState().root !== root || useVcs.getState().available) return; + if (!roots.length || generation !== projectGeneration || useVcs.getState().available) return; useVcs.setState({ available: true }); setContext("vcsAvailable", true); void refreshNow(); @@ -412,7 +423,9 @@ export function installVcsStore(): () => void { const available = !!project?.isGit; const root = project?.root ?? null; if (useVcs.getState().root === root && useVcs.getState().available === available) return; + projectGeneration++; clearTimeout(timer); + pendingPaths.clear(); useVcs.setState({ ...initial, available, root, version: useVcs.getState().version + 1 }); setContext("vcsAvailable", available); setFileDecorations("vcs", new Map()); diff --git a/src/test/deferred.ts b/src/test/deferred.ts new file mode 100644 index 000000000..126e5197a --- /dev/null +++ b/src/test/deferred.ts @@ -0,0 +1,9 @@ +export function deferred() { + let resolve!: (value: T) => void; + let reject!: (reason: unknown) => void; + const promise = new Promise((done, fail) => { + resolve = done; + reject = fail; + }); + return { promise, resolve, reject }; +} From 2ca0e195e5c7cb51250a67c1ba6924afa1cf3ce9 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 04:33:34 +0800 Subject: [PATCH 07/12] fix(editor): keep inline find controls inside narrow panes (#4588) The inline find/replace bar used a fixed grid with a 220px minimum field, so in narrow editor panes the counter, option buttons and Close spilled outside the pane. The bar is now a container-query layout: fields shrink, the action groups wrap, and below 500px (and again below 224px) the actions and replace field move to their own rows while Show Replace and Close stay reachable. --- e2e/editor.spec.ts | 42 +++ src/editor/core/view/EditorArea.module.css | 122 +++++-- src/editor/core/view/FindBar.tsx | 349 +++++++++++---------- 3 files changed, 316 insertions(+), 197 deletions(-) diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index 1eb7ad204..6a920e902 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -232,6 +232,48 @@ test("⌘R replaces every match in the file", async ({ workbench: page }) => { await expect(editor.locator(".cm-line", { hasText: "OrderDto" })).toHaveCount(2); }); +test("the inline find and replace controls stay inside a narrow editor pane", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1120, height: 760 }); + const editor = await openFromTree(page, "build.gradle.kts"); + await editor.locator(".cm-content").click(); + await page.keyboard.press("Meta+r"); + const bar = page.getByRole("search", { name: "Replace in file" }); + const find = bar.getByRole("textbox", { name: "Find" }); + const replace = bar.getByRole("textbox", { name: "Replace" }); + const next = bar.getByRole("button", { name: /Next Occurrence/ }); + await find.fill("OrderDto"); + await find.press("Tab"); + await expect(replace).toBeFocused(); + await replace.fill("OrderView"); + const navigationIsBelowFind = async () => { + const [input, button] = await Promise.all([find.boundingBox(), next.boundingBox()]); + return !!input && !!button && button.y >= input.y + input.height; + }; + const controlsFit = () => + bar.evaluate((panel) => { + const bounds = panel.getBoundingClientRect(); + return [...panel.querySelectorAll("button, textarea")].every((element) => { + const control = element.getBoundingClientRect(); + return control.width > 0 && control.left >= bounds.left && control.right <= bounds.right; + }); + }); + await expect.poll(navigationIsBelowFind).toBe(false); + + await page.setViewportSize({ width: 590, height: 760 }); + await expect.poll(controlsFit).toBe(true); + await expect.poll(navigationIsBelowFind).toBe(true); + await page.setViewportSize({ width: 495, height: 760 }); + await expect.poll(controlsFit).toBe(true); + await expect(find).toHaveValue("OrderDto"); + await expect(replace).toHaveValue("OrderView"); + await next.click(); + await expect(bar.getByText(/^[12]\/2$/)).toBeVisible(); + await bar.getByRole("button", { name: "Replace All" }).click(); + await expect(editor.locator(".cm-line", { hasText: "OrderView" })).toHaveCount(2); + await bar.getByRole("button", { name: "Close", exact: true }).click(); + await expect(bar).toBeHidden(); +}); + test("Markdown preview highlights ⌘F matches, selected words and scales diagrams with font zoom", async ({ workbench: page, }) => { diff --git a/src/editor/core/view/EditorArea.module.css b/src/editor/core/view/EditorArea.module.css index e491b6ae3..c813c5257 100644 --- a/src/editor/core/view/EditorArea.module.css +++ b/src/editor/core/view/EditorArea.module.css @@ -151,52 +151,126 @@ } /* Find / replace bar */ -.find { +.findContainer { flex: none; - display: grid; - grid-template-columns: minmax(220px, 420px) auto 1fr; - align-items: center; - column-gap: var(--space-1-5); - row-gap: var(--space-1-5); - padding: 6px 8px 6px 10px; + min-width: 0; + container: editor-find / inline-size; background: var(--bg-editor-inline, var(--bg-elev)); border-bottom: 1px solid var(--border-editor-tabs, var(--border)); } -.findExpandable { - grid-template-columns: auto minmax(220px, 420px) auto 1fr; +.find { + display: grid; + grid-template-columns: [mode] auto [field] minmax(0, 420px) [actions] fit-content(50%) [close] minmax( + min-content, + 1fr + ); + align-items: start; + row-gap: var(--space-1); + padding: var(--space-1-5) var(--space-2); } .findExpand { - grid-column: 1; - grid-row: 1; -} -.findExpandable .findField { - grid-column: 2; + grid-area: 1 / mode; + margin-inline-end: var(--space-1); } .findField { + grid-area: 1 / field; +} +.replaceField { + grid-area: 2 / field; +} +.findField, +.replaceField { min-width: 0; } -.findButtons { +.findClose { + grid-area: 1 / close; + justify-self: end; + margin-inline-start: var(--space-1); +} +.findExpand, +.findClose { + margin-block-start: var(--space-1); +} +.findButtons, +.replaceButtons { display: flex; + flex-wrap: wrap; align-items: center; + min-width: 0; + min-height: var(--h-field); + margin-inline-start: var(--space-1-5); +} +.findButtons { + grid-area: 1 / actions; gap: var(--space-0-5); } +.replaceButtons { + grid-area: 2 / actions; + gap: var(--space-1); +} .findCount { - font-size: var(--fs-ui); + min-inline-size: 5ch; + padding-inline: var(--space-1); + font-size: var(--fs-small); + font-variant-numeric: tabular-nums; color: var(--fg-subtle); - padding: 0 8px 0 4px; - min-width: 56px; white-space: nowrap; } .findCountNone { color: var(--danger); } -.findClose { - justify-self: end; + +@container editor-find (width < 500px) { + .find { + grid-template-columns: [mode] auto [field] minmax(0, 1fr) [close] auto; + } + .findButtons, + .replaceButtons { + grid-column: field / -1; + min-height: 0; + margin-inline-start: 0; + } + .findButtons { + grid-row: 2; + } + .replaceField { + grid-row: 3; + } + .replaceButtons { + grid-row: 4; + } + .replaceButtons > button { + max-width: 100%; + height: auto; + min-height: var(--h-control); + white-space: normal; + overflow-wrap: anywhere; + } } -.replaceButtons { - display: flex; - align-items: center; - gap: var(--space-1-5); + +@container editor-find (width < 224px) { + .findField, + .replaceField, + .replaceButtons { + grid-column: mode / -1; + } + .findExpand, + .findClose { + grid-row: 2; + margin-block-start: 0; + } + .findButtons { + grid-column: field; + } + .findInput { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(20px, 1fr)); + height: auto; + padding-block: var(--space-1); + } + .findInput textarea { + grid-column: 2 / -1; + } } /* Go to line */ diff --git a/src/editor/core/view/FindBar.tsx b/src/editor/core/view/FindBar.tsx index f419e138d..1b4a89b6b 100644 --- a/src/editor/core/view/FindBar.tsx +++ b/src/editor/core/view/FindBar.tsx @@ -608,182 +608,185 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo const canReplace = !!opts.search && !invalid; return ( -
      { - focusedTarget = target; - setContext("findBarFocus", true); - setContext( - "findBarHasResults", - !!target.results && !!opts.search && (!opts.regexp || regexValid(opts.search)) && !!count?.total, - ); - }} - onBlurCapture={(e) => { - if (!panelRef.current?.contains(e.relatedTarget as Node | null)) setContext("findBarFocus", false); - }} - className={clsx(styles.find, onReplaceShown && styles.findExpandable)} - role="search" - aria-label={replace ? "Replace in file" : "Find in file"} - > - {onReplaceShown && ( - e.preventDefault()} - onClick={() => { - if (replaceBoxRef.current?.contains(document.activeElement)) inputRef.current?.focus(); - onReplaceShown(!replace); - }} +
      +
      { + focusedTarget = target; + setContext("findBarFocus", true); + setContext( + "findBarHasResults", + !!target.results && !!opts.search && (!opts.regexp || regexValid(opts.search)) && !!count?.total, + ); + }} + onBlurCapture={(e) => { + if (!panelRef.current?.contains(e.relatedTarget as Node | null)) setContext("findBarFocus", false); + }} + className={styles.find} + role="search" + aria-label={replace ? "Replace in file" : "Find in file"} + > + {onReplaceShown && ( + e.preventDefault()} + onClick={() => { + if (replaceBoxRef.current?.contains(document.activeElement)) inputRef.current?.focus(); + onReplaceShown(!replace); + }} + /> + )} +
      + setOpts({ search })} + placeholder="Find" + aria-label="Find" + invalid={invalid || none} + multiline + onHistory={() => setHistoryMenu("find")} + onKeyDown={(e) => onKeyDown(e, "find")} + className={styles.findInput} + toggles={[ + { + id: "case", + icon: "case", + title: "Match Case", + shortcut: formatBinding("Alt+C"), + pressed: opts.caseSensitive, + onToggle: () => toggle("caseSensitive"), + }, + { + id: "word", + icon: "word", + title: "Words", + shortcut: formatBinding("Alt+W"), + pressed: opts.wholeWord, + onToggle: () => toggle("wholeWord"), + }, + { + id: "regex", + icon: "regex", + title: "Regex", + shortcut: formatBinding("Alt+X"), + pressed: opts.regexp, + onToggle: () => toggle("regexp"), + }, + ]} + /> +
      +
      + + {counter} + + run(findPrevious)} + /> + run(findNext)} + /> + setFilterMenu(true)} + /> + setMoreMenu(true)} /> +
      + + {replace && ( + <> +
      + setOpts({ replace: value })} + placeholder="Replace" + aria-label="Replace" + multiline + onHistory={() => setHistoryMenu("replace")} + onKeyDown={(e) => onKeyDown(e, "replace")} + toggles={[ + { + id: "preserveCase", + icon: "preserve-case", + title: "Preserve Case", + pressed: opts.preserveCase, + onToggle: () => toggle("preserveCase"), + }, + ]} + /> +
      +
      + + + +
      + + )} + setHistoryMenu(null)} /> - )} -
      - setOpts({ search })} - placeholder="Find" - aria-label="Find" - invalid={invalid || none} - multiline - onHistory={() => setHistoryMenu("find")} - onKeyDown={(e) => onKeyDown(e, "find")} - toggles={[ - { - id: "case", - icon: "case", - title: "Match Case", - shortcut: formatBinding("Alt+C"), - pressed: opts.caseSensitive, - onToggle: () => toggle("caseSensitive"), - }, - { - id: "word", - icon: "word", - title: "Words", - shortcut: formatBinding("Alt+W"), - pressed: opts.wholeWord, - onToggle: () => toggle("wholeWord"), - }, - { - id: "regex", - icon: "regex", - title: "Regex", - shortcut: formatBinding("Alt+X"), - pressed: opts.regexp, - onToggle: () => toggle("regexp"), - }, - ]} + setMoreMenu(false)} + /> + setFilterMenu(false)} />
      -
      - - {counter} - - run(findPrevious)} - /> - run(findNext)} - /> - setFilterMenu(true)} - /> - setMoreMenu(true)} /> -
      - - {replace && ( - <> -
      - setOpts({ replace: value })} - placeholder="Replace" - aria-label="Replace" - multiline - onHistory={() => setHistoryMenu("replace")} - onKeyDown={(e) => onKeyDown(e, "replace")} - toggles={[ - { - id: "preserveCase", - icon: "preserve-case", - title: "Preserve Case", - pressed: opts.preserveCase, - onToggle: () => toggle("preserveCase"), - }, - ]} - /> -
      -
      - - - -
      - - )} - setHistoryMenu(null)} - /> - setMoreMenu(false)} - /> - setFilterMenu(false)} - />
      ); } From 1ad8b06a1a168e11c248b49ccb22a3e96ab5d7ec Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 04:35:55 +0800 Subject: [PATCH 08/12] fix(markdown): keep the Project view clickable in Preview only (#4604) In Preview only the editor panel stays mounted but hidden, with no separator. react-resizable-panels adds an implicit resize region between two enabled panels without a separator; with the hidden panel's rect at zero it spanned everything left of the preview, showing a resize cursor and swallowing clicks in the Project view. The hidden editor panel is now disabled, leaving the group a single resizable panel. Fixes #4589 --- e2e/editor.spec.ts | 12 ++++++++++++ src/features/viewers/markdown/MarkdownEditor.tsx | 5 ++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index 6a920e902..27db94514 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -638,3 +638,15 @@ test("dragging the Markdown split divider resizes and reflows editor and preview .poll(async () => Math.round((await reopenedEditor.boundingBox())!.width)) .toBe(Math.round(initialEditor)); }); + +test("Markdown Preview only leaves the Project view clickable", async ({ workbench: page }) => { + await openFromTree(page, "README.md"); + await page.getByRole("button", { name: "Preview Only" }).click(); + await expect(page.getByRole("document", { name: "Markdown preview" })).toBeVisible(); + + const row = page.getByRole("treeitem", { name: "build.gradle.kts", exact: true }); + // A hidden editor panel used to leave an implicit resize region over everything left of the preview, + // which swallowed the click. + await row.click(); + await expect(row).toHaveAttribute("aria-selected", "true"); +}); diff --git a/src/features/viewers/markdown/MarkdownEditor.tsx b/src/features/viewers/markdown/MarkdownEditor.tsx index a608b6a30..3e9b29a93 100644 --- a/src/features/viewers/markdown/MarkdownEditor.tsx +++ b/src/features/viewers/markdown/MarkdownEditor.tsx @@ -122,7 +122,10 @@ export function MarkdownEditor({ className={styles.group} storageKey={mode === "split" ? SPLIT_STORAGE_KEY : undefined} > - + {/* Hidden but mounted in Preview only (its caret drives the preview). Disabled, it leaves the group a + single resizable panel: two enabled panels without a separator get an implicit resize region between + them, which for a hidden panel spans everything left of the preview. */} +
      {children}
      From 08613ca8005e7fcd14a9d9eacc37443ed566fe22 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 20 Nov 2026 04:49:29 +0800 Subject: [PATCH 09/12] fix(debugger): keep evaluation results readable in short dialogs (#4592) The Evaluate dialog's result had a 220px minimum height, so in short windows the dialog overflowed and the result and buttons were cut off. The dialog now caps its height to the window, the expression field scrolls within half of it, imports wrap, and the result takes the remaining space; the expression uses the editor font and its label is tied to the field. --- e2e/debug.spec.ts | 57 +++++++++++ src/features/debugger/ui/Overlays.module.css | 96 ++++++++++++++----- src/features/debugger/ui/Overlays.tsx | 93 ++++++++++-------- .../debugger/ui/VariablesView.module.css | 8 ++ src/features/debugger/ui/VariablesView.tsx | 13 ++- 5 files changed, 200 insertions(+), 67 deletions(-) diff --git a/e2e/debug.spec.ts b/e2e/debug.spec.ts index 1af77663b..3f909588d 100644 --- a/e2e/debug.spec.ts +++ b/e2e/debug.spec.ts @@ -113,3 +113,60 @@ test("stops at a breakpoint, shows frames and variables, steps and resumes", asy await expect.poll(() => ipcCalls(page, "debug_resume")).toHaveLength(1); await expect(debug.getByText("CreateOrderRequest(sku='A-1', qty=2)")).toBeHidden(); }); + +test("Evaluate keeps a multiline expression and its result visible in a short dialog", async ({ workbench: page }) => { + await page.setViewportSize({ width: 580, height: 420 }); + await stubDesktop(page); + await page.evaluate(async (session) => { + const handlers = window.__ipc.handlers; + handlers.debug_capabilities = () => ({}); + handlers.debug_completions = () => []; + handlers.debug_evaluate_in = () => ({ + name: "orderSummary", + typeName: "OrderSummary", + value: "total = 36", + variablesReference: 210, + evaluateName: null, + }); + handlers.debug_variables = () => [ + { name: "tax", value: "4", typeName: "int", variablesReference: 0, evaluateName: null }, + ]; + const stateModule = "/src/features/debugger/state.ts"; + const { adoptSession } = await import(/* @vite-ignore */ stateModule); + adoptSession(session, { name: "Checkout", adapter: "debugpy", status: "paused", selectedFrame: 11 }); + }, SESSION); + + await page.keyboard.press("Alt+F8"); + const dialog = page.getByRole("dialog", { name: "Evaluate expression" }); + const field = dialog.getByRole("textbox", { name: "Expression" }); + const expression = ["orderSummary(", ...Array.from({ length: 12 }, (_, i) => ` item${i},`), ")"].join("\n"); + await field.fill(expression); + await field.press("Enter"); + const result = dialog.getByRole("tree", { name: "Evaluation result" }); + const row = result.getByRole("treeitem").first(); + await expect(row).toContainText("total = 36"); + await expect + .poll(() => + dialog.locator("[data-dialog-body]").evaluate((body) => { + const area = body.querySelector("textarea")!; + const resultRow = body.querySelector('[role="treeitem"]')!.getBoundingClientRect(); + const bounds = body.getBoundingClientRect(); + return ( + body.scrollHeight <= body.clientHeight + 1 && + area.scrollHeight > area.clientHeight && + resultRow.top >= bounds.top && + resultRow.bottom <= bounds.bottom + ); + }), + ) + .toBe(true); + await row.click(); + await row.press("ArrowRight"); + await expect(result.getByText("tax", { exact: true })).toBeVisible(); + + await field.fill("otherExpression"); + await dialog.getByRole("button", { name: "History", exact: true }).click(); + await page.getByRole("menuitem", { name: /orderSummary/ }).click(); + await expect(field).toHaveValue(expression); + await expect(field).toBeFocused(); +}); diff --git a/src/features/debugger/ui/Overlays.module.css b/src/features/debugger/ui/Overlays.module.css index 88aef79ab..cae3559e5 100644 --- a/src/features/debugger/ui/Overlays.module.css +++ b/src/features/debugger/ui/Overlays.module.css @@ -172,31 +172,72 @@ } /* evaluate dialog */ +.evalDialog { + height: min(440px, 100%); +} + .evalBody { height: 100%; - box-sizing: border-box; - padding: 12px 14px; + padding: var(--space-2) var(--space-3) 0; display: flex; flex-direction: column; - gap: 10px; + gap: var(--space-2); +} + +.evalExpression, +.evalResult { + display: flex; + flex-direction: column; + min-height: 0; + gap: var(--space-1); +} + +/* Long fragments scroll inside the field so the result keeps its own space. */ +.evalExpression { + max-height: 50%; } .evalImport { + flex: none; + max-height: 40%; + overflow: auto; + padding: var(--space-1); display: flex; flex-wrap: wrap; align-items: center; + align-content: start; gap: var(--space-1) var(--space-2); + border-bottom: 1px solid var(--border); +} + +.evalImport > button { + max-width: 100%; + height: auto; + min-height: var(--h-control); + white-space: normal; + overflow-wrap: anywhere; } -/* Grows with the dialog when it is resized. */ .evalResult { flex: 1; - min-height: 220px; +} + +.evalResultContent { + flex: 1; + min-height: 0; display: flex; flex-direction: column; border: 1px solid var(--border-popup); border-radius: var(--radius-small); - padding: 4px 6px; + padding: var(--space-0-5) var(--space-1); + overflow: hidden; +} + +.evalHint { + padding: var(--space-2); + color: var(--fg-muted); + font-size: var(--fs-small); + overflow: auto; } .chooser { @@ -259,33 +300,38 @@ /* Evaluate: a field that grows with ⇧Enter, like IDEA's expression editor. */ .evalInputRow { display: flex; - align-items: flex-start; - gap: var(--space-1); -} -.evalInput { - flex: 1; - min-width: 0; - min-height: var(--h-field, 28px); - padding: 5px 8px; - resize: none; - appearance: none; - border: 0; + min-height: 0; border-radius: var(--radius-control, 4px); background: var(--bg-field, var(--bg-button)); box-shadow: inset 0 0 0 1px var(--border-button); - color: var(--fg-strong); - font-family: var(--font-mono); - font-size: var(--fs-ui); - line-height: 18px; - outline: none; - -webkit-user-select: text; - user-select: text; } -.evalInput:focus { +.evalInputRow:focus-within { box-shadow: inset 0 0 0 1px var(--focus-ring), 0 0 0 1px var(--focus-ring); } +.evalInput { + flex: 1; + min-width: 0; + min-height: 0; + padding: var(--space-1) var(--space-2); + resize: none; + appearance: none; + border: 0; + background: none; + color: var(--fg-strong); + font-family: var(--font-mono); + font-size: var(--fs-code); + font-weight: var(--fw-code); + line-height: var(--lh-code); + outline: none; + -webkit-user-select: text; + user-select: text; +} .evalInput::placeholder { color: var(--fg-faint); } +.evalHistory { + align-self: flex-start; + margin: var(--space-1); +} diff --git a/src/features/debugger/ui/Overlays.tsx b/src/features/debugger/ui/Overlays.tsx index 8408d899a..eef942f23 100644 --- a/src/features/debugger/ui/Overlays.tsx +++ b/src/features/debugger/ui/Overlays.tsx @@ -764,8 +764,9 @@ function EvaluateDialogInner({ initial }: { initial: string }) { const [history, setHistory] = useState(() => readHistory("evaluate")); const [historyMenu, setHistoryMenu] = useState(false); const historyPos = useRef(-1); - const historyButton = useRef(null); + const historyButton = useRef(null); const field = useRef(null); + const expressionId = useId(); const session = useDebug((s) => (s.active != null ? s.sessions[s.active] : undefined)); const paused = session?.status === "paused"; const close = () => useOverlays.setState({ evaluate: null }); @@ -824,7 +825,10 @@ function EvaluateDialogInner({ initial }: { initial: string }) { onClose={close} title="Evaluate" width={620} + minWidth={340} + minHeight={240} resizable="both" + className={styles.evalDialog} aria-label="Evaluate expression" footerStart={