src/config/pages.rs

314 lines · 10221 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 search filters `...` button, displays a popup when selected
173    SearchFilters,
174    /// playlist and video info display
175    SingleItemInfo,
176    /// displays channel info
177    ChannelDisplay,
178    /// button which loads the main channel page
179    ChannelMain,
180    /// button which loads the channel videos page
181    ChannelVideos,
182    /// button which loads the channel playlists page
183    ChannelPlaylists,
184}
185
186impl PageItems {
187    /// Converts `Self` into a `FrameworkItem` to be used in `State`
188    pub fn to_framework_item(&self, _framework: &mut Framework) -> Box<dyn FrameworkItem> {
189        match *self {
190            Self::SearchBar => Box::new(SearchBar::default()),
191            Self::Popular => Box::new(PageButton::Popular),
192            Self::Trending => Box::new(PageButton::Trending),
193            Self::History => Box::new(PageButton::History),
194            Self::MessageBar => Box::new(MessageBar::default()),
195            Self::ItemList => Box::new(ItemList::default()),
196            Self::SearchFilters => Box::new(SearchFilter::default()),
197            Self::SingleItemInfo => Box::new(SingleItem::default()),
198            Self::ChannelDisplay => Box::new(ChannelDisplay::default()),
199            Self::ChannelMain => Box::new(PageButton::ChannelMain),
200            Self::ChannelVideos => Box::new(PageButton::ChannelVideos),
201            Self::ChannelPlaylists => Box::new(PageButton::ChannelPlaylists),
202        }
203    }
204
205    pub fn width(&self) -> Constraint {
206        match self {
207            Self::Popular
208            | Self::Trending
209            | Self::History
210            | Self::ChannelMain
211            | Self::ChannelVideos
212            | Self::ChannelPlaylists => Constraint::Length(15),
213            Self::SearchBar => Constraint::Min(16),
214            Self::MessageBar => Constraint::Min(3),
215            Self::ItemList | Self::SingleItemInfo | Self::ChannelDisplay => Constraint::Min(9),
216            Self::SearchFilters => Constraint::Length(5),
217        }
218    }
219
220    pub fn height(&self) -> Constraint {
221        match self {
222            Self::Popular
223            | Self::History
224            | Self::ChannelMain
225            | Self::ChannelVideos
226            | Self::ChannelPlaylists
227            | Self::Trending
228            | Self::MessageBar
229            | Self::SearchBar
230            | Self::SearchFilters => Constraint::Length(3),
231            Self::ItemList | Self::SingleItemInfo | Self::ChannelDisplay => Constraint::Min(6),
232        }
233    }
234}
235
236fn constraint_to_u16(constraint: &Constraint) -> u16 {
237    match constraint {
238        Constraint::Max(length) | Constraint::Min(length) | Constraint::Length(length) => *length,
239        _ => unreachable!("only `Max`, `Min`, `Length` can be used as item length"),
240    }
241}
242
243fn max_constraint(constraints: &[Constraint]) -> Constraint {
244    let mut max_out = Constraint::Length(0);
245    let mut max = 0_u16;
246
247    constraints.iter().for_each(|constraint| {
248        let self_len = constraint_to_u16(constraint);
249        if self_len > max {
250            max = self_len;
251            max_out = *constraint;
252        }
253    });
254
255    max_out
256}
257
258// default functions
259
260fn main_menu_default() -> PageConfig {
261    PageConfig {
262        layout: vec![
263            PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
264            PageRow::from_vec(
265                vec![PageItems::Popular, PageItems::Trending, PageItems::History],
266                true,
267            ),
268            PageRow::from_vec(vec![PageItems::ItemList], false),
269            PageRow::from_vec(vec![PageItems::MessageBar], false),
270        ],
271        message: String::from("Loading main menu..."),
272    }
273}
274
275fn search_default() -> PageConfig {
276    PageConfig {
277        layout: vec![
278            PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
279            PageRow::from_vec(vec![PageItems::ItemList], false),
280            PageRow::from_vec(vec![PageItems::MessageBar], false),
281        ],
282        message: String::from("Loading search results..."),
283    }
284}
285
286fn singleitem_default() -> PageConfig {
287    PageConfig {
288        layout: vec![
289            PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
290            PageRow::from_vec(vec![PageItems::SingleItemInfo], false),
291            PageRow::from_vec(vec![PageItems::MessageBar], false),
292        ],
293        message: String::from("Loading item details..."),
294    }
295}
296
297fn channeldisplay_default() -> PageConfig {
298    PageConfig {
299        layout: vec![
300            PageRow::from_vec(vec![PageItems::SearchBar, PageItems::SearchFilters], false),
301            PageRow::from_vec(
302                vec![
303                    PageItems::ChannelMain,
304                    PageItems::ChannelVideos,
305                    PageItems::ChannelPlaylists,
306                ],
307                true,
308            ),
309            PageRow::from_vec(vec![PageItems::ChannelDisplay], false),
310            PageRow::from_vec(vec![PageItems::MessageBar], false),
311        ],
312        message: String::from("Loading channel details..."),
313    }
314}