Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai a5eff28b68 fix(ui): give a macOS dialog without footer buttons a Close button
A sheet has no window buttons, so a dialog with neither buttons nor a
footer could only be closed with Esc. The Extract Interface members
table may shrink to two rows so the dialog still fits a short window
under the taller sheet title.
2026-11-27 08:54:03 +08:00
l0ng-ai 44338541b1 feat(ui): show dialogs in the page as sheets without window buttons on macOS
The title heads the content instead of a title bar with drawn traffic
lights; Esc and Cancel close the dialog, and the title dims while the
window is inactive.
2026-11-27 08:37:23 +08:00
l0ng-ai d3c5055954 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.
2026-11-27 08:37:23 +08:00
47 змінених файлів з 1510 додано та 439 видалено

No files matched your search

+12 -1
Переглянути файл
@@ -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",
+12 -1
Переглянути файл
@@ -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"]
}
+40 -1
Переглянути файл
@@ -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<String>,
) -> 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<String>,
background: Option<String>,
) -> 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<String>) -> 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,
+107 -8
Переглянути файл
@@ -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<Box<EditorLaunch>>,
/// Get from VCS windows: the repository URL to fill in.
#[serde(default)]
pub clone_url: Option<String>,
}
/// 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<String>) -> 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<String>,
background: Option<String>,
) -> 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<String>) -> 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<AuxGeometry>, 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");
}
+3
Переглянути файл
@@ -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
+15
Переглянути файл
@@ -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;
}
}
}
+21
Переглянути файл
@@ -2394,11 +2394,21 @@ export const commands = {
windowIsFullscreen: () => __TAURI_INVOKE<boolean>("window_is_fullscreen"),
/** Opens an empty (welcome) window; returns its label. */
windowNew: () => typedError<string, IdeError>(__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<null, IdeError>(__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<null, IdeError>(__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<null, IdeError>(__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<IpcPath[], IdeError>(__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<null, IdeError>(__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-<parent>` 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";
+20
Переглянути файл
@@ -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;
}
+16
Переглянути файл
@@ -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;
}
+1 -1
Переглянути файл
@@ -44,7 +44,7 @@
.table {
flex: 1;
min-height: calc(var(--h-list-row) * 3);
min-height: calc(var(--h-list-row) * 2);
overflow: auto;
scrollbar-gutter: stable;
scroll-padding-top: var(--h-list-row);
+277 -143
Переглянути файл
@@ -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-<parent>`, 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 ? <NewProjectDialog onClose={() => 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 (
<WindowDialogFrame
title="New Project"
buttons={buttons}
onCancel={onClose}
sidebar={sidebar}
bodyClassName={styles.windowBody}
>
{children}
</WindowDialogFrame>
);
return form ? (
<Dialog
open
title="New Project"
onClose={onClose}
width={860}
resizable="both"
minWidth={720}
minHeight={480}
initialSize={loadDialogSize()}
onResized={saveDialogSize}
className={styles.dialog}
buttons={buttons}
>
{children}
</Dialog>
) : (
<Dialog open title="New Project" onClose={onClose} width={860} buttons={buttons}>
{children}
</Dialog>
);
}
/**
* 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<void>;
}) {
const tx = useTx();
const txTemplate = useTxTemplate();
const [catalog, setCatalog] = useState<GeneratorInfo[] | null>(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 <ProgressView job={job} onBack={() => setJob(null)} onClose={onClose} />;
if (job) return <ProgressView job={job} standalone={standalone} onBack={() => setJob(null)} onClose={onClose} />;
return (
<Dialog
open
title="New Project"
onClose={onClose}
width={860}
resizable="both"
minWidth={720}
minHeight={480}
initialSize={loadDialogSize()}
onResized={saveDialogSize}
className={styles.dialog}
buttons={[
{ label: "Create", role: "default", disabled: invalid, onClick: () => void createProject() },
{ label: "Cancel", role: "cancel" },
]}
const buttons: DialogButton[] = [
{ label: "Create", role: "default", disabled: invalid, onClick: () => void createProject() },
{ label: "Cancel", role: "cancel" },
];
const generators = (
<>
<Input
className={styles.search}
value={query}
placeholder="Search"
onChange={(e) => setQuery(e.target.value)}
aria-label="Search generators"
/>
<div className={styles.list} role="listbox" aria-label={tx("Generators")}>
{catalogError && <div className={styles.error}>{txTemplate(catalogError)}</div>}
{groupedEntries(catalog ?? [], query).map(([group, entries]) => (
<div key={group} role="group" aria-label={tx(group)}>
<div className={styles.groupLabel}>{tx(group)}</div>
{entries.map((g) => (
<button
key={g.id}
type="button"
role="option"
aria-selected={g.id === selected}
className={styles.entry}
title={tx(g.name)}
onClick={() => setSelected(g.id)}
>
<Icon name={hasIcon(g.icon) ? g.icon : "folder"} />
<span>{tx(g.name)}</span>
</button>
))}
</div>
))}
</div>
</>
);
const formView = (
<form
className={styles.form}
onSubmit={(e) => {
e.preventDefault();
void createProject();
}}
>
{generator?.description && <div className={styles.description}>{tx(generator.description)}</div>}
<div className={styles.grid}>
<label className={styles.label} htmlFor="np-name">
<T>Name:</T>
</label>
<Input
id="np-name"
data-autofocus
value={name}
invalid={!!nameError}
onChange={(e) => {
setNameEdited(true);
setName(e.target.value);
}}
/>
<label className={styles.label} htmlFor="np-location">
<T>Location:</T>
</label>
<div className={styles.location}>
<Input
id="np-location"
variant="bare"
className={styles.locationInput}
value={location}
onChange={(e) => setLocation(e.target.value)}
/>
<IconButton
icon="folder-open"
title="Browse…"
size="small"
onClick={() => void browse()}
disabled={!isTauri()}
/>
</div>
<span />
<div className={nameError ? `${styles.hint} ${styles.hintError}` : styles.hint}>
{nameError ? txTemplate(nameError) : path && txTemplate(`Project will be created in: ${path}`)}
</div>
{generator?.git && (
<>
<span />
<Checkbox checked={git} onChange={setGit} label="Create Git repository" />
</>
)}
{visibleFields.map((f) => (
<FieldRow
key={f.id}
field={f}
value={values[f.id] ?? ""}
onChange={(v) => setValue(f.id, v)}
sdks={f.kind.type === "sdk" ? (sdks[f.kind.sdk] ?? null) : null}
/>
))}
{loadingDynamic && (
<>
<span />
<div className={styles.hint}>
<T>Loading options…</T>
</div>
</>
)}
{dynamicError && (
<>
<span />
<div className={styles.error}>{txTemplate(dynamicError)}</div>
</>
)}
</div>
{missing.map((r) => (
<div key={r.program} className={styles.missing}>
<Icon name="warning" />
<span>
{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)}
</span>
</div>
))}
</form>
);
if (standalone)
return (
<Frame standalone onClose={onClose} buttons={buttons} sidebar={generators}>
{formView}
</Frame>
);
return (
<Frame standalone={false} form onClose={onClose} buttons={buttons}>
<SplitGroup
className={styles.layout}
elementRef={layout}
@@ -378,128 +605,14 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
maxSize="45%"
className={styles.sidebar}
>
<Input
className={styles.search}
value={query}
placeholder="Search"
onChange={(e) => setQuery(e.target.value)}
aria-label="Search generators"
/>
<div className={styles.list} role="listbox" aria-label={tx("Generators")}>
{catalogError && <div className={styles.error}>{txTemplate(catalogError)}</div>}
{groupedEntries(catalog ?? [], query).map(([group, entries]) => (
<div key={group} role="group" aria-label={tx(group)}>
<div className={styles.groupLabel}>{tx(group)}</div>
{entries.map((g) => (
<button
key={g.id}
type="button"
role="option"
aria-selected={g.id === selected}
className={styles.entry}
title={tx(g.name)}
onClick={() => setSelected(g.id)}
>
<Icon name={hasIcon(g.icon) ? g.icon : "folder"} />
<span>{tx(g.name)}</span>
</button>
))}
</div>
))}
</div>
{generators}
</SplitPanel>
<SplitHandle aria-label={tx("Generators")} />
<SplitPanel id="new-project-form" defaultSize="75%">
<form
className={styles.form}
onSubmit={(e) => {
e.preventDefault();
void createProject();
}}
>
{generator?.description && <div className={styles.description}>{tx(generator.description)}</div>}
<div className={styles.grid}>
<label className={styles.label} htmlFor="np-name">
<T>Name:</T>
</label>
<Input
id="np-name"
data-autofocus
value={name}
invalid={!!nameError}
onChange={(e) => {
setNameEdited(true);
setName(e.target.value);
}}
/>
<label className={styles.label} htmlFor="np-location">
<T>Location:</T>
</label>
<div className={styles.location}>
<Input
id="np-location"
variant="bare"
className={styles.locationInput}
value={location}
onChange={(e) => setLocation(e.target.value)}
/>
<IconButton
icon="folder-open"
title="Browse…"
size="small"
onClick={() => void browse()}
disabled={!isTauri()}
/>
</div>
<span />
<div className={nameError ? `${styles.hint} ${styles.hintError}` : styles.hint}>
{nameError ? txTemplate(nameError) : path && txTemplate(`Project will be created in: ${path}`)}
</div>
{generator?.git && (
<>
<span />
<Checkbox checked={git} onChange={setGit} label="Create Git repository" />
</>
)}
{visibleFields.map((f) => (
<FieldRow
key={f.id}
field={f}
value={values[f.id] ?? ""}
onChange={(v) => setValue(f.id, v)}
sdks={f.kind.type === "sdk" ? (sdks[f.kind.sdk] ?? null) : null}
/>
))}
{loadingDynamic && (
<>
<span />
<div className={styles.hint}>
<T>Loading options…</T>
</div>
</>
)}
{dynamicError && (
<>
<span />
<div className={styles.error}>{txTemplate(dynamicError)}</div>
</>
)}
</div>
{missing.map((r) => (
<div key={r.program} className={styles.missing}>
<Icon name="warning" />
<span>
{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)}
</span>
</div>
))}
</form>
{formView}
</SplitPanel>
</SplitGroup>
</Dialog>
</Frame>
);
}
@@ -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<HTMLPreElement>(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 (
<Dialog
open
title="New Project"
<Frame
standalone={standalone}
onClose={() => (failed ? onClose() : job.cancel())}
width={860}
buttons={
failed
? [
@@ -700,6 +834,6 @@ function ProgressView({ job, onBack, onClose }: { job: Job; onBack: () => void;
</pre>
{failed && <div className={styles.error}>{txTemplate(job.error ?? "")}</div>}
</div>
</Dialog>
</Frame>
);
}
+13 -1
Переглянути файл
@@ -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(<NewProjectDialog standalone onClose={() => {}} 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", () => {
+14
Переглянути файл
@@ -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;
}
+27
Переглянути файл
@@ -0,0 +1,27 @@
/**
* The New Project window (`new-project-<parent>`): 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 && <NewProjectDialog standalone onClose={closeDialogWindow} onCreated={created} />}
<OverlayHost />
<WindowResizeHandles />
</>
);
}
+11
Переглянути файл
@@ -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)),
};
+2 -7
Переглянути файл
@@ -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,
+16 -1
Переглянути файл
@@ -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(<ConnectDialog standalone onClose={close} onConnect={connect} />);
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();
});
+59 -13
Переглянути файл
@@ -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 (
<WindowDialogFrame title="Remote Development" buttons={buttons} onCancel={onClose}>
{children}
</WindowDialogFrame>
);
return (
<Dialog open title={tx("Remote Development")} onClose={onClose} width={560} buttons={buttons}>
{children}
</Dialog>
);
}
/**
* `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<boolean>;
}) {
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 (
<Dialog
open
title={tx("Remote Development")}
onClose={closeConnectDialog}
width={560}
<Frame
standalone={standalone}
onClose={onClose}
buttons={[
{
label: connecting ? "Connecting…" : "Open",
@@ -134,7 +180,7 @@ function ConnectDialog() {
]}
>
<form
className={styles.form}
className={standalone ? `${styles.form} ${styles.windowForm}` : styles.form}
onSubmit={(e) => {
e.preventDefault();
if (ready) void connect();
@@ -185,7 +231,7 @@ function ConnectDialog() {
}}
aria-label={tx("SSH configuration")}
/>
<Button onClick={() => void executeAction("file.settings", SSH_SETTINGS_PAGE)}>{tx("Configure…")}</Button>
<Button onClick={configure}>{tx("Configure…")}</Button>
</div>
</>
)}
@@ -235,7 +281,7 @@ function ConnectDialog() {
</div>
)}
</form>
</Dialog>
</Frame>
);
}
+4
Переглянути файл
@@ -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;
}
+135
Переглянути файл
@@ -0,0 +1,135 @@
/**
* The Remote Development window (`connect-<parent>`): 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<typeof getCurrentWebviewWindow>;
try {
self = getCurrentWebviewWindow();
} catch {
return () => {}; // Not a desktop window (tests).
}
let disposed = false;
let off: (() => void) | undefined;
void self
.listen<ConnectRequest>(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<boolean> {
const self = getCurrentWebviewWindow();
const id = ++nextId;
const offs: Array<() => void> = [];
try {
const result = new Promise<ConnectResult>((resolve) => {
void self
.listen<ConnectResult>(RESULT, ({ payload }) => payload.id === id && resolve(payload))
.then((u) => {
offs.push(u);
});
});
offs.push(
await self.listen<RemoteProgress | null>(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 && <ConnectDialog standalone onClose={closeDialogWindow} onConnect={connect} />}
<OverlayHost />
<WindowResizeHandles />
</>
);
}
+4 -2
Переглянути файл
@@ -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",
+2 -1
Переглянути файл
@@ -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 });
+1 -1
Переглянути файл
@@ -172,7 +172,7 @@ describe("Commit dialog diff window (#1863)", () => {
? "[data-testid='diff-view']"
: location === "footer"
? "[data-dialog-footer] button"
: "[data-dialog-titlebar] button",
: "[data-dialog-titlebar]",
)!;
fireEvent.keyDown(target, { key: "w", code: "KeyW", metaKey: true });
expect(closeTab).not.toHaveBeenCalled();
+34 -11
Переглянути файл
@@ -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);
}
+293 -159
Переглянути файл
@@ -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-<parent>`, 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<string> {
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) => <CloneDialog onClose={close} initialUrl={initialUrl} />);
const inPage = () => openDialog((close) => <CloneDialog onClose={close} initialUrl={initialUrl} />);
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<typeof getCurrentWebviewWindow>;
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 (
<WindowDialogFrame
title="Get from Version Control"
buttons={buttons}
onCancel={onCancel}
sidebar={sidebar}
bodyClassName={styles.windowBody}
>
{children}
</WindowDialogFrame>
);
return (
<Dialog
open
title={
<span className={styles.dialogTitle}>
<img src={logo} alt="" draggable={false} />
<T>Clone Repository</T>
</span>
}
aria-label="Clone Repository"
onClose={onCancel}
width="min(920px, calc(100vw - 48px))"
resizable="both"
className={styles.dialog}
buttons={buttons}
>
{children}
</Dialog>
);
}
/**
* `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<void>;
}) {
/** 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<Record<string, string>>({ 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 (
<Dialog
open
title={
<span className={styles.dialogTitle}>
<img src={logo} alt="" draggable={false} />
<T>Clone Repository</T>
</span>
}
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 },
]}
>
<div ref={layout} className={styles.layout} data-compact={compact || undefined}>
<aside className={styles.sidebar} aria-label={tx("Clone source")}>
{[{ id: "url", label: "Repository URL", icon: "branch" }, ...sources].map((s) => (
<button
key={s.id}
type="button"
className={styles.sourceItem}
data-selected={s.id === sourceId ? "" : undefined}
aria-pressed={s.id === sourceId}
disabled={busy}
onClick={() => setSourceId(s.id)}
>
<Icon name={s.icon} size={16} />
<span className={styles.sourceName}>
<T>{s.label}</T>
</span>
</button>
))}
</aside>
<form
className={styles.form}
onSubmit={(e) => {
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 = (
<aside className={standalone ? styles.windowSources : styles.sidebar} aria-label={tx("Clone source")}>
{[{ id: "url", label: "Repository URL", icon: "branch" }, ...sources].map((s) => (
<button
key={s.id}
type="button"
className={styles.sourceItem}
data-selected={s.id === sourceId ? "" : undefined}
aria-pressed={s.id === sourceId}
disabled={busy}
onClick={() => setSourceId(s.id)}
>
{source ? (
<div className={styles.sourcePane}>
<source.component url={url} onUrl={setUrl} onClone={(u) => void clone(u)} disabled={busy} />
</div>
) : (
<>
<div className={styles.fieldRow}>
<label htmlFor="vcs-clone-version">
<T>Version control:</T>
</label>
<Select
id="vcs-clone-version"
aria-label="Version control"
className={styles.versionSelect}
value="git"
options={[{ value: "git", label: "Git" }]}
onChange={() => {}}
disabled={busy}
/>
</div>
<div className={styles.fieldRow}>
<label htmlFor="vcs-clone-url">
<T>URL:</T>
</label>
<div ref={urlField} className={styles.comboField}>
<Input
id="vcs-clone-url"
data-autofocus
variant="bare"
className={styles.fieldInput}
value={url}
disabled={busy}
placeholder="https://github.com/user/repository.git"
onChange={(e) => setUrl(e.target.value)}
/>
<IconButton
icon="chevron-down"
size="normal"
className={styles.fieldButton}
title={recentUrls.length ? "Recent repository URLs" : "No recent repository URLs"}
disabled={busy || !recentUrls.length}
onClick={showUrlHistory}
/>
</div>
</div>
</>
)}
<Icon name={s.icon} size={16} />
<span className={styles.sourceName}>
<T>{s.label}</T>
</span>
</button>
))}
</aside>
);
const formView = (
<form
className={styles.form}
onSubmit={(e) => {
e.preventDefault();
void clone();
}}
>
{source ? (
<div className={styles.sourcePane}>
<source.component url={url} onUrl={setUrl} onClone={(u) => void clone(u)} disabled={busy} />
</div>
) : (
<>
<div className={styles.fieldRow}>
<label htmlFor="vcs-clone-version">
<T>Version control:</T>
</label>
<Select
id="vcs-clone-version"
aria-label="Version control"
className={styles.versionSelect}
value="git"
options={[{ value: "git", label: "Git" }]}
onChange={() => {}}
disabled={busy}
/>
</div>
<div className={styles.fieldRow}>
<label htmlFor="vcs-clone-dir">
<T>Directory:</T>
<label htmlFor="vcs-clone-url">
<T>URL:</T>
</label>
<div className={styles.comboField}>
<div ref={urlField} className={styles.comboField}>
<Input
id="vcs-clone-dir"
id="vcs-clone-url"
data-autofocus
variant="bare"
className={styles.fieldInput}
value={dir}
value={url}
disabled={busy}
onChange={(e) => setCustomDir(e.target.value)}
placeholder="https://github.com/user/repository.git"
onChange={(e) => setUrl(e.target.value)}
/>
<IconButton
icon="folder-open"
icon="chevron-down"
size="normal"
className={styles.fieldButton}
title="Browse…"
disabled={busy}
onClick={() => void browse()}
title={recentUrls.length ? "Recent repository URLs" : "No recent repository URLs"}
disabled={busy || !recentUrls.length}
onClick={showUrlHistory}
/>
</div>
</div>
</>
)}
<div className={styles.shallowRow}>
<Checkbox
checked={shallow}
disabled={busy}
onChange={setShallow}
label={<T>Shallow clone with a history truncated to</T>}
/>
<div className={styles.depthGroup}>
<Input
aria-label="Clone depth"
className={styles.depthInput}
type="number"
inputMode="numeric"
min={1}
step={1}
value={depthInput}
disabled={busy || !shallow}
invalid={shallow && depth === null}
onChange={(e) => setDepthInput(e.target.value)}
/>
<T>commits</T>
</div>
</div>
<div className={styles.feedback}>
{busy && (
<div className={styles.progress} aria-live="polite">
<ProgressBar value={progress.fraction} aria-label="Clone progress" />
<span className={styles.hint}>{progress.line || tx("Cloning…")}</span>
</div>
)}
{error && <div className={styles.error}>{error}</div>}
{!busy && !error && url.trim() && invalid && (
<div className={styles.hint}>
<T>{invalid}</T>
</div>
)}
</div>
</form>
<div className={styles.fieldRow}>
<label htmlFor="vcs-clone-dir">
<T>Directory:</T>
</label>
<div className={styles.comboField}>
<Input
id="vcs-clone-dir"
variant="bare"
className={styles.fieldInput}
value={dir}
disabled={busy}
onChange={(e) => setCustomDir(e.target.value)}
/>
<IconButton
icon="folder-open"
size="normal"
className={styles.fieldButton}
title="Browse…"
disabled={busy}
onClick={() => void browse()}
/>
</div>
</div>
</Dialog>
<div className={styles.shallowRow}>
<Checkbox
checked={shallow}
disabled={busy}
onChange={setShallow}
label={<T>Shallow clone with a history truncated to</T>}
/>
<div className={styles.depthGroup}>
<Input
aria-label="Clone depth"
className={styles.depthInput}
type="number"
inputMode="numeric"
min={1}
step={1}
value={depthInput}
disabled={busy || !shallow}
invalid={shallow && depth === null}
onChange={(e) => setDepthInput(e.target.value)}
/>
<T>commits</T>
</div>
</div>
<div className={styles.feedback}>
{busy && (
<div className={styles.progress} aria-live="polite">
<ProgressBar value={progress.fraction} aria-label="Clone progress" />
<span className={styles.hint}>{progress.line || tx("Cloning…")}</span>
</div>
)}
{error && <div className={styles.error}>{error}</div>}
{!busy && !error && url.trim() && invalid && (
<div className={styles.hint}>
<T>{invalid}</T>
</div>
)}
</div>
</form>
);
return (
<Frame standalone={standalone} onCancel={cancel} buttons={buttons} sidebar={sourceList}>
{standalone ? (
formView
) : (
<div ref={layout} className={styles.layout} data-compact={compact || undefined}>
{sourceList}
{formView}
</div>
)}
</Frame>
);
}
+68
Переглянути файл
@@ -0,0 +1,68 @@
/**
* The Get from VCS window (`clone-<parent>`): 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 && (
<CloneDialog
key={launch.key}
standalone
initialUrl={launch.url}
onClose={closeDialogWindow}
onCloned={cloned}
/>
)}
<OverlayHost />
<WindowResizeHandles />
</>
);
}
+2
Переглянути файл
@@ -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(),
+1 -1
Переглянути файл
@@ -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);
+1 -1
Переглянути файл
@@ -6,7 +6,7 @@ await initWebRuntime();
await installCommonWindowBoot();
// Auxiliary windows (`settings-<parent>`, `comparison-<parent>-<n>`, `diff-<parent>-<n>`,
// `deployment-<parent>`) load only their own module graph, without Workbench or CodeMirror
// `deployment-<parent>`, `new-project-<parent>`, `clone-<parent>`, `connect-<parent>`) load only their own module graph, without Workbench or CodeMirror
// when not needed.
const aux = auxiliaryWindow();
+16
Переглянути файл
@@ -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;
}
+5 -1
Переглянути файл
@@ -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}-*`);
+24 -4
Переглянути файл
@@ -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 (`<kind>-<parent>-<n>`); the others have one (`<kind>-<parent>`). */
const MULTIPLE: ReadonlySet<AuxKind> = 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<AuxKind> = 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<boolean> {
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;
+3 -1
Переглянути файл
@@ -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"
}
+3 -1
Переглянути файл
@@ -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"
}
+3 -1
Переглянути файл
@@ -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": "원격 호스트에 연결할 수 없음"
}
+3 -1
Переглянути файл
@@ -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"
}
+3 -1
Переглянути файл
@@ -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"
}
+3 -1
Переглянути файл
@@ -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": "Не удалось подключиться к удалённому хосту"
}
+3 -1
Переглянути файл
@@ -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"
}
+3 -1
Переглянути файл
@@ -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": "無法連線到遠端主機"
}
+3 -1
Переглянути файл
@@ -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": "无法连接到远程主机"
}
+9 -51
Переглянути файл
@@ -83,9 +83,8 @@
touch-action: none;
}
.macTitleBar {
height: var(--h-dialog-titlebar-mac, 28px);
padding: 0 12px 0 8px;
gap: var(--space-3);
height: var(--h-dialog-titlebar-mac, 40px);
padding: 0 var(--space-4);
}
.popupHeader {
height: 32px;
@@ -107,54 +106,9 @@
.macTitleBar .title {
font-size: var(--fs-ui);
}
/* NSWindow standard buttons: 12px, 8px apart; close red, minimise / zoom disabled (modal). */
.lights {
flex: none;
display: inline-flex;
gap: var(--space-2);
}
.light {
position: relative;
width: 12px;
height: 12px;
padding: 0;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 50%;
background: var(--traffic-off);
box-shadow: inset 0 0 0 0.5px var(--traffic-off-border);
cursor: default;
}
.lightClose {
background: var(--traffic-close);
box-shadow: inset 0 0 0 0.5px var(--traffic-close-border);
}
[data-inactive] .lightClose {
background: var(--traffic-off);
box-shadow: inset 0 0 0 0.5px var(--traffic-off-border);
}
.lightGlyph {
--icon-color: var(--traffic-glyph);
color: var(--traffic-glyph);
opacity: 0;
}
.lights:hover .lightClose,
.lightClose:focus-visible {
background: var(--traffic-close);
box-shadow: inset 0 0 0 0.5px var(--traffic-close-border);
}
.lights:hover .lightGlyph,
.lightClose:focus-visible .lightGlyph {
opacity: 1;
}
.lightClose:active {
background: var(--traffic-close-pressed);
}
.lightClose:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: 1px;
/* An inactive window's title dims, as AppKit's does. */
[data-inactive] .macTitleBar .title {
color: var(--fg-muted);
}
.body {
@@ -187,6 +141,10 @@
gap: var(--space-3);
padding: 12px 16px;
}
/* macOS: the buttons sit in the content's corner, as in the dialog windows. */
[data-platform="mac"] > .footer:not(.messageFooter) {
padding-bottom: var(--space-4);
}
.footerStart {
flex: 1 1 0;
min-width: fit-content;
+3 -6
Переглянути файл
@@ -64,17 +64,14 @@ describe("Dialog chrome", () => {
</Dialog>,
);
it("macOS: traffic lights (only close enabled), title after them, Cancel … default rightmost", () => {
it("macOS: a sheet titled in its content, no window buttons, Cancel … default rightmost", () => {
const onClose = vi.fn();
show("mac", onClose);
const bar = document.querySelector("[data-dialog-titlebar]") as HTMLElement;
const lights = within(bar).getAllByRole("button");
expect(lights.map((b) => b.getAttribute("aria-label"))).toEqual(["Close", "Minimize", "Zoom"]);
expect(lights[1]).toBeDisabled();
expect(lights[2]).toBeDisabled();
expect(within(bar).queryAllByRole("button")).toEqual([]);
expect(bar.textContent).toBe("Usages Detected");
expect(footerLabels()).toEqual(["Cancel", "Delete Anyway", "View Usages"]);
fireEvent.click(lights[0]!);
fireEvent.keyDown(document.activeElement ?? document.body, { key: "Escape" });
expect(onClose).toHaveBeenCalledTimes(1);
});
+9 -15
Переглянути файл
@@ -3,7 +3,6 @@ import { createPortal } from "react-dom";
import clsx from "clsx";
import { usePlatform } from "@/platform/platformInfo";
import { Button, IconButton } from "./Button";
import { Icon } from "./icons";
import { FOCUSABLE, dismissPopups, onWindowDeactivate, openLayer, trapTab } from "./popupState";
import { PopupAncestry } from "./Popup";
import { tx, useGivenTx } from "@/platform/i18n";
@@ -44,6 +43,8 @@ export function useDialogPlatform(override?: DialogPlatform): DialogPlatform {
return override ?? dialogPlatformOf(os);
}
const MAC_CLOSE_BUTTONS: readonly DialogButton[] = [{ label: "Close", role: "cancel" }];
const MAC_ORDER: Record<DialogButtonRole, number> = { cancel: -10, extra: 0, default: 100 };
/**
@@ -217,7 +218,7 @@ function DialogInner({
blockWorkbenchShortcuts = false,
title,
children,
buttons,
buttons: givenButtons,
footerStart,
onHelp,
footer,
@@ -244,6 +245,10 @@ function DialogInner({
const given = useGivenTx();
if (typeof title === "string") title = given(title);
const popup = asPopup || position === "top" || (title == null && !icon);
// A macOS sheet has no close button of its own: one without footer buttons gets a Close button
// so it can still be closed with the mouse.
const buttons =
platform === "mac" && !popup && !icon && !givenButtons?.length && !footer ? MAC_CLOSE_BUTTONS : givenButtons;
const onCloseRef = useRef(onClose);
const buttonsRef = useRef(buttons);
const restoreFocusRef = useRef(restoreFocus);
@@ -462,20 +467,9 @@ function DialogInner({
</div>
)
) : platform === "mac" ? (
// A sheet over the window, as the dialog windows look: the title heads the content, no
// window buttons of its own (Esc and Cancel or Close close it).
<div className={clsx(styles.titleBar, styles.macTitleBar)} data-dialog-drag="" data-dialog-titlebar="">
<span className={styles.lights}>
<button
type="button"
tabIndex={-1}
className={clsx(styles.light, styles.lightClose)}
aria-label={tx("Close")}
onClick={onClose}
>
<Icon name="close" size={10} className={styles.lightGlyph} />
</button>
<button type="button" tabIndex={-1} disabled className={styles.light} aria-label={tx("Minimize")} />
<button type="button" tabIndex={-1} disabled className={styles.light} aria-label={tx("Zoom")} />
</span>
<span className={styles.title}>{title}</span>
</div>
) : (
+79
Переглянути файл
@@ -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);
}
+99
Переглянути файл
@@ -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.<os>.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<HTMLElement>(null);
const [header, setHeader] = useState<HTMLElement | null>(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<HTMLElement>("[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 (
<section ref={ref} className={clsx(styles.window, os === "linux" && styles.windowEdge)} aria-label={windowTitle}>
{frameless && <TitleBar minimal dialog title={windowTitle} />}
<div className={styles.columns}>
{sidebar !== undefined && (
<aside className={styles.sidebar}>
{!frameless && <div className={styles.sidebarTop} {...windowDragRegion} />}
{sidebar}
</aside>
)}
<div className={styles.main}>
{!frameless && (
<header
ref={setHeader}
className={clsx(styles.header, sidebar === undefined && styles.headerBesideLights)}
{...windowDragRegion}
>
<h1 className={styles.title}>{windowTitle}</h1>
</header>
)}
<div className={clsx(styles.body, bodyClassName)}>{children}</div>
<footer className={styles.footer}>
<DialogButtons buttons={buttons} onCancel={onCancel} />
</footer>
</div>
</div>
</section>
);
}
+28
Переглянути файл
@@ -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();