feat(refactor): Extract Interface for Java classes (#3707)

Refactor > Extract Interface… (also in Refactor This) opens a dialog for the class of the current Java file: interface name, package and members. jdtls checks the extraction and computes the edit, which creates the interface, makes the class implement it and uses it where possible; the new file opens afterwards.
This commit is contained in:
l0ng-ai
2026-11-16 15:50:27 +08:00
committed by GitHub
parent 34c81a61e4
commit 4561ae05b2
29 changed files with 811 additions and 15 deletions
+62 -1
View File
@@ -1223,7 +1223,7 @@ pub async fn lsp_change_signature(
}
fn json_argument(args: &str) -> IdeResult<serde_json::Value> {
serde_json::from_str(args).map_err(|e| IdeError::invalid(format!("invalid move arguments: {e}")))
serde_json::from_str(args).map_err(|e| IdeError::invalid(format!("invalid refactoring arguments: {e}")))
}
fn json_strings(values: Vec<serde_json::Value>) -> Vec<String> {
@@ -1289,6 +1289,50 @@ pub async fn lsp_java_move(
.await
}
/// The Java class to extract an interface from: its members and the packages for the interface.
pub async fn lsp_extract_interface_info(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
) -> IdeResult<ExtractInterfaceInfo> {
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = project.lsp.extract_interface_info(doc, pos, cancel).await;
host.end_request(request);
result
}
/// Checks extracting a Java interface and computes its edit without applying it; `destination`
/// is one of the info's packages.
#[allow(clippy::too_many_arguments)]
pub async fn lsp_extract_interface(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
pos: Pos,
members: Vec<String>,
name: String,
destination: String,
confirmation: Option<String>,
) -> IdeResult<ServerRefactored> {
let destination = json_argument(&destination)?;
let project = host.project(window)?;
let cancel = host.begin_request(request);
let result = project.lsp.extract_interface(doc, pos, members, name, destination, confirmation, cancel).await;
host.end_request(request);
let mut extracted = result?;
blocking(move || {
if let Some(edit) = &mut extracted.edit {
project.documents.prepare_workspace_edit(edit)?;
}
Ok(extracted)
})
.await
}
pub async fn lsp_rename(
host: &Host,
window: &str,
@@ -2028,6 +2072,23 @@ pub(crate) fn register(d: &mut Dispatcher) {
)
.await
});
d.add("lsp_extract_interface_info", |c| async move {
lsp_extract_interface_info(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("pos")?).await
});
d.add("lsp_extract_interface", |c| async move {
lsp_extract_interface(
&c.host,
&c.window,
c.arg("request")?,
c.arg("doc")?,
c.arg("pos")?,
c.arg("members")?,
c.arg("name")?,
c.arg("destination")?,
c.arg("confirmation")?,
)
.await
});
d.add("lsp_java_move_destinations", |c| async move {
lsp_java_move_destinations(&c.host, &c.window, c.arg("request")?, c.arg("doc")?, c.arg("kind")?, c.arg("args")?)
.await
+1
View File
@@ -19,6 +19,7 @@ use std::time::{Duration, Instant};
pub(crate) const SERVER: &str = "jdtls";
pub(crate) mod configuration;
mod extract_interface;
mod formatter;
mod hierarchy;
pub(crate) mod jvm_inspect;
@@ -0,0 +1,128 @@
//! Extract Interface through jdtls' own requests: `java/checkExtractInterfaceStatus` lists the
//! members of the file's class an interface can declare and the packages it can go to,
//! `java/getRefactorEdit` (`extractInterface`) creates the interface, makes the class implement
//! it and uses it where possible. The UI picks the name, package and members and applies the edit.
use super::COMMAND_TIMEOUT;
use super::signature::{RefactorEdit, changed};
use crate::types::{ExtractInterfaceInfo, InterfaceMember, ProblemSeverity, RefactoringProblem, ServerRefactored};
use crate::{LspManager, convert};
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, Pos};
use serde::Deserialize;
use serde_json::{Value, json};
const FEATURE: &str = "Extract Interface";
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Status {
#[serde(default)]
members: Vec<InterfaceMember>,
#[serde(default)]
sub_type_name: String,
#[serde(default)]
destination_response: Destinations,
}
#[derive(Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Destinations {
#[serde(default)]
destinations: Vec<Value>,
}
fn info_of(status: Option<Status>) -> IdeResult<ExtractInterfaceInfo> {
let status = status
.filter(|s| !s.sub_type_name.is_empty())
.ok_or_else(|| IdeError::invalid("The file should declare a class"))?;
Ok(ExtractInterfaceInfo {
class_name: status.sub_type_name,
members: status.members,
packages: status.destination_response.destinations.iter().map(Value::to_string).collect(),
})
}
impl LspManager {
/// The class of the file at `doc`, its members and the packages for the interface.
pub async fn extract_interface_info(
&self,
doc: DocId,
pos: Pos,
cancel: CancellationToken,
) -> IdeResult<ExtractInterfaceInfo> {
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
let params = Self::signature_context(&snap, &t, pos);
let status: Option<Status> =
self.call(&t, "java/checkExtractInterfaceStatus", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
info_of(status)
}
/// Checks extracting `members` into the interface `name` in `package` (a package from
/// [`Self::extract_interface_info`]) and computes the edit without applying it.
#[allow(clippy::too_many_arguments)]
pub async fn extract_interface(
&self,
doc: DocId,
pos: Pos,
members: Vec<String>,
name: String,
package: Value,
confirmation: Option<String>,
cancel: CancellationToken,
) -> IdeResult<ServerRefactored> {
let (snap, t) = self.jdtls_target(doc, FEATURE).await?;
let mut params = json!({
"command": "extractInterface",
"context": Self::signature_context(&snap, &t, pos),
"options": { "tabSize": 4, "insertSpaces": true },
"commandArguments": [members, name, package],
});
if let Some(token) = confirmation {
params["confirmationToken"] = json!(token);
}
let answer: Option<RefactorEdit> =
self.call(&t, "java/getRefactorEdit", params, Some(&cancel), COMMAND_TIMEOUT).await?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// jdtls answers nothing when its checks fail, and reports why in a message of its own.
let Some(answer) = answer else {
return Ok(ServerRefactored {
problems: vec![RefactoringProblem {
severity: ProblemSeverity::Fatal,
message: "The interface could not be extracted".to_owned(),
}],
edit: None,
confirmation: None,
});
};
let conv = self.conv(t.enc());
Ok(changed(answer, |e| convert::workspace_edit(&conv, e)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_the_members_and_packages() {
let status: Status = serde_json::from_value(json!({
"members": [
{ "name": "area", "typeName": "double", "parameters": [], "handleIdentifier": "=p/src<a{Shape.java[Shape~area" },
{ "name": "UNIT", "typeName": "int", "handleIdentifier": "=p/src<a{Shape.java[Shape^UNIT" },
],
"subTypeName": "Shape",
"destinationResponse": { "destinations": [{ "displayName": "a", "isParentOfSelectedFile": true }] },
}))
.unwrap();
let info = info_of(Some(status)).unwrap();
assert_eq!(info.class_name, "Shape");
assert_eq!(info.members[0].parameters.as_deref(), Some(&[][..]));
assert_eq!(info.members[1].parameters, None);
assert_eq!(serde_json::from_str::<Value>(&info.packages[0]).unwrap()["displayName"], "a");
assert!(info_of(None).is_err());
}
}
+1 -1
View File
@@ -68,7 +68,7 @@ impl LspManager {
Ok((snap, t))
}
fn signature_context(snap: &DocSnap, t: &Target, pos: Pos) -> Value {
pub(super) fn signature_context(snap: &DocSnap, t: &Target, pos: Pos) -> Value {
let at = snap.position(t, pos);
json!({
"textDocument": { "uri": snap.uri },
+24 -1
View File
@@ -539,7 +539,30 @@ pub struct MethodSignature {
pub exceptions: Vec<SignatureException>,
}
/// A refactoring checked by the server (Change Signature, Move): problems to show, the edit when
/// A member Extract Interface can declare in the new interface.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct InterfaceMember {
pub name: String,
/// The method's return type or the field's type.
pub type_name: String,
/// The method's parameter types; `None` for a field.
pub parameters: Option<Vec<String>>,
/// The server's handle of the member, passed back unchanged.
pub handle_identifier: String,
}
/// What Extract Interface starts from: the file's class, the members the interface can declare and
/// the packages it can go to (as JSON, passed back unchanged).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct ExtractInterfaceInfo {
pub class_name: String,
pub members: Vec<InterfaceMember>,
pub packages: Vec<String>,
}
/// A refactoring checked by the server (Change Signature, Move, Extract Interface): problems to show, the edit when
/// none is fatal, and the token that confirms going on despite warnings.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+5
View File
@@ -24,6 +24,7 @@ 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 |
| **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 |
@@ -82,6 +83,10 @@ In the editor, **Move…** on a symbol runs the server's move refactoring, where
These move fields and methods between a class and its superclasses or subclasses, in Java and, with Phoxite as the PHP server, in PHP (methods, properties and constants). A dialog lets you pick the members and the destination; problems the move would cause are listed in **Problems Detected** before you continue. For Java they are provided by the extension bundled with OpenIDEA, for PHP by Phoxite; they are not available for other languages or other PHP servers.
## Extract Interface
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.
## 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.
+5
View File
@@ -24,6 +24,7 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
| **引入字段…** | `⌥⌘F` | `Ctrl+Alt+F` | 语言服务器 |
| **引入参数…** | `⌥⌘P` | `Ctrl+Alt+P` | 语言服务器 |
| **提取方法…** | `⌥⌘M` | `Ctrl+Alt+M` | 语言服务器 |
| **提取接口…** | — | — | Java |
| **内联…** | `⌥⌘N` | `Ctrl+Alt+N` | 语言服务器 |
| **移动…** | `F6` | `F6` | 语言服务器(符号);IDE(文件和文件夹) |
| **安全删除…** | `⌘⌦` | `Alt+Delete` | IDE,借助服务器查找引用 |
@@ -75,6 +76,10 @@ description: "重命名、引入与提取、内联、移动、更改签名和安
用于在类和它的父类或子类之间移动字段和方法:支持 Java,以及使用 Phoxite 作为 PHP 服务器时的 PHP(方法、属性和常量)。在对话框中选择成员和目标类;移动会引起的问题会先在 **检测到问题** 中列出,再决定是否继续。Java 由 OpenIDEA 自带的扩展提供,PHP 由 Phoxite 提供;其他语言和其他 PHP 服务器不可用。
## 提取接口
在 Java 中,**重构 › 提取接口…** 会从当前文件的类创建一个接口。在对话框中输入接口名称,选择所在软件包,并勾选接口要声明的方法(以及常量)。**重构** 会创建接口、让该类实现它、在可行的地方把对该类的使用替换为接口,并打开新文件;**预览** 会先列出所有改动。
## 更改签名
在 Java 方法上执行 **更改签名…**(`⌘F6`)会打开对话框,可以修改可见性、返回类型和方法名,添加、删除和调整形参顺序。新形参需要填写默认值,所有已有调用处都会传入这个值;勾选 **通过重载方法委托** 会保留旧签名作为重载并调用新方法。签名预览显示修改后的声明。**重构** 会一次更新方法本身、覆盖它的方法和所有调用;**预览** 先列出改动。其他语言在服务器把签名重写作为代码操作提供时才会出现。
+40
View File
@@ -395,6 +395,46 @@ pub async fn lsp_java_move(
ide_host::ops::lsp::lsp_java_move(&state.host, window.label(), request, doc, kind, args, confirmation).await
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_extract_interface_info(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
pos: Pos,
) -> IdeResult<ExtractInterfaceInfo> {
ide_host::ops::lsp::lsp_extract_interface_info(&state.host, window.label(), request, doc, pos).await
}
#[tauri::command]
#[specta::specta]
#[allow(clippy::too_many_arguments)]
pub async fn lsp_extract_interface(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
pos: Pos,
members: Vec<String>,
name: String,
destination: String,
confirmation: Option<String>,
) -> IdeResult<ServerRefactored> {
ide_host::ops::lsp::lsp_extract_interface(
&state.host,
window.label(),
request,
doc,
pos,
members,
name,
destination,
confirmation,
)
.await
}
#[tauri::command]
#[specta::specta]
pub async fn lsp_format(
+2
View File
@@ -304,6 +304,8 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
lsp::lsp_hierarchy_refactor,
lsp::lsp_signature_info,
lsp::lsp_change_signature,
lsp::lsp_extract_interface_info,
lsp::lsp_extract_interface,
lsp::lsp_java_move_destinations,
lsp::lsp_java_source_types,
lsp::lsp_java_move,
+1
View File
@@ -594,6 +594,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("refactor.extractField", "Introduce Field…"),
act("refactor.extractParameter", "Introduce Parameter…"),
act("refactor.extractMethod", "Extract Method…"),
act("refactor.extractInterface", "Extract Interface…"),
act("refactor.inline", "Inline…"),
SEP,
act("refactor.pullMembersUp", "Pull Members Up…"),
+2
View File
@@ -306,6 +306,8 @@ lsp_document_highlights trusted project_host bin
lsp_document_links trusted project_host bindings async
lsp_execute_code_action trusted project_host bindings async
lsp_execute_command trusted project_host bindings async
lsp_extract_interface trusted project_host bindings async
lsp_extract_interface_info trusted project_host bindings async
lsp_format trusted project_host bindings async
lsp_goto trusted project_host bindings async
lsp_goto_implementation trusted project_host bindings async
+24 -1
View File
@@ -644,6 +644,8 @@ export const commands = {
lspHierarchyRefactor: (request: RequestId, doc: DocId, pos: Pos, kind: HierarchyRefactoring, target: string | null, choices: HierarchyChoice[]) => typedError<HierarchyRefactored, IdeError>(__TAURI_INVOKE("lsp_hierarchy_refactor", { request, doc, pos, kind, target, choices })),
lspSignatureInfo: (request: RequestId, doc: DocId, pos: Pos) => typedError<MethodSignature, IdeError>(__TAURI_INVOKE("lsp_signature_info", { request, doc, pos })),
lspChangeSignature: (request: RequestId, doc: DocId, pos: Pos, signature: MethodSignature, delegate: boolean, confirmation: string | null) => typedError<ServerRefactored, IdeError>(__TAURI_INVOKE("lsp_change_signature", { request, doc, pos, signature, delegate, confirmation })),
lspExtractInterfaceInfo: (request: RequestId, doc: DocId, pos: Pos) => typedError<ExtractInterfaceInfo, IdeError>(__TAURI_INVOKE("lsp_extract_interface_info", { request, doc, pos })),
lspExtractInterface: (request: RequestId, doc: DocId, pos: Pos, members: string[], name: string, destination: string, confirmation: string | null) => typedError<ServerRefactored, IdeError>(__TAURI_INVOKE("lsp_extract_interface", { request, doc, pos, members, name, destination, confirmation })),
lspJavaMoveDestinations: (request: RequestId, doc: DocId, kind: string, args: string) => typedError<string[], IdeError>(__TAURI_INVOKE("lsp_java_move_destinations", { request, doc, kind, args })),
lspJavaSourceTypes: (request: RequestId, doc: DocId, projectName: string | null) => typedError<string[], IdeError>(__TAURI_INVOKE("lsp_java_source_types", { request, doc, projectName })),
lspJavaMove: (request: RequestId, doc: DocId, kind: string, args: string, confirmation: string | null) => typedError<ServerRefactored, IdeError>(__TAURI_INVOKE("lsp_java_move", { request, doc, kind, args, confirmation })),
@@ -5383,6 +5385,16 @@ export type ExternalTool = {
openConsole?: boolean,
};
/**
* What Extract Interface starts from: the file's class, the members the interface can declare and
* the packages it can go to (as JSON, passed back unchanged).
*/
export type ExtractInterfaceInfo = {
className: string,
members: InterfaceMember[],
packages: string[],
};
/** Framework facet attached to a module (Project Structure › Facets). */
export type FacetConfig = {
/** `"web"` | `"spring"` | `"jpa"`. */
@@ -6774,6 +6786,17 @@ export type IntellijThemeSource = {
themes: IntellijThemeFile[],
};
/** A member Extract Interface can declare in the new interface. */
export type InterfaceMember = {
name: string,
/** The method's return type or the field's type. */
typeName: string,
/** The method's parameter types; `None` for a field. */
parameters: string[] | null,
/** The server's handle of the member, passed back unchanged. */
handleIdentifier: string,
};
/** Optional parts of the invalidation; the symbol index is always rebuilt. */
export type InvalidateCachesOptions = {
/** Local History of every project. */
@@ -10055,7 +10078,7 @@ export type ServerInfo = {
};
/**
* A refactoring checked by the server (Change Signature, Move): problems to show, the edit when
* A refactoring checked by the server (Change Signature, Move, Extract Interface): problems to show, the edit when
* none is fatal, and the token that confirms going on despite warnings.
*/
export type ServerRefactored = {
+1
View File
@@ -949,6 +949,7 @@ export class EditorController implements SlotHost {
{ kind: "action", action: "refactor.extractVariable" },
{ kind: "action", action: "refactor.extractConstant" },
{ kind: "action", action: "refactor.extractMethod" },
{ kind: "action", action: "refactor.extractInterface" },
{ kind: "action", action: "refactor.inline" },
{ kind: "action", action: "refactor.pullMembersUp" },
{ kind: "action", action: "refactor.pushMembersDown" },
+3
View File
@@ -320,6 +320,9 @@ export function registerLspActions(): () => void {
editorAction("refactor.extractParameter", "Introduce Parameter…", "Refactor", (v) =>
runRefactoring(v, "extractParameter"),
),
editorAction("refactor.extractInterface", "Extract Interface…", "Refactor", (v) =>
runRefactoring(v, "extractInterface"),
),
editorAction("refactor.move", "Move…", "Refactor", (v) => runRefactoring(v, "move")),
editorAction("refactor.changeSignature", "Change Signature…", "Refactor", (v) =>
runRefactoring(v, "changeSignature"),
+2
View File
@@ -44,6 +44,7 @@ import { outsideProjectBanner } from "./outsideProject";
import { implementationGutter, registerNavigationActions } from "@/editor/navigation";
import {
ChangeSignatureDialog,
ExtractInterfaceDialog,
HierarchyDialog,
JAVA_REFACTORING_COMMAND,
runJavaRefactoringCommand,
@@ -122,6 +123,7 @@ export function activate(): () => void {
registerOverlay({ id: "editor-lsp.popups", component: LspPopups }),
registerOverlay({ id: "editor-lsp.hierarchyDialog", component: HierarchyDialog }),
registerOverlay({ id: "editor-lsp.changeSignatureDialog", component: ChangeSignatureDialog }),
registerOverlay({ id: "editor-lsp.extractInterfaceDialog", component: ExtractInterfaceDialog }),
registerClientCommand(JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand),
registerEditorBanner(outsideProjectBanner),
registerStatusItem({ id: "editor-lsp.usagesStatus", align: "left", priority: 10, component: UsagesStatus }),
@@ -0,0 +1,88 @@
.dialog [data-dialog-body] {
display: flex;
flex-direction: column;
overflow: hidden;
}
.body {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: 14px;
font-size: var(--fs-ui);
color: var(--fg);
}
.field {
flex: none;
display: flex;
flex-direction: column;
gap: var(--space-1-5);
}
.source {
font-family: var(--font-mono);
color: var(--fg-muted);
overflow-wrap: anywhere;
}
.table {
display: flex;
flex-direction: column;
border: 1px solid var(--border);
border-radius: 4px;
flex: 1 1 auto;
min-height: 0;
}
.head,
.row {
display: grid;
grid-template-columns: 1fr;
align-items: center;
gap: var(--space-2);
padding: 0 8px;
min-height: var(--h-list-row);
}
.head {
color: var(--fg-muted);
border-bottom: 1px solid var(--border);
}
.rows {
flex: 1 1 auto;
min-height: 0;
overflow: auto;
}
.row:hover {
background: var(--bg-hover);
}
.member {
min-width: 0;
}
.label {
font-family: var(--font-mono);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.error {
flex: none;
color: var(--danger);
font-size: var(--fs-small);
overflow-wrap: anywhere;
}
.busy {
display: flex;
align-items: center;
gap: var(--space-1-5);
color: var(--fg-muted);
}
@@ -0,0 +1,137 @@
/** IDEA's Extract Interface dialog for Java classes (`extractInterface.ts`). */
import { useState } from "react";
import { Checkbox, Dialog, Input, Select, Spinner, T } from "@/ui";
import { useTx } from "@/platform/i18n";
import {
extractInterface,
interfaceProblem,
memberLabel,
useExtractInterfaceDialog,
type InterfaceRequest,
} from "./extractInterface";
import styles from "./ExtractInterfaceDialog.module.css";
export function ExtractInterfaceDialog() {
const request = useExtractInterfaceDialog((s) => s.request);
if (!request) return null;
return <ExtractInterfaceDialogInner key={request.seq} request={request} />;
}
function ExtractInterfaceDialogInner({ request }: { request: InterfaceRequest }) {
const tx = useTx();
const { info, packages } = request;
const [name, setName] = useState("");
const [pkg, setPkg] = useState(() =>
String(
Math.max(
0,
packages.findIndex((p) => p.current),
),
),
);
const [checked, setChecked] = useState<ReadonlySet<string>>(new Set());
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const trimmed = name.trim();
const problem = interfaceProblem(trimmed, info.className, checked.size);
const target = packages[Number(pkg)];
const ready = !busy && !problem && !!target;
const allChecked = checked.size === info.members.length;
const close = () => {
useExtractInterfaceDialog.setState({ request: null });
request.view.focus();
};
const toggle = (id: string, on: boolean) =>
setChecked((all) => {
const next = new Set(all);
if (on) next.add(id);
else next.delete(id);
return next;
});
const submit = async (preview: boolean) => {
if (!ready) return;
setBusy(true);
setError(null);
const members = info.members.map((m) => m.handleIdentifier).filter((id) => checked.has(id));
const outcome = await extractInterface(request, trimmed, target, members, preview);
if (useExtractInterfaceDialog.getState().request !== request) return;
setBusy(false);
if (outcome.status === "done") close();
else if (outcome.error) setError(outcome.error);
};
return (
<Dialog
open
onClose={close}
title="Extract Interface"
className={styles.dialog}
width={560}
minHeight={360}
maxHeight={600}
resizable="both"
buttons={[
{ label: "Preview", role: "extra", disabled: !ready, onClick: () => void submit(true) },
{ label: "Refactor", role: "default", disabled: !ready, onClick: () => void submit(false) },
{ label: "Cancel", role: "cancel" },
]}
footerStart={
busy ? (
<span className={styles.busy}>
<Spinner size={12} />
<T>Checking for conflicts…</T>
</span>
) : undefined
}
>
<div className={styles.body}>
<div className={styles.field}>
<T>Extract interface from:</T>
<span className={styles.source}>{info.className}</span>
</div>
<label className={styles.field}>
<T>Interface name:</T>
<Input mono autoFocus value={name} onChange={(e) => setName(e.target.value)} />
</label>
<label className={styles.field}>
<T>Package for new interface:</T>
<Select
aria-label="Package for new interface"
value={pkg}
options={packages.map((p, i) => ({ value: String(i), label: p.name, icon: "package" }))}
onChange={setPkg}
/>
</label>
<div className={styles.table} role="table" aria-label={tx("Members to Form Interface")}>
<div className={styles.head} role="row">
<Checkbox
checked={allChecked}
indeterminate={checked.size > 0 && !allChecked}
onChange={(on) => setChecked(on ? new Set(info.members.map((m) => m.handleIdentifier)) : new Set())}
label={<T>Members to Form Interface</T>}
/>
</div>
<div className={styles.rows}>
{info.members.map((m) => (
<div key={m.handleIdentifier} className={styles.row} role="row">
<Checkbox
className={styles.member}
checked={checked.has(m.handleIdentifier)}
onChange={(on) => toggle(m.handleIdentifier, on)}
label={<span className={styles.label}>{memberLabel(m)}</span>}
/>
</div>
))}
</div>
</div>
{(error ?? (trimmed && problem)) && (
<span className={styles.error} role="alert">
{tx(error ?? problem!)}
</span>
)}
</div>
</Dialog>
);
}
+10 -1
View File
@@ -2,7 +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, not code actions.
* Pull Members Up / Push Members Down come from the Java extension, Extract Interface from jdtls
* requests, not code actions.
* Pure; used by Refactor This (⌃T) and the Refactor menu actions.
*/
import type { CodeAction } from "@/bindings";
@@ -17,6 +18,7 @@ export type RefactoringId =
| "extractConstant"
| "extractField"
| "extractParameter"
| "extractInterface"
| "inline"
| "pullMembersUp"
| "pushMembersDown";
@@ -96,6 +98,13 @@ export const REFACTORINGS: readonly Refactoring[] = [
reason: (sel) =>
sel ? "Selected block should represent an expression" : "Caret should be inside an expression in a function",
},
{
id: "extractInterface",
action: "refactor.extractInterface",
label: "Extract Interface…",
kind: null,
reason: () => "Caret should be inside a class",
},
{ id: "inline", action: "refactor.inline", label: "Inline…", kind: "refactor.inline", reason: () => AT_NAME },
{
id: "pullMembersUp",
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import { interfaceProblem, memberLabel, packageChoices } from "./extractInterface";
describe("extract interface", () => {
it("labels methods with their parameter types and fields with their type", () => {
const m = { name: "area", typeName: "double", parameters: ["int", "String"], handleIdentifier: "m" };
expect(memberLabel(m)).toBe("area(int, String): double");
expect(memberLabel({ ...m, parameters: [] })).toBe("area(): double");
expect(memberLabel({ name: "UNIT", typeName: "int", parameters: null, handleIdentifier: "f" })).toBe("UNIT: int");
});
it("keeps each package's server JSON and marks the file's own package", () => {
const json = [
JSON.stringify({ displayName: "com.a", path: "src/com/a", isParentOfSelectedFile: true }),
JSON.stringify({ displayName: "", path: "src" }),
];
const [own, root] = packageChoices(json);
expect(own).toMatchObject({ name: "com.a", current: true, json: json[0] });
expect(root).toMatchObject({ name: "(default package)", current: false });
});
it("needs a valid name other than the class's and at least one member", () => {
expect(interfaceProblem("", "Shape", 1)).toBe("No interface name specified");
expect(interfaceProblem("1x", "Shape", 1)).toBe("Interface name is not a valid identifier");
expect(interfaceProblem("Shape", "Shape", 1)).toBe("Interface name should differ from the class name");
expect(interfaceProblem("HasArea", "Shape", 0)).toBe("Select the members to form the interface");
expect(interfaceProblem("HasArea", "Shape", 2)).toBeNull();
});
});
+173
View File
@@ -0,0 +1,173 @@
/**
* Extract Interface for Java: jdtls lists the members of the file's class and the packages, the
* dialog (`ExtractInterfaceDialog.tsx`) picks the interface's name, package and members, and
* jdtls creates the interface, makes the class implement it and uses it where possible.
*/
import type { Text } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { create } from "zustand";
import type { ExtractInterfaceInfo, InterfaceMember, Pos, ServerRefactored } from "@/bindings";
import { whenSynced } from "@/editor/api";
import { docOf, isUnavailable, lspRequest } from "@/editor/lsp/lsp";
import { offsetToPos } from "@/editor/lsp/positions";
import { showHint } from "@/editor/lsp/hint";
import { openPopup } from "@/editor/lsp/popupStore";
import { summarizeWorkspaceEdit } from "@/editor/lsp/workspaceEdit";
import { tx } from "@/platform/i18n";
import { commands, isCancelled, nextRequestId, unavailableText } from "@/platform/ipc";
import { editorService } from "@/workbench/contributions";
import { cannotPerform } from "./catalog";
import { applyEdit, confirmProblems } from "./signature";
/** Languages whose server extracts interfaces through the dialog. */
export const EXTRACT_INTERFACE_LANGUAGES = new Set(["java"]);
type Json = Record<string, unknown>;
/** A package the interface can go to; `json` is passed back to the server unchanged. */
export interface PackageChoice {
name: string;
path: string;
current: boolean;
json: string;
}
export function packageChoices(packages: readonly string[]): PackageChoice[] {
return packages.map((json) => {
const p = JSON.parse(json) as Json;
const text = (v: unknown) => (typeof v === "string" ? v : "");
return {
name: text(p.displayName) || "(default package)",
path: text(p.path),
current: !!p.isParentOfSelectedFile,
json,
};
});
}
/** `area(double): double` for a method, `UNIT: int` for a field. */
export function memberLabel(m: InterfaceMember): string {
const params = m.parameters ? `(${m.parameters.join(", ")})` : "";
return `${m.name}${params}: ${m.typeName}`;
}
const JAVA_NAME = /^[A-Za-z_$][\w$]*$/;
/** Why the interface can't be extracted yet, or null. */
export function interfaceProblem(name: string, className: string, members: number): string | null {
if (!name) return "No interface name specified";
if (!JAVA_NAME.test(name)) return "Interface name is not a valid identifier";
if (name === className) return "Interface name should differ from the class name";
if (!members) return "Select the members to form the interface";
return null;
}
export interface InterfaceRequest {
seq: number;
view: EditorView;
doc: number;
pos: Pos;
/** The document `pos` refers to. */
text: Text;
info: ExtractInterfaceInfo;
packages: PackageChoice[];
}
export const useExtractInterfaceDialog = create<{ request: InterfaceRequest | null }>(() => ({ request: null }));
let seq = 0;
let running: AbortController | null = null;
function errorText(e: unknown): string {
if (isUnavailable(e)) return unavailableText(e, "No language server available");
return e instanceof Error ? e.message : String(e);
}
/** Extract Interface…: reads the file's class, then opens the dialog. */
export async function startExtractInterface(view: EditorView): Promise<void> {
const ctx = docOf(view);
if (!ctx) return;
if (ctx.readOnly) {
showHint(view, cannotPerform("The file is read-only"));
return;
}
running?.abort();
const run = (running = new AbortController());
await whenSynced(view);
const state = view.state;
const pos = offsetToPos(state.doc, state.selection.main.head);
const request = nextRequestId();
const abort = () => void commands.cancelRequest(request);
run.signal.addEventListener("abort", abort);
try {
const info = await lspRequest(() => commands.lspExtractInterfaceInfo(request, ctx.doc, pos));
if (run.signal.aborted || view.state.doc !== state.doc) return;
if (!info.members.length) {
showHint(view, cannotPerform("The class has no members to form an interface"));
return;
}
const packages = packageChoices(info.packages);
useExtractInterfaceDialog.setState({
request: { seq: ++seq, view, doc: ctx.doc, pos, text: state.doc, info, packages },
});
} catch (e) {
if (isCancelled(e) || run.signal.aborted) return;
showHint(view, cannotPerform(errorText(e)));
} finally {
run.signal.removeEventListener("abort", abort);
if (running === run) running = null;
}
}
export type InterfaceOutcome = { status: "done" } | { status: "stay"; error?: string };
/** Checks the extraction, confirms its problems and applies the edit (opening the new interface), or previews it. */
export async function extractInterface(
request: InterfaceRequest,
name: string,
pkg: PackageChoice,
members: readonly string[],
preview: boolean,
): Promise<InterfaceOutcome> {
const { view } = request;
if (view.state.doc !== request.text) return { status: "stay", error: "The file changed; open the dialog again" };
let confirmation: string | null = null;
let extracted: ServerRefactored;
try {
for (;;) {
await whenSynced(view);
const token: string | null = confirmation;
extracted = await lspRequest(() =>
commands.lspExtractInterface(nextRequestId(), request.doc, request.pos, [...members], name, pkg.json, token),
);
const fatal = extracted.problems.find((p) => p.severity === "fatal");
if (fatal || (!extracted.edit && !extracted.confirmation))
return { status: "stay", error: fatal?.message ?? "Nothing to change" };
if (!extracted.confirmation) break;
if (!(await confirmProblems(extracted.problems.map((p) => p.message)))) return { status: "stay" };
confirmation = extracted.confirmation;
}
} catch (e) {
if (isCancelled(e)) return { status: "stay" };
return { status: "stay", error: errorText(e) };
}
const edit = extracted.edit!;
const summary = summarizeWorkspaceEdit(edit);
if (!summary.files) return { status: "stay", error: "Nothing to change" };
const created = edit.files.find((f) => f.kind === "create")?.path;
const apply = async () => {
await applyEdit(view, edit);
if (created) await editorService().openFile(created, { focus: true });
};
if (preview) {
openPopup({
kind: "preview",
title: tx`Extract Interface from '${request.info.className}'`,
summary,
confirmLabel: "Do Refactor",
onConfirm: () => void apply(),
});
} else {
await apply();
}
return { status: "done" };
}
+1
View File
@@ -4,3 +4,4 @@ export { startHierarchyRefactoring } from "./hierarchy";
export { ChangeSignatureDialog } from "./ChangeSignatureDialog";
export { JAVA_REFACTORING_COMMAND, runJavaRefactoringCommand } from "./javaMove";
export { HierarchyDialog } from "./HierarchyDialog";
export { ExtractInterfaceDialog } from "./ExtractInterfaceDialog";
+12 -2
View File
@@ -66,6 +66,8 @@ const safeDelete = vi.fn();
vi.mock("./safeDelete", () => ({ safeDelete }));
const startHierarchyRefactoring = vi.fn();
vi.mock("./hierarchy", () => ({ startHierarchyRefactoring }));
const startExtractInterface = vi.fn();
vi.mock("./extractInterface", () => ({ EXTRACT_INTERFACE_LANGUAGES: new Set(["java"]), startExtractInterface }));
const { classifyAction, kindAdvertised, cannotPerform } = await import("./catalog");
const { refactorThis, runRefactoring } = await import("./refactorThis");
@@ -195,19 +197,27 @@ describe("Refactor This", () => {
expect(lspCodeActionQuery.mock.calls[0]![3]).toEqual(["refactor"]);
});
it("offers Pull Members Up / Push Members Down in Java files, after IDEA's other refactorings", async () => {
it("offers Extract Interface, Pull Members Up and Push Members Down in Java files, after IDEA's other refactorings", async () => {
query = answer([action("Convert to switch expression", "refactor.rewrite")]);
const v = editor("class Dog extends Animal { int price; }", "java");
await refactorThis(v, vi.fn());
expect(labels()).toEqual(["Pull Members Up…", "Push Members Down…", "Convert to switch expression"]);
expect(labels()).toEqual([
"Extract Interface…",
"Pull Members Up…",
"Push Members Down…",
"Convert to switch expression",
]);
const items = (useLspPopup.getState().popup as { items: { label: string; run: () => void }[] }).items;
items.find((i) => i.label === "Push Members Down…")!.run();
expect(startHierarchyRefactoring).toHaveBeenCalledWith(v, "pushDown");
items.find((i) => i.label === "Extract Interface…")!.run();
expect(startExtractInterface).toHaveBeenCalledWith(v);
closePopup();
v.destroy();
// Other languages have no server for them; nor does Java while its server is down.
await refactorThis(editor(), vi.fn());
expect(labels()).not.toContain("Pull Members Up…");
expect(labels()).not.toContain("Extract Interface…");
query = async () => unavailable;
await refactorThis(editor("class Dog {}", "java"), vi.fn());
expect(labels()).toEqual(["Nothing here"]);
+19 -3
View File
@@ -41,6 +41,7 @@ import {
import { safeDelete } from "./safeDelete";
import { startHierarchyRefactoring } from "./hierarchy";
import { SIGNATURE_LANGUAGES, startChangeSignature } from "./signature";
import { EXTRACT_INTERFACE_LANGUAGES, startExtractInterface } from "./extractInterface";
/** Languages with a server that runs the class-hierarchy refactorings (the app-owned JDT extension; Phoxite for PHP). */
const HIERARCHY_LANGUAGES = new Set(["java", "php"]);
@@ -158,6 +159,11 @@ 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)}`));
return;
}
// IDEA picks the expression first (and the server then extracts exactly that one).
if (EXPRESSION_REFACTORINGS.has(id) && view.state.selection.main.empty) {
if (await chooseExpressionFirst(view, () => runRefactoring(view, id))) return;
@@ -224,12 +230,13 @@ async function expressionAtCaret(view: EditorView, signal: AbortSignal): Promise
export function refactorThisItems(
view: EditorView,
answer: ServerAnswer,
facts: { symbol: boolean; expression: boolean; hierarchy?: boolean; signature?: boolean },
facts: { symbol: boolean; expression: boolean; hierarchy?: boolean; signature?: boolean; extractInterface?: boolean },
run: {
rename: (view: EditorView) => unknown;
safeDelete: (view: EditorView) => unknown;
hierarchy?: (view: EditorView, kind: "pullUp" | "pushDown") => unknown;
signature?: (view: EditorView) => unknown;
extractInterface?: (view: EditorView) => unknown;
},
): ListPopupItem[] {
const { mapped, other } = groupActions(answer.status === "ok" ? answer.query.actions : []);
@@ -245,6 +252,8 @@ export function refactorThisItems(
go = () => runRefactoring(view, r.id);
else if (r.id === "changeSignature" && facts.signature && serverUsable && run.signature)
go = () => run.signature!(view);
else if (r.id === "extractInterface" && facts.extractInterface && serverUsable && run.extractInterface)
go = () => run.extractInterface!(view);
else if (actions.length) go = () => runActions(view, r.label.replace(/…$/, ""), actions, r.id);
else if (r.id === "rename" && facts.symbol) go = () => run.rename(view);
else if (r.id === "safeDelete" && facts.symbol && !docOf(view)?.readOnly) go = () => run.safeDelete(view);
@@ -287,11 +296,18 @@ export async function refactorThis(view: EditorView, rename: (view: EditorView)
]);
const hierarchy = HIERARCHY_LANGUAGES.has(ctx.language) && !ctx.readOnly;
const signature = SIGNATURE_LANGUAGES.has(ctx.language) && !ctx.readOnly && symbol;
const extractInterface = EXTRACT_INTERFACE_LANGUAGES.has(ctx.language) && !ctx.readOnly;
items = refactorThisItems(
view,
answer,
{ symbol, expression, hierarchy, signature },
{ rename, safeDelete, hierarchy: startHierarchyRefactoring, signature: startChangeSignature },
{ symbol, expression, hierarchy, signature, extractInterface },
{
rename,
safeDelete,
hierarchy: startHierarchyRefactoring,
signature: startChangeSignature,
extractInterface: startExtractInterface,
},
);
} catch (e) {
if (isCancelled(e)) return;
+1
View File
@@ -61,6 +61,7 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = {
IntroduceConstant: "refactor.extractConstant",
IntroduceField: "refactor.extractField",
IntroduceParameter: "refactor.extractParameter",
ExtractInterface: "refactor.extractInterface",
Inline: "refactor.inline",
Move: "refactor.move",
SafeDelete: "refactor.safeDelete",
+1
View File
@@ -172,6 +172,7 @@ export const intellijMacos: Record<string, string[]> = {
"refactor.inline": ["Meta+Alt+N"],
"refactor.move": ["F6"],
"refactor.safeDelete": ["Meta+Delete"],
"refactor.extractInterface": [],
"refactor.pullMembersUp": [],
"refactor.pushMembersDown": [],
+1
View File
@@ -173,6 +173,7 @@ export const intellijWindows: Record<string, string[]> = {
"refactor.inline": ["Ctrl+Alt+N"],
"refactor.move": ["F6"],
"refactor.safeDelete": ["Alt+Delete"],
"refactor.extractInterface": [],
"refactor.pullMembersUp": [],
"refactor.pushMembersDown": [],
+1
View File
@@ -188,6 +188,7 @@ export const vscodeMacos: Record<string, string[]> = {
"refactor.inline": [],
"refactor.move": [],
"refactor.safeDelete": [],
"refactor.extractInterface": [],
"refactor.pullMembersUp": [],
"refactor.pushMembersDown": [],
+17 -1
View File
@@ -2139,5 +2139,21 @@
"Move {name} to another class": "Move {name} to another class",
"(default package)": "(default package)",
"Field": "Field",
"Move": "Move"
"Move": "Move",
"Extract Interface…": "Extract Interface…",
"Extract Interface": "Extract Interface",
"Extract interface from:": "Extract interface from:",
"Interface name:": "Interface name:",
"Package for new interface:": "Package for new interface:",
"Members to Form Interface": "Members to Form Interface",
"No interface name specified": "No interface name specified",
"Interface name is not a valid identifier": "Interface name is not a valid identifier",
"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}",
"Package for new interface": "Package for new interface"
}
+20 -4
View File
@@ -1785,7 +1785,7 @@
"Name for the new constant": "新常量的名称",
"Name for the new variable": "新变量的名称",
"Name of the current file": "当前文件的名称",
"Name:": "名称:",
"Name:": "名称:",
"Named scope": "命名范围",
"Names (e.g. .DS_Store, *.pyc) hidden from the project tree, navigation bar, search, indexing and Git changes.": "从项目树、导航栏、搜索、索引和 Git 更改中隐藏的名称(例如 .DS_Store、*.pyc)。",
"Narrow down on typing": "输入时缩小列表范围",
@@ -8499,8 +8499,8 @@
"Model": "模型",
"Migration": "迁移",
"Change Signature": "更改签名",
"Visibility:": "可见性:",
"Return type:": "返回类型:",
"Visibility:": "可见性:",
"Return type:": "返回类型:",
"package-private": "包私有",
"Delegate via overloading method": "通过重载方法委托",
"Signature Preview": "签名预览",
@@ -8522,5 +8522,21 @@
"Move {name} to a new file": "将 {name} 移动到新文件",
"Move {name} to another class": "将 {name} 移动到其他类",
"(default package)": "(默认包)",
"Field": "字段"
"Field": "字段",
"Extract Interface…": "提取接口…",
"Extract Interface": "提取接口",
"Extract interface from:": "从以下位置提取接口:",
"Interface name:": "接口名称:",
"Package for new interface:": "新接口的软件包:",
"Members to Form Interface": "形成接口的成员",
"No interface name specified": "未指定接口名称",
"Interface name is not a valid identifier": "接口名称不是有效的标识符",
"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} 不支持提取接口",
"Package for new interface": "新接口的软件包"
}