Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5a93a9a8e7 | ||
|
|
911fea3243 | ||
|
|
4aece8aff7 | ||
|
|
adb5e94511 | ||
|
|
673decf4d4 | ||
|
|
4d1cf66d96 | ||
|
|
2baad2ebae | ||
|
|
8383459f70 | ||
|
|
c34f6f3297 | ||
|
|
e4b6d918e4 | ||
|
|
bf5cf011ce | ||
|
|
6e6e47652a | ||
|
|
4c09a22add | ||
|
|
2bdf1ec76f | ||
|
|
f7e036abef | ||
|
|
f2de8f73aa | ||
|
|
643f305814 | ||
|
|
cbe1b3bd63 | ||
|
|
ae775b383c | ||
|
|
358d5af70b | ||
|
|
c6831090b5 | ||
|
|
38fc95d772 | ||
|
|
3f6638bf96 | ||
|
|
469c8aa481 | ||
|
|
df2997e9f3 | ||
|
|
f69725503f | ||
|
|
d5bc7e8031 | ||
|
|
efdffc82ae | ||
|
|
e23544a46b | ||
|
|
035ee937a0 | ||
|
|
bbb4063362 | ||
|
|
b4ba9d95b1 | ||
|
|
c18a2063c8 | ||
|
|
b636ef38bc | ||
|
|
195b5f3917 | ||
|
|
1a1e9d9542 | ||
|
|
d09b5d6abb | ||
|
|
439f5cd67b | ||
|
|
d79cb528fd | ||
|
|
9b76d2f96c | ||
|
|
bf54a3ce5f | ||
|
|
efbbb23525 | ||
|
|
3b85881af4 | ||
|
|
8cf8c4139c | ||
|
|
cd773e8f33 |
@@ -7,6 +7,49 @@ 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.117.0 — 2026-11-06
|
||||
|
||||
### New
|
||||
|
||||
- A share link's address now says what it opens: /file/ for a file, /folder/ for a folder, /watch/ for a video. Links you already sent keep working.
|
||||
- The upload dialog shows which folder the file goes to, and you can pick another one or make a new folder there. Opening Share copies a link at once.
|
||||
- The Channels tag chips show how many followed channels each holds. Continue watching in Plex has a See all, and a Plex item's Info shows the file size.
|
||||
|
||||
### Fixed
|
||||
|
||||
- An expired share link is marked as expired and is never copied. A crop of a video with wide pixels keeps exactly what its frame showed.
|
||||
- A Plex auto-skip waits 3 seconds into the marker before its countdown starts.
|
||||
|
||||
## 0.116.3 — 2026-11-04
|
||||
|
||||
### Fixed
|
||||
|
||||
- If a stylesheet is lost on the way, the app now asks for it again, so a poor connection no longer leaves the page unstyled until a reload.
|
||||
|
||||
## 0.116.2 — 2026-11-03
|
||||
|
||||
### Fixed
|
||||
|
||||
- A Plex video paused or muted in a background tab no longer loses its session after a minute, and if a session is lost anyway, playback comes back at once instead of after half a minute.
|
||||
|
||||
## 0.116.1 — 2026-11-03
|
||||
|
||||
### Fixed
|
||||
|
||||
- A playlist now shows the order the server holds after a revert to YouTube, a sync or a change on another device, and the next drag no longer brings back the old one.
|
||||
- An Undo on a removed or moved row puts it back in the right place while another change is still saving.
|
||||
|
||||
## 0.116.0 — 2026-11-03
|
||||
|
||||
### New
|
||||
|
||||
- In a playlist, tick rows with their box, Shift+click or x, then move or remove them together. An Undo puts them back at their places, and a single row's move has one too.
|
||||
- Drag rows onto another list in the rail: one row, or all the selected ones, also under a sort or a filter.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Removing a video from inside the player no longer loses your place in the list when the player closes.
|
||||
|
||||
## 0.115.0 — 2026-11-01
|
||||
|
||||
### New
|
||||
|
||||
@@ -74,7 +74,7 @@ only along a declared edge and writes them only through that unit's service; cor
|
||||
cannot (an ORM write on another unit's loaded row, SQL in `text()`, a commit by `begin()`) is review's to catch, listed in
|
||||
[`backend/app/README.md`](backend/app/README.md) with the conventions.
|
||||
Frontend, by folder under `src/`: `main.tsx` provider tree → `shell/` (`App`, header, nav rail, palette,
|
||||
boot; a shared `/watch` link boots from its own entry, `watch.html` → `watchMain.tsx` → `watch/`, held
|
||||
boot; a share link (`/watch`, `/file`, `/folder`) boots from its own entry, `watch.html` → `watchMain.tsx` → `watch/`, held
|
||||
app-free by a contract test) → **`modules/<page>/`** (one folder per page: the page, its rail, its store, its tests,
|
||||
and its `module.ts` definition — label, icon, gate, the lazy page and rail, its store — collected in nav order by
|
||||
`features/navigation/moduleRegistry`, which also mounts every store at the root; a new page is its folder, its id in
|
||||
|
||||
@@ -201,6 +201,16 @@ def _ratio(v: object) -> float | None:
|
||||
return n / d if n > 0 and d > 0 else None
|
||||
|
||||
|
||||
def quarter_turned(probe: dict) -> bool | None:
|
||||
"""Whether the first video stream of an ffprobe `-show_streams` JSON is stored turned a quarter
|
||||
(ffmpeg stands it upright before any filter, so its filters see width and height swapped). None
|
||||
when there is no video stream."""
|
||||
for s in probe.get("streams") or []:
|
||||
if s.get("codec_type") == "video":
|
||||
return _quarter_turned(s)
|
||||
return None
|
||||
|
||||
|
||||
def _quarter_turned(stream: dict) -> bool:
|
||||
rotation: object = (stream.get("tags") or {}).get("rotate")
|
||||
for sd in stream.get("side_data_list") or []:
|
||||
|
||||
@@ -11,7 +11,9 @@ with the worker branching on the asset's `source_kind` to run ffmpeg instead of
|
||||
(the `-ss` seeks first), so a short clip is cheap even from a long source
|
||||
* crop (± trim) → always re-encode (a filter can't be stream-copied), frame-accurate
|
||||
|
||||
`edit_spec = {trim?: {start_s, end_s}, crop?: {x, y, w, h}, accurate?: bool}`. `accurate` is the
|
||||
`edit_spec = {trim?: {start_s, end_s}, crop?: {x, y, w, h, frame_w?, frame_h?}, accurate?: bool}`. A
|
||||
crop with `frame_w`/`frame_h` counts the picture as it is SHOWN, measured on a frame of that size
|
||||
(`crop_filter`); one without them is in the file's stored pixels (its older form). `accurate` is the
|
||||
per-edit user choice for a trim-only cut (ignored when a crop forces a re-encode anyway). `split`
|
||||
is a frontend concept: the
|
||||
UI fans a split out into N trim jobs, so there is one output file per job here.
|
||||
@@ -60,6 +62,46 @@ class EditAborted(Exception):
|
||||
_MAX_SEGMENTS = 100
|
||||
|
||||
|
||||
def _crop_frame(crop: dict) -> dict | None:
|
||||
"""The picture size a crop was measured on, or None when it has none it could be scaled by (a
|
||||
spec from before it was sent, which `crop_filter` cuts in the file's own pixels)."""
|
||||
try:
|
||||
w, h = int(crop["frame_w"]), int(crop["frame_h"])
|
||||
# silent-ok: no frame is a crop's older form, and it is still the crop that was asked for. An
|
||||
# infinite number (JSON `1e400`) is OverflowError, and it is no more a frame than "x" is.
|
||||
except (KeyError, TypeError, ValueError, OverflowError):
|
||||
return None
|
||||
return {"frame_w": w, "frame_h": h} if w > 0 and h > 0 else None
|
||||
|
||||
|
||||
def crop_filter(crop: dict) -> str:
|
||||
"""The ffmpeg `crop` of an edit. Its numbers count the picture as the browser reports it, which
|
||||
is its SHOWN size: a video with wide pixels (320 stored, 640 shown) would be cut off to one side
|
||||
in ffmpeg's stored ones, so they are scaled to `iw` / `ih` by the size they were measured on. A
|
||||
rotated file needs nothing more: both the browser and ffmpeg's filters see it upright."""
|
||||
frame_w, frame_h = crop.get("frame_w"), crop.get("frame_h")
|
||||
if not frame_w or not frame_h:
|
||||
return f"crop={crop['w']}:{crop['h']}:{crop['x']}:{crop['y']}"
|
||||
return (
|
||||
f"crop=iw*{crop['w']}/{frame_w}:ih*{crop['h']}/{frame_h}"
|
||||
f":iw*{crop['x']}/{frame_w}:ih*{crop['y']}/{frame_h}"
|
||||
)
|
||||
|
||||
|
||||
def crop_stored_size(crop: dict, src_w: int | None, src_h: int | None) -> tuple[int, int] | None:
|
||||
"""The size `crop_filter` cuts out of a `src_w` x `src_h` frame, evened as `EVEN_FRAME` evens it —
|
||||
the clip's size when ffprobe cannot tell. The frame is the one ffmpeg's filters see: a rotated
|
||||
file's stood upright, its stored size turned (the caller's to turn). A crop counted in the shown
|
||||
picture is a fraction of that frame, not its own pixel count; None when the size is unknown."""
|
||||
if crop.get("frame_w") and crop.get("frame_h"):
|
||||
if not src_w or not src_h:
|
||||
return None
|
||||
w, h = src_w * crop["w"] // crop["frame_w"], src_h * crop["h"] // crop["frame_h"]
|
||||
else:
|
||||
w, h = crop["w"], crop["h"]
|
||||
return w // 2 * 2, h // 2 * 2
|
||||
|
||||
|
||||
def normalize_edit_spec(spec: dict | None) -> dict:
|
||||
"""Canonicalize a raw edit spec: clamp/round trim, coerce crop to ints, drop empties.
|
||||
|
||||
@@ -72,7 +114,7 @@ def normalize_edit_spec(spec: dict | None) -> dict:
|
||||
if crop:
|
||||
try:
|
||||
c = {k: int(round(float(crop[k]))) for k in ("x", "y", "w", "h")}
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
except (KeyError, TypeError, ValueError, OverflowError) as exc:
|
||||
# The clip still renders — uncropped. The user asked for a crop, got a whole frame,
|
||||
# and nothing anywhere called it a failure; this line is the only trace there is.
|
||||
log.warning(
|
||||
@@ -81,7 +123,8 @@ def normalize_edit_spec(spec: dict | None) -> dict:
|
||||
)
|
||||
c = None
|
||||
if c and c["w"] > 0 and c["h"] > 0 and c["x"] >= 0 and c["y"] >= 0:
|
||||
out["crop"] = c
|
||||
frame = _crop_frame(crop)
|
||||
out["crop"] = {**c, **frame} if frame else c
|
||||
|
||||
# Multi-segment JOIN (cut-list → one concatenated file). Takes precedence over `trim`.
|
||||
segs = spec.get("segments")
|
||||
@@ -268,7 +311,7 @@ def build_edit_cmd(src: Path, dest: Path, spec: dict, out_ext: str) -> list[str]
|
||||
if reencode:
|
||||
# Input -ss + re-encode is frame-accurate (decodes from the prior keyframe, discards up to
|
||||
# the exact cut). A crop adds the filter; an accurate trim only evens the frame.
|
||||
cropf = f"crop={crop['w']}:{crop['h']}:{crop['x']}:{crop['y']}," if crop else ""
|
||||
cropf = f"{crop_filter(crop)}," if crop else ""
|
||||
cmd += ["-vf", cropf + EVEN_FRAME, *X264_ARGS, *AAC_ARGS]
|
||||
else:
|
||||
cmd += ["-c", "copy", "-avoid_negative_ts", "make_zero"]
|
||||
@@ -313,7 +356,7 @@ def build_concat_plan(src: Path, dest: Path, spec: dict, out_ext: str, staging:
|
||||
]
|
||||
|
||||
if needs_reencode(spec):
|
||||
cropf = f",crop={crop['w']}:{crop['h']}:{crop['x']}:{crop['y']}" if crop else ""
|
||||
cropf = f",{crop_filter(crop)}" if crop else ""
|
||||
parts, labels = [], []
|
||||
for i, s in enumerate(segs):
|
||||
st, en = s["start_s"], s["end_s"]
|
||||
|
||||
@@ -127,14 +127,35 @@ def check_grant(token: str, grant: str | None, password_version: int) -> bool:
|
||||
# --- serialization -------------------------------------------------------------------------
|
||||
|
||||
|
||||
def owner_view(link: DownloadLink, base_url: str = "", token: str | None = None) -> dict:
|
||||
def opens(db: Session, link: DownloadLink) -> str:
|
||||
"""What a link opens, in the words its address and its preview use: "folder", "video" or
|
||||
"file". A file still being made reads as the video it mostly is."""
|
||||
from app.downloads import mediakind
|
||||
|
||||
if link.folder_id is not None:
|
||||
return "folder"
|
||||
job = db.get(DownloadJob, link.job_id)
|
||||
asset = db.get(MediaAsset, job.asset_id) if job and job.asset_id else None
|
||||
kind = asset.media_kind if asset else None
|
||||
return "file" if kind and kind != mediakind.VIDEO else "video"
|
||||
|
||||
|
||||
def share_path(db: Session, link: DownloadLink, token: str) -> str:
|
||||
"""The address a link is given out on: its path says what it opens (`opens`). Only a word for the
|
||||
reader, the token is the whole key: every prefix of `main.SHARE_PREFIXES` opens every link, so
|
||||
the links already sent on /watch/ work for good."""
|
||||
prefix = {"folder": "folder", "file": "file", "video": "watch"}[opens(db, link)]
|
||||
return f"/{prefix}/{token}"
|
||||
|
||||
|
||||
def owner_view(db: Session, link: DownloadLink, token: str | None = None) -> dict:
|
||||
"""What the file owner sees when managing their links. `token` is the one just made (it is in
|
||||
hand even where no copy is kept); else it is read back, and `url` is None when it cannot be."""
|
||||
token = token or recover(link)
|
||||
return {
|
||||
"id": link.id,
|
||||
"token": token,
|
||||
"url": f"{base_url}/watch/{token}" if token else None,
|
||||
"url": share_path(db, link, token) if token else None,
|
||||
"allow_download": link.allow_download,
|
||||
"has_password": link.password_hash is not None,
|
||||
"expires_at": link.expires_at.isoformat() if link.expires_at else None,
|
||||
|
||||
@@ -234,7 +234,9 @@ class DownloadJob(Base, TimestampMixin, UpdatedAtMixin):
|
||||
source_asset_id: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("media_assets.id", ondelete="SET NULL")
|
||||
)
|
||||
# For edit jobs: the trim/crop recipe {trim?:{start_s,end_s}, crop?:{x,y,w,h}} in pixels. For clip
|
||||
# For edit jobs: the trim/crop recipe {trim?:{start_s,end_s}, crop?:{x,y,w,h,frame_w?,frame_h?}}, its
|
||||
# crop in the SHOWN picture's pixels when it carries the frame it was measured on (`edit.crop_filter`),
|
||||
# else in the file's stored ones. For clip
|
||||
# jobs: the clip spec {source, ref, start_s, end_s, audio_track?, crop?:{x,y,w,h,aspect}}, its crop
|
||||
# in fractions of the box it was drawn in (`downloads.clip.normalize`).
|
||||
edit_spec: Mapped[dict | None] = mapped_column(JSON)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Server-rendered Open Graph tags for the public /watch/{token} page.
|
||||
"""Server-rendered Open Graph tags for the public page of a share link (/watch/, /file/, /folder/).
|
||||
|
||||
The watch page is a client-side SPA, so a social crawler (facebookexternalhit, Twitterbot, …) that
|
||||
fetches /watch/{token} would otherwise only see the generic index.html — a blank/greyed link card.
|
||||
@@ -76,16 +76,21 @@ def _watch_tags(token: str, db: Session) -> str | None:
|
||||
link = linksmod.find(db, token)
|
||||
if link is None or linksmod.is_expired(link):
|
||||
return None
|
||||
url = f"{settings.app_base}/watch/{token}"
|
||||
folder = link.folder_id is not None
|
||||
url = f"{settings.app_base}{linksmod.share_path(db, link, token)}"
|
||||
# What the card calls it, as its address does.
|
||||
kind = linksmod.opens(db, link)
|
||||
folder, video = kind == "folder", kind == "video"
|
||||
if link.password_hash:
|
||||
# Password-gated: don't leak the title/thumbnail in the unfurl.
|
||||
return "\n ".join(
|
||||
[
|
||||
"<title>Siftlode</title>",
|
||||
_tag("og:title", "Password-protected " + ("folder" if folder else "video")),
|
||||
_tag(
|
||||
"og:title",
|
||||
"Password-protected " + ("folder" if folder else "video" if video else "file"),
|
||||
),
|
||||
_tag("og:description", "Shared via Siftlode"),
|
||||
_tag("og:type", "website" if folder else "video.other"),
|
||||
_tag("og:type", "video.other" if video else "website"),
|
||||
_tag("og:url", url),
|
||||
_tag("og:site_name", "Siftlode"),
|
||||
]
|
||||
@@ -96,7 +101,7 @@ def _watch_tags(token: str, db: Session) -> str | None:
|
||||
asset = db.get(MediaAsset, job.asset_id) if job and job.asset_id else None
|
||||
if job is None or asset is None or asset.status != "ready":
|
||||
return None
|
||||
title = (job.display_name or asset.title or "Video").strip()
|
||||
title = (job.display_name or asset.title or ("Video" if video else "File")).strip()
|
||||
channel = (job.display_uploader or asset.uploader or "").strip()
|
||||
# Pick the link-preview image. Facebook's scraper REJECTS our own poster ("Corrupted Image" in the
|
||||
# Sharing Debugger): the poster is an ffmpeg-produced JPEG whose non-standard marker order FB's
|
||||
@@ -118,7 +123,7 @@ def _watch_tags(token: str, db: Session) -> str | None:
|
||||
f"<title>{html.escape(title)}</title>",
|
||||
_tag("og:title", title),
|
||||
_tag("og:description", channel or "Shared via Siftlode"),
|
||||
_tag("og:type", "video.other"),
|
||||
_tag("og:type", "video.other" if video else "website"),
|
||||
_tag("og:url", url),
|
||||
_tag("og:site_name", "Siftlode"),
|
||||
_tag("twitter:title", title, attr="name"),
|
||||
|
||||
@@ -837,6 +837,18 @@ def _fail_edit(
|
||||
)
|
||||
|
||||
|
||||
def _filter_frame(
|
||||
path: Path, width: int | None, height: int | None
|
||||
) -> tuple[int | None, int | None]:
|
||||
"""A file's frame as ffmpeg's filters see it: the stored size, turned when the stream is stored
|
||||
turned a quarter (ffmpeg stands it upright first). Unknown when the file cannot be read."""
|
||||
data = probe.probe_json(path)
|
||||
turned = clipmod.quarter_turned(data) if data else None
|
||||
if turned is None:
|
||||
return None, None
|
||||
return (height, width) if turned else (width, height)
|
||||
|
||||
|
||||
def _process_edit(job_id: int, asset_id: int) -> None:
|
||||
"""Produce a per-user trim/crop clip from the source asset's downloaded file via ffmpeg."""
|
||||
with SessionLocal() as db:
|
||||
@@ -905,6 +917,12 @@ def _process_edit(job_id: int, asset_id: int) -> None:
|
||||
size = final.stat().st_size if final.exists() else None
|
||||
# The clip's real frame: a re-encode evens an odd crop or source (`editmod.EVEN_FRAME`).
|
||||
_, _, out_w, out_h, _ = probe.probe_media(final)
|
||||
# Unsized, a crop's own size stands in, cut from the frame the filters saw.
|
||||
cut = (
|
||||
editmod.crop_stored_size(edit_spec["crop"], *_filter_frame(src_path, src_w, src_h))
|
||||
if crop and not (out_w and out_h)
|
||||
else None
|
||||
)
|
||||
|
||||
with SessionLocal() as db:
|
||||
asset = db.get(MediaAsset, asset_id)
|
||||
@@ -916,11 +934,10 @@ def _process_edit(job_id: int, asset_id: int) -> None:
|
||||
asset.duration_s = total_s or asset.duration_s
|
||||
if out_w and out_h:
|
||||
asset.width, asset.height = out_w, out_h
|
||||
elif crop:
|
||||
asset.width = edit_spec["crop"]["w"]
|
||||
asset.height = edit_spec["crop"]["h"]
|
||||
elif cut:
|
||||
asset.width, asset.height = cut
|
||||
else:
|
||||
asset.width, asset.height = src_w, src_h
|
||||
asset.width, asset.height = (None, None) if crop else (src_w, src_h)
|
||||
asset.error = None
|
||||
asset.last_access_at = datetime.now(timezone.utc)
|
||||
job = db.get(DownloadJob, job_id)
|
||||
|
||||
@@ -16,7 +16,8 @@ That is a per-job ceiling, not an aggregate ledger: concurrent jobs of one user
|
||||
remainder (in-flight bytes are not `ready`, so `footprint` cannot see them), so a wave of
|
||||
max_concurrent downloads can still land over the cap — the deliberate trade, since a download's size
|
||||
is unknown until it finishes. CLIP jobs consult it before their fetch or encode and again with
|
||||
their output's real size before it is placed. Edit jobs do not consult it at all (tracked as SEC-19).
|
||||
their output's real size before it is placed. Edit jobs consult it with their output's real size
|
||||
before it is placed (`test_edit_cap.py`).
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
+11
-5
@@ -151,7 +151,7 @@ async def _reap_hls_sessions() -> None:
|
||||
somebody pressed play again or the process restarted.
|
||||
|
||||
A FINISHED session is reaped on the short rule here, not kept for the full idle window: an open
|
||||
player checkpoints every 10 s and that route touches the session, so a paused viewer is no longer
|
||||
player keeps checkpointing and that route touches the session, so a paused viewer is no longer
|
||||
invisible to this pass (see `reap_idle`). Keeping every finished session for ten minutes instead
|
||||
held one whole segmented copy of a film per item on the download volume."""
|
||||
while True:
|
||||
@@ -368,6 +368,10 @@ INDEX_HTML = STATIC_DIR / "index.html"
|
||||
# A public share link's own page: the player alone, without the app's bundle (frontend/watch.html).
|
||||
WATCH_HTML = STATIC_DIR / "watch.html"
|
||||
INDEX_HEADERS = {"Cache-Control": "no-cache"}
|
||||
# The paths a share link opens on, by what it opens (`links.share_path`). Any of them opens any link.
|
||||
# A new one also goes in frontend/public/robots.txt, the Vite dev entry and WatchPage's token parsing
|
||||
# (watchEntry.contract.test.ts).
|
||||
SHARE_PREFIXES = ("watch/", "file/", "folder/")
|
||||
app.mount(
|
||||
"/assets",
|
||||
StaticFiles(directory=STATIC_DIR / "assets", check_dir=False),
|
||||
@@ -381,8 +385,10 @@ async def index() -> FileResponse:
|
||||
|
||||
|
||||
@app.get("/watch/{token}")
|
||||
async def watch_page(token: str):
|
||||
"""Serve the public player page for a share link, with per-video Open Graph tags injected so the
|
||||
@app.get("/file/{token}")
|
||||
@app.get("/folder/{token}")
|
||||
async def share_page(token: str):
|
||||
"""Serve the public page of a share link, with per-link Open Graph tags injected so the
|
||||
link unfurls richly (title/channel/thumbnail) in Messenger/social crawlers. A real browser
|
||||
ignores the extra tags and boots WatchPage; invalid/expired/password links fall back to the
|
||||
generic card."""
|
||||
@@ -409,8 +415,8 @@ async def spa_fallback(full_path: str) -> FileResponse:
|
||||
# Real SPA-root assets (welcome images, favicon, robots.txt) rarely change and have
|
||||
# stable names, so a moderate cache is safe and satisfies the cache-lifetime audit.
|
||||
return FileResponse(candidate, headers={"Cache-Control": "public, max-age=604800"})
|
||||
# A /watch/ path the route above does not match (a trailing segment, no token) is still the
|
||||
# A share path the route above does not match (a trailing segment, no token) is still the
|
||||
# player's: WatchPage reads the token off the path and says when a link is gone.
|
||||
if full_path.startswith("watch/"):
|
||||
if full_path.startswith(SHARE_PREFIXES):
|
||||
return FileResponse(WATCH_HTML, headers=INDEX_HEADERS)
|
||||
return FileResponse(INDEX_HTML, headers=INDEX_HEADERS)
|
||||
|
||||
+27
-13
@@ -125,7 +125,7 @@ class HlsSession:
|
||||
# replaces the viewer's registered session for the item — and the old player's next request
|
||||
# for `seg_12.ts`, resolved by (viewer, rating_key) alone, was answered 200 with the NEW session's twelfth segment, produced from a different offset
|
||||
# under `-copyts`. Wrong bytes, not an error, so the client's reclaim never fired on it.
|
||||
# A request naming a session that is no longer registered is a 404,
|
||||
# A request naming a session that is no longer registered is a 410,
|
||||
# which the player recovers from by restarting at the playhead.
|
||||
self.id = secrets.token_urlsafe(9)
|
||||
self.key = key # the item's rating_key (what the logs name)
|
||||
@@ -729,7 +729,7 @@ def _enforce_caps(
|
||||
whole segmented copy of the film under `_HLS_ROOT`, written faster than realtime. Counted only
|
||||
by the transcode cap, N distinct items were N ffmpegs and N film-sized scratch directories.
|
||||
|
||||
Somebody's playback stops at each drop. The route turns the missing session into a retryable 404
|
||||
Somebody's playback stops at each drop. The route turns the missing session into a 410
|
||||
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."""
|
||||
|
||||
@@ -918,7 +918,7 @@ def start_session(
|
||||
# stale and stops the session it names (`stop_session`), which stopped the playback that won.
|
||||
# Never None either: the POST /session route turns a None return into a "Media file not found
|
||||
# on disk" 404 — dishonest for a file that exists. A dead session instead degrades to a
|
||||
# retryable 404 ("No active playback session" / "Not available yet") the client re-requests.
|
||||
# 410 ("session_gone") on its URLs, and the client asks again.
|
||||
return s
|
||||
s = respawned
|
||||
ready = wait_for(_seg(0), timeout=25.0, proc=s.proc)
|
||||
@@ -1160,9 +1160,13 @@ def sweep_orphans(older_than: float | None = None) -> int:
|
||||
return dropped
|
||||
|
||||
|
||||
# How long a session whose ffmpeg has FINISHED may go unfetched before a new session request reaps
|
||||
# it (see reap_idle).
|
||||
_FINISHED_IDLE_S = 30
|
||||
# The slowest heartbeat a live player sends: a browser cuts the timers of a hidden page that makes no
|
||||
# sound to one a minute (measured on Chromium: a paused and a muted player, about a minute after
|
||||
# hiding; a hidden player with sound keeps its 10 s).
|
||||
_THROTTLED_HEARTBEAT_S = 60
|
||||
# How long a session whose ffmpeg has FINISHED may go without a signal before `reap_idle` takes it:
|
||||
# the beat before the reaper looks, one lost on the way, and the time the next one takes to arrive.
|
||||
_FINISHED_IDLE_S = 3 * _THROTTLED_HEARTBEAT_S
|
||||
|
||||
|
||||
def reap_idle(finished_idle_s: float = _FINISHED_IDLE_S) -> int:
|
||||
@@ -1171,20 +1175,23 @@ def reap_idle(finished_idle_s: float = _FINISHED_IDLE_S) -> int:
|
||||
|
||||
A finished session is also what a PAUSED viewer has: a remux runs far faster than realtime, so
|
||||
ffmpeg is done a minute or two in and writes ENDLIST; hls.js then stops asking for the playlist,
|
||||
and with its forward buffer full a paused player fetches nothing at all. With the 30 s rule that
|
||||
killed a one-minute pause, and playback died ~30 s after resuming.
|
||||
and with its forward buffer full a paused player fetches nothing at all.
|
||||
|
||||
What makes the short rule safe again is that fetching is no longer the only signal: a player
|
||||
parked MID-ITEM checkpoints its position every 10 s, and that route calls `touch_session`, so a
|
||||
viewer who is merely paused says so far more often than this rule asks. The heartbeat
|
||||
What makes the short rule safe is that fetching is not the only signal: a player parked MID-ITEM
|
||||
checkpoints its position and that route calls `touch_session`. That beat is every 10 s only while
|
||||
the page is visible or making sound; a hidden, silent one sends it once a minute, which a 30 s
|
||||
rule killed whenever the reaper happened to run more than 30 s after the beat (measured: a paused
|
||||
session gone that way, and one that lived on the same cadence because its phase was luckier).
|
||||
So the rule is sized to the throttled beat (`_THROTTLED_HEARTBEAT_S`). The heartbeat
|
||||
stops once the item is finished or before a position is known (`usePlexProgress.flush`) — both
|
||||
states where reaping is correct, and where the player's 404 → reclaim recovers a viewer who
|
||||
scrubs back in anyway. Do not restate this as "every 10 s whether or not it is playing":
|
||||
states where reaping is correct, and where the player's 410 → reclaim recovers a viewer who
|
||||
scrubs back in anyway. Do not restate this as "whether or not it is playing":
|
||||
a review found that claim in two comments and not in the code. An earlier blanket
|
||||
`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()
|
||||
doomed: list[tuple[HlsSession, Path | None]] = []
|
||||
reaped: list[tuple[str, str, int]] = []
|
||||
with _lock:
|
||||
for reg, s in list(_sessions.items()):
|
||||
done = s.proc.poll() is not None
|
||||
@@ -1192,6 +1199,13 @@ def reap_idle(finished_idle_s: float = _FINISHED_IDLE_S) -> int:
|
||||
if idle > _SESSION_IDLE_S or (done and idle > finished_idle_s):
|
||||
_sessions.pop(reg, None)
|
||||
doomed.append(_detach(s))
|
||||
reaped.append((s.key, "finished_idle" if done else "idle", int(idle)))
|
||||
# The viewer of a session wrongly taken sees only a 410 later, so this line is the one record of why.
|
||||
for key, reason, idle_s in reaped:
|
||||
log.info(
|
||||
"an idle session was reaped",
|
||||
extra=logs.event("plex.stream.session_reaped", key=key, reason=reason, idle_s=idle_s),
|
||||
)
|
||||
_finish(doomed)
|
||||
return len(doomed)
|
||||
|
||||
|
||||
@@ -41,11 +41,25 @@ def video(db: Session, video_id: str) -> Video | None:
|
||||
# --- tags ------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def tags_with_counts(db: Session, user: User) -> list[tuple[Tag, int]]:
|
||||
"""The tags this user sees (the shared system ones and their own), each with how many channel
|
||||
links it has, by category then name."""
|
||||
def tags_with_counts(db: Session, user: User) -> list[tuple[Tag, int, int]]:
|
||||
"""The tags this user sees (the shared system ones and their own), by category then name, each
|
||||
with how many channel links it has and how many of the user's own links sit on a channel they
|
||||
subscribe to and have not hidden — the rows the Channels page's tag filter shows (a hidden
|
||||
channel has its own tab). A link outlives an unsubscribe and a hide, so the two differ."""
|
||||
subscribed = select(Subscription.channel_id).where(
|
||||
owned_by(Subscription.user_id, user), Subscription.hidden.is_(False)
|
||||
)
|
||||
on_subscribed = dict(
|
||||
db.execute(
|
||||
select(ChannelTag.tag_id, func.count(ChannelTag.id))
|
||||
.where(owned_by(ChannelTag.user_id, user), ChannelTag.channel_id.in_(subscribed))
|
||||
.group_by(ChannelTag.tag_id)
|
||||
)
|
||||
.tuples()
|
||||
.all()
|
||||
)
|
||||
return [
|
||||
(tag, count)
|
||||
(tag, count, on_subscribed.get(tag.id, 0))
|
||||
for tag, count in db.execute(
|
||||
select(Tag, func.count(ChannelTag.id))
|
||||
.outerjoin(ChannelTag, ChannelTag.tag_id == Tag.id)
|
||||
|
||||
+152
-52
@@ -292,7 +292,7 @@ def set_progress(db: Session, user: User, video_id: str, position: int) -> None:
|
||||
|
||||
# Every reason a move is refused; the UI names each one (`playlists.moveErrors.<reason>`, held by the
|
||||
# frontend's backendIds contract, which reads this Literal).
|
||||
MoveReason = Literal["same_playlist", "not_in_playlist"]
|
||||
MoveReason = Literal["same_playlist"]
|
||||
|
||||
|
||||
class MoveRefused(Exception):
|
||||
@@ -406,30 +406,6 @@ def remove_item(db: Session, pl: Playlist, video_id: str, *, mark_dirty: bool) -
|
||||
return True
|
||||
|
||||
|
||||
def place_item(db: Session, pl: Playlist, video_id: str, position: int) -> None:
|
||||
"""Put a video already in the list at `position` (clamped to the end), renumbering the whole
|
||||
list: positions can have gaps after removals, so "index N" is only meaningful over the
|
||||
ordered rows."""
|
||||
rows = queries.items(db, pl.id)
|
||||
new = next(r for r in rows if r.video_id == video_id)
|
||||
rows.remove(new)
|
||||
rows.insert(min(position, len(rows)), new)
|
||||
for pos, row in enumerate(rows):
|
||||
row.position = pos
|
||||
db.flush()
|
||||
|
||||
|
||||
def add_to_playlist(db: Session, pl: Playlist, video_id: str, position: int | None) -> None:
|
||||
"""Add a video to one of the user's lists, at `position` when given (the list page's "Undo" of
|
||||
a removal puts the row back where it was in ONE request), else at the end. A video already in
|
||||
the list stays where it is."""
|
||||
added = add_item(db, pl, video_id, mark_dirty=False)
|
||||
if added and position is not None:
|
||||
place_item(db, pl, video_id, position)
|
||||
recompute_dirty(db, pl)
|
||||
db.flush()
|
||||
|
||||
|
||||
def rename_playlist(db: Session, pl: Playlist, name: str) -> None:
|
||||
"""A new name moves `dirty`; the caller holds the playlist's lock (the scheduled mirror refresh
|
||||
reads `dirty` under it)."""
|
||||
@@ -447,39 +423,163 @@ def delete_playlist(db: Session, pl: Playlist) -> None:
|
||||
db.flush()
|
||||
|
||||
|
||||
def move_item(db: Session, src: Playlist, dst: Playlist, video_id: str) -> None:
|
||||
"""Move one video from `src` into `dst`, in the caller's one transaction.
|
||||
def remove_items(db: Session, pl: Playlist, video_ids: list[str]) -> list[str]:
|
||||
"""Remove these videos from a playlist, in one transaction; a video not in it any more is simply
|
||||
not among them. Says which went: an Undo must not bring back one this removal never took."""
|
||||
lock_playlists(db, pl.id)
|
||||
wanted = set(video_ids)
|
||||
rows = [it for it in queries.items(db, pl.id) if it.video_id in wanted]
|
||||
for row in rows:
|
||||
db.delete(row)
|
||||
if rows:
|
||||
recompute_dirty(db, pl)
|
||||
touch(pl)
|
||||
db.flush()
|
||||
return [row.video_id for row in rows]
|
||||
|
||||
The client-side shape — add to the target, then remove from the source — leaves the video in
|
||||
BOTH lists whenever the second call fails. Idempotent: a video already in the target is simply
|
||||
dropped from the source (moving into a list that has it is a removal, not a duplicate). Raises
|
||||
`MoveRefused` for the same list twice, or a video a concurrent edit already took out."""
|
||||
|
||||
def _insert_at(
|
||||
db: Session,
|
||||
pl: Playlist,
|
||||
placed: list[tuple[int, str]],
|
||||
leaving: dict[str, PlaylistItem] | None = None,
|
||||
staying_out: frozenset[str] = frozenset(),
|
||||
) -> int:
|
||||
"""Add videos at their indices (ascending, so each index is where the row stood when the rows
|
||||
before it were back) and renumber the list 0..n-1, as positions can have gaps. A video already in
|
||||
the list stays where it is, and one the catalog has lost or in `staying_out` is left out, the
|
||||
ones after it closing up. A video with a row in `leaving` brings that row along, for the reason
|
||||
`move_items` re-parents. Says how many were added; the caller holds the playlist's lock."""
|
||||
leaving = leaving or {}
|
||||
rows = queries.items(db, pl.id)
|
||||
present = {r.video_id for r in rows}
|
||||
known = queries.known_video_ids(db, [vid for _, vid in placed])
|
||||
added = 0
|
||||
left_out = 0
|
||||
for at, vid in sorted(placed, key=lambda p: p[0]):
|
||||
if vid in present or vid not in known or vid in staying_out:
|
||||
left_out += 1
|
||||
continue
|
||||
row = leaving.pop(vid, None)
|
||||
if row is None:
|
||||
row = PlaylistItem(playlist_id=pl.id, video_id=vid, position=0)
|
||||
db.add(row)
|
||||
else:
|
||||
row.playlist_id = pl.id
|
||||
rows.insert(min(at - left_out, len(rows)), row)
|
||||
present.add(vid)
|
||||
added += 1
|
||||
for pos, row in enumerate(rows):
|
||||
row.position = pos
|
||||
return added
|
||||
|
||||
|
||||
def restore_items(db: Session, pl: Playlist, video_ids: list[str], positions: list[int]) -> int:
|
||||
"""Put removed videos back at their places, in ONE request: an append plus a whole-list reorder
|
||||
leaves them at the end whenever the second call fails. Says how many came back."""
|
||||
lock_playlists(db, pl.id)
|
||||
added = _insert_at(db, pl, list(zip(positions, video_ids, strict=True)))
|
||||
if added:
|
||||
recompute_dirty(db, pl)
|
||||
touch(pl)
|
||||
db.flush()
|
||||
return added
|
||||
|
||||
|
||||
class ListGone(Exception):
|
||||
"""A list of a two-list write was deleted between the route's read and the lock."""
|
||||
|
||||
def __init__(self, *, source: bool):
|
||||
super().__init__("source" if source else "target")
|
||||
self.source = source
|
||||
|
||||
|
||||
def _lock_both(db: Session, src: Playlist, dst: Playlist) -> None:
|
||||
"""Both lists, in id order: a move A→B beside a move B→A would otherwise lock crosswise. A list
|
||||
already gone is said here: a write into it would answer with its foreign key's 500."""
|
||||
found = lock_playlists(db, src.id, dst.id)
|
||||
if src.id not in found:
|
||||
raise ListGone(source=True)
|
||||
if dst.id not in found:
|
||||
raise ListGone(source=False)
|
||||
|
||||
|
||||
def move_items(
|
||||
db: Session, src: Playlist, dst: Playlist, video_ids: list[str]
|
||||
) -> tuple[list[str], list[str]]:
|
||||
"""Move these videos from `src` into `dst`, in the caller's one transaction, in the source's
|
||||
order whatever order they were picked in. Returns the ones that landed in the target and the ones
|
||||
it already held, which only left the source: the Undo needs to tell them apart. A video a
|
||||
concurrent edit already took out of the source is in neither. Raises `MoveRefused` for the same
|
||||
list twice."""
|
||||
if src.id == dst.id:
|
||||
raise MoveRefused("same_playlist")
|
||||
# Both lists, in id order: a move A→B beside a move B→A would otherwise lock crosswise.
|
||||
lock_playlists(db, src.id, dst.id)
|
||||
row = queries.item(db, src.id, video_id)
|
||||
if row is None:
|
||||
raise MoveRefused("not_in_playlist")
|
||||
dst_changed = False
|
||||
if queries.item(db, dst.id, video_id) is None:
|
||||
# Re-parent the existing row rather than delete+insert: `added_at` ("when I saved this")
|
||||
# survives the move, and there is no window where the video belongs to neither list. The
|
||||
# check above holds: both lists are locked, and an insert into the target (another tab's
|
||||
# add, a YouTube merge) waits for the lock — its foreign key needs the target row.
|
||||
row.playlist_id = dst.id
|
||||
row.position = next_item_position(db, dst.id)
|
||||
dst_changed = True
|
||||
if not dst_changed:
|
||||
db.delete(row)
|
||||
# The source always changed; the target only when the row landed in it. Touching a target
|
||||
# that already had the video promoted an untouched list in the rail's "recently changed" sort.
|
||||
recompute_dirty(db, src)
|
||||
touch(src)
|
||||
if dst_changed:
|
||||
_lock_both(db, src, dst)
|
||||
wanted = set(video_ids)
|
||||
rows = [it for it in queries.items(db, src.id) if it.video_id in wanted]
|
||||
held = queries.in_playlist(db, dst.id, [r.video_id for r in rows])
|
||||
position = next_item_position(db, dst.id)
|
||||
moved: list[str] = []
|
||||
already_there: list[str] = []
|
||||
for row in rows:
|
||||
if row.video_id in held:
|
||||
already_there.append(row.video_id)
|
||||
db.delete(row)
|
||||
else:
|
||||
moved.append(row.video_id)
|
||||
# Re-parented rather than deleted and inserted: `added_at` ("when I saved this") survives
|
||||
# the move, and there is no window where the video belongs to neither list. `held` stays
|
||||
# true: both lists are locked, and an insert into the target (another tab's add, a
|
||||
# YouTube merge) waits for the lock, as its foreign key needs the target row.
|
||||
row.playlist_id = dst.id
|
||||
row.position = position
|
||||
position += 1
|
||||
if rows:
|
||||
recompute_dirty(db, src)
|
||||
touch(src)
|
||||
# Only when a row landed in it: touching a target that already had the video promoted an untouched
|
||||
# list in the rail's "recently changed" sort.
|
||||
if moved:
|
||||
recompute_dirty(db, dst)
|
||||
touch(dst)
|
||||
db.flush()
|
||||
return moved, already_there
|
||||
|
||||
|
||||
def undo_move(
|
||||
db: Session,
|
||||
src: Playlist,
|
||||
dst: Playlist,
|
||||
moved: list[str],
|
||||
already_there: list[str],
|
||||
positions: list[int],
|
||||
) -> int:
|
||||
"""Take a move back in one transaction: the `moved` videos leave `dst` and return to their places
|
||||
in `src`, keeping their rows, as the move did. The `already_there` ones return too and stay in
|
||||
`dst`, which held them before. A moved video `dst` no longer holds has gone on from there, and
|
||||
bringing it back would leave it in lists the reader never put it in, so it stays out, as a
|
||||
move skips a video a concurrent edit took out. `positions` pairs with `moved` + `already_there`.
|
||||
Says how many came back. Raises `MoveRefused` for the same list twice, as a move does."""
|
||||
if src.id == dst.id:
|
||||
raise MoveRefused("same_playlist")
|
||||
_lock_both(db, src, dst)
|
||||
wanted = set(moved)
|
||||
rows = {it.video_id: it for it in queries.items(db, dst.id) if it.video_id in wanted}
|
||||
changed = bool(rows)
|
||||
placed = list(zip(positions, [*moved, *already_there], strict=True))
|
||||
back = _insert_at(db, src, placed, leaving=rows, staying_out=frozenset(wanted - rows.keys()))
|
||||
# What `src` holds again by now only leaves `dst`.
|
||||
for row in rows.values():
|
||||
db.delete(row)
|
||||
db.flush()
|
||||
if changed:
|
||||
recompute_dirty(db, dst)
|
||||
touch(dst)
|
||||
if back:
|
||||
recompute_dirty(db, src)
|
||||
touch(src)
|
||||
db.flush()
|
||||
return back
|
||||
|
||||
|
||||
def reorder_items(db: Session, pl: Playlist, order: list[str]) -> int:
|
||||
|
||||
@@ -611,7 +611,7 @@ def list_links(
|
||||
job_id: int, user: User = Depends(current_user), db: Session = Depends(get_db)
|
||||
) -> list[dict]:
|
||||
own_job(db, user, job_id)
|
||||
return [linksmod.owner_view(link) for link in queries.links_to(db, job_id=job_id)]
|
||||
return [linksmod.owner_view(db, link) for link in queries.links_to(db, job_id=job_id)]
|
||||
|
||||
|
||||
class CreateLinkIn(BaseModel):
|
||||
@@ -653,7 +653,7 @@ def create_link(
|
||||
raise refused(409, "share_unfinished")
|
||||
link, token = _new_link(db, user, body, job_id=job_id)
|
||||
db.commit()
|
||||
return linksmod.owner_view(link, token=token)
|
||||
return linksmod.owner_view(db, link, token=token)
|
||||
|
||||
|
||||
def _shareable_job(db: Session, user: User, job_id: int) -> "DownloadJob":
|
||||
@@ -684,7 +684,7 @@ def list_folder_links(
|
||||
folder_id: int, user: User = Depends(current_user), db: Session = Depends(get_db)
|
||||
) -> list[dict]:
|
||||
own_folder(db, user, folder_id)
|
||||
return [linksmod.owner_view(link) for link in queries.links_to(db, folder_id=folder_id)]
|
||||
return [linksmod.owner_view(db, link) for link in queries.links_to(db, folder_id=folder_id)]
|
||||
|
||||
|
||||
@router.post("/folders/{folder_id}/links")
|
||||
@@ -697,7 +697,7 @@ def create_folder_link(
|
||||
_shareable_folder(db, user, folder_id)
|
||||
link, token = _new_link(db, user, body, folder_id=folder_id)
|
||||
db.commit()
|
||||
return linksmod.owner_view(link, token=token)
|
||||
return linksmod.owner_view(db, link, token=token)
|
||||
|
||||
|
||||
class UpdateLinkIn(BaseModel):
|
||||
@@ -724,7 +724,7 @@ def update_link(
|
||||
sent=frozenset(body.model_fields_set),
|
||||
)
|
||||
db.commit()
|
||||
return linksmod.owner_view(link)
|
||||
return linksmod.owner_view(db, link)
|
||||
|
||||
|
||||
@router.delete("/links/{link_id}")
|
||||
|
||||
+131
-38
@@ -6,7 +6,7 @@ out (`/{id}/push-plan`, `/{id}/revert-youtube`), behind the optional write scope
|
||||
from typing import TYPE_CHECKING, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, model_validator
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import quota
|
||||
@@ -386,24 +386,17 @@ def delete_playlist(
|
||||
return {"deleted": playlist_id}
|
||||
|
||||
|
||||
class AddItemIn(VideoRefIn):
|
||||
# Where the video lands among the list's items, in their stored order (0 = first). Omitted, it
|
||||
# is appended. The list page's "Undo" of a removal puts the row back where it was with this —
|
||||
# ONE request, because append-then-reorder leaves it at the end whenever the second call fails.
|
||||
position: int | None = Field(default=None, ge=0)
|
||||
|
||||
|
||||
@router.post("/{playlist_id}/items")
|
||||
def add_item(
|
||||
playlist_id: int,
|
||||
body: AddItemIn,
|
||||
body: VideoRefIn,
|
||||
user: User = Depends(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
pl = _own_playlist(db, user, playlist_id)
|
||||
pl = _own_playlist(db, user, playlist_id, lock=True)
|
||||
video_id = body.video_id
|
||||
_video_or_404(db, video_id)
|
||||
service.add_to_playlist(db, pl, video_id, body.position)
|
||||
service.add_item(db, pl, video_id, mark_dirty=True)
|
||||
db.commit()
|
||||
return {"ok": True, "playlist_id": pl.id, "video_id": video_id}
|
||||
|
||||
@@ -415,58 +408,158 @@ def remove_item(
|
||||
user: User = Depends(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
pl = _own_playlist(db, user, playlist_id)
|
||||
pl = _own_playlist(db, user, playlist_id, lock=True)
|
||||
service.remove_item(db, pl, video_id, mark_dirty=True)
|
||||
db.commit()
|
||||
return {"ok": True, "playlist_id": pl.id, "video_id": video_id}
|
||||
|
||||
|
||||
class MoveItemIn(BaseModel):
|
||||
class VideoIdsIn(BaseModel):
|
||||
# Required: with a default, a misnamed key answered 200 having acted on no video.
|
||||
video_ids: list[str]
|
||||
|
||||
|
||||
def _paired(video_count: int, positions: list[int]) -> None:
|
||||
"""One place per video, none before the start and none twice: both undo bodies come back from
|
||||
the client, and the insert's arithmetic counts on places that only rise."""
|
||||
if len(positions) != video_count:
|
||||
raise ValueError("positions must pair one-to-one with the videos")
|
||||
if any(at < 0 for at in positions):
|
||||
raise ValueError("positions cannot be negative")
|
||||
if len(set(positions)) != len(positions):
|
||||
raise ValueError("positions cannot repeat")
|
||||
|
||||
|
||||
class RestoreItemsIn(VideoIdsIn):
|
||||
# Where each video goes back: an index over the ordered rows, one per video.
|
||||
positions: list[int] = []
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _one_position_per_video(self):
|
||||
_paired(len(self.video_ids), self.positions)
|
||||
return self
|
||||
|
||||
|
||||
class MoveItemsIn(VideoIdsIn):
|
||||
target_playlist_id: int
|
||||
|
||||
|
||||
@router.post("/{playlist_id}/items/{video_id}/move")
|
||||
def move_item(
|
||||
class UndoMoveIn(BaseModel):
|
||||
from_playlist_id: int
|
||||
# Required, as `video_ids` is. An empty one is still a real body: the target held them all.
|
||||
moved: list[str]
|
||||
already_there: list[str] = []
|
||||
# One per video of `moved` + `already_there`, in that order.
|
||||
positions: list[int]
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _one_position_per_video(self):
|
||||
_paired(len(self.moved) + len(self.already_there), self.positions)
|
||||
return self
|
||||
|
||||
|
||||
def _list_gone(e: service.ListGone) -> HTTPException:
|
||||
"""Each list of a two-list write under the reason the route's own read gives it."""
|
||||
return not_found("playlist") if e.source else not_found("move_target")
|
||||
|
||||
|
||||
def _move_refused(e: service.MoveRefused) -> HTTPException:
|
||||
return HTTPException(status_code=400, detail={"code": "playlist_move", "reason": e.reason})
|
||||
|
||||
|
||||
def _other_list(db: Session, user: User, playlist_id: int) -> "Playlist":
|
||||
"""The other list of a move. Its own reason: "this playlist doesn't exist any more" about a list
|
||||
that is gone was read as the one on screen, which is still there."""
|
||||
other = queries.own_playlist(db, user, playlist_id)
|
||||
if other is None:
|
||||
raise not_found("move_target")
|
||||
return other
|
||||
|
||||
|
||||
@router.post("/{playlist_id}/items/remove-bulk")
|
||||
def remove_items(
|
||||
playlist_id: int,
|
||||
video_id: str,
|
||||
body: MoveItemIn,
|
||||
body: VideoIdsIn,
|
||||
user: User = Depends(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
"""Move one video from a playlist into another of the caller's playlists, atomically.
|
||||
"""Remove many videos from a playlist at once. Returns the ones that went."""
|
||||
pl = _own_playlist(db, user, playlist_id, lock=True)
|
||||
removed = service.remove_items(db, pl, body.video_ids)
|
||||
db.commit()
|
||||
return {"ok": True, "playlist_id": pl.id, "removed": removed}
|
||||
|
||||
|
||||
@router.post("/{playlist_id}/items/restore")
|
||||
def restore_items(
|
||||
playlist_id: int,
|
||||
body: RestoreItemsIn,
|
||||
user: User = Depends(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
"""The "Undo" of a removal: the videos back at their places. Returns how many came back."""
|
||||
pl = _own_playlist(db, user, playlist_id, lock=True)
|
||||
added = service.restore_items(db, pl, body.video_ids, body.positions)
|
||||
db.commit()
|
||||
return {"ok": True, "playlist_id": pl.id, "added": added}
|
||||
|
||||
|
||||
@router.post("/{playlist_id}/items/move-bulk")
|
||||
def move_items(
|
||||
playlist_id: int,
|
||||
body: MoveItemsIn,
|
||||
user: User = Depends(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
"""Move videos into another of the caller's playlists, atomically.
|
||||
|
||||
ONE transaction on purpose. The obvious client-side shape — add to the target, then remove
|
||||
from the source — leaves the video in BOTH lists whenever the second call fails, which is
|
||||
exactly the kind of half-applied state this codebase treats as a bug rather than an edge
|
||||
case. Idempotent: if the video is already in the target, the source row is simply dropped
|
||||
(moving into a list that already has it is a removal, not a duplicate)."""
|
||||
from the source — leaves a video in BOTH lists whenever the second call fails. A video the
|
||||
target already has only leaves the source, and one a concurrent edit (another tab, a YouTube
|
||||
re-pull) already took out is skipped. Says which landed there and which it already held, for
|
||||
the "Undo"."""
|
||||
src = _own_playlist(db, user, playlist_id)
|
||||
# Its own reason: "this playlist doesn't exist any more" about a TARGET that is gone was read as
|
||||
# the list on screen — which is still there.
|
||||
dst = queries.own_playlist(db, user, body.target_playlist_id)
|
||||
if dst is None:
|
||||
raise not_found("move_target")
|
||||
dst = _other_list(db, user, body.target_playlist_id)
|
||||
try:
|
||||
service.move_item(db, src, dst, video_id)
|
||||
moved, already_there = service.move_items(db, src, dst, body.video_ids)
|
||||
except service.MoveRefused as e:
|
||||
# A same-list move is a bad request; a video a concurrent edit (another tab, a YouTube
|
||||
# re-pull) already took out is gone.
|
||||
status = 400 if e.reason == "same_playlist" else 404
|
||||
raise HTTPException(
|
||||
status_code=status, detail={"code": "playlist_move", "reason": e.reason}
|
||||
) from None
|
||||
raise _move_refused(e) from None
|
||||
except service.ListGone as e:
|
||||
raise _list_gone(e) from None
|
||||
db.commit()
|
||||
return {"ok": True, "from_playlist_id": src.id, "to_playlist_id": dst.id, "video_id": video_id}
|
||||
return {
|
||||
"ok": True,
|
||||
"from_playlist_id": src.id,
|
||||
"to_playlist_id": dst.id,
|
||||
"moved": moved,
|
||||
"already_there": already_there,
|
||||
}
|
||||
|
||||
|
||||
class ReorderItemsIn(BaseModel):
|
||||
video_ids: list[str] = []
|
||||
@router.post("/{playlist_id}/items/undo-move")
|
||||
def undo_move(
|
||||
playlist_id: int,
|
||||
body: UndoMoveIn,
|
||||
user: User = Depends(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
"""The "Undo" of a move, back into this playlist in one transaction. Returns how many came back."""
|
||||
src = _own_playlist(db, user, playlist_id)
|
||||
dst = _other_list(db, user, body.from_playlist_id)
|
||||
try:
|
||||
added = service.undo_move(db, src, dst, body.moved, body.already_there, body.positions)
|
||||
except service.MoveRefused as e:
|
||||
raise _move_refused(e) from None
|
||||
except service.ListGone as e:
|
||||
raise _list_gone(e) from None
|
||||
db.commit()
|
||||
return {"ok": True, "playlist_id": src.id, "added": added}
|
||||
|
||||
|
||||
@router.put("/{playlist_id}/order")
|
||||
def reorder_items(
|
||||
playlist_id: int,
|
||||
body: ReorderItemsIn,
|
||||
body: VideoIdsIn,
|
||||
user: User = Depends(current_user),
|
||||
db: Session = Depends(get_db),
|
||||
) -> dict:
|
||||
|
||||
@@ -432,6 +432,7 @@ def item_detail(
|
||||
"summary": (it.summary_hu or it.summary) if hu else it.summary,
|
||||
"year": it.year,
|
||||
"duration_seconds": it.duration_s,
|
||||
"size_bytes": it.size_bytes,
|
||||
"playable": it.playable,
|
||||
# Playback-class detail: HW/SW transcode split + the codec/bit-depth the info-page chip shows.
|
||||
"transcode_hw": it.transcode_hw,
|
||||
|
||||
@@ -323,13 +323,14 @@ def item_progress(
|
||||
`_should_push_resume`). `final` (sent on pause / seek / pagehide / unmount) pushes immediately and
|
||||
resets the throttle window, so Plex sees a settled position the instant the user pauses or seeks."""
|
||||
it = item_or_404(db, rating_key)
|
||||
# A player parked mid-item — playing or PAUSED — checkpoints every 10 s, so this is the signal
|
||||
# A player parked mid-item — playing or PAUSED — keeps checkpointing (every 10 s, once a minute
|
||||
# in a hidden silent page), so this is the signal
|
||||
# that such a viewer still wants their HLS session: the one thing `last_access` could not see,
|
||||
# since it moved only on a file fetch and a paused player fetches nothing (see
|
||||
# stream.reap_idle). It is NOT every open player: `usePlexProgress.flush` sends nothing once the
|
||||
# finish latch is up, or before the first position is known. Those are the states in which
|
||||
# reaping is the right answer anyway, and a viewer who scrubs back into a reaped session gets
|
||||
# the same 404 → reclaim the player already handles.
|
||||
# the same 410 → reclaim the player already handles.
|
||||
plex_stream.touch_session(user.id, str(rating_key))
|
||||
position = max(0, int(body.position_seconds))
|
||||
duration = int(body.duration_seconds)
|
||||
@@ -609,7 +610,9 @@ def stream_hls_file(
|
||||
is per (key, viewer, offset, tag) — so resolving by the key alone handed the old player the new
|
||||
session's `seg_12.ts`, produced from a different offset under `-copyts`: wrong
|
||||
bytes with a 200, which the player has no way to notice. A request for a
|
||||
session that is no longer the registered one is a 404, and the player reclaims at the playhead.
|
||||
session that is no longer the registered one is a 410, and the player reclaims at the playhead.
|
||||
410, not 404: a 404 here means "that segment is not there yet", worth hls.js's retries, and the
|
||||
player can only read the status (a gone session retried for half a minute behind that 404).
|
||||
|
||||
That reclaim is also why a request with no live session is no longer auto-started here: the
|
||||
auto-start could only ever begin at 0, silently throwing away the viewer's position."""
|
||||
@@ -625,7 +628,7 @@ def stream_hls_file(
|
||||
raise not_found("file")
|
||||
s = plex_stream.current_session(user.id, str(rating_key))
|
||||
if s is None or s.id != session_id:
|
||||
raise refused(404, "session_gone")
|
||||
raise refused(410, "session_gone")
|
||||
path = s.dir / filename
|
||||
# Only a name THIS session can actually produce is worth waiting for: its own playlists, and a
|
||||
# segment of one of its own renditions whose predecessor is already on disk (ffmpeg writes them
|
||||
@@ -648,13 +651,13 @@ def stream_hls_file(
|
||||
except OSError:
|
||||
# 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
|
||||
# to present as the same 410 a gone session does: the player's recovery is keyed on the
|
||||
# STATUS, 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
|
||||
# instance's in-flight segment request races the rmtree on every seek-restart.
|
||||
raise refused(404, "session_gone") from None
|
||||
raise refused(410, "session_gone") from None
|
||||
return Response(
|
||||
content=content,
|
||||
media_type=_HLS_CT[ext],
|
||||
|
||||
@@ -183,7 +183,9 @@ def playlist_remove_item(
|
||||
|
||||
|
||||
class PlexItemKeysIn(BaseModel):
|
||||
item_rating_keys: list[str] = []
|
||||
# Required: with a default, a misnamed key answered 200 having acted on no item, and a reorder
|
||||
# took it for an empty order.
|
||||
item_rating_keys: list[str]
|
||||
|
||||
|
||||
class PlexItemAddBulkIn(PlexItemKeysIn):
|
||||
|
||||
@@ -176,8 +176,15 @@ def watch_meta(token: str, db: Session = Depends(get_db)) -> dict:
|
||||
returns only `needs_password` until the viewer unlocks it (no title/thumbnail leak)."""
|
||||
link = _link_or_404(db, token)
|
||||
if link.password_hash:
|
||||
# Which kind it opens, for the password prompt's title — never what is in it.
|
||||
return {"needs_password": True, "kind": "folder" if link.folder_id is not None else "file"}
|
||||
# Which kind it opens, for the password prompt's words — never what is in it. `video` tells
|
||||
# a video (watched) from any other file (opened); the address is only a hint, every
|
||||
# prefix opens every link.
|
||||
opens = linksmod.opens(db, link)
|
||||
return {
|
||||
"needs_password": True,
|
||||
"kind": "folder" if opens == "folder" else "file",
|
||||
"video": opens == "video",
|
||||
}
|
||||
meta = _opened(db, link, token)
|
||||
db.commit()
|
||||
return meta
|
||||
|
||||
@@ -314,7 +314,8 @@ def search_youtube(
|
||||
|
||||
|
||||
class ClearSearchIn(BaseModel):
|
||||
video_ids: list[str] = []
|
||||
# Required: a default read a misnamed key as an empty list, a 200 that cleared nothing.
|
||||
video_ids: list[str]
|
||||
|
||||
|
||||
@router.post("/clear")
|
||||
|
||||
@@ -48,8 +48,9 @@ def list_tags(user: User = Depends(current_user), db: Session = Depends(get_db))
|
||||
"category": tag.category,
|
||||
"system": tag.user_id is None,
|
||||
"channel_count": count,
|
||||
"subscribed_count": subscribed,
|
||||
}
|
||||
for tag, count in queries.tags_with_counts(db, user)
|
||||
for tag, count, subscribed in queries.tags_with_counts(db, user)
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
"""The editor's crop lands on the part of the picture the frame was drawn on, also when a video's
|
||||
pixels are not square. The browser reports such a video by its shown size (320 stored, 640 shown),
|
||||
and ffmpeg's `crop` counts stored pixels: measured on a real clip, a frame over the middle half kept
|
||||
half the frame's red surroundings. So a crop carries the size it was measured on.
|
||||
|
||||
Real ffmpeg: the pixels of the output are the oracle.
|
||||
"""
|
||||
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app.config import settings
|
||||
from app.downloads import edit, pipeline, service, storage
|
||||
from app.downloads import upload as uploadmod
|
||||
from app.downloads.models import DownloadJob, MediaAsset
|
||||
|
||||
pytestmark = pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg not available")
|
||||
|
||||
|
||||
def _source(path: Path, size: str, box: str, sar: int, rotate: int = 0) -> None:
|
||||
"""Red, with a green box: a crop of the box holds no red. `rotate` tags the file to be shown
|
||||
turned by that many degrees counter-clockwise, as a phone records a portrait video."""
|
||||
tag = ["-display_rotation:v:0", str(rotate)] if rotate else []
|
||||
subprocess.run(
|
||||
[
|
||||
"ffmpeg", "-y", "-loglevel", "error",
|
||||
"-f", "lavfi", "-i", f"color=c=red:s={size}:d=2:r=10",
|
||||
"-f", "lavfi", "-i", "sine=duration=2",
|
||||
"-vf", f"drawbox={box}:c=lime:t=fill,setsar={sar}",
|
||||
"-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", str(path),
|
||||
],
|
||||
check=True,
|
||||
) # fmt: skip
|
||||
if tag:
|
||||
tagged = path.with_name("tagged-" + path.name)
|
||||
subprocess.run(
|
||||
["ffmpeg", "-y", "-loglevel", "error", *tag, "-i", str(path), "-c", "copy", str(tagged)],
|
||||
check=True,
|
||||
) # fmt: skip
|
||||
tagged.replace(path)
|
||||
|
||||
|
||||
def _red_and_green(path: Path) -> tuple[int, int]:
|
||||
raw = subprocess.run(
|
||||
["ffmpeg", "-loglevel", "error", "-i", str(path), "-frames:v", "1",
|
||||
"-f", "rawvideo", "-pix_fmt", "rgb24", "-"],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
).stdout # fmt: skip
|
||||
red = green = 0
|
||||
for i in range(0, len(raw) - 2, 3):
|
||||
if raw[i] > 180 and raw[i + 1] < 80:
|
||||
red += 1
|
||||
elif raw[i + 1] > 180 and raw[i] < 80:
|
||||
green += 1
|
||||
return red, green
|
||||
|
||||
|
||||
def _cut_asset(db, make_user, src: Path, spec: dict, then=lambda: None) -> MediaAsset:
|
||||
user = make_user()
|
||||
source = uploadmod.ingest_upload(
|
||||
db, user.id, filename="clip.mp4", src_path=src, size=src.stat().st_size
|
||||
)
|
||||
assert source.status == "done"
|
||||
then()
|
||||
job = service.enqueue_edit(db, user.id, source, spec)
|
||||
asset = db.get(MediaAsset, job.asset_id)
|
||||
job.status, asset.status = "running", "downloading" # the worker's claim
|
||||
db.commit()
|
||||
|
||||
pipeline._process_edit(job.id, asset.id)
|
||||
|
||||
db.expire_all()
|
||||
job, asset = db.get(DownloadJob, job.id), db.get(MediaAsset, job.asset_id)
|
||||
assert (job.status, job.error, asset.status) == ("done", None, "ready")
|
||||
return asset
|
||||
|
||||
|
||||
def _cut(db, make_user, tmp_path, src: Path, crop: dict, **spec) -> Path:
|
||||
asset = _cut_asset(db, make_user, src, {"crop": crop, **spec})
|
||||
return storage.abs_path(str(tmp_path), asset.rel_path)
|
||||
|
||||
|
||||
def test_a_crop_of_a_video_with_wide_pixels_keeps_what_the_frame_showed(
|
||||
db, make_user, tmp_path, monkeypatch
|
||||
):
|
||||
monkeypatch.setattr(settings, "files_root", str(tmp_path))
|
||||
src = tmp_path / "in.mp4"
|
||||
_source(src, "320x240", "x=80:y=60:w=160:h=120", sar=2)
|
||||
|
||||
# What the editor sends for the middle half of this video: the browser shows it at 640 x 240.
|
||||
final = _cut(
|
||||
db, make_user, tmp_path, src,
|
||||
{"x": 160, "y": 60, "w": 320, "h": 120, "frame_w": 640, "frame_h": 240},
|
||||
) # fmt: skip
|
||||
|
||||
red, green = _red_and_green(final)
|
||||
assert (red, green) == (0, 160 * 120)
|
||||
|
||||
|
||||
def test_a_crop_of_square_pixels_is_cut_where_it_was_drawn(db, make_user, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(settings, "files_root", str(tmp_path))
|
||||
src = tmp_path / "in.mp4"
|
||||
_source(src, "480x640", "x=120:y=160:w=240:h=320", sar=1)
|
||||
|
||||
final = _cut(
|
||||
db, make_user, tmp_path, src,
|
||||
{"x": 120, "y": 160, "w": 240, "h": 320, "frame_w": 480, "frame_h": 640},
|
||||
) # fmt: skip
|
||||
|
||||
assert _red_and_green(final) == (0, 240 * 320)
|
||||
|
||||
|
||||
def test_a_crop_stored_before_it_carried_its_frame_is_cut_as_it_always_was():
|
||||
spec = edit.normalize_edit_spec({"crop": {"x": 4, "y": 6, "w": 100, "h": 50}})
|
||||
assert spec["crop"] == {"x": 4, "y": 6, "w": 100, "h": 50}
|
||||
cmd = edit.build_edit_cmd(Path("in.mp4"), Path("out.mp4"), spec, "mp4")
|
||||
assert cmd[cmd.index("-vf") + 1].startswith("crop=100:50:4:6,")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("frame", [{"frame_w": 0, "frame_h": 240}, {"frame_w": "x", "frame_h": 2}])
|
||||
def test_a_frame_that_cannot_be_read_is_not_divided_by(frame):
|
||||
spec = edit.normalize_edit_spec({"crop": {"x": 4, "y": 6, "w": 100, "h": 50, **frame}})
|
||||
assert spec["crop"] == {"x": 4, "y": 6, "w": 100, "h": 50}
|
||||
|
||||
|
||||
def test_a_crop_of_a_join_keeps_what_the_frame_showed(db, make_user, tmp_path, monkeypatch):
|
||||
"""A cut-list joins through `filter_complex`, a crop path of its own."""
|
||||
monkeypatch.setattr(settings, "files_root", str(tmp_path))
|
||||
src = tmp_path / "in.mp4"
|
||||
_source(src, "320x240", "x=80:y=60:w=160:h=120", sar=2)
|
||||
|
||||
final = _cut(
|
||||
db, make_user, tmp_path, src,
|
||||
{"x": 160, "y": 60, "w": 320, "h": 120, "frame_w": 640, "frame_h": 240},
|
||||
segments=[{"start_s": 0, "end_s": 0.5}, {"start_s": 1, "end_s": 1.5}], accurate=True,
|
||||
) # fmt: skip
|
||||
|
||||
assert _red_and_green(final) == (0, 160 * 120)
|
||||
|
||||
|
||||
def test_a_crop_of_a_rotated_video_is_cut_where_it_was_drawn(db, make_user, tmp_path, monkeypatch):
|
||||
"""The browser shows a rotated file upright, so the frame was drawn on the upright picture."""
|
||||
monkeypatch.setattr(settings, "files_root", str(tmp_path))
|
||||
src = tmp_path / "in.mp4"
|
||||
# Stored 320 x 240, green on its left half; shown turned a quarter, 240 x 320.
|
||||
_source(src, "320x240", "x=0:y=0:w=160:h=240", sar=1, rotate=90)
|
||||
|
||||
# Turned counter-clockwise, the stored left half is the shown bottom half.
|
||||
final = _cut(
|
||||
db, make_user, tmp_path, src,
|
||||
{"x": 0, "y": 160, "w": 240, "h": 160, "frame_w": 240, "frame_h": 320},
|
||||
) # fmt: skip
|
||||
|
||||
assert _red_and_green(final) == (0, 240 * 160)
|
||||
|
||||
|
||||
def test_a_clip_ffprobe_cannot_size_gets_the_size_its_crop_cut(
|
||||
db, make_user, tmp_path, monkeypatch
|
||||
):
|
||||
monkeypatch.setattr(settings, "files_root", str(tmp_path))
|
||||
src = tmp_path / "in.mp4"
|
||||
_source(src, "320x240", "x=80:y=60:w=160:h=120", sar=2)
|
||||
|
||||
def probe_fails():
|
||||
monkeypatch.setattr(pipeline.probe, "probe_media", lambda _p: (None,) * 5)
|
||||
|
||||
asset = _cut_asset(
|
||||
db, make_user, src,
|
||||
{"crop": {"x": 160, "y": 60, "w": 320, "h": 120, "frame_w": 640, "frame_h": 240}},
|
||||
then=probe_fails,
|
||||
) # fmt: skip
|
||||
|
||||
# Half the shown width of a 320-wide file: 160 stored, not the 320 the frame counted.
|
||||
assert (asset.width, asset.height) == (160, 120)
|
||||
|
||||
|
||||
def test_a_rotated_clip_ffprobe_cannot_size_gets_the_upright_size_its_crop_cut(
|
||||
db, make_user, tmp_path, monkeypatch
|
||||
):
|
||||
"""The frame was drawn on the upright picture, which is the stored one turned: so is its cut."""
|
||||
monkeypatch.setattr(settings, "files_root", str(tmp_path))
|
||||
src = tmp_path / "in.mp4"
|
||||
_source(src, "320x240", "x=0:y=0:w=160:h=240", sar=1, rotate=90)
|
||||
|
||||
def probe_fails():
|
||||
monkeypatch.setattr(pipeline.probe, "probe_media", lambda _p: (None,) * 5)
|
||||
|
||||
asset = _cut_asset(
|
||||
db, make_user, src,
|
||||
{"crop": {"x": 0, "y": 160, "w": 240, "h": 160, "frame_w": 240, "frame_h": 320}},
|
||||
then=probe_fails,
|
||||
) # fmt: skip
|
||||
|
||||
# What ffmpeg cut (the rotated test above): 240 x 160, not the stored 320 x 120.
|
||||
assert (asset.width, asset.height) == (240, 160)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["frame_w", "x"])
|
||||
def test_an_infinite_number_in_a_crop_is_dropped_not_a_crash(key):
|
||||
crop = {"x": 4, "y": 6, "w": 100, "h": 50, "frame_w": 640, "frame_h": 240}
|
||||
spec = edit.normalize_edit_spec({"crop": {**crop, key: float("inf")}})
|
||||
if key == "frame_w":
|
||||
assert spec["crop"] == {"x": 4, "y": 6, "w": 100, "h": 50}
|
||||
else:
|
||||
assert "crop" not in spec
|
||||
@@ -150,6 +150,7 @@ def test_a_password_folder_link_shows_nothing_until_unlocked(shelf, client):
|
||||
assert client.get(f"/api/public/watch/{token}").json() == {
|
||||
"needs_password": True,
|
||||
"kind": "folder",
|
||||
"video": False,
|
||||
}
|
||||
bare = f"/api/public/watch/{token}/files/{shelf['inside'][0]}/file"
|
||||
assert client.get(bare).status_code == 403
|
||||
@@ -312,7 +313,7 @@ def test_a_password_file_link_says_it_opens_a_file(shelf, client):
|
||||
.json()
|
||||
)
|
||||
meta = client.get(f"/api/public/watch/{made['token']}").json()
|
||||
assert meta == {"needs_password": True, "kind": "file"}
|
||||
assert meta == {"needs_password": True, "kind": "file", "video": True}
|
||||
|
||||
|
||||
def test_a_file_whose_bytes_are_gone_is_not_offered(shelf, client, db):
|
||||
|
||||
@@ -5,11 +5,11 @@ POST /session: after the last playback, an abandoned session (its ffmpeg still w
|
||||
film, its directory a whole segmented copy of it) lived until somebody pressed play again.
|
||||
|
||||
And it must not take a PAUSED viewer's session: a remux finishes long before the film does, and a
|
||||
paused player with a full buffer fetches nothing, so "finished and unfetched for 30 s" does not mean
|
||||
paused player with a full buffer fetches nothing, so "finished and unfetched for a while" does not mean
|
||||
"abandoned". An earlier fix bought that safety by keeping EVERY finished session for the full
|
||||
ten-minute idle window — one segmented copy of a film per item, on the volume the download center
|
||||
shares. Its successor replaced the blanket retention with the signal that already existed: a player
|
||||
parked mid-item checkpoints its position every 10 s, paused or not, and that route says "still
|
||||
parked mid-item keeps checkpointing its position, paused or not, and that route says "still
|
||||
here" (it stops once the item is finished, where reaping is correct).
|
||||
|
||||
Both call sites are pinned here, because the bug each time was that only one of them moved: the
|
||||
@@ -81,6 +81,9 @@ class _Proc:
|
||||
return 0
|
||||
|
||||
|
||||
_PAST_THE_RULE = stream._FINISHED_IDLE_S + 5
|
||||
|
||||
|
||||
class _Session:
|
||||
def __init__(self, tmp_path, name: str, finished: bool, idle_s: float):
|
||||
self.key = name
|
||||
@@ -98,11 +101,29 @@ def sessions(monkeypatch):
|
||||
|
||||
|
||||
def test_the_periodic_pass_reaps_a_finished_session_nobody_has_claimed(tmp_path, sessions):
|
||||
sessions["12345"] = _Session(tmp_path, "done", finished=True, idle_s=45)
|
||||
sessions["12345"] = _Session(tmp_path, "done", finished=True, idle_s=_PAST_THE_RULE)
|
||||
assert stream.reap_idle() == 1
|
||||
assert sessions == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("idle_s", [65, 125])
|
||||
def test_a_heartbeat_throttled_to_once_a_minute_keeps_a_finished_session(
|
||||
tmp_path, sessions, idle_s
|
||||
):
|
||||
"""A hidden page that makes no sound gets its timers cut to one a minute (measured on a paused and
|
||||
on a muted player, about a minute after hiding), so that is the viewer's heartbeat there: the
|
||||
reaper can see a beat over a minute old, and two if one is lost on the way."""
|
||||
s = _Session(tmp_path, "hidden", finished=True, idle_s=idle_s)
|
||||
sessions[(1, "12345")] = s
|
||||
assert stream.reap_idle() == 0
|
||||
assert (1, "12345") in sessions and s.dir.exists() and not s.proc.killed
|
||||
|
||||
|
||||
def test_an_abandoned_finished_session_is_still_gone_within_minutes(tmp_path, sessions):
|
||||
sessions[(1, "12345")] = _Session(tmp_path, "gone", finished=True, idle_s=185)
|
||||
assert stream.reap_idle() == 1
|
||||
|
||||
|
||||
def test_the_periodic_pass_still_reaps_what_nobody_has_touched_for_the_idle_limit(
|
||||
tmp_path, sessions
|
||||
):
|
||||
@@ -116,8 +137,32 @@ def test_the_periodic_pass_still_reaps_what_nobody_has_touched_for_the_idle_limi
|
||||
assert sessions == {}
|
||||
|
||||
|
||||
def test_every_reap_says_which_rule_took_the_session(tmp_path, sessions, caplog):
|
||||
"""A session that vanishes leaves the viewer a 410 and nothing else: with no line here, a live
|
||||
stall could only ever be blamed on the reaper by inference."""
|
||||
sessions["1"] = _Session(
|
||||
tmp_path, "gone_done", finished=True, idle_s=stream._SESSION_IDLE_S - 5
|
||||
)
|
||||
sessions["2"] = _Session(
|
||||
tmp_path, "gone_live", finished=False, idle_s=stream._SESSION_IDLE_S + 5
|
||||
)
|
||||
sessions["3"] = _Session(tmp_path, "kept", finished=False, idle_s=5)
|
||||
with caplog.at_level("INFO"):
|
||||
assert stream.reap_idle() == 2
|
||||
reaped = {
|
||||
r.attrs["key"]: r.attrs
|
||||
for r in caplog.records
|
||||
if getattr(r, "event", "") == "plex.stream.session_reaped"
|
||||
}
|
||||
assert set(reaped) == {"gone_done", "gone_live"}
|
||||
assert reaped["gone_done"]["reason"] == "finished_idle"
|
||||
assert reaped["gone_live"]["reason"] == "idle"
|
||||
assert reaped["gone_done"]["idle_s"] == pytest.approx(stream._SESSION_IDLE_S - 5, abs=2)
|
||||
assert reaped["gone_live"]["idle_s"] == pytest.approx(stream._SESSION_IDLE_S + 5, abs=2)
|
||||
|
||||
|
||||
def test_touching_a_session_keeps_it_through_the_short_rule(tmp_path, sessions):
|
||||
s = _Session(tmp_path, "paused", finished=True, idle_s=90)
|
||||
s = _Session(tmp_path, "paused", finished=True, idle_s=_PAST_THE_RULE)
|
||||
sessions[(1, "12345")] = s
|
||||
stream.touch_session(1, "12345")
|
||||
assert stream.reap_idle() == 0
|
||||
@@ -160,7 +205,7 @@ def test_a_paused_viewers_checkpoint_keeps_their_session_alive(
|
||||
user = User(email="paused@example.com")
|
||||
db.add(user)
|
||||
db.commit()
|
||||
s = _Session(tmp_path, "paused", finished=True, idle_s=90)
|
||||
s = _Session(tmp_path, "paused", finished=True, idle_s=_PAST_THE_RULE)
|
||||
sessions[(user.id, "paused1")] = s
|
||||
resp = _client(db, user, override_dep).post(
|
||||
f"/api/plex/item/{it.rating_key}/progress",
|
||||
@@ -175,7 +220,7 @@ def test_starting_a_session_leaves_another_viewers_paused_one_alone(
|
||||
db, monkeypatch, tmp_path, sessions, override_dep
|
||||
):
|
||||
"""The opportunistic sweep this route used to run was not scoped to the key being started: it
|
||||
walked the WHOLE registry with the 30 s finished rule, so pressing play on any item killed a
|
||||
walked the WHOLE registry with the finished rule, so pressing play on any item killed a
|
||||
paused viewer's session — the very case the retention fix set out to protect."""
|
||||
monkeypatch.setattr(state, "_configured_cache", True)
|
||||
monkeypatch.setattr(plex_paths, "local_media_path", lambda db_, fp: "/local/a.mkv")
|
||||
@@ -183,7 +228,7 @@ def test_starting_a_session_leaves_another_viewers_paused_one_alone(
|
||||
user = User(email="starter@example.com")
|
||||
db.add(user)
|
||||
db.commit()
|
||||
paused = _Session(tmp_path, "paused", finished=True, idle_s=90)
|
||||
paused = _Session(tmp_path, "paused", finished=True, idle_s=_PAST_THE_RULE)
|
||||
sessions[(999, "someone-else")] = paused
|
||||
|
||||
def fake_start(db_, item, user_id, start, audio=None, aoff=0.0, multi=False, transcode=False):
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Adding a video AT a position: the list page's "Undo" of a removal.
|
||||
"""Putting a video back AT a position: the list page's "Undo" of a removal.
|
||||
|
||||
The row has to come back where it was in ONE request. The two-call shape (append, then send the
|
||||
whole order) leaves it at the end of the list whenever the second call fails, and the reorder would
|
||||
@@ -38,14 +38,17 @@ def _ids(db, pl_id):
|
||||
]
|
||||
|
||||
|
||||
def _add(client, pl_id, body):
|
||||
return client.post(f"/api/playlists/{pl_id}/items", json=body)
|
||||
def _restore(client, pl_id, video_id, position):
|
||||
return client.post(
|
||||
f"/api/playlists/{pl_id}/items/restore",
|
||||
json={"video_ids": [video_id], "positions": [position]},
|
||||
)
|
||||
|
||||
|
||||
def test_a_position_puts_the_video_back_in_its_place(db, make_user, as_user):
|
||||
user = make_user()
|
||||
pl = _seed(db, user, ["a", "b", "c"])
|
||||
r = _add(as_user(user), pl.id, {"video_id": "vX", "position": 1})
|
||||
r = _restore(as_user(user), pl.id, "vX", 1)
|
||||
assert r.status_code == 200
|
||||
assert _ids(db, pl.id) == ["a", "vX", "b", "c"]
|
||||
|
||||
@@ -54,36 +57,37 @@ def test_the_position_counts_rows_not_stored_numbers(db, make_user, as_user):
|
||||
# A removal leaves a gap (0, 5, 9): index 2 is before the THIRD row, not "position 2".
|
||||
user = make_user()
|
||||
pl = _seed(db, user, ["a", "b", "c"], positions=[0, 5, 9])
|
||||
_add(as_user(user), pl.id, {"video_id": "vX", "position": 2})
|
||||
_restore(as_user(user), pl.id, "vX", 2)
|
||||
assert _ids(db, pl.id) == ["a", "b", "vX", "c"]
|
||||
|
||||
|
||||
def test_a_position_past_the_end_appends(db, make_user, as_user):
|
||||
user = make_user()
|
||||
pl = _seed(db, user, ["a", "b"])
|
||||
_add(as_user(user), pl.id, {"video_id": "vX", "position": 40})
|
||||
_restore(as_user(user), pl.id, "vX", 40)
|
||||
assert _ids(db, pl.id) == ["a", "b", "vX"]
|
||||
|
||||
|
||||
def test_no_position_still_appends(db, make_user, as_user):
|
||||
def test_an_add_appends(db, make_user, as_user):
|
||||
user = make_user()
|
||||
pl = _seed(db, user, ["a", "b"])
|
||||
_add(as_user(user), pl.id, {"video_id": "vX"})
|
||||
r = as_user(user).post(f"/api/playlists/{pl.id}/items", json={"video_id": "vX"})
|
||||
assert r.status_code == 200
|
||||
assert _ids(db, pl.id) == ["a", "b", "vX"]
|
||||
|
||||
|
||||
def test_a_video_already_in_the_list_does_not_move(db, make_user, as_user):
|
||||
# The add is idempotent; a position must not turn it into a reorder.
|
||||
# A restore is idempotent; a position must not turn it into a reorder.
|
||||
user = make_user()
|
||||
pl = _seed(db, user, ["a", "b", "c"])
|
||||
_add(as_user(user), pl.id, {"video_id": "c", "position": 0})
|
||||
_restore(as_user(user), pl.id, "c", 0)
|
||||
assert _ids(db, pl.id) == ["a", "b", "c"]
|
||||
|
||||
|
||||
def test_a_negative_position_is_refused(db, make_user, as_user):
|
||||
user = make_user()
|
||||
pl = _seed(db, user, ["a"])
|
||||
r = _add(as_user(user), pl.id, {"video_id": "vX", "position": -1})
|
||||
r = _restore(as_user(user), pl.id, "vX", -1)
|
||||
assert r.status_code == 422
|
||||
assert _ids(db, pl.id) == ["a"]
|
||||
|
||||
@@ -101,6 +105,6 @@ def test_putting_a_removed_video_back_leaves_a_linked_list_clean(db, make_user,
|
||||
assert client.delete(f"/api/playlists/{pl.id}/items/b").status_code == 200
|
||||
db.expire_all()
|
||||
assert db.get(Playlist, pl.id).dirty is True
|
||||
_add(client, pl.id, {"video_id": "b", "position": 1})
|
||||
_restore(client, pl.id, "b", 1)
|
||||
db.expire_all()
|
||||
assert db.get(Playlist, pl.id).dirty is False
|
||||
|
||||
@@ -0,0 +1,640 @@
|
||||
"""Many videos at once: remove, move, and the Undo of each. Every test reads both lists after the call,
|
||||
as `test_playlist_move` does: a half-applied move is the failure these routes exist to rule out."""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.catalog.models import Channel, Video
|
||||
from app.reader import queries, service
|
||||
from app.reader.models import Playlist, PlaylistItem
|
||||
from app.sync.playlists import current_fingerprint
|
||||
|
||||
|
||||
def _seed_videos(db, ids):
|
||||
db.add(Channel(id="UCtest", title="Test"))
|
||||
now = datetime.now(timezone.utc)
|
||||
for v in ids:
|
||||
db.add(Video(id=v, channel_id="UCtest", published_at=now))
|
||||
db.commit()
|
||||
|
||||
|
||||
def _playlist(db, user, name, video_ids, **kw):
|
||||
pl = Playlist(user_id=user.id, name=name, **kw)
|
||||
db.add(pl)
|
||||
db.flush()
|
||||
for i, vid in enumerate(video_ids):
|
||||
db.add(PlaylistItem(playlist_id=pl.id, video_id=vid, position=i))
|
||||
db.commit()
|
||||
return pl
|
||||
|
||||
|
||||
def _ids(db, pl_id):
|
||||
db.expire_all()
|
||||
return list(
|
||||
db.execute(
|
||||
select(PlaylistItem.video_id)
|
||||
.where(PlaylistItem.playlist_id == pl_id)
|
||||
.order_by(PlaylistItem.position)
|
||||
).scalars()
|
||||
)
|
||||
|
||||
|
||||
def _positions(db, pl_id):
|
||||
db.expire_all()
|
||||
return list(
|
||||
db.execute(
|
||||
select(PlaylistItem.position)
|
||||
.where(PlaylistItem.playlist_id == pl_id)
|
||||
.order_by(PlaylistItem.position)
|
||||
).scalars()
|
||||
)
|
||||
|
||||
|
||||
def test_remove_bulk_takes_out_the_named_videos_and_counts_what_was_there(db, make_user, as_user):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a", "b", "c", "d"])
|
||||
pl = _playlist(db, user, "L", ["a", "b", "c", "d"])
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{pl.id}/items/remove-bulk", json={"video_ids": ["b", "d", "gone"]}
|
||||
)
|
||||
|
||||
assert r.status_code == 200
|
||||
assert r.json() == {"ok": True, "playlist_id": pl.id, "removed": ["b", "d"]}
|
||||
assert _ids(db, pl.id) == ["a", "c"]
|
||||
|
||||
|
||||
def test_remove_bulk_of_nothing_leaves_the_list_untouched(db, make_user, as_user):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a"])
|
||||
pl = _playlist(db, user, "L", ["a"])
|
||||
stamp = datetime.now(timezone.utc) - timedelta(days=3)
|
||||
pl.updated_at = stamp
|
||||
db.commit()
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{pl.id}/items/remove-bulk", json={"video_ids": ["gone"]}
|
||||
)
|
||||
|
||||
assert r.json()["removed"] == []
|
||||
db.expire_all()
|
||||
assert db.get(Playlist, pl.id).updated_at == stamp
|
||||
|
||||
|
||||
def test_restore_puts_the_videos_back_at_their_places(db, make_user, as_user):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a", "b", "c", "d"])
|
||||
pl = _playlist(db, user, "L", ["b", "d"])
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{pl.id}/items/restore",
|
||||
json={"video_ids": ["c", "a"], "positions": [2, 0]},
|
||||
)
|
||||
|
||||
assert r.json() == {"ok": True, "playlist_id": pl.id, "added": 2}
|
||||
assert _ids(db, pl.id) == ["a", "b", "c", "d"]
|
||||
assert _positions(db, pl.id) == [0, 1, 2, 3]
|
||||
|
||||
|
||||
def test_restore_leaves_a_video_already_back_where_it_is_and_skips_one_the_catalog_lost(
|
||||
db, make_user, as_user
|
||||
):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a", "b"])
|
||||
pl = _playlist(db, user, "L", ["b", "a"])
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{pl.id}/items/restore",
|
||||
json={"video_ids": ["a", "lost"], "positions": [0, 1]},
|
||||
)
|
||||
|
||||
assert r.json()["added"] == 0
|
||||
assert _ids(db, pl.id) == ["b", "a"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{"video_ids": ["a"], "positions": []},
|
||||
{"video_ids": ["a"], "positions": [0, 1]},
|
||||
{"video_ids": ["a"], "positions": [-1]},
|
||||
],
|
||||
)
|
||||
def test_restore_refuses_positions_that_do_not_pair(db, make_user, as_user, body):
|
||||
user = make_user()
|
||||
pl = _playlist(db, user, "L", [])
|
||||
|
||||
assert as_user(user).post(f"/api/playlists/{pl.id}/items/restore", json=body).status_code == 422
|
||||
|
||||
|
||||
def test_move_bulk_lands_in_the_sources_order_whatever_order_they_were_picked_in(
|
||||
db, make_user, as_user
|
||||
):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a", "b", "c", "x"])
|
||||
src = _playlist(db, user, "Source", ["a", "b", "c"])
|
||||
dst = _playlist(db, user, "Target", ["x"])
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{src.id}/items/move-bulk",
|
||||
json={"video_ids": ["c", "a"], "target_playlist_id": dst.id},
|
||||
)
|
||||
|
||||
assert r.status_code == 200
|
||||
assert r.json() == {
|
||||
"ok": True,
|
||||
"from_playlist_id": src.id,
|
||||
"to_playlist_id": dst.id,
|
||||
"moved": ["a", "c"],
|
||||
"already_there": [],
|
||||
}
|
||||
assert _ids(db, src.id) == ["b"]
|
||||
assert _ids(db, dst.id) == ["x", "a", "c"]
|
||||
|
||||
|
||||
def test_move_bulk_says_which_the_target_already_held_and_skips_one_already_gone(
|
||||
db, make_user, as_user
|
||||
):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a", "b", "c"])
|
||||
src = _playlist(db, user, "Source", ["a", "b"])
|
||||
dst = _playlist(db, user, "Target", ["b"])
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{src.id}/items/move-bulk",
|
||||
json={"video_ids": ["a", "b", "c"], "target_playlist_id": dst.id},
|
||||
)
|
||||
|
||||
assert r.json()["moved"] == ["a"]
|
||||
assert r.json()["already_there"] == ["b"]
|
||||
assert _ids(db, src.id) == []
|
||||
assert _ids(db, dst.id) == ["b", "a"]
|
||||
|
||||
|
||||
def test_move_bulk_keeps_when_each_video_was_saved(db, make_user, as_user):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a"])
|
||||
src = _playlist(db, user, "Source", ["a"])
|
||||
dst = _playlist(db, user, "Target", [])
|
||||
saved = datetime(2020, 1, 2, tzinfo=timezone.utc)
|
||||
row = db.scalar(select(PlaylistItem).where(PlaylistItem.playlist_id == src.id))
|
||||
row.added_at = saved
|
||||
db.commit()
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{src.id}/items/move-bulk",
|
||||
json={"video_ids": ["a"], "target_playlist_id": dst.id},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
|
||||
db.expire_all()
|
||||
moved = db.scalar(select(PlaylistItem).where(PlaylistItem.playlist_id == dst.id))
|
||||
assert moved.added_at == saved
|
||||
|
||||
|
||||
def test_a_target_that_gained_nothing_does_not_rise_in_the_recently_changed_sort(
|
||||
db, make_user, as_user
|
||||
):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a"])
|
||||
src = _playlist(db, user, "Source", ["a"])
|
||||
dst = _playlist(db, user, "Target", ["a"])
|
||||
stamp = datetime.now(timezone.utc) - timedelta(days=3)
|
||||
dst.updated_at = stamp
|
||||
db.commit()
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{src.id}/items/move-bulk",
|
||||
json={"video_ids": ["a"], "target_playlist_id": dst.id},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
|
||||
db.expire_all()
|
||||
assert db.get(Playlist, dst.id).updated_at == stamp
|
||||
|
||||
|
||||
def test_move_bulk_into_the_same_list_is_refused(db, make_user, as_user):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a"])
|
||||
pl = _playlist(db, user, "L", ["a"])
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{pl.id}/items/move-bulk",
|
||||
json={"video_ids": ["a"], "target_playlist_id": pl.id},
|
||||
)
|
||||
|
||||
assert r.status_code == 400
|
||||
assert r.json()["detail"] == {"code": "playlist_move", "reason": "same_playlist"}
|
||||
assert _ids(db, pl.id) == ["a"]
|
||||
|
||||
|
||||
def test_move_bulk_marks_a_linked_list_on_both_sides_as_unsynced(db, make_user, as_user):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a"])
|
||||
src = _playlist(db, user, "Source", ["a"], yt_playlist_id="PLs")
|
||||
dst = _playlist(db, user, "Target", [], yt_playlist_id="PLd")
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{src.id}/items/move-bulk",
|
||||
json={"video_ids": ["a"], "target_playlist_id": dst.id},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
|
||||
db.expire_all()
|
||||
assert db.get(Playlist, src.id).dirty is True
|
||||
assert db.get(Playlist, dst.id).dirty is True
|
||||
|
||||
|
||||
def test_undo_move_restores_both_lists_as_they_stood(db, make_user, as_user):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a", "b", "c", "d"])
|
||||
src = _playlist(db, user, "Source", ["a", "b", "c", "d"])
|
||||
dst = _playlist(db, user, "Target", ["c"])
|
||||
client = as_user(user)
|
||||
|
||||
moved = client.post(
|
||||
f"/api/playlists/{src.id}/items/move-bulk",
|
||||
json={"video_ids": ["a", "c"], "target_playlist_id": dst.id},
|
||||
).json()
|
||||
assert _ids(db, src.id) == ["b", "d"]
|
||||
assert _ids(db, dst.id) == ["c", "a"]
|
||||
|
||||
r = client.post(
|
||||
f"/api/playlists/{src.id}/items/undo-move",
|
||||
json={
|
||||
"from_playlist_id": dst.id,
|
||||
"moved": moved["moved"],
|
||||
"already_there": moved["already_there"],
|
||||
"positions": [0, 2],
|
||||
},
|
||||
)
|
||||
|
||||
assert r.json() == {"ok": True, "playlist_id": src.id, "added": 2}
|
||||
assert _ids(db, src.id) == ["a", "b", "c", "d"]
|
||||
# The one the target held before the move stays there.
|
||||
assert _ids(db, dst.id) == ["c"]
|
||||
|
||||
|
||||
def test_undo_move_keeps_when_each_video_was_saved(db, make_user, as_user):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a"])
|
||||
src = _playlist(db, user, "Source", [])
|
||||
dst = _playlist(db, user, "Target", ["a"])
|
||||
saved = datetime(2020, 1, 2, tzinfo=timezone.utc)
|
||||
row = db.scalar(select(PlaylistItem).where(PlaylistItem.playlist_id == dst.id))
|
||||
row.added_at = saved
|
||||
db.commit()
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{src.id}/items/undo-move",
|
||||
json={"from_playlist_id": dst.id, "moved": ["a"], "positions": [0]},
|
||||
)
|
||||
|
||||
assert r.json()["added"] == 1
|
||||
db.expire_all()
|
||||
back = db.scalar(select(PlaylistItem).where(PlaylistItem.playlist_id == src.id))
|
||||
assert back.added_at == saved
|
||||
|
||||
|
||||
def test_undo_move_leaves_a_video_that_moved_on_where_it_is(db, make_user, as_user):
|
||||
"""A to B, then B to C, then the first Undo: the video is not in the list the Undo takes it from,
|
||||
and coming back would leave it in two lists the reader never put it in."""
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a", "b"])
|
||||
src = _playlist(db, user, "Source", [])
|
||||
dst = _playlist(db, user, "Target", ["b"])
|
||||
third = _playlist(db, user, "Third", ["a"])
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{src.id}/items/undo-move",
|
||||
json={"from_playlist_id": dst.id, "moved": ["a", "b"], "positions": [0, 1]},
|
||||
)
|
||||
|
||||
assert r.json()["added"] == 1
|
||||
assert _ids(db, src.id) == ["b"]
|
||||
assert _ids(db, dst.id) == []
|
||||
assert _ids(db, third.id) == ["a"]
|
||||
|
||||
|
||||
def test_an_undo_closes_up_the_places_of_a_video_that_stayed_out(db, make_user, as_user):
|
||||
"""Each index counts the rows put back before it, so one that stays out moves the rest up."""
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a", "b", "c", "d"])
|
||||
src = _playlist(db, user, "Source", ["c", "d"])
|
||||
dst = _playlist(db, user, "Target", ["b"])
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{src.id}/items/undo-move",
|
||||
json={"from_playlist_id": dst.id, "moved": ["a", "b"], "positions": [0, 1]},
|
||||
)
|
||||
|
||||
assert r.json()["added"] == 1
|
||||
assert _ids(db, src.id) == ["b", "c", "d"]
|
||||
|
||||
|
||||
def test_a_restore_closes_up_the_places_of_a_video_the_catalog_lost(db, make_user, as_user):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["b", "c", "d"])
|
||||
pl = _playlist(db, user, "L", ["c", "d"])
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{pl.id}/items/restore",
|
||||
json={"video_ids": ["lost", "b"], "positions": [0, 1]},
|
||||
)
|
||||
|
||||
assert r.json()["added"] == 1
|
||||
assert _ids(db, pl.id) == ["b", "c", "d"]
|
||||
|
||||
|
||||
def test_undo_move_takes_a_video_out_of_the_target_when_the_source_has_it_again(
|
||||
db, make_user, as_user
|
||||
):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a"])
|
||||
src = _playlist(db, user, "Source", ["a"])
|
||||
dst = _playlist(db, user, "Target", ["a"])
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{src.id}/items/undo-move",
|
||||
json={"from_playlist_id": dst.id, "moved": ["a"], "positions": [0]},
|
||||
)
|
||||
|
||||
assert r.json()["added"] == 0
|
||||
assert _ids(db, src.id) == ["a"]
|
||||
assert _ids(db, dst.id) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("path", "body", "gone", "reason"),
|
||||
[
|
||||
("move-bulk", {"video_ids": ["a"], "target_playlist_id": "dst"}, "dst", "move_target"),
|
||||
("move-bulk", {"video_ids": ["a"], "target_playlist_id": "dst"}, "src", "playlist"),
|
||||
(
|
||||
"undo-move",
|
||||
{"from_playlist_id": "dst", "moved": ["a"], "positions": [0]},
|
||||
"src",
|
||||
"playlist",
|
||||
),
|
||||
(
|
||||
"undo-move",
|
||||
{"from_playlist_id": "dst", "moved": ["a"], "positions": [0]},
|
||||
"dst",
|
||||
"move_target",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_a_list_deleted_before_the_lock_is_not_found(
|
||||
db, make_user, as_user, monkeypatch, path, body, gone, reason
|
||||
):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a"])
|
||||
src = _playlist(db, user, "Source", ["a"])
|
||||
dst = _playlist(db, user, "Target", ["a"])
|
||||
ids = {"src": src.id, "dst": dst.id}
|
||||
body = {k: (dst.id if v == "dst" else v) for k, v in body.items()}
|
||||
# Another tab's delete committed between the route's read and this lock.
|
||||
monkeypatch.setattr(service, "lock_playlists", lambda _db, *got: set(got) - {ids[gone]})
|
||||
|
||||
r = as_user(user).post(f"/api/playlists/{src.id}/items/{path}", json=body)
|
||||
|
||||
assert r.status_code == 404
|
||||
assert reason in str(r.json()["detail"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "path", "body"),
|
||||
[
|
||||
("post", "items", {"video_id": "a"}),
|
||||
("delete", "items/a", None),
|
||||
("post", "items/remove-bulk", {"video_ids": ["a"]}),
|
||||
("post", "items/restore", {"video_ids": ["a"], "positions": [0]}),
|
||||
],
|
||||
)
|
||||
def test_a_one_list_write_finds_its_list_under_the_lock(
|
||||
db, make_user, as_user, monkeypatch, method, path, body
|
||||
):
|
||||
"""Read with its lock, so a delete that won the row answers 404 rather than a foreign key's 500."""
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a"])
|
||||
pl = _playlist(db, user, "L", [])
|
||||
real = queries.own_playlist
|
||||
|
||||
def locked_read_finds_nothing(db_, user_, playlist_id, *, lock=False):
|
||||
return None if lock else real(db_, user_, playlist_id)
|
||||
|
||||
monkeypatch.setattr(queries, "own_playlist", locked_read_finds_nothing)
|
||||
kw = {"json": body} if body is not None else {}
|
||||
|
||||
r = getattr(as_user(user), method)(f"/api/playlists/{pl.id}/{path}", **kw)
|
||||
|
||||
assert r.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("path", "body"),
|
||||
[
|
||||
("items/remove-bulk", {"ids": ["a"]}),
|
||||
("items/move-bulk", {"ids": ["a"], "target_playlist_id": 1}),
|
||||
("items/undo-move", {"ids": ["a"], "from_playlist_id": 1}),
|
||||
],
|
||||
)
|
||||
def test_a_body_without_its_videos_is_refused_rather_than_acting_on_none(
|
||||
db, make_user, as_user, path, body
|
||||
):
|
||||
user = make_user()
|
||||
pl = _playlist(db, user, "L", [])
|
||||
|
||||
assert as_user(user).post(f"/api/playlists/{pl.id}/{path}", json=body).status_code == 422
|
||||
|
||||
|
||||
def test_an_undo_of_only_videos_the_target_held_names_no_moved_ones(db, make_user, as_user):
|
||||
"""An empty `moved` is a real body: every video of the move was already in the target."""
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a"])
|
||||
src = _playlist(db, user, "Source", [])
|
||||
dst = _playlist(db, user, "Target", ["a"])
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{src.id}/items/undo-move",
|
||||
json={"from_playlist_id": dst.id, "moved": [], "already_there": ["a"], "positions": [0]},
|
||||
)
|
||||
|
||||
assert r.json()["added"] == 1
|
||||
assert _ids(db, src.id) == ["a"]
|
||||
assert _ids(db, dst.id) == ["a"]
|
||||
|
||||
|
||||
def test_an_undo_within_one_list_is_refused_and_keeps_its_videos(db, make_user, as_user):
|
||||
"""A move refuses the same list twice, so no Undo of one exists; a row must not go for asking."""
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a", "b"])
|
||||
pl = _playlist(db, user, "L", ["a", "b"])
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{pl.id}/items/undo-move",
|
||||
json={"from_playlist_id": pl.id, "moved": ["a"], "positions": [0]},
|
||||
)
|
||||
|
||||
assert r.status_code == 400
|
||||
assert r.json()["detail"] == {"code": "playlist_move", "reason": "same_playlist"}
|
||||
assert _ids(db, pl.id) == ["a", "b"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("path", "key", "extra"),
|
||||
[
|
||||
("items/restore", "video_ids", {}),
|
||||
("items/undo-move", "moved", {"from_playlist_id": None}),
|
||||
],
|
||||
)
|
||||
def test_two_videos_cannot_ask_for_one_place(db, make_user, as_user, path, key, extra):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a", "b", "c"])
|
||||
pl = _playlist(db, user, "L", ["c"])
|
||||
other = _playlist(db, user, "Other", ["a", "b"])
|
||||
body = {key: ["a", "b"], "positions": [0, 0]}
|
||||
body.update({k: other.id for k in extra})
|
||||
|
||||
r = as_user(user).post(f"/api/playlists/{pl.id}/{path}", json=body)
|
||||
|
||||
assert r.status_code == 422
|
||||
assert _ids(db, pl.id) == ["c"]
|
||||
|
||||
|
||||
def test_a_reorder_without_its_videos_is_refused(db, make_user, as_user):
|
||||
user = make_user()
|
||||
pl = _playlist(db, user, "L", [])
|
||||
|
||||
assert as_user(user).put(f"/api/playlists/{pl.id}/order", json={"ids": []}).status_code == 422
|
||||
|
||||
|
||||
def _synced(db, pl):
|
||||
pl.synced_fingerprint = current_fingerprint(db, pl)
|
||||
pl.dirty = False
|
||||
db.commit()
|
||||
|
||||
|
||||
def test_a_bulk_remove_and_its_undo_leave_a_linked_list_as_it_was(db, make_user, as_user):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a", "b"])
|
||||
pl = _playlist(db, user, "L", ["a", "b"], yt_playlist_id="PLx")
|
||||
_synced(db, pl)
|
||||
client = as_user(user)
|
||||
|
||||
r = client.post(f"/api/playlists/{pl.id}/items/remove-bulk", json={"video_ids": ["a"]})
|
||||
assert r.status_code == 200
|
||||
db.expire_all()
|
||||
assert db.get(Playlist, pl.id).dirty is True
|
||||
|
||||
r = client.post(
|
||||
f"/api/playlists/{pl.id}/items/restore", json={"video_ids": ["a"], "positions": [0]}
|
||||
)
|
||||
assert r.status_code == 200
|
||||
db.expire_all()
|
||||
assert db.get(Playlist, pl.id).dirty is False
|
||||
|
||||
|
||||
def test_a_move_and_its_undo_leave_both_linked_lists_as_they_were(db, make_user, as_user):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a", "b"])
|
||||
src = _playlist(db, user, "Source", ["a", "b"], yt_playlist_id="PLs")
|
||||
dst = _playlist(db, user, "Target", ["b"], yt_playlist_id="PLd")
|
||||
_synced(db, src)
|
||||
_synced(db, dst)
|
||||
client = as_user(user)
|
||||
|
||||
moved = client.post(
|
||||
f"/api/playlists/{src.id}/items/move-bulk",
|
||||
json={"video_ids": ["a"], "target_playlist_id": dst.id},
|
||||
).json()
|
||||
assert moved["moved"] == ["a"]
|
||||
db.expire_all()
|
||||
assert db.get(Playlist, src.id).dirty is True
|
||||
assert db.get(Playlist, dst.id).dirty is True
|
||||
|
||||
r = client.post(
|
||||
f"/api/playlists/{src.id}/items/undo-move",
|
||||
json={"from_playlist_id": dst.id, "moved": ["a"], "positions": [0]},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
db.expire_all()
|
||||
assert db.get(Playlist, src.id).dirty is False
|
||||
assert db.get(Playlist, dst.id).dirty is False
|
||||
|
||||
|
||||
def test_undo_move_is_one_transaction(db, make_user, as_user, monkeypatch):
|
||||
user = make_user()
|
||||
_seed_videos(db, ["a"])
|
||||
src = _playlist(db, user, "Source", [])
|
||||
dst = _playlist(db, user, "Target", ["a"])
|
||||
|
||||
def boom(*a, **kw):
|
||||
raise RuntimeError("second step failed")
|
||||
|
||||
monkeypatch.setattr(service, "_insert_at", boom)
|
||||
client = as_user(user)
|
||||
body = {"from_playlist_id": dst.id, "moved": ["a"], "already_there": [], "positions": [0]}
|
||||
with pytest.raises(RuntimeError):
|
||||
_ = client.post(f"/api/playlists/{src.id}/items/undo-move", json=body)
|
||||
|
||||
db.rollback()
|
||||
assert _ids(db, dst.id) == ["a"]
|
||||
assert _ids(db, src.id) == []
|
||||
|
||||
|
||||
def test_undo_move_refuses_positions_that_do_not_pair(db, make_user, as_user):
|
||||
user = make_user()
|
||||
src = _playlist(db, user, "Source", [])
|
||||
dst = _playlist(db, user, "Target", [])
|
||||
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{src.id}/items/undo-move",
|
||||
json={"from_playlist_id": dst.id, "moved": ["a"], "already_there": ["b"], "positions": [0]},
|
||||
)
|
||||
|
||||
assert r.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("path", "body"),
|
||||
[
|
||||
("remove-bulk", {"video_ids": ["a"]}),
|
||||
("restore", {"video_ids": ["a"], "positions": [0]}),
|
||||
("move-bulk", {"video_ids": ["a"], "target_playlist_id": 0}),
|
||||
("undo-move", {"from_playlist_id": 0, "moved": ["a"], "positions": [0]}),
|
||||
],
|
||||
)
|
||||
def test_another_accounts_list_is_not_found(db, make_user, as_user, path, body):
|
||||
owner, other = make_user(), make_user()
|
||||
_seed_videos(db, ["a"])
|
||||
theirs = _playlist(db, owner, "Theirs", ["a"])
|
||||
mine = _playlist(db, other, "Mine", [])
|
||||
body = {
|
||||
k: (mine.id if k in ("target_playlist_id", "from_playlist_id") else v)
|
||||
for k, v in body.items()
|
||||
}
|
||||
|
||||
r = as_user(other).post(f"/api/playlists/{theirs.id}/items/{path}", json=body)
|
||||
|
||||
assert r.status_code == 404
|
||||
assert _ids(db, theirs.id) == ["a"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("path", "key"), [("move-bulk", "target_playlist_id"), ("undo-move", "from_playlist_id")]
|
||||
)
|
||||
def test_the_other_list_of_a_move_must_be_the_callers_too(db, make_user, as_user, path, key):
|
||||
owner, other = make_user(), make_user()
|
||||
_seed_videos(db, ["a"])
|
||||
theirs = _playlist(db, owner, "Theirs", ["a"])
|
||||
mine = _playlist(db, other, "Mine", ["a"])
|
||||
body = {"video_ids": ["a"], "moved": ["a"], "positions": [0], key: theirs.id}
|
||||
|
||||
r = as_user(other).post(f"/api/playlists/{mine.id}/items/{path}", json=body)
|
||||
|
||||
assert r.status_code == 404
|
||||
assert "move_target" in str(r.json()["detail"])
|
||||
assert _ids(db, theirs.id) == ["a"]
|
||||
assert _ids(db, mine.id) == ["a"]
|
||||
@@ -51,7 +51,8 @@ def _ids(db, pl_id):
|
||||
|
||||
def _move(client, src, video_id, dst):
|
||||
return client.post(
|
||||
f"/api/playlists/{src}/items/{video_id}/move", json={"target_playlist_id": dst}
|
||||
f"/api/playlists/{src}/items/move-bulk",
|
||||
json={"video_ids": [video_id], "target_playlist_id": dst},
|
||||
)
|
||||
|
||||
|
||||
@@ -67,7 +68,8 @@ def test_move_leaves_the_video_in_exactly_one_list(db, make_user, as_user):
|
||||
"ok": True,
|
||||
"from_playlist_id": src.id,
|
||||
"to_playlist_id": dst.id,
|
||||
"video_id": "v1",
|
||||
"moved": ["v1"],
|
||||
"already_there": [],
|
||||
}
|
||||
db.expire_all()
|
||||
assert _ids(db, src.id) == ["v2"]
|
||||
@@ -116,8 +118,9 @@ def test_move_of_a_video_that_left_the_source_reports_it(db, make_user, as_user)
|
||||
dst = _playlist(db, user, "Target", [])
|
||||
|
||||
r = _move(as_user(user), src.id, "v1", dst.id)
|
||||
assert r.status_code == 404
|
||||
assert r.json()["detail"] == {"code": "playlist_move", "reason": "not_in_playlist"}
|
||||
assert r.status_code == 200
|
||||
assert (r.json()["moved"], r.json()["already_there"]) == ([], [])
|
||||
assert _ids(db, dst.id) == []
|
||||
|
||||
|
||||
def test_move_into_someone_elses_list_404s_and_changes_nothing(db, make_user, as_user):
|
||||
|
||||
@@ -102,16 +102,24 @@ PLEX = PlexPlaylist.__table__.name
|
||||
"call",
|
||||
[
|
||||
lambda c, pid, other: c.post(f"/api/playlists/{pid}/items", json={"video_id": "v2"}),
|
||||
lambda c, pid, other: c.post(
|
||||
f"/api/playlists/{pid}/items", json={"video_id": "v2", "position": 0}
|
||||
),
|
||||
lambda c, pid, other: c.post("/api/playlists/watch-later", json={"video_id": "v2"}),
|
||||
lambda c, pid, other: c.post(
|
||||
f"/api/playlists/{pid}/items/v1/move", json={"target_playlist_id": other}
|
||||
f"/api/playlists/{pid}/items/move-bulk",
|
||||
json={"video_ids": ["v1"], "target_playlist_id": other},
|
||||
),
|
||||
lambda c, pid, other: c.put(f"/api/playlists/{pid}/order", json={"video_ids": ["v1"]}),
|
||||
lambda c, pid, other: c.post(
|
||||
f"/api/playlists/{pid}/items/remove-bulk", json={"video_ids": ["v1"]}
|
||||
),
|
||||
lambda c, pid, other: c.post(
|
||||
f"/api/playlists/{pid}/items/restore", json={"video_ids": ["v2"], "positions": [0]}
|
||||
),
|
||||
lambda c, pid, other: c.post(
|
||||
f"/api/playlists/{pid}/items/undo-move",
|
||||
json={"from_playlist_id": other, "moved": ["v2"], "positions": [0]},
|
||||
),
|
||||
],
|
||||
ids=["add", "add-at", "watch-later", "move", "reorder"],
|
||||
ids=["add", "watch-later", "move", "reorder", "remove-bulk", "restore", "undo-move"],
|
||||
)
|
||||
def test_a_youtube_playlist_write_locks_the_playlist(db, make_user, as_user, locks, call):
|
||||
user = make_user()
|
||||
@@ -168,18 +176,35 @@ PLEX_ITEMS = PlexPlaylistItem.__table__.name
|
||||
"call",
|
||||
[
|
||||
lambda c, pid, other: c.post(f"/api/playlists/{pid}/items", json={"video_id": "v1"}),
|
||||
lambda c, pid, other: c.post(
|
||||
f"/api/playlists/{pid}/items", json={"video_id": "v2", "position": 0}
|
||||
),
|
||||
lambda c, pid, other: c.delete(f"/api/playlists/{pid}/items/v1"),
|
||||
lambda c, pid, other: c.post(
|
||||
f"/api/playlists/{pid}/items/v1/move", json={"target_playlist_id": other}
|
||||
f"/api/playlists/{pid}/items/move-bulk",
|
||||
json={"video_ids": ["v1"], "target_playlist_id": other},
|
||||
),
|
||||
lambda c, pid, other: c.put(f"/api/playlists/{pid}/order", json={"video_ids": ["v1"]}),
|
||||
# the ORM cascade deletes the items before the list row
|
||||
lambda c, pid, other: c.delete(f"/api/playlists/{pid}"),
|
||||
lambda c, pid, other: c.post(
|
||||
f"/api/playlists/{pid}/items/remove-bulk", json={"video_ids": ["v1"]}
|
||||
),
|
||||
lambda c, pid, other: c.post(
|
||||
f"/api/playlists/{pid}/items/restore", json={"video_ids": ["v2"], "positions": [0]}
|
||||
),
|
||||
lambda c, pid, other: c.post(
|
||||
f"/api/playlists/{pid}/items/undo-move",
|
||||
json={"from_playlist_id": other, "moved": ["v2"], "positions": [0]},
|
||||
),
|
||||
],
|
||||
ids=[
|
||||
"add-present",
|
||||
"remove",
|
||||
"move",
|
||||
"reorder",
|
||||
"delete",
|
||||
"remove-bulk",
|
||||
"restore",
|
||||
"undo-move",
|
||||
],
|
||||
ids=["add-present", "add-at", "remove", "move", "reorder", "delete"],
|
||||
)
|
||||
def test_a_youtube_item_write_locks_the_playlist_before_any_item(
|
||||
db, make_user, as_user, statements, call
|
||||
@@ -193,14 +218,23 @@ def test_a_youtube_item_write_locks_the_playlist_before_any_item(
|
||||
assert _locked_before_items(statements, YT, YT_ITEMS), statements
|
||||
|
||||
|
||||
def test_a_move_locks_both_lists_in_one_ordered_statement(db, make_user, as_user, statements):
|
||||
"""Two moves A→B and B→A each locking "its" list first would lock crosswise."""
|
||||
@pytest.mark.parametrize(
|
||||
("path", "body"),
|
||||
[
|
||||
("move-bulk", lambda other: {"video_ids": ["v1"], "target_playlist_id": other}),
|
||||
("undo-move", lambda other: {"from_playlist_id": other, "moved": ["v2"], "positions": [0]}),
|
||||
],
|
||||
ids=["move", "undo"],
|
||||
)
|
||||
def test_a_move_locks_both_lists_in_one_ordered_statement(
|
||||
db, make_user, as_user, statements, path, body
|
||||
):
|
||||
"""Two moves A→B and B→A each locking "its" list first would lock crosswise, and an Undo runs the
|
||||
other way round from a move by its nature."""
|
||||
user = make_user()
|
||||
pid, other = _yt(db, user)
|
||||
statements.clear()
|
||||
r = as_user(user).post(
|
||||
f"/api/playlists/{pid}/items/v1/move", json={"target_playlist_id": other}
|
||||
)
|
||||
r = as_user(user).post(f"/api/playlists/{pid}/items/{path}", json=body(other))
|
||||
assert r.status_code == 200, r.text
|
||||
lock = _locked_before_items(statements, YT, YT_ITEMS)
|
||||
assert lock and "ORDER BY" in lock, lock
|
||||
|
||||
@@ -219,6 +219,7 @@ def test_item_detail_movie_serves_from_row_despite_live_outage(db, monkeypatch,
|
||||
library_id=lib.id,
|
||||
kind="movie",
|
||||
title="The Godfather",
|
||||
size_bytes=15_000_000_000,
|
||||
genres=["Crime", "Drama"],
|
||||
directors=["Francis Ford Coppola"],
|
||||
studio="Paramount",
|
||||
@@ -238,6 +239,7 @@ def test_item_detail_movie_serves_from_row_despite_live_outage(db, monkeypatch,
|
||||
resp = _get(db, user, monkeypatch, override_dep, "/api/plex/item/m1")
|
||||
assert resp.status_code == 200, resp.text
|
||||
body = resp.json()
|
||||
assert body["size_bytes"] == 15_000_000_000
|
||||
assert body["imdb_rating"] == 8.7
|
||||
assert body["imdb_id"] == "tt0068646"
|
||||
assert body["imdb_url"] == "https://www.imdb.com/title/tt0068646/"
|
||||
|
||||
@@ -5,7 +5,7 @@ seek-restart — or a second viewer of the same item — replaces the registered
|
||||
viewer's next request for `seg_12.ts`, resolved by rating_key, was answered 200 with the NEW
|
||||
session's twelfth segment: bytes produced from a different `-ss` offset under `-copyts`, i.e. a
|
||||
timeline the client is not on. Wrong content with a success status is the one failure a player cannot
|
||||
notice, and the client's reclaim-on-404 could never fire on it.
|
||||
notice, and the client's reclaim could never fire on it.
|
||||
|
||||
No `db` fixture: the route reads nothing from the database (its own `Depends(get_db)` went with the
|
||||
removed auto-start, and `current_user` is overridden wholesale), so these must not sit in the DB
|
||||
@@ -88,10 +88,10 @@ def test_another_viewers_session_of_the_same_item_is_not_this_viewers(client, tm
|
||||
(d / "index.m3u8").write_bytes(b"#EXTM3U")
|
||||
sessions[(7, "m1")] = _Session("sid-a", d)
|
||||
r = client.get("/api/plex/stream/m1/hls/sid-a/index.m3u8")
|
||||
assert r.status_code == 404, r.text
|
||||
assert r.status_code == 410, r.text
|
||||
|
||||
|
||||
def test_a_segment_of_a_replaced_session_is_a_404_not_the_new_sessions_bytes(
|
||||
def test_a_segment_of_a_replaced_session_is_gone_not_the_new_sessions_bytes(
|
||||
client, tmp_path, sessions
|
||||
):
|
||||
"""Viewer A is at 0:00; viewer B seeks to 25:00 and their session takes the registry slot. A's
|
||||
@@ -102,15 +102,15 @@ def test_a_segment_of_a_replaced_session_is_a_404_not_the_new_sessions_bytes(
|
||||
(theirs / "seg_12.ts").write_bytes(b"theirs")
|
||||
sessions[(VIEWER, "m1")] = _Session("sid-b", theirs)
|
||||
r = client.get("/api/plex/stream/m1/hls/sid-a/seg_12.ts")
|
||||
assert r.status_code == 404, r.text
|
||||
assert r.status_code == 410, r.text
|
||||
assert b"theirs" not in r.content
|
||||
|
||||
|
||||
def test_a_playlist_with_no_live_session_is_a_404_not_a_silent_restart_at_zero(
|
||||
def test_a_playlist_with_no_live_session_is_gone_not_a_silent_restart_at_zero(
|
||||
client, monkeypatch, sessions
|
||||
):
|
||||
"""The entry playlist used to auto-start a session when none was registered — always at 0.0,
|
||||
silently throwing away the viewer's position. A 404 sends the player through its own reclaim,
|
||||
silently throwing away the viewer's position. A 410 sends the player through its own reclaim,
|
||||
which restarts at the playhead."""
|
||||
started: list[float] = []
|
||||
monkeypatch.setattr(
|
||||
@@ -119,7 +119,7 @@ def test_a_playlist_with_no_live_session_is_a_404_not_a_silent_restart_at_zero(
|
||||
lambda *a, **k: started.append(a[3] if len(a) > 3 else 0.0),
|
||||
)
|
||||
r = client.get("/api/plex/stream/m1/hls/sid-gone/index.m3u8")
|
||||
assert r.status_code == 404, r.text
|
||||
assert r.status_code == 410, r.text
|
||||
assert started == []
|
||||
|
||||
|
||||
@@ -235,12 +235,12 @@ def test_an_absurd_segment_index_is_a_404_not_a_500(client, tmp_path, sessions,
|
||||
assert r.status_code == 404, r.text
|
||||
|
||||
|
||||
def test_a_session_torn_down_during_the_read_is_a_404_not_a_500(
|
||||
def test_a_session_torn_down_during_the_read_is_gone_not_a_500(
|
||||
client, monkeypatch, tmp_path, sessions
|
||||
):
|
||||
"""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
|
||||
session before destroying the old hls instance. The player's recovery is keyed on the
|
||||
STATUS, so a 500 here skipped the reclaim and ended playback with "couldn't play"."""
|
||||
d = tmp_path / "m1_0_0_+0.00"
|
||||
d.mkdir()
|
||||
@@ -249,7 +249,7 @@ def test_a_session_torn_down_during_the_read_is_a_404_not_a_500(
|
||||
# The file existed when the wait checked, and is gone by the time the route reads it.
|
||||
monkeypatch.setattr(plex_stream, "wait_for", lambda *a, **k: True)
|
||||
r = client.get("/api/plex/stream/m1/hls/sid-a/seg_12.ts")
|
||||
assert r.status_code == 404, r.text
|
||||
assert r.status_code == 410, r.text
|
||||
|
||||
|
||||
def test_a_dead_producer_is_not_waited_out(client, tmp_path, sessions):
|
||||
|
||||
@@ -6,6 +6,8 @@ rows, since positions have gaps after a removal. One request: an append plus a s
|
||||
leaves the rows at the end whenever that call fails, and would overwrite another tab's changes.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.plex.models import PlexItem, PlexLibrary, PlexPlaylist, PlexPlaylistItem
|
||||
|
||||
|
||||
@@ -101,6 +103,22 @@ def test_positions_must_pair_with_the_keys(db, make_user, as_user):
|
||||
assert _order(db, pl.id)[0] == ["a"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "path"),
|
||||
[("post", "items/bulk"), ("post", "items/remove-bulk"), ("put", "order")],
|
||||
)
|
||||
def test_a_body_without_its_keys_is_refused_rather_than_acting_on_none(
|
||||
db, make_user, as_user, method, path
|
||||
):
|
||||
user = make_user()
|
||||
pl = _seed(db, user, ["a"], extra=())
|
||||
|
||||
r = getattr(as_user(user), method)(f"/api/plex/playlists/{pl.id}/{path}", json={"keys": ["a"]})
|
||||
|
||||
assert r.status_code == 422
|
||||
assert _order(db, pl.id)[0] == ["a"]
|
||||
|
||||
|
||||
def test_remove_then_put_back_is_no_change(db, make_user, as_user):
|
||||
user = make_user()
|
||||
pl = _seed(db, user, ["a", "b", "c", "d"], extra=())
|
||||
|
||||
@@ -14,7 +14,7 @@ from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.discover import pins
|
||||
from app.catalog.models import Channel, Video
|
||||
from app.catalog.models import Channel, Subscription, Video
|
||||
from app.reader import queries, service
|
||||
from app.reader.models import ChannelTag, ComfortPin, Playlist, PlaylistItem, Tag, VideoState
|
||||
|
||||
@@ -60,12 +60,44 @@ def test_a_system_tag_is_nobodys_to_edit(db, make_user):
|
||||
service.create_tag(db, other, "Theirs", "other", None) # another user's tag stays theirs
|
||||
db.commit()
|
||||
assert queries.own_tag(db, user, system.id) is None
|
||||
assert [t.id for t, _ in queries.tags_with_counts(db, user)] == [system.id]
|
||||
assert [t.id for t, *_ in queries.tags_with_counts(db, user)] == [system.id]
|
||||
|
||||
|
||||
# --- tags ------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _music_on_four(db, make_user):
|
||||
"""A tag on four channels: two followed, one followed but hidden, one no longer followed."""
|
||||
user, other = make_user(), make_user()
|
||||
tag = service.create_tag(db, user, "Music", "other", None)
|
||||
for cid in ("UCa", "UCb", "UChid", "UCgone"):
|
||||
db.add(Channel(id=cid, title=cid))
|
||||
db.flush()
|
||||
for cid in ("UCa", "UCb"):
|
||||
db.add(Subscription(user_id=user.id, channel_id=cid))
|
||||
db.add(Subscription(user_id=user.id, channel_id="UChid", hidden=True))
|
||||
db.add(Subscription(user_id=other.id, channel_id="UCgone"))
|
||||
for cid in ("UCa", "UCb", "UChid", "UCgone"):
|
||||
db.add(ChannelTag(channel_id=cid, tag_id=tag.id, user_id=user.id, source="user"))
|
||||
db.commit()
|
||||
return user, tag
|
||||
|
||||
|
||||
def test_a_tag_counts_apart_the_links_on_channels_the_user_still_follows(db, make_user):
|
||||
"""An unsubscribe and a hide keep the channel's tag links; the Channels page's filter lists only
|
||||
the followed channels not hidden, so its count must not hold the others."""
|
||||
user, tag = _music_on_four(db, make_user)
|
||||
[(_, count, subscribed)] = [r for r in queries.tags_with_counts(db, user) if r[0].id == tag.id]
|
||||
assert (count, subscribed) == (4, 2)
|
||||
|
||||
|
||||
def test_the_tag_list_sends_each_count_under_its_own_name(db, make_user, as_user):
|
||||
"""Both counts are ints, so a swap would type-check: the answer itself pins which is which."""
|
||||
user, tag = _music_on_four(db, make_user)
|
||||
[row] = [t for t in as_user(user).get("/api/tags").json() if t["id"] == tag.id]
|
||||
assert (row["channel_count"], row["subscribed_count"]) == (4, 2)
|
||||
|
||||
|
||||
def test_a_tag_is_made_once_per_name_and_an_unknown_category_is_other(db, make_user):
|
||||
user = make_user()
|
||||
tag = service.create_tag(db, user, "Later", "nonsense", "#fff")
|
||||
@@ -210,9 +242,8 @@ def test_an_add_is_idempotent_and_lands_where_asked(db, make_user):
|
||||
pl = service.create_playlist(db, user, "L")
|
||||
assert service.add_item(db, pl, "a", mark_dirty=False) is True
|
||||
assert service.add_item(db, pl, "a", mark_dirty=False) is False
|
||||
service.add_to_playlist(db, pl, "b", None)
|
||||
service.add_to_playlist(db, pl, "c", 0)
|
||||
service.add_to_playlist(db, pl, "a", 2) # already there: stays put
|
||||
assert service.add_item(db, pl, "b", mark_dirty=True) is True
|
||||
assert service.restore_items(db, pl, ["c", "a"], [0, 2]) == 1 # "a" is there: it stays put
|
||||
assert _uncommitted(db)
|
||||
db.commit()
|
||||
assert _ids(db, pl) == ["c", "a", "b"]
|
||||
@@ -235,14 +266,13 @@ def test_a_move_never_leaves_a_video_in_two_lists(db, make_user):
|
||||
service.add_item(db, dst, "b", mark_dirty=False)
|
||||
db.commit()
|
||||
with pytest.raises(service.MoveRefused, match="same_playlist"):
|
||||
service.move_item(db, src, src, "a")
|
||||
service.move_item(db, src, dst, "a")
|
||||
service.move_item(db, src, dst, "b") # already in the target: dropped from the source
|
||||
service.move_items(db, src, src, ["a"])
|
||||
assert service.move_items(db, src, dst, ["a"]) == (["a"], [])
|
||||
# already in the target: dropped from the source
|
||||
assert service.move_items(db, src, dst, ["b"]) == ([], ["b"])
|
||||
db.commit()
|
||||
assert (_ids(db, src), _ids(db, dst)) == ([], ["b", "a"])
|
||||
with pytest.raises(service.MoveRefused, match="not_in_playlist"):
|
||||
service.move_item(db, src, dst, "a")
|
||||
db.rollback()
|
||||
assert service.move_items(db, src, dst, ["a"]) == ([], [])
|
||||
|
||||
|
||||
def test_a_reorder_keeps_what_it_left_out_after_the_listed(db, make_user):
|
||||
|
||||
@@ -310,6 +310,14 @@ def test_clearing_leaves_a_video_the_caller_never_found(db, make_user, as_user):
|
||||
assert r.json() == {"ok": True, "removed": 0}
|
||||
|
||||
|
||||
def test_clearing_refuses_a_body_without_its_list(db, make_user, as_user):
|
||||
# A misnamed key read as an empty list: 200, and nothing cleared.
|
||||
user = make_user()
|
||||
r = as_user(user).post("/api/search/clear", json={"ids": ["s1"]})
|
||||
assert r.status_code == 422
|
||||
assert as_user(user).post("/api/search/clear", json={"video_ids": []}).status_code == 200
|
||||
|
||||
|
||||
# --- Plex show and season marks ---------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
"""A share link's address says what it opens: /watch/ a video, /file/ anything else, /folder/ a folder.
|
||||
|
||||
Only a word for the reader: the token is the key, so every path opens every link, and the links
|
||||
already sent out on /watch/ keep working for good. DB-lane.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
from app import main, security
|
||||
from app.config import settings
|
||||
from app.downloads import og
|
||||
from app.downloads import probe as probemod
|
||||
|
||||
_PAGE = """<!doctype html><html><head>
|
||||
<!--OG:START--><meta property="og:title" content="Siftlode" /><!--OG:END-->
|
||||
</head><body><script src="/assets/{entry}.js"></script></body></html>"""
|
||||
|
||||
_VIDEO = {
|
||||
"streams": [
|
||||
{"codec_type": "video", "codec_name": "h264", "pix_fmt": "yuv420p"},
|
||||
{"codec_type": "audio", "codec_name": "aac"},
|
||||
],
|
||||
"format": {"format_name": "mov,mp4", "duration": "5"},
|
||||
}
|
||||
_AUDIO = {
|
||||
"streams": [{"codec_type": "audio", "codec_name": "aac"}],
|
||||
"format": {"format_name": "mov,mp4", "duration": "5"},
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pages(tmp_path, monkeypatch):
|
||||
index, watch = tmp_path / "index.html", tmp_path / "watch.html"
|
||||
index.write_text(_PAGE.format(entry="app"), encoding="utf-8")
|
||||
watch.write_text(_PAGE.format(entry="watch"), encoding="utf-8")
|
||||
monkeypatch.setattr(main, "INDEX_HTML", index)
|
||||
monkeypatch.setattr(main, "WATCH_HTML", watch)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def key(monkeypatch):
|
||||
"""A link's address is read back from its encrypted token."""
|
||||
monkeypatch.setattr(security, "_fernet", Fernet(Fernet.generate_key()))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def shared(as_user, make_user, tmp_path, monkeypatch, upload_headers):
|
||||
"""Uploads a file ffprobe reads as `data` (None: it cannot read it) and shares it."""
|
||||
monkeypatch.setattr(settings, "files_root", str(tmp_path / "media"))
|
||||
owner = as_user(make_user())
|
||||
|
||||
def share(name: str, data: dict | None, **link: object) -> dict:
|
||||
monkeypatch.setattr(probemod, "probe_json", lambda _p: data)
|
||||
job = owner.post(
|
||||
"/api/files/upload",
|
||||
content=b"some bytes",
|
||||
headers=upload_headers(name, display_name=name),
|
||||
)
|
||||
assert job.status_code == 200, job.text
|
||||
made = owner.post(f"/api/downloads/{job.json()['id']}/links", json=link)
|
||||
assert made.status_code == 200, made.text
|
||||
return made.json()
|
||||
|
||||
share.owner = owner # type: ignore[attr-defined]
|
||||
return share
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("name", "data", "prefix"),
|
||||
[
|
||||
("clip.mp4", _VIDEO, "/watch/"),
|
||||
("song.m4a", _AUDIO, "/file/"),
|
||||
("backup.tar.gz", None, "/file/"),
|
||||
],
|
||||
)
|
||||
def test_a_link_is_given_out_on_the_path_of_what_it_opens(shared, name, data, prefix):
|
||||
made = shared(name, data)
|
||||
assert made["url"] == f"{prefix}{made['token']}"
|
||||
|
||||
|
||||
def test_a_folder_link_is_given_out_on_folder(shared, key):
|
||||
owner = shared.owner
|
||||
folder = owner.post("/api/files/folders", json={"name": "Friends"}).json()
|
||||
made = owner.post(f"/api/downloads/folders/{folder['id']}/links", json={}).json()
|
||||
assert made["url"] == f"/folder/{made['token']}"
|
||||
listed = owner.get(f"/api/downloads/folders/{folder['id']}/links").json()
|
||||
assert [entry["url"] for entry in listed] == [made["url"]]
|
||||
|
||||
|
||||
def test_the_list_gives_the_same_address_as_the_making(shared, key):
|
||||
made = shared("backup.tar.gz", None)
|
||||
owner = shared.owner
|
||||
files = owner.get("/api/files").json()
|
||||
job_id = next(f["id"] for f in files if f["display_name"] == "backup.tar.gz")
|
||||
listed = owner.get(f"/api/downloads/{job_id}/links").json()
|
||||
assert [entry["url"] for entry in listed] == [made["url"]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["watch", "file", "folder"])
|
||||
@pytest.mark.parametrize(
|
||||
("name", "data"), [("clip.mp4", _VIDEO), ("backup.tar.gz", None)], ids=["video", "file"]
|
||||
)
|
||||
def test_every_path_opens_every_link(pages, shared, client, path, name, data):
|
||||
"""The links already sent on /watch/ open whatever they open, for good."""
|
||||
token = shared(name, data)["token"]
|
||||
r = client.get(f"/{path}/{token}")
|
||||
assert r.status_code == 200
|
||||
assert "/assets/watch.js" in r.text and "/assets/app.js" not in r.text
|
||||
assert f'content="{name}"' in r.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["/file/no-such-token", "/folder/no-such-token", "/file/a/b"])
|
||||
def test_a_new_path_without_a_live_link_still_gets_the_player(pages, client, path):
|
||||
r = client.get(path)
|
||||
assert r.status_code == 200
|
||||
assert "/assets/watch.js" in r.text and "/assets/app.js" not in r.text
|
||||
|
||||
|
||||
def test_a_card_names_a_file_as_a_file(shared, db):
|
||||
made = shared("backup.tar.gz", None)
|
||||
tags = og._watch_tags(made["token"], db)
|
||||
assert f'{made["url"]}"' in tags
|
||||
assert "video.other" not in tags
|
||||
|
||||
locked = shared("notes.tar.gz", None, password="pw")
|
||||
hidden = og._watch_tags(locked["token"], db)
|
||||
assert "Password-protected file" in hidden and "notes" not in hidden
|
||||
assert "video.other" not in hidden
|
||||
|
||||
|
||||
def test_a_card_of_a_video_stays_a_video(shared, db):
|
||||
made = shared("clip.mp4", _VIDEO)
|
||||
tags = og._watch_tags(made["token"], db)
|
||||
assert f"/watch/{made['token']}" in tags and "video.other" in tags
|
||||
locked = shared("other.mp4", _VIDEO, password="pw")
|
||||
assert "Password-protected video" in og._watch_tags(locked["token"], db)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("name", "data", "video"),
|
||||
[("clip.mp4", _VIDEO, True), ("song.m4a", _AUDIO, False), ("backup.tar.gz", None, False)],
|
||||
)
|
||||
def test_a_password_link_says_whether_it_opens_a_video(shared, client, name, data, video):
|
||||
"""The lock screen asks to watch a video and to open anything else, whichever path it is on."""
|
||||
token = shared(name, data, password="pw")["token"]
|
||||
meta = client.get(f"/api/public/watch/{token}").json()
|
||||
assert meta == {"needs_password": True, "kind": "file", "video": video}
|
||||
+174
-138
@@ -301,7 +301,8 @@ Also in force:
|
||||
`fade-below` utility (`fade-below-panel` / `fade-above-panel` on a panel); the page band and a
|
||||
scrolling panel under its header fade by the scroller's own edge mask (`useScrollFade`), because what
|
||||
they sit on is the backdrop, not a colour. The chip rows fold their overflow into "+N" rather than
|
||||
scroll, so no row has clipped ends; the carousels fade theirs. The dialog edges come with C4's pinned
|
||||
scroll, so no row has clipped ends, and a filter row puts its picked chips first so the fold never
|
||||
holds the only sign that a filter is on; the carousels fade theirs. The dialog edges come with C4's pinned
|
||||
footer (S3f).
|
||||
- **Viewport height:** `dvh`, never `vh` / `h-screen`: `100vh` is the viewport with a mobile browser's
|
||||
toolbar retracted, so an `h-screen` shell runs its last rows under the toolbar (contract-tested).
|
||||
@@ -536,6 +537,26 @@ of a full-width panel and nothing on the right.
|
||||
shows them as four buttons with the item's place beside the selected view; a side panel in edit mode
|
||||
gives each group an Up / Down pair (`ui/OrderButtons`, `compact`). A move that would go nowhere is
|
||||
shown off, not hidden. A grip also picks up from the keyboard (space, the arrows, space).
|
||||
- **Selecting rows:** a list whose rows take bulk actions shows a box first in every row, always, and one
|
||||
over the column for the rows shown. Shift+click selects a range, `x` toggles the row under the keyboard,
|
||||
Esc clears. A selected row wears the accent tint as well as its tick. An action covers the selected rows
|
||||
shown; a row a filter hides stays selected and comes back ticked; another list starts over. The row's own
|
||||
menu still acts on that row alone. While anything is selected the toolbar's second row is the action band:
|
||||
the count (and how many a filter hides), the last move's target as one click, Move to, Remove, Clear
|
||||
selection. An action clears the selection, undoes by its toast and, when it fails, ticks its rows again.
|
||||
An Undo brings back what is still there to bring: a video the move put in the target and the target no
|
||||
longer holds stays where it went, and a warning says how many came back. One the target held already only
|
||||
left the source, so it returns there.
|
||||
Delete takes the selection when there is one, else the row under the keyboard, with no confirm. With every
|
||||
tick hidden by a filter it removes nothing and says so. An Esc during a drag puts the drag down, and only that.
|
||||
Below `xl` the band's buttons are glyphs named in their tooltips, and a filter's hidden count is "+N" with
|
||||
its sentence in the tooltip. The row the band replaces keeps its height, invisible, so a tick moves no row.
|
||||
On a phone the count is its number (the words read out, and in the tooltip) and the undo pair stays out.
|
||||
A row's grip also carries it onto a list in the rail, under a sort or a filter too (the grip then says
|
||||
so, and no key lifts it); a selected row carries every selected one, named on the drag image below the
|
||||
pointer. The target row lights up (`ring-accent`); the open list is none; an unpinned rail peeks by the
|
||||
drag's own hover and scrolls at its edges. Dropped inside the list, one row takes its new place and many
|
||||
stay. A key never leaves the list and moves its own row: the band and the row's menu are the other way.
|
||||
- **Motion:** 150–300ms micro-interactions, transform/opacity only; `prefers-reduced-motion` is respected.
|
||||
[WCAG 2.3.3]
|
||||
|
||||
@@ -697,140 +718,155 @@ of a full-width panel and nothing on the right.
|
||||
|
||||
## Decision log
|
||||
|
||||
| Date | Decision | Chosen | Over | Why |
|
||||
| ---------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 2026-09-24 | Floating button | Back to top: a round 48 glass FAB; "round" = floats over something (media or the page) | A Material 3 rounded square; a labelled pill; the old 64 circle | The common web convention for back to top; round tells it apart from every toolbar button; 64 was oversized |
|
||||
| 2026-09-24 | Device contract | Tablet portrait + landscape and up; phones out | A 1024px floor with a "too small" message | Portrait tablet use is real, and the app already renders at 820 portrait |
|
||||
| 2026-09-24 | Card actions on touch | Fewer visible, the rest in a "…" menu | 44px buttons that no longer fit the card | Six 44px targets need more width than a card has |
|
||||
| 2026-09-24 | Action placement | One menu with several triggers, never gesture-only, a desktop background menu that mirrors the toolbar | Visible buttons for everything | Fewer non-critical buttons on screen, without hiding any function |
|
||||
| 2026-09-24 | Text selection | Text stays selectable; a click that ends a selection does nothing | Click-to-play on titles | The user must be able to copy any text the app shows |
|
||||
| 2026-09-24 | A1 Button shape | r8 + a rung per context; glass is a Button variant | r12; a pill | Nested corners (r8 in r12 in r16); the pill already means "a filter or a choice" |
|
||||
| 2026-09-24 | A2 Icon buttons | Two sizes, r8; a round button only on media | One size; all round | A lone toolbar icon at the row size looks lost; round rows read as tags |
|
||||
| 2026-09-24 | A3 Touch size | 44 for every control primitive | 36 + gaps; Button only | One rule (HIG 44) instead of two sizes nobody remembers |
|
||||
| 2026-09-24 | A4 Input | Bordered, a 55% fg-into-bg edge (≥ 3:1) | Filled; today's look as a primitive | The only option that clears WCAG 1.4.11 without a heavy fill on glass |
|
||||
| 2026-09-24 | A5 Dropdown trigger | Pill in a toolbar, r8 in a form | Pill everywhere; r8 everywhere | Matches the neighbours in each context |
|
||||
| 2026-09-24 | A6 Checkbox, switch, slider | Native, accent-tinted, the row is the target | Drawn primitives | Free keyboard / screen-reader / forced-colours support; only 3 sites |
|
||||
| 2026-09-24 | B1 Density | Compact 32 / 28 / 24 by explicit height | Standard 38 / 32 / 26 | The owner's read of the lab; touch is covered separately (A3), and one toolbar row lines up at 28 |
|
||||
| 2026-09-24 | B2 Scheme set | Midnight, Forest→cyan, Slate→fuchsia, Matrix→lime | Today's six | The accent collided with danger (YouTube), warn (Slate) and success (Forest, Matrix); Midnight and Starship were one scheme twice; 4 of 6 light accents failed 4.5:1 |
|
||||
| 2026-09-24 | B3 State layers | Text colour at 10% / 16% over anything | Material's 8 / 12%; today's opacity + bg-card | Visible in every scheme and mode (≥ 1.2:1); today's row hover was 1.00:1 on a card |
|
||||
| 2026-09-24 | B4 Page chrome | One sticky band + fade; filters fold when short | A floating glass bar; everything scrolls | Tabs and filters always in reach, in one place; a keyboard-up tablet keeps its content |
|
||||
| 2026-09-24 | B5 Surfaces | One class + radius per role | Today's per-site mix | Nested corners and no per-site alpha drift |
|
||||
| 2026-09-24 | B6 /watch | The app's surfaces, native video controls | Flat and minimal | The page strangers see should look like the product; native controls work on any device |
|
||||
| 2026-09-24 | B7 Nav rail | Soft tint + edge bar, optional labels (a user setting), slim | Solid accent (recommended); a Material rail | The owner's combination: calmer than a solid fill, labels for who wants them, no width cost |
|
||||
| 2026-09-24 | B8 Loading | Skeleton by shape, spinner in a control | A spinner everywhere | Nothing jumps when data lands; a long wait doesn't look stuck |
|
||||
| 2026-09-24 | B9 Fade | Toolbars / headers, panel tabs, dialog edges, chip rows | Thumbnails; buttons | The north-star depth where content scrolls under chrome; not on content or small controls |
|
||||
| 2026-09-24 | C1 Action classification | The table (lab C1): state + primary at rest, everyday toggles on hover, "…" on touch, destructive into the menu | Visible buttons per site, as today | One action list per object, nothing gesture-only, fewer buttons without losing a function |
|
||||
| 2026-09-24 | C2 Side panels | A tap opens an overlay drawer; pin is a separate button ≥ 1024 | A tap pins and the content reflows | Below 768 the filters were unreachable; on touch a tap pinned and pushed the grid |
|
||||
| 2026-09-24 | C3 Players on touch | Tap = show the controls; 44px seek hit area; 44 buttons; the YT description behind ⓘ | Today (tap also pauses; 7.5px seek bar) | Measured live: you couldn't reach the seek bar without pausing, and the hover-only description never opened on a tap |
|
||||
| 2026-09-24 | C4 Dialogs | Focus by purpose; a pinned footer | Focus on Close; the footer scrolls | A form starts in its first field, and Save stays on screen with the keyboard up |
|
||||
| 2026-09-24 | C5 Plex player controls | The owner's lean set: no Stop / Restart / ±10 s buttons, Back by position, Next only with a next item, Resume + From the start on the card, touch double-tap ±10 s | Every control in one row (it ran off-screen below 1024); Back by a press counter; ±10 s keyboard-only | The row fits a portrait tablet; the decision to restart is made on the card; a tablet keeps the 10 s skip |
|
||||
| 2026-09-24 | Glass tuner | Retired; the schemes are the only colour choice | Keep it with ranges clamped to the rules | Free tuning is the drift the constitution exists to stop (owner) |
|
||||
| 2026-09-24 | Matrix toned down | Moss #86a05a at Midnight's lightness, near-neutral greys; every white-on-accent part → `--accent-fg` | The B2 lime #a3e635 | The owner found the lime neon and tiring; it was the loudest accent (L 0.85, C 0.21), and fixed white parts sat on it at 1.5:1 |
|
||||
| 2026-09-24 | Field primitives | `Input` / `Textarea` / `InnerInput` + `fieldClass`, `SelectTrigger`, the native controls; the lint rule "no raw `<input>`" | `inputCls` and ~40 hand-styled boxes | Six edges, four radii and two focus looks for one control; the ≥ 3:1 edge held nowhere |
|
||||
| 2026-09-25 | Surface roles | `SURFACE` roles in `ui/surfaces.ts`; the lint rule "no bare glass class"; menus p-1 with r8 rows | Three tiers paired ad hoc with five radii and three menu paddings | ~140 sites drifted; nested corners only hold if the radius comes with the role |
|
||||
| 2026-09-25 | Static labels | Flat tonal `Badge`, no edge; a filtering tag is an edged chip | A glass pill with an edge, like the chips | Edged = pressable at a glance; a static tag that looks like a chip gets clicked and does nothing |
|
||||
| 2026-09-25 | Header search | A 40 glass pill with the field edge (`lg`); what sits inside it is round | 44, r16, a glass box with a faint edge | The one rounded box among pills, and its edge under 3:1; the hero search is the YouTube/Gmail pill |
|
||||
| 2026-09-25 | Switch row (F12) | The whole settings row toggles (`SwitchRow`; a hand-laid row points a label at the switch) | Only the 36×24 switch toggles | The iOS / Material settings row; the text was a dead click beside the control it names |
|
||||
| 2026-09-25 | Edges and hovers (F14) | The ≥ 3:1 edge on the field family (fields, the form trigger); labelled pills keep the faint edge and the accent-edge hover | The ≥ 3:1 edge and a state-layer hover on every control | 1.4.11 asks an edge only where nothing else identifies the control; a heavy edge on every chip and tab weighs the whole UI down |
|
||||
| 2026-09-25 | Rating and live (F16) | Own tokens: `--rating` (theme-scoped gold), `--live`/`--live-fg`, `--rating-media`, `--media-chrome`; palette classes lint-refused | Map them to `--warn` / `--danger` | A gold star and a red LIVE are what the eye expects; as warn/danger they would read as a status. The old amber score was 2:1 on light |
|
||||
| 2026-09-25 | Fjord trial (B2 exception) | A fifth scheme, temporary: Midnight's neutrals, Playnite's steel accent (#337599 lifted to #5aa1cb) and steel rules; exit = fold into Midnight or remove | Retune Midnight straight away; borrow only the qualities | The owner wants to live with the calmer palette app-wide before it replaces the default; it breaks "own hue family" on purpose, and only until that call |
|
||||
| 2026-09-25 | Whole-card row (owner) | A card row's B3 layer is the card's `::before` under its content; the open button's hit layer spans the card, the actions sit above it | The name button's own hover, ending at the first badge or button | A row that half-answers the pointer reads as broken; a badge click did nothing |
|
||||
| 2026-09-25 | Badge tones (F29) | `Badge tone` neutral / accent / warn at 6%; light `--warn` #b45309 → #a14a07; edged label spans lint-refused | Keep edged status pills (a private Badge in Users, Settings "Granted", the suggestions count) | Edged = pressable at a glance; amber-700 was 4.58:1 as text and fell under 4.5 on its own tint |
|
||||
| 2026-09-26 | Page band built (B4) | Controls only in the band (intros scroll); the fold shows the same row in place; one `h1` per page (`PageHeading` steps the hidden one aside); `SectionLabel` headings; Skip to content | A popover of the folded filters; the page title kept visible | A folded row is still the same controls, nothing duplicated; the rail and the tab title already name the page |
|
||||
| 2026-09-26 | Fade built (B9) | `fade-below` on sticky toolbars and table headers; the scroller mask where the band sits on the backdrop | A painted band over the backdrop | The backdrop is the colour under the band, so fading the content into it is the same edge |
|
||||
| 2026-09-26 | Viewport units | `dvh` everywhere (the Plex player stage with S3f) | `vh` / `h-screen` | `100vh` hides the last rows under a tablet browser's toolbar |
|
||||
| 2026-09-26 | Video actions built (C1) | One list per video (menu, right-click, long-press, "…"); the card keeps watched / save / add to playlist on its picture on hover; download, details, copy, hide, reset in the menu | The six-button row under the card and the hover ⓘ | The menu is the one door every device has; the card loses a line of height and the touch card its row of 28px buttons |
|
||||
| 2026-09-26 | Plex actions built (C1) | One list per Plex title (play/open, watched, add to playlist, media info, copy title, pin); the poster keeps watched / add / "…" on its picture on hover; seasons get open / watched / add / copy | The hover ⓘ, the pin-only menu, an episode's add button at rest, a collection's "Remove" X on the card | The same door as a video's; the collection grid goes to two columns on a phone so the touch "…" leaves the title its line |
|
||||
| 2026-09-26 | Playlist actions built (C1) | A playlist row's "…" (play, pin, copy title / link, move, order, remove), Delete + an undo toast; one list per playlist (rename, pin, YouTube open / push / revert, delete) from its rail row and its header's "…" | The row's X column and its confirm; the header's pencil, YouTube link, push, revert and trash buttons | Remove is reversible, so it needs no confirm; the header keeps Play all; a narrow table drops "#" and Channel so the title keeps a width |
|
||||
| 2026-09-26 | Channel + Plex list actions (C1) | A channel row's "…" (open, pin, YouTube, copy, full history, hide + undo, unsubscribe); a Plex playlist's title / show / season "…", Delete + undo; its header's "…" (rename, delete); an action toast lasts ≥ 8 s | The channel row's full-history, hide and unsubscribe buttons; the Plex list's red X on every row, show and season; the header's pencil and trash | Hiding and removing are reversible, so they need no confirm and the undo needs time; unsubscribe and deleting a playlist keep theirs |
|
||||
| 2026-09-26 | Download / notification / Scheduler actions (C1) | A download row's "…" (play, share, save, edit, details, re-download, manage sharing, copies, cancel / delete / remove); a library row's Share stays in sight, ahead of save; a notification row's "…" and hover dismiss; the inbox band's and the Scheduler strip's "…" | The download row's five rare buttons and its cancel / delete / remove; the source link's copy button; an activity notice's Find / Undo links; the band's Clear everything; the strip's Purge discovery | The destructive rows keep their confirm, and Clear everything gains one; a row link keeps the browser's own menu; Find in feed drops the tag / search / age filters that could hide its video |
|
||||
| 2026-09-26 | Channel menu: Tags + Priority (C1) | Tags A–Z as in-place checks; Priority as fixed steps 10 · 5 · 3 · 2 · 1 · 0, the current one ticked; a pick re-sorts at once and the page + focus follow the row; one drawn `MenuCheck` for every checkable row that cannot be an `<input>` | Relative steps (+1 / +5); straight to the top; the stepper only; seven hand-drawn check marks (three box sizes, a tinted box, a × for "on", a trailing tick) | Bubbling a channel up is one pick; fixed levels keep the scale the reader already uses; the list moving where the reader can see it is the feedback |
|
||||
| 2026-09-26 | Reorder without a drag (WCAG 2.5.7) | Row menus: Top / Up / Down / Bottom (YouTube + Plex playlists); saved views: four buttons with the place beside the selected view (owner: A); side panels in edit mode: an Up / Down pair per group (owner: A), the name wrapping there | A "…" on every saved-view row; a "…" on every panel group; drag only | A visible, one-click path where the list is edited; the edge moves shown off so the buttons never shift |
|
||||
| 2026-09-26 | Titles in click surfaces | The surface stays a button, flagged `selectable`: its text selects, and the click that ends a selection does nothing; every plain `Pressable` pinned with its reason | Rebuilding each card and row so the title sits outside the button; exceptions for master-detail lists | Chrome selects inside a button once it is `user-select: text` (measured), so one flag on the primitive keeps the keyboard, focus and list walking every surface already has |
|
||||
| 2026-09-26 | Right-click on a selection | The browser's own menu opens on selected words; beside them the object's menu | A "Copy selection" row in the app menu | The reader selected the words to do something with them; the native menu copies, searches and translates, and changes nothing else |
|
||||
| 2026-09-26 | Keyboard ring on a flush row | Inside the row (a table row by its tag, a log line, a show header in its clipping card, with the card's corners) | The ring outside, as on a card | Outside it ran under the table head and past the table, and a clipping card cut it away entirely (invisible focus) |
|
||||
| 2026-09-26 | Fade at rest | The sticky header's fade appears with the first 1rem of scroll (a scroll-driven animation; no fade where unsupported) | A fade that is always drawn | At rest it dimmed the first row and hid its ring's top edge; nothing is under the header yet |
|
||||
| 2026-09-26 | Narrow playlist table | "#" and Channel hide by the table's own width (under 42rem), not the window's | Hiding below the `sm` window width | Beside the playlist rail a desktop window left the table 432 px and the title 0 px |
|
||||
| 2026-09-26 | Background menu built | Five list pages (feed, Plex grid, channels, playlist, notifications); the toolbar's sort / view / filters and the band's actions; no destructive row | Every page with a toolbar; the "…" menus copied whole, delete included | The tab-only pages have nothing a menu would add; a blank-area right-click must not be one click from delete |
|
||||
| 2026-09-26 | Media card anatomy (C) | One frame; the meta line pinned to its bottom; the length a badge on the picture; the Plex card on the same primitive as the video card | A: the year as an overline over the title; B: the year inline after it; a fixed two-line title slot | A one-line title left a hole the eye reads as a missing line; C puts nothing under a variable-height title |
|
||||
| 2026-09-26 | One Play | `MediaPlayGlyph` (the media button variant) and only where the click plays | The Plex card's hand-painted accent circle; a playable dot on every card | One Play for every card; a dot that only a colour and a tooltip explain says nothing |
|
||||
| 2026-09-26 | Filtering values on the info page | A value that filters (year, certificate, studio, director) is an edged chip; a fact is flat text | Everything flat, the clickable ones only hover-tinted | The S3d rule: edged = pressable, so the reader sees which values do something |
|
||||
| 2026-09-26 | Shelf density | On any strip: one title line over one meta line | The grid's two lines and full meta on a strip | The tallest card set the strip's height and left holes in the cards with less to say |
|
||||
| 2026-09-26 | Compact list row (B) | The title leads; a faint "…" at the end; the toggles float over the date on hover | A leading 128px action column | That column sat empty at rest, a hole at the start of every row |
|
||||
| 2026-09-26 | Media-info layout (B) | A main column (collections first, crew, cast) beside a facts sidebar; an empty column is not drawn | Every section full width, stacked | The collection is the most used; the keywords' column left a void beside a short details box |
|
||||
| 2026-09-26 | Mixed Home shelf (A) | Plex titles as wide art beside videos | Posters, with the videos not stretched | Stretching a video card to a poster's height left an ~80px gap |
|
||||
| 2026-09-27 | Home hero | A card (hover row + Play on the picture, the whole menu, a touch "…"; owner: A); three quarters wide and centred on a wide window; one fact line; the summary at the measure | The hero's pin row alone; full width; an 18rem picture column | The one answer stands in focus, and it offers what the same card offers anywhere |
|
||||
| 2026-09-27 | Home shelf tiles | A channel / playlist tile: Play, ↗ open, "…" with Open; a show acts on its next episode, ⓘ opens it; the shelf slot 232px | The tile's pin row alone; 200px | A tile without its object's actions read as broken; at 200 the Play touched the hover row |
|
||||
| 2026-09-27 | Synopsis preview (C) | A ~0.9 s mouse rest opens a passive panel beside the card | The synopsis as the picture's `title` tooltip; an ⓘ to hover; none | One long tooltip line fired anywhere on the art and clashed with the cut title's own tooltip |
|
||||
| 2026-09-27 | Reading measure | Prose capped at ~65 characters a line (`measure`) | The container's full width | At 110–130 characters a line the eye loses the next line's start |
|
||||
| 2026-09-24 | Chip family | One `Chip` (filter / token / tag / suggest / ghost) + `DismissibleChip`; nothing under 24; the lint rule "no raw `<button>` outside ui/" | Five chip geometries in five files | The applied-filter row, the tag cells, the year picker and the saved-view editor each drew their own chip; a one-letter tag was 21px wide |
|
||||
| 2026-09-24 | Button families | `Button` / `IconButton` / `Pressable` / chips / `DragHandle`; `lg` 40 for a hero CTA; pills and a 48 Play on media (from C5) | Every button hand-painted | 268 hand-rolled buttons in 79 files drifted into as many looks; the ladder only holds if every button stands on it |
|
||||
| 2026-09-27 | C4 as built | `initialFocus` required on every `Modal`; the commit row in `ModalFooter`, portalled under the body from any depth; the fades driven by the body's scroll timeline; `interactive-widget=resizes-content` | An optional prop defaulting to the ✕; a `footer` prop (the issue composer's buttons live three components down); always-on fades | A default is how 21 dialogs came to open on the ✕; lifting the composer's state to reach a prop is the larger change; a resting fade dimmed the first line |
|
||||
| 2026-09-27 | C3 + C5 as built | A tap toggles the bar through `pointerType` from `pointerdown`; a double-tap takes back its first tap's toggle; the card's pair is the video card's `MediaResumeButtons` (Continue / Restart), a sibling over the picture; the YT description is an ⓘ click popover | A delayed single tap (wait out the double-tap window); new "Resume / From the start" words for Plex; the pair inside the picture's button | A delayed tap feels dead; one media card says one pair of words; a button inside a button is invalid and the hover row already sits beside the picture |
|
||||
| 2026-09-27 | C2 as built | The side panel's drawer is `ui/Modal` `drawer-start`; drawer = a coarse pointer or below 768; the pin offered in its header ≥ 1024 | A drawer of its own inside `SidePanel` | Esc, Back, the scrim, the trap and the scroll lock are the dialog's; a second implementation is how two shells drift |
|
||||
| 2026-09-30 | Composition and the reader (E30 S6) | A chapter and a Conformance step: the space is used, one focal point, worst real data, where am I, a click answers at once, zoom and text size first-class; the person page as two columns (facts and bio left, "Known for" right) | Rules for pieces only; the bio in a full-width panel; a narrower panel | The person page passed every piece rule with half its panel empty; the owner reads zoomed in, so zoom is a requirement, not a nicety |
|
||||
| 2026-09-30 | Hungarian words (E30 S5) | The D3 list: Feed, Shorts, Admin, Token, Port stay; stream, Prio, Job, Audit, Demo, Auto, Info, Frontend/Backend, Backfill, transcode get the Hungarian word; one name per thing (kérelem, behúzás, one "Test connection") | Keep every loanword; translate Feed/Shorts too | The owner chose the list (D3); the final sweep found the same feature under two names in three places |
|
||||
| 2026-09-29 | Numbers and order in the UI language (E30 S3) | Every number through `lib/format.ts` in the UI language (decimal mark, grouping, compact, units); A→Z by the shown name in the UI language's alphabet, client and server alike; the language comes off `useTranslation`, never the singleton | `toFixed`, hand-built "1.2K", `localeCompare` in the browser's locale, byte-order server sorts | A Hungarian reader saw "8.3", "1.2K", "Életrajzi" after "Z"; the singleton read also left values in the old language after a switch (React Compiler) |
|
||||
| 2026-09-27 | Narrow rows by container | The download row, the playlist table and the Channels tag row stack by a container query; a fact line never wraps | Breakpoints on the window | The iPad zoomed in, split screen and a column beside a rail are narrow while the window is not; the zoomed download row broke "18.9 / MB" apart |
|
||||
| 2026-09-27 | Phones deferred | A phone-only layout (the hamburger nav, a folded feed band) waits for its own epic; E28 stays desktop + tablet | Fix the phone views inside E28 | Principle 2; the first phone attempts made the feed worse, and the epic's review grows with every sprint |
|
||||
| 2026-09-27 | Conformance check (S3g) | A four-step check before a UI change is done: primitive at a named rung, the chapter re-read, the rendered page measured by kind and look, every state seen | A reviewer's eye per sprint | The S1 probe found 69 button looks; after S3 every control kind is drawn by its primitive, and the check keeps a new look from arriving unnoticed |
|
||||
| 2026-09-27 | Segmented rung | `SegmentedToggle` defaults to the toolbar rung (28, `text-xs`); 24 only for a panel's captioned match toggle | The small default | Two toolbars had inherited 10px type from the default beside 28px buttons |
|
||||
| 2026-09-27 | Copy rule (S3g) | One name per feature (the rail may shorten it); four verbs for four meanings; sentence case with the app's places capitalised; "…" when a command asks first; one-sentence messages without a stop; curly quotes; dates relative in lists with the exact minute on hover, three absolute forms; units from Intl, short | Word-for-word names everywhere; the verbs as they were; all lower case; no "…"; always a stop; always absolute dates; long or compact units | The copy survey found 7 EN and 6 HU double names, 22 Delete against 27 Remove, five date shapes and three spellings of a minute; the owner picked every recommended option |
|
||||
| 2026-09-27 | One glyph, one meaning (S4) | Play only for playback or resuming a paused transfer; Retry = `RefreshCw`; reset / revert = `RotateCcw` | Retry drawn with Play | The first UI-review run (Downloads) found a failed row whose Retry showed ▷ in the row and its menu |
|
||||
| 2026-09-27 | Fjord kept | Fjord stays a fifth scheme beside Midnight; the trial wording goes | Fold it into Midnight; remove it | The owner lived with it and likes it; the vivid Midnight stays for those who want it. B2's own-hue rule still binds any new scheme |
|
||||
| 2026-09-27 | Tablet columns | A table hides `tabletHidden` columns below 64rem of its own width; Channels drops Prio, About, Length | Hide About only; give the name a bigger share | At 1024 the channel name had 60 px; the owner chose to drop all three there |
|
||||
| 2026-09-27 | Glyph pager | First / previous / next / last as glyph buttons round the page box, names as tooltips | Words beside the arrows (hidden only on a phone) | The owner's call: the words widened the row; four arrows are the shared convention |
|
||||
| 2026-09-27 | Match switch on the panel | `ui/MatchToggle` above the picker from two picks, everywhere; one wording (Any / All) | The picker's popover footer (Feed, Plex collection) | A closed picker hid an active "all"; six pickers had drawn it two ways |
|
||||
| 2026-09-27 | Missing picture, bare link | A glyph of the kind for no picture; a download with no name is titled by its short link, once | An empty box; the URL as title, channel and link | The owner's picks 4A and 3A: an empty box read as loading, the URL showed three times |
|
||||
| 2026-09-27 | Copy on a selection | Right-click on selected words keeps the browser's menu; no app Copy row | An app menu with Copy first | A real browser's menu has copy, search and translate; only the desktop pane's is thin |
|
||||
| 2026-10-01 | Zoom target 125–133% | Screens are held at 125% and 133% browser zoom (1536 × 729, 1444 × 685 on a 1080p window) and the largest text size | 200% browser zoom | The owner: 200% was a guess; 125–133% is what they read Siftlode and most sites at, so 200% would be an upper bound nobody uses |
|
||||
| 2026-10-01 | E31 Nav rail at short heights | One "Admin" rail item opening a panel of the admin pages | A denser rail when short; a visible "+4" hint | The rail fits at 133–150% without a hidden scroll; the admin pages are rare and admin-only |
|
||||
| 2026-10-01 | E31 Configuration sections | A vertical, grouped section list, as Settings has | Group tabs + sub-tabs; one long page with a contents list | Sixteen tabs wrapped to three rows at 133%; one pattern for both settings pages |
|
||||
| 2026-10-01 | E31 Statistics overview | Number tiles, and the per-operation counts as horizontal bars | Three narrow cards; a 30-day chart | The label sits by its value; what spends the quota is seen at a glance |
|
||||
| 2026-10-01 | E31 Channel page header | The full banner, folding to one row once the grid scrolls | Always compact; no banner | The header is fixed and took 40% of a 685px window; the channel keeps its face at first sight |
|
||||
| 2026-10-01 | E31 Channel page watch state | A fresh channel page shows the unwatched videos; a picked state is remembered | Show all, forgotten on reload | The owner: open a channel to see what is new; a choice made there should stick |
|
||||
| 2026-10-01 | E31 Audit log runs | A job's successful runs fold into one row that opens, whatever ran between; only that job's failure (never folded, danger colour) breaks it | A filter defaulting to admin actions; both | Nothing hidden, the noise collapsed, the failure seen |
|
||||
| 2026-10-01 | E31 Users row | Role and state as badges, the actions in the row's one menu | An inline role toggle; icon-only buttons | Action placement: the row shows state, rare and destructive actions live in the menu |
|
||||
| 2026-10-01 | E31 YouTube player | Video beside an info panel at 1280px and wider (the video as large as the height allows); stacked below | Today's stack with a one-line bar; full-window like Plex | The owner's eyesight: about 1460px of video on 1080p instead of 1008, the actions still visible |
|
||||
| 2026-10-01 | E31 Plex info and show pages | A second column for the facts, keywords and crew, as the person page; a collection's hero sized to its content | Full-width text; a larger poster and fanart | The right ~40% was empty; one composition for every media page |
|
||||
| 2026-10-01 | E31 Nav rail rows are links | Each page row is a real link: a middle-click or Ctrl-click opens the page in a new tab | A button | The owner: open a page in a tab of its own, as on any site |
|
||||
| 2026-10-02 | E31 Plex detail second column (refined) | The facts over the key crew beside the text; the keywords, chips that filter like the genres, under the text; the show page gets all three too | All three in the column, as the mockup drew it | At 20 keywords and 12 crew the column ran to twice the text's height (849 vs ~400 px at 133%): a hole under the text instead of beside it |
|
||||
| 2026-10-02 | E31 Plex detail poster and crew | The movie and show poster keeps its 2:3 and grows a rung in a wide hero (w-56 at a 64rem panel); the crew shows its first 6 names and "Show N more" (a list of 8 or fewer shows whole) | Poster stretched to the row; a "More" on the keywords | The row is as tall as the crew column, so the poster drew ~175×590 and cropped; the crew, not the keywords, set the hero's height |
|
||||
| 2026-10-04 | E32 `field` focus skips a mode switch | A form opens on its first field; a control above it that is not a field (the composer's Edit / Preview) is passed over by marking the field `data-initial-focus` | The first text field everywhere | That moved the focus in the download dialog off its profile choice and in the upload dialog off its drop zone; the mark changes only the form that needs it |
|
||||
| 2026-10-04 | E35 Lint for z-levels and edged labels | Both rules stay; the two eslint selectors (`Z_RAW`, `EDGED_LABEL`) that refused them go | Keep the selectors | 0 hits since the E28 sweep that fixed the sites: a check that never fires costs a probe test and a snapshot each, and the UI review holds both rules |
|
||||
| 2026-10-06 | `player` focus | A dialog that is a player opens focused on its panel (the YouTube player's rule, now `Modal`'s too); on the media element itself, Space and the arrows stay the element's own | `close`, or the media element | On the ✕ Space closed the player; on the element the browser's own controls acted on the same key as the player's (one Space played and paused, measured in Chrome) |
|
||||
| 2026-10-08 | Captions on touch | A `Tooltip` opens for a mouse and a key's focus only, never for a finger | A caption on tap; a long-press caption | On an iPad the tap that showed the caption was taken as a hover and lost its click (every rail button took two taps), and no finger sends the mouseleave that hides it; the rail's labels setting names the buttons on touch |
|
||||
| 2026-10-08 | Header search on touch | No key cap on a touch screen; the pill grows to 52 px so a ring shows round the 44 px Go; Go drops to its icon by the column's width | Keep the key cap; a 44 px Go overhanging a 40 px pill | On a tablet the 44 px key cap and Go sat on the pill's edge and cut the placeholder; an overhanging Go breaks the nested radii |
|
||||
| 2026-10-08 | Plex subtitles and the control bar | The player draws the cues itself; while the bar shows they rise above it (200 ms), then settle back | The browser's own cues, moved by `line` | On an iPad the bar covered the text; a native cue cannot be animated or measured, and our layer behaves the same on every engine |
|
||||
| 2026-10-08 | Hover on a button over a picture | The `media` variant's hover is a 2px accent ring over a darker body (Plex + YT cards, rail arrows; option B) | An accent fill (reads as "selected"); a white wash (weak on a bright poster) | The 60 → 75% black step was invisible, and over a card a rail arrow could not be told from the card's own Play under it |
|
||||
| 2026-10-08 | Plex "Add to collection" | A movie or show card's menu row opens a panel beside the card: its library's manual collections tick in place, a name + Enter creates one with the title in it (admin; option A) | An Add submenu with a "New…" dialog; the per-title editor modal from the menu | A collection took a trip to the Collections page, a name, a title search, then a second search per title; the panel is the video card's "Add to playlist" |
|
||||
| 2026-10-08 | YouTube modal chrome | No prev/next strips beside the card; Close an icon (the panel's top right; stacked, the title row's end); the description clamped to three lines + More; the panel shuts to a 2.75rem strip of close, expand, prev/next (option D1) | Keep the strips; a "Close" text button; the full description in a scroller; a panel that hides outright | The strips cost the video 7rem of width for a second copy of the panel's buttons; a long description pushed the channel and the actions out of sight; a hidden panel left no way to step the queue without the keyboard |
|
||||
| 2026-10-08 | The wheel over the YouTube modal | Over the video: volume. Over a panel with something to scroll: scroll only, never volume, not even at its end. Over a panel with nothing to scroll: volume (owner) | Volume everywhere; a scroll that hands over to the volume at its end | Reading a long description turned the volume down once it hit the end |
|
||||
| 2026-10-09 | A Plex show card plays | Its picture plays the show's next episode everywhere (an episode with a resume point → Continue + Restart, else the first unwatched, else S1·E1), resolved on the click; the preview names it once up; title and ⓘ open the show (option A + hover ask) | The picture opens the show page (as before); every card carrying `next` | A show card on Discover had no Play while Home's had one; carrying `next` costs a grid page up to 180 queries for the few cards anyone plays |
|
||||
| 2026-10-10 | Clip mode in the players (E38) | Scissors in the control row + `C`, `[` `]`; the panel in the player with the watched video as preview; overview + zoomed strip on `ui/RangeTrack` (ends are sliders); a toast + the Ready notification after Cut | A ⋯ menu entry; permanent In / Out buttons; a big dialog with its own preview (a second Plex transcode / YouTube iframe) | Owner's picks A, P1, a; a film is hours and a clip seconds, so only a zoomed strip gives a hand the precision. The Downloads editor's cuts moved onto the same track (keyboard-steppable now) |
|
||||
| 2026-10-10 | Crop in clip mode (E38) | A Crop toggle in the clip panel: a frame over the playing picture (`ui/CropFrame`, the editor's crop too), Free / 16:9 / 9:16 / 1:1, Whole picture; maximised YouTube keeps the panel in the bar's place; the wide side panel shuts while clipping | A frame always on the picture in clip mode (K2); a free shape only | Owner's K1 + a: a crop is rare, so it never covers the picture unasked; a phone or square clip needs a held shape. The iframe hides its picture's size: drawn on the 16:9 box, the cut fits it to the real picture |
|
||||
| 2026-10-10 | Marks on the player chrome | `--media-mark` (amber) and `--media-danger` (light red), the same in both themes; `media-marks` points the focus ring (`--focus`) and the chosen mark (`--chosen`: a track's tick, a tab's underline; the label stays white) at the amber on the player and every chrome surface; `media-scope` (a form) also the errors at the red | The theme's accent ring, chosen text, warn and danger | On the chrome (#171717) a light theme's accent ring (Slate 2.84:1), warn (2.99:1) and danger (2.77:1) all fall under 3:1; the accent as chosen text under 4.5:1 |
|
||||
| 2026-10-11 | Files page (one library) | List rows by default, the media grid a toggle remembered per folder; a sidebar of automatic source folders, own folders, Shared with me and the storage meter; the paste-a-link box in the toolbar | A media grid by default | The library holds videos AND plain files: rows read both, show more per screen and scan by size and date |
|
||||
| 2026-10-11 | Library list columns | Every kind of value in its own column (name, source, phone-safe, retention, size, added, actions), one grid with a subgrid per row so they line up; an action that does not apply keeps its slot empty; a right-click menu on every row (the ⋯ opens the same menu) | Badges flowing after the title; icons that shift when one is missing | Owner: values of one kind must fall in one vertical line; a row's every action reachable by right click |
|
||||
| 2026-10-11 | Running downloads | An app-wide tray, bottom right, shown only while something runs or failed (reason + retry), foldable to a pill | A rail icon with a count and a popover | Downloading became an action you start anywhere; a running one must be visible without going to look |
|
||||
| 2026-10-11 | Download done | The notification says whether it plays on a phone and carries Link másolása + Megnyitás (the folder, the item focused); never an automatic jump | A plain "ready" notice; auto-navigation to the item | The daily path is paste → done → copy the link; a jump would pull the user out of what they were doing |
|
||||
| 2026-10-11 | Library row quick icons (owner A) | On a wide list only the ⋯ holds a place; Copy link, Share and Save come up over the date while the row is hovered or holds the keyboard; a card (phone) keeps them in its own line; Keeps narrower | Three icons always in sight (the name kept ~150px at 1200); dropping Added below 64rem | Owner: the name is what a row is read by; every action stays in the ⋯ and the right-click menu |
|
||||
| 2026-10-12 | Files preview (owner ★) | A file that is not media opens from its name in the dialog shell, wide: an image, a PDF in the browser's own viewer, text as numbered plain text (HTML and SVG too) with a wrap toggle, else a no-preview card with Save; ← / → page the list's such files in its order; an image under 8 MB is its own thumbnail | A side panel beside the list; a new browser tab; pdf.js; syntax highlighting; a click that saves a file without a preview | Owner: one way to open anything, paged like the list; the browser's PDF viewer is free and isolated; a page is never rendered on our origin |
|
||||
| 2026-10-12 | A running download's step (owner ★) | The tray row names the step beside its bar ("Downloading audio · 12%", "Merging" with a pulse); a paused-only tray shows a pause mark, never the done check | A bare bar and % | A download fetches video and audio as two streams: unnamed, the second fill reads as a restart; the tray is the only place a download is followed |
|
||||
| 2026-10-14 | API tokens (owner A/A/A) | Settings → API tokens: a row per token in three lines (name + prefix, its folders and rights, last use and expiry), revoked from its ⋯; a new token asks the kind first (Hub exchange or Custom: rights as chips per folder), expiry 1 year by default; the token shows once in the same dialog, with Copy and a curl line | A table; one form with a preset link; the token in a banner above the list | A table truncates the rights at this width; the common token never shows a matrix to get wrong; closing the dialog is plainly when the token is gone |
|
||||
| 2026-10-15 | Folder links (owner A/A/A) | An own folder's menu has Copy link and Share with link… as a file row does (the dialog is the link half of the file's); the link opens a list of the folder's files as it is now, Play opening the watch player above it with the playing row lit, a document only downloading; the rail marks a folder with a live link beside its count | Share with link… alone; cards; a download-only list; no mark | Mostly videos from a phone, read on a phone: a list gives a long name its line and the next one is a tap away; the folder link is the one place where moving a file in publishes it, so where it is must show |
|
||||
| 2026-10-17 | Copy-only changes (owner ★) | Step 4 of the Conformance check alone (not 1–3 or 5): every state the changed text renders in, seen in both languages | The whole five-step check; no screenshot at all (DOM test + key parity) | Steps 1–3 and 5 judge controls, patterns and composition, which a text change does not touch; the one risk left is a longer Hungarian string wrapping or clipping, and only a screenshot shows that |
|
||||
| 2026-10-17 | Text on glass (owner ★) | Light `--muted` 15% toward `--fg` in every scheme (≥ 6:1 on the bare page); the item count, the badges and the current Files row on opaque tints mixed into the surface | Only the two failing components; the item count's number in `--fg` | Pixel-measured over every scheme × mode × backdrop, the count fell to 3.8:1 (dark too: thumbnails scroll under the toolbar's glass) and Channels' tabs to 4.1:1; an `--fg` count outshouts the filters beside it |
|
||||
| 2026-10-18 | Scheduler run history (owner D4, E1, E2 ★) | A row's last three runs as dots, newest first (interrupted: a hollow warn ring, set apart from skipped and failed), and a history button that opens the job's runs on the Activity page; a user's ad-hoc runs in their own block under the jobs, with no interval and no run button | An inline expandable history per row; a dark-grey interrupted dot; ad-hoc runs only on the Activity page | Three dots answer "did it run, did it work" at a glance; the whole history needs filters, which the Activity page has |
|
||||
| 2026-10-18 | Activity page (owner D1, D2, G1–G3 ★) | One page, "Napló" / "Activity": four tabs (Runs, Admin actions, Server log, Quota) under one filter bar (text, a period of 1 h · 24 h · 7 d · 30 d · 90 d defaulting to 7 days, an account), the view in the URL; runs and admin actions as dense rows that open in place as a log line does, filtered and paged on the server; a run's or a request's log lines one pivot away, as a history entry | One merged timeline; a page per source; a default period per tab; card rows; the audit log's client-side table | Each source keeps its own table and retention, read in one place; one bar keeps what you narrowed across tabs; about 1.8k runs a day need a log's density and a server-side filter |
|
||||
| 2026-10-24 | Related videos (owner U1–U3 ★, D1 A, D3) | On demand: a tab beside the description (wide), a drawer (stacked); the narrow thumbnailed row, its menu alone, a followed check; plays in place and the list stays the opened video's; an on-topic / Hungarian-trending switch kept on the account | Always shown; the end-of-video grid alone; a dialog; a big card or a text row; a list that follows the playing video | The modal is full on a small screen; a picture is what a choice among strangers rests on; a list that stays put is tried one by one, and spends no more of the day's cap |
|
||||
| 2026-10-25 | Related: one played; off (owner D1 a, D2 a) | Played from the list, it is the player's item: its title, controls and progress, marked watched at its end, the queue left where it was; a daily limit of 0 takes the tab and the button away | A linked video's in-place play (no controls, nothing kept); a tab that only shows a refusal | What is watched should count as watched, wherever it was started from; a control that can only be refused is not offered |
|
||||
| 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 |
|
||||
| 2026-11-01 | Docked bar glyphs (owner D8 a) | The maximised view's docked bar is glyph-only too (tooltips carry the names and keys): transport, auto-advance, loop, Mark watched (✓ / ✓✓); its controls scroll on a narrow window while Fullscreen and Exit stay pinned at its right end | Labels from `xl` up | On a tablet the labelled bar ran past the right edge and took Exit with it; the side panel had already lost its labels |
|
||||
| 2026-11-01 | Toolbar group glyphs (owner D9 a, D10 a, D11 a) | The feed's, channel page's and Plex Browse's filter pills name their group by a glyph (`Eye` watch state, `Shapes` content types, `ArrowDownUp` sort), the word in the tooltip and the accessible name; Sort + View end the toolbar's row, the chip row shows only with a chip; a channel page has no count pill | The value alone; Sort + View on a row of their own | "Watch state:" and "Sort:" cost a tablet row its room; the value says enough once the glyph names the group; the channel header already counts the videos |
|
||||
| 2026-11-01 | Channel header on a tablet (owner E2) | Below `xl` the action row drops its two words: "Prio" (the stepper's tooltip names it) and "Subscribed" (a ✓ glyph; its name in the aria-label, Unsubscribe in the tooltip); the tags keep the row's rest, folding into "+N" | The tag lane on a full line of its own below ~12rem; the tags under the channel name | On an iPad (820 px, 44 px targets) the lane got 29 px, a sliver; now 130 px, and every tag shows at 1180 |
|
||||
| 2026-11-01 | Clear watch progress (owner E a) | A video menu's Reset reads "Clear watch progress" in English (HU "Megtekintés visszaállítása" stays); "Reset view" is only a page's view reset (sort, filters, grouping) | "Reset view" for both; the playlist page's view reset renamed instead | On a playlist page the two stood one right-click apart under one name, and one of them erases the video's progress with no undo |
|
||||
| 2026-11-01 | Clear watch progress clears only that (owner A) | The row shows only on a video with a resume point and clears that alone: a hidden video stays hidden, a watched one watched. Un-hiding and un-watching have rows of their own |
|
||||
| Date | Decision | Chosen | Over | Why |
|
||||
| ---------- | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 2026-09-24 | Floating button | Back to top: a round 48 glass FAB; "round" = floats over something (media or the page) | A Material 3 rounded square; a labelled pill; the old 64 circle | The common web convention for back to top; round tells it apart from every toolbar button; 64 was oversized |
|
||||
| 2026-09-24 | Device contract | Tablet portrait + landscape and up; phones out | A 1024px floor with a "too small" message | Portrait tablet use is real, and the app already renders at 820 portrait |
|
||||
| 2026-09-24 | Card actions on touch | Fewer visible, the rest in a "…" menu | 44px buttons that no longer fit the card | Six 44px targets need more width than a card has |
|
||||
| 2026-09-24 | Action placement | One menu with several triggers, never gesture-only, a desktop background menu that mirrors the toolbar | Visible buttons for everything | Fewer non-critical buttons on screen, without hiding any function |
|
||||
| 2026-09-24 | Text selection | Text stays selectable; a click that ends a selection does nothing | Click-to-play on titles | The user must be able to copy any text the app shows |
|
||||
| 2026-09-24 | A1 Button shape | r8 + a rung per context; glass is a Button variant | r12; a pill | Nested corners (r8 in r12 in r16); the pill already means "a filter or a choice" |
|
||||
| 2026-09-24 | A2 Icon buttons | Two sizes, r8; a round button only on media | One size; all round | A lone toolbar icon at the row size looks lost; round rows read as tags |
|
||||
| 2026-09-24 | A3 Touch size | 44 for every control primitive | 36 + gaps; Button only | One rule (HIG 44) instead of two sizes nobody remembers |
|
||||
| 2026-09-24 | A4 Input | Bordered, a 55% fg-into-bg edge (≥ 3:1) | Filled; today's look as a primitive | The only option that clears WCAG 1.4.11 without a heavy fill on glass |
|
||||
| 2026-09-24 | A5 Dropdown trigger | Pill in a toolbar, r8 in a form | Pill everywhere; r8 everywhere | Matches the neighbours in each context |
|
||||
| 2026-09-24 | A6 Checkbox, switch, slider | Native, accent-tinted, the row is the target | Drawn primitives | Free keyboard / screen-reader / forced-colours support; only 3 sites |
|
||||
| 2026-09-24 | B1 Density | Compact 32 / 28 / 24 by explicit height | Standard 38 / 32 / 26 | The owner's read of the lab; touch is covered separately (A3), and one toolbar row lines up at 28 |
|
||||
| 2026-09-24 | B2 Scheme set | Midnight, Forest→cyan, Slate→fuchsia, Matrix→lime | Today's six | The accent collided with danger (YouTube), warn (Slate) and success (Forest, Matrix); Midnight and Starship were one scheme twice; 4 of 6 light accents failed 4.5:1 |
|
||||
| 2026-09-24 | B3 State layers | Text colour at 10% / 16% over anything | Material's 8 / 12%; today's opacity + bg-card | Visible in every scheme and mode (≥ 1.2:1); today's row hover was 1.00:1 on a card |
|
||||
| 2026-09-24 | B4 Page chrome | One sticky band + fade; filters fold when short | A floating glass bar; everything scrolls | Tabs and filters always in reach, in one place; a keyboard-up tablet keeps its content |
|
||||
| 2026-09-24 | B5 Surfaces | One class + radius per role | Today's per-site mix | Nested corners and no per-site alpha drift |
|
||||
| 2026-09-24 | B6 /watch | The app's surfaces, native video controls | Flat and minimal | The page strangers see should look like the product; native controls work on any device |
|
||||
| 2026-09-24 | B7 Nav rail | Soft tint + edge bar, optional labels (a user setting), slim | Solid accent (recommended); a Material rail | The owner's combination: calmer than a solid fill, labels for who wants them, no width cost |
|
||||
| 2026-09-24 | B8 Loading | Skeleton by shape, spinner in a control | A spinner everywhere | Nothing jumps when data lands; a long wait doesn't look stuck |
|
||||
| 2026-09-24 | B9 Fade | Toolbars / headers, panel tabs, dialog edges, chip rows | Thumbnails; buttons | The north-star depth where content scrolls under chrome; not on content or small controls |
|
||||
| 2026-09-24 | C1 Action classification | The table (lab C1): state + primary at rest, everyday toggles on hover, "…" on touch, destructive into the menu | Visible buttons per site, as today | One action list per object, nothing gesture-only, fewer buttons without losing a function |
|
||||
| 2026-09-24 | C2 Side panels | A tap opens an overlay drawer; pin is a separate button ≥ 1024 | A tap pins and the content reflows | Below 768 the filters were unreachable; on touch a tap pinned and pushed the grid |
|
||||
| 2026-09-24 | C3 Players on touch | Tap = show the controls; 44px seek hit area; 44 buttons; the YT description behind ⓘ | Today (tap also pauses; 7.5px seek bar) | Measured live: you couldn't reach the seek bar without pausing, and the hover-only description never opened on a tap |
|
||||
| 2026-09-24 | C4 Dialogs | Focus by purpose; a pinned footer | Focus on Close; the footer scrolls | A form starts in its first field, and Save stays on screen with the keyboard up |
|
||||
| 2026-09-24 | C5 Plex player controls | The owner's lean set: no Stop / Restart / ±10 s buttons, Back by position, Next only with a next item, Resume + From the start on the card, touch double-tap ±10 s | Every control in one row (it ran off-screen below 1024); Back by a press counter; ±10 s keyboard-only | The row fits a portrait tablet; the decision to restart is made on the card; a tablet keeps the 10 s skip |
|
||||
| 2026-09-24 | Glass tuner | Retired; the schemes are the only colour choice | Keep it with ranges clamped to the rules | Free tuning is the drift the constitution exists to stop (owner) |
|
||||
| 2026-09-24 | Matrix toned down | Moss #86a05a at Midnight's lightness, near-neutral greys; every white-on-accent part → `--accent-fg` | The B2 lime #a3e635 | The owner found the lime neon and tiring; it was the loudest accent (L 0.85, C 0.21), and fixed white parts sat on it at 1.5:1 |
|
||||
| 2026-09-24 | Field primitives | `Input` / `Textarea` / `InnerInput` + `fieldClass`, `SelectTrigger`, the native controls; the lint rule "no raw `<input>`" | `inputCls` and ~40 hand-styled boxes | Six edges, four radii and two focus looks for one control; the ≥ 3:1 edge held nowhere |
|
||||
| 2026-09-25 | Surface roles | `SURFACE` roles in `ui/surfaces.ts`; the lint rule "no bare glass class"; menus p-1 with r8 rows | Three tiers paired ad hoc with five radii and three menu paddings | ~140 sites drifted; nested corners only hold if the radius comes with the role |
|
||||
| 2026-09-25 | Static labels | Flat tonal `Badge`, no edge; a filtering tag is an edged chip | A glass pill with an edge, like the chips | Edged = pressable at a glance; a static tag that looks like a chip gets clicked and does nothing |
|
||||
| 2026-09-25 | Header search | A 40 glass pill with the field edge (`lg`); what sits inside it is round | 44, r16, a glass box with a faint edge | The one rounded box among pills, and its edge under 3:1; the hero search is the YouTube/Gmail pill |
|
||||
| 2026-09-25 | Switch row (F12) | The whole settings row toggles (`SwitchRow`; a hand-laid row points a label at the switch) | Only the 36×24 switch toggles | The iOS / Material settings row; the text was a dead click beside the control it names |
|
||||
| 2026-09-25 | Edges and hovers (F14) | The ≥ 3:1 edge on the field family (fields, the form trigger); labelled pills keep the faint edge and the accent-edge hover | The ≥ 3:1 edge and a state-layer hover on every control | 1.4.11 asks an edge only where nothing else identifies the control; a heavy edge on every chip and tab weighs the whole UI down |
|
||||
| 2026-09-25 | Rating and live (F16) | Own tokens: `--rating` (theme-scoped gold), `--live`/`--live-fg`, `--rating-media`, `--media-chrome`; palette classes lint-refused | Map them to `--warn` / `--danger` | A gold star and a red LIVE are what the eye expects; as warn/danger they would read as a status. The old amber score was 2:1 on light |
|
||||
| 2026-09-25 | Fjord trial (B2 exception) | A fifth scheme, temporary: Midnight's neutrals, Playnite's steel accent (#337599 lifted to #5aa1cb) and steel rules; exit = fold into Midnight or remove | Retune Midnight straight away; borrow only the qualities | The owner wants to live with the calmer palette app-wide before it replaces the default; it breaks "own hue family" on purpose, and only until that call |
|
||||
| 2026-09-25 | Whole-card row (owner) | A card row's B3 layer is the card's `::before` under its content; the open button's hit layer spans the card, the actions sit above it | The name button's own hover, ending at the first badge or button | A row that half-answers the pointer reads as broken; a badge click did nothing |
|
||||
| 2026-09-25 | Badge tones (F29) | `Badge tone` neutral / accent / warn at 6%; light `--warn` #b45309 → #a14a07; edged label spans lint-refused | Keep edged status pills (a private Badge in Users, Settings "Granted", the suggestions count) | Edged = pressable at a glance; amber-700 was 4.58:1 as text and fell under 4.5 on its own tint |
|
||||
| 2026-09-26 | Page band built (B4) | Controls only in the band (intros scroll); the fold shows the same row in place; one `h1` per page (`PageHeading` steps the hidden one aside); `SectionLabel` headings; Skip to content | A popover of the folded filters; the page title kept visible | A folded row is still the same controls, nothing duplicated; the rail and the tab title already name the page |
|
||||
| 2026-09-26 | Fade built (B9) | `fade-below` on sticky toolbars and table headers; the scroller mask where the band sits on the backdrop | A painted band over the backdrop | The backdrop is the colour under the band, so fading the content into it is the same edge |
|
||||
| 2026-09-26 | Viewport units | `dvh` everywhere (the Plex player stage with S3f) | `vh` / `h-screen` | `100vh` hides the last rows under a tablet browser's toolbar |
|
||||
| 2026-09-26 | Video actions built (C1) | One list per video (menu, right-click, long-press, "…"); the card keeps watched / save / add to playlist on its picture on hover; download, details, copy, hide, reset in the menu | The six-button row under the card and the hover ⓘ | The menu is the one door every device has; the card loses a line of height and the touch card its row of 28px buttons |
|
||||
| 2026-09-26 | Plex actions built (C1) | One list per Plex title (play/open, watched, add to playlist, media info, copy title, pin); the poster keeps watched / add / "…" on its picture on hover; seasons get open / watched / add / copy | The hover ⓘ, the pin-only menu, an episode's add button at rest, a collection's "Remove" X on the card | The same door as a video's; the collection grid goes to two columns on a phone so the touch "…" leaves the title its line |
|
||||
| 2026-09-26 | Playlist actions built (C1) | A playlist row's "…" (play, pin, copy title / link, move, order, remove), Delete + an undo toast; one list per playlist (rename, pin, YouTube open / push / revert, delete) from its rail row and its header's "…" | The row's X column and its confirm; the header's pencil, YouTube link, push, revert and trash buttons | Remove is reversible, so it needs no confirm; the header keeps Play all; a narrow table drops "#" and Channel so the title keeps a width |
|
||||
| 2026-09-26 | Channel + Plex list actions (C1) | A channel row's "…" (open, pin, YouTube, copy, full history, hide + undo, unsubscribe); a Plex playlist's title / show / season "…", Delete + undo; its header's "…" (rename, delete); an action toast lasts ≥ 8 s | The channel row's full-history, hide and unsubscribe buttons; the Plex list's red X on every row, show and season; the header's pencil and trash | Hiding and removing are reversible, so they need no confirm and the undo needs time; unsubscribe and deleting a playlist keep theirs |
|
||||
| 2026-09-26 | Download / notification / Scheduler actions (C1) | A download row's "…" (play, share, save, edit, details, re-download, manage sharing, copies, cancel / delete / remove); a library row's Share stays in sight, ahead of save; a notification row's "…" and hover dismiss; the inbox band's and the Scheduler strip's "…" | The download row's five rare buttons and its cancel / delete / remove; the source link's copy button; an activity notice's Find / Undo links; the band's Clear everything; the strip's Purge discovery | The destructive rows keep their confirm, and Clear everything gains one; a row link keeps the browser's own menu; Find in feed drops the tag / search / age filters that could hide its video |
|
||||
| 2026-09-26 | Channel menu: Tags + Priority (C1) | Tags A–Z as in-place checks; Priority as fixed steps 10 · 5 · 3 · 2 · 1 · 0, the current one ticked; a pick re-sorts at once and the page + focus follow the row; one drawn `MenuCheck` for every checkable row that cannot be an `<input>` | Relative steps (+1 / +5); straight to the top; the stepper only; seven hand-drawn check marks (three box sizes, a tinted box, a × for "on", a trailing tick) | Bubbling a channel up is one pick; fixed levels keep the scale the reader already uses; the list moving where the reader can see it is the feedback |
|
||||
| 2026-09-26 | Reorder without a drag (WCAG 2.5.7) | Row menus: Top / Up / Down / Bottom (YouTube + Plex playlists); saved views: four buttons with the place beside the selected view (owner: A); side panels in edit mode: an Up / Down pair per group (owner: A), the name wrapping there | A "…" on every saved-view row; a "…" on every panel group; drag only | A visible, one-click path where the list is edited; the edge moves shown off so the buttons never shift |
|
||||
| 2026-09-26 | Titles in click surfaces | The surface stays a button, flagged `selectable`: its text selects, and the click that ends a selection does nothing; every plain `Pressable` pinned with its reason | Rebuilding each card and row so the title sits outside the button; exceptions for master-detail lists | Chrome selects inside a button once it is `user-select: text` (measured), so one flag on the primitive keeps the keyboard, focus and list walking every surface already has |
|
||||
| 2026-09-26 | Right-click on a selection | The browser's own menu opens on selected words; beside them the object's menu | A "Copy selection" row in the app menu | The reader selected the words to do something with them; the native menu copies, searches and translates, and changes nothing else |
|
||||
| 2026-09-26 | Keyboard ring on a flush row | Inside the row (a table row by its tag, a log line, a show header in its clipping card, with the card's corners) | The ring outside, as on a card | Outside it ran under the table head and past the table, and a clipping card cut it away entirely (invisible focus) |
|
||||
| 2026-09-26 | Fade at rest | The sticky header's fade appears with the first 1rem of scroll (a scroll-driven animation; no fade where unsupported) | A fade that is always drawn | At rest it dimmed the first row and hid its ring's top edge; nothing is under the header yet |
|
||||
| 2026-09-26 | Narrow playlist table | "#" and Channel hide by the table's own width (under 42rem), not the window's | Hiding below the `sm` window width | Beside the playlist rail a desktop window left the table 432 px and the title 0 px |
|
||||
| 2026-09-26 | Background menu built | Five list pages (feed, Plex grid, channels, playlist, notifications); the toolbar's sort / view / filters and the band's actions; no destructive row | Every page with a toolbar; the "…" menus copied whole, delete included | The tab-only pages have nothing a menu would add; a blank-area right-click must not be one click from delete |
|
||||
| 2026-09-26 | Media card anatomy (C) | One frame; the meta line pinned to its bottom; the length a badge on the picture; the Plex card on the same primitive as the video card | A: the year as an overline over the title; B: the year inline after it; a fixed two-line title slot | A one-line title left a hole the eye reads as a missing line; C puts nothing under a variable-height title |
|
||||
| 2026-09-26 | One Play | `MediaPlayGlyph` (the media button variant) and only where the click plays | The Plex card's hand-painted accent circle; a playable dot on every card | One Play for every card; a dot that only a colour and a tooltip explain says nothing |
|
||||
| 2026-09-26 | Filtering values on the info page | A value that filters (year, certificate, studio, director) is an edged chip; a fact is flat text | Everything flat, the clickable ones only hover-tinted | The S3d rule: edged = pressable, so the reader sees which values do something |
|
||||
| 2026-09-26 | Shelf density | On any strip: one title line over one meta line | The grid's two lines and full meta on a strip | The tallest card set the strip's height and left holes in the cards with less to say |
|
||||
| 2026-09-26 | Compact list row (B) | The title leads; a faint "…" at the end; the toggles float over the date on hover | A leading 128px action column | That column sat empty at rest, a hole at the start of every row |
|
||||
| 2026-09-26 | Media-info layout (B) | A main column (collections first, crew, cast) beside a facts sidebar; an empty column is not drawn | Every section full width, stacked | The collection is the most used; the keywords' column left a void beside a short details box |
|
||||
| 2026-09-26 | Mixed Home shelf (A) | Plex titles as wide art beside videos | Posters, with the videos not stretched | Stretching a video card to a poster's height left an ~80px gap |
|
||||
| 2026-09-27 | Home hero | A card (hover row + Play on the picture, the whole menu, a touch "…"; owner: A); three quarters wide and centred on a wide window; one fact line; the summary at the measure | The hero's pin row alone; full width; an 18rem picture column | The one answer stands in focus, and it offers what the same card offers anywhere |
|
||||
| 2026-09-27 | Home shelf tiles | A channel / playlist tile: Play, ↗ open, "…" with Open; a show acts on its next episode, ⓘ opens it; the shelf slot 232px | The tile's pin row alone; 200px | A tile without its object's actions read as broken; at 200 the Play touched the hover row |
|
||||
| 2026-09-27 | Synopsis preview (C) | A ~0.9 s mouse rest opens a passive panel beside the card | The synopsis as the picture's `title` tooltip; an ⓘ to hover; none | One long tooltip line fired anywhere on the art and clashed with the cut title's own tooltip |
|
||||
| 2026-09-27 | Reading measure | Prose capped at ~65 characters a line (`measure`) | The container's full width | At 110–130 characters a line the eye loses the next line's start |
|
||||
| 2026-09-24 | Chip family | One `Chip` (filter / token / tag / suggest / ghost) + `DismissibleChip`; nothing under 24; the lint rule "no raw `<button>` outside ui/" | Five chip geometries in five files | The applied-filter row, the tag cells, the year picker and the saved-view editor each drew their own chip; a one-letter tag was 21px wide |
|
||||
| 2026-09-24 | Button families | `Button` / `IconButton` / `Pressable` / chips / `DragHandle`; `lg` 40 for a hero CTA; pills and a 48 Play on media (from C5) | Every button hand-painted | 268 hand-rolled buttons in 79 files drifted into as many looks; the ladder only holds if every button stands on it |
|
||||
| 2026-09-27 | C4 as built | `initialFocus` required on every `Modal`; the commit row in `ModalFooter`, portalled under the body from any depth; the fades driven by the body's scroll timeline; `interactive-widget=resizes-content` | An optional prop defaulting to the ✕; a `footer` prop (the issue composer's buttons live three components down); always-on fades | A default is how 21 dialogs came to open on the ✕; lifting the composer's state to reach a prop is the larger change; a resting fade dimmed the first line |
|
||||
| 2026-09-27 | C3 + C5 as built | A tap toggles the bar through `pointerType` from `pointerdown`; a double-tap takes back its first tap's toggle; the card's pair is the video card's `MediaResumeButtons` (Continue / Restart), a sibling over the picture; the YT description is an ⓘ click popover | A delayed single tap (wait out the double-tap window); new "Resume / From the start" words for Plex; the pair inside the picture's button | A delayed tap feels dead; one media card says one pair of words; a button inside a button is invalid and the hover row already sits beside the picture |
|
||||
| 2026-09-27 | C2 as built | The side panel's drawer is `ui/Modal` `drawer-start`; drawer = a coarse pointer or below 768; the pin offered in its header ≥ 1024 | A drawer of its own inside `SidePanel` | Esc, Back, the scrim, the trap and the scroll lock are the dialog's; a second implementation is how two shells drift |
|
||||
| 2026-09-30 | Composition and the reader (E30 S6) | A chapter and a Conformance step: the space is used, one focal point, worst real data, where am I, a click answers at once, zoom and text size first-class; the person page as two columns (facts and bio left, "Known for" right) | Rules for pieces only; the bio in a full-width panel; a narrower panel | The person page passed every piece rule with half its panel empty; the owner reads zoomed in, so zoom is a requirement, not a nicety |
|
||||
| 2026-09-30 | Hungarian words (E30 S5) | The D3 list: Feed, Shorts, Admin, Token, Port stay; stream, Prio, Job, Audit, Demo, Auto, Info, Frontend/Backend, Backfill, transcode get the Hungarian word; one name per thing (kérelem, behúzás, one "Test connection") | Keep every loanword; translate Feed/Shorts too | The owner chose the list (D3); the final sweep found the same feature under two names in three places |
|
||||
| 2026-09-29 | Numbers and order in the UI language (E30 S3) | Every number through `lib/format.ts` in the UI language (decimal mark, grouping, compact, units); A→Z by the shown name in the UI language's alphabet, client and server alike; the language comes off `useTranslation`, never the singleton | `toFixed`, hand-built "1.2K", `localeCompare` in the browser's locale, byte-order server sorts | A Hungarian reader saw "8.3", "1.2K", "Életrajzi" after "Z"; the singleton read also left values in the old language after a switch (React Compiler) |
|
||||
| 2026-09-27 | Narrow rows by container | The download row, the playlist table and the Channels tag row stack by a container query; a fact line never wraps | Breakpoints on the window | The iPad zoomed in, split screen and a column beside a rail are narrow while the window is not; the zoomed download row broke "18.9 / MB" apart |
|
||||
| 2026-09-27 | Phones deferred | A phone-only layout (the hamburger nav, a folded feed band) waits for its own epic; E28 stays desktop + tablet | Fix the phone views inside E28 | Principle 2; the first phone attempts made the feed worse, and the epic's review grows with every sprint |
|
||||
| 2026-09-27 | Conformance check (S3g) | A four-step check before a UI change is done: primitive at a named rung, the chapter re-read, the rendered page measured by kind and look, every state seen | A reviewer's eye per sprint | The S1 probe found 69 button looks; after S3 every control kind is drawn by its primitive, and the check keeps a new look from arriving unnoticed |
|
||||
| 2026-09-27 | Segmented rung | `SegmentedToggle` defaults to the toolbar rung (28, `text-xs`); 24 only for a panel's captioned match toggle | The small default | Two toolbars had inherited 10px type from the default beside 28px buttons |
|
||||
| 2026-09-27 | Copy rule (S3g) | One name per feature (the rail may shorten it); four verbs for four meanings; sentence case with the app's places capitalised; "…" when a command asks first; one-sentence messages without a stop; curly quotes; dates relative in lists with the exact minute on hover, three absolute forms; units from Intl, short | Word-for-word names everywhere; the verbs as they were; all lower case; no "…"; always a stop; always absolute dates; long or compact units | The copy survey found 7 EN and 6 HU double names, 22 Delete against 27 Remove, five date shapes and three spellings of a minute; the owner picked every recommended option |
|
||||
| 2026-09-27 | One glyph, one meaning (S4) | Play only for playback or resuming a paused transfer; Retry = `RefreshCw`; reset / revert = `RotateCcw` | Retry drawn with Play | The first UI-review run (Downloads) found a failed row whose Retry showed ▷ in the row and its menu |
|
||||
| 2026-09-27 | Fjord kept | Fjord stays a fifth scheme beside Midnight; the trial wording goes | Fold it into Midnight; remove it | The owner lived with it and likes it; the vivid Midnight stays for those who want it. B2's own-hue rule still binds any new scheme |
|
||||
| 2026-09-27 | Tablet columns | A table hides `tabletHidden` columns below 64rem of its own width; Channels drops Prio, About, Length | Hide About only; give the name a bigger share | At 1024 the channel name had 60 px; the owner chose to drop all three there |
|
||||
| 2026-09-27 | Glyph pager | First / previous / next / last as glyph buttons round the page box, names as tooltips | Words beside the arrows (hidden only on a phone) | The owner's call: the words widened the row; four arrows are the shared convention |
|
||||
| 2026-09-27 | Match switch on the panel | `ui/MatchToggle` above the picker from two picks, everywhere; one wording (Any / All) | The picker's popover footer (Feed, Plex collection) | A closed picker hid an active "all"; six pickers had drawn it two ways |
|
||||
| 2026-09-27 | Missing picture, bare link | A glyph of the kind for no picture; a download with no name is titled by its short link, once | An empty box; the URL as title, channel and link | The owner's picks 4A and 3A: an empty box read as loading, the URL showed three times |
|
||||
| 2026-09-27 | Copy on a selection | Right-click on selected words keeps the browser's menu; no app Copy row | An app menu with Copy first | A real browser's menu has copy, search and translate; only the desktop pane's is thin |
|
||||
| 2026-10-01 | Zoom target 125–133% | Screens are held at 125% and 133% browser zoom (1536 × 729, 1444 × 685 on a 1080p window) and the largest text size | 200% browser zoom | The owner: 200% was a guess; 125–133% is what they read Siftlode and most sites at, so 200% would be an upper bound nobody uses |
|
||||
| 2026-10-01 | E31 Nav rail at short heights | One "Admin" rail item opening a panel of the admin pages | A denser rail when short; a visible "+4" hint | The rail fits at 133–150% without a hidden scroll; the admin pages are rare and admin-only |
|
||||
| 2026-10-01 | E31 Configuration sections | A vertical, grouped section list, as Settings has | Group tabs + sub-tabs; one long page with a contents list | Sixteen tabs wrapped to three rows at 133%; one pattern for both settings pages |
|
||||
| 2026-10-01 | E31 Statistics overview | Number tiles, and the per-operation counts as horizontal bars | Three narrow cards; a 30-day chart | The label sits by its value; what spends the quota is seen at a glance |
|
||||
| 2026-10-01 | E31 Channel page header | The full banner, folding to one row once the grid scrolls | Always compact; no banner | The header is fixed and took 40% of a 685px window; the channel keeps its face at first sight |
|
||||
| 2026-10-01 | E31 Channel page watch state | A fresh channel page shows the unwatched videos; a picked state is remembered | Show all, forgotten on reload | The owner: open a channel to see what is new; a choice made there should stick |
|
||||
| 2026-10-01 | E31 Audit log runs | A job's successful runs fold into one row that opens, whatever ran between; only that job's failure (never folded, danger colour) breaks it | A filter defaulting to admin actions; both | Nothing hidden, the noise collapsed, the failure seen |
|
||||
| 2026-10-01 | E31 Users row | Role and state as badges, the actions in the row's one menu | An inline role toggle; icon-only buttons | Action placement: the row shows state, rare and destructive actions live in the menu |
|
||||
| 2026-10-01 | E31 YouTube player | Video beside an info panel at 1280px and wider (the video as large as the height allows); stacked below | Today's stack with a one-line bar; full-window like Plex | The owner's eyesight: about 1460px of video on 1080p instead of 1008, the actions still visible |
|
||||
| 2026-10-01 | E31 Plex info and show pages | A second column for the facts, keywords and crew, as the person page; a collection's hero sized to its content | Full-width text; a larger poster and fanart | The right ~40% was empty; one composition for every media page |
|
||||
| 2026-10-01 | E31 Nav rail rows are links | Each page row is a real link: a middle-click or Ctrl-click opens the page in a new tab | A button | The owner: open a page in a tab of its own, as on any site |
|
||||
| 2026-10-02 | E31 Plex detail second column (refined) | The facts over the key crew beside the text; the keywords, chips that filter like the genres, under the text; the show page gets all three too | All three in the column, as the mockup drew it | At 20 keywords and 12 crew the column ran to twice the text's height (849 vs ~400 px at 133%): a hole under the text instead of beside it |
|
||||
| 2026-10-02 | E31 Plex detail poster and crew | The movie and show poster keeps its 2:3 and grows a rung in a wide hero (w-56 at a 64rem panel); the crew shows its first 6 names and "Show N more" (a list of 8 or fewer shows whole) | Poster stretched to the row; a "More" on the keywords | The row is as tall as the crew column, so the poster drew ~175×590 and cropped; the crew, not the keywords, set the hero's height |
|
||||
| 2026-10-04 | E32 `field` focus skips a mode switch | A form opens on its first field; a control above it that is not a field (the composer's Edit / Preview) is passed over by marking the field `data-initial-focus` | The first text field everywhere | That moved the focus in the download dialog off its profile choice and in the upload dialog off its drop zone; the mark changes only the form that needs it |
|
||||
| 2026-10-04 | E35 Lint for z-levels and edged labels | Both rules stay; the two eslint selectors (`Z_RAW`, `EDGED_LABEL`) that refused them go | Keep the selectors | 0 hits since the E28 sweep that fixed the sites: a check that never fires costs a probe test and a snapshot each, and the UI review holds both rules |
|
||||
| 2026-10-06 | `player` focus | A dialog that is a player opens focused on its panel (the YouTube player's rule, now `Modal`'s too); on the media element itself, Space and the arrows stay the element's own | `close`, or the media element | On the ✕ Space closed the player; on the element the browser's own controls acted on the same key as the player's (one Space played and paused, measured in Chrome) |
|
||||
| 2026-10-08 | Captions on touch | A `Tooltip` opens for a mouse and a key's focus only, never for a finger | A caption on tap; a long-press caption | On an iPad the tap that showed the caption was taken as a hover and lost its click (every rail button took two taps), and no finger sends the mouseleave that hides it; the rail's labels setting names the buttons on touch |
|
||||
| 2026-10-08 | Header search on touch | No key cap on a touch screen; the pill grows to 52 px so a ring shows round the 44 px Go; Go drops to its icon by the column's width | Keep the key cap; a 44 px Go overhanging a 40 px pill | On a tablet the 44 px key cap and Go sat on the pill's edge and cut the placeholder; an overhanging Go breaks the nested radii |
|
||||
| 2026-10-08 | Plex subtitles and the control bar | The player draws the cues itself; while the bar shows they rise above it (200 ms), then settle back | The browser's own cues, moved by `line` | On an iPad the bar covered the text; a native cue cannot be animated or measured, and our layer behaves the same on every engine |
|
||||
| 2026-10-08 | Hover on a button over a picture | The `media` variant's hover is a 2px accent ring over a darker body (Plex + YT cards, rail arrows; option B) | An accent fill (reads as "selected"); a white wash (weak on a bright poster) | The 60 → 75% black step was invisible, and over a card a rail arrow could not be told from the card's own Play under it |
|
||||
| 2026-10-08 | Plex "Add to collection" | A movie or show card's menu row opens a panel beside the card: its library's manual collections tick in place, a name + Enter creates one with the title in it (admin; option A) | An Add submenu with a "New…" dialog; the per-title editor modal from the menu | A collection took a trip to the Collections page, a name, a title search, then a second search per title; the panel is the video card's "Add to playlist" |
|
||||
| 2026-10-08 | YouTube modal chrome | No prev/next strips beside the card; Close an icon (the panel's top right; stacked, the title row's end); the description clamped to three lines + More; the panel shuts to a 2.75rem strip of close, expand, prev/next (option D1) | Keep the strips; a "Close" text button; the full description in a scroller; a panel that hides outright | The strips cost the video 7rem of width for a second copy of the panel's buttons; a long description pushed the channel and the actions out of sight; a hidden panel left no way to step the queue without the keyboard |
|
||||
| 2026-10-08 | The wheel over the YouTube modal | Over the video: volume. Over a panel with something to scroll: scroll only, never volume, not even at its end. Over a panel with nothing to scroll: volume (owner) | Volume everywhere; a scroll that hands over to the volume at its end | Reading a long description turned the volume down once it hit the end |
|
||||
| 2026-10-09 | A Plex show card plays | Its picture plays the show's next episode everywhere (an episode with a resume point → Continue + Restart, else the first unwatched, else S1·E1), resolved on the click; the preview names it once up; title and ⓘ open the show (option A + hover ask) | The picture opens the show page (as before); every card carrying `next` | A show card on Discover had no Play while Home's had one; carrying `next` costs a grid page up to 180 queries for the few cards anyone plays |
|
||||
| 2026-10-10 | Clip mode in the players (E38) | Scissors in the control row + `C`, `[` `]`; the panel in the player with the watched video as preview; overview + zoomed strip on `ui/RangeTrack` (ends are sliders); a toast + the Ready notification after Cut | A ⋯ menu entry; permanent In / Out buttons; a big dialog with its own preview (a second Plex transcode / YouTube iframe) | Owner's picks A, P1, a; a film is hours and a clip seconds, so only a zoomed strip gives a hand the precision. The Downloads editor's cuts moved onto the same track (keyboard-steppable now) |
|
||||
| 2026-10-10 | Crop in clip mode (E38) | A Crop toggle in the clip panel: a frame over the playing picture (`ui/CropFrame`, the editor's crop too), Free / 16:9 / 9:16 / 1:1, Whole picture; maximised YouTube keeps the panel in the bar's place; the wide side panel shuts while clipping | A frame always on the picture in clip mode (K2); a free shape only | Owner's K1 + a: a crop is rare, so it never covers the picture unasked; a phone or square clip needs a held shape. The iframe hides its picture's size: drawn on the 16:9 box, the cut fits it to the real picture |
|
||||
| 2026-10-10 | Marks on the player chrome | `--media-mark` (amber) and `--media-danger` (light red), the same in both themes; `media-marks` points the focus ring (`--focus`) and the chosen mark (`--chosen`: a track's tick, a tab's underline; the label stays white) at the amber on the player and every chrome surface; `media-scope` (a form) also the errors at the red | The theme's accent ring, chosen text, warn and danger | On the chrome (#171717) a light theme's accent ring (Slate 2.84:1), warn (2.99:1) and danger (2.77:1) all fall under 3:1; the accent as chosen text under 4.5:1 |
|
||||
| 2026-10-11 | Files page (one library) | List rows by default, the media grid a toggle remembered per folder; a sidebar of automatic source folders, own folders, Shared with me and the storage meter; the paste-a-link box in the toolbar | A media grid by default | The library holds videos AND plain files: rows read both, show more per screen and scan by size and date |
|
||||
| 2026-10-11 | Library list columns | Every kind of value in its own column (name, source, phone-safe, retention, size, added, actions), one grid with a subgrid per row so they line up; an action that does not apply keeps its slot empty; a right-click menu on every row (the ⋯ opens the same menu) | Badges flowing after the title; icons that shift when one is missing | Owner: values of one kind must fall in one vertical line; a row's every action reachable by right click |
|
||||
| 2026-10-11 | Running downloads | An app-wide tray, bottom right, shown only while something runs or failed (reason + retry), foldable to a pill | A rail icon with a count and a popover | Downloading became an action you start anywhere; a running one must be visible without going to look |
|
||||
| 2026-10-11 | Download done | The notification says whether it plays on a phone and carries Link másolása + Megnyitás (the folder, the item focused); never an automatic jump | A plain "ready" notice; auto-navigation to the item | The daily path is paste → done → copy the link; a jump would pull the user out of what they were doing |
|
||||
| 2026-10-11 | Library row quick icons (owner A) | On a wide list only the ⋯ holds a place; Copy link, Share and Save come up over the date while the row is hovered or holds the keyboard; a card (phone) keeps them in its own line; Keeps narrower | Three icons always in sight (the name kept ~150px at 1200); dropping Added below 64rem | Owner: the name is what a row is read by; every action stays in the ⋯ and the right-click menu |
|
||||
| 2026-10-12 | Files preview (owner ★) | A file that is not media opens from its name in the dialog shell, wide: an image, a PDF in the browser's own viewer, text as numbered plain text (HTML and SVG too) with a wrap toggle, else a no-preview card with Save; ← / → page the list's such files in its order; an image under 8 MB is its own thumbnail | A side panel beside the list; a new browser tab; pdf.js; syntax highlighting; a click that saves a file without a preview | Owner: one way to open anything, paged like the list; the browser's PDF viewer is free and isolated; a page is never rendered on our origin |
|
||||
| 2026-10-12 | A running download's step (owner ★) | The tray row names the step beside its bar ("Downloading audio · 12%", "Merging" with a pulse); a paused-only tray shows a pause mark, never the done check | A bare bar and % | A download fetches video and audio as two streams: unnamed, the second fill reads as a restart; the tray is the only place a download is followed |
|
||||
| 2026-10-14 | API tokens (owner A/A/A) | Settings → API tokens: a row per token in three lines (name + prefix, its folders and rights, last use and expiry), revoked from its ⋯; a new token asks the kind first (Hub exchange or Custom: rights as chips per folder), expiry 1 year by default; the token shows once in the same dialog, with Copy and a curl line | A table; one form with a preset link; the token in a banner above the list | A table truncates the rights at this width; the common token never shows a matrix to get wrong; closing the dialog is plainly when the token is gone |
|
||||
| 2026-10-15 | Folder links (owner A/A/A) | An own folder's menu has Copy link and Share with link… as a file row does (the dialog is the link half of the file's); the link opens a list of the folder's files as it is now, Play opening the watch player above it with the playing row lit, a document only downloading; the rail marks a folder with a live link beside its count | Share with link… alone; cards; a download-only list; no mark | Mostly videos from a phone, read on a phone: a list gives a long name its line and the next one is a tap away; the folder link is the one place where moving a file in publishes it, so where it is must show |
|
||||
| 2026-10-17 | Copy-only changes (owner ★) | Step 4 of the Conformance check alone (not 1–3 or 5): every state the changed text renders in, seen in both languages | The whole five-step check; no screenshot at all (DOM test + key parity) | Steps 1–3 and 5 judge controls, patterns and composition, which a text change does not touch; the one risk left is a longer Hungarian string wrapping or clipping, and only a screenshot shows that |
|
||||
| 2026-10-17 | Text on glass (owner ★) | Light `--muted` 15% toward `--fg` in every scheme (≥ 6:1 on the bare page); the item count, the badges and the current Files row on opaque tints mixed into the surface | Only the two failing components; the item count's number in `--fg` | Pixel-measured over every scheme × mode × backdrop, the count fell to 3.8:1 (dark too: thumbnails scroll under the toolbar's glass) and Channels' tabs to 4.1:1; an `--fg` count outshouts the filters beside it |
|
||||
| 2026-10-18 | Scheduler run history (owner D4, E1, E2 ★) | A row's last three runs as dots, newest first (interrupted: a hollow warn ring, set apart from skipped and failed), and a history button that opens the job's runs on the Activity page; a user's ad-hoc runs in their own block under the jobs, with no interval and no run button | An inline expandable history per row; a dark-grey interrupted dot; ad-hoc runs only on the Activity page | Three dots answer "did it run, did it work" at a glance; the whole history needs filters, which the Activity page has |
|
||||
| 2026-10-18 | Activity page (owner D1, D2, G1–G3 ★) | One page, "Napló" / "Activity": four tabs (Runs, Admin actions, Server log, Quota) under one filter bar (text, a period of 1 h · 24 h · 7 d · 30 d · 90 d defaulting to 7 days, an account), the view in the URL; runs and admin actions as dense rows that open in place as a log line does, filtered and paged on the server; a run's or a request's log lines one pivot away, as a history entry | One merged timeline; a page per source; a default period per tab; card rows; the audit log's client-side table | Each source keeps its own table and retention, read in one place; one bar keeps what you narrowed across tabs; about 1.8k runs a day need a log's density and a server-side filter |
|
||||
| 2026-10-24 | Related videos (owner U1–U3 ★, D1 A, D3) | On demand: a tab beside the description (wide), a drawer (stacked); the narrow thumbnailed row, its menu alone, a followed check; plays in place and the list stays the opened video's; an on-topic / Hungarian-trending switch kept on the account | Always shown; the end-of-video grid alone; a dialog; a big card or a text row; a list that follows the playing video | The modal is full on a small screen; a picture is what a choice among strangers rests on; a list that stays put is tried one by one, and spends no more of the day's cap |
|
||||
| 2026-10-25 | Related: one played; off (owner D1 a, D2 a) | Played from the list, it is the player's item: its title, controls and progress, marked watched at its end, the queue left where it was; a daily limit of 0 takes the tab and the button away | A linked video's in-place play (no controls, nothing kept); a tab that only shows a refusal | What is watched should count as watched, wherever it was started from; a control that can only be refused is not offered |
|
||||
| 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 |
|
||||
| 2026-11-01 | Docked bar glyphs (owner D8 a) | The maximised view's docked bar is glyph-only too (tooltips carry the names and keys): transport, auto-advance, loop, Mark watched (✓ / ✓✓); its controls scroll on a narrow window while Fullscreen and Exit stay pinned at its right end | Labels from `xl` up | On a tablet the labelled bar ran past the right edge and took Exit with it; the side panel had already lost its labels |
|
||||
| 2026-11-01 | Toolbar group glyphs (owner D9 a, D10 a, D11 a) | The feed's, channel page's and Plex Browse's filter pills name their group by a glyph (`Eye` watch state, `Shapes` content types, `ArrowDownUp` sort), the word in the tooltip and the accessible name; Sort + View end the toolbar's row, the chip row shows only with a chip; a channel page has no count pill | The value alone; Sort + View on a row of their own | "Watch state:" and "Sort:" cost a tablet row its room; the value says enough once the glyph names the group; the channel header already counts the videos |
|
||||
| 2026-11-01 | Channel header on a tablet (owner E2) | Below `xl` the action row drops its two words: "Prio" (the stepper's tooltip names it) and "Subscribed" (a ✓ glyph; its name in the aria-label, Unsubscribe in the tooltip); the tags keep the row's rest, folding into "+N" | The tag lane on a full line of its own below ~12rem; the tags under the channel name | On an iPad (820 px, 44 px targets) the lane got 29 px, a sliver; now 130 px, and every tag shows at 1180 |
|
||||
| 2026-11-01 | Clear watch progress (owner E a) | A video menu's Reset reads "Clear watch progress" in English (HU "Megtekintés visszaállítása" stays); "Reset view" is only a page's view reset (sort, filters, grouping) | "Reset view" for both; the playlist page's view reset renamed instead | On a playlist page the two stood one right-click apart under one name, and one of them erases the video's progress with no undo |
|
||||
| 2026-11-01 | Clear watch progress clears only that (owner A) | The row shows only on a video with a resume point and clears that alone: a hidden video stays hidden, a watched one watched. Un-hiding and un-watching have rows of their own | The old Reset, which also un-hid and un-watched | A hidden video stays hidden: what the row's name says is all it does |
|
||||
| 2026-11-01 | Selecting a list's rows (owner D2 a) | An always visible box first in the row and one over the column for the rows shown; Shift+click a range, `x` the row under the keyboard, Esc clears; the selected row wears `accent/12` with its tick. Rows a filter hides stay selected, an action covers those shown; Watch later offers no selecting. | A "Select" button that shows the boxes on demand | Found at once and works on touch, with no mode to leave; costs about 2 rem a row |
|
||||
| 2026-11-01 | Selection band (owner D1 a, D3 a, D4 a) | The toolbar's second row while rows are selected, no floating bar: move (the last target as one click) and remove, no copy; both undo back to the places, a video the target held before stays there; a single row's move undoes too. | A floating bar at the bottom; copying to a list too; no undo on a move | It covers no row, and the player and the notices live at the bottom; twenty videos sent to the wrong list need a way back to their places |
|
||||
| 2026-11-01 | Grip on a phone (owner A) | Below a 24rem table a playlist row has no grip: the title keeps its width, and the row menu keeps the moves. | The grip and its drag kept, the title at 44 px | The title gets its width back, and the rail is shut on a phone, so a drag had nowhere to go |
|
||||
| 2026-11-01 | Selection band on a tablet (owner A) | Below `xl` the band is glyphs on one row, the names in tooltip and aria-label, as on the channel header; the replaced row stays in the same grid cell, invisible, so the first tick moves no row under the second tap. | The buttons in words, wrapping to a second row | The first tick pushed the list from under the second tap |
|
||||
| 2026-11-01 | Playlist heading on a narrow window (owner A) | The list's name had no width left: below `xl` Unsynced is its dot (the word read out, the hint in the tooltip); on a phone the cover is gone and Play all is its glyph, named in the tooltip. | Every word kept, the list's name at no width | A heading without its name says nothing |
|
||||
| 2026-11-02 | Dragging onto a list (owner D5 a, D6 a) | The grip carries a row, or every selected row with a selected one, onto a list in the rail; the toast undoes. Many dropped inside the list stay; a coarse pointer's drawer never peeks, so its rail is a target only when pinned. | Only the grabbed row going along; the grip off under a view | One row moving out of three lit ones misleads, and a filter is how the rows to move are found |
|
||||
| 2026-11-02 | Delete with every tick hidden (owner a) | It removes nothing and a warning says the filter hides them | Taking the row under the keyboard | While the band shows a selection, Delete means that selection: a row no one ticked must not go |
|
||||
| 2026-11-02 | Undo of a video gone further (owner a) | A video the move put in the target comes back only if the target still holds it, and a warning says how many | Everything back, whatever it did since | A move skips a video that left the source; the same rule back keeps a video out of lists the reader never put it in |
|
||||
| 2026-11-04 | Tag chip counts (owner D5a) | A Channels tag chip shows how many followed channels it holds: a muted number after the name, no badge | The number in brackets after the name | The owner's pick; the number is a detail of the name, so it takes the name's own text, muted, rather than a `CountBadge` |
|
||||
| 2026-11-05 | Picked tag chips lead the row (owner c) | On the Channels tag row the picked chips come first, in the tags' order, then the rest | Keep the order and fold the unpicked first; mark the "+N" when it holds a pick | The row folds from its end, so a picked tag late in the list sat only inside "+N" with nothing on the row saying a filter was on |
|
||||
| 2026-11-05 | A toggled tag chip keeps the focus (owner a) | A chip that moves when toggled takes the keyboard focus with it: to its new place, or to "+N" when it went into the closed fold | Keep a picked chip in the "+N" popover until it closes | The row always shows the filters as they are; the focus, not the order, was what got lost |
|
||||
| 2026-11-06 | Tag chip count after a dot (owner a) | The count keeps the chip's own colour, set off from the name by a "·" | The number dimmed (it fell under the 4.5:1 text floor, resting and pressed); the number in a tinted inner badge | Contrast holds in every scheme without a new token, and the dot still reads the number as a detail of the name |
|
||||
| 2026-11-06 | A pick in the open fold closes it (owner a) | Toggling a chip inside the "+N" popover closes the popover; the focus goes with the chip | Keep the popover open and focus the chip now in the picked one's place | The focus never sits outside a popover left open, and a picked chip leads the row anyway |
|
||||
| 2026-11-06 | An expired share link offers no Copy (owner a) | An expired row in the share dialog has a warn badge "expired <date>" and its address struck through; Open and Revoke stay, Copy goes | The warn badge alone, Copy kept | An expired link opens nothing, so it is no link to hand out; Open still lets the owner check it |
|
||||
| 2026-11-06 | The shared page's unlock button is a noun in Hungarian (owner a) | "Megtekintés" for a video, "Megnyitás" for a file or folder | Both verbs, "Megnézem" / "Megnyitom" | The app's Hungarian buttons are nouns; one button should not change grammatical form by link kind |
|
||||
|
||||
+2
-2
@@ -108,8 +108,8 @@ project checks needs a row.
|
||||
|
||||
| Scope | Narrowed | Why | Measured |
|
||||
| --- | --- | --- | --- |
|
||||
| check | e2e (Playwright) not in `check` | It needs the :8080 stack built from the tree (minutes). It runs in `check-full`, and `release` rebuilds the stack and requires it (E32 D2) — nothing ships without it. | 9 specs: 6 × 3 engines, 3 on chromium only (the row below) |
|
||||
| e2e | `a11y.spec.ts` `member.spec.ts` `devices.spec.ts` run on chromium only (`CHROMIUM_ONLY`, the webkit and ipad projects' `testIgnore`) | What they hold does not change with the engine: the axe scan reads the DOM and the accessibility tree, which the engines build alike; the member spec checks which pages and requests a role gets; the devices spec opens its own desktop and iPad contexts. Run three times they would triple their time and catch nothing more. What an engine does change (layout, events) the other specs hold on all three. | 3 of 9 specs |
|
||||
| check | e2e (Playwright) not in `check` | It needs the :8080 stack built from the tree (minutes). It runs in `check-full`, and `release` rebuilds the stack and requires it (E32 D2) — nothing ships without it. | 12 specs: 9 × 3 engines, 3 on chromium only (the row below) |
|
||||
| e2e | `a11y.spec.ts` `member.spec.ts` `devices.spec.ts` run on chromium only (`CHROMIUM_ONLY`, the webkit and ipad projects' `testIgnore`) | What they hold does not change with the engine: the axe scan reads the DOM and the accessibility tree, which the engines build alike; the member spec checks which pages and requests a role gets; the devices spec opens its own desktop and iPad contexts. Run three times they would triple their time and catch nothing more. What an engine does change (layout, events) the other specs hold on all three. | 3 of 12 specs |
|
||||
| pushes | no server-side gate (no CI) | Owner decision 2026-10-04. The gate (`scripts/check.sh`) runs on the dev machine before work is handed over, and `release` runs it, then e2e, before anything is merged and Trivy before the image is pushed — the CI only repeated that, after the merge. Its runner shared the git host's container, and one run there starved Gitea of memory until it stopped answering. What it added — a fresh `npm ci` on Linux — the image build does at publish. | — |
|
||||
| coverage | not in the gate; no threshold | Owner decision E32 D4: never enforced; "every regression test seen red" is the bar, and a percentage invites tests written to move it. Out of the lanes since E35: read once, by hand, it found 5 bugs; as a lane it was a number nobody acted on, and the slowest vitest run (the one that flaked). On demand: docs/development.md. | frontend 80% / backend 78% of lines (E32 S1) |
|
||||
| CVE gate | HIGH/CRITICAL with a fix available only | `--ignore-unfixed` + `--severity HIGH,CRITICAL`: a finding with no fix cannot be acted on by an upgrade; it shows in the scan output. A fixable one fails the publish, and the only way past it is `.trivyignore.yaml`. | 0 open (E32 S1) |
|
||||
|
||||
@@ -24,6 +24,10 @@ outlives an `expect` timeout); Node does not, so a request from the test side fa
|
||||
that one error again and passes every other failure straight on. Don't run two e2e suites on the
|
||||
same machine at once.
|
||||
|
||||
**A page load the machine had no buffer for** — on the same host a page load can fail at once with
|
||||
`net::ERR_NO_BUFFER_SPACE`. Every page load goes through `gotoRetrying` (same file), which tries that
|
||||
one error again; a test that calls `page.goto` itself fails `src/lib/e2eRetryConnect.test.ts`.
|
||||
|
||||
**Browsers** — every flow runs in three projects: `chromium` (Desktop Chrome), `webkit` (Desktop
|
||||
Safari) and `ipad` (iPad gen 7 landscape: 1080×810, touch, mobile) — except `a11y`, `member` and
|
||||
`devices`, which run on chromium only (`CHROMIUM_ONLY`; why is in the `docs/gates.md` row). Install the engines once per
|
||||
|
||||
@@ -4,7 +4,7 @@ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { MEMBER_STORAGE, SEED_FILE } from "./helpers";
|
||||
import { retryConnect } from "./retryConnect";
|
||||
import { gotoRetrying, retryConnect } from "./retryConnect";
|
||||
|
||||
/**
|
||||
* One-time setup for the characterization net (the `setup` project the tests depend on):
|
||||
@@ -52,7 +52,7 @@ async function signIn(page: Page, email: string, path: string): Promise<void> {
|
||||
// and player flows this net locks all open "/" expecting the feed; the opt-out is the one
|
||||
// Settings → Appearance → Startup writes. Both flags are the account's local state, held for the
|
||||
// account the browser records as their owner (`siftlode.owner`, see storage.ts claimLocalData).
|
||||
await page.goto("/");
|
||||
await gotoRetrying(page, "/");
|
||||
await page.evaluate((id: number) => {
|
||||
localStorage.setItem("siftlode.owner", String(id));
|
||||
localStorage.setItem("siftlode.lang", "en");
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { gotoRetrying } from "./retryConnect";
|
||||
|
||||
/** The plain member's saved session (global.setup.ts signs it in); `member.spec.ts` and
|
||||
* `devices.spec.ts` run from it. */
|
||||
@@ -16,7 +17,7 @@ export function seeded(key: string): string[] {
|
||||
|
||||
/** Open the app and wait for the authenticated shell (the nav rail) to be ready. */
|
||||
export async function openApp(page: Page, path = "/"): Promise<void> {
|
||||
await page.goto(path);
|
||||
await gotoRetrying(page, path);
|
||||
await expect(page.getByTestId("nav-feed")).toBeVisible();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
import { test, expect, type Locator, type Page } from "@playwright/test";
|
||||
import { openApp } from "./helpers";
|
||||
|
||||
// A video dragged onto a list in the rail, with a real pointer: the rail and the page are separate
|
||||
// React trees, and jsdom lays out nothing to drag across. The browser projects share one account, so
|
||||
// each test holds lists of its own, named for it, and takes them away after.
|
||||
|
||||
interface Listed {
|
||||
id: number;
|
||||
items: { id: string; title: string }[];
|
||||
}
|
||||
|
||||
const made: number[] = [];
|
||||
|
||||
async function newList(page: Page, name: string, videos: string[] = []): Promise<number> {
|
||||
const res = await page.request.post("/api/playlists", { data: { name } });
|
||||
const { id } = (await res.json()) as { id: number };
|
||||
made.push(id);
|
||||
for (const video_id of videos) {
|
||||
const added = await page.request.post(`/api/playlists/${String(id)}/items`, {
|
||||
data: { video_id },
|
||||
});
|
||||
expect(added.ok()).toBe(true);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
const contents = async (page: Page, id: number) =>
|
||||
((await (await page.request.get(`/api/playlists/${String(id)}`)).json()) as Listed).items.map(
|
||||
(v) => v.id,
|
||||
);
|
||||
|
||||
async function setUp(page: Page, name: string, project: string) {
|
||||
await pinOnTouch(page, project);
|
||||
const feed = (await (await page.request.get("/api/feed?limit=3")).json()) as {
|
||||
items: { id: string; title: string }[];
|
||||
};
|
||||
expect(feed.items.length).toBe(3);
|
||||
const videos = feed.items;
|
||||
const from = await newList(
|
||||
page,
|
||||
`${name} from`,
|
||||
videos.map((v) => v.id),
|
||||
);
|
||||
const to = await newList(page, `${name} to`);
|
||||
await openApp(page, `/?page=playlists&pl=${String(from)}`);
|
||||
await expect(page.getByRole("heading", { name: `${name} from` })).toBeVisible();
|
||||
await expect(page.locator("tbody tr")).toHaveCount(3);
|
||||
return { videos, from, to, target: page.locator(`[data-playlist-drop="${String(to)}"]`) };
|
||||
}
|
||||
|
||||
const centre = async (el: Locator) => {
|
||||
const box = await el.boundingBox();
|
||||
if (!box) throw new Error("nothing to point at");
|
||||
return { x: box.x + box.width / 2, y: box.y + box.height / 2 };
|
||||
};
|
||||
|
||||
/** Pick the row up by its grip and carry it to a point, the button still held. */
|
||||
async function carry(page: Page, grip: Locator, to: { x: number; y: number }) {
|
||||
const from = await centre(grip);
|
||||
await page.mouse.move(from.x, from.y);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(from.x + 8, from.y + 8, { steps: 3 });
|
||||
await page.mouse.move(to.x, to.y, { steps: 12 });
|
||||
}
|
||||
|
||||
/** The same onto the rail. An unpinned one is a tab until the drag's own hover peeks it open. */
|
||||
async function carryToRail(page: Page, grip: Locator, target: Locator) {
|
||||
const tab = page.getByRole("button", { name: "Pin Playlists open" });
|
||||
// The rail's lists answer after the rows: until then a pinned rail shows neither the list nor a tab.
|
||||
await target.or(tab).first().waitFor();
|
||||
if (await target.isVisible()) {
|
||||
await carry(page, grip, await centre(target));
|
||||
return;
|
||||
}
|
||||
await carry(page, grip, await centre(tab));
|
||||
await expect(target).toBeVisible();
|
||||
await page.mouse.move(...(Object.values(await centre(target)) as [number, number]), { steps: 6 });
|
||||
}
|
||||
|
||||
/** What dnd-kit tells a screen reader: said once the drag has taken the step in, so a drop after it
|
||||
* is the one a person makes, not one that beats the row to its new place. */
|
||||
const said = (page: Page, text: RegExp) =>
|
||||
expect(page.locator('[id^="DndLiveRegion"]').filter({ hasText: text })).toBeAttached();
|
||||
|
||||
/** A coarse pointer's rail never peeks, a drawer instead: on the tablet it is pinned, for these. */
|
||||
async function pinOnTouch(page: Page, project: string) {
|
||||
if (project !== "ipad") return;
|
||||
await page.route("**/api/me", async (route) => {
|
||||
const res = await route.fetch();
|
||||
const me = (await res.json()) as { preferences?: Record<string, unknown> };
|
||||
await route.fulfill({
|
||||
response: res,
|
||||
json: { ...me, preferences: { ...me.preferences, playlistsCollapsed: false } },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test.describe("acting on the selected rows", { tag: "@playlists" }, () => {
|
||||
test.afterEach(async ({ page }) => {
|
||||
for (const id of made.splice(0)) await page.request.delete(`/api/playlists/${String(id)}`);
|
||||
});
|
||||
|
||||
const box = (page: Page, title: string) =>
|
||||
page.getByRole("checkbox", { name: `Select “${title}”` });
|
||||
|
||||
test("a Shift range, the band's Remove, and its Undo back to the places", async ({
|
||||
page,
|
||||
}, info) => {
|
||||
const { videos, from } = await setUp(page, `band ${info.project.name}`, info.project.name);
|
||||
await box(page, videos[0]!.title).click();
|
||||
await box(page, videos[1]!.title).click({ modifiers: ["Shift"] });
|
||||
await expect(box(page, videos[1]!.title)).toBeChecked();
|
||||
await expect(box(page, videos[2]!.title)).not.toBeChecked();
|
||||
await page.getByRole("button", { name: "Remove", exact: true }).click();
|
||||
await expect(page.locator("tbody tr")).toHaveCount(1);
|
||||
await expect.poll(() => contents(page, from)).toEqual([videos[2]!.id]);
|
||||
await page.getByRole("button", { name: "Undo", exact: true }).last().click();
|
||||
await expect.poll(() => contents(page, from)).toEqual(videos.map((v) => v.id));
|
||||
await expect(page.locator("tbody tr")).toHaveCount(3);
|
||||
});
|
||||
|
||||
test("x ticks the walked row, Esc clears, and Delete takes the selection and goes on", async ({
|
||||
page,
|
||||
}, info) => {
|
||||
const { videos, from } = await setUp(page, `keys ${info.project.name}`, info.project.name);
|
||||
const firstRow = page.locator("tbody tr").first();
|
||||
await page.keyboard.press("j");
|
||||
await expect(firstRow).toBeFocused();
|
||||
await page.keyboard.press("x");
|
||||
await expect(box(page, videos[0]!.title)).toBeChecked();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(box(page, videos[0]!.title)).not.toBeChecked();
|
||||
await page.keyboard.press("x");
|
||||
await page.keyboard.press("j");
|
||||
await page.keyboard.press("x");
|
||||
await page.keyboard.press("Delete");
|
||||
await expect.poll(() => contents(page, from)).toEqual([videos[2]!.id]);
|
||||
await expect(page.locator("tbody tr")).toHaveCount(1);
|
||||
await expect(firstRow).toBeFocused();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("dragging onto a list", { tag: "@playlists" }, () => {
|
||||
test.afterEach(async ({ page }) => {
|
||||
await page.mouse.up();
|
||||
for (const id of made.splice(0)) await page.request.delete(`/api/playlists/${String(id)}`);
|
||||
});
|
||||
|
||||
test("a row leaves for the list it is dropped on, lit up on the way, and Undo brings it back", async ({
|
||||
page,
|
||||
}, info) => {
|
||||
const { videos, from, to, target } = await setUp(
|
||||
page,
|
||||
`drag one ${info.project.name}`,
|
||||
info.project.name,
|
||||
);
|
||||
const grip = page.getByRole("button", { name: `Reorder “${videos[1]!.title}”`, exact: false });
|
||||
await carryToRail(page, grip, target);
|
||||
await expect(target).toHaveClass(/ring-2/);
|
||||
await page.mouse.up();
|
||||
await expect(target).not.toHaveClass(/ring-2/);
|
||||
await expect(page.locator("tbody tr")).toHaveCount(2);
|
||||
// The grip that held the focus has left: the keyboard keeps its place in the list.
|
||||
await expect
|
||||
.poll(() => page.evaluate(() => document.activeElement?.closest("tbody") != null))
|
||||
.toBe(true);
|
||||
await expect.poll(() => contents(page, to)).toEqual([videos[1]!.id]);
|
||||
expect(await contents(page, from)).toEqual([videos[0]!.id, videos[2]!.id]);
|
||||
await page.getByRole("button", { name: "Undo", exact: true }).last().click();
|
||||
await expect.poll(() => contents(page, from)).toEqual(videos.map((v) => v.id));
|
||||
expect(await contents(page, to)).toEqual([]);
|
||||
});
|
||||
|
||||
test("a selected row carries the selected ones, named on the drag image", async ({
|
||||
page,
|
||||
}, info) => {
|
||||
const { videos, from, to, target } = await setUp(
|
||||
page,
|
||||
`drag many ${info.project.name}`,
|
||||
info.project.name,
|
||||
);
|
||||
await page.getByRole("checkbox", { name: videos[0]!.title, exact: false }).click();
|
||||
await page.getByRole("checkbox", { name: videos[2]!.title, exact: false }).click();
|
||||
const grip = page.getByRole("button", { name: `Reorder “${videos[2]!.title}”`, exact: false });
|
||||
await carryToRail(page, grip, target);
|
||||
const image = page.getByText("2 videos", { exact: true });
|
||||
await expect(image).toBeVisible();
|
||||
// Above every layer, by the tooltip's token: the overlay wrapping it takes the level.
|
||||
expect(await image.evaluate((el) => getComputedStyle(el.parentElement!).zIndex)).toBe("100");
|
||||
// Below the pointer, so it leaves the list's name to read.
|
||||
const { y } = await centre(target);
|
||||
expect((await image.boundingBox())!.y).toBeGreaterThan(y);
|
||||
await page.mouse.up();
|
||||
await expect.poll(() => contents(page, to)).toEqual([videos[0]!.id, videos[2]!.id]);
|
||||
expect(await contents(page, from)).toEqual([videos[1]!.id]);
|
||||
await expect(page.getByRole("checkbox", { name: "Select all" })).not.toBeChecked();
|
||||
});
|
||||
|
||||
test("many rows dropped inside the list stay as they were", async ({ page }, info) => {
|
||||
const { videos, from } = await setUp(
|
||||
page,
|
||||
`drag inside ${info.project.name}`,
|
||||
info.project.name,
|
||||
);
|
||||
await page.getByRole("checkbox", { name: videos[0]!.title, exact: false }).click();
|
||||
await page.getByRole("checkbox", { name: videos[1]!.title, exact: false }).click();
|
||||
const grip = page.getByRole("button", { name: `Reorder “${videos[0]!.title}”`, exact: false });
|
||||
await carry(page, grip, await centre(page.locator("tbody tr").nth(2)));
|
||||
await page.mouse.up();
|
||||
await expect(page.locator("tbody tr")).toHaveCount(3);
|
||||
expect(await contents(page, from)).toEqual(videos.map((v) => v.id));
|
||||
});
|
||||
|
||||
test("one row dropped inside the list takes the new place", async ({ page }, info) => {
|
||||
const { videos, from } = await setUp(
|
||||
page,
|
||||
`drag order ${info.project.name}`,
|
||||
info.project.name,
|
||||
);
|
||||
const grip = page.getByRole("button", { name: `Reorder “${videos[0]!.title}”`, exact: false });
|
||||
await carry(page, grip, await centre(page.locator("tbody tr").nth(2)));
|
||||
await said(page, /position 3/);
|
||||
await page.mouse.up();
|
||||
await expect
|
||||
.poll(() => contents(page, from))
|
||||
.toEqual([videos[1]!.id, videos[2]!.id, videos[0]!.id]);
|
||||
});
|
||||
|
||||
test("Escape puts the drag down, with nothing moved and nothing lit", async ({ page }, info) => {
|
||||
const { videos, from, to, target } = await setUp(
|
||||
page,
|
||||
`drag cancel ${info.project.name}`,
|
||||
info.project.name,
|
||||
);
|
||||
// A tick on another row: the Esc is the drag's, and leaves the selection alone.
|
||||
const ticked = page.getByRole("checkbox", { name: `Select “${videos[2]!.title}”` });
|
||||
await ticked.click();
|
||||
const grip = page.getByRole("button", { name: `Reorder “${videos[0]!.title}”`, exact: false });
|
||||
await carryToRail(page, grip, target);
|
||||
await expect(target).toHaveClass(/ring-2/);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(target).not.toHaveClass(/ring-2/);
|
||||
await page.mouse.up();
|
||||
expect(await contents(page, from)).toEqual(videos.map((v) => v.id));
|
||||
expect(await contents(page, to)).toEqual([]);
|
||||
await expect(ticked).toBeChecked();
|
||||
});
|
||||
|
||||
test("a key still reorders a row, alone", async ({ page }, info) => {
|
||||
const { videos, from } = await setUp(page, `drag key ${info.project.name}`, info.project.name);
|
||||
await page.getByRole("checkbox", { name: videos[0]!.title, exact: false }).click();
|
||||
await page.getByRole("checkbox", { name: videos[2]!.title, exact: false }).click();
|
||||
await page.getByRole("button", { name: `Reorder “${videos[0]!.title}”`, exact: false }).focus();
|
||||
await page.keyboard.press("Space");
|
||||
await said(page, /picked up/i);
|
||||
// A person's pause: dnd-kit drops an arrow pressed before it has measured the lifted row, which
|
||||
// nothing on the page announces (11 of 31 runs without it, none of 31 with it).
|
||||
await page.waitForTimeout(300);
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await said(page, /position 2/);
|
||||
await page.keyboard.press("Space");
|
||||
await expect
|
||||
.poll(() => contents(page, from))
|
||||
.toEqual([videos[1]!.id, videos[0]!.id, videos[2]!.id]);
|
||||
});
|
||||
|
||||
test("under a filter a row still goes to another list, and none is reordered", async ({
|
||||
page,
|
||||
}, info) => {
|
||||
const { videos, from, to, target } = await setUp(
|
||||
page,
|
||||
`drag filter ${info.project.name}`,
|
||||
info.project.name,
|
||||
);
|
||||
await page.getByRole("columnheader", { name: "Title" }).getByRole("button").last().click();
|
||||
await page.getByPlaceholder("Title").fill(videos[1]!.title);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.locator("tbody tr")).toHaveCount(1);
|
||||
const grip = page.getByRole("button", {
|
||||
name: `Drag “${videos[1]!.title}” onto a list`,
|
||||
exact: false,
|
||||
});
|
||||
await carryToRail(page, grip, target);
|
||||
await page.mouse.up();
|
||||
await expect.poll(() => contents(page, to)).toEqual([videos[1]!.id]);
|
||||
expect(await contents(page, from)).toEqual([videos[0]!.id, videos[2]!.id]);
|
||||
});
|
||||
|
||||
test("the rail scrolls while the drag holds at its edge", async ({ page }, info) => {
|
||||
const name = `drag scroll ${info.project.name}`;
|
||||
for (let i = 0; i < 12; i++) await newList(page, `${name} ${String(i)}`);
|
||||
await page.setViewportSize({ width: 1280, height: 520 });
|
||||
const { videos } = await setUp(page, name, info.project.name);
|
||||
const grip = page.getByRole("button", { name: `Reorder “${videos[0]!.title}”`, exact: false });
|
||||
const area = page.locator("[data-playlist-drop-area]");
|
||||
await carryToRail(page, grip, area.locator("[data-playlist-drop]").first());
|
||||
const scroller = () =>
|
||||
area.evaluate((el) => {
|
||||
for (let p = el.parentElement; p; p = p.parentElement) {
|
||||
const { overflowY } = getComputedStyle(p);
|
||||
if ((overflowY === "auto" || overflowY === "scroll") && p.scrollHeight > p.clientHeight) {
|
||||
const { left, right, bottom } = p.getBoundingClientRect();
|
||||
return { top: p.scrollTop, x: (left + right) / 2, bottom };
|
||||
}
|
||||
}
|
||||
return { top: -1, x: 0, bottom: 0 };
|
||||
});
|
||||
const before = await scroller();
|
||||
expect(before.top).toBeGreaterThanOrEqual(0);
|
||||
await page.mouse.move(before.x, before.bottom - 8, { steps: 4 });
|
||||
await expect.poll(async () => (await scroller()).top).toBeGreaterThan(before.top);
|
||||
await page.keyboard.press("Escape");
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,19 @@ const METHODS = new Set(["get", "post", "put", "patch", "delete", "head", "fetch
|
||||
const NO_CONNECTION = /\bconnect ETIMEDOUT\b/;
|
||||
const WAITS_MS = [500, 1000, 2000, 4000, 8000];
|
||||
|
||||
/** `attempt` again after each wait while it fails with `transient`; any other failure goes on. */
|
||||
async function tryAgain<R>(attempt: () => Promise<R>, transient: RegExp): Promise<R> {
|
||||
for (let i = 0; ; i++) {
|
||||
try {
|
||||
return await attempt();
|
||||
} catch (e) {
|
||||
const wait = WAITS_MS[i];
|
||||
if (wait === undefined || !transient.test(String((e as Error)?.message))) throw e;
|
||||
await new Promise((r) => setTimeout(r, wait));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** `ctx` with its request methods trying a connect that timed out again (see above). */
|
||||
export function retryConnect<T extends object>(ctx: T): T {
|
||||
return new Proxy(ctx, {
|
||||
@@ -18,17 +31,19 @@ export function retryConnect<T extends object>(ctx: T): T {
|
||||
const v: unknown = Reflect.get(target, key, target);
|
||||
if (typeof v !== "function") return v;
|
||||
if (typeof key !== "string" || !METHODS.has(key)) return v.bind(target);
|
||||
return async (...args: unknown[]) => {
|
||||
for (let i = 0; ; i++) {
|
||||
try {
|
||||
return await v.apply(target, args);
|
||||
} catch (e) {
|
||||
const wait = WAITS_MS[i];
|
||||
if (wait === undefined || !NO_CONNECTION.test(String((e as Error)?.message))) throw e;
|
||||
await new Promise((r) => setTimeout(r, wait));
|
||||
}
|
||||
}
|
||||
};
|
||||
return (...args: unknown[]) =>
|
||||
tryAgain(() => Promise.resolve(v.apply(target, args)), NO_CONNECTION);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// A page load has a failure of its own on the same machine: `net::ERR_NO_BUFFER_SPACE`, the socket
|
||||
// call refused for the moment. It stopped a release's e2e at its first page (0.116.3, with nothing
|
||||
// else running; 0.107.3 aborted on it too), and the unchanged rerun passed. A browser does not try
|
||||
// a main document again by itself, and the request never left, so this does. The suite's every page
|
||||
// load goes through here (`e2eRetryConnect.test.ts`).
|
||||
const NO_BUFFER = /\bERR_NO_BUFFER_SPACE\b/;
|
||||
|
||||
export function gotoRetrying<R>(page: { goto(url: string): Promise<R> }, url: string): Promise<R> {
|
||||
return tryAgain(() => page.goto(url), NO_BUFFER);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { test, type Page } from "@playwright/test";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { retryConnect } from "./retryConnect";
|
||||
import { gotoRetrying, retryConnect } from "./retryConnect";
|
||||
|
||||
/**
|
||||
* The speed baseline: numbers, not assertions — read by `scripts/audit_metrics.py --speed`, which
|
||||
@@ -78,7 +78,7 @@ test("speed baseline", async ({ browser, page: page0 }) => {
|
||||
for (let i = 0; i < RUNS; i++) {
|
||||
const ctx = await browser.newContext();
|
||||
const page = await ctx.newPage();
|
||||
await page.goto("/");
|
||||
await gotoRetrying(page, "/");
|
||||
// Timed inside the page, every frame: an `expect` would read the clock on its own retry
|
||||
// schedule (100 ms … 1 s steps), not when the card appeared.
|
||||
const at = await page.waitForFunction(
|
||||
@@ -108,7 +108,7 @@ test("speed baseline", async ({ browser, page: page0 }) => {
|
||||
for (let i = 0; i < RUNS; i++) {
|
||||
const ctx = await browser.newContext({ storageState: { cookies: [], origins: [] } });
|
||||
const page = await ctx.newPage();
|
||||
await page.goto(`/watch/${token}`);
|
||||
await gotoRetrying(page, `/watch/${token}`);
|
||||
await page.waitForFunction(() => document.querySelector("video, audio"), null, {
|
||||
polling: "raf",
|
||||
timeout: 30_000,
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { test, expect, type Page } from "@playwright/test";
|
||||
import { openApp } from "./helpers";
|
||||
import { gotoRetrying } from "./retryConnect";
|
||||
|
||||
// A request can be lost on the way on a loaded machine or a poor line. A lost stylesheet leaves the
|
||||
// whole page unstyled, and every test that finds its elements by testid still passes on it: only an
|
||||
// axe run ever noticed (8 controls under the target size). So this looks at the styles themselves.
|
||||
|
||||
/** Lose the first request for every stylesheet of the page; the ones after it go through. */
|
||||
async function loseEachStylesheetOnce(page: Page): Promise<string[]> {
|
||||
const lost: string[] = [];
|
||||
await page.route(/\/assets\/[^/]+\.css/, async (route) => {
|
||||
const url = route.request().url();
|
||||
if (lost.includes(url)) return route.continue();
|
||||
lost.push(url);
|
||||
return route.abort("failed");
|
||||
});
|
||||
return lost;
|
||||
}
|
||||
|
||||
/** Every stylesheet link of the page holds rules (a lost one still has a `sheet`, whose rules throw
|
||||
* on reading), and the page's own tokens are in force: `--bg` comes from the stylesheet alone, while
|
||||
* `--font-scale` would prove nothing, the app also sets it from script. */
|
||||
async function expectStyled(page: Page): Promise<void> {
|
||||
await expect
|
||||
.poll(() =>
|
||||
page.evaluate(() => {
|
||||
const hasRules = (l: HTMLLinkElement) => {
|
||||
try {
|
||||
return (l.sheet?.cssRules.length ?? 0) > 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
const links = [...document.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]')];
|
||||
const root = getComputedStyle(document.documentElement);
|
||||
return {
|
||||
links: links.length > 0,
|
||||
rules: links.every(hasRules),
|
||||
tokens: root.getPropertyValue("--bg").trim() !== "",
|
||||
};
|
||||
}),
|
||||
)
|
||||
.toEqual({ links: true, rules: true, tokens: true });
|
||||
}
|
||||
|
||||
test("the app gets back a stylesheet lost on the way", async ({ page }) => {
|
||||
const lost = await loseEachStylesheetOnce(page);
|
||||
await openApp(page);
|
||||
expect(lost.length).toBeGreaterThan(0);
|
||||
await expectStyled(page);
|
||||
});
|
||||
|
||||
test("a public /watch link gets back a stylesheet lost on the way", async ({ page }) => {
|
||||
const lost = await loseEachStylesheetOnce(page);
|
||||
// No such link: the page says so, and it is the same entry with the same stylesheet.
|
||||
await gotoRetrying(page, "/watch/no-such-token");
|
||||
await expect(page.locator("#root")).not.toBeEmpty();
|
||||
expect(lost.length).toBeGreaterThan(0);
|
||||
await expectStyled(page);
|
||||
});
|
||||
@@ -1,14 +1,16 @@
|
||||
# Siftlode is mostly a private, login-gated app; only the public landing and legal
|
||||
# pages are worth indexing. Allow crawling but keep bots out of the API surface.
|
||||
# Share links (/watch/) are unguessable capability URLs: kept out of search indexes,
|
||||
# Share links (/watch/, /file/, /folder/) are unguessable capability URLs: kept out of search indexes,
|
||||
# but link-preview crawlers are allowed below so shared links unfurl in chat apps.
|
||||
User-agent: *
|
||||
Allow: /
|
||||
Disallow: /api/
|
||||
Disallow: /auth/
|
||||
Disallow: /watch/
|
||||
Disallow: /file/
|
||||
Disallow: /folder/
|
||||
|
||||
# Link-preview / unfurl bots — allowed to fetch /watch/ so shared links render a rich
|
||||
# Link-preview / unfurl bots — allowed to fetch share links so shared links render a rich
|
||||
# card (title/channel/thumbnail). They don't build a search index, so this doesn't
|
||||
# expose share links to search engines.
|
||||
User-agent: facebookexternalhit
|
||||
|
||||
@@ -9,7 +9,13 @@ import { act, render, screen, fireEvent, cleanup } from "@testing-library/react"
|
||||
|
||||
vi.mock("react-i18next", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react-i18next")>();
|
||||
return { ...actual, useTranslation: () => ({ t: (k: string) => k }) };
|
||||
return {
|
||||
...actual,
|
||||
useTranslation: () => ({
|
||||
t: (k: string, o?: { action?: string; title?: string }) =>
|
||||
o?.title ? `${o.action}: ${o.title}` : k,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
import { Carousel } from "./Carousel";
|
||||
@@ -54,7 +60,10 @@ describe("Carousel", () => {
|
||||
);
|
||||
expect(screen.getByText("card-a")).toBeTruthy();
|
||||
expect(screen.getByRole("heading", { name: "Recently added" })).toBeTruthy();
|
||||
fireEvent.click(screen.getByRole("button", { name: "common.seeAll" }));
|
||||
// Named with its rail, the visible words first: a page of rails has a See all on each.
|
||||
const seeAll = screen.getByRole("button", { name: "common.seeAll: Recently added" });
|
||||
expect(seeAll.textContent).toBe("common.seeAll");
|
||||
fireEvent.click(seeAll);
|
||||
expect(onSeeAll).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
|
||||
@@ -109,7 +109,21 @@ export function Carousel({
|
||||
<div className="mb-3 flex items-baseline gap-2">
|
||||
<h2 className="text-sm font-semibold">{title}</h2>
|
||||
{onSeeAll && (
|
||||
<Button variant="link-muted" onClick={onSeeAll} className="ml-auto gap-0.5 text-xs">
|
||||
<Button
|
||||
variant="link-muted"
|
||||
onClick={onSeeAll}
|
||||
// Named with its rail: a page of rails has a See all on each, and a screen reader's
|
||||
// list of buttons (or a voice command) must tell them apart. The visible words lead.
|
||||
aria-label={
|
||||
label
|
||||
? t("common.seeAllOf", {
|
||||
action: seeAllLabel ?? t("common.seeAll"),
|
||||
title: label,
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
className="ml-auto gap-0.5 text-xs"
|
||||
>
|
||||
{seeAllLabel ?? t("common.seeAll")}
|
||||
<ChevronRight className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import clsx from "clsx";
|
||||
import type { InputHTMLAttributes, ReactNode, Ref } from "react";
|
||||
import type { InputHTMLAttributes, ReactNode, RefObject } from "react";
|
||||
|
||||
// A6 (docs/DESIGN.md): checkbox, slider and colour well are the BROWSER's controls, tinted
|
||||
// with the chosen colour (the accent; the media amber on the player chrome) — keyboard, screen
|
||||
@@ -10,18 +10,30 @@ import type { InputHTMLAttributes, ReactNode, Ref } from "react";
|
||||
|
||||
type Native = Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "onChange">;
|
||||
|
||||
/** The bare checkbox: inside your own `<label>`, or with an `aria-label`. Prefer `CheckRow`. */
|
||||
/** The bare checkbox: inside your own `<label>`, or with an `aria-label`. Prefer `CheckRow`.
|
||||
* `onChange` also says whether Shift was held, for a range. `mixed` is the third state, some of what
|
||||
* it covers: the DOM has no attribute for it, only the property. */
|
||||
export function Checkbox({
|
||||
onChange,
|
||||
className,
|
||||
ref,
|
||||
mixed = false,
|
||||
...rest
|
||||
}: Native & { onChange?: (checked: boolean) => void; ref?: Ref<HTMLInputElement> }) {
|
||||
}: Native & {
|
||||
onChange?: (checked: boolean, shift: boolean) => void;
|
||||
ref?: RefObject<HTMLInputElement | null>;
|
||||
mixed?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<input
|
||||
ref={ref}
|
||||
ref={(el) => {
|
||||
if (ref) ref.current = el;
|
||||
if (el) el.indeterminate = mixed;
|
||||
}}
|
||||
type="checkbox"
|
||||
onChange={(e) => onChange?.(e.target.checked)}
|
||||
onChange={(e) =>
|
||||
onChange?.(e.target.checked, e.nativeEvent instanceof MouseEvent && e.nativeEvent.shiftKey)
|
||||
}
|
||||
className={clsx(
|
||||
"size-4 shrink-0 cursor-pointer accent-chosen disabled:cursor-not-allowed",
|
||||
className,
|
||||
@@ -54,7 +66,7 @@ export function CheckRow({
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<Checkbox checked={checked} onChange={onChange} disabled={disabled} />
|
||||
<Checkbox checked={checked} onChange={(on) => onChange(on)} disabled={disabled} />
|
||||
{children}
|
||||
</label>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useRef, type ReactNode } from "react";
|
||||
import { useListNav } from "../../lib/listNav";
|
||||
import { useListNav, type NavSelection } from "../../lib/listNav";
|
||||
|
||||
// A plain list of cards or rows the keyboard can walk — `j`/`k`, the arrows, Enter (lib/listNav) — for
|
||||
// the lists that mount every item (the Plex title, season and episode grids, the download lists, a
|
||||
@@ -11,16 +11,19 @@ export default function NavGrid({
|
||||
as: Tag = "div",
|
||||
className,
|
||||
onDelete,
|
||||
selection,
|
||||
children,
|
||||
}: {
|
||||
as?: "div" | "tbody";
|
||||
className?: string;
|
||||
/** The Delete key takes the focused item out (lib/listNav): its index among the items. */
|
||||
onDelete?: (index: number) => void;
|
||||
/** `x` selects the focused item, Esc clears (lib/listNav). */
|
||||
selection?: NavSelection;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement & HTMLTableSectionElement>(null);
|
||||
useListNav(ref, { enabled: true, onDelete });
|
||||
useListNav(ref, { enabled: true, onDelete, selection });
|
||||
return (
|
||||
<Tag ref={ref} className={className}>
|
||||
{children}
|
||||
|
||||
@@ -35,13 +35,13 @@ Counter-examples, deliberately NOT here: `PosterTile` (knows about Plex montage
|
||||
|
||||
## What lives here
|
||||
|
||||
| area | components |
|
||||
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| overlays & anchoring | `AnchoredPopover` + `anchoredPopoverHooks` (the popover engine: arrows, typeahead, Escape, anchor-flip), `ActionMenu`, `MembershipMenu` (the body of a "which sets is it in" menu: checkbox rows + a field naming a new set), `ContextMenu` + `useContextMenu` (the SAME menu, opened by right-click / long-press / Shift+F10 / a row's `MoreButton` "…" via `buttonProps`; `anchor` for a panel a row opens; `PageMenu` for a page's background menu), `Modal` (+ `ModalFooter`; `initialFocus` by purpose, C4), `Overlay`, `SidePanel`, `Tooltip`, `Toaster` (+ `toastLevels`, `overlayOrder`; `lib/toastDock` docks one control under the stack, in every host), `CommandPalette`, `KeyboardHelp`, `ConfirmProvider` + `confirmContext` (`useConfirm` / `useChoice`: the app's promise-based confirm, mounted once at the root; a decision with more than two outcomes is one `useChoice`, never two chained confirms), `dialogFocus` (the focus half of the dialog contract: `Modal`'s, and the wizard's own shell), `menuGroups` (one menu from its groups, a rule only between non-empty ones), `pageMenuSlot` + `pageMenuItems` (a page's background menu, mirroring its own toolbar) |
|
||||
| actions & inputs | `Button`, `IconButton`, `Pressable` (`selectable` when its text is a title or a name), `Chip` + `chipStyles`, `DragHandle` + `OrderButtons` / `useOrderItems` (the non-drag reorder, WCAG 2.5.7) (one per button family, docs/DESIGN.md; a raw `<button>` or a bare `FocusSafeButton` outside the control primitives — eslint `BUTTON_PRIMITIVES` — is a lint error), `Input` + `fieldStyles`, `RenameField` (a name typed in place of the name: Enter or blur saves, Escape cancels; the caller hands the keyboard back), `DropZone` (the dashed place a file upload starts from: a drop, or a click that opens the file dialog), `Meter` (how full something is against a limit — one danger line for every place showing the same measure), `TimecodeField` + `useTimecodeField` / `TimecodeError` (a cut's time typed in: the draft, held by the caller, until Enter or blur takes it, then the value as it landed; unreadable stays once offered, marked invalid, and the caller places the line saying how to type one in its flow, outside a label; a draft goes when the value moves under it), `NativeControls`, `MenuCheck` (the drawn check of a menu row or a whole-row checkbox button; its tick is the `chosen` colour, which `media-marks` turns amber on the player chrome), `mediaChrome` (`MEDIA_CHOSEN`, a chosen tab or toggle on the chrome), `SelectTrigger` (the field family; a raw `<input>` is a lint error), `useReturnFocus`, `unavailable` (an off control's props: with a reason it stays focusable, `aria-disabled` and the reason in its tooltip; without one, `disabled`), `surfaces` (the B5 glass roles; a bare glass class is a lint error), `Badge` (a static label), `LinkButton` / `IconLink` (a link wearing the button face) over `buttonStyles`, `Skeleton` (B8 first loads, through `LoadingState shape`), `NavRail` (B7; `NavRailGroup` folds a set of rare pages into one row with a panel), `form`, `DraftSaveBar`, `Combobox`, `FilterSelect`, `SegmentedToggle`, `SortControl`, `ColumnSortControl`, `PriorityStepper`, `UndoToolbar`, `ViewSwitcher` (a list's display modes behind one toolbar icon), `copyItems` (`useCopyItems`: the "Copy title" / "Copy link" rows every object's menu ends with) + `useCopyFeedback` (a Copy button's "Copied" moment), `MatchToggle` (a multi-value filter's any/all switch), `LanguageSwitcher` (presentational: the caller decides what a change does), `sortableA11y` (what a screen reader hears during a keyboard reorder) |
|
||||
| data display | `DataTable` (+ `progressiveRows`: a long page mounts in steps; `rowOpen`: a press on the row runs its default action), `tableHeader` + `tableAlign`, `HiddenFilterCue` (names a filter whose column is off screen), `Pager` + `pagerContent`, `VirtualGrid` + `gridColumns` (the column/width maths, incl. the ultrawide `maxCols` cap), `readAhead`, `Carousel`, `MediaCard` + `mediaCardStyles` (the one media card, docs/DESIGN.md "Media card") + `MediaPreview` / `useMediaPreview` (its mouse-rest preview), `NavGrid` (a plain grid, list or table body the keyboard walks — `DataTable`, `VirtualGrid` and `Carousel` take `keyboardNav`), `RemoteImage` (every network picture: no Referer, retries past the negative cache, a fallback instead of the broken-image mark — a bare `<img>` is linted out), `Avatar`, `CountBadge`, `ItemCount`, `FilterChipGroup`, `RelativeTime` ("3d ago" with the exact minute on hover, docs/DESIGN.md "Copy"), `ClampedText` (a long text clamped to a few lines; More / Less only when it is cut), `StatTiles` + `StatTile` / `StatBars` (number tiles, a breakdown as horizontal bars), `RangeTrack` + `trackPosition` + `RulerTicks` (a time track over a window of a media item: regions, slider ends the arrows step, a playhead, a background slot — the editor's cuts, the players' clip panel), `CropFrame` (a crop frame over a picture, on the picture and not its bars: drag, edges, corners, the arrows; the editor's crop, the players' clip crop), `reveal` (a card's hover chrome: hover or keyboard focus on a mouse, never on touch) |
|
||||
| page & panel structure | `PageShell` + `pageToolbarSlot` + `pageHeaderSlot` (`PageHeader`: a page fills the floating header) + `pageHeading`, `PageScroller`, `Headings` (`PageHeading`, `SectionLabel`), `SkipLink` + `landmarks`, `FilterFold` (B4), `scrollFold` (`useScrollFold`: a fixed header that folds once its content scrolls), `PanelGroup`, `PanelGroups`, `Tabs` + `tabPanel`, `BackToTop` + `backToTopState` (PageScroller keeps the page's end clear of it), `FilterRail` (the filter-rail shell a rail fills with its groups: title bar, customize, reset), `stickyTop` (a sticky header at the scroller's top turns its top fade off) |
|
||||
| state & messaging | `QueryState`, `Banner`, `InlineNotice`, `CrashBoundary` |
|
||||
| area | components |
|
||||
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| overlays & anchoring | `AnchoredPopover` + `anchoredPopoverHooks` (the popover engine: arrows, typeahead, Escape, anchor-flip), `ActionMenu`, `MembershipMenu` (the body of a "which sets is it in" menu: checkbox rows + a field naming a new set), `ContextMenu` + `useContextMenu` (the SAME menu, opened by right-click / long-press / Shift+F10 / a row's `MoreButton` "…" via `buttonProps`; `anchor` for a panel a row opens; `PageMenu` for a page's background menu), `Modal` (+ `ModalFooter`; `initialFocus` by purpose, C4), `Overlay`, `SidePanel`, `Tooltip`, `Toaster` (+ `toastLevels`, `overlayOrder`; `lib/toastDock` docks one control under the stack, in every host), `CommandPalette`, `KeyboardHelp`, `ConfirmProvider` + `confirmContext` (`useConfirm` / `useChoice`: the app's promise-based confirm, mounted once at the root; a decision with more than two outcomes is one `useChoice`, never two chained confirms), `dialogFocus` (the focus half of the dialog contract: `Modal`'s, and the wizard's own shell), `menuGroups` (one menu from its groups, a rule only between non-empty ones), `pageMenuSlot` + `pageMenuItems` (a page's background menu, mirroring its own toolbar) |
|
||||
| actions & inputs | `Button`, `IconButton`, `Pressable` (`selectable` when its text is a title or a name), `Chip` + `chipStyles`, `RowSelectBox` (a table row's selecting box, Shift says a range), `DragHandle` + `OrderButtons` / `useOrderItems` (the non-drag reorder, WCAG 2.5.7) (one per button family, docs/DESIGN.md; a raw `<button>` or a bare `FocusSafeButton` outside the control primitives — eslint `BUTTON_PRIMITIVES` — is a lint error), `Input` + `fieldStyles`, `RenameField` (a name typed in place of the name: Enter or blur saves, Escape cancels; the caller hands the keyboard back), `DropZone` (the dashed place a file upload starts from: a drop, or a click that opens the file dialog), `Meter` (how full something is against a limit — one danger line for every place showing the same measure), `TimecodeField` + `useTimecodeField` / `TimecodeError` (a cut's time typed in: the draft, held by the caller, until Enter or blur takes it, then the value as it landed; unreadable stays once offered, marked invalid, and the caller places the line saying how to type one in its flow, outside a label; a draft goes when the value moves under it), `NativeControls`, `MenuCheck` (the drawn check of a menu row or a whole-row checkbox button; its tick is the `chosen` colour, which `media-marks` turns amber on the player chrome), `mediaChrome` (`MEDIA_CHOSEN`, a chosen tab or toggle on the chrome), `SelectTrigger` (the field family; a raw `<input>` is a lint error), `useReturnFocus`, `unavailable` (an off control's props: with a reason it stays focusable, `aria-disabled` and the reason in its tooltip; without one, `disabled`), `surfaces` (the B5 glass roles; a bare glass class is a lint error), `Badge` (a static label), `LinkButton` / `IconLink` (a link wearing the button face) over `buttonStyles`, `Skeleton` (B8 first loads, through `LoadingState shape`), `NavRail` (B7; `NavRailGroup` folds a set of rare pages into one row with a panel), `form`, `DraftSaveBar`, `Combobox`, `FilterSelect`, `SegmentedToggle`, `SortControl`, `ColumnSortControl`, `PriorityStepper`, `UndoToolbar`, `ViewSwitcher` (a list's display modes behind one toolbar icon), `copyItems` (`useCopyItems`: the "Copy title" / "Copy link" rows every object's menu ends with) + `useCopyFeedback` (a Copy button's "Copied" moment), `MatchToggle` (a multi-value filter's any/all switch), `LanguageSwitcher` (presentational: the caller decides what a change does), `sortableA11y` (what a screen reader hears during a keyboard reorder) |
|
||||
| data display | `DataTable` (+ `progressiveRows`: a long page mounts in steps; `rowOpen`: a press on the row runs its default action), `tableHeader` + `tableAlign`, `HiddenFilterCue` (names a filter whose column is off screen), `Pager` + `pagerContent`, `VirtualGrid` + `gridColumns` (the column/width maths, incl. the ultrawide `maxCols` cap), `readAhead`, `Carousel`, `MediaCard` + `mediaCardStyles` (the one media card, docs/DESIGN.md "Media card") + `MediaPreview` / `useMediaPreview` (its mouse-rest preview), `NavGrid` (a plain grid, list or table body the keyboard walks — `DataTable`, `VirtualGrid` and `Carousel` take `keyboardNav`), `RemoteImage` (every network picture: no Referer, retries past the negative cache, a fallback instead of the broken-image mark — a bare `<img>` is linted out), `Avatar`, `CountBadge`, `ItemCount`, `FilterChipGroup`, `RelativeTime` ("3d ago" with the exact minute on hover, docs/DESIGN.md "Copy"), `ClampedText` (a long text clamped to a few lines; More / Less only when it is cut), `StatTiles` + `StatTile` / `StatBars` (number tiles, a breakdown as horizontal bars), `RangeTrack` + `trackPosition` + `RulerTicks` (a time track over a window of a media item: regions, slider ends the arrows step, a playhead, a background slot — the editor's cuts, the players' clip panel), `CropFrame` (a crop frame over a picture, on the picture and not its bars: drag, edges, corners, the arrows; the editor's crop, the players' clip crop), `reveal` (a card's hover chrome: hover or keyboard focus on a mouse, never on touch) |
|
||||
| page & panel structure | `PageShell` + `pageToolbarSlot` + `pageHeaderSlot` (`PageHeader`: a page fills the floating header) + `pageHeading`, `PageScroller`, `Headings` (`PageHeading`, `SectionLabel`), `SkipLink` + `landmarks`, `FilterFold` (B4), `scrollFold` (`useScrollFold`: a fixed header that folds once its content scrolls), `PanelGroup`, `PanelGroups`, `Tabs` + `tabPanel`, `BackToTop` + `backToTopState` (PageScroller keeps the page's end clear of it), `FilterRail` (the filter-rail shell a rail fills with its groups: title bar, customize, reset), `stickyTop` (a sticky header at the scroller's top turns its top fade off) |
|
||||
| state & messaging | `QueryState`, `Banner`, `InlineNotice`, `CrashBoundary` |
|
||||
|
||||
## The size contract (E10 S1c)
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { RefObject } from "react";
|
||||
import { Checkbox } from "./NativeControls";
|
||||
|
||||
/** A table row's selecting box, and the same box over the column for all the rows. The whole cell is
|
||||
* the target, 44 on touch: the label starts at the cell's edge, past its padding, so it ends where
|
||||
* the next cell's control starts instead of lying under it. `onToggle` says whether Shift was held. */
|
||||
export function RowSelectBox({
|
||||
label,
|
||||
checked,
|
||||
mixed,
|
||||
title,
|
||||
onToggle,
|
||||
ref,
|
||||
}: {
|
||||
ref?: RefObject<HTMLInputElement | null>;
|
||||
label: string;
|
||||
checked: boolean;
|
||||
mixed?: boolean;
|
||||
title?: string;
|
||||
onToggle: (shift: boolean) => void;
|
||||
}) {
|
||||
return (
|
||||
<label
|
||||
title={title}
|
||||
// Shift+press would otherwise extend the page's text selection over the rows between.
|
||||
onMouseDown={(e) => {
|
||||
if (e.shiftKey) e.preventDefault();
|
||||
}}
|
||||
className="-ml-2 grid min-h-6 w-9 cursor-pointer place-items-center touch-target"
|
||||
>
|
||||
<Checkbox
|
||||
ref={ref}
|
||||
aria-label={label}
|
||||
checked={checked}
|
||||
mixed={mixed}
|
||||
onChange={(_, shift) => onToggle(shift)}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
@@ -232,7 +232,9 @@ export function ColumnHead<T>({
|
||||
two of them per playlist table, whose grip and actions headers are empty. */}
|
||||
{/* min-w-6 as well as min-h-6: a short header ("Ki", Hungarian "Who") was a 12px
|
||||
target beside its funnel, under the 24px floor. */}
|
||||
{col.sortable ? (
|
||||
{col.headerCell ? (
|
||||
col.headerCell
|
||||
) : col.sortable ? (
|
||||
<Pressable
|
||||
onClick={() => onToggleSort(col.key)}
|
||||
className="inline-flex min-h-6 min-w-6 items-center gap-1 hover:text-fg cursor-pointer touch-target"
|
||||
|
||||
@@ -1,4 +1,53 @@
|
||||
[
|
||||
{
|
||||
"version": "0.117.0",
|
||||
"date": "2026-11-06",
|
||||
"new": [
|
||||
"A share link's address now says what it opens: /file/ for a file, /folder/ for a folder, /watch/ for a video. Links you already sent keep working.",
|
||||
"The upload dialog shows which folder the file goes to, and you can pick another one or make a new folder there. Opening Share copies a link at once.",
|
||||
"The Channels tag chips show how many followed channels each holds. Continue watching in Plex has a See all, and a Plex item's Info shows the file size."
|
||||
],
|
||||
"fixed": [
|
||||
"An expired share link is marked as expired and is never copied. A crop of a video with wide pixels keeps exactly what its frame showed.",
|
||||
"A Plex auto-skip waits 3 seconds into the marker before its countdown starts."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.116.3",
|
||||
"date": "2026-11-04",
|
||||
"new": [],
|
||||
"fixed": [
|
||||
"If a stylesheet is lost on the way, the app now asks for it again, so a poor connection no longer leaves the page unstyled until a reload."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.116.2",
|
||||
"date": "2026-11-03",
|
||||
"new": [],
|
||||
"fixed": [
|
||||
"A Plex video paused or muted in a background tab no longer loses its session after a minute, and if a session is lost anyway, playback comes back at once instead of after half a minute."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.116.1",
|
||||
"date": "2026-11-03",
|
||||
"new": [],
|
||||
"fixed": [
|
||||
"A playlist now shows the order the server holds after a revert to YouTube, a sync or a change on another device, and the next drag no longer brings back the old one.",
|
||||
"An Undo on a removed or moved row puts it back in the right place while another change is still saving."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.116.0",
|
||||
"date": "2026-11-03",
|
||||
"new": [
|
||||
"In a playlist, tick rows with their box, Shift+click or x, then move or remove them together. An Undo puts them back at their places, and a single row's move has one too.",
|
||||
"Drag rows onto another list in the rail: one row, or all the selected ones, also under a sort or a filter."
|
||||
],
|
||||
"fixed": [
|
||||
"Removing a video from inside the player no longer loses your place in the list when the player closes."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.115.0",
|
||||
"date": "2026-11-01",
|
||||
|
||||
@@ -1,4 +1,53 @@
|
||||
[
|
||||
{
|
||||
"version": "0.117.0",
|
||||
"date": "2026-11-06",
|
||||
"new": [
|
||||
"A megosztási link címe most megmondja, mit nyit meg: /file/ egy fájlt, /folder/ egy mappát, /watch/ egy videót. A már elküldött linkek továbbra is működnek.",
|
||||
"A feltöltési ablak mutatja, melyik mappába kerül a fájl, és ott választhatsz másikat vagy új mappát hozhatsz létre. A Megosztás megnyitáskor rögtön kimásol egy linket.",
|
||||
"A Csatornák címkéi mutatják, hány követett csatorna tartozik hozzájuk. A Plex Folytatás sávjának is van Összes gombja, és az elem adatlapja mutatja a fájl méretét."
|
||||
],
|
||||
"fixed": [
|
||||
"A lejárt megosztási link lejártként látszik, és sosem kerül a vágólapra. A széles képpontú videó vágása pontosan azt tartja meg, amit a keret mutatott.",
|
||||
"A Plex automatikus átugrása a marker után 3 másodpercet vár, mielőtt a visszaszámlálás indul."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.116.3",
|
||||
"date": "2026-11-04",
|
||||
"new": [],
|
||||
"fixed": [
|
||||
"Ha egy stíluslap elvész útközben, az app most újra lekéri, így a rossz kapcsolat miatt nem marad formázatlan az oldal újratöltésig."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.116.2",
|
||||
"date": "2026-11-03",
|
||||
"new": [],
|
||||
"fixed": [
|
||||
"A háttérfülön szüneteltetett vagy némított Plex-videó már nem veszíti el a munkamenetét egy perc után, és ha mégis elveszne, a lejátszás azonnal visszatér, nem fél perc múlva."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.116.1",
|
||||
"date": "2026-11-03",
|
||||
"new": [],
|
||||
"fixed": [
|
||||
"A lista most a szerveren lévő sorrendet mutatja a YouTube-ra visszaállítás, a szinkron vagy egy másik eszközön végzett módosítás után, és a következő húzás már nem hozza vissza a régit.",
|
||||
"Az eltávolított vagy áthelyezett sor Visszavonása akkor is jó helyre teszi vissza a sort, ha közben egy másik módosítás még mentés alatt áll."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.116.0",
|
||||
"date": "2026-11-03",
|
||||
"new": [
|
||||
"A listákban a sorok kijelölhetők a jelölőnégyzetükkel, Shift+kattintással vagy az x billentyűvel, és együtt áthelyezhetők vagy eltávolíthatók. A Visszavonás a helyükre teszi őket, és egyetlen sor áthelyezésénél is ott van.",
|
||||
"A sorok ráhúzhatók a sáv egy másik listájára: egy sor vagy az összes kijelölt, rendezés és szűrés mellett is."
|
||||
],
|
||||
"fixed": [
|
||||
"Ha a lejátszóból távolítasz el egy videót, a lejátszó bezárása után megmarad a helyed a listában."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.115.0",
|
||||
"date": "2026-11-01",
|
||||
|
||||
@@ -45,6 +45,7 @@ const tag = (id: number, name: string): Tag => ({
|
||||
category: "other",
|
||||
system: false,
|
||||
channel_count: 0,
|
||||
subscribed_count: 0,
|
||||
});
|
||||
const docu = tag(1, "docu");
|
||||
const history = tag(2, "history");
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// @vitest-environment jsdom
|
||||
//
|
||||
// A tag's row in the manager says how many channels it is on, beside a hover list of them, over the
|
||||
// Channels page whose chip names the same tag with a number: all three count the same channels —
|
||||
// the followed ones the Subscriptions tab shows, hidden ones left out. Every link (the number a
|
||||
// delete removes) is only the delete's confirm.
|
||||
import { describe, it, expect, vi, beforeAll, afterEach } from "vitest";
|
||||
import { render, screen, cleanup, fireEvent } 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: (key: string, o?: { count?: number }) => (o?.count != null ? `${key}:${o.count}` : key),
|
||||
i18n: { language: "en" },
|
||||
}),
|
||||
}));
|
||||
|
||||
import TagManager from "./TagManager";
|
||||
import { api, type ManagedChannel, type Tag } from "../../lib/api";
|
||||
|
||||
beforeAll(() => {
|
||||
class Stub {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
takeRecords() {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
globalThis.ResizeObserver ??= Stub as unknown as typeof ResizeObserver;
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const tag = {
|
||||
id: 5,
|
||||
name: "Music",
|
||||
color: null,
|
||||
category: "other",
|
||||
system: false,
|
||||
channel_count: 4,
|
||||
subscribed_count: 2,
|
||||
} as Tag;
|
||||
const ch = (id: string, hidden: boolean) =>
|
||||
({ id, title: id, hidden, tag_ids: [5] }) as unknown as ManagedChannel;
|
||||
|
||||
describe("TagManager · a tag's count", () => {
|
||||
it("counts the followed channels the Subscriptions tab shows, not every link", async () => {
|
||||
vi.spyOn(api, "tags").mockResolvedValue([tag]);
|
||||
vi.spyOn(api, "channels").mockResolvedValue([
|
||||
ch("UCa", false),
|
||||
ch("UCb", false),
|
||||
ch("UChid", true),
|
||||
]);
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<TagManager onClose={() => {}} onFocusChannel={() => {}} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
expect(await screen.findByText("tagManager.channels:2")).toBeTruthy();
|
||||
expect(screen.queryByText("tagManager.channels:4")).toBeNull();
|
||||
fireEvent.mouseEnter(screen.getByText("tagManager.channels:2"));
|
||||
expect(await screen.findByText("UCa")).toBeTruthy();
|
||||
expect(screen.queryByText("UChid")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -71,7 +71,7 @@ function TagRow({
|
||||
: ""
|
||||
}`}
|
||||
>
|
||||
{t("tagManager.channels", { count: tag.channel_count })}
|
||||
{t("tagManager.channels", { count: tag.subscribed_count })}
|
||||
</span>
|
||||
<IconButton variant="danger" onClick={onDelete} label={t("tagManager.delete")}>
|
||||
<Trash2 />
|
||||
@@ -119,7 +119,7 @@ export default function TagManager({
|
||||
const userTags = (tagsQuery.data ?? []).filter((tg) => !tg.system);
|
||||
const channelsForTag = (tagId: number) =>
|
||||
(channelsQuery.data ?? [])
|
||||
.filter((c) => c.tag_ids.includes(tagId))
|
||||
.filter((c) => !c.hidden && c.tag_ids.includes(tagId))
|
||||
.map((c) => ({ id: c.id, title: c.title ?? c.id }));
|
||||
|
||||
const invalidate = () => {
|
||||
|
||||
@@ -21,7 +21,7 @@ const ALLOWED = new Set([
|
||||
// the built-in Watch later list's items ARE the mark. videoWrites makes those writes and the mark
|
||||
// together; a direct api call skips the mark.
|
||||
const WRITES =
|
||||
/\bapi\s*\.\s*(setState|clearProgress|watchLaterAdd|watchLaterRemove|addToPlaylist|removeFromPlaylist|moveToPlaylist)\b/;
|
||||
/\bapi\s*\.\s*(setState|clearProgress|watchLaterAdd|watchLaterRemove|addToPlaylist|removeFromPlaylist|removeManyFromPlaylist|restoreToPlaylist|moveManyToPlaylist|undoPlaylistMove)\b/;
|
||||
|
||||
describe("a video's state, Watch-later and playlist-item writes", () => {
|
||||
it("go through features/video/videoWrites, never the api directly", () => {
|
||||
@@ -38,7 +38,8 @@ describe("a video's state, Watch-later and playlist-item writes", () => {
|
||||
it("catches a write named without being called on the spot, and a playlist item's", () => {
|
||||
expect(WRITES.test("(saved ? api.watchLaterAdd : api.watchLaterRemove)(id)")).toBe(true);
|
||||
expect(WRITES.test("await api\n .removeFromPlaylist(listId, id)")).toBe(true);
|
||||
expect(WRITES.test("api.moveToPlaylist(a, id, b)")).toBe(true);
|
||||
expect(WRITES.test("api.moveManyToPlaylist(a, ids, b)")).toBe(true);
|
||||
expect(WRITES.test("api.undoPlaylistMove(a, b, m, t, p)")).toBe(true);
|
||||
expect(WRITES.test("this.setState(next); api.playlists()")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,7 +9,10 @@ import { api } from "../../lib/api";
|
||||
import { qk } from "../../lib/queryKeys";
|
||||
import {
|
||||
addPlaylistItem,
|
||||
movePlaylistItem,
|
||||
movePlaylistItems,
|
||||
removePlaylistItems,
|
||||
restorePlaylistItems,
|
||||
undoPlaylistMove,
|
||||
removePlaylistItem,
|
||||
clearVideoProgress,
|
||||
writeVideoState,
|
||||
@@ -77,12 +80,47 @@ describe("videoWrites", () => {
|
||||
expect(marks(qc)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("marks a move into and out of the Watch later list", async () => {
|
||||
vi.spyOn(api, "moveToPlaylist").mockResolvedValue({ ok: true } as never);
|
||||
it("marks a move into and out of the Watch later list, by what the server moved", async () => {
|
||||
vi.spyOn(api, "moveManyToPlaylist").mockResolvedValue({
|
||||
ok: true,
|
||||
moved: ["X"],
|
||||
already_there: ["Y"],
|
||||
} as never);
|
||||
const qc = new QueryClient();
|
||||
await movePlaylistItem(qc, MINE, "X", WATCH_LATER);
|
||||
await movePlaylistItems(qc, MINE, ["X", "Y", "gone"], WATCH_LATER);
|
||||
expect(marks(qc)).toEqual({ X: { saved: true }, Y: { saved: true } });
|
||||
await movePlaylistItems(qc, WATCH_LATER, ["X", "Y", "gone"], MINE);
|
||||
expect(marks(qc)).toEqual({ X: { saved: false }, Y: { saved: false } });
|
||||
});
|
||||
|
||||
it("marks a bulk removal from Watch later, and its restore", async () => {
|
||||
vi.spyOn(api, "removeManyFromPlaylist").mockResolvedValue({
|
||||
ok: true,
|
||||
removed: ["X"],
|
||||
} as never);
|
||||
vi.spyOn(api, "restoreToPlaylist").mockResolvedValue({ ok: true } as never);
|
||||
const qc = new QueryClient();
|
||||
await removePlaylistItems(qc, WATCH_LATER, ["X", "gone"]);
|
||||
expect(marks(qc)).toEqual({ X: { saved: false } });
|
||||
await restorePlaylistItems(qc, WATCH_LATER, ["X"], [0]);
|
||||
expect(marks(qc)).toEqual({ X: { saved: true } });
|
||||
await movePlaylistItem(qc, WATCH_LATER, "X", MINE);
|
||||
});
|
||||
|
||||
it("takes a move into Watch later back: only what landed there loses the mark", async () => {
|
||||
vi.spyOn(api, "undoPlaylistMove").mockResolvedValue({ ok: true } as never);
|
||||
const qc = new QueryClient();
|
||||
await undoPlaylistMove(qc, MINE, WATCH_LATER, {
|
||||
moved: ["X"],
|
||||
already_there: ["Y"],
|
||||
positions: [0, 1],
|
||||
});
|
||||
expect(api.undoPlaylistMove).toHaveBeenCalledWith(
|
||||
MINE.id,
|
||||
WATCH_LATER.id,
|
||||
["X"],
|
||||
["Y"],
|
||||
[0, 1],
|
||||
);
|
||||
expect(marks(qc)).toEqual({ X: { saved: false } });
|
||||
});
|
||||
|
||||
|
||||
@@ -43,10 +43,8 @@ const markIfWatchLater = (qc: QueryClient, list: ListRef, id: string, saved: boo
|
||||
if (list.kind === "watch_later") markVideo(qc, id, { saved });
|
||||
};
|
||||
|
||||
/** Add a video to a playlist; `position` (an index in the stored order) puts it back where a
|
||||
* removal took it from. */
|
||||
export function addPlaylistItem(qc: QueryClient, list: ListRef, id: string, position?: number) {
|
||||
return api.addToPlaylist(list.id, id, position).then((r) => {
|
||||
export function addPlaylistItem(qc: QueryClient, list: ListRef, id: string) {
|
||||
return api.addToPlaylist(list.id, id).then((r) => {
|
||||
markIfWatchLater(qc, list, id, true);
|
||||
return r;
|
||||
});
|
||||
@@ -59,11 +57,52 @@ export function removePlaylistItem(qc: QueryClient, list: ListRef, id: string) {
|
||||
});
|
||||
}
|
||||
|
||||
/** Move a video from one playlist to another, in one request (see `api.moveToPlaylist`). */
|
||||
export function movePlaylistItem(qc: QueryClient, from: ListRef, id: string, to: ListRef) {
|
||||
return api.moveToPlaylist(from.id, id, to.id).then((r) => {
|
||||
markIfWatchLater(qc, from, id, false);
|
||||
markIfWatchLater(qc, to, id, true);
|
||||
/** Take videos out of a playlist, in one request. Marks what the server says went. */
|
||||
export function removePlaylistItems(qc: QueryClient, list: ListRef, ids: string[]) {
|
||||
return api.removeManyFromPlaylist(list.id, ids).then((r) => {
|
||||
for (const id of r.removed) markIfWatchLater(qc, list, id, false);
|
||||
return r;
|
||||
});
|
||||
}
|
||||
|
||||
/** Put removed videos back at their places, in one request. */
|
||||
export function restorePlaylistItems(
|
||||
qc: QueryClient,
|
||||
list: ListRef,
|
||||
ids: string[],
|
||||
positions: number[],
|
||||
) {
|
||||
return api.restoreToPlaylist(list.id, ids, positions).then((r) => {
|
||||
for (const id of ids) markIfWatchLater(qc, list, id, true);
|
||||
return r;
|
||||
});
|
||||
}
|
||||
|
||||
/** Move videos from one playlist to another, in one request (see `api.moveManyToPlaylist`). Marks
|
||||
* what the server says it moved: a video a concurrent edit already took out is in neither answer. */
|
||||
export function movePlaylistItems(qc: QueryClient, from: ListRef, ids: string[], to: ListRef) {
|
||||
return api.moveManyToPlaylist(from.id, ids, to.id).then((r) => {
|
||||
for (const id of [...r.moved, ...r.already_there]) {
|
||||
markIfWatchLater(qc, from, id, false);
|
||||
markIfWatchLater(qc, to, id, true);
|
||||
}
|
||||
return r;
|
||||
});
|
||||
}
|
||||
|
||||
/** Take a move back: every video returns to `from`, and only the ones that landed in `to` leave it;
|
||||
* it held the others before the move. */
|
||||
export function undoPlaylistMove(
|
||||
qc: QueryClient,
|
||||
from: ListRef,
|
||||
to: ListRef,
|
||||
back: { moved: string[]; already_there: string[]; positions: number[] },
|
||||
) {
|
||||
return api
|
||||
.undoPlaylistMove(from.id, to.id, back.moved, back.already_there, back.positions)
|
||||
.then((r) => {
|
||||
for (const id of back.moved) markIfWatchLater(qc, to, id, false);
|
||||
for (const id of [...back.moved, ...back.already_there]) markIfWatchLater(qc, from, id, true);
|
||||
return r;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
"loadError": "Couldn't load this — check your connection and try again",
|
||||
"deletedTag": "Deleted tag",
|
||||
"seeAll": "See all",
|
||||
"seeAllOf": "{{action}}: {{title}}",
|
||||
"scrollLeft": "Scroll left",
|
||||
"scrollRight": "Scroll right",
|
||||
"search": "Search",
|
||||
|
||||
@@ -32,6 +32,9 @@
|
||||
"uploadProgress": "Upload progress",
|
||||
"added": "File uploaded",
|
||||
"addedConverting": "File uploaded — converting it so it plays on any phone",
|
||||
"targetLabel": "Upload to",
|
||||
"makingFolder": "Making “{{name}}”…",
|
||||
"targetFailed": "The folders could not be loaded",
|
||||
"failed": "Couldn't upload the file"
|
||||
},
|
||||
"status": {
|
||||
@@ -90,7 +93,7 @@
|
||||
"pickPlaceholder": "Search a user…",
|
||||
"noUsers": "No other users yet.",
|
||||
"linkSection": "Share a link",
|
||||
"linkHint": "Anyone with the link can watch — no account needed.",
|
||||
"linkHint": "Anyone with the link can open it — no account needed.",
|
||||
"linkCopied": "Share link copied to clipboard",
|
||||
"openNewTab": "Open in new tab",
|
||||
"linkFailed": "Couldn’t create the share link",
|
||||
@@ -111,6 +114,7 @@
|
||||
"revokeConfirm": "This link will stop working immediately.",
|
||||
"views_one": "{{count}} view",
|
||||
"views_other": "{{count}} views",
|
||||
"expiredOn": "expired {{date}}",
|
||||
"expiresOn": "expires {{date}}",
|
||||
"hasPassword": "password",
|
||||
"downloadable": "downloadable",
|
||||
|
||||
@@ -34,8 +34,10 @@
|
||||
"search": "Jump to the search box",
|
||||
"listStep": "Next / previous item",
|
||||
"gridMove": "Move around the list",
|
||||
"open": "Open the selected item",
|
||||
"listRemove": "Remove the selected item from the list",
|
||||
"open": "Open the current item",
|
||||
"listRemove": "Remove from the list",
|
||||
"listSelect": "Select or deselect the current item",
|
||||
"listClearSelection": "Clear the selection",
|
||||
"cap": {
|
||||
"space": "Space",
|
||||
"menu": "Menu"
|
||||
|
||||
@@ -94,7 +94,6 @@
|
||||
"sync_all_busy": "Your playlists are already syncing with YouTube — try again when it finishes"
|
||||
},
|
||||
"moveErrors": {
|
||||
"not_in_playlist": "That video isn't in this playlist any more — it changed somewhere else",
|
||||
"same_playlist": "That video is already in this playlist"
|
||||
},
|
||||
"railMenu": "Playlist actions",
|
||||
@@ -102,6 +101,45 @@
|
||||
"removeItem": "Remove",
|
||||
"removeItemOf": "Remove “{{title}}” from the playlist",
|
||||
"dragHandleOf": "Reorder “{{title}}”",
|
||||
"selectRow": "Select “{{title}}”",
|
||||
"selectAllShown": "Select all the rows shown",
|
||||
"selectedCount_one": "{{count}} selected",
|
||||
"selectedCount_other": "{{count}} selected",
|
||||
"selectedHidden_one": "{{count}} more hidden by the filter",
|
||||
"selectedHidden_other": "{{count}} more hidden by the filter",
|
||||
"selectedHiddenShort": "+{{n}}",
|
||||
"clearSelection": "Clear selection",
|
||||
"moveSelected": "Move to",
|
||||
"removeSelected": "Remove",
|
||||
"movedManyToast_one": "{{count}} video moved to “{{name}}”",
|
||||
"movedManyToast_other": "{{count}} videos moved to “{{name}}”",
|
||||
"removedManyToast_one": "{{count}} video removed from the playlist",
|
||||
"removedManyToast_other": "{{count}} videos removed from the playlist",
|
||||
"moveNoneLeft_one": "Nothing moved: it isn’t in this playlist any more",
|
||||
"moveNoneLeft_other": "Nothing moved: they aren’t in this playlist any more",
|
||||
"removeNoneLeft_one": "Nothing removed: it isn’t in this playlist any more",
|
||||
"removeNoneLeft_other": "Nothing removed: they aren’t in this playlist any more",
|
||||
"selectionCleared": "Selection cleared",
|
||||
"removeAllHidden_one": "The selected row is hidden by the filter",
|
||||
"removeAllHidden_other": "The selected rows are hidden by the filter",
|
||||
"undoNoneBack_one": "Nothing came back: that video isn’t where it was any more",
|
||||
"undoNoneBack_other": "Nothing came back: those videos aren’t where they were any more",
|
||||
"undoSomeBack_one": "Only {{count}} video came back: the rest aren’t where they were any more",
|
||||
"undoSomeBack_other": "Only {{count}} videos came back: the rest aren’t where they were any more",
|
||||
"dragCancelledMany_one": "Move cancelled; {{count}} video stays where it was",
|
||||
"dragCancelledMany_other": "Move cancelled; {{count}} videos stay where they were",
|
||||
"moveTargetsFailed": "Your playlists couldn’t be loaded",
|
||||
"moveTargetsLoading": "Loading your playlists…",
|
||||
"moveManyFailed": "Couldn't move the videos",
|
||||
"removeManyFailed": "Couldn't remove the videos",
|
||||
"undoMoveFailed": "Couldn't move the video back",
|
||||
"undoMoveManyFailed": "Couldn't move the videos back",
|
||||
"undoRemoveManyFailed": "Couldn't put the videos back",
|
||||
"dragHandleToList": "Drag “{{title}}” onto a list",
|
||||
"dragPickedMany_one": "{{count}} video picked up",
|
||||
"dragPickedMany_other": "{{count}} videos picked up",
|
||||
"dragOverList": "Over “{{name}}”",
|
||||
"dragDroppedOnList": "Dropped on “{{name}}”",
|
||||
"dragBlockedSort": "Reordering by hand is off while a column sort or grouping is applied.",
|
||||
"dragBlockedFilter": "Reordering by hand is off while a filter is applied.",
|
||||
"clearView": "Reset view",
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
"loadError": "Nem sikerült betölteni — ellenőrizd a kapcsolatot, és próbáld újra",
|
||||
"deletedTag": "Törölt címke",
|
||||
"seeAll": "Összes",
|
||||
"seeAllOf": "{{action}}: {{title}}",
|
||||
"scrollLeft": "Görgetés balra",
|
||||
"scrollRight": "Görgetés jobbra",
|
||||
"search": "Keresés",
|
||||
|
||||
@@ -32,6 +32,9 @@
|
||||
"uploadProgress": "Feltöltés folyamata",
|
||||
"added": "Fájl feltöltve",
|
||||
"addedConverting": "Fájl feltöltve — átalakítjuk, hogy minden telefonon lejátszható legyen",
|
||||
"targetLabel": "Feltöltés ide",
|
||||
"makingFolder": "„{{name}}” létrehozása…",
|
||||
"targetFailed": "A mappákat nem sikerült betölteni",
|
||||
"failed": "Nem sikerült feltölteni a fájlt"
|
||||
},
|
||||
"status": {
|
||||
@@ -90,7 +93,7 @@
|
||||
"pickPlaceholder": "Keress egy felhasználót…",
|
||||
"noUsers": "Nincs más felhasználó.",
|
||||
"linkSection": "Megosztás linkkel",
|
||||
"linkHint": "A link birtokában bárki megnézheti — fiók nélkül is.",
|
||||
"linkHint": "A link birtokában bárki megnyithatja — fiók nélkül is.",
|
||||
"linkCopied": "Megosztási link a vágólapra másolva",
|
||||
"openNewTab": "Megnyitás új lapon",
|
||||
"linkFailed": "Nem sikerült a megosztási link létrehozása",
|
||||
@@ -111,6 +114,7 @@
|
||||
"revokeConfirm": "A link azonnal használhatatlanná válik.",
|
||||
"views_one": "{{count}} megtekintés",
|
||||
"views_other": "{{count}} megtekintés",
|
||||
"expiredOn": "lejárt: {{date}}",
|
||||
"expiresOn": "lejár: {{date}}",
|
||||
"hasPassword": "jelszó",
|
||||
"downloadable": "letölthető",
|
||||
|
||||
@@ -34,8 +34,10 @@
|
||||
"search": "Ugrás a keresőbe",
|
||||
"listStep": "Következő / előző elem",
|
||||
"gridMove": "Mozgás a listában",
|
||||
"open": "A kijelölt elem megnyitása",
|
||||
"listRemove": "A kijelölt elem eltávolítása a listából",
|
||||
"open": "Az aktuális elem megnyitása",
|
||||
"listRemove": "Eltávolítás a listából",
|
||||
"listSelect": "Az aktuális elem kijelölése vagy a jelölés levétele",
|
||||
"listClearSelection": "A kijelölés törlése",
|
||||
"cap": {
|
||||
"space": "Szóköz",
|
||||
"menu": "Menü"
|
||||
|
||||
@@ -94,7 +94,6 @@
|
||||
"sync_all_busy": "A listáid épp szinkronizálnak a YouTube-bal — próbáld újra, ha végzett"
|
||||
},
|
||||
"moveErrors": {
|
||||
"not_in_playlist": "Ez a videó már nincs ebben a listában — időközben máshol megváltozott",
|
||||
"same_playlist": "Ez a videó már ebben a listában van"
|
||||
},
|
||||
"railMenu": "Lejátszási lista műveletei",
|
||||
@@ -102,6 +101,45 @@
|
||||
"removeItem": "Eltávolítás",
|
||||
"removeItemOf": "„{{title}}” eltávolítása a listáról",
|
||||
"dragHandleOf": "„{{title}}” átrendezése",
|
||||
"selectRow": "„{{title}}” kijelölése",
|
||||
"selectAllShown": "Az összes látható sor kijelölése",
|
||||
"selectedCount_one": "{{count}} kijelölve",
|
||||
"selectedCount_other": "{{count}} kijelölve",
|
||||
"selectedHidden_one": "további {{count}} a szűrő mögött",
|
||||
"selectedHidden_other": "további {{count}} a szűrő mögött",
|
||||
"selectedHiddenShort": "+{{n}}",
|
||||
"clearSelection": "Kijelölés törlése",
|
||||
"moveSelected": "Áthelyezés ide",
|
||||
"removeSelected": "Eltávolítás",
|
||||
"movedManyToast_one": "{{count}} videó áthelyezve ide: „{{name}}”",
|
||||
"movedManyToast_other": "{{count}} videó áthelyezve ide: „{{name}}”",
|
||||
"removedManyToast_one": "{{count}} videó eltávolítva a listáról",
|
||||
"removedManyToast_other": "{{count}} videó eltávolítva a listáról",
|
||||
"moveNoneLeft_one": "Nem történt áthelyezés: ez már nincs ebben a listában",
|
||||
"moveNoneLeft_other": "Nem történt áthelyezés: ezek már nincsenek ebben a listában",
|
||||
"removeNoneLeft_one": "Nem történt eltávolítás: ez már nincs ebben a listában",
|
||||
"removeNoneLeft_other": "Nem történt eltávolítás: ezek már nincsenek ebben a listában",
|
||||
"selectionCleared": "Kijelölés törölve",
|
||||
"removeAllHidden_one": "A kijelölt sort a szűrő elrejti",
|
||||
"removeAllHidden_other": "A kijelölt sorokat a szűrő elrejti",
|
||||
"undoNoneBack_one": "Semmi nem került vissza: ez a videó már nincs ott, ahol volt",
|
||||
"undoNoneBack_other": "Semmi nem került vissza: ezek a videók már nincsenek ott, ahol voltak",
|
||||
"undoSomeBack_one": "Csak {{count}} videó került vissza: a többi már nincs ott, ahol volt",
|
||||
"undoSomeBack_other": "Csak {{count}} videó került vissza: a többi már nincs ott, ahol volt",
|
||||
"dragCancelledMany_one": "Áthelyezés megszakítva; {{count}} videó a helyén marad",
|
||||
"dragCancelledMany_other": "Áthelyezés megszakítva; {{count}} videó a helyén marad",
|
||||
"moveTargetsFailed": "Nem sikerült betölteni a listáidat",
|
||||
"moveTargetsLoading": "A listáid betöltése…",
|
||||
"moveManyFailed": "Nem sikerült áthelyezni a videókat",
|
||||
"removeManyFailed": "Nem sikerült eltávolítani a videókat",
|
||||
"undoMoveFailed": "Nem sikerült visszahelyezni a videót",
|
||||
"undoMoveManyFailed": "Nem sikerült visszahelyezni a videókat",
|
||||
"undoRemoveManyFailed": "Nem sikerült visszatenni a videókat",
|
||||
"dragHandleToList": "„{{title}}” húzása egy listára",
|
||||
"dragPickedMany_one": "{{count}} videó felvéve",
|
||||
"dragPickedMany_other": "{{count}} videó felvéve",
|
||||
"dragOverList": "A(z) „{{name}}” lista fölött",
|
||||
"dragDroppedOnList": "Letéve a(z) „{{name}}” listára",
|
||||
"dragBlockedSort": "A kézi átrendezés ki van kapcsolva, amíg oszloprendezés vagy csoportosítás van érvényben.",
|
||||
"dragBlockedFilter": "A kézi átrendezés ki van kapcsolva, amíg szűrő van érvényben.",
|
||||
"clearView": "Nézet visszaállítása",
|
||||
|
||||
@@ -70,7 +70,9 @@ export interface ClipRequest {
|
||||
export interface EditSpec {
|
||||
trim?: { start_s: number; end_s?: number };
|
||||
segments?: { start_s: number; end_s: number }[];
|
||||
crop?: { x: number; y: number; w: number; h: number };
|
||||
// In the picture's size as the browser reports it, which `frame_w` x `frame_h` says: the server
|
||||
// scales them to the file's own pixels (a video's stored and shown sizes can differ).
|
||||
crop?: { x: number; y: number; w: number; h: number; frame_w?: number; frame_h?: number };
|
||||
accurate?: boolean;
|
||||
}
|
||||
|
||||
@@ -143,7 +145,7 @@ export interface ShareLink {
|
||||
// Null when the server cannot show this link's address again (no encrypted copy its key reads): the
|
||||
// link still opens for whoever has it; to share it anew, make a new link.
|
||||
token: string | null;
|
||||
url: string | null; // path like "/watch/<token>" — prepend window.location.origin to share
|
||||
url: string | null; // path like "/watch/<token>" or "/file/<token>" — prepend window.location.origin to share
|
||||
allow_download: boolean;
|
||||
has_password: boolean;
|
||||
expires_at: string | null;
|
||||
|
||||
@@ -68,25 +68,65 @@ export const playlistsApi = {
|
||||
req(`/api/playlists/${id}`, { method: "PATCH", body: JSON.stringify({ name }) }),
|
||||
deletePlaylist: (id: number, onYoutube = false) =>
|
||||
req(`/api/playlists/${id}${onYoutube ? "?on_youtube=true" : ""}`, { method: "DELETE" }),
|
||||
// `position` (an index in the stored order) puts it back where a removal took it from — the
|
||||
// list page's Undo; omitted, it is appended.
|
||||
addToPlaylist: (id: number, videoId: string, position?: number) =>
|
||||
addToPlaylist: (id: number, videoId: string) =>
|
||||
req(`/api/playlists/${id}/items`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ video_id: videoId, ...(position != null && { position }) }),
|
||||
body: JSON.stringify({ video_id: videoId }),
|
||||
}),
|
||||
removeFromPlaylist: (id: number, videoId: string) =>
|
||||
req(`/api/playlists/${id}/items/${videoId}`, { method: "DELETE" }),
|
||||
// One request on purpose: add-then-remove from the client leaves the video in BOTH lists when
|
||||
// the second call fails. The server does it in one transaction.
|
||||
moveToPlaylist: (
|
||||
// One request on purpose: add-then-remove from the client leaves a video in BOTH lists when the
|
||||
// second call fails. The server does it in one transaction, and says which landed in the target
|
||||
// and which it already held: the Undo needs to tell them apart.
|
||||
moveManyToPlaylist: (
|
||||
id: number,
|
||||
videoId: string,
|
||||
videoIds: string[],
|
||||
targetPlaylistId: number,
|
||||
): Promise<{ ok: true; from_playlist_id: number; to_playlist_id: number; video_id: string }> =>
|
||||
req(`/api/playlists/${id}/items/${videoId}/move`, {
|
||||
): Promise<{
|
||||
ok: true;
|
||||
from_playlist_id: number;
|
||||
to_playlist_id: number;
|
||||
moved: string[];
|
||||
already_there: string[];
|
||||
}> =>
|
||||
req(`/api/playlists/${id}/items/move-bulk`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ target_playlist_id: targetPlaylistId }),
|
||||
body: JSON.stringify({ video_ids: videoIds, target_playlist_id: targetPlaylistId }),
|
||||
}),
|
||||
// The Undo of a move, back into `id`. `positions` pairs with `moved` + `alreadyThere`.
|
||||
undoPlaylistMove: (
|
||||
id: number,
|
||||
fromPlaylistId: number,
|
||||
moved: string[],
|
||||
alreadyThere: string[],
|
||||
positions: number[],
|
||||
): Promise<{ ok: true; playlist_id: number; added: number }> =>
|
||||
req(`/api/playlists/${id}/items/undo-move`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
from_playlist_id: fromPlaylistId,
|
||||
moved,
|
||||
already_there: alreadyThere,
|
||||
positions,
|
||||
}),
|
||||
}),
|
||||
removeManyFromPlaylist: (
|
||||
id: number,
|
||||
videoIds: string[],
|
||||
): Promise<{ ok: true; playlist_id: number; removed: string[] }> =>
|
||||
req(`/api/playlists/${id}/items/remove-bulk`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ video_ids: videoIds }),
|
||||
}),
|
||||
// The Undo of a removal, in one request; an index in the stored order per video.
|
||||
restoreToPlaylist: (
|
||||
id: number,
|
||||
videoIds: string[],
|
||||
positions: number[],
|
||||
): Promise<{ ok: true; playlist_id: number; added: number }> =>
|
||||
req(`/api/playlists/${id}/items/restore`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ video_ids: videoIds, positions }),
|
||||
}),
|
||||
reorderPlaylist: (id: number, videoIds: string[]) =>
|
||||
req(`/api/playlists/${id}/order`, {
|
||||
|
||||
@@ -154,6 +154,7 @@ export interface PlexItemDetail {
|
||||
summary?: string | null;
|
||||
year?: number | null;
|
||||
duration_seconds: number | null;
|
||||
size_bytes?: number | null; // the file's, null while unknown
|
||||
playable: string; // direct | remux | transcode
|
||||
transcode_hw?: boolean | null; // transcode items only: true = HW-capable, false = SW-only, null = n/a
|
||||
codec_video?: string | null; // e.g. "hevc" / "h264" (info-chip subtitle)
|
||||
|
||||
@@ -7,7 +7,12 @@ export interface Tag {
|
||||
color: string | null;
|
||||
category: string;
|
||||
system: boolean;
|
||||
/** Every channel link it has, a channel the user no longer follows included (an unsubscribe keeps
|
||||
* the link) — what deleting the tag removes. */
|
||||
channel_count: number;
|
||||
/** The user's own links on channels they follow and have not hidden: the rows the Channels page's
|
||||
* filter shows (a hidden channel has its own tab). */
|
||||
subscribed_count: number;
|
||||
}
|
||||
|
||||
// One suggested user-tag for a channel, learned from the user's own manual-tag pattern.
|
||||
|
||||
@@ -18,6 +18,7 @@ import { api, HttpError } from "./api";
|
||||
import { msg, notify } from "./notifications";
|
||||
import { useChannelTagActions } from "./useChannelTagActions";
|
||||
import { useChannelPriority } from "./useChannelPriority";
|
||||
import { qk } from "./queryKeys";
|
||||
|
||||
const notifyMock = vi.mocked(notify);
|
||||
beforeEach(() => notifyMock.mockClear());
|
||||
@@ -44,6 +45,23 @@ describe("useChannelTagActions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// A tag counts the followed channels it is on: a toggle that lands changes that number.
|
||||
it("refreshes the tags once a toggle lands", async () => {
|
||||
vi.spyOn(api, "attachChannelTag").mockResolvedValue({ ok: true } as never);
|
||||
const qc = new QueryClient();
|
||||
const spy = vi.spyOn(qc, "invalidateQueries");
|
||||
const { result } = renderHook(
|
||||
() => useChannelTagActions({ optimisticToggle: () => {}, onError: () => {} }),
|
||||
{
|
||||
wrapper: ({ children }) => (
|
||||
<QueryClientProvider client={qc}>{children}</QueryClientProvider>
|
||||
),
|
||||
},
|
||||
);
|
||||
act(() => result.current.toggleTag("UC1", 7, false));
|
||||
await waitFor(() => expect(spy.mock.calls.map(([f]) => f?.queryKey)).toContainEqual(qk.tags()));
|
||||
});
|
||||
|
||||
it("names a refused create-and-attach", async () => {
|
||||
vi.spyOn(api, "createTag").mockRejectedValue(new HttpError(429, "slow"));
|
||||
const { result } = renderHook(
|
||||
|
||||
@@ -94,6 +94,22 @@ describe("quickShareLink", () => {
|
||||
expect(createDownloadLink).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// An expired link stays listed for its owner, but its recipient would land on "link gone".
|
||||
it("passes over an expired link, and mints one when every link has expired", async () => {
|
||||
const lastWeek = new Date(Date.now() - 7 * 86400_000).toISOString();
|
||||
const nextWeek = new Date(Date.now() + 7 * 86400_000).toISOString();
|
||||
downloadLinks.mockResolvedValue([
|
||||
{ id: 5, url: "/watch/gone", expires_at: lastWeek },
|
||||
{ id: 3, url: "/watch/live", expires_at: nextWeek },
|
||||
]);
|
||||
expect(await quickShareLink(qc(), { kind: "file", id: 1 })).toBe(`${origin}/watch/live`);
|
||||
expect(createDownloadLink).not.toHaveBeenCalled();
|
||||
|
||||
downloadLinks.mockResolvedValue([{ id: 5, url: "/watch/gone", expires_at: lastWeek }]);
|
||||
createDownloadLink.mockResolvedValue({ id: 9, url: "/watch/fresh" });
|
||||
expect(await quickShareLink(qc(), { kind: "file", id: 2 })).toBe(`${origin}/watch/fresh`);
|
||||
});
|
||||
|
||||
it("mints a new link when none it has can be shown, keeping the old ones listed", async () => {
|
||||
const hidden = { id: 4, url: null };
|
||||
downloadLinks.mockResolvedValue([hidden]);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import { qk } from "./queryKeys";
|
||||
import { api, type NewShareLink } from "./api";
|
||||
import { api, type NewShareLink, type ShareLink } from "./api";
|
||||
import { copyText } from "./clipboard";
|
||||
import { msg, notify } from "./notifications";
|
||||
import { notifyActionError } from "./actionErrors";
|
||||
@@ -38,6 +38,16 @@ export function invalidateLinks(qc: QueryClient, target: LinkTarget) {
|
||||
if (target.kind === "folder") void qc.invalidateQueries({ queryKey: qk.fileFolders() });
|
||||
}
|
||||
|
||||
/** Has a link stopped opening? The list still holds an expired link (its owner may want to see or
|
||||
* revoke it), but it is no link to hand out. */
|
||||
export const linkExpired = (link: ShareLink, now = Date.now()) =>
|
||||
link.expires_at !== null && Date.parse(link.expires_at) <= now;
|
||||
|
||||
/** The link to hand out of a list (newest first): the newest that still opens and whose address can
|
||||
* be shown — an expired one sends the recipient to "link gone", one without an address is no use
|
||||
* to copy. None: make one. */
|
||||
export const liveLink = (links: ShareLink[]) => links.find((l) => l.url && !linkExpired(l));
|
||||
|
||||
// One-click share: the row's Share button turns "share this" into a single action.
|
||||
// Ensure the file or folder has a public link (minting one on demand — omitting `allow_download` so
|
||||
// the backend default makes it downloadable), copy it to the clipboard, and toast with an "open in
|
||||
@@ -51,8 +61,7 @@ export async function quickShareLink(qc: QueryClient, target: LinkTarget): Promi
|
||||
queryKey: linksKey(target),
|
||||
queryFn: () => fetchLinks(target),
|
||||
});
|
||||
// The newest link whose address can still be shown; one that cannot is no use to copy.
|
||||
path = existing.find((l) => l.url)?.url;
|
||||
path = liveLink(existing)?.url;
|
||||
if (!path) {
|
||||
const made = await makeLink(target, {}); // omit allow_download → backend default (true)
|
||||
qc.setQueryData(linksKey(target), [made, ...existing]);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// The e2e suite's request wrapper (e2e/retryConnect.ts): a connect that never came about is tried
|
||||
// again, as every TCP stack would; any other failure, or an answer, goes straight to the test.
|
||||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { retryConnect } from "../../e2e/retryConnect";
|
||||
import { gotoRetrying, retryConnect } from "../../e2e/retryConnect";
|
||||
|
||||
const noConnection = () => new Error("apiRequestContext.get: connect ETIMEDOUT 127.0.0.1:8080");
|
||||
|
||||
@@ -39,3 +40,43 @@ describe("retryConnect", () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
|
||||
// The text Playwright gave when this stopped a release's e2e at its first page load (2026-11-04).
|
||||
const noBuffer = () => new Error("page.goto: net::ERR_NO_BUFFER_SPACE at http://127.0.0.1:8080/");
|
||||
|
||||
describe("gotoRetrying", () => {
|
||||
it("tries a page load the machine had no buffer for again", async () => {
|
||||
vi.useFakeTimers();
|
||||
const goto = vi.fn().mockRejectedValueOnce(noBuffer()).mockResolvedValue("response");
|
||||
const answer = gotoRetrying({ goto }, "/feed");
|
||||
await vi.runAllTimersAsync();
|
||||
await expect(answer).resolves.toBe("response");
|
||||
expect(goto).toHaveBeenCalledTimes(2);
|
||||
expect(goto).toHaveBeenLastCalledWith("/feed");
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("passes any other failure straight on, untried", async () => {
|
||||
const goto = vi.fn().mockRejectedValue(new Error("page.goto: net::ERR_CONNECTION_REFUSED"));
|
||||
await expect(gotoRetrying({ goto }, "/")).rejects.toThrow("ERR_CONNECTION_REFUSED");
|
||||
expect(goto).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("gives up after its last wait, with the error", async () => {
|
||||
vi.useFakeTimers();
|
||||
const goto = vi.fn().mockRejectedValue(noBuffer());
|
||||
const settled = expect(gotoRetrying({ goto }, "/")).rejects.toThrow("ERR_NO_BUFFER_SPACE");
|
||||
await vi.runAllTimersAsync();
|
||||
await settled;
|
||||
expect(goto).toHaveBeenCalledTimes(6);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("is the only way the suite loads a page", () => {
|
||||
const dir = new URL("../../e2e/", import.meta.url);
|
||||
const direct = readdirSync(dir)
|
||||
.filter((f) => f.endsWith(".ts") && f !== "retryConnect.ts")
|
||||
.filter((f) => /\.(goto|reload)\(/.test(readFileSync(new URL(f, dir), "utf-8")));
|
||||
expect(direct).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -65,6 +65,27 @@ class FakeHls implements HlsPort {
|
||||
lost404() {
|
||||
this.lost(404);
|
||||
}
|
||||
/** A request answered "this session is gone". hls.js only reports it (not fatal) and retries for
|
||||
* half a minute: with one video variant it has nowhere else to go. */
|
||||
gone() {
|
||||
this.handlers.onError({
|
||||
fatal: false,
|
||||
network: true,
|
||||
status: 410,
|
||||
type: "networkError",
|
||||
details: "fragLoadError",
|
||||
});
|
||||
}
|
||||
/** hls.js reports a failed request it will retry by itself. */
|
||||
retrying(status: number) {
|
||||
this.handlers.onError({
|
||||
fatal: false,
|
||||
network: true,
|
||||
status,
|
||||
type: "networkError",
|
||||
details: "fragLoadError",
|
||||
});
|
||||
}
|
||||
/** hls.js gave up on a playlist or fragment with this answer (null: no answer at all). */
|
||||
lost(status: number | null) {
|
||||
this.handlers.onError({
|
||||
@@ -353,7 +374,7 @@ describe("a failed session request", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a session the server no longer has (404)", () => {
|
||||
describe("something that never arrives (a fatal 404)", () => {
|
||||
it("is reclaimed where the viewer is", async () => {
|
||||
const { engine, asks, hlses, state } = setup();
|
||||
engine.start("A", 600);
|
||||
@@ -418,9 +439,85 @@ describe("a session the server no longer has (404)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a session the server says is gone (410)", () => {
|
||||
async function playing() {
|
||||
const s = setup();
|
||||
s.engine.start("A", 600);
|
||||
await s.asks[0]!.resolve(hls("A", 600));
|
||||
s.hlses[0]!.handlers.onManifestParsed();
|
||||
s.media.fire("canplay");
|
||||
s.state.position = 1299;
|
||||
return s;
|
||||
}
|
||||
|
||||
it("is reclaimed at the first answer, not after hls.js's half minute of retries", async () => {
|
||||
const { asks, hlses } = await playing();
|
||||
hlses[0]!.gone();
|
||||
expect(asks[1]!.startAt).toBe(1299);
|
||||
});
|
||||
|
||||
it("keeps the running picture until the new session answers", async () => {
|
||||
const { engine, hlses } = await playing();
|
||||
expect(engine.getSnapshot().ready).toBe(true);
|
||||
hlses[0]!.gone();
|
||||
expect(engine.getSnapshot().ready).toBe(true);
|
||||
});
|
||||
|
||||
it("asks once, whatever the same instance still reports", async () => {
|
||||
const { asks, hlses } = await playing();
|
||||
hlses[0]!.gone();
|
||||
hlses[0]!.gone();
|
||||
hlses[0]!.lost(410);
|
||||
expect(asks).toHaveLength(2);
|
||||
});
|
||||
|
||||
it(`shares the reclaim budget, and says so after ${MAX_SESSION_RECLAIMS}`, async () => {
|
||||
const { engine, asks, hlses } = setup();
|
||||
engine.start("A", 600);
|
||||
for (let i = 0; i <= MAX_SESSION_RECLAIMS; i++) {
|
||||
await asks[i]!.resolve(hls("A", 600));
|
||||
hlses[i]!.gone();
|
||||
}
|
||||
expect(asks).toHaveLength(MAX_SESSION_RECLAIMS + 1);
|
||||
expect(engine.getSnapshot().error).toBe("generic");
|
||||
});
|
||||
|
||||
it("keeps a seek made while it is out, inside what the old session still reports", async () => {
|
||||
const { engine, asks, hlses, media } = await playing();
|
||||
media.seekEnd = 800;
|
||||
hlses[0]!.gone();
|
||||
media.currentTime = 42;
|
||||
engine.seek("A", 1250);
|
||||
expect(media.currentTime).toBe(42); // the outgoing media stays where it is
|
||||
await asks[1]!.resolve(hls("A", 1299));
|
||||
expect(asks.map((a) => a.startAt)).toEqual([600, 1299, 1250]);
|
||||
});
|
||||
|
||||
it("leaves a segment that is merely not there yet to hls.js's retries", async () => {
|
||||
const { engine, asks, hlses } = await playing();
|
||||
hlses[0]!.retrying(404);
|
||||
expect(asks).toHaveLength(1);
|
||||
expect(engine.getSnapshot().error).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("a server that is restarting (a deploy)", () => {
|
||||
// The gateway answers 502 while the app restarts, and nothing at all may answer (status 0): the
|
||||
// stream is not broken, the server is away. The buffer keeps playing meanwhile.
|
||||
it("keeps a seek made while the retry is out", async () => {
|
||||
const { engine, asks, hlses, state, fire, media } = setup();
|
||||
engine.start("A", 600);
|
||||
await asks[0]!.resolve(hls("A", 600));
|
||||
hlses[0]!.handlers.onManifestParsed();
|
||||
media.seekEnd = 800;
|
||||
state.position = 1299;
|
||||
hlses[0]!.lost(502);
|
||||
expect(fire()).toBe(true);
|
||||
engine.seek("A", 1250);
|
||||
await asks[1]!.resolve(hls("A", 1299));
|
||||
expect(asks.map((a) => a.startAt)).toEqual([600, 1299, 1250]);
|
||||
});
|
||||
|
||||
it.each([502, 503, 504, 0, null])(
|
||||
"is waited out on %s: no error, and the stream comes back where the viewer is",
|
||||
async (status) => {
|
||||
|
||||
@@ -14,7 +14,7 @@ import type { HlsLevelInfo } from "./plexStats";
|
||||
// once: twenty presses of ← at key-repeat pace past the buffer were twenty requests, twenty ffmpeg
|
||||
// spawns, and five seconds before the picture moved again.
|
||||
|
||||
// Reclaims of a 404'd HLS session, within `RECLAIM_WINDOW_MS`, before the player stops and says so.
|
||||
// Reclaims of a lost HLS session, within `RECLAIM_WINDOW_MS`, before the player stops and says so.
|
||||
// Two covers the real case (the session was reaped, once) without letting a server that cannot serve
|
||||
// the stream keep the viewer on a spinner (see `onHlsError`).
|
||||
export const MAX_SESSION_RECLAIMS = 2;
|
||||
@@ -33,6 +33,8 @@ export const RECLAIM_WINDOW_MS = 120_000;
|
||||
export const AWAY_WINDOW_MS = 180_000;
|
||||
const AWAY_RETRY_MS = [2_000, 4_000, 8_000, 15_000];
|
||||
const SERVER_AWAY = new Set([0, 502, 503, 504]);
|
||||
// The server's answer for a session it no longer has; its 404 means a segment not there yet.
|
||||
const SESSION_GONE = 410;
|
||||
|
||||
/** Why a session could not play, in the three buckets the player has a sentence for. */
|
||||
type EngineError = "transcode" | "notFound" | "generic";
|
||||
@@ -183,7 +185,7 @@ export class HlsEngine {
|
||||
// the way back to the first item then sent a second request beside the one still out for it.
|
||||
private readonly inFlight = new Map<string, Request>();
|
||||
private queued: Request | null = null;
|
||||
// How often a session the server answered 404 for may be reclaimed (see `onHlsError`).
|
||||
// How often a session the server lost may be reclaimed (see `onHlsError`).
|
||||
private reclaims = { n: 0, at: 0 };
|
||||
// Since when the server has been away, and how often it was asked since (see `serverAway`).
|
||||
private away: { since: number; tries: number } | null = null;
|
||||
@@ -283,7 +285,7 @@ export class HlsEngine {
|
||||
|
||||
/** (Re)start `id` at `startAt` seconds. Another item's request goes out at once; one for the item
|
||||
* already being asked for waits for that answer (see the header). `quiet`: the attached stream is
|
||||
* still playing from its buffer (the server went away under it), so it stays the player's until
|
||||
* still playing from its buffer (the server went away or lost its session), so it stays the player's until
|
||||
* the answer replaces it — no "Loading…" over a running picture, its clock still true. */
|
||||
start(id: string, startAt: number, play = true, quiet = false): void {
|
||||
if (!this.deps.media()) return;
|
||||
@@ -459,42 +461,61 @@ export class HlsEngine {
|
||||
};
|
||||
}
|
||||
|
||||
// A fatal HLS error (the session died, the file became unreadable) would otherwise leave the
|
||||
// spinner up forever — it is said instead.
|
||||
// A fatal HLS error (the file became unreadable) would otherwise leave the spinner up forever — it
|
||||
// is said instead.
|
||||
//
|
||||
// Except a 404: the session is gone, not broken. Either the server reaped it (a pause longer than
|
||||
// its idle limit, a deploy) — hls.js never retries a 4xx, so this used to end playback with
|
||||
// "couldn't play" after the buffer ran out — or it was superseded before it ever played (two
|
||||
// requests for one item: the server's LAST spawn wins). The server answers a superseded session
|
||||
// exactly so the client asks again; the reclaim is that asking.
|
||||
// Except a session the server no longer has (410): gone, not broken. Either the server reaped it
|
||||
// or restarted, or it was superseded before it ever played (two requests for one item: the
|
||||
// server's LAST spawn wins), and the reclaim is the asking again that answer wants. It does not
|
||||
// wait for hls.js to give up. On a finished playlist, with one video variant and nothing to
|
||||
// switch to, it retries even a 4xx, six times over about half a minute (measured: seven requests,
|
||||
// then the reclaim), and in a throttled page once a minute (four minutes). On a growing one it
|
||||
// takes the segment for a gap and moves on, so the error is never fatal. Either way the first
|
||||
// answer is reported. Quiet, since the buffer is still playing: the picture runs on until the
|
||||
// answer, which restarts from where it was asked, so what played meanwhile is replayed (accepted:
|
||||
// a brief loading state marks it, and nothing the viewer has saved is lost).
|
||||
//
|
||||
// Bounded by the budget, not by whether the session got as far as playing: that belongs to ONE
|
||||
// session, and every restart builds a fresh one, so it could never bound a loop. The server also answers
|
||||
// 404 for "that segment is not there YET" — indistinguishable on the wire — so a transcode falling
|
||||
// behind realtime restarted ffmpeg forever behind a spinner that never became an error.
|
||||
// And except a fatal 404: hls.js gave up on something the server still does not have, and asking
|
||||
// again is all that is left.
|
||||
//
|
||||
// Both are bounded by the budget, not by whether the session got as far as playing: that belongs to
|
||||
// ONE session, and every restart builds a fresh one, so it could never bound a loop. A transcode
|
||||
// falling behind realtime restarted ffmpeg forever behind a spinner that never became an error.
|
||||
private onHlsError(req: Request, media: HTMLMediaElement, e: HlsFailure): void {
|
||||
this.deps.onHlsError?.(e);
|
||||
if (!e.fatal || !this.current(req)) return;
|
||||
if (!this.current(req)) return;
|
||||
if (e.network && e.status === SESSION_GONE) {
|
||||
this.reclaim(req, media, this.snapshot.ready);
|
||||
return;
|
||||
}
|
||||
if (!e.fatal) return;
|
||||
if (e.network && SERVER_AWAY.has(e.status ?? 0) && this.serverAway(req)) return;
|
||||
if (e.network && e.status === 404) {
|
||||
const now = this.deps.now();
|
||||
// A new window when the last loss was long enough ago. The anchor moves with EVERY loss: left
|
||||
// at the window's start, the window tumbled instead of rolling, and any loss period longer
|
||||
// than half the window reset the budget on every second loss (measured: 200 losses 70 s apart
|
||||
// → 200 reclaims, never an error).
|
||||
if (now - this.reclaims.at > RECLAIM_WINDOW_MS) this.reclaims.n = 0;
|
||||
this.reclaims.at = now;
|
||||
if (this.reclaims.n < MAX_SESSION_RECLAIMS) {
|
||||
this.reclaims.n += 1;
|
||||
// The server dropped it already; nothing to stop.
|
||||
this.attachedSession = null;
|
||||
this.start(req.id, this.playhead(), this.wantsPlay(media));
|
||||
return;
|
||||
}
|
||||
this.reclaim(req, media, false);
|
||||
return;
|
||||
}
|
||||
this.set({ error: "generic" });
|
||||
}
|
||||
|
||||
/** Ask for `req`'s item again where the viewer is, while the budget lasts; then say it cannot play. */
|
||||
private reclaim(req: Request, media: HTMLMediaElement, quiet: boolean): void {
|
||||
const now = this.deps.now();
|
||||
// A new window when the last loss was long enough ago. The anchor moves with EVERY loss: left
|
||||
// at the window's start, the window tumbled instead of rolling, and any loss period longer
|
||||
// than half the window reset the budget on every second loss (measured: 200 losses 70 s apart
|
||||
// → 200 reclaims, never an error).
|
||||
if (now - this.reclaims.at > RECLAIM_WINDOW_MS) this.reclaims.n = 0;
|
||||
this.reclaims.at = now;
|
||||
if (this.reclaims.n >= MAX_SESSION_RECLAIMS) {
|
||||
this.set({ error: "generic" });
|
||||
return;
|
||||
}
|
||||
this.reclaims.n += 1;
|
||||
// The server dropped it already; nothing to stop.
|
||||
this.attachedSession = null;
|
||||
this.start(req.id, this.playhead(), this.wantsPlay(media), quiet);
|
||||
}
|
||||
|
||||
/** The server is away (see `AWAY_WINDOW_MS`): ask for `req`'s item again where the viewer is,
|
||||
* after a delay that grows with each try. False once it has been away too long — the caller then
|
||||
* says it cannot play. A restart the viewer asks for meanwhile (a seek, another item) replaces the
|
||||
@@ -548,9 +569,10 @@ export class HlsEngine {
|
||||
const rel = T - this.sessionStart.current;
|
||||
// Native only when the attached media IS the current session. While one is still being asked
|
||||
// for, `sessionStart` and `seekable` describe the OLD one: a native seek there left the pending
|
||||
// restart current, and its answer then jumped to the earlier target.
|
||||
// restart current, and its answer then jumped to the earlier target. A quiet request leaves
|
||||
// `live` alone, so `pending` is what says one is out.
|
||||
const end = media.seekable.length ? media.seekable.end(0) : 0;
|
||||
if (this.live && rel >= 0 && rel <= end + 0.5) {
|
||||
if (this.live && !this.pending && rel >= 0 && rel <= end + 0.5) {
|
||||
media.currentTime = rel; // keeps playing on its own
|
||||
if (play) media.play().catch(() => {});
|
||||
} else {
|
||||
|
||||
@@ -93,6 +93,24 @@ describe("isTypingTarget", () => {
|
||||
it("is false on ordinary content", () => {
|
||||
expect(isTypingTarget(press({ key: "a" }))).toBe(false);
|
||||
});
|
||||
|
||||
it("is false on a box, where no letter types: the page's keys go on working after a tick", () => {
|
||||
for (const type of ["checkbox", "radio"]) {
|
||||
const el = document.createElement("input");
|
||||
el.type = type;
|
||||
document.body.append(el);
|
||||
expect(isTypingTarget(press({ key: "a" }, el))).toBe(false);
|
||||
el.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("stays true on a slider, whose arrows are its own", () => {
|
||||
const el = document.createElement("input");
|
||||
el.type = "range";
|
||||
document.body.append(el);
|
||||
expect(isTypingTarget(press({ key: "ArrowLeft" }, el))).toBe(true);
|
||||
el.remove();
|
||||
});
|
||||
});
|
||||
|
||||
describe("isActivationTarget", () => {
|
||||
@@ -101,6 +119,11 @@ describe("isActivationTarget", () => {
|
||||
document.body.append(btn);
|
||||
expect(isActivationTarget(press({ key: " " }, btn))).toBe(true);
|
||||
btn.remove();
|
||||
const box = document.createElement("input");
|
||||
box.type = "checkbox";
|
||||
document.body.append(box);
|
||||
expect(isActivationTarget(press({ key: " " }, box))).toBe(true);
|
||||
box.remove();
|
||||
expect(isActivationTarget(press({ key: " " }))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -33,6 +33,7 @@ export type KeyScope =
|
||||
| "search"
|
||||
| "list"
|
||||
| "listDelete"
|
||||
| "listSelect"
|
||||
| "undo"
|
||||
| "contextMenu"
|
||||
| "ytPlayer"
|
||||
@@ -46,6 +47,7 @@ const PAGE_LEVEL: ReadonlySet<KeyScope> = new Set<KeyScope>([
|
||||
"search",
|
||||
"list",
|
||||
"listDelete",
|
||||
"listSelect",
|
||||
]);
|
||||
/** True for a scope that acts on the page beneath the overlays (see `KeyScope`). */
|
||||
export const isPageLevelScope = (scope: KeyScope): boolean => PAGE_LEVEL.has(scope);
|
||||
@@ -138,6 +140,15 @@ export const SHORTCUTS = [
|
||||
// Its own scope beside `list`: only a list that can take an item out (a playlist's rows) registers
|
||||
// it, so the sheet does not promise Delete on the feed or a Plex grid, where nothing answers it.
|
||||
{ id: "remove", scope: "listDelete", keys: ["Delete"], labelKey: "keys.listRemove" },
|
||||
// …and only a list whose rows can be selected registers these. Escape stays quiet in a field: the
|
||||
// field's own Escape comes first, and a selection is not what the reader is in while typing.
|
||||
{ id: "select", scope: "listSelect", keys: ["x"], labelKey: "keys.listSelect" },
|
||||
{
|
||||
id: "clearSelection",
|
||||
scope: "listSelect",
|
||||
keys: ["Escape"],
|
||||
labelKey: "keys.listClearSelection",
|
||||
},
|
||||
// --- the row context menu (wherever useContextMenu is wired) ---------------------------------
|
||||
// Its OWN scope, not `global`: only the surfaces that actually call `useContextMenu` register it,
|
||||
// so the sheet stops advertising "Open the context menu" on the feed, Plex, Downloads and Settings
|
||||
@@ -264,15 +275,22 @@ export function isTypingTarget(e: KeyboardEvent): boolean {
|
||||
const el = (e.target as HTMLElement | null) ?? (document.activeElement as HTMLElement | null);
|
||||
if (!el) return false;
|
||||
const tag = (el.tagName || "").toLowerCase();
|
||||
// A box takes no letters, and a click on a table row's box leaves the focus on it: `j` went dead
|
||||
// there. A slider stays a field, as its arrows are its own.
|
||||
if (isBox(el)) return false;
|
||||
return tag === "input" || tag === "textarea" || tag === "select" || !!el.isContentEditable;
|
||||
}
|
||||
|
||||
function isBox(el: HTMLElement | null): boolean {
|
||||
return el instanceof HTMLInputElement && (el.type === "checkbox" || el.type === "radio");
|
||||
}
|
||||
|
||||
/** True while focus is on something Space/Enter activates natively. Both players defer Space to a
|
||||
* focused button ("Skip intro") rather than toggling playback; this is that shared rule. */
|
||||
export function isActivationTarget(e: KeyboardEvent): boolean {
|
||||
const el = (e.target as HTMLElement | null) ?? (document.activeElement as HTMLElement | null);
|
||||
const tag = (el?.tagName || "").toLowerCase();
|
||||
return tag === "button" || tag === "a";
|
||||
return tag === "button" || tag === "a" || isBox(el);
|
||||
}
|
||||
|
||||
/** One printable character that is neither a letter nor a digit (`[`, `]`, `,`). */
|
||||
@@ -462,7 +480,7 @@ export function useActiveScopes(): KeyScope[] {
|
||||
// registers `page` in its own effect, which React runs after every child's — so by mount order
|
||||
// the module jumps would head the sheet, above the list keys of the page you are looking at.
|
||||
const surfaces = live.filter((s) => !isPageLevelScope(s));
|
||||
const pageLevel = (["list", "listDelete", "search", "page"] as const).filter((s) =>
|
||||
const pageLevel = (["list", "listSelect", "listDelete", "search", "page"] as const).filter((s) =>
|
||||
live.includes(s),
|
||||
);
|
||||
return [...surfaces, ...pageLevel, "global"];
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
// @vitest-environment jsdom
|
||||
//
|
||||
// `x` selects the walked item and Esc clears, in a list that takes a selection (a playlist's rows).
|
||||
// Its own file: listNav keeps module state.
|
||||
import { useRef } from "react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, render, screen, waitFor } from "@testing-library/react";
|
||||
import { followRemoval, navItemAttrs, useListNav, type NavSelection } from "./listNav";
|
||||
import { useActiveScopes } from "./keymap";
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
function Rows({
|
||||
selection,
|
||||
onDelete,
|
||||
rows = 3,
|
||||
}: {
|
||||
selection?: NavSelection;
|
||||
onDelete?: (index: number) => void;
|
||||
rows?: number;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useListNav(ref, { enabled: true, selection, onDelete });
|
||||
return (
|
||||
<div ref={ref}>
|
||||
{Array.from({ length: rows }, (_, i) => (
|
||||
<div key={i} {...navItemAttrs(i)} data-testid={`r${i}`}>
|
||||
<button data-testid={`r${i}-action`}>action</button>
|
||||
<input data-testid={`r${i}-input`} />
|
||||
<input type="checkbox" data-testid={`r${i}-box`} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Scopes() {
|
||||
return <output data-testid="scopes">{useActiveScopes().join(" ")}</output>;
|
||||
}
|
||||
|
||||
function press(key: string, init: KeyboardEventInit = {}): KeyboardEvent {
|
||||
const e = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...init });
|
||||
(document.activeElement ?? document.body).dispatchEvent(e);
|
||||
return e;
|
||||
}
|
||||
|
||||
const selection = (cleared = true) => ({
|
||||
toggle: vi.fn<(index: number) => void>(),
|
||||
clear: vi.fn(() => cleared),
|
||||
removeSelected: vi.fn(() => false),
|
||||
});
|
||||
|
||||
describe("useListNav · selecting", () => {
|
||||
it("toggles the walked item on x", () => {
|
||||
const s = selection();
|
||||
render(<Rows selection={s} />);
|
||||
press("j");
|
||||
press("j");
|
||||
const e = press("x");
|
||||
expect(s.toggle).toHaveBeenCalledExactlyOnceWith(1);
|
||||
expect(e.defaultPrevented).toBe(true);
|
||||
});
|
||||
|
||||
it("toggles the item a control inside it holds the focus for", () => {
|
||||
const s = selection();
|
||||
render(<Rows selection={s} />);
|
||||
screen.getByTestId("r2-action").focus();
|
||||
press("x");
|
||||
expect(s.toggle).toHaveBeenCalledExactlyOnceWith(2);
|
||||
});
|
||||
|
||||
it("goes on answering with the focus on the row's box, where a click leaves it", () => {
|
||||
const s = selection();
|
||||
render(<Rows selection={s} />);
|
||||
screen.getByTestId("r1-box").focus();
|
||||
press("x");
|
||||
expect(s.toggle).toHaveBeenCalledExactlyOnceWith(1);
|
||||
press("j");
|
||||
expect(document.activeElement).toBe(screen.getByTestId("r2"));
|
||||
});
|
||||
|
||||
it("does nothing on x with no item under the keyboard", () => {
|
||||
const s = selection();
|
||||
render(<Rows selection={s} />);
|
||||
const e = press("x");
|
||||
expect(s.toggle).not.toHaveBeenCalled();
|
||||
expect(e.defaultPrevented).toBe(false);
|
||||
});
|
||||
|
||||
it("types an x in a field instead of selecting", () => {
|
||||
const s = selection();
|
||||
render(<Rows selection={s} />);
|
||||
screen.getByTestId("r0-input").focus();
|
||||
press("x");
|
||||
expect(s.toggle).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not flip back and forth while x is held down", () => {
|
||||
const s = selection();
|
||||
render(<Rows selection={s} />);
|
||||
press("j");
|
||||
press("x");
|
||||
press("x", { repeat: true });
|
||||
expect(s.toggle).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("clears on Esc wherever the focus is, and spends the key only when it cleared", () => {
|
||||
const s = selection();
|
||||
render(<Rows selection={s} />);
|
||||
expect(press("Escape").defaultPrevented).toBe(true);
|
||||
expect(s.clear).toHaveBeenCalledTimes(1);
|
||||
cleanup();
|
||||
|
||||
const idle = selection(false);
|
||||
render(<Rows selection={idle} />);
|
||||
expect(press("Escape").defaultPrevented).toBe(false);
|
||||
expect(idle.clear).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("takes the slot of an item that left by other hands, the focus on <body>", async () => {
|
||||
render(<Rows />);
|
||||
const leaving = screen.getByTestId("r1");
|
||||
followRemoval(screen.getByTestId("r1-action"));
|
||||
const list = leaving.parentElement!;
|
||||
list.removeChild(leaving);
|
||||
list.querySelector<HTMLElement>("[data-testid=r2]")!.setAttribute("data-nav-index", "1");
|
||||
await waitFor(() => expect(document.activeElement).toBe(screen.getByTestId("r2")));
|
||||
});
|
||||
|
||||
it("goes on to the next row left, past what a selection took from above it", async () => {
|
||||
const s = selection();
|
||||
s.removeSelected.mockImplementation(() => {
|
||||
// As a commit does it, after the key's handler: the two rows go, and the ones left are numbered
|
||||
// from the top.
|
||||
queueMicrotask(() => {
|
||||
screen.getByTestId("r0").remove();
|
||||
screen.getByTestId("r1").remove();
|
||||
screen.getByTestId("r2").setAttribute("data-nav-index", "0");
|
||||
screen.getByTestId("r3").setAttribute("data-nav-index", "1");
|
||||
});
|
||||
return true;
|
||||
});
|
||||
render(<Rows selection={s} rows={4} />);
|
||||
const r2 = screen.getByTestId("r2");
|
||||
screen.getByTestId("r1-box").focus();
|
||||
press("Delete");
|
||||
await waitFor(() => expect(document.activeElement).toBe(r2));
|
||||
});
|
||||
|
||||
it("leaves the focus where it is when something else took it meanwhile", async () => {
|
||||
render(<Rows />);
|
||||
const leaving = screen.getByTestId("r1");
|
||||
const other = screen.getByTestId("r0-input");
|
||||
other.focus();
|
||||
followRemoval(screen.getByTestId("r1-action"));
|
||||
leaving.remove();
|
||||
await new Promise((r) => setTimeout(r, 60));
|
||||
expect(document.activeElement).toBe(other);
|
||||
});
|
||||
|
||||
it("has Delete go to the selection first, wherever the focus is", () => {
|
||||
const s = selection();
|
||||
s.removeSelected.mockReturnValue(true);
|
||||
const onDelete = vi.fn();
|
||||
render(<Rows selection={s} onDelete={onDelete} />);
|
||||
expect(press("Delete").defaultPrevented).toBe(true);
|
||||
expect(s.removeSelected).toHaveBeenCalledTimes(1);
|
||||
expect(onDelete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("has Delete go on to the walked row when there is no selection", () => {
|
||||
const s = selection();
|
||||
const onDelete = vi.fn();
|
||||
render(<Rows selection={s} onDelete={onDelete} />);
|
||||
press("j");
|
||||
press("Delete");
|
||||
expect(onDelete).toHaveBeenCalledExactlyOnceWith(0);
|
||||
});
|
||||
|
||||
it("leaves both keys alone in a list that takes no selection", () => {
|
||||
render(<Rows />);
|
||||
press("j");
|
||||
expect(press("x").defaultPrevented).toBe(false);
|
||||
expect(press("Escape").defaultPrevented).toBe(false);
|
||||
});
|
||||
|
||||
it("lists the keys only over a list that takes a selection and has items", async () => {
|
||||
render(
|
||||
<>
|
||||
<Scopes />
|
||||
<Rows selection={selection()} />
|
||||
</>,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByTestId("scopes").textContent).toContain("listSelect"));
|
||||
cleanup();
|
||||
render(
|
||||
<>
|
||||
<Scopes />
|
||||
<Rows />
|
||||
</>,
|
||||
);
|
||||
await waitFor(() => expect(screen.getByTestId("scopes").textContent).toContain("list"));
|
||||
expect(screen.getByTestId("scopes").textContent).not.toContain("listSelect");
|
||||
});
|
||||
});
|
||||
@@ -36,6 +36,18 @@ interface NavList {
|
||||
readonly reveal: (index: number) => void;
|
||||
/** Takes the item at `index` out of the list (Delete), or null for a list that cannot. */
|
||||
readonly remove: () => ((index: number) => void) | null;
|
||||
/** The list's selection (`x`, Esc), or null for a list whose items cannot be selected. */
|
||||
readonly selection: () => NavSelection | null;
|
||||
}
|
||||
|
||||
/** What `x` and Esc do in a list whose items can be selected. `clear` says whether it cleared
|
||||
* anything: an Esc that did not is left for whoever else answers it. */
|
||||
export interface NavSelection {
|
||||
readonly toggle: (index: number) => void;
|
||||
readonly clear: () => boolean;
|
||||
/** Delete: takes the selection out, wherever the focus is. False when there is none, and Delete
|
||||
* goes on to the item under the keyboard. */
|
||||
readonly removeSelected: () => boolean;
|
||||
}
|
||||
|
||||
const lists = new Map<HTMLElement, NavList>();
|
||||
@@ -423,6 +435,12 @@ function onKey(e: KeyboardEvent): void {
|
||||
// On the item root, like Enter — and only in a list that registered a remover.
|
||||
remove: (ev) => {
|
||||
const cur = current();
|
||||
for (const list of ordered()) {
|
||||
if (!list.selection()?.removeSelected()) continue;
|
||||
ev.preventDefault();
|
||||
if (cur) refocusSlot(cur.list, cur.index, cur.item);
|
||||
return;
|
||||
}
|
||||
const remove = cur?.list.remove();
|
||||
if (!cur || !remove || document.activeElement !== cur.item) return;
|
||||
ev.preventDefault();
|
||||
@@ -432,15 +450,40 @@ function onKey(e: KeyboardEvent): void {
|
||||
},
|
||||
{ inTopLayer },
|
||||
);
|
||||
dispatch(
|
||||
e,
|
||||
"listSelect",
|
||||
{
|
||||
// Anywhere in the item, unlike Delete: a tick is undone by the same key, and after a click on
|
||||
// the box the focus sits inside the row. Held down, it must not flip back and forth.
|
||||
select: (ev) => {
|
||||
const cur = current();
|
||||
const selection = cur?.list.selection();
|
||||
if (!cur || !selection || ev.repeat) return;
|
||||
ev.preventDefault();
|
||||
selection.toggle(cur.index);
|
||||
},
|
||||
clearSelection: (ev) => {
|
||||
let cleared = false;
|
||||
for (const list of ordered()) if (list.selection()?.clear()) cleared = true;
|
||||
if (cleared) ev.preventDefault();
|
||||
},
|
||||
},
|
||||
{ inTopLayer },
|
||||
);
|
||||
}
|
||||
|
||||
// How long a removal gets to take its row out of the DOM before the focus gives up following it.
|
||||
const REMOVE_FRAMES = 30;
|
||||
|
||||
/** After the focused item was removed, focus the item now in its slot (the next one; the new last
|
||||
* when it was the last), so a second Delete takes the next row — the way a mail list behaves. Only
|
||||
* while nothing else took the focus meanwhile: the removal fell back to <body>, nothing more. */
|
||||
/** After the focused item was removed, focus the item that followed it and is still there (the new
|
||||
* last when none is), so a second Delete takes the next row — the way a mail list behaves. By element:
|
||||
* rows a selection took from above it would shift an index past the ones left. Only while nothing else
|
||||
* took the focus meanwhile: the removal fell back to <body>, nothing more. */
|
||||
function refocusSlot(list: NavList, index: number, removed: HTMLElement): void {
|
||||
const items = ownItems(list.el);
|
||||
const at = items.indexOf(removed);
|
||||
const after = at < 0 ? [] : items.slice(at + 1);
|
||||
let frames = 0;
|
||||
const wait = () => {
|
||||
if (removed.isConnected) {
|
||||
@@ -448,12 +491,24 @@ function refocusSlot(list: NavList, index: number, removed: HTMLElement): void {
|
||||
return;
|
||||
}
|
||||
if (!focusIsUnclaimed()) return;
|
||||
const next = after.find((el) => el.isConnected);
|
||||
if (next) return focusItem(next);
|
||||
const n = list.count();
|
||||
if (n > 0) focusIndex(list, Math.min(index, n - 1));
|
||||
};
|
||||
requestAnimationFrame(wait);
|
||||
}
|
||||
|
||||
/** The item holding `el` is leaving its list by other hands than Delete (a drag out of it): the focus
|
||||
* takes its slot all the same, not <body>. By element, as a click on a button leaves the focus
|
||||
* elsewhere in Safari. */
|
||||
export function followRemoval(el: Element): void {
|
||||
const item = el.closest<HTMLElement>(`[${INDEX}]`);
|
||||
const list =
|
||||
item && lists.get(item.parentElement?.closest<HTMLElement>(`[${LIST}]`) as HTMLElement);
|
||||
if (item && list) refocusSlot(list, indexOf(item), item);
|
||||
}
|
||||
|
||||
// ── The item a view was left from ────────────────────────────────────────────────────────────────
|
||||
// Opening something that switches the page or the view — a Plex title from Home's rail, a channel from
|
||||
// the Channels table — unmounts the list the keyboard was on, so Back used to hand focus to <body> and
|
||||
@@ -599,6 +654,8 @@ export function useListNav(
|
||||
reveal?: (index: number) => void;
|
||||
/** A list whose items the Delete key takes out (a playlist's rows): the item's index. */
|
||||
onDelete?: (index: number) => void;
|
||||
/** A list whose items can be selected, by `x` and Esc. */
|
||||
selection?: NavSelection;
|
||||
},
|
||||
): void {
|
||||
// Read when a key is pressed, so the registration below never re-runs for a new `opts` object.
|
||||
@@ -609,6 +666,7 @@ export function useListNav(
|
||||
const [hasItems, setHasItems] = useState(false);
|
||||
useKeyScope("list", opts.enabled && hasItems);
|
||||
useKeyScope("listDelete", opts.enabled && hasItems && !!opts.onDelete);
|
||||
useKeyScope("listSelect", opts.enabled && hasItems && !!opts.selection);
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!opts.enabled || !el) return;
|
||||
@@ -618,6 +676,7 @@ export function useListNav(
|
||||
cols: () => latestOpts().cols ?? measuredCols(el),
|
||||
reveal: (i) => latestOpts().reveal?.(i),
|
||||
remove: () => latestOpts().onDelete ?? null,
|
||||
selection: () => latestOpts().selection ?? null,
|
||||
});
|
||||
el.setAttribute(LIST, "");
|
||||
const check = () => setHasItems(el.querySelector(`[${INDEX}]`) !== null);
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// @vitest-environment jsdom
|
||||
//
|
||||
// An auto-skip's countdown starts below zero: the wait before it, while the Skip button already
|
||||
// shows. The bar it draws must read empty through the wait, not a negative width.
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { skipCountdown } from "./plexPlayerHooks";
|
||||
|
||||
describe("skipCountdown", () => {
|
||||
it("stays empty through the wait, runs over the delay, and stops at full", () => {
|
||||
expect(skipCountdown(-3, 5)).toBe(0);
|
||||
expect(skipCountdown(-0.1, 5)).toBe(0);
|
||||
expect(skipCountdown(2.5, 5)).toBe(0.5);
|
||||
expect(skipCountdown(7, 5)).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -434,6 +434,19 @@ export function usePlayerVolume(opts: {
|
||||
return { setVol, nudgeVolume, toggleMute, onWheel };
|
||||
}
|
||||
|
||||
// How long a marker plays before an auto-skip's countdown starts (seconds), at most: on a marker
|
||||
// too short for both, the wait gives way, so the countdown still ends inside it (`useAutoSkip`).
|
||||
const AUTO_SKIP_WAIT_S = 3;
|
||||
// What the countdown keeps in hand before the marker's end: it ticks on wall time, the playhead on
|
||||
// the media's, and the marker stops counting a second before its end.
|
||||
const AUTO_SKIP_SLACK_S = 0.5;
|
||||
|
||||
/** How far an auto-skip's countdown has run (0→1) after `elapsed` playing seconds of it. Through
|
||||
* the wait `elapsed` is below zero, and the bar it draws stays empty: a negative width is invalid
|
||||
* CSS, which the browser drops and keeps whatever it drew before. */
|
||||
export const skipCountdown = (elapsed: number, delay: number) =>
|
||||
Math.max(0, Math.min(1, elapsed / delay));
|
||||
|
||||
// Auto-skip intro/credits. Entering a marker whose auto-skip is on runs a countdown (skipProgress
|
||||
// 0→1 over autoSkipDelay s, shown on the Skip button); on completion it skips — to the marker end, or
|
||||
// for the credits that end the item to the next item (binge). Which credits those are, and which the
|
||||
@@ -481,6 +494,7 @@ export function useAutoSkip(opts: {
|
||||
(m) => abs >= m.start_s && abs < m.end_s - 1,
|
||||
);
|
||||
const activeMarkerRef = useLatest(activeMarker);
|
||||
const absRef = useLatest(abs);
|
||||
// A boolean, not the list, goes into the countdown's deps: a refetch hands back an equal-but-new
|
||||
// list and must not restart a countdown under way (see below); doSkip reads the list from a ref.
|
||||
const activeAuto = activeMarker != null && markerSkip(activeMarker, markers ?? []).auto;
|
||||
@@ -538,14 +552,19 @@ export function useAutoSkip(opts: {
|
||||
const enabled = (m.type === "intro" ? autoSkipIntro : autoSkipCredits) && activeAuto;
|
||||
if (!enabled || suspended || cancelledMarkerRef.current === key) return setSkipProgress(null);
|
||||
if (autoSkipDelay <= 0) return doSkip(m); // immediate
|
||||
let elapsed = 0;
|
||||
// Below zero is the wait: time to see where the marker has landed and press the button, which
|
||||
// shows from the start, before anything counts down to leaving. A delay of 0 asked for none.
|
||||
// It is cut to what the marker has left over the countdown (a short intro, or one resumed near
|
||||
// its end): a wait the countdown cannot finish after is an auto-skip that never fires.
|
||||
const left = m.end_s - 1 - absRef.current - autoSkipDelay - AUTO_SKIP_SLACK_S;
|
||||
let elapsed = -Math.max(0, Math.min(AUTO_SKIP_WAIT_S, left));
|
||||
setSkipProgress(0);
|
||||
const iv = window.setInterval(() => {
|
||||
// Freeze the countdown while the video is paused — otherwise it would fire and auto-seek a
|
||||
// deliberately-paused video. It resumes from where it stopped when playback resumes.
|
||||
if (videoRef.current?.paused) return;
|
||||
elapsed += 0.1;
|
||||
const p = Math.min(1, elapsed / autoSkipDelay);
|
||||
const p = skipCountdown(elapsed, autoSkipDelay);
|
||||
setSkipProgress(p);
|
||||
if (p >= 1) {
|
||||
window.clearInterval(iv);
|
||||
@@ -568,6 +587,7 @@ export function useAutoSkip(opts: {
|
||||
doSkip,
|
||||
videoRef,
|
||||
activeMarkerRef,
|
||||
absRef,
|
||||
activeAuto,
|
||||
]);
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { clear, events } from "./log";
|
||||
import { retryLostStylesheets } from "./stylesheetRetry";
|
||||
|
||||
const LOADED = { cssRules: [{}] };
|
||||
// A lost stylesheet still has a `sheet`, and reading its rules throws (measured: Chromium, WebKit).
|
||||
const LOST = {
|
||||
get cssRules(): never {
|
||||
throw new DOMException("Cannot access rules", "SecurityError");
|
||||
},
|
||||
};
|
||||
|
||||
function link(href: string, loaded: boolean, sheet: unknown = loaded ? LOADED : LOST) {
|
||||
const el = document.createElement("link");
|
||||
el.rel = "stylesheet";
|
||||
el.href = href;
|
||||
el.setAttribute("crossorigin", "");
|
||||
Object.defineProperty(el, "sheet", { value: sheet, configurable: true });
|
||||
document.head.append(el);
|
||||
return el;
|
||||
}
|
||||
|
||||
const links = () => [...document.head.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]')];
|
||||
const logged = () => events().map((e) => e.event);
|
||||
|
||||
describe("retryLostStylesheets", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
clear();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
document.head.innerHTML = "";
|
||||
});
|
||||
|
||||
it("leaves a loaded stylesheet alone", () => {
|
||||
const fine = link("/a.css", true);
|
||||
retryLostStylesheets();
|
||||
vi.runAllTimers();
|
||||
expect(links()).toEqual([fine]);
|
||||
expect(logged()).toEqual([]);
|
||||
});
|
||||
|
||||
it("asks again for a lost one, in its place, keeping its attributes", () => {
|
||||
const first = link("/a.css", true);
|
||||
const lost = link("/b.css", false);
|
||||
const last = link("/c.css", true);
|
||||
retryLostStylesheets();
|
||||
vi.advanceTimersByTime(0);
|
||||
const [a, b, c] = links();
|
||||
expect(a).toBe(first);
|
||||
expect(b).not.toBe(lost);
|
||||
expect(b!.getAttribute("href")).toBe("/b.css");
|
||||
expect(b!.hasAttribute("crossorigin")).toBe(true);
|
||||
expect(c).toBe(last);
|
||||
expect(logged()).toEqual(["app.stylesheet_lost"]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["no sheet at all", null],
|
||||
["an empty sheet", { cssRules: [] }],
|
||||
])("takes a link with %s for lost too", (_, sheet) => {
|
||||
const lost = link("/a.css", false, sheet);
|
||||
retryLostStylesheets();
|
||||
vi.advanceTimersByTime(0);
|
||||
expect(links()[0]).not.toBe(lost);
|
||||
});
|
||||
|
||||
it("says so once the new request has loaded", () => {
|
||||
link("/a.css", false);
|
||||
retryLostStylesheets();
|
||||
vi.advanceTimersByTime(0);
|
||||
links()[0]!.dispatchEvent(new Event("load"));
|
||||
vi.runAllTimers();
|
||||
expect(logged()).toEqual(["app.stylesheet_lost", "app.stylesheet_recovered"]);
|
||||
});
|
||||
|
||||
it("waits longer each time and then gives up, reporting it", () => {
|
||||
link("/a.css", false);
|
||||
retryLostStylesheets();
|
||||
const fail = () => links()[0]!.dispatchEvent(new Event("error"));
|
||||
|
||||
vi.advanceTimersByTime(0);
|
||||
const second = links()[0];
|
||||
fail();
|
||||
vi.advanceTimersByTime(999);
|
||||
expect(links()[0]).toBe(second);
|
||||
vi.advanceTimersByTime(1);
|
||||
const third = links()[0];
|
||||
expect(third).not.toBe(second);
|
||||
|
||||
fail();
|
||||
vi.advanceTimersByTime(2999);
|
||||
expect(links()[0]).toBe(third);
|
||||
vi.advanceTimersByTime(1);
|
||||
const fourth = links()[0];
|
||||
expect(fourth).not.toBe(third);
|
||||
|
||||
fail();
|
||||
vi.runAllTimers();
|
||||
expect(links()[0]).toBe(fourth);
|
||||
expect(logged()).toEqual(["app.stylesheet_lost", "app.stylesheet_gave_up"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
// A stylesheet can be lost on the way (a poor line, a loaded machine), and a browser never asks again
|
||||
// for one by itself: the page then stays unstyled until a reload, every control a bare browser button.
|
||||
// A module script waits for the document's stylesheets (measured: a sheet held 3 s held the module
|
||||
// too), so by the time this runs each link has either loaded or failed, and no event is left to wait
|
||||
// for. A lost one is asked for again in its own place, so the cascade's order stays as it was built.
|
||||
//
|
||||
// All of these sheets are this site's own: reading the rules of a loaded one is allowed, so a throw
|
||||
// says it failed (measured: Chromium, WebKit). Three tries, then the page stays as it is. A reload here
|
||||
// could loop, and the unstyled page still works.
|
||||
import { log } from "./log";
|
||||
|
||||
const RETRY_AFTER_MS = [0, 1000, 3000];
|
||||
|
||||
function holdsRules(link: HTMLLinkElement): boolean {
|
||||
try {
|
||||
return (link.sheet?.cssRules.length ?? 0) > 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function askAgain(link: HTMLLinkElement, attempt: number): void {
|
||||
const wait = RETRY_AFTER_MS[attempt];
|
||||
if (wait === undefined) {
|
||||
log.error("app.stylesheet_gave_up", "a stylesheet could not be loaded", { href: link.href });
|
||||
return;
|
||||
}
|
||||
window.setTimeout(() => {
|
||||
const next = link.cloneNode(false) as HTMLLinkElement;
|
||||
next.addEventListener("load", () =>
|
||||
log.info("app.stylesheet_recovered", "a lost stylesheet loaded on a new request", {
|
||||
href: next.href,
|
||||
attempt: attempt + 1,
|
||||
}),
|
||||
);
|
||||
next.addEventListener("error", () => askAgain(next, attempt + 1));
|
||||
link.replaceWith(next);
|
||||
}, wait);
|
||||
}
|
||||
|
||||
/** Run once, from a page's entry module. */
|
||||
export function retryLostStylesheets(): void {
|
||||
for (const link of document.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]')) {
|
||||
if (holdsRules(link)) continue;
|
||||
log.warn("app.stylesheet_lost", "a stylesheet was lost on the way; asking again", {
|
||||
href: link.href,
|
||||
});
|
||||
askAgain(link, 0);
|
||||
}
|
||||
}
|
||||
@@ -21,9 +21,23 @@ describe("a subscription change", () => {
|
||||
qk.feedSummary(),
|
||||
qk.discoveredChannels(),
|
||||
qk.watchedChannels(),
|
||||
qk.tags(),
|
||||
]);
|
||||
});
|
||||
|
||||
// A tag counts the followed channels it is on, not hidden: a hide changes the number as an
|
||||
// unsubscribe does, and both places that hide a channel must refresh it.
|
||||
it("a hide refreshes the tags wherever it is made", () => {
|
||||
const root = new URL("../", import.meta.url);
|
||||
const sites = readdirSync(root, { recursive: true, encoding: "utf8" })
|
||||
.map((f) => f.split("\\").join("/"))
|
||||
.filter((f) => f.endsWith(".tsx") && !f.includes(".test.") && !f.startsWith("design-lab/"))
|
||||
.map((f) => [f, readFileSync(new URL(f, root), "utf8")] as const)
|
||||
.filter(([, src]) => /api\.updateChannel\([^)]*hidden/.test(src));
|
||||
expect(sites.length).toBeGreaterThanOrEqual(2);
|
||||
for (const [f, src] of sites) expect(src, f).toContain("queryKey: qk.tags()");
|
||||
});
|
||||
|
||||
it("is refreshed through that one function wherever it is made", () => {
|
||||
const root = new URL("../", import.meta.url);
|
||||
const sites = readdirSync(root, { recursive: true, encoding: "utf8" })
|
||||
|
||||
@@ -3,8 +3,8 @@ import type { QueryClient } from "@tanstack/react-query";
|
||||
import { qk } from "./queryKeys";
|
||||
|
||||
/** Everything a subscribe or an unsubscribe changes: the channel itself, the manager's list and its
|
||||
* counts, the feed and its facets (the channel's videos come or go), and the two discovery lists (a
|
||||
* subscribed channel leaves them). ONE set for every site that makes the change: each used to keep
|
||||
* counts, the feed and its facets (the channel's videos come or go), the two discovery lists (a
|
||||
* subscribed channel leaves them), and the tags (a tag counts the followed channels it is on). ONE set for every site that makes the change: each used to keep
|
||||
* its own list, and each list missed something. */
|
||||
export function invalidateSubscription(qc: QueryClient, channelId: string): void {
|
||||
for (const queryKey of [
|
||||
@@ -15,6 +15,7 @@ export function invalidateSubscription(qc: QueryClient, channelId: string): void
|
||||
qk.feedSummary(),
|
||||
qk.discoveredChannels(),
|
||||
qk.watchedChannels(),
|
||||
qk.tags(),
|
||||
])
|
||||
void qc.invalidateQueries({ queryKey });
|
||||
}
|
||||
|
||||
@@ -24,6 +24,8 @@ type ColumnFilter<T> =
|
||||
export interface Column<T> {
|
||||
key: string;
|
||||
header: string;
|
||||
// A header that is a control of its own (the box that selects every row), in place of `header`.
|
||||
headerCell?: ReactNode;
|
||||
render: (row: T) => ReactNode;
|
||||
align?: "left" | "right" | "center";
|
||||
width?: string;
|
||||
@@ -49,6 +51,9 @@ export interface Column<T> {
|
||||
// one beside a panel: a secondary column that gives its room back to the name (the owner,
|
||||
// 2026-09-27: at 1024 the channel name had 60 px while About took as much). Same `@container` rule.
|
||||
tabletHidden?: boolean;
|
||||
// …and one it leaves out while it is narrower than 24rem, a phone beside the nav rail: there the
|
||||
// title kept 44 px. Only for a column whose job has another way (the grip: the row menu's moves).
|
||||
phoneHidden?: boolean;
|
||||
}
|
||||
|
||||
// The classes that hide a column below its width (`narrowHidden` / `tabletHidden`), for its cells and,
|
||||
@@ -69,14 +74,20 @@ const HIDE_BELOW = {
|
||||
col: " hidden @5xl:table-column",
|
||||
cue: " @5xl:hidden",
|
||||
},
|
||||
phone: {
|
||||
cell: " hidden @sm:table-cell",
|
||||
col: " hidden @sm:table-column",
|
||||
cue: " @sm:hidden",
|
||||
},
|
||||
} as const;
|
||||
|
||||
export function columnHideClass(
|
||||
col: { narrowHidden?: boolean; tabletHidden?: boolean },
|
||||
col: { narrowHidden?: boolean; tabletHidden?: boolean; phoneHidden?: boolean },
|
||||
part: "cell" | "col" | "cue" = "cell",
|
||||
): string {
|
||||
if (col.narrowHidden) return HIDE_BELOW.narrow[part];
|
||||
if (col.tabletHidden) return HIDE_BELOW.tablet[part];
|
||||
if (col.phoneHidden) return HIDE_BELOW.phone[part];
|
||||
return "";
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,11 @@ export function useChannelTagActions(opts: {
|
||||
? api.detachChannelTag(channelId, tagId)
|
||||
: api.attachChannelTag(channelId, tagId);
|
||||
call
|
||||
.then(() => opts.onSuccess?.(channelId))
|
||||
.then(() => {
|
||||
// A tag counts the followed channels it is on: the toggle changed that number.
|
||||
void qc.invalidateQueries({ queryKey: qk.tags() });
|
||||
opts.onSuccess?.(channelId);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
notifyActionError(err, msg("channels.tags.updateFailed"));
|
||||
opts.onError(channelId);
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
// @vitest-environment jsdom
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { useRowSelection } from "./useRowSelection";
|
||||
|
||||
const ABCDE = ["a", "b", "c", "d", "e"];
|
||||
|
||||
function setup(shown = ABCDE, all = ABCDE, scope: unknown = 1) {
|
||||
return renderHook(
|
||||
(p: { all: string[]; shown: string[]; scope: unknown }) =>
|
||||
useRowSelection(p.all, p.shown, p.scope),
|
||||
{ initialProps: { all, shown, scope } },
|
||||
);
|
||||
}
|
||||
|
||||
describe("useRowSelection", () => {
|
||||
it("toggles one row at a time, and says the selected rows in the order shown", () => {
|
||||
const { result } = setup();
|
||||
act(() => result.current.toggle("d"));
|
||||
act(() => result.current.toggle("b"));
|
||||
expect(result.current.shownSelected).toEqual(["b", "d"]);
|
||||
act(() => result.current.toggle("d"));
|
||||
expect(result.current.shownSelected).toEqual(["b"]);
|
||||
expect(result.current.isSelected("b")).toBe(true);
|
||||
expect(result.current.isSelected("d")).toBe(false);
|
||||
});
|
||||
|
||||
it("selects the range from the last row toggled, in either direction", () => {
|
||||
const { result } = setup();
|
||||
act(() => result.current.toggle("b"));
|
||||
act(() => result.current.toggle("d", true));
|
||||
expect(result.current.shownSelected).toEqual(["b", "c", "d"]);
|
||||
act(() => {
|
||||
result.current.clear();
|
||||
});
|
||||
act(() => result.current.toggle("d"));
|
||||
act(() => result.current.toggle("b", true));
|
||||
expect(result.current.shownSelected).toEqual(["b", "c", "d"]);
|
||||
});
|
||||
|
||||
it("takes a range's state from the row the range ends on: it can clear rows too", () => {
|
||||
const { result } = setup();
|
||||
act(() => result.current.toggle("a"));
|
||||
act(() => result.current.toggle("e", true));
|
||||
expect(result.current.shownSelected).toEqual(ABCDE);
|
||||
// `e` is selected, so a range ending on it clears; the anchor moved to `e` with the last click.
|
||||
act(() => result.current.toggle("b", true));
|
||||
expect(result.current.shownSelected).toEqual(["a"]);
|
||||
});
|
||||
|
||||
it("leaves rows outside the range alone", () => {
|
||||
const { result } = setup();
|
||||
act(() => result.current.toggle("a"));
|
||||
act(() => result.current.toggle("c"));
|
||||
act(() => result.current.toggle("e", true));
|
||||
expect(result.current.shownSelected).toEqual(["a", "c", "d", "e"]);
|
||||
});
|
||||
|
||||
it("follows the order on screen, not the stored one", () => {
|
||||
const { result } = setup(["e", "c", "a", "b", "d"]);
|
||||
act(() => result.current.toggle("c"));
|
||||
act(() => result.current.toggle("b", true));
|
||||
expect(result.current.shownSelected).toEqual(["c", "a", "b"]);
|
||||
});
|
||||
|
||||
it("makes a range with no row to start from a plain toggle", () => {
|
||||
const { result } = setup();
|
||||
act(() => result.current.toggle("c", true));
|
||||
expect(result.current.shownSelected).toEqual(["c"]);
|
||||
});
|
||||
|
||||
it("makes a range whose first row a filter hid a plain toggle", () => {
|
||||
const { result, rerender } = setup();
|
||||
act(() => result.current.toggle("a"));
|
||||
rerender({ all: ABCDE, shown: ["c", "d", "e"], scope: 1 });
|
||||
act(() => result.current.toggle("e", true));
|
||||
expect(result.current.shownSelected).toEqual(["e"]);
|
||||
});
|
||||
|
||||
it("has the header box cover the rows shown, and keep what a filter hides", () => {
|
||||
const { result, rerender } = setup();
|
||||
expect(result.current.headerState).toBe("none");
|
||||
act(() => result.current.toggle("a"));
|
||||
expect(result.current.headerState).toBe("some");
|
||||
rerender({ all: ABCDE, shown: ["c", "d"], scope: 1 });
|
||||
// The one selected row is hidden: nothing SHOWN is selected, and acting counts what is shown.
|
||||
expect(result.current.headerState).toBe("none");
|
||||
expect(result.current.shownSelected).toEqual([]);
|
||||
act(() => result.current.toggleAllShown());
|
||||
expect(result.current.headerState).toBe("all");
|
||||
expect(result.current.shownSelected).toEqual(["c", "d"]);
|
||||
act(() => result.current.toggleAllShown());
|
||||
expect(result.current.headerState).toBe("none");
|
||||
rerender({ all: ABCDE, shown: ABCDE, scope: 1 });
|
||||
expect(result.current.shownSelected).toEqual(["a"]);
|
||||
});
|
||||
|
||||
it("selects every row shown from a partial selection", () => {
|
||||
const { result } = setup();
|
||||
act(() => result.current.toggle("b"));
|
||||
act(() => result.current.toggleAllShown());
|
||||
expect(result.current.shownSelected).toEqual(ABCDE);
|
||||
});
|
||||
|
||||
it("has no header state to show over no rows", () => {
|
||||
const { result } = setup([], []);
|
||||
expect(result.current.headerState).toBe("none");
|
||||
act(() => result.current.toggleAllShown());
|
||||
expect(result.current.headerState).toBe("none");
|
||||
});
|
||||
|
||||
it("drops a row that left the list, so it does not come back selected", () => {
|
||||
const { result, rerender } = setup();
|
||||
act(() => result.current.toggle("b"));
|
||||
act(() => result.current.toggle("c"));
|
||||
rerender({ all: ["a", "c", "d", "e"], shown: ["a", "c", "d", "e"], scope: 1 });
|
||||
expect(result.current.shownSelected).toEqual(["c"]);
|
||||
rerender({ all: ABCDE, shown: ABCDE, scope: 1 });
|
||||
expect(result.current.shownSelected).toEqual(["c"]);
|
||||
});
|
||||
|
||||
it("clears on a change of scope, in the render that changes it", () => {
|
||||
const { result, rerender } = setup();
|
||||
act(() => result.current.toggle("a"));
|
||||
// The same videos in another list are not selected there.
|
||||
rerender({ all: ABCDE, shown: ABCDE, scope: 2 });
|
||||
expect(result.current.shownSelected).toEqual([]);
|
||||
act(() => result.current.toggle("c", true));
|
||||
expect(result.current.shownSelected).toEqual(["c"]);
|
||||
});
|
||||
|
||||
it("counts the selected rows a filter hides", () => {
|
||||
const { result, rerender } = setup();
|
||||
act(() => result.current.toggle("a"));
|
||||
act(() => result.current.toggle("c"));
|
||||
expect(result.current.hiddenCount).toBe(0);
|
||||
rerender({ all: ABCDE, shown: ["c", "d"], scope: 1 });
|
||||
expect(result.current.hiddenCount).toBe(1);
|
||||
});
|
||||
|
||||
it("ticks rows again on top of what is selected by then", () => {
|
||||
const { result } = setup();
|
||||
act(() => result.current.toggle("e"));
|
||||
act(() => result.current.select(["a", "b"]));
|
||||
expect(result.current.shownSelected).toEqual(["a", "b", "e"]);
|
||||
});
|
||||
|
||||
it("says whether clearing did anything", () => {
|
||||
const { result } = setup();
|
||||
let cleared = true;
|
||||
act(() => {
|
||||
cleared = result.current.clear();
|
||||
});
|
||||
expect(cleared).toBe(false);
|
||||
act(() => result.current.toggle("a"));
|
||||
act(() => {
|
||||
cleared = result.current.clear();
|
||||
});
|
||||
expect(cleared).toBe(true);
|
||||
expect(result.current.shownSelected).toEqual([]);
|
||||
});
|
||||
|
||||
it("counts a selected row a filter hides as something to clear", () => {
|
||||
const { result, rerender } = setup();
|
||||
act(() => result.current.toggle("a"));
|
||||
rerender({ all: ABCDE, shown: ["c"], scope: 1 });
|
||||
let cleared = false;
|
||||
act(() => {
|
||||
cleared = result.current.clear();
|
||||
});
|
||||
expect(cleared).toBe(true);
|
||||
rerender({ all: ABCDE, shown: ABCDE, scope: 1 });
|
||||
expect(result.current.shownSelected).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import { useState } from "react";
|
||||
|
||||
const NONE: ReadonlySet<string> = new Set();
|
||||
|
||||
/** Which rows of a table are ticked, for the bulk actions over them. `all` is every row the list
|
||||
* holds and `shown` the ones on screen, in screen order. A row a filter hides stays selected and
|
||||
* comes back ticked, but `shownSelected`, what an action covers, leaves it out: nothing happens to a
|
||||
* row the reader cannot see. A row that left the list drops out for good, or an Undo would bring it
|
||||
* back ticked. A change of `scope` starts over: the same video in another list is another row. */
|
||||
export function useRowSelection(all: readonly string[], shown: readonly string[], scope: unknown) {
|
||||
const [selected, setSelected] = useState(NONE);
|
||||
// The last row toggled: where a Shift range starts.
|
||||
const [anchor, setAnchor] = useState<string | null>(null);
|
||||
|
||||
const [selectedFor, setSelectedFor] = useState(scope);
|
||||
if (selectedFor !== scope) {
|
||||
setSelectedFor(scope);
|
||||
setSelected(NONE);
|
||||
setAnchor(null);
|
||||
}
|
||||
const held = new Set(all);
|
||||
const kept = [...selected].filter((id) => held.has(id));
|
||||
if (kept.length !== selected.size) setSelected(new Set(kept));
|
||||
|
||||
const shownSelected = shown.filter((id) => selected.has(id));
|
||||
|
||||
function toggle(id: string, range = false) {
|
||||
const on = !selected.has(id);
|
||||
const from = range && anchor != null ? shown.indexOf(anchor) : -1;
|
||||
const to = shown.indexOf(id);
|
||||
// Taken from where the range ends, the way a mail list does: it can clear a run of rows too.
|
||||
const rows =
|
||||
from >= 0 && to >= 0 ? shown.slice(Math.min(from, to), Math.max(from, to) + 1) : [id];
|
||||
const next = new Set(selected);
|
||||
for (const row of rows) {
|
||||
if (on) next.add(row);
|
||||
else next.delete(row);
|
||||
}
|
||||
setSelected(next);
|
||||
setAnchor(id);
|
||||
}
|
||||
|
||||
function toggleAllShown() {
|
||||
const next = new Set(selected);
|
||||
const on = shownSelected.length < shown.length;
|
||||
for (const row of shown) {
|
||||
if (on) next.add(row);
|
||||
else next.delete(row);
|
||||
}
|
||||
setSelected(next);
|
||||
setAnchor(null);
|
||||
}
|
||||
|
||||
/** Says whether there was anything to clear: an Esc that cleared nothing is not spent. */
|
||||
function clear(): boolean {
|
||||
const had = selected.size > 0;
|
||||
if (had) setSelected(NONE);
|
||||
setAnchor(null);
|
||||
return had;
|
||||
}
|
||||
|
||||
/** Tick these again: an action that took them off and failed. */
|
||||
function select(ids: readonly string[]) {
|
||||
setSelected((now) => new Set([...now, ...ids]));
|
||||
}
|
||||
|
||||
return {
|
||||
shownSelected,
|
||||
hiddenCount: selected.size - shownSelected.length,
|
||||
isSelected: (id: string) => selected.has(id),
|
||||
headerState:
|
||||
shownSelected.length === 0
|
||||
? ("none" as const)
|
||||
: shownSelected.length === shown.length
|
||||
? ("all" as const)
|
||||
: ("some" as const),
|
||||
toggle,
|
||||
toggleAllShown,
|
||||
clear,
|
||||
select,
|
||||
};
|
||||
}
|
||||
@@ -25,6 +25,7 @@ const tag = (id: number, name: string, system: boolean): Tag => ({
|
||||
color: null,
|
||||
category: "topic",
|
||||
channel_count: 1,
|
||||
subscribed_count: 1,
|
||||
});
|
||||
|
||||
function wrapper({ children }: { children: ReactNode }) {
|
||||
|
||||
@@ -18,6 +18,16 @@ describe("useUndoable", () => {
|
||||
expect(result.current.value).toEqual([10, 20]);
|
||||
});
|
||||
|
||||
it("peeks at a value set in this tick, before it renders", () => {
|
||||
const { result } = renderHook(() => useUndoable<number[]>([1]));
|
||||
const { peek, set } = result.current;
|
||||
act(() => {
|
||||
set([1, 2]);
|
||||
expect(peek()).toEqual([1, 2]);
|
||||
});
|
||||
expect(peek()).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it("keeps the undo history through a rebase", () => {
|
||||
const { result } = renderHook(() => useUndoable<number[]>([1]));
|
||||
act(() => result.current.set([1, 2]));
|
||||
|
||||
@@ -16,6 +16,8 @@ import { useLatest } from "./useLatest";
|
||||
// Render never reads the ref: a compiled component would otherwise memoize a stale value.
|
||||
export interface Undoable<T> {
|
||||
value: T;
|
||||
/** The value as of NOW, with a `set` not rendered yet, for code that runs after an await. */
|
||||
peek: () => T;
|
||||
set: (next: T) => void;
|
||||
reset: (value: T) => void;
|
||||
rebase: (map: (value: T) => T) => void;
|
||||
@@ -110,8 +112,11 @@ export function useUndoable<T>(
|
||||
setH(over);
|
||||
}, []);
|
||||
|
||||
const peek = useCallback(() => ref.current.present, []);
|
||||
|
||||
return {
|
||||
value: h.present,
|
||||
peek,
|
||||
set,
|
||||
reset,
|
||||
rebase,
|
||||
|
||||
@@ -17,12 +17,15 @@ import "flag-icons/css/flag-icons.min.css";
|
||||
import { lazyWithPreload } from "./lib/lazyWithPreload";
|
||||
import { installClientLog } from "./lib/logHooks";
|
||||
import { installStaleBuildReload } from "./lib/staleBuild";
|
||||
import { retryLostStylesheets } from "./lib/stylesheetRetry";
|
||||
import { appCopyOf } from "./i18n/appCopy";
|
||||
|
||||
// First, before any render: a crash or a navigation during boot belongs in the log too.
|
||||
installClientLog(appCopyOf, typedUrlKeys());
|
||||
// A tab from before the last release reloads onto the new build instead of crashing on a lazy chunk.
|
||||
installStaleBuildReload();
|
||||
// A stylesheet lost on the way is asked for again rather than leaving the page unstyled.
|
||||
retryLostStylesheets();
|
||||
|
||||
// Split by top-level route so each entry point is its own chunk: a legal page never downloads the
|
||||
// authenticated app bundle, and the app never carries it either. The legal pages live outside the
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
// The fit hook is mocked so `visible` is drivable: in jsdom every box measures 0, so the real
|
||||
// measurement can only ever produce one answer.
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
|
||||
import { render, screen, fireEvent, cleanup, act } from "@testing-library/react";
|
||||
import { useState } from "react";
|
||||
|
||||
vi.mock("react-i18next", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react-i18next")>();
|
||||
@@ -37,7 +38,7 @@ const chips = [chip("alpha"), chip("beta"), chip("gamma")];
|
||||
// The surface mounts with `visibility: hidden` until floating-ui has positioned it, which never
|
||||
// happens in jsdom (every box measures 0) — so it is out of the accessibility tree and only a
|
||||
// `hidden: true` query can see it. Presence is the whole question here, not visibility.
|
||||
const menu = () => screen.queryByRole("menu", { hidden: true });
|
||||
const menu = () => screen.queryByRole("dialog", { hidden: true });
|
||||
const moreBtn = () => screen.queryByRole("button", { name: /channels.tags.moreCount/ });
|
||||
|
||||
afterEach(() => {
|
||||
@@ -100,3 +101,114 @@ describe("TagFilterChips — the overflow menu", () => {
|
||||
expect(menu()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("TagFilterChips counts", () => {
|
||||
it("draws a chip's count after its name, and none when it has none", () => {
|
||||
fit.visible = 2;
|
||||
render(
|
||||
<TagFilterChips
|
||||
chips={[{ ...chip("alpha"), count: 42 }, { ...chip("beta"), count: 0 }, chip("gamma")]}
|
||||
/>,
|
||||
);
|
||||
const name = (label: string) =>
|
||||
screen.getAllByRole("button").find((b) => b.textContent?.startsWith(label));
|
||||
expect(name("alpha")?.textContent).toBe("alpha · 42");
|
||||
expect(name("beta")?.textContent).toBe("beta · 0");
|
||||
// In the chip's own colour: a dimmed count falls under the text contrast floor.
|
||||
expect(name("alpha")?.querySelector('[class*="opacity"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("draws nothing after the name of a chip that has no count", () => {
|
||||
fit.visible = 3;
|
||||
render(<TagFilterChips chips={[{ ...chip("alpha"), count: 42 }, chip("gamma")]} />);
|
||||
const gamma = screen.getAllByRole("button").find((b) => b.textContent?.startsWith("gamma"));
|
||||
expect(gamma?.textContent).toBe("gamma");
|
||||
expect(gamma?.querySelector("span")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// The channel manager puts the picked chips first, so a toggle moves its chip: out of the "+N" fold,
|
||||
// into it, or out of the list. The keyboard's focus goes with the chip, not to <body>.
|
||||
describe("TagFilterChips focus on a toggle that moves the chip", () => {
|
||||
function Row({ start }: { start: string[] }) {
|
||||
const [picked, setPicked] = useState(start);
|
||||
const all = ["alpha", "beta", "gamma"].map((k) => ({
|
||||
...chip(k),
|
||||
active: picked.includes(k),
|
||||
onToggle: () => setPicked((p) => (p.includes(k) ? p.filter((x) => x !== k) : [...p, k])),
|
||||
}));
|
||||
return (
|
||||
<TagFilterChips chips={[...all.filter((c) => c.active), ...all.filter((c) => !c.active)]} />
|
||||
);
|
||||
}
|
||||
const press = (el: HTMLElement) => {
|
||||
el.focus();
|
||||
fireEvent.click(el);
|
||||
};
|
||||
const named = (label: string) =>
|
||||
screen.getAllByRole("button", { hidden: true }).find((b) => b.textContent === label)!;
|
||||
|
||||
// Along the row needs no test of its own: a keyed move within one parent keeps its node, and
|
||||
// React gives the focus back to it after the commit. Only a remount (row ↔ fold) or a chip that
|
||||
// leaves the list loses it.
|
||||
|
||||
it("out of the fold: picked in the popover, it is focused on the row", async () => {
|
||||
fit.visible = 1;
|
||||
render(<Row start={[]} />);
|
||||
fireEvent.click(moreBtn()!);
|
||||
const inFold = named("beta");
|
||||
press(inFold);
|
||||
// The closing popover hands the focus back to "+N" a microtask later: past that too.
|
||||
await act(async () => {});
|
||||
const onRow = named("beta");
|
||||
expect(onRow).not.toBe(inFold);
|
||||
expect(document.activeElement).toBe(onRow);
|
||||
// …and the fold is shut: the focus is not left outside a popover still open.
|
||||
expect(menu()).toBeNull();
|
||||
expect(moreBtn()).toHaveProperty("ariaExpanded", "false");
|
||||
});
|
||||
|
||||
// A stored pick of a tag that no longer exists is an active chip that an un-pick removes for good.
|
||||
function WithGhost() {
|
||||
const [ghost, setGhost] = useState(true);
|
||||
const rest = ["alpha", "beta"].map(chip);
|
||||
return (
|
||||
<TagFilterChips
|
||||
chips={
|
||||
ghost
|
||||
? [{ ...chip("ghost"), active: true, onToggle: () => setGhost(false) }, ...rest]
|
||||
: rest
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
it.each([
|
||||
["with room for all", 3],
|
||||
["with a fold", 1],
|
||||
])("a chip that leaves the list hands the focus to the one now in its place (%s)", (_, n) => {
|
||||
fit.visible = n;
|
||||
render(<WithGhost />);
|
||||
press(named("ghost"));
|
||||
expect(document.activeElement).toBe(named("alpha"));
|
||||
});
|
||||
|
||||
it("into a closed fold: the focus goes to the +N that now holds it", () => {
|
||||
fit.visible = 1;
|
||||
render(<Row start={["gamma"]} />);
|
||||
press(named("gamma"));
|
||||
expect(named("alpha").closest('[role="dialog"]')).toBeNull(); // alpha leads the row now
|
||||
expect(document.activeElement).toBe(moreBtn());
|
||||
});
|
||||
|
||||
it("a mouse press that leaves the focus elsewhere takes nothing", () => {
|
||||
fit.visible = 3;
|
||||
render(<Row start={[]} />);
|
||||
const outside = document.body.appendChild(document.createElement("input"));
|
||||
outside.focus();
|
||||
fireEvent.click(named("gamma"));
|
||||
act(() => {});
|
||||
expect(document.activeElement).toBe(outside);
|
||||
outside.remove();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useLayoutEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { fitChipsWithPill } from "../../lib/chipOverflow";
|
||||
import { chipLaneClass, useChipOverflowFit } from "../../lib/useChipOverflowFit";
|
||||
@@ -19,6 +19,8 @@ import { ChipLabelPending } from "../../components/ui/Skeleton";
|
||||
export interface FilterChip {
|
||||
key: string;
|
||||
label: string;
|
||||
/** How many it holds, drawn muted after the name. */
|
||||
count?: number;
|
||||
/** The name is still on its way: the chip draws a placeholder, not `label` (a raw id). */
|
||||
pending?: boolean;
|
||||
active: boolean;
|
||||
@@ -28,12 +30,40 @@ export interface FilterChip {
|
||||
// A chip's text — the visible chip and the hidden measuring mirror both draw it, so the mirror
|
||||
// measures what shows (ActiveFilterChips' ChipText, for this row's chips).
|
||||
function ChipText({ chip }: { chip: FilterChip }) {
|
||||
return chip.pending ? <ChipLabelPending value={chip.label} /> : <>{chip.label}</>;
|
||||
if (chip.pending) return <ChipLabelPending value={chip.label} />;
|
||||
return (
|
||||
<>
|
||||
{chip.label}
|
||||
{/* The count in the chip's own colour, set off by a dot rather than dimmed: a dimmed count
|
||||
falls under the text contrast floor, on a resting chip and on a pressed one. */}
|
||||
{chip.count != null && (
|
||||
<>
|
||||
{" "}
|
||||
<span aria-hidden="true">·</span> <span className="tabular-nums">{chip.count}</span>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function TagChip({ chip }: { chip: FilterChip }) {
|
||||
function TagChip({
|
||||
chip,
|
||||
onToggled,
|
||||
}: {
|
||||
chip: FilterChip;
|
||||
onToggled: (key: string, from: HTMLElement) => void;
|
||||
}) {
|
||||
return (
|
||||
<Chip onClick={chip.onToggle} pressed={chip.active}>
|
||||
<Chip
|
||||
data-chip-key={chip.key}
|
||||
onClick={(e) => {
|
||||
// Before the toggle: a pressed chip may move (the caller's order can put picks first), and
|
||||
// the focus must go where it went.
|
||||
if (e.currentTarget === document.activeElement) onToggled(chip.key, e.currentTarget);
|
||||
chip.onToggle();
|
||||
}}
|
||||
pressed={chip.active}
|
||||
>
|
||||
<ChipText chip={chip} />
|
||||
</Chip>
|
||||
);
|
||||
@@ -53,7 +83,7 @@ export default function TagFilterChips({
|
||||
// Re-fit when the set, the labels, OR the pressed state change (the pressed paint can change a chip's
|
||||
// width via the `.pill` recipe, so an aria-pressed flip must re-measure too).
|
||||
const key = chips
|
||||
.map((c) => `${c.key}:${c.label}:${c.active ? 1 : 0}${c.pending ? "…" : ""}`)
|
||||
.map((c) => `${c.key}:${c.label}:${c.count ?? ""}:${c.active ? 1 : 0}${c.pending ? "…" : ""}`)
|
||||
.join("|");
|
||||
|
||||
const visible = useChipOverflowFit<number>({
|
||||
@@ -90,12 +120,54 @@ export default function TagFilterChips({
|
||||
const pop = useAnchoredPopover({
|
||||
open,
|
||||
onOpenChange: setOpen,
|
||||
mode: "menu",
|
||||
// A fold of toggle buttons, not a menu of items: each chip is a pressed/unpressed button in the
|
||||
// Tab order, which a role=menu with no menu items would hide from a screen reader.
|
||||
mode: "dialog",
|
||||
role: "dialog",
|
||||
placement: "bottom-end",
|
||||
});
|
||||
const { setReference } = pop.refs;
|
||||
const moreLabel = t("channels.tags.moreCount", { count: hidden });
|
||||
|
||||
// A toggle may move its chip between the row and the "+N" fold (two parents: the button is
|
||||
// remounted and the focus falls to <body>), or take it out of the list altogether (a stored pick of
|
||||
// a tag that no longer exists). A move along the row keeps its node, and React gives it the focus
|
||||
// back. The focus follows the chip: onto it where it now stands, onto "+N" when it went into a
|
||||
// closed fold, or onto the chip now in its old place when it is gone. A toggle in the open fold
|
||||
// closes it, so the focus never sits outside a popover left open. Held for the frame, since the fit
|
||||
// re-decides in layout effects after the toggle's render.
|
||||
const follow = useRef<{ key: string; at: number; closed: boolean } | null>(null);
|
||||
const foldRef = useRef<HTMLDivElement | null>(null);
|
||||
const moreRef = useRef<HTMLButtonElement | null>(null);
|
||||
const onToggled = (chipKey: string, from: HTMLElement) => {
|
||||
const closed = !!foldRef.current?.contains(from);
|
||||
follow.current = { key: chipKey, at: chips.findIndex((c) => c.key === chipKey), closed };
|
||||
requestAnimationFrame(() => (follow.current = null));
|
||||
if (closed) setOpen(false);
|
||||
};
|
||||
useLayoutEffect(() => {
|
||||
const target = follow.current;
|
||||
if (!target) return;
|
||||
const inBox = (box: HTMLElement | null) => [
|
||||
...(box?.querySelectorAll<HTMLElement>("[data-chip-key]") ?? []),
|
||||
];
|
||||
const row = inBox(rowRef.current);
|
||||
const find = (box: HTMLElement[]) => box.find((b) => b.dataset.chipKey === target.key);
|
||||
const gone = !chips.some((c) => c.key === target.key);
|
||||
const el =
|
||||
find(row) ??
|
||||
find(inBox(foldRef.current)) ??
|
||||
(gone ? (row[Math.min(target.at, row.length - 1)] ?? moreRef.current) : moreRef.current);
|
||||
if (el && document.activeElement !== el) el.focus();
|
||||
// The closing popover gives the focus back to "+N" in a microtask it queued as it unmounted
|
||||
// (seen in Chrome): this one, queued after it, has the last word.
|
||||
if (el && target.closed) queueMicrotask(() => el.isConnected && el.focus());
|
||||
});
|
||||
const setMore = (el: HTMLButtonElement | null) => {
|
||||
moreRef.current = el;
|
||||
setReference(el);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`${chipLaneClass} flex items-center gap-1.5 min-w-0 ${className ?? ""}`}>
|
||||
{/* Hidden measurer: all chips + a sample "+N" pill at natural widths, so the shared fit core can
|
||||
@@ -124,10 +196,10 @@ export default function TagFilterChips({
|
||||
|
||||
<div ref={rowRef} className="flex items-center gap-1.5 min-w-0 flex-1 overflow-hidden">
|
||||
{chips.slice(0, visible).map((c) => (
|
||||
<TagChip key={c.key} chip={c} />
|
||||
<TagChip key={c.key} chip={c} onToggled={onToggled} />
|
||||
))}
|
||||
{hidden > 0 && (
|
||||
<Chip ref={setReference} aria-label={moreLabel} {...pop.getReferenceProps()}>
|
||||
<Chip ref={setMore} aria-label={moreLabel} {...pop.getReferenceProps()}>
|
||||
+{hidden}
|
||||
</Chip>
|
||||
)}
|
||||
@@ -138,9 +210,11 @@ export default function TagFilterChips({
|
||||
ariaLabel={moreLabel}
|
||||
className={`${SURFACE.popover} flex max-w-[22rem] flex-wrap items-center gap-1.5 p-2 animate-[popIn_0.16s_ease]`}
|
||||
>
|
||||
{chips.slice(visible).map((c) => (
|
||||
<TagChip key={c.key} chip={c} />
|
||||
))}
|
||||
<div ref={foldRef} className="contents">
|
||||
{chips.slice(visible).map((c) => (
|
||||
<TagChip key={c.key} chip={c} onToggled={onToggled} />
|
||||
))}
|
||||
</div>
|
||||
</PopoverSurface>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -186,3 +186,58 @@ describe("buildChannelColumns — Added", () => {
|
||||
expect(screen.getByText(formatDate("2026-10-12T08:00:00+00:00", "en"))).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("tagFilterChips", () => {
|
||||
// An unsubscribe keeps a channel's tag links: the chip counts the followed ones, the rows the
|
||||
// filter shows, not every link the tag has.
|
||||
it("counts a tag's followed channels, and only a tag's", () => {
|
||||
const tag = {
|
||||
id: 3,
|
||||
name: "Tech",
|
||||
color: null,
|
||||
category: "topic",
|
||||
system: false,
|
||||
channel_count: 17,
|
||||
subscribed_count: 15,
|
||||
};
|
||||
const chips = tagFilterChips({
|
||||
userTags: [tag],
|
||||
tags: { isPending: false } as never,
|
||||
picked: ["99"],
|
||||
noTagOn: false,
|
||||
toggle: () => {},
|
||||
toggleNoTag: () => {},
|
||||
t: ((k: string) => k) as never,
|
||||
});
|
||||
expect(chips.find((c) => c.label === "Tech")?.count).toBe(15);
|
||||
expect(chips.find((c) => c.key === "t99")?.count).toBeUndefined();
|
||||
expect(chips[chips.length - 1]?.count).toBeUndefined();
|
||||
});
|
||||
|
||||
// The row folds from its end into "+N", so a picked tag late in the list was folded away: at 1024 px
|
||||
// "music" sat behind "+11" with nothing on the row saying a filter was on. The picks lead the row.
|
||||
it("puts the picked tags first, keeping their order, then the rest in theirs", () => {
|
||||
const tag = (id: number, name: string) => ({ id, name, system: false }) as Tag;
|
||||
const row = (picked: string[], noTagOn = false) =>
|
||||
tagFilterChips({
|
||||
userTags: [tag(1, "ai"), tag(2, "docu"), tag(3, "music"), tag(4, "nature")],
|
||||
tags: { isPending: false } as never,
|
||||
picked,
|
||||
noTagOn,
|
||||
toggle: () => {},
|
||||
toggleNoTag: () => {},
|
||||
t: ((k: string) => k) as never,
|
||||
}).map((c) => c.label + (c.active ? "*" : ""));
|
||||
expect(row(["4", "3"])).toEqual(["music*", "nature*", "ai", "docu", "channels.tags.noTag"]);
|
||||
expect(row(["99", "3"])).toEqual([
|
||||
"99*",
|
||||
"music*",
|
||||
"ai",
|
||||
"docu",
|
||||
"nature",
|
||||
"channels.tags.noTag",
|
||||
]);
|
||||
expect(row([], true)).toEqual(["channels.tags.noTag*", "ai", "docu", "music", "nature"]);
|
||||
expect(row([])).toEqual(["ai", "docu", "music", "nature", "channels.tags.noTag"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -51,11 +51,12 @@ export function tagsColumnTest(c: ManagedChannel, values: string[]): boolean {
|
||||
}
|
||||
|
||||
/** The manager's tag-filter chip row (the Tags column filter's values): any picked id that is not one
|
||||
* of the user's tags, then each user tag, then the "No tag" sentinel. A stored pick can outlive its
|
||||
* of the user's tags, then the picked ones of the user's tags and "No tag", then the rest, each group
|
||||
* in the tags' order with "No tag" last. The row folds from its end into "+N", so every pick leads it:
|
||||
* a filter that is on stays in sight, never only inside the fold. A stored pick can outlive its
|
||||
* tag (deleted here or on another device) and still narrows the table to nothing, so it stays a
|
||||
* visible, removable chip — FIRST, so the row's "+N" overflow never folds the reason away —
|
||||
* and so does every pick while the tag list loads or after it failed, named by lib/tagPicks' rule
|
||||
* (a placeholder, then the name, "Deleted tag" or the id), not hidden. */
|
||||
* visible, removable chip, and so does every pick while the tag list loads or after it failed, named
|
||||
* by lib/tagPicks' rule (a placeholder, then the name, "Deleted tag" or the id), not hidden. */
|
||||
export function tagFilterChips(o: {
|
||||
userTags: Tag[];
|
||||
tags: TagList;
|
||||
@@ -67,17 +68,11 @@ export function tagFilterChips(o: {
|
||||
}): FilterChip[] {
|
||||
const mine = new Set(o.userTags.map((tg) => String(tg.id)));
|
||||
const others = o.picked.filter((id) => id !== NO_TAG_SENTINEL && !mine.has(id));
|
||||
return [
|
||||
...others.map((id) => ({
|
||||
key: `t${id}`,
|
||||
label: tagPickLabel(Number(id), o.tags, o.t),
|
||||
pending: o.tags.isPending,
|
||||
active: true,
|
||||
onToggle: () => o.toggle(Number(id)),
|
||||
})),
|
||||
const known: FilterChip[] = [
|
||||
...o.userTags.map((tg) => ({
|
||||
key: `t${tg.id}`,
|
||||
label: tg.name,
|
||||
count: tg.subscribed_count,
|
||||
active: o.picked.includes(String(tg.id)),
|
||||
onToggle: () => o.toggle(tg.id),
|
||||
})),
|
||||
@@ -88,6 +83,17 @@ export function tagFilterChips(o: {
|
||||
onToggle: o.toggleNoTag,
|
||||
},
|
||||
];
|
||||
return [
|
||||
...others.map((id) => ({
|
||||
key: `t${id}`,
|
||||
label: tagPickLabel(Number(id), o.tags, o.t),
|
||||
pending: o.tags.isPending,
|
||||
active: true,
|
||||
onToggle: () => o.toggle(Number(id)),
|
||||
})),
|
||||
...known.filter((c) => c.active),
|
||||
...known.filter((c) => !c.active),
|
||||
];
|
||||
}
|
||||
|
||||
/** Everything the Channels-manager column set closes over. The manager owns the state + mutations;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user