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