functora-egui 0.2.0

shadcn/ui-inspired widget library for egui - buttons, inputs, selects, dialogs, and 70+ more components with light/dark theming
Documentation
use std::borrow::Cow;
use std::fmt::Display;
use std::str::FromStr;

use functora_core::i18n::Language;

pub const SCREEN_PARAM: &str = "screen";
pub const COMPONENT_PARAM: &str = "component";
pub const ROOT_PATH: &str = "/";

#[must_use]
pub fn resolve_history_url(pathname: &str, url: &str) -> String {
    if url == ROOT_PATH {
        pathname.to_owned()
    } else if let Some(query) = url.strip_prefix("/?") {
        format!("{pathname}?{query}")
    } else {
        url.to_owned()
    }
}

pub trait Routable:
    Display + FromStr + Clone + PartialEq + Eq + std::fmt::Debug + Send + Sync + 'static
{
    #[must_use]
    fn screen_param() -> &'static str {
        SCREEN_PARAM
    }
    #[must_use]
    fn to_slug(&self) -> String {
        self.to_string().to_lowercase()
    }
    #[must_use]
    fn to_url(&self) -> String
    where
        Self: Default,
    {
        if *self == Self::default() {
            ROOT_PATH.to_string()
        } else {
            format!(
                "/?{}={}",
                Self::screen_param(),
                urlencoding::encode(&self.to_slug())
            )
        }
    }
    #[must_use]
    fn from_url(url: &str) -> Option<Self>
    where
        Self: Default,
    {
        let query = url.split('?').nth(1).unwrap_or("");
        let params: std::collections::BTreeMap<String, String> =
            form_urlencoded::parse(query.as_bytes())
                .into_owned()
                .collect();
        let key = Self::screen_param();
        if let Some(screen) = params.get(key) {
            screen.parse().ok()
        } else if let Some(component) = params.get(COMPONENT_PARAM) {
            component.parse().ok()
        } else {
            None
        }
    }
}

impl<T> Routable for T where
    T: Display + FromStr + Clone + PartialEq + Eq + std::fmt::Debug + Send + Sync + 'static
{
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RouteKind {
    Page,
    Category,
    Modal,
    External,
}

pub trait RouteMetadata: Routable {
    fn label(&self, lang: Language) -> Cow<'static, str>;
    fn parent(&self) -> Option<Self>;
    fn children(&self) -> Vec<Self>;
    fn kind(&self) -> RouteKind {
        RouteKind::Page
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BreadcrumbPosition {
    Last,
    NotLast,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BreadcrumbSegment<R> {
    pub name: String,
    pub route: R,
    pub position: BreadcrumbPosition,
}

impl<R> BreadcrumbSegment<R> {
    #[must_use]
    pub fn is_last(&self) -> bool {
        self.position == BreadcrumbPosition::Last
    }
}

pub fn breadcrumbs_for<R>(route: &R, lang: Language) -> Vec<BreadcrumbSegment<R>>
where
    R: RouteMetadata + Clone,
{
    let mut chain = Vec::new();
    let mut current = Some(route.clone());
    while let Some(r) = current {
        if r.kind() != RouteKind::Category {
            chain.push(BreadcrumbSegment {
                name: r.label(lang).into_owned(),
                route: r.clone(),
                position: BreadcrumbPosition::NotLast,
            });
        }
        current = r.parent();
    }
    chain.reverse();
    if let Some(last) = chain.last_mut() {
        last.position = BreadcrumbPosition::Last;
    }
    chain
}

pub mod router_impl {
    use super::Routable;
    use crate::nav::NavHistory;

    pub struct AppRouter<R: Routable> {
        current: R,
        history: NavHistory<R>,
        system_back: bool,
    }

    impl<R> AppRouter<R>
    where
        R: Routable + Default,
    {
        #[must_use]
        pub fn new(default: &R) -> Self {
            let current = {
                #[cfg(all(target_arch = "wasm32", feature = "platform"))]
                {
                    crate::platform::web::location_href()
                        .and_then(|u| R::from_url(&u))
                        .unwrap_or_else(|| default.clone())
                }
                #[cfg(not(all(target_arch = "wasm32", feature = "platform")))]
                {
                    default.clone()
                }
            };
            let history = NavHistory::new(current.clone());
            Self {
                current,
                history,
                system_back: true,
            }
        }

        pub fn current(&self) -> &R {
            &self.current
        }

        pub fn history(&self) -> &NavHistory<R> {
            &self.history
        }

        pub fn history_mut(&mut self) -> &mut NavHistory<R> {
            &mut self.history
        }

        #[must_use]
        pub fn system_back(&self) -> bool {
            self.system_back
        }

        pub fn set_system_back(&mut self, enabled: bool) {
            self.system_back = enabled;
        }

        #[must_use]
        pub fn with_system_back(mut self, enabled: bool) -> Self {
            self.system_back = enabled;
            self
        }

        pub fn can_go_back(&self) -> bool {
            self.history.can_go_back()
        }

        pub fn handle_back(
            &mut self,
            ctx: &egui::Context,
        ) -> Option<crate::platform::android_back::BackOutcome> {
            if !self.system_back {
                return None;
            }
            let can = self.history.can_go_back();
            crate::platform::android_back::handle_system_back(ctx, can, || {
                if let Some(r) = self.history.go_back() {
                    self.current = r.clone();
                    history_push(&self.current);
                }
            })
        }

        pub fn navigate(&mut self, route: R) {
            if route == self.current {
                return;
            }
            self.history.push(route.clone());
            self.current = route;
            history_push(&self.current);
        }

        pub fn replace(&mut self, route: R) {
            self.history.replace(route.clone());
            self.current = route;
            history_replace(&self.current);
        }

        pub fn reset(&mut self, route: R) {
            self.history.reset(route.clone());
            self.current = route;
            history_replace(&self.current);
        }

        pub fn go_back(&mut self) -> Option<&R> {
            if let Some(r) = self.history.go_back() {
                self.current = r.clone();
                history_push(&self.current);
                Some(r)
            } else {
                None
            }
        }

        pub fn go_forward(&mut self) -> Option<&R> {
            if let Some(r) = self.history.go_forward() {
                self.current = r.clone();
                history_push(&self.current);
                Some(r)
            } else {
                None
            }
        }

        pub fn sync_from_url(&mut self, url: &str) -> Option<R> {
            let route = R::from_url(url)?;
            if route == self.current {
                None
            } else {
                self.current = route.clone();
                self.history.sync(&route);
                Some(route)
            }
        }

        pub fn ui(&mut self, ui: &mut egui::Ui) {
            #[cfg(all(target_arch = "wasm32", feature = "platform"))]
            {
                if let Some(href) = crate::platform::web::location_href() {
                    drop(self.sync_from_url(&href));
                }
            }
            let _ = self.handle_back(ui.ctx());
        }

        pub fn active_route(&self) -> Option<String> {
            Some(self.current.to_url())
        }
    }

    pub fn history_push<R>(route: &R)
    where
        R: Routable + Default,
    {
        #[cfg(all(target_arch = "wasm32", feature = "platform"))]
        {
            let url = route.to_url();
            if let Err(err) = crate::platform::web::history_push(&url) {
                tracing::warn!("history_push failed: {err}");
            }
        }
        #[cfg(not(all(target_arch = "wasm32", feature = "platform")))]
        {
            let _ = route;
        }
    }

    pub fn history_replace<R>(route: &R)
    where
        R: Routable + Default,
    {
        #[cfg(all(target_arch = "wasm32", feature = "platform"))]
        {
            let url = route.to_url();
            if let Err(err) = crate::platform::web::history_replace(&url) {
                tracing::warn!("history_replace failed: {err}");
            }
        }
        #[cfg(not(all(target_arch = "wasm32", feature = "platform")))]
        {
            let _ = route;
        }
    }
}

pub use router_impl::AppRouter;
pub use router_impl::{history_push, history_replace};