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

OpenInPicker.tsx

462 lines13.6 KB

1import { ThreadDetailsControl } from "./ThreadDetailsControl";
2import {
3 AuthOrchestrationOperateScope,
4 buildRemoteOpenUrl,
5 EditorId,
6 type EnvironmentId,
7 type ResolvedKeybindingsConfig,
8} from "@t3tools/contracts";
9import { memo, useEffect, useRef } from "react";
10import { isOpenFavoriteEditorShortcut, shortcutLabelForCommand } from "../../keybindings";
11import { usePreferredEditor } from "../../editorPreferences";
12import { editorLabelForPlatform } from "../../editorLabels";
13import {
14 openRemoteEditorUrl,
15 useRemoteCapableEditors,
16 useRemoteOpenHint,
17 useRemoteOpenState,
18} from "../../remoteOpen";
19import { useEnvironment } from "../../state/environments";
20import { ChevronDownIcon, FolderClosedIcon, SquareArrowOutUpRightIcon } from "lucide-react";
21​
22import { Group, GroupSeparator } from "../ui/group";
23import {
24 Menu,
25 MenuItem,
26 MenuItemLabel,
27 MenuPopup,
28 MenuShortcut,
29 MenuSub,
30 MenuSubTrigger,
31 MenuSubPopup,
32 MenuTrigger,
33} from "../ui/menu";
34import {
35 AntigravityIcon,
36 CursorIcon,
37 FileExplorerIcon,
38 FinderIcon,
39 Icon,
40 KiroIcon,
41 TraeIcon,
42 VisualStudioCode,
43 VisualStudioCodeInsiders,
44 VSCodium,
45 Zed,
46} from "../Icons";
47import {
48 AquaIcon,
49 CLionIcon,
50 DataGripIcon,
51 DataSpellIcon,
52 GoLandIcon,
53 IntelliJIdeaIcon,
54 PhpStormIcon,
55 PyCharmIcon,
56 RiderIcon,
57 RubyMineIcon,
58 RustRoverIcon,
59 WebStormIcon,
60} from "../JetBrainsIcons";
61import { announce } from "~/lib/announce";
62import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
63import { shellEnvironment } from "~/state/shell";
64import { useAtomCommand } from "~/state/use-atom-command";
65import {
66 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
67 THREAD_DETAILS_PANEL_ICON_CLASS,
68 THREAD_DETAILS_PANEL_LABEL_CLASS,
69 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
70 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
71} from "./threadDetailsPanelStyles";
72import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
73import { useComposerMenuState } from "./useComposerMenuState";
74​
75type OpenInOption = {
76 label: string;
77 Icon: Icon;
78 value: EditorId;
79 kind: "brand" | "generic";
80};
81​
82const resolveOpenInOptions = (platform: string, availableEditors: ReadonlyArray<EditorId>) => {
83 const baseOptions: ReadonlyArray<Omit<OpenInOption, "label">> = [
84 {
85 Icon: CursorIcon,
86 value: "cursor",
87 kind: "brand",
88 },
89 {
90 Icon: TraeIcon,
91 value: "trae",
92 kind: "brand",
93 },
94 {
95 Icon: KiroIcon,
96 value: "kiro",
97 kind: "brand",
98 },
99 {
100 Icon: VisualStudioCode,
101 value: "vscode",
102 kind: "brand",
103 },
104 {
105 Icon: VisualStudioCodeInsiders,
106 value: "vscode-insiders",
107 kind: "brand",
108 },
109 {
110 Icon: VSCodium,
111 value: "vscodium",
112 kind: "brand",
113 },
114 {
115 Icon: Zed,
116 value: "zed",
117 kind: "brand",
118 },
119 {
120 Icon: AntigravityIcon,
121 value: "antigravity",
122 kind: "brand",
123 },
124 {
125 Icon: IntelliJIdeaIcon,
126 value: "idea",
127 kind: "brand",
128 },
129 {
130 Icon: AquaIcon,
131 value: "aqua",
132 kind: "brand",
133 },
134 {
135 Icon: CLionIcon,
136 value: "clion",
137 kind: "brand",
138 },
139 {
140 Icon: DataGripIcon,
141 value: "datagrip",
142 kind: "brand",
143 },
144 {
145 Icon: DataSpellIcon,
146 value: "dataspell",
147 kind: "brand",
148 },
149 {
150 Icon: GoLandIcon,
151 value: "goland",
152 kind: "brand",
153 },
154 {
155 Icon: PhpStormIcon,
156 value: "phpstorm",
157 kind: "brand",
158 },
159 {
160 Icon: PyCharmIcon,
161 value: "pycharm",
162 kind: "brand",
163 },
164 {
165 Icon: RiderIcon,
166 value: "rider",
167 kind: "brand",
168 },
169 {
170 Icon: RubyMineIcon,
171 value: "rubymine",
172 kind: "brand",
173 },
174 {
175 Icon: RustRoverIcon,
176 value: "rustrover",
177 kind: "brand",
178 },
179 {
180 Icon: WebStormIcon,
181 value: "webstorm",
182 kind: "brand",
183 },
184 {
185 Icon: isMacPlatform(platform)
186 ? FinderIcon
187 : isWindowsPlatform(platform)
188 ? FileExplorerIcon
189 : FolderClosedIcon,
190 value: "file-manager",
191 kind: isMacPlatform(platform) || isWindowsPlatform(platform) ? "brand" : "generic",
192 },
193 ];
194 const availableEditorSet = new Set(availableEditors);
195 return baseOptions
196 .filter((option) => availableEditorSet.has(option.value))
197 .map((option) => ({ ...option, label: editorLabelForPlatform(option.value, platform) }));
198};
199​
200function getOpenInIconClass(kind: OpenInOption["kind"]) {
201 return cn(kind === "brand" ? "text-foreground opacity-100" : "text-muted-foreground");
203​
204export const OpenInPicker = memo(function OpenInPicker({
205 environmentId,
206 keybindings,
207 availableEditors,
208 openInCwd,
209 openInCwdIsFile = false,
210 presentation = "toolbar",
211 compact = false,
212 enableShortcut = true,
213 displayMode = "toolbar",
214 revealFileManager = false,
215}: {
216 environmentId: EnvironmentId;
217 keybindings: ResolvedKeybindingsConfig;
218 availableEditors: ReadonlyArray<EditorId>;
219 openInCwd: string | null;
220 openInCwdIsFile?: boolean;
221 presentation?: "toolbar" | "menu";
222 compact?: boolean;
223 enableShortcut?: boolean;
224 displayMode?: "toolbar" | "panel";
225 revealFileManager?: boolean;
226}) {
227 const isPanel = displayMode === "panel";
228 const ActionGroup = isPanel ? "div" : Group;
229 const panelAnchorRef = useRef<HTMLDivElement | null>(null);
230 const openInEditorMutation = useAtomCommand(shellEnvironment.openInEditor, "open in editor");
231 const remote = useRemoteOpenState(environmentId);
232 const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
233 const isHostEditorDenied = remote.mode === "local-exec" && !canOperateHost;
234 const canOpenEditor = remote.mode !== "remote-unavailable" && !isHostEditorDenied;
235 const [menuOpen, setMenuOpen] = useComposerMenuState(isHostEditorDenied);
236 const remoteCapableEditors = useRemoteCapableEditors();
237 const [remoteHintSeen, markRemoteHintSeen] = useRemoteOpenHint();
238 const environmentLabel = useEnvironment(environmentId)?.label ?? "this machine";
239 // Remote editors run on the viewing machine; only desktop can probe that PATH.
240 const effectiveEditors = remote.mode === "local-exec" ? availableEditors : remoteCapableEditors;
241 const [preferredEditor, setPreferredEditor] = usePreferredEditor(effectiveEditors);
242​
243 const openInEditor = async (editorId: EditorId | null): Promise<boolean> => {
244 if (!openInCwd) return false;
245 const editor = editorId ?? preferredEditor;
246 if (!editor) return false;
247 if (remote.mode === "remote-unavailable") return false;
248 if (remote.mode === "remote-links") {
249 const url = buildRemoteOpenUrl({
250 editor,
251 ...remote.host,
252 absolutePath: openInCwd,
253 isFile: openInCwdIsFile,
254 });
255 if (url === undefined) return false;
256 // Only record hint-seen/preferred when the shell actually accepted
257 // the URL (an older desktop build can refuse the editor scheme).
258 const opened = await openRemoteEditorUrl(url);
259 if (!opened) return false;
260 markRemoteHintSeen();
261 setPreferredEditor(editor);
262 return true;
263 }
264 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
265 const result = openInEditorMutation({
266 environmentId,
267 input: {
268 cwd: openInCwd,
269 editor,
270 ...(revealFileManager && editor === "file-manager" ? { reveal: true } : {}),
271 },
272 });
273 setPreferredEditor(editor);
274 return (await result)._tag === "Success";
275 };
276​
277 const openFavoriteEditorShortcutLabel = shortcutLabelForCommand(
278 keybindings,
279 "editor.openFavorite",
280 );
281​
282 useEffect(() => {
283 if (!enableShortcut || !canOpenEditor) return;
284 const handler = (e: globalThis.KeyboardEvent) => {
285 if (e.defaultPrevented || !isOpenFavoriteEditorShortcut(e, keybindings)) return;
286 if (!openInCwd) return;
287 if (!preferredEditor) return;
288 if (
289 remote.mode === "local-exec" &&
290 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
291 )
292 return;
293​
294 e.preventDefault();
295 const label = editorLabelForPlatform(preferredEditor, navigator.platform);
296 void openInEditor(preferredEditor).then((opened) => {
297 if (opened) announce(`Opened in ${label}`);
298 });
299 };
300 window.addEventListener("keydown", handler, true);
301 return () => window.removeEventListener("keydown", handler, true);
302 }, [
303 canOpenEditor,
304 enableShortcut,
305 environmentId,
306 keybindings,
307 openInCwd,
308 openInEditor,
309 preferredEditor,
310 remote.mode,
311 ]);
312 // Derive after the shortcut effect to preserve the editor list's compiler cache.
313 const options = resolveOpenInOptions(navigator.platform, effectiveEditors);
314 const primaryOption = options.find(({ value }) => value === preferredEditor) ?? null;
315 const primaryLabel = isPanel ? `Open in ${primaryOption?.label ?? "editor"}` : "Open";
316​
317 const editorItems = (
318 <>
319 {remote.mode === "remote-unavailable" ? (
320 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
321 No SSH route to {environmentLabel}
322 </MenuItem>
323 ) : (
324 <>
325 {options.length === 0 && (
326 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
327 No installed editors found
328 </MenuItem>
329 )}
330 {options.map(({ label, Icon, value, kind }) => (
331 <MenuItem
332 density={presentation === "menu" ? "touch" : "default"}
333 disabled={!openInCwd || !canOpenEditor}
334 key={value}
335 onClick={() => {
336 if (presentation === "menu") {
337 void openInEditor(value);
338 } else {
339 setPreferredEditor(value);
340 }
341 }}
342 >
343 <Icon aria-hidden="true" className={getOpenInIconClass(kind)} />
344 <MenuItemLabel>{label}</MenuItemLabel>
345 {value === preferredEditor && openFavoriteEditorShortcutLabel && (
346 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
347 )}
348 </MenuItem>
349 ))}
350 {remote.mode === "remote-links" && !remoteHintSeen && (
351 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
352 Opens over SSH. Needs your key on {environmentLabel}
353 </MenuItem>
354 )}
355 </>
356 )}
357 </>
358 );
359 if (presentation === "menu") {
360 return (
361 <>
362 {primaryOption && (
363 <MenuItem
364 density={presentation === "menu" ? "touch" : "default"}
365​
366 disabled={!openInCwd || !canOpenEditor}
367 onClick={() => openInEditor(preferredEditor)}
368 >
369 <primaryOption.Icon className={cn("size-4", getOpenInIconClass(primaryOption.kind))} />
370 <MenuItemLabel>Open in {primaryOption.label}</MenuItemLabel>
371 {openFavoriteEditorShortcutLabel && (
372 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
373 )}
374 </MenuItem>
375 )}
376 <MenuSub>
377 <MenuSubTrigger density="touch" disabled={isHostEditorDenied}>
378 <SquareArrowOutUpRightIcon className="size-4" />
379 <MenuItemLabel>Open in…</MenuItemLabel>
380 </MenuSubTrigger>
381 <MenuSubPopup>{editorItems}</MenuSubPopup>
382 </MenuSub>
383 </>
384 );
385 }
386​
387 return (
388 <ActionGroup
389 aria-label="Open in editor"
390 role="group"
391 {...(isPanel
392 ? { className: THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, ref: panelAnchorRef }
393 : {})}
394 >
395 <ThreadDetailsControl
396 aria-label={compact ? "Open file in preferred editor" : primaryLabel}
397 size={isPanel ? "sm" : "xs"}
398 variant={isPanel ? "ghost" : "outline"}
399 part="primary"
400 panel={isPanel}
401 disabled={!preferredEditor || !openInCwd || !canOpenEditor}
402 onClick={() => openInEditor(preferredEditor)}
403 >
404 {primaryOption?.Icon ? (
405 <primaryOption.Icon
406 aria-hidden="true"
407 className={cn(
408 isPanel ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3.5",
409 getOpenInIconClass(primaryOption.kind),
410 )}
411 />
412 ) : isPanel ? (
413 <SquareArrowOutUpRightIcon
414 aria-hidden="true"
415 className={THREAD_DETAILS_PANEL_ICON_CLASS}
416 />
417 ) : null}
418 <span
419 className={cn(
420 compact
421 ? "sr-only"
422 : "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
423 isPanel && cn("not-sr-only ml-0 min-w-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
424 )}
425 >
426 {primaryLabel}
427 </span>
428 </ThreadDetailsControl>
429 {isPanel ? (
430 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
431 ) : (
432 <GroupSeparator {...(!compact ? { className: "hidden @3xl/header-actions:block" } : {})} />
433 )}
434 <Menu open={menuOpen} onOpenChange={setMenuOpen}>
435 <MenuTrigger
436 disabled={isHostEditorDenied}
437 render={
438 <ThreadDetailsControl
439 aria-label="Choose editor"
440 size={isPanel ? "sm" : "icon-xs"}
441 variant={isPanel ? "ghost" : "outline"}
442 part="secondary"
443 panel={isPanel}
444 />
445 }
446 >
447 <ChevronDownIcon
448 aria-hidden="true"
449 className={isPanel ? THREAD_DETAILS_PANEL_CHEVRON_CLASS : "size-4"}
450 />
451 </MenuTrigger>
452 <MenuPopup
453 align="end"
454 {...(isPanel ? { anchor: panelAnchorRef } : {})}
455 className={isPanel ? "w-(--anchor-width)" : undefined}
456 >
457 {editorItems}
458 </MenuPopup>
459 </Menu>
460 </ActionGroup>
461 );
462});