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

OpenInPicker.tsx

460 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​
81const resolveOpenInOptions = (platform: string, availableEditors: ReadonlyArray<EditorId>) => {
82 const baseOptions: ReadonlyArray<Omit<OpenInOption, "label">> = [
83 {
84 Icon: CursorIcon,
85 value: "cursor",
86 kind: "brand",
87 },
88 {
89 Icon: TraeIcon,
90 value: "trae",
91 kind: "brand",
92 },
93 {
94 Icon: KiroIcon,
95 value: "kiro",
96 kind: "brand",
97 },
98 {
99 Icon: VisualStudioCode,
100 value: "vscode",
101 kind: "brand",
102 },
103 {
104 Icon: VisualStudioCodeInsiders,
105 value: "vscode-insiders",
106 kind: "brand",
107 },
108 {
109 Icon: VSCodium,
110 value: "vscodium",
111 kind: "brand",
112 },
113 {
114 Icon: Zed,
115 value: "zed",
116 kind: "brand",
117 },
118 {
119 Icon: AntigravityIcon,
120 value: "antigravity",
121 kind: "brand",
122 },
123 {
124 Icon: IntelliJIdeaIcon,
125 value: "idea",
126 kind: "brand",
127 },
128 {
129 Icon: AquaIcon,
130 value: "aqua",
131 kind: "brand",
132 },
133 {
134 Icon: CLionIcon,
135 value: "clion",
136 kind: "brand",
137 },
138 {
139 Icon: DataGripIcon,
140 value: "datagrip",
141 kind: "brand",
142 },
143 {
144 Icon: DataSpellIcon,
145 value: "dataspell",
146 kind: "brand",
147 },
148 {
149 Icon: GoLandIcon,
150 value: "goland",
151 kind: "brand",
152 },
153 {
154 Icon: PhpStormIcon,
155 value: "phpstorm",
156 kind: "brand",
157 },
158 {
159 Icon: PyCharmIcon,
160 value: "pycharm",
161 kind: "brand",
162 },
163 {
164 Icon: RiderIcon,
165 value: "rider",
166 kind: "brand",
167 },
168 {
169 Icon: RubyMineIcon,
170 value: "rubymine",
171 kind: "brand",
172 },
173 {
174 Icon: RustRoverIcon,
175 value: "rustrover",
176 kind: "brand",
177 },
178 {
179 Icon: WebStormIcon,
180 value: "webstorm",
181 kind: "brand",
182 },
183 {
184 Icon: isMacPlatform(platform)
185 ? FinderIcon
186 : isWindowsPlatform(platform)
187 ? FileExplorerIcon
188 : FolderClosedIcon,
189 value: "file-manager",
190 kind: isMacPlatform(platform) || isWindowsPlatform(platform) ? "brand" : "generic",
191 },
192 ];
193 const availableEditorSet = new Set(availableEditors);
194 return baseOptions
195 .filter((option) => availableEditorSet.has(option.value))
196 .map((option) => ({ ...option, label: editorLabelForPlatform(option.value, platform) }));
197};
198​
199function getOpenInIconClass(kind: OpenInOption["kind"]) {
200 return cn(kind === "brand" ? "text-foreground opacity-100" : "text-muted-foreground");
202​
203export const OpenInPicker = memo(function OpenInPicker({
204 environmentId,
205 keybindings,
206 availableEditors,
207 openInCwd,
208 openInCwdIsFile = false,
209 presentation = "toolbar",
210 compact = false,
211 enableShortcut = true,
212 displayMode = "toolbar",
213 revealFileManager = false,
214}: {
215 environmentId: EnvironmentId;
216 keybindings: ResolvedKeybindingsConfig;
217 availableEditors: ReadonlyArray<EditorId>;
218 openInCwd: string | null;
219 openInCwdIsFile?: boolean;
220 presentation?: "toolbar" | "menu";
221 compact?: boolean;
222 enableShortcut?: boolean;
223 displayMode?: "toolbar" | "panel";
224 revealFileManager?: boolean;
225}) {
226 const isPanel = displayMode === "panel";
227 const ActionGroup = isPanel ? "div" : Group;
228 const panelAnchorRef = useRef<HTMLDivElement | null>(null);
229 const openInEditorMutation = useAtomCommand(shellEnvironment.openInEditor, "open in editor");
230 const remote = useRemoteOpenState(environmentId);
231 const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
232 const isHostEditorDenied = remote.mode === "local-exec" && !canOperateHost;
233 const canOpenEditor = remote.mode !== "remote-unavailable" && !isHostEditorDenied;
234 const [menuOpen, setMenuOpen] = useComposerMenuState(isHostEditorDenied);
235 const remoteCapableEditors = useRemoteCapableEditors();
236 const [remoteHintSeen, markRemoteHintSeen] = useRemoteOpenHint();
237 const environmentLabel = useEnvironment(environmentId)?.label ?? "this machine";
238 // Remote mode ignores the server's PATH probe: what matters is what runs on
239 // the viewing machine, which only the desktop app can probe.
240 const effectiveEditors = remote.mode === "local-exec" ? availableEditors : remoteCapableEditors;
241 const [preferredEditor, setPreferredEditor] = usePreferredEditor(effectiveEditors);
242​
243 const openInEditor = (editorId: EditorId | null) => {
244 if (!openInCwd) return;
245 const editor = editorId ?? preferredEditor;
246 if (!editor) return;
247 if (remote.mode === "remote-unavailable") return;
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;
256 // Only record hint-seen/preferred when the shell actually accepted
257 // the URL (an older desktop build can refuse the editor scheme).
258 void openRemoteEditorUrl(url).then((opened) => {
259 if (!opened) return;
260 markRemoteHintSeen();
261 setPreferredEditor(editor);
262 });
263 return;
264 }
265 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;
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 result;
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 void openInEditor(preferredEditor);
297 };
298 window.addEventListener("keydown", handler, true);
299 return () => window.removeEventListener("keydown", handler, true);
300 }, [
301 canOpenEditor,
302 enableShortcut,
303 environmentId,
304 keybindings,
305 openInCwd,
306 openInEditor,
307 preferredEditor,
308 remote.mode,
309 ]);
310 // Derived after the shortcut effect so the compiler can cache the resolved editor list.
311 const options = resolveOpenInOptions(navigator.platform, effectiveEditors);
312 const primaryOption = options.find(({ value }) => value === preferredEditor) ?? null;
313 const primaryLabel = isPanel ? `Open in ${primaryOption?.label ?? "editor"}` : "Open";
314​
315 const editorItems = (
316 <>
317 {remote.mode === "remote-unavailable" ? (
318 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
319 No SSH route to {environmentLabel}
320 </MenuItem>
321 ) : (
322 <>
323 {options.length === 0 && (
324 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
325 No installed editors found
326 </MenuItem>
327 )}
328 {options.map(({ label, Icon, value, kind }) => (
329 <MenuItem
330 density={presentation === "menu" ? "touch" : "default"}
331 disabled={!openInCwd || !canOpenEditor}
332 key={value}
333 onClick={() => {
334 if (presentation === "menu") {
335 void openInEditor(value);
336 } else {
337 setPreferredEditor(value);
338 }
339 }}
340 >
341 <Icon aria-hidden="true" className={getOpenInIconClass(kind)} />
342 <MenuItemLabel>{label}</MenuItemLabel>
343 {value === preferredEditor && openFavoriteEditorShortcutLabel && (
344 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
345 )}
346 </MenuItem>
347 ))}
348 {remote.mode === "remote-links" && !remoteHintSeen && (
349 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
350 Opens over SSH. Needs your key on {environmentLabel}
351 </MenuItem>
352 )}
353 </>
354 )}
355 </>
356 );
357 if (presentation === "menu") {
358 return (
359 <>
360 {primaryOption && (
361 <MenuItem
362 density={presentation === "menu" ? "touch" : "default"}
363​
364 disabled={!openInCwd || !canOpenEditor}
365 onClick={() => openInEditor(preferredEditor)}
366 >
367 <primaryOption.Icon className={cn("size-4", getOpenInIconClass(primaryOption.kind))} />
368 <MenuItemLabel>Open in {primaryOption.label}</MenuItemLabel>
369 {openFavoriteEditorShortcutLabel && (
370 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
371 )}
372 </MenuItem>
373 )}
374 <MenuSub>
375 <MenuSubTrigger density="touch" disabled={isHostEditorDenied}>
376 <SquareArrowOutUpRightIcon className="size-4" />
377 <MenuItemLabel>Open in…</MenuItemLabel>
378 </MenuSubTrigger>
379 <MenuSubPopup>{editorItems}</MenuSubPopup>
380 </MenuSub>
381 </>
382 );
383 }
384​
385 return (
386 <ActionGroup
387 aria-label="Open in editor"
388 role="group"
389 {...(isPanel
390 ? { className: THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, ref: panelAnchorRef }
391 : {})}
392 >
393 <ThreadDetailsControl
394 aria-label={compact ? "Open file in preferred editor" : primaryLabel}
395 size={isPanel ? "sm" : "xs"}
396 variant={isPanel ? "ghost" : "outline"}
397 part="primary"
398 panel={isPanel}
399 disabled={!preferredEditor || !openInCwd || !canOpenEditor}
400 onClick={() => openInEditor(preferredEditor)}
401 >
402 {primaryOption?.Icon ? (
403 <primaryOption.Icon
404 aria-hidden="true"
405 className={cn(
406 isPanel ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3.5",
407 getOpenInIconClass(primaryOption.kind),
408 )}
409 />
410 ) : isPanel ? (
411 <SquareArrowOutUpRightIcon
412 aria-hidden="true"
413 className={THREAD_DETAILS_PANEL_ICON_CLASS}
414 />
415 ) : null}
416 <span
417 className={cn(
418 compact
419 ? "sr-only"
420 : "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
421 isPanel && cn("not-sr-only ml-0 min-w-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
422 )}
423 >
424 {primaryLabel}
425 </span>
426 </ThreadDetailsControl>
427 {isPanel ? (
428 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
429 ) : (
430 <GroupSeparator {...(!compact ? { className: "hidden @3xl/header-actions:block" } : {})} />
431 )}
432 <Menu open={menuOpen} onOpenChange={setMenuOpen}>
433 <MenuTrigger
434 disabled={isHostEditorDenied}
435 render={
436 <ThreadDetailsControl
437 aria-label="Choose editor"
438 size={isPanel ? "sm" : "icon-xs"}
439 variant={isPanel ? "ghost" : "outline"}
440 part="secondary"
441 panel={isPanel}
442 />
443 }
444 >
445 <ChevronDownIcon
446 aria-hidden="true"
447 className={isPanel ? THREAD_DETAILS_PANEL_CHEVRON_CLASS : "size-4"}
448 />
449 </MenuTrigger>
450 <MenuPopup
451 align="end"
452 {...(isPanel ? { anchor: panelAnchorRef } : {})}
453 className={isPanel ? "w-(--anchor-width)" : undefined}
454 >
455 {editorItems}
456 </MenuPopup>
457 </Menu>
458 </ActionGroup>
459 );
460});