Файли
openidea/src/features/code-insight/UsagesPopup.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

242 рядки
8.7 KiB
TypeScript

/**
* ⌥⌘F7 Show Usages: popup list at the caret with speed search (typing
* filters), an optional code preview and "Open in Find Window", which moves
* the found usages to the Find Usages tool window.
*/
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { create } from "zustand";
import clsx from "clsx";
import { EditorState, StateEffect, StateField } from "@codemirror/state";
import { Decoration, EditorView } from "@codemirror/view";
import { codePreviewExtensions } from "@/editor/api";
import { basename } from "@/platform/project";
import { shortcutLabel } from "@/platform/keymap";
import { Icon, IconButton, List, Popup, fileIconName, listNavigate } from "@/ui";
import { openLocation, readFileLines } from "./ipc";
import { showUsageResults, usageCount, useUsagesPopup, type Usage, type UsageGroup } from "./usages";
import { UsagePreview } from "./UsagesView";
import styles from "./UsagesPopup.module.css";
const close = () => useUsagesPopup.setState({ open: false });
const PREVIEW_KEY = "openidea.usages.popupPreview.v1";
function loadPreviewOption(): boolean {
try {
return localStorage.getItem(PREVIEW_KEY) === "true";
} catch {
return false;
}
}
/** The preview pane toggle (remembered). */
export const useUsagesPopupPreview = create<{ preview: boolean }>(() => ({ preview: loadPreviewOption() }));
export function setUsagesPopupPreview(preview: boolean) {
useUsagesPopupPreview.setState({ preview });
try {
localStorage.setItem(PREVIEW_KEY, String(preview));
} catch {
// storage unavailable: the toggle lasts for the session
}
}
/** Usages whose file name or line text contains the typed text (case-insensitive). */
export function filterUsages(items: readonly Usage[], filter: string): Usage[] {
const q = filter.trim().toLowerCase();
if (!q) return items as Usage[];
return items.filter((u) => u.text.toLowerCase().includes(q) || basename(u.path).toLowerCase().includes(q));
}
/** The popup's groups as locations for the Find Usages tool window. */
export function usageLocations(groups: readonly UsageGroup[]) {
return groups.flatMap((g) =>
g.usages.map((u) => ({
path: u.path,
range: { start: { line: u.line, col: u.col }, end: { line: u.line, col: u.endCol } },
})),
);
}
export function UsagesPopup() {
const open = useUsagesPopup((s) => s.open);
return open ? <UsagesPopupInner /> : null;
}
const ROW = 24;
function UsagesPopupInner() {
const { anchor, symbol, groups, note } = useUsagesPopup();
const preview = useUsagesPopupPreview((s) => s.preview);
const all = useMemo<Usage[]>(() => groups.flatMap((g) => g.usages), [groups]);
const [filter, setFilter] = useState("");
const items = useMemo(() => filterUsages(all, filter), [all, filter]);
const [active, setActive] = useState(0);
const current = Math.min(active, items.length - 1);
const total = usageCount(groups);
const pick = (u: Usage | undefined) => {
if (!u) return;
close();
void openLocation(u.path, u.line, u.col);
};
const openInFindWindow = () => {
close();
void showUsageResults({ symbol, locations: usageLocations(groups) });
};
const onKeyDown = (e: KeyboardEvent) => {
const next = listNavigate(e.key, { items, active: current, wrap: true, pageSize: 10 });
if (next !== null) {
e.preventDefault();
setActive(next);
return;
}
const plain = !e.metaKey && !e.ctrlKey && !e.altKey;
if (e.key === "Enter") {
e.preventDefault();
pick(items[current]);
} else if (e.key === "Escape" && filter) {
// The first Esc clears the speed search, the next one closes.
e.preventDefault();
e.stopPropagation();
setFilter("");
setActive(0);
} else if (e.key === "Backspace" && filter) {
e.preventDefault();
setFilter((f) => f.slice(0, -1));
setActive(0);
} else if (plain && e.key.length === 1 && (filter || e.key !== " ")) {
e.preventDefault();
setFilter((f) => f + e.key);
setActive(0);
}
};
const keys = shortcutLabel("find.usages");
return (
<Popup open anchor={anchor} onClose={close} aria-label="Usages" className={styles.popup}>
<div className={styles.focus} tabIndex={0} data-autofocus onKeyDown={onKeyDown}>
<div className={styles.header}>
<span className={styles.title}>
Usages{symbol ? ` of ${symbol}` : ""}{" "}
<span className={styles.count}>{filter ? `${items.length} of ${total}` : total} found</span>
</span>
{filter && (
<span className={clsx(styles.filter, !items.length && styles.noMatch)} role="status">
{filter}
</span>
)}
<IconButton
icon="list"
size="small"
title="Show Preview"
pressed={preview}
onMouseDown={(e) => e.preventDefault()}
onClick={() => setUsagesPopupPreview(!preview)}
/>
<button type="button" className={styles.link} onClick={openInFindWindow}>
Open in Find Window{keys ? ` ${keys}` : ""}
</button>
</div>
{note && <div className={styles.note}>{note}</div>}
<div className={styles.body} style={{ height: Math.max(1, Math.min(14, items.length)) * ROW }}>
<List
items={items}
getKey={(u) => `${u.path}:${u.line}:${u.col}`}
activeIndex={current}
onActiveChange={setActive}
focusable={false}
hoverSelects
rowHeight={ROW}
aria-label="Usages"
onActivate={pick}
empty={<div className={styles.empty}>Nothing matches '{filter}'</div>}
renderItem={(u) => (
<div className={styles.row}>
<Icon name={fileIconName(basename(u.path))} size={14} className={styles.icon} />
<UsagePreview usage={u} />
<span className={styles.spacer} />
<span className={styles.where}>
{basename(u.path)}:{u.line + 1}
</span>
</div>
)}
/>
</div>
{preview && <UsageCodePreview usage={items[current] ?? null} />}
</div>
</Popup>
);
}
const setMark = StateEffect.define<{ from: number; to: number } | null>();
const usageMark = Decoration.mark({ class: styles.previewMatch });
const usageLine = Decoration.line({ class: styles.previewLine });
const marks = StateField.define({
create: () => Decoration.none,
update(value, tr) {
for (const e of tr.effects) {
if (!e.is(setMark)) continue;
if (!e.value) return Decoration.none;
const line = tr.state.doc.lineAt(e.value.from);
const ranges = [usageLine.range(line.from)];
if (e.value.to > e.value.from) ranges.push(usageMark.range(e.value.from, e.value.to));
return Decoration.set(ranges);
}
return value.map(tr.changes);
},
provide: (f) => EditorView.decorations.from(f),
});
/** Read-only view of the usage's file around its line, the usage marked. */
function UsageCodePreview({ usage }: { usage: Usage | null }) {
const host = useRef<HTMLDivElement>(null);
const view = useRef<EditorView | null>(null);
const [loaded, setLoaded] = useState<string | null>(null);
useEffect(() => {
if (!host.current) return;
const v = new EditorView({ parent: host.current, state: EditorState.create({ extensions: marks }) });
view.current = v;
return () => {
v.destroy();
view.current = null;
};
}, []);
const path = usage?.path ?? null;
useEffect(() => {
if (!path) return;
let alive = true;
// Debounced so arrowing through the list doesn't load every file.
const t = setTimeout(() => {
void Promise.all([readFileLines(path), codePreviewExtensions(path)]).then(([lines, extensions]) => {
if (!alive || !view.current) return;
view.current.setState(EditorState.create({ doc: (lines ?? []).join("\n"), extensions: [extensions, marks] }));
setLoaded(path);
});
}, 60);
return () => {
alive = false;
clearTimeout(t);
};
}, [path]);
useEffect(() => {
const v = view.current;
if (!v || !usage || loaded !== usage.path) return;
const doc = v.state.doc;
if (usage.line >= doc.lines) return;
const line = doc.line(usage.line + 1);
const from = line.from + Math.min(usage.col, line.length);
const to = line.from + Math.min(usage.endCol, line.length);
v.dispatch({ effects: [setMark.of({ from, to }), EditorView.scrollIntoView(from, { y: "center" })] });
}, [usage, loaded]);
return (
<div className={styles.preview} role="region" aria-label="Preview">
<div ref={host} className={clsx(styles.previewEditor, loaded !== path && styles.previewHidden)} />
</div>
);
}