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