index.js 50 KB

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