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

OpenInPicker.tsx

441 lines13.1 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 editorItems = (
290 <>
291 {remote.mode === "remote-unavailable" ? (
292 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
293 No SSH route to {environmentLabel}
294 </MenuItem>
295 ) : (
296 <>
297 {options.length === 0 && (
298 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
299 No installed editors found
300 </MenuItem>
301 )}
302 {options.map(({ label, Icon, value, kind }) => (
303 <MenuItem
304 density={presentation === "menu" ? "touch" : "default"}
305 disabled={!openInCwd || !canOpenEditor}
306 key={value}
307 onClick={() => {
308 if (presentation === "menu") {
309 void openInEditor(value);
310 } else {
311 setPreferredEditor(value);
312 }
313 }}
314 >
315 <Icon aria-hidden="true" className={getOpenInIconClass(kind)} />
316 <MenuItemLabel>{label}</MenuItemLabel>
317 {value === preferredEditor && openFavoriteEditorShortcutLabel && (
318 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
319 )}
320 </MenuItem>
321 ))}
322 {remote.mode === "remote-links" && !remoteHintSeen && (
323 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
324 Opens over SSH. Needs your key on {environmentLabel}
325 </MenuItem>
326 )}
327 </>
328 )}
329 </>
330 );
331 if (presentation === "menu") {
332 return (
333 <>
334 {primaryOption && (
335 <MenuItem
336 density={presentation === "menu" ? "touch" : "default"}
337​
338 disabled={!openInCwd || !canOpenEditor}
339 onClick={() => openInEditor(preferredEditor)}
340 >
341 <primaryOption.Icon className={cn("size-4", getOpenInIconClass(primaryOption.kind))} />
342 <MenuItemLabel>Open in {primaryOption.label}</MenuItemLabel>
343 {openFavoriteEditorShortcutLabel && (
344 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
345 )}
346 </MenuItem>
347 )}
348 <MenuSub>
349 <MenuSubTrigger density="touch" disabled={isHostEditorDenied}>
350 <SquareArrowOutUpRightIcon className="size-4" />
351 <MenuItemLabel>Open in…</MenuItemLabel>
352 </MenuSubTrigger>
353 <MenuSubPopup>{editorItems}</MenuSubPopup>
354 </MenuSub>
355 </>
356 );
357 }
358​
359 return (
360 <ActionGroup
361 aria-label="Open in editor"
362 role="group"
363 {...(isPanel
364 ? { className: THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, ref: panelAnchorRef }
365 : {})}
366 >
367 <ThreadDetailsControl
368 aria-label={compact ? "Open file in preferred editor" : primaryLabel}
369 size={isPanel ? "sm" : "xs"}
370 variant={isPanel ? "ghost" : "outline"}
371 part="primary"
372 panel={isPanel}
373 disabled={!preferredEditor || !openInCwd || !canOpenEditor}
374 {...(enableShortcut && !backgroundThread ? { [OPEN_FAVORITE_EDITOR_ATTRIBUTE]: "" } : {})}
375 onClick={() => {
376 if (!preferredEditor) return;
377 const label = editorLabelForPlatform(preferredEditor, navigator.platform);
378 void openInEditor(preferredEditor).then((opened) => {
379 if (opened) announce(`Opened in ${label}`);
380 });
381 }}
382 >
383 {primaryOption?.Icon ? (
384 <primaryOption.Icon
385 aria-hidden="true"
386 className={cn(
387 isPanel ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3.5",
388 getOpenInIconClass(primaryOption.kind),
389 )}
390 />
391 ) : isPanel ? (
392 <SquareArrowOutUpRightIcon
393 aria-hidden="true"
394 className={THREAD_DETAILS_PANEL_ICON_CLASS}
395 />
396 ) : null}
397 <span
398 className={cn(
399 compact
400 ? "sr-only"
401 : "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
402 isPanel && cn("not-sr-only ml-0 min-w-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
403 )}
404 >
405 {primaryLabel}
406 </span>
407 </ThreadDetailsControl>
408 {isPanel ? (
409 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
410 ) : (
411 <GroupSeparator {...(!compact ? { className: "hidden @3xl/header-actions:block" } : {})} />
412 )}
413 <Menu open={menuOpen} onOpenChange={setMenuOpen}>
414 <MenuTrigger
415 disabled={isHostEditorDenied}
416 render={
417 <ThreadDetailsControl
418 aria-label="Choose editor"
419 size={isPanel ? "sm" : "icon-xs"}
420 variant={isPanel ? "ghost" : "outline"}
421 part="secondary"
422 panel={isPanel}
423 />
424 }
425 >
426 <ChevronDownIcon
427 aria-hidden="true"
428 className={isPanel ? THREAD_DETAILS_PANEL_CHEVRON_CLASS : "size-4"}
429 />
430 </MenuTrigger>
431 <MenuPopup
432 align="end"
433 {...(isPanel ? { anchor: panelAnchorRef } : {})}
434 className={isPanel ? "w-(--anchor-width)" : undefined}
435 >
436 {editorItems}
437 </MenuPopup>
438 </Menu>
439 </ActionGroup>
440 );
441});