Файли
openidea/src/features/code-insight/UsagesView.tsx
T
Mansur Akhmadiтаmansur-akhmadi 4a3eacff62 feat(code-insight): Export to Text File in the Find Usages tool window (#6292)
Adds Export to Text File… to the Find Usages toolbar and Find Action. It writes the active search as shown (access filter applied, excluded usages left out) as an indented text report to a file picked in the save dialog, and reports write errors as a notification.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:06:50 +08:00

576 рядки
21 KiB
TypeScript

/**
* "usages" tool window: Find Usages results grouped by file with line
* previews, one tab per search (pinnable, as the Find tool window's tabs).
*/
import { openCodeLocation } from "@/editor/api";
import { useCallback, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import clsx from "clsx";
import { create } from "zustand";
import { previewColors, tokenSpans, useLineTokens } from "@/editor/lineTokens";
import { save } from "@/platform/dialog";
import { writeDesktopText } from "@/platform/desktopFiles";
import { formatMessage, tx, useTx } from "@/platform/i18n";
import { useEditorPrefs } from "@/platform/editorSettings";
import { BUNDLED_MONO_FAMILY, monoFontFamily } from "@/platform/fonts";
import { shortcutLabel } from "@/platform/keymap";
import { basename, relativeDir, useProject } from "@/platform/project";
import { notifications, useOccurrenceNavigator } from "@/workbench/contributions";
import {
EmptyState,
Icon,
IconButton,
SourcePreview,
SplitGroup,
SplitHandle,
SplitPanel,
Spinner,
Tabs,
Tree,
fileIconName,
showContextMenu,
type MenuItem,
type TreeHandle,
type TreeRowState,
T,
} from "@/ui";
import { previewText } from "./ipc";
import {
activeUsageSearch,
closeUsageTab,
pinUsageTab,
trimPreview,
usageCount,
useUsages,
type Usage,
type UsageGroup,
type UsageSearch,
} from "./usages";
import styles from "./UsagesView.module.css";
import {
UsageAccessFilter,
filterUsageAccess,
supportsUsageAccess,
useUsageAccessOptions,
type UsageAccessOptions,
} from "./UsageAccessFilter";
type Node =
| { kind: "summary"; key: string }
| { kind: "file"; key: string; group: UsageGroup }
| { kind: "usage"; key: string; usage: Usage };
export function UsagePreview({ usage }: { usage: Usage }) {
const { text, textCol, from, to } = trimPreview(usage);
const tokens = useLineTokens({ path: usage.path, line: usage.line, col: textCol }, text);
return (
<span className={styles.preview}>
{tokenSpans(text, 0, from, tokens, "b:")}
<mark className={styles.match}>{text.slice(from, to)}</mark>
{tokenSpans(text, to, text.length, tokens, "a:")}
</span>
);
}
function usageTabLabel(t: UsageSearch, tx: (text: string) => string): string {
if (!t.symbol) return tx("Usages");
const text =
t.scope === "project"
? tx("Usages of '{symbol}' in Project Files")
: t.scope === "libraries"
? tx("Usages of '{symbol}' in Project and Libraries")
: tx("Usages of '{symbol}'");
return formatMessage(text, { symbol: t.symbol });
}
/** Tool window header: one content tab per search (`Usages of 'foo'`). */
export function UsagesTabs() {
const tx = useTx();
const tabs = useUsages((s) => s.tabs);
const search = useUsages(activeUsageSearch);
if (!search) return null;
const label = (t: (typeof tabs)[number]) => usageTabLabel(t, tx);
return (
<Tabs
variant="compact"
className={styles.tabs}
aria-label="Usage searches"
items={tabs.map((t) => ({
id: String(t.id),
label: label(t),
verbatim: true,
closable: true,
pinned: t.pinned,
}))}
activeId={String(search.id)}
onSelect={(id) => useUsages.setState({ active: Number(id) })}
onClose={(id) => closeUsageTab(Number(id))}
onTogglePin={(id) => {
const t = tabs.find((x) => x.id === Number(id));
if (t) pinUsageTab(t.id, !t.pinned);
}}
onContextMenu={(id, e) => {
const t = tabs.find((x) => x.id === Number(id));
if (!t) return;
// IDEA's content tab menu.
showContextMenu(e, [
{ id: "close", label: "Close Tab", run: () => closeUsageTab(t.id) },
{ id: "closeAll", label: "Close All Tabs", run: () => tabs.forEach((o) => closeUsageTab(o.id)) },
{
id: "closeOthers",
label: "Close Other Tabs",
disabled: tabs.length < 2,
run: () => tabs.forEach((o) => o.id !== t.id && closeUsageTab(o.id)),
},
{ kind: "separator" },
{ id: "pin", label: t.pinned ? "Unpin Tab" : "Pin Tab", run: () => pinUsageTab(t.id, !t.pinned) },
]);
}}
/>
);
}
const SUMMARY_KEY = "\u0000summary";
const usageKey = (u: Usage) =>
`${u.path}:${u.line}:${u.col}:${u.sourceLocation?.range.end.line ?? u.line}:${u.sourceLocation?.range.end.col ?? u.endCol}`;
/** Excluded (⌫) usages per search. */
const useExcluded = create<{ byTab: Record<number, ReadonlySet<string>> }>(() => ({ byTab: {} }));
const NONE: ReadonlySet<string> = new Set();
/** Usages under a node (itself for a usage). */
function nodeUsages(n: Node, files: readonly Node[]): Usage[] {
if (n.kind === "usage") return [n.usage];
if (n.kind === "file") return n.group.usages;
return files.flatMap((f) => (f.kind === "file" ? f.group.usages : []));
}
/** Toggles exclusion of `usages`: all excluded already → include them, else exclude them all. */
export function toggleExcludedUsages(excluded: ReadonlySet<string>, usages: readonly Usage[]): Set<string> {
const keys = usages.map(usageKey);
const next = new Set(excluded);
if (keys.every((k) => excluded.has(k))) keys.forEach((k) => next.delete(k));
else keys.forEach((k) => next.add(k));
return next;
}
/** The search's file groups as the tree shows them (access filter applied, files left empty dropped). */
function shownGroups(groups: readonly UsageGroup[], options: UsageAccessOptions): UsageGroup[] {
return groups.map((g) => ({ ...g, usages: filterUsageAccess(g.usages, options) })).filter((g) => g.usages.length > 0);
}
function exportedGroups(
groups: readonly UsageGroup[],
options: UsageAccessOptions,
excluded: ReadonlySet<string>,
): UsageGroup[] {
return shownGroups(groups, options)
.map((g) => ({ ...g, usages: g.usages.filter((u) => !excluded.has(usageKey(u))) }))
.filter((g) => g.usages.length > 0);
}
/** Export to Text File: the tree as shown (access filter applied), indented four spaces a level, without excluded usages. */
export function usagesReportText(
search: UsageSearch,
root: string,
options: UsageAccessOptions,
excluded: ReadonlySet<string>,
): string {
const files = exportedGroups(search.groups, options, excluded);
const total = usageCount(files);
const note = search.note ? ` ${search.note}` : "";
const lines = [
usageTabLabel(search, tx),
`${tx("Found usages")} (${total} ${tx(total === 1 ? "result" : "results")})${note}`,
];
for (const g of files) {
const dir = relativeDir(root, g.path);
const n = g.usages.length;
lines.push(` ${basename(g.path)}${dir ? ` ${dir}` : ""} (${n} ${tx(n === 1 ? "usage" : "usages")})`);
for (const u of g.usages) lines.push(` ${u.line + 1} ${u.text.trim()}`);
}
return `${lines.join("\n")}\n`;
}
const excludedIn = (search: UsageSearch) => useExcluded.getState().byTab[search.id] ?? NONE;
/** Whether the active search has usages to export (shown and not excluded). */
export function canExportUsages(): boolean {
const search = activeUsageSearch(useUsages.getState());
return (
!!search &&
!search.loading &&
exportedGroups(search.groups, useUsageAccessOptions.getState(), excludedIn(search)).length > 0
);
}
/** Saves the active search's results as text, to a file picked in the save dialog. */
export async function exportUsagesToTextFile(): Promise<void> {
const search = activeUsageSearch(useUsages.getState());
if (!search || !canExportUsages()) return;
const text = usagesReportText(
search,
useProject.getState().project?.root ?? "",
useUsageAccessOptions.getState(),
excludedIn(search),
);
const path = await save({
title: tx("Export to Text File"),
defaultPath: `${usageTabLabel(search, tx).replace(/[/\\:*?"<>|]/g, "_")}.txt`,
filters: [{ name: tx("Text file"), extensions: ["txt"] }],
});
if (!path) return;
try {
await writeDesktopText(path, text);
} catch (e) {
notifications().notify({
level: "error",
title: tx("Cannot export the usages"),
body: e instanceof Error ? e.message : String(e),
key: "usages.export",
});
}
}
function openUsage(u: Usage, focus: boolean) {
void openCodeLocation(u.path, { line: u.line, col: u.col }, { focus });
}
export function UsagesView() {
const tx = useTx();
const search = useUsages(activeUsageSearch);
const root = useProject((s) => s.project?.root ?? "");
const [collapsed, setCollapsed] = useState<{ id: number | null; keys: ReadonlySet<string> }>({
id: null,
keys: new Set(),
});
const accessOptions = useUsageAccessOptions();
const allUsages = useMemo(() => search?.groups.flatMap((g) => g.usages) ?? [], [search?.groups]);
const files = useMemo<Node[]>(
() => shownGroups(search?.groups ?? [], accessOptions).map((g) => ({ kind: "file", key: g.path, group: g })),
[search?.groups, accessOptions],
);
const roots = useMemo<Node[]>(() => (files.length ? [{ kind: "summary", key: SUMMARY_KEY }] : []), [files.length]);
const searchId = search?.id ?? null;
const expanded = useMemo(() => {
const hidden = collapsed.id === searchId ? collapsed.keys : new Set<string>();
return new Set([SUMMARY_KEY, ...files.map((r) => r.key)].filter((k) => !hidden.has(k)));
}, [files, collapsed, searchId]);
const getChildren = useCallback(
(n: Node): Node[] | undefined =>
n.kind === "summary"
? files
: n.kind === "file"
? n.group.usages.map((u) => ({ kind: "usage", key: usageKey(u), usage: u }) as Node)
: undefined,
[files],
);
const tree = useRef<TreeHandle>(null);
const [lead, setLead] = useState<Node | null>(null);
const excluded = useExcluded((s) => (searchId != null ? s.byTab[searchId] : undefined)) ?? NONE;
useOccurrenceNavigator("usages", (dir, focus) => {
const step = tree.current?.selectOccurrence(dir);
const n = step?.node as Node | undefined;
if (!step || n?.kind !== "usage") return null;
openUsage(n.usage, focus);
return step;
});
if (!search)
return (
<EmptyState>
<T>Use Find Usages (⌥F7) on a symbol to see its usages here</T>
</EmptyState>
);
const total = usageCount(search.groups);
const visibleLead =
lead?.kind === "usage"
? files.some((f) => f.kind === "file" && f.group.usages.some((u) => usageKey(u) === lead.key))
? lead
: null
: lead?.kind === "file"
? (files.find((f) => f.key === lead.key) ?? null)
: roots.length
? lead
: null;
const setAll = (collapse: boolean) =>
setCollapsed({ id: search.id, keys: collapse ? new Set(files.map((f) => f.key)) : new Set() });
const exclude = () => {
if (!visibleLead) return;
const next = toggleExcludedUsages(excluded, nodeUsages(visibleLead, files));
useExcluded.setState((s) => ({ byTab: { ...s.byTab, [search.id]: next } }));
// Excluding moves on to the next usage, as in IDEA.
if (next.size > excluded.size) tree.current?.selectOccurrence(1, { skipSubtree: true });
};
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
if ((e.key === "Backspace" || e.key === "Delete") && !e.metaKey && !e.altKey && !e.ctrlKey) {
e.preventDefault();
exclude();
}
};
const isExcluded = (n: Node) => nodeUsages(n, files).every((u) => excluded.has(usageKey(u)));
const renderNode = (n: Node, _state: TreeRowState) => {
if (n.kind === "summary")
return (
<span className={styles.row}>
<span className={styles.groupLabel}>
<T>Found usages</T>
</span>
<span className={styles.count}>
{!supportsUsageAccess(allUsages) || (accessOptions.read && accessOptions.write)
? total
: `${files.reduce((n, f) => n + (f.kind === "file" ? f.group.usages.length : 0), 0)} / ${total}`}{" "}
{tx(total === 1 ? "result" : "results")}
</span>
{search.note && <span className={styles.note}>{search.note}</span>}
</span>
);
if (n.kind === "file") {
const path = n.group.path;
return (
<span className={clsx(styles.row, isExcluded(n) && styles.excluded)}>
<Icon name={fileIconName(basename(path), path)} size={16} className={styles.icon} />
<span className={styles.file} title={path}>
{basename(path)}
</span>
<span className={styles.directory} title={path}>
{relativeDir(root, path)}
</span>
<span className={styles.count}>
{n.group.usages.length} {tx(n.group.usages.length === 1 ? "usage" : "usages")}
</span>
</span>
);
}
return (
<span className={clsx(styles.row, styles.occurrence, excluded.has(n.key) && styles.excluded)}>
<span className={styles.line}>{n.usage.line + 1}</span>
<UsagePreview usage={n.usage} />
</span>
);
};
return (
<div className={styles.view}>
<div className={styles.toolbar} role="toolbar" aria-orientation="vertical" aria-label={tx("Usages actions")}>
<IconButton
icon="refresh"
title={tx("Rerun Find Usages")}
size="small"
iconSize={16}
shortcut={shortcutLabel("usages.rerun")}
disabled={!search.rerun}
onClick={() => search.rerun?.()}
/>
<span className={styles.toolbarSep} />
<IconButton icon="arrow-up" action="navigate.prevOccurrence" size="small" iconSize={16} />
<IconButton icon="arrow-down" action="navigate.nextOccurrence" size="small" iconSize={16} />
<span className={styles.toolbarSep} />
<UsageAccessFilter items={allUsages} vertical />
<IconButton icon="expand-all" title="Expand All" size="small" iconSize={16} onClick={() => setAll(false)} />
<IconButton icon="collapse-all" title="Collapse All" size="small" iconSize={16} onClick={() => setAll(true)} />
<span className={styles.toolbarSep} />
<IconButton
icon="export"
title="Export to Text File…"
action="usages.exportToTextFile"
size="small"
iconSize={16}
disabled={search.loading || files.every(isExcluded)}
/>
</div>
<div className={styles.body} onKeyDown={onKeyDown}>
{!search.loading && !search.error && search.scope === "project" && (
<div className={styles.summary}>
<T>Usages in Project Files</T>
{search.searchLibraries && (
<button type="button" className={styles.link} onClick={() => search.searchLibraries?.()}>
{tx("Search in Project and Libraries")}
</button>
)}
</div>
)}
{(search.loading || search.error) && (
<div className={styles.summary} role="status" aria-live="polite">
{search.loading ? (
<>
<Spinner size={16} variant="spokes" />{" "}
{search.symbol
? formatMessage(tx("Searching for usages of '{symbol}'"), { symbol: search.symbol })
: tx("Searching for usages")}
…
</>
) : (
<span className={styles.error}>{search.error}</span>
)}
</div>
)}
<UsagesSplit preview={<UsagesPreview node={visibleLead} />}>
<Tree<Node>
key={`${search.id}:${accessOptions.read}:${accessOptions.write}`}
aria-label="Usages"
handleRef={tree}
roots={roots}
getKey={(n) => n.key}
getLabel={(n) =>
n.kind === "summary"
? tx("Found usages")
: n.kind === "file"
? basename(n.group.path)
: n.usage.text.trim()
}
getChildren={getChildren}
isExpandable={(n) => n.kind !== "usage"}
isOccurrence={(n) => n.kind === "usage" && !excluded.has(n.key)}
expanded={expanded}
onExpandedChange={(next) =>
setCollapsed({
id: search.id,
keys: new Set([SUMMARY_KEY, ...files.map((f) => f.key)].filter((k) => !next.has(k))),
})
}
renderNode={renderNode}
multiSelect={false}
onSelectionChange={(_sel, node) => setLead(node)}
onContextMenu={(n, _sel, e) => {
if (!n) return;
showContextMenu(e, [
{
id: "exclude",
label: isExcluded(n) ? "Include" : "Exclude",
shortcut: "⌫",
run: () => {
setLead(n);
const next = toggleExcludedUsages(excluded, nodeUsages(n, files));
useExcluded.setState((s) => ({ byTab: { ...s.byTab, [search.id]: next } }));
},
},
]);
}}
onActivate={(n) => {
const u = n.kind === "usage" ? n.usage : n.kind === "file" ? n.group.usages[0] : undefined;
if (u) openUsage(u, true);
}}
empty={
!search.loading && !search.error ? (
<EmptyState>{total ? tx("No usages match the access filters") : <T>No usages found</T>}</EmptyState>
) : undefined
}
/>
</UsagesSplit>
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Preview pane (persisted toggle in the ⋮ menu; on by default, like the Find tool window's).
const OPTIONS_KEY = "openidea.usages.view.v1";
export const useUsagesOptions = create<{ preview: boolean }>(() => {
try {
return { preview: true, ...JSON.parse(globalThis.localStorage?.getItem(OPTIONS_KEY) ?? "{}") };
} catch {
return { preview: true };
}
});
useUsagesOptions.subscribe((s) => {
try {
globalThis.localStorage?.setItem(OPTIONS_KEY, JSON.stringify(s));
} catch {
/* storage unavailable */
}
});
/** The Find Usages tool window's ⋮ menu entries. */
export function useUsagesHeaderMenu(): MenuItem[] {
const preview = useUsagesOptions((s) => s.preview);
return [
{
id: "preview",
label: "Preview Source",
checked: preview,
run: () => useUsagesOptions.setState({ preview: !preview }),
},
];
}
const DEFAULT_PREVIEW_LAYOUT = { usages: 50, preview: 50 };
function UsagesSplit({ preview, children }: { preview: ReactNode; children: ReactNode }) {
const show = useUsagesOptions((s) => s.preview);
const frame = useRef<HTMLDivElement>(null);
const [stacked, setStacked] = useState(false);
useLayoutEffect(() => {
const el = frame.current;
if (!show || !el) return;
const measure = () => setStacked(el.clientWidth < 580);
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(el);
return () => observer.disconnect();
}, [show]);
if (!show) return children;
return (
<div ref={frame} className={styles.splitFrame}>
<SplitGroup
orientation={stacked ? "vertical" : "horizontal"}
id="usages-preview-split"
storageKey={stacked ? "openidea.usages.previewSplit.vertical" : "openidea.usages.previewSplit"}
defaultLayout={DEFAULT_PREVIEW_LAYOUT}
>
<SplitPanel id="usages" minSize={stacked ? "30%" : 160} className={styles.panel}>
{children}
</SplitPanel>
<SplitHandle />
<SplitPanel id="preview" minSize={stacked ? "30%" : 160} className={styles.panel}>
{preview}
</SplitPanel>
</SplitGroup>
</div>
);
}
function UsagesPreview({ node }: { node: Node | null }) {
const usage = node?.kind === "usage" ? node.usage : node?.kind === "file" ? (node.group.usages[0] ?? null) : null;
const search = useUsages(activeUsageSearch);
const settings = useProject((s) => s.settings?.editor);
const { fallbackFont } = useEditorPrefs();
const family = settings?.fontFamily;
const fontFamily =
(family && family !== BUNDLED_MONO_FAMILY) || fallbackFont.trim()
? monoFontFamily(family, fallbackFont, "var(--font-mono)")
: undefined;
const highlights = useMemo(() => {
const group = usage && search?.groups.find((g) => g.path === usage.path);
return (group?.usages ?? []).map((u) => ({ line: u.line, ranges: [[u.col, u.endCol] as const] }));
}, [usage, search?.groups]);
return (
<div
className={styles.sourcePreview}
style={{
fontFamily,
fontSize: settings?.fontSize ?? undefined,
lineHeight: settings?.lineHeight != null ? `${settings.lineHeight}px` : undefined,
}}
>
<SourcePreview
path={usage?.path ?? null}
line={usage?.line ?? 0}
highlights={highlights}
load={previewText}
colorize={previewColors}
editorLayout
className={styles.sourceText}
/>
</div>
);
}