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

useSettings.ts

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