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