-
Notifications
You must be signed in to change notification settings - Fork 12
/
getRoute.ts
86 lines (73 loc) · 2.38 KB
/
getRoute.ts
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
import type { Route } from '~/types'
import { asRootPath } from '~/utils/path-utils'
import { pipe } from '~/utils/pipe-utils'
import type { Rewrite } from '../types'
function extractLocaleSegment(input: string) {
const localeSegment = input.match(/\/[(\w-)]+/)?.[0]
return localeSegment?.replace(/\/\([\w-]+\)/, '') || ''
}
function removeLocaleSegment(input: string) {
return input.replace(/\/[(\w-)]+/, '')
}
function removePageSegment(input: string) {
return input.replace(/\/page\.([tj])sx?$/, '')
}
function removeGroupSegments(input: string) {
return input.replace(/\/\([\w-]+\)/g, '')
}
function removeParallelSegments(input: string) {
return input.replace(/\/@\w+/g, '')
}
function removeInterceptedSegments(input: string) {
let result = input.replace(/\(\.\)/g, '')
const twoDotsRegExp = /[[\w-\]]+\/\(\.{2}\)/g
while (twoDotsRegExp.test(result)) {
result = result.replace(twoDotsRegExp, '')
}
return result.replace(/.*\(\.{3}\)/g, '/')
}
function formatDynamicSegments(input: string) {
return input
.replace(/\/\[\[\.\.\.(\w+)\]\]/g, '/:$1*') // [[...slug]] -> :slug*
.replace(/\/\[\[(\w+)\]\]/g, '/:$1*') // [[slug]] -> :slug*
.replace(/\/\[\.\.\.(\w+)\]/g, '/:$1+') // [...slug] -> :slug+
.replace(/\/\[(\w+)\]/g, '/:$1') // [slug] -> :slug
}
function getRouteName({ originPath }: Rewrite) {
const formatRouteName = pipe(
removePageSegment,
removeGroupSegments,
removeParallelSegments,
removeInterceptedSegments
)
return asRootPath(formatRouteName(originPath))
}
function getRouteHref({ localizedPath }: Rewrite) {
const localeSegment = extractLocaleSegment(localizedPath)
const formatRouteHref = pipe(
removeLocaleSegment,
removePageSegment,
removeGroupSegments,
removeParallelSegments,
removeInterceptedSegments,
formatDynamicSegments
)
return asRootPath(localeSegment, formatRouteHref(localizedPath))
}
function isRouteRewrite({ originPath }: Rewrite): boolean {
return Boolean(originPath.match(/\/page\.([tj])sx?$/)) || originPath === '/'
}
export function isRoute(input: unknown): input is Route {
return Boolean(
input && typeof input === 'object' && 'name' in input && 'href' in input
)
}
export function getRoute(rewrite: Rewrite): Route | undefined {
if (isRouteRewrite(rewrite)) {
return {
name: getRouteName(rewrite),
href: getRouteHref(rewrite),
}
}
return undefined
}