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

useProjectScriptSettings.ts

207 lines7.6 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 const command = commandForProjectScript(id);
144 const previousValue = keybindingValueForCommand(keybindings, command);
145 const previous = previousValue
146 ? decodeProjectScriptKeybindingRule({ keybinding: previousValue, command })
147 : null;
148 const next = decodeProjectScriptKeybindingRule({ keybinding, command });
149 const retainedElsewhere =
150 !nextScripts?.some((script) => script.id === id) &&
151 ((project && settings.defaultProjectScripts.some((script) => script.id === id)) ||
152 Object.entries(settings.projectSettingsOverrides).some(
153 ([projectId, entry]) =>
154 projectId !== project?.id &&
155 entry.defaultProjectScripts?.some((script) => script.id === id),
156 ) ||
157 projects.some(
158 (other) =>
159 other.environmentId === environmentId &&
160 other.id !== project?.id &&
161 (project ? resolveProjectScripts(settings, other) : other.scripts).some(
162 (script) => script.id === id,
163 ),
164 ));
165 const bindingResult = next
166 ? await upsertKeybinding({
167 environmentId,
168 input: previous && previous.key !== next.key ? { ...next, replace: previous } : next,
169 })
170 : previous && !retainedElsewhere
171 ? await removeKeybinding({ environmentId, input: previous })
172 : null;
173 if (bindingResult?._tag === "Failure") return reportScriptFailure(bindingResult);
174 }
175 }
176 return AsyncResult.success(undefined);
177 }
178​
179 function submit(scriptId: string | null, input: NewProjectScriptInput) {
180 const existingIds = [
181 ...projects.flatMap((project) => project.scripts.map((script) => script.id)),
182 ...targets.flatMap(({ settings, project }) =>
183 [
184 ...settings.defaultProjectScripts,
185 ...Object.values(settings.projectSettingsOverrides).flatMap(
186 (entry) => entry.defaultProjectScripts ?? [],
187 ),
188 ...(project?.scripts ?? []),
189 ].map((script) => script.id),
190 ),
191 ];
192 const id = scriptId ?? nextProjectScriptId(input.name, existingIds);
193 const next = buildProjectScript(id, input);
194 return persist(
195 (current) => {
196 const updated = current.map((script) =>
197 script.id === id ? next : releaseClaimedRoles(script, input),
198 );
199 return scriptId === null ? [...updated, next] : updated;
200 },
201 id,
202 input.keybinding,
203 );
204 }
205​
206 return { saving, persist, submit };