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

useSettings.ts

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