react-router.development.js 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  1. /**
  2. * React Router v6.8.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('@remix-run/router'), require('react')) :
  13. typeof define === 'function' && define.amd ? define(['exports', '@remix-run/router', 'react'], factory) :
  14. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactRouter = {}, global.RemixRouter, global.React));
  15. })(this, (function (exports, router, React) { '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. /**
  49. * Copyright (c) Facebook, Inc. and its affiliates.
  50. *
  51. * This source code is licensed under the MIT license found in the
  52. * LICENSE file in the root directory of this source tree.
  53. */
  54. /**
  55. * inlined Object.is polyfill to avoid requiring consumers ship their own
  56. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  57. */
  58. function isPolyfill(x, y) {
  59. return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
  60. ;
  61. }
  62. const is = typeof Object.is === "function" ? Object.is : isPolyfill; // Intentionally not using named imports because Rollup uses dynamic
  63. // dispatch for CommonJS interop named imports.
  64. const {
  65. useState,
  66. useEffect,
  67. useLayoutEffect,
  68. useDebugValue
  69. } = React__namespace;
  70. let didWarnOld18Alpha = false;
  71. let didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
  72. // because of a very particular set of implementation details and assumptions
  73. // -- change any one of them and it will break. The most important assumption
  74. // is that updates are always synchronous, because concurrent rendering is
  75. // only available in versions of React that also have a built-in
  76. // useSyncExternalStore API. And we only use this shim when the built-in API
  77. // does not exist.
  78. //
  79. // Do not assume that the clever hacks used by this hook also work in general.
  80. // The point of this shim is to replace the need for hacks by other libraries.
  81. function useSyncExternalStore$2(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of
  82. // React do not expose a way to check if we're hydrating. So users of the shim
  83. // will need to track that themselves and return the correct value
  84. // from `getSnapshot`.
  85. getServerSnapshot) {
  86. {
  87. if (!didWarnOld18Alpha) {
  88. if ("startTransition" in React__namespace) {
  89. didWarnOld18Alpha = true;
  90. console.error("You are using an outdated, pre-release alpha of React 18 that " + "does not support useSyncExternalStore. The " + "use-sync-external-store shim will not work correctly. Upgrade " + "to a newer pre-release.");
  91. }
  92. }
  93. } // Read the current snapshot from the store on every render. Again, this
  94. // breaks the rules of React, and only works here because of specific
  95. // implementation details, most importantly that updates are
  96. // always synchronous.
  97. const value = getSnapshot();
  98. {
  99. if (!didWarnUncachedGetSnapshot) {
  100. const cachedValue = getSnapshot();
  101. if (!is(value, cachedValue)) {
  102. console.error("The result of getSnapshot should be cached to avoid an infinite loop");
  103. didWarnUncachedGetSnapshot = true;
  104. }
  105. }
  106. } // Because updates are synchronous, we don't queue them. Instead we force a
  107. // re-render whenever the subscribed state changes by updating an some
  108. // arbitrary useState hook. Then, during render, we call getSnapshot to read
  109. // the current value.
  110. //
  111. // Because we don't actually use the state returned by the useState hook, we
  112. // can save a bit of memory by storing other stuff in that slot.
  113. //
  114. // To implement the early bailout, we need to track some things on a mutable
  115. // object. Usually, we would put that in a useRef hook, but we can stash it in
  116. // our useState hook instead.
  117. //
  118. // To force a re-render, we call forceUpdate({inst}). That works because the
  119. // new object always fails an equality check.
  120. const [{
  121. inst
  122. }, forceUpdate] = useState({
  123. inst: {
  124. value,
  125. getSnapshot
  126. }
  127. }); // Track the latest getSnapshot function with a ref. This needs to be updated
  128. // in the layout phase so we can access it during the tearing check that
  129. // happens on subscribe.
  130. useLayoutEffect(() => {
  131. inst.value = value;
  132. inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
  133. // commit phase if there was an interleaved mutation. In concurrent mode
  134. // this can happen all the time, but even in synchronous mode, an earlier
  135. // effect may have mutated the store.
  136. if (checkIfSnapshotChanged(inst)) {
  137. // Force a re-render.
  138. forceUpdate({
  139. inst
  140. });
  141. } // eslint-disable-next-line react-hooks/exhaustive-deps
  142. }, [subscribe, value, getSnapshot]);
  143. useEffect(() => {
  144. // Check for changes right before subscribing. Subsequent changes will be
  145. // detected in the subscription handler.
  146. if (checkIfSnapshotChanged(inst)) {
  147. // Force a re-render.
  148. forceUpdate({
  149. inst
  150. });
  151. }
  152. const handleStoreChange = () => {
  153. // TODO: Because there is no cross-renderer API for batching updates, it's
  154. // up to the consumer of this library to wrap their subscription event
  155. // with unstable_batchedUpdates. Should we try to detect when this isn't
  156. // the case and print a warning in development?
  157. // The store changed. Check if the snapshot changed since the last time we
  158. // read from the store.
  159. if (checkIfSnapshotChanged(inst)) {
  160. // Force a re-render.
  161. forceUpdate({
  162. inst
  163. });
  164. }
  165. }; // Subscribe to the store and return a clean-up function.
  166. return subscribe(handleStoreChange); // eslint-disable-next-line react-hooks/exhaustive-deps
  167. }, [subscribe]);
  168. useDebugValue(value);
  169. return value;
  170. }
  171. function checkIfSnapshotChanged(inst) {
  172. const latestGetSnapshot = inst.getSnapshot;
  173. const prevValue = inst.value;
  174. try {
  175. const nextValue = latestGetSnapshot();
  176. return !is(prevValue, nextValue);
  177. } catch (error) {
  178. return true;
  179. }
  180. }
  181. /**
  182. * Copyright (c) Facebook, Inc. and its affiliates.
  183. *
  184. * This source code is licensed under the MIT license found in the
  185. * LICENSE file in the root directory of this source tree.
  186. *
  187. * @flow
  188. */
  189. function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
  190. // Note: The shim does not use getServerSnapshot, because pre-18 versions of
  191. // React do not expose a way to check if we're hydrating. So users of the shim
  192. // will need to track that themselves and return the correct value
  193. // from `getSnapshot`.
  194. return getSnapshot();
  195. }
  196. /**
  197. * Inlined into the react-router repo since use-sync-external-store does not
  198. * provide a UMD-compatible package, so we need this to be able to distribute
  199. * UMD react-router bundles
  200. */
  201. const canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
  202. const isServerEnvironment = !canUseDOM;
  203. const shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore$2;
  204. const useSyncExternalStore = "useSyncExternalStore" in React__namespace ? (module => module.useSyncExternalStore)(React__namespace) : shim;
  205. const DataRouterContext = /*#__PURE__*/React__namespace.createContext(null);
  206. {
  207. DataRouterContext.displayName = "DataRouter";
  208. }
  209. const DataRouterStateContext = /*#__PURE__*/React__namespace.createContext(null);
  210. {
  211. DataRouterStateContext.displayName = "DataRouterState";
  212. }
  213. const AwaitContext = /*#__PURE__*/React__namespace.createContext(null);
  214. {
  215. AwaitContext.displayName = "Await";
  216. }
  217. const NavigationContext = /*#__PURE__*/React__namespace.createContext(null);
  218. {
  219. NavigationContext.displayName = "Navigation";
  220. }
  221. const LocationContext = /*#__PURE__*/React__namespace.createContext(null);
  222. {
  223. LocationContext.displayName = "Location";
  224. }
  225. const RouteContext = /*#__PURE__*/React__namespace.createContext({
  226. outlet: null,
  227. matches: []
  228. });
  229. {
  230. RouteContext.displayName = "Route";
  231. }
  232. const RouteErrorContext = /*#__PURE__*/React__namespace.createContext(null);
  233. {
  234. RouteErrorContext.displayName = "RouteError";
  235. }
  236. /**
  237. * Returns the full href for the given "to" value. This is useful for building
  238. * custom links that are also accessible and preserve right-click behavior.
  239. *
  240. * @see https://reactrouter.com/hooks/use-href
  241. */
  242. function useHref(to, _temp) {
  243. let {
  244. relative
  245. } = _temp === void 0 ? {} : _temp;
  246. !useInRouterContext() ? router.invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
  247. // router loaded. We can help them understand how to avoid that.
  248. "useHref() may be used only in the context of a <Router> component.") : void 0;
  249. let {
  250. basename,
  251. navigator
  252. } = React__namespace.useContext(NavigationContext);
  253. let {
  254. hash,
  255. pathname,
  256. search
  257. } = useResolvedPath(to, {
  258. relative
  259. });
  260. let joinedPathname = pathname; // If we're operating within a basename, prepend it to the pathname prior
  261. // to creating the href. If this is a root navigation, then just use the raw
  262. // basename which allows the basename to have full control over the presence
  263. // of a trailing slash on root links
  264. if (basename !== "/") {
  265. joinedPathname = pathname === "/" ? basename : router.joinPaths([basename, pathname]);
  266. }
  267. return navigator.createHref({
  268. pathname: joinedPathname,
  269. search,
  270. hash
  271. });
  272. }
  273. /**
  274. * Returns true if this component is a descendant of a <Router>.
  275. *
  276. * @see https://reactrouter.com/hooks/use-in-router-context
  277. */
  278. function useInRouterContext() {
  279. return React__namespace.useContext(LocationContext) != null;
  280. }
  281. /**
  282. * Returns the current location object, which represents the current URL in web
  283. * browsers.
  284. *
  285. * Note: If you're using this it may mean you're doing some of your own
  286. * "routing" in your app, and we'd like to know what your use case is. We may
  287. * be able to provide something higher-level to better suit your needs.
  288. *
  289. * @see https://reactrouter.com/hooks/use-location
  290. */
  291. function useLocation() {
  292. !useInRouterContext() ? router.invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
  293. // router loaded. We can help them understand how to avoid that.
  294. "useLocation() may be used only in the context of a <Router> component.") : void 0;
  295. return React__namespace.useContext(LocationContext).location;
  296. }
  297. /**
  298. * Returns the current navigation action which describes how the router came to
  299. * the current location, either by a pop, push, or replace on the history stack.
  300. *
  301. * @see https://reactrouter.com/hooks/use-navigation-type
  302. */
  303. function useNavigationType() {
  304. return React__namespace.useContext(LocationContext).navigationType;
  305. }
  306. /**
  307. * Returns a PathMatch object if the given pattern matches the current URL.
  308. * This is useful for components that need to know "active" state, e.g.
  309. * <NavLink>.
  310. *
  311. * @see https://reactrouter.com/hooks/use-match
  312. */
  313. function useMatch(pattern) {
  314. !useInRouterContext() ? router.invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
  315. // router loaded. We can help them understand how to avoid that.
  316. "useMatch() may be used only in the context of a <Router> component.") : void 0;
  317. let {
  318. pathname
  319. } = useLocation();
  320. return React__namespace.useMemo(() => router.matchPath(pattern, pathname), [pathname, pattern]);
  321. }
  322. /**
  323. * The interface for the navigate() function returned from useNavigate().
  324. */
  325. /**
  326. * Returns an imperative method for changing the location. Used by <Link>s, but
  327. * may also be used by other elements to change the location.
  328. *
  329. * @see https://reactrouter.com/hooks/use-navigate
  330. */
  331. function useNavigate() {
  332. !useInRouterContext() ? router.invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
  333. // router loaded. We can help them understand how to avoid that.
  334. "useNavigate() may be used only in the context of a <Router> component.") : void 0;
  335. let {
  336. basename,
  337. navigator
  338. } = React__namespace.useContext(NavigationContext);
  339. let {
  340. matches
  341. } = React__namespace.useContext(RouteContext);
  342. let {
  343. pathname: locationPathname
  344. } = useLocation();
  345. let routePathnamesJson = JSON.stringify(router.UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
  346. let activeRef = React__namespace.useRef(false);
  347. React__namespace.useEffect(() => {
  348. activeRef.current = true;
  349. });
  350. let navigate = React__namespace.useCallback(function (to, options) {
  351. if (options === void 0) {
  352. options = {};
  353. }
  354. router.warning(activeRef.current, "You should call navigate() in a React.useEffect(), not when " + "your component is first rendered.") ;
  355. if (!activeRef.current) return;
  356. if (typeof to === "number") {
  357. navigator.go(to);
  358. return;
  359. }
  360. let path = router.resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path"); // If we're operating within a basename, prepend it to the pathname prior
  361. // to handing off to history. If this is a root navigation, then we
  362. // navigate to the raw basename which allows the basename to have full
  363. // control over the presence of a trailing slash on root links
  364. if (basename !== "/") {
  365. path.pathname = path.pathname === "/" ? basename : router.joinPaths([basename, path.pathname]);
  366. }
  367. (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
  368. }, [basename, navigator, routePathnamesJson, locationPathname]);
  369. return navigate;
  370. }
  371. const OutletContext = /*#__PURE__*/React__namespace.createContext(null);
  372. /**
  373. * Returns the context (if provided) for the child route at this level of the route
  374. * hierarchy.
  375. * @see https://reactrouter.com/hooks/use-outlet-context
  376. */
  377. function useOutletContext() {
  378. return React__namespace.useContext(OutletContext);
  379. }
  380. /**
  381. * Returns the element for the child route at this level of the route
  382. * hierarchy. Used internally by <Outlet> to render child routes.
  383. *
  384. * @see https://reactrouter.com/hooks/use-outlet
  385. */
  386. function useOutlet(context) {
  387. let outlet = React__namespace.useContext(RouteContext).outlet;
  388. if (outlet) {
  389. return /*#__PURE__*/React__namespace.createElement(OutletContext.Provider, {
  390. value: context
  391. }, outlet);
  392. }
  393. return outlet;
  394. }
  395. /**
  396. * Returns an object of key/value pairs of the dynamic params from the current
  397. * URL that were matched by the route path.
  398. *
  399. * @see https://reactrouter.com/hooks/use-params
  400. */
  401. function useParams() {
  402. let {
  403. matches
  404. } = React__namespace.useContext(RouteContext);
  405. let routeMatch = matches[matches.length - 1];
  406. return routeMatch ? routeMatch.params : {};
  407. }
  408. /**
  409. * Resolves the pathname of the given `to` value against the current location.
  410. *
  411. * @see https://reactrouter.com/hooks/use-resolved-path
  412. */
  413. function useResolvedPath(to, _temp2) {
  414. let {
  415. relative
  416. } = _temp2 === void 0 ? {} : _temp2;
  417. let {
  418. matches
  419. } = React__namespace.useContext(RouteContext);
  420. let {
  421. pathname: locationPathname
  422. } = useLocation();
  423. let routePathnamesJson = JSON.stringify(router.UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
  424. return React__namespace.useMemo(() => router.resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
  425. }
  426. /**
  427. * Returns the element of the route that matched the current location, prepared
  428. * with the correct context to render the remainder of the route tree. Route
  429. * elements in the tree must render an <Outlet> to render their child route's
  430. * element.
  431. *
  432. * @see https://reactrouter.com/hooks/use-routes
  433. */
  434. function useRoutes(routes, locationArg) {
  435. !useInRouterContext() ? router.invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
  436. // router loaded. We can help them understand how to avoid that.
  437. "useRoutes() may be used only in the context of a <Router> component.") : void 0;
  438. let {
  439. navigator
  440. } = React__namespace.useContext(NavigationContext);
  441. let dataRouterStateContext = React__namespace.useContext(DataRouterStateContext);
  442. let {
  443. matches: parentMatches
  444. } = React__namespace.useContext(RouteContext);
  445. let routeMatch = parentMatches[parentMatches.length - 1];
  446. let parentParams = routeMatch ? routeMatch.params : {};
  447. let parentPathname = routeMatch ? routeMatch.pathname : "/";
  448. let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
  449. let parentRoute = routeMatch && routeMatch.route;
  450. {
  451. // You won't get a warning about 2 different <Routes> under a <Route>
  452. // without a trailing *, but this is a best-effort warning anyway since we
  453. // cannot even give the warning unless they land at the parent route.
  454. //
  455. // Example:
  456. //
  457. // <Routes>
  458. // {/* This route path MUST end with /* because otherwise
  459. // it will never match /blog/post/123 */}
  460. // <Route path="blog" element={<Blog />} />
  461. // <Route path="blog/feed" element={<BlogFeed />} />
  462. // </Routes>
  463. //
  464. // function Blog() {
  465. // return (
  466. // <Routes>
  467. // <Route path="post/:id" element={<Post />} />
  468. // </Routes>
  469. // );
  470. // }
  471. let parentPath = parentRoute && parentRoute.path || "";
  472. 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 + "/*") + "\">."));
  473. }
  474. let locationFromContext = useLocation();
  475. let location;
  476. if (locationArg) {
  477. var _parsedLocationArg$pa;
  478. let parsedLocationArg = typeof locationArg === "string" ? router.parsePath(locationArg) : locationArg;
  479. !(parentPathnameBase === "/" || ((_parsedLocationArg$pa = parsedLocationArg.pathname) == null ? void 0 : _parsedLocationArg$pa.startsWith(parentPathnameBase))) ? router.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;
  480. location = parsedLocationArg;
  481. } else {
  482. location = locationFromContext;
  483. }
  484. let pathname = location.pathname || "/";
  485. let remainingPathname = parentPathnameBase === "/" ? pathname : pathname.slice(parentPathnameBase.length) || "/";
  486. let matches = router.matchRoutes(routes, {
  487. pathname: remainingPathname
  488. });
  489. {
  490. router.warning(parentRoute || matches != null, "No routes matched location \"" + location.pathname + location.search + location.hash + "\" ") ;
  491. router.warning(matches == null || matches[matches.length - 1].route.element !== undefined, "Matched leaf route at location \"" + location.pathname + location.search + location.hash + "\" does not have an element. " + "This means it will render an <Outlet /> with a null value by default resulting in an \"empty\" page.") ;
  492. }
  493. let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
  494. params: Object.assign({}, parentParams, match.params),
  495. pathname: router.joinPaths([parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes
  496. navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),
  497. pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : router.joinPaths([parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes
  498. navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])
  499. })), parentMatches, dataRouterStateContext || undefined); // When a user passes in a `locationArg`, the associated routes need to
  500. // be wrapped in a new `LocationContext.Provider` in order for `useLocation`
  501. // to use the scoped location instead of the global location.
  502. if (locationArg && renderedMatches) {
  503. return /*#__PURE__*/React__namespace.createElement(LocationContext.Provider, {
  504. value: {
  505. location: _extends({
  506. pathname: "/",
  507. search: "",
  508. hash: "",
  509. state: null,
  510. key: "default"
  511. }, location),
  512. navigationType: router.Action.Pop
  513. }
  514. }, renderedMatches);
  515. }
  516. return renderedMatches;
  517. }
  518. function DefaultErrorElement() {
  519. let error = useRouteError();
  520. let message = router.isRouteErrorResponse(error) ? error.status + " " + error.statusText : error instanceof Error ? error.message : JSON.stringify(error);
  521. let stack = error instanceof Error ? error.stack : null;
  522. let lightgrey = "rgba(200,200,200, 0.5)";
  523. let preStyles = {
  524. padding: "0.5rem",
  525. backgroundColor: lightgrey
  526. };
  527. let codeStyles = {
  528. padding: "2px 4px",
  529. backgroundColor: lightgrey
  530. };
  531. let devInfo = null;
  532. {
  533. 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\xA0", /*#__PURE__*/React__namespace.createElement("code", {
  534. style: codeStyles
  535. }, "errorElement"), " props on\xA0", /*#__PURE__*/React__namespace.createElement("code", {
  536. style: codeStyles
  537. }, "<Route>")));
  538. }
  539. return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement("h2", null, "Unexpected Application Error!"), /*#__PURE__*/React__namespace.createElement("h3", {
  540. style: {
  541. fontStyle: "italic"
  542. }
  543. }, message), stack ? /*#__PURE__*/React__namespace.createElement("pre", {
  544. style: preStyles
  545. }, stack) : null, devInfo);
  546. }
  547. class RenderErrorBoundary extends React__namespace.Component {
  548. constructor(props) {
  549. super(props);
  550. this.state = {
  551. location: props.location,
  552. error: props.error
  553. };
  554. }
  555. static getDerivedStateFromError(error) {
  556. return {
  557. error: error
  558. };
  559. }
  560. static getDerivedStateFromProps(props, state) {
  561. // When we get into an error state, the user will likely click "back" to the
  562. // previous page that didn't have an error. Because this wraps the entire
  563. // application, that will have no effect--the error page continues to display.
  564. // This gives us a mechanism to recover from the error when the location changes.
  565. //
  566. // Whether we're in an error state or not, we update the location in state
  567. // so that when we are in an error state, it gets reset when a new location
  568. // comes in and the user recovers from the error.
  569. if (state.location !== props.location) {
  570. return {
  571. error: props.error,
  572. location: props.location
  573. };
  574. } // If we're not changing locations, preserve the location but still surface
  575. // any new errors that may come through. We retain the existing error, we do
  576. // this because the error provided from the app state may be cleared without
  577. // the location changing.
  578. return {
  579. error: props.error || state.error,
  580. location: state.location
  581. };
  582. }
  583. componentDidCatch(error, errorInfo) {
  584. console.error("React Router caught the following error during render", error, errorInfo);
  585. }
  586. render() {
  587. return this.state.error ? /*#__PURE__*/React__namespace.createElement(RouteContext.Provider, {
  588. value: this.props.routeContext
  589. }, /*#__PURE__*/React__namespace.createElement(RouteErrorContext.Provider, {
  590. value: this.state.error,
  591. children: this.props.component
  592. })) : this.props.children;
  593. }
  594. }
  595. function RenderedRoute(_ref) {
  596. let {
  597. routeContext,
  598. match,
  599. children
  600. } = _ref;
  601. let dataRouterContext = React__namespace.useContext(DataRouterContext); // Track how deep we got in our render pass to emulate SSR componentDidCatch
  602. // in a DataStaticRouter
  603. if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && match.route.errorElement) {
  604. dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
  605. }
  606. return /*#__PURE__*/React__namespace.createElement(RouteContext.Provider, {
  607. value: routeContext
  608. }, children);
  609. }
  610. function _renderMatches(matches, parentMatches, dataRouterState) {
  611. if (parentMatches === void 0) {
  612. parentMatches = [];
  613. }
  614. if (matches == null) {
  615. if (dataRouterState != null && dataRouterState.errors) {
  616. // Don't bail if we have data router errors so we can render them in the
  617. // boundary. Use the pre-matched (or shimmed) matches
  618. matches = dataRouterState.matches;
  619. } else {
  620. return null;
  621. }
  622. }
  623. let renderedMatches = matches; // If we have data errors, trim matches to the highest error boundary
  624. let errors = dataRouterState == null ? void 0 : dataRouterState.errors;
  625. if (errors != null) {
  626. let errorIndex = renderedMatches.findIndex(m => m.route.id && (errors == null ? void 0 : errors[m.route.id]));
  627. !(errorIndex >= 0) ? router.invariant(false, "Could not find a matching route for the current errors: " + errors) : void 0;
  628. renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
  629. }
  630. return renderedMatches.reduceRight((outlet, match, index) => {
  631. let error = match.route.id ? errors == null ? void 0 : errors[match.route.id] : null; // Only data routers handle errors
  632. let errorElement = dataRouterState ? match.route.errorElement || /*#__PURE__*/React__namespace.createElement(DefaultErrorElement, null) : null;
  633. let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
  634. let getChildren = () => /*#__PURE__*/React__namespace.createElement(RenderedRoute, {
  635. match: match,
  636. routeContext: {
  637. outlet,
  638. matches
  639. }
  640. }, error ? errorElement : match.route.element !== undefined ? match.route.element : outlet); // Only wrap in an error boundary within data router usages when we have an
  641. // errorElement on this route. Otherwise let it bubble up to an ancestor
  642. // errorElement
  643. return dataRouterState && (match.route.errorElement || index === 0) ? /*#__PURE__*/React__namespace.createElement(RenderErrorBoundary, {
  644. location: dataRouterState.location,
  645. component: errorElement,
  646. error: error,
  647. children: getChildren(),
  648. routeContext: {
  649. outlet: null,
  650. matches
  651. }
  652. }) : getChildren();
  653. }, null);
  654. }
  655. var DataRouterHook;
  656. (function (DataRouterHook) {
  657. DataRouterHook["UseBlocker"] = "useBlocker";
  658. DataRouterHook["UseRevalidator"] = "useRevalidator";
  659. })(DataRouterHook || (DataRouterHook = {}));
  660. var DataRouterStateHook;
  661. (function (DataRouterStateHook) {
  662. DataRouterStateHook["UseLoaderData"] = "useLoaderData";
  663. DataRouterStateHook["UseActionData"] = "useActionData";
  664. DataRouterStateHook["UseRouteError"] = "useRouteError";
  665. DataRouterStateHook["UseNavigation"] = "useNavigation";
  666. DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
  667. DataRouterStateHook["UseMatches"] = "useMatches";
  668. DataRouterStateHook["UseRevalidator"] = "useRevalidator";
  669. })(DataRouterStateHook || (DataRouterStateHook = {}));
  670. function getDataRouterConsoleError(hookName) {
  671. return hookName + " must be used within a data router. See https://reactrouter.com/routers/picking-a-router.";
  672. }
  673. function useDataRouterContext(hookName) {
  674. let ctx = React__namespace.useContext(DataRouterContext);
  675. !ctx ? router.invariant(false, getDataRouterConsoleError(hookName)) : void 0;
  676. return ctx;
  677. }
  678. function useDataRouterState(hookName) {
  679. let state = React__namespace.useContext(DataRouterStateContext);
  680. !state ? router.invariant(false, getDataRouterConsoleError(hookName)) : void 0;
  681. return state;
  682. }
  683. function useRouteContext(hookName) {
  684. let route = React__namespace.useContext(RouteContext);
  685. !route ? router.invariant(false, getDataRouterConsoleError(hookName)) : void 0;
  686. return route;
  687. }
  688. function useCurrentRouteId(hookName) {
  689. let route = useRouteContext(hookName);
  690. let thisRoute = route.matches[route.matches.length - 1];
  691. !thisRoute.route.id ? router.invariant(false, hookName + " can only be used on routes that contain a unique \"id\"") : void 0;
  692. return thisRoute.route.id;
  693. }
  694. /**
  695. * Returns the current navigation, defaulting to an "idle" navigation when
  696. * no navigation is in progress
  697. */
  698. function useNavigation() {
  699. let state = useDataRouterState(DataRouterStateHook.UseNavigation);
  700. return state.navigation;
  701. }
  702. /**
  703. * Returns a revalidate function for manually triggering revalidation, as well
  704. * as the current state of any manual revalidations
  705. */
  706. function useRevalidator() {
  707. let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
  708. let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
  709. return {
  710. revalidate: dataRouterContext.router.revalidate,
  711. state: state.revalidation
  712. };
  713. }
  714. /**
  715. * Returns the active route matches, useful for accessing loaderData for
  716. * parent/child routes or the route "handle" property
  717. */
  718. function useMatches() {
  719. let {
  720. matches,
  721. loaderData
  722. } = useDataRouterState(DataRouterStateHook.UseMatches);
  723. return React__namespace.useMemo(() => matches.map(match => {
  724. let {
  725. pathname,
  726. params
  727. } = match; // Note: This structure matches that created by createUseMatchesMatch
  728. // in the @remix-run/router , so if you change this please also change
  729. // that :) Eventually we'll DRY this up
  730. return {
  731. id: match.route.id,
  732. pathname,
  733. params,
  734. data: loaderData[match.route.id],
  735. handle: match.route.handle
  736. };
  737. }), [matches, loaderData]);
  738. }
  739. /**
  740. * Returns the loader data for the nearest ancestor Route loader
  741. */
  742. function useLoaderData() {
  743. let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
  744. let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
  745. if (state.errors && state.errors[routeId] != null) {
  746. console.error("You cannot `useLoaderData` in an errorElement (routeId: " + routeId + ")");
  747. return undefined;
  748. }
  749. return state.loaderData[routeId];
  750. }
  751. /**
  752. * Returns the loaderData for the given routeId
  753. */
  754. function useRouteLoaderData(routeId) {
  755. let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
  756. return state.loaderData[routeId];
  757. }
  758. /**
  759. * Returns the action data for the nearest ancestor Route action
  760. */
  761. function useActionData() {
  762. let state = useDataRouterState(DataRouterStateHook.UseActionData);
  763. let route = React__namespace.useContext(RouteContext);
  764. !route ? router.invariant(false, "useActionData must be used inside a RouteContext") : void 0;
  765. return Object.values((state == null ? void 0 : state.actionData) || {})[0];
  766. }
  767. /**
  768. * Returns the nearest ancestor Route error, which could be a loader/action
  769. * error or a render error. This is intended to be called from your
  770. * errorElement to display a proper error message.
  771. */
  772. function useRouteError() {
  773. var _state$errors;
  774. let error = React__namespace.useContext(RouteErrorContext);
  775. let state = useDataRouterState(DataRouterStateHook.UseRouteError);
  776. let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError); // If this was a render error, we put it in a RouteError context inside
  777. // of RenderErrorBoundary
  778. if (error) {
  779. return error;
  780. } // Otherwise look for errors from our data router state
  781. return (_state$errors = state.errors) == null ? void 0 : _state$errors[routeId];
  782. }
  783. /**
  784. * Returns the happy-path data from the nearest ancestor <Await /> value
  785. */
  786. function useAsyncValue() {
  787. let value = React__namespace.useContext(AwaitContext);
  788. return value == null ? void 0 : value._data;
  789. }
  790. /**
  791. * Returns the error from the nearest ancestor <Await /> value
  792. */
  793. function useAsyncError() {
  794. let value = React__namespace.useContext(AwaitContext);
  795. return value == null ? void 0 : value._error;
  796. }
  797. let blockerId = 0;
  798. /**
  799. * Allow the application to block navigations within the SPA and present the
  800. * user a confirmation dialog to confirm the navigation. Mostly used to avoid
  801. * using half-filled form data. This does not handle hard-reloads or
  802. * cross-origin navigations.
  803. */
  804. function useBlocker(shouldBlock) {
  805. let {
  806. router
  807. } = useDataRouterContext(DataRouterHook.UseBlocker);
  808. let [blockerKey] = React__namespace.useState(() => String(++blockerId));
  809. let blockerFunction = React__namespace.useCallback(args => {
  810. return typeof shouldBlock === "function" ? !!shouldBlock(args) : !!shouldBlock;
  811. }, [shouldBlock]);
  812. let blocker = router.getBlocker(blockerKey, blockerFunction); // Cleanup on unmount
  813. React__namespace.useEffect(() => () => router.deleteBlocker(blockerKey), [router, blockerKey]);
  814. return blocker;
  815. }
  816. const alreadyWarned = {};
  817. function warningOnce(key, cond, message) {
  818. if (!cond && !alreadyWarned[key]) {
  819. alreadyWarned[key] = true;
  820. router.warning(false, message) ;
  821. }
  822. }
  823. /**
  824. * Given a Remix Router instance, render the appropriate UI
  825. */
  826. function RouterProvider(_ref) {
  827. let {
  828. fallbackElement,
  829. router
  830. } = _ref;
  831. // Sync router state to our component state to force re-renders
  832. let state = useSyncExternalStore(router.subscribe, () => router.state, // We have to provide this so React@18 doesn't complain during hydration,
  833. // but we pass our serialized hydration data into the router so state here
  834. // is already synced with what the server saw
  835. () => router.state);
  836. let navigator = React__namespace.useMemo(() => {
  837. return {
  838. createHref: router.createHref,
  839. encodeLocation: router.encodeLocation,
  840. go: n => router.navigate(n),
  841. push: (to, state, opts) => router.navigate(to, {
  842. state,
  843. preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
  844. }),
  845. replace: (to, state, opts) => router.navigate(to, {
  846. replace: true,
  847. state,
  848. preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
  849. })
  850. };
  851. }, [router]);
  852. let basename = router.basename || "/"; // The fragment and {null} here are important! We need them to keep React 18's
  853. // useId happy when we are server-rendering since we may have a <script> here
  854. // containing the hydrated server-side staticContext (from StaticRouterProvider).
  855. // useId relies on the component tree structure to generate deterministic id's
  856. // so we need to ensure it remains the same on the client even though
  857. // we don't need the <script> tag
  858. return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(DataRouterContext.Provider, {
  859. value: {
  860. router,
  861. navigator,
  862. static: false,
  863. // Do we need this?
  864. basename
  865. }
  866. }, /*#__PURE__*/React__namespace.createElement(DataRouterStateContext.Provider, {
  867. value: state
  868. }, /*#__PURE__*/React__namespace.createElement(Router, {
  869. basename: router.basename,
  870. location: router.state.location,
  871. navigationType: router.state.historyAction,
  872. navigator: navigator
  873. }, router.state.initialized ? /*#__PURE__*/React__namespace.createElement(Routes, null) : fallbackElement))), null);
  874. }
  875. /**
  876. * A <Router> that stores all entries in memory.
  877. *
  878. * @see https://reactrouter.com/router-components/memory-router
  879. */
  880. function MemoryRouter(_ref2) {
  881. let {
  882. basename,
  883. children,
  884. initialEntries,
  885. initialIndex
  886. } = _ref2;
  887. let historyRef = React__namespace.useRef();
  888. if (historyRef.current == null) {
  889. historyRef.current = router.createMemoryHistory({
  890. initialEntries,
  891. initialIndex,
  892. v5Compat: true
  893. });
  894. }
  895. let history = historyRef.current;
  896. let [state, setState] = React__namespace.useState({
  897. action: history.action,
  898. location: history.location
  899. });
  900. React__namespace.useLayoutEffect(() => history.listen(setState), [history]);
  901. return /*#__PURE__*/React__namespace.createElement(Router, {
  902. basename: basename,
  903. children: children,
  904. location: state.location,
  905. navigationType: state.action,
  906. navigator: history
  907. });
  908. }
  909. /**
  910. * Changes the current location.
  911. *
  912. * Note: This API is mostly useful in React.Component subclasses that are not
  913. * able to use hooks. In functional components, we recommend you use the
  914. * `useNavigate` hook instead.
  915. *
  916. * @see https://reactrouter.com/components/navigate
  917. */
  918. function Navigate(_ref3) {
  919. let {
  920. to,
  921. replace,
  922. state,
  923. relative
  924. } = _ref3;
  925. !useInRouterContext() ? router.invariant(false, // TODO: This error is probably because they somehow have 2 versions of
  926. // the router loaded. We can help them understand how to avoid that.
  927. "<Navigate> may be used only in the context of a <Router> component.") : void 0;
  928. router.warning(!React__namespace.useContext(NavigationContext).static, "<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.") ;
  929. let dataRouterState = React__namespace.useContext(DataRouterStateContext);
  930. let navigate = useNavigate();
  931. React__namespace.useEffect(() => {
  932. // Avoid kicking off multiple navigations if we're in the middle of a
  933. // data-router navigation, since components get re-rendered when we enter
  934. // a submitting/loading state
  935. if (dataRouterState && dataRouterState.navigation.state !== "idle") {
  936. return;
  937. }
  938. navigate(to, {
  939. replace,
  940. state,
  941. relative
  942. });
  943. });
  944. return null;
  945. }
  946. /**
  947. * Renders the child route's element, if there is one.
  948. *
  949. * @see https://reactrouter.com/components/outlet
  950. */
  951. function Outlet(props) {
  952. return useOutlet(props.context);
  953. }
  954. /**
  955. * Declares an element that should be rendered at a certain URL path.
  956. *
  957. * @see https://reactrouter.com/components/route
  958. */
  959. function Route(_props) {
  960. router.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>.") ;
  961. }
  962. /**
  963. * Provides location context for the rest of the app.
  964. *
  965. * Note: You usually won't render a <Router> directly. Instead, you'll render a
  966. * router that is more specific to your environment such as a <BrowserRouter>
  967. * in web browsers or a <StaticRouter> for server rendering.
  968. *
  969. * @see https://reactrouter.com/router-components/router
  970. */
  971. function Router(_ref4) {
  972. let {
  973. basename: basenameProp = "/",
  974. children = null,
  975. location: locationProp,
  976. navigationType = router.Action.Pop,
  977. navigator,
  978. static: staticProp = false
  979. } = _ref4;
  980. !!useInRouterContext() ? router.invariant(false, "You cannot render a <Router> inside another <Router>." + " You should never have more than one in your app.") : void 0; // Preserve trailing slashes on basename, so we can let the user control
  981. // the enforcement of trailing slashes throughout the app
  982. let basename = basenameProp.replace(/^\/*/, "/");
  983. let navigationContext = React__namespace.useMemo(() => ({
  984. basename,
  985. navigator,
  986. static: staticProp
  987. }), [basename, navigator, staticProp]);
  988. if (typeof locationProp === "string") {
  989. locationProp = router.parsePath(locationProp);
  990. }
  991. let {
  992. pathname = "/",
  993. search = "",
  994. hash = "",
  995. state = null,
  996. key = "default"
  997. } = locationProp;
  998. let location = React__namespace.useMemo(() => {
  999. let trailingPathname = router.stripBasename(pathname, basename);
  1000. if (trailingPathname == null) {
  1001. return null;
  1002. }
  1003. return {
  1004. pathname: trailingPathname,
  1005. search,
  1006. hash,
  1007. state,
  1008. key
  1009. };
  1010. }, [basename, pathname, search, hash, state, key]);
  1011. router.warning(location != 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.") ;
  1012. if (location == null) {
  1013. return null;
  1014. }
  1015. return /*#__PURE__*/React__namespace.createElement(NavigationContext.Provider, {
  1016. value: navigationContext
  1017. }, /*#__PURE__*/React__namespace.createElement(LocationContext.Provider, {
  1018. children: children,
  1019. value: {
  1020. location,
  1021. navigationType
  1022. }
  1023. }));
  1024. }
  1025. /**
  1026. * A container for a nested tree of <Route> elements that renders the branch
  1027. * that best matches the current location.
  1028. *
  1029. * @see https://reactrouter.com/components/routes
  1030. */
  1031. function Routes(_ref5) {
  1032. let {
  1033. children,
  1034. location
  1035. } = _ref5;
  1036. let dataRouterContext = React__namespace.useContext(DataRouterContext); // When in a DataRouterContext _without_ children, we use the router routes
  1037. // directly. If we have children, then we're in a descendant tree and we
  1038. // need to use child routes.
  1039. let routes = dataRouterContext && !children ? dataRouterContext.router.routes : createRoutesFromChildren(children);
  1040. return useRoutes(routes, location);
  1041. }
  1042. /**
  1043. * Component to use for rendering lazily loaded data from returning defer()
  1044. * in a loader function
  1045. */
  1046. function Await(_ref6) {
  1047. let {
  1048. children,
  1049. errorElement,
  1050. resolve
  1051. } = _ref6;
  1052. return /*#__PURE__*/React__namespace.createElement(AwaitErrorBoundary, {
  1053. resolve: resolve,
  1054. errorElement: errorElement
  1055. }, /*#__PURE__*/React__namespace.createElement(ResolveAwait, null, children));
  1056. }
  1057. var AwaitRenderStatus;
  1058. (function (AwaitRenderStatus) {
  1059. AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
  1060. AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
  1061. AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
  1062. })(AwaitRenderStatus || (AwaitRenderStatus = {}));
  1063. const neverSettledPromise = new Promise(() => {});
  1064. class AwaitErrorBoundary extends React__namespace.Component {
  1065. constructor(props) {
  1066. super(props);
  1067. this.state = {
  1068. error: null
  1069. };
  1070. }
  1071. static getDerivedStateFromError(error) {
  1072. return {
  1073. error
  1074. };
  1075. }
  1076. componentDidCatch(error, errorInfo) {
  1077. console.error("<Await> caught the following error during render", error, errorInfo);
  1078. }
  1079. render() {
  1080. let {
  1081. children,
  1082. errorElement,
  1083. resolve
  1084. } = this.props;
  1085. let promise = null;
  1086. let status = AwaitRenderStatus.pending;
  1087. if (!(resolve instanceof Promise)) {
  1088. // Didn't get a promise - provide as a resolved promise
  1089. status = AwaitRenderStatus.success;
  1090. promise = Promise.resolve();
  1091. Object.defineProperty(promise, "_tracked", {
  1092. get: () => true
  1093. });
  1094. Object.defineProperty(promise, "_data", {
  1095. get: () => resolve
  1096. });
  1097. } else if (this.state.error) {
  1098. // Caught a render error, provide it as a rejected promise
  1099. status = AwaitRenderStatus.error;
  1100. let renderError = this.state.error;
  1101. promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
  1102. Object.defineProperty(promise, "_tracked", {
  1103. get: () => true
  1104. });
  1105. Object.defineProperty(promise, "_error", {
  1106. get: () => renderError
  1107. });
  1108. } else if (resolve._tracked) {
  1109. // Already tracked promise - check contents
  1110. promise = resolve;
  1111. status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
  1112. } else {
  1113. // Raw (untracked) promise - track it
  1114. status = AwaitRenderStatus.pending;
  1115. Object.defineProperty(resolve, "_tracked", {
  1116. get: () => true
  1117. });
  1118. promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
  1119. get: () => data
  1120. }), error => Object.defineProperty(resolve, "_error", {
  1121. get: () => error
  1122. }));
  1123. }
  1124. if (status === AwaitRenderStatus.error && promise._error instanceof router.AbortedDeferredError) {
  1125. // Freeze the UI by throwing a never resolved promise
  1126. throw neverSettledPromise;
  1127. }
  1128. if (status === AwaitRenderStatus.error && !errorElement) {
  1129. // No errorElement, throw to the nearest route-level error boundary
  1130. throw promise._error;
  1131. }
  1132. if (status === AwaitRenderStatus.error) {
  1133. // Render via our errorElement
  1134. return /*#__PURE__*/React__namespace.createElement(AwaitContext.Provider, {
  1135. value: promise,
  1136. children: errorElement
  1137. });
  1138. }
  1139. if (status === AwaitRenderStatus.success) {
  1140. // Render children with resolved value
  1141. return /*#__PURE__*/React__namespace.createElement(AwaitContext.Provider, {
  1142. value: promise,
  1143. children: children
  1144. });
  1145. } // Throw to the suspense boundary
  1146. throw promise;
  1147. }
  1148. }
  1149. /**
  1150. * @private
  1151. * Indirection to leverage useAsyncValue for a render-prop API on <Await>
  1152. */
  1153. function ResolveAwait(_ref7) {
  1154. let {
  1155. children
  1156. } = _ref7;
  1157. let data = useAsyncValue();
  1158. let toRender = typeof children === "function" ? children(data) : children;
  1159. return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, toRender);
  1160. } ///////////////////////////////////////////////////////////////////////////////
  1161. // UTILS
  1162. ///////////////////////////////////////////////////////////////////////////////
  1163. /**
  1164. * Creates a route config from a React "children" object, which is usually
  1165. * either a `<Route>` element or an array of them. Used internally by
  1166. * `<Routes>` to create a route config from its children.
  1167. *
  1168. * @see https://reactrouter.com/utils/create-routes-from-children
  1169. */
  1170. function createRoutesFromChildren(children, parentPath) {
  1171. if (parentPath === void 0) {
  1172. parentPath = [];
  1173. }
  1174. let routes = [];
  1175. React__namespace.Children.forEach(children, (element, index) => {
  1176. if (! /*#__PURE__*/React__namespace.isValidElement(element)) {
  1177. // Ignore non-elements. This allows people to more easily inline
  1178. // conditionals in their route config.
  1179. return;
  1180. }
  1181. if (element.type === React__namespace.Fragment) {
  1182. // Transparently support React.Fragment and its children.
  1183. routes.push.apply(routes, createRoutesFromChildren(element.props.children, parentPath));
  1184. return;
  1185. }
  1186. !(element.type === Route) ? router.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;
  1187. !(!element.props.index || !element.props.children) ? router.invariant(false, "An index route cannot have child routes.") : void 0;
  1188. let treePath = [...parentPath, index];
  1189. let route = {
  1190. id: element.props.id || treePath.join("-"),
  1191. caseSensitive: element.props.caseSensitive,
  1192. element: element.props.element,
  1193. index: element.props.index,
  1194. path: element.props.path,
  1195. loader: element.props.loader,
  1196. action: element.props.action,
  1197. errorElement: element.props.errorElement,
  1198. hasErrorBoundary: element.props.errorElement != null,
  1199. shouldRevalidate: element.props.shouldRevalidate,
  1200. handle: element.props.handle
  1201. };
  1202. if (element.props.children) {
  1203. route.children = createRoutesFromChildren(element.props.children, treePath);
  1204. }
  1205. routes.push(route);
  1206. });
  1207. return routes;
  1208. }
  1209. /**
  1210. * Renders the result of `matchRoutes()` into a React element.
  1211. */
  1212. function renderMatches(matches) {
  1213. return _renderMatches(matches);
  1214. }
  1215. /**
  1216. * @private
  1217. * Walk the route tree and add hasErrorBoundary if it's not provided, so that
  1218. * users providing manual route arrays can just specify errorElement
  1219. */
  1220. function enhanceManualRouteObjects(routes) {
  1221. return routes.map(route => {
  1222. let routeClone = _extends({}, route);
  1223. if (routeClone.hasErrorBoundary == null) {
  1224. routeClone.hasErrorBoundary = routeClone.errorElement != null;
  1225. }
  1226. if (routeClone.children) {
  1227. routeClone.children = enhanceManualRouteObjects(routeClone.children);
  1228. }
  1229. return routeClone;
  1230. });
  1231. }
  1232. function createMemoryRouter(routes, opts) {
  1233. return router.createRouter({
  1234. basename: opts == null ? void 0 : opts.basename,
  1235. history: router.createMemoryHistory({
  1236. initialEntries: opts == null ? void 0 : opts.initialEntries,
  1237. initialIndex: opts == null ? void 0 : opts.initialIndex
  1238. }),
  1239. hydrationData: opts == null ? void 0 : opts.hydrationData,
  1240. routes: enhanceManualRouteObjects(routes)
  1241. }).initialize();
  1242. } ///////////////////////////////////////////////////////////////////////////////
  1243. Object.defineProperty(exports, 'AbortedDeferredError', {
  1244. enumerable: true,
  1245. get: function () { return router.AbortedDeferredError; }
  1246. });
  1247. Object.defineProperty(exports, 'NavigationType', {
  1248. enumerable: true,
  1249. get: function () { return router.Action; }
  1250. });
  1251. Object.defineProperty(exports, 'createPath', {
  1252. enumerable: true,
  1253. get: function () { return router.createPath; }
  1254. });
  1255. Object.defineProperty(exports, 'defer', {
  1256. enumerable: true,
  1257. get: function () { return router.defer; }
  1258. });
  1259. Object.defineProperty(exports, 'generatePath', {
  1260. enumerable: true,
  1261. get: function () { return router.generatePath; }
  1262. });
  1263. Object.defineProperty(exports, 'isRouteErrorResponse', {
  1264. enumerable: true,
  1265. get: function () { return router.isRouteErrorResponse; }
  1266. });
  1267. Object.defineProperty(exports, 'json', {
  1268. enumerable: true,
  1269. get: function () { return router.json; }
  1270. });
  1271. Object.defineProperty(exports, 'matchPath', {
  1272. enumerable: true,
  1273. get: function () { return router.matchPath; }
  1274. });
  1275. Object.defineProperty(exports, 'matchRoutes', {
  1276. enumerable: true,
  1277. get: function () { return router.matchRoutes; }
  1278. });
  1279. Object.defineProperty(exports, 'parsePath', {
  1280. enumerable: true,
  1281. get: function () { return router.parsePath; }
  1282. });
  1283. Object.defineProperty(exports, 'redirect', {
  1284. enumerable: true,
  1285. get: function () { return router.redirect; }
  1286. });
  1287. Object.defineProperty(exports, 'resolvePath', {
  1288. enumerable: true,
  1289. get: function () { return router.resolvePath; }
  1290. });
  1291. exports.Await = Await;
  1292. exports.MemoryRouter = MemoryRouter;
  1293. exports.Navigate = Navigate;
  1294. exports.Outlet = Outlet;
  1295. exports.Route = Route;
  1296. exports.Router = Router;
  1297. exports.RouterProvider = RouterProvider;
  1298. exports.Routes = Routes;
  1299. exports.UNSAFE_DataRouterContext = DataRouterContext;
  1300. exports.UNSAFE_DataRouterStateContext = DataRouterStateContext;
  1301. exports.UNSAFE_LocationContext = LocationContext;
  1302. exports.UNSAFE_NavigationContext = NavigationContext;
  1303. exports.UNSAFE_RouteContext = RouteContext;
  1304. exports.UNSAFE_enhanceManualRouteObjects = enhanceManualRouteObjects;
  1305. exports.createMemoryRouter = createMemoryRouter;
  1306. exports.createRoutesFromChildren = createRoutesFromChildren;
  1307. exports.createRoutesFromElements = createRoutesFromChildren;
  1308. exports.renderMatches = renderMatches;
  1309. exports.unstable_useBlocker = useBlocker;
  1310. exports.useActionData = useActionData;
  1311. exports.useAsyncError = useAsyncError;
  1312. exports.useAsyncValue = useAsyncValue;
  1313. exports.useHref = useHref;
  1314. exports.useInRouterContext = useInRouterContext;
  1315. exports.useLoaderData = useLoaderData;
  1316. exports.useLocation = useLocation;
  1317. exports.useMatch = useMatch;
  1318. exports.useMatches = useMatches;
  1319. exports.useNavigate = useNavigate;
  1320. exports.useNavigation = useNavigation;
  1321. exports.useNavigationType = useNavigationType;
  1322. exports.useOutlet = useOutlet;
  1323. exports.useOutletContext = useOutletContext;
  1324. exports.useParams = useParams;
  1325. exports.useResolvedPath = useResolvedPath;
  1326. exports.useRevalidator = useRevalidator;
  1327. exports.useRouteError = useRouteError;
  1328. exports.useRouteLoaderData = useRouteLoaderData;
  1329. exports.useRoutes = useRoutes;
  1330. Object.defineProperty(exports, '__esModule', { value: true });
  1331. }));
  1332. //# sourceMappingURL=react-router.development.js.map