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

ProjectScriptsControl.tsx

470 lines16.7 KB

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