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

useSettings.ts

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