UNPKG

svelte-pathfinder

Version:

Tiny, state-based, advanced router for SvelteJS.

3 lines (2 loc) 12 kB
function e(){}function t(e){return e()}function n(e){e.forEach(t)}function o(t,...n){if(null==t)return e;const o=t.subscribe(...n);return o.unsubscribe?()=>o.unsubscribe():o}function r(e){let t;return o(e,(e=>t=e))(),t}const c=[],s=[],i=[],u=[],a=Promise.resolve();let l=!1;function f(){return l||(l=!0,a.then(b)),a}function d(e){i.push(e)}const h=new Set;let p=0;function b(){if(0===p){do{try{for(;p<c.length;){const e=c[p];p++,g(e.$$)}}catch(e){throw c.length=0,p=0,e}for(c.length=0,p=0;s.length;)s.pop()();for(let e=0;e<i.length;e+=1){const t=i[e];h.has(t)||(h.add(t),t())}i.length=0}while(c.length);for(;u.length;)u.pop()();l=!1,h.clear()}}function g(e){if(null!==e.fragment){e.update(),n(e.before_update);const t=e.dirty;e.dirty=[-1],e.fragment&&e.fragment.p(e.ctx,t),e.after_update.forEach(d)}}const m=[];function y(t,n=e){let o;const r=new Set;function c(e){if(c=e,((n=t)!=n?c==c:n!==c||n&&"object"==typeof n||"function"==typeof n)&&(t=e,o)){const e=!m.length;for(const e of r)e[1](),m.push(e,t);if(e){for(let e=0;e<m.length;e+=2)m[e][0](m[e+1]);m.length=0}}var n,c}return{set:c,update:function(e){c(e(t))},subscribe:function(s,i=e){const u=[s,i];return r.add(u),1===r.size&&(o=n(c)||e),s(t),()=>{r.delete(u),0===r.size&&(o(),o=null)}}}}function w(t,r,c){const s=!Array.isArray(t),i=s?[t]:t,u=r.length<2;return a=t=>{let c=!1;const a=[];let l=0,f=e;const d=()=>{if(l)return;f();const n=r(s?a[0]:a,t);u?t(n):f="function"==typeof n?n:e},h=i.map(((e,t)=>o(e,(e=>{a[t]=e,l&=~(1<<t),c&&d()}),(()=>{l|=1<<t}))));return c=!0,d(),function(){n(h),f()}},{subscribe:y(c,a).subscribe};var a}const v=/^((mailto:)|(tel:)|(sms:)|(data:)|(blob:)|(javascript:)|(ftp(s?):\/\/)|(file:\/\/))/,O="undefined"!=typeof location,$="undefined"!=typeof process,j="undefined"!=typeof history,A=j&&V(history.pushState),E="undefined"!=typeof window,x=E&&window!==window.parent,S=O&&("file:"===location.protocol||/[-_\w]+[.][\w]+$/i.test(location.pathname)),R=E&&j&&O&&!x,k=!A||S,I="#!",L={array:{separator:",",format:"bracket"},convertTypes:!0,breakHooks:!0,hashbang:!1,anchor:!1,scroll:!1,focus:!1,nesting:3,sideEffect:R,base:""};function N(){if(!O)return{};if(L.hashbang||k){const e=location.hash;return new URL(0===e.indexOf(I)?e.substring(2):e.substring(1),"file:")}return location}function C(){return L.base?L.base:O&&(L.hashbang||k)?location.pathname:"/"}function P(e){(L.hashbang||k)&&(e=I+e);const t=C();return("/"===t[t.length-1]?t.substring(0,t.length-1):t)+e}function T(e){e=H(e,N().origin);return e=H(e,C()),(L.hashbang||k)&&(e=H(e,I)),D(e)}function U(e){const t=e.tagName.toLowerCase(),n=e.type&&e.type.toLowerCase();return"button"===t||"input"===t&&["button","submit","image"].includes(n)}function _(e,t=""){const n=H(K(t),"#");if(e&&L.scroll){const t=M(L.scroll)?{...L.scroll,...e}:e,{top:n=0,left:o=0}=e,{scrollHeight:r,scrollWidth:c}=document.documentElement;if(n<=r&&o<=c)return Z(t);const s=function(e,t,n=5e3){const o=new ResizeObserver(e);o.observe(t);const r=()=>o.unobserve(t);return setTimeout(r,n),r}((e=>{if(!e[0])return s();(!n||e[0].contentRect.height>=n)&&(!o||e[0].contentRect.width>=o)&&(s(),Z(t))}),document.documentElement)}else if(n&&L.anchor){const e=M(L.anchor)?L.anchor:{},t=document.getElementById(n);if(t)return Z(e,t);const o=q((()=>{const t=document.getElementById(n);t&&(o(),Z(e,t))}))}else L.scroll&&Z()}function z(e={},{encode:t=encodeURIComponent}={}){return Object.keys(e).reduce(((n,o)=>{if(Object.prototype.hasOwnProperty.call(e,o)&&isNaN(parseInt(o,10)))if(Array.isArray(e[o]))"separator"===L.array.format?n.push(`${o}=${e[o].join(L.array.separator)}`):e[o].forEach((e=>n.push(`${o}[]=${t(e)}`)));else if(M(e[o])){let t=Y(o,e[o]);n.push(F(t))}else n.push(`${o}=${t(e[o])}`);return n}),[]).join("&")}function B(e="",t="*",{loose:n=!1,sensitive:o=!1,blank:r=!1,decode:c=decodeURIComponent}={}){const s={},i=t instanceof RegExp?t:t.split("/").reduce(((e,t,o,{length:r})=>{if(t){const n=t[0];if("*"===n)s.wild=void 0,e+="/(?<wild>.*)";else if(":"===n){const n=t.indexOf("?",1),o=t.indexOf(".",1),r=!!~n,c=!!~o,i=t.substring(1,r?n:c?o:t.length);s[i]=void 0,e+=r&&!c?`(?:/(?<${i}>[^/]+?))?`:`/(?<${i}>[^/]+?)`,c&&(e+=`${r?"?":""}\\${t.substring(o)}`)}else e+=`/${t}`}return o===r-1&&(e+=n?"(?:$|/)":"/?$"),e}),"^"),u=new RegExp(i,o?"":"i").exec(e);return u?Object.entries(u.groups||{}).reduce(((e,[t,n])=>{const o=c(n);return e[t]=L.convertTypes?X(o):o,e}),{}):r?s:null}function K(e,{decode:t=decodeURIComponent}={}){return t(e)}function D(e,t="/",n=!1){return!(e+="")&&n?e:0!==e.indexOf(t)?t+e:e}function H(e,t){return 0===(e+"").indexOf(t)?e.substring(t.length):e}function M(e){return!Array.isArray(e)&&"object"==typeof e&&null!==e}function V(e){return"function"==typeof e}function W(...e){return window.addEventListener(...e),()=>window.removeEventListener(...e)}function Z({top:e=0,left:t=0,...n}={},o){o?document.documentElement.scrollIntoView?o.scrollIntoView({behavior:"smooth",...n}):window.scrollTo({top:o.offsetTop-e,behavior:"smooth",...n}):window.scrollTo({top:e,left:t,behavior:"smooth",...n})}function q(e,t=5e3){const n=new MutationObserver(e);n.observe(document.body,{childList:!0,subtree:!0});const o=()=>n.disconnect();return setTimeout(o,t),o}function X(e){if(Array.isArray(e))return e[e.length-1]=X(e[e.length-1]),e;if("object"==typeof e)return Object.entries(e).reduce(((e,[t,n])=>(e[t]=X(n),e)),{});if("true"===e||"false"===e)return"true"===e;if("null"===e)return null;if("undefined"!==e){if(""!==e&&!isNaN(Number(e))&&Number(e).toString()===e)return Number(e);if("separator"===L.array.format&&"string"==typeof e){const t=e.split(L.array.separator);return t.length>1?t:e}return e}}function Y(e,t){const n=/(\[[^[\]]*])/g;let o=/(\[[^[\]]*])/.exec(e),r=o?e.slice(0,o.index):e,c=[];r&&c.push(r);let s=0;for(;(o=n.exec(e))&&s<L.nesting;)s++,c.push(o[1]);return o&&c.push(`[${e.slice(o.index)}]`),function(e,t){let n=t;for(let t=e.length-1;t>=0;--t){let o,r=e[t];if("[]"===r)o=[].concat(n);else{o={};const e="["===r.charAt(0)&&"]"===r.charAt(r.length-1)?r.slice(1,-1):r,t=parseInt(e,10);!isNaN(t)&&r!==e&&String(t)===e&&t>=0?(o=[],o[t]=L.convertTypes?X(n):n):o[e]=n}n=o}return n}(c,t)}function F(e={},t=""){return Object.entries(e).map((([e,n])=>"object"==typeof n?F(n,t?`${t}[${e}]`:e):`${t}[${e}]=${n}`)).join("&")}const G=ee((function(e=""){return"string"==typeof e&&(e=H(e,"/").split("/")),Object.prototype.hasOwnProperty.call(e,"toString")?e:Object.defineProperty(e,"toString",{value(){return D(this.join("/"))},configurable:!1,writable:!1})})),J=ee((function(e=""){return"string"==typeof e&&(e=function(e="",{decode:t=decodeURIComponent}={}){return e?e.replace("?","").replace(/\+/g," ").split("&").filter(Boolean).reduce(((e,n)=>{let[o,r]=n.split(/=(.*)/,2);o=t(o||""),r=t(r||"");let c=Y(o,r);return e=Object.keys(c).reduce(((e,t)=>{const n=L.convertTypes?X(c[t]):c[t];return e[t]?Array.isArray(e[t])?e[t]=e[t].concat(n):Object.assign(e[t],n):e[t]=n,e}),e),e}),{}):{}}(e)),Object.prototype.hasOwnProperty.call(e,"toString")?e:Object.defineProperty(e,"toString",{value(){return D(z(this),"?",!0)},configurable:!1,writable:!1})})),Q=ee((function(e=""){return D(K(e),"#",!0)}));function ee(e){return(t,n)=>{let o=t&&t.toString();!Array.isArray(n)&&(n=[n]);const c=new Set(n),s=function(e){return(...t)=>{const n=[...e];return!(L.breakHooks?n.some((e=>!1===e(...t))):n.reduce(((e,n)=>!1===n(...t)||e),!1))}}(c),{subscribe:i,set:u}=y(t=e(t),(()=>()=>c.clear()));function a(n){(n=e(n)).toString()!==o&&!1!==s(n,t,e.name)&&(o=n.toString(),u(t=n))}return s(null,t,e.name),{subscribe:i,update(e){a(e(r(this)))},set(e){a(e)},hook:n=>(V(n)&&(c.add(n),n(null,t,e.name)),()=>c.delete(n))}}}const te=function(){const e=N().pathname;if(!e)return;return D(H(e,C()))}(),{search:ne,hash:oe}=N();let re=!0,ce=!1,se=!1,ie=0;const ue=G(te,pe),ae=J(ne,pe),le=Q(oe,pe),fe=y({}),de=w([ue,ae,le],(([e,t,n],o)=>{let r=!1;return f().then((()=>{r||o(e+t+n)})),()=>r=!0}),te+ne+oe),he=w(ue,(e=>B.bind(null,e.toString())));function pe(){(L.scroll||L.focus)&&fe.update(((e={})=>(L.scroll&&(e._scroll={top:window.pageYOffset,left:window.pageXOffset}),L.focus&&(e._focus=document.activeElement.id),e)))}function be(e,t){const n=e.indexOf("#")>=0?e.slice(e.indexOf("#")):"",o=document.activeElement;!M(t)&&(t={}),f().then((()=>function(e,t){function n(){return e?document.getElementById(e):document.activeElement!==t&&document.activeElement!==document.body?document.activeElement:document.querySelector("[autofocus]")}L.focus&&setTimeout((()=>{const e=n();if(e)return e.focus();const t=q((()=>{const e=n();e&&(t(),e.focus())})),o=document.body,r=o.getAttribute("tabindex");o.tabIndex=-1,o.focus({preventScroll:!0}),null!==r?o.setAttribute("tabindex",r):o.removeAttribute("tabindex"),getSelection().removeAllRanges()}))}(t._focus,o))).then((()=>_(t._scroll,n)))}if(R||x){const e=new Set;e.add(de.subscribe((e=>{re||ce||!L.sideEffect||(A?history[se?"replaceState":"pushState"]({},null,P(e)):location.hash=P(e)),!ce&&be(e),!se&&ie++,re=se=ce=!1}))),A?(e.add(fe.subscribe((e=>{!re&&L.sideEffect&&history.replaceState(e,null,location.pathname+location.search+location.hash)}))),e.add(W("popstate",(e=>{ce=!0,ge(location.href,e.state),be(T(location.href),e.state)})))):e.add(W("hashchange",(()=>{if(ce=!0,!L.hashbang&&!k)return le.set(location.hash);ge(location.hash),be(T(location.hash))}))),e.add(W("beforeunload",(()=>{e.forEach((e=>e())),e.clear()}),!0))}function ge(e="",t={}){const{pathname:n,search:o,hash:r}=e instanceof URL?e:new URL(T(e),"file:");ue.set(n),ae.set(o),le.set(r),f().then((()=>fe.set(t||{})))}function me(e){ie>0&&R&&L.sideEffect?(history.back(),ie--):f().then((()=>ge(e)))}function ye(e,t){f().then((()=>{se=!0,ge(e,t)}))}function we(e){if(!e.target||e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||e.button||1!==e.which||e.defaultPrevented)return;const t=function(e,t){for(;e&&e.nodeName.toLowerCase()!==t;)e=e.parentNode;return e&&e.nodeName.toLowerCase()===t?e:null}(e.target,"a");if(!t||t.target||t.hasAttribute("download")||t.hasAttribute("rel")&&t.getAttribute("rel").includes("external"))return;const n=t.getAttribute("href"),o=t.href;!n||0!==o.indexOf(location.origin)||v.test(n)||!L.hashbang&&!k&&n.startsWith("#")||(e.preventDefault(),ge(o,Object.assign({},t.dataset)))}function ve(e){if(!e.target||e.defaultPrevented)return;const t=e.target,n=e.submitter||U(document.activeElement)&&document.activeElement;let o=t.action,r=t.method,c=t.target;if(n&&(n.hasAttribute("formaction")&&(o=n.formAction),n.hasAttribute("formmethod")&&(r=n.formMethod),n.hasAttribute("formtarget")&&(c=n.formTarget)),r&&"get"!==r.toLowerCase())return;if(c&&"_self"!==c.toLowerCase())return;const{pathname:s,hash:i}=new URL(o),u=[],a={},l=t.elements,f=l.length;for(let e=0;e<f;e++){const t=l[e];t.name&&!t.disabled&&(["checkbox","radio"].includes(t.type)&&!t.checked||U(t)&&t!==n||("hidden"!==t.type?u.push(`${t.name}=${t.value}`):a[t.name]=t.value))}let d=D(`${s}?${u.join("&")}${i}`);$&&d.match(/^\/[a-zA-Z]:\//)&&(d=d.replace(/^\/[a-zA-Z]:\//,"/")),e.preventDefault(),ge(d,a)}const Oe=function(e){return(t,n={})=>{if(t instanceof RegExp)throw new Error("Paramable does not support RegExp patterns.");let o;t=t.replace(/\/$/,"");const{subscribe:c}=y({},(r=>e.subscribe((e=>{var c;o=B(e.toString(),t,{blank:!0,...n}),r("object"!=typeof(c=o)||null===c?c:Object.create(Object.getPrototypeOf(c),Object.getOwnPropertyDescriptors(c)))}))));function s(r={}){Object.entries(o).some((([e,t])=>t!==r[e]))&&e.update((e=>{const o=n.loose?D(e.slice(t.split("/").length-1).join("/")):"";return function(e,t,{encode:n=encodeURIComponent}={}){return e.replace(/(\/|^)([:*][^/]*?)(\?)?(?=[/.]|$)/g,((e,o,r)=>(e=t["*"===r?"wild":r.substring(1)])?`/${n(e)}`:""))}(t+o,r)}))}return{get(){return r(this)},update(e){s(e(this.get()))},subscribe:c,set:s}}}(ue);export{me as back,we as click,le as fragment,ge as goto,Oe as paramable,ue as path,he as pattern,L as prefs,ae as query,ye as redirect,fe as state,ve as submit,de as url}; //# sourceMappingURL=pathfinder.min.mjs.map