Open History to see the last commit
1import {
2 EDITORS,
3 type ContextMenuItem,
4 type EditorId,
5 type EnvironmentId,
6} from "@t3tools/contracts";
7
8import { resolveDiffPathForWorkspace } from "./diffFileActions";
9import {
10 revealInFileExplorerLabelForKind,
11 revealInFileExplorerLabelForOs,
12} from "~/components/preview/fileExplorerLabel";
13import { readLocalApi } from "./localApi";
14import { serverEnvironment } from "./state/server";
15import { shellEnvironment } from "./state/shell";
16import { useAtomCommand } from "./state/use-atom-command";
17import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
18import { toastManager } from "./components/ui/toast";
19import { useAtomValue } from "@effect/atom-react";
20
21export type FileContextMenuAction =
22 | "reveal-in-folder"
23 | "open"
24 /** Submenu parent; never the activated id. */
25 | "open-with"
26 | `editor:${EditorId}`;
27
28export interface FileContextMenuTarget {
29 readonly environmentId: EnvironmentId | null;
30 /** Repo- or workspace-relative file path, as shown in diffs. */
31 readonly filePath: string;
32 readonly workspaceRoot: string | undefined;
33 readonly repositoryRoot?: string | undefined;
34}
35
36export function resolveFileContextMenuAbsolutePath(target: FileContextMenuTarget): string | null {
37 const workspaceFilePath = resolveDiffPathForWorkspace({
38 filePath: target.filePath,
39 workspaceRoot: target.workspaceRoot,
40 repositoryRoot: target.repositoryRoot,
41 });
42 if (workspaceFilePath === null) return null;
43 if (target.workspaceRoot === undefined) {
44 return workspaceFilePath.startsWith("/") || /^[a-zA-Z]:/.test(workspaceFilePath)
45 ? workspaceFilePath
46 : null;
47 }
48 return resolvePathLinkTarget(workspaceFilePath, target.workspaceRoot);
49}
50
51const EDITOR_LABEL_BY_ID = new Map(EDITORS.map((editor) => [editor.id, editor.label]));
52
53export interface FileContextMenuCapabilities {
54 readonly revealLabel: string | undefined;
55 readonly canOpenDefault: boolean;
56 readonly editorIds: ReadonlyArray<EditorId>;
57}
58
59export function buildFileContextMenuItems(input: {
60 readonly hasAbsolutePath: boolean;
61 readonly capabilities: FileContextMenuCapabilities;
62}): readonly ContextMenuItem<FileContextMenuAction>[] {
63 if (!input.hasAbsolutePath) return [];
64 const items: ContextMenuItem<FileContextMenuAction>[] = [];
65 if (input.capabilities.canOpenDefault) {
66 items.push({ id: "open", label: "Open", icon: "pencil" });
67 }
68 if (input.capabilities.revealLabel !== undefined) {
69 items.push({
70 id: "reveal-in-folder",
71 label: input.capabilities.revealLabel,
72 icon: "folder-tree",
73 });
74 }
75 const editorIds = input.capabilities.editorIds.filter((id) => id !== "file-manager");
76 if (editorIds.length > 0) {
77 items.push({
78 id: "open-with",
79 label: "Open with",
80 children: editorIds.map((editorId) => ({
81 id: `editor:${editorId}` as FileContextMenuAction,
82 label: EDITOR_LABEL_BY_ID.get(editorId) ?? editorId,
83 })),
84 });
85 }
86 return items;
87}
88
89export function useFileContextMenu(environmentId: EnvironmentId | null) {
90 const openInEditor = useAtomCommand(shellEnvironment.openInEditor, { reportFailure: false });
91 const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
92
93 const availableEditors = serverConfig?.availableEditors ?? [];
94 const capabilities: FileContextMenuCapabilities = {
95 // The reveal wording comes from the server because on WSL the reveal can
96 // run through Windows File Explorer even though the host reports Linux.
97 revealLabel:
98 environmentId !== null &&
99 serverConfig?.shellRevealInFileManager === true &&
100 serverConfig.availableEditors.includes("file-manager")
101 ? serverConfig.shellRevealInFileManagerKind === undefined
102 ? revealInFileExplorerLabelForOs(serverConfig.environment.platform.os)
103 : revealInFileExplorerLabelForKind(serverConfig.shellRevealInFileManagerKind)
104 : undefined,
105 canOpenDefault: availableEditors.includes("file-manager"),
106 editorIds: availableEditors,
107 };
108
109 const activate = async (
110 action: FileContextMenuAction,
111 target: FileContextMenuTarget,
112 ): Promise<void> => {
113 const absolutePath = resolveFileContextMenuAbsolutePath(target);
114 if (absolutePath === null || environmentId === null) return;
115
116 const reveal = action === "reveal-in-folder";
117 const editor =
118 action === "open" || reveal
119 ? ("file-manager" as const)
120 : (action.slice("editor:".length) as EditorId);
121 if (action !== "open" && !reveal && !capabilities.editorIds.includes(editor)) return;
122
123 const result = await openInEditor({
124 environmentId,
125 input: { cwd: absolutePath, editor, ...(reveal ? { reveal: true } : {}) },
126 });
127 if (result._tag !== "Failure") return;
128 toastManager.add({
129 type: "error",
130 title:
131 action === "open"
132 ? "Could not open file"
133 : reveal
134 ? "Unable to reveal file"
135 : `Could not open in ${EDITOR_LABEL_BY_ID.get(editor) ?? editor}`,
136 description: absolutePath,
137 });
138 };
139
140 const show = async (
141 target: FileContextMenuTarget,
142 position?: { x: number; y: number },
143 ): Promise<void> => {
144 const api = readLocalApi();
145 const items = buildFileContextMenuItems({
146 hasAbsolutePath: resolveFileContextMenuAbsolutePath(target) !== null,
147 capabilities,
148 });
149 if (items.length === 0 || api === undefined) return;
150 const clicked = await api.contextMenu.show(items, position);
151 if (clicked === null) return;
152 await activate(clicked as FileContextMenuAction, target);
153 };
154
155 return {
156 buildItems: (target: FileContextMenuTarget) =>
157 buildFileContextMenuItems({
158 hasAbsolutePath: resolveFileContextMenuAbsolutePath(target) !== null,
159 capabilities,
160 }),
161 capabilities,
162 activate,
163 show,
164 };
165}
166
167export function useFileContextMenuHandler(environmentId: EnvironmentId | null) {
168 const contextMenu = useFileContextMenu(environmentId);
169 return (target: FileContextMenuTarget, event?: { clientX: number; clientY: number }) => {
170 void contextMenu.show(target, event ? { x: event.clientX, y: event.clientY } : undefined);
171 };
172}