The best way to control Claude Code, Codex and more from any computer or phone

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