From b53b57ee17851df1600fbf1ffd59aa1caf517e9c Mon Sep 17 00:00:00 2001 From: hl-valdemar Date: Sun, 11 Oct 2026 23:30:11 +0200 Subject: [PATCH] feat: browse and save combined category feeds --- README.md | 21 +- src/config.rs | 217 ++++++++++ src/keys.rs | 30 +- src/main.rs | 1047 +++++++++++++++++++++++++++++++++++++++++-------- 4 files changed, 1143 insertions(+), 172 deletions(-) diff --git a/README.md b/README.md index e7a6c5d..d2bb95e 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ These are the default bindings. Overrides in `[keys]` replace an action's bindin | `s` | Edit the selected channel's tags | | `S` | Edit tags for all saved channels in the current category | | `R` (Shift-R) | Rename the current category, including category-scoped collection views | +| `P` (Shift-P) | Save the current combined-category feed as a new category | | `w` | Save the selected video to watch later (also works in previews) | | `W` | Choose combined or category watch later from any video view or preview | | `Alt-w` | Open the current category's watch later | @@ -112,9 +113,21 @@ In terminals supporting bracketed paste, clipboard text is inserted in one opera ### Category browser (`c`) -- **Normal:** `j` / `k` or arrow keys navigate; `i` enters filter mode; Enter browses the selected category; `p` toggles its persisted pin; `R` renames it; Esc closes. -- **Insert:** type a case-insensitive substring to filter; arrow keys or Ctrl-J / Ctrl-K navigate matches; Enter browses; Esc returns to normal mode without clearing the filter. -- Reopening the browser clears its filter. No matches makes browsing, pinning, and renaming a no-op. +- **Normal:** `j` / `k` or arrow keys navigate; Space checks/unchecks a category; `i` enters filter mode; Enter browses checked categories, or the hovered category if none are checked; `p` toggles its persisted pin; `R` renames it; Esc closes. +- **Insert:** type a case-insensitive substring to filter; arrow keys or Ctrl-J / Ctrl-K navigate matches; Enter browses the chosen categories; Esc returns to normal mode without clearing the filter. Space is ordinary input here. +- Checkboxes select categories for browsing; the dimmed `p` suffix marks pins independently. Hidden checks survive filtering. Enter still browses checked categories when there are no visible matches; without checks, an empty result makes browsing a no-op. Pinning, renaming, and toggling require a visible selected row. + +### Combined category feeds + +Check multiple categories in `c`, then press Enter to open their combined feed. One checked category opens its ordinary view; no checks retain the usual single-category shortcut. Esc discards the selector's staged choices. Reopening `c` from a combined feed prechecks its member categories. + +The combined feed uses the shared temporary tab, replacing the prior unpinned category/channel/collection view. Channels and video IDs are deduplicated, and videos use the same newest-first ordering and infinite scrolling as other feeds. Back/forward navigation restores cached rows, selection, and pagination. + +Press `P` to save the viewed union of channels under a new category name. Enter commits; Esc cancels; duplicate or invalid names leave the prompt open without overwriting anything. The new flat category becomes active without automatic pinning or re-fetching matching cached pages. Its memberships are an independent copy, not links to the original categories. + +Renaming a member category updates the combined view and its history. Membership changes recompute the channel union, preserving cached rows when the resolved union is unchanged; deleting a member invalidates the combined view rather than silently widening it. Explicit refresh still reloads the active view from page one. + +Combined feeds are not individual categories: `S`, `R`, and `Alt-w` / `Alt-v` require a single category. Save with `P` first to use those actions. Configure multi-selection with `selector.toggle` and saving with `category.save`; name entry uses the shared `input.*` controls. ### Saved channels (`u`) @@ -178,7 +191,7 @@ Category entries accept `@handles`, HTTPS YouTube channel URLs, or canonical `UC Video tables color channel names **cyan** when the creator belongs to at least one category. Untagged registrations keep the default text color; selected rows retain their black-on-cyan highlight. Membership is matched by channel ID or handle, not the displayed name, and updates after saving tags or reloading config. - **Search** and **Feed** are permanent tabs. Feed combines all `[channels]` registrations, including untagged channels, plus channels entered directly in categories, without duplicates. -- Browsing an unpinned category, channel, watch-later list, or saved-video list uses one shared temporary tab; choosing another replaces it. Pinned categories keep their own tabs, marked with a dimmed `p`. +- Browsing an unpinned category, combined-category feed, channel, watch-later list, or saved-video list uses one shared temporary tab; choosing another replaces it. Pinned categories keep their own tabs, marked with a dimmed `p`. - Removing a channel from a category does **not** unsubscribe it from Feed. To unsubscribe, remove its `[channels]` mappings and category references, then press `r`. - Temporary tabs do not survive restarting; saved categories and pins do. Hidden views retain loaded rows, selection, and pagination during the session. diff --git a/src/config.rs b/src/config.rs index 4d12248..e64fedd 100644 --- a/src/config.rs +++ b/src/config.rs @@ -384,6 +384,53 @@ pub fn set_category_pinned(path: &Path, name: &str, pinned: bool) -> io::Result< }) } +pub fn create_category(path: &Path, name: &str, channels: &[String]) -> io::Result { + let name = category_name(name)?; + let (original, mut document) = read_document(path)?; + let mappings = parse_channels(&document)?; + let mut categories = parse_categories(&document, &mappings)?; + let pinned_categories = parse_pins(&document)?; + let keys = keys::Bindings::from_toml(document.get("keys"))?; + if categories.contains_key(name) { + return Err(invalid(format!("Category already exists: {name:?}"))); + } + + let mut labels = BTreeMap::new(); + // As in saved_channels, use the first mapped handle for each identity. + for (handle, identity) in &mappings { + labels.entry(identity.as_str()).or_insert(handle.as_str()); + } + let identities: BTreeSet<_> = channels + .iter() + .map(|channel| resolve_channel(channel, &mappings)) + .collect::>()?; + let mut entries = Array::new(); + for identity in &identities { + let readable = labels.get(identity.as_str()).copied().unwrap_or_else(|| { + identity + .strip_prefix("https://www.youtube.com/") + .filter(|address| address.starts_with('@')) + .unwrap_or(identity) + }); + entries.push(readable); + } + if !document.contains_key("categories") { + document.insert("categories", Item::Table(Table::new())); + } + document["categories"] + .as_table_like_mut() + .expect("categories were validated") + .insert(name, value(entries)); + categories.insert(name.to_owned(), identities.into_iter().collect()); + save(path, original.as_deref(), document.to_string().as_bytes())?; + Ok(Config { + channels: mappings, + categories, + pinned_categories, + keys, + }) +} + pub fn rename_category(path: &Path, old: &str, new: &str) -> io::Result { let old = category_name(old)?; let new = category_name(new)?; @@ -873,6 +920,9 @@ mod tests { let pin_error = set_category_pinned(&path, "B", true).unwrap_err(); assert_eq!(pin_error.kind(), io::ErrorKind::InvalidData); assert_eq!(fs::read(&path).unwrap(), original.as_bytes()); + let create_error = create_category(&path, "New", &expected).unwrap_err(); + assert_eq!(create_error.kind(), io::ErrorKind::InvalidData); + assert_eq!(fs::read(&path).unwrap(), original.as_bytes()); } } @@ -989,6 +1039,173 @@ mod tests { } } + #[test] + fn category_creation_deduplicates_aliases_and_preserves_original_config() { + let directory = TestDirectory::new(); + let path = directory.0.join("config.toml"); + let id = "UC4QobU6STFB0P71PMvOGN5A"; + let url = format!("https://www.youtube.com/channel/{id}"); + let original = "# manual preferences\n[other]\nvalue = 42\n[settings]\npinned_categories = [' Source '] # favorite\nplayer = 'mpv'\n[keys.app]\nquit = ['q'] # key note\n[channels]\n'@zeta' = 'UC4QobU6STFB0P71PMvOGN5A' # mapping note\n'@alpha' = 'UC4QobU6STFB0P71PMvOGN5A'\n[categories]\n# category note\n' Source ' = [\n '@zeta', # entry note\n '@manual',\n '@manual',\n] # array note\nEmpty = []\n"; + fs::write(&path, original).unwrap(); + let before = load(&path).unwrap(); + let created = create_category( + &path, + " Combined ", + &[ + id.to_owned(), + url.clone(), + "@zeta".to_owned(), + "https://youtube.com/@alpha".to_owned(), + "@manual".to_owned(), + "https://www.youtube.com/@manual".to_owned(), + "UCabcdefghijklmnopqrstuv".to_owned(), + ], + ) + .unwrap(); + assert_eq!( + created.categories["Combined"], + [ + "https://www.youtube.com/@manual".to_owned(), + url, + "https://www.youtube.com/channel/UCabcdefghijklmnopqrstuv".to_owned(), + ] + ); + assert_eq!(created.channels, before.channels); + assert_eq!(created.categories["Source"], before.categories["Source"]); + assert_eq!(created.categories["Empty"], before.categories["Empty"]); + assert_eq!(created.pinned_categories, before.pinned_categories); + let contents = fs::read_to_string(&path).unwrap(); + let mut document = contents.parse::().unwrap(); + assert_eq!( + document["categories"]["Combined"] + .as_array() + .unwrap() + .iter() + .map(|entry| entry.as_str().unwrap()) + .collect::>(), + [ + "@manual", + "@alpha", + "https://www.youtube.com/channel/UCabcdefghijklmnopqrstuv", + ] + ); + document["categories"] + .as_table_like_mut() + .unwrap() + .remove("Combined"); + assert_eq!(document.to_string(), original); + assert_eq!(load(&path).unwrap().categories, created.categories); + assert_eq!(fs::read_dir(&directory.0).unwrap().count(), 1); + } + + #[test] + fn category_creation_uses_latest_mappings_and_supports_inline_unicode_and_empty() { + let directory = TestDirectory::new(); + let path = directory.0.join("config.toml"); + let original = "categories = { Source = ['@first', '@first'], Empty = [] } # categories note\nsettings = { pinned_categories = ['Source'], custom = 42 }\nchannels = { '@mapped' = 'UC4QobU6STFB0P71PMvOGN5A' }\n"; + fs::write(&path, original).unwrap(); + let opened = load(&path).unwrap(); + let latest = original.replace("UC4QobU6STFB0P71PMvOGN5A", "UCabcdefghijklmnopqrstuv"); + fs::write(&path, &latest).unwrap(); + let created = create_category( + &path, + " 日本語 🎵 ", + &["@mapped".to_owned(), "UCabcdefghijklmnopqrstuv".to_owned()], + ) + .unwrap(); + assert_ne!(created.channels, opened.channels); + assert_eq!( + created.categories["日本語 🎵"], + ["https://www.youtube.com/channel/UCabcdefghijklmnopqrstuv"] + ); + assert_eq!(created.pinned_categories, ["Source"]); + let contents = fs::read_to_string(&path).unwrap(); + let document = contents.parse::().unwrap(); + let before_document = latest.parse::().unwrap(); + assert!(document["categories"].is_inline_table()); + assert_eq!( + document["categories"]["日本語 🎵"][0].as_str(), + Some("@mapped") + ); + for section in ["settings", "channels"] { + assert_eq!( + document[section].to_string(), + before_document[section].to_string() + ); + } + for name in ["Source", "Empty"] { + assert_eq!( + document["categories"][name].to_string(), + before_document["categories"][name].to_string() + ); + } + assert!(contents.contains("# categories note")); + let empty = create_category(&path, "New empty", &[]).unwrap(); + assert!(empty.categories["New empty"].is_empty()); + assert_eq!(empty.pinned_categories, ["Source"]); + let missing = directory.0.join("nested/config.toml"); + let empty = create_category(&missing, "Empty", &[]).unwrap(); + assert!(empty.categories["Empty"].is_empty()); + assert!(empty.channels.is_empty()); + assert!(empty.pinned_categories.is_empty()); + assert_eq!(load(&missing).unwrap().categories, empty.categories); + } + + #[test] + fn category_creation_rejects_invalid_names_channels_and_configs_without_writes() { + let directory = TestDirectory::new(); + let path = directory.0.join("config.toml"); + let original = "[categories]\n' Source ' = ['@manual']\nEmpty = []\n"; + fs::write(&path, original).unwrap(); + for name in [ + "", + " ", + "Bad\nName", + "Bad\u{7f}Name", + "Source", + " Source ", + "Empty", + ] { + assert!(create_category(&path, name, &[]).is_err(), "{name:?}"); + assert_eq!(fs::read(&path).unwrap(), original.as_bytes()); + } + // Even an identical membership snapshot must not overwrite a category. + assert!(create_category(&path, "Source", &["@manual".to_owned()]).is_err()); + assert_eq!(fs::read(&path).unwrap(), original.as_bytes()); + for channel in [ + "", + "bad", + "@bad handle", + "@manual\n", + "https://example.com/@manual", + "https://www.youtube.com/@manual/videos", + ] { + assert!( + create_category(&path, "New", &["@valid".to_owned(), channel.to_owned()]).is_err(), + "{channel:?}" + ); + assert_eq!(fs::read(&path).unwrap(), original.as_bytes()); + } + for malformed in [ + "[categories\n", + "categories = 3\n", + "[categories]\nSource = [7]\n", + "[categories]\nSource = []\n' Source ' = []\n", + "[channels]\n'@mapped' = '@other'\n", + "[settings]\npinned_categories = [7]\n", + "[keys.app]\nunknown = ['q']\n", + ] { + fs::write(&path, malformed).unwrap(); + assert!(create_category(&path, "New", &[]).is_err()); + assert_eq!(fs::read(&path).unwrap(), malformed.as_bytes()); + } + let missing = directory.0.join("missing/config.toml"); + assert!(create_category(&missing, "Bad\nName", &[]).is_err()); + assert!(create_category(&missing, "New", &["@bad handle".to_owned()]).is_err()); + assert!(!missing.parent().unwrap().exists()); + assert_eq!(fs::read_dir(&directory.0).unwrap().count(), 1); + } + #[test] fn category_rename_preserves_memberships_pins_comments_and_section_order() { let directory = TestDirectory::new(); diff --git a/src/keys.rs b/src/keys.rs index b00049b..63095ee 100644 --- a/src/keys.rs +++ b/src/keys.rs @@ -22,7 +22,7 @@ pub enum Context { TagList, TagFilter, TagInput, - RenameInput, + CategoryNameInput, Help, } @@ -39,7 +39,7 @@ const ALL: &[Context] = &[ Context::TagList, Context::TagFilter, Context::TagInput, - Context::RenameInput, + Context::CategoryNameInput, Context::Help, ]; const VIEW: &[Context] = &[ @@ -60,7 +60,7 @@ const TEXT: &[Context] = &[ Context::SelectorInput, Context::TagFilter, Context::TagInput, - Context::RenameInput, + Context::CategoryNameInput, ]; const NON_TEXT: &[Context] = &[ Context::Normal, @@ -105,7 +105,7 @@ actions! { Interrupt, "app.interrupt", "Exit immediately", ALL, ["ctrl+c"]; Quit, "app.quit", "Quit the application", &[Context::Normal, Context::Info, Context::Description, Context::CollectionNormal, Context::CollectionInfo, Context::CollectionDescription, Context::Help], ["q"]; Help, "help.toggle", "Open or close keyboard help", NON_TEXT, ["?"]; - InputSubmit, "input.submit", "Submit search, browse selector, leave tag filter, stage new tag or rename category", TEXT, ["enter"]; + InputSubmit, "input.submit", "Submit search, browse selector, leave tag filter, stage new tag or save category name", 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"]; @@ -130,6 +130,7 @@ actions! { ChannelTags, "channel.tags", "Edit the selected channel's category tags", VIEW, ["s"]; CategoryTags, "category.tags", "Edit category tags for all channels in this category", VIEW, ["S"]; CategoryRename, "category.rename", "Rename the current or selected category", &[Context::Normal, Context::CollectionNormal, Context::SelectorNormal, Context::TagList], ["R"]; + CategorySave, "category.save", "Save the combined category view as a new category", VIEW, ["P"]; WatchLaterSave, "video.watch_later.save", "Save the selected video to watch later", VIEW, ["w"]; WatchLaterBrowse, "view.watch_later.browse", "Choose watch later across all categories or one category", VIEW, ["W"]; WatchLaterBrowseCategory, "view.watch_later.category", "Browse the current category's watch later", VIEW, ["alt+w"]; @@ -146,6 +147,7 @@ actions! { SelectorEdit, "selector.edit", "Edit the category, channel, or collection filter", &[Context::SelectorNormal], ["i"]; SelectorOpen, "selector.open", "Open the selected category, channel, or collection", &[Context::SelectorNormal], ["enter"]; SelectorPin, "selector.pin", "Toggle category pinning (category picker only)", &[Context::SelectorNormal], ["p"]; + SelectorToggle, "selector.toggle", "Check a category for combined browsing (category picker only)", &[Context::SelectorNormal], ["space"]; SelectorClose, "selector.close", "Close the category, channel, or collection 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"]; @@ -486,6 +488,10 @@ impl Bindings { &[CategoryRename], "Rename the current category (including scoped collections)", ), + ( + &[CategorySave], + "Save a combined category view as a new category", + ), (&[ViewTabNext, ViewTabPrevious], "Cycle visible tabs"), (&[ViewPrevious], "Back (preview close takes priority)"), (&[ViewNext], "Forward after going back"), @@ -571,7 +577,14 @@ impl Bindings { &[SelectorInputNext, SelectorInputPrevious], "Move while filtering", ), - (&[SelectorOpen, InputSubmit], "Browse the selected match"), + ( + &[SelectorOpen, InputSubmit], + "Browse checked categories, or the selected match", + ), + ( + &[SelectorToggle], + "Check categories for a combined feed (NORMAL only)", + ), ( &[SelectorPin], "Pin / unpin a category (category picker only)", @@ -610,9 +623,12 @@ impl Bindings { &[ ( &[InputSubmit], - "Submit search / stage tag / commit category rename", + "Submit search / stage tag / save category name", + ), + ( + &[InputCancel], + "Leave INSERT / abandon tag or category name", ), - (&[InputCancel], "Leave INSERT / abandon tag name or rename"), (&[DeleteCharacter], "Delete one character"), (&[DeleteWord], "Delete previous word"), (&[DeleteLine], "Clear the line"), diff --git a/src/main.rs b/src/main.rs index cb6ed4e..a030d04 100644 --- a/src/main.rs +++ b/src/main.rs @@ -50,11 +50,14 @@ //! n stages a new shared tag; Esc cancels the whole edit. Changed source membership requires reopening. //! Clearing all tags is refused for category-only channels, avoiding accidental unsubscription. //! Search and Feed are permanent tabs. Normal-mode c opens the saved-category browser. -//! The category browser starts NORMAL: j/k or arrows move, i filters, Enter browses, p pins, Esc closes. +//! The category browser starts NORMAL: j/k or arrows move, i filters, Space checks, Enter browses, p pins. //! 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. +//! Checks survive filtering: Enter browses checked categories, or the hovered match when none are checked. //! Pinned categories stay visible; browsing another category replaces the single temporary tab. +//! Multiple checked categories form a newest-first deduplicated temporary feed; c rechecks its members. +//! Category rows show checkboxes independently of the dim p pin suffix; Esc cancels staged choices. +//! P saves a combined feed's current channel union as a new flat, unpinned category; Esc cancels the name. //! Pinned category tab titles use a dimmed `p` suffix; Search, Feed, and temporary tabs do not. //! The suffix stays dimmed when selected and counts toward whole-label wrapping without changing category names. //! Browsing a pinned category focuses its existing tab and removes the temporary tab. @@ -69,7 +72,7 @@ //! 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. -//! Channels and unpinned categories share one temporary tab; hidden views retain caches and back history. +//! Channels, combined feeds and unpinned categories share one temporary tab; hidden views retain history. //! Channel views use the same pagination but extract only their stored channel identity; S stays category-only. //! Config changes preserve unsaved browsing, relabel saved identities, and drop explicitly removed subscriptions. //! r reloads config and refreshes the current view. @@ -139,7 +142,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 plus --progress-file for an independent private reporting stream 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, new tag, and category rename): 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; R renames the current explicit category; q quits.\nWATCH LATER: w saves the selected video once (also in previews); W opens a searchable watch-later collection selector; Alt-w opens the current explicit category's watch-later list. Both work in previews. Moving between watch-later scopes preserves the watched filter. Lists follow current channel category memberships and use persisted metadata offline. Only in watch-later views and their previews, x removes the selected video and X (Shift-X) prompts to remove the current filtered/category subset. Configure view.collection.remove.selected and view.collection.remove.bulk. In watch-later views f cycles All/Unwatched/Watched; y confirms bulk, n/Esc cancels, and Enter never confirms. The other collection and watched status are unchanged. Watch-later titles are magenta; a checkmark marks watched videos in every table. Eligible acknowledged progress reaching 95% of a known duration marks watched; seeking near the end counts, launcher exit does not. Separate watch-later.toml and watch-state.toml sit beside config.toml. Private playback-sessions survive Tubular exit for next-launch recovery.\nSAVED VIDEOS: v saves the selected video once (also in previews); V opens a searchable saved-video collection selector; Alt-v opens the current explicit category's saved-video list, including from a category watch-later list. Both work in previews. Alt-w/Alt-v require a category view or category-scoped collection; Search, Feed, channel views and all-categories collections do not infer a category. Lists derive from current channel memberships and use offline metadata in saved-videos.toml beside config.toml. Only in saved-video views and their previews, x removes the selected video and X prompts to remove the current category/list subset, without changing watch later or watched state. Search, Feed, category and channel views and their previews never remove collection membership. Saved titles are green, taking precedence over watch-later magenta. Saved lists have no watched filter; bulk removal snapshots the current list. Both collections share the temporary tab and cached back/forward history.\nCOLLECTION SELECTORS (W / V): All categories (combined) is the first entry, followed by configured categories. Start in NORMAL; j/k or arrows move; i enters INSERT to filter by a case-insensitive substring. Arrows or Ctrl-J/K move while typing; Enter opens the selected scope, or does nothing with no matches. Esc returns to NORMAL then closes without navigating; reopening clears the filter. Collection selectors do not change category pins.\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; R renames the hovered category; 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; R renames the selected tag; Esc cancels staged memberships without undoing committed renames.\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.\nCATEGORY RENAME (R / Shift-R): rename the current category or category-scoped collection, the hovered category in category/collection selectors, or a selected tag in single/bulk tagging. Combined and channel rows cannot be renamed. The prefilled floating input uses shared editing controls; Enter commits, Esc cancels. Existing category identity is saved immediately, with memberships, pins, comments, cached selection/pages/watch filters and navigation history preserved. Tag membership changes remain staged until the main tag-list Enter; an unstored new tag rename also stays staged. Invalid, duplicate, or externally changed source categories keep the prompt open without writes; close dialogs and reload config with r before retrying external changes. Configure category.rename; R remains literal in filter/search inputs.\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\"" + 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 plus --progress-file for an independent private reporting stream 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, new tag, and category name prompts): 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; R renames the current explicit category; P saves the active combined category feed as a new category; q quits.\nWATCH LATER: w saves the selected video once (also in previews); W opens a searchable watch-later collection selector; Alt-w opens the current explicit category's watch-later list. Both work in previews. Moving between watch-later scopes preserves the watched filter. Lists follow current channel category memberships and use persisted metadata offline. Only in watch-later views and their previews, x removes the selected video and X (Shift-X) prompts to remove the current filtered/category subset. Configure view.collection.remove.selected and view.collection.remove.bulk. In watch-later views f cycles All/Unwatched/Watched; y confirms bulk, n/Esc cancels, and Enter never confirms. The other collection and watched status are unchanged. Watch-later titles are magenta; a checkmark marks watched videos in every table. Eligible acknowledged progress reaching 95% of a known duration marks watched; seeking near the end counts, launcher exit does not. Separate watch-later.toml and watch-state.toml sit beside config.toml. Private playback-sessions survive Tubular exit for next-launch recovery.\nSAVED VIDEOS: v saves the selected video once (also in previews); V opens a searchable saved-video collection selector; Alt-v opens the current explicit category's saved-video list, including from a category watch-later list. Both work in previews. Alt-w/Alt-v require a category view or category-scoped collection; Search, Feed, combined category feeds, channel views and all-categories collections do not infer a category. Lists derive from current channel memberships and use offline metadata in saved-videos.toml beside config.toml. Only in saved-video views and their previews, x removes the selected video and X prompts to remove the current category/list subset, without changing watch later or watched state. Search, Feed, category and channel views and their previews never remove collection membership. Saved titles are green, taking precedence over watch-later magenta. Saved lists have no watched filter; bulk removal snapshots the current list. Both collections share the temporary tab and cached back/forward history.\nCOLLECTION SELECTORS (W / V): All categories (combined) is the first entry, followed by configured categories. Start in NORMAL; j/k or arrows move; i enters INSERT to filter by a case-insensitive substring. Arrows or Ctrl-J/K move while typing; Enter opens the selected scope, or does nothing with no matches. Esc returns to NORMAL then closes without navigating; reopening clears the filter. Collection selectors do not change category pins.\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; Space checks categories; Enter browses checked categories, or the hovered match if none are checked; p immediately saves pin/unpin; R renames the hovered category; Esc cancels checks and closes. Checkboxes are separate from the dim p pin marker. One checked category opens its ordinary view; multiple checked categories open their combined newest-first, deduplicated feed. Configure selector.toggle to change Space. 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 checked categories, or the selected match if none are checked; Esc returns to NORMAL with the filter retained. Space remains text while filtering. Hidden checked categories stay checked. With no checks and no matches, Enter/p do nothing. Reopening clears the filter and prechecks the active combined feed members.\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, combined category feeds 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, combined category and channel views retain loaded rows, selection, and pagination for this session. Combined feeds retain their cache when member assignments change but the resolved channel union stays equal; deleting a member invalidates the combined view rather than widening it. 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; R renames the selected tag; Esc cancels staged memberships without undoing committed renames.\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.\nSAVE COMBINED CATEGORY (P / Shift-P): only an active combined category feed can be saved, including from its previews. The floating name prompt uses shared input editing controls; Enter saves a new flat category containing the currently viewed channel union, using mapped handles where available; Esc cancels without writes. Invalid or duplicate names keep the prompt open and current view unchanged. Saving copies memberships, not dynamic source-category definitions; later source-category edits do not affect the saved category. The new category becomes the active unpinned temporary tab, preserving matching cached rows, selection, pending pages and pagination without refetching. Source categories and existing pins stay unchanged. Configure category.save; P remains text in inputs.\nCATEGORY RENAME (R / Shift-R): rename the current category or category-scoped collection, the hovered category in category/collection selectors, or a selected tag in single/bulk tagging. Combined and channel rows cannot be renamed. The prefilled floating input uses shared editing controls; Enter commits, Esc cancels. Existing category identity is saved immediately, with memberships, pins, comments, cached selection/pages/watch filters and navigation history preserved. Tag membership changes remain staged until the main tag-list Enter; an unstored new tag rename also stays staged. Invalid, duplicate, or externally changed source categories keep the prompt open without writes; close dialogs and reload config with r before retrying external changes. Configure category.rename; R remains literal in filter/search inputs.\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; must support --new-instance, --url, and --progress-file. @@ -177,17 +180,24 @@ enum ViewSource { Search, Feed, Category(String), + CategoryGroup(Vec), Channel(String), WatchLater(Option), SavedVideos(Option), } impl ViewSource { - fn channels<'a>(&'a self, config: &'a config::Config, feed: &'a [String]) -> &'a [String] { + fn channels<'a>( + &'a self, + config: &'a config::Config, + feed: &'a [String], + group: &'a [String], + ) -> &'a [String] { match self { Self::Search | Self::WatchLater(_) | Self::SavedVideos(_) => &[], Self::Feed => feed, Self::Category(name) => &config.categories[name], + Self::CategoryGroup(_) => group, Self::Channel(identity) => std::slice::from_ref(identity), } } @@ -209,11 +219,35 @@ impl ViewSource { *name = new.to_owned(); true } + Self::CategoryGroup(names) if names.iter().any(|name| name == old) => { + for name in names.iter_mut() { + if name == old { + *name = new.to_owned(); + } + } + names.sort_unstable(); + names.dedup(); + true + } _ => false, } } } +fn category_union(names: &[String], config: &config::Config) -> Option> { + let mut channels = Vec::new(); + for name in names { + channels.extend(config.categories.get(name)?.iter().cloned()); + } + channels.sort_unstable(); + channels.dedup(); + Some(channels) +} + +fn group_name(names: &[String]) -> String { + format!("Combined · {}", names.join(" + ")) +} + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] enum WatchFilter { #[default] @@ -266,6 +300,7 @@ struct CollectionRemoval { struct View { source: ViewSource, name: String, + group_channels: Vec, title: String, videos: Vec