src/items/itemlist.rs

291 lines · 9989 bytes

  1use std::error::Error;
  2
  3use tui::{layout::Constraint, style::Style};
  4use tui_additions::{
  5    framework::FrameworkItem,
  6    widgets::{Grid, TextList},
  7};
  8
  9use super::ItemInfo;
 10use crate::{
 11    config::{AppearanceConfig, KeyBindingsConfig, MainConfig},
 12    global::{
 13        functions::download_all_images,
 14        structs::{
 15            ChannelDisplayPage, ChannelDisplayPageType, FullPlaylistItem, FullVideoItem,
 16            InvidiousClient, Item, KeyAction, MainMenuPage, MiniChannelItem, MiniPlaylistItem,
 17            MiniVideoItem, Page, SingleItemPage, Task, Tasks, WatchHistory,
 18        },
 19    },
 20};
 21
 22/// An item list displays a list of items
 23// 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
 24#[derive(Clone)]
 25pub struct ItemList {
 26    pub info: ItemInfo,
 27    pub items: Vec<Item>,
 28    pub textlist: TextList,
 29    pub grid: Grid,
 30}
 31
 32impl ItemList {
 33    /// updates the styles of different things that may be updated by deselect/selects
 34    fn update_appearance(
 35        &mut self,
 36        appearance: &AppearanceConfig,
 37        mainconfig: &MainConfig,
 38        iteminfo: &tui_additions::framework::ItemInfo,
 39    ) {
 40        self.textlist.set_ascii_only(!mainconfig.allow_unicode);
 41        self.grid.set_border_type(appearance.borders);
 42        self.textlist.set_border_type(appearance.borders);
 43        self.textlist
 44            .set_style(Style::default().fg(appearance.colors.text));
 45
 46        if iteminfo.selected {
 47            self.grid
 48                .set_border_style(Style::default().fg(appearance.colors.outline_selected));
 49            self.textlist
 50                .set_cursor_style(Style::default().fg(appearance.colors.outline_hover));
 51            self.textlist
 52                .set_selected_style(Style::default().fg(appearance.colors.text_special));
 53        } else {
 54            self.textlist
 55                .set_cursor_style(Style::default().fg(appearance.colors.outline_secondary));
 56            self.textlist
 57                .set_selected_style(Style::default().fg(appearance.colors.text_secondary));
 58            if iteminfo.hover {
 59                self.grid
 60                    .set_border_style(Style::default().fg(appearance.colors.outline_hover));
 61            } else {
 62                self.grid
 63                    .set_border_style(Style::default().fg(appearance.colors.outline));
 64            }
 65        }
 66    }
 67}
 68
 69impl Default for ItemList {
 70    fn default() -> Self {
 71        Self {
 72            info: ItemInfo::default(),
 73            items: Vec::new(),
 74            textlist: TextList::default().non_ascii_replace(' '),
 75            grid: Grid::new(
 76                vec![Constraint::Percentage(60), Constraint::Percentage(40)],
 77                vec![Constraint::Percentage(100)],
 78            )
 79            .unwrap(),
 80        }
 81    }
 82}
 83
 84impl FrameworkItem for ItemList {
 85    fn render(
 86        &mut self,
 87        frame: &mut tui::Frame<tui::backend::CrosstermBackend<std::io::Stdout>>,
 88        framework: &mut tui_additions::framework::FrameworkClean,
 89        area: tui::layout::Rect,
 90        popup_render: bool,
 91        info: tui_additions::framework::ItemInfo,
 92    ) {
 93        if popup_render {
 94            return;
 95        }
 96
 97        let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
 98        let mainconfig = framework.data.global.get::<MainConfig>().unwrap();
 99        self.update_appearance(appearance, mainconfig, &info);
100
101        // creates the grid
102        let grid = self.grid.clone();
103        let chunks = grid.chunks(area).unwrap()[0].clone();
104
105        // creates the text list in cell (0, 1)
106        self.textlist.set_height(chunks[0].height);
107        self.textlist
108            .set_cursor_style(Style::default().fg(if info.selected {
109                appearance.colors.outline_hover
110            } else {
111                appearance.colors.outline_secondary
112            }));
113
114        let textlist = self.textlist.clone();
115
116        frame.render_widget(grid, area);
117        frame.render_widget(textlist, chunks[0]);
118
119        // used the `.render()` function in self.info because it is an ItemInfo and impls FrameworkItem instead of Widget
120        self.info
121            .render(frame, framework, chunks[1], popup_render, info);
122    }
123
124    fn selectable(&self) -> bool {
125        true
126    }
127
128    fn load_item(
129        &mut self,
130        framework: &mut tui_additions::framework::FrameworkClean,
131        _info: tui_additions::framework::ItemInfo,
132    ) -> Result<(), Box<dyn Error>> {
133        *self = Self::default();
134
135        let page = framework.data.state.get::<Page>().unwrap();
136        let image_index = framework
137            .data
138            .global
139            .get::<MainConfig>()
140            .unwrap()
141            .image_index;
142        let client = &framework.data.global.get::<InvidiousClient>().unwrap().0;
143
144        // fetch the items using the invidious api
145        match page {
146            Page::MainMenu(MainMenuPage::Trending) => {
147                self.items = client
148                    .trending(None)?
149                    .videos
150                    .into_iter()
151                    .map(|item| Item::from_trending_video(item, image_index))
152                    .collect();
153            }
154            Page::MainMenu(MainMenuPage::Popular) => {
155                self.items = client
156                    .popular(None)?
157                    .items
158                    .into_iter()
159                    .map(|item| Item::from_popular_item(item, image_index))
160                    .collect();
161            }
162            Page::MainMenu(MainMenuPage::History) => {
163                // the vector needs to be reversed because the latest watch history is pushed to
164                // the back, meaning it needs to be reversed so that the latests one are on top
165                self.items = framework
166                    .data
167                    .global
168                    .get::<WatchHistory>()
169                    .unwrap()
170                    .0
171                    .clone()
172                    .into_iter()
173                    .rev()
174                    .collect();
175            }
176            Page::Search(search) => {
177                self.items = client
178                    .search(Some(&search.to_string()))?
179                    .items
180                    .into_iter()
181                    .map(|item| Item::from_search_item(item, image_index))
182                    .collect();
183            }
184            _ => unreachable!("item `ItemList` cannot be used in `{page:?}`"),
185        }
186
187        if framework
188            .data
189            .global
190            .get::<MainConfig>()
191            .unwrap()
192            .images
193            .display()
194        {
195            // download thumbnails of all videos in the list
196            download_all_images(self.items.iter().map(|item| item.into()).collect());
197        }
198
199        // update the items in text list
200        self.textlist.set_items(&self.items).unwrap();
201        self.update();
202
203        Ok(())
204    }
205
206    fn key_event(
207        &mut self,
208        framework: &mut tui_additions::framework::FrameworkClean,
209        key: crossterm::event::KeyEvent,
210        _info: tui_additions::framework::ItemInfo,
211    ) -> Result<(), Box<dyn Error>> {
212        let action = if let Some(keyactions) = framework
213            .data
214            .global
215            .get::<KeyBindingsConfig>()
216            .unwrap()
217            .0
218            .get(&key.code)
219        {
220            if let Some(action) = keyactions.get(&key.modifiers.bits()) {
221                *action
222            } else {
223                return Ok(());
224            }
225        } else {
226            return Ok(());
227        };
228
229        // move the textlist cursor in the corresponding directions
230        let updated = match action {
231            KeyAction::MoveUp => self.textlist.up().is_ok(),
232            KeyAction::MoveDown => self.textlist.down().is_ok(),
233            KeyAction::MoveLeft => self.textlist.first().is_ok(),
234            KeyAction::MoveRight => self.textlist.last().is_ok(),
235            KeyAction::Select => {
236                let page_to_load = match &self.items[self.textlist.selected] {
237                    Item::MiniVideo(MiniVideoItem { id, .. })
238                    | Item::FullVideo(FullVideoItem { id, .. }) => {
239                        Page::SingleItem(SingleItemPage::Video(id.clone()))
240                    }
241                    Item::MiniPlaylist(MiniPlaylistItem { id, .. })
242                    | Item::FullPlaylist(FullPlaylistItem { id, .. }) => {
243                        Page::SingleItem(SingleItemPage::Playlist(id.clone()))
244                    }
245                    Item::MiniChannel(MiniChannelItem { id, .. }) => {
246                        Page::ChannelDisplay(ChannelDisplayPage {
247                            id: id.clone(),
248                            r#type: ChannelDisplayPageType::Main,
249                        })
250                    }
251                    _ => panic!("wtf did you just selected"),
252                };
253                framework
254                    .data
255                    .state
256                    .get_mut::<Tasks>()
257                    .unwrap()
258                    .priority
259                    .push(Task::LoadPage(page_to_load));
260                false
261            }
262            _ => false,
263        };
264
265        // only create a render task if the key event actually changed something
266        if updated {
267            self.info.item = Some(self.items[self.textlist.selected].clone());
268            framework
269                .data
270                .state
271                .get_mut::<Tasks>()
272                .unwrap()
273                .priority
274                .push(Task::RenderAll);
275        }
276
277        Ok(())
278    }
279}
280
281impl ItemList {
282    // change `self.item` to the currently selected item
283    pub fn update(&mut self) {
284        if self.items.is_empty() {
285            self.info.item = None;
286            return;
287        }
288
289        self.info.item = Some(self.items[self.textlist.selected].clone());
290    }
291}