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