Compare commits

..
101 changed files with 400 additions and 1746 deletions

No files matched your search

+1 -1
View File
@@ -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**, 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.
- **Compact mode** under **UI Options**.
## Editor color scheme
+1 -1
View File
@@ -26,7 +26,7 @@ description: "选择界面主题和编辑器配色方案,导入 IntelliJ 主
- **不同的工具窗口背景**:让工具窗口与编辑器区分开。
- **背景图像**:透过项目窗口显示的图像,可设置 **不透明度**、**填充**(缩放、原始大小或平铺)和 **位置**。
- **辅助功能**:**使用对比度滚动条** 和 **针对红绿色觉缺陷调整颜色**(适用于红色盲和绿色盲)。
- **UI 选项** 下的 **紧凑模式**,也可在 **视图 › 外观** 中切换。与 IntelliJ IDEA 一致:树和列表的行更矮,主工具栏、工具窗口栏和状态栏更紧凑,工具栏和工具窗口栏图标为 16px,工具栏、状态栏、编辑器标签页和工具窗口标题的文字小 1px。
- **UI 选项** 下的 **紧凑模式**。
## 编辑器配色方案
-143
View File
@@ -427,70 +427,6 @@ test("Find Usages from the editor context menu lists every usage by file and ope
).toHaveAttribute("aria-selected", "true");
});
test("usage locations and preview stay readable as the available space changes", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1040, height: 760 });
const editor = await openSample(page);
await page.evaluate(
({ file, other }) => {
const locations = [
{ path: file, range: { start: { line: 16, col: 8 }, end: { line: 16, col: 15 } } },
{ path: file, range: { start: { line: 20, col: 27 }, end: { line: 20, col: 34 } } },
{ path: other, range: { start: { line: 0, col: 0 }, end: { line: 0, col: 7 } } },
];
window.__ipc.handlers.lsp_references = () => ({
locations,
classified: [{ location: locations[2], kind: "code", text: "service.submit(order)" }],
incomplete: null,
librariesSkipped: true,
});
},
{ file: FILE, other: `${ROOT}/domain/checkout/processing/calculations/PaymentProcessingService.kt` },
);
await caretAt(editor, page, "val order: Order", "service");
await page.keyboard.press("Meta+Alt+F7");
const popup = page.getByRole("dialog", { name: "Usages" });
const scope = popup.getByRole("button", { name: "Scope" });
const openWindow = popup.getByRole("button", { name: /^Open in Find Window/ });
await expect(popup.getByTestId("usage-row")).toHaveCount(3);
await popup.getByRole("button", { name: "Show Preview" }).click();
const code = popup.getByRole("region", { name: "Preview" });
await expect(code.locator(".cm-content")).toContainText("service.find(status");
await page.setViewportSize({ width: 480, height: 470 });
const within = async (child: Locator, parent: Locator) => {
const [c, p] = await Promise.all([child.boundingBox(), parent.boundingBox()]);
return (
!!c &&
!!p &&
c.x >= p.x - 1 &&
c.y >= p.y - 1 &&
c.x + c.width <= p.x + p.width + 1 &&
c.y + c.height <= p.y + p.height + 1
);
};
await expect.poll(() => within(scope, popup)).toBe(true);
await expect.poll(() => within(openWindow, popup)).toBe(true);
await expect.poll(() => within(code, popup)).toBe(true);
const results = popup.getByRole("listbox", { name: "Usages" });
await expect.poll(() => within(popup.getByTestId("usage-row").last(), results)).toBe(true);
const firstRow = popup.getByTestId("usage-row").first();
const file = firstRow.getByText("build.gradle.kts", { exact: true });
await expect(file).toBeVisible();
const [filename, snippet] = await Promise.all([file.boundingBox(), firstRow.locator("mark").boundingBox()]);
expect(filename!.x + filename!.width).toBeLessThan(snippet!.x);
await openWindow.click();
const tree = page.getByRole("tree", { name: "Usages" });
const target = tree.getByRole("treeitem", { name: /^17 service\.find\(status/ });
await target.click();
const preview = page.getByRole("region", { name: "Preview" });
await expect(preview).toContainText("service.find(status");
await expect.poll(async () => (await preview.boundingBox())!.y > (await tree.boundingBox())!.y).toBe(true);
await page.setViewportSize({ width: 1040, height: 760 });
await expect.poll(async () => (await preview.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true);
await expect(preview).toContainText("service.find(status");
});
test("⇧F6 renames in place and sends the server's edit to be applied", async ({ workbench: page }) => {
const editor = await openSample(page);
await page.evaluate(
@@ -562,85 +498,6 @@ test("indexed single-file rename previews all anchors and applies only after con
expect(apply.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] });
});
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);
await page.evaluate(async () => {
const path = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ path);
const { settings } = useProject.getState();
useProject.setState({ settings: { ...settings, editor: { ...settings?.editor, fontSize: 16 } } });
});
await expect(editor.locator(".cm-content")).toHaveCSS("font-size", "16px");
const replacement = "com.acme.orders." + "SharedDevelopmentOrderModel".repeat(6);
await page.evaluate(
({ file, replacement, edit }) => {
window.__ipc.handlers.lsp_code_actions = () => [
{
title: "Replace Order with the fully qualified shared development order model",
kind: "quickfix",
isPreferred: true,
disabledReason: null,
edit: { files: [{ kind: "edit", path: file, edits: [{ range: edit, new_text: replacement }] }] },
command: null,
data: null,
server: 1,
},
...Array.from({ length: 11 }, (_, i) => ({
title: `Create alternative Order model ${i + 1}`,
kind: "quickfix",
isPreferred: false,
disabledReason: null,
edit: null,
command: null,
data: null,
server: 1,
})),
];
window.__ipc.handlers.lsp_execute_code_action = () => [];
},
{ file: FILE, replacement, edit: range(20, 19, 24) },
);
await caretAt(editor, page, "val order: Order", "Order ");
await page.keyboard.press("Alt+Enter");
const popup = page.getByRole("dialog", { name: "Intentions", exact: true });
const options = popup.getByRole("listbox", { name: "Intentions" });
const preview = popup.locator('[aria-label="Preview"]');
await expect(preview.locator("pre")).toContainText(replacement);
const wide = (await options.boundingBox())!;
const widePreview = (await preview.boundingBox())!;
expect(widePreview.x).toBeGreaterThanOrEqual(wide.x + wide.width - 1);
await page.setViewportSize({ width: 1050, height: 900 });
await expect
.poll(async () => {
const list = (await options.boundingBox())!;
const code = (await preview.boundingBox())!;
return code.x + code.width - list.x;
})
.toBeLessThanOrEqual(1);
await page.setViewportSize({ width: 520, height: 540 });
await expect
.poll(async () => {
const menu = (await popup.boundingBox())!;
const list = (await options.boundingBox())!;
const code = (await preview.boundingBox())!;
return {
popupFits: menu.x >= 0 && menu.y >= 0 && menu.x + menu.width <= 521 && menu.y + menu.height <= 541,
previewBelow: code.y >= list.y + list.height - 1,
previewFits: code.x >= menu.x && code.x + code.width <= menu.x + menu.width + 1,
};
})
.toEqual({ popupFits: true, previewBelow: true, previewFits: true });
expect(await preview.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(preview.locator("pre")).toHaveCSS("font-size", "16px");
await expect(options).toBeFocused();
await page.keyboard.press("Enter");
await expect(popup).toBeHidden();
await expect.poll(() => ipcCalls(page, "lsp_execute_code_action")).toHaveLength(1);
});
test("diagnostics underline the range and ⌥⏎ applies the preferred quick fix", async ({ workbench: page }) => {
const editor = await openSample(page);
await page.evaluate(
-48
View File
@@ -1,48 +0,0 @@
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);
});
-58
View File
@@ -133,64 +133,6 @@ test("breadcrumbs follow the caret into the symbol under it", async ({ workbench
await expect(bar).toBeHidden();
});
test("narrow breadcrumb bars keep the current symbol visible and allow opening earlier crumbs", async ({
workbench: page,
}) => {
const editor = await openFromTree(page, "build.gradle.kts");
const path = page.getByRole("navigation", { name: "Breadcrumbs", exact: true });
const code = page.getByRole("navigation", { name: "Code breadcrumbs" });
await editor.locator(".cm-line", { hasText: "service.find(status" }).click();
await expect(code).toContainText("list()");
await page.evaluate(async () => {
const documentModule = "/src/editor/core/model/document.ts";
const editorModule = "/src/editor/core/controller.ts";
const projectModule = "/src/platform/project.ts";
const schemaModule = "/src/features/settings/model/schema.ts";
const [{ useOutline }, { useEditorStatus }, { useProject }, { DEFAULT_SETTINGS }] = await Promise.all([
import(/* @vite-ignore */ documentModule),
import(/* @vite-ignore */ editorModule),
import(/* @vite-ignore */ projectModule),
import(/* @vite-ignore */ schemaModule),
]);
const base = useProject.getState().settings ?? DEFAULT_SETTINGS;
useProject.setState({ settings: { ...base, editor: { ...base.editor, fontSize: 17 } } });
const activePath = useEditorStatus.getState().status.path;
let outline = useOutline.getState()[activePath];
for (const name of ["OrderProcessingStrategies", "SalesApplicationRouting", "CheckoutWorkspaceConfiguration"]) {
outline = [{ ...outline[0], name, detail: null, children: outline }];
}
useOutline.setState({ [activePath]: outline });
});
await page.setViewportSize({ width: 620, height: 620 });
const fullyInBar = (bar: typeof path, label: string) =>
bar.evaluate((nav, text) => {
const crumb = [...nav.querySelectorAll("button")].find((button) => button.textContent === text);
if (!crumb) return false;
const { left, right } = nav.getBoundingClientRect();
const rect = crumb.getBoundingClientRect();
return rect.width > 0 && rect.left >= left - 1 && rect.right <= right + 1;
}, label);
for (const bar of [path, code]) {
await expect.poll(() => fullyInBar(bar, "list()")).toBe(true);
await expect(bar.locator('[aria-current="location"]')).toHaveText("list()");
}
await expect(code.locator('[aria-current="location"]')).toHaveCSS("font-size", "17px");
await code.hover();
await page.mouse.wheel(0, -1200);
await expect.poll(() => fullyInBar(code, "CheckoutWorkspaceConfiguration")).toBe(true);
const current = path.locator('[aria-current="location"]');
await current.focus();
await current.press("Home");
const project = path.getByRole("button", { name: /acme-api/ }).first();
await expect(project).toBeFocused();
await expect.poll(() => fullyInBar(path, "acme-api")).toBe(true);
await project.press("ArrowDown");
await expect(page.getByRole("listbox", { name: "acme-api" })).toBeVisible();
});
/** What the in-memory backend has saved for `path`. */
const saved = (page: Page, path: string) =>
page.evaluate(async (path) => {
-73
View File
@@ -1,73 +0,0 @@
import type { Page } from "@playwright/test";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
async function quickDocumentation(page: Page, markdown: string) {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate((value) => {
window.__ipc.handlers.lsp_hover = () => ({ contents: { kind: "markdown", value }, range: null });
}, markdown);
const line = editor.locator(".cm-line", { hasText: "return order.toDto()" });
await line.click();
await page.keyboard.press("End");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("F1");
const popup = page.getByRole("dialog", { name: "Documentation", exact: true });
await expect(popup.locator(".cm-lsp-markdown")).toBeVisible();
return popup;
}
test("short quick documentation uses a readable width and a compact corner of actions", async ({ workbench: page }) => {
const popup = await quickDocumentation(page, "Returns the total.");
const back = popup.getByRole("button", { name: "Back", exact: true });
const dock = popup.getByRole("button", { name: "Show in Documentation Tool Window" });
await expect(dock).toBeVisible();
const bounds = (await popup.boundingBox())!;
expect(bounds.width).toBeGreaterThanOrEqual(298);
expect(bounds.width).toBeLessThan(320);
const backBounds = (await back.boundingBox())!;
const dockBounds = (await dock.boundingBox())!;
expect(backBounds.x).toBeGreaterThan(bounds.x + bounds.width / 2);
expect(bounds.x + bounds.width - dockBounds.x - dockBounds.width).toBeLessThan(16);
await expect(popup.locator(".cm-lsp-markdown")).toHaveCSS("font-size", "13px");
await page.keyboard.press("Escape");
await expect(popup).toBeHidden();
});
test("long quick documentation scrolls with its actions in view", async ({ workbench: page }) => {
const signature = "fun calculateTotal(order: Order, options: ExtendedPricingOptions): CalculationResult";
const markdown = [
`\`\`\`kotlin\n${signature}\n\`\`\``,
...Array.from({ length: 22 }, (_, i) => {
return `Section ${i + 1}. Explains the applicable pricing rules, shipping restrictions and currency options.`;
}),
"End of pricing documentation.",
].join("\n\n");
const popup = await quickDocumentation(page, markdown);
const dock = popup.getByRole("button", { name: "Show in Documentation Tool Window" });
await expect(dock).toBeVisible();
expect((await popup.boundingBox())!.width).toBeLessThan(508);
await page.setViewportSize({ width: 430, height: 500 });
await expect
.poll(async () => {
const box = (await popup.boundingBox())!;
return Math.max(-box.x, -box.y, box.x + box.width - 430, box.y + box.height - 500);
})
.toBeLessThanOrEqual(1);
const body = popup.locator(".cm-lsp-markdown").locator("..");
const last = popup.getByText("End of pricing documentation.");
const dockBefore = (await dock.boundingBox())!;
await expect(body.locator("pre")).toContainText(signature);
const scroll = await body.evaluate((node) => {
node.scrollTop = node.scrollHeight;
return { top: node.scrollTop, horizontalOverflow: node.scrollWidth - node.clientWidth };
});
expect(scroll.top).toBeGreaterThan(0);
expect(scroll.horizontalOverflow).toBeLessThanOrEqual(1);
const lastBounds = (await last.boundingBox())!;
expect(lastBounds.y + lastBounds.height).toBeLessThanOrEqual(dockBefore.y + 1);
expect(await dock.boundingBox()).toEqual(dockBefore);
await expect(dock).toBeInViewport();
});
-79
View File
@@ -1,79 +0,0 @@
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");
});
+3 -25
View File
@@ -1,8 +1,8 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openConfigurations(page: Page, target?: string) {
await page.evaluate(async (target) => {
async function openConfigurations(page: Page) {
await page.evaluate(async () => {
const path = "/src/features/run/store.ts";
const { useRun } = await import(/* @vite-ignore */ path);
const base = {
@@ -21,7 +21,6 @@ async function openConfigurations(page: Page, target?: string) {
...base,
id: "layout:app",
name: "Payments development server",
target,
beforeLaunch: [{ kind: "run", target: "layout:prepare" }],
},
{ ...base, id: "layout:prepare", name: "Prepare generated sources for the payments development server" },
@@ -30,31 +29,10 @@ async function openConfigurations(page: Page, target?: string) {
loaded: true,
editorOpen: true,
});
}, target);
});
await expect(page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true })).toBeVisible();
}
test("long run target names leave room for configuration names in the sidebar", async ({ workbench: page }) => {
const target = "payments-development-shared-staging-runner-west";
await openConfigurations(page, target);
const dialog = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true });
const tree = dialog.getByRole("tree", { name: "Run configurations", exact: true });
const row = tree.getByRole("treeitem", { name: /^Payments development server/ });
const name = row.getByText("Payments development server", { exact: true });
const badge = row.getByText(`@ ${target}`, { exact: true });
await expect(badge).toBeVisible();
for (const width of [1100, 520]) {
await page.setViewportSize({ width, height: 820 });
await expect.poll(async () => (await name.boundingBox())!.width).toBeGreaterThan(width === 1100 ? 80 : 50);
await expect.poll(() => tree.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
}
await expect(badge).toBeHidden();
await expect(row).toHaveAttribute("title", new RegExp(`Payments development server @ ${target}`));
await expect(dialog.getByRole("textbox", { name: "Name", exact: true })).toHaveValue("Payments development server");
});
test("run configuration sidebar resizes with mouse and keyboard and remembers the layout", async ({
workbench: page,
}) => {
+12 -50
View File
@@ -218,45 +218,16 @@
min-width: 0;
overflow: hidden;
}
.crumbStrip {
display: flex;
align-items: center;
min-width: 0;
overflow-x: auto;
overflow-y: hidden;
scrollbar-width: none;
}
.crumbStrip::-webkit-scrollbar {
display: none;
}
.crumbStrip:is([data-crumbs-before], [data-crumbs-after]) {
--crumb-mask: linear-gradient(
to right,
var(--crumb-start, black),
black var(--space-3),
black calc(100% - var(--space-3)),
var(--crumb-end, black)
);
-webkit-mask-image: var(--crumb-mask);
mask-image: var(--crumb-mask);
}
.crumbStrip[data-crumbs-before] {
--crumb-start: transparent;
}
.crumbStrip[data-crumbs-after] {
--crumb-end: transparent;
}
.crumbStrip .crumbButton {
.crumbButton {
flex: none;
max-width: min(240px, 100%);
margin: 0;
padding: 0 var(--space-1);
font: inherit;
color: inherit;
}
.crumbStrip .crumbButton[aria-current="location"] {
max-width: 240px;
gap: 5px;
color: var(--fg);
}
.crumbButton:last-child {
flex: 0 1 auto;
min-width: 0;
}
.crumbIcon {
flex: none;
}
@@ -269,6 +240,7 @@
.statusSep {
flex: none;
color: var(--fg-faint);
margin: 0 2px;
}
.lock {
display: inline-flex;
@@ -367,23 +339,13 @@
flex: none;
display: flex;
align-items: center;
height: max(24px, calc(1em + var(--space-2)));
padding: 0 var(--space-2);
gap: var(--space-0-5);
height: 26px;
padding: 0 8px;
overflow: hidden;
background: var(--bg-editor, var(--bg-island));
color: var(--fg-muted);
font-family: var(--font-mono);
font-size: var(--fs-code);
}
.codeCrumbs .crumbStrip {
gap: var(--space-0-5);
}
.codeCrumbs .crumbButton {
height: max(20px, calc(1em + var(--space-1)));
max-width: 100%;
}
.codeCrumbs .crumbButton[aria-current="location"] {
background: var(--bg-tree-selected-inactive);
font-size: var(--fs-small);
}
.codeCrumbsTop {
border-bottom: 1px solid var(--border-editor-tabs, var(--border));
+48 -114
View File
@@ -1,16 +1,15 @@
/** Status bar widgets of the active text editor (design footer). */
import { Fragment, useLayoutEffect, useRef, useState, type ComponentPropsWithoutRef } from "react";
import { Fragment, useRef, useState } from "react";
import clsx from "clsx";
import { useShallow } from "zustand/react/shallow";
import { executeAction } from "@/platform/actions";
import { shortcutLabel } from "@/platform/keymap";
import { basename, dirname, projectFolder, relativePath, useProject } from "@/platform/project";
import type { LineEnding, OutlineItem } from "@/platform/ipc";
import { BarButton, Icon, Menu, badgeKind, fileIconName, revealHorizontally } from "@/ui";
import { BarButton, Icon, Menu, badgeKind, fileIconName } from "@/ui";
import { notifications, useProjectViewLead } from "@/workbench/contributions";
import { useDistractionFree } from "@/workbench/distractionFree";
import { ENCODING_CHOICES, useEditorPrefs } from "@/platform/editorSettings";
import { BUNDLED_MONO_FAMILY, monoFontFamily } from "@/platform/fonts";
import {
gitRevisionOf,
isUntitledUri,
@@ -146,39 +145,15 @@ function pathCrumbs(project: { root: string; name: string } | null, path: string
return segments;
}
function updateBreadcrumbEdges(row: HTMLDivElement) {
row.toggleAttribute("data-crumbs-before", row.scrollLeft > 1);
row.toggleAttribute("data-crumbs-after", row.scrollLeft + row.clientWidth < row.scrollWidth - 1);
}
function BreadcrumbStrip({
trail,
activateOnDown = false,
children,
...props
}: ComponentPropsWithoutRef<"nav"> & { trail: string; activateOnDown?: boolean }) {
const strip = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const row = strip.current;
if (!row) return;
const revealCurrent = () => {
const focused = document.activeElement;
if (focused instanceof HTMLElement && row.contains(focused)) revealHorizontally(row, focused);
else row.scrollLeft = row.scrollWidth;
updateBreadcrumbEdges(row);
};
revealCurrent();
if (typeof ResizeObserver === "undefined") return;
const resize = new ResizeObserver(revealCurrent);
resize.observe(row);
return () => resize.disconnect();
}, [trail]);
/** A row of crumbs; a segment with `nav` opens a popup of its children. */
function CrumbNav({ segments, className, ariaLabel }: { segments: Crumb[]; className?: string; ariaLabel?: string }) {
const [popup, setPopup] = useState<{ nav: NavSegment; anchor: HTMLElement } | null>(null);
return (
<nav
{...props}
className={className}
aria-label={ariaLabel}
onKeyDown={(e) => {
if (e.altKey || e.ctrlKey || e.metaKey) return;
const buttons = [...(strip.current?.querySelectorAll("button") ?? [])];
const buttons = [...e.currentTarget.querySelectorAll<HTMLButtonElement>("button")];
const index = buttons.indexOf(e.target as HTMLButtonElement);
if (index < 0) return;
let next: number;
@@ -186,7 +161,7 @@ function BreadcrumbStrip({
else if (e.key === "ArrowRight") next = Math.min(buttons.length - 1, index + 1);
else if (e.key === "Home") next = 0;
else if (e.key === "End") next = buttons.length - 1;
else if (e.key === "ArrowDown" && activateOnDown) {
else if (e.key === "ArrowDown") {
e.preventDefault();
e.stopPropagation();
buttons[index]?.click();
@@ -197,61 +172,27 @@ function BreadcrumbStrip({
buttons[next]?.focus();
}}
>
<div
ref={strip}
className={styles.crumbStrip}
onScroll={(e) => updateBreadcrumbEdges(e.currentTarget)}
onWheel={(e) => {
if (e.shiftKey || e.ctrlKey || e.deltaX) return;
const row = e.currentTarget;
const scale = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? row.clientWidth : 1;
row.scrollLeft += e.deltaY * scale;
}}
>
{children}
</div>
</nav>
);
}
/** A row of crumbs; a segment with `nav` opens a popup of its children. */
function CrumbNav({ segments, className }: { segments: Crumb[]; className?: string }) {
const [popup, setPopup] = useState<{ nav: NavSegment; anchor: HTMLElement } | null>(null);
return (
<BreadcrumbStrip
trail={segments.map((s) => s.title).join("\n")}
activateOnDown
className={className}
aria-label={tx("Breadcrumbs")}
>
{segments.map((s, i) => {
const current = i === segments.length - 1;
const icon = s.nav?.kind === "dir" && !s.nav.root && !current ? undefined : s.icon;
return (
<Fragment key={i}>
{i > 0 && <Icon name="chevron-right" size={12} className={styles.statusSep} />}
<BarButton
className={styles.crumbButton}
tooltip={s.title}
aria-current={current ? "location" : undefined}
aria-haspopup={s.nav ? "listbox" : undefined}
onClick={(e) => {
const nav = s.nav;
const anchor = e.currentTarget;
if (nav) setPopup((p) => (p?.anchor === anchor ? null : { nav, anchor }));
else s.run?.();
}}
>
{icon && (
<Icon name={icon} size={s.nav?.kind === "dir" && s.nav.root ? 12 : 16} className={styles.crumbIcon} />
)}
<span className={styles.crumbLabel}>{s.label}</span>
</BarButton>
</Fragment>
);
})}
{segments.map((s, i) => (
<Fragment key={i}>
{i > 0 && <Icon name="chevron-right" size={12} className={styles.statusSep} />}
<BarButton
className={styles.crumbButton}
tooltip={s.title}
aria-haspopup={s.nav ? "listbox" : undefined}
onClick={(e) => {
const nav = s.nav;
const anchor = e.currentTarget;
if (nav) setPopup((p) => (p?.anchor === anchor ? null : { nav, anchor }));
else s.run?.();
}}
>
{s.icon && <Icon name={s.icon} size={16} className={styles.crumbIcon} />}
<span className={styles.crumbLabel}>{s.label}</span>
</BarButton>
</Fragment>
))}
{popup && <NavChildrenPopup segment={popup.nav} anchor={popup.anchor} onClose={() => setPopup(null)} />}
</BreadcrumbStrip>
</nav>
);
}
@@ -300,7 +241,7 @@ export function Breadcrumbs({ className, inStatusBar = false }: { className?: st
segments.push(projectCrumb(project ?? currentProject));
}
if (!segments.length) return null;
return <CrumbNav segments={segments} className={className ?? styles.status} />;
return <CrumbNav segments={segments} className={className ?? styles.status} ariaLabel={tx("Breadcrumbs")} />;
}
/** The status bar instance of the navigation bar; renders only for `statusBar`. */
@@ -321,8 +262,7 @@ export function CodeBreadcrumbs({
tabId: string;
position: "top" | "bottom";
}) {
const { breadcrumbs: prefs, fallbackFont } = useEditorPrefs();
const editorSettings = useProject((s) => s.settings?.editor);
const prefs = useEditorPrefs().breadcrumbs;
const language = useDocMeta((s) => s[path]?.language);
const outline = useOutline((s) => s[path]);
let chain = useCaretSymbols(path, outline);
@@ -338,35 +278,29 @@ export function CodeBreadcrumbs({
!chain.length
)
return null;
const family = editorSettings?.fontFamily;
const fontFamily =
(family && family !== BUNDLED_MONO_FAMILY) || fallbackFont.trim()
? monoFontFamily(family, fallbackFont, "var(--font-mono)")
: undefined;
const fontSize = editorSettings?.fontSize ?? undefined;
return (
<BreadcrumbStrip
trail={JSON.stringify([path, fontFamily, fontSize, ...chain.map((item) => item.name)])}
style={{ fontFamily, fontSize }}
<nav
className={clsx(styles.codeCrumbs, position === "top" ? styles.codeCrumbsTop : styles.codeCrumbsBottom)}
aria-label={tx("Code breadcrumbs")}
>
{chain.map((item, i) => (
<BarButton
key={i}
className={styles.crumbButton}
tooltip={item.detail ?? item.name}
aria-current={i === chain.length - 1 ? "location" : undefined}
onClick={() =>
void editorController().openFile(path, {
selection: { line: item.selection_range.start.line, col: item.selection_range.start.col },
})
}
>
<span className={styles.crumbLabel}>{item.name}</span>
</BarButton>
<Fragment key={i}>
{i > 0 && <Icon name="chevron-right" size={12} className={styles.statusSep} />}
<BarButton
className={styles.crumbButton}
tooltip={item.detail ?? item.name}
onClick={() =>
void editorController().openFile(path, {
selection: { line: item.selection_range.start.line, col: item.selection_range.start.col },
})
}
>
<Icon name={`symbol-${badgeKind(item.kind)}`} size={14} className={styles.crumbIcon} />
<span className={styles.crumbLabel}>{item.name}</span>
</BarButton>
</Fragment>
))}
</BreadcrumbStrip>
</nav>
);
}
+9 -54
View File
@@ -30,7 +30,8 @@
}
.withPreview {
flex-direction: row;
min-width: 0;
width: auto;
max-width: min(1160px, 94vw);
}
.listMain {
display: flex;
@@ -38,11 +39,6 @@
min-width: 0;
flex: none;
}
.withPreview .listMain {
flex: 1 1 320px;
min-width: 300px;
min-height: 0;
}
.mnemonic {
width: 10px;
flex: none;
@@ -52,39 +48,14 @@
text-align: right;
}
.previewPanel {
flex: 0 1 var(--list-preview-width);
min-width: 300px;
width: 420px;
flex: none;
min-height: 60px;
max-height: 300px;
max-height: 340px;
overflow: auto;
border-left: 1px solid var(--border-popup);
background: var(--bg-popup-inline, var(--bg-elev));
}
.previewLeft {
flex-direction: row-reverse;
}
.previewLeft .previewPanel {
border-left: 0;
border-right: 1px solid var(--border-popup);
}
.previewBelow {
flex-direction: column;
}
.previewBelow .listMain {
flex: 0 1 auto;
min-width: 0;
}
.previewBelow .previewPanel {
flex: 0 1 auto;
min-width: 0;
min-height: 0;
max-height: min(300px, 40vh);
border-left: 0;
border-top: 1px solid var(--border-popup);
}
.previewBelow .previewPanel[aria-busy] {
height: 60px;
}
.previewText {
padding: 8px 10px;
font-size: var(--fs-small);
@@ -95,13 +66,12 @@
padding: 6px 0;
font-family: var(--openidea-editor-font, var(--font-mono));
font-weight: var(--fw-code);
font-size: var(--openidea-editor-font-size, var(--fs-code));
font-size: var(--fs-small);
color: var(--fg-editor);
}
.diffLine {
padding: 0 10px;
white-space: pre-wrap;
overflow-wrap: anywhere;
white-space: pre;
min-height: 1.4em;
}
.diff-added {
@@ -268,10 +238,6 @@
flex-direction: column;
overflow: hidden;
}
.docPopup:not([data-resized]) {
width: max-content;
min-width: min(300px, 90vw);
}
.docScope {
display: contents;
}
@@ -280,32 +246,21 @@
}
.docPopup .docFrame {
flex: 1 1 auto;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
}
.docPopup:not([data-resized]) .docFrame {
max-width: min(500px, 90vw);
max-height: 500px;
max-width: min(600px, 90vw);
max-height: 420px;
}
.docPopup .docBody {
flex: 1 1 auto;
min-height: 0;
overflow: auto;
overscroll-behavior: contain;
padding: var(--space-2) var(--space-4) var(--space-1);
}
.docPopup .docToolbar {
position: static;
flex: none;
align-self: flex-end;
margin: 0 var(--space-2) var(--space-1);
padding: 0;
border: 0;
}
.docPopup .docToolbar .spacer {
display: none;
}
.docWindowFrame {
height: 100%;
+14 -67
View File
@@ -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, useMemo, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import {
Checkbox,
@@ -49,17 +49,11 @@ function ItemIcon({ item }: { item: ListPopupItem }) {
return <span className={styles.iconSpacer} />;
}
function ListPreviewPanel({
preview,
themeClasses,
}: {
preview: ListPreview | null | "loading";
themeClasses?: string;
}) {
function ListPreviewPanel({ preview }: { preview: ListPreview | null | "loading" }) {
if (preview === "loading") return <div className={styles.previewPanel} aria-busy="true" />;
if (!preview) return null;
return (
<div className={clsx(styles.previewPanel, themeClasses)} role="region" aria-label={tx("Preview")}>
<div className={styles.previewPanel} aria-label={tx("Preview")}>
{preview.kind === "text" ? (
<div className={styles.previewText}>{preview.text}</div>
) : (
@@ -76,9 +70,6 @@ function ListPreviewPanel({
);
}
const LIST_PREVIEW_WIDTH = 420;
const MIN_SIDE_BY_SIDE_WIDTH = 660;
function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
const [query, setQuery] = useState("");
const filtered = useMemo(() => {
@@ -100,13 +91,6 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
const [preview, setPreview] = useState<{ id: string; data: ListPreview | null } | null>(null);
const fetchPreview = popup.preview;
const [viewportWidth, setViewportWidth] = useState(() => window.innerWidth);
useEffect(() => {
if (!fetchPreview) return;
const resize = () => setViewportWidth(window.innerWidth);
window.addEventListener("resize", resize);
return () => window.removeEventListener("resize", resize);
}, [fetchPreview]);
useEffect(() => {
if (!fetchPreview || !activeItem || activeItem.disabled) return;
const ctrl = new AbortController();
@@ -180,46 +164,22 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
? ("loading" as const)
: null
: null;
const hasPreview = shownPreview !== null;
const previewBelow = hasPreview && viewportWidth <= MIN_SIDE_BY_SIDE_WIDTH;
const previewLeft =
hasPreview &&
!previewBelow &&
popup.anchor.x + width + LIST_PREVIEW_WIDTH > viewportWidth - 6 &&
popup.anchor.x >= LIST_PREVIEW_WIDTH + 6;
const anchor = useMemo(() => {
if (!fetchPreview) return popup.anchor;
const x = popup.anchor.x - (previewLeft ? LIST_PREVIEW_WIDTH : 0);
return {
getBoundingClientRect: () =>
new DOMRect(
Math.max(0, Math.min(x, window.innerWidth)),
Math.max(0, Math.min(popup.anchor.y, window.innerHeight)),
0,
0,
),
};
}, [fetchPreview, popup.anchor, previewLeft]);
const popupSize = {
width: hasPreview ? width + LIST_PREVIEW_WIDTH : width,
"--list-preview-width": `${LIST_PREVIEW_WIDTH}px`,
} as CSSProperties;
const indexOf = (item: ListPopupItem) => popup.items.indexOf(item);
return (
<Popup
open
anchor={anchor}
anchor={popup.anchor}
onClose={closePopup}
aria-label={popup.title}
className={clsx(
styles.listPopup,
hasPreview && styles.withPreview,
previewBelow && styles.previewBelow,
previewLeft && styles.previewLeft,
)}
style={popupSize}
className={clsx(styles.listPopup, popup.preview && styles.withPreview)}
style={popup.preview ? undefined : { width }}
>
<div className={styles.listMain} data-testid="list-popup" aria-busy={popup.busy || undefined}>
<div
className={styles.listMain}
style={popup.preview ? { width } : undefined}
data-testid="list-popup"
aria-busy={popup.busy || undefined}
>
<div className={styles.listHeader}>
<span className={styles.listTitle}>{popup.title}</span>
{popup.busy && <Spinner size={12} />}
@@ -300,7 +260,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
/>
</div>
</div>
{popup.preview && <ListPreviewPanel preview={shownPreview} themeClasses={popup.themeClasses} />}
{popup.preview && <ListPreviewPanel preview={shownPreview} />}
{sub?.item.submenu && (
<Popup
open
@@ -396,19 +356,6 @@ function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
const focusSeq = useLspPopup((s) => s.focusSeq);
const scope = useRef<HTMLDivElement>(null);
const opened = useRef(focusSeq);
// The captured caret can end up outside the viewport while the popup is open.
const anchor = useMemo(
() => ({
getBoundingClientRect: () =>
new DOMRect(
Math.max(0, Math.min(popup.anchor.x, window.innerWidth)),
Math.max(0, Math.min(popup.anchor.y, window.innerHeight)),
0,
0,
),
}),
[popup.anchor],
);
useEffect(() => {
if (focusSeq !== opened.current)
scope.current?.querySelector<HTMLElement>("[data-lsp-doc]")?.focus({ preventScroll: true });
@@ -417,7 +364,7 @@ function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
return (
<Popup
open
anchor={anchor}
anchor={popup.anchor}
onClose={closePopup}
aria-label="Documentation"
className={styles.docPopup}
-1
View File
@@ -552,7 +552,6 @@ export async function showIntentions(view: EditorView) {
items,
busy,
preview,
themeClasses: view.themeClasses,
onClose: () => {
dismissed = true;
},
-1
View File
@@ -104,7 +104,6 @@ export type LspPopup =
pin?: { label: string; run: () => void };
/** Side panel for the selected row, fetched lazily; `signal` aborts when the selection moves. */
preview?: (item: ListPopupItem, signal: AbortSignal) => Promise<ListPreview | null>;
themeClasses?: string;
/** Runs when the popup goes away (closed, replaced or a row ran). */
onClose?: () => void;
}
+1 -3
View File
@@ -1,7 +1,6 @@
/** 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";
@@ -42,7 +41,6 @@ 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);
@@ -218,7 +216,7 @@ function ImportSessionsDialog() {
activeIndex={lead}
onSelect={select}
isSelected={(r) => !!sel.keys?.has(r.key)}
rowHeight={rowHeight}
rowHeight={ROW}
aria-label={tx("Sessions from other apps")}
empty={
<div className={styles.empty}>
@@ -176,6 +176,7 @@ function ExecutePopup({ tool }: { tool: BuildTool }) {
}}
focusable={false}
hoverSelects={false}
rowHeight={24}
sectionHeight={28}
className={styles.completions}
aria-label="Completions"
@@ -5,27 +5,18 @@
overflow: hidden;
}
.header {
height: 26px;
flex: none;
display: flex;
align-items: center;
flex-wrap: wrap;
min-height: var(--h-field);
gap: var(--space-0-5) var(--space-2);
padding: var(--space-0-5) 10px;
gap: var(--space-2);
padding: 0 10px;
border-bottom: 1px solid var(--border-popup);
font-size: var(--fs-ui);
font-size: var(--fs-small);
color: var(--fg-muted);
}
.actions {
display: flex;
align-items: center;
flex-wrap: wrap;
min-width: 0;
gap: var(--space-0-5) var(--space-2);
font-size: var(--fs-small);
}
.scope {
max-width: min(100%, 18em);
flex: none;
}
.searching {
@@ -35,32 +26,23 @@
}
.title {
flex: 1 1 160px;
display: flex;
align-items: baseline;
gap: var(--space-1);
flex: 1;
min-width: 0;
color: var(--fg-emphasis);
}
.titleLabel {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--fg-emphasis);
}
.count {
flex: none;
white-space: nowrap;
font-size: var(--fs-small);
color: var(--fg-subtle);
}
.link {
max-width: 100%;
flex: none;
border: none;
background: none;
padding: 0;
font: inherit;
color: var(--link);
text-align: left;
cursor: pointer;
}
.link:hover {
@@ -70,6 +52,7 @@
.body {
display: flex;
flex-direction: column;
min-height: 24px;
padding: 2px 0;
box-sizing: content-box;
}
@@ -77,31 +60,21 @@
flex: 1;
}
.row {
display: grid;
grid-template-columns: min(34%, 176px) 5ch minmax(0, 1fr);
display: flex;
align-items: center;
gap: var(--space-2);
min-width: 0;
width: 100%;
}
.file {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: 0;
}
.icon {
flex: none;
color: var(--fg-muted);
}
.fileName {
overflow: hidden;
text-overflow: ellipsis;
.spacer {
flex: 1;
}
.line {
overflow: hidden;
text-align: right;
font-variant-numeric: tabular-nums;
.where {
flex: none;
font-size: var(--fs-small);
color: var(--fg-subtle);
}
@@ -122,15 +95,12 @@
outline: none;
}
.filter {
max-width: 12ch;
flex: none;
font-family: var(--font-mono);
color: var(--fg-strong);
background: var(--accent-soft);
border-radius: var(--radius-small);
padding: 0 4px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.noMatch {
color: var(--danger);
@@ -141,9 +111,8 @@
font-size: var(--fs-small);
}
.preview {
flex: 0 1 auto;
height: min(164px, 32vh);
min-height: min(64px, 18vh);
flex: none;
height: 200px;
border-top: 1px solid var(--border-popup);
overflow: hidden;
}
@@ -162,9 +131,3 @@
.previewMatch {
background: var(--bg-text-search-result);
}
@media (max-width: 600px) {
.title {
flex-basis: 100%;
}
}
+42 -52
View File
@@ -12,7 +12,6 @@ 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,
@@ -84,7 +83,6 @@ 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<Usage[]>(() => groups.flatMap((g) => g.usages), [groups]);
const [filter, setFilter] = useState("");
const accessOptions = useUsageAccessOptions();
@@ -95,7 +93,6 @@ function UsagesPopupInner() {
const [active, setActive] = useState(0);
const current = Math.min(active, items.length - 1);
const total = usageCount(groups);
const rowCount = Math.max(1, Math.min(14, items.length));
const pick = (u: Usage | undefined) => {
if (!u) return;
close();
@@ -161,48 +158,46 @@ function UsagesPopupInner() {
>
<div className={styles.header}>
<span className={styles.title}>
<span className={styles.titleLabel}>{symbol ? tx`Usages of ${symbol}` : tx("Usages")}</span>{" "}
{symbol ? tx`Usages of ${symbol}` : tx("Usages")}{" "}
<span className={styles.count}>
{filter || items.length !== total ? tx`${items.length} of ${total} found` : tx`${total} found`}
</span>
</span>
<div className={styles.actions}>
{scope && (
<Select<UsageScope>
variant="ghost"
aria-label={tx("Scope")}
className={styles.scope}
value={scope}
options={[
{ value: "project", label: tx("Project Files") },
{ value: "libraries", label: tx("Project and Libraries") },
]}
onChange={setUsagesPopupScope}
/>
)}
{loading && (
<span className={styles.searching} role="status" aria-label={tx("Searching for more usages")}>
<Spinner size={16} variant="spokes" />
</span>
)}
{filter && (
<span className={clsx(styles.filter, !items.length && styles.noMatch)} role="status">
{filter}
</span>
)}
<IconButton
icon="preview-details"
size="small"
title="Show Preview"
pressed={preview}
onMouseDown={(e) => e.preventDefault()}
onClick={() => setUsagesPopupPreview(!preview)}
{scope && (
<Select<UsageScope>
variant="ghost"
aria-label={tx("Scope")}
className={styles.scope}
value={scope}
options={[
{ value: "project", label: tx("Project Files") },
{ value: "libraries", label: tx("Project and Libraries") },
]}
onChange={setUsagesPopupScope}
/>
<button type="button" className={styles.link} onClick={openInFindWindow}>
{tx("Open in Find Window")}
{keys ? ` ${keys}` : ""}
</button>
</div>
)}
{loading && (
<span className={styles.searching} role="status" aria-label={tx("Searching for more usages")}>
<Spinner size={16} variant="spokes" />
</span>
)}
{filter && (
<span className={clsx(styles.filter, !items.length && styles.noMatch)} role="status">
{filter}
</span>
)}
<IconButton
icon="preview-details"
size="small"
title="Show Preview"
pressed={preview}
onMouseDown={(e) => e.preventDefault()}
onClick={() => setUsagesPopupPreview(!preview)}
/>
<button type="button" className={styles.link} onClick={openInFindWindow}>
{tx("Open in Find Window")}
{keys ? ` ${keys}` : ""}
</button>
</div>
<UsageAccessFilter items={all} />
{note && (
@@ -210,10 +205,7 @@ function UsagesPopupInner() {
{note}
</div>
)}
<div
className={styles.body}
style={{ height: rowCount * rowHeight, minHeight: `min(${Math.min(rowCount, 3) * rowHeight}px, 18vh)` }}
>
<div className={styles.body} style={{ height: Math.max(1, Math.min(14, items.length)) * ROW }}>
<List
items={items}
getKey={(u) =>
@@ -223,7 +215,7 @@ function UsagesPopupInner() {
onActiveChange={setActive}
focusable={false}
hoverSelects
rowHeight={rowHeight}
rowHeight={ROW}
aria-label="Usages"
onActivate={pick}
empty={
@@ -233,14 +225,12 @@ function UsagesPopupInner() {
}
renderItem={(u) => (
<div className={styles.row} data-testid="usage-row" data-path={u.path} data-line={u.line}>
<span className={styles.file}>
<Icon name={fileIconName(basename(u.path), u.path)} size={16} className={styles.icon} />
<span className={styles.fileName} title={u.path}>
{basename(u.path)}
</span>
</span>
<span className={styles.line}>{u.line + 1}</span>
<Icon name={fileIconName(basename(u.path), u.path)} size={16} className={styles.icon} />
<UsagePreview usage={u} />
<span className={styles.spacer} />
<span className={styles.where}>
{basename(u.path)}:{u.line + 1}
</span>
</div>
)}
/>
@@ -25,15 +25,15 @@
background: var(--border);
}
.summary {
min-height: 26px;
height: 26px;
flex: none;
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-0-5) var(--space-1-5);
padding: var(--space-0-5) 10px;
gap: var(--space-1-5);
padding: 0 10px;
font-size: var(--fs-ui);
color: var(--fg-subtle);
white-space: nowrap;
}
.groupLabel {
color: var(--fg);
@@ -42,13 +42,12 @@
color: var(--danger);
}
.link {
max-width: 100%;
flex: none;
border: none;
background: none;
padding: 0;
font: inherit;
color: var(--link);
text-align: left;
cursor: pointer;
}
.link:hover {
@@ -82,18 +81,9 @@
flex: none;
}
.file {
flex: none;
max-width: 56%;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg);
}
.directory {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
}
.muted,
.count {
flex: none;
color: var(--fg-subtle);
@@ -111,7 +101,7 @@
overflow: hidden;
text-overflow: ellipsis;
font-family: var(--font-mono);
font-size: var(--fs-code);
font-size: var(--fs-ui);
color: var(--fg);
}
.match {
@@ -145,18 +135,3 @@
flex: 1;
min-height: 0;
}
.splitFrame {
display: flex;
min-width: 0;
}
.sourcePreview {
display: flex;
flex-direction: column;
font-family: var(--font-mono);
font-size: var(--fs-code);
line-height: 1.45;
}
.sourcePreview .sourceText[role="region"] {
font: inherit;
font-weight: var(--fw-code);
}
+19 -53
View File
@@ -2,13 +2,11 @@
* "usages" tool window: Find Usages results grouped by file with line
* previews, one tab per search (pinnable, as the Find tool window's tabs).
*/
import { useCallback, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { useCallback, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import clsx from "clsx";
import { create } from "zustand";
import { previewColors, tokenSpans, useLineTokens } from "@/editor/lineTokens";
import { formatMessage, useTx } from "@/platform/i18n";
import { useEditorPrefs } from "@/platform/editorSettings";
import { BUNDLED_MONO_FAMILY, monoFontFamily } from "@/platform/fonts";
import { shortcutLabel } from "@/platform/keymap";
import { basename, relativeDir, useProject } from "@/platform/project";
import { maybeEditorService, useOccurrenceNavigator } from "@/workbench/contributions";
@@ -247,12 +245,8 @@ export function UsagesView() {
return (
<span className={clsx(styles.row, isExcluded(n) && styles.excluded)}>
<Icon name={fileIconName(basename(path), path)} size={16} className={styles.icon} />
<span className={styles.file} title={path}>
{basename(path)}
</span>
<span className={styles.directory} title={path}>
{relativeDir(root, path)}
</span>
<span className={styles.file}>{basename(path)}</span>
<span className={styles.muted}>{relativeDir(root, path)}</span>
<span className={styles.count}>
{n.group.usages.length} {tx(n.group.usages.length === 1 ? "usage" : "usages")}
</span>
@@ -407,62 +401,34 @@ export function useUsagesHeaderMenu(): MenuItem[] {
function UsagesSplit({ preview, children }: { preview: ReactNode; children: ReactNode }) {
const show = useUsagesOptions((s) => s.preview);
const frame = useRef<HTMLDivElement>(null);
const [stacked, setStacked] = useState(false);
useLayoutEffect(() => {
const el = frame.current;
if (!show || !el) return;
const measure = () => setStacked(el.clientWidth < 580);
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(el);
return () => observer.disconnect();
}, [show]);
if (!show) return children;
return (
<div ref={frame} className={styles.splitFrame}>
<SplitGroup
orientation={stacked ? "vertical" : "horizontal"}
id="usages-preview-split"
storageKey={stacked ? "openidea.usages.previewSplit.vertical" : "openidea.usages.previewSplit"}
>
<SplitPanel id="usages" minSize={stacked ? "30%" : 160} className={styles.panel}>
{children}
</SplitPanel>
<SplitHandle />
<SplitPanel id="preview" minSize={stacked ? "30%" : 160} defaultSize="45%" className={styles.panel}>
{preview}
</SplitPanel>
</SplitGroup>
</div>
<SplitGroup orientation="horizontal" id="usages-preview-split" storageKey="openidea.usages.previewSplit">
<SplitPanel id="usages" minSize={160} className={styles.panel}>
{children}
</SplitPanel>
<SplitHandle />
<SplitPanel id="preview" minSize={160} defaultSize="45%" className={styles.panel}>
{preview}
</SplitPanel>
</SplitGroup>
);
}
function UsagesPreview({ node }: { node: Node | null }) {
const usage = node?.kind === "usage" ? node.usage : node?.kind === "file" ? (node.group.usages[0] ?? null) : null;
const search = useUsages(activeUsageSearch);
const settings = useProject((s) => s.settings?.editor);
const { fallbackFont } = useEditorPrefs();
const family = settings?.fontFamily;
const fontFamily =
(family && family !== BUNDLED_MONO_FAMILY) || fallbackFont.trim()
? monoFontFamily(family, fallbackFont, "var(--font-mono)")
: undefined;
const highlights = useMemo(() => {
const group = usage && search?.groups.find((g) => g.path === usage.path);
return (group?.usages ?? []).map((u) => ({ line: u.line, ranges: [[u.col, u.endCol] as const] }));
}, [usage, search?.groups]);
return (
<div className={styles.sourcePreview} style={{ fontFamily, fontSize: settings?.fontSize ?? undefined }}>
<SourcePreview
path={usage?.path ?? null}
line={usage?.line ?? 0}
highlights={highlights}
load={previewText}
colorize={previewColors}
className={styles.sourceText}
/>
</div>
<SourcePreview
path={usage?.path ?? null}
line={usage?.line ?? 0}
highlights={highlights}
load={previewText}
colorize={previewColors}
/>
);
}
+1 -3
View File
@@ -7,7 +7,6 @@ import { Icon, Input, List, Popup, listNavigate } from "@/ui";
import { tx } from "@/platform/i18n";
import type { GridColumn } from "./Grid";
import styles from "./Database.module.css";
import { useRowHeight } from "@/ui/density";
export function filterColumns(columns: readonly GridColumn[], query: string): number[] {
const q = query.trim().toLowerCase();
@@ -25,7 +24,6 @@ export function ColumnsPopup(props: {
onPick: (col: number) => void;
onClose: () => void;
}) {
const rowHeight = useRowHeight(22);
const [query, setQuery] = useState("");
const [active, setActive] = useState(0);
const shown = filterColumns(props.columns, query);
@@ -74,7 +72,7 @@ export function ColumnsPopup(props: {
onActivate={(_, i) => pick(i)}
focusable={false}
hoverSelects
rowHeight={rowHeight}
rowHeight={22}
aria-label={tx("Columns")}
className={styles.columnsList}
empty={<span>{tx("No matching columns")}</span>}
-28
View File
@@ -154,28 +154,6 @@
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);
@@ -679,12 +657,6 @@
}
/* 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);
-1
View File
@@ -30,7 +30,6 @@ vi.mock("@tanstack/react-virtual", () => ({
getTotalSize: () => count * 24,
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 24, key: index })),
scrollToIndex: () => {},
measure: () => {},
}),
}));
+1 -39
View File
@@ -16,8 +16,6 @@ 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";
@@ -37,7 +35,7 @@ import {
resolveTarget,
type EditBlockReason,
} from "./resultEditing";
import { formatElapsed, pageWindow } from "./resultView";
import { pageWindow } from "./resultView";
import { resultTabMenu } from "./resultTabActions";
import { analyze } from "./sql/analyze";
import { nameMatcher } from "./sql/dialect";
@@ -57,7 +55,6 @@ import {
rerunResult,
useDatabase,
withConnection,
type ConsoleExecution,
type OutputLine,
type ResultTab,
} from "./store";
@@ -747,40 +744,8 @@ 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 (
<div className={styles.executing} role="status">
<Spinner size={12} label={tx("Executing")} />
<span className={styles.executingText} title={path}>
{count > 1 ? tx`Executing ${count} statements in ${name}…` : tx`Executing in ${name}…`}
</span>
<span className={styles.executingTime}>{formatElapsed(Math.max(0, now - execution.startedAt))}</span>
</div>
);
}
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<HTMLDivElement>(null);
@@ -807,8 +772,6 @@ export function ResultsView() {
owner: e.currentTarget,
});
};
const executing = execution && <ExecutingBar path={execution[0]} execution={execution[1]} />;
if (!results.length && !hasOutput && executing) return <div className={styles.view}>{executing}</div>;
if (!results.length && !hasOutput)
return (
<EmptyState title="No results">
@@ -862,7 +825,6 @@ export function ResultsView() {
]}
/>
</ToolWindowContentTabs>
{executing}
<div
ref={panel}
className={styles.fill}
+12 -126
View File
@@ -23,7 +23,6 @@ import {
Facet,
Prec,
RangeSet,
type Range,
StateEffect,
StateField,
type Extension,
@@ -43,15 +42,8 @@ import {
import { useEffect, useMemo, useRef, useState, type PointerEvent } from "react";
import { createRoot } from "react-dom/client";
import type { EditorDocContext } from "@/editor/api";
import { iconNode, spinnerNode } from "@/ui/iconNode";
import {
call,
commands,
type DbDriver,
type DbSessionContext,
type DbStatementOutcome,
type SqlStatement,
} from "@/platform/ipc";
import { iconNode } from "@/ui/iconNode";
import { call, commands, type DbDriver, type DbSessionContext, type DbStatementOutcome } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { Icon, IconButton, Select, Toolbar, lazyComponent } from "@/ui";
import { useProject } from "@/platform/project";
@@ -101,7 +93,6 @@ import type { ResultTab } from "./store";
/** `templates` feature's language-data key for finer template contexts. */
const TEMPLATE_CONTEXT_KEY = "openideaTemplateContexts";
import { formatElapsed } from "./resultView";
import { SQL_LANGUAGE } from "./sqlLanguage";
export { SQL_LANGUAGE };
const ROW_LIMITS = ["100", "500", "1000", "5000", "50000"];
@@ -116,40 +107,19 @@ interface RunMark {
ms: number | null;
}
/** The statements a running request submitted (a batch: all of them, in order). */
interface Executing {
/** Tells this run from a later one on the same console. */
token: number;
/** The statements' offsets in the text sent. */
sent: readonly { from: number; to: number }[];
/** Where they are now. */
spans: readonly { from: number; to: number }[];
/** Where the elapsed time shows: after the last statement's `;`. */
at: number;
startedAt: number;
}
interface RunState {
marks: readonly RunMark[];
/** Message of the bottom error banner (`null`: hidden). */
banner: string | null;
executing: Executing | null;
}
const setRun = StateEffect.define<RunState>();
const runField = StateField.define<RunState>({
create: () => ({ marks: [], banner: null, executing: null }),
create: () => ({ marks: [], banner: 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) {
@@ -165,18 +135,12 @@ const runField = StateField.define<RunState>({
timingAt: tr.changes.mapPos(m.timingAt),
});
}
return { ...value, marks, executing };
return { ...value, marks };
},
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),
@@ -200,47 +164,11 @@ class TimingWidget extends WidgetType {
toDOM() {
const span = document.createElement("span");
span.className = "cm-openidea-db-timing";
span.textContent = formatElapsed(this.ms);
span.textContent = this.ms < 1000 ? `${Math.round(this.ms)} ms` : `${(this.ms / 1000).toFixed(1)} s`;
return span;
}
}
/** The running time of the request, ticking until it ends. */
class ElapsedWidget extends WidgetType {
private timer: ReturnType<typeof setInterval> | 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();
@@ -264,12 +192,9 @@ const runGutter = gutter({
markers: (view) => {
const st = view.state.field(runField);
const doc = view.state.doc;
const ex = st.executing;
const ranges: Range<GutterMarker>[] = st.marks
.filter((m) => m.from <= doc.length && !ex?.spans.some((r) => r.from <= m.to && m.from <= r.to))
const ranges = st.marks
.filter((m) => m.from <= doc.length)
.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);
},
});
@@ -308,59 +233,20 @@ 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({ ...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 }) });
}
view.dispatch({ effects: setRun.of({ marks, banner: failed ? `[${name}] ${failed.error}` : 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;
await executeRange(view, path, sel.from, sel.to);
const outcomes = await executeConsole(path, view.state.doc.toString(), sel.from, sel.to);
if (outcomes.length) markOutcomes(view, outcomes);
}
/** Runs every statement of `view`, in order (stops at the first that fails). */
export async function executeScriptInView(view: EditorView, path: string) {
await executeRange(view, path, 0, view.state.doc.length);
const outcomes = await executeConsole(path, view.state.doc.toString(), 0, view.state.doc.length);
if (outcomes.length) markOutcomes(view, outcomes);
}
/** Explain Plan of the statement at the caret (or the first selected one) of `view`. */
+1 -59
View File
@@ -3,10 +3,9 @@ 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, executeScriptInView } from "./console";
import { consoleExtension } 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() }));
@@ -31,7 +30,6 @@ 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,
@@ -136,59 +134,3 @@ 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<void>((resolve) => {
finish = resolve;
});
const execute = backend.execute.getMockImplementation()!;
backend.execute.mockImplementationOnce(async (...args: unknown[]) => {
await gate;
return execute(...(args as Parameters<typeof execute>));
});
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<void>;
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();
});
});
-1
View File
@@ -157,7 +157,6 @@ export function activate(): () => void {
manualCommit: new Set(),
pendingTx: new Set(),
running: {},
executions: {},
dialog: null,
newMenuOpen: false,
});
@@ -67,7 +67,6 @@ import {
useDatabase,
withConnection,
} from "./store";
import { provideToolWindowService } from "@/workbench/contributions";
const initial = useDatabase.getState();
const initialProject = useProject.getState();
@@ -130,8 +129,6 @@ 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];
+1 -6
View File
@@ -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, the series of the chart, and how long a statement took.
* Aggregates of a selection, and the series of the chart.
*/
import type { Cell } from "./model";
@@ -462,8 +462,3 @@ 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`;
}
@@ -9,7 +9,6 @@ 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,
@@ -96,7 +95,6 @@ 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 }] }),
@@ -811,64 +809,3 @@ 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<void>((resolve) => {
finish = resolve;
});
const execute = backend.execute.getMockImplementation()!;
backend.execute.mockImplementationOnce(async (...args: unknown[]) => {
await gate;
return execute(...(args as Parameters<typeof execute>));
});
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(<ResultsView />));
let pending!: Promise<unknown>;
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(<ResultsView />));
let pending!: Promise<unknown>;
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();
});
});
+2 -21
View File
@@ -174,12 +174,6 @@ export interface SourceCatalog {
databases: Record<string, DbCatalogSchema[]>;
}
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;
@@ -211,8 +205,6 @@ interface DatabaseState {
output: OutputLine[];
/** Console path → running request. */
running: Record<string, RequestId>;
/** Console path → what its running request submitted, and since when (ms since the epoch). */
executions: Record<string, ConsoleExecution>;
maxRows: number;
dialog: DialogState | null;
/** Target of the tree's lead node. */
@@ -279,7 +271,6 @@ export const useDatabase = create<DatabaseState>(() => ({
activeResult: null,
output: [],
running: {},
executions: {},
maxRows: 500,
dialog: null,
selectedSource: null,
@@ -1242,8 +1233,6 @@ 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<DbStatementOutcome[]> {
const id = consoleSource(path);
if (!id) {
@@ -1263,14 +1252,8 @@ 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 },
executions: { ...s.executions, [path]: { startedAt: Date.now(), statements: statements.length } },
}));
onStart?.(statements);
useDatabase.setState((s) => ({ running: { ...s.running, [path]: request } }));
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 [];
@@ -1313,9 +1296,7 @@ export async function executeConsole(
if (s.running[path] !== request) return s;
const running = { ...s.running };
delete running[path];
const executions = { ...s.executions };
delete executions[path];
return { running, executions };
return { running };
});
}
}
+1 -3
View File
@@ -14,7 +14,6 @@ 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 },
@@ -67,7 +66,6 @@ export function HeapClasses({
selected: number | null;
onSelect: (row: HeapClassRow | null) => void;
}) {
const rowHeight = useRowHeight(22);
const tx = useTx();
const [query, setQuery] = useState<ClassQuery>(DEFAULT_CLASS_QUERY);
const compared = changes !== null;
@@ -126,7 +124,7 @@ export function HeapClasses({
renderItem={(r) => <ClassRow row={r} changes={changes} />}
activeIndex={selected === null ? -1 : rows.findIndex((r) => r.classIndex === selected)}
onActiveChange={(i) => onSelect(rows[i] ?? null)}
rowHeight={rowHeight}
rowHeight={22}
tableBody={{ headerRows: 1 }}
empty={<span className={styles.note}>{tx("No matches")}</span>}
/>
@@ -6,7 +6,6 @@ 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;
@@ -22,7 +21,6 @@ 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)),
@@ -72,7 +70,7 @@ export function BiggestObjects({
)}
activeIndex={selected === null ? -1 : rows.findIndex((o) => o.object === selected)}
onActiveChange={(i) => rows[i] && onSelect(rows[i])}
rowHeight={rowHeight}
rowHeight={22}
tableBody={{ headerRows: 1 }}
/>
</div>
+1 -3
View File
@@ -24,7 +24,6 @@ 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 },
@@ -106,7 +105,6 @@ 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;
@@ -250,7 +248,7 @@ export function MemoryView({ session }: { session: DebugSession }) {
onActivate={(r, _i, e) => {
if (e.type === "keydown" && listsInstances && paused) showInstancesOf(r.name);
}}
rowHeight={rowHeight}
rowHeight={22}
tableBody={{ headerRows: 1 }}
empty={<span className={styles.note}>{tx("No matches")}</span>}
/>
@@ -18,7 +18,6 @@ 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 };
@@ -33,7 +32,6 @@ 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<GhAccountRepos | null>(null);
const [query, setQuery] = useState("");
const [attempt, setAttempt] = useState(0);
@@ -142,7 +140,7 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource
activeIndex={active}
onActiveChange={pick}
focusable={false}
rowHeight={rowHeight}
rowHeight={26}
empty={
<span className={styles.muted}>
<T>{state.repos.length ? "No matching repositories" : "No repositories"}</T>
+1 -3
View File
@@ -16,7 +16,6 @@ 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 <div className={error ? `${styles.centered} ${styles.errorText}` : styles.centered}>{children}</div>;
@@ -171,7 +170,6 @@ 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]);
@@ -221,7 +219,7 @@ function ChangesTree() {
selected={selection}
onSelectionChange={setSelection}
multiSelect
rowHeight={rowHeight}
rowHeight={22}
aria-label="Changes"
speedSearch
onActivate={(n) => n.file && showDiff(ordered, n.file)}
@@ -178,6 +178,7 @@ function HeadPopup(props: { anchor: HTMLElement; initialRepo: GHRemote; onClose:
onActivate={(r) => choose(r)}
focusable={false}
hoverSelects
rowHeight={24}
className={styles.headList}
aria-label="Branches"
empty={<div className={styles.hint}>{tx("Nothing to show")}</div>}
@@ -78,6 +78,7 @@ export function BranchWidget({
getKey={(a) => a}
onActivate={(a) => run(a)}
hoverSelects
rowHeight={24}
aria-label={tx("Branches")}
renderItem={(a, state) => (
<div className={styles.popupRow} data-active={state.active || undefined}>
+1
View File
@@ -86,6 +86,7 @@ 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={
+1
View File
@@ -79,6 +79,7 @@ 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={
@@ -1,67 +1,61 @@
.popup {
display: flex;
flex-direction: column;
width: min(670px, calc(100vw - 32px));
width: 620px;
max-width: 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);
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));
height: var(--h-row);
padding: 4px 10px 0;
font-size: var(--fs-small);
color: var(--fg-subtle);
}
.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-size: var(--fs-small);
font: inherit;
cursor: pointer;
}
.link:hover {
color: var(--link-hover);
}
.query {
.inputRow {
display: flex;
align-items: center;
gap: var(--space-1-5);
padding: 6px 10px;
border-bottom: 1px solid var(--border-popup);
}
.inputIcon {
flex: none;
padding: var(--space-2);
color: var(--fg-subtle);
}
.input {
flex: 1;
font-family: var(--font-ui);
}
.rows {
flex: 1 1 auto;
min-height: var(--h-row);
max-height: 600px;
overflow-x: hidden;
max-height: 360px;
height: auto;
}
.section {
display: flex;
align-items: center;
width: 100%;
gap: var(--space-3);
gap: 10px;
padding: 0;
font-size: var(--fs-small);
color: var(--fg-subtle);
@@ -99,35 +93,23 @@
.detail {
flex: 0 1 auto;
min-width: 0;
max-width: min(36%, 26ch);
max-width: 45%;
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: var(--space-1) var(--space-3) var(--space-2);
padding: 6px 10px;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.footer {
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);
padding: 6px 10px;
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);
}
+47 -85
View File
@@ -4,15 +4,14 @@
* 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 { useId, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { useMemo, 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, Kbd, List, Popup, SearchField, T, firstSelectable, listNavigate } from "@/ui";
import { Icon, Input, List, Popup, T, 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";
@@ -45,13 +44,8 @@ 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<HTMLInputElement>(null);
const rowHeight = useRowHeight(ROW_HEIGHT);
const listId = useId();
const [line, setLine] = useState("");
const [active, setActive] = useState(-1);
const [history, setHistory] = useState(() => readHistory(root));
@@ -63,10 +57,6 @@ 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;
@@ -85,25 +75,21 @@ function RunAnythingPopup({ root }: { root: string }) {
setActive(-1);
};
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.nativeEvent.isComposing || e.altKey || e.ctrlKey || e.metaKey) return;
const onKeyDown = (e: KeyboardEvent) => {
if (["ArrowDown", "ArrowUp", "PageDown", "PageUp"].includes(e.key)) {
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) {
const next = listNavigate(e.key, { items: rows, active: Math.max(active, 0), wrap: true, isSection });
if (next !== null) {
e.preventDefault();
setActive(next < 0 ? first : next);
setActive(active < 0 && e.key === "ArrowDown" ? rows.findIndex((r) => !isSection(r)) : next);
}
return;
}
if (e.key === "Tab" && !e.shiftKey && hasRows) {
if (e.key === "Tab") {
e.preventDefault();
e.stopPropagation();
complete(selected ?? rows[first]);
complete(rows[active >= 0 ? active : rows.findIndex((r) => !isSection(r))]);
} else if (e.key === "Enter") {
e.preventDefault();
if (selected) run(selected);
if (active >= 0) run(rows[active]);
else runLine();
}
};
@@ -111,7 +97,7 @@ function RunAnythingPopup({ root }: { root: string }) {
return (
<Popup
open
anchor={commandAnchor}
anchor={{ x: window.innerWidth / 2, y: 72 }}
placement="bottom"
onClose={close}
role="dialog"
@@ -131,83 +117,59 @@ function RunAnythingPopup({ root }: { root: string }) {
onClick={() => {
clearHistory(root);
setHistory([]);
setActive(-1);
field.current?.focus();
}}
>
<T>Clear History</T>
</button>
)}
</div>
<div className={styles.query}>
<SearchField
ref={field}
<div className={styles.inputRow}>
<Icon name="run-anything" size={16} className={styles.inputIcon} />
<Input
data-autofocus
leadingIcon="run-anything"
clearable={false}
role="combobox"
aria-autocomplete="list"
aria-expanded={hasRows}
aria-controls={hasRows ? listId : undefined}
aria-activedescendant={selected?.kind === "item" ? `${listId}-${active}` : undefined}
value={command}
variant="bare"
className={styles.input}
value={line}
placeholder="Run a command, configuration or goal"
aria-label="Command line"
onChange={(value) => {
setLine(value);
onChange={(e) => {
setLine(e.target.value);
setActive(-1);
}}
onKeyDown={onKeyDown}
/>
</div>
{hasRows ? (
<>
<List
id={listId}
items={rows}
getKey={(r) => r.key}
isSection={isSection}
renderSection={(r) => <div className={styles.section}>{r.kind === "section" && <T>{r.label}</T>}</div>}
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" ? (
<div className={clsx(styles.row, state.active && styles.activeRow)}>
<Icon name={r.item.icon ?? "run"} size={16} className={styles.rowIcon} />
<span className={styles.label} title={r.item.label}>
{r.item.label}
</span>
{r.item.detail && (
<span className={styles.detail} title={r.item.detail}>
{r.item.detail}
</span>
)}
</div>
) : null
}
/>
<div className={styles.footer}>
<span className={styles.navigationHint}>
<Kbd>↑</Kbd>
<Kbd>↓</Kbd>
<T>Navigate</T>
</span>
<T>Tab to complete, Enter to run</T>
</div>
</>
) : (
line.trim() && (
<List
items={rows}
getKey={(r) => r.key}
isSection={isSection}
renderSection={(r) => <div className={styles.section}>{r.kind === "section" && <T>{r.label}</T>}</div>}
activeIndex={active}
onActiveChange={setActive}
onActivate={(r) => run(r)}
focusable={false}
hoverSelects={false}
rowHeight={24}
className={styles.rows}
aria-label="Run Anything entries"
empty={
<div className={styles.empty}>
<T>Press Enter to run the command in the project directory</T>
{line.trim() ? <T>Press Enter to run the command in the project directory</T> : <T>Type a command</T>}
</div>
)
)}
}
renderItem={(r, state) =>
r.kind === "item" ? (
<div className={clsx(styles.row, state.active && styles.activeRow)}>
<Icon name={r.item.icon ?? "run"} size={16} className={styles.rowIcon} />
<span className={styles.label}>{r.item.label}</span>
{r.item.detail && <span className={styles.detail}>{r.item.detail}</span>}
</div>
) : null
}
/>
<div className={styles.footer}>
<T>Enter to run, Tab to complete. Other commands run in the project directory.</T>
</div>
</div>
</Popup>
);
+2 -4
View File
@@ -1,7 +1,6 @@
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";
@@ -60,7 +59,6 @@ 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";
@@ -117,7 +115,7 @@ export function AddConfigPopup({
variant="bare"
/>
</div>
<div style={{ height: Math.max(rowHeight, Math.min(rows.length * rowHeight, 14 * rowHeight)) }}>
<div style={{ height: Math.max(ROW, Math.min(rows.length * ROW, 14 * ROW)) }}>
<List<TypeRow>
aria-label="Configuration types"
className={styles.chooserList}
@@ -129,7 +127,7 @@ export function AddConfigPopup({
onActiveChange={setActive}
focusable={false}
hoverSelects
rowHeight={rowHeight}
rowHeight={ROW}
onActivate={(r) => pick(r)}
empty={
<span className={styles.chooserMuted}>
+4 -6
View File
@@ -16,7 +16,6 @@ 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";
@@ -100,7 +99,7 @@ export function buildRows(
return rows;
}
const heightOf = (r: Row, rowHeight: number) => (r.type === "section" && !r.label ? SEPARATOR : rowHeight);
const rowHeight = (r: Row) => (r.type === "section" && !r.label ? SEPARATOR : ROW);
let closedAt = 0;
/** The chooser closed within the last moment (a click on its own anchor shouldn't reopen it). */
@@ -146,7 +145,6 @@ export function mnemonics(rows: readonly Row[]): Map<string, number> {
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);
@@ -287,8 +285,8 @@ function ConfigChooser() {
};
const height = Math.min(
rows.reduce((sum, r) => sum + heightOf(r, rowHeight), 0),
14 * rowHeight,
rows.reduce((sum, r) => sum + rowHeight(r), 0),
14 * ROW,
);
// IDEA: a configuration's submenu lists its executors, then Edit and Pin.
@@ -368,7 +366,7 @@ function ConfigChooser() {
onActiveChange={setActive}
focusable={false}
hoverSelects
rowHeight={rowHeight}
rowHeight={ROW}
onActivate={(r) => activate(r)}
renderItem={(r, { active: isActive }) => {
if (r.type === "save") {
+5 -10
View File
@@ -511,7 +511,6 @@ function EditConfigsDialog() {
aria-expanded={!collapsed.has(r.key)}
className={styles.editItem}
style={{ paddingLeft: 6 }}
title={tx(r.label)}
onClick={() => toggle(r.key)}
onDragOver={(e) => e.preventDefault()}
onDrop={(e) => onDrop(e, r.kind, null)}
@@ -535,7 +534,6 @@ function EditConfigsDialog() {
aria-expanded={!collapsed.has(r.key)}
className={clsx(styles.editItem, sel && styles.editItemSelected)}
style={{ paddingLeft: 22 }}
title={r.name}
onClick={() => setSelection({ type: "folder", kind: r.kind, name: r.name })}
onDoubleClick={() => toggle(r.key)}
onDragOver={(e) => e.preventDefault()}
@@ -549,9 +547,6 @@ function EditConfigsDialog() {
}
const c = r.config;
const isTomcat = c.kind === "tomcat";
const name = c.name || tx("Unnamed");
const target = c.target ? targetName(c, runTargets) : null;
const scope = !c.detected && !isTomcat ? (c.local ? "local" : "user") : null;
const tomcatNoArtifact =
isTomcat &&
((c.params?.deployment ?? "artifact") === "artifact"
@@ -566,9 +561,7 @@ function EditConfigsDialog() {
className={clsx(styles.editItem, current?.id === c.id && styles.editItemSelected)}
style={{ paddingLeft: r.depth === 2 ? 50 : 34 }}
onClick={() => setSelection({ type: "config", id: c.id })}
title={[name + (target ? ` @ ${target}` : "") + (scope ? ` (${scope})` : ""), commandLine(c)]
.filter(Boolean)
.join("\n")}
title={commandLine(c)}
draggable
onDragStart={(e) => {
dragged.current = c.id;
@@ -586,9 +579,11 @@ function EditConfigsDialog() {
)}
</span>
<span className={styles.chooserName}>{c.name || <T>Unnamed</T>}</span>
{target && <span className={clsx(styles.chooserMuted, styles.editTarget)}>@ {target}</span>}
{c.target && <span className={styles.chooserMuted}>@ {targetName(c, runTargets)}</span>}
{errorsById[c.id] && <Icon name="error" size={12} className={styles.failed} label="Invalid" />}
{scope && <span className={styles.chooserMuted}>{scope}</span>}
{!c.detected && !isTomcat && (
<span className={styles.chooserMuted}>{c.local ? "local" : "user"}</span>
)}
</button>
);
})}
+5 -23
View File
@@ -338,17 +338,17 @@
align-items: center;
gap: var(--space-1);
max-width: 260px;
height: var(--h-toolbar-widget);
border-radius: var(--radius-toolbar-dropdown);
height: 30px;
border-radius: 6px;
}
.widgetDevice {
composes: widgetChooser;
max-width: 180px;
}
.widgetButton {
width: var(--titlebar-tool-button);
height: var(--titlebar-tool-button);
border-radius: var(--radius-toolbar-button);
width: 30px;
height: 30px;
border-radius: 6px;
}
.widgetLoading {
display: inline-flex;
@@ -553,7 +553,6 @@
flex: 1;
}
.editSidebar {
container: run-config-navigation / inline-size;
min-height: 0;
display: flex;
flex-direction: column;
@@ -597,22 +596,6 @@
background: var(--bg-selected-strong);
color: var(--fg-strong);
}
.editTarget {
flex: 0 1 auto;
min-width: 0;
max-width: 25%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.editItem .failed {
flex: none;
}
@container run-config-navigation (max-width: 220px) {
.editItem .chooserMuted {
display: none;
}
}
.editForm {
flex: 1;
min-width: 0;
@@ -718,7 +701,6 @@
}
.editGroupName {
color: var(--fg-strong);
font-weight: 600;
}
.editEmpty {
flex: 1;
+7 -9
View File
@@ -12,11 +12,9 @@ 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);
@@ -94,20 +92,20 @@ export function RunWidget() {
<IconButton
icon="run"
size="large"
iconSize={iconSize - 2}
iconSize={18}
className={clsx(styles.widgetButton, styles.widgetRun)}
title="Run"
disabled
/>
)}
<span className={clsx(styles.widgetButton, styles.widgetLoading)}>
<Spinner variant="spokes" size={iconSize - 2} label={tx("Starting…")} />
<Spinner variant="spokes" size={18} label={tx("Starting…")} />
</span>
{!debugging && (
<IconButton
icon="debug"
size="large"
iconSize={iconSize - 2}
iconSize={18}
className={styles.widgetButton}
title="Debug"
disabled
@@ -120,7 +118,7 @@ export function RunWidget() {
<IconButton
icon="resume"
size="large"
iconSize={iconSize}
iconSize={20}
className={styles.widgetButton}
title="Resume Program"
shortcut={shortcutLabel("debug.resume")}
@@ -143,7 +141,7 @@ export function RunWidget() {
<IconButton
icon="run"
size="large"
iconSize={iconSize}
iconSize={20}
className={clsx(styles.widgetButton, styles.widgetRun)}
title={
selected
@@ -161,7 +159,7 @@ export function RunWidget() {
<IconButton
icon="debug"
size="large"
iconSize={iconSize}
iconSize={20}
className={styles.widgetButton}
title={selected ? tx`Debug '${selected.name}'` : currentFile ? "Debug Current File" : "Debug"}
shortcut={shortcutLabel("run.debug")}
@@ -198,7 +196,7 @@ export function RunWidget() {
ref={moreRef}
icon="more"
size="large"
iconSize={iconSize}
iconSize={20}
className={styles.widgetButton}
title="More Actions"
aria-haspopup="menu"
+1
View File
@@ -85,6 +85,7 @@ function ScratchChooser({ languages }: { languages: readonly ScratchLanguage[] }
onActivate={(r) => pick(r)}
focusable={false}
hoverSelects
rowHeight={24}
className={styles.list}
aria-label="Languages"
empty={
@@ -29,7 +29,6 @@ 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);
@@ -187,7 +186,6 @@ 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);
@@ -249,7 +247,8 @@ function BookmarksPopup() {
jump(r);
}}
aria-label="Bookmarks"
rowHeight={rowHeight}
rowHeight={22}
sectionHeight={24}
empty={<span>{items.length || paths.length ? null : <T>No bookmarks</T>}</span>}
renderSection={(r) =>
r.kind === "file" ? (
@@ -1,7 +1,6 @@
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";
@@ -88,7 +87,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_ROWS = 10;
const MIN_LIST = 10 * ROW;
const DEBOUNCE_MS = 60;
export function SearchEverywhereOverlay() {
@@ -101,7 +100,6 @@ 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);
@@ -474,8 +472,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_ROWS * rowHeight : 0;
const listHeight = Math.max(minList, rows.length * rowHeight);
const minList = parsed.text.trim() && !listing ? MIN_LIST : 0;
const listHeight = Math.max(minList, rows.length * ROW);
const previewTarget = previewOf(activeRow);
const emptyQuery = !parsed.text.trim();
const showEmpty = !rows.length && snap && !snap.loading && (!emptyQuery || tab !== "all");
@@ -523,8 +521,8 @@ function SearchEverywhereDialog() {
isSelected={(r) => !!sel.keys?.has(r.key)}
onActivate={(r, _i, e) => activate(r, (e as MouseEvent).shiftKey)}
focusable={false}
rowHeight={rowHeight}
sectionHeight={rowHeight}
rowHeight={ROW}
sectionHeight={ROW}
className={styles.list}
aria-label={tx("Results")}
renderItem={(r, state) => (
+2 -4
View File
@@ -37,7 +37,6 @@ 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";
@@ -145,7 +144,6 @@ 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));
@@ -593,7 +591,7 @@ function FindInFilesDialog() {
openRow(r, e.shiftKey);
}}
focusable={false}
rowHeight={rowHeight}
rowHeight={ROW}
aria-label="Matches"
empty={
query ? (
@@ -866,7 +864,7 @@ function FindInFilesDialog() {
<div className={styles.split}>
{rows.length ? (
<SplitGroup orientation="vertical" id="find-popup-split" storageKey={FIND_POPUP_SPLIT_KEY}>
<SplitPanel id="results" minSize={rowHeight * 3} defaultSize="33%">
<SplitPanel id="results" minSize={ROW * 3} defaultSize="33%">
{resultsBox}
</SplitPanel>
<SplitHandle hairline={false} />
@@ -387,6 +387,7 @@ function RecentFilesDialog() {
}}
onActivate={(t) => openTool(t.tw)}
focusable={false}
rowHeight={24}
aria-label="Tool windows"
renderItem={(t) => <ToolRow tw={t.tw} title={t.title} indices={t.indices} />}
/>
@@ -413,6 +414,7 @@ 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 && (
@@ -17,7 +17,6 @@ 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";
@@ -365,7 +364,6 @@ 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);
@@ -468,7 +466,7 @@ function FileStructureDialog() {
e.preventDefault();
};
const height = Math.min(420, Math.max(1, visibleCount(filter.nodes, collapsed)) * rowHeight + 8);
const height = Math.min(420, Math.max(1, visibleCount(filter.nodes, collapsed)) * POPUP_ROW + 8);
return (
<Dialog
open
@@ -555,7 +553,7 @@ function FileStructureDialog() {
speedSearch={false}
activateExpandable
onActivate={(n) => choose(n)}
rowHeight={rowHeight}
rowHeight={POPUP_ROW}
indent={16}
empty={
<span className={styles.popupEmpty}>
@@ -1,7 +1,6 @@
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";
@@ -107,16 +106,6 @@ 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);
@@ -13,7 +13,6 @@ 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";
@@ -46,7 +45,6 @@ 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");
@@ -356,6 +356,7 @@ export function SettingsLayout() {
onSelectionChange={(_sel, node) => node && selectPage(node.key)}
multiSelect={false}
speedSearch={false}
rowHeight={24}
empty={
<div className={styles.noMatch}>
<T>No matches</T>
@@ -93,6 +93,7 @@ function TemplateStep({
onActivate={(t) => onPick(t)}
focusable={false}
hoverSelects
rowHeight={24}
className={styles.templateList}
aria-label="File templates"
renderItem={(t) => (
+1 -3
View File
@@ -4,7 +4,6 @@ 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() {
@@ -58,7 +57,6 @@ 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(() =>
@@ -131,7 +129,7 @@ function ChooserPopup({ request }: { request: ChooserRequest }) {
renderSection={(r) => <div className={styles.section}>{r.item.label}</div>}
focusable={false}
hoverSelects
rowHeight={rowHeight}
rowHeight={22}
className={styles.list}
aria-label={request.title}
empty={<div className={styles.empty}>{request.emptyText ?? tx("Nothing to show")}</div>}
+2 -4
View File
@@ -2,7 +2,6 @@ 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";
@@ -92,7 +91,6 @@ 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<ReadonlySet<Group>>(new Set());
@@ -129,7 +127,7 @@ export function BranchFilterPopup({
setActive(next);
}
};
const height = Math.min(MAX_LIST_HEIGHT, Math.max(rowHeight * 3, rows.length * rowHeight));
const height = Math.min(MAX_LIST_HEIGHT, Math.max(ROW_HEIGHT * 3, rows.length * ROW_HEIGHT));
return (
<Popup
open
@@ -165,7 +163,7 @@ export function BranchFilterPopup({
onActivate={activate}
focusable={false}
hoverSelects
rowHeight={rowHeight}
rowHeight={ROW_HEIGHT}
aria-label="Branches"
className={styles.branchFilterListBody}
empty={
+2 -2
View File
@@ -3,8 +3,8 @@
align-items: center;
gap: var(--space-1);
max-width: 280px;
height: var(--h-toolbar-widget);
border-radius: var(--radius-toolbar-dropdown);
height: 30px;
border-radius: 6px;
}
.icon {
flex: none;
+7 -10
View File
@@ -24,7 +24,6 @@ import {
type MenuItem,
T,
} from "@/ui";
import { useRowHeight } from "@/ui/density";
import type { PopupAnchor } from "@/ui/Popup";
import { buildBranchRows, preferredBranchRow, withExpanded, type BranchRow, type PopupAction } from "./branches";
import { branchPresentation, extensionPopupActions, useBranchWidgetExtensions } from "./branchWidgetExtensions";
@@ -353,13 +352,13 @@ const NO_BRANCHES: readonly Branch[] = [];
const INDENT = 16;
const ROW_HEIGHT = 24;
const SEPARATOR_HEIGHT = 9;
const listHeight = (rows: readonly { type: string; key: string }[], rowHeight: number) =>
const listHeight = (rows: readonly { type: string; key: string }[]) =>
Math.min(
440,
Math.max(
rowHeight * 3,
ROW_HEIGHT * 3,
rows.reduce(
(h, r) => h + (r.type === "section" && r.key.startsWith("separator:") ? SEPARATOR_HEIGHT : rowHeight),
(h, r) => h + (r.type === "section" && r.key.startsWith("separator:") ? SEPARATOR_HEIGHT : ROW_HEIGHT),
0,
),
),
@@ -423,7 +422,6 @@ 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);
@@ -557,7 +555,7 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack }
{!root && <IconButton icon="git-fetch" title="Fetch" size="small" action="vcs.fetch" />}
{!root && <OptionsButton hasTags={tags.length > 0} />}
</div>
<div ref={listRef} style={{ height: listHeight(rows, rowHeight) }} className={styles.listWrap}>
<div ref={listRef} style={{ height: listHeight(rows) }} className={styles.listWrap}>
<List
items={rows}
getKey={(r) => r.key}
@@ -575,7 +573,7 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack }
onActivate={(_r, i) => activate(i)}
focusable={false}
hoverSelects
rowHeight={rowHeight}
rowHeight={ROW_HEIGHT}
aria-label="Branches"
className={styles.list}
empty={<span className={styles.empty}>{loaded ? tx("No matching branches") : tx("Loading…")}</span>}
@@ -620,7 +618,6 @@ 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);
@@ -808,7 +805,7 @@ function MultiRepoPanel({ onClose, actions: popupActions }: { onClose: () => voi
<IconButton icon="git-fetch" title="Fetch" size="small" action="vcs.fetch" />
<OptionsButton hasTags={tags.length > 0} />
</div>
<div ref={listRef} style={{ height: listHeight(rows, rowHeight) }} className={styles.listWrap}>
<div ref={listRef} style={{ height: listHeight(rows) }} className={styles.listWrap}>
<List
items={rows}
getKey={(r) => r.key}
@@ -826,7 +823,7 @@ function MultiRepoPanel({ onClose, actions: popupActions }: { onClose: () => voi
onActivate={(_r, i) => activate(i)}
focusable={false}
hoverSelects
rowHeight={rowHeight}
rowHeight={ROW_HEIGHT}
aria-label="Repositories and branches"
className={styles.list}
empty={
+1 -3
View File
@@ -3,7 +3,6 @@ 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<Commit | null> {
return new Promise((resolve) => {
@@ -29,7 +28,6 @@ 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()),
@@ -43,7 +41,7 @@ function CommitChooser({
getKey={commitKey}
renderItem={(c) => `${c.shortId} ${c.summary} — ${c.author}`}
onActivate={onDone}
rowHeight={rowHeight}
rowHeight={26}
aria-label={title}
/>
</div>
+1 -3
View File
@@ -112,7 +112,6 @@ 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";
@@ -1382,7 +1381,6 @@ async function stashFileChanges(stash: StashEntry): Promise<LogChange[]> {
}
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);
@@ -1493,7 +1491,7 @@ export function StashesPanel() {
loadChildren={loadFiles}
selected={useMemo(() => new Set(selectedKey ? [selectedKey] : []), [selectedKey])}
multiSelect={false}
rowHeight={rowHeight}
rowHeight={22}
aria-label="Stashes"
className={styles.stashList}
empty={<span className={styles.empty}>{error ?? (loaded ? tx("No stashes") : tx("Loading…"))}</span>}
+1 -3
View File
@@ -10,7 +10,6 @@ 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;
@@ -76,7 +75,6 @@ function CommitList({
error: string | null;
onClose: () => void;
}) {
const rowHeight = useRowHeight(22);
return (
<div className={styles.commitListBody}>
{error ? (
@@ -91,7 +89,7 @@ function CommitList({
<List
items={commits}
getKey={(c) => c.id}
rowHeight={rowHeight}
rowHeight={22}
aria-label="Commits"
className={styles.grow}
empty={
+2 -3
View File
@@ -28,7 +28,6 @@ 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));
@@ -154,7 +153,6 @@ 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<DirectoryCompareEntry[]>([]);
const [current, setCurrent] = useState<DirectoryCompareEntry | null>(null);
@@ -340,7 +338,8 @@ export function DirectoryCompare({ left, right }: { left: string; right: string
onActivate={(r, _i, e) => {
if ("entry" in r && e.type === "keydown") open(r.entry);
}}
rowHeight={rowHeight}
rowHeight={22}
sectionHeight={24}
tableBody={{ headerRows: 1 }}
empty={
!busy && !cancelled && !error ? (
@@ -9,11 +9,11 @@
display: inline-flex;
align-items: center;
justify-content: center;
width: var(--titlebar-tool-button);
height: var(--titlebar-tool-button);
width: 30px;
height: 30px;
padding: 0;
border: 0;
border-radius: var(--radius-toolbar-button);
border-radius: 6px;
cursor: pointer;
}
.go {
+1
View File
@@ -193,6 +193,7 @@ function Chooser({
renderSection={(i) => <span title={i.detail}>{i.rev}</span>}
focusable={false}
hoverSelects
rowHeight={24}
aria-label="Revisions"
className={styles.grow}
renderItem={(i) => (
+1 -3
View File
@@ -18,7 +18,6 @@ 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;
@@ -97,7 +96,6 @@ 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<Commit[][] | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -225,7 +223,7 @@ function SyncCommitsPopup({
onActivate={(row) => {
if (row.type === "commit") openDiff(row.commit);
}}
rowHeight={rowHeight}
rowHeight={22}
aria-label={title}
className={styles.list}
/>
+2 -4
View File
@@ -6,7 +6,6 @@
*/
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";
@@ -76,7 +75,6 @@ export function TargetBranchInput({
remote: string | null;
}) {
const tx = useTx();
const rowHeight = useRowHeight(ROW_HEIGHT);
const input = useRef<HTMLInputElement>(null);
const [open, setOpen] = useState(false);
// No row is chosen until the user moves in the list: Enter keeps pushing the typed name.
@@ -141,7 +139,7 @@ export function TargetBranchInput({
<span key={s.name}>{s.name}</span>
))}
</div>
<div className={styles.targetListWrap} style={{ height: rows * rowHeight + LIST_PADDING }}>
<div className={styles.targetListWrap} style={{ height: rows * ROW_HEIGHT + LIST_PADDING }}>
<List
items={suggestions}
getKey={(s) => s.name}
@@ -150,7 +148,7 @@ export function TargetBranchInput({
onActivate={(s) => choose(s)}
focusable={false}
hoverSelects
rowHeight={rowHeight}
rowHeight={ROW_HEIGHT}
aria-label={tx("Remote branches")}
className={styles.targetList}
empty={<span className={styles.hint}>{tx("No matching remote branches")}</span>}
+1 -3
View File
@@ -15,7 +15,6 @@ 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
@@ -65,7 +64,6 @@ 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));
@@ -143,7 +141,7 @@ function ConflictsDialog({ onClose }: { onClose: () => void }) {
getKey={(f) => f.path}
activeIndex={Math.min(active, files.length - 1)}
onActiveChange={setActive}
rowHeight={rowHeight}
rowHeight={22}
aria-label="Conflicted files"
className={styles.boxList}
empty={
+1
View File
@@ -204,6 +204,7 @@ 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) => (
+5 -10
View File
@@ -3,7 +3,6 @@ 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";
@@ -220,8 +219,6 @@ export function CommitList() {
const selectedSet = useMemo(() => new Set(selection), [selection]);
const revealTick = useGitLog((s) => s.revealTick);
const scrollRef = useRef<HTMLDivElement>(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],
@@ -235,24 +232,23 @@ 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, row]);
}, [commits, revealTick, selectedIndex]);
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];
@@ -585,7 +581,7 @@ export function CommitList() {
const c = commits[v.index];
if (!c)
return (
<div key="loading" className={styles.row} style={{ top: v.start - ROW, height: row }}>
<div key="loading" className={styles.row} style={{ top: v.start - ROW }}>
<Spinner size={12} />{" "}
<span className={styles.muted}>
<T>Loading…</T>
@@ -602,7 +598,6 @@ 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)}
+1 -3
View File
@@ -22,7 +22,6 @@ function CommitRowView({
fileHistoryTarget,
graph,
top,
height,
selected,
head,
mine,
@@ -46,7 +45,6 @@ function CommitRowView({
fileHistoryTarget: string | null;
graph: GraphRow | undefined;
top: number;
height: number;
selected: boolean;
head: boolean;
mine: boolean;
@@ -164,7 +162,7 @@ function CommitRowView({
selected && styles.selected,
opts.showColumnDividers && styles.showDividers,
)}
style={{ top, height }}
style={{ top }}
onMouseDown={(e) => {
if (e.shiftKey) e.preventDefault(); // no text selection on range clicks
onPick(commitKey(c), e);
+4 -6
View File
@@ -1,5 +1,4 @@
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";
@@ -39,15 +38,14 @@ export function GraphCell({
onNode?: () => void;
interactive?: boolean;
}) {
const height = useRowHeight(ROW);
const cy = height / 2;
const cy = ROW / 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 : height) +
(s.arrow ? arrowHead(up ? fromX : toX, up ? 0 : height, up ? -1 : 1) : "");
seg(fromX, up ? 0 : cy, toX, up ? cy : ROW) +
(s.arrow ? arrowHead(up ? fromX : toX, up ? 0 : ROW, up ? -1 : 1) : "");
const line = (
<path
key={interactive ? undefined : `${up ? "u" : "d"}${i}`}
@@ -116,7 +114,7 @@ export function GraphCell({
<svg
className={styles.graph}
width={width}
height={height}
height={ROW}
aria-label={tx("Commit graph")}
onMouseLeave={() => onHover?.(null)}
>
+1 -3
View File
@@ -18,7 +18,6 @@ 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[] }
@@ -260,7 +259,6 @@ 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<PatchFile[] | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -318,7 +316,7 @@ function ApplyPatchDialog({ patch, source, onClose }: { patch: string; source: s
<List
items={files}
getKey={(f) => f.path}
rowHeight={rowHeight}
rowHeight={22}
aria-label="Patch files"
className={styles.boxList}
empty={
+2 -5
View File
@@ -30,7 +30,6 @@ 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 {
@@ -257,7 +256,6 @@ 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<RepoPush[] | null>(null);
@@ -476,7 +474,7 @@ function MultiPushDialog({ only, onClose }: MultiPushDialogProps) {
selected={new Set(shown ? [shown.key] : [])}
multiSelect={false}
onSelectionChange={(_sel, lead) => setShown(lead)}
rowHeight={rowHeight}
rowHeight={22}
aria-label="Outgoing commits"
className={styles.boxList}
empty={
@@ -606,7 +604,6 @@ 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);
@@ -740,7 +737,7 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
getKey={(c) => c.id}
activeIndex={shownCommit}
onActiveChange={setShownCommit}
rowHeight={rowHeight}
rowHeight={22}
aria-label="Outgoing commits"
className={styles.boxList}
empty={<span>{upstream ? tx("Everything is up to date") : tx("No commits")}</span>}
-4
View File
@@ -166,10 +166,6 @@
"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",
+2
View File
@@ -2915,6 +2915,8 @@
"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",
+2
View File
@@ -2815,6 +2815,8 @@
"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",
+2
View File
@@ -2965,6 +2965,8 @@
"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": "구성 유형 검색",
+2
View File
@@ -2887,6 +2887,8 @@
"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",
+2
View File
@@ -2888,6 +2888,8 @@
"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",
+2 -4
View File
@@ -3706,6 +3706,8 @@
"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": "搜索配置类型",
@@ -4861,10 +4863,6 @@
"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": "无法复制引用",
+3 -21
View File
@@ -295,8 +295,6 @@ 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%) */
@@ -304,8 +302,6 @@ 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;
@@ -328,8 +324,6 @@ 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;
@@ -1502,30 +1496,18 @@ html {
* Appearance options (Settings › Appearance), applied as attributes on :root
* by the settings runtime.
*/
/*
* 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.
*/
/* Compact mode: smaller rows, toolbars and tabs. */
: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: 22px;
--h-list-row: 22px;
--h-row: 20px;
--h-list-row: 20px;
--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] {
+4 -4
View File
@@ -23,18 +23,18 @@
}
/* Status bar widget (StatusBar.Widget): UI font, secondary text, rounded hover. */
.status {
height: max(var(--h-statusbar) - 8px, var(--h-control-small));
height: 22px;
margin: 0 -2px;
padding: 0 6px;
color: var(--fg-secondary);
font-size: var(--fs-chrome);
font-size: var(--fs-ui);
}
/* Main toolbar widget (project / VCS / run configuration). */
.title {
height: var(--h-toolbar-widget);
height: 28px;
margin: 0 -4px;
padding: 0 8px;
border-radius: var(--radius-toolbar-dropdown);
border-radius: var(--radius-toolbar-button, 6px);
color: var(--fg-strong);
}
.mono {
+2 -7
View File
@@ -16,7 +16,6 @@ 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";
@@ -134,8 +133,8 @@ export function List<T>({
isSelected,
onActivate,
onContextMenu,
rowHeight: fixedRowHeight,
sectionHeight: fixedSectionHeight,
rowHeight = 24,
sectionHeight = 24,
sectionHeightOf,
focusable = true,
hoverSelects = false,
@@ -155,9 +154,6 @@ export function List<T>({
const scrollRef = useRef<HTMLDivElement>(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,
@@ -165,7 +161,6 @@ export function List<T>({
overscan,
getItemKey: (i) => getKey(items[i]!, i),
});
useEffect(() => virtualizer.measure(), [virtualizer, rowHeight, sectionHeight]);
const viewportHeight = virtualizer.scrollRect?.height;
useEffect(() => {
+1
View File
@@ -253,6 +253,7 @@ export function SelectListbox<V extends string = string>({
onActivate={(o) => choose(o)}
focusable={false}
hoverSelects
rowHeight={24}
aria-label={given(aria["aria-label"])}
className={clsx(styles.list, listClassName)}
renderItem={(o) => {
+2 -3
View File
@@ -15,13 +15,12 @@
.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: var(--h-tab);
height: 28px;
}
.scroller {
display: flex;
@@ -42,7 +41,7 @@
align-items: stretch;
height: calc(100% - 6px);
min-height: 22px;
max-height: var(--h-tab);
max-height: 28px;
border-radius: var(--radius-tab, 6px);
color: var(--fg-strong);
transition:
+2 -3
View File
@@ -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,8 +353,7 @@ export function Tree<T>(props: TreeProps<T>) {
const leadIndex = lead != null ? (indexOfKey.get(lead) ?? -1) : -1;
const themedRowHeight = useIconRowHeight();
const defaultRowHeight = useRowHeight();
const rowHeight = fixedRowHeight ?? themedRowHeight ?? defaultRowHeight;
const rowHeight = fixedRowHeight ?? themedRowHeight ?? DEFAULT_ROW_HEIGHT;
const virtualizer = useVirtualizer({
count: rows.length,
getScrollElement: () => scrollRef.current,
-54
View File
@@ -1,54 +0,0 @@
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) => (
<Tree
roots={[{ key: "a" }]}
getKey={(n) => n.key}
getLabel={(n) => n.key}
getChildren={() => undefined}
isExpandable={() => false}
rowHeight={rowHeight}
aria-label="t"
/>
);
const { container, rerender } = render(tree());
const row = () => container.querySelector<HTMLElement>('[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(<List items={["a", "b"]} getKey={(s) => s} renderItem={(s) => s} aria-label="l" />);
const option = () => container.querySelector<HTMLElement>('[role="option"]');
expect(option()?.style.height).toBe("24px");
act(() => setCompactMode(true));
expect(option()?.style.height).toBe("22px");
});
});
-27
View File
@@ -1,27 +0,0 @@
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<boolean>(() => 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;
}
-14
View File
@@ -1,6 +1,5 @@
/** 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");
@@ -9,16 +8,3 @@ 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 =
`<svg class="${spinnerStyles.spinner}" width="${size}" height="${size}" viewBox="0 0 24 24">` +
'<circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-opacity="0.2" stroke-width="2.4"/>' +
'<path d="M21 12a9 9 0 0 0-9-9" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/>' +
"</svg>";
return span;
}
+1 -3
View File
@@ -6,7 +6,6 @@ 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";
@@ -95,7 +94,6 @@ 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<Submenu[]>([]);
const [expanded, setExpanded] = useState(false);
const [open, setOpen] = useState<number | null>(null);
@@ -251,7 +249,7 @@ function MainMenuBar({ merged, row, onExpandedChange }: MainMenuProps & { merged
}
}}
>
<Icon name="main-menu" size={iconSize} />
<Icon name="main-menu" size={20} />
</button>
);
const titles = (
+2
View File
@@ -101,6 +101,7 @@ 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={
@@ -211,6 +212,7 @@ 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) => (
+2 -9
View File
@@ -7,16 +7,12 @@
gap: var(--space-1);
padding: 0 10px 0 12px;
font-family: var(--font-ui);
font-size: var(--fs-chrome);
font-size: var(--fs-ui);
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);
@@ -33,14 +29,11 @@
min-width: 0;
padding: 0 4px;
}
/* Left items shrink on narrow windows; right items move into the overflow popup. */
/* Left items (breadcrumbs…) give way first on narrow windows; right items move into the overflow popup. */
.shrink {
flex: 0 1 auto;
overflow: hidden;
}
.shrink[data-status-item="editor.breadcrumbs"]:not(:empty) {
min-width: min(152px, 28vw);
}
.shrink > * {
min-width: 0;
overflow: hidden;
+5 -8
View File
@@ -112,24 +112,22 @@ export function StatusBar({ lightEdit = false }: { lightEdit?: boolean }) {
return () => ro.disconnect();
}, []);
useLayoutEffect(() => {
const leftHosts = [...(barRef.current?.querySelectorAll<HTMLElement>(":scope > [data-status-item]") ?? [])];
measure.current = () => {
const bar = barRef.current;
if (!bar) return;
const css = getComputedStyle(bar);
const gap = parseFloat(css.columnGap) || 0;
const spacer = spacerRef.current;
const leftWidth = leftHosts.reduce(
(width, el) =>
el.getClientRects().length ? width + (parseFloat(getComputedStyle(el).minWidth) || 0) + gap : width,
0,
);
// Left items shrink instead (down to their gap); the spacer keeps its minimum.
const leftShown = [...bar.querySelectorAll<HTMLElement>(":scope > [data-status-item]")].filter(
(el) => el.getClientRects().length > 0,
).length;
const available =
bar.clientWidth -
(parseFloat(css.paddingLeft) || 0) -
(parseFloat(css.paddingRight) || 0) -
(spacer ? parseFloat(getComputedStyle(spacer).minWidth) || 0 : 0) -
leftWidth;
leftShown * gap;
const items = shownRight.map((i) => ({
id: i.id,
priority: i.priority,
@@ -148,7 +146,6 @@ export function StatusBar({ lightEdit = false }: { lightEdit?: boolean }) {
}
// The spacer changes width whenever an item comes or goes; the bar, when the window resizes.
for (const el of [spacerRef.current, barRef.current, moreRef.current]) if (el) ro?.observe(el);
for (const el of leftHosts) ro?.observe(el);
});
const renderLeft = (item: StatusItemContribution) => {
+4 -11
View File
@@ -9,7 +9,6 @@
-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 {
@@ -69,12 +68,12 @@
/* Main toolbar dropdown widgets. */
.widget {
min-width: 0;
height: var(--h-toolbar-widget);
height: 30px;
margin: 0;
padding: 0 8px;
border-radius: var(--radius-toolbar-dropdown);
border-radius: var(--radius-popup);
color: var(--fg-strong);
font-size: var(--fs-chrome);
font-size: var(--fs-ui);
}
.widget {
gap: var(--space-1-5);
@@ -107,12 +106,6 @@
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;
@@ -127,7 +120,7 @@
.tool {
width: var(--titlebar-tool-button);
height: var(--titlebar-tool-button);
border-radius: var(--radius-toolbar-button);
border-radius: var(--radius-popup);
color: var(--fg-secondary);
}
+2 -5
View File
@@ -5,7 +5,6 @@ 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";
@@ -214,7 +213,6 @@ function useToolbar() {
}
function GearButton({ customize }: { customize: MenuItem[] }) {
const iconSize = useChromeIconSize();
const [open, setOpen] = useState(false);
const ref = useRef<HTMLButtonElement>(null);
const settings = useProject((s) => s.settings);
@@ -243,7 +241,7 @@ function GearButton({ customize }: { customize: MenuItem[] }) {
ref={ref}
icon="settings"
title="IDE and Project Settings"
iconSize={iconSize}
iconSize={20}
className={styles.tool}
aria-haspopup="menu"
aria-expanded={open}
@@ -257,7 +255,6 @@ 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<string, TitleItemContribution> }) {
const actions = useActions((s) => s.actions);
const iconSize = useChromeIconSize();
if (id === PROJECT_WIDGET) return <ProjectButton />;
const item = items.get(id);
if (item) return <TitleItem item={item} />;
@@ -272,7 +269,7 @@ function ToolbarEntry({ id, items }: { id: string; items: ReadonlyMap<string, Ti
action={action.id}
title={action.title}
shortcut={shortcutLabel(action.id) ?? (action.id === "navigate.searchEverywhere" ? "⇧⇧" : undefined)}
iconSize={iconSize}
iconSize={20}
className={styles.tool}
/>
</div>
+2
View File
@@ -268,6 +268,7 @@ 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={
@@ -473,6 +474,7 @@ 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={
@@ -343,11 +343,6 @@
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);
}
@@ -445,7 +440,6 @@
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);
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more