form

package
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

📝 Form

Form provides a high-level form state and validation engine for Kitex applications. It is inspired by React Hook Form and provides strongly-typed form management, automatic mapping from raw DOM map data to Go structs, and asynchronous submission handling.

✨ Features

  • 🔒 Strongly Typed: Manage form state using strongly-typed Go structs.
  • ⚡ Reactive State: Integrates seamlessly with Kitex's VDOM using kitex.UseState.
  • 🛡️ Validation Engine: Built-in support for synchronous validation rules.
  • 🚦 Submission State: Automatically tracks IsSubmitting state during async operations.
  • 🧩 Manual Error Handling: Set or clear arbitrary errors manually with SetError.

🚀 Getting Started

1. Define your form structure

Create a Go struct that represents your form data. You can use form tags (or fall back to json tags or field names) to map field names from the UI; string values from text inputs are automatically converted for numeric and boolean fields:

type UserForm struct {
	Name     string `form:"name"`
	Age      int    `form:"age"`
	IsActive bool   `form:"is_active"`
}
2. Initialize the hook

Inside a Kitex functional component, initialize the form using form.Use:

package main

import (
	"fmt"

	"github.com/masterkeysrd/kite/extras/form"
	"github.com/masterkeysrd/kite/extras/kitex"
	"github.com/masterkeysrd/kite/style"
)

var MyForm = kitex.FC("MyForm", func(_ kitex.NoProps) kitex.Node {
	formAPI := form.Use(form.Options[UserForm]{
		InitialValues: UserForm{Name: "Default User", Age: 18},
		Validate: func(values UserForm) map[string]string {
			errors := make(map[string]string)
			if len(values.Name) < 3 {
				errors["name"] = "Name must be at least 3 characters"
			}
			return errors
		},
	})

	onSubmit := func(values UserForm) error {
		// Handle API request or state update here
		fmt.Printf("Submitting: %+v\n", values)
		return nil // returning an error populates the "root" error
	}

	state := formAPI.State()

	// ... Render your UI ...
3. Connect to the UI

Use kitex.Form or manually wire form elements to the HandleSubmit function:

	return kitex.Form(kitex.FormProps{
		OnSubmit: formAPI.HandleSubmit(onSubmit),
	},
		kitex.Box.Style(
			style.S().Margin(0, 0, 1, 0),
			kitex.Input(kitex.InputProps{
				Name:  "name",
				Value: state.Values.Name,
			}),
			kitex.If(state.Errors["name"] != "", func() kitex.Node {
				return kitex.Span.Style(style.S().Foreground(style.Hex("#f87171")), kitex.Text(state.Errors["name"]))
			}),
		),
		
		kitex.Box.Style(
			style.S().Margin(0, 0, 1, 0),
			kitex.Checkbox(kitex.CheckboxProps{
				Name:    "is_active",
				Checked: state.Values.IsActive,
			}),
		),

		kitex.Button(kitex.ButtonProps{
			Type:     "submit",
			Disabled: state.IsSubmitting,
		}, kitex.IfElse(state.IsSubmitting, kitex.Text("Saving..."), kitex.Text("Save"))),

		kitex.If(state.Errors["root"] != "", func() kitex.Node {
			return kitex.Text(state.Errors["root"])
		}),
	)
})

🛠 API Reference

form.Use(Options[T]) API[T]

Initializes the form hook with configuration options and returns the API interface.

Options[T]
  • InitialValues T: The starting values of the form struct.
  • Validate func(T) map[string]string: A callback executed before submission. Should return a map of field names to error messages. Return an empty map or nil if there are no errors.
API[T]
  • State() State[T]: Returns the current snapshot of the form.
  • HandleSubmit(onSubmit func(T) error) func(map[string]any): Wraps a submit handler function and returns a DOM event handler that parses raw form values into struct T, validates them, and invokes onSubmit.
  • SetError(key string, message string): Manually set an error for a given field key. Passing an empty message "" clears the error for that key.
State[T]
  • Values T: The current fully parsed values.
  • Errors map[string]string: Current validation or manual errors.
  • IsSubmitting bool: true while the onSubmit function is executing.
  • IsValid bool: true if Errors map is empty.

Documentation

Overview

Package form provides a high-level form state and validation engine for Kite applications. It is inspired by React Hook Form and provides strongly-typed form management, automatic mapping from DOM events to Go structs, and asynchronous submission handling.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type API

type API[T any] struct {
	Ref               kitex.Ref[*element.FormElement]
	State             func() State[T]
	HandleSubmit      func(func(T) error) func(map[string]any)
	HandleSubmitAsync func(func(context.Context, T) error) func(map[string]any)
	SetError          func(string, string)
	ClearErrors       func(...string)
	Reset             func(...T)
}

API provides refs, state access, submission handlers, and error/reset helpers.

func Use

func Use[T any](opts Options[T]) API[T]

Use initializes and returns a typed form API for struct T.

type Options

type Options[T any] struct {
	InitialValues T
	Validate      func(T) map[string]string
	Mode          ValidationMode
}

Options configures the form hook.

type State

type State[T any] struct {
	Values       T
	Errors       map[string]string
	IsSubmitting bool
	IsValid      bool
	IsDirty      bool
	Touched      map[string]bool
	SubmitCount  int
}

State stores form values, field errors, and submission/interaction metadata.

type ValidationMode

type ValidationMode uint8

ValidationMode controls when Options.Validate runs for a form with Ref attached.

const (
	// ValidateOnSubmit validates only when the form is submitted (default).
	ValidateOnSubmit ValidationMode = iota
	// ValidateOnBlur validates touched fields whenever a control loses focus.
	ValidateOnBlur
	// ValidateOnChange validates whenever a control value changes.
	ValidateOnChange
)

Jump to

Keyboard shortcuts

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