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

useSettings.ts

530 lines18.2 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 {
29 findSharedSettingsMismatches,
30 pickSharedServerSettings,
31 splitSharedServerPatch,
32 supportsSharedSettingsSync,
33} from "@t3tools/client-runtime/state/shared-settings";
34import { ensureLocalApi } from "~/localApi";
35import {
36 getThemeDefinition,
37 getThemePreviewSidebarArtwork,
38 resolveThemeHalf,
39 subscribeToThemePreview,
40 themeAllowsSidebarArtwork,
41} from "~/themePalette";
42import * as Struct from "effect/Struct";
43import { toastManager } from "~/components/ui/toast";
44import { isHostedStaticApp } from "~/hostedPairing";
45import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
46import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
47import { useAtomCommand } from "~/state/use-atom-command";
48import { useTheme } from "./useTheme";
49​
50const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
51​
52type UnifiedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
53​
54const clientSettingsListeners = new Set<() => void>();
55const clientSettingsHydrationListeners = new Set<() => void>();
56let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
57let clientSettingsHydrated = false;
58let clientSettingsHydrationPromise: Promise<void> | null = null;
59let clientSettingsHydrationGeneration = 0;
60let clientSettingsPersistenceQueue: Promise<void> = Promise.resolve();
61​
62function emitClientSettingsChange() {
63 for (const listener of clientSettingsListeners) {
64 listener();
65 }
67​
68function emitClientSettingsHydrationChange() {
69 for (const listener of clientSettingsHydrationListeners) {
70 listener();
71 }
73​
74function getClientSettingsSnapshot(): ClientSettings {
75 return clientSettingsSnapshot;
77​
78function replaceClientSettingsSnapshot(settings: ClientSettings): void {
79 clientSettingsSnapshot = settings;
80 emitClientSettingsChange();
82​
83function setClientSettingsHydrated(nextHydrated: boolean): void {
84 if (clientSettingsHydrated === nextHydrated) {
85 return;
86 }
87 clientSettingsHydrated = nextHydrated;
88 emitClientSettingsHydrationChange();
90​
91function subscribeClientSettings(listener: () => void): () => void {
92 clientSettingsListeners.add(listener);
93 void hydrateClientSettings();
94 return () => {
95 clientSettingsListeners.delete(listener);
96 };
98​
99function getClientSettingsHydratedSnapshot(): boolean {
100 return clientSettingsHydrated;
102​
103function subscribeClientSettingsHydration(listener: () => void): () => void {
104 clientSettingsHydrationListeners.add(listener);
105 void hydrateClientSettings();
106 return () => {
107 clientSettingsHydrationListeners.delete(listener);
108 };
110​
111async function hydrateClientSettings(): Promise<void> {
112 if (clientSettingsHydrated) {
113 return;
114 }
115 if (clientSettingsHydrationPromise) {
116 return clientSettingsHydrationPromise;
117 }
118​
119 const hydrationGeneration = clientSettingsHydrationGeneration;
120 const nextHydration = (async () => {
121 try {
122 const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
123 if (hydrationGeneration !== clientSettingsHydrationGeneration) {
124 return;
125 }
126 if (persistedSettings) {
127 replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
128 }
129 } catch (error) {
130 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, {
131 operation: "hydrate",
132 ...safeErrorLogAttributes(error),
133 });
134 } finally {
135 if (hydrationGeneration === clientSettingsHydrationGeneration) {
136 setClientSettingsHydrated(true);
137 }
138 }
139 })();
140​
141 const hydrationPromise = nextHydration.finally(() => {
142 if (clientSettingsHydrationPromise === hydrationPromise) {
143 clientSettingsHydrationPromise = null;
144 }
145 });
146 clientSettingsHydrationPromise = hydrationPromise;
147​
148 return clientSettingsHydrationPromise;
150​
151const defaultClientSettingsPersistence = (settings: ClientSettings): Promise<void> =>
152 ensureLocalApi().persistence.setClientSettings(settings);
153​
154function enqueueClientSettingsPersistence<A>(work: () => Promise<A>): Promise<A> {
155 const result = clientSettingsPersistenceQueue.then(work);
156 clientSettingsPersistenceQueue = result.then(
157 () => undefined,
158 () => undefined,
159 );
160 return result;
162​
163export function persistClientSettingsPatch(
164 patch: ClientSettingsPatch,
165 persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
166): void {
167 replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch });
168 void enqueueClientSettingsPersistence(() => persist(getClientSettingsSnapshot())).catch(
169 (error) => {
170 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, {
171 operation: "persist",
172 ...safeErrorLogAttributes(error),
173 });
174 },
175 );
177​
178/**
179 * Persists a client-settings update before publishing it to the in-memory
180 * snapshot. If another settings write lands while persistence is pending, the
181 * updater is reapplied to that newer snapshot and persisted again so neither
182 * change is lost.
183 */
184export async function persistClientSettingsUpdate(
185 update: (current: ClientSettings) => ClientSettings,
186 persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
187): Promise<ClientSettings> {
188 return enqueueClientSettingsPersistence(async () => {
189 for (;;) {
190 const current = getClientSettingsSnapshot();
191 const next = update(current);
192 await persist(next);
193 if (getClientSettingsSnapshot() === current) {
194 replaceClientSettingsSnapshot(next);
195 return next;
196 }
197 }
198 });
200​
201// ── Key sets for routing patches ─────────────────────────────────────
202​
203const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields));
204​
205function splitPatch(patch: UnifiedSettingsPatch): {
206 serverPatch: ServerSettingsPatch;
207 clientPatch: ClientSettingsPatch;
208} {
209 const serverPatch: Record<string, unknown> = {};
210 const clientPatch: Record<string, unknown> = {};
211 for (const [key, value] of Object.entries(patch)) {
212 if (SERVER_SETTINGS_KEYS.has(key)) {
213 serverPatch[key] = value;
214 } else {
215 clientPatch[key] = value;
216 }
217 }
218 return {
219 serverPatch: serverPatch as ServerSettingsPatch,
220 clientPatch: clientPatch as ClientSettingsPatch,
221 };
223​
224// ── Hooks ────────────────────────────────────────────────────────────
225​
226/**
227 * Non-hook accessor for the current merged client settings snapshot.
228 * Used by non-React code paths (e.g. runtime services) that need the latest
229 * settings without subscribing.
230 */
231export function getClientSettings(): ClientSettings {
232 return getClientSettingsSnapshot();
234​
235/**
236 * Resolves once client settings have been read from disk.
237 *
238 * The pre-hydration snapshot is just the schema defaults, so imperative paths
239 * that open a preview must await this or they bake the built-in viewport, zoom
240 * and appearance into a tab that never picks up the user's saved values.
241 */
242export function ensureClientSettingsHydrated(): Promise<void> {
243 return hydrateClientSettings();
245​
246export function useClientSettingsHydrated(): boolean {
247 return useSyncExternalStore(
248 subscribeClientSettingsHydration,
249 getClientSettingsHydratedSnapshot,
250 () => false,
251 );
253​
254function useClientSettingsValue(): ClientSettings {
255 return useSyncExternalStore(
256 subscribeClientSettings,
257 getClientSettingsSnapshot,
258 () => DEFAULT_CLIENT_SETTINGS,
259 );
261​
262export function mergeEnvironmentSettings(
263 serverSettings: ServerSettings,
264 clientSettings: ClientSettings,
265): UnifiedSettings {
266 // Decode drops retired client keys, but older untyped persistence adapters
267 // can still return them. Server-owned values must always win.
268 return { ...clientSettings, ...serverSettings };
270​
271function useMergedSettings<T>(
272 serverSettings: ServerSettings,
273 selector: ((settings: UnifiedSettings) => T) | undefined,
274): T {
275 const clientSettings = useClientSettingsValue();
276​
277 const merged = useMemo<UnifiedSettings>(
278 () => mergeEnvironmentSettings(serverSettings, clientSettings),
279 [clientSettings, serverSettings],
280 );
281​
282 return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
284​
285export function useClientSettings<T = ClientSettings>(
286 selector?: (settings: ClientSettings) => T,
287): T {
288 const settings = useClientSettingsValue();
289 return useMemo(() => (selector ? selector(settings) : (settings as T)), [selector, settings]);
291​
292export function resolveEnvironmentIdentificationMode(input: {
293 mode: EnvironmentIdentificationMode;
294 settingsHydrated: boolean;
295 paletteThemeActive?: boolean;
296 paletteThemeAllowsArtwork?: boolean;
297}): EnvironmentIdentificationMode {
298 // Avoid briefly rendering the default artwork before a persisted pill/none choice loads.
299 if (!input.settingsHydrated) return "none";
300 // Artwork palettes are maintained for built-ins only. Keep an explicit
301 // "none", but use the theme-aware pill for user-controlled palettes.
302 return input.paletteThemeActive && !input.paletteThemeAllowsArtwork && input.mode === "artwork"
303 ? "pill"
304 : input.mode;
306​
307export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
308 const settingsHydrated = useClientSettingsHydrated();
309 const mode = useClientSettingsValue().environmentIdentificationMode;
310 const { resolvedTheme, theme, themeHalves } = useTheme();
311 const previewSidebarArtwork = useSyncExternalStore(
312 subscribeToThemePreview,
313 getThemePreviewSidebarArtwork,
314 () => null,
315 );
316 const activeTheme = resolveThemeHalf(theme, themeHalves, resolvedTheme);
317 const activeThemeDefinition = getThemeDefinition(activeTheme);
318 return resolveEnvironmentIdentificationMode({
319 mode,
320 settingsHydrated,
321 paletteThemeActive: previewSidebarArtwork !== null || activeThemeDefinition !== null,
322 paletteThemeAllowsArtwork: previewSidebarArtwork ?? themeAllowsSidebarArtwork(activeTheme),
323 });
325​
326/**
327 * Whether the legacy sidebar (Settings → General → Legacy features) replaces
328 * the default one.
329 *
330 * Held at the default sidebar until client settings hydrate: the pre-hydration
331 * snapshot is just the schema defaults, so resolving against it could mount one
332 * sidebar and then swap it out once persisted settings land — remounting the
333 * whole tree for everyone instead of only for legacy opt-ins.
334 */
335export function useLegacySidebarEnabled(): boolean {
336 const settingsHydrated = useClientSettingsHydrated();
337 const legacySidebarEnabled = useClientSettingsValue().legacySidebarEnabled;
338 return settingsHydrated && legacySidebarEnabled;
340​
341/** Read current settings for one environment, merged with client-local preferences. */
342export function useEnvironmentSettings<T = UnifiedSettings>(
343 environmentId: EnvironmentId,
344 selector?: (settings: UnifiedSettings) => T,
345): T {
346 const serverSettings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));
347 return useMergedSettings(serverSettings ?? DEFAULT_SERVER_SETTINGS, selector);
349​
350/** Primary-only settings access for the settings UI and other explicitly global surfaces. */
351export function usePrimarySettings<T = UnifiedSettings>(
352 selector?: (settings: UnifiedSettings) => T,
353): T {
354 return useMergedSettings(useAtomValue(primaryServerSettingsAtom), selector);
356​
357export const PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE =
358 "This setting is saved on a server, and the hosted app is not anchored to one. Change it from the desktop app or from the server's own address.";
359​
360/**
361 * Whether primary-scoped server settings have a server to live on. The
362 * hosted app connects to every environment as a remote, so it has no primary:
363 * `usePrimarySettings` reads schema defaults there and writes have nowhere
364 * to go. Desktop and server-served web always have one.
365 */
366export function usePrimarySettingsAvailable(): boolean {
367 const primaryEnvironment = usePrimaryEnvironment();
368 return primaryEnvironment !== null || !isHostedStaticApp();
370​
371/** Environments that can receive a shared settings write right now. */
372function useSharedSettingsSyncTargetIds(): ReadonlyArray<EnvironmentId> {
373 const { environments } = useEnvironments();
374 return useMemo(
375 () =>
376 environments
377 .filter(supportsSharedSettingsSync)
378 .map((environment) => environment.environmentId),
379 [environments],
380 );
382​
383/**
384 * Returns an updater that routes each key to the correct backing store.
385 *
386 * Server keys are optimistically patched in atom-backed server state, then
387 * persisted via RPC. Shared server keys (see `SHARED_SERVER_SETTING_KEYS`)
388 * are written to every eligible sync target, not only the selected target, so
389 * a user preference does not silently drift between machines. Client keys go
390 * through client persistence.
391 */
392function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
393 const persistServerSettings = useAtomCommand(
394 serverEnvironment.updateSettings,
395 "server settings update",
396 );
397 const sharedSettingsSyncTargetIds = useSharedSettingsSyncTargetIds();
398 const updateSettings = useCallback(
399 (patch: UnifiedSettingsPatch) => {
400 const { serverPatch, clientPatch } = splitPatch(patch);
401​
402 if (Object.keys(serverPatch).length > 0) {
403 const { sharedPatch, localPatch } = splitSharedServerPatch(serverPatch);
404 // Dropping the write silently leaves the control looking saved.
405 const warnUnsaved = () =>
406 toastManager.add({
407 type: "warning",
408 title: "Setting not saved",
409 description: PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
410 });
411 if (Object.keys(localPatch).length > 0) {
412 if (environmentId) {
413 void persistServerSettings({
414 environmentId,
415 input: { patch: localPatch },
416 });
417 } else {
418 warnUnsaved();
419 }
420 }
421 if (Object.keys(sharedPatch).length > 0) {
422 const targets = new Set(sharedSettingsSyncTargetIds);
423 if (environmentId) {
424 targets.add(environmentId);
425 }
426 if (targets.size === 0) {
427 warnUnsaved();
428 }
429 for (const targetId of targets) {
430 void persistServerSettings({
431 environmentId: targetId,
432 input: { patch: sharedPatch },
433 });
434 }
435 }
436 }
437 if (Object.keys(clientPatch).length > 0) {
438 persistClientSettingsPatch(clientPatch);
439 }
440 },
441 [environmentId, persistServerSettings, sharedSettingsSyncTargetIds],
442 );
443​
444 return updateSettings;
446​
447/**
448 * Shared-settings sync targets whose values differ from the primary's,
449 * plus an action that writes the primary's values to all of them. Drift
450 * happens when an environment was offline during an edit or was changed by
451 * an older client.
452 */
453export function useSharedSettingsSync() {
454 const primaryEnvironment = usePrimaryEnvironment();
455 const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
456 // Read the loaded config, not `primaryServerSettingsAtom`: that atom falls
457 // back to defaults while the primary is disconnected, and "apply to all"
458 // must never push defaults over real values. Same for a primary too old to
459 // hold the shared keys: its decoded defaults are not a source of truth.
460 const primarySettings =
461 primaryEnvironment !== null && supportsSharedSettingsSync(primaryEnvironment)
462 ? (primaryEnvironment.serverConfig?.settings ?? null)
463 : null;
464 const { environments } = useEnvironments();
465 const persistServerSettings = useAtomCommand(
466 serverEnvironment.updateSettings,
467 "server settings update",
468 );
469​
470 const mismatches = useMemo(
471 () =>
472 findSharedSettingsMismatches({
473 primaryEnvironmentId,
474 primarySettings,
475 environments: environments.map((environment) => ({
476 environmentId: environment.environmentId,
477 label: environment.label,
478 syncEligible: supportsSharedSettingsSync(environment),
479 settings: environment.serverConfig?.settings ?? null,
480 })),
481 }),
482 [environments, primaryEnvironmentId, primarySettings],
483 );
484​
485 const applyToAll = useCallback(() => {
486 if (primarySettings === null) {
487 return;
488 }
489 const patch = pickSharedServerSettings(primarySettings);
490 for (const mismatch of mismatches) {
491 void persistServerSettings({
492 environmentId: mismatch.environmentId,
493 input: { patch },
494 });
495 }
496 }, [mismatches, persistServerSettings, primarySettings]);
497​
498 return { mismatches, applyToAll };
500​
501export function useUpdateEnvironmentSettings(environmentId: EnvironmentId) {
502 return useUpdateSettingsTarget(environmentId);
504​
505export function useUpdatePrimarySettings() {
506 return useUpdateSettingsTarget(usePrimaryEnvironment()?.environmentId ?? null);
508​
509export function useUpdateClientSettings() {
510 return useCallback((patch: ClientSettingsPatch) => {
511 persistClientSettingsPatch(patch);
512 }, []);
514​
515export function __resetClientSettingsPersistenceForTests(): void {
516 clientSettingsHydrationGeneration += 1;
517 clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
518 clientSettingsHydrated = false;
519 clientSettingsHydrationPromise = null;
520 clientSettingsPersistenceQueue = Promise.resolve();
521 clientSettingsListeners.clear();
522 clientSettingsHydrationListeners.clear();
524​
525export function __setClientSettingsForTests(settings: ClientSettings): void {
526 clientSettingsHydrationGeneration += 1;
527 clientSettingsSnapshot = settings;
528 clientSettingsHydrated = true;
529 clientSettingsHydrationPromise = null;