дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
feat(refactor): Extract Type Alias and Extract Interface for TypeScript (#6040)
tsserver's "Extract to type alias" and "Extract to interface" were reachable only as unnamed server items in Refactor This, and Refactor > Extract Interface… worked only in Java. In TS/JS files, Extract Interface… now runs tsserver's "Extract to interface" (Java keeps the jdtls dialog). The new Refactor > Extract Type Alias… runs "Extract to type alias" ("Extract to typedef" in JavaScript). The new type is then renamed in place, as Introduce Variable does. When tsserver offers no such action, a hint says why. classifyAction maps these tsserver titles so Refactor This lists them under Extract/Introduce. The menu item now lives in ide-host's menu spec.
Closes #6014
Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
1 джерело
25d1046af0
коміт
72b0c7c48c
24 files changed
+293
-31
No files matched your search
@@ -587,6 +587,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("refactor.extractParameter", "Introduce Parameter…"),
|
||||
act("refactor.extractMethod", "Extract Method…"),
|
||||
act("refactor.extractInterface", "Extract Interface…"),
|
||||
act("refactor.extractTypeAlias", "Extract Type Alias…"),
|
||||
act("refactor.inline", "Inline…"),
|
||||
SEP,
|
||||
act("refactor.pullMembersUp", "Pull Members Up…"),
|
||||
|
||||
@@ -24,7 +24,8 @@ The **Refactor** menu has IntelliJ IDEA's refactorings with their usual shortcut
|
||||
| **Introduce Field…** | `⌥⌘F` | `Ctrl+Alt+F` | Language server |
|
||||
| **Introduce Parameter…** | `⌥⌘P` | `Ctrl+Alt+P` | Language server |
|
||||
| **Extract Method…** | `⌥⌘M` | `Ctrl+Alt+M` | Language server |
|
||||
| **Extract Interface…** | — | — | Java |
|
||||
| **Extract Interface…** | — | — | Java (dialog); TypeScript: language server |
|
||||
| **Extract Type Alias…** | — | — | TypeScript, JavaScript (`@typedef`): language server |
|
||||
| **Inline…** | `⌥⌘N` | `Ctrl+Alt+N` | Language server |
|
||||
| **Move…** | `F6` | `F6` | Language server (symbols); the IDE (files and folders) |
|
||||
| **Safe Delete…** | `⌘⌦` | `Alt+Delete` | The IDE, using the server's references |
|
||||
@@ -87,6 +88,8 @@ These move fields and methods between a class and its superclasses or subclasses
|
||||
|
||||
In Java, **Refactor › Extract Interface…** creates an interface from the class of the current file. In the dialog, enter the interface name, choose its package and check the methods (and constants) it should declare. **Refactor** creates the interface, makes the class implement it, replaces the class with the interface wherever that is possible, and opens the new file; **Preview** lists the changes first.
|
||||
|
||||
In TypeScript, select an object type literal (for example `{ name: string; age: number }`) and choose **Refactor › Extract Interface…**: the language server declares an `interface` for it and uses it in its place. **Refactor › Extract Type Alias…** does the same with a `type` declaration for any selected type, and in JavaScript adds a JSDoc `@typedef`. Afterwards the new name is renamed in place, as after **Introduce Variable…**. When the server has nothing to extract at the selection, the editor says so.
|
||||
|
||||
## Change Signature
|
||||
|
||||
In Java, **Change Signature…** (`⌘F6`) on a method opens a dialog to change its visibility, return type and name, and to add, remove and reorder its parameters. A new parameter needs a default value, which is passed at every existing call; **Delegate via overloading method** keeps the old signature as an overload that calls the new one. The preview line shows the resulting declaration. **Refactor** updates the method, its overrides and all calls in one step; **Preview** lists the changes first. In other languages it appears when the server offers a signature rewrite as a code action.
|
||||
|
||||
@@ -15,21 +15,22 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
|
||||
|
||||
## 可用的重构
|
||||
|
||||
| 重构 | macOS | Windows / Linux | 实现方式 |
|
||||
| ------------- | ----- | --------------- | --------------------------------------- |
|
||||
| **重命名…** | `⇧F6` | `Shift+F6` | 语言服务器;局部变量没有服务器也可以 |
|
||||
| **更改签名…** | `⌘F6` | `Ctrl+F6` | Java(对话框);其他语言:语言服务器 |
|
||||
| **引入变量…** | `⌥⌘V` | `Ctrl+Alt+V` | 语言服务器;简单情况没有服务器也可以 |
|
||||
| **引入常量…** | `⌥⌘C` | `Ctrl+Alt+C` | 语言服务器;简单情况没有服务器也可以 |
|
||||
| **引入字段…** | `⌥⌘F` | `Ctrl+Alt+F` | 语言服务器 |
|
||||
| **引入参数…** | `⌥⌘P` | `Ctrl+Alt+P` | 语言服务器 |
|
||||
| **提取方法…** | `⌥⌘M` | `Ctrl+Alt+M` | 语言服务器 |
|
||||
| **提取接口…** | — | — | Java |
|
||||
| **内联…** | `⌥⌘N` | `Ctrl+Alt+N` | 语言服务器 |
|
||||
| **移动…** | `F6` | `F6` | 语言服务器(符号);IDE(文件和文件夹) |
|
||||
| **安全删除…** | `⌘⌦` | `Alt+Delete` | IDE,借助服务器查找引用 |
|
||||
| **上拉成员…** | — | — | Java;PHP(使用 Phoxite) |
|
||||
| **下推成员…** | — | — | Java;PHP(使用 Phoxite) |
|
||||
| 重构 | macOS | Windows / Linux | 实现方式 |
|
||||
| ----------------- | ----- | --------------- | ------------------------------------------------ |
|
||||
| **重命名…** | `⇧F6` | `Shift+F6` | 语言服务器;局部变量没有服务器也可以 |
|
||||
| **更改签名…** | `⌘F6` | `Ctrl+F6` | Java(对话框);其他语言:语言服务器 |
|
||||
| **引入变量…** | `⌥⌘V` | `Ctrl+Alt+V` | 语言服务器;简单情况没有服务器也可以 |
|
||||
| **引入常量…** | `⌥⌘C` | `Ctrl+Alt+C` | 语言服务器;简单情况没有服务器也可以 |
|
||||
| **引入字段…** | `⌥⌘F` | `Ctrl+Alt+F` | 语言服务器 |
|
||||
| **引入参数…** | `⌥⌘P` | `Ctrl+Alt+P` | 语言服务器 |
|
||||
| **提取方法…** | `⌥⌘M` | `Ctrl+Alt+M` | 语言服务器 |
|
||||
| **提取接口…** | — | — | Java(对话框);TypeScript:语言服务器 |
|
||||
| **提取类型别名…** | — | — | TypeScript、JavaScript(`@typedef`):语言服务器 |
|
||||
| **内联…** | `⌥⌘N` | `Ctrl+Alt+N` | 语言服务器 |
|
||||
| **移动…** | `F6` | `F6` | 语言服务器(符号);IDE(文件和文件夹) |
|
||||
| **安全删除…** | `⌘⌦` | `Alt+Delete` | IDE,借助服务器查找引用 |
|
||||
| **上拉成员…** | — | — | Java;PHP(使用 Phoxite) |
|
||||
| **下推成员…** | — | — | Java;PHP(使用 Phoxite) |
|
||||
|
||||
## 重命名
|
||||
|
||||
@@ -80,6 +81,8 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
|
||||
|
||||
在 Java 中,**重构 › 提取接口…** 会从当前文件的类创建一个接口。在对话框中输入接口名称,选择所在软件包,并勾选接口要声明的方法(以及常量)。**重构** 会创建接口、让该类实现它、在可行的地方把对该类的使用替换为接口,并打开新文件;**预览** 会先列出所有改动。
|
||||
|
||||
在 TypeScript 中,选中一个对象类型字面量(例如 `{ name: string; age: number }`)后选择 **重构 › 提取接口…**,语言服务器会为它声明一个 `interface` 并在原处使用它。**重构 › 提取类型别名…** 对任意选中的类型做同样的事,生成 `type` 声明;在 JavaScript 中则添加 JSDoc `@typedef`。完成后会就地重命名新名称,与 **引入变量…** 之后一样。如果服务器在选区处没有可提取的内容,编辑器会给出提示。
|
||||
|
||||
## 更改签名
|
||||
|
||||
在 Java 方法上执行 **更改签名…**(`⌘F6`)会打开对话框,可以修改可见性、返回类型和方法名,添加、删除和调整形参顺序。新形参需要填写默认值,所有已有调用处都会传入这个值;勾选 **通过重载方法委托** 会保留旧签名作为重载并调用新方法。签名预览显示修改后的声明。**重构** 会一次更新方法本身、覆盖它的方法和所有调用;**预览** 先列出改动。其他语言在服务器把签名重写作为代码操作提供时才会出现。
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const file = "/dev/acme-api/shapes.ts";
|
||||
const literal = "{ width: number; height: number }";
|
||||
const text = `export function area(shape: ${literal}): number {\n return shape.width * shape.height;\n}\n`;
|
||||
|
||||
/** Opens `file`, stubs tsserver with `actions` (titles and kinds as typescript-language-server reports them) and selects the type literal. */
|
||||
async function open(page: Page, actions: { title: string; kind: string; declaration: string }[]) {
|
||||
await page.evaluate(
|
||||
async ({ file, text }) => {
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
(await import(/* @vite-ignore */ backend)).docBackend().files.set(file, text);
|
||||
const contributions = "/src/workbench/contributions.ts";
|
||||
await (await import(/* @vite-ignore */ contributions)).editorService().openFile(file, { focus: true });
|
||||
},
|
||||
{ file, text },
|
||||
);
|
||||
const content = page.locator(".cm-editor .cm-content").first();
|
||||
await expect(content).toContainText("export function area");
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
({ actions, literal }) => {
|
||||
const toAction = (a: (typeof actions)[number]) => ({
|
||||
title: a.title,
|
||||
kind: a.kind,
|
||||
isPreferred: false,
|
||||
disabledReason: null,
|
||||
edit: null,
|
||||
command: null,
|
||||
data: a.declaration,
|
||||
server: 1,
|
||||
});
|
||||
window.__ipc.handlers.lsp_code_action_query = () => ({ actions: actions.map(toAction), advertisedKinds: null });
|
||||
window.__ipc.handlers.lsp_resolve_code_action = (args) => args.action;
|
||||
// tsserver's edit: the declaration above the function, its name in place of the literal.
|
||||
window.__ipc.handlers.lsp_execute_code_action = async (args) => {
|
||||
const api = "/src/editor/api.ts";
|
||||
const { view } = (await import(/* @vite-ignore */ api)).activeEditor();
|
||||
const doc = view.state.doc.toString();
|
||||
const from = doc.indexOf(literal);
|
||||
view.dispatch({
|
||||
changes: [
|
||||
{ from: 0, insert: `${(args.action as { data: string }).data}\n\n` },
|
||||
{ from, to: from + literal.length, insert: "NewType" },
|
||||
],
|
||||
});
|
||||
return [];
|
||||
};
|
||||
},
|
||||
{ actions, literal },
|
||||
);
|
||||
await page.evaluate(
|
||||
async ({ literal }) => {
|
||||
const api = "/src/editor/api.ts";
|
||||
const { view } = (await import(/* @vite-ignore */ api)).activeEditor();
|
||||
const from = view.state.doc.toString().indexOf(literal);
|
||||
view.dispatch({ selection: { anchor: from, head: from + literal.length } });
|
||||
},
|
||||
{ literal },
|
||||
);
|
||||
return content;
|
||||
}
|
||||
|
||||
async function refactorMenu(page: Page, content: ReturnType<Page["locator"]>, item: string) {
|
||||
await content
|
||||
.locator(".cm-line")
|
||||
.first()
|
||||
.click({ button: "right", position: { x: 260, y: 8 } });
|
||||
await page.getByRole("menuitem", { name: "Refactor", exact: true }).hover();
|
||||
await page.getByRole("menuitem", { name: new RegExp(`^${item}`) }).click();
|
||||
}
|
||||
|
||||
test("Extract Type Alias… declares a type from the selection and renames it in place", async ({ workbench: page }) => {
|
||||
const content = await open(page, [
|
||||
{ title: "Extract to type alias", kind: "refactor.extract.type", declaration: `type NewType = ${literal};` },
|
||||
{
|
||||
title: "Extract to interface",
|
||||
kind: "refactor.extract.interface",
|
||||
declaration: "interface NewType {\n width: number;\n height: number;\n}",
|
||||
},
|
||||
]);
|
||||
await refactorMenu(page, content, "Extract Type Alias…");
|
||||
await expect(content).toContainText(`type NewType = ${literal};`);
|
||||
await expect(content.locator(".cm-lsp-inplace-primary")).toHaveText("NewType");
|
||||
await page.keyboard.type("Size");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(content.locator(".cm-lsp-inplace")).toHaveCount(0);
|
||||
await expect(content).toContainText(`type Size = ${literal};`);
|
||||
await expect(content).toContainText("area(shape: Size)");
|
||||
});
|
||||
|
||||
test("Extract Interface… in TypeScript runs tsserver's Extract to interface", async ({ workbench: page }) => {
|
||||
const content = await open(page, [
|
||||
{ title: "Extract to type alias", kind: "refactor.extract.type", declaration: `type NewType = ${literal};` },
|
||||
{
|
||||
title: "Extract to interface",
|
||||
kind: "refactor.extract.interface",
|
||||
declaration: "interface NewType {\n width: number;\n height: number;\n}",
|
||||
},
|
||||
]);
|
||||
await refactorMenu(page, content, "Extract Interface…");
|
||||
await expect(content).toContainText("interface NewType {");
|
||||
await expect(content.locator(".cm-lsp-inplace-primary")).toHaveText("NewType");
|
||||
});
|
||||
|
||||
test("says why when tsserver has no type to extract at the selection", async ({ workbench: page }) => {
|
||||
const content = await open(page, []);
|
||||
await refactorMenu(page, content, "Extract Interface…");
|
||||
await expect(page.getByRole("status")).toHaveText(
|
||||
"Cannot perform refactoring. Selected block should represent an object type",
|
||||
);
|
||||
});
|
||||
@@ -1012,6 +1012,7 @@ export class EditorController implements SlotHost {
|
||||
{ kind: "action", action: "refactor.extractConstant" },
|
||||
{ kind: "action", action: "refactor.extractMethod" },
|
||||
{ kind: "action", action: "refactor.extractInterface" },
|
||||
{ kind: "action", action: "refactor.extractTypeAlias" },
|
||||
{ kind: "action", action: "refactor.inline" },
|
||||
{ kind: "action", action: "refactor.pullMembersUp" },
|
||||
{ kind: "action", action: "refactor.pushMembersDown" },
|
||||
|
||||
@@ -448,6 +448,9 @@ export function registerLspActions(): () => void {
|
||||
editorAction("refactor.extractInterface", "Extract Interface…", "Refactor", (v) =>
|
||||
runRefactoring(v, "extractInterface"),
|
||||
),
|
||||
editorAction("refactor.extractTypeAlias", "Extract Type Alias…", "Refactor", (v) =>
|
||||
runRefactoring(v, "extractTypeAlias"),
|
||||
),
|
||||
editorAction("refactor.move", "Move…", "Refactor", (v) => runRefactoring(v, "move")),
|
||||
editorAction("refactor.changeSignature", "Change Signature…", "Refactor", (v) =>
|
||||
runRefactoring(v, "changeSignature"),
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
* IDEA's refactorings and how language-server code actions map onto them:
|
||||
* `refactor.extract.*` → Extract Method / Introduce Variable…, `refactor.inline*`
|
||||
* → Inline, `refactor.move*` → Move, signature rewrites → Change Signature.
|
||||
* Pull Members Up / Push Members Down come from the Java extension, Extract Interface from jdtls
|
||||
* requests, not code actions.
|
||||
* Pull Members Up / Push Members Down come from the Java extension, Java's Extract Interface from
|
||||
* jdtls requests, not code actions; tsserver's "Extract to interface / type alias" are code actions.
|
||||
* Pure; used by Refactor This (⌃T) and the Refactor menu actions.
|
||||
*/
|
||||
import type { CodeAction } from "@/bindings";
|
||||
@@ -19,6 +19,7 @@ export type RefactoringId =
|
||||
| "extractField"
|
||||
| "extractParameter"
|
||||
| "extractInterface"
|
||||
| "extractTypeAlias"
|
||||
| "inline"
|
||||
| "pullMembersUp"
|
||||
| "pushMembersDown";
|
||||
@@ -104,8 +105,17 @@ export const REFACTORINGS: readonly Refactoring[] = [
|
||||
action: "refactor.extractInterface",
|
||||
label: "Extract Interface…",
|
||||
section: EXTRACT,
|
||||
kind: null,
|
||||
reason: () => "Caret should be inside a class",
|
||||
// Java runs it through the dialog; TypeScript through tsserver's "Extract to interface".
|
||||
kind: "refactor.extract",
|
||||
reason: () => "Selected block should represent an object type",
|
||||
},
|
||||
{
|
||||
id: "extractTypeAlias",
|
||||
action: "refactor.extractTypeAlias",
|
||||
label: "Extract Type Alias…",
|
||||
section: EXTRACT,
|
||||
kind: "refactor.extract",
|
||||
reason: () => "Selected block should represent a type",
|
||||
},
|
||||
{
|
||||
id: "inline",
|
||||
@@ -169,6 +179,9 @@ export function classifyAction(action: Pick<CodeAction, "kind" | "title">): Refa
|
||||
if (kindIs(kind, "refactor.extract") || (generic && /^(extract|introduce)\b/i.test(title))) {
|
||||
const sub = kind.slice("refactor.extract".length);
|
||||
const is = (re: RegExp) => re.test(sub) || re.test(title);
|
||||
// tsserver ("Extract to typedef" is its JSDoc form in JavaScript).
|
||||
if (/^extract to (type alias|typedef)$/i.test(title)) return "extractTypeAlias";
|
||||
if (/^extract to interface$/i.test(title)) return "extractInterface";
|
||||
if (
|
||||
/^(extract|introduce)( (in)?to)?( an?)? (type\b|typedef|interface|struct|enum|trait|superclass|module)/i.test(
|
||||
title,
|
||||
|
||||
@@ -145,11 +145,15 @@ describe("catalog", () => {
|
||||
expect(c("Change signature", "refactor.changeSignature")).toBe("changeSignature");
|
||||
expect(c("Convert parameters to destructured object", "refactor.rewrite.parameters.toDestructured")).toBeNull();
|
||||
expect(c("Extract type alias", "refactor.extract.type")).toBeNull();
|
||||
expect(c("Extract to type alias", "refactor.extract.type")).toBe("extractTypeAlias");
|
||||
expect(c("Extract to typedef", "refactor.extract.typedef")).toBe("extractTypeAlias");
|
||||
expect(c("Extract to interface", "refactor.extract.interface")).toBe("extractInterface");
|
||||
expect(c("Extract to interface", "refactor")).toBe("extractInterface");
|
||||
expect(c("Remove unused", "quickfix")).toBeNull();
|
||||
// typescript-language-server reports plain `refactor` for everything.
|
||||
expect(c("Extract to inner function in function 'formatMoney'", "refactor")).toBe("extractMethod");
|
||||
expect(c("Extract to constant in enclosing scope", "refactor")).toBe("extractVariable");
|
||||
expect(c("Extract to type alias", "refactor")).toBeNull();
|
||||
expect(c("Extract to type alias", "refactor")).toBe("extractTypeAlias");
|
||||
expect(c("Extract type as type alias", "refactor.extract")).toBeNull();
|
||||
expect(c("Extract struct from enum variant", "refactor.extract")).toBeNull();
|
||||
expect(c("Move to a new file", "refactor")).toBe("move");
|
||||
@@ -418,6 +422,67 @@ describe("Refactor menu actions", () => {
|
||||
expect(temporaryHighlights(v)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("run tsserver's Extract to type alias / interface in TypeScript and rename the new type", async () => {
|
||||
const text = "function f(p: { a: string }) {}";
|
||||
const literal = "{ a: string }";
|
||||
const v = editor(text, "typescript");
|
||||
v.dispatch({ selection: { anchor: text.indexOf(literal), head: text.indexOf(literal) + literal.length } });
|
||||
query = answer([
|
||||
action("Extract to interface", "refactor.extract.interface"),
|
||||
action("Extract to type alias", "refactor.extract.type"),
|
||||
]);
|
||||
onApply = () =>
|
||||
v.dispatch({
|
||||
changes: [
|
||||
{ from: 0, insert: "type NewType = { a: string };\n\n" },
|
||||
{ from: text.indexOf(literal), to: text.indexOf(literal) + literal.length, insert: "NewType" },
|
||||
],
|
||||
});
|
||||
await runRefactoring(v, "extractTypeAlias");
|
||||
expect(lspCodeActionQuery.mock.calls[0]![3]).toEqual(["refactor"]);
|
||||
expect(lspResolveCodeAction.mock.calls[0]![1].title).toBe("Extract to type alias");
|
||||
await vi.waitFor(() => expect(inplaceSession(v.state)).not.toBeNull());
|
||||
expect(inplaceSession(v.state)!.oldName).toBe("NewType");
|
||||
|
||||
lspResolveCodeAction.mockClear();
|
||||
onApply = null;
|
||||
const w = editor(text, "typescriptreact");
|
||||
w.dispatch({ selection: { anchor: text.indexOf(literal), head: text.indexOf(literal) + literal.length } });
|
||||
await runRefactoring(w, "extractInterface");
|
||||
expect(lspResolveCodeAction.mock.calls[0]![1].title).toBe("Extract to interface");
|
||||
expect(startExtractInterface).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("say why when tsserver offers no type extraction, and keep Extract Interface on Java's dialog", async () => {
|
||||
query = answer([action("Extract to constant in enclosing scope", "refactor.extract.constant")]);
|
||||
const ts = editor("const x = 1;", "typescript");
|
||||
await runRefactoring(ts, "extractTypeAlias");
|
||||
expect(showHint).toHaveBeenLastCalledWith(ts, "Cannot perform refactoring. Selected block should represent a type");
|
||||
await runRefactoring(ts, "extractInterface");
|
||||
expect(showHint).toHaveBeenLastCalledWith(
|
||||
ts,
|
||||
"Cannot perform refactoring. Selected block should represent an object type",
|
||||
);
|
||||
expect(lspExecuteCodeAction).not.toHaveBeenCalled();
|
||||
|
||||
const rs = editor();
|
||||
await runRefactoring(rs, "extractTypeAlias");
|
||||
expect(showHint).toHaveBeenLastCalledWith(
|
||||
rs,
|
||||
"Cannot perform refactoring. Extract Type Alias is not supported for Rust",
|
||||
);
|
||||
await runRefactoring(rs, "extractInterface");
|
||||
expect(showHint).toHaveBeenLastCalledWith(
|
||||
rs,
|
||||
"Cannot perform refactoring. Extract Interface is not supported for Rust",
|
||||
);
|
||||
|
||||
lspCodeActionQuery.mockClear();
|
||||
await runRefactoring(editor("class A {}", "java"), "extractInterface");
|
||||
expect(startExtractInterface).toHaveBeenCalledOnce();
|
||||
expect(lspCodeActionQuery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rename the introduced name in place after the server's edit", async () => {
|
||||
const text = "fn main() { let total = price * 2; }";
|
||||
const v = editor(text);
|
||||
|
||||
@@ -59,6 +59,9 @@ const REFACTORING_SERVERS: Readonly<Record<string, { server: string; ids: Readon
|
||||
},
|
||||
};
|
||||
|
||||
/** Languages where tsserver offers "Extract to interface" and "Extract to type alias" (typedef in JavaScript). */
|
||||
const TYPE_EXTRACT_LANGUAGES = new Set(["typescript", "typescriptreact", "javascript", "javascriptreact"]);
|
||||
|
||||
/** Outcome of the server query: its answer, or why there is none. */
|
||||
export type ServerAnswer =
|
||||
| { status: "ok"; query: CodeActionQuery }
|
||||
@@ -192,9 +195,20 @@ export async function runRefactoring(view: EditorView, id: RefactoringId): Promi
|
||||
await startChangeSignature(view);
|
||||
return;
|
||||
}
|
||||
if (id === "extractInterface") {
|
||||
if (EXTRACT_INTERFACE_LANGUAGES.has(ctx.language)) await startExtractInterface(view);
|
||||
else showHint(view, cannotPerform(`Extract Interface is not supported for ${await languageName(ctx.language)}`));
|
||||
if (id === "extractInterface" && EXTRACT_INTERFACE_LANGUAGES.has(ctx.language)) {
|
||||
await startExtractInterface(view);
|
||||
return;
|
||||
}
|
||||
if ((id === "extractInterface" || id === "extractTypeAlias") && !TYPE_EXTRACT_LANGUAGES.has(ctx.language)) {
|
||||
const lang = await languageName(ctx.language);
|
||||
showHint(
|
||||
view,
|
||||
cannotPerform(
|
||||
id === "extractInterface"
|
||||
? `Extract Interface is not supported for ${lang}`
|
||||
: `Extract Type Alias is not supported for ${lang}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
// IDEA picks the expression first (and the server then extracts exactly that one).
|
||||
|
||||
@@ -45,6 +45,23 @@ describe("introducedName", () => {
|
||||
expect(introducedName(before, after)?.name).toBe("fun_name");
|
||||
});
|
||||
|
||||
it("finds tsserver's extracted type alias and interface", () => {
|
||||
const before = "function f(p: { a: string; b: number }) {}\n";
|
||||
const alias = "type NewType = { a: string; b: number };\n\nfunction f(p: NewType) {}\n";
|
||||
expect(spansText(alias, introducedName(before, alias)!.spans)).toEqual(["NewType", "NewType"]);
|
||||
const iface = "interface NewType {\n a: string;\n b: number;\n}\n\nfunction f(p: NewType) {}\n";
|
||||
expect(introducedName(before, iface)?.name).toBe("NewType");
|
||||
});
|
||||
|
||||
it("finds tsserver's unique NewType_1 when NewType is taken", () => {
|
||||
// typescript's Extract to typedef output, verbatim: `typedef` is inserted twice too.
|
||||
const before =
|
||||
"/** @typedef {object} NewType */\n\n/** @param {{ a: number, b: number, c: number }} p */\nfunction f(p) {}\n";
|
||||
const after =
|
||||
"/**\n* @typedef {{a: number;b: number;c: number;}} NewType_1\n*/\n\n/** @typedef {object} NewType */\n\n/** @param {NewType_1} p */\nfunction f(p) {}\n";
|
||||
expect(spansText(after, introducedName(before, after)!.spans)).toEqual(["NewType_1", "NewType_1"]);
|
||||
});
|
||||
|
||||
it("is null without a new name used twice", () => {
|
||||
expect(introducedName("a + b", "(a + b)")).toBeNull();
|
||||
expect(introducedName("x", "x")).toBeNull();
|
||||
|
||||
@@ -40,7 +40,12 @@ export const EXPRESSION_REFACTORINGS: ReadonlySet<RefactoringId> = new Set([
|
||||
]);
|
||||
|
||||
/** Refactorings whose result is a new name renamed in place afterwards. */
|
||||
const NAMING_REFACTORINGS: ReadonlySet<RefactoringId> = new Set([...EXPRESSION_REFACTORINGS, "extractMethod"]);
|
||||
const NAMING_REFACTORINGS: ReadonlySet<RefactoringId> = new Set([
|
||||
...EXPRESSION_REFACTORINGS,
|
||||
"extractMethod",
|
||||
"extractInterface",
|
||||
"extractTypeAlias",
|
||||
]);
|
||||
|
||||
export function introducesName(id: RefactoringId | null): boolean {
|
||||
return !!id && NAMING_REFACTORINGS.has(id);
|
||||
@@ -184,7 +189,8 @@ function insertedTokens(before: Token[], after: Token[]): Token[] {
|
||||
}
|
||||
|
||||
/** Names servers give new declarations before the user names them. */
|
||||
const SERVER_DEFAULT = /^(new[A-Z_]\w*|newLocal\w*|var_name\d*|fun_name\d*|extracted\w*|new_\w+|value\d*)$/;
|
||||
const SERVER_DEFAULT =
|
||||
/^(new[A-Z_]\w*|NewType(?:_\d+)?|newLocal\w*|var_name\d*|fun_name\d*|extracted\w*|new_\w+|value\d*)$/;
|
||||
|
||||
/**
|
||||
* The name a refactoring introduced, and every place the edit wrote it, from
|
||||
|
||||
@@ -204,6 +204,7 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
"refactor.move": ["F6"],
|
||||
"refactor.safeDelete": ["Meta+Delete"],
|
||||
"refactor.extractInterface": [],
|
||||
"refactor.extractTypeAlias": [],
|
||||
"refactor.pullMembersUp": [],
|
||||
"refactor.pushMembersDown": [],
|
||||
|
||||
|
||||
@@ -205,6 +205,7 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
"refactor.move": ["F6"],
|
||||
"refactor.safeDelete": ["Alt+Delete"],
|
||||
"refactor.extractInterface": [],
|
||||
"refactor.extractTypeAlias": [],
|
||||
"refactor.pullMembersUp": [],
|
||||
"refactor.pushMembersDown": [],
|
||||
|
||||
|
||||
@@ -209,6 +209,7 @@ export const vscodeMacos: Record<string, string[]> = {
|
||||
"refactor.move": [],
|
||||
"refactor.safeDelete": [],
|
||||
"refactor.extractInterface": [],
|
||||
"refactor.extractTypeAlias": [],
|
||||
"refactor.pullMembersUp": [],
|
||||
"refactor.pushMembersDown": [],
|
||||
|
||||
|
||||
@@ -304,6 +304,7 @@
|
||||
"menu.refactor.extractConstant": "Introduce Constant…",
|
||||
"menu.refactor.extractField": "Introduce Field…",
|
||||
"menu.refactor.extractInterface": "Extract Interface…",
|
||||
"menu.refactor.extractTypeAlias": "Extract Type Alias…",
|
||||
"menu.refactor.extractMethod": "Extract Method…",
|
||||
"menu.refactor.extractParameter": "Introduce Parameter…",
|
||||
"menu.refactor.extractVariable": "Introduce Variable…",
|
||||
|
||||
@@ -304,6 +304,7 @@
|
||||
"menu.refactor.extractConstant": "Ввести константу…",
|
||||
"menu.refactor.extractField": "Ввести поле…",
|
||||
"menu.refactor.extractInterface": "Извлечь интерфейс…",
|
||||
"menu.refactor.extractTypeAlias": "Извлечь псевдоним типа…",
|
||||
"menu.refactor.extractMethod": "Извлечь метод…",
|
||||
"menu.refactor.extractParameter": "Ввести параметр…",
|
||||
"menu.refactor.extractVariable": "Ввести переменную…",
|
||||
|
||||
@@ -2971,10 +2971,13 @@
|
||||
"Interface name should differ from the class name": "Interface name should differ from the class name",
|
||||
"Select the members to form the interface": "Select the members to form the interface",
|
||||
"The class has no members to form an interface": "The class has no members to form an interface",
|
||||
"Caret should be inside a class": "Caret should be inside a class",
|
||||
"Extract Interface from '{name}'": "Extract Interface from '{name}'",
|
||||
"The interface could not be extracted": "The interface could not be extracted",
|
||||
"Extract Interface is not supported for {name}": "Extract Interface is not supported for {name}",
|
||||
"Extract Type Alias…": "Extract Type Alias…",
|
||||
"Extract Type Alias is not supported for {name}": "Extract Type Alias is not supported for {name}",
|
||||
"Selected block should represent a type": "Selected block should represent a type",
|
||||
"Selected block should represent an object type": "Selected block should represent an object type",
|
||||
"Package for new interface": "Package for new interface",
|
||||
"Untitled files were not saved": "Untitled files were not saved",
|
||||
"Missing blank line between subject and body": "Missing blank line between subject and body",
|
||||
|
||||
@@ -9262,10 +9262,13 @@
|
||||
"Interface name should differ from the class name": "Имя интерфейса должно отличаться от имени класса",
|
||||
"Select the members to form the interface": "Выберите члены для формирования интерфейса",
|
||||
"The class has no members to form an interface": "В классе нет членов для формирования интерфейса",
|
||||
"Caret should be inside a class": "Каретка должна находиться внутри класса",
|
||||
"Extract Interface from '{name}'": "Извлечь интерфейс из '{name}'",
|
||||
"The interface could not be extracted": "Не удалось извлечь интерфейс",
|
||||
"Extract Interface is not supported for {name}": "Извлечение интерфейса не поддерживается для {name}",
|
||||
"Extract Type Alias…": "Извлечь псевдоним типа…",
|
||||
"Extract Type Alias is not supported for {name}": "Извлечение псевдонима типа не поддерживается для {name}",
|
||||
"Selected block should represent a type": "Выбранный блок должен представлять тип",
|
||||
"Selected block should represent an object type": "Выбранный блок должен представлять объектный тип",
|
||||
"Package for new interface": "Пакет для нового интерфейса",
|
||||
"Untitled files were not saved": "Безымянные файлы не были сохранены",
|
||||
"Missing blank line between subject and body": "Отсутствует пустая строка между заголовком и телом сообщения",
|
||||
|
||||
@@ -2272,10 +2272,13 @@
|
||||
"Interface name should differ from the class name": "Arayüz adı sınıf adından farklı olmalıdır",
|
||||
"Select the members to form the interface": "Arayüzü oluşturacak üyeleri seçin",
|
||||
"The class has no members to form an interface": "Sınıfta arayüz oluşturacak üye bulunmuyor",
|
||||
"Caret should be inside a class": "İmleç bir sınıfın içinde olmalıdır",
|
||||
"Extract Interface from '{name}'": "'{name}' Sınıfından Arayüz Çıkar",
|
||||
"The interface could not be extracted": "Arayüz çıkarılamadı",
|
||||
"Extract Interface is not supported for {name}": "{name} için Arayüz Çıkar desteklenmiyor",
|
||||
"Extract Type Alias…": "Tür Takma Adı Çıkar…",
|
||||
"Extract Type Alias is not supported for {name}": "{name} için Tür Takma Adı Çıkar desteklenmiyor",
|
||||
"Selected block should represent a type": "Seçili blok bir türü temsil etmelidir",
|
||||
"Selected block should represent an object type": "Seçili blok bir nesne türünü temsil etmelidir",
|
||||
"Package for new interface": "Yeni arayüzün paketi",
|
||||
"Untitled files were not saved": "Adsız dosyalar kaydedilmedi",
|
||||
"Missing blank line between subject and body": "Konu ile gövde arasında boş satır eksik",
|
||||
|
||||
@@ -8725,10 +8725,13 @@
|
||||
"Interface name should differ from the class name": "介面名稱應與類別名稱不同",
|
||||
"Select the members to form the interface": "選擇形成介面的成員",
|
||||
"The class has no members to form an interface": "該類別沒有可形成介面的成員",
|
||||
"Caret should be inside a class": "游標應位於類別中",
|
||||
"Extract Interface from '{name}'": "從 '{name}' 提取介面",
|
||||
"The interface could not be extracted": "無法提取介面",
|
||||
"Extract Interface is not supported for {name}": "{name} 不支援提取介面",
|
||||
"Extract Type Alias…": "提取型別別名…",
|
||||
"Extract Type Alias is not supported for {name}": "{name} 不支援提取型別別名",
|
||||
"Selected block should represent a type": "所選程式碼區塊應為一個型別",
|
||||
"Selected block should represent an object type": "所選程式碼區塊應為一個物件型別",
|
||||
"Package for new interface": "新介面的軟體包",
|
||||
"Untitled files were not saved": "未命名檔案未儲存",
|
||||
"Missing blank line between subject and body": "主題和正文之間缺少空行",
|
||||
|
||||
@@ -9399,10 +9399,13 @@
|
||||
"Interface name should differ from the class name": "接口名称应与类名不同",
|
||||
"Select the members to form the interface": "选择形成接口的成员",
|
||||
"The class has no members to form an interface": "该类没有可形成接口的成员",
|
||||
"Caret should be inside a class": "光标应位于类中",
|
||||
"Extract Interface from '{name}'": "从 '{name}' 提取接口",
|
||||
"The interface could not be extracted": "无法提取接口",
|
||||
"Extract Interface is not supported for {name}": "{name} 不支持提取接口",
|
||||
"Extract Type Alias…": "提取类型别名…",
|
||||
"Extract Type Alias is not supported for {name}": "{name} 不支持提取类型别名",
|
||||
"Selected block should represent a type": "所选代码块应为一个类型",
|
||||
"Selected block should represent an object type": "所选代码块应为一个对象类型",
|
||||
"Package for new interface": "新接口的软件包",
|
||||
"Untitled files were not saved": "未命名文件未保存",
|
||||
"Missing blank line between subject and body": "主题和正文之间缺少空行",
|
||||
|
||||
@@ -301,6 +301,7 @@
|
||||
"menu.refactor.extractConstant": "Sabit Tanımla…",
|
||||
"menu.refactor.extractField": "Alan Tanımla…",
|
||||
"menu.refactor.extractInterface": "Arayüz Çıkar…",
|
||||
"menu.refactor.extractTypeAlias": "Tür Takma Adı Çıkar…",
|
||||
"menu.refactor.extractMethod": "Metot Çıkar…",
|
||||
"menu.refactor.extractParameter": "Parametre Tanımla…",
|
||||
"menu.refactor.extractVariable": "Değişken Tanımla…",
|
||||
|
||||
@@ -301,6 +301,7 @@
|
||||
"menu.refactor.extractConstant": "引入常量…",
|
||||
"menu.refactor.extractField": "引入欄位…",
|
||||
"menu.refactor.extractInterface": "提取介面…",
|
||||
"menu.refactor.extractTypeAlias": "提取型別別名…",
|
||||
"menu.refactor.extractMethod": "提取方法…",
|
||||
"menu.refactor.extractParameter": "引入參數…",
|
||||
"menu.refactor.extractVariable": "引入變數…",
|
||||
|
||||
@@ -304,6 +304,7 @@
|
||||
"menu.refactor.extractConstant": "引入常量…",
|
||||
"menu.refactor.extractField": "引入字段…",
|
||||
"menu.refactor.extractInterface": "提取接口…",
|
||||
"menu.refactor.extractTypeAlias": "提取类型别名…",
|
||||
"menu.refactor.extractMethod": "提取方法…",
|
||||
"menu.refactor.extractParameter": "引入参数…",
|
||||
"menu.refactor.extractVariable": "引入变量…",
|
||||
|
||||
Reference in new issue
Заблокувати користувача