diff --git a/CHANGELOG.md b/CHANGELOG.md index a13abaf..696bd77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,8 +3,10 @@ ## Unreleased ### Added +- **GAP-11**:`compose_form` / `表单装配` 支持 `target` / `表单插槽`(如 `#id`),把表单注入引言 HTML 内的挂载点,而不是始终作为 `.main-intro` 的兄弟节点。 ### Fixed +- **GAP-12**:`ext/…` import 解析失败且未设置 `MARQDO_EXT` 时,错误附带 `hint: set MARQDO_EXT to the directory that contains web/`。 ### Changed diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md index 28b7a35..5b99ca9 100644 --- a/ext/web/web.mq.md +++ b/ext/web/web.mq.md @@ -303,10 +303,11 @@ List pagination for the main bind: sets DB `limit`/`offset` and renders previous ## compose_form + `form` + `id` + + `target`=None -Embed a form into the page main slot. `listen` auto-registers `GET|POST /_form/{id}` from page/route forms (optional `app.mount_form`). +Embed a form into the page main slot. Optional `target` / `form_slot` (CSS id, e.g. `#qd-note-form-mount`) injects the form **inside** that element in `intro` HTML instead of a sibling `.site-form` after `.main-intro` (GAP-11). Missing mount falls back to sibling. `listen` auto-registers `GET|POST /_form/{id}` from page/route forms (optional `app.mount_form`). -**> web_compose_form page=`self` form=`form` id=`id`** +**> web_compose_form page=`self` form=`form` id=`id` target=`target`** ## render + `db`=None diff --git a/ext/web/网页.mq.md b/ext/web/网页.mq.md index 1b070f3..feb8b1a 100644 --- a/ext/web/网页.mq.md +++ b/ext/web/网页.mq.md @@ -285,10 +285,11 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c ## 表单装配 + `表单` + `id` + + `表单插槽`=None -将表单嵌入页面主区。`listen` 会从页面/路由上的表单自动挂载 `GET|POST /_form/{id}`(可选再 `挂载表单`)。 +将表单嵌入页面主区。可选 `表单插槽`(元素 id,如 `#qd-note-form-mount`):把表单注入引言 HTML 内该节点,而不是 `.main-intro` 后的兄弟 `.site-form`(GAP-11)。插槽缺失时回退为兄弟节点。`listen` 会从页面/路由上的表单自动挂载 `GET|POST /_form/{id}`(可选再 `挂载表单`)。 -**> web_compose_form page=`self` form=`表单` id=`id`** +**> web_compose_form page=`self` form=`表单` id=`id` target=`表单插槽`** ## 渲染 + `数据库`=None diff --git a/plugins/web/src/compose.rs b/plugins/web/src/compose.rs index 60571e0..c3fc609 100644 --- a/plugins/web/src/compose.rs +++ b/plugins/web/src/compose.rs @@ -184,7 +184,15 @@ pub fn compose_main( } /// 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 { +/// +/// Optional `form_target` (CSS id / `#id`) mounts the form **inside** intro HTML +/// at that element instead of appending a sibling `.site-form` (GAP-11). +pub fn compose_form( + page: &Value, + form: &Value, + form_id: &str, + form_target: Option<&str>, +) -> Result { let id = form_id.trim(); if id.is_empty() { return Err("compose_form requires non-empty `id`".into()); @@ -200,6 +208,15 @@ pub fn compose_form(page: &Value, form: &Value, form_id: &str) -> Result Result c_int ), ( "web_compose_form", - "page,form,id", + "page,form,id,target", web_compose_form as PluginFn, ), ("web_render", "page", web_render as PluginFn), diff --git a/plugins/web/src/render.rs b/plugins/web/src/render.rs index 63a3f07..36c9b21 100644 --- a/plugins/web/src/render.rs +++ b/plugins/web/src/render.rs @@ -40,6 +40,106 @@ fn is_simple_ident(s: &str) -> bool { .all(|c| c.is_ascii_alphanumeric() || c == '_' || !c.is_ascii()) } +/// Normalize a form mount selector to a bare HTML id (`#foo` → `foo`). +fn form_mount_id(target: &str) -> Option<&str> { + let t = target.trim().trim_start_matches('#'); + if t.is_empty() { + return None; + } + // Keep injection conservative: id must be a simple token (no spaces / quotes). + if t.chars().any(|c| c.is_whitespace() || c == '"' || c == '\'' || c == '<' || c == '>') { + return None; + } + Some(t) +} + +/// Inject `payload` as the inner HTML of the first element with `id="…"` / `id='…'`. +/// Returns `None` if no matching open+close pair is found (caller falls back to sibling form). +pub(crate) fn inject_html_into_id(haystack: &str, id: &str, payload: &str) -> Option { + let id = form_mount_id(id)?; + let patterns = [format!("id=\"{id}\""), format!("id='{id}'")]; + for pat in &patterns { + let Some(idx) = haystack.find(pat.as_str()) else { + continue; + }; + let tag_start = haystack[..idx].rfind('<')?; + // Reject closing tags / comments accidentally matching. + let after_lt = haystack.as_bytes().get(tag_start + 1).copied()?; + if after_lt == b'/' || after_lt == b'!' { + continue; + } + let name_end = haystack[tag_start + 1..] + .find(|c: char| c.is_whitespace() || c == '>' || c == '/') + .map(|i| tag_start + 1 + i) + .unwrap_or(idx); + let tag_name = haystack[tag_start + 1..name_end].trim(); + if tag_name.is_empty() { + continue; + } + let after_id = idx + pat.len(); + let open_gt = haystack[after_id..].find('>')? + after_id; + // Skip self-closing `
`. + if haystack.as_bytes().get(open_gt.saturating_sub(1)) == Some(&b'/') { + continue; + } + let close = format!(""); + // Case-insensitive close search for HTML friendliness. + let rest = &haystack[open_gt + 1..]; + let close_rel = rest + .to_ascii_lowercase() + .find(&close.to_ascii_lowercase())?; + let close_idx = open_gt + 1 + close_rel; + let mut out = String::with_capacity(haystack.len() + payload.len()); + out.push_str(&haystack[..open_gt + 1]); + out.push_str(payload); + out.push_str(&haystack[close_idx..]); + return Some(out); + } + None +} + +/// Append intro + optional form: either inject into `form_target` mount inside intro, or sibling. +fn push_intro_and_form( + buf: &mut String, + intro: &str, + args: &Value, + form_data: Option<&Value>, + form_errors: Option<&Value>, + csrf: Option<&str>, +) { + let form = args.get("form"); + let form_id = args + .get("form_id") + .and_then(|v| v.as_str()) + .unwrap_or("form"); + let target = args + .get("form_target") + .or_else(|| args.get("target")) + .or_else(|| args.get("form_slot")) + .or_else(|| args.get("表单插槽")) + .and_then(|v| v.as_str()) + .unwrap_or(""); + let form_html = form.map(|f| { + crate::form::render_body(f, form_id, form_data, form_errors, csrf) + }); + + if let Some(ref html) = form_html { + if !target.is_empty() && !intro.is_empty() { + if let Some(injected) = inject_html_into_id(intro, target, html) { + buf.push_str(&format!("
{injected}
")); + return; + } + } + } + + if !intro.is_empty() { + buf.push_str(&format!("
{intro}
")); + } + if let Some(html) = form_html { + buf.push_str(&html); + } +} + /// True when `back` is a DB field path (`table.col` / `mod.table.col`), not a URL or site path. fn is_db_bind_back(back: &str) -> bool { let s = normalize_ref(back); @@ -775,22 +875,14 @@ pub fn render_page_ex( main_html.push_str(images); } } - 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, - csrf, - )); - } + push_intro_and_form( + &mut main_html, + &intro, + args, + form_data, + form_errors, + csrf, + ); if !items.is_empty() { let is_detail = args .get("detail") @@ -905,16 +997,7 @@ pub fn render_fragment(args: &Value, db_url: Option<&str>) -> String { body.push_str(images); } } - 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, None)); - } + push_intro_and_form(&mut body, &intro, args, None, None, None); if !items.is_empty() { let is_detail = args .get("detail") @@ -1123,4 +1206,45 @@ mod nav_tests { assert!(html.contains("@media not (min-width: 900px)"), "{html}"); assert!(html.contains(">Home<"), "{html}"); } + + #[test] + fn inject_html_into_id_replaces_inner() { + let intro = r#"
L
"#; + let out = inject_html_into_id(intro, "#form-mount", "
x
") + .expect("inject"); + assert!(out.contains(r#"
x
"#), "{out}"); + assert!(out.contains(r#"
L
"#), "{out}"); + } + + #[test] + fn form_target_mounts_inside_intro() { + let page = json!({ + "title": "Compose", + "shell_css": "off", + "intro": "
A
", + "form_id": "note", + "form_target": "#qd-note-form-mount", + "form": { + "title": "note", + "show_meta": false, + "fields": [{"name": "title", "label": "Title", "type": "text"}] + } + }); + let html = render_page(&page, None, None); + assert_eq!(html.matches("class=\"site-form\"").count(), 1, "{html}"); + let mount_at = html.find("id=\"qd-note-form-mount\"").expect("mount"); + let form_at = html.find("class=\"site-form\"").expect("form"); + assert!(form_at > mount_at, "{html}"); + assert!( + html.contains("qd-note-form-mount\">
of main-intro. + let intro_end = html.find("class=\"main-intro\"").expect("intro") + + html[html.find("class=\"main-intro\"").unwrap()..] + .find("
") + .expect("intro close"); + // With injection, site-form is before the outer main-intro close — already asserted by adjacency. + let _ = intro_end; + } } diff --git a/src/load.rs b/src/load.rs index 14ae0d9..4c3c611 100644 --- a/src/load.rs +++ b/src/load.rs @@ -136,6 +136,16 @@ pub fn resolve_import(from_dir: &Path, rel: &str) -> Result { if let Some(p) = find_in_ancestor_dir(from_dir, "ext", rest) { return Ok(p); } + let mut msg = format!( + "cannot resolve import `{rel}` from {}", + from_dir.display() + ); + if env::var_os("MARQDO_EXT").is_none() { + msg.push_str( + "\nhint: set MARQDO_EXT to the directory that contains web/ (or run `marqdo ext add web`)", + ); + } + bail!("{msg}"); } // Relative again with normalize if direct.exists() { @@ -287,4 +297,29 @@ mod tests { let p2 = resolve_import(Path::new("tests/keywords"), "std/text.mq.md").unwrap(); assert!(p2.ends_with("text.mq.md")); } + + #[test] + fn resolve_ext_missing_hints_marqdo_ext() { + let prev = env::var_os("MARQDO_EXT"); + env::remove_var("MARQDO_EXT"); + // Unique path so cwd/ext cannot satisfy the import. + let err = resolve_import( + Path::new("/tmp"), + "ext/__gap12_missing__/nope.mq.md", + ) + .unwrap_err(); + let msg = format!("{err:#}"); + match prev { + Some(v) => env::set_var("MARQDO_EXT", v), + None => env::remove_var("MARQDO_EXT"), + } + assert!( + msg.contains("cannot resolve import `ext/__gap12_missing__/nope.mq.md`"), + "{msg}" + ); + assert!( + msg.contains("hint: set MARQDO_EXT to the directory that contains web/"), + "{msg}" + ); + } } diff --git a/tests/ext/web-form-slot-smoke.mq.md b/tests/ext/web-form-slot-smoke.mq.md new file mode 100644 index 0000000..2745009 --- /dev/null +++ b/tests/ext/web-form-slot-smoke.mq.md @@ -0,0 +1,43 @@ +--- +title: web form slot smoke +description: compose_form target= mounts form inside intro HTML (GAP-11). +import web:ext/web/web.mq.md +import json:lib/json.mq.md +import text:lib/text.mq.md +--- + +# main + +`fields` = + +| 字段 | 标签 | 类型 | 必填 | 默认 | +|------|------|------|------|------| +| title | Title | text | true | | + +*f = > web.form table="notes" action="insert"* +*f = > `f`.fields fields=`fields`* + +*intro = "
voice
"* +*page = > web.page title="Slot" intro=`intro`* +*page = > `page`.compose_form id="note" form=`f` target="#qd-note-form-mount"* + +*tgt = > json.get value=`page` key="form_target"* +1. `tgt` + > print text=target-ok +2. * + > print text=target-fail + +*html = > `page`.render* +*`has_mount` = > text.contains text=`html` sub="qd-note-form-mount"* +*`has_form` = > text.contains text=`html` sub="site-form"* +*`order_ok` = > text.contains text=`html` sub="qd-note-form-mount\">
print text=slot-ok + 2. * + > print text=slot-order-fail + 2. * + > print text=slot-form-fail +2. * + > print text=slot-mount-fail diff --git a/tests/gold.rs b/tests/gold.rs index c804c5b..3390b97 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -1710,6 +1710,21 @@ render-ok", ); } +#[test] +fn ext_web_form_slot_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-slot-smoke.mq.md", + "target-ok +slot-ok", + ); +} + #[test] fn ext_web_part_smoke() { let status = Command::new("cargo")