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