UNPKG

vicowa-web-components

Version:
2 lines 2.67 kB
const t=Symbol("privateData");function e(t,e){!t.url||e.history.state&&t.url===e.history.state.url||(e.history.state||e.history.replaceState({url:t.url,customData:t.customData},t.title,t.url),e.history.pushState({url:t.url,customData:t.customData},t.title,t.url))}function n(t,n,s){const{routes:a,notFoundHandler:o,targetWindow:r}=t,l=new RegExp(`^${document.location.origin}`),i=(n=n.replace(l,"").replace(/[/]+/g,"/")).split("?"),u=i[0].split("/");let c;const h=a.find((t=>t.destinations.every(((t,e,n)=>{let s=!1;return s=t.slash?""===u[e]:t.regExp?t.regExp.test(u[e]):t.optional?u.length===e||u.length===e-1:t.all?u.length-1>=e:t.name?e===n.length-1&&u.length===n.length||u.length-1>e&&n.length-1>e:u.length-1===e,s}))));if(i.length>1){c=i[1].split("&").reduce(((t,e)=>{const n=e.split("=").map((t=>t.trim()));return t[n[0]]=n[1],t}),{})}if(h){const t=h.destinations.reduce(((t,e,n)=>{if(u.length)if(n<h.destinations.length-1){const n=u.shift();e.name&&(t.params[e.name]=n)}else t.params[e.name||0]=u.join("/");return t}),{params:{},url:n,query:c,customData:s}),a=[...h.callbacks],o=async n=>{n&&(n.length>1?await n(t,(async()=>{a.length&&(await o(a.shift()),a.length||e(t,r))})):(await n(t),e(t,r)))};o(a.shift())}else o&&o({url:n,query:c,customData:s})}class Router{constructor(e=window){this[t]={routes:[],notFoundHandler:void 0,targetWindow:e};const s=e=>{const s=this[t];delete s.url,delete s.title,e&&e.url?(s.title=e.title,s.url=e.url,s.customData=e.customData):s.targetWindow.history.state&&(s.title=s.targetWindow.history.state.title,s.url=s.targetWindow.history.state.url,s.customData=s.targetWindow.history.state.customData),s.url?n(s,s.url,s.customData):document.location.href&&n(s,document.location.href,null)};s(e.history.state),e.addEventListener("popstate",(t=>{s(t.state)})),e.addEventListener("load",(()=>{this.goTo(document.location.href)}))}set onNotFound(e){this[t].notFoundHandler=e}get onNotFound(){return this[t].notFoundHandler}addRoute(e,...n){this[t].routes.push(function(t,e){return{destinations:(t=t.replace(/[/]+/g,"/")).split("/").map((t=>{const e={};return/^:/.test(t)?/\(\.\*\)$/.test(t)?(e.name=t.substring(1,t.length-4),e.all=!0):/\?$/.test(t)?(e.name=t.substring(1,t.length-1),e.optional=!0):e.name=t.substring(1):/\*/.test(t)?/^\*/.test(t)?e.all=!0:(e.wildcard=!0,e.regExp=new RegExp(`^${t.replace(/\./g,"\\.").replace("*",".*")}$`)):t?e.regExp=new RegExp(`^${t}$`):e.slash=!0,e})),callbacks:e}}(e,n))}goTo(e,s){n(this[t],e,s)}clearRoutes(){this[t].routes=[]}}const s=new Map;export function getRouter(t){return s.has(t)||s.set(t,new Router(t)),s.get(t)}export function removeRouter(t){s.delete(t)} //# sourceMappingURL=route.js.map