-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRedLineTrains.elm
120 lines (85 loc) · 2.7 KB
/
RedLineTrains.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
108
109
110
111
112
113
114
115
116
117
118
119
120
module RedLineTrains exposing (main)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Http
import Prediction exposing (Prediction)
import Stop exposing (Stop)
type Model
= LoadingStops
| DisplayingStops (List Stop)
| LoadingTimes Stop
| DisplayingPredictions Stop (List Prediction)
type Msg
= StopsLoaded (Result Http.Error (List Stop))
| StopSelected Stop
| PredictionsLoaded Stop (Result Http.Error (List Prediction))
main : Program Never Model Msg
main =
Html.program
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
init : ( Model, Cmd Msg )
init =
( LoadingStops, fetchStopsCmd )
fetchStopsCmd : Cmd Msg
fetchStopsCmd =
Http.send StopsLoaded getStopsRequest
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
StopsLoaded (Err error) ->
Debug.crash <| toString error
StopsLoaded (Ok stops) ->
( DisplayingStops stops, Cmd.none )
PredictionsLoaded _ (Err error) ->
Debug.crash <| toString error
PredictionsLoaded stop (Ok predictions) ->
( DisplayingPredictions stop predictions, Cmd.none )
StopSelected stop ->
( LoadingTimes stop, fetchPredictionsCmd stop )
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
view : Model -> Html Msg
view model =
case model of
LoadingStops ->
h1 [] [ text "Loading stops..." ]
DisplayingStops stops ->
ol [] <| List.map viewStop stops
LoadingTimes stop ->
h1 [] [ text "Loading times..." ]
DisplayingPredictions stop predictions ->
div
[]
[ h1 [] [ text <| "Arrival times for " ++ stop.name ]
, text <| toString predictions
]
viewStop : Stop -> Html Msg
viewStop stop =
li []
[ a
[ href "#"
, onClick <| StopSelected stop
]
[ text stop.name ]
]
getStopsUrl : String
getStopsUrl =
"https://api-v3.mbta.com/stops?filter[route]=Red"
getPredictionsUrl : Stop -> String
getPredictionsUrl stop =
"https://api-v3.mbta.com/predictions?filter[route]=Red&filter[stop]=" ++ stop.id
getStopsRequest : Http.Request (List Stop)
getStopsRequest =
Http.get getStopsUrl Stop.listDecoder
fetchPredictionsCmd : Stop -> Cmd Msg
fetchPredictionsCmd stop =
Http.send (PredictionsLoaded stop) <| getPredictionsRequest stop
getPredictionsRequest : Stop -> Http.Request (List Prediction)
getPredictionsRequest stop =
Http.get (getPredictionsUrl stop) Prediction.listDecoder