purescript-pux-router v1.0.0
purescript-pux-router
The routing module from Pux framework as a standalone library except that the sampleURL interface has been updated to work with the new Web and Effect libraries that replace the old DOM and Eff ones respectively.
Below is a modified version of the Router documentation from the Pux github website:
Routing
In Pux, routing is a set of applicatives for matching URLs to data types, along
with a signal for location changes. These are provided by Pux.Router
.
URL changes are mapped to an event. A data type for routes is used to contain the matched URL along with parameter and query data.
data Event = PageView Route | Navigate String DOMEvent
data Route = Home | Users String | User Int | NotFound
We also need a function that constructs a route event from a url, which we
build using routing applicatives and pass to router
to return the
matched route:
match :: String -> Event
match url = PageView $ fromMaybe NotFound $ router url $
Home <$ end
<|>
Users <$> (lit "users" *> param "sortBy") <* end
<|>
Users "name" <$ (lit "users") <* end
<|>
User <$> (lit "users" *> int) <* end
Learn applicative basics in Functors, Applicatives, and Monads in Pictures.
Pux.Router
provides applicatives lit
, str
, num
, int
, bool
, param
,
params
, any
, and end
for mapping url parts to route values.
As you can see above, lit
matches a literal string, and its value is ignored.
int
matches the second part of /users/123
to the integer value of User
.
end
matches the end of the URL. param
matches a query parameter, in our case
"sortBy". Queries are a bit tricky as they are optional. Therefore end
also
matches if there is a query present. This means the order of our Users
rules
is essential. If we had the param
less version first, the one with param
would never be tried!
Now that we have a function for making a route from a url, we can map it over
the url signal provided by
sampleURL
takes a window history object from purescript-dom and returns a signal of the
URL which is updated whenever the popstate
event occurs.
6 years ago