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

ProjectScriptsControl.tsx

479 lines17.4 KB

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