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