use iced::Task;
#[derive(Debug, Clone)]
pub(crate) struct PaginationState {
pub(crate) page: usize,
pub(crate) page_size: usize,
pub(crate) total: usize,
}
impl PaginationState {
pub(crate) const fn new(page_size: usize) -> Self {
Self {
page: 0,
page_size,
total: 0,
}
}
pub(crate) const fn total_pages(&self) -> usize {
if self.total == 0 {
0
} else {
self.total.div_ceil(self.page_size)
}
}
pub(crate) fn prev_page(&mut self) -> bool {
if self.page > 0 {
self.page -= 1;
true
} else {
false
}
}
pub(crate) fn next_page(&mut self) -> bool {
if self.page + 1 < self.total_pages() {
self.page += 1;
true
} else {
false
}
}
pub(crate) fn reset(&mut self) {
self.page = 0;
}
pub(crate) fn offset(&self) -> usize {
self.page * self.page_size
}
}
#[derive(Debug, Clone)]
pub(crate) struct AsyncLoadState {
loading: bool,
has_loaded: bool,
error: Option<String>,
}
impl AsyncLoadState {
pub(crate) const fn new() -> Self {
Self {
loading: false,
has_loaded: false,
error: None,
}
}
pub(crate) fn loading(&self) -> bool {
self.loading
}
pub(crate) fn has_loaded(&self) -> bool {
self.has_loaded
}
pub(crate) fn error(&self) -> Option<&str> {
self.error.as_deref()
}
pub(crate) fn start_loading(&mut self) {
self.loading = true;
self.error = None;
}
pub(crate) fn finish_loading(&mut self) {
self.loading = false;
self.has_loaded = true;
}
pub(crate) fn fail(&mut self, error: String) {
self.error = Some(error);
self.loading = false;
}
pub(crate) fn clear_error(&mut self) {
self.error = None;
}
pub(crate) fn set_has_loaded(&mut self) {
self.has_loaded = true;
}
}
#[derive(Debug, Clone)]
pub(crate) struct DebounceState {
generation: u64,
pending: bool,
}
impl DebounceState {
pub(crate) const fn new() -> Self {
Self {
generation: 0,
pending: false,
}
}
pub(crate) fn trigger(&mut self, ms: u64) -> Task<u64> {
self.generation = self.generation.wrapping_add(1);
self.pending = true;
let current = self.generation;
Task::perform(
super::widgets::debounce_sleep(ms, current),
std::convert::identity,
)
}
#[must_use]
pub(crate) fn should_process(&mut self, generation: u64) -> bool {
if generation == self.generation && self.pending {
self.pending = false;
true
} else {
false
}
}
}
pub(crate) fn none_if_empty(s: &str) -> Option<String> {
if s.is_empty() {
None
} else {
Some(s.to_string())
}
}