/
Route.elm
55 lines (39 loc) · 1.22 KB
/
Route.elm
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
module Route exposing (Route(..), parse, toString)
import Content exposing (Content)
import Database
import Database.ID as ID exposing (ID)
import Url exposing (Url)
import Url.Builder as Builder
import Url.Parser as Parser exposing ((</>), Parser, s, top)
type Route
= NotFound
| Root
| NodeById ID
| NodeByTitle Content
toString : Route -> String
toString route =
case route of
Root ->
Builder.absolute [] []
NotFound ->
Builder.absolute [ "404" ] []
NodeById id_ ->
Builder.absolute [ "node", ID.toString id_ ] []
NodeByTitle title ->
Builder.absolute [ "node", Url.percentEncode (Content.toString title) ] []
parse : Url -> Route
parse url =
Maybe.withDefault NotFound (Parser.parse parser url)
parser : Parser (Route -> a) a
parser =
Parser.oneOf
[ Parser.map Root top
, Parser.map NodeById (s "node" </> id)
, Parser.map NodeByTitle (s "node" </> content)
]
id : Parser (ID -> a) a
id =
Parser.custom "ID" (ID.fromString >> Result.toMaybe)
content : Parser (Content -> a) a
content =
Parser.custom "CONTENT" (Url.percentDecode >> Maybe.andThen (Content.fromString >> Result.toMaybe))