feat(plex): port the saved-views (personal views) UI to Plex (frontend)
Plex now has the same personal-views system as the feed — the rail header icon opens the quick-pick popover, the rail title opens the manager modal (list / create / rename / delete / reorder / set-default / apply), and the active view leads the chip row with a "modified" dot. One SavedViewsProvider serves both modules: it switches `source` (feed ⟷ plex) by the active page (both filter providers are global, so it reads whichever the page owns) and runs the same logic on per-source wiring — the live filters, apply, a stable signature (feed filtersToParams / plex plexFiltersSignature), coercion (asFilters / coercePlexFilters), and what to strip on save. Moved below PlexProvider in the tree so it can read plex state; resets sticky/modal on a source switch. The shared popover/modal/chip are unchanged; the modal describes a plex view's captured filters via a pure buildPlexActiveFilters (extracted from usePlexActiveFilters — no duplication). api.savedViews/createView take a source; `SavedView.filters` is now an opaque blob. New coercePlexFilters/plexFilters- Signature (also dedups PlexProvider's collection migration). Empty-state copy genericised (no longer says "feed"). A Plex view captures the rail filters (not watch-state/sort/scope). Verified end-to-end on localdev: create/apply/preview/default/delete on plex, feed views stay separate + unregressed (402 vitest), no console errors.
This commit is contained in:
@@ -4,9 +4,12 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { qk } from "../lib/queryKeys";
|
||||
import {
|
||||
api,
|
||||
getActiveAccount,
|
||||
coercePlexFilters,
|
||||
coerceTagModes,
|
||||
getActiveAccount,
|
||||
plexFiltersSignature,
|
||||
type FeedFilters,
|
||||
type PlexFilters,
|
||||
type SavedView,
|
||||
} from "../lib/api";
|
||||
import { filtersToParams } from "../lib/urlState";
|
||||
@@ -14,12 +17,17 @@ import { preferSticky } from "../lib/savedViews";
|
||||
import { notifyActionError } from "../lib/actionErrors";
|
||||
import { accountKey, LS, writeJSON } from "../lib/storage";
|
||||
import { useConfirm } from "./ConfirmProvider";
|
||||
import { useNavigation } from "./NavigationProvider";
|
||||
import { useFeedFilters, useFeedFiltersActions } from "./FeedFiltersProvider";
|
||||
import { usePlex, usePlexActions } from "./PlexProvider";
|
||||
|
||||
// A saved view's `filters` is an opaque JSON blob from the DB — the FeedFilters type says nothing about
|
||||
// what an older build wrote there, so coerce the array/shape fields (and migrate the legacy global
|
||||
// tagMode) before the blob reaches app state or a serializer. NOT a migration: a view saved against a
|
||||
// dropped field just loses that filter.
|
||||
// Saved "smart views" now serve TWO modules — the feed and Plex — keyed by `source`. This one provider
|
||||
// switches which module it operates on by the active page (both filter providers are global, so it can
|
||||
// read either), so the shared UI (popover / modal / chip) works on the feed page against feed views and
|
||||
// on the plex page against plex views without a second provider or an App-layout change.
|
||||
|
||||
// A saved view's `filters` is an opaque JSON blob from the DB; coerce it to the module's shape before it
|
||||
// reaches app state or a serializer (an older build's dropped field just falls away — NOT a migration).
|
||||
export const asFilters = (raw: FeedFilters): FeedFilters => ({
|
||||
...raw,
|
||||
tags: raw.tags ?? [],
|
||||
@@ -27,13 +35,27 @@ export const asFilters = (raw: FeedFilters): FeedFilters => ({
|
||||
tagModes: coerceTagModes(raw),
|
||||
});
|
||||
|
||||
// A stable signature of a filter set (only non-default keys, shuffle seed ignored) so a view can be
|
||||
// matched against the live filters regardless of key order or transient fields.
|
||||
const keyOf = (f: FeedFilters) => filtersToParams(asFilters(f)).toString();
|
||||
type ViewSource = "feed" | "plex";
|
||||
|
||||
// Mirror the default view's filters to localStorage so the app can seed them on next load before the
|
||||
// network returns (read by FeedFiltersProvider).
|
||||
function syncDefaultMirror(views: SavedView[]): void {
|
||||
// The per-source wiring the generic logic runs on: the live filters, how to apply a view's, a stable
|
||||
// signature for matching, coercion, and what to strip before saving (the feed's transient shuffle seed).
|
||||
interface ViewConfig {
|
||||
source: ViewSource;
|
||||
filters: Record<string, unknown>;
|
||||
setFilters: (f: Record<string, unknown>) => void;
|
||||
keyOf: (f: Record<string, unknown>) => string;
|
||||
asFilters: (raw: Record<string, unknown>) => Record<string, unknown>;
|
||||
stripForSave: (f: Record<string, unknown>) => Record<string, unknown>;
|
||||
/** Feed only: mirror the default view's filters to localStorage so it seeds before the network returns. */
|
||||
syncDefaultMirror?: (views: SavedView[]) => void;
|
||||
}
|
||||
|
||||
const feedKeyOf = (f: Record<string, unknown>) =>
|
||||
filtersToParams(asFilters(f as unknown as FeedFilters)).toString();
|
||||
const plexKeyOf = (f: Record<string, unknown>) => plexFiltersSignature(coercePlexFilters(f));
|
||||
|
||||
// Mirror the feed default view's filters to localStorage (read by FeedFiltersProvider on load).
|
||||
function syncFeedDefaultMirror(views: SavedView[]): void {
|
||||
const key = accountKey(LS.defaultViewFilters, getActiveAccount());
|
||||
if (!key) return;
|
||||
const def = views.find((v) => v.is_default);
|
||||
@@ -41,26 +63,21 @@ function syncDefaultMirror(views: SavedView[]): void {
|
||||
}
|
||||
|
||||
export interface SavedViewsContext {
|
||||
/** Which module these views belong to — the shared UI branches its filter-describer on it. */
|
||||
source: ViewSource;
|
||||
views: SavedView[];
|
||||
loading: boolean;
|
||||
/** The view whose saved filters EXACTLY match the live filters (null if none) — highlighted as active. */
|
||||
activeViewId: number | null;
|
||||
/** The view to name in the chip: the exact match, else the last-applied ("sticky") one it diverged from. */
|
||||
displayView: SavedView | null;
|
||||
/** True when a sticky view is shown but the live filters no longer match it (the chip's "modified" dot). */
|
||||
isDirty: boolean;
|
||||
modalOpen: boolean;
|
||||
openModal: () => void;
|
||||
closeModal: () => void;
|
||||
/** Apply a view's filters and remember it as the active/sticky one. */
|
||||
apply: (v: SavedView) => void;
|
||||
/** Forget the active/sticky view (the chip disappears) without touching the filters. */
|
||||
clearActive: () => void;
|
||||
/** Save the CURRENT filters as a new view; returns success so a caller can keep its editor open on fail. */
|
||||
create: (name: string) => Promise<boolean>;
|
||||
rename: (id: number, name: string) => Promise<boolean>;
|
||||
toggleDefault: (v: SavedView) => Promise<void>;
|
||||
/** Delete a view after confirming; resolves true only when it was actually deleted (false on cancel/fail). */
|
||||
remove: (v: SavedView) => Promise<boolean>;
|
||||
reorder: (nextIds: number[]) => Promise<void>;
|
||||
}
|
||||
@@ -71,33 +88,72 @@ export function SavedViewsProvider({ children }: { children: ReactNode }) {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const confirm = useConfirm();
|
||||
const filters = useFeedFilters();
|
||||
const { setFilters } = useFeedFiltersActions();
|
||||
const { page } = useNavigation();
|
||||
|
||||
const viewsQuery = useQuery({ queryKey: qk.savedViews(), queryFn: api.savedViews });
|
||||
// Both filter providers are global — read both, then use the one the active page owns.
|
||||
const feedFilters = useFeedFilters();
|
||||
const { setFilters: setFeedFilters } = useFeedFiltersActions();
|
||||
const { filters: plexFilters } = usePlex();
|
||||
const { setFilters: setPlexFilters } = usePlexActions();
|
||||
|
||||
const cfg: ViewConfig = useMemo(() => {
|
||||
if (page === "plex") {
|
||||
return {
|
||||
source: "plex",
|
||||
filters: plexFilters as unknown as Record<string, unknown>,
|
||||
setFilters: (f) => setPlexFilters(f as unknown as PlexFilters),
|
||||
keyOf: plexKeyOf,
|
||||
asFilters: (raw) => coercePlexFilters(raw) as unknown as Record<string, unknown>,
|
||||
stripForSave: (f) => f, // Plex has no transient field to drop
|
||||
};
|
||||
}
|
||||
return {
|
||||
source: "feed",
|
||||
filters: feedFilters as unknown as Record<string, unknown>,
|
||||
setFilters: (f) => setFeedFilters(f as unknown as FeedFilters),
|
||||
keyOf: feedKeyOf,
|
||||
asFilters: (raw) =>
|
||||
asFilters(raw as unknown as FeedFilters) as unknown as Record<string, unknown>,
|
||||
// Strip the transient shuffle seed so a saved "shuffle" view re-rolls fresh on apply.
|
||||
stripForSave: (f) => {
|
||||
const { seed: _seed, ...rest } = f;
|
||||
return rest;
|
||||
},
|
||||
syncDefaultMirror: syncFeedDefaultMirror,
|
||||
};
|
||||
}, [page, feedFilters, plexFilters, setFeedFilters, setPlexFilters]);
|
||||
|
||||
const source = cfg.source;
|
||||
const viewsQuery = useQuery({
|
||||
queryKey: qk.savedViews(source),
|
||||
queryFn: () => api.savedViews(source),
|
||||
});
|
||||
const views = useMemo(() => viewsQuery.data ?? [], [viewsQuery.data]);
|
||||
|
||||
const [stickyId, setStickyId] = useState<number | null>(null);
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
|
||||
// Keep the default-view mirror (read on load) in sync with the server state.
|
||||
// Switching modules (feed ⟷ plex) starts fresh: a feed view can't be the sticky/active one on plex,
|
||||
// and a feed modal shouldn't linger open on plex.
|
||||
useEffect(() => {
|
||||
if (viewsQuery.data) syncDefaultMirror(viewsQuery.data);
|
||||
}, [viewsQuery.data]);
|
||||
setStickyId(null);
|
||||
setModalOpen(false);
|
||||
}, [source]);
|
||||
|
||||
const currentKey = keyOf(filters);
|
||||
// Feed only: keep the default-view mirror (read on load) in sync with the server state.
|
||||
useEffect(() => {
|
||||
if (viewsQuery.data) cfg.syncDefaultMirror?.(viewsQuery.data);
|
||||
}, [viewsQuery.data, cfg]);
|
||||
|
||||
const currentKey = cfg.keyOf(cfg.filters);
|
||||
const activeView = useMemo(
|
||||
// When several views capture identical filters, prefer the one the user explicitly applied
|
||||
// (sticky) so apply(B) isn't silently re-attributed to an earlier duplicate A; else the first.
|
||||
() =>
|
||||
preferSticky(
|
||||
views.filter((v) => keyOf(v.filters) === currentKey),
|
||||
views.filter((v) => cfg.keyOf(v.filters) === currentKey),
|
||||
stickyId,
|
||||
),
|
||||
[views, currentKey, stickyId],
|
||||
[views, currentKey, stickyId, cfg],
|
||||
);
|
||||
// An exact match becomes the sticky selection, so filters that happen to equal a view (deep-link,
|
||||
// manual, or an applied view) name that view in the chip and keep naming it after a later tweak.
|
||||
useEffect(() => {
|
||||
if (activeView) setStickyId(activeView.id);
|
||||
}, [activeView]);
|
||||
@@ -109,7 +165,7 @@ export function SavedViewsProvider({ children }: { children: ReactNode }) {
|
||||
const displayView = activeView ?? stickyView;
|
||||
const isDirty = displayView != null && activeView == null;
|
||||
|
||||
const refresh = () => qc.invalidateQueries({ queryKey: qk.savedViews() });
|
||||
const refresh = () => qc.invalidateQueries({ queryKey: qk.savedViews(source) });
|
||||
async function runViewMutation(fn: () => Promise<unknown>, failMsg: string): Promise<boolean> {
|
||||
try {
|
||||
await fn();
|
||||
@@ -123,6 +179,7 @@ export function SavedViewsProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
|
||||
const value: SavedViewsContext = {
|
||||
source,
|
||||
views,
|
||||
loading: viewsQuery.isLoading,
|
||||
activeViewId: activeView?.id ?? null,
|
||||
@@ -132,16 +189,17 @@ export function SavedViewsProvider({ children }: { children: ReactNode }) {
|
||||
openModal: () => setModalOpen(true),
|
||||
closeModal: () => setModalOpen(false),
|
||||
apply: (v) => {
|
||||
setFilters(asFilters(v.filters));
|
||||
cfg.setFilters(cfg.asFilters(v.filters));
|
||||
setStickyId(v.id);
|
||||
},
|
||||
clearActive: () => setStickyId(null),
|
||||
create: async (name) => {
|
||||
const clean = name.trim();
|
||||
if (!clean) return false;
|
||||
// Strip the transient shuffle seed so a saved "shuffle" view re-rolls fresh on apply.
|
||||
const { seed: _seed, ...rest } = filters;
|
||||
return runViewMutation(() => api.createView(clean, rest), t("views.actionFailed"));
|
||||
return runViewMutation(
|
||||
() => api.createView(clean, cfg.stripForSave(cfg.filters), source),
|
||||
t("views.actionFailed"),
|
||||
);
|
||||
},
|
||||
rename: async (id, name) => {
|
||||
const next = name.trim();
|
||||
@@ -164,10 +222,8 @@ export function SavedViewsProvider({ children }: { children: ReactNode }) {
|
||||
return runViewMutation(() => api.deleteView(v.id), t("views.actionFailed"));
|
||||
},
|
||||
reorder: async (nextIds) => {
|
||||
// Optimistic reorder so the drop sticks visually before the round-trip; the refetch reverts to
|
||||
// the server's truth on failure (with a toast, so it doesn't silently snap back).
|
||||
qc.setQueryData<SavedView[]>(
|
||||
qk.savedViews(),
|
||||
qk.savedViews(source),
|
||||
nextIds.map((id) => views.find((v) => v.id === id)!).filter(Boolean),
|
||||
);
|
||||
await runViewMutation(() => api.reorderViews(nextIds), t("views.reorderFailed"));
|
||||
|
||||
Reference in New Issue
Block a user