index.js 59 KB

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