@tanstack/react-router 0.0.1-beta.53 → 0.0.1-beta.54
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.
|
@@ -19,5 +19,5 @@
|
|
|
19
19
|
*
|
|
20
20
|
* @license MIT
|
|
21
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=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})}));
|
|
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})}));
|
|
23
23
|
//# sourceMappingURL=index.production.js.map
|