-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathEvent.elm
More file actions
427 lines (309 loc) · 11.8 KB
/
Event.elm
File metadata and controls
427 lines (309 loc) · 11.8 KB
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
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
253
254
255
256
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
module Test.Html.Event exposing
( Event, simulate, expect, toResult
, expectStopPropagation, expectNotStopPropagation, expectPreventDefault, expectNotPreventDefault
, custom, click, doubleClick, mouseDown, mouseUp, mouseEnter, mouseLeave, mouseOver, mouseOut, input, check, submit, blur, focus
)
{-| This module lets you simulate events on `Html` values and expect that
they result in certain `Msg` values being sent to `update`.
## Simulating Events
@docs Event, simulate, expect, toResult
## Testing Event Effects
These functions allow you to test that your event handlers are (or are not) calling
[`stopPropagation()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation)
and
[`preventDefault()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault).
In Elm, you do this by calling
[special functions](https://package.elm-lang.org/packages/elm/html/latest/Html-Events#stopPropagationOn)
in `Html.Events`.
@docs expectStopPropagation, expectNotStopPropagation, expectPreventDefault, expectNotPreventDefault
## Event Builders
@docs custom, click, doubleClick, mouseDown, mouseUp, mouseEnter, mouseLeave, mouseOver, mouseOut, input, check, submit, blur, focus
-}
import Dict
import Expect exposing (Expectation)
import Json.Decode as Decode exposing (Decoder)
import Json.Encode as Encode exposing (Value)
import Test.Html.Internal.ElmHtml.InternalTypes exposing (ElmHtml(..))
import Test.Html.Query as Query
import Test.Html.Query.Internal as QueryInternal
import Test.Internal as Internal
import VirtualDom
{-| A simulated event.
See [`simulate`](#simulate).
-}
type Event msg
= Event ( String, Value ) (QueryInternal.Single msg)
{-| Simulate an event on a node.
import Test.Html.Event as Event
type Msg
= Change String
test "Input produces expected Msg" <|
\() ->
Html.input [ onInput Change ] [ ]
|> Query.fromHtml
|> Event.simulate (Event.input "cats")
|> Event.expect (Change "cats")
-}
simulate : ( String, Value ) -> Query.Single msg -> Event msg
simulate =
Event
{-| Passes if the given message is triggered by the simulated event.
import Test.Html.Event as Event
type Msg
= Change String
test "Input produces expected Msg" <|
\() ->
Html.input [ onInput Change ] [ ]
|> Query.fromHtml
|> Event.simulate (Event.input "cats")
|> Event.expect (Change "cats")
-}
expect : msg -> Event msg -> Expectation
expect msg (Event event (QueryInternal.Single showTrace query)) =
case toResult (Event event (QueryInternal.Single showTrace query)) of
Err noEvent ->
Expect.fail noEvent
|> QueryInternal.failWithQuery showTrace "" query
Ok foundMsg ->
foundMsg
|> Expect.equal msg
|> QueryInternal.failWithQuery showTrace
("Event.expectEvent: Expected the msg \u{001B}[32m"
++ Internal.toString msg
++ "\u{001B}[39m from the event \u{001B}[31m"
++ Internal.toString event
++ "\u{001B}[39m but could not find the event."
)
query
{-| Returns a Result with the Msg produced by the event simulated on a node.
Note that Event.expect gives nicer messages; this is generally more useful
when testing that an event handler is _not_ present.
import Test.Html.Event as Event
test "Input produces expected Msg" <|
\() ->
Html.input [ onInput Change ] [ ]
|> Query.fromHtml
|> Event.simulate (Event.input "cats")
|> Event.toResult
|> Expect.equal (Ok (Change "cats"))
-}
toResult : Event msg -> Result String msg
toResult event =
findHandler event
|> Result.map (Decode.map .message)
|> Result.andThen
(\handler ->
Decode.decodeValue handler (eventPayload event)
|> Result.mapError Decode.errorToString
)
-- EFFECTS --
{-| Passes if the event handler stops propagation of the event.
-}
expectStopPropagation : Event msg -> Expectation
expectStopPropagation event =
case checkStopPropagation event of
Err reason ->
Expect.fail reason
Ok False ->
Expect.fail "I found a handler that could have stopped propagation of the event, but it didn't."
Ok True ->
Expect.pass
{-| Passes if the event handler doesn't stop propagation of the event.
-}
expectNotStopPropagation : Event msg -> Expectation
expectNotStopPropagation event =
case checkStopPropagation event of
Err reason ->
Expect.fail reason
Ok False ->
Expect.pass
Ok True ->
Expect.fail
"I found a handler that should have not stopped propagation of the event, but it did."
{-| Passes if the event handler prevents default action of the event.
-}
expectPreventDefault : Event msg -> Expectation
expectPreventDefault event =
case checkPreventDefault event of
Err reason ->
Expect.fail reason
Ok False ->
Expect.fail "I found a handler that could have prevented default action of the event, but it didn't."
Ok True ->
Expect.pass
{-| Passes if the event handler doesn't prevent default action of the event.
-}
expectNotPreventDefault : Event msg -> Expectation
expectNotPreventDefault event =
case checkPreventDefault event of
Err reason ->
Expect.fail reason
Ok False ->
Expect.pass
Ok True ->
Expect.fail
"I found a handler that should have not prevented the default action of the event, but it did."
{-| A [`click`](https://developer.mozilla.org/en-US/docs/Web/Events/click) event.
-}
click : ( String, Value )
click =
( "click", emptyObject )
{-| A [`dblclick`](https://developer.mozilla.org/en-US/docs/Web/Events/dblclick) event.
-}
doubleClick : ( String, Value )
doubleClick =
( "dblclick", emptyObject )
{-| A [`mousedown`](https://developer.mozilla.org/en-US/docs/Web/Events/mousedown) event.
-}
mouseDown : ( String, Value )
mouseDown =
( "mousedown", emptyObject )
{-| A [`mouseup`](https://developer.mozilla.org/en-US/docs/Web/Events/mouseup) event.
-}
mouseUp : ( String, Value )
mouseUp =
( "mouseup", emptyObject )
{-| A [`mouseenter`](https://developer.mozilla.org/en-US/docs/Web/Events/mouseenter) event.
-}
mouseEnter : ( String, Value )
mouseEnter =
( "mouseenter", emptyObject )
{-| A [`mouseleave`](https://developer.mozilla.org/en-US/docs/Web/Events/mouseleave) event.
-}
mouseLeave : ( String, Value )
mouseLeave =
( "mouseleave", emptyObject )
{-| A [`mouseover`](https://developer.mozilla.org/en-US/docs/Web/Events/mouseover) event.
-}
mouseOver : ( String, Value )
mouseOver =
( "mouseover", emptyObject )
{-| A [`mouseout`](https://developer.mozilla.org/en-US/docs/Web/Events/mouseout) event.
-}
mouseOut : ( String, Value )
mouseOut =
( "mouseout", emptyObject )
{-| An [`input`](https://developer.mozilla.org/en-US/docs/Web/Events/input) event.
-}
input : String -> ( String, Value )
input value =
( "input"
, Encode.object
[ ( "target"
, Encode.object [ ( "value", Encode.string value ) ]
)
]
)
{-| A [`change`](https://developer.mozilla.org/en-US/docs/Web/Events/change) event
where `event.target.checked` is set to the given `Bool` value.
-}
check : Bool -> ( String, Value )
check checked =
( "change"
, Encode.object
[ ( "target"
, Encode.object [ ( "checked", Encode.bool checked ) ]
)
]
)
{-| A [`submit`](https://developer.mozilla.org/en-US/docs/Web/Events/submit) event.
-}
submit : ( String, Value )
submit =
( "submit", emptyObject )
{-| A [`blur`](https://developer.mozilla.org/en-US/docs/Web/Events/blur) event.
-}
blur : ( String, Value )
blur =
( "blur", emptyObject )
{-| A [`focus`](https://developer.mozilla.org/en-US/docs/Web/Events/focus) event.
-}
focus : ( String, Value )
focus =
( "focus", emptyObject )
{-| Simulate a custom event. The `String` is the event name, and the `Value` is the event object
the browser would send to the event listener callback.
import Test.Html.Event as Event
import Json.Encode as Encode exposing (Value)
type Msg
= Change String
test "Input produces expected Msg" <|
\() ->
let
simulatedEventObject : Value
simulatedEventObject =
Encode.object
[ ( "target"
, Encode.object [ ( "value", Encode.string "cats" ) ]
)
]
in
Html.input [ onInput Change ] [ ]
|> Query.fromHtml
|> Event.simulate (Event.custom "input" simulatedEventObject)
|> Event.expect (Change "cats")
-}
custom : String -> Value -> ( String, Value )
custom =
Tuple.pair
-- INTERNAL --
emptyObject : Value
emptyObject =
Encode.object []
eventPayload : Event msg -> Value
eventPayload (Event ( _, payload ) _) =
payload
type alias Handling msg =
{ message : msg, stopPropagation : Bool, preventDefault : Bool }
findHandler : Event msg -> Result String (Decoder (Handling msg))
findHandler (Event ( eventName, _ ) (QueryInternal.Single _ query)) =
QueryInternal.traverse query
|> Result.andThen (QueryInternal.verifySingle eventName)
|> Result.mapError QueryInternal.queryErrorToString
|> Result.andThen (findEvent eventName)
findEvent : String -> ElmHtml msg -> Result String (Decoder (Handling msg))
findEvent eventName element =
let
elementOutput =
QueryInternal.prettyPrint element
handlerToDecoder : VirtualDom.Handler msg -> Decoder (Handling msg)
handlerToDecoder handler =
case handler of
VirtualDom.Normal decoder ->
decoder |> Decode.map (\msg -> Handling msg False False)
VirtualDom.MayStopPropagation decoder ->
decoder |> Decode.map (\( msg, sp ) -> Handling msg sp False)
VirtualDom.MayPreventDefault decoder ->
decoder |> Decode.map (\( msg, pd ) -> Handling msg False pd)
VirtualDom.Custom decoder ->
decoder
eventDecoder node =
node.facts.events
|> Dict.get eventName
|> Maybe.map handlerToDecoder
|> Result.fromMaybe ("Event.expectEvent: I found a node, but it does not listen for \"" ++ eventName ++ "\" events like I expected it would.\n\n" ++ elementOutput)
in
case element of
TextTag _ ->
Err ("I found a text node instead of an element. Text nodes do not receive events, so it would be impossible to simulate \"" ++ eventName ++ "\" events on it. The text in the node was: \"" ++ elementOutput ++ "\"")
NodeEntry node ->
eventDecoder node
CustomNode facts ->
eventDecoder { facts = facts }
MarkdownNode node ->
eventDecoder node
checkStopPropagation : Event msg -> Result String Bool
checkStopPropagation =
checkEffect .stopPropagation
checkPreventDefault : Event msg -> Result String Bool
checkPreventDefault =
checkEffect .preventDefault
checkEffect : (Handling msg -> Bool) -> Event msg -> Result String Bool
checkEffect extractor event =
findHandler event
|> Result.map (Decode.map extractor)
|> Result.andThen
(\handler ->
Decode.decodeValue handler (eventPayload event)
|> Result.mapError Decode.errorToString
)