UNPKG

pinecone-router

Version:

The feature-packed router for Alpine.js.

5 lines (3 loc) 8.38 kB
(()=>{var $1=(b)=>`Invalid expression type. Expression: ${b}`,x=(b)=>`Can't find an element with target ID: ${b}`,g=(b)=>`Route already exists: ${b}`;var Q1=(b)=>`x-${b} must be used on the same template as x-route`,c="targetID must be specified for programmatically added templates",m=(b)=>`Path: ${b} was not found`;function _(b){if(b.tagName.toLowerCase()!=="template")throw new TypeError("Directives can only be used on template elements.")}function N(b){if(_(b),b._x_PineconeRouter_route===void 0)throw new TypeError(Q1("template"))}function O(b){if(typeof b!="object"||!Array.isArray(b))throw new TypeError($1(b))}var $={hash:!1,basePath:"",globalHandlers:[],handleClicks:!0,targetID:void 0,preload:!1,fetchOptions:{},pushState:!0},d=(b)=>{return $={...$,...b},$};var h=(b,j,J)=>{if(b.indexOf(j)===-1)return J;let z=b[b.indexOf(j)+1];if(!z)return J;if(j==="target"){let Z=z.match(/([a-z0-9_-]+)/);if(Z)return Z[1]}return z},B=(b)=>{if(b=="notfound"||$.hash)return b;if(!b.startsWith($.basePath))b=$.basePath+b;return b},w=(b)=>{return/^\[.*\]$|^Array\(.*\)$/.test(b.trim())},u=(b,j)=>{let J=b??j??"",z=document.getElementById(J);if(J&&!z)throw new ReferenceError(x(J));return z??void 0};var S=new Set,T=new Map,y=new Map,P=new Set,p=(b,j)=>{document.dispatchEvent(new CustomEvent("pinecone:fetch-error",{detail:{error:b,url:j}}))},n=(b,j,J,z,Z)=>{let H=j.id+J;if(S.has(H))return;S.add(H);let Q=j.content,Y=Array(Q.childElementCount);Q.querySelectorAll("script").forEach((K)=>{let G=document.createElement("script");Array.from(K.attributes).forEach((W)=>G.setAttribute(W.name,W.value)),G.textContent=K.textContent,K.parentNode?.replaceChild(G,K)});let M=Array.from(Q.children);for(let K=0;K<M.length;K++)Y[K]=M[K].cloneNode(!0),b.addScopeToNode(Y[K],{},j);b.mutateDom(()=>{if(z)z.replaceChildren(...Y);else j.after(...Y);Y.forEach((K)=>{b.initTree(K)})}),j._x_PineconeRouter_template=Y,j._x_PineconeRouter_templateUrls=Z,j._x_PineconeRouter_undoTemplate=()=>{b.mutateDom(()=>{Y.forEach((K)=>{b.destroyTree(K),K.remove()})}),delete j._x_PineconeRouter_template},b.nextTick(()=>S.delete(H))},E=(b)=>{if(b._x_PineconeRouter_undoTemplate)b._x_PineconeRouter_undoTemplate(),delete b._x_PineconeRouter_undoTemplate},o=async(b,j,J,z,Z)=>{if(j._x_PineconeRouter_templateUrls!=null&&j._x_PineconeRouter_templateUrls!=z)E(j),j.innerHTML="";if(j._x_PineconeRouter_template)return;if(j.content.childElementCount){n(b,j,J,Z,z);return}if(z)return I(z,j).then(()=>n(b,j,J,Z,z))},D=(b,j)=>{return b.map((J)=>J.replace(/:([^/.]+)/g,(z,Z)=>j[Z]||Z))},i=async(b,j="high")=>{if(b=B(b),T.has(b))return T.get(b);if(y.has(b))return y.get(b);let J=fetch(b,{...$.fetchOptions,priority:j}).then((z)=>{if(!z.ok)return p(z.statusText,b),"";return z.text()}).then((z)=>{if(z)T.set(b,z);return y.delete(b),z||""}).catch((z)=>{if(z instanceof TypeError)p(z.message,b);return""});return y.set(b,J),J},k=(b,j)=>{P.add({urls:b,el:j})},s=()=>{for(let b of P){if(b.el)I(b.urls,b.el,"low");else b.urls.map((j)=>i(j,"low"));P.delete(b)}},I=(b,j,J="high")=>Promise.all(b.map((z)=>i(z,J))).then((z)=>{j.innerHTML=z.join("")});var Y1=(b,j)=>{b.directive("template",(J,{expression:z,modifiers:Z},{evaluate:H,cleanup:Q,Alpine:Y,effect:M})=>{N(J);let K=u(h(Z,"target"),$.targetID),G=J._x_PineconeRouter_route,W,q=Z.includes("interpolate");if(z!=""){if(!w(z))z=`['${z}']`;let F=H(z);if(O(F),W=F,!q&&($.preload||Z.includes("preload")))k(W,J);let C=j.routes.get(G);C.templates=W}let V=(F)=>{if(j.context.route?.path===G){if(F&&q)F=D(F,j.context.params);o(Y,J,z,F,K).then(()=>{j.loading=!1})}else E(J)},X=M(()=>V(W));Q(()=>{J._x_PineconeRouter_undoTemplate&&J._x_PineconeRouter_undoTemplate(),Y.release(X)})})},a=Y1;var G1=(b,j)=>{b.directive("handler",(J,{expression:z,modifiers:Z},{evaluate:H,cleanup:Q})=>{if(!w(z))z=`[${z}]`;let Y=H(z);O(Y);let M=Y;for(let G=0;G<M.length;G++)M[G]=M[G].bind(b.$data(J));let K;if(Z.includes("global"))$.globalHandlers=M;else{N(J);let G=J._x_PineconeRouter_route;K=j.routes.get(G),K.handlers=M}Q(()=>{if(Z.includes("global"))$.globalHandlers=[];else K.handlers=[]})}).before("template")},l=G1;var H1=(b,j)=>{b.directive("route",(J,{expression:z,value:Z},{cleanup:H})=>{let Q=$.hash?z:B(z);if(_(J),Q!="notfound")j.add(Q,{name:Z});J._x_PineconeRouter_route=Q,H(()=>{j.routes.delete(Q),delete J._x_PineconeRouter_route})}).before("handler")},r=H1;var t=()=>{return{entries:[],index:0,canGoBack:function(){return this.index>0},back:function(){this.to(this.index-1)},canGoForward:function(){return this.index<this.entries.length-1},forward:function(){this.to(this.index+1)},to:function(b){if(b in this.entries)this.router?.navigate(this.entries[b],!1,!1,b)},push:function(b,j){if(this.index<this.entries.length-1)this.entries=this.entries.slice(0,this.index+1);if(this.entries.push(b),this.index=this.entries.length-1,j)this.pushState(b)},pushState:function(b){if(!$.pushState)return;let j=$.hash&&!b.startsWith("#")?"#"+b:b,J={path:j};history.pushState(J,"",j)},setRouter(b){this.router=b}}};var M1=(b,{targetID:j,templates:J=[],handlers:z=[],interpolate:Z=!1,name:H}={})=>({programmaticTemplates:J.length>0,pattern:W1(b),interpolate:Z,templates:J,targetID:j,handlers:z,name:H||b,path:b,match(Q){let Y=this.pattern.exec(Q);if(Y)return{...Y.groups}}});function W1(b){let J=b.split("/").filter(Boolean).map((z)=>{if(!z.startsWith(":"))return"/"+z;let[,Z,H,Q]=z.match(/^:(\w+)([?+*]?)(?:\.(.+))?$/)||[],Y=H==="*"||H==="+",M=H==="?"||H==="*",G=`(?<${Z}>${Y?M?".*?":".+":"[^/]+?"})`,W=Q?`\\.${Q}`:"",q=G+W;if(M)return`(?:/${q})?`;return`/${q}`}).join("");return new RegExp(`^${J}/?$`,"i")}var f=M1;var R=(b,j,J)=>{return{path:b,params:j,route:J}};async function e(b,j,J){let z;return new Promise(async(Z,H)=>{J.signal.addEventListener("abort",()=>H());for(let Q of b){if(J.signal.aborted)return;let Y={...j,data:z};try{z=await Q(Y,J)}catch(M){H(M)}}Z()})}var b1=(b,j,J)=>{let z=f("notfound",{handlers:[(K)=>console.error(new ReferenceError(m(K.path)))],name:"notfound"}),Z=new Map([["notfound",z]]),H=R(J,{}),Q=null,Y=!1,M={name:b,version:j,history:t(),routes:Z,context:H,get loading(){return Y},set loading(K){if(Y==K)return;Y=K,document.dispatchEvent(new Event(K?"pinecone:start":"pinecone:end"))},settings:(K)=>d(K),add:function(K,G){if(K!="notfound"){if(!$.hash)K=B(K);if(this.routes.has(K))throw new Error(g(K))}if(G.templates&&($.preload||G.preload))k(G.templates);this.routes.set(K,f(K,G))},remove:function(K){this.routes.delete(K)},navigate:async function(K,G,W,q){if(Q)Q.abort();Q=new AbortController,this.loading=!0,K=B(K);let V=K.split("?")[0]||"/",X=this.routes.get("notfound"),F={};for(let[L,U]of this.routes){let v=U.match(V);if(v){F=v,X=U;break}}let C=R(V,F,X),A=$.globalHandlers.concat(X.handlers);if(A.length){try{await e(A,C,Q)}catch(L){this.loading=!1;return}if(!X.templates)this.loading=!1}if(q!=null)this.history.index=q,this.history.pushState(K);else if(W||K!=this.context.path)this.history.push(K,!G&&!W);if(this.context=C,X.programmaticTemplates){let L=document.getElementById(X.targetID??$.targetID??"");if(!L)throw new Error(c);let U=X.interpolate?D(X.templates,F):X.templates;I(U,L).finally(()=>this.loading=!1)}if(!X.templates.length)this.loading=!1}};return M.history.setRouter(M),M};var j1=(b)=>{window.document.body.addEventListener("click",(j)=>{if(j.ctrlKey||j.metaKey||j.altKey||j.shiftKey||j.button||j.defaultPrevented)return;let J=j.target.closest("a");if(!J)return;if($.handleClicks===!1&&!J.hasAttribute("x-link")||J.hasAttribute("data-native")||J.hasAttribute("native"))return;let z=J.getAttribute("href"),Z=J.getAttribute("target");if(z&&(!Z||/^_?self$/i.test(Z)))b.navigate(z),j.preventDefault()})};var z1="pinecone-router",K1="7.2.0";var X1=function(b){let j=()=>{return $.hash?location.hash.substring(1):location.pathname},J=b.reactive(b1(z1,K1,j()));window.PineconeRouter=J,document.addEventListener("alpine:initialized",()=>{J.navigate(j(),!1,!0)}),window.addEventListener("popstate",()=>{J.navigate($.hash?window.location.hash.substring(1):window.location.pathname,!0)}),j1(J),document.addEventListener("pinecone:end",()=>b.nextTick(s),{once:!0}),a(b,J),l(b,J),r(b,J),b.$router=J,b.magic("router",()=>J),b.magic("history",()=>J.history),b.magic("params",()=>J.context.params)},Z1=X1;document.addEventListener("alpine:init",()=>{window.Alpine.plugin(Z1)});})(); //# debugId=4B850DD1155F2E2464756E2164756E21 //# sourceMappingURL=router.min.js.map