src/items/itemlist.rs

512 lines · 18135 bytes

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