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

useSettings.ts

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