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

useSettings.ts

364 lines11.8 KB

1/**
2 * Environment-scoped settings hooks.
3 *
4 * Abstracts the split between server-authoritative settings (persisted in
5 * `settings.json` on the server, fetched via `server.getConfig`) and
6 * client-only settings (persisted in localStorage).
7 *
8 * Live server settings always require an environment id. Primary-environment
9 * access is intentionally named as such so environment-sensitive consumers
10 * cannot silently read the wrong server's settings.
11 */
12import { useCallback, useMemo, useSyncExternalStore } from "react";
13import { useAtomValue } from "@effect/atom-react";
14import {
15 DEFAULT_SERVER_SETTINGS,
16 type EnvironmentId,
17 ServerSettings,
18 type ServerSettingsPatch,
19} from "@t3tools/contracts";
20import {
21 type ClientSettingsPatch,
22 type ClientSettings,
23 DEFAULT_CLIENT_SETTINGS,
24 type EnvironmentIdentificationMode,
25 type UnifiedSettings,
26} from "@t3tools/contracts/settings";
27import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
28import { ensureLocalApi } from "~/localApi";
29import {
30 getThemeDefinition,
31 getThemePreviewSidebarArtwork,
32 resolveThemeHalf,
33 subscribeToThemePreview,
34} from "~/themePalette";
35import * as Struct from "effect/Struct";
36import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
37import { usePrimaryEnvironment } from "~/state/environments";
38import { useAtomCommand } from "~/state/use-atom-command";
39import { useTheme } from "./useTheme";
40​
41const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
42​
43type UnifiedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
44​
45const clientSettingsListeners = new Set<() => void>();
46const clientSettingsHydrationListeners = new Set<() => void>();
47let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
48let clientSettingsHydrated = false;
49let clientSettingsHydrationPromise: Promise<void> | null = null;
50let clientSettingsHydrationGeneration = 0;
51​
52function emitClientSettingsChange() {
53 for (const listener of clientSettingsListeners) {
54 listener();
55 }
57​
58function emitClientSettingsHydrationChange() {
59 for (const listener of clientSettingsHydrationListeners) {
60 listener();
61 }
63​
64function getClientSettingsSnapshot(): ClientSettings {
65 return clientSettingsSnapshot;
67​
68function replaceClientSettingsSnapshot(settings: ClientSettings): void {
69 clientSettingsSnapshot = settings;
70 emitClientSettingsChange();
72​
73function setClientSettingsHydrated(nextHydrated: boolean): void {
74 if (clientSettingsHydrated === nextHydrated) {
75 return;
76 }
77 clientSettingsHydrated = nextHydrated;
78 emitClientSettingsHydrationChange();
80​
81function subscribeClientSettings(listener: () => void): () => void {
82 clientSettingsListeners.add(listener);
83 void hydrateClientSettings();
84 return () => {
85 clientSettingsListeners.delete(listener);
86 };
88​
89function getClientSettingsHydratedSnapshot(): boolean {
90 return clientSettingsHydrated;
92​
93function subscribeClientSettingsHydration(listener: () => void): () => void {
94 clientSettingsHydrationListeners.add(listener);
95 void hydrateClientSettings();
96 return () => {
97 clientSettingsHydrationListeners.delete(listener);
98 };
100​
101async function hydrateClientSettings(): Promise<void> {
102 if (clientSettingsHydrated) {
103 return;
104 }
105 if (clientSettingsHydrationPromise) {
106 return clientSettingsHydrationPromise;
107 }
108​
109 const hydrationGeneration = clientSettingsHydrationGeneration;
110 const nextHydration = (async () => {
111 try {
112 const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
113 if (hydrationGeneration !== clientSettingsHydrationGeneration) {
114 return;
115 }
116 if (persistedSettings) {
117 replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
118 }
119 } catch (error) {
120 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, {
121 operation: "hydrate",
122 ...safeErrorLogAttributes(error),
123 });
124 } finally {
125 if (hydrationGeneration === clientSettingsHydrationGeneration) {
126 setClientSettingsHydrated(true);
127 }
128 }
129 })();
130​
131 const hydrationPromise = nextHydration.finally(() => {
132 if (clientSettingsHydrationPromise === hydrationPromise) {
133 clientSettingsHydrationPromise = null;
134 }
135 });
136 clientSettingsHydrationPromise = hydrationPromise;
137​
138 return clientSettingsHydrationPromise;
140​
141function persistClientSettings(settings: ClientSettings): void {
142 replaceClientSettingsSnapshot(settings);
143 void ensureLocalApi()
144 .persistence.setClientSettings(settings)
145 .catch((error) => {
146 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, {
147 operation: "persist",
148 ...safeErrorLogAttributes(error),
149 });
150 });
152​
153// ── Key sets for routing patches ─────────────────────────────────────
154​
155const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields));
156​
157function splitPatch(patch: UnifiedSettingsPatch): {
158 serverPatch: ServerSettingsPatch;
159 clientPatch: ClientSettingsPatch;
160} {
161 const serverPatch: Record<string, unknown> = {};
162 const clientPatch: Record<string, unknown> = {};
163 for (const [key, value] of Object.entries(patch)) {
164 if (SERVER_SETTINGS_KEYS.has(key)) {
165 serverPatch[key] = value;
166 } else {
167 clientPatch[key] = value;
168 }
169 }
170 return {
171 serverPatch: serverPatch as ServerSettingsPatch,
172 clientPatch: clientPatch as ClientSettingsPatch,
173 };
175​
176// ── Hooks ────────────────────────────────────────────────────────────
177​
178/**
179 * Non-hook accessor for the current merged client settings snapshot.
180 * Used by non-React code paths (e.g. runtime services) that need the latest
181 * settings without subscribing.
182 */
183export function getClientSettings(): ClientSettings {
184 return getClientSettingsSnapshot();
186​
187export function useClientSettingsHydrated(): boolean {
188 return useSyncExternalStore(
189 subscribeClientSettingsHydration,
190 getClientSettingsHydratedSnapshot,
191 () => false,
192 );
194​
195function useClientSettingsValue(): ClientSettings {
196 return useSyncExternalStore(
197 subscribeClientSettings,
198 getClientSettingsSnapshot,
199 () => DEFAULT_CLIENT_SETTINGS,
200 );
202​
203export function mergeEnvironmentSettings(
204 serverSettings: ServerSettings,
205 clientSettings: ClientSettings,
206): UnifiedSettings {
207 return { ...serverSettings, ...clientSettings };
209​
210function useMergedSettings<T>(
211 serverSettings: ServerSettings,
212 selector: ((settings: UnifiedSettings) => T) | undefined,
213): T {
214 const clientSettings = useClientSettingsValue();
215​
216 const merged = useMemo<UnifiedSettings>(
217 () => mergeEnvironmentSettings(serverSettings, clientSettings),
218 [clientSettings, serverSettings],
219 );
220​
221 return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
223​
224export function useClientSettings<T = ClientSettings>(
225 selector?: (settings: ClientSettings) => T,
226): T {
227 const settings = useClientSettingsValue();
228 return useMemo(() => (selector ? selector(settings) : (settings as T)), [selector, settings]);
230​
231export function resolveEnvironmentIdentificationMode(input: {
232 mode: EnvironmentIdentificationMode;
233 settingsHydrated: boolean;
234 paletteThemeActive?: boolean;
235 paletteThemeAllowsArtwork?: boolean;
236}): EnvironmentIdentificationMode {
237 // Avoid briefly rendering the default artwork before a persisted pill/none choice loads.
238 if (!input.settingsHydrated) return "none";
239 // Stage artwork has fixed colors that can clash with palette themes. Keep an
240 // explicit "none", but use the theme-aware pill in place of artwork.
241 return input.paletteThemeActive && !input.paletteThemeAllowsArtwork && input.mode === "artwork"
242 ? "pill"
243 : input.mode;
245​
246export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
247 const settingsHydrated = useClientSettingsHydrated();
248 const mode = useClientSettingsValue().environmentIdentificationMode;
249 const { resolvedTheme, theme, themeHalves } = useTheme();
250 const previewSidebarArtwork = useSyncExternalStore(
251 subscribeToThemePreview,
252 getThemePreviewSidebarArtwork,
253 () => null,
254 );
255 const activeTheme = resolveThemeHalf(theme, themeHalves, resolvedTheme);
256 const activeThemeDefinition = getThemeDefinition(activeTheme);
257 return resolveEnvironmentIdentificationMode({
258 mode,
259 settingsHydrated,
260 paletteThemeActive: previewSidebarArtwork !== null || activeThemeDefinition !== null,
261 paletteThemeAllowsArtwork:
262 previewSidebarArtwork ?? activeThemeDefinition?.sidebarArtwork === true,
263 });
265​
266/**
267 * Whether the legacy sidebar (Settings → General → Legacy features) replaces
268 * the default one.
269 *
270 * Held at the default sidebar until client settings hydrate: the pre-hydration
271 * snapshot is just the schema defaults, so resolving against it could mount one
272 * sidebar and then swap it out once persisted settings land — remounting the
273 * whole tree for everyone instead of only for legacy opt-ins.
274 */
275export function useLegacySidebarEnabled(): boolean {
276 const settingsHydrated = useClientSettingsHydrated();
277 const legacySidebarEnabled = useClientSettingsValue().legacySidebarEnabled;
278 return settingsHydrated && legacySidebarEnabled;
280​
281/** Read current settings for one environment, merged with client-local preferences. */
282export function useEnvironmentSettings<T = UnifiedSettings>(
283 environmentId: EnvironmentId,
284 selector?: (settings: UnifiedSettings) => T,
285): T {
286 const serverSettings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));
287 return useMergedSettings(serverSettings ?? DEFAULT_SERVER_SETTINGS, selector);
289​
290/** Primary-only settings access for the settings UI and other explicitly global surfaces. */
291export function usePrimarySettings<T = UnifiedSettings>(
292 selector?: (settings: UnifiedSettings) => T,
293): T {
294 return useMergedSettings(useAtomValue(primaryServerSettingsAtom), selector);
296​
297/**
298 * Returns an updater that routes each key to the correct backing store.
299 *
300 * Server keys are optimistically patched in atom-backed server state, then
301 * persisted via RPC. Client keys go through client persistence.
302 */
303function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
304 const persistServerSettings = useAtomCommand(
305 serverEnvironment.updateSettings,
306 "server settings update",
307 );
308 const updateSettings = useCallback(
309 (patch: UnifiedSettingsPatch) => {
310 const { serverPatch, clientPatch } = splitPatch(patch);
311​
312 if (Object.keys(serverPatch).length > 0) {
313 if (environmentId) {
314 void persistServerSettings({
315 environmentId,
316 input: { patch: serverPatch },
317 });
318 }
319 }
320 if (Object.keys(clientPatch).length > 0) {
321 persistClientSettings({
322 ...getClientSettingsSnapshot(),
323 ...clientPatch,
324 });
325 }
326 },
327 [environmentId, persistServerSettings],
328 );
329​
330 return updateSettings;
332​
333export function useUpdateEnvironmentSettings(environmentId: EnvironmentId) {
334 return useUpdateSettingsTarget(environmentId);
336​
337export function useUpdatePrimarySettings() {
338 return useUpdateSettingsTarget(usePrimaryEnvironment()?.environmentId ?? null);
340​
341export function useUpdateClientSettings() {
342 return useCallback((patch: ClientSettingsPatch) => {
343 persistClientSettings({
344 ...getClientSettingsSnapshot(),
345 ...patch,
346 });
347 }, []);
349​
350export function __resetClientSettingsPersistenceForTests(): void {
351 clientSettingsHydrationGeneration += 1;
352 clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
353 clientSettingsHydrated = false;
354 clientSettingsHydrationPromise = null;
355 clientSettingsListeners.clear();
356 clientSettingsHydrationListeners.clear();
358​
359export function __setClientSettingsForTests(settings: ClientSettings): void {
360 clientSettingsHydrationGeneration += 1;
361 clientSettingsSnapshot = settings;
362 clientSettingsHydrated = true;
363 clientSettingsHydrationPromise = null;