src/items/itemlist.rs

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