diff --git a/doc/design/ext-web.md b/doc/design/ext-web.md index ff4da2b..278682b 100644 --- a/doc/design/ext-web.md +++ b/doc/design/ext-web.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Accepted · 实现中**(旧实现已清空,按本文从零开发) | +| 状态 | **Accepted · 实现中**(页面装配 / db CRUD / form §5.5 / admin schema 表单已落地) | | 日期 | 2026-08-11 | | 相关 | [markdown-mapping.md](markdown-mapping.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [stdlib-i18n.md](stdlib-i18n.md) | | 安装(目标) | `marqdo ext add web`(中英:`web` / `网页`) | diff --git a/ext/web/README.md b/ext/web/README.md index 9a9a2be..8eaa31a 100644 --- a/ext/web/README.md +++ b/ext/web/README.md @@ -18,9 +18,13 @@ Canonical sample (design §4): [`examples/web-site/`](../../examples/web-site/). ```bash cargo run -- run examples/web-site/index.mq.md -# http://127.0.0.1:18081/ · /admin +# http://127.0.0.1:18081/ +# /_form/article · /admin · /admin/articles/new ``` -Offline assemble smoke: `tests/ext/web-smoke.mq.md`. +Offline smokes: `tests/ext/web-smoke.mq.md`, `web-form-smoke.mq.md`, `web-admin-smoke.mq.md`. -**Form / validate / submit** (§5.5): field table + rules + `mount_form` → `GET|POST /_form/{id}`. +| Feature | Notes | +|---------|--------| +| Form §5.5 | field/rules tables · `validate` · `submit` · `mount_form` → `GET\|POST /_form/{id}` | +| Admin CRUD | `admin=True` · schema → same form path · new/edit/delete under `/admin/{table}` | \ No newline at end of file diff --git a/plugins/web/src/db.rs b/plugins/web/src/db.rs index 7756421..b3ef46b 100644 --- a/plugins/web/src/db.rs +++ b/plugins/web/src/db.rs @@ -286,3 +286,32 @@ pub fn list_tables(url: &str) -> Result, String> { .map_err(|e| e.to_string())?; Ok(rows) } + +#[derive(Debug, Clone)] +pub struct ColumnInfo { + pub name: String, + pub sql_type: String, + pub notnull: bool, + pub pk: bool, +} + +/// `PRAGMA table_info` → column metadata for admin forms. +pub fn table_info(url: &str, table: &str) -> Result, String> { + let table = ident(table)?; + let conn = open(url)?; + let sql = format!("PRAGMA table_info(\"{table}\")"); + let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?; + let rows = stmt + .query_map([], |r| { + Ok(ColumnInfo { + name: r.get::<_, String>(1)?, + sql_type: r.get::<_, String>(2).unwrap_or_else(|_| "TEXT".into()), + notnull: r.get::<_, i64>(3).unwrap_or(0) != 0, + pk: r.get::<_, i64>(5).unwrap_or(0) != 0, + }) + }) + .map_err(|e| e.to_string())? + .collect::, _>>() + .map_err(|e| e.to_string())?; + Ok(rows) +} diff --git a/plugins/web/src/form.rs b/plugins/web/src/form.rs index bb1c88c..fabad3a 100644 --- a/plugins/web/src/form.rs +++ b/plugins/web/src/form.rs @@ -175,6 +175,74 @@ pub fn form_new(table: Option<&str>, action: &str, id: Option<&str>) -> Value { Value::Object(m) } +fn sql_type_to_input(sql_type: &str, name: &str) -> &'static str { + let t = sql_type.to_ascii_uppercase(); + if t.contains("INT") || t.contains("REAL") || t.contains("FLOAT") || t.contains("DOUBLE") { + return "number"; + } + if name == "body" || name.ends_with("_body") || name.ends_with("_text") { + return "textarea"; + } + if name.contains("email") { + return "email"; + } + if name.contains("url") || name == "href" { + return "url"; + } + "text" +} + +/// Build a form handle from live SQLite schema (admin new/edit). +pub fn from_schema( + db_url: &str, + table: &str, + action: &str, + id: Option<&str>, +) -> Result { + let action = match action { + "update" | "更新" => "update", + _ => "insert", + }; + let cols = db::table_info(db_url, table)?; + if cols.is_empty() { + return Err(format!("unknown table `{table}`")); + } + let mut fields = Vec::new(); + for c in &cols { + if action == "insert" && c.pk && c.name == "id" { + continue; // SERIAL / AUTOINCREMENT + } + let input = sql_type_to_input(&c.sql_type, &c.name); + let required = c.notnull || (action == "update" && c.pk); + fields.push(json!({ + "name": c.name, + "label": c.name, + "type": input, + "required": required, + "default": "", + "pk": c.pk, + })); + } + let mut form = form_new(Some(table), action, id); + if let Some(obj) = form.as_object_mut() { + obj.insert("fields".into(), Value::Array(fields)); + obj.insert("redirect".into(), json!(format!("/admin/{table}"))); + if action == "insert" { + obj.insert("action_url".into(), json!(format!("/admin/{table}/new"))); + obj.insert("title".into(), json!(format!("New {table}"))); + } else if let Some(i) = id { + obj.insert( + "action_url".into(), + json!(format!("/admin/{table}/{i}/edit")), + ); + obj.insert("title".into(), json!(format!("Edit {table} #{i}"))); + obj.insert("id".into(), json!(i)); + } + obj.insert("cancel_href".into(), json!(format!("/admin/{table}"))); + } + Ok(form) +} + pub fn set_fields(form: &Value, fields: &Value) -> Value { let mut obj = form.as_object().cloned().unwrap_or_default(); obj.insert("fields".into(), as_form_fields(fields)); @@ -384,44 +452,82 @@ pub fn render(form: &Value, form_id: &str, data: Option<&Value>, errors: Option< .get("table") .and_then(|v| v.as_str()) .unwrap_or(""); + let heading = form + .get("title") + .and_then(|v| v.as_str()) + .unwrap_or(form_id); + let post_to = form + .get("action_url") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()) + .unwrap_or_else(|| format!("/_form/{form_id}")); + let cancel = form + .get("cancel_href") + .and_then(|v| v.as_str()) + .unwrap_or("/"); + let row_id = form.get("id").map(cell_str).unwrap_or_default(); let mut body = String::from( r#""#, ); - body.push_str(&format!("form {id}", id = esc(form_id))); + body.push_str(&format!("{}", esc(heading))); body.push_str( r#""#, ); body.push_str(&format!( "

{}

table={} · action={}

", - esc(form_id), + esc(heading), esc(table), esc(action) )); body.push_str(&format!( - "
", - esc(form_id) + "", + esc(&post_to) )); + if action == "update" && !row_id.is_empty() { + body.push_str(&format!( + "", + esc(&row_id) + )); + } for f in &fields { let name = f.get("name").and_then(|v| v.as_str()).unwrap_or(""); + if name.is_empty() { + continue; + } let label = f.get("label").and_then(|v| v.as_str()).unwrap_or(name); let ty = f.get("type").and_then(|v| v.as_str()).unwrap_or("text"); let required = f.get("required").and_then(|v| v.as_bool()).unwrap_or(false); let default = f.get("default").and_then(|v| v.as_str()).unwrap_or(""); + let pk = f.get("pk").and_then(|v| v.as_bool()).unwrap_or(false); let value = if data.contains_key(name) { field_text(&data, name) + } else if name == "id" && !row_id.is_empty() { + row_id.clone() } else { default.to_string() }; + let readonly = action == "update" && pk && name == "id"; + if readonly { + // already emitted as hidden; show read-only label + body.push_str(&format!( + "", + esc(label), + esc(&value) + )); + continue; + } let req_attr = if required { " required" } else { "" }; body.push_str(""); } - body.push_str( - "
home
", - ); + body.push_str(&format!( + "
cancel
", + esc(cancel) + )); body.push_str("
"); body } pub fn submit(form: &Value, data: &Value, db_url: &str) -> Result { - let v = validate(form, None, data); + let action = form + .get("action") + .and_then(|v| v.as_str()) + .unwrap_or("insert"); + let mut row_map = data_map(data); + if action == "update" { + if let Some(fid) = form.get("id").map(cell_str).filter(|s| !s.is_empty()) { + if !row_map.contains_key("id") { + row_map.insert("id".to_string(), json!(fid)); + } + } + } + let data = Value::Object(row_map.clone()); + let v = validate(form, None, &data); if !v.get("ok").and_then(|x| x.as_bool()).unwrap_or(false) { return Ok(json!({ "ok": false, @@ -479,17 +599,13 @@ pub fn submit(form: &Value, data: &Value, db_url: &str) -> Result .get("table") .and_then(|v| v.as_str()) .ok_or_else(|| "form missing `table`".to_string())?; - let action = form - .get("action") - .and_then(|v| v.as_str()) - .unwrap_or("insert"); - let row = Value::Object(data_map(data)); + let row = Value::Object(row_map); let result = if action == "update" { let id = form .get("id") .map(cell_str) .filter(|s| !s.is_empty()) - .or_else(|| data_map(data).get("id").map(cell_str)) + .or_else(|| data_map(&data).get("id").map(cell_str)) .ok_or_else(|| "update requires `id`".to_string())?; db::update(db_url, table, &id, &row)? } else { diff --git a/plugins/web/src/http.rs b/plugins/web/src/http.rs index 8139712..3f36f7a 100644 --- a/plugins/web/src/http.rs +++ b/plugins/web/src/http.rs @@ -1,4 +1,4 @@ -//! Blocking HTTP listen: page shell, `/_part/{id}`, `/_form/{id}`, optional `/admin`. +//! Blocking HTTP listen: page shell, `/_part/{id}`, `/_form/{id}`, `/admin` CRUD. use std::collections::HashMap; use std::net::SocketAddr; @@ -44,6 +44,12 @@ pub fn listen( .route("/_form/{id}", get(form_get).post(form_post)) .route("/admin", get(admin_home)) .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", get(admin_delete)) .with_state(state); let addr: SocketAddr = format!("{host}:{port}") @@ -97,11 +103,24 @@ async fn form_post( let Some(url) = st.db_url.as_deref() else { return Html(String::from("

no database

")).into_response(); }; + submit_and_respond(frm, &id, url, posted) +} + +fn posted_to_value(posted: HashMap) -> Value { let mut data = Map::new(); for (k, v) in posted { data.insert(k, json!(v)); } - let data_v = Value::Object(data); + Value::Object(data) +} + +fn submit_and_respond( + frm: &Value, + form_id: &str, + url: &str, + posted: HashMap, +) -> Response { + let data_v = posted_to_value(posted); match form::submit(frm, &data_v, url) { Ok(res) if res.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) => { let redirect = res @@ -112,44 +131,65 @@ async fn form_post( } Ok(res) => { let errors = res.get("errors"); - Html(form::render(frm, &id, Some(&data_v), errors)).into_response() + Html(form::render(frm, form_id, Some(&data_v), errors)).into_response() } Err(e) => Html(format!("

submit error: {}

", esc(&e))).into_response(), } } -async fn admin_home(State(st): State>) -> Response { +fn admin_gate(st: &AppState) -> Option { if !st.admin { - return Html(String::from("

admin disabled

")).into_response(); + return Some(Html(String::from("

admin disabled

")).into_response()); } - let Some(url) = st.db_url.as_deref() else { - return Html(String::from("

no database

")).into_response(); - }; + if st.db_url.is_none() { + return Some(Html(String::from("

no database

")).into_response()); + } + None +} + +fn admin_shell(title: &str, inner: &str) -> String { + format!( + r#"{title} +{inner}"#, + title = esc(title), + inner = inner + ) +} + +async fn admin_home(State(st): State>) -> Response { + if let Some(r) = admin_gate(&st) { + return r; + } + let url = st.db_url.as_deref().unwrap(); let tables = db::list_tables(url).unwrap_or_default(); - let mut body = String::from( - "admin", - ); - body.push_str("

admin

    "); + let mut inner = String::from("

    admin

    tables

      "); for t in &tables { - body.push_str(&format!("
    • {t}
    • ")); + inner.push_str(&format!("
    • {t}
    • ")); } + inner.push_str("
    "); if !st.forms.is_empty() { - body.push_str("

forms

    "); + inner.push_str("

    mounted forms

      "); for id in st.forms.keys() { - body.push_str(&format!("
    • {id}
    • ")); + inner.push_str(&format!("
    • {id}
    • ")); } + inner.push_str("
    "); } - body.push_str("

home

"); - Html(body).into_response() + Html(admin_shell("admin", &inner)).into_response() } async fn admin_table(State(st): State>, Path(table): Path) -> Response { - if !st.admin { - return Redirect::to("/").into_response(); + if let Some(r) = admin_gate(&st) { + return r; } - let Some(url) = st.db_url.as_deref() else { - return Html(String::from("

no database

")).into_response(); - }; + let url = st.db_url.as_deref().unwrap(); let Ok(data) = db::select(url, &table, 200) else { return Html(format!("

cannot read {table}

")).into_response(); }; @@ -158,24 +198,34 @@ async fn admin_table(State(st): State>, Path(table): Path) .and_then(|v| v.as_array()) .cloned() .unwrap_or_default(); - let mut body = format!( - "{table}" - ); - body.push_str(&format!( - "

{table}

back

" - )); - let cols: Vec = rows + let mut cols: Vec = rows .first() .and_then(|r| r.as_object()) .map(|m| m.keys().cloned().collect()) .unwrap_or_default(); - for c in &cols { - body.push_str(&format!("")); + if cols.is_empty() { + if let Ok(info) = db::table_info(url, &table) { + cols = info.into_iter().map(|c| c.name).collect(); + } } - body.push_str(""); + // prefer id first + if let Some(i) = cols.iter().position(|c| c == "id") { + let idc = cols.remove(i); + cols.insert(0, idc); + } + + let mut inner = format!("

{table}

"); + inner.push_str(&format!( + "" + )); + inner.push_str("
{c}
"); + for c in &cols { + inner.push_str(&format!("", esc(c))); + } + inner.push_str(""); for row in &rows { - body.push_str(""); let m = row.as_object().cloned().unwrap_or_else(Map::new); + inner.push_str(""); for c in &cols { let cell = m .get(c) @@ -185,12 +235,112 @@ async fn admin_table(State(st): State>, Path(table): Path) other => other.to_string(), }) .unwrap_or_default(); - body.push_str(&format!("", esc(&cell))); + inner.push_str(&format!("", esc(&cell))); } - body.push_str(""); + let id = m + .get("id") + .map(|v| match v { + Value::String(s) => s.clone(), + other => other.to_string(), + }) + .unwrap_or_default(); + if !id.is_empty() { + inner.push_str(&format!( + "" + )); + } else { + inner.push_str(""); + } + inner.push_str(""); } - body.push_str("
{}
{}{}
edit · delete
"); - Html(body).into_response() + if rows.is_empty() { + inner.push_str("(empty)"); + } + inner.push_str(""); + Html(admin_shell(&table, &inner)).into_response() +} + +async fn admin_new_get(State(st): State>, Path(table): Path) -> Response { + if let Some(r) = admin_gate(&st) { + return r; + } + let url = st.db_url.as_deref().unwrap(); + match form::from_schema(url, &table, "insert", None) { + Ok(frm) => Html(form::render(&frm, &format!("admin-{table}-new"), None, None)) + .into_response(), + Err(e) => Html(format!("

{}

", esc(&e))).into_response(), + } +} + +async fn admin_new_post( + State(st): State>, + Path(table): Path, + Form(posted): Form>, +) -> Response { + if let Some(r) = admin_gate(&st) { + return r; + } + let url = st.db_url.as_deref().unwrap(); + match form::from_schema(url, &table, "insert", None) { + Ok(frm) => submit_and_respond(&frm, &format!("admin-{table}-new"), url, posted), + Err(e) => Html(format!("

{}

", esc(&e))).into_response(), + } +} + +async fn admin_edit_get( + State(st): State>, + Path((table, id)): Path<(String, String)>, +) -> Response { + if let Some(r) = admin_gate(&st) { + return r; + } + let url = st.db_url.as_deref().unwrap(); + let row = match db::get(url, &table, &id) { + Ok(Value::Null) => { + return Html(format!("

row {id} not found

")).into_response(); + } + Ok(v) => v, + Err(e) => return Html(format!("

{}

", esc(&e))).into_response(), + }; + match form::from_schema(url, &table, "update", Some(&id)) { + Ok(frm) => Html(form::render( + &frm, + &format!("admin-{table}-edit"), + Some(&row), + None, + )) + .into_response(), + Err(e) => Html(format!("

{}

", esc(&e))).into_response(), + } +} + +async fn admin_edit_post( + State(st): State>, + Path((table, id)): Path<(String, String)>, + Form(posted): Form>, +) -> Response { + if let Some(r) = admin_gate(&st) { + return r; + } + let url = st.db_url.as_deref().unwrap(); + match form::from_schema(url, &table, "update", Some(&id)) { + Ok(frm) => submit_and_respond(&frm, &format!("admin-{table}-edit"), url, posted), + Err(e) => Html(format!("

{}

", esc(&e))).into_response(), + } +} + +async fn admin_delete( + State(st): State>, + Path((table, id)): Path<(String, String)>, +) -> Response { + if let Some(r) = admin_gate(&st) { + return r; + } + let url = st.db_url.as_deref().unwrap(); + if let Err(e) = db::delete(url, &table, &id) { + return Html(format!("

delete failed: {}

", esc(&e))).into_response(); + } + Redirect::to(&format!("/admin/{table}")).into_response() } fn esc(s: &str) -> String { diff --git a/plugins/web/src/lib.rs b/plugins/web/src/lib.rs index 0bc963c..703a2f1 100644 --- a/plugins/web/src/lib.rs +++ b/plugins/web/src/lib.rs @@ -411,6 +411,35 @@ web_ffi!(web_form_submit, |args: &Value| { form::submit(&form_v, &data, &url) }); +web_ffi!(web_form_from_schema, |args: &Value| { + let url = db_url_of(args)?; + let table = arg_str(args, "table")?.to_string(); + let action = arg_str_opt(args, "action").unwrap_or("insert"); + let id = match args.get("id") { + None | Some(Value::Null) => None, + Some(_) => Some(arg_text(args, "id")?), + }; + form::from_schema(&url, &table, action, id.as_deref()) +}); + +web_ffi!(web_db_table_info, |args: &Value| { + let url = db_url_of(args)?; + let table = arg_str(args, "table")?.to_string(); + let cols = db::table_info(&url, &table)?; + let arr: Vec = cols + .into_iter() + .map(|c| { + json!({ + "name": c.name, + "type": c.sql_type, + "notnull": c.notnull, + "pk": c.pk, + }) + }) + .collect(); + Ok(json!({ "columns": arr })) +}); + web_ffi!(web_listen, |args: &Value| { use std::collections::HashMap; let (page, db_url, host, port, admin, forms) = if args.get("page").is_some() @@ -532,6 +561,12 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int ), ("web_form_render", "form,id", web_form_render as PluginFn), ("web_form_submit", "form,data,url", web_form_submit as PluginFn), + ( + "web_form_from_schema", + "url,table,action", + web_form_from_schema as PluginFn, + ), + ("web_db_table_info", "url,table", web_db_table_info as PluginFn), ("web_listen", "app", web_listen as PluginFn), ]; for (name, params, f) in regs { diff --git a/tests/ext/web-admin-smoke.mq.md b/tests/ext/web-admin-smoke.mq.md new file mode 100644 index 0000000..90396f6 --- /dev/null +++ b/tests/ext/web-admin-smoke.mq.md @@ -0,0 +1,84 @@ +--- +title: web admin form-from-schema smoke +description: Schema-derived admin forms share validate/submit (offline). +> ext/web/web.mq.md +> web-fixtures/db/articles.mq.md as articles +> lib/json.mq.md +--- + +# main + +*`store` = > web.db url="sqlite:web-fixtures/data/admin-smoke.db" * +*`schema` = > articles.schema * +> `store`.init name=articles fields=`schema` +*`url` = > json.get value=`store` key=url * + +*`info` = > web_db_table_info url=`url` table=articles * +*`cols` = > json.get value=`info` key=columns * +*`n` = > len value=`cols` * +1. `n` >= 2 + > print text=schema-ok +2. * + > print text=schema-fail + +*`fnew` = > web_form_from_schema url=`url` table=articles action=insert * +*`fields` = > json.get value=`fnew` key=fields * +*`nf` = > len value=`fields` * +1. `nf` >= 1 + > print text=new-form-ok +2. * + > print text=new-form-fail + +`row` = + +| title | body | +|-------|------| +| Admin create | via schema form | + +*`sub` = > web_form_submit form=`fnew` data=`row` url=`url` * +*`sok` = > json.get value=`sub` key=ok * +1. `sok` + > print text=insert-ok +2. * + > print text=insert-fail + +*`got` = > `store`.get table=articles id=1 * +*`title` = > json.get value=`got` key=title * +1. `title` == "Admin create" + > print text=get-ok +2. * + > print text=get-fail + +*`fedit` = > web_form_from_schema url=`url` table=articles action=update id=1 * +`patch` = + +| title | body | +|-------|------| +| Admin edited | body updated | + +*`up` = > web_form_submit form=`fedit` data=`patch` url=`url` * +*`uok` = > json.get value=`up` key=ok * +1. `uok` + > print text=update-ok +2. * + > print text=update-fail + +*`got2` = > `store`.get table=articles id=1 * +*`title2` = > json.get value=`got2` key=title * +1. `title2` == "Admin edited" + > print text=edit-ok +2. * + > print text=edit-fail + +`empty` = + +| title | body | +|-------|------| +| | | + +*`bad` = > web_form_submit form=`fnew` data=`empty` url=`url` * +*`bok` = > json.get value=`bad` key=ok * +1. `bok` + > print text=required-should-fail +2. * + > print text=required-ok diff --git a/tests/gold.rs b/tests/gold.rs index b74bbd4..2c8bdc7 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -1258,6 +1258,26 @@ render-ok", ); } +#[test] +fn ext_web_admin_smoke() { + let status = Command::new("cargo") + .args(["build", "-p", "marqdo_plugin_web"]) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .status() + .expect("build web plugin"); + assert!(status.success(), "failed to build marqdo_plugin_web"); + assert_out( + "tests/ext/web-admin-smoke.mq.md", + "schema-ok +new-form-ok +insert-ok +get-ok +update-ok +edit-ok +required-ok", + ); +} + #[test] fn ext_agent_framework_smoke() { let status = Command::new("cargo")