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