Open History to see the last commit
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 FlaskConicalIcon,
14 HammerIcon,
15 ListChecksIcon,
16 PlayIcon,
17 WrenchIcon,
18} from "lucide-react";
19import React, { type FormEvent, type KeyboardEvent, useEffect, useState } from "react";
20
21import {
22 keybindingValueForCommand,
23 decodeProjectScriptKeybindingRule,
24} from "~/lib/projectScriptKeybindings";
25import { keybindingFromKeyboardEvent } from "~/components/settings/KeybindingsSettings.logic";
26import { commandForProjectScript, nextProjectScriptId } from "~/projectScripts";
27import {
28 AlertDialog,
29 AlertDialogClose,
30 AlertDialogDescription,
31 AlertDialogFooter,
32 AlertDialogHeader,
33 AlertDialogPopup,
34 AlertDialogTitle,
35} from "./ui/alert-dialog";
36import { Button } from "./ui/button";
37import {
38 Dialog,
39 DialogDescription,
40 DialogFooter,
41 DialogHeader,
42 DialogPanel,
43 DialogPopup,
44 DialogTitle,
45} from "./ui/dialog";
46import { Input } from "./ui/input";
47import { Label } from "./ui/label";
48import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
49import { Switch } from "./ui/switch";
50import { Textarea } from "./ui/textarea";
51
52const SCRIPT_ICONS: Array<{ id: ProjectScriptIcon; label: string }> = [
53 { id: "play", label: "Play" },
54 { id: "test", label: "Test" },
55 { id: "lint", label: "Lint" },
56 { id: "configure", label: "Configure" },
57 { id: "build", label: "Build" },
58 { id: "debug", label: "Debug" },
59];
60
61export function ScriptIcon({
62 icon,
63 className = "size-3.5",
64}: {
65 icon: ProjectScriptIcon;
66 className?: string;
67}) {
68 if (icon === "test") return <FlaskConicalIcon className={className} />;
69 if (icon === "lint") return <ListChecksIcon className={className} />;
70 if (icon === "configure") return <WrenchIcon className={className} />;
71 if (icon === "build") return <HammerIcon className={className} />;
72 if (icon === "debug") return <BugIcon className={className} />;
73 return <PlayIcon className={className} />;
74}
75
76export interface NewProjectScriptInput {
77 name: string;
78 command: string;
79 icon: ProjectScriptIcon;
80 runOnWorktreeCreate: boolean;
81 keybinding: string | null;
82 /** Optional URL to open in the in-app preview when this script runs. */
83 previewUrl: string | null;
84 /** When true, automatically open the preview panel pointed at `previewUrl`. */
85 autoOpenPreview: boolean;
86}
87
88export type ProjectScriptActionResult = AtomCommandResult<void, unknown>;
89
90export const EMPTY_PROJECT_SCRIPT_INPUT: NewProjectScriptInput = {
91 name: "",
92 command: "",
93 icon: "play",
94 runOnWorktreeCreate: false,
95 keybinding: null,
96 previewUrl: null,
97 autoOpenPreview: false,
98};
99
100/** What the editor dialog should open with. `scriptId: null` means "add". */
101export interface ProjectScriptEditorRequest {
102 scriptId: string | null;
103 initial: NewProjectScriptInput;
104 /** Validation error to show immediately (e.g. a failed t3.json import). */
105 error?: string;
106}
107
108export function editorRequestForScript(
109 script: ProjectScript,
110 keybindings: ResolvedKeybindingsConfig,
111): ProjectScriptEditorRequest {
112 return {
113 scriptId: script.id,
114 initial: {
115 name: script.name,
116 command: script.command,
117 icon: script.icon,
118 runOnWorktreeCreate: script.runOnWorktreeCreate,
119 keybinding: keybindingValueForCommand(keybindings, commandForProjectScript(script.id)),
120 previewUrl: script.previewUrl ?? null,
121 autoOpenPreview: script.autoOpenPreview ?? false,
122 },
123 };
124}
125
126/**
127 * Add/edit dialog for a project script, shared by the chat-header scripts menu
128 * and the project settings page. The parent owns which script (if any) is
129 * being edited via `request`; the dialog owns the form state and validation.
130 */
131export function ProjectScriptEditorDialog({
132 request,
133 scripts,
134 onSubmit,
135 onDelete,
136 onClose,
137}: {
138 request: ProjectScriptEditorRequest | null;
139 /** Existing scripts, used to derive a unique id for new scripts. */
140 scripts: ReadonlyArray<ProjectScript>;
141 onSubmit: (
142 scriptId: string | null,
143 input: NewProjectScriptInput,
144 ) => Promise<ProjectScriptActionResult>;
145 onDelete: (scriptId: string) => void;
146 onClose: () => void;
147}) {
148 const formId = React.useId();
149 const [name, setName] = useState("");
150 const [command, setCommand] = useState("");
151 const [icon, setIcon] = useState<ProjectScriptIcon>("play");
152 const [iconPickerOpen, setIconPickerOpen] = useState(false);
153 const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);
154 const [keybinding, setKeybinding] = useState("");
155 const [previewUrl, setPreviewUrl] = useState("");
156 const [autoOpenPreview, setAutoOpenPreview] = useState(false);
157 const [validationError, setValidationError] = useState<string | null>(null);
158 const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
159
160 const isOpen = request !== null;
161 const isEditing = request?.scriptId != null;
162
163 // Hydrate the form whenever a new request opens the dialog.
164 useEffect(() => {
165 if (!request) return;
166 setName(request.initial.name);
167 setCommand(request.initial.command);
168 setIcon(request.initial.icon);
169 setIconPickerOpen(false);
170 setRunOnWorktreeCreate(request.initial.runOnWorktreeCreate);
171 setKeybinding(request.initial.keybinding ?? "");
172 setPreviewUrl(request.initial.previewUrl ?? "");
173 setAutoOpenPreview(request.initial.autoOpenPreview);
174 setValidationError(request.error ?? null);
175 }, [request]);
176
177 const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
178 if (event.key === "Tab") return;
179 event.preventDefault();
180 if (event.key === "Backspace" || event.key === "Delete") {
181 setKeybinding("");
182 return;
183 }
184 const next = keybindingFromKeyboardEvent(event, navigator.platform);
185 if (!next) return;
186 setKeybinding(next);
187 };
188
189 const submit = async (event: FormEvent) => {
190 event.preventDefault();
191 if (!request) return;
192 const trimmedName = name.trim();
193 const trimmedCommand = command.trim();
194 if (trimmedName.length === 0) {
195 setValidationError("Name is required.");
196 return;
197 }
198 if (trimmedCommand.length === 0) {
199 setValidationError("Command is required.");
200 return;
201 }
202
203 setValidationError(null);
204 let payload: NewProjectScriptInput;
205 try {
206 const scriptIdForValidation =
207 request.scriptId ??
208 nextProjectScriptId(
209 trimmedName,
210 scripts.map((script) => script.id),
211 );
212 const keybindingRule = decodeProjectScriptKeybindingRule({
213 keybinding,
214 command: commandForProjectScript(scriptIdForValidation),
215 });
216 const trimmedPreviewUrl = previewUrl.trim();
217 payload = {
218 name: trimmedName,
219 command: trimmedCommand,
220 icon,
221 runOnWorktreeCreate,
222 keybinding: keybindingRule?.key ?? null,
223 previewUrl: trimmedPreviewUrl.length > 0 ? trimmedPreviewUrl : null,
224 autoOpenPreview: trimmedPreviewUrl.length > 0 ? autoOpenPreview : false,
225 } satisfies NewProjectScriptInput;
226 } catch (error) {
227 setValidationError(error instanceof Error ? error.message : "Failed to save action.");
228 return;
229 }
230
231 const result = await onSubmit(request.scriptId, 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 setIconPickerOpen(false);
240 onClose();
241 };
242
243 return (
244 <>
245 <Dialog
246 open={isOpen}
247 onOpenChange={(open) => {
248 if (!open) {
249 setIconPickerOpen(false);
250 onClose();
251 }
252 }}
253 >
254 <DialogPopup>
255 <DialogHeader>
256 <DialogTitle>{isEditing ? "Edit Action" : "Add Action"}</DialogTitle>
257 <DialogDescription>
258 Actions are project-scoped commands you can run from the top bar or keybindings.
259 </DialogDescription>
260 </DialogHeader>
261 <DialogPanel>
262 <form id={formId} className="space-y-4" onSubmit={submit}>
263 <div className="space-y-1.5">
264 <Label htmlFor="script-name">Name</Label>
265 <div className="flex items-center gap-2">
266 <Popover onOpenChange={setIconPickerOpen} open={iconPickerOpen}>
267 <PopoverTrigger
268 render={
269 <Button
270 type="button"
271 variant="outline"
272 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"
273 aria-label="Choose icon"
274 />
275 }
276 >
277 <ScriptIcon icon={icon} className="size-4.5" />
278 </PopoverTrigger>
279 <PopoverPopup align="start">
280 <div className="grid grid-cols-3 gap-2">
281 {SCRIPT_ICONS.map((entry) => {
282 const isSelected = entry.id === icon;
283 return (
284 <button
285 key={entry.id}
286 type="button"
287 className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs dark:border-transparent ${
288 isSelected
289 ? "border-primary/70 bg-primary/10 dark:ring-1 dark:ring-primary/30"
290 : "border-border/70 hover:bg-accent/60 dark:bg-white/[0.035]"
291 }`}
292 onClick={() => {
293 setIcon(entry.id);
294 setIconPickerOpen(false);
295 }}
296 >
297 <ScriptIcon icon={entry.id} className="size-4" />
298 <span>{entry.label}</span>
299 </button>
300 );
301 })}
302 </div>
303 </PopoverPopup>
304 </Popover>
305 <Input
306 id="script-name"
307 autoFocus
308 placeholder="Test"
309 value={name}
310 onChange={(event) => setName(event.target.value)}
311 />
312 </div>
313 </div>
314 <div className="space-y-1.5">
315 <Label htmlFor="script-keybinding">Keybinding</Label>
316 <Input
317 id="script-keybinding"
318 placeholder="Press shortcut"
319 value={keybinding}
320 readOnly
321 onKeyDown={captureKeybinding}
322 />
323 <p className="text-xs text-muted-foreground">
324 Press a shortcut. Use <code>Backspace</code> to clear.
325 </p>
326 </div>
327 <div className="space-y-1.5">
328 <Label htmlFor="script-command">Command</Label>
329 <Textarea
330 id="script-command"
331 placeholder="bun test"
332 value={command}
333 onChange={(event) => setCommand(event.target.value)}
334 />
335 </div>
336 <div className="space-y-1.5">
337 <Label htmlFor="script-preview-url">Preview URL (optional)</Label>
338 <Input
339 id="script-preview-url"
340 placeholder="http://localhost:5173"
341 value={previewUrl}
342 onChange={(event) => setPreviewUrl(event.target.value)}
343 />
344 <p className="text-xs text-muted-foreground">
345 Open this URL in the in-app preview when this action runs.
346 </p>
347 </div>
348 <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]">
349 <span>Run automatically on worktree creation</span>
350 <Switch
351 checked={runOnWorktreeCreate}
352 onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
353 />
354 </label>
355 <label
356 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] ${
357 previewUrl.trim().length === 0 ? "opacity-60" : ""
358 }`}
359 >
360 <span>Open preview automatically when this action runs</span>
361 <Switch
362 checked={autoOpenPreview}
363 disabled={previewUrl.trim().length === 0}
364 onCheckedChange={(checked) => setAutoOpenPreview(Boolean(checked))}
365 />
366 </label>
367 {validationError && <p className="text-sm text-destructive">{validationError}</p>}
368 </form>
369 </DialogPanel>
370 <DialogFooter className="dark:border-transparent dark:bg-transparent">
371 {isEditing && (
372 <Button
373 type="button"
374 variant="destructive-outline"
375 className="mr-auto"
376 onClick={() => setDeleteConfirmOpen(true)}
377 >
378 Delete
379 </Button>
380 )}
381 <Button type="button" variant="outline" onClick={onClose}>
382 Cancel
383 </Button>
384 <Button form={formId} type="submit">
385 {isEditing ? "Save changes" : "Save action"}
386 </Button>
387 </DialogFooter>
388 </DialogPopup>
389 </Dialog>
390
391 <AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
392 <AlertDialogPopup>
393 <AlertDialogHeader>
394 <AlertDialogTitle>Delete action "{name}"?</AlertDialogTitle>
395 <AlertDialogDescription>This action cannot be undone.</AlertDialogDescription>
396 </AlertDialogHeader>
397 <AlertDialogFooter>
398 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
399 <Button
400 variant="destructive"
401 onClick={() => {
402 if (!request?.scriptId) return;
403 setDeleteConfirmOpen(false);
404 onClose();
405 onDelete(request.scriptId);
406 }}
407 >
408 Delete action
409 </Button>
410 </AlertDialogFooter>
411 </AlertDialogPopup>
412 </AlertDialog>
413 </>
414 );
415}