src/app/pages/main_menu.rs

46e7ed5b32a7417aabe4491e60a597344597d330
youtube-tui/src/app/pages/main_menu.rs history · blame · raw

367 lines · 12553 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 = match &item {
175                                    ListItem::FullVideo(v) => v.title.clone(),
176                                    _ => unreachable!(),
177                                };
178
179                                list.push_back(item);
180                                text_list.items.push(title);
181                            }
182                        });
183
184                        *enum_items = Some((list, text_list, None));
185                    }
186                },
187
188                _ => {}
189            },
190            _ => {}
191        }
192
193        Ok(Box::new(this))
194    }
195}
196
197impl MainMenuItem {
198    pub fn render_item<B: Backend>(
199        &mut self,
200        frame: &mut Frame<B>,
201        rect: Rect,
202        selected: bool,
203        hover: bool,
204        popup_focus: bool,
205        page: &Page,
206    ) {
207        let mut style = Style::default().fg(if selected {
208            Color::LightBlue
209        } else if hover {
210            Color::LightRed
211        } else {
212            Color::Reset
213        });
214
215        match self {
216            MainMenuItem::SeletorTab(selector) => {
217                if !hover && page == &(Page::MainMenu(*selector)) {
218                    style = style.fg(Color::LightYellow);
219                }
220                let text = match selector {
221                    MainMenuSelector::Trending => "Trending",
222                    MainMenuSelector::Popular => "Popular",
223                    MainMenuSelector::History => "History",
224                };
225
226                let block = Block::default()
227                    .border_type(BorderType::Rounded)
228                    .borders(Borders::ALL)
229                    .border_style(style);
230                let paragraph = Paragraph::new(text)
231                    .block(block)
232                    .alignment(Alignment::Center);
233
234                frame.render_widget(paragraph, rect);
235            }
236            MainMenuItem::VideoList(data) => {
237                let split = HorizontalSplit::default()
238                    .percentages(vec![60, 40])
239                    .border_style(Style::default().fg(if selected {
240                        Color::LightBlue
241                    } else if hover {
242                        Color::LightRed
243                    } else {
244                        Color::Reset
245                    }));
246
247                let chunks = split.inner(rect);
248
249                frame.render_widget(split, rect);
250
251                if let Some((videos, list, _)) = data {
252                    list.area(chunks[0]);
253                    let mut list = list.clone();
254
255                    if selected {
256                        list.selected_style(Style::default().fg(Color::LightRed));
257                    } else {
258                        list.selected_style(Style::default().fg(Color::LightYellow));
259                    }
260
261                    if let Some(item) = videos.iter().nth(list.selected) {
262                        if !popup_focus {
263                            frame.render_widget(ItemDisplay { item: item.clone() }, chunks[1]);
264                        }
265                    }
266
267                    frame.render_widget(list, chunks[0]);
268                }
269            }
270        }
271    }
272}
273
274fn textlist_from_video_list(original: &LinkedList<ListItem>) -> Vec<String> {
275    original
276        .iter()
277        .map(|item| match item {
278            ListItem::MiniVideo(video) => video
279                .title
280                .clone()
281                .chars()
282                .map(|c| if c.is_ascii() { c } else { '?' })
283                .collect(),
284            _ => {
285                unreachable!()
286            }
287        })
288        .collect()
289}
290
291#[derive(Debug, Clone, Copy, PartialEq)]
292pub enum MainMenuSelector {
293    Trending,
294    Popular,
295    History,
296}
297
298impl Default for MainMenuSelector {
299    fn default() -> Self {
300        Self::Popular
301    }
302}
303
304pub struct MainMenu;
305
306impl MainMenu {
307    pub fn message() -> String {
308        String::from("Loading home page...")
309    }
310
311    pub fn min() -> (u16, u16) {
312        (45, 15)
313    }
314
315    pub fn default() -> Vec<Row> {
316        vec![
317            Row {
318                items: vec![
319                    RowItem {
320                        item: Item::Global(GlobalItem::SearchBar(String::new())),
321                        constraint: Constraint::Min(16),
322                    },
323                    RowItem {
324                        item: Item::Global(GlobalItem::SearchSettings),
325                        constraint: Constraint::Length(5),
326                    },
327                ],
328                centered: false,
329                height: Constraint::Length(3),
330            },
331            Row {
332                items: vec![
333                    RowItem {
334                        item: Item::MainMenu(MainMenuItem::SeletorTab(MainMenuSelector::Popular)),
335                        constraint: Constraint::Length(15),
336                    },
337                    RowItem {
338                        item: Item::MainMenu(MainMenuItem::SeletorTab(MainMenuSelector::Trending)),
339                        constraint: Constraint::Length(15),
340                    },
341                    RowItem {
342                        item: Item::MainMenu(MainMenuItem::SeletorTab(MainMenuSelector::History)),
343                        constraint: Constraint::Length(15),
344                    },
345                ],
346                centered: true,
347                height: Constraint::Length(3),
348            },
349            Row {
350                items: vec![RowItem {
351                    item: Item::MainMenu(MainMenuItem::VideoList(None)),
352                    constraint: Constraint::Percentage(100),
353                }],
354                centered: false,
355                height: Constraint::Min(6),
356            },
357            Row {
358                items: vec![RowItem {
359                    item: Item::Global(GlobalItem::MessageBar),
360                    constraint: Constraint::Percentage(100),
361                }],
362                centered: false,
363                height: Constraint::Length(3),
364            },
365        ]
366    }
367}