Файли
openidea/e2e/usagesPopup.fixture.tsx
T
tongkangwangтаl0ng-ai a2498f096a 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]>
2026-12-05 00:29:34 +08:00

268 рядки
9.9 KiB
TypeScript

import { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import { bootWorkbenchWindow } from "../src/workbenchBoot";
import { installCommonWindowBoot } from "../src/windowBoot";
import { dismissUsagesPopup, useUsagesPopup, type Usage, type UsageGroup } from "../src/features/code-insight/usages";
import { useUsageAccessOptions } from "../src/features/code-insight/UsageAccessFilter";
import "./usagesPopup.fixture.css";
const symbol = "getNoOrderApproveDetail";
const longName = "LmsCarrierWaterCarrierRatingApprovalTransportPlanConfigurationServiceImpl.java";
const sizeKey = "openidea.usages.popupSize.v1";
function group(file: string, texts: string[], access?: Usage["access"]): UsageGroup {
const path = `/dev/acme-api/src/${file}`;
return {
path,
usages: texts.map((text, index) => {
const col = text.indexOf(symbol);
return { path, line: index * 40 + 9, col, endCol: col + symbol.length, text, access };
}),
};
}
const shortGroups = () =>
["A.java", "Api.java", "Job.java"].map((file) => group(file, [`return service.${symbol}(query);`]));
const longGroup = () => group(longName, [`return service.${symbol}(query, currentUser, BUSINESS_ID);`]);
const scenarios = [
{
id: "normal",
label: "普通文件名",
hint: "放大窗口:文件名展示完整后不再加宽,新增宽度应留给右侧代码。",
groups: () => [
group("LmsTransportPlanController.java", Array(3).fill(`return transportPlanService.${symbol}(query);`)),
group("NoOrderApprovalDetailTest.java", [
`assertThrows(RenException.class, () -> service.${symbol}(null));`,
`PlanDetailVO detail = service.${symbol}(query(BUSINESS_ID));`,
`when(mockService.${symbol}(any())).thenReturn(new PlanDetailVO());`,
]),
],
},
{
id: "short",
label: "短文件名",
hint: "左列只占短文件名需要的宽度,右侧代码靠前,不应留出大片空白。",
groups: shortGroups,
},
{
id: "long",
label: "超长文件名",
hint: "左列有宽度上限,超出部分省略;放大后右侧代码仍应获得大部分空间。悬停查看完整路径。",
groups: () => [...shortGroups(), longGroup()],
},
{
id: "duplicates",
label: "同名不同目录",
hint: "两个 Routes.java 应显示 billing / checkout 目录以便区分,文件名、行号、代码仍应对齐。",
groups: () => [
group(`billing/Routes.java`, [`return service.${symbol}(invoice);`]),
group(`checkout/Routes.java`, [`return service.${symbol}(cart);`]),
group("Worker.java", [`await service.${symbol}(job);`]),
],
},
{
id: "mixed",
label: "中文与长代码",
hint: "中英文文件名、长代码和大行号应对齐;宽度不足时省略,拉宽后能看到更多代码。",
groups: () =>
[
group("订单审批详情查询.java", [
`return transportPlanService.${symbol}(query, currentUser, BUSINESS_ID, APPROVAL_STATUS, transportPlanConfiguration, tenantContext);`,
]),
group("Order审批Test.java", [`assertEquals("审批通过", service.${symbol}(query).getStatus());`]),
].map((item, index) => ({
...item,
usages: item.usages.map((usage) => ({ ...usage, line: index ? 9998 : 998 })),
})),
},
{
id: "many",
label: "200 条滚动",
hint: "最长文件名在第 200 条。滚到底部或在窗口内输入 Handler 搜索,列宽应保持稳定;Esc 清除搜索。",
groups: () => [
...Array.from({ length: 199 }, (_, index) =>
group(`Handler${String(index + 1).padStart(3, "0")}.java`, [`return service.${symbol}(query${index + 1});`]),
),
longGroup(),
],
},
{
id: "access",
label: "读写与搜索",
hint: "切换标题栏的读/写按钮,或输入 Read / Write 搜索,列宽应稳定;输入 zzzz 可测空结果,Esc 恢复。",
groups: () => [
group("Read.java", [`detail = service.${symbol}(query);`], "read"),
group("ApprovalTransportPlanWrite.java", [`service.${symbol}(query).setApproved(true);`], "write"),
group("Unknown.java", [`return service.${symbol}(query);`]),
],
},
{
id: "streaming",
label: "逐步加载",
hint: "先显示短文件名;3 秒后追加超长文件名,左列应自动变宽并受宽度上限约束。再次选择可重播。",
groups: shortGroups,
},
] as const;
type Scenario = (typeof scenarios)[number];
let pendingLoad: ReturnType<typeof setTimeout> | undefined;
function showAt(x: number, y: number, scenario: Scenario) {
clearTimeout(pendingLoad);
// A fresh mount also resets any position chosen by the previous drag.
flushSync(() => dismissUsagesPopup());
useUsageAccessOptions.setState({ read: true, write: true });
useUsagesPopup.setState({
open: true,
anchor: { x, y },
symbol,
loading: scenario.id === "streaming",
scope: "project",
note: `${scenario.label} · 拖动标题栏移动,右下角缩放,Esc 关闭`,
groups: scenario.groups(),
});
if (scenario.id === "streaming") {
pendingLoad = setTimeout(() => {
if (!useUsagesPopup.getState().open) return;
useUsagesPopup.setState({ groups: [...shortGroups(), longGroup()], loading: false });
}, 3000);
}
}
function DemoControls() {
const [scenario, setScenario] = useState<Scenario>(scenarios[0]);
const [picking, setPicking] = useState(false);
const [anchor, setAnchor] = useState<{ x: number; y: number } | null>(null);
const [fontSize, setFontSize] = useState(13);
const show = (x: number, y: number, next = scenario) => {
setPicking(false);
setAnchor({ x, y });
showAt(x, y, next);
};
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();
};
useEffect(() => {
const frame = requestAnimationFrame(() => show(window.innerWidth / 2, 80));
return () => {
cancelAnimationFrame(frame);
clearTimeout(pendingLoad);
};
// Open the initial sample once; subsequent openings come from the controls.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<>
{anchor && <div className="usages-demo-anchor" aria-hidden="true" style={{ left: anchor.x, top: anchor.y }} />}
{picking && (
<button
type="button"
className="usages-demo-pick"
aria-label="选择引用窗口弹出位置"
onClick={(event) => show(event.clientX, event.clientY)}
onKeyDown={(event) => {
if (event.key === "Escape") setPicking(false);
}}
autoFocus
>
点击任意位置打开引用窗口
</button>
)}
<section className="usages-demo-controls" aria-label="引用窗口测试控制台">
<div className="usages-demo-heading">
<strong>引用窗口测试</strong>
<span>橙点为弹出位置;所有场景均可拖动、缩放,尺寸会保留。</span>
</div>
<div className="usages-demo-actions" role="group" aria-label="测试场景">
{scenarios.map((item) => (
<button
key={item.id}
type="button"
aria-pressed={scenario.id === item.id}
onClick={() => {
setScenario(item);
centered(item);
}}
>
{item.label}
</button>
))}
</div>
<p className="usages-demo-hint" role="status">
{scenario.hint}
</p>
<div className="usages-demo-actions">
<button type="button" onClick={() => centered()}>
居中打开
</button>
<button type="button" onClick={() => show(12, 80)}>
左边缘
</button>
<button type="button" onClick={() => show(window.innerWidth - 12, 80)}>
右边缘
</button>
<button type="button" onClick={() => show(window.innerWidth / 2, window.innerHeight - 12)}>
底部翻转
</button>
<button
type="button"
onClick={() => {
dismissUsagesPopup();
setPicking(true);
}}
>
任意位置
</button>
<button
type="button"
onClick={() => {
flushSync(() => dismissUsagesPopup());
localStorage.removeItem(sizeKey);
centered();
}}
>
重置尺寸
</button>
<button type="button" onClick={() => resize(420)}>
窄窗口 420
</button>
<button type="button" onClick={() => resize(680)}>
默认宽 680
</button>
<button type="button" onClick={() => resize(1000)}>
宽窗口 1000
</button>
<label>
界面字号
<select
aria-label="界面字号"
value={fontSize}
onChange={(event) => {
const size = Number(event.target.value);
setFontSize(size);
document.documentElement.style.setProperty("--fs-ui", `${size}px`);
document.documentElement.style.setProperty("--fs-small", `${size - 1}px`);
document.documentElement.style.setProperty("--fs-tiny", `${size - 2}px`);
centered();
}}
>
{[13, 16, 18].map((size) => (
<option key={size} value={size}>
{size}px
</option>
))}
</select>
</label>
</div>
</section>
</>
);
}
await installCommonWindowBoot();
await bootWorkbenchWindow();
createRoot(document.getElementById("usages-demo")!).render(<DemoControls />);