src/app/pages/main_menu.rs

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

312 lines · 10255 bytes

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