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