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