form

package module
v0.0.27 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 21, 2026 License: MIT Imports: 3 Imported by: 0

README

tinywasm/form

Project Badges

Fast form generation from Go structs for TinyGo + WASM. Uses tinywasm/fmt exclusively (no standard library).

Quick Start

type User struct {
    Name  string `placeholder:"Full Name"`
    Email string
    Role  string `options:"admin:Admin,user:User"`
}

f, err := form.New("parent-id", &User{Name: "John"})
html := f.RenderHTML()    // render to HTML string

Public API

form.New(parentID string, structPtr any) (*Form, error)

Creates a Form from a struct pointer.

  • Reflects exported fields → matches each to a registered Input by name/alias
  • Copies struct field values into inputs
  • Returns error if any exported field has no matching input
  • Form id = parentID + "." + lowercase(structName)
  • Default action = /lowercase(structName), method = POST
form.RegisterInput(inputs ...input.Input)

Registers custom input types globally. Called with ("", "") as dummy init args.

form.SetGlobalClass(classes ...string)

Sets CSS classes applied to all <form> elements.

(*Form) Methods
Method Description
GetID() string Returns form's HTML id
SetSSR(bool) *Form Enables SSR mode (adds method, action, <button type="submit">)
RenderHTML() string Generates form HTML
Validate() error Validates all inputs, returns first error
SyncValues() error Copies input values back into the source struct
OnSubmit(func(any) error) *Form Sets WASM submit callback
OnMount() WASM only — sets up event delegation
OnUnmount() WASM only — cleanup (handled by dom)
Input(fieldName string) input.Input Returns input for a field name
SetOptions(field string, opts ...fmt.KeyValue) *Form Sets options on a field's input
SetValues(field string, values ...string) *Form Sets value on a field's input
Render Modes
Mode SetSSR Output
WASM/Fetch (default) false <form id="..."> inputs </form>
SSR true <form id="..." method="POST" action="/..."> inputs <button type="submit"> </form>

Struct Tags

Tag Format Description
options "key1:text1,key2:text2" Options for select/radio/datalist
placeholder "My placeholder" HTML placeholder
title "My tooltip" HTML title attribute
validate "false" Skip validation for this field
type User struct {
    Name     string `placeholder:"Full Name" title:"Enter your full name"`
    Role     string `options:"admin:Admin,user:User"`
    Internal string `validate:"false"`
}

Field Matching

New() matches each exported struct field to a registered Input:

  1. lowercase(FieldName) vs Input's htmlName or aliases
  2. lowercase(StructName.FieldName) vs Input's aliases

Matching is case-insensitive. First match wins.

Input Interface

type Input interface {
    dom.Component  // GetID(), SetID(), RenderHTML(), Children()
    HTMLName() string                  // HTML type ("text", "email", etc.)
    FieldName() string                 // struct field name
    ValidateField(value string) error  // field validation
    Clone(parentID, name string) Input // creates new instance
}

WASM Event Flow

dom.Mount("root", myForm)
  → myForm.RenderHTML() injected into DOM
  → myForm.OnMount() called
      → one "input"/"change" listener at <form> level
          → finds input by event.target.id
          → calls SetValues(val) + ValidateField(val)
      → one "submit" listener
          → PreventDefault()
          → SyncValues() → Validate() → OnSubmit callback

Documentation Index

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetTagOptions added in v0.0.2

func GetTagOptions(fieldTag string) ([]fmt.KeyValue, bool)

GetTagOptions extracts options from a struct field tag using fmt.TagPairs.

func ParseOptionsTag added in v0.0.2

func ParseOptionsTag(tag string) []fmt.KeyValue

ParseOptionsTag parses "key1:text1,key2:text2" format into []fmt.KeyValue.

func RegisterInput added in v0.0.2

func RegisterInput(inputs ...input.Input)

RegisterInput registers input types for field mapping.

func SetGlobalClass added in v0.0.2

func SetGlobalClass(classes ...string)

Types

type Form

type Form struct {
	Value  any
	Inputs []input.Input
	// contains filtered or unexported fields
}

Form represents a form instance.

func New

func New(parentID string, structPtr any) (*Form, error)

New creates a new Form from a struct pointer. parentID: ID of the parent DOM element where the form will be mounted. Returns an error if any exported field has no matching registered input.

func (*Form) GetID added in v0.0.17

func (f *Form) GetID() string

GetID returns the html id that group the form

func (*Form) Input added in v0.0.2

func (f *Form) Input(fieldName string) input.Input

Input returns the input with the given field name, or nil if not found.

func (*Form) OnSubmit added in v0.0.2

func (f *Form) OnSubmit(fn func(any) error) *Form

OnSubmit sets the callback for form submission in WASM mode.

func (*Form) ParentID added in v0.0.2

func (f *Form) ParentID() string

ParentID returns the ID of the parent element.

func (*Form) RenderHTML added in v0.0.2

func (f *Form) RenderHTML() string

RenderHTML renders the form based on its SSR mode.

func (*Form) SetID added in v0.0.17

func (f *Form) SetID(id string)

SetID sets the html id that group the form

func (*Form) SetOptions added in v0.0.2

func (f *Form) SetOptions(fieldName string, opts ...fmt.KeyValue) *Form

SetOptions sets options for the input matching the given field name.

func (*Form) SetSSR added in v0.0.2

func (f *Form) SetSSR(enabled bool) *Form

SetSSR enables or disables SSR mode for this form.

func (*Form) SetValues added in v0.0.2

func (f *Form) SetValues(fieldName string, values ...string) *Form

SetValues sets values for the input matching the given field name.

func (*Form) SyncValues added in v0.0.2

func (f *Form) SyncValues() error

SyncValues synchronizes all input values back to the source struct.

func (*Form) Validate added in v0.0.2

func (f *Form) Validate() error

Validate validates all inputs and returns the first error found.

func (*Form) ValidateData added in v0.0.26

func (f *Form) ValidateData(action byte, data ...any) error

ValidateData satisfies crudp.DataValidator via Go duck typing. It validates the struct in data[0] using this form's configured input rules.

Design:

  • Reuses the existing form instance — no allocation per call.
  • Uses pre-computed fieldIndices (set in New) for O(1) field access.
  • Calls inp.ValidateField(val) which is a pure function — no state mutation.
  • Thread-safe: reads only immutable form config, never writes.

The action byte follows crudp conventions: 'c'=create, 'r'=read, 'u'=update, 'd'=delete. All actions run the same validation; handlers may add action-specific logic on top.

Directories

Path Synopsis
example
web command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL