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

...
Автор SHA1 Повідомлення Дата
l0ng-ai f79ae0273e refactor(editor): provide the Copy Path chooser to the editor API instead of importing it
Keeps @/editor/api free of the popup store and keymap imports, so modules
that load it (and the language smoke's inputs) don't grow.
2026-11-27 03:36:26 +08:00
l0ng-ai c6c17c4a8f feat(project): Copy Path/Reference… in the Project view opens the previewing chooser
The Project view's Copy Path/Reference… opened a submenu of names only. It now
opens the same chooser as the editor, at the menu's position, with a preview
of what each row copies for the selection (several paths one per line):
absolute path, file name, path from content root and source root, plus the
contributed rows (repository path, remote link, agent reference).
2026-11-27 03:29:37 +08:00
l0ng-ai 74eefd6116 feat(agents): Send to Agent from the editor tab menu and editor tab drops on the composer (#6241)
The editor tab context menu gets Send to Agent, which adds the tab's file as
an @ reference to the agent message typed last. Dragging a file tab onto the
agent composer adds the same reference; session and virtual tabs are not
accepted there.

Fixes #6036
2026-11-27 03:22:21 +08:00
12 змінених файлів з 283 додано та 97 видалено

No files matched your search

+16
Переглянути файл
@@ -41,3 +41,19 @@ test("Copy Path/Reference keeps its preview and shortcut visible and can be resi
await expect(popup).toBeHidden();
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(path);
});
test("Copy Path/Reference… in the Project view previews what each row copies", async ({ workbench: page, context }) => {
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await page.getByRole("treeitem", { name: "build.gradle.kts" }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Copy Path/Reference…" }).click();
const popup = page.getByRole("dialog", { name: "Copy Path/Reference…" });
const name = popup.getByRole("option", { name: /^File Name/ });
await expect(name.locator('[title="build.gradle.kts"]')).toBeVisible();
await expect(popup.getByRole("option", { name: /^Path From Content Root/ })).toBeVisible();
await page.keyboard.type("file name");
await expect(name).toHaveAttribute("aria-selected", "true");
await page.keyboard.press("Enter");
await expect(popup).toBeHidden();
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("build.gradle.kts");
});
+32 -1
Переглянути файл
@@ -34,7 +34,7 @@ import type { LanguageDescription } from "@codemirror/language";
import type { HunkKind } from "@/bindings";
import type { LineEnding } from "@/platform/ipc";
import { create } from "zustand";
import { maybeEditorService, type EditorInput } from "@/workbench/contributions";
import { maybeEditorService, type EditorInput, type MenuGroupContext } from "@/workbench/contributions";
import { isSameOrInside } from "@/platform/paths";
import { useProject } from "@/platform/project";
import { rootOfPath } from "@/platform/projectRoots";
@@ -1017,6 +1017,37 @@ export function _provideCodePreview(provider: typeof codePreviewProvider) {
codePreviewProvider = provider;
}
/** A row of the Copy Path/Reference… chooser. */
export interface CopyPathRow {
/** The action whose shortcut the row shows. */
id: string;
/** English label, translated by the chooser. */
label: string;
/** The copied text; a row without one is left out. */
preview: string | null;
run: () => void;
}
type CopyPathChooser = (
anchor: { x: number; y: number } | "center",
rows: readonly CopyPathRow[],
ctx: MenuGroupContext,
) => void;
let copyPathChooser: CopyPathChooser | null = null;
/**
* The editor's Copy Path/Reference… chooser for files outside an editor (the Project view's
* selection): `rows`, then the rows contributed to the `copyPath` menu for `ctx`, with previews.
*/
export function openCopyPathChooser(...args: Parameters<CopyPathChooser>): void {
copyPathChooser?.(...args);
}
/** @internal editor/core only. */
export function _provideCopyPathChooser(open: CopyPathChooser) {
copyPathChooser = open;
}
let workspaceHistory: ((id: number, redo: boolean) => Promise<void>) | null = null;
/** Undo/redo a refactoring through the same history used by editor commands. */
+18 -39
Переглянути файл
@@ -70,7 +70,8 @@ import { customRegions } from "./cm/regions";
import { toggleRenderedViewAtCaret } from "./cm/renderedDocs";
import { enclosingHeaders } from "./cm/stickyScroll";
import { moveElementLeft, moveElementRight } from "./cm/moveElement";
import { caretAnchor, openPopup, updatePopup, useLspPopup, type LspPopup } from "@/editor/lsp/popupStore";
import { caretAnchor, openPopup, updatePopup, useLspPopup } from "@/editor/lsp/popupStore";
import { copyPathPopup } from "./copyPathChooser";
import {
cursorCodeBlockEnd,
cursorCodeBlockStart,
@@ -111,7 +112,7 @@ import {
import { useProject } from "@/platform/project";
import { call, commands } from "@/platform/ipc";
import { editorPrefs } from "@/platform/editorSettings";
import { menuGroupItems, notifications } from "@/workbench/contributions";
import { notifications } from "@/workbench/contributions";
import { togglePinSelectedContent } from "@/workbench/toolwindows/content";
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
import { toggleReadOnly } from "./fileAttributes";
@@ -649,22 +650,6 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot | null) {
// The popup's items resolve against the open document; a notebook cell has none.
if (!slot) return;
const path = slot.model.path;
const contributed = menuGroupItems("copyPath", {
paths: [path],
...selectedLineContext(view.state),
}).flatMap((item) =>
(item.kind ?? "item") === "item" && "run" in item && item.id && item.run && item.preview
? [
{
id: item.id,
label: item.verbatim ? item.label : tx(item.label),
preview: item.preview,
shortcut: shortcutLabel(item.id),
run: item.run,
},
]
: [],
);
const flavours = [
{ id: "project.copyAbsolutePath", label: "Absolute Path", value: pathToCopy("absolute", path) },
{
@@ -681,26 +666,20 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot | null) {
value: pathWithLines(view.state, path),
},
];
const popup: Extract<LspPopup, { kind: "list" }> = {
kind: "list",
title: tx("Copy Path/Reference…"),
layout: "copyPath",
anchor: caretAnchor(view, view.state.selection.main.head),
items: [
...flavours
.filter((f) => f.value !== null)
.map((f) => ({
id: f.id,
label: tx(f.label),
preview: f.value!,
shortcut: shortcutLabel(f.id),
run: () => {
const lineNumbered =
f.id === "editor.copyPathWithLineNumber" || f.id === "editor.copyAbsolutePathWithLineNumber";
void executeAction(f.id, lineNumbered ? f.value : path);
},
})),
...contributed,
const popup = copyPathPopup(
caretAnchor(view, view.state.selection.main.head),
flavours.map((f) => ({
id: f.id,
label: f.label,
preview: f.value,
run: () => {
const lineNumbered =
f.id === "editor.copyPathWithLineNumber" || f.id === "editor.copyAbsolutePathWithLineNumber";
void executeAction(f.id, lineNumbered ? f.value : path);
},
})),
{ paths: [path], ...selectedLineContext(view.state) },
[
{
id: "editor.copyReference",
label: tx("Reference"),
@@ -710,7 +689,7 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot | null) {
run: () => {},
},
],
};
);
openPopup(popup);
void resolveReference(view, slot)
.then((reference) => {
+52
Переглянути файл
@@ -0,0 +1,52 @@
/** The Copy Path/Reference… chooser: each way to copy, with a preview of the text it copies. */
import { tx } from "@/platform/i18n";
import { shortcutLabel } from "@/platform/keymap";
import { menuGroupItems, type MenuGroupContext } from "@/workbench/contributions";
import { openPopup, type ListPopupItem, type LspPopup, type PopupPoint } from "@/editor/lsp/popupStore";
import type { CopyPathRow } from "@/editor/api";
/** The chooser's popup: `rows`, then the rows contributed to the `copyPath` menu for `ctx`. */
export function copyPathPopup(
anchor: PopupPoint | "center",
rows: readonly CopyPathRow[],
ctx: MenuGroupContext,
trailing: readonly ListPopupItem[] = [],
): Extract<LspPopup, { kind: "list" }> {
const contributed = menuGroupItems("copyPath", ctx).flatMap((item) =>
(item.kind ?? "item") === "item" && "run" in item && item.id && item.run && item.preview
? [
{
id: item.id,
label: item.verbatim ? item.label : tx(item.label),
preview: item.preview,
shortcut: shortcutLabel(item.id),
run: item.run,
},
]
: [],
);
return {
kind: "list",
title: tx("Copy Path/Reference…"),
layout: "copyPath",
anchor,
items: [
...rows.flatMap((row) =>
row.preview === null
? []
: [{ id: row.id, label: tx(row.label), preview: row.preview, shortcut: shortcutLabel(row.id), run: row.run }],
),
...contributed,
...trailing,
],
};
}
/** Opens the chooser for files outside an editor (`openCopyPathChooser` of `@/editor/api`). */
export function openCopyPathChooser(
anchor: PopupPoint | "center",
rows: readonly CopyPathRow[],
ctx: MenuGroupContext,
): void {
openPopup(copyPathPopup(anchor, rows, ctx));
}
+3 -1
Переглянути файл
@@ -10,7 +10,8 @@ import {
registerOverlay,
registerStatusItem,
} from "@/workbench/contributions";
import { _provideCodePreview, _provideDocumentAttacher, editorsFor } from "@/editor/api";
import { _provideCodePreview, _provideCopyPathChooser, _provideDocumentAttacher, editorsFor } from "@/editor/api";
import { openCopyPathChooser } from "./copyPathChooser";
import { isUntitledUri } from "@/platform/virtualDocs";
import { formatDocument } from "@/editor/lsp/format";
import { chooserTitle, locationItems, pinToFind } from "@/editor/lsp/navigation";
@@ -82,6 +83,7 @@ export function activate(): void | (() => void) {
},
});
_provideDocumentAttacher((path, options) => attachDocument(ctrl.manager, path, options));
_provideCopyPathChooser(openCopyPathChooser);
_provideCodePreview((path, editable) =>
previewExtensions(path, ctrl.manager.settings()?.editor, ctrl.manager.backend, editable),
);
+21 -3
Переглянути файл
@@ -24,7 +24,9 @@ import { registerKeyClaim } from "@/platform/keymap";
import { isVirtualUri } from "@/platform/virtualDocs";
import { copySourceOf } from "@/platform/clipboardSource";
import {
EDITOR_TAB_MIME,
getAgentContextSources,
maybeEditorService,
notifications,
OWNS_FILE_DROP,
type AgentContextSource,
@@ -100,6 +102,18 @@ type Item =
const isSection = (item: Item) => item.kind === "section";
/** The file of an editor tab drag payload (`{paneId, tabId}`), null for virtual and non-file tabs. */
const tabFilePath = (payload: string): string | null => {
try {
const p = JSON.parse(payload) as { paneId?: unknown; tabId?: unknown };
if (typeof p.paneId !== "string" || typeof p.tabId !== "string") return null;
const input = maybeEditorService()?.tabInput?.(p.paneId, p.tabId);
return input?.kind === "file" && input.path && !isVirtualUri(input.path) ? input.path : null;
} catch {
return null;
}
};
const SECTION_TITLES: Record<Section, string> = {
command: "Commands",
skill: "Skills",
@@ -941,17 +955,21 @@ export function Composer(props: ComposerProps) {
};
}, [addPaths, addImages]);
// Files and folders dragged from the Project view: the same `@` references.
// Files and folders dragged from the Project view, and file tabs dragged from the editor:
// the same `@` references.
useEffect(() => {
const el = boxRef.current;
if (!el) return;
return registerDropTarget(el, {
accepts: (type) => type === FILES_DRAG,
accepts: (type, data) => type === FILES_DRAG || (type === EDITOR_TAB_MIME && !!tabFilePath(data.payload)),
over: () => setFileOver(true),
leave: () => setFileOver(false),
drop: (data) => {
setFileOver(false);
addPaths(data.payload.split("\n").filter(Boolean));
if (data.type === EDITOR_TAB_MIME) {
const path = tabFilePath(data.payload);
if (path) addPaths([path]);
} else addPaths(data.payload.split("\n").filter(Boolean));
},
});
}, [addPaths]);
+27
Переглянути файл
@@ -7,6 +7,7 @@ import userEvent from "@testing-library/user-event";
import { caretOf, setCaret, textOf, typeChars, typeIn } from "./composerTesting";
import chipStyles from "./ReferenceChip.module.css";
import { FILES_DRAG, dragSession } from "@/ui";
import { EDITOR_TAB_MIME, provideEditorService, type EditorService } from "@/workbench/contributions";
import { useProject } from "@/platform/project";
const findFiles = vi.fn();
@@ -123,6 +124,32 @@ describe("Composer dropped paths", () => {
expect(textOf(box)).toBe("@src/a.ts @src/dir/ ");
});
it("references the file of an editor tab dragged onto it and ignores other tabs", () => {
provideEditorService({
tabInput: (_pane: string, tab: string) =>
tab === "file"
? { kind: "file", key: "/p/src/a.ts", path: "/p/src/a.ts" }
: { kind: "agentSession", key: "agent:one", data: { task: "one" } },
} as unknown as EditorService);
const box = renderComposer();
const restore = document.elementFromPoint;
document.elementFromPoint = () => box;
try {
act(() => {
const other = dragSession({
type: EDITOR_TAB_MIME,
payload: JSON.stringify({ paneId: "p", tabId: "session" }),
});
expect(other.drop(0, 0)).toBe(false);
const file = dragSession({ type: EDITOR_TAB_MIME, payload: JSON.stringify({ paneId: "p", tabId: "file" }) });
expect(file.drop(0, 0)).toBe(true);
});
} finally {
document.elementFromPoint = restore;
}
expect(textOf(box)).toBe("@src/a.ts ");
});
it("deduplicates live references and allows a deleted reference to be dropped again", () => {
const box = renderComposer();
drop(box, "/p/src/a.ts\n/p/src/a.ts\n/p/src/dir/");
+3 -2
Переглянути файл
@@ -232,7 +232,7 @@ export function activate(): () => void {
registerStatusItem({ id: "agents.status", align: "right", priority: 3, title: "Agents", component: AgentsStatus }),
registerMenuGroup({
id: "agents.send",
menus: ["editor", "projectView"],
menus: ["editor", "editorTab", "projectView"],
order: 80,
items: (menu, { paths, dirs }) =>
paths.length && !paths.some(isVirtualUri) && agentsHere()
@@ -240,7 +240,8 @@ export function activate(): () => void {
{
kind: "action",
action: "agents.sendToAgent",
arg: menu === "projectView" ? paths.map((p, i) => (dirs?.[i] ? `${p}/` : p)) : undefined,
// The editor sends its selection; a tab or the Project view sends the files.
arg: menu === "editor" ? undefined : paths.map((p, i) => (dirs?.[i] ? `${p}/` : p)),
},
]
: [],
+18
Переглянути файл
@@ -3,6 +3,7 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
import type { AgentEntry, AgentEvent, AgentTask } from "@/bindings";
import {
dropOnEditor,
menuGroupItems,
useContributions,
useEditorTabTitles,
type EditorInput,
@@ -595,3 +596,20 @@ describe("the diff of an agent change", () => {
expect(backend.openInput.mock.lastCall![0].data.chain).toBeUndefined();
});
});
describe("Send to Agent menus", () => {
it("sends the selection from the editor and the files from an editor tab or the Project view", () => {
const dispose = activate();
try {
const send = (menu: "editor" | "editorTab" | "projectView", dirs?: boolean[]) =>
menuGroupItems(menu, { paths: ["/p/a.ts", "/p/src"].slice(0, dirs ? 2 : 1), dirs }).find(
(i) => "action" in i && i.action === "agents.sendToAgent",
);
expect(send("editor")).toMatchObject({ arg: undefined });
expect(send("editorTab")).toMatchObject({ arg: ["/p/a.ts"] });
expect(send("projectView", [false, true])).toMatchObject({ arg: ["/p/a.ts", "/p/src/"] });
} finally {
dispose();
}
});
});
+2 -2
Переглянути файл
@@ -605,7 +605,7 @@ export function ProjectView() {
const rootNode = m.roots[0];
if (!rootNode) return;
setSelection(new Set([rootNode.key]), rootNode.key);
showContextMenu(e, contextMenuItems([rootNode]));
showContextMenu(e, contextMenuItems([rootNode], { x: e.clientX, y: e.clientY }));
return;
}
const nodes = [...sel].map((k) => m.byKey.get(k)).filter((n): n is ProjectNode => !!n && !n.placeholder);
@@ -614,7 +614,7 @@ export function ProjectView() {
// Contributed groups may read the file first (bounded wait).
const at = { x: e.clientX, y: e.clientY };
void prepareMenuGroups("projectView", menuGroupContext(target)).then(() =>
showContextMenu(at, contextMenuItems(target)),
showContextMenu(at, contextMenuItems(target, at)),
);
}, []);
+39 -15
Переглянути файл
@@ -8,6 +8,11 @@ import { registerMenuGroup } from "@/workbench/contributions";
import { contextMenuItems, keyLabel, revealLabel } from "./contextMenu";
import type { ProjectNode } from "./model";
import { useProjectTree } from "./store";
import { closePopup, useLspPopup } from "@/editor/lsp/popupStore";
import { _provideCopyPathChooser } from "@/editor/api";
import { openCopyPathChooser } from "@/editor/core/copyPathChooser";
_provideCopyPathChooser(openCopyPathChooser);
vi.mock("@/platform/ipc", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/ipc")>()),
@@ -79,6 +84,7 @@ beforeEach(() => {
});
afterEach(() => {
closePopup();
disposers.forEach((d) => d());
useProject.setState({ project: null, settings: null });
useProjectTree.setState({ root: null });
@@ -147,38 +153,56 @@ describe("project view context menu", () => {
}
});
it("lists contributed links in Copy Path/Reference…", () => {
/** Runs Copy Path/Reference… and returns the chooser's rows as `label: preview`. */
const chooser = (items: MenuItem[]) => {
const item = resolveMenuItems(items).find((r) => r.label === "Copy Path/Reference…");
expect(item?.submenu).toBeUndefined();
item!.run!();
const popup = useLspPopup.getState().popup;
return popup?.kind === "list" ? popup.items.map((i) => `${i.label}: ${i.preview}`) : undefined;
};
it("previews each way Copy Path/Reference… copies the selection, contributed links included", () => {
disposers.push(
registerMenuGroup({
id: "test.link",
menus: ["copyPath"],
items: (_menu, ctx) => [
{ label: `Link ${ctx.paths.join()} ${ctx.dirs?.join()}`, verbatim: true, run: () => undefined },
{
id: "test.link",
label: "Link",
verbatim: true,
preview: `${ctx.paths.join()} ${ctx.dirs?.join()}`,
run: () => undefined,
},
// Without a preview a contribution has nothing to show in the chooser.
{ id: "test.bare", label: "Bare", run: () => undefined },
],
}),
);
expect(sub(contextMenuItems([node("/p/src", true)]), "Copy Path/Reference…")).toEqual([
"Absolute Path",
"File Name",
"Path From Content Root",
"-",
"Link /p/src true",
expect(chooser(contextMenuItems([node("/p/src", true), node("/p/src/a.ts")], { x: 10, y: 20 }))).toEqual([
"Absolute Path: /p/src\n/p/src/a.ts",
"File Name: src\na.ts",
"Path From Content Root: src\nsrc/a.ts",
"Link: /p/src,/p/src/a.ts true,false",
]);
expect(useLspPopup.getState().popup).toMatchObject({ layout: "copyPath", anchor: { x: 10, y: 20 } });
});
it("lists contributed links in Copy Path/Reference… of library files too", () => {
it("offers no content root paths for library files in Copy Path/Reference…", () => {
disposers.push(
registerMenuGroup({
id: "test.link",
menus: ["copyPath"],
items: (_menu, ctx) => [{ label: `Link ${ctx.paths.join()}`, verbatim: true, run: () => undefined }],
items: (_menu, ctx) => [
{ id: "test.link", label: "Link", verbatim: true, preview: ctx.paths.join(), run: () => undefined },
],
}),
);
expect(sub(contextMenuItems([{ ...node("/root/.m2/lib.jar"), readOnly: true }]), "Copy Path/Reference…")).toEqual([
"Absolute Path",
"File Name",
"-",
"Link /root/.m2/lib.jar",
expect(chooser(contextMenuItems([{ ...node("/root/.m2/lib.jar"), readOnly: true }]))).toEqual([
"Absolute Path: /root/.m2/lib.jar",
"File Name: lib.jar",
"Link: /root/.m2/lib.jar",
]);
});
+52 -34
Переглянути файл
@@ -1,5 +1,7 @@
/** Context menu and "New" popup of the project view. */
import { openCopyPathChooser } from "@/editor/api";
import { executeAction, getAction } from "@/platform/actions";
import type { PathKind } from "@/platform/copyPath";
import { getContext } from "@/platform/context";
import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
import { formatBinding, hostBinding, isMacHost, shortcutLabel } from "@/platform/keymap";
@@ -18,6 +20,7 @@ import {
canPaste,
copyPaths,
copySelection,
pathsFor,
delegate,
deleteSelection,
findFileUsages,
@@ -151,6 +154,8 @@ function delegated(
}
type Entry = MenuItem | null | false | undefined;
/** Where a menu opens; popups its items open appear there. */
type MenuPoint = { x: number; y: number } | "center";
/** A submenu of the present entries, or nothing when none is left (never an empty submenu). */
function submenu(id: string, label: string, entries: Entry[], icon?: string): MenuItem | null {
@@ -160,8 +165,13 @@ function submenu(id: string, label: string, entries: Entry[], icon?: string): Me
}
/** Project view actions available for the selected files and directories. */
export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
if (nodes.some((n) => n.readOnly)) return libraryMenuItems(nodes.filter((n) => !n.group));
/** `at`: where the menu opens, for the popups its items open (Copy Path/Reference…). */
export function contextMenuItems(nodes: ProjectNode[], at: MenuPoint = "center"): MenuItem[] {
if (nodes.some((n) => n.readOnly))
return libraryMenuItems(
nodes.filter((n) => !n.group),
at,
);
const lead = nodes[0] ?? null;
const single = nodes.length === 1 ? lead : null;
const nonRoot = nodes.filter((n) => !n.root);
@@ -217,22 +227,7 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
disabled: !nonRoot.length,
run: () => copySelection(false),
},
{
id: "copyPath",
label: "Copy Path/Reference…",
submenu: [
{
id: "abs",
label: "Absolute Path",
shortcut: keyLabel("project.copyAbsolutePath"),
run: () => void copyPaths("absolute", nodes),
},
{ id: "name", label: "File Name", run: () => void copyPaths("name", nodes) },
{ id: "rel", label: "Path From Content Root", run: () => void copyPaths("relative", nodes) },
{ kind: "separator" },
...menuGroupItems("copyPath", menuGroupContext(nodes)),
],
},
copyPathItem(nodes, at, false),
{
id: "paste",
label: "Paste",
@@ -464,27 +459,13 @@ function openInRightSplitItem(files: ProjectNode[]): MenuItem {
}
/** Library sources (External Libraries) are read-only: copy, find and reveal only. */
function libraryMenuItems(nodes: ProjectNode[]): MenuItem[] {
function libraryMenuItems(nodes: ProjectNode[], at: MenuPoint): MenuItem[] {
if (!nodes.length) return [];
const single = nodes.length === 1 ? nodes[0]! : null;
const folder = single?.dir ? single.path : null;
const items: Entry[] = [
{ id: "copy", label: "Copy", icon: "copy", shortcut: keyLabel("project.copy"), run: () => copySelection(false) },
{
id: "copyPath",
label: "Copy Path/Reference…",
submenu: [
{
id: "abs",
label: "Absolute Path",
shortcut: keyLabel("project.copyAbsolutePath"),
run: () => void copyPaths("absolute", nodes),
},
{ id: "name", label: "File Name", run: () => void copyPaths("name", nodes) },
{ kind: "separator" },
...menuGroupItems("copyPath", menuGroupContext(nodes)),
],
},
copyPathItem(nodes, at, true),
{ kind: "separator" },
!!folder && delegated("find.inPath", { directory: folder }, "Find in Files…", { icon: "search" }),
!!folder && { kind: "separator" },
@@ -518,6 +499,43 @@ export function revealLabel() {
return fileManagerName();
}
/**
* Copy Path/Reference…: a chooser previewing what each way copies for the selection (several
* paths one per line), contributed links and references included. Library files have no
* content or source root.
*/
function copyPathItem(nodes: ProjectNode[], at: MenuPoint, library: boolean): Entry {
const row = (kind: PathKind, id: string, label: string) => {
const paths = pathsFor(kind, nodes);
return {
id,
label,
// A selection only partly under a source root has no source-root path.
preview: paths.length && paths.length === nodes.length ? paths.join("\n") : null,
run: () => void copyPaths(kind, nodes),
};
};
return {
id: "copyPath",
label: "Copy Path/Reference…",
run: () =>
openCopyPathChooser(
at,
[
row("absolute", "project.copyAbsolutePath", "Absolute Path"),
row("name", "project.copyFileName", "File Name"),
...(library
? []
: [
row("relative", "project.copyRelativePath", "Path From Content Root"),
row("source", "project.copySourceRootPath", "Path From Source Root"),
]),
],
menuGroupContext(nodes),
),
};
}
/** What contributed menu groups see: the selected (non-placeholder) paths. */
export function menuGroupContext(nodes: ProjectNode[]): MenuGroupContext {
const real = nodes.filter((n) => !n.placeholder);