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