src/items/itemlist.rs

469 lines · 15907 bytes

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