From db6158e9e2c405e2ee494c1f33c9f398eec53be9 Mon Sep 17 00:00:00 2001 From: cflmy Date: Wed, 12 Aug 2026 09:26:30 +0800 Subject: [PATCH] Polish admin UI and add app.static file serving. Admin gets a sidebar shell, flash messages, empty states, and forms in-chrome; listen can nest a public directory under /static (or a custom mount). Co-authored-by: Cursor --- Cargo.lock | 62 ++++ doc/design/ext-web.md | 17 +- examples/web-site-zh/README.md | 2 +- examples/web-site-zh/index.mq.md | 1 + examples/web-site-zh/public/site.css | 5 + examples/web-site/README.md | 2 +- examples/web-site/index.mq.md | 1 + examples/web-site/public/site.css | 5 + ext/web/web.mq.md | 10 +- ext/web/网页.mq.md | 10 +- plugins/web/Cargo.toml | 1 + plugins/web/src/http.rs | 457 +++++++++++++++++++----- plugins/web/src/lib.rs | 79 +++- tests/ext/web-fixtures/public/hello.txt | 1 + tests/ext/web-static-smoke.mq.md | 31 ++ tests/gold.rs | 16 + 16 files changed, 605 insertions(+), 95 deletions(-) create mode 100644 examples/web-site-zh/public/site.css create mode 100644 examples/web-site/public/site.css create mode 100644 tests/ext/web-fixtures/public/hello.txt create mode 100644 tests/ext/web-static-smoke.mq.md diff --git a/Cargo.lock b/Cargo.lock index b182427..60a1738 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -391,6 +391,12 @@ version = "0.3.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7" +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + [[package]] name = "futures-task" version = "0.3.33" @@ -486,6 +492,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "http-range-header" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c" + [[package]] name = "httparse" version = "1.10.1" @@ -708,6 +720,7 @@ dependencies = [ "serde", "serde_json", "tokio", + "tower-http", ] [[package]] @@ -728,6 +741,16 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -1173,6 +1196,7 @@ version = "1.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" dependencies = [ + "bytes", "libc", "mio", "pin-project-lite", @@ -1193,6 +1217,19 @@ dependencies = [ "syn 3.0.3", ] +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + [[package]] name = "tower" version = "0.5.3" @@ -1209,6 +1246,31 @@ dependencies = [ "tracing", ] +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "http-range-header", + "httpdate", + "mime", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "tokio", + "tokio-util", + "tower-layer", + "tower-service", +] + [[package]] name = "tower-layer" version = "0.3.3" diff --git a/doc/design/ext-web.md b/doc/design/ext-web.md index a794406..5f2f708 100644 --- a/doc/design/ext-web.md +++ b/doc/design/ext-web.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Accepted · 实现中**(页面装配 / db CRUD+`select where` / form §5.5 / 表单嵌入 / admin / `app.route` / 路由 `/_part` 已落地) | +| 状态 | **Accepted · 完成**(SQLite 作者面:页面装配 / db CRUD+`where` / form / 嵌入主区 / `app.route` / 路由 `/_part` / admin UI / `app.static`;Postgres 等见 §9) | | 日期 | 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` / `网页`) | @@ -349,10 +349,12 @@ title: 站点 ### 5.4 应用 · `app` / `应用` -**英文:** `# app` · `## route` · `## listen` · 形参 `page` `db` `admin` `host` `port` -**中文:** `# 应用` · `## 路由` · `## 监听` · 形参 `页面` `数据库` `后台` `主机` `端口` +**英文:** `# app` · `## route` · `## static` · `## listen` · 形参 `page` `db` `admin` `host` `port` +**中文:** `# 应用` · `## 路由` · `## 静态` · `## 监听` · 形参 `页面` `数据库` `后台` `主机` `端口` -`listen` / `监听`:加载插件、注入 `db_url`、按页面 part 提供 `/_part/{id}`(首页)与 `{path}/_part/{id}`(`app.route` 页)、启动 HTTP。作者不必手写 part 注册。 +`listen` / `监听`:加载插件、注入 `db_url`、按页面 part 提供 `/_part/{id}`(首页)与 `{path}/_part/{id}`(`app.route` 页)、可选 `static` 目录挂载、启动 HTTP。作者不必手写 part 注册。 + +`static` / `静态`:`dir=`(或 `目录=`)+ 可选 `mount=`(默认 `/static`);`listen` 时用 `tower-http` 提供只读文件服务。 ### 5.5 表单 · `form` / `表单`(规划锁定) @@ -575,12 +577,11 @@ submit → action=insert → db.insert;action=update → db.update --- -## 9. 非本波次(可记入路线图,不挡作者面评审) +## 9. 非本波次(可记入路线图) -- Postgres / Redis / S3 驱动细节(SQLite 先落地); +- Postgres / Redis / S3 驱动细节(SQLite 已落地); - 复杂权限与多租户; -- 子页路由糖的更多约定(`# 应用.route` 已够用); -- `/admin` 的视觉与交互细化(CRUD/表单必须走 §5.3–§5.5;UI 可后做)。 +- 子页路由糖的更多约定(`# 应用.route` 已够用)。 --- diff --git a/examples/web-site-zh/README.md b/examples/web-site-zh/README.md index 90a5024..23867b5 100644 --- a/examples/web-site-zh/README.md +++ b/examples/web-site-zh/README.md @@ -7,4 +7,4 @@ cargo build -p marqdo_plugin_web cargo run -- examples/web-site-zh/index.mq.md ``` -打开 http://127.0.0.1:18082/ — `/about`、`/new`、`/admin`。 +打开 http://127.0.0.1:18082/ — `/about`、`/new`、`/admin`、`/static/site.css`。 diff --git a/examples/web-site-zh/index.mq.md b/examples/web-site-zh/index.mq.md index 3b630cd..dec1e0f 100644 --- a/examples/web-site-zh/index.mq.md +++ b/examples/web-site-zh/index.mq.md @@ -61,4 +61,5 @@ description: Home + /about + /new(表单嵌入)+ 后台;只用 ext/web/网 *`app` = > 网页.应用 页面=`page` 数据库=`store` 后台=True 主机=127.0.0.1 端口=18082 * *`app` = > `app`.路由 路径=/about 页面=`about` * *`app` = > `app`.路由 路径=/new 页面=`new` * +*`app` = > `app`.静态 目录=public 挂载=/static * > `app`.监听 diff --git a/examples/web-site-zh/public/site.css b/examples/web-site-zh/public/site.css new file mode 100644 index 0000000..9f94f4d --- /dev/null +++ b/examples/web-site-zh/public/site.css @@ -0,0 +1,5 @@ +/* 可选站点样式 — /static/site.css */ +body.site-hint::before { + content: "static ok"; + display: none; +} diff --git a/examples/web-site/README.md b/examples/web-site/README.md index c5de2d1..ebbb3cf 100644 --- a/examples/web-site/README.md +++ b/examples/web-site/README.md @@ -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/ — `/about`, `/new` (form in page slot), `/admin`. +Then open http://127.0.0.1:18081/ — `/about`, `/new` (form in page slot), `/admin`, `/static/site.css`. diff --git a/examples/web-site/index.mq.md b/examples/web-site/index.mq.md index 3dd34ec..3c0efba 100644 --- a/examples/web-site/index.mq.md +++ b/examples/web-site/index.mq.md @@ -69,4 +69,5 @@ New article: form embedded in the page main slot (design §5.5.4). *`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`.route path=/new page=`new` * +*`app` = > `app`.static dir=public mount=/static * > `app`.listen diff --git a/examples/web-site/public/site.css b/examples/web-site/public/site.css new file mode 100644 index 0000000..e912cb6 --- /dev/null +++ b/examples/web-site/public/site.css @@ -0,0 +1,5 @@ +/* Optional site stylesheet — served at /static/site.css */ +body.site-hint::before { + content: "static ok"; + display: none; +} diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md index a913689..b87e0d1 100644 --- a/ext/web/web.mq.md +++ b/ext/web/web.mq.md @@ -198,8 +198,16 @@ Register `GET|POST /_form/{id}` for listen when the form is not already embedded **> web_app_mount_form app=`self` id=`id` form=`form`** +## static + + `dir` + + `mount`=/static + +Serve files from `dir` under `mount` (default `/static`). Path is resolved from the process working directory at listen time. + +**> web_app_static app=`self` dir=`dir` mount=`mount`** + ## listen -Serve `/`, routed pages, `/_part/{id}` (home) and `{path}/_part/{id}` (routes), `/_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), optional `/static` (or custom mount), and optional `/admin`. **> web_listen app=`self`** diff --git a/ext/web/网页.mq.md b/ext/web/网页.mq.md index d9a663a..aff4dbc 100644 --- a/ext/web/网页.mq.md +++ b/ext/web/网页.mq.md @@ -188,8 +188,16 @@ description: 官方网站类(中文)。表格 + 方法;不写袋式胶水 **> web_app_mount_form app=`self` id=`id` form=`表单`** +## 静态 + + `目录` + + `挂载`=/static + +将 `目录` 下的文件挂到 `挂载`(默认 `/static`)。路径在 `监听` 时相对进程工作目录解析。 + +**> web_app_static app=`self` dir=`目录` mount=`挂载`** + ## 监听 -提供 `/`、路由页、首页 `/_part/{id}`、路由 `{路径}/_part/{id}`、`/_form/{id}`,以及可选 `/admin`。 +提供 `/`、路由页、首页 `/_part/{id}`、路由 `{路径}/_part/{id}`、`/_form/{id}`、可选静态目录,以及可选 `/admin`。 **> web_listen app=`self`** diff --git a/plugins/web/Cargo.toml b/plugins/web/Cargo.toml index 13927d5..00a2c88 100644 --- a/plugins/web/Cargo.toml +++ b/plugins/web/Cargo.toml @@ -15,4 +15,5 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "sync", "time", "signal"] } axum = "0.8" +tower-http = { version = "0.6", features = ["fs"] } rusqlite = { version = "0.32", features = ["bundled"] } diff --git a/plugins/web/src/http.rs b/plugins/web/src/http.rs index e0fe7c7..5a0b2fa 100644 --- a/plugins/web/src/http.rs +++ b/plugins/web/src/http.rs @@ -1,16 +1,19 @@ -//! Blocking HTTP listen: page shell, `/_part/{id}`, `/_form/{id}`, `/admin` CRUD. +//! Blocking HTTP listen: page shell, `/_part`, `/_form`, `/admin`, optional static dir. use std::collections::HashMap; use std::net::SocketAddr; +use std::path::PathBuf; use std::sync::Arc; -use axum::extract::{Form, Path, State}; +use axum::extract::{Form, Path, Query, State}; use axum::http::Uri; use axum::response::{Html, IntoResponse, Redirect, Response}; use axum::routing::get; use axum::Router; +use serde::Deserialize; use serde_json::{json, Map, Value}; use tokio::runtime::Runtime; +use tower_http::services::ServeDir; use crate::db; use crate::form; @@ -57,6 +60,8 @@ pub fn listen( admin: bool, mut forms: HashMap, routes: HashMap, + static_dir: Option, + static_mount: &str, ) -> Result { let mut form_owners = HashMap::new(); collect_page_forms(page, &mut forms, &mut form_owners); @@ -94,6 +99,23 @@ pub fn listen( app = app.route(&part_path, get(routed_part)); } + let mount = normalize_static_mount(static_mount); + if let Some(dir) = static_dir { + if !dir.is_dir() { + return Err(format!( + "static dir `{}` is not a directory", + dir.display() + )); + } + eprintln!( + "marqdo web static: {} → {}", + mount, + dir.display() + ); + let svc = ServeDir::new(dir); + app = app.nest_service(&mount, svc); + } + let app = app.with_state(state); let addr: SocketAddr = format!("{host}:{port}") @@ -113,6 +135,22 @@ pub fn listen( Ok(json!({ "ok": true })) } +pub fn normalize_static_mount(raw: &str) -> String { + let s = raw.trim(); + if s.is_empty() { + return "/static".into(); + } + let mut m = if s.starts_with('/') { + s.to_string() + } else { + format!("/{s}") + }; + while m.len() > 1 && m.ends_with('/') { + m.pop(); + } + m +} + async fn home(State(st): State>) -> Html { let html = render::render_page(&st.page, st.db_url.as_deref()); Html(html) @@ -181,7 +219,7 @@ async fn form_post( let Some(url) = st.db_url.as_deref() else { return Html(String::from("

no database

")).into_response(); }; - submit_and_respond(&st, frm, &id, url, posted) + submit_and_respond(&st, frm, &id, url, posted, None) } fn posted_to_value(posted: HashMap) -> Value { @@ -192,25 +230,55 @@ fn posted_to_value(posted: HashMap) -> Value { Value::Object(data) } +fn with_flash(redirect: &str, flash: &str) -> String { + if redirect.contains('?') { + format!("{redirect}&flash={flash}") + } else { + format!("{redirect}?flash={flash}") + } +} + fn submit_and_respond( st: &AppState, frm: &Value, form_id: &str, url: &str, posted: HashMap, + admin_table: Option<&str>, ) -> Response { let data_v = posted_to_value(posted); match form::submit(frm, &data_v, url) { Ok(res) if res.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) => { - let redirect = res + let mut redirect = res .get("redirect") .and_then(|v| v.as_str()) - .unwrap_or("/"); - Redirect::to(redirect).into_response() + .unwrap_or("/") + .to_string(); + if form_id.contains("-new") { + redirect = with_flash(&redirect, "created"); + } else if form_id.contains("-edit") { + redirect = with_flash(&redirect, "updated"); + } + Redirect::to(&redirect).into_response() } Ok(res) => { let errors = res.get("errors"); - if let Some(page) = st.form_owners.get(form_id) { + if let Some(table) = admin_table { + Html(admin_form_page( + st, + table, + if form_id.contains("-edit") { + "Edit" + } else { + "New" + }, + frm, + form_id, + Some(&data_v), + errors, + )) + .into_response() + } else if let Some(page) = st.form_owners.get(form_id) { Html(render::render_page_ex( page, st.db_url.as_deref(), @@ -228,59 +296,205 @@ fn submit_and_respond( fn admin_gate(st: &AppState) -> Option { if !st.admin { - return Some(Html(String::from("

admin disabled

")).into_response()); + return Some(Html(admin_shell(st, "Admin", None, "

Admin is disabled for this app.

")).into_response()); } if st.db_url.is_none() { - return Some(Html(String::from("

no database

")).into_response()); + return Some(Html(admin_shell(st, "Admin", None, "

No database bound to this app.

")).into_response()); } None } -fn admin_shell(title: &str, inner: &str) -> String { +fn flash_html(flash: Option<&str>) -> String { + match flash { + Some("created") => "
Row created.
".into(), + Some("updated") => "
Row updated.
".into(), + Some("deleted") => "
Row deleted.
".into(), + Some(other) if !other.is_empty() => { + format!("
{}
", esc(other)) + } + _ => String::new(), + } +} + +fn truncate_cell(s: &str, max: usize) -> String { + let mut it = s.chars(); + let head: String = it.by_ref().take(max).collect(); + if it.next().is_some() { + format!("{head}…") + } else { + head + } +} + +fn admin_shell(st: &AppState, title: &str, active: Option<&str>, inner: &str) -> String { + let tables = st + .db_url + .as_deref() + .and_then(|u| db::list_tables(u).ok()) + .unwrap_or_default(); + let mut side = String::from(""); + format!( - r#"{title} + r#" + + + +{title} · Admin {inner}"#, +:root {{ --ink:#1c1917; --muted:#78716c; --paper:#fafaf9; --line:#e7e5e4; --accent:#0f766e; --ok:#166534; --err:#b91c1c; --side:#f5f5f4; }} +* {{ box-sizing:border-box; }} +body {{ margin:0; font-family:"IBM Plex Sans","Noto Sans SC",sans-serif; background:var(--paper); color:var(--ink); min-height:100vh; display:grid; grid-template-columns:14rem 1fr; }} +@media (max-width:720px) {{ body {{ grid-template-columns:1fr; }} .admin-nav {{ border-right:0; border-bottom:1px solid var(--line); }} }} +.admin-nav {{ background:var(--side); border-right:1px solid var(--line); padding:1.1rem 1rem 1.5rem; }} +.admin-nav .brand {{ display:block; font-weight:600; font-size:1.05rem; margin-bottom:1rem; color:var(--ink); }} +.admin-nav ul {{ list-style:none; margin:0; padding:0; display:grid; gap:.2rem; }} +.admin-nav a {{ color:var(--ink); text-decoration:none; display:block; padding:.35rem .5rem; border-radius:4px; }} +.admin-nav a:hover,.admin-nav a.active {{ background:#fff; color:var(--accent); }} +.admin-nav .nav-label {{ margin:1.1rem 0 .35rem; font-size:.75rem; text-transform:uppercase; letter-spacing:.04em; color:var(--muted); }} +.admin-nav .nav-foot {{ margin-top:1.5rem; font-size:.9rem; }} +.admin-nav .muted {{ color:var(--muted); font-size:.9rem; }} +.admin-main {{ padding:1.25rem 1.5rem 2rem; max-width:56rem; }} +.admin-main h1 {{ margin:0 0 .35rem; font-size:1.65rem; }} +.crumbs {{ color:var(--muted); font-size:.85rem; margin-bottom:1rem; }} +.crumbs a {{ color:var(--muted); }} +.toolbar {{ display:flex; gap:.75rem; align-items:center; margin:0 0 1.1rem; flex-wrap:wrap; }} +.meta {{ color:var(--muted); font-size:.9rem; margin:0 0 1rem; }} +.btn {{ display:inline-block; background:var(--accent); color:#fff!important; padding:.45rem .85rem; border-radius:4px; text-decoration:none; border:0; font:inherit; cursor:pointer; }} +.btn:hover {{ filter:brightness(1.05); }} +.btn-muted {{ background:#78716c; }} +.btn-ghost {{ background:transparent; color:var(--accent)!important; border:1px solid var(--line); }} +table.data {{ width:100%; border-collapse:collapse; background:#fff; border:1px solid var(--line); border-radius:6px; overflow:hidden; }} +table.data th,table.data td {{ border-bottom:1px solid var(--line); padding:.55rem .7rem; text-align:left; vertical-align:top; font-size:.92rem; }} +table.data th {{ background:#f5f5f4; font-weight:600; }} +table.data tr:last-child td {{ border-bottom:0; }} +table.data .actions {{ white-space:nowrap; }} +.empty {{ background:#fff; border:1px dashed var(--line); border-radius:6px; padding:2rem 1.25rem; text-align:center; color:var(--muted); }} +.empty strong {{ display:block; color:var(--ink); margin-bottom:.35rem; font-size:1.05rem; }} +.flash {{ padding:.65rem .85rem; border-radius:4px; margin:0 0 1rem; }} +.flash.ok {{ background:#ecfdf5; color:var(--ok); border:1px solid #a7f3d0; }} +.flash.err {{ background:#fef2f2; color:var(--err); border:1px solid #fecaca; }} +.danger {{ color:var(--err); }} +.site-form {{ max-width:28rem; margin-top:.5rem; }} +.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:var(--err); 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; font:inherit; }} +.site-form .meta {{ color:var(--muted); font-size:.9rem; }} + + + +{side} +
{inner}
+"#, title = esc(title), + side = side, inner = inner ) } -async fn admin_home(State(st): State>) -> Response { +fn admin_form_page( + st: &AppState, + table: &str, + kind: &str, + frm: &Value, + form_id: &str, + data: Option<&Value>, + errors: Option<&Value>, +) -> String { + let mut body = format!( + "

Admin / {t} / {kind}

{kind} {t}

", + t = esc(table), + kind = esc(kind), + ); + body.push_str(&form::render_body(frm, form_id, data, errors)); + admin_shell(st, &format!("{kind} {table}"), Some(table), &body) +} + +#[derive(Deserialize)] +struct FlashQuery { + flash: Option, +} + +async fn admin_home( + State(st): State>, + Query(q): Query, +) -> Response { if let Some(r) = admin_gate(&st) { return r; } let url = st.db_url.as_deref().unwrap(); let tables = db::list_tables(url).unwrap_or_default(); - let mut inner = String::from("

admin

tables

    "); - for t in &tables { - inner.push_str(&format!("
  • {t}
  • ")); - } - inner.push_str("
"); - if !st.forms.is_empty() { - inner.push_str("

mounted forms

    "); - for id in st.forms.keys() { - inner.push_str(&format!("
  • {id}
  • ")); + let mut inner = String::from("

    Admin

    SQLite tables for this site.

    "); + inner.push_str(&flash_html(q.flash.as_deref())); + if tables.is_empty() { + inner.push_str( + "
    No tablesInitialize a table via db.init / 数据库.初始化.
    ", + ); + } else { + inner.push_str(""); + for t in &tables { + inner.push_str(&format!( + "", + t = esc(t) + )); } - inner.push_str(""); + inner.push_str("
    Table
    {t}New
    "); } - Html(admin_shell("admin", &inner)).into_response() + Html(admin_shell(&st, "Admin", None, &inner)).into_response() } -async fn admin_table(State(st): State>, Path(table): Path) -> Response { +async fn admin_table( + State(st): State>, + Path(table): Path, + Query(q): Query, +) -> Response { if let Some(r) = admin_gate(&st) { return r; } let url = st.db_url.as_deref().unwrap(); let Ok(data) = db::select(url, &table, 200, None) else { - return Html(format!("

    cannot read {table}

    ")).into_response(); + return Html(admin_shell( + &st, + &table, + Some(&table), + &format!("

    Cannot read table {}.

    ", esc(&table)), + )) + .into_response(); }; let rows = data .get("rows") @@ -297,56 +511,68 @@ async fn admin_table(State(st): State>, Path(table): Path) cols = info.into_iter().map(|c| c.name).collect(); } } - // prefer id first if let Some(i) = cols.iter().position(|c| c == "id") { let idc = cols.remove(i); cols.insert(0, idc); } - let mut inner = format!("

    {table}

    "); + let mut inner = format!( + "

    Admin / {t}

    {t}

    ", + t = esc(&table) + ); + inner.push_str(&flash_html(q.flash.as_deref())); inner.push_str(&format!( - "" + "
    New row{} row{}
    ", + esc(&table), + rows.len(), + if rows.len() == 1 { "" } else { "s" } )); - inner.push_str(""); - for c in &cols { - inner.push_str(&format!("", esc(c))); - } - inner.push_str(""); - for row in &rows { - let m = row.as_object().cloned().unwrap_or_else(Map::new); - inner.push_str(""); + + if rows.is_empty() { + inner.push_str(&format!( + "", + esc(&table), + esc(&table) + )); + } else { + inner.push_str("
    {}
    "); for c in &cols { - let cell = m - .get(c) + inner.push_str(&format!("", esc(c))); + } + inner.push_str(""); + for row in &rows { + let m = row.as_object().cloned().unwrap_or_else(Map::new); + inner.push_str(""); + for c in &cols { + let cell = m + .get(c) + .map(|v| match v { + Value::String(s) => s.clone(), + Value::Null => String::new(), + other => other.to_string(), + }) + .unwrap_or_default(); + inner.push_str(&format!("", esc(&truncate_cell(&cell, 80)))); + } + let id = m + .get("id") .map(|v| match v { Value::String(s) => s.clone(), - Value::Null => String::new(), other => other.to_string(), }) .unwrap_or_default(); - inner.push_str(&format!("", esc(&cell))); + if !id.is_empty() { + inner.push_str(&format!( + "" + )); + } else { + inner.push_str(""); + } + inner.push_str(""); } - let id = m - .get("id") - .map(|v| match v { - Value::String(s) => s.clone(), - other => other.to_string(), - }) - .unwrap_or_default(); - if !id.is_empty() { - inner.push_str(&format!( - "" - )); - } else { - inner.push_str(""); - } - inner.push_str(""); + inner.push_str("
    {}
    {}{}Edit · Delete
    edit · delete
    "); } - if rows.is_empty() { - inner.push_str("(empty)"); - } - inner.push_str(""); - Html(admin_shell(&table, &inner)).into_response() + Html(admin_shell(&st, &table, Some(&table), &inner)).into_response() } async fn admin_new_get(State(st): State>, Path(table): Path) -> Response { @@ -355,9 +581,23 @@ async fn admin_new_get(State(st): State>, Path(table): Path Html(form::render(&frm, &format!("admin-{table}-new"), None, None)) - .into_response(), - Err(e) => Html(format!("

    {}

    ", esc(&e))).into_response(), + Ok(frm) => Html(admin_form_page( + &st, + &table, + "New", + &frm, + &format!("admin-{table}-new"), + None, + None, + )) + .into_response(), + Err(e) => Html(admin_shell( + &st, + &table, + Some(&table), + &format!("

    {}

    ", esc(&e)), + )) + .into_response(), } } @@ -371,8 +611,21 @@ 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(&st, &frm, &format!("admin-{table}-new"), url, posted), - Err(e) => Html(format!("

    {}

    ", esc(&e))).into_response(), + Ok(frm) => submit_and_respond( + &st, + &frm, + &format!("admin-{table}-new"), + url, + posted, + Some(&table), + ), + Err(e) => Html(admin_shell( + &st, + &table, + Some(&table), + &format!("

    {}

    ", esc(&e)), + )) + .into_response(), } } @@ -386,20 +639,43 @@ async fn admin_edit_get( let url = st.db_url.as_deref().unwrap(); let row = match db::get(url, &table, &id) { Ok(Value::Null) => { - return Html(format!("

    row {id} not found

    ")).into_response(); + return Html(admin_shell( + &st, + &table, + Some(&table), + &format!("

    Row {id} not found.

    "), + )) + .into_response(); } Ok(v) => v, - Err(e) => return Html(format!("

    {}

    ", esc(&e))).into_response(), + Err(e) => { + return Html(admin_shell( + &st, + &table, + Some(&table), + &format!("

    {}

    ", esc(&e)), + )) + .into_response(); + } }; match form::from_schema(url, &table, "update", Some(&id)) { - Ok(frm) => Html(form::render( + Ok(frm) => Html(admin_form_page( + &st, + &table, + "Edit", &frm, &format!("admin-{table}-edit"), Some(&row), None, )) .into_response(), - Err(e) => Html(format!("

    {}

    ", esc(&e))).into_response(), + Err(e) => Html(admin_shell( + &st, + &table, + Some(&table), + &format!("

    {}

    ", esc(&e)), + )) + .into_response(), } } @@ -413,8 +689,21 @@ 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(&st, &frm, &format!("admin-{table}-edit"), url, posted), - Err(e) => Html(format!("

    {}

    ", esc(&e))).into_response(), + Ok(frm) => submit_and_respond( + &st, + &frm, + &format!("admin-{table}-edit"), + url, + posted, + Some(&table), + ), + Err(e) => Html(admin_shell( + &st, + &table, + Some(&table), + &format!("

    {}

    ", esc(&e)), + )) + .into_response(), } } @@ -427,9 +716,15 @@ async fn admin_delete( } let url = st.db_url.as_deref().unwrap(); if let Err(e) = db::delete(url, &table, &id) { - return Html(format!("

    delete failed: {}

    ", esc(&e))).into_response(); + return Html(admin_shell( + &st, + &table, + Some(&table), + &format!("

    Delete failed: {}

    ", esc(&e)), + )) + .into_response(); } - Redirect::to(&format!("/admin/{table}")).into_response() + Redirect::to(&with_flash(&format!("/admin/{table}"), "deleted")).into_response() } fn esc(s: &str) -> String { diff --git a/plugins/web/src/lib.rs b/plugins/web/src/lib.rs index 76422c3..278cc0a 100644 --- a/plugins/web/src/lib.rs +++ b/plugins/web/src/lib.rs @@ -354,6 +354,8 @@ web_ffi!(web_app_new, |args: &Value| { "admin": admin, "forms": {}, "routes": {}, + "static_dir": null, + "static_mount": "/static", })) }); @@ -380,6 +382,8 @@ fn normalize_route_path(raw: &str) -> Result { || path.starts_with("/_form/") || path == "/_part" || path.starts_with("/_part/") + || path == "/static" + || path.starts_with("/static/") { return Err(format!("route path `{path}` is reserved")); } @@ -428,6 +432,32 @@ web_ffi!(web_app_mount_form, |args: &Value| { Ok(app) }); +web_ffi!(web_app_static, |args: &Value| { + let mut app = args.get("app").cloned().unwrap_or(json!({})); + let dir = arg_str(args, "dir")?.to_string(); + if dir.trim().is_empty() { + return Err("static `dir` is empty".into()); + } + let mount = arg_str_opt(args, "mount").unwrap_or("/static"); + let mount = http::normalize_static_mount(mount); + // Also reserve custom mounts against later routes. + if mount == "/admin" + || mount.starts_with("/admin/") + || mount == "/_form" + || mount.starts_with("/_form/") + || mount == "/_part" + || mount.starts_with("/_part/") + { + return Err(format!("static mount `{mount}` is reserved")); + } + let obj = app + .as_object_mut() + .ok_or_else(|| "app must be a map".to_string())?; + obj.insert("static_dir".into(), json!(dir)); + obj.insert("static_mount".into(), json!(mount)); + Ok(app) +}); + web_ffi!(web_form_new, |args: &Value| { let table = arg_str_opt(args, "table"); let action = arg_str_opt(args, "action").unwrap_or("insert"); @@ -517,7 +547,10 @@ 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, routes) = if args.get("page").is_some() + use std::path::PathBuf; + let (page, db_url, host, port, admin, forms, routes, static_dir, static_mount) = if args + .get("page") + .is_some() || args.get("host").is_some() { let page = args.get("page").cloned().unwrap_or(json!({})); @@ -531,6 +564,10 @@ web_ffi!(web_listen, |args: &Value| { Some(Value::Bool(b)) => *b, _ => false, }; + let static_dir = arg_str_opt(args, "static_dir").map(PathBuf::from); + let static_mount = arg_str_opt(args, "static_mount") + .unwrap_or("/static") + .to_string(); ( page, db_url, @@ -539,6 +576,8 @@ web_ffi!(web_listen, |args: &Value| { admin, HashMap::new(), HashMap::new(), + static_dir, + static_mount, ) } else { let app = args.get("app").cloned().unwrap_or_else(|| args.clone()); @@ -574,8 +613,37 @@ web_ffi!(web_listen, |args: &Value| { routes.insert(k.clone(), v.clone()); } } - (page, db_url, host, port, admin, forms, routes) + let static_dir = app + .get("static_dir") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .map(PathBuf::from); + let static_mount = app + .get("static_mount") + .and_then(|v| v.as_str()) + .unwrap_or("/static") + .to_string(); + ( + page, + db_url, + host, + port, + admin, + forms, + routes, + static_dir, + static_mount, + ) }; + let static_dir = static_dir.map(|p| { + if p.is_absolute() { + p + } else { + std::env::current_dir() + .unwrap_or_else(|_| PathBuf::from(".")) + .join(p) + } + }); http::listen( &page, db_url.as_deref(), @@ -584,6 +652,8 @@ web_ffi!(web_listen, |args: &Value| { admin, forms, routes, + static_dir, + &static_mount, ) }); @@ -657,6 +727,11 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int "app,id,form", web_app_mount_form as PluginFn, ), + ( + "web_app_static", + "app,dir,mount", + web_app_static as PluginFn, + ), ("web_form_new", "table,action,id", web_form_new as PluginFn), ("web_form_fields", "form,fields", web_form_fields as PluginFn), ("web_form_rules", "form,rules", web_form_rules as PluginFn), diff --git a/tests/ext/web-fixtures/public/hello.txt b/tests/ext/web-fixtures/public/hello.txt new file mode 100644 index 0000000..bd8409e --- /dev/null +++ b/tests/ext/web-fixtures/public/hello.txt @@ -0,0 +1 @@ +Marqdo web static fixture. diff --git a/tests/ext/web-static-smoke.mq.md b/tests/ext/web-static-smoke.mq.md new file mode 100644 index 0000000..54e3ec1 --- /dev/null +++ b/tests/ext/web-static-smoke.mq.md @@ -0,0 +1,31 @@ +--- +title: web static smoke +description: Offline app.static registration (no listen). +> ext/web/web.mq.md +> lib/json.mq.md +--- + +# main + +*`home` = > web.page title="Home" * +*`app` = > web.app page=`home` host=127.0.0.1 port=18081 * +*`app` = > `app`.static dir=web-fixtures/public mount=/static * + +*`dir` = > json.get value=`app` key=static_dir * +1. `dir` == "web-fixtures/public" + > print text=dir-ok +2. * + > print text=dir-fail + +*`mount` = > json.get value=`app` key=static_mount * +1. `mount` == "/static" + > print text=mount-ok +2. * + > print text=mount-fail + +*`app2` = > `app`.static dir=assets mount=/assets * +*`m2` = > json.get value=`app2` key=static_mount * +1. `m2` == "/assets" + > print text=custom-ok +2. * + > print text=custom-fail diff --git a/tests/gold.rs b/tests/gold.rs index f8900c8..5d1b003 100644 --- a/tests/gold.rs +++ b/tests/gold.rs @@ -1358,6 +1358,22 @@ route-ok", ); } +#[test] +fn ext_web_static_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-static-smoke.mq.md", + "dir-ok +mount-ok +custom-ok", + ); +} + #[test] fn ext_agent_framework_smoke() { let status = Command::new("cargo")