use super::key::Binding;
use crate::{Cmd, Msg};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Type {
#[default]
Arabic,
Dots,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyMap {
pub prev_page: Binding,
pub next_page: Binding,
}
impl Default for KeyMap {
fn default() -> Self {
Self {
prev_page: Binding::new(&["pgup", "left", "h"]),
next_page: Binding::new(&["pgdown", "right", "l"]),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Model {
pub kind: Type,
pub page: usize,
pub per_page: usize,
pub total_pages: usize,
pub active_dot: String,
pub inactive_dot: String,
pub arabic_format: String,
pub key_map: KeyMap,
}
impl Default for Model {
fn default() -> Self {
Self::new()
}
}
impl Model {
#[must_use]
pub fn new() -> Self {
Self {
kind: Type::Arabic,
page: 0,
per_page: 1,
total_pages: 1,
active_dot: "•".into(),
inactive_dot: "○".into(),
arabic_format: "%d/%d".into(),
key_map: KeyMap::default(),
}
}
pub const fn set_total_pages(&mut self, items: usize) -> usize {
if items < 1 || self.per_page < 1 {
return self.total_pages;
}
self.total_pages = items.div_ceil(self.per_page);
self.total_pages
}
#[must_use]
pub fn items_on_page(&self, total: usize) -> usize {
let (start, end) = self.slice_bounds(total);
end.saturating_sub(start)
}
#[must_use]
pub fn slice_bounds(&self, length: usize) -> (usize, usize) {
let start = self.page * self.per_page;
(start.min(length), (start + self.per_page).min(length))
}
pub const fn prev_page(&mut self) {
self.page = self.page.saturating_sub(1);
}
pub const fn next_page(&mut self) {
if !self.on_last_page() {
self.page += 1;
}
}
#[must_use]
pub const fn on_last_page(&self) -> bool {
self.page + 1 >= self.total_pages
}
#[must_use]
pub const fn on_first_page(&self) -> bool {
self.page == 0
}
pub fn update<M>(&mut self, msg: &Msg<M>) -> Cmd<M> {
if let Msg::KeyPress(key) = msg {
if self.key_map.next_page.matches(key) {
self.next_page();
} else if self.key_map.prev_page.matches(key) {
self.prev_page();
}
}
Cmd::none()
}
#[must_use]
pub fn view(&self) -> String {
match self.kind {
Type::Dots => (0..self.total_pages)
.map(|i| {
if i == self.page {
self.active_dot.as_str()
} else {
self.inactive_dot.as_str()
}
})
.collect(),
Type::Arabic => {
let page = (self.page + 1).to_string();
let total = self.total_pages.to_string();
self.arabic_format
.replacen("%d", &page, 1)
.replacen("%d", &total, 1)
}
}
}
}
#[cfg(test)]
mod tests;