index.js 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  1. /**
  2. * React Router DOM v6.30.1
  3. *
  4. * Copyright (c) Remix Software Inc.
  5. *
  6. * This source code is licensed under the MIT license found in the
  7. * LICENSE.md file in the root directory of this source tree.
  8. *
  9. * @license MIT
  10. */
  11. import * as React from 'react';
  12. import * as ReactDOM from 'react-dom';
  13. import { UNSAFE_mapRouteProperties, UNSAFE_logV6DeprecationWarnings, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, Router, UNSAFE_useRoutesImpl, UNSAFE_NavigationContext, useHref, useResolvedPath, useLocation, useNavigate, createPath, UNSAFE_useRouteId, UNSAFE_RouteContext, useMatches, useNavigation, useBlocker } from 'react-router';
  14. export { AbortedDeferredError, Await, MemoryRouter, Navigate, NavigationType, Outlet, Route, Router, Routes, UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, UNSAFE_useRouteId, createMemoryRouter, createPath, createRoutesFromChildren, createRoutesFromElements, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, renderMatches, replace, resolvePath, useActionData, useAsyncError, useAsyncValue, useBlocker, useHref, useInRouterContext, useLoaderData, useLocation, useMatch, useMatches, useNavigate, useNavigation, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRevalidator, useRouteError, useRouteLoaderData, useRoutes } from 'react-router';
  15. import { stripBasename, UNSAFE_warning, createRouter, createBrowserHistory, createHashHistory, UNSAFE_ErrorResponseImpl, UNSAFE_invariant, joinPaths, IDLE_FETCHER, matchPath } from '@remix-run/router';
  16. export { UNSAFE_ErrorResponseImpl } from '@remix-run/router';
  17. function _extends() {
  18. _extends = Object.assign ? Object.assign.bind() : function (target) {
  19. for (var i = 1; i < arguments.length; i++) {
  20. var source = arguments[i];
  21. for (var key in source) {
  22. if (Object.prototype.hasOwnProperty.call(source, key)) {
  23. target[key] = source[key];
  24. }
  25. }
  26. }
  27. return target;
  28. };
  29. return _extends.apply(this, arguments);
  30. }
  31. function _objectWithoutPropertiesLoose(source, excluded) {
  32. if (source == null) return {};
  33. var target = {};
  34. var sourceKeys = Object.keys(source);
  35. var key, i;
  36. for (i = 0; i < sourceKeys.length; i++) {
  37. key = sourceKeys[i];
  38. if (excluded.indexOf(key) >= 0) continue;
  39. target[key] = source[key];
  40. }
  41. return target;
  42. }
  43. const defaultMethod = "get";
  44. const defaultEncType = "application/x-www-form-urlencoded";
  45. function isHtmlElement(object) {
  46. return object != null && typeof object.tagName === "string";
  47. }
  48. function isButtonElement(object) {
  49. return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
  50. }
  51. function isFormElement(object) {
  52. return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
  53. }
  54. function isInputElement(object) {
  55. return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
  56. }
  57. function isModifiedEvent(event) {
  58. return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
  59. }
  60. function shouldProcessLinkClick(event, target) {
  61. return event.button === 0 && (
  62. // Ignore everything but left clicks
  63. !target || target === "_self") &&
  64. // Let browser handle "target=_blank" etc.
  65. !isModifiedEvent(event) // Ignore clicks with modifier keys
  66. ;
  67. }
  68. /**
  69. * Creates a URLSearchParams object using the given initializer.
  70. *
  71. * This is identical to `new URLSearchParams(init)` except it also
  72. * supports arrays as values in the object form of the initializer
  73. * instead of just strings. This is convenient when you need multiple
  74. * values for a given key, but don't want to use an array initializer.
  75. *
  76. * For example, instead of:
  77. *
  78. * let searchParams = new URLSearchParams([
  79. * ['sort', 'name'],
  80. * ['sort', 'price']
  81. * ]);
  82. *
  83. * you can do:
  84. *
  85. * let searchParams = createSearchParams({
  86. * sort: ['name', 'price']
  87. * });
  88. */
  89. function createSearchParams(init) {
  90. if (init === void 0) {
  91. init = "";
  92. }
  93. return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
  94. let value = init[key];
  95. return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]);
  96. }, []));
  97. }
  98. function getSearchParamsForLocation(locationSearch, defaultSearchParams) {
  99. let searchParams = createSearchParams(locationSearch);
  100. if (defaultSearchParams) {
  101. // Use `defaultSearchParams.forEach(...)` here instead of iterating of
  102. // `defaultSearchParams.keys()` to work-around a bug in Firefox related to
  103. // web extensions. Relevant Bugzilla tickets:
  104. // https://bugzilla.mozilla.org/show_bug.cgi?id=1414602
  105. // https://bugzilla.mozilla.org/show_bug.cgi?id=1023984
  106. defaultSearchParams.forEach((_, key) => {
  107. if (!searchParams.has(key)) {
  108. defaultSearchParams.getAll(key).forEach(value => {
  109. searchParams.append(key, value);
  110. });
  111. }
  112. });
  113. }
  114. return searchParams;
  115. }
  116. // One-time check for submitter support
  117. let _formDataSupportsSubmitter = null;
  118. function isFormDataSubmitterSupported() {
  119. if (_formDataSupportsSubmitter === null) {
  120. try {
  121. new FormData(document.createElement("form"),
  122. // @ts-expect-error if FormData supports the submitter parameter, this will throw
  123. 0);
  124. _formDataSupportsSubmitter = false;
  125. } catch (e) {
  126. _formDataSupportsSubmitter = true;
  127. }
  128. }
  129. return _formDataSupportsSubmitter;
  130. }
  131. const supportedFormEncTypes = new Set(["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"]);
  132. function getFormEncType(encType) {
  133. if (encType != null && !supportedFormEncTypes.has(encType)) {
  134. process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "\"" + encType + "\" is not a valid `encType` for `<Form>`/`<fetcher.Form>` " + ("and will default to \"" + defaultEncType + "\"")) : void 0;
  135. return null;
  136. }
  137. return encType;
  138. }
  139. function getFormSubmissionInfo(target, basename) {
  140. let method;
  141. let action;
  142. let encType;
  143. let formData;
  144. let body;
  145. if (isFormElement(target)) {
  146. // When grabbing the action from the element, it will have had the basename
  147. // prefixed to ensure non-JS scenarios work, so strip it since we'll
  148. // re-prefix in the router
  149. let attr = target.getAttribute("action");
  150. action = attr ? stripBasename(attr, basename) : null;
  151. method = target.getAttribute("method") || defaultMethod;
  152. encType = getFormEncType(target.getAttribute("enctype")) || defaultEncType;
  153. formData = new FormData(target);
  154. } else if (isButtonElement(target) || isInputElement(target) && (target.type === "submit" || target.type === "image")) {
  155. let form = target.form;
  156. if (form == null) {
  157. throw new Error("Cannot submit a <button> or <input type=\"submit\"> without a <form>");
  158. }
  159. // <button>/<input type="submit"> may override attributes of <form>
  160. // When grabbing the action from the element, it will have had the basename
  161. // prefixed to ensure non-JS scenarios work, so strip it since we'll
  162. // re-prefix in the router
  163. let attr = target.getAttribute("formaction") || form.getAttribute("action");
  164. action = attr ? stripBasename(attr, basename) : null;
  165. method = target.getAttribute("formmethod") || form.getAttribute("method") || defaultMethod;
  166. encType = getFormEncType(target.getAttribute("formenctype")) || getFormEncType(form.getAttribute("enctype")) || defaultEncType;
  167. // Build a FormData object populated from a form and submitter
  168. formData = new FormData(form, target);
  169. // If this browser doesn't support the `FormData(el, submitter)` format,
  170. // then tack on the submitter value at the end. This is a lightweight
  171. // solution that is not 100% spec compliant. For complete support in older
  172. // browsers, consider using the `formdata-submitter-polyfill` package
  173. if (!isFormDataSubmitterSupported()) {
  174. let {
  175. name,
  176. type,
  177. value
  178. } = target;
  179. if (type === "image") {
  180. let prefix = name ? name + "." : "";
  181. formData.append(prefix + "x", "0");
  182. formData.append(prefix + "y", "0");
  183. } else if (name) {
  184. formData.append(name, value);
  185. }
  186. }
  187. } else if (isHtmlElement(target)) {
  188. throw new Error("Cannot submit element that is not <form>, <button>, or " + "<input type=\"submit|image\">");
  189. } else {
  190. method = defaultMethod;
  191. action = null;
  192. encType = defaultEncType;
  193. body = target;
  194. }
  195. // Send body for <Form encType="text/plain" so we encode it into text
  196. if (formData && encType === "text/plain") {
  197. body = formData;
  198. formData = undefined;
  199. }
  200. return {
  201. action,
  202. method: method.toLowerCase(),
  203. encType,
  204. formData,
  205. body
  206. };
  207. }
  208. const _excluded = ["onClick", "relative", "reloadDocument", "replace", "state", "target", "to", "preventScrollReset", "viewTransition"],
  209. _excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to", "viewTransition", "children"],
  210. _excluded3 = ["fetcherKey", "navigate", "reloadDocument", "replace", "state", "method", "action", "onSubmit", "relative", "preventScrollReset", "viewTransition"];
  211. // HEY YOU! DON'T TOUCH THIS VARIABLE!
  212. //
  213. // It is replaced with the proper version at build time via a babel plugin in
  214. // the rollup config.
  215. //
  216. // Export a global property onto the window for React Router detection by the
  217. // Core Web Vitals Technology Report. This way they can configure the `wappalyzer`
  218. // to detect and properly classify live websites as being built with React Router:
  219. // https://github.com/HTTPArchive/wappalyzer/blob/main/src/technologies/r.json
  220. const REACT_ROUTER_VERSION = "6";
  221. try {
  222. window.__reactRouterVersion = REACT_ROUTER_VERSION;
  223. } catch (e) {
  224. // no-op
  225. }
  226. function createBrowserRouter(routes, opts) {
  227. return createRouter({
  228. basename: opts == null ? void 0 : opts.basename,
  229. future: _extends({}, opts == null ? void 0 : opts.future, {
  230. v7_prependBasename: true
  231. }),
  232. history: createBrowserHistory({
  233. window: opts == null ? void 0 : opts.window
  234. }),
  235. hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
  236. routes,
  237. mapRouteProperties: UNSAFE_mapRouteProperties,
  238. dataStrategy: opts == null ? void 0 : opts.dataStrategy,
  239. patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation,
  240. window: opts == null ? void 0 : opts.window
  241. }).initialize();
  242. }
  243. function createHashRouter(routes, opts) {
  244. return createRouter({
  245. basename: opts == null ? void 0 : opts.basename,
  246. future: _extends({}, opts == null ? void 0 : opts.future, {
  247. v7_prependBasename: true
  248. }),
  249. history: createHashHistory({
  250. window: opts == null ? void 0 : opts.window
  251. }),
  252. hydrationData: (opts == null ? void 0 : opts.hydrationData) || parseHydrationData(),
  253. routes,
  254. mapRouteProperties: UNSAFE_mapRouteProperties,
  255. dataStrategy: opts == null ? void 0 : opts.dataStrategy,
  256. patchRoutesOnNavigation: opts == null ? void 0 : opts.patchRoutesOnNavigation,
  257. window: opts == null ? void 0 : opts.window
  258. }).initialize();
  259. }
  260. function parseHydrationData() {
  261. var _window;
  262. let state = (_window = window) == null ? void 0 : _window.__staticRouterHydrationData;
  263. if (state && state.errors) {
  264. state = _extends({}, state, {
  265. errors: deserializeErrors(state.errors)
  266. });
  267. }
  268. return state;
  269. }
  270. function deserializeErrors(errors) {
  271. if (!errors) return null;
  272. let entries = Object.entries(errors);
  273. let serialized = {};
  274. for (let [key, val] of entries) {
  275. // Hey you! If you change this, please change the corresponding logic in
  276. // serializeErrors in react-router-dom/server.tsx :)
  277. if (val && val.__type === "RouteErrorResponse") {
  278. serialized[key] = new UNSAFE_ErrorResponseImpl(val.status, val.statusText, val.data, val.internal === true);
  279. } else if (val && val.__type === "Error") {
  280. // Attempt to reconstruct the right type of Error (i.e., ReferenceError)
  281. if (val.__subType) {
  282. let ErrorConstructor = window[val.__subType];
  283. if (typeof ErrorConstructor === "function") {
  284. try {
  285. // @ts-expect-error
  286. let error = new ErrorConstructor(val.message);
  287. // Wipe away the client-side stack trace. Nothing to fill it in with
  288. // because we don't serialize SSR stack traces for security reasons
  289. error.stack = "";
  290. serialized[key] = error;
  291. } catch (e) {
  292. // no-op - fall through and create a normal Error
  293. }
  294. }
  295. }
  296. if (serialized[key] == null) {
  297. let error = new Error(val.message);
  298. // Wipe away the client-side stack trace. Nothing to fill it in with
  299. // because we don't serialize SSR stack traces for security reasons
  300. error.stack = "";
  301. serialized[key] = error;
  302. }
  303. } else {
  304. serialized[key] = val;
  305. }
  306. }
  307. return serialized;
  308. }
  309. const ViewTransitionContext = /*#__PURE__*/React.createContext({
  310. isTransitioning: false
  311. });
  312. if (process.env.NODE_ENV !== "production") {
  313. ViewTransitionContext.displayName = "ViewTransition";
  314. }
  315. const FetchersContext = /*#__PURE__*/React.createContext(new Map());
  316. if (process.env.NODE_ENV !== "production") {
  317. FetchersContext.displayName = "Fetchers";
  318. }
  319. //#endregion
  320. ////////////////////////////////////////////////////////////////////////////////
  321. //#region Components
  322. ////////////////////////////////////////////////////////////////////////////////
  323. /**
  324. Webpack + React 17 fails to compile on any of the following because webpack
  325. complains that `startTransition` doesn't exist in `React`:
  326. * import { startTransition } from "react"
  327. * import * as React from from "react";
  328. "startTransition" in React ? React.startTransition(() => setState()) : setState()
  329. * import * as React from from "react";
  330. "startTransition" in React ? React["startTransition"](() => setState()) : setState()
  331. Moving it to a constant such as the following solves the Webpack/React 17 issue:
  332. * import * as React from from "react";
  333. const START_TRANSITION = "startTransition";
  334. START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()
  335. However, that introduces webpack/terser minification issues in production builds
  336. in React 18 where minification/obfuscation ends up removing the call of
  337. React.startTransition entirely from the first half of the ternary. Grabbing
  338. this exported reference once up front resolves that issue.
  339. See https://github.com/remix-run/react-router/issues/10579
  340. */
  341. const START_TRANSITION = "startTransition";
  342. const startTransitionImpl = React[START_TRANSITION];
  343. const FLUSH_SYNC = "flushSync";
  344. const flushSyncImpl = ReactDOM[FLUSH_SYNC];
  345. const USE_ID = "useId";
  346. const useIdImpl = React[USE_ID];
  347. function startTransitionSafe(cb) {
  348. if (startTransitionImpl) {
  349. startTransitionImpl(cb);
  350. } else {
  351. cb();
  352. }
  353. }
  354. function flushSyncSafe(cb) {
  355. if (flushSyncImpl) {
  356. flushSyncImpl(cb);
  357. } else {
  358. cb();
  359. }
  360. }
  361. class Deferred {
  362. constructor() {
  363. this.status = "pending";
  364. this.promise = new Promise((resolve, reject) => {
  365. this.resolve = value => {
  366. if (this.status === "pending") {
  367. this.status = "resolved";
  368. resolve(value);
  369. }
  370. };
  371. this.reject = reason => {
  372. if (this.status === "pending") {
  373. this.status = "rejected";
  374. reject(reason);
  375. }
  376. };
  377. });
  378. }
  379. }
  380. /**
  381. * Given a Remix Router instance, render the appropriate UI
  382. */
  383. function RouterProvider(_ref) {
  384. let {
  385. fallbackElement,
  386. router,
  387. future
  388. } = _ref;
  389. let [state, setStateImpl] = React.useState(router.state);
  390. let [pendingState, setPendingState] = React.useState();
  391. let [vtContext, setVtContext] = React.useState({
  392. isTransitioning: false
  393. });
  394. let [renderDfd, setRenderDfd] = React.useState();
  395. let [transition, setTransition] = React.useState();
  396. let [interruption, setInterruption] = React.useState();
  397. let fetcherData = React.useRef(new Map());
  398. let {
  399. v7_startTransition
  400. } = future || {};
  401. let optInStartTransition = React.useCallback(cb => {
  402. if (v7_startTransition) {
  403. startTransitionSafe(cb);
  404. } else {
  405. cb();
  406. }
  407. }, [v7_startTransition]);
  408. let setState = React.useCallback((newState, _ref2) => {
  409. let {
  410. deletedFetchers,
  411. flushSync: flushSync,
  412. viewTransitionOpts: viewTransitionOpts
  413. } = _ref2;
  414. newState.fetchers.forEach((fetcher, key) => {
  415. if (fetcher.data !== undefined) {
  416. fetcherData.current.set(key, fetcher.data);
  417. }
  418. });
  419. deletedFetchers.forEach(key => fetcherData.current.delete(key));
  420. let isViewTransitionUnavailable = router.window == null || router.window.document == null || typeof router.window.document.startViewTransition !== "function";
  421. // If this isn't a view transition or it's not available in this browser,
  422. // just update and be done with it
  423. if (!viewTransitionOpts || isViewTransitionUnavailable) {
  424. if (flushSync) {
  425. flushSyncSafe(() => setStateImpl(newState));
  426. } else {
  427. optInStartTransition(() => setStateImpl(newState));
  428. }
  429. return;
  430. }
  431. // flushSync + startViewTransition
  432. if (flushSync) {
  433. // Flush through the context to mark DOM elements as transition=ing
  434. flushSyncSafe(() => {
  435. // Cancel any pending transitions
  436. if (transition) {
  437. renderDfd && renderDfd.resolve();
  438. transition.skipTransition();
  439. }
  440. setVtContext({
  441. isTransitioning: true,
  442. flushSync: true,
  443. currentLocation: viewTransitionOpts.currentLocation,
  444. nextLocation: viewTransitionOpts.nextLocation
  445. });
  446. });
  447. // Update the DOM
  448. let t = router.window.document.startViewTransition(() => {
  449. flushSyncSafe(() => setStateImpl(newState));
  450. });
  451. // Clean up after the animation completes
  452. t.finished.finally(() => {
  453. flushSyncSafe(() => {
  454. setRenderDfd(undefined);
  455. setTransition(undefined);
  456. setPendingState(undefined);
  457. setVtContext({
  458. isTransitioning: false
  459. });
  460. });
  461. });
  462. flushSyncSafe(() => setTransition(t));
  463. return;
  464. }
  465. // startTransition + startViewTransition
  466. if (transition) {
  467. // Interrupting an in-progress transition, cancel and let everything flush
  468. // out, and then kick off a new transition from the interruption state
  469. renderDfd && renderDfd.resolve();
  470. transition.skipTransition();
  471. setInterruption({
  472. state: newState,
  473. currentLocation: viewTransitionOpts.currentLocation,
  474. nextLocation: viewTransitionOpts.nextLocation
  475. });
  476. } else {
  477. // Completed navigation update with opted-in view transitions, let 'er rip
  478. setPendingState(newState);
  479. setVtContext({
  480. isTransitioning: true,
  481. flushSync: false,
  482. currentLocation: viewTransitionOpts.currentLocation,
  483. nextLocation: viewTransitionOpts.nextLocation
  484. });
  485. }
  486. }, [router.window, transition, renderDfd, fetcherData, optInStartTransition]);
  487. // Need to use a layout effect here so we are subscribed early enough to
  488. // pick up on any render-driven redirects/navigations (useEffect/<Navigate>)
  489. React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);
  490. // When we start a view transition, create a Deferred we can use for the
  491. // eventual "completed" render
  492. React.useEffect(() => {
  493. if (vtContext.isTransitioning && !vtContext.flushSync) {
  494. setRenderDfd(new Deferred());
  495. }
  496. }, [vtContext]);
  497. // Once the deferred is created, kick off startViewTransition() to update the
  498. // DOM and then wait on the Deferred to resolve (indicating the DOM update has
  499. // happened)
  500. React.useEffect(() => {
  501. if (renderDfd && pendingState && router.window) {
  502. let newState = pendingState;
  503. let renderPromise = renderDfd.promise;
  504. let transition = router.window.document.startViewTransition(async () => {
  505. optInStartTransition(() => setStateImpl(newState));
  506. await renderPromise;
  507. });
  508. transition.finished.finally(() => {
  509. setRenderDfd(undefined);
  510. setTransition(undefined);
  511. setPendingState(undefined);
  512. setVtContext({
  513. isTransitioning: false
  514. });
  515. });
  516. setTransition(transition);
  517. }
  518. }, [optInStartTransition, pendingState, renderDfd, router.window]);
  519. // When the new location finally renders and is committed to the DOM, this
  520. // effect will run to resolve the transition
  521. React.useEffect(() => {
  522. if (renderDfd && pendingState && state.location.key === pendingState.location.key) {
  523. renderDfd.resolve();
  524. }
  525. }, [renderDfd, transition, state.location, pendingState]);
  526. // If we get interrupted with a new navigation during a transition, we skip
  527. // the active transition, let it cleanup, then kick it off again here
  528. React.useEffect(() => {
  529. if (!vtContext.isTransitioning && interruption) {
  530. setPendingState(interruption.state);
  531. setVtContext({
  532. isTransitioning: true,
  533. flushSync: false,
  534. currentLocation: interruption.currentLocation,
  535. nextLocation: interruption.nextLocation
  536. });
  537. setInterruption(undefined);
  538. }
  539. }, [vtContext.isTransitioning, interruption]);
  540. React.useEffect(() => {
  541. process.env.NODE_ENV !== "production" ? UNSAFE_warning(fallbackElement == null || !router.future.v7_partialHydration, "`<RouterProvider fallbackElement>` is deprecated when using " + "`v7_partialHydration`, use a `HydrateFallback` component instead") : void 0;
  542. // Only log this once on initial mount
  543. // eslint-disable-next-line react-hooks/exhaustive-deps
  544. }, []);
  545. let navigator = React.useMemo(() => {
  546. return {
  547. createHref: router.createHref,
  548. encodeLocation: router.encodeLocation,
  549. go: n => router.navigate(n),
  550. push: (to, state, opts) => router.navigate(to, {
  551. state,
  552. preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
  553. }),
  554. replace: (to, state, opts) => router.navigate(to, {
  555. replace: true,
  556. state,
  557. preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
  558. })
  559. };
  560. }, [router]);
  561. let basename = router.basename || "/";
  562. let dataRouterContext = React.useMemo(() => ({
  563. router,
  564. navigator,
  565. static: false,
  566. basename
  567. }), [router, navigator, basename]);
  568. let routerFuture = React.useMemo(() => ({
  569. v7_relativeSplatPath: router.future.v7_relativeSplatPath
  570. }), [router.future.v7_relativeSplatPath]);
  571. React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future, router.future), [future, router.future]);
  572. // The fragment and {null} here are important! We need them to keep React 18's
  573. // useId happy when we are server-rendering since we may have a <script> here
  574. // containing the hydrated server-side staticContext (from StaticRouterProvider).
  575. // useId relies on the component tree structure to generate deterministic id's
  576. // so we need to ensure it remains the same on the client even though
  577. // we don't need the <script> tag
  578. return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(UNSAFE_DataRouterContext.Provider, {
  579. value: dataRouterContext
  580. }, /*#__PURE__*/React.createElement(UNSAFE_DataRouterStateContext.Provider, {
  581. value: state
  582. }, /*#__PURE__*/React.createElement(FetchersContext.Provider, {
  583. value: fetcherData.current
  584. }, /*#__PURE__*/React.createElement(ViewTransitionContext.Provider, {
  585. value: vtContext
  586. }, /*#__PURE__*/React.createElement(Router, {
  587. basename: basename,
  588. location: state.location,
  589. navigationType: state.historyAction,
  590. navigator: navigator,
  591. future: routerFuture
  592. }, state.initialized || router.future.v7_partialHydration ? /*#__PURE__*/React.createElement(MemoizedDataRoutes, {
  593. routes: router.routes,
  594. future: router.future,
  595. state: state
  596. }) : fallbackElement))))), null);
  597. }
  598. // Memoize to avoid re-renders when updating `ViewTransitionContext`
  599. const MemoizedDataRoutes = /*#__PURE__*/React.memo(DataRoutes);
  600. function DataRoutes(_ref3) {
  601. let {
  602. routes,
  603. future,
  604. state
  605. } = _ref3;
  606. return UNSAFE_useRoutesImpl(routes, undefined, state, future);
  607. }
  608. /**
  609. * A `<Router>` for use in web browsers. Provides the cleanest URLs.
  610. */
  611. function BrowserRouter(_ref4) {
  612. let {
  613. basename,
  614. children,
  615. future,
  616. window
  617. } = _ref4;
  618. let historyRef = React.useRef();
  619. if (historyRef.current == null) {
  620. historyRef.current = createBrowserHistory({
  621. window,
  622. v5Compat: true
  623. });
  624. }
  625. let history = historyRef.current;
  626. let [state, setStateImpl] = React.useState({
  627. action: history.action,
  628. location: history.location
  629. });
  630. let {
  631. v7_startTransition
  632. } = future || {};
  633. let setState = React.useCallback(newState => {
  634. v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  635. }, [setStateImpl, v7_startTransition]);
  636. React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  637. React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future), [future]);
  638. return /*#__PURE__*/React.createElement(Router, {
  639. basename: basename,
  640. children: children,
  641. location: state.location,
  642. navigationType: state.action,
  643. navigator: history,
  644. future: future
  645. });
  646. }
  647. /**
  648. * A `<Router>` for use in web browsers. Stores the location in the hash
  649. * portion of the URL so it is not sent to the server.
  650. */
  651. function HashRouter(_ref5) {
  652. let {
  653. basename,
  654. children,
  655. future,
  656. window
  657. } = _ref5;
  658. let historyRef = React.useRef();
  659. if (historyRef.current == null) {
  660. historyRef.current = createHashHistory({
  661. window,
  662. v5Compat: true
  663. });
  664. }
  665. let history = historyRef.current;
  666. let [state, setStateImpl] = React.useState({
  667. action: history.action,
  668. location: history.location
  669. });
  670. let {
  671. v7_startTransition
  672. } = future || {};
  673. let setState = React.useCallback(newState => {
  674. v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  675. }, [setStateImpl, v7_startTransition]);
  676. React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  677. React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future), [future]);
  678. return /*#__PURE__*/React.createElement(Router, {
  679. basename: basename,
  680. children: children,
  681. location: state.location,
  682. navigationType: state.action,
  683. navigator: history,
  684. future: future
  685. });
  686. }
  687. /**
  688. * A `<Router>` that accepts a pre-instantiated history object. It's important
  689. * to note that using your own history object is highly discouraged and may add
  690. * two versions of the history library to your bundles unless you use the same
  691. * version of the history library that React Router uses internally.
  692. */
  693. function HistoryRouter(_ref6) {
  694. let {
  695. basename,
  696. children,
  697. future,
  698. history
  699. } = _ref6;
  700. let [state, setStateImpl] = React.useState({
  701. action: history.action,
  702. location: history.location
  703. });
  704. let {
  705. v7_startTransition
  706. } = future || {};
  707. let setState = React.useCallback(newState => {
  708. v7_startTransition && startTransitionImpl ? startTransitionImpl(() => setStateImpl(newState)) : setStateImpl(newState);
  709. }, [setStateImpl, v7_startTransition]);
  710. React.useLayoutEffect(() => history.listen(setState), [history, setState]);
  711. React.useEffect(() => UNSAFE_logV6DeprecationWarnings(future), [future]);
  712. return /*#__PURE__*/React.createElement(Router, {
  713. basename: basename,
  714. children: children,
  715. location: state.location,
  716. navigationType: state.action,
  717. navigator: history,
  718. future: future
  719. });
  720. }
  721. if (process.env.NODE_ENV !== "production") {
  722. HistoryRouter.displayName = "unstable_HistoryRouter";
  723. }
  724. const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
  725. const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
  726. /**
  727. * The public API for rendering a history-aware `<a>`.
  728. */
  729. const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef(_ref7, ref) {
  730. let {
  731. onClick,
  732. relative,
  733. reloadDocument,
  734. replace,
  735. state,
  736. target,
  737. to,
  738. preventScrollReset,
  739. viewTransition
  740. } = _ref7,
  741. rest = _objectWithoutPropertiesLoose(_ref7, _excluded);
  742. let {
  743. basename
  744. } = React.useContext(UNSAFE_NavigationContext);
  745. // Rendered into <a href> for absolute URLs
  746. let absoluteHref;
  747. let isExternal = false;
  748. if (typeof to === "string" && ABSOLUTE_URL_REGEX.test(to)) {
  749. // Render the absolute href server- and client-side
  750. absoluteHref = to;
  751. // Only check for external origins client-side
  752. if (isBrowser) {
  753. try {
  754. let currentUrl = new URL(window.location.href);
  755. let targetUrl = to.startsWith("//") ? new URL(currentUrl.protocol + to) : new URL(to);
  756. let path = stripBasename(targetUrl.pathname, basename);
  757. if (targetUrl.origin === currentUrl.origin && path != null) {
  758. // Strip the protocol/origin/basename for same-origin absolute URLs
  759. to = path + targetUrl.search + targetUrl.hash;
  760. } else {
  761. isExternal = true;
  762. }
  763. } catch (e) {
  764. // We can't do external URL detection without a valid URL
  765. process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "<Link to=\"" + to + "\"> contains an invalid URL which will probably break " + "when clicked - please update to a valid URL path.") : void 0;
  766. }
  767. }
  768. }
  769. // Rendered into <a href> for relative URLs
  770. let href = useHref(to, {
  771. relative
  772. });
  773. let internalOnClick = useLinkClickHandler(to, {
  774. replace,
  775. state,
  776. target,
  777. preventScrollReset,
  778. relative,
  779. viewTransition
  780. });
  781. function handleClick(event) {
  782. if (onClick) onClick(event);
  783. if (!event.defaultPrevented) {
  784. internalOnClick(event);
  785. }
  786. }
  787. return (
  788. /*#__PURE__*/
  789. // eslint-disable-next-line jsx-a11y/anchor-has-content
  790. React.createElement("a", _extends({}, rest, {
  791. href: absoluteHref || href,
  792. onClick: isExternal || reloadDocument ? onClick : handleClick,
  793. ref: ref,
  794. target: target
  795. }))
  796. );
  797. });
  798. if (process.env.NODE_ENV !== "production") {
  799. Link.displayName = "Link";
  800. }
  801. /**
  802. * A `<Link>` wrapper that knows if it's "active" or not.
  803. */
  804. const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef(_ref8, ref) {
  805. let {
  806. "aria-current": ariaCurrentProp = "page",
  807. caseSensitive = false,
  808. className: classNameProp = "",
  809. end = false,
  810. style: styleProp,
  811. to,
  812. viewTransition,
  813. children
  814. } = _ref8,
  815. rest = _objectWithoutPropertiesLoose(_ref8, _excluded2);
  816. let path = useResolvedPath(to, {
  817. relative: rest.relative
  818. });
  819. let location = useLocation();
  820. let routerState = React.useContext(UNSAFE_DataRouterStateContext);
  821. let {
  822. navigator,
  823. basename
  824. } = React.useContext(UNSAFE_NavigationContext);
  825. let isTransitioning = routerState != null &&
  826. // Conditional usage is OK here because the usage of a data router is static
  827. // eslint-disable-next-line react-hooks/rules-of-hooks
  828. useViewTransitionState(path) && viewTransition === true;
  829. let toPathname = navigator.encodeLocation ? navigator.encodeLocation(path).pathname : path.pathname;
  830. let locationPathname = location.pathname;
  831. let nextLocationPathname = routerState && routerState.navigation && routerState.navigation.location ? routerState.navigation.location.pathname : null;
  832. if (!caseSensitive) {
  833. locationPathname = locationPathname.toLowerCase();
  834. nextLocationPathname = nextLocationPathname ? nextLocationPathname.toLowerCase() : null;
  835. toPathname = toPathname.toLowerCase();
  836. }
  837. if (nextLocationPathname && basename) {
  838. nextLocationPathname = stripBasename(nextLocationPathname, basename) || nextLocationPathname;
  839. }
  840. // If the `to` has a trailing slash, look at that exact spot. Otherwise,
  841. // we're looking for a slash _after_ what's in `to`. For example:
  842. //
  843. // <NavLink to="/users"> and <NavLink to="/users/">
  844. // both want to look for a / at index 6 to match URL `/users/matt`
  845. const endSlashPosition = toPathname !== "/" && toPathname.endsWith("/") ? toPathname.length - 1 : toPathname.length;
  846. let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(endSlashPosition) === "/";
  847. let isPending = nextLocationPathname != null && (nextLocationPathname === toPathname || !end && nextLocationPathname.startsWith(toPathname) && nextLocationPathname.charAt(toPathname.length) === "/");
  848. let renderProps = {
  849. isActive,
  850. isPending,
  851. isTransitioning
  852. };
  853. let ariaCurrent = isActive ? ariaCurrentProp : undefined;
  854. let className;
  855. if (typeof classNameProp === "function") {
  856. className = classNameProp(renderProps);
  857. } else {
  858. // If the className prop is not a function, we use a default `active`
  859. // class for <NavLink />s that are active. In v5 `active` was the default
  860. // value for `activeClassName`, but we are removing that API and can still
  861. // use the old default behavior for a cleaner upgrade path and keep the
  862. // simple styling rules working as they currently do.
  863. className = [classNameProp, isActive ? "active" : null, isPending ? "pending" : null, isTransitioning ? "transitioning" : null].filter(Boolean).join(" ");
  864. }
  865. let style = typeof styleProp === "function" ? styleProp(renderProps) : styleProp;
  866. return /*#__PURE__*/React.createElement(Link, _extends({}, rest, {
  867. "aria-current": ariaCurrent,
  868. className: className,
  869. ref: ref,
  870. style: style,
  871. to: to,
  872. viewTransition: viewTransition
  873. }), typeof children === "function" ? children(renderProps) : children);
  874. });
  875. if (process.env.NODE_ENV !== "production") {
  876. NavLink.displayName = "NavLink";
  877. }
  878. /**
  879. * A `@remix-run/router`-aware `<form>`. It behaves like a normal form except
  880. * that the interaction with the server is with `fetch` instead of new document
  881. * requests, allowing components to add nicer UX to the page as the form is
  882. * submitted and returns with data.
  883. */
  884. const Form = /*#__PURE__*/React.forwardRef((_ref9, forwardedRef) => {
  885. let {
  886. fetcherKey,
  887. navigate,
  888. reloadDocument,
  889. replace,
  890. state,
  891. method = defaultMethod,
  892. action,
  893. onSubmit,
  894. relative,
  895. preventScrollReset,
  896. viewTransition
  897. } = _ref9,
  898. props = _objectWithoutPropertiesLoose(_ref9, _excluded3);
  899. let submit = useSubmit();
  900. let formAction = useFormAction(action, {
  901. relative
  902. });
  903. let formMethod = method.toLowerCase() === "get" ? "get" : "post";
  904. let submitHandler = event => {
  905. onSubmit && onSubmit(event);
  906. if (event.defaultPrevented) return;
  907. event.preventDefault();
  908. let submitter = event.nativeEvent.submitter;
  909. let submitMethod = (submitter == null ? void 0 : submitter.getAttribute("formmethod")) || method;
  910. submit(submitter || event.currentTarget, {
  911. fetcherKey,
  912. method: submitMethod,
  913. navigate,
  914. replace,
  915. state,
  916. relative,
  917. preventScrollReset,
  918. viewTransition
  919. });
  920. };
  921. return /*#__PURE__*/React.createElement("form", _extends({
  922. ref: forwardedRef,
  923. method: formMethod,
  924. action: formAction,
  925. onSubmit: reloadDocument ? onSubmit : submitHandler
  926. }, props));
  927. });
  928. if (process.env.NODE_ENV !== "production") {
  929. Form.displayName = "Form";
  930. }
  931. /**
  932. * This component will emulate the browser's scroll restoration on location
  933. * changes.
  934. */
  935. function ScrollRestoration(_ref10) {
  936. let {
  937. getKey,
  938. storageKey
  939. } = _ref10;
  940. useScrollRestoration({
  941. getKey,
  942. storageKey
  943. });
  944. return null;
  945. }
  946. if (process.env.NODE_ENV !== "production") {
  947. ScrollRestoration.displayName = "ScrollRestoration";
  948. }
  949. //#endregion
  950. ////////////////////////////////////////////////////////////////////////////////
  951. //#region Hooks
  952. ////////////////////////////////////////////////////////////////////////////////
  953. var DataRouterHook;
  954. (function (DataRouterHook) {
  955. DataRouterHook["UseScrollRestoration"] = "useScrollRestoration";
  956. DataRouterHook["UseSubmit"] = "useSubmit";
  957. DataRouterHook["UseSubmitFetcher"] = "useSubmitFetcher";
  958. DataRouterHook["UseFetcher"] = "useFetcher";
  959. DataRouterHook["useViewTransitionState"] = "useViewTransitionState";
  960. })(DataRouterHook || (DataRouterHook = {}));
  961. var DataRouterStateHook;
  962. (function (DataRouterStateHook) {
  963. DataRouterStateHook["UseFetcher"] = "useFetcher";
  964. DataRouterStateHook["UseFetchers"] = "useFetchers";
  965. DataRouterStateHook["UseScrollRestoration"] = "useScrollRestoration";
  966. })(DataRouterStateHook || (DataRouterStateHook = {}));
  967. // Internal hooks
  968. function getDataRouterConsoleError(hookName) {
  969. return hookName + " must be used within a data router. See https://reactrouter.com/v6/routers/picking-a-router.";
  970. }
  971. function useDataRouterContext(hookName) {
  972. let ctx = React.useContext(UNSAFE_DataRouterContext);
  973. !ctx ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;
  974. return ctx;
  975. }
  976. function useDataRouterState(hookName) {
  977. let state = React.useContext(UNSAFE_DataRouterStateContext);
  978. !state ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;
  979. return state;
  980. }
  981. // External hooks
  982. /**
  983. * Handles the click behavior for router `<Link>` components. This is useful if
  984. * you need to create custom `<Link>` components with the same click behavior we
  985. * use in our exported `<Link>`.
  986. */
  987. function useLinkClickHandler(to, _temp) {
  988. let {
  989. target,
  990. replace: replaceProp,
  991. state,
  992. preventScrollReset,
  993. relative,
  994. viewTransition
  995. } = _temp === void 0 ? {} : _temp;
  996. let navigate = useNavigate();
  997. let location = useLocation();
  998. let path = useResolvedPath(to, {
  999. relative
  1000. });
  1001. return React.useCallback(event => {
  1002. if (shouldProcessLinkClick(event, target)) {
  1003. event.preventDefault();
  1004. // If the URL hasn't changed, a regular <a> will do a replace instead of
  1005. // a push, so do the same here unless the replace prop is explicitly set
  1006. let replace = replaceProp !== undefined ? replaceProp : createPath(location) === createPath(path);
  1007. navigate(to, {
  1008. replace,
  1009. state,
  1010. preventScrollReset,
  1011. relative,
  1012. viewTransition
  1013. });
  1014. }
  1015. }, [location, navigate, path, replaceProp, state, target, to, preventScrollReset, relative, viewTransition]);
  1016. }
  1017. /**
  1018. * A convenient wrapper for reading and writing search parameters via the
  1019. * URLSearchParams interface.
  1020. */
  1021. function useSearchParams(defaultInit) {
  1022. process.env.NODE_ENV !== "production" ? UNSAFE_warning(typeof URLSearchParams !== "undefined", "You cannot use the `useSearchParams` hook in a browser that does not " + "support the URLSearchParams API. If you need to support Internet " + "Explorer 11, we recommend you load a polyfill such as " + "https://github.com/ungap/url-search-params.") : void 0;
  1023. let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));
  1024. let hasSetSearchParamsRef = React.useRef(false);
  1025. let location = useLocation();
  1026. let searchParams = React.useMemo(() =>
  1027. // Only merge in the defaults if we haven't yet called setSearchParams.
  1028. // Once we call that we want those to take precedence, otherwise you can't
  1029. // remove a param with setSearchParams({}) if it has an initial value
  1030. getSearchParamsForLocation(location.search, hasSetSearchParamsRef.current ? null : defaultSearchParamsRef.current), [location.search]);
  1031. let navigate = useNavigate();
  1032. let setSearchParams = React.useCallback((nextInit, navigateOptions) => {
  1033. const newSearchParams = createSearchParams(typeof nextInit === "function" ? nextInit(searchParams) : nextInit);
  1034. hasSetSearchParamsRef.current = true;
  1035. navigate("?" + newSearchParams, navigateOptions);
  1036. }, [navigate, searchParams]);
  1037. return [searchParams, setSearchParams];
  1038. }
  1039. function validateClientSideSubmission() {
  1040. if (typeof document === "undefined") {
  1041. throw new Error("You are calling submit during the server render. " + "Try calling submit within a `useEffect` or callback instead.");
  1042. }
  1043. }
  1044. let fetcherId = 0;
  1045. let getUniqueFetcherId = () => "__" + String(++fetcherId) + "__";
  1046. /**
  1047. * Returns a function that may be used to programmatically submit a form (or
  1048. * some arbitrary data) to the server.
  1049. */
  1050. function useSubmit() {
  1051. let {
  1052. router
  1053. } = useDataRouterContext(DataRouterHook.UseSubmit);
  1054. let {
  1055. basename
  1056. } = React.useContext(UNSAFE_NavigationContext);
  1057. let currentRouteId = UNSAFE_useRouteId();
  1058. return React.useCallback(function (target, options) {
  1059. if (options === void 0) {
  1060. options = {};
  1061. }
  1062. validateClientSideSubmission();
  1063. let {
  1064. action,
  1065. method,
  1066. encType,
  1067. formData,
  1068. body
  1069. } = getFormSubmissionInfo(target, basename);
  1070. if (options.navigate === false) {
  1071. let key = options.fetcherKey || getUniqueFetcherId();
  1072. router.fetch(key, currentRouteId, options.action || action, {
  1073. preventScrollReset: options.preventScrollReset,
  1074. formData,
  1075. body,
  1076. formMethod: options.method || method,
  1077. formEncType: options.encType || encType,
  1078. flushSync: options.flushSync
  1079. });
  1080. } else {
  1081. router.navigate(options.action || action, {
  1082. preventScrollReset: options.preventScrollReset,
  1083. formData,
  1084. body,
  1085. formMethod: options.method || method,
  1086. formEncType: options.encType || encType,
  1087. replace: options.replace,
  1088. state: options.state,
  1089. fromRouteId: currentRouteId,
  1090. flushSync: options.flushSync,
  1091. viewTransition: options.viewTransition
  1092. });
  1093. }
  1094. }, [router, basename, currentRouteId]);
  1095. }
  1096. // v7: Eventually we should deprecate this entirely in favor of using the
  1097. // router method directly?
  1098. function useFormAction(action, _temp2) {
  1099. let {
  1100. relative
  1101. } = _temp2 === void 0 ? {} : _temp2;
  1102. let {
  1103. basename
  1104. } = React.useContext(UNSAFE_NavigationContext);
  1105. let routeContext = React.useContext(UNSAFE_RouteContext);
  1106. !routeContext ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFormAction must be used inside a RouteContext") : UNSAFE_invariant(false) : void 0;
  1107. let [match] = routeContext.matches.slice(-1);
  1108. // Shallow clone path so we can modify it below, otherwise we modify the
  1109. // object referenced by useMemo inside useResolvedPath
  1110. let path = _extends({}, useResolvedPath(action ? action : ".", {
  1111. relative
  1112. }));
  1113. // If no action was specified, browsers will persist current search params
  1114. // when determining the path, so match that behavior
  1115. // https://github.com/remix-run/remix/issues/927
  1116. let location = useLocation();
  1117. if (action == null) {
  1118. // Safe to write to this directly here since if action was undefined, we
  1119. // would have called useResolvedPath(".") which will never include a search
  1120. path.search = location.search;
  1121. // When grabbing search params from the URL, remove any included ?index param
  1122. // since it might not apply to our contextual route. We add it back based
  1123. // on match.route.index below
  1124. let params = new URLSearchParams(path.search);
  1125. let indexValues = params.getAll("index");
  1126. let hasNakedIndexParam = indexValues.some(v => v === "");
  1127. if (hasNakedIndexParam) {
  1128. params.delete("index");
  1129. indexValues.filter(v => v).forEach(v => params.append("index", v));
  1130. let qs = params.toString();
  1131. path.search = qs ? "?" + qs : "";
  1132. }
  1133. }
  1134. if ((!action || action === ".") && match.route.index) {
  1135. path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
  1136. }
  1137. // If we're operating within a basename, prepend it to the pathname prior
  1138. // to creating the form action. If this is a root navigation, then just use
  1139. // the raw basename which allows the basename to have full control over the
  1140. // presence of a trailing slash on root actions
  1141. if (basename !== "/") {
  1142. path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
  1143. }
  1144. return createPath(path);
  1145. }
  1146. // TODO: (v7) Change the useFetcher generic default from `any` to `unknown`
  1147. /**
  1148. * Interacts with route loaders and actions without causing a navigation. Great
  1149. * for any interaction that stays on the same page.
  1150. */
  1151. function useFetcher(_temp3) {
  1152. var _route$matches;
  1153. let {
  1154. key
  1155. } = _temp3 === void 0 ? {} : _temp3;
  1156. let {
  1157. router
  1158. } = useDataRouterContext(DataRouterHook.UseFetcher);
  1159. let state = useDataRouterState(DataRouterStateHook.UseFetcher);
  1160. let fetcherData = React.useContext(FetchersContext);
  1161. let route = React.useContext(UNSAFE_RouteContext);
  1162. let routeId = (_route$matches = route.matches[route.matches.length - 1]) == null ? void 0 : _route$matches.route.id;
  1163. !fetcherData ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFetcher must be used inside a FetchersContext") : UNSAFE_invariant(false) : void 0;
  1164. !route ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFetcher must be used inside a RouteContext") : UNSAFE_invariant(false) : void 0;
  1165. !(routeId != null) ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "useFetcher can only be used on routes that contain a unique \"id\"") : UNSAFE_invariant(false) : void 0;
  1166. // Fetcher key handling
  1167. // OK to call conditionally to feature detect `useId`
  1168. // eslint-disable-next-line react-hooks/rules-of-hooks
  1169. let defaultKey = useIdImpl ? useIdImpl() : "";
  1170. let [fetcherKey, setFetcherKey] = React.useState(key || defaultKey);
  1171. if (key && key !== fetcherKey) {
  1172. setFetcherKey(key);
  1173. } else if (!fetcherKey) {
  1174. // We will only fall through here when `useId` is not available
  1175. setFetcherKey(getUniqueFetcherId());
  1176. }
  1177. // Registration/cleanup
  1178. React.useEffect(() => {
  1179. router.getFetcher(fetcherKey);
  1180. return () => {
  1181. // Tell the router we've unmounted - if v7_fetcherPersist is enabled this
  1182. // will not delete immediately but instead queue up a delete after the
  1183. // fetcher returns to an `idle` state
  1184. router.deleteFetcher(fetcherKey);
  1185. };
  1186. }, [router, fetcherKey]);
  1187. // Fetcher additions
  1188. let load = React.useCallback((href, opts) => {
  1189. !routeId ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "No routeId available for fetcher.load()") : UNSAFE_invariant(false) : void 0;
  1190. router.fetch(fetcherKey, routeId, href, opts);
  1191. }, [fetcherKey, routeId, router]);
  1192. let submitImpl = useSubmit();
  1193. let submit = React.useCallback((target, opts) => {
  1194. submitImpl(target, _extends({}, opts, {
  1195. navigate: false,
  1196. fetcherKey
  1197. }));
  1198. }, [fetcherKey, submitImpl]);
  1199. let FetcherForm = React.useMemo(() => {
  1200. let FetcherForm = /*#__PURE__*/React.forwardRef((props, ref) => {
  1201. return /*#__PURE__*/React.createElement(Form, _extends({}, props, {
  1202. navigate: false,
  1203. fetcherKey: fetcherKey,
  1204. ref: ref
  1205. }));
  1206. });
  1207. if (process.env.NODE_ENV !== "production") {
  1208. FetcherForm.displayName = "fetcher.Form";
  1209. }
  1210. return FetcherForm;
  1211. }, [fetcherKey]);
  1212. // Exposed FetcherWithComponents
  1213. let fetcher = state.fetchers.get(fetcherKey) || IDLE_FETCHER;
  1214. let data = fetcherData.get(fetcherKey);
  1215. let fetcherWithComponents = React.useMemo(() => _extends({
  1216. Form: FetcherForm,
  1217. submit,
  1218. load
  1219. }, fetcher, {
  1220. data
  1221. }), [FetcherForm, submit, load, fetcher, data]);
  1222. return fetcherWithComponents;
  1223. }
  1224. /**
  1225. * Provides all fetchers currently on the page. Useful for layouts and parent
  1226. * routes that need to provide pending/optimistic UI regarding the fetch.
  1227. */
  1228. function useFetchers() {
  1229. let state = useDataRouterState(DataRouterStateHook.UseFetchers);
  1230. return Array.from(state.fetchers.entries()).map(_ref11 => {
  1231. let [key, fetcher] = _ref11;
  1232. return _extends({}, fetcher, {
  1233. key
  1234. });
  1235. });
  1236. }
  1237. const SCROLL_RESTORATION_STORAGE_KEY = "react-router-scroll-positions";
  1238. let savedScrollPositions = {};
  1239. /**
  1240. * When rendered inside a RouterProvider, will restore scroll positions on navigations
  1241. */
  1242. function useScrollRestoration(_temp4) {
  1243. let {
  1244. getKey,
  1245. storageKey
  1246. } = _temp4 === void 0 ? {} : _temp4;
  1247. let {
  1248. router
  1249. } = useDataRouterContext(DataRouterHook.UseScrollRestoration);
  1250. let {
  1251. restoreScrollPosition,
  1252. preventScrollReset
  1253. } = useDataRouterState(DataRouterStateHook.UseScrollRestoration);
  1254. let {
  1255. basename
  1256. } = React.useContext(UNSAFE_NavigationContext);
  1257. let location = useLocation();
  1258. let matches = useMatches();
  1259. let navigation = useNavigation();
  1260. // Trigger manual scroll restoration while we're active
  1261. React.useEffect(() => {
  1262. window.history.scrollRestoration = "manual";
  1263. return () => {
  1264. window.history.scrollRestoration = "auto";
  1265. };
  1266. }, []);
  1267. // Save positions on pagehide
  1268. usePageHide(React.useCallback(() => {
  1269. if (navigation.state === "idle") {
  1270. let key = (getKey ? getKey(location, matches) : null) || location.key;
  1271. savedScrollPositions[key] = window.scrollY;
  1272. }
  1273. try {
  1274. sessionStorage.setItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY, JSON.stringify(savedScrollPositions));
  1275. } catch (error) {
  1276. process.env.NODE_ENV !== "production" ? UNSAFE_warning(false, "Failed to save scroll positions in sessionStorage, <ScrollRestoration /> will not work properly (" + error + ").") : void 0;
  1277. }
  1278. window.history.scrollRestoration = "auto";
  1279. }, [storageKey, getKey, navigation.state, location, matches]));
  1280. // Read in any saved scroll locations
  1281. if (typeof document !== "undefined") {
  1282. // eslint-disable-next-line react-hooks/rules-of-hooks
  1283. React.useLayoutEffect(() => {
  1284. try {
  1285. let sessionPositions = sessionStorage.getItem(storageKey || SCROLL_RESTORATION_STORAGE_KEY);
  1286. if (sessionPositions) {
  1287. savedScrollPositions = JSON.parse(sessionPositions);
  1288. }
  1289. } catch (e) {
  1290. // no-op, use default empty object
  1291. }
  1292. }, [storageKey]);
  1293. // Enable scroll restoration in the router
  1294. // eslint-disable-next-line react-hooks/rules-of-hooks
  1295. React.useLayoutEffect(() => {
  1296. let getKeyWithoutBasename = getKey && basename !== "/" ? (location, matches) => getKey( // Strip the basename to match useLocation()
  1297. _extends({}, location, {
  1298. pathname: stripBasename(location.pathname, basename) || location.pathname
  1299. }), matches) : getKey;
  1300. let disableScrollRestoration = router == null ? void 0 : router.enableScrollRestoration(savedScrollPositions, () => window.scrollY, getKeyWithoutBasename);
  1301. return () => disableScrollRestoration && disableScrollRestoration();
  1302. }, [router, basename, getKey]);
  1303. // Restore scrolling when state.restoreScrollPosition changes
  1304. // eslint-disable-next-line react-hooks/rules-of-hooks
  1305. React.useLayoutEffect(() => {
  1306. // Explicit false means don't do anything (used for submissions)
  1307. if (restoreScrollPosition === false) {
  1308. return;
  1309. }
  1310. // been here before, scroll to it
  1311. if (typeof restoreScrollPosition === "number") {
  1312. window.scrollTo(0, restoreScrollPosition);
  1313. return;
  1314. }
  1315. // try to scroll to the hash
  1316. if (location.hash) {
  1317. let el = document.getElementById(decodeURIComponent(location.hash.slice(1)));
  1318. if (el) {
  1319. el.scrollIntoView();
  1320. return;
  1321. }
  1322. }
  1323. // Don't reset if this navigation opted out
  1324. if (preventScrollReset === true) {
  1325. return;
  1326. }
  1327. // otherwise go to the top on new locations
  1328. window.scrollTo(0, 0);
  1329. }, [location, restoreScrollPosition, preventScrollReset]);
  1330. }
  1331. }
  1332. /**
  1333. * Setup a callback to be fired on the window's `beforeunload` event. This is
  1334. * useful for saving some data to `window.localStorage` just before the page
  1335. * refreshes.
  1336. *
  1337. * Note: The `callback` argument should be a function created with
  1338. * `React.useCallback()`.
  1339. */
  1340. function useBeforeUnload(callback, options) {
  1341. let {
  1342. capture
  1343. } = options || {};
  1344. React.useEffect(() => {
  1345. let opts = capture != null ? {
  1346. capture
  1347. } : undefined;
  1348. window.addEventListener("beforeunload", callback, opts);
  1349. return () => {
  1350. window.removeEventListener("beforeunload", callback, opts);
  1351. };
  1352. }, [callback, capture]);
  1353. }
  1354. /**
  1355. * Setup a callback to be fired on the window's `pagehide` event. This is
  1356. * useful for saving some data to `window.localStorage` just before the page
  1357. * refreshes. This event is better supported than beforeunload across browsers.
  1358. *
  1359. * Note: The `callback` argument should be a function created with
  1360. * `React.useCallback()`.
  1361. */
  1362. function usePageHide(callback, options) {
  1363. let {
  1364. capture
  1365. } = options || {};
  1366. React.useEffect(() => {
  1367. let opts = capture != null ? {
  1368. capture
  1369. } : undefined;
  1370. window.addEventListener("pagehide", callback, opts);
  1371. return () => {
  1372. window.removeEventListener("pagehide", callback, opts);
  1373. };
  1374. }, [callback, capture]);
  1375. }
  1376. /**
  1377. * Wrapper around useBlocker to show a window.confirm prompt to users instead
  1378. * of building a custom UI with useBlocker.
  1379. *
  1380. * Warning: This has *a lot of rough edges* and behaves very differently (and
  1381. * very incorrectly in some cases) across browsers if user click addition
  1382. * back/forward navigations while the confirm is open. Use at your own risk.
  1383. */
  1384. function usePrompt(_ref12) {
  1385. let {
  1386. when,
  1387. message
  1388. } = _ref12;
  1389. let blocker = useBlocker(when);
  1390. React.useEffect(() => {
  1391. if (blocker.state === "blocked") {
  1392. let proceed = window.confirm(message);
  1393. if (proceed) {
  1394. // This timeout is needed to avoid a weird "race" on POP navigations
  1395. // between the `window.history` revert navigation and the result of
  1396. // `window.confirm`
  1397. setTimeout(blocker.proceed, 0);
  1398. } else {
  1399. blocker.reset();
  1400. }
  1401. }
  1402. }, [blocker, message]);
  1403. React.useEffect(() => {
  1404. if (blocker.state === "blocked" && !when) {
  1405. blocker.reset();
  1406. }
  1407. }, [blocker, when]);
  1408. }
  1409. /**
  1410. * Return a boolean indicating if there is an active view transition to the
  1411. * given href. You can use this value to render CSS classes or viewTransitionName
  1412. * styles onto your elements
  1413. *
  1414. * @param href The destination href
  1415. * @param [opts.relative] Relative routing type ("route" | "path")
  1416. */
  1417. function useViewTransitionState(to, opts) {
  1418. if (opts === void 0) {
  1419. opts = {};
  1420. }
  1421. let vtContext = React.useContext(ViewTransitionContext);
  1422. !(vtContext != null) ? process.env.NODE_ENV !== "production" ? UNSAFE_invariant(false, "`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. " + "Did you accidentally import `RouterProvider` from `react-router`?") : UNSAFE_invariant(false) : void 0;
  1423. let {
  1424. basename
  1425. } = useDataRouterContext(DataRouterHook.useViewTransitionState);
  1426. let path = useResolvedPath(to, {
  1427. relative: opts.relative
  1428. });
  1429. if (!vtContext.isTransitioning) {
  1430. return false;
  1431. }
  1432. let currentPath = stripBasename(vtContext.currentLocation.pathname, basename) || vtContext.currentLocation.pathname;
  1433. let nextPath = stripBasename(vtContext.nextLocation.pathname, basename) || vtContext.nextLocation.pathname;
  1434. // Transition is active if we're going to or coming from the indicated
  1435. // destination. This ensures that other PUSH navigations that reverse
  1436. // an indicated transition apply. I.e., on the list view you have:
  1437. //
  1438. // <NavLink to="/details/1" viewTransition>
  1439. //
  1440. // If you click the breadcrumb back to the list view:
  1441. //
  1442. // <NavLink to="/list" viewTransition>
  1443. //
  1444. // We should apply the transition because it's indicated as active going
  1445. // from /list -> /details/1 and therefore should be active on the reverse
  1446. // (even though this isn't strictly a POP reverse)
  1447. return matchPath(path.pathname, nextPath) != null || matchPath(path.pathname, currentPath) != null;
  1448. }
  1449. //#endregion
  1450. export { BrowserRouter, Form, HashRouter, Link, NavLink, RouterProvider, ScrollRestoration, FetchersContext as UNSAFE_FetchersContext, ViewTransitionContext as UNSAFE_ViewTransitionContext, useScrollRestoration as UNSAFE_useScrollRestoration, createBrowserRouter, createHashRouter, createSearchParams, HistoryRouter as unstable_HistoryRouter, usePrompt as unstable_usePrompt, useBeforeUnload, useFetcher, useFetchers, useFormAction, useLinkClickHandler, useSearchParams, useSubmit, useViewTransitionState };
  1451. //# sourceMappingURL=index.js.map