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

OpenInPicker.tsx

361 lines13.0 KB

1import { ThreadDetailsControl } from "./ThreadDetailsControl";
2import {
3 AuthOrchestrationOperateScope,
4 buildRemoteOpenUrl,
5 EditorId,
6 type EnvironmentId,
7 type ResolvedKeybindingsConfig,
8} from "@t3tools/contracts";
9import { T, useGT, useMessages, Var } from "gt-react";
10import { memo, use, useRef } from "react";
11import { BackgroundThreadContext } from "./backgroundThread";
12import { shortcutLabelForCommand } from "../../keybindings";
13import type { FileManagerAction } from "./OpenInPicker.logic";
14import { OPEN_FAVORITE_EDITOR_ATTRIBUTE } from "./OpenInPickerShortcut";
15import { usePreferredEditor } from "../../editorPreferences";
16import { editorLabelForPlatform } from "../../editorLabels";
17import type { MessageResolver } from "../../i18n/messages";
18import {
19 openRemoteEditorUrl,
20 useRemoteCapableEditors,
21 useRemoteOpenHint,
22 useRemoteOpenState,
23} from "../../remoteOpen";
24import { useEnvironment } from "../../state/environments";
25import { ChevronDownIcon, SquareArrowOutUpRightIcon } from "lucide-react";
26​
27import { Group, GroupSeparator } from "../ui/group";
28import {
29 Menu,
30 MenuItem,
31 MenuItemLabel,
32 MenuPopup,
33 MenuShortcut,
34 MenuSub,
35 MenuSubTrigger,
36 MenuSubPopup,
37 MenuTrigger,
38} from "../ui/menu";
39import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
40import { type EditorIconOption, editorIconOptions } from "../editorIcons";
41import { announce } from "~/lib/announce";
42import { cn } from "~/lib/utils";
43import { shellEnvironment } from "~/state/shell";
44import { useAtomCommand } from "~/state/use-atom-command";
45import {
46 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
47 THREAD_DETAILS_PANEL_ICON_CLASS,
48 THREAD_DETAILS_PANEL_LABEL_CLASS,
49 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
50 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
51} from "./threadDetailsPanelStyles";
52import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
53import { useComposerMenuState } from "./useComposerMenuState";
54​
55type OpenInOption = EditorIconOption & { label: string };
56​
57const resolveOpenInOptions = (
58 platform: string,
59 availableEditors: ReadonlyArray<EditorId>,
60 resolve: MessageResolver,
61): ReadonlyArray<OpenInOption> => {
62 const availableEditorSet = new Set(availableEditors);
63 return editorIconOptions(platform)
64 .filter((option) => availableEditorSet.has(option.value))
65 .map((option) => ({
66 ...option,
67 label: editorLabelForPlatform(option.value, platform, resolve),
68 }));
69};
70​
71function getOpenInIconClass(kind: OpenInOption["kind"]) {
72 return cn(kind === "brand" ? "text-foreground opacity-100" : "text-muted-foreground");
74​
75export const OpenInPicker = memo(function OpenInPicker({
76 environmentId,
77 keybindings,
78 availableEditors,
79 openInCwd,
80 openInCwdIsFile = false,
81 presentation = "toolbar",
82 compact = false,
83 enableShortcut = true,
84 displayMode = "toolbar",
85 fileManagerAction = "open",
86}: {
87 environmentId: EnvironmentId;
88 keybindings: ResolvedKeybindingsConfig;
89 availableEditors: ReadonlyArray<EditorId>;
90 openInCwd: string | null;
91 openInCwdIsFile?: boolean;
92 presentation?: "toolbar" | "menu";
93 compact?: boolean;
94 enableShortcut?: boolean;
95 displayMode?: "toolbar" | "panel";
96 fileManagerAction?: FileManagerAction;
97}) {
98 const gt = useGT();
99 const messages = useMessages();
100 const isPanel = displayMode === "panel";
101 const ActionGroup = isPanel ? "div" : Group;
102 const panelAnchorRef = useRef<HTMLDivElement | null>(null);
103 const openInEditorMutation = useAtomCommand(shellEnvironment.openInEditor, "open in editor");
104 const remote = useRemoteOpenState(environmentId);
105 const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
106 const isHostEditorDenied = remote.mode === "local-exec" && !canOperateHost;
107 const canOpenEditor = remote.mode !== "remote-unavailable" && !isHostEditorDenied;
108 const [menuOpen, setMenuOpen] = useComposerMenuState(isHostEditorDenied);
109 const remoteCapableEditors = useRemoteCapableEditors();
110 const [remoteHintSeen, markRemoteHintSeen] = useRemoteOpenHint();
111 const environmentLabel = useEnvironment(environmentId)?.label ?? null;
112 // Remote editors run on the viewing machine; only desktop can probe that PATH.
113 const effectiveEditors = remote.mode === "local-exec" ? availableEditors : remoteCapableEditors;
114 const [preferredEditor, setPreferredEditor] = usePreferredEditor(effectiveEditors);
115 const isEditorUnavailable = (editor: EditorId | null) =>
116 editor === "file-manager" && fileManagerAction === "unavailable";
117​
118 const openInEditor = async (editorId: EditorId | null): Promise<boolean> => {
119 if (!openInCwd) return false;
120 const editor = editorId ?? preferredEditor;
121 if (!editor || isEditorUnavailable(editor)) return false;
122 if (remote.mode === "remote-unavailable") return false;
123 if (remote.mode === "remote-links") {
124 const url = buildRemoteOpenUrl({
125 editor,
126 ...remote.host,
127 absolutePath: openInCwd,
128 isFile: openInCwdIsFile,
129 });
130 if (url === undefined) return false;
131 // Only record hint-seen/preferred when the shell actually accepted
132 // the URL (an older desktop build can refuse the editor scheme).
133 const opened = await openRemoteEditorUrl(url);
134 if (!opened) return false;
135 markRemoteHintSeen();
136 setPreferredEditor(editor);
137 return true;
138 }
139 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
140 const result = openInEditorMutation({
141 environmentId,
142 input: {
143 cwd: openInCwd,
144 editor,
145 ...(fileManagerAction === "reveal" && editor === "file-manager" ? { reveal: true } : {}),
146 },
147 });
148 setPreferredEditor(editor);
149 return (await result)._tag === "Success";
150 };
151​
152 const openFavoriteEditorShortcutLabel = shortcutLabelForCommand(
153 keybindings,
154 "editor.openFavorite",
155 );
156​
157 const backgroundThread = use(BackgroundThreadContext);
158 const options = resolveOpenInOptions(navigator.platform, effectiveEditors, messages);
159 const primaryOption = options.find(({ value }) => value === preferredEditor) ?? null;
160 const primaryLabel = isPanel
161 ? primaryOption
162 ? gt("Open in {editor}", { editor: primaryOption.label })
163 : gt("Open in editor")
164 : gt("Open", { $context: "verb, opens the project in the preferred editor" });
165​
166 const unavailableReason =
167 remote.mode === "remote-unavailable"
168 ? environmentLabel !== null
169 ? gt("No SSH route to {environment}", { environment: environmentLabel })
170 : gt("No SSH route to this machine")
171 : remote.mode === "remote-links" && options.length === 0
172 ? environmentLabel !== null
173 ? gt("Open from a computer to edit on {environment}", { environment: environmentLabel })
174 : gt("Open from a computer to edit on this machine")
175 : null;
176​
177 const editorItems = (
178 <>
179 {unavailableReason !== null ? (
180 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
181 {unavailableReason}
182 </MenuItem>
183 ) : (
184 <>
185 {options.length === 0 && (
186 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
187 <T>No installed editors found</T>
188 </MenuItem>
189 )}
190 {options.map(({ label, Icon, value, kind }) => (
191 <MenuItem
192 density={presentation === "menu" ? "touch" : "default"}
193 disabled={
194 !openInCwd ||
195 !canOpenEditor ||
196 (presentation === "menu" && isEditorUnavailable(value))
197 }
198 key={value}
199 onClick={() => {
200 if (presentation === "menu") {
201 void openInEditor(value);
202 } else {
203 setPreferredEditor(value);
204 }
205 }}
206 >
207 <Icon aria-hidden="true" className={getOpenInIconClass(kind)} />
208 <MenuItemLabel>{label}</MenuItemLabel>
209 {value === preferredEditor && openFavoriteEditorShortcutLabel && (
210 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
211 )}
212 </MenuItem>
213 ))}
214 {remote.mode === "remote-links" && !remoteHintSeen && (
215 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
216 {environmentLabel !== null
217 ? gt("Opens over SSH. Needs your key on {environment}", {
218 environment: environmentLabel,
219 })
220 : gt("Opens over SSH. Needs your key on this machine")}
221 </MenuItem>
222 )}
223 </>
224 )}
225 </>
226 );
227 if (presentation === "menu") {
228 return (
229 <>
230 {primaryOption && (
231 <MenuItem
232 density={presentation === "menu" ? "touch" : "default"}
233 disabled={!openInCwd || !canOpenEditor || isEditorUnavailable(preferredEditor)}
234 onClick={() => openInEditor(preferredEditor)}
235 >
236 <primaryOption.Icon className={cn("size-4", getOpenInIconClass(primaryOption.kind))} />
237 <MenuItemLabel>
238 <T>
239 Open in <Var>{primaryOption.label}</Var>
240 </T>
241 </MenuItemLabel>
242 {openFavoriteEditorShortcutLabel && (
243 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
244 )}
245 </MenuItem>
246 )}
247 <MenuSub>
248 <MenuSubTrigger density="touch" disabled={isHostEditorDenied}>
249 <SquareArrowOutUpRightIcon className="size-4" />
250 <MenuItemLabel>
251 <T>Open in…</T>
252 </MenuItemLabel>
253 </MenuSubTrigger>
254 <MenuSubPopup>{editorItems}</MenuSubPopup>
255 </MenuSub>
256 </>
257 );
258 }
259​
260 const primaryControlLabel = compact ? gt("Open file in preferred editor") : primaryLabel;
261 const primaryControl = (
262 <ThreadDetailsControl
263 aria-label={primaryControlLabel}
264 // Tooltip replaces the button data-slot, so toolbar theming needs a separate hook.
265 data-toolbar-control=""
266 size={isPanel ? "sm" : "xs"}
267 variant={isPanel ? "ghost" : "outline"}
268 part="primary"
269 panel={isPanel}
270 disabled={
271 !preferredEditor || !openInCwd || !canOpenEditor || isEditorUnavailable(preferredEditor)
272 }
273 {...(enableShortcut && !backgroundThread ? { [OPEN_FAVORITE_EDITOR_ATTRIBUTE]: "" } : {})}
274 onClick={() => {
275 if (!preferredEditor) return;
276 const label = editorLabelForPlatform(preferredEditor, navigator.platform);
277 void openInEditor(preferredEditor).then((opened) => {
278 if (opened) announce(gt("Opened in {editor}", { editor: label }));
279 });
280 }}
281 >
282 {primaryOption?.Icon ? (
283 <primaryOption.Icon
284 aria-hidden="true"
285 className={cn(
286 isPanel ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3.5",
287 getOpenInIconClass(primaryOption.kind),
288 )}
289 />
290 ) : isPanel ? (
291 <SquareArrowOutUpRightIcon aria-hidden="true" className={THREAD_DETAILS_PANEL_ICON_CLASS} />
292 ) : null}
293 <span
294 className={cn(
295 compact
296 ? "sr-only"
297 : "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
298 isPanel && cn("not-sr-only ml-0 min-w-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
299 )}
300 >
301 {primaryLabel}
302 </span>
303 </ThreadDetailsControl>
304 );
305​
306 return (
307 <ActionGroup
308 aria-label={gt("Open in editor")}
309 role="group"
310 {...(isPanel
311 ? { className: THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, ref: panelAnchorRef }
312 : {})}
313 >
314 <Tooltip>
315 <TooltipTrigger render={primaryControl} />
316 <TooltipPopup side="top">{primaryControlLabel}</TooltipPopup>
317 </Tooltip>
318 {isPanel ? (
319 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
320 ) : (
321 <GroupSeparator {...(!compact ? { className: "hidden @3xl/header-actions:block" } : {})} />
322 )}
323 <Menu open={menuOpen} onOpenChange={setMenuOpen}>
324 <Tooltip>
325 <TooltipTrigger
326 render={
327 <MenuTrigger
328 disabled={isHostEditorDenied}
329 render={
330 <ThreadDetailsControl
331 aria-label={gt("Choose editor")}
332 data-toolbar-control=""
333 size={isPanel ? "sm" : "icon-xs"}
334 variant={isPanel ? "ghost" : "outline"}
335 part="secondary"
336 panel={isPanel}
337 />
338 }
339 />
340 }
341 >
342 <ChevronDownIcon
343 aria-hidden="true"
344 className={isPanel ? THREAD_DETAILS_PANEL_CHEVRON_CLASS : "size-4"}
345 />
346 </TooltipTrigger>
347 <TooltipPopup side="top">
348 <T>Choose editor</T>
349 </TooltipPopup>
350 </Tooltip>
351 <MenuPopup
352 align="end"
353 {...(isPanel ? { anchor: panelAnchorRef } : {})}
354 className={isPanel ? "w-(--anchor-width)" : undefined}
355 >
356 {editorItems}
357 </MenuPopup>
358 </Menu>
359 </ActionGroup>
360 );
361});