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