Rewrite ext/web around tables and class methods.
Drop bag/scaffold glue and rebuild the web plugin for compose, SQLite CRUD, and listen, with call_lib_path support and a §4 English site sample. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
8041a2274c
commit
9599303c4c
38 files changed
+2772
-4658
No files matched your search
@@ -0,0 +1,180 @@
|
||||
//! Page assemble: compose_components / compose_main.
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::table::{
|
||||
as_bind, as_compose, as_css_named, bind_table_name, normalize_ref, normalize_slot,
|
||||
parse_site_path, SitePath,
|
||||
};
|
||||
|
||||
pub fn compose_components(
|
||||
page: &Value,
|
||||
layout: &Value,
|
||||
mut call_lib: impl FnMut(&str) -> Result<Value, String>,
|
||||
) -> Result<Value, String> {
|
||||
let mut obj = page.as_object().cloned().unwrap_or_default();
|
||||
let rows = as_compose(layout);
|
||||
let mut css = obj
|
||||
.get("styles_css")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let mut slot_class = obj
|
||||
.get("slot_class")
|
||||
.and_then(|v| v.as_object())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut parts = Map::new();
|
||||
let mut compose_out = Vec::new();
|
||||
|
||||
for row in rows.as_array().cloned().unwrap_or_default() {
|
||||
let src_raw = row.get("src").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let style_raw = row.get("style").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if src_raw.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let (name, bind_table) = match parse_site_path(src_raw) {
|
||||
SitePath::LibMember { lib, member } => {
|
||||
let t = call_lib(&format!("{lib}.{member}"))?;
|
||||
(member, t)
|
||||
}
|
||||
SitePath::Plain(s) => {
|
||||
let t = call_lib(&format!("{s}.{s}"))?;
|
||||
(s, t)
|
||||
}
|
||||
SitePath::DbField { .. } => {
|
||||
return Err(format!("component cell cannot be a db field: {src_raw}"));
|
||||
}
|
||||
};
|
||||
let slot = normalize_slot(&name);
|
||||
let style_name = if style_raw.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
match parse_site_path(style_raw) {
|
||||
SitePath::LibMember { lib, member } => {
|
||||
let st = call_lib(&format!("{lib}.{member}"))?;
|
||||
css.push_str(&as_css_named(&member, &st));
|
||||
member
|
||||
}
|
||||
SitePath::Plain(s) => s,
|
||||
SitePath::DbField { .. } => normalize_ref(style_raw),
|
||||
}
|
||||
};
|
||||
let binds = as_bind(&bind_table);
|
||||
match slot.as_str() {
|
||||
"nav" => obj.insert("nav".into(), binds.clone()),
|
||||
"sidebar" => obj.insert("sidebar".into(), binds.clone()),
|
||||
"footer" => obj.insert("footer".into(), binds.clone()),
|
||||
_ => obj.insert("main".into(), binds.clone()),
|
||||
};
|
||||
if !style_name.is_empty() {
|
||||
slot_class.insert(slot.clone(), json!(style_name));
|
||||
}
|
||||
compose_out.push(json!({ "src": name, "style": style_name, "slot": slot }));
|
||||
|
||||
let mut part = Map::new();
|
||||
part.insert("_type".into(), json!("page"));
|
||||
part.insert("slot".into(), json!(slot));
|
||||
part.insert("fragment".into(), json!(slot));
|
||||
match slot.as_str() {
|
||||
"nav" => {
|
||||
part.insert("nav".into(), binds);
|
||||
}
|
||||
"sidebar" => {
|
||||
part.insert("sidebar".into(), binds);
|
||||
}
|
||||
"footer" => {
|
||||
part.insert("footer".into(), binds);
|
||||
}
|
||||
_ => {
|
||||
part.insert("main".into(), binds);
|
||||
}
|
||||
}
|
||||
parts.insert(name, Value::Object(part));
|
||||
}
|
||||
|
||||
obj.insert("compose".into(), Value::Array(compose_out));
|
||||
if !css.is_empty() {
|
||||
obj.insert("styles_css".into(), json!(css));
|
||||
}
|
||||
if !slot_class.is_empty() {
|
||||
obj.insert("slot_class".into(), Value::Object(slot_class));
|
||||
}
|
||||
if !parts.is_empty() {
|
||||
obj.insert("parts".into(), Value::Object(parts));
|
||||
}
|
||||
Ok(Value::Object(obj))
|
||||
}
|
||||
|
||||
pub fn compose_main(
|
||||
page: &Value,
|
||||
main_table: &Value,
|
||||
mut call_lib: impl FnMut(&str) -> Result<Value, String>,
|
||||
) -> Result<Value, String> {
|
||||
let mut obj = page.as_object().cloned().unwrap_or_default();
|
||||
let raw = as_bind(main_table);
|
||||
let arr = raw.as_array().cloned().unwrap_or_default();
|
||||
let mut binds = Vec::new();
|
||||
let mut css = obj
|
||||
.get("styles_css")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
|
||||
for b in arr {
|
||||
let front = b
|
||||
.get("front")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let back_raw = b.get("back").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let css_raw = b.get("css").and_then(|v| v.as_str()).unwrap_or("");
|
||||
|
||||
let back = match parse_site_path(back_raw) {
|
||||
SitePath::DbField { table, field } => format!("{table}.{field}"),
|
||||
SitePath::Plain(s) => s,
|
||||
SitePath::LibMember { lib, member } => {
|
||||
let v = call_lib(&format!("{lib}.{member}"))?;
|
||||
match v {
|
||||
Value::String(s) => s,
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
};
|
||||
let css_name = match parse_site_path(css_raw) {
|
||||
SitePath::LibMember { lib, member } => {
|
||||
let st = call_lib(&format!("{lib}.{member}"))?;
|
||||
css.push_str(&as_css_named(&member, &st));
|
||||
member
|
||||
}
|
||||
SitePath::Plain(s) => s,
|
||||
SitePath::DbField { .. } => normalize_ref(css_raw),
|
||||
};
|
||||
binds.push(json!({ "front": front, "back": back, "css": css_name }));
|
||||
}
|
||||
|
||||
if let Some(t) = bind_table_name(&binds) {
|
||||
obj.insert("table".into(), json!(t));
|
||||
}
|
||||
obj.insert("main".into(), Value::Array(binds.clone()));
|
||||
if !css.is_empty() {
|
||||
obj.insert("styles_css".into(), json!(css));
|
||||
}
|
||||
|
||||
let mut parts = obj
|
||||
.get("parts")
|
||||
.and_then(|v| v.as_object())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut part = Map::new();
|
||||
part.insert("_type".into(), json!("page"));
|
||||
part.insert("slot".into(), json!("main"));
|
||||
part.insert("fragment".into(), json!("main"));
|
||||
part.insert("main".into(), Value::Array(binds));
|
||||
if let Some(intro) = obj.get("intro") {
|
||||
part.insert("intro".into(), intro.clone());
|
||||
}
|
||||
parts.insert("index".into(), Value::Object(part));
|
||||
obj.insert("parts".into(), Value::Object(parts));
|
||||
Ok(Value::Object(obj))
|
||||
}
|
||||
+215
-709
@@ -1,782 +1,288 @@
|
||||
//! SQLite helpers: open, migrate, define, CRUD.
|
||||
//! SQLite helpers for `# db` CRUD (`init` / `insert` / `select` / `get` / `update` / `delete` / `exec`).
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use rusqlite::{params_from_iter, Connection, ToSql};
|
||||
use rusqlite::{types::ValueRef, Connection, OptionalExtension, params_from_iter};
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn resolve_sqlite_path(url: &str) -> Result<PathBuf, String> {
|
||||
let u = url.trim();
|
||||
let path = if let Some(rest) = u.strip_prefix("sqlite:") {
|
||||
let rest = rest.trim();
|
||||
if let Some(r) = rest.strip_prefix("///") {
|
||||
// sqlite:///abs/path
|
||||
format!("/{r}")
|
||||
} else if rest.starts_with('/') {
|
||||
// sqlite:/abs/path
|
||||
rest.to_string()
|
||||
} else {
|
||||
rest.trim_start_matches("./").to_string()
|
||||
}
|
||||
} else if u.starts_with("postgres://") || u.starts_with("postgresql://") {
|
||||
return Err("postgres not enabled in this build (W4); use sqlite: URL".into());
|
||||
} else {
|
||||
u.to_string()
|
||||
};
|
||||
let p = PathBuf::from(if path.is_empty() {
|
||||
"./data/app.db"
|
||||
} else {
|
||||
&path
|
||||
});
|
||||
if let Some(parent) = p.parent() {
|
||||
fn open(url: &str) -> Result<Connection, String> {
|
||||
let path = url
|
||||
.strip_prefix("sqlite:")
|
||||
.or_else(|| url.strip_prefix("SQLITE:"))
|
||||
.unwrap_or(url);
|
||||
if let Some(parent) = PathBuf::from(path).parent() {
|
||||
if !parent.as_os_str().is_empty() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("create db dir: {e}"))?;
|
||||
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
Ok(p)
|
||||
let conn = Connection::open(path).map_err(|e| e.to_string())?;
|
||||
conn.execute_batch("PRAGMA foreign_keys = ON;")
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(conn)
|
||||
}
|
||||
|
||||
pub fn open_db(url: &str) -> Result<Connection, String> {
|
||||
let path = resolve_sqlite_path(url)?;
|
||||
Connection::open(&path).map_err(|e| format!("open db {}: {e}", path.display()))
|
||||
}
|
||||
|
||||
fn ident_ok(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& s.chars()
|
||||
fn ident(s: &str) -> Result<&str, String> {
|
||||
let s = s.trim();
|
||||
if s.is_empty()
|
||||
|| !s
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '_')
|
||||
}
|
||||
|
||||
fn quote_ident(s: &str) -> Result<String, String> {
|
||||
if !ident_ok(s) {
|
||||
return Err(format!("invalid identifier `{s}`"));
|
||||
{
|
||||
return Err(format!("bad identifier `{s}`"));
|
||||
}
|
||||
Ok(format!("\"{s}\""))
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
fn sql_type(t: &str) -> &'static str {
|
||||
match t.trim().to_ascii_lowercase().as_str() {
|
||||
"int" | "integer" | "bigint" => "INTEGER",
|
||||
"bool" | "boolean" => "INTEGER",
|
||||
"int" | "integer" => "INTEGER",
|
||||
"real" | "float" | "double" => "REAL",
|
||||
"timestamp" | "datetime" => "TEXT",
|
||||
"blob" => "BLOB",
|
||||
_ => "TEXT",
|
||||
}
|
||||
}
|
||||
|
||||
/// Ensure migrations table and apply `*.sql` files in `dir` (sorted).
|
||||
pub fn migrate(url: &str, dir: &str) -> Result<Value, String> {
|
||||
let conn = open_db(url)?;
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS _marqdo_migrations (
|
||||
id TEXT PRIMARY KEY,
|
||||
applied_at TEXT NOT NULL
|
||||
);",
|
||||
)
|
||||
.map_err(|e| format!("ensure migrations table: {e}"))?;
|
||||
|
||||
let dir = Path::new(dir);
|
||||
if !dir.is_dir() {
|
||||
return Ok(json!({ "ok": true, "applied": [], "note": "no migrations dir" }));
|
||||
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(),
|
||||
}
|
||||
let mut files: Vec<_> = fs::read_dir(dir)
|
||||
.map_err(|e| format!("read migrations: {e}"))?
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().and_then(|e| e.to_str()) == Some("sql"))
|
||||
.collect();
|
||||
files.sort();
|
||||
|
||||
let mut applied = Vec::new();
|
||||
for path in files {
|
||||
let id = path
|
||||
.file_name()
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let already: bool = conn
|
||||
.query_row(
|
||||
"SELECT 1 FROM _marqdo_migrations WHERE id = ?1",
|
||||
[&id],
|
||||
|_| Ok(true),
|
||||
)
|
||||
.unwrap_or(false);
|
||||
if already {
|
||||
continue;
|
||||
}
|
||||
let sql = fs::read_to_string(&path).map_err(|e| format!("read {}: {e}", path.display()))?;
|
||||
conn.execute_batch(&sql)
|
||||
.map_err(|e| format!("migrate {id}: {e}"))?;
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
conn.execute(
|
||||
"INSERT INTO _marqdo_migrations (id, applied_at) VALUES (?1, ?2)",
|
||||
[&id, &now],
|
||||
)
|
||||
.map_err(|e| format!("record migration: {e}"))?;
|
||||
applied.push(Value::String(id));
|
||||
}
|
||||
Ok(json!({ "ok": true, "applied": applied }))
|
||||
}
|
||||
|
||||
/// Create table from field list (list of maps: name, type, null, default, unique).
|
||||
pub fn define_table(url: &str, table: &str, fields: &Value, primary: &str) -> Result<Value, String> {
|
||||
let table_q = quote_ident(table)?;
|
||||
let primary = if primary.is_empty() { "id" } else { primary };
|
||||
let rows = match fields {
|
||||
Value::Array(a) => a.clone(),
|
||||
_ => return Err("fields must be a list of maps".into()),
|
||||
};
|
||||
let mut cols = Vec::new();
|
||||
for row in &rows {
|
||||
let name = row
|
||||
fn to_sql(v: &Value) -> rusqlite::types::Value {
|
||||
match v {
|
||||
Value::Null => rusqlite::types::Value::Null,
|
||||
Value::Bool(b) => rusqlite::types::Value::Integer(if *b { 1 } else { 0 }),
|
||||
Value::Number(n) => {
|
||||
if let Some(i) = n.as_i64() {
|
||||
rusqlite::types::Value::Integer(i)
|
||||
} else if let Some(f) = n.as_f64() {
|
||||
rusqlite::types::Value::Real(f)
|
||||
} else {
|
||||
rusqlite::types::Value::Text(n.to_string())
|
||||
}
|
||||
}
|
||||
Value::String(s) => {
|
||||
let t = s.trim();
|
||||
if let Ok(i) = t.parse::<i64>() {
|
||||
rusqlite::types::Value::Integer(i)
|
||||
} else if let Ok(f) = t.parse::<f64>() {
|
||||
if !t.contains('e') && !t.contains('E') && t.contains('.') {
|
||||
rusqlite::types::Value::Real(f)
|
||||
} else {
|
||||
rusqlite::types::Value::Text(s.clone())
|
||||
}
|
||||
} else {
|
||||
rusqlite::types::Value::Text(s.clone())
|
||||
}
|
||||
}
|
||||
other => rusqlite::types::Value::Text(other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn from_sql(v: ValueRef<'_>) -> Value {
|
||||
match v {
|
||||
ValueRef::Null => Value::Null,
|
||||
ValueRef::Integer(i) => json!(i),
|
||||
ValueRef::Real(f) => json!(f),
|
||||
ValueRef::Text(t) => Value::String(String::from_utf8_lossy(t).into_owned()),
|
||||
ValueRef::Blob(b) => Value::String(format!("blob:{}b", b.len())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `fields` = list of {name,type,nullable?} or columnar schema table already normalized.
|
||||
pub fn init(url: &str, table: &str, fields: &Value) -> Result<Value, String> {
|
||||
let table = ident(table)?;
|
||||
let cols = crate::table::as_fields(fields);
|
||||
let arr = cols.as_array().ok_or("fields must be a list")?;
|
||||
if arr.is_empty() {
|
||||
return Err("empty fields".into());
|
||||
}
|
||||
let mut parts = Vec::new();
|
||||
let mut has_pk = false;
|
||||
for c in arr {
|
||||
let name = c
|
||||
.get("name")
|
||||
.or_else(|| row.get("名"))
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "field missing name".to_string())?;
|
||||
let ty = row
|
||||
.or_else(|| c.get("字段"))
|
||||
.map(cell_str)
|
||||
.unwrap_or_default();
|
||||
let name = ident(&name)?;
|
||||
let ty = c
|
||||
.get("type")
|
||||
.or_else(|| row.get("类型"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("text");
|
||||
let nullable = row
|
||||
.get("null")
|
||||
.or_else(|| row.get("可空"))
|
||||
.and_then(|v| v.as_bool())
|
||||
.or_else(|| c.get("类型"))
|
||||
.map(cell_str)
|
||||
.unwrap_or_else(|| "text".into());
|
||||
let nullable = c
|
||||
.get("nullable")
|
||||
.or_else(|| c.get("可空"))
|
||||
.and_then(|v| match v {
|
||||
Value::Bool(b) => Some(*b),
|
||||
Value::String(s) => Some(matches!(s.as_str(), "true" | "True" | "1" | "是" | "可")),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(true);
|
||||
let unique = row
|
||||
.get("unique")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
let name_q = quote_ident(name)?;
|
||||
let mut col = format!("{name_q} {}", sql_type(ty));
|
||||
if name == primary {
|
||||
let mut col = format!("\"{name}\" {}", sql_type(&ty));
|
||||
if name == "id" && !has_pk {
|
||||
col.push_str(" PRIMARY KEY");
|
||||
if sql_type(ty) == "INTEGER" {
|
||||
if sql_type(&ty) == "INTEGER" {
|
||||
col.push_str(" AUTOINCREMENT");
|
||||
}
|
||||
has_pk = true;
|
||||
} else if !nullable {
|
||||
col.push_str(" NOT NULL");
|
||||
}
|
||||
if unique && name != primary {
|
||||
col.push_str(" UNIQUE");
|
||||
}
|
||||
if let Some(def) = row.get("default").or_else(|| row.get("默认")) {
|
||||
if let Some(s) = def.as_str() {
|
||||
if s.eq_ignore_ascii_case("now") {
|
||||
col.push_str(" DEFAULT (datetime('now'))");
|
||||
} else if s == "false" {
|
||||
col.push_str(" DEFAULT 0");
|
||||
} else if s == "true" {
|
||||
col.push_str(" DEFAULT 1");
|
||||
} else {
|
||||
col.push_str(&format!(" DEFAULT '{s}'"));
|
||||
}
|
||||
} else if let Some(b) = def.as_bool() {
|
||||
col.push_str(if b { " DEFAULT 1" } else { " DEFAULT 0" });
|
||||
} else if let Some(n) = def.as_i64() {
|
||||
col.push_str(&format!(" DEFAULT {n}"));
|
||||
}
|
||||
}
|
||||
cols.push(col);
|
||||
}
|
||||
if cols.is_empty() {
|
||||
return Err("no fields".into());
|
||||
parts.push(col);
|
||||
}
|
||||
let sql = format!(
|
||||
"CREATE TABLE IF NOT EXISTS {table_q} ({});",
|
||||
cols.join(", ")
|
||||
"CREATE TABLE IF NOT EXISTS \"{table}\" ({})",
|
||||
parts.join(", ")
|
||||
);
|
||||
let conn = open_db(url)?;
|
||||
conn.execute_batch(&sql)
|
||||
.map_err(|e| format!("define table: {e}"))?;
|
||||
Ok(json!({ "ok": true, "table": table, "sql": sql }))
|
||||
let conn = open(url)?;
|
||||
conn.execute_batch(&sql).map_err(|e| e.to_string())?;
|
||||
Ok(json!({ "_type": "db_table", "name": table, "url": url }))
|
||||
}
|
||||
|
||||
fn row_values(
|
||||
row: &rusqlite::Row<'_>,
|
||||
names: &[String],
|
||||
) -> Result<Value, String> {
|
||||
let mut map = Map::new();
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
let v: Value = match row.get_ref(i).map_err(|e| e.to_string())? {
|
||||
rusqlite::types::ValueRef::Null => Value::Null,
|
||||
rusqlite::types::ValueRef::Integer(n) => json!(n),
|
||||
rusqlite::types::ValueRef::Real(f) => json!(f),
|
||||
rusqlite::types::ValueRef::Text(t) => {
|
||||
Value::String(String::from_utf8_lossy(t).into_owned())
|
||||
}
|
||||
rusqlite::types::ValueRef::Blob(b) => {
|
||||
Value::String(format!("blob:{}bytes", b.len()))
|
||||
}
|
||||
};
|
||||
map.insert(name.clone(), v);
|
||||
}
|
||||
Ok(Value::Object(map))
|
||||
}
|
||||
|
||||
pub fn query_all(url: &str, table: &str, limit: i64) -> Result<Value, String> {
|
||||
let table_q = quote_ident(table)?;
|
||||
let lim = if limit <= 0 { 200 } else { limit.min(2000) };
|
||||
let conn = open_db(url)?;
|
||||
let sql = format!("SELECT * FROM {table_q} LIMIT {lim}");
|
||||
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
|
||||
let names: Vec<String> = (0..stmt.column_count())
|
||||
.map(|i| stmt.column_name(i).unwrap_or("?").to_string())
|
||||
.collect();
|
||||
let mut rows = stmt.query([]).map_err(|e| e.to_string())?;
|
||||
let mut out = Vec::new();
|
||||
while let Some(row) = rows.next().map_err(|e| e.to_string())? {
|
||||
out.push(row_values(row, &names)?);
|
||||
}
|
||||
Ok(json!({ "rows": out, "count": out.len() }))
|
||||
}
|
||||
|
||||
pub fn exec_sql(url: &str, sql: &str, args: Option<&Value>) -> Result<Value, String> {
|
||||
let conn = open_db(url)?;
|
||||
let bind = json_args(args)?;
|
||||
let refs: Vec<&dyn ToSql> = bind.iter().map(|v| v as &dyn ToSql).collect();
|
||||
let n = conn
|
||||
.execute(sql, params_from_iter(refs))
|
||||
.map_err(|e| format!("exec: {e}"))?;
|
||||
Ok(json!({ "ok": true, "changes": n }))
|
||||
}
|
||||
|
||||
pub fn query_sql(url: &str, sql: &str, args: Option<&Value>) -> Result<Value, String> {
|
||||
let conn = open_db(url)?;
|
||||
let bind = json_args(args)?;
|
||||
let mut stmt = conn.prepare(sql).map_err(|e| e.to_string())?;
|
||||
let names: Vec<String> = (0..stmt.column_count())
|
||||
.map(|i| stmt.column_name(i).unwrap_or("?").to_string())
|
||||
.collect();
|
||||
let refs: Vec<&dyn ToSql> = bind.iter().map(|v| v as &dyn ToSql).collect();
|
||||
let mut rows = stmt
|
||||
.query(params_from_iter(refs))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut out = Vec::new();
|
||||
while let Some(row) = rows.next().map_err(|e| e.to_string())? {
|
||||
let mut map = Map::new();
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
let v: Value = match row.get_ref(i).map_err(|e| e.to_string())? {
|
||||
rusqlite::types::ValueRef::Null => Value::Null,
|
||||
rusqlite::types::ValueRef::Integer(n) => json!(n),
|
||||
rusqlite::types::ValueRef::Real(f) => json!(f),
|
||||
rusqlite::types::ValueRef::Text(t) => {
|
||||
Value::String(String::from_utf8_lossy(t).into_owned())
|
||||
}
|
||||
rusqlite::types::ValueRef::Blob(b) => {
|
||||
Value::String(format!("blob:{}bytes", b.len()))
|
||||
}
|
||||
};
|
||||
map.insert(name.clone(), v);
|
||||
}
|
||||
out.push(Value::Object(map));
|
||||
}
|
||||
Ok(json!({ "rows": out, "count": out.len() }))
|
||||
}
|
||||
|
||||
enum SqlVal {
|
||||
Null,
|
||||
Int(i64),
|
||||
Real(f64),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
impl ToSql for SqlVal {
|
||||
fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
|
||||
Ok(match self {
|
||||
SqlVal::Null => rusqlite::types::ToSqlOutput::Owned(rusqlite::types::Value::Null),
|
||||
SqlVal::Int(n) => rusqlite::types::ToSqlOutput::Owned(rusqlite::types::Value::Integer(*n)),
|
||||
SqlVal::Real(f) => rusqlite::types::ToSqlOutput::Owned(rusqlite::types::Value::Real(*f)),
|
||||
SqlVal::Text(s) => {
|
||||
rusqlite::types::ToSqlOutput::Owned(rusqlite::types::Value::Text(s.clone()))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn json_args(args: Option<&Value>) -> Result<Vec<SqlVal>, String> {
|
||||
let Some(v) = args else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let arr = v
|
||||
.as_array()
|
||||
.ok_or_else(|| "args must be a JSON array".to_string())?;
|
||||
let mut out = Vec::new();
|
||||
for a in arr {
|
||||
out.push(match a {
|
||||
Value::Null => SqlVal::Null,
|
||||
Value::Bool(b) => SqlVal::Int(if *b { 1 } else { 0 }),
|
||||
Value::Number(n) => {
|
||||
if let Some(i) = n.as_i64() {
|
||||
SqlVal::Int(i)
|
||||
} else if let Some(f) = n.as_f64() {
|
||||
SqlVal::Real(f)
|
||||
} else {
|
||||
SqlVal::Text(n.to_string())
|
||||
}
|
||||
}
|
||||
Value::String(s) => SqlVal::Text(s.clone()),
|
||||
other => SqlVal::Text(other.to_string()),
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn insert_row(url: &str, table: &str, row: &Value) -> Result<Value, String> {
|
||||
let obj = row
|
||||
.as_object()
|
||||
.ok_or_else(|| "row must be a map".to_string())?;
|
||||
let table_q = quote_ident(table)?;
|
||||
let mut cols = Vec::new();
|
||||
let mut placeholders = Vec::new();
|
||||
let mut vals = Vec::new();
|
||||
for (k, v) in obj {
|
||||
if !ident_ok(k) {
|
||||
return Err(format!("bad column `{k}`"));
|
||||
}
|
||||
cols.push(format!("\"{k}\""));
|
||||
placeholders.push("?");
|
||||
vals.push(v.clone());
|
||||
}
|
||||
if cols.is_empty() {
|
||||
return Err("empty row".into());
|
||||
}
|
||||
let sql = format!(
|
||||
"INSERT INTO {table_q} ({}) VALUES ({})",
|
||||
cols.join(", "),
|
||||
placeholders.join(", ")
|
||||
);
|
||||
let r = exec_sql(url, &sql, Some(&Value::Array(vals)))?;
|
||||
let _ = admin_log(url, "create", table, None, Some(row));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Insert many rows from `as_rows` output.
|
||||
pub fn insert_rows(url: &str, table: &str, rows: &Value) -> Result<Value, String> {
|
||||
let arr = rows
|
||||
.as_array()
|
||||
.ok_or_else(|| "rows must be an array".to_string())?;
|
||||
let mut n = 0;
|
||||
pub fn insert(url: &str, table: &str, rows: &Value) -> Result<Value, String> {
|
||||
let table = ident(table)?;
|
||||
let rows = crate::table::as_rows(rows);
|
||||
let arr = rows.as_array().ok_or("rows must be a list")?;
|
||||
let conn = open(url)?;
|
||||
let mut n = 0i64;
|
||||
for row in arr {
|
||||
insert_row(url, table, row)?;
|
||||
let obj = row.as_object().ok_or("row must be a map")?;
|
||||
let mut cols = Vec::new();
|
||||
let mut placeholders = Vec::new();
|
||||
let mut vals = Vec::new();
|
||||
for (k, v) in obj {
|
||||
if k == "@" || k == "行" || k == "row" {
|
||||
continue;
|
||||
}
|
||||
let _ = ident(k)?;
|
||||
cols.push(format!("\"{k}\""));
|
||||
placeholders.push("?");
|
||||
vals.push(to_sql(v));
|
||||
}
|
||||
if cols.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let sql = format!(
|
||||
"INSERT INTO \"{table}\" ({}) VALUES ({})",
|
||||
cols.join(", "),
|
||||
placeholders.join(", ")
|
||||
);
|
||||
conn.execute(&sql, params_from_iter(vals.iter().cloned()))
|
||||
.map_err(|e| e.to_string())?;
|
||||
n += 1;
|
||||
}
|
||||
Ok(json!({ "ok": true, "inserted": n }))
|
||||
}
|
||||
|
||||
pub fn get_row(url: &str, table: &str, id: &str) -> Result<Value, String> {
|
||||
let table_q = quote_ident(table)?;
|
||||
let conn = open_db(url)?;
|
||||
let sql = format!("SELECT * FROM {table_q} WHERE \"id\" = ?1 LIMIT 1");
|
||||
pub fn select(url: &str, table: &str, limit: i64) -> Result<Value, String> {
|
||||
let table = ident(table)?;
|
||||
let conn = open(url)?;
|
||||
let sql = format!("SELECT * FROM \"{table}\" LIMIT ?1");
|
||||
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
|
||||
let names: Vec<String> = (0..stmt.column_count())
|
||||
.map(|i| stmt.column_name(i).unwrap_or("?").to_string())
|
||||
.collect();
|
||||
let mut rows = stmt.query(rusqlite::params![id]).map_err(|e| e.to_string())?;
|
||||
let Some(row) = rows.next().map_err(|e| e.to_string())? else {
|
||||
return Err(format!("row id={id} not found"));
|
||||
};
|
||||
row_values(row, &names)
|
||||
let mut rows = Vec::new();
|
||||
let mut rows_iter = stmt
|
||||
.query(rusqlite::params![limit])
|
||||
.map_err(|e| e.to_string())?;
|
||||
while let Some(r) = rows_iter.next().map_err(|e| e.to_string())? {
|
||||
let mut m = Map::new();
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
m.insert(name.clone(), from_sql(r.get_ref(i).map_err(|e| e.to_string())?));
|
||||
}
|
||||
rows.push(Value::Object(m));
|
||||
}
|
||||
Ok(json!({ "rows": rows }))
|
||||
}
|
||||
|
||||
pub fn update_row(url: &str, table: &str, id: &str, row: &Value) -> Result<Value, String> {
|
||||
let obj = row
|
||||
.as_object()
|
||||
.ok_or_else(|| "row must be a map".to_string())?;
|
||||
let table_q = quote_ident(table)?;
|
||||
pub fn get(url: &str, table: &str, id: &str) -> Result<Value, String> {
|
||||
let table = ident(table)?;
|
||||
let conn = open(url)?;
|
||||
let sql = format!("SELECT * FROM \"{table}\" WHERE \"id\" = ?1 LIMIT 1");
|
||||
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
|
||||
let names: Vec<String> = (0..stmt.column_count())
|
||||
.map(|i| stmt.column_name(i).unwrap_or("?").to_string())
|
||||
.collect();
|
||||
let row = stmt
|
||||
.query_row(rusqlite::params![id], |r| {
|
||||
let mut m = Map::new();
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
m.insert(name.clone(), from_sql(r.get_ref(i)?));
|
||||
}
|
||||
Ok(Value::Object(m))
|
||||
})
|
||||
.optional()
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(row.unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
pub fn update(url: &str, table: &str, id: &str, row: &Value) -> Result<Value, String> {
|
||||
let table = ident(table)?;
|
||||
let obj = row.as_object().ok_or("row must be a map")?;
|
||||
let mut sets = Vec::new();
|
||||
let mut vals = Vec::new();
|
||||
for (k, v) in obj {
|
||||
if k == "id" || !ident_ok(k) {
|
||||
if k == "id" {
|
||||
continue;
|
||||
}
|
||||
let _ = ident(k)?;
|
||||
sets.push(format!("\"{k}\" = ?"));
|
||||
vals.push(v.clone());
|
||||
vals.push(to_sql(v));
|
||||
}
|
||||
if sets.is_empty() {
|
||||
return Err("nothing to update".into());
|
||||
}
|
||||
vals.push(json!(id));
|
||||
vals.push(rusqlite::types::Value::Text(id.to_string()));
|
||||
let sql = format!(
|
||||
"UPDATE {table_q} SET {} WHERE \"id\" = ?",
|
||||
"UPDATE \"{table}\" SET {} WHERE \"id\" = ?",
|
||||
sets.join(", ")
|
||||
);
|
||||
let r = exec_sql(url, &sql, Some(&Value::Array(vals)))?;
|
||||
let _ = admin_log(url, "update", table, Some(id), Some(row));
|
||||
Ok(r)
|
||||
let conn = open(url)?;
|
||||
let n = conn
|
||||
.execute(&sql, params_from_iter(vals.iter().cloned()))
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(json!({ "ok": true, "updated": n }))
|
||||
}
|
||||
|
||||
pub fn delete_row(url: &str, table: &str, id: &str) -> Result<Value, String> {
|
||||
let table_q = quote_ident(table)?;
|
||||
let sql = format!("DELETE FROM {table_q} WHERE \"id\" = ?");
|
||||
let r = exec_sql(url, &sql, Some(&json!([id])))?;
|
||||
let _ = admin_log(url, "delete", table, Some(id), None);
|
||||
Ok(r)
|
||||
pub fn delete(url: &str, table: &str, id: &str) -> Result<Value, String> {
|
||||
let table = ident(table)?;
|
||||
let conn = open(url)?;
|
||||
let sql = format!("DELETE FROM \"{table}\" WHERE \"id\" = ?1");
|
||||
let n = conn
|
||||
.execute(&sql, rusqlite::params![id])
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(json!({ "ok": true, "deleted": n }))
|
||||
}
|
||||
|
||||
pub fn ensure_admin_log(url: &str) -> Result<(), String> {
|
||||
let conn = open_db(url)?;
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS _marqdo_admin_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
action TEXT NOT NULL,
|
||||
table_name TEXT NOT NULL,
|
||||
row_id TEXT,
|
||||
detail TEXT
|
||||
);",
|
||||
)
|
||||
.map_err(|e| format!("ensure admin log: {e}"))?;
|
||||
Ok(())
|
||||
pub fn exec(url: &str, sql: &str, args: Option<&Value>) -> Result<Value, String> {
|
||||
let conn = open(url)?;
|
||||
let vals: Vec<rusqlite::types::Value> = match args {
|
||||
Some(Value::Array(a)) => a.iter().map(to_sql).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let n = conn
|
||||
.execute(sql, params_from_iter(vals.iter().cloned()))
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(json!({ "ok": true, "changes": n }))
|
||||
}
|
||||
|
||||
pub fn admin_log(
|
||||
url: &str,
|
||||
action: &str,
|
||||
table: &str,
|
||||
row_id: Option<&str>,
|
||||
detail: Option<&Value>,
|
||||
) -> Result<(), String> {
|
||||
ensure_admin_log(url)?;
|
||||
let detail_s = detail
|
||||
.map(|v| v.to_string())
|
||||
.unwrap_or_default();
|
||||
exec_sql(
|
||||
url,
|
||||
"INSERT INTO _marqdo_admin_log (action, table_name, row_id, detail) VALUES (?, ?, ?, ?)",
|
||||
Some(&json!([action, table, row_id.unwrap_or(""), detail_s])),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// User tables for admin (skip sqlite_* and _marqdo_*).
|
||||
pub fn list_user_tables(url: &str) -> Result<Vec<String>, String> {
|
||||
let conn = open_db(url)?;
|
||||
pub fn list_tables(url: &str) -> Result<Vec<String>, String> {
|
||||
let conn = open(url)?;
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT name FROM sqlite_master
|
||||
WHERE type='table'
|
||||
AND name NOT LIKE 'sqlite_%'
|
||||
AND name NOT LIKE '_marqdo_%'
|
||||
ORDER BY name",
|
||||
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_marqdo%' ORDER BY name",
|
||||
)
|
||||
.map_err(|e| format!("list tables: {e}"))?;
|
||||
.map_err(|e| e.to_string())?;
|
||||
let rows = stmt
|
||||
.query_map([], |r| r.get::<_, String>(0))
|
||||
.map_err(|e| format!("list tables query: {e}"))?;
|
||||
let mut out = Vec::new();
|
||||
for r in rows {
|
||||
out.push(r.map_err(|e| format!("list tables row: {e}"))?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Column names via PRAGMA table_info.
|
||||
pub fn table_columns(url: &str, table: &str) -> Result<Vec<String>, String> {
|
||||
if !ident_ok(table) {
|
||||
return Err(format!("bad table `{table}`"));
|
||||
}
|
||||
let conn = open_db(url)?;
|
||||
let mut stmt = conn
|
||||
.prepare(&format!("PRAGMA table_info(\"{table}\")"))
|
||||
.map_err(|e| format!("pragma: {e}"))?;
|
||||
let rows = stmt
|
||||
.query_map([], |r| r.get::<_, String>(1))
|
||||
.map_err(|e| format!("pragma map: {e}"))?;
|
||||
let mut out = Vec::new();
|
||||
for r in rows {
|
||||
out.push(r.map_err(|e| format!("pragma row: {e}"))?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn admin_shell(title: &str, body: &str, tables: &[String], current: Option<&str>) -> String {
|
||||
let mut side = Vec::new();
|
||||
side.push(json!({"label": "Dashboard", "href": "/admin"}));
|
||||
for t in tables {
|
||||
let label = if current == Some(t.as_str()) {
|
||||
format!("· {t}")
|
||||
} else {
|
||||
t.clone()
|
||||
};
|
||||
side.push(json!({"label": label, "href": format!("/admin/{t}")}));
|
||||
}
|
||||
side.push(json!({"label": "Log", "href": "/admin/log"}));
|
||||
crate::page::render_page(&json!({
|
||||
"title": title,
|
||||
"nav": [
|
||||
{"label": "Site", "href": "/"},
|
||||
{"label": "Admin", "href": "/admin"},
|
||||
{"label": "Log", "href": "/admin/log"}
|
||||
],
|
||||
"sidebar": side,
|
||||
"intro": body,
|
||||
}))
|
||||
}
|
||||
|
||||
fn admin_bar(title: &str, crumbs: &str, actions: &str) -> String {
|
||||
format!(
|
||||
"<div class=\"admin-page\">\
|
||||
<header class=\"admin-bar\">\
|
||||
<div class=\"admin-bar-text\">\
|
||||
<p class=\"admin-crumbs\">{crumbs}</p>\
|
||||
<h1>{title}</h1>\
|
||||
</div>\
|
||||
<div class=\"admin-actions\">{actions}</div>\
|
||||
</header>"
|
||||
)
|
||||
}
|
||||
|
||||
fn cell_display(v: &Value) -> String {
|
||||
match v {
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Null => String::new(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn admin_home_html(url: Option<&str>, tables: &[String]) -> String {
|
||||
let count = tables.len();
|
||||
let actions = "<a class=\"btn\" href=\"/admin/log\">View log</a>";
|
||||
let mut html = admin_bar("Dashboard", "Admin", actions);
|
||||
html.push_str(&format!(
|
||||
"<p class=\"admin-lead\">{count} table(s) in the database.</p>"
|
||||
));
|
||||
if tables.is_empty() {
|
||||
html.push_str(
|
||||
"<p class=\"admin-empty\">No user tables yet. Define one with <code>db.init</code>.</p>",
|
||||
);
|
||||
} else {
|
||||
html.push_str("<div class=\"admin-cards\">");
|
||||
for t in tables {
|
||||
let t_e = crate::page::html_escape(t);
|
||||
let n = url
|
||||
.and_then(|u| query_all(u, t, 200).ok())
|
||||
.and_then(|d| d.get("count").and_then(|v| v.as_u64()))
|
||||
.unwrap_or(0);
|
||||
html.push_str(&format!(
|
||||
"<article class=\"admin-card\">\
|
||||
<h2>{t_e}</h2>\
|
||||
<p class=\"admin-meta\">{n} rows</p>\
|
||||
<div class=\"admin-card-actions\">\
|
||||
<a class=\"btn\" href=\"/admin/{t_e}\">Open</a>\
|
||||
<a class=\"btn btn-ghost\" href=\"/admin/{t_e}/new\">New</a>\
|
||||
</div>\
|
||||
</article>"
|
||||
));
|
||||
}
|
||||
html.push_str("</div>");
|
||||
}
|
||||
html.push_str("</div>");
|
||||
admin_shell("Admin", &html, tables, None)
|
||||
}
|
||||
|
||||
pub fn admin_list_html(url: &str, table: &str) -> Result<String, String> {
|
||||
let tables = list_user_tables(url).unwrap_or_default();
|
||||
let cols = table_columns(url, table)?;
|
||||
let data = query_all(url, table, 200)?;
|
||||
let rows = data
|
||||
.get("rows")
|
||||
.and_then(|v| v.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let t = crate::page::html_escape(table);
|
||||
let actions = format!("<a class=\"btn\" href=\"/admin/{t}/new\">New row</a>");
|
||||
let mut html = admin_bar(
|
||||
table,
|
||||
&format!("<a href=\"/admin\">Admin</a> / {t}"),
|
||||
&actions,
|
||||
);
|
||||
let headers = if cols.is_empty() {
|
||||
rows.first()
|
||||
.and_then(|r| r.as_object())
|
||||
.map(|m| m.keys().cloned().collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
cols.clone()
|
||||
};
|
||||
html.push_str("<div class=\"content table-wrap admin-table\"><table><thead><tr>");
|
||||
for k in &headers {
|
||||
html.push_str(&format!("<th>{}</th>", crate::page::html_escape(k)));
|
||||
}
|
||||
html.push_str("<th class=\"col-actions\">Actions</th></tr></thead><tbody>");
|
||||
if rows.is_empty() {
|
||||
html.push_str(&format!(
|
||||
"<tr><td colspan=\"{}\">No rows yet.</td></tr>",
|
||||
headers.len() + 1
|
||||
));
|
||||
} else {
|
||||
for r in &rows {
|
||||
html.push_str("<tr>");
|
||||
let obj = r.as_object().cloned().unwrap_or_default();
|
||||
for k in &headers {
|
||||
let cell = obj.get(k).map(cell_display).unwrap_or_default();
|
||||
let truncated = if cell.chars().count() > 120 {
|
||||
let s: String = cell.chars().take(117).collect();
|
||||
format!("{s}…")
|
||||
} else {
|
||||
cell
|
||||
};
|
||||
html.push_str(&format!(
|
||||
"<td>{}</td>",
|
||||
crate::page::html_escape(&truncated)
|
||||
));
|
||||
}
|
||||
let id = obj.get("id").map(cell_display).unwrap_or_default();
|
||||
let id_e = crate::page::html_escape(&id);
|
||||
html.push_str(&format!(
|
||||
"<td class=\"col-actions\">\
|
||||
<a class=\"btn btn-small\" href=\"/admin/{t}/{id_e}/edit\">Edit</a>\
|
||||
<form class=\"inline-form\" method=\"post\" action=\"/admin/{t}/{id_e}/delete\" \
|
||||
onsubmit=\"return confirm('Delete row {id_e}?');\">\
|
||||
<button type=\"submit\" class=\"btn btn-small btn-danger\">Delete</button></form>\
|
||||
</td></tr>"
|
||||
));
|
||||
}
|
||||
}
|
||||
html.push_str("</tbody></table></div></div>");
|
||||
Ok(admin_shell(
|
||||
&format!("Admin · {table}"),
|
||||
&html,
|
||||
&tables,
|
||||
Some(table),
|
||||
))
|
||||
}
|
||||
|
||||
fn form_fields(cols: &[String], values: Option<&Map<String, Value>>) -> String {
|
||||
let mut fields = String::from("<div class=\"admin-form-fields\">");
|
||||
let mut any = false;
|
||||
for c in cols {
|
||||
if c == "id" {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
let name = crate::page::html_escape(c);
|
||||
let val = values
|
||||
.and_then(|m| m.get(c))
|
||||
.map(cell_display)
|
||||
.unwrap_or_default();
|
||||
let val_e = crate::page::html_escape(&val);
|
||||
if c == "body" || c == "content" || c == "正文" || c == "detail" {
|
||||
fields.push_str(&format!(
|
||||
"<label class=\"admin-field\"><span>{name}</span>\
|
||||
<textarea name=\"{name}\" rows=\"6\">{val_e}</textarea></label>"
|
||||
));
|
||||
} else {
|
||||
fields.push_str(&format!(
|
||||
"<label class=\"admin-field\"><span>{name}</span>\
|
||||
<input name=\"{name}\" value=\"{val_e}\"/></label>"
|
||||
));
|
||||
}
|
||||
}
|
||||
if !any {
|
||||
fields.push_str("<p class=\"admin-empty\">No editable columns.</p>");
|
||||
}
|
||||
fields.push_str("</div>");
|
||||
fields
|
||||
}
|
||||
|
||||
pub fn admin_new_form_html(url: &str, table: &str) -> Result<String, String> {
|
||||
let tables = list_user_tables(url).unwrap_or_default();
|
||||
let cols = table_columns(url, table)?;
|
||||
let fields = form_fields(&cols, None);
|
||||
let t = crate::page::html_escape(table);
|
||||
let actions = format!("<a class=\"btn btn-ghost\" href=\"/admin/{t}\">Cancel</a>");
|
||||
let mut html = admin_bar(
|
||||
&format!("New · {table}"),
|
||||
&format!("<a href=\"/admin\">Admin</a> / <a href=\"/admin/{t}\">{t}</a> / new"),
|
||||
&actions,
|
||||
);
|
||||
html.push_str(&format!(
|
||||
"<form class=\"admin-form\" method=\"post\" action=\"/admin/{t}/new\">{fields}\
|
||||
<div class=\"admin-form-footer\">\
|
||||
<button type=\"submit\" class=\"btn\">Create</button>\
|
||||
<a class=\"btn btn-ghost\" href=\"/admin/{t}\">Back</a>\
|
||||
</div></form></div>"
|
||||
));
|
||||
Ok(admin_shell(
|
||||
&format!("New {table}"),
|
||||
&html,
|
||||
&tables,
|
||||
Some(table),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn admin_edit_form_html(url: &str, table: &str, id: &str) -> Result<String, String> {
|
||||
let tables = list_user_tables(url).unwrap_or_default();
|
||||
let cols = table_columns(url, table)?;
|
||||
let row = get_row(url, table, id)?;
|
||||
let obj = row.as_object();
|
||||
let fields = form_fields(&cols, obj);
|
||||
let t = crate::page::html_escape(table);
|
||||
let id_e = crate::page::html_escape(id);
|
||||
let actions = format!("<a class=\"btn btn-ghost\" href=\"/admin/{t}\">Cancel</a>");
|
||||
let mut html = admin_bar(
|
||||
&format!("Edit · {table} #{id}"),
|
||||
&format!("<a href=\"/admin\">Admin</a> / <a href=\"/admin/{t}\">{t}</a> / {id_e}"),
|
||||
&actions,
|
||||
);
|
||||
html.push_str(&format!(
|
||||
"<form class=\"admin-form\" method=\"post\" action=\"/admin/{t}/{id_e}/edit\">{fields}\
|
||||
<div class=\"admin-form-footer\">\
|
||||
<button type=\"submit\" class=\"btn\">Save</button>\
|
||||
<a class=\"btn btn-ghost\" href=\"/admin/{t}\">Back</a>\
|
||||
</div></form></div>"
|
||||
));
|
||||
Ok(admin_shell(
|
||||
&format!("Edit {table}"),
|
||||
&html,
|
||||
&tables,
|
||||
Some(table),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn admin_log_html(url: &str) -> Result<String, String> {
|
||||
ensure_admin_log(url)?;
|
||||
let tables = list_user_tables(url).unwrap_or_default();
|
||||
let data = query_sql(
|
||||
url,
|
||||
"SELECT id, at, action, table_name, row_id, detail FROM _marqdo_admin_log ORDER BY id DESC LIMIT 200",
|
||||
None,
|
||||
)?;
|
||||
let rows = data
|
||||
.get("rows")
|
||||
.and_then(|v| v.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut html = admin_bar("Activity log", "<a href=\"/admin\">Admin</a> / log", "");
|
||||
html.push_str(
|
||||
"<div class=\"content table-wrap admin-table\"><table><thead><tr>\
|
||||
<th>id</th><th>at</th><th>action</th><th>table</th><th>row</th><th>detail</th>\
|
||||
</tr></thead><tbody>",
|
||||
);
|
||||
if rows.is_empty() {
|
||||
html.push_str("<tr><td colspan=\"6\">No log entries yet.</td></tr>");
|
||||
} else {
|
||||
for r in &rows {
|
||||
let o = r.as_object().cloned().unwrap_or_default();
|
||||
html.push_str("<tr>");
|
||||
for k in ["id", "at", "action", "table_name", "row_id", "detail"] {
|
||||
let mut cell = o.get(k).map(cell_display).unwrap_or_default();
|
||||
if k == "detail" && cell.chars().count() > 80 {
|
||||
cell = format!("{}…", cell.chars().take(77).collect::<String>());
|
||||
}
|
||||
let class = if k == "action" {
|
||||
format!(
|
||||
" class=\"log-action log-{}\"",
|
||||
crate::page::html_escape(&cell)
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
html.push_str(&format!(
|
||||
"<td{class}>{}</td>",
|
||||
crate::page::html_escape(&cell)
|
||||
));
|
||||
}
|
||||
html.push_str("</tr>");
|
||||
}
|
||||
}
|
||||
html.push_str("</tbody></table></div></div>");
|
||||
Ok(admin_shell("Admin log", &html, &tables, None))
|
||||
.map_err(|e| e.to_string())?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(rows)
|
||||
}
|
||||
+117
-375
@@ -1,402 +1,144 @@
|
||||
//! Async HTTP server (tokio + axum).
|
||||
//! Blocking HTTP listen: page shell, `/_part/{id}`, optional `/admin`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::extract::{Path as AxPath, State};
|
||||
use axum::http::{header, StatusCode};
|
||||
use axum::response::{Html, IntoResponse, Response};
|
||||
use axum::extract::{Path, State};
|
||||
use axum::response::{Html, IntoResponse, Redirect, Response};
|
||||
use axum::routing::get;
|
||||
use axum::{Form, Router};
|
||||
use serde_json::{json, Value};
|
||||
use tower_http::services::ServeDir;
|
||||
use axum::Router;
|
||||
use serde_json::{json, Map, Value};
|
||||
use tokio::runtime::Runtime;
|
||||
|
||||
use crate::db;
|
||||
use crate::page;
|
||||
use crate::render;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct AppState {
|
||||
/// Pre-rendered static HTML (optional).
|
||||
pages: HashMap<String, String>,
|
||||
/// Live page configs re-rendered per request (path → page JSON).
|
||||
page_cfgs: HashMap<String, Value>,
|
||||
page: Value,
|
||||
db_url: Option<String>,
|
||||
admin_tables: Vec<String>,
|
||||
admin: bool,
|
||||
}
|
||||
|
||||
fn arg_str(args: &Value, key: &str, default: &str) -> String {
|
||||
args.get(key)
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or(default)
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn arg_u16(args: &Value, key: &str, default: u16) -> u16 {
|
||||
match args.get(key) {
|
||||
Some(Value::Number(n)) => n.as_u64().unwrap_or(default as u64) as u16,
|
||||
Some(Value::String(s)) => s.parse().unwrap_or(default),
|
||||
_ => default,
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_path(p: &str) -> String {
|
||||
if p.is_empty() || p == "/" {
|
||||
return "/".into();
|
||||
}
|
||||
let mut s = p.to_string();
|
||||
if !s.starts_with('/') {
|
||||
s.insert(0, '/');
|
||||
}
|
||||
if s.len() > 1 && s.ends_with('/') {
|
||||
s.pop();
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn build_pages(args: &Value) -> (HashMap<String, String>, HashMap<String, Value>) {
|
||||
let mut pages = HashMap::new();
|
||||
let mut cfgs = HashMap::new();
|
||||
|
||||
if let Some(page_cfg) = args.get("page") {
|
||||
cfgs.insert("/".into(), page_cfg.clone());
|
||||
}
|
||||
|
||||
if let Some(routes) = args.get("routes").and_then(|v| v.as_array()) {
|
||||
for r in routes {
|
||||
let path = r
|
||||
.get("path")
|
||||
.or_else(|| r.get("href"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("/");
|
||||
let path = normalize_path(path);
|
||||
if let Some(cfg) = r.get("page") {
|
||||
cfgs.insert(path.clone(), cfg.clone());
|
||||
} else if let Some(h) = r.get("html").and_then(|v| v.as_str()) {
|
||||
pages.insert(path, h.to_string());
|
||||
} else if r.get("nav").is_some() || r.get("main").is_some() || r.get("intro").is_some()
|
||||
{
|
||||
cfgs.insert(path, r.clone());
|
||||
} else {
|
||||
pages.insert(path, page::render_page(r));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if pages.is_empty() && cfgs.is_empty() {
|
||||
pages.insert("/".into(), page::default_hello_html());
|
||||
}
|
||||
(pages, cfgs)
|
||||
}
|
||||
|
||||
fn resolve_admin_tables(args: &Value, db_url: Option<&str>) -> Vec<String> {
|
||||
let from_args: Vec<String> = args
|
||||
.get("admin_tables")
|
||||
.and_then(|v| v.as_array())
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|v| v.as_str().map(|s| s.to_string()))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if !from_args.is_empty() {
|
||||
return from_args;
|
||||
}
|
||||
let Some(url) = db_url else {
|
||||
return Vec::new();
|
||||
};
|
||||
db::list_user_tables(url).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn render_live(st: &AppState, cfg: &Value) -> String {
|
||||
page::render_page_with_db(cfg, st.db_url.as_deref())
|
||||
}
|
||||
|
||||
async fn serve_page(
|
||||
State(st): State<Arc<AppState>>,
|
||||
axum::extract::OriginalUri(uri): axum::extract::OriginalUri,
|
||||
) -> Response {
|
||||
let path = normalize_path(uri.path());
|
||||
if let Some(cfg) = st.page_cfgs.get(&path) {
|
||||
return Html(render_live(&st, cfg)).into_response();
|
||||
}
|
||||
if let Some(html) = st.pages.get(&path) {
|
||||
return Html(html.clone()).into_response();
|
||||
}
|
||||
(
|
||||
StatusCode::NOT_FOUND,
|
||||
Html(page::render_page(&json!({
|
||||
"title": "404",
|
||||
"main": "<h1>404</h1><p>Not found</p>",
|
||||
"nav": [{"label": "Home", "href": "/"}],
|
||||
}))),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
fn admin_tables_now(st: &AppState) -> Vec<String> {
|
||||
if !st.admin_tables.is_empty() {
|
||||
return st.admin_tables.clone();
|
||||
}
|
||||
let Some(url) = st.db_url.as_ref() else {
|
||||
return Vec::new();
|
||||
};
|
||||
db::list_user_tables(url).unwrap_or_default()
|
||||
}
|
||||
|
||||
async fn admin_home(State(st): State<Arc<AppState>>) -> Response {
|
||||
let tables = admin_tables_now(&st);
|
||||
Html(db::admin_home_html(st.db_url.as_deref(), &tables)).into_response()
|
||||
}
|
||||
|
||||
async fn admin_log_page(State(st): State<Arc<AppState>>) -> Response {
|
||||
let Some(url) = st.db_url.as_ref() else {
|
||||
return Html("<p>No database</p>").into_response();
|
||||
};
|
||||
match db::admin_log_html(url) {
|
||||
Ok(html) => Html(html).into_response(),
|
||||
Err(e) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Html(page::html_escape(&e)),
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn admin_table(State(st): State<Arc<AppState>>, AxPath(table): AxPath<String>) -> Response {
|
||||
let Some(url) = st.db_url.as_ref() else {
|
||||
return Html("<p>No database</p>").into_response();
|
||||
};
|
||||
let tables = admin_tables_now(&st);
|
||||
if !tables.iter().any(|t| t == &table) {
|
||||
return (StatusCode::NOT_FOUND, Html("<p>Unknown table</p>")).into_response();
|
||||
}
|
||||
match db::admin_list_html(url, &table) {
|
||||
Ok(html) => Html(html).into_response(),
|
||||
Err(e) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Html(page::html_escape(&e)),
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn admin_new_get(State(st): State<Arc<AppState>>, AxPath(table): AxPath<String>) -> Response {
|
||||
let Some(url) = st.db_url.as_ref() else {
|
||||
return Html("<p>No database</p>").into_response();
|
||||
};
|
||||
let tables = admin_tables_now(&st);
|
||||
if !tables.iter().any(|t| t == &table) {
|
||||
return (StatusCode::NOT_FOUND, "unknown").into_response();
|
||||
}
|
||||
match db::admin_new_form_html(url, &table) {
|
||||
Ok(html) => Html(html).into_response(),
|
||||
Err(e) => (StatusCode::BAD_REQUEST, Html(page::html_escape(&e))).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn admin_new_post(
|
||||
State(st): State<Arc<AppState>>,
|
||||
AxPath(table): AxPath<String>,
|
||||
Form(form): Form<HashMap<String, String>>,
|
||||
) -> Response {
|
||||
let Some(url) = st.db_url.as_ref() else {
|
||||
return Html("<p>No database</p>").into_response();
|
||||
};
|
||||
let tables = admin_tables_now(&st);
|
||||
if !tables.iter().any(|t| t == &table) {
|
||||
return (StatusCode::NOT_FOUND, "unknown").into_response();
|
||||
}
|
||||
let mut map = serde_json::Map::new();
|
||||
for (k, v) in form {
|
||||
if k == "id" {
|
||||
continue;
|
||||
}
|
||||
map.insert(k, Value::String(v));
|
||||
}
|
||||
match db::insert_row(url, &table, &Value::Object(map)) {
|
||||
Ok(_) => Response::builder()
|
||||
.status(StatusCode::SEE_OTHER)
|
||||
.header(header::LOCATION, format!("/admin/{table}"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
Err(e) => (StatusCode::BAD_REQUEST, Html(page::html_escape(&e))).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn admin_edit_get(
|
||||
State(st): State<Arc<AppState>>,
|
||||
AxPath((table, id)): AxPath<(String, String)>,
|
||||
) -> Response {
|
||||
let Some(url) = st.db_url.as_ref() else {
|
||||
return Html("<p>No database</p>").into_response();
|
||||
};
|
||||
let tables = admin_tables_now(&st);
|
||||
if !tables.iter().any(|t| t == &table) {
|
||||
return (StatusCode::NOT_FOUND, "unknown").into_response();
|
||||
}
|
||||
match db::admin_edit_form_html(url, &table, &id) {
|
||||
Ok(html) => Html(html).into_response(),
|
||||
Err(e) => (StatusCode::BAD_REQUEST, Html(page::html_escape(&e))).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn admin_edit_post(
|
||||
State(st): State<Arc<AppState>>,
|
||||
AxPath((table, id)): AxPath<(String, String)>,
|
||||
Form(form): Form<HashMap<String, String>>,
|
||||
) -> Response {
|
||||
let Some(url) = st.db_url.as_ref() else {
|
||||
return Html("<p>No database</p>").into_response();
|
||||
};
|
||||
let tables = admin_tables_now(&st);
|
||||
if !tables.iter().any(|t| t == &table) {
|
||||
return (StatusCode::NOT_FOUND, "unknown").into_response();
|
||||
}
|
||||
let mut map = serde_json::Map::new();
|
||||
for (k, v) in form {
|
||||
if k == "id" {
|
||||
continue;
|
||||
}
|
||||
map.insert(k, Value::String(v));
|
||||
}
|
||||
match db::update_row(url, &table, &id, &Value::Object(map)) {
|
||||
Ok(_) => Response::builder()
|
||||
.status(StatusCode::SEE_OTHER)
|
||||
.header(header::LOCATION, format!("/admin/{table}"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
Err(e) => (StatusCode::BAD_REQUEST, Html(page::html_escape(&e))).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn admin_delete_post(
|
||||
State(st): State<Arc<AppState>>,
|
||||
AxPath((table, id)): AxPath<(String, String)>,
|
||||
) -> Response {
|
||||
let Some(url) = st.db_url.as_ref() else {
|
||||
return Html("<p>No database</p>").into_response();
|
||||
};
|
||||
let tables = admin_tables_now(&st);
|
||||
if !tables.iter().any(|t| t == &table) {
|
||||
return (StatusCode::NOT_FOUND, "unknown").into_response();
|
||||
}
|
||||
match db::delete_row(url, &table, &id) {
|
||||
Ok(_) => Response::builder()
|
||||
.status(StatusCode::SEE_OTHER)
|
||||
.header(header::LOCATION, format!("/admin/{table}"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
Err(e) => (StatusCode::BAD_REQUEST, Html(page::html_escape(&e))).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocking entry used by ABI: run async server until Ctrl-C or optional duration_ms.
|
||||
pub fn listen(args: &Value) -> Result<Value, String> {
|
||||
let host = arg_str(args, "host", "127.0.0.1");
|
||||
let port = arg_u16(args, "port", 8080);
|
||||
let (pages, page_cfgs) = build_pages(args);
|
||||
let static_dir = args
|
||||
.get("static_dir")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(PathBuf::from);
|
||||
let db_url = args
|
||||
.get("db_url")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
let admin = args
|
||||
.get("admin")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
let admin_tables = resolve_admin_tables(args, db_url.as_deref());
|
||||
let duration_ms = match args.get("duration_ms") {
|
||||
Some(Value::Number(n)) => n.as_u64(),
|
||||
Some(Value::String(s)) => s.parse().ok(),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
pub fn listen(
|
||||
page: &Value,
|
||||
db_url: Option<&str>,
|
||||
host: &str,
|
||||
port: u16,
|
||||
admin: bool,
|
||||
) -> Result<Value, String> {
|
||||
let state = Arc::new(AppState {
|
||||
pages,
|
||||
page_cfgs,
|
||||
db_url: db_url.clone(),
|
||||
admin_tables,
|
||||
page: page.clone(),
|
||||
db_url: db_url.map(|s| s.to_string()),
|
||||
admin,
|
||||
});
|
||||
|
||||
let mut app = Router::new().route("/", get(serve_page));
|
||||
let mut paths: Vec<String> = state.pages.keys().cloned().collect();
|
||||
paths.extend(state.page_cfgs.keys().cloned());
|
||||
for path in paths {
|
||||
if path == "/" {
|
||||
continue;
|
||||
}
|
||||
if admin && (path == "/admin" || path.starts_with("/admin/")) {
|
||||
continue;
|
||||
}
|
||||
app = app.route(&path, get(serve_page));
|
||||
}
|
||||
app = app.fallback(get(serve_page));
|
||||
let app = Router::new()
|
||||
.route("/", get(home))
|
||||
.route("/_part/{id}", get(part))
|
||||
.route("/admin", get(admin_home))
|
||||
.route("/admin/{table}", get(admin_table))
|
||||
.with_state(state);
|
||||
|
||||
if admin {
|
||||
if let Some(url) = db_url.as_deref() {
|
||||
let _ = db::ensure_admin_log(url);
|
||||
}
|
||||
app = app
|
||||
.route("/admin", get(admin_home))
|
||||
.route("/admin/log", get(admin_log_page))
|
||||
.route("/admin/{table}", get(admin_table))
|
||||
.route(
|
||||
"/admin/{table}/new",
|
||||
get(admin_new_get).post(admin_new_post),
|
||||
)
|
||||
.route(
|
||||
"/admin/{table}/{id}/edit",
|
||||
get(admin_edit_get).post(admin_edit_post),
|
||||
)
|
||||
.route("/admin/{table}/{id}/delete", axum::routing::post(admin_delete_post));
|
||||
}
|
||||
|
||||
if let Some(dir) = static_dir {
|
||||
if dir.is_dir() {
|
||||
app = app.nest_service("/static", ServeDir::new(dir));
|
||||
}
|
||||
}
|
||||
|
||||
let app = app.with_state(state);
|
||||
let addr: SocketAddr = format!("{host}:{port}")
|
||||
.parse()
|
||||
.map_err(|e| format!("bad addr: {e}"))?;
|
||||
|
||||
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.map_err(|e| format!("tokio runtime: {e}"))?;
|
||||
.map_err(|e| format!("bad listen addr {host}:{port}: {e}"))?;
|
||||
|
||||
let rt = Runtime::new().map_err(|e| e.to_string())?;
|
||||
rt.block_on(async move {
|
||||
let listener = tokio::net::TcpListener::bind(addr)
|
||||
.await
|
||||
.map_err(|e| format!("bind {addr}: {e}"))?;
|
||||
let bound = listener
|
||||
.local_addr()
|
||||
.map_err(|e| format!("local_addr: {e}"))?;
|
||||
eprintln!("marqdo web listening on http://{bound}");
|
||||
eprintln!("marqdo web listening on http://{addr}");
|
||||
axum::serve(listener, app)
|
||||
.await
|
||||
.map_err(|e| format!("serve: {e}"))
|
||||
})?;
|
||||
Ok(json!({ "ok": true }))
|
||||
}
|
||||
|
||||
let server = axum::serve(listener, app);
|
||||
if let Some(ms) = duration_ms {
|
||||
tokio::select! {
|
||||
r = server => r.map_err(|e| format!("server: {e}"))?,
|
||||
_ = tokio::time::sleep(Duration::from_millis(ms)) => {}
|
||||
}
|
||||
} else {
|
||||
server
|
||||
.with_graceful_shutdown(async {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("server: {e}"))?;
|
||||
async fn home(State(st): State<Arc<AppState>>) -> Html<String> {
|
||||
let html = render::render_page(&st.page, st.db_url.as_deref());
|
||||
Html(html)
|
||||
}
|
||||
|
||||
async fn part(State(st): State<Arc<AppState>>, Path(id): Path<String>) -> Response {
|
||||
let Some(parts) = st.page.get("parts").and_then(|v| v.as_object()) else {
|
||||
return Html(String::from("<p>no parts</p>")).into_response();
|
||||
};
|
||||
let Some(cfg) = parts.get(&id) else {
|
||||
return Html(format!("<p>unknown part {id}</p>")).into_response();
|
||||
};
|
||||
let html = render::render_fragment(cfg, st.db_url.as_deref());
|
||||
Html(html).into_response()
|
||||
}
|
||||
|
||||
async fn admin_home(State(st): State<Arc<AppState>>) -> Response {
|
||||
if !st.admin {
|
||||
return Html(String::from("<p>admin disabled</p>")).into_response();
|
||||
}
|
||||
let Some(url) = st.db_url.as_deref() else {
|
||||
return Html(String::from("<p>no database</p>")).into_response();
|
||||
};
|
||||
let tables = db::list_tables(url).unwrap_or_default();
|
||||
let mut body = String::from(
|
||||
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"/><title>admin</title></head><body>",
|
||||
);
|
||||
body.push_str("<h1>admin</h1><ul>");
|
||||
for t in &tables {
|
||||
body.push_str(&format!("<li><a href=\"/admin/{t}\">{t}</a></li>"));
|
||||
}
|
||||
body.push_str("</ul><p><a href=\"/\">home</a></p></body></html>");
|
||||
Html(body).into_response()
|
||||
}
|
||||
|
||||
async fn admin_table(State(st): State<Arc<AppState>>, Path(table): Path<String>) -> Response {
|
||||
if !st.admin {
|
||||
return Redirect::to("/").into_response();
|
||||
}
|
||||
let Some(url) = st.db_url.as_deref() else {
|
||||
return Html(String::from("<p>no database</p>")).into_response();
|
||||
};
|
||||
let Ok(data) = db::select(url, &table, 200) else {
|
||||
return Html(format!("<p>cannot read {table}</p>")).into_response();
|
||||
};
|
||||
let rows = data
|
||||
.get("rows")
|
||||
.and_then(|v| v.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut body = format!(
|
||||
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"/><title>{table}</title></head><body>"
|
||||
);
|
||||
body.push_str(&format!("<h1>{table}</h1><p><a href=\"/admin\">back</a></p><table border=\"1\" cellpadding=\"6\"><thead><tr>"));
|
||||
let cols: Vec<String> = rows
|
||||
.first()
|
||||
.and_then(|r| r.as_object())
|
||||
.map(|m| m.keys().cloned().collect())
|
||||
.unwrap_or_default();
|
||||
for c in &cols {
|
||||
body.push_str(&format!("<th>{c}</th>"));
|
||||
}
|
||||
body.push_str("</tr></thead><tbody>");
|
||||
for row in &rows {
|
||||
body.push_str("<tr>");
|
||||
let m = row.as_object().cloned().unwrap_or_else(Map::new);
|
||||
for c in &cols {
|
||||
let cell = m.get(c).map(|v| match v {
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Null => String::new(),
|
||||
other => other.to_string(),
|
||||
}).unwrap_or_default();
|
||||
body.push_str(&format!("<td>{}</td>", esc(&cell)));
|
||||
}
|
||||
Ok(json!({ "ok": true, "addr": bound.to_string() }))
|
||||
})
|
||||
body.push_str("</tr>");
|
||||
}
|
||||
body.push_str("</tbody></table></body></html>");
|
||||
Html(body).into_response()
|
||||
}
|
||||
|
||||
fn esc(s: &str) -> String {
|
||||
s.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
}
|
||||
+301
-244
@@ -1,9 +1,10 @@
|
||||
//! Marqdo web plugin (C ABI v2): async HTTP, SQLite, page shell, admin.
|
||||
//! Marqdo web plugin (C ABI v2): SQLite, page assemble, HTTP listen.
|
||||
|
||||
mod compose;
|
||||
mod db;
|
||||
mod http;
|
||||
mod page;
|
||||
mod table_util;
|
||||
mod render;
|
||||
mod table;
|
||||
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
@@ -45,6 +46,8 @@ pub struct MarqdoHostApi {
|
||||
|
||||
static mut HOST_FREE: Option<unsafe extern "C" fn(*mut c_void)> = None;
|
||||
static mut HOST_ALLOC: Option<unsafe extern "C" fn(usize) -> *mut c_void> = None;
|
||||
static mut HOST_QUERY: Option<HostQueryFn> = None;
|
||||
static mut HOST_USERDATA: *mut c_void = ptr::null_mut();
|
||||
|
||||
unsafe fn host_strdup(s: &str) -> *mut c_char {
|
||||
let alloc = HOST_ALLOC.expect("host alloc");
|
||||
@@ -86,198 +89,291 @@ fn parse_args(args_json: *const c_char) -> Result<Value, String> {
|
||||
if s.trim().is_empty() {
|
||||
return Ok(json!({}));
|
||||
}
|
||||
serde_json::from_str(s).map_err(|e| format!("json: {e}"))
|
||||
serde_json::from_str(s).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
|
||||
args.get(key)
|
||||
.and_then(|v| v.as_str())
|
||||
fn take_host_string(p: *mut c_char) -> Option<String> {
|
||||
if p.is_null() {
|
||||
return None;
|
||||
}
|
||||
let s = unsafe { CStr::from_ptr(p) }
|
||||
.to_str()
|
||||
.ok()
|
||||
.map(|s| s.to_string());
|
||||
unsafe {
|
||||
if let Some(free) = HOST_FREE {
|
||||
free(p as *mut c_void);
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn host_query_json(name: &str, args: &Value) -> Result<Value, String> {
|
||||
let query = unsafe { HOST_QUERY }.ok_or_else(|| "host_query not available".to_string())?;
|
||||
let userdata = unsafe { HOST_USERDATA };
|
||||
let c_name = CString::new(name).map_err(|e| e.to_string())?;
|
||||
let c_args = CString::new(args.to_string()).map_err(|e| e.to_string())?;
|
||||
let mut out_ptr: *mut c_char = ptr::null_mut();
|
||||
let mut err_ptr: *mut c_char = ptr::null_mut();
|
||||
let rc = unsafe {
|
||||
query(
|
||||
userdata,
|
||||
c_name.as_ptr(),
|
||||
c_args.as_ptr(),
|
||||
&mut out_ptr,
|
||||
&mut err_ptr,
|
||||
)
|
||||
};
|
||||
let err = take_host_string(err_ptr);
|
||||
let out = take_host_string(out_ptr);
|
||||
if rc != 0 {
|
||||
return Err(err.unwrap_or_else(|| format!("host_query `{name}` failed")));
|
||||
}
|
||||
let out = out.unwrap_or_else(|| "null".into());
|
||||
serde_json::from_str(&out).map_err(|e| format!("host_query `{name}` bad JSON: {e}"))
|
||||
}
|
||||
|
||||
fn call_lib(path: &str) -> Result<Value, String> {
|
||||
host_query_json("call_lib_path", &json!({ "path": path }))
|
||||
}
|
||||
|
||||
fn arg_text(v: &Value, key: &str) -> Result<String, String> {
|
||||
match v.get(key) {
|
||||
None | Some(Value::Null) => Err(format!("missing `{key}`")),
|
||||
Some(Value::String(s)) => Ok(s.clone()),
|
||||
Some(Value::Number(n)) => Ok(n.to_string()),
|
||||
Some(Value::Bool(b)) => Ok(b.to_string()),
|
||||
Some(other) => Ok(other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn arg_str<'a>(v: &'a Value, key: &str) -> Result<&'a str, String> {
|
||||
v.get(key)
|
||||
.and_then(|x| x.as_str())
|
||||
.ok_or_else(|| format!("missing `{key}`"))
|
||||
}
|
||||
|
||||
fn arg_str_opt<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
|
||||
v.get(key).and_then(|x| x.as_str()).filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
fn db_url_of(args: &Value) -> Result<String, String> {
|
||||
if let Some(s) = arg_str_opt(args, "url").or_else(|| arg_str_opt(args, "db_url")) {
|
||||
return Ok(s.to_string());
|
||||
}
|
||||
if let Some(db) = args.get("db") {
|
||||
if let Some(s) = db.get("url").and_then(|v| v.as_str()) {
|
||||
return Ok(s.to_string());
|
||||
}
|
||||
}
|
||||
Err("missing db url".into())
|
||||
}
|
||||
|
||||
fn reply(out_json: *mut *mut c_char, err_msg: *mut *mut c_char, r: Result<Value, String>) -> c_int {
|
||||
match r {
|
||||
Ok(v) => {
|
||||
set_out(out_json, &v.to_string());
|
||||
0
|
||||
}
|
||||
Err(e) => {
|
||||
set_err(err_msg, &e);
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! web_ffi {
|
||||
($name:ident, $body:expr, $label:expr) => {
|
||||
($name:ident, $body:expr) => {
|
||||
unsafe extern "C" fn $name(
|
||||
args_json: *const c_char,
|
||||
out_json: *mut *mut c_char,
|
||||
err_msg: *mut *mut c_char,
|
||||
) -> c_int {
|
||||
match (|| -> Result<Value, String> {
|
||||
let args = parse_args(args_json)?;
|
||||
$body(&args)
|
||||
})() {
|
||||
Ok(v) => {
|
||||
set_out(out_json, &v.to_string());
|
||||
0
|
||||
}
|
||||
let args = match parse_args(args_json) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
set_err(err_msg, &format!("{}: {e}", $label));
|
||||
1
|
||||
set_err(err_msg, &format!("{}: {e}", stringify!($name)));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
};
|
||||
let r: Result<Value, String> = (|| $body(&args))();
|
||||
reply(
|
||||
out_json,
|
||||
err_msg,
|
||||
r.map_err(|e| format!("{}: {e}", stringify!($name))),
|
||||
)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
web_ffi!(
|
||||
web_render,
|
||||
|args: &Value| Ok(Value::String(page::render_page(args))),
|
||||
"web_render"
|
||||
);
|
||||
web_ffi!(web_page_new, |args: &Value| {
|
||||
let title = arg_str_opt(args, "title").unwrap_or("Marqdo Web");
|
||||
let intro = arg_str_opt(args, "intro").unwrap_or("");
|
||||
Ok(json!({
|
||||
"title": title,
|
||||
"intro": intro,
|
||||
}))
|
||||
});
|
||||
|
||||
web_ffi!(
|
||||
web_as_links,
|
||||
|args: &Value| {
|
||||
let table = args.get("table").cloned().unwrap_or(Value::Null);
|
||||
Ok(table_util::as_links(&table))
|
||||
},
|
||||
"web_as_links"
|
||||
);
|
||||
web_ffi!(web_compose_components, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let components = args
|
||||
.get("components")
|
||||
.cloned()
|
||||
.ok_or_else(|| "missing `components`".to_string())?;
|
||||
compose::compose_components(&page, &components, |path| call_lib(path))
|
||||
});
|
||||
|
||||
web_ffi!(
|
||||
web_as_fields,
|
||||
|args: &Value| {
|
||||
let table = args.get("table").cloned().unwrap_or(Value::Null);
|
||||
Ok(table_util::as_fields(&table))
|
||||
},
|
||||
"web_as_fields"
|
||||
);
|
||||
web_ffi!(web_compose_main, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let main = args
|
||||
.get("main")
|
||||
.cloned()
|
||||
.ok_or_else(|| "missing `main`".to_string())?;
|
||||
compose::compose_main(&page, &main, |path| call_lib(path))
|
||||
});
|
||||
|
||||
web_ffi!(
|
||||
web_as_bind,
|
||||
|args: &Value| {
|
||||
let table = args.get("table").cloned().unwrap_or(Value::Null);
|
||||
Ok(table_util::as_bind(&table))
|
||||
},
|
||||
"web_as_bind"
|
||||
);
|
||||
web_ffi!(web_render, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or_else(|| args.clone());
|
||||
let db_url = db_url_of(args).ok();
|
||||
let html = render::render_page(&page, db_url.as_deref());
|
||||
Ok(Value::String(html))
|
||||
});
|
||||
|
||||
web_ffi!(
|
||||
web_as_rows,
|
||||
|args: &Value| {
|
||||
let table = args.get("table").cloned().unwrap_or(Value::Null);
|
||||
Ok(table_util::as_rows(&table))
|
||||
},
|
||||
"web_as_rows"
|
||||
);
|
||||
web_ffi!(web_db_new, |args: &Value| {
|
||||
let url = arg_str_opt(args, "url").unwrap_or("sqlite:site.db");
|
||||
Ok(json!({ "url": url }))
|
||||
});
|
||||
|
||||
web_ffi!(
|
||||
web_listen,
|
||||
|args: &Value| http::listen(args),
|
||||
"web_listen"
|
||||
);
|
||||
web_ffi!(web_db_init, |args: &Value| {
|
||||
let url = db_url_of(args)?;
|
||||
let name = arg_str(args, "name")
|
||||
.or_else(|_| arg_str(args, "table"))?
|
||||
.to_string();
|
||||
let fields = args.get("fields").cloned().unwrap_or(json!([]));
|
||||
db::init(&url, &name, &fields)
|
||||
});
|
||||
|
||||
web_ffi!(
|
||||
web_db_migrate,
|
||||
|args: &Value| {
|
||||
let url = args
|
||||
.get("url")
|
||||
.or_else(|| args.get("db_url"))
|
||||
web_ffi!(web_db_insert, |args: &Value| {
|
||||
let url = db_url_of(args)?;
|
||||
let table = arg_str(args, "table")?.to_string();
|
||||
let rows = args
|
||||
.get("rows")
|
||||
.or_else(|| args.get("row"))
|
||||
.cloned()
|
||||
.unwrap_or(json!([]));
|
||||
db::insert(&url, &table, &rows)
|
||||
});
|
||||
|
||||
web_ffi!(web_db_select, |args: &Value| {
|
||||
let url = db_url_of(args)?;
|
||||
let table = arg_str(args, "table")?.to_string();
|
||||
let limit = args
|
||||
.get("limit")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(200);
|
||||
db::select(&url, &table, limit)
|
||||
});
|
||||
|
||||
web_ffi!(web_db_get, |args: &Value| {
|
||||
let url = db_url_of(args)?;
|
||||
let table = arg_str(args, "table")?.to_string();
|
||||
let id = arg_text(args, "id")?;
|
||||
db::get(&url, &table, &id)
|
||||
});
|
||||
|
||||
web_ffi!(web_db_update, |args: &Value| {
|
||||
let url = db_url_of(args)?;
|
||||
let table = arg_str(args, "table")?.to_string();
|
||||
let id = arg_text(args, "id")?;
|
||||
let row = args.get("row").cloned().unwrap_or(json!({}));
|
||||
db::update(&url, &table, &id, &row)
|
||||
});
|
||||
|
||||
web_ffi!(web_db_delete, |args: &Value| {
|
||||
let url = db_url_of(args)?;
|
||||
let table = arg_str(args, "table")?.to_string();
|
||||
let id = arg_text(args, "id")?;
|
||||
db::delete(&url, &table, &id)
|
||||
});
|
||||
|
||||
web_ffi!(web_db_exec, |args: &Value| {
|
||||
let url = db_url_of(args)?;
|
||||
let sql = arg_str(args, "sql")?.to_string();
|
||||
let args_v = args.get("args");
|
||||
db::exec(&url, &sql, args_v)
|
||||
});
|
||||
|
||||
web_ffi!(web_db_list_tables, |args: &Value| {
|
||||
let url = db_url_of(args)?;
|
||||
let tables = db::list_tables(&url)?;
|
||||
Ok(json!({ "tables": tables }))
|
||||
});
|
||||
|
||||
web_ffi!(web_app_new, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let db = args.get("db").cloned().unwrap_or(Value::Null);
|
||||
let host = arg_str_opt(args, "host").unwrap_or("127.0.0.1");
|
||||
let port = args
|
||||
.get("port")
|
||||
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
||||
.unwrap_or(18081);
|
||||
let admin = match args.get("admin") {
|
||||
Some(Value::Bool(b)) => *b,
|
||||
Some(Value::String(s)) => matches!(s.as_str(), "true" | "True" | "1" | "yes"),
|
||||
Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0,
|
||||
_ => false,
|
||||
};
|
||||
Ok(json!({
|
||||
"page": page,
|
||||
"db": db,
|
||||
"host": host,
|
||||
"port": port,
|
||||
"admin": admin,
|
||||
}))
|
||||
});
|
||||
|
||||
web_ffi!(web_listen, |args: &Value| {
|
||||
let (page, db_url, host, port, admin) = if args.get("page").is_some() || args.get("host").is_some()
|
||||
{
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let db_url = db_url_of(args).ok();
|
||||
let host = arg_str_opt(args, "host").unwrap_or("127.0.0.1");
|
||||
let port = args
|
||||
.get("port")
|
||||
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
||||
.unwrap_or(18081) as u16;
|
||||
let admin = match args.get("admin") {
|
||||
Some(Value::Bool(b)) => *b,
|
||||
_ => false,
|
||||
};
|
||||
(page, db_url, host.to_string(), port, admin)
|
||||
} else {
|
||||
let app = args.get("app").cloned().unwrap_or_else(|| args.clone());
|
||||
let page = app.get("page").cloned().unwrap_or(json!({}));
|
||||
let db_url = app
|
||||
.get("db")
|
||||
.and_then(|d| d.get("url"))
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "missing `url`".to_string())?;
|
||||
let dir = args
|
||||
.get("dir")
|
||||
.map(|s| s.to_string())
|
||||
.or_else(|| arg_str_opt(&app, "db_url").map(|s| s.to_string()));
|
||||
let host = app
|
||||
.get("host")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("migrations");
|
||||
db::migrate(url, dir)
|
||||
},
|
||||
"web_db_migrate"
|
||||
);
|
||||
|
||||
web_ffi!(
|
||||
web_db_define,
|
||||
|args: &Value| {
|
||||
let url = args
|
||||
.get("url")
|
||||
.or_else(|| args.get("db_url"))
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "missing `url`".to_string())?;
|
||||
let table = arg_text(args, "table")?;
|
||||
let fields = args.get("fields").cloned().unwrap_or(json!([]));
|
||||
let primary = args
|
||||
.get("primary")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("id");
|
||||
db::define_table(url, table, &fields, primary)
|
||||
},
|
||||
"web_db_define"
|
||||
);
|
||||
|
||||
web_ffi!(
|
||||
web_db_all,
|
||||
|args: &Value| {
|
||||
let url = args
|
||||
.get("url")
|
||||
.or_else(|| args.get("db_url"))
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "missing `url`".to_string())?;
|
||||
let table = arg_text(args, "table")?;
|
||||
let limit = args
|
||||
.get("limit")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(200);
|
||||
db::query_all(url, table, limit)
|
||||
},
|
||||
"web_db_all"
|
||||
);
|
||||
|
||||
web_ffi!(
|
||||
web_db_exec,
|
||||
|args: &Value| {
|
||||
let url = args
|
||||
.get("url")
|
||||
.or_else(|| args.get("db_url"))
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "missing `url`".to_string())?;
|
||||
let sql = arg_text(args, "sql")?;
|
||||
db::exec_sql(url, sql, args.get("args"))
|
||||
},
|
||||
"web_db_exec"
|
||||
);
|
||||
|
||||
web_ffi!(
|
||||
web_db_query,
|
||||
|args: &Value| {
|
||||
let url = args
|
||||
.get("url")
|
||||
.or_else(|| args.get("db_url"))
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "missing `url`".to_string())?;
|
||||
let sql = arg_text(args, "sql")?;
|
||||
db::query_sql(url, sql, args.get("args"))
|
||||
},
|
||||
"web_db_query"
|
||||
);
|
||||
|
||||
web_ffi!(
|
||||
web_db_insert,
|
||||
|args: &Value| {
|
||||
let url = args
|
||||
.get("url")
|
||||
.or_else(|| args.get("db_url"))
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "missing `url`".to_string())?;
|
||||
let table = arg_text(args, "table")?;
|
||||
if let Some(rows) = args.get("rows") {
|
||||
let normalized = table_util::as_rows(rows);
|
||||
return db::insert_rows(url, table, &normalized);
|
||||
}
|
||||
let row = args.get("row").cloned().unwrap_or(json!({}));
|
||||
let normalized = table_util::as_rows(&row);
|
||||
if let Some(arr) = normalized.as_array() {
|
||||
if arr.len() > 1 || row.as_object().is_some_and(|m| {
|
||||
m.values().any(|v| v.is_array())
|
||||
}) {
|
||||
return db::insert_rows(url, table, &normalized);
|
||||
}
|
||||
if let Some(one) = arr.first() {
|
||||
return db::insert_row(url, table, one);
|
||||
}
|
||||
}
|
||||
db::insert_row(url, table, &row)
|
||||
},
|
||||
"web_db_insert"
|
||||
);
|
||||
.unwrap_or("127.0.0.1")
|
||||
.to_string();
|
||||
let port = app
|
||||
.get("port")
|
||||
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
||||
.unwrap_or(18081) as u16;
|
||||
let admin = app
|
||||
.get("admin")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
(page, db_url, host, port, admin)
|
||||
};
|
||||
http::listen(&page, db_url.as_deref(), &host, port, admin)
|
||||
});
|
||||
|
||||
fn register(host: &MarqdoHostApi, name: &str, params: &str, fn_ptr: PluginFn) -> c_int {
|
||||
let register = match host.register_fn {
|
||||
@@ -294,6 +390,9 @@ pub unsafe extern "C" fn marqdo_plugin_abi_version() -> u32 {
|
||||
ABI_VERSION
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn marqdo_plugin_shutdown() {}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int {
|
||||
if host.is_null() {
|
||||
@@ -302,83 +401,41 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
|
||||
let host = &*host;
|
||||
HOST_ALLOC = host.alloc;
|
||||
HOST_FREE = host.free;
|
||||
HOST_QUERY = host.host_query;
|
||||
HOST_USERDATA = host.userdata;
|
||||
if host.host_query.is_none() {
|
||||
return 1;
|
||||
}
|
||||
if register(host, "web_render", "title,nav,sidebar,footer,main", web_render) != 0 {
|
||||
return 1;
|
||||
}
|
||||
if register(host, "web_as_links", "table", web_as_links) != 0 {
|
||||
return 1;
|
||||
}
|
||||
if register(host, "web_as_fields", "table", web_as_fields) != 0 {
|
||||
return 1;
|
||||
}
|
||||
if register(host, "web_as_bind", "table", web_as_bind) != 0 {
|
||||
return 1;
|
||||
}
|
||||
if register(host, "web_as_rows", "table", web_as_rows) != 0 {
|
||||
return 1;
|
||||
}
|
||||
if register(host, "web_listen", "host,port", web_listen) != 0 {
|
||||
return 1;
|
||||
}
|
||||
if register(host, "web_db_migrate", "url,dir", web_db_migrate) != 0 {
|
||||
return 1;
|
||||
}
|
||||
if register(host, "web_db_define", "url,table,fields", web_db_define) != 0 {
|
||||
return 1;
|
||||
}
|
||||
if register(host, "web_db_all", "url,table", web_db_all) != 0 {
|
||||
return 1;
|
||||
}
|
||||
if register(host, "web_db_exec", "url,sql", web_db_exec) != 0 {
|
||||
return 1;
|
||||
}
|
||||
if register(host, "web_db_query", "url,sql", web_db_query) != 0 {
|
||||
return 1;
|
||||
}
|
||||
if register(host, "web_db_insert", "url,table,rows", web_db_insert) != 0 {
|
||||
return 1;
|
||||
|
||||
let regs = [
|
||||
("web_page_new", "title,intro", web_page_new as PluginFn),
|
||||
(
|
||||
"web_compose_components",
|
||||
"page,components",
|
||||
web_compose_components as PluginFn,
|
||||
),
|
||||
("web_compose_main", "page,main", web_compose_main as PluginFn),
|
||||
("web_render", "page", web_render as PluginFn),
|
||||
("web_db_new", "url", web_db_new as PluginFn),
|
||||
("web_db_init", "url,name,fields", web_db_init as PluginFn),
|
||||
("web_db_insert", "url,table,rows", web_db_insert as PluginFn),
|
||||
("web_db_select", "url,table,limit", web_db_select as PluginFn),
|
||||
("web_db_get", "url,table,id", web_db_get as PluginFn),
|
||||
("web_db_update", "url,table,id,row", web_db_update as PluginFn),
|
||||
("web_db_delete", "url,table,id", web_db_delete as PluginFn),
|
||||
("web_db_exec", "url,sql,args", web_db_exec as PluginFn),
|
||||
("web_db_list_tables", "url", web_db_list_tables as PluginFn),
|
||||
(
|
||||
"web_app_new",
|
||||
"page,db,admin,host,port",
|
||||
web_app_new as PluginFn,
|
||||
),
|
||||
("web_listen", "app", web_listen as PluginFn),
|
||||
];
|
||||
for (name, params, f) in regs {
|
||||
if register(host, name, params, f) != 0 {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn marqdo_plugin_shutdown() {
|
||||
HOST_ALLOC = None;
|
||||
HOST_FREE = None;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn render_contains_nav() {
|
||||
let html = page::render_page(&json!({
|
||||
"title": "T",
|
||||
"nav": [{"label": "Home", "href": "/"}],
|
||||
"main": "<p>hi</p>",
|
||||
}));
|
||||
assert!(html.contains("Home"));
|
||||
assert!(html.contains("<p>hi</p>"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn define_and_query_sqlite() {
|
||||
let dir = std::env::temp_dir().join(format!("mq-web-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let url = format!("sqlite:{}/t.db", dir.display());
|
||||
let fields = json!([
|
||||
{"name": "id", "type": "integer", "null": false},
|
||||
{"name": "title", "type": "text", "null": false},
|
||||
]);
|
||||
db::define_table(&url, "posts", &fields, "id").unwrap();
|
||||
db::insert_row(&url, "posts", &json!({"title": "hello"})).unwrap();
|
||||
let rows = db::query_all(&url, "posts", 10).unwrap();
|
||||
assert_eq!(rows["count"], 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -1,546 +0,0 @@
|
||||
//! HTML page shell + content layouts (prose / cards / table / list).
|
||||
//! Regions resolve from unified bind tables (`front` / `back` / `css`).
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::db;
|
||||
use crate::table_util::{
|
||||
as_bind, bind_has_db, bind_table_name, binds_as_static_links, project_rows, qualify_binds,
|
||||
};
|
||||
|
||||
const DEFAULT_THEME_CSS: &str = include_str!("theme.css");
|
||||
|
||||
fn link_label(item: &Value) -> String {
|
||||
item.get("label")
|
||||
.or_else(|| item.get("标签"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn link_href(item: &Value) -> String {
|
||||
item.get("href")
|
||||
.or_else(|| item.get("链接"))
|
||||
.or_else(|| item.get("路径"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("#")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn link_css(item: &Value) -> String {
|
||||
item.get("css")
|
||||
.or_else(|| item.get("class"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn class_attr(css: &str) -> String {
|
||||
let css = css.trim();
|
||||
if css.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" class=\"{}\"", html_escape(css))
|
||||
}
|
||||
}
|
||||
|
||||
fn render_links(items: &[Value], class: &str) -> String {
|
||||
let mut out = format!("<ul class=\"{class}\">");
|
||||
for it in items {
|
||||
let label = html_escape(&link_label(it));
|
||||
let href = html_escape(&link_href(it));
|
||||
let css = class_attr(&link_css(it));
|
||||
out.push_str(&format!("<li><a href=\"{href}\"{css}>{label}</a></li>"));
|
||||
}
|
||||
out.push_str("</ul>");
|
||||
out
|
||||
}
|
||||
|
||||
pub fn html_escape(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn items_from(v: Option<&Value>) -> Vec<Value> {
|
||||
match v {
|
||||
Some(Value::Array(a)) => a.clone(),
|
||||
Some(Value::Object(m)) => {
|
||||
if let Some(Value::Array(rows)) = m.get("rows") {
|
||||
return rows.clone();
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn looks_like_bind(v: &Value) -> bool {
|
||||
match v {
|
||||
Value::Array(a) => a.first().and_then(|x| x.as_object()).is_some_and(|m| {
|
||||
m.contains_key("front")
|
||||
|| m.contains_key("前端变量")
|
||||
|| m.contains_key("页面导航")
|
||||
|| m.contains_key("label")
|
||||
}),
|
||||
Value::Object(m) => {
|
||||
m.contains_key("前端变量")
|
||||
|| m.contains_key("front")
|
||||
|| m.contains_key("页面导航")
|
||||
|| m.contains_key("对应路由")
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn cell_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 record_title(obj: &Map<String, Value>) -> String {
|
||||
for k in ["title", "标题", "name", "名", "label", "标签"] {
|
||||
if let Some(v) = obj.get(k) {
|
||||
let s = cell_text(v);
|
||||
if !s.is_empty() {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
}
|
||||
obj.iter()
|
||||
.find(|(k, _)| *k != "_css" && *k != "id")
|
||||
.map(|(_, v)| cell_text(v))
|
||||
.unwrap_or_else(|| "item".into())
|
||||
}
|
||||
|
||||
fn record_body(obj: &Map<String, Value>) -> String {
|
||||
for k in ["body", "正文", "content", "内容", "description", "描述", "summary"] {
|
||||
if let Some(v) = obj.get(k) {
|
||||
let s = cell_text(v);
|
||||
if !s.is_empty() {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
fn field_css(obj: &Map<String, Value>, field: &str) -> String {
|
||||
obj.get("_css")
|
||||
.and_then(|v| v.as_object())
|
||||
.and_then(|m| m.get(field))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn render_cards(items: &[Value]) -> String {
|
||||
let mut out = String::from("<section class=\"content cards\">");
|
||||
for it in items {
|
||||
if let Some(obj) = it.as_object() {
|
||||
let title = html_escape(&record_title(obj));
|
||||
let body = record_body(obj);
|
||||
let title_css = class_attr(&field_css(obj, "title"));
|
||||
let title_css = if title_css.is_empty() {
|
||||
class_attr(&field_css(obj, "标题"))
|
||||
} else {
|
||||
title_css
|
||||
};
|
||||
let body_css = class_attr(&field_css(obj, "body"));
|
||||
let body_css = if body_css.is_empty() {
|
||||
class_attr(&field_css(obj, "正文"))
|
||||
} else {
|
||||
body_css
|
||||
};
|
||||
out.push_str("<article>");
|
||||
out.push_str(&format!("<h2{title_css}>{title}</h2>"));
|
||||
if !body.is_empty() {
|
||||
out.push_str(&format!("<p{body_css}>{}</p>", html_escape(&body)));
|
||||
}
|
||||
// Extra bound fronts (not title/body/id/_css)
|
||||
for (k, v) in obj {
|
||||
if matches!(
|
||||
k.as_str(),
|
||||
"title"
|
||||
| "标题"
|
||||
| "body"
|
||||
| "正文"
|
||||
| "content"
|
||||
| "内容"
|
||||
| "id"
|
||||
| "_css"
|
||||
| "name"
|
||||
| "名"
|
||||
| "label"
|
||||
| "标签"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
let css = class_attr(&field_css(obj, k));
|
||||
out.push_str(&format!(
|
||||
"<div data-field=\"{}\"{css}>{}</div>",
|
||||
html_escape(k),
|
||||
html_escape(&cell_text(v))
|
||||
));
|
||||
}
|
||||
if let Some(id) = obj.get("id") {
|
||||
out.push_str(&format!(
|
||||
"<div class=\"meta\">#{}</div>",
|
||||
html_escape(&cell_text(id))
|
||||
));
|
||||
}
|
||||
out.push_str("</article>");
|
||||
} else if let Some(s) = it.as_str() {
|
||||
out.push_str(&format!(
|
||||
"<article><h2>{}</h2></article>",
|
||||
html_escape(s)
|
||||
));
|
||||
}
|
||||
}
|
||||
out.push_str("</section>");
|
||||
out
|
||||
}
|
||||
|
||||
fn render_table(items: &[Value]) -> String {
|
||||
let Some(first) = items.first().and_then(|v| v.as_object()) else {
|
||||
return String::from("<p class=\"main-intro\">No rows.</p>");
|
||||
};
|
||||
let cols: Vec<String> = first
|
||||
.keys()
|
||||
.filter(|k| *k != "_css")
|
||||
.cloned()
|
||||
.collect();
|
||||
let mut out = String::from("<div class=\"content table-wrap\"><table><thead><tr>");
|
||||
for c in &cols {
|
||||
out.push_str(&format!("<th>{}</th>", html_escape(c)));
|
||||
}
|
||||
out.push_str("</tr></thead><tbody>");
|
||||
for it in items {
|
||||
let Some(obj) = it.as_object() else {
|
||||
continue;
|
||||
};
|
||||
out.push_str("<tr>");
|
||||
for c in &cols {
|
||||
let cell = obj.get(c).map(cell_text).unwrap_or_default();
|
||||
let css = class_attr(&field_css(obj, c));
|
||||
out.push_str(&format!("<td{css}>{}</td>", html_escape(&cell)));
|
||||
}
|
||||
out.push_str("</tr>");
|
||||
}
|
||||
out.push_str("</tbody></table></div>");
|
||||
out
|
||||
}
|
||||
|
||||
fn render_list(items: &[Value]) -> String {
|
||||
let mut out = String::from("<ul class=\"content list\">");
|
||||
for it in items {
|
||||
if let Some(obj) = it.as_object() {
|
||||
let title = html_escape(&record_title(obj));
|
||||
let body = record_body(obj);
|
||||
let title_css = class_attr(&field_css(obj, "title"));
|
||||
if body.is_empty() {
|
||||
out.push_str(&format!("<li{title_css}>{title}</li>"));
|
||||
} else {
|
||||
out.push_str(&format!(
|
||||
"<li><strong{title_css}>{title}</strong> — {}</li>",
|
||||
html_escape(&body)
|
||||
));
|
||||
}
|
||||
} else if let Some(s) = it.as_str() {
|
||||
out.push_str(&format!("<li>{}</li>", html_escape(s)));
|
||||
}
|
||||
}
|
||||
out.push_str("</ul>");
|
||||
out
|
||||
}
|
||||
|
||||
fn render_main_block(intro: &str, items: Option<&Vec<Value>>, layout: &str) -> String {
|
||||
let mut out = String::new();
|
||||
if !intro.is_empty() {
|
||||
out.push_str(&format!("<div class=\"main-intro\">{intro}</div>"));
|
||||
}
|
||||
let Some(items) = items.filter(|v| !v.is_empty()) else {
|
||||
return out;
|
||||
};
|
||||
match layout {
|
||||
"table" | "表格" => out.push_str(&render_table(items)),
|
||||
"list" | "列表" => out.push_str(&render_list(items)),
|
||||
"prose" | "正文" => {
|
||||
out.push_str("<section class=\"content prose\">");
|
||||
for it in items {
|
||||
if let Some(obj) = it.as_object() {
|
||||
let title = html_escape(&record_title(obj));
|
||||
let body = record_body(obj);
|
||||
let title_css = class_attr(&field_css(obj, "title"));
|
||||
let body_css = class_attr(&field_css(obj, "body"));
|
||||
out.push_str(&format!("<h2{title_css}>{title}</h2>"));
|
||||
if !body.is_empty() {
|
||||
out.push_str(&format!("<p{body_css}>{}</p>", html_escape(&body)));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str("</section>");
|
||||
}
|
||||
_ => out.push_str(&render_cards(items)),
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Resolve a region value into link items (static or DB-looped).
|
||||
fn resolve_link_region(
|
||||
raw: Option<&Value>,
|
||||
db_url: Option<&str>,
|
||||
default_table: Option<&str>,
|
||||
) -> Vec<Value> {
|
||||
let Some(raw) = raw else {
|
||||
return Vec::new();
|
||||
};
|
||||
// Already resolved link list?
|
||||
if let Value::Array(a) = raw {
|
||||
if a.first().and_then(|x| x.as_object()).is_some_and(|m| {
|
||||
m.contains_key("label") || m.contains_key("href")
|
||||
}) && !a
|
||||
.first()
|
||||
.and_then(|x| x.as_object())
|
||||
.is_some_and(|m| m.contains_key("front"))
|
||||
{
|
||||
return a.clone();
|
||||
}
|
||||
}
|
||||
if !looks_like_bind(raw) {
|
||||
return items_from(Some(raw));
|
||||
}
|
||||
let binds = as_bind(raw);
|
||||
let arr = qualify_binds(binds.as_array().map(|v| v.as_slice()).unwrap_or(&[]), default_table);
|
||||
if bind_has_db(&arr) {
|
||||
let Some(url) = db_url else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(table) = bind_table_name(&arr) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(data) = db::query_all(url, &table, 200) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let rows = data
|
||||
.get("rows")
|
||||
.and_then(|v| v.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let projected = project_rows(&arr, &rows);
|
||||
let mut links = Vec::new();
|
||||
for it in projected.as_array().cloned().unwrap_or_default() {
|
||||
let obj = it.as_object().cloned().unwrap_or_default();
|
||||
let label = obj
|
||||
.get("label")
|
||||
.or_else(|| obj.get("标签"))
|
||||
.or_else(|| obj.get("title"))
|
||||
.or_else(|| obj.get("前端变量"))
|
||||
.map(cell_text)
|
||||
.filter(|s| !s.is_empty())
|
||||
.or_else(|| {
|
||||
obj.iter()
|
||||
.find(|(k, _)| *k != "_css" && *k != "id" && *k != "href" && *k != "路径")
|
||||
.map(|(_, v)| cell_text(v))
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let href = obj
|
||||
.get("href")
|
||||
.or_else(|| obj.get("路径"))
|
||||
.or_else(|| obj.get("对应路由"))
|
||||
.map(cell_text)
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or_else(|| "#".into());
|
||||
let css = obj
|
||||
.get("_css")
|
||||
.and_then(|v| v.as_object())
|
||||
.and_then(|m| {
|
||||
m.get("label")
|
||||
.or_else(|| m.get("title"))
|
||||
.or_else(|| m.values().next())
|
||||
})
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
links.push(json!({ "label": label, "href": href, "css": css }));
|
||||
}
|
||||
links
|
||||
} else {
|
||||
binds_as_static_links(&arr)
|
||||
.as_array()
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve main: bind table → DB loop, or legacy live list / HTML intro.
|
||||
fn resolve_main(
|
||||
args: &Value,
|
||||
db_url: Option<&str>,
|
||||
default_table: Option<&str>,
|
||||
) -> (String, Option<Vec<Value>>) {
|
||||
let intro = args
|
||||
.get("intro")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
|
||||
if let Some(items) = args.get("main_items").and_then(|v| v.as_array()) {
|
||||
return (intro, Some(items.clone()));
|
||||
}
|
||||
|
||||
let main = args.get("main");
|
||||
if let Some(raw) = main {
|
||||
if looks_like_bind(raw) {
|
||||
let binds = as_bind(raw);
|
||||
let arr = qualify_binds(binds.as_array().map(|v| v.as_slice()).unwrap_or(&[]), default_table);
|
||||
if bind_has_db(&arr) {
|
||||
if let (Some(url), Some(table)) = (db_url, bind_table_name(&arr)) {
|
||||
if let Ok(data) = db::query_all(url, &table, 200) {
|
||||
let rows = data
|
||||
.get("rows")
|
||||
.and_then(|v| v.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let projected = project_rows(&arr, &rows);
|
||||
return (
|
||||
intro,
|
||||
Some(projected.as_array().cloned().unwrap_or_default()),
|
||||
);
|
||||
}
|
||||
}
|
||||
return (intro, Some(Vec::new()));
|
||||
}
|
||||
}
|
||||
if let Value::Array(a) = raw {
|
||||
return (intro, Some(a.clone()));
|
||||
}
|
||||
if let Some(s) = raw.as_str() {
|
||||
if intro.is_empty() {
|
||||
return (s.to_string(), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !intro.is_empty() {
|
||||
return (intro, None);
|
||||
}
|
||||
if let Some(s) = main.and_then(|v| v.as_str()) {
|
||||
return (s.to_string(), None);
|
||||
}
|
||||
("<p>Welcome</p>".into(), None)
|
||||
}
|
||||
|
||||
/// Render a four-region page shell; optional `db_url` resolves live binds.
|
||||
pub fn render_page(args: &Value) -> String {
|
||||
let db_url = args
|
||||
.get("db_url")
|
||||
.or_else(|| args.get("url"))
|
||||
.and_then(|v| v.as_str());
|
||||
render_page_with_db(args, db_url)
|
||||
}
|
||||
|
||||
pub fn render_page_with_db(args: &Value, db_url: Option<&str>) -> String {
|
||||
let title = args
|
||||
.get("title")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Marqdo Web");
|
||||
let theme_css = args.get("css").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let layout = args
|
||||
.get("layout")
|
||||
.or_else(|| args.get("主体样式"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("cards");
|
||||
let default_table = args
|
||||
.get("table")
|
||||
.or_else(|| args.get("数据表"))
|
||||
.and_then(|v| v.as_str());
|
||||
|
||||
let nav = resolve_link_region(args.get("nav"), db_url, default_table);
|
||||
let sidebar = resolve_link_region(args.get("sidebar"), db_url, default_table);
|
||||
let footer = resolve_link_region(args.get("footer"), db_url, default_table);
|
||||
let (intro, main_items) = resolve_main(args, db_url, default_table);
|
||||
|
||||
let body_main = if main_items.is_some() {
|
||||
render_main_block(&intro, main_items.as_ref(), layout)
|
||||
} else if !intro.is_empty() {
|
||||
format!("<div class=\"main-intro\">{intro}</div>")
|
||||
} else {
|
||||
String::from("<div class=\"main-intro\"><p>Welcome</p></div>")
|
||||
};
|
||||
|
||||
let has_side = !sidebar.is_empty();
|
||||
let layout_class = if has_side {
|
||||
"has-sidebar"
|
||||
} else {
|
||||
"no-sidebar"
|
||||
};
|
||||
let extra_css = if theme_css.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(
|
||||
"<link rel=\"stylesheet\" href=\"{}\"/>",
|
||||
html_escape(theme_css)
|
||||
)
|
||||
};
|
||||
let side = if has_side {
|
||||
format!(
|
||||
"<aside class=\"side\"><span class=\"side-label\">侧栏</span>{}</aside>",
|
||||
render_links(&sidebar, "side-nav")
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
format!(
|
||||
r#"<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<title>{title}</title>
|
||||
<style>
|
||||
{builtin}
|
||||
</style>
|
||||
{extra_css}
|
||||
</head>
|
||||
<body class="{layout_class}">
|
||||
<header class="topnav">{nav}</header>
|
||||
{side}
|
||||
<main class="main">{main}</main>
|
||||
<footer class="foot">{foot}</footer>
|
||||
</body>
|
||||
</html>"#,
|
||||
title = html_escape(title),
|
||||
builtin = DEFAULT_THEME_CSS,
|
||||
extra_css = extra_css,
|
||||
layout_class = layout_class,
|
||||
nav = render_links(&nav, "nav"),
|
||||
side = side,
|
||||
main = body_main,
|
||||
foot = render_links(&footer, "foot-nav"),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn default_hello_html() -> String {
|
||||
render_page(&json!({
|
||||
"title": "Marqdo Web",
|
||||
"nav": [{"label": "Home", "href": "/"}],
|
||||
"intro": "<h1>Marqdo Web</h1><p>Hello from ext/web.</p>",
|
||||
"footer": [{"label": "Marqdo", "href": "https://github.com/cflmy/marqdo"}],
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
//! Minimal HTML shell for assembled pages / parts.
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::db;
|
||||
use crate::table::{as_bind, normalize_slot, project_rows};
|
||||
|
||||
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 resolve_links(raw: Option<&Value>, db_url: Option<&str>) -> Vec<(String, String)> {
|
||||
let Some(raw) = raw else {
|
||||
return Vec::new();
|
||||
};
|
||||
let binds = as_bind(raw);
|
||||
let arr = binds.as_array().cloned().unwrap_or_default();
|
||||
if arr.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let has_db = arr.iter().any(|b| {
|
||||
b.get("back")
|
||||
.and_then(|v| v.as_str())
|
||||
.is_some_and(|s| s.contains('.'))
|
||||
});
|
||||
if has_db {
|
||||
let Some(url) = db_url else {
|
||||
return Vec::new();
|
||||
};
|
||||
let table = crate::table::bind_table_name(&arr);
|
||||
let Some(table) = table else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(data) = db::select(url, &table, 200) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let rows = data
|
||||
.get("rows")
|
||||
.and_then(|v| v.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let projected = project_rows(&arr, &rows);
|
||||
let mut out = Vec::new();
|
||||
for it in projected.as_array().cloned().unwrap_or_default() {
|
||||
let m = it.as_object().cloned().unwrap_or_default();
|
||||
let label = m
|
||||
.get("title")
|
||||
.or_else(|| m.get("label"))
|
||||
.map(text)
|
||||
.unwrap_or_default();
|
||||
let href = m
|
||||
.get("href")
|
||||
.or_else(|| m.get("path"))
|
||||
.map(text)
|
||||
.unwrap_or_else(|| "#".into());
|
||||
if !label.is_empty() {
|
||||
out.push((label, href));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// static: front=label back=href
|
||||
arr.into_iter()
|
||||
.map(|b| {
|
||||
let label = b.get("front").map(text).unwrap_or_default();
|
||||
let href = b.get("back").map(text).unwrap_or_else(|| "#".into());
|
||||
(label, href)
|
||||
})
|
||||
.filter(|(l, _)| !l.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn render_ul(links: &[(String, String)], class: &str) -> String {
|
||||
let mut s = format!("<ul class=\"{}\">", esc(class));
|
||||
for (label, href) in links {
|
||||
s.push_str(&format!(
|
||||
"<li><a href=\"{}\">{}</a></li>",
|
||||
esc(href),
|
||||
esc(label)
|
||||
));
|
||||
}
|
||||
s.push_str("</ul>");
|
||||
s
|
||||
}
|
||||
|
||||
fn resolve_main(args: &Value, db_url: Option<&str>) -> (String, Vec<Map<String, Value>>) {
|
||||
let intro = args
|
||||
.get("intro")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let Some(main) = args.get("main") else {
|
||||
return (intro, Vec::new());
|
||||
};
|
||||
let binds = as_bind(main);
|
||||
let arr = binds.as_array().cloned().unwrap_or_default();
|
||||
if arr.is_empty() {
|
||||
return (intro, Vec::new());
|
||||
}
|
||||
let Some(url) = db_url else {
|
||||
return (intro, Vec::new());
|
||||
};
|
||||
let Some(table) = crate::table::bind_table_name(&arr) else {
|
||||
return (intro, Vec::new());
|
||||
};
|
||||
let Ok(data) = db::select(url, &table, 200) else {
|
||||
return (intro, Vec::new());
|
||||
};
|
||||
let rows = data
|
||||
.get("rows")
|
||||
.and_then(|v| v.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let projected = project_rows(&arr, &rows);
|
||||
let items = projected
|
||||
.as_array()
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|v| v.as_object().cloned())
|
||||
.collect();
|
||||
(intro, items)
|
||||
}
|
||||
|
||||
fn field_css(obj: &Map<String, Value>, field: &str) -> String {
|
||||
obj.get("_css")
|
||||
.and_then(|v| v.as_object())
|
||||
.and_then(|m| m.get(field))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn slot_attrs(slot: &str, parts: &Map<String, Value>) -> String {
|
||||
let mut a = format!(" data-slot=\"{}\"", esc(slot));
|
||||
for (id, cfg) in parts {
|
||||
let s = cfg
|
||||
.get("slot")
|
||||
.or_else(|| cfg.get("fragment"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
if s == slot || (slot == "sidebar" && id == "side") || (slot == "main" && id == "index") {
|
||||
a.push_str(&format!(" data-slot-src=\"/_part/{}\"", esc(id)));
|
||||
break;
|
||||
}
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
fn slot_class(args: &Value, slot: &str, base: &str) -> String {
|
||||
let extra = args
|
||||
.get("slot_class")
|
||||
.and_then(|v| v.as_object())
|
||||
.and_then(|m| m.get(slot))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
if extra.is_empty() {
|
||||
base.to_string()
|
||||
} else {
|
||||
format!("{base} {extra}")
|
||||
}
|
||||
}
|
||||
|
||||
const SHELL_CSS: &str = r#"
|
||||
:root { --ink:#1c1917; --muted:#57534e; --paper:#fafaf9; --line:#e7e5e4; --accent:#0f766e; }
|
||||
body { margin:0; font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif; background:var(--paper); color:var(--ink); display:grid; min-height:100vh; grid-template-rows:auto 1fr auto; }
|
||||
body.has-sidebar { grid-template-columns:14rem 1fr; grid-template-areas:"top top" "side main" "foot foot"; }
|
||||
body.no-sidebar { grid-template-areas:"top" "main" "foot"; }
|
||||
header.topnav { grid-area:top; border-bottom:1px solid var(--line); padding:.85rem 1.25rem; background:#fff; }
|
||||
aside.side { grid-area:side; border-right:1px solid var(--line); padding:1.25rem 1rem; background:#f5f5f4; }
|
||||
main.main { grid-area:main; padding:1.5rem 1.25rem 2rem; }
|
||||
footer.foot { grid-area:foot; border-top:1px solid var(--line); padding:.85rem 1.25rem; color:var(--muted); background:#fff; }
|
||||
ul.nav, ul.side-nav, ul.foot-nav { list-style:none; margin:0; padding:0; display:flex; flex-wrap:wrap; gap:.35rem 1rem; }
|
||||
ul.side-nav { flex-direction:column; }
|
||||
a { color:var(--ink); text-decoration:none; }
|
||||
a:hover { color:var(--accent); }
|
||||
.content.cards { display:grid; gap:1rem; margin-top:1.25rem; grid-template-columns:repeat(auto-fill,minmax(16rem,1fr)); }
|
||||
.content.cards article { background:#fff; border:1px solid var(--line); border-radius:6px; padding:1rem; }
|
||||
.main-intro h1 { margin:0 0 .75rem; font-size:2rem; }
|
||||
.main-intro p { color:var(--muted); }
|
||||
"#;
|
||||
|
||||
pub fn render_page(args: &Value, db_url: Option<&str>) -> String {
|
||||
let title = args
|
||||
.get("title")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Marqdo Web");
|
||||
let extra = args
|
||||
.get("styles_css")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let parts = args
|
||||
.get("parts")
|
||||
.and_then(|v| v.as_object())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
let nav = resolve_links(args.get("nav"), db_url);
|
||||
let side = resolve_links(args.get("sidebar"), db_url);
|
||||
let foot = resolve_links(args.get("footer"), db_url);
|
||||
let (intro, items) = resolve_main(args, db_url);
|
||||
|
||||
let has_side = args.get("sidebar").is_some() || !side.is_empty();
|
||||
let body_class = if has_side {
|
||||
"has-sidebar"
|
||||
} else {
|
||||
"no-sidebar"
|
||||
};
|
||||
|
||||
let mut main_html = String::new();
|
||||
if !intro.is_empty() {
|
||||
main_html.push_str(&format!("<div class=\"main-intro\">{intro}</div>"));
|
||||
}
|
||||
if !items.is_empty() {
|
||||
main_html.push_str("<section class=\"content cards\">");
|
||||
for it in &items {
|
||||
let title = it
|
||||
.get("title")
|
||||
.map(text)
|
||||
.unwrap_or_else(|| "item".into());
|
||||
let body = it.get("body").map(text).unwrap_or_default();
|
||||
let tc = class_attr(&field_css(it, "title"));
|
||||
let bc = class_attr(&field_css(it, "body"));
|
||||
main_html.push_str("<article>");
|
||||
main_html.push_str(&format!("<h2{tc}>{}</h2>", esc(&title)));
|
||||
if !body.is_empty() {
|
||||
main_html.push_str(&format!("<p{bc}>{}</p>", esc(&body)));
|
||||
}
|
||||
main_html.push_str("</article>");
|
||||
}
|
||||
main_html.push_str("</section>");
|
||||
}
|
||||
|
||||
format!(
|
||||
r#"<!DOCTYPE html>
|
||||
<html lang="zh-CN"><head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<title>{title}</title>
|
||||
<style>{SHELL_CSS}{extra}</style>
|
||||
</head>
|
||||
<body class="{body_class}">
|
||||
<header class="{nav_class}"{nav_attrs}>{nav_ul}</header>
|
||||
{side_html}
|
||||
<main class="{main_class}"{main_attrs}>{main_html}</main>
|
||||
<footer class="{foot_class}"{foot_attrs}>{foot_ul}</footer>
|
||||
</body></html>"#,
|
||||
title = esc(title),
|
||||
nav_class = slot_class(args, "nav", "topnav"),
|
||||
nav_attrs = slot_attrs("nav", &parts),
|
||||
nav_ul = render_ul(&nav, "nav"),
|
||||
side_html = if has_side {
|
||||
format!(
|
||||
"<aside class=\"{}\"{}><span class=\"side-label\">侧栏</span>{}</aside>",
|
||||
slot_class(args, "sidebar", "side"),
|
||||
slot_attrs("sidebar", &parts),
|
||||
render_ul(&side, "side-nav")
|
||||
)
|
||||
} else {
|
||||
String::new()
|
||||
},
|
||||
main_class = slot_class(args, "main", "main"),
|
||||
main_attrs = slot_attrs("main", &parts),
|
||||
foot_class = slot_class(args, "footer", "foot"),
|
||||
foot_attrs = slot_attrs("footer", &parts),
|
||||
foot_ul = render_ul(&foot, "foot-nav"),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn render_fragment(args: &Value, db_url: Option<&str>) -> String {
|
||||
let slot = args
|
||||
.get("fragment")
|
||||
.or_else(|| args.get("slot"))
|
||||
.and_then(|v| v.as_str())
|
||||
.map(normalize_slot)
|
||||
.unwrap_or_else(|| "main".into());
|
||||
match slot.as_str() {
|
||||
"nav" => {
|
||||
let links = resolve_links(args.get("nav"), db_url);
|
||||
format!(
|
||||
"<header class=\"topnav\" data-slot=\"nav\">{}</header>",
|
||||
render_ul(&links, "nav")
|
||||
)
|
||||
}
|
||||
"sidebar" => {
|
||||
let links = resolve_links(args.get("sidebar"), db_url);
|
||||
format!(
|
||||
"<aside class=\"side\" data-slot=\"sidebar\"><span class=\"side-label\">侧栏</span>{}</aside>",
|
||||
render_ul(&links, "side-nav")
|
||||
)
|
||||
}
|
||||
"footer" => {
|
||||
let links = resolve_links(args.get("footer"), db_url);
|
||||
format!(
|
||||
"<footer class=\"foot\" data-slot=\"footer\">{}</footer>",
|
||||
render_ul(&links, "foot-nav")
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
let (intro, items) = resolve_main(args, db_url);
|
||||
let mut body = String::new();
|
||||
if !intro.is_empty() {
|
||||
body.push_str(&format!("<div class=\"main-intro\">{intro}</div>"));
|
||||
}
|
||||
if !items.is_empty() {
|
||||
body.push_str("<section class=\"content cards\">");
|
||||
for it in &items {
|
||||
let title = it.get("title").map(text).unwrap_or_default();
|
||||
let b = it.get("body").map(text).unwrap_or_default();
|
||||
let tc = class_attr(&field_css(it, "title"));
|
||||
let bc = class_attr(&field_css(it, "body"));
|
||||
body.push_str(&format!(
|
||||
"<article><h2{tc}>{}</h2><p{bc}>{}</p></article>",
|
||||
esc(&title),
|
||||
esc(&b)
|
||||
));
|
||||
}
|
||||
body.push_str("</section>");
|
||||
}
|
||||
format!("<main class=\"main\" data-slot=\"main\">{body}</main>")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
//! GFM table helpers + site path parsing (cells stay string literals).
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
const FIELD_KEYS: &[&str] = &["字段", "name", "列", "column"];
|
||||
const TYPE_KEYS: &[&str] = &["类型", "type"];
|
||||
const NULL_KEYS: &[&str] = &["可空", "null", "nullable"];
|
||||
const FRONT_KEYS: &[&str] = &["属性", "前端变量", "front", "field"];
|
||||
const BACK_KEYS: &[&str] = &["值", "后端数据库", "back", "db"];
|
||||
const CSS_KEYS: &[&str] = &["样式", "绑定css样式", "css", "class", "style"];
|
||||
const SRC_KEYS: &[&str] = &["组件", "导入的页面", "src", "page"];
|
||||
const STYLE_KEYS: &[&str] = &["样式", "style", "class"];
|
||||
const PROP_KEYS: &[&str] = &["属性", "property", "prop", "名", "name"];
|
||||
const VAL_KEYS: &[&str] = &["值", "value"];
|
||||
|
||||
pub fn normalize_ref(s: &str) -> String {
|
||||
let s = s.trim();
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut rest = s;
|
||||
while let Some(start) = rest.find('`') {
|
||||
out.push_str(&rest[..start]);
|
||||
rest = &rest[start + 1..];
|
||||
if let Some(end) = rest.find('`') {
|
||||
out.push_str(&rest[..end]);
|
||||
rest = &rest[end + 1..];
|
||||
} else {
|
||||
out.push('`');
|
||||
out.push_str(rest);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
fn pick<'a>(m: &'a Map<String, Value>, keys: &[&str]) -> Option<&'a Value> {
|
||||
keys.iter().find_map(|k| m.get(*k))
|
||||
}
|
||||
|
||||
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 as_str_list(v: &Value) -> Vec<String> {
|
||||
match v {
|
||||
Value::Array(a) => a.iter().map(cell_str).collect(),
|
||||
Value::Null => Vec::new(),
|
||||
other => vec![cell_str(other)],
|
||||
}
|
||||
}
|
||||
|
||||
fn boolish(v: &Value) -> bool {
|
||||
match v {
|
||||
Value::Bool(b) => *b,
|
||||
Value::String(s) => matches!(s.trim(), "1" | "true" | "True" | "yes" | "是" | "可"),
|
||||
Value::Number(n) => n.as_i64().unwrap_or(0) != 0,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Schema table → `[{name,type,nullable}, …]`
|
||||
pub fn as_fields(table: &Value) -> Value {
|
||||
match table {
|
||||
Value::Array(rows) => {
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
if let Some(m) = row.as_object() {
|
||||
let name = pick(m, FIELD_KEYS).map(cell_str).unwrap_or_default();
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let ty = pick(m, TYPE_KEYS)
|
||||
.map(cell_str)
|
||||
.unwrap_or_else(|| "text".into());
|
||||
let nullable = pick(m, NULL_KEYS).map(boolish).unwrap_or(true);
|
||||
out.push(json!({ "name": name, "type": ty, "nullable": nullable }));
|
||||
}
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
Value::Object(m) => {
|
||||
let names = pick(m, FIELD_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let types = pick(m, TYPE_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let nulls = pick(m, NULL_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let ty = types.get(i).cloned().unwrap_or_else(|| "text".into());
|
||||
let nullable = nulls
|
||||
.get(i)
|
||||
.map(|s| boolish(&Value::String(s.clone())))
|
||||
.unwrap_or(true);
|
||||
out.push(json!({ "name": name, "type": ty, "nullable": nullable }));
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
_ => json!([]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Seed / row table → list of maps.
|
||||
pub fn as_rows(table: &Value) -> Value {
|
||||
match table {
|
||||
Value::Array(a) => Value::Array(a.clone()),
|
||||
Value::Object(m) => {
|
||||
// @ / 行 / row column → list of maps
|
||||
let keys: Vec<String> = m.keys().cloned().collect();
|
||||
let row_key = ["@", "行", "row"]
|
||||
.iter()
|
||||
.find(|k| m.contains_key(**k))
|
||||
.map(|s| s.to_string());
|
||||
if let Some(rk) = row_key {
|
||||
let n = as_str_list(m.get(&rk).unwrap()).len();
|
||||
let mut out = Vec::new();
|
||||
for i in 0..n {
|
||||
let mut row = Map::new();
|
||||
for k in &keys {
|
||||
if k == &rk {
|
||||
continue;
|
||||
}
|
||||
let list = as_str_list(m.get(k).unwrap_or(&Value::Null));
|
||||
row.insert(k.clone(), json!(list.get(i).cloned().unwrap_or_default()));
|
||||
}
|
||||
if let Some(id) = as_str_list(m.get(&rk).unwrap()).get(i) {
|
||||
if !id.is_empty() {
|
||||
row.insert("id".into(), json!(id));
|
||||
}
|
||||
}
|
||||
out.push(Value::Object(row));
|
||||
}
|
||||
return Value::Array(out);
|
||||
}
|
||||
// Columnar GFM table: each value is a same-length array → zip into rows.
|
||||
let mut col_lens: Vec<usize> = Vec::new();
|
||||
let mut all_arrays = !m.is_empty();
|
||||
for v in m.values() {
|
||||
match v {
|
||||
Value::Array(a) => col_lens.push(a.len()),
|
||||
_ => {
|
||||
all_arrays = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if all_arrays {
|
||||
let n = col_lens.iter().copied().max().unwrap_or(0);
|
||||
if n > 0 && col_lens.iter().all(|&l| l == n || l == 0) {
|
||||
let mut out = Vec::new();
|
||||
for i in 0..n {
|
||||
let mut row = Map::new();
|
||||
for (k, v) in m {
|
||||
if let Value::Array(a) = v {
|
||||
row.insert(
|
||||
k.clone(),
|
||||
a.get(i).cloned().unwrap_or(Value::Null),
|
||||
);
|
||||
}
|
||||
}
|
||||
out.push(Value::Object(row));
|
||||
}
|
||||
return Value::Array(out);
|
||||
}
|
||||
}
|
||||
// single map
|
||||
Value::Array(vec![Value::Object(m.clone())])
|
||||
}
|
||||
_ => json!([]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bind table → `[{front,back,css}, …]`
|
||||
pub fn as_bind(table: &Value) -> Value {
|
||||
match table {
|
||||
Value::Array(rows) => {
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
if let Some(m) = row.as_object() {
|
||||
let front = normalize_ref(&pick(m, FRONT_KEYS).map(cell_str).unwrap_or_default());
|
||||
let back = normalize_ref(&pick(m, BACK_KEYS).map(cell_str).unwrap_or_default());
|
||||
let css = normalize_ref(&pick(m, CSS_KEYS).map(cell_str).unwrap_or_default());
|
||||
if !front.is_empty() || !back.is_empty() {
|
||||
out.push(json!({ "front": front, "back": back, "css": css }));
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
Value::Object(m) => {
|
||||
let fronts = pick(m, FRONT_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let backs = pick(m, BACK_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let csses = pick(m, CSS_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let n = fronts.len().max(backs.len());
|
||||
let mut out = Vec::new();
|
||||
for i in 0..n {
|
||||
let front = normalize_ref(&fronts.get(i).cloned().unwrap_or_default());
|
||||
let back = normalize_ref(&backs.get(i).cloned().unwrap_or_default());
|
||||
let css = normalize_ref(&csses.get(i).cloned().unwrap_or_default());
|
||||
if !front.is_empty() || !back.is_empty() {
|
||||
out.push(json!({ "front": front, "back": back, "css": css }));
|
||||
}
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
_ => json!([]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Page table → `[{src,style,slot}, …]`
|
||||
pub fn as_compose(table: &Value) -> Value {
|
||||
match table {
|
||||
Value::Object(m) => {
|
||||
let srcs = pick(m, SRC_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let styles = pick(m, STYLE_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
for (i, src_raw) in srcs.iter().enumerate() {
|
||||
let src = normalize_ref(src_raw);
|
||||
if src.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let style = normalize_ref(&styles.get(i).cloned().unwrap_or_default());
|
||||
let slot = infer_slot(&src);
|
||||
out.push(json!({ "src": src, "style": style, "slot": slot }));
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
Value::Array(rows) => {
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
if let Some(m) = row.as_object() {
|
||||
let src = normalize_ref(&pick(m, SRC_KEYS).map(cell_str).unwrap_or_default());
|
||||
if src.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let style = normalize_ref(&pick(m, STYLE_KEYS).map(cell_str).unwrap_or_default());
|
||||
let slot = infer_slot(&src);
|
||||
out.push(json!({ "src": src, "style": style, "slot": slot }));
|
||||
}
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
_ => json!([]),
|
||||
}
|
||||
}
|
||||
|
||||
fn infer_slot(src: &str) -> String {
|
||||
let base = src.rsplit('.').next().unwrap_or(src);
|
||||
match base {
|
||||
"nav" | "links" => "nav".into(),
|
||||
"side" | "sidebar" => "sidebar".into(),
|
||||
"foot" | "footer" => "footer".into(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn normalize_slot(name: &str) -> String {
|
||||
match name {
|
||||
"nav" | "links" => "nav".into(),
|
||||
"side" | "sidebar" => "sidebar".into(),
|
||||
"foot" | "footer" => "footer".into(),
|
||||
"main" | "index" | "" => "main".into(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Style table → CSS text for `.name { … }`
|
||||
pub fn as_css_named(name: &str, table: &Value) -> String {
|
||||
let name = normalize_ref(name);
|
||||
if name.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let mut rules = Vec::new();
|
||||
match table {
|
||||
Value::Object(m) => {
|
||||
let props = pick(m, PROP_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let vals = pick(m, VAL_KEYS).map(as_str_list).unwrap_or_default();
|
||||
for (i, p) in props.iter().enumerate() {
|
||||
if p.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let v = vals.get(i).cloned().unwrap_or_default();
|
||||
rules.push(format!(" {p}: {v};"));
|
||||
}
|
||||
}
|
||||
Value::Array(rows) => {
|
||||
for row in rows {
|
||||
if let Some(m) = row.as_object() {
|
||||
let p = pick(m, PROP_KEYS).map(cell_str).unwrap_or_default();
|
||||
let v = pick(m, VAL_KEYS).map(cell_str).unwrap_or_default();
|
||||
if !p.is_empty() {
|
||||
rules.push(format!(" {p}: {v};"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if rules.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
format!(".{} {{\n{}\n}}\n", name, rules.join("\n"))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum SitePath {
|
||||
LibMember { lib: String, member: String },
|
||||
DbField { table: String, field: String },
|
||||
Plain(String),
|
||||
}
|
||||
|
||||
pub fn parse_site_path(raw: &str) -> SitePath {
|
||||
let s = normalize_ref(raw);
|
||||
if s.is_empty() {
|
||||
return SitePath::Plain(String::new());
|
||||
}
|
||||
let parts: Vec<&str> = s.split('.').filter(|p| !p.is_empty()).collect();
|
||||
match parts.as_slice() {
|
||||
[lib, member] => SitePath::LibMember {
|
||||
lib: (*lib).into(),
|
||||
member: (*member).into(),
|
||||
},
|
||||
[_, table, field] => SitePath::DbField {
|
||||
table: (*table).into(),
|
||||
field: (*field).into(),
|
||||
},
|
||||
_ => SitePath::Plain(s),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bind_table_name(binds: &[Value]) -> Option<String> {
|
||||
let mut found: Option<String> = None;
|
||||
for b in binds {
|
||||
let back = b.get("back").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if let SitePath::DbField { table, .. } = parse_site_path(back) {
|
||||
match &found {
|
||||
None => found = Some(table),
|
||||
Some(prev) if prev != &table => return None,
|
||||
_ => {}
|
||||
}
|
||||
} else if back.contains('.') {
|
||||
let mut p = back.splitn(2, '.');
|
||||
if let (Some(t), Some(_)) = (p.next(), p.next()) {
|
||||
match &found {
|
||||
None => found = Some(t.into()),
|
||||
Some(prev) if prev != t => return None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
pub fn project_rows(binds: &[Value], rows: &[Value]) -> Value {
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
let obj = row.as_object().cloned().unwrap_or_default();
|
||||
let mut m = Map::new();
|
||||
let mut css = Map::new();
|
||||
for b in binds {
|
||||
let front = b.get("front").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let back = b.get("back").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let class = b.get("css").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let col = match parse_site_path(back) {
|
||||
SitePath::DbField { field, .. } => field,
|
||||
SitePath::Plain(s) if s.contains('.') => {
|
||||
s.split('.').next_back().unwrap_or(&s).to_string()
|
||||
}
|
||||
SitePath::Plain(s) => s,
|
||||
SitePath::LibMember { .. } => back.to_string(),
|
||||
};
|
||||
if let Some(v) = obj.get(&col).or_else(|| obj.get(front)) {
|
||||
m.insert(front.to_string(), v.clone());
|
||||
}
|
||||
if !class.is_empty() {
|
||||
css.insert(front.to_string(), json!(class));
|
||||
}
|
||||
}
|
||||
if let Some(id) = obj.get("id") {
|
||||
m.insert("id".into(), id.clone());
|
||||
}
|
||||
if !css.is_empty() {
|
||||
m.insert("_css".into(), Value::Object(css));
|
||||
}
|
||||
out.push(Value::Object(m));
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
@@ -1,627 +0,0 @@
|
||||
//! Convert Marqdo GFM table values (list-of-maps or column-oriented map) into
|
||||
//! nav links / schema fields — so authors write readable tables, not JSON.
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
const LABEL_KEYS: &[&str] = &[
|
||||
"页面导航",
|
||||
"导航",
|
||||
"label",
|
||||
"标签",
|
||||
"title",
|
||||
"标题",
|
||||
"名",
|
||||
"name",
|
||||
];
|
||||
const HREF_KEYS: &[&str] = &[
|
||||
"对应路由",
|
||||
"路由",
|
||||
"href",
|
||||
"链接",
|
||||
"路径",
|
||||
"path",
|
||||
"url",
|
||||
];
|
||||
const FIELD_KEYS: &[&str] = &["字段", "name", "列", "名", "column"];
|
||||
const TYPE_KEYS: &[&str] = &["类型", "type"];
|
||||
const NULL_KEYS: &[&str] = &["可空", "null", "nullable"];
|
||||
const DEFAULT_KEYS: &[&str] = &["默认", "default"];
|
||||
const UNIQUE_KEYS: &[&str] = &["唯一", "unique"];
|
||||
|
||||
/// Unified UI bind: frontend var ↔ optional DB path / href ↔ optional CSS.
|
||||
const FRONT_KEYS: &[&str] = &["前端变量", "front", "变量", "名", "field"];
|
||||
const BACK_KEYS: &[&str] = &[
|
||||
"后端数据库",
|
||||
"back",
|
||||
"数据库",
|
||||
"字段绑定",
|
||||
"db",
|
||||
"绑定",
|
||||
];
|
||||
const CSS_KEYS: &[&str] = &["绑定css样式", "css", "样式", "class", "style", "classes"];
|
||||
|
||||
fn pick<'a>(m: &'a Map<String, Value>, keys: &[&str]) -> Option<&'a Value> {
|
||||
for k in keys {
|
||||
if let Some(v) = m.get(*k) {
|
||||
return Some(v);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn as_str_list(v: &Value) -> Vec<String> {
|
||||
match v {
|
||||
Value::Array(a) => a
|
||||
.iter()
|
||||
.map(|x| match x {
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Bool(b) => b.to_string(),
|
||||
Value::Number(n) => n.to_string(),
|
||||
Value::Null => String::new(),
|
||||
other => other.to_string(),
|
||||
})
|
||||
.collect(),
|
||||
Value::String(s) => vec![s.clone()],
|
||||
Value::Null => Vec::new(),
|
||||
other => vec![other.to_string()],
|
||||
}
|
||||
}
|
||||
|
||||
fn cell_str(v: &Value) -> String {
|
||||
match v {
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Bool(b) => b.to_string(),
|
||||
Value::Number(n) => n.to_string(),
|
||||
Value::Null => String::new(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn boolish(v: &Value) -> bool {
|
||||
match v {
|
||||
Value::Bool(b) => *b,
|
||||
Value::String(s) => matches!(
|
||||
s.trim(),
|
||||
"1" | "true" | "True" | "yes" | "是" | "可" | "nullable"
|
||||
),
|
||||
Value::Number(n) => n.as_i64().unwrap_or(0) != 0,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn ident_ok(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& s.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '_')
|
||||
}
|
||||
|
||||
/// `table.column` DB reference (not a URL path).
|
||||
pub fn is_db_ref(s: &str) -> bool {
|
||||
let s = s.trim();
|
||||
if s.is_empty() || s.starts_with('/') || s.contains("://") {
|
||||
return false;
|
||||
}
|
||||
let mut parts = s.split('.');
|
||||
match (parts.next(), parts.next(), parts.next()) {
|
||||
(Some(t), Some(c), None) => ident_ok(t) && ident_ok(c),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_db_ref(s: &str) -> Option<(String, String)> {
|
||||
if !is_db_ref(s) {
|
||||
return None;
|
||||
}
|
||||
let mut parts = s.trim().splitn(2, '.');
|
||||
Some((parts.next()?.to_string(), parts.next()?.to_string()))
|
||||
}
|
||||
|
||||
fn bind_row(front: String, back: String, css: String) -> Value {
|
||||
json!({ "front": front, "back": back, "css": css })
|
||||
}
|
||||
|
||||
fn looks_like_bind_map(m: &Map<String, Value>) -> bool {
|
||||
pick(m, FRONT_KEYS).is_some()
|
||||
}
|
||||
|
||||
/// Turn the unified 3-col bind table into `[{front, back, css}, ...]`.
|
||||
/// Also accepts legacy nav tables (`页面导航` / `对应路由`) as static link binds.
|
||||
pub fn as_bind(table: &Value) -> Value {
|
||||
match table {
|
||||
Value::Null => json!([]),
|
||||
Value::Array(rows) => {
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
if let Some(m) = row.as_object() {
|
||||
if looks_like_bind_map(m) {
|
||||
let front = pick(m, FRONT_KEYS).map(cell_str).unwrap_or_default();
|
||||
let back = pick(m, BACK_KEYS).map(cell_str).unwrap_or_default();
|
||||
let css = pick(m, CSS_KEYS).map(cell_str).unwrap_or_default();
|
||||
if !front.is_empty() || !back.is_empty() {
|
||||
out.push(bind_row(front, back, css));
|
||||
}
|
||||
} else if pick(m, LABEL_KEYS).is_some() || pick(m, HREF_KEYS).is_some() {
|
||||
let front = pick(m, LABEL_KEYS).map(cell_str).unwrap_or_default();
|
||||
let back = pick(m, HREF_KEYS)
|
||||
.map(cell_str)
|
||||
.unwrap_or_else(|| "#".into());
|
||||
out.push(bind_row(front, back, String::new()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
Value::Object(m) => {
|
||||
if m.get("_type").and_then(|v| v.as_str()) == Some("live") {
|
||||
return json!([]);
|
||||
}
|
||||
if looks_like_bind_map(m) {
|
||||
let fronts = pick(m, FRONT_KEYS)
|
||||
.map(as_str_list)
|
||||
.unwrap_or_default();
|
||||
let backs = pick(m, BACK_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let csses = pick(m, CSS_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let n = fronts.len().max(backs.len()).max(csses.len());
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
let front = fronts.get(i).cloned().unwrap_or_default();
|
||||
let back = backs.get(i).cloned().unwrap_or_default();
|
||||
let css = csses.get(i).cloned().unwrap_or_default();
|
||||
if front.is_empty() && back.is_empty() {
|
||||
continue;
|
||||
}
|
||||
out.push(bind_row(front, back, css));
|
||||
}
|
||||
return Value::Array(out);
|
||||
}
|
||||
// Legacy column nav → bind rows (require label column; bare `url` is not nav)
|
||||
let labels = pick(m, LABEL_KEYS)
|
||||
.map(as_str_list)
|
||||
.unwrap_or_default();
|
||||
let hrefs = pick(m, HREF_KEYS)
|
||||
.map(as_str_list)
|
||||
.unwrap_or_default();
|
||||
if !labels.is_empty() {
|
||||
let n = labels.len().max(hrefs.len());
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
let front = labels.get(i).cloned().unwrap_or_default();
|
||||
let back = hrefs.get(i).cloned().unwrap_or_else(|| "#".into());
|
||||
out.push(bind_row(front, back, String::new()));
|
||||
}
|
||||
return Value::Array(out);
|
||||
}
|
||||
json!([])
|
||||
}
|
||||
_ => json!([]),
|
||||
}
|
||||
}
|
||||
|
||||
/// True when any bind row points at `table.column`.
|
||||
pub fn bind_has_db(binds: &[Value]) -> bool {
|
||||
binds.iter().any(|b| {
|
||||
b.get("back")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(is_db_ref)
|
||||
.unwrap_or(false)
|
||||
})
|
||||
}
|
||||
|
||||
/// Infer the single DB table name from bind rows (`posts.title` → `posts`).
|
||||
pub fn bind_table_name(binds: &[Value]) -> Option<String> {
|
||||
let mut found: Option<String> = None;
|
||||
for b in binds {
|
||||
let back = b.get("back").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if let Some((t, _)) = parse_db_ref(back) {
|
||||
match &found {
|
||||
None => found = Some(t),
|
||||
Some(prev) if prev != &t => return None, // mixed tables
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Static link region: each bind row is one link (`front`=label, `back`=href).
|
||||
pub fn binds_as_static_links(binds: &[Value]) -> Value {
|
||||
let mut out = Vec::new();
|
||||
for b in binds {
|
||||
let label = b
|
||||
.get("front")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let href = b
|
||||
.get("back")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| {
|
||||
let s = s.trim();
|
||||
if s.is_empty() {
|
||||
"#"
|
||||
} else {
|
||||
s
|
||||
}
|
||||
})
|
||||
.unwrap_or("#")
|
||||
.to_string();
|
||||
let css = b
|
||||
.get("css")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if label.is_empty() && href == "#" {
|
||||
continue;
|
||||
}
|
||||
out.push(json!({ "label": label, "href": href, "css": css }));
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
|
||||
/// Loop DB rows through field binds → `[{front: value, ..., _css: {front: class}}]`.
|
||||
pub fn project_rows(binds: &[Value], rows: &[Value]) -> Value {
|
||||
let mut out = Vec::with_capacity(rows.len());
|
||||
for row in rows {
|
||||
let Some(obj) = row.as_object() else {
|
||||
continue;
|
||||
};
|
||||
let mut item = Map::new();
|
||||
let mut css_map = Map::new();
|
||||
for b in binds {
|
||||
let front = b
|
||||
.get("front")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if front.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let back = b.get("back").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let css = b.get("css").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let val = if let Some((_, col)) = parse_db_ref(back) {
|
||||
obj.get(&col).cloned().unwrap_or(Value::Null)
|
||||
} else if back.is_empty() {
|
||||
Value::String(front.clone())
|
||||
} else if ident_ok(back) {
|
||||
obj.get(back).cloned().unwrap_or(Value::Null)
|
||||
} else {
|
||||
Value::String(back.to_string())
|
||||
};
|
||||
item.insert(front.clone(), val);
|
||||
if !css.is_empty() {
|
||||
css_map.insert(front, json!(css));
|
||||
}
|
||||
}
|
||||
// Keep id for meta when present on source row
|
||||
if let Some(id) = obj.get("id") {
|
||||
item.entry("id".to_string()).or_insert_with(|| id.clone());
|
||||
}
|
||||
if !css_map.is_empty() {
|
||||
item.insert("_css".into(), Value::Object(css_map));
|
||||
}
|
||||
out.push(Value::Object(item));
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
|
||||
fn looks_like_href(s: &str) -> bool {
|
||||
let s = s.trim();
|
||||
s.starts_with('/')
|
||||
|| s.starts_with('#')
|
||||
|| s.starts_with("http://")
|
||||
|| s.starts_with("https://")
|
||||
}
|
||||
|
||||
/// When `page.table=` is set, bare column backs become `table.column`.
|
||||
/// There is **no** default table name — callers must pass one.
|
||||
pub fn qualify_binds(binds: &[Value], table: Option<&str>) -> Vec<Value> {
|
||||
let Some(t) = table.map(str::trim).filter(|s| !s.is_empty()) else {
|
||||
return binds.to_vec();
|
||||
};
|
||||
if !ident_ok(t) {
|
||||
return binds.to_vec();
|
||||
}
|
||||
binds
|
||||
.iter()
|
||||
.map(|b| {
|
||||
let front = b.get("front").cloned().unwrap_or(json!(""));
|
||||
let css = b.get("css").cloned().unwrap_or(json!(""));
|
||||
let back = b
|
||||
.get("back")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
let back = if back.is_empty() || is_db_ref(&back) || looks_like_href(&back) {
|
||||
back
|
||||
} else if ident_ok(&back) {
|
||||
format!("{t}.{back}")
|
||||
} else {
|
||||
back
|
||||
};
|
||||
json!({ "front": front, "back": back, "css": css })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
const ROW_INDEX_KEYS: &[&str] = &["@", "行", "row"];
|
||||
|
||||
/// GFM data table → `[{col: val}, …]` for inserts.
|
||||
/// Accepts: list-of-maps (`@`/`行` geometry), column-oriented map (dict of lists), or one map row.
|
||||
pub fn as_rows(table: &Value) -> Value {
|
||||
match table {
|
||||
Value::Null => json!([]),
|
||||
Value::Array(rows) => {
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
if let Some(m) = row.as_object() {
|
||||
let mut clean = Map::new();
|
||||
for (k, v) in m {
|
||||
if ROW_INDEX_KEYS.contains(&k.as_str()) {
|
||||
continue;
|
||||
}
|
||||
clean.insert(k.clone(), v.clone());
|
||||
}
|
||||
if !clean.is_empty() {
|
||||
out.push(Value::Object(clean));
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
Value::Object(m) => {
|
||||
let keys: Vec<String> = m
|
||||
.keys()
|
||||
.filter(|k| !ROW_INDEX_KEYS.contains(&k.as_str()))
|
||||
.cloned()
|
||||
.collect();
|
||||
if keys.is_empty() {
|
||||
return json!([]);
|
||||
}
|
||||
let any_list = keys.iter().any(|k| m.get(k).is_some_and(|v| v.is_array()));
|
||||
if any_list {
|
||||
let cols: Vec<(String, Vec<String>)> = keys
|
||||
.iter()
|
||||
.map(|k| (k.clone(), as_str_list(m.get(k).unwrap_or(&Value::Null))))
|
||||
.collect();
|
||||
let n = cols.iter().map(|(_, v)| v.len()).max().unwrap_or(0);
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
let mut row = Map::new();
|
||||
for (k, vals) in &cols {
|
||||
row.insert(
|
||||
k.clone(),
|
||||
json!(vals.get(i).cloned().unwrap_or_default()),
|
||||
);
|
||||
}
|
||||
out.push(Value::Object(row));
|
||||
}
|
||||
Value::Array(out)
|
||||
} else {
|
||||
let mut row = Map::new();
|
||||
for k in keys {
|
||||
if let Some(v) = m.get(&k) {
|
||||
row.insert(k, v.clone());
|
||||
}
|
||||
}
|
||||
json!([Value::Object(row)])
|
||||
}
|
||||
}
|
||||
_ => json!([]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn a nav/side/footer table into `[{label, href}, ...]`.
|
||||
pub fn as_links(table: &Value) -> Value {
|
||||
let binds = as_bind(table);
|
||||
let arr = binds.as_array().cloned().unwrap_or_default();
|
||||
if bind_has_db(&arr) {
|
||||
// Without DB handle here, return empty — callers should use project_rows.
|
||||
return json!([]);
|
||||
}
|
||||
binds_as_static_links(&arr)
|
||||
}
|
||||
|
||||
/// Turn a schema table into `[{name, type, null, ...}, ...]`.
|
||||
pub fn as_fields(table: &Value) -> Value {
|
||||
match table {
|
||||
Value::Null => json!([]),
|
||||
Value::Array(rows) => {
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
if let Some(m) = row.as_object() {
|
||||
if let Some(f) = field_from_map(m) {
|
||||
out.push(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
Value::Object(m) => {
|
||||
let names = pick(m, FIELD_KEYS)
|
||||
.map(as_str_list)
|
||||
.unwrap_or_default();
|
||||
let types = pick(m, TYPE_KEYS)
|
||||
.map(as_str_list)
|
||||
.unwrap_or_default();
|
||||
let nulls = pick(m, NULL_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let defaults = pick(m, DEFAULT_KEYS)
|
||||
.map(as_str_list)
|
||||
.unwrap_or_default();
|
||||
let uniques = pick(m, UNIQUE_KEYS)
|
||||
.map(as_str_list)
|
||||
.unwrap_or_default();
|
||||
if names.is_empty() {
|
||||
return json!([]);
|
||||
}
|
||||
let n = names.len();
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
let name = &names[i];
|
||||
if name.is_empty() || name == "@" || name == "行" || name == "row" {
|
||||
continue;
|
||||
}
|
||||
let ty = types.get(i).cloned().unwrap_or_else(|| "text".into());
|
||||
let nullable = nulls
|
||||
.get(i)
|
||||
.map(|s| {
|
||||
matches!(
|
||||
s.trim(),
|
||||
"1" | "true" | "True" | "yes" | "是" | "可" | "nullable"
|
||||
)
|
||||
})
|
||||
.unwrap_or(true);
|
||||
let mut field = json!({
|
||||
"name": name,
|
||||
"type": ty,
|
||||
"null": nullable,
|
||||
});
|
||||
if let Some(d) = defaults.get(i) {
|
||||
if !d.is_empty() {
|
||||
field
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.insert("default".into(), json!(d));
|
||||
}
|
||||
}
|
||||
if let Some(u) = uniques.get(i) {
|
||||
let uniq = matches!(u.trim(), "1" | "true" | "True" | "yes" | "是" | "唯一");
|
||||
field
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.insert("unique".into(), json!(uniq));
|
||||
}
|
||||
out.push(field);
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
_ => json!([]),
|
||||
}
|
||||
}
|
||||
|
||||
fn field_from_map(m: &Map<String, Value>) -> Option<Value> {
|
||||
let name = pick(m, FIELD_KEYS).map(cell_str)?;
|
||||
if name.is_empty() || name == "@" || name == "行" || name == "row" {
|
||||
return None;
|
||||
}
|
||||
let ty = pick(m, TYPE_KEYS)
|
||||
.map(cell_str)
|
||||
.unwrap_or_else(|| "text".into());
|
||||
let nullable = pick(m, NULL_KEYS).map(boolish).unwrap_or(true);
|
||||
let mut field = json!({
|
||||
"name": name,
|
||||
"type": ty,
|
||||
"null": nullable,
|
||||
});
|
||||
if let Some(d) = pick(m, DEFAULT_KEYS) {
|
||||
field
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.insert("default".into(), d.clone());
|
||||
}
|
||||
if let Some(u) = pick(m, UNIQUE_KEYS) {
|
||||
field
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.insert("unique".into(), json!(boolish(u)));
|
||||
}
|
||||
Some(field)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn column_nav_table() {
|
||||
let t = json!({
|
||||
"页面导航": ["首页", "管理"],
|
||||
"对应路由": ["/", "/admin"],
|
||||
});
|
||||
let links = as_links(&t);
|
||||
assert_eq!(links.as_array().unwrap().len(), 2);
|
||||
assert_eq!(links[0]["label"], "首页");
|
||||
assert_eq!(links[0]["href"], "/");
|
||||
assert_eq!(links[1]["label"], "管理");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn column_schema_table() {
|
||||
let t = json!({
|
||||
"字段": ["id", "title"],
|
||||
"类型": ["integer", "text"],
|
||||
"可空": ["false", "false"],
|
||||
});
|
||||
let fields = as_fields(&t);
|
||||
assert_eq!(fields[0]["name"], "id");
|
||||
assert_eq!(fields[0]["type"], "integer");
|
||||
assert_eq!(fields[0]["null"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn column_bind_table() {
|
||||
let t = json!({
|
||||
"前端变量": ["title", "body"],
|
||||
"后端数据库": ["posts.title", "posts.body"],
|
||||
"绑定css样式": ["card-title", "card-body"],
|
||||
});
|
||||
let binds = as_bind(&t);
|
||||
assert_eq!(binds.as_array().unwrap().len(), 2);
|
||||
assert_eq!(binds[0]["front"], "title");
|
||||
assert_eq!(binds[0]["back"], "posts.title");
|
||||
assert_eq!(binds[0]["css"], "card-title");
|
||||
assert_eq!(bind_table_name(binds.as_array().unwrap()).as_deref(), Some("posts"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_nav_via_bind() {
|
||||
let t = json!({
|
||||
"前端变量": ["首页", "管理"],
|
||||
"后端数据库": ["/", "/admin"],
|
||||
"绑定css样式": ["", ""],
|
||||
});
|
||||
let links = as_links(&t);
|
||||
assert_eq!(links[0]["label"], "首页");
|
||||
assert_eq!(links[0]["href"], "/");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_rows_applies_css() {
|
||||
let binds = as_bind(&json!({
|
||||
"前端变量": ["title", "body"],
|
||||
"后端数据库": ["posts.title", "posts.body"],
|
||||
"绑定css样式": ["t", "b"],
|
||||
}));
|
||||
let rows = json!([{"id": 1, "title": "Hello", "body": "World"}]);
|
||||
let out = project_rows(
|
||||
binds.as_array().unwrap(),
|
||||
rows.as_array().unwrap(),
|
||||
);
|
||||
assert_eq!(out[0]["title"], "Hello");
|
||||
assert_eq!(out[0]["_css"]["title"], "t");
|
||||
assert_eq!(out[0]["_css"]["body"], "b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qualify_bare_columns() {
|
||||
let binds = as_bind(&json!({
|
||||
"前端变量": ["title"],
|
||||
"后端数据库": ["title"],
|
||||
"绑定css样式": ["t"],
|
||||
}));
|
||||
let q = qualify_binds(binds.as_array().unwrap(), Some("articles"));
|
||||
assert_eq!(q[0]["back"], "articles.title");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn as_rows_column_dict() {
|
||||
let t = json!({
|
||||
"title": ["hello", "second"],
|
||||
"body": ["a", "b"],
|
||||
});
|
||||
let rows = as_rows(&t);
|
||||
assert_eq!(rows.as_array().unwrap().len(), 2);
|
||||
assert_eq!(rows[0]["title"], "hello");
|
||||
assert_eq!(rows[1]["body"], "b");
|
||||
}
|
||||
}
|
||||
@@ -1,509 +0,0 @@
|
||||
/* Marqdo Web default theme — semantic / classless shell.
|
||||
Content kinds: prose, cards, table. No purple/cream-terracotta AI defaults. */
|
||||
|
||||
:root {
|
||||
--ink: #1c1917;
|
||||
--ink-muted: #57534e;
|
||||
--paper: #fafaf9;
|
||||
--panel: #ffffff;
|
||||
--line: #e7e5e4;
|
||||
--accent: #0f766e;
|
||||
--accent-hover: #0d9488;
|
||||
--side-w: 14rem;
|
||||
--radius: 6px;
|
||||
--font-display: "Source Serif 4", "Noto Serif SC", Georgia, serif;
|
||||
--font-ui: "IBM Plex Sans", "Noto Sans SC", "Segoe UI", sans-serif;
|
||||
--font-mono: "IBM Plex Mono", ui-monospace, monospace;
|
||||
--space: 1.25rem;
|
||||
--max-prose: 42rem;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html {
|
||||
font-size: 16px;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
grid-template-rows: auto 1fr auto;
|
||||
grid-template-columns: 1fr;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
font-family: var(--font-ui);
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
body.has-sidebar {
|
||||
grid-template-columns: var(--side-w) 1fr;
|
||||
grid-template-areas:
|
||||
"top top"
|
||||
"side main"
|
||||
"foot foot";
|
||||
}
|
||||
|
||||
body.no-sidebar {
|
||||
grid-template-areas:
|
||||
"top"
|
||||
"main"
|
||||
"foot";
|
||||
}
|
||||
|
||||
/* —— Shell —— */
|
||||
header.topnav {
|
||||
grid-area: top;
|
||||
background: var(--panel);
|
||||
border-bottom: 1px solid var(--line);
|
||||
padding: 0.85rem var(--space);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
aside.side {
|
||||
grid-area: side;
|
||||
background: #f5f5f4;
|
||||
border-right: 1px solid var(--line);
|
||||
padding: var(--space) 1rem;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
main.main {
|
||||
grid-area: main;
|
||||
padding: calc(var(--space) * 1.25) var(--space) calc(var(--space) * 2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
footer.foot {
|
||||
grid-area: foot;
|
||||
border-top: 1px solid var(--line);
|
||||
padding: 0.85rem var(--space);
|
||||
color: var(--ink-muted);
|
||||
font-size: 0.9rem;
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
/* —— Nav links —— */
|
||||
ul.nav,
|
||||
ul.side-nav,
|
||||
ul.foot-nav {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
gap: 0.35rem 1.15rem;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
ul.side-nav {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 0.2rem;
|
||||
}
|
||||
|
||||
aside.side .side-label {
|
||||
display: block;
|
||||
font-size: 0.72rem;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--ink-muted);
|
||||
margin: 0 0 0.65rem;
|
||||
font-family: var(--font-ui);
|
||||
}
|
||||
|
||||
ul.nav a,
|
||||
ul.side-nav a,
|
||||
ul.foot-nav a {
|
||||
color: var(--ink);
|
||||
text-decoration: none;
|
||||
font-weight: 500;
|
||||
border-radius: var(--radius);
|
||||
padding: 0.35rem 0.45rem;
|
||||
}
|
||||
|
||||
ul.side-nav a {
|
||||
display: block;
|
||||
padding: 0.45rem 0.6rem;
|
||||
}
|
||||
|
||||
ul.nav a:hover,
|
||||
ul.side-nav a:hover,
|
||||
ul.foot-nav a:hover {
|
||||
color: var(--accent);
|
||||
background: rgba(15, 118, 110, 0.08);
|
||||
}
|
||||
|
||||
ul.side-nav a[aria-current="page"],
|
||||
ul.nav a[aria-current="page"] {
|
||||
color: var(--accent);
|
||||
background: rgba(15, 118, 110, 0.12);
|
||||
}
|
||||
|
||||
/* —— Prose (intro / raw main HTML) —— */
|
||||
.main-intro,
|
||||
.content.prose {
|
||||
max-width: var(--max-prose);
|
||||
font-family: var(--font-display);
|
||||
font-size: 1.125rem;
|
||||
}
|
||||
|
||||
.main-intro h1,
|
||||
.content.prose h1 {
|
||||
font-size: 2rem;
|
||||
line-height: 1.2;
|
||||
margin: 0 0 0.75rem;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.main-intro p,
|
||||
.content.prose p {
|
||||
margin: 0 0 1rem;
|
||||
color: var(--ink-muted);
|
||||
}
|
||||
|
||||
/* Bound field hooks from `|绑定css样式|` */
|
||||
.card-title {
|
||||
font-family: var(--font-display);
|
||||
}
|
||||
|
||||
.card-body {
|
||||
color: var(--ink-muted);
|
||||
}
|
||||
|
||||
.content.cards {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
margin-top: 1.25rem;
|
||||
grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr));
|
||||
}
|
||||
|
||||
.content.cards article {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
padding: 1rem 1.1rem;
|
||||
box-shadow: 0 1px 0 rgba(28, 25, 23, 0.04);
|
||||
}
|
||||
|
||||
.content.cards article h2 {
|
||||
font-family: var(--font-display);
|
||||
font-size: 1.2rem;
|
||||
margin: 0 0 0.45rem;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.content.cards article p {
|
||||
margin: 0;
|
||||
color: var(--ink-muted);
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.content.cards article .meta {
|
||||
margin-top: 0.65rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--ink-muted);
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
/* —— Table layout —— */
|
||||
.content.table-wrap {
|
||||
margin-top: 1.25rem;
|
||||
overflow-x: auto;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
.content.table-wrap table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.content.table-wrap th,
|
||||
.content.table-wrap td {
|
||||
padding: 0.55rem 0.75rem;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.content.table-wrap th {
|
||||
background: #f5f5f4;
|
||||
font-weight: 600;
|
||||
font-size: 0.8rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--ink-muted);
|
||||
}
|
||||
|
||||
.content.table-wrap tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
|
||||
/* —— Simple list —— */
|
||||
.content.list {
|
||||
margin: 1.25rem 0 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
max-width: var(--max-prose);
|
||||
}
|
||||
|
||||
.content.list li {
|
||||
padding: 0.65rem 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
font-family: var(--font-display);
|
||||
}
|
||||
|
||||
/* —— Admin panel —— */
|
||||
.admin-page {
|
||||
max-width: 56rem;
|
||||
}
|
||||
|
||||
.admin-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1.25rem;
|
||||
padding-bottom: 1rem;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.admin-crumbs {
|
||||
margin: 0 0 0.25rem;
|
||||
font-size: 0.8rem;
|
||||
color: var(--ink-muted);
|
||||
}
|
||||
|
||||
.admin-crumbs a {
|
||||
color: var(--ink-muted);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.admin-crumbs a:hover {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.admin-bar h1 {
|
||||
margin: 0;
|
||||
font-family: var(--font-display);
|
||||
font-size: 1.65rem;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.admin-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.admin-lead {
|
||||
margin: 0 0 1rem;
|
||||
color: var(--ink-muted);
|
||||
}
|
||||
|
||||
.admin-empty {
|
||||
color: var(--ink-muted);
|
||||
padding: 1.5rem 0;
|
||||
}
|
||||
|
||||
.admin-cards {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr));
|
||||
}
|
||||
|
||||
.admin-card {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
padding: 1rem 1.1rem;
|
||||
}
|
||||
|
||||
.admin-card h2 {
|
||||
margin: 0 0 0.35rem;
|
||||
font-size: 1.15rem;
|
||||
font-family: var(--font-display);
|
||||
}
|
||||
|
||||
.admin-meta {
|
||||
margin: 0 0 0.85rem;
|
||||
font-size: 0.85rem;
|
||||
color: var(--ink-muted);
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
.admin-card-actions {
|
||||
display: flex;
|
||||
gap: 0.45rem;
|
||||
}
|
||||
|
||||
.btn,
|
||||
button.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0.4rem 0.85rem;
|
||||
border-radius: var(--radius);
|
||||
border: 1px solid var(--accent);
|
||||
background: var(--accent);
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-size: 0.9rem;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.btn:hover,
|
||||
button.btn:hover {
|
||||
background: var(--accent-hover);
|
||||
border-color: var(--accent-hover);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.btn-ghost {
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
border-color: var(--line);
|
||||
}
|
||||
|
||||
.btn-ghost:hover {
|
||||
background: #f5f5f4;
|
||||
color: var(--ink);
|
||||
border-color: var(--line);
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: #fff;
|
||||
color: #b91c1c;
|
||||
border-color: #fecaca;
|
||||
}
|
||||
|
||||
.btn-danger:hover {
|
||||
background: #fef2f2;
|
||||
color: #991b1b;
|
||||
border-color: #fecaca;
|
||||
}
|
||||
|
||||
.btn-small {
|
||||
padding: 0.25rem 0.55rem;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.col-actions {
|
||||
white-space: nowrap;
|
||||
width: 1%;
|
||||
}
|
||||
|
||||
.inline-form {
|
||||
display: inline;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.admin-table th.col-actions {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.admin-table td.col-actions {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.admin-form {
|
||||
max-width: 28rem;
|
||||
}
|
||||
|
||||
.admin-form-fields {
|
||||
display: grid;
|
||||
gap: 0.9rem;
|
||||
}
|
||||
|
||||
.admin-field {
|
||||
display: grid;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.admin-field span {
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
color: var(--ink-muted);
|
||||
}
|
||||
|
||||
.admin-field input,
|
||||
.admin-field textarea {
|
||||
width: 100%;
|
||||
padding: 0.5rem 0.65rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
font: inherit;
|
||||
background: var(--panel);
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.admin-field input:focus,
|
||||
.admin-field textarea:focus {
|
||||
outline: 2px solid color-mix(in srgb, var(--accent) 35%, transparent);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.admin-form-footer {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
margin-top: 1.25rem;
|
||||
}
|
||||
|
||||
.log-action {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.log-create {
|
||||
color: #0f766e;
|
||||
}
|
||||
|
||||
.log-update {
|
||||
color: #a16207;
|
||||
}
|
||||
|
||||
.log-delete {
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
aside.side .side-label {
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
a:hover {
|
||||
color: var(--accent-hover);
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
body.has-sidebar {
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-areas:
|
||||
"top"
|
||||
"side"
|
||||
"main"
|
||||
"foot";
|
||||
}
|
||||
|
||||
aside.side {
|
||||
border-right: 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
ul.side-nav {
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user