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