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 className="w-7 px-0 sm:w-6 @3xl/header-actions:w-auto! @3xl/header-actions:px-[calc(--spacing(2)-1px)]"
345 aria-label={`Run ${primaryScript.name}`}
346 onClick={() => onRunScript(primaryScript)}
347 />
348 }
349 >
350 <ScriptIcon icon={primaryScript.icon} />
351 <span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
352 {primaryScript.name}
353 </span>
354 </TooltipTrigger>
355 <TooltipPopup side="top">Run {primaryScript.name}</TooltipPopup>
356 </Tooltip>
357 <GroupSeparator className="hidden @3xl/header-actions:block" />
358 <Menu
359 highlightItemOnHover={false}
360 open={actionsMenuOpen.scripts}
361 onOpenChange={(open) => setActionsMenuOpen({ scripts: open, imports: false })}
362 >
363 <MenuTrigger
364 render={<Button size="icon-xs" variant="outline" aria-label="Script actions" />}
365 >
366 <ChevronDownIcon className="size-4" />
367 </MenuTrigger>
368 <MenuPopup align="end">
369 {scripts.map((script) => {
370 const shortcutLabel = shortcutLabelForCommand(
371 keybindings,
372 commandForProjectScript(script.id),
373 );
374 return (
375 <MenuItem
376 key={script.id}
377 className={`group ${dropdownItemClassName}`}
378 onClick={() => onRunScript(script)}
379 >
380 <ScriptIcon icon={script.icon} className="size-4" />
381 <span className="truncate">
382 {script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name}
383 </span>
384 <span className="relative ms-auto flex h-6 min-w-6 items-center justify-end">
385 {shortcutLabel && (
386 <MenuShortcut className="ms-0 transition-opacity group-hover:opacity-0 group-focus-visible:opacity-0">
387 {shortcutLabel}
388 </MenuShortcut>
389 )}
390 <Button
391 type="button"
392 variant="ghost"
393 size="icon-xs"
394 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"
395 aria-label={`Edit ${script.name}`}
396 onPointerDown={(event) => {
397 event.preventDefault();
398 event.stopPropagation();
399 }}
400 onClick={(event) => {
401 event.preventDefault();
402 event.stopPropagation();
403 openEditDialog(script);
404 }}
405 >
406 <SettingsIcon className="size-3.5" />
407 </Button>
408 </span>
409 </MenuItem>
410 );
411 })}
412 {importMenuItems}
413 <MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
414 <PlusIcon className="size-4" />
415 Add action
416 </MenuItem>
417 </MenuPopup>
418 </Menu>
419 </Group>
420 ) : importableScripts.length > 0 ? (
421 <Menu
422 highlightItemOnHover={false}
423 open={actionsMenuOpen.imports}
424 onOpenChange={(open) => setActionsMenuOpen({ scripts: false, imports: open })}
425 >
426 <MenuTrigger render={<Button size="xs" variant="outline" aria-label="Project actions" />}>
427 <PlusIcon className="size-3.5" />
428 <span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
429 Add action
430 </span>
431 <ChevronDownIcon className="size-3.5" />
432 </MenuTrigger>
433 <MenuPopup align="end">
434 {importMenuItems}
435 <MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
436 <PlusIcon className="size-4" />
437 Add action
438 </MenuItem>
439 </MenuPopup>
440 </Menu>
441 ) : (
442 <Tooltip>
443 <TooltipTrigger
444 render={
445 <Button
446 size="xs"
447 variant="outline"
448 className="w-7 px-0 sm:w-6 @3xl/header-actions:w-auto! @3xl/header-actions:px-[calc(--spacing(2)-1px)]"
449 aria-label="Add action"
450 onClick={openAddDialog}
451 />
452 }
453 >
454 <PlusIcon className="size-3.5" />
455 <span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
456 Add action
457 </span>
458 </TooltipTrigger>
459 <TooltipPopup side="top">Add action</TooltipPopup>
460 </Tooltip>
461 )}
462
463 <Dialog
464 onOpenChange={(open) => {
465 setDialogOpen(open);
466 if (!open) {
467 setIconPickerOpen(false);
468 }
469 }}
470 onOpenChangeComplete={(open) => {
471 if (open) return;
472 setEditingScriptId(null);
473 setName("");
474 setCommand("");
475 setIcon("play");
476 setRunOnWorktreeCreate(false);
477 setKeybinding("");
478 setPreviewUrl("");
479 setAutoOpenPreview(false);
480 setValidationError(null);
481 }}
482 open={dialogOpen}
483 >
484 <DialogPopup>
485 <DialogHeader>
486 <DialogTitle>{isEditing ? "Edit Action" : "Add Action"}</DialogTitle>
487 <DialogDescription>
488 Actions are project-scoped commands you can run from the top bar or keybindings.
489 </DialogDescription>
490 </DialogHeader>
491 <DialogPanel>
492 <form id={addScriptFormId} className="space-y-4" onSubmit={submitAddScript}>
493 <div className="space-y-1.5">
494 <Label htmlFor="script-name">Name</Label>
495 <div className="flex items-center gap-2">
496 <Popover onOpenChange={setIconPickerOpen} open={iconPickerOpen}>
497 <PopoverTrigger
498 render={
499 <Button
500 type="button"
501 variant="outline"
502 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"
503 aria-label="Choose icon"
504 />
505 }
506 >
507 <ScriptIcon icon={icon} className="size-4.5" />
508 </PopoverTrigger>
509 <PopoverPopup align="start">
510 <div className="grid grid-cols-3 gap-2">
511 {SCRIPT_ICONS.map((entry) => {
512 const isSelected = entry.id === icon;
513 return (
514 <button
515 key={entry.id}
516 type="button"
517 className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs dark:border-transparent ${
518 isSelected
519 ? "border-primary/70 bg-primary/10 dark:ring-1 dark:ring-primary/30"
520 : "border-border/70 hover:bg-accent/60 dark:bg-white/[0.035]"
521 }`}
522 onClick={() => {
523 setIcon(entry.id);
524 setIconPickerOpen(false);
525 }}
526 >
527 <ScriptIcon icon={entry.id} className="size-4" />
528 <span>{entry.label}</span>
529 </button>
530 );
531 })}
532 </div>
533 </PopoverPopup>
534 </Popover>
535 <Input
536 id="script-name"
537 autoFocus
538 placeholder="Test"
539 value={name}
540 onChange={(event) => setName(event.target.value)}
541 />
542 </div>
543 </div>
544 <div className="space-y-1.5">
545 <Label htmlFor="script-keybinding">Keybinding</Label>
546 <Input
547 id="script-keybinding"
548 placeholder="Press shortcut"
549 value={keybinding}
550 readOnly
551 onKeyDown={captureKeybinding}
552 />
553 <p className="text-xs text-muted-foreground">
554 Press a shortcut. Use <code>Backspace</code> to clear.
555 </p>
556 </div>
557 <div className="space-y-1.5">
558 <Label htmlFor="script-command">Command</Label>
559 <Textarea
560 id="script-command"
561 placeholder="bun test"
562 value={command}
563 onChange={(event) => setCommand(event.target.value)}
564 />
565 </div>
566 <div className="space-y-1.5">
567 <Label htmlFor="script-preview-url">Preview URL (optional)</Label>
568 <Input
569 id="script-preview-url"
570 placeholder="http://localhost:5173"
571 value={previewUrl}
572 onChange={(event) => setPreviewUrl(event.target.value)}
573 />
574 <p className="text-xs text-muted-foreground">
575 Open this URL in the in-app preview when this action runs.
576 </p>
577 </div>
578 <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]">
579 <span>Run automatically on worktree creation</span>
580 <Switch
581 checked={runOnWorktreeCreate}
582 onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
583 />
584 </label>
585 <label
586 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] ${
587 previewUrl.trim().length === 0 ? "opacity-60" : ""
588 }`}
589 >
590 <span>Open preview automatically when this action runs</span>
591 <Switch
592 checked={autoOpenPreview}
593 disabled={previewUrl.trim().length === 0}
594 onCheckedChange={(checked) => setAutoOpenPreview(Boolean(checked))}
595 />
596 </label>
597 {validationError && <p className="text-sm text-destructive">{validationError}</p>}
598 </form>
599 </DialogPanel>
600 <DialogFooter className="dark:border-transparent dark:bg-transparent">
601 {isEditing && (
602 <Button
603 type="button"
604 variant="destructive-outline"
605 className="mr-auto"
606 onClick={() => setDeleteConfirmOpen(true)}
607 >
608 Delete
609 </Button>
610 )}
611 <Button
612 type="button"
613 variant="outline"
614 onClick={() => {
615 setDialogOpen(false);
616 }}
617 >
618 Cancel
619 </Button>
620 <Button form={addScriptFormId} type="submit">
621 {isEditing ? "Save changes" : "Save action"}
622 </Button>
623 </DialogFooter>
624 </DialogPopup>
625 </Dialog>
626
627 <AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
628 <AlertDialogPopup>
629 <AlertDialogHeader>
630 <AlertDialogTitle>Delete action "{name}"?</AlertDialogTitle>
631 <AlertDialogDescription>This action cannot be undone.</AlertDialogDescription>
632 </AlertDialogHeader>
633 <AlertDialogFooter>
634 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
635 <Button variant="destructive" onClick={confirmDeleteScript}>
636 Delete action
637 </Button>
638 </AlertDialogFooter>
639 </AlertDialogPopup>
640 </AlertDialog>
641 </>
642 );
643}