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