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

OpenInPicker.tsx

463 lines13.4 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 { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
62import { shellEnvironment } from "~/state/shell";
63import { useAtomCommand } from "~/state/use-atom-command";
64import {
65 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
66 THREAD_DETAILS_PANEL_ICON_CLASS,
67 THREAD_DETAILS_PANEL_LABEL_CLASS,
68 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
69 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
70} from "./threadDetailsPanelStyles";
71import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
72import { useComposerMenuState } from "./useComposerMenuState";
73​
74type OpenInOption = {
75 label: string;
76 Icon: Icon;
77 value: EditorId;
78 kind: "brand" | "generic";
79};
80​
81export const resolveOpenInOptions = (
82 platform: string,
83 availableEditors: ReadonlyArray<EditorId>,
84) => {
85 const baseOptions: ReadonlyArray<Omit<OpenInOption, "label">> = [
86 {
87 Icon: CursorIcon,
88 value: "cursor",
89 kind: "brand",
90 },
91 {
92 Icon: TraeIcon,
93 value: "trae",
94 kind: "brand",
95 },
96 {
97 Icon: KiroIcon,
98 value: "kiro",
99 kind: "brand",
100 },
101 {
102 Icon: VisualStudioCode,
103 value: "vscode",
104 kind: "brand",
105 },
106 {
107 Icon: VisualStudioCodeInsiders,
108 value: "vscode-insiders",
109 kind: "brand",
110 },
111 {
112 Icon: VSCodium,
113 value: "vscodium",
114 kind: "brand",
115 },
116 {
117 Icon: Zed,
118 value: "zed",
119 kind: "brand",
120 },
121 {
122 Icon: AntigravityIcon,
123 value: "antigravity",
124 kind: "brand",
125 },
126 {
127 Icon: IntelliJIdeaIcon,
128 value: "idea",
129 kind: "brand",
130 },
131 {
132 Icon: AquaIcon,
133 value: "aqua",
134 kind: "brand",
135 },
136 {
137 Icon: CLionIcon,
138 value: "clion",
139 kind: "brand",
140 },
141 {
142 Icon: DataGripIcon,
143 value: "datagrip",
144 kind: "brand",
145 },
146 {
147 Icon: DataSpellIcon,
148 value: "dataspell",
149 kind: "brand",
150 },
151 {
152 Icon: GoLandIcon,
153 value: "goland",
154 kind: "brand",
155 },
156 {
157 Icon: PhpStormIcon,
158 value: "phpstorm",
159 kind: "brand",
160 },
161 {
162 Icon: PyCharmIcon,
163 value: "pycharm",
164 kind: "brand",
165 },
166 {
167 Icon: RiderIcon,
168 value: "rider",
169 kind: "brand",
170 },
171 {
172 Icon: RubyMineIcon,
173 value: "rubymine",
174 kind: "brand",
175 },
176 {
177 Icon: RustRoverIcon,
178 value: "rustrover",
179 kind: "brand",
180 },
181 {
182 Icon: WebStormIcon,
183 value: "webstorm",
184 kind: "brand",
185 },
186 {
187 Icon: isMacPlatform(platform)
188 ? FinderIcon
189 : isWindowsPlatform(platform)
190 ? FileExplorerIcon
191 : FolderClosedIcon,
192 value: "file-manager",
193 kind: isMacPlatform(platform) || isWindowsPlatform(platform) ? "brand" : "generic",
194 },
195 ];
196 const availableEditorSet = new Set(availableEditors);
197 return baseOptions
198 .filter((option) => availableEditorSet.has(option.value))
199 .map((option) => ({ ...option, label: editorLabelForPlatform(option.value, platform) }));
200};
201​
202function getOpenInIconClass(kind: OpenInOption["kind"]) {
203 return cn(kind === "brand" ? "text-foreground opacity-100" : "text-muted-foreground");
205​
206export const OpenInPicker = memo(function OpenInPicker({
207 environmentId,
208 keybindings,
209 availableEditors,
210 openInCwd,
211 openInCwdIsFile = false,
212 presentation = "toolbar",
213 compact = false,
214 enableShortcut = true,
215 displayMode = "toolbar",
216 revealFileManager = false,
217}: {
218 environmentId: EnvironmentId;
219 keybindings: ResolvedKeybindingsConfig;
220 availableEditors: ReadonlyArray<EditorId>;
221 openInCwd: string | null;
222 openInCwdIsFile?: boolean;
223 presentation?: "toolbar" | "menu";
224 compact?: boolean;
225 enableShortcut?: boolean;
226 displayMode?: "toolbar" | "panel";
227 revealFileManager?: boolean;
228}) {
229 const isPanel = displayMode === "panel";
230 const ActionGroup = isPanel ? "div" : Group;
231 const panelAnchorRef = useRef<HTMLDivElement | null>(null);
232 const openInEditorMutation = useAtomCommand(shellEnvironment.openInEditor, "open in editor");
233 const remote = useRemoteOpenState(environmentId);
234 const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
235 const isHostEditorDenied = remote.mode === "local-exec" && !canOperateHost;
236 const canOpenEditor = remote.mode !== "remote-unavailable" && !isHostEditorDenied;
237 const [menuOpen, setMenuOpen] = useComposerMenuState(isHostEditorDenied);
238 const remoteCapableEditors = useRemoteCapableEditors();
239 const [remoteHintSeen, markRemoteHintSeen] = useRemoteOpenHint();
240 const environmentLabel = useEnvironment(environmentId)?.label ?? "this machine";
241 // Remote mode ignores the server's PATH probe: what matters is what runs on
242 // the viewing machine, which only the desktop app can probe.
243 const effectiveEditors = remote.mode === "local-exec" ? availableEditors : remoteCapableEditors;
244 const [preferredEditor, setPreferredEditor] = usePreferredEditor(effectiveEditors);
245​
246 const openInEditor = (editorId: EditorId | null) => {
247 if (!openInCwd) return;
248 const editor = editorId ?? preferredEditor;
249 if (!editor) return;
250 if (remote.mode === "remote-unavailable") return;
251 if (remote.mode === "remote-links") {
252 const url = buildRemoteOpenUrl({
253 editor,
254 ...remote.host,
255 absolutePath: openInCwd,
256 isFile: openInCwdIsFile,
257 });
258 if (url === undefined) return;
259 // Only record hint-seen/preferred when the shell actually accepted
260 // the URL (an older desktop build can refuse the editor scheme).
261 void openRemoteEditorUrl(url).then((opened) => {
262 if (!opened) return;
263 markRemoteHintSeen();
264 setPreferredEditor(editor);
265 });
266 return;
267 }
268 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;
269 const result = openInEditorMutation({
270 environmentId,
271 input: {
272 cwd: openInCwd,
273 editor,
274 ...(revealFileManager && editor === "file-manager" ? { reveal: true } : {}),
275 },
276 });
277 setPreferredEditor(editor);
278 return result;
279 };
280​
281 const openFavoriteEditorShortcutLabel = shortcutLabelForCommand(
282 keybindings,
283 "editor.openFavorite",
284 );
285​
286 useEffect(() => {
287 if (!enableShortcut || !canOpenEditor) return;
288 const handler = (e: globalThis.KeyboardEvent) => {
289 if (e.defaultPrevented || !isOpenFavoriteEditorShortcut(e, keybindings)) return;
290 if (!openInCwd) return;
291 if (!preferredEditor) return;
292 if (
293 remote.mode === "local-exec" &&
294 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
295 )
296 return;
297​
298 e.preventDefault();
299 void openInEditor(preferredEditor);
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});