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 <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-12 09:26:30 +08:00
1 parent a0c56fa352
commit db6158e9e2
16 files changed
+605 -95

No files matched your search

Generated
+62
View File
@@ -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"
+9 -8
View File
@@ -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` 已够用)。
---
+1 -1
View File
@@ -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`。
+1
View File
@@ -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`.监听
+5
View File
@@ -0,0 +1,5 @@
/* 可选站点样式 — /static/site.css */
body.site-hint::before {
content: "static ok";
display: none;
}
+1 -1
View File
@@ -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`.
+1
View File
@@ -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
+5
View File
@@ -0,0 +1,5 @@
/* Optional site stylesheet — served at /static/site.css */
body.site-hint::before {
content: "static ok";
display: none;
}
+9 -1
View File
@@ -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`**
+9 -1
View File
@@ -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`**
+1
View File
@@ -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"] }
+376 -81
View File
@@ -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<String, Value>,
routes: HashMap<String, Value>,
static_dir: Option<PathBuf>,
static_mount: &str,
) -> Result<Value, String> {
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<Arc<AppState>>) -> Html<String> {
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("<p>no database</p>")).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<String, String>) -> Value {
@@ -192,25 +230,55 @@ fn posted_to_value(posted: HashMap<String, String>) -> 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<String, String>,
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<Response> {
if !st.admin {
return Some(Html(String::from("<p>admin disabled</p>")).into_response());
return Some(Html(admin_shell(st, "Admin", None, "<p class=\"flash err\">Admin is disabled for this app.</p>")).into_response());
}
if st.db_url.is_none() {
return Some(Html(String::from("<p>no database</p>")).into_response());
return Some(Html(admin_shell(st, "Admin", None, "<p class=\"flash err\">No database bound to this app.</p>")).into_response());
}
None
}
fn admin_shell(title: &str, inner: &str) -> String {
fn flash_html(flash: Option<&str>) -> String {
match flash {
Some("created") => "<div class=\"flash ok\">Row created.</div>".into(),
Some("updated") => "<div class=\"flash ok\">Row updated.</div>".into(),
Some("deleted") => "<div class=\"flash ok\">Row deleted.</div>".into(),
Some(other) if !other.is_empty() => {
format!("<div class=\"flash ok\">{}</div>", 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("<nav class=\"admin-nav\"><a class=\"brand\" href=\"/admin\">Admin</a>");
if tables.is_empty() {
side.push_str("<p class=\"muted\">No tables yet.</p>");
} else {
side.push_str("<ul>");
for t in &tables {
let cls = if active == Some(t.as_str()) {
" class=\"active\""
} else {
""
};
side.push_str(&format!(
"<li><a{cls} href=\"/admin/{}\">{}</a></li>",
esc(t),
esc(t)
));
}
side.push_str("</ul>");
}
if !st.forms.is_empty() {
side.push_str("<p class=\"nav-label\">Forms</p><ul>");
let mut ids: Vec<_> = st.forms.keys().cloned().collect();
ids.sort();
for id in ids {
side.push_str(&format!(
"<li><a href=\"/_form/{}\">{}</a></li>",
esc(&id),
esc(&id)
));
}
side.push_str("</ul>");
}
side.push_str("<div class=\"nav-foot\"><a href=\"/\">← Site</a></div></nav>");
format!(
r#"<!DOCTYPE html><html><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>{title}</title>
r#"<!DOCTYPE html>
<html lang="zh-CN"><head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>{title} · Admin</title>
<style>
body{{font-family:"IBM Plex Sans","Noto Sans SC",sans-serif;margin:1.5rem;background:#fafaf9;color:#1c1917}}
a{{color:#0f766e;text-decoration:none}} a:hover{{text-decoration:underline}}
table{{border-collapse:collapse;background:#fff}} th,td{{border:1px solid #e7e5e4;padding:.45rem .65rem;text-align:left}}
.toolbar{{display:flex;gap:1rem;align-items:center;margin:.75rem 0 1.25rem;flex-wrap:wrap}}
.btn{{display:inline-block;background:#0f766e;color:#fff!important;padding:.4rem .75rem;border-radius:4px}}
.btn-muted{{background:#78716c}}
.danger{{color:#b91c1c}}
</style></head><body>{inner}</body></html>"#,
: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; }}
</style>
</head>
<body>
{side}
<main class="admin-main">{inner}</main>
</body></html>"#,
title = esc(title),
side = side,
inner = inner
)
}
async fn admin_home(State(st): State<Arc<AppState>>) -> 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!(
"<p class=\"crumbs\"><a href=\"/admin\">Admin</a> / <a href=\"/admin/{t}\">{t}</a> / {kind}</p><h1>{kind} {t}</h1>",
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<String>,
}
async fn admin_home(
State(st): State<Arc<AppState>>,
Query(q): Query<FlashQuery>,
) -> 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("<h1>admin</h1><div class=\"toolbar\"><a href=\"/\">home</a></div><h2>tables</h2><ul>");
for t in &tables {
inner.push_str(&format!("<li><a href=\"/admin/{t}\">{t}</a></li>"));
}
inner.push_str("</ul>");
if !st.forms.is_empty() {
inner.push_str("<h2>mounted forms</h2><ul>");
for id in st.forms.keys() {
inner.push_str(&format!("<li><a href=\"/_form/{id}\">{id}</a></li>"));
let mut inner = String::from("<h1>Admin</h1><p class=\"meta\">SQLite tables for this site.</p>");
inner.push_str(&flash_html(q.flash.as_deref()));
if tables.is_empty() {
inner.push_str(
"<div class=\"empty\"><strong>No tables</strong>Initialize a table via <code>db.init</code> / <code>数据库.初始化</code>.</div>",
);
} else {
inner.push_str("<table class=\"data\"><thead><tr><th>Table</th><th></th></tr></thead><tbody>");
for t in &tables {
inner.push_str(&format!(
"<tr><td><a href=\"/admin/{t}\">{t}</a></td><td class=\"actions\"><a class=\"btn\" href=\"/admin/{t}/new\">New</a></td></tr>",
t = esc(t)
));
}
inner.push_str("</ul>");
inner.push_str("</tbody></table>");
}
Html(admin_shell("admin", &inner)).into_response()
Html(admin_shell(&st, "Admin", None, &inner)).into_response()
}
async fn admin_table(State(st): State<Arc<AppState>>, Path(table): Path<String>) -> Response {
async fn admin_table(
State(st): State<Arc<AppState>>,
Path(table): Path<String>,
Query(q): Query<FlashQuery>,
) -> 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!("<p>cannot read {table}</p>")).into_response();
return Html(admin_shell(
&st,
&table,
Some(&table),
&format!("<p class=\"flash err\">Cannot read table {}.</p>", esc(&table)),
))
.into_response();
};
let rows = data
.get("rows")
@@ -297,56 +511,68 @@ async fn admin_table(State(st): State<Arc<AppState>>, Path(table): Path<String>)
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!("<h1>{table}</h1>");
let mut inner = format!(
"<p class=\"crumbs\"><a href=\"/admin\">Admin</a> / {t}</p><h1>{t}</h1>",
t = esc(&table)
);
inner.push_str(&flash_html(q.flash.as_deref()));
inner.push_str(&format!(
"<div class=\"toolbar\"><a class=\"btn\" href=\"/admin/{table}/new\">New</a><a href=\"/admin\">back</a><a href=\"/\">home</a></div>"
"<div class=\"toolbar\"><a class=\"btn\" href=\"/admin/{}/new\">New row</a><span class=\"meta\">{} row{}</span></div>",
esc(&table),
rows.len(),
if rows.len() == 1 { "" } else { "s" }
));
inner.push_str("<table><thead><tr>");
for c in &cols {
inner.push_str(&format!("<th>{}</th>", esc(c)));
}
inner.push_str("<th></th></tr></thead><tbody>");
for row in &rows {
let m = row.as_object().cloned().unwrap_or_else(Map::new);
inner.push_str("<tr>");
if rows.is_empty() {
inner.push_str(&format!(
"<div class=\"empty\"><strong>No rows in {}</strong><a class=\"btn\" href=\"/admin/{}/new\">Create the first row</a></div>",
esc(&table),
esc(&table)
));
} else {
inner.push_str("<table class=\"data\"><thead><tr>");
for c in &cols {
let cell = m
.get(c)
inner.push_str(&format!("<th>{}</th>", esc(c)));
}
inner.push_str("<th></th></tr></thead><tbody>");
for row in &rows {
let m = row.as_object().cloned().unwrap_or_else(Map::new);
inner.push_str("<tr>");
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!("<td>{}</td>", 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!("<td>{}</td>", esc(&cell)));
if !id.is_empty() {
inner.push_str(&format!(
"<td class=\"actions\"><a href=\"/admin/{table}/{id}/edit\">Edit</a> · <a class=\"danger\" href=\"/admin/{table}/{id}/delete\" onclick=\"return confirm('Delete row #{id}?')\">Delete</a></td>"
));
} else {
inner.push_str("<td></td>");
}
inner.push_str("</tr>");
}
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!(
"<td><a href=\"/admin/{table}/{id}/edit\">edit</a> · <a class=\"danger\" href=\"/admin/{table}/{id}/delete\" onclick=\"return confirm('Delete #{id}?')\">delete</a></td>"
));
} else {
inner.push_str("<td></td>");
}
inner.push_str("</tr>");
inner.push_str("</tbody></table>");
}
if rows.is_empty() {
inner.push_str("<tr><td colspan=\"99\">(empty)</td></tr>");
}
inner.push_str("</tbody></table>");
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<Arc<AppState>>, Path(table): Path<String>) -> Response {
@@ -355,9 +581,23 @@ async fn admin_new_get(State(st): State<Arc<AppState>>, Path(table): Path<String
}
let url = st.db_url.as_deref().unwrap();
match form::from_schema(url, &table, "insert", None) {
Ok(frm) => Html(form::render(&frm, &format!("admin-{table}-new"), None, None))
.into_response(),
Err(e) => Html(format!("<p>{}</p>", 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!("<p class=\"flash err\">{}</p>", 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!("<p>{}</p>", 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!("<p class=\"flash err\">{}</p>", 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!("<p>row {id} not found</p>")).into_response();
return Html(admin_shell(
&st,
&table,
Some(&table),
&format!("<p class=\"flash err\">Row {id} not found.</p>"),
))
.into_response();
}
Ok(v) => v,
Err(e) => return Html(format!("<p>{}</p>", esc(&e))).into_response(),
Err(e) => {
return Html(admin_shell(
&st,
&table,
Some(&table),
&format!("<p class=\"flash err\">{}</p>", 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!("<p>{}</p>", esc(&e))).into_response(),
Err(e) => Html(admin_shell(
&st,
&table,
Some(&table),
&format!("<p class=\"flash err\">{}</p>", 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!("<p>{}</p>", 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!("<p class=\"flash err\">{}</p>", 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!("<p>delete failed: {}</p>", esc(&e))).into_response();
return Html(admin_shell(
&st,
&table,
Some(&table),
&format!("<p class=\"flash err\">Delete failed: {}</p>", 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 {
+77 -2
View File
@@ -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<String, String> {
|| 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),
+1
View File
@@ -0,0 +1 @@
Marqdo web static fixture.
+31
View File
@@ -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
+16
View File
@@ -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")