//! Site icons, `
` link/script assembly, and image HTML assembly.
//! Tables stay data; assembly is a function — 配置即数据、装配即函数.
use serde_json::{json, Map, Value};
use std::path::{Path, PathBuf};
use crate::table::normalize_ref;
#[derive(Clone, Debug)]
pub struct HeadLink {
pub rel: String,
pub href: String,
pub type_: String,
pub sizes: String,
pub media: String,
pub as_: String,
pub crossorigin: String,
/// When `Some(true)`, emit `defer` on classic scripts (not modules).
pub defer: Option,
pub async_: bool,
/// Query `?v=` bump for cache busting.
pub version: String,
}
#[derive(Clone, Debug)]
pub struct IconRoute {
pub url: String,
pub path: PathBuf,
pub content_type: String,
}
fn cell_str(v: &Value) -> String {
match v {
Value::Null => String::new(),
Value::String(s) => s.clone(),
Value::Bool(b) => b.to_string(),
Value::Number(n) => n.to_string(),
other => other.to_string(),
}
}
fn pick<'a>(m: &'a Map, keys: &[&str]) -> Option<&'a Value> {
keys.iter().find_map(|k| m.get(*k))
}
fn cell_boolish(v: &Value) -> Option {
match v {
Value::Bool(b) => Some(*b),
Value::Number(n) => Some(n.as_i64().unwrap_or(0) != 0),
Value::String(s) => {
let s = s.trim();
if s.is_empty() {
return None;
}
if matches!(
s,
"1" | "true" | "True" | "yes" | "on" | "真" | "是"
) {
Some(true)
} else if matches!(
s,
"0" | "false" | "False" | "no" | "off" | "假" | "否"
) {
Some(false)
} else {
None
}
}
_ => None,
}
}
fn row_bool(m: &Map, keys: &[&str]) -> Option {
pick(m, keys).and_then(cell_boolish)
}
fn row_str(m: &Map, keys: &[&str]) -> String {
pick(m, keys)
.map(|v| normalize_ref(&cell_str(v)))
.unwrap_or_default()
.trim()
.to_string()
}
/// Append `?v=` / `&v=` for cache busting.
pub fn href_with_version(href: &str, version: &str) -> String {
let version = version.trim();
if version.is_empty() {
return href.to_string();
}
if href.contains('?') {
format!("{href}&v={version}")
} else {
format!("{href}?v={version}")
}
}
fn esc(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}
/// Infer Content-Type from file extension.
pub fn mime_for_path(path: &str) -> &'static str {
let lower = path.to_ascii_lowercase();
if lower.ends_with(".ico") {
"image/x-icon"
} else if lower.ends_with(".png") {
"image/png"
} else if lower.ends_with(".svg") {
"image/svg+xml"
} else if lower.ends_with(".webp") {
"image/webp"
} else if lower.ends_with(".jpg") || lower.ends_with(".jpeg") {
"image/jpeg"
} else if lower.ends_with(".gif") {
"image/gif"
} else if lower.ends_with(".webmanifest") || lower.ends_with(".json") {
"application/manifest+json"
} else if lower.ends_with(".css") {
"text/css; charset=utf-8"
} else if lower.ends_with(".js") || lower.ends_with(".mjs") {
"text/javascript; charset=utf-8"
} else {
"application/octet-stream"
}
}
fn rows_of(table: &Value) -> Vec