Open History to see the last commit
1import type {
2 KeybindingCommand,
3 ProjectId,
4 ProjectScript,
5 EnvironmentId,
6} from "@t3tools/contracts";
7import { AuthSettingsWriteScope, EnvironmentAuthorizationError } from "@t3tools/contracts";
8import type { UnifiedSettings } from "@t3tools/contracts/settings";
9import {
10 isAtomCommandInterrupted,
11 mapAtomCommandResult,
12 squashAtomCommandFailure,
13 type AtomCommandResult,
14} from "@t3tools/client-runtime/state/runtime";
15import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
16import { resolveProjectScripts } from "@t3tools/shared/projectScripts";
17import * as Cause from "effect/Cause";
18import { AsyncResult } from "effect/reactivity";
19import { useStableCallback } from "../../hooks/useStableCallback";
20import {
21 decodeProjectScriptKeybindingRule,
22 keybindingValueForCommand,
23} from "../../lib/projectScriptKeybindings";
24import {
25 buildProjectScript,
26 commandForProjectScript,
27 nextProjectScriptId,
28 projectScriptIdFromCommand,
29 releaseClaimedRoles,
30} from "../../projectScripts";
31import { appAtomRegistry } from "../../rpc/atomRegistry";
32import { serverEnvironment } from "../../state/server";
33import { readEnvironmentScope } from "../../state/session";
34import { useAtomCommand } from "../../state/use-atom-command";
35import { useProjects } from "../../state/entities";
36import { type NewProjectScriptInput } from "../ProjectScriptsControl";
37import { stackedThreadToast, toastManager } from "../ui/toast";
38
39/**
40 * Adds, edits, and deletes the active project's scripts. A script's keyboard
41 * shortcut lives in the environment's keybindings, so each change writes the
42 * script settings first and then reconciles the shortcut.
43 */
44export function useProjectScriptEditing(input: {
45 readonly environmentId: EnvironmentId;
46 readonly project: EnvironmentProject | null;
47 readonly scripts: ReadonlyArray<ProjectScript>;
48 readonly settings: UnifiedSettings;
49}) {
50 const { environmentId, project, scripts, settings } = input;
51 const allProjects = useProjects();
52 const updateProjectScriptSettings = useAtomCommand(serverEnvironment.updateSettings, {
53 reportFailure: false,
54 });
55 const upsertKeybinding = useAtomCommand(serverEnvironment.upsertKeybinding, {
56 reportFailure: false,
57 });
58 const removeKeybinding = useAtomCommand(serverEnvironment.removeKeybinding, {
59 reportFailure: false,
60 });
61 const persistProjectScripts = async (input: {
62 projectId: ProjectId;
63 projectCwd: string;
64 previousScripts: ReadonlyArray<ProjectScript>;
65 nextScripts: ReadonlyArray<ProjectScript>;
66 keybinding: NewProjectScriptInput["keybinding"];
67 keybindingCommand: KeybindingCommand | null;
68 }): Promise<AtomCommandResult<void, unknown>> => {
69 const serverConfig = appAtomRegistry.get(serverEnvironment.configValueAtom(environmentId));
70 const previousKeybinding = keybindingValueForCommand(
71 serverConfig?.keybindings ?? [],
72 input.keybindingCommand,
73 );
74 const isDeletingScript = !input.nextScripts.some(
75 (script) => commandForProjectScript(script.id) === input.keybindingCommand,
76 );
77 const changesKeybinding =
78 input.keybinding !== undefined &&
79 (input.keybinding?.trim() || null) !== previousKeybinding &&
80 (!isDeletingScript || readEnvironmentScope(environmentId, AuthSettingsWriteScope));
81 if (changesKeybinding && !readEnvironmentScope(environmentId, AuthSettingsWriteScope)) {
82 return AsyncResult.failure(
83 Cause.fail(
84 new EnvironmentAuthorizationError({
85 requiredScope: AuthSettingsWriteScope,
86 message: "This connection cannot change keyboard shortcuts.",
87 }),
88 ),
89 );
90 }
91 const keybindingRule = changesKeybinding
92 ? decodeProjectScriptKeybindingRule({
93 keybinding: input.keybinding,
94 command: input.keybindingCommand,
95 })
96 : null;
97 const updateResult = mapAtomCommandResult(
98 await updateProjectScriptSettings({
99 environmentId,
100 input: {
101 patch:
102 serverConfig?.environment.capabilities.projectSettingsOverrides === true
103 ? {
104 projectSettingsOverrides: {
105 [input.projectId]: {
106 ...settings.projectSettingsOverrides[input.projectId],
107 defaultProjectScripts: input.nextScripts,
108 },
109 },
110 }
111 : {
112 projectScriptOverrides: {
113 [input.projectId]: input.nextScripts,
114 },
115 },
116 },
117 }),
118 () => undefined,
119 );
120 if (updateResult._tag === "Failure") {
121 return updateResult;
122 }
123
124 if (!changesKeybinding) return updateResult;
125 if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) {
126 return AsyncResult.failure(
127 Cause.fail(
128 new EnvironmentAuthorizationError({
129 requiredScope: AuthSettingsWriteScope,
130 message: isDeletingScript
131 ? "The script was deleted, but its keyboard shortcut could not be removed because permission changed."
132 : "The script was saved, but this connection can no longer change keyboard shortcuts.",
133 }),
134 ),
135 );
136 }
137
138 const scriptId = input.keybindingCommand
139 ? projectScriptIdFromCommand(input.keybindingCommand)
140 : null;
141 if (!keybindingRule && !input.previousScripts.some((script) => script.id === scriptId)) {
142 return updateResult;
143 }
144 const retainedElsewhere =
145 !input.nextScripts.some((script) => script.id === scriptId) &&
146 (settings.defaultProjectScripts.some((script) => script.id === scriptId) ||
147 Object.entries(settings.projectSettingsOverrides).some(
148 ([projectId, entry]) =>
149 projectId !== input.projectId &&
150 entry.defaultProjectScripts?.some((script) => script.id === scriptId),
151 ) ||
152 allProjects.some(
153 (other) =>
154 other.environmentId === environmentId &&
155 other.id !== input.projectId &&
156 resolveProjectScripts(settings, other).some((script) => script.id === scriptId),
157 ));
158 if (!keybindingRule && retainedElsewhere) return updateResult;
159
160 const previousRules = (serverConfig?.keybindings ?? []).flatMap((binding) => {
161 if (binding.command !== input.keybindingCommand || binding.whenAst) return [];
162 const previous = decodeProjectScriptKeybindingRule({
163 keybinding: keybindingValueForCommand([binding], input.keybindingCommand),
164 command: input.keybindingCommand,
165 });
166 return previous ? [previous] : [];
167 });
168 const previous = previousRules.at(-1);
169 for (const rule of keybindingRule ? previousRules.slice(0, -1) : previousRules) {
170 const result = await removeKeybinding({ environmentId, input: rule });
171 if (result._tag === "Failure") return mapAtomCommandResult(result, () => undefined);
172 }
173 return keybindingRule
174 ? mapAtomCommandResult(
175 await upsertKeybinding({
176 environmentId,
177 input:
178 previous && previous.key !== keybindingRule.key
179 ? { ...keybindingRule, replace: previous }
180 : keybindingRule,
181 }),
182 () => undefined,
183 )
184 : updateResult;
185 };
186 const saveProjectScript = async (
187 input: NewProjectScriptInput,
188 ): Promise<AtomCommandResult<void, unknown>> => {
189 if (!project) {
190 return AsyncResult.success(undefined);
191 }
192 const nextId = nextProjectScriptId(
193 input.name,
194 scripts.map((script) => script.id),
195 );
196 const nextScript = buildProjectScript(nextId, input);
197 const nextScripts = [
198 ...scripts.map((script) => releaseClaimedRoles(script, input)),
199 nextScript,
200 ];
201
202 return persistProjectScripts({
203 projectId: project.id,
204 projectCwd: project.workspaceRoot,
205 previousScripts: scripts,
206 nextScripts,
207 keybinding: input.keybinding,
208 keybindingCommand: commandForProjectScript(nextId),
209 });
210 };
211 const updateProjectScript = async (
212 scriptId: string,
213 input: NewProjectScriptInput,
214 ): Promise<AtomCommandResult<void, unknown>> => {
215 if (!project) {
216 return AsyncResult.success(undefined);
217 }
218 const existingScript = scripts.find((script) => script.id === scriptId);
219 if (!existingScript) {
220 return AsyncResult.failure(Cause.fail(new Error("Script not found.")));
221 }
222
223 const updatedScript = buildProjectScript(existingScript.id, input);
224 const nextScripts = scripts.map((script) =>
225 script.id === scriptId ? updatedScript : releaseClaimedRoles(script, input),
226 );
227
228 return persistProjectScripts({
229 projectId: project.id,
230 projectCwd: project.workspaceRoot,
231 previousScripts: scripts,
232 nextScripts,
233 keybinding: input.keybinding,
234 keybindingCommand: commandForProjectScript(scriptId),
235 });
236 };
237 const deleteProjectScript = async (
238 scriptId: string,
239 ): Promise<AtomCommandResult<void, unknown>> => {
240 if (!project) {
241 return AsyncResult.success(undefined);
242 }
243 const nextScripts = scripts.filter((script) => script.id !== scriptId);
244
245 const deletedName = scripts.find((s) => s.id === scriptId)?.name;
246
247 const result = await persistProjectScripts({
248 projectId: project.id,
249 projectCwd: project.workspaceRoot,
250 previousScripts: scripts,
251 nextScripts,
252 keybinding: null,
253 keybindingCommand: commandForProjectScript(scriptId),
254 });
255 if (result._tag === "Success") {
256 toastManager.add({
257 type: "success",
258 title: `Deleted action "${deletedName ?? "Unknown"}"`,
259 });
260 } else if (!isAtomCommandInterrupted(result)) {
261 const error = squashAtomCommandFailure(result);
262 toastManager.add(
263 stackedThreadToast({
264 type: "error",
265 title: "Could not delete action",
266 description: error instanceof Error ? error.message : "An unexpected error occurred.",
267 }),
268 );
269 }
270 return result;
271 };
272 return {
273 saveProjectScript: useStableCallback(saveProjectScript),
274 updateProjectScript: useStableCallback(updateProjectScript),
275 deleteProjectScript: useStableCallback(deleteProjectScript),
276 };
277}