` + esc(md) + `
diff --git a/Cargo.lock b/Cargo.lock index 1108d29..9a68b64 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -410,8 +410,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index b44d073..5c4c0e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,6 +52,7 @@ libc = { version = "0.2", optional = true } [target.'cfg(target_arch = "wasm32")'.dependencies] # No `wasmbind`: keeps cdylib free of wasm-bindgen imports (raw mq_* ABI). chrono = { version = "0.4", default-features = false, features = ["alloc", "std"] } +getrandom = { version = "=0.2.17", default-features = false, features = ["js"] } [workspace] members = [ diff --git a/crates/marqdo-wasm/js/marqdo-bridge.js b/crates/marqdo-wasm/js/marqdo-bridge.js index 2c847d8..8f18e11 100644 --- a/crates/marqdo-wasm/js/marqdo-bridge.js +++ b/crates/marqdo-wasm/js/marqdo-bridge.js @@ -197,6 +197,20 @@ export function eventArgsFromDom(ev, valueFromSel) { args.fields = fields; } } + if (ev && (ev.type === "scroll" || ev.type === "resize")) { + try { + const doc = typeof document !== "undefined" ? document.documentElement : null; + const body = typeof document !== "undefined" ? document.body : null; + const scrollTop = (doc && (doc.scrollTop || 0)) || (body && body.scrollTop) || 0; + const height = doc ? (doc.scrollHeight - doc.clientHeight) || 1 : 1; + const ratio = Math.max(0, Math.min(1, scrollTop / height)); + args.scroll_top = scrollTop; + args.scroll_max = height; + args.scroll_ratio = ratio; + } catch (_) { + /* ignore */ + } + } return args; } @@ -721,75 +735,88 @@ function runObserveEffect(exports, spec, onError) { const kind = String(spec.kind || spec.type || "intersect").toLowerCase(); const sel = String(spec.sel || ""); const thenFn = spec.then; - const id = String(spec.id || `obs${++observeSeq}`); - const el = qsOne(sel); - if (!el || !thenFn) return; + const baseId = String(spec.id || `obs${++observeSeq}`); + const nodes = qsAll(sel); + if (!nodes.length || (!thenFn && !spec.add_class)) return; - const prev = observeHandles.get(id); - if (prev) { - try { - prev.disconnect(); - } catch (_) { - /* ignore */ - } - } - - const fire = (payload) => { - try { - const result = call(exports, thenFn, payload); - if (!result.ok) { - if (onError) onError(result.error); - return; + nodes.forEach((el, idx) => { + const id = nodes.length === 1 ? baseId : `${baseId}_${idx}`; + const prev = observeHandles.get(id); + if (prev) { + try { + prev.disconnect(); + } catch (_) { + /* ignore */ } - applyEffects(exports, result.value, { onError }); - } catch (e) { - if (onError) onError(String(e)); } - }; - if (kind === "resize" && typeof ResizeObserver !== "undefined") { - const ro = new ResizeObserver((entries) => { - const en = entries[0]; - const cr = en?.contentRect; - fire({ - ok: true, - kind: "resize", - id, - width: cr ? cr.width : 0, - height: cr ? cr.height : 0, - }); - }); - ro.observe(el); - observeHandles.set(id, ro); - return; - } + const fire = (payload) => { + try { + const result = call(exports, thenFn, payload); + if (!result.ok) { + if (onError) onError(result.error); + return; + } + applyEffects(exports, result.value, { onError }); + } catch (e) { + if (onError) onError(String(e)); + } + }; - if (typeof IntersectionObserver !== "undefined") { - const io = new IntersectionObserver( - (entries) => { + if (kind === "resize" && typeof ResizeObserver !== "undefined") { + const ro = new ResizeObserver((entries) => { const en = entries[0]; - if (!en) return; + const cr = en?.contentRect; fire({ ok: true, - kind: "intersect", + kind: "resize", id, - intersecting: !!en.isIntersecting, - ratio: en.intersectionRatio, + width: cr ? cr.width : 0, + height: cr ? cr.height : 0, }); - if (spec.once && en.isIntersecting) { - try { - io.disconnect(); - } catch (_) { - /* ignore */ + }); + ro.observe(el); + observeHandles.set(id, ro); + return; + } + + if (typeof IntersectionObserver !== "undefined") { + const opts = { threshold: spec.threshold != null ? Number(spec.threshold) : 0.1 }; + if (spec.rootMargin != null) opts.rootMargin = String(spec.rootMargin); + const io = new IntersectionObserver( + (entries) => { + const en = entries[0]; + if (!en) return; + if (en.isIntersecting && spec.add_class) { + for (const c of String(spec.add_class).split(/\s+/).filter(Boolean)) { + el.classList.add(c); + } } - observeHandles.delete(id); - } - }, - { threshold: spec.threshold != null ? Number(spec.threshold) : 0.1 }, - ); - io.observe(el); - observeHandles.set(id, io); - } + if (thenFn) { + fire({ + ok: true, + kind: "intersect", + id, + intersecting: !!en.isIntersecting, + ratio: en.intersectionRatio, + target_id: el.id || "", + }); + } + if (spec.once && en.isIntersecting) { + try { + io.disconnect(); + } catch (_) { + /* ignore */ + } + observeHandles.delete(id); + } + }, + opts, + ); + io.observe(el); + observeHandles.set(id, io); + } + }); } function buildFetchInit(spec) { diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md index 102aa9b..560a128 100644 --- a/ext/web/web.mq.md +++ b/ext/web/web.mq.md @@ -370,6 +370,28 @@ re-renders the same branded page on failure. No author JS. *> web_compose_auth_form page=`self` action=`action` submit=`submit` form_id=`form_id` err_id=`err_id` target=`target` next=`next` kind=`kind`* +## compose_nav_brand + + `title`="" + + `href`="/" + + `logo`="" + + `logo_light`="" + + `theme_key`="mq-theme" + +SSR topnav brand (logo + title), theme toggle, and drawer button. Interactive +behavior stays in `client.mq.md` via `compose_client` / `client_embed`. + +*> web_compose_nav_brand page=`self` title=`title` href=`href` logo=`logo` logo_light=`logo_light` theme_key=`theme_key`* + +## compose_client + + `source` + + `bridge`="/static/marqdo-bridge.js" + + `wasm`="/static/marqdo_wasm.wasm" + +Stamp `page.client` so render injects official bridge auto-mount (`data-mq-wasm` / +`data-mq-source-url`). Build with `marqdo wasm build -o static` first. + +*> web_compose_client page=`self` source=`source` bridge=`bridge` wasm=`wasm`* + ## render + `db`=None @@ -635,6 +657,15 @@ Field table + rules table; submit writes through `# db`. *> web_form_rules form=`self` rules=`rules`* +## labels + + `submit`="Submit" + + `cancel`="cancel" + + `cancel_href`="" + +Localized submit / cancel copy for rendered forms. + +*> web_form_labels form=`self` submit=`submit` cancel=`cancel` cancel_href=`cancel_href`* + ## validate + `rules`=None + `data` diff --git a/ext/web/网页.mq.md b/ext/web/网页.mq.md index a721f94..1b9a0fc 100644 --- a/ext/web/网页.mq.md +++ b/ext/web/网页.mq.md @@ -351,6 +351,27 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c *> web_compose_auth_form page=`self` action=`动作` submit=`提交` form_id=`表单id` err_id=`错误id` target=`表单插槽` next=`回跳` kind=`种类`* +## 导航品牌 + + `标题`="" + + `链接`="/" + + `标志`="" + + `浅色标志`="" + + `主题键`="mq-theme" + +SSR 顶栏刊名 Logo、主题切换钮与目录抽屉钮。交互写在 `client.mq.md`,配合 `客户端`。 + +*> web_compose_nav_brand page=`self` title=`标题` href=`链接` logo=`标志` logo_light=`浅色标志` theme_key=`主题键`* + +## 客户端 + + `源` + + `桥`="/static/marqdo-bridge.js" + + `wasm`="/static/marqdo_wasm.wasm" + +写入 `page.client`,渲染时注入官方 bridge 自启(`data-mq-wasm` / `data-mq-source-url`)。 +先 `marqdo wasm build -o public`(或站点 static 目录)。 + +*> web_compose_client page=`self` source=`源` bridge=`桥` wasm=`wasm`* + ## 渲染 + `数据库`=None @@ -609,6 +630,15 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c *> web_form_rules form=`self` rules=`规则`* +## 文案 + + `提交`="提交" + + `取消`="取消" + + `取消链接`="" + +表单提交钮 / 取消链接文案(默认英文 Submit/cancel 由渲染层回退)。 + +*> web_form_labels form=`self` submit=`提交` cancel=`取消` cancel_href=`取消链接`* + ## 校验 + `规则`=None + `数据` diff --git a/lib/browser.mq.md b/lib/browser.mq.md index 525d858..09b6ea9 100644 --- a/lib/browser.mq.md +++ b/lib/browser.mq.md @@ -44,6 +44,42 @@ Build set_class effect map. **`m` = > table.put in=None at=sel value=class** *> table.put in=None at="set_class" value=m* +## add_class + + `sel` + + `class` + +Build add_class effect map (classList.add; space-separated names OK). + +**`m` = > table.put in=None at=sel value=class** +*> table.put in=None at="add_class" value=m* + +## remove_class + + `sel` + + `class` + +Build remove_class effect map. + +**`m` = > table.put in=None at=sel value=class** +*> table.put in=None at="remove_class" value=m* + +## toggle_class + + `sel` + + `class` + +Build toggle_class effect map. + +**`m` = > table.put in=None at=sel value=class** +*> table.put in=None at="toggle_class" value=m* + +## set_style + + `sel` + + `style` + +Build set_style effect map; style is a map of CSS properties or a cssText string. + +**`m` = > table.put in=None at=sel value=style** +*> table.put in=None at="set_style" value=m* + ## set_attr + `sel` + `attrs` diff --git a/lib/浏览器.mq.md b/lib/浏览器.mq.md index 6a86fa2..72346fc 100644 --- a/lib/浏览器.mq.md +++ b/lib/浏览器.mq.md @@ -43,6 +43,42 @@ import table:lib/table.mq.md **`m` = > table.put in=None at=选择器 value=类** *> table.put in=None at="set_class" value=m* +## 加类 + + `选择器` + + `类` + +构造 add_class 效应(classList.add;可用空格分隔多个类名)。 + +**`m` = > table.put in=None at=选择器 value=类** +*> table.put in=None at="add_class" value=m* + +## 去类 + + `选择器` + + `类` + +构造 remove_class 效应。 + +**`m` = > table.put in=None at=选择器 value=类** +*> table.put in=None at="remove_class" value=m* + +## 切类 + + `选择器` + + `类` + +构造 toggle_class 效应。 + +**`m` = > table.put in=None at=选择器 value=类** +*> table.put in=None at="toggle_class" value=m* + +## 设样式 + + `选择器` + + `样式` + +构造 set_style 效应;样式为属性表或 cssText 字符串。 + +**`m` = > table.put in=None at=选择器 value=样式** +*> table.put in=None at="set_style" value=m* + ## 设属性 + `选择器` + `属性` diff --git a/plugins/web/abi_extra.go b/plugins/web/abi_extra.go index 68871b9..6be094c 100644 --- a/plugins/web/abi_extra.go +++ b/plugins/web/abi_extra.go @@ -174,6 +174,27 @@ func web_form_rules(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { return replyJSON(outJSON, errMsg, form.SetRules(formBag, args["rules"]), nil) } +//export web_form_labels +func web_form_labels(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { + args, err := parseArgs(argsJSON) + if err != nil { + return replyJSON(outJSON, errMsg, nil, err) + } + submit, _ := argStr(args, "submit") + if submit == "" { + submit, _ = argStr(args, "提交") + } + cancel, _ := argStr(args, "cancel") + if cancel == "" { + cancel, _ = argStr(args, "取消") + } + cancelHref, _ := argStr(args, "cancel_href") + if cancelHref == "" { + cancelHref, _ = argStr(args, "取消链接") + } + return replyJSON(outJSON, errMsg, form.SetLabels(asPageMap(args["form"]), submit, cancel, cancelHref), nil) +} + //export web_form_validate func web_form_validate(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int { args, err := parseArgs(argsJSON) diff --git a/plugins/web/internal/compose/compose_nav_brand.go b/plugins/web/internal/compose/compose_nav_brand.go new file mode 100644 index 0000000..d2a3cd7 --- /dev/null +++ b/plugins/web/internal/compose/compose_nav_brand.go @@ -0,0 +1,55 @@ +package compose + +import ( + "strings" +) + +// ComposeNavBrand stamps page.nav_brand for SSR topnav lockup (logo + title), +// theme toggle, and drawer button chrome. Client WASM only wires behavior. +func ComposeNavBrand(page any, title, href, logo, logoLight, themeKey string) (any, error) { + obj := asObject(page) + spec := map[string]any{} + if s := strings.TrimSpace(title); s != "" { + spec["title"] = s + } + if s := strings.TrimSpace(href); s != "" { + spec["href"] = s + } else { + spec["href"] = "/" + } + if s := strings.TrimSpace(logo); s != "" { + spec["logo"] = s + } + if s := strings.TrimSpace(logoLight); s != "" { + spec["logo_light"] = s + } + if s := strings.TrimSpace(themeKey); s != "" { + spec["theme_key"] = s + } else { + spec["theme_key"] = "mq-theme" + } + obj["nav_brand"] = spec + return obj, nil +} + +// ComposeClient stamps page.client so render injects official bridge auto-mount +// (data-mq-wasm / data-mq-source-url). Authors ship client.mq.md, not business JS. +func ComposeClient(page any, bridge, wasm, source string) (any, error) { + obj := asObject(page) + spec := map[string]any{} + if s := strings.TrimSpace(bridge); s != "" { + spec["bridge"] = s + } else { + spec["bridge"] = "/static/marqdo-bridge.js" + } + if s := strings.TrimSpace(wasm); s != "" { + spec["wasm"] = s + } else { + spec["wasm"] = "/static/marqdo_wasm.wasm" + } + if s := strings.TrimSpace(source); s != "" { + spec["source"] = s + } + obj["client"] = spec + return obj, nil +} diff --git a/plugins/web/internal/compose/compose_nav_brand_test.go b/plugins/web/internal/compose/compose_nav_brand_test.go new file mode 100644 index 0000000..fd27415 --- /dev/null +++ b/plugins/web/internal/compose/compose_nav_brand_test.go @@ -0,0 +1,32 @@ +package compose_test + +import ( + "testing" + + "github.com/marqdo/marqdo/plugins/web/internal/compose" +) + +func TestComposeNavBrandAndClient(t *testing.T) { + page := map[string]any{"title": "t"} + out, err := compose.ComposeNavBrand(page, "求道量子", "/", "/static/logo.png", "/static/logo-light.png", "mq-theme") + if err != nil { + t.Fatal(err) + } + m := out.(map[string]any) + b, ok := m["nav_brand"].(map[string]any) + if !ok || b["title"] != "求道量子" || b["logo"] != "/static/logo.png" { + t.Fatalf("nav_brand: %#v", m["nav_brand"]) + } + out, err = compose.ComposeClient(m, "", "", "/static/client.mq.md") + if err != nil { + t.Fatal(err) + } + m = out.(map[string]any) + c, ok := m["client"].(map[string]any) + if !ok || c["source"] != "/static/client.mq.md" { + t.Fatalf("client: %#v", m["client"]) + } + if c["bridge"] != "/static/marqdo-bridge.js" { + t.Fatalf("bridge default: %#v", c) + } +} diff --git a/plugins/web/internal/form/form.go b/plugins/web/internal/form/form.go index 588c579..7ad9424 100644 --- a/plugins/web/internal/form/form.go +++ b/plugins/web/internal/form/form.go @@ -68,6 +68,21 @@ func SetRules(formBag map[string]any, rules any) map[string]any { return out } +// SetLabels stamps localized submit / cancel button copy (and optional cancel href). +func SetLabels(formBag map[string]any, submit, cancel, cancelHref string) map[string]any { + out := cloneMap(formBag) + if s := strings.TrimSpace(submit); s != "" { + out["submit"] = s + } + if s := strings.TrimSpace(cancel); s != "" { + out["cancel"] = s + } + if s := strings.TrimSpace(cancelHref); s != "" { + out["cancel_href"] = s + } + return out +} + func cloneMap(m map[string]any) map[string]any { out := map[string]any{} for k, v := range m { @@ -758,9 +773,15 @@ func RenderBodyCtx(formBag map[string]any, formID string, data, errors any, csrf } body.WriteString("") } - fmt.Fprintf(&body, `
`, - esc(cancel)) + submitLabel := strOf(formBag, "submit", "") + if submitLabel == "" { + submitLabel = strOf(formBag, "提交", "") + } + if submitLabel == "" { + submitLabel = "Submit" + } + cancelLabel := strOf(formBag, "cancel", "") + if cancelLabel == "" { + cancelLabel = strOf(formBag, "取消", "") + } + if cancelLabel == "" { + cancelLabel = "cancel" + } + cancelHref := cancel + if c := strOf(formBag, "cancel_href", ""); c != "" { + cancelHref = c + } else if c := strOf(formBag, "取消链接", ""); c != "" { + cancelHref = c + } + fmt.Fprintf(&body, ``, + esc(submitLabel), esc(cancelHref), esc(cancelLabel)) body.WriteString(``) return body.String() } diff --git a/plugins/web/internal/form/form_test.go b/plugins/web/internal/form/form_test.go index 02816a0..d4df58c 100644 --- a/plugins/web/internal/form/form_test.go +++ b/plugins/web/internal/form/form_test.go @@ -68,3 +68,23 @@ func TestRenderContainsInputFields(t *testing.T) { } } } + +func TestRenderMarkdownAndLabels(t *testing.T) { + f := form.New("posts", "insert", "") + f = form.SetFields(f, []any{ + map[string]any{"字段": "content", "标签": "正文", "类型": "markdown", "必填": true}, + }) + f = form.SetLabels(f, "发布文章", "返回列表", "/desk/posts") + html := form.Render(f, "post", nil, nil, "") + for _, want := range []string{ + `data-mq-field="markdown"`, + `class="mq-markdown"`, + ">发布文章", + `href="/desk/posts"`, + ">返回列表", + } { + if !strings.Contains(html, want) { + t.Fatalf("missing %q in:\n%s", want, html) + } + } +} diff --git a/plugins/web/internal/render/chrome_brand.go b/plugins/web/internal/render/chrome_brand.go new file mode 100644 index 0000000..e56d2a1 --- /dev/null +++ b/plugins/web/internal/render/chrome_brand.go @@ -0,0 +1,222 @@ +package render + +import ( + "regexp" + "strings" + "unicode" + "unicode/utf8" +) + +// formatMetaDate shortens ISO timestamps to YYYY-MM-DD for card/article meta. +func formatMetaDate(s string) string { + s = strings.TrimSpace(s) + if len(s) >= 10 && s[4] == '-' && s[7] == '-' { + if len(s) == 10 || s[10] == 'T' || s[10] == ' ' { + return s[:10] + } + } + return s +} + +func navBrandSpec(page map[string]any) map[string]any { + if page == nil { + return nil + } + if b, ok := page["nav_brand"].(map[string]any); ok { + return b + } + return nil +} + +func themeKeyOf(page map[string]any) string { + if b := navBrandSpec(page); b != nil { + if k := text(b["theme_key"]); k != "" { + return k + } + if k := text(b["主题键"]); k != "" { + return k + } + } + return "mq-theme" +} + +func renderNavBrandHTML(page map[string]any) string { + b := navBrandSpec(page) + if b == nil { + return "" + } + title := text(b["title"]) + if title == "" { + title = text(b["标题"]) + } + if title == "" { + title = text(page["title"]) + } + href := text(b["href"]) + if href == "" { + href = text(b["链接"]) + } + if href == "" { + href = "/" + } + logo := text(b["logo"]) + if logo == "" { + logo = text(b["标志"]) + } + var s strings.Builder + s.WriteString(``) + if logo != "" { + s.WriteString(`]*>)(.*?)(
)`) + +func shouldDropcap(plain string) bool { + plain = strings.Join(strings.Fields(plain), "") + if plain == "" { + return false + } + if strings.HasPrefix(plain, "$$") { + return false + } + r, _ := utf8.DecodeRuneInString(plain) + if r == '$' || r == '\\' || r == '[' || r == '(' || unicode.IsDigit(r) { + return false + } + if unicode.In(r, unicode.Han) { + return true + } + return (r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') +} + +func stripTags(s string) string { + var b strings.Builder + in := false + for _, r := range s { + switch { + case r == '<': + in = true + case r == '>': + in = false + case !in: + b.WriteRune(r) + } + } + return b.String() +} + +// tuneDropcapHTML adds has-dropcap to the first eligible paragraph in article markdown HTML. +func tuneDropcapHTML(inner string) string { + m := firstPBlockRe.FindStringSubmatch(inner) + if m == nil { + return inner + } + plain := stripTags(m[3]) + if !shouldDropcap(plain) { + return inner + } + open := m[2] + if strings.Contains(open, "has-dropcap") { + return inner + } + if strings.Contains(open, `class="`) { + open = strings.Replace(open, `class="`, `class="has-dropcap `, 1) + } else if strings.Contains(open, `class='`) { + open = strings.Replace(open, `class='`, `class='has-dropcap `, 1) + } else { + open = strings.TrimSuffix(open, ">") + ` class="has-dropcap">` + } + loc := firstPBlockRe.FindStringIndex(inner) + if loc == nil { + return inner + } + return inner[:loc[0]] + m[1] + open + m[3] + m[4] + inner[loc[1]:] +} diff --git a/plugins/web/internal/render/chrome_brand_test.go b/plugins/web/internal/render/chrome_brand_test.go new file mode 100644 index 0000000..56cd979 --- /dev/null +++ b/plugins/web/internal/render/chrome_brand_test.go @@ -0,0 +1,27 @@ +package render + +import ( + "strings" + "testing" +) + +func TestFormatMetaDate(t *testing.T) { + if got := formatMetaDate("2026-09-17T13:41:04Z"); got != "2026-09-17" { + t.Fatalf("got %q", got) + } + if got := formatMetaDate("plain"); got != "plain" { + t.Fatalf("got %q", got) + } +} + +func TestTuneDropcapHTML(t *testing.T) { + in := "中文首段。
二段
" + out := tuneDropcapHTML(in) + if !strings.Contains(out, `class="has-dropcap"`) { + t.Fatalf("expected dropcap: %s", out) + } + skip := "$E=mc^2$
" + if got := tuneDropcapHTML(skip); strings.Contains(got, "has-dropcap") { + t.Fatalf("formula should skip: %s", got) + } +} diff --git a/plugins/web/internal/render/markdown.go b/plugins/web/internal/render/markdown.go index 32c9e15..5a331a2 100644 --- a/plugins/web/internal/render/markdown.go +++ b/plugins/web/internal/render/markdown.go @@ -34,5 +34,5 @@ func markdownToHTML(md string) string { if err := gm.Convert([]byte(md), &buf); err != nil { return `` + esc(md) + `