src/items/itemlist.rs
503 lines · 17662 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::Subscriptions) => {}
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 let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
341 let status = framework.data.global.get::<Status>().unwrap();
342
343 if mainconfig.images.display() {
344 // download thumbnails of all videos in the list
345 download_all_images(self.items.iter().map(|item| item.into()).collect());
346 }
347
348 // update the items in text list
349 self.textlist.set_items(&self.items).unwrap();
350 self.update();
351
352 set_envs(
353 self.infalte_item_update(mainconfig, status).into_iter(),
354 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
355 );
356 update_provider(framework.data);
357
358 Ok(())
359 }
360
361 fn key_event(
362 &mut self,
363 framework: &mut tui_additions::framework::FrameworkClean,
364 key: crossterm::event::KeyEvent,
365 _info: tui_additions::framework::ItemInfo,
366 ) -> Result<(), Box<dyn Error>> {
367 let action = if let Some(action) = framework
368 .data
369 .global
370 .get::<KeyBindingsConfig>()
371 .unwrap()
372 .get(key)
373 {
374 action
375 } else {
376 return Ok(());
377 };
378
379 // move the textlist cursor in the corresponding directions
380 let updated = match action {
381 KeyAction::MoveUp => self.textlist.up().is_ok(),
382 KeyAction::MoveDown => self.textlist.down().is_ok(),
383 KeyAction::MoveLeft => self.textlist.first().is_ok(),
384 KeyAction::MoveRight => self.textlist.last().is_ok(),
385 KeyAction::Select => {
386 self.select_at_cursor(framework);
387 false
388 }
389 _ => false,
390 };
391
392 // only create a render task if the key event actually changed something
393 if updated {
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 y = (y - chunk.y) as usize + self.textlist.scroll;
447
448 // clicking on already selected item
449 if y == self.textlist.selected
450 || y == self.textlist.selected + 2
451 || y == self.textlist.selected + 1
452 {
453 self.select_at_cursor(framework);
454 return true;
455 }
456
457 // clicking on rows after the last item
458 if y > self.textlist.items.len() + 1 {
459 return false;
460 }
461
462 // moving the cursor
463 if y <= self.textlist.selected {
464 self.textlist.selected = y;
465 }
466
467 if y >= self.textlist.selected + 2 {
468 self.textlist.selected = y - 2;
469 }
470
471 self.update();
472 set_envs(
473 self.infalte_item_update(
474 framework.data.global.get::<MainConfig>().unwrap(),
475 framework.data.global.get::<Status>().unwrap(),
476 )
477 .into_iter(),
478 &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
479 );
480
481 // render the new image
482 framework
483 .data
484 .global
485 .get_mut::<Status>()
486 .unwrap()
487 .render_image = true;
488
489 true
490 }
491}
492
493impl ItemList {
494 // change `self.item` to the currently selected item
495 pub fn update(&mut self) {
496 if self.items.is_empty() {
497 self.info.item = None;
498 return;
499 }
500
501 self.info.item = Some(self.items[self.textlist.selected].clone());
502 }
503}