diff --git a/crates/ide-host/src/ops/lsp.rs b/crates/ide-host/src/ops/lsp.rs index 3713361ec..a61118bc6 100644 --- a/crates/ide-host/src/ops/lsp.rs +++ b/crates/ide-host/src/ops/lsp.rs @@ -1223,7 +1223,7 @@ pub async fn lsp_change_signature( } fn json_argument(args: &str) -> IdeResult { - 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) -> Vec { @@ -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 { + 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, + name: String, + destination: String, + confirmation: Option, +) -> IdeResult { + 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 diff --git a/crates/ide-lsp/src/jdtls.rs b/crates/ide-lsp/src/jdtls.rs index 33f38bfcd..6c256e8b6 100644 --- a/crates/ide-lsp/src/jdtls.rs +++ b/crates/ide-lsp/src/jdtls.rs @@ -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; diff --git a/crates/ide-lsp/src/jdtls/extract_interface.rs b/crates/ide-lsp/src/jdtls/extract_interface.rs new file mode 100644 index 000000000..775ea3201 --- /dev/null +++ b/crates/ide-lsp/src/jdtls/extract_interface.rs @@ -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, + #[serde(default)] + sub_type_name: String, + #[serde(default)] + destination_response: Destinations, +} + +#[derive(Default, Deserialize)] +#[serde(rename_all = "camelCase")] +struct Destinations { + #[serde(default)] + destinations: Vec, +} + +fn info_of(status: Option) -> IdeResult { + 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 { + let (snap, t) = self.jdtls_target(doc, FEATURE).await?; + let params = Self::signature_context(&snap, &t, pos); + let status: Option = + 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, + name: String, + package: Value, + confirmation: Option, + cancel: CancellationToken, + ) -> IdeResult { + 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 = + 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(&info.packages[0]).unwrap()["displayName"], "a"); + assert!(info_of(None).is_err()); + } +} diff --git a/crates/ide-lsp/src/jdtls/signature.rs b/crates/ide-lsp/src/jdtls/signature.rs index 3cb4f43a0..f15f0cd38 100644 --- a/crates/ide-lsp/src/jdtls/signature.rs +++ b/crates/ide-lsp/src/jdtls/signature.rs @@ -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 }, diff --git a/crates/ide-lsp/src/types.rs b/crates/ide-lsp/src/types.rs index bd5a3c322..1cc3c67df 100644 --- a/crates/ide-lsp/src/types.rs +++ b/crates/ide-lsp/src/types.rs @@ -539,7 +539,30 @@ pub struct MethodSignature { pub exceptions: Vec, } -/// 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>, + /// 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, + pub packages: Vec, +} + +/// 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")] diff --git a/docs/en/guide/refactoring.mdx b/docs/en/guide/refactoring.mdx index 97e4a726e..85462caf1 100644 --- a/docs/en/guide/refactoring.mdx +++ b/docs/en/guide/refactoring.mdx @@ -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. diff --git a/docs/zh/guide/refactoring.mdx b/docs/zh/guide/refactoring.mdx index ebbe6ab36..ea946db56 100644 --- a/docs/zh/guide/refactoring.mdx +++ b/docs/zh/guide/refactoring.mdx @@ -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`)会打开对话框,可以修改可见性、返回类型和方法名,添加、删除和调整形参顺序。新形参需要填写默认值,所有已有调用处都会传入这个值;勾选 **通过重载方法委托** 会保留旧签名作为重载并调用新方法。签名预览显示修改后的声明。**重构** 会一次更新方法本身、覆盖它的方法和所有调用;**预览** 先列出改动。其他语言在服务器把签名重写作为代码操作提供时才会出现。 diff --git a/src-tauri/src/commands/lsp.rs b/src-tauri/src/commands/lsp.rs index c75db9267..e1c92c3d8 100644 --- a/src-tauri/src/commands/lsp.rs +++ b/src-tauri/src/commands/lsp.rs @@ -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 { + 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, + name: String, + destination: String, + confirmation: Option, +) -> IdeResult { + 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( diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 1738ed862..14c93de6f 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -304,6 +304,8 @@ pub fn builder() -> tauri_specta::Builder { 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, diff --git a/src-tauri/src/menu.rs b/src-tauri/src/menu.rs index 01de8971d..30960b2c1 100644 --- a/src-tauri/src/menu.rs +++ b/src-tauri/src/menu.rs @@ -594,6 +594,7 @@ pub fn spec(os: Os) -> Vec { 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…"), diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index b8edeae60..64baa4aeb 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -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 diff --git a/src/bindings.ts b/src/bindings.ts index 695ade29f..0f883e785 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -644,6 +644,8 @@ export const commands = { lspHierarchyRefactor: (request: RequestId, doc: DocId, pos: Pos, kind: HierarchyRefactoring, target: string | null, choices: HierarchyChoice[]) => typedError(__TAURI_INVOKE("lsp_hierarchy_refactor", { request, doc, pos, kind, target, choices })), lspSignatureInfo: (request: RequestId, doc: DocId, pos: Pos) => typedError(__TAURI_INVOKE("lsp_signature_info", { request, doc, pos })), lspChangeSignature: (request: RequestId, doc: DocId, pos: Pos, signature: MethodSignature, delegate: boolean, confirmation: string | null) => typedError(__TAURI_INVOKE("lsp_change_signature", { request, doc, pos, signature, delegate, confirmation })), + lspExtractInterfaceInfo: (request: RequestId, doc: DocId, pos: Pos) => typedError(__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(__TAURI_INVOKE("lsp_extract_interface", { request, doc, pos, members, name, destination, confirmation })), lspJavaMoveDestinations: (request: RequestId, doc: DocId, kind: string, args: string) => typedError(__TAURI_INVOKE("lsp_java_move_destinations", { request, doc, kind, args })), lspJavaSourceTypes: (request: RequestId, doc: DocId, projectName: string | null) => typedError(__TAURI_INVOKE("lsp_java_source_types", { request, doc, projectName })), lspJavaMove: (request: RequestId, doc: DocId, kind: string, args: string, confirmation: string | null) => typedError(__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 = { diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index 7db46616c..f8362fd02 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -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" }, diff --git a/src/editor/lsp/actions.ts b/src/editor/lsp/actions.ts index 13c19634f..f544d39e7 100644 --- a/src/editor/lsp/actions.ts +++ b/src/editor/lsp/actions.ts @@ -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"), diff --git a/src/editor/lsp/index.ts b/src/editor/lsp/index.ts index eab196447..e14a0b99a 100644 --- a/src/editor/lsp/index.ts +++ b/src/editor/lsp/index.ts @@ -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 }), diff --git a/src/editor/refactor/ExtractInterfaceDialog.module.css b/src/editor/refactor/ExtractInterfaceDialog.module.css new file mode 100644 index 000000000..a5ab09a7a --- /dev/null +++ b/src/editor/refactor/ExtractInterfaceDialog.module.css @@ -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); +} diff --git a/src/editor/refactor/ExtractInterfaceDialog.tsx b/src/editor/refactor/ExtractInterfaceDialog.tsx new file mode 100644 index 000000000..a6a2e5465 --- /dev/null +++ b/src/editor/refactor/ExtractInterfaceDialog.tsx @@ -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 ; +} + +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>(new Set()); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(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 ( + void submit(true) }, + { label: "Refactor", role: "default", disabled: !ready, onClick: () => void submit(false) }, + { label: "Cancel", role: "cancel" }, + ]} + footerStart={ + busy ? ( + + + Checking for conflicts… + + ) : undefined + } + > +
+
+ Extract interface from: + {info.className} +
+ +