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

ProjectScriptsControl.tsx

487 lines17.5 KB

1import { ThreadDetailsControl } from "./chat/ThreadDetailsControl";
2import {
3 AuthSettingsWriteScope,
4 type EnvironmentId,
5 type ProjectScript,
6 type T3ProjectFileScript,
7 type ResolvedKeybindingsConfig,
8} from "@t3tools/contracts";
9import { useAtomValue } from "@effect/atom-react";
10import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
11import {
12 isAtomCommandInterrupted,
13 squashAtomCommandFailure,
14} from "@t3tools/client-runtime/state/runtime";
15import { ChevronDownIcon, DownloadIcon, PlusIcon, SettingsIcon, WrenchIcon } from "lucide-react";
16import React, { useCallback, useMemo, useState } from "react";
17​
18import { commandForProjectScript, primaryProjectScript } from "~/projectScripts";
19import { shortcutLabelForCommand } from "~/keybindings";
20import { serverEnvironment } from "~/state/server";
21import { readEnvironmentScope } from "~/state/session";
22import {
23 EMPTY_PROJECT_SCRIPT_INPUT,
24 editorRequestForScript,
25 ProjectScriptEditorDialog,
26 ScriptIcon,
27 type NewProjectScriptInput,
28 type ProjectScriptActionResult,
29 type ProjectScriptEditorRequest,
30} from "./projectScriptEditor";
31import { Button } from "./ui/button";
32import { Group, GroupSeparator } from "./ui/group";
33import {
34 Menu,
35 MenuGroup,
36 MenuGroupLabel,
37 MenuItem,
38 MenuItemLabel,
39 MenuPopup,
40 MenuSeparator,
41 MenuShortcut,
42 MenuTrigger,
43 MenuSub,
44 MenuSubTrigger,
45 MenuSubPopup,
46} from "./ui/menu";
47import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
48import { cn } from "~/lib/utils";
49import {
50 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
51 THREAD_DETAILS_PANEL_ICON_CLASS,
52 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
53 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
54} from "./chat/threadDetailsPanelStyles";
55​
56export type { NewProjectScriptInput, ProjectScriptActionResult };
57​
58const NO_FILE_SCRIPTS: ReadonlyArray<T3ProjectFileScript> = [];
59​
60interface ProjectScriptsControlProps {
61 displayMode?: "toolbar" | "panel";
62 presentation?: "toolbar" | "menu";
63 onRequestMenuClose?: () => void;
64 environmentId: EnvironmentId;
65 scripts: ReadonlyArray<ProjectScript>;
66 /** Scripts declared in the project's checked-in t3.json, offered for import. */
67 fileScripts?: ReadonlyArray<T3ProjectFileScript>;
68 preferredScriptId?: string | null;
69 onRunScript?: ((script: ProjectScript) => void) | undefined;
70 onAddScript: (input: NewProjectScriptInput) => Promise<ProjectScriptActionResult>;
71 onUpdateScript: (
72 scriptId: string,
73 input: NewProjectScriptInput,
74 ) => Promise<ProjectScriptActionResult>;
75 onDeleteScript: (scriptId: string) => Promise<ProjectScriptActionResult>;
77​
78export default function ProjectScriptsControl({
79 displayMode = "toolbar",
80 presentation = "toolbar",
81 onRequestMenuClose,
82 environmentId,
83 scripts,
84 fileScripts = NO_FILE_SCRIPTS,
85 preferredScriptId = null,
86 onRunScript,
87 onAddScript,
88 onUpdateScript,
89 onDeleteScript,
90}: ProjectScriptsControlProps) {
91 const isPanel = displayMode === "panel";
92 const ActionGroup = isPanel ? "div" : Group;
93 const panelAnchorRef = React.useRef<HTMLDivElement | null>(null);
94 const keybindings =
95 useAtomValue(serverEnvironment.configValueAtom(environmentId))?.keybindings ??
96 DEFAULT_RESOLVED_KEYBINDINGS;
97 const [actionsMenuOpen, setActionsMenuOpen] = useState({
98 presentation,
99 scripts: false,
100 imports: false,
101 });
102 if (actionsMenuOpen.presentation !== presentation) {
103 setActionsMenuOpen({ presentation, scripts: false, imports: false });
104 }
105 const [editorRequest, setEditorRequest] = useState<ProjectScriptEditorRequest | null>(null);
106​
107 const primaryScript = useMemo(() => {
108 if (preferredScriptId) {
109 const preferred = scripts.find((script) => script.id === preferredScriptId);
110 if (preferred) return preferred;
111 }
112 return primaryProjectScript(scripts);
113 }, [preferredScriptId, scripts]);
114 const importableScripts = useMemo(
115 () =>
116 fileScripts.filter(
117 (fileScript) =>
118 !scripts.some(
119 (script) =>
120 script.command === fileScript.command ||
121 script.name.toLowerCase() === fileScript.name.toLowerCase(),
122 ),
123 ),
124 [fileScripts, scripts],
125 );
126​
127 const openAddDialog = () => {
128 setEditorRequest({ scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT });
129 };
130​
131 const openEditDialog = (script: ProjectScript) => {
132 onRequestMenuClose?.();
133 setActionsMenuOpen({ presentation, scripts: false, imports: false });
134 setEditorRequest(editorRequestForScript(script, keybindings));
135 };
136​
137 const submitScript = useCallback(
138 (scriptId: string | null, input: NewProjectScriptInput) =>
139 scriptId === null ? onAddScript(input) : onUpdateScript(scriptId, input),
140 [onAddScript, onUpdateScript],
141 );
142​
143 const importFileScript = async (fileScript: T3ProjectFileScript) => {
144 const payload: NewProjectScriptInput = {
145 name: fileScript.name,
146 command: fileScript.command,
147 icon: fileScript.icon ?? "play",
148 runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,
149 waitForSetup: fileScript.runOnWorktreeCreate === true && fileScript.async === false,
150 ...(readEnvironmentScope(environmentId, AuthSettingsWriteScope) ? { keybinding: null } : {}),
151 previewUrl: fileScript.previewUrl ?? null,
152 autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,
153 };
154 const result = await onAddScript(payload);
155 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
156 // Surface the failure through the regular add dialog, prefilled so the
157 // user can adjust and retry.
158 const error = squashAtomCommandFailure(result);
159 setEditorRequest({
160 scriptId: null,
161 initial: payload,
162 error: error instanceof Error ? error.message : "Failed to import action.",
163 });
164 }
165 };
166​
167 const importMenuItems = importableScripts.length > 0 && (
168 <>
169 {primaryScript && <MenuSeparator />}
170 <MenuGroup>
171 <MenuGroupLabel>From t3.json</MenuGroupLabel>
172 {importableScripts.map((fileScript) => (
173 <MenuItem
174 density={presentation === "menu" ? "touch" : "default"}
175 key={`${fileScript.name} ${fileScript.command}`}
176 onClick={() => void importFileScript(fileScript)}
177 >
178 <ScriptIcon icon={fileScript.icon ?? "play"} className="size-4" />
179 <MenuItemLabel>{fileScript.name}</MenuItemLabel>
180 <MenuShortcut>
181 <DownloadIcon className="size-3.5" aria-label="Import" />
182 </MenuShortcut>
183 </MenuItem>
184 ))}
185 </MenuGroup>
186 </>
187 );
188​
189 const scriptItems = (
190 <>
191 {scripts.map((script) => {
192 const shortcutLabel = shortcutLabelForCommand(
193 keybindings,
194 commandForProjectScript(script.id),
195 );
196 return (
197 <MenuItem
198 density={presentation === "menu" ? "touch" : "default"}
199 key={script.id}
200 className="group"
201 disabled={!onRunScript}
202 onClick={() => onRunScript?.(script)}
203 >
204 <ScriptIcon icon={script.icon} className="size-4" />
205 <MenuItemLabel>
206 {script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name}
207 </MenuItemLabel>
208 <span className="relative ms-auto flex h-6 min-w-6 items-center justify-end">
209 {shortcutLabel &&
210 (presentation === "menu" ? (
211 <MenuShortcut className="ms-0 mr-7">{shortcutLabel}</MenuShortcut>
212 ) : (
213 // The shortcut yields its slot to the edit button on hover.
214 <span className="transition-opacity group-hover:opacity-0 group-focus-visible:opacity-0">
215 <MenuShortcut className="ms-0">{shortcutLabel}</MenuShortcut>
216 </span>
217 ))}
218 <span
219 className={`absolute right-0 top-1/2 flex -translate-y-1/2 ${presentation === "menu" ? "" : "opacity-0 pointer-events-none transition-opacity group-hover:opacity-100 group-hover:pointer-events-auto group-focus-visible:opacity-100 group-focus-visible:pointer-events-auto"}`}
220 >
221 <Button
222 type="button"
223 variant="ghost"
224 size="icon-xs"
225 className="size-6"
226 aria-label={`Edit ${script.name}`}
227 onPointerDown={(event) => {
228 event.preventDefault();
229 event.stopPropagation();
230 }}
231 onClick={(event) => {
232 event.preventDefault();
233 event.stopPropagation();
234 openEditDialog(script);
235 }}
236 >
237 <SettingsIcon className="size-3.5" />
238 </Button>
239 </span>
240 </span>
241 </MenuItem>
242 );
243 })}
244 {importMenuItems}
245 <MenuItem density={presentation === "menu" ? "touch" : "default"} onClick={openAddDialog}>
246 <PlusIcon className="size-4" />
247 <MenuItemLabel>{isPanel ? "Add project script" : "Add action"}</MenuItemLabel>
248 </MenuItem>
249 </>
250 );
251​
252 return (
253 <>
254 {presentation === "menu" ? (
255 <>
256 {primaryScript && (
257 <MenuItem
258 density={presentation === "menu" ? "touch" : "default"}
259 disabled={!onRunScript}
260 onClick={() => onRunScript?.(primaryScript)}
261 >
262 <ScriptIcon icon={primaryScript.icon} className="size-4" />
263 <MenuItemLabel>Run {primaryScript.name}</MenuItemLabel>
264 <MenuShortcut>
265 {shortcutLabelForCommand(keybindings, commandForProjectScript(primaryScript.id))}
266 </MenuShortcut>
267 </MenuItem>
268 )}
269 {primaryScript || importableScripts.length > 0 ? (
270 <MenuSub
271 open={actionsMenuOpen.scripts}
272 onOpenChange={(open) =>
273 setActionsMenuOpen({ presentation, scripts: open, imports: false })
274 }
275 >
276 <MenuSubTrigger density="touch">
277 <ScriptIcon icon="play" className="size-4" />
278 <MenuItemLabel>Project actions</MenuItemLabel>
279 </MenuSubTrigger>
280 <MenuSubPopup>{scriptItems}</MenuSubPopup>
281 </MenuSub>
282 ) : (
283 <MenuItem
284 density={presentation === "menu" ? "touch" : "default"}
285 onClick={openAddDialog}
286 >
287 <PlusIcon className="size-4" />
288 <MenuItemLabel>Add project action…</MenuItemLabel>
289 </MenuItem>
290 )}
291 </>
292 ) : primaryScript ? (
293 <ActionGroup
294 role="group"
295 aria-label="Project scripts"
296 {...(isPanel
297 ? { className: THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, ref: panelAnchorRef }
298 : {})}
299 >
300 <Tooltip>
301 <TooltipTrigger
302 render={
303 <ThreadDetailsControl
304 size="xs"
305 variant={isPanel ? "ghost" : "outline"}
306 part="primary"
307 panel={isPanel}
308 className={isPanel ? undefined : "w-7 sm:w-6 @3xl/header-actions:w-auto!"}
309 aria-label={`Run ${primaryScript.name}`}
310 // The tooltip wrapper replaces data-slot="button", so themed
311 // toolbar styling needs its own hook.
312 data-toolbar-control=""
313 aria-disabled={!onRunScript || undefined}
314 onClick={() => onRunScript?.(primaryScript)}
315 />
316 }
317 >
318 <ScriptIcon
319 icon={primaryScript.icon}
320 {...(isPanel ? { className: THREAD_DETAILS_PANEL_ICON_CLASS } : {})}
321 />
322 <span
323 className={cn(
324 "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
325 isPanel && "not-sr-only ml-0 truncate",
326 )}
327 >
328 {primaryScript.name}
329 </span>
330 </TooltipTrigger>
331 <TooltipPopup side="top">
332 {onRunScript
333 ? `Run ${primaryScript.name}`
334 : "Pair this client again with permission to run terminal commands."}
335 </TooltipPopup>
336 </Tooltip>
337 {isPanel ? (
338 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
339 ) : (
340 <GroupSeparator className="hidden @3xl/header-actions:block" />
341 )}
342 <Menu
343 open={actionsMenuOpen.scripts}
344 onOpenChange={(open) =>
345 setActionsMenuOpen({ presentation, scripts: open, imports: false })
346 }
347 >
348 <MenuTrigger
349 render={
350 <ThreadDetailsControl
351 size={isPanel ? "sm" : "icon-xs"}
352 variant={isPanel ? "ghost" : "outline"}
353 part="secondary"
354 panel={isPanel}
355 aria-label="Script actions"
356 />
357 }
358 >
359 <ChevronDownIcon
360 className={isPanel ? THREAD_DETAILS_PANEL_CHEVRON_CLASS : "size-4"}
361 />
362 </MenuTrigger>
363 <MenuPopup
364 align="end"
365 {...(isPanel ? { anchor: panelAnchorRef } : {})}
366 className={isPanel ? "w-(--anchor-width)" : undefined}
367 >
368 {scriptItems}
369 </MenuPopup>
370 </Menu>
371 </ActionGroup>
372 ) : importableScripts.length > 0 ? (
373 isPanel ? (
374 <div
375 role="group"
376 aria-label="Project actions"
377 className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}
378 ref={panelAnchorRef}
379 >
380 <ThreadDetailsControl
381 size="sm"
382 variant="ghost"
383 part="primary"
384 aria-label="Project actions"
385 onClick={() => setActionsMenuOpen({ presentation, scripts: false, imports: true })}
386 >
387 <WrenchIcon className={THREAD_DETAILS_PANEL_ICON_CLASS} />
388 <span className="min-w-0 truncate">Actions</span>
389 </ThreadDetailsControl>
390 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
391 <Menu
392 highlightItemOnHover={false}
393 open={actionsMenuOpen.imports}
394 onOpenChange={(open) =>
395 setActionsMenuOpen({ presentation, scripts: false, imports: open })
396 }
397 >
398 <MenuTrigger
399 render={
400 <ThreadDetailsControl
401 size="sm"
402 variant="ghost"
403 part="secondary"
404 aria-label="Choose project action"
405 />
406 }
407 >
408 <ChevronDownIcon className={THREAD_DETAILS_PANEL_CHEVRON_CLASS} />
409 </MenuTrigger>
410 <MenuPopup align="end" anchor={panelAnchorRef} className="w-(--anchor-width)">
411 {importMenuItems}
412 <MenuItem onClick={openAddDialog}>
413 <PlusIcon className="size-4" />
414 Add action
415 </MenuItem>
416 </MenuPopup>
417 </Menu>
418 </div>
419 ) : (
420 <Menu
421 highlightItemOnHover={false}
422 open={actionsMenuOpen.imports}
423 onOpenChange={(open) =>
424 setActionsMenuOpen({ presentation, scripts: false, imports: open })
425 }
426 >
427 <MenuTrigger
428 render={<Button size="xs" variant="outline" aria-label="Project actions" />}
429 >
430 <WrenchIcon className="size-3.5" />
431 <span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
432 Actions
433 </span>
434 <ChevronDownIcon className="size-3.5" />
435 </MenuTrigger>
436 <MenuPopup align="end">
437 {importMenuItems}
438 <MenuItem onClick={openAddDialog}>
439 <PlusIcon className="size-4" />
440 Add action
441 </MenuItem>
442 </MenuPopup>
443 </Menu>
444 )
445 ) : (
446 <Tooltip>
447 <TooltipTrigger
448 render={
449 <ThreadDetailsControl
450 size="xs"
451 variant={isPanel ? "ghost" : "outline"}
452 part="row"
453 panel={isPanel}
454 className={isPanel ? undefined : "w-7 sm:w-6 @3xl/header-actions:w-auto!"}
455 aria-label={isPanel ? "Add project script" : "Add action"}
456 // The tooltip wrapper replaces data-slot="button", so themed
457 // toolbar styling needs its own hook.
458 data-toolbar-control=""
459 onClick={openAddDialog}
460 />
461 }
462 >
463 <PlusIcon className="size-3.5" />
464 <span
465 className={cn(
466 "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
467 isPanel && "not-sr-only ml-0.5",
468 )}
469 >
470 {isPanel ? "Add project script" : "Add action"}
471 </span>
472 </TooltipTrigger>
473 <TooltipPopup side="top">{isPanel ? "Add project script" : "Add action"}</TooltipPopup>
474 </Tooltip>
475 )}
476​
477 <ProjectScriptEditorDialog
478 environmentId={environmentId}
479 request={editorRequest}
480 scripts={scripts}
481 onSubmit={submitScript}
482 onDelete={(scriptId) => void onDeleteScript(scriptId)}
483 onClose={() => setEditorRequest(null)}
484 />
485 </>
486 );