Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

fileContextMenu.ts

247 lines8.4 KB

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