Last active
February 1, 2017 13:04
-
-
Save nmk/fc0e1594438e336aa80f13e91a8fe262 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main exposing (..) | |
import Form exposing (..) | |
import Form.Input as Input | |
import Form.Validate exposing (..) | |
import Html exposing (..) | |
type Color | |
= Red | |
| Green | |
| Blue | |
colorsWithNumericKeys : List ( String, Color ) | |
colorsWithNumericKeys = | |
[ ( "1", Red ) | |
, ( "2", Green ) | |
, ( "3", Blue ) | |
] | |
colors : List ( String, Color ) | |
colors = | |
[ ( "c1", Red ) | |
, ( "c2", Green ) | |
, ( "c3", Blue ) | |
] | |
type alias Output = | |
List Color | |
type alias Model = | |
{ outputForm : OutputForm } | |
type MyError | |
= InvalidColor | |
type alias OutputForm = | |
Form MyError Output | |
checkboxList : List ( String, value ) -> Validation e (List value) | |
checkboxList items = | |
let | |
validateItem ( key, value ) = | |
field key | |
(bool | |
|> andThen | |
(\checked -> | |
if checked then | |
succeed (Just value) | |
else | |
succeed Nothing | |
) | |
) | |
in | |
sequence (List.map validateItem items) | |
|> Form.Validate.map (List.filterMap identity) | |
validate : Validation e Output | |
validate = | |
let | |
colorsOptions = | |
List.map (\( id, c ) -> ( id, c )) colors | |
in | |
field "colors" (checkboxList colorsOptions) | |
sequence : List (Validation e a) -> Validation e (List a) | |
sequence validations = | |
List.foldr (Form.Validate.map2 (::)) (Form.Validate.succeed []) validations | |
update : Form.Msg -> Model -> Model | |
update msg model = | |
let | |
_ = | |
Debug.log "form msg" msg | |
in | |
{ model | outputForm = Form.update msg model.outputForm } | |
initialModel : Model | |
initialModel = | |
{ outputForm = Form.initial [] validate } | |
view : Model -> Html Form.Msg | |
view { outputForm } = | |
div | |
[] | |
[ Input.dumpErrors outputForm | |
, pre [] [ text (toString (Form.getOutput outputForm)) ] | |
, div [] | |
(colors | |
|> List.map | |
(\( id, color ) -> | |
label | |
[] | |
[ Input.checkboxInput (Form.getFieldAsBool ("colors." ++ id) outputForm) [] | |
, text (toString color) | |
] | |
) | |
) | |
] | |
main : Program Never Model Form.Msg | |
main = | |
beginnerProgram | |
{ model = initialModel | |
, update = update | |
, view = view | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment