//! Minimal HTML shell for assembled pages / parts.
use serde_json::{json, Map, Value};
use crate::db;
use crate::markdown;
use crate::table::{
as_bind, as_nav_rows, nav_label_href, nav_media_when_class, normalize_ref, normalize_slot,
parse_site_path, project_rows, SitePath,
};
fn esc(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}
fn text(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 class_attr(css: &str) -> String {
if css.is_empty() {
String::new()
} else {
format!(" class=\"{}\"", esc(css))
}
}
fn is_simple_ident(s: &str) -> bool {
!s.is_empty()
&& s.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || !c.is_ascii())
}
/// Normalize a form mount selector to a bare HTML id (`#foo` → `foo`).
fn form_mount_id(target: &str) -> Option<&str> {
let t = target.trim().trim_start_matches('#');
if t.is_empty() {
return None;
}
// Keep injection conservative: id must be a simple token (no spaces / quotes).
if t.chars().any(|c| c.is_whitespace() || c == '"' || c == '\'' || c == '<' || c == '>') {
return None;
}
Some(t)
}
/// Inject `payload` as the inner HTML of the first element with `id="…"` / `id='…'`.
/// Returns `None` if no matching open+close pair is found (caller falls back to sibling form).
pub(crate) fn inject_html_into_id(haystack: &str, id: &str, payload: &str) -> Option {
let id = form_mount_id(id)?;
let patterns = [format!("id=\"{id}\""), format!("id='{id}'")];
for pat in &patterns {
let Some(idx) = haystack.find(pat.as_str()) else {
continue;
};
let tag_start = haystack[..idx].rfind('<')?;
// Reject closing tags / comments accidentally matching.
let after_lt = haystack.as_bytes().get(tag_start + 1).copied()?;
if after_lt == b'/' || after_lt == b'!' {
continue;
}
let name_end = haystack[tag_start + 1..]
.find(|c: char| c.is_whitespace() || c == '>' || c == '/')
.map(|i| tag_start + 1 + i)
.unwrap_or(idx);
let tag_name = haystack[tag_start + 1..name_end].trim();
if tag_name.is_empty() {
continue;
}
let after_id = idx + pat.len();
let open_gt = haystack[after_id..].find('>')? + after_id;
// Skip self-closing ``.
if haystack.as_bytes().get(open_gt.saturating_sub(1)) == Some(&b'/') {
continue;
}
let close = format!("{tag_name}>");
// Case-insensitive close search for HTML friendliness.
let rest = &haystack[open_gt + 1..];
let close_rel = rest
.to_ascii_lowercase()
.find(&close.to_ascii_lowercase())?;
let close_idx = open_gt + 1 + close_rel;
let mut out = String::with_capacity(haystack.len() + payload.len());
out.push_str(&haystack[..open_gt + 1]);
out.push_str(payload);
out.push_str(&haystack[close_idx..]);
return Some(out);
}
None
}
/// Append intro + optional form: either inject into `form_target` mount inside intro, or sibling.
fn push_intro_and_form(
buf: &mut String,
intro: &str,
args: &Value,
form_data: Option<&Value>,
form_errors: Option<&Value>,
csrf: Option<&str>,
) {
let form = args.get("form");
let form_id = args
.get("form_id")
.and_then(|v| v.as_str())
.unwrap_or("form");
let target = args
.get("form_target")
.or_else(|| args.get("target"))
.or_else(|| args.get("form_slot"))
.or_else(|| args.get("表单插槽"))
.and_then(|v| v.as_str())
.unwrap_or("");
let form_html = form.map(|f| {
crate::form::render_body(f, form_id, form_data, form_errors, csrf)
});
if let Some(ref html) = form_html {
if !target.is_empty() && !intro.is_empty() {
if let Some(injected) = inject_html_into_id(intro, target, html) {
buf.push_str(&format!("{injected}
"));
return;
}
}
}
if !intro.is_empty() {
buf.push_str(&format!("{intro}
"));
}
if let Some(html) = form_html {
buf.push_str(&html);
}
}
/// True when `back` is a DB field path (`table.col` / `mod.table.col`), not a URL or site path.
fn is_db_bind_back(back: &str) -> bool {
let s = normalize_ref(back);
if s.is_empty()
|| s.contains("://")
|| s.starts_with('/')
|| s.starts_with('#')
|| s.starts_with('?')
{
return false;
}
match parse_site_path(&s) {
SitePath::DbField { .. } => true,
SitePath::LibMember { lib, member } => is_simple_ident(&lib) && is_simple_ident(&member),
SitePath::Plain(p) => {
let parts: Vec<&str> = p.split('.').filter(|x| !x.is_empty()).collect();
parts.len() == 2 && parts.iter().all(|x| is_simple_ident(x))
}
}
}
#[derive(Clone, Debug)]
struct NavLink {
label: String,
href: String,
class: String,
media: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NavWhen {
Always,
Hide,
Auth,
Guest,
}
fn parse_nav_when(raw: &str) -> NavWhen {
let t = raw.trim();
if t.is_empty()
|| matches!(
t,
"*" | "always" | "Always" | "真" | "yes" | "on" | "show" | "all"
)
{
return NavWhen::Always;
}
if matches!(
t,
"hide" | "never" | "off" | "no" | "假" | "否" | "0" | "false" | "False"
) {
return NavWhen::Hide;
}
if matches!(
t,
"auth" | "user" | "登录" | "已登录" | "logged_in" | "logged-in"
) {
return NavWhen::Auth;
}
if matches!(
t,
"guest" | "anon" | "anonymous" | "访客" | "匿名" | "未登录"
) {
return NavWhen::Guest;
}
// Unknown token: keep visible (forward-compatible).
NavWhen::Always
}
/// `Some(true)` logged in, `Some(false)` guest, `None` unknown (do not filter auth/guest).
fn page_auth_state(page: Option<&Value>) -> Option {
let page = page?;
if let Some(v) = page
.get("_nav_user")
.or_else(|| page.get("user"))
.or_else(|| page.get("username"))
.or_else(|| page.get("_user"))
{
match v {
Value::Null => Some(false),
Value::Bool(b) => Some(*b),
Value::String(s) => Some(!s.trim().is_empty()),
Value::Number(n) => Some(n.as_i64().unwrap_or(0) != 0),
_ => Some(true),
}
} else if let Some(v) = page.get("_logged_in").or_else(|| page.get("logged_in")) {
match v {
Value::Bool(b) => Some(*b),
Value::String(s) => Some(matches!(
s.trim(),
"1" | "true" | "True" | "yes" | "on" | "真" | "是"
)),
Value::Number(n) => Some(n.as_i64().unwrap_or(0) != 0),
_ => None,
}
} else {
None
}
}
fn nav_when_visible(when: NavWhen, auth: Option) -> bool {
match when {
NavWhen::Always => true,
NavWhen::Hide => false,
NavWhen::Auth => auth.unwrap_or(true), // unknown → keep (compat)
NavWhen::Guest => match auth {
Some(logged_in) => !logged_in,
None => true,
},
}
}
fn resolve_links(raw: Option<&Value>, db_url: Option<&str>, page: Option<&Value>) -> Vec {
let Some(raw) = raw else {
return Vec::new();
};
let auth = page_auth_state(page);
let binds = as_bind(raw);
let arr = binds.as_array().cloned().unwrap_or_default();
let rows: Vec