src/items/itemlist.rs

607 lines · 21835 bytes

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