From d3c505595408a047ced885180f0095969d5c5359 Mon Sep 17 00:00:00 2001 From: l0ng-ai <24760907+l0ng-ai@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:04:22 +0800 Subject: [PATCH] feat(ui): open New Project, Get from VCS and Remote Development in their own windows Each dialog gets a native window over its project window: a full-height sidebar under the traffic lights, the title heading the content and the buttons in its corner. The windows hand their result back to the project window, which opens the created or cloned project or makes the remote connection and reports its progress. Remote windows and the browser build keep the dialogs in the page. --- src-tauri/capabilities/default.json | 13 +- src-tauri/capabilities/e2e.json | 13 +- src-tauri/src/commands/window.rs | 41 +- src-tauri/src/windows.rs | 115 ++++- src-tauri/tests/commands.snap | 3 + src/auxiliaryBoot.ts | 15 + src/bindings.ts | 21 + src/cloneWindowBoot.ts | 20 + src/connectWindowBoot.ts | 16 + src/features/app/NewProject.tsx | 420 ++++++++++------ .../app/__tests__/newProjectDialog.test.tsx | 14 +- src/features/app/newProject.module.css | 14 + src/features/app/newProjectWindow.tsx | 27 ++ src/features/github/clone/source.ts | 11 + src/features/github/index.ts | 9 +- .../remote-dev/ConnectDialog.test.tsx | 17 +- src/features/remote-dev/ConnectDialog.tsx | 72 ++- src/features/remote-dev/RemoteDev.module.css | 4 + src/features/remote-dev/connectWindow.tsx | 135 ++++++ src/features/remote-dev/index.ts | 6 +- src/features/remote-dev/model.ts | 3 +- src/features/vcs/clone.module.css | 45 +- src/features/vcs/clone.tsx | 452 ++++++++++++------ src/features/vcs/cloneWindow.tsx | 68 +++ src/features/vcs/index.ts | 2 + src/features/welcome/WelcomeView.tsx | 2 +- src/main.tsx | 2 +- src/newProjectWindowBoot.ts | 16 + src/platform/auxWindow.test.ts | 6 +- src/platform/auxWindow.ts | 28 +- src/platform/locales/text/es.json | 4 +- src/platform/locales/text/fr.json | 4 +- src/platform/locales/text/ko.json | 4 +- src/platform/locales/text/pl.json | 4 +- src/platform/locales/text/pt.json | 4 +- src/platform/locales/text/ru.json | 4 +- src/platform/locales/text/tr.json | 4 +- src/platform/locales/text/zh-TW.json | 4 +- src/platform/locales/text/zh.json | 4 +- src/workbench/WindowDialogFrame.module.css | 79 +++ src/workbench/WindowDialogFrame.tsx | 99 ++++ src/workbench/dialogWindow.ts | 28 ++ 42 files changed, 1487 insertions(+), 365 deletions(-) create mode 100644 src/cloneWindowBoot.ts create mode 100644 src/connectWindowBoot.ts create mode 100644 src/features/app/newProjectWindow.tsx create mode 100644 src/features/github/clone/source.ts create mode 100644 src/features/remote-dev/connectWindow.tsx create mode 100644 src/features/vcs/cloneWindow.tsx create mode 100644 src/newProjectWindowBoot.ts create mode 100644 src/workbench/WindowDialogFrame.module.css create mode 100644 src/workbench/WindowDialogFrame.tsx create mode 100644 src/workbench/dialogWindow.ts diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index cdfcf6c434..c7ffc5f438 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -2,7 +2,18 @@ "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", "description": "Capability for the main window", - "windows": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"], + "windows": [ + "main", + "project-*", + "settings-*", + "comparison-*", + "diff-*", + "editor-*", + "deployment-*", + "new-project-*", + "clone-*", + "connect-*" + ], "permissions": [ "core:default", "core:window:allow-start-dragging", diff --git a/src-tauri/capabilities/e2e.json b/src-tauri/capabilities/e2e.json index 3bfe73ecaa..0eec203e33 100644 --- a/src-tauri/capabilities/e2e.json +++ b/src-tauri/capabilities/e2e.json @@ -2,6 +2,17 @@ "$schema": "../gen/schemas/desktop-schema.json", "identifier": "e2e-bridge", "description": "Debug-only automation bridge", - "windows": ["main", "project-*", "settings-*", "comparison-*", "diff-*", "editor-*", "deployment-*"], + "windows": [ + "main", + "project-*", + "settings-*", + "comparison-*", + "diff-*", + "editor-*", + "deployment-*", + "new-project-*", + "clone-*", + "connect-*" + ], "permissions": ["mcp-bridge:default"] } diff --git a/src-tauri/src/commands/window.rs b/src-tauri/src/commands/window.rs index cf74483898..2ef523eff4 100644 --- a/src-tauri/src/commands/window.rs +++ b/src-tauri/src/commands/window.rs @@ -152,6 +152,42 @@ pub async fn window_open_deployment( windows::open_deployment_window(&app, &window, server, paths, background) } +/// Opens this window's New Project window (or focuses it). `background` (`#rrggbb`) paints a new +/// window until its page has loaded. +#[desktop_command(trust = always)] +#[tauri::command] +#[specta::specta] +pub async fn window_open_new_project( + app: AppHandle, + window: WebviewWindow, + background: Option, +) -> IdeResult<()> { + windows::open_new_project_window(&app, &window, background) +} + +/// Opens this window's Get from VCS window (or focuses it), filling in `url` when given. +/// `background` (`#rrggbb`) paints a new window until its page has loaded. +#[desktop_command(trust = always)] +#[tauri::command] +#[specta::specta] +pub async fn window_open_clone( + app: AppHandle, + window: WebviewWindow, + url: Option, + background: Option, +) -> IdeResult<()> { + windows::open_clone_window(&app, &window, url, background) +} + +/// Opens this window's Remote Development window (or focuses it). `background` (`#rrggbb`) +/// paints a new window until its page has loaded. +#[desktop_command(trust = always)] +#[tauri::command] +#[specta::specta] +pub async fn window_open_connect(app: AppHandle, window: WebviewWindow, background: Option) -> IdeResult<()> { + windows::open_connect_window(&app, &window, background) +} + /// Focuses the next / previous window (⌘` / ⇧⌘`). #[desktop_command(trust = always)] #[tauri::command] @@ -437,7 +473,7 @@ pub fn menu_configure( fn owns_menu_config(source: &str, target: &str) -> bool { let owner = match windows::auxiliary(target) { - Some((windows::AuxKind::Settings, parent)) => parent, + Some((kind, parent)) if kind.runs_menu_in_parent() => parent, _ => target, }; source == owner @@ -1021,11 +1057,14 @@ ide_command::desktop_domain!( window_flash_taskbar, window_is_fullscreen, window_new, + window_open_clone, window_open_comparison, + window_open_connect, window_open_deployment, window_open_diff, window_open_editor, window_open_file_in_new_window, + window_open_new_project, window_open_files, window_open_project, window_open_projects, diff --git a/src-tauri/src/windows.rs b/src-tauri/src/windows.rs index 2c976a0aed..96ab29b63d 100644 --- a/src-tauri/src/windows.rs +++ b/src-tauri/src/windows.rs @@ -6,7 +6,7 @@ //! (`window_take_launch`), and re-taken whenever [`LAUNCH_EVENT`] fires (a //! second app instance asking an already-loaded window to open a path). //! -//! Auxiliary windows ([`AuxKind`]: Settings, Compare with Local, Diff, Sync with Deployed) belong to a project window and share its project (see +//! Auxiliary windows ([`AuxKind`]: Settings, Compare with Local, Diff, Sync with Deployed, New Project, Get from VCS, Remote Development) belong to a project window and share its project (see //! [`AppState::project`]). Their labels name the kind and the parent //! (`settings-main`, `comparison-project-2-3`, `diff-main-0`); their [`Launch`] says what to show. @@ -46,6 +46,12 @@ const EDITOR_SIZE: (f64, f64) = (1100.0, 720.0); const EDITOR_MIN_SIZE: (f64, f64) = (640.0, 360.0); const DEPLOYMENT_SIZE: (f64, f64) = (1400.0, 900.0); const DEPLOYMENT_MIN_SIZE: (f64, f64) = (800.0, 500.0); +const NEW_PROJECT_SIZE: (f64, f64) = (860.0, 620.0); +const NEW_PROJECT_MIN_SIZE: (f64, f64) = (720.0, 480.0); +const CLONE_SIZE: (f64, f64) = (920.0, 620.0); +const CLONE_MIN_SIZE: (f64, f64) = (640.0, 420.0); +const CONNECT_SIZE: (f64, f64) = (600.0, 460.0); +const CONNECT_MIN_SIZE: (f64, f64) = (520.0, 380.0); /// What a freshly opened window should do once its frontend is up. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)] @@ -83,6 +89,9 @@ pub struct Launch { /// Editor windows: the file to show (Open in New Window → lightweight aux editor). #[serde(default)] pub editor: Option>, + /// Get from VCS windows: the repository URL to fill in. + #[serde(default)] + pub clone_url: Option, } /// What a lightweight editor window shows: a file, with optional caret / selection (0-based), or @@ -638,11 +647,22 @@ pub enum AuxKind { Diff, Editor, Deployment, + NewProject, + Clone, + Connect, } impl AuxKind { - const ALL: [AuxKind; 5] = - [AuxKind::Settings, AuxKind::Comparison, AuxKind::Diff, AuxKind::Editor, AuxKind::Deployment]; + const ALL: [AuxKind; 8] = [ + AuxKind::Settings, + AuxKind::Comparison, + AuxKind::Diff, + AuxKind::Editor, + AuxKind::Deployment, + AuxKind::NewProject, + AuxKind::Clone, + AuxKind::Connect, + ]; /// Label prefix, and the key of the one remembered geometry shared by every window of the kind. pub fn name(self) -> &'static str { @@ -652,6 +672,9 @@ impl AuxKind { AuxKind::Diff => "diff", AuxKind::Editor => "editor", AuxKind::Deployment => "deployment", + AuxKind::NewProject => "new-project", + AuxKind::Clone => "clone", + AuxKind::Connect => "connect", } } @@ -663,17 +686,23 @@ impl AuxKind { /// Shows the project's documents: gets its parent's events and edits made in sibling windows, /// and asks about its own unsaved changes before the parent closes it. pub fn shares_documents(self) -> bool { - self != AuxKind::Settings + !self.dialog() } - /// Has no actions of its own: menu items run in its project window. - fn runs_menu_in_parent(self) -> bool { - self == AuxKind::Settings + /// Has no actions of its own: menu items run in its project window, which owns the menu. + pub fn runs_menu_in_parent(self) -> bool { + self.dialog() } /// Needs its parent to have a project open. fn needs_project(self) -> bool { - self != AuxKind::Settings + !self.dialog() + } + + /// A dialog in its own window (Settings, New Project, Get from VCS, Remote Development): + /// works without the parent's project or documents, and leaves the menu to the parent. + fn dialog(self) -> bool { + matches!(self, AuxKind::Settings | AuxKind::NewProject | AuxKind::Clone | AuxKind::Connect) } pub fn min_size(self) -> (f64, f64) { @@ -683,6 +712,9 @@ impl AuxKind { AuxKind::Diff => DIFF_MIN_SIZE, AuxKind::Editor => EDITOR_MIN_SIZE, AuxKind::Deployment => DEPLOYMENT_MIN_SIZE, + AuxKind::NewProject => NEW_PROJECT_MIN_SIZE, + AuxKind::Clone => CLONE_MIN_SIZE, + AuxKind::Connect => CONNECT_MIN_SIZE, } } @@ -693,6 +725,9 @@ impl AuxKind { AuxKind::Diff => DIFF_SIZE, AuxKind::Editor => EDITOR_SIZE, AuxKind::Deployment => DEPLOYMENT_SIZE, + AuxKind::NewProject => NEW_PROJECT_SIZE, + AuxKind::Clone => CLONE_SIZE, + AuxKind::Connect => CONNECT_SIZE, } } } @@ -2129,6 +2164,60 @@ pub fn open_deployment_window( ) } +/// Opens (or focuses) the New Project window of `parent`'s project window: a separate window +/// centred over it, so the wizard can be moved and sized on its own. +pub fn open_new_project_window(app: &AppHandle, parent: &WebviewWindow, background: Option) -> IdeResult<()> { + open_auxiliary_window( + app, + parent, + AuxWindow { + kind: AuxKind::NewProject, + title: "New Project", + size: AuxKind::NewProject.default_size(), + min_size: AuxKind::NewProject.min_size(), + launch: Launch::default(), + background, + }, + ) +} + +/// Opens (or focuses, filling in `url`) the Get from VCS window of `parent`'s project window. +pub fn open_clone_window( + app: &AppHandle, + parent: &WebviewWindow, + url: Option, + background: Option, +) -> IdeResult<()> { + open_auxiliary_window( + app, + parent, + AuxWindow { + kind: AuxKind::Clone, + title: "Get from Version Control", + size: AuxKind::Clone.default_size(), + min_size: AuxKind::Clone.min_size(), + launch: Launch { clone_url: url.filter(|u| !u.trim().is_empty()), ..Default::default() }, + background, + }, + ) +} + +/// Opens (or focuses) the Remote Development window of `parent`'s project window. +pub fn open_connect_window(app: &AppHandle, parent: &WebviewWindow, background: Option) -> IdeResult<()> { + open_auxiliary_window( + app, + parent, + AuxWindow { + kind: AuxKind::Connect, + title: "Remote Development", + size: AuxKind::Connect.default_size(), + min_size: AuxKind::Connect.min_size(), + launch: Launch::default(), + background, + }, + ) +} + #[cfg(any(target_os = "macos", test))] fn resolve_aux_geometry(saved: Option, default_size: (f64, f64), min_size: (f64, f64)) -> AuxGeometry { match saved.filter(|g| g.width.is_finite() && g.height.is_finite() && g.width > 0.0 && g.height > 0.0) { @@ -3276,6 +3365,10 @@ mod tests { assert_eq!(auxiliary("diff-project-2-3"), Some((AuxKind::Diff, "project-2"))); assert_eq!(auxiliary("editor-project-2-3"), Some((AuxKind::Editor, "project-2"))); assert_eq!(auxiliary("deployment-project-2"), Some((AuxKind::Deployment, "project-2"))); + assert_eq!(auxiliary("new-project-project-2"), Some((AuxKind::NewProject, "project-2"))); + assert_eq!(auxiliary("new-project-main"), Some((AuxKind::NewProject, "main"))); + assert_eq!(auxiliary("clone-project-2"), Some((AuxKind::Clone, "project-2"))); + assert_eq!(auxiliary("connect-main"), Some((AuxKind::Connect, "main"))); for label in ["main", "project-1", "comparison-main", "comparison-main-x", "settings-", "settingsmain"] { assert_eq!(auxiliary(label), None, "{label}"); } @@ -3305,6 +3398,9 @@ mod tests { ("settings-main", "app.checkForUpdates", Parent { label: "main", raise: true }), ("settings-project-2", "file.newFile", Parent { label: "project-2", raise: true }), ("settings-main", "editor.closeTab", Parent { label: "main", raise: true }), + ("new-project-main", "file.newFile", Parent { label: "main", raise: true }), + ("clone-main", "vcs.clone", Parent { label: "main", raise: true }), + ("new-project-project-2", "editor.closeTab", Parent { label: "project-2", raise: true }), ("settings-main", "file.settings", Parent { label: "main", raise: false }), ("settings-main", "app.quit", Parent { label: "main", raise: false }), ("comparison-main-0", "app.quit", Parent { label: "main", raise: false }), @@ -3374,6 +3470,9 @@ mod tests { "comparison-project-2-0", "diff-main-9", "deployment-main", + "new-project-main", + "clone-main", + "connect-main", ] { assert!(!keeps_window_state(label), "{label} must not use physical window-state"); } diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index a81154f3aa..abef9e115f 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -867,12 +867,15 @@ window_group_restore always desktop bin window_group_select always desktop bindings async window_is_fullscreen always desktop bindings sync window_new always desktop bindings async +window_open_clone always desktop bindings async window_open_comparison always desktop bindings async +window_open_connect always desktop bindings async window_open_deployment always desktop bindings async window_open_diff always desktop bindings async window_open_editor always desktop bindings async window_open_file_in_new_window always desktop bindings async window_open_files always desktop bindings async +window_open_new_project always desktop bindings async window_open_project always desktop bindings async window_open_projects always desktop bindings sync window_open_remote always desktop bindings async diff --git a/src/auxiliaryBoot.ts b/src/auxiliaryBoot.ts index 0575f35874..abb0e62f65 100644 --- a/src/auxiliaryBoot.ts +++ b/src/auxiliaryBoot.ts @@ -30,5 +30,20 @@ export async function bootAuxiliaryWindow(aux: { kind: AuxKind; parent: string } mountWindowRoot(bootDeploymentWindow(aux.parent)); return; } + case "new-project": { + const { bootNewProjectWindow } = await import("./newProjectWindowBoot"); + mountWindowRoot(bootNewProjectWindow(aux.parent)); + return; + } + case "connect": { + const { bootConnectWindow } = await import("./connectWindowBoot"); + mountWindowRoot(bootConnectWindow(aux.parent)); + return; + } + case "clone": { + const { bootCloneWindow } = await import("./cloneWindowBoot"); + mountWindowRoot(bootCloneWindow(aux.parent)); + return; + } } } diff --git a/src/bindings.ts b/src/bindings.ts index b76e9eb98f..a4ef5ce8df 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -2394,11 +2394,21 @@ export const commands = { windowIsFullscreen: () => __TAURI_INVOKE("window_is_fullscreen"), /** Opens an empty (welcome) window; returns its label. */ windowNew: () => typedError(__TAURI_INVOKE("window_new")), + /** + * Opens this window's Get from VCS window (or focuses it), filling in `url` when given. + * `background` (`#rrggbb`) paints a new window until its page has loaded. + */ + windowOpenClone: (url: string | null, background: string | null) => typedError(__TAURI_INVOKE("window_open_clone", { url, background })), /** * Opens a window listing the files that differ between two revisions of this window's project. * `background` (`#rrggbb`) paints it until its page has loaded. */ windowOpenComparison: (comparison: ComparisonLaunch, background: string | null) => typedError(__TAURI_INVOKE("window_open_comparison", { comparison, background })), + /** + * Opens this window's Remote Development window (or focuses it). `background` (`#rrggbb`) + * paints a new window until its page has loaded. + */ + windowOpenConnect: (background: string | null) => typedError(__TAURI_INVOKE("window_open_connect", { background })), /** * Opens this window's Sync with Deployed window comparing `paths` with `server` (or hands them * to the open one). `background` (`#rrggbb`) paints a new window until its page has loaded. @@ -2427,6 +2437,11 @@ export const commands = { * itself, in LightEdit. */ windowOpenFiles: (files: string[]) => typedError(__TAURI_INVOKE("window_open_files", { files })), + /** + * Opens this window's New Project window (or focuses it). `background` (`#rrggbb`) paints a new + * window until its page has loaded. + */ + windowOpenNewProject: (background: string | null) => typedError(__TAURI_INVOKE("window_open_new_project", { background })), /** * Opens `path` in a new window (`new_window`) or tells the caller to open it * itself (`current`). A project already open in some window is focused instead. @@ -2491,6 +2506,8 @@ export const commands = { deployment: DeploymentLaunch | null, /** Editor windows: the file to show (Open in New Window → lightweight aux editor). */ editor: EditorLaunch_Serialize | null, + /** Get from VCS windows: the repository URL to fill in. */ + cloneUrl: string | null, } | null>("window_take_launch"), /** * Local bootstrap snapshot for a `settings-` window, avoiding a sequential @@ -9496,6 +9513,8 @@ export type Launch_Deserialize = { deployment?: DeploymentLaunch | null, /** Editor windows: the file to show (Open in New Window → lightweight aux editor). */ editor?: EditorLaunch_Deserialize | null, + /** Get from VCS windows: the repository URL to fill in. */ + cloneUrl?: string | null, }; /** What a freshly opened window should do once its frontend is up. */ @@ -9527,6 +9546,8 @@ export type Launch_Serialize = { deployment: DeploymentLaunch | null, /** Editor windows: the file to show (Open in New Window → lightweight aux editor). */ editor: EditorLaunch_Serialize | null, + /** Get from VCS windows: the repository URL to fill in. */ + cloneUrl: string | null, }; export type LegacyPasswordAction = "check" | "retry" | "removePlaintext"; diff --git a/src/cloneWindowBoot.ts b/src/cloneWindowBoot.ts new file mode 100644 index 0000000000..7e1bd3cd20 --- /dev/null +++ b/src/cloneWindowBoot.ts @@ -0,0 +1,20 @@ +import type { ComponentType } from "react"; +import { installLocaleSync } from "./features/app/locale"; +import { githubCloneSource } from "./features/github/clone/source"; +import { trackRuntimeSettings } from "./features/settings/runtime"; +import { activateCloneLaunches, CloneWindow } from "./features/vcs/cloneWindow"; +import { registerCloneSource } from "./workbench/contributions"; +import { activateDialogWindow } from "./workbench/dialogWindow"; +import { activateList } from "./windowBoot"; + +/** Get from VCS window of project window `parent`: the clone dialog and its sources, no workbench. */ +export function bootCloneWindow(parent: string): ComponentType { + activateList("clone window", [ + ["locale", installLocaleSync], + ["settings", trackRuntimeSettings], + ["github", () => registerCloneSource(githubCloneSource)], + ["dialog", () => activateDialogWindow(parent)], + ["launch", activateCloneLaunches], + ]); + return CloneWindow; +} diff --git a/src/connectWindowBoot.ts b/src/connectWindowBoot.ts new file mode 100644 index 0000000000..ddba4801d8 --- /dev/null +++ b/src/connectWindowBoot.ts @@ -0,0 +1,16 @@ +import type { ComponentType } from "react"; +import { installLocaleSync } from "./features/app/locale"; +import { ConnectWindow } from "./features/remote-dev/connectWindow"; +import { trackRuntimeSettings } from "./features/settings/runtime"; +import { activateDialogWindow } from "./workbench/dialogWindow"; +import { activateList } from "./windowBoot"; + +/** Remote Development window of project window `parent`: the connect dialog only, no workbench. */ +export function bootConnectWindow(parent: string): ComponentType { + activateList("remote development window", [ + ["locale", installLocaleSync], + ["settings", trackRuntimeSettings], + ["dialog", () => activateDialogWindow(parent)], + ]); + return ConnectWindow; +} diff --git a/src/features/app/NewProject.tsx b/src/features/app/NewProject.tsx index 836b92ec22..495f5971b1 100644 --- a/src/features/app/NewProject.tsx +++ b/src/features/app/NewProject.tsx @@ -3,9 +3,14 @@ * left, the chosen one's form on the right, then a progress view while the backend * creates the project. The new project opens in a new window (this one when it has * no project). + * + * In the desktop app the wizard has its own native window (`new-project-`, see + * `newProjectWindow.tsx`), which hands the created folder back to its project window; remote + * windows and the browser build show it as a dialog in the page. */ import { Channel } from "@tauri-apps/api/core"; -import { useEffect, useMemo, useRef, useState } from "react"; +import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow"; +import { useEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { create } from "zustand"; import { call, @@ -22,9 +27,14 @@ import { } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { useTx, useTxTemplate } from "@/platform/i18n"; +import { logError } from "@/platform/errorLog"; +import { isRemoteWindow } from "@/platform/remote"; +import { windowBackgroundHex } from "@/workbench/theme"; +import { WindowDialogFrame } from "@/workbench/WindowDialogFrame"; import { Checkbox, Dialog, + type DialogButton, Icon, IconButton, Input, @@ -48,10 +58,44 @@ import { defaultProjectDirectory, openProjectInWindow } from "./windows"; import styles from "./newProject.module.css"; const useNewProject = create<{ open: boolean }>(() => ({ open: false })); -export const showNewProject = () => useNewProject.setState({ open: true }); +const showInPage = () => useNewProject.setState({ open: true }); + +/** Sent by the New Project window to its project window with the created folder. */ +export const NEW_PROJECT_CREATED = "openidea://new-project/created"; + +/** File › New Project…: its own window in the desktop app, else a dialog in this page. */ +export function showNewProject() { + if (!isTauri() || isRemoteWindow()) return showInPage(); + void call(commands.windowOpenNewProject(windowBackgroundHex())).catch((e: unknown) => { + logError("cannot open the New Project window", e); + showInPage(); + }); +} + +/** Opens a project the New Project window created, like the in-page dialog does. */ +export function openCreatedProject(dir: string) { + void getCurrentWebviewWindow() + .setFocus() + .catch(() => {}); + return openProjectInWindow(dir, useProject.getState().project !== null); +} export function NewProjectOverlay() { const open = useNewProject((s) => s.open); + useEffect(() => { + if (!isTauri()) return; + let disposed = false; + let off: (() => void) | undefined; + void getCurrentWebviewWindow() + .listen<{ dir: string }>(NEW_PROJECT_CREATED, ({ payload }) => { + void openCreatedProject(payload.dir).catch((e: unknown) => logError("cannot open the new project", e)); + }) + .then((u) => (disposed ? u() : (off = u))); + return () => { + disposed = true; + off?.(); + }; + }, []); return open ? useNewProject.setState({ open: false })} /> : null; } @@ -139,7 +183,68 @@ function saveDialogSize(size: { w: number; h: number }) { } } -function NewProjectDialog({ onClose }: { onClose: () => void }) { +interface FrameProps { + standalone: boolean; + onClose: () => void; + buttons: readonly DialogButton[]; + children: ReactNode; + /** The wizard form: resizable, its size remembered. */ + form?: boolean; + /** In the window: the generator list, beside the content. */ + sidebar?: ReactNode; +} + +/** The wizard's own window, or a dialog in the page. */ +function Frame({ standalone, onClose, buttons, children, form = false, sidebar }: FrameProps) { + if (standalone) + return ( + + {children} + + ); + return form ? ( + + {children} + + ) : ( + + {children} + + ); +} + +/** + * The wizard. `standalone`: it fills the New Project window, and the created project opens in + * `parent` (the window's project window) instead of here. + */ +export function NewProjectDialog({ + onClose, + standalone = false, + onCreated, +}: { + onClose: () => void; + standalone?: boolean; + /** Opens the created project; defaults to opening it from this window. */ + onCreated?: (dir: string) => Promise; +}) { const tx = useTx(); const txTemplate = useTxTemplate(); const [catalog, setCatalog] = useState(null); @@ -338,6 +443,10 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) { ), ); saveLocation(location.trim()); + if (onCreated) { + await onCreated(dir); + return; + } onClose(); await openProjectInWindow(dir, useProject.getState().project !== null); } catch (e) { @@ -346,25 +455,143 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) { } }; - if (job) return setJob(null)} onClose={onClose} />; + if (job) return setJob(null)} onClose={onClose} />; - return ( - void createProject() }, - { label: "Cancel", role: "cancel" }, - ]} + const buttons: DialogButton[] = [ + { label: "Create", role: "default", disabled: invalid, onClick: () => void createProject() }, + { label: "Cancel", role: "cancel" }, + ]; + const generators = ( + <> + setQuery(e.target.value)} + aria-label="Search generators" + /> +
+ {catalogError &&
{txTemplate(catalogError)}
} + {groupedEntries(catalog ?? [], query).map(([group, entries]) => ( +
+
{tx(group)}
+ {entries.map((g) => ( + + ))} +
+ ))} +
+ + ); + const formView = ( +
{ + e.preventDefault(); + void createProject(); + }} > + {generator?.description &&
{tx(generator.description)}
} +
+ + { + setNameEdited(true); + setName(e.target.value); + }} + /> + +
+ setLocation(e.target.value)} + /> + void browse()} + disabled={!isTauri()} + /> +
+ +
+ {nameError ? txTemplate(nameError) : path && txTemplate(`Project will be created in: ${path}`)} +
+ {generator?.git && ( + <> + + + + )} + {visibleFields.map((f) => ( + setValue(f.id, v)} + sdks={f.kind.type === "sdk" ? (sdks[f.kind.sdk] ?? null) : null} + /> + ))} + {loadingDynamic && ( + <> + +
+ Loading options… +
+ + )} + {dynamicError && ( + <> + +
{txTemplate(dynamicError)}
+ + )} +
+ {missing.map((r) => ( +
+ + + {r.found + ? tx`${r.program} ${r.found} is installed, but this project needs ${r.min ?? ""} or later.` + : tx`${r.program} is not installed.`}{" "} + {r.hint && tx(r.hint)} + +
+ ))} +
+ ); + + if (standalone) + return ( + + {formView} + + ); + return ( + void }) { maxSize="45%" className={styles.sidebar} > - setQuery(e.target.value)} - aria-label="Search generators" - /> -
- {catalogError &&
{txTemplate(catalogError)}
} - {groupedEntries(catalog ?? [], query).map(([group, entries]) => ( -
-
{tx(group)}
- {entries.map((g) => ( - - ))} -
- ))} -
+ {generators} -
{ - e.preventDefault(); - void createProject(); - }} - > - {generator?.description &&
{tx(generator.description)}
} -
- - { - setNameEdited(true); - setName(e.target.value); - }} - /> - -
- setLocation(e.target.value)} - /> - void browse()} - disabled={!isTauri()} - /> -
- -
- {nameError ? txTemplate(nameError) : path && txTemplate(`Project will be created in: ${path}`)} -
- {generator?.git && ( - <> - - - - )} - {visibleFields.map((f) => ( - setValue(f.id, v)} - sdks={f.kind.type === "sdk" ? (sdks[f.kind.sdk] ?? null) : null} - /> - ))} - {loadingDynamic && ( - <> - -
- Loading options… -
- - )} - {dynamicError && ( - <> - -
{txTemplate(dynamicError)}
- - )} -
- {missing.map((r) => ( -
- - - {r.found - ? tx`${r.program} ${r.found} is installed, but this project needs ${r.min ?? ""} or later.` - : tx`${r.program} is not installed.`}{" "} - {r.hint && tx(r.hint)} - -
- ))} -
+ {formView}
-
+ ); } @@ -662,7 +775,17 @@ function DependencyPicker({ ); } -function ProgressView({ job, onBack, onClose }: { job: Job; onBack: () => void; onClose: () => void }) { +function ProgressView({ + job, + standalone, + onBack, + onClose, +}: { + job: Job; + standalone: boolean; + onBack: () => void; + onClose: () => void; +}) { const txTemplate = useTxTemplate(); const tx = useTx(); const log = useRef(null); @@ -671,12 +794,23 @@ function ProgressView({ job, onBack, onClose }: { job: Job; onBack: () => void; if (el) el.scrollTop = el.scrollHeight; }, [job.lines.length]); const failed = job.error !== null; + useEffect(() => { + if (!standalone || failed || !isTauri()) return; + // Closing the window stops the generator instead of leaving it running unseen. + let disposed = false; + let off: (() => void) | undefined; + void getCurrentWebviewWindow() + .onCloseRequested(() => job.cancel()) + .then((u) => (disposed ? u() : (off = u))); + return () => { + disposed = true; + off?.(); + }; + }, [standalone, failed, job]); return ( - (failed ? onClose() : job.cancel())} - width={860} buttons={ failed ? [ @@ -700,6 +834,6 @@ function ProgressView({ job, onBack, onClose }: { job: Job; onBack: () => void; {failed &&
{txTemplate(job.error ?? "")}
} -
+ ); } diff --git a/src/features/app/__tests__/newProjectDialog.test.tsx b/src/features/app/__tests__/newProjectDialog.test.tsx index 60f79778de..0fcb576aec 100644 --- a/src/features/app/__tests__/newProjectDialog.test.tsx +++ b/src/features/app/__tests__/newProjectDialog.test.tsx @@ -1,7 +1,7 @@ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { GeneratorInfo } from "@/bindings"; -import { NewProjectOverlay, showNewProject } from "../NewProject"; +import { NewProjectDialog, NewProjectOverlay, showNewProject } from "../NewProject"; const mocks = vi.hoisted(() => ({ freeName: vi.fn(), @@ -114,6 +114,18 @@ describe("File › New Project… name and location", () => { await waitFor(() => expect(mocks.open).toHaveBeenCalled()); expect(localStorage.getItem("openidea.newProject.location")).toBe("/elsewhere"); }); + + it("in its own window, hands the created project to its project window instead of opening it", async () => { + const created = vi.fn(() => Promise.resolve()); + render( {}} onCreated={created} />); + expect(screen.queryByRole("dialog")).toBeNull(); + await waitFor(() => expect(nameInput()).toHaveValue("untitled2")); + await waitFor(() => expect(createButton()).toBeEnabled()); + fireEvent.click(createButton()); + await waitFor(() => expect(created).toHaveBeenCalledWith("/work/projects/untitled2")); + expect(mocks.open).not.toHaveBeenCalled(); + expect(localStorage.getItem("openidea.newProject.location")).toBe("/work/projects"); + }); }); describe("File › New Project… SDK fields", () => { diff --git a/src/features/app/newProject.module.css b/src/features/app/newProject.module.css index 5311a9f180..8b8403a6c2 100644 --- a/src/features/app/newProject.module.css +++ b/src/features/app/newProject.module.css @@ -237,3 +237,17 @@ white-space: pre-wrap; overflow-wrap: anywhere; } + +/* The New Project window */ +.windowBody { + display: flex; + flex-direction: column; + overflow: hidden; +} +.windowBody .form { + padding-top: 0; +} +.windowBody .progress { + height: 100%; + padding-top: 0; +} diff --git a/src/features/app/newProjectWindow.tsx b/src/features/app/newProjectWindow.tsx new file mode 100644 index 0000000000..72ae417758 --- /dev/null +++ b/src/features/app/newProjectWindow.tsx @@ -0,0 +1,27 @@ +/** + * The New Project window (`new-project-`): the wizard in its own native window. The + * created project opens from the parent project window, which then has it (or a new window). + */ +import { emitTo } from "@tauri-apps/api/event"; +import { closeDialogWindow, useDialogWindow } from "@/workbench/dialogWindow"; +import { OverlayHost } from "@/workbench/OverlayHost"; +import { useApplyTheme } from "@/workbench/theme"; +import { WindowResizeHandles } from "@/workbench/WindowResizeHandles"; +import { NEW_PROJECT_CREATED, NewProjectDialog } from "./NewProject"; + +export function NewProjectWindow() { + useApplyTheme(); + const parent = useDialogWindow((s) => s.parent); + const created = async (dir: string) => { + if (!parent) return; + await emitTo(parent, NEW_PROJECT_CREATED, { dir }); + closeDialogWindow(); + }; + return ( + <> + {parent && } + + + + ); +} diff --git a/src/features/github/clone/source.ts b/src/features/github/clone/source.ts new file mode 100644 index 0000000000..0125a163a8 --- /dev/null +++ b/src/features/github/clone/source.ts @@ -0,0 +1,11 @@ +import { lazyComponent } from "@/ui"; +import type { CloneSourceContribution } from "@/workbench/contributions"; + +/** Get from VCS › GitHub: the signed-in accounts' repositories. */ +export const githubCloneSource: CloneSourceContribution = { + id: "github", + label: "GitHub", + icon: "github", + order: 10, + component: lazyComponent(() => import("./GitHubCloneSource").then((m) => m.GitHubCloneSource)), +}; diff --git a/src/features/github/index.ts b/src/features/github/index.ts index a85a26f1da..80fe130d38 100644 --- a/src/features/github/index.ts +++ b/src/features/github/index.ts @@ -12,6 +12,7 @@ import "./ui/palette.css"; import { registerActions, type Action } from "@/platform/actions"; import { setContext } from "@/platform/context"; import { lazyComponent } from "@/ui"; +import { githubCloneSource } from "./clone/source"; import { registerCloneSource, registerEditorKind, @@ -257,13 +258,7 @@ export function activate(): () => void { setContext("githubPrTab", "list"); const disposers = [ activateSettingsPages(), - registerCloneSource({ - id: "github", - label: "GitHub", - icon: "github", - order: 10, - component: lazyComponent(() => import("./clone/GitHubCloneSource").then((m) => m.GitHubCloneSource)), - }), + registerCloneSource(githubCloneSource), registerGitLogChecks(lazyComponent(() => import("./LogCommitChecks").then((m) => m.LogCommitChecks))), registerToolWindow({ id: WINDOW, diff --git a/src/features/remote-dev/ConnectDialog.test.tsx b/src/features/remote-dev/ConnectDialog.test.tsx index bba3c8d3d3..ecd73806a2 100644 --- a/src/features/remote-dev/ConnectDialog.test.tsx +++ b/src/features/remote-dev/ConnectDialog.test.tsx @@ -3,7 +3,7 @@ import { act, fireEvent, render, screen, waitFor, within } from "@testing-librar import { emitLocalIdeEvent, type IdeEvent, type RemoteEntry, type Settings } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { useRemoteProgress } from "@/platform/remote"; -import { ConnectHost } from "./ConnectDialog"; +import { ConnectDialog, ConnectHost } from "./ConnectDialog"; import { closeConnectDialog, openConnectDialog, useConnectDialog } from "./model"; const { list, distros, globalSettings, openRemote, executeAction } = vi.hoisted(() => ({ @@ -153,3 +153,18 @@ it("opens a folder of the chosen WSL distribution, without browsing over SFTP", await waitFor(() => expect(openRemote).toHaveBeenCalledWith({ kind: "wsl", distro: installed[1] }, "~")); expect(list).not.toHaveBeenCalled(); }); + +it("in its own window, hands the connection to its project window and shows its failure", async () => { + const close = vi.fn(); + const connect = vi.fn().mockRejectedValueOnce(new Error("Host key mismatch")).mockResolvedValueOnce(true); + render(); + expect(screen.queryByRole("dialog")).toBeNull(); + await waitFor(() => expect(screen.getByRole("button", { name: "Open" })).toBeEnabled()); + fireEvent.click(screen.getByRole("button", { name: "Open" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Host key mismatch"); + expect(close).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "Open" })); + await waitFor(() => expect(close).toHaveBeenCalled()); + expect(connect).toHaveBeenLastCalledWith({ kind: "ssh", config: "first" }, "~"); + expect(openRemote).not.toHaveBeenCalled(); +}); diff --git a/src/features/remote-dev/ConnectDialog.tsx b/src/features/remote-dev/ConnectDialog.tsx index cc0457bb26..7d7971b7ee 100644 --- a/src/features/remote-dev/ConnectDialog.tsx +++ b/src/features/remote-dev/ConnectDialog.tsx @@ -1,12 +1,17 @@ -/** Picks an SSH configuration and a folder on that host, then opens it in this or a new window. */ -import { useEffect, useState } from "react"; +/** + * Picks an SSH configuration and a folder on that host, then opens it in this or a new window. + * In the desktop app it has its own window (`connectWindow.tsx`). + */ +import { useEffect, useState, type ReactNode } from "react"; import { executeAction } from "@/platform/actions"; import { useTx } from "@/platform/i18n"; import { call, commands, isCancelled, onIdeEvent, type RemoteEntry, type RemoteTarget } from "@/platform/ipc"; import { localGlobalSettings, useRemoteProgress } from "@/platform/remote"; import { sshLabel, type SshConfigValid, validateRemote } from "@/platform/remoteSettings"; -import { Button, Dialog, Icon, Input, ProgressBar, Select, Spinner } from "@/ui"; +import { Button, Dialog, Icon, Input, ProgressBar, Select, Spinner, type DialogButton } from "@/ui"; import { openRemoteProject } from "@/workbench/projectWindow"; +import { windowBackgroundHex } from "@/workbench/theme"; +import { WindowDialogFrame } from "@/workbench/WindowDialogFrame"; import { browsableFolders, closeConnectDialog, @@ -47,7 +52,44 @@ function useLocalSshConfigs(): SshConfigValid[] { return configs; } -function ConnectDialog() { +function Frame({ + standalone, + onClose, + buttons, + children, +}: { + standalone: boolean; + onClose: () => void; + buttons: readonly DialogButton[]; + children: ReactNode; +}) { + const tx = useTx(); + if (standalone) + return ( + + {children} + + ); + return ( + + {children} + + ); +} + +/** + * `standalone`: fills the Remote Development window, whose project window connects + * (`onConnect`: true once the project is open). + */ +export function ConnectDialog({ + standalone = false, + onClose = closeConnectDialog, + onConnect, +}: { + standalone?: boolean; + onClose?: () => void; + onConnect?: (target: RemoteTarget, path: string) => Promise; +}) { const tx = useTx(); const configs = useLocalSshConfigs(); const [picked, setSsh] = useState(""); @@ -99,7 +141,8 @@ function ConnectDialog() { setError(null); setBusy(true); try { - if (await openRemoteProject(target, path.trim() || "~")) closeConnectDialog(); + const dir = path.trim() || "~"; + if (await (onConnect ? onConnect(target, dir) : openRemoteProject(target, dir))) onClose(); else setBusy(false); } catch (e) { if (!isCancelled(e)) setError(e instanceof Error ? e.message : String(e)); @@ -117,12 +160,15 @@ function ConnectDialog() { const ready = !!name && !busy && !!path.trim(); const connecting = useRemoteProgress((s) => s.progress !== null); + const configure = () => + standalone + ? void call(commands.windowOpenSettings(SSH_SETTINGS_PAGE, false, windowBackgroundHex())).catch(() => {}) + : void executeAction("file.settings", SSH_SETTINGS_PAGE); + return ( -
{ e.preventDefault(); if (ready) void connect(); @@ -185,7 +231,7 @@ function ConnectDialog() { }} aria-label={tx("SSH configuration")} /> - + )} @@ -235,7 +281,7 @@ function ConnectDialog() { )}
-
+ ); } diff --git a/src/features/remote-dev/RemoteDev.module.css b/src/features/remote-dev/RemoteDev.module.css index d0ea9c546f..386576b3e5 100644 --- a/src/features/remote-dev/RemoteDev.module.css +++ b/src/features/remote-dev/RemoteDev.module.css @@ -6,6 +6,10 @@ align-items: center; padding: 14px var(--space-4); } +/* In the Remote Development window the title above it gives the space. */ +.windowForm { + padding-top: 0; +} .form > * { grid-column: 1 / -1; } diff --git a/src/features/remote-dev/connectWindow.tsx b/src/features/remote-dev/connectWindow.tsx new file mode 100644 index 0000000000..23702d1ac0 --- /dev/null +++ b/src/features/remote-dev/connectWindow.tsx @@ -0,0 +1,135 @@ +/** + * The Remote Development window (`connect-`): the connect dialog in its own native + * window. The connection is its project window's (the remote project may open in it), so the + * window hands the target over, shows the progress the project window sends back, and closes + * once the project is open; a failure stays in the window, as in the dialog. + */ +import { emitTo } from "@tauri-apps/api/event"; +import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow"; +import { Window } from "@tauri-apps/api/window"; +import { logError } from "@/platform/errorLog"; +import { call, commands, isCancelled, isTauri, type RemoteProgress, type RemoteTarget } from "@/platform/ipc"; +import { isRemoteWindow, useRemoteProgress } from "@/platform/remote"; +import { closeDialogWindow, useDialogWindow } from "@/workbench/dialogWindow"; +import { showError } from "@/workbench/messages"; +import { OverlayHost } from "@/workbench/OverlayHost"; +import { openRemoteProject } from "@/workbench/projectWindow"; +import { useApplyTheme, windowBackgroundHex } from "@/workbench/theme"; +import { WindowResizeHandles } from "@/workbench/WindowResizeHandles"; +import { ConnectDialog } from "./ConnectDialog"; +import { openConnectDialog, useConnectDialog } from "./model"; + +const REQUEST = "openidea://connect/request"; +const PROGRESS = "openidea://connect/progress"; +const RESULT = "openidea://connect/result"; + +interface ConnectRequest { + id: number; + from: string; + target: RemoteTarget; + path: string; +} +interface ConnectResult { + id: number; + opened: boolean; + error?: string; +} + +/** File › Remote Development…: its own window in the desktop app, else a dialog in this page. */ +export function showConnect() { + if (!isTauri() || isRemoteWindow()) return openConnectDialog(); + void call(commands.windowOpenConnect(windowBackgroundHex())).catch((e: unknown) => { + logError("cannot open the Remote Development window", e); + openConnectDialog(); + }); +} + +/** Connects for the Remote Development window, here in its project window. */ +export function installConnectHandoff(): () => void { + if (!isTauri()) return () => {}; + let self: ReturnType; + try { + self = getCurrentWebviewWindow(); + } catch { + return () => {}; // Not a desktop window (tests). + } + let disposed = false; + let off: (() => void) | undefined; + void self + .listen(REQUEST, ({ payload: { id, from, target, path } }) => { + void self.setFocus().catch(() => {}); + const relay = useRemoteProgress.subscribe((s) => void emitTo(from, PROGRESS, s.progress).catch(() => {})); + useConnectDialog.setState({ inWindow: true }); + const reply = async (result: ConnectResult) => { + if (await Window.getByLabel(from)) return emitTo(from, RESULT, result); + // The window is gone (closed, or with this window's old project): tell it here. + if (result.error) await showError("Cannot connect to the remote host", result.error); + }; + void openRemoteProject(target, path) + .then( + (opened) => reply({ id, opened }), + (e: unknown) => reply(isCancelled(e) ? { id, opened: false } : { id, opened: false, error: errorText(e) }), + ) + .finally(() => { + relay(); + useConnectDialog.setState({ inWindow: false }); + }); + }) + .then((u) => (disposed ? u() : (off = u))); + return () => { + disposed = true; + off?.(); + }; +} + +function errorText(e: unknown) { + return e instanceof Error ? e.message : String(e); +} + +let nextId = 0; + +/** Asks project window `parent` to connect; true once the project is open, false if it was not. */ +async function requestConnect(parent: string, target: RemoteTarget, path: string): Promise { + const self = getCurrentWebviewWindow(); + const id = ++nextId; + const offs: Array<() => void> = []; + try { + const result = new Promise((resolve) => { + void self + .listen(RESULT, ({ payload }) => payload.id === id && resolve(payload)) + .then((u) => { + offs.push(u); + }); + }); + offs.push( + await self.listen(PROGRESS, ({ payload }) => + useRemoteProgress.setState({ progress: payload }), + ), + ); + await emitTo(parent, REQUEST, { id, from: self.label, target, path } satisfies ConnectRequest); + const { opened, error } = await result; + if (error) throw new Error(error); + return opened; + } finally { + offs.forEach((off) => off()); + useRemoteProgress.setState({ progress: null }); + } +} + +export function ConnectWindow() { + useApplyTheme(); + const parent = useDialogWindow((s) => s.parent); + const connect = async (target: RemoteTarget, path: string) => { + if (!parent) return false; + const opened = await requestConnect(parent, target, path); + if (opened) closeDialogWindow(); + return opened; + }; + return ( + <> + {parent && } + + + + ); +} diff --git a/src/features/remote-dev/index.ts b/src/features/remote-dev/index.ts index c1c148bdbc..4c26ea054d 100644 --- a/src/features/remote-dev/index.ts +++ b/src/features/remote-dev/index.ts @@ -11,10 +11,11 @@ import { confirm } from "@/workbench/messages"; import { tx } from "@/platform/i18n"; import { confirmLeaveProject } from "@/platform/project"; import { ConnectHost } from "./ConnectDialog"; +import { installConnectHandoff, showConnect } from "./connectWindow"; import { reopenInContainer } from "./container"; import { installDirenvNotifications, reloadEnvironment } from "./environment"; import { RemoteStatus } from "./RemoteStatus"; -import { closeConnectDialog, openConnectDialog } from "./model"; +import { closeConnectDialog } from "./model"; import { restorePorts, usePorts } from "./ports"; import { installReconnect, reconnectNow } from "./reconnect"; @@ -71,6 +72,7 @@ export function activate(): () => void { installReconnect(), installDirenvNotifications(), registerOverlay({ id: "remote.connect", component: ConnectHost }), + installConnectHandoff(), registerStatusItem({ id: "remote.location", title: "Remote Host", @@ -86,7 +88,7 @@ export function activate(): () => void { category: "File", icon: "remote", keywords: ["ssh", "remote", "server", "gateway", "connect", "host"], - run: () => openConnectDialog(), + run: () => showConnect(), }, { id: "remote.reconnect", diff --git a/src/features/remote-dev/model.ts b/src/features/remote-dev/model.ts index e1b51c0ccb..48ab9084c5 100644 --- a/src/features/remote-dev/model.ts +++ b/src/features/remote-dev/model.ts @@ -2,7 +2,8 @@ import { create } from "zustand"; import type { RemoteEntry, RemoteStage } from "@/platform/ipc"; -export const useConnectDialog = create<{ open: boolean }>(() => ({ open: false })); +/** `open`: the dialog in this page. `inWindow`: connecting for the Remote Development window. */ +export const useConnectDialog = create<{ open: boolean; inWindow: boolean }>(() => ({ open: false, inWindow: false })); export function openConnectDialog() { useConnectDialog.setState({ open: true }); diff --git a/src/features/vcs/clone.module.css b/src/features/vcs/clone.module.css index 445c4fb835..ce4b4f9903 100644 --- a/src/features/vcs/clone.module.css +++ b/src/features/vcs/clone.module.css @@ -26,34 +26,42 @@ } .sidebar { flex: 0 0 200px; - padding: var(--space-2) 0; + padding: var(--space-2) var(--space-1); border-right: 1px solid var(--border); - background: color-mix(in srgb, var(--bg-dialog, var(--bg-elev)) 96%, var(--fg-strong)); + background: var(--bg-island); overflow: auto; } .sourceItem { - min-height: var(--h-row); + height: var(--h-list-row); display: flex; align-items: center; gap: var(--space-2); - padding: var(--space-1) var(--space-3); + padding: 0 var(--space-2); width: 100%; border: 0; - background: none; - color: var(--fg-strong); + border-radius: var(--radius-control, 4px); + background: transparent; + color: var(--fg); font: inherit; text-align: left; cursor: default; } +.sourceItem:hover:not(:disabled) { + background: var(--bg-hover); +} .sourceItem[data-selected] { - background: var(--bg-tree-selected); + background: var(--bg-list-selected); + color: var(--fg-strong); +} +.sourceItem:focus-visible { + outline: 2px solid var(--focus-ring); + outline-offset: -2px; } .sourceName { min-width: 0; - overflow-wrap: anywhere; - font-weight: 500; - font-size: var(--fs-ui); - line-height: 1.4; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .form { --clone-label-width: 112px; @@ -190,3 +198,18 @@ display: flex; flex-direction: column; } + +/* The Get from VCS window: the frame lays out the sources. */ +.windowBody { + display: flex; + overflow: hidden; +} +.windowBody .form { + padding-top: 0; +} +.windowSources { + flex: 1; + min-height: 0; + overflow: auto; + padding: 0 var(--space-1) var(--space-2); +} diff --git a/src/features/vcs/clone.tsx b/src/features/vcs/clone.tsx index ecca909918..f8c8c184d7 100644 --- a/src/features/vcs/clone.tsx +++ b/src/features/vcs/clone.tsx @@ -1,11 +1,31 @@ -/** Get from VCS: clone a repository into a new folder and open it as a project. */ -import { useEffect, useRef, useState } from "react"; +/** + * Get from VCS: clone a repository into a new folder and open it as a project. In the desktop app + * the dialog has its own native window (`clone-`, see `cloneWindow.tsx`), which hands the + * cloned folder back to its project window to open; remote windows show it in the page. + */ +import { useEffect, useRef, useState, type ReactNode } from "react"; import { Channel } from "@tauri-apps/api/core"; +import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow"; +import { logError } from "@/platform/errorLog"; import { tx } from "@/platform/i18n"; -import { callDesktop, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc"; +import { call, callDesktop, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc"; import { openProject } from "@/platform/project"; -import { Checkbox, Dialog, Icon, IconButton, Input, ProgressBar, Select, T, showContextMenu } from "@/ui"; +import { isRemoteWindow } from "@/platform/remote"; +import { + Checkbox, + Dialog, + Icon, + IconButton, + Input, + ProgressBar, + Select, + T, + showContextMenu, + type DialogButton, +} from "@/ui"; import { cloneSourceList, notifications, useCloneSources } from "@/workbench/contributions"; +import { windowBackgroundHex } from "@/workbench/theme"; +import { WindowDialogFrame } from "@/workbench/WindowDialogFrame"; import { openDialog } from "./dialogs"; import { progressFraction } from "./model"; import logo from "../../../src-tauri/icons/128x128.png"; @@ -106,15 +126,120 @@ async function defaultParent(): Promise { return ""; } +/** Sent by the Get from VCS window to its project window with the cloned folder. */ +export const CLONED = "openidea://clone/cloned"; + export function showCloneDialog(initialUrl = "") { if (!isTauri()) { notifications().notify({ group: "vcs", level: "warning", title: "Cloning requires the desktop app" }); return; } - openDialog((close) => ); + const inPage = () => openDialog((close) => ); + if (isRemoteWindow()) { + inPage(); + return; + } + void call(commands.windowOpenClone(initialUrl || null, windowBackgroundHex())).catch((e: unknown) => { + logError("cannot open the Get from VCS window", e); + inPage(); + }); } -function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl: string }) { +/** Opens a cloned folder as this window's project. */ +async function openCloned(dir: string) { + try { + await openProject(dir); + } catch (e) { + notifications().notify({ + group: "vcs", + level: "error", + title: "Cloned, but the project could not be opened", + body: e instanceof Error ? e.message : String(e), + }); + } +} + +/** Opens what the Get from VCS window cloned, here in its project window. */ +export function installCloneHandoff(): () => void { + if (!isTauri()) return () => {}; + let self: ReturnType; + try { + self = getCurrentWebviewWindow(); + } catch { + return () => {}; // Not a desktop window (tests). + } + let disposed = false; + let off: (() => void) | undefined; + void self + .listen<{ dir: string }>(CLONED, ({ payload }) => { + void self.setFocus().catch(() => {}); + void openCloned(payload.dir); + }) + .then((u) => (disposed ? u() : (off = u))); + return () => { + disposed = true; + off?.(); + }; +} + +interface FrameProps { + standalone: boolean; + onCancel: () => void; + buttons: readonly DialogButton[]; + children: ReactNode; + /** The clone sources; the window shows them full height. */ + sidebar: ReactNode; +} + +function Frame({ standalone, onCancel, buttons, children, sidebar }: FrameProps) { + if (standalone) + return ( + + {children} + + ); + return ( + + + Clone Repository + + } + aria-label="Clone Repository" + onClose={onCancel} + width="min(920px, calc(100vw - 48px))" + resizable="both" + className={styles.dialog} + buttons={buttons} + > + {children} + + ); +} + +/** + * `standalone`: fills the Get from VCS window; the cloned folder goes to `onCloned` (its project + * window) instead of opening here. + */ +export function CloneDialog({ + onClose, + initialUrl, + standalone = false, + onCloned, +}: { + onClose: () => void; + initialUrl: string; + standalone?: boolean; + onCloned?: (dir: string) => Promise; +}) { /** Sidebar selection: "url" (Repository URL) or a contributed source's id; each keeps its own URL. */ const [sourceId, setSourceId] = useState("url"); const [urls, setUrls] = useState>({ url: initialUrl }); @@ -188,6 +313,23 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl: else void callDesktop("cancel_request", { id }); }; + useEffect(() => { + if (!standalone || !isTauri()) return; + // Closing the window stops a clone in progress instead of leaving it running unseen. + let disposed = false; + let off: (() => void) | undefined; + void getCurrentWebviewWindow() + .onCloseRequested(() => { + const id = request.current; + if (id !== null) void callDesktop("cancel_request", { id }); + }) + .then((u) => (disposed ? u() : (off = u))); + return () => { + disposed = true; + off?.(); + }; + }, [standalone]); + const clone = async (picked?: string) => { const cloneUrl = picked ?? url; const target = (customDir ?? joinPath(parent, cloneDirName(cloneUrl))).trim(); @@ -205,17 +347,12 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl: await callDesktop("vcs_clone", { request: id, url: cloneUrl.trim(), dest: target, depth, onOutput: channel }); writeParent(parentOf(target)); rememberUrl(cloneUrl.trim()); - onClose(); - try { - await openProject(target); - } catch (e) { - notifications().notify({ - group: "vcs", - level: "error", - title: "Cloned, but the project could not be opened", - body: e instanceof Error ? e.message : String(e), - }); + if (onCloned) { + await onCloned(target); + return; } + onClose(); + await openCloned(target); } catch (e) { if (isCancelled(e)) setError("Clone cancelled"); else setError(e instanceof Error ? e.message : String(e)); @@ -226,165 +363,162 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl: } }; - return ( - - - Clone Repository - - } - aria-label="Clone Repository" - onClose={cancel} - width="min(920px, calc(100vw - 48px))" - resizable="both" - className={styles.dialog} - buttons={[ - { label: "Clone", role: "default", disabled: !!invalid || busy, onClick: () => void clone() }, - { label: "Cancel", role: "cancel", onClick: cancel }, - ]} - > -
- - -
{ - e.preventDefault(); - void clone(); - }} + const buttons: DialogButton[] = [ + { label: "Clone", role: "default", disabled: !!invalid || busy, onClick: () => void clone() }, + { label: "Cancel", role: "cancel", onClick: cancel }, + ]; + const sourceList = ( +
- - )} + + + {s.label} + + + ))} + + ); + const formView = ( + { + e.preventDefault(); + void clone(); + }} + > + {source ? ( +
+ void clone(u)} disabled={busy} /> +
+ ) : ( + <> +
+ + setCustomDir(e.target.value)} + placeholder="https://github.com/user/repository.git" + onChange={(e) => setUrl(e.target.value)} /> void browse()} + title={recentUrls.length ? "Recent repository URLs" : "No recent repository URLs"} + disabled={busy || !recentUrls.length} + onClick={showUrlHistory} />
+ + )} -
- Shallow clone with a history truncated to} - /> -
- setDepthInput(e.target.value)} - /> - commits -
-
- -
- {busy && ( -
- - {progress.line || tx("Cloning…")} -
- )} - {error &&
{error}
} - {!busy && !error && url.trim() && invalid && ( -
- {invalid} -
- )} -
- +
+ +
+ setCustomDir(e.target.value)} + /> + void browse()} + /> +
-
+ +
+ Shallow clone with a history truncated to} + /> +
+ setDepthInput(e.target.value)} + /> + commits +
+
+ +
+ {busy && ( +
+ + {progress.line || tx("Cloning…")} +
+ )} + {error &&
{error}
} + {!busy && !error && url.trim() && invalid && ( +
+ {invalid} +
+ )} +
+ + ); + + return ( + + {standalone ? ( + formView + ) : ( +
+ {sourceList} + {formView} +
+ )} + ); } diff --git a/src/features/vcs/cloneWindow.tsx b/src/features/vcs/cloneWindow.tsx new file mode 100644 index 0000000000..af6681ce59 --- /dev/null +++ b/src/features/vcs/cloneWindow.tsx @@ -0,0 +1,68 @@ +/** + * The Get from VCS window (`clone-`): the clone dialog in its own native window. The + * cloned folder opens in the parent project window. A later Get from VCS with a URL (a + * `x-github-client` link, say) fills it in here unless a clone is running. + */ +import { create } from "zustand"; +import { emitTo } from "@tauri-apps/api/event"; +import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow"; +import { commands } from "@/platform/ipc"; +import { closeDialogWindow, useDialogWindow } from "@/workbench/dialogWindow"; +import { OverlayHost } from "@/workbench/OverlayHost"; +import { useApplyTheme } from "@/workbench/theme"; +import { WindowResizeHandles } from "@/workbench/WindowResizeHandles"; +import { CLONED, CloneDialog } from "./clone"; + +/** Same event as `windows::LAUNCH_EVENT`: a pending launch (URL) is waiting. */ +const LAUNCH_EVENT = "openidea://launch"; + +/** The launch's URL, with a key that remounts the form for each new one. */ +const useLaunch = create<{ url: string; key: number } | null>(() => null); + +/** Takes this window's launches: the first one, then each a later Get from VCS hands over. */ +export function activateCloneLaunches(): () => void { + let disposed = false; + let off: (() => void) | undefined; + const take = (first: boolean) => + void commands + .windowTakeLaunch() + .catch(() => null) + .then((l) => { + const url = l?.cloneUrl ?? ""; + if (!disposed && (first || url)) useLaunch.setState((prev) => ({ url, key: (prev?.key ?? 0) + 1 }), true); + }); + take(true); + void getCurrentWebviewWindow() + .listen(LAUNCH_EVENT, () => take(false)) + .then((u) => (disposed ? u() : (off = u))); + return () => { + disposed = true; + off?.(); + }; +} + +export function CloneWindow() { + useApplyTheme(); + const parent = useDialogWindow((s) => s.parent); + const launch = useLaunch(); + const cloned = async (dir: string) => { + if (!parent) return; + await emitTo(parent, CLONED, { dir }); + closeDialogWindow(); + }; + return ( + <> + {parent && launch && ( + + )} + + + + ); +} diff --git a/src/features/vcs/index.ts b/src/features/vcs/index.ts index fffe8c57c4..bd751f4647 100644 --- a/src/features/vcs/index.ts +++ b/src/features/vcs/index.ts @@ -46,6 +46,7 @@ import { registerCompareActions } from "./compare"; import { activateDiffViewer } from "./diffViewer"; import { installDiffEditorHost } from "./DiffWindow"; import { VcsDialogHost } from "./dialogs"; +import { installCloneHandoff } from "./clone"; import { changeMarkers } from "./gutter"; import { installHunkPopup } from "./HunkPopup"; import { LOCAL_HISTORY_KIND } from "./localHistoryKind"; @@ -285,6 +286,7 @@ export function activate(): () => void { trackMergeRebaseItem(), installHunkPopup(), registerOverlay({ id: "vcs.dialogs", component: VcsDialogHost }), + installCloneHandoff(), registerOverlay({ id: "vcs.branches", component: BranchesPopupHost }), registerOverlay({ id: "vcs.syncCommits", component: SyncCommitsPopupHost }), activateConflictBanner(), diff --git a/src/features/welcome/WelcomeView.tsx b/src/features/welcome/WelcomeView.tsx index 72275442cb..013275c36f 100644 --- a/src/features/welcome/WelcomeView.tsx +++ b/src/features/welcome/WelcomeView.tsx @@ -148,7 +148,7 @@ export function WelcomeView() { const reopening = useSession((s) => s.reopening); // A remote project connecting with no dialog or list row to show it (a new window's). const connecting = useRemoteProgress((s) => s.location); - const connectDialog = useConnectDialog((s) => s.open); + const connectDialog = useConnectDialog((s) => s.open || s.inWindow); const listOpening = useRecent((s) => s.opening); const opening = useProject((s) => s.opening); const Plugins = useSettingsPages((s) => s.pages.get(PLUGINS_PAGE)?.component); diff --git a/src/main.tsx b/src/main.tsx index 0a8d868cdc..3fc7a24a4e 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -6,7 +6,7 @@ await initWebRuntime(); await installCommonWindowBoot(); // Auxiliary windows (`settings-`, `comparison--`, `diff--`, -// `deployment-`) load only their own module graph, without Workbench or CodeMirror +// `deployment-`, `new-project-`, `clone-`, `connect-`) load only their own module graph, without Workbench or CodeMirror // when not needed. const aux = auxiliaryWindow(); diff --git a/src/newProjectWindowBoot.ts b/src/newProjectWindowBoot.ts new file mode 100644 index 0000000000..8103abb0ef --- /dev/null +++ b/src/newProjectWindowBoot.ts @@ -0,0 +1,16 @@ +import type { ComponentType } from "react"; +import { installLocaleSync } from "./features/app/locale"; +import { NewProjectWindow } from "./features/app/newProjectWindow"; +import { trackRuntimeSettings } from "./features/settings/runtime"; +import { activateDialogWindow } from "./workbench/dialogWindow"; +import { activateList } from "./windowBoot"; + +/** New Project window of project window `parent`: the wizard only, no workbench. */ +export function bootNewProjectWindow(parent: string): ComponentType { + activateList("new project window", [ + ["locale", installLocaleSync], + ["settings", trackRuntimeSettings], + ["dialog", () => activateDialogWindow(parent)], + ]); + return NewProjectWindow; +} diff --git a/src/platform/auxWindow.test.ts b/src/platform/auxWindow.test.ts index c4b0043eef..80add84101 100644 --- a/src/platform/auxWindow.test.ts +++ b/src/platform/auxWindow.test.ts @@ -14,9 +14,13 @@ describe("auxiliaryWindow", () => { expect(auxiliaryWindow("editor-main-0")).toEqual({ kind: "editor", parent: "main" }); expect(auxiliaryWindow("editor-project-2-14")).toEqual({ kind: "editor", parent: "project-2" }); expect(auxiliaryWindow("deployment-project-2")).toEqual({ kind: "deployment", parent: "project-2" }); + expect(auxiliaryWindow("new-project-main")).toEqual({ kind: "new-project", parent: "main" }); + expect(auxiliaryWindow("new-project-project-2")).toEqual({ kind: "new-project", parent: "project-2" }); + expect(auxiliaryWindow("clone-main")).toEqual({ kind: "clone", parent: "main" }); + expect(auxiliaryWindow("connect-project-2")).toEqual({ kind: "connect", parent: "project-2" }); }); - it.each(["settings", "comparison", "diff", "editor", "deployment"])( + it.each(["settings", "comparison", "diff", "editor", "deployment", "new-project", "clone", "connect"])( "grants %s windows permission to close", (kind) => { expect(capability.windows).toContain(`${kind}-*`); diff --git a/src/platform/auxWindow.ts b/src/platform/auxWindow.ts index 5f8ee40efd..dc15680c83 100644 --- a/src/platform/auxWindow.ts +++ b/src/platform/auxWindow.ts @@ -1,5 +1,6 @@ /** - * Auxiliary windows: Settings, comparison and deployment windows that belong + * Auxiliary windows: Settings, comparison, deployment and dialog windows (New Project, Get from VCS, + * Remote Development) that belong * to a project window (their parent) and share its project. Labels name the * kind and the parent (`settings-main`, `comparison-project-2-3`), mirroring * `windows::auxiliary` in src-tauri/src/windows.rs. @@ -8,11 +9,30 @@ import { getAllWindows, getCurrentWindow } from "@tauri-apps/api/window"; import { TauriEvent } from "@tauri-apps/api/event"; import { isTauri } from "./ipc"; -export type AuxKind = "settings" | "comparison" | "diff" | "editor" | "deployment"; +export type AuxKind = + | "settings" + | "comparison" + | "diff" + | "editor" + | "deployment" + | "new-project" + | "clone" + | "connect"; /** Kinds with several windows per parent (`--`); the others have one (`-`). */ const MULTIPLE: ReadonlySet = new Set(["comparison", "diff", "editor"]); -const KINDS: readonly AuxKind[] = ["settings", "comparison", "diff", "editor", "deployment"]; +const KINDS: readonly AuxKind[] = [ + "settings", + "comparison", + "diff", + "editor", + "deployment", + "new-project", + "clone", + "connect", +]; +/** Kinds that show none of the parent's documents (`AuxKind::shares_documents` in windows.rs). */ +const WITHOUT_DOCUMENTS: ReadonlySet = new Set(["settings", "new-project", "clone", "connect"]); /** An auxiliary window reports to its parent whether it closed, and which documents it released. */ export const AUX_CLOSED = "openidea://auxiliary/closed"; @@ -64,7 +84,7 @@ export async function closeDocumentWindows(): Promise { const parent = getCurrentWindow(); const children = (await getAllWindows()).filter((window) => { const aux = auxiliaryWindow(window.label); - return aux !== null && aux.kind !== "settings" && aux.parent === parent.label; + return aux !== null && !WITHOUT_DOCUMENTS.has(aux.kind) && aux.parent === parent.label; }); for (const child of children) { let finish!: (closed: boolean) => void; diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 18209b6496..e67063e3f1 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -6182,5 +6182,7 @@ "Blocked command pattern": "Patrón de comando bloqueado", "Mode applies to": "El modo se aplica a", "Context": "Contexto", - "Allow all optional permissions": "Permitir todos los permisos opcionales" + "Allow all optional permissions": "Permitir todos los permisos opcionales", + "Get from Version Control": "Obtener del control de versiones", + "Cannot connect to the remote host": "No se puede conectar al host remoto" } diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index ae7c9a5193..42e29211c1 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -5826,5 +5826,7 @@ "Blocked command pattern": "Motif de commande bloquée", "Mode applies to": "Le mode s'applique à", "Context": "Contexte", - "Allow all optional permissions": "Autoriser toutes les autorisations facultatives" + "Allow all optional permissions": "Autoriser toutes les autorisations facultatives", + "Get from Version Control": "Récupérer depuis le contrôle de version", + "Cannot connect to the remote host": "Impossible de se connecter à l’hôte distant" } diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 82f1aa61d0..1750ed568e 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -6292,5 +6292,7 @@ "Blocked command pattern": "차단된 명령 패턴", "Mode applies to": "모드 적용 범위", "Context": "컨텍스트", - "Allow all optional permissions": "모든 선택 권한 허용" + "Allow all optional permissions": "모든 선택 권한 허용", + "Get from Version Control": "버전 관리에서 가져오기", + "Cannot connect to the remote host": "원격 호스트에 연결할 수 없음" } diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 43ff3433e7..930c11185e 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -5990,5 +5990,7 @@ "Blocked command pattern": "Wzorzec zablokowanego polecenia", "Mode applies to": "Tryb dotyczy", "Context": "Kontekst", - "Allow all optional permissions": "Zezwól na wszystkie opcjonalne uprawnienia" + "Allow all optional permissions": "Zezwól na wszystkie opcjonalne uprawnienia", + "Get from Version Control": "Pobierz z systemu kontroli wersji", + "Cannot connect to the remote host": "Nie można połączyć się z hostem zdalnym" } diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index ee7040959f..00a537d53a 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -6005,5 +6005,7 @@ "Blocked command pattern": "Padrão de comando bloqueado", "Mode applies to": "O modo se aplica a", "Context": "Contexto", - "Allow all optional permissions": "Permitir todas as permissões opcionais" + "Allow all optional permissions": "Permitir todas as permissões opcionais", + "Get from Version Control": "Obter do controle de versão", + "Cannot connect to the remote host": "Não é possível conectar ao host remoto" } diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index d8d4b38214..f118f86c02 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -10179,5 +10179,7 @@ "SQL INSERT": "SQL INSERT", "SQL UPDATE": "SQL UPDATE", "SQL DELETE": "SQL DELETE", - "Column comment": "Комментарий к столбцу" + "Column comment": "Комментарий к столбцу", + "Get from Version Control": "Получить из системы контроля версий", + "Cannot connect to the remote host": "Не удалось подключиться к удалённому хосту" } diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index 94774086e4..037ad015b2 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -8839,5 +8839,7 @@ "SQL INSERT": "SQL INSERT", "SQL UPDATE": "SQL UPDATE", "SQL DELETE": "SQL DELETE", - "Column comment": "Sütun yorumu" + "Column comment": "Sütun yorumu", + "Get from Version Control": "Sürüm Kontrolünden Al", + "Cannot connect to the remote host": "Uzak sunucuya bağlanılamıyor" } diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 295c936649..dcd5d3771d 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -9384,5 +9384,7 @@ "SQL INSERT": "SQL INSERT 陳述式", "SQL UPDATE": "SQL UPDATE 陳述式", "SQL DELETE": "SQL DELETE 陳述式", - "Column comment": "欄位註解" + "Column comment": "欄位註解", + "Get from Version Control": "從版本控制取得", + "Cannot connect to the remote host": "無法連線到遠端主機" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 44c793749a..4657d9d17f 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10654,5 +10654,7 @@ "Use {suggested} for this project": "对此项目使用 {suggested}", "GitHub account: @{activeLogin}": "GitHub 账户:@{activeLogin}", "Uses GitHub CLI's active account without setting GH_TOKEN in the project environment.": "使用 GitHub CLI 当前活动账户,不在项目环境中设置 GH_TOKEN。", - "Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations).": "将此账户的 GH_TOKEN 传递给此项目中启动的进程(终端、智能体、Git 和运行配置)。" + "Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations).": "将此账户的 GH_TOKEN 传递给此项目中启动的进程(终端、智能体、Git 和运行配置)。", + "Get from Version Control": "从版本控制获取", + "Cannot connect to the remote host": "无法连接到远程主机" } diff --git a/src/workbench/WindowDialogFrame.module.css b/src/workbench/WindowDialogFrame.module.css new file mode 100644 index 0000000000..c5c8d40958 --- /dev/null +++ b/src/workbench/WindowDialogFrame.module.css @@ -0,0 +1,79 @@ +.window { + height: 100%; + display: flex; + flex-direction: column; + min-width: 0; + background: var(--bg-island); + color: var(--fg); +} +/* Linux: frameless X11 windows have no shadow, so mark the edge in CSS. */ +.windowEdge { + position: relative; +} +.windowEdge::after { + content: ""; + position: absolute; + inset: 0; + z-index: 1; + pointer-events: none; + box-shadow: inset 0 0 0 1px var(--border-window); +} +.columns { + flex: 1; + min-height: 0; + display: flex; +} +.sidebar { + flex: 0 0 220px; + min-height: 0; + display: flex; + flex-direction: column; + border-right: 1px solid var(--border); + background: var(--bg-dialog, var(--bg-elev)); +} +/* Under the traffic lights: drags the window. */ +.sidebarTop { + flex: none; + height: var(--h-titlebar); +} +.main { + flex: 1; + min-width: 0; + min-height: 0; + display: flex; + flex-direction: column; +} +.header { + flex: none; + display: flex; + align-items: center; + height: var(--h-titlebar); + padding: 0 var(--space-4); +} +/* Without a sidebar the traffic lights sit at the header's start. */ +.headerBesideLights { + padding-left: 84px; +} +.title { + margin: 0; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--fg-strong); + font-size: var(--fs-ui); + font-weight: 600; +} +.body { + flex: 1; + min-height: 0; + overflow: auto; +} +.footer { + flex: none; + display: flex; + align-items: center; + justify-content: flex-end; + gap: var(--space-3); + padding: 12px var(--space-4) var(--space-4); +} diff --git a/src/workbench/WindowDialogFrame.tsx b/src/workbench/WindowDialogFrame.tsx new file mode 100644 index 0000000000..7ede9fcefa --- /dev/null +++ b/src/workbench/WindowDialogFrame.tsx @@ -0,0 +1,99 @@ +/** + * A dialog shown in its own native window. On macOS the optional sidebar runs the full height + * of the window with the traffic lights over its top, and the title heads the content, above + * the button row; there is no separate title strip. Windows and Linux are frameless + * (tauri..conf.json), so a page-drawn title bar with the caption buttons sits on top there. + * Esc and ⌘W cancel, like a dialog's Esc in the page. + */ +import clsx from "clsx"; +import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react"; +import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow"; +import { useTx } from "@/platform/i18n"; +import { isImeKey } from "@/platform/ime"; +import { isTauri } from "@/platform/ipc"; +import { usePlatform } from "@/platform/platformInfo"; +import { DialogButtons, isPopupOpen, type DialogButton } from "@/ui"; +import { useNativeTitlebar } from "./nativeTitlebar"; +import { TitleBar } from "./TitleBar"; +import { windowDragRegion } from "./window-drag"; +import styles from "./WindowDialogFrame.module.css"; + +export function WindowDialogFrame({ + title, + buttons, + onCancel, + sidebar, + bodyClassName, + children, +}: { + title: string; + buttons: readonly DialogButton[]; + /** Esc, ⌘W, and `cancel` buttons without their own handler. */ + onCancel: () => void; + /** Full-height navigation on the left (a list of kinds, sources…). */ + sidebar?: ReactNode; + bodyClassName?: string; + children: ReactNode; +}) { + const tx = useTx(); + const os = usePlatform((s) => s.os); + const frameless = usePlatform((s) => s.framelessTitleBar); + const ref = useRef(null); + const [header, setHeader] = useState(null); + // The traffic lights centre on the header's height. + useNativeTitlebar(frameless ? null : header); + const cancel = useRef(onCancel); + useLayoutEffect(() => { + cancel.current = onCancel; + }); + useEffect(() => { + ref.current?.querySelector("[data-autofocus]")?.focus({ preventScroll: true }); + }, []); + const windowTitle = tx(title); + useEffect(() => { + if (!isTauri()) return; + void getCurrentWebviewWindow() + .setTitle(windowTitle) + .catch(() => {}); + }, [windowTitle]); + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.defaultPrevented || isImeKey(e)) return; + const mod = e.metaKey || e.ctrlKey; + if ((e.key === "Escape" && !isPopupOpen()) || (mod && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "w")) { + e.preventDefault(); + cancel.current(); + } + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, []); + return ( +
+ {frameless && } +
+ {sidebar !== undefined && ( + + )} +
+ {!frameless && ( +
+

{windowTitle}

+
+ )} +
{children}
+ +
+
+
+ ); +} diff --git a/src/workbench/dialogWindow.ts b/src/workbench/dialogWindow.ts new file mode 100644 index 0000000000..a30bcd27c1 --- /dev/null +++ b/src/workbench/dialogWindow.ts @@ -0,0 +1,28 @@ +/** + * Windows that show one dialog of their project window (New Project, Get from VCS): they load + * the parent's project and settings for the dialog's defaults, then hand results back to it. + */ +import { create } from "zustand"; +import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow"; +import { logError } from "@/platform/errorLog"; +import { commands } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; + +/** The parent window's label, set once its project and settings are here. */ +export const useDialogWindow = create<{ parent: string | null }>(() => ({ parent: null })); + +export function activateDialogWindow(parent: string): void { + void (async () => { + try { + const project = await commands.projectCurrent(); + useProject.setState( + project ? { project, settings: project.settings } : { project: null, settings: await commands.settingsGet() }, + ); + } catch (e) { + logError("cannot load the project of a dialog window", e); + } + useDialogWindow.setState({ parent }); + })(); +} + +export const closeDialogWindow = () => void getCurrentWebviewWindow().close();