Last active
July 22, 2016 15:57
-
-
Save Fenntasy/ad677911a293212cb1dc2a8a22574e34 to your computer and use it in GitHub Desktop.
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
module Main exposing (..) | |
import Html.App exposing (program) | |
import Html exposing (div, button, text, input) | |
import Html.Events exposing (onClick, onInput) | |
import Time exposing (Time, second) | |
import String | |
import Task | |
type alias Model = | |
{ countdown : Maybe Float | |
, started : Bool | |
, duration : Int | |
, timeLeft : Int | |
, startTime : Time | |
} | |
init : ( Model, Cmd Msg ) | |
init = | |
( { countdown = Nothing | |
, started = False | |
, duration = 0 | |
, timeLeft = 0 | |
, startTime = 0 | |
} | |
, Cmd.none | |
) | |
main = | |
program | |
{ init = init | |
, view = view | |
, update = update | |
, subscriptions = subscriptions | |
} | |
subscriptions : Model -> Sub Msg | |
subscriptions model = | |
case model.started of | |
False -> | |
Sub.none | |
True -> | |
Time.every second Tick | |
view : Model -> Html.Html Msg | |
view model = | |
let | |
result = | |
case model.countdown of | |
Nothing -> | |
div [] [] | |
Just val -> | |
div [] [ text (toString model.timeLeft ++ " seconds left") ] | |
in | |
div [] | |
[ input [ onInput Input ] [] | |
, button [ onClick Start ] [ text "Start" ] | |
, button [ onClick Stop ] [ text "Stop" ] | |
, result | |
] | |
type Msg | |
= Input String | |
| Start | |
| Stop | |
| Tick Time | |
| GotTime Time | |
timeLeft : Time -> Time -> Int -> Int | |
timeLeft startTime currentTime duration = | |
duration - (round ((currentTime - startTime) / 1000)) | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
case msg of | |
Input string -> | |
let | |
result = | |
String.toFloat string |> Result.toMaybe | |
duration = | |
case result of | |
Nothing -> | |
0 | |
Just val -> | |
round (val * 3600) | |
in | |
( { model | |
| countdown = result | |
, duration = duration | |
, timeLeft = duration | |
} | |
, Cmd.none | |
) | |
GotTime time -> | |
( { model | startTime = time }, Cmd.none ) | |
Start -> | |
( { model | started = True }, Task.perform (\_ -> Debug.crash "") GotTime Time.now ) | |
Stop -> | |
( { model | started = False, countdown = Nothing }, Cmd.none ) | |
Tick newTime -> | |
let | |
time = | |
model.duration - (round ((newTime - model.startTime) / 1000)) | |
in | |
( { model | timeLeft = time }, Cmd.none ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment