react-router-dom.development.js 53 KB

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