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

ProjectScriptsControl.tsx

623 lines23.0 KB

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