1
Fork 0
mirror of https://github.com/thegeneralist01/archivr synced 2026-07-22 03:05:32 +02:00

feat: add capturing w/ parent-child entries (#32)

* feat(core): YouTube playlist/channel/YTM-playlist capture with parent–child entries

- ytdlp: add fetch_playlist_info() using yt-dlp -J --flat-playlist for
  reliable container title + shallow entry list; normalize item URLs via
  webpage_url → absolute url → id fallback (domain inferred from container
  URL so YTM stays on music.youtube.com)
- capture: add record_container_entry() (no blob, no primary_media artifact);
  extend record_media_entry() with parent_entry_id/root_entry_id params (all
  existing single-item call sites pass None, None)
- capture: implement YouTubePlaylist / YouTubeChannel / YouTubeMusicPlaylist
  capture path replacing the two not-implemented stubs: fetch playlist info →
  create container entry (reusing existing run + item) → per-child run items
  (parent_item_id = container item) → download each video/track as a child
  entry; per-child failures are non-fatal; perform_capture returns result.status
  reflecting actual run outcome so capture_handler marks the job correctly
- archive: add child_count i64 to EntrySummary (col 12 in all listing queries);
  add get_entry_summary() private helper; fix get_entry_detail() to use
  get_entry_summary() so child entries are resolvable via the detail endpoint;
  add list_child_entries(conn, uid, caller_bits) with the same
  admin/collection visibility predicate as list_root_entries

archive_runs.requested_count stays 1 (one user locator); discovered/
completed/failed_count reflect container item + N video items via
refresh_run_counters.

* feat(server,frontend): expose children endpoint + expand UI for container entries

server:
- add GET /api/archives/:id/entries/:uid/children → list_entry_children,
  calling list_child_entries with caller_bits so visibility model is enforced
- fix capture_handler: use result.status ("completed"/"failed") to set job
  status rather than always "completed", mirroring rearchive_handler; this
  surfaces partial playlist failures to the polling client

frontend:
- api.js: add fetchEntryChildren(archiveId, entryUid)
- EntryRow: one outer div.entry-row-outer (display:block) keeps nth-child
  striping correct; inner div.entry-row-main is the flex row with all column
  cells and event handling; .child-entries sits below inside the outer wrapper
- expand chevron appears when entry.child_count > 0; clicking fetches children
  lazily and renders ChildRow components reusing .col-* flex widths
- child-count badge shown next to title on container entries
- styles.css: scoped CSS with #entries-body > .entry-row-outer selectors
  (higher specificity than > div) to override flex on outer wrapper; inner row
  and column rules replicated at correct depth; nth-child, is-selected,
  is-multi-selected, url-cell hover all handled

* fix(frontend): make child entry rows interactive

ChildRow now receives onRowClick and selectedUids from EntryRow (which
receives selectedUids from EntriesView alongside the existing booleans).
Clicking a child row invokes onRowClick(child, e) so it flows through
handleRowClick → selectEntry → fetchEntryDetail exactly as a root entry
would. Shift-range selection gracefully degrades to single-select since
child entries are not in the root entries array.

Selected/multi-selected visual state is wired: .child-entry-row.is-selected
shows the same #eee2d2 background + accent outline as root rows; hover
restores full opacity. Frontend static assets rebuilt.

* feat(core): playlist per-item quality + incremental sync

ytdlp.rs:
- Add PlaylistItemProbe / PlaylistProbeResult (pub, serde::Serialize)
- Add private available_video_heights_from_value() helper for Value entries
- Add probe_playlist_qualities(): yt-dlp -J (full metadata, no flat flag)
  returns per-video quality lists in one subprocess call

capture.rs:
- Add per_item_quality: HashMap<String,String> and sync: bool to CaptureConfig
  (both Default; keyed by yt-dlp video ID, not URL)
- Add pub locator_to_playlist_url(): validates only the three playlist sources,
  expands shorthands; keeps locator_to_ytdlp_url's no-playlists contract
- Playlist capture block: sync-aware container resolution
  - sync + existing container → reuse it via complete_archive_run_item,
    skip already-archived children (by canonical URL) before creating
    run items so refresh_run_counters only counts new items
  - sync + no container → create normally (first sync run)
  - non-sync → always create fresh container (existing behaviour)
- Per-item quality: config.per_item_quality.get(id) falls back to child_quality

archive.rs:
- Add get_archived_playlist_child_urls(): returns HashSet of canonical URLs
  of all children under any container matching the playlist canonical URL
- Add find_container_entry_id_by_canonical_url(): returns most-recent
  container entry id (parent_entry_id IS NULL) for a given canonical URL

routes.rs: stub per_item_quality/sync on both CaptureConfig sites (server
agent will wire body fields in Phase 2)

* fix(core)+test: propagate sync query errors; cover new playlist/sync functions

archive.rs:
- get_archived_playlist_child_urls: collect() as rusqlite::Result<HashSet<_>>
  instead of filter_map(ok) so row-level errors surface rather than silently
  skipping and causing duplicate downloads

capture.rs:
- match get_archived_playlist_child_urls result and fail_run on error instead
  of unwrap_or_default, preventing silent re-downloads on DB failure

Tests added to capture.rs:
- locator_to_playlist_url_accepts_playlist_shorthands (yt:playlist/, ytm:playlist/, full URL)
- locator_to_playlist_url_accepts_channel_shorthands (yt:@handle)
- locator_to_playlist_url_rejects_non_playlist_sources (single video, tweet, web page)

Tests added to archive.rs (all use in-memory DB via make_tag_test_db):
- find_container_entry_id_returns_none_when_absent
- find_container_entry_id_returns_root_entry
- find_container_entry_id_ignores_child_entries (child with parent_entry_id set)
- get_archived_playlist_child_urls_empty_when_no_playlist
- get_archived_playlist_child_urls_returns_children
- get_archived_playlist_child_urls_excludes_other_playlists

* feat(server,frontend): playlist quality selector + per-video overrides + sync UI

routes.rs:
- CaptureBody gains per_item_quality (HashMap<String,String>, serde(default))
  and sync (bool, serde(default)); both validated before use
  - per_item_quality values validated against same quality predicate as top-level
    quality field ("best"|"audio"|"NNNp") so bad per-video values are rejected
    at the API boundary rather than silently falling through to quality_format
- capture_handler threads body.per_item_quality + body.sync into CaptureConfig
  (replaces hardcoded empty stubs); rearchive_handler keeps empty defaults
- New POST /api/archives/:id/captures/probe-playlist: calls
  probe_playlist_qualities via spawn_blocking; 400 for non-playlist locator,
  502 on yt-dlp failure, returns PlaylistProbeResult as JSON

api.js:
- probePlaylist(archiveId, locator): POST probe-playlist endpoint
- submitCapture: forwards per_item_quality (non-empty) and sync:true from
  extraExtensions param added to submitBgJob

CaptureDialog.jsx:
- isPlaylistSource(): detects yt:/youtube: playlist/@/channel, ytm:playlist/,
  YouTube/YTM HTTP(S) URLs with list= param or channel pathnames
- makeItem(): 6 new playlist state fields
- applyPlaylistQuality(): conflict logic — videos that can reach selected
  quality get it set; videos that can't and have no prior selection are left
  null (conflict); videos with a prior selection keep it when quality is raised
- hasConflict(): any playlistItems entry with quality===null
- updateLocator(): isPlaylistSource branch with 800ms debounce→probePlaylist;
  existing isVideoSource path unchanged
- Archive button disabled when anyConflict or any probe in flight
- Per-video expand list with individual quality selects, conflict badges,
  sync toggle (appears after probe completes)

styles.css: playlist expansion, conflict, sync toggle CSS

* fix(core): ignore per_item_quality for YTM playlist items

YouTube Music playlists force child_quality = Some("audio") because
yt-dlp can't download DRM-free audio-only tracks any other way. The
previous per_item_quality lookup could override this with e.g. "best",
defeating the invariant. Guard the lookup behind !is_audio so YTM items
are always downloaded as audio regardless of what the caller sends.

* fix(frontend): exclude /watch from isPlaylistSource

youtube.com/watch?v=...&list=... and music.youtube.com/watch are single
videos in the backend (Source::YouTubeVideo / YouTubeMusicTrack) regardless
of the list param. Previously isPlaylistSource returned true for these,
which would have triggered the playlist probe path while the video probe
was already running, and the render would attempt to show playlist UI on
an item whose playlistProbeState stays idle.

Guard: if pathname === '/watch', return false before the list-param check.

* fix(frontend): tighten isPlaylistSource to mirror backend routing exactly

Previous fix excluded /watch but still returned true for any youtube.com
URL with a ?list= param (e.g. /shorts/xxx?list=yyy). Backend determine_source
only routes to YouTubePlaylist on /playlist?list=... and to YouTubeChannel on
/@handle, /channel/, /c/, /user/ paths — everything else is a single item.

Rewrite the HTTP block to match:
- youtube.com: pathname==='/playlist' && list param → playlist
             : /@, /channel/, /c/, /user/ → channel
             : anything else (incl. /watch&list=, /shorts?list=) → false
- music.youtube.com: pathname==='/playlist' && list param → YTM playlist
                   : /watch → single track (falls through to false)

* fix(frontend): guard handleArchive against Enter-key bypass of disabled state

The Archive button is disabled when anyConflict || anyProbing, but
onKeyDown on the locator input calls onSubmit() → handleArchive()
directly, bypassing the button's disabled check entirely.

Add the same conditions as early returns inside handleArchive itself,
operating on toSubmit (the items that would actually be submitted) so
the guard is tight — items with no locator are already excluded by the
toSubmit filter.

* fix(frontend): drop m.youtube.com from isPlaylistSource

Backend determine_source playlist/channel regex only matches
(?:www\.)?youtube\.com — mobile URLs hitting m.youtube.com would be
probed as playlist in the UI but captured as Source::Url server-side.
Remove m.youtube.com from the detector to keep frontend and backend
in exact agreement. Add backend support when needed.

* fix(frontend): audio-only conflict handling in playlist quality selector

applyPlaylistQuality('audio'):
- Only sets quality='audio' on items where has_audio=true
- Items with has_audio=false: keep prior selection if set, else null
  (conflict) — same rule as unsupported height, blocks archive until
  user explicitly picks a quality for those items

Playlist-level 'Audio only' option:
- Changed hasAnyAudio → allHaveAudio (every item must have audio)
- When any item lacks audio, the option is hidden entirely so the
  selector can never create immediate conflicts just by appearing

* fix(frontend): add yt:user/ to isPlaylistSource shorthand detection

Backend determine_source routes yt:user/... (and youtube:user/...) to
YouTubeChannel — already covered by the yt: shorthand block for
playlist/, @, channel/, c/ but missing user/. Old-style user channel
URLs would capture correctly server-side but never show the playlist
quality/sync UI.

* fix(frontend): block playlist submission unless probe is done

Previous guard only blocked while playlistProbeState==='probing'.
Two remaining bypass paths:
- idle: 800ms debounce not yet fired after URL typed
- error: probe failed — no per-video quality data available

Change anyProbing and handleArchive guard to:
  isPlaylistSource(locator) && playlistProbeState !== 'done'

This means idle/probing/error all block submission for playlist items.
error is intentionally blocking — without quality data the per-video
requirement can't be satisfied; user must retry or remove the URL.

* fix(frontend): accurate error message when playlist probe fails

Previous text said 'using best quality' implying the capture would
proceed, but probe error now blocks submission. Replace with 'Probe
failed — edit URL to retry' in orange (capture-quality-hint--error)
so the disabled button and the message are consistent.

* fix(frontend): exact quality match in applyPlaylistQuality

Replace maxHeight >= newHeight (cap check) with item.qualities.includes(newQ)
(exact match). A video with [2160p, 1080p] does not support 1440p; the
previous logic would mark it as supporting any quality up to 2160p and
submit '1440p' which yt-dlp silently downloads as 1080p — misrepresenting
the selected quality.

With exact match, unsupported qualities correctly fall through to the
conflict path (keep prior selection or null), enforcing the same manual-
choice requirement as any other unsupported quality.

Per-row selects are unaffected: they already render only pi.qualities
(the video's actual available formats), no maxHeight logic involved.

* fix(frontend): move playlist expand chevron to left of input

User asked for the chevron to be on the left of the playlist input,
not tucked after the quality selector on the right.

- Remove chevron from qualityEl (it was between the quality select and
  the remove button)
- Add it as the first child of capture-row-main, before the <input>,
  when isPlaylistSource && playlistProbeState === 'done'
- Show a same-width placeholder span while probing/idle/error so the
  input does not jump left when the chevron appears after probe completes
- Add capture-playlist-toggle--left modifier (flex-shrink:0, tighter
  padding) and .capture-playlist-toggle-placeholder (fixed 22px width)

* doc(server): scope per_item_quality guarantee to the UI

The server validates per_item_quality value shapes but does not enforce
that every playlist item has an entry. Items without an override get
the global quality as a yt-dlp cap with graceful fallback.

The 'must choose quality for unsupported videos' invariant is a UI
constraint enforced by the frontend before submission. A direct API
caller bypassing the UI accepts yt-dlp's standard cap-and-fallback
behavior. Document this scope explicitly so the gap is intentional,
not accidental.

* fix(frontend): prevent 'reading some of undefined' crash from stale sessionStorage

Old captureItems entries saved before the playlist fields were added
have playlistItems=undefined (missing key). The hasConflict guard
checked !== null, which undefined passes, then called .some() on
undefined → TypeError.

Two-part fix:
1. sessionStorage restore: merge each saved item over makeItem() defaults
   so any missing fields (playlistItems, playlistProbeState, etc.) are
   filled with their correct initial values before the item is used
2. hasConflict: use Array.isArray() instead of !== null so undefined
   is also safely rejected — defence-in-depth for any future field gap

* fix(core): playlist total size includes children; per_item_quality as include-set

archive.rs: total_artifact_bytes for root entries now adds a correlated
subquery summing children's blob bytes so playlist/channel containers
show the real download size instead of 0.

capture.rs: non-empty per_item_quality map now acts as an include-set —
items whose yt-dlp ID is absent are skipped entirely. This wires the
UI's per-video delete button to actual capture exclusion. Empty map
preserves the existing behaviour (download everything).

routes.rs + capture.rs doc: comments updated to reflect both semantics
(empty = all / non-empty = only listed IDs) accurately.

* fix(frontend): QA fixes — playlist UX, selection stroke, URL expand

CaptureDialog.jsx:
- Placeholder no longer appears on idle playlist rows (only during
  probing); chevron shows only after probe completes — no left-padding
  while the user is still typing
- Per-video delete button added to expanded playlist list; removes item
  from playlistItems so its ID is absent from per_item_quality on submit
- anyEmptyPlaylist guard: Archive button disabled + handleArchive early-
  return when all videos have been deleted (empty map would otherwise
  silently download everything)

styles.css:
- Selection stroke switched from outline to box-shadow:inset everywhere
  (entry-row-outer, child-entry-row, legacy flat-div selector) —
  guaranteed inside element bounds, no layout interference
- URL cell overflow only on :hover; removed is-selected .url-cell rule
  that was expanding child URLs when their parent was selected
- Playlist items redesign: separator lines instead of background fills,
  amber left-border for conflicts, thin scrollbar, tighter padding
- Remove button: opacity 0.3 always-visible baseline; full opacity on
  hover/:focus-visible; forced to 1 on coarse-pointer (touch) devices

* fix(frontend): no left gap on playlist rows until chevron exists

Remove the probing-state placeholder span entirely. The chevron renders
only when playlistProbeState === 'done'; all other states (idle, probing,
error) render null. The small layout shift when the chevron appears after
probe is acceptable; blank padding while there is no chevron is not.

* fix(frontend): clear box-shadow on entry-row-outer to prevent double stroke

The flat selector '#entries-body > div.is-selected' already applies
box-shadow to .entry-row-outer (it IS a direct child div). The outer
override rule only cleared 'outline', so the box-shadow leaked through,
wrapping the entire parent+children block with a second stroke.

Add box-shadow: none to both .is-selected and .is-multi-selected on
.entry-row-outer so the stroke sits only on .entry-row-main.

* docs: document per-video exclude in README YouTube playlists section

* fix(frontend): scope selection background to entry-row-main only

Moving background:#eee2d2 off .entry-row-outer onto > .entry-row-main
so that expanded child entries don't inherit the selection highlight.

Outer wrapper now explicitly unsets background (cancelling the flat-div
cascade rule) and clears outline+box-shadow. Both the selection colour
and the inset stroke live on .entry-row-main only.

* fix(frontend): alternating stripe backgrounds on child entry rows

Child rows were inheriting the parent entry's stripe color, making the
expanded list look like one flat block. Apply the same odd/even palette
as root entries (var(--paper-3) / #f2ede5) so each video row is visually
distinct within the expanded group.

* fix(core): delete_entry correctly nulls FK for child entries

archive_run_items.produced_entry_id has no ON DELETE action so it must
be manually nulled before the entry row is deleted. The old query used
WHERE root_entry_id = entry_id, which finds descendants of a root but
returns nothing when entry_id IS a child (children have no sub-children,
so no row has root_entry_id = child_id). The DELETE then failed under
foreign_keys=ON.

Fix: add OR produced_entry_id = ?1 so the entry's own run_item FK is
always cleared before deletion, regardless of whether it is a root or a
child. The subtree subquery is kept for the root-deletion case where all
child run_items also need nulling.

* fix(core+frontend): child entry selection and delete correctness

database.rs — delete_entry:
- subtree_ids now uses WHERE id = ?1 OR root_entry_id = ?1 so the entry
  itself is always included; previously a child deletion passed an empty
  vec to cascade_cached_bytes_after_subtree_delete (no grandchildren
  exist), leaving cached_bytes stale on entries sharing that child's blobs

App.jsx — handleRowClick:
- Shift-range now queries DOM order (#entries-body [data-entry-uid])
  instead of entries.findIndex(); child rows are in the DOM but not in
  the root entries array, so findIndex always returned -1 for them
- Ctrl/meta branch computes next set before the state update so
  selectEntry can fire synchronously for child rows; auto-snap only
  restores root entries, so ctrl-clicking a lone child never loaded its
  detail panel — now calls selectEntry(entry) when the child ends up as
  the sole selection, selectEntry(null) on multi or deselect
- selectedUids added to handleRowClick's useCallback dep array

* fix(frontend): resolve detail entry for any remaining child after ctrl-deselect

Add entryCacheRef (uid→entry Map) populated on every row click. When
ctrl/meta-deselecting leaves exactly one other entry selected, look up
the remaining UID in the cache before falling back to the root entries
array. Without this, deselecting from a multi-selection where the
remaining entry is a child row left selectedEntry null (auto-snap only
searches root entries).

* fix(frontend): child row stripes, deleted-child visibility, selection completeness

EntryRow.jsx / ChildRow:
- Index-based light/dark classes (child-entry-row--light/dark) replace
  nth-child rules; parity comes from children.map idx so no sibling —
  including the loading div — can shift the stripe order
- Loading div moved outside .child-entries so it never affects child
  row ordering at all
- Accept deletedUids prop; filter expanded children array before render
  so deleted children disappear immediately without waiting for reload

EntriesView.jsx: thread deletedUids through to EntryRow

App.jsx:
- Add deletedUids state; handleEntryDeleted/handleBulkDeleted populate it
- isRoot/hasChildDelete computed from entries before setEntries (safe in
  StrictMode — no side-effects inside updater functions)
- Child delete triggers loadEntries to refresh stale parent child_count
  and total_artifact_bytes
- handleRowClick ctrl/meta cache-miss branch uses det.summary (not det)
  from fetchEntryDetail; archiveId added to dep array
- handleRowClick dep array includes archiveId

* fix(frontend): add inset stroke to child-entry-row.is-multi-selected

* fix(frontend): suppress mouse-click focus ring on entry expand button

* fix(frontend): index-based stripes for root and child rows

Root rows: EntriesView passes rowIndex from entries.map to EntryRow,
which applies entry-row-outer--light/dark. Retires both nth-child stripe
blocks so skeleton rows can never shift the first real entry to dark.
Skeleton rows keep a :not(.entry-row-outer) nth-child fallback.

Child rows: colours changed from the warm root palette (paper-3/#f2ede5)
to cooler near-whites (#fafaf8/#f2f0ec) so children are visually distinct
from their parent row regardless of which stripe the parent sits on.

* feat(core+frontend): bare yt:ID resolves to YouTube video

determine_source: yt:ID / youtube:ID with no prefix and exactly 11
chars [A-Za-z0-9_-] → YouTubeVideo via is_youtube_video_id helper.
Reserved prefixes (playlist/, channel/, c/, user/, @) still fire first
so they are unaffected by the fallback.

expand_shorthand_to_url: bare yt:ID expands to watch?v=ID using the
same predicate, consistent with how ytm:ID → music.youtube.com/watch.

isVideoSource (frontend): same 11-char /^[A-Za-z0-9_-]{11}$/ regex so
yt:ID triggers the quality probe and capture-row guards identically to
yt:video/ID.

Tests: test_is_youtube_video_id covers valid IDs (alphanumeric, with _
and -), too-short, too-long, and invalid-char cases using genuinely
invalid fixtures. test_youtube_sources adds bare-ID cases and confirms
reserved prefixes (playlist/, @) are not affected.

* fix(core+frontend): exclude avatar blobs from tweet % cached display

tweet/tweet_thread entries have avatar artifacts that are always
deduplicated from the first capture of each author. Counting them in
the cached-bytes percentage makes it artificially high (or incorrect
when the real media content is new but avatars are cached).

database.rs:
- refresh_entry_cached_bytes: AND ea.artifact_role != 'avatar'
- cascade_cached_bytes_after_delete: same filter
- cascade_cached_bytes_after_subtree_delete: same filter
- Initial cached_bytes migration: same filter
- Re-migration (else branch): recomputes cached_bytes for existing
  entries that have avatar artifacts, scoped to only those entries

archive.rs:
- EntrySummary gains cacheable_bytes: i64 — non-avatar total bytes,
  computed inline in every SQL query as the denominator for % cached
- ENTRY_SELECT_COLS adds cacheable_bytes at index 13 (with children
  subquery, same as total_artifact_bytes)
- list_root_entries adds same expression
- All 6 row-mapping closures include cacheable_bytes: row.get(13)?

EntryRow.jsx:
- SIZE display stays: formatBytes(entry.total_artifact_bytes)
- % cached badge uses cacheable_bytes as denominator:
  cached_bytes / cacheable_bytes * 100

* feat(frontend): j/k keyboard navigation for entries; test avatar cached_bytes

App.jsx — j/k handler:
- Fires on keydown when not focused on INPUT/TEXTAREA/SELECT/contenteditable
- Ignores meta/ctrl/alt modifier combos
- Uses DOM order (#entries-body [data-entry-uid]) so expanded child rows
  participate, matching the shift-range selection logic
- Resolves target entry via entryCacheRef → root entries array →
  fetchEntryDetail(..).summary on cache miss
- Scrolls target into view (block: nearest); updates lastAnchorIndexRef
  so subsequent shift-click ranges start from the keyboard-navigated row

archive.rs — cached_bytes_excludes_avatar_blobs test:
- Two tweet entries sharing an avatar blob (100B) and a media blob (900B)
- Asserts refresh_entry_cached_bytes sets cached_bytes = 900 (not 1000)
- Asserts list_root_entries summary: cached_bytes=900, cacheable_bytes=900,
  total_artifact_bytes=1000 — SIZE includes avatar, % cached denominator
  and numerator both exclude it

* fix(frontend): guard j/k uncached-child fetch with monotonic token

Rapid j/k over child rows that aren't in entryCacheRef triggers
fetchEntryDetail calls in parallel. Without a guard the last one to
settle wins, desyncing selectedUids (highlight) from selectedEntry
(detail panel/URL).

Fix:
- jkSeqRef (monotonic counter) incremented before each server fetch;
  the .then() guard tok === jkSeqRef.current drops results from
  superseded navigations
- handleRowClick increments jkSeqRef.current so any click also cancels
  an in-flight j/k fetch

* fix(frontend): guard ctrl/meta cache-miss fetch; add / search shortcut

App.jsx ctrl/meta branch: cache-miss fetchEntryDetail now captures
tok = ++jkSeqRef.current before the fetch and gates selectEntry on
tok === jkSeqRef.current — same pattern as the j/k handler — so a
slow response after a later click/navigate can't overwrite selection.

/ key: reuses the Cmd+K/Ctrl+K handler path (focus+select search input,
or pendingSearchFocus + archive view switch). Guards: editable targets
(INPUT/TEXTAREA/SELECT/contentEditable) and modifier keys are checked
before preventDefault() so typing / in inputs is untouched.

* feat(core): attempt SpotifyTrack via yt-dlp instead of hard-failing

Previously all Spotify sources returned an error claiming yt-dlp cannot
download DRM-protected audio. yt-dlp does have a Spotify extractor
(experimental, content-dependent), so refusing upfront is worse than
trying and letting it report the real failure.

SpotifyTrack now goes through the same yt-dlp metadata + audio-quality
download path as YouTubeMusicTrack. SpotifyAlbum and SpotifyPlaylist
still return an explicit error — fetch_playlist_info has YouTube-specific
URL fallback logic that would produce bogus child URLs for Spotify flat
entries; those sources need dedicated container handling first.

* chore: remove docs/superpowers from repo and gitignore whitelist

* feat(core+frontend): Spotify album/playlist capture via yt-dlp container path

Previously SpotifyAlbum and SpotifyPlaylist hard-failed with a DRM error.
yt-dlp does support Spotify (experimentally), so they now go through the
same probe/container/child path as YouTube playlists.

ytdlp.rs:
- Extract normalize_item_url() helper used by both fetch_playlist_info
  and probe_playlist_qualities; eliminates the duplicate URL-normalization
  blocks and the YouTube-specific fallback_host variable
- Fallback logic is now platform-aware: YouTube/YTM bare IDs → watch URL,
  Spotify → open.spotify.com/track/{id}, unknown → skip with warning

capture.rs:
- locator_to_playlist_url: accept SpotifyAlbum | SpotifyPlaylist so the
  probe-playlist endpoint accepts Spotify album/playlist URLs
- Container branch: add SpotifyAlbum | SpotifyPlaylist to the matches!
- is_audio: true for SpotifyAlbum | SpotifyPlaylist (audio-only, like YTM)
- child_source: SpotifyTrack for Spotify containers (not YouTubeMusicTrack)
- generate_entry_title and record_media_entry both use the correct child
  source so entity_kind, source_kind, and representation_kind are right

CaptureDialog.jsx:
- isPlaylistSource: recognise open.spotify.com/album/ and /playlist/,
  and spotify:album:ID / spotify:playlist:ID shorthands, so Spotify
  containers get the probe UI, per-track excludes, and sync toggle

* fix(core+server): partial playlist refresh + child visibility inheritance

database.rs:
- finish_archive_run: reverted 'partial' status (violates CHECK constraint);
  restored binary completed/failed
- get_run_completed_count(): new helper for callers that need to distinguish
  partial success without touching the DB status enum

capture.rs:
- CaptureResult gains completed_count: i64 (0 for single-item captures;
  populated from get_run_completed_count for container/playlist captures)
- All CaptureResult construction sites updated

routes.rs:
- Playlist job_status mapping: mark job 'completed' when completed_count > 0
  (even if status == 'failed'), so partially-successful playlist captures
  trigger onCaptured and show the archived entries without a manual reload.
  Truly zero-success runs (completed_count == 0, status == 'failed') stay
  failed as expected.
- probe_playlist_handler error message updated to mention Spotify

archive.rs (list_child_entries):
- Add third OR arm: children are visible when their parent container is in a
  collection visible to the caller. Fixes empty child list for non-admin
  users with access to a playlist container but not its newly-created
  children (which are all in the default 'private' collection).

* fix(server): use completed_count to distinguish partial from total failure

finish_archive_run is binary (completed/failed) — a playlist where some
tracks succeed and some fail returns status='failed'. Without this fix,
the job mapping treated any failed status as a job failure, causing
onCaptured to never fire and leaving successfully archived entries hidden
until a manual reload.

Now: job is 'failed' only when status='failed' && completed_count==0.
Partial runs (completed_count > 0) map to a completed job so the UI
refreshes and shows the entries that were successfully captured.

* fix(core+server): exclude container from child success count; rename field; tests

database.rs:
- get_run_completed_child_count(): renamed from get_run_completed_count and
  scoped to child items only (parent_item_id IS NOT NULL). The container
  run item is always completed first, so the old function inflated the count
  by at least 1 for every playlist, making all-video-failed runs appear as
  partial successes.
- New regression test: completed_child_count_excludes_container — completes
  both a root and a child item, asserts DB completed_count==2 while
  get_run_completed_child_count==1.

capture.rs:
- CaptureResult.completed_count renamed to completed_child_count to match
  the function and make the semantics unambiguous at the call site.

routes.rs:
- job_status decision now uses result.completed_child_count == 0 so that a
  playlist where every video fails (child_count==0) is correctly reported
  as a failed job, not a completed one.

archive.rs:
- New regression test: list_child_entries_inherits_parent_visibility —
  enrolls only the container in a USER-visible collection, asserts the
  child is visible to a USER caller and invisible to a GUEST caller.
This commit is contained in:
TheGeneralist 2026-07-21 21:57:29 +02:00 committed by GitHub
parent d202e177e1
commit 6377daadae
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
23 changed files with 2243 additions and 2640 deletions

View file

@ -86,6 +86,7 @@ export default function App() {
const [archives, setArchives] = useState([])
const [archiveId, setArchiveId] = useState(null)
const [entries, setEntries] = useState([])
const [deletedUids, setDeletedUids] = useState(() => new Set())
const [selectedEntryUid, setSelectedEntryUid] = useState(() => parseLocation().entry)
const [selectedEntry, setSelectedEntry] = useState(null)
const [selectedUids, setSelectedUids] = useState(() => {
@ -131,6 +132,11 @@ export default function App() {
const pendingSearchFocus = useRef(false)
const firstArchiveLoad = useRef(true)
const lastAnchorIndexRef = useRef(null)
// Monotonic token for j/k keyboard navigation; cancels stale fetchEntryDetail calls.
const jkSeqRef = useRef(0)
// uid entry object cache; populated on every row click so ctrl/shift
// selections can resolve child entries that aren't in the root entries array.
const entryCacheRef = useRef(new Map())
const humanizeTags = currentUser?.humanize_slugs ?? false;
@ -260,12 +266,20 @@ export default function App() {
}, [])
const handleRowClick = useCallback((entry, e) => {
// Cache every clicked entry so shift/ctrl can resolve child entries
// that are not present in the root `entries` array.
entryCacheRef.current.set(entry.entry_uid, entry)
// Invalidate any in-flight j/k uncached-child fetch.
++jkSeqRef.current
if (e.shiftKey && lastAnchorIndexRef.current !== null) {
e.preventDefault()
const anchorIdx = entries.findIndex(x => x.entry_uid === lastAnchorIndexRef.current)
const clickIdx = entries.findIndex(x => x.entry_uid === entry.entry_uid)
// Use DOM order so child rows (not in the `entries` array) participate
// in range selection. Every rendered row has data-entry-uid.
const allNodes = [...document.querySelectorAll('#entries-body [data-entry-uid]')]
const anchorIdx = allNodes.findIndex(n => n.dataset.entryUid === lastAnchorIndexRef.current)
const clickIdx = allNodes.findIndex(n => n.dataset.entryUid === entry.entry_uid)
if (anchorIdx === -1 || clickIdx === -1) {
// anchor evicted by search/filter/delete fall back to single select
lastAnchorIndexRef.current = entry.entry_uid
setSelectedUids(new Set([entry.entry_uid]))
selectEntry(entry)
@ -273,24 +287,41 @@ export default function App() {
}
const lo = Math.min(anchorIdx, clickIdx)
const hi = Math.max(anchorIdx, clickIdx)
const range = entries.slice(lo, hi + 1)
const uids = new Set(range.map(x => x.entry_uid))
const uids = new Set(allNodes.slice(lo, hi + 1).map(n => n.dataset.entryUid))
setSelectedUids(uids)
if (uids.size === 1) selectEntry(range[0])
if (uids.size === 1) selectEntry(entry)
} else if (e.ctrlKey || e.metaKey) {
lastAnchorIndexRef.current = entry.entry_uid
setSelectedUids(prev => {
const next = new Set(prev)
if (next.has(entry.entry_uid)) next.delete(entry.entry_uid)
else next.add(entry.entry_uid)
return next
})
const next = new Set(selectedUids)
if (next.has(entry.entry_uid)) next.delete(entry.entry_uid)
else next.add(entry.entry_uid)
setSelectedUids(next)
if (next.size === 0) {
selectEntry(null)
} else if (next.size === 1) {
// Resolve the remaining UID may be a child not in the root entries array
// and not yet cached (e.g. picked up via shift-range without a direct click).
const [remainingUid] = next
const cached = entryCacheRef.current.get(remainingUid)
?? entries.find(x => x.entry_uid === remainingUid)
?? null
if (cached) {
selectEntry(cached)
} else {
const tok = ++jkSeqRef.current
fetchEntryDetail(archiveId, remainingUid)
.then(det => { if (tok === jkSeqRef.current && det?.summary) selectEntry(det.summary) })
.catch(() => {})
}
} else {
selectEntry(null)
}
} else {
lastAnchorIndexRef.current = entry.entry_uid
setSelectedUids(new Set([entry.entry_uid]))
selectEntry(entry)
}
}, [entries, selectEntry])
}, [entries, selectedUids, selectEntry, archiveId])
const handleTagFilterSet = useCallback((fullPath) => {
setTagFilter(fullPath)
@ -342,18 +373,26 @@ export default function App() {
}, [archiveId, selectedEntry])
const handleEntryDeleted = useCallback((entryUid) => {
const isRoot = entries.some(e => e.entry_uid === entryUid)
setDeletedUids(prev => { const n = new Set(prev); n.add(entryUid); return n })
setEntries(prev => prev.filter(e => e.entry_uid !== entryUid))
setSelectedEntry(prev => prev?.entry_uid === entryUid ? null : prev)
setSelectedEntryUid(prev => prev === entryUid ? null : prev)
setSelectedUids(prev => { const n = new Set(prev); n.delete(entryUid); return n })
}, [])
// Child delete: parent row's child_count/size are stale reload after state updates.
if (!isRoot) loadEntries(archiveId, searchQuery, tagFilter)
}, [entries, archiveId, searchQuery, tagFilter, loadEntries])
const handleBulkDeleted = useCallback((uids) => {
const rootUids = new Set(entries.map(e => e.entry_uid))
const hasChildDelete = [...uids].some(u => !rootUids.has(u))
setDeletedUids(prev => { const n = new Set(prev); uids.forEach(u => n.add(u)); return n })
setEntries(prev => prev.filter(e => !uids.has(e.entry_uid)))
setSelectedUids(new Set())
setSelectedEntry(null)
setSelectedEntryUid(null)
}, [])
if (hasChildDelete) loadEntries(archiveId, searchQuery, tagFilter)
}, [entries, archiveId, searchQuery, tagFilter, loadEntries])
// Auto-snap: drive selectedEntryUid from selectedUids so URL sync and detail
// panel stay correct. size >= 2 clears single-entry state (bulk panel takes over).
@ -397,24 +436,81 @@ export default function App() {
if (current !== url) history.replaceState(null, '', url)
}, [searchQuery, tagFilter, selectedEntryUid, view])
// K / Ctrl+K: focus the search input, switching to archive view first if needed.
// K / Ctrl+K / /: focus the search input, switching to archive view first if needed.
useEffect(() => {
const handler = (e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault()
if (view === 'archive') {
searchInputRef.current?.focus()
searchInputRef.current?.select()
} else {
pendingSearchFocus.current = true
setView('archive')
}
const isSlash = e.key === '/' && !e.metaKey && !e.ctrlKey && !e.altKey
const isCmdK = (e.metaKey || e.ctrlKey) && e.key === 'k'
if (!isSlash && !isCmdK) return
// Don't intercept / when already typing in an input
const tag = document.activeElement?.tagName
if (isSlash && (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT')) return
if (isSlash && document.activeElement?.isContentEditable) return
e.preventDefault()
if (view === 'archive') {
searchInputRef.current?.focus()
searchInputRef.current?.select()
} else {
pendingSearchFocus.current = true
setView('archive')
}
}
document.addEventListener('keydown', handler)
return () => document.removeEventListener('keydown', handler)
}, [view])
// j/k: navigate entries down/up when not focused on an input element.
useEffect(() => {
const handler = (e) => {
// Ignore when a modifier is held (don't steal browser/app shortcuts)
if (e.metaKey || e.ctrlKey || e.altKey) return
if (e.key !== 'j' && e.key !== 'k') return
// Ignore when focus is on any editable target
const tag = document.activeElement?.tagName
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return
if (document.activeElement?.isContentEditable) return
const allNodes = [...document.querySelectorAll('#entries-body [data-entry-uid]')]
if (allNodes.length === 0) return
const [currentUid] = selectedUids.size === 1 ? selectedUids : [null]
const currentIdx = currentUid
? allNodes.findIndex(n => n.dataset.entryUid === currentUid)
: -1
const nextIdx = e.key === 'j'
? Math.min(currentIdx + 1, allNodes.length - 1)
: Math.max(currentIdx - 1, 0)
if (nextIdx === currentIdx && currentIdx !== -1) return
const nextNode = allNodes[nextIdx < 0 ? 0 : nextIdx]
const nextUid = nextNode.dataset.entryUid
lastAnchorIndexRef.current = nextUid
const tok = ++jkSeqRef.current
setSelectedUids(new Set([nextUid]))
// Resolve entry object: cache root entries array server fetch.
// Token guards against a slow fetch settling after the user has moved on.
const cached = entryCacheRef.current.get(nextUid)
?? entries.find(x => x.entry_uid === nextUid)
?? null
if (cached) {
selectEntry(cached)
} else {
fetchEntryDetail(archiveId, nextUid)
.then(det => { if (tok === jkSeqRef.current && det?.summary) selectEntry(det.summary) })
.catch(() => {})
}
nextNode.scrollIntoView({ block: 'nearest' })
e.preventDefault()
}
document.addEventListener('keydown', handler)
return () => document.removeEventListener('keydown', handler)
}, [selectedUids, entries, selectEntry, archiveId])
// After switching to archive view via K, focus the search input once rendered.
useEffect(() => {
if (view === 'archive' && pendingSearchFocus.current) {
@ -563,6 +659,7 @@ export default function App() {
onRowClick={handleRowClick}
archiveId={archiveId}
pendingCaptures={pendingCaptures}
deletedUids={deletedUids}
/>
)}
{view === 'runs' && <RunsView runs={runs} />}

View file

@ -25,6 +25,10 @@ export async function fetchEntryDetail(archiveId, entryUid) {
return getJson(`/api/archives/${archiveId}/entries/${entryUid}`);
}
export async function fetchEntryChildren(archiveId, entryUid) {
return getJson(`/api/archives/${archiveId}/entries/${entryUid}/children`);
}
// Fetch multiple artifact JSON payloads for an entry in parallel.
// Returns a Promise<Array> preserving index order.
export function fetchEntryArtifacts(archiveId, entryUid, indices) {
@ -149,6 +153,8 @@ export async function submitCapture(archiveId, locator, quality = null, extensio
if (typeof extensions.cookie_ext_enabled === 'boolean') payload.cookie_ext_enabled = extensions.cookie_ext_enabled
if (typeof extensions.modal_closer_enabled === 'boolean') payload.modal_closer_enabled = extensions.modal_closer_enabled
if (typeof extensions.via_freedium === 'boolean') payload.via_freedium = extensions.via_freedium
if (extensions.per_item_quality && typeof extensions.per_item_quality === 'object' && Object.keys(extensions.per_item_quality).length > 0) payload.per_item_quality = extensions.per_item_quality
if (extensions.sync === true) payload.sync = true
}
const res = await fetch(`/api/archives/${archiveId}/captures`, {
method: "POST",
@ -168,6 +174,19 @@ export async function probeCapture(archiveId, locator) {
return getJson(`/api/archives/${archiveId}/captures/probe?locator=${encodeURIComponent(locator)}`);
}
export async function probePlaylist(archiveId, locator) {
const res = await fetch(`/api/archives/${archiveId}/captures/probe-playlist`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ locator }),
})
if (!res.ok) {
const body = await res.json().catch(() => ({}))
throw new Error(body.error || `HTTP ${res.status}`)
}
return res.json()
}
export async function pollCaptureJob(archiveId, jobUid) {
return getJson(`/api/archives/${archiveId}/capture_jobs/${jobUid}`);
}

View file

@ -1,5 +1,5 @@
import { useRef, useEffect, useState, useCallback } from 'react'
import { submitCapture, pollCaptureJob, probeCapture, getInstanceSettings } from '../api'
import { submitCapture, pollCaptureJob, probeCapture, probePlaylist, getInstanceSettings } from '../api'
let nextItemId = 1
@ -14,7 +14,11 @@ function isVideoSource(locator) {
for (const scheme of ['yt:', 'youtube:']) {
if (ll.startsWith(scheme)) {
const after = ll.slice(scheme.length)
return after.startsWith('video/') || after.startsWith('short/') || after.startsWith('shorts/')
if (after.startsWith('video/') || after.startsWith('short/') || after.startsWith('shorts/'))
return true
// bare yt:ID exactly 11 chars [A-Za-z0-9_-], same predicate as is_youtube_video_id in core
if (/^[a-z0-9_-]{11}$/i.test(after)) return true
return false
}
}
@ -63,6 +67,52 @@ function isVideoSource(locator) {
return false
}
function isPlaylistSource(locator) {
const l = locator.trim()
const ll = l.toLowerCase()
// yt: / youtube: shorthands playlist, channel, @ handles
for (const scheme of ['yt:', 'youtube:']) {
if (ll.startsWith(scheme)) {
const after = ll.slice(scheme.length)
return after.startsWith('playlist/') || after.startsWith('@') ||
after.startsWith('channel/') || after.startsWith('c/') || after.startsWith('user/')
}
}
// ytm: shorthand playlist
if (ll.startsWith('ytm:')) {
return ll.slice(4).startsWith('playlist/')
}
// spotify: shorthands album and playlist (not track)
if (ll.startsWith('spotify:')) {
const after = ll.slice(8)
return after.startsWith('album:') || after.startsWith('playlist:')
}
// HTTP/HTTPS URLs
if (ll.startsWith('http://') || ll.startsWith('https://')) {
try {
const url = new URL(l)
const host = url.hostname
if (host === 'youtube.com' || host === 'www.youtube.com') {
if (url.pathname === '/playlist' && url.searchParams.has('list')) return true
if (url.pathname.startsWith('/@') || url.pathname.startsWith('/channel/') ||
url.pathname.startsWith('/c/') || url.pathname.startsWith('/user/')) return true
}
if (host === 'music.youtube.com') {
if (url.pathname === '/playlist' && url.searchParams.has('list')) return true
}
if (host === 'open.spotify.com') {
if (url.pathname.startsWith('/album/') || url.pathname.startsWith('/playlist/')) return true
}
} catch {}
}
return false
}
function makeItem(locator = '') {
return {
id: nextItemId++, locator, quality: 'best',
@ -71,9 +121,47 @@ function makeItem(locator = '') {
probeQualities: null, // null | string[] when done, e.g. ["1080p","720p","480p"]
probeHasAudio: false, // true when probe confirms at least one audio track
status: 'idle', error: null, jobUid: null, archiveId: null,
// playlist probe state
playlistProbeState: 'idle', // 'idle' | 'probing' | 'done' | 'error'
playlistInfo: null, // raw API response or null
playlistItems: null, // [{id, url, title, qualities, has_audio, quality}] or null
playlistQuality: null, // selected playlist-level quality string or null
playlistExpanded: false, // whether per-video list is expanded
syncEnabled: false, // sync mode toggle
}
}
function applyPlaylistQuality(newQ, currentItems) {
if (newQ === 'best') {
return currentItems.map(item => ({ ...item, quality: 'best' }))
}
if (newQ === 'audio') {
return currentItems.map(item => {
if (item.has_audio) return { ...item, quality: 'audio' }
// No audio track same conflict rule as unsupported height:
// keep a prior selection if one exists, otherwise leave null (blocks archive).
if (item.quality !== null) return item
return { ...item, quality: null }
})
}
return currentItems.map(item => {
// Exact match only: the video must list this quality in its available formats.
// maxHeight >= newHeight would be a cap (yt-dlp silent fallback), not what
// the user selected; a video with [2160p, 1080p] does NOT support 1440p.
if (item.qualities.includes(newQ)) {
return { ...item, quality: newQ }
}
// Quality not available for this item keep prior selection if one exists,
// otherwise null (conflict, blocks archive until user picks manually).
if (item.quality !== null) return item
return { ...item, quality: null }
})
}
function hasConflict(item) {
return Array.isArray(item.playlistItems) && item.playlistItems.some(pi => pi.quality === null)
}
export default function CaptureDialog({ open, archiveId, onClose, onCaptured, onToast, onJobStarted, onJobSettled, activeJobs = [] }) {
const dialogRef = useRef(null)
const isFirstRenderRef = useRef(true)
@ -105,7 +193,9 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
const idle = saved.filter(it => !it.status || it.status === 'idle')
if (idle.length > 0) {
idle.forEach(it => { if (it.id >= nextItemId) nextItemId = it.id + 1 })
return idle
// Merge with makeItem() defaults so items saved before the playlist
// fields were added don't have undefined where null/false is expected.
return idle.map(it => ({ ...makeItem(it.locator), ...it }))
}
}
} catch {}
@ -283,7 +373,7 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
onToastRef.current(text, null, type, headline)
}
async function submitBgJob(locator, quality, batchId) {
async function submitBgJob(locator, quality, batchId, extraExtensions = {}) {
const aid = archiveIdRef.current
const id = crypto.randomUUID?.() ?? `job-${Date.now()}-${Math.random()}`
// Capture session options at call time (synchronous before first await)
@ -293,6 +383,7 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
cookie_ext_enabled: cookieExtEnabled,
modal_closer_enabled: modalCloserEnabled,
via_freedium: freediumEnabled,
...extraExtensions,
}
try {
const job = await submitCapture(aid, locator, quality, extensions)
@ -309,19 +400,31 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
function handleArchive() {
const toSubmit = items.filter(it => it.locator.trim())
if (toSubmit.length === 0) return
if (toSubmit.some(it => hasConflict(it))) return
if (toSubmit.some(it => it.probeState === 'probing' ||
(isPlaylistSource(it.locator) && it.playlistProbeState !== 'done'))) return
if (toSubmit.some(it => Array.isArray(it.playlistItems) && it.playlistItems.length === 0)) return
const batchId = toSubmit.length > 1
? (crypto.randomUUID?.() ?? `batch-${Date.now()}`)
: null
if (batchId) {
batchRef.current.set(batchId, { total: toSubmit.length, archived: 0, warnings: 0, failed: 0, failedLocators: [], warningLocators: [] })
}
// Capture options at call time before any state changes
const capturedQuality = toSubmit.map(it => it.quality || 'best')
// Capture all submission data before any state changes
const submissions = toSubmit.map(it => ({
locator: it.locator.trim(),
quality: it.playlistItems !== null ? null : (it.quality || 'best'),
extraExtensions: it.playlistItems !== null
? { per_item_quality: Object.fromEntries(it.playlistItems.map(pi => [pi.id, pi.quality])), sync: it.syncEnabled }
: {},
}))
// Reset form and close dialog immediately
setItems([makeItem()])
dialogRef.current?.close()
// Submit each in background
toSubmit.forEach((it, i) => submitBgJob(it.locator.trim(), capturedQuality[i], batchId))
submissions.forEach(({ locator, quality, extraExtensions }) =>
submitBgJob(locator, quality, batchId, extraExtensions)
)
}
function addRow() {
@ -340,45 +443,108 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
function updateLocator(id, val) {
// Cancel any in-flight debounce and immediately clear stale probe results.
// This prevents old qualities from being visible (and submittable) while
// the 600ms debounce is pending for the new URL.
// the debounce is pending for the new URL.
clearTimeout(probeTimers.current.get(id))
setItems(prev => prev.map(it =>
it.id === id
? { ...it, locator: val, probeState: 'idle', probeQualities: null, probeHasAudio: false, quality: 'best' }
? { ...it, locator: val, probeState: 'idle', probeQualities: null, probeHasAudio: false, quality: 'best',
playlistProbeState: 'idle', playlistInfo: null, playlistItems: null, playlistQuality: null, playlistExpanded: false }
: it
))
if (!isVideoSource(val)) return
// Schedule a fresh probe after the user stops typing
const timer = setTimeout(async () => {
probeTimers.current.delete(id)
setItems(prev => prev.map(it => it.id === id ? { ...it, probeState: 'probing' } : it))
try {
const result = await probeCapture(archiveIdRef.current, val.trim())
setItems(prev => prev.map(it => {
if (it.id !== id || it.locator !== val) return it // stale locator changed again
const qualities = result.qualities ?? []
const hasAudio = result.has_audio ?? false
// Audio-only source: no video heights but audio confirmed force audio mode
const quality = (qualities.length === 0 && hasAudio) ? 'audio' : 'best'
return { ...it, probeState: 'done', probeQualities: qualities, probeHasAudio: hasAudio, quality }
}))
} catch {
// Probe failed (network error, etc.) clear silently; user can still submit
setItems(prev => prev.map(it =>
it.id === id ? { ...it, probeState: 'idle', probeQualities: null } : it
))
}
}, 600)
probeTimers.current.set(id, timer)
if (isVideoSource(val)) {
// Schedule a fresh probe after the user stops typing
const timer = setTimeout(async () => {
probeTimers.current.delete(id)
setItems(prev => prev.map(it => it.id === id ? { ...it, probeState: 'probing' } : it))
try {
const result = await probeCapture(archiveIdRef.current, val.trim())
setItems(prev => prev.map(it => {
if (it.id !== id || it.locator !== val) return it // stale locator changed again
const qualities = result.qualities ?? []
const hasAudio = result.has_audio ?? false
// Audio-only source: no video heights but audio confirmed force audio mode
const quality = (qualities.length === 0 && hasAudio) ? 'audio' : 'best'
return { ...it, probeState: 'done', probeQualities: qualities, probeHasAudio: hasAudio, quality }
}))
} catch {
// Probe failed (network error, etc.) clear silently; user can still submit
setItems(prev => prev.map(it =>
it.id === id ? { ...it, probeState: 'idle', probeQualities: null } : it
))
}
}, 600)
probeTimers.current.set(id, timer)
} else if (isPlaylistSource(val)) {
// Schedule a playlist probe (playlists are slower 800ms debounce)
const timer = setTimeout(async () => {
probeTimers.current.delete(id)
setItems(prev => prev.map(it => it.id === id ? { ...it, playlistProbeState: 'probing' } : it))
try {
const result = await probePlaylist(archiveIdRef.current, val.trim())
setItems(prev => prev.map(it => {
if (it.id !== id || it.locator !== val) return it // stale locator changed again
return {
...it,
playlistProbeState: 'done',
playlistInfo: result,
playlistItems: result.items.map(pi => ({ ...pi, quality: null })),
playlistQuality: null,
}
}))
} catch {
setItems(prev => prev.map(it =>
it.id === id ? { ...it, playlistProbeState: 'error' } : it
))
}
}, 800)
probeTimers.current.set(id, timer)
}
}
function updateQuality(id, val) {
setItems(prev => prev.map(it => it.id === id ? { ...it, quality: val } : it))
}
function updatePlaylistQuality(id, q) {
setItems(prev => prev.map(it => {
if (it.id !== id) return it
const newItems = applyPlaylistQuality(q, it.playlistItems)
return { ...it, playlistQuality: q, playlistItems: newItems }
}))
}
function updatePlaylistItemQuality(id, videoId, q) {
setItems(prev => prev.map(it => {
if (it.id !== id) return it
return { ...it, playlistItems: it.playlistItems.map(pi => pi.id === videoId ? { ...pi, quality: q } : pi) }
}))
}
function togglePlaylistExpanded(id) {
setItems(prev => prev.map(it => it.id === id ? { ...it, playlistExpanded: !it.playlistExpanded } : it))
}
function updateSync(id, val) {
setItems(prev => prev.map(it => it.id === id ? { ...it, syncEnabled: val } : it))
}
function deletePlaylistItem(itemId, videoId) {
setItems(prev => prev.map(it =>
it.id !== itemId ? it :
{ ...it, playlistItems: it.playlistItems.filter(pi => pi.id !== videoId) }
))
}
const pendingCount = items.filter(it => it.locator.trim()).length
const anyConflict = items.some(it => hasConflict(it))
// True if any playlist row has had all its videos deleted archive would be a no-op.
const anyEmptyPlaylist = items.some(it =>
Array.isArray(it.playlistItems) && it.playlistItems.length === 0
)
const anyProbing = items.some(it =>
it.probeState === 'probing' ||
// For playlist sources block unless probe completed successfully:
// idle = debounce not yet fired; probing = in flight; error = no quality data.
(isPlaylistSource(it.locator) && it.playlistProbeState !== 'done')
)
return (
<dialog ref={dialogRef} className="capture-dialog">
@ -407,6 +573,11 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
onQualityChange={val => updateQuality(item.id, val)}
onRemove={() => removeRow(item.id)}
onSubmit={handleArchive}
onPlaylistQualityChange={q => updatePlaylistQuality(item.id, q)}
onPlaylistItemQualityChange={(vid, q) => updatePlaylistItemQuality(item.id, vid, q)}
onPlaylistToggle={() => togglePlaylistExpanded(item.id)}
onSyncChange={val => updateSync(item.id, val)}
onPlaylistItemDelete={(vid) => deletePlaylistItem(item.id, vid)}
/>
))}
</div>
@ -530,7 +701,7 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
type="button"
className="capture-submit"
onClick={handleArchive}
disabled={pendingCount === 0}
disabled={pendingCount === 0 || anyConflict || anyProbing || anyEmptyPlaylist}
>
{pendingCount > 1 ? `Archive ${pendingCount}` : 'Archive'}
</button>
@ -543,7 +714,8 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
)
}
function CaptureRow({ item, autoFocus, onLocatorChange, onQualityChange, onRemove, onSubmit }) {
function CaptureRow({ item, autoFocus, onLocatorChange, onQualityChange, onRemove, onSubmit,
onPlaylistQualityChange, onPlaylistItemQualityChange, onPlaylistToggle, onSyncChange, onPlaylistItemDelete }) {
const inputRef = useRef(null)
useEffect(() => {
@ -554,6 +726,47 @@ function CaptureRow({ item, autoFocus, onLocatorChange, onQualityChange, onRemov
// Quality control shown right of the input
const qualityEl = (() => {
// Playlist source handling
if (isPlaylistSource(item.locator)) {
if (item.playlistProbeState === 'probing') {
return <span className="capture-quality-probing" aria-label="Probing playlist…"></span>
}
if (item.playlistProbeState === 'done') {
const allHeights = [...new Set(
item.playlistItems.flatMap(pi => pi.qualities.map(q => parseInt(q)))
)].sort((a, b) => b - a)
const allHaveAudio = item.playlistItems.every(pi => pi.has_audio)
const conflictCount = item.playlistItems.filter(pi => pi.quality === null).length
return (
<>
<select
className="capture-quality"
value={item.playlistQuality ?? ''}
onChange={e => onPlaylistQualityChange(e.target.value)}
aria-label="Playlist quality"
>
{!item.playlistQuality && <option value="" disabled>Select quality</option>}
<option value="best">Best quality</option>
{allHeights.map(h => <option key={h} value={`${h}p`}>{h}p</option>)}
{allHaveAudio && <option value="audio">Audio only</option>}
</select>
{conflictCount > 0 && (
<span className="capture-conflict-badge">{conflictCount} need selection</span>
)}
</>
)
}
if (item.playlistProbeState === 'error') {
return (
<span className="capture-quality-hint capture-quality-hint--error">
Probe failed edit URL to retry
</span>
)
}
return null
}
// Video source handling (unchanged)
if (!isVideoSource(item.locator)) return null
if (item.probeState === 'probing') {
return <span className="capture-quality-probing" aria-label="Checking available qualities"></span>
@ -565,8 +778,6 @@ function CaptureRow({ item, autoFocus, onLocatorChange, onQualityChange, onRemov
return <span className="capture-quality-hint">No media detected</span>
}
if (qualities.length === 0 && hasAudio) {
// Audio-only source: no video tracks, only audio available.
// Don't offer "Best quality" it would request a video format and fail.
return (
<select
className="capture-quality"
@ -594,9 +805,29 @@ function CaptureRow({ item, autoFocus, onLocatorChange, onQualityChange, onRemov
return null // probeState === 'idle', debounce not yet fired
})()
const syncToggle = isPlaylistSource(item.locator) && item.playlistProbeState === 'done' ? (
<label className="capture-sync-row">
<input type="checkbox" checked={item.syncEnabled} onChange={e => onSyncChange(e.target.checked)} />
<span>Sync skip already-archived videos</span>
</label>
) : null
return (
<div className="capture-row">
<div className="capture-row-main">
{isPlaylistSource(item.locator) ? (
item.playlistProbeState === 'done' ? (
<button
type="button"
className="capture-playlist-toggle capture-playlist-toggle--left"
onClick={onPlaylistToggle}
aria-label={item.playlistExpanded ? 'Collapse video list' : 'Expand video list'}
aria-expanded={item.playlistExpanded}
>
{item.playlistExpanded ? '▲' : '▼'}
</button>
) : null
) : null}
<input
ref={inputRef}
className="capture-input"
@ -618,6 +849,41 @@ function CaptureRow({ item, autoFocus, onLocatorChange, onQualityChange, onRemov
{item.error && (
<p className="capture-row-error">{item.error}</p>
)}
{isPlaylistSource(item.locator) && item.playlistProbeState === 'done' && item.playlistExpanded ? (
<div className="capture-playlist-items">
{item.playlistItems.map(pi => (
<div
key={pi.id}
className={`capture-playlist-item${pi.quality === null ? ' capture-playlist-item--conflict' : ''}`}
>
<span className="capture-playlist-item-title">{pi.title || pi.url}</span>
<select
className="capture-item-quality"
value={pi.quality ?? ''}
onChange={e => onPlaylistItemQualityChange(pi.id, e.target.value)}
aria-label={`Quality for ${pi.title || pi.url}`}
>
{pi.quality === null && <option value="" disabled>Choose</option>}
<option value="best">Best quality</option>
{pi.qualities.map(q => <option key={q} value={q}>{q}</option>)}
{pi.has_audio && <option value="audio">Audio only</option>}
</select>
{pi.quality === null && (
<span className="capture-playlist-conflict-badge">Choose quality</span>
)}
<button
type="button"
className="capture-playlist-item-remove"
aria-label={`Remove ${pi.title || pi.url}`}
onClick={() => onPlaylistItemDelete(pi.id)}
>
&times;
</button>
</div>
))}
{syncToggle}
</div>
) : syncToggle}
</div>
)
}

View file

@ -2,7 +2,7 @@ import SkeletonEntryRow from './SkeletonEntryRow';
import EntryRow from './EntryRow';
export default function EntriesView({ entries, selectedUids, onRowClick, archiveId, pendingCaptures = [] }) {
export default function EntriesView({ entries, selectedUids, onRowClick, archiveId, pendingCaptures = [], deletedUids }) {
return (
<section id="archive-view" className="view is-active">
<div className="entry-table">
@ -18,14 +18,17 @@ export default function EntriesView({ entries, selectedUids, onRowClick, archive
{pendingCaptures.filter(c => c.archiveId === archiveId).reverse().map(cap => (
<SkeletonEntryRow key={cap.id} />
))}
{entries.map(entry => (
{entries.map((entry, idx) => (
<EntryRow
key={entry.entry_uid}
entry={entry}
rowIndex={idx}
archiveId={archiveId}
isSelected={selectedUids.size === 1 && selectedUids.has(entry.entry_uid)}
isMultiSelected={selectedUids.size >= 2 && selectedUids.has(entry.entry_uid)}
onRowClick={onRowClick}
selectedUids={selectedUids}
deletedUids={deletedUids}
/>
))}
</div>

View file

@ -1,8 +1,51 @@
import { useState } from 'react';
import { formatTimestamp, formatBytes, valueText, sourceIconSvg } from '../utils';
import { fetchEntryChildren } from '../api';
export default function EntryRow({ entry, archiveId, isSelected, isMultiSelected, onRowClick }) {
function ChildRow({ entry, index, onRowClick, selectedUids }) {
const isSelected = (selectedUids?.size === 1) && selectedUids.has(entry.entry_uid);
const isMultiSelected = (selectedUids?.size >= 2) && selectedUids.has(entry.entry_uid);
const cls = ['child-entry-row',
index % 2 === 0 ? 'child-entry-row--light' : 'child-entry-row--dark',
isSelected && 'is-selected',
isMultiSelected && 'is-multi-selected',
].filter(Boolean).join(' ');
return (
<div
className={cls}
tabIndex={0}
data-entry-uid={entry.entry_uid}
onMouseDown={e => { if (e.shiftKey) e.preventDefault(); }}
onClick={e => onRowClick(entry, e)}
onKeyDown={e => { if (e.key === 'Enter') onRowClick(entry, e); }}
>
<div className="col-check" aria-hidden="true" />
<div className="col-added">{formatTimestamp(entry.archived_at)}</div>
<div className="col-title">
<span className="source-icon">
<span dangerouslySetInnerHTML={{ __html: sourceIconSvg(entry.source_kind) }} />
</span>
<span className="entry-title">{valueText(entry.title) || valueText(entry.entry_uid)}</span>
</div>
<div className="col-type">
<span className="type-pill">{valueText(entry.entity_kind)}</span>
</div>
<div className="col-size">
<span className="size-total">{formatBytes(entry.total_artifact_bytes)}</span>
</div>
<div className="url-cell col-url">{valueText(entry.original_url)}</div>
</div>
);
}
export default function EntryRow({ entry, archiveId, rowIndex, isSelected, isMultiSelected, onRowClick, selectedUids, deletedUids }) {
const [favFailed, setFavFailed] = useState(false);
const [expanded, setExpanded] = useState(false);
const [children, setChildren] = useState(null);
const [childrenLoading, setChildrenLoading] = useState(false);
const showFavicon =
entry.source_kind === 'web' &&
entry.entity_kind === 'page' &&
@ -24,49 +67,108 @@ export default function EntryRow({ entry, archiveId, isSelected, isMultiSelected
);
const checked = isSelected || isMultiSelected;
const hasChildren = entry.child_count > 0;
function handleCheckboxClick(e) {
e.stopPropagation();
// treat checkbox tap as ctrl+click: toggle this entry without clearing others
onRowClick(entry, { ctrlKey: true, metaKey: false, shiftKey: false, preventDefault() {} });
}
async function handleExpandClick(e) {
e.stopPropagation();
if (expanded) {
setExpanded(false);
return;
}
setExpanded(true);
if (children === null && !childrenLoading) {
setChildrenLoading(true);
try {
const result = await fetchEntryChildren(archiveId, entry.entry_uid);
setChildren(result);
} catch (_) {
setChildren([]);
} finally {
setChildrenLoading(false);
}
}
}
const outerClass = [
'entry-row-outer',
rowIndex % 2 === 0 ? 'entry-row-outer--light' : 'entry-row-outer--dark',
isSelected && 'is-selected',
isMultiSelected && 'is-multi-selected',
].filter(Boolean).join(' ');
return (
<div
className={[isSelected && 'is-selected', isMultiSelected && 'is-multi-selected'].filter(Boolean).join(' ') || undefined}
tabIndex={0}
data-entry-uid={entry.entry_uid}
onMouseDown={e => { if (e.shiftKey) e.preventDefault() }}
onClick={e => onRowClick(entry, e)}
onKeyDown={e => { if (e.key === 'Enter') onRowClick(entry, e) }}
>
<div className="col-check">
<button
type="button"
className={`row-checkbox${checked ? ' is-checked' : ''}`}
aria-pressed={checked}
aria-label={checked ? 'Deselect entry' : 'Select entry'}
onClick={handleCheckboxClick}
onKeyDown={e => e.stopPropagation()}
/>
<div className={outerClass} data-entry-uid={entry.entry_uid}>
<div
className="entry-row-main"
tabIndex={0}
onMouseDown={e => { if (e.shiftKey) e.preventDefault(); }}
onClick={e => onRowClick(entry, e)}
onKeyDown={e => { if (e.key === 'Enter') onRowClick(entry, e); }}
>
<div className="col-check">
<button
type="button"
className={`row-checkbox${checked ? ' is-checked' : ''}`}
aria-pressed={checked}
aria-label={checked ? 'Deselect entry' : 'Select entry'}
onClick={handleCheckboxClick}
onKeyDown={e => e.stopPropagation()}
/>
</div>
<div className="col-added">{formatTimestamp(entry.archived_at)}</div>
<div className="col-title">
{hasChildren && (
<button
type="button"
className={`entry-expand-btn${expanded ? ' is-expanded' : ''}`}
aria-label={expanded ? 'Collapse children' : `Expand ${entry.child_count} items`}
aria-expanded={expanded}
onClick={handleExpandClick}
onKeyDown={e => e.stopPropagation()}
/>
)}
<span className="source-icon">{icon}</span>
<span className="entry-title">{valueText(entry.title) || valueText(entry.entry_uid)}</span>
{hasChildren && (
<span className="child-count-badge" aria-hidden="true">{entry.child_count}</span>
)}
</div>
<div className="col-type">
<span className="type-pill">{valueText(entry.entity_kind)}</span>
</div>
<div className="col-size">
<span className="size-total">{formatBytes(entry.total_artifact_bytes)}</span>
{entry.cached_bytes > 0 && entry.cacheable_bytes > 0 && (
<span className="size-cached-pct" title={`${formatBytes(entry.cached_bytes)} already on disk from an earlier entry`}>
{Math.round(entry.cached_bytes / entry.cacheable_bytes * 100)}% cached
</span>
)}
</div>
<div className="url-cell col-url">{valueText(entry.original_url)}</div>
</div>
<div className="col-added">{formatTimestamp(entry.archived_at)}</div>
<div className="col-title">
<span className="source-icon">{icon}</span>
<span className="entry-title">{valueText(entry.title) || valueText(entry.entry_uid)}</span>
</div>
<div className="col-type">
<span className="type-pill">{valueText(entry.entity_kind)}</span>
</div>
<div className="col-size">
<span className="size-total">{formatBytes(entry.total_artifact_bytes)}</span>
{entry.cached_bytes > 0 && entry.total_artifact_bytes > 0 && (
<span className="size-cached-pct" title={`${formatBytes(entry.cached_bytes)} already on disk from an earlier entry`}>
{Math.round(entry.cached_bytes / entry.total_artifact_bytes * 100)}% cached
</span>
)}
</div>
<div className="url-cell col-url">{valueText(entry.original_url)}</div>
{expanded && (
<>
{childrenLoading && <div className="child-entries-loading">Loading</div>}
<div className="child-entries" aria-label={`${entry.child_count} child entries`}>
{children && children
.filter(c => !deletedUids?.has(c.entry_uid))
.map((child, idx) => (
<ChildRow
key={child.entry_uid}
entry={child}
index={idx}
onRowClick={onRowClick}
selectedUids={selectedUids}
/>
))}
</div>
</>
)}
</div>
);
}

View file

@ -299,17 +299,19 @@ select {
border-bottom: 1px solid var(--line-soft);
}
#entries-body > div > div { padding: 7px 10px; flex-shrink: 0; overflow: hidden; }
#entries-body > div:nth-child(even) { background: #f2ede5; }
#entries-body > div:nth-child(odd) { background: var(--paper-3); }
/* Skeleton rows (no index class) fall back to nth-child; real rows use explicit classes. */
#entries-body > div:not(.entry-row-outer):nth-child(even) { background: #f2ede5; }
#entries-body > div:not(.entry-row-outer):nth-child(odd) { background: var(--paper-3); }
/* Index-based stripes for real entry rows — immune to skeleton sibling count. */
#entries-body > .entry-row-outer--light { background: var(--paper-3); }
#entries-body > .entry-row-outer--dark { background: #f2ede5; }
#entries-body > div.is-selected {
background: #eee2d2;
outline: 2px solid var(--accent);
outline-offset: -2px;
box-shadow: inset 0 0 0 2px var(--accent);
}
#entries-body > div.is-multi-selected {
background: #eee2d2;
outline: 2px solid var(--accent);
outline-offset: -2px;
box-shadow: inset 0 0 0 2px var(--accent);
}
.col-added { width: 162px; color: var(--muted); }
@ -339,8 +341,7 @@ select {
.source-icon > * { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; }
.source-icon svg { width: 100%; height: 100%; }
.url-cell { color: #555b55; white-space: nowrap; text-overflow: ellipsis; word-break: break-all; }
#entries-body .url-cell:hover,
#entries-body .is-selected .url-cell { overflow: visible; white-space: normal; }
#entries-body .url-cell:hover { overflow: visible; white-space: normal; }
.type-pill { display: inline-block; padding: 2px 6px; background: #d8e3df; color: #275a5f; border: 1px solid #bfd0ca; border-radius: var(--r); }
/* ── Multi-select checkbox column ───────────────────────────────────────── */
@ -890,6 +891,7 @@ select {
color: var(--muted);
font-style: italic;
}
.capture-quality-hint--error { color: #c05000; font-style: normal; }
/* Status dot */
.cap-dot {
@ -2726,3 +2728,254 @@ body.has-audio-bar { padding-bottom: 56px; }
@media (pointer: coarse) {
.skeleton-row .col-added { padding-left: 10px; }
}
/* ── Child entry expansion ───────────────────────────────────────────────── */
/* Outer wrapper: one block per entry-group so nth-child stays correct.
#entries-body > .entry-row-outer beats #entries-body > div on specificity
(id + class > id + element) so display:flex is safely overridden. */
#entries-body > .entry-row-outer {
display: block;
border-bottom: none;
}
/* Inner flex row: replicates the #entries-body > div row behaviour. */
#entries-body > .entry-row-outer > .entry-row-main {
display: flex;
align-items: center;
cursor: default;
border-bottom: 1px solid var(--line-soft);
/* Reset padding that #entries-body > div > div would otherwise apply. */
padding: 0;
flex-shrink: unset;
overflow: visible;
}
/* Column cells inside the inner row. */
#entries-body > .entry-row-outer > .entry-row-main > div {
padding: 7px 10px;
flex-shrink: 0;
overflow: hidden;
}
#entries-body > .entry-row-outer > .entry-row-main > div:last-child { padding-right: 22px; }
#entries-body > .entry-row-outer > .entry-row-main .col-added { padding-left: 22px; }
/* Selection: class lives on outer wrapper; background + stroke scoped to inner row
so expanded child entries don't inherit the selection highlight. */
#entries-body > .entry-row-outer.is-selected { background: unset; outline: none; box-shadow: none; }
#entries-body > .entry-row-outer.is-multi-selected { background: unset; outline: none; box-shadow: none; }
#entries-body > .entry-row-outer.is-selected > .entry-row-main {
background: #eee2d2;
box-shadow: inset 0 0 0 2px var(--accent);
}
#entries-body > .entry-row-outer.is-multi-selected > .entry-row-main {
background: #eee2d2;
box-shadow: inset 0 0 0 2px var(--accent);
}
/* URL overflow on hover only — explicit pointer, not selection. */
#entries-body > .entry-row-outer .url-cell:hover { overflow: visible; white-space: normal; }
/* child-entries container: reset the padding that #entries-body > div > div applies. */
#entries-body > .entry-row-outer > .child-entries {
display: block;
padding: 0;
flex-shrink: unset;
overflow: visible;
border-left: 2px solid var(--line-soft);
margin-left: 32px;
}
/* Each child row reuses the same .col-* flex widths as normal rows. */
.child-entry-row {
display: flex;
align-items: center;
cursor: default;
border-bottom: 1px solid var(--line-soft);
opacity: 0.88;
}
.child-entry-row:hover { opacity: 1; }
.child-entry-row:last-child { border-bottom: none; }
.child-entry-row--light { background: #fafaf8; }
.child-entry-row--dark { background: #f2f0ec; }
.child-entry-row.is-selected {
background: #eee2d2;
box-shadow: inset 0 0 0 2px var(--accent);
opacity: 1;
}
.child-entry-row.is-multi-selected {
background: #eee2d2;
box-shadow: inset 0 0 0 2px var(--accent);
opacity: 1;
}
.child-entry-row > div {
padding: 6px 10px;
flex-shrink: 0;
overflow: hidden;
}
.child-entry-row .col-added { padding-left: 22px; }
.child-entry-row > div:last-child { padding-right: 22px; }
/* Expand chevron button */
.entry-expand-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
flex-shrink: 0;
padding: 0;
margin-right: 2px;
background: none;
border: none;
cursor: pointer;
opacity: 0.45;
color: inherit;
transition: opacity 0.15s;
}
.entry-expand-btn:focus { outline: none; }
.entry-expand-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 2px; }
.entry-expand-btn::before {
content: '';
display: block;
width: 0;
height: 0;
border-top: 4px solid transparent;
border-bottom: 4px solid transparent;
border-left: 6px solid currentColor;
transition: transform 0.15s;
}
.entry-expand-btn:hover { opacity: 1; }
.entry-expand-btn.is-expanded::before { transform: rotate(90deg); }
/* Child count badge next to title */
.child-count-badge {
display: inline-block;
margin-left: 5px;
padding: 0 5px;
font-size: 0.72em;
font-weight: 600;
background: color-mix(in srgb, var(--line-soft) 60%, transparent);
border-radius: 10px;
opacity: 0.75;
vertical-align: middle;
line-height: 1.6;
}
/* Loading placeholder inside child-entries */
.child-entries-loading {
padding: 8px 12px;
font-size: 0.85em;
opacity: 0.55;
}
/* ── Playlist quality expansion ──────────────────────────── */
.capture-playlist-toggle {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 0.75rem;
color: var(--muted);
background: none;
border: none;
cursor: pointer;
padding: 2px 6px;
}
.capture-playlist-toggle:hover { color: var(--text); }
.capture-playlist-toggle--left {
flex-shrink: 0;
padding: 2px 4px;
font-size: 0.7rem;
}
.capture-conflict-badge {
font-size: 0.7rem;
color: #c07000;
background: #fff3cd;
border: 1px solid #e0a000;
border-radius: 4px;
padding: 1px 6px;
margin-left: 6px;
}
.capture-playlist-items {
border-top: 1px solid var(--line-soft);
max-height: 320px;
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: var(--line) transparent;
}
.capture-playlist-item {
display: flex;
align-items: center;
gap: 8px;
padding: 5px 10px 5px 14px;
font-size: 0.8rem;
border-bottom: 1px solid var(--line-soft);
border-left: 3px solid transparent;
}
.capture-playlist-item:last-of-type { border-bottom: none; }
.capture-playlist-item--conflict {
border-left-color: #c07000;
background: color-mix(in srgb, #c07000 6%, transparent);
}
.capture-playlist-item-title {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--text);
opacity: 0.9;
}
.capture-item-quality {
font-size: 0.73rem;
padding: 2px 4px;
border: 1px solid var(--line);
border-radius: 3px;
background: var(--paper-3);
color: var(--text);
flex-shrink: 0;
}
.capture-playlist-conflict-badge {
font-size: 0.68rem;
font-weight: 600;
color: #c07000;
white-space: nowrap;
flex-shrink: 0;
}
.capture-playlist-item-remove {
flex-shrink: 0;
display: inline-flex;
align-items: center;
justify-content: center;
width: 18px;
height: 18px;
padding: 0;
border: none;
background: none;
color: var(--muted);
cursor: pointer;
border-radius: 3px;
opacity: 0.3;
transition: opacity 0.1s, color 0.1s;
}
.capture-playlist-item:hover .capture-playlist-item-remove,
.capture-playlist-item-remove:focus-visible { opacity: 1; }
.capture-playlist-item-remove:hover { color: #c04000; opacity: 1; }
@media (pointer: coarse) { .capture-playlist-item-remove { opacity: 1; } }
.capture-playlist-item-remove { font-size: 0.75rem; line-height: 1; }
.capture-sync-row {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
font-size: 0.78rem;
color: var(--muted);
border-top: 1px solid var(--line-soft);
cursor: pointer;
}
.capture-sync-row input[type=checkbox] { cursor: pointer; }