oxblade-adminlte 0.1.0

Rust port of jeroennoten/laravel-adminlte: AdminLTE dashboard layouts, menus and plugins for Laravel for Rust.
Documentation
use crate::AssetConfig;
use serde::{Deserialize, Serialize};

/// The page's initial Bootstrap color mode, corresponding to PHP's color_mode.default.
///
/// ```
/// use oxblade_adminlte::ColorMode;
/// assert_eq!(ColorMode::default(), ColorMode::Auto);
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum ColorMode {
    /// Resolve from the browser's color preference.
    #[default]
    Auto,
    /// Start with the light theme.
    Light,
    /// Start with the dark theme.
    Dark,
}

impl ColorMode {
    fn authored(self) -> Option<&'static str> {
        match self {
            Self::Auto => None,
            Self::Light => Some("light"),
            Self::Dark => Some("dark"),
        }
    }
}

/// Typed settings for the PHP layout helper and shell.
///
/// This type can be deserialized from application configuration. Missing keys retain the defaults.
///
/// ```
/// use oxblade_adminlte::Layout;
/// assert!(Layout::default().view("en").body_classes().contains("layout-fixed"));
/// ```
#[derive(Clone, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Layout {
    topnav: bool,
    fixed_sidebar: bool,
    fixed_navbar: bool,
    fixed_footer: bool,
    compact: bool,
    sidebar_mini: bool,
    sidebar_collapse: bool,
    sidebar_nav_compact: bool,
    sidebar_nav_indent: bool,
    sidebar_without_hover: bool,
    sidebar_expand: Breakpoint,
    sidebar_pills: bool,
    body_class: String,
    wrapper_class: String,
    content_class: String,
    topnav_container: String,
    color_mode: ColorMode,
    rtl: Option<bool>,
    print: PrintTokens,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
enum PrintTokens {
    Text(String),
    List(Vec<String>),
}

impl Default for PrintTokens {
    fn default() -> Self {
        Self::List(Vec::new())
    }
}

impl PrintTokens {
    fn resolved(&self) -> Option<String> {
        let tokens: Vec<&str> = match self {
            Self::Text(input) => input.split_whitespace().collect(),
            Self::List(input) => input.iter().map(String::as_str).collect(),
        };
        let allowed = ["plain", "app"]
            .into_iter()
            .filter(|token| tokens.contains(token))
            .collect::<Vec<_>>();
        (!allowed.is_empty()).then(|| allowed.join(" "))
    }
}

#[derive(Clone, Copy, Debug, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
enum Breakpoint {
    Sm,
    Md,
    #[default]
    Lg,
    Xl,
    Xxl,
}
impl Breakpoint {
    fn class(self) -> &'static str {
        match self {
            Self::Sm => "sidebar-expand-sm",
            Self::Md => "sidebar-expand-md",
            Self::Lg => "sidebar-expand-lg",
            Self::Xl => "sidebar-expand-xl",
            Self::Xxl => "sidebar-expand-xxl",
        }
    }
    fn width(self) -> Option<u16> {
        match self {
            Self::Sm => Some(576),
            Self::Md => Some(768),
            Self::Lg => None,
            Self::Xl => Some(1200),
            Self::Xxl => Some(1400),
        }
    }
}

impl Default for Layout {
    fn default() -> Self {
        Self {
            topnav: false,
            fixed_sidebar: true,
            fixed_navbar: false,
            fixed_footer: false,
            compact: false,
            sidebar_mini: true,
            sidebar_collapse: false,
            sidebar_nav_compact: false,
            sidebar_nav_indent: false,
            sidebar_without_hover: false,
            sidebar_expand: Breakpoint::Lg,
            sidebar_pills: false,
            body_class: "bg-body-tertiary".into(),
            wrapper_class: String::new(),
            content_class: String::new(),
            topnav_container: "container-fluid".into(),
            color_mode: ColorMode::Auto,
            rtl: None,
            print: PrintTokens::default(),
        }
    }
}

impl Layout {
    /// Resolve request-local language and layout tokens, as PHP's LayoutHelper does.
    ///
    /// ```
    /// let page = oxblade_adminlte::Layout::default().view("en_US");
    /// assert_eq!(page.body_classes(), "layout-fixed sidebar-expand-lg sidebar-mini bg-body-tertiary");
    /// ```
    pub fn view(&self, locale: &str) -> LayoutView {
        self.resolve_view(locale, None)
    }

    /// Resolves the view using the selected AdminLTE palette from the PHP asset settings.
    ///
    /// ```
    /// let assets = oxblade_adminlte::AssetConfig::default();
    /// let view = oxblade_adminlte::Layout::default().view_with_assets("ar", &assets);
    /// assert!(view.rtl());
    /// ```
    pub fn view_with_assets(&self, locale: &str, assets: &AssetConfig) -> LayoutView {
        self.resolve_view(locale, Some(assets))
    }

    fn resolve_view(&self, locale: &str, assets: Option<&AssetConfig>) -> LayoutView {
        let (palette_primary, palette_contrast) =
            assets.map(AssetConfig::palette_attributes).unwrap_or_default();
        let locale = locale.replace('_', "-");
        let language = locale.split('-').next().unwrap_or_default();
        let rtl = self.rtl.unwrap_or_else(|| {
            locale.eq_ignore_ascii_case("uz-AF")
                || matches!(
                    language.to_ascii_lowercase().as_str(),
                    "ar" | "arc"
                        | "ckb"
                        | "dv"
                        | "fa"
                        | "ha"
                        | "he"
                        | "khw"
                        | "ks"
                        | "ps"
                        | "sd"
                        | "ug"
                        | "ur"
                        | "yi"
                )
        });
        let mut classes = Vec::new();
        add_if(&mut classes, self.fixed_sidebar && !self.topnav, "layout-fixed");
        add_if(&mut classes, self.fixed_navbar, "fixed-header");
        add_if(&mut classes, self.fixed_footer, "fixed-footer");
        add_if(&mut classes, self.compact, "compact-mode");
        if !self.topnav {
            classes.push(self.sidebar_expand.class());
            add_if(&mut classes, self.sidebar_mini, "sidebar-mini");
            add_if(&mut classes, self.sidebar_collapse, "sidebar-collapse");
            add_if(&mut classes, self.sidebar_nav_compact, "nav-compact");
            add_if(&mut classes, self.sidebar_nav_indent, "nav-indent");
            add_if(&mut classes, self.sidebar_without_hover, "sidebar-without-hover");
        }
        let custom = self.body_class.as_str();
        if !custom.is_empty() && custom != "0" && !classes.contains(&custom) {
            classes.push(custom);
        }
        LayoutView {
            locale,
            rtl,
            body_classes: classes.join(" "),
            wrapper_classes: join_class("app-wrapper", &self.wrapper_class),
            content_classes: join_class("app-main", &self.content_class),
            topnav: self.topnav,
            container: if self.topnav {
                self.topnav_container.clone()
            } else {
                "container-fluid".into()
            },
            fixed_footer: self.fixed_footer,
            theme: self.color_mode.authored(),
            palette_primary,
            palette_contrast,
            print: self.print.resolved(),
            sidebar_breakpoint: self.sidebar_expand.width(),
            sidebar_nav_classes: if self.sidebar_pills {
                "nav sidebar-menu flex-column nav-pills"
            } else {
                "nav sidebar-menu flex-column"
            },
        }
    }
}

fn add_if<'a>(classes: &mut Vec<&'a str>, condition: bool, value: &'a str) {
    if condition {
        classes.push(value);
    }
}

fn join_class(base: &str, extra: &str) -> String {
    if extra.is_empty() || extra == "0" {
        base.to_owned()
    } else {
        format!("{base} {extra}")
    }
}

/// Resolved class and attribute data for the embedded AdminLTE Blade layouts.
///
/// ```
/// let view = oxblade_adminlte::Layout::default().view("ar");
/// assert!(view.body_classes().starts_with("layout-fixed"));
/// ```
#[derive(Clone, Debug, Serialize)]
pub struct LayoutView {
    locale: String,
    rtl: bool,
    body_classes: String,
    wrapper_classes: String,
    content_classes: String,
    topnav: bool,
    container: String,
    fixed_footer: bool,
    theme: Option<&'static str>,
    palette_primary: Option<String>,
    palette_contrast: Option<&'static str>,
    print: Option<String>,
    sidebar_breakpoint: Option<u16>,
    sidebar_nav_classes: &'static str,
}

impl LayoutView {
    /// Whether PHP's LayoutHelper would use right-to-left assets.
    ///
    /// ```
    /// assert!(oxblade_adminlte::Layout::default().view("ar").rtl());
    /// ```
    pub fn rtl(&self) -> bool {
        self.rtl
    }

    /// Whether the PHP top-navigation mode omits the sidebar.
    ///
    /// ```
    /// assert!(!oxblade_adminlte::Layout::default().view("en").topnav());
    /// ```
    pub fn topnav(&self) -> bool {
        self.topnav
    }

    /// Ordered body class names, as in PHP's LayoutHelper::makeBodyClasses.
    ///
    /// ```
    /// assert!(oxblade_adminlte::Layout::default().view("en").body_classes().ends_with("bg-body-tertiary"));
    /// ```
    pub fn body_classes(&self) -> &str {
        &self.body_classes
    }
}