Files
siftlode/frontend/src/lib/usePref.ts
T
peter 6a7ff330f6 refactor(frontend): the shared hooks in lib/ stop lying about their deps (E27 S2)
Ten more suppressions, and React 19 turns out to supply the missing primitive.

useEffectEvent (stable since React 19.2, which S1 brought in) is the canonical answer to the
"bind the listener once, but read the latest values" pattern these hooks were disabling the
checker for. Three of playerModalHooks' four escape hatches become honest dep lists: the
wheel-volume handler, the native-controls handover, and the fullscreen-change sync. The
contract is no longer prose — the compiler enforces it.

The fourth stays, deliberately, and now says why at the site: the YouTube player's lifecycle
effect must run once per video (re-running destroys and rebuilds the iframe), and YT.Player
takes its callbacks as an object literal, which an effect event may not be passed into.

Fixed, not suppressed:
- useDismiss captured onClose when the popover opened, so a caller that re-rendered with a
  different handler while it stayed open kept getting the OLD one called. The disabled dep list
  asserted the opposite ("read fresh from this run's closure"). Both the handler and the ref
  list are read through refs now; three tests, the two that matter mutation-checked.
- usePref wrapped its seed in a useCallback whose dep list had to be excused. useState calls a
  lazy initializer exactly once, so the memo was saving nothing; inlined.
- useCardPager clamped an out-of-range page from an effect. Adjusted during render instead —
  React discards that pass rather than committing it, so no out-of-range page is ever painted.
- plexPlayerHooks' auto-skip countdown reads its marker from the ref that already existed, so
  the dep list names its real inputs. That also made the set-state-in-effect finding go away:
  the progress is genuinely timer-driven, and the checker can now see that.
- useUrlMirror and useChipOverflowFit only needed their stable refs listed.

Two test-harness suppressions (a render-phase probe ref, a module-level setState handle) moved
inline with the reason they exist: both exist to observe a hook from outside without changing
what is being measured.

Suppressions 99 -> 89; exhaustive-deps 35 -> 27.
2026-09-21 00:07:12 +02:00

138 lines
6.5 KiB
TypeScript

import { useCallback, useEffect, useRef, useState } from "react";
import { useQueryClient, type QueryClient } from "@tanstack/react-query";
import { qk } from "./queryKeys";
import { api } from "./api";
import type { Me } from "./api/account";
import { readAccount, writeAccount } from "./storage";
import { notifyActionError } from "./actionErrors";
import { updateMeCache } from "./useMe";
import i18n from "../i18n";
// The local state + cache already show the new value, so a refused save is otherwise invisible until
// the next load quietly puts the old one back. `req` reports none of 403/404/429 and only the
// connection notice for a lost connection — say it (E11 S2b).
const reportPrefSaveFailure = (err: unknown) =>
notifyActionError(err, i18n.t("errors.writeFailed.prefs"));
// The ONE per-account + server preference hook. A preference (unlike an ephemeral filter) persists to
// the account on the server (PUT /api/me/preferences, which MERGES the partial payload) and follows the
// account across devices. usePref folds what every such pref used to hand-roll — seed local state, and
// on change write the server + an optional local mirror + the `me` cache — into one hook, so a new
// server-synced pref is a one-liner.
//
// It seeds straight from the `me` cache, which is always populated when it mounts: BootGate mounts the
// app tree only once /api/me has answered, and a tab whose account changes reloads, so there is nothing
// to adopt after mount. The source of truth is the server; the `me` cache is kept in sync optimistically so other
// consumers reading the same key (e.g. a second player instance) see the change at once.
export interface UsePrefOptions<T> {
/** Also mirror to per-account localStorage under this base key; that copy seeds the value when the
* server payload lacks the key. */
localKey?: string;
/** Debounce the server PUT by N ms so a slider drag / rapid toggles coalesce into one request. The
* local state + cache still update instantly; only the network write is deferred. */
debounceMs?: number;
/** Normalize a raw stored value (from the server payload or the localStorage mirror) into T — e.g.
* mapping legacy values forward, or clamping. Defaults to identity. Must be idempotent. */
parse?: (raw: unknown) => T;
}
function readServerPref(me: Me | null | undefined, key: string): unknown {
return me?.preferences?.[key];
}
// Optimistically merge a preferences patch into the `me` cache so readers see it without a refetch —
// the shape mirrors the server's PUT /api/me/preferences merge. Shared by useSavePref and usePref.set
// (their sole difference is WHEN the server write fires — immediately vs debounced), so the cache-merge
// shape lives in ONE place.
function mergePrefsCache(qc: QueryClient, patch: Record<string, unknown>): void {
updateMeCache(qc, (m) => ({ ...m, preferences: { ...m.preferences, ...patch } }));
}
/** The raw preference persister: save an arbitrary partial preferences patch to the server and merge
* it into the `me` cache optimistically (so readers see it without a refetch). For dynamic or
* multi-key prefs that don't map to a single stateful usePref call — e.g. a variable set of toggles
* (PlexInfo's per-collection strip-source hiding). Prefer usePref for a fixed, stateful key. */
export function useSavePref(): (patch: Record<string, unknown>) => void {
const qc = useQueryClient();
return useCallback(
(patch: Record<string, unknown>) => {
api.savePrefs(patch).catch(reportPrefSaveFailure);
mergePrefsCache(qc, patch);
},
[qc],
);
}
/** A per-account preference persisted to the server (and optionally mirrored to localStorage).
* Returns `[value, setValue]`; the setter is stable. */
export function usePref<T>(
serverKey: string,
defaultValue: T,
options: UsePrefOptions<T> = {},
): [T, (next: T) => void] {
const { localKey, debounceMs, parse } = options;
const qc = useQueryClient();
// Latest parse in a ref so the seed and the setter don't depend on a fresh closure each render (which
// would churn the memoized setter). parse must be idempotent anyway.
const parseRef = useRef(parse);
parseRef.current = parse;
const norm = useCallback((raw: unknown): T => {
const p = parseRef.current;
return p ? p(raw) : (raw as T);
}, []);
// Seeded inline rather than through a memoized `seed()`: useState calls a lazy initializer exactly
// once, at mount, so there was nothing for the useCallback to save — and its dep list was the one
// place in this file that had to be excused from the checker (it read `defaultValue` without
// naming it). Server preference wins, then the per-account localStorage mirror, then the default.
const [value, setValue] = useState<T>(() => {
const server = readServerPref(qc.getQueryData<Me | null>(qk.me()), serverKey);
if (server !== undefined) return norm(server);
if (localKey) return norm(readAccount(localKey, defaultValue));
return defaultValue;
});
const saveTimer = useRef<number | undefined>(undefined);
// The pending debounced server write, if any — flushed (NOT dropped) on unmount so the last change
// isn't lost. Dropping it would leave the server stale while local/cache/localStorage hold the new
// value, and the next load — which seeds from the server first — would bring the old value back.
const pendingSave = useRef<(() => void) | null>(null);
useEffect(
() => () => {
window.clearTimeout(saveTimer.current);
pendingSave.current?.();
pendingSave.current = null;
},
[],
);
const set = useCallback(
(next: T) => {
setValue(next);
if (localKey) writeAccount(localKey, next);
// Keep the `me` cache in step so other readers of this key (and a later mount of this hook,
// which seeds from the cache) see the new value without a refetch. Merges into preferences, mirroring the server PUT.
const payload = { [serverKey]: next };
mergePrefsCache(qc, payload);
// savePrefs is fire-and-forget (idempotent PUT, so `req` retries a transient blip once); a
// failure that survives that is reported, not swallowed.
const flush = () => api.savePrefs(payload).catch(reportPrefSaveFailure);
if (debounceMs) {
window.clearTimeout(saveTimer.current);
pendingSave.current = flush;
saveTimer.current = window.setTimeout(() => {
pendingSave.current = null;
flush();
}, debounceMs);
} else {
flush();
}
},
[qc, serverKey, localKey, debounceMs],
);
return [value, set];
}