src/config/pages.rs

db597a03bc7a1786d5261e8a55628da30193c775
youtube-tui/src/config/pages.rs history · blame · raw

221 lines · 6317 bytes

  1use super::ConfigTrait;
  2use crate::items::{ItemList, MessageBar, PageButton, SearchBar};
  3use serde::{Deserialize, Serialize};
  4use std::slice;
  5use tui::layout::Constraint;
  6use tui_additions::framework::{Framework, FrameworkItem, Row, RowItem, State};
  7use typemap::Key;
  8
  9// Minimum screen dimention for the tui to display without panicking,
 10// is automatically generated from PageConfig
 11// will be inserted into `framework.data.state`
 12#[derive(Clone, Copy)]
 13pub struct MinDimentions {
 14    pub width: u16,
 15    pub height: u16,
 16}
 17
 18impl MinDimentions {
 19    pub const fn new(width: u16, height: u16) -> Self {
 20        Self { width, height }
 21    }
 22}
 23
 24impl Default for MinDimentions {
 25    fn default() -> Self {
 26        Self {
 27            width: 0,
 28            height: 0,
 29        }
 30    }
 31}
 32
 33impl Key for MinDimentions {
 34    type Value = Self;
 35}
 36
 37#[derive(Clone, Serialize, Deserialize)]
 38pub struct PagesConfig {
 39    #[serde(default = "main_menu_default")]
 40    pub main_menu: PageConfig,
 41}
 42
 43impl Key for PagesConfig {
 44    type Value = Self;
 45}
 46
 47impl ConfigTrait for PagesConfig {
 48    const LABEL: &'static str = "pages";
 49}
 50
 51impl Default for PagesConfig {
 52    fn default() -> Self {
 53        Self {
 54            main_menu: main_menu_default(),
 55        }
 56    }
 57}
 58
 59// This struct impls Into<State>,  the corresponding page is converted into State on page load
 60// Each page has its own minimum width and height, which is automatically determined by the items in the page
 61// If it doesn't meet the minimum dimentions, a "protective screen" will be shown to prevent panicking
 62#[derive(Clone, Serialize, Deserialize)]
 63pub struct PageConfig {
 64    pub layout: Vec<PageRow>,
 65    pub message: String,
 66}
 67
 68impl PageConfig {
 69    pub fn min_width(&self) -> u16 {
 70        self.layout
 71            .iter()
 72            .map(|row| {
 73                row.iter()
 74                    .map(|item| constraint_to_u16(&item.width()))
 75                    .sum::<u16>()
 76            })
 77            .max()
 78            .unwrap()
 79    }
 80
 81    pub fn min_height(&self) -> u16 {
 82        self.layout
 83            .iter()
 84            .map(|row| {
 85                row.iter()
 86                    .map(|item| constraint_to_u16(&item.height()))
 87                    .max()
 88                    .unwrap()
 89            })
 90            .sum::<u16>()
 91    }
 92
 93    pub fn to_state(&self, framework: &mut Framework) -> State {
 94        State(
 95            self.layout
 96                .iter()
 97                .map(|row| Row {
 98                    centered: row.is_centered(),
 99                    height: max_constraint(
100                        &row.iter().map(|item| item.height()).collect::<Vec<_>>(),
101                    ),
102                    items: row
103                        .iter()
104                        .map(|item| RowItem {
105                            item: item.to_framework_item(framework),
106                            width: item.width(),
107                        })
108                        .collect::<Vec<_>>(),
109                })
110                .collect::<Vec<_>>(),
111        )
112    }
113}
114
115// CenteredRow will have its items centered, while NonCenteredRow will align to the left
116#[derive(Clone, Serialize, Deserialize)]
117pub enum PageRow {
118    CenteredRow(Vec<PageItems>),
119    NonCenteredRow(Vec<PageItems>),
120}
121
122impl PageRow {
123    pub fn iter(&self) -> slice::Iter<PageItems> {
124        match self {
125            Self::CenteredRow(iter) | Self::NonCenteredRow(iter) => iter.iter(),
126        }
127    }
128
129    pub fn is_centered(&self) -> bool {
130        match self {
131            Self::CenteredRow(_) => true,
132            Self::NonCenteredRow(_) => false,
133        }
134    }
135
136    pub fn from_vec(items: Vec<PageItems>, centered: bool) -> Self {
137        if centered {
138            Self::CenteredRow(items)
139        } else {
140            Self::NonCenteredRow(items)
141        }
142    }
143}
144
145// PageItems will be converted into Box<dyn FrameworkItem> on page load to be used an item in the framework
146// Seen https://docs.rs/tui-additions/latest/tui_additions/framework/trait.FrameworkItem.html
147// Each item has a minimum width and height for it to render without panicking
148#[derive(Clone, Copy, Serialize, Deserialize)]
149pub enum PageItems {
150    SearchBar,
151    ItemList,
152    MessageBar,
153    Trending,
154    Popular,
155}
156
157impl PageItems {
158    pub fn to_framework_item(&self, framework: &mut Framework) -> Box<dyn FrameworkItem> {
159        match *self {
160            PageItems::SearchBar => Box::new(SearchBar::default()),
161            PageItems::Popular => Box::new(PageButton::Popular),
162            PageItems::Trending => Box::new(PageButton::Trending),
163            PageItems::MessageBar => Box::new(MessageBar::default()),
164            PageItems::ItemList => Box::new(ItemList::new(framework)),
165        }
166    }
167
168    pub fn width(&self) -> Constraint {
169        match self {
170            Self::Popular | Self::Trending => Constraint::Length(15),
171            Self::SearchBar => Constraint::Min(16),
172            Self::MessageBar => Constraint::Min(3),
173            Self::ItemList => Constraint::Min(6),
174        }
175    }
176
177    pub fn height(&self) -> Constraint {
178        match self {
179            Self::Popular | Self::Trending | Self::MessageBar | Self::SearchBar => {
180                Constraint::Length(3)
181            }
182            Self::ItemList => Constraint::Min(6),
183        }
184    }
185}
186
187fn constraint_to_u16(constraint: &Constraint) -> u16 {
188    match constraint {
189        Constraint::Max(length) | Constraint::Min(length) | Constraint::Length(length) => *length,
190        _ => unreachable!(),
191    }
192}
193
194fn max_constraint(constraints: &[Constraint]) -> Constraint {
195    let mut max_out = Constraint::Length(0);
196    let mut max = 0_u16;
197
198    constraints.iter().for_each(|constraint| {
199        let self_len = constraint_to_u16(constraint);
200        if self_len > max {
201            max = self_len;
202            max_out = *constraint;
203        }
204    });
205
206    max_out
207}
208
209// default functions
210
211fn main_menu_default() -> PageConfig {
212    PageConfig {
213        layout: vec![
214            PageRow::from_vec(vec![PageItems::SearchBar], false),
215            PageRow::from_vec(vec![PageItems::Trending, PageItems::Popular], true),
216            PageRow::from_vec(vec![PageItems::ItemList], false),
217            PageRow::from_vec(vec![PageItems::MessageBar], false),
218        ],
219        message: String::from("Loading main menu..."),
220    }
221}