From 6afe229406b8cf9ff33a7655dfcbb5ebed8c91fb Mon Sep 17 00:00:00 2001 From: hl-valdemar Date: Sun, 11 Oct 2026 19:37:52 +0200 Subject: [PATCH] feat: filter channel category tagging --- README.md | 13 +- src/keys.rs | 22 ++- src/main.rs | 461 +++++++++++++++++++++++++++++++++++++++++----------- 3 files changed, 394 insertions(+), 102 deletions(-) diff --git a/README.md b/README.md index 0a37767..3f61348 100644 --- a/README.md +++ b/README.md @@ -85,11 +85,11 @@ The full-description view scrolls with ↓ / ↑, Ctrl-J / Ctrl-K, or PageDown / ### Text input -These shortcuts work in search, category/channel-filter, and new-tag fields: +These shortcuts work in search, category/channel/tag-filter, and new-tag fields: | Key | Action | | --- | --- | -| Enter | Submit the search, browse the selected category/channel, or stage the new tag | +| Enter | Submit the search, browse the selected category/channel, leave tag-filter mode, or stage the new tag | | Esc | Leave insert mode or abandon the new-tag name | | Backspace | Delete one character | | Option/Alt-Backspace or Ctrl-W | Delete the previous whitespace-delimited word | @@ -115,9 +115,12 @@ Press **`U` (Shift-U)** on a video to browse its creator directly, including cha ### Channel tags (`s`, or `S` for bulk editing) -- `j` / `k` or arrow keys navigate; Space toggles a tag. -- `n` prompts for a new tag name. Enter stages it checked and returns to the list. -- Enter **in the main tag list** saves the staged memberships. Esc cancels without writing. +- **Normal:** `j` / `k` or arrow keys navigate; Space toggles a tag; `i` edits the filter. +- **Insert:** type a case-insensitive substring to filter live; arrow keys or Ctrl-J / Ctrl-K navigate matches. Enter or Esc returns to normal mode without saving or clearing the filter. +- Filtering only hides rows: checked and unchecked staged memberships outside the filter are retained. With no matches, navigation and toggling do nothing. Reopening the dialog clears its filter. +- `n` prompts for a new tag name. Enter stages it checked, clears the filter, and selects the new tag; Esc abandons the name. +- Enter **in the normal-mode tag list** saves all staged memberships, including hidden tags. Esc cancels without writing. These controls apply to both single-channel and bulk tagging. +- Filter actions are configurable as `tags.edit`, `tags.input.next`, and `tags.input.previous`; text editing uses the shared `input.*` actions. Bulk editing applies the exact checked tag set to **every saved channel in the current category**, not only channels with loaded videos. Tags shared by every target start checked; mixed memberships start unchecked. Review the checked set before saving: unchecked tags are removed from all targets. Other channels, saved registrations, empty categories, pins, and comments are preserved. diff --git a/src/keys.rs b/src/keys.rs index 5c5ec7f..5e59574 100644 --- a/src/keys.rs +++ b/src/keys.rs @@ -17,6 +17,7 @@ pub enum Context { SelectorNormal, SelectorInput, TagList, + TagFilter, TagInput, Help, } @@ -29,6 +30,7 @@ const ALL: &[Context] = &[ Context::SelectorNormal, Context::SelectorInput, Context::TagList, + Context::TagFilter, Context::TagInput, Context::Help, ]; @@ -36,6 +38,7 @@ const VIEW: &[Context] = &[Context::Normal, Context::Info, Context::Description] const TEXT: &[Context] = &[ Context::SearchInput, Context::SelectorInput, + Context::TagFilter, Context::TagInput, ]; const NON_TEXT: &[Context] = &[ @@ -78,7 +81,7 @@ actions! { Interrupt, "app.interrupt", "Exit immediately", ALL, ["ctrl+c"]; Quit, "app.quit", "Quit the application", &[Context::Normal, Context::Info, Context::Description, Context::Help], ["q"]; Help, "help.toggle", "Open or close keyboard help", NON_TEXT, ["?"]; - InputSubmit, "input.submit", "Submit search, selector filter or new tag", TEXT, ["enter"]; + InputSubmit, "input.submit", "Submit search, browse selector, leave tag filter or stage new tag", TEXT, ["enter"]; InputCancel, "input.cancel", "Leave text input without submitting", TEXT, ["escape"]; DeleteCharacter, "input.delete.character", "Delete the previous character", TEXT, ["backspace"]; DeleteWord, "input.delete.word", "Delete the previous word", TEXT, ["alt+backspace", "ctrl+w"]; @@ -112,6 +115,9 @@ actions! { SelectorClose, "selector.close", "Close the category or channel picker", &[Context::SelectorNormal], ["escape"]; TagNext, "tags.select.next", "Select the next category tag", &[Context::TagList], ["j", "down"]; TagPrevious, "tags.select.previous", "Select the previous category tag", &[Context::TagList], ["k", "up"]; + TagEdit, "tags.edit", "Edit the category tag filter", &[Context::TagList], ["i"]; + TagInputNext, "tags.input.next", "Select the next tag while editing the filter", &[Context::TagFilter], ["down", "ctrl+j"]; + TagInputPrevious, "tags.input.previous", "Select the previous tag while editing the filter", &[Context::TagFilter], ["up", "ctrl+k"]; TagToggle, "tags.toggle", "Toggle the selected category tag", &[Context::TagList], ["space"]; TagNew, "tags.new", "Enter a new category tag name", &[Context::TagList], ["n"]; TagSave, "tags.save", "Save category tag changes", &[Context::TagList], ["enter"]; @@ -262,7 +268,7 @@ impl Key { #[derive(Clone, Debug, PartialEq, Eq)] pub struct Bindings { labels: Vec>, - contexts: [Vec<(Key, Action)>; 9], + contexts: [Vec<(Key, Action)>; ALL.len()], } impl Default for Bindings { @@ -378,7 +384,7 @@ impl Bindings { } fn build(keys: Vec>) -> io::Result { - let mut contexts: [Vec<(Key, Action)>; 9] = std::array::from_fn(|_| Vec::new()); + let mut contexts: [Vec<(Key, Action)>; ALL.len()] = std::array::from_fn(|_| Vec::new()); for definition in DEFINITIONS { for &context in definition.contexts { let entries = &mut contexts[context as usize]; @@ -483,6 +489,12 @@ impl Bindings { "CHANNEL TAGS", &[ (&[TagNext, TagPrevious], "Move between tags"), + (&[TagEdit], "Enter filter INSERT mode"), + (&[TagInputNext, TagInputPrevious], "Move while filtering"), + ( + &[InputSubmit, InputCancel], + "Leave tag filter without saving", + ), (&[TagToggle], "Toggle a tag"), (&[TagNew], "Enter a new tag name"), (&[TagSave], "Save tags"), @@ -565,7 +577,9 @@ impl Bindings { } if matches!( actions, - [DescriptionNext, DescriptionPrevious] | [SelectorInputNext, SelectorInputPrevious] + [DescriptionNext, DescriptionPrevious] + | [SelectorInputNext, SelectorInputPrevious] + | [TagInputNext, TagInputPrevious] ) && matches(actions[0], &["↓", "Ctrl+j"]) && matches(actions[1], &["↑", "Ctrl+k"]) { diff --git a/src/main.rs b/src/main.rs index 5788395..e696de7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -38,7 +38,9 @@ //! Deselecting removes the channel from that tag, preserving other creators and empty tags. //! Missing handle/ID metadata or a conflicting mapping prevents saving rather than guessing. //! 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. +//! i filters tags case-insensitively; arrows or Ctrl-J/K move through matches while typing. +//! Enter/Esc leaves filter editing without saving; hidden staged memberships remain unchanged. +//! n prompts for a new tag; Enter stages it checked, clears the filter, and selects it. Esc abandons the name. //! Normal-mode S in a category view edits every saved channel, even with no videos loaded. //! Shared tags start checked; Enter atomically replaces every target's tags with the checked set. //! Unchecked tags lose only target channels; other creators, registrations, pins, and empty categories remain. @@ -119,7 +121,7 @@ use youtube::{Job, PAGE_SIZE, Page, PlayerLaunch, Video}; #[command( version, about = "Browse YouTube and open selected videos in Terebi", - after_help = "Key names below describe default bindings. [keys] overrides named actions with a string or array; omitted actions keep defaults and [] disables an action. Live hints and help reflect overrides.\n--default-config prints complete default TOML to stdout and exits without loading config or starting a terminal.\nRequires 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:\n[settings]\npinned_categories = [\"Favorites\"]\n[categories]\nCreators = [\"@jawed\"]\nFavorites = [\"@jawed\"]\n[channels]\n\"@jawed\" = \"https://www.youtube.com/channel/UC4QobU6STFB0P71PMvOGN5A\"\n[settings].pinned_categories is an array of category names; pins referencing removed categories are ignored. Settings, channels, categories and keys tables can appear in any order. Add [settings] above pinned_categories in older configs; root-level pins are no longer accepted.\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 = "Key names below describe default bindings. [keys] overrides named actions with a string or array; omitted actions keep defaults and [] disables an action. Live hints and help reflect overrides.\n--default-config prints complete default TOML to stdout and exits without loading config or starting a terminal.\nRequires 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:\n[settings]\npinned_categories = [\"Favorites\"]\n[categories]\nCreators = [\"@jawed\"]\nFavorites = [\"@jawed\"]\n[channels]\n\"@jawed\" = \"https://www.youtube.com/channel/UC4QobU6STFB0P71PMvOGN5A\"\n[settings].pinned_categories is an array of category names; pins referencing removed categories are ignored. Settings, channels, categories and keys tables can appear in any order. Add [settings] above pinned_categories in older configs; root-level pins are no longer accepted.\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.\nTAG FILTER (s/S): i edits a case-insensitive substring filter; arrows or Ctrl-J/K move through matches while typing. Enter or Esc returns to NORMAL without saving or clearing the filter. Hidden staged memberships are retained; no matches makes navigation/toggling a no-op. Reopening clears the filter.\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, clears the filter, selects the new tag, 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. @@ -279,11 +281,70 @@ struct CategoryDialog { target: CategoryTarget, label: String, tags: BTreeMap, + mode: Mode, + query: String, + search_names: Vec, + matches: Vec, selection: ListState, name: Option, error: Option, } +impl CategoryDialog { + fn new(target: CategoryTarget, label: String, tags: BTreeMap) -> Self { + let mut dialog = Self { + target, + label, + search_names: tags.keys().map(|name| name.to_lowercase()).collect(), + matches: Vec::with_capacity(tags.len()), + tags, + mode: Mode::Normal, + query: String::new(), + selection: ListState::default(), + name: None, + error: None, + }; + dialog.refilter(); + dialog + } + + fn refilter(&mut self) { + filter_choices( + &self.query, + &self.search_names, + &mut self.matches, + &mut self.selection, + ); + self.error = None; + } +} + +fn filter_choices( + query: &str, + search_names: &[String], + matches: &mut Vec, + selection: &mut ListState, +) { + let selected = selection + .selected() + .and_then(|row| matches.get(row)) + .copied(); + let query = query.to_lowercase(); + matches.clear(); + matches.extend( + search_names + .iter() + .enumerate() + .filter(|(_, name)| name.contains(&query)) + .map(|(index, _)| index), + ); + selection.select( + selected + .and_then(|index| matches.binary_search(&index).ok()) + .or_else(|| (!matches.is_empty()).then_some(0)), + ); +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum BrowserKind { Categories, @@ -303,24 +364,11 @@ struct Browser { impl Browser { 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)), + filter_choices( + &self.query, + &self.search_names, + &mut self.matches, + &mut self.selection, ); self.error = None; } @@ -333,10 +381,10 @@ enum PreviewMode { } struct KeyHints { - footers: [(Context, String); 9], + footers: [(Context, String); 10], preview: [String; 2], browser: [String; 2], - tags: [String; 2], + tags: [String; 3], tags_empty: String, help: String, } @@ -412,13 +460,24 @@ impl KeyHints { ( Context::TagList, format!( - "TAGS · {} toggle · {} save · {} cancel · {} help", + "TAGS · {} filter · {} toggle · {} save · {} cancel · {} help", + key(Action::TagEdit), key(Action::TagToggle), key(Action::TagSave), key(Action::TagCancel), key(Action::Help) ), ), + ( + Context::TagFilter, + format!( + "TAG FILTER INSERT · {}/{} move · {}/{} normal", + key(Action::TagInputNext), + key(Action::TagInputPrevious), + key(Action::InputSubmit), + key(Action::InputCancel) + ), + ), ( Context::TagInput, format!( @@ -470,9 +529,10 @@ impl KeyHints { ], tags: [ format!( - "{}/{} move · {} toggle · {} save · {} new · {} cancel", + "{}/{} move · {} filter · {} toggle · {} save · {} new · {} cancel", key(Action::TagNext), key(Action::TagPrevious), + key(Action::TagEdit), key(Action::TagToggle), key(Action::TagSave), key(Action::TagNew), @@ -484,6 +544,14 @@ impl KeyHints { key(Action::InputCancel), key(Action::DeleteLine) ), + format!( + "{}/{} move · {}/{} back · {} clear", + key(Action::TagInputNext), + key(Action::TagInputPrevious), + key(Action::InputSubmit), + key(Action::InputCancel), + key(Action::DeleteLine) + ), ], tags_empty: format!("No tags. Press {} to create one.", key(Action::TagNew)), help: format!( @@ -1146,7 +1214,6 @@ impl App { return; } } - let mut selection = ListState::default(); let handle_url = format!("https://www.youtube.com/{handle}"); let tags = self .config @@ -1161,15 +1228,11 @@ impl App { ) }) .collect(); - selection.select((!self.config.categories.is_empty()).then_some(0)); - self.category_dialog = Some(CategoryDialog { - target: CategoryTarget::Channel { handle, channel }, + self.category_dialog = Some(CategoryDialog::new( + CategoryTarget::Channel { handle, channel }, label, tags, - selection, - name: None, - error: None, - }); + )); } fn open_bulk_category_picker(&mut self) { @@ -1202,17 +1265,22 @@ impl App { ) }) .collect(); - let mut selection = ListState::default(); - selection.select(self.config.categories.keys().position(|tag| tag == &name)); self.close_preview(); - self.category_dialog = Some(CategoryDialog { - label: format!(" {name} · {} channels ", channels.len()), - target: CategoryTarget::Category { name, channels }, + let mut dialog = CategoryDialog::new( + CategoryTarget::Category { + name: name.clone(), + channels, + }, + format!( + " {name} · {} channels ", + self.config.categories[&name].len() + ), tags, - selection, - name: None, - error: None, - }); + ); + dialog + .selection + .select(self.config.categories.keys().position(|tag| tag == &name)); + self.category_dialog = Some(dialog); } fn category_key(&mut self, key: KeyEvent, action: Option) { @@ -1235,6 +1303,10 @@ impl App { dialog.error = Some("That tag already exists.".into()); } else { dialog.tags.insert(name.clone(), true); + dialog.search_names = + dialog.tags.keys().map(|tag| tag.to_lowercase()).collect(); + dialog.query.clear(); + dialog.refilter(); dialog .selection .select(dialog.tags.keys().position(|tag| tag == &name)); @@ -1245,8 +1317,28 @@ impl App { _ => edit_input(name, key, action), } } else { - let count = dialog.tags.len(); + let action = if dialog.mode == Mode::Insert { + match action { + Some(Action::InputCancel | Action::InputSubmit) => { + dialog.mode = Mode::Normal; + self.category_dialog = Some(dialog); + return; + } + Some(Action::TagInputNext) => Some(Action::TagNext), + Some(Action::TagInputPrevious) => Some(Action::TagPrevious), + _ => { + edit_input(&mut dialog.query, key, action); + dialog.refilter(); + self.category_dialog = Some(dialog); + return; + } + } + } else { + action + }; + let count = dialog.matches.len(); match action { + Some(Action::TagEdit) => dialog.mode = Mode::Insert, Some(Action::TagCancel) => { self.switch_view(self.view_index); return; @@ -1259,7 +1351,8 @@ impl App { if let Some((_, checked)) = dialog .selection .selected() - .and_then(|index| dialog.tags.iter_mut().nth(index)) + .and_then(|row| dialog.matches.get(row)) + .and_then(|index| dialog.tags.iter_mut().nth(*index)) { *checked = !*checked; dialog.error = None; @@ -1429,6 +1522,8 @@ impl App { } else if let Some(dialog) = &self.category_dialog { if dialog.name.is_some() { Context::TagInput + } else if dialog.mode == Mode::Insert { + Context::TagFilter } else { Context::TagList } @@ -2008,8 +2103,8 @@ impl App { dialog .tags .len() - .saturating_add(if bulk { 7 } else { 5 }) - .clamp(7, if bulk { 18 } else { 16 }) as u16 + .saturating_add(if bulk { 10 } else { 8 }) + .clamp(10, if bulk { 21 } else { 19 }) as u16 }); let popup = Rect::new( area.x + (area.width - width) / 2, @@ -2028,7 +2123,8 @@ impl App { }) .title_bottom(dialog.label.as_str()) .border_style(Style::new().fg(Color::Cyan)); - let [body, warning, error, help] = Layout::vertical([ + let [input, body, warning, error, help] = Layout::vertical([ + Constraint::Length(if dialog.name.is_none() { 3 } else { 0 }), Constraint::Min(1), Constraint::Length(if bulk && dialog.name.is_none() { 2 } else { 0 }), Constraint::Length(if dialog.error.is_some() { 2 } else { 0 }), @@ -2036,6 +2132,31 @@ impl App { ]) .areas(block.inner(popup)); frame.render_widget(block, popup); + if dialog.name.is_none() { + let input_block = Block::bordered().title(if dialog.mode == Mode::Insert { + " Filter · INSERT " + } else { + " Filter · NORMAL " + }); + let text_area = input_block.inner(input); + let text = Line::raw(dialog.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 dialog.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 bulk && dialog.name.is_none() { frame.render_widget(Paragraph::new( "Saving replaces all memberships. Only tags shared by every channel start checked." @@ -2056,14 +2177,23 @@ impl App { } } else if dialog.tags.is_empty() { frame.render_widget(Paragraph::new(self.key_hints.tags_empty.as_str()), body); + } else if dialog.matches.is_empty() { + frame.render_widget(Paragraph::new("No matching tags.").dim(), body); } else { frame.render_stateful_widget( - List::new(dialog.tags.iter().map(|(name, checked)| { - Line::from(vec![ - (if *checked { "[x] " } else { "[ ] " }).into(), - name.as_str().into(), - ]) - })) + List::new( + dialog + .tags + .iter() + .enumerate() + .filter(|(index, _)| dialog.matches.binary_search(index).is_ok()) + .map(|(_, (name, checked))| { + Line::from(vec![ + (if *checked { "[x] " } else { "[ ] " }).into(), + name.as_str().into(), + ]) + }), + ) .highlight_symbol("> ") .highlight_style(Style::new().fg(Color::Black).bg(Color::Cyan)), body, @@ -2081,6 +2211,8 @@ impl App { frame.render_widget( Paragraph::new(if dialog.name.is_some() { self.key_hints.tags[1].as_str() + } else if dialog.mode == Mode::Insert { + self.key_hints.tags[2].as_str() } else { self.key_hints.tags[0].as_str() }) @@ -2437,15 +2569,15 @@ tags.cancel = "z" assert_eq!(app.views[app.view_index].next_start, 41); let history = app.view_history.clone(); app.category_dialog = Some(CategoryDialog { - target: CategoryTarget::Channel { - handle: "@Beta".into(), - channel: "beta".into(), - }, - label: "@Beta".into(), - tags: BTreeMap::new(), - selection: ListState::default(), name: None, - error: None, + ..CategoryDialog::new( + CategoryTarget::Channel { + handle: "@Beta".into(), + channel: "beta".into(), + }, + "@Beta".into(), + BTreeMap::new(), + ) }); press(&mut app, KeyCode::Esc, KeyModifiers::NONE); assert_eq!(app.view_history, history); @@ -2572,15 +2704,15 @@ tags.cancel = "z" 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, + ..CategoryDialog::new( + CategoryTarget::Channel { + handle: "@Alpha".into(), + channel: "alpha".into(), + }, + "@Alpha".into(), + BTreeMap::new(), + ) }); press(&mut app, KeyCode::Char('?')); assert!(app.help_popup.is_none()); @@ -3179,6 +3311,149 @@ tags.cancel = "z" .unwrap(); assert!(app.job.is_none()); } + #[test] + fn filtered_tagging_saves_visible_changes_without_losing_hidden_memberships() { + use ratatui::{Terminal, backend::TestBackend}; + + for bulk in [false, true] { + let path = std::env::temp_dir().join(format!( + "tubular-filtered-tags-{}-{bulk}.toml", + std::process::id() + )); + let original = "[channels]\n'@a' = 'UC4QobU6STFB0P71PMvOGN5A'\n'@b' = 'UCaYhcUwRBNscFNUKTjgPFiA'\n[categories]\nAlpha = ['@a', '@b']\nGamma = []\nZebra = ['@a', '@b']\n"; + std::fs::write(&path, original).unwrap(); + let mut app = App::new( + Options::parse_from(["tubular"]), + path.clone(), + config::load(&path).unwrap(), + ); + app.views[0].videos = youtube::search_results( + r#"{"entries":[{"id":"jNQXAC9IVRw","title":"Creator video","channel":"Creator","channel_id":"UC4QobU6STFB0P71PMvOGN5A","uploader_id":"@a"}]}"# + ).unwrap().videos; + app.views[0].selection.select(Some(0)); + if bulk { + app.view_index = app + .views + .iter() + .position(|view| view.name == "Alpha") + .unwrap(); + } + app.views[app.view_index].loaded = true; + let press = |app: &mut App, code, modifiers| { + app.key(KeyEvent::new(code, modifiers)); + }; + press( + &mut app, + KeyCode::Char(if bulk { 'S' } else { 's' }), + KeyModifiers::NONE, + ); + press(&mut app, KeyCode::Char('i'), KeyModifiers::NONE); + for c in "missing".chars() { + press(&mut app, KeyCode::Char(c), KeyModifiers::NONE); + } + let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap(); + terminal + .draw(|frame| app.draw(frame, Duration::ZERO)) + .unwrap(); + let text: String = terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect(); + assert!(text.contains("No matching tags.")); + press(&mut app, KeyCode::Esc, KeyModifiers::NONE); + press(&mut app, KeyCode::Char(' '), KeyModifiers::NONE); + press(&mut app, KeyCode::Char('i'), KeyModifiers::NONE); + press(&mut app, KeyCode::Char('u'), KeyModifiers::CONTROL); + for c in "GA".chars() { + press(&mut app, KeyCode::Char(c), KeyModifiers::SHIFT); + } + press(&mut app, KeyCode::Enter, KeyModifiers::NONE); + assert!(app.category_dialog.is_some(), "filter Enter must not save"); + assert_eq!(std::fs::read_to_string(&path).unwrap(), original); + press(&mut app, KeyCode::Char(' '), KeyModifiers::NONE); + terminal + .draw(|frame| app.draw(frame, Duration::ZERO)) + .unwrap(); + let text: String = terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect(); + assert!(text.contains("[x] Gamma")); + assert!(!text.contains("[x] Alpha") && !text.contains("[x] Zebra")); + press(&mut app, KeyCode::Enter, KeyModifiers::NONE); + assert!(app.category_dialog.is_none()); + let saved = config::load(&path).unwrap(); + let a = config::normalize_channel("UC4QobU6STFB0P71PMvOGN5A").unwrap(); + let b = config::normalize_channel("UCaYhcUwRBNscFNUKTjgPFiA").unwrap(); + assert_eq!(saved.categories["Alpha"], [a.clone(), b.clone()]); + assert_eq!(saved.categories["Zebra"], [a.clone(), b.clone()]); + assert_eq!( + saved.categories["Gamma"], + if bulk { vec![a, b] } else { vec![a] } + ); + std::fs::remove_file(path).unwrap(); + } + } + + #[test] + fn tag_filter_preserves_selection_and_stages_new_tags_outside_the_filter() { + let mut app = app(&["tubular"]); + app.category_dialog = Some(CategoryDialog::new( + CategoryTarget::Channel { + handle: "@a".into(), + channel: String::new(), + }, + "Creator".into(), + [ + ("Alpha".into(), false), + ("Gamma".into(), true), + ("Zebra".into(), false), + ] + .into(), + )); + let press = |app: &mut App, code, modifiers| { + app.key(KeyEvent::new(code, modifiers)); + }; + press(&mut app, KeyCode::Char('j'), KeyModifiers::NONE); + press(&mut app, KeyCode::Char('i'), KeyModifiers::NONE); + press(&mut app, KeyCode::Char('a'), KeyModifiers::NONE); + press(&mut app, KeyCode::Char('j'), KeyModifiers::CONTROL); + press(&mut app, KeyCode::Esc, KeyModifiers::NONE); + press(&mut app, KeyCode::Char(' '), KeyModifiers::NONE); + assert!(app.category_dialog.as_ref().unwrap().tags["Zebra"]); + assert!(!app.category_dialog.as_ref().unwrap().tags["Alpha"]); + press(&mut app, KeyCode::Char('i'), KeyModifiers::NONE); + press(&mut app, KeyCode::Char('u'), KeyModifiers::CONTROL); + for c in "gamma".chars() { + press(&mut app, KeyCode::Char(c), KeyModifiers::NONE); + } + press(&mut app, KeyCode::Esc, KeyModifiers::NONE); + press(&mut app, KeyCode::Char('n'), KeyModifiers::NONE); + for c in "New".chars() { + press(&mut app, KeyCode::Char(c), KeyModifiers::NONE); + } + press(&mut app, KeyCode::Enter, KeyModifiers::NONE); + let dialog = app.category_dialog.as_ref().unwrap(); + assert!(dialog.tags["New"]); + assert!(dialog.query.is_empty(), "new tag must be visible"); + press(&mut app, KeyCode::Char(' '), KeyModifiers::NONE); + assert!( + !app.category_dialog.as_ref().unwrap().tags["New"], + "new tag is selected" + ); + press(&mut app, KeyCode::Esc, KeyModifiers::NONE); + assert!(app.category_dialog.is_none()); + assert!( + app.config.categories.is_empty(), + "cancel discards staged changes" + ); + } #[test] fn bulk_picker_uses_all_saved_channels_and_commits_or_cancels_the_whole_group() { @@ -3851,15 +4126,15 @@ tags.cancel = "z" assert!(!app.can_prefetch()); app.preview = None; app.category_dialog = Some(CategoryDialog { - target: CategoryTarget::Channel { - channel: String::new(), - handle: String::new(), - }, - label: String::new(), - tags: BTreeMap::new(), - selection: ListState::default(), name: None, - error: None, + ..CategoryDialog::new( + CategoryTarget::Channel { + channel: String::new(), + handle: String::new(), + }, + String::new(), + BTreeMap::new(), + ) }); assert!(!app.can_prefetch()); app.category_dialog = None; @@ -3914,15 +4189,15 @@ tags.cancel = "z" assert_eq!(terminal.get_cursor_position().unwrap(), (x, 2).into()); } app.category_dialog = Some(CategoryDialog { - target: CategoryTarget::Channel { - channel: String::new(), - handle: String::new(), - }, - label: String::new(), - tags: BTreeMap::new(), - selection: ListState::default(), name: Some(String::new()), - error: None, + ..CategoryDialog::new( + CategoryTarget::Channel { + channel: String::new(), + handle: String::new(), + }, + String::new(), + BTreeMap::new(), + ) }); for (text, x) in [("", 3), ("日本語", 9), ("abcdefghijklmnopqrstuvwxyz", 20)] { app.category_dialog.as_mut().unwrap().name = Some(text.into()); @@ -3976,16 +4251,16 @@ tags.cancel = "z" if tag_input { app.mode = Mode::Normal; app.category_dialog = Some(CategoryDialog { - target: CategoryTarget::Channel { - channel: "https://www.youtube.com/channel/UC4QobU6STFB0P71PMvOGN5A" - .into(), - handle: "@jawed".into(), - }, - label: "jawed".into(), - tags: BTreeMap::new(), - selection: ListState::default(), name: Some(input.into()), - error: None, + ..CategoryDialog::new( + CategoryTarget::Channel { + channel: "https://www.youtube.com/channel/UC4QobU6STFB0P71PMvOGN5A" + .into(), + handle: "@jawed".into(), + }, + "jawed".into(), + BTreeMap::new(), + ) }); } else { app.key(KeyEvent::new(KeyCode::Char('i'), KeyModifiers::NONE));