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