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