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

useScopedSettings.ts

160 lines5.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";
16import { useCallback, useMemo } from "react";
17​
18import {
19 mergeEnvironmentSettings,
20 persistClientSettingsPatch,
21 useClientSettings,
22} from "../../hooks/useSettings";
23import { serverEnvironment } from "../../state/server";
24import { useAtomCommand } from "../../state/use-atom-command";
25import { toastManager } from "../ui/toast";
26import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeContext";
27import {
28 persistScopedSettingsPatch,
29 planProjectOverridesClear,
30 planScopedSettingsClear,
31 planScopedSettingsPatch,
32 scopedSettingsAreMixed,
33 scopedSettingsSource,
34 type ProjectOverrideEntry,
35 type ScopedSettingsPatch,
36} from "./scopedSettings";
37​
38/** Effective settings for the representative target: project overrides applied on top of its environment. */
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 const settings = useMemo(
46 () => mergeEnvironmentSettings(serverSettings, clientSettings),
47 [clientSettings, serverSettings],
48 );
49 return useMemo(() => (selector ? selector(settings) : (settings as T)), [selector, settings]);
51​
52export function useScopedSettingsMixed(keys: readonly (keyof ServerSettings)[]): boolean {
53 const { targets } = useSettingsScope();
54 return scopedSettingsAreMixed(targets, keys);
56​
57/** Where the keys' effective values come from across the selected targets. */
58export function useScopedSettingSource(keys: readonly (keyof ServerSettings)[]) {
59 const { targets } = useSettingsScope();
60 return scopedSettingsSource(targets, keys);
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 );
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 );
122​
123/**
124 * Drop the project overrides for `keys` so the selected checkouts inherit
125 * again. Rows also render outside the settings layout (provider cards,
126 * dialogs), where there is no scope and nothing to clear.
127 */
128export function useClearScopedSettings() {
129 const context = useOptionalSettingsScope();
130 const run = useRunScopedPlan();
131 return useCallback(
132 (keys: readonly ProjectScopedServerSettingKey[]) => {
133 if (context === null) return;
134 run(planScopedSettingsClear(context.scope, context.environments, keys));
135 },
136 [context, run],
137 );
139​
140/** Clear `keys` on specific project entries, from an environment scope's chain popover. */
141export function useClearProjectOverrides() {
142 const context = useOptionalSettingsScope();
143 const run = useRunScopedPlan();
144 return useCallback(
145 (entries: readonly ProjectOverrideEntry[], keys: readonly ProjectScopedServerSettingKey[]) => {
146 if (context === null) return;
147 run(planProjectOverridesClear(context.environments, entries, keys));
148 },
149 [context, run],
150 );
152​
153export function useScopedSettingsWriteAllowed() {
154 const { connectedEnvironments } = useSettingsScope();
155 const writable = useEnvironmentsWithScope(connectedEnvironments, AuthSettingsWriteScope);
156 return (
157 connectedEnvironments.length > 0 &&
158 connectedEnvironments.every((target) => writable.has(target.environmentId))
159 );