forked from evancz/elm-architecture-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomGif.elm
102 lines (73 loc) · 1.82 KB
/
RandomGif.elm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
module RandomGif exposing (..)
import Html exposing (..)
import Html.Attributes exposing (style)
import Html.Events exposing (onClick)
import Http
import Json.Decode as Json
import Task
-- MODEL
type alias Model =
{ topic : String
, gifUrl : String
}
init : String -> (Model, Cmd Msg)
init topic =
( Model topic "assets/waiting.gif"
, getRandomGif topic
)
-- UPDATE
type Msg
= RequestMore
| GifFetchSucceed String
| GifFetchFail Http.Error
update : Msg -> Model -> (Model, Cmd Msg)
update action model =
case action of
RequestMore ->
(model, getRandomGif model.topic)
GifFetchSucceed url ->
( Model model.topic url
, Cmd.none
)
GifFetchFail error ->
( model -- for now if the fetch fail we just does nothing
, Cmd.none
)
-- VIEW
(=>) = (,)
view : Model -> Html Msg
view model =
div [ style [ "width" => "200px" ] ]
[ h2 [headerStyle] [text model.topic]
, div [imgStyle model.gifUrl] []
, button [ onClick RequestMore ] [ text "More Please!" ]
]
headerStyle : Attribute a
headerStyle =
style
[ "width" => "200px"
, "text-align" => "center"
]
imgStyle : String -> Attribute a
imgStyle url =
style
[ "display" => "inline-block"
, "width" => "200px"
, "height" => "200px"
, "background-position" => "center center"
, "background-size" => "cover"
, "background-image" => ("url('" ++ url ++ "')")
]
-- EFFECTS
getRandomGif : String -> Cmd Msg
getRandomGif topic =
Task.perform GifFetchFail GifFetchSucceed (Http.get decodeUrl (randomUrl topic))
randomUrl : String -> String
randomUrl topic =
Http.url "http://api.giphy.com/v1/gifs/random"
[ "api_key" => "dc6zaTOxFJmzC"
, "tag" => topic
]
decodeUrl : Json.Decoder String
decodeUrl =
Json.at ["data", "image_url"] Json.string