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