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

useScopedSettings.ts

148 lines5.1 KB

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 ClientSettings,
13 type ProjectScopedServerSettingKey,
14 type ServerSettings,
15 type UnifiedSettings,
16} from "@t3tools/contracts";
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​
39// Callers often pass an inline selector; a separate hook keeps the merge cached across those.
40function useMergedSettings(serverSettings: ServerSettings, clientSettings: ClientSettings) {
41 "use memo";
42 return mergeEnvironmentSettings(serverSettings, clientSettings);
44​
45export function useScopedSettings<T = UnifiedSettings>(
46 selector?: (settings: UnifiedSettings) => T,
47): T {
48 const { target } = useSettingsScope();
49 const clientSettings = useClientSettings();
50 const serverSettings = target?.settings ?? DEFAULT_SERVER_SETTINGS;
51 useMigrateModelPreferences(target?.environmentId ?? null, target?.settings ?? null);
52 const settings = useMergedSettings(serverSettings, clientSettings);
53 return selector ? selector(settings) : (settings as T);
55​
56export function useScopedSettingsMixed(keys: readonly (keyof ServerSettings)[]): boolean {
57 const { targets } = useSettingsScope();
58 return scopedSettingsAreMixed(targets, keys);
60​
61export function useScopedSettingSource(keys: readonly (keyof ServerSettings)[]) {
62 const { targets } = useSettingsScope();
63 return scopedSettingsSource(targets, keys);
65​
66function useRunScopedPlan() {
67 const persistServer = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
68 return (plan: ReturnType<typeof planScopedSettingsPatch>) => {
69 if (plan.unavailableReason) {
70 toastManager.add({
71 type: "warning",
72 title: "Setting not saved",
73 description: plan.unavailableReason,
74 });
75 return;
76 }
77 void persistScopedSettingsPatch(
78 plan,
79 async (request) => {
80 const missing = requiredScopesForServerSettingsPatch(request.input.patch).find(
81 (scope) => !readEnvironmentScope(request.environmentId, scope),
82 );
83 if (missing)
84 return AsyncResult.failure(
85 Cause.fail(
86 new EnvironmentAuthorizationError({
87 requiredScope: missing,
88 message: "This connection lacks permission to change these settings.",
89 }),
90 ),
91 );
92 return persistServer(request);
93 },
94 persistClientSettingsPatch,
95 ).then(({ failedEnvironments, savedEnvironments, savedEnvironmentCount }) => {
96 if (failedEnvironments.length === 0) return;
97 toastManager.add({
98 type: "error",
99 title:
100 savedEnvironmentCount > 0 ? "Setting saved on some environments" : "Setting not saved",
101 description: [
102 ...failedEnvironments.map(
103 ({ label, message }) => `Could not save on ${label}: ${message}`,
104 ),
105 ...(savedEnvironmentCount > 0
106 ? [`Saved on ${savedEnvironments.map(({ label }) => label).join(", ")}.`]
107 : []),
108 ].join("\n"),
109 });
110 });
111 };
113​
114export function useUpdateScopedSettings() {
115 const { scope, environments } = useSettingsScope();
116 const run = useRunScopedPlan();
117 return (patch: ScopedSettingsPatch) => run(planScopedSettingsPatch(scope, environments, patch));
119​
120export function useClearScopedSettings() {
121 const context = useOptionalSettingsScope();
122 const run = useRunScopedPlan();
123 return (keys: readonly ProjectScopedServerSettingKey[]) => {
124 if (context === null) return;
125 run(planScopedSettingsClear(context.scope, context.environments, keys));
126 };
128​
129export function useClearProjectOverrides() {
130 const context = useOptionalSettingsScope();
131 const run = useRunScopedPlan();
132 return (
133 entries: readonly ProjectOverrideEntry[],
134 keys: readonly ProjectScopedServerSettingKey[],
135 ) => {
136 if (context === null) return;
137 run(planProjectOverridesClear(context.environments, entries, keys));
138 };
140​
141export function useScopedSettingsWriteAllowed() {
142 const { connectedEnvironments } = useSettingsScope();
143 const writable = useEnvironmentsWithScope(connectedEnvironments, AuthSettingsWriteScope);
144 return (
145 connectedEnvironments.length > 0 &&
146 connectedEnvironments.every((target) => writable.has(target.environmentId))
147 );