Open History to see the last commit
1import { EnvironmentId, type T3ProjectFileScript } from "@t3tools/contracts";
2import {
3 isAtomCommandInterrupted,
4 squashAtomCommandFailure,
5} from "@t3tools/client-runtime/state/runtime";
6import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
7import { ChevronDownIcon, PlusIcon } from "lucide-react";
8import { useCallback, useMemo, useState } from "react";
9import { useT3ProjectFileState } from "../../hooks/useT3ProjectFileScripts";
10import { useEnvironments } from "../../state/environments";
11import {
12 EMPTY_PROJECT_SCRIPT_INPUT,
13 editorRequestForScript,
14 ProjectScriptEditorDialog,
15 ScriptIcon,
16 type NewProjectScriptInput,
17 type ProjectScriptEditorRequest,
18} from "../projectScriptEditor";
19import { Button } from "../ui/button";
20import {
21 Menu,
22 MenuGroup,
23 MenuGroupLabel,
24 MenuItem,
25 MenuPopup,
26 MenuSeparator,
27 MenuTrigger,
28} from "../ui/menu";
29import { ProjectActionsList } from "./ProjectActionsList";
30import { useProjectScriptSettings } from "./useProjectScriptSettings";
31import { SettingsRow, SettingsSection } from "./settingsLayout";
32import { useSettingsScope } from "./SettingsScopeContext";
33
34/**
35 * A project's actions on each selected environment. Actions belong to a
36 * project, so this only renders at a project scope; the environment's
37 * `defaultProjectScripts` is the layer a project without its own list
38 * inherits. Shortcuts are environment-wide, so the same action id shares its
39 * binding on an environment.
40 */
41export function ProjectActionsSettings() {
42 const { scope, targets, target } = useSettingsScope();
43 const { environments } = useEnvironments();
44 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
45 const representativeConfig = target
46 ? environments.find((environment) => environment.environmentId === target.environmentId)
47 ?.serverConfig
48 : undefined;
49 const scripts = target?.settings.defaultProjectScripts ?? [];
50 const keybindings = representativeConfig?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS;
51 const mixed = targets.some(
52 (candidate) =>
53 JSON.stringify(candidate.settings.defaultProjectScripts) !== JSON.stringify(scripts),
54 );
55 const [request, setRequest] = useState<ProjectScriptEditorRequest | null>(null);
56 const memberById = new Map(
57 isProjectScope ? scope.members.map((member) => [member.id, member]) : [],
58 );
59 const { saving, persist, submit } = useProjectScriptSettings(
60 targets.flatMap((candidate) => {
61 const environment = environments.find(
62 (entry) => entry.environmentId === candidate.environmentId,
63 );
64 if (!environment?.serverConfig) return [];
65 const member = candidate.projectId ? memberById.get(candidate.projectId) : undefined;
66 // An older server ignores the override record, so a project edit there
67 // would report success and vanish; such environments are left out and
68 // the legacy per-project map keeps serving them.
69 if (
70 member &&
71 environment.serverConfig.environment?.capabilities.projectSettingsOverrides !== true
72 ) {
73 return [];
74 }
75 return [
76 {
77 environmentId: candidate.environmentId,
78 // Writes read the raw environment settings so an override entry is
79 // extended, not derived from already-resolved values.
80 settings: environment.serverConfig.settings,
81 keybindings: environment.serverConfig.keybindings,
82 ...(member ? { project: member } : {}),
83 },
84 ];
85 }),
86 );
87
88 // A project's t3.json can declare actions to import. Read it from the
89 // representative checkout; the imported action still fans out.
90 const representativeMember = target?.projectId ? memberById.get(target.projectId) : undefined;
91 const t3File = useT3ProjectFileState(
92 representativeMember?.environmentId ?? EnvironmentId.make("none"),
93 representativeMember?.workspaceRoot ?? null,
94 );
95 const importableScripts = useMemo(
96 () =>
97 t3File.scripts.filter(
98 (fileScript) =>
99 !scripts.some(
100 (script) =>
101 script.command === fileScript.command ||
102 script.name.toLowerCase() === fileScript.name.toLowerCase(),
103 ),
104 ),
105 [scripts, t3File.scripts],
106 );
107 const importFileScript = useCallback(
108 async (fileScript: T3ProjectFileScript) => {
109 const payload: NewProjectScriptInput = {
110 name: fileScript.name,
111 command: fileScript.command,
112 icon: fileScript.icon ?? "play",
113 runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,
114 keybinding: null,
115 previewUrl: fileScript.previewUrl ?? null,
116 autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,
117 };
118 const result = await submit(null, payload);
119 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
120 const error = squashAtomCommandFailure(result);
121 setRequest({
122 scriptId: null,
123 initial: payload,
124 error: error instanceof Error ? error.message : "Failed to import action.",
125 });
126 }
127 },
128 [submit],
129 );
130
131 return (
132 <SettingsSection id="project-actions" title="Actions">
133 <SettingsRow
134 serverScoped
135 settingKeys={["defaultProjectScripts"]}
136 mixed={mixed}
137 title="Actions"
138 description="Commands that run in this project's checkout or its worktree, with optional shortcuts."
139 onResetOverride={() => void persist(() => null)}
140 control={
141 <div className="flex flex-wrap items-center gap-1.5">
142 {importableScripts.length > 0 ? (
143 <Menu>
144 <MenuTrigger
145 render={
146 <Button
147 id="import-scripts"
148 size="xs"
149 variant="ghost"
150 disabled={saving}
151 type="button"
152 />
153 }
154 >
155 Import scripts
156 <ChevronDownIcon className="size-3.5" />
157 </MenuTrigger>
158 <MenuPopup align="end" className="w-72">
159 <MenuGroup>
160 <MenuGroupLabel>Import from t3.json</MenuGroupLabel>
161 <p className="px-2 pb-2 text-pretty text-sm text-muted-foreground">
162 Add actions declared by this checkout without editing them first.
163 </p>
164 </MenuGroup>
165 <MenuSeparator />
166 {importableScripts.map((fileScript) => (
167 <MenuItem
168 key={`${fileScript.name} ${fileScript.command}`}
169 onClick={() => void importFileScript(fileScript)}
170 >
171 <ScriptIcon icon={fileScript.icon ?? "play"} className="size-4 shrink-0" />
172 <div className="min-w-0 flex-1">
173 <div className="truncate font-medium">{fileScript.name}</div>
174 <div className="truncate font-mono text-muted-foreground">
175 {fileScript.command}
176 </div>
177 </div>
178 </MenuItem>
179 ))}
180 </MenuPopup>
181 </Menu>
182 ) : null}
183 <Button
184 size="xs"
185 variant="outline"
186 disabled={saving || targets.length === 0}
187 onClick={() => setRequest({ scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT })}
188 >
189 <PlusIcon className="size-3.5" />
190 Add action
191 </Button>
192 </div>
193 }
194 />
195 {mixed ? (
196 <SettingsRow
197 title="Different actions across environments"
198 description="Choose one environment to edit its list. Adding an action here adds it on every selected environment."
199 />
200 ) : (
201 <ProjectActionsList
202 scripts={scripts}
203 keybindings={keybindings}
204 disabled={saving}
205 onEdit={(script) => setRequest(editorRequestForScript(script, keybindings))}
206 />
207 )}
208 {t3File.status === "invalid" ? (
209 <SettingsRow
210 title="t3.json is invalid"
211 description="A t3.json exists in this checkout but fails to parse, so every action and icon it declares is ignored. Check the JSON syntax and icon values."
212 className="text-warning"
213 />
214 ) : null}
215 <ProjectScriptEditorDialog
216 request={request}
217 scripts={scripts}
218 onSubmit={submit}
219 onDelete={(id) =>
220 void persist((current) => current.filter((script) => script.id !== id), id, null)
221 }
222 onClose={() => setRequest(null)}
223 />
224 </SettingsSection>
225 );
226}