Файли
openidea/src/features/vcs/MergeEditor.tsx
T
l0ng-ai 82b6980a59 feat: Second pass aligning interactions with IntelliJ IDEA (#23)
* feat: Second pass aligning interactions with IntelliJ IDEA

Result tool windows
- Next/Previous Occurrence (⌥⌘↓/↑) across Find, Usages, Problems, TODO,
  Inspection and Hierarchy, with an "N of M" status hint
- Find: reuse the unpinned tab, Pin Tab, source preview, group by file or
  directory, exclude moves to the next result, Rerun
- Usages: tabs with pinning, exclude and preview
- Problems, TODO, Inspection: no autoscroll by default, severity-first sorting,
  context menu with quick fixes and copy description
- Trees: F4/⌘↓ jump to source; speed search Home/End and arrow handling

Find in Files, bookmarks, navigation
- Replace mode: Enter replaces the selection, ⇧⌥Enter replaces all, multi-select
- Pin Window toggle, highlighted read-only preview, search/replace history (⌥↓),
  Alt mnemonics, search context filter (comments / string literals)
- Mnemonic bookmarks (⌥F3, ⌃⇧digit, ⌃digit), ⌘F3 bookmarks popup, descriptions,
  ⌘-click gutter toggles a bookmark
- Select In popup (⌥F1); Recent Locations double-click and Delete;
  Search Everywhere remembers the query per tab

Code insight and refactoring
- Extract/Introduce continue with in-place rename and name suggestions;
  expression and occurrence choosers with live highlighting
- Safe Delete confirms first; numbered Refactor This
- Quick Documentation history, in-popup links and a Documentation tool window;
  Quick Definition switches between targets and shows the whole declaration
- Goto chooser lists symbol names and can pin to the Find window
- Parameter Info Tab/⇧Tab, intention preview, Reformat dialog and summary,
  inlay hint ⌘-click and context menu
- Live templates: Enter moves to the next field, two-step Esc, ⌘J as a lookup,
  language surrounders with mnemonics
- File Structure popup as a filterable tree; Show Usages filter and preview;
  call hierarchy jumps to call sites

Editor
- Paste re-indents each line by default; Move Statement moves whole statements
  in and out of blocks and re-indents
- Type over closing quotes of existing strings; ⌘D/⌘⌫ cover folded regions;
  ⌥⌫ deletes the preceding word
- ⌃G / ⌃⌘G whole-word rules and wrap hint; double-modifier caret cloning
- Visual-column block selection, nested Collapse All, recursive folding,
  fold selection toggle, Go to Matching Brace, gutter drag selects lines,
  sticky line and error stripe clicks, Insert toggles overwrite mode

Run, VCS, workbench
- Gutter icons show the last test result; Modify Run Configuration; test tree
  hides passed tests, context menu and assertion diff
- Stack frames resolve by fully qualified class name; context run chooser
- Inline Smart Step Into
- Git Log multi-select filters, "me" and date range; favourite branches,
  Fetch and tags in the branch popup; stash Keep index and Unstash options
- Terminal tab titles follow the shell; Distraction Free persists; gear menu;
  sticky balloons move to the notifications tool window after a while

* fix(vcs): Label restored local changes as yours after Smart Checkout; name the branch checked out

Conflicts from restoring stashed changes show the user's uncommitted
changes on the left like other operations, and the checkout notification
names the new branch instead of the previous one.

* fix: Close the merge editor on Apply; confirm before terminating a running Run tab

Like IDEA, applying a merge result closes its tab, and closing a Run tab
whose process still runs asks before terminating it (with a Settings
toggle and "Do not ask again").

* fix(terminal): Don't start a new session in the background after closing the last tab

The hidden Terminal window stays mounted, so it reopened a session as soon
as the last tab closed. It now opens the Local tab only once the window is
shown again, as IDEA does.

* fix(vcs): Start the merge result from a three-way merge; close the editor on Apply

The result pane now begins with non-conflicting changes merged and each
conflict showing the base text, resolved from the side panes, instead of
raw conflict markers. Apply now reports success, so the tab closes.

fix(search): Match File Structure filter on word starts

* fix: Limit Smart Step Into to the paused line; drop usages hints on callbacks; show full intention titles

Adapters that list every remaining call in the function (debugpy) made Smart
Step Into fall back to a chooser that offered calls from later lines. Targets
are now narrowed to the calls on the paused line, so they are picked in place.

Anonymous functions and callbacks no longer get a 'no usages' hint, and
intention titles are no longer cut short when there is room for them.

* fix: Undo / Redo from the Edit menu and Find Action use the editor's history

They ran the webview's native undo, which misses programmatic edits such as
templates, completion and refactorings, so nothing happened in the editor.
2026-10-25 09:44:46 +08:00

341 рядки
12 KiB
TypeScript

/** Three-pane merge conflict editor: Yours | Result | Theirs. */
import { useCallback, useEffect, useRef, useState } from "react";
import clsx from "clsx";
import { RangeSetBuilder, StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view";
import { history, historyKeymap } from "@codemirror/commands";
import { keymap } from "@codemirror/view";
import { unifiedMergeView } from "@codemirror/merge";
import type { MergeSides } from "@/bindings";
import { useTxTemplate } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { Button, IconButton, Spinner, T } from "@/ui";
import { editorService, type EditorInput } from "@/workbench/contributions";
import { languageFor, viewerBase } from "./cm";
import { confirmDialog } from "./dialogs";
import { initialResult, mergeTitles, resolutionText, type Resolution, type ResultConflict } from "./conflicts";
import { baseName } from "./model";
import { errorMessage, readWorkingText, runOp, writeFileText } from "./ops";
import { refreshNow } from "./store";
import styles from "./MergeEditor.module.css";
import type { MergeData } from "./mergeKind";
export { MERGE_KIND, mergeInput, type MergeData } from "./mergeKind";
/** Drops the conflict at an index once a resolution replaced its text. */
const resolvedConflict = StateEffect.define<number>();
function resolveConflict(view: EditorView, index: number, how: Resolution) {
const c = view.state.field(conflictField).conflicts[index];
if (!c) return;
view.dispatch({
changes: { from: c.from, to: c.to, insert: resolutionText(c, how) },
effects: resolvedConflict.of(index),
userEvent: "input.resolve",
});
}
class ActionsWidget extends WidgetType {
constructor(
readonly index: number,
readonly hasBase: boolean,
) {
super();
}
eq(o: ActionsWidget) {
return o.index === this.index && o.hasBase === this.hasBase;
}
toDOM(view: EditorView) {
const el = document.createElement("div");
el.className = "cm-conflict-actions";
const add = (label: string, how: Resolution) => {
const b = document.createElement("button");
b.type = "button";
b.textContent = label;
// Keep the caret / focus in the editor; resolve on click (mouse or keyboard).
b.onmousedown = (e) => e.preventDefault();
b.onclick = (e) => {
e.preventDefault();
resolveConflict(view, this.index, how);
};
el.appendChild(b);
};
const title = document.createElement("span");
title.textContent = `Conflict ${this.index + 1}`;
el.appendChild(title);
add("Accept Yours", "ours");
add("Accept Theirs", "theirs");
add("Accept Both", "both");
if (this.hasBase) add("Use Base", "base");
return el;
}
ignoreEvent() {
return true;
}
}
const conflictLine = Decoration.line({ class: "cm-conflict-marker" });
function decorate(state: EditorState, conflicts: readonly ResultConflict[]): DecorationSet {
const b = new RangeSetBuilder<Decoration>();
const doc = state.doc;
conflicts.forEach((c, i) => {
b.add(c.from, c.from, Decoration.widget({ widget: new ActionsWidget(i, c.base !== null), block: true, side: -1 }));
if (c.to <= c.from) return;
const endLine = doc.lineAt(c.to - 1).number;
for (let n = doc.lineAt(c.from).number; n <= endLine; n++) b.add(doc.line(n).from, doc.line(n).from, conflictLine);
});
return b.finish();
}
/**
* The result's unresolved conflicts, tracked as ranges holding the base text (no
* markers), as IDEA's merge dialog shows them. Typing at a conflict's edges stays in it.
*/
const conflictField = StateField.define<{ conflicts: ResultConflict[]; deco: DecorationSet }>({
create: () => ({ conflicts: [], deco: Decoration.none }),
update(v, tr) {
const done = new Set(tr.effects.filter((e) => e.is(resolvedConflict)).map((e) => e.value as number));
let conflicts = v.conflicts.filter((_, i) => !done.has(i));
if (tr.docChanged)
conflicts = conflicts.map((c) => ({ ...c, from: tr.changes.mapPos(c.from, -1), to: tr.changes.mapPos(c.to, 1) }));
if (!tr.docChanged && !done.size) return v;
return { conflicts, deco: decorate(tr.state, conflicts) };
},
provide: (f) => EditorView.decorations.from(f, (v) => v.deco),
});
const resultTheme = EditorView.baseTheme({
".cm-conflict-marker": {
backgroundColor: "color-mix(in srgb, var(--vcs-conflict) 14%, transparent)",
color: "var(--fg-subtle)",
},
".cm-conflict-actions": {
display: "flex",
alignItems: "center",
gap: "6px",
padding: "3px 8px",
fontFamily: "var(--font-ui)",
fontSize: "var(--fs-small)",
color: "var(--vcs-conflict)",
background: "var(--bg-elev)",
borderTop: "1px solid var(--border)",
},
".cm-conflict-actions button": {
padding: "0 6px",
border: "1px solid var(--border-strong)",
borderRadius: "var(--radius-small)",
color: "var(--fg-secondary)",
background: "var(--bg-control)",
font: "inherit",
lineHeight: "18px",
},
".cm-conflict-actions button:hover": { color: "var(--fg-strong)", background: "var(--bg-control-hover)" },
});
export function MergeEditor({ input }: { input: EditorInput }) {
const { path } = input.data as MergeData;
const [state, setState] = useState<{
ours: string;
theirs: string;
base: string | null;
working: string;
merged: string | null;
sides: MergeSides;
} | null>(null);
const [error, setError] = useState<string | null>(null);
const [lang, setLang] = useState<Extension | null>(null);
const [left, setLeft] = useState(0);
const [resolved, setResolved] = useState(false);
const oursRef = useRef<HTMLDivElement>(null);
const resultRef = useRef<HTMLDivElement>(null);
const theirsRef = useRef<HTMLDivElement>(null);
const resultView = useRef<EditorView | null>(null);
const txt = useTxTemplate();
const titles = mergeTitles(state?.sides);
const load = useCallback(async () => {
try {
const [v, working] = await Promise.all([call(commands.vcsConflictVersions(path)), readWorkingText(path)]);
setState({
ours: v.ours ?? "",
theirs: v.theirs ?? "",
base: v.base,
working: working ?? "",
merged: v.merged,
sides: v.sides,
});
setError(null);
} catch (e) {
setError(errorMessage(e));
}
}, [path]);
useEffect(() => {
void Promise.resolve().then(load);
}, [load]);
useEffect(() => {
let alive = true;
void languageFor(path).then((l) => alive && setLang(() => l ?? []));
return () => {
alive = false;
};
}, [path]);
useEffect(() => {
if (!state || lang === null || !oursRef.current || !resultRef.current || !theirsRef.current) return;
const side = () => [
viewerBase({ readOnly: true }),
lang,
state.base !== null ? unifiedMergeView({ original: state.base, mergeControls: false, gutter: true }) : [],
];
const ours = new EditorView({ doc: state.ours, parent: oursRef.current, extensions: side() });
const theirs = new EditorView({ doc: state.theirs, parent: theirsRef.current, extensions: side() });
// Like IDEA, start from the three-way merge (non-conflicting changes applied, conflicts
// showing the base) rather than the marker-laden working copy.
const start =
state.merged !== null ? initialResult(state.merged) : initialResult(state.working, state.sides.reversed);
const result = new EditorView({
doc: start.text,
parent: resultRef.current,
extensions: [
viewerBase({ readOnly: false }),
history(),
keymap.of(historyKeymap),
lang,
conflictField.init((s) => ({ conflicts: start.conflicts, deco: decorate(s, start.conflicts) })),
resultTheme,
EditorView.updateListener.of((u) => {
if (u.docChanged) setLeft(u.state.field(conflictField).conflicts.length);
}),
],
});
resultView.current = result;
setLeft(result.state.field(conflictField).conflicts.length);
return () => {
ours.destroy();
theirs.destroy();
result.destroy();
resultView.current = null;
};
}, [state, lang]);
const goto = (dir: 1 | -1) => {
const v = resultView.current;
if (!v) return;
const blocks = v.state.field(conflictField).conflicts;
if (!blocks.length) return;
const head = v.state.selection.main.head;
const target =
dir === 1
? (blocks.find((b) => b.from > head) ?? blocks[0]!)
: ([...blocks].reverse().find((b) => b.to < head) ?? blocks[blocks.length - 1]!);
v.dispatch({
selection: { anchor: target.from },
effects: EditorView.scrollIntoView(target.from, { y: "center" }),
});
v.focus();
};
const acceptAll = (how: Resolution) => {
const v = resultView.current;
if (!v) return;
const conflicts = v.state.field(conflictField).conflicts;
v.dispatch({
changes: conflicts.map((c) => ({ from: c.from, to: c.to, insert: resolutionText(c, how) })),
effects: conflicts.map((_, i) => resolvedConflict.of(i)),
userEvent: "input.resolve",
});
};
const apply = async () => {
const v = resultView.current;
if (!v) return;
const remaining = v.state.field(conflictField).conflicts.length;
if (
remaining > 0 &&
!(await confirmDialog({
title: "Unresolved Conflicts",
message: `${remaining} conflict${remaining === 1 ? " is" : "s are"} unresolved and keep the base text. Save and mark the file as resolved anyway?`,
okLabel: "Mark Resolved",
}))
)
return;
const text = v.state.doc.toString();
const ok = await runOp(
`Resolve ${baseName(path)}`,
async () => {
await writeFileText(path, text, { save: true });
await call(commands.vcsStage([path]));
return true;
},
{ success: `${baseName(path)}: conflicts resolved` },
);
if (ok) {
setResolved(true);
await refreshNow();
// Like IDEA, applying the result closes the merge editor.
editorService().closeInput?.(input.key);
}
};
if (error)
return (
<div className={styles.message}>
{error}
<Button onClick={() => void load()}>
<T>Retry</T>
</Button>
</div>
);
if (resolved)
return (
<div className={styles.message}>
{baseName(path)} has been resolved and staged.
<Button onClick={() => void editorService().openFile(path, { focus: true })}>
<T>Open File</T>
</Button>
</div>
);
return (
<div className={styles.root}>
<div className={styles.toolbar} role="toolbar" aria-label="Merge">
<IconButton icon="arrow-up" title="Previous Conflict" size="small" onClick={() => goto(-1)} />
<IconButton icon="arrow-down" title="Next Conflict" size="small" onClick={() => goto(1)} />
<span className={styles.sep} />
<Button size="small" onClick={() => acceptAll("ours")}>
<T>Accept All Yours</T>
</Button>
<Button size="small" onClick={() => acceptAll("theirs")}>
<T>Accept All Theirs</T>
</Button>
<IconButton icon="refresh" title="Reload from Disk" size="small" onClick={() => void load()} />
<span className={clsx(styles.status, !left && styles.statusDone)}>
{left ? `${left} conflict${left === 1 ? "" : "s"} left` : "All conflicts resolved"}
</span>
<Button size="small" variant="primary" onClick={() => void apply()}>
<T>Apply</T>
</Button>
</div>
<div className={styles.labels}>
<span>{txt(titles.yours)}</span>
<span>
<T>Result</T>
</span>
<span>{txt(titles.theirs)}</span>
</div>
{!state || lang === null ? (
<div className={styles.message}>
<Spinner size={14} />
</div>
) : null}
<div className={styles.panes} hidden={!state || lang === null}>
<div ref={oursRef} className={styles.pane} aria-label="Your version" role="region" />
<div ref={resultRef} className={styles.pane} aria-label="Result" role="region" />
<div ref={theirsRef} className={styles.pane} aria-label="Their version" role="region" />
</div>
</div>
);
}