дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 09:41:34 +02:00
fix(code-insight): stabilize Show Usages popup sizing and placement (#8080)
* fix(code-insight): stabilize Show Usages popup sizing and placement The popup used a fixed 680px width and 14-row limit. Restoring a saved size also prevented it from adapting to incoming results. Follow the IntelliJ popup sizing and placement flow while limiting the filename column to 25% of the popup width to leave space for code. Sizing and columns: - Restore both saved dimensions while waiting for results. Once results arrive, cap the natural width at the saved width and calculate the height from content. Only preview mode also uses the saved height. - Measure filenames, line numbers and code with the actual fonts, with a 500px natural width limit per column. Fit short filenames to their content and ellipsize long names at 25% of the row width. Reserve 5ch for line numbers and at least 8em for code, which fills the remaining space. - Include the filename cap, code minimum width, header, controls, borders and gaps in the natural popup width. Do not widen the popup for text that the filename column will clip. - Cache maximum natural widths during streaming and filtering. After a manual resize, keep updating filename measurements but stop resizing the popup automatically until it is reopened or preview is toggled. - Show up to 30 rows normally or 20 with preview. Leave half a row when the list scrolls, and let the list fill the available height. - Preserve the 360x160 minimum size and existing storage keys. Fit the viewport when it is smaller, and save the actual size on close. Placement and preview: - Open below the caret. When it is outside the visible editor, use a point one third across and halfway down the visible editing area. - Add optional fitToScreen placement to Popup. Keep the fitted position when content shrinks, and move only when necessary to stay visible. Reset placement when the anchor changes or preview rebuilds the popup. - Reuse the shared split panels with a default 60/40 list/preview split, persisted proportions, mouse dragging and keyboard adjustment. Set the preview minimum to five actual editor lines and update it after font or editor geometry changes. - Preserve the preview's pixel height while manually resizing the outer popup. Wait for the splitter's final measurement before restoring it. - Add onResizeStart on the first pointer movement. Clicking the resize handle alone does not lock preview height. Toggling preview clears saved dimensions, measurements, manual size and drag position, and cancels pending resize callbacks. - Add a translated accessible label to the preview divider and preserve its keyboard controls alongside usage-list navigation. Verification: - 17 Playwright layout and demo tests passed in local Google Chrome, covering both themes, the 25% cap, narrow windows, filtering, saved dimensions, position stability, preview, keyboard controls and resize. Both filename-cap regression cases failed before the fix and passed afterward. - Wait for fonts and entry animations before dragging the one-pixel divider or measuring dimensions. Account for popup growth when the search caption changes while checking the filename cap. - 49 Popup and Show Usages unit tests passed on the final version. - pnpm typecheck and pnpm build passed, including Safari 15.4 checks. Changed-file oxlint, oxfmt and git diff --check passed. - An earlier full test run had 20,483 passed, 65 skipped and two existing translation-check failures in color-preview/varColors.ts and vcs/rebase.tsx. Earlier full lint and knip checks passed. Full format checking failed on an existing untracked .workbuddy memory file. - Before/after screenshots for both themes and narrow windows, plus interaction recordings, are retained in temporary verification folders. Tests used browser fixtures; the native Tauri webview was not tested because no Tauri MCP bridge was available. * fix(code-insight): restore focus across preview toggle, avoid width ratchet, and clean up cancelled resizes --------- Co-authored-by: l0ng-ai <[email protected]>
Цей коміт міститься в:
1 джерело
494d1a9bf5
коміт
a2498f096a
13 files changed
+1060
-145
No files matched your search
@@ -141,6 +141,7 @@ function DemoControls() {
|
||||
};
|
||||
const centered = (next = scenario) => show(window.innerWidth / 2, 80, next);
|
||||
const resize = (width: number) => {
|
||||
flushSync(() => dismissUsagesPopup());
|
||||
localStorage.setItem(sizeKey, JSON.stringify({ w: width, h: 320 }));
|
||||
centered();
|
||||
};
|
||||
@@ -218,6 +219,7 @@ function DemoControls() {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
flushSync(() => dismissUsagesPopup());
|
||||
localStorage.removeItem(sizeKey);
|
||||
centered();
|
||||
}}
|
||||
|
||||
@@ -2,9 +2,6 @@ import { expect, test } from "./fixtures";
|
||||
|
||||
let errors: string[];
|
||||
|
||||
/** The filename column's cap for a row this wide (`UsagesPopup.module.css`). */
|
||||
const fileCap = (row: number) => Math.max(Math.min(row * 0.38, 176), row * 0.2);
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
errors = [];
|
||||
page.on("pageerror", (error) => errors.push(error.message));
|
||||
@@ -33,8 +30,7 @@ test("demo scenarios fit short names, cap long names and retain code at each pre
|
||||
await controls.getByRole("button", { name: "超长文件名", exact: true }).click();
|
||||
for (const name of ["窄窗口 420", "默认宽 680", "宽窗口 1000"]) {
|
||||
await controls.getByRole("button", { name, exact: true }).click();
|
||||
const rowWidth = await first.evaluate((el) => el.getBoundingClientRect().width);
|
||||
await expect.poll(fileWidth).toBeCloseTo(fileCap(rowWidth), 0);
|
||||
await expect.poll(async () => (await fileWidth()) / (await popup.boundingBox())!.width).toBeLessThanOrEqual(0.25);
|
||||
expect(
|
||||
await first.locator(":scope > span:last-child").evaluate((el) => el.getBoundingClientRect().width),
|
||||
).toBeGreaterThanOrEqual(100);
|
||||
@@ -82,7 +78,7 @@ test("demo columns stay stable with the longest filename offscreen, scrolling an
|
||||
await expect.poll(width).toBeCloseTo(before, 0);
|
||||
});
|
||||
|
||||
test("demo access filters and empty speed search recover without shifting columns", async ({ page }) => {
|
||||
test("demo access filters and empty speed search preserve the filename cap", async ({ page }) => {
|
||||
await page.getByRole("button", { name: "读写与搜索", exact: true }).click();
|
||||
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
|
||||
const rows = popup.getByTestId("usage-row");
|
||||
@@ -92,6 +88,11 @@ test("demo access filters and empty speed search recover without shifting column
|
||||
.locator(":scope > span:first-child")
|
||||
.evaluate((el) => el.getBoundingClientRect().width);
|
||||
await expect(rows).toHaveCount(3);
|
||||
await popup.evaluate(async (el) => {
|
||||
await document.fonts.ready;
|
||||
await Promise.all(el.getAnimations().map((animation) => animation.finished));
|
||||
});
|
||||
const popupBefore = (await popup.boundingBox())!.width;
|
||||
const before = await width();
|
||||
await popup.getByRole("button", { name: "Show write accesses", exact: true }).click();
|
||||
await expect(rows).toHaveCount(2);
|
||||
@@ -102,7 +103,9 @@ test("demo access filters and empty speed search recover without shifting column
|
||||
await expect(rows).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(rows).toHaveCount(2);
|
||||
await expect.poll(width).toBeCloseTo(before, 0);
|
||||
await expect
|
||||
.poll(async () => (await width()) - ((await popup.boundingBox())!.width - popupBefore) / 4)
|
||||
.toBeCloseTo(before, 0);
|
||||
await popup.getByRole("button", { name: "Show write accesses", exact: true }).click();
|
||||
await expect(rows).toHaveCount(3);
|
||||
});
|
||||
@@ -131,10 +134,13 @@ test("demo loading and live font changes remeasure the filename column", async (
|
||||
await expect(content).toHaveAttribute("data-loading", "false");
|
||||
await expect(content).toHaveAttribute("data-total", "4");
|
||||
await expect.poll(width).toBeGreaterThan(before);
|
||||
const rowWidth = await popup
|
||||
.getByTestId("usage-row")
|
||||
.first()
|
||||
.evaluate((el) => el.getBoundingClientRect().width);
|
||||
expect(await width()).toBeCloseTo(fileCap(rowWidth), 0);
|
||||
expect(await width()).toBeLessThanOrEqual(500);
|
||||
expect(
|
||||
await popup
|
||||
.getByTestId("usage-row")
|
||||
.first()
|
||||
.locator(":scope > span:last-child")
|
||||
.evaluate((el) => el.getBoundingClientRect().width),
|
||||
).toBeGreaterThanOrEqual(100);
|
||||
await page.screenshot({ path: test.info().outputPath("usages-demo-scenarios.png"), animations: "disabled" });
|
||||
});
|
||||
@@ -1,7 +1,383 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
import type { Page } from "@playwright/test";
|
||||
|
||||
async function resizePopupWidth(page: Page, width: number) {
|
||||
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
|
||||
await popup.evaluate((el) => Promise.all(el.getAnimations().map((animation) => animation.finished)));
|
||||
const box = (await popup.boundingBox())!;
|
||||
const corner = (await popup.getByRole("separator", { name: "Resize", exact: true }).boundingBox())!;
|
||||
const x = corner.x + corner.width / 2;
|
||||
const y = corner.y + corner.height / 2;
|
||||
await page.mouse.move(x, y);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(x + width - box.width, y, { steps: 5 });
|
||||
await page.mouse.up();
|
||||
await expect.poll(async () => (await popup.boundingBox())!.width).toBeCloseTo(width, 0);
|
||||
}
|
||||
|
||||
test.use({ video: "on" });
|
||||
|
||||
for (const theme of ["light", "dark"] as const) {
|
||||
test(`Show Usages keeps its fitted position when results shrink in ${theme} theme`, async ({ workbench: page }) => {
|
||||
await page.evaluate(async (theme) => {
|
||||
const themeModule = "/src/workbench/theme.ts";
|
||||
await (await import(/* @vite-ignore */ themeModule)).setTheme(theme);
|
||||
localStorage.setItem("openidea.usages.popupSize.v1", JSON.stringify({ w: 900, h: 700 }));
|
||||
const usages = "/src/features/code-insight/usages.ts";
|
||||
const preview = "/src/features/code-insight/UsagesPopup.tsx";
|
||||
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
|
||||
(await import(/* @vite-ignore */ preview)).setUsagesPopupPreview(false);
|
||||
useUsagesPopup.setState({
|
||||
open: true,
|
||||
anchor: { x: 1200, y: 700 },
|
||||
symbol: "run",
|
||||
loading: true,
|
||||
groups: [],
|
||||
note: null,
|
||||
scope: null,
|
||||
});
|
||||
}, theme);
|
||||
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
|
||||
await expect.poll(async () => (await popup.boundingBox())?.height).toBeCloseTo(700, 0);
|
||||
await popup.evaluate((el) => Promise.all(el.getAnimations().map((a) => a.finished)));
|
||||
const before = (await popup.boundingBox())!;
|
||||
await page.screenshot({ path: test.info().outputPath("1-loading.png"), animations: "disabled" });
|
||||
await page.evaluate(async () => {
|
||||
const usages = "/src/features/code-insight/usages.ts";
|
||||
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
|
||||
const path = "/dev/app/A.ts";
|
||||
useUsagesPopup.setState({
|
||||
loading: false,
|
||||
groups: [{ path, usages: [0, 1].map((line) => ({ path, line, col: 0, endCol: 3, text: "run();" })) }],
|
||||
});
|
||||
});
|
||||
await expect.poll(async () => (await popup.boundingBox())!.height).toBeCloseTo(160, 0);
|
||||
await page.screenshot({ path: test.info().outputPath("2-results.png"), animations: "disabled" });
|
||||
await expect.poll(async () => (await popup.boundingBox())!.x).toBeCloseTo(before.x, 0);
|
||||
await expect.poll(async () => (await popup.boundingBox())!.y).toBeCloseTo(before.y, 0);
|
||||
});
|
||||
|
||||
test(`Show Usages caps filename width at a quarter of the popup in ${theme} theme`, async ({ workbench: page }) => {
|
||||
await page.evaluate(async (theme) => {
|
||||
const themeModule = "/src/workbench/theme.ts";
|
||||
await (await import(/* @vite-ignore */ themeModule)).setTheme(theme);
|
||||
localStorage.removeItem("openidea.usages.popupSize.v1");
|
||||
const usages = "/src/features/code-insight/usages.ts";
|
||||
const preview = "/src/features/code-insight/UsagesPopup.tsx";
|
||||
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
|
||||
(await import(/* @vite-ignore */ preview)).setUsagesPopupPreview(false);
|
||||
const path = "/dev/app/TransportPlanConfigurationServiceForOrderApprovalQueries.ts";
|
||||
useUsagesPopup.setState({
|
||||
open: true,
|
||||
anchor: { x: 40, y: 60 },
|
||||
symbol: "run",
|
||||
loading: false,
|
||||
note: null,
|
||||
scope: null,
|
||||
groups: [{ path, usages: [0, 1].map((line) => ({ path, line, col: 0, endCol: 3, text: "run();" })) }],
|
||||
});
|
||||
}, theme);
|
||||
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
|
||||
const file = popup.getByTestId("usage-row").first().locator(":scope > span:first-child");
|
||||
const label = popup.getByTestId("usage-row").first().locator(":scope > span:first-child > span");
|
||||
await expect(label).toBeVisible();
|
||||
await popup.evaluate(async (el) => {
|
||||
await document.fonts.ready;
|
||||
await Promise.all(el.getAnimations().map((a) => a.finished));
|
||||
});
|
||||
await page.screenshot({ path: test.info().outputPath("natural-filename.png"), animations: "disabled" });
|
||||
await expect
|
||||
.poll(async () => (await file.boundingBox())!.width / (await popup.boundingBox())!.width)
|
||||
.toBeLessThanOrEqual(0.25);
|
||||
expect(await label.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeGreaterThan(0);
|
||||
await page.setViewportSize({ width: 480, height: 620 });
|
||||
const code = popup.getByTestId("usage-row").first().locator(":scope > span:last-child");
|
||||
await expect.poll(async () => (await popup.boundingBox())!.width).toBeLessThanOrEqual(468);
|
||||
await expect
|
||||
.poll(async () => (await file.boundingBox())!.width / (await popup.boundingBox())!.width)
|
||||
.toBeLessThanOrEqual(0.25);
|
||||
expect((await code.boundingBox())!.width).toBeGreaterThanOrEqual(100);
|
||||
await page.screenshot({ path: test.info().outputPath("narrow-filename.png"), animations: "disabled" });
|
||||
});
|
||||
}
|
||||
|
||||
test("Show Usages splits preview at 40%, preserves its pixel height on window resize and remembers divider changes", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1400, height: 1100 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
window.__ipc.handlers.fs_read_text = () => Array.from({ length: 80 }, (_, line) => `run(${line});`).join("\n");
|
||||
});
|
||||
const show = () =>
|
||||
page.evaluate(async () => {
|
||||
const usages = "/src/features/code-insight/usages.ts";
|
||||
const preview = "/src/features/code-insight/UsagesPopup.tsx";
|
||||
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
|
||||
const { setUsagesPopupPreview } = await import(/* @vite-ignore */ preview);
|
||||
setUsagesPopupPreview(true);
|
||||
const path = "/dev/app/A.ts";
|
||||
useUsagesPopup.setState({
|
||||
open: true,
|
||||
anchor: { x: 40, y: 60 },
|
||||
symbol: "run",
|
||||
loading: false,
|
||||
note: null,
|
||||
groups: [
|
||||
{
|
||||
path,
|
||||
usages: Array.from({ length: 40 }, (_, line) => ({ path, line, col: 0, endCol: 3, text: "run();" })),
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
await page.evaluate(() => localStorage.setItem("openidea.usages.popupSize.v1", JSON.stringify({ w: 900, h: 750 })));
|
||||
await show();
|
||||
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
|
||||
const preview = popup.getByRole("region", { name: "Preview", exact: true });
|
||||
const divider = popup.getByRole("separator", { name: "Resize usages preview", exact: true });
|
||||
const list = popup.getByRole("listbox", { name: "Usages" });
|
||||
await expect(divider).toBeVisible();
|
||||
await expect(preview.locator(".cm-content")).toBeVisible();
|
||||
await expect(preview.locator(".cm-content")).toContainText("run(0)");
|
||||
await page.evaluate(async () => {
|
||||
await document.fonts.ready;
|
||||
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
|
||||
});
|
||||
await popup.evaluate((el) => Promise.all(el.getAnimations().map((animation) => animation.finished)));
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const groupHeight = await preview.evaluate((el) => el.closest("[data-group]")!.getBoundingClientRect().height);
|
||||
return (await preview.boundingBox())!.height / (groupHeight - 1);
|
||||
})
|
||||
.toBeCloseTo(0.4, 2);
|
||||
const before = (await preview.boundingBox())!.height;
|
||||
const listBefore = (await list.boundingBox())!.height;
|
||||
const groupBefore = await preview.evaluate((el) => el.closest("[data-group]")!.getBoundingClientRect().height);
|
||||
const corner = (await popup.getByRole("separator", { name: "Resize", exact: true }).boundingBox())!;
|
||||
await page.mouse.move(corner.x + 4, corner.y + 4);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(corner.x + 84, corner.y + 104, { steps: 5 });
|
||||
await page.mouse.up();
|
||||
await expect.poll(async () => (await preview.boundingBox())!.height).toBeCloseTo(before, 0);
|
||||
const groupAfter = await preview.evaluate((el) => el.closest("[data-group]")!.getBoundingClientRect().height);
|
||||
await expect
|
||||
.poll(async () => (await list.boundingBox())!.height)
|
||||
.toBeCloseTo(listBefore + groupAfter - groupBefore, 0);
|
||||
const boundary = (await divider.boundingBox())!;
|
||||
// A click on the outer resize handle must not keep anchoring later divider drags.
|
||||
await popup.getByRole("separator", { name: "Resize", exact: true }).click();
|
||||
await page.mouse.move(boundary.x + boundary.width / 2, boundary.y + 0.5);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(boundary.x + boundary.width / 2, boundary.y - 79.5, { steps: 5 });
|
||||
await page.mouse.up();
|
||||
await expect.poll(async () => (await preview.boundingBox())!.height).toBeCloseTo(before + 80, 0);
|
||||
const layout = await page.evaluate(() => JSON.parse(localStorage.getItem("openidea.usages.popupSplit.v1")!));
|
||||
expect(layout.preview).toBeGreaterThan(40);
|
||||
await divider.focus();
|
||||
await page.keyboard.press("ArrowUp");
|
||||
await expect.poll(async () => (await preview.boundingBox())!.height).toBeGreaterThan(before + 80);
|
||||
const savedLayout = await page.evaluate(() => JSON.parse(localStorage.getItem("openidea.usages.popupSplit.v1")!));
|
||||
await page.screenshot({ path: test.info().outputPath("usages-preview-divider.png"), animations: "disabled" });
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/workbench/theme.ts";
|
||||
await (await import(/* @vite-ignore */ path)).setTheme("dark");
|
||||
});
|
||||
await page.screenshot({ path: test.info().outputPath("usages-preview-divider-dark.png"), animations: "disabled" });
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(popup).toHaveCount(0);
|
||||
await show();
|
||||
await expect(divider).toBeVisible();
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const groupHeight = await preview.evaluate((el) => el.closest("[data-group]")!.getBoundingClientRect().height);
|
||||
return ((await preview.boundingBox())!.height / (groupHeight - 1)) * 100;
|
||||
})
|
||||
.toBeCloseTo(savedLayout.preview, 0);
|
||||
await popup.evaluate((el) => Promise.all(el.getAnimations().map((animation) => animation.finished)));
|
||||
const reopened = (await divider.boundingBox())!;
|
||||
await page.mouse.move(reopened.x + reopened.width / 2, reopened.y + 0.5);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(reopened.x + reopened.width / 2, 1090, { steps: 5 });
|
||||
await page.mouse.up();
|
||||
const minimum = await preview
|
||||
.locator(".cm-content")
|
||||
.evaluate((el) => parseFloat(getComputedStyle(el).lineHeight) * 5);
|
||||
await expect.poll(async () => (await preview.boundingBox())!.height).toBeCloseTo(minimum, 0);
|
||||
});
|
||||
|
||||
test("Show Usages restores the initial window, then smart-sizes results and resets dimensions on preview changes", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.evaluate(async () => {
|
||||
localStorage.setItem("openidea.usages.popupSize.v1", JSON.stringify({ w: 900, h: 700 }));
|
||||
const usages = "/src/features/code-insight/usages.ts";
|
||||
const preview = "/src/features/code-insight/UsagesPopup.tsx";
|
||||
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
|
||||
const { setUsagesPopupPreview } = await import(/* @vite-ignore */ preview);
|
||||
setUsagesPopupPreview(true);
|
||||
useUsagesPopup.setState({
|
||||
open: true,
|
||||
anchor: { x: 400, y: 100 },
|
||||
symbol: "QueryWrapper",
|
||||
groups: [],
|
||||
loading: true,
|
||||
note: null,
|
||||
scope: null,
|
||||
});
|
||||
});
|
||||
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
|
||||
await expect(popup.getByText("Searching for usages…", { exact: true })).toBeVisible();
|
||||
await expect.poll(async () => (await popup.boundingBox())!.width).toBeCloseTo(900, 0);
|
||||
await expect.poll(async () => (await popup.boundingBox())!.height).toBeCloseTo(700, 0);
|
||||
await page.screenshot({ path: test.info().outputPath("usages-initial-restore.png"), animations: "disabled" });
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const usages = "/src/features/code-insight/usages.ts";
|
||||
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
|
||||
const path = "/dev/app/A.ts";
|
||||
useUsagesPopup.setState({
|
||||
groups: [{ path, usages: [0, 1].map((line) => ({ path, line, col: 0, endCol: 3, text: "run();" })) }],
|
||||
});
|
||||
});
|
||||
await expect.poll(async () => (await popup.boundingBox())!.width).toBeLessThan(900);
|
||||
await expect.poll(async () => (await popup.boundingBox())!.height).toBeCloseTo(700, 0);
|
||||
const shortWidth = (await popup.boundingBox())!.width;
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const usages = "/src/features/code-insight/usages.ts";
|
||||
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
|
||||
const path = "/dev/app/TransportPlanConfigurationServiceForOrderApprovalQueries.ts";
|
||||
useUsagesPopup.setState({
|
||||
groups: [
|
||||
{
|
||||
path,
|
||||
usages: [0, 1].map((line) => ({
|
||||
path,
|
||||
line,
|
||||
col: 0,
|
||||
endCol: 3,
|
||||
text: "run(configuration, currentUser, transportPlan, approvalStatus);".repeat(4),
|
||||
})),
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
await expect.poll(async () => (await popup.boundingBox())!.width).toBeGreaterThan(shortWidth);
|
||||
expect((await popup.boundingBox())!.width).toBeLessThan(900);
|
||||
await expect.poll(async () => (await popup.boundingBox())!.height).toBeCloseTo(700, 0);
|
||||
await page.screenshot({ path: test.info().outputPath("usages-smart-size.png"), animations: "disabled" });
|
||||
await popup.getByRole("button", { name: "Show Preview", exact: true }).click();
|
||||
await expect.poll(async () => (await popup.boundingBox())!.height).toBeCloseTo(160, 0);
|
||||
expect(await page.evaluate(() => localStorage.getItem("openidea.usages.popupSize.v1"))).toBeNull();
|
||||
await popup.getByRole("button", { name: "Show Preview", exact: true }).click();
|
||||
await expect.poll(async () => (await popup.boundingBox())!.height).toBeLessThan(300);
|
||||
await expect(popup.getByRole("region", { name: "Preview", exact: true }).locator(".cm-content")).toBeVisible();
|
||||
await page.evaluate(async () => {
|
||||
await document.fonts.ready;
|
||||
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
|
||||
});
|
||||
await popup.evaluate((el) => Promise.all(el.getAnimations().map((animation) => animation.finished)));
|
||||
const finalSize = (await popup.boundingBox())!;
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(popup).toHaveCount(0);
|
||||
const saved = await page.evaluate(() => JSON.parse(localStorage.getItem("openidea.usages.popupSize.v1")!));
|
||||
expect(saved.w).toBeCloseTo(finalSize.width, 0);
|
||||
expect(saved.h).toBeCloseTo(finalSize.height, 0);
|
||||
});
|
||||
|
||||
test("Show Usages sizes to arriving content and fits the screen without flipping away from the caret", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1600, height: 1200 });
|
||||
await page.evaluate(async () => {
|
||||
const usages = "/src/features/code-insight/usages.ts";
|
||||
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
|
||||
const path = "/dev/app/A.ts";
|
||||
useUsagesPopup.setState({
|
||||
open: true,
|
||||
anchor: { x: 40, y: 50 },
|
||||
symbol: "run",
|
||||
loading: true,
|
||||
groups: [{ path, usages: [{ path, line: 0, col: 0, endCol: 3, text: "run();" }] }],
|
||||
});
|
||||
});
|
||||
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
|
||||
await expect(popup).toBeVisible();
|
||||
await popup.evaluate((el) => Promise.all(el.getAnimations().map((a) => a.finished)));
|
||||
const short = (await popup.boundingBox())!;
|
||||
expect(short.width).toBeLessThan(680);
|
||||
expect(short.x).toBeCloseTo(40, 0);
|
||||
expect(short.y).toBeCloseTo(50, 0);
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const usages = "/src/features/code-insight/usages.ts";
|
||||
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
|
||||
const path = "/dev/app/TransportPlanConfigurationService.ts";
|
||||
useUsagesPopup.setState({
|
||||
loading: false,
|
||||
groups: [
|
||||
{
|
||||
path,
|
||||
usages: Array.from({ length: 40 }, (_, line) => ({
|
||||
path,
|
||||
line,
|
||||
col: 0,
|
||||
endCol: 3,
|
||||
text: "run(configuration, currentUser, transportPlan, approvalStatus);",
|
||||
})),
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
await expect.poll(async () => (await popup.boundingBox())!.width).toBeGreaterThan(short.width + 100);
|
||||
const list = popup.getByRole("listbox", { name: "Usages" });
|
||||
await expect.poll(async () => (await list.boundingBox())!.height).toBeCloseTo(30 * 24 + 8, 0);
|
||||
const wide = (await popup.boundingBox())!.width;
|
||||
await popup.getByTestId("usages-popup").focus();
|
||||
await page.keyboard.type("zzzz");
|
||||
await expect(popup.getByText("Nothing matches 'zzzz'", { exact: true })).toBeVisible();
|
||||
expect((await popup.boundingBox())!.width).toBeCloseTo(wide, 0);
|
||||
await page.keyboard.press("Escape");
|
||||
await popup.getByRole("button", { name: "Show Preview", exact: true }).click();
|
||||
const preview = popup.getByRole("region", { name: "Preview", exact: true });
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const groupHeight = await preview.evaluate((el) => el.closest("[data-group]")!.getBoundingClientRect().height);
|
||||
return (await preview.boundingBox())!.height / (groupHeight - 1);
|
||||
})
|
||||
.toBeCloseTo(0.4, 2);
|
||||
expect((await list.boundingBox())!.height).toBeLessThan(20 * 24 + 8);
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const usages = "/src/features/code-insight/usages.ts";
|
||||
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
|
||||
useUsagesPopup.setState({ open: true, anchor: { x: 1590, y: 1190 } });
|
||||
});
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const box = (await popup.boundingBox())!;
|
||||
return box.x + box.width;
|
||||
})
|
||||
.toBeCloseTo(1594, 0);
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const box = (await popup.boundingBox())!;
|
||||
return box.y + box.height;
|
||||
})
|
||||
.toBeLessThanOrEqual(1194);
|
||||
await page.setViewportSize({ width: 480, height: 360 });
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const box = (await popup.boundingBox())!;
|
||||
return Math.max(box.x + box.width - 474, box.y + box.height - 354);
|
||||
})
|
||||
.toBeLessThanOrEqual(1);
|
||||
await expect(popup.getByRole("button", { name: "Show Preview", exact: true })).toBeVisible();
|
||||
expect(await list.evaluate((element) => element.scrollHeight > element.clientHeight)).toBe(true);
|
||||
});
|
||||
|
||||
test("Show Usages drags by the title bar, keeps its controls usable and stays inside the viewport", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
@@ -38,7 +414,7 @@ test("Show Usages drags by the title bar, keeps its controls usable and stays in
|
||||
await page.mouse.up();
|
||||
await expect.poll(async () => (await popup.boundingBox())!.x).toBeCloseTo(before.x + 120, 0);
|
||||
await expect.poll(async () => (await popup.boundingBox())!.y).toBeCloseTo(before.y + 100, 0);
|
||||
const moved = (await popup.boundingBox())!;
|
||||
let moved = (await popup.boundingBox())!;
|
||||
expect(moved.width).toBeCloseTo(before.width, 0);
|
||||
expect(moved.height).toBeCloseTo(before.height, 0);
|
||||
await page.screenshot({ path: test.info().outputPath("usages-after-drag.png") });
|
||||
@@ -48,11 +424,17 @@ test("Show Usages drags by the title bar, keeps its controls usable and stays in
|
||||
await page.keyboard.press("Escape");
|
||||
await popup.getByRole("button", { name: "Show Preview", exact: true }).click();
|
||||
await expect(popup.getByRole("region", { name: "Preview", exact: true })).toBeVisible();
|
||||
await expect.poll(async () => (await popup.boundingBox())!.x).toBeCloseTo(moved.x, 0);
|
||||
await expect.poll(async () => (await popup.boundingBox())!.y).toBeCloseTo(moved.y, 0);
|
||||
await expect(popup.getByRole("region", { name: "Preview", exact: true }).locator(".cm-content")).toBeVisible();
|
||||
await page.evaluate(async () => {
|
||||
await document.fonts.ready;
|
||||
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
|
||||
});
|
||||
await expect.poll(async () => (await popup.boundingBox())!.x).toBeCloseTo(before.x, 0);
|
||||
await expect.poll(async () => (await popup.boundingBox())!.y).toBeCloseTo(before.y, 0);
|
||||
moved = (await popup.boundingBox())!;
|
||||
|
||||
const resizeBefore = (await popup.boundingBox())!;
|
||||
const corner = (await popup.getByRole("separator", { name: "Resize" }).boundingBox())!;
|
||||
const corner = (await popup.getByRole("separator", { name: "Resize", exact: true }).boundingBox())!;
|
||||
await page.mouse.move(corner.x + 4, corner.y + 4);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(corner.x + 84, corner.y + 64, { steps: 5 });
|
||||
@@ -156,6 +538,7 @@ test("Show Usages distinguishes same-named files without losing the line or snip
|
||||
|
||||
// Once there is enough room, both directory labels are shown in full again.
|
||||
await page.setViewportSize({ width: 1400, height: 900 });
|
||||
await resizePopupWidth(page, 900);
|
||||
for (const [row, directory] of [
|
||||
[billing, "billing"],
|
||||
[checkout, "checkout"],
|
||||
@@ -193,6 +576,7 @@ test("Show Usages fits the filename column to its content and gives added width
|
||||
await page.evaluate(async () => {
|
||||
await document.fonts.ready;
|
||||
});
|
||||
await resizePopupWidth(page, 1200);
|
||||
const file = popup.getByTitle("/dev/app/src/LmsTransportPlanController.java", { exact: true });
|
||||
const before = (await file.boundingBox())!.width;
|
||||
const code = popup.getByTestId("usage-row").first().locator(":scope > span:last-child");
|
||||
@@ -231,27 +615,32 @@ test("Show Usages caps exceptionally long filenames to preserve code in wide and
|
||||
}, path);
|
||||
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
|
||||
const row = popup.getByTestId("usage-row");
|
||||
await resizePopupWidth(page, 1000);
|
||||
const file = row.getByTitle(path, { exact: true });
|
||||
const label = row.getByText(name, { exact: true });
|
||||
const code = row.locator(":scope > span:last-child");
|
||||
await expect(popup).toBeVisible();
|
||||
await expect
|
||||
.poll(async () => (await file.boundingBox())!.width - (await row.boundingBox())!.width * 0.2)
|
||||
.toBeCloseTo(0, 0);
|
||||
.poll(async () => (await file.boundingBox())!.width / (await popup.boundingBox())!.width)
|
||||
.toBeLessThanOrEqual(0.25);
|
||||
expect((await file.boundingBox())!.width).toBeGreaterThan(200);
|
||||
expect(await label.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeGreaterThan(0);
|
||||
expect((await code.boundingBox())!.width).toBeGreaterThan(500);
|
||||
expect((await code.boundingBox())!.width).toBeGreaterThan(300);
|
||||
await page.setViewportSize({ width: 480, height: 620 });
|
||||
await expect.poll(async () => (await popup.boundingBox())!.width).toBeLessThanOrEqual(468);
|
||||
await expect
|
||||
.poll(async () => (await file.boundingBox())!.width / (await popup.boundingBox())!.width)
|
||||
.toBeLessThanOrEqual(0.25);
|
||||
expect(await label.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeGreaterThan(0);
|
||||
expect((await code.boundingBox())!.width).toBeGreaterThanOrEqual(100);
|
||||
await expect(row.getByText("124", { exact: true })).toBeVisible();
|
||||
await expect(row.locator("mark")).toHaveText("run");
|
||||
});
|
||||
|
||||
test("Show Usages resizes from its corner, the list fills it, and it reopens at that size", async ({
|
||||
test("Show Usages stops smart sizing after a manual resize and resumes it when reopened", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1200, height: 800 });
|
||||
await page.setViewportSize({ width: 1200, height: 1200 });
|
||||
const show = () =>
|
||||
page.evaluate(async () => {
|
||||
const usages = "/src/features/code-insight/usages.ts";
|
||||
@@ -272,6 +661,10 @@ test("Show Usages resizes from its corner, the list fills it, and it reopens at
|
||||
await show();
|
||||
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
|
||||
const list = popup.getByRole("listbox", { name: "Usages" });
|
||||
await popup.evaluate(async (el) => {
|
||||
await document.fonts.ready;
|
||||
await Promise.all(el.getAnimations().map((animation) => animation.finished));
|
||||
});
|
||||
const before = (await popup.boundingBox())!;
|
||||
const listBefore = (await list.boundingBox())!;
|
||||
const corner = (await popup.getByRole("separator", { name: "Resize" }).boundingBox())!;
|
||||
@@ -286,10 +679,74 @@ test("Show Usages resizes from its corner, the list fills it, and it reopens at
|
||||
expect((await list.boundingBox())!.height).toBeGreaterThan(listBefore.height + 100);
|
||||
await page.screenshot({ path: test.info().outputPath("usages-resized.png") });
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const usages = "/src/features/code-insight/usages.ts";
|
||||
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
|
||||
const path = "/dev/app/src/TransportPlanConfigurationService.ts";
|
||||
useUsagesPopup.setState({
|
||||
groups: [
|
||||
{
|
||||
path,
|
||||
usages: Array.from({ length: 80 }, (_, line) => ({
|
||||
path,
|
||||
line,
|
||||
col: 0,
|
||||
endCol: 3,
|
||||
text: "run(configuration, currentUser, transportPlan, approvalStatus);",
|
||||
})),
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
await expect(popup.getByTestId("usages-popup")).toHaveAttribute("data-total", "80");
|
||||
expect((await popup.boundingBox())!.width).toBeCloseTo(after.width, 0);
|
||||
expect((await popup.boundingBox())!.height).toBeCloseTo(after.height, 0);
|
||||
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(popup).toHaveCount(0);
|
||||
await show();
|
||||
await popup.evaluate((el) => Promise.all(el.getAnimations().map((animation) => animation.finished)));
|
||||
const reopened = (await popup.boundingBox())!;
|
||||
expect(Math.abs(reopened.width - after.width)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(reopened.height - after.height)).toBeLessThanOrEqual(1);
|
||||
expect(reopened.width).toBeCloseTo(before.width, 0);
|
||||
expect(reopened.height).toBeCloseTo(before.height, 0);
|
||||
await popup.getByRole("button", { name: "Show Preview", exact: true }).click();
|
||||
await expect(popup.getByRole("region", { name: "Preview", exact: true })).toBeVisible();
|
||||
await expect.poll(async () => (await popup.boundingBox())!.height).toBeLessThan(before.height);
|
||||
expect(await page.evaluate(() => localStorage.getItem("openidea.usages.popupSize.v1"))).toBeNull();
|
||||
await popup.getByRole("button", { name: "Show Preview", exact: true }).click();
|
||||
await expect.poll(async () => (await popup.boundingBox())!.height).toBeCloseTo(before.height, 0);
|
||||
});
|
||||
|
||||
test("Show Usages preserves minimum dimensions for saved sizes and manual resizing while fitting the viewport", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.evaluate(async () => {
|
||||
localStorage.setItem("openidea.usages.popupSize.v1", JSON.stringify({ w: 250, h: 80 }));
|
||||
const usages = "/src/features/code-insight/usages.ts";
|
||||
const { useUsagesPopup } = await import(/* @vite-ignore */ usages);
|
||||
const path = "/dev/app/A.ts";
|
||||
useUsagesPopup.setState({
|
||||
open: true,
|
||||
anchor: { x: 40, y: 50 },
|
||||
symbol: "run",
|
||||
groups: [{ path, usages: [0, 1].map((line) => ({ path, line, col: 0, endCol: 3, text: "run();" })) }],
|
||||
});
|
||||
});
|
||||
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
|
||||
await expect(popup).toBeVisible();
|
||||
await expect.poll(async () => (await popup.boundingBox())!.width).toBeCloseTo(360, 0);
|
||||
expect((await popup.boundingBox())!.height).toBeCloseTo(160, 0);
|
||||
await expect(popup).not.toHaveAttribute("data-resized");
|
||||
await popup.evaluate((el) => Promise.all(el.getAnimations().map((animation) => animation.finished)));
|
||||
const corner = (await popup.getByRole("separator", { name: "Resize" }).boundingBox())!;
|
||||
await page.mouse.move(corner.x + 4, corner.y + 4);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(corner.x - 200, corner.y - 100, { steps: 5 });
|
||||
await page.mouse.up();
|
||||
await expect(popup).toHaveAttribute("data-resized");
|
||||
expect((await popup.boundingBox())!.width).toBeCloseTo(360, 0);
|
||||
expect((await popup.boundingBox())!.height).toBeCloseTo(160, 0);
|
||||
await page.setViewportSize({ width: 320, height: 140 });
|
||||
await expect.poll(async () => (await popup.boundingBox())!.width).toBeLessThanOrEqual(308);
|
||||
await expect.poll(async () => (await popup.boundingBox())!.height).toBeLessThanOrEqual(128);
|
||||
});
|
||||
@@ -1,9 +1,12 @@
|
||||
.popup {
|
||||
width: min(680px, 90vw);
|
||||
width: var(--usages-width, max-content);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
.popup:not([data-resized]) {
|
||||
height: var(--usages-popup-height);
|
||||
}
|
||||
.header {
|
||||
cursor: move;
|
||||
touch-action: none;
|
||||
@@ -70,10 +73,11 @@
|
||||
text-decoration: underline;
|
||||
}
|
||||
.body {
|
||||
flex: 1 1 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: var(--usages-height);
|
||||
min-height: var(--usages-min-height);
|
||||
min-height: 0;
|
||||
padding: 2px 0;
|
||||
box-sizing: content-box;
|
||||
}
|
||||
@@ -84,15 +88,18 @@
|
||||
.popup[data-resized] .body {
|
||||
flex: 1 1 0;
|
||||
height: auto;
|
||||
min-height: var(--usages-min-height);
|
||||
min-height: 0;
|
||||
}
|
||||
.body > * {
|
||||
flex: 1;
|
||||
}
|
||||
.row {
|
||||
display: grid;
|
||||
/* The longest filename, up to 176px (38% when narrow) or a fifth of a wider popup. */
|
||||
grid-template-columns: minmax(0, min(var(--usages-file-width, 176px), max(min(38%, 176px), 20%))) 5ch minmax(8em, 1fr);
|
||||
/* Short filenames fit their content; longer names use at most a quarter of the row. */
|
||||
grid-template-columns: minmax(
|
||||
0,
|
||||
min(var(--usages-file-width, 176px), 25%, max(0px, calc(100% - 5ch - 8em - 2 * var(--space-2))))
|
||||
) 5ch minmax(8em, 1fr);
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
@@ -121,6 +128,10 @@
|
||||
padding-left: calc(16px + var(--space-1));
|
||||
white-space: nowrap;
|
||||
}
|
||||
.codeMeasure {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-code);
|
||||
}
|
||||
.icon {
|
||||
flex: none;
|
||||
color: var(--fg-icon);
|
||||
@@ -153,6 +164,7 @@
|
||||
}
|
||||
|
||||
.focus {
|
||||
flex: 1 1 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
@@ -177,11 +189,15 @@
|
||||
color: var(--fg-faint);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.split {
|
||||
flex: 1 1 0;
|
||||
}
|
||||
.previewDivider {
|
||||
background: var(--border-popup);
|
||||
}
|
||||
.preview {
|
||||
flex: 0 1 auto;
|
||||
height: min(164px, 32vh);
|
||||
min-height: min(64px, 18vh);
|
||||
border-top: 1px solid var(--border-popup);
|
||||
flex: 1 1 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.previewEditor {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
|
||||
import { create } from "zustand";
|
||||
import type { PanelImperativeHandle } from "react-resizable-panels";
|
||||
import clsx from "clsx";
|
||||
import { EditorState, StateEffect, StateField } from "@codemirror/state";
|
||||
import { Decoration, EditorView } from "@codemirror/view";
|
||||
@@ -12,7 +13,19 @@ import { codePreviewExtensions } from "@/editor/api";
|
||||
import { disambiguateTitles } from "@/editor/core/model/tabTitles";
|
||||
import { basename } from "@/platform/project";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { Icon, IconButton, List, Popup, Select, Spinner, fileIconName, listNavigate } from "@/ui";
|
||||
import {
|
||||
Icon,
|
||||
IconButton,
|
||||
List,
|
||||
Popup,
|
||||
Select,
|
||||
Spinner,
|
||||
SplitGroup,
|
||||
SplitPanel,
|
||||
SplitHandle,
|
||||
fileIconName,
|
||||
listNavigate,
|
||||
} from "@/ui";
|
||||
import { useRowHeight } from "@/ui/density";
|
||||
import { openLocation, readFileLines } from "./ipc";
|
||||
import {
|
||||
@@ -63,7 +76,11 @@ const MIN_HEIGHT = 160;
|
||||
function loadUsagesPopupSize(): { w: number; h: number } | null {
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem(SIZE_KEY) ?? "null") as { w?: unknown; h?: unknown } | null;
|
||||
return typeof saved?.w === "number" && typeof saved.h === "number" && Number.isFinite(saved.w + saved.h)
|
||||
return typeof saved?.w === "number" &&
|
||||
typeof saved.h === "number" &&
|
||||
Number.isFinite(saved.w + saved.h) &&
|
||||
saved.w > 0 &&
|
||||
saved.h > 0
|
||||
? { w: Math.max(MIN_WIDTH, saved.w), h: Math.max(MIN_HEIGHT, saved.h) }
|
||||
: null;
|
||||
} catch {
|
||||
@@ -122,33 +139,206 @@ function UsagesPopupInner() {
|
||||
);
|
||||
const content = useRef<HTMLDivElement>(null);
|
||||
const fileSizer = useRef<HTMLDivElement>(null);
|
||||
// Measure all filenames: virtualized rows and speed search must keep the columns aligned.
|
||||
useLayoutEffect(() => {
|
||||
const host = content.current;
|
||||
const sizer = fileSizer.current;
|
||||
if (!host || !sizer) return;
|
||||
const measure = () => {
|
||||
host.style.setProperty("--usages-file-width", `${Math.ceil(sizer.getBoundingClientRect().width)}px`);
|
||||
};
|
||||
measure();
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(sizer);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
host.style.removeProperty("--usages-file-width");
|
||||
};
|
||||
}, [filePaths, directories]);
|
||||
const codeSizer = useRef<HTMLSpanElement>(null);
|
||||
const header = useRef<HTMLDivElement>(null);
|
||||
const actions = useRef<HTMLDivElement>(null);
|
||||
const body = useRef<HTMLDivElement>(null);
|
||||
const previewPanel = useRef<PanelImperativeHandle | null>(null);
|
||||
const [previewLineHeight, setPreviewLineHeight] = useState(0);
|
||||
const resizingPreviewHeight = useRef<number | null>(null);
|
||||
const previewResizeFrame = useRef(0);
|
||||
const previewResizeEndFrame = useRef(0);
|
||||
useEffect(
|
||||
() => () => {
|
||||
cancelAnimationFrame(previewResizeFrame.current);
|
||||
cancelAnimationFrame(previewResizeEndFrame.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
const [previousFocus] = useState(() => document.activeElement as HTMLElement | null);
|
||||
const [savedSize, setSavedSize] = useState(loadUsagesPopupSize);
|
||||
const smartSizing = useRef(!loading || all.length > 0);
|
||||
const popupElement = useRef<HTMLElement | null>(null);
|
||||
const lastSize = useRef<{ w: number; h: number } | null>(null);
|
||||
const [manuallyResized, setManuallyResized] = useState(false);
|
||||
const preferredWidth = useRef(0);
|
||||
const columnWidths = useRef([0, 0, 0]);
|
||||
const [size, setSize] = useState<{ w: number; h: number; preview: number } | null>(null);
|
||||
const [filter, setFilter] = useState("");
|
||||
const accessOptions = useUsageAccessOptions();
|
||||
const items = useMemo(
|
||||
() => filterUsages(filterUsageAccess(all, accessOptions), filter),
|
||||
[all, filter, accessOptions],
|
||||
);
|
||||
const rowCount = Math.max(1, Math.min(preview ? 20 : 30, items.length));
|
||||
useEffect(
|
||||
() => () => {
|
||||
const active = document.activeElement;
|
||||
if (
|
||||
previousFocus?.isConnected &&
|
||||
(!active || active === document.body || !active.isConnected || popupElement.current?.contains(active))
|
||||
) {
|
||||
previousFocus.focus({ preventScroll: true });
|
||||
}
|
||||
},
|
||||
[previousFocus],
|
||||
);
|
||||
useLayoutEffect(
|
||||
() => () => {
|
||||
const bounds = popupElement.current?.getBoundingClientRect();
|
||||
const finalSize = bounds?.width && bounds.height ? { w: bounds.width, h: bounds.height } : lastSize.current;
|
||||
if (finalSize) saveUsagesPopupSize(finalSize);
|
||||
},
|
||||
[],
|
||||
);
|
||||
// Measure all filenames: virtualized rows and speed search must keep the columns aligned.
|
||||
useLayoutEffect(() => {
|
||||
const host = content.current;
|
||||
const sizer = fileSizer.current;
|
||||
if (!host || !sizer) return;
|
||||
const context = document.createElement("canvas").getContext("2d");
|
||||
const measure = () => {
|
||||
const fileWidth = Math.max(
|
||||
columnWidths.current[0]!,
|
||||
Math.min(500, Math.ceil(sizer.getBoundingClientRect().width)),
|
||||
);
|
||||
columnWidths.current[0] = fileWidth;
|
||||
host.style.setProperty("--usages-file-width", `${fileWidth}px`);
|
||||
const previewElement = host.querySelector<HTMLElement>("[data-usages-preview]");
|
||||
const previewHeight = preview ? 5 * (previewLineHeight || rowHeight) : 0;
|
||||
if (manuallyResized) {
|
||||
setSize((previous) =>
|
||||
previous && previous.preview !== previewHeight ? { ...previous, preview: previewHeight } : previous,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!context || !codeSizer.current) return;
|
||||
const font = getComputedStyle(codeSizer.current);
|
||||
context.font = `${font.fontWeight} ${font.fontSize} ${font.fontFamily}`;
|
||||
let codeWidth = 0;
|
||||
// IDEA caps each measured column at 500px and never shrinks a window as results arrive.
|
||||
for (const usage of all) {
|
||||
codeWidth = Math.min(500, Math.max(codeWidth, context.measureText(usage.text.trim()).width));
|
||||
if (codeWidth === 500) break;
|
||||
}
|
||||
const caption = header.current?.firstElementChild;
|
||||
const headerStyle = header.current && getComputedStyle(header.current);
|
||||
const actionsStyle = actions.current && getComputedStyle(actions.current);
|
||||
const titleWidth = Array.from(caption?.children ?? []).reduce((sum, el) => sum + el.scrollWidth, 4);
|
||||
const controls = Array.from(actions.current?.children ?? []);
|
||||
const toolbarWidth =
|
||||
controls.reduce((sum, el) => sum + Math.max(el.scrollWidth, el.getBoundingClientRect().width), 0) +
|
||||
Math.max(0, controls.length - 1) * (parseFloat(actionsStyle?.columnGap ?? "0") || 0);
|
||||
const popup = host.parentElement!;
|
||||
popupElement.current = popup;
|
||||
const popupStyle = getComputedStyle(popup);
|
||||
const border = parseFloat(popupStyle.borderLeftWidth) + parseFloat(popupStyle.borderRightWidth) || 0;
|
||||
const headerWidth =
|
||||
titleWidth +
|
||||
toolbarWidth +
|
||||
border +
|
||||
(parseFloat(headerStyle?.paddingLeft ?? "0") || 0) +
|
||||
(parseFloat(headerStyle?.paddingRight ?? "0") || 0) +
|
||||
(parseFloat(headerStyle?.columnGap ?? "0") || 0);
|
||||
const row = host.querySelector<HTMLElement>('[data-testid="usage-row"]');
|
||||
const option = row?.parentElement;
|
||||
const rowStyle = row && getComputedStyle(row);
|
||||
const optionStyle = option && getComputedStyle(option);
|
||||
const inset = option ? option.parentElement!.clientWidth - option.getBoundingClientRect().width : 0;
|
||||
const codeMinWidth = 8 * (parseFloat(rowStyle?.fontSize ?? "0") || 0);
|
||||
const measured = [
|
||||
fileWidth,
|
||||
row?.children[1]?.getBoundingClientRect().width ?? 0,
|
||||
Math.max(codeWidth, codeMinWidth),
|
||||
];
|
||||
columnWidths.current = measured.map((value, index) =>
|
||||
Math.max(columnWidths.current[index]!, Math.min(500, value)),
|
||||
);
|
||||
const remainingColumnsWidth =
|
||||
columnWidths.current[1]! + columnWidths.current[2]! + 2 * (parseFloat(rowStyle?.columnGap ?? "0") || 0);
|
||||
// At the 25% cap, the other columns and gaps take three times the filename width.
|
||||
const columnsWidth =
|
||||
Math.min(fileWidth, remainingColumnsWidth / 3) +
|
||||
remainingColumnsWidth +
|
||||
(parseFloat(optionStyle?.paddingLeft ?? "0") || 0) +
|
||||
(parseFloat(optionStyle?.paddingRight ?? "0") || 0) +
|
||||
inset +
|
||||
border;
|
||||
preferredWidth.current = Math.max(MIN_WIDTH, preferredWidth.current, headerWidth, columnsWidth);
|
||||
if (!loading || all.length > 0) smartSizing.current = true;
|
||||
// AbstractPopup restores both dimensions first; ShowUsagesAction sizes subsequent results.
|
||||
const restoreInitial = !smartSizing.current && savedSize !== null;
|
||||
const w = Math.min(restoreInitial ? savedSize.w : preferredWidth.current, window.innerWidth - 12);
|
||||
// Reflow the existing header before calculating the height of its wrapped controls.
|
||||
popup.style.setProperty("--usages-width", `${Math.max(1, Math.ceil(w))}px`);
|
||||
const bodyStyle = body.current && getComputedStyle(body.current);
|
||||
const chrome =
|
||||
host.getBoundingClientRect().height -
|
||||
(body.current?.getBoundingClientRect().height ?? 0) -
|
||||
(previewElement?.getBoundingClientRect().height ?? 0) +
|
||||
(parseFloat(bodyStyle?.paddingTop ?? "0") || 0) +
|
||||
(parseFloat(bodyStyle?.paddingBottom ?? "0") || 0) +
|
||||
(parseFloat(popupStyle.borderTopWidth) || 0) +
|
||||
(parseFloat(popupStyle.borderBottomWidth) || 0);
|
||||
const available = Math.max(1, window.innerHeight - 12);
|
||||
const padding =
|
||||
(parseFloat(bodyStyle?.paddingTop ?? "0") || 0) + (parseFloat(bodyStyle?.paddingBottom ?? "0") || 0);
|
||||
const fixedHeight = chrome - padding;
|
||||
// getPreferredBounds leaves half a row when scrolling, or 4px when all rows fit.
|
||||
const extra = items.length > rowCount ? rowHeight / 2 : padding;
|
||||
const tableLimit = available - previewHeight;
|
||||
let tableHeight = rowCount * rowHeight + extra;
|
||||
if (tableHeight + fixedHeight > tableLimit) {
|
||||
tableHeight =
|
||||
Math.max(1, Math.floor((tableLimit - fixedHeight - rowHeight / 2) / rowHeight)) * rowHeight + rowHeight / 2;
|
||||
}
|
||||
let h = Math.max(MIN_HEIGHT, fixedHeight + tableHeight + previewHeight);
|
||||
if (preview && savedSize) h = Math.max(h, savedSize.h);
|
||||
if (restoreInitial) h = savedSize.h;
|
||||
const next = { w: Math.max(1, Math.ceil(w)), h: Math.min(available, h), preview: previewHeight };
|
||||
lastSize.current = next;
|
||||
setSize((previous) =>
|
||||
previous?.w === next.w && previous.h === next.h && previous.preview === next.preview ? previous : next,
|
||||
);
|
||||
};
|
||||
measure();
|
||||
let frame = 0;
|
||||
const observer = new ResizeObserver(() => {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(measure);
|
||||
});
|
||||
observer.observe(sizer);
|
||||
if (codeSizer.current) observer.observe(codeSizer.current);
|
||||
if (header.current) observer.observe(header.current);
|
||||
window.addEventListener("resize", measure);
|
||||
document.fonts?.addEventListener("loadingdone", measure);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
cancelAnimationFrame(frame);
|
||||
window.removeEventListener("resize", measure);
|
||||
document.fonts?.removeEventListener("loadingdone", measure);
|
||||
host.style.removeProperty("--usages-file-width");
|
||||
};
|
||||
}, [
|
||||
all,
|
||||
filePaths,
|
||||
directories,
|
||||
symbol,
|
||||
scope,
|
||||
preview,
|
||||
previewLineHeight,
|
||||
rowCount,
|
||||
items.length,
|
||||
rowHeight,
|
||||
savedSize,
|
||||
manuallyResized,
|
||||
loading,
|
||||
filter,
|
||||
note,
|
||||
]);
|
||||
const [active, setActive] = useState(0);
|
||||
const [initialSize] = useState(loadUsagesPopupSize);
|
||||
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();
|
||||
@@ -171,7 +361,7 @@ function UsagesPopupInner() {
|
||||
};
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key !== "Escape" && e.target instanceof Element && e.target.closest("button")) return;
|
||||
if (e.key !== "Escape" && e.target instanceof Element && e.target.closest('button, [role="separator"]')) return;
|
||||
const next = listNavigate(e.key, { items, active: current, wrap: true, pageSize: 10 });
|
||||
if (next !== null) {
|
||||
e.preventDefault();
|
||||
@@ -202,17 +392,50 @@ function UsagesPopupInner() {
|
||||
const keys = shortcutLabel("find.usages");
|
||||
return (
|
||||
<Popup
|
||||
key={String(preview)}
|
||||
open
|
||||
anchor={anchor}
|
||||
offset={0}
|
||||
fitToScreen
|
||||
restoreFocus={false}
|
||||
onClose={close}
|
||||
aria-label="Usages"
|
||||
className={styles.popup}
|
||||
style={
|
||||
size
|
||||
? ({
|
||||
"--usages-width": `${size.w}px`,
|
||||
"--usages-popup-height": `${size.h}px`,
|
||||
} as CSSProperties)
|
||||
: undefined
|
||||
}
|
||||
draggable
|
||||
resizable="both"
|
||||
minWidth={MIN_WIDTH}
|
||||
minHeight={MIN_HEIGHT}
|
||||
initialSize={initialSize}
|
||||
onResized={saveUsagesPopupSize}
|
||||
onResizeStart={() => {
|
||||
cancelAnimationFrame(previewResizeEndFrame.current);
|
||||
resizingPreviewHeight.current =
|
||||
content.current?.querySelector("[data-usages-preview]")?.getBoundingClientRect().height ?? null;
|
||||
setManuallyResized(true);
|
||||
}}
|
||||
onResized={(next) => {
|
||||
cancelAnimationFrame(previewResizeFrame.current);
|
||||
const previewHeight = resizingPreviewHeight.current;
|
||||
if (previewHeight !== null) {
|
||||
// Let the splitter measure the final group size before restoring pixel height.
|
||||
previewResizeEndFrame.current = requestAnimationFrame(() => {
|
||||
previewResizeEndFrame.current = requestAnimationFrame(() => {
|
||||
cancelAnimationFrame(previewResizeFrame.current);
|
||||
previewPanel.current?.resize(previewHeight);
|
||||
resizingPreviewHeight.current = null;
|
||||
});
|
||||
});
|
||||
}
|
||||
lastSize.current = next;
|
||||
setManuallyResized(true);
|
||||
saveUsagesPopupSize(next);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
ref={content}
|
||||
@@ -225,7 +448,7 @@ function UsagesPopupInner() {
|
||||
data-scope={scope ?? undefined}
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
<div className={styles.header} data-popup-drag>
|
||||
<div ref={header} className={styles.header} data-popup-drag>
|
||||
<span className={styles.title}>
|
||||
<span className={styles.titleLabel}>{symbol ? tx`Usages of ${symbol}` : tx("Usages")}</span>{" "}
|
||||
{(total > 0 || !loading) && (
|
||||
@@ -234,7 +457,7 @@ function UsagesPopupInner() {
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<div className={styles.actions}>
|
||||
<div ref={actions} className={styles.actions}>
|
||||
<UsageAccessFilter items={all} />
|
||||
{scope && (
|
||||
<Select<UsageScope>
|
||||
@@ -265,7 +488,23 @@ function UsagesPopupInner() {
|
||||
title="Show Preview"
|
||||
pressed={preview}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => setUsagesPopupPreview(!preview)}
|
||||
onClick={() => {
|
||||
cancelAnimationFrame(previewResizeFrame.current);
|
||||
cancelAnimationFrame(previewResizeEndFrame.current);
|
||||
resizingPreviewHeight.current = null;
|
||||
try {
|
||||
localStorage.removeItem(SIZE_KEY);
|
||||
} catch {
|
||||
// Clearing the in-memory size still resets this popup.
|
||||
}
|
||||
setSavedSize(null);
|
||||
setSize(null);
|
||||
setManuallyResized(false);
|
||||
preferredWidth.current = 0;
|
||||
columnWidths.current = [0, 0, 0];
|
||||
smartSizing.current = true;
|
||||
setUsagesPopupPreview(!preview);
|
||||
}}
|
||||
/>
|
||||
<button type="button" className={styles.link} onClick={openInFindWindow}>
|
||||
{tx("Open in Find Window")}
|
||||
@@ -286,52 +525,83 @@ function UsagesPopupInner() {
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div
|
||||
className={styles.body}
|
||||
style={
|
||||
{
|
||||
"--usages-height": `${rowCount * rowHeight}px`,
|
||||
"--usages-min-height": `min(${Math.min(rowCount, 3) * rowHeight}px, 18vh)`,
|
||||
} as CSSProperties
|
||||
}
|
||||
<span ref={codeSizer} className={clsx(styles.fileSizer, styles.codeMeasure)} aria-hidden="true">
|
||||
M
|
||||
</span>
|
||||
<SplitGroup
|
||||
orientation="vertical"
|
||||
className={styles.split}
|
||||
storageKey={preview ? "openidea.usages.popupSplit.v1" : undefined}
|
||||
defaultLayout={preview ? { usages: 60, preview: 40 } : { usages: 100 }}
|
||||
onLayoutChange={() => {
|
||||
if (resizingPreviewHeight.current === null) return;
|
||||
cancelAnimationFrame(previewResizeFrame.current);
|
||||
previewResizeFrame.current = requestAnimationFrame(() => {
|
||||
if (resizingPreviewHeight.current !== null) previewPanel.current?.resize(resizingPreviewHeight.current);
|
||||
});
|
||||
}}
|
||||
>
|
||||
<List
|
||||
items={items}
|
||||
getKey={(u) =>
|
||||
`${u.path}:${u.line}:${u.col}:${u.sourceLocation?.range.end.line ?? u.line}:${u.sourceLocation?.range.end.col ?? u.endCol}`
|
||||
}
|
||||
activeIndex={current}
|
||||
onActiveChange={setActive}
|
||||
focusable={false}
|
||||
hoverSelects
|
||||
rowHeight={rowHeight}
|
||||
aria-label="Usages"
|
||||
onActivate={pick}
|
||||
empty={
|
||||
<div className={styles.empty}>
|
||||
{filter
|
||||
? tx`Nothing matches '${filter}'`
|
||||
: total
|
||||
? tx("No usages match the access filters")
|
||||
: loading
|
||||
? tx("Searching for usages…")
|
||||
: tx("No usages found")}
|
||||
</div>
|
||||
}
|
||||
renderItem={(u) => (
|
||||
<div className={styles.row} data-testid="usage-row" data-path={u.path} data-line={u.line}>
|
||||
<span className={styles.file} title={u.path}>
|
||||
<Icon name={fileIconName(basename(u.path), u.path)} size={16} className={styles.icon} />
|
||||
<span className={styles.fileName}>{basename(u.path)}</span>
|
||||
{directories.has(u.path) && <span className={styles.directory}>{directories.get(u.path)}</span>}
|
||||
</span>
|
||||
<span className={styles.line}>{u.line + 1}</span>
|
||||
<UsagePreview usage={u} />
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
{preview && <UsageCodePreview usage={items[current] ?? null} />}
|
||||
<SplitPanel id="usages" minSize={Math.min(rowHeight, 24)}>
|
||||
<div
|
||||
ref={body}
|
||||
className={styles.body}
|
||||
style={
|
||||
{
|
||||
"--usages-height": `${rowCount * rowHeight}px`,
|
||||
} as CSSProperties
|
||||
}
|
||||
>
|
||||
<List
|
||||
items={items}
|
||||
getKey={(u) =>
|
||||
`${u.path}:${u.line}:${u.col}:${u.sourceLocation?.range.end.line ?? u.line}:${u.sourceLocation?.range.end.col ?? u.endCol}`
|
||||
}
|
||||
activeIndex={current}
|
||||
onActiveChange={setActive}
|
||||
focusable={false}
|
||||
hoverSelects
|
||||
rowHeight={rowHeight}
|
||||
aria-label="Usages"
|
||||
onActivate={pick}
|
||||
empty={
|
||||
<div className={styles.empty}>
|
||||
{filter
|
||||
? tx`Nothing matches '${filter}'`
|
||||
: total
|
||||
? tx("No usages match the access filters")
|
||||
: loading
|
||||
? tx("Searching for usages…")
|
||||
: tx("No usages found")}
|
||||
</div>
|
||||
}
|
||||
renderItem={(u) => (
|
||||
<div className={styles.row} data-testid="usage-row" data-path={u.path} data-line={u.line}>
|
||||
<span className={styles.file} title={u.path}>
|
||||
<Icon name={fileIconName(basename(u.path), u.path)} size={16} className={styles.icon} />
|
||||
<span className={styles.fileName}>{basename(u.path)}</span>
|
||||
{directories.has(u.path) && <span className={styles.directory}>{directories.get(u.path)}</span>}
|
||||
</span>
|
||||
<span className={styles.line}>{u.line + 1}</span>
|
||||
<UsagePreview usage={u} />
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</SplitPanel>
|
||||
{preview && (
|
||||
<>
|
||||
<SplitHandle className={styles.previewDivider} aria-label={tx("Resize usages preview")} />
|
||||
<SplitPanel
|
||||
id="preview"
|
||||
panelRef={previewPanel}
|
||||
minSize={size?.preview ?? 5 * rowHeight}
|
||||
groupResizeBehavior="preserve-pixel-size"
|
||||
>
|
||||
<UsageCodePreview usage={items[current] ?? null} onLineHeight={setPreviewLineHeight} />
|
||||
</SplitPanel>
|
||||
</>
|
||||
)}
|
||||
</SplitGroup>
|
||||
</div>
|
||||
</Popup>
|
||||
);
|
||||
@@ -357,20 +627,31 @@ const marks = StateField.define({
|
||||
});
|
||||
|
||||
/** Read-only view of the usage's file around its line, the usage marked. */
|
||||
function UsageCodePreview({ usage }: { usage: Usage | null }) {
|
||||
function UsageCodePreview({ usage, onLineHeight }: { usage: Usage | null; onLineHeight: (height: number) => void }) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const view = useRef<EditorView | null>(null);
|
||||
const [loaded, setLoaded] = useState<string | null>(null);
|
||||
const lineHeightReporter = useMemo(
|
||||
() =>
|
||||
EditorView.updateListener.of((update) => {
|
||||
if (update.geometryChanged) onLineHeight(update.view.defaultLineHeight);
|
||||
}),
|
||||
[onLineHeight],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!host.current) return;
|
||||
const v = new EditorView({ parent: host.current, state: EditorState.create({ extensions: marks }) });
|
||||
const v = new EditorView({
|
||||
parent: host.current,
|
||||
state: EditorState.create({ extensions: [marks, lineHeightReporter] }),
|
||||
});
|
||||
view.current = v;
|
||||
v.requestMeasure({ read: (editor) => editor.defaultLineHeight, write: (height) => onLineHeight(height) });
|
||||
return () => {
|
||||
v.destroy();
|
||||
view.current = null;
|
||||
};
|
||||
}, []);
|
||||
}, [lineHeightReporter, onLineHeight]);
|
||||
|
||||
const path = usage?.path ?? null;
|
||||
useEffect(() => {
|
||||
@@ -380,7 +661,9 @@ function UsageCodePreview({ usage }: { usage: Usage | null }) {
|
||||
const t = setTimeout(() => {
|
||||
void Promise.all([readFileLines(path), codePreviewExtensions(path)]).then(([lines, extensions]) => {
|
||||
if (!alive || !view.current) return;
|
||||
view.current.setState(EditorState.create({ doc: (lines ?? []).join("\n"), extensions: [extensions, marks] }));
|
||||
view.current.setState(
|
||||
EditorState.create({ doc: (lines ?? []).join("\n"), extensions: [extensions, marks, lineHeightReporter] }),
|
||||
);
|
||||
setLoaded(path);
|
||||
});
|
||||
}, 60);
|
||||
@@ -388,7 +671,7 @@ function UsageCodePreview({ usage }: { usage: Usage | null }) {
|
||||
alive = false;
|
||||
clearTimeout(t);
|
||||
};
|
||||
}, [path]);
|
||||
}, [path, lineHeightReporter]);
|
||||
|
||||
useEffect(() => {
|
||||
const v = view.current;
|
||||
@@ -402,7 +685,7 @@ function UsageCodePreview({ usage }: { usage: Usage | null }) {
|
||||
}, [usage, loaded]);
|
||||
|
||||
return (
|
||||
<div className={styles.preview} role="region" aria-label={tx("Preview")}>
|
||||
<div className={styles.preview} data-usages-preview role="region" aria-label={tx("Preview")}>
|
||||
<div ref={host} className={clsx(styles.previewEditor, loaded !== path && styles.previewHidden)} />
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const opened = vi.hoisted(() => [] as string[]);
|
||||
const activeEditor = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/editor/api", async (original) => ({
|
||||
...(await original<typeof import("@/editor/api")>()),
|
||||
activeEditor,
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const ipc = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
@@ -17,7 +22,22 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
};
|
||||
});
|
||||
|
||||
const { withDocument } = await import("./ipc");
|
||||
const { withDocument, caretPoint } = await import("./ipc");
|
||||
|
||||
it("anchors Show Usages below a visible caret and inside the editor when the caret is offscreen", () => {
|
||||
const coordsAtPos = vi.fn(() => ({ left: 180, right: 181, top: 190, bottom: 210 }));
|
||||
activeEditor.mockReturnValue({
|
||||
view: {
|
||||
state: { selection: { main: { head: 0 } } },
|
||||
coordsAtPos,
|
||||
scrollDOM: { getBoundingClientRect: () => new DOMRect(100, 100, 600, 400) },
|
||||
},
|
||||
});
|
||||
expect(caretPoint(true)).toEqual({ x: 180, y: 210 });
|
||||
coordsAtPos.mockReturnValue({ left: 180, right: 181, top: 600, bottom: 620 });
|
||||
expect(caretPoint(true)).toEqual({ x: 300, y: 300 });
|
||||
activeEditor.mockReturnValue(null);
|
||||
});
|
||||
|
||||
describe("withDocument", () => {
|
||||
it("opens a library type through its language server, a project file from disk", async () => {
|
||||
|
||||
@@ -83,10 +83,16 @@ function wordAt(view: EditorView, offset: number): string | null {
|
||||
}
|
||||
|
||||
/** Screen point below the caret of the active editor. */
|
||||
export function caretPoint(): { x: number; y: number } {
|
||||
export function caretPoint(preferVisible = false): { x: number; y: number } {
|
||||
const ed = activeEditor();
|
||||
if (ed) {
|
||||
const c = ed.view.coordsAtPos(ed.view.state.selection.main.head);
|
||||
if (preferVisible) {
|
||||
const visible = ed.view.scrollDOM.getBoundingClientRect();
|
||||
if (c && c.left >= visible.left && c.left <= visible.right && c.bottom >= visible.top && c.top <= visible.bottom)
|
||||
return { x: c.left, y: c.bottom };
|
||||
return { x: visible.left + visible.width / 3, y: visible.top + visible.height / 2 };
|
||||
}
|
||||
if (c) return { x: c.left, y: c.bottom };
|
||||
const r = ed.view.dom.getBoundingClientRect();
|
||||
return { x: r.left + 40, y: r.top + 40 };
|
||||
|
||||
@@ -534,7 +534,7 @@ async function searchPopup(c: CaretContext, libraries: boolean, widenable: boole
|
||||
const openEarly = () => {
|
||||
if (popupRequest !== request) return;
|
||||
pending();
|
||||
if (!early && !reopened) useUsagesPopup.setState({ open: true, anchor: caretPoint(), symbol: c.word });
|
||||
if (!early && !reopened) useUsagesPopup.setState({ open: true, anchor: caretPoint(true), symbol: c.word });
|
||||
early = true;
|
||||
shown ||= !!found;
|
||||
const so = found ?? { groups: [], note: null };
|
||||
@@ -563,7 +563,7 @@ async function searchPopup(c: CaretContext, libraries: boolean, widenable: boole
|
||||
popupTarget = { c, widenable: widenable || scope !== null, hintUntil: 0 };
|
||||
const total = usageCount(groups);
|
||||
if (shown || reopened || total > 1) {
|
||||
if (!early && !reopened) useUsagesPopup.setState({ open: true, anchor: caretPoint(), symbol: c.word });
|
||||
if (!early && !reopened) useUsagesPopup.setState({ open: true, anchor: caretPoint(true), symbol: c.word });
|
||||
useUsagesPopup.setState({ groups, note, loading: false, scope });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ vi.mock("./usages", async (orig) => ({
|
||||
showUsageResults: (a: unknown) => showUsageResults(a),
|
||||
}));
|
||||
|
||||
const { UsagesPopup, filterUsages, usageLocations } = await import("./UsagesPopup");
|
||||
const { UsagesPopup, filterUsages, setUsagesPopupPreview, usageLocations } = await import("./UsagesPopup");
|
||||
const { showUsagesPopup, useUsagesPopup, dismissUsagesPopup, setUsagesPopupScope } = await import("./usages");
|
||||
|
||||
const usage = (path: string, line: number, text: string) => ({ path, line, col: 0, endCol: 3, text });
|
||||
@@ -69,6 +69,7 @@ afterEach(() =>
|
||||
dismissUsagesPopup();
|
||||
useUsageAccessOptions.setState({ read: true, write: true });
|
||||
localStorage.removeItem("openidea.usages.accessFilter.v1");
|
||||
localStorage.removeItem("openidea.usages.popupSize.v1");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -109,21 +110,68 @@ describe("Show Usages popup", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("is resizable and opens at the size it was left at", () => {
|
||||
localStorage.setItem("openidea.usages.popupSize.v1", JSON.stringify({ w: 900, h: 120 }));
|
||||
it("recalculates size from results instead of locking future popups to saved width", () => {
|
||||
localStorage.setItem("openidea.usages.popupSize.v1", JSON.stringify({ w: 900, h: 720 }));
|
||||
try {
|
||||
open();
|
||||
expect(screen.getByRole("separator", { name: "Resize" })).toBeInTheDocument();
|
||||
const popup = screen.getByRole("dialog", { name: "Usages" });
|
||||
expect(popup).toHaveAttribute("data-resized");
|
||||
// Clamped to the minimum height.
|
||||
expect(popup.style.width).toBe("900px");
|
||||
expect(popup.style.height).toBe("160px");
|
||||
expect(popup).not.toHaveAttribute("data-resized");
|
||||
const width = parseFloat(popup.style.getPropertyValue("--usages-width"));
|
||||
expect(width).toBeGreaterThanOrEqual(360);
|
||||
expect(width).toBeLessThan(900);
|
||||
expect(popup.style.getPropertyValue("--usages-popup-height")).toBe("160px");
|
||||
} finally {
|
||||
localStorage.removeItem("openidea.usages.popupSize.v1");
|
||||
}
|
||||
});
|
||||
|
||||
it("does not cap a wider popup to a previously saved narrow width", () => {
|
||||
localStorage.setItem("openidea.usages.popupSize.v1", JSON.stringify({ w: 360, h: 160 }));
|
||||
try {
|
||||
render(<UsagesPopup />);
|
||||
const path = "/p/TransportPlanConfigurationService.ts";
|
||||
act(() =>
|
||||
useUsagesPopup.setState({
|
||||
open: true,
|
||||
anchor: { x: 0, y: 0 },
|
||||
symbol: "run",
|
||||
groups: [
|
||||
{
|
||||
path,
|
||||
usages: [
|
||||
usage(path, 1, "run(configuration, currentUser, transportPlan, approvalStatus, tenantContext);"),
|
||||
],
|
||||
},
|
||||
],
|
||||
note: null,
|
||||
}),
|
||||
);
|
||||
const popup = screen.getByRole("dialog", { name: "Usages" });
|
||||
expect(parseFloat(popup.style.getPropertyValue("--usages-width"))).toBeGreaterThan(360);
|
||||
} finally {
|
||||
localStorage.removeItem("openidea.usages.popupSize.v1");
|
||||
}
|
||||
});
|
||||
|
||||
it("restores focus to the previous element after toggling preview and closing", () => {
|
||||
const opener = document.createElement("button");
|
||||
document.body.appendChild(opener);
|
||||
opener.focus();
|
||||
try {
|
||||
open();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Show Preview" }));
|
||||
expect(screen.getByRole("region", { name: "Preview" })).toBeInTheDocument();
|
||||
fireEvent.keyDown(document.activeElement!, { key: "Escape" });
|
||||
expect(useUsagesPopup.getState().open).toBe(false);
|
||||
expect(document.activeElement).toBe(opener);
|
||||
} finally {
|
||||
act(() => setUsagesPopupPreview(false));
|
||||
localStorage.removeItem("openidea.usages.popupPreview.v1");
|
||||
opener.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("the preview pane toggles", () => {
|
||||
open();
|
||||
expect(screen.queryByRole("region", { name: "Preview" })).toBeNull();
|
||||
|
||||
@@ -3988,6 +3988,7 @@
|
||||
"Checkout '{name}'": "Checkout '{name}'",
|
||||
"GitHub account": "GitHub account",
|
||||
"Find actions": "Find actions",
|
||||
"Resize usages preview": "Resize usages preview",
|
||||
"Resize find preview": "Resize find preview",
|
||||
"Caret": "Caret",
|
||||
"Code Structure": "Code Structure",
|
||||
|
||||
@@ -3399,6 +3399,7 @@
|
||||
"Reset IDE Zoom": "重置 IDE 缩放",
|
||||
"Reset Shortcuts": "重置快捷键",
|
||||
"Reset Zoom": "重置缩放",
|
||||
"Resize usages preview": "调整引用预览大小",
|
||||
"Resize find preview": "调整查找预览大小",
|
||||
"Reset to Language Defaults": "重置为语言默认值",
|
||||
"Comment Code": "注释代码",
|
||||
|
||||
@@ -97,6 +97,47 @@ describe("Popup", () => {
|
||||
});
|
||||
|
||||
it("resizes by its right edge, bottom edge and corner within the minimums, and reports each size", () => {
|
||||
const onResized = vi.fn();
|
||||
const onResizeStart = vi.fn();
|
||||
render(
|
||||
<Popup
|
||||
open
|
||||
anchor={{ x: 0, y: 0 }}
|
||||
onClose={() => {}}
|
||||
aria-label="Branches"
|
||||
resizable="both"
|
||||
minWidth={200}
|
||||
minHeight={100}
|
||||
initialSize={{ w: 400, h: 300 }}
|
||||
onResizeStart={onResizeStart}
|
||||
onResized={onResized}
|
||||
>
|
||||
<div>rows</div>
|
||||
</Popup>,
|
||||
);
|
||||
const popup = screen.getByRole("dialog", { name: "Branches" });
|
||||
expect([popup.style.width, popup.style.height]).toEqual(["400px", "300px"]);
|
||||
expect(popup.hasAttribute("data-resized")).toBe(true);
|
||||
// jsdom lays nothing out: the popup measures what its style says, at the origin.
|
||||
popup.getBoundingClientRect = () =>
|
||||
new DOMRect(0, 0, parseFloat(popup.style.width), parseFloat(popup.style.height));
|
||||
fireEvent.pointerDown(screen.getByRole("separator", { name: "Resize" }), { button: 0 });
|
||||
fireEvent.pointerUp(window);
|
||||
expect(onResizeStart).not.toHaveBeenCalled();
|
||||
const drag = (handle: Element, dx: number, dy: number) => {
|
||||
fireEvent.pointerDown(handle, { button: 0, clientX: 0, clientY: 0 });
|
||||
fireEvent.pointerMove(window, { buttons: 1, clientX: dx, clientY: dy });
|
||||
fireEvent.pointerUp(window);
|
||||
return [popup.style.width, popup.style.height];
|
||||
};
|
||||
expect(drag(popup.querySelector(`.${popupStyles.resizeRight}`)!, 100, 50)).toEqual(["500px", "300px"]);
|
||||
expect(drag(popup.querySelector(`.${popupStyles.resizeBottom}`)!, 50, -100)).toEqual(["500px", "200px"]);
|
||||
expect(drag(screen.getByRole("separator", { name: "Resize" }), -1000, -1000)).toEqual(["200px", "100px"]);
|
||||
expect(onResized.mock.calls).toEqual([[{ w: 500, h: 300 }], [{ w: 500, h: 200 }], [{ w: 200, h: 100 }]]);
|
||||
expect(onResizeStart).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("releases resize listeners and cursor lock when pointercancel interrupts a resize", () => {
|
||||
const onResized = vi.fn();
|
||||
render(
|
||||
<Popup
|
||||
@@ -114,21 +155,16 @@ describe("Popup", () => {
|
||||
</Popup>,
|
||||
);
|
||||
const popup = screen.getByRole("dialog", { name: "Branches" });
|
||||
expect([popup.style.width, popup.style.height]).toEqual(["400px", "300px"]);
|
||||
expect(popup.hasAttribute("data-resized")).toBe(true);
|
||||
// jsdom lays nothing out: the popup measures what its style says, at the origin.
|
||||
popup.getBoundingClientRect = () =>
|
||||
new DOMRect(0, 0, parseFloat(popup.style.width), parseFloat(popup.style.height));
|
||||
const drag = (handle: Element, dx: number, dy: number) => {
|
||||
fireEvent.pointerDown(handle, { button: 0, clientX: 0, clientY: 0 });
|
||||
fireEvent.pointerMove(window, { buttons: 1, clientX: dx, clientY: dy });
|
||||
fireEvent.pointerUp(window);
|
||||
return [popup.style.width, popup.style.height];
|
||||
};
|
||||
expect(drag(popup.querySelector(`.${popupStyles.resizeRight}`)!, 100, 50)).toEqual(["500px", "300px"]);
|
||||
expect(drag(popup.querySelector(`.${popupStyles.resizeBottom}`)!, 50, -100)).toEqual(["500px", "200px"]);
|
||||
expect(drag(screen.getByRole("separator", { name: "Resize" }), -1000, -1000)).toEqual(["200px", "100px"]);
|
||||
expect(onResized.mock.calls).toEqual([[{ w: 500, h: 300 }], [{ w: 500, h: 200 }], [{ w: 200, h: 100 }]]);
|
||||
fireEvent.pointerDown(screen.getByRole("separator", { name: "Resize" }), { button: 0, clientX: 0, clientY: 0 });
|
||||
fireEvent.pointerMove(window, { buttons: 1, clientX: 60, clientY: 40 });
|
||||
fireEvent.pointerCancel(window);
|
||||
expect(onResized).toHaveBeenCalledTimes(1);
|
||||
expect(onResized).toHaveBeenCalledWith({ w: 460, h: 340 });
|
||||
expect(document.querySelector("[data-drag-cursor-surface]")).toBeNull();
|
||||
fireEvent.pointerMove(window, { buttons: 1, clientX: 200, clientY: 200 });
|
||||
expect([popup.style.width, popup.style.height]).toEqual(["460px", "340px"]);
|
||||
});
|
||||
|
||||
it("has no resize handles and ignores a remembered size unless resizable", () => {
|
||||
|
||||
+50
-11
@@ -51,6 +51,8 @@ export interface PopupProps {
|
||||
anchor: PopupAnchor;
|
||||
placement?: Placement;
|
||||
offset?: number;
|
||||
/** Fit the initial placement, then keep the current position unless the popup no longer fits. */
|
||||
fitToScreen?: boolean;
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
@@ -83,6 +85,8 @@ export interface PopupProps {
|
||||
minHeight?: number;
|
||||
/** Size to open at, such as one remembered from `onResized`. While a size applies the popup has `data-resized`. */
|
||||
initialSize?: { w: number; h: number } | null;
|
||||
/** Called before the first size change of a manual resize gesture. */
|
||||
onResizeStart?: () => void;
|
||||
/** The size a resize ended at. */
|
||||
onResized?: (size: { w: number; h: number }) => void;
|
||||
}
|
||||
@@ -145,6 +149,7 @@ function PopupInner({
|
||||
anchor,
|
||||
placement = "bottom-start",
|
||||
offset = 4,
|
||||
fitToScreen = false,
|
||||
children,
|
||||
className,
|
||||
style,
|
||||
@@ -162,6 +167,7 @@ function PopupInner({
|
||||
minWidth = 200,
|
||||
minHeight = 120,
|
||||
initialSize,
|
||||
onResizeStart,
|
||||
onResized,
|
||||
...aria
|
||||
}: PopupProps) {
|
||||
@@ -171,23 +177,38 @@ function PopupInner({
|
||||
const reference = toReference(position ?? anchor);
|
||||
const hasInlineMaxHeight = style?.maxHeight != null && style.maxHeight !== "";
|
||||
const atPoint = !!anchor && typeof anchor === "object" && "x" in anchor && !("getBoundingClientRect" in anchor);
|
||||
const middleware = useMemo(
|
||||
() => [
|
||||
const fittedPosition = useRef<{ anchor: PopupAnchor; x: number; y: number } | null>(null);
|
||||
const middleware = useMemo(() => {
|
||||
const preservePosition: Middleware = {
|
||||
name: "preservePosition",
|
||||
options: anchor,
|
||||
fn: () =>
|
||||
fittedPosition.current?.anchor === anchor ? { x: fittedPosition.current.x, y: fittedPosition.current.y } : {},
|
||||
};
|
||||
const rememberPosition: Middleware = {
|
||||
name: "rememberPosition",
|
||||
fn({ x, y }) {
|
||||
fittedPosition.current = { anchor, x, y };
|
||||
return {};
|
||||
},
|
||||
};
|
||||
return [
|
||||
offsetMw(moved ? 0 : offset),
|
||||
hasInlineMaxHeight ? null : measureNaturalHeight,
|
||||
moved ? null : flip({ padding: 6 }),
|
||||
moved || fitToScreen ? null : flip({ padding: 6 }),
|
||||
fitToScreen && !moved ? preservePosition : null,
|
||||
// At a point (a context menu) nothing is covered by moving up: fit the screen before scrolling.
|
||||
shift({ padding: 6, crossAxis: atPoint || moved }),
|
||||
shift({ padding: 6, crossAxis: atPoint || moved || fitToScreen }),
|
||||
sizeMw({
|
||||
padding: 6,
|
||||
apply({ rects, elements, availableHeight, availableWidth, middlewareData }) {
|
||||
const floatingStyle = elements.floating.style;
|
||||
const maxHeight = Math.max(120, availableHeight);
|
||||
const maxHeight = Math.max(fitToScreen ? 0 : 120, availableHeight);
|
||||
if (!hasInlineMaxHeight && (rects.floating.height > maxHeight || floatingStyle.maxHeight)) {
|
||||
floatingStyle.maxHeight = `${maxHeight}px`;
|
||||
// A popup as wide as its content: a scrollbar that only appears on overflow takes its
|
||||
// width from the content (menu labels get cut). Always shown, it widens the popup instead.
|
||||
if (rects.floating.height > maxHeight) floatingStyle.overflowY = "scroll";
|
||||
if (rects.floating.height > maxHeight && !(fitToScreen && resizable)) floatingStyle.overflowY = "scroll";
|
||||
const scrollTop = middlewareData.measureNaturalHeight?.scrollTop;
|
||||
if (scrollTop) elements.floating.scrollTop = scrollTop;
|
||||
}
|
||||
@@ -197,9 +218,9 @@ function PopupInner({
|
||||
if (matchWidth) floatingStyle.minWidth = `${Math.min(rects.reference.width, width)}px`;
|
||||
},
|
||||
}),
|
||||
],
|
||||
[hasInlineMaxHeight, offset, matchWidth, maxWidthOverAnchor, atPoint, moved],
|
||||
);
|
||||
fitToScreen && !moved ? rememberPosition : null,
|
||||
];
|
||||
}, [anchor, hasInlineMaxHeight, offset, matchWidth, maxWidthOverAnchor, atPoint, moved, fitToScreen, resizable]);
|
||||
const { refs, floatingStyles, isPositioned } = useFloating({
|
||||
placement: moved ? "bottom-start" : placement,
|
||||
strategy: "fixed",
|
||||
@@ -220,7 +241,14 @@ function PopupInner({
|
||||
const ancestry = useMemo(() => [...outer, layerId], [outer]);
|
||||
const [size, setSize] = useState(() => (resizable && initialSize) || null);
|
||||
const cancelDrag = useRef<(() => void) | null>(null);
|
||||
useEffect(() => () => cancelDrag.current?.(), []);
|
||||
const cancelResize = useRef<(() => void) | null>(null);
|
||||
useEffect(
|
||||
() => () => {
|
||||
cancelDrag.current?.();
|
||||
cancelResize.current?.();
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const layer = openLayer(() => elRef.current, closeOnDeactivate ? () => onCloseRef.current("outside") : undefined);
|
||||
@@ -314,6 +342,7 @@ function PopupInner({
|
||||
const el = elRef.current;
|
||||
if (e.button !== 0 || !el) return;
|
||||
e.preventDefault();
|
||||
cancelResize.current?.();
|
||||
const releaseCursor = lockDragCursor(EDGE_CURSOR[edge]);
|
||||
const start = { x: e.clientX, y: e.clientY };
|
||||
const rect = el.getBoundingClientRect();
|
||||
@@ -322,20 +351,30 @@ function PopupInner({
|
||||
if (!(ev.buttons & 1)) return up();
|
||||
const w = edge === "bottom" ? rect.width : rect.width + ev.clientX - start.x;
|
||||
const h = edge === "right" ? rect.height : rect.height + ev.clientY - start.y;
|
||||
if (!last) onResizeStart?.();
|
||||
last = {
|
||||
w: Math.min(Math.max(w, minWidth), window.innerWidth - rect.left - 6),
|
||||
h: Math.min(Math.max(h, minHeight), window.innerHeight - rect.top - 6),
|
||||
};
|
||||
setSize(last);
|
||||
};
|
||||
const up = () => {
|
||||
const cleanup = () => {
|
||||
window.removeEventListener("pointermove", move);
|
||||
window.removeEventListener("pointerup", up);
|
||||
window.removeEventListener("pointercancel", up);
|
||||
window.removeEventListener("blur", up);
|
||||
releaseCursor();
|
||||
cancelResize.current = null;
|
||||
};
|
||||
const up = () => {
|
||||
cleanup();
|
||||
if (last) onResized?.(last);
|
||||
};
|
||||
cancelResize.current = cleanup;
|
||||
window.addEventListener("pointermove", move);
|
||||
window.addEventListener("pointerup", up);
|
||||
window.addEventListener("pointercancel", up);
|
||||
window.addEventListener("blur", up);
|
||||
};
|
||||
|
||||
return createPortal(
|
||||
|
||||
Reference in new issue
Заблокувати користувача