Skip to main content

oxblade_adminlte/
assets.rs

1use crate::SafeUrl;
2use indexmap::IndexMap;
3use serde::{Deserialize, Serialize};
4use std::collections::BTreeMap;
5
6const PRESETS: &str = include_str!("../resources/config/presets.json");
7
8#[derive(Deserialize)]
9struct Upstream {
10    assets: AssetConfig,
11    plugins: Plugins,
12}
13
14/// The core asset delivery mode, corresponding to PHP's assets.mode.
15///
16/// ```
17/// assert_eq!(oxblade_adminlte::AssetMode::default(), oxblade_adminlte::AssetMode::Local);
18/// ```
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
20#[serde(rename_all = "lowercase")]
21pub enum AssetMode {
22    /// Prefer a published local file.
23    #[default]
24    Local,
25    /// Prefer the configured CDN URL.
26    Cdn,
27}
28
29/// The application's public asset bindings, equivalent to PHP's asset() and public-path check.
30///
31/// ```
32/// use oxblade_adminlte::AssetHost;
33/// struct Public;
34/// impl AssetHost for Public {
35///     fn published(&self, _: &str) -> bool { false }
36///     fn url(&self, path: &str) -> String { format!("/{path}") }
37/// }
38/// assert!(!Public.published("adminlte.css"));
39/// ```
40pub trait AssetHost {
41    /// Whether a local path has been published by the application.
42    ///
43    /// ```
44    /// # use oxblade_adminlte::AssetHost;
45    /// # struct Public;
46    /// # impl AssetHost for Public {
47    /// # fn published(&self, _: &str) -> bool { false }
48    /// # fn url(&self, path: &str) -> String { format!("/{path}") }
49    /// # }
50    /// assert!(!Public.published("missing.css"));
51    /// ```
52    fn published(&self, path: &str) -> bool;
53
54    /// Generates the public URL of a local path, which is validated before rendering.
55    ///
56    /// ```
57    /// # use oxblade_adminlte::AssetHost;
58    /// # struct Public;
59    /// # impl AssetHost for Public {
60    /// # fn published(&self, _: &str) -> bool { false }
61    /// # fn url(&self, path: &str) -> String { format!("/{path}") }
62    /// # }
63    /// assert_eq!(Public.url("adminlte.css"), "/adminlte.css");
64    /// ```
65    fn url(&self, path: &str) -> String;
66}
67
68/// Overrides for PHP's core AdminLTE asset locations.
69///
70/// A missing location uses the shipped preset. An explicit JSON null disables that location.
71///
72/// ```
73/// use oxblade_adminlte::AssetConfig;
74/// let config: AssetConfig = serde_json::from_str(r#"{"mode":"cdn"}"#)?;
75/// assert_eq!(config.version("v4.10.4"), "4.10");
76/// # Ok::<(), serde_json::Error>(())
77/// ```
78#[derive(Clone, Debug, Deserialize)]
79#[serde(default)]
80pub struct AssetConfig {
81    mode: AssetMode,
82    cdn_fallback: bool,
83    adminlte_version: Option<String>,
84    extended_colors: bool,
85    extended_colors_v3_aliases: bool,
86    palette: Palette,
87    bootstrap_js: bool,
88    bootstrap_icons: bool,
89    fonts: bool,
90    overlayscrollbars: bool,
91    local: BTreeMap<String, Option<String>>,
92    cdn: BTreeMap<String, Option<String>>,
93}
94
95#[derive(Clone, Debug, Default, Deserialize)]
96#[serde(default)]
97struct Palette {
98    primary: Option<String>,
99    contrast: Option<serde_json::Value>,
100}
101
102impl Default for AssetConfig {
103    fn default() -> Self {
104        Self {
105            mode: AssetMode::Local,
106            cdn_fallback: true,
107            adminlte_version: None,
108            extended_colors: false,
109            extended_colors_v3_aliases: false,
110            palette: Palette::default(),
111            bootstrap_js: true,
112            bootstrap_icons: true,
113            fonts: true,
114            overlayscrollbars: true,
115            local: BTreeMap::new(),
116            cdn: BTreeMap::new(),
117        }
118    }
119}
120
121impl AssetConfig {
122    pub(crate) fn palette_attributes(&self) -> (Option<String>, Option<&'static str>) {
123        const BOOTSTRAP: &[&str] = &[
124            "secondary",
125            "success",
126            "danger",
127            "warning",
128            "info",
129            "light",
130            "dark",
131        ];
132        const EXTENDED: &[&str] = &[
133            "amber", "fuchsia", "graphite", "indigo", "midnight", "navy", "olive", "orange", "pink", "sky",
134            "slate", "steel", "teal", "violet",
135        ];
136        const LEGACY: &[&str] = &[
137            "blue",
138            "cyan",
139            "fuchsia",
140            "gray",
141            "gray-dark",
142            "green",
143            "indigo",
144            "lightblue",
145            "lime",
146            "maroon",
147            "navy",
148            "olive",
149            "orange",
150            "pink",
151            "purple",
152            "red",
153            "teal",
154            "yellow",
155        ];
156        let extended = if self.extended_colors_v3_aliases {
157            LEGACY
158        } else {
159            EXTENDED
160        };
161        let primary = self
162            .palette
163            .primary
164            .as_ref()
165            .filter(|color| {
166                self.extended_colors
167                    && (BOOTSTRAP.contains(&color.as_str()) || extended.contains(&color.as_str()))
168            })
169            .cloned();
170        let contrast = match &self.palette.contrast {
171            None if self.extended_colors && self.extended_colors_v3_aliases => Some("aa"),
172            Some(value) if value.as_str() == Some("aa") => Some("aa"),
173            _ => None,
174        };
175        (primary, contrast)
176    }
177
178    /// Version used by the PHP placeholder. An override wins, else use the installed release line.
179    ///
180    /// ```
181    /// let config = oxblade_adminlte::AssetConfig::default();
182    /// assert_eq!(config.version("v4.10.4"), "4.10");
183    /// ```
184    pub fn version<'a>(&'a self, distribution: &'a str) -> &'a str {
185        if let Some(version) = self.adminlte_version.as_deref().filter(|value| !value.is_empty()) {
186            return version;
187        }
188        let distribution = distribution.trim_start_matches('v');
189        let Some((major, tail)) = distribution.split_once('.') else {
190            return "4.8";
191        };
192        let minor = tail.bytes().take_while(u8::is_ascii_digit).count();
193        if major.is_empty() || !major.bytes().all(|byte| byte.is_ascii_digit()) || minor == 0 {
194            return "4.8";
195        }
196        &distribution[..major.len() + 1 + minor]
197    }
198
199    /// Resolves one PHP asset key, with RTL selection and local/CDN fallback.
200    ///
201    /// ```
202    /// # use oxblade_adminlte::{AssetConfig, AssetHost};
203    /// # struct Public;
204    /// # impl AssetHost for Public {
205    /// # fn published(&self, _: &str) -> bool { false }
206    /// # fn url(&self, path: &str) -> String { format!("/{path}") }
207    /// # }
208    /// let url = AssetConfig::default().resolve("adminlte_css", false, "4.10.4", &Public)?;
209    /// assert!(url.is_some());
210    /// # Ok::<(), serde_json::Error>(())
211    /// ```
212    pub fn resolve(
213        &self,
214        key: &str,
215        rtl: bool,
216        distribution: &str,
217        host: &impl AssetHost,
218    ) -> Result<Option<SafeUrl>, serde_json::Error> {
219        let defaults: Upstream = serde_json::from_str(PRESETS)?;
220        Ok(self.resolve_with(key, rtl, self.version(distribution), host, &defaults.assets))
221    }
222
223    fn resolve_with(
224        &self,
225        key: &str,
226        rtl: bool,
227        version: &str,
228        host: &impl AssetHost,
229        defaults: &Self,
230    ) -> Option<SafeUrl> {
231        let key = match (rtl, key) {
232            (true, "adminlte_css") => "adminlte_rtl_css",
233            (true, "colors_css") => "colors_rtl_css",
234            (true, "colors_v3_css") => "colors_v3_rtl_css",
235            (_, key) => key,
236        };
237        let cdn = location(&self.cdn, &defaults.cdn, key)
238            .and_then(|location| remote_url(&location.replace("{version}", version)));
239        let local = location(&self.local, &defaults.local, key).filter(|path| local_path(path));
240        let local_url = || local.and_then(|path| remote_url(&host.url(path)));
241        if self.mode == AssetMode::Cdn {
242            return cdn.or_else(local_url);
243        }
244        match local {
245            None => cdn,
246            Some(path) if host.published(path) => local_url(),
247            Some(_) if self.cdn_fallback && cdn.is_some() => cdn,
248            Some(_) => local_url(),
249        }
250    }
251
252    /// Builds the ordered base styles and scripts used by the PHP master view.
253    ///
254    /// ```
255    /// # use oxblade_adminlte::{AssetConfig, AssetHost};
256    /// # struct Public;
257    /// # impl AssetHost for Public {
258    /// # fn published(&self, _: &str) -> bool { false }
259    /// # fn url(&self, path: &str) -> String { format!("/{path}") }
260    /// # }
261    /// let assets = AssetConfig::default().page(false, "4.10.4", &Public)?;
262    /// assert!(!assets.css().is_empty());
263    /// # Ok::<(), serde_json::Error>(())
264    /// ```
265    pub fn page(
266        &self,
267        rtl: bool,
268        distribution: &str,
269        host: &impl AssetHost,
270    ) -> Result<PageAssets, serde_json::Error> {
271        let defaults: Upstream = serde_json::from_str(PRESETS)?;
272        let version = self.version(distribution);
273        let mut result = PageAssets::default();
274        for (key, enabled) in [
275            ("fonts_css", self.fonts),
276            ("overlayscrollbars_css", self.overlayscrollbars),
277            ("bootstrap_icons_css", self.bootstrap_icons),
278            ("adminlte_css", true),
279            (
280                if self.extended_colors_v3_aliases {
281                    "colors_v3_css"
282                } else {
283                    "colors_css"
284                },
285                self.extended_colors,
286            ),
287        ] {
288            if enabled && let Some(url) = self.resolve_with(key, rtl, version, host, &defaults.assets) {
289                result.css.push(url);
290            }
291        }
292        for (key, enabled) in [
293            ("overlayscrollbars_js", self.overlayscrollbars),
294            ("bootstrap_js", self.bootstrap_js),
295            ("adminlte_js", true),
296        ] {
297            if enabled && let Some(url) = self.resolve_with(key, rtl, version, host, &defaults.assets) {
298                result.js.push(Script { url, defer: false });
299            }
300        }
301        Ok(result)
302    }
303}
304
305fn location<'a>(
306    configured: &'a BTreeMap<String, Option<String>>,
307    shipped: &'a BTreeMap<String, Option<String>>,
308    key: &str,
309) -> Option<&'a str> {
310    configured
311        .get(key)
312        .or_else(|| shipped.get(key))
313        .and_then(Option::as_deref)
314        .filter(|path| !path.is_empty())
315}
316
317fn remote_url(value: &str) -> Option<SafeUrl> {
318    if value.starts_with("//") {
319        return format!("https:{value}").parse().ok();
320    }
321    if value.starts_with('/')
322        || value
323            .split_once("://")
324            .is_some_and(|(scheme, _)| scheme.eq_ignore_ascii_case("https"))
325    {
326        value.parse().ok()
327    } else {
328        None
329    }
330}
331
332fn local_path(value: &str) -> bool {
333    !value.is_empty()
334        && !value.starts_with('/')
335        && !value.contains(['\\', ':', '\0', '?', '#'])
336        && value
337            .split('/')
338            .all(|segment| !matches!(segment, "" | "." | ".."))
339}
340
341/// Per-page activation replacing PHP's raw section override.
342///
343/// ```
344/// assert_eq!(oxblade_adminlte::PluginActivation::default(), oxblade_adminlte::PluginActivation::Inherit);
345/// ```
346#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Deserialize)]
347#[serde(rename_all = "lowercase")]
348pub enum PluginActivation {
349    /// Use the plugin's configured default.
350    #[default]
351    Inherit,
352    /// Include the plugin for this page.
353    Enable,
354    /// Do not include the plugin for this page.
355    Disable,
356}
357
358/// The original ordered PHP plugin configuration, with typed page activation at render time.
359///
360/// ```
361/// let presets = oxblade_adminlte::Plugins::presets()?;
362/// # let _ = presets;
363/// # Ok::<(), serde_json::Error>(())
364/// ```
365#[derive(Clone, Debug, Default, Deserialize)]
366#[serde(transparent)]
367pub struct Plugins(IndexMap<String, Plugin>);
368
369#[derive(Clone, Debug, Default, Deserialize)]
370#[serde(default)]
371struct Plugin {
372    name: Option<String>,
373    active: bool,
374    files: Vec<PluginFile>,
375}
376
377#[derive(Clone, Debug, Default, Deserialize)]
378#[serde(default)]
379struct PluginFile {
380    #[serde(rename = "type")]
381    kind: String,
382    asset: bool,
383    location: Option<String>,
384    rtl: Option<String>,
385    defer: bool,
386}
387
388impl Plugins {
389    /// Loads the named runtime presets from the pinned Laravel-AdminLTE configuration.
390    ///
391    /// ```
392    /// assert!(oxblade_adminlte::Plugins::presets().is_ok());
393    /// ```
394    pub fn presets() -> Result<Self, serde_json::Error> {
395        Ok(serde_json::from_str::<Upstream>(PRESETS)?.plugins)
396    }
397
398    /// Resolves active CSS and JS references by declaration order.
399    ///
400    /// ```
401    /// # use oxblade_adminlte::{AssetHost, Plugins};
402    /// # struct Public;
403    /// # impl AssetHost for Public {
404    /// # fn published(&self, _: &str) -> bool { false }
405    /// # fn url(&self, path: &str) -> String { format!("/{path}") }
406    /// # }
407    /// assert!(Plugins::default().resolve(&Default::default(), false, "4.10", &Public).css().is_empty());
408    /// ```
409    pub fn resolve(
410        &self,
411        page: &BTreeMap<String, PluginActivation>,
412        rtl: bool,
413        version: &str,
414        host: &impl AssetHost,
415    ) -> PageAssets {
416        let mut result = PageAssets::default();
417        for (key, plugin) in &self.0 {
418            let name = plugin.name.as_deref().unwrap_or(key);
419            let active = match page.get(name).copied().unwrap_or_default() {
420                PluginActivation::Inherit => plugin.active,
421                PluginActivation::Enable => true,
422                PluginActivation::Disable => false,
423            };
424            if !active {
425                continue;
426            }
427            for file in &plugin.files {
428                let rtl = rtl
429                    .then_some(file.rtl.as_deref())
430                    .flatten()
431                    .filter(|value| !value.is_empty() && *value != "0");
432                let Some(location) = rtl
433                    .or(file.location.as_deref())
434                    .filter(|value| !value.is_empty() && *value != "0")
435                else {
436                    continue;
437                };
438                let location = if file.asset {
439                    if !local_path(location) {
440                        continue;
441                    }
442                    host.url(location)
443                } else {
444                    location.to_owned()
445                };
446                let Some(url) = remote_url(&location.replace("{version}", version)) else {
447                    continue;
448                };
449                match file.kind.as_str() {
450                    "css" => result.css.push(url),
451                    "js" => result.js.push(Script {
452                        url,
453                        defer: file.defer,
454                    }),
455                    _ => {}
456                }
457            }
458        }
459        result
460    }
461}
462
463/// Resolved CSS and JS passes for PHP's master or plugins view.
464///
465/// ```
466/// assert!(oxblade_adminlte::PageAssets::default().css().is_empty());
467/// ```
468#[derive(Clone, Debug, Default, Serialize)]
469pub struct PageAssets {
470    css: Vec<SafeUrl>,
471    js: Vec<Script>,
472}
473
474impl PageAssets {
475    /// Resolved stylesheet URLs in output order.
476    ///
477    /// ```
478    /// assert!(oxblade_adminlte::PageAssets::default().css().is_empty());
479    /// ```
480    pub fn css(&self) -> &[SafeUrl] {
481        &self.css
482    }
483}
484
485#[derive(Clone, Debug, Serialize)]
486struct Script {
487    url: SafeUrl,
488    defer: bool,
489}