diff --git a/doc/design/ext-web.md b/doc/design/ext-web.md index 278682b..e9028b2 100644 --- a/doc/design/ext-web.md +++ b/doc/design/ext-web.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Accepted · 实现中**(页面装配 / db CRUD / form §5.5 / admin schema 表单已落地) | +| 状态 | **Accepted · 实现中**(页面装配 / db CRUD / form §5.5 / 表单嵌入主区 / admin / `app.route` 已落地) | | 日期 | 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` / `网页`) | @@ -464,7 +464,7 @@ submit → action=insert → db.insert;action=update → db.update #### 5.5.4 与页面的关系 - 表单可以是独立路由页,或页面表里的一个「组件」导出(仍用 `|属性|值|样式|` 描述展示,提交走 form 类)。 -- 初版优先:**独立 form 句柄 + `app` 挂载提交端点**;嵌入页面槽位为随后波次。 +- **`page.compose_form id=… form=…`**:把 form 嵌入该页主区;`listen` 从首页与路由页收集表单并挂载 `/_form/{id}`(`app.mount_form` 仍可用)。校验失败时若表单有所属页,则带回该页壳重渲染。 ### 5.6 文件职责 diff --git a/examples/web-site/README.md b/examples/web-site/README.md index a0e24d5..c5de2d1 100644 --- a/examples/web-site/README.md +++ b/examples/web-site/README.md @@ -7,4 +7,4 @@ cargo build -p marqdo_plugin_web cargo run -- examples/web-site/index.mq.md ``` -Then open http://127.0.0.1:18081/ (admin at `/admin`). +Then open http://127.0.0.1:18081/ — `/about`, `/new` (form in page slot), `/admin`. diff --git a/examples/web-site/components/nav.mq.md b/examples/web-site/components/nav.mq.md index 7f157a6..6c0fbac 100644 --- a/examples/web-site/components/nav.mq.md +++ b/examples/web-site/components/nav.mq.md @@ -8,7 +8,7 @@ Static top links for the shell. |------|-----|------| | Home | / | | | About | /about | | -| New | /_form/article | | +| New | /new | | | Admin | /admin | | **`nav`** diff --git a/examples/web-site/index.mq.md b/examples/web-site/index.mq.md index 8bd34bf..3dd34ec 100644 --- a/examples/web-site/index.mq.md +++ b/examples/web-site/index.mq.md @@ -1,6 +1,6 @@ --- title: web-site -description: Home + /about route + form §5.5 + admin. +description: Home + /about + /new (form in page slot) + admin. > ext/web/web.mq.md > styles/shell.mq.md > components/nav.mq.md @@ -60,7 +60,13 @@ About page: same shell, different intro (no main bind). *`article_form` = > `article_form`.fields fields=`article_fields` * *`article_form` = > `article_form`.rules rules=`article_rules` * +New article: form embedded in the page main slot (design §5.5.4). + +*`new` = > web.page title="New article" intro="

New article

Form lives in the main slot.

" * +*`new` = > `new`.compose_components components=`home` * +*`new` = > `new`.compose_form id=article form=`article_form` * + *`app` = > web.app page=`page` db=`store` admin=True host=127.0.0.1 port=18081 * *`app` = > `app`.route path=/about page=`about` * -*`app` = > `app`.mount_form id=article form=`article_form` * +*`app` = > `app`.route path=/new page=`new` * > `app`.listen diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md index ce861c7..ec4e639 100644 --- a/ext/web/web.mq.md +++ b/ext/web/web.mq.md @@ -39,6 +39,14 @@ Assemble main from a bind table (`|属性|值|样式|` or `|front|back|css|`). **> web_compose_main page=`self` main=`main`** +## compose_form + + `form` + + `id` + +Embed a form into the page main slot. `listen` auto-registers `GET|POST /_form/{id}` from page/route forms (optional `app.mount_form`). + +**> web_compose_form page=`self` form=`form` id=`id`** + ## render + `db`=None @@ -184,12 +192,12 @@ Mount an assembled page at `path` (e.g. `/about`). `/` is the home `page=`. + `id` + `form` -Register `GET|POST /_form/{id}` for listen. +Register `GET|POST /_form/{id}` for listen when the form is not already embedded via `page.compose_form`. **> web_app_mount_form app=`self` id=`id` form=`form`** ## listen -Serve `/`, routed pages, `/_part/{id}`, `/_form/{id}`, and optional `/admin`. +Serve `/`, routed pages, `/_part/{id}`, `/_form/{id}` (from mounts + page embeds), and optional `/admin`. **> web_listen app=`self`** diff --git a/ext/web/网页.mq.md b/ext/web/网页.mq.md index b143c72..5595cb9 100644 --- a/ext/web/网页.mq.md +++ b/ext/web/网页.mq.md @@ -35,6 +35,14 @@ description: 官方网站类(中文)。表格 + 方法;不写袋式胶水 **> web_compose_main page=`self` main=`主体`** +## 表单装配 + + `表单` + + `id` + +将表单嵌入页面主区。`listen` 会从页面/路由上的表单自动挂载 `GET|POST /_form/{id}`(可选再 `挂载表单`)。 + +**> web_compose_form page=`self` form=`表单` id=`id`** + ## 渲染 + `数据库`=None diff --git a/plugins/web/src/compose.rs b/plugins/web/src/compose.rs index 022e031..811340c 100644 --- a/plugins/web/src/compose.rs +++ b/plugins/web/src/compose.rs @@ -178,3 +178,47 @@ pub fn compose_main( obj.insert("parts".into(), Value::Object(parts)); Ok(Value::Object(obj)) } + +/// Embed a form into the page main slot (`form_id` → POST `/_form/{id}`). +pub fn compose_form(page: &Value, form: &Value, form_id: &str) -> Result { + let id = form_id.trim(); + if id.is_empty() { + return Err("compose_form requires non-empty `id`".into()); + } + let mut obj = page.as_object().cloned().unwrap_or_default(); + let mut frm = form.clone(); + if let Some(m) = frm.as_object_mut() { + // Quieter meta when sitting inside a page shell. + m.entry("show_meta".to_string()).or_insert(json!(false)); + if !m.contains_key("title") { + m.insert("title".into(), json!(id)); + } + } + obj.insert("form_id".into(), json!(id)); + obj.insert("form".into(), frm.clone()); + let mut forms = obj + .get("forms") + .and_then(|v| v.as_object()) + .cloned() + .unwrap_or_default(); + forms.insert(id.to_string(), frm.clone()); + obj.insert("forms".into(), Value::Object(forms)); + + let mut parts = obj + .get("parts") + .and_then(|v| v.as_object()) + .cloned() + .unwrap_or_default(); + let mut part = Map::new(); + part.insert("_type".into(), json!("page")); + part.insert("slot".into(), json!("main")); + part.insert("fragment".into(), json!("main")); + part.insert("form_id".into(), json!(id)); + part.insert("form".into(), frm); + if let Some(intro) = obj.get("intro") { + part.insert("intro".into(), intro.clone()); + } + parts.insert(format!("form_{id}"), Value::Object(part)); + obj.insert("parts".into(), Value::Object(parts)); + Ok(Value::Object(obj)) +} diff --git a/plugins/web/src/form.rs b/plugins/web/src/form.rs index fabad3a..6975580 100644 --- a/plugins/web/src/form.rs +++ b/plugins/web/src/form.rs @@ -423,7 +423,13 @@ pub fn validate(form: &Value, extra_rules: Option<&Value>, data: &Value) -> Valu }) } -pub fn render(form: &Value, form_id: &str, data: Option<&Value>, errors: Option<&Value>) -> String { +/// Form markup only (no document shell) — for page main-slot embed and `/_form`. +pub fn render_body( + form: &Value, + form_id: &str, + data: Option<&Value>, + errors: Option<&Value>, +) -> String { let fields = form .get("fields") .and_then(|v| v.as_array()) @@ -466,31 +472,20 @@ pub fn render(form: &Value, form_id: &str, data: Option<&Value>, errors: Option< .and_then(|v| v.as_str()) .unwrap_or("/"); let row_id = form.get("id").map(cell_str).unwrap_or_default(); + let show_meta = form + .get("show_meta") + .and_then(|v| v.as_bool()) + .unwrap_or(true); - let mut body = String::from( - r#""#, - ); - body.push_str(&format!("{}", esc(heading))); - body.push_str( - r#""#, - ); - body.push_str(&format!( - "

{}

table={} · action={}

", - esc(heading), - esc(table), - esc(action) - )); + let mut body = String::from("
"); + if show_meta { + body.push_str(&format!( + "

table={} · action={} · id={}

", + esc(table), + esc(action), + esc(heading) + )); + } body.push_str(&format!( "
", esc(&post_to) @@ -520,7 +515,6 @@ a{color:#0f766e} }; let readonly = action == "update" && pk && name == "id"; if readonly { - // already emitted as hidden; show read-only label body.push_str(&format!( "", esc(label), @@ -570,7 +564,37 @@ a{color:#0f766e} "
cancel
", esc(cancel) )); - body.push_str("
"); + body.push_str("
"); + body +} + +/// Standalone form document (`GET|POST /_form/{id}`). +pub fn render(form: &Value, form_id: &str, data: Option<&Value>, errors: Option<&Value>) -> String { + let heading = form + .get("title") + .and_then(|v| v.as_str()) + .unwrap_or(form_id); + let mut body = String::from( + r#""#, + ); + body.push_str(&format!("{}", esc(heading))); + body.push_str( + r#""#, + ); + body.push_str(&format!("

{}

", esc(heading))); + body.push_str(&render_body(form, form_id, data, errors)); + body.push_str(""); body } diff --git a/plugins/web/src/http.rs b/plugins/web/src/http.rs index c10666d..623e1bb 100644 --- a/plugins/web/src/http.rs +++ b/plugins/web/src/http.rs @@ -22,23 +22,53 @@ struct AppState { db_url: Option, admin: bool, forms: HashMap, + /// Page that owns an embedded form (for re-render on validation errors). + form_owners: HashMap, routes: HashMap, } +fn collect_page_forms( + page: &Value, + forms: &mut HashMap, + owners: &mut HashMap, +) { + if let Some(obj) = page.get("forms").and_then(|v| v.as_object()) { + for (k, v) in obj { + forms.insert(k.clone(), v.clone()); + owners.insert(k.clone(), page.clone()); + } + } + if let (Some(id), Some(f)) = ( + page.get("form_id").and_then(|v| v.as_str()), + page.get("form"), + ) { + if !id.is_empty() { + forms.insert(id.to_string(), f.clone()); + owners.insert(id.to_string(), page.clone()); + } + } +} + pub fn listen( page: &Value, db_url: Option<&str>, host: &str, port: u16, admin: bool, - forms: HashMap, + mut forms: HashMap, routes: HashMap, ) -> Result { + let mut form_owners = HashMap::new(); + collect_page_forms(page, &mut forms, &mut form_owners); + for p in routes.values() { + collect_page_forms(p, &mut forms, &mut form_owners); + } let state = Arc::new(AppState { page: page.clone(), db_url: db_url.map(|s| s.to_string()), admin, forms, + form_owners, routes: routes.clone(), }); @@ -126,7 +156,7 @@ 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) + submit_and_respond(&st, frm, &id, url, posted) } fn posted_to_value(posted: HashMap) -> Value { @@ -138,6 +168,7 @@ fn posted_to_value(posted: HashMap) -> Value { } fn submit_and_respond( + st: &AppState, frm: &Value, form_id: &str, url: &str, @@ -154,7 +185,17 @@ fn submit_and_respond( } Ok(res) => { let errors = res.get("errors"); - Html(form::render(frm, form_id, Some(&data_v), errors)).into_response() + if let Some(page) = st.form_owners.get(form_id) { + Html(render::render_page_ex( + page, + st.db_url.as_deref(), + Some(&data_v), + errors, + )) + .into_response() + } else { + Html(form::render(frm, form_id, Some(&data_v), errors)).into_response() + } } Err(e) => Html(format!("

submit error: {}

", esc(&e))).into_response(), } @@ -305,7 +346,7 @@ async fn admin_new_post( } 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), + Ok(frm) => submit_and_respond(&st, &frm, &format!("admin-{table}-new"), url, posted), Err(e) => Html(format!("

{}

", esc(&e))).into_response(), } } @@ -347,7 +388,7 @@ async fn admin_edit_post( } 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), + Ok(frm) => submit_and_respond(&st, &frm, &format!("admin-{table}-edit"), url, posted), Err(e) => Html(format!("

{}

", esc(&e))).into_response(), } } diff --git a/plugins/web/src/lib.rs b/plugins/web/src/lib.rs index 36ac13c..8c68bd7 100644 --- a/plugins/web/src/lib.rs +++ b/plugins/web/src/lib.rs @@ -234,6 +234,16 @@ web_ffi!(web_compose_main, |args: &Value| { compose::compose_main(&page, &main, |path| call_lib(path)) }); +web_ffi!(web_compose_form, |args: &Value| { + let page = args.get("page").cloned().unwrap_or(json!({})); + let form = args + .get("form") + .cloned() + .ok_or_else(|| "missing `form`".to_string())?; + let id = arg_str(args, "id")?.to_string(); + compose::compose_form(&page, &form, &id) +}); + web_ffi!(web_render, |args: &Value| { let page = args.get("page").cloned().unwrap_or_else(|| args.clone()); let db_url = db_url_of(args).ok(); @@ -602,6 +612,11 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int web_compose_components as PluginFn, ), ("web_compose_main", "page,main", web_compose_main as PluginFn), + ( + "web_compose_form", + "page,form,id", + web_compose_form as PluginFn, + ), ("web_render", "page", web_render as PluginFn), ("web_db_new", "url", web_db_new as PluginFn), ("web_db_init", "url,name,fields", web_db_init as PluginFn), diff --git a/plugins/web/src/render.rs b/plugins/web/src/render.rs index 2100c61..e471c6c 100644 --- a/plugins/web/src/render.rs +++ b/plugins/web/src/render.rs @@ -224,9 +224,28 @@ a:hover { color:var(--accent); } .content.cards article { background:#fff; border:1px solid var(--line); border-radius:6px; padding:1rem; } .main-intro h1 { margin:0 0 .75rem; font-size:2rem; } .main-intro p { color:var(--muted); } +.site-form { margin-top:1.25rem; max-width:28rem; } +.site-form form { display:grid; gap:.85rem; } +.site-form label { display:grid; gap:.25rem; font-size:.9rem; } +.site-form input, .site-form textarea { padding:.5rem .6rem; border:1px solid var(--line); border-radius:4px; font:inherit; background:#fff; } +.site-form input[readonly] { background:#f5f5f4; color:var(--muted); } +.site-form .err { color:#b91c1c; font-size:.85rem; } +.site-form .actions { display:flex; gap:.75rem; align-items:center; flex-wrap:wrap; } +.site-form button { background:var(--accent); color:#fff; border:0; padding:.55rem 1rem; border-radius:4px; cursor:pointer; } +.site-form .meta { color:var(--muted); font-size:.9rem; } "#; pub fn render_page(args: &Value, db_url: Option<&str>) -> String { + render_page_ex(args, db_url, None, None) +} + +/// Like `render_page`, optionally replaying form POST data/errors into the embedded form. +pub fn render_page_ex( + args: &Value, + db_url: Option<&str>, + form_data: Option<&Value>, + form_errors: Option<&Value>, +) -> String { let title = args .get("title") .and_then(|v| v.as_str()) @@ -257,6 +276,18 @@ pub fn render_page(args: &Value, db_url: Option<&str>) -> String { if !intro.is_empty() { main_html.push_str(&format!("
{intro}
")); } + if let Some(form) = args.get("form") { + let form_id = args + .get("form_id") + .and_then(|v| v.as_str()) + .unwrap_or("form"); + main_html.push_str(&crate::form::render_body( + form, + form_id, + form_data, + form_errors, + )); + } if !items.is_empty() { main_html.push_str("
"); for it in &items { @@ -348,6 +379,13 @@ pub fn render_fragment(args: &Value, db_url: Option<&str>) -> String { if !intro.is_empty() { body.push_str(&format!("
{intro}
")); } + if let Some(form) = args.get("form") { + let form_id = args + .get("form_id") + .and_then(|v| v.as_str()) + .unwrap_or("form"); + body.push_str(&crate::form::render_body(form, form_id, None, None)); + } if !items.is_empty() { body.push_str("
"); for it in &items { diff --git a/tests/ext/web-form-embed-smoke.mq.md b/tests/ext/web-form-embed-smoke.mq.md new file mode 100644 index 0000000..81e4d05 --- /dev/null +++ b/tests/ext/web-form-embed-smoke.mq.md @@ -0,0 +1,33 @@ +--- +title: web form embed smoke +description: Offline page.compose_form embeds form in main HTML (no listen). +> ext/web/web.mq.md +> lib/json.mq.md +--- + +# main + +`fields` = + +| 字段 | 标签 | 类型 | 必填 | 默认 | +|------|------|------|------|------| +| title | Title | text | true | | +| body | Body | textarea | false | | + +*`f` = > web.form table=articles action=insert * +*`f` = > `f`.fields fields=`fields` * + +*`page` = > web.page title="Compose" intro="

Compose

" * +*`page` = > `page`.compose_form id=article form=`f` * + +*`fid` = > json.get value=`page` key=form_id * +1. `fid` + > print text=form-id-ok +2. * + > print text=form-id-fail + +*`html` = > `page`.render * +1. `html` + > print text=render-ok +2. * + > print text=render-fail diff --git a/tests/gold.rs b/tests/gold.rs index 3bb0634..3fd3d53 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -1294,6 +1294,21 @@ render-ok", ); } +#[test] +fn ext_web_form_embed_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-form-embed-smoke.mq.md", + "form-id-ok +render-ok", + ); +} + #[test] fn ext_agent_framework_smoke() { let status = Command::new("cargo")