This repository has been archived by the owner on Mar 1, 2019. It is now read-only.
/
Router.purs
82 lines (56 loc) · 2.02 KB
/
Router.purs
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
module Cherry.Router
( router
, navigateTo
, redirectTo
, goForward
, goBack
) where
import Prelude
import Control.Monad.Eff (Eff)
import DOM (DOM)
import DOM.Event.EventTarget (addEventListener, eventListener)
import DOM.Event.Types (EventTarget, EventType)
import DOM.HTML (window)
import DOM.HTML.Event.EventTypes (popstate)
import DOM.HTML.History (DocumentTitle(..), URL(..), back, forward, pushState, replaceState)
import DOM.HTML.Location (pathname, search)
import DOM.HTML.Types (HISTORY, Window, windowToEventTarget)
import DOM.HTML.Window (history, location)
import Data.Foreign (Foreign, toForeign)
import Data.Maybe (Maybe(..))
router :: forall e.
(String -> Eff (dom :: DOM | e) Unit) ->
Eff (dom :: DOM | e) Unit
router matcher = do
handler
eventWindow >>= addEventListener popstate listener false
where
handler = do
l <- window >>= location
path <- (<>) <$> pathname l <*> search l
matcher path
listener = eventListener (\_ -> handler)
navigateTo :: forall e.
String ->
Eff (dom :: DOM, history :: HISTORY | e) Unit
navigateTo url = do
window >>= history >>= pushState null (DocumentTitle "") (URL url)
window >>= dispatchEvent popstate
redirectTo :: forall e.
String ->
Eff (dom :: DOM, history :: HISTORY | e) Unit
redirectTo url = do
window >>= history >>= replaceState null (DocumentTitle "") (URL url)
window >>= dispatchEvent popstate
goForward :: forall e. Eff (dom :: DOM, history :: HISTORY | e) Unit
goForward = window >>= history >>= forward
goBack :: forall e. Eff (dom :: DOM, history :: HISTORY | e) Unit
goBack = window >>= history >>= back
eventWindow :: forall e. Eff (dom :: DOM | e) EventTarget
eventWindow = windowToEventTarget <$> window
null :: Foreign
null = toForeign Nothing
foreign import dispatchEvent :: forall e.
EventType ->
Window ->
Eff (dom :: DOM | e) Unit