Embed forms in page main via compose_form.

listen collects forms from home and routed pages so mount_form is optional; validation errors re-render the owning page shell.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-12 09:02:37 +08:00
1 parent 0dcd9e3d03
commit b09538d242
13 files changed
+272 -40

No files matched your search

+2 -2
View File
@@ -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 文件职责
+1 -1
View File
@@ -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`.
+1 -1
View File
@@ -8,7 +8,7 @@ Static top links for the shell.
|------|-----|------|
| Home | / | |
| About | /about | |
| New | /_form/article | |
| New | /new | |
| Admin | /admin | |
**`nav`**
+8 -2
View File
@@ -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="<h1>New article</h1><p>Form lives in the main slot.</p>" *
*`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
+10 -2
View File
@@ -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`**
+8
View File
@@ -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
+44
View File
@@ -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<Value, String> {
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))
}
+51 -27
View File
@@ -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#"<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/>"#,
);
body.push_str(&format!("<title>{}</title>", esc(heading)));
body.push_str(
r#"<style>
body{font-family:"IBM Plex Sans","Noto Sans SC",sans-serif;margin:1.5rem;background:#fafaf9;color:#1c1917}
form{max-width:28rem;display:grid;gap:.85rem}
label{display:grid;gap:.25rem;font-size:.9rem}
input,textarea{padding:.5rem .6rem;border:1px solid #e7e5e4;border-radius:4px;font:inherit}
input[readonly]{background:#f5f5f4;color:#57534e}
.err{color:#b91c1c;font-size:.85rem}
.actions{display:flex;gap:.75rem;align-items:center;flex-wrap:wrap}
button{background:#0f766e;color:#fff;border:0;padding:.55rem 1rem;border-radius:4px;cursor:pointer}
a{color:#0f766e}
.meta{color:#57534e;font-size:.9rem}
</style></head><body>"#,
);
body.push_str(&format!(
"<h1>{}</h1><p class=\"meta\">table=<code>{}</code> · action=<code>{}</code></p>",
esc(heading),
esc(table),
esc(action)
));
let mut body = String::from("<div class=\"site-form\">");
if show_meta {
body.push_str(&format!(
"<p class=\"meta\">table=<code>{}</code> · action=<code>{}</code> · id=<code>{}</code></p>",
esc(table),
esc(action),
esc(heading)
));
}
body.push_str(&format!(
"<form method=\"post\" action=\"{}\">",
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!(
"<label>{}<input type=\"text\" value=\"{}\" readonly/></label>",
esc(label),
@@ -570,7 +564,37 @@ a{color:#0f766e}
"<div class=\"actions\"><button type=\"submit\">Submit</button><a href=\"{}\">cancel</a></div>",
esc(cancel)
));
body.push_str("</form></body></html>");
body.push_str("</form></div>");
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#"<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/>"#,
);
body.push_str(&format!("<title>{}</title>", esc(heading)));
body.push_str(
r#"<style>
body{font-family:"IBM Plex Sans","Noto Sans SC",sans-serif;margin:1.5rem;background:#fafaf9;color:#1c1917}
.site-form form{max-width:28rem;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 #e7e5e4;border-radius:4px;font:inherit}
.site-form input[readonly]{background:#f5f5f4;color:#57534e}
.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:#0f766e;color:#fff;border:0;padding:.55rem 1rem;border-radius:4px;cursor:pointer}
.site-form a{color:#0f766e}
.site-form .meta{color:#57534e;font-size:.9rem}
</style></head><body>"#,
);
body.push_str(&format!("<h1>{}</h1>", esc(heading)));
body.push_str(&render_body(form, form_id, data, errors));
body.push_str("</body></html>");
body
}
+46 -5
View File
@@ -22,23 +22,53 @@ struct AppState {
db_url: Option<String>,
admin: bool,
forms: HashMap<String, Value>,
/// Page that owns an embedded form (for re-render on validation errors).
form_owners: HashMap<String, Value>,
routes: HashMap<String, Value>,
}
fn collect_page_forms(
page: &Value,
forms: &mut HashMap<String, Value>,
owners: &mut HashMap<String, Value>,
) {
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<String, Value>,
mut forms: HashMap<String, Value>,
routes: HashMap<String, Value>,
) -> Result<Value, String> {
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("<p>no database</p>")).into_response();
};
submit_and_respond(frm, &id, url, posted)
submit_and_respond(&st, frm, &id, url, posted)
}
fn posted_to_value(posted: HashMap<String, String>) -> Value {
@@ -138,6 +168,7 @@ fn posted_to_value(posted: HashMap<String, String>) -> 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!("<p>submit error: {}</p>", 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!("<p>{}</p>", 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!("<p>{}</p>", esc(&e))).into_response(),
}
}
+15
View File
@@ -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),
+38
View File
@@ -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!("<div class=\"main-intro\">{intro}</div>"));
}
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("<section class=\"content cards\">");
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!("<div class=\"main-intro\">{intro}</div>"));
}
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("<section class=\"content cards\">");
for it in &items {
+33
View File
@@ -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="<h1>Compose</h1>" *
*`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
+15
View File
@@ -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")