src/config/pages.rs

319 lines · 10454 bytes

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