src/app/pages/main_menu.rs

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

376 lines · 13394 bytes

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