/select-prism

Use a Monocle Prism to handle <select> conflict between ADTs and Strings

Primary LanguageElmApache License 2.0Apache-2.0

select-prism

A <select> is basically the UI representation of a union type or ADT.Using a Prism and it’s data structure for a data transformation that’s not quite isomorphic, we can use go from an ADT to a String and back like we’d prefer to do.

import Html exposing (..)
import Html.SelectPrism exposing (selectp)


view : Model -> Html Msg
view { selectedColor } =
    -- Right Here ↓
    selectp colorp ChangeColor selectedColor [] colorOptions


colorOptions : List ( String, Color )
colorOptions =
    [ ( "❤️  Red", Red )
    , ( "💙 Blue", Blue )
    , ( "💚 Green", Green )
    ]


type alias Model =
    { selectedColor : Color }


type Msg
    = ChangeColor (Result String Color)


type Color
    = Red
    | Blue
    | Green


{-| You the developer are responsible for this `Prism`s correctness
-}
colorp : Prism String Color
colorp =
    let
        colorFromString : String -> Maybe Color
        colorFromString s =
            case s of
                "red" ->
                    Just Red

                "green" ->
                    Just Green

                "blue" ->
                    Just Blue

                _ ->
                    Nothing

        colorToString : Color -> String
        colorToString c =
            case c of
                Red ->
                    "red"

                Green ->
                    "green"

                Blue ->
                    "blue"
    in
        -- Using `Prism` as a constructor
        Prism colorFromString colorToString

Do check out the example and/or read my blog entry which goes into more depth.


Project & Community Notes

This project is regrettably available on GitHub. The Elm community has tied itself to the closed-source, Microsoft-owned code forge of GitHub for package registry and identity. This does not protect the privacy or freedom of its community members.


License

This project is licensed under Apache License 2.0 - LICENSE file for details.

Funding

If you want to make a small contribution to the maintanence of this & other projects

  • Liberapay
  • Bitcoin: 39nLVxrXPnD772dEqWFwfZZbfTv5BvV89y (verified on Keybase)
  • Zcash: t1a9pD1D2SDTTd7dbc15KnKsyYXtGcjHuZZ (verified on Keybase)