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 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_LABEL_CLASS,
54 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
55 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
56} from "./chat/threadDetailsPanelStyles";
57
58export type { NewProjectScriptInput, ProjectScriptActionResult };
59
60const NO_FILE_SCRIPTS: ReadonlyArray<T3ProjectFileScript> = [];
61
62interface ProjectScriptsControlProps {
63 displayMode?: "toolbar" | "panel";
64 presentation?: "toolbar" | "menu";
65 onRequestMenuClose?: () => void;
66 environmentId: EnvironmentId;
67 scripts: ReadonlyArray<ProjectScript>;
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>;
77}
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 const error = squashAtomCommandFailure(result);
159 setEditorRequest({
160 scriptId: null,
161 initial: payload,
162 error: error instanceof Error ? error.message : "Failed to import action.",
163 });
164 }
165 };
166
167 const importMenuItems = importableScripts.length > 0 && (
168 <>
169 {scripts.length > 0 && <MenuSeparator />}
170 <MenuGroup>
171 <MenuGroupLabel>From t3.json</MenuGroupLabel>
172 {importableScripts.map((fileScript) => (
173 <MenuItem
174 density={presentation === "menu" ? "touch" : "default"}
175 key={`${fileScript.name} ${fileScript.command}`}
176 onClick={() => void importFileScript(fileScript)}
177 >
178 <ScriptIcon icon={fileScript.icon ?? "play"} className="size-4" />
179 <MenuItemLabel>{fileScript.name}</MenuItemLabel>
180 <MenuShortcut>
181 <DownloadIcon className="size-3.5" aria-label="Import" />
182 </MenuShortcut>
183 </MenuItem>
184 ))}
185 </MenuGroup>
186 </>
187 );
188
189 const scriptItems = (
190 <>
191 {scripts.map((script) => {
192 const shortcutLabel = shortcutLabelForCommand(
193 keybindings,
194 commandForProjectScript(script.id),
195 );
196 return (
197 <MenuItem
198 density={presentation === "menu" ? "touch" : "default"}
199 key={script.id}
200 className="group"
201 disabled={!onRunScript}
202 onClick={() => onRunScript?.(script)}
203 >
204 <ScriptIcon icon={script.icon} className="size-4" />
205 <MenuItemLabel>{projectScriptMenuLabel(script)}</MenuItemLabel>
206 <span className="relative ms-auto flex h-6 min-w-6 items-center justify-end">
207 {shortcutLabel &&
208 (presentation === "menu" ? (
209 <MenuShortcut className="ms-0 mr-7">{shortcutLabel}</MenuShortcut>
210 ) : (
211 <span className="transition-opacity group-hover:opacity-0 group-focus-visible:opacity-0">
212 <MenuShortcut className="ms-0">{shortcutLabel}</MenuShortcut>
213 </span>
214 ))}
215 <span
216 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"}`}
217 >
218 <Button
219 type="button"
220 variant="ghost"
221 size="icon-xs"
222 className="size-6"
223 aria-label={`Edit ${script.name}`}
224 onPointerDown={(event) => {
225 event.preventDefault();
226 event.stopPropagation();
227 }}
228 onClick={(event) => {
229 event.preventDefault();
230 event.stopPropagation();
231 openEditDialog(script);
232 }}
233 >
234 <SettingsIcon className="size-3.5" />
235 </Button>
236 </span>
237 </span>
238 </MenuItem>
239 );
240 })}
241 {importMenuItems}
242 <MenuItem density={presentation === "menu" ? "touch" : "default"} onClick={openAddDialog}>
243 <PlusIcon className="size-4" />
244 <MenuItemLabel>{isPanel ? "Add project script" : "Add action"}</MenuItemLabel>
245 </MenuItem>
246 </>
247 );
248
249 return (
250 <>
251 {presentation === "menu" ? (
252 <>
253 {primaryScript && (
254 <MenuItem
255 density={presentation === "menu" ? "touch" : "default"}
256 disabled={!onRunScript}
257 onClick={() => onRunScript?.(primaryScript)}
258 >
259 <ScriptIcon icon={primaryScript.icon} className="size-4" />
260 <MenuItemLabel>Run {primaryScript.name}</MenuItemLabel>
261 <MenuShortcut>
262 {shortcutLabelForCommand(keybindings, commandForProjectScript(primaryScript.id))}
263 </MenuShortcut>
264 </MenuItem>
265 )}
266 {scripts.length > 0 || importableScripts.length > 0 ? (
267 <MenuSub
268 open={actionsMenuOpen.scripts}
269 onOpenChange={(open) =>
270 setActionsMenuOpen({ presentation, scripts: open, imports: false })
271 }
272 >
273 <MenuSubTrigger density="touch">
274 <ScriptIcon icon="play" className="size-4" />
275 <MenuItemLabel>Project actions</MenuItemLabel>
276 </MenuSubTrigger>
277 <MenuSubPopup>{scriptItems}</MenuSubPopup>
278 </MenuSub>
279 ) : (
280 <MenuItem
281 density={presentation === "menu" ? "touch" : "default"}
282 onClick={openAddDialog}
283 >
284 <PlusIcon className="size-4" />
285 <MenuItemLabel>Add project action…</MenuItemLabel>
286 </MenuItem>
287 )}
288 </>
289 ) : primaryScript ? (
290 <ActionGroup
291 role="group"
292 aria-label="Project scripts"
293 {...(isPanel
294 ? { className: THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, ref: panelAnchorRef }
295 : {})}
296 >
297 <Tooltip>
298 <TooltipTrigger
299 render={
300 <ThreadDetailsControl
301 size="xs"
302 variant={isPanel ? "ghost" : "outline"}
303 part="primary"
304 panel={isPanel}
305 className={isPanel ? undefined : "w-7 sm:w-6 @3xl/header-actions:w-auto!"}
306 aria-label={`Run ${primaryScript.name}`}
307 // The tooltip wrapper replaces data-slot="button", so themed
308 // toolbar styling needs its own hook.
309 data-toolbar-control=""
310 aria-disabled={!onRunScript || undefined}
311 onClick={() => onRunScript?.(primaryScript)}
312 />
313 }
314 >
315 <ScriptIcon
316 icon={primaryScript.icon}
317 {...(isPanel ? { className: THREAD_DETAILS_PANEL_ICON_CLASS } : {})}
318 />
319 <span
320 className={cn(
321 "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
322 isPanel && cn("not-sr-only ml-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
323 )}
324 >
325 {primaryScript.name}
326 </span>
327 </TooltipTrigger>
328 <TooltipPopup side="top">
329 {onRunScript
330 ? `Run ${primaryScript.name}`
331 : "Pair this client again with permission to run terminal commands."}
332 </TooltipPopup>
333 </Tooltip>
334 {isPanel ? (
335 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
336 ) : (
337 <GroupSeparator className="hidden @3xl/header-actions:block" />
338 )}
339 <Menu
340 open={actionsMenuOpen.scripts}
341 onOpenChange={(open) =>
342 setActionsMenuOpen({ presentation, scripts: open, imports: false })
343 }
344 >
345 <MenuTrigger
346 render={
347 <ThreadDetailsControl
348 size={isPanel ? "sm" : "icon-xs"}
349 variant={isPanel ? "ghost" : "outline"}
350 part="secondary"
351 panel={isPanel}
352 aria-label="Script actions"
353 />
354 }
355 >
356 <ChevronDownIcon
357 className={isPanel ? THREAD_DETAILS_PANEL_CHEVRON_CLASS : "size-4"}
358 />
359 </MenuTrigger>
360 <MenuPopup
361 align="end"
362 {...(isPanel ? { anchor: panelAnchorRef } : {})}
363 className={isPanel ? "w-(--anchor-width)" : undefined}
364 >
365 {scriptItems}
366 </MenuPopup>
367 </Menu>
368 </ActionGroup>
369 ) : scripts.length > 0 || importableScripts.length > 0 ? (
370 isPanel ? (
371 <div
372 role="group"
373 aria-label="Project actions"
374 className={THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS}
375 ref={panelAnchorRef}
376 >
377 <ThreadDetailsControl
378 size="sm"
379 variant="ghost"
380 part="primary"
381 aria-label="Project actions"
382 onClick={() => setActionsMenuOpen({ presentation, scripts: false, imports: true })}
383 >
384 <WrenchIcon className={THREAD_DETAILS_PANEL_ICON_CLASS} />
385 <span className={cn("min-w-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS)}>
386 Actions
387 </span>
388 </ThreadDetailsControl>
389 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
390 <Menu
391 highlightItemOnHover={false}
392 open={actionsMenuOpen.imports}
393 onOpenChange={(open) =>
394 setActionsMenuOpen({ presentation, scripts: false, imports: open })
395 }
396 >
397 <MenuTrigger
398 render={
399 <ThreadDetailsControl
400 size="sm"
401 variant="ghost"
402 part="secondary"
403 aria-label="Choose project action"
404 />
405 }
406 >
407 <ChevronDownIcon className={THREAD_DETAILS_PANEL_CHEVRON_CLASS} />
408 </MenuTrigger>
409 <MenuPopup align="end" anchor={panelAnchorRef} className="w-(--anchor-width)">
410 {scriptItems}
411 </MenuPopup>
412 </Menu>
413 </div>
414 ) : (
415 <Menu
416 highlightItemOnHover={false}
417 open={actionsMenuOpen.imports}
418 onOpenChange={(open) =>
419 setActionsMenuOpen({ presentation, scripts: false, imports: open })
420 }
421 >
422 <MenuTrigger
423 render={<Button size="xs" variant="outline" aria-label="Project actions" />}
424 >
425 <WrenchIcon className="size-3.5" />
426 <span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
427 Actions
428 </span>
429 <ChevronDownIcon className="size-3.5" />
430 </MenuTrigger>
431 <MenuPopup align="end">{scriptItems}</MenuPopup>
432 </Menu>
433 )
434 ) : (
435 <Tooltip>
436 <TooltipTrigger
437 render={
438 <ThreadDetailsControl
439 size="xs"
440 variant={isPanel ? "ghost" : "outline"}
441 part="row"
442 panel={isPanel}
443 className={isPanel ? undefined : "w-7 sm:w-6 @3xl/header-actions:w-auto!"}
444 aria-label={isPanel ? "Add project script" : "Add action"}
445 data-toolbar-control=""
446 onClick={openAddDialog}
447 />
448 }
449 >
450 <PlusIcon className="size-3.5" />
451 <span
452 className={cn(
453 "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
454 isPanel && cn("not-sr-only ml-0.5", THREAD_DETAILS_PANEL_LABEL_CLASS),
455 )}
456 >
457 {isPanel ? "Add project script" : "Add action"}
458 </span>
459 </TooltipTrigger>
460 <TooltipPopup side="top">{isPanel ? "Add project script" : "Add action"}</TooltipPopup>
461 </Tooltip>
462 )}
463
464 <ProjectScriptEditorDialog
465 environmentId={environmentId}
466 request={editorRequest}
467 scripts={scripts}
468 onSubmit={submitScript}
469 onDelete={(scriptId) => void onDeleteScript(scriptId)}
470 onClose={() => setEditorRequest(null)}
471 />
472 </>
473 );
474}