src/items/itemlist.rs

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