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