Open History to see the last commit
1import type {
2 ProjectScript,
3 ResolvedKeybindingsConfig,
4 T3ProjectFileScript,
5} from "@t3tools/contracts";
6import {
7 isAtomCommandInterrupted,
8 squashAtomCommandFailure,
9} from "@t3tools/client-runtime/state/runtime";
10import { ChevronDownIcon, DownloadIcon, PlusIcon, SettingsIcon, WrenchIcon } from "lucide-react";
11import React, { useCallback, useMemo, useState } from "react";
12
13import { commandForProjectScript, primaryProjectScript } from "~/projectScripts";
14import { shortcutLabelForCommand } from "~/keybindings";
15import {
16 EMPTY_PROJECT_SCRIPT_INPUT,
17 editorRequestForScript,
18 ProjectScriptEditorDialog,
19 ScriptIcon,
20 type NewProjectScriptInput,
21 type ProjectScriptActionResult,
22 type ProjectScriptEditorRequest,
23} from "./projectScriptEditor";
24import { Button } from "./ui/button";
25import { Group, GroupSeparator } from "./ui/group";
26import {
27 Menu,
28 MenuGroup,
29 MenuGroupLabel,
30 MenuItem,
31 MenuPopup,
32 MenuSeparator,
33 MenuShortcut,
34 MenuTrigger,
35} from "./ui/menu";
36import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
37import { cn } from "~/lib/utils";
38import {
39 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
40 THREAD_DETAILS_PANEL_ICON_CLASS,
41 THREAD_DETAILS_PANEL_ROW_POPUP_CLASS,
42 THREAD_DETAILS_PANEL_ROW_CLASS,
43 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
44 THREAD_DETAILS_PANEL_SPLIT_PRIMARY_CLASS,
45 THREAD_DETAILS_PANEL_SPLIT_SECONDARY_CLASS,
46 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
47} from "./chat/threadDetailsPanelStyles";
48
49export type { NewProjectScriptInput, ProjectScriptActionResult };
50
51const NO_FILE_SCRIPTS: ReadonlyArray<T3ProjectFileScript> = [];
52
53interface ProjectScriptsControlProps {
54 displayMode?: "toolbar" | "panel";
55 scripts: ReadonlyArray<ProjectScript>;
56 /** Scripts declared in the project's checked-in t3.json, offered for import. */
57 fileScripts?: ReadonlyArray<T3ProjectFileScript>;
58 keybindings: ResolvedKeybindingsConfig;
59 preferredScriptId?: string | null;
60 onRunScript: (script: ProjectScript) => void;
61 onAddScript: (input: NewProjectScriptInput) => Promise<ProjectScriptActionResult>;
62 onUpdateScript: (
63 scriptId: string,
64 input: NewProjectScriptInput,
65 ) => Promise<ProjectScriptActionResult>;
66 onDeleteScript: (scriptId: string) => Promise<ProjectScriptActionResult>;
67}
68
69export default function ProjectScriptsControl({
70 displayMode = "toolbar",
71 scripts,
72 fileScripts = NO_FILE_SCRIPTS,
73 keybindings,
74 preferredScriptId = null,
75 onRunScript,
76 onAddScript,
77 onUpdateScript,
78 onDeleteScript,
79}: ProjectScriptsControlProps) {
80 const isPanel = displayMode === "panel";
81 const ActionGroup = isPanel ? "div" : Group;
82 const panelAnchorRef = React.useRef<HTMLDivElement | null>(null);
83 const addScriptFormId = React.useId();
84 const [editingScriptId, setEditingScriptId] = useState<string | null>(null);
85 const [actionsMenuOpen, setActionsMenuOpen] = useState({
86 scripts: false,
87 imports: false,
88 });
89 const [editorRequest, setEditorRequest] = useState<ProjectScriptEditorRequest | null>(null);
90
91 const primaryScript = useMemo(() => {
92 if (preferredScriptId) {
93 const preferred = scripts.find((script) => script.id === preferredScriptId);
94 if (preferred) return preferred;
95 }
96 return primaryProjectScript(scripts);
97 }, [preferredScriptId, scripts]);
98 const importableScripts = useMemo(
99 () =>
100 fileScripts.filter(
101 (fileScript) =>
102 !scripts.some(
103 (script) =>
104 script.command === fileScript.command ||
105 script.name.toLowerCase() === fileScript.name.toLowerCase(),
106 ),
107 ),
108 [fileScripts, scripts],
109 );
110 const dropdownItemClassName =
111 "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";
112
113 const openAddDialog = () => {
114 setEditorRequest({ scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT });
115 };
116
117 const openEditDialog = (script: ProjectScript) => {
118 setActionsMenuOpen({ scripts: false, imports: false });
119 setEditorRequest(editorRequestForScript(script, keybindings));
120 };
121
122 const submitScript = useCallback(
123 (scriptId: string | null, input: NewProjectScriptInput) =>
124 scriptId === null ? onAddScript(input) : onUpdateScript(scriptId, input),
125 [onAddScript, onUpdateScript],
126 );
127
128 const importFileScript = async (fileScript: T3ProjectFileScript) => {
129 const payload: NewProjectScriptInput = {
130 name: fileScript.name,
131 command: fileScript.command,
132 icon: fileScript.icon ?? "play",
133 runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,
134 waitForSetup: fileScript.runOnWorktreeCreate === true && fileScript.async === false,
135 keybinding: null,
136 previewUrl: fileScript.previewUrl ?? null,
137 autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,
138 };
139 const result = await onAddScript(payload);
140 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
141 // Surface the failure through the regular add dialog, prefilled so the
142 // user can adjust and retry.
143 const error = squashAtomCommandFailure(result);
144 setEditorRequest({
145 scriptId: null,
146 initial: payload,
147 error: error instanceof Error ? error.message : "Failed to import action.",
148 });
149 }
150 };
151
152 const importMenuItems = importableScripts.length > 0 && (
153 <>
154 {primaryScript && <MenuSeparator />}
155 <MenuGroup>
156 <MenuGroupLabel>From t3.json</MenuGroupLabel>
157 {importableScripts.map((fileScript) => (
158 <MenuItem
159 key={`${fileScript.name} ${fileScript.command}`}
160 className={dropdownItemClassName}
161 onClick={() => void importFileScript(fileScript)}
162 >
163 <ScriptIcon icon={fileScript.icon ?? "play"} className="size-4" />
164 <span className="truncate">{fileScript.name}</span>
165 <MenuShortcut className="ms-auto">
166 <DownloadIcon className="size-3.5" aria-label="Import" />
167 </MenuShortcut>
168 </MenuItem>
169 ))}
170 </MenuGroup>
171 </>
172 );
173
174 return (
175 <>
176 {primaryScript ? (
177 <ActionGroup
178 role="group"
179 aria-label="Project scripts"
180 {...(isPanel
181 ? { className: THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, ref: panelAnchorRef }
182 : {})}
183 >
184 <Tooltip>
185 <TooltipTrigger
186 render={
187 <Button
188 size="xs"
189 variant={isPanel ? "ghost" : "outline"}
190 className={
191 isPanel
192 ? THREAD_DETAILS_PANEL_SPLIT_PRIMARY_CLASS
193 : "w-7 px-0 sm:w-6 @3xl/header-actions:w-auto! @3xl/header-actions:px-[calc(--spacing(2)-1px)]"
194 }
195 aria-label={`Run ${primaryScript.name}`}
196 // The tooltip wrapper replaces data-slot="button", so themed
197 // toolbar styling needs its own hook.
198 data-toolbar-control=""
199 onClick={() => onRunScript(primaryScript)}
200 />
201 }
202 >
203 <ScriptIcon
204 icon={primaryScript.icon}
205 {...(isPanel ? { className: THREAD_DETAILS_PANEL_ICON_CLASS } : {})}
206 />
207 <span
208 className={cn(
209 "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
210 isPanel && "not-sr-only ml-0.5 truncate",
211 )}
212 >
213 {primaryScript.name}
214 </span>
215 </TooltipTrigger>
216 <TooltipPopup side="top">Run {primaryScript.name}</TooltipPopup>
217 </Tooltip>
218 {isPanel ? (
219 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
220 ) : (
221 <GroupSeparator className="hidden @3xl/header-actions:block" />
222 )}
223 <Menu
224 highlightItemOnHover={false}
225 open={actionsMenuOpen.scripts}
226 onOpenChange={(open) => setActionsMenuOpen({ scripts: open, imports: false })}
227 >
228 <MenuTrigger
229 render={
230 <Button
231 size={isPanel ? "sm" : "icon-xs"}
232 variant={isPanel ? "ghost" : "outline"}
233 className={isPanel ? THREAD_DETAILS_PANEL_SPLIT_SECONDARY_CLASS : undefined}
234 aria-label="Script actions"
235 />
236 }
237 >
238 <ChevronDownIcon
239 className={isPanel ? THREAD_DETAILS_PANEL_CHEVRON_CLASS : "size-4"}
240 />
241 </MenuTrigger>
242 <MenuPopup
243 align="end"
244 {...(isPanel ? { anchor: panelAnchorRef } : {})}
245 className={isPanel ? THREAD_DETAILS_PANEL_ROW_POPUP_CLASS : undefined}
246 >
247 {scripts.map((script) => {
248 const shortcutLabel = shortcutLabelForCommand(
249 keybindings,
250 commandForProjectScript(script.id),
251 );
252 return (
253 <MenuItem
254 key={script.id}
255 className={`group ${dropdownItemClassName}`}
256 onClick={() => onRunScript(script)}
257 >
258 <ScriptIcon icon={script.icon} className="size-4" />
259 <span className="truncate">
260 {script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name}
261 </span>
262 <span className="relative ms-auto flex h-6 min-w-6 items-center justify-end">
263 {shortcutLabel && (
264 <MenuShortcut className="ms-0 transition-opacity group-hover:opacity-0 group-focus-visible:opacity-0">
265 {shortcutLabel}
266 </MenuShortcut>
267 )}
268 <Button
269 type="button"
270 variant="ghost"
271 size="icon-xs"
272 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"
273 aria-label={`Edit ${script.name}`}
274 onPointerDown={(event) => {
275 event.preventDefault();
276 event.stopPropagation();
277 }}
278 onClick={(event) => {
279 event.preventDefault();
280 event.stopPropagation();
281 openEditDialog(script);
282 }}
283 >
284 <SettingsIcon className="size-3.5" />
285 </Button>
286 </span>
287 </MenuItem>
288 );
289 })}
290 {importMenuItems}
291 <MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
292 <PlusIcon className="size-4" />
293 {isPanel ? "Add project script" : "Add action"}
294 </MenuItem>
295 </MenuPopup>
296 </Menu>
297 </ActionGroup>
298 ) : importableScripts.length > 0 ? (
299 isPanel ? (
300 <div
301 role="group"
302 aria-label="Project actions"
303 className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}
304 ref={panelAnchorRef}
305 >
306 <Button
307 size="sm"
308 variant="ghost"
309 className={THREAD_DETAILS_PANEL_SPLIT_PRIMARY_CLASS}
310 aria-label="Project actions"
311 onClick={() => setActionsMenuOpen({ scripts: false, imports: true })}
312 >
313 <WrenchIcon className={THREAD_DETAILS_PANEL_ICON_CLASS} />
314 <span className="ml-0.5 min-w-0 truncate">Actions</span>
315 </Button>
316 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
317 <Menu
318 highlightItemOnHover={false}
319 open={actionsMenuOpen.imports}
320 onOpenChange={(open) => setActionsMenuOpen({ scripts: false, imports: open })}
321 >
322 <MenuTrigger
323 render={
324 <Button
325 size="sm"
326 variant="ghost"
327 className={THREAD_DETAILS_PANEL_SPLIT_SECONDARY_CLASS}
328 aria-label="Choose project action"
329 />
330 }
331 >
332 <ChevronDownIcon className={THREAD_DETAILS_PANEL_CHEVRON_CLASS} />
333 </MenuTrigger>
334 <MenuPopup
335 align="end"
336 anchor={panelAnchorRef}
337 className={THREAD_DETAILS_PANEL_ROW_POPUP_CLASS}
338 >
339 {importMenuItems}
340 <MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
341 <PlusIcon className="size-4" />
342 Add action
343 </MenuItem>
344 </MenuPopup>
345 </Menu>
346 </div>
347 ) : (
348 <Menu
349 highlightItemOnHover={false}
350 open={actionsMenuOpen.imports}
351 onOpenChange={(open) => setActionsMenuOpen({ scripts: false, imports: open })}
352 >
353 <MenuTrigger
354 render={<Button size="xs" variant="outline" aria-label="Project actions" />}
355 >
356 <WrenchIcon className="size-3.5" />
357 <span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
358 Actions
359 </span>
360 <ChevronDownIcon className="size-3.5" />
361 </MenuTrigger>
362 <MenuPopup align="end">
363 {importMenuItems}
364 <MenuItem className={dropdownItemClassName} onClick={openAddDialog}>
365 <PlusIcon className="size-4" />
366 Add action
367 </MenuItem>
368 </MenuPopup>
369 </Menu>
370 )
371 ) : (
372 <Tooltip>
373 <TooltipTrigger
374 render={
375 <Button
376 size="xs"
377 variant={isPanel ? "ghost" : "outline"}
378 className={
379 isPanel
380 ? THREAD_DETAILS_PANEL_ROW_CLASS
381 : "w-7 px-0 sm:w-6 @3xl/header-actions:w-auto! @3xl/header-actions:px-[calc(--spacing(2)-1px)]"
382 }
383 aria-label={isPanel ? "Add project script" : "Add action"}
384 // The tooltip wrapper replaces data-slot="button", so themed
385 // toolbar styling needs its own hook.
386 data-toolbar-control=""
387 onClick={openAddDialog}
388 />
389 }
390 >
391 <PlusIcon className="size-3.5" />
392 <span
393 className={cn(
394 "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
395 isPanel && "not-sr-only ml-0.5",
396 )}
397 >
398 {isPanel ? "Add project script" : "Add action"}
399 </span>
400 </TooltipTrigger>
401 <TooltipPopup side="top">{isPanel ? "Add project script" : "Add action"}</TooltipPopup>
402 </Tooltip>
403 )}
404
405 <ProjectScriptEditorDialog
406 request={editorRequest}
407 scripts={scripts}
408 onSubmit={submitScript}
409 onDelete={(scriptId) => void onDeleteScript(scriptId)}
410 onClose={() => setEditorRequest(null)}
411 />
412 </>
413 );
414}