concept Photo in category elm

appears as: Photo, Photo
Elm in Action

This is an excerpt from Manning's book Elm in Action.

Let’s create a type alias called Photo, and then use that in place of { url : String }.

Listing 3.2. Creating a type alias called Photo
type alias Photo =        #1
    { url : String }      #1

 
initialModel : { photos : List Photo, selectedUrl : String }
initialModel =
   ...

photoArray : Array Photo
photoArray =
    Array.fromList initialModel.photos

This makes our initialModel annotation not only more concise, but also easier to maintain! Now if we add a new field to our Photo record, we can change the type alias in one place instead of having to hunt down several individual annotations.

In chapter 3, we created an Array Photo to help us choose a photo at random. We then used a Random.Generator Int to get a random index into that array, and Array.get with that index to obtain the Photo we desired. Is there some way we could randomly choose a Photo without the intermediate Array? Indeed there is: the Random.uniform function!

You’ve already seen how we can use Http.expectString to obtain a String from a server, and how we can use decodeString and a Decoder to translate a String into a list of Photo records for our Model.

Listing 4.7. The complete PhotoGroove.elm
module PhotoGroove exposing (main)

import Browser
import Html exposing (..)
import Html.Attributes exposing (class, classList, id, name, src, title, type_)
import Html.Events exposing (onClick)
import Http
import Json.Decode exposing (Decoder, bool, int, list, string, succeed)
import Json.Decode.Pipeline exposing (optional, required)
import Random

 
urlPrefix : String
urlPrefix =
    "http://elm-in-action.com/"

 
type Msg
    = ClickedPhoto String
    | ClickedSize ThumbnailSize
    | ClickedSurpriseMe
    | GotRandomPhoto Photo
    | GotPhotos (Result Http.Error (List Photo))

 
view : Model -> Html Msg
view model =
    div [ class "content" ] <|                                #1
        case model.status of
            Loaded photos selectedUrl ->
                viewLoaded photos selectedUrl model.chosenSize

            Loading ->
                []

            Errored errorMessage ->
                [ text ("Error: " ++ errorMessage) ]

 
viewLoaded : List Photo -> String -> ThumbnailSize -> List (Html Msg)
viewLoaded photos selectedUrl chosenSize =
    [ h1 [] [ text "Photo Groove" ]
    , button
        [ onClick ClickedSurpriseMe ]
        [ text "Surprise Me!" ]
    , h3 [] [ text "Thumbnail Size:" ]
    , div [ id "choose-size" ]
        (List.map viewSizeChooser [ Small, Medium, Large ])
    , div [ id "thumbnails", class (sizeToString chosenSize) ]
        (List.map (viewThumbnail selectedUrl) photos)
    , img
        [ class "large"
        , src (urlPrefix ++ "large/" ++ selectedUrl)
        ]
        []
    ]

 
viewThumbnail : String -> Photo -> Html Msg
viewThumbnail selectedUrl thumb =
    img
        [ src (urlPrefix ++ thumb.url)
        , title (thumb.title ++ " [" ++ String.fromInt thumb.size ++ " KB]")
        , classList [ ( "selected", selectedUrl == thumb.url ) ]
        , onClick (ClickedPhoto thumb.url)
        ]
        []

 
viewSizeChooser : ThumbnailSize -> Html Msg
viewSizeChooser size =
    label []
        [ input [ type_ "radio", name "size", onClick (ClickedSize size) ] []
        , text (sizeToString size)
        ]

 
sizeToString : ThumbnailSize -> String
sizeToString size =
    case size of
        Small ->
            "small"

        Medium ->
            "med"

        Large ->
            "large"

 
type ThumbnailSize
    = Small
    | Medium
    | Large

 
type alias Photo =
    { url : String
    , size : Int
    , title : String
    }

 

photoDecoder : Decoder Photo
photoDecoder =
    succeed Photo                                                 #2
        |> required "url" string                                  #3
        |> required "size" int                                    #4
        |> optional "title" string "(untitled)                    #5

 
type Status
    = Loading
    | Loaded (List Photo) String
    | Errored String

 
type alias Model =
    { status : Status
    , chosenSize : ThumbnailSize
    }

 
initialModel : Model
initialModel =
    { status = Loading
    , chosenSize = Medium
    }

 
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        GotRandomPhoto photo ->
            ( { model | status = selectUrl photo.url model.status }, Cmd.none )

        ClickedPhoto url ->
            ( { model | status = selectUrl url model.status }, Cmd.none )

        ClickedSize size ->
            ( { model | chosenSize = size }, Cmd.none )

        ClickedSurpriseMe ->
            case model.status of
                Loaded (firstPhoto :: otherPhotos) _ ->          #6
                    Random.uniform firstPhoto otherPhotos        #7
                        |> Random.generate GotRandomPhoto        #7
                        |> Tuple.pair model                      #7

                Loaded [] _ ->                                   #8
                    ( model, Cmd.none )

                Loading ->
                    ( model, Cmd.none )

                Errored errorMessage ->
                    ( model, Cmd.none )

        GotPhotos (Ok photos) ->                                  #9
            case photos of
                first :: rest ->
                    ( { model | status = Loaded photos first.url }
                    , Cmd.none
                    )

                [] ->
                    ( { model | status = Errored "0 photos found" }, Cmd.none )

        GotPhotos (Err httpError) ->
            ( { model | status = Errored "Server error!" }, Cmd.none )

 
selectUrl : String -> Status -> Status
selectUrl url status =
    case status of
        Loaded photos _ ->
            Loaded photos url

        Loading ->
            status

        Errored errorMessage ->
            status

 
initialCmd : Cmd Msg
initialCmd =
    Http.get
        { url = "http://elm-in-action.com/photos/list.json"
        , expect = Http.expectJson GotPhotos (list photoDecoder)  #10
        }

 
main : Program () Model Msg
main =
    Browser.element
        { init = \flags -> ( initialModel, initialCmd )
        , view = view
        , update = update
        , subscriptions = \_ -> Sub.none
        }