feat(web): form_load SSR prefill and safe {id} desk routes

Edit pages can stamp compose_form_load to hydrate forms from DB by route id without author JS. Part slots use {part} so pathParamNames can inject {id} again.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-18 12:50:59 +08:00
1 parent 98018fc63b
commit 3f96592c99
9 files changed
+199 -14

No files matched your search

+8
View File
@@ -356,6 +356,14 @@ Embed a form into the page main slot. Optional `target` / `form_slot` (CSS id, e
*> web_compose_form page=`self` form=`form` id=`id` target=`target`*
## compose_form_load
+ `table`
+ `id_param`="id"
Prefill the composed form from DB using route/query `id` (desk edit pages).
*> web_compose_form_load page=`self` table=`table` id_param=`id_param`*
## compose_auth_form
+ `action`
+ `submit`=""
+8
View File
@@ -335,6 +335,14 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
*> web_compose_form page=`self` form=`表单` id=`id` target=`表单插槽`*
## 表单载入
+ `表`
+ `id参数`="id"
编辑页:按路由/查询参数中的 id 从数据库预填已装配表单,无需作者 JS 拉行。
*> web_compose_form_load page=`self` table=`表` id_param=`id参数`*
## 鉴权表单
+ `动作`
+ `提交`=""
@@ -0,0 +1,24 @@
package compose
import (
"fmt"
"strings"
)
// ComposeFormLoad stamps page.form_load so render prefills the composed form
// from DB by route/query id (desk edit pages without author JS).
func ComposeFormLoad(page any, table, idParam string) (any, error) {
obj := asObject(page)
table = strings.TrimSpace(table)
if table == "" {
return nil, fmt.Errorf("compose_form_load requires non-empty table")
}
spec := map[string]any{"table": table}
if s := strings.TrimSpace(idParam); s != "" {
spec["id_param"] = s
} else {
spec["id_param"] = "id"
}
obj["form_load"] = spec
return obj, nil
}
@@ -0,0 +1,32 @@
package compose
import "testing"
func TestComposeFormLoad(t *testing.T) {
page := map[string]any{"title": "Edit"}
out, err := ComposeFormLoad(page, "posts", "")
if err != nil {
t.Fatal(err)
}
obj, ok := out.(map[string]any)
if !ok {
t.Fatalf("want map, got %T", out)
}
load, ok := obj["form_load"].(map[string]any)
if !ok {
t.Fatalf("missing form_load: %#v", obj)
}
if load["table"] != "posts" {
t.Fatalf("table=%v", load["table"])
}
if load["id_param"] != "id" {
t.Fatalf("id_param=%v", load["id_param"])
}
}
func TestComposeFormLoadRequiresTable(t *testing.T) {
_, err := ComposeFormLoad(map[string]any{}, " ", "id")
if err == nil {
t.Fatal("expected error for empty table")
}
}
+16 -6
View File
@@ -684,6 +684,9 @@ func RenderBodyCtx(formBag map[string]any, formID string, data, errors any, csrf
if formBag != nil {
rowID = cellStr(formBag["id"])
}
if rowID == "" {
rowID = fieldText(dataM, "id")
}
showMeta := true
if formBag != nil {
if v, ok := formBag["show_meta"].(bool); ok {
@@ -692,21 +695,28 @@ func RenderBodyCtx(formBag map[string]any, formID string, data, errors any, csrf
}
var body strings.Builder
body.WriteString(`<div class="site-form">`)
if showMeta {
fmt.Fprintf(&body, `<p class="meta">table=<code>%s</code> · action=<code>%s</code> · id=<code>%s</code></p>`,
esc(tableName), esc(action), esc(heading))
}
hasFile := false
hasMarkdown := false
for _, f := range fields {
if fm, ok := f.(map[string]any); ok {
ty, _ := fm["type"].(string)
if strings.EqualFold(ty, "file") {
hasFile = true
break
}
if strings.EqualFold(ty, "markdown") {
hasMarkdown = true
}
}
}
formClass := "site-form"
if hasMarkdown {
formClass += " editor-skin"
}
body.WriteString(`<div class="` + formClass + `">`)
if showMeta {
fmt.Fprintf(&body, `<p class="meta">table=<code>%s</code> · action=<code>%s</code> · id=<code>%s</code></p>`,
esc(tableName), esc(action), esc(heading))
}
body.WriteString(`<form method="post" action="` + esc(postTo) + `"`)
if hasFile {
body.WriteString(` enctype="multipart/form-data"`)
@@ -10,3 +10,15 @@ func TestGoMuxPattern(t *testing.T) {
t.Fatalf("got %q", got)
}
}
func TestPathParamNamesIncludesID(t *testing.T) {
got := pathParamNames("/desk/posts/{id}")
if len(got) != 1 || got[0] != "id" {
t.Fatalf("got %#v", got)
}
got = pathParamNames("/post/{slug}")
if len(got) != 1 || got[0] != "slug" {
t.Fatalf("got %#v", got)
}
}
+25 -7
View File
@@ -112,7 +112,9 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", st.handleHome)
mux.HandleFunc("GET /_part/{id}", st.handleHomePart)
// Part slot uses {part} (not {id}) so dynamic routes like /desk/posts/{id}
// do not collide with Go ServeMux duplicate wildcard names.
mux.HandleFunc("GET /_part/{part}", st.handleHomePart)
mux.HandleFunc("GET /_form/{id}", st.handleFormGet)
mux.HandleFunc("POST /_form/{id}", st.handleFormPost)
@@ -125,14 +127,14 @@ func NewHandler(appBag map[string]any, entryDir string) (http.Handler, error) {
}
if strings.Contains(routePath, "{") {
mux.HandleFunc("GET "+goMuxPattern(routePath), st.makeDynamicPage(pageV, routePath))
mux.HandleFunc("GET "+goMuxPattern(routePath)+"/_part/{id}", st.makeDynamicPart(pageV, routePath))
mux.HandleFunc("GET "+goMuxPattern(routePath)+"/_part/{part}", st.makeDynamicPart(pageV, routePath))
} else {
pv := pageV
mux.HandleFunc("GET "+routePath, func(w http.ResponseWriter, r *http.Request) {
st.writePage(w, r, pv)
})
mux.HandleFunc("GET "+routePath+"/_part/{id}", func(w http.ResponseWriter, r *http.Request) {
st.writePart(w, r, pv, r.PathValue("id"))
mux.HandleFunc("GET "+routePath+"/_part/{part}", func(w http.ResponseWriter, r *http.Request) {
st.writePart(w, r, pv, r.PathValue("part"))
})
}
}
@@ -298,7 +300,7 @@ func (st *state) handleHome(w http.ResponseWriter, r *http.Request) {
}
func (st *state) handleHomePart(w http.ResponseWriter, r *http.Request) {
st.writePart(w, r, st.page, r.PathValue("id"))
st.writePart(w, r, st.page, r.PathValue("part"))
}
func (st *state) preparePage(page map[string]any, r *http.Request) map[string]any {
@@ -306,6 +308,21 @@ func (st *state) preparePage(page map[string]any, r *http.Request) map[string]an
assets.MergeSiteHead(p, st.siteHead)
if r != nil {
withNavAuth(p, r.Header.Get("Cookie"))
params, _ := p["params"].(map[string]any)
if params == nil {
params = map[string]any{}
} else {
params = cloneMap(params)
}
for k, vs := range r.URL.Query() {
if len(vs) == 0 {
continue
}
if _, exists := params[k]; !exists {
params[k] = vs[0]
}
}
p["params"] = params
}
return p
}
@@ -431,7 +448,7 @@ func (st *state) makeDynamicPart(page map[string]any, pattern string) http.Handl
params[name] = r.PathValue(name)
}
injectParams(p, params)
st.writePart(w, r, p, r.PathValue("id"))
st.writePart(w, r, p, r.PathValue("part"))
}
}
@@ -791,7 +808,8 @@ func pathParamNames(pattern string) []string {
if strings.HasPrefix(seg, "{") && strings.HasSuffix(seg, "}") {
name := strings.TrimSuffix(strings.TrimPrefix(seg, "{"), "}")
name = strings.TrimPrefix(name, "*")
if name != "" && name != "id" {
// Include "id" — part slots use {part}, so route {id} is safe for PathValue.
if name != "" {
names = append(names, name)
}
}
+54 -1
View File
@@ -1120,9 +1120,59 @@ func pageFormHTML(page map[string]any) (formID string, html string) {
ctx.ReturnPath = r
ctx.Path = r
}
return id, form.RenderBodyCtx(frm, id, nil, nil, "", ctx)
data := resolveFormData(page, "")
return id, form.RenderBodyCtx(frm, id, data, nil, "", ctx)
}
// resolveFormData returns stamped form_data, or loads a DB row via form_load + params.
func resolveFormData(page map[string]any, dbURL string) map[string]any {
if page == nil {
return nil
}
if raw, ok := page["form_data"].(map[string]any); ok && raw != nil && len(raw) > 0 {
return raw
}
if dbURL == "" {
if u, ok := page["_db_url"].(string); ok {
dbURL = u
}
}
load, ok := page["form_load"].(map[string]any)
if !ok || load == nil || dbURL == "" {
return nil
}
table := text(load["table"])
if table == "" {
table = text(load["表"])
}
if table == "" {
return nil
}
idParam := text(load["id_param"])
if idParam == "" {
idParam = text(load["id参数"])
}
if idParam == "" {
idParam = "id"
}
id := ""
if params, ok := page["params"].(map[string]any); ok {
id = text(params[idParam])
}
if id == "" {
return nil
}
row, err := db.Get(dbURL, table, id)
if err != nil || row == nil {
return nil
}
if m, ok := row.(map[string]any); ok {
return m
}
return nil
}
func pushIntro(buf *strings.Builder, intro string) {
pushIntroAndForm(buf, intro, nil)
}
@@ -1217,6 +1267,9 @@ func RenderPage(page map[string]any, dbURL string, partID string) string {
if page == nil {
page = map[string]any{}
}
if dbURL != "" {
page["_db_url"] = dbURL
}
if partID != "" {
parts, _ := page["parts"].(map[string]any)
if parts != nil {
+20
View File
@@ -76,6 +76,7 @@ extern int web_compose_form(char *args_json, char **out_json, char **err_msg);
extern int web_compose_auth_form(char *args_json, char **out_json, char **err_msg);
extern int web_compose_nav_brand(char *args_json, char **out_json, char **err_msg);
extern int web_compose_client(char *args_json, char **out_json, char **err_msg);
extern int web_compose_form_load(char *args_json, char **out_json, char **err_msg);
extern int web_app_new(char *args_json, char **out_json, char **err_msg);
extern int web_app_route(char *args_json, char **out_json, char **err_msg);
extern int web_db_update(char *args_json, char **out_json, char **err_msg);
@@ -176,6 +177,7 @@ static int register_core(void) {
if (host_register((char *)"web_compose_auth_form", (char *)"page,action,submit,form_id,err_id,target,next,kind", web_compose_auth_form) != 0) return 1;
if (host_register((char *)"web_compose_nav_brand", (char *)"page,title,href,logo,logo_light,theme_key", web_compose_nav_brand) != 0) return 1;
if (host_register((char *)"web_compose_client", (char *)"page,source,bridge,wasm", web_compose_client) != 0) return 1;
if (host_register((char *)"web_compose_form_load", (char *)"page,table,id_param", web_compose_form_load) != 0) return 1;
if (host_register((char *)"web_render", (char *)"page", web_render) != 0) return 1;
if (host_register((char *)"web_db_new", (char *)"url", web_db_new) != 0) return 1;
if (host_register((char *)"web_db_init", (char *)"url,name,fields", web_db_init) != 0) return 1;
@@ -914,6 +916,24 @@ func web_compose_client(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.i
return replyJSON(outJSON, errMsg, out, err)
}
//export web_compose_form_load
func web_compose_form_load(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)
if err != nil {
return replyJSON(outJSON, errMsg, nil, err)
}
table, _ := argStr(args, "table")
if table == "" {
table, _ = argStr(args, "表")
}
idParam, _ := argStr(args, "id_param")
if idParam == "" {
idParam, _ = argStr(args, "id参数")
}
out, err := compose.ComposeFormLoad(args["page"], table, idParam)
return replyJSON(outJSON, errMsg, out, err)
}
//export web_app_new
func web_app_new(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
args, err := parseArgs(argsJSON)