oxblade-adminlte 0.1.0

Rust port of jeroennoten/laravel-adminlte: AdminLTE dashboard layouts, menus and plugins for Laravel for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use crate::SafeUrl;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

const PRESETS: &str = include_str!("../resources/config/presets.json");

#[derive(Deserialize)]
struct Upstream {
    assets: AssetConfig,
    plugins: Plugins,
}

/// The core asset delivery mode, corresponding to PHP's assets.mode.
///
/// ```
/// assert_eq!(oxblade_adminlte::AssetMode::default(), oxblade_adminlte::AssetMode::Local);
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AssetMode {
    /// Prefer a published local file.
    #[default]
    Local,
    /// Prefer the configured CDN URL.
    Cdn,
}

/// The application's public asset bindings, equivalent to PHP's asset() and public-path check.
///
/// ```
/// use oxblade_adminlte::AssetHost;
/// struct Public;
/// impl AssetHost for Public {
///     fn published(&self, _: &str) -> bool { false }
///     fn url(&self, path: &str) -> String { format!("/{path}") }
/// }
/// assert!(!Public.published("adminlte.css"));
/// ```
pub trait AssetHost {
    /// Whether a local path has been published by the application.
    ///
    /// ```
    /// # use oxblade_adminlte::AssetHost;
    /// # struct Public;
    /// # impl AssetHost for Public {
    /// # fn published(&self, _: &str) -> bool { false }
    /// # fn url(&self, path: &str) -> String { format!("/{path}") }
    /// # }
    /// assert!(!Public.published("missing.css"));
    /// ```
    fn published(&self, path: &str) -> bool;

    /// Generates the public URL of a local path, which is validated before rendering.
    ///
    /// ```
    /// # use oxblade_adminlte::AssetHost;
    /// # struct Public;
    /// # impl AssetHost for Public {
    /// # fn published(&self, _: &str) -> bool { false }
    /// # fn url(&self, path: &str) -> String { format!("/{path}") }
    /// # }
    /// assert_eq!(Public.url("adminlte.css"), "/adminlte.css");
    /// ```
    fn url(&self, path: &str) -> String;
}

/// Overrides for PHP's core AdminLTE asset locations.
///
/// A missing location uses the shipped preset. An explicit JSON null disables that location.
///
/// ```
/// use oxblade_adminlte::AssetConfig;
/// let config: AssetConfig = serde_json::from_str(r#"{"mode":"cdn"}"#)?;
/// assert_eq!(config.version("v4.10.4"), "4.10");
/// # Ok::<(), serde_json::Error>(())
/// ```
#[derive(Clone, Debug, Deserialize)]
#[serde(default)]
pub struct AssetConfig {
    mode: AssetMode,
    cdn_fallback: bool,
    adminlte_version: Option<String>,
    extended_colors: bool,
    extended_colors_v3_aliases: bool,
    palette: Palette,
    bootstrap_js: bool,
    bootstrap_icons: bool,
    fonts: bool,
    overlayscrollbars: bool,
    local: BTreeMap<String, Option<String>>,
    cdn: BTreeMap<String, Option<String>>,
}

#[derive(Clone, Debug, Default, Deserialize)]
#[serde(default)]
struct Palette {
    primary: Option<String>,
    contrast: Option<serde_json::Value>,
}

impl Default for AssetConfig {
    fn default() -> Self {
        Self {
            mode: AssetMode::Local,
            cdn_fallback: true,
            adminlte_version: None,
            extended_colors: false,
            extended_colors_v3_aliases: false,
            palette: Palette::default(),
            bootstrap_js: true,
            bootstrap_icons: true,
            fonts: true,
            overlayscrollbars: true,
            local: BTreeMap::new(),
            cdn: BTreeMap::new(),
        }
    }
}

impl AssetConfig {
    pub(crate) fn palette_attributes(&self) -> (Option<String>, Option<&'static str>) {
        const BOOTSTRAP: &[&str] = &[
            "secondary",
            "success",
            "danger",
            "warning",
            "info",
            "light",
            "dark",
        ];
        const EXTENDED: &[&str] = &[
            "amber", "fuchsia", "graphite", "indigo", "midnight", "navy", "olive", "orange", "pink", "sky",
            "slate", "steel", "teal", "violet",
        ];
        const LEGACY: &[&str] = &[
            "blue",
            "cyan",
            "fuchsia",
            "gray",
            "gray-dark",
            "green",
            "indigo",
            "lightblue",
            "lime",
            "maroon",
            "navy",
            "olive",
            "orange",
            "pink",
            "purple",
            "red",
            "teal",
            "yellow",
        ];
        let extended = if self.extended_colors_v3_aliases {
            LEGACY
        } else {
            EXTENDED
        };
        let primary = self
            .palette
            .primary
            .as_ref()
            .filter(|color| {
                self.extended_colors
                    && (BOOTSTRAP.contains(&color.as_str()) || extended.contains(&color.as_str()))
            })
            .cloned();
        let contrast = match &self.palette.contrast {
            None if self.extended_colors && self.extended_colors_v3_aliases => Some("aa"),
            Some(value) if value.as_str() == Some("aa") => Some("aa"),
            _ => None,
        };
        (primary, contrast)
    }

    /// Version used by the PHP placeholder. An override wins, else use the installed release line.
    ///
    /// ```
    /// let config = oxblade_adminlte::AssetConfig::default();
    /// assert_eq!(config.version("v4.10.4"), "4.10");
    /// ```
    pub fn version<'a>(&'a self, distribution: &'a str) -> &'a str {
        if let Some(version) = self.adminlte_version.as_deref().filter(|value| !value.is_empty()) {
            return version;
        }
        let distribution = distribution.trim_start_matches('v');
        let Some((major, tail)) = distribution.split_once('.') else {
            return "4.8";
        };
        let minor = tail.bytes().take_while(u8::is_ascii_digit).count();
        if major.is_empty() || !major.bytes().all(|byte| byte.is_ascii_digit()) || minor == 0 {
            return "4.8";
        }
        &distribution[..major.len() + 1 + minor]
    }

    /// Resolves one PHP asset key, with RTL selection and local/CDN fallback.
    ///
    /// ```
    /// # use oxblade_adminlte::{AssetConfig, AssetHost};
    /// # struct Public;
    /// # impl AssetHost for Public {
    /// # fn published(&self, _: &str) -> bool { false }
    /// # fn url(&self, path: &str) -> String { format!("/{path}") }
    /// # }
    /// let url = AssetConfig::default().resolve("adminlte_css", false, "4.10.4", &Public)?;
    /// assert!(url.is_some());
    /// # Ok::<(), serde_json::Error>(())
    /// ```
    pub fn resolve(
        &self,
        key: &str,
        rtl: bool,
        distribution: &str,
        host: &impl AssetHost,
    ) -> Result<Option<SafeUrl>, serde_json::Error> {
        let defaults: Upstream = serde_json::from_str(PRESETS)?;
        Ok(self.resolve_with(key, rtl, self.version(distribution), host, &defaults.assets))
    }

    fn resolve_with(
        &self,
        key: &str,
        rtl: bool,
        version: &str,
        host: &impl AssetHost,
        defaults: &Self,
    ) -> Option<SafeUrl> {
        let key = match (rtl, key) {
            (true, "adminlte_css") => "adminlte_rtl_css",
            (true, "colors_css") => "colors_rtl_css",
            (true, "colors_v3_css") => "colors_v3_rtl_css",
            (_, key) => key,
        };
        let cdn = location(&self.cdn, &defaults.cdn, key)
            .and_then(|location| remote_url(&location.replace("{version}", version)));
        let local = location(&self.local, &defaults.local, key).filter(|path| local_path(path));
        let local_url = || local.and_then(|path| remote_url(&host.url(path)));
        if self.mode == AssetMode::Cdn {
            return cdn.or_else(local_url);
        }
        match local {
            None => cdn,
            Some(path) if host.published(path) => local_url(),
            Some(_) if self.cdn_fallback && cdn.is_some() => cdn,
            Some(_) => local_url(),
        }
    }

    /// Builds the ordered base styles and scripts used by the PHP master view.
    ///
    /// ```
    /// # use oxblade_adminlte::{AssetConfig, AssetHost};
    /// # struct Public;
    /// # impl AssetHost for Public {
    /// # fn published(&self, _: &str) -> bool { false }
    /// # fn url(&self, path: &str) -> String { format!("/{path}") }
    /// # }
    /// let assets = AssetConfig::default().page(false, "4.10.4", &Public)?;
    /// assert!(!assets.css().is_empty());
    /// # Ok::<(), serde_json::Error>(())
    /// ```
    pub fn page(
        &self,
        rtl: bool,
        distribution: &str,
        host: &impl AssetHost,
    ) -> Result<PageAssets, serde_json::Error> {
        let defaults: Upstream = serde_json::from_str(PRESETS)?;
        let version = self.version(distribution);
        let mut result = PageAssets::default();
        for (key, enabled) in [
            ("fonts_css", self.fonts),
            ("overlayscrollbars_css", self.overlayscrollbars),
            ("bootstrap_icons_css", self.bootstrap_icons),
            ("adminlte_css", true),
            (
                if self.extended_colors_v3_aliases {
                    "colors_v3_css"
                } else {
                    "colors_css"
                },
                self.extended_colors,
            ),
        ] {
            if enabled && let Some(url) = self.resolve_with(key, rtl, version, host, &defaults.assets) {
                result.css.push(url);
            }
        }
        for (key, enabled) in [
            ("overlayscrollbars_js", self.overlayscrollbars),
            ("bootstrap_js", self.bootstrap_js),
            ("adminlte_js", true),
        ] {
            if enabled && let Some(url) = self.resolve_with(key, rtl, version, host, &defaults.assets) {
                result.js.push(Script { url, defer: false });
            }
        }
        Ok(result)
    }
}

fn location<'a>(
    configured: &'a BTreeMap<String, Option<String>>,
    shipped: &'a BTreeMap<String, Option<String>>,
    key: &str,
) -> Option<&'a str> {
    configured
        .get(key)
        .or_else(|| shipped.get(key))
        .and_then(Option::as_deref)
        .filter(|path| !path.is_empty())
}

fn remote_url(value: &str) -> Option<SafeUrl> {
    if value.starts_with("//") {
        return format!("https:{value}").parse().ok();
    }
    if value.starts_with('/')
        || value
            .split_once("://")
            .is_some_and(|(scheme, _)| scheme.eq_ignore_ascii_case("https"))
    {
        value.parse().ok()
    } else {
        None
    }
}

fn local_path(value: &str) -> bool {
    !value.is_empty()
        && !value.starts_with('/')
        && !value.contains(['\\', ':', '\0', '?', '#'])
        && value
            .split('/')
            .all(|segment| !matches!(segment, "" | "." | ".."))
}

/// Per-page activation replacing PHP's raw section override.
///
/// ```
/// assert_eq!(oxblade_adminlte::PluginActivation::default(), oxblade_adminlte::PluginActivation::Inherit);
/// ```
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PluginActivation {
    /// Use the plugin's configured default.
    #[default]
    Inherit,
    /// Include the plugin for this page.
    Enable,
    /// Do not include the plugin for this page.
    Disable,
}

/// The original ordered PHP plugin configuration, with typed page activation at render time.
///
/// ```
/// let presets = oxblade_adminlte::Plugins::presets()?;
/// # let _ = presets;
/// # Ok::<(), serde_json::Error>(())
/// ```
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(transparent)]
pub struct Plugins(IndexMap<String, Plugin>);

#[derive(Clone, Debug, Default, Deserialize)]
#[serde(default)]
struct Plugin {
    name: Option<String>,
    active: bool,
    files: Vec<PluginFile>,
}

#[derive(Clone, Debug, Default, Deserialize)]
#[serde(default)]
struct PluginFile {
    #[serde(rename = "type")]
    kind: String,
    asset: bool,
    location: Option<String>,
    rtl: Option<String>,
    defer: bool,
}

impl Plugins {
    /// Loads the named runtime presets from the pinned Laravel-AdminLTE configuration.
    ///
    /// ```
    /// assert!(oxblade_adminlte::Plugins::presets().is_ok());
    /// ```
    pub fn presets() -> Result<Self, serde_json::Error> {
        Ok(serde_json::from_str::<Upstream>(PRESETS)?.plugins)
    }

    /// Resolves active CSS and JS references by declaration order.
    ///
    /// ```
    /// # use oxblade_adminlte::{AssetHost, Plugins};
    /// # struct Public;
    /// # impl AssetHost for Public {
    /// # fn published(&self, _: &str) -> bool { false }
    /// # fn url(&self, path: &str) -> String { format!("/{path}") }
    /// # }
    /// assert!(Plugins::default().resolve(&Default::default(), false, "4.10", &Public).css().is_empty());
    /// ```
    pub fn resolve(
        &self,
        page: &BTreeMap<String, PluginActivation>,
        rtl: bool,
        version: &str,
        host: &impl AssetHost,
    ) -> PageAssets {
        let mut result = PageAssets::default();
        for (key, plugin) in &self.0 {
            let name = plugin.name.as_deref().unwrap_or(key);
            let active = match page.get(name).copied().unwrap_or_default() {
                PluginActivation::Inherit => plugin.active,
                PluginActivation::Enable => true,
                PluginActivation::Disable => false,
            };
            if !active {
                continue;
            }
            for file in &plugin.files {
                let rtl = rtl
                    .then_some(file.rtl.as_deref())
                    .flatten()
                    .filter(|value| !value.is_empty() && *value != "0");
                let Some(location) = rtl
                    .or(file.location.as_deref())
                    .filter(|value| !value.is_empty() && *value != "0")
                else {
                    continue;
                };
                let location = if file.asset {
                    if !local_path(location) {
                        continue;
                    }
                    host.url(location)
                } else {
                    location.to_owned()
                };
                let Some(url) = remote_url(&location.replace("{version}", version)) else {
                    continue;
                };
                match file.kind.as_str() {
                    "css" => result.css.push(url),
                    "js" => result.js.push(Script {
                        url,
                        defer: file.defer,
                    }),
                    _ => {}
                }
            }
        }
        result
    }
}

/// Resolved CSS and JS passes for PHP's master or plugins view.
///
/// ```
/// assert!(oxblade_adminlte::PageAssets::default().css().is_empty());
/// ```
#[derive(Clone, Debug, Default, Serialize)]
pub struct PageAssets {
    css: Vec<SafeUrl>,
    js: Vec<Script>,
}

impl PageAssets {
    /// Resolved stylesheet URLs in output order.
    ///
    /// ```
    /// assert!(oxblade_adminlte::PageAssets::default().css().is_empty());
    /// ```
    pub fn css(&self) -> &[SafeUrl] {
        &self.css
    }
}

#[derive(Clone, Debug, Serialize)]
struct Script {
    url: SafeUrl,
    defer: bool,
}