/// Type-safe decoding and validation of HTML form data. A port of the Gleam
/// package `formal` (hex.pm/packages/formal, Apache-2.0).
///
/// import form
///
/// pub type SignUp {
/// SignUp(email: String, password: String)
/// }
///
/// /// A schema that decodes a `SignUp` from form data.
/// fn signup_schema() -> form.Schema {
/// use email <- form.field("email", form.parse_email())
/// use password <- form.field("password", {
/// form.parse_string()
/// |> form.check_string_length_more_than(7)
/// })
/// use _ <- form.field("confirm", {
/// form.parse_string()
/// |> form.check_confirms(password)
/// })
/// form.success(SignUp(email: email, password: password))
/// }
///
/// A `Schema` describes how to decode a typed value from the key-value
/// string pairs an HTML form produces. `new` turns it into a `Form`; add
/// the submitted values (`add_values` takes `http.form_body(req)`'s list
/// as it is) and `run` gives either the decoded value, or the form with
/// errors attached, ready to re-render:
///
/// fn handle_submission(values: List<(String, String)>) {
/// match form.new(signup_schema()) |> form.add_values(values) |> form.run {
/// Ok(signup) -> // ... use the SignUp value
/// Error(f) -> // ... re-render, `form.field_error_messages(f, "email")`
/// }
/// }
///
/// Parsers (`parse_*`) extract a value from a field's input and are
/// _short-circuiting_: when one fails, the checks (`check_*`) chained after
/// it don't run, so `parse_int() |> check_int_more_than(0)` on `"abc"`
/// reports `[MustBeInt]`, nothing more. Checks don't short-circuit each
/// other: every failed check adds its error.
import std/float
import std/list
import std/result
import std/string
// ---- types -------------------------------------------------------------------
/// A form! Created from a `Schema` with the `new` function.
///
/// Supply values to a form with the `add_*` functions and then pass it to the
/// `run` function to get either the resulting value or any errors.
///
/// Use the `language` function to supply a new translation function to change
/// the language of the error messages returned by the `field_error_messages`
/// function. The default language is `en_gb` English.
pub opaque type Form
{ Form(
translator: fn(FieldError) -> String
, values: List<(String, String)>
, errors: List<(String, List)>
, run: RunFunction
)
}
type RunFunction = fn(
List<(String, String)>
, List<(String, List)>
)
-> (model, List<(String, List)>)
/// A description of how to decode a typed value from form data. This can be
/// used to create a new form object using the `new` function.
pub opaque type Schema { Schema(run: RunFunction) }
/// Why a field failed to parse or validate; `en_gb` and `en_us` translate
/// these into text for the user, or supply your own with `language`.
@derive Eq Show Debug
pub type FieldError
{ MustBePresent
, MustBeInt
, MustBeFloat
, MustBeEmail
, MustBePhoneNumber
, MustBeColour
, MustBeStringLengthMoreThan(limit: Int)
, MustBeStringLengthLessThan(limit: Int)
, MustBeIntMoreThan(limit: Int)
, MustBeIntLessThan(limit: Int)
, MustBeFloatMoreThan(limit: Float)
, MustBeFloatLessThan(limit: Float)
, MustBeAccepted
/// For confirmation of passwords, etc. Must match the first field.
, MustConfirm
/// For values that must be unique, e.g. user email addresses.
, MustBeUnique
, CustomError(message: String)
}
/// A parser extracts a value from form values, converting it to a desired
/// type and optionally validating the value. Parsers are used with the
/// `field` function.
///
/// See the `parse_*` and `check_*` functions for more information.
///
/// Functions that start with `parse_*` are _short-circuiting_, so any parser
/// functions that come afterwards will not be run. For example, given this
/// code:
///
/// form.parse_int() |> form.check_int_more_than(0)
///
/// If the input is not an int then `parse_int` will fail, causing
/// `check_int_more_than` not to run, so the errors will be `[MustBeInt]`.
pub opaque type Parser
{ Parser(
run: fn(List, CheckingStatus)
-> (value, CheckingStatus, List)
)
}
type CheckingStatus { Check, DontCheck }
// ---- forms -------------------------------------------------------------------
/// Create a new form from a schema.
///
/// Add values to the form with the `add_*` functions and use `run` to get
/// either the final value or some errors from the form and values.
///
/// ## Example
///
/// let schema = {
/// use name <- form.field("name", {
/// form.parse_string() |> form.check_not_empty
/// })
/// use age <- form.field("age", form.parse_int())
/// form.success(Person(name: name, age: age))
/// }
/// let f = form.new(schema)
pub fn new :: schema: Schema -> Form
{
Form(translator: en_gb, values: [], errors: [], run: schema.run)
}
/// Supply a translation function that will be used when converting any
/// `FieldError`s to text that can be presented to the user.
///
/// Built-in languages:
///
/// - `en_gb`
/// - `en_us`
///
/// These functions are named using the IETF language tag for the language
/// they translate to.
///
/// If no language is supplied then `en_gb` is used by default.
pub fn language ::
form: Form
translator: fn(FieldError) -> String
-> Form
{
Form(..form, translator: translator)
}
/// Get all the errors within a form.
///
/// If `run` or `add_error` have not been called then there will be no errors.
pub fn all_errors :: form: Form -> List<(String, List)>
{
form.errors
}
/// Get all the values within a form.
pub fn all_values :: form: Form -> List<(String, String)>
{
form.values
}
/// Get all the values for a given form field.
///
/// ## Examples
///
/// let f = form.new(schema)
/// |> form.add_int("one", 100)
/// |> form.add_string("one", "Hello")
/// |> form.add_string("two", "Hi!")
/// form.field_values(f, "one") == ["Hello", "100"]
pub fn field_values :: form: Form name: String -> List
{
values_of form.values name
}
/// Get the first value for a given form field.
///
/// ## Examples
///
/// let f = form.new(schema) |> form.add_int("one", 100)
/// form.field_value(f, "one") == "100"
/// form.field_value(f, "two") == ""
pub fn field_value :: form: Form name: String -> String
{
match values_of form.values name { [first, ..] -> first, [] -> "" }
}
/// Run a form, returning either the successfully parsed value if there are
/// no errors, or a new instance of the form with the errors added to the
/// fields.
pub fn run :: form: Form -> Result>
{
let (value, errors) = form.run form.values []
match errors { [] -> Ok(value), _ -> Error(Form(..form, errors: errors)) }
}
/// Add multiple values to a form. This function is useful for adding values
/// from a HTTP request form body sent to your server, or from a HTML form
/// element in your browser-based application.
///
/// ## Example
///
/// form.new(signup_schema())
/// |> form.add_values(http.form_body(req))
/// |> form.run
pub fn add_values ::
form: Form
values: List<(String, String)>
-> Form
{
Form(..form, values: list.append values form.values)
}
/// Replace any existing values of a form with new values. This function is
/// useful for adding values from a HTTP request form body sent to your
/// server, or from a HTML form element in your browser-based application.
pub fn set_values ::
form: Form
values: List<(String, String)>
-> Form
{
Form(..form, values: values)
}
/// Add a string value to the form.
///
/// You may want to use this to pre-fill a form with some already-saved
/// values for the user to edit.
pub fn add_string ::
form: Form
field: String
value: String
-> Form
{
Form(..form, values: [(field, value), ..form.values])
}
/// Add an int value to the form.
///
/// You may want to use this to pre-fill a form with some already-saved
/// values for the user to edit.
pub fn add_int :: form: Form field: String value: Int -> Form
{
Form(..form, values: [(field, show value), ..form.values])
}
/// Get the error messages for a field, if there are any.
///
/// The text is formatted using the translator function given with the
/// `language` function. The default translator is `en_gb`.
pub fn field_error_messages :: form: Form name: String -> List
{
list.flat_map
(errors_of form.errors name)
fn errors { list.map errors form.translator }
}
/// Get all the form field errors.
///
/// If the `run` function or the `add_error` function have not been called
/// then the form is clean and won't have any errors yet.
pub fn field_errors :: form: Form name: String -> List
{
flatten (errors_of form.errors name)
}
/// Add an error to one of the fields of the form.
///
/// This function may be useful if you have some additional validation that
/// runs outside of the form schema and you want to surface the error
/// messages to the user via the form.
pub fn add_error ::
form: Form
name: String
error: FieldError
-> Form
{
Form(..form, errors: [(name, [error]), ..form.errors])
}
// The values of `name` in `pairs`, in order (gleam's `list.key_filter`).
fn values_of :: pairs: List<(String, String)> name: String -> List
{
pairs
|> list.filter fn pair { match pair { (key, _) -> key == name } }
|> list.map fn pair { match pair { (_, value) -> value } }
}
// The error lists of `name` in `pairs`, in order.
fn errors_of ::
pairs: List<(String, List)>
name: String
-> List>
{
pairs
|> list.filter fn pair { match pair { (key, _) -> key == name } }
|> list.map fn pair { match pair { (_, errors) -> errors } }
}
fn flatten :: xss: List> -> List
{
list.fold xss [] fn acc xs { list.append acc xs }
}
// The first occurrence of each error, in order (gleam's `list.unique`).
fn unique :: errors: List -> List
{
list.reverse
( list.fold
errors
[]
fn acc error
{
if list.any acc fn seen { seen == error }
{
acc
}
else
{
[error, ..acc]
}
}
)
}
// ---- schemas -----------------------------------------------------------------
/// Add a new parser to the form for a given form field name.
pub fn field ::
name: String
parser: Parser
continuation: fn(value) -> Schema
-> Schema
{
Schema( fn values errors
{
let input = values_of values name
let (value, _status, new_errors) = parser.run input Check
let errors = match new_errors
{ [] -> errors, _ -> [(name, new_errors), ..errors] }
(continuation value).run values errors
}
)
}
/// Finalise a schema, having successfully parsed a value.
pub fn success :: value: model -> Schema
{
Schema(fn _ errors { (value, errors) })
}
// ---- parsers -----------------------------------------------------------------
/// A parser that applies another parser to each input value in a list.
///
/// Takes a parser for a single value and returns a parser that can handle
/// multiple values of the same type. This is useful for form fields that
/// can have multiple values, such as checkboxes, multi-selects, or just
/// repeated inputs of other types.
///
/// ## Example
///
/// let schema = {
/// use tags <- form.field("tag", form.parse_list(form.parse_string()))
/// form.success(Article(tags: tags))
/// }
///
/// This would parse multiple "tag" fields into a list of strings.
pub fn parse_list :: parser: Parser