@tanstack/react-router 0.0.1-beta.54 → 0.0.1-beta.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/index.js +48 -73
- package/build/cjs/index.js.map +1 -1
- package/build/esm/index.js +18 -89
- package/build/esm/index.js.map +1 -1
- package/build/stats-html.html +1 -1
- package/build/stats-react.json +66 -76
- package/build/types/index.d.ts +5 -17
- package/build/umd/index.development.js +262 -612
- package/build/umd/index.development.js.map +1 -1
- package/build/umd/index.production.js +23 -4
- package/build/umd/index.production.js.map +1 -1
- package/package.json +3 -5
- package/src/index.tsx +16 -84
- package/build/cjs/useStore.js +0 -64
- package/build/cjs/useStore.js.map +0 -1
- package/src/useStore.ts +0 -70
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react"),require("use-sync-external-store/shim/with-selector")):"function"==typeof define&&define.amd?define(["exports","react","use-sync-external-store/shim/with-selector"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).ReactRouter={},t.React,t.withSelector)}(this,(function(t,e,r){"use strict";function
|
|
11
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react"),require("use-sync-external-store/shim/with-selector")):"function"==typeof define&&define.amd?define(["exports","react","use-sync-external-store/shim/with-selector"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).ReactRouter={},t.React,t.withSelector)}(this,(function(t,e,r){"use strict";function s(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach((function(r){if("default"!==r){var s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,s.get?s:{enumerable:!0,get:function(){return t[r]}})}})),e.default=t,Object.freeze(e)}var o=s(e);function a(){return a=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t[s]=r[s])}return t},a.apply(this,arguments)}function n(t,e){if(!t)throw new Error("Invariant failed")}
|
|
12
12
|
/**
|
|
13
|
-
*
|
|
13
|
+
* store
|
|
14
14
|
*
|
|
15
15
|
* Copyright (c) TanStack
|
|
16
16
|
*
|
|
@@ -18,6 +18,25 @@
|
|
|
18
18
|
* LICENSE.md file in the root directory of this source tree.
|
|
19
19
|
*
|
|
20
20
|
* @license MIT
|
|
21
|
-
*/
|
|
22
|
-
const at="popstate";function st(t){let e=t.getLocation(),r=()=>{},o=new Set;const a=()=>{e=t.getLocation(),o.forEach((t=>t()))};return{get location(){return e},listen:e=>(0===o.size&&(r=t.listener(a)),o.add(e),()=>{o.delete(e),0===o.size&&r()}),push:(e,r)=>{t.pushState(e,r),a()},replace:(e,r)=>{t.replaceState(e,r),a()},go:e=>{t.go(e),a()},back:()=>{t.back(),a()},forward:()=>{t.forward(),a()}}}function nt(t){const e=t?.getHref??(()=>`${window.location.pathname}${window.location.hash}${window.location.search}`),r=t?.createHref??(t=>t);return st({getLocation:()=>ct(e(),history.state),listener:t=>(window.addEventListener(at,t),()=>{window.removeEventListener(at,t)}),pushState:(t,e)=>{window.history.pushState({...e,key:ut()},"",r(t))},replaceState:(t,e)=>{window.history.replaceState({...e,key:ut()},"",r(t))},back:()=>window.history.back(),forward:()=>window.history.forward(),go:t=>window.history.go(t)})}function it(t={initialEntries:["/"]}){const e=t.initialEntries;let r=t.initialIndex??e.length-1,o={};return st({getLocation:()=>ct(e[r],o),listener:()=>()=>{},pushState:(t,a)=>{o={...a,key:ut()},e.push(t),r++},replaceState:(t,a)=>{o={...a,key:ut()},e[r]=t},back:()=>{r--},forward:()=>{r=Math.min(r+1,e.length-1)},go:t=>window.history.go(t)})}function ct(t,e){let r=t.indexOf("#"),o=t.indexOf("?");return{href:t,pathname:t.substring(0,r>0?o>0?Math.min(r,o):r:o>0?o:t.length),hash:r>-1?t.substring(r,o):"",search:o>-1?t.substring(o):"",state:e}}function ut(){return(Math.random()+1).toString(36).substring(7)}function ht(t){return t[t.length-1]}function lt(t,e){if(t){"undefined"!=typeof console&&console.warn(e);try{throw new Error(e)}catch{}}return!0}function dt(t,e){return function(t){return"function"==typeof t}(t)?t(e):t}function ft(t,e){return e.reduce(((e,r)=>(e[r]=t[r],e)),{})}function pt(t){return mt(t.filter(Boolean).join("/"))}function mt(t){return t.replace(/\/{2,}/g,"/")}function gt(t){return"/"===t?t:t.replace(/^\/{1,}/,"")}function yt(t){return"/"===t?t:t.replace(/\/{1,}$/,"")}function vt(t){return yt(gt(t))}function bt(t,e,r){e=e.replace(new RegExp(`^${t}`),"/"),r=r.replace(new RegExp(`^${t}`),"/");let o=wt(e);const a=wt(r);a.forEach(((t,e)=>{if("/"===t.value)e?e===a.length-1&&o.push(t):o=[t];else if(".."===t.value)o.length>1&&"/"===ht(o)?.value&&o.pop(),o.pop();else{if("."===t.value)return;o.push(t)}}));const s=pt([t,...o.map((t=>t.value))]);return mt(s)}function wt(t){if(!t)return[];const e=[];if("/"===(t=mt(t)).slice(0,1)&&(t=t.substring(1),e.push({type:"pathname",value:"/"})),!t)return e;const r=t.split("/").filter(Boolean);return e.push(...r.map((t=>t.startsWith("*")?{type:"wildcard",value:t}:"$"===t.charAt(0)?{type:"param",value:t}:{type:"pathname",value:t}))),"/"===t.slice(-1)&&(t=t.substring(1),e.push({type:"pathname",value:"/"})),e}function St(t,e,r){return pt(wt(t).map((t=>"*"!==t.value||r?"param"===t.type?e[t.value.substring(1)]??"":t.value:"")))}function Pt(t,e,r){const o=Lt(t,e,r);if(!r.to||o)return o??{}}function Lt(t,e,r){if(!e.startsWith(t))return;const o=wt(e="/"!=t?e.substring(t.length):e),a=wt(`${r.to??"*"}`),s={};let n=(()=>{for(let t=0;t<Math.max(o.length,a.length);t++){const e=o[t],n=a[t],i=t===a.length-1,c=t===o.length-1;if(n){if("wildcard"===n.type)return!!e?.value&&(s["*"]=pt(o.slice(t).map((t=>t.value))),!0);if("pathname"===n.type){if("/"===n.value&&!e?.value)return!0;if(e)if(r.caseSensitive){if(n.value!==e.value)return!1}else if(n.value.toLowerCase()!==e.value.toLowerCase())return!1}if(!e)return!1;if("param"===n.type){if("/"===e?.value)return!1;"$"!==e.value.charAt(0)&&(s[n.value.substring(1)]=e.value)}}if(i&&!c)return!!r.fuzzy}return!0})();return n?s:void 0}function Mt(t,e){var r,o,a,s="";for(r in t)if(void 0!==(a=t[r]))if(Array.isArray(a))for(o=0;o<a.length;o++)s&&(s+="&"),s+=encodeURIComponent(r)+"="+encodeURIComponent(a[o]);else s&&(s+="&"),s+=encodeURIComponent(r)+"="+encodeURIComponent(a);return(e||"")+s}function Et(t){if(!t)return"";var e=decodeURIComponent(t);return"false"!==e&&("true"===e||("0"===e.charAt(0)?e:0*+e==0?+e:e))}function At(t){for(var e,r,o={},a=t.split("&");e=a.shift();)void 0!==o[r=(e=e.split("=")).shift()]?o[r]=[].concat(o[r],Et(e.shift())):o[r]=Et(e.shift());return o}class xt{constructor(t,e,r,o,a){Object.assign(this,{...t,originalIndex:r,options:e,getRouter:()=>a,childRoutes:void 0,getParentRoute:()=>o}),a.options.createRoute?.({router:a,route:this})}}const _t="__root__",Ot=(t={},e=[],r=!0,o,a)=>{r&&(t.path=_t),o===_t&&(o="");let s=r?_t:t.path;s&&"/"!==s&&(s=vt(s));const i=s||t.id;let c=pt([o,i]);s===_t&&(s="/"),c!==_t&&(c=pt(["/",c]));const u=c===_t?"/":yt(pt([a,s]));return{id:c,routeId:i,path:s,fullPath:u,options:t,children:e,addChildren:e=>Ot(t,e,!1,o,a),createRoute:t=>Ot(t,void 0,!1,c,u),generate:()=>{n(!1)}}};ot(!1);let Rt=[],Dt=!1;function jt(){Dt||(Rt.forEach((t=>t())),Rt=[])}function Ct(t,e){const r=new Set,o={state:t,subscribe:t=>(r.add(t),()=>r.delete(t)),setState:t=>{const a=o.state;o.state=rt((e=>{t(e)}))(a),e&&console.log(o.state),Rt.push((()=>r.forEach((t=>t(o.state,a))))),jt()}};return o}function kt(t){Dt=!0,t(),Dt=!1,jt()}function Ft(t,e){if(t===e)return t;const r=e,o=Array.isArray(t)&&Array.isArray(r);if(o||It(t)&&It(r)){const e=o?t.length:Object.keys(t).length,a=o?r:Object.keys(r),s=a.length,n=o?[]:{};let i=0;for(let e=0;e<s;e++){const s=o?e:a[e];n[s]=Ft(t[s],r[s]),n[s]===t[s]&&i++}return e===s&&i===e?t:n}return r}function It(t){if(!$t(t))return!1;const e=t.constructor;if(void 0===e)return!0;const r=e.prototype;return!!$t(r)&&!!r.hasOwnProperty("isPrototypeOf")}function $t(t){return"[object Object]"===Object.prototype.toString.call(t)}const Nt=["component","errorComponent","pendingComponent"];class Tt{abortController=new AbortController;#t="";#e=()=>{};onLoaderDataListeners=new Set;constructor(t,e,r){Object.assign(this,{route:e,router:t,id:r.id,pathname:r.pathname,params:r.params,store:Ct({routeSearch:{},search:{},status:"idle",routeLoaderData:{},loaderData:{},isFetching:!1,invalid:!1,invalidAt:1/0})}),this.__hasLoaders()||this.store.setState((t=>t.status="success"))}setLoaderData=t=>{kt((()=>{this.store.setState((e=>{e.routeLoaderData=t})),this.#r()}))};cancel=()=>{this.abortController?.abort()};load=async t=>{const e=Date.now(),r=t?.preload?Math.max(t?.maxAge,t?.gcMaxAge):0;if(t?.preload&&r>0){if(this.router.store.state.currentMatches.find((t=>t.id===this.id)))return;this.router.store.setState((r=>{r.matchCache[this.id]={gc:e+t.gcMaxAge,match:this}}))}if("success"===this.store.state.status&&this.getIsInvalid()||"error"===this.store.state.status||"idle"===this.store.state.status){const e=t?.preload?t?.maxAge:void 0;await this.fetch({maxAge:e})}};fetch=async t=>(this.__loadPromise=new Promise((async e=>{const r=""+Date.now()+Math.random();this.#t=r;const o=()=>r!==this.#t?this.__loadPromise?.then((()=>e())):void 0;let a;kt((()=>{"idle"===this.store.state.status&&this.store.setState((t=>t.status="loading")),this.store.setState((t=>t.invalid=!1))})),this.store.setState((t=>t.isFetching=!0)),this.#e=e;const s=(async()=>{await Promise.all(Nt.map((async t=>{const e=this.route.options[t];this[t]?.preload&&(this[t]=await this.router.options.loadComponent(e))})))})(),n=Promise.resolve().then((async()=>{try{if(this.route.options.loader){const t=await this.router.loadMatchData(this);if(a=o())return a;this.setLoaderData(t)}return this.store.setState((e=>{e.error=void 0,e.status="success",e.updatedAt=Date.now(),e.invalidAt=e.updatedAt+(t?.maxAge??this.route.options.loaderMaxAge??this.router.options.defaultLoaderMaxAge??0)})),this.store.state.routeLoaderData}catch(t){if(a=o())return a;throw this.store.setState((e=>{e.error=t,e.status="error",e.updatedAt=Date.now()})),t}})),i=async()=>{if(a=o())return a;this.store.setState((t=>t.isFetching=!1)),this.#e(),delete this.__loadPromise};try{await Promise.all([s,n.catch((()=>{}))]),i()}catch{i()}})),this.__loadPromise);invalidate=async()=>{this.store.setState((t=>t.invalid=!0)),this.router.store.state.currentMatches.find((t=>t.id===this.id))&&await this.load()};__hasLoaders=()=>!(!this.route.options.loader&&!Nt.some((t=>this.route.options[t]?.preload)));getIsInvalid=()=>{const t=Date.now();return this.store.state.invalid||this.store.state.invalidAt<t};#r=()=>{this.store.setState((t=>{t.loaderData=Ft(t.loaderData,{...this.parentMatch?.store.state.loaderData,...t.routeLoaderData})})),this.onLoaderDataListeners.forEach((t=>t()))};__setParentMatch=t=>{!this.parentMatch&&t&&(this.parentMatch=t,this.parentMatch.__onLoaderData((()=>{this.#r()})))};__onLoaderData=t=>{this.onLoaderDataListeners.add(t)};__validate=()=>{const t=this.parentMatch?.store.state.search??this.router.store.state.latestLocation.search;try{const e=this.store.state.routeSearch;let r=("object"==typeof this.route.options.validateSearch?this.route.options.validateSearch.parse:this.route.options.validateSearch)?.(t)??{};kt((()=>{e!==r&&this.store.setState((t=>t.invalid=!0)),this.store.setState((e=>{e.routeSearch=r,e.search={...t,...r}}))})),Nt.map((async t=>{const e=this.route.options[t];"function"!=typeof this[t]&&(this[t]=e)}))}catch(t){console.error(t);const e=new Error("Invalid search params found",{cause:t});return e.code="INVALID_SEARCH_PARAMS",void this.store.setState((t=>{t.status="error",t.error=e}))}}}const zt=Ht(JSON.parse),Bt=Ut(JSON.stringify);function Ht(t){return e=>{"?"===e.substring(0,1)&&(e=e.substring(1));let r=At(e);for(let e in r){const o=r[e];if("string"==typeof o)try{r[e]=t(o)}catch(t){}}return r}}function Ut(t){return e=>{(e={...e})&&Object.keys(e).forEach((r=>{const o=e[r];if(void 0===o||void 0===o)delete e[r];else if(o&&"object"==typeof o&&null!==o)try{e[r]=t(o)}catch(t){}}));const r=Mt(e).toString();return r?`?${r}`:""}}const Kt=async({router:t,routeMatch:e})=>{const r=t.buildNext({to:".",search:t=>({...t??{},__data:{matchId:e.id}})}),o=await fetch(r.href,{method:"GET",signal:e.abortController.signal});if(o.ok)return o.json();throw new Error("Failed to fetch match data")};class Wt{#o;startedLoadingAt=Date.now();resolveNavigation=()=>{};constructor(t){this.options={defaultLoaderGcMaxAge:3e5,defaultLoaderMaxAge:0,defaultPreloadMaxAge:2e3,defaultPreloadDelay:50,context:void 0,...t,stringifySearch:t?.stringifySearch??Bt,parseSearch:t?.parseSearch??zt,fetchServerDataFn:t?.fetchServerDataFn??Kt},this.store=Ct(Jt()),this.basepath="",this.update(t),this.options.Router?.(this)}reset=()=>{this.store.setState((t=>Object.assign(t,Jt())))};mount=()=>{if(!Gt){this.store.state.currentMatches.length||this.load();const t="visibilitychange",e="focus";return window.addEventListener&&(window.addEventListener(t,this.#a,!1),window.addEventListener(e,this.#a,!1)),()=>{window.removeEventListener&&(window.removeEventListener(t,this.#a),window.removeEventListener(e,this.#a))}}return()=>{}};update=t=>{Object.assign(this.options,t),(!this.history||this.options.history&&this.options.history!==this.history)&&(this.#o&&this.#o(),this.history=this.options.history??(Gt?it():nt()),this.store.setState((t=>{t.latestLocation=this.#s(),t.currentLocation=t.latestLocation})),this.#o=this.history.listen((()=>{this.load(this.#s(this.store.state.latestLocation))})));const{basepath:e,routeConfig:r}=this.options;return this.basepath=`/${vt(e??"")??""}`,r&&(this.routesById={},this.routeTree=this.#n(r)),this};buildNext=t=>{const e=this.#i(t),r=this.matchRoutes(e.pathname),o=r.map((t=>t.route.options.preSearchFilters??[])).flat().filter(Boolean),a=r.map((t=>t.route.options.postSearchFilters??[])).flat().filter(Boolean);return this.#i({...t,__preSearchFilters:o,__postSearchFilters:a})};cancelMatches=()=>{[...this.store.state.currentMatches,...this.store.state.pendingMatches||[]].forEach((t=>{t.cancel()}))};load=async t=>{let e=Date.now();const r=e;let o;this.startedLoadingAt=r,this.cancelMatches(),kt((()=>{t&&this.store.setState((e=>{e.latestLocation=t})),o=this.matchRoutes(this.store.state.latestLocation.pathname,{strictParseParams:!0}),this.store.setState((t=>{t.status="loading",t.pendingMatches=o,t.pendingLocation=this.store.state.latestLocation}))}));try{await this.loadMatches(o)}catch(t){console.warn(t),n(!1)}if(this.startedLoadingAt!==r)return this.navigationPromise;const a=this.store.state.currentMatches,s=[],i=[];a.forEach((t=>{o.find((e=>e.id===t.id))?i.push(t):s.push(t)}));const c=o.filter((t=>!a.find((e=>e.id===t.id))));e=Date.now(),s.forEach((t=>{t.__onExit?.({params:t.params,search:t.store.state.routeSearch}),"error"!==t.store.state.status||t.store.state.isFetching||t.store.setState((t=>{t.status="idle",t.error=void 0}));const r=Math.max(t.route.options.loaderGcMaxAge??this.options.defaultLoaderGcMaxAge??0,t.route.options.loaderMaxAge??this.options.defaultLoaderMaxAge??0);r>0&&this.store.setState((o=>{o.matchCache[t.id]={gc:r==1/0?Number.MAX_SAFE_INTEGER:e+r,match:t}}))})),i.forEach((t=>{t.route.options.onTransition?.({params:t.params,search:t.store.state.routeSearch})})),c.forEach((t=>{t.__onExit=t.route.options.onLoaded?.({params:t.params,search:t.store.state.search}),delete this.store.state.matchCache[t.id]})),this.store.setState((t=>{Object.assign(t,{status:"idle",currentLocation:this.store.state.latestLocation,currentMatches:o,pendingLocation:void 0,pendingMatches:void 0})})),this.options.onRouteChange?.(),this.resolveNavigation()};cleanMatchCache=()=>{const t=Date.now();this.store.setState((e=>{Object.keys(e.matchCache).forEach((r=>{const o=e.matchCache[r];"loading"!==o.match.store.state.status&&(o.gc>0&&o.gc>t||delete e.matchCache[r])}))}))};getRoute=t=>{const e=this.routesById[t];return n(e),e};loadRoute=async(t=this.store.state.latestLocation)=>{const e=this.buildNext(t),r=this.matchRoutes(e.pathname,{strictParseParams:!0});return await this.loadMatches(r),r};preloadRoute=async(t=this.store.state.latestLocation,e)=>{const r=this.buildNext(t),o=this.matchRoutes(r.pathname,{strictParseParams:!0});return await this.loadMatches(o,{preload:!0,maxAge:e.maxAge??this.options.defaultPreloadMaxAge??this.options.defaultLoaderMaxAge??0,gcMaxAge:e.gcMaxAge??this.options.defaultPreloadGcMaxAge??this.options.defaultLoaderGcMaxAge??0}),o};matchRoutes=(t,e)=>{const r=[];if(!this.routeTree)return r;const o=[...this.store.state.currentMatches,...this.store.state.pendingMatches??[]],a=async s=>{let n=ht(r)?.params??{};const i=this.options.filterRoutes?.(s)??s;let c=[];const u=(r,o)=>(o.some((o=>{if(!o.path&&o.childRoutes?.length)return u([...c,o],o.childRoutes);const a=!("/"===o.path&&!o.childRoutes?.length),s=Pt(this.basepath,t,{to:o.fullPath,fuzzy:a,caseSensitive:o.options.caseSensitive??this.options.caseSensitive});if(s){let t;try{t=o.options.parseParams?.(s)??s}catch(t){if(e?.strictParseParams)throw t}n={...n,...t}}return s&&(c=[...r,o]),!!c.length})),!!c.length);if(u([],i),!c.length)return;c.forEach((t=>{const e=St(t.path,n),a=St(t.id,n,!0),s=o.find((t=>t.id===a))||this.store.state.matchCache[a]?.match||new Tt(this,t,{id:a,params:n,pathname:pt([this.basepath,e])});r.push(s)}));const h=ht(c);h.childRoutes?.length&&a(h.childRoutes)};return a([this.routeTree]),function(t){t.forEach(((e,r)=>{const o=t[r-1];o&&e.__setParentMatch(o)}))}(r),r};loadMatches=async(t,e)=>{this.cleanMatchCache(),t.forEach((async t=>{t.__validate()})),await Promise.all(t.map((async t=>{try{await(t.route.options.beforeLoad?.({router:this,match:t}))}catch(r){throw e?.preload||t.route.options.onLoadError?.(r),r}})));const r=t.map((async(r,o)=>{const a=t[1],s=r.store.state.search;s.__data?.matchId&&s.__data.matchId!==r.id||(r.load(e),"success"!==r.store.state.status&&r.__loadPromise&&await r.__loadPromise,a&&await a.__loadPromise)}));await Promise.all(r)};loadMatchData=async t=>{if(Gt||!this.options.useServerData)return await(t.route.options.loader?.({params:t.params,search:t.store.state.routeSearch,signal:t.abortController.signal}))||{};return await this.options.fetchServerDataFn({router:this,routeMatch:t})};invalidateRoute=async t=>{const e=this.buildNext(t),r=this.matchRoutes(e.pathname).map((t=>t.id));await Promise.allSettled([...this.store.state.currentMatches,...this.store.state.pendingMatches??[]].map((async t=>{if(r.includes(t.id))return t.invalidate()})))};reload=()=>{this.navigate({fromCurrent:!0,replace:!0,search:!0})};resolvePath=(t,e)=>bt(this.basepath,t,mt(e));navigate=async({from:t,to:e=".",search:r,hash:o,replace:a,params:s})=>{const i=String(e),c=void 0===t?t:String(t);let u;try{new URL(`${i}`),u=!0}catch(t){}return n(!u),this.#c({from:c,to:i,search:r,hash:o,replace:a,params:s})};matchRoute=(t,e)=>{t={...t,to:t.to?this.resolvePath(t.from??"",t.to):void 0};const r=this.buildNext(t);return e?.pending?!!this.store.state.pendingLocation&&Pt(this.basepath,this.store.state.pendingLocation.pathname,{...e,to:r.pathname}):Pt(this.basepath,this.store.state.currentLocation.pathname,{...e,to:r.pathname})};buildLink=({from:t,to:e=".",search:r,params:o,hash:a,target:s,replace:n,activeOptions:i,preload:c,preloadMaxAge:u,preloadGcMaxAge:h,preloadDelay:l,disabled:d})=>{try{return new URL(`${e}`),{type:"external",href:e}}catch(t){}const f={from:t,to:e,search:r,params:o,hash:a,replace:n},p=this.buildNext(f);c=c??this.options.defaultPreload;const m=l??this.options.defaultPreloadDelay??0,g=this.store.state.currentLocation.pathname===p.pathname,y=this.store.state.currentLocation.pathname.split("/"),v=p.pathname.split("/").every(((t,e)=>t===y[e])),b=this.store.state.currentLocation.hash===p.hash;return{type:"internal",next:p,handleFocus:t=>{c&&this.preloadRoute(f,{maxAge:u,gcMaxAge:h}).catch((t=>{console.warn(t),console.warn("Error preloading route! ☝️")}))},handleClick:t=>{d||function(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}(t)||t.defaultPrevented||s&&"_self"!==s||0!==t.button||(t.preventDefault(),!g||r||a||this.invalidateRoute(f),this.#c(f))},handleEnter:t=>{const e=t.target||{};if(c){if(e.preloadTimeout)return;e.preloadTimeout=setTimeout((()=>{e.preloadTimeout=null,this.preloadRoute(f,{maxAge:u,gcMaxAge:h}).catch((t=>{console.warn(t),console.warn("Error preloading route! ☝️")}))}),m)}},handleLeave:t=>{const e=t.target||{};e.preloadTimeout&&(clearTimeout(e.preloadTimeout),e.preloadTimeout=null)},isActive:(i?.exact?g:v)&&(!i?.includeHash||b),disabled:d}};dehydrate=()=>({state:{...ft(this.store.state,["latestLocation","currentLocation","status","lastUpdated"]),currentMatches:this.store.state.currentMatches.map((t=>({id:t.id,state:{...ft(t.store.state,["status","routeLoaderData","invalidAt","invalid"])}})))},context:this.options.context});hydrate=t=>{this.store.setState((e=>{this.options.context=t.context;const r=this.matchRoutes(t.state.latestLocation.pathname,{strictParseParams:!0});r.forEach(((e,r)=>{const o=t.state.currentMatches[r];n(o&&o.id===e.id),e.store.setState((t=>{Object.assign(t,o.state)})),e.setLoaderData(o.state.routeLoaderData)})),r.forEach((t=>t.__validate())),Object.assign(e,{...t.state,currentMatches:r})}))};getLoader=t=>{const e=t.from||"/",r=this.getRoute(e);if(!r)return;let o=this.store.state.loaders[e]||(()=>(this.store.setState((t=>{t.loaders[e]={pending:[],fetch:async t=>{if(!r)return;const o={loadedAt:Date.now(),loaderContext:t};this.store.setState((t=>{t.loaders[e].current=o,t.loaders[e].latest=o,t.loaders[e].pending.push(o)}));try{return await(r.options.loader?.(t))}finally{this.store.setState((t=>{t.loaders[e].pending=t.loaders[e].pending.filter((t=>t!==o))}))}}}})),this.store.state.loaders[e]))();return o};#n=t=>{const e=(t,r)=>t.map(((t,o)=>{const a=t.options,s=new xt(t,a,o,r,this);if(this.routesById[s.id])throw new Error;this.routesById[s.id]=s;const n=t.children;return s.childRoutes=n.length?e(n,s):void 0,s}));return e([t])[0]};#s=t=>{let{pathname:e,search:r,hash:o,state:a}=this.history.location;const s=this.options.parseSearch(r);return{pathname:e,searchStr:r,search:Ft(t?.search,s),hash:o.split("#").reverse()[0]??"",href:`${e}${r}${o}`,state:a,key:a?.key||"__init__"}};#a=()=>{this.load()};#i=(t={})=>{const e=t.fromCurrent?this.store.state.latestLocation.pathname:t.from??this.store.state.latestLocation.pathname;let r=bt(this.basepath??"/",e,`${t.to??"."}`);const o=this.matchRoutes(this.store.state.latestLocation.pathname,{strictParseParams:!0}),a=this.matchRoutes(r),s={...ht(o)?.params};let n=!0===(t.params??!0)?s:dt(t.params,s);n&&a.map((t=>t.route.options.stringifyParams)).filter(Boolean).forEach((t=>{Object.assign({},n,t(n))})),r=St(r,n??{});const i=t.__preSearchFilters?.length?t.__preSearchFilters?.reduce(((t,e)=>e(t)),this.store.state.latestLocation.search):this.store.state.latestLocation.search,c=!0===t.search?i:t.search?dt(t.search,i)??{}:t.__preSearchFilters?.length?i:{},u=t.__postSearchFilters?.length?t.__postSearchFilters.reduce(((t,e)=>e(t)),c):c,h=Ft(this.store.state.latestLocation.search,u),l=this.options.stringifySearch(h);let d=!0===t.hash?this.store.state.latestLocation.hash:dt(t.hash,this.store.state.latestLocation.hash);return d=d?`#${d}`:"",{pathname:r,search:h,searchStr:l,state:this.store.state.latestLocation.state,hash:d,href:`${r}${l}${d}`,key:t.key}};#c=t=>{const e=this.buildNext(t),r=""+Date.now()+Math.random();this.navigateTimeout&&clearTimeout(this.navigateTimeout);let o="replace";t.replace||(o="push");this.store.state.latestLocation.href===e.href&&!e.key&&(o="replace");const a=`${e.pathname}${e.searchStr}${e.hash?`#${e.hash}`:""}`;return this.history["push"===o?"push":"replace"](a,{id:r,...e.state}),this.navigationPromise=new Promise((t=>{const e=this.resolveNavigation;this.resolveNavigation=()=>{e(),t()}}))}}const Gt="undefined"==typeof window||!window.document.createElement;function Jt(){return{status:"idle",latestLocation:null,currentLocation:null,currentMatches:[],loaders:{},lastUpdated:Date.now(),matchCache:{},get isFetching(){return"loading"===this.status||this.currentMatches.some((t=>t.store.state.isFetching))},get isPreloading(){return Object.values(this.matchCache).some((t=>t.match.store.state.isFetching&&!this.currentMatches.find((e=>e.id===t.match.id))))}}}function qt(t,e=(t=>t),o){return r.useSyncExternalStoreWithSelector(t.subscribe,(()=>t.state),(()=>t.state),e,o?Xt:void 0)}function Xt(t,e){if(Object.is(t,e))return!0;if("object"!=typeof t||null===t||"object"!=typeof e||null===e)return!1;const r=Object.keys(t);if(r.length!==Object.keys(e).length)return!1;for(let o=0;o<r.length;o++)if(!Object.prototype.hasOwnProperty.call(e,r[o])||!Object.is(t[r[o]],e[r[o]]))return!1;return!0}function Vt(t){const e=te(),{type:r,children:o,target:s,activeProps:n=(()=>({className:"active"})),inactiveProps:i=(()=>({})),activeOptions:c,disabled:u,hash:h,search:l,params:d,to:f=".",preload:p,preloadDelay:m,preloadMaxAge:g,replace:y,style:v,className:b,onClick:w,onFocus:S,onMouseEnter:P,onMouseLeave:L,onTouchStart:M,onTouchEnd:E,...A}=t,x=e.buildLink(t);if("external"===x.type){const{href:t}=x;return{href:t}}const{handleClick:_,handleFocus:O,handleEnter:R,handleLeave:D,isActive:j,next:C}=x,k=t=>e=>{e.persist&&e.persist(),t.filter(Boolean).forEach((t=>{e.defaultPrevented||t(e)}))},F=j?dt(n,{})??{}:{},I=j?{}:dt(i,{})??{};return{...F,...I,...A,href:u?void 0:C.href,onClick:k([w,t=>{a.startTransition?a.startTransition((()=>{_(t)})):_(t)}]),onFocus:k([S,O]),onMouseEnter:k([P,R]),onMouseLeave:k([L,D]),target:s,style:{...v,...F.style,...I.style},className:[b,F.className,I.className].filter(Boolean).join(" ")||void 0,...u?{role:"link","aria-disabled":!0}:void 0,"data-status":j?"active":void 0}}const Qt=a.forwardRef(((t,e)=>{const r=Vt(t);return a.createElement("a",s({ref:e},r,{children:"function"==typeof t.children?t.children({isActive:"active"===r["data-status"]}):t.children}))})),Yt=a.createContext(null),Zt=a.createContext(null);function te(){const t=a.useContext(Zt);return lt(!t,"useRouter must be used inside a <Router> component!"),t.router}function ee(){return a.useContext(Yt)}function re(t){const e=te(),r=ee()[0],o=t?.from?e.store.state.currentMatches.find((e=>e.route.id===t?.from)):r;return n(o,t?.from&&t.from),(t?.strict??1)&&n(r.route.id==o?.route.id,(o?.route.id,r.route.id,o?.route.id,o?.route.id)),qt(o.store,(e=>t?.track?.(o)??o),t?.shallow),o}function oe(){const t=te();return e=>{const{pending:r,caseSensitive:o,...a}=e;return t.matchRoute(a,{pending:r,caseSensitive:o})}}function ae(){const t=ee().slice(1),e=t[0];return e?a.createElement(se,{matches:t,match:e}):null}function se({matches:t,match:e}){const r=te();qt(e.store);const o=a.useCallback((()=>null),[]),s=a.useCallback((t=>{if("error"===t.match.store.state.status)throw t.match.store.state.error;if("success"===t.match.store.state.status)return a.createElement(t.match.component??r.options.defaultComponent??ae);if("loading"===t.match.store.state.status)throw t.match.__loadPromise;n(!1)}),[]),i=e.pendingComponent??r.options.defaultPendingComponent??o,c=e.errorComponent??r.options.defaultErrorComponent;return a.createElement(Yt.Provider,{value:t},a.createElement(a.Suspense,{fallback:a.createElement(i,null)},a.createElement(ne,{key:e.route.id,errorComponent:c,match:e},a.createElement(s,{match:e}))))}class ne extends a.Component{state={error:!1,info:void 0};componentDidCatch(t,e){console.error(`Error in route match: ${this.props.match.id}`),console.error(t),this.setState({error:t,info:e})}render(){return a.createElement(ie,s({},this.props,{errorState:this.state,reset:()=>this.setState({})}))}}function ie(t){const[e,r]=a.useState(t.errorState);te();const o=t.errorComponent??ce;return a.useEffect((()=>{t.errorState.error&&r(t.errorState),t.reset()}),[t.errorState.error]),t.errorState.error?a.createElement(o,e):t.children}function ce({error:t}){return a.createElement("div",{style:{padding:".5rem",maxWidth:"100%"}},a.createElement("strong",{style:{fontSize:"1.2rem"}},"Something went wrong!"),a.createElement("div",{style:{height:".5rem"}}),a.createElement("div",null,a.createElement("pre",null,t.message?a.createElement("code",{style:{fontSize:".7em",border:"1px solid red",borderRadius:".25rem",padding:".5rem",color:"red"}},t.message):null)))}t.DefaultErrorBoundary=ce,t.Link=Qt,t.MatchRoute=function(t){const e=oe()(t);return e?"function"==typeof t.children?t.children(e):e?t.children:null:null},t.Outlet=ae,t.ReactRouter=class extends Wt{constructor(t){super({...t,loadComponent:async t=>(t.preload&&await t.preload(),t)})}},t.Route=xt,t.RouteMatch=Tt,t.Router=Wt,t.RouterProvider=function({router:t,...e}){t.update(e);const r=qt(t.store,(t=>t.currentMatches),void 0);return a.useEffect(t.mount,[t]),a.createElement(a.Fragment,null,a.createElement(Zt.Provider,{value:{router:t}},a.createElement(Yt.Provider,{value:[void 0,...r]},a.createElement(ae,null))))},t.batch=kt,t.cleanPath=mt,t.createAction=function(t){const e=Ct({submissions:[]},t.debug);return{options:t,store:e,reset:()=>{e.setState((t=>{t.submissions=[]}))},submit:async r=>{const o={submittedAt:Date.now(),status:"pending",payload:r,invalidate:()=>{a((t=>{t.isInvalid=!0}))},getIsLatest:()=>e.state.submissions[e.state.submissions.length-1]?.submittedAt===o.submittedAt},a=t=>{e.setState((e=>{const r=e.submissions.find((t=>t.submittedAt===o.submittedAt));n(r),t(r)}))};e.setState((e=>{e.submissions.push(o),e.submissions.reverse(),e.submissions=e.submissions.slice(0,t.maxSubmissions??10),e.submissions.reverse()}));const s=async()=>{t.onEachSettled?.(o),o.getIsLatest()&&await(t.onLatestSettled?.(o))};try{const e=await(t.action?.(o.payload));return a((t=>{t.response=e})),await(t.onEachSuccess?.(o)),o.getIsLatest()&&await(t.onLatestSuccess?.(o)),await s(),a((t=>{t.status="success"})),e}catch(e){throw console.error(e),a((t=>{t.error=e})),await(t.onEachError?.(o)),o.getIsLatest()&&await(t.onLatestError?.(o)),await s(),a((t=>{t.status="error"})),e}}}},t.createBrowserHistory=nt,t.createHashHistory=function(){return nt({getHref:()=>window.location.hash.substring(1),createHref:t=>`#${t}`})},t.createMemoryHistory=it,t.createRouteConfig=Ot,t.createStore=Ct,t.decode=At,t.defaultFetchServerDataFn=Kt,t.defaultParseSearch=zt,t.defaultStringifySearch=Bt,t.encode=Mt,t.functionalUpdate=dt,t.interpolatePath=St,t.invariant=n,t.joinPaths=pt,t.last=ht,t.lazy=function(t){const e=a.lazy(t);return e.preload=async()=>{await t()},e},t.matchByPath=Lt,t.matchPathname=Pt,t.matchesContext=Yt,t.parsePathname=wt,t.parseSearchWith=Ht,t.pick=ft,t.replaceEqualDeep=Ft,t.resolvePath=bt,t.rootRouteId=_t,t.routerContext=Zt,t.stringifySearchWith=Ut,t.trackDeep=function(t){const e=new Set;return JSON.stringify(t,((t,r)=>{if("function"!=typeof r){if("object"==typeof r&&null!==r){if(e.has(r))return;e.add(r)}return r}})),t},t.trimPath=vt,t.trimPathLeft=gt,t.trimPathRight=yt,t.useAction=function(t,e){qt(t.store,(t=>e?.track?.(t)??t),!0);const[r]=a.useState({});return Object.assign(r,{...t,latestSubmission:t.store.state.submissions[t.store.state.submissions.length-1],pendingSubmissions:a.useMemo((()=>t.store.state.submissions.filter((t=>"pending"===t.status))),[t.store.state.submissions])}),r},t.useLinkProps=Vt,t.useLoaderData=function(t){const e=re(t);return n(e,t?.from&&t.from),qt(e.store,(e=>t?.track?.(e.loaderData)??e.loaderData)),e.store.state.loaderData},t.useMatch=re,t.useMatchRoute=oe,t.useMatches=ee,t.useNavigate=function(t){const e=te();return r=>e.navigate({...t,...r})},t.useParams=function(t){const e=te();return qt(e.store,(e=>{const r=ht(e.currentMatches)?.params;return t?.track?.(r)??r})),ht(e.store.state.currentMatches)?.params},t.useRoute=function(t){const e=te().getRoute(t);return n(e),e},t.useRouter=te,t.useRouterStore=function(t,e){return qt(te().store,t,e)},t.useSearch=function(t){const e=re(t);return qt(e.store,(e=>t?.track?.(e.search)??e.search)),e.store.state.search},t.useStore=qt,t.warning=lt,Object.defineProperty(t,"__esModule",{value:!0})}));
|
|
21
|
+
*/class i{listeners=new Set;batching=!1;queue=[];constructor(t,e){this.state=t,this.options=e}subscribe=t=>{this.listeners.add(t);const e=this.options?.onSubscribe?.(t,this);return()=>{this.listeners.delete(t),e?.()}};setState=t=>{const e=this.state;this.state=this.options?.updateFn?this.options.updateFn(e)(t):t(e),this.queue.push((()=>{this.listeners.forEach((t=>t(this.state,e))),this.options?.onUpdate?.(this.state,e)})),this.#t()};#t=()=>{this.batching||(this.queue.forEach((t=>t())),this.queue=[])};batch=t=>{this.batching=!0,t(),this.batching=!1,this.#t()}}
|
|
22
|
+
/**
|
|
23
|
+
* router
|
|
24
|
+
*
|
|
25
|
+
* Copyright (c) TanStack
|
|
26
|
+
*
|
|
27
|
+
* This source code is licensed under the MIT license found in the
|
|
28
|
+
* LICENSE.md file in the root directory of this source tree.
|
|
29
|
+
*
|
|
30
|
+
* @license MIT
|
|
31
|
+
*/const c="popstate";function h(t){let e=t.getLocation(),r=()=>{},s=new Set;const o=()=>{e=t.getLocation(),s.forEach((t=>t()))};return{get location(){return e},listen:e=>(0===s.size&&(r=t.listener(o)),s.add(e),()=>{s.delete(e),0===s.size&&r()}),push:(e,r)=>{t.pushState(e,r),o()},replace:(e,r)=>{t.replaceState(e,r),o()},go:e=>{t.go(e),o()},back:()=>{t.back(),o()},forward:()=>{t.forward(),o()}}}function u(t){const e=t?.getHref??(()=>`${window.location.pathname}${window.location.hash}${window.location.search}`),r=t?.createHref??(t=>t);return h({getLocation:()=>d(e(),history.state),listener:t=>(window.addEventListener(c,t),()=>{window.removeEventListener(c,t)}),pushState:(t,e)=>{window.history.pushState({...e,key:p()},"",r(t))},replaceState:(t,e)=>{window.history.replaceState({...e,key:p()},"",r(t))},back:()=>window.history.back(),forward:()=>window.history.forward(),go:t=>window.history.go(t)})}function l(t={initialEntries:["/"]}){const e=t.initialEntries;let r=t.initialIndex??e.length-1,s={};return h({getLocation:()=>d(e[r],s),listener:()=>()=>{},pushState:(t,o)=>{s={...o,key:p()},e.push(t),r++},replaceState:(t,o)=>{s={...o,key:p()},e[r]=t},back:()=>{r--},forward:()=>{r=Math.min(r+1,e.length-1)},go:t=>window.history.go(t)})}function d(t,e){let r=t.indexOf("#"),s=t.indexOf("?");return{href:t,pathname:t.substring(0,r>0?s>0?Math.min(r,s):r:s>0?s:t.length),hash:r>-1?t.substring(r,s):"",search:s>-1?t.substring(s):"",state:e}}function p(){return(Math.random()+1).toString(36).substring(7)}function f(t){return t[t.length-1]}function m(t,e){if(t){"undefined"!=typeof console&&console.warn(e);try{throw new Error(e)}catch{}}return!0}function y(t,e){return"function"==typeof t?t(e):t}function g(t,e){return e.reduce(((e,r)=>(e[r]=t[r],e)),{})}function v(t,e){if(t===e)return t;const r=e,s=Array.isArray(t)&&Array.isArray(r);if(s||w(t)&&w(r)){const e=s?t.length:Object.keys(t).length,o=s?r:Object.keys(r),a=o.length,n=s?[]:{};let i=0;for(let e=0;e<a;e++){const a=s?e:o[e];n[a]=v(t[a],r[a]),n[a]===t[a]&&i++}return e===a&&i===e?t:n}return r}function w(t){if(!b(t))return!1;const e=t.constructor;if(void 0===e)return!0;const r=e.prototype;return!!b(r)&&!!r.hasOwnProperty("isPrototypeOf")}function b(t){return"[object Object]"===Object.prototype.toString.call(t)}function S(t){return L(t.filter(Boolean).join("/"))}function L(t){return t.replace(/\/{2,}/g,"/")}function E(t){return"/"===t?t:t.replace(/^\/{1,}/,"")}function P(t){return"/"===t?t:t.replace(/\/{1,}$/,"")}function R(t){return P(E(t))}function _(t,e,r){e=e.replace(new RegExp(`^${t}`),"/"),r=r.replace(new RegExp(`^${t}`),"/");let s=M(e);const o=M(r);o.forEach(((t,e)=>{if("/"===t.value)e?e===o.length-1&&s.push(t):s=[t];else if(".."===t.value)s.length>1&&"/"===f(s)?.value&&s.pop(),s.pop();else{if("."===t.value)return;s.push(t)}}));return L(S([t,...s.map((t=>t.value))]))}function M(t){if(!t)return[];const e=[];if("/"===(t=L(t)).slice(0,1)&&(t=t.substring(1),e.push({type:"pathname",value:"/"})),!t)return e;const r=t.split("/").filter(Boolean);return e.push(...r.map((t=>t.startsWith("*")?{type:"wildcard",value:t}:"$"===t.charAt(0)?{type:"param",value:t}:{type:"pathname",value:t}))),"/"===t.slice(-1)&&(t=t.substring(1),e.push({type:"pathname",value:"/"})),e}function x(t,e,r){return S(M(t).map((t=>"*"!==t.value||r?"param"===t.type?e[t.value.substring(1)]??"":t.value:"")))}function C(t,e,r){const s=k(t,e,r);if(!r.to||s)return s??{}}function k(t,e,r){if(!e.startsWith(t))return;const s=M(e="/"!=t?e.substring(t.length):e),o=M(`${r.to??"*"}`),a={};return(()=>{for(let t=0;t<Math.max(s.length,o.length);t++){const e=s[t],n=o[t],i=t===o.length-1,c=t===s.length-1;if(n){if("wildcard"===n.type)return!!e?.value&&(a["*"]=S(s.slice(t).map((t=>t.value))),!0);if("pathname"===n.type){if("/"===n.value&&!e?.value)return!0;if(e)if(r.caseSensitive){if(n.value!==e.value)return!1}else if(n.value.toLowerCase()!==e.value.toLowerCase())return!1}if(!e)return!1;if("param"===n.type){if("/"===e?.value)return!1;"$"!==e.value.charAt(0)&&(a[n.value.substring(1)]=e.value)}}if(i&&!c)return!!r.fuzzy}return!0})()?a:void 0}function O(t,e){var r,s,o,a="";for(r in t)if(void 0!==(o=t[r]))if(Array.isArray(o))for(s=0;s<o.length;s++)a&&(a+="&"),a+=encodeURIComponent(r)+"="+encodeURIComponent(o[s]);else a&&(a+="&"),a+=encodeURIComponent(r)+"="+encodeURIComponent(o);return(e||"")+a}function j(t){if(!t)return"";var e=decodeURIComponent(t);return"false"!==e&&("true"===e||("0"===e.charAt(0)?e:0*+e==0?+e:e))}function $(t){for(var e,r,s={},o=t.split("&");e=o.shift();)void 0!==s[r=(e=e.split("=")).shift()]?s[r]=[].concat(s[r],j(e.shift())):s[r]=j(e.shift());return s}class A{constructor(t,e,r,s,o){Object.assign(this,{...t,originalIndex:r,options:e,getRouter:()=>o,childRoutes:void 0,getParentRoute:()=>s}),o.options.createRoute?.({router:o,route:this})}}const F="__root__",T=(t={},e=[],r=!0,s,o)=>{r&&(t.path=F),s===F&&(s="");let a=r?F:t.path;a&&"/"!==a&&(a=R(a));const i=a||t.id;let c=S([s,i]);a===F&&(a="/"),c!==F&&(c=S(["/",c]));const h=c===F?"/":P(S([o,a]));return{id:c,routeId:i,path:a,fullPath:h,options:t,children:e,addChildren:e=>T(t,e,!1,s,o),createRoute:t=>T(t,void 0,!1,c,h),generate:()=>{n(!1)}}},I=["component","errorComponent","pendingComponent"];class D{abortController=new AbortController;onLoaderDataListeners=new Set;constructor(t,e,r){Object.assign(this,{route:e,router:t,id:r.id,pathname:r.pathname,params:r.params,store:new i({updatedAt:0,routeSearch:{},search:{},status:"idle"})}),this.#e()||this.store.setState((t=>({...t,status:"success"})))}cancel=()=>{this.abortController?.abort()};load=async()=>{"pending"!==this.store.state.status&&await this.fetch()};#r="";fetch=async()=>(this.__loadPromise=Promise.resolve().then((async()=>{const t=""+Date.now()+Math.random();this.#r=t;const e=()=>t!==this.#r?this.__loadPromise:void 0;let r;this.store.batch((()=>{"idle"===this.store.state.status&&this.store.setState((t=>({...t,status:"pending"})))}));const s=(async()=>{await Promise.all(I.map((async t=>{const e=this.route.options[t];this[t]?.preload&&(this[t]=await this.router.options.loadComponent(e))})))})(),o=Promise.resolve().then((()=>{if(this.route.options.onLoad)return this.route.options.onLoad({params:this.params,search:this.store.state.search,signal:this.abortController.signal})}));try{if(await s,await o,r=e())return await r;this.store.setState((t=>({...t,error:void 0,status:"success",updatedAt:Date.now()})))}catch(t){this.store.setState((e=>({...e,error:t,status:"error",updatedAt:Date.now()})))}finally{delete this.__loadPromise}})),this.__loadPromise);#e=()=>!(!this.route.options.onLoad&&!I.some((t=>this.route.options[t]?.preload)));__setParentMatch=t=>{!this.parentMatch&&t&&(this.parentMatch=t)};__validate=()=>{const t=this.parentMatch?.store.state.search??this.router.store.state.latestLocation.search;try{let e=("object"==typeof this.route.options.validateSearch?this.route.options.validateSearch.parse:this.route.options.validateSearch)?.(t)??{};this.store.setState((r=>({...r,routeSearch:e,search:{...t,...e}}))),I.map((async t=>{const e=this.route.options[t];"function"!=typeof this[t]&&(this[t]=e)}))}catch(t){console.error(t);const e=new Error("Invalid search params found",{cause:t});return e.code="INVALID_SEARCH_PARAMS",void this.store.setState((t=>({...t,status:"error",error:e})))}}}const N=H(JSON.parse),B=z(JSON.stringify);function H(t){return e=>{"?"===e.substring(0,1)&&(e=e.substring(1));let r=$(e);for(let e in r){const s=r[e];if("string"==typeof s)try{r[e]=t(s)}catch(t){}}return r}}function z(t){return e=>{(e={...e})&&Object.keys(e).forEach((r=>{const s=e[r];if(void 0===s||void 0===s)delete e[r];else if(s&&"object"==typeof s&&null!==s)try{e[r]=t(s)}catch(t){}}));const r=O(e).toString();return r?`?${r}`:""}}const U=async({router:t,routeMatch:e})=>{const r=t.buildNext({to:".",search:t=>({...t??{},__data:{matchId:e.id}})}),s=await fetch(r.href,{method:"GET",signal:e.abortController.signal});if(s.ok)return s.json();throw new Error("Failed to fetch match data")};class q{#s;startedLoadingAt=Date.now();resolveNavigation=()=>{};constructor(t){this.options={defaultPreloadDelay:50,context:void 0,...t,stringifySearch:t?.stringifySearch??B,parseSearch:t?.parseSearch??N,fetchServerDataFn:t?.fetchServerDataFn??U},this.store=new i(K()),this.basepath="",this.update(t),this.options.Router?.(this)}reset=()=>{this.store.setState((t=>Object.assign(t,K())))};mount=()=>{if(!W){this.store.state.currentMatches.length||this.load();const t="visibilitychange",e="focus";return window.addEventListener&&(window.addEventListener(t,this.#o,!1),window.addEventListener(e,this.#o,!1)),()=>{window.removeEventListener&&(window.removeEventListener(t,this.#o),window.removeEventListener(e,this.#o))}}return()=>{}};update=t=>{if(Object.assign(this.options,t),!this.history||this.options.history&&this.options.history!==this.history){this.#s&&this.#s(),this.history=this.options.history??(W?l():u());const t=this.#a();this.store.setState((e=>({...e,latestLocation:t,currentLocation:t}))),this.#s=this.history.listen((()=>{this.load(this.#a(this.store.state.latestLocation))}))}const{basepath:e,routeConfig:r}=this.options;return this.basepath=`/${R(e??"")??""}`,r&&(this.routesById={},this.routeTree=this.#n(r)),this};buildNext=t=>{const e=this.#i(t),r=this.matchRoutes(e.pathname),s=r.map((t=>t.route.options.preSearchFilters??[])).flat().filter(Boolean),o=r.map((t=>t.route.options.postSearchFilters??[])).flat().filter(Boolean);return this.#i({...t,__preSearchFilters:s,__postSearchFilters:o})};cancelMatches=()=>{[...this.store.state.currentMatches,...this.store.state.pendingMatches||[]].forEach((t=>{t.cancel()}))};load=async t=>{let e=Date.now();const r=e;let s;this.startedLoadingAt=r,this.cancelMatches(),this.store.batch((()=>{t&&this.store.setState((e=>({...e,latestLocation:t}))),s=this.matchRoutes(this.store.state.latestLocation.pathname,{strictParseParams:!0}),this.store.setState((t=>({...t,status:"pending",pendingMatches:s,pendingLocation:this.store.state.latestLocation})))}));try{await this.loadMatches(s)}catch(t){console.warn(t),n(!1)}if(this.startedLoadingAt!==r)return this.navigationPromise;const o=this.store.state.currentMatches,a=[],i=[];o.forEach((t=>{s.find((e=>e.id===t.id))?i.push(t):a.push(t)}));const c=s.filter((t=>!o.find((e=>e.id===t.id))));e=Date.now(),a.forEach((t=>{t.__onExit?.({params:t.params,search:t.store.state.routeSearch}),"error"===t.store.state.status&&this.store.setState((t=>({...t,status:"idle",error:void 0})))})),i.forEach((t=>{t.route.options.onTransition?.({params:t.params,search:t.store.state.routeSearch})})),c.forEach((t=>{t.__onExit=t.route.options.onLoaded?.({params:t.params,search:t.store.state.search})})),this.store.setState((t=>({...t,status:"idle",currentLocation:this.store.state.latestLocation,currentMatches:s,pendingLocation:void 0,pendingMatches:void 0}))),this.options.onRouteChange?.(),this.resolveNavigation()};getRoute=t=>{const e=this.routesById[t];return n(e),e};loadRoute=async(t=this.store.state.latestLocation)=>{const e=this.buildNext(t),r=this.matchRoutes(e.pathname,{strictParseParams:!0});return await this.loadMatches(r),r};preloadRoute=async(t=this.store.state.latestLocation)=>{const e=this.buildNext(t),r=this.matchRoutes(e.pathname,{strictParseParams:!0});return await this.loadMatches(r,{preload:!0}),r};matchRoutes=(t,e)=>{const r=[];if(!this.routeTree)return r;const s=[...this.store.state.currentMatches,...this.store.state.pendingMatches??[]],o=async a=>{let n=f(r)?.params??{};const i=this.options.filterRoutes?.(a)??a;let c=[];const h=(r,s)=>(s.some((s=>{if(!s.path&&s.childRoutes?.length)return h([...c,s],s.childRoutes);const o=!("/"===s.path&&!s.childRoutes?.length),a=C(this.basepath,t,{to:s.fullPath,fuzzy:o,caseSensitive:s.options.caseSensitive??this.options.caseSensitive});if(a){let t;try{t=s.options.parseParams?.(a)??a}catch(t){if(e?.strictParseParams)throw t}n={...n,...t}}return a&&(c=[...r,s]),!!c.length})),!!c.length);if(h([],i),!c.length)return;c.forEach((t=>{const e=x(t.path,n),o=x(t.id,n,!0),a=s.find((t=>t.id===o))||new D(this,t,{id:o,params:n,pathname:S([this.basepath,e])});r.push(a)}));const u=f(c);u.childRoutes?.length&&o(u.childRoutes)};return o([this.routeTree]),function(t){t.forEach(((e,r)=>{const s=t[r-1];s&&e.__setParentMatch(s)}))}
|
|
32
|
+
/**
|
|
33
|
+
* react-store
|
|
34
|
+
*
|
|
35
|
+
* Copyright (c) TanStack
|
|
36
|
+
*
|
|
37
|
+
* This source code is licensed under the MIT license found in the
|
|
38
|
+
* LICENSE.md file in the root directory of this source tree.
|
|
39
|
+
*
|
|
40
|
+
* @license MIT
|
|
41
|
+
*/(r),r};loadMatches=async(t,e)=>{t.forEach((async t=>{t.__validate()})),await Promise.all(t.map((async t=>{try{await(t.route.options.beforeLoad?.({router:this,match:t}))}catch(r){throw e?.preload||t.route.options.onLoadError?.(r),r}})));const r=t.map((async(e,r)=>{const s=t[1],o=e.store.state.search;o.__data?.matchId&&o.__data.matchId!==e.id||(e.load(),"success"!==e.store.state.status&&e.__loadPromise&&await e.__loadPromise,s&&await s.__loadPromise)}));await Promise.all(r)};reload=()=>{this.navigate({fromCurrent:!0,replace:!0,search:!0})};resolvePath=(t,e)=>_(this.basepath,t,L(e));navigate=async({from:t,to:e=".",search:r,hash:s,replace:o,params:a})=>{const i=String(e),c=void 0===t?t:String(t);let h;try{new URL(`${i}`),h=!0}catch(t){}return n(!h),this.#c({from:c,to:i,search:r,hash:s,replace:o,params:a})};matchRoute=(t,e)=>{t={...t,to:t.to?this.resolvePath(t.from??"",t.to):void 0};const r=this.buildNext(t);return e?.pending?!!this.store.state.pendingLocation&&C(this.basepath,this.store.state.pendingLocation.pathname,{...e,to:r.pathname}):C(this.basepath,this.store.state.currentLocation.pathname,{...e,to:r.pathname})};buildLink=({from:t,to:e=".",search:r,params:s,hash:o,target:a,replace:n,activeOptions:i,preload:c,preloadMaxAge:h,preloadGcMaxAge:u,preloadDelay:l,disabled:d})=>{try{return new URL(`${e}`),{type:"external",href:e}}catch(t){}const p={from:t,to:e,search:r,params:s,hash:o,replace:n},f=this.buildNext(p);c=c??this.options.defaultPreload;const m=l??this.options.defaultPreloadDelay??0,y=this.store.state.currentLocation.pathname===f.pathname,g=this.store.state.currentLocation.pathname.split("/"),v=f.pathname.split("/").every(((t,e)=>t===g[e])),w=this.store.state.currentLocation.hash===f.hash;return{type:"internal",next:f,handleFocus:t=>{c&&this.preloadRoute(p).catch((t=>{console.warn(t),console.warn("Error preloading route! ☝️")}))},handleClick:t=>{d||function(t){return!!(t.metaKey||t.altKey||t.ctrlKey||t.shiftKey)}(t)||t.defaultPrevented||a&&"_self"!==a||0!==t.button||(t.preventDefault(),this.#c(p))},handleEnter:t=>{const e=t.target||{};if(c){if(e.preloadTimeout)return;e.preloadTimeout=setTimeout((()=>{e.preloadTimeout=null,this.preloadRoute(p).catch((t=>{console.warn(t),console.warn("Error preloading route! ☝️")}))}),m)}},handleLeave:t=>{const e=t.target||{};e.preloadTimeout&&(clearTimeout(e.preloadTimeout),e.preloadTimeout=null)},isActive:(i?.exact?y:v)&&(!i?.includeHash||w),disabled:d}};dehydrate=()=>({state:{...g(this.store.state,["latestLocation","currentLocation","status","lastUpdated"]),currentMatches:this.store.state.currentMatches.map((t=>({id:t.id,state:{...g(t.store.state,["status"])}})))},context:this.options.context});hydrate=t=>{this.store.setState((e=>{this.options.context=t.context;const r=this.matchRoutes(t.state.latestLocation.pathname,{strictParseParams:!0});return r.forEach(((e,r)=>{const s=t.state.currentMatches[r];n(s&&s.id===e.id),e.store.setState((t=>({...t,...s.state})))})),r.forEach((t=>t.__validate())),{...e,...t.state,currentMatches:r}}))};#n=t=>{const e=(t,r)=>t.map(((t,s)=>{const o=t.options,a=new A(t,o,s,r,this);if(this.routesById[a.id])throw new Error;this.routesById[a.id]=a;const n=t.children;return a.childRoutes=n.length?e(n,a):void 0,a}));return e([t])[0]};#a=t=>{let{pathname:e,search:r,hash:s,state:o}=this.history.location;const a=this.options.parseSearch(r);return{pathname:e,searchStr:r,search:v(t?.search,a),hash:s.split("#").reverse()[0]??"",href:`${e}${r}${s}`,state:o,key:o?.key||"__init__"}};#o=()=>{this.load()};#i=(t={})=>{const e=t.fromCurrent?this.store.state.latestLocation.pathname:t.from??this.store.state.latestLocation.pathname;let r=_(this.basepath??"/",e,`${t.to??"."}`);const s=this.matchRoutes(this.store.state.latestLocation.pathname,{strictParseParams:!0}),o=this.matchRoutes(r),a={...f(s)?.params};let n=!0===(t.params??!0)?a:y(t.params,a);n&&o.map((t=>t.route.options.stringifyParams)).filter(Boolean).forEach((t=>{Object.assign({},n,t(n))})),r=x(r,n??{});const i=t.__preSearchFilters?.length?t.__preSearchFilters?.reduce(((t,e)=>e(t)),this.store.state.latestLocation.search):this.store.state.latestLocation.search,c=!0===t.search?i:t.search?y(t.search,i)??{}:t.__preSearchFilters?.length?i:{},h=t.__postSearchFilters?.length?t.__postSearchFilters.reduce(((t,e)=>e(t)),c):c,u=v(this.store.state.latestLocation.search,h),l=this.options.stringifySearch(u);let d=!0===t.hash?this.store.state.latestLocation.hash:y(t.hash,this.store.state.latestLocation.hash);return d=d?`#${d}`:"",{pathname:r,search:u,searchStr:l,state:this.store.state.latestLocation.state,hash:d,href:`${r}${l}${d}`,key:t.key}};#c=t=>{const e=this.buildNext(t),r=""+Date.now()+Math.random();this.navigateTimeout&&clearTimeout(this.navigateTimeout);let s="replace";t.replace||(s="push");this.store.state.latestLocation.href===e.href&&!e.key&&(s="replace");const o=`${e.pathname}${e.searchStr}${e.hash?`#${e.hash}`:""}`;return this.history["push"===s?"push":"replace"](o,{id:r,...e.state}),this.navigationPromise=new Promise((t=>{const e=this.resolveNavigation;this.resolveNavigation=()=>{e(),t()}}))}}const W="undefined"==typeof window||!window.document.createElement;function K(){return{status:"idle",latestLocation:null,currentLocation:null,currentMatches:[],lastUpdated:Date.now()}}function G(t,e=(t=>t),s){return r.useSyncExternalStoreWithSelector(t.subscribe,(()=>t.state),(()=>t.state),e,s?J:void 0)}function J(t,e){if(Object.is(t,e))return!0;if("object"!=typeof t||null===t||"object"!=typeof e||null===e)return!1;const r=Object.keys(t);if(r.length!==Object.keys(e).length)return!1;for(let s=0;s<r.length;s++)if(!Object.prototype.hasOwnProperty.call(e,r[s])||!Object.is(t[r[s]],e[r[s]]))return!1;return!0}function V(t){const e=Z(),{type:r,children:s,target:a,activeProps:n=(()=>({className:"active"})),inactiveProps:i=(()=>({})),activeOptions:c,disabled:h,hash:u,search:l,params:d,to:p=".",preload:f,preloadDelay:m,preloadMaxAge:g,replace:v,style:w,className:b,onClick:S,onFocus:L,onMouseEnter:E,onMouseLeave:P,onTouchStart:R,onTouchEnd:_,...M}=t,x=e.buildLink(t);if("external"===x.type){const{href:t}=x;return{href:t}}const{handleClick:C,handleFocus:k,handleEnter:O,handleLeave:j,isActive:$,next:A}=x,F=t=>e=>{e.persist&&e.persist(),t.filter(Boolean).forEach((t=>{e.defaultPrevented||t(e)}))},T=$?y(n,{})??{}:{},I=$?{}:y(i,{})??{};return{...T,...I,...M,href:h?void 0:A.href,onClick:F([S,t=>{o.startTransition?o.startTransition((()=>{C(t)})):C(t)}]),onFocus:F([L,k]),onMouseEnter:F([E,O]),onMouseLeave:F([P,j]),target:a,style:{...w,...T.style,...I.style},className:[b,T.className,I.className].filter(Boolean).join(" ")||void 0,...h?{role:"link","aria-disabled":!0}:void 0,"data-status":$?"active":void 0}}const Q=o.forwardRef(((t,e)=>{const r=V(t);return o.createElement("a",a({ref:e},r,{children:"function"==typeof t.children?t.children({isActive:"active"===r["data-status"]}):t.children}))})),X=o.createContext(null),Y=o.createContext(null);function Z(){const t=o.useContext(Y);return m(!t,"useRouter must be used inside a <Router> component!"),t.router}function tt(){return o.useContext(X)}function et(t){const e=Z(),r=tt()[0],s=t?.from?e.store.state.currentMatches.find((e=>e.route.id===t?.from)):r;return n(s,t?.from&&t.from),(t?.strict??1)&&n(r.route.id==s?.route.id,(s?.route.id,r.route.id,s?.route.id,s?.route.id)),G(s.store,(e=>t?.track?.(s)??s),t?.shallow),s}function rt(){const t=Z();return e=>{const{pending:r,caseSensitive:s,...o}=e;return t.matchRoute(o,{pending:r,caseSensitive:s})}}function st(){const t=tt().slice(1),e=t[0];return e?o.createElement(ot,{matches:t,match:e}):null}function ot({matches:t,match:e}){const r=Z();G(e.store);const s=o.useCallback((()=>null),[]),a=o.useCallback((t=>{if("error"===t.match.store.state.status)throw t.match.store.state.error;if("success"===t.match.store.state.status)return o.createElement(t.match.component??r.options.defaultComponent??st);if("pending"===t.match.store.state.status)throw t.match.__loadPromise;n(!1)}),[]),i=e.pendingComponent??r.options.defaultPendingComponent??s,c=e.errorComponent??r.options.defaultErrorComponent;return o.createElement(X.Provider,{value:t},o.createElement(o.Suspense,{fallback:o.createElement(i,null)},o.createElement(at,{key:e.route.id,errorComponent:c,match:e},o.createElement(a,{match:e}))))}class at extends o.Component{state={error:!1,info:void 0};componentDidCatch(t,e){console.error(`Error in route match: ${this.props.match.id}`),console.error(t),this.setState({error:t,info:e})}render(){return o.createElement(nt,a({},this.props,{errorState:this.state,reset:()=>this.setState({})}))}}function nt(t){const[e,r]=o.useState(t.errorState),s=Z(),a=t.errorComponent??it,n=o.useRef("");return o.useEffect((()=>{e&&s.store.state.currentLocation.key!==n.current&&r({}),n.current=s.store.state.currentLocation.key}),[e,s.store.state.currentLocation.key]),o.useEffect((()=>{t.errorState.error&&r(t.errorState)}),[t.errorState.error]),t.errorState.error&&e.error?o.createElement(a,e):t.children}function it({error:t}){return o.createElement("div",{style:{padding:".5rem",maxWidth:"100%"}},o.createElement("strong",{style:{fontSize:"1.2rem"}},"Something went wrong!"),o.createElement("div",{style:{height:".5rem"}}),o.createElement("div",null,o.createElement("pre",null,t.message?o.createElement("code",{style:{fontSize:".7em",border:"1px solid red",borderRadius:".25rem",padding:".5rem",color:"red"}},t.message):null)))}t.DefaultErrorBoundary=it,t.Link=Q,t.MatchRoute=function(t){const e=rt()(t);return e?"function"==typeof t.children?t.children(e):e?t.children:null:null},t.Outlet=st,t.ReactRouter=class extends q{constructor(t){super({...t,loadComponent:async t=>(t.preload&&await t.preload(),t)})}},t.Route=A,t.RouteMatch=D,t.Router=q,t.RouterProvider=function({router:t,...e}){t.update(e);const r=G(t.store,(t=>t.currentMatches),void 0);return o.useEffect(t.mount,[t]),o.createElement(o.Fragment,null,o.createElement(Y.Provider,{value:{router:t}},o.createElement(X.Provider,{value:[void 0,...r]},o.createElement(st,null))))},t.cleanPath=L,t.createBrowserHistory=u,t.createHashHistory=function(){return u({getHref:()=>window.location.hash.substring(1),createHref:t=>`#${t}`})},t.createMemoryHistory=l,t.createRouteConfig=T,t.decode=$,t.defaultFetchServerDataFn=U,t.defaultParseSearch=N,t.defaultStringifySearch=B,t.encode=O,t.functionalUpdate=y,t.interpolatePath=x,t.invariant=n,t.isPlainObject=w,t.joinPaths=S,t.last=f,t.lazy=function(t){const e=o.lazy(t);return e.preload=async()=>{await t()},e},t.matchByPath=k,t.matchPathname=C,t.matchesContext=X,t.parsePathname=M,t.parseSearchWith=H,t.pick=g,t.replaceEqualDeep=v,t.resolvePath=_,t.rootRouteId=F,t.routerContext=Y,t.stringifySearchWith=z,t.trimPath=R,t.trimPathLeft=E,t.trimPathRight=P,t.useLinkProps=V,t.useMatch=et,t.useMatchRoute=rt,t.useMatches=tt,t.useNavigate=function(t){const e=Z();return r=>e.navigate({...t,...r})},t.useParams=function(t){const e=Z();return G(e.store,(e=>{const r=f(e.currentMatches)?.params;return t?.track?.(r)??r})),f(e.store.state.currentMatches)?.params},t.useRoute=function(t){const e=Z().getRoute(t);return n(e),e},t.useRouter=Z,t.useRouterStore=function(t,e){return G(Z().store,t,e)},t.useSearch=function(t){const e=et(t);return G(e.store,(e=>t?.track?.(e.search)??e.search)),e.store.state.search},t.useStore=G,t.warning=m,Object.defineProperty(t,"__esModule",{value:!0})}));
|
|
23
42
|
//# sourceMappingURL=index.production.js.map
|