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