src/items/itemlist.rs

526 lines · 18425 bytes

  1use std::error::Error;
  2
  3use crate::{
  4    config::*,
  5    global::{functions::*, structs::*},
  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 { 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 ratatui::Frame<ratatui::backend::CrosstermBackend<std::io::Stdout>>,
229        framework: &mut tui_additions::framework::FrameworkClean,
230        area: ratatui::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 | KeyAction::First => self.textlist.first().is_ok(),
382            KeyAction::MoveRight | KeyAction::End => 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            self.update(framework);
393            set_envs(
394                self.infalte_item_update(
395                    framework.data.global.get::<MainConfig>().unwrap(),
396                    framework.data.global.get::<Status>().unwrap(),
397                )
398                .into_iter(),
399                &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
400            );
401
402            framework
403                .data
404                .global
405                .get_mut::<Status>()
406                .unwrap()
407                .render_image = true;
408            self.info.item = Some(self.items[self.textlist.selected].clone());
409            framework
410                .data
411                .state
412                .get_mut::<Tasks>()
413                .unwrap()
414                .priority
415                .push(Task::RenderAll);
416        }
417
418        Ok(())
419    }
420
421    fn mouse_event(
422        &mut self,
423        framework: &mut tui_additions::framework::FrameworkClean,
424        x: u16,
425        y: u16,
426        _absolute_x: u16,
427        _absolute_y: u16,
428    ) -> bool {
429        let chunk = self
430            .grid
431            .chunks(
432                if let Some(prev_frame) = framework.data.global.get::<Status>().unwrap().prev_frame
433                {
434                    prev_frame
435                } else {
436                    return false;
437                },
438            )
439            .unwrap()[0][0];
440
441        if !chunk.intersects(Rect::new(x, y, 1, 1)) {
442            return false;
443        }
444
445        let previously_selected = self.textlist.selected;
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        if self.textlist.selected == previously_selected {
472            return false;
473        }
474
475        self.update(framework);
476        set_envs(
477            self.infalte_item_update(
478                framework.data.global.get::<MainConfig>().unwrap(),
479                framework.data.global.get::<Status>().unwrap(),
480            )
481            .into_iter(),
482            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
483        );
484
485        // render the new image
486        framework
487            .data
488            .global
489            .get_mut::<Status>()
490            .unwrap()
491            .render_image = true;
492
493        true
494    }
495}
496
497impl ItemList {
498    // change `self.item` to the currently selected item
499    pub fn update(&mut self, framework: &mut FrameworkClean) {
500        let selected = self.items.get(self.textlist.selected);
501
502        if selected.is_none() {
503            return;
504        }
505
506        if matches!(selected, Some(Item::Page(_)) | Some(Item::Unknown(_))) {
507            framework
508                .data
509                .global
510                .get_mut::<Status>()
511                .unwrap()
512                .render_image = true;
513            framework
514                .data
515                .state
516                .get_mut::<Tasks>()
517                .unwrap()
518                .priority
519                .push(Task::ClearPage);
520            self.info.item = None;
521            return;
522        }
523
524        self.info.item = Some(self.items[self.textlist.selected].clone());
525    }
526}