Skip to main content

oxblade_adminlte/
layout.rs

1use crate::AssetConfig;
2use serde::{Deserialize, Serialize};
3
4/// The page's initial Bootstrap color mode, corresponding to PHP's color_mode.default.
5///
6/// ```
7/// use oxblade_adminlte::ColorMode;
8/// assert_eq!(ColorMode::default(), ColorMode::Auto);
9/// ```
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
11#[serde(rename_all = "lowercase")]
12#[non_exhaustive]
13pub enum ColorMode {
14    /// Resolve from the browser's color preference.
15    #[default]
16    Auto,
17    /// Start with the light theme.
18    Light,
19    /// Start with the dark theme.
20    Dark,
21}
22
23impl ColorMode {
24    fn authored(self) -> Option<&'static str> {
25        match self {
26            Self::Auto => None,
27            Self::Light => Some("light"),
28            Self::Dark => Some("dark"),
29        }
30    }
31}
32
33/// Typed settings for the PHP layout helper and shell.
34///
35/// This type can be deserialized from application configuration. Missing keys retain the defaults.
36///
37/// ```
38/// use oxblade_adminlte::Layout;
39/// assert!(Layout::default().view("en").body_classes().contains("layout-fixed"));
40/// ```
41#[derive(Clone, Debug, Deserialize)]
42#[serde(default, deny_unknown_fields)]
43pub struct Layout {
44    topnav: bool,
45    fixed_sidebar: bool,
46    fixed_navbar: bool,
47    fixed_footer: bool,
48    compact: bool,
49    sidebar_mini: bool,
50    sidebar_collapse: bool,
51    sidebar_nav_compact: bool,
52    sidebar_nav_indent: bool,
53    sidebar_without_hover: bool,
54    sidebar_expand: Breakpoint,
55    sidebar_pills: bool,
56    body_class: String,
57    wrapper_class: String,
58    content_class: String,
59    topnav_container: String,
60    color_mode: ColorMode,
61    rtl: Option<bool>,
62    print: PrintTokens,
63}
64
65#[derive(Clone, Debug, Deserialize)]
66#[serde(untagged)]
67enum PrintTokens {
68    Text(String),
69    List(Vec<String>),
70}
71
72impl Default for PrintTokens {
73    fn default() -> Self {
74        Self::List(Vec::new())
75    }
76}
77
78impl PrintTokens {
79    fn resolved(&self) -> Option<String> {
80        let tokens: Vec<&str> = match self {
81            Self::Text(input) => input.split_whitespace().collect(),
82            Self::List(input) => input.iter().map(String::as_str).collect(),
83        };
84        let allowed = ["plain", "app"]
85            .into_iter()
86            .filter(|token| tokens.contains(token))
87            .collect::<Vec<_>>();
88        (!allowed.is_empty()).then(|| allowed.join(" "))
89    }
90}
91
92#[derive(Clone, Copy, Debug, Default, Deserialize)]
93#[serde(rename_all = "lowercase")]
94enum Breakpoint {
95    Sm,
96    Md,
97    #[default]
98    Lg,
99    Xl,
100    Xxl,
101}
102impl Breakpoint {
103    fn class(self) -> &'static str {
104        match self {
105            Self::Sm => "sidebar-expand-sm",
106            Self::Md => "sidebar-expand-md",
107            Self::Lg => "sidebar-expand-lg",
108            Self::Xl => "sidebar-expand-xl",
109            Self::Xxl => "sidebar-expand-xxl",
110        }
111    }
112    fn width(self) -> Option<u16> {
113        match self {
114            Self::Sm => Some(576),
115            Self::Md => Some(768),
116            Self::Lg => None,
117            Self::Xl => Some(1200),
118            Self::Xxl => Some(1400),
119        }
120    }
121}
122
123impl Default for Layout {
124    fn default() -> Self {
125        Self {
126            topnav: false,
127            fixed_sidebar: true,
128            fixed_navbar: false,
129            fixed_footer: false,
130            compact: false,
131            sidebar_mini: true,
132            sidebar_collapse: false,
133            sidebar_nav_compact: false,
134            sidebar_nav_indent: false,
135            sidebar_without_hover: false,
136            sidebar_expand: Breakpoint::Lg,
137            sidebar_pills: false,
138            body_class: "bg-body-tertiary".into(),
139            wrapper_class: String::new(),
140            content_class: String::new(),
141            topnav_container: "container-fluid".into(),
142            color_mode: ColorMode::Auto,
143            rtl: None,
144            print: PrintTokens::default(),
145        }
146    }
147}
148
149impl Layout {
150    /// Resolve request-local language and layout tokens, as PHP's LayoutHelper does.
151    ///
152    /// ```
153    /// let page = oxblade_adminlte::Layout::default().view("en_US");
154    /// assert_eq!(page.body_classes(), "layout-fixed sidebar-expand-lg sidebar-mini bg-body-tertiary");
155    /// ```
156    pub fn view(&self, locale: &str) -> LayoutView {
157        self.resolve_view(locale, None)
158    }
159
160    /// Resolves the view using the selected AdminLTE palette from the PHP asset settings.
161    ///
162    /// ```
163    /// let assets = oxblade_adminlte::AssetConfig::default();
164    /// let view = oxblade_adminlte::Layout::default().view_with_assets("ar", &assets);
165    /// assert!(view.rtl());
166    /// ```
167    pub fn view_with_assets(&self, locale: &str, assets: &AssetConfig) -> LayoutView {
168        self.resolve_view(locale, Some(assets))
169    }
170
171    fn resolve_view(&self, locale: &str, assets: Option<&AssetConfig>) -> LayoutView {
172        let (palette_primary, palette_contrast) =
173            assets.map(AssetConfig::palette_attributes).unwrap_or_default();
174        let locale = locale.replace('_', "-");
175        let language = locale.split('-').next().unwrap_or_default();
176        let rtl = self.rtl.unwrap_or_else(|| {
177            locale.eq_ignore_ascii_case("uz-AF")
178                || matches!(
179                    language.to_ascii_lowercase().as_str(),
180                    "ar" | "arc"
181                        | "ckb"
182                        | "dv"
183                        | "fa"
184                        | "ha"
185                        | "he"
186                        | "khw"
187                        | "ks"
188                        | "ps"
189                        | "sd"
190                        | "ug"
191                        | "ur"
192                        | "yi"
193                )
194        });
195        let mut classes = Vec::new();
196        add_if(&mut classes, self.fixed_sidebar && !self.topnav, "layout-fixed");
197        add_if(&mut classes, self.fixed_navbar, "fixed-header");
198        add_if(&mut classes, self.fixed_footer, "fixed-footer");
199        add_if(&mut classes, self.compact, "compact-mode");
200        if !self.topnav {
201            classes.push(self.sidebar_expand.class());
202            add_if(&mut classes, self.sidebar_mini, "sidebar-mini");
203            add_if(&mut classes, self.sidebar_collapse, "sidebar-collapse");
204            add_if(&mut classes, self.sidebar_nav_compact, "nav-compact");
205            add_if(&mut classes, self.sidebar_nav_indent, "nav-indent");
206            add_if(&mut classes, self.sidebar_without_hover, "sidebar-without-hover");
207        }
208        let custom = self.body_class.as_str();
209        if !custom.is_empty() && custom != "0" && !classes.contains(&custom) {
210            classes.push(custom);
211        }
212        LayoutView {
213            locale,
214            rtl,
215            body_classes: classes.join(" "),
216            wrapper_classes: join_class("app-wrapper", &self.wrapper_class),
217            content_classes: join_class("app-main", &self.content_class),
218            topnav: self.topnav,
219            container: if self.topnav {
220                self.topnav_container.clone()
221            } else {
222                "container-fluid".into()
223            },
224            fixed_footer: self.fixed_footer,
225            theme: self.color_mode.authored(),
226            palette_primary,
227            palette_contrast,
228            print: self.print.resolved(),
229            sidebar_breakpoint: self.sidebar_expand.width(),
230            sidebar_nav_classes: if self.sidebar_pills {
231                "nav sidebar-menu flex-column nav-pills"
232            } else {
233                "nav sidebar-menu flex-column"
234            },
235        }
236    }
237}
238
239fn add_if<'a>(classes: &mut Vec<&'a str>, condition: bool, value: &'a str) {
240    if condition {
241        classes.push(value);
242    }
243}
244
245fn join_class(base: &str, extra: &str) -> String {
246    if extra.is_empty() || extra == "0" {
247        base.to_owned()
248    } else {
249        format!("{base} {extra}")
250    }
251}
252
253/// Resolved class and attribute data for the embedded AdminLTE Blade layouts.
254///
255/// ```
256/// let view = oxblade_adminlte::Layout::default().view("ar");
257/// assert!(view.body_classes().starts_with("layout-fixed"));
258/// ```
259#[derive(Clone, Debug, Serialize)]
260pub struct LayoutView {
261    locale: String,
262    rtl: bool,
263    body_classes: String,
264    wrapper_classes: String,
265    content_classes: String,
266    topnav: bool,
267    container: String,
268    fixed_footer: bool,
269    theme: Option<&'static str>,
270    palette_primary: Option<String>,
271    palette_contrast: Option<&'static str>,
272    print: Option<String>,
273    sidebar_breakpoint: Option<u16>,
274    sidebar_nav_classes: &'static str,
275}
276
277impl LayoutView {
278    /// Whether PHP's LayoutHelper would use right-to-left assets.
279    ///
280    /// ```
281    /// assert!(oxblade_adminlte::Layout::default().view("ar").rtl());
282    /// ```
283    pub fn rtl(&self) -> bool {
284        self.rtl
285    }
286
287    /// Whether the PHP top-navigation mode omits the sidebar.
288    ///
289    /// ```
290    /// assert!(!oxblade_adminlte::Layout::default().view("en").topnav());
291    /// ```
292    pub fn topnav(&self) -> bool {
293        self.topnav
294    }
295
296    /// Ordered body class names, as in PHP's LayoutHelper::makeBodyClasses.
297    ///
298    /// ```
299    /// assert!(oxblade_adminlte::Layout::default().view("en").body_classes().ends_with("bg-body-tertiary"));
300    /// ```
301    pub fn body_classes(&self) -> &str {
302        &self.body_classes
303    }
304}