Commit fde98b5a5b

fde98b5a5b954daa033312309e6e3fc4091797e0

parent: db597a03bc

Unsigned

Siriusmart <71584876+Siriusmart@users.noreply.github.com> · 2022-09-16 19:21 UTC

search filters and search page

Layout: unified · split

Cargo.lock −2
@@ -1511,8 +1511,6 @@ dependencies = [
15111511[[package]]
15121512name = "tui-additions"
15131513version = "0.1.8"
1514source = "registry+https://github.com/rust-lang/crates.io-index"
1515checksum = "2978e90e761ab278f378e954c40e142191178844ca6d05458bcbc0faadd77eba"
15161514dependencies = [
15171515 "crossterm 0.25.0",
15181516 "dyn-clone",
Cargo.toml +2 −2
@@ -19,7 +19,7 @@ crossterm = {version = "0.25", features = ["serde"]}
1919viuer = {version = "0.6", features = ["sixel"]}
2020home = "0.5"
2121chrono = {version = "0.4", default-features = false, features = ["clock"]}
22tui-additions = {version = "0.1", default-features = false, features = ["framework", "widgets"]}
22# tui-additions = {version = "0.1", default-features = false, features = ["framework", "widgets"]}
2323typemap = "0.3"
2424invidious = {version = "0.3", default-features = false, features = ["reqwest"]}
2525serde_yaml = "0.9"
@@ -28,4 +28,4 @@ tokio = "1.21"
2828futures = "0.3"
2929reqwest = "0.11"
3030# serde_json = "1.0"
31# tui-additions = {path = "../../Rust/Packages/tui-additions", default-features = false, features = ["framework", "widgets"]}
31tui-additions = {path = "../../Rust/Packages/tui-additions", default-features = false, features = ["framework", "widgets"]}
README.md +4 −4
@@ -29,7 +29,7 @@ An aesthetically pleasing YouTube TUI written in Rust.
2929>
3030> #### Sixels!
3131>
32> You can now display PNGs in terminal yay! Very slow and lots of delay, trying to get it work multithreaded so that it can still be usable but with no success. If anyone knows how to do that (or just make it faster) please help.
32> You can now display PNGs in terminal yay! Terrible performance, but running with `--release` flag improves a bit.
3333>
3434> #### Code readability
3535>
@@ -40,12 +40,12 @@ An aesthetically pleasing YouTube TUI written in Rust.
4040> #### Done
4141>
4242> - Config files (mostly, more options will be added when I get to that part)
43> - Home page with its basic items
43> - Home and search page
4444>
4545> #### To do before release
4646>
47> - Search filters
48> - All pages (search, video/playlist/channel info)
47> - All pages (video/playlist/channel info)
48> - Watch history
4949> - Basically back to where it is before the rewrite
5050
5151## Overview
src/config/appearance.rs +7
@@ -31,6 +31,8 @@ pub struct ColorsConfig {
3131 pub message_outline: Color,
3232 #[serde(default = "message_error_outline_default")]
3333 pub message_error_outline: Color,
34 #[serde(default = "message_success_outline_default")]
35 pub message_success_outline: Color,
3436 #[serde(default = "error_text_default")]
3537 pub error_text: Color,
3638 #[serde(default)]
@@ -64,6 +66,7 @@ impl Default for ColorsConfig {
6466 outline_secondary: outline_secondary_default(),
6567 message_outline: message_outline_default(),
6668 message_error_outline: message_error_outline_default(),
69 message_success_outline: message_success_outline_default(),
6770 error_text: error_text_default(),
6871 item_info: ItemInfoColors::default(),
6972 }
@@ -127,6 +130,10 @@ fn message_error_outline_default() -> Color {
127130 Color::LightRed
128131}
129132
133fn message_success_outline_default() -> Color {
134 Color::LightGreen
135}
136
130137fn error_text_default() -> Color {
131138 Color::LightRed
132139}
src/config/keybindings.rs +24
@@ -52,6 +52,30 @@ impl Default for KeyBindingsConfig {
5252 q.insert(0, KeyAction::Exit);
5353 map.insert(KeyCode::Char('q'), q);
5454
55 let mut backspace = HashMap::new();
56 backspace.insert(0, KeyAction::Back);
57 map.insert(KeyCode::Backspace, backspace);
58
59 let mut r = HashMap::new();
60 r.insert(2, KeyAction::Reload);
61 map.insert(KeyCode::Char('r'), r);
62
63 let mut h = HashMap::new();
64 h.insert(0, KeyAction::MoveLeft);
65 map.insert(KeyCode::Char('h'), h);
66
67 let mut j = HashMap::new();
68 j.insert(0, KeyAction::MoveDown);
69 map.insert(KeyCode::Char('j'), j);
70
71 let mut k = HashMap::new();
72 k.insert(0, KeyAction::MoveUp);
73 map.insert(KeyCode::Char('k'), k);
74
75 let mut l = HashMap::new();
76 l.insert(0, KeyAction::MoveRight);
77 map.insert(KeyCode::Char('l'), l);
78
5579 Self(map)
5680 }
5781}
src/config/pages.rs +30 −11
@@ -1,5 +1,5 @@
11use super::ConfigTrait;
2use crate::items::{ItemList, MessageBar, PageButton, SearchBar};
2use crate::items::{ItemList, MessageBar, PageButton, SearchBar, SearchFilter};
33use serde::{Deserialize, Serialize};
44use std::slice;
55use tui::layout::Constraint;
@@ -38,6 +38,8 @@ impl Key for MinDimentions {
3838pub struct PagesConfig {
3939 #[serde(default = "main_menu_default")]
4040 pub main_menu: PageConfig,
41 #[serde(default = "search_default")]
42 pub search: PageConfig,
4143}
4244
4345impl Key for PagesConfig {
@@ -52,6 +54,7 @@ impl Default for PagesConfig {
5254 fn default() -> Self {
5355 Self {
5456 main_menu: main_menu_default(),
57 search: search_default(),
5558 }
5659 }
5760}
@@ -152,16 +155,18 @@ pub enum PageItems {
152155 MessageBar,
153156 Trending,
154157 Popular,
158 SearchFilters,
155159}
156160
157161impl PageItems {
158162 pub fn to_framework_item(&self, framework: &mut Framework) -> Box<dyn FrameworkItem> {
159163 match *self {
160 PageItems::SearchBar => Box::new(SearchBar::default()),
161 PageItems::Popular => Box::new(PageButton::Popular),
162 PageItems::Trending => Box::new(PageButton::Trending),
163 PageItems::MessageBar => Box::new(MessageBar::default()),
164 PageItems::ItemList => Box::new(ItemList::new(framework)),
164 Self::SearchBar => Box::new(SearchBar::default()),
165 Self::Popular => Box::new(PageButton::Popular),
166 Self::Trending => Box::new(PageButton::Trending),
167 Self::MessageBar => Box::new(MessageBar::default()),
168 Self::ItemList => Box::new(ItemList::new(framework)),
169 Self::SearchFilters => Box::new(SearchFilter::default()),
165170 }
166171 }
167172
@@ -170,15 +175,18 @@ impl PageItems {
170175 Self::Popular | Self::Trending => Constraint::Length(15),
171176 Self::SearchBar => Constraint::Min(16),
172177 Self::MessageBar => Constraint::Min(3),
173 Self::ItemList => Constraint::Min(6),
178 Self::ItemList => Constraint::Min(9),
179 Self::SearchFilters => Constraint::Length(5),
174180 }
175181 }
176182
177183 pub fn height(&self) -> Constraint {
178184 match self {
179 Self::Popular | Self::Trending | Self::MessageBar | Self::SearchBar => {
180 Constraint::Length(3)
181 }
185 Self::Popular
186 | Self::Trending
187 | Self::MessageBar
188 | Self::SearchBar
189 | Self::SearchFilters => Constraint::Length(3),
182190 Self::ItemList => Constraint::Min(6),
183191 }
184192 }
@@ -211,7 +219,7 @@ fn max_constraint(constraints: &[Constraint]) -> Constraint {
211219fn main_menu_default() -> PageConfig {
212220 PageConfig {
213221 layout: vec![
214 PageRow::from_vec(vec![PageItems::SearchBar], false),
222 PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
215223 PageRow::from_vec(vec![PageItems::Trending, PageItems::Popular], true),
216224 PageRow::from_vec(vec![PageItems::ItemList], false),
217225 PageRow::from_vec(vec![PageItems::MessageBar], false),
@@ -219,3 +227,14 @@ fn main_menu_default() -> PageConfig {
219227 message: String::from("Loading main menu..."),
220228 }
221229}
230
231fn search_default() -> PageConfig {
232 PageConfig {
233 layout: vec![
234 PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
235 PageRow::from_vec(vec![PageItems::ItemList], false),
236 PageRow::from_vec(vec![PageItems::MessageBar], false),
237 ],
238 message: String::from("Loading search results..."),
239 }
240}
src/config/search.rs +227 −1
@@ -1,5 +1,9 @@
1use crate::{config::ConfigTrait, global::traits::asurlstring::AsUrlString};
1use crate::{
2 config::ConfigTrait,
3 global::{message::Message, traits::asurlstring::AsUrlString},
4};
25use serde::{Deserialize, Serialize};
6use tui_additions::framework::FrameworkClean;
37use typemap::Key;
48
59// can be turned into URL Params for the search term with filters
@@ -40,6 +44,53 @@ pub struct SearchFilters {
4044 pub r#type: SearchFilterType,
4145}
4246
47impl SearchFilters {
48 pub fn get_all() -> [(&'static str, Vec<&'static str>); 5] {
49 [
50 (SearchFilterSort::NAME, SearchFilterSort::ordering()),
51 (SearchFilterDate::NAME, SearchFilterDate::ordering()),
52 (SearchFilterDuration::NAME, SearchFilterDuration::ordering()),
53 (SearchFilterType::NAME, SearchFilterType::ordering()),
54 ("Reset filters", vec!["Are you sure?"]),
55 ]
56 }
57
58 pub fn get_selected(&self, index: usize) -> usize {
59 match index {
60 0 => self.sort.selected_index(),
61 1 => self.date.selected_index(),
62 2 => self.duration.selected_index(),
63 3 => self.r#type.selected_index(),
64 4 => 0,
65 _ => unreachable!(),
66 }
67 }
68
69 pub fn set_index(&mut self, index_at: usize, set_index: usize, message: &mut Message) {
70 // panic!("function ran");
71 match index_at {
72 0 => self.sort = SearchFilterSort::at_index(set_index),
73 1 => self.date = SearchFilterDate::at_index(set_index),
74 2 => self.duration = SearchFilterDuration::at_index(set_index),
75 3 => self.r#type = SearchFilterType::at_index(set_index),
76 4 => {
77 if set_index == 0 {
78 self.reset(message)
79 } else {
80 unreachable!()
81 }
82 }
83 _ => unreachable!(),
84 }
85 }
86
87 pub fn reset(&mut self, message: &mut Message) {
88 *self = Self::default();
89
90 *message = Message::Success(String::from("Search filters has been reset"));
91 }
92}
93
4394#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
4495pub enum SearchFilterSort {
4596 Relevance,
@@ -159,3 +210,178 @@ impl AsUrlString for SearchFilterDuration {
159210impl AsUrlString for SearchFilterType {
160211 const TAG: &'static str = "type";
161212}
213
214pub trait SearchFilterItem
215where
216 Self: Sized,
217{
218 const NAME: &'static str;
219
220 fn option_name(&self) -> &'static str;
221 fn ordering() -> Vec<&'static str>;
222 fn selected_index(&self) -> usize;
223 fn at_index(index: usize) -> Self;
224}
225
226const SORT_ORDERING: [SearchFilterSort; 4] = [
227 SearchFilterSort::Relevance,
228 SearchFilterSort::Rating,
229 SearchFilterSort::Date,
230 SearchFilterSort::Views,
231];
232const DATE_ORDERING: [SearchFilterDate; 6] = [
233 SearchFilterDate::None,
234 SearchFilterDate::Hour,
235 SearchFilterDate::Day,
236 SearchFilterDate::Week,
237 SearchFilterDate::Month,
238 SearchFilterDate::Year,
239];
240const DURATION_ORDERING: [SearchFilterDuration; 4] = [
241 SearchFilterDuration::None,
242 SearchFilterDuration::Short,
243 SearchFilterDuration::Medium,
244 SearchFilterDuration::Long,
245];
246const TYPE_ORDERING: [SearchFilterType; 4] = [
247 SearchFilterType::All,
248 SearchFilterType::Video,
249 SearchFilterType::Channel,
250 SearchFilterType::Playlist,
251];
252
253impl SearchFilterItem for SearchFilterSort {
254 const NAME: &'static str = "Sort by";
255
256 fn option_name(&self) -> &'static str {
257 match self {
258 Self::Relevance => "Relevance",
259 Self::Rating => "Rating",
260 Self::Date => "Upload date",
261 Self::Views => "View count",
262 }
263 }
264
265 fn ordering() -> Vec<&'static str> {
266 SORT_ORDERING
267 .iter()
268 .map(|item| item.option_name())
269 .collect::<Vec<_>>()
270 }
271
272 fn selected_index(&self) -> usize {
273 match self {
274 Self::Relevance => 0,
275 Self::Rating => 1,
276 Self::Date => 2,
277 Self::Views => 3,
278 }
279 }
280
281 fn at_index(index: usize) -> Self {
282 SORT_ORDERING[index]
283 }
284}
285
286impl SearchFilterItem for SearchFilterDate {
287 const NAME: &'static str = "Upload date";
288
289 fn option_name(&self) -> &'static str {
290 match self {
291 Self::None => "Any date",
292 Self::Hour => "Last hour",
293 Self::Day => "Today",
294 Self::Week => "This week",
295 Self::Month => "This month",
296 Self::Year => "This year",
297 }
298 }
299
300 fn ordering() -> Vec<&'static str> {
301 DATE_ORDERING
302 .iter()
303 .map(|item| item.option_name())
304 .collect::<Vec<_>>()
305 }
306
307 fn selected_index(&self) -> usize {
308 match self {
309 Self::None => 0,
310 Self::Hour => 1,
311 Self::Day => 2,
312 Self::Week => 3,
313 Self::Month => 4,
314 Self::Year => 5,
315 }
316 }
317
318 fn at_index(index: usize) -> Self {
319 DATE_ORDERING[index]
320 }
321}
322
323impl SearchFilterItem for SearchFilterDuration {
324 const NAME: &'static str = "Duration";
325
326 fn option_name(&self) -> &'static str {
327 match self {
328 Self::None => "Any duration",
329 Self::Short => "Short (< 4 minutes)",
330 Self::Medium => "Medium (4 - 20 minutes)",
331 Self::Long => "Long (> 20 minutes)",
332 }
333 }
334
335 fn ordering() -> Vec<&'static str> {
336 DURATION_ORDERING
337 .iter()
338 .map(|item| item.option_name())
339 .collect::<Vec<_>>()
340 }
341
342 fn selected_index(&self) -> usize {
343 match self {
344 Self::None => 0,
345 Self::Short => 1,
346 Self::Medium => 2,
347 Self::Long => 3,
348 }
349 }
350
351 fn at_index(index: usize) -> Self {
352 DURATION_ORDERING[index]
353 }
354}
355
356impl SearchFilterItem for SearchFilterType {
357 const NAME: &'static str = "Type";
358
359 fn option_name(&self) -> &'static str {
360 match self {
361 Self::All => "Any type",
362 Self::Video => "Video",
363 Self::Channel => "Channel",
364 Self::Playlist => "Playlist",
365 }
366 }
367
368 fn ordering() -> Vec<&'static str> {
369 TYPE_ORDERING
370 .iter()
371 .map(|item| item.option_name())
372 .collect::<Vec<_>>()
373 }
374
375 fn selected_index(&self) -> usize {
376 match self {
377 Self::All => 0,
378 Self::Video => 1,
379 Self::Channel => 2,
380 Self::Playlist => 3,
381 }
382 }
383
384 fn at_index(index: usize) -> Self {
385 TYPE_ORDERING[index]
386 }
387}
src/global/functions/mod.rs +2
@@ -6,3 +6,5 @@ mod date_text;
66pub use date_text::date_text;
77mod download_all_images;
88pub use download_all_images::download_all_images;
9mod popup_area;
10pub use popup_area::popup_area;
src/global/functions/popup_area.rs added +48
@@ -0,0 +1,48 @@
1use tui::layout::Rect;
2
3pub fn popup_area(
4 (max_width_percentage, max_height_percentage): (u16, u16),
5 (min_width_length, min_height_length): (u16, u16),
6 area: Rect,
7) -> Result<Rect, Rect> {
8 let mut success = true;
9
10 let (width, x) = {
11 if min_width_length >= area.width {
12 success = false;
13 (area.width, 0)
14 } else {
15 let mut width = area.width * max_width_percentage / 100;
16 if width < min_width_length {
17 width = min_width_length;
18 }
19 (width, (area.width - width) / 2)
20 }
21 };
22
23 let (height, y) = {
24 if min_height_length >= area.height {
25 success = false;
26 (area.height, 0)
27 } else {
28 let mut height = area.height * max_height_percentage / 100;
29 if height < min_height_length {
30 height = min_height_length;
31 }
32 (height, (area.height - height) / 2)
33 }
34 };
35
36 let rect = Rect {
37 x,
38 y,
39 width,
40 height,
41 };
42
43 if success {
44 Ok(rect)
45 } else {
46 Err(rect)
47 }
48}
src/global/functions/viewcount_text.rs +1 −1
@@ -13,5 +13,5 @@ pub fn viewcount_text(views: u64) -> String {
1313 }
1414 }
1515
16 unreachable!()
16 String::from("No views")
1717}
src/global/keyaction.rs +2
@@ -10,4 +10,6 @@ pub enum KeyAction {
1010 Select,
1111 Deselect,
1212 Exit,
13 Back,
14 Reload,
1315}
src/global/message.rs +3 −3
@@ -5,6 +5,7 @@ use typemap::Key;
55pub enum Message {
66 Message(String),
77 Error(String),
8 Success(String),
89 None,
910}
1011
@@ -16,9 +17,8 @@ impl Message {
1617 // to_string is used by the message bar to convert Message to string
1718 pub fn to_string(&self, default: &str) -> String {
1819 match self {
19 Message::Message(msg) => msg.to_string(),
20 Message::Error(msg) => msg.to_string(),
21 Message::None => default.to_string(),
20 Self::Message(msg) | Self::Error(msg) | Self::Success(msg) => msg.to_string(),
21 Self::None => default.to_string(),
2222 }
2323 }
2424}
src/global/mod.rs +1
@@ -4,6 +4,7 @@ pub mod item;
44pub mod keyaction;
55pub mod message;
66pub mod page;
7pub mod status;
78pub mod tasks;
89
910pub mod functions;
src/global/page.rs +2 −2
@@ -37,7 +37,7 @@ impl Page {
3737 let pages_config = framework.data.global.get::<PagesConfig>().unwrap();
3838 match self {
3939 Self::MainMenu(_) => pages_config.main_menu.clone(),
40 Self::Search(_) => todo!(),
40 Self::Search(_) => pages_config.search.clone(),
4141 }
4242 }
4343
@@ -46,7 +46,7 @@ impl Page {
4646 let pages_config = framework.data.global.get::<PagesConfig>().unwrap();
4747 match self {
4848 Self::MainMenu(_) => pages_config.main_menu.message.clone(),
49 Self::Search(_) => todo!(),
49 Self::Search(_) => pages_config.main_menu.message.clone(),
5050 }
5151 }
5252}
src/global/status.rs added +24
@@ -0,0 +1,24 @@
1use typemap::Key;
2
3#[derive(Clone)]
4pub struct Status {
5 pub popup_opened: bool,
6}
7
8impl Key for Status {
9 type Value = Self;
10}
11
12impl Default for Status {
13 fn default() -> Self {
14 Self {
15 popup_opened: false,
16 }
17 }
18}
19
20impl Status {
21 pub fn reset(&mut self) {
22 *self = Self::default();
23 }
24}
src/global/tasks.rs +64 −33
@@ -1,6 +1,6 @@
11use crate::config::{AppearanceConfig, MinDimentions};
22
3use super::{message::Message, page::Page};
3use super::{message::Message, page::Page, status::Status};
44use std::{error::Error, io::Stdout, mem};
55use tui::{
66 backend::CrosstermBackend, layout::Alignment, style::Style, widgets::Paragraph, Frame, Terminal,
@@ -14,6 +14,7 @@ pub enum Task {
1414 Reload,
1515 RenderOnly(usize, usize),
1616 LoadPage(Page),
17 ClearPage,
1718}
1819
1920#[derive(Clone, PartialEq, Eq)]
@@ -21,6 +22,7 @@ pub struct TaskQueue {
2122 pub render: RenderTask,
2223 pub reload: bool,
2324 pub load_page: Option<Page>,
25 pub clear_all: bool,
2426}
2527
2628impl Default for TaskQueue {
@@ -29,6 +31,7 @@ impl Default for TaskQueue {
2931 render: RenderTask::None,
3032 reload: false,
3133 load_page: None,
34 clear_all: false,
3235 }
3336 }
3437}
@@ -50,6 +53,7 @@ impl TaskQueue {
5053 _ => return,
5154 },
5255 Task::LoadPage(page) => self.load_page = Some(page),
56 Task::ClearPage => self.clear_all = true,
5357 // _ => {}
5458 }
5559 }
@@ -64,6 +68,10 @@ impl TaskQueue {
6468 framework: &mut Framework,
6569 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
6670 ) -> Result<(), Box<dyn Error>> {
71 if self.clear_all {
72 terminal.clear()?;
73 }
74
6775 match self.render {
6876 RenderTask::All => {
6977 Self::render(framework, terminal)?;
@@ -79,8 +87,9 @@ impl TaskQueue {
7987 // reload simply runs `.load()` on all items
8088 *framework.data.global.get_mut::<Message>().unwrap() =
8189 Message::Message(String::from("Reloading page..."));
82 Self::render(framework, terminal)?;
83 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load() {
90 Self::render_force_clear(framework, terminal)?;
91 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
92 {
8493 Message::Error(format!("{}", e))
8594 } else {
8695 Message::None
@@ -100,12 +109,14 @@ impl TaskQueue {
100109
101110 let state = page_config.to_state(framework);
102111 framework.set_state(state);
112 framework.data.state.get_mut::<Status>().unwrap().reset();
103113 *framework.data.state.get_mut::<Page>().unwrap() = page;
104 Self::render(framework, terminal)?;
114 Self::render_force_clear(framework, terminal)?;
105115 *framework.data.global.get_mut::<Message>().unwrap() = Message::None;
106116
107117 framework.cursor = CursorState::default();
108 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load() {
118 *framework.data.global.get_mut::<Message>().unwrap() = if let Err(e) = framework.load()
119 {
109120 Message::Error(format!("{}", e))
110121 } else {
111122 Message::None
@@ -121,39 +132,59 @@ impl TaskQueue {
121132 framework: &mut Framework,
122133 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
123134 ) -> Result<(), Box<dyn Error>> {
124 terminal.draw(|frame: &mut Frame<CrosstermBackend<Stdout>>| {
125 let min_dimentions = framework.data.state.get::<MinDimentions>().unwrap();
126 let area = frame.size();
127
128 // if the minimum width and height is not meet, then displays a "protective screen" to prevent panicking
129 if area.width < min_dimentions.width || area.height < min_dimentions.height {
130 let paragraph = Paragraph::new(format!(
131 "{}Current: {} x {}\nRequired: {} x {}",
132 "\n".repeat(area.height as usize / 2 - 1),
133 area.width,
134 area.height,
135 min_dimentions.width,
136 min_dimentions.height
137 ))
138 .alignment(Alignment::Center)
139 .style(
140 Style::default().fg(framework
141 .data
142 .global
143 .get::<AppearanceConfig>()
144 .unwrap()
145 .colors
146 .error_text),
147 );
148 frame.render_widget(paragraph, area);
149 return;
150 }
135 terminal.draw(|frame| {
136 Self::render_with_frame(framework, frame);
137 })?;
138
139 Ok(())
140 }
151141
152 framework.render(frame);
142 // this function force clears the terminal before rendering, removing sixels and halfblock images
143 pub fn render_force_clear(
144 framework: &mut Framework,
145 terminal: &mut Terminal<CrosstermBackend<Stdout>>,
146 ) -> Result<(), Box<dyn Error>> {
147 terminal.clear()?;
148 terminal.draw(|frame| {
149 Self::render_with_frame(framework, frame);
153150 })?;
154151
155152 Ok(())
156153 }
154
155 pub fn render_with_frame(
156 framework: &mut Framework,
157 frame: &mut Frame<CrosstermBackend<Stdout>>,
158 ) {
159 let min_dimentions = framework.data.state.get::<MinDimentions>().unwrap();
160 let area = frame.size();
161
162 // if the minimum width and height is not meet, then displays a "protective screen" to prevent panicking
163 if area.width < min_dimentions.width || area.height < min_dimentions.height {
164 let paragraph = Paragraph::new(format!(
165 "{}Current: {} x {}\nRequired: {} x {}",
166 "\n".repeat(area.height as usize / 2 - 1),
167 area.width,
168 area.height,
169 min_dimentions.width,
170 min_dimentions.height
171 ))
172 .alignment(Alignment::Center)
173 .style(
174 Style::default().fg(framework
175 .data
176 .global
177 .get::<AppearanceConfig>()
178 .unwrap()
179 .colors
180 .error_text),
181 );
182 frame.render_widget(paragraph, area);
183 return;
184 }
185
186 framework.render(frame);
187 }
157188}
158189
159190#[derive(Clone, PartialEq, Eq, Debug)]
src/init.rs +5 −1
@@ -3,7 +3,10 @@ use crate::{
33 AppearanceConfig, AppearanceConfigSerde, ConfigTrait, KeyBindingsConfig, MainConfig,
44 MinDimentions, PagesConfig, Search,
55 },
6 global::{invidiousclient::InvidiousClient, message::Message, page::Page, tasks::Tasks},
6 global::{
7 invidiousclient::InvidiousClient, message::Message, page::Page, status::Status,
8 tasks::Tasks,
9 },
710};
811use home::home_dir;
912use std::{error::Error, fs};
@@ -57,6 +60,7 @@ pub fn init(framework: &mut Framework) -> Result<(), Box<dyn Error>> {
5760 .data
5861 .state
5962 .insert::<MinDimentions>(MinDimentions::default());
63 framework.data.state.insert::<Status>(Status::default());
6064
6165 Ok(())
6266}
src/items/iteminfo.rs +20 −13
@@ -8,7 +8,7 @@ use viuer::{print_from_file, Config};
88
99use crate::{
1010 config::{AppearanceConfig, MainConfig},
11 global::item::Item,
11 global::{item::Item, status::Status},
1212};
1313
1414// an item info displays info of any `Item`s
@@ -40,7 +40,9 @@ impl FrameworkItem for ItemInfo {
4040 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
4141
4242 // The scroll (space above) text info will be the height of the image, but if the image fail to display, the scroll will be 0
43 let scroll = if main_config.images.display() {
43 let scroll = if main_config.images.display()
44 && !framework.data.state.get::<Status>().unwrap().popup_opened
45 {
4446 let thumbnail_path = home::home_dir()
4547 .unwrap()
4648 .join(".cache/youtube-tui/thumbnails/")
@@ -99,16 +101,19 @@ impl FrameworkItem for ItemInfo {
99101 Style::default().fg(appearance.colors.item_info.viewcount),
100102 ));
101103 }
102 out.0.extend(vec![
103 (
104 format!("Length: {}", minivideo.length),
105 Style::default().fg(appearance.colors.item_info.length),
106 ),
107 (
108 format!("Published {}", minivideo.published),
109 Style::default().fg(appearance.colors.item_info.published),
110 )
111 ].into_iter());
104 out.0.extend(
105 vec![
106 (
107 format!("Length: {}", minivideo.length),
108 Style::default().fg(appearance.colors.item_info.length),
109 ),
110 (
111 format!("Published {}", minivideo.published),
112 Style::default().fg(appearance.colors.item_info.published),
113 ),
114 ]
115 .into_iter(),
116 );
112117 out
113118 }
114119 };
@@ -139,7 +144,9 @@ impl FrameworkItem for ItemInfo {
139144 if text.len() == 0 {
140145 return;
141146 }
142 let paragraph = Paragraph::new(format!("Description:\n{}", text)).style(style).wrap(Wrap { trim: true });
147 let paragraph = Paragraph::new(format!("Description:\n{}", text))
148 .style(style)
149 .wrap(Wrap { trim: true });
143150 frame.render_widget(
144151 paragraph,
145152 Rect {
src/items/itemlist.rs +25 −21
@@ -34,24 +34,7 @@ impl ItemList {
3434 Self {
3535 info: ItemInfo::default(),
3636 items: Vec::new(),
37 textlist: TextList::default()
38 .border_type(
39 framework
40 .data
41 .global
42 .get::<AppearanceConfig>()
43 .unwrap()
44 .borders,
45 )
46 .ascii_only(
47 !framework
48 .data
49 .global
50 .get::<MainConfig>()
51 .unwrap()
52 .allow_unicode,
53 )
54 .non_ascii_replace(' '),
37 textlist: TextList::default().non_ascii_replace(' '),
5538 grid: Grid::new(
5639 vec![Constraint::Percentage(60), Constraint::Percentage(40)],
5740 vec![Constraint::Percentage(100)],
@@ -77,7 +60,6 @@ impl FrameworkItem for ItemList {
7760 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
7861
7962 // creates the grid
80 self.grid.set_border_type(appearance.borders);
8163 self.grid
8264 .set_border_style(Style::default().fg(if info.hover {
8365 appearance.colors.outline_hover
@@ -118,6 +100,19 @@ impl FrameworkItem for ItemList {
118100 framework: &mut tui_additions::framework::FrameworkClean,
119101 _info: tui_additions::framework::ItemInfo,
120102 ) -> Result<(), Box<dyn Error>> {
103 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
104
105 self.grid.set_border_type(appearance.borders);
106 self.textlist.set_border_type(appearance.borders);
107 self.textlist.set_ascii_only(
108 !framework
109 .data
110 .global
111 .get::<MainConfig>()
112 .unwrap()
113 .allow_unicode,
114 );
115
121116 let page = framework.data.state.get::<Page>().unwrap();
122117 let image_index = framework
123118 .data
@@ -155,8 +150,17 @@ impl FrameworkItem for ItemList {
155150 }
156151 }
157152
158 // download thumbnails of all videos in the list
159 download_all_images(self.items.iter().map(|item| item.into()).collect());
153 if framework
154 .data
155 .global
156 .get::<MainConfig>()
157 .unwrap()
158 .images
159 .display()
160 {
161 // download thumbnails of all videos in the list
162 download_all_images(self.items.iter().map(|item| item.into()).collect());
163 }
160164
161165 // update the items in text list
162166 self.textlist.set_items(&self.items).unwrap();
src/items/messagebar.rs +1
@@ -32,6 +32,7 @@ impl FrameworkItem for MessageBar {
3232 .border_type(appearance.borders)
3333 .border_style(Style::default().fg(match message {
3434 Message::None => appearance.colors.outline,
35 Message::Success(_) => appearance.colors.message_success_outline,
3536 Message::Error(_) => appearance.colors.message_error_outline,
3637 Message::Message(_) => appearance.colors.message_outline,
3738 }));
src/items/mod.rs +2
@@ -8,3 +8,5 @@ mod itemlist;
88pub use itemlist::*;
99mod pagebutton;
1010pub use pagebutton::*;
11mod searchfilters;
12pub use searchfilters::*;
src/items/searchbar.rs +2 −1
@@ -86,8 +86,9 @@ impl FrameworkItem for SearchBar {
8686 KeyCode::Right => self.text_field.right().is_ok(),
8787 KeyCode::Left => self.text_field.left().is_ok(),
8888 KeyCode::Enter => {
89 let mut search = framework.data.state.get::<Search>().unwrap().clone();
89 let mut search = framework.data.state.get_mut::<Search>().unwrap();
9090 search.query = self.text_field.content.clone();
91 let search = search.clone();
9192 let tasks = framework.data.state.get_mut::<Tasks>().unwrap();
9293 tasks.priority.push(Task::LoadPage(Page::Search(search)));
9394 false
src/items/searchfilters.rs added +292
@@ -0,0 +1,292 @@
1use std::array::IntoIter;
2
3use crate::{
4 config::{AppearanceConfig, KeyBindingsConfig, Search, SearchFilters},
5 global::{
6 functions::popup_area,
7 keyaction::KeyAction,
8 message::Message,
9 status::Status,
10 tasks::{Task, Tasks},
11 },
12};
13use tui::{
14 layout::{Alignment, Constraint},
15 style::Style,
16 widgets::{Block, Borders, Clear, Paragraph},
17};
18use tui_additions::{
19 framework::{FrameworkClean, FrameworkItem},
20 widgets::{Grid, TextList},
21};
22
23const POPUP_MIN_WIDTH: u16 = 22;
24const POPUP_MIN_HEIGHT: u16 = 9;
25const POPUP_WIDTH_PERCENTAGE: u16 = 70;
26const POPOUP_HEIGHT_PERCENTAGE: u16 = 70;
27
28#[derive(Clone)]
29pub struct SearchFilter {
30 pub left_textlist: TextList,
31 pub right_textlist: TextList,
32 pub right_options: Vec<Vec<&'static str>>,
33 pub left_options: Vec<&'static str>,
34 pub current_hover: bool,
35 pub grid: Grid,
36}
37
38impl Default for SearchFilter {
39 fn default() -> Self {
40 Self {
41 left_textlist: TextList::default(),
42 right_textlist: TextList::default(),
43 right_options: Vec::new(),
44 left_options: Vec::new(),
45 // false = left, true = right
46 current_hover: false,
47 grid: Grid::new(
48 vec![Constraint::Percentage(50), Constraint::Percentage(50)],
49 vec![Constraint::Percentage(100)],
50 )
51 .unwrap(),
52 }
53 }
54}
55
56impl SearchFilter {
57 pub fn update(&mut self, framework: &FrameworkClean) {
58 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
59 if self.current_hover {
60 self.left_textlist
61 .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
62 self.right_textlist
63 .set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
64 } else {
65 self.right_textlist
66 .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
67 self.left_textlist
68 .set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
69 }
70
71 self.right_textlist.selected = framework
72 .data
73 .state
74 .get::<Search>()
75 .unwrap()
76 .filters
77 .get_selected(self.left_textlist.selected);
78 self.right_textlist
79 .set_items(&self.right_options[self.left_textlist.selected])
80 .unwrap();
81 }
82}
83
84impl FrameworkItem for SearchFilter {
85 fn render(
86 &mut self,
87 frame: &mut tui::Frame<tui::backend::CrosstermBackend<std::io::Stdout>>,
88 framework: &mut tui_additions::framework::FrameworkClean,
89 area: tui::layout::Rect,
90 popup_render: bool,
91 info: tui_additions::framework::ItemInfo,
92 ) {
93 if popup_render && info.selected {
94 let frame_area = frame.size();
95 let (area, success) = match popup_area(
96 (POPUP_WIDTH_PERCENTAGE, POPOUP_HEIGHT_PERCENTAGE),
97 (POPUP_MIN_WIDTH, POPUP_MIN_HEIGHT),
98 frame_area,
99 ) {
100 Ok(area) => (area, true),
101 Err(area) => (area, false),
102 };
103
104 frame.render_widget(Clear, area);
105
106 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
107
108 if !success {
109 let block = Block::default()
110 .borders(Borders::ALL)
111 .border_type(appearance.borders)
112 .border_style(Style::default().fg(appearance.colors.outline_selected));
113
114 let paragraph = Paragraph::new(format!(
115 "{}Current: {}x{}\nRequired: {}x{}",
116 "\n".repeat(frame_area.height as usize / 2 - 1),
117 frame_area.width,
118 frame_area.height,
119 POPUP_MIN_WIDTH,
120 POPUP_MIN_HEIGHT,
121 ))
122 .alignment(Alignment::Center)
123 .style(Style::default().fg(appearance.colors.error_text))
124 .block(block);
125
126 frame.render_widget(paragraph, area);
127
128 return;
129 }
130
131 let chunks = self.grid.chunks(area).unwrap().remove(0);
132
133 frame.render_widget(self.grid.clone(), area);
134
135 self.right_textlist.selected = framework
136 .data
137 .state
138 .get::<Search>()
139 .unwrap()
140 .filters
141 .get_selected(self.left_textlist.selected);
142
143 self.left_textlist.set_height(chunks[0].height);
144 frame.render_widget(self.left_textlist.clone(), chunks[0]);
145
146 self.right_textlist.set_height(chunks[1].height);
147 frame.render_widget(self.right_textlist.clone(), chunks[1]);
148 } else if !popup_render {
149 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
150
151 let block = Block::default()
152 .borders(Borders::ALL)
153 .border_type(appearance.borders)
154 .border_style(Style::default().fg(if info.hover {
155 appearance.colors.outline_hover
156 } else if info.selected {
157 appearance.colors.outline_secondary
158 } else {
159 appearance.colors.outline
160 }));
161
162 let button = Paragraph::new("...").block(block);
163
164 frame.render_widget(button, area);
165 }
166 }
167
168 fn load_item(
169 &mut self,
170 framework: &mut tui_additions::framework::FrameworkClean,
171 _info: tui_additions::framework::ItemInfo,
172 ) -> Result<(), Box<dyn std::error::Error>> {
173 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
174 (self.left_options, self.right_options) = SearchFilters::get_all().into_iter().unzip();
175 self.left_textlist.set_border_type(appearance.borders);
176 self.right_textlist.set_border_type(appearance.borders);
177 self.grid.set_border_type(appearance.borders);
178
179 self.update(&framework);
180
181 self.left_textlist.set_items(&self.left_options)?;
182 self.right_textlist
183 .set_items(&self.right_options[self.left_textlist.selected])?;
184 self.grid
185 .set_border_style(Style::default().fg(appearance.colors.outline_selected));
186
187 Ok(())
188 }
189
190 fn select(&mut self, framework: &mut tui_additions::framework::FrameworkClean) -> bool {
191 framework
192 .data
193 .state
194 .get_mut::<Status>()
195 .unwrap()
196 .popup_opened = true;
197 framework
198 .data
199 .state
200 .get_mut::<Tasks>()
201 .unwrap()
202 .priority
203 .push(Task::ClearPage);
204 self.update(framework);
205 true
206 }
207
208 fn deselect(&mut self, framework: &mut tui_additions::framework::FrameworkClean) -> bool {
209 framework
210 .data
211 .state
212 .get_mut::<Status>()
213 .unwrap()
214 .popup_opened = false;
215 true
216 }
217
218 fn key_event(
219 &mut self,
220 framework: &mut tui_additions::framework::FrameworkClean,
221 key: crossterm::event::KeyEvent,
222 _info: tui_additions::framework::ItemInfo,
223 ) -> Result<(), Box<dyn std::error::Error>> {
224 let action = if let Some(keyactions) = framework
225 .data
226 .global
227 .get::<KeyBindingsConfig>()
228 .unwrap()
229 .0
230 .get(&key.code)
231 {
232 if let Some(action) = keyactions.get(&key.modifiers.bits()) {
233 *action
234 } else {
235 return Ok(());
236 }
237 } else {
238 return Ok(());
239 };
240
241 let hovered_textlist = if self.current_hover {
242 &mut self.right_textlist
243 } else {
244 &mut self.left_textlist
245 };
246
247 let current_hover_before = self.current_hover;
248
249 let updated = match action {
250 KeyAction::Select => {
251 self.current_hover = !self.current_hover;
252 true
253 }
254 KeyAction::MoveUp => hovered_textlist.up().is_ok(),
255 KeyAction::MoveDown => hovered_textlist.down().is_ok(),
256 KeyAction::MoveLeft => hovered_textlist.first().is_ok(),
257 KeyAction::MoveRight => hovered_textlist.last().is_ok(),
258 _ => false,
259 };
260
261 if updated {
262 framework
263 .data
264 .state
265 .get_mut::<Tasks>()
266 .unwrap()
267 .priority
268 .push(Task::RenderAll);
269
270 if current_hover_before {
271 framework
272 .data
273 .state
274 .get_mut::<Search>()
275 .unwrap()
276 .filters
277 .set_index(
278 self.left_textlist.selected,
279 self.right_textlist.selected,
280 framework.data.global.get_mut::<Message>().unwrap(),
281 );
282 } else {
283 self.right_textlist
284 .set_items(&self.right_options[self.left_textlist.selected])?;
285 }
286 }
287
288 self.update(framework);
289
290 Ok(())
291 }
292}
src/run.rs +8
@@ -82,6 +82,14 @@ pub fn run(
8282 KeyAction::MoveDown => framework.r#move(FrameworkDirection::Down)?,
8383 KeyAction::MoveLeft => framework.r#move(FrameworkDirection::Left)?,
8484 KeyAction::MoveRight => framework.r#move(FrameworkDirection::Right)?,
85 KeyAction::Back => {
86 if framework.revert_last_history().is_err() {
87 *framework.data.global.get_mut::<Message>().unwrap() =
88 Message::Error(String::from(
89 "This is already the beginning of history",
90 ))
91 }
92 }
8593 KeyAction::Select => {
8694 let _ = framework.select();
8795 }