fix(boot): a new tab knows its account before anything renders
With Settings -> Appearance -> Startup turned off, every NEW tab or window still opened on Home; only a same-tab reload honoured it. The provider tree mounted before /api/me answered, so NavigationProvider's initializer could not read the per-account opt-out, landed on Home and mirrored ?page=home into the address bar. When App pinned the account a moment later, the re-hydrate re-read that mirror and stayed on Home. The same mount-then-patch shape made a new tab start on default filters, the default theme and the browser language, and correct each after the first paint. BootGate (main.tsx, above the providers) now owns the setup-status and /api/me queries and mounts the tree only once the identity is settled: it pins the tab's account and adopts the account's language in a layout effect, so the first frame of the app is already right. The tree is keyed on the account id, which makes "per-account state is read once, for this account" a structural guarantee. With that, the whole re-hydrate machinery is gone: useAccountRehydrate, the reactive active-account store, the markDirty guards, the pin-deferred saved-view seed and the present-dimension bookkeeping of the shared Channels/Plex links. PrefsProvider, FeedFiltersProvider, usePref and App's panel layouts seed from the me cache instead of adopting it in an effect; the theme is applied in layout effects. The app chunk is fetched in parallel with the probe, and the boot screen only fades its label in after 400 ms, on one clock across the gate and the Suspense fallback. Module switches no longer flash a placeholder either. Measured frame by frame in Chromium and WebKit, every first visit to a module showed "Loading..." for 17-70 ms: the lazy chunk's Suspense fallback, then often the first fetch's LoadingState. Pages are now lazyWithPreload components, and App fetches the chunks of every module the account can reach (plus the channel page) once the first page is idle; a preloaded page renders synchronously and never suspends. LoadingState, the one shared loading visual, fades in only after 300 ms, so a fast load shows nothing in between and a slow one still gets its spinner.
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
// @vitest-environment jsdom
|
||||
//
|
||||
// BootGate settles the tab's identity BEFORE the app tree mounts. The bug it replaced: a new tab (no
|
||||
// pinned account in sessionStorage) built the app for "no account" first — so with Settings →
|
||||
// Appearance → Startup turned off, NavigationProvider's initializer could not read the opt-out and
|
||||
// landed on Home, mirrored ?page=home into the address bar, and then re-read its own mirror when the
|
||||
// account was pinned, staying on Home. Only a same-tab reload (account already pinned) was right.
|
||||
//
|
||||
// Real NavigationProvider, real storage and i18n; only the two boot probes are stubbed. The probe
|
||||
// records EVERY render, so "never showed the wrong page, not even for one render" is what is asserted.
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { render, screen, cleanup, act } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import BootGate from "./BootGate";
|
||||
import { NavigationProvider, useNavigation } from "./NavigationProvider";
|
||||
import { api, type Me } from "../lib/api";
|
||||
import { ACTIVE_ACCOUNT_KEY } from "../lib/activeAccount";
|
||||
import i18n from "../i18n";
|
||||
|
||||
const renders: { page: string; lang: string }[] = [];
|
||||
function Probe() {
|
||||
const { page } = useNavigation();
|
||||
const { i18n: inst } = useTranslation();
|
||||
renders.push({ page, lang: inst.language });
|
||||
return <div data-testid="app">{page}</div>;
|
||||
}
|
||||
|
||||
function mount() {
|
||||
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
render(
|
||||
<QueryClientProvider client={qc}>
|
||||
<BootGate>
|
||||
<NavigationProvider>
|
||||
<Probe />
|
||||
</NavigationProvider>
|
||||
</BootGate>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
const account = (over: Partial<Me> = {}) => ({ id: 5, preferences: {}, ...over }) as Me;
|
||||
|
||||
beforeEach(async () => {
|
||||
localStorage.clear();
|
||||
sessionStorage.clear(); // a NEW tab: nothing pinned yet
|
||||
window.history.replaceState(null, "", "/");
|
||||
renders.length = 0;
|
||||
await i18n.changeLanguage("en");
|
||||
vi.spyOn(api, "setupStatus").mockResolvedValue({ configured: true });
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("BootGate", () => {
|
||||
it("a new tab with Startup off opens on the page the account left — never on Home first", async () => {
|
||||
localStorage.setItem("siftlode.startOnHome.5", "0");
|
||||
localStorage.setItem("siftlode.page.5", "downloads");
|
||||
vi.spyOn(api, "me").mockResolvedValue(account());
|
||||
mount();
|
||||
|
||||
expect((await screen.findByTestId("app")).textContent).toBe("downloads");
|
||||
expect(renders.map((r) => r.page)).toEqual(renders.map(() => "downloads"));
|
||||
expect(new URLSearchParams(window.location.search).get("page")).toBe("downloads");
|
||||
expect(sessionStorage.getItem(ACTIVE_ACCOUNT_KEY)).toBe("5"); // the tab is pinned
|
||||
});
|
||||
|
||||
it("renders the app in the account's language from its first render", async () => {
|
||||
vi.spyOn(api, "me").mockResolvedValue(account({ preferences: { language: "hu" } }));
|
||||
mount();
|
||||
|
||||
await screen.findByTestId("app");
|
||||
expect(renders.map((r) => r.lang)).toEqual(renders.map(() => "hu"));
|
||||
});
|
||||
|
||||
it("mounts nothing of the app while the identity is still unknown", async () => {
|
||||
vi.spyOn(api, "me").mockReturnValue(new Promise<Me | null>(() => {}));
|
||||
mount();
|
||||
await act(async () => {}); // the setup probe resolves; `me` never does
|
||||
|
||||
expect(screen.queryByTestId("app")).toBeNull();
|
||||
expect(renders).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("signed out: mounts the app (App shows the landing) without pinning an account", async () => {
|
||||
vi.spyOn(api, "me").mockResolvedValue(null);
|
||||
mount();
|
||||
|
||||
await screen.findByTestId("app");
|
||||
expect(sessionStorage.getItem(ACTIVE_ACCOUNT_KEY)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import { Fragment, useLayoutEffect, useState, type ReactNode } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { api, getActiveAccount, setActiveAccount } from "../lib/api";
|
||||
import { qk } from "../lib/queryKeys";
|
||||
import i18n, { isSupported, setLanguage } from "../i18n";
|
||||
import { StateMessage } from "./ui/QueryState";
|
||||
|
||||
// The boot sequence, in ONE place: nothing of the app renders until this tab knows WHO it is.
|
||||
//
|
||||
// Per-account state is everywhere — the landing page, the feed's filters, the Plex scope, the manager's
|
||||
// tab, the theme, the language — and all of it is read synchronously when its provider mounts. Those
|
||||
// providers used to mount before /api/me answered, so a new tab first built the app for "no account"
|
||||
// (defaults: Home instead of the page you left, the default theme, the browser language) and then
|
||||
// patched each piece once <App> pinned the account. Every patch was a visible jump at best, and at
|
||||
// worst it read a value the first pass had already written (the landing page mirrored ?page=home into
|
||||
// the address bar, then re-read its own mirror and stayed on Home). So the order is inverted instead:
|
||||
// settle the identity, adopt what must be adopted before a single pixel of the app is drawn, THEN mount
|
||||
// the provider tree — whose initializers are then simply right, with nothing to re-read.
|
||||
//
|
||||
// The tree is keyed on the account id, which enforces that in code rather than in a comment: if a tab's
|
||||
// identity ever changed without a reload, every per-account initializer would run again for the new
|
||||
// account instead of holding the previous one's values. (Today every switch reloads — NavSidebar.)
|
||||
|
||||
/** The quiet screen shown while the tab's identity (or the app chunk) is still on its way. On a normal
|
||||
* connection that is a few hundred milliseconds, and a "Loading…" label flashed for that long reads as
|
||||
* a flicker, not as information — so the label only fades in once the wait is long enough to need one.
|
||||
* The delay counts from navigation start, not from mount, so the gate's screen and the Suspense
|
||||
* fallback that may follow it keep one clock instead of each restarting the fade. */
|
||||
export function BootScreen() {
|
||||
const { t } = useTranslation();
|
||||
const [wait] = useState(() => LABEL_DELAY_MS - performance.now());
|
||||
return (
|
||||
<div className="min-h-screen grid place-items-center text-muted">
|
||||
<span style={wait > 0 ? { animation: `fadeIn 0.2s ease ${wait}ms both` } : undefined}>
|
||||
{t("common.loading")}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const LABEL_DELAY_MS = 400;
|
||||
|
||||
export default function BootGate({ children }: { children: ReactNode }) {
|
||||
const { t } = useTranslation();
|
||||
// First-run install gate: a fresh instance reports configured=false and runs in setup mode, where
|
||||
// every other route is locked — so `me` is held back until the instance is known to be set up
|
||||
// (otherwise it would 503 against the setup-mode lock).
|
||||
const setupQuery = useQuery({
|
||||
queryKey: qk.setupStatus(),
|
||||
queryFn: api.setupStatus,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
const needsSetup = setupQuery.data?.configured === false;
|
||||
// THE fetching `me` query; every other reader is a passive (enabled:false) observer of its cache.
|
||||
// Polled while signed in so an account an admin suspends or deletes is noticed with no interaction:
|
||||
// the refetch 401s and App's handler drops to the login page. Not polled signed out — that refetch
|
||||
// is pointless and used to flicker the public landing.
|
||||
const meQuery = useQuery({
|
||||
queryKey: qk.me(),
|
||||
queryFn: api.me,
|
||||
enabled: setupQuery.isSuccess && !needsSetup,
|
||||
refetchInterval: (query) => (query.state.data ? 60_000 : false),
|
||||
});
|
||||
const me = meQuery.data;
|
||||
|
||||
// Who this tab is, once known: an account id, `null` for "nobody" (signed out, setup mode, or no
|
||||
// setup answer at all — App renders the landing / the wizard for those), `undefined` while unknown.
|
||||
// Keyed on the DATA, not the status: a background refetch that fails keeps the last answer, so a
|
||||
// server blip never tears the whole app down to this screen.
|
||||
const identity: number | null | undefined = setupQuery.isPending
|
||||
? undefined
|
||||
: !setupQuery.isSuccess || needsSetup
|
||||
? null
|
||||
: me === undefined
|
||||
? undefined
|
||||
: (me?.id ?? null);
|
||||
|
||||
// Adopt the identity before the tree mounts. A layout effect, so the re-render it triggers happens
|
||||
// before the browser paints: the frame that first shows the app already has the account pinned.
|
||||
// • Pin this tab to the account it loaded as. Without the pin, a tab riding the session's default
|
||||
// account would silently swap identity when ANOTHER tab changes that default (adds or switches
|
||||
// an account); once pinned it sends its own account header. An explicit switch on THIS tab sets
|
||||
// the pin itself, so this is a no-op then.
|
||||
// • Adopt the account's language, which follows the account across devices — the local copy only
|
||||
// knows what this browser last showed.
|
||||
const [readyFor, setReadyFor] = useState<number | null | undefined>(undefined);
|
||||
useLayoutEffect(() => {
|
||||
if (identity === undefined) return;
|
||||
if (me && getActiveAccount() == null) setActiveAccount(me.id);
|
||||
const lang = me?.preferences?.language;
|
||||
if (typeof lang === "string" && isSupported(lang) && lang !== i18n.language) setLanguage(lang);
|
||||
setReadyFor(identity);
|
||||
// `me` is read for the identity it produced; a background refetch of the same account must not
|
||||
// re-run the adoption over a language the user has just changed.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [identity]);
|
||||
|
||||
// No answer at all (a network or 5xx failure on the very first probe): say so, with a retry. After
|
||||
// a retry the identity lands and the tree mounts from scratch, like any first load.
|
||||
if (me === undefined && meQuery.isError)
|
||||
return (
|
||||
<div className="min-h-screen grid place-items-center">
|
||||
<StateMessage tone="error" onRetry={() => meQuery.refetch()}>
|
||||
{t("common.somethingWrong")}
|
||||
</StateMessage>
|
||||
</div>
|
||||
);
|
||||
if (identity === undefined || readyFor !== identity) return <BootScreen />;
|
||||
return <Fragment key={identity ?? "anon"}>{children}</Fragment>;
|
||||
}
|
||||
@@ -17,7 +17,6 @@ vi.mock("./NavigationProvider", () => ({
|
||||
}));
|
||||
|
||||
import { ChannelsProvider, useChannels, useChannelsActions } from "./ChannelsProvider";
|
||||
import { setActiveAccount } from "../lib/api/core";
|
||||
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<ChannelsProvider>{children}</ChannelsProvider>
|
||||
@@ -101,20 +100,17 @@ describe("ChannelsProvider — S8 shareable URL", () => {
|
||||
expect(new URLSearchParams(window.location.search).has("ctab")).toBe(false);
|
||||
});
|
||||
|
||||
it("a PARTIAL shared link (fresh tab) does not clobber the account's stored sort/filters", () => {
|
||||
// Regression: on a fresh tab the account pins AFTER mount, so the seed's base for the OMITTED
|
||||
// dimensions was read as defaults. Persisting the whole seed used to overwrite the account's real
|
||||
// stored sort + filter map. The fix persists ONLY the URL-present dimensions.
|
||||
it("a PARTIAL shared link does not clobber the account's stored sort/filters", () => {
|
||||
// Regression: the seed's base for the OMITTED dimensions used to be read as defaults, and
|
||||
// persisting the seed overwrote the account's real stored sort + filter map.
|
||||
localStorage.setItem(
|
||||
"siftlode.channelSort.1",
|
||||
JSON.stringify({ key: "subscribers", dir: "desc" }),
|
||||
);
|
||||
localStorage.setItem("siftlode.channelsFilterMap.1", JSON.stringify({ sync: "needsFull" }));
|
||||
sessionStorage.removeItem("siftlode.activeAccount"); // account not pinned yet at mount
|
||||
window.history.replaceState({ sfPage: "channels" }, "", "/?ctab=hidden"); // only the tab in the URL
|
||||
|
||||
const { result } = render();
|
||||
act(() => setActiveAccount(1)); // App pins the account after /api/me
|
||||
|
||||
// The present dim (tab) is adopted from the link...
|
||||
expect(result.current.view).toBe("hidden");
|
||||
|
||||
@@ -9,12 +9,11 @@ import {
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { getAccountRaw, setAccountRaw, LS } from "../lib/storage";
|
||||
import { getAccountRaw, LS } from "../lib/storage";
|
||||
import { parseChannelLayout, type ChannelLayout } from "../lib/channelLayout";
|
||||
import { hydrateSort, type SortState } from "../lib/columnSort";
|
||||
import { useSortState } from "../lib/useSortState";
|
||||
import { useFilterState } from "../lib/useFilterState";
|
||||
import { useActiveAccountId } from "../lib/activeAccount";
|
||||
import { useUrlMirror } from "../lib/useUrlMirror";
|
||||
import { rememberNavPosition } from "../lib/history";
|
||||
import {
|
||||
@@ -74,25 +73,16 @@ function readStoredFilters(): FilterMap {
|
||||
// present, the URL wins over this account's stored view — read once at mount and applied over the slice
|
||||
// hooks (see the provider). The keys are channels-unique, so their mere presence identifies a shared
|
||||
// manager view; no ?page check is needed (the mirror below is page-gated so it never pollutes others).
|
||||
// The seed = the URL-merged state PLUS which dimensions the URL actually carried. `present` matters
|
||||
// because the base below is read at MOUNT, before the account is pinned (getAccountRaw returns null),
|
||||
// so an OMITTED dimension's base is a default, not this account's stored value. The provider seeds and
|
||||
// persists only the PRESENT dimensions and lets the absent ones re-hydrate from storage normally —
|
||||
// otherwise a partial shared link silently resets the omitted stored sort / filter map.
|
||||
type ChannelsSeedPresent = { view: boolean; sort: boolean; filters: boolean };
|
||||
type ChannelsUrlSeed = { state: ChannelsUrlState; present: ChannelsSeedPresent };
|
||||
function readChannelsUrlSeed(): ChannelsUrlSeed | null {
|
||||
// The base is this account's stored view (BootGate pins the account before this provider mounts), so
|
||||
// a PARTIAL link — one carrying only the tab, say — keeps the stored sort and filter map for the rest.
|
||||
function readChannelsUrlSeed(): ChannelsUrlState | null {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (!hasChannelsParams(params)) return null;
|
||||
const state = channelsParamsToState(params, {
|
||||
return channelsParamsToState(params, {
|
||||
view: clampView(getAccountRaw(LS.channelsView)),
|
||||
sort: hydrateSort(getAccountRaw(LS.channelSort), [], null),
|
||||
filters: readStoredFilters(),
|
||||
});
|
||||
return {
|
||||
state,
|
||||
present: { view: params.has("ctab"), sort: params.has("csort"), filters: params.has("cf") },
|
||||
};
|
||||
}
|
||||
|
||||
type ChannelsState = {
|
||||
@@ -168,10 +158,9 @@ export function ChannelsProvider({ children }: { children: ReactNode }) {
|
||||
// The subscribed table's column-filter map, owned here (lifted out of DataTable) so the top status
|
||||
// chips, the Sync column funnel, and the card layout share one state; useFilterState persists it.
|
||||
const [filters, setFilters] = useFilterState(LS.channelsFilterMap, migrateSyncChip);
|
||||
// view + layout are persisted tabs (usePersistedTab = the shared account-scoped tab-state hook), so
|
||||
// they get init-from-storage AND the account-pin re-hydrate for free (this provider mounts above
|
||||
// <App>, which pins the account only after /api/me). Stored un-clamped; clampView/parseChannelLayout
|
||||
// heal them for display. setView layers the history logic (below) on top of the raw setter.
|
||||
// view + layout are persisted tabs (usePersistedTab = the shared account-scoped tab-state hook).
|
||||
// Stored un-clamped; clampView/parseChannelLayout heal them for display. setView layers the history
|
||||
// logic (below) on top of the raw setter.
|
||||
const [viewRaw, setViewRaw] = usePersistedTab(LS.channelsView, "subscribed");
|
||||
const view = clampView(viewRaw);
|
||||
const [layoutRaw, setLayout] = usePersistedTab(LS.channelLayout, "table");
|
||||
@@ -185,43 +174,20 @@ export function ChannelsProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
// S8 — shareable manager view. Captured once at mount (or null when no manager URL keys are present).
|
||||
const [urlSeed] = useState(readChannelsUrlSeed);
|
||||
const accountId = useActiveAccountId();
|
||||
const seededRef = useRef(false);
|
||||
const persistedRef = useRef(false);
|
||||
|
||||
// Apply the shared-link seed once, BEFORE paint, through the slice setters. Going through the setters
|
||||
// (not raw state) is deliberate: each one calls its hook's markDirty, so the account-pin re-hydrate
|
||||
// (which fires later on a fresh tab) sees the slice as user-edited and won't reload the stored view
|
||||
// over the shared one. setViewRaw (not setView) restores the tab without pushing a phantom history
|
||||
// entry. A normal load has urlSeed === null and this is a no-op.
|
||||
// Apply the shared-link seed once, BEFORE paint, through the slice setters — which persist it, so the
|
||||
// shared view also survives a later PLAIN reload (no URL). setViewRaw (not setView) restores the tab
|
||||
// without pushing a phantom history entry. A normal load has urlSeed === null and this is a no-op.
|
||||
useLayoutEffect(() => {
|
||||
if (!urlSeed || seededRef.current) return;
|
||||
seededRef.current = true;
|
||||
// Only apply the dimensions the URL actually carried. An omitted dimension must NOT go through its
|
||||
// setter (which would markDirty and block the account-pin re-hydrate from loading the stored value)
|
||||
// — leave it to hydrate from storage normally. Fixes a partial link wiping the stored sort/filters.
|
||||
const { state, present } = urlSeed;
|
||||
if (present.view && state.view !== view) setViewRaw(state.view);
|
||||
if (present.filters) setFilters(state.filters);
|
||||
if (present.sort) setSort(state.sort);
|
||||
if (urlSeed.view !== view) setViewRaw(urlSeed.view);
|
||||
setFilters(urlSeed.filters);
|
||||
setSort(urlSeed.sort);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// On a fresh tab the account pins AFTER mount, so the seed's setter writes above no-op'd (no account
|
||||
// yet). Persist the seed to the account once it's known, so the shared view also survives a later
|
||||
// PLAIN reload (no URL) — mirrors PlexProvider's rehydrate-persist. The slice hooks' own re-hydrate
|
||||
// already skips (marked dirty above), so this only touches storage, not state.
|
||||
useEffect(() => {
|
||||
if (!urlSeed || accountId == null || persistedRef.current) return;
|
||||
persistedRef.current = true;
|
||||
// Persist ONLY the URL-present dimensions — the omitted ones were seeded from mount-time defaults
|
||||
// (no account yet), so writing them here would overwrite the account's real stored sort/filter map.
|
||||
const { state, present } = urlSeed;
|
||||
if (present.view) setAccountRaw(LS.channelsView, state.view);
|
||||
if (present.filters) setAccountRaw(LS.channelsFilterMap, JSON.stringify(state.filters));
|
||||
if (present.sort) setAccountRaw(LS.channelSort, JSON.stringify(state.sort));
|
||||
}, [urlSeed, accountId]);
|
||||
|
||||
// Latest-value ref so the STABLE setView can compare against the current tab without depending on
|
||||
// it (a dep would recreate the action on every switch and re-render every actions consumer).
|
||||
// Written during render — the sanctioned pattern NavigationProvider uses for `pageRef`.
|
||||
@@ -237,7 +203,7 @@ export function ChannelsProvider({ children }: { children: ReactNode }) {
|
||||
// Re-selecting the tab you are already on is not a navigation — bail before pushing, or clicking
|
||||
// the active tab (and goToFullHistory forcing "subscribed") stacks Back entries that do nothing.
|
||||
if (v === viewRef.current) return;
|
||||
setViewRaw(v); // persists + guards the account-pin re-hydrate (via usePersistedTab)
|
||||
setViewRaw(v); // persists (via usePersistedTab)
|
||||
// Only own an entry while the manager is already on screen. Arriving from elsewhere
|
||||
// (focusChannel / goToFullHistory) lets setPage push the entry — the stamp effect labels it — so
|
||||
// one navigation never costs two Back presses.
|
||||
|
||||
@@ -8,14 +8,14 @@ import {
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { qk } from "../lib/queryKeys";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
api,
|
||||
getActiveAccount,
|
||||
coerceTagModes,
|
||||
coerceUntagged,
|
||||
DEFAULT_TAG_MODES,
|
||||
type FeedFilters,
|
||||
type Me,
|
||||
} from "../lib/api";
|
||||
import { filterParamUpdates, hasFilterParams, paramsToFilters } from "../lib/urlState";
|
||||
import { useUrlMirror } from "../lib/useUrlMirror";
|
||||
@@ -53,9 +53,8 @@ const DEFAULT_FILTERS: FeedFilters = {
|
||||
|
||||
const FILTERS_KEY = LS.filters;
|
||||
|
||||
// This account's own persisted filters (per-account keys — never another account's). When the
|
||||
// account isn't known yet (first load, before the tab is pinned), start from defaults; the post-login
|
||||
// effect loads the real ones once the id arrives.
|
||||
// This account's own persisted filters (per-account keys — never another account's). No account
|
||||
// (signed out) → defaults.
|
||||
export function loadAccountFilters(id: number | null): FeedFilters {
|
||||
// Your last-applied filters win, so a reload keeps whatever view you're on (a saved view you
|
||||
// picked, or manual tweaks) — setFilters persists them under LS.filters on every change. A starred
|
||||
@@ -87,10 +86,12 @@ export function loadAccountFilters(id: number | null): FeedFilters {
|
||||
}
|
||||
|
||||
// URL wins over localStorage so a pasted link reproduces the exact view.
|
||||
function loadInitialFilters(): FeedFilters {
|
||||
function loadInitialFilters(me: Me | null | undefined): FeedFilters {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (hasFilterParams(params)) return paramsToFilters(params, DEFAULT_FILTERS);
|
||||
return loadAccountFilters(getActiveAccount());
|
||||
const f = loadAccountFilters(getActiveAccount());
|
||||
// The shared demo account has no subscriptions, so default it to the whole library.
|
||||
return me?.is_demo ? { ...f, scope: "all" } : f;
|
||||
}
|
||||
|
||||
interface FeedFiltersActions {
|
||||
@@ -108,18 +109,18 @@ export function useFeedFiltersActions(): FeedFiltersActions {
|
||||
}
|
||||
|
||||
export function FeedFiltersProvider({ children }: { children: ReactNode }) {
|
||||
const [filters, setFiltersState] = useState<FeedFilters>(loadInitialFilters);
|
||||
const qc = useQueryClient();
|
||||
// Seeded for the account this tab is — BootGate mounts this provider only once the account is
|
||||
// pinned and `me` is cached, so this is the account's own view from the first render.
|
||||
const [filters, setFiltersState] = useState<FeedFilters>(() =>
|
||||
loadInitialFilters(qc.getQueryData<Me | null>(qk.me())),
|
||||
);
|
||||
// Whether this load arrived with feed-filter params in the URL (a bookmark/shared link). Captured
|
||||
// once at mount — such filters win over the account's stored view and are persisted to the account.
|
||||
const [initialHadUrlFilters] = useState(() =>
|
||||
hasFilterParams(new URLSearchParams(window.location.search)),
|
||||
);
|
||||
|
||||
// Passive observer: App owns the fetching `qk.me()` query (gated on setup state); enabled:false
|
||||
// here reads its cache and re-renders when it lands, without triggering a second fetch (which
|
||||
// could 503 in setup mode). We only need id + is_demo, which don't change on background refetch.
|
||||
const meQuery = useQuery({ queryKey: qk.me(), queryFn: api.me, enabled: false });
|
||||
|
||||
const setFilters = useCallback((next: FeedFilters) => {
|
||||
setFiltersState(next);
|
||||
// Persist under THIS tab's active account so filters don't bleed between accounts.
|
||||
@@ -135,25 +136,12 @@ export function FeedFiltersProvider({ children }: { children: ReactNode }) {
|
||||
const { page } = useNavigation();
|
||||
useUrlMirror(filterParamUpdates(page === "feed" ? filters : null));
|
||||
|
||||
// Load THIS account's own filters when the account first resolves or changes (login / switch /
|
||||
// add). Filters are per-account localStorage state, so another account's last view (incl. its
|
||||
// default saved view) must never carry over. A share link's filters (captured at mount) win and
|
||||
// are persisted to the account instead. Runs on id change only, so a 60s background refetch of
|
||||
// the same account never clobbers the filters you're editing.
|
||||
// A share link's filters (captured at mount) win over the account's stored view and are persisted
|
||||
// to it once, so the view the link opened also survives a later plain reload.
|
||||
useEffect(() => {
|
||||
const id = meQuery.data?.id;
|
||||
if (id == null) return;
|
||||
if (initialHadUrlFilters) {
|
||||
const key = accountKey(FILTERS_KEY, id);
|
||||
if (key) writeJSON(key, filters);
|
||||
return;
|
||||
}
|
||||
let f = loadAccountFilters(id);
|
||||
// The shared demo account has no subscriptions, so default it to the whole library.
|
||||
if (meQuery.data?.is_demo) f = { ...f, scope: "all" };
|
||||
setFiltersState(f);
|
||||
if (initialHadUrlFilters) setFilters(filters);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [meQuery.data?.id]);
|
||||
}, []);
|
||||
|
||||
const actions = useMemo<FeedFiltersActions>(() => ({ setFilters }), [setFilters]);
|
||||
|
||||
|
||||
@@ -22,8 +22,8 @@ export default function KeyGate({ meId, compact = false }: { meId: number; compa
|
||||
});
|
||||
const configured = keyQ.data?.configured ?? false;
|
||||
// Password accounts must re-verify to reset (guards a hijacked session); Google-only accounts
|
||||
// have no password to check. Reactive passive observer of the App-owned qk.me() query (enabled:
|
||||
// false — App does the fetching), so hasPassword stays correct even if me resolves after mount.
|
||||
// have no password to check. Passive observer of the qk.me() query BootGate fetches (enabled:false),
|
||||
// so hasPassword follows the cache when a refetch changes it.
|
||||
const meQ = useQuery({ queryKey: qk.me(), queryFn: api.me, enabled: false });
|
||||
const hasPassword = meQ.data?.has_password ?? false;
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ import { useTranslation } from "react-i18next";
|
||||
import { urlWithParams, type Page } from "../lib/urlState";
|
||||
import { pageTitleKey } from "../lib/pageMeta";
|
||||
import { setAccountRaw } from "../lib/storage";
|
||||
import { useAccountRehydrate } from "../lib/useAccountRehydrate";
|
||||
import { setNavigator } from "../lib/nav";
|
||||
import {
|
||||
closeOverlaysThenNavigate,
|
||||
@@ -102,27 +101,6 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
|
||||
const channelViewRef = useRef(channelView);
|
||||
channelViewRef.current = channelView;
|
||||
|
||||
// The landing page is per-account (PAGE_KEY), but this provider mounts above <App>, which pins the
|
||||
// tab's account only after /api/me — so on a fresh tab `loadInitialPage` reads an unknown account and
|
||||
// falls back to "feed". Re-read once the account is pinned and correct the CURRENT history entry
|
||||
// (replaceState, not push) so Back isn't given a phantom "feed" step. markDirty (set by setPage)
|
||||
// skips this if the user already navigated in the pre-pin window.
|
||||
const markDirty = useAccountRehydrate(() => {
|
||||
const stored = loadInitialPage();
|
||||
if (stored === pageRef.current) return;
|
||||
setPageState(stored);
|
||||
setAccountRaw(PAGE_KEY, stored); // no-op re-write, keeps storage authoritative
|
||||
// Correct the CURRENT entry (replace, not push) and PRESERVE any markers already on it — a channel
|
||||
// (_chan) or YT search (_yt) opened in the pre-pin window survives on top of the restored page,
|
||||
// rather than being orphaned from history so Back can't close it. Mirror the corrected page to the
|
||||
// address bar too (urlWithParams keeps any ?chan/filter params already there).
|
||||
window.history.replaceState(
|
||||
{ ...(window.history.state || {}), sfPage: stored },
|
||||
"",
|
||||
urlWithParams({ page: stored === "feed" ? null : stored }),
|
||||
);
|
||||
});
|
||||
|
||||
const setPage = useCallback(
|
||||
(next: Page) =>
|
||||
// Never under an open overlay — see the interface doc. The refs are read when the push
|
||||
@@ -131,7 +109,6 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
|
||||
// A channel page overlays the content column, so a nav click must close it even when the
|
||||
// underlying page is unchanged (e.g. "Feed" while a channel opened from the feed).
|
||||
if (next === pageRef.current && !channelViewRef.current) return;
|
||||
markDirty();
|
||||
setChannelView(null); // leave any open channel page when navigating via the rail
|
||||
setPageState(next);
|
||||
setAccountRaw(PAGE_KEY, next);
|
||||
@@ -163,15 +140,12 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
|
||||
);
|
||||
notifyNav();
|
||||
}),
|
||||
[markDirty],
|
||||
[],
|
||||
);
|
||||
|
||||
// A sub-view (channel / YT search) is an OVERLAY, not a page change, so it does NOT markDirty: a
|
||||
// pre-pin account re-hydrate should still restore the stored page underneath — the re-hydrate's
|
||||
// replaceState spreads the _chan/_yt markers, so the overlay survives on top of the restored page.
|
||||
//
|
||||
// Like setPage it never lands under an open overlay: the player's channel link and the palette's
|
||||
// channel rows call it from inside one.
|
||||
// A sub-view (channel / YT search) is an OVERLAY, not a page change. Like setPage it never lands
|
||||
// under an open overlay: the player's channel link and the palette's channel rows call it from
|
||||
// inside one.
|
||||
const openChannel = useCallback((id: string, name?: string) => {
|
||||
closeOverlaysThenNavigate(() => {
|
||||
const url = urlWithParams({ chan: id });
|
||||
@@ -197,7 +171,6 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
|
||||
}, []);
|
||||
|
||||
const enterYtSearch = useCallback((q: string) => {
|
||||
// Overlay, not a page change — see openChannel: no markDirty, the re-hydrate preserves _yt.
|
||||
setYtSearch(q);
|
||||
// Drop any prior _ytScrape marker — the new search's source isn't known yet; Feed re-stamps it
|
||||
// once the results resolve, so a reload only restores a confirmed scrape-sourced search.
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react";
|
||||
import { LS, setAccountRaw } from "../lib/storage";
|
||||
import { useAccountRehydrate } from "../lib/useAccountRehydrate";
|
||||
import { useUrlMirror } from "../lib/useUrlMirror";
|
||||
import { useNavigation } from "./NavigationProvider";
|
||||
import { readSelectedId } from "./playlistsInit";
|
||||
@@ -43,19 +42,11 @@ export function PlaylistsProvider({ children }: { children: ReactNode }) {
|
||||
const [search, setSearchState] = useState("");
|
||||
const [selectedId, setSelectedIdState] = useState<number | null>(readSelectedId);
|
||||
|
||||
// Re-read the selected playlist once the account is pinned after mount (first load on a fresh tab):
|
||||
// this provider mounts above <App>, which pins the account only after /api/me.
|
||||
const markDirty = useAccountRehydrate(() => setSelectedIdState(readSelectedId()));
|
||||
|
||||
const setSearch = useCallback((q: string) => setSearchState(q), []);
|
||||
const setSelectedId = useCallback(
|
||||
(id: number | null) => {
|
||||
markDirty();
|
||||
setSelectedIdState(id);
|
||||
if (id != null) setAccountRaw(LS.playlist, String(id));
|
||||
},
|
||||
[markDirty],
|
||||
);
|
||||
const setSelectedId = useCallback((id: number | null) => {
|
||||
setSelectedIdState(id);
|
||||
if (id != null) setAccountRaw(LS.playlist, String(id));
|
||||
}, []);
|
||||
|
||||
// Mirror the selected playlist to ?pl on the Playlists page so it's bookmarkable; clear it elsewhere
|
||||
// (the localStorage copy still restores it on return). useUrlMirror keeps ?page and the other nav
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from "react";
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { coercePlexFilters, EMPTY_PLEX_FILTERS, type PlexFilters } from "../lib/api";
|
||||
import { parseSortState, type SortState } from "../lib/columnSort";
|
||||
import { parsePlexField, type PlexSearchField } from "../lib/plexSearch";
|
||||
@@ -10,7 +18,6 @@ import {
|
||||
type PlexUrlState,
|
||||
} from "../lib/plexUrlState";
|
||||
import { getAccountRaw, LS, setAccountRaw } from "../lib/storage";
|
||||
import { useAccountRehydrate } from "../lib/useAccountRehydrate";
|
||||
import { useUrlMirror } from "../lib/useUrlMirror";
|
||||
import { useNavigation } from "./NavigationProvider";
|
||||
|
||||
@@ -20,10 +27,8 @@ import { useNavigation } from "./NavigationProvider";
|
||||
// instead of prop-drilling through App. Mirrors FeedFiltersProvider (split State + Actions contexts,
|
||||
// stable useCallback setters, one-line hooks; composed in main.tsx around <App/>).
|
||||
//
|
||||
// scope / show / sort / filters / q are per-account persisted (localStorage). init-from-storage seeds
|
||||
// them, and useAccountRehydrate re-reads once the tab's account is pinned — this provider mounts above
|
||||
// <App>, which pins it only after /api/me, so a fresh tab would otherwise show defaults until a reload
|
||||
// (an account SWITCH does full-reload, but the FIRST load does not). `playlistOpen` is an ephemeral
|
||||
// scope / show / sort / filters / q are per-account persisted (localStorage) and seeded from it at mount
|
||||
// (BootGate pins the tab's account first; an account switch reloads). `playlistOpen` is an ephemeral
|
||||
// hand-off (the rail sets it, PlexBrowse consumes it into a history subview then clears it). The Plex
|
||||
// search term is deliberately its OWN state, NOT the feed's `filters.q`, so a Plex search never leaks
|
||||
// into (and is never greeted by a stale value from) the feed.
|
||||
@@ -95,7 +100,7 @@ export function usePlexActions(): PlexActions {
|
||||
return useContext(ActionsContext);
|
||||
}
|
||||
|
||||
// The per-account init readers, shared by the initial useState seed AND the account-pin re-hydrate.
|
||||
// The per-account init readers, shared by the useState seeds and the shared-link seed's base.
|
||||
function readPlexScope(): string {
|
||||
const v = getAccountRaw(LS.plexLibrary) ?? "both";
|
||||
return ["movie", "show", "both"].includes(v) ? v : "both";
|
||||
@@ -144,45 +149,31 @@ function readPlexFilters(): PlexFilters {
|
||||
return EMPTY_PLEX_FILTERS;
|
||||
}
|
||||
}
|
||||
// A shared-link seed = the URL-merged state PLUS which dimensions the URL actually carried. `present`
|
||||
// matters because the base below is read at MOUNT, before the account is pinned (getAccountRaw returns
|
||||
// null then), so the base for an OMITTED dimension is a hard default, NOT this account's stored value.
|
||||
// The provider must therefore persist/keep only the PRESENT dimensions on account-pin and re-read the
|
||||
// account's real stored value for the absent ones — otherwise a partial link silently resets them.
|
||||
type PlexSeedPresent = { scope: boolean; sort: boolean; show: boolean; filters: boolean };
|
||||
type PlexUrlSeed = { state: PlexUrlState; present: PlexSeedPresent };
|
||||
function readPlexUrlSeed(): PlexUrlSeed | null {
|
||||
// The base is this account's stored view (BootGate pins the account before this provider mounts), so a
|
||||
// PARTIAL link — one carrying only the scope, say — keeps the stored sort, show and filters for the rest.
|
||||
function readPlexUrlSeed(): PlexUrlState | null {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (!hasPlexParams(params)) return null;
|
||||
const state = plexParamsToState(params, {
|
||||
return plexParamsToState(params, {
|
||||
scope: readPlexScope(),
|
||||
sort: readPlexSort(),
|
||||
show: readPlexShow(),
|
||||
filters: readPlexFilters(),
|
||||
});
|
||||
return {
|
||||
state,
|
||||
present: {
|
||||
scope: params.has("pscope"),
|
||||
sort: params.has("psort"),
|
||||
show: params.has("pshow"),
|
||||
filters: params.has("pf"),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function PlexProvider({ children }: { children: ReactNode }) {
|
||||
// Captured once: the shared-link content state (or null). Seeds the slices below and, on account pin,
|
||||
// is persisted to the account instead of being clobbered by the stored view (see the rehydrate).
|
||||
// Captured once: the shared-link content state (or null). Seeds the slices below and is persisted to
|
||||
// the account (the effect further down), so the shared view also survives a later plain reload.
|
||||
const [urlSeed] = useState(readPlexUrlSeed);
|
||||
// The former per-library picker is now a cross-library SCOPE: movie | show | both (unified library).
|
||||
// (Reuses the old LS.plexLibrary key; an old stored library-id value falls back to "both".)
|
||||
const [scope, setScopeState] = useState<string>(() => urlSeed?.state.scope ?? readPlexScope());
|
||||
const [show, setShowState] = useState<string>(() => urlSeed?.state.show ?? readPlexShow());
|
||||
const [sort, setSortState] = useState<SortState>(() => urlSeed?.state.sort ?? readPlexSort());
|
||||
const [scope, setScopeState] = useState<string>(() => urlSeed?.scope ?? readPlexScope());
|
||||
const [show, setShowState] = useState<string>(() => urlSeed?.show ?? readPlexShow());
|
||||
const [sort, setSortState] = useState<SortState>(() => urlSeed?.sort ?? readPlexSort());
|
||||
// The expanded Plex filters live as one JSON blob (the string-only account store serializes it).
|
||||
const [filtersRaw, setFiltersRaw] = useState<string>(() =>
|
||||
urlSeed ? JSON.stringify(urlSeed.state.filters) : readPlexFiltersRaw(),
|
||||
urlSeed ? JSON.stringify(urlSeed.filters) : readPlexFiltersRaw(),
|
||||
);
|
||||
const filters = useMemo<PlexFilters>(() => {
|
||||
try {
|
||||
@@ -203,87 +194,42 @@ export function PlexProvider({ children }: { children: ReactNode }) {
|
||||
// PlexBrowse consumes it into an info/show history subview then clears it.
|
||||
const [jumpTo, setJumpTo] = useState<PlexJumpTarget | null>(null);
|
||||
|
||||
// Re-read every per-account slice once the account is pinned after mount (first load on a fresh tab).
|
||||
// A shared-link seed is the exception: instead of reloading the account's stored view, PERSIST the URL
|
||||
// state to this account (so the shared view wins and survives a later plain reload), and adopt only the
|
||||
// non-shared slices (q/field) from storage. Mirrors FeedFiltersProvider's initialHadUrlFilters branch.
|
||||
const markDirty = useAccountRehydrate(() => {
|
||||
if (urlSeed) {
|
||||
// Per dimension: a dimension the URL carried (present) is the shared view — adopt it and persist
|
||||
// it to this now-pinned account (so it wins and survives a later plain reload). A dimension the
|
||||
// URL OMITTED was seeded from a mount-time default (no account yet), so do NOT persist that
|
||||
// default over the account's real stored value — re-read the stored value instead, exactly like a
|
||||
// normal load. This is the fix for a partial shared link silently resetting the omitted slices.
|
||||
const { state, present } = urlSeed;
|
||||
if (present.scope) setAccountRaw(LS.plexLibrary, state.scope);
|
||||
else setScopeState(readPlexScope());
|
||||
if (present.show) setAccountRaw(LS.plexShow, state.show);
|
||||
else setShowState(readPlexShow());
|
||||
if (present.sort) setAccountRaw(LS.plexSort, JSON.stringify(state.sort));
|
||||
else setSortState(readPlexSort());
|
||||
if (present.filters) setAccountRaw(LS.plexFilters, JSON.stringify(state.filters));
|
||||
else setFiltersRaw(readPlexFiltersRaw());
|
||||
setQState(readPlexQ());
|
||||
setFieldState(readPlexField());
|
||||
return;
|
||||
}
|
||||
setScopeState(readPlexScope());
|
||||
setShowState(readPlexShow());
|
||||
setSortState(readPlexSort());
|
||||
setFiltersRaw(readPlexFiltersRaw());
|
||||
setQState(readPlexQ());
|
||||
setFieldState(readPlexField());
|
||||
});
|
||||
// Persist a shared link's view to the account once, so it wins over the stored view and survives a
|
||||
// later plain reload. The seed's base was the stored view, so a dimension the link omitted is written
|
||||
// back unchanged. Mirrors FeedFiltersProvider's initialHadUrlFilters branch.
|
||||
useEffect(() => {
|
||||
if (!urlSeed) return;
|
||||
setAccountRaw(LS.plexLibrary, urlSeed.scope);
|
||||
setAccountRaw(LS.plexShow, urlSeed.show);
|
||||
setAccountRaw(LS.plexSort, JSON.stringify(urlSeed.sort));
|
||||
setAccountRaw(LS.plexFilters, JSON.stringify(urlSeed.filters));
|
||||
}, [urlSeed]);
|
||||
|
||||
const setScope = useCallback(
|
||||
(v: string) => {
|
||||
markDirty();
|
||||
setScopeState(v);
|
||||
setAccountRaw(LS.plexLibrary, v);
|
||||
},
|
||||
[markDirty],
|
||||
);
|
||||
const setShow = useCallback(
|
||||
(v: string) => {
|
||||
markDirty();
|
||||
setShowState(v);
|
||||
setAccountRaw(LS.plexShow, v);
|
||||
},
|
||||
[markDirty],
|
||||
);
|
||||
const setSort = useCallback(
|
||||
(v: SortState) => {
|
||||
markDirty();
|
||||
setSortState(v);
|
||||
setAccountRaw(LS.plexSort, JSON.stringify(v));
|
||||
},
|
||||
[markDirty],
|
||||
);
|
||||
const setFilters = useCallback(
|
||||
(f: PlexFilters) => {
|
||||
markDirty();
|
||||
const s = JSON.stringify(f);
|
||||
setFiltersRaw(s);
|
||||
setAccountRaw(LS.plexFilters, s);
|
||||
},
|
||||
[markDirty],
|
||||
);
|
||||
const setQ = useCallback(
|
||||
(v: string) => {
|
||||
markDirty();
|
||||
setQState(v);
|
||||
setAccountRaw(LS.plexQ, v);
|
||||
},
|
||||
[markDirty],
|
||||
);
|
||||
const setField = useCallback(
|
||||
(v: PlexSearchField) => {
|
||||
markDirty();
|
||||
setFieldState(v);
|
||||
setAccountRaw(LS.plexField, v);
|
||||
},
|
||||
[markDirty],
|
||||
);
|
||||
const setScope = useCallback((v: string) => {
|
||||
setScopeState(v);
|
||||
setAccountRaw(LS.plexLibrary, v);
|
||||
}, []);
|
||||
const setShow = useCallback((v: string) => {
|
||||
setShowState(v);
|
||||
setAccountRaw(LS.plexShow, v);
|
||||
}, []);
|
||||
const setSort = useCallback((v: SortState) => {
|
||||
setSortState(v);
|
||||
setAccountRaw(LS.plexSort, JSON.stringify(v));
|
||||
}, []);
|
||||
const setFilters = useCallback((f: PlexFilters) => {
|
||||
const s = JSON.stringify(f);
|
||||
setFiltersRaw(s);
|
||||
setAccountRaw(LS.plexFilters, s);
|
||||
}, []);
|
||||
const setQ = useCallback((v: string) => {
|
||||
setQState(v);
|
||||
setAccountRaw(LS.plexQ, v);
|
||||
}, []);
|
||||
const setField = useCallback((v: PlexSearchField) => {
|
||||
setFieldState(v);
|
||||
setAccountRaw(LS.plexField, v);
|
||||
}, []);
|
||||
|
||||
const state = useMemo<PlexState>(
|
||||
() => ({ scope, show, sort, filters, q, field, playlistOpen, jumpTo }),
|
||||
|
||||
@@ -3,14 +3,15 @@ import {
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { qk } from "../lib/queryKeys";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { api } from "../lib/api";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { api, type Me } from "../lib/api";
|
||||
import {
|
||||
applyTheme,
|
||||
DEFAULT_THEME,
|
||||
@@ -53,35 +54,47 @@ export function usePrefs(): PrefsController {
|
||||
}
|
||||
|
||||
export function PrefsProvider({ children }: { children: ReactNode }) {
|
||||
const [theme, setThemeState] = useState<ThemePrefs>(() => loadLocalTheme());
|
||||
const [perf, setPerf] = useState(() => getAccountRaw(PERF_KEY) === "1");
|
||||
const [hints, setHints] = useState(() => hintsEnabled());
|
||||
const [notif, setNotif] = useState<NotifSettings>(() => getNotifSettings());
|
||||
// The last server-known prefs. Written on adopt + after each save so the auto-save effect can
|
||||
// compare against it and avoid echoing a server-adopted value straight back. A ref (drives no UI).
|
||||
const baselineRef = useRef<EditablePrefs>({
|
||||
theme: loadLocalTheme(),
|
||||
performanceMode: getAccountRaw(PERF_KEY) === "1",
|
||||
hints: hintsEnabled(),
|
||||
notifications: getNotifSettings(),
|
||||
const qc = useQueryClient();
|
||||
// The account's prefs, seeded straight from the `me` cache — BootGate mounts this only once /api/me
|
||||
// has answered, so a theme changed on another device is right on the first paint instead of
|
||||
// switching after it. This browser's copy fills any key the server has never stored.
|
||||
const [seed] = useState<EditablePrefs>(() => {
|
||||
const prefs = qc.getQueryData<Me | null>(qk.me())?.preferences;
|
||||
return {
|
||||
theme: prefs?.theme ? { ...DEFAULT_THEME, ...prefs.theme } : loadLocalTheme(),
|
||||
performanceMode:
|
||||
typeof prefs?.performanceMode === "boolean"
|
||||
? prefs.performanceMode
|
||||
: getAccountRaw(PERF_KEY) === "1",
|
||||
hints: typeof prefs?.hints === "boolean" ? prefs.hints : hintsEnabled(),
|
||||
notifications: prefs?.notifications
|
||||
? { ...getNotifSettings(), ...prefs.notifications }
|
||||
: getNotifSettings(),
|
||||
};
|
||||
});
|
||||
const [theme, setThemeState] = useState<ThemePrefs>(seed.theme);
|
||||
const [perf, setPerf] = useState(seed.performanceMode);
|
||||
const [hints, setHints] = useState(seed.hints);
|
||||
const [notif, setNotif] = useState<NotifSettings>(seed.notifications);
|
||||
// The last server-known prefs: the seed, then each successful save. The auto-save effect compares
|
||||
// against it, so the seed itself is never echoed back as a save. A ref (drives no UI).
|
||||
const baselineRef = useRef<EditablePrefs>(seed);
|
||||
const [saveState, setSaveState] = useState<PrefsController["saveState"]>("idle");
|
||||
const saveMsgTimer = useRef<number | undefined>(undefined);
|
||||
const saveTimer = useRef<number | undefined>(undefined);
|
||||
// Passive observer of the account App fetches (enabled:false → reads cache, re-renders on update).
|
||||
const { data: me } = useQuery({ queryKey: qk.me(), queryFn: api.me, enabled: false });
|
||||
|
||||
// Live-apply the prefs locally for instant preview (their localStorage mirrors update via the
|
||||
// stores too); persistence to the server is the auto-save effect below.
|
||||
useEffect(() => applyTheme(theme), [theme]);
|
||||
useEffect(() => {
|
||||
// stores too); persistence to the server is the auto-save effect below. The look is applied in
|
||||
// LAYOUT effects, before the browser paints, so the app's first frame is already in the account's
|
||||
// theme rather than in the baseline one main.tsx sets for the boot screen.
|
||||
useLayoutEffect(() => applyTheme(theme), [theme]);
|
||||
useLayoutEffect(() => {
|
||||
document.documentElement.dataset.perf = perf ? "1" : "";
|
||||
setAccountRaw(PERF_KEY, perf ? "1" : "0");
|
||||
}, [perf]);
|
||||
// The per-scheme background image (the "glass over image" look) is on when the user hasn't opted
|
||||
// out and we're not in perf mode. Drives `html[data-backdrop]` (see index.css), which paints the
|
||||
// theme-appropriate image on <body> and switches the glass to translucent.
|
||||
useEffect(() => {
|
||||
useLayoutEffect(() => {
|
||||
const on = theme.bgImage && !perf;
|
||||
document.documentElement.dataset.backdrop = on ? "on" : "off";
|
||||
}, [theme.bgImage, perf]);
|
||||
@@ -132,31 +145,6 @@ export function PrefsProvider({ children }: { children: ReactNode }) {
|
||||
[],
|
||||
);
|
||||
|
||||
// On login / account switch, adopt the server-stored prefs into the live states AND the auto-save
|
||||
// baseline (so adopting them doesn't echo a save back).
|
||||
useEffect(() => {
|
||||
const prefs = me?.preferences;
|
||||
if (!prefs) return;
|
||||
const adopted: EditablePrefs = {
|
||||
theme: prefs.theme ? { ...DEFAULT_THEME, ...prefs.theme } : loadLocalTheme(),
|
||||
performanceMode:
|
||||
typeof prefs.performanceMode === "boolean"
|
||||
? prefs.performanceMode
|
||||
: getAccountRaw(PERF_KEY) === "1",
|
||||
hints: typeof prefs.hints === "boolean" ? prefs.hints : hintsEnabled(),
|
||||
notifications: prefs.notifications
|
||||
? { ...getNotifSettings(), ...prefs.notifications }
|
||||
: getNotifSettings(),
|
||||
};
|
||||
setThemeState(adopted.theme);
|
||||
saveLocalTheme(adopted.theme);
|
||||
setPerf(adopted.performanceMode);
|
||||
setHints(adopted.hints);
|
||||
setNotif(adopted.notifications);
|
||||
baselineRef.current = adopted;
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [me?.id]);
|
||||
|
||||
// Theme applies live (and caches to localStorage); the auto-save effect persists it to the server.
|
||||
const setTheme = useCallback((next: ThemePrefs) => {
|
||||
setThemeState(next);
|
||||
|
||||
@@ -43,7 +43,7 @@ vi.mock("./PlexProvider", () => ({
|
||||
vi.mock("./ConfirmProvider", () => ({ useConfirm: () => async () => true }));
|
||||
|
||||
import { SavedViewsProvider, useSavedViews } from "./SavedViewsProvider";
|
||||
import { api, setActiveAccount, type SavedView } from "../lib/api";
|
||||
import { api, type SavedView } from "../lib/api";
|
||||
import { LS, accountKey } from "../lib/storage";
|
||||
import { ACTIVE_ACCOUNT_KEY } from "../lib/activeAccount";
|
||||
import { qk } from "../lib/queryKeys";
|
||||
@@ -109,21 +109,6 @@ describe("SavedViewsProvider — default-view seeding on first resolve", () => {
|
||||
expect(h.setFeedFilters.mock.calls[0]![0]).toMatchObject({ scope: "all", show: "watched" });
|
||||
});
|
||||
|
||||
it("feed: on a fresh tab the query resolves before the account pins — defers, then seeds on the pin", async () => {
|
||||
// The provider mounts above <App>, which pins the tab-account only after /api/me; the ungated
|
||||
// views query resolves first. Seeding must WAIT for the account (not seed nothing and burn its
|
||||
// one-shot — the pre-fix regression that left a fresh tab on DEFAULT_FILTERS until a reload).
|
||||
sessionStorage.removeItem(ACTIVE_ACCOUNT_KEY);
|
||||
await mountResolved([
|
||||
view({ id: 2, is_default: true, filters: { scope: "all", show: "watched" } }),
|
||||
]);
|
||||
expect(h.setFeedFilters).not.toHaveBeenCalled();
|
||||
// App pins the account; the reactive id re-fires the effect and the deferred seed lands.
|
||||
act(() => setActiveAccount(ID));
|
||||
await waitFor(() => expect(h.setFeedFilters).toHaveBeenCalledTimes(1));
|
||||
expect(h.setFeedFilters.mock.calls[0]![0]).toMatchObject({ scope: "all", show: "watched" });
|
||||
});
|
||||
|
||||
it("feed: does NOT seed when the account already has stored filters", async () => {
|
||||
localStorage.setItem(accountKey(LS.filters, ID)!, JSON.stringify({ scope: "my" }));
|
||||
await mountResolved([view({ id: 2, is_default: true, filters: { scope: "all" } })]);
|
||||
|
||||
@@ -25,7 +25,6 @@ import { filtersToParams, hasFilterParams } from "../lib/urlState";
|
||||
import { pickDefaultToSeed, preferSticky } from "../lib/savedViews";
|
||||
import { notifyActionError } from "../lib/actionErrors";
|
||||
import { accountKey, LS } from "../lib/storage";
|
||||
import { useActiveAccountId } from "../lib/activeAccount";
|
||||
import { useConfirm } from "./ConfirmProvider";
|
||||
import { useNavigation } from "./NavigationProvider";
|
||||
import { useFeedFilters, useFeedFiltersActions } from "./FeedFiltersProvider";
|
||||
@@ -179,19 +178,13 @@ export function SavedViewsProvider({ children }: { children: ReactNode }) {
|
||||
// semantics document. This replaced the feed-only localStorage mirror that raced FeedFiltersProvider's
|
||||
// login effect (on a fresh browser the feed could seed DEFAULT_FILTERS and never re-apply until a
|
||||
// reload) — and it gives Plex the default it previously never applied at all. Per-source guard so a
|
||||
// 60s background refetch never re-seeds over the filters you're editing.
|
||||
//
|
||||
// WAIT FOR THE ACCOUNT PIN. This provider mounts above <App>, which pins the tab-account only after
|
||||
// /api/me — but viewsQuery is ungated, so on a fresh tab it resolves FIRST, while the account is null.
|
||||
// canSeedDefault() reads the per-account stored-filters key, which is indeterminate (→ "assume stored")
|
||||
// with no account, so evaluating it too early would decline to seed AND burn the one-shot guard, never
|
||||
// re-running once the account pins. Gating on the reactive account id makes the effect re-fire on the
|
||||
// pin (useActiveAccountId subscribes), and defers consuming the guard until canSeedDefault is real.
|
||||
const accountId = useActiveAccountId();
|
||||
// 60s background refetch never re-seeds over the filters you're editing. canSeedDefault() reads the
|
||||
// per-account stored-filters key, which is always readable here: BootGate pins the tab's account
|
||||
// before this provider mounts.
|
||||
const seededRef = useRef<Set<ViewSource>>(new Set());
|
||||
useEffect(() => {
|
||||
const data = viewsQuery.data;
|
||||
if (!data || accountId == null || seededRef.current.has(source)) return;
|
||||
if (!data || seededRef.current.has(source)) return;
|
||||
seededRef.current.add(source);
|
||||
const def = pickDefaultToSeed(data, cfg.canSeedDefault());
|
||||
if (!def) return;
|
||||
@@ -200,7 +193,7 @@ export function SavedViewsProvider({ children }: { children: ReactNode }) {
|
||||
// cfg is read fresh on this resolve and the per-source guard makes the body run once, so cfg
|
||||
// (which re-memoizes on every filter edit) is deliberately kept out of the deps.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [viewsQuery.data, source, accountId]);
|
||||
}, [viewsQuery.data, source]);
|
||||
|
||||
const currentKey = cfg.keyOf(cfg.filters);
|
||||
const activeView = useMemo(
|
||||
|
||||
@@ -131,10 +131,9 @@ function Appearance({ prefs }: { prefs: PrefsController }) {
|
||||
// Controlled by App's prefs draft: each change applies locally for preview but is only
|
||||
// persisted on an explicit Save (handled by the panel's Save/Discard bar).
|
||||
const { theme, setTheme, perf, setPerf, hints, setHints } = prefs;
|
||||
// The landing page (E24). NOT a server preference like the rest of this tab: `loadInitialPage`
|
||||
// has to answer before /api/me lands, so the value must be readable synchronously from
|
||||
// localStorage — a landing module decided after the first paint would be a visible jump. The two
|
||||
// stored values come from navigationInit, which is what reads them back at boot.
|
||||
// The landing page (E24). Per-account localStorage, not a server preference like the rest of this
|
||||
// tab: `loadInitialPage` reads it synchronously in NavigationProvider's initializer. The two stored
|
||||
// values come from navigationInit, which is what reads them back at boot.
|
||||
const [startOnHome, setStartOnHome] = useAccountPersistedState(LS.startOnHome, START_ON_HOME.on);
|
||||
|
||||
return (
|
||||
|
||||
@@ -22,8 +22,8 @@ const OnboardingWizard = lazy(() => import("./OnboardingWizard"));
|
||||
//
|
||||
// The wizard auto-opens on first login for accounts that still need to connect YouTube (derived from
|
||||
// granted scopes + storage flags, so it's stable across the OAuth round-trip) and is reopenable from
|
||||
// Settings / the notify "reconnect" action. It reads `me` as a passive qk.me() observer (App owns the
|
||||
// fetching query), so it re-runs the auto-open check when the account resolves or its grants change.
|
||||
// Settings / the notify "reconnect" action. It reads `me` as a passive qk.me() observer (BootGate owns
|
||||
// the fetching query), so it re-runs the auto-open check when the account's grants change.
|
||||
|
||||
interface WizardActions {
|
||||
openWizard: () => void;
|
||||
@@ -43,7 +43,7 @@ export function useWizard(): WizardActions {
|
||||
|
||||
export function WizardProvider({ children }: { children: ReactNode }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
// Passive observer of the account App fetches (enabled:false → reads cache, re-renders on update).
|
||||
// Passive observer of the account BootGate fetches (enabled:false → reads cache, re-renders on update).
|
||||
const { data: me } = useQuery({ queryKey: qk.me(), queryFn: api.me, enabled: false });
|
||||
|
||||
const openWizard = useCallback(() => setOpen(true), []);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { lazy, type ComponentType } from "react";
|
||||
import type { ComponentType } from "react";
|
||||
import { lazyWithPreload, type PreloadableComponent } from "../lib/lazyWithPreload";
|
||||
import type { Page } from "../lib/urlState";
|
||||
import type { PanelId, PanelLayout } from "../lib/panelLayout";
|
||||
import { useMe } from "../lib/useMe";
|
||||
@@ -21,22 +22,24 @@ import { useSavedViews } from "./SavedViewsProvider";
|
||||
// its own isolated scope to <Feed> directly — see the scope note in FeedFiltersProvider).
|
||||
|
||||
// Route-level code splitting: each page is its own lazy chunk (admin-only pages never reach
|
||||
// non-admins; the logged-out landing pulls only the shell). Rendered inside App's <Suspense>.
|
||||
const Home = lazy(() => import("./Home"));
|
||||
const Feed = lazy(() => import("./Feed"));
|
||||
const Channels = lazy(() => import("./Channels"));
|
||||
const Playlists = lazy(() => import("./Playlists"));
|
||||
const PlexBrowse = lazy(() => import("./PlexBrowse"));
|
||||
const PlexSidebar = lazy(() => import("./PlexSidebar"));
|
||||
const NotificationsPanel = lazy(() => import("./NotificationsPanel"));
|
||||
const Messages = lazy(() => import("./Messages"));
|
||||
const DownloadCenter = lazy(() => import("./DownloadCenter"));
|
||||
const Stats = lazy(() => import("./Stats"));
|
||||
const Scheduler = lazy(() => import("./Scheduler"));
|
||||
const ConfigPanel = lazy(() => import("./ConfigPanel"));
|
||||
const AdminUsers = lazy(() => import("./AdminUsers"));
|
||||
const AuditLog = lazy(() => import("./AuditLog"));
|
||||
const SettingsPanel = lazy(() => import("./SettingsPanel"));
|
||||
// non-admins; the logged-out landing pulls only the shell). Rendered inside App's <Suspense>. Each
|
||||
// one is preloadable: App fetches the chunks of every page the account can reach once the first page
|
||||
// is on screen (preloadPages below), so switching modules never shows the chunk fallback.
|
||||
const Home = lazyWithPreload(() => import("./Home"));
|
||||
const Feed = lazyWithPreload(() => import("./Feed"));
|
||||
const Channels = lazyWithPreload(() => import("./Channels"));
|
||||
const Playlists = lazyWithPreload(() => import("./Playlists"));
|
||||
const PlexBrowse = lazyWithPreload(() => import("./PlexBrowse"));
|
||||
const PlexSidebar = lazyWithPreload(() => import("./PlexSidebar"));
|
||||
const NotificationsPanel = lazyWithPreload(() => import("./NotificationsPanel"));
|
||||
const Messages = lazyWithPreload(() => import("./Messages"));
|
||||
const DownloadCenter = lazyWithPreload(() => import("./DownloadCenter"));
|
||||
const Stats = lazyWithPreload(() => import("./Stats"));
|
||||
const Scheduler = lazyWithPreload(() => import("./Scheduler"));
|
||||
const ConfigPanel = lazyWithPreload(() => import("./ConfigPanel"));
|
||||
const AdminUsers = lazyWithPreload(() => import("./AdminUsers"));
|
||||
const AuditLog = lazyWithPreload(() => import("./AuditLog"));
|
||||
const SettingsPanel = lazyWithPreload(() => import("./SettingsPanel"));
|
||||
|
||||
// The GLOBAL feed page: wires <Feed> to the app-wide feed filters / view / live-search. (The channel
|
||||
// page renders <Feed> itself with its own channel-scoped filters, so those two never share state.)
|
||||
@@ -80,8 +83,9 @@ function MessagesPage() {
|
||||
}
|
||||
|
||||
export type PageDef = {
|
||||
// Prop-free by construction: reads `me` + module state from hooks/providers.
|
||||
Component: ComponentType;
|
||||
// Prop-free by construction: reads `me` + module state from hooks/providers. Preloadable by type, so
|
||||
// a new page cannot silently opt out of preloadPages.
|
||||
Component: PreloadableComponent<object>;
|
||||
// Channels + Audit render a table with a sticky header at the scroller top; the shell's top fade
|
||||
// would sit on it and flip on with the first scroll, so they turn it off. Defaults to on.
|
||||
fadeTop?: boolean;
|
||||
@@ -94,12 +98,13 @@ export type PageDef = {
|
||||
// page id → the component App renders in the content column (+ its shell chrome config).
|
||||
export const PAGE_CONTENT: Record<Page, PageDef> = {
|
||||
home: { Component: Home, maxWidth: "80rem" },
|
||||
feed: { Component: FeedPage },
|
||||
// The two wrappers preload the lazy chunk they render.
|
||||
feed: { Component: Object.assign(FeedPage, { preload: Feed.preload }) },
|
||||
channels: { Component: Channels, fadeTop: false, maxWidth: "96rem" },
|
||||
playlists: { Component: Playlists, fadeTop: false, maxWidth: "64rem" },
|
||||
plex: { Component: PlexBrowse, maxWidth: "1600px" },
|
||||
notifications: { Component: NotificationsPanel, maxWidth: "48rem" },
|
||||
messages: { Component: MessagesPage },
|
||||
messages: { Component: Object.assign(MessagesPage, { preload: Messages.preload }) },
|
||||
downloads: { Component: DownloadCenter, maxWidth: "56rem" },
|
||||
stats: { Component: Stats },
|
||||
scheduler: { Component: Scheduler },
|
||||
@@ -134,3 +139,13 @@ export const PAGE_RAIL: Partial<Record<Page, RailDef>> = {
|
||||
plex: { Rail: PlexSidebar, panelId: "plex", collapse: "filter" },
|
||||
playlists: { Rail: PlaylistsRail, panelId: "playlists", collapse: "playlists" },
|
||||
};
|
||||
|
||||
/** Fetch the code of these pages and of their side rails now, ahead of their first visit. Errors are
|
||||
* swallowed: a chunk that fails to preload is simply fetched (and its failure surfaced) on visit. */
|
||||
export function preloadPages(pages: Page[]): void {
|
||||
for (const p of pages) {
|
||||
PAGE_CONTENT[p].Component.preload().catch(() => {});
|
||||
const rail = PAGE_RAIL[p]?.Rail as Partial<PreloadableComponent<RailProps>> | undefined;
|
||||
rail?.preload?.().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,11 +6,17 @@ import { Button } from "./Button";
|
||||
// Centered loading state: a spinning accent ring + an optional label. The single shared loading
|
||||
// visual for a page/section's first load, so all of them read the same (and can be swapped for
|
||||
// skeletons later in one place). `role=status`/`aria-live` announces it to screen readers.
|
||||
//
|
||||
const LOADING_REVEAL_DELAY = "300ms";
|
||||
// It fades in only after LOADING_REVEAL_DELAY: most first loads here answer in tens of milliseconds,
|
||||
// and a spinner shown for two frames before the content replaces it reads as a flicker, not as
|
||||
// feedback. A load that really takes a while still gets the spinner, a third of a second in.
|
||||
export function LoadingState({ label, className = "" }: { label?: ReactNode; className?: string }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div
|
||||
className={`flex flex-col items-center gap-3 py-10 text-sm text-muted ${className}`}
|
||||
style={{ animation: `fadeIn 0.2s ease ${LOADING_REVEAL_DELAY} both` }}
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
>
|
||||
|
||||
Reference in New Issue
Block a user