Add ext/web with table-driven pages and polished admin CRUD.
Ship the web L1/plugin stack (bind tables, variable-named db.init, live render) and tighten the admin UI with sidebar, toolbar, forms, and activity log. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
ab8ea8438f
commit
8041a2274c
26 files changed
+5689
-242
No files matched your search
@@ -0,0 +1,782 @@
|
||||
//! SQLite helpers: open, migrate, define, CRUD.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use rusqlite::{params_from_iter, Connection, ToSql};
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
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() {
|
||||
if !parent.as_os_str().is_empty() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("create db dir: {e}"))?;
|
||||
}
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
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()
|
||||
.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}`"));
|
||||
}
|
||||
Ok(format!("\"{s}\""))
|
||||
}
|
||||
|
||||
fn sql_type(t: &str) -> &'static str {
|
||||
match t.trim().to_ascii_lowercase().as_str() {
|
||||
"int" | "integer" | "bigint" => "INTEGER",
|
||||
"bool" | "boolean" => "INTEGER",
|
||||
"real" | "float" | "double" => "REAL",
|
||||
"timestamp" | "datetime" => "TEXT",
|
||||
_ => "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" }));
|
||||
}
|
||||
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
|
||||
.get("name")
|
||||
.or_else(|| row.get("名"))
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "field missing name".to_string())?;
|
||||
let ty = row
|
||||
.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())
|
||||
.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 {
|
||||
col.push_str(" PRIMARY KEY");
|
||||
if sql_type(ty) == "INTEGER" {
|
||||
col.push_str(" AUTOINCREMENT");
|
||||
}
|
||||
} 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());
|
||||
}
|
||||
let sql = format!(
|
||||
"CREATE TABLE IF NOT EXISTS {table_q} ({});",
|
||||
cols.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 }))
|
||||
}
|
||||
|
||||
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;
|
||||
for row in arr {
|
||||
insert_row(url, table, row)?;
|
||||
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");
|
||||
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)
|
||||
}
|
||||
|
||||
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)?;
|
||||
let mut sets = Vec::new();
|
||||
let mut vals = Vec::new();
|
||||
for (k, v) in obj {
|
||||
if k == "id" || !ident_ok(k) {
|
||||
continue;
|
||||
}
|
||||
sets.push(format!("\"{k}\" = ?"));
|
||||
vals.push(v.clone());
|
||||
}
|
||||
if sets.is_empty() {
|
||||
return Err("nothing to update".into());
|
||||
}
|
||||
vals.push(json!(id));
|
||||
let sql = format!(
|
||||
"UPDATE {table_q} 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)
|
||||
}
|
||||
|
||||
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 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 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)?;
|
||||
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",
|
||||
)
|
||||
.map_err(|e| format!("list tables: {e}"))?;
|
||||
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))
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
//! Async HTTP server (tokio + axum).
|
||||
|
||||
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::routing::get;
|
||||
use axum::{Form, Router};
|
||||
use serde_json::{json, Value};
|
||||
use tower_http::services::ServeDir;
|
||||
|
||||
use crate::db;
|
||||
use crate::page;
|
||||
|
||||
#[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>,
|
||||
db_url: Option<String>,
|
||||
admin_tables: Vec<String>,
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
|
||||
let state = Arc::new(AppState {
|
||||
pages,
|
||||
page_cfgs,
|
||||
db_url: db_url.clone(),
|
||||
admin_tables,
|
||||
});
|
||||
|
||||
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));
|
||||
|
||||
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}"))?;
|
||||
|
||||
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}");
|
||||
|
||||
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}"))?;
|
||||
}
|
||||
Ok(json!({ "ok": true, "addr": bound.to_string() }))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
//! Marqdo web plugin (C ABI v2): async HTTP, SQLite, page shell, admin.
|
||||
|
||||
mod db;
|
||||
mod http;
|
||||
mod page;
|
||||
mod table_util;
|
||||
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
use std::ptr;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const ABI_VERSION: u32 = 2;
|
||||
|
||||
type PluginFn = unsafe extern "C" fn(
|
||||
args_json: *const c_char,
|
||||
out_json: *mut *mut c_char,
|
||||
err_msg: *mut *mut c_char,
|
||||
) -> c_int;
|
||||
|
||||
type HostQueryFn = unsafe extern "C" fn(
|
||||
userdata: *mut c_void,
|
||||
name: *const c_char,
|
||||
args_json: *const c_char,
|
||||
out_json: *mut *mut c_char,
|
||||
err_msg: *mut *mut c_char,
|
||||
) -> c_int;
|
||||
|
||||
#[repr(C)]
|
||||
pub struct MarqdoHostApi {
|
||||
pub userdata: *mut c_void,
|
||||
pub register_fn: Option<
|
||||
unsafe extern "C" fn(
|
||||
userdata: *mut c_void,
|
||||
name: *const c_char,
|
||||
params: *const c_char,
|
||||
fn_ptr: PluginFn,
|
||||
) -> c_int,
|
||||
>,
|
||||
pub alloc: Option<unsafe extern "C" fn(n: usize) -> *mut c_void>,
|
||||
pub free: Option<unsafe extern "C" fn(p: *mut c_void)>,
|
||||
pub host_query: Option<HostQueryFn>,
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
unsafe fn host_strdup(s: &str) -> *mut c_char {
|
||||
let alloc = HOST_ALLOC.expect("host alloc");
|
||||
let bytes = s.as_bytes();
|
||||
let p = alloc(bytes.len() + 1) as *mut u8;
|
||||
if p.is_null() {
|
||||
return ptr::null_mut();
|
||||
}
|
||||
std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len());
|
||||
*p.add(bytes.len()) = 0;
|
||||
p as *mut c_char
|
||||
}
|
||||
|
||||
fn set_out(out: *mut *mut c_char, s: &str) {
|
||||
if out.is_null() {
|
||||
return;
|
||||
}
|
||||
unsafe {
|
||||
*out = host_strdup(s);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_err(err: *mut *mut c_char, s: &str) {
|
||||
if err.is_null() {
|
||||
return;
|
||||
}
|
||||
unsafe {
|
||||
*err = host_strdup(s);
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_args(args_json: *const c_char) -> Result<Value, String> {
|
||||
if args_json.is_null() {
|
||||
return Ok(json!({}));
|
||||
}
|
||||
let s = unsafe { CStr::from_ptr(args_json) }
|
||||
.to_str()
|
||||
.map_err(|_| "args not utf-8".to_string())?;
|
||||
if s.trim().is_empty() {
|
||||
return Ok(json!({}));
|
||||
}
|
||||
serde_json::from_str(s).map_err(|e| format!("json: {e}"))
|
||||
}
|
||||
|
||||
fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
|
||||
args.get(key)
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| format!("missing `{key}`"))
|
||||
}
|
||||
|
||||
macro_rules! web_ffi {
|
||||
($name:ident, $body:expr, $label: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
|
||||
}
|
||||
Err(e) => {
|
||||
set_err(err_msg, &format!("{}: {e}", $label));
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
web_ffi!(
|
||||
web_render,
|
||||
|args: &Value| Ok(Value::String(page::render_page(args))),
|
||||
"web_render"
|
||||
);
|
||||
|
||||
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_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_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_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_listen,
|
||||
|args: &Value| http::listen(args),
|
||||
"web_listen"
|
||||
);
|
||||
|
||||
web_ffi!(
|
||||
web_db_migrate,
|
||||
|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 dir = args
|
||||
.get("dir")
|
||||
.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"
|
||||
);
|
||||
|
||||
fn register(host: &MarqdoHostApi, name: &str, params: &str, fn_ptr: PluginFn) -> c_int {
|
||||
let register = match host.register_fn {
|
||||
Some(f) => f,
|
||||
None => return 1,
|
||||
};
|
||||
let n = CString::new(name).unwrap();
|
||||
let p = CString::new(params).unwrap();
|
||||
unsafe { register(host.userdata, n.as_ptr(), p.as_ptr(), fn_ptr) }
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn marqdo_plugin_abi_version() -> u32 {
|
||||
ABI_VERSION
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int {
|
||||
if host.is_null() {
|
||||
return 1;
|
||||
}
|
||||
let host = &*host;
|
||||
HOST_ALLOC = host.alloc;
|
||||
HOST_FREE = host.free;
|
||||
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;
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,546 @@
|
||||
//! 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,627 @@
|
||||
//! 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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
/* 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