From 7c682a580f6f32949cd234f287d7e704d1335fd8 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Sat, 21 Nov 2026 07:25:05 +0800 Subject: [PATCH] fix(editor): group the Refactor This actions (#4906) Refactor This uses a compact action list with an Extract/Introduce section and dividers for the related action groups. Filtering keeps captions only for groups with matching actions. The number beside each action still selects that action directly. --- e2e/refactorThisLayout.spec.ts | 71 +++++++++++++++++++++ src/editor/lsp/Popups.module.css | 10 ++- src/editor/lsp/Popups.tsx | 80 ++++++++++++++++++------ src/editor/lsp/popupStore.ts | 4 ++ src/editor/refactor/catalog.ts | 54 +++++++++++----- src/editor/refactor/refactorThis.test.ts | 6 +- src/editor/refactor/refactorThis.ts | 10 ++- src/platform/locales/text/en.json | 1 + src/platform/locales/text/zh.json | 1 + 9 files changed, 196 insertions(+), 41 deletions(-) create mode 100644 e2e/refactorThisLayout.spec.ts diff --git a/e2e/refactorThisLayout.spec.ts b/e2e/refactorThisLayout.spec.ts new file mode 100644 index 000000000..0413ddd34 --- /dev/null +++ b/e2e/refactorThisLayout.spec.ts @@ -0,0 +1,71 @@ +import type { Page } from "@playwright/test"; +import { expect, test } from "./fixtures"; + +async function openRefactorList(page: Page) { + await page.evaluate(async () => { + const path = "/src/editor/lsp/popupStore.ts"; + const { openPopup } = await import(/* @vite-ignore */ path); + const run = (action: string) => () => { + document.body.dataset.selectedRefactoring = action; + }; + openPopup({ + kind: "list", + title: "Refactor This", + anchor: { x: 300, y: 140 }, + compact: true, + numbered: true, + items: [ + { id: "rename", label: "Rename…", shortcut: "Shift+F6", run: run("rename") }, + { + id: "extractVariable", + label: "Introduce Variable…", + shortcut: "Ctrl+Alt+V", + section: { id: "extract", label: "Extract/Introduce" }, + run: run("extractVariable"), + }, + { id: "inline", label: "Inline…", section: { id: "inline" }, run: run("inline") }, + ], + }); + }); +} + +test("the compact Refactor This list groups actions without numbering or selecting its captions", async ({ + workbench: page, +}) => { + await openRefactorList(page); + const popup = page.getByRole("dialog", { name: "Refactor This", exact: true }); + const group = popup.getByText("Extract/Introduce", { exact: true }); + await expect(group).toBeVisible(); + expect((await popup.boundingBox())!.width).toBeLessThan(360); + await expect(popup.getByRole("option")).toHaveCount(3); + const introduce = popup.getByRole("option", { name: /Introduce Variable/ }); + await expect(introduce.getByText("2", { exact: true })).toBeVisible(); + + await page.keyboard.press("ArrowDown"); + await expect(introduce).toHaveAttribute("aria-selected", "true"); + await page.keyboard.press("2"); + await expect(popup).toBeHidden(); + await expect(page.locator("body")).toHaveAttribute("data-selected-refactoring", "extractVariable"); +}); + +test("filtering keeps captions only for groups with a matching action", async ({ workbench: page }) => { + await openRefactorList(page); + const popup = page.getByRole("dialog", { name: "Refactor This", exact: true }); + const list = popup.getByRole("listbox"); + const group = popup.getByText("Extract/Introduce", { exact: true }); + await expect(list).toBeFocused(); + await expect(group).toBeVisible(); + + await page.keyboard.type("variable"); + await expect(group).toBeVisible(); + await expect(popup.getByRole("option")).toHaveCount(1); + await expect(popup.getByRole("option")).toHaveAttribute("aria-selected", "true"); + await page.keyboard.press("Enter"); + await expect(page.locator("body")).toHaveAttribute("data-selected-refactoring", "extractVariable"); + + await openRefactorList(page); + await expect(list).toBeFocused(); + await page.keyboard.type("rename"); + await expect(group).toBeHidden(); + await expect(popup.getByRole("option", { name: /Rename/ })).toHaveAttribute("aria-selected", "true"); +}); diff --git a/src/editor/lsp/Popups.module.css b/src/editor/lsp/Popups.module.css index d96463933..c6eb0138c 100644 --- a/src/editor/lsp/Popups.module.css +++ b/src/editor/lsp/Popups.module.css @@ -6,6 +6,14 @@ display: flex; flex-direction: column; } +.compactListPopup { + min-width: 0; +} +.listDivider { + width: 100%; + height: 1px; + background: var(--border-popup); +} .listHeader { height: 28px; flex: none; @@ -116,7 +124,7 @@ .listBody { display: flex; flex-direction: column; - min-height: 24px; + min-height: var(--h-list-row); padding: 0 0 4px; box-sizing: content-box; } diff --git a/src/editor/lsp/Popups.tsx b/src/editor/lsp/Popups.tsx index 523f92608..98ed10b22 100644 --- a/src/editor/lsp/Popups.tsx +++ b/src/editor/lsp/Popups.tsx @@ -16,6 +16,7 @@ import { Spinner, SymbolBadge, fileIconName, + firstSelectable, fuzzyMatch, selectableText, T, @@ -40,6 +41,7 @@ import styles from "./Popups.module.css"; import fieldsetStyles from "@/ui/DialogFieldset.module.css"; import { tx } from "@/platform/i18n"; import { executeAction } from "@/platform/actions"; +import { useRowHeight } from "@/ui/density"; export function BulbIcon({ fix }: { fix?: boolean }) { return ; @@ -82,19 +84,44 @@ function ListPreviewPanel({ const LIST_PREVIEW_WIDTH = 420; const MIN_SIDE_BY_SIDE_WIDTH = 660; +type ListPopupRow = + | { kind: "action"; item: ListPopupItem; match: number[] | null } + | { kind: "section"; key: string; label?: string }; + +const isListSection = (row: ListPopupRow) => row.kind === "section"; +const dividerHeight = (row: ListPopupRow) => (row.kind === "section" && !row.label ? 9 : undefined); + +function listPopupRows(items: ListPopupItem[], query: string): ListPopupRow[] { + const rows: ListPopupRow[] = []; + let previous: string | undefined; + for (const item of items) { + const match = query ? fuzzyMatch(item.label, query) : null; + if (query && match === null) continue; + const { section } = item; + if (section?.id !== previous && (section?.label || rows.length)) { + rows.push({ kind: "section", key: `section:${rows.length}`, label: section?.label }); + } + rows.push({ kind: "action", item, match }); + previous = section?.id; + } + return rows; +} + function ListPopup({ popup }: { popup: Extract }) { const [query, setQuery] = useState(""); - const filtered = useMemo(() => { - if (!query) return popup.items.map((item) => ({ item, match: null as number[] | null })); - return popup.items.map((item) => ({ item, match: fuzzyMatch(item.label, query) })).filter((r) => r.match !== null); - }, [popup.items, query]); - const firstEnabled = Math.max( - 0, - filtered.findIndex((r) => !r.item.disabled), - ); + const rows = useMemo(() => listPopupRows(popup.items, query), [popup.items, query]); + const firstEnabled = rows.findIndex((row) => row.kind === "action" && !row.item.disabled); const [active, setActive] = useState(firstEnabled); - const activeIndex = Math.min(active, Math.max(0, filtered.length - 1)); - const activeItem = filtered[activeIndex]?.item; + const clamped = Math.min(active, rows.length - 1); + const activeIndex = + rows[clamped]?.kind === "action" + ? clamped + : firstEnabled >= 0 + ? firstEnabled + : firstSelectable(rows, isListSection); + const activeRow = rows[activeIndex]; + const activeItem = activeRow?.kind === "action" ? activeRow.item : undefined; + const showIcons = !popup.compact || popup.items.some((item) => item.icon || item.symbol); // Choosers highlight what the selected row would act on. useEffect(() => { @@ -156,16 +183,20 @@ function ListPopup({ popup }: { popup: Extract }) { if (item) activate(item); } else if (e.key === "Backspace" && query) { setQuery(query.slice(0, -1)); - setActive(0); + setActive(-1); e.preventDefault(); } else if (e.key.length === 1 && !(e.key === " " && !query)) { setQuery(query + e.key); - setActive(0); + setActive(-1); e.preventDefault(); } }; - const height = Math.min(12, Math.max(1, filtered.length)) * 24; + const rowHeight = useRowHeight(); + const height = Math.min( + 12 * rowHeight, + rows.reduce((sum, row) => sum + (dividerHeight(row) ?? rowHeight), 0) || rowHeight, + ); // Rows are virtualized (absolutely positioned), so size the popup from the content. const width = useMemo(() => { const chars = Math.max( @@ -174,8 +205,9 @@ function ListPopup({ popup }: { popup: Extract }) { (i) => i.label.length + (i.preview?.length ?? 0) + (i.detail?.length ?? 0) + (i.shortcut?.length ?? 0), ), ); - return Math.min(720, Math.max(320, chars * 7 + 90 + (popup.numbered ? 16 : 0))); - }, [popup]); + const padding = popup.compact ? 44 + (showIcons ? 20 : 0) : 90; + return Math.min(720, Math.max(popup.compact ? 272 : 320, chars * 7 + padding + (popup.numbered ? 16 : 0))); + }, [popup, showIcons]); const shownPreview = popup.preview ? preview && preview.id === activeItem?.id ? preview.data @@ -216,6 +248,7 @@ function ListPopup({ popup }: { popup: Extract }) { aria-label={popup.title} className={clsx( styles.listPopup, + popup.compact && styles.compactListPopup, hasPreview && styles.withPreview, previewBelow && styles.previewBelow, previewLeft && styles.previewLeft, @@ -242,14 +275,19 @@ function ListPopup({ popup }: { popup: Extract }) {
r.item.id} + items={rows} + getKey={(row) => (row.kind === "section" ? row.key : row.item.id)} + isSection={isListSection} + sectionHeightOf={dividerHeight} + renderSection={(row) => + row.kind === "section" && row.label ? {row.label} : + } activeIndex={activeIndex} onActiveChange={setActive} hoverSelects autoFocus aria-label={popup.title} - onActivate={(r) => activate(r.item)} + onActivate={(row) => row.kind === "action" && activate(row.item)} empty={ popup.busy ? ( @@ -261,7 +299,9 @@ function ListPopup({ popup }: { popup: Extract }) { ) } - renderItem={({ item, match }) => { + renderItem={(row) => { + if (row.kind !== "action") return null; + const { item, match } = row; const n = popup.numbered && !query ? indexOf(item) + 1 : 0; return (
}) { data-line={item.location?.line} > {popup.numbered && {n > 0 && n <= 9 ? n : ""}} - + {showIcons && } {item.preview && ( diff --git a/src/editor/lsp/popupStore.ts b/src/editor/lsp/popupStore.ts index 7048ac72f..3dc3896b1 100644 --- a/src/editor/lsp/popupStore.ts +++ b/src/editor/lsp/popupStore.ts @@ -14,6 +14,8 @@ export interface PopupPoint { export interface ListPopupItem { id: string; label: string; + /** Adjacent actions with the same section id share a caption or divider. */ + section?: { id: string; label?: string }; /** Muted trailing text (file:line, kind…). */ detail?: string; /** Second line / muted text after the label (code preview). */ @@ -100,6 +102,8 @@ export type LspPopup = items: ListPopupItem[]; /** Rows 1-9 get a number; typing it runs the row (IDEA's numbered popups). */ numbered?: boolean; + /** Compact action list, with room for icons only when a row has one. */ + compact?: boolean; /** More rows are still being looked for (`aria-busy`). */ busy?: boolean; /** Header pin button (e.g. "Open in Find Tool Window"). */ diff --git a/src/editor/refactor/catalog.ts b/src/editor/refactor/catalog.ts index ac7638e4a..f26633559 100644 --- a/src/editor/refactor/catalog.ts +++ b/src/editor/refactor/catalog.ts @@ -28,6 +28,7 @@ export interface Refactoring { /** Action id (keymaps, menu). */ action: string; label: string; + section?: { id: string; label?: string }; /** LSP kind prefix that can produce it; null for client-side refactorings. */ kind: string | null; /** IDEA's reason when nothing applies at the caret / selection. */ @@ -35,6 +36,9 @@ export interface Refactoring { } const AT_NAME = "Caret should be positioned at the name of the element to be refactored"; +const EXTRACT = { id: "extract", label: "Extract/Introduce" }; +const MOVE = { id: "move" }; +const HIERARCHY = { id: "hierarchy" }; /** IDEA's Refactor This order. */ export const REFACTORINGS: readonly Refactoring[] = [ @@ -52,26 +56,11 @@ export const REFACTORINGS: readonly Refactoring[] = [ kind: "refactor.rewrite", reason: () => "Caret should be positioned at the name of the function or method to be refactored", }, - { id: "move", action: "refactor.move", label: "Move…", kind: "refactor.move", reason: () => AT_NAME }, - { - id: "safeDelete", - action: "refactor.safeDelete", - label: "Safe Delete…", - kind: null, - reason: () => "Caret should be on a symbol", - }, - { - id: "extractMethod", - action: "refactor.extractMethod", - label: "Extract Method…", - kind: "refactor.extract", - reason: (sel) => - sel ? "Selected block should represent a set of statements or an expression" : "Select the code to extract", - }, { id: "extractVariable", action: "refactor.extractVariable", label: "Introduce Variable…", + section: EXTRACT, kind: "refactor.extract", reason: (sel) => (sel ? "Selected block should represent an expression" : "Caret should be inside an expression"), }, @@ -79,6 +68,7 @@ export const REFACTORINGS: readonly Refactoring[] = [ id: "extractConstant", action: "refactor.extractConstant", label: "Introduce Constant…", + section: EXTRACT, kind: "refactor.extract", reason: (sel) => (sel ? "Selected block should represent an expression" : "Caret should be inside an expression"), }, @@ -86,6 +76,7 @@ export const REFACTORINGS: readonly Refactoring[] = [ id: "extractField", action: "refactor.extractField", label: "Introduce Field…", + section: EXTRACT, kind: "refactor.extract", reason: (sel) => sel ? "Selected block should represent an expression" : "Caret should be inside an expression in a class", @@ -94,22 +85,50 @@ export const REFACTORINGS: readonly Refactoring[] = [ id: "extractParameter", action: "refactor.extractParameter", label: "Introduce Parameter…", + section: EXTRACT, kind: "refactor.extract", reason: (sel) => sel ? "Selected block should represent an expression" : "Caret should be inside an expression in a function", }, + { + id: "extractMethod", + action: "refactor.extractMethod", + label: "Extract Method…", + section: EXTRACT, + kind: "refactor.extract", + reason: (sel) => + sel ? "Selected block should represent a set of statements or an expression" : "Select the code to extract", + }, { id: "extractInterface", action: "refactor.extractInterface", label: "Extract Interface…", + section: EXTRACT, kind: null, reason: () => "Caret should be inside a class", }, - { id: "inline", action: "refactor.inline", label: "Inline…", kind: "refactor.inline", reason: () => AT_NAME }, + { + id: "inline", + action: "refactor.inline", + label: "Inline…", + section: { id: "inline" }, + kind: "refactor.inline", + reason: () => AT_NAME, + }, + { id: "move", action: "refactor.move", label: "Move…", section: MOVE, kind: "refactor.move", reason: () => AT_NAME }, + { + id: "safeDelete", + action: "refactor.safeDelete", + label: "Safe Delete…", + section: MOVE, + kind: null, + reason: () => "Caret should be on a symbol", + }, { id: "pullMembersUp", action: "refactor.pullMembersUp", label: "Pull Members Up…", + section: HIERARCHY, kind: null, reason: () => "Caret should be inside a class that has members to pull up", }, @@ -117,6 +136,7 @@ export const REFACTORINGS: readonly Refactoring[] = [ id: "pushMembersDown", action: "refactor.pushMembersDown", label: "Push Members Down…", + section: HIERARCHY, kind: null, reason: () => "Caret should be inside a class that has members to push down", }, diff --git a/src/editor/refactor/refactorThis.test.ts b/src/editor/refactor/refactorThis.test.ts index a6c53a742..cf6cff633 100644 --- a/src/editor/refactor/refactorThis.test.ts +++ b/src/editor/refactor/refactorThis.test.ts @@ -181,7 +181,7 @@ describe("catalog", () => { }); describe("Refactor This", () => { - it("lists only the refactorings applicable at the caret, in IDEA order", async () => { + it("lists applicable refactorings in menu order and groups extraction actions", async () => { prepare = ok({ start: { line: 0, col: 0 }, end: { line: 0, col: 1 } }); query = answer([ action("Inline variable", "refactor.inline"), @@ -190,7 +190,9 @@ describe("Refactor This", () => { action("Extract into function", "refactor.extract", "Can't extract here"), ]); await refactorThis(editor(), vi.fn()); - expect(labels()).toEqual(["Rename…", "Safe Delete…", "Introduce Variable…", "Inline…", "Convert to raw string"]); + expect(labels()).toEqual(["Rename…", "Introduce Variable…", "Inline…", "Safe Delete…", "Convert to raw string"]); + const popup = useLspPopup.getState().popup; + expect(popup?.kind === "list" && popup.items[1]?.section?.label).toBe("Extract/Introduce"); // IDEA's numbered list: 1-9 run a row directly. expect((useLspPopup.getState().popup as { numbered?: boolean }).numbered).toBe(true); expect(lspCodeActionQuery).toHaveBeenCalledOnce(); diff --git a/src/editor/refactor/refactorThis.ts b/src/editor/refactor/refactorThis.ts index b7a0ae100..673fb8153 100644 --- a/src/editor/refactor/refactorThis.ts +++ b/src/editor/refactor/refactorThis.ts @@ -263,7 +263,13 @@ export function refactorThisItems( go = () => introduceFallback(view, INTRODUCE[r.id]!, answer.status === "notReady" ? "notReady" : "error"); if (!go) continue; const exec = go; - items.push({ id: r.id, label: r.label, shortcut: shortcutLabel(r.action), run: () => void exec() }); + items.push({ + id: r.id, + label: r.label, + section: r.section, + shortcut: shortcutLabel(r.action), + run: () => void exec(), + }); } other.forEach((a, i) => items.push({ @@ -326,6 +332,7 @@ export async function refactorThis(view: EditorView, rename: (view: EditorView) anchor: caretAnchor(view, state.selection.main.head), title: "Refactor This", items, + compact: true, numbered: true, }); } @@ -338,6 +345,7 @@ export function showNothingHere( kind: "list", anchor, title: "Refactor This", + compact: true, items: [{ id: "nothing", label: "Nothing here", disabled: "No refactoring applies here", run: () => {} }], }); } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 7bbbc10d0..77d73a81d 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2646,6 +2646,7 @@ "Delete…": "Delete…", "Previous Definition": "Previous Definition", "Next Definition": "Next Definition", + "Extract/Introduce": "Extract/Introduce", "Configure {name}…": "Configure {name}…", "Check the system Trash for these items. {names}": "Check the system Trash for these items. {names}", "Git User Name Is Not Defined": "Git User Name Is Not Defined", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index df388fad9..86f8cc39a 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -709,6 +709,7 @@ "Unwrap/Remove…": "解包/移除…", "Basic": "基本补全", "Quick Definition": "快速定义", + "Extract/Introduce": "提取/引入", "Reformat File…": "重新格式化文件…", "Go to Declaration or Usages": "转到声明或用法", "Go to Implementation(s)": "转到实现",