forked from remix-run/react-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.tsx
506 lines (453 loc) · 13.4 KB
/
index.tsx
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
import * as React from "react";
import type { BrowserHistory, HashHistory, History } from "history";
import { createBrowserHistory, createHashHistory, createPath } from "history";
import {
MemoryRouter,
Navigate,
Outlet,
Route,
Router,
Routes,
createRoutesFromChildren,
generatePath,
matchRoutes,
matchPath,
resolvePath,
renderMatches,
useHref,
useInRouterContext,
useLocation,
useMatch,
useNavigate,
useNavigationType,
useOutlet,
useParams,
useResolvedPath,
useRoutes,
useOutletContext
} from "react-router";
import type { To } from "react-router";
function warning(cond: boolean, message: string): void {
if (!cond) {
// eslint-disable-next-line no-console
if (typeof console !== "undefined") console.warn(message);
try {
// Welcome to debugging React Router!
//
// This error is thrown as a convenience so you can more easily
// find the source for a warning that appears in the console by
// enabling "pause on exceptions" in your JavaScript debugger.
throw new Error(message);
// eslint-disable-next-line no-empty
} catch (e) {}
}
}
////////////////////////////////////////////////////////////////////////////////
// RE-EXPORTS
////////////////////////////////////////////////////////////////////////////////
// Note: Keep in sync with react-router exports!
export {
MemoryRouter,
Navigate,
Outlet,
Route,
Router,
Routes,
createRoutesFromChildren,
generatePath,
matchRoutes,
matchPath,
renderMatches,
resolvePath,
useHref,
useInRouterContext,
useLocation,
useMatch,
useNavigate,
useNavigationType,
useOutlet,
useParams,
useResolvedPath,
useRoutes,
useOutletContext
};
export type {
Location,
Path,
To,
NavigationType,
MemoryRouterProps,
NavigateFunction,
NavigateOptions,
NavigateProps,
Navigator,
OutletProps,
Params,
PathMatch,
RouteMatch,
RouteObject,
RouteProps,
PathRouteProps,
LayoutRouteProps,
IndexRouteProps,
RouterProps,
RoutesProps
} from "react-router";
///////////////////////////////////////////////////////////////////////////////
// DANGER! PLEASE READ ME!
// We provide these exports as an escape hatch in the event that you need any
// routing data that we don't provide an explicit API for. With that said, we
// want to cover your use case if we can, so if you feel the need to use these
// we want to hear from you. Let us know what you're building and we'll do our
// best to make sure we can support you!
//
// We consider these exports an implementation detail and do not guarantee
// against any breaking changes, regardless of the semver release. Use with
// extreme caution and only if you understand the consequences. Godspeed.
///////////////////////////////////////////////////////////////////////////////
/** @internal */
export {
UNSAFE_NavigationContext,
UNSAFE_LocationContext,
UNSAFE_RouteContext
} from "react-router";
////////////////////////////////////////////////////////////////////////////////
// COMPONENTS
////////////////////////////////////////////////////////////////////////////////
export interface BrowserRouterProps {
basename?: string;
children?: React.ReactNode;
window?: Window;
}
/**
* A `<Router>` for use in web browsers. Provides the cleanest URLs.
*/
export function BrowserRouter({
basename,
children,
window
}: BrowserRouterProps) {
let historyRef = React.useRef<BrowserHistory>();
if (historyRef.current == null) {
historyRef.current = createBrowserHistory({ window });
}
let history = historyRef.current;
let [state, setState] = React.useState({
action: history.action,
location: history.location
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return (
<Router
basename={basename}
children={children}
location={state.location}
navigationType={state.action}
navigator={history}
/>
);
}
export interface HashRouterProps {
basename?: string;
children?: React.ReactNode;
window?: Window;
}
/**
* A `<Router>` for use in web browsers. Stores the location in the hash
* portion of the URL so it is not sent to the server.
*/
export function HashRouter({ basename, children, window }: HashRouterProps) {
let historyRef = React.useRef<HashHistory>();
if (historyRef.current == null) {
historyRef.current = createHashHistory({ window });
}
let history = historyRef.current;
let [state, setState] = React.useState({
action: history.action,
location: history.location
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return (
<Router
basename={basename}
children={children}
location={state.location}
navigationType={state.action}
navigator={history}
/>
);
}
export interface HistoryRouterProps {
basename?: string;
children?: React.ReactNode;
history: History;
}
/**
* A `<Router>` that accepts a pre-instantiated history object. It's important
* to note that using your own history object is highly discouraged and may add
* two versions of the history library to your bundles unless you use the same
* version of the history library that React Router uses internally.
*/
function HistoryRouter({ basename, children, history }: HistoryRouterProps) {
const [state, setState] = React.useState({
action: history.action,
location: history.location
});
React.useLayoutEffect(() => history.listen(setState), [history]);
return (
<Router
basename={basename}
children={children}
location={state.location}
navigationType={state.action}
navigator={history}
/>
);
}
if (__DEV__) {
HistoryRouter.displayName = "unstable_HistoryRouter";
}
export { HistoryRouter as unstable_HistoryRouter };
function isModifiedEvent(event: React.MouseEvent) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
export interface LinkProps
extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
reloadDocument?: boolean;
replace?: boolean;
state?: any;
to: To;
}
/**
* The public API for rendering a history-aware <a>.
*/
export const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(
function LinkWithRef(
{ onClick, reloadDocument, replace = false, state, target, to, ...rest },
ref
) {
let href = useHref(to);
let internalOnClick = useLinkClickHandler(to, { replace, state, target });
function handleClick(
event: React.MouseEvent<HTMLAnchorElement, MouseEvent>
) {
if (onClick) onClick(event);
if (!event.defaultPrevented && !reloadDocument) {
internalOnClick(event);
}
}
return (
// eslint-disable-next-line jsx-a11y/anchor-has-content
<a
{...rest}
href={href}
onClick={handleClick}
ref={ref}
target={target}
/>
);
}
);
if (__DEV__) {
Link.displayName = "Link";
}
export interface NavLinkProps
extends Omit<LinkProps, "className" | "style" | "children"> {
children:
| React.ReactNode
| ((props: { isActive: boolean }) => React.ReactNode);
caseSensitive?: boolean;
className?: string | ((props: { isActive: boolean }) => string | undefined);
end?: boolean;
style?:
| React.CSSProperties
| ((props: { isActive: boolean }) => React.CSSProperties);
}
/**
* A <Link> wrapper that knows if it's "active" or not.
*/
export const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(
function NavLinkWithRef(
{
"aria-current": ariaCurrentProp = "page",
caseSensitive = false,
className: classNameProp = "",
end = false,
style: styleProp,
to,
children,
...rest
},
ref
) {
let location = useLocation();
let path = useResolvedPath(to);
let locationPathname = location.pathname;
let toPathname = path.pathname;
if (!caseSensitive) {
locationPathname = locationPathname.toLowerCase();
toPathname = toPathname.toLowerCase();
}
let isActive =
locationPathname === toPathname ||
(!end &&
locationPathname.startsWith(toPathname) &&
locationPathname.charAt(toPathname.length) === "/");
let ariaCurrent = isActive ? ariaCurrentProp : undefined;
let className: string | undefined;
if (typeof classNameProp === "function") {
className = classNameProp({ isActive });
} else {
// If the className prop is not a function, we use a default `active`
// class for <NavLink />s that are active. In v5 `active` was the default
// value for `activeClassName`, but we are removing that API and can still
// use the old default behavior for a cleaner upgrade path and keep the
// simple styling rules working as they currently do.
className = [classNameProp, isActive ? "active" : null]
.filter(Boolean)
.join(" ");
}
let style =
typeof styleProp === "function" ? styleProp({ isActive }) : styleProp;
return (
<Link
{...rest}
aria-current={ariaCurrent}
className={className}
ref={ref}
style={style}
to={to}
>
{typeof children === "function" ? children({ isActive }) : children}
</Link>
);
}
);
if (__DEV__) {
NavLink.displayName = "NavLink";
}
////////////////////////////////////////////////////////////////////////////////
// HOOKS
////////////////////////////////////////////////////////////////////////////////
/**
* Handles the click behavior for router `<Link>` components. This is useful if
* you need to create custom `<Link>` components with the same click behavior we
* use in our exported `<Link>`.
*/
export function useLinkClickHandler<E extends Element = HTMLAnchorElement>(
to: To,
{
target,
replace: replaceProp,
state
}: {
target?: React.HTMLAttributeAnchorTarget;
replace?: boolean;
state?: any;
} = {}
): (event: React.MouseEvent<E, MouseEvent>) => void {
let navigate = useNavigate();
let location = useLocation();
let path = useResolvedPath(to);
return React.useCallback(
(event: React.MouseEvent<E, MouseEvent>) => {
if (
event.button === 0 && // Ignore everything but left clicks
(!target || target === "_self") && // Let browser handle "target=_blank" etc.
!isModifiedEvent(event) // Ignore clicks with modifier keys
) {
event.preventDefault();
// If the URL hasn't changed, a regular <a> will do a replace instead of
// a push, so do the same here.
let replace =
!!replaceProp || createPath(location) === createPath(path);
navigate(to, { replace, state });
}
},
[location, navigate, path, replaceProp, state, target, to]
);
}
/**
* A convenient wrapper for reading and writing search parameters via the
* URLSearchParams interface.
*/
export function useSearchParams(defaultInit?: URLSearchParamsInit) {
warning(
typeof URLSearchParams !== "undefined",
`You cannot use the \`useSearchParams\` hook in a browser that does not ` +
`support the URLSearchParams API. If you need to support Internet ` +
`Explorer 11, we recommend you load a polyfill such as ` +
`https://github.com/ungap/url-search-params\n\n` +
`If you're unsure how to load polyfills, we recommend you check out ` +
`https://polyfill.io/v3/ which provides some recommendations about how ` +
`to load polyfills only for users that need them, instead of for every ` +
`user.`
);
let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));
let location = useLocation();
let searchParams = React.useMemo(() => {
let searchParams = createSearchParams(location.search);
for (let key of defaultSearchParamsRef.current.keys()) {
if (!searchParams.has(key)) {
defaultSearchParamsRef.current.getAll(key).forEach(value => {
searchParams.append(key, value);
});
}
}
return searchParams;
}, [location.search]);
let navigate = useNavigate();
let setSearchParams = React.useCallback(
(
nextInit: URLSearchParamsInit,
navigateOptions?: { replace?: boolean; state?: any }
) => {
navigate("?" + createSearchParams(nextInit), navigateOptions);
},
[navigate]
);
return [searchParams, setSearchParams] as const;
}
export type ParamKeyValuePair = [string, string];
export type URLSearchParamsInit =
| string
| ParamKeyValuePair[]
| Record<string, string | string[]>
| URLSearchParams;
/**
* Creates a URLSearchParams object using the given initializer.
*
* This is identical to `new URLSearchParams(init)` except it also
* supports arrays as values in the object form of the initializer
* instead of just strings. This is convenient when you need multiple
* values for a given key, but don't want to use an array initializer.
*
* For example, instead of:
*
* let searchParams = new URLSearchParams([
* ['sort', 'name'],
* ['sort', 'price']
* ]);
*
* you can do:
*
* let searchParams = createSearchParams({
* sort: ['name', 'price']
* });
*/
export function createSearchParams(
init: URLSearchParamsInit = ""
): URLSearchParams {
return new URLSearchParams(
typeof init === "string" ||
Array.isArray(init) ||
init instanceof URLSearchParams
? init
: Object.keys(init).reduce((memo, key) => {
let value = init[key];
return memo.concat(
Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]
);
}, [] as ParamKeyValuePair[])
);
}