Skip to content

Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.

feat(tui): centralize widget components, fix playback state lock, and polish search ergonomics

Samir Hossains1082d74f9833
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ca08c1e..8cffe8b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,23 @@
## [Unreleased]
### Added
+- **Centralized UI widgets subsystem (`src/tui/widgets`)**: Standardized single-line text input
+ fields (`render_single_line_input`), viewport-accurate Ratatui scrollbars (`render_scrollbar`),
+ modal dialog framing and footer action bars (`ModalFrame`, `render_modal_footer`), and unified
+ media badge and codec tag extraction (`badge.rs`) across search, details, and modal popups.
+- **Search suggestion source badges**: Added visual pill origin tags (`[CMD]`, `[HISTORY]`,
+ `[FAVORITES]`, `[TV]`, `[SUGGEST]`) to dropdown suggestions for instant origin clarity.
+- **Responsive single-column result cards on narrow terminals (<75 cols)**: Dynamic single-column
+ grid fallback on compact terminal windows ensuring titles, badges, ratings, and tags never clip
+ or distort horizontally.
+- **Search result jump & pagination ergonomics (`Home`, `End`, `PageDown`, `PageUp`, `g`, `G`)**:
+ In `Normal` mode on the search results screen, `Home` and `g` jump to the top result, `End` and `G`
+ jump to the bottom result while automatically fetching the next page, and `PageDown`/`PageUp`
+ page through results.
+- **Playback & stream resolve state-lock fix (`playback.rs`, `download.rs`)**: Fixed an issue
+ where failed or timed-out 4KHDHub/mirror resolutions left `is_resolving_playback` permanently set
+ to `true`, preventing subsequent playback attempts; added a 15-second resolution timeout and
+ enforced state resets on all error, cancellation, and modal dismissal paths.
- **1-Key direct watch history resume (`Space` / `P`)**: Pressing `Space` or `P` on any item in
`/history` immediately launches direct playback for the recorded season and episode without
manual Details navigation. Opening Details from history (`Enter`) pre-seeds selection to the
diff --git a/docs/controls.md b/docs/controls.md
index 338b677..1318a4b 100644
--- a/docs/controls.md
+++ b/docs/controls.md
@@ -8,8 +8,8 @@ MovieBox-TUI is designed for fast keyboard navigation with complete mouse suppor
| :--- | :--- |
| **`↑` / `↓` / `k` / `j`** | Navigate lists, search results, or move cursor up/down |
| **`←` / `→` / `h` / `l`** | Move text input cursor, step wide grid columns, or switch Details panes (Audio/Seasons/Episodes/Streams) |
-| **`Home` / `End`** | Jump to start / end of list, results grid, or text input line |
-| **`PageUp` / `PageDown`** | Scroll lists and modal pickers by 5 items (or scroll help overlay) |
+| **`Home` / `End` / `g` / `G`** | Jump to start / end of list or search results (auto-fetches next page), or move cursor to beginning / end of input line |
+| **`PageUp` / `PageDown`** | Scroll search results, lists, and modal pickers by visible page height (or scroll help overlay) |
| **`Enter`** | Open, play, or confirm the selected item |
| **`Space` / `P`** | Direct resume playback for recorded season/episode on `/history` items |
| **`Esc`** | Focus search input (when results present), dismiss popup dialog, or return to landing |
diff --git a/docs/modules.md b/docs/modules.md
index bf50097..aae812f 100644
--- a/docs/modules.md
+++ b/docs/modules.md
@@ -98,6 +98,11 @@ src/
terminal.rs Terminal capability probes (basic UI, image querying).
theme.rs Color themes + terminal color detection.
text.rs Grapheme-safe text input buffer (TextInputBuffer) and width/truncation helpers.
+ widgets/ Centralized UI widgets subsystem.
+ badge.rs Resolution pill badges and audio/video media tag extraction.
+ input.rs Single-line text input field rendering with grapheme cursor and truncation.
+ modal.rs Modal dialog frame builder (ModalFrame) and centered footer key action bars.
+ scrollbar.rs Viewport-accurate vertical scrollbars.
tui/app/ The application object (App) and all behavior.
mod.rs App struct, App::new, and small helpers.
diff --git a/src/tui/app/download.rs b/src/tui/app/download.rs
index d257ed4..83f1e3f 100644
--- a/src/tui/app/download.rs
+++ b/src/tui/app/download.rs
@@ -335,13 +335,18 @@ impl App {
};
let sender = self.action_sender.clone();
tokio::spawn(async move {
- match client.resolve_release(&release).await {
- Ok(source) => {
+ let result = tokio::time::timeout(
+ std::time::Duration::from_secs(15),
+ client.resolve_release(&release),
+ )
+ .await;
+ match result {
+ Ok(Ok(source)) => {
sender
.send(Action::StartDownload(subtitle_url, Some(source.url)))
.ok();
}
- Err(error) => {
+ Ok(Err(error)) => {
log::error!("stream resolve failed: {error}");
sender
.send(Action::SetStatus(format!(
@@ -349,6 +354,14 @@ impl App {
)))
.ok();
}
+ Err(_) => {
+ log::error!("stream resolve timed out");
+ sender
+ .send(Action::SetStatus(
+ "Error: Stream resolve timed out".to_string(),
+ ))
+ .ok();
+ }
}
});
} else {
diff --git a/src/tui/app/keyboard.rs b/src/tui/app/keyboard.rs
index f447072..912d219 100644
--- a/src/tui/app/keyboard.rs
+++ b/src/tui/app/keyboard.rs
@@ -862,6 +862,94 @@ impl App {
KeyCode::Right => {
self.action_sender.send(Action::MoveRight).ok();
}
+ KeyCode::Home | KeyCode::Char('g') => {
+ if self.state.favorites_focus {
+ self.state.favorites_landing_state.select(Some(0));
+ } else if !self.state.search_results.is_empty() {
+ self.state.search_list_state.select(Some(0));
+ if let Some(res) = self.state.search_results.first() {
+ self.action_sender
+ .send(Action::FetchPreview(res.id.clone()))
+ .ok();
+ }
+ self.prefetch_visible_posters();
+ self.state.normalize_result_view();
+ }
+ }
+ KeyCode::End | KeyCode::Char('G') => {
+ if self.state.favorites_focus {
+ let total = self.state.favorites_landing_items().len();
+ if total > 0 {
+ self.state.favorites_landing_state.select(Some(total - 1));
+ }
+ } else if !self.state.search_results.is_empty() {
+ let last = self.state.search_results.len().saturating_sub(1);
+ self.state.search_list_state.select(Some(last));
+ if let Some(res) = self.state.search_results.get(last) {
+ self.action_sender
+ .send(Action::FetchPreview(res.id.clone()))
+ .ok();
+ }
+ self.prefetch_visible_posters();
+ self.state.normalize_result_view();
+ self.trigger_next_page_if_needed();
+ }
+ }
+ KeyCode::PageDown => {
+ if self.state.favorites_focus {
+ let cur =
+ self.state.favorites_landing_state.selected().unwrap_or(0);
+ let total = self.state.favorites_landing_items().len();
+ if total > 0 {
+ self.state
+ .favorites_landing_state
+ .select(Some((cur + 5).min(total - 1)));
+ }
+ } else if !self.state.search_results.is_empty() {
+ let step = self
+ .state
+ .last_result_metrics
+ .map(|m| m.visible_items)
+ .unwrap_or(8);
+ let cur = self.state.search_list_state.selected().unwrap_or(0);
+ let target = (cur + step)
+ .min(self.state.search_results.len().saturating_sub(1));
+ self.state.search_list_state.select(Some(target));
+ if let Some(res) = self.state.search_results.get(target) {
+ self.action_sender
+ .send(Action::FetchPreview(res.id.clone()))
+ .ok();
+ }
+ self.prefetch_visible_posters();
+ self.state.normalize_result_view();
+ self.trigger_next_page_if_needed();
+ }
+ }
+ KeyCode::PageUp => {
+ if self.state.favorites_focus {
+ let cur =
+ self.state.favorites_landing_state.selected().unwrap_or(0);
+ self.state
+ .favorites_landing_state
+ .select(Some(cur.saturating_sub(5)));
+ } else if !self.state.search_results.is_empty() {
+ let step = self
+ .state
+ .last_result_metrics
+ .map(|m| m.visible_items)
+ .unwrap_or(8);
+ let cur = self.state.search_list_state.selected().unwrap_or(0);
+ let target = cur.saturating_sub(step);
+ self.state.search_list_state.select(Some(target));
+ if let Some(res) = self.state.search_results.get(target) {
+ self.action_sender
+ .send(Action::FetchPreview(res.id.clone()))
+ .ok();
+ }
+ self.prefetch_visible_posters();
+ self.state.normalize_result_view();
+ }
+ }
KeyCode::Enter => {
if self.state.search_results.is_empty()
&& !self.state.search_query.trim().is_empty()
@@ -1144,3 +1232,69 @@ impl App {
|| self.state.show_episode_download_confirm
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
+
+ #[tokio::test]
+ async fn test_normal_mode_jump_navigation() {
+ let mut app = App::new();
+ app.state.active_screen = crate::tui::state::Screen::Home;
+ app.state.input_mode = InputMode::Normal;
+ app.state.search_results = vec![
+ crate::models::SearchResult {
+ id: "1".to_string(),
+ title: "Movie 1".to_string(),
+ stype: 1,
+ release_year: "2020".to_string(),
+ provider: crate::models::ProviderKind::MovieBox,
+ cover_url: None,
+ season: 0,
+ episode: 0,
+ },
+ crate::models::SearchResult {
+ id: "2".to_string(),
+ title: "Movie 2".to_string(),
+ stype: 1,
+ release_year: "2021".to_string(),
+ provider: crate::models::ProviderKind::MovieBox,
+ cover_url: None,
+ season: 0,
+ episode: 0,
+ },
+ crate::models::SearchResult {
+ id: "3".to_string(),
+ title: "Movie 3".to_string(),
+ stype: 1,
+ release_year: "2022".to_string(),
+ provider: crate::models::ProviderKind::MovieBox,
+ cover_url: None,
+ season: 0,
+ episode: 0,
+ },
+ ];
+ app.state.search_list_state.select(Some(0));
+
+ // Jump to End
+ app.handle_key(KeyEvent::new(KeyCode::End, KeyModifiers::empty()))
+ .await;
+ assert_eq!(app.state.search_list_state.selected(), Some(2));
+
+ // Jump to Home
+ app.handle_key(KeyEvent::new(KeyCode::Home, KeyModifiers::empty()))
+ .await;
+ assert_eq!(app.state.search_list_state.selected(), Some(0));
+
+ // Jump to End with G
+ app.handle_key(KeyEvent::new(KeyCode::Char('G'), KeyModifiers::SHIFT))
+ .await;
+ assert_eq!(app.state.search_list_state.selected(), Some(2));
+
+ // Jump to Home with g
+ app.handle_key(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::empty()))
+ .await;
+ assert_eq!(app.state.search_list_state.selected(), Some(0));
+ }
+}
diff --git a/src/tui/app/navigation.rs b/src/tui/app/navigation.rs
index 1540f59..eb5e981 100644
--- a/src/tui/app/navigation.rs
+++ b/src/tui/app/navigation.rs
@@ -385,6 +385,7 @@ impl App {
match action {
Action::GoBack => {
if self.state.player_picker_popup {
+ self.state.is_resolving_playback = false;
self.state.player_picker_popup = false;
self.state.player_picker_link = None;
self.state.player_picker_subtitle = None;
@@ -393,6 +394,7 @@ impl App {
return None;
}
if self.state.subtitle_popup || self.state.is_download_subtitle_popup {
+ self.state.is_resolving_playback = false;
self.state.subtitle_popup = false;
self.state.is_download_subtitle_popup = false;
self.state.pending_play_link = None;
diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rs
index 265db7e..5d73620 100644
--- a/src/tui/app/playback.rs
+++ b/src/tui/app/playback.rs
@@ -395,8 +395,13 @@ impl App {
};
let sender = self.action_sender.clone();
tokio::spawn(async move {
- match client.resolve_release(&release).await {
- Ok(source) => {
+ let result = tokio::time::timeout(
+ std::time::Duration::from_secs(15),
+ client.resolve_release(&release),
+ )
+ .await;
+ match result {
+ Ok(Ok(source)) => {
let default_player =
available_players.iter().copied().find(|kind| {
crate::tui::player::supports_headers(
@@ -410,7 +415,7 @@ impl App {
sender.send(Action::LaunchPlayback(player, source)).ok();
}
}
- Err(error) => {
+ Ok(Err(error)) => {
log::error!("4KHDHub resolve failed: {error}");
sender
.send(Action::SetStatus(format!(
@@ -418,6 +423,14 @@ impl App {
)))
.ok();
}
+ Err(_) => {
+ log::error!("4KHDHub resolve timed out");
+ sender
+ .send(Action::SetStatus(
+ "Error: 4KHDHub source resolve timed out".to_string(),
+ ))
+ .ok();
+ }
}
});
} else {
@@ -744,4 +757,37 @@ mod tests {
assert!(app.state.subtitle_popup);
assert_eq!(app.state.subtitle_list.len(), 3);
}
+
+ #[tokio::test]
+ async fn test_playback_resolving_lock_resets_on_picker_and_player_actions() {
+ let mut app = crate::tui::app::App::new();
+ app.state.is_resolving_playback = true;
+
+ app.handle_playback(crate::tui::action::Action::ShowPlaybackPicker(
+ crate::providers::models::PlaybackSource::bare(
+ crate::providers::models::ProviderKind::MovieBox,
+ "https://example.com/stream.m3u8",
+ None,
+ ),
+ ))
+ .await;
+
+ assert!(!app.state.is_resolving_playback);
+ }
+
+ #[tokio::test]
+ async fn test_playback_resolving_lock_resets_on_player_crash() {
+ let mut app = crate::tui::app::App::new();
+ app.state.is_resolving_playback = true;
+ app.state.is_playing = true;
+
+ app.handle_playback(crate::tui::action::Action::PlayerCrashed(
+ Some(1),
+ "failed".to_string(),
+ ))
+ .await;
+
+ assert!(!app.state.is_resolving_playback);
+ assert!(!app.state.is_playing);
+ }
}
diff --git a/src/tui/mod.rs b/src/tui/mod.rs
index 594f04b..1926226 100644
--- a/src/tui/mod.rs
+++ b/src/tui/mod.rs
@@ -10,6 +10,7 @@ pub mod terminal;
pub mod text;
pub mod theme;
pub use crate::updater;
+pub mod widgets;
pub fn clear_area(frame: &mut ratatui::Frame, area: ratatui::layout::Rect, _theme: &theme::Theme) {
frame.render_widget(ratatui::widgets::Clear, area);
diff --git a/src/tui/overlay.rs b/src/tui/overlay.rs
index f8db06b..eeb8cfa 100644
--- a/src/tui/overlay.rs
+++ b/src/tui/overlay.rs
@@ -3,10 +3,7 @@ use ratatui::{
layout::{Alignment, Constraint, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
- widgets::{
- Block, BorderType, Borders, List, ListItem, ListState, Paragraph, Scrollbar,
- ScrollbarOrientation, ScrollbarState,
- },
+ widgets::{Block, BorderType, Borders, List, ListItem, ListState, Paragraph},
};
use crate::tui::theme::Theme;
@@ -117,22 +114,14 @@ pub fn picker(
.min(items.len().saturating_sub(1));
let visible_rows = items.len().clamp(1, max_picker_rows(area));
let popup = picker_layout(area, items, spec.confirm_label, spec.minimum_width);
- clear_modal_area(frame, area, popup, theme);
-
let title = format!(
- " {} · {}/{} ",
+ "{} · {}/{}",
spec.title,
selected.saturating_add(1),
items.len().max(1)
);
- let block = Block::default()
- .title(title)
- .title_style(theme.title)
- .borders(Borders::ALL)
- .border_type(border_type(basic_terminal))
- .border_style(theme.lavender);
- let inner = block.inner(popup);
- frame.render_widget(block, popup);
+ let inner = crate::tui::widgets::ModalFrame::new(&title, theme, basic_terminal)
+ .render(frame, popup, area);
let sections = Layout::vertical([Constraint::Min(1), Constraint::Length(2)]).split(inner);
let max_item_w = sections[0]
@@ -152,28 +141,15 @@ pub fn picker(
frame.render_stateful_widget(list, sections[0], state);
if items.len() > visible_rows {
- let mut scrollbar_state = ScrollbarState::new(items.len())
- .viewport_content_length(visible_rows)
- .position(selected);
- let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
- .thumb_style(theme.lavender)
- .track_style(theme.surface1)
- .begin_symbol(if basic_terminal {
- Some("^")
- } else {
- Some("▲")
- })
- .end_symbol(if basic_terminal {
- Some("v")
- } else {
- Some("▼")
- })
- .track_symbol(if basic_terminal {
- Some("|")
- } else {
- Some("│")
- });
- frame.render_stateful_widget(scrollbar, sections[0], &mut scrollbar_state);
+ crate::tui::widgets::render_scrollbar(
+ frame,
+ sections[0],
+ items.len(),
+ visible_rows,
+ selected,
+ theme,
+ basic_terminal,
+ );
}
let confirm_label = if sections[1].width < 40 && spec.confirm_label == "Download" {
@@ -181,21 +157,14 @@ pub fn picker(
} else {
spec.confirm_label
};
- let footer = Line::from(vec![
+ let footer = vec![
key_hint("↑↓", "Move", theme),
Span::raw(" "),
key_hint("Enter", confirm_label, theme),
Span::raw(" "),
key_hint("Esc", "Back", theme),
- ]);
- frame.render_widget(
- Paragraph::new(footer).alignment(Alignment::Center).block(
- Block::default()
- .borders(Borders::TOP)
- .border_style(theme.muted),
- ),
- sections[1],
- );
+ ];
+ crate::tui::widgets::render_modal_footer(frame, sections[1], footer, theme);
}
pub fn confirmation(
@@ -215,16 +184,8 @@ pub fn confirmation(
36,
64,
);
- clear_modal_area(frame, area, popup, theme);
-
- let block = Block::default()
- .title(format!(" {title} "))
- .title_style(theme.title)
- .borders(Borders::ALL)
- .border_type(border_type(basic_terminal))
- .border_style(theme.lavender);
- let inner = block.inner(popup);
- frame.render_widget(block, popup);
+ let inner = crate::tui::widgets::ModalFrame::new(title, theme, basic_terminal)
+ .render(frame, popup, area);
let sections = Layout::vertical([
Constraint::Length(summary.len() as u16),
Constraint::Length(1),
diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rs
index 258f0c2..d804655 100644
--- a/src/tui/screens/details.rs
+++ b/src/tui/screens/details.rs
@@ -1,13 +1,13 @@
+pub(crate) use crate::tui::widgets::{
+ extract_media_tags, render_media_tag_spans, resolution_badge_spans,
+};
use crate::tui::{state::AppState, theme::Theme};
use ratatui::{
Frame,
layout::{Alignment, Constraint, Direction, Layout, Rect},
style::{Color, Modifier, Style},
text::{Line, Span},
- widgets::{
- Block, Borders, List, ListItem, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState,
- Wrap,
- },
+ widgets::{Block, Borders, List, ListItem, Paragraph, Wrap},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -1536,265 +1536,6 @@ pub(crate) fn stream_loading_spinner(tick_count: u64, basic_terminal: bool) -> &
}
}
-pub(crate) fn resolution_badge_spans<'a>(
- resolution: i64,
- theme: &'a Theme,
- basic_terminal: bool,
-) -> Vec<Span<'a>> {
- if basic_terminal {
- let (label, style) = match resolution {
- 2160 | 4320 => ("[4K]", theme.rating.add_modifier(Modifier::BOLD)),
- 1080 => ("[1080p]", theme.highlight.add_modifier(Modifier::BOLD)),
- 720 => ("[720p]", theme.teal.add_modifier(Modifier::BOLD)),
- 480 | 540 | 576 => ("[SD]", theme.text_dim.add_modifier(Modifier::BOLD)),
- _ if resolution > 0 => (
- match resolution {
- 2160 => "[4K]",
- 1080 => "[1080p]",
- 720 => "[720p]",
- 480 => "[480p]",
- 360 => "[360p]",
- _ => "[HD]",
- },
- theme.text.add_modifier(Modifier::BOLD),
- ),
- _ => ("[SD]", theme.text_dim),
- };
- return vec![Span::styled(format!("{:<8}", label), style)];
- }
-
- let (badge_bg, contrast_fg, label) = match resolution {
- 2160 | 4320 => (
- theme_color(theme.rating, Color::Rgb(249, 226, 175)),
- if theme.is_light {
- Color::White
- } else {
- theme_color(theme.crust, Color::Rgb(17, 17, 27))
- },
- " 4K ",
- ),
- 1080 => (
- theme_color(theme.sapphire, Color::Rgb(116, 199, 236)),
- if theme.is_light {
- Color::White
- } else {
- theme_color(theme.crust, Color::Rgb(17, 17, 27))
- },
- " 1080p ",
- ),
- 720 => (
- theme_color(theme.teal, Color::Rgb(148, 226, 213)),
- if theme.is_light {
- Color::White
- } else {
- theme_color(theme.crust, Color::Rgb(17, 17, 27))
- },
- " 720p ",
- ),
- 480 | 540 | 576 => (
- theme_color(theme.surface2, Color::Rgb(88, 91, 112)),
- theme_color(theme.text, Color::White),
- " SD ",
- ),
- _ if resolution > 0 => (
- theme_color(theme.surface2, Color::Rgb(88, 91, 112)),
- theme_color(theme.text, Color::White),
- match resolution {
- 2160 => " 4K ",
- 1080 => " 1080p ",
- 720 => " 720p ",
- 480 => " 480p ",
- 360 => " 360p ",
- _ => " HD ",
- },
- ),
- _ => (
- theme_color(theme.surface2, Color::Rgb(88, 91, 112)),
- theme_color(theme.text_dim, Color::Gray),
- " SD ",
- ),
- };
-
- vec![
- Span::styled(
- label,
- Style::default()
- .bg(badge_bg)
- .fg(contrast_fg)
- .add_modifier(Modifier::BOLD),
- ),
- Span::raw(" "),
- ]
-}
-
-#[derive(Debug, Clone, Default)]
-struct MediaTags {
- hdr: Option<&'static str>,
- audio: Option<&'static str>,
- codec: Option<&'static str>,
- source: Option<&'static str>,
-}
-
-fn extract_media_tags(title: &str, codec_name: &str) -> MediaTags {
- let lower_title = title.to_ascii_lowercase();
- let lower_codec = codec_name.to_ascii_lowercase();
-
- let hdr = if lower_title.contains("hdr10+") || lower_title.contains("hdr10plus") {
- Some("HDR10+")
- } else if lower_title.contains("dovi")
- || lower_title.contains("dolby vision")
- || lower_title.contains("dolbyvision")
- || lower_title.contains(".dv.")
- || lower_title.contains(" dv ")
- || lower_title.contains("-dv")
- {
- Some("DV")
- } else if lower_title.contains("hdr") {
- Some("HDR")
- } else {
- None
- };
-
- let audio = if lower_title.contains("atmos") {
- Some("ATMOS")
- } else if lower_title.contains("7.1") {
- Some("7.1")
- } else if lower_title.contains("5.1")
- || lower_title.contains("ddp5.1")
- || lower_title.contains("dd5.1")
- || lower_title.contains("ac3")
- {
- Some("5.1")
- } else {
- None
- };
-
- let codec = if lower_codec.contains("hevc")
- || lower_codec.contains("x265")
- || lower_codec.contains("h265")
- || lower_title.contains("hevc")
- || lower_title.contains("x265")
- || lower_title.contains("h.265")
- || lower_title.contains("h265")
- {
- Some("HEVC")
- } else if lower_codec.contains("av1") || lower_title.contains("av1") {
- Some("AV1")
- } else if lower_codec.contains("h264")
- || lower_codec.contains("x264")
- || lower_codec.contains("avc")
- || lower_title.contains("x264")
- || lower_title.contains("h.264")
- || lower_title.contains("h264")
- || lower_title.contains("avc")
- {
- Some("H.264")
- } else {
- None
- };
-
- let source = if lower_title.contains("remux") {
- Some("REMUX")
- } else if lower_title.contains("bluray")
- || lower_title.contains("bdrip")
- || lower_title.contains("brrip")
- {
- Some("BluRay")
- } else if lower_title.contains("web-dl")
- || lower_title.contains("webdl")
- || lower_title.contains("webrip")
- {
- Some("WEB-DL")
- } else {
- None
- };
-
- MediaTags {
- hdr,
- audio,
- codec,
- source,
- }
-}
-
-fn render_media_tag_spans<'a>(
- tags: &MediaTags,
- theme: &'a Theme,
- basic_terminal: bool,
-) -> Vec<Span<'a>> {
- let mut spans = Vec::new();
-
- if let Some(hdr) = tags.hdr {
- if basic_terminal {
- spans.push(Span::styled(
- format!("[{hdr}] "),
- theme.rating.add_modifier(Modifier::BOLD),
- ));
- } else {
- let bg = theme_color(theme.surface1, Color::Rgb(73, 76, 94));
- let fg = theme_color(theme.rating, Color::Yellow);
- spans.push(Span::styled(
- format!(" {hdr} "),
- Style::default().bg(bg).fg(fg).add_modifier(Modifier::BOLD),
- ));
- spans.push(Span::raw(" "));
- }
- }
-
- if let Some(audio) = tags.audio {
- if basic_terminal {
- spans.push(Span::styled(
- format!("[{audio}] "),
- theme.sapphire.add_modifier(Modifier::BOLD),
- ));
- } else {
- let bg = theme_color(theme.surface0, Color::Rgb(56, 58, 74));
- let fg = theme_color(theme.sapphire, Color::Cyan);
- spans.push(Span::styled(
- format!(" {audio} "),
- Style::default().bg(bg).fg(fg).add_modifier(Modifier::BOLD),
- ));
- spans.push(Span::raw(" "));
- }
- }
-
- if let Some(codec) = tags.codec {
- if basic_terminal {
- spans.push(Span::styled(
- format!("[{codec}] "),
- theme.teal.add_modifier(Modifier::BOLD),
- ));
- } else {
- let bg = theme_color(theme.surface0, Color::Rgb(56, 58, 74));
- let fg = theme_color(theme.teal, Color::Rgb(148, 226, 213));
- spans.push(Span::styled(
- format!(" {codec} "),
- Style::default().bg(bg).fg(fg),
- ));
- spans.push(Span::raw(" "));
- }
- }
-
- if let Some(source) = tags.source {
- if basic_terminal {
- spans.push(Span::styled(
- format!("[{source}] "),
- theme.lavender.add_modifier(Modifier::BOLD),
- ));
- } else {
- let bg = theme_color(theme.surface0, Color::Rgb(56, 58, 74));
- let fg = theme_color(theme.lavender, Color::Rgb(180, 190, 254));
- spans.push(Span::styled(
- format!(" {source} "),
- Style::default().bg(bg).fg(fg),
- ));
- spans.push(Span::raw(" "));
- }
- }
-
- spans
-}
-
fn with_selection_surface(style: Style, basic_terminal: bool, theme: &Theme) -> Style {
if basic_terminal {
style
@@ -2064,47 +1805,24 @@ fn render_scroll_indicator(
theme: &Theme,
basic_terminal: bool,
) {
- let viewport_length = area.height.saturating_sub(2) as usize;
- if content_length <= viewport_length || viewport_length == 0 {
- return;
- }
-
- let mut state = ScrollbarState::default()
- .content_length(content_length)
- .viewport_content_length(viewport_length)
- .position(position);
- let scrollbar = Scrollbar::default()
- .orientation(ScrollbarOrientation::VerticalRight)
- .thumb_style(theme.lavender)
- .track_style(theme.surface1)
- .begin_symbol(if basic_terminal {
- Some("^")
- } else {
- Some("▲")
- })
- .end_symbol(if basic_terminal {
- Some("v")
- } else {
- Some("▼")
- })
- .track_symbol(if basic_terminal {
- Some("|")
- } else {
- Some("│")
- });
- frame.render_stateful_widget(
- scrollbar,
- area.inner(ratatui::layout::Margin {
- vertical: 1,
- horizontal: 0,
- }),
- &mut state,
+ let scroll_area = area.inner(ratatui::layout::Margin {
+ vertical: 1,
+ horizontal: 0,
+ });
+ crate::tui::widgets::render_scrollbar(
+ frame,
+ scroll_area,
+ content_length,
+ scroll_area.height as usize,
+ position,
+ theme,
+ basic_terminal,
);
}
#[cfg(test)]
mod tests {
use super::*;
-
+ use crate::tui::widgets::MediaTags;
#[test]
fn test_stream_loading_spinner_frames() {
assert_eq!(stream_loading_spinner(0, false), "⠋");
diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rs
index 30ac57b..4813a82 100644
--- a/src/tui/screens/home.rs
+++ b/src/tui/screens/home.rs
@@ -1247,35 +1247,15 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
}
}
- let content_len = state.search_results.len();
- if content_len > metrics.visible_items {
- let scrollbar = ratatui::widgets::Scrollbar::default()
- .orientation(ratatui::widgets::ScrollbarOrientation::VerticalRight)
- .begin_symbol(if state.basic_terminal {
- Some("^")
- } else {
- Some("▲")
- })
- .end_symbol(if state.basic_terminal {
- Some("v")
- } else {
- Some("▼")
- })
- .track_symbol(if state.basic_terminal {
- Some("|")
- } else {
- Some("│")
- })
- .thumb_symbol(if state.basic_terminal { "|" } else { "█" });
-
- let mut scrollbar_state = ratatui::widgets::ScrollbarState::default()
- .content_length(content_len.saturating_sub(metrics.visible_items))
- .position(state.result_scroll);
-
- let sb_area = results_area;
-
- frame.render_stateful_widget(scrollbar, sb_area, &mut scrollbar_state);
- }
+ crate::tui::widgets::render_scrollbar(
+ frame,
+ results_area,
+ state.search_results.len(),
+ metrics.visible_items,
+ state.result_scroll,
+ theme,
+ state.basic_terminal,
+ );
} else {
render_search_state(frame, chunks[4], state, theme, view);
}
@@ -1297,22 +1277,13 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
total_rows,
state.tv_input_active,
);
- crate::tui::overlay::clear_modal_area(frame, area, popup_area, theme);
-
let title = format!(
- " TV Playlists · {}/{} ",
+ "TV Playlists · {}/{}",
state.tv_manager_selected.saturating_add(1),
total_rows.max(1)
);
- let popup_block = ratatui::widgets::Block::default()
- .title(title)
- .title_style(theme.title)
- .borders(ratatui::widgets::Borders::ALL)
- .border_type(crate::tui::overlay::border_type(state.basic_terminal))
- .border_style(theme.lavender);
-
- let inner_area = popup_block.inner(popup_area);
- frame.render_widget(popup_block, popup_area);
+ let inner_area = crate::tui::widgets::ModalFrame::new(&title, theme, state.basic_terminal)
+ .render(frame, popup_area, area);
let sections = ratatui::layout::Layout::vertical([
ratatui::layout::Constraint::Min(1),
@@ -1326,58 +1297,13 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
} else {
"Enter playlist URL:"
};
- let segments = state.tv_input_buffer.graphemes();
- let cursor = state.tv_input_buffer.cursor();
- let max_width = inner_area.width.saturating_sub(6) as usize;
-
- let mut start = 0;
- if cursor >= max_width {
- start = cursor - max_width + 1;
- }
-
- let mut before_cursor: String = segments[start..cursor].concat();
- if start > 0 && before_cursor.chars().count() > 3 {
- before_cursor = format!("...{}", &before_cursor[3..]);
- }
-
- let cursor_char = if cursor < segments.len() {
- segments[cursor].to_string()
- } else {
- " ".to_string()
- };
-
- let end = (start + max_width).min(segments.len());
- let after_slice = &segments[cursor.saturating_add(1).min(segments.len())..end];
- let mut after_cursor: String = after_slice.concat();
- if end < segments.len() {
- let len = after_cursor.chars().count();
- if len > 3 {
- let keep: String = after_cursor.chars().take(len - 3).collect();
- after_cursor = format!("{keep}...");
- } else if !after_cursor.is_empty() {
- after_cursor = "...".to_string();
- }
- }
-
- let lines = vec![
- ratatui::text::Line::from(vec![
- ratatui::text::Span::raw(" "),
- ratatui::text::Span::styled(label, theme.sapphire),
- ]),
- ratatui::text::Line::from(vec![
- ratatui::text::Span::styled(" ❯ ", theme.sapphire),
- ratatui::text::Span::styled(before_cursor, theme.text),
- ratatui::text::Span::styled(
- cursor_char,
- theme.text.add_modifier(ratatui::style::Modifier::REVERSED),
- ),
- ratatui::text::Span::styled(after_cursor, theme.text),
- ]),
- ];
- frame.render_widget(
- ratatui::widgets::Paragraph::new(lines)
- .wrap(ratatui::widgets::Wrap { trim: false }),
+ crate::tui::widgets::render_single_line_input(
+ frame,
sections[0],
+ label,
+ &state.tv_input_buffer,
+ theme,
+ state.basic_terminal,
);
} else {
let items: Vec<ratatui::widgets::ListItem> = rows
@@ -1446,13 +1372,13 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
}
let footer = if state.tv_input_active {
- ratatui::text::Line::from(vec![
+ vec![
crate::tui::overlay::key_hint("Enter", "Add", theme),
ratatui::text::Span::raw(" "),
crate::tui::overlay::key_hint("Esc", "Cancel", theme),
- ])
+ ]
} else {
- ratatui::text::Line::from(vec![
+ vec![
crate::tui::overlay::key_hint("↑↓", "Move", theme),
ratatui::text::Span::raw(" "),
crate::tui::overlay::key_hint("Enter", "Select", theme),
@@ -1460,19 +1386,9 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
crate::tui::overlay::key_hint("d", "Remove", theme),
ratatui::text::Span::raw(" "),
crate::tui::overlay::key_hint("Esc", "Close", theme),
- ])
+ ]
};
-
- frame.render_widget(
- ratatui::widgets::Paragraph::new(footer)
- .alignment(ratatui::layout::Alignment::Center)
- .block(
- ratatui::widgets::Block::default()
- .borders(ratatui::widgets::Borders::TOP)
- .border_style(theme.muted),
- ),
- sections[1],
- );
+ crate::tui::widgets::render_modal_footer(frame, sections[1], footer, theme);
}
if state.addon_manager_popup {
@@ -1480,22 +1396,13 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let total_rows = state.addon_manager_rows().len();
let popup_area =
crate::tui::overlay::addon_manager_layout(area, addons_count, state.addon_input_active);
- crate::tui::overlay::clear_modal_area(frame, area, popup_area, theme);
-
let title = format!(
- " Addons Manager · {}/{} ",
+ "Addons Manager · {}/{}",
state.addon_manager_selected.saturating_add(1),
total_rows.max(1)
);
- let popup_block = ratatui::widgets::Block::default()
- .title(title)
- .title_style(theme.title)
- .borders(ratatui::widgets::Borders::ALL)
- .border_type(crate::tui::overlay::border_type(state.basic_terminal))
- .border_style(theme.lavender);
-
- let inner_area = popup_block.inner(popup_area);
- frame.render_widget(popup_block, popup_area);
+ let inner_area = crate::tui::widgets::ModalFrame::new(&title, theme, state.basic_terminal)
+ .render(frame, popup_area, area);
if state.addon_input_active {
let sections = ratatui::layout::Layout::vertical([
@@ -1504,71 +1411,21 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
])
.split(inner_area);
- let segments = state.addon_input_buffer.graphemes();
- let cursor = state.addon_input_buffer.cursor();
- let max_width = inner_area.width.saturating_sub(6) as usize;
-
- let mut start = 0;
- if cursor >= max_width {
- start = cursor - max_width + 1;
- }
-
- let mut before_cursor: String = segments[start..cursor].concat();
- if start > 0 && before_cursor.chars().count() > 3 {
- before_cursor = format!("...{}", &before_cursor[3..]);
- }
-
- let cursor_char = if cursor < segments.len() {
- segments[cursor].to_string()
- } else {
- " ".to_string()
- };
-
- let end = (start + max_width).min(segments.len());
- let after_slice = &segments[cursor.saturating_add(1).min(segments.len())..end];
- let mut after_cursor: String = after_slice.concat();
- if end < segments.len() {
- let len = after_cursor.chars().count();
- if len > 3 {
- let keep: String = after_cursor.chars().take(len - 3).collect();
- after_cursor = format!("{keep}...");
- } else if len > 0 {
- after_cursor = "...".to_string();
- }
- }
-
- let lines = vec![
- ratatui::text::Line::from(vec![
- ratatui::text::Span::raw(" "),
- ratatui::text::Span::styled("Enter Addon Manifest URL:", theme.sapphire),
- ]),
- ratatui::text::Line::from(vec![
- ratatui::text::Span::styled(" ❯ ", theme.sapphire),
- ratatui::text::Span::styled(before_cursor, theme.text),
- ratatui::text::Span::styled(
- cursor_char,
- theme.text.add_modifier(ratatui::style::Modifier::REVERSED),
- ),
- ratatui::text::Span::styled(after_cursor, theme.text),
- ]),
- ];
- frame.render_widget(ratatui::widgets::Paragraph::new(lines), sections[0]);
+ crate::tui::widgets::render_single_line_input(
+ frame,
+ sections[0],
+ "Enter Addon Manifest URL:",
+ &state.addon_input_buffer,
+ theme,
+ state.basic_terminal,
+ );
- let footer = ratatui::text::Line::from(vec![
+ let footer = vec![
crate::tui::overlay::key_hint("Enter", "Add", theme),
ratatui::text::Span::raw(" "),
crate::tui::overlay::key_hint("Esc", "Cancel", theme),
- ]);
- frame.render_widget(
- ratatui::widgets::Paragraph::new(footer)
- .alignment(ratatui::layout::Alignment::Center)
- .block(
- ratatui::widgets::Block::default()
- .borders(ratatui::widgets::Borders::TOP)
- .border_style(theme.muted),
- ),
- sections[1],
- );
+ ];
+ crate::tui::widgets::render_modal_footer(frame, sections[1], footer, theme);
} else {
let sections = ratatui::layout::Layout::vertical([
ratatui::layout::Constraint::Min(1),
@@ -1658,7 +1515,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
ratatui::text::Line::from(vec![ratatui::text::Span::raw(" "), add_button]);
frame.render_widget(ratatui::widgets::Paragraph::new(button_line), sections[1]);
- let footer = ratatui::text::Line::from(vec![
+ let footer = vec![
crate::tui::overlay::key_hint("↑↓←→", "Move", theme),
ratatui::text::Span::raw(" "),
crate::tui::overlay::key_hint("Enter/Space", "Toggle/Select", theme),
@@ -1666,18 +1523,8 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
crate::tui::overlay::key_hint("d", "Remove", theme),
ratatui::text::Span::raw(" "),
crate::tui::overlay::key_hint("Esc", "Close", theme),
- ]);
-
- frame.render_widget(
- ratatui::widgets::Paragraph::new(footer)
- .alignment(ratatui::layout::Alignment::Center)
- .block(
- ratatui::widgets::Block::default()
- .borders(ratatui::widgets::Borders::TOP)
- .border_style(theme.muted),
- ),
- sections[2],
- );
+ ];
+ crate::tui::widgets::render_modal_footer(frame, sections[2], footer, theme);
}
}
@@ -1729,6 +1576,32 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
);
}
}
+fn suggestion_source_badge<'a>(
+ suggestion: &str,
+ state: &AppState,
+ theme: &'a Theme,
+ basic_terminal: bool,
+) -> Span<'a> {
+ let (tag, style) = if suggestion.starts_with('/') {
+ if suggestion.eq_ignore_ascii_case("/history") {
+ ("[HISTORY]", theme.sapphire)
+ } else if suggestion.eq_ignore_ascii_case("/favorites") {
+ ("[FAVORITES]", theme.rating)
+ } else {
+ ("[CMD]", theme.teal)
+ }
+ } else if state.is_tv_mode {
+ ("[TV]", theme.lavender)
+ } else {
+ ("[SUGGEST]", theme.overlay1)
+ };
+
+ if basic_terminal {
+ Span::styled(format!("{tag} "), style.add_modifier(Modifier::BOLD))
+ } else {
+ Span::styled(format!("{tag} "), style)
+ }
+}
fn render_search_suggestions(
frame: &mut Frame,
@@ -1844,14 +1717,18 @@ fn render_search_suggestions(
theme.overlay1
};
+ let badge_span = suggestion_source_badge(suggestion, state, theme, state.basic_terminal);
+ let badge_width = crate::tui::text::width(&badge_span.content);
+
let mut spans = vec![
Span::styled(branch_symbol, branch_style),
+ badge_span,
Span::styled(display_name, text_style),
];
if let Some(description) = desc {
- let name_len = crate::tui::text::width(display_name);
- let pad = 24usize.saturating_sub(name_len).max(2);
+ let name_len = crate::tui::text::width(display_name) + badge_width;
+ let pad = 28usize.saturating_sub(name_len).max(2);
spans.push(Span::raw(" ".repeat(pad)));
let desc_budget = (available_width as usize)
.saturating_sub(3 + name_len + pad)
@@ -1872,3 +1749,59 @@ fn render_search_suggestions(
frame.render_widget(Paragraph::new(Line::from(spans)), row_area);
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ratatui::{Terminal, backend::TestBackend};
+
+ #[test]
+ fn test_suggestion_source_badge_types() {
+ let theme = Theme::mocha();
+ let state = AppState::default();
+
+ let badge_cmd = suggestion_source_badge("/help", &state, &theme, false);
+ assert!(badge_cmd.content.contains("[CMD]"));
+
+ let badge_hist = suggestion_source_badge("/history", &state, &theme, false);
+ assert!(badge_hist.content.contains("[HISTORY]"));
+
+ let badge_fav = suggestion_source_badge("/favorites", &state, &theme, false);
+ assert!(badge_fav.content.contains("[FAVORITES]"));
+
+ let badge_sug = suggestion_source_badge("Breaking Bad", &state, &theme, false);
+ assert!(badge_sug.content.contains("[SUGGEST]"));
+ }
+
+ #[test]
+ fn test_render_search_suggestions_dropdown() {
+ let backend = TestBackend::new(80, 24);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let state = AppState {
+ input_mode: InputMode::Editing,
+ search_suggestions: vec![
+ "/help".to_string(),
+ "/history".to_string(),
+ "Inception".to_string(),
+ ],
+ suggest_index: Some(0),
+ ..Default::default()
+ };
+ let theme = Theme::mocha();
+
+ terminal
+ .draw(|frame| {
+ let area = Rect::new(0, 0, 80, 24);
+ let search_bar = Rect::new(10, 2, 60, 3);
+ render_search_suggestions(
+ frame,
+ area,
+ search_bar,
+ &state,
+ &theme,
+ SearchViewState::Empty,
+ );
+ })
+ .unwrap();
+ }
+}
diff --git a/src/tui/state.rs b/src/tui/state.rs
index 8299e34..d001610 100644
--- a/src/tui/state.rs
+++ b/src/tui/state.rs
@@ -47,6 +47,9 @@ pub struct ResultMetrics {
}
pub fn result_columns_for(width: u16) -> u16 {
+ if width < 75 {
+ return 1;
+ }
let by_width = if width >= 160 {
3
} else if width >= 110 {
diff --git a/src/tui/widgets/badge.rs b/src/tui/widgets/badge.rs
new file mode 100644
index 0000000..cc745db
--- /dev/null
+++ b/src/tui/widgets/badge.rs
@@ -0,0 +1,310 @@
+use ratatui::{
+ style::{Color, Modifier, Style},
+ text::Span,
+};
+
+use crate::tui::theme::Theme;
+
+fn theme_color(style: Style, fallback: Color) -> Color {
+ style.fg.unwrap_or(fallback)
+}
+
+pub fn resolution_badge_spans<'a>(
+ resolution: i64,
+ theme: &'a Theme,
+ basic_terminal: bool,
+) -> Vec<Span<'a>> {
+ if basic_terminal {
+ let (label, style) = match resolution {
+ 2160 | 4320 => ("[4K]", theme.rating.add_modifier(Modifier::BOLD)),
+ 1080 => ("[1080p]", theme.highlight.add_modifier(Modifier::BOLD)),
+ 720 => ("[720p]", theme.teal.add_modifier(Modifier::BOLD)),
+ 480 | 540 | 576 => ("[SD]", theme.text_dim.add_modifier(Modifier::BOLD)),
+ _ if resolution > 0 => (
+ match resolution {
+ 2160 => "[4K]",
+ 1080 => "[1080p]",
+ 720 => "[720p]",
+ 480 => "[480p]",
+ 360 => "[360p]",
+ _ => "[HD]",
+ },
+ theme.text.add_modifier(Modifier::BOLD),
+ ),
+ _ => ("[SD]", theme.text_dim),
+ };
+ return vec![Span::styled(format!("{:<8}", label), style)];
+ }
+
+ let (badge_bg, contrast_fg, label) = match resolution {
+ 2160 | 4320 => (
+ theme_color(theme.rating, Color::Rgb(249, 226, 175)),
+ if theme.is_light {
+ Color::White
+ } else {
+ theme_color(theme.crust, Color::Rgb(17, 17, 27))
+ },
+ " 4K ",
+ ),
+ 1080 => (
+ theme_color(theme.sapphire, Color::Rgb(116, 199, 236)),
+ if theme.is_light {
+ Color::White
+ } else {
+ theme_color(theme.crust, Color::Rgb(17, 17, 27))
+ },
+ " 1080p ",
+ ),
+ 720 => (
+ theme_color(theme.teal, Color::Rgb(148, 226, 213)),
+ if theme.is_light {
+ Color::White
+ } else {
+ theme_color(theme.crust, Color::Rgb(17, 17, 27))
+ },
+ " 720p ",
+ ),
+ 480 | 540 | 576 => (
+ theme_color(theme.surface2, Color::Rgb(88, 91, 112)),
+ theme_color(theme.text, Color::White),
+ " SD ",
+ ),
+ _ if resolution > 0 => (
+ theme_color(theme.surface2, Color::Rgb(88, 91, 112)),
+ theme_color(theme.text, Color::White),
+ match resolution {
+ 2160 => " 4K ",
+ 1080 => " 1080p ",
+ 720 => " 720p ",
+ 480 => " 480p ",
+ 360 => " 360p ",
+ _ => " HD ",
+ },
+ ),
+ _ => (
+ theme_color(theme.surface2, Color::Rgb(88, 91, 112)),
+ theme_color(theme.text_dim, Color::Gray),
+ " SD ",
+ ),
+ };
+
+ vec![
+ Span::styled(
+ label,
+ Style::default()
+ .bg(badge_bg)
+ .fg(contrast_fg)
+ .add_modifier(Modifier::BOLD),
+ ),
+ Span::raw(" "),
+ ]
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct MediaTags {
+ pub hdr: Option<&'static str>,
+ pub audio: Option<&'static str>,
+ pub codec: Option<&'static str>,
+ pub source: Option<&'static str>,
+}
+
+pub fn extract_media_tags(title: &str, codec_name: &str) -> MediaTags {
+ let lower_title = title.to_ascii_lowercase();
+ let lower_codec = codec_name.to_ascii_lowercase();
+
+ let hdr = if lower_title.contains("hdr10+") || lower_title.contains("hdr10plus") {
+ Some("HDR10+")
+ } else if lower_title.contains("dovi")
+ || lower_title.contains("dolby vision")
+ || lower_title.contains("dolbyvision")
+ || lower_title.contains(".dv.")
+ || lower_title.contains(" dv ")
+ || lower_title.contains("-dv")
+ {
+ Some("DV")
+ } else if lower_title.contains("hdr") {
+ Some("HDR")
+ } else {
+ None
+ };
+
+ let audio = if lower_title.contains("atmos") {
+ Some("ATMOS")
+ } else if lower_title.contains("7.1") {
+ Some("7.1")
+ } else if lower_title.contains("5.1")
+ || lower_title.contains("ddp5.1")
+ || lower_title.contains("dd5.1")
+ || lower_title.contains("ac3")
+ {
+ Some("5.1")
+ } else {
+ None
+ };
+
+ let codec = if lower_codec.contains("hevc")
+ || lower_codec.contains("x265")
+ || lower_codec.contains("h265")
+ || lower_title.contains("hevc")
+ || lower_title.contains("x265")
+ || lower_title.contains("h.265")
+ || lower_title.contains("h265")
+ {
+ Some("HEVC")
+ } else if lower_codec.contains("av1") || lower_title.contains("av1") {
+ Some("AV1")
+ } else if lower_codec.contains("h264")
+ || lower_codec.contains("x264")
+ || lower_codec.contains("avc")
+ || lower_title.contains("x264")
+ || lower_title.contains("h.264")
+ || lower_title.contains("h264")
+ || lower_title.contains("avc")
+ {
+ Some("H.264")
+ } else {
+ None
+ };
+
+ let source = if lower_title.contains("remux") {
+ Some("REMUX")
+ } else if lower_title.contains("bluray")
+ || lower_title.contains("bdrip")
+ || lower_title.contains("brrip")
+ {
+ Some("BluRay")
+ } else if lower_title.contains("web-dl")
+ || lower_title.contains("webdl")
+ || lower_title.contains("webrip")
+ {
+ Some("WEB-DL")
+ } else {
+ None
+ };
+
+ MediaTags {
+ hdr,
+ audio,
+ codec,
+ source,
+ }
+}
+
+pub fn render_media_tag_spans<'a>(
+ tags: &MediaTags,
+ theme: &'a Theme,
+ basic_terminal: bool,
+) -> Vec<Span<'a>> {
+ let mut spans = Vec::new();
+
+ if let Some(hdr) = tags.hdr {
+ if basic_terminal {
+ spans.push(Span::styled(
+ format!("[{hdr}] "),
+ theme.rating.add_modifier(Modifier::BOLD),
+ ));
+ } else {
+ let bg = theme_color(theme.surface1, Color::Rgb(73, 76, 94));
+ let fg = theme_color(theme.rating, Color::Yellow);
+ spans.push(Span::styled(
+ format!(" {hdr} "),
+ Style::default().bg(bg).fg(fg).add_modifier(Modifier::BOLD),
+ ));
+ spans.push(Span::raw(" "));
+ }
+ }
+
+ if let Some(audio) = tags.audio {
+ if basic_terminal {
+ spans.push(Span::styled(
+ format!("[{audio}] "),
+ theme.sapphire.add_modifier(Modifier::BOLD),
+ ));
+ } else {
+ let bg = theme_color(theme.surface0, Color::Rgb(56, 58, 74));
+ let fg = theme_color(theme.sapphire, Color::Cyan);
+ spans.push(Span::styled(
+ format!(" {audio} "),
+ Style::default().bg(bg).fg(fg).add_modifier(Modifier::BOLD),
+ ));
+ spans.push(Span::raw(" "));
+ }
+ }
+
+ if let Some(codec) = tags.codec {
+ if basic_terminal {
+ spans.push(Span::styled(
+ format!("[{codec}] "),
+ theme.teal.add_modifier(Modifier::BOLD),
+ ));
+ } else {
+ let bg = theme_color(theme.surface0, Color::Rgb(56, 58, 74));
+ let fg = theme_color(theme.teal, Color::Rgb(148, 226, 213));
+ spans.push(Span::styled(
+ format!(" {codec} "),
+ Style::default().bg(bg).fg(fg),
+ ));
+ spans.push(Span::raw(" "));
+ }
+ }
+
+ if let Some(source) = tags.source {
+ if basic_terminal {
+ spans.push(Span::styled(
+ format!("[{source}] "),
+ theme.lavender.add_modifier(Modifier::BOLD),
+ ));
+ } else {
+ let bg = theme_color(theme.surface0, Color::Rgb(56, 58, 74));
+ let fg = theme_color(theme.lavender, Color::Rgb(180, 190, 254));
+ spans.push(Span::styled(
+ format!(" {source} "),
+ Style::default().bg(bg).fg(fg),
+ ));
+ spans.push(Span::raw(" "));
+ }
+ }
+
+ spans
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_extract_media_tags() {
+ let tags = extract_media_tags(
+ "Dune.Part.Two.2024.2160p.UHD.BluRay.x265.Atmos.TrueHD.7.1.DV.HDR",
+ "hevc",
+ );
+ assert_eq!(tags.hdr, Some("DV"));
+ assert_eq!(tags.audio, Some("ATMOS"));
+ assert_eq!(tags.codec, Some("HEVC"));
+ assert_eq!(tags.source, Some("BluRay"));
+ }
+
+ #[test]
+ fn test_resolution_badge_spans_4k() {
+ let theme = Theme::default();
+ let spans_normal = resolution_badge_spans(2160, &theme, false);
+ assert_eq!(spans_normal.len(), 2);
+
+ let spans_basic = resolution_badge_spans(2160, &theme, true);
+ assert_eq!(spans_basic.len(), 1);
+ assert!(spans_basic[0].content.contains("[4K]"));
+ }
+
+ #[test]
+ fn test_render_media_tag_spans() {
+ let theme = Theme::default();
+ let tags = MediaTags {
+ hdr: Some("HDR"),
+ audio: Some("5.1"),
+ codec: Some("HEVC"),
+ source: Some("WEB-DL"),
+ };
+ let spans = render_media_tag_spans(&tags, &theme, false);
+ assert_eq!(spans.len(), 8);
+ }
+}
diff --git a/src/tui/widgets/input.rs b/src/tui/widgets/input.rs
new file mode 100644
index 0000000..3873d05
--- /dev/null
+++ b/src/tui/widgets/input.rs
@@ -0,0 +1,113 @@
+use ratatui::{
+ Frame,
+ layout::Rect,
+ style::Modifier,
+ text::{Line, Span},
+ widgets::{Paragraph, Wrap},
+};
+
+use crate::tui::{text::TextInputBuffer, theme::Theme};
+
+pub fn render_single_line_input(
+ frame: &mut Frame,
+ area: Rect,
+ label: &str,
+ buffer: &TextInputBuffer,
+ theme: &Theme,
+ basic_terminal: bool,
+) {
+ let segments = buffer.graphemes();
+ let cursor = buffer.cursor();
+ let max_width = (area.width as usize).saturating_sub(6);
+
+ let mut start = 0;
+ if cursor >= max_width {
+ start = cursor - max_width + 1;
+ }
+
+ let mut before_cursor: String = segments[start..cursor].concat();
+ if start > 0 && before_cursor.chars().count() > 3 {
+ before_cursor = format!("...{}", &before_cursor[3..]);
+ }
+
+ let cursor_char = if cursor < segments.len() {
+ segments[cursor].to_string()
+ } else {
+ " ".to_string()
+ };
+
+ let end = (start + max_width).min(segments.len());
+ let after_slice = &segments[cursor.saturating_add(1).min(segments.len())..end];
+ let mut after_cursor: String = after_slice.concat();
+ if end < segments.len() {
+ let len = after_cursor.chars().count();
+ if len > 3 {
+ let keep: String = after_cursor.chars().take(len - 3).collect();
+ after_cursor = format!("{keep}...");
+ } else if !after_cursor.is_empty() {
+ after_cursor = "...".to_string();
+ }
+ }
+
+ let prompt_symbol = if basic_terminal { " > " } else { " ❯ " };
+ let lines = vec![
+ Line::from(vec![Span::raw(" "), Span::styled(label, theme.sapphire)]),
+ Line::from(vec![
+ Span::styled(prompt_symbol, theme.sapphire),
+ Span::styled(before_cursor, theme.text),
+ Span::styled(cursor_char, theme.text.add_modifier(Modifier::REVERSED)),
+ Span::styled(after_cursor, theme.text),
+ ]),
+ ];
+
+ frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), area);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ratatui::{Terminal, backend::TestBackend};
+
+ #[test]
+ fn test_render_single_line_input_empty() {
+ let backend = TestBackend::new(80, 10);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let buffer = TextInputBuffer::new();
+ let theme = Theme::default();
+
+ terminal
+ .draw(|f| {
+ render_single_line_input(
+ f,
+ Rect::new(0, 0, 80, 3),
+ "Enter URL:",
+ &buffer,
+ &theme,
+ false,
+ );
+ })
+ .unwrap();
+ }
+
+ #[test]
+ fn test_render_single_line_input_with_content() {
+ let backend = TestBackend::new(40, 5);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let mut buffer = TextInputBuffer::from_str("https://example.com/playlist.m3u8");
+ buffer.move_home();
+ let theme = Theme::default();
+
+ terminal
+ .draw(|f| {
+ render_single_line_input(
+ f,
+ Rect::new(0, 0, 40, 3),
+ "Enter URL:",
+ &buffer,
+ &theme,
+ true,
+ );
+ })
+ .unwrap();
+ }
+}
diff --git a/src/tui/widgets/mod.rs b/src/tui/widgets/mod.rs
new file mode 100644
index 0000000..7510459
--- /dev/null
+++ b/src/tui/widgets/mod.rs
@@ -0,0 +1,9 @@
+pub mod badge;
+pub mod input;
+pub mod modal;
+pub mod scrollbar;
+
+pub use badge::{MediaTags, extract_media_tags, render_media_tag_spans, resolution_badge_spans};
+pub use input::render_single_line_input;
+pub use modal::{ModalFrame, render_modal_footer};
+pub use scrollbar::render_scrollbar;
diff --git a/src/tui/widgets/modal.rs b/src/tui/widgets/modal.rs
new file mode 100644
index 0000000..c5676ec
--- /dev/null
+++ b/src/tui/widgets/modal.rs
@@ -0,0 +1,101 @@
+use ratatui::{
+ Frame,
+ layout::{Alignment, Rect},
+ style::Style,
+ text::{Line, Span},
+ widgets::{Block, Borders, Paragraph},
+};
+
+use crate::tui::{overlay, theme::Theme};
+
+pub struct ModalFrame<'a> {
+ title: &'a str,
+ theme: &'a Theme,
+ basic_terminal: bool,
+ border_style: Option<Style>,
+}
+
+impl<'a> ModalFrame<'a> {
+ pub fn new(title: &'a str, theme: &'a Theme, basic_terminal: bool) -> Self {
+ Self {
+ title,
+ theme,
+ basic_terminal,
+ border_style: None,
+ }
+ }
+
+ pub fn border_style(mut self, style: Style) -> Self {
+ self.border_style = Some(style);
+ self
+ }
+
+ pub fn render(&self, frame: &mut Frame, area: Rect, full_area: Rect) -> Rect {
+ overlay::clear_modal_area(frame, full_area, area, self.theme);
+ let block = Block::default()
+ .title(format!(" {} ", self.title.trim()))
+ .title_style(self.theme.title)
+ .borders(Borders::ALL)
+ .border_type(overlay::border_type(self.basic_terminal))
+ .border_style(self.border_style.unwrap_or(self.theme.lavender));
+ let inner = block.inner(area);
+ frame.render_widget(block, area);
+ inner
+ }
+}
+
+pub fn render_modal_footer(
+ frame: &mut Frame,
+ area: Rect,
+ spans: Vec<Span<'static>>,
+ theme: &Theme,
+) {
+ let footer = Line::from(spans);
+ frame.render_widget(
+ Paragraph::new(footer).alignment(Alignment::Center).block(
+ Block::default()
+ .borders(Borders::TOP)
+ .border_style(theme.muted),
+ ),
+ area,
+ );
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ratatui::{Terminal, backend::TestBackend};
+
+ #[test]
+ fn test_modal_frame_render() {
+ let backend = TestBackend::new(80, 24);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let theme = Theme::default();
+
+ terminal
+ .draw(|f| {
+ let full = Rect::new(0, 0, 80, 24);
+ let popup = Rect::new(10, 5, 60, 14);
+ let modal = ModalFrame::new("Test Modal", &theme, false);
+ let inner = modal.render(f, popup, full);
+ assert_eq!(inner.width, 58);
+ assert_eq!(inner.height, 12);
+ })
+ .unwrap();
+ }
+
+ #[test]
+ fn test_render_modal_footer() {
+ let backend = TestBackend::new(80, 24);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let theme = Theme::default();
+
+ terminal
+ .draw(|f| {
+ let footer_area = Rect::new(10, 15, 60, 2);
+ let spans = vec![Span::raw("Enter: Save Esc: Cancel")];
+ render_modal_footer(f, footer_area, spans, &theme);
+ })
+ .unwrap();
+ }
+}
diff --git a/src/tui/widgets/scrollbar.rs b/src/tui/widgets/scrollbar.rs
new file mode 100644
index 0000000..eaaa3ce
--- /dev/null
+++ b/src/tui/widgets/scrollbar.rs
@@ -0,0 +1,94 @@
+use ratatui::{
+ Frame,
+ layout::Rect,
+ widgets::{Scrollbar, ScrollbarOrientation, ScrollbarState},
+};
+
+use crate::tui::theme::Theme;
+
+pub fn render_scrollbar(
+ frame: &mut Frame,
+ area: Rect,
+ content_length: usize,
+ viewport_length: usize,
+ position: usize,
+ theme: &Theme,
+ basic_terminal: bool,
+) {
+ if content_length <= viewport_length || viewport_length == 0 {
+ return;
+ }
+
+ let mut scrollbar_state = ScrollbarState::default()
+ .content_length(content_length)
+ .viewport_content_length(viewport_length)
+ .position(position);
+
+ let scrollbar = Scrollbar::default()
+ .orientation(ScrollbarOrientation::VerticalRight)
+ .thumb_style(theme.lavender)
+ .track_style(theme.surface1)
+ .begin_symbol(if basic_terminal {
+ Some("^")
+ } else {
+ Some("▲")
+ })
+ .end_symbol(if basic_terminal {
+ Some("v")
+ } else {
+ Some("▼")
+ })
+ .track_symbol(if basic_terminal {
+ Some("|")
+ } else {
+ Some("│")
+ })
+ .thumb_symbol(if basic_terminal { "|" } else { "█" });
+
+ frame.render_stateful_widget(scrollbar, area, &mut scrollbar_state);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ratatui::{Terminal, backend::TestBackend};
+
+ #[test]
+ fn test_render_scrollbar_hidden_when_content_fits() {
+ let backend = TestBackend::new(80, 10);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let theme = Theme::default();
+
+ terminal
+ .draw(|f| {
+ render_scrollbar(f, Rect::new(0, 0, 80, 10), 5, 10, 0, &theme, false);
+ })
+ .unwrap();
+ }
+
+ #[test]
+ fn test_render_scrollbar_visible_when_overflowing() {
+ let backend = TestBackend::new(80, 10);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let theme = Theme::default();
+
+ terminal
+ .draw(|f| {
+ render_scrollbar(f, Rect::new(0, 0, 80, 10), 50, 10, 12, &theme, false);
+ })
+ .unwrap();
+ }
+
+ #[test]
+ fn test_render_scrollbar_basic_terminal() {
+ let backend = TestBackend::new(80, 10);
+ let mut terminal = Terminal::new(backend).unwrap();
+ let theme = Theme::default();
+
+ terminal
+ .draw(|f| {
+ render_scrollbar(f, Rect::new(0, 0, 80, 10), 50, 10, 12, &theme, true);
+ })
+ .unwrap();
+ }
+}