cedricss / elm-form-machine / Form.Machine

A state machine to handle forms in elm.


type alias FormError formField =
( formField, String )

An error about one specific field.


type State object objectField
    = Displaying object
    | Editing ({ object : object, errors : List (FormError objectField) })
    | Failed String
    | Loading
    | Unloaded

The form machine can have 5 states.


type Event object objectField customEvents
    = Create
    | Display object
    | Edit objectField
    | Fail String
    | Perform customEvents
    | Request
    | Save

Events to move the machine from one state to another


type alias Config object objectField customEvents msg =
{ badTransition : Event object objectField customEvents -> State object objectField -> ( State object objectField
, Platform.Cmd.Cmd msg )
, default : object
, perform : customEvents -> State object objectField -> ( State object objectField
, Platform.Cmd.Cmd msg )
, save : Validate.Valid object -> Platform.Cmd.Cmd msg
, update : object -> objectField -> object
, validator : Validate.Validator (FormError objectField) object 
}

Custom handlers for the machine. Read transition.

transition : Config object objectField customEvents msg -> Event object objectField customEvents -> State object objectField -> ( State object objectField, Platform.Cmd.Cmd msg )

Perform a transition with the given configuration, event and current state.

If it's impossible to handle such event for the current state, the badTransition function is called, for example to log it to your error monitoring platform.

The update function will update one specific field of the object, for example after the user typed into the related input.

The save function only accepts a Validate.Valid object: you can be certain the object is validated with validator before saving. Note: you can unwrap the valid object with Validate.fromValid

To handle any additional custom events, send a Perform customEvent event and the perform function will be called with this customEvent.

Common.transition
    { badTransition = logBadRobotFormTransition
    , default = defaultRobot
    , perform = performCustomEvent
    , save = Request.saveRobot SavedRobot
    , update = updateRobotField
    , validator = robotValidator
    }
    event
    state