@tanstack/react-location-lite-experimental
Version:
13 lines (12 loc) • 12.9 kB
JavaScript
/**
* react-location-lite-experimental
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("history")):"function"==typeof define&&define.amd?define(["exports","react","history"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactLocationLite={},e.React,e.History)}(this,(function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var a=n(t);function o(){return o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},o.apply(this,arguments)}function s(e,t){if(null==e)return{};var r,n,a={},o=Object.keys(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||(a[r]=e[r]);return a}function i(e){if(!e)return"";var t=decodeURIComponent(e);return"false"!==t&&("true"===t||(0*+t==0?+t:t))}const c=["children","location","routes","basepath"],u=["to","search","hash","children","target","style","replace","onClick","onMouseEnter","className","getActiveProps","getInactiveProps","activeOptions","disabled","_ref"],l=["style","className"],h=["style","className"],f=["children"],p=a.createContext(null),d=a.createContext(null),m=a.createContext(null),y=Boolean("undefined"!=typeof window&&window.document&&window.document.createElement),v=y?a.useLayoutEffect:a.useEffect;function g(e){return a.createElement(d.Provider,e)}function b(){const e=S(),t=_(),r=j();return v((()=>{t({to:".",search:!0,hash:!0}).href!==e.current.href&&r({to:".",search:!0,hash:!0,fromCurrent:!0,replace:!0})}),[]),null}function S(){const e=a.useContext(p);return N(!!e,"useLocation must be used within a <ReactLocation />"),e.location}function w(){const e=a.useContext(m);if(!e)throw N(!0,"You are trying to use useRouter() outside of ReactLocation!"),new Error;return e}function P(e,t){if(!e.routes.length)return[];const r=[],n=(a,s)=>{var i;let{pathname:c,params:u}=s;const l=(null!=e&&e.filterRoutes?null==e?void 0:e.filterRoutes(a):a).find((r=>{var n,a;const s=B([c,r.path]),i=!!("/"!==r.path||null!=(n=r.children)&&n.length),l=C(t,{to:s,search:r.search,fuzzy:i,caseSensitive:null!=(a=r.caseSensitive)?a:e.caseSensitive});return l&&(u=o({},u,l)),!!l}));if(!l)return;const h=E(l.path,u);c=B([c,h]);const f={id:E(l.id,u,!0),route:l,params:u,pathname:c,search:t.search};r.push(f),null!=(i=l.children)&&i.length&&n(l.children,f)};return n(e.routes,e.rootMatch),r}function E(e,t,r){return B(I(e).map((e=>{return"*"!==e.value||r?"param"===e.type?null!=(n=t[e.value.substring(1)])?n:"":e.value:"";var n})))}function O(){return a.useContext(d)}function R(){var e;return null==(e=O())?void 0:e[0]}function j(){const e=S(),t=R(),r=_();return T((function(n){var a;let{search:o,hash:s,replace:i,from:c,to:u,fromCurrent:l}=n;l=null!=(a=l)?a:void 0===u;const h=r({to:u,search:o,hash:s,from:l?e.current:null!=c?c:{pathname:t.pathname}});e.navigate(h,i)}))}function _(){const e=S(),t=w();return T((r=>{const n=e.buildNext(t.basepath,r),a=P(t,n),s=a.map((e=>{var t;return null!=(t=e.route.preSearchFilters)?t:[]})).flat().filter(Boolean),i=a.map((e=>{var t;return null!=(t=e.route.postSearchFilters)?t:[]})).flat().filter(Boolean);return e.buildNext(t.basepath,o({},r,{__preSearchFilters:s,__postSearchFilters:i}))}))}function k(){var e,t;const r=w(),[n,...o]=O(),s=o[0];if(!s)return null;const i=null!=(e=s.route.element)?e:r.defaultElement,c=a.createElement(g,{value:o},null!=i?i:a.createElement(k,null)),u=null!=(t=s.route.pendingElement)?t:r.defaultPendingElement;return u?a.createElement(a.Suspense,{fallback:u},c):c}function x(){const e=w(),t=R();return T((r=>U(e.basepath,t.pathname,A(r))))}function C(e,t){const r=F(e,t),n=function(e,t){return!(!t.search||!t.search(e.search))}(e,t);if((!t.to||r)&&(!t.search||n))return null!=r?r:{}}function L(){const e=w(),t=x();return T((r=>(r=o({},r,{to:r.to?t(""+r.to):void 0}),C(e.state.location,r))))}function M(e,t){const r=S();a.useEffect((()=>{if(!t)return;let n=r.history.block((t=>{window.confirm(e)?(n(),t.retry()):r.current.pathname=window.location.pathname}));return n}),[t,r,e])}function N(e,t){if(!e){"undefined"!=typeof console&&console.warn(t);try{throw new Error(t)}catch(e){}}}function H(e,t){return"function"==typeof e?e(t):e}function B(e){return A(e.filter(Boolean).join("/"))}function A(e){return(""+e).replace(/\/{2,}/g,"/")}function F(e,t){var r;const n=I(e.pathname),a=I(""+(null!=(r=t.to)?r:"*")),o={};return(()=>{for(let e=0;e<Math.max(n.length,a.length);e++){const r=n[e],s=a[e],i=e===a.length-1,c=e===n.length-1;if(s){if("wildcard"===s.type)return!(null==r||!r.value)&&(o["*"]=B(n.slice(e).map((e=>e.value))),!0);if("pathname"===s.type){if("/"===s.value&&(null==r||!r.value))return!0;if(r)if(t.caseSensitive){if(s.value!==r.value)return!1}else if(s.value.toLowerCase()!==r.value.toLowerCase())return!1}if(!r)return!1;"param"===s.type&&(o[s.value.substring(1)]=r.value)}if(i&&!c)return!!t.fuzzy}return!0})()?o:void 0}function I(e){if(!e)return[];const t=[];if("/"===(e=A(e)).slice(0,1)&&(e=e.substring(1),t.push({type:"pathname",value:"/"})),!e)return t;const r=e.split("/").filter(Boolean);return t.push(...r.map((e=>e.startsWith("*")?{type:"wildcard",value:e}:":"===e.charAt(0)?{type:"param",value:e}:{type:"pathname",value:e}))),"/"===e.slice(-1)&&(e=e.substring(1),t.push({type:"pathname",value:"/"})),t}function U(e,t,r){t=t.replace(new RegExp("^"+e),"/"),r=r.replace(new RegExp("^"+e),"/");let n=I(t);const a=I(r);a.forEach(((e,t)=>{if("/"===e.value)t?t===a.length-1&&n.push(e):n=[e];else if(".."===e.value)n.pop();else{if("."===e.value)return;n.push(e)}}));return A(B([e,...n.map((e=>e.value))]))}function T(e){const t=a.useRef(),r=a.useRef(e);return r.current=e,t.current||(t.current=function(){return r.current(...arguments)}),t.current}function z(e,t){if(e===t)return e;const r=Array.isArray(e)&&Array.isArray(t);if(r||K(e)&&K(t)){const n=r?e.length:Object.keys(e).length,a=r?t:Object.keys(t),o=a.length,s=r?[]:{};let i=0;for(let n=0;n<o;n++){const o=r?n:a[n];s[o]=z(e[o],t[o]),s[o]===e[o]&&i++}return n===o&&i===n?e:s}return t}function K(e){if(!W(e))return!1;const t=e.constructor;if(void 0===t)return!0;const r=t.prototype;return!!W(r)&&!!r.hasOwnProperty("isPrototypeOf")}function W(e){return"[object Object]"===Object.prototype.toString.call(e)}const q=J(JSON.parse),D=$(JSON.stringify);function J(e){return t=>{"?"===t.substring(0,1)&&(t=t.substring(1));let r=function(e){for(var t,r,n={},a=e.split("&");t=a.shift();)void 0!==n[r=(t=t.split("=")).shift()]?n[r]=[].concat(n[r],i(t.shift())):n[r]=i(t.shift());return n}(t);for(let t in r){const n=r[t];if("string"==typeof n)try{r[t]=e(n)}catch(e){}}return r}}function $(e){return t=>{(t=o({},t))&&Object.keys(t).forEach((r=>{const n=t[r];if(void 0===n||void 0===n)delete t[r];else if(n&&"object"==typeof n&&null!==n)try{t[r]=e(n)}catch(e){}}));const r=function(e,t){var r,n,a,o="";for(r in e)if(void 0!==(a=e[r]))if(Array.isArray(a))for(n=0;n<a.length;n++)o&&(o+="&"),o+=encodeURIComponent(r)+"="+encodeURIComponent(a[n]);else o&&(o+="&"),o+=encodeURIComponent(r)+"="+encodeURIComponent(a);return(t||"")+o}(t);return r?"?"+r:""}}Object.defineProperty(e,"createBrowserHistory",{enumerable:!0,get:function(){return r.createBrowserHistory}}),Object.defineProperty(e,"createHashHistory",{enumerable:!0,get:function(){return r.createHashHistory}}),Object.defineProperty(e,"createMemoryHistory",{enumerable:!0,get:function(){return r.createMemoryHistory}}),e.Link=function(e){let{to:t=".",search:r,hash:n,children:i,target:c,style:f={},replace:p,onClick:d,className:m="",getActiveProps:y=(()=>({className:"active"})),getInactiveProps:v=(()=>({})),activeOptions:g,disabled:b,_ref:w}=e,P=s(e,u);const E=R(),O=S(),k=j(),x=_();try{N(!1,"<Link /> should not be used for external URLs like: "+new URL(""+t).href)}catch(e){}const C=x({to:t,search:r,hash:n,from:{pathname:E.pathname}}),L=O.current.pathname===C.pathname,M=O.current.pathname.split("/"),H=C.pathname.split("/").every(((e,t)=>e===M[t])),B=O.current.hash===C.hash,A=null!=g&&g.exact?L:H,F=null==g||!g.includeHash||B,I=A&&F,U=I?y():{},{style:T={},className:z=""}=U,K=s(U,l),W=I?{}:v(),{style:q={},className:D=""}=W,J=s(W,h);return a.createElement("a",o({ref:w,href:b?void 0:C.href,onClick:e=>{d&&d(e),function(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}(e)||e.defaultPrevented||c&&"_self"!==c||0!==e.button||(e.preventDefault(),k({to:t,search:r,hash:n,replace:p,from:{pathname:E.pathname}}))},target:c,style:o({},f,T,q),className:[m,z,D].filter(Boolean).join(" ")||void 0},b?{role:"link","aria-disabled":!0}:void 0,P,K,J,{children:"function"==typeof i?i({isActive:I}):i}))},e.MatchRoute=function(e){let{children:t}=e,r=s(e,f);const n=L()(r);return"function"==typeof t?t(n):n?t:null},e.MatchesProvider=g,e.Navigate=function(e){let t=j();return v((()=>{t(e)}),[t]),null},e.Outlet=k,e.Prompt=function(e){let{message:t,when:r,children:n}=e;return M(t,null==r||r),null!=n?n:null},e.ReactLocation=class{constructor(e){var t,n;this.listeners=[],this.isTransitioning=!1,this.history=(null==e?void 0:e.history)||(y?r.createBrowserHistory():r.createMemoryHistory()),this.stringifySearch=null!=(t=null==e?void 0:e.stringifySearch)?t:D,this.parseSearch=null!=(n=null==e?void 0:e.parseSearch)?n:q,this.current=this.parseLocation(this.history.location),this.destroy=this.history.listen((e=>{this.current=this.parseLocation(e.location,this.current),this.notify()}))}subscribe(e){return this.listeners.push(e),()=>{this.listeners=this.listeners.filter((t=>t!==e))}}notify(){this.listeners.forEach((e=>e()))}buildNext(e,t){var r,n,a,s,i;void 0===e&&(e="/"),void 0===t&&(t={});const c=o({},this.current,t.from),u=U(e,c.pathname,""+(null!=(r=t.to)?r:".")),l=null!=(n=t.__preSearchFilters)&&n.length?t.__preSearchFilters.reduce(((e,t)=>t(e)),c.search):c.search,h=!0===t.search?l:t.search?null!=(a=H(t.search,l))?a:{}:null!=(s=t.__preSearchFilters)&&s.length?l:{},f=null!=(i=t.__postSearchFilters)&&i.length?t.__postSearchFilters.reduce(((e,t)=>t(e)),h):h,p=z(c.search,f),d=this.stringifySearch(p);let m=!0===t.hash?c.hash:H(t.hash,c.hash);return m=m?"#"+m:"",{pathname:u,search:p,searchStr:d,hash:m,href:""+u+d+m,key:t.key}}navigate(e,t){this.current=e,this.navigateTimeout&&clearTimeout(this.navigateTimeout);let r="replace";t||(r="push");return this.parseLocation(this.history.location).href===this.current.href&&!this.current.key&&(r="replace"),"replace"===r?this.history.replace({pathname:this.current.pathname,hash:this.current.hash,search:this.current.searchStr}):this.history.push({pathname:this.current.pathname,hash:this.current.hash,search:this.current.searchStr})}parseLocation(e,t){var r;const n=this.parseSearch(e.search);return{pathname:e.pathname,searchStr:e.search,search:z(null==t?void 0:t.search,n),hash:null!=(r=e.hash.split("#").reverse()[0])?r:"",href:""+e.pathname+e.search+e.hash,key:e.key}}},e.Router=function(e){let{children:t,location:r,routes:n,basepath:i}=e,u=s(e,c);const l=A("/"+(null!=i?i:"")),[h,f]=a.useState({location:r.current,matches:[]}),d=a.useMemo((()=>({id:"root",params:{},search:{},pathname:l,route:null})),[l]),y=a.useMemo((()=>{const e={},t=(r,n)=>r.map((r=>{var a,s;const i=null!=(a=r.path)?a:"*",c=B(["root"===(null==n?void 0:n.id)?"":null==n?void 0:n.id,(null==i?void 0:i.replace(/(.)\/$/,"$1"))+(r.id?"-"+r.id:"")]);if(r=o({},r,{id:c}),e[c])throw new Error;return e[c]=r,r.children=null!=(s=r.children)&&s.length?t(r.children,r):void 0,r}));return n=t(n),o({},u,{routesById:e,routes:n,basepath:l,rootMatch:d,state:h})}),[h,d,l]);return v((()=>{const e=()=>{const e=P(y,r.current);f((()=>({location:r.current,matches:e})))};return e(),r.subscribe(e)}),[r]),a.createElement(p.Provider,{value:{location:r}},a.createElement(m.Provider,{value:y},a.createElement(b,null),a.createElement(g,{value:[y.rootMatch,...y.state.matches]},null!=t?t:a.createElement(k,null))))},e.cleanPath=A,e.defaultParseSearch=q,e.defaultStringifySearch=D,e.functionalUpdate=H,e.matchByPath=F,e.matchRoute=C,e.matchRoutes=P,e.parsePathname=I,e.parseSearchWith=J,e.resolvePath=U,e.stringifySearchWith=$,e.useLocation=S,e.useMatch=R,e.useMatchRoute=L,e.useMatches=O,e.useNavigate=j,e.useParentMatches=function(){const e=w(),t=R(),r=e.state.matches;return r.slice(0,r.findIndex((e=>e.id===t.id))-1)},e.usePrompt=M,e.useResolvePath=x,e.useRouter=w,e.useSearch=function(){return S().current.search},Object.defineProperty(e,"__esModule",{value:!0})}));
//# sourceMappingURL=index.production.min.js.map