UNPKG

1.54 kBJavaScriptView Raw
1import { match } from "@reach/router/lib/utils"
2import stripPrefix from "./strip-prefix"
3import normalizePagePath from "./normalize-page-path"
4
5let matchPaths = []
6
7const trimPathname = rawPathname => {
8 let pathname = decodeURIComponent(rawPathname)
9 // Remove the pathPrefix from the pathname.
10 let trimmedPathname = stripPrefix(pathname, __BASE_PATH__)
11 // Remove any hashfragment
12 .split(`#`)[0]
13 // Remove search query
14 .split(`?`)[0]
15
16 return trimmedPathname
17}
18
19/**
20 * Set list of matchPaths
21 *
22 * @param {Array<{path: string, matchPath: string}>} value collection of matchPaths
23 */
24export const setMatchPaths = value => {
25 matchPaths = value
26}
27
28/**
29 * Return a matchpath url
30 * if `match-paths.json` contains `{ "/foo*": "/page1", ...}`, then
31 * `/foo?bar=far` => `/page1`
32 *
33 * @param {string} rawPathname A raw pathname
34 * @return {string|null}
35 */
36export const findMatchPath = rawPathname => {
37 const trimmedPathname = cleanPath(rawPathname)
38
39 for (const { matchPath, path } of matchPaths) {
40 if (match(matchPath, trimmedPathname)) {
41 return normalizePagePath(path)
42 }
43 }
44
45 return null
46}
47
48/**
49 * Clean a url and converts /index.html => /
50 * E.g `/foo?bar=far` => `/foo`
51 *
52 * @param {string} rawPathname A raw pathname
53 * @return {string}
54 */
55export const cleanPath = rawPathname => {
56 const trimmedPathname = trimPathname(rawPathname)
57
58 let foundPath = trimmedPathname
59 if (foundPath === `/index.html`) {
60 foundPath = `/`
61 }
62
63 foundPath = normalizePagePath(foundPath)
64
65 return foundPath
66}