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

ProjectScriptsControl.tsx

363 lines12.8 KB

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>;
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​
105 const openAddDialog = () => {
106 setEditorRequest({ scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT });
107 };
108​
109 const openEditDialog = (script: ProjectScript) => {
110 onRequestMenuClose?.();
111 setActionsMenuOpen({ presentation, scripts: false, imports: false });
112 setEditorRequest(editorRequestForScript(script, keybindings));
113 };
114​
115 const submitScript = useCallback(
116 (scriptId: string | null, input: NewProjectScriptInput) =>
117 scriptId === null ? onAddScript(input) : onUpdateScript(scriptId, input),
118 [onAddScript, onUpdateScript],
119 );
120​
121 const importFileScript = async (fileScript: T3ProjectFileScript) => {
122 const payload: NewProjectScriptInput = {
123 name: fileScript.name,
124 command: fileScript.command,
125 icon: fileScript.icon ?? "play",
126 runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,
127 waitForSetup: fileScript.runOnWorktreeCreate === true && fileScript.async === false,
128 keybinding: null,
129 previewUrl: fileScript.previewUrl ?? null,
130 autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,
131 };
132 const result = await onAddScript(payload);
133 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
134 // Surface the failure through the regular add dialog, prefilled so the
135 // user can adjust and retry.
136 const error = squashAtomCommandFailure(result);
137 setEditorRequest({
138 scriptId: null,
139 initial: payload,
140 error: error instanceof Error ? error.message : "Failed to import action.",
141 });
142 }
143 };
144​
145 const importMenuItems = importableScripts.length > 0 && (
146 <>
147 {primaryScript && <MenuSeparator />}
148 <MenuGroup>
149 <MenuGroupLabel>From t3.json</MenuGroupLabel>
150 {importableScripts.map((fileScript) => (
151 <MenuItem
152 density={presentation === "menu" ? "touch" : "default"}
153 key={`${fileScript.name} ${fileScript.command}`}
154 onClick={() => void importFileScript(fileScript)}
155 >
156 <ScriptIcon icon={fileScript.icon ?? "play"} className="size-4" />
157 <MenuItemLabel>{fileScript.name}</MenuItemLabel>
158 <MenuShortcut>
159 <DownloadIcon className="size-3.5" aria-label="Import" />
160 </MenuShortcut>
161 </MenuItem>
162 ))}
163 </MenuGroup>
164 </>
165 );
166​
167 const scriptItems = (
168 <>
169 {scripts.map((script) => {
170 const shortcutLabel = shortcutLabelForCommand(
171 keybindings,
172 commandForProjectScript(script.id),
173 );
174 return (
175 <MenuItem
176 density={presentation === "menu" ? "touch" : "default"}
177 key={script.id}
178 className="group"
179 onClick={() => onRunScript(script)}
180 >
181 <ScriptIcon icon={script.icon} className="size-4" />
182 <MenuItemLabel>
183 {script.runOnWorktreeCreate ? `${script.name} (setup)` : script.name}
184 </MenuItemLabel>
185 <span className="relative ms-auto flex h-6 min-w-6 items-center justify-end">
186 {shortcutLabel &&
187 (presentation === "menu" ? (
188 <MenuShortcut className="ms-0 mr-7">{shortcutLabel}</MenuShortcut>
189 ) : (
190 // The shortcut yields its slot to the edit button on hover.
191 <span className="transition-opacity group-hover:opacity-0 group-focus-visible:opacity-0">
192 <MenuShortcut className="ms-0">{shortcutLabel}</MenuShortcut>
193 </span>
194 ))}
195 <span
196 className={`absolute right-0 top-1/2 flex -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"}`}
197 >
198 <Button
199 type="button"
200 variant="ghost"
201 size="icon-xs"
202 className="size-6"
203 aria-label={`Edit ${script.name}`}
204 onPointerDown={(event) => {
205 event.preventDefault();
206 event.stopPropagation();
207 }}
208 onClick={(event) => {
209 event.preventDefault();
210 event.stopPropagation();
211 openEditDialog(script);
212 }}
213 >
214 <SettingsIcon className="size-3.5" />
215 </Button>
216 </span>
217 </span>
218 </MenuItem>
219 );
220 })}
221 {importMenuItems}
222 <MenuItem density={presentation === "menu" ? "touch" : "default"} onClick={openAddDialog}>
223 <PlusIcon className="size-4" />
224 <MenuItemLabel>Add action</MenuItemLabel>
225 </MenuItem>
226 </>
227 );
228​
229 return (
230 <>
231 {presentation === "menu" ? (
232 <>
233 {primaryScript && (
234 <MenuItem
235 density={presentation === "menu" ? "touch" : "default"}
236 onClick={() => onRunScript(primaryScript)}
237 >
238 <ScriptIcon icon={primaryScript.icon} className="size-4" />
239 <MenuItemLabel>Run {primaryScript.name}</MenuItemLabel>
240 <MenuShortcut>
241 {shortcutLabelForCommand(keybindings, commandForProjectScript(primaryScript.id))}
242 </MenuShortcut>
243 </MenuItem>
244 )}
245 {primaryScript || importableScripts.length > 0 ? (
246 <MenuSub
247 open={actionsMenuOpen.scripts}
248 onOpenChange={(open) =>
249 setActionsMenuOpen({ presentation, scripts: open, imports: false })
250 }
251 >
252 <MenuSubTrigger density="touch">
253 <ScriptIcon icon="play" className="size-4" />
254 <MenuItemLabel>Project actions</MenuItemLabel>
255 </MenuSubTrigger>
256 <MenuSubPopup>{scriptItems}</MenuSubPopup>
257 </MenuSub>
258 ) : (
259 <MenuItem
260 density={presentation === "menu" ? "touch" : "default"}
261 onClick={openAddDialog}
262 >
263 <PlusIcon className="size-4" />
264 <MenuItemLabel>Add project action…</MenuItemLabel>
265 </MenuItem>
266 )}
267 </>
268 ) : primaryScript ? (
269 <Group aria-label="Project scripts">
270 <Tooltip>
271 <TooltipTrigger
272 render={
273 <Button
274 size="xs"
275 variant="outline"
276 className="w-7 sm:w-6 @3xl/header-actions:w-auto!"
277 aria-label={`Run ${primaryScript.name}`}
278 // The tooltip wrapper replaces data-slot="button", so themed
279 // toolbar styling needs its own hook.
280 data-toolbar-control=""
281 onClick={() => onRunScript(primaryScript)}
282 />
283 }
284 >
285 <ScriptIcon icon={primaryScript.icon} />
286 <span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
287 {primaryScript.name}
288 </span>
289 </TooltipTrigger>
290 <TooltipPopup side="top">Run {primaryScript.name}</TooltipPopup>
291 </Tooltip>
292 <GroupSeparator className="hidden @3xl/header-actions:block" />
293 <Menu
294 open={actionsMenuOpen.scripts}
295 onOpenChange={(open) =>
296 setActionsMenuOpen({ presentation, scripts: open, imports: false })
297 }
298 >
299 <MenuTrigger
300 render={<Button size="icon-xs" variant="outline" aria-label="Script actions" />}
301 >
302 <ChevronDownIcon className="size-4" />
303 </MenuTrigger>
304 <MenuPopup align="end">{scriptItems}</MenuPopup>
305 </Menu>
306 </Group>
307 ) : importableScripts.length > 0 ? (
308 <Menu
309 open={actionsMenuOpen.imports}
310 onOpenChange={(open) =>
311 setActionsMenuOpen({ presentation, scripts: false, imports: open })
312 }
313 >
314 <MenuTrigger render={<Button size="xs" variant="outline" aria-label="Project actions" />}>
315 <PlusIcon className="size-3.5" />
316 <span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
317 Add action
318 </span>
319 <ChevronDownIcon className="size-3.5" />
320 </MenuTrigger>
321 <MenuPopup align="end">
322 {importMenuItems}
323 <MenuItem onClick={openAddDialog}>
324 <PlusIcon className="size-4" />
325 Add action
326 </MenuItem>
327 </MenuPopup>
328 </Menu>
329 ) : (
330 <Tooltip>
331 <TooltipTrigger
332 render={
333 <Button
334 size="xs"
335 variant="outline"
336 className="w-7 sm:w-6 @3xl/header-actions:w-auto!"
337 aria-label="Add action"
338 // The tooltip wrapper replaces data-slot="button", so themed
339 // toolbar styling needs its own hook.
340 data-toolbar-control=""
341 onClick={openAddDialog}
342 />
343 }
344 >
345 <PlusIcon className="size-3.5" />
346 <span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
347 Add action
348 </span>
349 </TooltipTrigger>
350 <TooltipPopup side="top">Add action</TooltipPopup>
351 </Tooltip>
352 )}
353​
354 <ProjectScriptEditorDialog
355 request={editorRequest}
356 scripts={scripts}
357 onSubmit={submitScript}
358 onDelete={(scriptId) => void onDeleteScript(scriptId)}
359 onClose={() => setEditorRequest(null)}
360 />
361 </>
362 );