Open History to see the last commit
1import type {
2 ProjectScript,
3 ProjectScriptIcon,
4 ResolvedKeybindingsConfig,
5} from "@t3tools/contracts";
6import {
7 isAtomCommandInterrupted,
8 squashAtomCommandFailure,
9 type AtomCommandResult,
10} from "@t3tools/client-runtime/state/runtime";
11import {
12 BugIcon,
13 ChevronDownIcon,
14 FlaskConicalIcon,
15 HammerIcon,
16 ListChecksIcon,
17 PlayIcon,
18 PlusIcon,
19 SettingsIcon,
20 WrenchIcon,
21} from "lucide-react";
22import React, { type FormEvent, type KeyboardEvent, useCallback, useMemo, useState } from "react";
23
24import {
25 keybindingValueForCommand,
26 decodeProjectScriptKeybindingRule,
27} from "~/lib/projectScriptKeybindings";
28import { keybindingFromKeyboardEvent } from "~/components/settings/KeybindingsSettings.logic";
29import {
30 commandForProjectScript,
31 nextProjectScriptId,
32 primaryProjectScript,
33} from "~/projectScripts";
34import { shortcutLabelForCommand } from "~/keybindings";
35import {
36 AlertDialog,
37 AlertDialogClose,
38 AlertDialogDescription,
39 AlertDialogFooter,
40 AlertDialogHeader,
41 AlertDialogPopup,
42 AlertDialogTitle,
43} from "./ui/alert-dialog";
44import { Button } from "./ui/button";
45import {
46 Dialog,
47 DialogDescription,
48 DialogFooter,
49 DialogHeader,
50 DialogPanel,
51 DialogPopup,
52 DialogTitle,
53} from "./ui/dialog";
54import { Group, GroupSeparator } from "./ui/group";
55import { Input } from "./ui/input";
56import { Label } from "./ui/label";
57import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu";
58import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
59import { Switch } from "./ui/switch";
60import { Textarea } from "./ui/textarea";
61import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
62import { cn } from "~/lib/utils";
63import {
64 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
65 THREAD_DETAILS_PANEL_ICON_CLASS,
66 THREAD_DETAILS_PANEL_ROW_POPUP_CLASS,
67 THREAD_DETAILS_PANEL_ROW_CLASS,
68 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
69 THREAD_DETAILS_PANEL_SPLIT_PRIMARY_CLASS,
70 THREAD_DETAILS_PANEL_SPLIT_SECONDARY_CLASS,
71 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
72} from "./chat/threadDetailsPanelStyles";
73
74const SCRIPT_ICONS: Array<{ id: ProjectScriptIcon; label: string }> = [
75 { id: "play", label: "Play" },
76 { id: "test", label: "Test" },
77 { id: "lint", label: "Lint" },
78 { id: "configure", label: "Configure" },
79 { id: "build", label: "Build" },
80 { id: "debug", label: "Debug" },
81];
82
83function ScriptIcon({
84 icon,
85 className = "size-3.5",
86}: {
87 icon: ProjectScriptIcon;
88 className?: string;
89}) {
90 if (icon === "test") return <FlaskConicalIcon className={className} />;
91 if (icon === "lint") return <ListChecksIcon className={className} />;
92 if (icon === "configure") return <WrenchIcon className={className} />;
93 if (icon === "build") return <HammerIcon className={className} />;
94 if (icon === "debug") return <BugIcon className={className} />;
95 return <PlayIcon className={className} />;
96}
97
98export interface NewProjectScriptInput {
99 name: string;
100 command: string;
101 icon: ProjectScriptIcon;
102 runOnWorktreeCreate: boolean;
103 keybinding: string | null;
104 /** Optional URL to open in the in-app preview when this script runs. */
105 previewUrl: string | null;
106 /** When true, automatically open the preview panel pointed at `previewUrl`. */
107 autoOpenPreview: boolean;
108}
109
110export type ProjectScriptActionResult = AtomCommandResult<void, unknown>;
111
112interface ProjectScriptsControlProps {
113 displayMode?: "toolbar" | "panel";
114 scripts: ReadonlyArray<ProjectScript>;
115 keybindings: ResolvedKeybindingsConfig;
116 preferredScriptId?: string | null;
117 onRunScript: (script: ProjectScript) => void;
118 onAddScript: (input: NewProjectScriptInput) => Promise<ProjectScriptActionResult>;
119 onUpdateScript: (
120 scriptId: string,
121 input: NewProjectScriptInput,
122 ) => Promise<ProjectScriptActionResult>;
123 onDeleteScript: (scriptId: string) => Promise<ProjectScriptActionResult>;
124}
125
126export default function ProjectScriptsControl({
127 displayMode = "toolbar",
128 scripts,
129 keybindings,
130 preferredScriptId = null,
131 onRunScript,
132 onAddScript,
133 onUpdateScript,
134 onDeleteScript,
135}: ProjectScriptsControlProps) {
136 const isPanel = displayMode === "panel";
137 const ActionGroup = isPanel ? "div" : Group;
138 const panelAnchorRef = React.useRef<HTMLDivElement | null>(null);
139 const addScriptFormId = React.useId();
140 const [editingScriptId, setEditingScriptId] = useState<string | null>(null);
141 const [dialogOpen, setDialogOpen] = useState(false);
142 const [name, setName] = useState("");
143 const [command, setCommand] = useState("");
144 const [icon, setIcon] = useState<ProjectScriptIcon>("play");
145 const [iconPickerOpen, setIconPickerOpen] = useState(false);
146 const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);
147 const [keybinding, setKeybinding] = useState("");
148 const [previewUrl, setPreviewUrl] = useState("");
149 const [autoOpenPreview, setAutoOpenPreview] = useState(false);
150 const [validationError, setValidationError] = useState<string | null>(null);
151 const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
152
153 const primaryScript = useMemo(() => {
154 if (preferredScriptId) {
155 const preferred = scripts.find((script) => script.id === preferredScriptId);
156 if (preferred) return preferred;
157 }
158 return primaryProjectScript(scripts);
159 }, [preferredScriptId, scripts]);
160 const isEditing = editingScriptId !== null;
161 const dropdownItemClassName =
162 "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";
163
164 const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
165 if (event.key === "Tab") return;
166 event.preventDefault();
167 if (event.key === "Backspace" || event.key === "Delete") {
168 setKeybinding("");
169 return;
170 }
171 const next = keybindingFromKeyboardEvent(event, navigator.platform);
172 if (!next) return;
173 setKeybinding(next);
174 };
175
176 const submitAddScript = async (event: FormEvent) => {
177 event.preventDefault();
178 const trimmedName = name.trim();
179 const trimmedCommand = command.trim();
180 if (trimmedName.length === 0) {
181 setValidationError("Name is required.");
182 return;
183 }
184 if (trimmedCommand.length === 0) {
185 setValidationError("Command is required.");
186 return;
187 }
188
189 setValidationError(null);
190 let payload: NewProjectScriptInput;
191 try {
192 const scriptIdForValidation =
193 editingScriptId ??
194 nextProjectScriptId(
195 trimmedName,
196 scripts.map((script) => script.id),
197 );
198 const keybindingRule = decodeProjectScriptKeybindingRule({
199 keybinding,
200 command: commandForProjectScript(scriptIdForValidation),
201 });
202 const trimmedPreviewUrl = previewUrl.trim();
203 payload = {
204 name: trimmedName,
205 command: trimmedCommand,
206 icon,
207 runOnWorktreeCreate,
208 keybinding: keybindingRule?.key ?? null,
209 previewUrl: trimmedPreviewUrl.length > 0 ? trimmedPreviewUrl : null,
210 autoOpenPreview: trimmedPreviewUrl.length > 0 ? autoOpenPreview : false,
211 } satisfies NewProjectScriptInput;
212 } catch (error) {
213 setValidationError(error instanceof Error ? error.message : "Failed to save action.");
214 return;
215 }
216
217 const result = editingScriptId
218 ? await onUpdateScript(editingScriptId, payload)
219 : await onAddScript(payload);
220 if (result._tag === "Failure") {
221 if (!isAtomCommandInterrupted(result)) {
222 const error = squashAtomCommandFailure(result);
223 setValidationError(error instanceof Error ? error.message : "Failed to save action.");
224 }
225 return;
226 }
227 setDialogOpen(false);
228 setIconPickerOpen(false);
229 };
230
231 const openAddDialog = () => {
232 setEditingScriptId(null);
233 setName("");
234 setCommand("");
235 setIcon("play");
236 setIconPickerOpen(false);
237 setRunOnWorktreeCreate(false);
238 setKeybinding("");
239 setPreviewUrl("");
240 setAutoOpenPreview(false);
241 setValidationError(null);
242 setDialogOpen(true);
243 };
244
245 const openEditDialog = (script: ProjectScript) => {
246 setEditingScriptId(script.id);
247 setName(script.name);
248 setCommand(script.command);
249 setIcon(script.icon);
250 setIconPickerOpen(false);
251 setRunOnWorktreeCreate(script.runOnWorktreeCreate);
252 setKeybinding(keybindingValueForCommand(keybindings, commandForProjectScript(script.id)) ?? "");
253 setPreviewUrl(script.previewUrl ?? "");
254 setAutoOpenPreview(script.autoOpenPreview ?? false);
255 setValidationError(null);
256 setDialogOpen(true);
257 };
258
259 const confirmDeleteScript = useCallback(() => {
260 if (!editingScriptId) return;
261 setDeleteConfirmOpen(false);
262 setDialogOpen(false);
263 void onDeleteScript(editingScriptId);
264 }, [editingScriptId, onDeleteScript]);
265
266 return (
267 <>
268 {primaryScript ? (
269 <ActionGroup
270 role="group"
271 aria-label="Project scripts"
272 {...(isPanel
273 ? { className: THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, ref: panelAnchorRef }
274 : {})}
275 >
276 <Tooltip>
277 <TooltipTrigger
278 render={
279 <Button
280 size="xs"
281 variant={isPanel ? "ghost" : "outline"}
282 className={isPanel ? THREAD_DETAILS_PANEL_SPLIT_PRIMARY_CLASS : undefined}
283 aria-label={`Run ${primaryScript.name}`}
284 onClick={() => onRunScript(primaryScript)}
285 />
286 }
287 >
288 <ScriptIcon
289 icon={primaryScript.icon}
290 {...(isPanel ? { className: THREAD_DETAILS_PANEL_ICON_CLASS } : {})}
291 />
292 <span
293 className={cn(
294 "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
295 isPanel && "not-sr-only ml-0.5 truncate",
296 )}
297 >
298 {primaryScript.name}
299 </span>
300 </TooltipTrigger>
301 <TooltipPopup side="top">Run {primaryScript.name}</TooltipPopup>
302 </Tooltip>
303 {isPanel ? (
304 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
305 ) : (
306 <GroupSeparator className="hidden @3xl/header-actions:block" />
307 )}
308 <Menu highlightItemOnHover={false}>
309 <MenuTrigger
310 render={
311 <Button
312 size={isPanel ? "sm" : "icon-xs"}
313 variant={isPanel ? "ghost" : "outline"}
314 className={isPanel ? THREAD_DETAILS_PANEL_SPLIT_SECONDARY_CLASS : undefined}
315 aria-label="Script actions"
316 />
317 }
318 >
319 <ChevronDownIcon
320 className={isPanel ? THREAD_DETAILS_PANEL_CHEVRON_CLASS : "size-4"}
321 />
322 </MenuTrigger>
323 <MenuPopup
324 align="end"
325 {...(isPanel ? { anchor: panelAnchorRef } : {})}
326 className={isPanel ? THREAD_DETAILS_PANEL_ROW_POPUP_CLASS : undefined}
327 >
328 {scripts.map((script) => {
329 const shortcutLabel = shortcutLabelForCommand(
330 keybindings,
331 commandForProjectScript(script.id),
332 );
333 return (
334 <MenuItem
335 key={script.id}
336 className={`group ${dropdownItemClassName}`}
337 onClick={() => onRunScript(script)}
338 >
339 <ScriptIcon icon={script.icon} className="size-4" />
340 <span className="truncate">
341 {script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name}
342 </span>
343 <span className="relative ms-auto flex h-6 min-w-6 items-center justify-end">
344 {shortcutLabel && (
345 <MenuShortcut className="ms-0 transition-opacity group-hover:opacity-0 group-focus-visible:opacity-0">
346 {shortcutLabel}
347 </MenuShortcut>
348 )}
349 <Button
350 type="button"
351 variant="ghost"
352 size="icon-xs"
353 className="absolute right-0 top-1/2 size-6 -translate-y-1/2 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"
354 aria-label={`Edit ${script.name}`}
355 onPointerDown={(event) => {
356 event.preventDefault();
357 event.stopPropagation();
358 }}
359 onClick={(event) => {
360 event.preventDefault();
361 event.stopPropagation();
362 openEditDialog(script);
363 }}
364 >
365 <SettingsIcon className="size-3.5" />
366 </Button>
367 </span>
368 </MenuItem>
369 );
370 })}
371 <MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
372 <PlusIcon className="size-4" />
373 {isPanel ? "Add project script" : "Add action"}
374 </MenuItem>
375 </MenuPopup>
376 </Menu>
377 </ActionGroup>
378 ) : (
379 <Tooltip>
380 <TooltipTrigger
381 render={
382 <Button
383 size="xs"
384 variant={isPanel ? "ghost" : "outline"}
385 className={isPanel ? THREAD_DETAILS_PANEL_ROW_CLASS : undefined}
386 aria-label={isPanel ? "Add project script" : "Add action"}
387 onClick={openAddDialog}
388 />
389 }
390 >
391 <PlusIcon className="size-3.5" />
392 <span
393 className={cn(
394 "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
395 isPanel && "not-sr-only ml-0.5",
396 )}
397 >
398 {isPanel ? "Add project script" : "Add action"}
399 </span>
400 </TooltipTrigger>
401 <TooltipPopup side="top">{isPanel ? "Add project script" : "Add action"}</TooltipPopup>
402 </Tooltip>
403 )}
404
405 <Dialog
406 onOpenChange={(open) => {
407 setDialogOpen(open);
408 if (!open) {
409 setIconPickerOpen(false);
410 }
411 }}
412 onOpenChangeComplete={(open) => {
413 if (open) return;
414 setEditingScriptId(null);
415 setName("");
416 setCommand("");
417 setIcon("play");
418 setRunOnWorktreeCreate(false);
419 setKeybinding("");
420 setPreviewUrl("");
421 setAutoOpenPreview(false);
422 setValidationError(null);
423 }}
424 open={dialogOpen}
425 >
426 <DialogPopup>
427 <DialogHeader>
428 <DialogTitle>{isEditing ? "Edit Action" : "Add Action"}</DialogTitle>
429 <DialogDescription>
430 Actions are project-scoped commands you can run from the top bar or keybindings.
431 </DialogDescription>
432 </DialogHeader>
433 <DialogPanel>
434 <form id={addScriptFormId} className="space-y-4" onSubmit={submitAddScript}>
435 <div className="space-y-1.5">
436 <Label htmlFor="script-name">Name</Label>
437 <div className="flex items-center gap-2">
438 <Popover onOpenChange={setIconPickerOpen} open={iconPickerOpen}>
439 <PopoverTrigger
440 render={
441 <Button
442 type="button"
443 variant="outline"
444 className="size-9 shrink-0 hover:bg-popover active:bg-popover data-pressed:bg-popover data-pressed:shadow-xs/5 data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)]"
445 aria-label="Choose icon"
446 />
447 }
448 >
449 <ScriptIcon icon={icon} className="size-4.5" />
450 </PopoverTrigger>
451 <PopoverPopup align="start">
452 <div className="grid grid-cols-3 gap-2">
453 {SCRIPT_ICONS.map((entry) => {
454 const isSelected = entry.id === icon;
455 return (
456 <button
457 key={entry.id}
458 type="button"
459 className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs ${
460 isSelected
461 ? "border-primary/70 bg-primary/10"
462 : "border-border/70 hover:bg-accent/60"
463 }`}
464 onClick={() => {
465 setIcon(entry.id);
466 setIconPickerOpen(false);
467 }}
468 >
469 <ScriptIcon icon={entry.id} className="size-4" />
470 <span>{entry.label}</span>
471 </button>
472 );
473 })}
474 </div>
475 </PopoverPopup>
476 </Popover>
477 <Input
478 id="script-name"
479 autoFocus
480 placeholder="Test"
481 value={name}
482 onChange={(event) => setName(event.target.value)}
483 />
484 </div>
485 </div>
486 <div className="space-y-1.5">
487 <Label htmlFor="script-keybinding">Keybinding</Label>
488 <Input
489 id="script-keybinding"
490 placeholder="Press shortcut"
491 value={keybinding}
492 readOnly
493 onKeyDown={captureKeybinding}
494 />
495 <p className="text-xs text-muted-foreground">
496 Press a shortcut. Use <code>Backspace</code> to clear.
497 </p>
498 </div>
499 <div className="space-y-1.5">
500 <Label htmlFor="script-command">Command</Label>
501 <Textarea
502 id="script-command"
503 placeholder="bun test"
504 value={command}
505 onChange={(event) => setCommand(event.target.value)}
506 />
507 </div>
508 <div className="space-y-1.5">
509 <Label htmlFor="script-preview-url">Preview URL (optional)</Label>
510 <Input
511 id="script-preview-url"
512 placeholder="http://localhost:5173"
513 value={previewUrl}
514 onChange={(event) => setPreviewUrl(event.target.value)}
515 />
516 <p className="text-xs text-muted-foreground">
517 Open this URL in the in-app preview when this action runs.
518 </p>
519 </div>
520 <label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm">
521 <span>Run automatically on worktree creation</span>
522 <Switch
523 checked={runOnWorktreeCreate}
524 onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
525 />
526 </label>
527 <label
528 className={`flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm ${
529 previewUrl.trim().length === 0 ? "opacity-60" : ""
530 }`}
531 >
532 <span>Open preview automatically when this action runs</span>
533 <Switch
534 checked={autoOpenPreview}
535 disabled={previewUrl.trim().length === 0}
536 onCheckedChange={(checked) => setAutoOpenPreview(Boolean(checked))}
537 />
538 </label>
539 {validationError && <p className="text-sm text-destructive">{validationError}</p>}
540 </form>
541 </DialogPanel>
542 <DialogFooter>
543 {isEditing && (
544 <Button
545 type="button"
546 variant="destructive-outline"
547 className="mr-auto"
548 onClick={() => setDeleteConfirmOpen(true)}
549 >
550 Delete
551 </Button>
552 )}
553 <Button
554 type="button"
555 variant="outline"
556 onClick={() => {
557 setDialogOpen(false);
558 }}
559 >
560 Cancel
561 </Button>
562 <Button form={addScriptFormId} type="submit">
563 {isEditing ? "Save changes" : "Save action"}
564 </Button>
565 </DialogFooter>
566 </DialogPopup>
567 </Dialog>
568
569 <AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
570 <AlertDialogPopup>
571 <AlertDialogHeader>
572 <AlertDialogTitle>Delete action "{name}"?</AlertDialogTitle>
573 <AlertDialogDescription>This action cannot be undone.</AlertDialogDescription>
574 </AlertDialogHeader>
575 <AlertDialogFooter>
576 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
577 <Button variant="destructive" onClick={confirmDeleteScript}>
578 Delete action
579 </Button>
580 </AlertDialogFooter>
581 </AlertDialogPopup>
582 </AlertDialog>
583 </>
584 );
585}