elm

Elm/html: ordered list of different kind of elements


I was looking at some Elm examples and I found "Example 3: A Dynamic List of Counters". I wanted to alter it to include checkboxes, so a single list with counters and/or checkboxes. Each having their own actions and model (such as a name, and a checked bool).

On top of that I would like to order the list, so that checked checkboxes all appear at the top, unchecked at the bottom and the counters in the middle.

I couldn't find any examples on how to do and structure this though.

Note: I'm very new to Elm (and functional programming in general).


Solution

  • One way to achieve this is to use a union type for the item (untested, I don't have a Elm environment right now to check this):

    type Item = Checkbox String Bool | Counter
    
    type alias Model =
        { items : List ( ID, Item )
        , nextID : ID
        }
    

    Depending on the type of item, you'd then render it as

    viewItem item =
       case item of
         Counter value -> renderCounter value
         CheckBox name state -> renderCheckbox name state
    

    All your view has to do is call viewItem for each Item, sort the items and put everything in a container (e.g. a div):

    view address model =
      let 
        items = List.map (viewItem address) model.items 
                |> List.sort (your custom sorting here)
      in
          div [] ([remove, insert] ++ items)