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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
20#[serde(rename_all = "lowercase")]
21pub enum AssetMode {
22 #[default]
24 Local,
25 Cdn,
27}
28
29pub trait AssetHost {
41 fn published(&self, path: &str) -> bool;
53
54 fn url(&self, path: &str) -> String;
66}
67
68#[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 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 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 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#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Deserialize)]
347#[serde(rename_all = "lowercase")]
348pub enum PluginActivation {
349 #[default]
351 Inherit,
352 Enable,
354 Disable,
356}
357
358#[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 pub fn presets() -> Result<Self, serde_json::Error> {
395 Ok(serde_json::from_str::<Upstream>(PRESETS)?.plugins)
396 }
397
398 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#[derive(Clone, Debug, Default, Serialize)]
469pub struct PageAssets {
470 css: Vec<SafeUrl>,
471 js: Vec<Script>,
472}
473
474impl PageAssets {
475 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}