Open History to see the last commit
1import {
2 AuthOrchestrationOperateScope,
3 buildRemoteOpenUrl,
4 EDITORS,
5 type ContextMenuItem,
6 type EditorId,
7 type EnvironmentId,
8 type ContextMenuSource,
9} from "@t3tools/contracts";
10
11import { contextMenuSourceOf } from "./contextMenuSource";
12import { joinDiffFilePath, resolveDiffPathForWorkspace } from "./diffFileActions";
13import {
14 revealInFileExplorerLabelForKind,
15 revealInFileExplorerLabelForOs,
16} from "~/components/preview/fileExplorerLabel";
17import { useEditorMenuIcons } from "./editorMenuIcons";
18import { readLocalApi } from "./localApi";
19import {
20 openRemoteEditorUrl,
21 useRemoteCapableEditors,
22 useRemoteOpenResolution,
23} from "./remoteOpen";
24import { serverEnvironment } from "./state/server";
25import { useEnvironmentScope } from "./state/session";
26import { shellEnvironment } from "./state/shell";
27import { useAtomCommand } from "./state/use-atom-command";
28import { toastManager } from "./components/ui/toast";
29import { useAtomValue } from "@effect/atom-react";
30import { msg, useMessages } from "gt-react";
31
32import type { MessageResolver } from "./i18n/messages";
33
34export type FileContextMenuAction =
35 | "reveal-in-folder"
36 | "open"
37 /** Submenu parent; never the activated id. */
38 | "open-with"
39 | `editor:${EditorId}`;
40
41export interface FileContextMenuTarget {
42 readonly environmentId: EnvironmentId | null;
43 /** Repo- or workspace-relative file path, as shown in diffs. */
44 readonly filePath: string;
45 readonly workspaceRoot: string | undefined;
46 readonly repositoryRoot?: string | undefined;
47 readonly isDirectory?: boolean;
48}
49
50export function resolveFileContextMenuAbsolutePath(target: FileContextMenuTarget): string | null {
51 const workspaceFilePath = resolveDiffPathForWorkspace({
52 filePath: target.filePath,
53 workspaceRoot: target.workspaceRoot,
54 repositoryRoot: target.repositoryRoot,
55 });
56 if (workspaceFilePath === null) return null;
57 if (target.workspaceRoot === undefined) {
58 return workspaceFilePath.startsWith("/") || /^[a-zA-Z]:/.test(workspaceFilePath)
59 ? workspaceFilePath
60 : null;
61 }
62 return joinDiffFilePath(target.workspaceRoot, workspaceFilePath);
63}
64
65const EDITOR_LABEL_BY_ID = new Map(EDITORS.map((editor) => [editor.id, editor.label]));
66
67export interface FileContextMenuCapabilities {
68 readonly revealLabel: string | undefined;
69 readonly canOpenDefault: boolean;
70 readonly editorIds: ReadonlyArray<EditorId>;
71}
72
73function buildFileContextMenuItems(input: {
74 readonly hasAbsolutePath: boolean;
75 readonly capabilities: FileContextMenuCapabilities;
76 readonly editorIcons: ReadonlyMap<EditorId, string>;
77 readonly resolve: MessageResolver;
78}): readonly ContextMenuItem<FileContextMenuAction>[] {
79 if (!input.hasAbsolutePath) return [];
80 const items: ContextMenuItem<FileContextMenuAction>[] = [];
81 if (input.capabilities.canOpenDefault) {
82 items.push({
83 id: "open",
84 label: input.resolve(msg({ context: "verb, opens a file" })`Open`),
85 icon: "pencil",
86 });
87 }
88 if (input.capabilities.revealLabel !== undefined) {
89 items.push({
90 id: "reveal-in-folder",
91 label: input.capabilities.revealLabel,
92 icon: "folder-tree",
93 });
94 }
95 const editorIds = input.capabilities.editorIds.filter((id) => id !== "file-manager");
96 if (editorIds.length > 0) {
97 items.push({
98 id: "open-with",
99 label: input.resolve(msg("Open with")),
100 children: editorIds.map((editorId) => {
101 const iconImage = input.editorIcons.get(editorId);
102 return {
103 id: `editor:${editorId}` as FileContextMenuAction,
104 label: EDITOR_LABEL_BY_ID.get(editorId) ?? editorId,
105 ...(iconImage === undefined ? {} : { iconImage }),
106 };
107 }),
108 });
109 }
110 return items;
111}
112
113export function useFileContextMenu(environmentId: EnvironmentId | null) {
114 const openInEditor = useAtomCommand(shellEnvironment.openInEditor, { reportFailure: false });
115 const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
116 const resolve = useMessages();
117
118 const remoteOpen = useRemoteOpenResolution(environmentId);
119 const remoteCapableEditors = useRemoteCapableEditors();
120 const mode = environmentId !== null && remoteOpen.isResolved ? remoteOpen.state.mode : null;
121 // Shell actions run on the server host, which is the viewer's machine only in local-exec.
122 const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
123 const isLocalExec = mode === "local-exec" && canOperateHost;
124 const remoteHost = remoteOpen.state.mode === "remote-links" ? remoteOpen.state.host : null;
125
126 const availableEditors = isLocalExec
127 ? (serverConfig?.availableEditors ?? [])
128 : mode === "remote-links"
129 ? remoteCapableEditors
130 : [];
131 const capabilities: FileContextMenuCapabilities = {
132 // WSL can reveal in Windows Explorer despite reporting Linux; use server wording.
133 revealLabel:
134 isLocalExec &&
135 serverConfig?.shellRevealInFileManager === true &&
136 serverConfig.availableEditors.includes("file-manager")
137 ? serverConfig.shellRevealInFileManagerKind === undefined
138 ? revealInFileExplorerLabelForOs(serverConfig.environment.platform.os, resolve)
139 : revealInFileExplorerLabelForKind(serverConfig.shellRevealInFileManagerKind, resolve)
140 : undefined,
141 canOpenDefault: isLocalExec && availableEditors.includes("file-manager"),
142 editorIds: availableEditors,
143 };
144 const editorIcons = useEditorMenuIcons(availableEditors);
145
146 const editorFailureTitle = (editor: EditorId) =>
147 resolve(msg`Could not open in ${{ editor: EDITOR_LABEL_BY_ID.get(editor) ?? editor }}`);
148
149 const activate = async (
150 action: FileContextMenuAction,
151 target: FileContextMenuTarget,
152 ): Promise<void> => {
153 const absolutePath = resolveFileContextMenuAbsolutePath(target);
154 if (absolutePath === null || environmentId === null) return;
155
156 const reveal = action === "reveal-in-folder";
157 const editor =
158 action === "open" || reveal
159 ? ("file-manager" as const)
160 : (action.slice("editor:".length) as EditorId);
161 if (action === "open" && !capabilities.canOpenDefault) return;
162 if (reveal && capabilities.revealLabel === undefined) return;
163 if (action !== "open" && !reveal && !capabilities.editorIds.includes(editor)) return;
164
165 if (remoteHost !== null) {
166 const url = buildRemoteOpenUrl({
167 editor,
168 ...remoteHost,
169 absolutePath,
170 isFile: target.isDirectory !== true,
171 });
172 if (url !== undefined && (await openRemoteEditorUrl(url))) return;
173 toastManager.add({
174 type: "error",
175 title: editorFailureTitle(editor),
176 description: absolutePath,
177 });
178 return;
179 }
180
181 const result = await openInEditor({
182 environmentId,
183 input: { cwd: absolutePath, editor, ...(reveal ? { reveal: true } : {}) },
184 });
185 if (result._tag !== "Failure") return;
186 toastManager.add({
187 type: "error",
188 title:
189 action === "open"
190 ? resolve(msg("Could not open file"))
191 : reveal
192 ? resolve(msg("Unable to reveal file"))
193 : editorFailureTitle(editor),
194 description: absolutePath,
195 });
196 };
197
198 const show = async (
199 target: FileContextMenuTarget,
200 position?: { x: number; y: number },
201 source?: ContextMenuSource,
202 ): Promise<void> => {
203 const api = readLocalApi();
204 const items = buildFileContextMenuItems({
205 hasAbsolutePath: resolveFileContextMenuAbsolutePath(target) !== null,
206 capabilities,
207 editorIcons,
208 resolve,
209 });
210 if (items.length === 0 || api === undefined) return;
211 const clicked = await api.contextMenu.show(items, position, source);
212 if (clicked === null) return;
213 await activate(clicked as FileContextMenuAction, target);
214 };
215
216 return {
217 buildItems: (target: FileContextMenuTarget) =>
218 buildFileContextMenuItems({
219 hasAbsolutePath: resolveFileContextMenuAbsolutePath(target) !== null,
220 capabilities,
221 editorIcons,
222 resolve,
223 }),
224 capabilities,
225 activate,
226 show,
227 };
228}
229
230export function useFileContextMenuHandler(environmentId: EnvironmentId | null) {
231 const contextMenu = useFileContextMenu(environmentId);
232 return (
233 target: FileContextMenuTarget,
234 event?: Pick<MouseEvent, "type" | "button" | "detail" | "clientX" | "clientY">,
235 ) => {
236 void contextMenu.show(
237 target,
238 event ? { x: event.clientX, y: event.clientY } : undefined,
239 event ? contextMenuSourceOf(event) : undefined,
240 );
241 };
242}