Resolve /_part against home or routed pages.

Stamp _route on app.route pages and emit {path}/_part/{id} slot sources so partials refresh the correct page.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-12 09:05:50 +08:00
1 parent b09538d242
commit 02b3dfab48
8 files changed
+137 -16

No files matched your search

+1 -1
View File
@@ -352,7 +352,7 @@ title: 站点
**英文:** `# app` · `## route` · `## listen` · 形参 `page` `db` `admin` `host` `port`
**中文:** `# 应用` · `## 路由` · `## 监听` · 形参 `页面` `数据库` `后台` `主机` `端口`
`listen` / `监听`:加载插件、注入 `db_url`、按页面 part 提供 `/_part/{id}`、启动 HTTP。作者不必手写 part 注册。
`listen` / `监听`:加载插件、注入 `db_url`、按页面 part 提供 `/_part/{id}`(首页)与 `{path}/_part/{id}`(`app.route` 页)、启动 HTTP。作者不必手写 part 注册。
### 5.5 表单 · `form` / `表单`(规划锁定)
+1 -1
View File
@@ -198,6 +198,6 @@ Register `GET|POST /_form/{id}` for listen when the form is not already embedded
## listen
Serve `/`, routed pages, `/_part/{id}`, `/_form/{id}` (from mounts + page embeds), and optional `/admin`.
Serve `/`, routed pages, `/_part/{id}` (home) and `{path}/_part/{id}` (routes), `/_form/{id}` (from mounts + page embeds), and optional `/admin`.
**> web_listen app=`self`**
+2
View File
@@ -188,4 +188,6 @@ description: 官方网站类(中文)。表格 + 方法;不写袋式胶水
## 监听
提供 `/`、路由页、首页 `/_part/{id}`、路由 `{路径}/_part/{id}`、`/_form/{id}`,以及可选 `/admin`。
**> web_listen app=`self`**
+32 -7
View File
@@ -74,7 +74,7 @@ pub fn listen(
let mut app = Router::new()
.route("/", get(home))
.route("/_part/{id}", get(part))
.route("/_part/{id}", get(home_part))
.route("/_form/{id}", get(form_get).post(form_post))
.route("/admin", get(admin_home))
.route("/admin/{table}", get(admin_table))
@@ -85,11 +85,13 @@ pub fn listen(
)
.route("/admin/{table}/{id}/delete", get(admin_delete));
// Register each author route as an exact GET path.
// Register each author route as an exact GET path + `{path}/_part/{id}`.
let mut paths: Vec<String> = routes.keys().cloned().collect();
paths.sort();
for path in paths {
app = app.route(&path, get(routed_page));
let part_path = format!("{path}/_part/{{id}}");
app = app.route(&part_path, get(routed_part));
}
let app = app.with_state(state);
@@ -127,15 +129,38 @@ async fn routed_page(State(st): State<Arc<AppState>>, uri: Uri) -> Response {
Html(render::render_page(page, st.db_url.as_deref())).into_response()
}
async fn part(State(st): State<Arc<AppState>>, Path(id): Path<String>) -> Response {
let Some(parts) = st.page.get("parts").and_then(|v| v.as_object()) else {
fn render_part_from_page(page: &Value, id: &str, db_url: Option<&str>) -> Response {
let Some(parts) = page.get("parts").and_then(|v| v.as_object()) else {
return Html(String::from("<p>no parts</p>")).into_response();
};
let Some(cfg) = parts.get(&id) else {
let Some(cfg) = parts.get(id) else {
return Html(format!("<p>unknown part {id}</p>")).into_response();
};
let html = render::render_fragment(cfg, st.db_url.as_deref());
Html(html).into_response()
Html(render::render_fragment(cfg, db_url)).into_response()
}
async fn home_part(State(st): State<Arc<AppState>>, Path(id): Path<String>) -> Response {
render_part_from_page(&st.page, &id, st.db_url.as_deref())
}
/// `{route}/_part/{id}` — resolve part against the page mounted at `route`.
async fn routed_part(
State(st): State<Arc<AppState>>,
uri: Uri,
Path(id): Path<String>,
) -> Response {
let full = uri.path();
let marker = format!("/_part/{id}");
let Some(page_path) = full.strip_suffix(&marker) else {
return Html(format!("<p>bad part path {}</p>", esc(full))).into_response();
};
if page_path.is_empty() || page_path == "/" {
return render_part_from_page(&st.page, &id, st.db_url.as_deref());
}
let Some(page) = st.routes.get(page_path) else {
return Html(format!("<p>404 not found: {}</p>", esc(page_path))).into_response();
};
render_part_from_page(page, &id, st.db_url.as_deref())
}
async fn form_get(State(st): State<Arc<AppState>>, Path(id): Path<String>) -> Response {
+5 -1
View File
@@ -378,10 +378,14 @@ fn normalize_route_path(raw: &str) -> Result<String, String> {
web_ffi!(web_app_route, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let path = normalize_route_path(arg_str(args, "path")?)?;
let page = args
let mut page = args
.get("page")
.cloned()
.ok_or_else(|| "missing `page` for route".to_string())?;
// Stamp mount path so render can emit `{path}/_part/{id}` slot sources.
if let Some(obj) = page.as_object_mut() {
obj.insert("_route".into(), json!(&path));
}
let obj = app
.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?;
+28 -6
View File
@@ -177,7 +177,25 @@ fn field_css(obj: &Map<String, Value>, field: &str) -> String {
.to_string()
}
fn slot_attrs(slot: &str, parts: &Map<String, Value>) -> String {
fn part_src_prefix(args: &Value) -> String {
match args.get("_route").and_then(|v| v.as_str()) {
Some(r) if !r.is_empty() && r != "/" => {
let mut p = r.to_string();
while p.len() > 1 && p.ends_with('/') {
p.pop();
}
if p.starts_with('/') {
p
} else {
format!("/{p}")
}
}
_ => String::new(),
}
}
fn slot_attrs(slot: &str, parts: &Map<String, Value>, page: &Value) -> String {
let prefix = part_src_prefix(page);
let mut a = format!(" data-slot=\"{}\"", esc(slot));
for (id, cfg) in parts {
let s = cfg
@@ -186,7 +204,11 @@ fn slot_attrs(slot: &str, parts: &Map<String, Value>) -> String {
.and_then(|v| v.as_str())
.unwrap_or("");
if s == slot || (slot == "sidebar" && id == "side") || (slot == "main" && id == "index") {
a.push_str(&format!(" data-slot-src=\"/_part/{}\"", esc(id)));
a.push_str(&format!(
" data-slot-src=\"{}/_part/{}\"",
esc(&prefix),
esc(id)
));
break;
}
}
@@ -324,22 +346,22 @@ pub fn render_page_ex(
</body></html>"#,
title = esc(title),
nav_class = slot_class(args, "nav", "topnav"),
nav_attrs = slot_attrs("nav", &parts),
nav_attrs = slot_attrs("nav", &parts, args),
nav_ul = render_ul(&nav, "nav"),
side_html = if has_side {
format!(
"<aside class=\"{}\"{}><span class=\"side-label\">侧栏</span>{}</aside>",
slot_class(args, "sidebar", "side"),
slot_attrs("sidebar", &parts),
slot_attrs("sidebar", &parts, args),
render_ul(&side, "side-nav")
)
} else {
String::new()
},
main_class = slot_class(args, "main", "main"),
main_attrs = slot_attrs("main", &parts),
main_attrs = slot_attrs("main", &parts, args),
foot_class = slot_class(args, "footer", "foot"),
foot_attrs = slot_attrs("footer", &parts),
foot_attrs = slot_attrs("footer", &parts, args),
foot_ul = render_ul(&foot, "foot-nav"),
)
}
+52
View File
@@ -0,0 +1,52 @@
---
title: web part smoke
description: Routed pages stamp _route and emit {path}/_part/{id} slot sources.
> ext/web/web.mq.md
> web-fixtures/components/nav.mq.md
> web-fixtures/components/side.mq.md
> web-fixtures/components/foot.mq.md
> lib/json.mq.md
---
# main
`layout` =
| 组件 | 样式 |
|------|------|
| nav.`nav` | |
| side.`side` | |
| foot.`foot` | |
*`home` = > web.page title="Home" intro="<h1>Home</h1>" *
*`home` = > `home`.compose_components components=`layout` *
*`about` = > web.page title="About" intro="<h1>About</h1>" *
*`about` = > `about`.compose_components components=`layout` *
*`app` = > web.app page=`home` host=127.0.0.1 port=18081 *
*`app` = > `app`.route path=/about page=`about` *
*`routes` = > json.get value=`app` key=routes *
*`routed` = > json.get value=`routes` key="/about" *
*`route` = > json.get value=`routed` key=_route *
1. `route` == "/about"
> print text=route-stamp-ok
2. *
> print text=route-stamp-fail
*`home_html` = > `home`.render *
*`home_chunks` = > split value=`home_html` sep=/_part/ *
*`hn` = > len value=`home_chunks` *
1. `hn` >= 2
> print text=home-part-ok
2. *
> print text=home-part-fail
*`about_html` = > `routed`.render *
*`about_chunks` = > split value=`about_html` sep=/about/_part/ *
*`an` = > len value=`about_chunks` *
1. `an` >= 2
> print text=route-part-ok
2. *
> print text=route-part-fail
+16
View File
@@ -1309,6 +1309,22 @@ render-ok",
);
}
#[test]
fn ext_web_part_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-part-smoke.mq.md",
"route-stamp-ok
home-part-ok
route-part-ok",
);
}
#[test]
fn ext_agent_framework_smoke() {
let status = Command::new("cargo")