UNPKG

svelte-pathfinder

Version:

Tiny, state-based, advanced router for SvelteJS.

3 lines (2 loc) 10.7 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("svelte"),require("svelte/store")):"function"==typeof define&&define.amd?define(["exports","svelte","svelte/store"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).pathfinder={},e.svelte,e.store)}(this,(function(e,t,n){"use strict";const o=/^((mailto:)|(tel:)|(sms:)|(data:)|(blob:)|(javascript:)|(ftp(s?):\/\/)|(file:\/\/))/,r="undefined"!=typeof location,i="undefined"!=typeof process,s="undefined"!=typeof history,c=s&&k(history.pushState),a="undefined"!=typeof window,u=a&&window!==window.parent,l=r&&("file:"===location.protocol||/[-_\w]+[.][\w]+$/i.test(location.pathname)),f=a&&s&&r&&!u,d=!c||l,h="#!",p={array:{separator:",",format:"bracket"},convertTypes:!0,breakHooks:!0,hashbang:!1,anchor:!1,scroll:!1,focus:!1,nesting:3,sideEffect:f,base:""};function b(){if(!r)return{};if(p.hashbang||d){const e=location.hash;return new URL(0===e.indexOf(h)?e.substring(2):e.substring(1),"file:")}return location}function m(){return p.base?p.base:r&&(p.hashbang||d)?location.pathname:"/"}function g(e){(p.hashbang||d)&&(e=h+e);const t=m();return("/"===t[t.length-1]?t.substring(0,t.length-1):t)+e}function y(e){e=A(e,b().origin);return e=A(e,m()),(p.hashbang||d)&&(e=A(e,h)),x(e)}function w(e){const t=e.tagName.toLowerCase(),n=e.type&&e.type.toLowerCase();return"button"===t||"input"===t&&["button","submit","image"].includes(n)}function v(e,t=""){const n=A($(t),"#");if(e&&p.scroll){const t=E(p.scroll)?{...p.scroll,...e}:e,{top:n=0,left:o=0}=e,{scrollHeight:r,scrollWidth:i}=document.documentElement;if(n<=r&&o<=i)return R(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(),R(t))}),document.documentElement)}else if(n&&p.anchor){const e=E(p.anchor)?p.anchor:{},t=document.getElementById(n);if(t)return R(e,t);const o=I((()=>{const t=document.getElementById(n);t&&(o(),R(e,t))}))}else p.scroll&&R()}function O(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"===p.array.format?n.push(`${o}=${e[o].join(p.array.separator)}`):e[o].forEach((e=>n.push(`${o}[]=${t(e)}`)));else if(E(e[o])){let t=N(o,e[o]);n.push(T(t))}else n.push(`${o}=${t(e[o])}`);return n}),[]).join("&")}function j(e="",t="*",{loose:n=!1,sensitive:o=!1,blank:r=!1,decode:i=decodeURIComponent}={}){const s={},c=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,i=!!~o,c=t.substring(1,r?n:i?o:t.length);s[c]=void 0,e+=r&&!i?`(?:/(?<${c}>[^/]+?))?`:`/(?<${c}>[^/]+?)`,i&&(e+=`${r?"?":""}\\${t.substring(o)}`)}else e+=`/${t}`}return o===r-1&&(e+=n?"(?:$|/)":"/?$"),e}),"^"),a=new RegExp(c,o?"":"i").exec(e);return a?Object.entries(a.groups||{}).reduce(((e,[t,n])=>{const o=i(n);return e[t]=p.convertTypes?L(o):o,e}),{}):r?s:null}function $(e,{decode:t=decodeURIComponent}={}){return t(e)}function x(e,t="/",n=!1){return!(e+="")&&n?e:0!==e.indexOf(t)?t+e:e}function A(e,t){return 0===(e+"").indexOf(t)?e.substring(t.length):e}function E(e){return!Array.isArray(e)&&"object"==typeof e&&null!==e}function k(e){return"function"==typeof e}function S(...e){return window.addEventListener(...e),()=>window.removeEventListener(...e)}function R({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 I(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 L(e){if(Array.isArray(e))return e[e.length-1]=L(e[e.length-1]),e;if("object"==typeof e)return Object.entries(e).reduce(((e,[t,n])=>(e[t]=L(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"===p.array.format&&"string"==typeof e){const t=e.split(p.array.separator);return t.length>1?t:e}return e}}function N(e,t){const n=/(\[[^[\]]*])/g;let o=/(\[[^[\]]*])/.exec(e),r=o?e.slice(0,o.index):e,i=[];r&&i.push(r);let s=0;for(;(o=n.exec(e))&&s<p.nesting;)s++,i.push(o[1]);return o&&i.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]=p.convertTypes?L(n):n):o[e]=n}n=o}return n}(i,t)}function T(e={},t=""){return Object.entries(e).map((([e,n])=>"object"==typeof n?T(n,t?`${t}[${e}]`:e):`${t}[${e}]=${n}`)).join("&")}const C=_((function(e=""){return"string"==typeof e&&(e=A(e,"/").split("/")),Object.prototype.hasOwnProperty.call(e,"toString")?e:Object.defineProperty(e,"toString",{value(){return x(this.join("/"))},configurable:!1,writable:!1})})),P=_((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 i=N(o,r);return e=Object.keys(i).reduce(((e,t)=>{const n=p.convertTypes?L(i[t]):i[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 x(O(this),"?",!0)},configurable:!1,writable:!1})})),U=_((function(e=""){return x($(e),"#",!0)}));function _(e){return(t,o)=>{let r=t&&t.toString();!Array.isArray(o)&&(o=[o]);const i=new Set(o),s=function(e){return(...t)=>{const n=[...e];return!(p.breakHooks?n.some((e=>!1===e(...t))):n.reduce(((e,n)=>!1===n(...t)||e),!1))}}(i),{subscribe:c,set:a}=n.writable(t=e(t),(()=>()=>i.clear()));function u(n){(n=e(n)).toString()!==r&&!1!==s(n,t,e.name)&&(r=n.toString(),a(t=n))}return s(null,t,e.name),{subscribe:c,update(e){u(e(n.get(this)))},set(e){u(e)},hook:n=>(k(n)&&(i.add(n),n(null,t,e.name)),()=>i.delete(n))}}}const q=function(){const e=b().pathname;if(!e)return;return x(A(e,m()))}(),{search:B,hash:K}=b();let z=!0,D=!1,H=!1,M=0;const V=C(q,G),W=P(B,G),Z=U(K,G),X=n.writable({}),Y=n.derived([V,W,Z],(([e,n,o],r)=>{let i=!1;return t.tick().then((()=>{i||r(e+n+o)})),()=>i=!0}),q+B+K),F=n.derived(V,(e=>j.bind(null,e.toString())));function G(){(p.scroll||p.focus)&&X.update(((e={})=>(p.scroll&&(e._scroll={top:window.pageYOffset,left:window.pageXOffset}),p.focus&&(e._focus=document.activeElement.id),e)))}function J(e,n){const o=e.indexOf("#")>=0?e.slice(e.indexOf("#")):"",r=document.activeElement;!E(n)&&(n={}),t.tick().then((()=>function(e,t){function n(){return e?document.getElementById(e):document.activeElement!==t&&document.activeElement!==document.body?document.activeElement:document.querySelector("[autofocus]")}p.focus&&setTimeout((()=>{const e=n();if(e)return e.focus();const t=I((()=>{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()}))}(n._focus,r))).then((()=>v(n._scroll,o)))}if(f||u){const e=new Set;e.add(Y.subscribe((e=>{z||D||!p.sideEffect||(c?history[H?"replaceState":"pushState"]({},null,g(e)):location.hash=g(e)),!D&&J(e),!H&&M++,z=H=D=!1}))),c?(e.add(X.subscribe((e=>{!z&&p.sideEffect&&history.replaceState(e,null,location.pathname+location.search+location.hash)}))),e.add(S("popstate",(e=>{D=!0,Q(location.href,e.state),J(y(location.href),e.state)})))):e.add(S("hashchange",(()=>{if(D=!0,!p.hashbang&&!d)return Z.set(location.hash);Q(location.hash),J(y(location.hash))}))),e.add(S("beforeunload",(()=>{e.forEach((e=>e())),e.clear()}),!0))}function Q(e="",n={}){const{pathname:o,search:r,hash:i}=e instanceof URL?e:new URL(y(e),"file:");V.set(o),W.set(r),Z.set(i),t.tick().then((()=>X.set(n||{})))}const ee=function(e){return(t,o={})=>{if(t instanceof RegExp)throw new Error("Paramable does not support RegExp patterns.");let r;t=t.replace(/\/$/,"");const{subscribe:i}=n.writable({},(n=>e.subscribe((e=>{var i;r=j(e.toString(),t,{blank:!0,...o}),n("object"!=typeof(i=r)||null===i?i:Object.create(Object.getPrototypeOf(i),Object.getOwnPropertyDescriptors(i)))}))));function s(n={}){Object.entries(r).some((([e,t])=>t!==n[e]))&&e.update((e=>{const r=o.loose?x(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+r,n)}))}return{get(){return n.get(this)},update(e){s(e(this.get()))},subscribe:i,set:s}}}(V);e.back=function(e){M>0&&f&&p.sideEffect?(history.back(),M--):t.tick().then((()=>Q(e)))},e.click=function(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"),r=t.href;!n||0!==r.indexOf(location.origin)||o.test(n)||!p.hashbang&&!d&&n.startsWith("#")||(e.preventDefault(),Q(r,Object.assign({},t.dataset)))},e.fragment=Z,e.goto=Q,e.paramable=ee,e.path=V,e.pattern=F,e.prefs=p,e.query=W,e.redirect=function(e,n){t.tick().then((()=>{H=!0,Q(e,n)}))},e.state=X,e.submit=function(e){if(!e.target||e.defaultPrevented)return;const t=e.target,n=e.submitter||w(document.activeElement)&&document.activeElement;let o=t.action,r=t.method,s=t.target;if(n&&(n.hasAttribute("formaction")&&(o=n.formAction),n.hasAttribute("formmethod")&&(r=n.formMethod),n.hasAttribute("formtarget")&&(s=n.formTarget)),r&&"get"!==r.toLowerCase())return;if(s&&"_self"!==s.toLowerCase())return;const{pathname:c,hash:a}=new URL(o),u=[],l={},f=t.elements,d=f.length;for(let e=0;e<d;e++){const t=f[e];t.name&&!t.disabled&&(["checkbox","radio"].includes(t.type)&&!t.checked||w(t)&&t!==n||("hidden"!==t.type?u.push(`${t.name}=${t.value}`):l[t.name]=t.value))}let h=x(`${c}?${u.join("&")}${a}`);i&&h.match(/^\/[a-zA-Z]:\//)&&(h=h.replace(/^\/[a-zA-Z]:\//,"/")),e.preventDefault(),Q(h,l)},e.url=Y})); //# sourceMappingURL=index.min.js.map