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