feat(17-01): repeater field type and the dependent dropdown save recheck

- cabana: type repeater with nested form.fields (text, textarea, number,
  checkbox, switch, dropdown, richeditor), prompt, minItems, maxItems,
  titleFrom; groups, style, nested repeaters and other types fail boot
- rows decoded before projection: only nested keys, coerced scalars,
  per-row required (field.index.nested), row bounds; ProjectWritableFields
  exempts repeater lists only, nestedValue unchanged
- nested richeditor values sanitized with notices under the row path
- dependent dropdowns rechecked on save, top level and per row; null when
  the sibling takes no choice, 422 form.dependent_invalid otherwise
- dependent-options accepts repeater.field; schema carries RepeaterForm
- backend lang repeater.max_items, repeater.min_items,
  form.dependent_invalid; TestCompanionsRepeaterSmoke; docs
This commit is contained in:
2026-10-12 15:24:01 +02:00
parent 71fa597830
commit 46835fd064
16 changed files with 961 additions and 43 deletions

View File

@@ -2,12 +2,16 @@ package cabana
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"reflect"
"strconv"
"strings"
"git.golem15.com/golem15/summercms/modules/pact"
"git.golem15.com/golem15/summercms/modules/phrasebook"
"git.golem15.com/golem15/summercms/modules/towel"
"github.com/goccy/go-yaml/ast"
)
@@ -78,6 +82,9 @@ func usesDependsOn(fields []FormField) bool {
if field.DependsOn != "" {
return true
}
if field.Form != nil && usesDependsOn(field.Form.Fields) {
return true
}
}
return false
}
@@ -98,6 +105,13 @@ func requireDependentProvider(ctl pact.AdminController, fields []FormField) erro
if field.DependsOn != "" {
return fmt.Errorf("field %s: dependsOn needs controller %s to implement pact.DependentOptionsProvider", field.Name, ctl.ID())
}
if field.Form != nil {
for _, inner := range field.Form.Fields {
if inner.DependsOn != "" {
return fmt.Errorf("field %s.%s: dependsOn needs controller %s to implement pact.DependentOptionsProvider", field.Name, inner.Name, ctl.ID())
}
}
}
}
return nil
}
@@ -106,8 +120,8 @@ func requireDependentProvider(ctl pact.AdminController, fields []FormField) erro
// that only an admin controller's save path supports: its checks run in the
// controller save and nowhere else.
func controllerFormOnly(field FormField) error {
if field.Type == richEditorType {
return fmt.Errorf("richeditor is supported in controller forms only")
if field.Type == richEditorType || field.Type == repeaterType {
return fmt.Errorf("%s is supported in controller forms only", field.Type)
}
if field.DependsOn != "" {
return fmt.Errorf("dependsOn is supported in controller forms only")
@@ -117,13 +131,29 @@ func controllerFormOnly(field FormField) error {
// dependentField is the dependsOn dropdown name of the controller's form, or
// false.
func dependentField(cc *CompiledController, name string) (FormField, bool) {
// dependentField is the dependsOn dropdown of the controller's form named
// by path: a top-level field name, or repeater.nested for a dropdown of a
// repeater row. The returned field carries the path as its Name.
func dependentField(cc *CompiledController, path string) (FormField, bool) {
if cc == nil || cc.Form == nil {
return FormField{}, false
}
outer, inner, nested := strings.Cut(path, ".")
for _, field := range cc.Form.Fields {
if field.Name == name && field.DependsOn != "" {
return field, true
if field.Name != outer {
continue
}
if !nested {
return field, field.DependsOn != ""
}
if field.Form == nil {
return FormField{}, false
}
for _, sub := range field.Form.Fields {
if sub.Name == inner && sub.DependsOn != "" {
sub.Name = path
return sub, true
}
}
}
return FormField{}, false
@@ -143,6 +173,8 @@ func dependentValue(v any) any {
return t
case bool:
return strconv.FormatBool(t)
case json.Number:
return t.String()
case float64:
return strconv.FormatFloat(t, 'f', -1, 64)
case int:
@@ -219,3 +251,132 @@ func (s *service) dependentOptionsRoute(w http.ResponseWriter, r *http.Request)
WriteData(w, http.StatusOK, out, map[string]any{"locale": locale})
})
}
// msgDependentInvalid is the 422 message of a dependent dropdown value that
// is not among the options for the submitted sibling value (backend::lang).
const msgDependentInvalid = "backend::lang.form.dependent_invalid"
// checkDependentValues rechecks every dependsOn dropdown of a save (D-08):
// at the top level when the dropdown or its sibling is written, and in every
// row of a written repeater. The controller's provider is asked with the
// sibling's submitted value (the stored one when only the dropdown is
// written). When the answer does not apply, the dropdown is stored null; when
// it applies, a value that is not among the options is a 422
// form.dependent_invalid on the field (field.index.nested in a row). Null is
// accepted here; required is checked by the rules.
func checkDependentValues(ctx context.Context, cc *CompiledController, tr *phrasebook.Translator, target any, projected map[string]any, op string) error {
if cc == nil || cc.Form == nil || !usesDependsOn(cc.Form.Fields) {
return nil
}
provider, ok := cc.Controller.(pact.DependentOptionsProvider)
if !ok || provider == nil {
return fmt.Errorf("cabana: controller %s has no DependentOptions", controllerID(cc))
}
cache := map[string]pact.DependentOptionSet{}
ask := func(path, sibling string, value any) (pact.DependentOptionSet, error) {
v := dependentValue(value)
key := path + "\x00" + fmt.Sprint(v)
if set, ok := cache[key]; ok {
return set, nil
}
set, err := provider.DependentOptions(ctx, path, map[string]any{sibling: v})
if err != nil {
return pact.DependentOptionSet{}, err
}
cache[key] = set
return set, nil
}
locCtx := towel.WithLocale(ctx, schemaLocale(ctx, tr))
message := translateKey(locCtx, tr, msgDependentInvalid)
details := map[string]any{}
for _, field := range cc.Form.Fields {
if field.DependsOn != "" && contextAllows(cc, field.Name, op) {
key, siblingKey := fillKeyOf(cc, field.Name), fillKeyOf(cc, field.DependsOn)
value, hasValue := projected[key]
sibling, hasSibling := projected[siblingKey]
if hasValue || hasSibling {
if !hasValue {
value = modelValue(target, key)
}
if !hasSibling {
sibling = modelValue(target, siblingKey)
}
set, err := ask(field.Name, field.DependsOn, sibling)
if err != nil {
return err
}
switch {
case !set.Applies:
projected[key] = nil
case !amongOptions(set, value):
details[field.Name] = []string{message}
}
}
}
if field.Type != repeaterType || field.Form == nil {
continue
}
rows, ok := repeaterRows(projected, fillKeyOf(cc, field.Name))
if !ok {
continue
}
for i, item := range rows {
row, ok := item.(map[string]any)
if !ok {
continue
}
for _, inner := range field.Form.Fields {
if inner.DependsOn == "" {
continue
}
set, err := ask(field.Name+"."+inner.Name, inner.DependsOn, row[inner.DependsOn])
if err != nil {
return err
}
switch {
case !set.Applies:
row[inner.Name] = nil
case !amongOptions(set, row[inner.Name]):
details[fmt.Sprintf("%s.%d.%s", field.Name, i, inner.Name)] = []string{message}
}
}
}
}
if len(details) > 0 {
return &ValidationError{Details: details}
}
return nil
}
// amongOptions reports whether value is null or one of the set's option
// values.
func amongOptions(set pact.DependentOptionSet, value any) bool {
v := dependentValue(value)
if v == nil {
return true
}
text, _ := v.(string)
for _, opt := range set.Options {
if opt.Value == text {
return true
}
}
return false
}
// modelValue is the current value of the model's column, dereferenced; nil
// when the column is missing or a nil pointer.
func modelValue(model any, column string) any {
v := reflect.ValueOf(model)
for v.Kind() == reflect.Pointer {
if v.IsNil() {
return nil
}
v = v.Elem()
}
f := fieldByColumn(v, column)
if !f.IsValid() || !f.CanInterface() {
return nil
}
return derefValue(f.Interface())
}