src/items/itemlist.rs
569 lines · 20193 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 render(
277 &mut self,
278 frame: &mut ratatui::Frame,
279 framework: &mut tui_additions::framework::FrameworkClean,
280 area: ratatui::layout::Rect,
281 popup_render: bool,
282 info: tui_additions::framework::ItemInfo,
283 ) {
284 if popup_render {
285 return;
286 }
287
288 let status = framework.data.global.get::<Status>().unwrap();
289 let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
290 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
291
292 if status.provider_updated {
293 set_envs(
294 self.infalte_item_update(mainconfig, status).into_iter(),
295 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
296 );
297 }
298
299 self.update_appearance(appearance, mainconfig, &info);
300
301 // creates the grid
302 let grid = self.grid.clone();
303 let chunks = grid.chunks(area).unwrap()[0].clone();
304
305 // creates the text list in cell (0, 1)
306 self.textlist.set_height(chunks[0].height);
307 self.textlist
308 .set_cursor_style(Style::default().fg(if info.selected {
309 appearance.colors.outline_hover
310 } else {
311 appearance.colors.outline_secondary
312 }));
313
314 let textlist = self.textlist.clone();
315
316 frame.render_widget(grid, area);
317 frame.render_widget(textlist, chunks[0]);
318
319 // used the `.render()` function in self.info because it is an ItemInfo and impls FrameworkItem instead of Widget
320 self.info
321 .render(frame, framework, chunks[1], popup_render, info);
322 }
323
324 fn selectable(&self) -> bool {
325 true
326 }
327
328 fn load_item(
329 &mut self,
330 framework: &mut tui_additions::framework::FrameworkClean,
331 _info: tui_additions::framework::ItemInfo,
332 ) -> Result<(), Box<dyn Error>> {
333 *self = Self::default();
334
335 let page = framework.data.state.get::<Page>().unwrap();
336 let image_index = framework
337 .data
338 .global
339 .get::<MainConfig>()
340 .unwrap()
341 .image_index;
342
343 // fetch the items using the invidious api
344 match page {
345 Page::MainMenu(MainMenuPage::Trending) => {
346 self.items = SearchProviderWrapper::trending()?
347 .into_iter()
348 .map(|item| Item::from_common_video(item, image_index))
349 .collect();
350 }
351 Page::MainMenu(MainMenuPage::Popular) => {
352 self.items = SearchProviderWrapper::popular()?
353 .into_iter()
354 .map(|item| Item::from_popular_item(item, image_index))
355 .collect();
356 }
357 Page::MainMenu(MainMenuPage::Library) => {
358 let history = framework.data.global.get::<Library>().unwrap();
359 self.items = history.0.clone().into_iter().rev().collect();
360 }
361 Page::MainMenu(MainMenuPage::History) => {
362 // the vector needs to be reversed because the latest watch history is pushed to
363 // the back, meaning it needs to be reversed so that the latests one are on top
364 let history = framework.data.global.get::<WatchHistory>().unwrap();
365 self.items = history.0.clone().into_iter().rev().collect();
366 }
367 Page::Search(search) => {
368 self.items = SearchProviderWrapper::search(search)?
369 .into_iter()
370 .map(|item| Item::from_search_item(item, image_index))
371 .collect();
372 if !self.items.is_empty() {
373 self.items.push(Item::Page(true));
374 }
375 if search.page != 1 {
376 self.items.insert(0, Item::Page(false));
377 }
378 }
379 _ => unreachable!("item `ItemList` cannot be used in `{page:?}`"),
380 }
381
382 // update the items in text list
383 self.textlist.set_items(&self.items).unwrap();
384 self.update(framework);
385
386 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
387 let status = framework.data.global.get::<Status>().unwrap();
388 if mainconfig.images.display() {
389 // download thumbnails of all videos in the list
390 download_all_images(self.items.iter().map(|item| item.into()).collect());
391 }
392
393 set_envs(
394 self.infalte_item_update(mainconfig, status).into_iter(),
395 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
396 );
397 update_provider(framework.data);
398
399 Ok(())
400 }
401
402 fn key_event(
403 &mut self,
404 framework: &mut tui_additions::framework::FrameworkClean,
405 key: crossterm::event::KeyEvent,
406 _info: tui_additions::framework::ItemInfo,
407 ) -> Result<(), Box<dyn Error>> {
408 let action = if let Some(action) = framework
409 .data
410 .global
411 .get::<KeyBindingsConfig>()
412 .unwrap()
413 .get(key)
414 {
415 action
416 } else {
417 return Ok(());
418 };
419
420 // move the textlist cursor in the corresponding directions
421 let updated = match action {
422 KeyAction::MoveUp => self.textlist.up().is_ok(),
423 KeyAction::MoveDown => self.textlist.down().is_ok(),
424 KeyAction::MoveLeft | KeyAction::First => self.textlist.first().is_ok(),
425 KeyAction::MoveRight | KeyAction::End => self.textlist.last().is_ok(),
426 KeyAction::Select => {
427 self.select_at_cursor(framework);
428 false
429 }
430 _ => false,
431 };
432
433 // only create a render task if the key event actually changed something
434 if updated && !self.items.is_empty() {
435 self.update(framework);
436 set_envs(
437 self.infalte_item_update(
438 framework.data.global.get::<MainConfig>().unwrap(),
439 framework.data.global.get::<Status>().unwrap(),
440 )
441 .into_iter(),
442 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
443 );
444
445 framework
446 .data
447 .global
448 .get_mut::<Status>()
449 .unwrap()
450 .render_image = true;
451 self.info.item = Some(self.items[self.textlist.selected].clone());
452 framework
453 .data
454 .state
455 .get_mut::<Tasks>()
456 .unwrap()
457 .priority
458 .push(Task::RenderAll);
459 }
460
461 Ok(())
462 }
463
464 fn mouse_event(
465 &mut self,
466 framework: &mut tui_additions::framework::FrameworkClean,
467 x: u16,
468 y: u16,
469 _absolute_x: u16,
470 _absolute_y: u16,
471 ) -> bool {
472 let chunk = self
473 .grid
474 .chunks(
475 if let Some(prev_frame) = framework.data.global.get::<Status>().unwrap().prev_frame
476 {
477 prev_frame
478 } else {
479 return false;
480 },
481 )
482 .unwrap()[0][0];
483
484 if !chunk.intersects(Rect::new(x, y, 1, 1)) {
485 return false;
486 }
487
488 let previously_selected = self.textlist.selected;
489 let y = (y - chunk.y) as usize + self.textlist.scroll;
490
491 // clicking on already selected item
492 if y == self.textlist.selected
493 || y == self.textlist.selected + 2
494 || y == self.textlist.selected + 1
495 {
496 self.select_at_cursor(framework);
497 return true;
498 }
499
500 // clicking on rows after the last item
501 if y > self.textlist.items.len() + 1 {
502 return false;
503 }
504
505 // moving the cursor
506 if y <= self.textlist.selected {
507 self.textlist.selected = y;
508 }
509
510 if y >= self.textlist.selected + 2 {
511 self.textlist.selected = y - 2;
512 }
513
514 if self.textlist.selected == previously_selected {
515 return false;
516 }
517
518 self.update(framework);
519 set_envs(
520 self.infalte_item_update(
521 framework.data.global.get::<MainConfig>().unwrap(),
522 framework.data.global.get::<Status>().unwrap(),
523 )
524 .into_iter(),
525 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
526 );
527
528 // render the new image
529 framework
530 .data
531 .global
532 .get_mut::<Status>()
533 .unwrap()
534 .render_image = true;
535
536 true
537 }
538}
539
540impl ItemList {
541 // change `self.item` to the currently selected item
542 pub fn update(&mut self, framework: &mut FrameworkClean) {
543 let selected = self.items.get(self.textlist.selected);
544
545 if selected.is_none() {
546 return;
547 }
548
549 if matches!(selected, Some(Item::Page(_))) {
550 framework
551 .data
552 .global
553 .get_mut::<Status>()
554 .unwrap()
555 .render_image = true;
556 framework
557 .data
558 .state
559 .get_mut::<Tasks>()
560 .unwrap()
561 .priority
562 .push(Task::ClearPage);
563 self.info.item = None;
564 return;
565 }
566
567 self.info.item = Some(self.items[self.textlist.selected].clone());
568 }
569}