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

OpenInPicker.tsx

463 lines13.2 KB

1import { ThreadDetailsControl } from "./ThreadDetailsControl";
2import {
3 AuthOrchestrationOperateScope,
4 buildRemoteOpenUrl,
5 EditorId,
6 type EnvironmentId,
7 type ResolvedKeybindingsConfig,
8} from "@t3tools/contracts";
9import { memo, useCallback, useEffect, useMemo, 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_SPLIT_GROUP_CLASS,
68 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
69} from "./threadDetailsPanelStyles";
70import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
71import { useComposerMenuState } from "./useComposerMenuState";
72​
73type OpenInOption = {
74 label: string;
75 Icon: Icon;
76 value: EditorId;
77 kind: "brand" | "generic";
78};
79​
80export const resolveOpenInOptions = (
81 platform: string,
82 availableEditors: ReadonlyArray<EditorId>,
83) => {
84 const baseOptions: ReadonlyArray<Omit<OpenInOption, "label">> = [
85 {
86 Icon: CursorIcon,
87 value: "cursor",
88 kind: "brand",
89 },
90 {
91 Icon: TraeIcon,
92 value: "trae",
93 kind: "brand",
94 },
95 {
96 Icon: KiroIcon,
97 value: "kiro",
98 kind: "brand",
99 },
100 {
101 Icon: VisualStudioCode,
102 value: "vscode",
103 kind: "brand",
104 },
105 {
106 Icon: VisualStudioCodeInsiders,
107 value: "vscode-insiders",
108 kind: "brand",
109 },
110 {
111 Icon: VSCodium,
112 value: "vscodium",
113 kind: "brand",
114 },
115 {
116 Icon: Zed,
117 value: "zed",
118 kind: "brand",
119 },
120 {
121 Icon: AntigravityIcon,
122 value: "antigravity",
123 kind: "brand",
124 },
125 {
126 Icon: IntelliJIdeaIcon,
127 value: "idea",
128 kind: "brand",
129 },
130 {
131 Icon: AquaIcon,
132 value: "aqua",
133 kind: "brand",
134 },
135 {
136 Icon: CLionIcon,
137 value: "clion",
138 kind: "brand",
139 },
140 {
141 Icon: DataGripIcon,
142 value: "datagrip",
143 kind: "brand",
144 },
145 {
146 Icon: DataSpellIcon,
147 value: "dataspell",
148 kind: "brand",
149 },
150 {
151 Icon: GoLandIcon,
152 value: "goland",
153 kind: "brand",
154 },
155 {
156 Icon: PhpStormIcon,
157 value: "phpstorm",
158 kind: "brand",
159 },
160 {
161 Icon: PyCharmIcon,
162 value: "pycharm",
163 kind: "brand",
164 },
165 {
166 Icon: RiderIcon,
167 value: "rider",
168 kind: "brand",
169 },
170 {
171 Icon: RubyMineIcon,
172 value: "rubymine",
173 kind: "brand",
174 },
175 {
176 Icon: RustRoverIcon,
177 value: "rustrover",
178 kind: "brand",
179 },
180 {
181 Icon: WebStormIcon,
182 value: "webstorm",
183 kind: "brand",
184 },
185 {
186 Icon: isMacPlatform(platform)
187 ? FinderIcon
188 : isWindowsPlatform(platform)
189 ? FileExplorerIcon
190 : FolderClosedIcon,
191 value: "file-manager",
192 kind: isMacPlatform(platform) || isWindowsPlatform(platform) ? "brand" : "generic",
193 },
194 ];
195 const availableEditorSet = new Set(availableEditors);
196 return baseOptions
197 .filter((option) => availableEditorSet.has(option.value))
198 .map((option) => ({ ...option, label: editorLabelForPlatform(option.value, platform) }));
199};
200​
201function getOpenInIconClass(kind: OpenInOption["kind"]) {
202 return cn(kind === "brand" ? "text-foreground opacity-100" : "text-muted-foreground");
204​
205export const OpenInPicker = memo(function OpenInPicker({
206 environmentId,
207 keybindings,
208 availableEditors,
209 openInCwd,
210 presentation = "toolbar",
211 compact = false,
212 enableShortcut = true,
213 displayMode = "toolbar",
214}: {
215 environmentId: EnvironmentId;
216 keybindings: ResolvedKeybindingsConfig;
217 availableEditors: ReadonlyArray<EditorId>;
218 openInCwd: string | null;
219 presentation?: "toolbar" | "menu";
220 compact?: boolean;
221 enableShortcut?: boolean;
222 displayMode?: "toolbar" | "panel";
223}) {
224 const isPanel = displayMode === "panel";
225 const ActionGroup = isPanel ? "div" : Group;
226 const panelAnchorRef = useRef<HTMLDivElement | null>(null);
227 const openInEditorMutation = useAtomCommand(shellEnvironment.openInEditor, "open in editor");
228 const remote = useRemoteOpenState(environmentId);
229 const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
230 const isHostEditorDenied = remote.mode === "local-exec" && !canOperateHost;
231 const canOpenEditor = remote.mode !== "remote-unavailable" && !isHostEditorDenied;
232 const [menuOpen, setMenuOpen] = useComposerMenuState(isHostEditorDenied);
233 const remoteCapableEditors = useRemoteCapableEditors();
234 const [remoteHintSeen, markRemoteHintSeen] = useRemoteOpenHint();
235 const environmentLabel = useEnvironment(environmentId)?.label ?? "this machine";
236 // Remote mode ignores the server's PATH probe: what matters is what runs on
237 // the viewing machine, which only the desktop app can probe.
238 const effectiveEditors = remote.mode === "local-exec" ? availableEditors : remoteCapableEditors;
239 const [preferredEditor, setPreferredEditor] = usePreferredEditor(effectiveEditors);
240 const options = useMemo(
241 () => resolveOpenInOptions(navigator.platform, effectiveEditors),
242 [effectiveEditors],
243 );
244 const primaryOption = options.find(({ value }) => value === preferredEditor) ?? null;
245​
246 const openInEditor = useCallback(
247 (editorId: EditorId | null) => {
248 if (!openInCwd) return;
249 const editor = editorId ?? preferredEditor;
250 if (!editor) return;
251 if (remote.mode === "remote-unavailable") return;
252 if (remote.mode === "remote-links") {
253 const url = buildRemoteOpenUrl({
254 editor,
255 host: remote.host.host,
256 absolutePath: openInCwd,
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 },
275 });
276 setPreferredEditor(editor);
277 return result;
278 },
279 [
280 environmentId,
281 markRemoteHintSeen,
282 openInCwd,
283 openInEditorMutation,
284 preferredEditor,
285 remote,
286 setPreferredEditor,
287 ],
288 );
289​
290 const openFavoriteEditorShortcutLabel = useMemo(
291 () => shortcutLabelForCommand(keybindings, "editor.openFavorite"),
292 [keybindings],
293 );
294​
295 useEffect(() => {
296 if (!enableShortcut || !canOpenEditor) return;
297 const handler = (e: globalThis.KeyboardEvent) => {
298 if (!isOpenFavoriteEditorShortcut(e, keybindings)) return;
299 if (!openInCwd) return;
300 if (!preferredEditor) return;
301 if (
302 remote.mode === "local-exec" &&
303 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
304 )
305 return;
306​
307 e.preventDefault();
308 void openInEditor(preferredEditor);
309 };
310 window.addEventListener("keydown", handler);
311 return () => window.removeEventListener("keydown", handler);
312 }, [
313 canOpenEditor,
314 enableShortcut,
315 environmentId,
316 keybindings,
317 openInCwd,
318 openInEditor,
319 preferredEditor,
320 remote.mode,
321 ]);
322 const primaryLabel = isPanel ? `Open in ${primaryOption?.label ?? "editor"}` : "Open";
323​
324 const editorItems = (
325 <>
326 {remote.mode === "remote-unavailable" ? (
327 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
328 No SSH route to {environmentLabel}
329 </MenuItem>
330 ) : (
331 <>
332 {options.length === 0 && (
333 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
334 No installed editors found
335 </MenuItem>
336 )}
337 {options.map(({ label, Icon, value, kind }) => (
338 <MenuItem
339 density={presentation === "menu" ? "touch" : "default"}
340 disabled={!openInCwd || !canOpenEditor}
341 key={value}
342 onClick={() => openInEditor(value)}
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 && "not-sr-only ml-0 min-w-0 truncate",
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});