Last active
May 23, 2016 23:43
-
-
Save tjweir/e4c8fcaab2546fa017c7f8a3b591f084 to your computer and use it in GitHub Desktop.
Make http requests. You can add your own topic.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Html exposing (..) | |
| import Html.App as Html | |
| import Html.Attributes exposing (..) | |
| import Html.Events exposing (..) | |
| import Http | |
| import Json.Decode as Json | |
| import Task | |
| main = | |
| Html.program | |
| { init = init "cats" | |
| , view = view | |
| , update = update | |
| , subscriptions = subscriptions | |
| } | |
| -- MODEL | |
| type alias Model = | |
| { topic : String | |
| , gifUrl : String | |
| } | |
| init : String -> (Model, Cmd Msg) | |
| init topic = | |
| ( Model topic "waiting.gif" | |
| , getRandomGif topic | |
| ) | |
| -- UPDATE | |
| type Msg | |
| = MorePlease | |
| | FetchSucceed String | |
| | FetchFail Http.Error | |
| | UpdateField String | |
| | NoOp | |
| update : Msg -> Model -> (Model, Cmd Msg) | |
| update action model = | |
| case action of | |
| MorePlease -> | |
| (model, getRandomGif model.topic) | |
| FetchSucceed newUrl -> | |
| (Model model.topic newUrl, Cmd.none) | |
| FetchFail _ -> | |
| (model, Cmd.none) | |
| UpdateField str -> | |
| ({model | topic = str} , Cmd.none) | |
| NoOp -> | |
| (model, Cmd.none) | |
| -- VIEW | |
| view : Model -> Html Msg | |
| view model = | |
| div [] | |
| [ h2 [] [text model.topic] | |
| , input | |
| [ id "topic" | |
| , placeholder "What needs to be done?" | |
| , autofocus True | |
| , on "input" (Json.map UpdateField targetValue) | |
| , onEnter NoOp MorePlease | |
| ] | |
| [] | |
| , button [ onClick MorePlease ] [ text "More Please!" ] | |
| , br [] [] | |
| , img [src model.gifUrl] [] | |
| ] | |
| -- SUBSCRIPTIONS | |
| subscriptions : Model -> Sub Msg | |
| subscriptions model = | |
| Sub.none | |
| -- HTTP | |
| getRandomGif : String -> Cmd Msg | |
| getRandomGif topic = | |
| let | |
| url = | |
| "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=" ++ topic | |
| in | |
| Task.perform FetchFail FetchSucceed (Http.get decodeGifUrl url) | |
| decodeGifUrl : Json.Decoder String | |
| decodeGifUrl = | |
| Json.at ["data", "image_url"] Json.string | |
| onEnter : msg -> msg -> Attribute msg | |
| onEnter fail success = | |
| let | |
| tagger code = | |
| if code == 13 then success | |
| else fail | |
| in | |
| on "keyup" (Json.map tagger keyCode) | |
| myStyle = | |
| style | |
| [ ("width", "100%") | |
| , ("height", "40px") | |
| , ("padding", "10px 0") | |
| , ("font-size", "2em") | |
| , ("text-align", "center") | |
| ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment