Open History to see the last commit
1import { AuthSettingsWriteScope } from "@t3tools/contracts";
2import { useEnvironmentsWithScope } from "../../state/session";
3import {
4 requiredScopesForServerSettingsPatch,
5 EnvironmentAuthorizationError,
6} from "@t3tools/contracts";
7import { readEnvironmentScope } from "../../state/session";
8import * as Cause from "effect/Cause";
9import { AsyncResult } from "effect/reactivity";
10import {
11 DEFAULT_SERVER_SETTINGS,
12 type EnvironmentId,
13 type ProjectScopedServerSettingKey,
14 type ServerSettings,
15 type UnifiedSettings,
16} from "@t3tools/contracts";
17
18import { persistClientSettingsPatch, useMergedSettings } from "../../hooks/useSettings";
19import { appAtomRegistry } from "../../rpc/atomRegistry";
20import { readEnvironment } from "../../state/environments";
21import { serverEnvironment } from "../../state/server";
22import { useAtomCommand } from "../../state/use-atom-command";
23import { toastManager } from "../ui/toast";
24import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeContext";
25import {
26 createScopedSettingsWriter,
27 pendingScopedWritesAtom,
28 planProjectOverridesClear,
29 planScopedSettingsClear,
30 planScopedSettingsPatch,
31 scopedSettingsAreMixed,
32 scopedSettingsSource,
33 settlePendingScopedWrites,
34 type ProjectOverrideEntry,
35 type ScopedSettingsPatch,
36} from "./scopedSettings";
37
38const readSettings = (environmentId: EnvironmentId) =>
39 readEnvironment(environmentId)?.serverConfig?.settings ?? null;
40const writeScopedSettings = createScopedSettingsWriter(readSettings);
41
42export function useScopedSettings<T = UnifiedSettings>(
43 selector?: (settings: UnifiedSettings) => T,
44): T {
45 const { target } = useSettingsScope();
46 return useMergedSettings(target?.settings ?? DEFAULT_SERVER_SETTINGS, selector);
47}
48
49export function useScopedSettingsMixed(keys: readonly (keyof ServerSettings)[]): boolean {
50 const { targets } = useSettingsScope();
51 return scopedSettingsAreMixed(targets, keys);
52}
53
54export function useScopedSettingSource(keys: readonly (keyof ServerSettings)[]) {
55 const { targets } = useSettingsScope();
56 return scopedSettingsSource(targets, keys);
57}
58
59function useRunScopedPlan() {
60 const persistServer = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
61 return (
62 environments: Parameters<typeof writeScopedSettings>[0],
63 planner: Parameters<typeof writeScopedSettings>[1],
64 onFailed?: () => void,
65 ) => {
66 const plan = planner(environments);
67 if (plan.unavailableReason) {
68 toastManager.add({
69 type: "warning",
70 title: "Setting not saved",
71 description: plan.unavailableReason,
72 });
73 onFailed?.();
74 return;
75 }
76 const save = {};
77 const settle = (environmentId: EnvironmentId, saved?: ServerSettings) =>
78 appAtomRegistry.update(pendingScopedWritesAtom, (writes) =>
79 settlePendingScopedWrites(
80 writes,
81 { save, environmentId },
82 (id) => readSettings(id) ?? undefined,
83 saved,
84 ),
85 );
86 appAtomRegistry.update(pendingScopedWritesAtom, (writes) => [
87 ...writes,
88 ...plan.serverWrites.map(({ environmentId, patch }) => ({ save, environmentId, patch })),
89 ]);
90 void writeScopedSettings(
91 environments,
92 planner,
93 async (request) => {
94 const missing = requiredScopesForServerSettingsPatch(request.input.patch).find(
95 (scope) => !readEnvironmentScope(request.environmentId, scope),
96 );
97 const result = missing
98 ? AsyncResult.failure(
99 Cause.fail(
100 new EnvironmentAuthorizationError({
101 requiredScope: missing,
102 message: "This connection lacks permission to change these settings.",
103 }),
104 ),
105 )
106 : await persistServer(request).catch((error: unknown) => {
107 settle(request.environmentId);
108 throw error;
109 });
110 settle(request.environmentId, result._tag === "Success" ? result.value : undefined);
111 return result;
112 },
113 persistClientSettingsPatch,
114 ).then(({ failedEnvironments, savedEnvironments, savedEnvironmentCount }) => {
115 if (failedEnvironments.length === 0) return;
116 onFailed?.();
117 toastManager.add({
118 type: "error",
119 title:
120 savedEnvironmentCount > 0 ? "Setting saved on some environments" : "Setting not saved",
121 description: [
122 ...failedEnvironments.map(
123 ({ label, message }) => `Could not save on ${label}: ${message}`,
124 ),
125 ...(savedEnvironmentCount > 0
126 ? [`Saved on ${savedEnvironments.map(({ label }) => label).join(", ")}.`]
127 : []),
128 ].join("\n"),
129 });
130 });
131 };
132}
133
134export function useUpdateScopedSettings() {
135 const { scope, environments, deviceOnly } = useSettingsScope();
136 const run = useRunScopedPlan();
137 /** `onFailed` runs when any target rejects or drops the patch, so a draft can fall back. */
138 return (patch: ScopedSettingsPatch, options?: { readonly onFailed?: () => void }) =>
139 run(
140 environments,
141 (current) => planScopedSettingsPatch(scope, current, patch, { deviceOnly }),
142 options?.onFailed,
143 );
144}
145
146export function useClearScopedSettings() {
147 const context = useOptionalSettingsScope();
148 const run = useRunScopedPlan();
149 return (keys: readonly ProjectScopedServerSettingKey[]) => {
150 if (context === null) return;
151 run(context.environments, (current) => planScopedSettingsClear(context.scope, current, keys));
152 };
153}
154
155export function useClearProjectOverrides() {
156 const context = useOptionalSettingsScope();
157 const run = useRunScopedPlan();
158 return (
159 entries: readonly ProjectOverrideEntry[],
160 keys: readonly ProjectScopedServerSettingKey[],
161 ) => {
162 if (context === null) return;
163 run(context.environments, (current) => planProjectOverridesClear(current, entries, keys));
164 };
165}
166
167export function useScopedSettingsWriteAllowed() {
168 const { connectedEnvironments } = useSettingsScope();
169 const writable = useEnvironmentsWithScope(connectedEnvironments, AuthSettingsWriteScope);
170 return (
171 connectedEnvironments.length > 0 &&
172 connectedEnvironments.every((target) => writable.has(target.environmentId))
173 );
174}