Open History to see the last commit
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");
202}
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 mode ignores the server's PATH probe: what matters is what runs on
240 // the viewing machine, which only the desktop app can probe.
241 const effectiveEditors = remote.mode === "local-exec" ? availableEditors : remoteCapableEditors;
242 const [preferredEditor, setPreferredEditor] = usePreferredEditor(effectiveEditors);
243
244 const openInEditor = async (editorId: EditorId | null): Promise<boolean> => {
245 if (!openInCwd) return false;
246 const editor = editorId ?? preferredEditor;
247 if (!editor) return false;
248 if (remote.mode === "remote-unavailable") return false;
249 if (remote.mode === "remote-links") {
250 const url = buildRemoteOpenUrl({
251 editor,
252 ...remote.host,
253 absolutePath: openInCwd,
254 isFile: openInCwdIsFile,
255 });
256 if (url === undefined) return false;
257 // Only record hint-seen/preferred when the shell actually accepted
258 // the URL (an older desktop build can refuse the editor scheme).
259 const opened = await openRemoteEditorUrl(url);
260 if (!opened) return false;
261 markRemoteHintSeen();
262 setPreferredEditor(editor);
263 return true;
264 }
265 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
266 const result = openInEditorMutation({
267 environmentId,
268 input: {
269 cwd: openInCwd,
270 editor,
271 ...(revealFileManager && editor === "file-manager" ? { reveal: true } : {}),
272 },
273 });
274 setPreferredEditor(editor);
275 return (await result)._tag === "Success";
276 };
277
278 const openFavoriteEditorShortcutLabel = shortcutLabelForCommand(
279 keybindings,
280 "editor.openFavorite",
281 );
282
283 useEffect(() => {
284 if (!enableShortcut || !canOpenEditor) return;
285 const handler = (e: globalThis.KeyboardEvent) => {
286 if (e.defaultPrevented || !isOpenFavoriteEditorShortcut(e, keybindings)) return;
287 if (!openInCwd) return;
288 if (!preferredEditor) return;
289 if (
290 remote.mode === "local-exec" &&
291 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
292 )
293 return;
294
295 e.preventDefault();
296 const label = editorLabelForPlatform(preferredEditor, navigator.platform);
297 void openInEditor(preferredEditor).then((opened) => {
298 if (opened) announce(`Opened in ${label}`);
299 });
300 };
301 window.addEventListener("keydown", handler, true);
302 return () => window.removeEventListener("keydown", handler, true);
303 }, [
304 canOpenEditor,
305 enableShortcut,
306 environmentId,
307 keybindings,
308 openInCwd,
309 openInEditor,
310 preferredEditor,
311 remote.mode,
312 ]);
313 // Derived after the shortcut effect so the compiler can cache the resolved editor list.
314 const options = resolveOpenInOptions(navigator.platform, effectiveEditors);
315 const primaryOption = options.find(({ value }) => value === preferredEditor) ?? null;
316 const primaryLabel = isPanel ? `Open in ${primaryOption?.label ?? "editor"}` : "Open";
317
318 const editorItems = (
319 <>
320 {remote.mode === "remote-unavailable" ? (
321 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
322 No SSH route to {environmentLabel}
323 </MenuItem>
324 ) : (
325 <>
326 {options.length === 0 && (
327 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
328 No installed editors found
329 </MenuItem>
330 )}
331 {options.map(({ label, Icon, value, kind }) => (
332 <MenuItem
333 density={presentation === "menu" ? "touch" : "default"}
334 disabled={!openInCwd || !canOpenEditor}
335 key={value}
336 onClick={() => {
337 if (presentation === "menu") {
338 void openInEditor(value);
339 } else {
340 setPreferredEditor(value);
341 }
342 }}
343 >
344 <Icon aria-hidden="true" className={getOpenInIconClass(kind)} />
345 <MenuItemLabel>{label}</MenuItemLabel>
346 {value === preferredEditor && openFavoriteEditorShortcutLabel && (
347 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
348 )}
349 </MenuItem>
350 ))}
351 {remote.mode === "remote-links" && !remoteHintSeen && (
352 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
353 Opens over SSH. Needs your key on {environmentLabel}
354 </MenuItem>
355 )}
356 </>
357 )}
358 </>
359 );
360 if (presentation === "menu") {
361 return (
362 <>
363 {primaryOption && (
364 <MenuItem
365 density={presentation === "menu" ? "touch" : "default"}
366
367 disabled={!openInCwd || !canOpenEditor}
368 onClick={() => openInEditor(preferredEditor)}
369 >
370 <primaryOption.Icon className={cn("size-4", getOpenInIconClass(primaryOption.kind))} />
371 <MenuItemLabel>Open in {primaryOption.label}</MenuItemLabel>
372 {openFavoriteEditorShortcutLabel && (
373 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
374 )}
375 </MenuItem>
376 )}
377 <MenuSub>
378 <MenuSubTrigger density="touch" disabled={isHostEditorDenied}>
379 <SquareArrowOutUpRightIcon className="size-4" />
380 <MenuItemLabel>Open in…</MenuItemLabel>
381 </MenuSubTrigger>
382 <MenuSubPopup>{editorItems}</MenuSubPopup>
383 </MenuSub>
384 </>
385 );
386 }
387
388 return (
389 <ActionGroup
390 aria-label="Open in editor"
391 role="group"
392 {...(isPanel
393 ? { className: THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, ref: panelAnchorRef }
394 : {})}
395 >
396 <ThreadDetailsControl
397 aria-label={compact ? "Open file in preferred editor" : primaryLabel}
398 size={isPanel ? "sm" : "xs"}
399 variant={isPanel ? "ghost" : "outline"}
400 part="primary"
401 panel={isPanel}
402 disabled={!preferredEditor || !openInCwd || !canOpenEditor}
403 onClick={() => openInEditor(preferredEditor)}
404 >
405 {primaryOption?.Icon ? (
406 <primaryOption.Icon
407 aria-hidden="true"
408 className={cn(
409 isPanel ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3.5",
410 getOpenInIconClass(primaryOption.kind),
411 )}
412 />
413 ) : isPanel ? (
414 <SquareArrowOutUpRightIcon
415 aria-hidden="true"
416 className={THREAD_DETAILS_PANEL_ICON_CLASS}
417 />
418 ) : null}
419 <span
420 className={cn(
421 compact
422 ? "sr-only"
423 : "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
424 isPanel && cn("not-sr-only ml-0 min-w-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
425 )}
426 >
427 {primaryLabel}
428 </span>
429 </ThreadDetailsControl>
430 {isPanel ? (
431 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
432 ) : (
433 <GroupSeparator {...(!compact ? { className: "hidden @3xl/header-actions:block" } : {})} />
434 )}
435 <Menu open={menuOpen} onOpenChange={setMenuOpen}>
436 <MenuTrigger
437 disabled={isHostEditorDenied}
438 render={
439 <ThreadDetailsControl
440 aria-label="Choose editor"
441 size={isPanel ? "sm" : "icon-xs"}
442 variant={isPanel ? "ghost" : "outline"}
443 part="secondary"
444 panel={isPanel}
445 />
446 }
447 >
448 <ChevronDownIcon
449 aria-hidden="true"
450 className={isPanel ? THREAD_DETAILS_PANEL_CHEVRON_CLASS : "size-4"}
451 />
452 </MenuTrigger>
453 <MenuPopup
454 align="end"
455 {...(isPanel ? { anchor: panelAnchorRef } : {})}
456 className={isPanel ? "w-(--anchor-width)" : undefined}
457 >
458 {editorItems}
459 </MenuPopup>
460 </Menu>
461 </ActionGroup>
462 );
463});