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

ProjectScriptsControl.tsx

526 lines19.4 KB

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