Add app.route for mounting extra pages by path.
Register GET routes from assembled pages; sample /about + offline smoke. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
897db76aa7
commit
0dcd9e3d03
9 files changed
+172
-15
No files matched your search
@@ -7,6 +7,7 @@ Static top links for the shell.
|
||||
| 属性 | 值 | 样式 |
|
||||
|------|-----|------|
|
||||
| Home | / | |
|
||||
| About | /about | |
|
||||
| New | /_form/article | |
|
||||
| Admin | /admin | |
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: web-site
|
||||
description: Home = page table; main inline; class methods assemble; form §5.5.
|
||||
description: Home + /about route + form §5.5 + admin.
|
||||
> ext/web/web.mq.md
|
||||
> styles/shell.mq.md
|
||||
> components/nav.mq.md
|
||||
@@ -51,10 +51,16 @@ Article create form (design §5.5): field table + rules table.
|
||||
*`page` = > `page`.compose_components components=`home` *
|
||||
*`page` = > `page`.compose_main main=`index` *
|
||||
|
||||
About page: same shell, different intro (no main bind).
|
||||
|
||||
*`about` = > web.page title="About" intro="<h1>About</h1><p>Marqdo web = tables + class methods.</p>" *
|
||||
*`about` = > `about`.compose_components components=`home` *
|
||||
|
||||
*`article_form` = > web.form table=articles action=insert *
|
||||
*`article_form` = > `article_form`.fields fields=`article_fields` *
|
||||
*`article_form` = > `article_form`.rules rules=`article_rules` *
|
||||
|
||||
*`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`.listen
|
||||
+2
-1
@@ -27,4 +27,5 @@ Offline smokes: `tests/ext/web-smoke.mq.md`, `web-form-smoke.mq.md`, `web-admin-
|
||||
| Feature | Notes |
|
||||
|---------|--------|
|
||||
| Form §5.5 | field/rules tables · `validate` · `submit` · `mount_form` → `GET\|POST /_form/{id}` |
|
||||
| Admin CRUD | `admin=True` · schema → same form path · new/edit/delete under `/admin/{table}` |
|
||||
| Admin CRUD | `admin=True` · schema → same form path · new/edit/delete under `/admin/{table}` |
|
||||
| Route | `` `app`.route path=/about page=`about` `` → `GET /about` |
|
||||
+5
-3
@@ -174,9 +174,11 @@ Field table + rules table; submit writes through `# db`.
|
||||
|
||||
## route
|
||||
+ `path`
|
||||
+ `page`=None
|
||||
+ `page`
|
||||
|
||||
**`self`**
|
||||
Mount an assembled page at `path` (e.g. `/about`). `/` is the home `page=`.
|
||||
|
||||
**> web_app_route app=`self` path=`path` page=`page`**
|
||||
|
||||
## mount_form
|
||||
+ `id`
|
||||
@@ -188,6 +190,6 @@ Register `GET|POST /_form/{id}` for listen.
|
||||
|
||||
## listen
|
||||
|
||||
Serve `/`, `/_part/{id}`, `/_form/{id}`, and optional `/admin`.
|
||||
Serve `/`, routed pages, `/_part/{id}`, `/_form/{id}`, and optional `/admin`.
|
||||
|
||||
**> web_listen app=`self`**
|
||||
+4
-2
@@ -166,9 +166,11 @@ description: 官方网站类(中文)。表格 + 方法;不写袋式胶水
|
||||
|
||||
## 路由
|
||||
+ `路径`
|
||||
+ `页面`=None
|
||||
+ `页面`
|
||||
|
||||
**`self`**
|
||||
将已装配页面挂到 `路径`(如 `/about`)。`/` 由首页 `页面=` 提供。
|
||||
|
||||
**> web_app_route app=`self` path=`路径` page=`页面`**
|
||||
|
||||
## 挂载表单
|
||||
+ `id`
|
||||
|
||||
+26
-3
@@ -5,6 +5,7 @@ use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Form, Path, State};
|
||||
use axum::http::Uri;
|
||||
use axum::response::{Html, IntoResponse, Redirect, Response};
|
||||
use axum::routing::get;
|
||||
use axum::Router;
|
||||
@@ -21,6 +22,7 @@ struct AppState {
|
||||
db_url: Option<String>,
|
||||
admin: bool,
|
||||
forms: HashMap<String, Value>,
|
||||
routes: HashMap<String, Value>,
|
||||
}
|
||||
|
||||
pub fn listen(
|
||||
@@ -30,15 +32,17 @@ pub fn listen(
|
||||
port: u16,
|
||||
admin: bool,
|
||||
forms: HashMap<String, Value>,
|
||||
routes: HashMap<String, Value>,
|
||||
) -> Result<Value, String> {
|
||||
let state = Arc::new(AppState {
|
||||
page: page.clone(),
|
||||
db_url: db_url.map(|s| s.to_string()),
|
||||
admin,
|
||||
forms,
|
||||
routes: routes.clone(),
|
||||
});
|
||||
|
||||
let app = Router::new()
|
||||
let mut app = Router::new()
|
||||
.route("/", get(home))
|
||||
.route("/_part/{id}", get(part))
|
||||
.route("/_form/{id}", get(form_get).post(form_post))
|
||||
@@ -49,8 +53,16 @@ pub fn listen(
|
||||
"/admin/{table}/{id}/edit",
|
||||
get(admin_edit_get).post(admin_edit_post),
|
||||
)
|
||||
.route("/admin/{table}/{id}/delete", get(admin_delete))
|
||||
.with_state(state);
|
||||
.route("/admin/{table}/{id}/delete", get(admin_delete));
|
||||
|
||||
// Register each author route as an exact GET path.
|
||||
let mut paths: Vec<String> = routes.keys().cloned().collect();
|
||||
paths.sort();
|
||||
for path in paths {
|
||||
app = app.route(&path, get(routed_page));
|
||||
}
|
||||
|
||||
let app = app.with_state(state);
|
||||
|
||||
let addr: SocketAddr = format!("{host}:{port}")
|
||||
.parse()
|
||||
@@ -74,6 +86,17 @@ async fn home(State(st): State<Arc<AppState>>) -> Html<String> {
|
||||
Html(html)
|
||||
}
|
||||
|
||||
async fn routed_page(State(st): State<Arc<AppState>>, uri: Uri) -> Response {
|
||||
let mut path = uri.path().to_string();
|
||||
while path.len() > 1 && path.ends_with('/') {
|
||||
path.pop();
|
||||
}
|
||||
let Some(page) = st.routes.get(&path) else {
|
||||
return Html(format!("<p>404 not found: {}</p>", esc(&path))).into_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 {
|
||||
return Html(String::from("<p>no parts</p>")).into_response();
|
||||
|
||||
+77
-5
@@ -332,9 +332,59 @@ web_ffi!(web_app_new, |args: &Value| {
|
||||
"port": port,
|
||||
"admin": admin,
|
||||
"forms": {},
|
||||
"routes": {},
|
||||
}))
|
||||
});
|
||||
|
||||
fn normalize_route_path(raw: &str) -> Result<String, String> {
|
||||
let s = raw.trim();
|
||||
if s.is_empty() {
|
||||
return Err("route path is empty".into());
|
||||
}
|
||||
if s == "/" {
|
||||
return Err("route path `/` is reserved for the home page".into());
|
||||
}
|
||||
let mut path = if s.starts_with('/') {
|
||||
s.to_string()
|
||||
} else {
|
||||
format!("/{s}")
|
||||
};
|
||||
while path.len() > 1 && path.ends_with('/') {
|
||||
path.pop();
|
||||
}
|
||||
// reserved prefixes
|
||||
if path == "/admin"
|
||||
|| path.starts_with("/admin/")
|
||||
|| path == "/_form"
|
||||
|| path.starts_with("/_form/")
|
||||
|| path == "/_part"
|
||||
|| path.starts_with("/_part/")
|
||||
{
|
||||
return Err(format!("route path `{path}` is reserved"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
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
|
||||
.get("page")
|
||||
.cloned()
|
||||
.ok_or_else(|| "missing `page` for route".to_string())?;
|
||||
let obj = app
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| "app must be a map".to_string())?;
|
||||
let routes = obj
|
||||
.entry("routes".to_string())
|
||||
.or_insert_with(|| json!({}));
|
||||
let rmap = routes
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| "app.routes must be a map".to_string())?;
|
||||
rmap.insert(path, page);
|
||||
Ok(app)
|
||||
});
|
||||
|
||||
web_ffi!(web_app_mount_form, |args: &Value| {
|
||||
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
||||
let id = arg_str(args, "id")?.to_string();
|
||||
@@ -442,7 +492,7 @@ web_ffi!(web_db_table_info, |args: &Value| {
|
||||
|
||||
web_ffi!(web_listen, |args: &Value| {
|
||||
use std::collections::HashMap;
|
||||
let (page, db_url, host, port, admin, forms) = if args.get("page").is_some()
|
||||
let (page, db_url, host, port, admin, forms, routes) = if args.get("page").is_some()
|
||||
|| args.get("host").is_some()
|
||||
{
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
@@ -456,8 +506,15 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
Some(Value::Bool(b)) => *b,
|
||||
_ => false,
|
||||
};
|
||||
let forms = HashMap::new();
|
||||
(page, db_url, host.to_string(), port, admin, forms)
|
||||
(
|
||||
page,
|
||||
db_url,
|
||||
host.to_string(),
|
||||
port,
|
||||
admin,
|
||||
HashMap::new(),
|
||||
HashMap::new(),
|
||||
)
|
||||
} else {
|
||||
let app = args.get("app").cloned().unwrap_or_else(|| args.clone());
|
||||
let page = app.get("page").cloned().unwrap_or(json!({}));
|
||||
@@ -486,9 +543,23 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
forms.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
(page, db_url, host, port, admin, forms)
|
||||
let mut routes = HashMap::new();
|
||||
if let Some(obj) = app.get("routes").and_then(|v| v.as_object()) {
|
||||
for (k, v) in obj {
|
||||
routes.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
(page, db_url, host, port, admin, forms, routes)
|
||||
};
|
||||
http::listen(&page, db_url.as_deref(), &host, port, admin, forms)
|
||||
http::listen(
|
||||
&page,
|
||||
db_url.as_deref(),
|
||||
&host,
|
||||
port,
|
||||
admin,
|
||||
forms,
|
||||
routes,
|
||||
)
|
||||
});
|
||||
|
||||
fn register(host: &MarqdoHostApi, name: &str, params: &str, fn_ptr: PluginFn) -> c_int {
|
||||
@@ -546,6 +617,7 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
|
||||
"page,db,admin,host,port",
|
||||
web_app_new as PluginFn,
|
||||
),
|
||||
("web_app_route", "app,path,page", web_app_route as PluginFn),
|
||||
(
|
||||
"web_app_mount_form",
|
||||
"app,id,form",
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
---
|
||||
title: web route smoke
|
||||
description: Offline app.route registration (no listen).
|
||||
> ext/web/web.mq.md
|
||||
> lib/json.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*`home` = > web.page title="Home" intro="<h1>Home</h1>" *
|
||||
*`about` = > web.page title="About" intro="<h1>About</h1>" *
|
||||
*`app` = > web.app page=`home` host=127.0.0.1 port=18081 *
|
||||
*`app` = > `app`.route path=/about page=`about` *
|
||||
*`app` = > `app`.route path=docs page=`about` *
|
||||
|
||||
*`routes` = > json.get value=`app` key=routes *
|
||||
*`about_page` = > json.get value=`routes` key="/about" *
|
||||
*`docs_page` = > json.get value=`routes` key="/docs" *
|
||||
|
||||
1. `about_page`
|
||||
> print text=about-ok
|
||||
2. *
|
||||
> print text=about-fail
|
||||
|
||||
1. `docs_page`
|
||||
> print text=docs-ok
|
||||
2. *
|
||||
> print text=docs-fail
|
||||
|
||||
*`html` = > `about`.render *
|
||||
1. `html`
|
||||
> print text=render-ok
|
||||
2. *
|
||||
> print text=render-fail
|
||||
@@ -1278,6 +1278,22 @@ required-ok",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_web_route_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-route-smoke.mq.md",
|
||||
"about-ok
|
||||
docs-ok
|
||||
render-ok",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_agent_framework_smoke() {
|
||||
let status = Command::new("cargo")
|
||||
|
||||
Reference in new issue
Block a user