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

OpenInPicker.tsx

356 lines12.7 KB

1import { ThreadDetailsControl } from "./ThreadDetailsControl";
2import {
3 AuthOrchestrationOperateScope,
4 buildRemoteOpenUrl,
5 EditorId,
6 type EnvironmentId,
7 type ResolvedKeybindingsConfig,
8} from "@t3tools/contracts";
9import { T, useGT, useMessages, Var } from "gt-react";
10import { memo, use, useRef } from "react";
11import { BackgroundThreadContext } from "./backgroundThread";
12import { shortcutLabelForCommand } from "../../keybindings";
13import type { FileManagerAction } from "./OpenInPicker.logic";
14import { OPEN_FAVORITE_EDITOR_ATTRIBUTE } from "./OpenInPickerShortcut";
15import { usePreferredEditor } from "../../editorPreferences";
16import { editorLabelForPlatform } from "../../editorLabels";
17import type { MessageResolver } from "../../i18n/messages";
18import {
19 openRemoteEditorUrl,
20 useRemoteCapableEditors,
21 useRemoteOpenHint,
22 useRemoteOpenState,
23} from "../../remoteOpen";
24import { useEnvironment } from "../../state/environments";
25import { ChevronDownIcon, SquareArrowOutUpRightIcon } from "lucide-react";
26​
27import { Group, GroupSeparator } from "../ui/group";
28import {
29 Menu,
30 MenuItem,
31 MenuItemLabel,
32 MenuPopup,
33 MenuShortcut,
34 MenuSub,
35 MenuSubTrigger,
36 MenuSubPopup,
37 MenuTrigger,
38} from "../ui/menu";
39import { SharedTooltipTrigger } from "../ui/shared-tooltip";
40import { type EditorIconOption, editorIconOptions } from "../editorIcons";
41import { announce } from "~/lib/announce";
42import { cn } from "~/lib/utils";
43import { shellEnvironment } from "~/state/shell";
44import { useAtomCommand } from "~/state/use-atom-command";
45import {
46 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
47 THREAD_DETAILS_PANEL_ICON_CLASS,
48 THREAD_DETAILS_PANEL_LABEL_CLASS,
49 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
50 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
51} from "./threadDetailsPanelStyles";
52import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
53import { useComposerMenuState } from "./useComposerMenuState";
54​
55type OpenInOption = EditorIconOption & { label: string };
56​
57const resolveOpenInOptions = (
58 platform: string,
59 availableEditors: ReadonlyArray<EditorId>,
60 resolve: MessageResolver,
61): ReadonlyArray<OpenInOption> => {
62 const availableEditorSet = new Set(availableEditors);
63 return editorIconOptions(platform)
64 .filter((option) => availableEditorSet.has(option.value))
65 .map((option) => ({
66 ...option,
67 label: editorLabelForPlatform(option.value, platform, resolve),
68 }));
69};
70​
71function getOpenInIconClass(kind: OpenInOption["kind"]) {
72 return cn(kind === "brand" ? "text-foreground opacity-100" : "text-muted-foreground");
74​
75export const OpenInPicker = memo(function OpenInPicker({
76 environmentId,
77 keybindings,
78 availableEditors,
79 openInCwd,
80 openInCwdIsFile = false,
81 presentation = "toolbar",
82 compact = false,
83 enableShortcut = true,
84 displayMode = "toolbar",
85 fileManagerAction = "open",
86}: {
87 environmentId: EnvironmentId;
88 keybindings: ResolvedKeybindingsConfig;
89 availableEditors: ReadonlyArray<EditorId>;
90 openInCwd: string | null;
91 openInCwdIsFile?: boolean;
92 presentation?: "toolbar" | "menu";
93 compact?: boolean;
94 enableShortcut?: boolean;
95 displayMode?: "toolbar" | "panel";
96 fileManagerAction?: FileManagerAction;
97}) {
98 const gt = useGT();
99 const messages = useMessages();
100 const isPanel = displayMode === "panel";
101 const ActionGroup = isPanel ? "div" : Group;
102 const panelAnchorRef = useRef<HTMLDivElement | null>(null);
103 const openInEditorMutation = useAtomCommand(shellEnvironment.openInEditor, "open in editor");
104 const remote = useRemoteOpenState(environmentId);
105 const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
106 const isHostEditorDenied = remote.mode === "local-exec" && !canOperateHost;
107 const canOpenEditor = remote.mode !== "remote-unavailable" && !isHostEditorDenied;
108 const [menuOpen, setMenuOpen] = useComposerMenuState(isHostEditorDenied);
109 const remoteCapableEditors = useRemoteCapableEditors();
110 const [remoteHintSeen, markRemoteHintSeen] = useRemoteOpenHint();
111 const environmentLabel = useEnvironment(environmentId)?.label ?? null;
112 // Remote editors run on the viewing machine; only desktop can probe that PATH.
113 const effectiveEditors = remote.mode === "local-exec" ? availableEditors : remoteCapableEditors;
114 const [preferredEditor, setPreferredEditor] = usePreferredEditor(effectiveEditors);
115 const isEditorUnavailable = (editor: EditorId | null) =>
116 editor === "file-manager" && fileManagerAction === "unavailable";
117​
118 const openInEditor = async (editorId: EditorId | null): Promise<boolean> => {
119 if (!openInCwd) return false;
120 const editor = editorId ?? preferredEditor;
121 if (!editor || isEditorUnavailable(editor)) return false;
122 if (remote.mode === "remote-unavailable") return false;
123 if (remote.mode === "remote-links") {
124 const url = buildRemoteOpenUrl({
125 editor,
126 ...remote.host,
127 absolutePath: openInCwd,
128 isFile: openInCwdIsFile,
129 });
130 if (url === undefined) return false;
131 // Only record hint-seen/preferred when the shell actually accepted
132 // the URL (an older desktop build can refuse the editor scheme).
133 const opened = await openRemoteEditorUrl(url);
134 if (!opened) return false;
135 markRemoteHintSeen();
136 setPreferredEditor(editor);
137 return true;
138 }
139 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
140 const result = openInEditorMutation({
141 environmentId,
142 input: {
143 cwd: openInCwd,
144 editor,
145 ...(fileManagerAction === "reveal" && editor === "file-manager" ? { reveal: true } : {}),
146 },
147 });
148 setPreferredEditor(editor);
149 return (await result)._tag === "Success";
150 };
151​
152 const openFavoriteEditorShortcutLabel = shortcutLabelForCommand(
153 keybindings,
154 "editor.openFavorite",
155 );
156​
157 const backgroundThread = use(BackgroundThreadContext);
158 const options = resolveOpenInOptions(navigator.platform, effectiveEditors, messages);
159 const primaryOption = options.find(({ value }) => value === preferredEditor) ?? null;
160 const primaryLabel = isPanel
161 ? primaryOption
162 ? gt`Open in ${{ editor: primaryOption.label }}`
163 : gt`Open in editor`
164 : gt({ context: "verb, opens the project in the preferred editor" })`Open`;
165​
166 const unavailableReason =
167 remote.mode === "remote-unavailable"
168 ? environmentLabel !== null
169 ? gt`No SSH route to ${{ environment: environmentLabel }}`
170 : gt`No SSH route to this machine`
171 : remote.mode === "remote-links" && options.length === 0
172 ? environmentLabel !== null
173 ? gt`Open from a computer to edit on ${{ environment: environmentLabel }}`
174 : gt`Open from a computer to edit on this machine`
175 : null;
176​
177 const editorItems = (
178 <>
179 {unavailableReason !== null ? (
180 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
181 {unavailableReason}
182 </MenuItem>
183 ) : (
184 <>
185 {options.length === 0 && (
186 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
187 <T>No installed editors found</T>
188 </MenuItem>
189 )}
190 {options.map(({ label, Icon, value, kind }) => (
191 <MenuItem
192 density={presentation === "menu" ? "touch" : "default"}
193 disabled={
194 !openInCwd ||
195 !canOpenEditor ||
196 (presentation === "menu" && isEditorUnavailable(value))
197 }
198 key={value}
199 onClick={() => {
200 if (presentation === "menu") {
201 void openInEditor(value);
202 } else {
203 setPreferredEditor(value);
204 }
205 }}
206 >
207 <Icon aria-hidden="true" className={getOpenInIconClass(kind)} />
208 <MenuItemLabel>{label}</MenuItemLabel>
209 {value === preferredEditor && openFavoriteEditorShortcutLabel && (
210 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
211 )}
212 </MenuItem>
213 ))}
214 {remote.mode === "remote-links" && !remoteHintSeen && (
215 <MenuItem density={presentation === "menu" ? "touch" : "default"} disabled>
216 {environmentLabel !== null
217 ? gt`Opens over SSH. Needs your key on ${{ environment: environmentLabel }}`
218 : gt`Opens over SSH. Needs your key on this machine`}
219 </MenuItem>
220 )}
221 </>
222 )}
223 </>
224 );
225 if (presentation === "menu") {
226 return (
227 <>
228 {primaryOption && (
229 <MenuItem
230 density={presentation === "menu" ? "touch" : "default"}
231 disabled={!openInCwd || !canOpenEditor || isEditorUnavailable(preferredEditor)}
232 onClick={() => openInEditor(preferredEditor)}
233 >
234 <primaryOption.Icon className={cn("size-4", getOpenInIconClass(primaryOption.kind))} />
235 <MenuItemLabel>
236 <T>
237 Open in <Var>{primaryOption.label}</Var>
238 </T>
239 </MenuItemLabel>
240 {openFavoriteEditorShortcutLabel && (
241 <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
242 )}
243 </MenuItem>
244 )}
245 <MenuSub>
246 <MenuSubTrigger density="touch" disabled={isHostEditorDenied}>
247 <SquareArrowOutUpRightIcon className="size-4" />
248 <MenuItemLabel>
249 <T>Open in…</T>
250 </MenuItemLabel>
251 </MenuSubTrigger>
252 <MenuSubPopup>{editorItems}</MenuSubPopup>
253 </MenuSub>
254 </>
255 );
256 }
257​
258 const primaryControlLabel = compact ? gt`Open file in preferred editor` : primaryLabel;
259 const primaryControl = (
260 <ThreadDetailsControl
261 aria-label={primaryControlLabel}
262 // Tooltip replaces the button data-slot, so toolbar theming needs a separate hook.
263 data-toolbar-control=""
264 size={isPanel ? "sm" : "xs"}
265 variant={isPanel ? "ghost" : "outline"}
266 part="primary"
267 panel={isPanel}
268 disabled={
269 !preferredEditor || !openInCwd || !canOpenEditor || isEditorUnavailable(preferredEditor)
270 }
271 {...(enableShortcut && !backgroundThread ? { [OPEN_FAVORITE_EDITOR_ATTRIBUTE]: "" } : {})}
272 onClick={() => {
273 if (!preferredEditor) return;
274 const label = editorLabelForPlatform(preferredEditor, navigator.platform);
275 void openInEditor(preferredEditor).then((opened) => {
276 if (opened) announce(gt`Opened in ${{ editor: label }}`);
277 });
278 }}
279 >
280 {primaryOption?.Icon ? (
281 <primaryOption.Icon
282 aria-hidden="true"
283 className={cn(
284 isPanel ? THREAD_DETAILS_PANEL_ICON_CLASS : "size-3.5",
285 getOpenInIconClass(primaryOption.kind),
286 )}
287 />
288 ) : isPanel ? (
289 <SquareArrowOutUpRightIcon aria-hidden="true" className={THREAD_DETAILS_PANEL_ICON_CLASS} />
290 ) : null}
291 <span
292 className={cn(
293 compact
294 ? "sr-only"
295 : "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
296 isPanel && cn("not-sr-only ml-0 min-w-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
297 )}
298 >
299 {primaryLabel}
300 </span>
301 </ThreadDetailsControl>
302 );
303​
304 return (
305 <ActionGroup
306 aria-label={gt`Open in editor`}
307 role="group"
308 {...(isPanel
309 ? { className: THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, ref: panelAnchorRef }
310 : {})}
311 >
312 <SharedTooltipTrigger render={primaryControl} label={primaryControlLabel} />
313 {isPanel ? (
314 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
315 ) : (
316 <GroupSeparator {...(!compact ? { className: "hidden @3xl/header-actions:block" } : {})} />
317 )}
318 <Menu open={menuOpen} onOpenChange={setMenuOpen}>
319 <SharedTooltipTrigger
320 render={
321 <MenuTrigger
322 disabled={isHostEditorDenied}
323 render={
324 <ThreadDetailsControl
325 aria-label={gt`Choose editor`}
326 data-toolbar-control=""
327 size={isPanel ? "sm" : "icon-xs"}
328 variant={isPanel ? "ghost" : "outline"}
329 part="secondary"
330 panel={isPanel}
331 />
332 }
333 />
334 }
335 label={
336 <>
337 <T>Choose editor</T>
338 </>
339 }
340 >
341 <ChevronDownIcon
342 aria-hidden="true"
343 className={isPanel ? THREAD_DETAILS_PANEL_CHEVRON_CLASS : "size-4"}
344 />
345 </SharedTooltipTrigger>
346 <MenuPopup
347 align="end"
348 {...(isPanel ? { anchor: panelAnchorRef } : {})}
349 className={isPanel ? "w-(--anchor-width)" : undefined}
350 >
351 {editorItems}
352 </MenuPopup>
353 </Menu>
354 </ActionGroup>
355 );
356});