fix(filters): a pick that hides More… keeps the focus, counts read alike, Plex facets say they failed

Picking in the year dialog the one year the chips hid took More… away with the dialog, and the
focus fell to <body>: it now goes to the picked year's chip. A count badge is compact in the UI
language everywhere (a chip read "17200" beside its cell's "17.2K"). While the Plex facets load
or fail, the sections they fill say so instead of vanishing as if the library had none.
This commit is contained in:
2026-11-14 19:32:01 +01:00
parent 36f9aefb76
commit be6bd586d7
6 changed files with 198 additions and 83 deletions
+7 -2
View File
@@ -1,15 +1,20 @@
import { useTranslation } from "react-i18next";
import { formatCompact } from "../../lib/format";
// A small count pill shown beside a tab label or filter chip (pending requests, item counts). One // A small count pill shown beside a tab label or filter chip (pending requests, item counts). One
// source for the count-badge token so Tabs and FilterChipGroup can't drift. The `active` variant sits // source for the count-badge token so Tabs and FilterChipGroup can't drift. The `active` variant sits
// on an accent-filled parent (a pressed tab/chip), so it tints against accent-fg; the resting variant // on an accent-filled parent (a pressed tab/chip), so it tints against accent-fg; the resting variant
// carries its own accent tint. Callers guard on `count > 0` — this just renders the pill. // carries its own accent tint. Callers guard on `count > 0` — this just renders the pill. The count is
// compact in the UI language ("17.2K" / "17,2 E"), the same as every other count in the app.
export default function CountBadge({ count, active }: { count: number; active?: boolean }) { export default function CountBadge({ count, active }: { count: number; active?: boolean }) {
const { i18n } = useTranslation();
return ( return (
<span <span
className={`tabular-nums text-2xs leading-none px-1.5 py-0.5 rounded-full ${ className={`tabular-nums text-2xs leading-none px-1.5 py-0.5 rounded-full ${
active ? "bg-accent-fg/20" : "bg-accent/20 text-accent" active ? "bg-accent-fg/20" : "bg-accent/20 text-accent"
}`} }`}
> >
{count} {formatCompact(count, i18n.language)}
</span> </span>
); );
} }
@@ -1,4 +1,5 @@
// @vitest-environment jsdom // @vitest-environment jsdom
import { useState } from "react";
import { describe, it, expect, vi, afterEach } from "vitest"; import { describe, it, expect, vi, afterEach } from "vitest";
import { render, screen, fireEvent, cleanup, within, act } from "@testing-library/react"; import { render, screen, fireEvent, cleanup, within, act } from "@testing-library/react";
@@ -88,6 +89,44 @@ describe("YearPicker", () => {
expect(screen.getByRole("button", { name: "sidebar.year.more" })).toBeTruthy(); expect(screen.getByRole("button", { name: "sidebar.year.more" })).toBeTruthy();
}); });
it("offers no More… once every year with titles is a chip", () => {
const { rerender } = render(<YearPicker years={YEARS.slice(0, 6)} onPick={() => {}} />);
expect(screen.queryByRole("button", { name: "sidebar.year.more" })).toBeNull();
// Seven years, the seventh selected: it is kept as a chip, so nothing is left for the dialog.
rerender(<YearPicker years={YEARS.slice(0, 7)} selected={2013} onPick={() => {}} />);
expect(screen.queryByRole("button", { name: "sidebar.year.more" })).toBeNull();
});
it("picking the one year the chips hid moves the focus to its chip, not to <body>", () => {
// Seven years: the pick keeps 2013 as a chip, so More… leaves with the dialog it opened.
function Picker() {
const [year, setYear] = useState<number | undefined>();
return <YearPicker years={YEARS.slice(0, 7)} selected={year} onPick={setYear} />;
}
vi.useFakeTimers();
try {
render(<Picker />);
const more = screen.getByRole("button", { name: "sidebar.year.more" });
more.focus();
fireEvent.click(more);
const cell = screen.getByRole("dialog").querySelector<HTMLElement>('[data-year="2013"]')!;
cell.focus();
fireEvent.click(cell);
act(() => {
vi.runAllTimers();
});
expect(screen.queryByRole("button", { name: "sidebar.year.more" })).toBeNull();
expect(document.activeElement).toBe(screen.getByRole("button", { pressed: true }));
} finally {
vi.useRealTimers();
}
});
it("a chip's count is compact too, the same as its cell's", () => {
render(<YearPicker years={[{ year: 2025, count: 17243 }]} onPick={() => {}} />);
expect(screen.getByRole("button").textContent).toBe("202517.2K");
});
it("More… is a plain chip: the ellipsis says a dialog follows, no chevron", () => { it("More… is a plain chip: the ellipsis says a dialog follows, no chevron", () => {
render(<YearPicker years={YEARS} onPick={() => {}} />); render(<YearPicker years={YEARS} onPick={() => {}} />);
expect( expect(
+15 -2
View File
@@ -1,4 +1,4 @@
import { useMemo, useState } from "react"; import { useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Chip } from "./Chip"; import { Chip } from "./Chip";
import CountBadge from "./CountBadge"; import CountBadge from "./CountBadge";
@@ -52,10 +52,22 @@ export default function YearPicker({
// only if it is one of them. // only if it is one of them.
const more = years.some((y) => !quick.some((q) => q.year === y.year)); const more = years.some((y) => !quick.some((q) => q.year === y.year));
const chipsRef = useRef<HTMLDivElement>(null);
const toggle = (year: number) => onPick(selected === year ? undefined : year); const toggle = (year: number) => onPick(selected === year ? undefined : year);
const pickAndClose = (year: number) => { const pickAndClose = (year: number) => {
toggle(year); toggle(year);
setOpen(false); setOpen(false);
// A pick that leaves the dialog nothing to show takes More… away with it, and the dialog then has
// nowhere to give the focus back: it fell to <body>, which also folded an unpinned rail. So it
// goes to the picked year's chip (the first chip if the pick cleared it). A timer, not a frame: a
// page the browser is not painting runs no requestAnimationFrame.
window.setTimeout(() => {
const now = document.activeElement;
const row = chipsRef.current;
if ((now && now !== document.body && now.isConnected) || !row) return;
const chip = row.querySelector<HTMLElement>(`[data-year="${year}"]`);
(chip ?? row.querySelector<HTMLElement>("button"))?.focus({ preventScroll: true });
}, 0);
}; };
const cell = (y: YearCount, index: number) => { const cell = (y: YearCount, index: number) => {
@@ -79,7 +91,7 @@ export default function YearPicker({
}; };
return ( return (
<div className="flex flex-wrap gap-1.5"> <div ref={chipsRef} className="flex flex-wrap gap-1.5">
{quick.map((y) => { {quick.map((y) => {
const on = selected === y.year; const on = selected === y.year;
// The chip kept only for the selection leaves with it: from the keyboard, the focus goes to // The chip kept only for the selection leaves with it: from the keyboard, the focus goes to
@@ -89,6 +101,7 @@ export default function YearPicker({
<Chip <Chip
key={y.year} key={y.year}
pressed={on} pressed={on}
data-year={y.year}
onClick={(e) => { onClick={(e) => {
if (leaves && e.currentTarget === document.activeElement) if (leaves && e.currentTarget === document.activeElement)
handOffFocus(e.currentTarget, () => toggle(y.year)); handOffFocus(e.currentTarget, () => toggle(y.year));
+115 -79
View File
@@ -1,4 +1,4 @@
import { useState } from "react"; import { type ReactNode, useState } from "react";
import { qk } from "../../lib/queryKeys"; import { qk } from "../../lib/queryKeys";
import { usePlexCollectionTitles } from "../../lib/usePlexCollectionTitles"; import { usePlexCollectionTitles } from "../../lib/usePlexCollectionTitles";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
@@ -85,6 +85,27 @@ export default function PlexSidebar() {
// just lists them as removable chips. Studios now have their own picker section (below). // just lists them as removable chips. Studios now have their own picker section (below).
const peopleActive = filters.directors.length + filters.actors.length > 0; const peopleActive = filters.directors.length + filters.actors.length > 0;
// A section the facets fill, shown when its facet has values. While the facets are not here, it
// says why it is empty: a first load or a failed one must not read as a library with no genres
// (honest states). The Year section announces it; these only show it, so it is read once.
const facetsState: FacetsState = facets
? "ready"
: facetsQ.isError
? "error"
: facetsQ.isLoading
? "loading"
: "ready";
const facetSection = (
id: string,
title: string,
has: (f: PlexFacets) => boolean,
body: (f: PlexFacets) => ReactNode,
): PanelItem[] => {
if (facets) return has(facets) ? [{ id, title, body: body(facets) }] : [];
if (facetsState === "ready") return [];
return [{ id, title, body: <FacetsStatus state={facetsState} /> }];
};
// Group bodies (no title — the PanelGroup card supplies it). Only available groups are pushed, // Group bodies (no title — the PanelGroup card supplies it). Only available groups are pushed,
// so facet-gated / scope-gated sections drop out cleanly; PanelGroups orders them by the saved // so facet-gated / scope-gated sections drop out cleanly; PanelGroups orders them by the saved
// layout and lets the user reorder / hide / collapse them. // layout and lets the user reorder / hide / collapse them.
@@ -154,33 +175,32 @@ export default function PlexSidebar() {
/> />
), ),
}, },
...(facets && facets.genres.length > 0 ...facetSection(
? [ "genre",
{ t("plex.filter.genre"),
id: "genre", (f) => f.genres.length > 0,
title: t("plex.filter.genre"), (f) => (
body: ( <>
<> <MatchToggle
<MatchToggle picked={filters.genres.length}
picked={filters.genres.length} value={filters.genreMode ?? "any"}
value={filters.genreMode ?? "any"} onChange={(m) => patch({ genreMode: m })}
onChange={(m) => patch({ genreMode: m })} />
/> <Combobox
<Combobox label={t("plex.filter.genre")}
label={t("plex.filter.genre")} options={f.genres}
options={facets.genres} selected={filters.genres}
selected={filters.genres} onChange={(next) => patch({ genres: next })}
onChange={(next) => patch({ genres: next })} />
/> </>
</> ),
), ),
},
]
: []),
{ {
id: "year", id: "year",
title: t("plex.filter.year"), title: t("plex.filter.year"),
body: <PlexYearFilter filters={filters} facets={facets} patch={patch} />, body: (
<PlexYearFilter filters={filters} facets={facets} facetsState={facetsState} patch={patch} />
),
}, },
...(scope === "movie" ...(scope === "movie"
? [ ? [
@@ -227,62 +247,55 @@ export default function PlexSidebar() {
/> />
), ),
}, },
...(facets && facets.content_ratings.length > 0 ...facetSection(
? [ "contentrating",
{ t("plex.filter.contentRating"),
id: "contentrating", (f) => f.content_ratings.length > 0,
title: t("plex.filter.contentRating"), (f) => (
body: ( <Combobox
<Combobox label={t("plex.filter.contentRating")}
label={t("plex.filter.contentRating")} options={f.content_ratings.map((o) => ({
options={facets.content_ratings.map((o) => ({ ...o,
...o, label: vocab(t, "certificate", o.value),
label: vocab(t, "certificate", o.value), }))}
}))} selected={filters.contentRatings}
selected={filters.contentRatings} onChange={(next) => patch({ contentRatings: next })}
onChange={(next) => patch({ contentRatings: next })} />
/> ),
), ),
}, ...facetSection(
] "studio",
: []), t("plex.filter.studio"),
...(facets && facets.studios.length > 0 (f) => f.studios.length > 0,
? [ (f) => (
{ <Combobox
id: "studio", label={t("plex.filter.studio")}
title: t("plex.filter.studio"), options={f.studios}
body: ( selected={filters.studios}
<Combobox onChange={(next) => patch({ studios: next })}
label={t("plex.filter.studio")} />
options={facets.studios} ),
selected={filters.studios} ),
onChange={(next) => patch({ studios: next })}
/>
),
},
]
: []),
// Playback class (Direct Play / Direct Stream / Transcode HW/SW) — movie-only (shows have no // Playback class (Direct Play / Direct Stream / Transcode HW/SW) — movie-only (shows have no
// class), and dropped when the facet is empty. Labels are localized (the facet ships class keys). // class), and dropped when the facet is empty. Labels are localized (the facet ships class keys).
...(scope === "movie" && facets && facets.playable.length > 0 ...(scope === "movie"
? [ ? facetSection(
{ "playable",
id: "playable", t("plex.filter.playable"),
title: t("plex.filter.playable"), (f) => f.playable.length > 0,
body: ( (f) => (
<Combobox <Combobox
label={t("plex.filter.playable")} label={t("plex.filter.playable")}
options={facets.playable.map((p) => ({ options={f.playable.map((p) => ({
value: p.value, value: p.value,
label: t(`plex.filter.playableOpt.${p.value}`), label: t(`plex.filter.playableOpt.${p.value}`),
count: p.count, count: p.count,
}))} }))}
selected={filters.playable} selected={filters.playable}
onChange={(next) => patch({ playable: next })} onChange={(next) => patch({ playable: next })}
/> />
), ),
}, )
]
: []), : []),
]; ];
@@ -483,15 +496,18 @@ function RemovableChip({ label, onRemove }: { label: string; onRemove: () => voi
export function PlexYearFilter({ export function PlexYearFilter({
filters, filters,
facets, facets,
facetsState = "ready",
patch, patch,
}: { }: {
filters: PlexFilters; filters: PlexFilters;
facets: PlexFacets | undefined; facets: PlexFacets | undefined;
facetsState?: FacetsState;
patch: (p: Partial<PlexFilters>) => void; patch: (p: Partial<PlexFilters>) => void;
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
return ( return (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
{facetsState !== "ready" && <FacetsStatus state={facetsState} announce />}
{facets && facets.years.length > 0 && ( {facets && facets.years.length > 0 && (
<YearPicker <YearPicker
years={facets.years} years={facets.years}
@@ -518,6 +534,26 @@ export function PlexYearFilter({
); );
} }
type FacetsState = "ready" | "loading" | "error";
/** Why a facet-filled section is empty while the facets are not here. `announce` makes it a live
* region: one section announces, the rest only show it. */
function FacetsStatus({
state,
announce = false,
}: {
state: Exclude<FacetsState, "ready">;
announce?: boolean;
}) {
const { t } = useTranslation();
const role = announce ? (state === "error" ? "alert" : "status") : undefined;
return (
<p className="text-muted px-1 py-1.5 text-xs" role={role}>
{t(state === "error" ? "common.loadError" : "common.loading")}
</p>
);
}
function NumberInput({ function NumberInput({
label, label,
value, value,
@@ -64,6 +64,27 @@ describe("the Plex rail's Year section", () => {
expect(screen.queryByRole("button", { pressed: true })).toBeNull(); expect(screen.queryByRole("button", { pressed: true })).toBeNull();
}); });
it("says the years are loading, or failed to load, rather than showing none", () => {
const { rerender } = render(
<PlexYearFilter
filters={EMPTY_PLEX_FILTERS}
facets={undefined}
facetsState="loading"
patch={() => {}}
/>,
);
expect(screen.getByRole("status").textContent).toBe("common.loading");
rerender(
<PlexYearFilter
filters={EMPTY_PLEX_FILTERS}
facets={undefined}
facetsState="error"
patch={() => {}}
/>,
);
expect(screen.getByRole("alert").textContent).toBe("common.loadError");
});
it("names the range fields", () => { it("names the range fields", () => {
render(<PlexYearFilter filters={EMPTY_PLEX_FILTERS} facets={FACETS} patch={() => {}} />); render(<PlexYearFilter filters={EMPTY_PLEX_FILTERS} facets={FACETS} patch={() => {}} />);
expect(screen.getByRole("spinbutton", { name: "plex.filter.yearFrom" })).toBeTruthy(); expect(screen.getByRole("spinbutton", { name: "plex.filter.yearFrom" })).toBeTruthy();
@@ -14,6 +14,7 @@ vi.mock("react-i18next", async (importOriginal) => {
useTranslation: () => ({ useTranslation: () => ({
t: (key: string, opts?: { count?: number }) => t: (key: string, opts?: { count?: number }) =>
opts?.count != null ? `${key}:${opts.count}` : key, opts?.count != null ? `${key}:${opts.count}` : key,
i18n: { language: "en" },
}), }),
}; };
}); });