src/app/pages/main_menu.rs

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

381 lines · 14417 bytes

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