Make Web an executable handbook with recursive Markdown layouts

This commit is contained in:
cflmy committed 2026-11-08 21:50:01 +08:00
1 parent cc5277d2b5
commit 5080136d65
84 files changed
+3394 -957

No files matched your search

+32 -24
View File
@@ -26,6 +26,7 @@ import (
"github.com/marqdo/marqdo/plugins/web/internal/httpx"
"github.com/marqdo/marqdo/plugins/web/internal/middleware"
"github.com/marqdo/marqdo/plugins/web/internal/page"
"github.com/marqdo/marqdo/plugins/web/internal/plugin"
)
//export web_render_nodes
@@ -123,27 +124,32 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
}
}
}
homeArgs := map[string]any{"title": "Marqdo"}
var homeMeta map[string]string
documentPage := func(f artifact.ArtifactFile) (map[string]any, error) {
title := f.Meta["title"]
if title == "" {
title = f.Meta["标题"]
}
body, structured, err := artifact.RenderFile(f, plugin.RunArtifact)
if err != nil {
return nil, err
}
pg := page.New(map[string]any{"title": title, "intro": body})
stampArtifactData(pg, f.Meta)
if structured {
pg["artifact_html"] = artifact.RenderHTMLPage(title, body)
}
return pg, nil
}
home := page.New(map[string]any{"title": "Marqdo"})
for _, f := range files {
if f.Kind == "web" && (f.Route == "/" || f.Rel == "index.mq.md") {
title := f.Meta["title"]
if title == "" {
title = f.Meta["标题"]
if f.Kind == "web" && f.Route == "/" {
home, err = documentPage(f)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
if title == "" {
title = "Marqdo"
}
homeArgs = map[string]any{
"title": title,
"intro": artifact.MarkdownHTML(f.Body),
}
homeMeta = f.Meta
break
}
}
home := page.New(homeArgs)
stampArtifactData(home, homeMeta)
a := app.New(map[string]any{
"page": home,
"db": args["db"],
@@ -156,15 +162,10 @@ func web_serve_root(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
if f.Route == "/" {
continue
}
title := f.Meta["title"]
if title == "" {
title = f.Meta["标题"]
pg, err := documentPage(f)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
pg := page.New(map[string]any{
"title": title,
"intro": artifact.MarkdownHTML(f.Body),
})
stampArtifactData(pg, f.Meta)
out, err := app.Route(a, f.Route, pg)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
@@ -230,6 +231,13 @@ func web_inspect(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
if root, ok := argStr(args, "root"); ok && root != "" {
files, err := artifact.ScanRoot(root)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
return replyJSON(outJSON, errMsg, artifact.InspectBag(nil, files), nil)
}
a := asPageMap(args["app"])
if a != nil {
if insp, ok := a["inspect"].(map[string]any); ok {
+145 -18
View File
@@ -9,7 +9,6 @@ import (
"strings"
"github.com/marqdo/marqdo/plugins/web/internal/render"
"github.com/marqdo/marqdo/plugins/web/internal/table"
)
// MetaType returns canonical kind: web | endpoint | "" from flat frontmatter map.
@@ -92,19 +91,77 @@ func ParseFrontmatter(src string) (meta map[string]string, body string) {
return meta, body
}
// RenderNodes turns a unified View table into an HTML fragment.
// Columns: type|slot|value|attrs|style (ZH: 类型|槽|值|属性|样式).
// RenderNodes renders the existing five-column View schema recursively. Container
// value cells hold more View rows; markdown leaves hold ordinary Markdown text.
func RenderNodes(nodes any) (string, error) {
raw := table.AsRows(nodes)
list, _ := raw.([]any)
var b strings.Builder
b.WriteString(`<div class="mq-view">`)
for _, item := range list {
b.WriteString(`<style>` + LayoutCSS + `</style><div class="mq-view">`)
if err := renderNodes(&b, nodes, 0); err != nil {
return "", err
}
b.WriteString(`</div>`)
return b.String(), nil
}
// Fixed runtime geometry, shared by offline previews and served Documents.
// Authors choose row/column instead of embedding CSS or HTML in content cells.
const LayoutCSS = `.mq-view{max-width:72rem;margin:auto;padding:1.5rem;line-height:1.6;font-family:system-ui,sans-serif}.mq-view *{box-sizing:border-box}.mq-view .mq-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,16rem),1fr));gap:1.5rem}.mq-view .mq-column{display:flex;flex-direction:column;gap:1.5rem}.mq-view .mq-node{min-width:0}.mq-view nav,.mq-view footer{padding-block:1rem}.mq-view footer{border-top:1px solid #d5dce5}.mq-view a{color:#2457a7}.mq-view img{max-width:100%;height:auto}.mq-view pre{overflow:auto}`
// Preserve typed value cells when normalizing column tables. General AsRows
// treats @ cells as text, which would stringify nested component tables.
func viewRows(nodes any) ([]any, error) {
switch v := nodes.(type) {
case nil:
return nil, nil
case []any:
return v, nil
case map[string]any:
if _, ok := v["type"].(string); ok {
return []any{v}, nil
}
if _, ok := v["类型"].(string); ok {
return []any{v}, nil
}
n := -1
for _, cell := range v {
col, ok := cell.([]any)
if !ok {
return nil, fmt.Errorf("View: expected a row or column table")
}
if n < 0 {
n = len(col)
} else if n != len(col) {
return nil, fmt.Errorf("View: column lengths differ")
}
}
rows := []any{}
for i := 0; i < n; i++ {
row := map[string]any{}
for key, cell := range v {
row[key] = cell.([]any)[i]
}
rows = append(rows, row)
}
return rows, nil
default:
return nil, fmt.Errorf("View: expected rows, got %T", nodes)
}
}
func renderNodes(b *strings.Builder, nodes any, depth int) error {
if depth > 64 {
return fmt.Errorf("View: nesting exceeds 64 levels")
}
rows, err := viewRows(nodes)
if err != nil {
return err
}
for i, item := range rows {
row, ok := item.(map[string]any)
if !ok {
continue
return fmt.Errorf("View row %d: expected a map", i+1)
}
ty := first(row, "type", "类型")
ty := strings.ToLower(first(row, "type", "类型"))
slot := first(row, "slot", "槽")
val := first(row, "value", "值")
attrs := first(row, "attrs", "属性")
@@ -116,23 +173,92 @@ func RenderNodes(nodes any) (string, error) {
if slot != "" {
class += " slot-" + html.EscapeString(slot)
}
switch strings.ToLower(ty) {
tag := ""
switch ty {
case "row", "横排":
tag = "div"
class += " mq-row"
case "column", "纵排":
tag = "div"
class += " mq-column"
case "nav", "导航":
tag = "nav"
case "header", "页头":
tag = "header"
case "footer", "页脚":
tag = "footer"
case "section", "区域":
tag = "section"
case "aside", "侧栏":
tag = "aside"
}
if tag != "" {
children := row["value"]
if children == nil {
children = row["值"]
}
if children == nil {
return fmt.Errorf("View row %d (%s): missing child rows in value", i+1, ty)
}
b.WriteString(`<` + tag + ` class="` + class + `">`)
if err := renderNodes(b, children, depth+1); err != nil {
return fmt.Errorf("View %s/%s: %w", ty, slot, err)
}
b.WriteString(`</` + tag + `>`)
continue
}
switch ty {
case "markdown", "正文":
b.WriteString(`<div class="` + class + `">` + render.MarkdownToHTML(val) + `</div>`)
case "title", "标题":
b.WriteString(`<h1 class="` + class + `">` + inline(val) + `</h1>`)
case "link", "链接":
href := attrs
if href == "" {
href = "#"
if attrs == "" {
attrs = "#"
}
b.WriteString(`<a class="` + class + `" href="` + html.EscapeString(href) + `">` + inline(val) + `</a>`)
b.WriteString(`<a class="` + class + `" href="` + html.EscapeString(attrs) + `">` + inline(val) + `</a>`)
case "html", "原文":
b.WriteString(`<div class="` + class + `">` + val + `</div>`)
default: // text
default:
value := row["value"]
if value == nil {
value = row["值"]
}
switch value.(type) {
case []any, map[string]any:
return fmt.Errorf("View row %d: unknown structural type %q", i+1, ty)
}
b.WriteString(`<p class="` + class + `">` + inline(val) + `</p>`)
}
}
b.WriteString(`</div>`)
return b.String(), nil
return nil
}
// RenderFile explicitly opts a Document into startup-time component assembly.
// Documents without view: main retain their existing Markdown/data-source path.
func RenderFile(f ArtifactFile, run func(string, map[string]any) (any, error)) (string, bool, error) {
view := metaString(f.Meta, "view", "视图")
if view == "" {
return MarkdownHTML(f.Body), false, nil
}
if view != "main" {
return "", false, fmt.Errorf("%s: view/视图 must be main", f.Rel)
}
if metaString(f.Meta, "data_source", "数据源") != "" {
return "", false, fmt.Errorf("%s: view main is startup assembly; use an ordinary Document for automatic data_source binding", f.Rel)
}
nodes, err := run(f.Path, nil)
if err != nil {
return "", false, fmt.Errorf("%s: view main: %w", f.Rel, err)
}
if nodes == nil {
return "", false, fmt.Errorf("%s: view main must return View rows", f.Rel)
}
html, err := RenderNodes(nodes)
if err != nil {
return "", false, fmt.Errorf("%s: %w", f.Rel, err)
}
return html, true, nil
}
func inline(s string) string {
@@ -159,7 +285,7 @@ func RenderHTMLPage(title, innerHTML string) string {
if t == "" {
t = "Marqdo"
}
return "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>" + t +
return "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>" + t +
"</title></head><body class=\"mq-document\"><main>" + innerHTML + "</main></body></html>"
}
@@ -313,6 +439,7 @@ func InspectBag(app map[string]any, declared []ArtifactFile) map[string]any {
}
}
return map[string]any{
"_type": "web_inspection",
"declared": dec,
"system": SystemRoutes(),
}
+90 -1
View File
@@ -1,6 +1,9 @@
package artifact
import "testing"
import (
"strings"
"testing"
)
func TestMetaType(t *testing.T) {
if MetaType(map[string]string{"type": "web"}) != "web" {
@@ -53,3 +56,89 @@ func contains(s, sub string) bool {
return false
})())
}
func TestNestedLayoutKeepsMarkdownLeavesAndSiblingOrder(t *testing.T) {
leaf := func(slot, text string) any { return map[string]any{"type": "markdown", "slot": slot, "value": text} }
nodes := []any{map[string]any{"type": "footer", "value": []any{
map[string]any{"type": "row", "slot": "footer", "value": []any{
leaf("brand", "### Marqdo\n\nReadable **documents**."),
map[string]any{"类型": "横排", "槽": "links", "值": []any{
leaf("docs", "### Docs\n\n[Guide](/guide)"),
leaf("community", "### Community\n\n[About](/about)"),
}},
}},
}}}
got, err := RenderNodes(nodes)
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"<footer", "mq-row", "slot-links", "<strong>documents</strong>", `href="/guide"`, `href="/about"`} {
if !strings.Contains(got, want) {
t.Fatalf("missing %q: %s", want, got)
}
}
if strings.Index(got, "slot-brand") > strings.Index(got, "slot-docs") || strings.Index(got, "slot-docs") > strings.Index(got, "slot-community") {
t.Fatal("component order changed")
}
if strings.Contains(got, "map[") {
t.Fatal("nested data was stringified")
}
}
func TestNestedColumnTableRetainsTypedValue(t *testing.T) {
nodes := map[string]any{"@": []any{1}, "type": []any{"column"}, "value": []any{[]any{map[string]any{"type": "markdown", "value": "# Leaf"}}}}
got, err := RenderNodes(nodes)
if err != nil || !strings.Contains(got, "<h1") || !strings.Contains(got, "Leaf") {
t.Fatalf("%v: %s", err, got)
}
}
func TestInvalidChildrenAreDiagnosed(t *testing.T) {
for _, value := range []any{"<div>not child rows</div>", []any{"bad row"}} {
if _, err := RenderNodes([]any{map[string]any{"type": "row", "value": value}}); err == nil {
t.Fatalf("accepted %v", value)
}
}
var deep any = []any{map[string]any{"type": "text", "value": "end"}}
for i := 0; i < 66; i++ {
deep = []any{map[string]any{"type": "column", "value": deep}}
}
if _, err := RenderNodes(deep); err == nil {
t.Fatal("unbounded nesting")
}
}
func TestViewDocumentExecutesOnlyAnExplicitMain(t *testing.T) {
calls := 0
run := func(path string, args map[string]any) (any, error) {
calls++
return []any{map[string]any{"type": "markdown", "value": "# Composed"}}, nil
}
f := ArtifactFile{Path: "index.mq.md", Rel: "index.mq.md", Meta: map[string]string{}, Body: "# Ordinary"}
body, structured, err := RenderFile(f, run)
if err != nil || structured || calls != 0 || !strings.Contains(body, "Ordinary") {
t.Fatalf("ordinary: %v %v %d", err, structured, calls)
}
f.Meta["视图"] = "main"
body, structured, err = RenderFile(f, run)
if err != nil || !structured || calls != 1 || !strings.Contains(body, "Composed") {
t.Fatalf("view: %v %v %d", err, structured, calls)
}
f.Meta["视图"] = "typo"
if _, _, err = RenderFile(f, run); err == nil || calls != 1 {
t.Fatal("invalid view must fail before execution")
}
}
func TestViewDocumentRejectsAnEmptyAssemblyAndAutomaticDataSource(t *testing.T) {
f := ArtifactFile{Path: "index.mq.md", Rel: "index.mq.md", Meta: map[string]string{"view": "main"}}
calls := 0
run := func(string, map[string]any) (any, error) { calls++; return nil, nil }
if _, _, err := RenderFile(f, run); err == nil || !strings.Contains(err.Error(), "must return View rows") {
t.Fatalf("empty assembly: %v", err)
}
f.Meta["data_source"] = "posts"
if _, _, err := RenderFile(f, run); err == nil || calls != 1 {
t.Fatalf("data source silently ignored: %v", err)
}
}
@@ -2,6 +2,7 @@ package render
import (
"fmt"
"path/filepath"
"strings"
"testing"
@@ -11,7 +12,20 @@ import (
)
func TestAnlianPostsResolve(t *testing.T) {
url := "sqlite:/home/cflmy/work/marqdo/examples/anlian-mq/data/anlian-mq.db"
url := "sqlite:" + filepath.Join(t.TempDir(), "anlian.db")
fields := []any{
map[string]any{"name": "title", "type": "text", "nullable": false},
map[string]any{"name": "summary", "type": "text"},
map[string]any{"name": "board", "type": "text"},
map[string]any{"name": "slug", "type": "text"},
}
if _, err := db.Init(url, "posts", fields); err != nil {
t.Fatal(err)
}
rows := []any{map[string]any{"title": "欢迎", "summary": "Portable test fixture", "board": "demo", "slug": "welcome"}}
if _, err := db.Insert(url, "posts", rows); err != nil {
t.Fatal(err)
}
card := map[string]any{
"属性": []any{"title", "body", "meta", "href"},
"值": []any{"posts.title", "posts.summary", "posts.board", "posts.slug"},
+6 -1
View File
@@ -1272,7 +1272,6 @@ func resolveFormData(page map[string]any, dbURL string) map[string]any {
return nil
}
func pushIntro(buf *strings.Builder, intro string) {
pushIntroAndForm(buf, intro, nil)
}
@@ -1364,6 +1363,12 @@ func renderFragment(page map[string]any, dbURL, slot string) string {
// RenderPage builds full-page HTML (or a part fragment when partID is set).
func RenderPage(page map[string]any, dbURL string, partID string) string {
// Explicit View Documents already own their structure and document shell.
if partID == "" && page != nil {
if html, ok := page["artifact_html"].(string); ok {
return html
}
}
if page == nil {
page = map[string]any{}
}
+1 -1
View File
@@ -272,7 +272,7 @@ static int register_core(void) {
if (host_register((char *)"web_render_document", (char *)"page,body,db,title", web_render_document) != 0) return 1;
if (host_register((char *)"web_dom_markdown", (char *)"text", web_dom_markdown) != 0) return 1;
if (host_register((char *)"web_serve_root", (char *)"root,host,port,db,static_dir,middleware", web_serve_root) != 0) return 1;
if (host_register((char *)"web_inspect", (char *)"app", web_inspect) != 0) return 1;
if (host_register((char *)"web_inspect", (char *)"app,root", web_inspect) != 0) return 1;
if (host_register((char *)"web_app_use", (char *)"app,middleware", web_app_use) != 0) return 1;
if (host_register((char *)"web_route_use", (char *)"route,middleware", web_route_use) != 0) return 1;
return 0;