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