forked from TheSeamau5/elm-undo-redo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCounterWithCats.elm
107 lines (82 loc) · 2.3 KB
/
CounterWithCats.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
103
104
105
106
107
module CounterWithCats exposing (..)
import Browser
import Html exposing (Html, div, button, img, text)
import Html.Attributes exposing (src)
import Html.Events exposing (onClick)
import UndoList exposing (UndoList)
import Http
import Task
import Json.Decode as Json
main : Program () Model Msg
main =
Browser.element
{ init = \() -> init
, view = view
, update = update
, subscriptions = always Sub.none
}
type alias Model =
UndoList
{ counter : Int
, gifUrl : Maybe String
}
type Msg
= Increment
| Undo
| Redo
| OnFetch (Result Http.Error String)
init : ( Model, Cmd msg )
init =
( UndoList.fresh { counter = 0, gifUrl = Nothing }
, Cmd.none
)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg ({ present } as model) =
case msg of
Increment ->
( UndoList.new { present | counter = present.counter + 1 }
model
, getRandomGif "cats"
)
Undo ->
( UndoList.undo model, Cmd.none )
Redo ->
( UndoList.redo model, Cmd.none )
OnFetch (Ok newUrl) ->
( UndoList.mapPresent (\_ -> { present | gifUrl = Just newUrl })
model
, Cmd.none
)
OnFetch (Err _) ->
( model, Cmd.none )
view : Model -> Html Msg
view model =
div []
[ button [ onClick Increment ]
[ text "Increment" ]
, button [ onClick Undo ]
[ text "Undo" ]
, button [ onClick Redo ]
[ text "Redo" ]
, div []
[ text (String.fromInt model.present.counter) ]
, div []
(case model.present.gifUrl of
Just gifUrl ->
[ img [ src gifUrl ] [] ]
Nothing ->
[ text "Increment to display a GIF image" ]
)
]
-- Taken from https://guide.elm-lang.org/architecture/effects/http.html
getRandomGif : String -> Cmd Msg
getRandomGif topic =
let
url =
"https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=" ++ topic
in
Http.get url decodeGifUrl
|> Http.send OnFetch
decodeGifUrl : Json.Decoder String
decodeGifUrl =
Json.at [ "data", "image_url" ] Json.string