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

OpenInPicker.tsx

469 lines14.0 KB

1import { ThreadDetailsControl } from "./ThreadDetailsControl";
2import {
3 AuthOrchestrationOperateScope,
4 buildRemoteOpenUrl,
5 EditorId,
6 type EnvironmentId,
7 type ResolvedKeybindingsConfig,
8} from "@t3tools/contracts";
9import { memo, use, useEffect, useRef } from "react";
10import { BackgroundThreadContext } from "./backgroundThread";
11import { isOpenFavoriteEditorShortcut, shortcutLabelForCommand } from "../../keybindings";
12import { usePreferredEditor } from "../../editorPreferences";
13import { editorLabelForPlatform } from "../../editorLabels";
14import {
15 openRemoteEditorUrl,
16 useRemoteCapableEditors,
17 useRemoteOpenHint,
18 useRemoteOpenState,
19} from "../../remoteOpen";
20import { useEnvironment } from "../../state/environments";
21import { ChevronDownIcon, FolderClosedIcon, SquareArrowOutUpRightIcon } from "lucide-react";
22​
23import { Group, GroupSeparator } from "../ui/group";
24import {
25 Menu,
26 MenuItem,
27 MenuItemLabel,
28 MenuPopup,
29 MenuShortcut,
30 MenuSub,
31 MenuSubTrigger,
32 MenuSubPopup,
33 MenuTrigger,
34} from "../ui/menu";
35import {
36 AntigravityIcon,
37 CursorIcon,
38 FileExplorerIcon,
39 FinderIcon,
40 Icon,
41 KiroIcon,
42 TraeIcon,
43 VisualStudioCode,
44 VisualStudioCodeInsiders,
45 VSCodium,
46 Zed,
47} from "../Icons";
48import {
49 AquaIcon,
50 CLionIcon,
51 DataGripIcon,
52 DataSpellIcon,
53 GoLandIcon,
54 IntelliJIdeaIcon,
55 PhpStormIcon,
56 PyCharmIcon,
57 RiderIcon,
58 RubyMineIcon,
59 RustRoverIcon,
60 WebStormIcon,
61} from "../JetBrainsIcons";
62import { announce } from "~/lib/announce";
63import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
64import { shellEnvironment } from "~/state/shell";
65import { useAtomCommand } from "~/state/use-atom-command";
66import {
67 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
68 THREAD_DETAILS_PANEL_ICON_CLASS,
69 THREAD_DETAILS_PANEL_LABEL_CLASS,
70 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
71 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
72} from "./threadDetailsPanelStyles";
73import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
74import { useComposerMenuState } from "./useComposerMenuState";
75​
76type OpenInOption = {
77 label: string;
78 Icon: Icon;
79 value: EditorId;
80 kind: "brand" | "generic";
81};
82​
83const resolveOpenInOptions = (platform: string, availableEditors: ReadonlyArray<EditorId>) => {
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 openInCwdIsFile = false,
211 presentation = "toolbar",
212 compact = false,
213 enableShortcut = true,
214 displayMode = "toolbar",
215 revealFileManager = false,
216}: {
217 environmentId: EnvironmentId;
218 keybindings: ResolvedKeybindingsConfig;
219 availableEditors: ReadonlyArray<EditorId>;
220 openInCwd: string | null;
221 openInCwdIsFile?: boolean;
222 presentation?: "toolbar" | "menu";
223 compact?: boolean;
224 enableShortcut?: boolean;
225 displayMode?: "toolbar" | "panel";
226 revealFileManager?: boolean;
227}) {
228 const isPanel = displayMode === "panel";
229 const ActionGroup = isPanel ? "div" : Group;
230 const panelAnchorRef = useRef<HTMLDivElement | null>(null);
231 const openInEditorMutation = useAtomCommand(shellEnvironment.openInEditor, "open in editor");
232 const remote = useRemoteOpenState(environmentId);
233 const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
234 const isHostEditorDenied = remote.mode === "local-exec" && !canOperateHost;
235 const canOpenEditor = remote.mode !== "remote-unavailable" && !isHostEditorDenied;
236 const [menuOpen, setMenuOpen] = useComposerMenuState(isHostEditorDenied);
237 const remoteCapableEditors = useRemoteCapableEditors();
238 const [remoteHintSeen, markRemoteHintSeen] = useRemoteOpenHint();
239 const environmentLabel = useEnvironment(environmentId)?.label ?? "this machine";
240 // Remote editors run on the viewing machine; only desktop can probe that PATH.
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 const backgroundThread = use(BackgroundThreadContext);
284 useEffect(() => {
285 if (!enableShortcut || !canOpenEditor || backgroundThread) return;
286 const handler = (e: globalThis.KeyboardEvent) => {
287 if (e.defaultPrevented || !isOpenFavoriteEditorShortcut(e, keybindings)) return;
288 if (!openInCwd) return;
289 if (!preferredEditor) return;
290 if (
291 remote.mode === "local-exec" &&
292 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
293 )
294 return;
295​
296 e.preventDefault();
297 const label = editorLabelForPlatform(preferredEditor, navigator.platform);
298 void openInEditor(preferredEditor).then((opened) => {
299 if (opened) announce(`Opened in ${label}`);
300 });
301 };
302 window.addEventListener("keydown", handler, true);
303 return () => window.removeEventListener("keydown", handler, true);
304 }, [
305 backgroundThread,
306 canOpenEditor,
307 enableShortcut,
308 environmentId,
309 keybindings,
310 openInCwd,
311 openInEditor,
312 preferredEditor,
313 remote.mode,
314 ]);
315 // Derive after the shortcut effect to preserve the editor list's compiler cache.
316 const options = resolveOpenInOptions(navigator.platform, effectiveEditors);
317 const primaryOption = options.find(({ value }) => value === preferredEditor) ?? null;
318 const primaryLabel = isPanel ? `Open in ${primaryOption?.label ?? "editor"}` : "Open";
319​
320 const editorItems = (
321 <>
322 {remote.mode === "remote-unavailable" ? (
323 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
324 No SSH route to {environmentLabel}
325 </MenuItem>
326 ) : (
327 <>
328 {options.length === 0 && (
329 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
330 No installed editors found
331 </MenuItem>
332 )}
333 {options.map(({ label, Icon, value, kind }) => (
334 <MenuItem
335 density={presentation === "menu" ? "touch" : "default"}
336 disabled={!openInCwd || !canOpenEditor}
337 key={value}
338 onClick={() => {
339 if (presentation === "menu") {
340 void openInEditor(value);
341 } else {
342 setPreferredEditor(value);
343 }
344 }}
345 >
346 <Icon aria-hidden="true" className={getOpenInIconClass(kind)} />
347 <MenuItemLabel>{label}</MenuItemLabel>
348 {value === preferredEditor && openFavoriteEditorShortcutLabel && (
349 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
350 )}
351 </MenuItem>
352 ))}
353 {remote.mode === "remote-links" && !remoteHintSeen && (
354 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
355 Opens over SSH. Needs your key on {environmentLabel}
356 </MenuItem>
357 )}
358 </>
359 )}
360 </>
361 );
362 if (presentation === "menu") {
363 return (
364 <>
365 {primaryOption && (
366 <MenuItem
367 density={presentation === "menu" ? "touch" : "default"}
368​
369 disabled={!openInCwd || !canOpenEditor}
370 onClick={() => openInEditor(preferredEditor)}
371 >
372 <primaryOption.Icon className={cn("size-4", getOpenInIconClass(primaryOption.kind))} />
373 <MenuItemLabel>Open in {primaryOption.label}</MenuItemLabel>
374 {openFavoriteEditorShortcutLabel && (
375 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
376 )}
377 </MenuItem>
378 )}
379 <MenuSub>
380 <MenuSubTrigger density="touch" disabled={isHostEditorDenied}>
381 <SquareArrowOutUpRightIcon className="size-4" />
382 <MenuItemLabel>Open in…</MenuItemLabel>
383 </MenuSubTrigger>
384 <MenuSubPopup>{editorItems}</MenuSubPopup>
385 </MenuSub>
386 </>
387 );
388 }
389​
390 return (
391 <ActionGroup
392 aria-label="Open in editor"
393 role="group"
394 {...(isPanel
395 ? { className: THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, ref: panelAnchorRef }
396 : {})}
397 >
398 <ThreadDetailsControl
399 aria-label={compact ? "Open file in preferred editor" : primaryLabel}
400 size={isPanel ? "sm" : "xs"}
401 variant={isPanel ? "ghost" : "outline"}
402 part="primary"
403 panel={isPanel}
404 disabled={!preferredEditor || !openInCwd || !canOpenEditor}
405 onClick={() => openInEditor(preferredEditor)}
406 >
407 {primaryOption?.Icon ? (
408 <primaryOption.Icon
409 aria-hidden="true"
410 className={cn(
411 isPanel ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3.5",
412 getOpenInIconClass(primaryOption.kind),
413 // A hairline keeps pale app icons from dissolving into the card.
414 isPanel &&
415 primaryOption.kind === "brand" &&
416 "redesign:rounded-sm redesign:ring-1 redesign:ring-black/10 redesign:dark:ring-white/15",
417 )}
418 />
419 ) : isPanel ? (
420 <SquareArrowOutUpRightIcon
421 aria-hidden="true"
422 className={THREAD_DETAILS_PANEL_ICON_CLASS}
423 />
424 ) : null}
425 <span
426 className={cn(
427 compact
428 ? "sr-only"
429 : "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
430 isPanel && cn("not-sr-only ml-0 min-w-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
431 )}
432 >
433 {primaryLabel}
434 </span>
435 </ThreadDetailsControl>
436 {isPanel ? (
437 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
438 ) : (
439 <GroupSeparator {...(!compact ? { className: "hidden @3xl/header-actions:block" } : {})} />
440 )}
441 <Menu open={menuOpen} onOpenChange={setMenuOpen}>
442 <MenuTrigger
443 disabled={isHostEditorDenied}
444 render={
445 <ThreadDetailsControl
446 aria-label="Choose editor"
447 size={isPanel ? "sm" : "icon-xs"}
448 variant={isPanel ? "ghost" : "outline"}
449 part="secondary"
450 panel={isPanel}
451 />
452 }
453 >
454 <ChevronDownIcon
455 aria-hidden="true"
456 className={isPanel ? THREAD_DETAILS_PANEL_CHEVRON_CLASS : "size-4"}
457 />
458 </MenuTrigger>
459 <MenuPopup
460 align="end"
461 {...(isPanel ? { anchor: panelAnchorRef } : {})}
462 className={isPanel ? "w-(--anchor-width)" : undefined}
463 >
464 {editorItems}
465 </MenuPopup>
466 </Menu>
467 </ActionGroup>
468 );
469});