From 16c57ea101f840ec8976a15843dfa34e9d3d34e1 Mon Sep 17 00:00:00 2001 From: hl-valdemar Date: Sun, 11 Oct 2026 12:50:16 +0200 Subject: [PATCH] feat: filter categories in modal selector --- src/main.rs | 276 +++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 252 insertions(+), 24 deletions(-) diff --git a/src/main.rs b/src/main.rs index b2cf2ff..7015414 100644 --- a/src/main.rs +++ b/src/main.rs @@ -36,7 +36,10 @@ //! Normal-mode s edits memberships: j/k moves, Space toggles, Enter commits, Esc cancels. //! n prompts for a new tag; Enter stages it checked, Esc returns. Only list Enter writes the file. //! Search and Feed are permanent tabs. Normal-mode c opens the saved-category browser. -//! j/k moves, Enter browses, p immediately persists pin/unpin, and Esc closes the browser. +//! The category browser starts NORMAL: j/k or arrows move, i filters, Enter browses, p pins, Esc closes. +//! INSERT filters live with case-insensitive substring matching; arrows or Ctrl-J/K move, Enter browses. +//! Esc returns to NORMAL without clearing the filter; another Esc closes. Search input editing shortcuts apply. +//! Matching selections survive filter edits; no matches leaves Enter/p without an action. //! Pinned categories stay visible; browsing another category replaces the single temporary tab. //! Browsing a pinned category focuses its existing tab and removes the temporary tab. //! Top-level `pinned_categories = ["Favorites"]` persists pins; missing category names are ignored. @@ -91,7 +94,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 --url followed by the canonical YouTube video URL and handles extraction, decoding, and playback itself; Tubular no longer pipes media to a player.\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 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 toggles description; t toggles thumbnail; c browses saved categories; s edits channel tags; 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): j/k or arrows move; Enter browses; p immediately saves pin/unpin; Esc closes. Choosing a pinned category focuses its existing tab and clears the temporary tab.\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 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.\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.\nOpening the description fetches full video metadata, preserving paragraphs and caching it for these results.\nPreview windows use up to 70% width and 60% height, capped at 96 by 20 cells.\nIn descriptions, Up/Down scroll lines and PgUp/PgDn scroll pages; j/k still selects videos.\nEsc closes the description; i closes it to edit the query. Scrolling stays within the text.\nTHUMBNAIL: t or Esc closes; j/k or arrows load the selected video's image; d switches to description.\nThumbnails are fetched lazily into memory and fit proportionally inside the popup on resize.\nTerminal graphics are detected at startup, with colored half-block rendering when image protocols are unavailable.\nDownloading, JPEG decoding, and image resizing/encoding do not block navigation.\ni, c, s, view changes, and refresh dismiss the thumbnail; typing t in INSERT or a tag name 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 reuses Terebi's window. 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 --url followed by the canonical YouTube video URL and handles extraction, decoding, and playback itself; Tubular no longer pipes media to a player.\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 toggles description; t toggles thumbnail; c browses saved categories; s edits channel tags; 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 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.\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.\nOpening the description fetches full video metadata, preserving paragraphs and caching it for these results.\nPreview windows use up to 70% width and 60% height, capped at 96 by 20 cells.\nIn descriptions, Up/Down scroll lines and PgUp/PgDn scroll pages; j/k still selects videos.\nEsc closes the description; i closes it to edit the query. Scrolling stays within the text.\nTHUMBNAIL: t or Esc closes; j/k or arrows load the selected video's image; d switches to description.\nThumbnails are fetched lazily into memory and fit proportionally inside the popup on resize.\nTerminal graphics are detected at startup, with colored half-block rendering when image protocols are unavailable.\nDownloading, JPEG decoding, and image resizing/encoding do not block navigation.\ni, c, s, view changes, and refresh dismiss the thumbnail; typing t in INSERT or a tag name 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 reuses Terebi's window. Quitting Tubular cancels only pending metadata/CLI work; Terebi continues playing independently.\nExample: tubular \"rust programming\"" )] struct Options { /// Terebi CLI executable; accepts --url followed by a YouTube video URL. @@ -228,10 +231,39 @@ struct CategoryDialog { } struct CategoryBrowser { + mode: Mode, + query: String, + search_names: Vec, + matches: Vec, selection: ListState, error: Option, } +impl CategoryBrowser { + fn refilter(&mut self) { + let selected = self + .selection + .selected() + .and_then(|row| self.matches.get(row)) + .copied(); + let query = self.query.to_lowercase(); + self.matches.clear(); + self.matches.extend( + self.search_names + .iter() + .enumerate() + .filter(|(_, name)| name.contains(&query)) + .map(|(index, _)| index), + ); + self.selection.select( + selected + .and_then(|index| self.matches.binary_search(&index).ok()) + .or_else(|| (!self.matches.is_empty()).then_some(0)), + ); + self.error = None; + } +} + struct App { options: Options, query: String, @@ -338,10 +370,22 @@ impl App { .position(|name| self.view_index >= 2 && name == &self.views[self.view_index].name) .or_else(|| (!self.config.categories.is_empty()).then_some(0)), ); - self.category_browser = Some(CategoryBrowser { - selection, + let mut browser = CategoryBrowser { + mode: Mode::Normal, + query: String::new(), + search_names: self + .config + .categories + .keys() + .map(|name| name.to_lowercase()) + .collect(), + matches: Vec::with_capacity(self.config.categories.len()), + selection: ListState::default(), error: None, - }); + }; + browser.refilter(); + browser.selection = selection; + self.category_browser = Some(browser); } fn browse_category_key(&mut self, key: KeyEvent) { @@ -349,9 +393,40 @@ impl App { .category_browser .take() .expect("category browser is open"); - let count = self.config.categories.len(); + if browser.mode == Mode::Insert { + match key.code { + KeyCode::Esc => browser.mode = Mode::Normal, + KeyCode::Enter | KeyCode::Up | KeyCode::Down => {} + KeyCode::Char('j' | 'k') if key.modifiers.contains(KeyModifiers::CONTROL) => {} + _ if delete_input(&mut browser.query, key) => { + browser.refilter(); + self.category_browser = Some(browser); + return; + } + KeyCode::Char(c) + if !key + .modifiers + .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) => + { + browser.query.push(c); + browser.refilter(); + self.category_browser = Some(browser); + return; + } + _ => { + self.category_browser = Some(browser); + return; + } + } + if key.code == KeyCode::Esc { + self.category_browser = Some(browser); + return; + } + } + let count = browser.matches.len(); match key.code { KeyCode::Esc => return, + KeyCode::Char('i') if browser.mode == Mode::Normal => browser.mode = Mode::Insert, KeyCode::Down | KeyCode::Char('j') if count != 0 => { browser.selection.select(Some( browser @@ -367,11 +442,14 @@ impl App { browser.selection.selected().unwrap_or(0).saturating_sub(1), )); } - KeyCode::Enter | KeyCode::Char('p') => { + KeyCode::Enter | KeyCode::Char('p') + if browser.mode == Mode::Normal || key.code == KeyCode::Enter => + { if let Some(name) = browser .selection .selected() - .and_then(|index| self.config.categories.keys().nth(index)) + .and_then(|row| browser.matches.get(row)) + .and_then(|index| self.config.categories.keys().nth(*index)) .cloned() { if key.code == KeyCode::Enter { @@ -389,11 +467,29 @@ impl App { let pinned = !self.config.pinned_categories.contains(&name); match config::set_category_pinned(&self.config_path, &name, pinned) { Ok(config) => { + let names_changed = + config.categories.keys().ne(self.config.categories.keys()); self.apply_config(config); self.switch_view(self.view_index); - browser - .selection - .select(self.config.categories.keys().position(|key| key == &name)); + if names_changed { + browser.search_names.clear(); + browser.search_names.extend( + self.config + .categories + .keys() + .map(|name| name.to_lowercase()), + ); + browser.refilter(); + browser.selection.select( + self.config + .categories + .keys() + .position(|key| key == &name) + .and_then(|index| { + browser.matches.binary_search(&index).ok() + }), + ); + } browser.error = None; } Err(error) => browser.error = Some(error.to_string()), @@ -1150,8 +1246,16 @@ impl App { Mode::Insert => { "INSERT · Enter search → normal · Esc normal · Ctrl-U clear · Ctrl-C quit" } + Mode::Normal + if self + .category_browser + .as_ref() + .is_some_and(|browser| browser.mode == Mode::Insert) => + { + "CATEGORIES INSERT · type filter · ↑/↓ or Ctrl-J/K move · Enter browse · Esc normal" + } Mode::Normal if self.category_browser.is_some() => { - "CATEGORIES · j/k · Enter browse · p pin/unpin · Esc close · Ctrl-C quit" + "CATEGORIES NORMAL · j/k · i filter · Enter browse · p pin/unpin · Esc close" } Mode::Normal if self.description_open => { "NORMAL · ↑/↓ PgUp/PgDn scroll · j/k video · d/Esc close · i insert · q quit" @@ -1324,14 +1428,35 @@ impl App { let popup = preview_area(frame.area()); frame.render_widget(Clear, popup); let block = Block::bordered() - .title(" Categories · Enter browse · p pin · Esc close ") + .title(" Categories · i filter · Enter browse · p pin ") .border_style(Style::new().fg(Color::Cyan)); - let [list, error] = Layout::vertical([ + let [input, list, error] = Layout::vertical([ + Constraint::Length(3), Constraint::Min(1), Constraint::Length(if browser.error.is_some() { 2 } else { 0 }), ]) .areas(block.inner(popup)); frame.render_widget(block, popup); + let input_block = Block::bordered().title(if browser.mode == Mode::Insert { + " Filter · INSERT " + } else { + " Filter · NORMAL " + }); + let text_area = input_block.inner(input); + let text = Line::raw(browser.query.as_str()); + let scroll = text + .width() + .saturating_sub(text_area.width.saturating_sub(1) as usize); + let cursor = text.width().saturating_sub(scroll) as u16; + frame.render_widget( + Paragraph::new(text) + .scroll((0, scroll.min(u16::MAX as usize) as u16)) + .block(input_block), + input, + ); + if browser.mode == Mode::Insert && text_area.width != 0 && text_area.height != 0 { + frame.set_cursor_position((text_area.x + cursor.min(text_area.width - 1), text_area.y)); + } if self.config.categories.is_empty() { frame.render_widget( Paragraph::new("No categories yet. Use s on a video to save its channel.") @@ -1339,18 +1464,31 @@ impl App { .dim(), list, ); + } else if browser.matches.is_empty() { + frame.render_widget(Paragraph::new("No matching categories.").dim(), list); } else { - let items = self.config.categories.keys().map(|name| { - Line::from(vec![ - if self.config.pinned_categories.contains(name) { - "[p] " - } else { - "[ ] " + let mut matches = browser.matches.iter().copied(); + let mut next = matches.next(); + let items = self + .config + .categories + .keys() + .enumerate() + .filter_map(|(index, name)| { + if next != Some(index) { + return None; } - .into(), - name.as_str().into(), - ]) - }); + next = matches.next(); + Some(Line::from(vec![ + if self.config.pinned_categories.contains(name) { + "[p] " + } else { + "[ ] " + } + .into(), + name.as_str().into(), + ])) + }); frame.render_stateful_widget( List::new(items) .highlight_symbol("> ") @@ -1561,6 +1699,96 @@ mod tests { ) } + #[test] + fn filtering_preserves_selected_categories_and_browses_the_filtered_row() { + let mut app = app(&["tubular"]); + app.query = "main search untouched".into(); + app.apply_config(config::Config { + categories: [ + ("Alpha".into(), vec![]), + ("Japanese immersion".into(), vec![]), + ("Japanese news".into(), vec![]), + ] + .into(), + ..config::Config::default() + }); + app.key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE)); + app.key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE)); + for c in "JAPANESE".chars() { + app.key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)); + } + app.key(KeyEvent::new(KeyCode::Char('j'), KeyModifiers::CONTROL)); + assert_eq!( + app.category_browser.as_ref().unwrap().selection.selected(), + Some(1) + ); + for c in " news".chars() { + app.key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)); + } + assert_eq!( + app.category_browser.as_ref().unwrap().selection.selected(), + Some(0) + ); + app.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + assert_eq!(app.category_browser.as_ref().unwrap().mode, Mode::Normal); + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(app.views[app.view_index].name, "Japanese news"); + assert_eq!(app.query, "main search untouched"); + assert!(app.category_browser.is_none()); + } + + #[test] + fn insert_filter_types_jk_handles_empty_matches_and_navigates_without_editing() { + let mut app = app(&["tubular"]); + app.apply_config(config::Config { + categories: [ + ("Alpha".into(), vec![]), + ("Jazz".into(), vec![]), + ("Jokes".into(), vec![]), + ("日本語だけで".into(), vec![]), + ] + .into(), + ..config::Config::default() + }); + app.key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE)); + app.key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE)); + for c in "jk".chars() { + app.key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)); + } + assert!( + app.category_browser + .as_ref() + .unwrap() + .selection + .selected() + .is_none() + ); + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert!(app.category_browser.is_some()); + assert_eq!(app.view_index, 0); + app.key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE)); + for (code, modifiers, row) in [ + (KeyCode::Char('j'), KeyModifiers::CONTROL, 1), + (KeyCode::Char('k'), KeyModifiers::CONTROL, 0), + (KeyCode::Down, KeyModifiers::NONE, 1), + (KeyCode::Up, KeyModifiers::NONE, 0), + ] { + app.key(KeyEvent::new(code, modifiers)); + assert_eq!( + app.category_browser.as_ref().unwrap().selection.selected(), + Some(row) + ); + } + assert_eq!(app.category_browser.as_ref().unwrap().query, "j"); + app.key(KeyEvent::new(KeyCode::Char('w'), KeyModifiers::CONTROL)); + for c in "日本".chars() { + app.key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)); + } + app.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + assert_eq!(app.views[app.view_index].name, "日本語だけで"); + assert_eq!(app.mode, Mode::Normal); + } + #[test] fn category_browser_replaces_the_temporary_tab_and_cycles_only_visible_views() { let mut app = app(&["tubular"]);