Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useProjectScriptSettings.ts

210 lines7.7 KB

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