-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathutils.ts
More file actions
89 lines (75 loc) · 2.34 KB
/
Copy pathutils.ts
File metadata and controls
89 lines (75 loc) · 2.34 KB
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
87
88
89
import React from 'react'
import { useLocation, useParams } from 'react-router-dom'
import { createUrl, getFullPath } from '../utils/route'
import type { Base, Meta, PagePropsOptions, State } from '../utils/types'
import type { PropsProvider as PropsProviderType, RouteRaw } from './types'
type RouterOptions = {
base?: Base
routes: RouteRaw[]
initialState?: State
PropsProvider?: PropsProviderType
pagePropsOptions?: PagePropsOptions
}
export function createRouter({
base,
routes,
initialState,
PropsProvider,
pagePropsOptions = { passToPage: true },
}: RouterOptions) {
let currentRoute: RouteRaw | undefined = undefined
function augmentRoute(originalRoute: RouteRaw) {
const meta: Meta = {
...(originalRoute.meta || {}),
state: null,
}
const augmentedRoute: RouteRaw = {
...originalRoute,
meta,
component: (props: Record<string, any>) => {
const { pathname, hash, search } = useLocation()
const url = createUrl(pathname + search + hash)
const routeBase = base && base({ url })
const from = currentRoute
const to = {
...augmentedRoute,
path: pathname,
hash,
search,
params: useParams(),
query: Object.fromEntries(url.searchParams),
fullPath: getFullPath(url, routeBase),
}
if (!currentRoute) {
// First route, use provided initialState
meta.state = initialState
}
currentRoute = to
if (PropsProvider) {
return React.createElement(
PropsProvider,
{ ...props, from, to, pagePropsOptions },
originalRoute.component
)
}
const { passToPage } = pagePropsOptions || {}
return React.createElement(originalRoute.component, {
...props,
...((passToPage && meta.state) || {}),
})
},
}
if (Array.isArray(originalRoute.routes)) {
augmentedRoute.routes = originalRoute.routes.map(augmentRoute)
// Nested routes compatibility with React Router 6
augmentedRoute.children = augmentedRoute.routes
}
return augmentedRoute
}
return {
getCurrentRoute: () => currentRoute,
isFirstRoute: () => !currentRoute,
routes: routes.map(augmentRoute),
}
}
export type Router = ReturnType<typeof createRouter>