src/config/pages.rs

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

357 lines · 11912 bytes

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