1 | import { match } from "@reach/router/lib/utils"
|
2 | import stripPrefix from "./strip-prefix"
|
3 | import normalizePagePath from "./normalize-page-path"
|
4 |
|
5 | const pathCache = new Map()
|
6 | let matchPaths = []
|
7 |
|
8 | const trimPathname = rawPathname => {
|
9 | const pathname = decodeURIComponent(rawPathname)
|
10 |
|
11 | const trimmedPathname = stripPrefix(pathname, __BASE_PATH__)
|
12 |
|
13 | .split(`#`)[0]
|
14 |
|
15 | .split(`?`)[0]
|
16 |
|
17 | return trimmedPathname
|
18 | }
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | export const setMatchPaths = value => {
|
26 | matchPaths = value
|
27 | }
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 | export const findMatchPath = rawPathname => {
|
38 | const trimmedPathname = cleanPath(rawPathname)
|
39 |
|
40 | for (const { matchPath, path } of matchPaths) {
|
41 | if (match(matchPath, trimmedPathname)) {
|
42 | return normalizePagePath(path)
|
43 | }
|
44 | }
|
45 |
|
46 | return null
|
47 | }
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 | export const findPath = rawPathname => {
|
58 | const trimmedPathname = trimPathname(rawPathname)
|
59 |
|
60 | if (pathCache.has(trimmedPathname)) {
|
61 | return pathCache.get(trimmedPathname)
|
62 | }
|
63 |
|
64 | let foundPath = findMatchPath(trimmedPathname)
|
65 |
|
66 | if (!foundPath) {
|
67 | foundPath = cleanPath(rawPathname)
|
68 | }
|
69 |
|
70 | pathCache.set(trimmedPathname, foundPath)
|
71 |
|
72 | return foundPath
|
73 | }
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 | export const cleanPath = rawPathname => {
|
83 | const trimmedPathname = trimPathname(rawPathname)
|
84 |
|
85 | let foundPath = trimmedPathname
|
86 | if (foundPath === `/index.html`) {
|
87 | foundPath = `/`
|
88 | }
|
89 |
|
90 | foundPath = normalizePagePath(foundPath)
|
91 |
|
92 | return foundPath
|
93 | }
|