Compare commits

...
43 Commits
Author SHA1 Message Date
peter 41ad538edc release: 0.114.0 (feature/e13-notifications-order) 2026-10-29 02:18:56 +01:00
peter 7489cab3bc chore(release): 0.114.0 2026-10-29 02:06:52 +01:00
peter 91256b10b0 test(nav): pin the restore's last look and the clearing of the name it looks for 2026-10-29 01:31:41 +01:00
peter b22e903174 fix(notifications): Earlier opens on Back only for a row that can be nowhere else, and Mark read reads read at once
A namesake in Earlier while the row itself was still in Needs you or Recent opened the fold, which took the place match away and left the name twice on the page: the focus fell to <body>. Row names are trimmed as Back saves them, so a title ending in a space still matches. Mark read handed the focus to a row that still said it was unread until the write landed; the row now reads read in the press's own render, and unread again if the write is refused.
2026-10-29 01:31:40 +01:00
peter d6e72d7576 fix(notifications): Back to a row that folded away since opens Earlier on it 2026-10-29 00:47:52 +01:00
peter e3a4593acf fix(nav): Back looks for a moved item only in the page's lists, once its own list has had its chance, and its reveal stops the scroll restore
The cross-list match took a same-named row of the app-wide download tray, and took it at the first look while a virtualized list had yet to render the item. The reveal of a moved item ran before the scroll restore's first frame, which put the old offset back over it. The pending restore's name is readable, for a page that folds rows away.
2026-10-29 00:47:52 +01:00
peter fa271a31b9 fix(notifications): Mark all read waits for the fresh list, is not offered where it cannot act, and a row says it is unread
The mask over a stale read lifted when the write settled, before the refetch landed, and the band took the rows back. A band holding only what asks by its kind (an access-requests nudge) left the button enabled with nothing to do. The unread dot was only drawn: the spoken label now says it, apart from the name Back finds the row by, and follows the row while it holds the focus.
2026-10-29 00:38:34 +01:00
peter 947efaba6e docs(design): the notification order's decision row carries what it was chosen over and why 2026-10-29 00:38:34 +01:00
peter 22d873ed49 fix(nav): an item Back finds in another list is brought into view 2026-10-28 22:04:07 +01:00
peter d825aff30d fix(notifications): a row is named by what it is about, not its kind alone 2026-10-28 22:04:06 +01:00
peter 9dd56e94d4 docs(design): the notification center's order and its Earlier fold 2026-10-28 21:54:00 +01:00
peter 25ad2ee1ba test(ui): a self-closing dialog leaves the focus in a menu that stays open 2026-10-28 21:54:00 +01:00
peter c86ec7f7a5 fix(nav): Back finds an item that moved to another list by its name 2026-10-28 21:54:00 +01:00
peter 0469812499 fix(notifications): Mark all read empties a band of read rows, and a read landing mid-write cannot refill it 2026-10-28 21:54:00 +01:00
peter ee658b8bfc test(plex): pin the late-checkpoint race, its window, and the bulk mark's push supersede 2026-10-28 21:53:59 +01:00
peter 52b93d0014 fix(plex): a restart that fails to start still deletes the session it moved aside 2026-10-28 21:53:59 +01:00
peter c3ad7684ea test(ui): pin the notifications Earlier fold as a plain Pressable
Its text is the disclosure's own label, not a title to select.
2026-10-28 20:44:01 +01:00
peter a5666bfde9 style(notifications): the Earlier fold reads as a section heading, like its siblings
It was a ghost button in body type under two uppercase section labels. It is now
the heading itself, its text the disclosure's button (24px tall, past the
WCAG 2.5.8 floor).
2026-10-28 20:42:18 +01:00
peter f49dc6532f feat(notifications): what asks for you comes first, then one stream; old read rows fold
The center showed two fixed sections, the server's above this browser's, so an
admin's "access requests waiting" sat under every server row, week-old read
"Download ready" notices among them. One order now, for both sources
(lib/inboxOrder): "Needs you" (unread, an access-requests nudge, a notice
waiting on an interaction), then everything else newest first, and read rows
older than a week fold under "Earlier (n)", closed by default.

A row that asked in this visit keeps its place once read: marking it read no
longer moves it to another list under the reader. Mark all read empties the
band, the client notices of the visit included (the server rows read at once,
not when the write lands). Marking a row read from its button hands the focus
to the row instead of dropping it on <body> as the button goes.
2026-10-28 20:01:21 +01:00
peter 0d410592e2 fix(plex): a stale finish refusal no longer sticks, and a refusal keeps the player's detail
A refusal that landed after a replay raised the refusal flag for the finish that watch made later,
so leaving skipped the watched patch. Each finish now resets the flag and a refusal acts only for
the finish it answers.

A refusal while the player still sat on the item (the up-next card) removed the detail query it
observes, dropping the card and restarting its countdown, or losing it if the refetch failed. It is
now refetched under the player and dropped only when the player leaves.
2026-10-28 19:05:24 +01:00
peter 7e5d4a7d93 fix(ui): a closing dialog's focus restore reaches the dialog left standing above it, and survives a menu
A dialog closing on its own under a standing modal skipped its restore, and the standing modal's
own target was a control inside the closed one: closing it left the focus on <body>. The skipped
target is now handed to the standing dialog, which falls back to it.

Focus on a row of one of the dialog's own menus (the popover engine portals them out of the dialog
root) read as the user walking away, so Back with a menu open left the focus on <body>. A focus in
a popover portal now counts as held, and one still standing is not taken from.
2026-10-28 19:05:24 +01:00
peter 24190e4c16 fix(plex): a checkpoint sent just before the finish no longer lands on the watched row
The 10 s tick in flight when the player finishes (or a refusal rollback whose state write in fact
committed) wrote its mid-item position onto the freshly watched row and scheduled a resume push
after the scrobble, so Plex showed the item in progress again. The checkpoint is now a conditional
write that skips a row marked watched in the last 30 s and answers like a finish; a rewatch past
that is checkpointed as before. Marking an item (or a season/show) watched also supersedes resume
pushes still in flight, as the near-end finish already did.
2026-10-28 18:56:12 +01:00
peter e96a562f14 fix(plex): a segment name ffmpeg never spells is refused; teardown no longer holds the registry lock
The artifact guard parsed the sequence with int(), so a zero-padded or non-ASCII-digit name read
as a segment the session had reached and parked the sync route for the full 20 s wait. It now
also requires the canonical spelling segment_name() produces.

Stopping, replacing, culling or reaping a session waited up to 3 s for ffmpeg and deleted a whole
segmented film under _lock, which every segment request and checkpoint takes. Teardown now signals
the process and moves its directory aside under the lock, and waits/deletes after it. A new session
on the same path still waits for the dying ffmpeg first (it writes by path), and the orphan sweep
recognises a moved-aside directory left by a crash.
2026-10-28 18:48:21 +01:00
peter 4084dd2f92 release: 0.113.0 (feature/e46-url-is-the-view) 2026-10-28 02:19:29 +01:00
peter 6aa6a6efdf chore(release): 0.113.0 2026-10-28 02:07:48 +01:00
peter 5686759bca fix(nav): a page settling keeps a reload's overlay entry; an old entry's sub-view goes to its own (review round 4)
- useUrlMirror: a change before the user has done anything since the load is the page settling (the
  rail stepping off a playlist deleted since, Files off a folder gone), not another view: the reload
  mark stays, and the player that reopens takes its entry over — one Back closes it, as before.
- useHistorySubview: an entry an older build wrote is a module's only when its _sub is the view the
  address names under that module's key (the card's push kept the season's `v` beside its `m`).
- Playlists: the rail's default selection and the page's "the rail moved there" read one helper.
- moduleUrl contract: writer literals in a choice's branches are scanned too; the sub-view census
  walks type arguments of any depth and refuses an aliased import.
- A stale comment on the nav press over a live search.
2026-10-28 01:39:26 +01:00
peter 99a33e7fd1 fix(history): a sub-view reads only its own module's from the entry it mounts on
The entry's _sub now names its owner (_subOf, the module's address key). Signed out on a Plex season,
the sign-in card took the season for one of its modes and rendered a card with an empty button; the
other way round, Plex took the card's register view for one of its own. An entry an older build wrote
is read as the module's only when its address names one of that module's views.
2026-10-28 00:29:40 +01:00
peter 8804bdde63 Merge branch 'main' into feature/e46-url-is-the-view 2026-10-28 00:11:30 +01:00
peter 35266fd7e8 release: 0.112.1 (bug/authlib-cve) 2026-10-28 00:08:40 +01:00
peter 6211e15611 chore(release): 0.112.1 2026-10-27 23:59:09 +01:00
peter 02906d0acb fix(nav): the address keeps what the app rewrites around it (review round 3)
- The Feed press over a live search ends only the search: the feed's own view stays named.
- Leaving a search steps back only off an entry the app pushed (_ytOwn); one a link or a reload
  opened is cleared in place, also where the Navigation API is missing.
- useUrlMirror rewrites a changed view through replaceView, so a reload's overlay marks go; its
  first write and its landing writes keep them for an overlay that reopens.
- Files and Playlists: a box emptied and filled again settles at once, never naming the ended search.
- Playlists: a linked player is scoped to the playlist the store started with, and only the rail's
  own move to the first playlist is no pick.
- Contract: writer objects are scanned to their matching brace, a computed or shorthand key is
  refused, and every useHistorySubview call hands a named definition.
- Lint: playwright/no-skipped-test also refuses fixme (gate snapshot regenerated).
- FEED_DEFAULT_SORT at the three remaining sites; linkedNotListed says to search by name.
2026-10-27 23:33:22 +01:00
peter 66e427dfa4 fix(nav): a search the address opened marks its entry, so a channel over it keeps it
A search reached by a reload or a link had no _yt mark on its entry, so a channel opened from its
results carried none, and a landing back on that channel (an overlay over it closing) ended the
search under it.
2026-10-27 22:43:17 +01:00
peter 011dea8eb7 fix(deps): Authlib 1.7.2 -> 1.9.1 for CVE-2026-96760 and CVE-2026-114616
One pin bumped in place; pip check passes and pip-audit finds nothing.
2026-10-27 21:46:16 +01:00
peter e2b725dba7 test(e2e): the Files sort round trip starts from a known sort and puts the account's back
A header press cycles the sort (asc, desc, none), so the case depended on what an earlier run left
in the account: the third run in a row pressed it to none.
2026-10-27 16:34:17 +01:00
peter 6d57d62ac8 fix(nav): a linked player, file and search survive what the app does by itself (review round 2)
- Playlists: a link over a playlist the account does not hold plays alone; the rail's own
  fallback no longer counts as a pick that gives the player up.
- The linked opener opens or clears nothing once the address names another player, and stops
  looking (and fetching its row) once it settled.
- Files: a list the server's cap cut — the sorted or searched one too — keeps the link, with a
  notice of its own (EN/HU).
- History: an in-place view rewrite (search refine, count, channel to channel, sub-view)
  drops a reloaded entry's overlay marks (replaceView); a landing on a channel opened from a
  search keeps the search; the Feed press on a search opens the plain feed.
- Files/Playlists: an emptied search is written at once.
- Client log: plf/cf (column text filters) are typed keys; the shell has none of its own.
- Contract: writers outside lib/ take a literal or a lib/ function's result; every URL key is
  sorted typed or not; the writer regexes are held by a fixture; sub-views named; the bookmark
  net reads page tags.
- Feed defaults in one constant; one live-search queue helper; Scheduler writes through the
  Activity codec; notRun copy (EN/HU) names Forward and a plain "Search YouTube" button.
2026-10-27 16:08:52 +01:00
peter 0d5c6273f1 fix(nav): the address follows the view through overlays, reloads and Back (review round 1)
- A URL mirror names the view again on every entry Back or Forward lands on, so a change made
  under a dialog, a drawer or a sub-view is not undone by the next reload.
- A view pushed from the entry a reload under a dialog started from no longer inherits its overlay
  mark; a reload under two overlays closes onto the page in one step.
- The linked player reopens over a live search, gives itself up when its list moves first, and
  plays alone over an emptied playlist; a capped Files list keeps the link it cannot resolve.
- The Feed press over a channel ends the search; leaving a search ends its asked mark; Files and
  Playlists searches end with their page; the feed always names its view and debounces its search.
- Search-box keys are declared per module and kept out of the client log below TRACE.
- Writers outside lib/ go through codecs; the URL contract scans computed keys, overlay writers and
  two-line reads, and holds every page to a bookmark round trip (Config, Activity, Playlists and the
  Files sort and viewer added).
2026-10-27 13:52:42 +01:00
peter 7b4e007680 feat(nav): the live YouTube search and Home's budget are named in the address
A YouTube search is `?yt=<term>` (+ `ytn` for a non-default count), so a reload, a link
or Back/Forward reopens it. It runs by itself only where it costs no quota: the free page
scrape, a search asked for in this document, or results still cached. An API search
reopened any other way shows its term and waits for "Search YouTube again".

Home's time budget is `hb`; the question's draw stays on the history entry.

An e2e spec opens every page's bookmark in a fresh browser context; CLAUDE.md and
docs/development.md name the module URL codec as the place for view state.
2026-10-27 11:51:29 +01:00
peter 3d26ca0efa feat(player): a bookmark reopens every player as it was, once
The Plex player names the playlist it plays through (v=player:<id>:playlist:<pid>), so a bookmark
rebuilds the queue from the playlist's own order while the item is still in it.

Found in the browser and fixed:
- after a reload the shell's player opened a second one over Home and the feed: it read the catalog
  row the page had fetched (a disabled query still reads the shared cache); it now waits for ready.
- every reload under an open overlay left a dead history step: the first overlay to open takes over
  the entry the document was loaded on.
- the feed's address was implicit, the same as the start-page landing, so a reloaded or bookmarked
  feed opened as Home: the feed now names itself (page=feed) like every page.
- a linked file or video that is gone was said, but stayed in the address and was said again on
  every reload: its keys are taken off.

The overlay address is written in one place (the entry is named once it is current), and the player
keys only the codec reads are no longer exported.
2026-10-27 07:33:55 +01:00
peter fa893c73a3 feat(player): the YouTube player and the file viewer are named in the address
The player names what it plays in its own history entry (watch, wrel, wtab): a reload or a
bookmark reopens it on the page that hosts it, with that page's list as the queue, or alone
from the catalog (GET /api/videos/{id}/row); a page that hosts none gets the shell's. Back
lands on the page's address without it (useBackToClose's url; ui/Modal passes it on). The
Files viewer and player do the same (fview, fplay). The Plex and channel-manager views are
always written in full, as their fallback is remembered state.
2026-10-27 05:29:49 +01:00
peter d4f24de4ba feat(nav): tabs, list views and name searches are named in the address
Settings, Configuration and Users name their tab (stab/cfgtab/utab); a link's tab wins and a tab pre-selected
while its page is on screen now switches it. A playlist's sort, filters and grouping (plsort/plf/plgroup), the
Files sort (fsort, always written) and the name searches of Channels, Files, Playlists and Plex (cq/fq/plq/pq+pqf)
reopen from the address; the searches are written once the typing pauses.
2026-10-26 01:13:39 +01:00
peter 91d36b3357 fix(channel): the channel page's address names the channel and its own view, not the page under it
Opening a channel kept every key of the page under it (`?q=music&sort=oldest&chan=…`, a sort the
channel did not show), and the channel's own tab, sort and content types lived in its state alone, so a
reload or a bookmark lost them. Now the channel's address is `channelUrl`: the shell's keys and `chan`,
shared by `openChannel` and the channel link's href. The page writes its view (`chtab`, `chsort`,
`chtypes`, lib/channelPageUrlState) and reopens it; these are shell keys, cleared by a page switch and
by closing it in place. While a channel stands over a page, no module store writes its keys (`urlPage`);
Back finds them on the page's own entry. A link written by an older build opens without the page's keys.
2026-10-26 00:19:02 +01:00
peter 9bd7304bb9 fix(plex): a reload during a binge reopens the episode playing now
The player stepped to the next item in its own state while the history entry still held the item it
opened with, so F5 restarted the first episode. The player now says every item it moves on to, and the
page rewrites its entry with it (useHistorySubview's `follow`: no navigation, the overlays over the
player stay open, and the entry under an overlay is rewritten when a step lands back on it). The
player's URL is the item playing (`?v=player:<id>`), so a bookmark opens it; the list it plays from
stays in the history entry.
2026-10-25 23:24:29 +01:00
peter b30c60d1a5 feat(nav): each module declares its URL keys; a page switch clears them and a page opens without another's
The shell cleared a hand-kept key list on a page switch (it missed the Files and feed keys) and cleared
nothing when a page opened from a link carrying another page's keys. ModuleDef.urlKeys now names every
key a page's view writes, the shell derives both from the registry, and moduleUrl.contract.test holds the
declarations true: one owner per key, no shell key, exactly what each codec writes, and no undeclared
key literal in the app.
2026-10-25 20:48:14 +01:00
172 changed files with 7981 additions and 653 deletions
+31
View File
@@ -7,6 +7,37 @@ edit the release notes and re-run the generator.
Upgrading, pinning a version and rolling back: [docs/self-hosting.md](docs/self-hosting.md#upgrading).
## 0.114.0 — 2026-10-29
### New
- Notifications: what asks for you comes first, then everything else as one stream, newest first. Read notices older than a week fold under Earlier, and Back returns to the row you left.
### Fixed
- Plex: a progress save sent just before an episode ends no longer leaves it unwatched, and a refused finish no longer sticks.
- After a dialog closes, the keyboard focus returns to where it was, also inside a menu that stays open.
## 0.113.0 — 2026-10-28
### New
- The address names what you see: tabs, list views, sorts and searches (the live YouTube search too), the YouTube player and the file viewer. A reload, a bookmark or a shared link opens the same view.
- A link to a video reopens the player over its page once; Back closes it. A video the page no longer lists plays on its own and says so.
### Fixed
- Back and Forward step through the views as you saw them, across dialogs, players and reloads: a reload under an open player no longer leaves a Back step that does nothing.
- Signed out on a Plex page, the sign-in card could show a button with no text.
- The channel page's address names the channel and its own view, not the page under it.
- A reload during a Plex binge reopens the episode playing now, not the one it started from.
## 0.112.1 — 2026-10-27
### Fixed
- Security: the sign-in library is updated, closing two published vulnerabilities.
## 0.112.0 — 2026-10-25
### New
+1
View File
@@ -115,6 +115,7 @@ CQRS, a repository/DI framework, a router library, a generic CRUD-router factory
| FE keyboard shortcut | a row in `lib/keymap.ts` + `dispatch()` | a private `keydown` listener with its own key literals |
| FE list/grid keys | `NavGrid`/`keyboardNav` + `navItemAttrs` + `data-nav-open` | a private arrow-key / roving-tabindex handler |
| FE view push (history) | `rememberNavPosition()` right before `history.pushState` | a push that forgets: Back strands focus on `<body>` |
| FE view state | the module's URL codec: its keys in `urlKeys` (`module.ts`), read and written by `lib/<id>UrlState.ts` through `useUrlMirror` (contract-held, `e2e/bookmark.spec.ts`) | `useState` / sessionStorage alone: a reload, a bookmark or a shared link loses the view |
| FE a page's header content | the page renders it into the floating header itself (`PageHeader`, `ui/PageShell`) | a `page === …` branch in the shell's header, or a bridge carrying a page's state up to it |
| FE module store | its definition's `Store` (`module.ts`), mounted at the root by `ModuleStores`; it reads no other module's store (contract-held) | a provider hand-nested in `main.tsx` |
| FE saved views | the module's own store from `features/filters` (`createSavedViewsStore` + `useSavedViewsStore`) | one store switched by the active page — every visit elsewhere reset it |
+1 -1
View File
@@ -1 +1 @@
0.112.0
0.114.0
+30 -9
View File
@@ -6,9 +6,9 @@ The rest of the mirror's writes stay with the sync (`plex.sync`): a collection's
after a write-back, its local cleanup after a delete.
"""
from datetime import datetime, timezone
from datetime import datetime, timedelta, timezone
from sqlalchemy import CursorResult, delete, func, select, update
from sqlalchemy import CursorResult, delete, func, or_, select, update
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.orm import Session
@@ -271,6 +271,10 @@ def reorder_playlist(db: Session, pl: PlexPlaylist, rating_keys: list[str]) -> N
# --- a user's watch state --------------------------------------------------------------------
# How long after a watched mark a mid-item position is read as the finishing player's late tick
# (`checkpoint`): the tick is every 10 s, plus the request's own latency and a retry.
_LATE_CHECKPOINT_S = 30
def mark_finished(db: Session, user_id: int, item_id: int, now: datetime) -> bool:
"""Mark the item watched (position cleared) and say whether THIS call made it so. Two near-end
@@ -352,16 +356,33 @@ def checkpoint(
now: datetime,
*,
dirty: bool,
) -> PlexState:
"""Record a resume position. `dirty` marks it not yet mirrored to Plex — set before a push, so
the reconcile re-pushes it if the push fails and the push can settle it once Plex confirms."""
) -> bool:
"""Record a resume position, and say whether it was recorded. `dirty` marks it not yet mirrored
to Plex — set before a push, so the reconcile re-pushes it if the push fails and the push can
settle it once Plex confirms.
Not onto a row marked watched in the last `_LATE_CHECKPOINT_S`: that position is the player's
tick sent just before its own finish (or a mark from another tab), and writing it made a watched
item in progress again — on Plex too, through the resume push it carried. Decided by the write
itself, since the mark can commit between any read here and the write. A rewatch is checkpointed
as before once the mark is that far behind it."""
st = state_row(db, user, item_id, st)
st.position_seconds = position
st.progress_updated_at = now
values: dict[str, object] = {"position_seconds": position, "progress_updated_at": now}
if dirty:
st.synced_to_plex = False
values["synced_to_plex"] = False
not_just_finished = or_(
PlexState.status != "watched",
PlexState.watched_at.is_(None),
PlexState.watched_at <= now - timedelta(seconds=_LATE_CHECKPOINT_S),
)
result = db.execute(
update(PlexState)
.where(PlexState.id == st.id, not_just_finished)
.values(values)
.execution_options(synchronize_session="fetch")
)
db.flush()
return st
return isinstance(result, CursorResult) and result.rowcount > 0
def forget_state(db: Session, st: PlexState) -> None:
+152 -75
View File
@@ -66,7 +66,9 @@ _SESSION_IDLE_S = 600 # reap a session with no access for this long
# restart leaves them behind like any other. `sweep_orphans` deletes ONLY names
# matching one of those two shapes: `_HLS_ROOT` is admin-configurable (PLEX_HLS_DIR), so it may
# legitimately point at a shared scratch path we do not own, and a blanket "delete every directory
# under the root" would take the neighbours with it.
# under the root" would take the neighbours with it. A torn-down session's directory is renamed to
# its own name + `_TOMB` + 8 hex digits before it is deleted (see `_detach`), so a crash between the
# two leaves a name this sweep still recognises.
#
# The KEY is anchored to digits (a Plex rating_key is a number) — that is what keeps foreign names
# out. A `.+` there let `snapshot_2024_backup_+1.00` through, and pairing `.+` with an optional tail
@@ -74,8 +76,10 @@ _SESSION_IDLE_S = 600 # reap a session with no access for this long
# non-numeric rating_key would merely leave its directory unswept, which is the safe direction to
# fail. Covered by test_plex_stream.py — this regex is the only thing standing between the sweep
# and someone else's data.
_TOMB = ".dead-"
_SESSION_DIR_RE = re.compile(
r"^\d+_\d+(_[^_]+_[+-]\d+\.\d{2})?$|^\d+_u\d+_\d+_[^_]+_[+-]\d+\.\d{2}$"
r"^\d+_\d+(_[^_]+_[+-]\d+\.\d{2})?$"
rf"|^\d+_u\d+_\d+_[^_]+_[+-]\d+\.\d{{2}}({re.escape(_TOMB)}[0-9a-f]{{8}})?$"
)
# When this process started. `sweep_orphans` only deletes directories older than this: everything
# newer belongs to a session THIS run created, and since `start_session` reuses a directory path
@@ -93,7 +97,7 @@ _MTIME_GRACE_S = 2.0
_lock = threading.Lock()
# Keyed by VIEWER and item, (user_id, rating_key). Keyed by the item alone, a second account opening
# the same film `_kill`ed the first one's session: the displaced viewer got a 404, reclaimed at its
# the same film tore down the first one's session: the displaced viewer got a 404, reclaimed at its
# playhead, and so evicted the other in turn — two people could not watch one film at once. (One
# account on two devices still shares a session; that case ends in the player's bounded reclaim.)
_sessions: dict[tuple[int, str], "HlsSession"] = {}
@@ -641,29 +645,82 @@ def _probe_first_pts(seg: Path) -> float | None:
return None
def _kill(s: HlsSession) -> None:
# Teardown is split in two, because every segment request and checkpoint takes `_lock`: waiting up to
# 3 s for an ffmpeg to exit and deleting a whole segmented film under it stalled every other
# viewer's playback for one viewer's seek or one reap pass. `_detach` (under the lock) signals the
# process and renames its directory aside — so the deletion can never hit a NEW session that reuses
# the path — and `_finish` (after the lock is released) waits and deletes.
#
# What the rename cannot cover is the dying ffmpeg itself: it writes by path, so until it has exited
# it can still put a segment, or its final ENDLIST playlist, into a new session's directory on the
# same path. `_dying` remembers it by that path, and `_spawn` waits it out — under the lock, on
# purpose — before it creates the directory again.
_dying: dict[Path, subprocess.Popen] = {}
def _await_exit(key: str, proc: subprocess.Popen) -> None:
try:
s.proc.terminate()
try:
s.proc.wait(timeout=3)
proc.wait(timeout=3)
# silent-ok: the escalation IS the handling. A transcode that ignores TERM for three
# seconds gets KILL, which is exactly what this branch does.
except subprocess.TimeoutExpired:
s.proc.kill()
proc.kill()
except Exception as exc: # noqa: BLE001 — teardown finishes whatever the process does
# Not nothing: what survives this is an ffmpeg nobody owns any more, holding a VAAPI
# handle and a core, and the transcode cap that is supposed to bound them counts rows in
# `_sessions` rather than processes. One line is the only way that ever surfaces.
log.info(
"could not stop the transcode process",
extra=logs.event("plex.stream.kill_failed", key=key, reason=type(exc).__name__),
)
def _detach(s: HlsSession) -> tuple[HlsSession, Path | None]:
"""Caller holds _lock and has taken `s` out of `_sessions`. Hand the result to `_finish` once the
lock is released."""
try:
s.proc.terminate()
except Exception as exc: # noqa: BLE001 — teardown finishes whatever the process does
log.info(
"could not stop the transcode process",
extra=logs.event("plex.stream.kill_failed", key=s.key, reason=type(exc).__name__),
)
shutil.rmtree(s.dir, ignore_errors=True)
_dying[s.dir] = s.proc
tomb = s.dir.with_name(f"{s.dir.name}{_TOMB}{secrets.token_hex(4)}")
try:
s.dir.rename(tomb)
# silent-ok: nothing on disk (ffmpeg died before writing, or a sweep took it) — nothing to delete.
except FileNotFoundError:
return s, None
except OSError as exc:
# Cannot be moved aside, so it cannot be deleted outside the lock either: the path may be a
# new session's a moment from now. Deleted here instead, the old way.
log.info(
"a session directory could not be moved aside; deleted under the lock",
extra=logs.event("plex.stream.tomb_failed", key=s.key, reason=type(exc).__name__),
)
shutil.rmtree(s.dir, ignore_errors=True)
return s, None
return s, tomb
def _enforce_caps(user_id: int, max_transcodes: int, max_sessions: int) -> None:
"""Caller holds _lock. Three bounds, applied after a session is registered, each dropping the
least recently accessed sessions over it:
def _finish(doomed: "list[tuple[HlsSession, Path | None]]") -> None:
"""The slow half of a teardown, called WITHOUT `_lock`."""
for s, tomb in doomed:
_await_exit(s.key, s.proc)
with _lock:
if _dying.get(s.dir) is s.proc:
del _dying[s.dir]
if tomb is not None:
shutil.rmtree(tomb, ignore_errors=True)
def _enforce_caps(
user_id: int, max_transcodes: int, max_sessions: int
) -> "list[tuple[HlsSession, Path | None]]":
"""Caller holds _lock, and `_finish`es what this returns once it has released it. Three bounds,
applied after a session is registered, each dropping the least recently accessed sessions over it:
* this account's own sessions (`_MAX_SESSIONS_PER_USER`) — first, so a single account filling the
box evicts itself before anyone else;
@@ -676,6 +733,8 @@ def _enforce_caps(user_id: int, max_transcodes: int, max_sessions: int) -> None:
and the player restarts at the playhead, so from the server nothing failed — and "my film keeps
rebuffering" has no other explanation anywhere, hence the line."""
doomed: list[tuple[HlsSession, Path | None]] = []
def cull(pool: list[tuple[tuple[int, str], HlsSession]], cap: int, bound: str) -> None:
if len(pool) <= cap:
return
@@ -690,12 +749,13 @@ def _enforce_caps(user_id: int, max_transcodes: int, max_sessions: int) -> None:
sessions=len(pool),
),
)
_kill(sess)
_sessions.pop(reg, None)
doomed.append(_detach(sess))
cull([kv for kv in _sessions.items() if kv[0][0] == user_id], _MAX_SESSIONS_PER_USER, "user")
cull([kv for kv in _sessions.items() if kv[1].transcode], max_transcodes, "transcode")
cull(list(_sessions.items()), max_sessions, "total")
return doomed
def start_session(
@@ -759,68 +819,79 @@ def start_session(
# can't starve the co-located API/playback. preexec_fn runs in the forked child (POSIX); on a
# platform without fork (the API always runs in a Linux container in prod) it's simply omitted.
preexec = _sw_child_preexec if (transcode and not hw and os.name == "posix") else None
with _lock:
if replace_only is not None and _sessions.get(reg) is not replace_only:
return None # superseded/culled while we waited out of lock — don't clobber the newer one
old = _sessions.pop(reg, None)
if old is not None:
_kill(old)
shutil.rmtree(directory, ignore_errors=True)
directory.mkdir(parents=True, exist_ok=True)
proc = subprocess.Popen(
_ffmpeg_cmd(
src,
start_s,
doomed: list[tuple[HlsSession, Path | None]] = []
# Finished even when the new session fails to start (no space, no ffmpeg, a DB error): what
# was moved aside under the lock is otherwise left for a restart's sweep.
try:
with _lock:
if replace_only is not None and _sessions.get(reg) is not replace_only:
return None # superseded/culled while we waited out of lock — don't clobber the newer one
old = _sessions.pop(reg, None)
if old is not None:
doomed.append(_detach(old))
# An ffmpeg still exiting from THIS path (the old session, or one stopped a moment ago)
# would write into the directory about to be made; see `_dying`.
prev = _dying.pop(directory, None)
if prev is not None:
_await_exit(key, prev)
shutil.rmtree(directory, ignore_errors=True)
directory.mkdir(parents=True, exist_ok=True)
proc = subprocess.Popen(
_ffmpeg_cmd(
src,
start_s,
directory,
audio_ord,
aoff,
audio_langs if is_multi else None,
transcode=transcode,
hw=hw,
tonemap=tonemap,
preset=preset,
crf=crf,
max_height=max_height,
loudnorm=loudnorm,
),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
preexec_fn=preexec,
)
s = HlsSession(
key,
directory,
audio_ord,
aoff,
audio_langs if is_multi else None,
proc,
start_s,
variants,
transcode=transcode,
hw=hw,
tonemap=tonemap,
preset=preset,
crf=crf,
max_height=max_height,
loudnorm=loudnorm,
),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
preexec_fn=preexec,
)
s = HlsSession(
key,
directory,
proc,
start_s,
variants,
transcode=transcode,
hw=hw,
tonemap=tonemap,
user_id=user_id,
)
_sessions[reg] = s
# The one line that says which pipeline a session actually got. Everything downstream
# — the cap, the HW→SW fallback, the subtitle offset — is about this choice, and until
# now it was only inferable from the ffmpeg command nobody keeps.
log.info(
"an HLS session started",
extra=logs.event(
"plex.stream.session_started",
key=key,
transcode=transcode,
hw=hw,
tonemap=tonemap,
variants=len(variants or ()),
start_s=round(start_s, 1),
),
)
# Admin-configurable caps (Configuration → Plex); at least 1 each so playback can't be
# capped to zero.
_enforce_caps(
user_id,
max(1, sysconfig.get_int(db, "plex_max_transcodes")),
max(1, sysconfig.get_int(db, "plex_max_sessions")),
)
user_id=user_id,
)
_sessions[reg] = s
# The one line that says which pipeline a session actually got. Everything downstream
# — the cap, the HW→SW fallback, the subtitle offset — is about this choice, and until
# now it was only inferable from the ffmpeg command nobody keeps.
log.info(
"an HLS session started",
extra=logs.event(
"plex.stream.session_started",
key=key,
transcode=transcode,
hw=hw,
tonemap=tonemap,
variants=len(variants or ()),
start_s=round(start_s, 1),
),
)
# Admin-configurable caps (Configuration → Plex); at least 1 each so playback can't be
# capped to zero.
doomed += _enforce_caps(
user_id,
max(1, sysconfig.get_int(db, "plex_max_transcodes")),
max(1, sysconfig.get_int(db, "plex_max_sessions")),
)
finally:
_finish(doomed)
return s
s = _spawn(*_select_encode(db, item, transcode, src))
@@ -974,6 +1045,11 @@ def artifact_may_arrive(s: "HlsSession", filename: str) -> bool:
# session, absent for a single-audio one.
if variant not in (s.variants or (None,)):
return False
# And the name must be the one ffmpeg SPELLS for that sequence: `int()` also reads `seg_007.ts`
# and a non-ASCII digit run as a sequence the session may have reached, and neither file is
# ever written — a yes there parked the request for the whole wait.
if filename != segment_name(seq, variant):
return False
if seq == 0:
return True
try:
@@ -1108,16 +1184,16 @@ def reap_idle(finished_idle_s: float = _FINISHED_IDLE_S) -> int:
`reap_abandoned` bought the same safety by keeping every finished session for ten minutes — each
one a whole segmented copy of the film on a volume shared with the download center."""
now = time.time()
dropped = 0
doomed: list[tuple[HlsSession, Path | None]] = []
with _lock:
for reg, s in list(_sessions.items()):
done = s.proc.poll() is not None
idle = now - s.last_access
if idle > _SESSION_IDLE_S or (done and idle > finished_idle_s):
_kill(s)
_sessions.pop(reg, None)
dropped += 1
return dropped
doomed.append(_detach(s))
_finish(doomed)
return len(doomed)
def stop_session(user_id: int, key: str, session_id: str) -> bool:
@@ -1132,8 +1208,9 @@ def stop_session(user_id: int, key: str, session_id: str) -> bool:
s = _sessions.get((user_id, key))
if s is None or s.id != session_id:
return False
_kill(s)
_sessions.pop((user_id, key), None)
doomed = [_detach(s)]
_finish(doomed)
return True
+15
View File
@@ -249,6 +249,21 @@ def set_video_progress(
return {"ok": True, "video_id": video_id, "position_seconds": position}
@router.get("/videos/{video_id}/row")
def get_video_row(
video_id: str = Path(max_length=32),
user: User = Depends(current_user),
db: Session = Depends(get_db),
) -> dict:
"""One catalog video as the feed lists it (its channel, this user's watch state and resume point,
saved): what a player opened from an address starts from. The catalog only, so it costs nothing;
every video a player can open (a list's row, a related one) is in it."""
rows = queries.feed_rows_by_ids(db, user, [video_id])
if not rows:
raise not_found("video")
return rows[0]
@router.get("/videos/{video_id}")
def get_video_detail(
video_id: str,
+25 -10
View File
@@ -234,6 +234,15 @@ def person_image(u: str, request: Request) -> Response:
return imgcache.response(data, ct)
def _supersede_resume_pushes(user_id: int, item_id: int, now: datetime) -> None:
"""A watched mark supersedes every resume push still in flight for the item: stamping it as the
latest push makes `_resume_push_superseded` drop them. Popping the entry instead (to keep the map
small) removed the very guard, and an older resume push could then land at Plex AFTER the
scrobble and revive a resume point on a watched item. Eviction bounds the map."""
with _push_throttle_lock:
_last_push_at[(user_id, item_id)] = now
def _push_resume_guarded(
user_id: int,
item_id: int,
@@ -329,12 +338,7 @@ def item_progress(
near_end = duration > 0 and position > duration - _FINISH_MARGIN_S
if near_end:
flipped = service.mark_finished(db, user.id, it.id, now)
# The finish supersedes every resume push still in flight for this item: stamping it as the
# latest push makes `_resume_push_superseded` drop them. Popping the entry instead (to keep
# the map small) removed the very guard, and an older resume push could then land at Plex
# AFTER the scrobble and revive a resume point on a watched item. Eviction bounds the map.
with _push_throttle_lock:
_last_push_at[(user.id, it.id)] = now
_supersede_resume_pushes(user.id, it.id, now)
db.commit()
# Only the checkpoint that flipped the row scrobbles: a later checkpoint of the same finished
# item — or a second one racing this one — would otherwise bump Plex's viewCount again.
@@ -352,7 +356,11 @@ def item_progress(
push_now = _should_push_resume(user.id, it.id, now, final)
# Marked dirty before the (background) push so the reconcile knows to re-push if it fails, and so
# `push_state_to_plex` can settle synced_to_plex once Plex confirms.
service.checkpoint(db, user, it.id, st, position, now, dirty=push_now)
if not service.checkpoint(db, user, it.id, st, position, now, dirty=push_now):
# Marked watched a moment ago: this is the finishing player's late tick (see
# `service.checkpoint`), and the answer is the same one a near-end checkpoint gets.
db.commit()
return {"ok": True, "status": "watched", "position_seconds": 0}
db.commit()
if push_now:
_push_watch(
@@ -408,6 +416,8 @@ def item_state(
_push_watch(background, db, user.id, it.id, rating_key, "unwatched")
return {"ok": True, "status": "new"}
service.set_status(db, user, it.id, st, status)
if status == "watched":
_supersede_resume_pushes(user.id, it.id, datetime.now(timezone.utc))
db.commit()
if status == "watched" and prev_status != "watched":
_push_watch(background, db, user.id, it.id, rating_key, "watched")
@@ -427,6 +437,10 @@ def _bulk_state(
always reads the committed marks."""
pushable = plex_watch.link_for_push(db, user_id) is not None
to_push = service.bulk_state(db, user_id, eps, watched)
if watched:
now = datetime.now(timezone.utc)
for item_id, _rating_key, _action in to_push:
_supersede_resume_pushes(user_id, item_id, now)
if pushable and to_push:
# One coalesced background task for the whole batch (reuses a single session + Plex client),
# not one task per episode — a 200-ep show mark is 1 task, not 200.
@@ -632,9 +646,10 @@ def stream_hls_file(
try:
content = path.read_bytes()
except OSError:
# The session was torn down between the wait and the read — `_kill` rmtrees the whole
# directory, and nothing holds `_lock` across those two steps. It has to present as the same
# 404 a gone session does: the player's recovery is keyed on the STATUS (`code === 404`), so
# The session was torn down between the wait and the read — teardown moves the whole
# directory aside and deletes it, and nothing holds `_lock` across those two steps. It has
# to present as the same 404 a gone session does: the player's recovery is keyed on the
# STATUS (`code === 404`), so
# a 500 here skipped the reclaim and ended playback with "couldn't play" instead of
# restarting at the playhead. Ordinary trigger: `loadSession` awaits the new session — which
# kills and rmtrees the old one — before destroying the old hls instance, so the outgoing
+3 -2
View File
@@ -6,9 +6,10 @@
# bumped in place instead of a full regeneration, which would move every other package too — then
# `pip install -r requirements.lock && pip check` must pass. In place so far: urllib3 2.7.0 -> 2.8.0 (PYSEC-2026-4175/4176/4177); yt-dlp 2026.7.4 -> 2026.8.19
# (it marks the clients that need a stream PO token, so the downloader stops fetching into a 403);
# certifi 2026.7.22 -> 2026.10.19 (GHSA-6q48-6c7w-9gw2); brotli 1.2.0 -> 1.2.1 (PYSEC-2026-4322).
# certifi 2026.7.22 -> 2026.10.19 (GHSA-6q48-6c7w-9gw2); brotli 1.2.0 -> 1.2.1 (PYSEC-2026-4322);
# Authlib 1.7.2 -> 1.9.1 (CVE-2026-96760, CVE-2026-114616).
APScheduler==3.11.3
Authlib==1.7.2
Authlib==1.9.1
Mako==1.4.1
MarkupSafe==3.0.3
PyYAML==6.0.3
+1
View File
@@ -83,6 +83,7 @@ class _Proc:
class _Session:
def __init__(self, tmp_path, name: str, finished: bool, idle_s: float):
self.key = name
self.dir = tmp_path / name
self.dir.mkdir()
self.proc = _Proc(finished)
+158
View File
@@ -0,0 +1,158 @@
"""Tearing a session down does not stall everybody else's playback.
Every segment request (`current_session`) and every checkpoint (`touch_session`) takes the one
registry `_lock`. Stopping a session waits up to 3 s for its ffmpeg to exit and then deletes a whole
segmented film, ~1200 files — and that used to happen under the same lock, so one viewer's seek, a
cap cull or a reap pass held up every other viewer's HLS requests for seconds, each one a parked
threadpool worker and its pooled DB connection.
What still has to be atomic is pinned too: a session directory is reused for the same item, offset
and tag, so a new session on that path must not start before the old ffmpeg — which writes by path
— has exited.
"""
import threading
import time
import pytest
from app.plex import stream
class _SlowProc:
"""An ffmpeg that takes a while to exit after TERM: `wait` blocks until `exited` is set."""
def __init__(self, order: list[str], name: str):
self.order = order
self.name = name
self.waiting = threading.Event()
self.exited = threading.Event()
def poll(self):
return 0 if self.exited.is_set() else None
def terminate(self):
pass
def kill(self):
self.exited.set()
def wait(self, timeout=None):
self.waiting.set()
if not self.exited.wait(timeout):
raise stream.subprocess.TimeoutExpired("ffmpeg", timeout)
self.order.append(f"{self.name} exited")
return 0
class _Session:
def __init__(self, directory, proc, key: str):
self.id = f"sid-{key}"
self.key = key
self.dir = directory
self.proc = proc
self.last_access = time.time()
self.transcode = False
@pytest.fixture
def sessions(monkeypatch):
live: dict = {}
monkeypatch.setattr(stream, "_sessions", live)
monkeypatch.setattr(stream, "_dying", {}, raising=False)
return live
def test_stopping_a_session_does_not_hold_up_another_viewers_requests(tmp_path, sessions):
order: list[str] = []
slow = _SlowProc(order, "a")
d = tmp_path / "1_u1_0_0_+0.00"
d.mkdir()
(d / "seg_0.ts").write_bytes(b"x")
sessions[(1, "a")] = _Session(d, slow, "a")
sessions[(2, "b")] = _Session(tmp_path / "2_u2_0_0_+0.00", _SlowProc(order, "b"), "b")
stopper = threading.Thread(target=stream.stop_session, args=(1, "a", "sid-a"))
stopper.start()
try:
assert slow.waiting.wait(2.0), "the stop never waited for its ffmpeg"
got: list = []
reader = threading.Thread(target=lambda: got.append(stream.current_session(2, "b")))
reader.start()
reader.join(1.0)
assert not reader.is_alive(), "a segment request waited on another viewer's teardown"
assert got and got[0] is sessions[(2, "b")]
finally:
slow.exited.set()
stopper.join(5.0)
# The teardown still finishes: the session is gone and nothing of its directory is left behind.
assert (1, "a") not in sessions
assert sorted(p.name for p in tmp_path.iterdir()) == []
def test_a_reap_pass_does_not_hold_up_another_viewers_requests(tmp_path, sessions):
order: list[str] = []
slow = _SlowProc(order, "a")
d = tmp_path / "1_u1_0_0_+0.00"
d.mkdir()
gone = _Session(d, slow, "a")
gone.last_access = time.time() - stream._SESSION_IDLE_S - 5
sessions[(1, "a")] = gone
sessions[(2, "b")] = _Session(tmp_path / "2_u2_0_0_+0.00", _SlowProc(order, "b"), "b")
reaper = threading.Thread(target=stream.reap_idle)
reaper.start()
try:
assert slow.waiting.wait(2.0), "the reap never waited for its ffmpeg"
toucher = threading.Thread(target=stream.touch_session, args=(2, "b"))
toucher.start()
toucher.join(1.0)
assert not toucher.is_alive(), "a checkpoint waited on another viewer's teardown"
finally:
slow.exited.set()
reaper.join(5.0)
assert list(sessions) == [(2, "b")]
assert not d.exists()
class _FakeItem:
rating_key = "12345"
file_path = "/media/movie.mkv"
playable = "remux"
codec_video = "h264"
def test_a_new_session_on_a_dying_ones_path_starts_only_after_it_exited(
tmp_path, sessions, monkeypatch
):
"""The same item at the same second gets the same directory. The old ffmpeg writes by PATH, so
while it is still winding down after TERM it can write a segment — or, on a clean exit, a final
playlist with ENDLIST — into the NEW session's directory."""
order: list[str] = []
procs = iter([_SlowProc(order, "old"), _SlowProc(order, "new")])
def popen(*a, **k):
order.append("popen")
return next(procs)
monkeypatch.setattr(stream, "_HLS_ROOT", tmp_path)
src = tmp_path / "movie.mkv"
src.write_bytes(b"x")
monkeypatch.setattr(stream.paths, "local_media_path", lambda db, fp: src)
monkeypatch.setattr(stream.sysconfig, "get_int", lambda db, k: 2)
monkeypatch.setattr(stream.sysconfig, "get_bool", lambda db, k: False)
monkeypatch.setattr(stream.subprocess, "Popen", popen)
monkeypatch.setattr(stream, "wait_for", lambda *a, **k: True)
first = stream.start_session(db=None, user_id=7, item=_FakeItem(), start_s=0.0)
assert first is not None
stopper = threading.Thread(target=stream.stop_session, args=(7, "12345", first.id))
stopper.start()
assert first.proc.waiting.wait(2.0)
threading.Timer(0.3, first.proc.exited.set).start()
second = stream.start_session(db=None, user_id=7, item=_FakeItem(), start_s=0.0)
stopper.join(5.0)
assert second is not None and second.dir == first.dir
assert order.index("old exited") < order.index("popen", 1)
assert second.dir.is_dir(), "the old teardown deleted the new session's directory"
second.proc.exited.set()
+148 -1
View File
@@ -13,7 +13,7 @@ from datetime import datetime, timedelta, timezone
from sqlalchemy import select
from app.db import SessionLocal
from app.plex.models import PlexItem, PlexLibrary, PlexState
from app.plex.models import PlexItem, PlexLibrary, PlexSeason, PlexShow, PlexState
from app.plex import service as plex_service
from app.routes.plex import playback
@@ -81,3 +81,150 @@ def test_the_finish_supersedes_a_resume_push_still_in_flight(db, as_user, make_u
)
assert r.json() == {"ok": True, "status": "watched", "position_seconds": 0}
assert playback._resume_push_superseded(user.id, item.id, earlier) is True
def test_a_checkpoint_sent_before_the_finish_does_not_land_on_the_watched_row(
db, as_user, make_user, monkeypatch
):
"""The 10 s tick posted at 2699 of 3000 s (not near the end) races the credits auto-skip's
"watched". When the mark commits first, the late checkpoint used to write its position onto the
watched row and schedule a resume push after the scrobble: Plex showed the item in progress, and
a Plex-authoritative pull imported it back."""
user = make_user()
item = _item(db)
monkeypatch.setattr(playback.plex_stream, "touch_session", lambda uid, key: None)
client = as_user(user)
assert client.post("/api/plex/item/m1/state", json={"status": "watched"}).status_code == 200
r = client.post(
"/api/plex/item/m1/progress", json={"position_seconds": 2699, "duration_seconds": 3000}
)
assert r.status_code == 200, r.text
assert r.json() == {"ok": True, "status": "watched", "position_seconds": 0}
db.expire_all()
st = db.execute(select(PlexState).where(PlexState.item_id == item.id)).scalars().one()
assert (st.status, st.position_seconds) == ("watched", 0)
def test_a_rewatch_records_its_position_once_the_finish_is_behind_it(
db, as_user, make_user, monkeypatch
):
"""The other half: a watched item played again is still checkpointed — only a position arriving
right on the heels of the mark is read as that mark's late tick."""
user = make_user()
item = _item(db)
long_ago = datetime.now(timezone.utc) - timedelta(days=3)
db.add(PlexState(user_id=user.id, item_id=item.id, status="watched", watched_at=long_ago))
db.commit()
monkeypatch.setattr(playback.plex_stream, "touch_session", lambda uid, key: None)
r = as_user(user).post(
"/api/plex/item/m1/progress", json={"position_seconds": 600, "duration_seconds": 3000}
)
assert r.json() == {"ok": True, "position_seconds": 600}
db.expire_all()
st = db.execute(select(PlexState).where(PlexState.item_id == item.id)).scalars().one()
assert (st.status, st.position_seconds) == ("watched", 600)
def test_marking_watched_supersedes_a_resume_push_still_in_flight(
db, as_user, make_user, monkeypatch
):
"""The same guard the near-end finish has: a resume push scheduled before the mark must not reach
Plex after its scrobble."""
user = make_user()
item = _item(db)
earlier = datetime.now(timezone.utc) - timedelta(seconds=5)
assert playback._should_push_resume(user.id, item.id, earlier, final=True)
r = as_user(user).post("/api/plex/item/m1/state", json={"status": "watched"})
assert r.status_code == 200, r.text
assert playback._resume_push_superseded(user.id, item.id, earlier) is True
def _state(db, user, item):
db.expire_all()
st = (
db.execute(
select(PlexState).where(PlexState.user_id == user.id, PlexState.item_id == item.id)
)
.scalars()
.one()
)
return st.status, st.position_seconds
def test_a_mark_committed_after_the_checkpoints_read_still_refuses_it(db, make_user):
"""The race itself, not its sequential shadow: the route read the row while it was still in
progress, and the finish committed from another session before the checkpoint wrote. Only a write
conditional on the row as it is NOW refuses that position."""
user = make_user()
item = _item(db)
db.add(PlexState(user_id=user.id, item_id=item.id, status="new", position_seconds=2690))
db.commit()
now = datetime.now(timezone.utc)
read = plex_service.state_row(db, user, item.id) # what the checkpoint's route read: "new"
assert read.status == "new"
other = SessionLocal()
try:
assert plex_service.mark_finished(other, user.id, item.id, now) is True
other.commit()
finally:
other.close()
assert plex_service.checkpoint(db, user, item.id, read, 2699, now, dirty=True) is False
db.commit()
assert _state(db, user, item) == ("watched", 0)
def test_a_tick_seconds_behind_the_mark_is_refused_a_rewatch_a_minute_later_is_not(db, make_user):
"""A position right behind the mark is that mark's late tick; one a minute later is a rewatch.
Literal times on purpose: a window widened to an hour must fail here, not move with it."""
user = make_user()
item = _item(db)
now = datetime.now(timezone.utc)
st = PlexState(user_id=user.id, item_id=item.id, status="watched", watched_at=now)
db.add(st)
db.commit()
st.watched_at = now - timedelta(seconds=20)
db.commit()
assert plex_service.checkpoint(db, user, item.id, st, 600, now, dirty=True) is False
db.commit()
st.watched_at = now - timedelta(seconds=60)
db.commit()
assert plex_service.checkpoint(db, user, item.id, st, 600, now, dirty=True) is True
db.commit()
assert _state(db, user, item) == ("watched", 600)
def test_marking_a_season_watched_supersedes_its_episodes_resume_pushes(db, as_user, make_user):
"""The bulk mark has the same guard as one item's: an episode's resume push scheduled before
the season was marked must not reach Plex after the scrobble."""
user = make_user()
lib = PlexLibrary(plex_key="2", title="Shows", kind="show", enabled=True)
db.add(lib)
db.flush()
sh = PlexShow(rating_key="sh1", library_id=lib.id, title="Show")
db.add(sh)
db.flush()
se = PlexSeason(rating_key="se1", show_id=sh.id, season_number=1)
db.add(se)
db.flush()
ep = PlexItem(
rating_key="e1",
library_id=lib.id,
kind="episode",
title="E1",
show_id=sh.id,
season_id=se.id,
season_number=1,
episode_number=1,
)
db.add(ep)
db.commit()
earlier = datetime.now(timezone.utc) - timedelta(seconds=5)
assert playback._should_push_resume(user.id, ep.id, earlier, final=True)
r = as_user(user).post("/api/plex/season/se1/state", json={"watched": True})
assert r.json() == {"ok": True, "changed": 1, "watched": True}
assert playback._resume_push_superseded(user.id, ep.id, earlier) is True
+26 -1
View File
@@ -198,6 +198,31 @@ def test_a_name_the_session_cannot_produce_fails_at_once(client, tmp_path, sessi
assert elapsed < 2.0, f"waited {elapsed:.1f}s for a playlist this session never writes"
@pytest.mark.parametrize(
("name", "audio_langs"),
[
("seg_00.ts", None), # `int()` reads it as segment 0, which needs no predecessor
("seg_007.ts", None), # …as segment 7, whose predecessor seg_6.ts is on disk
("seg_٧.ts", None), # an Arabic-Indic 7: `\d` and `int()` both take it
("seg_a0_07.ts", ["hu", "en"]),
("seg_0_00.ts", ["hu", "en"]),
],
)
def test_a_segment_name_ffmpeg_never_spells_is_refused(tmp_path, name, audio_langs):
"""ffmpeg writes `seg_%d.ts`: no padding, ASCII digits. A name that only PARSES to a sequence the
session has reached is still a file that will never appear, and saying yes to it parked the
request for the full 20 s wait — the parking this guard exists to end."""
d = tmp_path / "m1_0_0_+0.00"
d.mkdir()
for v in plex_stream.session_variants(audio_langs) or (None,):
(d / plex_stream.segment_name(6, v)).write_bytes(b"x")
sess = _Session("sid-a", d, running=True, audio_langs=audio_langs)
assert not plex_stream.artifact_may_arrive(sess, name)
# The canonical spelling of the same next segment is still accepted.
v = (plex_stream.session_variants(audio_langs) or (None,))[0]
assert plex_stream.artifact_may_arrive(sess, plex_stream.segment_name(7, v))
@pytest.mark.parametrize("digits", [100, 5000])
def test_an_absurd_segment_index_is_a_404_not_a_500(client, tmp_path, sessions, digits):
"""`int()` on an unbounded digit run raises ValueError past 4300 digits, and only OSError was
@@ -213,7 +238,7 @@ def test_an_absurd_segment_index_is_a_404_not_a_500(client, tmp_path, sessions,
def test_a_session_torn_down_during_the_read_is_a_404_not_a_500(
client, monkeypatch, tmp_path, sessions
):
"""`_kill` rmtrees the whole directory and nothing holds `_lock` across the wait and the read,
"""Teardown moves the whole directory aside and nothing holds `_lock` across the wait and the read,
so the file can vanish in between — on every seek-restart, since `loadSession` awaits the new
session before destroying the old hls instance. The player's recovery is keyed on the 404
STATUS, so a 500 here skipped the reclaim and ended playback with "couldn't play"."""
+4 -2
View File
@@ -348,7 +348,8 @@ def test_an_early_checkpoint_drops_a_bare_state_and_zeroes_a_marked_one(db, make
user = make_user()
lib = _lib(db)
bare, hid = _movie(db, lib, "bare"), _movie(db, lib, "hid")
st = service.checkpoint(db, user, bare.id, None, 120, NOW, dirty=True)
assert service.checkpoint(db, user, bare.id, None, 120, NOW, dirty=True)
st = queries.state(db, user, bare.id)
assert (st.position_seconds, st.synced_to_plex) == (120, False)
_state(db, user, hid, status="hidden", position_seconds=40)
service.clear_progress(db, queries.state(db, user, bare.id), NOW)
@@ -429,7 +430,8 @@ def test_a_first_write_that_lost_the_race_updates_the_winners_row(db, make_user)
user = make_user()
it = _movie(db, _lib(db), "m-race")
_state(db, user, it, position_seconds=10) # the request that won, committed
st = service.checkpoint(db, user, it.id, None, 42, NOW, dirty=True) # read "none" before it
assert service.checkpoint(db, user, it.id, None, 42, NOW, dirty=True) # read "none" before it
st = queries.state(db, user, it.id)
assert (st.position_seconds, st.synced_to_plex) == (42, False)
st = service.set_status(db, user, it.id, None, "hidden")
assert st.status == "hidden"
+1
View File
@@ -39,6 +39,7 @@ class _Proc:
class _Session:
def __init__(self, session_id: str, directory):
self.id = session_id
self.key = "m1"
self.dir = directory
self.proc = _Proc()
self.last_access = time.time()
+67 -1
View File
@@ -26,6 +26,9 @@ from app.plex.stream import _SESSION_DIR_RE
"12345_0_2_+0.00", # current shape, explicit audio_ord
"12345_842_multi_-1.25", # multi-audio, negative offset
"12345_842_multi_+12.50",
# a torn-down session's directory, moved aside to be deleted outside the lock — left behind
# only if the process died between the rename and the delete
"12345_u7_842_multi_+12.50.dead-0123abcd",
],
)
def test_our_session_directories_are_swept(name):
@@ -47,6 +50,9 @@ def test_our_session_directories_are_swept(name):
"snapshot_2024_backup_+1.00", # session-ish tail, but the key isn't a rating_key
"backup_2024_multi_+0.00",
".config",
"12345_u7_0_0_+0.00.dead-", # a tombstone suffix with no id
"12345_u7_0_0_+0.00.dead-notours!",
"backup_u7_0_0_+0.00.dead-0123abcd",
],
)
def test_foreign_directories_are_left_alone(name):
@@ -159,7 +165,7 @@ class TestSweepOrphans:
class _FakeProc:
"""Stand-in for the ffmpeg Popen — start_session only stores it (and _kill/reap poll it later)."""
"""Stand-in for the ffmpeg Popen — start_session only stores it (and teardown/reap poll it later)."""
def poll(self):
return None
@@ -1052,3 +1058,63 @@ class TestSessionsPerViewer:
self._start(monkeypatch, user_id=uid)
assert len(stream._sessions) == 3 and (1, "12345") not in stream._sessions
assert oldest.proc.killed and not oldest.transcode
class TestTeardownFinishes:
"""A session taken down by a cap or replaced by its own viewer is only renamed aside under the
lock; it is deleted after. The rename alone already moves the directory and `terminate()` alone
already marks the proc killed — so what is pinned here is the tomb: a whole segmented copy of the
film that only a restart's sweep would otherwise reclaim."""
capturing_env = TestTranscodeStartSession.capturing_env
@staticmethod
def _left_behind(root):
return sorted(p.name for p in root.iterdir() if stream._TOMB in p.name) + sorted(
str(p) for p in stream._dying
)
def test_a_culled_session_is_deleted_not_only_moved_aside(self, capturing_env, monkeypatch):
monkeypatch.setattr(stream, "_dying", {})
first = TestSessionsPerViewer._start(monkeypatch, user_id=1, rating_key="1")
first.last_access -= 60
TestSessionsPerViewer._start(monkeypatch, user_id=1, rating_key="2")
TestSessionsPerViewer._start(monkeypatch, user_id=1, rating_key="3")
assert first.proc.killed and not first.dir.exists()
assert self._left_behind(capturing_env) == []
def test_a_viewers_restart_deletes_the_session_it_replaces(self, capturing_env, monkeypatch):
monkeypatch.setattr(stream, "_dying", {})
monkeypatch.setattr(
stream, "_select_encode", lambda db, item, transcode, src: (False, False)
)
monkeypatch.setattr(
stream, "_probe_first_pts", lambda seg: None
) # no real segment to probe
old = stream.start_session(db=None, user_id=1, item=_FakeItem(), start_s=0.0)
new = stream.start_session(db=None, user_id=1, item=_FakeItem(), start_s=600.0)
assert old.proc.killed and new.dir.exists() and not old.dir.exists()
assert self._left_behind(capturing_env) == []
def test_a_restart_that_fails_to_start_still_deletes_what_it_replaced(
self, capturing_env, monkeypatch
):
# The new ffmpeg cannot start (a full disk, no ffmpeg, no memory): the old session is already
# moved aside, and nothing else in this process would ever delete it.
monkeypatch.setattr(stream, "_dying", {})
monkeypatch.setattr(
stream, "_select_encode", lambda db, item, transcode, src: (False, False)
)
monkeypatch.setattr(
stream, "_probe_first_pts", lambda seg: None
) # no real segment to probe
old = stream.start_session(db=None, user_id=1, item=_FakeItem(), start_s=0.0)
def no_ffmpeg(*args, **kwargs):
raise OSError(28, "No space left on device")
monkeypatch.setattr(stream.subprocess, "Popen", no_ffmpeg)
with pytest.raises(OSError):
stream.start_session(db=None, user_id=1, item=_FakeItem(), start_s=600.0)
assert old.proc.killed and not old.dir.exists()
assert self._left_behind(capturing_env) == []
+47
View File
@@ -0,0 +1,47 @@
"""A catalog video as the feed lists it, the row a player opened from an address starts from. DB lane."""
from datetime import datetime, timezone
from app.catalog.models import Channel, Video
from app.reader.models import VideoState
def _video(db, vid="v1"):
db.add(Channel(id="UCo", title="Owner", handle="@owner"))
db.flush()
db.add(
Video(
id=vid,
title="A talk",
channel_id="UCo",
published_at=datetime.now(timezone.utc),
duration_seconds=3600,
)
)
db.commit()
def test_a_video_comes_as_the_feed_row_with_my_own_state(db, make_user, as_user):
me, other = make_user(), make_user()
_video(db)
db.add(VideoState(user_id=me.id, video_id="v1", status="new", position_seconds=600))
db.add(VideoState(user_id=other.id, video_id="v1", status="watched", position_seconds=90))
db.commit()
r = as_user(me).get("/api/videos/v1/row")
assert r.status_code == 200, r.text
row = r.json()
assert (row["id"], row["title"], row["channel_title"]) == ("v1", "A talk", "Owner")
assert (row["status"], row["position_seconds"]) == ("new", 600)
assert row["watch_url"] == "https://www.youtube.com/watch?v=v1"
def test_a_video_never_opened_has_no_state(db, make_user, as_user):
_video(db)
row = as_user(make_user()).get("/api/videos/v1/row").json()
assert (row["status"], row["position_seconds"], row["saved"]) == ("new", 0, False)
def test_a_video_outside_the_catalog_is_not_found(db, make_user, as_user):
r = as_user(make_user()).get("/api/videos/nope/row")
assert r.status_code == 404
assert r.json()["detail"]["code"] == "not_found"
+6 -1
View File
@@ -378,7 +378,11 @@ Which actions are visible and which live in a menu.
managing the shares, re-download, the copies, cancel / delete / remove
behind their confirms); a link inside a row keeps the browser's own right-click menu. A notification
row keeps its link and its unread mark, shows its dismiss on hover (in the "…" on touch), and its
"…" holds find / undo for an activity notice. The notification center's band keeps Mark all read
"…" holds find / undo for an activity notice. The notification center lists what asks for the
reader first ("Needs you · n": an unread row, a notice waiting on an action — one read during the
visit keeps its place there until Mark all read), then one stream of both sources, newest first,
and folds read rows older than a week under "Earlier (n)", a heading-style disclosure, closed — Back to a row
that folded away since opens it on that row. Its band keeps Mark all read
and puts Clear everything, now behind a confirm, in its "…"; the Scheduler's strip keeps Run all
and Pause and puts Purge discovery in its "…". A list whose row objects are rebuilt each render or replaced by a
poll passes `useContextMenu({ keyOf })` (its id), so the "…" still closes its own menu. A menu's
@@ -824,3 +828,4 @@ of a full-width panel and nothing on the right.
| 2026-10-25 | Player panel glyphs (owner 1A, 2A, 3) | In the side panel the queue row is glyph-only on one line, and Mark watched is a glyph toggle among the actions (✓ / ✓✓); the docked bar keeps its labels; the related switch at the default size, "Trending" | Labelled buttons wrapping onto three lines; glyphs on the docked bar too; Mark watched on its own line | The panel is narrow and the list controls are the same few every time; each glyph keeps its full name and shortcut in its tooltip; the docked bar has the width for words |
| 2026-10-25 | Auto-advance glyphs (owner E A, H a) | Auto-advance wears list glyphs (`ListEnd` next and off, `ListStart` previous, `Shuffle` random), in the panel and the docked bar; the auto-advance and loop cycles are `lit`, not `pressed` | The skip arrows for the mode; an X'd list for off; `aria-pressed` on a cycle | Beside Previous / Next the skip arrows read as a second Next; a cycle of three or four modes is no two-state switch, and its name already says which |
| 2026-10-25 | Restart and Reset glyphs (owner L A) | A menu's Play from the beginning wears `RotateCcw`, as the card's own Restart does; Reset (clear progress and status) wears `Eraser`; Redownload wears `RefreshCw`, the retry arrow | The skip arrow ⏮ on the menu's Restart; `RotateCcw` on both Restart and Reset; `TimerReset` for Restart | ⏮ is Previous beside the player; one action wore two glyphs, and two actions in one menu would have worn one |
| 2026-10-28 | Notification order (owner A-D1 a, A-D2 a, ★ a) | What asks for the reader first, from either source ("Needs you · n"), then one stream newest first; read rows older than a week fold under "Earlier (n)", closed, its label in the section-heading style with a chevron | One stream with no band; this browser's activity above the server's (the two fixed sections); a server-side retention that deletes old rows | An admin's access requests sat under up to a hundred server rows; week-old read notices crowded what is new; folding keeps the rows (nothing is deleted) and an unread row never folds, whatever its age |
+16 -2
View File
@@ -45,7 +45,18 @@ A frontend page is one folder, `frontend/src/modules/<id>/` (the layering is in
page renders into the floating header itself through `PageHeader`; the shell knows no page.
2. `module.ts`: its `ModuleDef` (`lib/moduleDef.ts`): id, label keys, icon, an optional `gate`, the page as a
`lazyWithPreload(() => import(…))`, and optionally a rail and a `Store`. Of its own folder it imports statically
only its store (a `…Provider` / `…Store` file); the page and the rail load lazily.
only its store (a `…Provider` / `…Store` file); the page and the rail load lazily. `urlKeys` names every
address-bar key its view writes (the URL is the view: a bookmark reopens it), its list kept in `lib/` beside
its codec; the shell clears them on a page switch and opens a page without another page's keys.
Every setting the page shows — a tab, a sort, a filter, a search, the item open in it — goes there: a codec
in `lib/<id>UrlState.ts` (read the params into the view, write the view as updates, a default left out —
or always written, when an address naming none falls back to a view remembered elsewhere), written with
`useUrlMirror` (a sub-view through `useHistorySubview`'s `url`, an overlay through `useBackToClose`'s),
always as the codec's result: a writer outside `lib/` computes no key of its own. Read back first on mount
(a link wins over anything remembered). A key that carries typed text — a search box's, a column filter
map with a text filter — is also in `typedUrlKeys` (the client log keeps what was typed out). Add its round
trip to `e2e/bookmark.spec.ts`, tagged with the page (`{ tag: "@<id>" }`). Only what an address cannot promise to
reopen stays out, said in its codec (Home's draw, `lib/homeUrlState`).
3. `index.ts`, the module's public face: the definition, and only what other folders must read (its store's
hooks). Another folder reaches the module through this file or not at all.
4. The id in `lib/urlState`'s `PAGES`, and the definition in `features/navigation/moduleRegistry.ts`, in
@@ -58,7 +69,10 @@ A frontend page is one folder, `frontend/src/modules/<id>/` (the layering is in
returns to `ui/FilterRail`; tsc names each table still missing the new id.
What holds it: `moduleRegistry.contract.test.ts` (every id defined once, from its own folder, lazily),
`moduleStores.contract.test.tsx` (no store reads another module), the `local/layers` lint rule (imports only go
`moduleStores.contract.test.tsx` (no store reads another module), `moduleUrl.contract.test.ts` (each URL key
belongs to one module and matches what its codec writes; a writer outside `lib/` is handed a literal or a `lib/`
function's result, never a key of its own; no key literal written or read from the live query undeclared; every key
sorted as typed or not; every page with keys in a tagged bookmark round trip), the `local/layers` lint rule (imports only go
down, a module only through its face) and `chunkGuard` in the build (no lazy page on the boot path), plus the
i18n parity test.
+259
View File
@@ -0,0 +1,259 @@
import { test, expect, type Browser, type Page } from "@playwright/test";
import {
clickVisibleChannelLink,
expectContentType,
gotoPage,
openApp,
openFirstVideo,
toggleContentType,
} from "./helpers";
// The address is the view: a view set through the UI, its address opened as a bookmark — in a NEW
// browser context, so nothing this tab remembered (its history entries, sessionStorage, the view
// storage it wrote) can stand in for what the address says. One round trip per page that names its
// view, tagged with the page (moduleUrl.contract.test holds the tags to the module definitions),
// plus the overlays the shell opens over any page (the channel page, the player) and the live
// search. Not Plex: what it shows is the instance's own library, which a test stack may not have.
const STORAGE_STATE = "e2e/.auth/state.json";
/** The page's address, opened as a bookmark in a fresh context of the same account. */
async function bookmarked(browser: Browser, page: Page, prepare?: (p: Page) => Promise<void>) {
const url = page.url();
const ctx = await browser.newContext({ storageState: STORAGE_STATE, locale: "en-US" });
const fresh = await ctx.newPage();
await prepare?.(fresh);
await openApp(fresh, url);
return fresh;
}
const tab = (p: Page, name: string) => p.getByRole("tab", { name, exact: true });
const column = (p: Page, name: string) =>
p.getByRole("columnheader", { name: new RegExp(`^${name}`) });
async function gotoAdminPage(page: Page, id: string): Promise<void> {
await page.getByTestId("nav-admin").click();
await page.getByTestId(`nav-admin-${id}`).click();
}
test.describe("a bookmark reopens the view it was taken of", () => {
test("the feed's filters", { tag: "@feed" }, async ({ page, browser }) => {
await openApp(page, "/?page=feed");
await toggleContentType(page, "includeLive");
await expect(page).toHaveURL(/[?&]live=/);
const fresh = await bookmarked(browser, page);
await expectContentType(fresh, "includeLive", true);
await fresh.context().close();
});
test("Home's time budget", { tag: "@home" }, async ({ page, browser }) => {
await openApp(page, "/?page=home");
await page.getByRole("button", { name: "An evening", exact: true }).click();
await expect(page).toHaveURL(/[?&]hb=long/);
const fresh = await bookmarked(browser, page);
await expect(fresh.getByRole("button", { name: "An evening", exact: true })).toHaveAttribute(
"aria-pressed",
"true",
);
await fresh.context().close();
});
test("a Settings tab", { tag: "@settings" }, async ({ page, browser }) => {
await openApp(page, "/?page=feed");
await gotoPage(page, "settings");
await tab(page, "Notifications").click();
const fresh = await bookmarked(browser, page);
await expect(tab(fresh, "Notifications")).toHaveAttribute("aria-selected", "true");
await fresh.context().close();
});
test("an admin page's tab", { tag: "@users" }, async ({ page, browser }) => {
await openApp(page, "/?page=feed");
await gotoAdminPage(page, "users");
await tab(page, "Access requests").click();
const fresh = await bookmarked(browser, page);
await expect(tab(fresh, "Access requests")).toHaveAttribute("aria-selected", "true");
await fresh.context().close();
});
test("a Configuration group", { tag: "@config" }, async ({ page, browser }) => {
await openApp(page, "/?page=feed");
await gotoAdminPage(page, "config");
const second = page.getByRole("tab").nth(1);
const name = (await second.textContent()) ?? "";
await second.click();
await expect(page).toHaveURL(/[?&]cfgtab=/);
const fresh = await bookmarked(browser, page);
await expect(fresh.getByRole("tab", { name, exact: true })).toHaveAttribute(
"aria-selected",
"true",
);
await fresh.context().close();
});
test("the Activity tab and its time window", { tag: "@activity" }, async ({ page, browser }) => {
await openApp(page, "/?page=feed");
await gotoAdminPage(page, "activity");
await tab(page, "Server log").click();
await page.getByRole("button", { name: "30 days", exact: true }).click();
await expect(page).toHaveURL(/[?&]aw=30d/);
const fresh = await bookmarked(browser, page);
await expect(tab(fresh, "Server log")).toHaveAttribute("aria-selected", "true");
await expect(fresh.getByRole("button", { name: "30 days", exact: true })).toHaveAttribute(
"aria-pressed",
"true",
);
await fresh.context().close();
});
test("a playlist and its sort", { tag: "@playlists" }, async ({ page, browser }) => {
await openApp(page, "/?page=feed");
await gotoPage(page, "playlists");
await expect(column(page, "Title")).toBeVisible();
await column(page, "Title").getByRole("button").first().click();
await expect(page).toHaveURL(/[?&]plsort=/);
const sorted = await column(page, "Title").getAttribute("aria-sort");
const fresh = await bookmarked(browser, page);
await expect(column(fresh, "Title")).toHaveAttribute("aria-sort", sorted ?? "");
expect(new URL(fresh.url()).searchParams.get("pl")).toBe(
new URL(page.url()).searchParams.get("pl"),
);
await fresh.context().close();
});
test(
"the Channels manager's tab and name search",
{ tag: "@channels" },
async ({ page, browser }) => {
await openApp(page, "/?page=feed");
await gotoPage(page, "channels");
await tab(page, "Hidden").click();
await page.getByPlaceholder("Search channels…").fill("zz");
await expect(page).toHaveURL(/zz/); // written once the typing settles
const fresh = await bookmarked(browser, page);
await expect(tab(fresh, "Hidden")).toHaveAttribute("aria-selected", "true");
await expect(fresh.getByPlaceholder("Search channels…")).toHaveValue("zz");
await fresh.context().close();
},
);
test("the Files search", { tag: "@files" }, async ({ page, browser }) => {
await openApp(page, "/?page=feed");
await gotoPage(page, "files");
await page.getByPlaceholder("Search files…").fill("zz");
await expect(page).toHaveURL(/zz/);
const fresh = await bookmarked(browser, page);
await expect(fresh.getByPlaceholder("Search files…")).toHaveValue("zz");
await fresh.context().close();
});
// A file of the test's own, uploaded for it and deleted after, and the account's sort put back:
// the account is left as it was found.
test(
"the Files sort, and the file open in the viewer",
{ tag: "@files" },
async ({ page, browser }) => {
await openApp(page, "/?page=feed");
const NAME = "bookmark-note";
// One a run cut short left behind goes first.
const left = (await (await page.request.get("/api/files")).json()) as Record<
string,
unknown
>[];
for (const f of left.filter((f) => JSON.stringify(f).includes(`"${NAME}`)))
await page.request.delete(`/api/files/${String(f.id)}`);
const up = await page.request.post("/api/files/upload", {
headers: { "X-Upload-Filename": `${NAME}.txt` },
data: Buffer.from("a note the bookmark reopens\n"),
});
expect(up.ok(), await up.text()).toBeTruthy();
const { id } = (await up.json()) as { id: number };
// The account's own sort, put back after: a header press cycles it (asc, desc, none), so the
// case starts from none, as the address names it, whatever an earlier run left.
const me = (await (await page.request.get("/api/me")).json()) as {
preferences?: Record<string, unknown>;
};
const ownSort = me.preferences?.filesSort ?? null;
try {
await openApp(page, "/?page=files&fsort=none");
await column(page, "Name").getByRole("button").first().click();
await expect(page).toHaveURL(/[?&]fsort=name/);
const sorted = await column(page, "Name").getAttribute("aria-sort");
await page.getByText(NAME, { exact: true }).first().click();
await expect(page).toHaveURL(new RegExp(`[?&]fview=${id}`));
const fresh = await bookmarked(browser, page);
await expect(fresh.getByRole("dialog", { name: NAME })).toBeVisible();
await fresh.keyboard.press("Escape");
await expect(column(fresh, "Name")).toHaveAttribute("aria-sort", sorted ?? "");
await fresh.context().close();
} finally {
await page.request.delete(`/api/files/${id}`);
await page.request.put("/api/me/preferences", { data: { filesSort: ownSort } });
}
},
);
test("a channel page's own tab, over the page it was opened from", async ({ page, browser }) => {
await openApp(page, "/?page=feed");
await expect(page.getByTestId("video-card").first()).toBeVisible();
expect(await clickVisibleChannelLink(page)).toBe(true);
const title = await page.getByTestId("channel-title").textContent();
await tab(page, "About").click();
const fresh = await bookmarked(browser, page);
await expect(fresh.getByTestId("channel-title")).toHaveText(title ?? "");
await expect(tab(fresh, "About")).toHaveAttribute("aria-selected", "true");
await fresh.context().close();
});
test("the player and the video it plays", async ({ page, browser }) => {
await openApp(page, "/?page=feed");
await openFirstVideo(page);
await expect(page).toHaveURL(/[?&]watch=/);
const watch = new URL(page.url()).searchParams.get("watch");
const fresh = await bookmarked(browser, page);
await expect(fresh.getByTestId("player-modal")).toBeVisible();
expect(new URL(fresh.url()).searchParams.get("watch")).toBe(watch);
await fresh.context().close();
});
// The search itself never reaches YouTube here: the answer is the server's shape, served by the
// test, and the request it answers is what the address named. The instance's search settings are
// pinned too (the free source, switched on): a stack left on the API source reopens the search
// waiting for its press, by design, and one with search off offers none.
test(
"a live YouTube search, its term and its count",
{ tag: "@feed" },
async ({ page, browser }) => {
const answer = async (p: Page, seen: string[]) => {
await p.route("**/api/me", async (route) => {
const me = (await (await route.fetch()).json()) as Record<string, unknown>;
return route.fulfill({ json: { ...me, search_source: "scrape", search_enabled: true } });
});
await p.route("**/api/search/youtube?**", (route) => {
seen.push(route.request().url());
return route.fulfill({ json: { items: [], next_cursor: null, source: "scrape" } });
});
};
await answer(page, []);
await openApp(page, "/?page=feed");
await page.getByPlaceholder("Search your subscriptions…").fill("lofi");
await page.getByRole("button", { name: "Search YouTube", exact: true }).click();
await expect(page.getByText("YouTube results for “lofi”")).toBeVisible();
await expect(page).toHaveURL(/[?&]yt=lofi/); // named as it opens, not only once the count is set
await page.getByRole("button", { name: "40", exact: true }).click();
await expect(page).toHaveURL(/[?&]ytn=40/);
const seen: string[] = [];
const fresh = await bookmarked(browser, page, (p) => answer(p, seen));
await expect(fresh.getByText("YouTube results for “lofi”")).toBeVisible();
await expect(fresh.getByRole("button", { name: "40", exact: true })).toHaveAttribute(
"aria-pressed",
"true",
);
await expect.poll(() => seen.length).toBeGreaterThan(0);
const asked = new URL(seen[0]!).searchParams;
expect([asked.get("q"), asked.get("limit")]).toEqual(["lofi", "40"]);
await fresh.context().close();
},
);
});
+2 -1
View File
@@ -898,7 +898,8 @@ export default tseslint.config(
plugins: { playwright },
rules: {
"playwright/no-focused-test": "error",
"playwright/no-skipped-test": "error",
// fixme too: a test Playwright never runs, which the bookmark net would still count.
"playwright/no-skipped-test": ["error", { disallowFixme: true }],
},
},
{
+95 -1
View File
@@ -23,7 +23,7 @@ vi.mock("../../lib/history", () => ({ useBackToClose: () => {} }));
import Modal from "./Modal";
import { clearAll, notify } from "../../lib/notifications";
import { pushLayer, removeLayer, useLayer } from "../../lib/layerStack";
import { flushSync } from "react-dom";
import { createPortal, flushSync } from "react-dom";
// Fire a keydown on window (where Modal installs its handler), inside act.
const press = (key: string, shiftKey = false) =>
@@ -311,6 +311,100 @@ describe("Modal focus trap (offsetParent stubbed 'visible')", () => {
document.body.removeChild(trigger);
});
it("hands its trigger to the dialog left standing above it, which restores it on close", () => {
// The standing upper dialog captured ITS restore target while the focus was inside the lower
// one — a control that is gone once the lower closes. So the lower skipping its own restore
// (above) handed the trigger to no one, and closing the upper left the focus on <body>.
// The arrangement keyboard help or the error dialog opened over a dialog actually has.
const trigger = document.createElement("button");
document.body.appendChild(trigger);
trigger.focus();
function Siblings() {
const [lower, setLower] = useState(true);
const [upper, setUpper] = useState(false);
return (
<>
{lower && (
<Modal initialFocus="close" title="lower" onClose={() => {}}>
<button onClick={() => setUpper(true)}>open upper</button>
<button onClick={() => setLower(false)}>close lower</button>
</Modal>
)}
{upper && (
<Modal initialFocus="close" title="upper" onClose={() => {}}>
<button onClick={() => setUpper(false)}>close upper</button>
</Modal>
)}
</>
);
}
render(<Siblings />);
screen.getByText("open upper").focus();
act(() => void screen.getByText("open upper").click()); // opened from inside the lower dialog
const inUpper = screen.getByText("close upper");
inUpper.focus();
// The lower closes on its own under the standing upper (`.click()` moves no focus).
act(() => void screen.getByText("close lower").click());
expect(screen.queryByText("close lower")).toBeNull();
expect(document.activeElement).toBe(inUpper);
act(() => void inUpper.click());
expect(document.activeElement).toBe(trigger);
document.body.removeChild(trigger);
});
it("restores the trigger when it closes with the focus in one of its menus", () => {
// The popover engine portals a menu out of the dialog's root (it carries no aria-modal), so a
// focus on a menu row read as "the user walked away": Back with a menu open inside a dialog
// left the focus on <body>. The portal marker is the one `ui/AnchoredPopover` reads too.
const trigger = document.createElement("button");
document.body.appendChild(trigger);
trigger.focus();
const portal = document.createElement("div");
portal.setAttribute("data-floating-ui-portal", "");
document.body.appendChild(portal);
const { unmount } = render(
<Modal initialFocus="close" title="t" onClose={() => {}}>
<Body />
{createPortal(<button>menu-row</button>, portal)}
</Modal>,
);
screen.getByText("menu-row").focus();
unmount();
expect(document.activeElement).toBe(trigger);
document.body.removeChild(trigger);
document.body.removeChild(portal);
});
it("does not pull the focus out of a menu that stays open when it closes on its own", () => {
// The other side of counting a menu row as held: a menu that is NOT this dialog's — a page's
// "…" left open while a dialog finishes in the background — stays standing, and a dialog that
// closes on its own (a write's success) must not take the focus from it to its trigger.
const trigger = document.createElement("button");
document.body.appendChild(trigger);
trigger.focus();
const portal = document.createElement("div");
portal.setAttribute("data-floating-ui-portal", "");
const row = document.createElement("button");
row.textContent = "page-menu-row";
portal.appendChild(row);
document.body.appendChild(portal);
function SelfClosing() {
const [open, setOpen] = useState(true);
return open ? (
<Modal initialFocus="close" title="t" onClose={() => {}}>
<button onClick={() => setOpen(false)}>finish</button>
</Modal>
) : null;
}
render(<SelfClosing />);
row.focus();
act(() => void screen.getByText("finish").click()); // `.click()` moves no focus
expect(screen.queryByText("finish")).toBeNull();
expect(document.activeElement).toBe(row);
document.body.removeChild(trigger);
document.body.removeChild(portal);
});
it("leaves the focus alone when the user moved it out of the dialog themselves", () => {
// The other half of the same rule, and the branch nothing drove: taking focus back from where
// the user deliberately put it is the rudest thing a closing dialog can do.
+6 -1
View File
@@ -65,6 +65,7 @@ export default function Modal({
placement = "center",
initialFocus,
headerActions,
url,
}: {
title: ReactNode;
initialFocus: ModalFocus;
@@ -81,10 +82,14 @@ export default function Modal({
placement?: "center" | "drawer" | "drawer-start" | "top";
/** Controls beside the ✕ in the header (a side panel's pin and customize, C2). */
headerActions?: ReactNode;
/** What the dialog names in the address while it is open, when it is part of the view (a viewer, a
* player): written into its own history entry, so a reload or a bookmark reopens it and Back lands
* on the address without it (lib/history). */
url?: Record<string, string | null>;
}) {
const { t } = useTranslation();
// Browser/mouse Back closes the topmost modal instead of navigating away.
useBackToClose(onClose);
useBackToClose(onClose, url);
// ONE container element for the dialog's whole life, re-parented between <body> and the fullscreen
// element — and attached before the children commit, so an `autoFocus` child
// still gets the focus. Both rules live in the hook; `ui/AnchoredPopover` shares it.
@@ -17,6 +17,7 @@ vi.mock("react-i18next", async (importOriginal) => {
import PageScroller from "./PageScroller";
import BackToTop from "./BackToTop";
import { notifyNav } from "../../lib/history";
import { revealedNavItem } from "../../lib/listNav";
beforeAll(() => {
// useScrollFade wires a ResizeObserver (watch-the-children); jsdom ships none.
@@ -125,6 +126,38 @@ describe("PageScroller scroll memory", () => {
expect(main.scrollTop).toBe(450);
});
// Back focuses an item the restore did not expect — one that moved to another list while the page
// was away — and scrolls it into view: the restore's next frame put the old offset back over it.
it("gives the page up to an item brought into view while it restores", () => {
let frames: FrameRequestCallback[] = [];
vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => frames.push(cb));
const flush = (n: number) => {
for (let i = 0; i < n; i++) {
const run = frames;
frames = [];
for (const cb of run) cb(0);
}
};
setEntry(1);
const { container } = render(
<PageScroller scrollKey="e:k1">
<div id="moved" />
</PageScroller>,
);
const main = sizedMain(container);
main.scrollTop = 450;
fireEvent.scroll(main);
setEntry(2);
notifyNav();
flush(1);
setEntry(1);
notifyNav(); // Back: the restore to 450 waits for its first frame
main.scrollTop = 120; // the item scrolled into view
revealedNavItem(container.querySelector("#moved")!);
flush(5);
expect(main.scrollTop).toBe(120);
});
// Landing at the end shows Back to top, whose spacer then brings the spot within reach.
it("finishes the way to a spot the spacer brings within reach after it lands", () => {
let frames: FrameRequestCallback[] = [];
@@ -12,6 +12,7 @@ import { StickyTopProvider } from "./stickyTop";
import { useBackToTopShown, useCornerLift } from "./backToTopState";
import { CONTENT_ID } from "./landmarks";
import { ensureNavId, peekNavId, subscribeNav } from "../../lib/history";
import { NAV_REVEAL_EVENT } from "../../lib/listNav";
// Saved scroll offsets, keyed by `${historyEntryId}:${scrollKey}`. The entry id ties an offset to the
// exact history entry, so Back restores where you left it and a forward navigation (a new entry) opens
@@ -63,11 +64,15 @@ function restoreScroll(el: HTMLElement, top: number): () => void {
el.removeEventListener("wheel", stop);
el.removeEventListener("touchstart", stop);
el.removeEventListener("pointerdown", stop);
el.removeEventListener(NAV_REVEAL_EVENT, stop);
document.removeEventListener("keydown", stop, true);
};
el.addEventListener("wheel", stop, { passive: true });
el.addEventListener("touchstart", stop, { passive: true });
el.addEventListener("pointerdown", stop);
// So does an item the keyboard brought into view (`lib/listNav`): Back focusing one that is not
// where the restored offset shows.
el.addEventListener(NAV_REVEAL_EVENT, stop);
document.addEventListener("keydown", stop, true);
const tick = () => {
if (cancelled) return;
+3 -2
View File
@@ -10,8 +10,9 @@ import { MEDIA_CHOSEN } from "./mediaChrome";
// Below it a side rail leaves a phone too little width for the content beside it (measured at 390 px:
// the rail clipped its own labels and Settings → Account pushed its buttons over their text), so there
// it is a horizontal row that scrolls. A page whose sub-tab is worth keeping persists it with
// lib/storage's useTabPersistedState (per browser tab: Admin Users, Config, Settings, Stats):
// a reload keeps the user where they were, and a fresh tab opens on the first sub-tab. Not every
// lib/storage's useTabPersistedState (per browser tab: Admin Users, Config, Settings) and names it in
// the address: a reload keeps the user where they were, a link opens its tab, and a fresh tab opens on
// the first sub-tab. Not every
// caller: the channel manager's view is account-wide (ChannelsProvider), and Downloads, a channel page
// and the player settings start on their first tab each time.
//
+33 -4
View File
@@ -75,6 +75,16 @@ export function lockBodyScroll(): () => void {
};
}
// A popover engine surface (`ui/AnchoredPopover`): portalled out of the dialog's root and carrying no
// aria-modal, so a focus on one of a dialog's menu rows is inside the dialog all the same.
const FLOATING = "[data-floating-ui-portal]";
// Restore targets handed to a dialog left standing above one that closed (see the cleanup below):
// that dialog's own target was captured while the focus was in the one that closed, and is gone.
// Keyed by the standing dialog's aria-modal element; a WeakMap, so a dialog that never closes
// through this hook leaves nothing behind.
const handedRestore = new WeakMap<Element, HTMLElement>();
/** The rest of the contract: lock the page behind, open focused, hand the focus back on close.
* `scopeRef` is the panel the focus should land in; `ownerRef`, when the dialog is bigger than its
* panel, is that whole dialog — it must be the SAME element `trapTab` is scoped to, or the two
@@ -128,6 +138,11 @@ export function useDialogChrome(
// Today that reads the same either way (a detached owner and a null one both fail every
// `contains` below), but the cleanup should not depend on a ref React has already let go of.
const ownerAtOpen = ownerRef?.current ?? scope;
// This dialog's aria-modal element, the key a closing dialog under it hands its target by.
const modalAtOpen =
ownerAtOpen?.closest('[aria-modal="true"]') ??
ownerAtOpen?.querySelector('[aria-modal="true"]') ??
null;
if (scope && !scope.contains(document.activeElement)) {
const back = focusedRef.current;
const target =
@@ -144,10 +159,12 @@ export function useDialogChrome(
// it — and while it held the focus we read that as the user walking away. Then both closing
// together left the focus on <body>: ours skipped the restore, and the child's own
// `restoreTo` was already detached (passive cleanups run parent-first). Measured in jsdom,
// and it is the ordinary case — an error dialog raised over a dialog.
// and it is the ordinary case — an error dialog raised over a dialog. And one of its own
// menus (see FLOATING): Back with a menu open closed the dialog with the focus on a menu row.
heldRef.current =
(owner?.contains(active) ?? false) ||
(active instanceof Element && active.closest('[aria-modal="true"]') != null);
(active instanceof Element &&
(active.closest('[aria-modal="true"]') != null || active.closest(FLOATING) != null));
// Where to put the focus back on a re-mount, though: the PANEL's own last focus. A toast is
// gone by then, so restoring onto it would strand the focus exactly as before.
if (scopeRef.current?.contains(document.activeElement))
@@ -172,16 +189,28 @@ export function useDialogChrome(
// this, a dialog closing on its own (an in-flight mutation's `onSuccess`) under a modal raised
// above it pulled the focus out of that standing dialog onto our own trigger, behind its
// scrim — where Enter still activated it.
//
// Skipped, the trigger is handed to that standing dialog instead: ITS target was captured
// while the focus was in ours, so it is gone now, and it falls back to the one handed to it.
// A popover still standing (a menu of a dialog that stays open) is not ours to take from
// either, though there is no dialog to hand the trigger to.
const owner = ownerAtOpen;
const active = document.activeElement;
const target = restoreTo?.isConnected
? restoreTo
: modalAtOpen
? handedRestore.get(modalAtOpen)
: undefined;
const above = active instanceof Element ? active.closest('[aria-modal="true"]') : null;
const standingAbove =
above !== null &&
above.isConnected &&
!above.contains(owner as Node | null) &&
!(owner?.contains(above) ?? false);
if (heldRef.current && !standingAbove && restoreTo && restoreTo.isConnected)
restoreTo.focus();
const standingMenu = active instanceof Element && active.closest(FLOATING)?.isConnected;
if (!heldRef.current || !target?.isConnected) return;
if (standingAbove) handedRestore.set(above, target);
else if (!standingMenu) target.focus();
};
}, [restoreTo, scopeRef, ownerRef, focusScope]);
}
@@ -38,6 +38,10 @@ const PLAIN: Record<string, [number, string]> = {
"shell/NavSidebar.tsx": [3, "the account trigger and its menu rows"],
"features/header/PaletteLauncher.tsx": [2, "launcher controls"],
"modules/playlists/PlaylistsRail.tsx": [1, "the load-error retry"],
"modules/notifications/NotificationsPanel.tsx": [
1,
"the Earlier (n) fold's heading (a disclosure: its text is its label)",
],
"modules/plex/PlexCollectionEditor.tsx": [1, "a checkbox row in a picker"],
"modules/plex/PlexInfo.tsx": [1, "the rating filter (a number)"],
"modules/plex/PlexPlayerSettings.tsx": [1, "the clock's date-style options"],
@@ -1,4 +1,35 @@
[
{
"version": "0.114.0",
"date": "2026-10-29",
"new": [
"Notifications: what asks for you comes first, then everything else as one stream, newest first. Read notices older than a week fold under Earlier, and Back returns to the row you left."
],
"fixed": [
"Plex: a progress save sent just before an episode ends no longer leaves it unwatched, and a refused finish no longer sticks.",
"After a dialog closes, the keyboard focus returns to where it was, also inside a menu that stays open."
]
},
{
"version": "0.113.0",
"date": "2026-10-28",
"new": [
"The address names what you see: tabs, list views, sorts and searches (the live YouTube search too), the YouTube player and the file viewer. A reload, a bookmark or a shared link opens the same view.",
"A link to a video reopens the player over its page once; Back closes it. A video the page no longer lists plays on its own and says so."
],
"fixed": [
"Back and Forward step through the views as you saw them, across dialogs, players and reloads: a reload under an open player no longer leaves a Back step that does nothing.",
"Signed out on a Plex page, the sign-in card could show a button with no text.",
"The channel page's address names the channel and its own view, not the page under it.",
"A reload during a Plex binge reopens the episode playing now, not the one it started from."
]
},
{
"version": "0.112.1",
"date": "2026-10-27",
"new": [],
"fixed": ["Security: the sign-in library is updated, closing two published vulnerabilities."]
},
{
"version": "0.112.0",
"date": "2026-10-25",
@@ -1,4 +1,37 @@
[
{
"version": "0.114.0",
"date": "2026-10-29",
"new": [
"Értesítések: elöl az, ami rád vár, utána minden más egy folyamban, a legújabb elöl. Az egy hétnél régebbi olvasott értesítések a Korábbiak alá csukódnak, és a Vissza arra a sorra tér vissza, ahonnan elmentél."
],
"fixed": [
"Plex: az epizód vége előtt közvetlenül elküldött mentés már nem hagyja megnézetlenül, és egy elutasított befejezés sem ragad be.",
"Párbeszédablak bezárása után a billentyűfókusz oda tér vissza, ahol volt, egy nyitva maradó menüben is."
]
},
{
"version": "0.113.0",
"date": "2026-10-28",
"new": [
"A cím megnevezi, amit látsz: a füleket, a listanézeteket, a rendezést és a kereséseket (az élő YouTube-keresést is), a YouTube-lejátszót és a fájlnézőt. Újratöltés, könyvjelző vagy megosztott link ugyanazt a nézetet nyitja meg.",
"Egy videóra mutató link egyszer újranyitja a lejátszót az oldala fölött, a Vissza bezárja. Ha az oldal már nem listázza a videót, a lejátszó csak azt az egyet játssza le, és ezt jelzi is."
],
"fixed": [
"A Vissza és az Előre úgy lép végig a nézeteken, ahogy láttad őket, párbeszédablakokon, lejátszókon és újratöltésen át: nyitott lejátszó alatti újratöltés után nem marad semmit sem csináló Vissza-lépés.",
"Plex-oldalon kijelentkezve a bejelentkező kártyán felirat nélküli gomb jelenhetett meg.",
"A csatornaoldal címe a csatornát és annak saját nézetét nevezi meg, nem az alatta lévő oldalt.",
"Plexben sorozatnézés közben az újratöltés az épp futó epizódot nyitja meg, nem azt, amelyikkel kezdted."
]
},
{
"version": "0.112.1",
"date": "2026-10-27",
"new": [],
"fixed": [
"Biztonság: frissült a bejelentkezési könyvtár, ami két nyilvánosan ismert sérülékenységet zár be."
]
},
{
"version": "0.112.0",
"date": "2026-10-25",
@@ -27,6 +27,8 @@ vi.mock("react-i18next", async (importOriginal) => {
import { NavigationProvider } from "./NavigationProvider";
import { useNavigation, useNavigationActions } from "./navigationContext";
import { urlPage } from "./urlPage";
import { channelUrl } from "../../lib/urlState";
import { useBackToClose } from "../../lib/history";
import { PageHeading } from "../../components/ui/Headings";
@@ -167,6 +169,19 @@ describe("NavigationProvider · setPage's same-page guard", () => {
expect(window.location.search).toBe("?page=plex&keep=1");
});
it("leaves the keys of the modules it does not list by hand behind too: Files and the feed's", () => {
// Each module declares its keys (`urlKeys`), and the switch clears the union of them: a key
// missing from a hand-kept list rode along onto the next page's entry.
window.history.replaceState(
{ sfPage: "files" },
"",
"/?page=files&folder=all&item=5&q=music&sort=oldest&keep=1",
);
const { result } = render();
act(() => result.current.setPage("plex"));
expect(window.location.search).toBe("?page=plex&keep=1");
});
it("pushes nothing when it is already that page", () => {
const { result } = render();
act(() => result.current.setPage("plex"));
@@ -195,6 +210,93 @@ describe("NavigationProvider · setPage's same-page guard", () => {
});
});
describe("NavigationProvider · a link carrying another page's keys", () => {
it("opens with only its own page's keys: what the page does not show, its address does not say", () => {
window.history.replaceState(
{},
"",
"/?page=activity&at=logs&folder=all&ctab=hidden&q=music&pscope=movie&pl=3&keep=1",
);
render();
expect(window.location.search).toBe("?page=activity&at=logs&keep=1");
});
it("keeps the channel page open over any page", () => {
window.history.replaceState({}, "", "/?page=stats&chan=UC1&folder=all");
const { result } = render();
expect(window.location.search).toBe("?page=stats&chan=UC1");
expect(result.current.channelView?.id).toBe("UC1");
});
it("opens a channel link with only the channel page's keys, even over the page they belong to", () => {
window.history.replaceState({}, "", "/?q=music&sort=oldest&chan=UC1&chtab=about&chtypes=ns");
render();
expect(window.location.search).toBe("?chan=UC1&chtab=about&chtypes=ns&page=feed");
});
});
// The channel page has an address of its own (the owner, 2026-10-05): it used to take the feed's
// filters along (`?q=music&sort=oldest&chan=…`), naming a sort the channel did not show.
describe("NavigationProvider · the channel page's address", () => {
it("names only the channel; the page under it keeps its own address for Back", async () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?q=music&sort=oldest");
const { result } = render();
act(() => result.current.openChannel("UC1", "One"));
expect(window.location.search).toBe("?page=feed&chan=UC1");
act(() => window.history.back());
await vi.waitFor(() => expect(result.current.channelView).toBeNull());
expect(window.location.search).toBe("?q=music&sort=oldest&page=feed");
});
it("says no page owns the address while the channel stands over it", () => {
window.history.replaceState({ sfPage: "plex" }, "", "/?page=plex");
const { result } = render();
expect(result.current.page).toBe("plex");
expect(urlPage(result.current)).toBe("plex");
act(() => result.current.openChannel("UC1", "One"));
expect(urlPage(result.current)).toBeNull();
});
it("another channel opened from it starts fresh", () => {
const { result } = render();
act(() => result.current.openChannel("UC1", "One"));
window.history.replaceState(window.history.state, "", "/?chan=UC1&chtab=about&chsort=oldest");
act(() => result.current.openChannel("UC2", "Two"));
expect(window.location.search).toBe("?chan=UC2");
});
it("a page switch takes the channel page's keys with it", () => {
window.history.replaceState({}, "", "/?chan=UC1&chtab=about&chsort=oldest&chtypes=n");
const { result } = render();
act(() => result.current.setPage("stats"));
expect(window.location.search).toBe("?page=stats");
});
it("closing it in place takes its keys with it", () => {
window.history.replaceState({}, "", "/?chan=UC1&chtab=about&chtypes=n");
const { result } = render();
stubNavigation([false]);
act(() => result.current.closeChannel());
expect(window.location.search).toBe("?page=feed");
});
});
// The YouTube player opens over any page and names itself in its own entry (lib/playerUrlState).
describe("NavigationProvider · the player's address", () => {
it("a page switch takes a player the address still names with it", () => {
window.history.replaceState({}, "", "/?q=music&watch=v1&wrel=v2&wtab=related");
const { result } = render();
act(() => result.current.setPage("stats"));
expect(window.location.search).toBe("?page=stats");
});
it("a channel link names no player: opening the channel closes it", () => {
window.history.replaceState({}, "", "/?q=music&watch=v1&wrel=v2&wtab=related");
render();
expect(channelUrl("UC1")).toBe("/?page=feed&chan=UC1");
});
});
describe("NavigationProvider · Back", () => {
// A tab that had a since-removed module open, reloaded onto the new build: its older history
// entries still name that page, and Back lands on one of them.
@@ -208,7 +310,7 @@ describe("NavigationProvider · Back", () => {
expect(result.current.page).toBe("feed");
// …and the entry says so too, so the address bar and a later Feed click agree with the screen.
expect(window.history.state).toMatchObject({ sfPage: "feed" });
expect(window.location.search).toBe("?keep=1");
expect(window.location.search).toBe("?page=feed&keep=1");
});
it("lands where a retired page's content went, and the entry names that page", () => {
@@ -325,7 +427,7 @@ describe("NavigationProvider · a page the account cannot open", () => {
window.history.replaceState(null, "", "/?page=scheduler&keep=1");
const { result } = render();
expect(result.current.page).toBe("feed");
expect(window.location.search).toBe("?keep=1");
expect(window.location.search).toBe("?page=feed&keep=1");
expect(window.history.state).toMatchObject({ sfPage: "feed" });
});
@@ -361,7 +463,7 @@ describe("NavigationProvider · a page the account cannot open", () => {
qc.setQueryData(qk.me(), member);
});
await settle();
expect(window.location.search).toBe("");
expect(window.location.search).toBe("?page=feed");
expect(window.history.state).toMatchObject({ sfPage: "feed" });
expect(getAccountRaw(PAGE_KEY)).toBe("feed");
act(() => {
@@ -381,7 +483,7 @@ describe("NavigationProvider · a page the account cannot open", () => {
});
await settle();
expect(result.current.channelView).toBeNull();
expect(window.location.search).toBe("");
expect(window.location.search).toBe("?page=feed");
expect(window.history.state?._chan).toBeUndefined();
});
});
@@ -0,0 +1,57 @@
// @vitest-environment jsdom
//
// A reload under a dialog that does not reopen (About) loads on the dialog's entry, its overlay mark
// still on it. A view rewritten in place there (the search refined) is another view: the next overlay
// pushes its own entry over it rather than taking this one over — taken over, closing it stepped back
// onto the entry below, and the screen went back to the search before the refine. Its own file: the
// entry is read as the history module loads, so it is set up before the import.
import { describe, expect, it, vi } from "vitest";
import { act, renderHook } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactNode } from "react";
vi.mock("react-i18next", async (importOriginal) => ({
...(await importOriginal<typeof import("react-i18next")>()),
useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en" } }),
}));
describe("a view rewritten in place on the entry a reload under a dialog started from", () => {
it("is where an overlay over it closes to", async () => {
window.history.replaceState({ sfPage: "feed", _yt: "dogs" }, "", "/?page=feed&yt=dogs");
window.history.pushState(
{ sfPage: "feed", _yt: "dogs", _ov: 1, _ovd: 1 },
"",
"/?page=feed&yt=dogs",
);
const { NavigationProvider } = await import("./NavigationProvider");
const { useNavigation, useNavigationActions } = await import("./navigationContext");
const { useBackToClose } = await import("../../lib/history");
const { qk } = await import("../../lib/queryKeys");
const { claimLocalData } = await import("../../lib/storage");
const qc = new QueryClient();
qc.setQueryData(qk.me(), { id: 1, role: "admin" });
claimLocalData(1);
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={qc}>
<NavigationProvider>{children}</NavigationProvider>
</QueryClientProvider>
);
const nav = renderHook(() => ({ ...useNavigation(), ...useNavigationActions() }), { wrapper });
act(() => nav.result.current.enterYtSearch("cats"));
const depth = window.history.length;
const overlay = renderHook(() => useBackToClose(() => {}));
await act(async () => {
await Promise.resolve();
});
expect(window.history.length).toBe(depth + 1);
await act(async () => {
const landed = new Promise((res) => window.addEventListener("popstate", res, { once: true }));
overlay.unmount();
await landed;
});
expect(new URLSearchParams(window.location.search).get("yt")).toBe("cats");
expect(nav.result.current.ytSearch).toBe("cats");
}, 30_000); // the provider's whole import graph loads inside the case (see the header)
});
@@ -2,8 +2,13 @@ import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react
import { useLatest } from "../../lib/useLatest";
import { useTranslation } from "react-i18next";
import { useMe } from "../../lib/useMe";
import { resolvePage, retiredParams, urlWithParams, type Page } from "../../lib/urlState";
import { ACTIVITY_KEYS } from "../../lib/activityUrlState";
import {
channelUrl,
resolvePage,
retiredParams,
urlWithParams,
type Page,
} from "../../lib/urlState";
import { useDocumentObjectTitle } from "../../lib/documentTitle";
import { getAccountRaw, setAccountRaw } from "../../lib/storage";
import {
@@ -12,8 +17,17 @@ import {
nextNavId,
notifyNav,
rememberNavPosition,
replaceView,
} from "../../lib/history";
import { pageTitleKey, reachablePage } from "./moduleRegistry";
import { foreignUrlKeys, moduleUrlKeys, pageTitleKey, reachablePage } from "./moduleRegistry";
import { CHANNEL_PAGE_KEYS } from "../../lib/channelPageUrlState";
import { PLAYER_KEYS } from "../../lib/playerUrlState";
import {
DEFAULT_YT_COUNT,
ytCountFrom,
ytSearchFrom,
ytSearchParams,
} from "../../lib/ytSearchUrlState";
import {
channelViewFrom,
loadInitialPage,
@@ -37,24 +51,35 @@ import {
//
// The contexts, their value types and the hooks live in navigationContext.ts.
/** The address bar of `page`'s root: the page (feed implicit) with every view-specific key cleared. */
/** The address bar of `page`'s root: the page — the feed too: a bare address is the landing (Home, or
* the remembered page), so a feed left unnamed reloaded or bookmarked as another page — no channel or
* player over it, and every module's own keys cleared — a page switch resets to that module's root,
* and its store mirrors what it holds back in. */
function pageRootParams(page: Page): Record<string, string | null> {
return {
page: page === "feed" ? null : page,
chan: null,
v: null,
pl: null,
pscope: null,
psort: null,
pshow: null,
pf: null,
ctab: null,
csort: null,
cf: null,
...Object.fromEntries(ACTIVITY_KEYS.map((k) => [k, null])),
page,
...closedChannelParams(),
...nulls(PLAYER_KEYS),
...nulls(moduleUrlKeys()),
};
}
/** The address of the page under a live search, the search ended: no search, player or channel. */
const searchEndParams = (): Record<string, string | null> => ({
...closedChannelParams(),
...nulls(PLAYER_KEYS),
...ytSearchParams(null, DEFAULT_YT_COUNT),
});
const nulls = (keys: readonly string[]) => Object.fromEntries(keys.map((k) => [k, null]));
/** No channel page: neither `chan` nor its view's keys, which the page itself writes (ChannelPage) —
* a closed channel leaves none behind. (An opened one gets its address from `channelUrl`.) */
const closedChannelParams = (): Record<string, string | null> => ({
chan: null,
...nulls(CHANNEL_PAGE_KEYS),
});
export function NavigationProvider({ children }: { children: ReactNode }) {
const { t, i18n } = useTranslation();
// Held here as well as in Settings: this is the instance mounted on every boot, so a value only
@@ -66,18 +91,30 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
// and the address bar (stamped from it below) agree.
const me = useMe();
const page = reachablePage(chosenPage, me);
// Ephemeral: not persisted and not in the URL, so a reload returns to the normal feed (a search
// spends quota, so we never auto-replay it) — UNLESS it was zero-quota scrape-sourced, which rides
// in history.state and is free to re-fetch. The popstate handler derives it from history.state so
// Back steps player → search → feed instead of the search vanishing without a history entry.
const [ytSearch, setYtSearch] = useState<string | null>(() => {
const st = window.history.state;
return st?._yt && st?._ytScrape ? (st._yt as string) : null;
});
// The live YouTube search: named in the address (`yt`, and `ytn` for its count, lib/ytSearchUrlState)
// so a reload or a link opens it again; its own history entry, so Back steps player → search → feed.
// Whether it RUNS by itself is not the address's to say: `ytAsked` is the term this document was
// asked to search for (sent from the search box, or "Search YouTube" pressed), on the entries
// it has stayed on since — leaving the search ends it. Anything else — a reload, a link, a Back or
// a Forward onto a search — runs only when it costs no quota (Feed decides).
const [ytSearch, setYtSearch] = useState<string | null>(() =>
page === "feed" ? ytSearchFrom(new URLSearchParams(window.location.search)) : null,
);
const [ytCount, setYtCountState] = useState(() =>
ytCountFrom(new URLSearchParams(window.location.search)),
);
const [ytAsked, setYtAsked] = useState<string | null>(null);
const ytSearchRef = useLatest(ytSearch);
const ytCountRef = useLatest(ytCount);
// The search ends: off the screen, and no longer asked for.
const endYtSearch = useCallback(() => {
setYtSearch(null);
setYtAsked(null);
}, []);
// The open channel page rides in history.state (_chan = id, _chanName = a name to show before the
// detail loads) AND is mirrored to the address bar as ?chan=<id>, so Back closes it, a reload restores
// it, and a bookmarked ?chan link opens it (unlike ytSearch, which is dropped). Reload of an in-app
// entry reads history.state._chan; a fresh bookmark has only the ?chan param.
// it, and a bookmarked ?chan link opens it. Reload of an in-app entry reads history.state._chan; a
// fresh bookmark has only the ?chan param.
const [channelView, setChannelView] = useState<ChannelView | null>(() =>
channelViewFrom(window.history.state, window.location.search),
);
@@ -107,31 +144,36 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
closeOverlaysThenNavigate(() => {
// 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) {
// So must a live search on it, though that press ends only the search: the page's view stays.
const samePage = next === pageRef.current && !channelViewRef.current;
if (samePage && ytSearchRef.current == null) {
then?.();
return;
}
setChannelView(null); // leave any open channel page when navigating via the rail
// A live search under that channel ends too: the page opens at its root, which the address
// below names — the Feed press over a channel opened from a search included.
endYtSearch();
setPageState(next);
setAccountRaw(PAGE_KEY, next);
// Push an in-app history entry so browser/mouse Back steps through pages instead of leaving
// the app. A fresh { sfPage } (no carried-over _yt/_chan markers) so each page starts at its
// root, and the address bar reflects the page (feed is implicit) while clearing the
// view-specific params (chan/v/pl and the plex content keys pscope/psort/pshow/pf) — a page
// switch resets to that module's root. Feed filters (owned by FeedFiltersProvider) are left
// intact; the plex/channels keys re-mirror from PlexProvider / ChannelsProvider on return to
// their page. The item it was opened from is still focused: the state setters above have not
// re-rendered anything yet.
// root, and the address bar reflects the page (the feed too) while clearing `chan` and
// every module's own keys (pageRootParams) — a page switch resets to that module's root, and
// each module's store mirrors its state back in on its page. The item it was opened from is
// still focused: the state setters above have not re-rendered anything yet.
// The press on a search over its own page ends only the search: the page's view is the one
// on screen and stays named — its store, unchanged, writes nothing back in.
rememberNavPosition();
window.history.pushState(
{ sfPage: next, sfScroll: nextNavId() },
"",
urlWithParams(pageRootParams(next)),
urlWithParams(samePage ? searchEndParams() : pageRootParams(next)),
);
notifyNav();
then?.();
}),
[pageRef, channelViewRef],
[pageRef, channelViewRef, ytSearchRef, endYtSearch],
);
// A sub-view (channel / YT search) is an OVERLAY, not a page change. Like setPage it never lands
@@ -139,10 +181,12 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
// inside one.
const openChannel = useCallback((id: string, name?: string) => {
closeOverlaysThenNavigate(() => {
const url = urlWithParams({ chan: id });
// The channel's address names the channel alone: the page under it keeps its own keys on its
// own entry, where Back finds them, and writes none while the channel stands over it (urlPage).
const url = channelUrl(id);
if (window.history.state?._chan) {
const st = window.history.state;
window.history.replaceState({ ...st, _chan: id, _chanName: name ?? null }, "", url);
replaceView({ ...st, _chan: id, _chanName: name ?? null }, url);
} else {
const st = rememberNavPosition();
window.history.pushState({ ...st, _chan: id, _chanName: name ?? null }, "", url);
@@ -157,36 +201,67 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
// No owned history entry (e.g. opened straight from a ?chan bookmark), or none of this document
// below it to step back to (a full tab, see backStaysInDocument): clear it in place — the
// entry's channel marks and the ?chan param.
// A live search under it (the channel opened from its results) is on screen again, and named
// again: the channel's address carried none of it.
setChannelView(null);
const { _chan: _id, _chanName: _name, ...st } = window.history.state ?? {};
window.history.replaceState(st, "", urlWithParams({ chan: null }));
replaceView(
st,
urlWithParams({
...closedChannelParams(),
...ytSearchParams(ytSearchRef.current, ytCountRef.current),
}),
);
}
}, []);
}, [ytSearchRef, ytCountRef]);
const enterYtSearch = useCallback((q: string) => {
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.
const { _ytScrape: _drop, ...st } = window.history.state || {};
if (st._yt)
window.history.replaceState({ ...st, _yt: q }, ""); // refine current search
else {
// New sub-view entry.
const { _ytScrape: _dropToo, ...left } = rememberNavPosition();
window.history.pushState({ ...left, sfPage: "feed", _yt: q }, "");
setYtAsked(q);
const st = window.history.state ?? {};
const here = new URLSearchParams(window.location.search);
if (st._yt || ytSearchFrom(here) != null) {
// Refine the search on screen, in place, at the count it shows (one a link opened too: it
// is the first entry of this document, so its new `_yt` mark has nothing of ours below it).
replaceView({ ...st, _yt: q }, urlWithParams(ytSearchParams(q, ytCountFrom(here))));
} else {
// New sub-view entry, at the default count — ours (`_ytOwn`): leaving it steps back off it.
setYtCountState(DEFAULT_YT_COUNT);
const left = rememberNavPosition();
window.history.pushState(
{ ...left, sfPage: "feed", _yt: q, _ytOwn: 1 },
"",
urlWithParams(ytSearchParams(q, DEFAULT_YT_COUNT)),
);
}
}, []);
// The press that runs the search on screen, where it did not run by itself.
const askYtSearch = useCallback(() => setYtAsked(ytSearchRef.current), [ytSearchRef]);
const setYtCount = useCallback(
(n: number) => {
setYtCountState(n);
replaceView(
window.history.state ?? {},
urlWithParams(ytSearchParams(ytSearchRef.current, n)),
);
},
[ytSearchRef],
);
const exitYtSearch = useCallback(() => {
// Pop our search entry (so Forward still works); fall back to a clear in place if we don't own
// one, or there is no entry of this document below it (a full tab, see backStaysInDocument).
if (window.history.state?._yt && backStaysInDocument()) window.history.back();
// one — a search a link or a reload opened is marked (`_yt`) but was pushed by nobody: below it is
// another site, or nothing — or there is no entry of this document below it (a full tab, see
// backStaysInDocument).
if (window.history.state?._ytOwn && backStaysInDocument()) window.history.back();
else {
setYtSearch(null);
const { _yt: _q, _ytScrape: _scrape, ...st } = window.history.state ?? {};
window.history.replaceState(st, "");
endYtSearch();
const { _yt: _q, _ytOwn: _own, ...st } = window.history.state ?? {};
replaceView(st, urlWithParams(ytSearchParams(null, DEFAULT_YT_COUNT)));
}
}, []);
}, [endYtSearch]);
// Leaving the feed ends any live YouTube search, so coming back shows the normal feed. Adjusted
// DURING the render that changes the page, against the page we were last on: as an effect it ran
@@ -196,7 +271,7 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
const [pageSearchWasOn, setPageSearchWasOn] = useState(page);
if (pageSearchWasOn !== page) {
setPageSearchWasOn(page);
if (page !== "feed") setYtSearch(null);
if (page !== "feed") endYtSearch();
}
// The browser tab names the place and the object in it (DESIGN § Composition, "Where am I"):
@@ -233,25 +308,33 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
// then sync state from history.state on popstate — the browser restores each entry's URL for us, so
// the popstate handler only needs to read history.state.
useEffect(() => {
// A reload drops a stale _yt EXCEPT when scrape-sourced (zero quota): then keep _yt + _ytScrape
// so it restores and re-fetches free (ytSearch above already initialised from it). _chan/_chanName
// are always kept so a channel page survives F5.
// The entry of a search the address names carries its `_yt` mark, whichever way it opened (sent
// from the box, a reload, a link): a channel opened from its results reads the search under it
// from that mark. A mark left without one (an older build's entry) goes. _chan/_chanName are
// always kept so a channel page survives F5.
const st = window.history.state || {};
// Mirror the resolved initial page to the address bar (feed implicit) so a page reached from the
// stored landing pref — not just from the URL — is itself bookmarkable. urlWithParams preserves any
// ?chan / ?v / ?pl / filter params the loaders already read.
// Mirror the resolved initial page to the address bar (the feed too) so a page reached from the
// stored landing pref — not just from the URL — is itself bookmarkable. urlWithParams keeps the
// shell's keys (?chan, a player's) and the page's own; other pages' go (below).
// A retired page's link — or the remembered last page, when that is what opened — also opens its
// part of the page that replaced it (an `at` tab).
const linked = new URLSearchParams(window.location.search).get("page");
const remembered = getAccountRaw(PAGE_KEY);
// A link can carry another page's keys (hand-edited, or written by an older build): the page
// opens without them, so its address names only what it shows — and a channel page open over it
// shows none of the page's own (an older build's channel links carried the feed's filters).
const shown = channelViewFrom(st, window.location.search);
const url = urlWithParams({
...nulls(shown ? moduleUrlKeys() : foreignUrlKeys(mountPage)),
...retiredParams(linked ?? (resolvePage(remembered) === mountPage ? remembered : null)),
page: mountPage === "feed" ? null : mountPage,
page: mountPage,
});
if (st._yt && st._ytScrape) {
window.history.replaceState({ ...st, sfPage: mountPage }, "", url);
const named =
mountPage === "feed" ? ytSearchFrom(new URLSearchParams(window.location.search)) : null;
if (named != null) {
window.history.replaceState({ ...st, _yt: named, sfPage: mountPage }, "", url);
} else {
const { _yt: _staleYt, _ytScrape: _staleScrape, ...rest } = st;
const { _yt: _staleYt, _ytScrape: _staleScrape, _ytOwn: _staleOwn, ...rest } = st;
window.history.replaceState({ ...rest, sfPage: mountPage }, "", url);
}
function onPop(e: PopStateEvent) {
@@ -267,13 +350,22 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
window.history.replaceState(
{ ...window.history.state, sfPage: p },
"",
urlWithParams({ ...retiredParams(sf), page: p === "feed" ? null : p }),
urlWithParams({ ...retiredParams(sf), page: p }),
);
setPageState(p);
setAccountRaw(PAGE_KEY, p);
// The YouTube-search sub-view and the channel page ride in history.state, so Back/Forward
// restores or clears them to match the entry we landed on.
setYtSearch((e.state?._yt as string) ?? null);
// The YouTube search is read from the address the browser restored, so Back/Forward opens or
// clears it to match the entry we landed on. One landed on without it has ended: a Forward back
// onto it is not asked for, and an API search waits for a press.
// A channel page opened from its results stands over it: its entry carries the search's mark
// (its address does not), and the search stays under it — closing a player over that channel
// lands there, and is no leaving of the search.
const here = new URLSearchParams(window.location.search);
const under = e.state?._chan && typeof e.state._yt === "string" ? e.state._yt : null;
const landed = p === "feed" ? (ytSearchFrom(here) ?? under) : null;
setYtSearch(landed);
if (landed == null) setYtAsked(null);
setYtCountState(ytCountFrom(here));
// The channel page rides in history.state._chan, with a ?chan URL fallback for a fresh bookmark
// entry (URL-only, no _chan) — reading e.state alone would wrongly close the channel when a
// popstate lands here (e.g. after an overlay's programmatic history.back()). channelViewFrom
@@ -285,12 +377,26 @@ export function NavigationProvider({ children }: { children: ReactNode }) {
}, [mountPage]);
const state = useMemo<NavigationState>(
() => ({ page, channelView, ytSearch }),
[page, channelView, ytSearch],
() => ({
page,
channelView,
ytSearch,
ytCount,
ytSearchAsked: ytSearch != null && ytAsked === ytSearch,
}),
[page, channelView, ytSearch, ytCount, ytAsked],
);
const actions = useMemo<NavigationActions>(
() => ({ setPage, openChannel, closeChannel, enterYtSearch, exitYtSearch }),
[setPage, openChannel, closeChannel, enterYtSearch, exitYtSearch],
() => ({
setPage,
openChannel,
closeChannel,
enterYtSearch,
exitYtSearch,
askYtSearch,
setYtCount,
}),
[setPage, openChannel, closeChannel, enterYtSearch, exitYtSearch, askYtSearch, setYtCount],
);
return (
@@ -0,0 +1,320 @@
// @vitest-environment jsdom
//
// The live YouTube search in the address: sent from the search box it gets its own entry naming the
// term (and its count), a reload or a link opens it again, Back/Forward read it from the address the
// browser restored — and only a search asked for in this document counts as asked (an API search
// reopened any other way waits for a press, Feed's part).
import { describe, it, expect, afterEach, beforeEach, vi } from "vitest";
import { renderHook, act, cleanup } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactNode } from "react";
vi.mock("react-i18next", async (importOriginal) => {
const actual = await importOriginal<typeof import("react-i18next")>();
return {
...actual,
useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en" } }),
};
});
import { NavigationProvider } from "./NavigationProvider";
import { useNavigation, useNavigationActions } from "./navigationContext";
import { qk } from "../../lib/queryKeys";
import { claimLocalData } from "../../lib/storage";
let qc = new QueryClient();
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={qc}>
<NavigationProvider>{children}</NavigationProvider>
</QueryClientProvider>
);
const render = () =>
renderHook(() => ({ ...useNavigation(), ...useNavigationActions() }), { wrapper });
const search = () => new URLSearchParams(window.location.search);
/** No entry of this document under the current one (a bookmark opened in a new tab). */
function stubNoEntryBelow() {
Object.defineProperty(window, "navigation", {
configurable: true,
value: {
currentEntry: { index: 1 },
entries: () => [{ sameDocument: false }, { sameDocument: true }],
},
});
}
beforeEach(() => {
qc = new QueryClient();
qc.setQueryData(qk.me(), { id: 1, role: "admin", plex_enabled: true });
localStorage.clear();
claimLocalData(1);
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&q=lofi");
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
Reflect.deleteProperty(window, "navigation");
});
describe("NavigationProvider · the YouTube search in the address", () => {
it("names a search sent from the box on an entry of its own, over the feed's", () => {
const { result } = render();
const depth = window.history.length;
act(() => result.current.enterYtSearch("lofi"));
expect(window.history.length).toBe(depth + 1);
expect(search().get("yt")).toBe("lofi");
expect(search().get("q")).toBe("lofi"); // the feed's own keys stay
expect(search().get("ytn")).toBeNull(); // the default count is left out
expect(result.current.ytSearch).toBe("lofi");
expect(result.current.ytSearchAsked).toBe(true);
});
it("refines the search on screen in place, at the count it shows", () => {
const { result } = render();
act(() => result.current.enterYtSearch("lofi"));
act(() => result.current.setYtCount(60));
expect(search().get("ytn")).toBe("60");
const depth = window.history.length;
act(() => result.current.enterYtSearch("lofi beats"));
expect(window.history.length).toBe(depth);
expect(search().get("yt")).toBe("lofi beats");
expect(search().get("ytn")).toBe("60");
expect(result.current.ytCount).toBe(60);
});
it("a new search starts at the default count", () => {
const { result } = render();
act(() => result.current.enterYtSearch("lofi"));
act(() => result.current.setYtCount(40));
stubNoEntryBelow(); // left in place, so the next search is a new entry
vi.spyOn(window.history, "back").mockImplementation(() => {});
act(() => result.current.exitYtSearch());
act(() => result.current.enterYtSearch("jazz"));
expect(result.current.ytCount).toBe(20);
expect(search().get("ytn")).toBeNull();
});
it("writes the count, and clears it back at the default", () => {
const { result } = render();
act(() => result.current.enterYtSearch("lofi"));
act(() => result.current.setYtCount(100));
expect(search().get("ytn")).toBe("100");
act(() => result.current.setYtCount(20));
expect(search().get("ytn")).toBeNull();
});
it("reopens the search a reload or a link names, not as asked", () => {
window.history.replaceState(null, "", "/?page=feed&yt=lofi&ytn=40");
const { result } = render();
expect(result.current.ytSearch).toBe("lofi");
expect(result.current.ytCount).toBe(40);
expect(result.current.ytSearchAsked).toBe(false);
expect(search().get("yt")).toBe("lofi"); // the mount's own stamp keeps it
act(() => result.current.askYtSearch());
expect(result.current.ytSearchAsked).toBe(true);
});
it("refines a search a link opened in place too, at the count it shows", () => {
window.history.replaceState(null, "", "/?page=feed&yt=lofi&ytn=40");
const { result } = render();
const depth = window.history.length;
act(() => result.current.enterYtSearch("jazz"));
expect(window.history.length).toBe(depth);
expect([search().get("yt"), search().get("ytn")]).toEqual(["jazz", "40"]);
});
it("Back onto an entry whose address alone names the search reopens it", () => {
const { result } = render();
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&yt=lofi");
act(() => {
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
});
expect(result.current.ytSearch).toBe("lofi");
});
it("keeps the search mark of an entry the reload started from", () => {
window.history.replaceState({ sfPage: "feed", _yt: "lofi" }, "", "/?page=feed&yt=lofi");
render();
expect(window.history.state?._yt).toBe("lofi");
});
it("marks the entry of a search the address opened (a reload, a link)", () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&yt=lofi");
render();
expect(window.history.state?._yt).toBe("lofi");
});
it("drops an older build's search mark the address does not name", () => {
window.history.replaceState(
{ sfPage: "feed", _yt: "lofi", _ytScrape: true },
"",
"/?page=feed",
);
const { result } = render();
expect(result.current.ytSearch).toBeNull();
expect(window.history.state?._yt).toBeUndefined();
expect(window.history.state?._ytScrape).toBeUndefined();
});
it("names no search under another page", () => {
window.history.replaceState(null, "", "/?page=plex&yt=lofi");
const { result } = render();
expect(result.current.page).toBe("plex");
expect(result.current.ytSearch).toBeNull();
expect(search().get("yt")).toBeNull();
});
it("Back/Forward read the search from the address the browser restored, not as asked", () => {
const { result } = render();
act(() => result.current.enterYtSearch("lofi"));
window.history.replaceState({ sfPage: "feed", _yt: "jazz" }, "", "/?page=feed&yt=jazz&ytn=60");
act(() => {
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
});
expect(result.current.ytSearch).toBe("jazz");
expect(result.current.ytCount).toBe(60);
expect(result.current.ytSearchAsked).toBe(false);
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&q=lofi");
act(() => {
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
});
expect(result.current.ytSearch).toBeNull();
});
it("leaving a search with no entry of this document below clears it from the address", () => {
window.history.replaceState(null, "", "/?page=feed&yt=lofi&ytn=40");
const { result } = render();
stubNoEntryBelow();
const back = vi.spyOn(window.history, "back").mockImplementation(() => {});
act(() => result.current.exitYtSearch());
expect(back).not.toHaveBeenCalled();
expect(result.current.ytSearch).toBeNull();
expect(search().get("yt")).toBeNull();
expect(search().get("ytn")).toBeNull();
});
it("a search left by Back and reached again by Forward is not asked for", () => {
const { result } = render();
act(() => result.current.enterYtSearch("lofi"));
expect(result.current.ytSearchAsked).toBe(true);
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&q=lofi");
act(() => {
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
});
window.history.replaceState({ sfPage: "feed", _yt: "lofi" }, "", "/?page=feed&yt=lofi");
act(() => {
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
});
expect(result.current.ytSearch).toBe("lofi");
expect(result.current.ytSearchAsked).toBe(false);
});
it("a search left in place is not asked for when it is opened again by a link", () => {
window.history.replaceState(null, "", "/?page=feed&yt=lofi");
const { result } = render();
act(() => result.current.askYtSearch());
stubNoEntryBelow();
act(() => result.current.exitYtSearch());
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&yt=lofi");
act(() => {
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
});
expect(result.current.ytSearchAsked).toBe(false);
});
it("the Feed press over a channel opened from the search opens the plain feed", () => {
const { result } = render();
act(() => result.current.enterYtSearch("lofi"));
act(() => result.current.openChannel("UC1"));
act(() => result.current.setPage("feed"));
expect(result.current.channelView).toBeNull();
expect(result.current.ytSearch).toBeNull();
expect(search().get("yt")).toBeNull();
});
it("the Feed press on the search itself opens the plain feed, as over a channel", () => {
const { result } = render();
act(() => result.current.enterYtSearch("lofi"));
const depth = window.history.length;
act(() => result.current.setPage("feed"));
expect(result.current.ytSearch).toBeNull();
expect(search().get("yt")).toBeNull();
expect(window.history.length).toBe(depth + 1); // its own entry: Back returns to the search
});
it("the Feed press on the search keeps the feed's own view in the address", () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&show=all&sort=oldest");
const { result } = render();
act(() => result.current.enterYtSearch("lofi"));
act(() => result.current.setPage("feed"));
expect(search().get("yt")).toBeNull();
expect([search().get("show"), search().get("sort")]).toEqual(["all", "oldest"]);
});
it("a search sent from the box is left by a step back off its own entry", () => {
const { result } = render();
act(() => result.current.enterYtSearch("lofi"));
const back = vi.spyOn(window.history, "back").mockImplementation(() => {});
act(() => result.current.exitYtSearch());
expect(back).toHaveBeenCalledTimes(1);
});
it("a search a link opened is left in place, not by a step back off the document", () => {
window.history.replaceState(null, "", "/?page=feed&yt=lofi");
const { result } = render();
const back = vi.spyOn(window.history, "back");
act(() => result.current.exitYtSearch());
expect(back).not.toHaveBeenCalled();
expect(result.current.ytSearch).toBeNull();
expect(search().get("yt")).toBeNull();
});
it("a landing on a channel opened from the search (an overlay over it closing) keeps the search", () => {
const { result } = render();
act(() => result.current.enterYtSearch("lofi"));
act(() => result.current.openChannel("UC1"));
// A player over the channel closed: the step back lands on the channel's own entry.
act(() => {
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
});
expect(result.current.ytSearch).toBe("lofi");
expect(result.current.ytSearchAsked).toBe(true);
// Back off the channel: the search it stood over is still the one asked for.
window.history.replaceState({ sfPage: "feed", _yt: "lofi" }, "", "/?page=feed&yt=lofi");
act(() => {
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
});
expect(result.current.ytSearchAsked).toBe(true);
});
it("a landing on a channel opened from a search the address opened keeps the search", () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed&yt=lofi");
const { result } = render();
act(() => result.current.openChannel("UC1"));
act(() => {
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
});
expect(result.current.ytSearch).toBe("lofi");
});
it("a channel closed in place over the search names the search again", () => {
const { result } = render();
act(() => result.current.enterYtSearch("lofi"));
act(() => result.current.setYtCount(40));
act(() => result.current.openChannel("UC1"));
expect(search().get("yt")).toBeNull();
stubNoEntryBelow();
act(() => result.current.closeChannel());
expect(result.current.ytSearch).toBe("lofi");
expect([search().get("yt"), search().get("ytn")]).toEqual(["lofi", "40"]);
});
it("a page switch takes the search off the address", () => {
const { result } = render();
act(() => result.current.enterYtSearch("lofi"));
act(() => result.current.setPage("home"));
expect(result.current.ytSearch).toBeNull();
expect(search().get("yt")).toBeNull();
});
});
@@ -0,0 +1,111 @@
// @vitest-environment jsdom
//
// The channel page opens over any page, and its address names the channel alone (the owner, 2026-10-05:
// it used to carry the feed's filters, naming a sort the channel did not show). The page under it is
// still mounted — its store lives at the root — and a change in it while the channel stands over it
// (a background refetch, the header search) must not write its keys onto the channel's address. Closing
// the channel brings them back. The real provider and the real stores; only the network is absent.
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { act, cleanup, render, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useEffect } from "react";
vi.mock("react-i18next", async (importOriginal) => ({
...(await importOriginal<typeof import("react-i18next")>()),
useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en" } }),
}));
import { NavigationProvider } from "./NavigationProvider";
import { ModuleStores } from "./ModuleStores";
import { useNavigationActions, type NavigationActions } from "./navigationContext";
import { useFeedFilters, useFeedFiltersActions } from "../../modules/feed";
import { usePlexActions } from "../../modules/plex";
import { useChannelsActions } from "../../modules/channels";
import { useFilesActions } from "../../modules/files";
import { usePlaylistsActions } from "../../modules/playlists";
import { claimLocalData } from "../../lib/storage";
type Probe = {
nav: NavigationActions;
change: Record<string, () => void>;
};
const probe: { current: Probe | null } = { current: null };
function Probe() {
const nav = useNavigationActions();
const filters = useFeedFilters();
const { setFilters } = useFeedFiltersActions();
const plex = usePlexActions();
const channels = useChannelsActions();
const files = useFilesActions();
const playlists = usePlaylistsActions();
// Handed out after each render (an effect, not the render itself, may write outside it).
useEffect(() => {
probe.current = {
nav,
change: {
feed: () => setFilters({ ...filters, sort: "oldest" }),
plex: () => plex.setScope("movie"),
channels: () => channels.setView("hidden"),
files: () => files.setView({ kind: "folder", id: 3 }),
playlists: () => playlists.setSelectedId(5),
"plex search": () => plex.setQ("poirot"),
"channels search": () => channels.setSearch("tom"),
"files search": () => files.setSearch("notes"),
"playlists search": () => playlists.setSearch("jazz"),
},
};
});
return null;
}
// What each change above writes, once its page is what the address shows: [page, key, value]. A
// search is written once the typing pauses.
const WRITTEN: Record<string, [string, string, string]> = {
feed: ["feed", "sort", "oldest"],
plex: ["plex", "pscope", "movie"],
channels: ["channels", "ctab", "hidden"],
files: ["files", "folder", "3"],
playlists: ["playlists", "pl", "5"],
"plex search": ["plex", "pq", "poirot"],
"channels search": ["channels", "cq", "tom"],
"files search": ["files", "fq", "notes"],
"playlists search": ["playlists", "plq", "jazz"],
};
const PAUSE = () => new Promise((r) => setTimeout(r, 400));
beforeEach(() => {
localStorage.clear();
claimLocalData(3);
});
afterEach(() => {
cleanup();
window.history.replaceState(null, "", "/");
});
const search = () => new URLSearchParams(window.location.search);
describe.each(Object.keys(WRITTEN))("a channel page over %s", (change) => {
it("keeps the page's keys off its address, and they come back when it closes", async () => {
const [page, key, value] = WRITTEN[change]!;
// The page named even for the feed: a bare address opens on Home (the account's default).
window.history.replaceState({ sfPage: page }, "", `/?page=${page}`);
render(
<QueryClientProvider client={new QueryClient()}>
<NavigationProvider>
<ModuleStores>
<Probe />
</ModuleStores>
</NavigationProvider>
</QueryClientProvider>,
);
act(() => probe.current!.nav.openChannel("UC1", "One"));
act(() => probe.current!.change[change]!());
await act(PAUSE);
expect(search().get(key)).toBeNull();
expect(search().get("chan")).toBe("UC1");
act(() => probe.current!.nav.closeChannel());
await waitFor(() => expect(search().get("chan")).toBeNull());
await waitFor(() => expect(search().get(key)).toBe(value));
});
});
@@ -48,6 +48,21 @@ export const REGISTERED_PAGES: readonly Page[] = ALL.map((m) => m.id);
const BY_ID = Object.fromEntries(ALL.map((m) => [m.id, m])) as Record<Page, ModuleDef>;
// Every module's address-bar keys, and those of every module but `page`: what a page switch clears and
// what a page opens without (NavigationProvider). Derived from the definitions, so a new module's keys
// are cleared the day it declares them.
const ALL_URL_KEYS: readonly string[] = ALL.flatMap((m) => m.urlKeys);
export function moduleUrlKeys(): readonly string[] {
return ALL_URL_KEYS;
}
/** Every module's address-bar keys that carry typed text — what the client log keeps out (main.tsx). */
export function typedUrlKeys(): readonly string[] {
return ALL.flatMap((m) => m.typedUrlKeys ?? []);
}
export function foreignUrlKeys(page: Page): readonly string[] {
return ALL.filter((m) => m.id !== page).flatMap((m) => m.urlKeys);
}
// Look up a module's definition by page id (every Page is covered, incl. settings).
export function moduleDef(id: Page): ModuleDef {
return BY_ID[id];
@@ -1,5 +1,6 @@
import { createContext, useContext } from "react";
import type { Page } from "../../lib/urlState";
import { DEFAULT_YT_COUNT } from "../../lib/ytSearchUrlState";
import type { ChannelView } from "./navigationInit";
// The navigation contexts + their hooks, split out of NavigationProvider so that file exports only
@@ -15,8 +16,13 @@ export interface NavigationState {
page: Page;
/** The open channel page (null = none). Overlays `page`; rides in history.state._chan. */
channelView: ChannelView | null;
/** Live YouTube search term (null = normal feed). A feed sub-view; rides in history.state._yt. */
/** Live YouTube search term (null = normal feed). A feed sub-view, named in the address (`yt`). */
ytSearch: string | null;
/** How many results the search gathers (`ytn`). */
ytCount: number;
/** The search on screen was asked for in this document (sent from the search box, or run again by
* a press), not only reopened by a reload, a link or Back. An API search runs only when asked. */
ytSearchAsked: boolean;
}
export interface NavigationActions {
@@ -33,12 +39,17 @@ export interface NavigationActions {
closeChannel: () => void;
enterYtSearch: (q: string) => void;
exitYtSearch: () => void;
/** Run the search on screen: the "Search YouTube" press. */
askYtSearch: () => void;
setYtCount: (n: number) => void;
}
export const NavigationStateContext = createContext<NavigationState>({
page: "feed",
channelView: null,
ytSearch: null,
ytCount: DEFAULT_YT_COUNT,
ytSearchAsked: false,
});
export const NavigationActionsContext = createContext<NavigationActions>({
setPage: () => {},
@@ -46,6 +57,8 @@ export const NavigationActionsContext = createContext<NavigationActions>({
closeChannel: () => {},
enterYtSearch: () => {},
exitYtSearch: () => {},
askYtSearch: () => {},
setYtCount: () => {},
});
export function useNavigation(): NavigationState {
@@ -0,0 +1,9 @@
import type { Page } from "../../lib/urlState";
import type { NavigationState } from "./navigationContext";
/** The page whose own keys the address bar carries: none while the channel page stands over it, so
* every module store writes its keys (`useUrlMirror`) only while its page is what the screen shows.
* A plain function beside the context, not a hook in it: the stores' tests mock that module. */
export function urlPage(nav: Pick<NavigationState, "page" | "channelView">): Page | null {
return nav.channelView ? null : nav.page;
}
@@ -0,0 +1,40 @@
import { lazy, Suspense, useState } from "react";
import { useTranslation } from "react-i18next";
import { useQueryClient } from "@tanstack/react-query";
import { type Video, type VideoStatus } from "../../lib/api";
import { qk } from "../../lib/queryKeys";
import { notifyActionError } from "../../lib/actionErrors";
import { useStableCallback } from "../../lib/useLatest";
import { writeVideoState } from "../video/videoWrites";
import { useOpenLinkedPlayer } from "./useOpenLinkedPlayer";
const PlayerModal = lazy(() => import("./PlayerModal"));
/** The shell's player, for an address that names one over a page that hosts none of its own (the
* channel manager, where the watched-videos dialog played it; any page a link names): the video
* alone. Decided at boot, once — `hosted` is whether the page on screen then opens it itself. */
export function LinkedPlayer({ hosted }: { hosted: boolean }) {
const { t } = useTranslation();
const qc = useQueryClient();
const [own] = useState(!hosted);
const [video, setVideo] = useState<Video | null>(null);
useOpenLinkedPlayer(
own,
() => undefined,
(v) => setVideo(v),
);
const onState = useStableCallback((id: string, status: VideoStatus) => {
const write = writeVideoState(qc, id, status);
write
.then(() => qc.invalidateQueries({ queryKey: qk.feed() }))
.catch((e: unknown) => notifyActionError(e, t("errors.writeFailed.videoState")));
return write;
});
const close = useStableCallback(() => setVideo(null));
if (!video) return null;
return (
<Suspense fallback={null}>
<PlayerModal video={video} startAt={null} onClose={close} onState={onState} />
</Suspense>
);
}
@@ -111,6 +111,7 @@ function renderModal(ui: ReactNode) {
afterEach(() => {
cleanup();
vi.restoreAllMocks();
window.history.replaceState(null, "", "/");
started.length = 0;
loaded.length = 0;
seeks.length = 0;
+32 -3
View File
@@ -68,6 +68,7 @@ import {
import { canFullscreenElements, fullscreenElement } from "../../lib/fullscreen";
import { dispatch, isActivationTarget, setScopeCoveredProbe, useKeyScope } from "../../lib/keymap";
import { useBackToClose } from "../../lib/history";
import { linkedPlayer, playerParamUpdates, type PlayerPanelTab } from "../../lib/playerUrlState";
import ChannelNameLink from "../video/ChannelNameLink";
import Toaster from "../../components/ui/Toaster";
import { useOverlayOrder } from "../../components/ui/overlayOrder";
@@ -222,8 +223,6 @@ export default function PlayerModal({
const { openChannel } = useNavigationActions();
const qc = useQueryClient();
const { ref: descFadeRef, style: descFadeStyle } = useScrollFade();
// Browser/mouse Back closes the player instead of leaving the page.
useBackToClose(onClose);
// Freeze the launch queue: the player steps through the SAME filtered + sorted list it was
// opened with, for its whole session. The live feed refetches and reorders/drops items under
// us — e.g. auto-marking each video watched near its end removes it from a filtered feed — which
@@ -277,6 +276,25 @@ export default function PlayerModal({
setRelatedOf(active.id);
setRelated(null);
}
// An address that names the item this player opens on (a reload, a bookmark) names its view too: the
// related video playing in place over it and the panel's tab come back with it. Read once.
const [linked] = useState(() => {
const here = linkedPlayer();
return here && here.watch === video.id ? here : null;
});
const linkedRelated = useQuery({
queryKey: qk.videoRow(linked?.related ?? ""),
queryFn: () => api.videoRow(linked!.related!),
enabled: !!linked?.related,
retry: false,
});
const [relatedAdopted, setRelatedAdopted] = useState(false);
if (!relatedAdopted && linkedRelated.data) {
setRelatedAdopted(true);
// Only over the item it was named with: a step of the queue before it arrived left that one.
if (active.id === linked?.watch && !related)
setRelated({ video: linkedRelated.data, startAt: null });
}
const subject = related?.video ?? active;
const subjectResume = related
? (related.startAt ?? related.video.position_seconds ?? 0)
@@ -753,7 +771,7 @@ export default function PlayerModal({
// take the side panel's place of the description, a tab beside it; stacked, a drawer over the video
// opened from a button beside the ⓘ. The list is the OPENED video's: one played from it leaves the
// list in place, to try the next one (the owner's pick).
const [panelTab, setPanelTab] = useState<"description" | "related">("description");
const [panelTab, setPanelTab] = useState<PlayerPanelTab>(linked?.panel ?? "description");
const [relatedOpen, setRelatedOpen] = useState(false);
// The drawer is the stacked layout's: going wide while it is open, the list moves into the panel's
// tab instead. Left open, it reopened unasked when the window narrowed again.
@@ -762,6 +780,17 @@ export default function PlayerModal({
setPanelTab("related");
}
const panelTabs = useTabPanel();
// Browser/mouse Back closes the player instead of leaving the page. Its entry's address names what
// it plays (the queue's item, a related one over it) and the wide panel's tab, so a reload or a
// bookmark reopens it as it is; the page's own entry under it never carries them.
useBackToClose(
onClose,
playerParamUpdates({
watch: active.id,
related: related?.video.id ?? null,
panel: wide ? panelTab : "description",
}),
);
// Turned off on this instance (a daily limit of 0): no tab, no button — nothing that could only
// be refused.
const relatedOn = useMe().related_enabled;
@@ -0,0 +1,196 @@
// @vitest-environment jsdom
//
// The URL is the view: the YouTube player names what it plays in its own history entry — the item of
// the queue, a related video played in place over it, the wide panel's tab — so a reload or a bookmark
// reopens it as it was, and Back lands on the page's address without it. Its own file: the overlay
// history is module state, and these read the address the closed players of other tests step back over.
//
// `window.YT` is a fake installed before the player's API loader first runs (see PlayerModal.dom.test).
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
vi.mock("react-i18next", async (importOriginal) => ({
...(await importOriginal<typeof import("react-i18next")>()),
useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en" } }),
}));
vi.mock("../navigation/navigationContext", () => ({
useNavigationActions: () => ({ openChannel: vi.fn() }),
}));
vi.mock("../video/AddToPlaylist", () => ({ default: () => null }));
vi.mock("../downloads/DownloadButton", () => ({ default: () => null }));
import PlayerModal from "./PlayerModal";
import { api, type Me, type Video } from "../../lib/api";
import { qk } from "../../lib/queryKeys";
beforeAll(() => {
class Stub {
observe() {}
unobserve() {}
disconnect() {}
takeRecords() {
return [];
}
}
globalThis.ResizeObserver ??= Stub as unknown as typeof ResizeObserver;
globalThis.IntersectionObserver ??= Stub as unknown as typeof IntersectionObserver;
});
const started: { videoId: string; start: number | undefined }[] = [];
let playerEvents: { onReady?: () => void } = {};
const fakePlayer = new Proxy(
{ getCurrentTime: () => 0, getDuration: () => 3000, getVideoData: () => null },
{ get: (t, k) => (k in t ? t[k as keyof typeof t] : k === "then" ? undefined : () => undefined) },
);
window.YT = {
Player: function (
_el: unknown,
opts: { videoId: string; playerVars: { start?: number }; events?: typeof playerEvents },
) {
started.push({ videoId: opts.videoId, start: opts.playerVars.start });
playerEvents = opts.events ?? {};
return fakePlayer;
} as never,
};
const lastStart = () => started[started.length - 1];
const vid = (id: string, position_seconds = 0): Video =>
({
id,
title: `Video ${id}`,
channel_id: "UCx",
channel_title: "Channel",
status: "new",
position_seconds,
duration_seconds: 3000,
watch_url: `https://www.youtube.com/watch?v=${id}`,
}) as unknown as Video;
const related = (id: string, position_seconds = 0) => ({
...vid(id, position_seconds),
followed: false,
});
// The wide layout (the side panel with its tabs): jsdom has no matchMedia, so one is put in.
function wideWindow() {
window.matchMedia = ((q: string) => ({
matches: q === "(min-width: 1280px)",
media: q,
addEventListener: () => {},
removeEventListener: () => {},
})) as unknown as typeof window.matchMedia;
}
function renderModal(video: Video, queue: Video[]) {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
qc.setQueryData(qk.me(), { related_enabled: true } as Me);
return render(
<QueryClientProvider client={qc}>
<PlayerModal
video={video}
queue={queue}
onClose={() => {}}
onState={() => Promise.resolve()}
/>
</QueryClientProvider>,
);
}
// A closed player steps back over its entry a task later (jsdom's back(), like a browser's).
async function closeAndLand(unmount: () => void) {
const landed = new Promise((r) => window.addEventListener("popstate", r, { once: true }));
unmount();
await act(() => landed);
}
const here = () => new URLSearchParams(window.location.search);
beforeEach(() => {
vi.spyOn(api, "videoDetail").mockReturnValue(new Promise(() => {}));
vi.spyOn(api, "related").mockResolvedValue({
items: [related("rel1"), related("rel2", 120)],
has_more: false,
next_cursor: null,
});
});
afterEach(() => {
vi.restoreAllMocks();
delete (window as { matchMedia?: unknown }).matchMedia;
started.length = 0;
});
describe("the player's address", () => {
it("names the item playing now in its own entry, a step of the queue too", async () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?q=talks");
const r = renderModal(vid("A"), [vid("A"), vid("B")]);
await waitFor(() => expect(here().get("watch")).toBe("A"));
expect(here().get("q")).toBe("talks");
fireEvent.click(screen.getAllByRole("button", { name: "player.next" })[0]!);
await waitFor(() => expect(here().get("watch")).toBe("B"));
await closeAndLand(r.unmount);
expect(window.location.search).toBe("?q=talks");
});
it("wide: names the related video playing over it and the panel's tab, and Back drops it", async () => {
wideWindow();
window.history.replaceState({ sfPage: "feed" }, "", "/");
const r = renderModal(vid("A", 40), [vid("A", 40)]);
act(() => playerEvents.onReady?.());
fireEvent.click(screen.getByRole("tab", { name: "player.related.title" }));
await waitFor(() => expect(here().get("wtab")).toBe("related"));
const rows = await screen.findAllByRole("link", { name: "Video rel2" });
fireEvent.click(rows.find((a) => a.hasAttribute("data-nav-open"))!);
await waitFor(() => expect(here().get("wrel")).toBe("rel2"));
expect(here().get("watch")).toBe("A");
fireEvent.click(screen.getByRole("button", { name: "player.back" }));
await waitFor(() => expect(here().has("wrel")).toBe(false));
expect(here().get("watch")).toBe("A");
await closeAndLand(r.unmount);
expect(window.location.search).toBe("");
});
it("wide: a link's related video and panel tab come back over the item it names", async () => {
wideWindow();
window.history.replaceState({ sfPage: "feed" }, "", "/?watch=A&wrel=rel2&wtab=related");
const row = vi.spyOn(api, "videoRow").mockResolvedValue(vid("rel2", 120));
const r = renderModal(vid("A", 40), [vid("A", 40)]);
await waitFor(() => expect(lastStart()).toEqual({ videoId: "rel2", start: 120 }));
expect(row).toHaveBeenCalledWith("rel2");
const tab = screen.getByRole("tab", { name: "player.related.title" });
expect(tab.getAttribute("aria-selected")).toBe("true");
expect(screen.getByRole("button", { name: "player.back" })).toBeTruthy();
expect(here().get("wrel")).toBe("rel2");
await closeAndLand(r.unmount);
// The entry the link opened at named the player; once the player is gone, so is its name.
expect(window.location.search).toBe("");
});
it("a link's related video that arrives after the queue stepped on stays off the next item", async () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?watch=A&wrel=rel2");
let arrive: (v: Video) => void = () => {};
vi.spyOn(api, "videoRow").mockReturnValue(new Promise<Video>((r) => (arrive = r)));
const r = renderModal(vid("A"), [vid("A"), vid("B")]);
fireEvent.click(screen.getAllByRole("button", { name: "player.next" })[0]!);
await waitFor(() => expect(here().get("watch")).toBe("B"));
await act(async () => {
arrive(vid("rel2", 120));
await new Promise((r) => setTimeout(r, 50)); // the query hands its answer on a tick later
});
expect(screen.getByRole("heading", { name: "Video B" })).toBeTruthy();
expect(here().has("wrel")).toBe(false);
await closeAndLand(r.unmount);
});
it("wide: a link naming another item brings none of its view", async () => {
wideWindow();
window.history.replaceState({ sfPage: "feed" }, "", "/?watch=Z&wrel=rel2&wtab=related");
const row = vi.spyOn(api, "videoRow").mockResolvedValue(vid("rel2", 120));
const r = renderModal(vid("A", 40), [vid("A", 40)]);
await waitFor(() => expect(here().get("watch")).toBe("A"));
expect(row).not.toHaveBeenCalled();
expect(here().has("wrel")).toBe(false);
expect(here().has("wtab")).toBe(false);
expect(lastStart()?.videoId).toBe("A");
await closeAndLand(r.unmount);
});
});
@@ -0,0 +1,181 @@
// @vitest-environment jsdom
//
// A reload or a bookmark of the YouTube player reopens it: the page that hosts it opens it once its list
// is in — from the list, so it plays on through it, or alone from the catalog — and a page that hosts
// none gets the shell's, the video alone. A video the catalog no longer has is said, not swallowed.
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, render, renderHook, screen, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactNode } from "react";
vi.mock("react-i18next", async (importOriginal) => ({
...(await importOriginal<typeof import("react-i18next")>()),
useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en" } }),
}));
vi.mock("../../lib/actionErrors", () => ({ notifyActionError: vi.fn() }));
// The player itself is not what is under test: it shows what it was opened on.
vi.mock("./PlayerModal", () => ({
default: ({ video, queue }: { video: Video; queue?: Video[] }) => (
<p>
playing {video.id} {queue ? "in a list" : "alone"}
</p>
),
}));
import { useOpenLinkedPlayer } from "./useOpenLinkedPlayer";
import { LinkedPlayer } from "./LinkedPlayer";
import { api, type Video } from "../../lib/api";
import { notifyActionError } from "../../lib/actionErrors";
import { qk } from "../../lib/queryKeys";
const vid = (id: string) => ({ id, title: id }) as unknown as Video;
function wrapper({ children }: { children: ReactNode }) {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
}
afterEach(() => {
cleanup();
vi.restoreAllMocks();
vi.mocked(notifyActionError).mockClear();
window.history.replaceState(null, "", "/");
});
describe("useOpenLinkedPlayer", () => {
it("opens the item from the host's list once the list is in, and only once", async () => {
window.history.replaceState(null, "", "/?watch=B");
const row = vi.spyOn(api, "videoRow");
const open = vi.fn();
const list = [vid("A"), vid("B")];
const { rerender } = renderHook(
({ ready, rows }) => useOpenLinkedPlayer(ready, (id) => rows.find((v) => v.id === id), open),
{ wrapper, initialProps: { ready: false, rows: list } },
);
expect(open).not.toHaveBeenCalled();
rerender({ ready: true, rows: list });
await waitFor(() => expect(open).toHaveBeenCalledWith(list[1], true));
// The list refetched (new rows for the same videos): the player it opened is not opened again.
rerender({ ready: true, rows: [vid("A"), vid("B")] });
expect(open).toHaveBeenCalledTimes(1);
expect(row).not.toHaveBeenCalled();
});
it("opens an item the list does not hold alone, its row from the catalog", async () => {
window.history.replaceState(null, "", "/?watch=Z");
vi.spyOn(api, "videoRow").mockResolvedValue(vid("Z"));
const open = vi.fn();
renderHook(() => useOpenLinkedPlayer(true, () => undefined, open), { wrapper });
await waitFor(() => expect(open).toHaveBeenCalledWith(vid("Z"), false));
});
it("says so when the catalog no longer has it", async () => {
window.history.replaceState(null, "", "/?watch=Z");
const gone = new Error("not found");
vi.spyOn(api, "videoRow").mockRejectedValue(gone);
const open = vi.fn();
renderHook(() => useOpenLinkedPlayer(true, () => undefined, open), { wrapper });
await waitFor(() =>
expect(notifyActionError).toHaveBeenCalledWith(gone, "player.linkedFailed"),
);
expect(open).not.toHaveBeenCalled();
// Said once: the address no longer names it, so a reload or a copied link does not say it again.
expect(new URLSearchParams(window.location.search).has("watch")).toBe(false);
});
it("leaves a player opened while the row was on its way alone, and its address", async () => {
window.history.replaceState(null, "", "/?watch=Z");
let answer: (v: Video) => void = () => {};
vi.spyOn(api, "videoRow").mockReturnValue(new Promise((r) => (answer = r)));
const open = vi.fn();
renderHook(() => useOpenLinkedPlayer(true, () => undefined, open), { wrapper });
// A card clicked meanwhile: its player names itself in the address.
window.history.replaceState(null, "", "/?watch=Y");
answer(vid("Z"));
await new Promise((r) => setTimeout(r, 20));
expect(open).not.toHaveBeenCalled();
expect(new URLSearchParams(window.location.search).get("watch")).toBe("Y");
});
it("does not clear the address of a player opened since when its catalog read fails", async () => {
window.history.replaceState(null, "", "/?watch=Z");
let refuse: (e: Error) => void = () => {};
vi.spyOn(api, "videoRow").mockReturnValue(new Promise((_, r) => (refuse = r)));
renderHook(() => useOpenLinkedPlayer(true, () => undefined, vi.fn()), { wrapper });
window.history.replaceState(null, "", "/?watch=Y");
refuse(new Error("not found"));
await new Promise((r) => setTimeout(r, 20));
expect(new URLSearchParams(window.location.search).get("watch")).toBe("Y");
});
it("given up over a moved list, keeps the address of a player opened since", async () => {
window.history.replaceState(null, "", "/?watch=Z");
const { rerender } = renderHook(
({ scope }) => useOpenLinkedPlayer(false, () => undefined, vi.fn(), scope),
{ wrapper, initialProps: { scope: 1 } },
);
window.history.replaceState(null, "", "/?watch=Y");
rerender({ scope: 2 });
await new Promise((r) => setTimeout(r, 20));
expect(new URLSearchParams(window.location.search).get("watch")).toBe("Y");
});
it("stops looking once it opened: the video leaving the list asks the catalog for nothing", async () => {
window.history.replaceState(null, "", "/?watch=B");
const row = vi.spyOn(api, "videoRow").mockResolvedValue(vid("B"));
const find = vi.fn((id: string) => (id === "B" ? vid("B") : undefined));
const { rerender } = renderHook(
({ rows }) => useOpenLinkedPlayer(true, rows ? find : () => undefined, vi.fn()),
{ wrapper, initialProps: { rows: true } },
);
await waitFor(() => expect(find).toHaveBeenCalled());
find.mockClear();
rerender({ rows: false });
rerender({ rows: true });
await new Promise((r) => setTimeout(r, 20));
expect(find).not.toHaveBeenCalled();
expect(row).not.toHaveBeenCalled();
});
it("opens nothing, and asks for nothing, for an address that names no player", async () => {
window.history.replaceState(null, "", "/?q=talks");
const row = vi.spyOn(api, "videoRow");
const open = vi.fn();
renderHook(() => useOpenLinkedPlayer(true, () => undefined, open), { wrapper });
await new Promise((r) => setTimeout(r, 20));
expect(open).not.toHaveBeenCalled();
expect(row).not.toHaveBeenCalled();
});
});
describe("the shell's LinkedPlayer", () => {
it("plays the video alone over a page that hosts no player", async () => {
window.history.replaceState(null, "", "/?page=channels&watch=Z");
vi.spyOn(api, "videoRow").mockResolvedValue(vid("Z"));
render(<LinkedPlayer hosted={false} />, { wrapper });
expect(await screen.findByText("playing Z alone")).toBeTruthy();
});
it("leaves it to a page that hosts its own, even once that page has fetched the row", async () => {
// The page plays it alone, from the catalog row it asked for: the same cache entry this one reads.
window.history.replaceState(null, "", "/?page=home&watch=Z");
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
qc.setQueryData(qk.videoRow("Z"), vid("Z"));
render(
<QueryClientProvider client={qc}>
<LinkedPlayer hosted />
</QueryClientProvider>,
);
await new Promise((r) => setTimeout(r, 20));
expect(screen.queryByText(/playing/)).toBeNull();
});
it("leaves it to a page that hosts its own", async () => {
window.history.replaceState(null, "", "/?watch=Z");
const row = vi.spyOn(api, "videoRow").mockResolvedValue(vid("Z"));
render(<LinkedPlayer hosted />, { wrapper });
await new Promise((r) => setTimeout(r, 20));
expect(row).not.toHaveBeenCalled();
expect(screen.queryByText(/playing/)).toBeNull();
});
});
@@ -0,0 +1,71 @@
import { useEffect, useEffectEvent, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useQuery } from "@tanstack/react-query";
import { api, type Video } from "../../lib/api";
import { qk } from "../../lib/queryKeys";
import { linkedPlayer, PLAYER_KEYS } from "../../lib/playerUrlState";
import { clearParams } from "../../lib/urlState";
import { notifyActionError } from "../../lib/actionErrors";
/** Opens the player an address names (a reload, a bookmark — lib/playerUrlState) on the page that
* hosts it, once: read as the host mounts, opened once its list is in (`ready`). From the list when the
* item is in it (`find`), so the player plays on through the list; else alone, its row fetched from
* the catalog. A row the catalog no longer has is said, not swallowed.
*
* `scope` names the list the address put it over (a playlist, a live search): when the host moves to
* another before it opened, the address under it named something else, and the player is given up —
* opened later, it would start over a list nobody linked, unasked. So it is when a player opened
* meanwhile (a card clicked while the row was on its way): the address names that one now. */
export function useOpenLinkedPlayer(
ready: boolean,
find: (id: string) => Video | undefined,
open: (video: Video, inList: boolean) => void,
scope: string | number | null = null,
): void {
const { t } = useTranslation();
const [linked] = useState(() => linkedPlayer()?.watch ?? null);
const [linkedScope] = useState(scope);
// Opened, said to be gone or given up, once. A ref for the effect (a StrictMode re-run of it must
// not open it twice); the state stops the lookup and the row fetch on screen after it.
const done = useRef(linked == null);
const [settled, setSettled] = useState(linked == null);
const moved = scope !== linkedScope;
const waiting = ready && !moved && !settled && linked != null;
const listed = waiting ? find(linked) : undefined;
const row = useQuery({
queryKey: qk.videoRow(linked ?? ""),
queryFn: () => api.videoRow(linked!),
enabled: waiting && !listed,
retry: false,
});
const openIt = useEffectEvent(open);
const failed = useEffectEvent((err: unknown) => {
notifyActionError(err, t("player.linkedFailed"));
clearParams(...PLAYER_KEYS);
});
useEffect(() => {
if (done.current) return;
const settle = () => {
done.current = true;
// State, not derived: a one-way decision taken as the list or the row arrives. Derived from
// `listed`, the lookup and the row fetch would come back whenever the video left the list.
setSettled(true);
};
// A player opened since names its own: this one is not wanted any more.
if (linkedPlayer()?.watch !== linked) return settle();
if (moved) {
// The address goes on naming it under the new list (a reload would open it there).
clearParams(...PLAYER_KEYS);
return settle();
}
// Not before the host is ready: the row's cache entry is shared, so another opener's fetch fills
// it here too (a disabled query still reads the cache) — the shell's player over a page that
// plays its own would open a second one.
if (!ready) return;
if (listed) openIt(listed, true);
else if (row.data) openIt(row.data, false);
else if (row.isError) failed(row.error);
else return;
settle();
}, [linked, moved, ready, listed, row.data, row.isError, row.error]);
}
@@ -48,8 +48,9 @@ describe("ChannelNameLink", () => {
it("is an anchor whose href opens this channel on the current page", () => {
const { link } = renderLink();
expect(link.tagName).toBe("A");
// The same URL openChannel pushes: the current page's query plus ?chan=<id>.
expect(link.getAttribute("href")).toBe(`/?page=feed&show=unwatched&chan=${CH}`);
// The same URL openChannel pushes: the current page plus ?chan=<id> — not the page's own keys,
// which named a view the channel does not show (`show=unwatched` here).
expect(link.getAttribute("href")).toBe(`/?page=feed&chan=${CH}`);
});
it("takes the in-app path on a plain left click, and suppresses the browser navigation", () => {
@@ -73,11 +74,16 @@ describe("ChannelNameLink", () => {
expect(onOpenInApp).not.toHaveBeenCalled();
});
it("does not lose the rest of the address bar", () => {
window.history.replaceState({}, "", "/?page=channels&q=abc");
// The address names only what the screen shows: the channel over the page, not the page's filters
// (a link's new tab once opened the channel under the feed's search and sort).
it("keeps the page and the shell's keys, and leaves the page's and another channel's behind", () => {
window.history.replaceState(
{},
"",
"/?page=channels&q=abc&ctab=hidden&chtab=about&m=signup#x=1",
);
const { link } = renderLink();
expect(link.getAttribute("href")).toContain("page=channels");
expect(link.getAttribute("href")).toContain("q=abc");
expect(link.getAttribute("href")).toBe(`/?page=channels&chan=${CH}&m=signup#x=1`);
});
it("gives a channel with no title yet an accessible name", () => {
@@ -1,15 +1,15 @@
import { forwardRef, type AnchorHTMLAttributes } from "react";
import { useTranslation } from "react-i18next";
import { isPlainLeftClick } from "../../lib/nav";
import { urlWithParams } from "../../lib/urlState";
import { channelUrl } from "../../lib/urlState";
// A channel name that is a REAL link. The player showed it as a `<button>`, so the browser's own
// gestures did nothing on it: middle-click and Ctrl/Cmd-click opened no tab, on a thing that looks
// exactly like a link (the YouTube icon right next to it IS an anchor and does open one). The video
// card's channel name had the same `<button>`, so it renders through here too.
//
// The href is the same URL `openChannel` pushes — `?chan=<id>` on the current page — so a new tab
// lands where the in-app navigation would have. A plain left click is still handled in-app, because
// The href is the same URL `openChannel` pushes (`channelUrl`: the channel over the current page,
// without the page's own keys) — so a new tab lands where the in-app navigation would have. A plain left click is still handled in-app, because
// the SPA path does more than navigate (the player has to close first and reclaim its own
// Back-to-close history entry; see lib/history.closeOverlaysThenNavigate).
type Props = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href" | "onClick" | "title"> & {
@@ -33,7 +33,7 @@ const ChannelNameLink = forwardRef<HTMLAnchorElement, Props>(function ChannelNam
<a
{...rest}
ref={ref}
href={urlWithParams({ chan: channelId })}
href={channelUrl(channelId)}
title={tooltip}
onClick={(e) => {
if (stopPropagation) e.stopPropagation();
+4 -1
View File
@@ -75,6 +75,9 @@
"clearNow": "Clear now",
"cleared_one": "Cleared {{count}} result",
"cleared_other": "Cleared {{count}} results",
"showHint": "How many results to fetch at a time — “Load more” pulls another batch of this size."
"showHint": "How many results to fetch at a time — “Load more” pulls another batch of this size.",
"notRunTitle": "Not searched yet",
"notRunBody": "A YouTube API search spends 100 units of the shared daily quota, so a reload, a link, Back or Forward doesn't start one by itself.",
"runAgain": "Search YouTube"
}
}
+2
View File
@@ -1,4 +1,6 @@
{
"linkedGone": "The file in the address is no longer in this list",
"linkedNotListed": "The file in the link isn't among the files listed here — search for it by name",
"navLabel": "Files",
"searchPlaceholder": "Search files…",
"count_one": "{{count}} item",
+6 -2
View File
@@ -6,11 +6,15 @@
"clearConfirmTitle": "Clear every notification?",
"clearConfirmBody": "Every notification here leaves the list, read or not. They don't come back.",
"markRead": "Mark read",
"unreadName": "{{name}}, unread",
"dismiss": "Dismiss",
"rowMenu": "Notification actions",
"menu": "Notifications actions",
"sectionSystem": "System",
"sectionActivity": "Activity",
"sectionNeedsYou_one": "Needs you · {{count}}",
"sectionNeedsYou_other": "Needs you · {{count}}",
"sectionRecent": "Recent",
"earlier_one": "Earlier ({{count}})",
"earlier_other": "Earlier ({{count}})",
"andMore_one": "and {{count}} more",
"andMore_other": "and {{count}} more",
"openScheduler": "Open Scheduler",
+1
View File
@@ -1,5 +1,6 @@
{
"loading": "Loading…",
"linkedFailed": "The video in the address could not be opened",
"backToOriginal": "Back to the original video",
"back": "Back",
"previous": "Previous",
+4 -1
View File
@@ -75,6 +75,9 @@
"clearNow": "Törlés most",
"cleared_one": "{{count}} találat törölve",
"cleared_other": "{{count}} találat törölve",
"showHint": "Hány találatot szerezzen egyszerre — a „Továbbiak betöltése” ennyivel tölt tovább."
"showHint": "Hány találatot szerezzen egyszerre — a „Továbbiak betöltése” ennyivel tölt tovább.",
"notRunTitle": "Ez a keresés még nem futott le",
"notRunBody": "Egy YouTube API-keresés 100 egységet fogyaszt a közös napi kvótából, ezért újratöltéskor, linkről, vissza- vagy előrelépéskor nem indul el magától.",
"runAgain": "Keresés a YouTube-on"
}
}
+2
View File
@@ -1,4 +1,6 @@
{
"linkedGone": "A linkben szereplő fájl már nincs ebben a listában",
"linkedNotListed": "A linkben szereplő fájl nincs a listázottak között — keress rá a nevére",
"navLabel": "Fájlok",
"searchPlaceholder": "Keresés a fájlok között…",
"count_one": "{{count}} elem",
+6 -2
View File
@@ -6,11 +6,15 @@
"clearConfirmTitle": "Törlöd az összes értesítést?",
"clearConfirmBody": "Minden itteni értesítés eltűnik a listából, olvasott és olvasatlan is. Nem hozhatók vissza.",
"markRead": "Olvasottnak jelöl",
"unreadName": "{{name}}, olvasatlan",
"dismiss": "Elrejtés",
"rowMenu": "Értesítés műveletei",
"menu": "Értesítések műveletei",
"sectionSystem": "Rendszer",
"sectionActivity": "Tevékenység",
"sectionNeedsYou_one": "Rád vár · {{count}}",
"sectionNeedsYou_other": "Rád vár · {{count}}",
"sectionRecent": "Legutóbbiak",
"earlier_one": "Korábbiak ({{count}})",
"earlier_other": "Korábbiak ({{count}})",
"andMore_one": "és még {{count}}",
"andMore_other": "és még {{count}}",
"openScheduler": "Ütemező megnyitása",
+1
View File
@@ -1,5 +1,6 @@
{
"loading": "Betöltés…",
"linkedFailed": "A linkben szereplő videó nem nyitható meg",
"backToOriginal": "Vissza az eredeti videóhoz",
"back": "Vissza",
"previous": "Előző",
+8 -1
View File
@@ -2,12 +2,19 @@ import { LS, setTabRaw } from "./storage";
// The admin Users page's persisted-tab key + the Access-requests tab id, plus a helper to
// pre-select that tab before navigating there (a notification's "Review" link uses it —
// useTabPersistedState reads the key on mount, and the page mounts fresh on navigation).
// useTabPersistedState reads the key on mount, and the page on screen hears it).
//
// Kept out of AdminUsers.tsx so callers (App, NotificationsPanel) can pre-select the tab
// WITHOUT statically importing the — now lazy-loaded — admin page, which would otherwise pull
// it back into the main bundle and defeat the code-split.
export const ADMIN_USERS_TAB_KEY = LS.adminUsersTab;
// The address-bar key the page mirrors its tab to.
export const USERS_TAB_URL_KEY = "utab";
/** The address-bar delta for the Users tab shown. */
export function usersTabParams(tab: string | null): Record<string, string | null> {
return { [USERS_TAB_URL_KEY]: tab };
}
const ADMIN_USERS_ACCESS_TAB = "access";
export function focusAccessRequestsTab(): void {
+1 -1
View File
@@ -20,7 +20,7 @@ import { setupApi } from "./api/setup";
export type * from "./api/setup";
import { feedApi } from "./api/feed";
export type * from "./api/feed";
export { TAKEOUT_JOB } from "./api/feed";
export { FEED_DEFAULT_SHOW, FEED_DEFAULT_SORT, TAKEOUT_JOB } from "./api/feed";
import { discoverApi } from "./api/discover";
export type * from "./api/discover";
export { DISCOVER_BUDGETS, HERO_TIERS, discoverCardKey } from "./api/discover";
+8
View File
@@ -81,6 +81,11 @@ export interface FeedResponse {
// or optional (dead surface). Re-add if a consumer ever needs it.
}
/** The feed's view and order with nothing chosen: what a bookmark of the plain feed names, and what
* the active-filter chips read "nothing applied" against. */
export const FEED_DEFAULT_SHOW = "unwatched";
export const FEED_DEFAULT_SORT = "newest";
export interface FeedFilters {
tags: number[];
/** Per-category tag match (language / topic / other each independently any/all). */
@@ -314,6 +319,9 @@ export const feedApi = {
duration_seconds: Math.floor(durationSeconds),
}),
videoDetail: (id: string): Promise<VideoDetail> => req(`/api/videos/${id}`),
/** One catalog video as the feed lists it (this user's state with it): what a player opened from an
* address starts from. */
videoRow: (id: string): Promise<Video> => req(`/api/videos/${encodeURIComponent(id)}/row`),
// One file of a Google Takeout export, its bytes as they are; the server tells the two apart.
takeoutUpload: (file: File): Promise<TakeoutUpload> => uploadReq("/api/takeout", file),
takeoutStatus: (): Promise<TakeoutStatus> => req("/api/takeout"),
@@ -0,0 +1,69 @@
// The channel page's address: what a view writes, and what an address opens.
import { describe, it, expect } from "vitest";
import {
channelPageParamUpdates as encode,
channelPageViewFrom as decode,
type ChannelPageView,
} from "./channelPageUrlState";
const FRESH: ChannelPageView = {
tab: "videos",
sort: "newest",
types: { includeNormal: true, includeShorts: false, includeLive: false },
};
const params = (u: Record<string, string | null>) =>
new URLSearchParams(Object.entries(u).filter((e): e is [string, string] => e[1] != null));
describe("channel page address", () => {
it("names a fresh page by its content types alone", () => {
expect(encode(FRESH)).toEqual({ chtab: null, chsort: null, chtypes: "n" });
});
it("names the tab, the sort and every content type it shows", () => {
expect(
encode({
tab: "about",
sort: "oldest",
types: { includeNormal: false, includeShorts: true, includeLive: true },
}),
).toEqual({ chtab: "about", chsort: "oldest", chtypes: "sl" });
});
it("names an empty content choice, which no letters would", () => {
const none = { includeNormal: false, includeShorts: false, includeLive: false };
expect(encode({ ...FRESH, types: none }).chtypes).toBe("none");
expect(decode(params({ chtypes: "none" }), FRESH).types).toEqual(none);
});
it("clears every key once the page is closed", () => {
expect(encode(null)).toEqual({ chtab: null, chsort: null, chtypes: null });
});
it.each<ChannelPageView>([
FRESH,
{
tab: "about",
sort: "views",
types: { includeNormal: true, includeShorts: true, includeLive: false },
},
{
tab: "videos",
sort: "oldest",
types: { includeNormal: false, includeShorts: false, includeLive: true },
},
])("reopens the view it names: %o", (view) => {
expect(decode(params(encode(view)), FRESH)).toEqual(view);
});
it("opens a bare channel link as a fresh page, with the feed's content types", () => {
const feedTypes = { includeNormal: true, includeShorts: true, includeLive: false };
expect(decode(new URLSearchParams("chan=UC1"), { ...FRESH, types: feedTypes })).toEqual({
...FRESH,
types: feedTypes,
});
});
it("ignores a tab it does not know", () => {
expect(decode(params({ chtab: "bogus" }), FRESH).tab).toBe("videos");
});
});
+57
View File
@@ -0,0 +1,57 @@
// The channel page's address-bar keys. The page opens over any page (`?chan=`, the shell's), so its own
// keys are the shell's too: no module owns them, a page switch clears them with `chan`, and the page
// under it writes none of ITS keys while the channel stands over it — the address names only what the
// screen shows. The watch state is not here: it is an account preference that follows every channel
// (`channelShow`).
export const CHANNEL_PAGE_KEYS = ["chtab", "chsort", "chtypes"] as const;
export type ChannelTab = "videos" | "about";
type ChannelContentTypes = {
includeNormal: boolean;
includeShorts: boolean;
includeLive: boolean;
};
export type ChannelPageView = { tab: ChannelTab; sort: string; types: ChannelContentTypes };
const DEFAULT_SORT = "newest";
// The content types as letters: n(ormal) s(horts) l(ive); "none" for an empty choice.
const TYPE_LETTERS: [keyof ChannelContentTypes, string][] = [
["includeNormal", "n"],
["includeShorts", "s"],
["includeLive", "l"],
];
/** The address-bar delta for the channel page's view; `null` clears every key (the page closed). The
* content types are always written: a page opened fresh takes them from the feed, so a link without
* them would reopen with whatever the feed of the browser opening it holds. */
export function channelPageParamUpdates(v: ChannelPageView | null): Record<string, string | null> {
if (v == null) return { chtab: null, chsort: null, chtypes: null };
const letters = TYPE_LETTERS.filter(([k]) => v.types[k])
.map(([, l]) => l)
.join("");
return {
chtab: v.tab === "about" ? "about" : null,
chsort: v.sort && v.sort !== DEFAULT_SORT ? v.sort : null,
chtypes: letters || "none",
};
}
/** The view a channel page's address names; what it leaves out comes from `fresh` (the defaults of a
* page opened without a link: the videos tab, newest first, the feed's content types). */
export function channelPageViewFrom(
params: URLSearchParams,
fresh: ChannelPageView,
): ChannelPageView {
const raw = params.get("chtypes");
const types =
raw == null
? fresh.types
: (Object.fromEntries(
TYPE_LETTERS.map(([k, l]) => [k, raw !== "none" && raw.includes(l)]),
) as ChannelContentTypes);
return {
tab: params.get("chtab") === "about" ? "about" : fresh.tab,
sort: params.get("chsort") || fresh.sort,
types,
};
}
+35 -12
View File
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
//
// The Channels-manager content state (active tab + column sort + the column-filter map) round-trips
// through namespaced URL keys (ctab/csort/cf) so a manager view is shareable, the plexUrlState
// The Channels-manager content state (active tab + column sort + the column-filter map + the name
// search) round-trips through namespaced URL keys (ctab/csort/cf/cq) so a manager view is shareable, the plexUrlState
// analogue. `cf` carries the mixed scalar/array FilterMap as a JSON blob.
import { describe, expect, it } from "vitest";
import {
@@ -20,7 +20,7 @@ const RICH_FILTERS: FilterMap = {
tags: ["12", "34"],
};
const BASE: ChannelsUrlState = { view: "subscribed", sort: null, filters: {} };
const BASE: ChannelsUrlState = { view: "subscribed", sort: null, filters: {}, search: "" };
// Apply an updates delta onto a base URLSearchParams the way urlWithParams would (null deletes).
function applyUpdates(updates: Record<string, string | null>): URLSearchParams {
@@ -32,29 +32,49 @@ function applyUpdates(updates: Record<string, string | null>): URLSearchParams {
}
describe("channelsParamUpdates", () => {
it("emits nothing for the all-default state", () => {
expect(channelsParamUpdates(BASE)).toEqual({ ctab: null, csort: null, cf: null });
it("writes no search for a blank one", () => {
expect(channelsParamUpdates({ ...BASE, search: " " }).cq).toBeNull();
});
it("writes the default view in full: this browser remembers one a link must not inherit", () => {
expect(channelsParamUpdates(BASE)).toEqual({
ctab: "subscribed",
csort: "none",
cf: "",
cq: null,
});
});
it("a link to the default view opens it over another remembered one", () => {
const params = applyUpdates(channelsParamUpdates(BASE));
const back = channelsParamsToState(params, {
view: "hidden",
sort: { key: "subscribers", dir: "desc" },
filters: { sync: "fully" },
search: "",
});
expect(back).toEqual(BASE);
});
it("clears every key when passed null (off-manager page)", () => {
expect(channelsParamUpdates(null)).toEqual({ ctab: null, csort: null, cf: null });
expect(channelsParamUpdates(null)).toEqual({ ctab: null, csort: null, cf: null, cq: null });
});
it("emits only non-default keys", () => {
it("writes the view picked", () => {
const u = channelsParamUpdates({
view: "hidden",
sort: { key: "subscribers", dir: "desc" },
filters: { sync: "fully" },
search: "tom",
});
expect(u.ctab).toBe("hidden");
expect(u.csort).toBe("subscribers:desc");
expect(u.cf).toBe(JSON.stringify({ sync: "fully" }));
expect(u.cq).toBe("tom");
});
it("drops empty filter entries so a cleared funnel emits no cf", () => {
expect(
channelsParamUpdates({ view: "subscribed", sort: null, filters: { tags: [], sync: "" } }).cf,
).toBeNull();
it("drops empty filter entries so a cleared funnel writes an empty cf", () => {
expect(channelsParamUpdates({ ...BASE, filters: { tags: [], sync: "" } }).cf).toBe("");
});
});
@@ -64,12 +84,14 @@ describe("round-trip", () => {
view: "blocked",
sort: { key: "priority", dir: "asc" },
filters: RICH_FILTERS,
search: "jazz",
};
const params = applyUpdates(channelsParamUpdates(state));
const back = channelsParamsToState(params, BASE);
expect(back.view).toBe("blocked");
expect(back.sort).toEqual({ key: "priority", dir: "asc" });
expect(back.filters).toEqual(RICH_FILTERS);
expect(back.search).toBe("jazz");
// the array shape survives the JSON round-trip, not collapsed to a scalar
expect(Array.isArray(back.filters.tags)).toBe(true);
});
@@ -80,6 +102,7 @@ describe("round-trip", () => {
view: "discovery",
sort: null,
filters: { sync: "needsFull" },
search: "",
});
expect(back.view).toBe("discovery"); // from base, no ctab
expect(back.filters).toEqual({ sync: "needsFull" }); // from base, no cf
@@ -88,7 +111,7 @@ describe("round-trip", () => {
it("ignores an out-of-vocabulary tab / bad sort / corrupt cf and falls back to base", () => {
const params = new URLSearchParams("ctab=bogus&csort=key:sideways&cf=notjson");
const back = channelsParamsToState(params, { view: "subscribed", sort: null, filters: {} });
const back = channelsParamsToState(params, BASE);
expect(back.view).toBe("subscribed"); // bogus tab → base
expect(back.sort).toBeNull(); // bad dir → parseSortState null → base (null)
expect(back.filters).toEqual({}); // corrupt cf → decodeFilters heals to empty
+21 -44
View File
@@ -2,11 +2,13 @@
// from the address bar so a manager view is bookmarkable/shareable — the analogue of the feed's
// urlState and Plex's plexUrlState. Keys are NAMESPACED (`ctab`/`csort`/`cf`) so they're
// channels-unique (like `?v=`/`?pl`/`pscope`): no other provider ever reads or clears them, and the
// feed's URL-stripping can't delete them out from under the manager. Only non-default values are
// emitted, so URLs stay clean. The manager's name search is deliberately EPHEMERAL (like the feed/plex
// rail search) and stays OUT of the shared contract.
import { decodeSortParam, encodeSortParam, type SortState } from "./columnSort";
// feed's URL-stripping can't delete them out from under the manager. The tab, sort and filters are
// always written, their defaults too: a page opened without them takes this browser's remembered view,
// which may not be the one bookmarked. The name search (`cq`) is part of the view like the rest (a
// bookmark of a searched list opens searched), but nothing remembers it, so only a term is written.
import { decodeSortParamOrNone, encodeSortParamOrNone, type SortState } from "./columnSort";
import { type FilterMap } from "./tableColumns";
import { decodeFilterMap, encodeFilterMap } from "./filterMapParam";
// The content state this mirrors. `view` is the raw tab string (the provider clamps it); `sort` is the
// raw provider SortState (healed against live columns only at the point of use), so the user's real
@@ -15,55 +17,29 @@ export interface ChannelsUrlState {
view: string;
sort: SortState;
filters: FilterMap;
search: string;
}
const KEYS = ["ctab", "csort", "cf"] as const;
export const CHANNELS_KEYS = ["ctab", "csort", "cf", "cq"] as const;
const KEYS = CHANNELS_KEYS;
const VIEWS = ["subscribed", "discovery", "hidden", "blocked"];
// Sort ⇄ `key:dir` (e.g. `subscribers:desc`) via the shared codec in columnSort. There is no default
// sort here (fallback null), so any sort emits — no default short-circuit needed.
// The FilterMap mixes scalar column filters (priority=select, name=text, the sync chip) with array ones
// (tags=multi), so it's carried as a compact JSON blob rather than a nested query string — JSON round-
// trips both shapes exactly (and future multi columns for free), and the values are opaque enum/id
// tokens where a readable querystring buys little. Empty entries are dropped so a cleared funnel emits
// no `cf`.
function encodeFilters(map: FilterMap): string | null {
const clean: FilterMap = {};
for (const [k, v] of Object.entries(map)) {
if (Array.isArray(v) ? v.length : v) clean[k] = v;
}
return Object.keys(clean).length ? JSON.stringify(clean) : null;
}
// A URL blob is untrusted input: accept only a plain object of string / string[] entries, anything else
// heals to empty (same discipline as useFilterState's storage hydrate).
function decodeFilters(raw: string): FilterMap {
try {
const v = JSON.parse(raw);
if (!v || typeof v !== "object" || Array.isArray(v)) return {};
const out: FilterMap = {};
for (const [k, val] of Object.entries(v)) {
if (typeof val === "string") out[k] = val;
else if (Array.isArray(val) && val.every((x) => typeof x === "string"))
out[k] = val as string[];
}
return out;
} catch {
return {};
}
}
// Sort ⇄ `key:dir` (e.g. `subscribers:desc`, `none` unsorted) via the shared codec in columnSort. The
// filter map rides as one JSON value (lib/filterMapParam), an empty one as `cf=`.
/** The address-bar delta for the manager content state: each namespaced key mapped to its emitted
* value, or null to delete it (so a control back at its default clears the key). Pass `null` to clear
* value, or null to delete it (only the search's, when cleared). Pass `null` to clear
* ALL manager keys — used when the app is off the Channels page (localStorage still holds the state; it
* re-mirrors on return). Feed the result into urlWithParams(). */
export function channelsParamUpdates(
state: ChannelsUrlState | null,
): Record<string, string | null> {
if (!state) return { ctab: null, csort: null, cf: null };
if (!state) return { ctab: null, csort: null, cf: null, cq: null };
return {
ctab: state.view && state.view !== "subscribed" ? state.view : null,
csort: encodeSortParam(state.sort),
cf: encodeFilters(state.filters),
ctab: state.view || "subscribed",
csort: encodeSortParamOrNone(state.sort),
cf: encodeFilterMap(state.filters) ?? "",
cq: state.search.trim() || null,
};
}
@@ -79,10 +55,11 @@ export function channelsParamsToState(
base: ChannelsUrlState,
): ChannelsUrlState {
const tab = params.get("ctab");
const csort = params.get("csort");
const linkedSort = decodeSortParamOrNone(params.get("csort"));
return {
view: tab && VIEWS.includes(tab) ? tab : base.view,
sort: csort != null ? (decodeSortParam(csort) ?? base.sort) : base.sort,
filters: params.has("cf") ? decodeFilters(params.get("cf") ?? "") : base.filters,
sort: linkedSort === undefined ? base.sort : linkedSort,
filters: params.has("cf") ? decodeFilterMap(params.get("cf") ?? "") : base.filters,
search: params.get("cq") ?? base.search,
};
}
+16
View File
@@ -53,6 +53,22 @@ export function decodeSortParam(raw: string): SortState {
return parseSortState({ key, dir });
}
// The list's own order (no column sort) as a word of its own, for a page whose sort is remembered (an
// account pref, this browser's view): there the sort is always written, because a page opened without
// one takes the remembered sort, which may not be the one bookmarked.
const UNSORTED = "none";
export function encodeSortParamOrNone(s: SortState): string {
return encodeSortParam(s) ?? UNSORTED;
}
/** The sort an address names; `undefined` when it names none or a malformed one (the remembered one
* applies). */
export function decodeSortParamOrNone(raw: string | null): SortState | undefined {
if (raw == null) return undefined;
return raw === UNSORTED ? null : (decodeSortParam(raw) ?? undefined);
}
/** The header-click cycle: unsorted → ascending → descending → unsorted. */
export function cycleSort(current: SortState, key: string): SortState {
if (!current || current.key !== key) return { key, dir: "asc" };
+8
View File
@@ -0,0 +1,8 @@
// The Configuration page's address-bar key: the config group its tab rail shows. Here, beside the other
// pages' keys, so the page's definition can declare it without importing the lazy page.
export const CONFIG_TAB_KEY = "cfgtab";
/** The address-bar delta for the config group shown (null: none named). */
export function configTabParams(tab: string | null): Record<string, string | null> {
return { [CONFIG_TAB_KEY]: tab };
}
+20
View File
@@ -0,0 +1,20 @@
// The file an address names open on the Files page: the player's key wins over the viewer's, and only a
// real row id opens anything — a fractional, zero, negative or garbled one would look up a row that
// cannot exist and say the file is gone.
import { describe, expect, it } from "vitest";
import { openFileFrom } from "./filesUrlState";
const from = (q: string) => openFileFrom(new URLSearchParams(q));
describe("openFileFrom", () => {
it("reads the viewer's and the player's file", () => {
expect(from("fview=3")).toEqual({ open: "view", id: 3 });
expect(from("fplay=4")).toEqual({ open: "play", id: 4 });
expect(from("fview=3&fplay=4")).toEqual({ open: "play", id: 4 });
});
it("opens nothing for an id that is not a positive integer", () => {
for (const raw of ["1.5", "0", "-2", "abc", ""]) expect(from(`fview=${raw}`)).toBeNull();
expect(from("q=x")).toBeNull();
});
});
+56
View File
@@ -0,0 +1,56 @@
// The Files page's address-bar keys: the folder shown (`?folder=`, its encoding in
// modules/files/filesContext), the file it turns to once (`?item=`), the name search (`?fq=`) and the
// sort (`?fsort=`, always written, lib/columnSort's `none` for the list's own order). Here, beside the
// other pages' codecs (lib/<id>UrlState), where the URL contract test reads them all.
export const FILES_FOLDER_KEY = "folder";
export const FILES_ITEM_KEY = "item";
export const FILES_SEARCH_KEY = "fq";
export const FILES_SORT_KEY = "fsort";
// The file open over the list: in the viewer, or in the player. Each dialog names itself in its own
// history entry (ui/Modal's `url`), so Back lands on the list's address without it.
export const FILES_VIEW_KEY = "fview";
export const FILES_PLAY_KEY = "fplay";
export const FILES_KEYS = [
FILES_FOLDER_KEY,
FILES_ITEM_KEY,
FILES_SEARCH_KEY,
FILES_SORT_KEY,
FILES_VIEW_KEY,
FILES_PLAY_KEY,
] as const;
export type FilesOpenFile = { open: "view" | "play"; id: number };
/** The address-bar delta for the list (the page's store): its search, folder and the file it turns to
* — each null when not named (`null`: the page is not what the address shows). */
export function filesListParams(
list: { search: string; folder: string | null; item: number | null } | null,
): Record<string, string | null> {
return {
[FILES_SEARCH_KEY]: list?.search || null,
[FILES_FOLDER_KEY]: list?.folder ?? null,
[FILES_ITEM_KEY]: list?.item != null ? String(list.item) : null,
};
}
/** The address-bar delta for the list's sort (lib/columnSort's encoding, `none` included). */
export function filesSortParams(sort: string | null): Record<string, string | null> {
return { [FILES_SORT_KEY]: sort };
}
/** What a file open over the list names in its own entry: the viewer's, or the player's. */
export function filesOpenParams(file: FilesOpenFile): Record<string, string | null> {
return { [file.open === "play" ? FILES_PLAY_KEY : FILES_VIEW_KEY]: String(file.id) };
}
/** The file an address opens over the list (a reload, a bookmark), or null. */
export function openFileFrom(params: URLSearchParams): FilesOpenFile | null {
for (const [open, key] of [
["play", FILES_PLAY_KEY],
["view", FILES_VIEW_KEY],
] as const) {
const id = Number(params.get(key));
if (Number.isInteger(id) && id > 0) return { open, id };
}
return null;
}
+33
View File
@@ -0,0 +1,33 @@
import { type FilterMap } from "./tableColumns";
// A table's column-filter map as one address-bar value (the channel manager's `cf`, a playlist's `plf`).
// The map mixes scalar column filters (select, text, the sync chip) with array ones (multi), so it's
// carried as a compact JSON blob rather than a nested query string — JSON round-trips both shapes
// exactly (and future multi columns for free) where a readable querystring buys little. A text
// column's entry is what the user typed, so a map with one is a typed key (ModuleDef.typedUrlKeys).
// Empty entries are dropped so a cleared funnel emits nothing.
export function encodeFilterMap(map: FilterMap): string | null {
const clean: FilterMap = {};
for (const [k, v] of Object.entries(map)) {
if (Array.isArray(v) ? v.length : v) clean[k] = v;
}
return Object.keys(clean).length ? JSON.stringify(clean) : null;
}
// A URL blob is untrusted input: accept only a plain object of string / string[] entries, anything else
// heals to empty (same discipline as useFilterState's storage hydrate).
export function decodeFilterMap(raw: string): FilterMap {
try {
const v = JSON.parse(raw);
if (!v || typeof v !== "object" || Array.isArray(v)) return {};
const out: FilterMap = {};
for (const [k, val] of Object.entries(v)) {
if (typeof val === "string") out[k] = val;
else if (Array.isArray(val) && val.every((x) => typeof x === "string"))
out[k] = val as string[];
}
return out;
} catch {
return {};
}
}
+1 -1
View File
@@ -78,7 +78,7 @@
{ "allowShortCircuit": false, "allowTaggedTemplates": false, "allowTernary": false }
],
"playwright/no-focused-test": [2],
"playwright/no-skipped-test": [2]
"playwright/no-skipped-test": [2, { "allowConditional": false, "disallowFixme": true }]
},
"settings": null
},
@@ -0,0 +1,93 @@
// @vitest-environment jsdom
//
// An overlay that is part of the view (a player) names itself in its own history entry's address, so a
// reload or a bookmark opens it — and the entry under it never carries those keys, so Back lands on the
// page as it was. Driven through jsdom's real history: its back()/forward() land their popstate a
// task later, like a browser's.
import { afterEach, describe, expect, it } from "vitest";
import { act, renderHook } from "@testing-library/react";
import { useBackToClose } from "./history";
const settle = () =>
act(async () => {
await Promise.resolve();
});
// Step through the history the way the browser does, and wait for its popstate to land.
const step = (go: () => void) =>
act(async () => {
const landed = new Promise((r) => window.addEventListener("popstate", r, { once: true }));
go();
await landed;
await Promise.resolve();
});
const search = () => new URLSearchParams(window.location.search);
/** A player-like overlay whose close really unmounts it, naming `url` in its entry. */
function mountPlayer(initial: Record<string, string | null>) {
const holder: { unmount?: () => void } = {};
const r = renderHook(
(url: Record<string, string | null>) => useBackToClose(() => holder.unmount?.(), url),
{ initialProps: initial },
);
holder.unmount = r.unmount;
return r;
}
afterEach(() => {
window.history.replaceState(null, "", "/");
});
describe("an overlay named in its entry's address", () => {
it("is named in its own entry, and Back lands on the address under it without it", async () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?q=music");
const depth = window.history.length;
mountPlayer({ watch: "v1", wtab: null });
await settle();
expect(window.history.length).toBe(depth + 1);
expect(search().get("watch")).toBe("v1");
expect(search().get("q")).toBe("music");
// What a page reads as Back lands (a host mounting there reopens a player its address names):
// the entry under the player never carried it, so there is nothing to clear first.
let landedOn = "";
window.addEventListener("popstate", () => (landedOn = window.location.search), { once: true });
await step(() => window.history.back());
expect(landedOn).toBe("?q=music");
expect(search().has("watch")).toBe(false);
expect(search().get("q")).toBe("music");
});
it("follows what it names as it changes", async () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?q=music");
const r = mountPlayer({ watch: "v1", wtab: null });
await settle();
r.rerender({ watch: "v2", wtab: "related" });
expect(search().get("watch")).toBe("v2");
expect(search().get("wtab")).toBe("related");
r.rerender({ watch: "v2", wtab: null });
expect(search().has("wtab")).toBe(false);
await step(() => r.unmount());
expect(search().has("watch")).toBe(false);
expect(search().get("q")).toBe("music");
});
it("closed by its own control, leaves the entry under it as it was", async () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?q=music");
const r = mountPlayer({ watch: "v1" });
await settle();
await step(() => r.unmount());
expect(window.location.search).toBe("?q=music");
});
it("an entry that still names it after it closed is cleared once it is the current one", async () => {
// A reload under an open player: the entry the new document starts from names the player.
window.history.replaceState({ sfPage: "feed" }, "", "/?q=music&watch=v1");
const r = mountPlayer({ watch: "v1" });
await settle();
await step(() => r.unmount());
expect(search().has("watch")).toBe(false);
// Forward onto the closed player's entry: nothing is open there, so neither is it named.
await step(() => window.history.forward());
expect(search().has("watch")).toBe(false);
expect(search().get("q")).toBe("music");
});
});
@@ -0,0 +1,47 @@
// @vitest-environment jsdom
//
// A reload under two overlays (a dialog, or a maximised player, over the player) loads on the upper
// one's entry; only the player reopens, and takes that entry over. The lower one's entry is still
// under it, and nothing reopens there: closing the player steps back over it too, so one close
// lands on the page — not on a dead step that looks like it. Its own file: the entry is read as the
// module loads, so it is set up before the import.
import { describe, expect, it } from "vitest";
import { act, renderHook } from "@testing-library/react";
describe("an overlay reopened on the entry a reload under two started from", () => {
it("closes onto the page under both", async () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed");
window.history.pushState({ sfPage: "feed", _ov: 1, _ovd: 1 }, "", "/?page=feed&watch=v1");
window.history.pushState({ sfPage: "feed", _ov: 2, _ovd: 2 }, "", "/?page=feed&watch=v1");
const depth = window.history.length;
const { useBackToClose } = await import("./history");
const holder: { unmount?: () => void } = {};
const r = renderHook(() => useBackToClose(() => holder.unmount?.(), { watch: "v1" }));
holder.unmount = r.unmount;
await act(async () => {
await Promise.resolve();
});
expect(window.history.length).toBe(depth);
await act(async () => {
const landed = new Promise((res) => window.addEventListener("popstate", res, { once: true }));
r.unmount();
await landed;
await Promise.resolve();
});
expect(window.history.state?._ov).toBeUndefined();
expect(window.location.search).toBe("?page=feed");
});
it("a pushed overlay entry records how many it stands on", async () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed");
const { useBackToClose } = await import("./history");
const r = renderHook(() => useBackToClose(() => {}));
await act(async () => {
await Promise.resolve();
});
expect(window.history.state?._ovd).toBe(1);
r.unmount();
});
});
@@ -0,0 +1,37 @@
// @vitest-environment jsdom
//
// A reload under two overlays: the player reopens on the upper one's entry, the lower one's is dead
// under it. A browser Back closes the player — and steps over the dead entry too, onto the page, as
// the player's own close does. Its own file: the entry is read as the module loads, so it is set up
// before the import.
import { describe, expect, it } from "vitest";
import { act, renderHook } from "@testing-library/react";
const landing = () =>
new Promise((res) => window.addEventListener("popstate", res, { once: true }));
describe("a browser Back over an overlay reopened on the entry a reload under two started from", () => {
it("lands on the page under both", async () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed");
window.history.pushState({ sfPage: "feed", _ov: 1, _ovd: 1 }, "", "/?page=feed&watch=v1");
window.history.pushState({ sfPage: "feed", _ov: 2, _ovd: 2 }, "", "/?page=feed&watch=v1");
const { useBackToClose } = await import("./history");
let closed = false;
renderHook(() => useBackToClose(() => (closed = true), { watch: "v1" }));
await act(async () => {
await Promise.resolve();
});
await act(async () => {
const first = landing();
window.history.back();
await first;
await landing(); // the step over the dead entry
await Promise.resolve();
});
expect(closed).toBe(true);
expect(window.history.state?._ov).toBeUndefined();
expect(window.location.search).toBe("?page=feed");
});
});
@@ -0,0 +1,43 @@
// @vitest-environment jsdom
//
// A reload under two overlays, in a tab whose entries below the dead one are not this document's
// (Chrome dropped them, see backStaysInDocument): closing the reopened player cannot step over both,
// so it steps back one — onto the dead entry, still in the app — rather than leaving it. Its own file:
// the entry is read as the module loads, so it is set up before the import.
import { afterEach, describe, expect, it, vi } from "vitest";
import { act, renderHook } from "@testing-library/react";
afterEach(() => {
Reflect.deleteProperty(window, "navigation");
});
describe("an overlay reopened over a dead entry with nothing of this document below it", () => {
it("closes one step back, staying in the document", async () => {
window.history.replaceState({ sfPage: "feed", _ov: 1, _ovd: 1 }, "", "/?page=feed&watch=v1");
window.history.pushState({ sfPage: "feed", _ov: 2, _ovd: 2 }, "", "/?page=feed&watch=v1");
const { useBackToClose } = await import("./history");
// Two steps back would leave the document; one stays in it.
Object.defineProperty(window, "navigation", {
configurable: true,
value: {
currentEntry: { index: 2 },
entries: () => [{ sameDocument: false }, { sameDocument: true }, { sameDocument: true }],
},
});
const go = vi.spyOn(window.history, "go");
const back = vi.spyOn(window.history, "back");
const r = renderHook(() => useBackToClose(() => {}, { watch: "v1" }));
await act(async () => {
await Promise.resolve();
});
await act(async () => {
const landed = new Promise((res) => window.addEventListener("popstate", res, { once: true }));
r.unmount();
await landed;
});
expect(go).not.toHaveBeenCalled();
expect(back).toHaveBeenCalledTimes(1);
expect(window.history.state?._ov).toBe(1);
});
});
@@ -0,0 +1,36 @@
// @vitest-environment jsdom
//
// A reload under an open overlay (a player the address names) loads the document on that overlay's
// entry, and the page opens the overlay again. It takes that entry over: pushed over it instead, Back
// would close the player onto the same page once more — one dead step for every reload. Its own file:
// the entry is read as the module loads, so it is set up before the import.
import { describe, expect, it } from "vitest";
import { act, renderHook } from "@testing-library/react";
const search = () => new URLSearchParams(window.location.search);
describe("an overlay reopened on the entry a reload started from", () => {
it("takes that entry over, and Back lands on the page under it", async () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?q=music");
window.history.pushState({ sfPage: "feed", _ov: 3 }, "", "/?q=music&watch=v1");
const depth = window.history.length;
const { useBackToClose } = await import("./history");
const holder: { unmount?: () => void } = {};
const r = renderHook(() => useBackToClose(() => holder.unmount?.(), { watch: "v1" }));
holder.unmount = r.unmount;
await act(async () => {
await Promise.resolve();
});
expect(window.history.length).toBe(depth);
expect(search().get("watch")).toBe("v1");
await act(async () => {
const landed = new Promise((res) => window.addEventListener("popstate", res, { once: true }));
window.history.back();
await landed;
await Promise.resolve();
});
expect(window.location.search).toBe("?q=music");
});
});
@@ -0,0 +1,40 @@
// @vitest-environment jsdom
//
// The entry a reload under an open dialog started from carries the dialog's mark, and a dialog that
// does not reopen (About, the cheat sheet) leaves it there. A view pushed from that entry (a channel
// page, a search, a sub-view) must not inherit the mark: the first overlay over it took the view's
// entry over as its own, and closing it closed the view too. Its own file: the entry is read as the
// module loads, so it is set up before the import.
import { describe, expect, it } from "vitest";
import { act, renderHook } from "@testing-library/react";
describe("a view pushed from the entry a reload under a dialog started from", () => {
it("is not taken over by the first overlay over it", async () => {
window.history.replaceState({ sfPage: "feed" }, "", "/?page=feed");
window.history.pushState({ sfPage: "feed", _ov: 3 }, "", "/?page=feed");
const { rememberNavPosition, useBackToClose } = await import("./history");
// openChannel's push, as it spreads the entry it leaves.
const left = rememberNavPosition();
expect(left._ov).toBeUndefined();
window.history.pushState({ ...left, _chan: "UC1" }, "", "/?chan=UC1");
const depth = window.history.length;
const holder: { unmount?: () => void } = {};
const r = renderHook(() => useBackToClose(() => holder.unmount?.(), { watch: "v1" }));
holder.unmount = r.unmount;
await act(async () => {
await Promise.resolve();
});
expect(window.history.length).toBe(depth + 1);
await act(async () => {
const landed = new Promise((res) => window.addEventListener("popstate", res, { once: true }));
r.unmount();
await landed;
await Promise.resolve();
});
expect(window.history.state?._chan).toBe("UC1");
expect(window.location.search).toBe("?chan=UC1");
});
});
+138 -2
View File
@@ -51,7 +51,7 @@ describe("useHistorySubview seed", () => {
});
it("prefers history.state._sub over the URL param (in-app entry)", () => {
setUrl("?v=a", { _sub: "b" });
setUrl("?v=a", { _sub: "b", _subOf: "v" });
const { result } = renderHook(() => useHistorySubview("root", url));
expect(result.current.view).toBe("b");
});
@@ -63,7 +63,7 @@ describe("useHistorySubview seed", () => {
});
it("ignores the URL entirely when no SubviewUrl is supplied (state-only mirror)", () => {
setUrl("?v=a", { _sub: "fromState" });
setUrl("?v=a", { _sub: "fromState", _subOf: "" });
const { result } = renderHook(() => useHistorySubview("root"));
expect(result.current.view).toBe("fromState");
// A URL param with no url config must NOT leak in.
@@ -128,6 +128,64 @@ describe("useHistorySubview open", () => {
});
});
// One entry, two modules: the sign-in card mounts on the entry a Plex season stood on (signed out
// there), and Plex on one the card's register view stood on (signed in from it). Each reads only its
// own sub-view: another's is not one of its views (the card rendered a mode it has no button for).
describe("useHistorySubview on an entry another module's sub-view stood on", () => {
const other: SubviewUrl<string> = {
key: "m",
encode: (v) => (v === "signin" ? null : v),
decode: (raw) => (raw === "register" ? raw : null),
};
it("opens at its own root, not on the other's view", () => {
const plex = renderHook(() => useHistorySubview("root", url));
act(() => plex.result.current.open("season"));
plex.unmount();
const card = renderHook(() => useHistorySubview("signin", other));
expect(card.result.current.view).toBe("signin");
});
it("the other way round too", () => {
const card = renderHook(() => useHistorySubview("signin", other));
act(() => card.result.current.open("register"));
card.unmount();
window.history.replaceState(window.history.state, "", "/");
const plex = renderHook(() => useHistorySubview("root", url));
expect(plex.result.current.view).toBe("root");
});
it("an older build's entry, which says nothing: its own only when its address names its view", () => {
setUrl("?v=season", { _sub: "season" });
expect(renderHook(() => useHistorySubview("signin", other)).result.current.view).toBe("signin");
expect(renderHook(() => useHistorySubview("root", url)).result.current.view).toBe("season");
});
it("an older build's entry whose address names both: the _sub goes to the one it is the view of", () => {
// The card's push kept the season's `v` beside its own `m`.
setUrl("?v=season&m=register", { _sub: "register" });
expect(renderHook(() => useHistorySubview("root", url)).result.current.view).toBe("season");
expect(renderHook(() => useHistorySubview("signin", other)).result.current.view).toBe(
"register",
);
});
it("reads its own from an entry it rewrote in place, which no address names", () => {
const first = renderHook(() => useHistorySubview("root"));
act(() => first.result.current.open("x", { replace: true }));
first.unmount();
expect(renderHook(() => useHistorySubview("root")).result.current.view).toBe("x");
});
it("still reads its own", () => {
const plex = renderHook(() => useHistorySubview("root", url));
act(() => plex.result.current.open("season"));
plex.unmount();
window.history.replaceState(window.history.state, "", "/");
expect(renderHook(() => useHistorySubview("root", url)).result.current.view).toBe("season");
});
});
describe("useHistorySubview popstate", () => {
it("restores the sub-view from state._sub on Back/Forward", () => {
const { result } = renderHook(() => useHistorySubview("root", url));
@@ -185,6 +243,84 @@ describe("useHistorySubview entry", () => {
});
});
// A view that moves on by itself — the Plex player stepping to the next episode — is still the same
// entry: no push, nothing for Back to step through. But the entry must say where it moved, or a reload
// reopens the item the viewer started with (the owner, 2026-10-25: F5 during a binge restarted the
// first episode).
describe("useHistorySubview follow", () => {
async function overlayOver() {
const closed = vi.fn();
const layer = renderHook(() => useBackToClose(closed));
await act(async () => {
await Promise.resolve();
});
return { closed, layer };
}
it("rewrites the entry it stands on, so a reload reopens the view it moved on to", () => {
const { result } = renderHook(() => useHistorySubview("root", url));
act(() => result.current.open("a"));
const before = window.history.length;
act(() => result.current.follow("b"));
expect(result.current.view).toBe("b");
expect(window.history.state?._sub).toBe("b");
expect(window.location.search).toBe("?v=b");
expect(window.history.length).toBe(before);
const { result: reloaded } = renderHook(() => useHistorySubview("root", url));
expect(reloaded.current.view).toBe("b");
});
it("is not a navigation: an overlay over the view stays open", async () => {
const { result } = renderHook(() => useHistorySubview("root", url));
act(() => result.current.open("a"));
const { closed, layer } = await overlayOver();
act(() => result.current.follow("b"));
await act(async () => {
await new Promise((r) => setTimeout(r, 20));
});
expect(closed).not.toHaveBeenCalled();
expect(window.history.state?._ov).toBeDefined();
// A reload with the overlay up reopens the view it moved on to as well.
expect(window.history.state?._sub).toBe("b");
layer.unmount(); // the history goes back to the view's own entry before the next test
await waitFor(() => expect(window.history.state?._ov).toBeUndefined());
});
it("the entry under an overlay follows too: closing the overlay lands on the moved-on view", async () => {
const { result } = renderHook(() => useHistorySubview("root", url));
act(() => result.current.open("a"));
const { layer } = await overlayOver();
act(() => result.current.follow("b"));
layer.unmount(); // the overlay closes: its entry goes by a back() onto the view's own entry
await waitFor(() => expect(window.history.state?._ov).toBeUndefined());
expect(result.current.view).toBe("b");
expect(window.history.state?._sub).toBe("b");
expect(window.location.search).toBe("?v=b");
});
it("a navigation on the same entry ends it: an overlay closing over it lands on the new view", async () => {
const { result } = renderHook(() => useHistorySubview("root", url));
act(() => result.current.open("a"));
act(() => result.current.follow("b"));
act(() => result.current.open("c", { replace: true }));
const { layer } = await overlayOver();
layer.unmount();
await waitFor(() => expect(window.history.state?._ov).toBeUndefined());
expect(result.current.view).toBe("c");
expect(window.history.state?._sub).toBe("c");
});
it("does not follow onto another entry: Back to the view below restores that one", async () => {
const { result } = renderHook(() => useHistorySubview("root", url));
act(() => result.current.open("a"));
act(() => result.current.open("p"));
act(() => result.current.follow("q"));
act(() => window.history.back());
await waitFor(() => expect(result.current.view).toBe("a"));
expect(window.history.state?._sub).toBe("a");
});
});
// Chrome keeps 50 entries a tab; when full, a new entry drops the oldest "skippable" one — one the page
// left by a pushState with no user gesture — and that can be this page's own entry under the
// sub-view. back() then left the document for an older one (measured 2026-10-07: its restored Plex
+189 -33
View File
@@ -6,10 +6,11 @@
// a module (e.g. the sign-in card's "forgot password" → sign-in) returns to the parent view first.
// - useBackToClose: while an overlay/modal is mounted it occupies one history entry; Back
// closes the topmost one. A module-level stack keeps nesting correct — closing one modal by
// its own button pops exactly its entry without tripping the modals underneath.
// its own button pops exactly its entry without tripping the modals underneath. An overlay
// that is part of the view (a player) names itself in its entry's address.
//
// setPage() pushes a clean { sfPage } entry (dropping _sub/_ov), so each page starts at its root.
import { useCallback, useEffect, useEffectEvent, useMemo, useState } from "react";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
import { navPosition, restoreNavPosition, type NavPosition } from "./listNav";
import { urlWithParams } from "./urlState";
import { useLatest } from "./useLatest";
@@ -86,7 +87,10 @@ if (typeof window !== "undefined") {
/** Call right before a pushState that opens a new view over the current entry (a page, a sub-view, a
* channel, a tab). Returns the current state WITHOUT the stamp: a push that spreads the current state
* must spread this, so the new entry does not inherit a position it was never left from. */
* must spread this, so the new entry does not inherit a position it was never left from — nor an
* overlay's marks, which belong to the entry being left (an entry a reload under an open dialog
* started from carries them, and the first overlay over a view pushed from it took that view's entry
* over for its own). */
export function rememberNavPosition(): Record<string, unknown> {
// A restore still waiting for the last landing's lists belongs to the page being left: left
// running, it would focus "list N, item M" of whatever page this push opens.
@@ -94,7 +98,8 @@ export function rememberNavPosition(): Record<string, unknown> {
const { sfNav: _stale, ...st } = (window.history.state ?? {}) as Record<string, unknown>;
const pos = navPosition();
window.history.replaceState(pos ? { ...st, sfNav: pos } : st, "");
return st;
const { _ov: _overlay, _ovd: _depth, ...view } = st;
return view;
}
// --- Is the entry a back() lands on still ours? --------------------------------------------
@@ -110,12 +115,12 @@ interface NavigationLike {
entries: () => readonly { sameDocument: boolean }[];
}
/** Would one more history.back() still land in this document? */
export function backStaysInDocument(): boolean {
/** Would `steps` more steps back (one, a history.back()) still land in this document? */
export function backStaysInDocument(steps = 1): boolean {
const nav = (window as { navigation?: NavigationLike }).navigation;
const at = nav?.currentEntry?.index;
if (nav == null || at == null) return true;
return nav.entries()[at - pendingProgrammatic - 1]?.sameDocument === true;
return nav.entries()[at - pendingSteps - steps]?.sameDocument === true;
}
// --- Sub-views (value carried in history.state._sub) ---------------------------------------
@@ -134,6 +139,9 @@ export interface SubviewUrl<T> {
entry?: (view: T) => T;
}
/** Whose sub-view an entry's `_sub` is: the key its module mirrors to (a state-only one has none). */
const subOwner = (url: { key: string } | undefined): string => url?.key ?? "";
export function useHistorySubview<T>(
root: T,
url?: SubviewUrl<T>,
@@ -143,6 +151,9 @@ export function useHistorySubview<T>(
* continuation of the navigation that just arrived here, not a step the user took inside the
* module. See the `jumpTo` hand-off in PlexBrowse. */
open: (next: T, opts?: { replace?: boolean }) => void;
/** The view moved on by itself (the Plex player stepped to the next episode): the entry it stands
* on says so from now on, without a navigation — the overlays over it stay open. */
follow: (next: T) => void;
back: () => void;
} {
// Resolve the current entry's sub-view: history.state._sub for an in-app entry, else decode the
@@ -150,18 +161,35 @@ export function useHistorySubview<T>(
// ⚠️ The seed AND the popstate handler must use THIS same fallback: a popstate can land on a
// bookmark entry (URL-only, no _sub) — e.g. after an overlay's programmatic history.back() — and
// reading history.state alone would wrongly collapse the bookmarked sub-view to root.
// The entry's _sub is this module's only when it says so (`_subOf`): one entry can carry another
// module's — the sign-in card mounts on the entry a Plex season stood on when signed out there, and
// took that season for one of its modes (a card with no button for it). An entry an older build
// wrote says nothing: its _sub is this module's when it is the view the address names under this
// module's key. The key alone is not enough: the card's push kept the season's `v` beside its `m`.
const readView = (): T => {
const fromState = window.history.state?._sub as T | undefined;
const st = window.history.state;
const raw = url ? new URLSearchParams(window.location.search).get(url.key) : null;
const decoded = url && raw != null ? url.decode(raw) : null;
const owned =
st?._subOf === undefined
? decoded != null && st?._sub != null && url?.encode(st._sub as T) === raw
: st._subOf === subOwner(url);
const fromState = owned ? (st?._sub as T | undefined) : undefined;
if (fromState != null) return fromState;
if (url) {
const raw = new URLSearchParams(window.location.search).get(url.key);
const decoded = raw != null ? url.decode(raw) : null;
if (decoded != null) return decoded;
}
if (decoded != null) return decoded;
return root;
};
const [view, setView] = useState<T>(readView);
const readLandedView = useEffectEvent(readView);
// Where `follow` moved the view, and on which entry. An overlay over the view holds an entry of its
// own (a copy of the view's state, same sfScroll id), and only the current entry can be rewritten:
// the view's own entry under the overlay still says where it was until a step lands back on it.
const followedRef = useRef<{ entry: number; view: T } | null>(null);
const readLandedView = useEffectEvent((): T => {
const followed = followedRef.current;
if (followed == null || peekNavId() !== followed.entry) return readView();
writeSubEntry(followed.view, url);
return followed.view;
});
useEffect(() => {
// Back/Forward restores the sub-view from the landed entry (state OR its restored ?<key> URL).
const onPop = () => setView(readLandedView());
@@ -182,20 +210,19 @@ export function useHistorySubview<T>(
const go = useCallback(
(next: T, opts?: { replace?: boolean }) => {
setView(next);
const kept = url?.entry ? url.entry(next) : next;
const href = url ? urlWithParams({ [url.key]: url.encode(next) }) : "";
// A navigation says where the view is now, on the entry it lands on or rewrites.
followedRef.current = null;
if (opts?.replace) {
// Same ENTRY, so it keeps its sfScroll id: PageScroller keys offsets per (entry, view), and
// the view key has changed, so the sub-view still opens at the top without minting an id
// that would orphan the one this entry already carries.
window.history.replaceState({ ...window.history.state, _sub: kept }, "", href);
writeSubEntry(next, url);
notifyNav();
return;
}
const kept = url?.entry ? url.entry(next) : next;
const href = url ? urlWithParams({ [url.key]: url.encode(next) }) : "";
// A fresh sfScroll so the opened sub-view is its own scroll entry (starts at the top, and Back
// restores the view we came from) — then notify PageScroller, which this push doesn't re-render.
window.history.pushState(
{ ...rememberNavPosition(), _sub: kept, sfScroll: nextNavId() },
{ ...rememberNavPosition(), _sub: kept, _subOf: subOwner(url), sfScroll: nextNavId() },
"",
href,
);
@@ -218,9 +245,26 @@ export function useHistorySubview<T>(
}),
[go, rootRef],
);
const follow = useCallback(
(next: T) => {
setView(next);
followedRef.current = { entry: ensureNavId(), view: next };
writeSubEntry(next, url);
},
[url],
);
// Memoised as a whole for the same reason: a consumer that wants "re-run when the sub-view moves"
// can now write `[sub]` and mean it, instead of re-running on every parent render.
return useMemo(() => ({ view, open, back }), [view, open, back]);
return useMemo(() => ({ view, open, follow, back }), [view, open, follow, back]);
}
// Rewrite the CURRENT entry to hold `next`. Same entry, so it keeps its sfScroll id: PageScroller keys
// offsets per (entry, view), and the view key has changed, so the sub-view still opens at the top
// without minting an id that would orphan the one this entry already carries.
function writeSubEntry<T>(next: T, url: SubviewUrl<T> | undefined): void {
const kept = url?.entry ? url.entry(next) : next;
const href = url ? urlWithParams({ [url.key]: url.encode(next) }) : "";
replaceView({ ...window.history.state, _sub: kept, _subOf: subOwner(url) }, href);
}
// --- Overlays / modals (one history entry each, nesting-safe) -------------------------------
@@ -245,16 +289,69 @@ export function useHistorySubview<T>(
// both undid the navigation AND closed the dialog above it, and the dead Back press after that (the
// last two measured in Chrome). With nothing ever buried, the stack and the history agree by
// construction.
type Overlay = { token: number; cb: () => void };
// `url`: the keys an overlay names in the address of its own entry (and of the entries above it).
type Overlay = { token: number; cb: () => void; url?: OverlayUrl };
type OverlayUrl = Record<string, string | null>;
const overlayStack: Overlay[] = [];
// Every key an overlay has named in this document: an entry carries those of the overlays it stands
// for and none of the rest. The entry under an overlay is never written with its keys, so Back lands
// on an address without it; and one that still names a closed overlay (the entry a reload under an
// open player started from, a Forward onto an entry whose overlay is gone) is cleared once it is
// the current entry.
const overlayUrlKeys = new Set<string>();
let overlayCounter = 0;
// A plain function, not `++overlayCounter` inline: the React Compiler cannot lower an update of a
// module variable inside a hook, and skipped the whole hook for it (react-hooks/todo).
const nextOverlayToken = () => ++overlayCounter;
// Overlay history entries we've actually pushed. Reconciled toward overlayStack.length.
let historyDepth = 0;
// Programmatic history.back() calls still awaiting their popstate — each must be ignored.
// The entry this document was loaded on, when it was an overlay's (a reload under an open player):
// the first overlay to open takes it over rather than pushing another over it — pushed, Back would
// close the player onto that same page again, one dead step per reload. Until the first push or Back;
// a view pushed from it does not carry its mark (rememberNavPosition). `_ovd` on an overlay's entry is how many overlay
// entries it stood on, its own included: a reload under two (a dialog, or a maximised player, over
// the player) leaves the lower one's entry under the one taken over, and closing the taken-over
// overlay steps back over those too (`deadBelow`) — one Back closes it, as it opened.
let reloadedOverlayEntry: unknown = window.history.state?._ov ?? null;
const reloadedDepth: unknown = window.history.state?._ovd;
let deadBelow = 0;
/** Rewrite the current entry in place for another view (a refined search, another channel, a
* sub-view followed): `state` and `href` as replaceState takes them. With no overlay open, the
* entry's overlay marks go — the ones a reload under an overlay left. They named the view it was
* left from, and the first overlay over the new one would take this entry over: closed, it stepped
* back onto the entry below and the screen went back to the view before the rewrite. */
export function replaceView(state: Record<string, unknown>, href?: string): void {
if (historyDepth > 0) {
window.history.replaceState(state, "", href);
return;
}
reloadedOverlayEntry = null;
const { _ov: _overlay, _ovd: _depth, ...view } = state;
window.history.replaceState(view, "", href);
}
// Programmatic history steps back still awaiting their popstate — each must be ignored — and how
// many entries they step over in all (a step over dead entries is one traversal of several).
let pendingProgrammatic = 0;
let pendingSteps = 0;
const pendingStepCounts: number[] = [];
function stepBack(steps: number): void {
pendingProgrammatic++;
pendingSteps += steps;
pendingStepCounts.push(steps);
if (steps === 1) window.history.back();
else window.history.go(-steps);
}
function landedStepBack(): void {
pendingProgrammatic--;
pendingSteps -= pendingStepCounts.shift() ?? 1;
}
// The overlay at the bottom of the stack closing: back over its entry and any dead ones under it.
function stepsToClose(): number {
const steps = historyDepth === 0 ? 1 + deadBelow : 1;
if (historyDepth === 0) deadBelow = 0;
return steps;
}
let reconcileScheduled = false;
let listenerInstalled = false;
// Re-checked after every reconcile — see `afterClosing`.
@@ -270,22 +367,59 @@ function reconcileHistory(): void {
const want = overlayStack.length;
while (historyDepth < want && pendingProgrammatic === 0) {
historyDepth++;
window.history.pushState({ ...window.history.state, _ov: nextOverlayToken() }, "");
const here = window.history.state?._ov;
if (historyDepth === 1 && here != null && here === reloadedOverlayEntry) {
reloadedOverlayEntry = null;
if (typeof reloadedDepth === "number" && reloadedDepth > 1) deadBelow = reloadedDepth - 1;
continue;
}
reloadedOverlayEntry = null;
window.history.pushState(
{ ...window.history.state, _ov: nextOverlayToken(), _ovd: historyDepth + deadBelow },
"",
);
}
while (historyDepth > want) {
historyDepth--;
if (backStaysInDocument()) {
pendingProgrammatic++;
window.history.back();
} else {
const steps = stepsToClose();
if (backStaysInDocument(steps)) stepBack(steps);
else if (steps > 1 && backStaysInDocument()) stepBack(1);
else {
// Nothing of ours below to step back to (see backStaysInDocument): the entry stays, unmarked.
const { _ov: _drop, ...st } = (window.history.state ?? {}) as Record<string, unknown>;
const {
_ov: _drop,
_ovd: _depth,
...st
} = (window.history.state ?? {}) as Record<string, unknown>;
window.history.replaceState(st, "");
}
}
nameOverlaysHere();
syncWaiters.forEach((cb) => cb());
}
// The address of the entry the open overlays stand on: their keys, every other overlay's cleared.
// Undefined (the address as it is) while no overlay names any. Written by `nameOverlaysHere` alone:
// a pushed entry starts as a copy of the one under it and is named once it is the current one.
function overlayHref(): string | undefined {
if (overlayUrlKeys.size === 0) return undefined;
const updates: OverlayUrl = {};
for (const k of overlayUrlKeys) updates[k] = null;
for (const o of overlayStack) Object.assign(updates, o.url);
return urlWithParams(updates);
}
// Write the current entry's overlay keys, once the history has caught up with the stack (before
// that, the current entry may be one about to be pushed over or stepped back from).
function nameOverlaysHere(): void {
if (historyDepth !== overlayStack.length || pendingProgrammatic > 0) return;
const href = overlayHref();
if (href != null && href !== hrefNow())
window.history.replaceState(window.history.state, "", href);
}
const hrefNow = () => window.location.pathname + window.location.search + window.location.hash;
function scheduleReconcile(): void {
if (reconcileScheduled) return;
reconcileScheduled = true;
@@ -296,15 +430,21 @@ function ensureOverlayListener(): void {
if (listenerInstalled) return;
listenerInstalled = true;
window.addEventListener("popstate", () => {
reloadedOverlayEntry = null;
if (pendingProgrammatic > 0) {
pendingProgrammatic--; // our own back(): consume and ignore
landedStepBack(); // our own back(): consume and ignore
// The last one landed: an overlay that opened while it was in flight still owes its entry.
if (pendingProgrammatic === 0 && historyDepth < overlayStack.length) scheduleReconcile();
else nameOverlaysHere();
return;
}
// Genuine user Back: the browser already dropped one overlay entry, so close the topmost
// overlay to match. Its unmount cleanup finds itself already off the stack and only re-syncs.
// The last one closing over dead entries (see `deadBelow`) steps over them too.
if (historyDepth > 0) historyDepth--;
const dead = historyDepth === 0 ? deadBelow : 0;
if (historyDepth === 0) deadBelow = 0;
if (dead > 0 && backStaysInDocument(dead)) stepBack(dead);
const top = overlayStack.pop();
if (top) top.cb();
scheduleReconcile();
@@ -421,15 +561,21 @@ export function closeTopOverlayThenRun(close: () => void, run: () => void): void
}
/** While the calling component is mounted, Back (or the browser/mouse back button) closes it via
* `onClose` instead of navigating away. Mount the component only while the overlay is open. */
export function useBackToClose(onClose: () => void): void {
* `onClose` instead of navigating away. Mount the component only while the overlay is open.
* `url`: what the overlay names in its entry's address (a null value: the key absent), followed as
* it changes; the entry under it never carries those keys. */
export function useBackToClose(onClose: () => void, url?: OverlayUrl): void {
const cb = useEffectEvent(onClose);
const named = useEffectEvent(() => url);
const entryRef = useRef<Overlay | null>(null);
useEffect(() => {
ensureOverlayListener();
const entry: Overlay = { token: nextOverlayToken(), cb: () => cb() };
entryRef.current = entry;
overlayStack.push(entry);
scheduleReconcile();
return () => {
entryRef.current = null;
const idx = overlayStack.indexOf(entry);
// idx === -1 means the shared handler already removed us on a real user Back; either way,
// just re-sync history to the (possibly unchanged) overlay count on the next tick.
@@ -437,6 +583,16 @@ export function useBackToClose(onClose: () => void): void {
scheduleReconcile();
};
}, []);
// After the effect above (declaration order), so the first run names the entry before it is pushed.
const urlDep = url ? JSON.stringify(url) : "";
useEffect(() => {
const entry = entryRef.current;
const next = named();
if (!entry || !next) return;
entry.url = next;
for (const k of Object.keys(next)) overlayUrlKeys.add(k);
nameOverlaysHere();
}, [urlDep]);
}
/** A Back-closable layer that exists only WHILE `active`. Stacks on top of `useBackToClose` and any
+20
View File
@@ -0,0 +1,20 @@
// Home's time budget in the address bar (`?page=home&hb=short`): a page SETTING, like a feed filter,
// so it is a link and survives a reload. What Home draws under it is not: the question's seed, the
// press and the cards already offered stay on the history entry (Home.tsx), because the same question
// draws other cards once what you have watched moves on — an address cannot promise "that view".
import { DISCOVER_BUDGETS, type DiscoverBudget } from "./api";
const HOME_BUDGET_KEY = "hb";
export const HOME_KEYS = [HOME_BUDGET_KEY] as const;
export const DEFAULT_BUDGET: DiscoverBudget = "any";
/** The budget a URL names, or null when it names none (or none Home offers). */
export function budgetFrom(params: URLSearchParams): DiscoverBudget | null {
const raw = params.get(HOME_BUDGET_KEY);
return DISCOVER_BUDGETS.includes(raw as DiscoverBudget) ? (raw as DiscoverBudget) : null;
}
/** The URL update for a budget: the default clears its key. */
export function budgetParams(budget: DiscoverBudget): Record<string, string | null> {
return { [HOME_BUDGET_KEY]: budget === DEFAULT_BUDGET ? null : budget };
}
+113
View File
@@ -0,0 +1,113 @@
import { describe, expect, it } from "vitest";
import { FOLD_AFTER_MS, entryKey, orderInbox, type InboxOrder } from "./inboxOrder";
import type { AppNotification } from "./api";
import type { Notification as ClientNotif } from "./notifications";
const NOW = Date.parse("2026-10-28T12:00:00Z");
const ago = (ms: number) => NOW - ms;
const H = 3600 * 1000;
const D = 24 * H;
const server = (id: number, at: number | null, read: boolean) =>
({
id,
type: "download_done",
title: "t",
body: null,
data: null,
read,
dismissed: false,
created_at: at === null ? null : new Date(at).toISOString(),
}) as AppNotification;
const client = (id: number, at: number, extra: Partial<ClientNotif> = {}) =>
({
id,
level: "info",
message: "m",
requiresInteraction: false,
ts: at,
read: true,
dismissed: true,
transient: false,
repeat: 1,
...extra,
}) as ClientNotif;
const keys = (o: InboxOrder) => ({
needsYou: o.needsYou.map(entryKey),
recent: o.recent.map(entryKey),
earlier: o.earlier.map(entryKey),
});
const order = (s: AppNotification[], c: ClientNotif[], held: ReadonlySet<string> = new Set()) =>
keys(orderInbox(s, c, { now: NOW, held }));
describe("orderInbox", () => {
it("puts a waiting access-requests nudge above every server row, read or not", () => {
const o = order(
[server(1, ago(1 * H), false), server(2, ago(1 * D), true)],
[client(1, ago(5 * 60 * 1000), { meta: { kind: "access-requests" } })],
);
expect(o.needsYou).toEqual(["client:1", "server:1"]);
expect(o.recent).toEqual(["server:2"]);
});
it("an old unread row still asks: it never folds or drifts below newer read ones", () => {
const o = order([server(1, ago(30 * D), false), server(2, ago(1 * H), true)], []);
expect(o.needsYou).toEqual(["server:1"]);
expect(o.recent).toEqual(["server:2"]);
expect(o.earlier).toEqual([]);
});
it("merges both sources into one stream, newest first", () => {
const o = order(
[server(1, ago(3 * H), true), server(2, ago(1 * H), true)],
[client(7, ago(2 * H)), client(8, ago(4 * H))],
);
expect(o.recent).toEqual(["server:2", "client:7", "server:1", "client:8"]);
});
it("folds read rows older than a week, and only those", () => {
const o = order(
[server(1, ago(FOLD_AFTER_MS + H), true), server(2, ago(FOLD_AFTER_MS - H), true)],
[client(3, ago(9 * D))],
);
expect(o.recent).toEqual(["server:2"]);
expect(o.earlier).toEqual(["server:1", "client:3"]);
});
it("keeps a row that asked earlier in the visit in its place once read, from either source", () => {
// Opening the center marks the client notices read: the band must not empty as it renders; and
// a server row marked read must not jump lists under the reader.
const o = order(
[server(1, ago(30 * D), true), server(2, ago(3 * H), true)],
[client(4, ago(2 * H)), client(5, ago(1 * H))],
new Set(["client:4", "server:1"]),
);
expect(o.needsYou).toEqual(["client:4", "server:1"]);
expect(o.recent).toEqual(["client:5", "server:2"]);
expect(o.earlier).toEqual([]);
});
it("an unread client notice (raised while the center is open) asks", () => {
const o = order([], [client(6, ago(H), { read: false })]);
expect(o.needsYou).toEqual(["client:6"]);
});
it("a notice waiting on an interaction asks until it is dealt with", () => {
const o = order(
[],
[
client(1, ago(H), { requiresInteraction: true, dismissed: false }),
client(2, ago(H), { requiresInteraction: true, dismissed: true }),
],
);
expect(o.needsYou).toEqual(["client:1"]);
expect(o.recent).toEqual(["client:2"]);
});
it("a server row of no known date sorts last and never folds", () => {
const o = order([server(1, null, true), server(2, ago(30 * D), true)], [client(3, ago(H))]);
expect(o.recent).toEqual(["client:3", "server:1"]);
expect(o.earlier).toEqual(["server:2"]);
});
});
+72
View File
@@ -0,0 +1,72 @@
import type { AppNotification } from "./api";
import type { Notification as ClientNotif } from "./notifications";
// The notification center's order, in ONE rule for both sources. It used to be two fixed sections,
// the server's above this browser's — so an admin's "access requests waiting" sat under up to a
// hundred server rows, week-old read "Download ready" notices among them. Now what asks for the
// reader comes first, then everything else as one time-ordered stream, and read rows older than a
// week fold away (kept, not deleted).
export type InboxEntry =
| { src: "server"; n: AppNotification; at: number }
| { src: "client"; n: ClientNotif; at: number };
export interface InboxOrder {
/** Unread, or waiting on an action: newest first. Never folded, whatever its age. */
needsYou: InboxEntry[];
/** The rest from the last week (or of no known date), newest first. */
recent: InboxEntry[];
/** Read rows older than `FOLD_AFTER_MS`, newest first — shown only on request. */
earlier: InboxEntry[];
}
export const FOLD_AFTER_MS = 7 * 24 * 3600 * 1000;
// A row of no known date (a server row stored without one) sorts last and never folds: its age is
// unknown, and hiding it on a guess is how a row goes missing.
const NO_DATE = Number.NEGATIVE_INFINITY;
function serverAt(n: AppNotification): number {
const at = n.created_at ? Date.parse(n.created_at) : NaN;
return Number.isNaN(at) ? NO_DATE : at;
}
/** A row's key across both sources: their ids are separate sequences, and they share one list now. */
export const keyOf = (src: InboxEntry["src"], id: number): string => `${src}:${id}`;
export const entryKey = (e: InboxEntry): string => keyOf(e.src, e.n.id);
/** Whether a client notice asks for the reader by what it is: an access-requests nudge for as long
* as it exists (its producer removes it when nothing is pending), a notice that waits on an
* interaction until it is dealt with. */
export const clientAsks = (n: ClientNotif): boolean =>
n.meta?.kind === "access-requests" || (n.requiresInteraction && !n.dismissed);
export function orderInbox(
server: readonly AppNotification[],
client: readonly ClientNotif[],
/** `held`: the rows that asked earlier in this visit (entry keys). They keep their place once read —
* a row marked read must not jump to another list under the reader, taking the keyboard focus to
* <body> as it remounts there — and they are how a client notice stays up at all: opening the
* center marks every client notice read, so "unread" alone would empty the band as it renders. */
{ now, held }: { now: number; held: ReadonlySet<string> },
): InboxOrder {
const out: InboxOrder = { needsYou: [], recent: [], earlier: [] };
const place = (e: InboxEntry, asks: boolean) => {
if (asks) out.needsYou.push(e);
else if (e.at !== NO_DATE && now - e.at > FOLD_AFTER_MS) out.earlier.push(e);
else out.recent.push(e);
};
for (const n of server)
place({ src: "server", n, at: serverAt(n) }, !n.read || held.has(keyOf("server", n.id)));
for (const n of client)
place(
{ src: "client", n, at: n.ts },
!n.read || held.has(keyOf("client", n.id)) || clientAsks(n),
);
// Newest first; equal times keep their source's own order (Array.sort is stable).
const newest = (a: InboxEntry, b: InboxEntry) => (b.at === a.at ? 0 : b.at > a.at ? 1 : -1);
out.needsYou.sort(newest);
out.recent.sort(newest);
out.earlier.sort(newest);
return out;
}
@@ -0,0 +1,206 @@
// @vitest-environment jsdom
//
// Back to a page whose item changed lists while it was away. The notification center holds a row
// that asked for the reader in "Needs you" for the visit; on the next visit the same row, read now,
// sits in the stream below. The restore matched the unnamed list by its place, missed the name there
// and fell back to the saved index — the focus landed on the neighbour, and Enter opened the wrong
// notification. Its own file: listNav keeps module-level state.
import { afterEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, render } from "@testing-library/react";
import { useRef } from "react";
import {
NAV_REVEAL_EVENT,
navItemAttrs,
navPosition,
pendingNavName,
restoreNavPosition,
useListNav,
} from "./listNav";
afterEach(cleanup);
// `count`: a virtualized list's, which counts rows it has yet to render.
function List({ items, count }: { items: string[]; count?: number }) {
const ref = useRef<HTMLDivElement>(null);
useListNav(ref, { enabled: true, count });
return (
<div ref={ref}>
{items.map((t, i) => (
<div key={`${t}-${i}`} {...navItemAttrs(i, t)}>
<button data-nav-open="">{t}</button>
</div>
))}
</div>
);
}
// `tray`: a list of the app's own, outside the page (the running downloads), whose rows can share a
// name with the page's.
const Page = ({
lists,
tray,
counts = [],
}: {
lists: string[][];
tray?: string[];
counts?: number[];
}) => (
<>
<main>
{lists.map((items, i) => (
<List key={i} items={items} count={counts[i]} />
))}
</main>
{tray && <List items={tray} />}
</>
);
const button = (name: string) =>
[...document.querySelectorAll("button")].find((b) => b.textContent === name)!;
const focused = () => document.activeElement?.closest("[data-nav-index]")?.textContent;
const wait = (ms: number) => act(() => new Promise((r) => setTimeout(r, ms)));
async function leaveAndReturn(
before: string[][],
from: string,
after: string[][],
tray?: string[],
) {
const { unmount } = render(<Page lists={before} tray={tray} />);
button(from).focus();
const pos = navPosition()!;
unmount(); // the page switch
render(<Page lists={after} tray={tray} />); // Back
const cancel = restoreNavPosition(pos);
await wait(120);
cancel();
}
describe("Back to an item that moved to another list", () => {
it("finds it by its name in the list it moved to, not its neighbour at the old place", async () => {
await leaveAndReturn([["subscribed", "download"], ["older"]], "subscribed", [
["download"],
["subscribed", "older"],
]);
expect(focused()).toBe("subscribed");
});
it("finds it when the list it left is gone altogether", async () => {
await leaveAndReturn([["subscribed"], ["older"]], "subscribed", [["subscribed", "older"]]);
expect(focused()).toBe("subscribed");
});
it("does not guess between two items of that name elsewhere: the saved place", async () => {
await leaveAndReturn([["twin", "download"], ["older"]], "twin", [
["download"],
["twin", "older", "twin"],
]);
expect(focused()).toBe("download");
});
it("brings an item found in another list into view; one in its own list stays put", async () => {
// The scroll restore put the page where the item WAS: found elsewhere, it would hold the focus
// off screen.
const reveal = vi.fn();
Element.prototype.scrollIntoView = reveal;
// ...and tells the page's scroll restore, which would otherwise put the old offset back over it.
const told = vi.fn();
document.addEventListener(NAV_REVEAL_EVENT, told);
await leaveAndReturn([["subscribed", "download"], ["older"]], "subscribed", [
["download"],
["subscribed", "older"],
]);
expect(reveal).toHaveBeenCalledTimes(1);
expect(told).toHaveBeenCalledTimes(1);
cleanup();
reveal.mockClear();
told.mockClear();
await leaveAndReturn([["subscribed", "download"]], "download", [["download", "subscribed"]]);
expect(focused()).toBe("download");
expect(reveal).not.toHaveBeenCalled();
expect(told).not.toHaveBeenCalled();
document.removeEventListener(NAV_REVEAL_EVENT, told);
});
it("never takes it from a list outside the page: the download tray's row of that name", async () => {
// A feed card and its download in the tray are both named by the video's title.
await leaveAndReturn(
[["subscribed", "download"]],
"subscribed",
[["download"]],
["subscribed"],
);
expect(focused()).toBe("download");
});
it("waits for its own list to render the place before looking in another one", async () => {
// A virtualized list puts its rows back a frame after the page: the item is still to come at
// the first look, and the one of that name in the rail below is not it.
const { unmount } = render(<Page lists={[["older", "subscribed"], ["subscribed-2"]]} />);
button("subscribed").focus();
const pos = navPosition()!;
unmount();
const { rerender } = render(<Page lists={[["older"], ["subscribed"]]} counts={[2]} />);
const cancel = restoreNavPosition(pos);
await wait(60);
rerender(<Page lists={[["older", "subscribed"], ["subscribed"]]} counts={[2]} />);
await wait(120);
cancel();
expect(document.activeElement?.closest("main > div")).toBe(
document.querySelector("main")!.firstElementChild,
);
});
it("looks in another list at its last look when its own never renders the place it counts", async () => {
vi.useFakeTimers();
try {
const { unmount } = render(<Page lists={[["older", "subscribed"], ["subscribed-2"]]} />);
button("subscribed").focus();
const pos = navPosition()!;
unmount();
// Its own list still counts two, and keeps showing one; the item is in the next list.
render(<Page lists={[["older"], ["subscribed"]]} counts={[2]} />);
const cancel = restoreNavPosition(pos);
await act(async () => vi.advanceTimersByTimeAsync(1000));
expect(focused()).toBeUndefined(); // still giving its own list the chance
await act(async () => vi.advanceTimersByTimeAsync(1100));
expect(focused()).toBe("subscribed");
cancel();
} finally {
vi.useRealTimers();
}
});
});
describe("the name a Back is still looking for", () => {
const pos = { list: 0, lists: 1, index: 0, name: "subscribed" };
it("is there while it looks, and gone once cancelled", () => {
const cancel = restoreNavPosition(pos);
expect(pendingNavName()).toBe("subscribed");
cancel();
expect(pendingNavName()).toBeNull();
});
it("is gone once the focus went somewhere else", async () => {
render(<button>elsewhere</button>);
const cancel = restoreNavPosition(pos);
button("elsewhere").focus();
await wait(80);
expect(pendingNavName()).toBeNull();
cancel();
});
it("is gone once it gave up", async () => {
vi.useFakeTimers();
try {
const cancel = restoreNavPosition(pos);
await vi.advanceTimersByTimeAsync(2100);
expect(pendingNavName()).toBeNull();
cancel();
} finally {
vi.useRealTimers();
}
});
});
+97 -22
View File
@@ -42,6 +42,15 @@ const lists = new Map<HTMLElement, NavList>();
// The item we gave a tabindex to, so the next move can take it back — and whether we named it too.
let roved: HTMLElement | null = null;
let named = false;
// A named item's label follows its spoken state while it holds the focus: Mark read hands the
// focus to the row BEFORE the row reads read, and the label given then said "unread" until the
// keyboard moved on.
const relabel =
typeof MutationObserver === "undefined"
? null
: new MutationObserver(() => {
if (named && roved) roved.setAttribute("aria-label", spokenName(roved));
});
const INDEX = "data-nav-index";
const LIST = "data-nav-list";
@@ -56,14 +65,24 @@ const REVEAL_FRAMES = 10;
* `inset` draws the keyboard ring INSIDE the item. The ring sits 2 px outside by default, which a
* card with a gap round it has room for; an item flush against its neighbours (a log line) or against
* the edge of a clipping card (a Plex playlist show header) does not: the ring ran past the list, or
* was clipped away entirely. A table row needs no flag: index.css insets every `tr` by its tag. */
* was clipped away entirely. A table row needs no flag: index.css insets every `tr` by its tag.
*
* `label` is what is SPOKEN instead of `name`, when it carries a state the item can lose while the
* page is away (a notification's "unread"): `name` is also how Back finds the item again, and a
* name that changed with the state would miss it. */
export const navItemAttrs = (
index: number,
name?: string | null,
{ inset = false }: { inset?: boolean } = {},
): { "data-nav-index": number; "data-nav-name"?: string; "data-nav-inset"?: "" } => ({
{ inset = false, label }: { inset?: boolean; label?: string } = {},
): {
"data-nav-index": number;
"data-nav-name"?: string;
"data-nav-label"?: string;
"data-nav-inset"?: "";
} => ({
[INDEX]: index,
...(name ? { "data-nav-name": name } : null),
...(label ? { "data-nav-label": label } : null),
...(inset ? { "data-nav-inset": "" } : null),
});
@@ -204,11 +223,23 @@ function itemName(el: HTMLElement): string {
).trim();
}
/** What a screen reader hears while the item holds the focus: its `label` when it gives one. */
const spokenName = (el: HTMLElement): string => el.getAttribute("data-nav-label") || itemName(el);
/** The event an item brought into view sends up its page: a scroll restore still under way gives the
* page up to it (`ui/PageScroller`) — on Back, an item found in another list than the one it was
* left in is not where the restored offset shows, and the restore's next frame scrolled it away. */
export const NAV_REVEAL_EVENT = "navreveal";
export const revealedNavItem = (el: HTMLElement): void => {
el.dispatchEvent(new Event(NAV_REVEAL_EVENT, { bubbles: true }));
};
function focusItem(el: HTMLElement, reveal = true): void {
if (roved !== el) {
if (named) roved?.removeAttribute("role");
if (named) roved?.removeAttribute("aria-label");
roved?.removeAttribute("tabindex");
relabel?.disconnect();
roved = null;
named = false;
// An item that is a Tab stop in its own right (a native <button> tile, a role=button card with
@@ -219,7 +250,7 @@ function focusItem(el: HTMLElement, reveal = true): void {
// A card root is a plain <div>: focused, it has no role and no name, and a screen reader read it
// as an unlabelled run of text. While it holds the focus it is a group named after what Enter
// opens. A row (<tr>) keeps its own role.
const name = itemName(el);
const name = spokenName(el);
if (
el.tagName === "DIV" &&
name &&
@@ -229,13 +260,17 @@ function focusItem(el: HTMLElement, reveal = true): void {
el.setAttribute("role", "group");
el.setAttribute("aria-label", name);
named = true;
relabel?.observe(el, { attributeFilter: ["data-nav-label", "data-nav-name"] });
}
}
}
el.focus({ preventScroll: true });
// `nearest` + the item's scroll margins: a visible item does not move, an item under the floating
// header or past the bottom edge scrolls just far enough to clear it.
if (reveal) el.scrollIntoView?.({ block: "nearest" });
if (reveal) {
el.scrollIntoView?.({ block: "nearest" });
revealedNavItem(el);
}
}
function focusIndex(
@@ -459,18 +494,37 @@ export function navPosition(): NavPosition | null {
// look — on a timer, not animation frames: a hidden tab runs none.
const RESTORE_MS = 2000;
const RESTORE_POLL_MS = 50;
// The restore under way, while it looks for its item.
let pending: NavPosition | null = null;
/** The item in `list` to hand the focus back to: the saved place while it still holds the saved
/** The item to hand the focus back to: in `list`, the saved place while it still holds the saved
* name, else the nearest item of that name (names repeat — a log console's identical request
* lines), else the saved place. */
function restoreTarget(list: NavList, pos: NavPosition): HTMLElement | null {
const at = itemAt(list, pos.index);
if (!pos.name || (at && itemName(at) === pos.name)) return at;
const distance = (el: HTMLElement) => Math.abs(indexOf(el) - pos.index);
const named = ownItems(list.el)
.filter((it) => itemName(it) === pos.name)
.sort((a, b) => distance(a) - distance(b));
return named[0] ?? at;
* lines). Then the one item of that name in another of the page's lists: an item can change lists
* while the page was away (a notification asked for the reader on the visit it was opened from and
* sits in the stream on the next), and the place left behind is now its neighbour's. Only when the
* name is the page's alone — of two, either could be the one — and only the PAGE's lists: the
* running-downloads tray is the app's, on every page, and its row of a download is named like the
* feed card it came from. Not while `list` has yet to render a saved place it still counts (a
* virtualized list puts its rows back a frame after the page), until the `last` look: the item is
* likely still to come there. Else the saved place. */
function restoreTarget(
all: readonly NavList[],
list: NavList | undefined,
pos: NavPosition,
last: boolean,
): HTMLElement | null {
const at = list ? itemAt(list, pos.index) : null;
if (list && (!pos.name || (at && itemName(at) === pos.name))) return at;
if (!pos.name) return null;
const named = (l: NavList) => ownItems(l.el).filter((it) => itemName(it) === pos.name);
if (list) {
const distance = (el: HTMLElement) => Math.abs(indexOf(el) - pos.index);
const here = named(list).sort((a, b) => distance(a) - distance(b));
if (here[0]) return here[0];
}
if (list && !at && pos.index < list.count() && !last) return null;
const [only, ...more] = all.filter((l) => l.el.closest("main")).flatMap(named);
return only && more.length === 0 ? only : at;
}
/** Focus the item at `pos` once its list is on screen again. A NAMED list (a rail) is found by its
@@ -478,15 +532,21 @@ function restoreTarget(list: NavList, pos: NavPosition): HTMLElement | null {
* watched in between, after the page's cache expired — shifts every place after it, and matching by
* place landed the focus in the wrong rail. An unnamed list only by its
* place, and only once the page has exactly as many lists as when it was left: with more or fewer,
* list N may be another list, and <body> is the honest outcome. Gives up when the time is up, and at
* list N may be another list, and <body> is the honest outcome — unless the item's name is the
* page's alone (`restoreTarget`). Gives up when the time is up, and at
* once when focus is already somewhere (the reader moved on, a dialog took it). The item is focused
* where the scroll restore put it, never scrolled to. (A stand-in the focus keeper placed when the view
* where the scroll restore put it, never scrolled to — but one found in another list is brought into
* view. (A stand-in the focus keeper placed when the view
* it held was swapped away counts as untouched, like <body>.) Returns a cancel. */
export function restoreNavPosition(pos: NavPosition): () => void {
const deadline = Date.now() + RESTORE_MS;
let timer: ReturnType<typeof setTimeout> | undefined;
pending = pos;
const done = () => {
if (pending === pos) pending = null;
};
const attempt = () => {
if (!focusIsUnclaimed()) return;
if (!focusIsUnclaimed()) return done();
const all = ordered();
const list = pos.label
? all.find((l) => labelOf(l) === pos.label)
@@ -499,18 +559,33 @@ export function restoreNavPosition(pos: NavPosition): () => void {
// The saved place still holding the saved name wins, and among several items of that name the
// nearest one: names repeat (a log console's `http.request GET /api/feed 200` lines, two
// downloads of one video), and the first of them is rarely the one left behind.
const el = list ? restoreTarget(list, pos) : null;
if (el) return focusItem(el, false);
if (Date.now() < deadline) timer = setTimeout(attempt, RESTORE_POLL_MS);
const last = Date.now() + RESTORE_POLL_MS >= deadline;
const el = restoreTarget(all, list, pos, last);
// Where the scroll restore put it — unless it is found in another list than the one it was left
// in: the restored scroll is the old place's, and the item would hold the focus off screen.
if (el) {
done();
return focusItem(el, !list?.el.contains(el));
}
if (last) done();
else timer = setTimeout(attempt, RESTORE_POLL_MS);
};
// Not inside the popstate dispatch that landed: a sub-view's own listener (`useHistorySubview`)
// may run after ours and has not switched the view yet — focus still sits in the view being left,
// and "focus is already somewhere" would give up for good (measured in Chrome:
// Plex show → Back left focus on <body>). One task later the view has rendered.
timer = setTimeout(attempt, 0);
return () => clearTimeout(timer);
return () => {
clearTimeout(timer);
done();
};
}
/** The name of the item a Back is still looking for, while it looks: a page that keeps some of its
* rows folded away (the notification center's Earlier) opens the fold holding it — a list it does
* not render is one the restore cannot find the item in. Read it as the page mounts. */
export const pendingNavName = (): string | null => pending?.name ?? null;
/** Register `ref` as a keyboard-navigable list while `enabled`. A virtualized list must say how many
* items it has (`count` — the loaded ones, for an infinite list), how many per row (`cols`) and how
* to scroll an unmounted item into view (`reveal`). A list that mounts everything omits all three:
+16 -2
View File
@@ -10,9 +10,12 @@ import { installClientLog } from "./logHooks";
const appCopy = (text: string | null) =>
["Refresh", "Frissítés"].includes(text?.trim() ?? "") ? "Refresh" : null;
// The pages' typed keys, as main.tsx hands them over from the module definitions.
const TYPED = ["q", "fq", "yt"];
beforeAll(() => {
installClientLog(appCopy);
installClientLog(appCopy); // a hot reload's second call must not wrap History twice
installClientLog(appCopy, TYPED);
installClientLog(appCopy, TYPED); // a hot reload's second call must not wrap History twice
expect(events().map((e) => e.event)).toEqual(["app.start", "nav.view"]);
clear();
});
@@ -56,6 +59,17 @@ describe("client log hooks", () => {
});
});
it("keeps a page's own search box out below TRACE too", () => {
setLevel("DEBUG");
window.history.pushState({ sfPage: "files" }, "", "/?folder=all&fq=private+words&yt=lofi");
expect(views()[0]!.attrs!.values).toEqual({ folder: "all" });
expect(JSON.stringify(views())).not.toContain("private");
setLevel("TRACE");
window.history.pushState({ sfPage: "files" }, "", "/?folder=all&fq=private+words");
expect(views()[1]!.attrs!.values).toEqual({ folder: "all", fq: "private words" });
});
it("records an overlay opening as a view of its own, and Back as a pop", () => {
window.history.pushState({ sfPage: "feed", _ov: 1 }, "");
// What Back does: the browser restores the previous entry's state (the unwrapped prototype
+9 -4
View File
@@ -13,9 +13,10 @@ import { FRONTEND_SHA, FRONTEND_VERSION } from "./version";
import { enabled, errorAttrs, log } from "./log";
import { pathTemplate } from "./http";
// URL parameters that carry what the user TYPED — search text. Logged only at TRACE ("Teljes").
// Every other parameter is filter/sort/view state: its NAME is kept at INFO, its value at DEBUG.
const TYPED_PARAMS = new Set(["q", "keywords", "search"]);
// URL parameters that carry what the user TYPED — a search, a column's text filter. Logged only at
// TRACE ("Teljes"). Every other parameter is filter/sort/view state: its NAME is kept at INFO, its
// value at DEBUG. The shell has none; each page's join at install (ModuleDef.typedUrlKeys).
const TYPED_PARAMS = new Set<string>();
type Via = "start" | "push" | "replace" | "pop";
@@ -168,9 +169,13 @@ let installed = false;
/** Install the hooks. Idempotent: a second call (a hot reload) must not wrap History twice.
* `appCopy` turns on-screen app copy into its English wording (i18n/appCopy.ts) — passed in, so this
* module stays free of the i18n runtime. */
export function installClientLog(appCopy: AppCopy = () => null): void {
export function installClientLog(
appCopy: AppCopy = () => null,
typedParams: readonly string[] = [],
): void {
if (installed) return;
installed = true;
for (const k of typedParams) TYPED_PARAMS.add(k);
log.info("app.start", "app loaded", {
version: FRONTEND_VERSION,
+14
View File
@@ -44,4 +44,18 @@ export type ModuleDef = {
// Static, unlike the page: it is on the boot path by design. It reads no other module's store, so
// the order the stores nest in does not matter (moduleStores.contract.test).
Store?: ComponentType<{ children: ReactNode }>;
// Every address-bar key this page's view writes: its filters, sort, tab, the item it shows. The URL
// IS the view, so a bookmark reopens it. The shell clears them all on a page switch, and opens a page
// with no other page's keys in its address (NavigationProvider), so one page's state never rides
// along onto another's URL. Empty for a page with nothing of its own in the URL. Each key belongs to
// one module and none is a shell key (moduleUrl.contract.test).
urlKeys: readonly string[];
// Those of them that carry what the user TYPED (a search box's text, a column filter map holding a
// text filter): the client log keeps their values out below its most detailed level (lib/logHooks).
// moduleUrl.contract.test sorts every key of urlKeys as typed or not, so a new one is decided.
typedUrlKeys?: readonly string[];
// Its page plays YouTube videos in the player and reopens it from an address that names one (a
// reload, a bookmark — lib/playerUrlState), with its own list as the queue. A page without it gets
// the shell's player for such an address: the video alone.
playsVideos?: boolean;
};
+42
View File
@@ -0,0 +1,42 @@
// The YouTube player's address-bar keys. The player opens over any page (the feed, a channel page, Home,
// a playlist, a channel's watched videos), so its keys are the shell's: no module owns them, a page
// switch clears them, and the page under it keeps its own. The player names them in its own history
// entry (lib/history's `useBackToClose`), so Back lands on the page as it was, without the player.
// The list it plays from is the page's: the feed's filters, the open playlist (`pl`) — already named.
// No position: the player resumes from the server's (`video_states`), which is where it was left.
const PLAYER_WATCH_KEY = "watch"; // the item of the list playing now
const PLAYER_RELATED_KEY = "wrel"; // a related video played in place over it
const PLAYER_PANEL_KEY = "wtab"; // the wide panel's tab, when it is not the description
export const PLAYER_KEYS = [PLAYER_WATCH_KEY, PLAYER_RELATED_KEY, PLAYER_PANEL_KEY] as const;
export type PlayerPanelTab = "description" | "related";
export type PlayerUrlState = { watch: string; related: string | null; panel: PlayerPanelTab };
/** The player's keys for its entry. The panel's tab is written only when it is not the default: no
* browser remembers it, so a link without one opens the description as this one would. */
export function playerParamUpdates(state: PlayerUrlState): Record<string, string | null> {
return {
[PLAYER_WATCH_KEY]: state.watch,
[PLAYER_RELATED_KEY]: state.related,
[PLAYER_PANEL_KEY]: state.panel === "related" ? "related" : null,
};
}
/** The player an address names, or null when it names none. */
function playerFrom(params: URLSearchParams): PlayerUrlState | null {
const watch = params.get(PLAYER_WATCH_KEY);
if (!watch) return null;
return {
watch,
related: params.get(PLAYER_RELATED_KEY) || null,
panel: params.get(PLAYER_PANEL_KEY) === "related" ? "related" : "description",
};
}
/** The player the address names now: read by a host as it mounts (a reload, a bookmark), and by the
* player as it opens. No entry but the player's own carries these keys once the history has caught
* up, so a host mounted later (a page switch back) finds none. */
export function linkedPlayer(): PlayerUrlState | null {
return playerFrom(new URLSearchParams(window.location.search));
}
+52
View File
@@ -0,0 +1,52 @@
import { decodeSortParam, encodeSortParam, type SortState } from "./columnSort";
import { decodeFilterMap, encodeFilterMap } from "./filterMapParam";
import { type FilterMap } from "./tableColumns";
// The Playlists page's address-bar keys: the playlist shown (`pl`), the rail's name search (`plq`), and
// the open playlist's view — its track sort, column filters and grouping (`plsort`/`plf`/`plgroup`).
// The playlist is remembered per account too (PlaylistsProvider); the search and the view are
// remembered nowhere else (the view starts over on every playlist), so each of those is written only
// when it differs from the default: its key's absence IS the default.
export const PLAYLISTS_KEYS = ["pl", "plq", "plsort", "plf", "plgroup"] as const;
export type PlaylistView = { sort: SortState; filters: FilterMap; groupBy: boolean };
// The neutral view: "#" ascending IS the stored order, so the header can show a real arrow for it
// instead of the list looking unsorted (or, worse, looking sorted by whatever column the stored
// order happens to correlate with — the user read a channel-grouped playlist as sorted by Channel).
export const PLAYLIST_STORED_SORT: SortState = { key: "pos", dir: "asc" };
export function isStoredSort(s: SortState): boolean {
return s?.key === PLAYLIST_STORED_SORT?.key && s?.dir === PLAYLIST_STORED_SORT?.dir;
}
/** The address-bar delta for the page's store: the playlist shown and the rail's search (each null
* when not named). */
export function playlistsParams(
selected: number | null,
search: string,
): Record<string, string | null> {
return { pl: selected != null ? String(selected) : null, plq: search || null };
}
/** The address-bar delta for an open playlist's view; `null` clears it (no playlist open). */
export function playlistViewParamUpdates(v: PlaylistView | null): Record<string, string | null> {
if (!v) return { plsort: null, plf: null, plgroup: null };
return {
// An unsorted view (a header clicked through to "none") is the stored order too.
plsort: v.sort && !isStoredSort(v.sort) ? encodeSortParam(v.sort) : null,
plf: encodeFilterMap(v.filters),
plgroup: v.groupBy ? "1" : null,
};
}
/** The view an address names; what it leaves out is the default. */
export function playlistViewFrom(params: URLSearchParams): PlaylistView {
const sort = params.get("plsort");
const filters = params.get("plf");
return {
sort: (sort != null && decodeSortParam(sort)) || PLAYLIST_STORED_SORT,
filters: filters != null ? decodeFilterMap(filters) : {},
groupBy: params.get("plgroup") === "1",
};
}
@@ -0,0 +1,119 @@
// @vitest-environment jsdom
//
// The finish latch's refusal path, against a real query cache.
//
// A refusal answers ONE finish: a replay begun while it was in flight starts a new watch, and a
// refusal that lands after it must not take back the finish that watch later makes — that left the
// cache saying unwatched, mid-episode, for an item the server had watched.
//
// And a refusal while the player is still on the item (the up-next card, the default end state) must
// not empty the detail that player observes: the card is gated on it, so it dropped, came back with its
// countdown restarted when the refetch landed, and never came back if that refetch failed too. The
// entry is dropped when the player leaves, where the next open has to fetch the truth.
import { describe, it, expect, vi, afterEach, beforeEach } from "vitest";
import { act, cleanup, renderHook } from "@testing-library/react";
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
import { type ReactNode } from "react";
import { usePlexProgress } from "./plexPlayerHooks";
import { api, type PlexItemDetail } from "./api";
import { qk } from "./queryKeys";
import i18n, { plexLang } from "../i18n";
const RK = "4242";
const key = () => qk.plexItem(RK, plexLang(i18n.language));
const detail = { id: RK, status: "new", position_seconds: 600 } as unknown as PlexItemDetail;
function deferred() {
let reject: (e: unknown) => void = () => {};
const promise = new Promise((_, rej) => {
reject = rej;
});
return { promise, reject };
}
const flush = () =>
act(async () => {
await Promise.resolve();
await Promise.resolve();
});
describe("usePlexProgress — a refused finish", () => {
let qc: QueryClient;
let video: HTMLVideoElement;
beforeEach(() => {
qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
video = document.createElement("video");
vi.spyOn(api, "plexProgress").mockResolvedValue({ ok: true } as never);
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
const setup = (observe: boolean) => {
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={qc}>{children}</QueryClientProvider>
);
// Stable, as the player's own refs are: the effect re-runs on a new ref object, and a re-run
// starts the item over.
const refs = {
videoRef: { current: video },
absRef: { current: 1500 },
durationRef: { current: 3000 },
};
return renderHook(
() => {
useQuery({
queryKey: key(),
queryFn: () => Promise.resolve(detail),
enabled: observe,
});
return usePlexProgress({
id: RK,
qc,
...refs,
});
},
{ wrapper },
);
};
it.each([
["before", true],
["after", false],
])(
"a refusal landing after a replay, %s its next finish, takes back neither",
async (_, early) => {
qc.setQueryData(key(), detail);
const { result } = setup(false);
const first = deferred();
act(() => result.current.finish(first.promise));
act(() => void video.dispatchEvent(new Event("play"))); // the viewer plays it again
if (early) {
first.reject(new Error("refused")); // only now is the first finish refused
await flush();
}
act(() => result.current.finish(Promise.resolve()));
await flush();
if (!early) {
first.reject(new Error("refused"));
await flush();
}
act(() => result.current.settle());
expect(qc.getQueryData(key())).toMatchObject({ status: "watched", position_seconds: 0 });
},
);
it("keeps the detail the still-open player observes, and drops it when the player leaves", async () => {
const { result, unmount } = setup(true);
await flush();
expect(qc.getQueryData(key())).toBeDefined();
const refused = deferred();
act(() => result.current.finish(refused.promise));
refused.reject(new Error("refused"));
await flush();
expect(qc.getQueryData(key())).toBeDefined();
unmount();
expect(qc.getQueryData(key())).toBeUndefined();
});
});
+28 -8
View File
@@ -214,6 +214,14 @@ export function usePlexProgress(opts: {
// write; this closes the other three. What the refusal does take back is the
// CLAIM: the cache must not say watched, and `settle` must not re-assert it on the way out.
let finishRefused = false;
// Whether the player has left the item (`settle` ran): what a refusal does to the cached detail
// depends on whether the player is still observing it.
let left = false;
// Which finish a refusal answers. A replay starts a new watch, so a refusal of an earlier finish
// that lands after it must not raise `finishRefused` for the finish that watch makes later — the
// leave then skipped its watched patch, and the cache said unwatched, mid-item, for an item the
// server had watched.
let finishGen = 0;
// `final` = a settled checkpoint (pause / page-hide / leaving the player) vs. the periodic tick.
// Only final checkpoints get mirrored to a linked Plex account (backend-side debounce), so Plex
// sees the resume position when the user actually stops — not a timeline call every 10 seconds.
@@ -261,6 +269,7 @@ export function usePlexProgress(opts: {
const onPlayAgain = () => {
finished = false;
finishRefused = false;
finishGen = finishGen + 1;
};
video?.addEventListener("play", onPlayAgain);
// Back (unmount) persists the position server-side via flush(), but reopening the same item in
@@ -273,12 +282,14 @@ export function usePlexProgress(opts: {
const settle = () => {
// Match the language-keyed detail query so the optimistic resume patch lands.
const key = qk.plexItem(id, plexLang(i18n.language));
left = true;
if (finished) {
// A refused finish claims nothing: the server has the item unwatched at the position the
// rollback restored, and the catch below has already dropped this entry, so the next open
// fetches the truth. Re-patching "watched / 0" here would put back the very lie the
// refusal handler removed.
if (!finishRefused)
// rollback restored. Re-patching "watched / 0" here would put back the very lie the refusal
// handler took back, and the entry the player kept observing (see the catch below) may
// still be the one from before the rollback — dropped, the next open fetches the truth.
if (finishRefused) qc.removeQueries({ queryKey: key });
else
qc.setQueryData(key, (old) =>
old ? { ...old, status: "watched", position_seconds: 0 } : old,
);
@@ -293,6 +304,9 @@ export function usePlexProgress(opts: {
settleRef.current = settle;
finishRef.current = (confirmed?: Promise<unknown>) => {
finished = true;
finishRefused = false;
finishGen = finishGen + 1;
const gen = finishGen;
// The latch has to go up BEFORE the media pauses, so it cannot wait for the server. If the
// watched write is then refused, what is taken back is the CLAIM, not the latch (see
// `finishRefused`): the cached detail said watched / position 0 while the server still had
@@ -306,6 +320,7 @@ export function usePlexProgress(opts: {
// position left an unwatched item with a ~99% bar that reopened in its last seconds.
const ended = video?.ended === true;
void confirmed?.catch(() => {
if (gen !== finishGen) return;
finishRefused = true;
// Restore the resume point the finish replaced — but ONLY where there is one to restore.
// On the play-to-the-end path `pos` IS the end of the media, and the backend reads a
@@ -316,10 +331,15 @@ export function usePlexProgress(opts: {
// credits-skip caller captures a mid-episode position and is unaffected.
if (!ended && pos > 0 && dur > 0 && pos <= dur - FINISH_MARGIN_S)
api.plexProgress(id, pos, dur, true).catch(() => {});
// `settle` may already have patched the detail to watched / 0 on the way out. Dropping that
// entry rather than invalidating it: an invalidated query with no observer keeps serving its
// stale data, and this one is a lie — no data is better, the next open fetches the truth.
qc.removeQueries({ queryKey: qk.plexItem(id, plexLang(i18n.language)) });
// Still on the item (the up-next card is the default end state), the player observes this
// entry: emptying it dropped the card — gated on the detail — and its countdown restarted
// when the refetch landed, or the card never came back if that failed too. So it is
// refetched under the player, and dropped when the player leaves (`settle`). Already left,
// `settle` may have patched it to watched / 0 on the way out, and an invalidated query with
// no observer keeps serving that lie: dropped now, the next open fetches the truth.
const key = qk.plexItem(id, plexLang(i18n.language));
if (left) qc.removeQueries({ queryKey: key });
else void qc.invalidateQueries({ queryKey: key });
});
};
return () => {
+28 -7
View File
@@ -48,15 +48,36 @@ const BASE: PlexUrlState = {
};
describe("plexParamUpdates", () => {
it("emits nothing for the all-default state", () => {
it("writes the default view in full: this account remembers one a link must not inherit", () => {
expect(plexParamUpdates(BASE)).toEqual({
pscope: null,
psort: null,
pshow: null,
pf: null,
pscope: "both",
psort: "title:asc",
pshow: "all",
pf: "",
});
});
it("writes an unsorted view as such, so a link to it is not sorted by the remembered sort", () => {
const unsorted = { ...BASE, sort: null };
expect(plexParamUpdates(unsorted).psort).toBe("none");
const back = plexParamsToState(applyUpdates(plexParamUpdates(unsorted)), {
...BASE,
sort: { key: "year", dir: "desc" },
});
expect(back?.sort).toBeNull();
});
it("a link to the default view opens it over another remembered one", () => {
const params = applyUpdates(plexParamUpdates(BASE));
const back = plexParamsToState(params, {
scope: "movie",
sort: { key: "year", dir: "desc" },
show: "watched",
filters: RICH_FILTERS,
});
expect(back).toEqual(BASE);
});
it("clears every key when passed null (off-plex page)", () => {
expect(plexParamUpdates(null)).toEqual({
pscope: null,
@@ -66,7 +87,7 @@ describe("plexParamUpdates", () => {
});
});
it("emits only non-default keys", () => {
it("writes the view picked", () => {
const u = plexParamUpdates({
scope: "movie",
sort: { key: "year", dir: "desc" },
@@ -76,7 +97,7 @@ describe("plexParamUpdates", () => {
expect(u.pscope).toBe("movie");
expect(u.psort).toBe("year:desc");
expect(u.pshow).toBe("in_progress");
expect(u.pf).toBeNull();
expect(u.pf).toBe("");
});
});
+42 -20
View File
@@ -3,11 +3,12 @@
// urlState. Keys are NAMESPACED (`pscope`/`psort`/`pshow`/`pf`) rather than reusing the feed's bare
// `scope`/`sort`/`show`: FeedFiltersProvider actively STRIPS its own KEYS from the URL whenever the app
// is off the feed page, so a shared key would be deleted out from under the Plex page. The namespaced
// keys are Plex-unique (like `?v=`/`?pl`), so no other provider ever reads or clears them. Only non-
// default values are emitted, so URLs stay clean.
// keys are Plex-unique (like `?v=`/`?pl`), so no other provider ever reads or clears them. Every key is
// written on the page, its default too: a page opened without one takes this account's remembered view,
// which may not be the one bookmarked.
import { parsePlexFilters, plexFiltersToParams, type PlexFilters } from "./api";
import { decodeSortParam, encodeSortParam, type SortState } from "./columnSort";
import { PLEX_SORT_FALLBACK } from "./plexSort";
import { decodeSortParamOrNone, encodeSortParamOrNone, type SortState } from "./columnSort";
import { parsePlexField, type PlexSearchField } from "./plexSearch";
// The content state this mirrors. `sort` is the RAW provider SortState (scope-healed only at the point of
// use), so the user's real preference round-trips through the URL.
@@ -18,29 +19,29 @@ export interface PlexUrlState {
filters: PlexFilters;
}
const KEYS = ["pscope", "psort", "pshow", "pf"] as const;
export const PLEX_KEYS = ["pscope", "psort", "pshow", "pf"] as const;
const KEYS = PLEX_KEYS;
// The header search: its term and the field it searches. Both remembered per account, so both are
// always written on the page (an empty term too): a link without them would open with whatever this
// browser searched last. The field means something only beside a term.
export const PLEX_SEARCH_KEYS = ["pq", "pqf"] as const;
// The Plex sub-view's key (show, season, info, person… — modules/plex/plexSubUrl encodes it).
export const PLEX_SUB_KEY = "v";
const SCOPES = ["movie", "show", "both"];
const SHOWS = ["all", "unwatched", "in_progress", "watched"];
// Sort ⇄ `key:dir` (e.g. `year:desc`) via the shared codec in columnSort; the Plex default (`title:asc`)
// emits nothing.
function encodeSort(s: SortState): string | null {
if (!s || (s.key === PLEX_SORT_FALLBACK?.key && s.dir === PLEX_SORT_FALLBACK?.dir)) return null;
return encodeSortParam(s);
}
/** The address-bar delta for the Plex content state: each namespaced key mapped to its emitted value,
* or null to delete it (so a control back at its default clears the key). Pass `null` to clear ALL Plex
/** The address-bar delta for the Plex content state: each namespaced key mapped to its value (sort as
* `key:dir`, the shared columnSort codec; an empty filter set as `pf=`). Pass `null` to clear ALL Plex
* keys — used when the app is off the Plex page (localStorage still holds the state; it re-mirrors on
* return). Feed the result into urlWithParams(). */
export function plexParamUpdates(state: PlexUrlState | null): Record<string, string | null> {
if (!state) return { pscope: null, psort: null, pshow: null, pf: null };
const pf = plexFiltersToParams(state.filters).toString();
return {
pscope: state.scope && state.scope !== "both" ? state.scope : null,
psort: encodeSort(state.sort),
pshow: state.show && state.show !== "all" ? state.show : null,
pf: pf || null,
pscope: state.scope || "both",
psort: encodeSortParamOrNone(state.sort),
pshow: state.show || "all",
pf,
};
}
@@ -54,8 +55,8 @@ export function hasPlexParams(params: URLSearchParams): boolean {
export function plexParamsToState(params: URLSearchParams, base: PlexUrlState): PlexUrlState {
const scope = params.get("pscope");
const show = params.get("pshow");
const psort = params.get("psort");
const sort = psort != null ? (decodeSortParam(psort) ?? base.sort) : base.sort;
const linkedSort = decodeSortParamOrNone(params.get("psort"));
const sort = linkedSort === undefined ? base.sort : linkedSort;
return {
scope: scope && SCOPES.includes(scope) ? scope : base.scope,
sort,
@@ -65,3 +66,24 @@ export function plexParamsToState(params: URLSearchParams, base: PlexUrlState):
: base.filters,
};
}
export type PlexSearchUrlState = { q: string; field: PlexSearchField };
/** The address-bar delta for the header search; `null` clears it (off the Plex page). */
export function plexSearchParamUpdates(
state: PlexSearchUrlState | null,
): Record<string, string | null> {
if (!state) return { pq: null, pqf: null };
const q = state.q.trim();
return { pq: q, pqf: q ? state.field : null };
}
/** What of the header search an address names (absent: the remembered value applies). */
export function plexSearchFrom(params: URLSearchParams): Partial<PlexSearchUrlState> {
const q = params.get("pq");
const field = params.get("pqf");
return {
...(q != null && { q }),
...(field != null && { field: parsePlexField(field) }),
};
}
+1
View File
@@ -33,6 +33,7 @@ describe("qk — single-id and scalar keys", () => {
it("returns [root, id]", () => {
expect(qk.channel("c1")).toEqual(["channel", "c1"]);
expect(qk.videoDetail("v1")).toEqual(["video-detail", "v1"]);
expect(qk.videoRow("v1")).toEqual(["video-row", "v1"]);
expect(qk.playlistMembership("v1")).toEqual(["playlist-membership", "v1"]);
expect(qk.plexItem("i1")).toEqual(["plex-item", "i1"]);
expect(qk.plexPlaylist(9)).toEqual(["plex-playlist", 9]);
+1
View File
@@ -32,6 +32,7 @@ export const qk = {
ytSearch: (q?: string | null, count?: number) =>
q !== undefined ? (["yt-search", q, count] as const) : (["yt-search"] as const),
videoDetail: (id: string) => ["video-detail", id] as const,
videoRow: (id: string) => ["video-row", id] as const,
related: (id?: string, region?: string) =>
id !== undefined ? (["related", id, region] as const) : (["related"] as const),
// This session's confirmed marks per video (lib/progressCache `markVideo`): no fetch behind it.
+10 -2
View File
@@ -1,8 +1,16 @@
import { LS, setTabRaw } from "./storage";
// The Settings page's tabs, and a helper to pre-select one before navigating there (a notice's link,
// a return from Google). useTabPersistedState reads the key when the page mounts, and the page mounts
// fresh on navigation. Kept out of SettingsPanel.tsx so a caller does not pull the page in with it.
// a return from Google). useTabPersistedState reads the key when the page mounts, and the page on
// screen hears it. Kept out of SettingsPanel.tsx so a caller does not pull the page in with it. The
// address-bar key the page mirrors its tab to is here too, beside the other pages' keys.
export const SETTINGS_TAB_KEY = "stab";
/** The address-bar delta for the Settings tab shown. */
export function settingsTabParams(tab: string | null): Record<string, string | null> {
return { [SETTINGS_TAB_KEY]: tab };
}
export type SettingsTabId =
| "appearance"
| "notifications"
+36 -8
View File
@@ -1,4 +1,4 @@
import { useCallback, useState } from "react";
import { useCallback, useEffect, useState } from "react";
// Central registry of every key the app keeps in the browser (localStorage, and a tab's
// sessionStorage). One place to see them all, rename safely, and avoid collisions — instead of
@@ -307,10 +307,11 @@ export function useAccountPersistedState(
// --- a page's sub-tab, per browser tab ---------------------------------------------------------
// Which sub-tab a page was left on (Settings, Configuration, Statistics, Users) is kept for THIS browser
// tab only — sessionStorage, the account's (see ownKey): it survives a reload and a trip to another page, and a new
// Which sub-tab a page was left on (Settings, Configuration, Users) is kept for THIS browser tab only —
// sessionStorage, the account's (see ownKey): it survives a reload and a trip to another page, and a new
// tab opens the page on its first sub-tab (the owner's call: a position remembered forever in
// localStorage made Configuration open on "Plex" in every fresh tab, as if that were its home).
// localStorage made Configuration open on "Plex" in every fresh tab, as if that were its home). The
// address names the tab too (the page mirrors it): a link or a bookmark that carries one wins.
/** The sub-tab stored for this browser tab, or null. */
function getTabRaw(base: string): string | null {
@@ -322,8 +323,7 @@ function getTabRaw(base: string): string | null {
}
}
/** Pre-select a page's sub-tab before navigating there (a "Review" link, the Google-link return). */
export function setTabRaw(base: string, value: string): void {
function writeTabRaw(base: string, value: string): void {
const k = ownKey(base);
if (!k) return;
try {
@@ -333,10 +333,23 @@ export function setTabRaw(base: string, value: string): void {
}
}
/** `useAccountPersistedState` for a page's sub-tab, kept per browser tab (see above). */
// A pre-selection made while the page is already on screen (a notice's link opened over Settings) has
// no mount to be read at, and the navigation to the same page is a no-op: the page's hook hears it.
const TAB_SELECT_EVENT = "siftlode:tab-select";
type TabSelect = { base: string; value: string };
/** Pre-select a page's sub-tab before navigating there (a "Review" link, the Google-link return). */
export function setTabRaw(base: string, value: string): void {
writeTabRaw(base, value);
window.dispatchEvent(new CustomEvent<TabSelect>(TAB_SELECT_EVENT, { detail: { base, value } }));
}
/** `useAccountPersistedState` for a page's sub-tab, kept per browser tab (see above). `urlKey`: the
* address-bar key the page mirrors its tab to — a tab it names is the one the page opens on. */
export function useTabPersistedState(
base: string,
fallback = "",
urlKey?: string,
): [string, (value: string) => void] {
const [value, setValue] = useState<string>(() => {
// The position used to live in localStorage; a value left there would never be read again.
@@ -348,12 +361,27 @@ export function useTabPersistedState(
/* ignore */
}
}
const linked = urlKey ? new URLSearchParams(window.location.search).get(urlKey) : null;
if (linked) {
// Kept for this browser tab too, so a later trip back to the page (its address cleared by the
// page switch) still opens it here.
writeTabRaw(base, linked);
return linked;
}
return getTabRaw(base) ?? fallback;
});
useEffect(() => {
function onSelect(e: Event) {
const { detail } = e as CustomEvent<TabSelect>;
if (detail.base === base) setValue(detail.value);
}
window.addEventListener(TAB_SELECT_EVENT, onSelect);
return () => window.removeEventListener(TAB_SELECT_EVENT, onSelect);
}, [base]);
const set = useCallback(
(next: string) => {
setValue(next);
setTabRaw(base, next);
writeTabRaw(base, next);
},
[base],
);
+17
View File
@@ -41,4 +41,21 @@ describe("a page's sub-tab, per browser tab", () => {
const { result } = renderHook(() => useTabPersistedState("siftlode.adminUsersTab", "roles"));
expect(result.current[0]).toBe("access");
});
it("opens on the tab the address names, and keeps it for this browser tab", () => {
setTabRaw("siftlode.settingsTab", "account");
window.history.replaceState(null, "", "/?page=settings&stab=tokens");
const { result, unmount } = renderHook(() =>
useTabPersistedState("siftlode.settingsTab", "appearance", "stab"),
);
expect(result.current[0]).toBe("tokens");
unmount();
// Back on the page later, through the rail (the page switch cleared its address).
window.history.replaceState(null, "", "/?page=settings");
expect(
renderHook(() => useTabPersistedState("siftlode.settingsTab", "appearance", "stab")).result
.current[0],
).toBe("tokens");
window.history.replaceState(null, "", "/");
});
});
+2 -2
View File
@@ -127,13 +127,13 @@ describe("a page opened at a path that starts with //", () => {
});
describe("filterParamUpdates", () => {
it("maps non-default filters to values and defaults to null (delete)", () => {
it("maps non-default filters to values and other defaults to null (delete)", () => {
const f: FeedFilters = { ...DEFAULTS, q: "react", tags: [3, 7], show: "watched" };
const upd = filterParamUpdates(f);
expect(upd.q).toBe("react");
expect(upd.tags).toBe("3,7");
expect(upd.show).toBe("watched");
expect(upd.sort).toBeNull(); // default "newest" is not emitted → cleared
expect(upd.sort).toBe("newest"); // the view and the order are always named, defaults too
expect(upd.scope).toBeNull();
});
+58 -13
View File
@@ -4,9 +4,11 @@
// bookmarkable/shareable — the old "Share view" workaround (and the whole-query stripUrlParams) is
// retired. Only non-default values are emitted so URLs stay clean. NOTE: the browser TAB title stays
// the short module/channel name (NavigationProvider owns document.title) — the query never leaks into it.
import { TAG_CATEGORIES, type FeedFilters } from "./api";
import { FEED_DEFAULT_SHOW, FEED_DEFAULT_SORT, TAG_CATEGORIES, type FeedFilters } from "./api";
import { CHANNEL_PAGE_KEYS } from "./channelPageUrlState";
import { PLAYER_KEYS } from "./playerUrlState";
const KEYS = [
export const FEED_KEYS = [
"q",
"show",
"sort",
@@ -29,12 +31,32 @@ const KEYS = [
"mindur",
"maxdur",
] as const;
const KEYS = FEED_KEYS;
// The keys the shell itself reads, whatever page is on screen: the page, the channel page and its view
// (it opens over any page, lib/channelPageUrlState), the YouTube player (the same, lib/playerUrlState),
// the welcome card's mode and the one-time entry links. No module may declare one of these
// (moduleUrl.contract.test); a page switch clears only the channel's and the player's.
export const SHELL_KEYS = [
"page",
"chan",
...CHANNEL_PAGE_KEYS,
...PLAYER_KEYS,
"m",
"link",
"oauth",
"admin",
"account",
"login",
"deleted",
"token",
] as const;
export function filtersToParams(f: FeedFilters): URLSearchParams {
const p = new URLSearchParams();
if (f.q) p.set("q", f.q);
if (f.show && f.show !== "unwatched") p.set("show", f.show);
if (f.sort && f.sort !== "newest") p.set("sort", f.sort);
if (f.show && f.show !== FEED_DEFAULT_SHOW) p.set("show", f.show);
if (f.sort && f.sort !== FEED_DEFAULT_SORT) p.set("sort", f.sort);
if (f.scope === "all") p.set("scope", "all");
// Library provenance filter (only meaningful in "all" scope); "organic" is the default.
if (f.scope === "all" && f.librarySource && f.librarySource !== "organic")
@@ -58,13 +80,19 @@ export function filtersToParams(f: FeedFilters): URLSearchParams {
}
/** Build the address-bar delta for the feed filters: each recognized filter key mapped to its emitted
* value, or null to delete it (so switching a filter back to its default clears the key). Pass `null`
* to clear ALL filter keys — used when leaving the feed, where the localStorage copy still holds them.
* Feed the result into urlWithParams(). */
* value, or null to delete it (so switching a filter back to its default clears the key) — except the
* view and the order, always written (defaults too): a feed address then always names its view, so a
* bookmark of the default feed opens the default feed, not whatever view the account stored since
* (an address naming none falls back to it). Pass `null` to clear ALL filter keys — used when leaving
* the feed, where the localStorage copy still holds them. Feed the result into urlWithParams(). */
export function filterParamUpdates(f: FeedFilters | null): Record<string, string | null> {
const p = f ? filtersToParams(f) : new URLSearchParams();
const out: Record<string, string | null> = {};
for (const k of KEYS) out[k] = p.get(k);
if (f) {
out.show = f.show || FEED_DEFAULT_SHOW;
out.sort = f.sort || FEED_DEFAULT_SORT;
}
return out;
}
@@ -78,8 +106,8 @@ export function paramsToFilters(params: URLSearchParams, base: FeedFilters): Fee
};
if (params.has("q")) f.q = params.get("q") ?? "";
if (params.has("show")) f.show = params.get("show") || "unwatched";
if (params.has("sort")) f.sort = params.get("sort") || "newest";
if (params.has("show")) f.show = params.get("show") || FEED_DEFAULT_SHOW;
if (params.has("sort")) f.sort = params.get("sort") || FEED_DEFAULT_SORT;
if (params.has("scope")) f.scope = params.get("scope") === "all" ? "all" : "my";
if (params.has("source")) {
const s = params.get("source");
@@ -211,6 +239,22 @@ export function urlWithParams(updates: Record<string, string | null>): string {
return hrefHere(params);
}
/** The channel page's address, opened over the page on screen: the shell's own keys (the page, an
* entry link not yet read) and the channel — none of the page's keys, none of another channel's view
* (the channel page writes its own, lib/channelPageUrlState), and no player (opening a channel closes
* it). What `openChannel` pushes, and what a
* channel link points at, so a new tab opens the same view. */
export function channelUrl(id: string): string {
const here = new URLSearchParams(window.location.search);
const viewKeys: readonly string[] = [...CHANNEL_PAGE_KEYS, ...PLAYER_KEYS];
const params = new URLSearchParams();
for (const k of SHELL_KEYS) {
const v = k === "chan" ? id : here.get(k);
if (v != null && !viewKeys.includes(k)) params.set(k, v);
}
return hrefHere(params);
}
/** This page's address with its query replaced by `query` and its fragment by `hash` — what every
* address-bar writer hands to `history`. Built on the URL itself, never by gluing `pathname` in front:
* a path opened as `//evil.com/x` would read as a link to ANOTHER host, `history.replaceState` refuses
@@ -224,10 +268,11 @@ export function hrefHere(query: URLSearchParams, hash: string = window.location.
return url.pathname.startsWith("//") ? url.href : `${url.pathname}${url.search}${url.hash}`;
}
/** Remove specific TRANSIENT params (one-time auth/admin links: ?link, ?oauth, ?admin, ?access, ?verify,
* ?reset) from the address bar once they've been read, WITHOUT touching the nav/filter params that now
* live there. Preserves history.state. Replaces the old whole-query stripUrlParams, which is unsafe now
* that the query is the source of truth for navigation. No-op when none of the keys are present. */
/** Take `keys` off the current entry's address, WITHOUT touching the nav/filter params that live
* there: TRANSIENT params once read (one-time auth/admin links: ?link, ?oauth, ?admin, ?access, ?verify,
* ?reset), and what a link named that the page could not show (a file or a video that is gone, said
* once) — left, it would be said again on every reload, or shared. Preserves history.state. No-op when
* none of the keys are present. */
export function clearParams(...keys: string[]): void {
const params = new URLSearchParams(window.location.search);
let changed = false;
+7 -7
View File
@@ -1,5 +1,5 @@
import { useTranslation } from "react-i18next";
import { DEFAULT_TAG_MODES, type FeedFilters } from "./api";
import { DEFAULT_TAG_MODES, FEED_DEFAULT_SHOW, FEED_DEFAULT_SORT, type FeedFilters } from "./api";
import { tagPickLabel } from "./tagPicks";
import { useChannelNames } from "./useChannelNames";
import { parseSort } from "./feedSort";
@@ -20,11 +20,11 @@ const DEFAULT_SIDEBAR_FILTERS: Omit<FeedFilters, "q" | "scope"> = {
tagModes: DEFAULT_TAG_MODES,
untagged: false,
channelIds: [],
sort: "newest",
sort: FEED_DEFAULT_SORT,
includeNormal: true,
includeShorts: false,
includeLive: false,
show: "unwatched",
show: FEED_DEFAULT_SHOW,
};
/**
@@ -74,19 +74,19 @@ export function useActiveFilters(
});
}
if (filters.show !== "unwatched") {
if (filters.show !== FEED_DEFAULT_SHOW) {
out.push({
key: "show",
label: t("sidebar.show." + filters.show),
remove: () => setFilters({ ...filters, show: "unwatched" }),
remove: () => setFilters({ ...filters, show: FEED_DEFAULT_SHOW }),
});
}
if (filters.sort !== "newest" && filters.sort !== "relevance") {
if (filters.sort !== FEED_DEFAULT_SORT && filters.sort !== "relevance") {
out.push({
key: "sort",
label: t("feed.sortKey." + parseSort(filters.sort).key),
remove: () => setFilters({ ...filters, sort: "newest", seed: undefined }),
remove: () => setFilters({ ...filters, sort: FEED_DEFAULT_SORT, seed: undefined }),
});
}
+40 -2
View File
@@ -5,7 +5,7 @@
// so an inline object literal (new identity every render) only fires when a param actually changes; a
// null value clears a key; and every other param on the URL is preserved.
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { renderHook } from "@testing-library/react";
import { act, cleanup, renderHook } from "@testing-library/react";
import { useUrlMirror } from "./useUrlMirror";
const setUrl = (search: string) => window.history.replaceState(null, "", search || "/");
@@ -15,7 +15,10 @@ beforeEach(() => {
setUrl("/");
spy = vi.spyOn(window.history, "replaceState");
});
afterEach(() => spy.mockRestore());
afterEach(() => {
cleanup();
spy.mockRestore();
});
describe("useUrlMirror", () => {
it("writes the param onto the current entry on mount", () => {
@@ -49,6 +52,41 @@ describe("useUrlMirror", () => {
expect(window.location.search).toBe("?page=playlists&pl=5");
});
// An entry above the view's own (a dialog's, a drawer's, a sub-view's) took a change the entry
// under it never saw: Back restores that entry's older address, and a reload would bring the old
// view back over the one on screen.
it("names the view again on the entry Back lands on", async () => {
setUrl("?page=plex&pf=");
const { rerender } = renderHook((p: Record<string, string | null>) => useUrlMirror(p), {
initialProps: { pf: "" } as Record<string, string | null>,
});
window.history.pushState({ _ov: 1 }, "", window.location.href);
rerender({ pf: "genres=Drama" });
expect(window.location.search).toBe("?page=plex&pf=genres%3DDrama");
await act(async () => {
const landed = new Promise((res) => window.addEventListener("popstate", res, { once: true }));
window.history.back();
await landed;
await new Promise((res) => setTimeout(res, 0));
});
expect(window.history.state).toBeNull();
expect(window.location.search).toBe("?page=plex&pf=genres%3DDrama");
});
it("writes nothing on a landing that already names the view", async () => {
setUrl("?pl=5");
renderHook(() => useUrlMirror({ pl: "5" }));
window.history.pushState({ _ov: 1 }, "", window.location.href);
spy.mockClear();
await act(async () => {
const landed = new Promise((res) => window.addEventListener("popstate", res, { once: true }));
window.history.back();
await landed;
await new Promise((res) => setTimeout(res, 0));
});
expect(spy).not.toHaveBeenCalled();
});
it("leaves an unconsumed auth token in the fragment alone", () => {
// This hook's mount effect is what ran before <App> (and therefore before the auth card) had even
// loaded, so whatever it writes to the address bar is what the card later reads. It must not eat
@@ -0,0 +1,27 @@
// @vitest-environment jsdom
//
// A reload under an overlay that reopens (the player) loads on the overlay's entry, its mark on it,
// and the overlay takes that entry over as it opens again. A page's first mirror write on that load
// (the defaults its address did not name yet) is the same view, not another: the mark stays, and the
// reopened overlay still takes its entry over rather than pushing one more. Its own file: the entry
// is read as the history module loads, so it is set up before the import.
import { describe, expect, it } from "vitest";
import { act, renderHook } from "@testing-library/react";
describe("a page's first mirror write on the entry a reload under an overlay started from", () => {
it("leaves the entry to the overlay that reopens", async () => {
window.history.replaceState({ sfPage: "activity" }, "", "/?page=activity");
window.history.pushState({ sfPage: "activity", _ov: 1, _ovd: 1 }, "", "/?page=activity");
const { useUrlMirror } = await import("./useUrlMirror");
const { useBackToClose } = await import("./history");
renderHook(() => useUrlMirror({ at: "runs" }));
expect(new URLSearchParams(window.location.search).get("at")).toBe("runs");
const depth = window.history.length;
renderHook(() => useBackToClose(() => {}));
await act(async () => {
await Promise.resolve();
});
expect(window.history.length).toBe(depth);
});
});
@@ -0,0 +1,39 @@
// @vitest-environment jsdom
//
// A reload under a dialog that does not reopen (About) loads on the dialog's entry, its overlay mark
// still on it. A page's view mirrored onto that entry (another tab) is another view: the next overlay
// pushes its own entry over it rather than taking this one over — taken over, closing it stepped back
// onto the entry below, and the page read its old view back from that address. Its own file: the
// entry is read as the history module loads, so it is set up before the import.
import { describe, expect, it } from "vitest";
import { act, renderHook } from "@testing-library/react";
describe("a view mirrored onto the entry a reload under a dialog started from", () => {
it("is where an overlay over it closes to", async () => {
window.history.replaceState({ sfPage: "activity" }, "", "/?page=activity&at=runs");
window.history.pushState(
{ sfPage: "activity", _ov: 1, _ovd: 1 },
"",
"/?page=activity&at=runs",
);
const { useUrlMirror } = await import("./useUrlMirror");
const { useBackToClose } = await import("./history");
const mirror = renderHook(({ at }) => useUrlMirror({ at }), { initialProps: { at: "runs" } });
mirror.rerender({ at: "admin" });
expect(new URLSearchParams(window.location.search).get("at")).toBe("admin");
const depth = window.history.length;
const overlay = renderHook(() => useBackToClose(() => {}));
await act(async () => {
await Promise.resolve();
});
expect(window.history.length).toBe(depth + 1);
await act(async () => {
const landed = new Promise((res) => window.addEventListener("popstate", res, { once: true }));
overlay.unmount();
await landed;
});
expect(new URLSearchParams(window.location.search).get("at")).toBe("admin");
});
});
@@ -0,0 +1,37 @@
// @vitest-environment jsdom
//
// A reload under an overlay that reopens (the player) loads on the overlay's entry, its mark on it.
// A page that settles before the overlay is back (the rail steps off a playlist deleted since, before
// the player's row has loaded) has not been sent to another view: nothing the user did moved it. The
// mark stays, and the reopened overlay takes its entry over rather than pushing one more — one more
// was a Back that went nowhere. Its own file: the entry is read as the history module loads, so it is
// set up before the import.
import { describe, expect, it } from "vitest";
import { act, renderHook } from "@testing-library/react";
describe("a page settling on the entry a reload under an overlay started from", () => {
it("before the user has done anything, leaves the entry to the overlay that reopens", async () => {
Object.defineProperty(navigator, "userActivation", {
configurable: true,
value: { hasBeenActive: false },
});
window.history.replaceState({ sfPage: "playlists" }, "", "/?page=playlists&pl=7");
window.history.pushState(
{ sfPage: "playlists", _ov: 1, _ovd: 1 },
"",
"/?page=playlists&pl=7&watch=Z",
);
const { useUrlMirror } = await import("./useUrlMirror");
const { useBackToClose } = await import("./history");
const mirror = renderHook(({ pl }) => useUrlMirror({ pl }), { initialProps: { pl: "7" } });
mirror.rerender({ pl: "1" });
expect(new URLSearchParams(window.location.search).get("pl")).toBe("1");
const depth = window.history.length;
renderHook(() => useBackToClose(() => {}));
await act(async () => {
await Promise.resolve();
});
expect(window.history.length).toBe(depth);
});
});

Some files were not shown because too many files have changed in this diff Show More