react-router.development.js 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  1. /**
  2. * React Router v6.30.1
  3. *
  4. * Copyright (c) Remix Software Inc.
  5. *
  6. * This source code is licensed under the MIT license found in the
  7. * LICENSE.md file in the root directory of this source tree.
  8. *
  9. * @license MIT
  10. */
  11. import * as React from 'react';
  12. import { UNSAFE_invariant, joinPaths, matchPath, UNSAFE_decodePath, UNSAFE_getResolveToMatches, UNSAFE_warning, resolveTo, parsePath, matchRoutes, Action, UNSAFE_convertRouteMatchToUiMatch, stripBasename, IDLE_BLOCKER, isRouteErrorResponse, createMemoryHistory, AbortedDeferredError, createRouter } from '@remix-run/router';
  13. export { AbortedDeferredError, Action as NavigationType, createPath, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, replace, resolvePath } from '@remix-run/router';
  14. const DataRouterContext = /*#__PURE__*/React.createContext(null);
  15. {
  16. DataRouterContext.displayName = "DataRouter";
  17. }
  18. const DataRouterStateContext = /*#__PURE__*/React.createContext(null);
  19. {
  20. DataRouterStateContext.displayName = "DataRouterState";
  21. }
  22. const AwaitContext = /*#__PURE__*/React.createContext(null);
  23. {
  24. AwaitContext.displayName = "Await";
  25. }
  26. const NavigationContext = /*#__PURE__*/React.createContext(null);
  27. {
  28. NavigationContext.displayName = "Navigation";
  29. }
  30. const LocationContext = /*#__PURE__*/React.createContext(null);
  31. {
  32. LocationContext.displayName = "Location";
  33. }
  34. const RouteContext = /*#__PURE__*/React.createContext({
  35. outlet: null,
  36. matches: [],
  37. isDataRoute: false
  38. });
  39. {
  40. RouteContext.displayName = "Route";
  41. }
  42. const RouteErrorContext = /*#__PURE__*/React.createContext(null);
  43. {
  44. RouteErrorContext.displayName = "RouteError";
  45. }
  46. /**
  47. * Returns the full href for the given "to" value. This is useful for building
  48. * custom links that are also accessible and preserve right-click behavior.
  49. *
  50. * @see https://reactrouter.com/v6/hooks/use-href
  51. */
  52. function useHref(to, {
  53. relative
  54. } = {}) {
  55. !useInRouterContext() ? UNSAFE_invariant(false,
  56. // TODO: This error is probably because they somehow have 2 versions of the
  57. // router loaded. We can help them understand how to avoid that.
  58. `useHref() may be used only in the context of a <Router> component.`) : void 0;
  59. let {
  60. basename,
  61. navigator
  62. } = React.useContext(NavigationContext);
  63. let {
  64. hash,
  65. pathname,
  66. search
  67. } = useResolvedPath(to, {
  68. relative
  69. });
  70. let joinedPathname = pathname;
  71. // If we're operating within a basename, prepend it to the pathname prior
  72. // to creating the href. If this is a root navigation, then just use the raw
  73. // basename which allows the basename to have full control over the presence
  74. // of a trailing slash on root links
  75. if (basename !== "/") {
  76. joinedPathname = pathname === "/" ? basename : joinPaths([basename, pathname]);
  77. }
  78. return navigator.createHref({
  79. pathname: joinedPathname,
  80. search,
  81. hash
  82. });
  83. }
  84. /**
  85. * Returns true if this component is a descendant of a `<Router>`.
  86. *
  87. * @see https://reactrouter.com/v6/hooks/use-in-router-context
  88. */
  89. function useInRouterContext() {
  90. return React.useContext(LocationContext) != null;
  91. }
  92. /**
  93. * Returns the current location object, which represents the current URL in web
  94. * browsers.
  95. *
  96. * Note: If you're using this it may mean you're doing some of your own
  97. * "routing" in your app, and we'd like to know what your use case is. We may
  98. * be able to provide something higher-level to better suit your needs.
  99. *
  100. * @see https://reactrouter.com/v6/hooks/use-location
  101. */
  102. function useLocation() {
  103. !useInRouterContext() ? UNSAFE_invariant(false,
  104. // TODO: This error is probably because they somehow have 2 versions of the
  105. // router loaded. We can help them understand how to avoid that.
  106. `useLocation() may be used only in the context of a <Router> component.`) : void 0;
  107. return React.useContext(LocationContext).location;
  108. }
  109. /**
  110. * Returns the current navigation action which describes how the router came to
  111. * the current location, either by a pop, push, or replace on the history stack.
  112. *
  113. * @see https://reactrouter.com/v6/hooks/use-navigation-type
  114. */
  115. function useNavigationType() {
  116. return React.useContext(LocationContext).navigationType;
  117. }
  118. /**
  119. * Returns a PathMatch object if the given pattern matches the current URL.
  120. * This is useful for components that need to know "active" state, e.g.
  121. * `<NavLink>`.
  122. *
  123. * @see https://reactrouter.com/v6/hooks/use-match
  124. */
  125. function useMatch(pattern) {
  126. !useInRouterContext() ? UNSAFE_invariant(false,
  127. // TODO: This error is probably because they somehow have 2 versions of the
  128. // router loaded. We can help them understand how to avoid that.
  129. `useMatch() may be used only in the context of a <Router> component.`) : void 0;
  130. let {
  131. pathname
  132. } = useLocation();
  133. return React.useMemo(() => matchPath(pattern, UNSAFE_decodePath(pathname)), [pathname, pattern]);
  134. }
  135. const navigateEffectWarning = `You should call navigate() in a React.useEffect(), not when ` + `your component is first rendered.`;
  136. // Mute warnings for calls to useNavigate in SSR environments
  137. function useIsomorphicLayoutEffect(cb) {
  138. let isStatic = React.useContext(NavigationContext).static;
  139. if (!isStatic) {
  140. // We should be able to get rid of this once react 18.3 is released
  141. // See: https://github.com/facebook/react/pull/26395
  142. // eslint-disable-next-line react-hooks/rules-of-hooks
  143. React.useLayoutEffect(cb);
  144. }
  145. }
  146. /**
  147. * Returns an imperative method for changing the location. Used by `<Link>`s, but
  148. * may also be used by other elements to change the location.
  149. *
  150. * @see https://reactrouter.com/v6/hooks/use-navigate
  151. */
  152. function useNavigate() {
  153. let {
  154. isDataRoute
  155. } = React.useContext(RouteContext);
  156. // Conditional usage is OK here because the usage of a data router is static
  157. // eslint-disable-next-line react-hooks/rules-of-hooks
  158. return isDataRoute ? useNavigateStable() : useNavigateUnstable();
  159. }
  160. function useNavigateUnstable() {
  161. !useInRouterContext() ? UNSAFE_invariant(false,
  162. // TODO: This error is probably because they somehow have 2 versions of the
  163. // router loaded. We can help them understand how to avoid that.
  164. `useNavigate() may be used only in the context of a <Router> component.`) : void 0;
  165. let dataRouterContext = React.useContext(DataRouterContext);
  166. let {
  167. basename,
  168. future,
  169. navigator
  170. } = React.useContext(NavigationContext);
  171. let {
  172. matches
  173. } = React.useContext(RouteContext);
  174. let {
  175. pathname: locationPathname
  176. } = useLocation();
  177. let routePathnamesJson = JSON.stringify(UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath));
  178. let activeRef = React.useRef(false);
  179. useIsomorphicLayoutEffect(() => {
  180. activeRef.current = true;
  181. });
  182. let navigate = React.useCallback((to, options = {}) => {
  183. UNSAFE_warning(activeRef.current, navigateEffectWarning) ;
  184. // Short circuit here since if this happens on first render the navigate
  185. // is useless because we haven't wired up our history listener yet
  186. if (!activeRef.current) return;
  187. if (typeof to === "number") {
  188. navigator.go(to);
  189. return;
  190. }
  191. let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path");
  192. // If we're operating within a basename, prepend it to the pathname prior
  193. // to handing off to history (but only if we're not in a data router,
  194. // otherwise it'll prepend the basename inside of the router).
  195. // If this is a root navigation, then we navigate to the raw basename
  196. // which allows the basename to have full control over the presence of a
  197. // trailing slash on root links
  198. if (dataRouterContext == null && basename !== "/") {
  199. path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  200. }
  201. (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
  202. }, [basename, navigator, routePathnamesJson, locationPathname, dataRouterContext]);
  203. return navigate;
  204. }
  205. const OutletContext = /*#__PURE__*/React.createContext(null);
  206. /**
  207. * Returns the context (if provided) for the child route at this level of the route
  208. * hierarchy.
  209. * @see https://reactrouter.com/v6/hooks/use-outlet-context
  210. */
  211. function useOutletContext() {
  212. return React.useContext(OutletContext);
  213. }
  214. /**
  215. * Returns the element for the child route at this level of the route
  216. * hierarchy. Used internally by `<Outlet>` to render child routes.
  217. *
  218. * @see https://reactrouter.com/v6/hooks/use-outlet
  219. */
  220. function useOutlet(context) {
  221. let outlet = React.useContext(RouteContext).outlet;
  222. if (outlet) {
  223. return /*#__PURE__*/React.createElement(OutletContext.Provider, {
  224. value: context
  225. }, outlet);
  226. }
  227. return outlet;
  228. }
  229. /**
  230. * Returns an object of key/value pairs of the dynamic params from the current
  231. * URL that were matched by the route path.
  232. *
  233. * @see https://reactrouter.com/v6/hooks/use-params
  234. */
  235. function useParams() {
  236. let {
  237. matches
  238. } = React.useContext(RouteContext);
  239. let routeMatch = matches[matches.length - 1];
  240. return routeMatch ? routeMatch.params : {};
  241. }
  242. /**
  243. * Resolves the pathname of the given `to` value against the current location.
  244. *
  245. * @see https://reactrouter.com/v6/hooks/use-resolved-path
  246. */
  247. function useResolvedPath(to, {
  248. relative
  249. } = {}) {
  250. let {
  251. future
  252. } = React.useContext(NavigationContext);
  253. let {
  254. matches
  255. } = React.useContext(RouteContext);
  256. let {
  257. pathname: locationPathname
  258. } = useLocation();
  259. let routePathnamesJson = JSON.stringify(UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath));
  260. return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
  261. }
  262. /**
  263. * Returns the element of the route that matched the current location, prepared
  264. * with the correct context to render the remainder of the route tree. Route
  265. * elements in the tree must render an `<Outlet>` to render their child route's
  266. * element.
  267. *
  268. * @see https://reactrouter.com/v6/hooks/use-routes
  269. */
  270. function useRoutes(routes, locationArg) {
  271. return useRoutesImpl(routes, locationArg);
  272. }
  273. // Internal implementation with accept optional param for RouterProvider usage
  274. function useRoutesImpl(routes, locationArg, dataRouterState, future) {
  275. !useInRouterContext() ? UNSAFE_invariant(false,
  276. // TODO: This error is probably because they somehow have 2 versions of the
  277. // router loaded. We can help them understand how to avoid that.
  278. `useRoutes() may be used only in the context of a <Router> component.`) : void 0;
  279. let {
  280. navigator
  281. } = React.useContext(NavigationContext);
  282. let {
  283. matches: parentMatches
  284. } = React.useContext(RouteContext);
  285. let routeMatch = parentMatches[parentMatches.length - 1];
  286. let parentParams = routeMatch ? routeMatch.params : {};
  287. let parentPathname = routeMatch ? routeMatch.pathname : "/";
  288. let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
  289. let parentRoute = routeMatch && routeMatch.route;
  290. {
  291. // You won't get a warning about 2 different <Routes> under a <Route>
  292. // without a trailing *, but this is a best-effort warning anyway since we
  293. // cannot even give the warning unless they land at the parent route.
  294. //
  295. // Example:
  296. //
  297. // <Routes>
  298. // {/* This route path MUST end with /* because otherwise
  299. // it will never match /blog/post/123 */}
  300. // <Route path="blog" element={<Blog />} />
  301. // <Route path="blog/feed" element={<BlogFeed />} />
  302. // </Routes>
  303. //
  304. // function Blog() {
  305. // return (
  306. // <Routes>
  307. // <Route path="post/:id" element={<Post />} />
  308. // </Routes>
  309. // );
  310. // }
  311. let parentPath = parentRoute && parentRoute.path || "";
  312. warningOnce(parentPathname, !parentRoute || parentPath.endsWith("*"), `You rendered descendant <Routes> (or called \`useRoutes()\`) at ` + `"${parentPathname}" (under <Route path="${parentPath}">) but the ` + `parent route path has no trailing "*". This means if you navigate ` + `deeper, the parent won't match anymore and therefore the child ` + `routes will never render.\n\n` + `Please change the parent <Route path="${parentPath}"> to <Route ` + `path="${parentPath === "/" ? "*" : `${parentPath}/*`}">.`);
  313. }
  314. let locationFromContext = useLocation();
  315. let location;
  316. if (locationArg) {
  317. let parsedLocationArg = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
  318. !(parentPathnameBase === "/" || parsedLocationArg.pathname?.startsWith(parentPathnameBase)) ? UNSAFE_invariant(false, `When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, ` + `the location pathname must begin with the portion of the URL pathname that was ` + `matched by all parent routes. The current pathname base is "${parentPathnameBase}" ` + `but pathname "${parsedLocationArg.pathname}" was given in the \`location\` prop.`) : void 0;
  319. location = parsedLocationArg;
  320. } else {
  321. location = locationFromContext;
  322. }
  323. let pathname = location.pathname || "/";
  324. let remainingPathname = pathname;
  325. if (parentPathnameBase !== "/") {
  326. // Determine the remaining pathname by removing the # of URL segments the
  327. // parentPathnameBase has, instead of removing based on character count.
  328. // This is because we can't guarantee that incoming/outgoing encodings/
  329. // decodings will match exactly.
  330. // We decode paths before matching on a per-segment basis with
  331. // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they
  332. // match what `window.location.pathname` would reflect. Those don't 100%
  333. // align when it comes to encoded URI characters such as % and &.
  334. //
  335. // So we may end up with:
  336. // pathname: "/descendant/a%25b/match"
  337. // parentPathnameBase: "/descendant/a%b"
  338. //
  339. // And the direct substring removal approach won't work :/
  340. let parentSegments = parentPathnameBase.replace(/^\//, "").split("/");
  341. let segments = pathname.replace(/^\//, "").split("/");
  342. remainingPathname = "/" + segments.slice(parentSegments.length).join("/");
  343. }
  344. let matches = matchRoutes(routes, {
  345. pathname: remainingPathname
  346. });
  347. {
  348. UNSAFE_warning(parentRoute || matches != null, `No routes matched location "${location.pathname}${location.search}${location.hash}" `) ;
  349. UNSAFE_warning(matches == null || matches[matches.length - 1].route.element !== undefined || matches[matches.length - 1].route.Component !== undefined || matches[matches.length - 1].route.lazy !== undefined, `Matched leaf route at location "${location.pathname}${location.search}${location.hash}" ` + `does not have an element or Component. This means it will render an <Outlet /> with a ` + `null value by default resulting in an "empty" page.`) ;
  350. }
  351. let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
  352. params: Object.assign({}, parentParams, match.params),
  353. pathname: joinPaths([parentPathnameBase,
  354. // Re-encode pathnames that were decoded inside matchRoutes
  355. navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),
  356. pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : joinPaths([parentPathnameBase,
  357. // Re-encode pathnames that were decoded inside matchRoutes
  358. navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])
  359. })), parentMatches, dataRouterState, future);
  360. // When a user passes in a `locationArg`, the associated routes need to
  361. // be wrapped in a new `LocationContext.Provider` in order for `useLocation`
  362. // to use the scoped location instead of the global location.
  363. if (locationArg && renderedMatches) {
  364. return /*#__PURE__*/React.createElement(LocationContext.Provider, {
  365. value: {
  366. location: {
  367. pathname: "/",
  368. search: "",
  369. hash: "",
  370. state: null,
  371. key: "default",
  372. ...location
  373. },
  374. navigationType: Action.Pop
  375. }
  376. }, renderedMatches);
  377. }
  378. return renderedMatches;
  379. }
  380. function DefaultErrorComponent() {
  381. let error = useRouteError();
  382. let message = isRouteErrorResponse(error) ? `${error.status} ${error.statusText}` : error instanceof Error ? error.message : JSON.stringify(error);
  383. let stack = error instanceof Error ? error.stack : null;
  384. let lightgrey = "rgba(200,200,200, 0.5)";
  385. let preStyles = {
  386. padding: "0.5rem",
  387. backgroundColor: lightgrey
  388. };
  389. let codeStyles = {
  390. padding: "2px 4px",
  391. backgroundColor: lightgrey
  392. };
  393. let devInfo = null;
  394. {
  395. console.error("Error handled by React Router default ErrorBoundary:", error);
  396. devInfo = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("p", null, "\uD83D\uDCBF Hey developer \uD83D\uDC4B"), /*#__PURE__*/React.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", /*#__PURE__*/React.createElement("code", {
  397. style: codeStyles
  398. }, "ErrorBoundary"), " or", " ", /*#__PURE__*/React.createElement("code", {
  399. style: codeStyles
  400. }, "errorElement"), " prop on your route."));
  401. }
  402. return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("h2", null, "Unexpected Application Error!"), /*#__PURE__*/React.createElement("h3", {
  403. style: {
  404. fontStyle: "italic"
  405. }
  406. }, message), stack ? /*#__PURE__*/React.createElement("pre", {
  407. style: preStyles
  408. }, stack) : null, devInfo);
  409. }
  410. const defaultErrorElement = /*#__PURE__*/React.createElement(DefaultErrorComponent, null);
  411. class RenderErrorBoundary extends React.Component {
  412. constructor(props) {
  413. super(props);
  414. this.state = {
  415. location: props.location,
  416. revalidation: props.revalidation,
  417. error: props.error
  418. };
  419. }
  420. static getDerivedStateFromError(error) {
  421. return {
  422. error: error
  423. };
  424. }
  425. static getDerivedStateFromProps(props, state) {
  426. // When we get into an error state, the user will likely click "back" to the
  427. // previous page that didn't have an error. Because this wraps the entire
  428. // application, that will have no effect--the error page continues to display.
  429. // This gives us a mechanism to recover from the error when the location changes.
  430. //
  431. // Whether we're in an error state or not, we update the location in state
  432. // so that when we are in an error state, it gets reset when a new location
  433. // comes in and the user recovers from the error.
  434. if (state.location !== props.location || state.revalidation !== "idle" && props.revalidation === "idle") {
  435. return {
  436. error: props.error,
  437. location: props.location,
  438. revalidation: props.revalidation
  439. };
  440. }
  441. // If we're not changing locations, preserve the location but still surface
  442. // any new errors that may come through. We retain the existing error, we do
  443. // this because the error provided from the app state may be cleared without
  444. // the location changing.
  445. return {
  446. error: props.error !== undefined ? props.error : state.error,
  447. location: state.location,
  448. revalidation: props.revalidation || state.revalidation
  449. };
  450. }
  451. componentDidCatch(error, errorInfo) {
  452. console.error("React Router caught the following error during render", error, errorInfo);
  453. }
  454. render() {
  455. return this.state.error !== undefined ? /*#__PURE__*/React.createElement(RouteContext.Provider, {
  456. value: this.props.routeContext
  457. }, /*#__PURE__*/React.createElement(RouteErrorContext.Provider, {
  458. value: this.state.error,
  459. children: this.props.component
  460. })) : this.props.children;
  461. }
  462. }
  463. function RenderedRoute({
  464. routeContext,
  465. match,
  466. children
  467. }) {
  468. let dataRouterContext = React.useContext(DataRouterContext);
  469. // Track how deep we got in our render pass to emulate SSR componentDidCatch
  470. // in a DataStaticRouter
  471. if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {
  472. dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
  473. }
  474. return /*#__PURE__*/React.createElement(RouteContext.Provider, {
  475. value: routeContext
  476. }, children);
  477. }
  478. function _renderMatches(matches, parentMatches = [], dataRouterState = null, future = null) {
  479. if (matches == null) {
  480. if (!dataRouterState) {
  481. return null;
  482. }
  483. if (dataRouterState.errors) {
  484. // Don't bail if we have data router errors so we can render them in the
  485. // boundary. Use the pre-matched (or shimmed) matches
  486. matches = dataRouterState.matches;
  487. } else if (future?.v7_partialHydration && parentMatches.length === 0 && !dataRouterState.initialized && dataRouterState.matches.length > 0) {
  488. // Don't bail if we're initializing with partial hydration and we have
  489. // router matches. That means we're actively running `patchRoutesOnNavigation`
  490. // so we should render down the partial matches to the appropriate
  491. // `HydrateFallback`. We only do this if `parentMatches` is empty so it
  492. // only impacts the root matches for `RouterProvider` and no descendant
  493. // `<Routes>`
  494. matches = dataRouterState.matches;
  495. } else {
  496. return null;
  497. }
  498. }
  499. let renderedMatches = matches;
  500. // If we have data errors, trim matches to the highest error boundary
  501. let errors = dataRouterState?.errors;
  502. if (errors != null) {
  503. let errorIndex = renderedMatches.findIndex(m => m.route.id && errors?.[m.route.id] !== undefined);
  504. !(errorIndex >= 0) ? UNSAFE_invariant(false, `Could not find a matching route for errors on route IDs: ${Object.keys(errors).join(",")}`) : void 0;
  505. renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
  506. }
  507. // If we're in a partial hydration mode, detect if we need to render down to
  508. // a given HydrateFallback while we load the rest of the hydration data
  509. let renderFallback = false;
  510. let fallbackIndex = -1;
  511. if (dataRouterState && future && future.v7_partialHydration) {
  512. for (let i = 0; i < renderedMatches.length; i++) {
  513. let match = renderedMatches[i];
  514. // Track the deepest fallback up until the first route without data
  515. if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {
  516. fallbackIndex = i;
  517. }
  518. if (match.route.id) {
  519. let {
  520. loaderData,
  521. errors: _errors
  522. } = dataRouterState;
  523. let needsToRunLoader = match.route.loader && loaderData[match.route.id] === undefined && (!_errors || _errors[match.route.id] === undefined);
  524. if (match.route.lazy || needsToRunLoader) {
  525. // We found the first route that's not ready to render (waiting on
  526. // lazy, or has a loader that hasn't run yet). Flag that we need to
  527. // render a fallback and render up until the appropriate fallback
  528. renderFallback = true;
  529. if (fallbackIndex >= 0) {
  530. renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);
  531. } else {
  532. renderedMatches = [renderedMatches[0]];
  533. }
  534. break;
  535. }
  536. }
  537. }
  538. }
  539. return renderedMatches.reduceRight((outlet, match, index) => {
  540. // Only data routers handle errors/fallbacks
  541. let error;
  542. let shouldRenderHydrateFallback = false;
  543. let errorElement = null;
  544. let hydrateFallbackElement = null;
  545. if (dataRouterState) {
  546. error = errors && match.route.id ? errors[match.route.id] : undefined;
  547. errorElement = match.route.errorElement || defaultErrorElement;
  548. if (renderFallback) {
  549. if (fallbackIndex < 0 && index === 0) {
  550. warningOnce("route-fallback", false, "No `HydrateFallback` element provided to render during initial hydration");
  551. shouldRenderHydrateFallback = true;
  552. hydrateFallbackElement = null;
  553. } else if (fallbackIndex === index) {
  554. shouldRenderHydrateFallback = true;
  555. hydrateFallbackElement = match.route.hydrateFallbackElement || null;
  556. }
  557. }
  558. }
  559. let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
  560. let getChildren = () => {
  561. let children;
  562. if (error) {
  563. children = errorElement;
  564. } else if (shouldRenderHydrateFallback) {
  565. children = hydrateFallbackElement;
  566. } else if (match.route.Component) {
  567. // Note: This is a de-optimized path since React won't re-use the
  568. // ReactElement since it's identity changes with each new
  569. // React.createElement call. We keep this so folks can use
  570. // `<Route Component={...}>` in `<Routes>` but generally `Component`
  571. // usage is only advised in `RouterProvider` when we can convert it to
  572. // `element` ahead of time.
  573. children = /*#__PURE__*/React.createElement(match.route.Component, null);
  574. } else if (match.route.element) {
  575. children = match.route.element;
  576. } else {
  577. children = outlet;
  578. }
  579. return /*#__PURE__*/React.createElement(RenderedRoute, {
  580. match: match,
  581. routeContext: {
  582. outlet,
  583. matches,
  584. isDataRoute: dataRouterState != null
  585. },
  586. children: children
  587. });
  588. };
  589. // Only wrap in an error boundary within data router usages when we have an
  590. // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to
  591. // an ancestor ErrorBoundary/errorElement
  592. return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /*#__PURE__*/React.createElement(RenderErrorBoundary, {
  593. location: dataRouterState.location,
  594. revalidation: dataRouterState.revalidation,
  595. component: errorElement,
  596. error: error,
  597. children: getChildren(),
  598. routeContext: {
  599. outlet: null,
  600. matches,
  601. isDataRoute: true
  602. }
  603. }) : getChildren();
  604. }, null);
  605. }
  606. var DataRouterHook;
  607. (function (DataRouterHook) {
  608. DataRouterHook["UseBlocker"] = "useBlocker";
  609. DataRouterHook["UseRevalidator"] = "useRevalidator";
  610. DataRouterHook["UseNavigateStable"] = "useNavigate";
  611. })(DataRouterHook || (DataRouterHook = {}));
  612. var DataRouterStateHook;
  613. (function (DataRouterStateHook) {
  614. DataRouterStateHook["UseBlocker"] = "useBlocker";
  615. DataRouterStateHook["UseLoaderData"] = "useLoaderData";
  616. DataRouterStateHook["UseActionData"] = "useActionData";
  617. DataRouterStateHook["UseRouteError"] = "useRouteError";
  618. DataRouterStateHook["UseNavigation"] = "useNavigation";
  619. DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
  620. DataRouterStateHook["UseMatches"] = "useMatches";
  621. DataRouterStateHook["UseRevalidator"] = "useRevalidator";
  622. DataRouterStateHook["UseNavigateStable"] = "useNavigate";
  623. DataRouterStateHook["UseRouteId"] = "useRouteId";
  624. })(DataRouterStateHook || (DataRouterStateHook = {}));
  625. function getDataRouterConsoleError(hookName) {
  626. return `${hookName} must be used within a data router. See https://reactrouter.com/v6/routers/picking-a-router.`;
  627. }
  628. function useDataRouterContext(hookName) {
  629. let ctx = React.useContext(DataRouterContext);
  630. !ctx ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
  631. return ctx;
  632. }
  633. function useDataRouterState(hookName) {
  634. let state = React.useContext(DataRouterStateContext);
  635. !state ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
  636. return state;
  637. }
  638. function useRouteContext(hookName) {
  639. let route = React.useContext(RouteContext);
  640. !route ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : void 0;
  641. return route;
  642. }
  643. // Internal version with hookName-aware debugging
  644. function useCurrentRouteId(hookName) {
  645. let route = useRouteContext(hookName);
  646. let thisRoute = route.matches[route.matches.length - 1];
  647. !thisRoute.route.id ? UNSAFE_invariant(false, `${hookName} can only be used on routes that contain a unique "id"`) : void 0;
  648. return thisRoute.route.id;
  649. }
  650. /**
  651. * Returns the ID for the nearest contextual route
  652. */
  653. function useRouteId() {
  654. return useCurrentRouteId(DataRouterStateHook.UseRouteId);
  655. }
  656. /**
  657. * Returns the current navigation, defaulting to an "idle" navigation when
  658. * no navigation is in progress
  659. */
  660. function useNavigation() {
  661. let state = useDataRouterState(DataRouterStateHook.UseNavigation);
  662. return state.navigation;
  663. }
  664. /**
  665. * Returns a revalidate function for manually triggering revalidation, as well
  666. * as the current state of any manual revalidations
  667. */
  668. function useRevalidator() {
  669. let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
  670. let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
  671. return React.useMemo(() => ({
  672. revalidate: dataRouterContext.router.revalidate,
  673. state: state.revalidation
  674. }), [dataRouterContext.router.revalidate, state.revalidation]);
  675. }
  676. /**
  677. * Returns the active route matches, useful for accessing loaderData for
  678. * parent/child routes or the route "handle" property
  679. */
  680. function useMatches() {
  681. let {
  682. matches,
  683. loaderData
  684. } = useDataRouterState(DataRouterStateHook.UseMatches);
  685. return React.useMemo(() => matches.map(m => UNSAFE_convertRouteMatchToUiMatch(m, loaderData)), [matches, loaderData]);
  686. }
  687. /**
  688. * Returns the loader data for the nearest ancestor Route loader
  689. */
  690. function useLoaderData() {
  691. let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
  692. let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
  693. if (state.errors && state.errors[routeId] != null) {
  694. console.error(`You cannot \`useLoaderData\` in an errorElement (routeId: ${routeId})`);
  695. return undefined;
  696. }
  697. return state.loaderData[routeId];
  698. }
  699. /**
  700. * Returns the loaderData for the given routeId
  701. */
  702. function useRouteLoaderData(routeId) {
  703. let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
  704. return state.loaderData[routeId];
  705. }
  706. /**
  707. * Returns the action data for the nearest ancestor Route action
  708. */
  709. function useActionData() {
  710. let state = useDataRouterState(DataRouterStateHook.UseActionData);
  711. let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
  712. return state.actionData ? state.actionData[routeId] : undefined;
  713. }
  714. /**
  715. * Returns the nearest ancestor Route error, which could be a loader/action
  716. * error or a render error. This is intended to be called from your
  717. * ErrorBoundary/errorElement to display a proper error message.
  718. */
  719. function useRouteError() {
  720. let error = React.useContext(RouteErrorContext);
  721. let state = useDataRouterState(DataRouterStateHook.UseRouteError);
  722. let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);
  723. // If this was a render error, we put it in a RouteError context inside
  724. // of RenderErrorBoundary
  725. if (error !== undefined) {
  726. return error;
  727. }
  728. // Otherwise look for errors from our data router state
  729. return state.errors?.[routeId];
  730. }
  731. /**
  732. * Returns the happy-path data from the nearest ancestor `<Await />` value
  733. */
  734. function useAsyncValue() {
  735. let value = React.useContext(AwaitContext);
  736. return value?._data;
  737. }
  738. /**
  739. * Returns the error from the nearest ancestor `<Await />` value
  740. */
  741. function useAsyncError() {
  742. let value = React.useContext(AwaitContext);
  743. return value?._error;
  744. }
  745. let blockerId = 0;
  746. /**
  747. * Allow the application to block navigations within the SPA and present the
  748. * user a confirmation dialog to confirm the navigation. Mostly used to avoid
  749. * using half-filled form data. This does not handle hard-reloads or
  750. * cross-origin navigations.
  751. */
  752. function useBlocker(shouldBlock) {
  753. let {
  754. router,
  755. basename
  756. } = useDataRouterContext(DataRouterHook.UseBlocker);
  757. let state = useDataRouterState(DataRouterStateHook.UseBlocker);
  758. let [blockerKey, setBlockerKey] = React.useState("");
  759. let blockerFunction = React.useCallback(arg => {
  760. if (typeof shouldBlock !== "function") {
  761. return !!shouldBlock;
  762. }
  763. if (basename === "/") {
  764. return shouldBlock(arg);
  765. }
  766. // If they provided us a function and we've got an active basename, strip
  767. // it from the locations we expose to the user to match the behavior of
  768. // useLocation
  769. let {
  770. currentLocation,
  771. nextLocation,
  772. historyAction
  773. } = arg;
  774. return shouldBlock({
  775. currentLocation: {
  776. ...currentLocation,
  777. pathname: stripBasename(currentLocation.pathname, basename) || currentLocation.pathname
  778. },
  779. nextLocation: {
  780. ...nextLocation,
  781. pathname: stripBasename(nextLocation.pathname, basename) || nextLocation.pathname
  782. },
  783. historyAction
  784. });
  785. }, [basename, shouldBlock]);
  786. // This effect is in charge of blocker key assignment and deletion (which is
  787. // tightly coupled to the key)
  788. React.useEffect(() => {
  789. let key = String(++blockerId);
  790. setBlockerKey(key);
  791. return () => router.deleteBlocker(key);
  792. }, [router]);
  793. // This effect handles assigning the blockerFunction. This is to handle
  794. // unstable blocker function identities, and happens only after the prior
  795. // effect so we don't get an orphaned blockerFunction in the router with a
  796. // key of "". Until then we just have the IDLE_BLOCKER.
  797. React.useEffect(() => {
  798. if (blockerKey !== "") {
  799. router.getBlocker(blockerKey, blockerFunction);
  800. }
  801. }, [router, blockerKey, blockerFunction]);
  802. // Prefer the blocker from `state` not `router.state` since DataRouterContext
  803. // is memoized so this ensures we update on blocker state updates
  804. return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER;
  805. }
  806. /**
  807. * Stable version of useNavigate that is used when we are in the context of
  808. * a RouterProvider.
  809. */
  810. function useNavigateStable() {
  811. let {
  812. router
  813. } = useDataRouterContext(DataRouterHook.UseNavigateStable);
  814. let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);
  815. let activeRef = React.useRef(false);
  816. useIsomorphicLayoutEffect(() => {
  817. activeRef.current = true;
  818. });
  819. let navigate = React.useCallback((to, options = {}) => {
  820. UNSAFE_warning(activeRef.current, navigateEffectWarning) ;
  821. // Short circuit here since if this happens on first render the navigate
  822. // is useless because we haven't wired up our router subscriber yet
  823. if (!activeRef.current) return;
  824. if (typeof to === "number") {
  825. router.navigate(to);
  826. } else {
  827. router.navigate(to, {
  828. fromRouteId: id,
  829. ...options
  830. });
  831. }
  832. }, [router, id]);
  833. return navigate;
  834. }
  835. const alreadyWarned$1 = {};
  836. function warningOnce(key, cond, message) {
  837. if (!cond && !alreadyWarned$1[key]) {
  838. alreadyWarned$1[key] = true;
  839. UNSAFE_warning(false, message) ;
  840. }
  841. }
  842. const alreadyWarned = {};
  843. function warnOnce(key, message) {
  844. if (!alreadyWarned[message]) {
  845. alreadyWarned[message] = true;
  846. console.warn(message);
  847. }
  848. }
  849. const logDeprecation = (flag, msg, link) => warnOnce(flag, `⚠️ React Router Future Flag Warning: ${msg}. ` + `You can use the \`${flag}\` future flag to opt-in early. ` + `For more information, see ${link}.`);
  850. function logV6DeprecationWarnings(renderFuture, routerFuture) {
  851. if (renderFuture?.v7_startTransition === undefined) {
  852. logDeprecation("v7_startTransition", "React Router will begin wrapping state updates in `React.startTransition` in v7", "https://reactrouter.com/v6/upgrading/future#v7_starttransition");
  853. }
  854. if (renderFuture?.v7_relativeSplatPath === undefined && (!routerFuture || routerFuture.v7_relativeSplatPath === undefined)) {
  855. logDeprecation("v7_relativeSplatPath", "Relative route resolution within Splat routes is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_relativesplatpath");
  856. }
  857. if (routerFuture) {
  858. if (routerFuture.v7_fetcherPersist === undefined) {
  859. logDeprecation("v7_fetcherPersist", "The persistence behavior of fetchers is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_fetcherpersist");
  860. }
  861. if (routerFuture.v7_normalizeFormMethod === undefined) {
  862. logDeprecation("v7_normalizeFormMethod", "Casing of `formMethod` fields is being normalized to uppercase in v7", "https://reactrouter.com/v6/upgrading/future#v7_normalizeformmethod");
  863. }
  864. if (routerFuture.v7_partialHydration === undefined) {
  865. logDeprecation("v7_partialHydration", "`RouterProvider` hydration behavior is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_partialhydration");
  866. }
  867. if (routerFuture.v7_skipActionErrorRevalidation === undefined) {
  868. logDeprecation("v7_skipActionErrorRevalidation", "The revalidation behavior after 4xx/5xx `action` responses is changing in v7", "https://reactrouter.com/v6/upgrading/future#v7_skipactionerrorrevalidation");
  869. }
  870. }
  871. }
  872. /**
  873. Webpack + React 17 fails to compile on any of the following because webpack
  874. complains that `startTransition` doesn't exist in `React`:
  875. * import { startTransition } from "react"
  876. * import * as React from from "react";
  877. "startTransition" in React ? React.startTransition(() => setState()) : setState()
  878. * import * as React from from "react";
  879. "startTransition" in React ? React["startTransition"](() => setState()) : setState()
  880. Moving it to a constant such as the following solves the Webpack/React 17 issue:
  881. * import * as React from from "react";
  882. const START_TRANSITION = "startTransition";
  883. START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()
  884. However, that introduces webpack/terser minification issues in production builds
  885. in React 18 where minification/obfuscation ends up removing the call of
  886. React.startTransition entirely from the first half of the ternary. Grabbing
  887. this exported reference once up front resolves that issue.
  888. See https://github.com/remix-run/react-router/issues/10579
  889. */
  890. const START_TRANSITION = "startTransition";
  891. const startTransitionImpl = React[START_TRANSITION];
  892. /**
  893. * Given a Remix Router instance, render the appropriate UI
  894. */
  895. function RouterProvider({
  896. fallbackElement,
  897. router,
  898. future
  899. }) {
  900. let [state, setStateImpl] = React.useState(router.state);
  901. let {
  902. v7_startTransition
  903. } = future || {};
  904. let setState = React.useCallback(newState => {
  905. if (v7_startTransition && startTransitionImpl) {
  906. startTransitionImpl(() => setStateImpl(newState));
  907. } else {
  908. setStateImpl(newState);
  909. }
  910. }, [setStateImpl, v7_startTransition]);
  911. // Need to use a layout effect here so we are subscribed early enough to
  912. // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
  913. React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
  914. React.useEffect(() => {
  915. UNSAFE_warning(fallbackElement == null || !router.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using " + "`v7_partialHydration`, use a `HydrateFallback` component instead") ;
  916. // Only log this once on initial mount
  917. // eslint-disable-next-line react-hooks/exhaustive-deps
  918. }, []);
  919. let navigator = React.useMemo(() => {
  920. return {
  921. createHref: router.createHref,
  922. encodeLocation: router.encodeLocation,
  923. go: n => router.navigate(n),
  924. push: (to, state, opts) => router.navigate(to, {
  925. state,
  926. preventScrollReset: opts?.preventScrollReset
  927. }),
  928. replace: (to, state, opts) => router.navigate(to, {
  929. replace: true,
  930. state,
  931. preventScrollReset: opts?.preventScrollReset
  932. })
  933. };
  934. }, [router]);
  935. let basename = router.basename || "/";
  936. let dataRouterContext = React.useMemo(() => ({
  937. router,
  938. navigator,
  939. static: false,
  940. basename
  941. }), [router, navigator, basename]);
  942. React.useEffect(() => logV6DeprecationWarnings(future, router.future), [router, future]);
  943. // The fragment and {null} here are important! We need them to keep React 18's
  944. // useId happy when we are server-rendering since we may have a <script> here
  945. // containing the hydrated server-side staticContext (from StaticRouterProvider).
  946. // useId relies on the component tree structure to generate deterministic id's
  947. // so we need to ensure it remains the same on the client even though
  948. // we don't need the <script> tag
  949. return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(DataRouterContext.Provider, {
  950. value: dataRouterContext
  951. }, /*#__PURE__*/React.createElement(DataRouterStateContext.Provider, {
  952. value: state
  953. }, /*#__PURE__*/React.createElement(Router, {
  954. basename: basename,
  955. location: state.location,
  956. navigationType: state.historyAction,
  957. navigator: navigator,
  958. future: {
  959. v7_relativeSplatPath: router.future.v7_relativeSplatPath
  960. }
  961. }, state.initialized || router.future.v7_partialHydration ? /*#__PURE__*/React.createElement(DataRoutes, {
  962. routes: router.routes,
  963. future: router.future,
  964. state: state
  965. }) : fallbackElement))), null);
  966. }
  967. function DataRoutes({
  968. routes,
  969. future,
  970. state
  971. }) {
  972. return useRoutesImpl(routes, undefined, state, future);
  973. }
  974. /**
  975. * A `<Router>` that stores all entries in memory.
  976. *
  977. * @see https://reactrouter.com/v6/router-components/memory-router
  978. */
  979. function MemoryRouter({
  980. basename,
  981. children,
  982. initialEntries,
  983. initialIndex,
  984. future
  985. }) {
  986. let historyRef = React.useRef();
  987. if (historyRef.current == null) {
  988. historyRef.current = createMemoryHistory({
  989. initialEntries,
  990. initialIndex,
  991. v5Compat: true
  992. });
  993. }
  994. let history = historyRef.current;
  995. let [state, setStateImpl] = React.useState({
  996. action: history.action,
  997. location: history.location
  998. });
  999. let {
  1000. v7_startTransition
  1001. } = future || {};
  1002. let setState = React.useCallback(newState => {
  1003. v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  1004. }, [setStateImpl, v7_startTransition]);
  1005. React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  1006. React.useEffect(() => logV6DeprecationWarnings(future), [future]);
  1007. return /*#__PURE__*/React.createElement(Router, {
  1008. basename: basename,
  1009. children: children,
  1010. location: state.location,
  1011. navigationType: state.action,
  1012. navigator: history,
  1013. future: future
  1014. });
  1015. }
  1016. /**
  1017. * Changes the current location.
  1018. *
  1019. * Note: This API is mostly useful in React.Component subclasses that are not
  1020. * able to use hooks. In functional components, we recommend you use the
  1021. * `useNavigate` hook instead.
  1022. *
  1023. * @see https://reactrouter.com/v6/components/navigate
  1024. */
  1025. function Navigate({
  1026. to,
  1027. replace,
  1028. state,
  1029. relative
  1030. }) {
  1031. !useInRouterContext() ? UNSAFE_invariant(false,
  1032. // TODO: This error is probably because they somehow have 2 versions of
  1033. // the router loaded. We can help them understand how to avoid that.
  1034. `<Navigate> may be used only in the context of a <Router> component.`) : void 0;
  1035. let {
  1036. future,
  1037. static: isStatic
  1038. } = React.useContext(NavigationContext);
  1039. UNSAFE_warning(!isStatic, `<Navigate> must not be used on the initial render in a <StaticRouter>. ` + `This is a no-op, but you should modify your code so the <Navigate> is ` + `only ever rendered in response to some user interaction or state change.`) ;
  1040. let {
  1041. matches
  1042. } = React.useContext(RouteContext);
  1043. let {
  1044. pathname: locationPathname
  1045. } = useLocation();
  1046. let navigate = useNavigate();
  1047. // Resolve the path outside of the effect so that when effects run twice in
  1048. // StrictMode they navigate to the same place
  1049. let path = resolveTo(to, UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath), locationPathname, relative === "path");
  1050. let jsonPath = JSON.stringify(path);
  1051. React.useEffect(() => navigate(JSON.parse(jsonPath), {
  1052. replace,
  1053. state,
  1054. relative
  1055. }), [navigate, jsonPath, relative, replace, state]);
  1056. return null;
  1057. }
  1058. /**
  1059. * Renders the child route's element, if there is one.
  1060. *
  1061. * @see https://reactrouter.com/v6/components/outlet
  1062. */
  1063. function Outlet(props) {
  1064. return useOutlet(props.context);
  1065. }
  1066. /**
  1067. * Declares an element that should be rendered at a certain URL path.
  1068. *
  1069. * @see https://reactrouter.com/v6/components/route
  1070. */
  1071. function Route(_props) {
  1072. UNSAFE_invariant(false, `A <Route> is only ever to be used as the child of <Routes> element, ` + `never rendered directly. Please wrap your <Route> in a <Routes>.`) ;
  1073. }
  1074. /**
  1075. * Provides location context for the rest of the app.
  1076. *
  1077. * Note: You usually won't render a `<Router>` directly. Instead, you'll render a
  1078. * router that is more specific to your environment such as a `<BrowserRouter>`
  1079. * in web browsers or a `<StaticRouter>` for server rendering.
  1080. *
  1081. * @see https://reactrouter.com/v6/router-components/router
  1082. */
  1083. function Router({
  1084. basename: basenameProp = "/",
  1085. children = null,
  1086. location: locationProp,
  1087. navigationType = Action.Pop,
  1088. navigator,
  1089. static: staticProp = false,
  1090. future
  1091. }) {
  1092. !!useInRouterContext() ? UNSAFE_invariant(false, `You cannot render a <Router> inside another <Router>.` + ` You should never have more than one in your app.`) : void 0;
  1093. // Preserve trailing slashes on basename, so we can let the user control
  1094. // the enforcement of trailing slashes throughout the app
  1095. let basename = basenameProp.replace(/^\/*/, "/");
  1096. let navigationContext = React.useMemo(() => ({
  1097. basename,
  1098. navigator,
  1099. static: staticProp,
  1100. future: {
  1101. v7_relativeSplatPath: false,
  1102. ...future
  1103. }
  1104. }), [basename, future, navigator, staticProp]);
  1105. if (typeof locationProp === "string") {
  1106. locationProp = parsePath(locationProp);
  1107. }
  1108. let {
  1109. pathname = "/",
  1110. search = "",
  1111. hash = "",
  1112. state = null,
  1113. key = "default"
  1114. } = locationProp;
  1115. let locationContext = React.useMemo(() => {
  1116. let trailingPathname = stripBasename(pathname, basename);
  1117. if (trailingPathname == null) {
  1118. return null;
  1119. }
  1120. return {
  1121. location: {
  1122. pathname: trailingPathname,
  1123. search,
  1124. hash,
  1125. state,
  1126. key
  1127. },
  1128. navigationType
  1129. };
  1130. }, [basename, pathname, search, hash, state, key, navigationType]);
  1131. UNSAFE_warning(locationContext != null, `<Router basename="${basename}"> is not able to match the URL ` + `"${pathname}${search}${hash}" because it does not start with the ` + `basename, so the <Router> won't render anything.`) ;
  1132. if (locationContext == null) {
  1133. return null;
  1134. }
  1135. return /*#__PURE__*/React.createElement(NavigationContext.Provider, {
  1136. value: navigationContext
  1137. }, /*#__PURE__*/React.createElement(LocationContext.Provider, {
  1138. children: children,
  1139. value: locationContext
  1140. }));
  1141. }
  1142. /**
  1143. * A container for a nested tree of `<Route>` elements that renders the branch
  1144. * that best matches the current location.
  1145. *
  1146. * @see https://reactrouter.com/v6/components/routes
  1147. */
  1148. function Routes({
  1149. children,
  1150. location
  1151. }) {
  1152. return useRoutes(createRoutesFromChildren(children), location);
  1153. }
  1154. /**
  1155. * Component to use for rendering lazily loaded data from returning defer()
  1156. * in a loader function
  1157. */
  1158. function Await({
  1159. children,
  1160. errorElement,
  1161. resolve
  1162. }) {
  1163. return /*#__PURE__*/React.createElement(AwaitErrorBoundary, {
  1164. resolve: resolve,
  1165. errorElement: errorElement
  1166. }, /*#__PURE__*/React.createElement(ResolveAwait, null, children));
  1167. }
  1168. var AwaitRenderStatus;
  1169. (function (AwaitRenderStatus) {
  1170. AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
  1171. AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
  1172. AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
  1173. })(AwaitRenderStatus || (AwaitRenderStatus = {}));
  1174. const neverSettledPromise = new Promise(() => {});
  1175. class AwaitErrorBoundary extends React.Component {
  1176. constructor(props) {
  1177. super(props);
  1178. this.state = {
  1179. error: null
  1180. };
  1181. }
  1182. static getDerivedStateFromError(error) {
  1183. return {
  1184. error
  1185. };
  1186. }
  1187. componentDidCatch(error, errorInfo) {
  1188. console.error("<Await> caught the following error during render", error, errorInfo);
  1189. }
  1190. render() {
  1191. let {
  1192. children,
  1193. errorElement,
  1194. resolve
  1195. } = this.props;
  1196. let promise = null;
  1197. let status = AwaitRenderStatus.pending;
  1198. if (!(resolve instanceof Promise)) {
  1199. // Didn't get a promise - provide as a resolved promise
  1200. status = AwaitRenderStatus.success;
  1201. promise = Promise.resolve();
  1202. Object.defineProperty(promise, "_tracked", {
  1203. get: () => true
  1204. });
  1205. Object.defineProperty(promise, "_data", {
  1206. get: () => resolve
  1207. });
  1208. } else if (this.state.error) {
  1209. // Caught a render error, provide it as a rejected promise
  1210. status = AwaitRenderStatus.error;
  1211. let renderError = this.state.error;
  1212. promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
  1213. Object.defineProperty(promise, "_tracked", {
  1214. get: () => true
  1215. });
  1216. Object.defineProperty(promise, "_error", {
  1217. get: () => renderError
  1218. });
  1219. } else if (resolve._tracked) {
  1220. // Already tracked promise - check contents
  1221. promise = resolve;
  1222. status = "_error" in promise ? AwaitRenderStatus.error : "_data" in promise ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
  1223. } else {
  1224. // Raw (untracked) promise - track it
  1225. status = AwaitRenderStatus.pending;
  1226. Object.defineProperty(resolve, "_tracked", {
  1227. get: () => true
  1228. });
  1229. promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
  1230. get: () => data
  1231. }), error => Object.defineProperty(resolve, "_error", {
  1232. get: () => error
  1233. }));
  1234. }
  1235. if (status === AwaitRenderStatus.error && promise._error instanceof AbortedDeferredError) {
  1236. // Freeze the UI by throwing a never resolved promise
  1237. throw neverSettledPromise;
  1238. }
  1239. if (status === AwaitRenderStatus.error && !errorElement) {
  1240. // No errorElement, throw to the nearest route-level error boundary
  1241. throw promise._error;
  1242. }
  1243. if (status === AwaitRenderStatus.error) {
  1244. // Render via our errorElement
  1245. return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
  1246. value: promise,
  1247. children: errorElement
  1248. });
  1249. }
  1250. if (status === AwaitRenderStatus.success) {
  1251. // Render children with resolved value
  1252. return /*#__PURE__*/React.createElement(AwaitContext.Provider, {
  1253. value: promise,
  1254. children: children
  1255. });
  1256. }
  1257. // Throw to the suspense boundary
  1258. throw promise;
  1259. }
  1260. }
  1261. /**
  1262. * @private
  1263. * Indirection to leverage useAsyncValue for a render-prop API on `<Await>`
  1264. */
  1265. function ResolveAwait({
  1266. children
  1267. }) {
  1268. let data = useAsyncValue();
  1269. let toRender = typeof children === "function" ? children(data) : children;
  1270. return /*#__PURE__*/React.createElement(React.Fragment, null, toRender);
  1271. }
  1272. ///////////////////////////////////////////////////////////////////////////////
  1273. // UTILS
  1274. ///////////////////////////////////////////////////////////////////////////////
  1275. /**
  1276. * Creates a route config from a React "children" object, which is usually
  1277. * either a `<Route>` element or an array of them. Used internally by
  1278. * `<Routes>` to create a route config from its children.
  1279. *
  1280. * @see https://reactrouter.com/v6/utils/create-routes-from-children
  1281. */
  1282. function createRoutesFromChildren(children, parentPath = []) {
  1283. let routes = [];
  1284. React.Children.forEach(children, (element, index) => {
  1285. if (! /*#__PURE__*/React.isValidElement(element)) {
  1286. // Ignore non-elements. This allows people to more easily inline
  1287. // conditionals in their route config.
  1288. return;
  1289. }
  1290. let treePath = [...parentPath, index];
  1291. if (element.type === React.Fragment) {
  1292. // Transparently support React.Fragment and its children.
  1293. routes.push.apply(routes, createRoutesFromChildren(element.props.children, treePath));
  1294. return;
  1295. }
  1296. !(element.type === Route) ? UNSAFE_invariant(false, `[${typeof element.type === "string" ? element.type : element.type.name}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`) : void 0;
  1297. !(!element.props.index || !element.props.children) ? UNSAFE_invariant(false, "An index route cannot have child routes.") : void 0;
  1298. let route = {
  1299. id: element.props.id || treePath.join("-"),
  1300. caseSensitive: element.props.caseSensitive,
  1301. element: element.props.element,
  1302. Component: element.props.Component,
  1303. index: element.props.index,
  1304. path: element.props.path,
  1305. loader: element.props.loader,
  1306. action: element.props.action,
  1307. errorElement: element.props.errorElement,
  1308. ErrorBoundary: element.props.ErrorBoundary,
  1309. hasErrorBoundary: element.props.ErrorBoundary != null || element.props.errorElement != null,
  1310. shouldRevalidate: element.props.shouldRevalidate,
  1311. handle: element.props.handle,
  1312. lazy: element.props.lazy
  1313. };
  1314. if (element.props.children) {
  1315. route.children = createRoutesFromChildren(element.props.children, treePath);
  1316. }
  1317. routes.push(route);
  1318. });
  1319. return routes;
  1320. }
  1321. /**
  1322. * Renders the result of `matchRoutes()` into a React element.
  1323. */
  1324. function renderMatches(matches) {
  1325. return _renderMatches(matches);
  1326. }
  1327. function mapRouteProperties(route) {
  1328. let updates = {
  1329. // Note: this check also occurs in createRoutesFromChildren so update
  1330. // there if you change this -- please and thank you!
  1331. hasErrorBoundary: route.ErrorBoundary != null || route.errorElement != null
  1332. };
  1333. if (route.Component) {
  1334. {
  1335. if (route.element) {
  1336. UNSAFE_warning(false, "You should not include both `Component` and `element` on your route - " + "`Component` will be used.") ;
  1337. }
  1338. }
  1339. Object.assign(updates, {
  1340. element: /*#__PURE__*/React.createElement(route.Component),
  1341. Component: undefined
  1342. });
  1343. }
  1344. if (route.HydrateFallback) {
  1345. {
  1346. if (route.hydrateFallbackElement) {
  1347. UNSAFE_warning(false, "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - " + "`HydrateFallback` will be used.") ;
  1348. }
  1349. }
  1350. Object.assign(updates, {
  1351. hydrateFallbackElement: /*#__PURE__*/React.createElement(route.HydrateFallback),
  1352. HydrateFallback: undefined
  1353. });
  1354. }
  1355. if (route.ErrorBoundary) {
  1356. {
  1357. if (route.errorElement) {
  1358. UNSAFE_warning(false, "You should not include both `ErrorBoundary` and `errorElement` on your route - " + "`ErrorBoundary` will be used.") ;
  1359. }
  1360. }
  1361. Object.assign(updates, {
  1362. errorElement: /*#__PURE__*/React.createElement(route.ErrorBoundary),
  1363. ErrorBoundary: undefined
  1364. });
  1365. }
  1366. return updates;
  1367. }
  1368. function createMemoryRouter(routes, opts) {
  1369. return createRouter({
  1370. basename: opts?.basename,
  1371. future: {
  1372. ...opts?.future,
  1373. v7_prependBasename: true
  1374. },
  1375. history: createMemoryHistory({
  1376. initialEntries: opts?.initialEntries,
  1377. initialIndex: opts?.initialIndex
  1378. }),
  1379. hydrationData: opts?.hydrationData,
  1380. routes,
  1381. mapRouteProperties,
  1382. dataStrategy: opts?.dataStrategy,
  1383. patchRoutesOnNavigation: opts?.patchRoutesOnNavigation
  1384. }).initialize();
  1385. }
  1386. export { Await, MemoryRouter, Navigate, Outlet, Route, Router, RouterProvider, Routes, DataRouterContext as UNSAFE_DataRouterContext, DataRouterStateContext as UNSAFE_DataRouterStateContext, LocationContext as UNSAFE_LocationContext, NavigationContext as UNSAFE_NavigationContext, RouteContext as UNSAFE_RouteContext, logV6DeprecationWarnings as UNSAFE_logV6DeprecationWarnings, mapRouteProperties as UNSAFE_mapRouteProperties, useRouteId as UNSAFE_useRouteId, useRoutesImpl as UNSAFE_useRoutesImpl, createMemoryRouter, createRoutesFromChildren, createRoutesFromChildren as createRoutesFromElements, renderMatches, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes };
  1387. //# sourceMappingURL=react-router.development.js.map