src/items/itemlist.rs

628 lines · 22821 bytes

12 symbols in this file
  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        if self.items.is_empty() {
165            return;
166        }
167
168        let page_to_load =
169            if LocalStore::get_info(self.items[self.textlist.selected].id().unwrap_or_default())
170                .is_some()
171            {
172                match &self.items[self.textlist.selected] {
173                    Item::MiniVideo(MiniVideoItem { id, .. })
174                    | Item::FullVideo(FullVideoItem { id, .. }) => {
175                        Some(Page::SingleItem(SingleItemPage::Video(id.clone())))
176                    }
177                    Item::MiniPlaylist(MiniPlaylistItem { id, .. })
178                    | Item::FullPlaylist(FullPlaylistItem { id, .. }) => {
179                        Some(Page::SingleItem(SingleItemPage::Playlist(id.clone())))
180                    }
181                    Item::MiniChannel(MiniChannelItem { id, .. })
182                    | Item::FullChannel(FullChannelItem { id, .. }) => {
183                        Some(Page::ChannelDisplay(ChannelDisplayPage {
184                            id: id.to_string(),
185                            r#type: ChannelDisplayPageType::Main,
186                        }))
187                    }
188                    // Item::Unknown(_) => {
189                    //     *framework.data.global.get_mut::<Message>().unwrap() =
190                    //         Message::Message(String::from("Unknown item"));
191                    //     framework
192                    //         .data
193                    //         .state
194                    //         .get_mut::<Tasks>()
195                    //         .unwrap()
196                    //         .priority
197                    //         .push(Task::RenderAll);
198                    //     None
199                    // }
200                    Item::Page(b) => match framework.data.state.get::<Page>().unwrap() {
201                        Page::Search(search) => Some(Page::Search(Search {
202                            page: if *b { search.page + 1 } else { search.page - 1 },
203                            ..search.clone()
204                        })),
205                        _ => unreachable!("Page turners can only be used in search pages"),
206                    },
207                }
208            } else {
209                match &self.items[self.textlist.selected] {
210                    Item::MiniVideo(MiniVideoItem { id, .. })
211                    | Item::FullVideo(FullVideoItem { id, .. }) => {
212                        Some(Page::SingleItem(SingleItemPage::Video(id.clone())))
213                    }
214                    Item::MiniPlaylist(MiniPlaylistItem { id, .. })
215                    | Item::FullPlaylist(FullPlaylistItem { id, .. }) => {
216                        Some(Page::SingleItem(SingleItemPage::Playlist(id.clone())))
217                    }
218                    Item::MiniChannel(MiniChannelItem { id, .. })
219                    | Item::FullChannel(FullChannelItem { id, .. }) => {
220                        Some(Page::ChannelDisplay(ChannelDisplayPage {
221                            id: id.clone(),
222                            r#type: ChannelDisplayPageType::Main,
223                        }))
224                    }
225                    // Item::Unknown(_) => {
226                    //     *framework.data.global.get_mut::<Message>().unwrap() =
227                    //         Message::Message(String::from("Unknown item"));
228                    //     framework
229                    //         .data
230                    //         .state
231                    //         .get_mut::<Tasks>()
232                    //         .unwrap()
233                    //         .priority
234                    //         .push(Task::RenderAll);
235                    //     None
236                    // }
237                    Item::Page(b) => match framework.data.state.get::<Page>().unwrap() {
238                        Page::Search(search) => Some(Page::Search(Search {
239                            page: if *b { search.page + 1 } else { search.page - 1 },
240                            ..search.clone()
241                        })),
242                        _ => unreachable!("Page turners can only be used in search pages"),
243                    },
244                }
245            };
246
247        if let Some(page_to_load) = page_to_load {
248            framework
249                .data
250                .state
251                .get_mut::<Tasks>()
252                .unwrap()
253                .priority
254                .push(Task::LoadPage(page_to_load));
255        }
256    }
257}
258
259impl Default for ItemList {
260    fn default() -> Self {
261        Self {
262            info: ItemInfo::default(),
263            items: Vec::new(),
264            textlist: TextList::default().non_ascii_replace(' '),
265            grid: Grid::new(
266                vec![Constraint::Percentage(60), Constraint::Percentage(40)],
267                vec![Constraint::Percentage(100)],
268            )
269            .unwrap(),
270        }
271    }
272}
273
274impl FrameworkItem for ItemList {
275    fn message(
276        &mut self,
277        framework: &mut FrameworkClean,
278        data: std::collections::HashMap<String, Box<dyn std::any::Any>>,
279    ) -> bool {
280        if !data.contains_key("type") {
281            return false;
282        }
283
284        let updated = data.get("type").is_some_and(|v| {
285            v.downcast_ref::<String>()
286                .is_some_and(|v| match v.as_str() {
287                    "scrollup" => self.textlist.up().is_ok(),
288                    "scrolldown" => self.textlist.down().is_ok(),
289                    _ => false,
290                })
291        });
292
293        if updated && !self.items.is_empty() {
294            self.update(framework);
295            set_envs(
296                self.infalte_item_update(
297                    framework.data.global.get::<MainConfig>().unwrap(),
298                    framework.data.global.get::<Status>().unwrap(),
299                )
300                .into_iter(),
301                &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
302            );
303
304            framework
305                .data
306                .global
307                .get_mut::<Status>()
308                .unwrap()
309                .render_image = true;
310            self.info.item = Some(self.items[self.textlist.selected].clone());
311            framework
312                .data
313                .state
314                .get_mut::<Tasks>()
315                .unwrap()
316                .priority
317                .push(Task::RenderAll);
318        }
319
320        updated
321    }
322
323    fn render(
324        &mut self,
325        frame: &mut ratatui::Frame,
326        framework: &mut tui_additions::framework::FrameworkClean,
327        area: ratatui::layout::Rect,
328        popup_render: bool,
329        info: tui_additions::framework::ItemInfo,
330    ) {
331        if popup_render {
332            return;
333        }
334
335        let status = framework.data.global.get::<Status>().unwrap();
336        let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
337        let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
338
339        if status.provider_updated {
340            set_envs(
341                self.infalte_item_update(mainconfig, status).into_iter(),
342                &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
343            );
344        }
345
346        self.update_appearance(appearance, mainconfig, &info);
347
348        // creates the grid
349        let grid = self.grid.clone();
350        let chunks = grid.chunks(area).unwrap()[0].clone();
351
352        // creates the text list in cell (0, 1)
353        self.textlist.set_height(chunks[0].height);
354        self.textlist
355            .set_cursor_style(Style::default().fg(if info.selected {
356                appearance.colors.outline_hover
357            } else {
358                appearance.colors.outline_secondary
359            }));
360
361        let textlist = self.textlist.clone();
362
363        frame.render_widget(grid, area);
364        frame.render_widget(textlist, chunks[0]);
365
366        // used the `.render()` function in self.info because it is an ItemInfo and impls FrameworkItem instead of Widget
367        self.info
368            .render(frame, framework, chunks[1], popup_render, info);
369    }
370
371    fn selectable(&self) -> bool {
372        true
373    }
374
375    fn load_item(
376        &mut self,
377        framework: &mut tui_additions::framework::FrameworkClean,
378        _info: tui_additions::framework::ItemInfo,
379    ) -> Result<(), Box<dyn Error>> {
380        *self = Self::default();
381
382        let page = framework.data.state.get::<Page>().unwrap();
383        let image_index = framework
384            .data
385            .global
386            .get::<MainConfig>()
387            .unwrap()
388            .image_index;
389
390        let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
391
392        // fetch the items using the invidious api
393        match page {
394            Page::MainMenu(MainMenuPage::Trending) => {
395                self.items = SearchProviderWrapper::trending()?
396                    .into_iter()
397                    .map(|item| Item::from_common_video(item, image_index))
398                    .collect();
399            }
400            Page::MainMenu(MainMenuPage::Popular) => {
401                self.items = SearchProviderWrapper::popular()?
402                    .into_iter()
403                    .map(|item| Item::from_popular_item(item, image_index))
404                    .collect();
405            }
406            Page::MainMenu(MainMenuPage::Library) => {
407                let history = framework.data.global.get::<Library>().unwrap();
408                self.items = history.0.clone().into_iter().rev().collect();
409            }
410            Page::MainMenu(MainMenuPage::History) => {
411                // the vector needs to be reversed because the latest watch history is pushed to
412                // the back, meaning it needs to be reversed so that the latests one are on top
413                let history = framework.data.global.get::<WatchHistory>().unwrap();
414                self.items = history.0.clone().into_iter().rev().collect();
415            }
416            Page::Search(search) => {
417                self.items = SearchProviderWrapper::search(search)?
418                    .into_iter()
419                    .map(|item| Item::from_search_item(item, image_index))
420                    .filter(|item| {
421                        let channel_id = match item.clone() {
422                            Item::MiniVideo(video) => Some(video.channel_id),
423                            Item::MiniPlaylist(playlist) => Some(playlist.channel_id),
424                            Item::MiniChannel(channel) => Some(channel.id),
425                            Item::FullVideo(video) => Some(video.channel_id),
426                            Item::FullPlaylist(playlist) => Some(playlist.channel_id),
427                            Item::FullChannel(channel) => Some(channel.id),
428                            _ => None,
429                        };
430
431                        !channel_id.is_some_and(|channel_id| {
432                            mainconfig.block_list.channels.contains(&channel_id)
433                        })
434                    })
435                    .collect();
436                if !self.items.is_empty() {
437                    self.items.push(Item::Page(true));
438                }
439                if search.page != 1 {
440                    self.items.insert(0, Item::Page(false));
441                }
442            }
443            _ => unreachable!("item `ItemList` cannot be used in `{page:?}`"),
444        }
445
446        // update the items in text list
447        self.textlist.set_items(&self.items).unwrap();
448        self.update(framework);
449
450        let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
451        let status = framework.data.global.get::<Status>().unwrap();
452        if mainconfig.images.display() {
453            // download thumbnails of all videos in the list
454            download_all_images(self.items.iter().map(|item| item.into()).collect());
455        }
456
457        set_envs(
458            self.infalte_item_update(mainconfig, status).into_iter(),
459            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
460        );
461        update_provider(framework.data);
462
463        Ok(())
464    }
465
466    fn key_event(
467        &mut self,
468        framework: &mut tui_additions::framework::FrameworkClean,
469        key: crossterm::event::KeyEvent,
470        _info: tui_additions::framework::ItemInfo,
471    ) -> Result<(), Box<dyn Error>> {
472        let action = if let Some(action) = framework
473            .data
474            .global
475            .get::<KeyBindingsConfig>()
476            .unwrap()
477            .get(key)
478        {
479            action
480        } else {
481            return Ok(());
482        };
483
484        // move the textlist cursor in the corresponding directions
485        let updated = match action {
486            KeyAction::MoveUp => self.textlist.up().is_ok(),
487            KeyAction::MoveDown => self.textlist.down().is_ok(),
488            KeyAction::MoveLeft | KeyAction::First => self.textlist.first().is_ok(),
489            KeyAction::MoveRight | KeyAction::End => self.textlist.last().is_ok(),
490            KeyAction::Select => {
491                self.select_at_cursor(framework);
492                false
493            }
494            _ => false,
495        };
496
497        // only create a render task if the key event actually changed something
498        if updated && !self.items.is_empty() {
499            self.update(framework);
500            set_envs(
501                self.infalte_item_update(
502                    framework.data.global.get::<MainConfig>().unwrap(),
503                    framework.data.global.get::<Status>().unwrap(),
504                )
505                .into_iter(),
506                &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
507            );
508
509            framework
510                .data
511                .global
512                .get_mut::<Status>()
513                .unwrap()
514                .render_image = true;
515            self.info.item = Some(self.items[self.textlist.selected].clone());
516            framework
517                .data
518                .state
519                .get_mut::<Tasks>()
520                .unwrap()
521                .priority
522                .push(Task::RenderAll);
523        }
524
525        Ok(())
526    }
527
528    fn mouse_event(
529        &mut self,
530        framework: &mut tui_additions::framework::FrameworkClean,
531        x: u16,
532        y: u16,
533        _absolute_x: u16,
534        _absolute_y: u16,
535    ) -> bool {
536        let chunk = self
537            .grid
538            .chunks(
539                if let Some(prev_frame) = framework.data.global.get::<Status>().unwrap().prev_frame
540                {
541                    prev_frame
542                } else {
543                    return false;
544                },
545            )
546            .unwrap()[0][0];
547
548        if !chunk.intersects(Rect::new(x, y, 1, 1)) {
549            return false;
550        }
551
552        let previously_selected = self.textlist.selected;
553        let y = (y - chunk.y) as usize + self.textlist.scroll;
554
555        // clicking on already selected item
556        if y == self.textlist.selected
557            || y == self.textlist.selected + 2
558            || y == self.textlist.selected + 1
559        {
560            self.select_at_cursor(framework);
561            return true;
562        }
563
564        // clicking on rows after the last item
565        if y > self.textlist.items.len() + 1 {
566            let _ = self.textlist.last();
567        } else if y <= self.textlist.selected {
568            self.textlist.selected = y;
569        } else if y >= self.textlist.selected + 2 {
570            self.textlist.selected = y - 2;
571        }
572
573        if self.textlist.selected == previously_selected {
574            return false;
575        }
576
577        self.update(framework);
578        set_envs(
579            self.infalte_item_update(
580                framework.data.global.get::<MainConfig>().unwrap(),
581                framework.data.global.get::<Status>().unwrap(),
582            )
583            .into_iter(),
584            &mut framework.data.state.get_mut::<StateEnvs>().unwrap().0,
585        );
586
587        // render the new image
588        framework
589            .data
590            .global
591            .get_mut::<Status>()
592            .unwrap()
593            .render_image = true;
594
595        true
596    }
597}
598
599impl ItemList {
600    // change `self.item` to the currently selected item
601    pub fn update(&mut self, framework: &mut FrameworkClean) {
602        let selected = self.items.get(self.textlist.selected);
603
604        if selected.is_none() {
605            return;
606        }
607
608        if matches!(selected, Some(Item::Page(_))) {
609            framework
610                .data
611                .global
612                .get_mut::<Status>()
613                .unwrap()
614                .render_image = true;
615            framework
616                .data
617                .state
618                .get_mut::<Tasks>()
619                .unwrap()
620                .priority
621                .push(Task::ClearPage);
622            self.info.item = None;
623            return;
624        }
625
626        self.info.item = Some(self.items[self.textlist.selected].clone());
627    }
628}