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