Files
siftlode/frontend/src/lib/plexSort.ts
T
peter ccd7170a20 fix(sort): harden shared sort primitives (R13 S1 review round 2)
- SortControl no longer renders a blank select when an always-sorted view
  (no defaultLabel) is handed a key its options don't offer: it falls back to
  the first option instead of value="" (which also tripped React's controlled
  warning). Robustness now lives in the primitive, not each caller.
- PLEX_SORT_FALLBACK is Object.frozen: it's handed out by reference from
  healSort/healPlexSort and stored as provider state, so freezing turns any
  accidental in-place SortState mutation into a loud error instead of silently
  corrupting the shared fallback.
- Test: SortControl falls back to the first option for an unavailable key.

Gate green: tsc/eslint(0 err)/prettier/knip clean, vitest 106.
2026-08-14 00:10:13 +02:00

38 lines
1.9 KiB
TypeScript

import { healSort, type SortOption, type SortState } from "./columnSort";
// Plex's sort vocabulary, source-agnostic like the feed's — a `SortOption[]` fed to the shared
// SortControl. Direction lives in the SortState (no more sibling `sortDir` on PlexFilters); the wire
// call (`plexLibrary`) still splits it into `sort` + `sort_dir` at the server boundary.
const MOVIE_SORTS = ["added", "release", "year", "rating", "duration", "title"] as const;
const SHOW_SORTS = ["added", "release", "year", "rating", "title"] as const;
/** The sort keys a scope offers — movie libraries add `duration`; shows/both don't. */
function plexSortKeys(scope: string): string[] {
return [...(scope === "movie" ? MOVIE_SORTS : SHOW_SORTS)];
}
/** The historical default: `sort=title`, `sort_dir=asc`. Frozen: it is handed out by reference (from
* healSort/healPlexSort and as the provider's default state), so an accidental in-place mutation of a
* SortState would otherwise corrupt the shared fallback for every caller. */
export const PLEX_SORT_FALLBACK: SortState = Object.freeze({ key: "title", dir: "asc" as const });
/** Labelled, alpha-ordered options for the SortControl. `label` resolves each key (i18n
* `plex.sort.<key>`). */
export function plexSortOptions(scope: string, label: (key: string) => string): SortOption[] {
return plexSortKeys(scope)
.map((key) => ({ key, label: label(key) }))
.sort((a, b) => a.label.localeCompare(b.label));
}
/** Heal a stored sort against a scope's available keys, collapsing an out-of-scope key to the default.
* The single heal both the sidebar control and the browse query use, so they never diverge. Always
* non-null (the fallback is), so callers can read `.key` without a guard. */
export function healPlexSort(sort: SortState, scope: string): NonNullable<SortState> {
return healSort(
sort,
plexSortKeys(scope).map((key) => ({ key, label: key })),
PLEX_SORT_FALLBACK,
)!;
}