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