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

useScopedSettings.ts

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