Skip to content

Instantly share code, notes, and snippets.

@amitaibu
Created August 26, 2015 19:07
Show Gist options
  • Save amitaibu/bda348525785e4018b70 to your computer and use it in GitHub Desktop.
Save amitaibu/bda348525785e4018b70 to your computer and use it in GitHub Desktop.
import Effects exposing (Never)
import RandomGif exposing (init, update, view)
import StartApp
import Task
app =
StartApp.start
{ init = init "funny cats"
, update = update
, view = view
, inputs = []
}
main =
app.html
port tasks : Signal (Task.Task Never ())
port tasks =
app.tasks
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
import Time exposing (Time, second)
-- MODEL
type alias Model =
{ topic : String
, gifUrl : String
, counter: Time
}
init : String -> (Model, Effects Action)
init topic =
( Model topic "assets/waiting.gif" 0
, getRandomGif topic
)
-- UPDATE
type Action
= RequestMore
| NewGif (Maybe String)
| Tick Time
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) 0
, Effects.tick Tick
)
Tick clockTime ->
let
needsRefresh = model.counter > 5000000
newElapsedTime = model.counter + clockTime
in
if needsRefresh
then
(
Model model.topic model.gifUrl 0
, getRandomGif model.topic
)
else
(
Model model.topic model.gifUrl newElapsedTime
, Effects.tick Tick
)
-- 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!" ]
, div [] [ text (toString (floor model.counter // 1000000)) ]
]
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment