src/items/itemlist.rs
612 lines · 21658 bytes
1use std::error::Error;
2
3use crate::{
4 config::*,
5 global::{functions::*, structs::*, traits::SearchProviderWrapper},
6 items::ItemInfo,
7};
8use home::home_dir;
9use ratatui::{
10 layout::{Constraint, Rect},
11 style::Style,
12};
13use tui_additions::{
14 framework::{FrameworkClean, FrameworkItem},
15 widgets::{Grid, TextList},
16};
17
18/// An item list displays a list of items
19// It consists of a 1 x 2 grid, with the left cell displaying a text list, the right displaying item info of the currently hovered item
20#[derive(Clone)]
21pub struct ItemList {
22 pub info: ItemInfo,
23 pub items: Vec<Item>,
24 pub textlist: TextList,
25 pub grid: Grid,
26}
27
28impl ItemList {
29 pub fn infalte_item_update(
30 &self,
31 mainconfig: &MainConfig,
32 status: &Status,
33 ) -> Vec<(String, String)> {
34 if self.textlist.items.is_empty() {
35 return Vec::new();
36 }
37
38 match &self.items[self.textlist.selected] {
39 Item::MiniVideo(MiniVideoItem {
40 id,
41 title,
42 channel_id,
43 channel,
44 ..
45 })
46 | Item::FullVideo(FullVideoItem {
47 id,
48 title,
49 channel_id,
50 channel,
51 ..
52 }) => {
53 vec![
54 (
55 String::from("hover-url"),
56 format!(
57 "{}/watch?v={id}",
58 match status.provider {
59 Provider::YouTube => "https://youtube.com",
60 Provider::Invidious => &mainconfig.invidious_instance,
61 }
62 ),
63 ),
64 (String::from("hover-title"), title.clone()),
65 (String::from("hover-id"), id.clone()),
66 (String::from("hover-type"), String::from("video")),
67 (String::from("hover-channel-id"), channel_id.clone()),
68 (String::from("hover-channel"), channel.clone()),
69 ]
70 }
71 Item::MiniPlaylist(MiniPlaylistItem {
72 id,
73 title,
74 channel_id,
75 channel,
76 ..
77 })
78 | Item::FullPlaylist(FullPlaylistItem {
79 id,
80 title,
81 channel_id,
82 channel,
83 ..
84 }) => {
85 vec![
86 (
87 String::from("hover-url"),
88 format!(
89 "{}/playlist?list={id}",
90 match status.provider {
91 Provider::YouTube => "https://youtube.com",
92 Provider::Invidious => &mainconfig.invidious_instance,
93 }
94 ),
95 ),
96 (String::from("hover-title"), title.clone()),
97 (String::from("hover-id"), id.clone()),
98 (String::from("hover-type"), String::from("playlist")),
99 (String::from("hover-channel-id"), channel_id.clone()),
100 (String::from("hover-channel"), channel.clone()),
101 ]
102 }
103 Item::MiniChannel(MiniChannelItem { id, name, .. })
104 | Item::FullChannel(FullChannelItem { id, name, .. }) => {
105 vec![
106 (
107 String::from("hover-url"),
108 format!(
109 "{}/channel/{id}",
110 match status.provider {
111 Provider::YouTube => "https://youtube.com",
112 Provider::Invidious => &mainconfig.invidious_instance,
113 }
114 ),
115 ),
116 (String::from("hover-title"), name.clone()),
117 (String::from("hover-id"), id.clone()),
118 (String::from("hover-channel-id"), id.clone()),
119 (String::from("hover-channel"), name.clone()),
120 (String::from("hover-type"), String::from("channel")),
121 ]
122 }
123 Item::Page(_) => {
124 vec![(String::from("hover-url"), String::from("not avaliable"))]
125 }
126 }
127 }
128
129 fn update_appearance(
130 &mut self,
131 appearance: &AppearanceConfig,
132 mainconfig: &MainConfig,
133 iteminfo: &tui_additions::framework::ItemInfo,
134 ) {
135 self.textlist.set_ascii_only(!mainconfig.allow_unicode);
136 self.grid.set_border_type(appearance.borders);
137 self.textlist.set_border_type(appearance.borders);
138 self.textlist
139 .set_style(Style::default().fg(appearance.colors.text));
140
141 if iteminfo.selected {
142 self.grid
143 .set_border_style(Style::default().fg(appearance.colors.outline_selected));
144 self.textlist
145 .set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
146 self.textlist
147 .set_selected_style(Style::default().fg(appearance.colors.text_special));
148 } else {
149 self.textlist
150 .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
151 self.textlist
152 .set_selected_style(Style::default().fg(appearance.colors.text_secondary));
153 if iteminfo.hover {
154 self.grid
155 .set_border_style(Style::default().fg(appearance.colors.outline_hover));
156 } else {
157 self.grid
158 .set_border_style(Style::default().fg(appearance.colors.outline));
159 }
160 }
161 }
162
163 /// handles select (enter)
164 fn select_at_cursor(&self, framework: &mut FrameworkClean) {
165 let page_to_load = if home_dir()
166 .unwrap()
167 .join(format!(
168 ".cache/youtube-tui/info/{}.json",
169 self.items[self.textlist.selected].id().unwrap_or_default()
170 ))
171 .exists()
172 {
173 match &self.items[self.textlist.selected] {
174 Item::MiniVideo(MiniVideoItem { id, .. })
175 | Item::FullVideo(FullVideoItem { id, .. }) => {
176 Some(Page::SingleItem(SingleItemPage::Video(id.clone())))
177 }
178 Item::MiniPlaylist(MiniPlaylistItem { id, .. })
179 | Item::FullPlaylist(FullPlaylistItem { id, .. }) => {
180 Some(Page::SingleItem(SingleItemPage::Playlist(id.clone())))
181 }
182 Item::MiniChannel(MiniChannelItem { id, .. })
183 | Item::FullChannel(FullChannelItem { id, .. }) => {
184 Some(Page::ChannelDisplay(ChannelDisplayPage {
185 id: id.to_string(),
186 r#type: ChannelDisplayPageType::Main,
187 }))
188 }
189 // Item::Unknown(_) => {
190 // *framework.data.global.get_mut::<Message>().unwrap() =
191 // Message::Message(String::from("Unknown item"));
192 // framework
193 // .data
194 // .state
195 // .get_mut::<Tasks>()
196 // .unwrap()
197 // .priority
198 // .push(Task::RenderAll);
199 // None
200 // }
201 Item::Page(b) => match framework.data.state.get::<Page>().unwrap() {
202 Page::Search(search) => Some(Page::Search(Search {
203 page: if *b { search.page + 1 } else { search.page - 1 },
204 ..search.clone()
205 })),
206 _ => unreachable!("Page turners can only be used in search pages"),
207 },
208 }
209 } else {
210 match &self.items[self.textlist.selected] {
211 Item::MiniVideo(MiniVideoItem { id, .. })
212 | Item::FullVideo(FullVideoItem { id, .. }) => {
213 Some(Page::SingleItem(SingleItemPage::Video(id.clone())))
214 }
215 Item::MiniPlaylist(MiniPlaylistItem { id, .. })
216 | Item::FullPlaylist(FullPlaylistItem { id, .. }) => {
217 Some(Page::SingleItem(SingleItemPage::Playlist(id.clone())))
218 }
219 Item::MiniChannel(MiniChannelItem { id, .. })
220 | Item::FullChannel(FullChannelItem { id, .. }) => {
221 Some(Page::ChannelDisplay(ChannelDisplayPage {
222 id: id.clone(),
223 r#type: ChannelDisplayPageType::Main,
224 }))
225 }
226 // Item::Unknown(_) => {
227 // *framework.data.global.get_mut::<Message>().unwrap() =
228 // Message::Message(String::from("Unknown item"));
229 // framework
230 // .data
231 // .state
232 // .get_mut::<Tasks>()
233 // .unwrap()
234 // .priority
235 // .push(Task::RenderAll);
236 // None
237 // }
238 Item::Page(b) => match framework.data.state.get::<Page>().unwrap() {
239 Page::Search(search) => Some(Page::Search(Search {
240 page: if *b { search.page + 1 } else { search.page - 1 },
241 ..search.clone()
242 })),
243 _ => unreachable!("Page turners can only be used in search pages"),
244 },
245 }
246 };
247
248 if let Some(page_to_load) = page_to_load {
249 framework
250 .data
251 .state
252 .get_mut::<Tasks>()
253 .unwrap()
254 .priority
255 .push(Task::LoadPage(page_to_load));
256 }
257 }
258}
259
260impl Default for ItemList {
261 fn default() -> Self {
262 Self {
263 info: ItemInfo::default(),
264 items: Vec::new(),
265 textlist: TextList::default().non_ascii_replace(' '),
266 grid: Grid::new(
267 vec![Constraint::Percentage(60), Constraint::Percentage(40)],
268 vec![Constraint::Percentage(100)],
269 )
270 .unwrap(),
271 }
272 }
273}
274
275impl FrameworkItem for ItemList {
276 fn message(
277 &mut self,
278 framework: &mut FrameworkClean,
279 data: std::collections::HashMap<String, Box<dyn std::any::Any>>,
280 ) -> bool {
281 if !data.contains_key("type") {
282 return false;
283 }
284
285 let updated = data.get("type").is_some_and(|v| {
286 v.downcast_ref::<String>()
287 .is_some_and(|v| match v.as_str() {
288 "scrollup" => self.textlist.up().is_ok(),
289 "scrolldown" => self.textlist.down().is_ok(),
290 _ => false,
291 })
292 });
293
294 if updated && !self.items.is_empty() {
295 self.update(framework);
296 set_envs(
297 self.infalte_item_update(
298 framework.data.global.get::<MainConfig>().unwrap(),
299 framework.data.global.get::<Status>().unwrap(),
300 )
301 .into_iter(),
302 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
303 );
304
305 framework
306 .data
307 .global
308 .get_mut::<Status>()
309 .unwrap()
310 .render_image = true;
311 self.info.item = Some(self.items[self.textlist.selected].clone());
312 framework
313 .data
314 .state
315 .get_mut::<Tasks>()
316 .unwrap()
317 .priority
318 .push(Task::RenderAll);
319 }
320
321 updated
322 }
323
324 fn render(
325 &mut self,
326 frame: &mut ratatui::Frame,
327 framework: &mut tui_additions::framework::FrameworkClean,
328 area: ratatui::layout::Rect,
329 popup_render: bool,
330 info: tui_additions::framework::ItemInfo,
331 ) {
332 if popup_render {
333 return;
334 }
335
336 let status = framework.data.global.get::<Status>().unwrap();
337 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
338 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
339
340 if status.provider_updated {
341 set_envs(
342 self.infalte_item_update(mainconfig, status).into_iter(),
343 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
344 );
345 }
346
347 self.update_appearance(appearance, mainconfig, &info);
348
349 // creates the grid
350 let grid = self.grid.clone();
351 let chunks = grid.chunks(area).unwrap()[0].clone();
352
353 // creates the text list in cell (0, 1)
354 self.textlist.set_height(chunks[0].height);
355 self.textlist
356 .set_cursor_style(Style::default().fg(if info.selected {
357 appearance.colors.outline_hover
358 } else {
359 appearance.colors.outline_secondary
360 }));
361
362 let textlist = self.textlist.clone();
363
364 frame.render_widget(grid, area);
365 frame.render_widget(textlist, chunks[0]);
366
367 // used the `.render()` function in self.info because it is an ItemInfo and impls FrameworkItem instead of Widget
368 self.info
369 .render(frame, framework, chunks[1], popup_render, info);
370 }
371
372 fn selectable(&self) -> bool {
373 true
374 }
375
376 fn load_item(
377 &mut self,
378 framework: &mut tui_additions::framework::FrameworkClean,
379 _info: tui_additions::framework::ItemInfo,
380 ) -> Result<(), Box<dyn Error>> {
381 *self = Self::default();
382
383 let page = framework.data.state.get::<Page>().unwrap();
384 let image_index = framework
385 .data
386 .global
387 .get::<MainConfig>()
388 .unwrap()
389 .image_index;
390
391 // fetch the items using the invidious api
392 match page {
393 Page::MainMenu(MainMenuPage::Trending) => {
394 self.items = SearchProviderWrapper::trending()?
395 .into_iter()
396 .map(|item| Item::from_common_video(item, image_index))
397 .collect();
398 }
399 Page::MainMenu(MainMenuPage::Popular) => {
400 self.items = SearchProviderWrapper::popular()?
401 .into_iter()
402 .map(|item| Item::from_popular_item(item, image_index))
403 .collect();
404 }
405 Page::MainMenu(MainMenuPage::Library) => {
406 let history = framework.data.global.get::<Library>().unwrap();
407 self.items = history.0.clone().into_iter().rev().collect();
408 }
409 Page::MainMenu(MainMenuPage::History) => {
410 // the vector needs to be reversed because the latest watch history is pushed to
411 // the back, meaning it needs to be reversed so that the latests one are on top
412 let history = framework.data.global.get::<WatchHistory>().unwrap();
413 self.items = history.0.clone().into_iter().rev().collect();
414 }
415 Page::Search(search) => {
416 self.items = SearchProviderWrapper::search(search)?
417 .into_iter()
418 .map(|item| Item::from_search_item(item, image_index))
419 .collect();
420 if !self.items.is_empty() {
421 self.items.push(Item::Page(true));
422 }
423 if search.page != 1 {
424 self.items.insert(0, Item::Page(false));
425 }
426 }
427 _ => unreachable!("item `ItemList` cannot be used in `{page:?}`"),
428 }
429
430 // update the items in text list
431 self.textlist.set_items(&self.items).unwrap();
432 self.update(framework);
433
434 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
435 let status = framework.data.global.get::<Status>().unwrap();
436 if mainconfig.images.display() {
437 // download thumbnails of all videos in the list
438 download_all_images(self.items.iter().map(|item| item.into()).collect());
439 }
440
441 set_envs(
442 self.infalte_item_update(mainconfig, status).into_iter(),
443 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
444 );
445 update_provider(framework.data);
446
447 Ok(())
448 }
449
450 fn key_event(
451 &mut self,
452 framework: &mut tui_additions::framework::FrameworkClean,
453 key: crossterm::event::KeyEvent,
454 _info: tui_additions::framework::ItemInfo,
455 ) -> Result<(), Box<dyn Error>> {
456 let action = if let Some(action) = framework
457 .data
458 .global
459 .get::<KeyBindingsConfig>()
460 .unwrap()
461 .get(key)
462 {
463 action
464 } else {
465 return Ok(());
466 };
467
468 // move the textlist cursor in the corresponding directions
469 let updated = match action {
470 KeyAction::MoveUp => self.textlist.up().is_ok(),
471 KeyAction::MoveDown => self.textlist.down().is_ok(),
472 KeyAction::MoveLeft | KeyAction::First => self.textlist.first().is_ok(),
473 KeyAction::MoveRight | KeyAction::End => self.textlist.last().is_ok(),
474 KeyAction::Select => {
475 self.select_at_cursor(framework);
476 false
477 }
478 _ => false,
479 };
480
481 // only create a render task if the key event actually changed something
482 if updated && !self.items.is_empty() {
483 self.update(framework);
484 set_envs(
485 self.infalte_item_update(
486 framework.data.global.get::<MainConfig>().unwrap(),
487 framework.data.global.get::<Status>().unwrap(),
488 )
489 .into_iter(),
490 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
491 );
492
493 framework
494 .data
495 .global
496 .get_mut::<Status>()
497 .unwrap()
498 .render_image = true;
499 self.info.item = Some(self.items[self.textlist.selected].clone());
500 framework
501 .data
502 .state
503 .get_mut::<Tasks>()
504 .unwrap()
505 .priority
506 .push(Task::RenderAll);
507 }
508
509 Ok(())
510 }
511
512 fn mouse_event(
513 &mut self,
514 framework: &mut tui_additions::framework::FrameworkClean,
515 x: u16,
516 y: u16,
517 _absolute_x: u16,
518 _absolute_y: u16,
519 ) -> bool {
520 let chunk = self
521 .grid
522 .chunks(
523 if let Some(prev_frame) = framework.data.global.get::<Status>().unwrap().prev_frame
524 {
525 prev_frame
526 } else {
527 return false;
528 },
529 )
530 .unwrap()[0][0];
531
532 if !chunk.intersects(Rect::new(x, y, 1, 1)) {
533 return false;
534 }
535
536 let previously_selected = self.textlist.selected;
537 let y = (y - chunk.y) as usize + self.textlist.scroll;
538
539 // clicking on already selected item
540 if y == self.textlist.selected
541 || y == self.textlist.selected + 2
542 || y == self.textlist.selected + 1
543 {
544 self.select_at_cursor(framework);
545 return true;
546 }
547
548 // clicking on rows after the last item
549 if y > self.textlist.items.len() + 1 {
550 let _ = self.textlist.last();
551 } else if y <= self.textlist.selected {
552 self.textlist.selected = y;
553 } else if y >= self.textlist.selected + 2 {
554 self.textlist.selected = y - 2;
555 }
556
557 if self.textlist.selected == previously_selected {
558 return false;
559 }
560
561 self.update(framework);
562 set_envs(
563 self.infalte_item_update(
564 framework.data.global.get::<MainConfig>().unwrap(),
565 framework.data.global.get::<Status>().unwrap(),
566 )
567 .into_iter(),
568 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
569 );
570
571 // render the new image
572 framework
573 .data
574 .global
575 .get_mut::<Status>()
576 .unwrap()
577 .render_image = true;
578
579 true
580 }
581}
582
583impl ItemList {
584 // change `self.item` to the currently selected item
585 pub fn update(&mut self, framework: &mut FrameworkClean) {
586 let selected = self.items.get(self.textlist.selected);
587
588 if selected.is_none() {
589 return;
590 }
591
592 if matches!(selected, Some(Item::Page(_))) {
593 framework
594 .data
595 .global
596 .get_mut::<Status>()
597 .unwrap()
598 .render_image = true;
599 framework
600 .data
601 .state
602 .get_mut::<Tasks>()
603 .unwrap()
604 .priority
605 .push(Task::ClearPage);
606 self.info.item = None;
607 return;
608 }
609
610 self.info.item = Some(self.items[self.textlist.selected].clone());
611 }
612}