ext/web W4c: SEO meta, Markdown render, RSS, pagination UI
Add lib/net markdown_parse, page.meta/paginate and app.route_rss author APIs, GFM Markdown article bodies, head SEO tags, list pagination nav, and RSS 2.0 feed routes — keeping tables + class methods as the author surface. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
be6223f1fb
commit
e7c9c21a49
18 files changed
+671
-60
No files matched your search
Generated
+1
@@ -872,6 +872,7 @@ dependencies = [
|
||||
"axum",
|
||||
"futures-util",
|
||||
"getrandom 0.2.17",
|
||||
"pulldown-cmark",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 状态 | **W0–W3.5 + 安全硬化已落地;内容标配 W4 进行中** |
|
||||
| 状态 | **W0–W3.5 + 安全硬化 + 内容标配 W4c 已落地;Postgres/Redis W4 待** |
|
||||
| 日期 | 2026-08-11 |
|
||||
| **锁定设计** | [design/ext-web.md](../design/ext-web.md) |
|
||||
| 相关 | [ext-cli.md](../design/ext-cli.md) · [ext-abi.md](../design/ext-abi.md) · [ext-llm.md](../design/ext-llm.md) |
|
||||
@@ -29,7 +29,7 @@
|
||||
| **W3s** | 安全硬化:argon2 密码哈希、CSRF、SQLite 会话持久化、CSPRNG、登录限速 | **done** |
|
||||
| **W3.5** | 人写面首版:`web.assemble` + `` `表`.`字段` `` + `examples/man-write-site` | **done**(编排袋仍可再瘦) |
|
||||
| **W4** | Postgres;Redis / S3 驱动 | pending |
|
||||
| **W4c** | 内容标配:SEO / Markdown / RSS / 分页 UI(见 [web-net-capabilities.md](../design/web-net-capabilities.md)) | in progress |
|
||||
| **W4c** | 内容标配:SEO / Markdown / RSS / 分页 UI(见 [web-net-capabilities.md](../design/web-net-capabilities.md)) | **done** |
|
||||
|
||||
验收金样:`tests/ext/web-smoke.mq.md`、`tests/ext/web-security-smoke.mq.md`、`ext_cli_add_web`。
|
||||
|
||||
|
||||
@@ -90,6 +90,22 @@ of a list of cards. Set on the dynamic post page so `/post/{slug}` shows one pos
|
||||
|
||||
**> web_page_detail page=`self` detail=`detail`**
|
||||
|
||||
## meta
|
||||
+ `meta`
|
||||
|
||||
SEO / OpenGraph metadata as a data table (`|key|value|`). Keys such as `title`, `description`, `canonical`, `og:type` become `<head>` tags at render time.
|
||||
|
||||
**> web_page_meta page=`self` meta=`meta`**
|
||||
|
||||
## paginate
|
||||
+ `offset`=0
|
||||
+ `limit`=10
|
||||
+ `path`=/
|
||||
|
||||
List pagination for the main bind: sets DB `limit`/`offset` and renders previous/next navigation.
|
||||
|
||||
**> web_page_paginate page=`self` offset=`offset` limit=`limit` path=`path`**
|
||||
|
||||
## compose_form
|
||||
+ `form`
|
||||
+ `id`
|
||||
@@ -419,6 +435,19 @@ Keep the app's `admin=True`, and gate `/admin*` behind a login page. `users` is
|
||||
|
||||
**> web_app_auth app=`self` users=`users` session_ttl=`session_ttl`**
|
||||
|
||||
## route_rss
|
||||
+ `path`
|
||||
+ `table`
|
||||
+ `limit`=20
|
||||
+ `order`=-created_at
|
||||
+ `title`=Feed
|
||||
+ `link`=/
|
||||
+ `description`=""
|
||||
|
||||
Register an RSS 2.0 feed at `path` (e.g. `/feed.xml`) backed by a DB table.
|
||||
|
||||
**> web_app_route_rss app=`self` path=`path` table=`table` limit=`limit` order=`order` title=`title` link=`link` description=`description`**
|
||||
|
||||
# auth
|
||||
+ `users`
|
||||
+ `session_ttl`=3600
|
||||
|
||||
@@ -81,6 +81,22 @@ import sys:lib/sys.mq.md
|
||||
|
||||
**> web_page_detail page=`self` detail=`详情`**
|
||||
|
||||
## 元数据
|
||||
+ `元数据`
|
||||
|
||||
SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`canonical`、`og:type` 等会在渲染时写入 `<head>`。
|
||||
|
||||
**> web_page_meta page=`self` meta=`元数据`**
|
||||
|
||||
## 分页
|
||||
+ `偏移`=0
|
||||
+ `上限`=10
|
||||
+ `路径`=/
|
||||
|
||||
为主体列表绑定设置 DB 分页(`limit`/`offset`),并渲染上一页/下一页导航。
|
||||
|
||||
**> web_page_paginate page=`self` offset=`偏移` limit=`上限` path=`路径`**
|
||||
|
||||
## 表单装配
|
||||
+ `表单`
|
||||
+ `id`
|
||||
@@ -401,6 +417,19 @@ import sys:lib/sys.mq.md
|
||||
|
||||
**> web_app_auth app=`self` users=`用户表` session_ttl=`会话时长`**
|
||||
|
||||
## 路由订阅
|
||||
+ `路径`
|
||||
+ `表`
|
||||
+ `上限`=20
|
||||
+ `排序`=-created_at
|
||||
+ `标题`=Feed
|
||||
+ `链接`=/
|
||||
+ `描述`=""
|
||||
|
||||
在 `路径`(如 `/feed.xml`)注册 RSS 2.0 订阅源,数据来自数据库表。
|
||||
|
||||
**> web_app_route_rss app=`self` path=`路径` table=`表` limit=`上限` order=`排序` title=`标题` link=`链接` description=`描述`**
|
||||
|
||||
# 鉴权
|
||||
+ `用户表`
|
||||
+ `会话时长`=3600
|
||||
|
||||
@@ -71,3 +71,10 @@ Parse a `Cookie` request header (default) or one or more `Set-Cookie` response h
|
||||
Parse a `multipart/form-data` request body (given its `boundary`) into a list of `{name, filename?, content_type?, value}` parts.
|
||||
|
||||
**> host_multipart_parse body=`body` boundary=`boundary`**
|
||||
|
||||
## markdown_parse
|
||||
+ `text`
|
||||
|
||||
Parse Markdown / GFM into HTML (pure transform, no network I/O).
|
||||
|
||||
**> host_markdown_parse text=`text`**
|
||||
@@ -71,3 +71,10 @@ POST 并消费 OpenAI 兼容 SSE。返回 `{status, events}`(`delta` / `done`
|
||||
解析 `multipart/form-data` 请求体(给定 `boundary`)为 `{name, filename?, content_type?, value}` 部件列表。
|
||||
|
||||
**> host_multipart_parse body=`正文` boundary=`边界`**
|
||||
|
||||
## 解析Markdown
|
||||
+ `文本`
|
||||
|
||||
将 Markdown / GFM 解析为 HTML(纯转换,无网络 I/O)。
|
||||
|
||||
**> host_markdown_parse text=`文本`**
|
||||
@@ -21,3 +21,4 @@ tokio-tungstenite = "0.24"
|
||||
futures-util = "0.3"
|
||||
argon2 = "0.5"
|
||||
getrandom = "0.2"
|
||||
pulldown-cmark = "0.12"
|
||||
@@ -19,6 +19,7 @@ use crate::form;
|
||||
use crate::middleware::Middleware;
|
||||
use crate::rate_limit;
|
||||
use crate::render;
|
||||
use crate::rss;
|
||||
use crate::session;
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -71,6 +72,7 @@ pub fn listen(
|
||||
session_ttl: u64,
|
||||
cookie_secure: bool,
|
||||
ws_routes: HashMap<String, bool>,
|
||||
rss_routes: HashMap<String, Value>,
|
||||
middleware: &Middleware,
|
||||
) -> Result<Value, String> {
|
||||
let mut form_owners = HashMap::new();
|
||||
@@ -179,6 +181,21 @@ pub fn listen(
|
||||
);
|
||||
}
|
||||
|
||||
let mut rss_paths: Vec<String> = rss_routes.keys().cloned().collect();
|
||||
rss_paths.sort();
|
||||
for path in rss_paths {
|
||||
let cfg = rss_routes.get(&path).cloned().unwrap_or_default();
|
||||
let route_path = path.clone();
|
||||
app = app.route(
|
||||
&path,
|
||||
get(move |State(st): State<Arc<AppState>>| {
|
||||
let cfg = cfg.clone();
|
||||
let route_path = route_path.clone();
|
||||
async move { rss_feed(&st, &route_path, &cfg) }
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
let mount = normalize_static_mount(static_mount);
|
||||
if let Some(dir) = static_dir {
|
||||
if !dir.is_dir() {
|
||||
@@ -232,6 +249,40 @@ pub fn normalize_static_mount(raw: &str) -> String {
|
||||
m
|
||||
}
|
||||
|
||||
fn rss_feed(st: &AppState, _path: &str, cfg: &Value) -> Response {
|
||||
let Some(url) = st.db_url.as_deref() else {
|
||||
return Html(String::from("<p>no database</p>")).into_response();
|
||||
};
|
||||
let table = cfg
|
||||
.get("table")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("posts");
|
||||
let limit = cfg
|
||||
.get("limit")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(20);
|
||||
let order = cfg.get("order").and_then(|v| v.as_str());
|
||||
let title = cfg
|
||||
.get("title")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Feed");
|
||||
let link = cfg.get("link").and_then(|v| v.as_str()).unwrap_or("/");
|
||||
let description = cfg
|
||||
.get("description")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let rows = db::select_order(url, table, limit, None, order, None, None)
|
||||
.ok()
|
||||
.and_then(|v| v.get("rows").and_then(|r| r.as_array()).cloned())
|
||||
.unwrap_or_default();
|
||||
let xml = rss::build_rss(title, link, description, &rows);
|
||||
(
|
||||
[(axum::http::header::CONTENT_TYPE, "application/rss+xml; charset=utf-8")],
|
||||
xml,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
async fn home(State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap) -> Response {
|
||||
let (_, csrf, set_cookie) = resolve_session(&headers);
|
||||
let html = render::render_page(&st.page, st.db_url.as_deref(), Some(&csrf));
|
||||
|
||||
@@ -4,10 +4,12 @@ mod compose;
|
||||
mod db;
|
||||
mod form;
|
||||
mod http;
|
||||
mod markdown;
|
||||
mod middleware;
|
||||
mod password;
|
||||
mod rate_limit;
|
||||
mod render;
|
||||
mod rss;
|
||||
mod session;
|
||||
mod table;
|
||||
mod ws;
|
||||
@@ -345,6 +347,92 @@ web_ffi!(web_page_detail, |args: &Value| {
|
||||
Ok(Value::Object(obj))
|
||||
});
|
||||
|
||||
web_ffi!(web_page_meta, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let meta = args
|
||||
.get("meta")
|
||||
.or_else(|| args.get("table"))
|
||||
.cloned()
|
||||
.unwrap_or(json!({}));
|
||||
let mut obj = page.as_object().cloned().unwrap_or_default();
|
||||
obj.insert("meta".into(), Value::Object(crate::table::as_meta_map(&meta)));
|
||||
Ok(Value::Object(obj))
|
||||
});
|
||||
|
||||
web_ffi!(web_page_paginate, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let offset = args
|
||||
.get("offset")
|
||||
.and_then(|v| v.as_i64().or_else(|| v.as_u64().map(|u| u as i64)))
|
||||
.unwrap_or(0);
|
||||
let limit = args
|
||||
.get("limit")
|
||||
.and_then(|v| v.as_i64().or_else(|| v.as_u64().map(|u| u as i64)))
|
||||
.unwrap_or(10);
|
||||
let path = arg_str_opt(args, "path").unwrap_or("/").to_string();
|
||||
let mut obj = page.as_object().cloned().unwrap_or_default();
|
||||
obj.insert(
|
||||
"paginate".into(),
|
||||
json!({ "offset": offset, "limit": limit, "path": path }),
|
||||
);
|
||||
Ok(Value::Object(obj))
|
||||
});
|
||||
|
||||
web_ffi!(web_rss_build, |args: &Value| {
|
||||
let title = arg_str_opt(args, "title").unwrap_or("Feed");
|
||||
let link = arg_str_opt(args, "link").unwrap_or("/");
|
||||
let description = arg_str_opt(args, "description").unwrap_or("");
|
||||
let items = args
|
||||
.get("items")
|
||||
.or_else(|| args.get("rows"))
|
||||
.and_then(|v| v.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
Ok(Value::String(rss::build_rss(
|
||||
title,
|
||||
link,
|
||||
description,
|
||||
&items,
|
||||
)))
|
||||
});
|
||||
|
||||
web_ffi!(web_app_route_rss, |args: &Value| {
|
||||
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
||||
let path = normalize_route_path(arg_str(args, "path")?)?;
|
||||
let table = arg_str(args, "table")?.to_string();
|
||||
let limit = args
|
||||
.get("limit")
|
||||
.and_then(|v| v.as_i64().or_else(|| v.as_u64().map(|u| u as i64)))
|
||||
.unwrap_or(20);
|
||||
let order = arg_str_opt(args, "order").unwrap_or("-created_at").to_string();
|
||||
let title = arg_str_opt(args, "title").unwrap_or("Feed").to_string();
|
||||
let link = arg_str_opt(args, "link").unwrap_or("/").to_string();
|
||||
let description = arg_str_opt(args, "description")
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let obj = app
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| "app must be a map".to_string())?;
|
||||
let mut rss_routes = obj
|
||||
.get("rss_routes")
|
||||
.and_then(|v| v.as_object())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
rss_routes.insert(
|
||||
path,
|
||||
json!({
|
||||
"table": table,
|
||||
"limit": limit,
|
||||
"order": order,
|
||||
"title": title,
|
||||
"link": link,
|
||||
"description": description,
|
||||
}),
|
||||
);
|
||||
obj.insert("rss_routes".into(), Value::Object(rss_routes));
|
||||
Ok(app)
|
||||
});
|
||||
|
||||
web_ffi!(web_compose_form, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let form = args
|
||||
@@ -878,6 +966,7 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
auth_users,
|
||||
session_ttl,
|
||||
ws_routes,
|
||||
rss_routes,
|
||||
middleware,
|
||||
cookie_secure,
|
||||
) = if args.get("page").is_some() || args.get("host").is_some() {
|
||||
@@ -922,6 +1011,7 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
auth_users,
|
||||
session_ttl,
|
||||
HashMap::new(),
|
||||
HashMap::new(),
|
||||
middleware::Middleware::default(),
|
||||
cookie_secure,
|
||||
)
|
||||
@@ -971,6 +1061,12 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
ws_routes.insert(k.clone(), echo);
|
||||
}
|
||||
}
|
||||
let mut rss_routes = HashMap::new();
|
||||
if let Some(obj) = app.get("rss_routes").and_then(|v| v.as_object()) {
|
||||
for (k, v) in obj {
|
||||
rss_routes.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
let static_dir = app
|
||||
.get("static_dir")
|
||||
.and_then(|v| v.as_str())
|
||||
@@ -1025,6 +1121,7 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
auth_users,
|
||||
session_ttl,
|
||||
ws_routes,
|
||||
rss_routes,
|
||||
middleware,
|
||||
cookie_secure,
|
||||
)
|
||||
@@ -1050,6 +1147,7 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
session_ttl,
|
||||
cookie_secure,
|
||||
ws_routes,
|
||||
rss_routes,
|
||||
&middleware,
|
||||
)
|
||||
});
|
||||
@@ -1119,6 +1217,26 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
|
||||
"page,detail",
|
||||
web_page_detail as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_page_meta",
|
||||
"page,meta",
|
||||
web_page_meta as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_page_paginate",
|
||||
"page,offset,limit,path",
|
||||
web_page_paginate as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_rss_build",
|
||||
"title,link,description,items",
|
||||
web_rss_build as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_app_route_rss",
|
||||
"app,path,table,limit,order,title,link,description",
|
||||
web_app_route_rss as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_style",
|
||||
"name,table",
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Markdown → HTML for article bodies (GFM subset via pulldown-cmark).
|
||||
|
||||
use pulldown_cmark::{html, Options, Parser};
|
||||
|
||||
pub fn to_html(md: &str) -> String {
|
||||
let mut opts = Options::empty();
|
||||
opts.insert(
|
||||
Options::ENABLE_STRIKETHROUGH
|
||||
| Options::ENABLE_TABLES
|
||||
| Options::ENABLE_TASKLISTS,
|
||||
);
|
||||
let parser = Parser::new_ext(md, opts);
|
||||
let mut html_out = String::new();
|
||||
html::push_html(&mut html_out, parser);
|
||||
format!("<div class=\"article-body md\">{html_out}</div>")
|
||||
}
|
||||
+138
-58
@@ -3,6 +3,7 @@
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::db;
|
||||
use crate::markdown;
|
||||
use crate::table::{as_bind, normalize_ref, normalize_slot, parse_site_path, project_rows, SitePath};
|
||||
|
||||
fn esc(s: &str) -> String {
|
||||
@@ -77,7 +78,7 @@ fn resolve_links(raw: Option<&Value>, db_url: Option<&str>) -> Vec<(String, Stri
|
||||
let Some(table) = table else {
|
||||
return Vec::new();
|
||||
};
|
||||
let data = select_page_data(url, &table, raw, 200);
|
||||
let data = select_page_data(url, &table, raw, 200, 0);
|
||||
let rows = data
|
||||
.get("rows")
|
||||
.and_then(|v| v.as_array())
|
||||
@@ -127,27 +128,38 @@ fn render_ul(links: &[(String, String)], class: &str) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
fn resolve_main(args: &Value, db_url: Option<&str>) -> (String, Vec<Map<String, Value>>) {
|
||||
fn resolve_main(args: &Value, db_url: Option<&str>) -> (String, Vec<Map<String, Value>>, Option<i64>) {
|
||||
let intro = args
|
||||
.get("intro")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let Some(main) = args.get("main") else {
|
||||
return (intro, Vec::new());
|
||||
return (intro, Vec::new(), None);
|
||||
};
|
||||
let binds = as_bind(main);
|
||||
let arr = binds.as_array().cloned().unwrap_or_default();
|
||||
if arr.is_empty() {
|
||||
return (intro, Vec::new());
|
||||
return (intro, Vec::new(), None);
|
||||
}
|
||||
let Some(url) = db_url else {
|
||||
return (intro, Vec::new());
|
||||
return (intro, Vec::new(), None);
|
||||
};
|
||||
let Some(table) = crate::table::bind_table_name(&arr) else {
|
||||
return (intro, Vec::new());
|
||||
return (intro, Vec::new(), None);
|
||||
};
|
||||
let data = select_page_data(url, &table, args, 200);
|
||||
let limit = args
|
||||
.get("paginate")
|
||||
.and_then(|p| p.get("limit"))
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(200);
|
||||
let offset = args
|
||||
.get("paginate")
|
||||
.and_then(|p| p.get("offset"))
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(0);
|
||||
let data = select_page_data(url, &table, args, limit, offset);
|
||||
let total = data.get("total").and_then(|v| v.as_i64());
|
||||
let rows = data
|
||||
.get("rows")
|
||||
.and_then(|v| v.as_array())
|
||||
@@ -161,7 +173,7 @@ fn resolve_main(args: &Value, db_url: Option<&str>) -> (String, Vec<Map<String,
|
||||
.into_iter()
|
||||
.filter_map(|v| v.as_object().cloned())
|
||||
.collect();
|
||||
(intro, items)
|
||||
(intro, items, total)
|
||||
}
|
||||
|
||||
/// Run the page's DB query: `where` (with `{param}` placeholders resolved from
|
||||
@@ -171,6 +183,7 @@ fn select_page_data(
|
||||
table: &str,
|
||||
args: &Value,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Value {
|
||||
let mut where_v = args.get("query").cloned();
|
||||
if let Some(m) = where_v.as_ref().and_then(|v| v.as_object()) {
|
||||
@@ -187,11 +200,20 @@ fn select_page_data(
|
||||
}
|
||||
}
|
||||
let order = args.get("order").and_then(|v| v.as_str());
|
||||
if order.is_some_and(|s| !s.trim().is_empty()) {
|
||||
db::select_order(url, table, limit, where_v.as_ref(), order, None, None)
|
||||
} else {
|
||||
db::select(url, table, limit, where_v.as_ref())
|
||||
}
|
||||
let paginate = args.get("paginate").is_some();
|
||||
db::select_order(
|
||||
url,
|
||||
table,
|
||||
limit,
|
||||
where_v.as_ref(),
|
||||
order.filter(|s| !s.trim().is_empty()),
|
||||
if paginate || offset > 0 {
|
||||
Some(offset)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
None,
|
||||
)
|
||||
.unwrap_or(json!({ "rows": [] }))
|
||||
}
|
||||
|
||||
@@ -318,9 +340,103 @@ a:hover { color:var(--accent); }
|
||||
.article-body { line-height:1.75; color:var(--ink); }
|
||||
.article-p { margin:0 0 1rem; white-space:pre-line; }
|
||||
.article-h2 { margin:1.5rem 0 .75rem; }
|
||||
.article-code { background:#f5f5f4; border:1px solid var(--line); border-radius:6px; padding:1rem; overflow-x:auto; font-size:.9rem; }
|
||||
.article-body.md { line-height: 1.75; }
|
||||
.article-body.md pre { background:#f5f5f4; border:1px solid var(--line); border-radius:6px; padding:1rem; overflow-x:auto; }
|
||||
.article-body.md code { font-size:.9em; }
|
||||
.pagination { display:flex; gap:1rem; align-items:center; margin:1.5rem 0; font-size:.95rem; }
|
||||
.pagination a { color:var(--accent); text-decoration:none; }
|
||||
.pagination a:hover { text-decoration:underline; }
|
||||
.pagination .page-status { color:var(--muted); }
|
||||
"#;
|
||||
|
||||
fn head_html(args: &Value, default_title: &str) -> String {
|
||||
let meta = args.get("meta").and_then(|v| v.as_object());
|
||||
let page_title = meta
|
||||
.and_then(|m| m.get("title"))
|
||||
.map(text)
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or_else(|| default_title.to_string());
|
||||
let mut s = format!("<title>{}</title>", esc(&page_title));
|
||||
if let Some(m) = meta {
|
||||
for (k, v) in m {
|
||||
if k == "title" {
|
||||
continue;
|
||||
}
|
||||
let val = text(v);
|
||||
if val.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match k.as_str() {
|
||||
"description" => {
|
||||
s.push_str(&format!(
|
||||
"<meta name=\"description\" content=\"{}\"/>",
|
||||
esc(&val)
|
||||
));
|
||||
}
|
||||
"canonical" => {
|
||||
s.push_str(&format!("<link rel=\"canonical\" href=\"{}\"/>", esc(&val)));
|
||||
}
|
||||
k if k.starts_with("og:") => {
|
||||
s.push_str(&format!(
|
||||
"<meta property=\"{}\" content=\"{}\"/>",
|
||||
esc(k),
|
||||
esc(&val)
|
||||
));
|
||||
}
|
||||
other => {
|
||||
s.push_str(&format!(
|
||||
"<meta name=\"{}\" content=\"{}\"/>",
|
||||
esc(other),
|
||||
esc(&val)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn render_pagination(args: &Value, total: i64, item_count: usize) -> String {
|
||||
let Some(p) = args.get("paginate") else {
|
||||
return String::new();
|
||||
};
|
||||
let offset = p.get("offset").and_then(|v| v.as_i64()).unwrap_or(0);
|
||||
let limit = p.get("limit").and_then(|v| v.as_i64()).unwrap_or(10);
|
||||
if limit <= 0 {
|
||||
return String::new();
|
||||
}
|
||||
let path = p
|
||||
.get("path")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("/")
|
||||
.to_string();
|
||||
let mut s = String::from("<nav class=\"pagination\" aria-label=\"Pagination\">");
|
||||
if offset > 0 {
|
||||
let prev = offset.saturating_sub(limit);
|
||||
s.push_str(&format!(
|
||||
"<a class=\"page-prev\" href=\"{}?offset={}\">← Previous</a> ",
|
||||
esc(&path),
|
||||
prev
|
||||
));
|
||||
}
|
||||
let end = offset + item_count as i64;
|
||||
s.push_str(&format!(
|
||||
"<span class=\"page-status\">{}–{} of {}</span> ",
|
||||
offset + 1,
|
||||
end.min(total),
|
||||
total
|
||||
));
|
||||
if end < total {
|
||||
s.push_str(&format!(
|
||||
"<a class=\"page-next\" href=\"{}?offset={}\">Next →</a>",
|
||||
esc(&path),
|
||||
end
|
||||
));
|
||||
}
|
||||
s.push_str("</nav>");
|
||||
s
|
||||
}
|
||||
|
||||
pub fn render_page(args: &Value, db_url: Option<&str>, csrf: Option<&str>) -> String {
|
||||
render_page_ex(args, db_url, None, None, csrf)
|
||||
}
|
||||
@@ -350,7 +466,7 @@ pub fn render_page_ex(
|
||||
let nav = resolve_links(args.get("nav"), db_url);
|
||||
let side = resolve_links(args.get("sidebar"), db_url);
|
||||
let foot = resolve_links(args.get("footer"), db_url);
|
||||
let (intro, items) = resolve_main(args, db_url);
|
||||
let (intro, items, total) = resolve_main(args, db_url);
|
||||
|
||||
let has_side = args.get("sidebar").is_some() || !side.is_empty();
|
||||
let body_class = if has_side {
|
||||
@@ -390,6 +506,9 @@ pub fn render_page_ex(
|
||||
}
|
||||
main_html.push_str("</section>");
|
||||
}
|
||||
if let Some(t) = total {
|
||||
main_html.push_str(&render_pagination(args, t, items.len()));
|
||||
}
|
||||
}
|
||||
|
||||
format!(
|
||||
@@ -397,7 +516,7 @@ pub fn render_page_ex(
|
||||
<html lang="zh-CN"><head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<title>{title}</title>
|
||||
{head}
|
||||
<style>{SHELL_CSS}{extra}</style>
|
||||
</head>
|
||||
<body class="{body_class}">
|
||||
@@ -406,7 +525,7 @@ pub fn render_page_ex(
|
||||
<main class="{main_class}"{main_attrs}>{main_html}</main>
|
||||
<footer class="{foot_class}"{foot_attrs}>{foot_ul}</footer>
|
||||
</body></html>"#,
|
||||
title = esc(title),
|
||||
head = head_html(args, title),
|
||||
nav_class = slot_class(args, "nav", "topnav"),
|
||||
nav_attrs = slot_attrs("nav", &parts, args),
|
||||
nav_ul = render_ul(&nav, "nav"),
|
||||
@@ -458,7 +577,7 @@ pub fn render_fragment(args: &Value, db_url: Option<&str>) -> String {
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
let (intro, items) = resolve_main(args, db_url);
|
||||
let (intro, items, _total) = resolve_main(args, db_url);
|
||||
let mut body = String::new();
|
||||
if !intro.is_empty() {
|
||||
body.push_str(&format!("<div class=\"main-intro\">{intro}</div>"));
|
||||
@@ -554,47 +673,8 @@ fn render_article(it: &Map<String, Value>) -> String {
|
||||
));
|
||||
}
|
||||
if !body.is_empty() {
|
||||
s.push_str(&render_article_body(&body));
|
||||
s.push_str(&markdown::to_html(&body));
|
||||
}
|
||||
s.push_str("</article>");
|
||||
s
|
||||
}
|
||||
|
||||
/// Split a Markdown-ish article body into block elements.
|
||||
fn render_article_body(body: &str) -> String {
|
||||
let mut s = String::from("<div class=\"article-body\">");
|
||||
for para in body.split("\n\n") {
|
||||
let para = para.trim();
|
||||
if para.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(code) = para.strip_prefix("```") {
|
||||
let code = code.strip_suffix("```").unwrap_or(code);
|
||||
s.push_str(&format!(
|
||||
"<pre class=\"article-code\">{}</pre>",
|
||||
esc(code)
|
||||
));
|
||||
continue;
|
||||
}
|
||||
if let Some(h) = para.strip_prefix("## ") {
|
||||
s.push_str(&format!(
|
||||
"<h2 class=\"article-h2\">{}</h2>",
|
||||
esc(h.trim())
|
||||
));
|
||||
continue;
|
||||
}
|
||||
if let Some(h) = para.strip_prefix("# ") {
|
||||
s.push_str(&format!(
|
||||
"<h2 class=\"article-h2\">{}</h2>",
|
||||
esc(h.trim())
|
||||
));
|
||||
continue;
|
||||
}
|
||||
s.push_str(&format!(
|
||||
"<p class=\"article-p\">{}</p>",
|
||||
esc(para).replace('\n', "<br/>")
|
||||
));
|
||||
}
|
||||
s.push_str("</div>");
|
||||
s
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//! RSS 2.0 feed assembly (content-site W4).
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
fn esc(s: &str) -> String {
|
||||
s.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
.replace('"', """)
|
||||
}
|
||||
|
||||
fn cell_str(v: &Value) -> String {
|
||||
match v {
|
||||
Value::Null => String::new(),
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Bool(b) => b.to_string(),
|
||||
Value::Number(n) => n.to_string(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn pick<'a>(m: &'a serde_json::Map<String, Value>, keys: &[&str]) -> Option<&'a Value> {
|
||||
keys.iter().find_map(|k| m.get(*k))
|
||||
}
|
||||
|
||||
/// Build RSS 2.0 XML from channel metadata and row maps.
|
||||
pub fn build_rss(
|
||||
title: &str,
|
||||
link: &str,
|
||||
description: &str,
|
||||
items: &[Value],
|
||||
) -> String {
|
||||
let mut body = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<rss version="2.0"><channel>
|
||||
<title>{t}</title>
|
||||
<link>{l}</link>
|
||||
<description>{d}</description>
|
||||
"#,
|
||||
t = esc(title),
|
||||
l = esc(link),
|
||||
d = esc(description),
|
||||
);
|
||||
for row in items {
|
||||
let Some(m) = row.as_object() else {
|
||||
continue;
|
||||
};
|
||||
let item_title = pick(m, &["title", "标题"])
|
||||
.map(cell_str)
|
||||
.unwrap_or_default();
|
||||
let item_link = pick(m, &["link", "href", "链接", "slug"])
|
||||
.map(cell_str)
|
||||
.unwrap_or_default();
|
||||
let item_desc = pick(m, &["description", "summary", "摘要", "body", "正文"])
|
||||
.map(cell_str)
|
||||
.unwrap_or_default();
|
||||
let pub_date = pick(m, &["pubDate", "published", "created_at", "发布"])
|
||||
.map(cell_str)
|
||||
.unwrap_or_default();
|
||||
let full_link = if item_link.starts_with("http") {
|
||||
item_link.clone()
|
||||
} else if item_link.starts_with('/') {
|
||||
format!("{link}{item_link}")
|
||||
} else if !item_link.is_empty() {
|
||||
format!("{link}/{item_link}")
|
||||
} else {
|
||||
link.to_string()
|
||||
};
|
||||
body.push_str("<item>");
|
||||
body.push_str(&format!("<title>{}</title>", esc(&item_title)));
|
||||
body.push_str(&format!("<link>{}</link>", esc(&full_link)));
|
||||
body.push_str(&format!(
|
||||
"<description>{}</description>",
|
||||
esc(&item_desc)
|
||||
));
|
||||
if !pub_date.is_empty() {
|
||||
body.push_str(&format!("<pubDate>{}</pubDate>", esc(&pub_date)));
|
||||
}
|
||||
body.push_str("</item>");
|
||||
}
|
||||
body.push_str("</channel></rss>");
|
||||
body
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn rss_contains_item() {
|
||||
let xml = build_rss(
|
||||
"Blog",
|
||||
"http://example.com",
|
||||
"Feed",
|
||||
&[json!({"title": "Hi", "slug": "/post/a", "summary": "text"})],
|
||||
);
|
||||
assert!(xml.contains("<rss"));
|
||||
assert!(xml.contains("<title>Hi</title>"));
|
||||
}
|
||||
}
|
||||
@@ -531,3 +531,50 @@ pub fn project_rows(binds: &[Value], rows: &[Value]) -> Value {
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
|
||||
const META_KEY_KEYS: &[&str] = &["键", "key", "name"];
|
||||
const META_VAL_KEYS: &[&str] = &["值", "value"];
|
||||
|
||||
/// SEO / OpenGraph meta table → `{title, description, og:…, canonical, …}`.
|
||||
pub fn as_meta_map(table: &Value) -> Map<String, Value> {
|
||||
let mut out = Map::new();
|
||||
match table {
|
||||
Value::Array(rows) => {
|
||||
for row in rows {
|
||||
let Some(obj) = row.as_object() else {
|
||||
continue;
|
||||
};
|
||||
let key = META_KEY_KEYS
|
||||
.iter()
|
||||
.find_map(|k| obj.get(*k))
|
||||
.map(|v| normalize_ref(&meta_text(v)))
|
||||
.unwrap_or_default();
|
||||
let val = META_VAL_KEYS
|
||||
.iter()
|
||||
.find_map(|k| obj.get(*k))
|
||||
.map(|v| meta_text(v))
|
||||
.unwrap_or_default();
|
||||
if !key.is_empty() {
|
||||
out.insert(key, json!(val));
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Object(m) => {
|
||||
for (k, v) in m {
|
||||
out.insert(k.clone(), json!(meta_text(v)));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn meta_text(v: &Value) -> String {
|
||||
match v {
|
||||
Value::Null => String::new(),
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Bool(b) => b.to_string(),
|
||||
Value::Number(n) => n.to_string(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
@@ -123,6 +123,7 @@ pub enum HostFn {
|
||||
CollectionClear = 121,
|
||||
CookieParse = 122,
|
||||
MultipartParse = 123,
|
||||
MarkdownParse = 124,
|
||||
}
|
||||
|
||||
|
||||
@@ -243,6 +244,7 @@ impl HostFn {
|
||||
121 => Self::CollectionClear,
|
||||
122 => Self::CookieParse,
|
||||
123 => Self::MultipartParse,
|
||||
124 => Self::MarkdownParse,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -366,6 +368,7 @@ impl HostFn {
|
||||
"host_collection_clear" | "collection_clear" => Self::CollectionClear,
|
||||
"host_cookie_parse" | "cookie_parse" => Self::CookieParse,
|
||||
"host_multipart_parse" | "multipart_parse" => Self::MultipartParse,
|
||||
"host_markdown_parse" | "markdown_parse" => Self::MarkdownParse,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -476,6 +479,7 @@ impl HostFn {
|
||||
Self::CollectionClear => "host_collection_clear",
|
||||
Self::CookieParse => "host_cookie_parse",
|
||||
Self::MultipartParse => "host_multipart_parse",
|
||||
Self::MarkdownParse => "host_markdown_parse",
|
||||
Self::WritebackRecord => "host_writeback_record",
|
||||
Self::WritebackGet => "host_writeback_get",
|
||||
Self::WritebackClear => "host_writeback_clear",
|
||||
@@ -560,6 +564,7 @@ impl HostFn {
|
||||
Self::CollectionClear => &["value"],
|
||||
Self::CookieParse => &["text", "is_response"],
|
||||
Self::MultipartParse => &["body", "boundary"],
|
||||
Self::MarkdownParse => &["text"],
|
||||
Self::WritebackRecord => &["value"],
|
||||
Self::WritebackGet | Self::WritebackClear => &[],
|
||||
Self::WritebackList => &[],
|
||||
@@ -842,6 +847,7 @@ pub fn call_host(
|
||||
HostFn::CollectionClear => super::collection::collection_clear(require(bound, "value")?),
|
||||
HostFn::CookieParse => net::cookie_parse(require(bound, "text")?, bound.get("is_response")),
|
||||
HostFn::MultipartParse => net::multipart_parse(require(bound, "body")?, require(bound, "boundary")?),
|
||||
HostFn::MarkdownParse => net::markdown_parse(require(bound, "text")?),
|
||||
HostFn::OuterCallLine => Ok(Value::Int(
|
||||
ctx.call_site_lines
|
||||
.first()
|
||||
|
||||
@@ -448,6 +448,26 @@ pub fn multipart_parse(body: &Value, boundary: &Value) -> Result<Value, String>
|
||||
Ok(Value::List(parts))
|
||||
}
|
||||
|
||||
/// Parse Markdown / GFM into HTML (pure transform, no network I/O).
|
||||
pub fn markdown_parse(text: &Value) -> Result<Value, String> {
|
||||
let md = as_text(text, "text")?;
|
||||
Ok(Value::Text(markdown_to_html(md)))
|
||||
}
|
||||
|
||||
fn markdown_to_html(md: &str) -> String {
|
||||
use pulldown_cmark::{html, Options, Parser};
|
||||
let mut opts = Options::empty();
|
||||
opts.insert(
|
||||
Options::ENABLE_STRIKETHROUGH
|
||||
| Options::ENABLE_TABLES
|
||||
| Options::ENABLE_TASKLISTS,
|
||||
);
|
||||
let parser = Parser::new_ext(md, opts);
|
||||
let mut html_out = String::new();
|
||||
html::push_html(&mut html_out, parser);
|
||||
html_out
|
||||
}
|
||||
|
||||
/// Extract `data:` payloads from an SSE body (ignores comments / event: / id:).
|
||||
pub fn sse_data_payloads(text: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
@@ -981,4 +1001,15 @@ data: [DONE]\n\
|
||||
.iter()
|
||||
.any(|(k, v)| k == "value" && matches!(v, Value::Text(t) if t == "file body")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markdown_parse_basic() {
|
||||
let md = Value::Text("# Hello\n\nA **bold** word.".into());
|
||||
let out = markdown_parse(&md).unwrap();
|
||||
let Value::Text(html) = out else {
|
||||
panic!("expected text html");
|
||||
};
|
||||
assert!(html.contains("<h1"));
|
||||
assert!(html.contains("<strong>bold</strong>"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
title: web content smoke (W4)
|
||||
description: SEO meta + paginate bag (offline ABI).
|
||||
import web:ext/web/web.mq.md
|
||||
import plugin:lib/plugin.mq.md
|
||||
import sys:lib/sys.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*p = > plugin.native_path name="web"*
|
||||
1. `p`
|
||||
> plugin.load path=`p`
|
||||
2. *
|
||||
> sys.exit code=1
|
||||
|
||||
`meta` =
|
||||
|
||||
| 行 | 键 | 值 |
|
||||
|----|-----|-----|
|
||||
| 1 | title | My Site |
|
||||
| 2 | description | A demo site |
|
||||
| 3 | og:type | website |
|
||||
|
||||
*page = > web.page title="Home"*
|
||||
*page = > page.meta meta=`meta`*
|
||||
*mm = page[^meta]*
|
||||
*m = mm[^title]*
|
||||
1. `m` == "My Site"
|
||||
> print text=meta-ok
|
||||
2. *
|
||||
> print text=meta-fail
|
||||
|
||||
*page = > page.paginate offset=0 limit=5 path="/"*
|
||||
*poff = page[^paginate][^offset]*
|
||||
1. `poff` == 0
|
||||
> print text=paginate-ok
|
||||
2. *
|
||||
> print text=paginate-fail
|
||||
|
||||
`rows` =
|
||||
|
||||
| 行 | title | slug | summary |
|
||||
|----|-------|------|---------|
|
||||
| 1 | Hello | /a | First post |
|
||||
|
||||
*feed = > web_rss_build title="Blog" link="http://example.com" description="Demo" items=`rows`*
|
||||
1. `feed` != ""
|
||||
> print text=rss-ok
|
||||
2. *
|
||||
> print text=rss-fail
|
||||
@@ -1724,6 +1724,22 @@ auth-bad-reject-ok",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_web_content_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-content-smoke.mq.md",
|
||||
"meta-ok
|
||||
paginate-ok
|
||||
rss-ok",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ext_web_db_w2_smoke() {
|
||||
// W2 data layer: transactions, connection pooling, pagination, query
|
||||
@@ -2299,6 +2315,14 @@ fn lib_net_multipart_parse() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_net_markdown_parse() {
|
||||
assert_out(
|
||||
"tests/lib/net-markdown.mq.md",
|
||||
"markdown-ok",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_net_openai_sse() {
|
||||
assert_out(
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
title: lib/net markdown_parse smoke
|
||||
import net:lib/net.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
*html = > net.markdown_parse text="# Title\n\nHello **world**."*
|
||||
1. `html` != ""
|
||||
> print text=markdown-ok
|
||||
2. *
|
||||
> print text=markdown-fail
|
||||
Reference in new issue
Block a user