Open History to see the last commit
1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { AuthSettingsWriteScope, EnvironmentAuthorizationError } from "@t3tools/contracts";
3import { readEnvironmentScope } from "../../state/session";
4import {
5 isAtomCommandInterrupted,
6 mapAtomCommandResult,
7 squashAtomCommandFailure,
8 type AtomCommandResult,
9} from "@t3tools/client-runtime/state/runtime";
10import {
11 type EnvironmentId,
12 type ProjectId,
13 type ProjectScript,
14 type ResolvedKeybindingsConfig,
15 type ServerSettings,
16} from "@t3tools/contracts";
17import { resolveProjectScripts } from "@t3tools/shared/projectScripts";
18import { clearProjectSettingsOverrides } from "@t3tools/shared/projectSettings";
19import * as Cause from "effect/Cause";
20import { AsyncResult } from "effect/reactivity";
21import { msg } from "gt-react";
22import { useRef, useState } from "react";
23
24import {
25 decodeProjectScriptKeybindingRule,
26 keybindingValueForCommand,
27} from "../../lib/projectScriptKeybindings";
28import {
29 buildProjectScript,
30 commandForProjectScript,
31 nextProjectScriptId,
32 releaseClaimedRoles,
33} from "../../projectScripts";
34import { useProjects } from "../../state/entities";
35import { serverEnvironment } from "../../state/server";
36import { useAtomCommand } from "../../state/use-atom-command";
37import type { NewProjectScriptInput } from "../projectScriptEditor";
38import { m } from "../../i18n/messages";
39import { toastManager } from "../ui/toast";
40
41function reportScriptFailure(result: AtomCommandResult<unknown, unknown>) {
42 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
43 const error = squashAtomCommandFailure(result);
44 toastManager.add({
45 type: "error",
46 title: m(msg("Failed to save project actions")),
47 description:
48 error instanceof Error
49 ? (thrownErrorMessage(error, m) ?? error.message)
50 : m(msg("An error occurred.")),
51 });
52 }
53 return mapAtomCommandResult(result, () => undefined);
54}
55
56export function useProjectScriptSettings(
57 targets: readonly {
58 environmentId: EnvironmentId;
59 settings: ServerSettings;
60 keybindings: ResolvedKeybindingsConfig;
61 project?: { id: ProjectId; scripts: readonly ProjectScript[] };
62 }[],
63) {
64 const projects = useProjects();
65 const [saving, setSaving] = useState(false);
66 const savingRef = useRef(false);
67 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, "project actions update");
68 const upsertKeybinding = useAtomCommand(
69 serverEnvironment.upsertKeybinding,
70 "action shortcut update",
71 );
72 const removeKeybinding = useAtomCommand(
73 serverEnvironment.removeKeybinding,
74 "action shortcut removal",
75 );
76
77 async function persist(
78 transform: (current: readonly ProjectScript[]) => readonly ProjectScript[] | null,
79 scriptId?: string,
80 keybinding?: string | null,
81 onSettingsSaved?: () => void,
82 ): Promise<AtomCommandResult<void, unknown>> {
83 if (savingRef.current || targets.length === 0) {
84 const message = m(msg("No available machine, or another action change is saving."));
85 toastManager.add({
86 type: "error",
87 title: m(msg("Actions not saved")),
88 description: message,
89 });
90 return AsyncResult.failure(Cause.fail(new Error(message)));
91 }
92 if (
93 targets.some(
94 ({ environmentId }) => !readEnvironmentScope(environmentId, AuthSettingsWriteScope),
95 )
96 ) {
97 return reportScriptFailure(
98 AsyncResult.failure(
99 Cause.fail(
100 new EnvironmentAuthorizationError({
101 requiredScope: AuthSettingsWriteScope,
102 message: m(msg("This connection cannot change environment settings.")),
103 }),
104 ),
105 ),
106 );
107 }
108 savingRef.current = true;
109 setSaving(true);
110 return writeTargets(transform, scriptId, keybinding, onSettingsSaved).finally(() => {
111 savingRef.current = false;
112 setSaving(false);
113 });
114 }
115
116 async function writeTargets(
117 transform: (current: readonly ProjectScript[]) => readonly ProjectScript[] | null,
118 scriptId: string | undefined,
119 keybinding: string | null | undefined,
120 onSettingsSaved: (() => void) | undefined,
121 ): Promise<AtomCommandResult<void, unknown>> {
122 for (const { environmentId, settings, keybindings, project } of targets) {
123 const current = project
124 ? resolveProjectScripts(settings, project)
125 : settings.defaultProjectScripts;
126 const nextScripts = transform(current);
127 const effectiveScripts = nextScripts ?? settings.defaultProjectScripts;
128 const result = await updateSettings({
129 environmentId,
130 input: {
131 patch: project
132 ? {
133 projectSettingsOverrides: {
134 [project.id]:
135 nextScripts === null
136 ? clearProjectSettingsOverrides(settings, project.id, [
137 "defaultProjectScripts",
138 ])
139 : {
140 ...settings.projectSettingsOverrides[project.id],
141 defaultProjectScripts: nextScripts,
142 },
143 },
144 }
145 : { defaultProjectScripts: nextScripts ?? [] },
146 },
147 });
148 if (result._tag === "Failure") return reportScriptFailure(result);
149 onSettingsSaved?.();
150 const changedIds = scriptId
151 ? [scriptId]
152 : current
153 .filter((script) => !effectiveScripts.some((next) => next.id === script.id))
154 .map((script) => script.id);
155 for (const id of changedIds) {
156 if (keybinding === undefined && effectiveScripts.some((script) => script.id === id)) {
157 continue;
158 }
159 const command = commandForProjectScript(id);
160 const previousValue = keybindingValueForCommand(keybindings, command);
161 const previous = previousValue
162 ? decodeProjectScriptKeybindingRule({ keybinding: previousValue, command })
163 : null;
164 const next = decodeProjectScriptKeybindingRule({ keybinding, command });
165 const retainedElsewhere =
166 !nextScripts?.some((script) => script.id === id) &&
167 ((project && settings.defaultProjectScripts.some((script) => script.id === id)) ||
168 Object.entries(settings.projectSettingsOverrides).some(
169 ([projectId, entry]) =>
170 projectId !== project?.id &&
171 entry.defaultProjectScripts?.some((script) => script.id === id),
172 ) ||
173 projects.some(
174 (other) =>
175 other.environmentId === environmentId &&
176 other.id !== project?.id &&
177 (project ? resolveProjectScripts(settings, other) : other.scripts).some(
178 (script) => script.id === id,
179 ),
180 ));
181 const bindingResult = next
182 ? await upsertKeybinding({
183 environmentId,
184 input: previous && previous.key !== next.key ? { ...next, replace: previous } : next,
185 })
186 : previous && !retainedElsewhere
187 ? await removeKeybinding({ environmentId, input: previous })
188 : null;
189 if (bindingResult?._tag === "Failure") return reportScriptFailure(bindingResult);
190 }
191 }
192 return AsyncResult.success(undefined);
193 }
194
195 function submit(
196 scriptId: string | null,
197 input: NewProjectScriptInput,
198 onActionCreated?: (scriptId: string) => void,
199 retryingCreation = false,
200 ) {
201 const existingIds = [
202 ...projects.flatMap((project) => project.scripts.map((script) => script.id)),
203 ...targets.flatMap(({ settings, project }) =>
204 [
205 ...settings.defaultProjectScripts,
206 ...Object.values(settings.projectSettingsOverrides).flatMap(
207 (entry) => entry.defaultProjectScripts ?? [],
208 ),
209 ...(project?.scripts ?? []),
210 ].map((script) => script.id),
211 ),
212 ];
213 const id = scriptId ?? nextProjectScriptId(input.name, existingIds);
214 const next = buildProjectScript(id, input);
215 const creating = scriptId === null || retryingCreation;
216 return persist(
217 (current) => {
218 const updated = current.map((script) =>
219 script.id === id ? next : releaseClaimedRoles(script, input),
220 );
221 // A retried creation may have reached only some targets before failing.
222 return creating && !current.some((script) => script.id === id)
223 ? [...updated, next]
224 : updated;
225 },
226 id,
227 input.keybinding,
228 creating ? () => onActionCreated?.(id) : undefined,
229 );
230 }
231
232 return { saving, persist, submit };
233}