src/config/pages.rs

324 lines · 10612 bytes

  1use crate::{
  2    global::traits::ConfigTrait,
  3    items::{
  4        ChannelDisplay, ItemList, MessageBar, PageButton, SearchBar, SearchFilter, SingleItem,
  5    },
  6};
  7use serde::{Deserialize, Serialize};
  8use std::slice;
  9use tui::layout::Constraint;
 10use tui_additions::framework::{Framework, FrameworkItem, Row, RowItem, State};
 11use typemap::Key;
 12
 13/// Minimum screen dimention for the tui to display without panicking, stored in `data.state`
 14// is automatically generated from PageConfig
 15#[derive(Clone, Copy, Default)]
 16pub struct MinDimentions {
 17    pub width: u16,
 18    pub height: u16,
 19}
 20
 21impl MinDimentions {
 22    pub const fn new(width: u16, height: u16) -> Self {
 23        Self { width, height }
 24    }
 25}
 26
 27impl Key for MinDimentions {
 28    type Value = Self;
 29}
 30
 31/// Layout for all pages
 32#[derive(Clone, Serialize, Deserialize)]
 33pub struct PagesConfig {
 34    #[serde(default = "main_menu_default")]
 35    pub main_menu: PageConfig,
 36    #[serde(default = "search_default")]
 37    pub search: PageConfig,
 38    #[serde(default = "singleitem_default")]
 39    pub singleitem: PageConfig,
 40    #[serde(default = "channeldisplay_default")]
 41    pub channeldisplay: PageConfig,
 42}
 43
 44impl Key for PagesConfig {
 45    type Value = Self;
 46}
 47
 48impl ConfigTrait for PagesConfig {
 49    const LABEL: &'static str = "pages";
 50}
 51
 52impl Default for PagesConfig {
 53    fn default() -> Self {
 54        Self {
 55            main_menu: main_menu_default(),
 56            search: search_default(),
 57            singleitem: singleitem_default(),
 58            channeldisplay: channeldisplay_default(),
 59        }
 60    }
 61}
 62
 63// This struct impls Into<State>,  the corresponding page is converted into State on page load
 64// Each page has its own minimum width and height, which is automatically determined by the items in the page
 65// If it doesn't meet the minimum dimentions, a "protective screen" will be shown to prevent panicking
 66/// Layout for one single page
 67#[derive(Clone, Serialize, Deserialize)]
 68pub struct PageConfig {
 69    pub layout: Vec<PageRow>,
 70    pub message: String,
 71}
 72
 73impl PageConfig {
 74    /// Calculates minimum width for all items to display
 75    pub fn min_width(&self) -> u16 {
 76        self.layout
 77            .iter()
 78            .map(|row| {
 79                row.iter()
 80                    .map(|item| constraint_to_u16(&item.width()))
 81                    .sum::<u16>()
 82            })
 83            .max()
 84            .unwrap()
 85    }
 86
 87    /// Calculates minimum height for all items to display
 88    pub fn min_height(&self) -> u16 {
 89        self.layout
 90            .iter()
 91            .map(|row| {
 92                row.iter()
 93                    .map(|item| constraint_to_u16(&item.height()))
 94                    .max()
 95                    .unwrap()
 96            })
 97            .sum::<u16>()
 98    }
 99
100    /// Converts itself into `State` to be used in `Framework`
101    pub fn to_state(&self, framework: &mut Framework) -> State {
102        State(
103            self.layout
104                .iter()
105                .map(|row| Row {
106                    centered: row.is_centered(),
107                    height: max_constraint(
108                        &row.iter().map(|item| item.height()).collect::<Vec<_>>(),
109                    ),
110                    items: row
111                        .iter()
112                        .map(|item| RowItem {
113                            item: item.to_framework_item(framework),
114                            width: item.width(),
115                        })
116                        .collect::<Vec<_>>(),
117                })
118                .collect::<Vec<_>>(),
119        )
120    }
121}
122
123/// CenteredRow will have its items centered, while NonCenteredRow will align to the left
124#[derive(Clone, Serialize, Deserialize)]
125#[serde(tag = "type", content = "items")]
126pub enum PageRow {
127    CenteredRow(Vec<PageItems>),
128    NonCenteredRow(Vec<PageItems>),
129}
130
131impl PageRow {
132    pub fn iter(&self) -> slice::Iter<PageItems> {
133        match self {
134            Self::CenteredRow(iter) | Self::NonCenteredRow(iter) => iter.iter(),
135        }
136    }
137
138    pub fn is_centered(&self) -> bool {
139        match self {
140            Self::CenteredRow(_) => true,
141            Self::NonCenteredRow(_) => false,
142        }
143    }
144
145    pub fn from_vec(items: Vec<PageItems>, centered: bool) -> Self {
146        if centered {
147            Self::CenteredRow(items)
148        } else {
149            Self::NonCenteredRow(items)
150        }
151    }
152}
153
154// PageItems will be converted into Box<dyn FrameworkItem> on page load to be used an item in the framework
155// Seen https://docs.rs/tui-additions/latest/tui_additions/framework/trait.FrameworkItem.html
156// Each item has a minimum width and height for it to render without panicking
157/// All avaliable items for `PageConfig`
158#[derive(Clone, Copy, Serialize, Deserialize)]
159pub enum PageItems {
160    /// the search bar
161    SearchBar,
162    /// a list of item e.g. in the main menu or search items
163    ItemList,
164    /// the bottom panel which optionally displays a text
165    MessageBar,
166    /// the trending button which loads the trending page
167    Trending,
168    /// the popular button which loads the popular page
169    Popular,
170    /// the history button which loads the watch history page
171    History,
172    /// the subscriptions button which loads the subscriptions page
173    Subscriptions,
174    /// the library button which loads the saved page
175    Library,
176    /// the search filters `...` button, displays a popup when selected
177    SearchFilters,
178    /// playlist and video info display
179    SingleItemInfo,
180    /// displays channel info
181    ChannelDisplay,
182    /// button which loads the main channel page
183    ChannelMain,
184    /// button which loads the channel videos page
185    ChannelVideos,
186    /// button which loads the channel playlists page
187    ChannelPlaylists,
188}
189
190impl PageItems {
191    /// Converts `Self` into a `FrameworkItem` to be used in `State`
192    pub fn to_framework_item(&self, _framework: &mut Framework) -> Box<dyn FrameworkItem> {
193        match *self {
194            Self::SearchBar => Box::<SearchBar>::default(),
195            Self::Popular => Box::new(PageButton::Popular),
196            Self::Trending => Box::new(PageButton::Trending),
197            Self::History => Box::new(PageButton::History),
198            Self::Subscriptions => Box::new(PageButton::Subscriptions),
199            Self::Library => Box::new(PageButton::Library),
200            Self::MessageBar => Box::<MessageBar>::default(),
201            Self::ItemList => Box::<ItemList>::default(),
202            Self::SearchFilters => Box::<SearchFilter>::default(),
203            Self::SingleItemInfo => Box::<SingleItem>::default(),
204            Self::ChannelDisplay => Box::<ChannelDisplay>::default(),
205            Self::ChannelMain => Box::new(PageButton::ChannelMain),
206            Self::ChannelVideos => Box::new(PageButton::ChannelVideos),
207            Self::ChannelPlaylists => Box::new(PageButton::ChannelPlaylists),
208        }
209    }
210
211    pub fn width(&self) -> Constraint {
212        match self {
213            Self::Popular
214            | Self::Trending
215            | Self::History
216            | Self::Subscriptions
217            | Self::Library
218            | Self::ChannelMain
219            | Self::ChannelVideos
220            | Self::ChannelPlaylists => Constraint::Length(15),
221            Self::SearchBar => Constraint::Min(16),
222            Self::MessageBar => Constraint::Min(3),
223            Self::ItemList | Self::SingleItemInfo | Self::ChannelDisplay => Constraint::Min(9),
224            Self::SearchFilters => Constraint::Length(5),
225        }
226    }
227
228    pub fn height(&self) -> Constraint {
229        match self {
230            Self::Popular
231            | Self::History
232            | Self::Subscriptions
233            | Self::Library
234            | Self::ChannelMain
235            | Self::ChannelVideos
236            | Self::ChannelPlaylists
237            | Self::Trending
238            | Self::MessageBar
239            | Self::SearchBar
240            | Self::SearchFilters => Constraint::Length(3),
241            Self::ItemList | Self::SingleItemInfo | Self::ChannelDisplay => Constraint::Min(6),
242        }
243    }
244}
245
246fn constraint_to_u16(constraint: &Constraint) -> u16 {
247    match constraint {
248        Constraint::Max(length) | Constraint::Min(length) | Constraint::Length(length) => *length,
249        _ => unreachable!("only `Max`, `Min`, `Length` can be used as item length"),
250    }
251}
252
253fn max_constraint(constraints: &[Constraint]) -> Constraint {
254    let mut max_out = Constraint::Length(0);
255    let mut max = 0_u16;
256
257    constraints.iter().for_each(|constraint| {
258        let self_len = constraint_to_u16(constraint);
259        if self_len > max {
260            max = self_len;
261            max_out = *constraint;
262        }
263    });
264
265    max_out
266}
267
268// default functions
269
270fn main_menu_default() -> PageConfig {
271    PageConfig {
272        layout: vec![
273            PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
274            PageRow::from_vec(
275                vec![PageItems::Popular, PageItems::Library, PageItems::History],
276                true,
277            ),
278            PageRow::from_vec(vec![PageItems::ItemList], false),
279            PageRow::from_vec(vec![PageItems::MessageBar], false),
280        ],
281        message: String::from("Loading main menu..."),
282    }
283}
284
285fn search_default() -> PageConfig {
286    PageConfig {
287        layout: vec![
288            PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
289            PageRow::from_vec(vec![PageItems::ItemList], false),
290            PageRow::from_vec(vec![PageItems::MessageBar], false),
291        ],
292        message: String::from("Loading search results..."),
293    }
294}
295
296fn singleitem_default() -> PageConfig {
297    PageConfig {
298        layout: vec![
299            PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
300            PageRow::from_vec(vec![PageItems::SingleItemInfo], false),
301            PageRow::from_vec(vec![PageItems::MessageBar], false),
302        ],
303        message: String::from("Loading item details..."),
304    }
305}
306
307fn channeldisplay_default() -> PageConfig {
308    PageConfig {
309        layout: vec![
310            PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
311            PageRow::from_vec(
312                vec![
313                    PageItems::ChannelMain,
314                    PageItems::ChannelVideos,
315                    PageItems::ChannelPlaylists,
316                ],
317                true,
318            ),
319            PageRow::from_vec(vec![PageItems::ChannelDisplay], false),
320            PageRow::from_vec(vec![PageItems::MessageBar], false),
321        ],
322        message: String::from("Loading channel details..."),
323    }
324}