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 ProjectScopedServerSettingKey,
13 type ServerSettings,
14 type UnifiedSettings,
15} from "@t3tools/contracts";
16import { useCallback, useMemo } from "react";
17
18import {
19 mergeEnvironmentSettings,
20 persistClientSettingsPatch,
21 useClientSettings,
22 useMigrateModelPreferences,
23} from "../../hooks/useSettings";
24import { serverEnvironment } from "../../state/server";
25import { useAtomCommand } from "../../state/use-atom-command";
26import { toastManager } from "../ui/toast";
27import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeContext";
28import {
29 persistScopedSettingsPatch,
30 planProjectOverridesClear,
31 planScopedSettingsClear,
32 planScopedSettingsPatch,
33 scopedSettingsAreMixed,
34 scopedSettingsSource,
35 type ProjectOverrideEntry,
36 type ScopedSettingsPatch,
37} from "./scopedSettings";
38
39export function useScopedSettings<T = UnifiedSettings>(
40 selector?: (settings: UnifiedSettings) => T,
41): T {
42 const { target } = useSettingsScope();
43 const clientSettings = useClientSettings();
44 const serverSettings = target?.settings ?? DEFAULT_SERVER_SETTINGS;
45 useMigrateModelPreferences(target?.environmentId ?? null, target?.settings ?? null);
46 const settings = useMemo(
47 () => mergeEnvironmentSettings(serverSettings, clientSettings),
48 [clientSettings, serverSettings],
49 );
50 return useMemo(() => (selector ? selector(settings) : (settings as T)), [selector, settings]);
51}
52
53export function useScopedSettingsMixed(keys: readonly (keyof ServerSettings)[]): boolean {
54 const { targets } = useSettingsScope();
55 return scopedSettingsAreMixed(targets, keys);
56}
57
58export function useScopedSettingSource(keys: readonly (keyof ServerSettings)[]) {
59 const { targets } = useSettingsScope();
60 return scopedSettingsSource(targets, keys);
61}
62
63function useRunScopedPlan() {
64 const persistServer = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
65 return useCallback(
66 (plan: ReturnType<typeof planScopedSettingsPatch>) => {
67 if (plan.unavailableReason) {
68 toastManager.add({
69 type: "warning",
70 title: "Setting not saved",
71 description: plan.unavailableReason,
72 });
73 return;
74 }
75 void persistScopedSettingsPatch(
76 plan,
77 async (request) => {
78 const missing = requiredScopesForServerSettingsPatch(request.input.patch).find(
79 (scope) => !readEnvironmentScope(request.environmentId, scope),
80 );
81 if (missing)
82 return AsyncResult.failure(
83 Cause.fail(
84 new EnvironmentAuthorizationError({
85 requiredScope: missing,
86 message: "This connection lacks permission to change these settings.",
87 }),
88 ),
89 );
90 return persistServer(request);
91 },
92 persistClientSettingsPatch,
93 ).then(({ failedEnvironments, savedEnvironments, savedEnvironmentCount }) => {
94 if (failedEnvironments.length === 0) return;
95 toastManager.add({
96 type: "error",
97 title:
98 savedEnvironmentCount > 0 ? "Setting saved on some environments" : "Setting not saved",
99 description: [
100 ...failedEnvironments.map(
101 ({ label, message }) => `Could not save on ${label}: ${message}`,
102 ),
103 ...(savedEnvironmentCount > 0
104 ? [`Saved on ${savedEnvironments.map(({ label }) => label).join(", ")}.`]
105 : []),
106 ].join("\n"),
107 });
108 });
109 },
110 [persistServer],
111 );
112}
113
114export function useUpdateScopedSettings() {
115 const { scope, environments } = useSettingsScope();
116 const run = useRunScopedPlan();
117 return useCallback(
118 (patch: ScopedSettingsPatch) => run(planScopedSettingsPatch(scope, environments, patch)),
119 [environments, run, scope],
120 );
121}
122
123export function useClearScopedSettings() {
124 const context = useOptionalSettingsScope();
125 const run = useRunScopedPlan();
126 return useCallback(
127 (keys: readonly ProjectScopedServerSettingKey[]) => {
128 if (context === null) return;
129 run(planScopedSettingsClear(context.scope, context.environments, keys));
130 },
131 [context, run],
132 );
133}
134
135export function useClearProjectOverrides() {
136 const context = useOptionalSettingsScope();
137 const run = useRunScopedPlan();
138 return useCallback(
139 (entries: readonly ProjectOverrideEntry[], keys: readonly ProjectScopedServerSettingKey[]) => {
140 if (context === null) return;
141 run(planProjectOverridesClear(context.environments, entries, keys));
142 },
143 [context, run],
144 );
145}
146
147export function useScopedSettingsWriteAllowed() {
148 const { connectedEnvironments } = useSettingsScope();
149 const writable = useEnvironmentsWithScope(connectedEnvironments, AuthSettingsWriteScope);
150 return (
151 connectedEnvironments.length > 0 &&
152 connectedEnvironments.every((target) => writable.has(target.environmentId))
153 );
154}