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

fileContextMenu.ts

178 lines6.3 KB

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