diff --git a/src/main.rs b/src/main.rs index 4944d43..2ea6721 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,6 +20,7 @@ //! HQ thumbnails reserve their proportional 4:3 footprint before loading, avoiding metadata reflow. //! Thumbnails have one column of left padding and two columns before the left-aligned text. //! A blank row separates the bold title from the dimmed author · publication date. +//! Full descriptions keep the same metadata header fixed above a body with one-column side padding. //! Description excerpts use normal brightness and retain a two-column right gutter. //! Overflowing excerpts end with … without splitting wide glyphs; full descriptions preserve paragraphs. //! Both modes share an in-memory LRU of 64 full descriptions, keyed by video ID across views. @@ -102,7 +103,7 @@ use youtube::{Job, PAGE_SIZE, Page, PlayerLaunch, Video}; #[command( version, about = "Browse YouTube and open selected videos in Terebi", - after_help = "Requires yt-dlp for browsing; thumbnails also use curl. Playback requires Terebi and its own streaming dependencies.\nDefaults to terebi on PATH; --player overrides the CLI path.\nTerebi receives --new-instance --url followed by the canonical YouTube video URL and handles extraction, decoding, and playback itself; each selection opens an independent player instance without replacing existing playback.\nAlways start in NORMAL. A CLI query is searched automatically; otherwise press i to enter a query.\nINSERT: type to edit; Enter submits if changed and returns to NORMAL; Esc returns without submitting.\nTEXT EDITING (search, category filter, and new tag): Option/Alt+Backspace or Ctrl-W deletes the previous whitespace-delimited word, including trailing whitespace; Cmd/Super+Backspace or Ctrl-U clears the entire line. Plain Backspace removes one character.\nThe terminal must transmit modified Backspace. If it intercepts Option/Cmd, map those shortcuts to Ctrl-W/Ctrl-U respectively.\nNORMAL: j/k or arrows select; Enter opens the video in Terebi; i edits the query; d opens video info (again for full description); c browses saved categories; s edits channel tags; S edits all channels in the current category; q quits.\nSearch and Feed are permanent tabs. Pinned categories also stay visible; one temporary category tab is replaced by each new unpinned selection.\nTab/Shift-Tab cycle only visible tabs; r reloads config and refreshes the current view from its first page.\nCATEGORY BROWSER (c): starts NORMAL; j/k or arrows move; i enters INSERT to filter; Enter browses; p immediately saves pin/unpin; Esc closes. Choosing a pinned category focuses its existing tab and clears the temporary tab.\nCATEGORY FILTER INSERT: type a case-insensitive substring to filter live; arrows or Ctrl-J/K move; Enter browses the selected match; Esc returns to NORMAL with the filter retained. In NORMAL, j/k and pinning operate on the filtered list. No matches makes Enter/p a no-op. Reopening the selector clears the filter.\nHidden category views retain loaded rows, selection, and pagination for this session. Temporary tabs do not survive restarting; pins do.\nPUBLISHED: Every video view shows YYYY-MM-DD. Exact upload dates take precedence; ~ marks an estimated UTC date from flat metadata, and Unknown means unavailable. Dates are cached without fetching full metadata for every video.\nLOADING: Result/feed and preview titles show an animated spinner while content loads, including further pages and thumbnail decoding/resizing; it disappears when ready or on error.\nFeed sits immediately right of Search and combines every saved [channels] registration, including untagged channels, plus channels entered directly in tags.\nChannel URLs and videos are deduplicated; Feed keeps its cached selection and page position when only tag assignments change.\nSubscriptions: $XDG_CONFIG_HOME/tubular/config.toml, or ~/.config/tubular/config.toml when XDG_CONFIG_HOME is unset/empty/relative.\nExample TOML:\npinned_categories = [\"Favorites\"]\n[categories]\nCreators = [\"@jawed\"]\nFavorites = [\"@jawed\"]\n[channels]\n\"@jawed\" = \"https://www.youtube.com/channel/UC4QobU6STFB0P71PMvOGN5A\"\npinned_categories is a top-level array of category names; pins referencing removed categories are ignored.\n[categories] defines flat, overlapping tags, each with its own feed; there is no hierarchy or inheritance.\nEntries accept @handles, HTTPS YouTube channel URLs, or canonical UC channel IDs.\n[channels] registers saved handles with canonical channel URLs/IDs; feeds use these stable identities.\nChecked tags save the handle plus its mapping; existing URLs/aliases are replaced with the handle, preserving comments.\nUnchecked tags remove only that channel's tag assignment; other creators, omitted tags, empty tag arrays, saved registrations, and pins are retained.\nUntagging does not unsubscribe from Feed. To unsubscribe, remove all of that channel's [channels] mappings and tag entries, then press r.\nUnmapped handles work directly. Existing URL entries still load.\nSaving a single channel requires a handle and canonical ID; unavailable metadata or conflicting mappings are reported without changing the file.\nPAGINATION: Search loads 20 results per page; Feed and tags request 20 uploads per channel's /videos tab per page.\nMoving near the loaded end in NORMAL fetches more asynchronously, preserving existing rows, selection, and previews. Insert mode and open popups pause automatic prefetch.\nFeed views merge newest-first using approximate upload dates. Older uploads wait while newer channel pages catch up; undated uploads appear when the feed is exhausted.\nStatus shows the page and whether more is available or the end is reached. Switching views cancels pending extraction; returning resumes the same range with cached rows intact.\nPage errors retain loaded rows and stop automatic retries; r reloads config and restarts the current view from page one.\nDeep pages may take longer because yt-dlp offsets re-traverse earlier continuation pages.\nTAGS (s): existing assignments are checked; j/k or arrows move; Space toggles; Enter saves all staged memberships; n prompts for a new tag; Esc cancels without writing.\nBULK TAGS (S, category views only): edits all saved channels in the current category, not just channels with loaded videos. Tags shared by every target start checked; mixed memberships start unchecked. Enter atomically applies the exact checked tag set to every target, removing targets from all unchecked categories while leaving other channels untouched. Empty categories, registrations, pins, and comments remain. n stages a new category for all targets; Esc cancels without saving. If source channels changed while editing, close and reopen. Clearing all tags is refused if any target lacks a [channels] registration, so category-only subscriptions are not accidentally lost.\nNEW TAG: type a name; Enter stages it checked and returns to the list; Esc abandons the name; Ctrl-U clears.\nNew tags and membership changes reach disk only on Enter in the main tag list.\nVIDEO INFO: d opens thumbnail and details; d again expands the full description inside the same popup; another d returns to info. Esc closes.\nThe popup uses up to 70% width and 60% height, capped at 96 by 20 cells.\nFull descriptions preserve paragraphs; Up/Down or Ctrl-J/K scroll lines and PgUp/PgDn scroll pages. Plain j/k selects videos in either mode.\nThumbnails have one column of left padding and two columns before the text. Image space is reserved before loading so metadata does not shift when decoding finishes.\nThe title is bold, only author/publication metadata is dimmed, and readable excerpts end with an ellipsis when clipped.\nImages fit proportionally on resize. Terminal graphics are detected at startup, falling back to colored half-blocks.\nDownloading, JPEG decoding, and image resizing/encoding do not block navigation.\nSwitching info/description retains in-flight work and cached content. Full descriptions have a session LRU of 64; thumbnails retain eight inactive images plus the selected image.\ni, c, s, S, view changes, and refresh dismiss the preview; successful refresh clears its caches. Typing d or t in INSERT edits text.\nCtrl-C quits in any mode or popup.\nThe player CLI exits once macOS accepts the handoff; Tubular reports launcher errors, while later extraction/playback errors appear in Terebi.\nSelecting another video opens a new Terebi player, leaving existing playback untouched. Quitting Tubular cancels only pending metadata/CLI work; Terebi continues playing independently.\nExample: tubular \"rust programming\"" + after_help = "Requires yt-dlp for browsing; thumbnails also use curl. Playback requires Terebi and its own streaming dependencies.\nDefaults to terebi on PATH; --player overrides the CLI path.\nTerebi receives --new-instance --url followed by the canonical YouTube video URL and handles extraction, decoding, and playback itself; each selection opens an independent player instance without replacing existing playback.\nAlways start in NORMAL. A CLI query is searched automatically; otherwise press i to enter a query.\nINSERT: type to edit; Enter submits if changed and returns to NORMAL; Esc returns without submitting.\nTEXT EDITING (search, category filter, and new tag): Option/Alt+Backspace or Ctrl-W deletes the previous whitespace-delimited word, including trailing whitespace; Cmd/Super+Backspace or Ctrl-U clears the entire line. Plain Backspace removes one character.\nThe terminal must transmit modified Backspace. If it intercepts Option/Cmd, map those shortcuts to Ctrl-W/Ctrl-U respectively.\nNORMAL: j/k or arrows select; Enter opens the video in Terebi; i edits the query; d opens video info (again for full description); c browses saved categories; s edits channel tags; S edits all channels in the current category; q quits.\nSearch and Feed are permanent tabs. Pinned categories also stay visible; one temporary category tab is replaced by each new unpinned selection.\nTab/Shift-Tab cycle only visible tabs; r reloads config and refreshes the current view from its first page.\nCATEGORY BROWSER (c): starts NORMAL; j/k or arrows move; i enters INSERT to filter; Enter browses; p immediately saves pin/unpin; Esc closes. Choosing a pinned category focuses its existing tab and clears the temporary tab.\nCATEGORY FILTER INSERT: type a case-insensitive substring to filter live; arrows or Ctrl-J/K move; Enter browses the selected match; Esc returns to NORMAL with the filter retained. In NORMAL, j/k and pinning operate on the filtered list. No matches makes Enter/p a no-op. Reopening the selector clears the filter.\nHidden category views retain loaded rows, selection, and pagination for this session. Temporary tabs do not survive restarting; pins do.\nPUBLISHED: Every video view shows YYYY-MM-DD. Exact upload dates take precedence; ~ marks an estimated UTC date from flat metadata, and Unknown means unavailable. Dates are cached without fetching full metadata for every video.\nLOADING: Result/feed and preview titles show an animated spinner while content loads, including further pages and thumbnail decoding/resizing; it disappears when ready or on error.\nFeed sits immediately right of Search and combines every saved [channels] registration, including untagged channels, plus channels entered directly in tags.\nChannel URLs and videos are deduplicated; Feed keeps its cached selection and page position when only tag assignments change.\nSubscriptions: $XDG_CONFIG_HOME/tubular/config.toml, or ~/.config/tubular/config.toml when XDG_CONFIG_HOME is unset/empty/relative.\nExample TOML:\npinned_categories = [\"Favorites\"]\n[categories]\nCreators = [\"@jawed\"]\nFavorites = [\"@jawed\"]\n[channels]\n\"@jawed\" = \"https://www.youtube.com/channel/UC4QobU6STFB0P71PMvOGN5A\"\npinned_categories is a top-level array of category names; pins referencing removed categories are ignored.\n[categories] defines flat, overlapping tags, each with its own feed; there is no hierarchy or inheritance.\nEntries accept @handles, HTTPS YouTube channel URLs, or canonical UC channel IDs.\n[channels] registers saved handles with canonical channel URLs/IDs; feeds use these stable identities.\nChecked tags save the handle plus its mapping; existing URLs/aliases are replaced with the handle, preserving comments.\nUnchecked tags remove only that channel's tag assignment; other creators, omitted tags, empty tag arrays, saved registrations, and pins are retained.\nUntagging does not unsubscribe from Feed. To unsubscribe, remove all of that channel's [channels] mappings and tag entries, then press r.\nUnmapped handles work directly. Existing URL entries still load.\nSaving a single channel requires a handle and canonical ID; unavailable metadata or conflicting mappings are reported without changing the file.\nPAGINATION: Search loads 20 results per page; Feed and tags request 20 uploads per channel's /videos tab per page.\nMoving near the loaded end in NORMAL fetches more asynchronously, preserving existing rows, selection, and previews. Insert mode and open popups pause automatic prefetch.\nFeed views merge newest-first using approximate upload dates. Older uploads wait while newer channel pages catch up; undated uploads appear when the feed is exhausted.\nStatus shows the page and whether more is available or the end is reached. Switching views cancels pending extraction; returning resumes the same range with cached rows intact.\nPage errors retain loaded rows and stop automatic retries; r reloads config and restarts the current view from page one.\nDeep pages may take longer because yt-dlp offsets re-traverse earlier continuation pages.\nTAGS (s): existing assignments are checked; j/k or arrows move; Space toggles; Enter saves all staged memberships; n prompts for a new tag; Esc cancels without writing.\nBULK TAGS (S, category views only): edits all saved channels in the current category, not just channels with loaded videos. Tags shared by every target start checked; mixed memberships start unchecked. Enter atomically applies the exact checked tag set to every target, removing targets from all unchecked categories while leaving other channels untouched. Empty categories, registrations, pins, and comments remain. n stages a new category for all targets; Esc cancels without saving. If source channels changed while editing, close and reopen. Clearing all tags is refused if any target lacks a [channels] registration, so category-only subscriptions are not accidentally lost.\nNEW TAG: type a name; Enter stages it checked and returns to the list; Esc abandons the name; Ctrl-U clears.\nNew tags and membership changes reach disk only on Enter in the main tag list.\nVIDEO INFO: d opens thumbnail and details; d again expands the full description inside the same popup; another d returns to info. Esc closes.\nThe popup uses up to 70% width and 60% height, capped at 96 by 20 cells.\nFull descriptions have one-column left/right padding and a fixed bold title above the dimmed author/publication row. Only the description body scrolls; paragraphs are preserved. Up/Down or Ctrl-J/K scroll lines and PgUp/PgDn scroll pages. Plain j/k selects videos in either mode.\nThumbnails have one column of left padding and two columns before the text. Image space is reserved before loading so metadata does not shift when decoding finishes.\nThe title is bold, only author/publication metadata is dimmed, and readable excerpts end with an ellipsis when clipped.\nImages fit proportionally on resize. Terminal graphics are detected at startup, falling back to colored half-blocks.\nDownloading, JPEG decoding, and image resizing/encoding do not block navigation.\nSwitching info/description retains in-flight work and cached content. Full descriptions have a session LRU of 64; thumbnails retain eight inactive images plus the selected image.\ni, c, s, S, view changes, and refresh dismiss the preview; successful refresh clears its caches. Typing d or t in INSERT edits text.\nCtrl-C quits in any mode or popup.\nThe player CLI exits once macOS accepts the handoff; Tubular reports launcher errors, while later extraction/playback errors appear in Terebi.\nSelecting another video opens a new Terebi player, leaving existing playback untouched. Quitting Tubular cancels only pending metadata/CLI work; Terebi continues playing independently.\nExample: tubular \"rust programming\"" )] struct Options { /// Terebi CLI executable; accepts --new-instance --url followed by a YouTube video URL. @@ -1340,15 +1341,6 @@ impl App { let popup = preview_area(frame.area()); frame.render_widget(Clear, popup); let block = Block::bordered().border_style(Style::new().fg(Color::Cyan)); - let block = if mode == PreviewMode::Description { - block.title_bottom(Line::from(vec![ - " ".into(), - video.title.as_str().into(), - " ".into(), - ])) - } else { - block - }; let inner = block.inner(popup); let cached = cached_description(&self.descriptions, &video.id); let text = match cached { @@ -1359,22 +1351,8 @@ impl App { .as_deref() .unwrap_or("Loading full description..."), }; - if mode == PreviewMode::Description { - let paragraph = Paragraph::new(text).wrap(Wrap { trim: false }); - let viewport = (inner.width, inner.height); - if self.description_viewport != Some(viewport) { - self.description_max_scroll = if viewport.0 == 0 || viewport.1 == 0 { - 0 - } else { - paragraph - .line_count(viewport.0) - .saturating_sub(viewport.1 as usize) - .min(u16::MAX as usize) as u16 - }; - self.description_viewport = Some(viewport); - } - self.description_scroll = self.description_scroll.min(self.description_max_scroll); - frame.render_widget(paragraph.scroll((self.description_scroll, 0)), inner); + let mut details = if mode == PreviewMode::Description { + inner.inner(ratatui::layout::Margin::new(1, 0)) } else { let [_, image, _, mut details] = Layout::horizontal([ Constraint::Length(1), @@ -1388,35 +1366,53 @@ impl App { details.x -= reclaimed; details.width += reclaimed; details.width = details.width.saturating_sub(2); - let metadata = Paragraph::new(vec![ - Line::raw(video.title.as_str()).bold(), - Line::default(), - Line::from(vec![ - video.channel.as_deref().unwrap_or("Unknown").into(), - " · ".into(), - video - .publication_date - .as_deref() - .unwrap_or("Unknown") - .into(), - ]) - .dim(), + details + }; + let metadata = Paragraph::new(vec![ + Line::raw(video.title.as_str()).bold(), + Line::default(), + Line::from(vec![ + video.channel.as_deref().unwrap_or("Unknown").into(), + " · ".into(), + video + .publication_date + .as_deref() + .unwrap_or("Unknown") + .into(), ]) - .wrap(Wrap { trim: true }); - let height = if details.is_empty() { - 0 - } else { - metadata - .line_count(details.width) - .min(details.height as usize) as u16 - }; - let mut excerpt = details; - let gap = (excerpt.height - height).min(1); - excerpt.y += height + gap; - excerpt.height -= height + gap; - details.height = height; - frame.render_widget(metadata, details); - let paragraph = Paragraph::new(text).wrap(Wrap { trim: false }); + .dim(), + ]) + .wrap(Wrap { trim: true }); + let height = if details.is_empty() { + 0 + } else { + metadata + .line_count(details.width) + .min(details.height as usize) as u16 + }; + let mut excerpt = details; + let gap = (excerpt.height - height).min(1); + excerpt.y += height + gap; + excerpt.height -= height + gap; + details.height = height; + frame.render_widget(metadata, details); + let paragraph = Paragraph::new(text).wrap(Wrap { trim: false }); + if mode == PreviewMode::Description { + let viewport = (excerpt.width, excerpt.height); + if self.description_viewport != Some(viewport) { + self.description_max_scroll = if excerpt.is_empty() { + 0 + } else { + paragraph + .line_count(viewport.0) + .saturating_sub(viewport.1 as usize) + .min(u16::MAX as usize) as u16 + }; + self.description_viewport = Some(viewport); + } + self.description_scroll = self.description_scroll.min(self.description_max_scroll); + frame.render_widget(paragraph.scroll((self.description_scroll, 0)), excerpt); + } else { let overflow = cached.is_some_and(|text| !text.is_empty()) && !excerpt.is_empty() && paragraph.line_count(excerpt.width) > usize::from(excerpt.height); @@ -3159,10 +3155,9 @@ mod tests { .unwrap(); let buffer = terminal.backend().buffer(); let popup = preview_area(buffer.area); - let caption: String = (popup.x..popup.right()) - .map(|x| buffer[(x, popup.bottom() - 1)].symbol()) - .collect(); - assert!(caption.contains(" Second ")); + let title = &buffer[(popup.x + 2, popup.y + 1)]; + assert_eq!(title.symbol(), "S"); + assert!(title.modifier.contains(ratatui::style::Modifier::BOLD)); press(&mut app, KeyCode::Down); assert_eq!(app.description_scroll, 1); assert_eq!(app.views[0].selection.selected(), Some(1)); @@ -3194,4 +3189,66 @@ mod tests { assert_eq!(app.query, "td"); assert_eq!(app.preview, None); } + + #[test] + fn full_description_keeps_padded_metadata_visible_while_scrolling() { + use ratatui::{Terminal, backend::TestBackend, style::Modifier}; + + let mut app = app(&["tubular"]); + app.views[0].videos = youtube::search_results( + r#"{"entries":[{"id":"jNQXAC9IVRw","title":"Selected video","channel":"Creator","upload_date":"20050423"}]}"#, + ).unwrap().videos; + app.views[0].selection.select(Some(0)); + app.preview = Some(PreviewMode::Description); + app.remember_description( + "jNQXAC9IVRw".into(), + (0..100).map(|i| format!("Body line {i:03}\n")).collect(), + ); + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + terminal + .draw(|frame| app.draw(frame, Duration::ZERO)) + .unwrap(); + let before = terminal.backend().buffer().clone(); + let popup = preview_area(before.area); + let x = popup.x + 2; + let title_y = popup.y + 1; + let body_y = (title_y..popup.bottom() - 1) + .find(|&y| before[(x, y)].symbol() == "B") + .expect("description is visible below metadata"); + assert!(before[(x, title_y)].modifier.contains(Modifier::BOLD)); + assert!(before[(x, title_y + 2)].modifier.contains(Modifier::DIM)); + assert!(!before[(x, body_y)].modifier.contains(Modifier::DIM)); + assert_eq!( + app.description_viewport, + Some((popup.width - 4, popup.bottom() - 1 - body_y)) + ); + app.key(KeyEvent::new(KeyCode::Char('j'), KeyModifiers::CONTROL)); + terminal + .draw(|frame| app.draw(frame, Duration::ZERO)) + .unwrap(); + let after = terminal.backend().buffer(); + for y in title_y..body_y { + for x in popup.x + 1..popup.right() - 1 { + assert_eq!(before[(x, y)], after[(x, y)], "metadata must stay fixed"); + } + } + let row = |buffer: &ratatui::buffer::Buffer, y| -> String { + (x..popup.right() - 2) + .map(|x| buffer[(x, y)].symbol()) + .collect() + }; + assert_eq!(row(&before, body_y).trim_end(), "Body line 000"); + assert_eq!(row(after, body_y).trim_end(), "Body line 001"); + for y in title_y..popup.bottom() - 1 { + assert_eq!(after[(popup.x + 1, y)].symbol(), " "); + assert_eq!(after[(popup.right() - 2, y)].symbol(), " "); + } + // When the wrapped header consumes the pane, there is no scrollable viewport. + let mut narrow = Terminal::new(TestBackend::new(12, 8)).unwrap(); + narrow + .draw(|frame| app.draw(frame, Duration::ZERO)) + .unwrap(); + assert_eq!(app.description_max_scroll, 0); + assert_eq!(app.description_scroll, 0); + } }