import { api, getToken } from "@/lib/api"; import type { UserPreferences } from "@/lib/types"; import { useUi } from "@/store/ui"; /** Seed the local browse settings from the signed-in user's saved preferences. */ export function applyPreferences( preferences: UserPreferences | null | undefined, ): void { if (!preferences) return; const ui = useUi.getState(); if (Array.isArray(preferences.ratings)) ui.setRatings(preferences.ratings); if (typeof preferences.ordering === "string") ui.setOrdering(preferences.ordering); if (typeof preferences.per_page === "number") ui.setPerPage(preferences.per_page); if (typeof preferences.zoom === "number") ui.setZoom(preferences.zoom); if (typeof preferences.e621_per_page === "number") { ui.setE621PerPage(preferences.e621_per_page); } } /** The browse settings currently in effect, as a preferences payload. */ export function preferencesPayload(extra?: UserPreferences): UserPreferences { const ui = useUi.getState(); return { ratings: ui.ratings, ordering: ui.ordering, per_page: ui.perPage, zoom: ui.zoom, e621_per_page: ui.e621PerPage, ...extra, }; } export function savePreferences( patch: UserPreferences, ): Promise { return api("/api/auth/preferences/", { method: "POST", json: patch, }); } let pending: number | null = null; let pendingPatch: UserPreferences = {}; /** * Persist browse settings for the signed-in user, debounced so slider drags * do not spam the API. Guests keep using localStorage only. */ export function schedulePreferenceSave(patch: UserPreferences): void { if (!getToken()) return; pendingPatch = { ...pendingPatch, ...patch }; if (pending !== null) window.clearTimeout(pending); pending = window.setTimeout(() => { pending = null; const body = preferencesPayload(pendingPatch); pendingPatch = {}; void savePreferences(body).catch(() => undefined); }, 700); }