src/app/pages/main_menu.rs

2737f153106b44565bbbab1d0b08ab3067071283
youtube-tui/src/app/pages/main_menu.rs history · blame · raw

351 lines · 12068 bytes

  1use std::{collections::LinkedList, error::Error, fs};
  2
  3use crate::{
  4    app::{
  5        app::App,
  6        pages::{global::*, item_info::*},
  7    },
  8    functions::download_all_thumbnails,
  9    structs::{Item, ListItem, Page, Row, RowItem},
 10    traits::{KeyInput, LoadItem, SelectItem},
 11    widgets::{horizontal_split::HorizontalSplit, item_display::ItemDisplay, text_list::TextList},
 12};
 13use crossterm::event::KeyCode;
 14use tui::{
 15    backend::Backend,
 16    layout::{Alignment, Constraint, Rect},
 17    style::{Color, Style},
 18    widgets::{Block, BorderType, Borders, Paragraph},
 19    Frame,
 20};
 21#[derive(Debug, Clone)]
 22pub enum MainMenuItem {
 23    SeletorTab(MainMenuSelector),
 24    VideoList(Option<(LinkedList<ListItem>, TextList, Option<usize>)>), // Videos, List, page
 25}
 26
 27// app.client.trending(None)
 28
 29impl SelectItem for MainMenuItem {
 30    fn select(&mut self, mut app: App) -> (App, bool) {
 31        let selected = match self {
 32            MainMenuItem::SeletorTab(selector) => {
 33                if app.page == (Page::MainMenu(*selector)) {
 34                    return (app, false);
 35                }
 36                app.page = Page::MainMenu(*selector);
 37                app.load = true;
 38                false
 39            }
 40
 41            _ => true,
 42        };
 43
 44        (app, selected)
 45    }
 46
 47    fn selectable(&self) -> bool {
 48        true
 49    }
 50}
 51
 52impl KeyInput for MainMenuItem {
 53    fn key_input(&mut self, key: KeyCode, app: App) -> (bool, App) {
 54        match self {
 55            MainMenuItem::VideoList(Some((video_list, list, _))) => match key {
 56                KeyCode::Up => list.up(),
 57                KeyCode::Down => list.down(),
 58                KeyCode::PageUp => list.selected = 0,
 59                KeyCode::PageDown => list.selected = list.items.len() - 1,
 60                KeyCode::Enter => {
 61                    let state = ItemInfo::default();
 62                    let mut history = app.history.clone();
 63                    history.push(app.into());
 64
 65                    return (
 66                        false,
 67                        App {
 68                            history,
 69                            page: Page::ItemDisplay(DisplayItem::Video(
 70                                video_list.iter().nth(list.selected).unwrap().id(),
 71                            )),
 72                            selectable: App::selectable(&state),
 73                            state,
 74                            ..Default::default()
 75                        },
 76                    );
 77                }
 78                _ => {}
 79            },
 80            _ => {}
 81        }
 82
 83        (true, app)
 84    }
 85}
 86
 87impl LoadItem for MainMenuItem {
 88    fn load_item(&self, app: &App) -> Result<Box<Self>, Box<dyn Error>> {
 89        let mut this = self.clone();
 90
 91        match &mut this {
 92            MainMenuItem::VideoList(enum_items) => match app.page {
 93                Page::MainMenu(tab) => match tab {
 94                    MainMenuSelector::Trending => {
 95                        let list: LinkedList<ListItem> = app
 96                            .client
 97                            .trending(None)?
 98                            .videos
 99                            .into_iter()
100                            .map(|t| ListItem::MiniVideo(t.into()))
101                            .collect();
102
103                        download_all_thumbnails(
104                            list.iter()
105                                .map(|t| match t {
106                                    ListItem::MiniVideo(v) => {
107                                        (v.video_thumbnail.clone(), v.video_id.clone())
108                                    }
109                                    _ => unreachable!(),
110                                })
111                                .collect(),
112                        )?;
113
114                        if let Some((video_list, text_list, _)) = enum_items {
115                            *text_list = TextList::default();
116                            text_list.items(textlist_from_video_list(&list));
117
118                            *video_list = list;
119                        } else {
120                            let mut text_list = TextList::default();
121                            text_list.items(textlist_from_video_list(&list));
122                            *enum_items = Some((list, text_list, None));
123                        };
124                    }
125
126                    MainMenuSelector::Popular => {
127                        let list: LinkedList<ListItem> = app
128                            .client
129                            .popular(None)?
130                            .items
131                            .into_iter()
132                            .map(|t| ListItem::MiniVideo(t.into()))
133                            .collect();
134
135                        download_all_thumbnails(
136                            list.iter()
137                                .map(|t| match t {
138                                    ListItem::MiniVideo(v) => {
139                                        (v.video_thumbnail.clone(), v.video_id.clone())
140                                    }
141                                    _ => unreachable!(),
142                                })
143                                .collect(),
144                        )?;
145
146                        let mut text_list = TextList::default();
147
148                        if let Some((video_list, text_list, _)) = enum_items {
149                            *text_list = TextList::default();
150                            text_list.items(textlist_from_video_list(&list));
151
152                            *video_list = list;
153                        } else {
154                            text_list.items(textlist_from_video_list(&list));
155                            *enum_items = Some((list, text_list, None));
156                        };
157                    }
158
159                    MainMenuSelector::History => {
160                        let mut list = LinkedList::new();
161                        let mut text_list = TextList::default();
162
163                        app.watch_history.0.iter().for_each(|t| {
164                            let file = fs::read_to_string(
165                                home::home_dir()
166                                    .expect("Cannot get your home directory")
167                                    .join(".local/share/youtube-tui/watch_history/info")
168                                    .join(format!("{}.json", t)),
169                            );
170
171                            if let Ok(file) = file {
172                                let item: ListItem = serde_json::from_str(&file).unwrap();
173
174                                let title = item.to_string();
175
176                                list.push_back(item);
177                                text_list.items.push(title);
178                            }
179                        });
180
181                        *enum_items = Some((list, text_list, None));
182                    }
183                },
184
185                _ => {}
186            },
187            _ => {}
188        }
189
190        Ok(Box::new(this))
191    }
192}
193
194impl MainMenuItem {
195    pub fn render_item<B: Backend>(
196        &mut self,
197        frame: &mut Frame<B>,
198        rect: Rect,
199        selected: bool,
200        hover: bool,
201        popup_focus: bool,
202        page: &Page,
203    ) {
204        let mut style = Style::default().fg(if selected {
205            Color::LightBlue
206        } else if hover {
207            Color::LightRed
208        } else {
209            Color::Reset
210        });
211
212        match self {
213            MainMenuItem::SeletorTab(selector) => {
214                if !hover && page == &(Page::MainMenu(*selector)) {
215                    style = style.fg(Color::LightYellow);
216                }
217                let text = match selector {
218                    MainMenuSelector::Trending => "Trending",
219                    MainMenuSelector::Popular => "Popular",
220                    MainMenuSelector::History => "History",
221                };
222
223                let block = Block::default()
224                    .border_type(BorderType::Rounded)
225                    .borders(Borders::ALL)
226                    .border_style(style);
227                let paragraph = Paragraph::new(text)
228                    .block(block)
229                    .alignment(Alignment::Center);
230
231                frame.render_widget(paragraph, rect);
232            }
233            MainMenuItem::VideoList(data) => {
234                let split = HorizontalSplit::default()
235                    .percentages(vec![60, 40])
236                    .border_style(Style::default().fg(if selected {
237                        Color::LightBlue
238                    } else if hover {
239                        Color::LightRed
240                    } else {
241                        Color::Reset
242                    }));
243
244                let chunks = split.inner(rect);
245
246                frame.render_widget(split, rect);
247
248                if let Some((videos, list, _)) = data {
249                    list.area(chunks[0]);
250                    let mut list = list.clone();
251
252                    if selected {
253                        list.selected_style(Style::default().fg(Color::LightRed));
254                    } else {
255                        list.selected_style(Style::default().fg(Color::LightYellow));
256                    }
257
258                    if let Some(item) = videos.iter().nth(list.selected) {
259                        if !popup_focus {
260                            frame.render_widget(ItemDisplay { item: item.clone() }, chunks[1]);
261                        }
262                    }
263
264                    frame.render_widget(list, chunks[0]);
265                }
266            }
267        }
268    }
269}
270
271pub fn textlist_from_video_list(original: &LinkedList<ListItem>) -> Vec<String> {
272    original.iter().map(|item| item.to_string()).collect()
273}
274
275#[derive(Debug, Clone, Copy, PartialEq)]
276pub enum MainMenuSelector {
277    Trending,
278    Popular,
279    History,
280}
281
282impl Default for MainMenuSelector {
283    fn default() -> Self {
284        Self::Popular
285    }
286}
287
288pub struct MainMenu;
289
290impl MainMenu {
291    pub fn message() -> String {
292        String::from("Loading home page...")
293    }
294
295    pub fn min() -> (u16, u16) {
296        (45, 15)
297    }
298
299    pub fn default() -> Vec<Row> {
300        vec![
301            Row {
302                items: vec![
303                    RowItem {
304                        item: Item::Global(GlobalItem::SearchBar),
305                        constraint: Constraint::Min(16),
306                    },
307                    RowItem {
308                        item: Item::Global(GlobalItem::SearchSettings),
309                        constraint: Constraint::Length(5),
310                    },
311                ],
312                centered: false,
313                height: Constraint::Length(3),
314            },
315            Row {
316                items: vec![
317                    RowItem {
318                        item: Item::MainMenu(MainMenuItem::SeletorTab(MainMenuSelector::Popular)),
319                        constraint: Constraint::Length(15),
320                    },
321                    RowItem {
322                        item: Item::MainMenu(MainMenuItem::SeletorTab(MainMenuSelector::Trending)),
323                        constraint: Constraint::Length(15),
324                    },
325                    RowItem {
326                        item: Item::MainMenu(MainMenuItem::SeletorTab(MainMenuSelector::History)),
327                        constraint: Constraint::Length(15),
328                    },
329                ],
330                centered: true,
331                height: Constraint::Length(3),
332            },
333            Row {
334                items: vec![RowItem {
335                    item: Item::MainMenu(MainMenuItem::VideoList(None)),
336                    constraint: Constraint::Percentage(100),
337                }],
338                centered: false,
339                height: Constraint::Min(6),
340            },
341            Row {
342                items: vec![RowItem {
343                    item: Item::Global(GlobalItem::MessageBar),
344                    constraint: Constraint::Percentage(100),
345                }],
346                centered: false,
347                height: Constraint::Length(3),
348            },
349        ]
350    }
351}