Файли
openidea/src/features/vcs/DiffWindow.tsx
T
audichuang 9592b9ee1b fix(vcs): Jump to Source in the comparison window opens the file in the project window (#6595)
Jump to Source from a diff in the Compare with Branch window went to the comparison window's own editor area, which stays hidden until Show Diff, so nothing appeared. The comparison window now hands openFile to the project window's editor, as the diff window does, for files in any folder of the project (workspace projects included); files outside the project still open in the comparison window.

Fixes #6405

Co-authored-by: audichuang <[email protected]>
2026-11-28 06:59:28 +08:00

359 рядки
13 KiB
TypeScript
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
/**
* The diff window (`diff-<parent>-<n>`): one file's diff in a window of its own (IDEA's
* "Show Diff in New Window"), beside its project window.
*/
import clsx from "clsx";
import { create } from "zustand";
import { flushSync } from "react-dom";
import { registerAction } from "@/platform/actions";
import { emitTo } from "@tauri-apps/api/event";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { activateEmbeddedDocuments } from "@/editor/core/embeddedDocuments";
import { tx } from "@/platform/i18n";
import { AUX_CLOSED, type AuxCloseResult } from "@/platform/auxWindow";
import { setContext } from "@/platform/context";
import { isImeKey } from "@/platform/ime";
import { call, commands, isTauri, type DiffLaunch } from "@/platform/ipc";
import { projectFolder, useProject } from "@/platform/project";
import { installDiffWindowSave } from "./diffWindowSave";
import { restoreRemote } from "@/platform/remote";
import { usePlatform } from "@/platform/platformInfo";
import { Spinner, T, isPopupOpen, lazyComponent } from "@/ui";
import { ask, showError } from "@/workbench/messages";
import { editorService, notifications, provideEditorService, type OpenOptions } from "@/workbench/contributions";
import { OverlayHost } from "@/workbench/OverlayHost";
import { TitleBar } from "@/workbench/TitleBar";
import { WindowResizeHandles } from "@/workbench/WindowResizeHandles";
import { useApplyTheme, windowBackgroundHex } from "@/workbench/theme";
import { DIFF_KIND, diffInput, diffTitle, openDiff, type DiffData, type DiffSide } from "./diffInput";
import { saveStagedDocuments } from "./stagedDocument";
import { refreshNow, useVcs } from "./store";
import styles from "./common.module.css";
const DiffEditor = lazyComponent(() => import("./DiffEditor").then((m) => m.DiffEditor));
/** Opens `path` in the project window's editor (DiffEditor's "Jump to Source"). */
const OPEN_SOURCE = "openidea://diff/open-source";
/** Opens a diff in an editor tab of the project window (IDEA's "Show Diff in Editor Tab"). */
const OPEN_DIFF = "openidea://diff/open-diff";
const LAUNCH_EVENT = "openidea://launch";
const useDiff = create<{
data: DiffData | null;
project: string;
title: string;
error: string | null;
closing: boolean;
}>(() => ({ data: null, project: "", title: "", error: null, closing: false }));
/** The launch's diff as the diff viewer's input data. */
function toDiffData(launch: DiffLaunch): DiffData {
return {
path: launch.path,
left: launch.left as DiffSide,
middle: (launch.middle as DiffSide | null) ?? undefined,
right: launch.right as DiffSide,
line: launch.line ?? undefined,
lineSide: launch.lineSide ?? undefined,
col: launch.col ?? undefined,
chain: launch.chain?.map(toDiffData),
};
}
/** The project, file and revisions shown in the native caption. */
function diffCaption(data: DiffData): string {
const project = useDiff.getState().project;
const file = diffTitle(data);
return tx`${project} - Diff: ${file}`;
}
function showCaption(caption: string) {
if (useDiff.getState().title === caption) return;
useDiff.setState({ title: caption });
void getCurrentWindow()
.setTitle(caption)
.catch(() => {});
}
/** Hands `path` to the project window's editor, which owns the project's documents and tabs. */
export function openSource(parent: string, path: string, options?: OpenOptions) {
return emitTo(parent, OPEN_SOURCE, { path, options });
}
/** Loads the diff of this window's launch and hands its editor commands to the project window. */
export function activateDiffWindow(parent: string): () => void {
const native = getCurrentWindow();
const documents = activateEmbeddedDocuments();
let disposed = false;
let closing = false;
let closed = false;
let pending = Promise.resolve();
let stopClose: (() => void) | undefined;
let stopSave: (() => void) | undefined;
let stopLaunch: (() => void) | undefined;
// A close prompt pauses file switches until the window stays open or closes.
const enqueue = (run: () => Promise<void>) => {
const next = pending.then(async () => {
if (!disposed && !closed) await run();
});
pending = next.catch(() => {});
return next;
};
const save = async () => {
await saveStagedDocuments();
await documents.save();
};
const showDiff = async (data: DiffData) => {
try {
await saveStagedDocuments();
} catch {
return; // The staged pane shows the conflict and retains the draft.
}
if (disposed) return;
useDiff.setState({ data, error: null });
showCaption(diffCaption(data));
};
provideEditorService({
openFile: (path, options) => openSource(parent, path, options),
openInput: (input, options) => {
// F7 along a diff chain shows the neighbour here; anything else goes to the project window.
const data = input.kind === DIFF_KIND ? (input.data as DiffData) : null;
if (data) return enqueue(() => showDiff(data));
return input.path ? openSource(parent, input.path, options) : Promise.resolve();
},
activePath: () => null,
activeCursor: () => null,
saveAll: save,
});
const unregisterSave = registerAction({
id: "file.save",
title: "Save All",
category: "File",
run: async () => {
try {
await save();
} catch (error) {
showError(tx("Could not save diff"), error instanceof Error ? error.message : String(error));
}
},
});
// IDEA's Show Diff in Editor Tab: the diff moves to the project window, edits saved first.
const unregisterToEditor = registerAction({
id: "vcs.showDiffInEditorTab",
title: "Show Diff in Editor Tab",
category: "Git",
icon: "editor-only",
run: async () => {
const data = useDiff.getState().data;
if (!data) return;
try {
await save();
await emitTo(parent, OPEN_DIFF, data);
await native.close();
} catch (error) {
showError(tx("Cannot show diff in an editor tab"), error instanceof Error ? error.message : String(error));
}
},
});
const savingReady = installDiffWindowSave(parent, save).then((off) => {
if (disposed) off();
else stopSave = off;
});
void native
.onCloseRequested(async (event) => {
if (closing) {
event.preventDefault();
return;
}
closing = true;
// 保存和释放文档期间禁止继续输入;取消关闭后恢复编辑。
flushSync(() => useDiff.setState({ closing: true }));
await enqueue(async () => {
try {
if (documents.dirty() && useProject.getState().settings?.files?.autoSave === false) {
const answer = await ask({
title: tx("Save local changes?"),
body: tx("Save the files edited in this diff before closing."),
buttons: [{ id: "save", label: tx("Save and Close"), primary: true }],
});
if (answer.button !== "save") {
event.preventDefault();
return;
}
}
await save();
await documents.dispose();
closed = true;
} catch (error) {
event.preventDefault();
notifications().notify({
level: "error",
title: tx("Could not close diff"),
body: error instanceof Error ? error.message : String(error),
});
} finally {
if (!closed) useDiff.setState({ closing: false });
const result: AuxCloseResult = { label: native.label, closed, documents: [] };
await emitTo(parent, AUX_CLOSED, result).catch((error) =>
console.warn("cannot report diff window close", error),
);
closing = false;
}
});
})
.then((off) => {
if (disposed) off();
else stopClose = off;
});
const onKey = (event: KeyboardEvent) => {
if (event.defaultPrevented || isImeKey(event) || isPopupOpen()) return;
if (event.key === "Escape") {
event.preventDefault();
void native.close();
}
};
const onCloseShortcut = (event: KeyboardEvent) => {
if (isImeKey(event) || isPopupOpen()) return;
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "w") {
event.preventDefault();
event.stopImmediatePropagation();
void native.close();
}
};
window.addEventListener("keydown", onKey);
window.addEventListener("keydown", onCloseShortcut, true);
const readLaunch = () => {
void enqueue(async () => {
const launch = (await commands.windowTakeLaunch())?.diffWindow;
if (launch) await showDiff(toDiffData(launch));
else if (!useDiff.getState().data) throw new Error(tx("Missing diff request"));
}).catch((error) => {
if (disposed) return;
if (useDiff.getState().data) showError(tx("Cannot show diff in a new window"), String(error));
else useDiff.setState({ error: String(error) });
});
};
void (async () => {
await savingReady;
await restoreRemote();
const project = await commands.projectCurrent();
if (!project) throw new Error(tx("The diff’s project is no longer open"));
// Settings only: restoring the project's editor session here would overwrite the main window's tabs.
useProject.setState({ settings: project.settings });
const roots = await call(commands.vcsRoots());
useVcs.setState({
available: roots.length > 0,
root: project.root,
roots: roots.map((root) => root.root),
});
setContext("projectOpen", true);
setContext("vcsAvailable", roots.length > 0);
await refreshNow();
if (disposed) return;
useDiff.setState({ project: project.name });
const off = await native.listen(LAUNCH_EVENT, readLaunch);
if (disposed) {
off();
return;
}
stopLaunch = off;
readLaunch();
})().catch((error) => useDiff.setState({ error: String(error) }));
return () => {
disposed = true;
stopClose?.();
stopSave?.();
stopLaunch?.();
unregisterSave();
unregisterToEditor();
window.removeEventListener("keydown", onKey);
window.removeEventListener("keydown", onCloseShortcut, true);
};
}
/** Jump to Source from a diff window opens the file in its project window's editor. */
export function installDiffEditorHost(): () => void {
if (!isTauri()) return () => {};
let disposed = false;
const stops: Array<() => void> = [];
const keep = (off: () => void) => {
if (disposed) off();
else stops.push(off);
};
const native = getCurrentWindow();
void native
.listen<{ path: string; options?: OpenOptions }>(OPEN_SOURCE, ({ payload }) => {
const folder = projectFolder(useProject.getState().project, payload.path);
if (folder && payload.path.startsWith(`${folder.root}/`)) {
void editorService()
.openFile(payload.path, payload.options)
.then(() => native.setFocus());
}
})
.then(keep);
void native
.listen<DiffData>(OPEN_DIFF, ({ payload }) => {
if (!projectFolder(useProject.getState().project, payload.path)) return;
void openDiff(payload).then(() => native.setFocus());
})
.then(keep);
return () => {
disposed = true;
for (const stop of stops) stop();
};
}
/** Opens one diff in a window of this project window (falls back to an editor tab outside Tauri). */
export function showDiffWindow(data: DiffData, fallback: () => void) {
if (!isTauri()) {
fallback();
return;
}
const launch = toDiffLaunch(data);
void call(commands.windowOpenDiff(launch, windowBackgroundHex())).catch((error) =>
showError(tx("Cannot show diff in a new window"), error instanceof Error ? error.message : String(error)),
);
}
function toDiffLaunch(data: DiffData): DiffLaunch {
return {
path: data.path,
left: data.left,
middle: data.middle,
right: data.right,
line: data.line,
lineSide: data.lineSide,
col: data.col,
chain: data.chain?.map(toDiffLaunch),
};
}
export function DiffWindow() {
useApplyTheme();
const { data, title, error, closing } = useDiff();
// macOS overlays traffic lights on the bar; Windows and Linux are frameless, like Settings.
const os = usePlatform((s) => s.os);
const ownTitleBar = usePlatform((s) => s.overlayTitleBar || s.framelessTitleBar);
return (
<main className={clsx(styles.comparisonWindow, os === "linux" && styles.comparisonWindowEdge)}>
{ownTitleBar && <TitleBar minimal dialog title={title} />}
{error ? (
<div className={styles.error} role="alert">
{error}
</div>
) : !data ? (
<div className={styles.comparisonWindowLoading} role="status">
<Spinner />
<T>Loading…</T>
</div>
) : (
<div className={styles.comparisonWindowBody} inert={closing}>
<DiffEditor key={diffInput(data).key} input={diffInput(data)} />
</div>
)}
<OverlayHost />
<WindowResizeHandles />
</main>
);
}