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

OpenInPicker.tsx

448 lines13.3 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, useRef } from "react";
10import { BackgroundThreadContext } from "./backgroundThread";
11import { shortcutLabelForCommand } from "../../keybindings";
12import { OPEN_FAVORITE_EDITOR_ATTRIBUTE } from "./OpenInPickerShortcut";
13import { usePreferredEditor } from "../../editorPreferences";
14import { editorLabelForPlatform } from "../../editorLabels";
15import {
16 openRemoteEditorUrl,
17 useRemoteCapableEditors,
18 useRemoteOpenHint,
19 useRemoteOpenState,
20} from "../../remoteOpen";
21import { useEnvironment } from "../../state/environments";
22import { ChevronDownIcon, FolderClosedIcon, SquareArrowOutUpRightIcon } from "lucide-react";
23​
24import { Group, GroupSeparator } from "../ui/group";
25import {
26 Menu,
27 MenuItem,
28 MenuItemLabel,
29 MenuPopup,
30 MenuShortcut,
31 MenuSub,
32 MenuSubTrigger,
33 MenuSubPopup,
34 MenuTrigger,
35} from "../ui/menu";
36import {
37 AntigravityIcon,
38 CursorIcon,
39 FileExplorerIcon,
40 FinderIcon,
41 Icon,
42 KiroIcon,
43 TraeIcon,
44 VisualStudioCode,
45 VisualStudioCodeInsiders,
46 VSCodium,
47 Zed,
48} from "../Icons";
49import {
50 AquaIcon,
51 CLionIcon,
52 DataGripIcon,
53 DataSpellIcon,
54 GoLandIcon,
55 IntelliJIdeaIcon,
56 PhpStormIcon,
57 PyCharmIcon,
58 RiderIcon,
59 RubyMineIcon,
60 RustRoverIcon,
61 WebStormIcon,
62} from "../JetBrainsIcons";
63import { announce } from "~/lib/announce";
64import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
65import { shellEnvironment } from "~/state/shell";
66import { useAtomCommand } from "~/state/use-atom-command";
67import {
68 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
69 THREAD_DETAILS_PANEL_ICON_CLASS,
70 THREAD_DETAILS_PANEL_LABEL_CLASS,
71 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
72 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
73} from "./threadDetailsPanelStyles";
74import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
75import { useComposerMenuState } from "./useComposerMenuState";
76​
77type OpenInOption = {
78 label: string;
79 Icon: Icon;
80 value: EditorId;
81 kind: "brand" | "generic";
82};
83​
84const resolveOpenInOptions = (platform: string, availableEditors: ReadonlyArray<EditorId>) => {
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 editors run on the viewing machine; only desktop can probe that PATH.
242 const effectiveEditors = remote.mode === "local-exec" ? availableEditors : remoteCapableEditors;
243 const [preferredEditor, setPreferredEditor] = usePreferredEditor(effectiveEditors);
244​
245 const openInEditor = async (editorId: EditorId | null): Promise<boolean> => {
246 if (!openInCwd) return false;
247 const editor = editorId ?? preferredEditor;
248 if (!editor) return false;
249 if (remote.mode === "remote-unavailable") return false;
250 if (remote.mode === "remote-links") {
251 const url = buildRemoteOpenUrl({
252 editor,
253 ...remote.host,
254 absolutePath: openInCwd,
255 isFile: openInCwdIsFile,
256 });
257 if (url === undefined) return false;
258 // Only record hint-seen/preferred when the shell actually accepted
259 // the URL (an older desktop build can refuse the editor scheme).
260 const opened = await openRemoteEditorUrl(url);
261 if (!opened) return false;
262 markRemoteHintSeen();
263 setPreferredEditor(editor);
264 return true;
265 }
266 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
267 const result = openInEditorMutation({
268 environmentId,
269 input: {
270 cwd: openInCwd,
271 editor,
272 ...(revealFileManager && editor === "file-manager" ? { reveal: true } : {}),
273 },
274 });
275 setPreferredEditor(editor);
276 return (await result)._tag === "Success";
277 };
278​
279 const openFavoriteEditorShortcutLabel = shortcutLabelForCommand(
280 keybindings,
281 "editor.openFavorite",
282 );
283​
284 const backgroundThread = use(BackgroundThreadContext);
285 const options = resolveOpenInOptions(navigator.platform, effectiveEditors);
286 const primaryOption = options.find(({ value }) => value === preferredEditor) ?? null;
287 const primaryLabel = isPanel ? `Open in ${primaryOption?.label ?? "editor"}` : "Open";
288​
289 const unavailableReason =
290 remote.mode === "remote-unavailable"
291 ? `No SSH route to ${environmentLabel}`
292 : remote.mode === "remote-links" && options.length === 0
293 ? `Open from a computer to edit on ${environmentLabel}`
294 : null;
295​
296 const editorItems = (
297 <>
298 {unavailableReason !== null ? (
299 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
300 {unavailableReason}
301 </MenuItem>
302 ) : (
303 <>
304 {options.length === 0 && (
305 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
306 No installed editors found
307 </MenuItem>
308 )}
309 {options.map(({ label, Icon, value, kind }) => (
310 <MenuItem
311 density={presentation === "menu" ? "touch" : "default"}
312 disabled={!openInCwd || !canOpenEditor}
313 key={value}
314 onClick={() => {
315 if (presentation === "menu") {
316 void openInEditor(value);
317 } else {
318 setPreferredEditor(value);
319 }
320 }}
321 >
322 <Icon aria-hidden="true" className={getOpenInIconClass(kind)} />
323 <MenuItemLabel>{label}</MenuItemLabel>
324 {value === preferredEditor && openFavoriteEditorShortcutLabel && (
325 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
326 )}
327 </MenuItem>
328 ))}
329 {remote.mode === "remote-links" && !remoteHintSeen && (
330 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
331 Opens over SSH. Needs your key on {environmentLabel}
332 </MenuItem>
333 )}
334 </>
335 )}
336 </>
337 );
338 if (presentation === "menu") {
339 return (
340 <>
341 {primaryOption && (
342 <MenuItem
343 density={presentation === "menu" ? "touch" : "default"}
344​
345 disabled={!openInCwd || !canOpenEditor}
346 onClick={() => openInEditor(preferredEditor)}
347 >
348 <primaryOption.Icon className={cn("size-4", getOpenInIconClass(primaryOption.kind))} />
349 <MenuItemLabel>Open in {primaryOption.label}</MenuItemLabel>
350 {openFavoriteEditorShortcutLabel && (
351 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
352 )}
353 </MenuItem>
354 )}
355 <MenuSub>
356 <MenuSubTrigger density="touch" disabled={isHostEditorDenied}>
357 <SquareArrowOutUpRightIcon className="size-4" />
358 <MenuItemLabel>Open in…</MenuItemLabel>
359 </MenuSubTrigger>
360 <MenuSubPopup>{editorItems}</MenuSubPopup>
361 </MenuSub>
362 </>
363 );
364 }
365​
366 return (
367 <ActionGroup
368 aria-label="Open in editor"
369 role="group"
370 {...(isPanel
371 ? { className: THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, ref: panelAnchorRef }
372 : {})}
373 >
374 <ThreadDetailsControl
375 aria-label={compact ? "Open file in preferred editor" : primaryLabel}
376 size={isPanel ? "sm" : "xs"}
377 variant={isPanel ? "ghost" : "outline"}
378 part="primary"
379 panel={isPanel}
380 disabled={!preferredEditor || !openInCwd || !canOpenEditor}
381 {...(enableShortcut && !backgroundThread ? { [OPEN_FAVORITE_EDITOR_ATTRIBUTE]: "" } : {})}
382 onClick={() => {
383 if (!preferredEditor) return;
384 const label = editorLabelForPlatform(preferredEditor, navigator.platform);
385 void openInEditor(preferredEditor).then((opened) => {
386 if (opened) announce(`Opened in ${label}`);
387 });
388 }}
389 >
390 {primaryOption?.Icon ? (
391 <primaryOption.Icon
392 aria-hidden="true"
393 className={cn(
394 isPanel ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3.5",
395 getOpenInIconClass(primaryOption.kind),
396 )}
397 />
398 ) : isPanel ? (
399 <SquareArrowOutUpRightIcon
400 aria-hidden="true"
401 className={THREAD_DETAILS_PANEL_ICON_CLASS}
402 />
403 ) : null}
404 <span
405 className={cn(
406 compact
407 ? "sr-only"
408 : "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
409 isPanel && cn("not-sr-only ml-0 min-w-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
410 )}
411 >
412 {primaryLabel}
413 </span>
414 </ThreadDetailsControl>
415 {isPanel ? (
416 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
417 ) : (
418 <GroupSeparator {...(!compact ? { className: "hidden @3xl/header-actions:block" } : {})} />
419 )}
420 <Menu open={menuOpen} onOpenChange={setMenuOpen}>
421 <MenuTrigger
422 disabled={isHostEditorDenied}
423 render={
424 <ThreadDetailsControl
425 aria-label="Choose editor"
426 size={isPanel ? "sm" : "icon-xs"}
427 variant={isPanel ? "ghost" : "outline"}
428 part="secondary"
429 panel={isPanel}
430 />
431 }
432 >
433 <ChevronDownIcon
434 aria-hidden="true"
435 className={isPanel ? THREAD_DETAILS_PANEL_CHEVRON_CLASS : "size-4"}
436 />
437 </MenuTrigger>
438 <MenuPopup
439 align="end"
440 {...(isPanel ? { anchor: panelAnchorRef } : {})}
441 className={isPanel ? "w-(--anchor-width)" : undefined}
442 >
443 {editorItems}
444 </MenuPopup>
445 </Menu>
446 </ActionGroup>
447 );
448});