react-router.development.js 65 KB

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