fix: GAP-11 form slot mount and GAP-12 MARQDO_EXT import hint
compose_form/表单装配 can inject into intro via target/表单插槽; unresolved ext/ imports hint to set MARQDO_EXT when unset. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
cf9d96477b
commit
fb6254e501
9 files changed
+278
-33
No files matched your search
@@ -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
|
||||
|
||||
|
||||
+3
-2
@@ -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
|
||||
|
||||
+3
-2
@@ -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
|
||||
|
||||
@@ -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<Value, String> {
|
||||
///
|
||||
/// 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<Value, String> {
|
||||
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<Value,
|
||||
}
|
||||
obj.insert("form_id".into(), json!(id));
|
||||
obj.insert("form".into(), frm.clone());
|
||||
let target = form_target
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.to_string());
|
||||
if let Some(ref t) = target {
|
||||
obj.insert("form_target".into(), json!(t));
|
||||
} else {
|
||||
obj.remove("form_target");
|
||||
}
|
||||
let mut forms = obj
|
||||
.get("forms")
|
||||
.and_then(|v| v.as_object())
|
||||
@@ -219,6 +236,9 @@ pub fn compose_form(page: &Value, form: &Value, form_id: &str) -> Result<Value,
|
||||
part.insert("fragment".into(), json!("main"));
|
||||
part.insert("form_id".into(), json!(id));
|
||||
part.insert("form".into(), frm);
|
||||
if let Some(ref t) = target {
|
||||
part.insert("form_target".into(), json!(t));
|
||||
}
|
||||
if let Some(intro) = obj.get("intro") {
|
||||
part.insert("intro".into(), intro.clone());
|
||||
}
|
||||
|
||||
@@ -813,7 +813,11 @@ web_ffi!(web_compose_form, |args: &Value| {
|
||||
.cloned()
|
||||
.ok_or_else(|| "missing `form`".to_string())?;
|
||||
let id = arg_str(args, "id")?.to_string();
|
||||
compose::compose_form(&page, &form, &id)
|
||||
let target = arg_str_opt(args, "target")
|
||||
.or_else(|| arg_str_opt(args, "form_target"))
|
||||
.or_else(|| arg_str_opt(args, "form_slot"))
|
||||
.or_else(|| arg_str_opt(args, "表单插槽"));
|
||||
compose::compose_form(&page, &form, &id, target)
|
||||
});
|
||||
|
||||
web_ffi!(web_render, |args: &Value| {
|
||||
@@ -2515,7 +2519,7 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
|
||||
),
|
||||
(
|
||||
"web_compose_form",
|
||||
"page,form,id",
|
||||
"page,form,id,target",
|
||||
web_compose_form as PluginFn,
|
||||
),
|
||||
("web_render", "page", web_render as PluginFn),
|
||||
|
||||
+150
-26
@@ -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<String> {
|
||||
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 `<div id="x" />`.
|
||||
if haystack.as_bytes().get(open_gt.saturating_sub(1)) == Some(&b'/') {
|
||||
continue;
|
||||
}
|
||||
let close = format!("</{tag_name}>");
|
||||
// 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!("<div class=\"main-intro\">{injected}</div>"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !intro.is_empty() {
|
||||
buf.push_str(&format!("<div class=\"main-intro\">{intro}</div>"));
|
||||
}
|
||||
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!("<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,
|
||||
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!("<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, 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#"<div class="cols"><div id="left">L</div><div id="form-mount"></div></div>"#;
|
||||
let out = inject_html_into_id(intro, "#form-mount", "<form class=\"site-form\">x</form>")
|
||||
.expect("inject");
|
||||
assert!(out.contains(r#"<div id="form-mount"><form class="site-form">x</form></div>"#), "{out}");
|
||||
assert!(out.contains(r#"<div id="left">L</div>"#), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn form_target_mounts_inside_intro() {
|
||||
let page = json!({
|
||||
"title": "Compose",
|
||||
"shell_css": "off",
|
||||
"intro": "<div class=\"cols\"><div id=\"a\">A</div><div id=\"qd-note-form-mount\"></div></div>",
|
||||
"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\"><div class=\"site-form\""),
|
||||
"{html}"
|
||||
);
|
||||
// Sibling fallback would place site-form after </div></div> of main-intro.
|
||||
let intro_end = html.find("class=\"main-intro\"").expect("intro")
|
||||
+ html[html.find("class=\"main-intro\"").unwrap()..]
|
||||
.find("</div>")
|
||||
.expect("intro close");
|
||||
// With injection, site-form is before the outer main-intro close — already asserted by adjacency.
|
||||
let _ = intro_end;
|
||||
}
|
||||
}
|
||||
+35
@@ -136,6 +136,16 @@ pub fn resolve_import(from_dir: &Path, rel: &str) -> Result<PathBuf> {
|
||||
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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 = "<div class=\"cols\"><section id=\"left\">voice</section><div id=\"qd-note-form-mount\"></div></div>"*
|
||||
*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\"><div class=\"site-form\""*
|
||||
1. `has_mount`
|
||||
1. `has_form`
|
||||
1. `order_ok`
|
||||
> print text=slot-ok
|
||||
2. *
|
||||
> print text=slot-order-fail
|
||||
2. *
|
||||
> print text=slot-form-fail
|
||||
2. *
|
||||
> print text=slot-mount-fail
|
||||
@@ -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")
|
||||
|
||||
Reference in new issue
Block a user