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