Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProjectScriptsControl.tsx

508 lines18.8 KB

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