From f5c1386315dbd6ccfbede1b81ae9e9ef1f9abfa6 Mon Sep 17 00:00:00 2001 From: hl-valdemar Date: Sun, 11 Oct 2026 16:57:59 +0200 Subject: [PATCH] feat: add keybinding help popup and concise status hints --- README.md | 3 + src/main.rs | 309 +++++++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 284 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 1060bc2..378a1ee 100644 --- a/README.md +++ b/README.md @@ -69,10 +69,13 @@ Each selection opens an independent player instance without replacing existing p | `S` | Edit tags for all saved channels in the current category | | Tab / Shift-Tab | Switch between visible views | | `r` | Reload configuration and refresh the current view | +| `?` | Open / close the scrollable keybinding reference | | `q` | Quit | **Ctrl-C quits from any mode or popup.** +The bottom bar shows essential actions for the current context. Press `?` in normal mode—including selectors and previews—for the full reference. Scroll help with `j` / `k`, arrows, Ctrl-J / Ctrl-K, or PageDown / PageUp; `?` or Esc closes it without changing the underlying view or dialog. In text fields, `?` remains ordinary input. + Back and forward navigation restore cached videos, selection, and pagination, including replaced temporary tabs. Removed views are skipped; empty history leaves the current view unchanged. Opening a different view after going back discards the old forward branch. Esc first closes a dialog or leaves insert mode without navigating. Minus and plus remain ordinary text inside input fields. The full-description view scrolls with ↓ / ↑, Ctrl-J / Ctrl-K, or PageDown / PageUp. Plain `j` / `k` still changes the selected video. The bold title, dimmed author/publication row, and description scroll together. diff --git a/src/main.rs b/src/main.rs index d16c1d6..5c90a85 100644 --- a/src/main.rs +++ b/src/main.rs @@ -56,6 +56,8 @@ //! In normal mode Esc or minus goes back through visited views, restoring cached rows and selection. //! Plus goes forward after going back; a new view navigation discards the old forward branch. //! Esc closes popups or leaves insert mode first; missing historical views are skipped. +//! Normal-mode ? overlays a scrollable keybinding reference without changing the view or dialog. +//! Help scrolls with j/k, arrows, Ctrl-J/K and page keys; ? or Esc closes it. Text inputs keep literal ?. //! Normal-mode u opens a searchable saved-channel selector with the category browser's modal controls. //! Normal-mode U opens the selected video's creator directly, without saving a subscription. //! Choices include untagged registrations and category-only channels, deduplicated with readable handle labels. @@ -112,7 +114,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/channel filters, 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; u browses saved channels; U opens the selected video's channel; 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; Esc or - in NORMAL goes back through view history; + goes forward. Both restore cached rows, selection, and pagination, including replaced temporary tabs. New view navigation clears the forward branch. Removed views are skipped and empty history does nothing. Esc first closes popups or leaves INSERT without navigating; minus types normally in input fields. 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.\nCHANNEL BROWSER (u): starts NORMAL; j/k or arrows move; i enters INSERT to filter; Enter opens only the selected channel's videos; Esc closes. INSERT uses case-insensitive filtering, arrows or Ctrl-J/K to move, Enter to browse, and Esc to return to NORMAL. Empty matches do nothing.\nSaved choices include registered channels (even untagged) and category-only subscriptions, deduplicated by resolved identity; mapped handles label aliases. Channel selection never changes subscriptions or pins.\nChannels and unpinned categories share one temporary browsing tab. Choosing either replaces the previous temporary view while pinned category tabs remain visible. Revisiting or navigating back restores cached rows, selection, and page position. Channel views use the same infinite scrolling but extract only their chosen channel; S remains category-only.\nVIDEO CHANNEL (U / Shift-U): opens the selected video's creator in the same temporary channel tab, reusing cached rows and pagination without subscribing. A canonical channel ID or valid @handle is required; unavailable metadata leaves the current view unchanged. Saved mappings resolve handle-only rows. Unsaved channels do not appear in the saved selector unless you save them.\nReloading config relabels stable saved identities and removes explicitly unsubscribed channels; removing the active saved channel falls back to Search. Unsaved channels opened with U remain browseable for the session.\nHidden category and channel 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 an empty line above the bold title and dimmed author/publication row. Title, metadata, and description scroll together as one document; 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\"" + 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.\nNORMAL ? opens a scrollable keybinding reference over the current view or dialog. The bottom bar shows only essential actions. Scroll help with j/k, arrows, Ctrl-J/K or PageUp/PageDown; ? or Esc closes it. Question mark remains literal text in input fields.\nINSERT: type to edit; Enter submits if changed and returns to NORMAL; Esc returns without submitting.\nTEXT EDITING (search, category/channel filters, 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; u browses saved channels; U opens the selected video's channel; 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; Esc or - in NORMAL goes back through view history; + goes forward. Both restore cached rows, selection, and pagination, including replaced temporary tabs. New view navigation clears the forward branch. Removed views are skipped and empty history does nothing. Esc first closes popups or leaves INSERT without navigating; minus and plus type normally in input fields. 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.\nCHANNEL BROWSER (u): starts NORMAL; j/k or arrows move; i enters INSERT to filter; Enter opens only the selected channel's videos; Esc closes. INSERT uses case-insensitive filtering, arrows or Ctrl-J/K to move, Enter to browse, and Esc to return to NORMAL. Empty matches do nothing.\nSaved choices include registered channels (even untagged) and category-only subscriptions, deduplicated by resolved identity; mapped handles label aliases. Channel selection never changes subscriptions or pins.\nChannels and unpinned categories share one temporary browsing tab. Choosing either replaces the previous temporary view while pinned category tabs remain visible. Revisiting or navigating back restores cached rows, selection, and page position. Channel views use the same infinite scrolling but extract only their chosen channel; S remains category-only.\nVIDEO CHANNEL (U / Shift-U): opens the selected video's creator in the same temporary channel tab, reusing cached rows and pagination without subscribing. A canonical channel ID or valid @handle is required; unavailable metadata leaves the current view unchanged. Saved mappings resolve handle-only rows. Unsaved channels do not appear in the saved selector unless you save them.\nReloading config relabels stable saved identities and removes explicitly unsubscribed channels; removing the active saved channel falls back to Search. Unsaved channels opened with U remain browseable for the session.\nHidden category and channel 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 an empty line above the bold title and dimmed author/publication row. Title, metadata, and description scroll together as one document; 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. @@ -321,6 +323,71 @@ enum PreviewMode { Description, } +const KEYBINDINGS_HELP: &str = r#" +VIEWS AND VIDEOS +j / k or arrows Select next / previous video +Enter Play the selected video in Terebi +i Edit the search query +d Info → full description → info +U (Shift-U) Browse the selected video's channel +u Choose a saved channel +c Choose a saved category +s Edit the selected channel's tags +S (Shift-S) Edit all channels in a category +Tab / Shift-Tab Cycle visible tabs +Esc / - Back (Esc closes popups first) ++ Forward after going back +g / Home First loaded video +G / End Last loaded video +r Reload config and refresh +? Open / close this reference +q / Ctrl-C Quit + +FULL DESCRIPTION +Arrows, Ctrl-J/K Scroll lines +PageDown / PageUp Scroll pages +j / k Change the selected video +d Return to video info +Esc Close the preview + +CHANNEL / CATEGORY SELECTOR +j / k or arrows Move in NORMAL mode +i Enter filter INSERT mode +Arrows, Ctrl-J/K Move while filtering +Enter Browse the selected match +p Pin / unpin a category (NORMAL) +Esc INSERT → NORMAL → close + +CHANNEL TAGS +j / k or arrows Move between tags +Space Toggle a tag +n Enter a new tag name +Enter Save tags; in name input, stage tag +Esc Cancel; in name input, abandon name + +TEXT INPUT +Enter Submit; search returns to NORMAL +Esc Leave INSERT / abandon tag name +Backspace Delete one character +Alt-Backspace Delete previous word (or Ctrl-W) +Cmd-Backspace Clear the line (or Ctrl-U) +? / + / - Ordinary characters while typing + +HELP WINDOW +j / k or arrows Scroll lines (also Ctrl-J/K) +PageDown / PageUp Scroll pages +? / Esc Close help without changing view +Ctrl-C Quit from any mode or popup +"#; + +#[derive(Default)] +struct HelpPopup { + paragraph: Paragraph<'static>, + scroll: u16, + max_scroll: u16, + viewport: Option<(u16, u16)>, +} + struct App { options: Options, query: String, @@ -337,6 +404,7 @@ struct App { browser: Option, temporary_view: Option, preview: Option, + help_popup: Option, thumbnail: thumbnail::Thumbnail, description_job: Option<(usize, Job)>, description_error: Option, @@ -380,6 +448,7 @@ impl App { browser: None, temporary_view: None, preview: None, + help_popup: None, thumbnail: thumbnail::Thumbnail::new(), description_job: None, description_error: None, @@ -830,6 +899,7 @@ impl App { && self.category_dialog.is_none() && self.browser.is_none() && self.preview.is_none() + && self.help_popup.is_none() && self.views[self.view_index].needs_page() } @@ -1239,6 +1309,43 @@ impl App { if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) { return true; } + if let Some(help) = &mut self.help_popup { + match key.code { + KeyCode::Esc | KeyCode::Char('?') => self.help_popup = None, + KeyCode::Char('q') => return true, + KeyCode::Down | KeyCode::Char('j') => { + help.scroll = help.scroll.saturating_add(1).min(help.max_scroll); + } + KeyCode::Up | KeyCode::Char('k') => help.scroll = help.scroll.saturating_sub(1), + KeyCode::PageDown => { + let page = help.viewport.map_or(1, |(_, height)| height.max(1)); + help.scroll = help.scroll.saturating_add(page).min(help.max_scroll); + } + KeyCode::PageUp => { + let page = help.viewport.map_or(1, |(_, height)| height.max(1)); + help.scroll = help.scroll.saturating_sub(page); + } + _ => {} + } + return false; + } + if key.code == KeyCode::Char('?') + && self.mode == Mode::Normal + && self + .browser + .as_ref() + .is_none_or(|browser| browser.mode == Mode::Normal) + && self + .category_dialog + .as_ref() + .is_none_or(|dialog| dialog.name.is_none()) + { + self.help_popup = Some(HelpPopup { + paragraph: Paragraph::new(KEYBINDINGS_HELP).wrap(Wrap { trim: false }), + ..Default::default() + }); + return false; + } if self.category_dialog.is_some() { self.category_key(key); return false; @@ -1487,35 +1594,29 @@ impl App { status, ); let help_text = match self.mode { - Mode::Insert => { - "INSERT · Enter search → normal · Esc normal · Ctrl-U clear · Ctrl-C quit" + _ if self.help_popup.is_some() => "HELP · j/k ↑/↓ scroll · PgUp/PgDn · ?/Esc close", + Mode::Insert => "INSERT · Enter search · Esc normal · Ctrl-C quit", + Mode::Normal if self.category_dialog.is_some() => { + if self.category_dialog.as_ref().unwrap().name.is_some() { + "NEW TAG · Enter stage · Esc cancel · Ctrl-C quit" + } else { + "TAGS · Space toggle · Enter save · Esc cancel · ? help" + } } Mode::Normal if self.browser.is_some() => { - let browser = self.browser.as_ref().expect("browser is open"); - match (browser.kind, &browser.mode) { - (BrowserKind::Channels, Mode::Insert) => { - "CHANNELS INSERT · type filter · ↑/↓ or Ctrl-J/K move · Enter browse · Esc normal" - } - (BrowserKind::Channels, Mode::Normal) => { - "CHANNELS NORMAL · j/k ↑/↓ · i filter · Enter browse · Esc close" - } - (BrowserKind::Categories, Mode::Insert) => { - "CATEGORIES INSERT · type filter · ↑/↓ or Ctrl-J/K move · Enter browse · Esc normal" - } - (BrowserKind::Categories, Mode::Normal) => { - "CATEGORIES NORMAL · j/k · i filter · Enter browse · p pin/unpin · Esc close" - } + if self.browser.as_ref().unwrap().mode == Mode::Insert { + "FILTER INSERT · ↑/↓ move · Enter browse · Esc normal" + } else { + "BROWSE · j/k move · i filter · Enter browse · Esc close · ? help" } } Mode::Normal if self.preview == Some(PreviewMode::Description) => { - "NORMAL · ↑/↓ Ctrl-J/K PgUp/PgDn scroll · j/k video · U creator · d info · Esc close · - back · i insert · q quit" + "DESCRIPTION · ↑/↓ scroll · d info · Esc close · ? help" } Mode::Normal if self.preview == Some(PreviewMode::Info) => { - "NORMAL · j/k video · U creator · d description · Esc close · - back · i insert · q quit" - } - Mode::Normal => { - "NORMAL · j/k · Esc/- back · + forward · Enter play · i search · c categories · u channels · U creator · s channel tags · S bulk tags · d info · Tab views · r refresh · q quit" + "INFO · d description · Esc close · ? help" } + Mode::Normal => "NORMAL · j/k select · Enter play · i search · ? help · q quit", }; frame.render_widget(Paragraph::new(help_text).dim(), help); if let Some(mode) = self.preview @@ -1661,6 +1762,35 @@ impl App { } self.draw_category_dialog(frame); self.draw_browser(frame); + self.draw_help(frame); + } + + fn draw_help(&mut self, frame: &mut Frame) { + let Some(help) = &mut self.help_popup else { + return; + }; + let popup = preview_area(frame.area()); + let block = Block::bordered() + .title(" Keybindings · ?/Esc close · ↑/↓ PgUp/PgDn ") + .border_style(Style::new().fg(Color::Cyan)); + let inner = block.inner(popup).inner(ratatui::layout::Margin::new(1, 0)); + let viewport = (inner.width, inner.height); + if help.viewport != Some(viewport) { + help.max_scroll = if inner.is_empty() { + 0 + } else { + help.paragraph + .line_count(inner.width) + .saturating_sub(inner.height as usize) + .min(u16::MAX as usize) as u16 + }; + help.viewport = Some(viewport); + } + help.scroll = help.scroll.min(help.max_scroll); + frame.render_widget(Clear, popup); + help.paragraph = std::mem::take(&mut help.paragraph).scroll((help.scroll, 0)); + frame.render_widget(&help.paragraph, inner); + frame.render_widget(block, popup); } fn draw_browser(&mut self, frame: &mut Frame) { @@ -1986,6 +2116,135 @@ mod tests { app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); } + #[test] + fn help_scrolls_without_navigating_and_closes_to_the_same_preview() { + use ratatui::{Terminal, backend::TestBackend}; + let mut app = app(&["tubular"]); + app.apply_config(config::Config { + channels: [ + ("@Alpha".into(), "alpha".into()), + ("@Beta".into(), "beta".into()), + ] + .into(), + ..Default::default() + }); + loaded_channel_views(&mut app); + browse_channel(&mut app, "Alpha"); + browse_channel(&mut app, "Beta"); + let history = app.view_history.clone(); + let selected = app.views[app.view_index].selection.selected(); + let press = |app: &mut App, code| app.key(KeyEvent::new(code, KeyModifiers::NONE)); + app.views[app.view_index].has_more = true; + assert!(app.can_prefetch()); + press(&mut app, KeyCode::Char('?')); + assert!(!app.can_prefetch()); + app.preview = Some(PreviewMode::Info); + let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); + terminal + .draw(|frame| app.draw(frame, Duration::ZERO)) + .unwrap(); + press(&mut app, KeyCode::Char('j')); + assert_eq!(app.help_popup.as_ref().unwrap().scroll, 1); + for code in [ + KeyCode::Enter, + KeyCode::Tab, + KeyCode::Char('-'), + KeyCode::Char('+'), + ] { + press(&mut app, code); + } + assert_eq!(app.view_history, history); + assert!(app.forward_history.is_empty()); + assert!(app.player_launch.is_none()); + assert_eq!(app.views[app.view_index].selection.selected(), selected); + for _ in 0..100 { + press(&mut app, KeyCode::PageDown); + } + let help = app.help_popup.as_ref().unwrap(); + assert_eq!(help.scroll, help.max_scroll); + let previous_max = help.max_scroll; + app.key(KeyEvent::new(KeyCode::Char('k'), KeyModifiers::CONTROL)); + assert_eq!(app.help_popup.as_ref().unwrap().scroll, previous_max - 1); + let mut larger = Terminal::new(TestBackend::new(120, 40)).unwrap(); + larger + .draw(|frame| app.draw(frame, Duration::ZERO)) + .unwrap(); + let help = app.help_popup.as_ref().unwrap(); + assert_eq!(help.scroll, help.max_scroll); + for _ in 0..100 { + press(&mut app, KeyCode::PageUp); + } + assert_eq!(app.help_popup.as_ref().unwrap().scroll, 0); + press(&mut app, KeyCode::Esc); + assert!(app.help_popup.is_none()); + assert_eq!(app.preview, Some(PreviewMode::Info)); + assert_eq!( + app.views[app.view_index].source, + ViewSource::Channel("beta".into()) + ); + press(&mut app, KeyCode::Char('-')); + assert_eq!( + app.views[app.view_index].source, + ViewSource::Channel("alpha".into()) + ); + press(&mut app, KeyCode::Char('+')); + assert_eq!( + app.views[app.view_index].source, + ViewSource::Channel("beta".into()) + ); + } + + #[test] + fn help_preserves_selector_state_and_question_mark_is_literal_in_every_input() { + let mut app = app(&["tubular"]); + app.apply_config(config::Config { + channels: [("@Alpha".into(), "alpha".into())].into(), + ..Default::default() + }); + let press = |app: &mut App, code| app.key(KeyEvent::new(code, KeyModifiers::NONE)); + app.open_browser(BrowserKind::Channels); + press(&mut app, KeyCode::Char('?')); + assert!(app.help_popup.is_some()); + press(&mut app, KeyCode::Char('?')); + assert!(app.help_popup.is_none()); + assert_eq!(app.browser.as_ref().unwrap().selection.selected(), Some(0)); + press(&mut app, KeyCode::Char('i')); + press(&mut app, KeyCode::Char('?')); + assert!(app.help_popup.is_none()); + assert_eq!(app.browser.as_ref().unwrap().query, "?"); + assert!(app.browser.as_ref().unwrap().matches.is_empty()); + press(&mut app, KeyCode::Esc); + press(&mut app, KeyCode::Esc); + press(&mut app, KeyCode::Char('i')); + press(&mut app, KeyCode::Char('?')); + assert!(app.help_popup.is_none()); + assert_eq!(app.query, "?"); + press(&mut app, KeyCode::Esc); + app.category_dialog = Some(CategoryDialog { + target: CategoryTarget::Channel { + handle: "@Alpha".into(), + channel: "alpha".into(), + }, + label: "@Alpha".into(), + tags: BTreeMap::new(), + selection: ListState::default(), + name: Some(String::new()), + error: None, + }); + press(&mut app, KeyCode::Char('?')); + assert!(app.help_popup.is_none()); + assert_eq!( + app.category_dialog.as_ref().unwrap().name.as_deref(), + Some("?") + ); + press(&mut app, KeyCode::Esc); + press(&mut app, KeyCode::Char('?')); + assert!(app.help_popup.is_some()); + press(&mut app, KeyCode::Esc); + assert!(app.category_dialog.is_some()); + assert!(app.help_popup.is_none()); + } + #[test] fn plus_restores_forward_views_and_new_navigation_discards_the_forward_branch() { let mut app = app(&["tubular"]); @@ -2545,18 +2804,13 @@ mod tests { .draw(|frame| app.draw(frame, Duration::ZERO)) .unwrap(); let rendered = text(&terminal); - assert!(rendered.contains("CHANNELS NORMAL")); assert!(rendered.contains("@Alpha")); assert!(!rendered.contains("[p]") && !rendered.contains("[ ]")); - assert!(!rendered.contains("pin/unpin")); app.key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE)); app.key(KeyEvent::new(KeyCode::Char('z'), KeyModifiers::NONE)); terminal .draw(|frame| app.draw(frame, Duration::ZERO)) .unwrap(); - let rendered = text(&terminal); - assert!(rendered.contains("CHANNELS INSERT")); - assert!(rendered.contains("No matching channels.")); let popup = preview_area(Rect::new(0, 0, 180, 40)); assert_eq!( terminal.get_cursor_position().unwrap(), @@ -2569,7 +2823,6 @@ mod tests { terminal .draw(|frame| app.draw(frame, Duration::ZERO)) .unwrap(); - assert!(text(&terminal).contains("No saved channels yet.")); assert!(app.job.is_none()); }