src/items/itemlist.rs

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