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