forked from rescript-lang/rescript-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRescriptReactRouter.res
208 lines (178 loc) · 5.79 KB
/
RescriptReactRouter.res
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
@get external location: Dom.window => Dom.location = "location"
/* actually the cb is Dom.event => unit, but let's restrict the access for now */
@send
external addEventListener: (Dom.window, string, unit => unit) => unit = "addEventListener"
@send
external removeEventListener: (Dom.window, string, unit => unit) => unit = "removeEventListener"
@send
external dispatchEvent: (Dom.window, Dom.event) => unit = "dispatchEvent"
@get external pathname: Dom.location => string = "pathname"
@get external hash: Dom.location => string = "hash"
@get external search: Dom.location => string = "search"
@send
external pushState: (Dom.history, @as(json`null`) _, @as("") _, ~href: string) => unit = "pushState"
@send
external replaceState: (Dom.history, @as(json`null`) _, @as("") _, ~href: string) => unit =
"replaceState"
@val external event: 'a = "Event"
@new external makeEventIE11Compatible: string => Dom.event = "Event"
@val @scope("document")
external createEventNonIEBrowsers: string => Dom.event = "createEvent"
@send
external initEventNonIEBrowsers: (Dom.event, string, bool, bool) => unit = "initEvent"
let safeMakeEvent = eventName =>
if Js.typeof(event) == "function" {
makeEventIE11Compatible(eventName)
} else {
let event = createEventNonIEBrowsers("Event")
initEventNonIEBrowsers(event, eventName, true, true)
event
}
/* This is copied from array.ml. We want to cut dependencies for rescript-react so
that it's friendlier to use in size-constrained codebases */
let arrayToList = a => {
let rec tolist = (i, res) =>
if i < 0 {
res
} else {
tolist(i - 1, list{Array.unsafe_get(a, i), ...res})
}
tolist(Array.length(a) - 1, list{})
}
/* if we ever roll our own parser in the future, make sure you test all url combinations
e.g. foo.com/?#bar
*/
/* sigh URLSearchParams doesn't work on IE11, edge16, etc. */
/* actually you know what, not gonna provide search for now. It's a mess.
We'll let users roll their own solution/data structure for now */
let pathParse = str =>
switch str {
| ""
| "/" =>
list{}
| raw =>
/* remove the preceeding /, which every pathname seems to have */
let raw = Js.String.sliceToEnd(~from=1, raw)
/* remove the trailing /, which some pathnames might have. Ugh */
let raw = switch Js.String.get(raw, Js.String.length(raw) - 1) {
| "/" => Js.String.slice(~from=0, ~to_=-1, raw)
| _ => raw
}
/* remove search portion if present in string */
let raw = switch raw |> Js.String.splitAtMost("?", ~limit=2) {
| [path, _] => path
| _ => raw
}
raw |> Js.String.split("/") |> Js.Array.filter(item => String.length(item) != 0) |> arrayToList
}
let path = (~serverUrlString=?, ()) =>
switch (serverUrlString, %external(window)) {
| (None, None) => list{}
| (Some(serverUrlString), _) => pathParse(serverUrlString)
| (_, Some(window: Dom.window)) => pathParse(window |> location |> pathname)
}
let hash = () =>
switch %external(window) {
| None => ""
| Some(window: Dom.window) =>
switch window |> location |> hash {
| ""
| "#" => ""
| raw =>
/* remove the preceeding #, which every hash seems to have.
Why is this even included in location.hash?? */
raw |> Js.String.sliceToEnd(~from=1)
}
}
let searchParse = str =>
switch str {
| ""
| "?" => ""
| raw =>
switch raw |> Js.String.splitAtMost("?", ~limit=2) {
| [_, search] => search
| _ => ""
}
}
let search = (~serverUrlString=?, ()) =>
switch (serverUrlString, %external(window)) {
| (None, None) => ""
| (Some(serverUrlString), _) => searchParse(serverUrlString)
| (_, Some(window: Dom.window)) => searchParse(window |> location |> search)
}
let push = path =>
switch (%external(history), %external(window)) {
| (None, _)
| (_, None) => ()
| (Some(history: Dom.history), Some(window: Dom.window)) =>
pushState(history, ~href=path)
dispatchEvent(window, safeMakeEvent("popstate"))
}
let replace = path =>
switch (%external(history), %external(window)) {
| (None, _)
| (_, None) => ()
| (Some(history: Dom.history), Some(window: Dom.window)) =>
replaceState(history, ~href=path)
dispatchEvent(window, safeMakeEvent("popstate"))
}
type url = {
path: list<string>,
hash: string,
search: string,
}
let urlNotEqual = (a, b) => {
let rec listNotEqual = (aList, bList) =>
switch (aList, bList) {
| (list{}, list{}) => false
| (list{}, list{_, ..._})
| (list{_, ..._}, list{}) => true
| (list{aHead, ...aRest}, list{bHead, ...bRest}) =>
if aHead !== bHead {
true
} else {
listNotEqual(aRest, bRest)
}
}
a.hash !== b.hash || (a.search !== b.search || listNotEqual(a.path, b.path))
}
type watcherID = unit => unit
let url = (~serverUrlString=?, ()) => {
path: path(~serverUrlString?, ()),
hash: hash(),
search: search(~serverUrlString?, ()),
}
/* alias exposed publicly */
let dangerouslyGetInitialUrl = url
let watchUrl = callback =>
switch %external(window) {
| None => () => ()
| Some(window: Dom.window) =>
let watcherID = () => callback(url())
addEventListener(window, "popstate", watcherID)
watcherID
}
let unwatchUrl = watcherID =>
switch %external(window) {
| None => ()
| Some(window: Dom.window) => removeEventListener(window, "popstate", watcherID)
}
let useUrl = (~serverUrl=?, ()) => {
let (url, setUrl) = React.useState(() =>
switch serverUrl {
| Some(url) => url
| None => dangerouslyGetInitialUrl()
}
)
React.useEffect(() => {
let watcherId = watchUrl(url => setUrl(_ => url))
// check for updates that may have occured between the initial state and
// the subscribe above
let newUrl = dangerouslyGetInitialUrl()
if urlNotEqual(newUrl, url) {
setUrl(_ => newUrl)
}
Some(() => unwatchUrl(watcherId))
}, [])
url
}