-
-
Notifications
You must be signed in to change notification settings - Fork 10.9k
Expand file tree
/
Copy pathlib.tsx
More file actions
2225 lines (1944 loc) · 61.9 KB
/
lib.tsx
File metadata and controls
2225 lines (1944 loc) · 61.9 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
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as React from "react";
import type {
BrowserHistory,
HashHistory,
History,
Action as NavigationType,
Location,
To,
} from "../router/history";
import {
createBrowserHistory,
createHashHistory,
createPath,
invariant,
warning,
} from "../router/history";
import type {
BlockerFunction,
Fetcher,
FutureConfig,
GetScrollRestorationKeyFunction,
HydrationState,
RelativeRoutingType,
Router as DataRouter,
} from "../router/router";
import { IDLE_FETCHER, createRouter } from "../router/router";
import type {
DataStrategyFunction,
FormEncType,
HTMLFormMethod,
UIMatch,
} from "../router/utils";
import {
ErrorResponseImpl,
joinPaths,
matchPath,
stripBasename,
} from "../router/utils";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import type * as _ from "./global";
import type {
SubmitOptions,
URLSearchParamsInit,
SubmitTarget,
FetcherSubmitOptions,
} from "./dom";
import {
createSearchParams,
defaultMethod,
getFormSubmissionInfo,
getSearchParamsForLocation,
shouldProcessLinkClick,
} from "./dom";
import type {
DiscoverBehavior,
PrefetchBehavior,
ScriptsProps,
} from "./ssr/components";
import {
PrefetchPageLinks,
FrameworkContext,
mergeRefs,
usePrefetchBehavior,
} from "./ssr/components";
import { Router, mapRouteProperties } from "../components";
import type {
RouteObject,
NavigateOptions,
PatchRoutesOnNavigationFunction,
} from "../context";
import {
DataRouterContext,
DataRouterStateContext,
FetchersContext,
NavigationContext,
RouteContext,
ViewTransitionContext,
} from "../context";
import {
useBlocker,
useHref,
useLocation,
useMatches,
useNavigate,
useNavigation,
useResolvedPath,
useRouteId,
} from "../hooks";
import type { SerializeFrom } from "../types/route-data";
////////////////////////////////////////////////////////////////////////////////
//#region Global Stuff
////////////////////////////////////////////////////////////////////////////////
const isBrowser =
typeof window !== "undefined" &&
typeof window.document !== "undefined" &&
typeof window.document.createElement !== "undefined";
// HEY YOU! DON'T TOUCH THIS VARIABLE!
//
// It is replaced with the proper version at build time via a babel plugin in
// the rollup config.
//
// Export a global property onto the window for React Router detection by the
// Core Web Vitals Technology Report. This way they can configure the `wappalyzer`
// to detect and properly classify live websites as being built with React Router:
// https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json
declare global {
const REACT_ROUTER_VERSION: string;
}
try {
if (isBrowser) {
window.__reactRouterVersion = REACT_ROUTER_VERSION;
}
} catch (e) {
// no-op
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Routers
////////////////////////////////////////////////////////////////////////////////
interface DOMRouterOpts {
basename?: string;
future?: Partial<FutureConfig>;
hydrationData?: HydrationState;
dataStrategy?: DataStrategyFunction;
patchRoutesOnNavigation?: PatchRoutesOnNavigationFunction;
window?: Window;
}
/**
* @category Data Routers
*/
export function createBrowserRouter(
routes: RouteObject[],
opts?: DOMRouterOpts
): DataRouter {
return createRouter({
basename: opts?.basename,
future: opts?.future,
history: createBrowserHistory({ window: opts?.window }),
hydrationData: opts?.hydrationData || parseHydrationData(),
routes,
mapRouteProperties,
dataStrategy: opts?.dataStrategy,
patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,
window: opts?.window,
}).initialize();
}
/**
* @category Data Routers
*/
export function createHashRouter(
routes: RouteObject[],
opts?: DOMRouterOpts
): DataRouter {
return createRouter({
basename: opts?.basename,
future: opts?.future,
history: createHashHistory({ window: opts?.window }),
hydrationData: opts?.hydrationData || parseHydrationData(),
routes,
mapRouteProperties,
dataStrategy: opts?.dataStrategy,
patchRoutesOnNavigation: opts?.patchRoutesOnNavigation,
window: opts?.window,
}).initialize();
}
function parseHydrationData(): HydrationState | undefined {
let state = window?.__staticRouterHydrationData;
if (state && state.errors) {
state = {
...state,
errors: deserializeErrors(state.errors),
};
}
return state;
}
function deserializeErrors(
errors: DataRouter["state"]["errors"]
): DataRouter["state"]["errors"] {
if (!errors) return null;
let entries = Object.entries(errors);
let serialized: DataRouter["state"]["errors"] = {};
for (let [key, val] of entries) {
// Hey you! If you change this, please change the corresponding logic in
// serializeErrors in react-router-dom/server.tsx :)
if (val && val.__type === "RouteErrorResponse") {
serialized[key] = new ErrorResponseImpl(
val.status,
val.statusText,
val.data,
val.internal === true
);
} else if (val && val.__type === "Error") {
// Attempt to reconstruct the right type of Error (i.e., ReferenceError)
if (val.__subType) {
let ErrorConstructor = window[val.__subType];
if (typeof ErrorConstructor === "function") {
try {
// @ts-expect-error
let error = new ErrorConstructor(val.message);
// Wipe away the client-side stack trace. Nothing to fill it in with
// because we don't serialize SSR stack traces for security reasons
error.stack = "";
serialized[key] = error;
} catch (e) {
// no-op - fall through and create a normal Error
}
}
}
if (serialized[key] == null) {
let error = new Error(val.message);
// Wipe away the client-side stack trace. Nothing to fill it in with
// because we don't serialize SSR stack traces for security reasons
error.stack = "";
serialized[key] = error;
}
} else {
serialized[key] = val;
}
}
return serialized;
}
//#endregion
////////////////////////////////////////////////////////////////////////////////
//#region Components
////////////////////////////////////////////////////////////////////////////////
/**
* @category Types
*/
export interface BrowserRouterProps {
basename?: string;
children?: React.ReactNode;
window?: Window;
}
/**
* A `<Router>` for use in web browsers. Provides the cleanest URLs.
*
* @category Component Routers
*/
export function BrowserRouter({
basename,
children,
window,
}: BrowserRouterProps) {
let historyRef = React.useRef<BrowserHistory>();
if (historyRef.current == null) {
historyRef.current = createBrowserHistory({ window, v5Compat: true });
}
let history = historyRef.current;
let [state, setStateImpl] = React.useState({
action: history.action,
location: history.location,
});
let setState = React.useCallback(
(newState: { action: NavigationType; location: Location }) => {
React.startTransition(() => setStateImpl(newState));
},
[setStateImpl]
);
React.useLayoutEffect(() => history.listen(setState), [history, setState]);
return (
<Router
basename={basename}
children={children}
location={state.location}
navigationType={state.action}
navigator={history}
/>
);
}
/**
* @category Types
*/
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.
*
* @category Component Routers
*/
export function HashRouter({ basename, children, window }: HashRouterProps) {
let historyRef = React.useRef<HashHistory>();
if (historyRef.current == null) {
historyRef.current = createHashHistory({ window, v5Compat: true });
}
let history = historyRef.current;
let [state, setStateImpl] = React.useState({
action: history.action,
location: history.location,
});
let setState = React.useCallback(
(newState: { action: NavigationType; location: Location }) => {
React.startTransition(() => setStateImpl(newState));
},
[setStateImpl]
);
React.useLayoutEffect(() => history.listen(setState), [history, setState]);
return (
<Router
basename={basename}
children={children}
location={state.location}
navigationType={state.action}
navigator={history}
/>
);
}
/**
* @category Types
*/
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.
*
* @name unstable_HistoryRouter
* @category Component Routers
*/
export function HistoryRouter({
basename,
children,
history,
}: HistoryRouterProps) {
let [state, setStateImpl] = React.useState({
action: history.action,
location: history.location,
});
let setState = React.useCallback(
(newState: { action: NavigationType; location: Location }) => {
React.startTransition(() => setStateImpl(newState));
},
[setStateImpl]
);
React.useLayoutEffect(() => history.listen(setState), [history, setState]);
return (
<Router
basename={basename}
children={children}
location={state.location}
navigationType={state.action}
navigator={history}
/>
);
}
HistoryRouter.displayName = "unstable_HistoryRouter";
/**
* @category Types
*/
export interface LinkProps
extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
/**
Defines the link discovery behavior
```tsx
<Link /> // default ("render")
<Link discover="render" />
<Link discover="none" />
```
- **render** - default, discover the route when the link renders
- **none** - don't eagerly discover, only discover if the link is clicked
*/
discover?: DiscoverBehavior;
/**
Defines the data and module prefetching behavior for the link.
```tsx
<Link /> // default
<Link prefetch="none" />
<Link prefetch="intent" />
<Link prefetch="render" />
<Link prefetch="viewport" />
```
- **none** - default, no prefetching
- **intent** - prefetches when the user hovers or focuses the link
- **render** - prefetches when the link renders
- **viewport** - prefetches when the link is in the viewport, very useful for mobile
Prefetching is done with HTML `<link rel="prefetch">` tags. They are inserted after the link.
```tsx
<a href="..." />
<a href="..." />
<link rel="prefetch" /> // might conditionally render
```
Because of this, if you are using `nav :last-child` you will need to use `nav :last-of-type` so the styles don't conditionally fall off your last link (and any other similar selectors).
*/
prefetch?: PrefetchBehavior;
/**
Will use document navigation instead of client side routing when the link is clicked: the browser will handle the transition normally (as if it were an `<a href>`).
```tsx
<Link to="/logout" reloadDocument />
```
*/
reloadDocument?: boolean;
/**
Replaces the current entry in the history stack instead of pushing a new one onto it.
```tsx
<Link replace />
```
```
# with a history stack like this
A -> B
# normal link click pushes a new entry
A -> B -> C
# but with `replace`, B is replaced by C
A -> C
```
*/
replace?: boolean;
/**
Adds persistent client side routing state to the next location.
```tsx
<Link to="/somewhere/else" state={{ some: "value" }} />
```
The location state is accessed from the `location`.
```tsx
function SomeComp() {
const location = useLocation()
location.state; // { some: "value" }
}
```
This state is inaccessible on the server as it is implemented on top of [`history.state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state)
*/
state?: any;
/**
Prevents the scroll position from being reset to the top of the window when the link is clicked and the app is using {@link ScrollRestoration}. This only prevents new locations reseting scroll to the top, scroll position will be restored for back/forward button navigation.
```tsx
<Link to="?tab=one" preventScrollReset />
```
*/
preventScrollReset?: boolean;
/**
Defines the relative path behavior for the link.
```tsx
<Link to=".." /> // default: "route"
<Link relative="route" />
<Link relative="path" />
```
Consider a route hierarchy where a parent route pattern is "blog" and a child route pattern is "blog/:slug/edit".
- **route** - default, resolves the link relative to the route pattern. In the example above a relative link of `".."` will remove both `:slug/edit` segments back to "/blog".
- **path** - relative to the path so `..` will only remove one URL segment up to "/blog/:slug"
*/
relative?: RelativeRoutingType;
/**
Can be a string or a partial {@link Path}:
```tsx
<Link to="/some/path" />
<Link
to={{
pathname: "/some/path",
search: "?query=string",
hash: "#hash",
}}
/>
```
*/
to: To;
/**
Enables a [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) for this navigation.
```jsx
<Link to={to} viewTransition>
Click me
</Link>
```
To apply specific styles for the transition, see {@link useViewTransitionState}
*/
viewTransition?: boolean;
}
const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
/**
A progressively enhanced `<a href>` wrapper to enable navigation with client-side routing.
```tsx
import { Link } from "react-router";
<Link to="/dashboard">Dashboard</Link>;
<Link
to={{
pathname: "/some/path",
search: "?query=string",
hash: "#hash",
}}
/>
```
@category Components
*/
export const Link = React.forwardRef<HTMLAnchorElement, LinkProps>(
function LinkWithRef(
{
onClick,
discover = "render",
prefetch = "none",
relative,
reloadDocument,
replace,
state,
target,
to,
preventScrollReset,
viewTransition,
...rest
},
forwardedRef
) {
let { basename } = React.useContext(NavigationContext);
let isAbsolute = typeof to === "string" && ABSOLUTE_URL_REGEX.test(to);
// Rendered into <a href> for absolute URLs
let absoluteHref;
let isExternal = false;
if (typeof to === "string" && isAbsolute) {
// Render the absolute href server- and client-side
absoluteHref = to;
// Only check for external origins client-side
if (isBrowser) {
try {
let currentUrl = new URL(window.location.href);
let targetUrl = to.startsWith("//")
? new URL(currentUrl.protocol + to)
: new URL(to);
let path = stripBasename(targetUrl.pathname, basename);
if (targetUrl.origin === currentUrl.origin && path != null) {
// Strip the protocol/origin/basename for same-origin absolute URLs
to = path + targetUrl.search + targetUrl.hash;
} else {
isExternal = true;
}
} catch (e) {
// We can't do external URL detection without a valid URL
warning(
false,
`<Link to="${to}"> contains an invalid URL which will probably break ` +
`when clicked - please update to a valid URL path.`
);
}
}
}
// Rendered into <a href> for relative URLs
let href = useHref(to, { relative });
let [shouldPrefetch, prefetchRef, prefetchHandlers] = usePrefetchBehavior(
prefetch,
rest
);
let internalOnClick = useLinkClickHandler(to, {
replace,
state,
target,
preventScrollReset,
relative,
viewTransition,
});
function handleClick(
event: React.MouseEvent<HTMLAnchorElement, MouseEvent>
) {
if (onClick) onClick(event);
if (!event.defaultPrevented) {
internalOnClick(event);
}
}
let link = (
// eslint-disable-next-line jsx-a11y/anchor-has-content
<a
{...rest}
{...prefetchHandlers}
href={absoluteHref || href}
onClick={isExternal || reloadDocument ? onClick : handleClick}
ref={mergeRefs(forwardedRef, prefetchRef)}
target={target}
data-discover={
!isAbsolute && discover === "render" ? "true" : undefined
}
/>
);
return shouldPrefetch && !isAbsolute ? (
<>
{link}
<PrefetchPageLinks page={href} />
</>
) : (
link
);
}
);
Link.displayName = "Link";
/**
The object passed to {@link NavLink} `children`, `className`, and `style` prop callbacks to render and style the link based on its state.
```
// className
<NavLink
to="/messages"
className={({ isActive, isPending }) =>
isPending ? "pending" : isActive ? "active" : ""
}
>
Messages
</NavLink>
// style
<NavLink
to="/messages"
style={({ isActive, isPending }) => {
return {
fontWeight: isActive ? "bold" : "",
color: isPending ? "red" : "black",
}
)}
/>
// children
<NavLink to="/tasks">
{({ isActive, isPending }) => (
<span className={isActive ? "active" : ""}>Tasks</span>
)}
</NavLink>
```
*/
export type NavLinkRenderProps = {
/**
* Indicates if the link's URL matches the current location.
*/
isActive: boolean;
/**
* Indicates if the pending location matches the link's URL.
*/
isPending: boolean;
/**
* Indicates if a view transition to the link's URL is in progress. See {@link useViewTransitionState}
*/
isTransitioning: boolean;
};
/**
* @category Types
*/
export interface NavLinkProps
extends Omit<LinkProps, "className" | "style" | "children"> {
/**
Can be regular React children or a function that receives an object with the active and pending states of the link.
```tsx
<NavLink to="/tasks">
{({ isActive }) => (
<span className={isActive ? "active" : ""}>Tasks</span>
)}
</NavLink>
```
*/
children?: React.ReactNode | ((props: NavLinkRenderProps) => React.ReactNode);
/**
Changes the matching logic to make it case-sensitive:
| Link | URL | isActive |
| -------------------------------------------- | ------------- | -------- |
| `<NavLink to="/SpOnGe-bOB" />` | `/sponge-bob` | true |
| `<NavLink to="/SpOnGe-bOB" caseSensitive />` | `/sponge-bob` | false |
*/
caseSensitive?: boolean;
/**
Classes are automatically applied to NavLink that correspond to {@link NavLinkRenderProps}.
```css
a.active { color: red; }
a.pending { color: blue; }
a.transitioning {
view-transition-name: my-transition;
}
```
*/
className?: string | ((props: NavLinkRenderProps) => string | undefined);
/**
Changes the matching logic for the `active` and `pending` states to only match to the "end" of the {@link NavLinkProps.to}. If the URL is longer, it will no longer be considered active.
| Link | URL | isActive |
| ----------------------------- | ------------ | -------- |
| `<NavLink to="/tasks" />` | `/tasks` | true |
| `<NavLink to="/tasks" />` | `/tasks/123` | true |
| `<NavLink to="/tasks" end />` | `/tasks` | true |
| `<NavLink to="/tasks" end />` | `/tasks/123` | false |
`<NavLink to="/">` is an exceptional case because _every_ URL matches `/`. To avoid this matching every single route by default, it effectively ignores the `end` prop and only matches when you're at the root route.
*/
end?: boolean;
style?:
| React.CSSProperties
| ((props: NavLinkRenderProps) => React.CSSProperties | undefined);
}
/**
Wraps {@link Link | `<Link>`} with additional props for styling active and pending states.
- Automatically applies classes to the link based on its active and pending states, see {@link NavLinkProps.className}.
- Automatically applies `aria-current="page"` to the link when the link is active. See [`aria-current`](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current) on MDN.
```tsx
import { NavLink } from "react-router"
<NavLink to="/message" />
```
States are available through the className, style, and children render props. See {@link NavLinkRenderProps}.
```tsx
<NavLink
to="/messages"
className={({ isActive, isPending }) =>
isPending ? "pending" : isActive ? "active" : ""
}
>
Messages
</NavLink>
```
@category Components
*/
export const NavLink = React.forwardRef<HTMLAnchorElement, NavLinkProps>(
function NavLinkWithRef(
{
"aria-current": ariaCurrentProp = "page",
caseSensitive = false,
className: classNameProp = "",
end = false,
style: styleProp,
to,
viewTransition,
children,
...rest
},
ref
) {
let path = useResolvedPath(to, { relative: rest.relative });
let location = useLocation();
let routerState = React.useContext(DataRouterStateContext);
let { navigator, basename } = React.useContext(NavigationContext);
let isTransitioning =
routerState != null &&
// Conditional usage is OK here because the usage of a data router is static
// eslint-disable-next-line react-hooks/rules-of-hooks
useViewTransitionState(path) &&
viewTransition === true;
let toPathname = navigator.encodeLocation
? navigator.encodeLocation(path).pathname
: path.pathname;
let locationPathname = location.pathname;
let nextLocationPathname =
routerState && routerState.navigation && routerState.navigation.location
? routerState.navigation.location.pathname
: null;
if (!caseSensitive) {
locationPathname = locationPathname.toLowerCase();
nextLocationPathname = nextLocationPathname
? nextLocationPathname.toLowerCase()
: null;
toPathname = toPathname.toLowerCase();
}
if (nextLocationPathname && basename) {
nextLocationPathname =
stripBasename(nextLocationPathname, basename) || nextLocationPathname;
}
// If the `to` has a trailing slash, look at that exact spot. Otherwise,
// we're looking for a slash _after_ what's in `to`. For example:
//
// <NavLink to="/users"> and <NavLink to="/users/">
// both want to look for a / at index 6 to match URL `/users/matt`
const endSlashPosition =
toPathname !== "/" && toPathname.endsWith("/")
? toPathname.length - 1
: toPathname.length;
let isActive =
locationPathname === toPathname ||
(!end &&
locationPathname.startsWith(toPathname) &&
locationPathname.charAt(endSlashPosition) === "/");
let isPending =
nextLocationPathname != null &&
(nextLocationPathname === toPathname ||
(!end &&
nextLocationPathname.startsWith(toPathname) &&
nextLocationPathname.charAt(toPathname.length) === "/"));
let renderProps = {
isActive,
isPending,
isTransitioning,
};
let ariaCurrent = isActive ? ariaCurrentProp : undefined;
let className: string | undefined;
if (typeof classNameProp === "function") {
className = classNameProp(renderProps);
} 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,
isPending ? "pending" : null,
isTransitioning ? "transitioning" : null,
]
.filter(Boolean)
.join(" ");
}
let style =
typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
return (
<Link
{...rest}
aria-current={ariaCurrent}
className={className}
ref={ref}
style={style}
to={to}
viewTransition={viewTransition}
>
{typeof children === "function" ? children(renderProps) : children}
</Link>
);
}
);
NavLink.displayName = "NavLink";
/**
* Form props shared by navigations and fetchers
*/
interface SharedFormProps extends React.FormHTMLAttributes<HTMLFormElement> {
/**
* The HTTP verb to use when the form is submitted. Supports "get", "post",
* "put", "delete", and "patch".
*
* Native `<form>` only supports `get` and `post`, avoid the other verbs if
* you'd like to support progressive enhancement
*/
method?: HTMLFormMethod;
/**
* The encoding type to use for the form submission.
*/
encType?:
| "application/x-www-form-urlencoded"
| "multipart/form-data"
| "text/plain";
/**
* The URL to submit the form data to. If `undefined`, this defaults to the closest route in context.
*/
action?: string;
/**
* Determines whether the form action is relative to the route hierarchy or
* the pathname. Use this if you want to opt out of navigating the route
* hierarchy and want to instead route based on /-delimited URL segments
*/
relative?: RelativeRoutingType;
/**
* Prevent the scroll position from resetting to the top of the viewport on
* completion of the navigation when using the <ScrollRestoration> component
*/
preventScrollReset?: boolean;
/**
* A function to call when the form is submitted. If you call
* `event.preventDefault()` then this form will not do anything.
*/
onSubmit?: React.FormEventHandler<HTMLFormElement>;
}
/**
* Form props available to fetchers
* @category Types
*/
export interface FetcherFormProps extends SharedFormProps {}
/**
* Form props available to navigations
* @category Types
*/
export interface FormProps extends SharedFormProps {
discover?: DiscoverBehavior;
/**
* Indicates a specific fetcherKey to use when using `navigate={false}` so you
* can pick up the fetcher's state in a different component in a {@link
* useFetcher}.
*/
fetcherKey?: string;
/**
* Skips the navigation and uses a {@link useFetcher | fetcher} internally
* when `false`. This is essentially a shorthand for `useFetcher()` +
* `<fetcher.Form>` where you don't care about the resulting data in this
* component.
*/
navigate?: boolean;
/**
* Forces a full document navigation instead of client side routing + data
* fetch.
*/
reloadDocument?: boolean;
/**
* Replaces the current entry in the browser history stack when the form
* navigates. Use this if you don't want the user to be able to click "back"