forked from evancz/elm-architecture-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRandomGif.elm
100 lines (72 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
module RandomGif where
import Effects exposing (Effects, Never)
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, Effects Action)
init topic =
( Model topic "assets/waiting.gif"
, getRandomGif topic
)
-- UPDATE
type Action
= RequestMore
| NewGif (Maybe String)
update : Action -> Model -> (Model, Effects Action)
update action model =
case action of
RequestMore ->
(model, getRandomGif model.topic)
NewGif maybeUrl ->
( Model model.topic (Maybe.withDefault model.gifUrl maybeUrl)
, Effects.none
)
-- VIEW
(=>) = (,)
view : Signal.Address Action -> Model -> Html
view address model =
div [ style [ "width" => "200px" ] ]
[ h2 [headerStyle] [text model.topic]
, div [imgStyle model.gifUrl] []
, button [ onClick address RequestMore ] [ text "More Please!" ]
]
headerStyle : Attribute
headerStyle =
style
[ "width" => "200px"
, "text-align" => "center"
]
imgStyle : String -> Attribute
imgStyle url =
style
[ "display" => "inline-block"
, "width" => "200px"
, "height" => "200px"
, "background-position" => "center center"
, "background-size" => "cover"
, "background-image" => ("url('" ++ url ++ "')")
]
-- EFFECTS
getRandomGif : String -> Effects Action
getRandomGif topic =
Http.get decodeUrl (randomUrl topic)
|> Task.toMaybe
|> Task.map NewGif
|> Effects.task
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