Plot.elm 7.29 KB
Newer Older
1
2
3
4
5
6
7
8
port module Plot exposing (main)

import Browser
import Common exposing (classes)
import Dict
import Html.Styled exposing (..)
import Html.Styled.Events exposing (onClick)
import Http
André Espaze's avatar
André Espaze committed
9
import Json.Decode as Decode exposing (Decoder)
10
11
12
import KeywordMultiSelector
import KeywordSelector
import Tachyons.Classes as T
André Espaze's avatar
André Espaze committed
13
import Task
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import Time
import Url
import Url.Builder as UB


type alias Model =
    { urlPrefix : String
    , series : List String
    , searchString : String
    , searchedSeries : List String
    , selectedSeries : List String
    , activeSelection : Bool
    }


type alias SeriesCatalog =
    Dict.Dict String String


André Espaze's avatar
André Espaze committed
33
34
35
36
37
38
39
40
41
type alias Serie =
    Dict.Dict String Float


serieDecoder : Decoder Serie
serieDecoder =
    Decode.dict Decode.float


42
43
44
45
46
47
48
49
type Msg
    = CatalogReceived (Result Http.Error SeriesCatalog)
    | ToggleSelection
    | ToggleItem String
    | SearchSeries String
    | MakeSearch
    | OnApply
    | GotPlot (Result Http.Error String)
André Espaze's avatar
André Espaze committed
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
    | RenderPlot (Result String (List Serie))


type alias Trace =
    { type_ : String
    , name : String
    , x : List String
    , y : List Float
    , mode : String
    }


type alias TraceArgs =
    String -> List String -> List Float -> String -> Trace


scatterPlot : TraceArgs
scatterPlot =
    Trace "scatter"


type alias PlotArgs =
    { data : List Trace
    }


port renderPlot : PlotArgs -> Cmd msg
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135


type alias RenderArgs =
    { plotlyResponse : String
    , selectedSeries : List String
    , permalinkQuery : String
    }


port renderPlotly : RenderArgs -> Cmd msg


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    let
        removeItem x xs =
            List.filter ((/=) x) xs

        toggleItem x xs =
            if List.member x xs then
                removeItem x xs

            else
                x :: xs

        newModel x =
            ( x, Cmd.none )

        keywordMatch xm xs =
            if String.length xm < 2 then
                []

            else
                KeywordSelector.select xm xs |> List.take 20

        plotUrl =
            UB.crossOrigin model.urlPrefix
                [ "tsplot" ]
                (List.map (\x -> UB.string "series" x) model.selectedSeries)
    in
    case msg of
        CatalogReceived (Ok x) ->
            let
                series =
                    Dict.keys x
            in
            newModel { model | series = series }

        CatalogReceived (Err x) ->
            let
                _ =
                    Debug.log "Error on CatalogReceived" x
            in
            newModel model

        ToggleSelection ->
            newModel { model | activeSelection = not model.activeSelection }

        ToggleItem x ->
André Espaze's avatar
André Espaze committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
            let
                selectedSeries =
                    toggleItem x model.selectedSeries

                getSerie serieName =
                    Http.task
                        { method = "GET"
                        , url =
                            UB.crossOrigin
                                model.urlPrefix
                                [ "api", "series", "state" ]
                                [ UB.string "name" serieName ]
                        , headers = []
                        , body = Http.emptyBody
                        , timeout = Nothing
                        , resolver =
                            Http.stringResolver <|
                                Common.decodeJsonMessage serieDecoder
                        }

                getSeries =
                    Task.sequence <| List.map getSerie selectedSeries
            in
            ( { model | selectedSeries = selectedSeries }
            , Task.attempt RenderPlot getSeries
            )
162
163
164
165
166
167
168

        SearchSeries x ->
            newModel { model | searchString = x }

        MakeSearch ->
            newModel { model | searchedSeries = keywordMatch model.searchString model.series }

André Espaze's avatar
André Espaze committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
        RenderPlot (Ok xs) ->
            let
                vals =
                    List.map2
                        (\name x ->
                            scatterPlot
                                name
                                (Dict.keys x)
                                (Dict.values x)
                                "lines"
                        )
                        model.selectedSeries
                        xs
            in
            ( model, renderPlot <| PlotArgs vals )

        RenderPlot (Err x) ->
            let
                _ =
                    Debug.log "Error on RenderPlot" x
            in
            newModel model

192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
        OnApply ->
            ( model, Http.get { url = plotUrl, expect = Http.expectString GotPlot } )

        GotPlot (Ok x) ->
            let
                validUrl =
                    Common.maybe
                        ("http://dummy" ++ plotUrl)
                        (always plotUrl)
                        (Url.fromString plotUrl)

                q =
                    validUrl
                        |> Url.fromString
                        |> Maybe.map (.query >> Maybe.withDefault "")
                        |> Maybe.withDefault ""
            in
            ( model, renderPlotly <| RenderArgs x model.selectedSeries q )

        GotPlot (Err x) ->
            let
                _ =
                    Debug.log "Error on GotPlot" x
            in
            newModel model


selectorConfig : KeywordMultiSelector.Config Msg
selectorConfig =
    { searchSelector =
        { action = Nothing
        , defaultText =
            text
                "Type some keywords in input bar for selecting time series"
        , toggleMsg = ToggleItem
        }
    , actionSelector =
        { action =
            Just
                { attrs = [ classes [ T.white, T.bg_dark_blue ] ]
                , html = text "Apply"
                , clickMsg = OnApply
                }
        , defaultText = text ""
        , toggleMsg = ToggleItem
        }
    , onInputMsg = SearchSeries
    , divAttrs = [ classes [ T.mb4 ] ]
    }


view : Model -> Html Msg
view model =
    let
        cls =
            classes [ T.pb2, T.f4, T.fw6, T.db, T.navy, T.link, T.dim ]

        children =
            [ a [ cls, onClick ToggleSelection ] [ text "Series selection" ] ]

        ctx =
253
254
255
256
            KeywordMultiSelector.Context
                model.searchString
                model.searchedSeries
                model.selectedSeries
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
    in
    div [ classes [ T.center, T.pt4, T.w_90 ] ]
        (if model.activeSelection then
            List.append children
                [ KeywordMultiSelector.view selectorConfig ctx
                ]

         else
            children
        )


main : Program String Model Msg
main =
    let
        initialGet urlPrefix =
            Http.get
                { expect = Http.expectJson CatalogReceived (Decode.dict Decode.string)
                , url =
                    UB.crossOrigin urlPrefix
                        [ "api", "series", "catalog" ]
                        []
                }

        init urlPrefix =
            ( Model urlPrefix [] "" [] [] True, initialGet urlPrefix )

        sub model =
            if model.activeSelection then
                Time.every 1000 (always MakeSearch)

            else
                Sub.none
    in
    Browser.element
        { init = init
        , view = view >> toUnstyled
        , update = update
        , subscriptions = sub
        }