swup 4.4.2 → 4.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/Swup.cjs +1 -1
- package/dist/Swup.cjs.map +1 -1
- package/dist/Swup.modern.js +1 -1
- package/dist/Swup.modern.js.map +1 -1
- package/dist/Swup.module.js +1 -1
- package/dist/Swup.module.js.map +1 -1
- package/dist/Swup.umd.js +1 -1
- package/dist/Swup.umd.js.map +1 -1
- package/dist/types/helpers/Location.d.ts.map +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/modules/Hooks.d.ts +6 -0
- package/dist/types/modules/Hooks.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/helpers/Location.ts +1 -0
- package/src/index.ts +3 -1
- package/src/modules/Hooks.ts +15 -2
package/dist/Swup.modern.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import t from"delegate-it";import{match as e}from"path-to-regexp";function i(){return i=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(t[s]=i[s])}return t},i.apply(this,arguments)}const s=(t,e)=>String(t).toLowerCase().replace(/[\s/_.]+/g,"-").replace(/[^\w-]+/g,"").replace(/--+/g,"-").replace(/^-+|-+$/g,"")||e||"",n=({hash:t}={})=>location.pathname+location.search+(t?location.hash:""),o=(t,e={})=>{const s=i({url:t=t||n({hash:!0}),random:Math.random(),source:"swup"},e);history.pushState(s,"",t)},r=(t=null,e={})=>{t=t||n({hash:!0});const s=i({},history.state||{},{url:t,random:Math.random(),source:"swup"},e);history.replaceState(s,"",t)},a=(e,s,n,o)=>{const r=new AbortController;return o=i({},o,{signal:r.signal}),t(e,s,n,o),{destroy:()=>r.abort()}};class l extends URL{constructor(t,e=document.baseURI){super(t.toString(),e)}get url(){return this.pathname+this.search}static fromElement(t){const e=t.getAttribute("href")||t.getAttribute("xlink:href")||"";return new l(e)}static fromUrl(t){return new l(t)}}const h=(t,i)=>{try{return e(t,i)}catch(e){throw new Error(`[swup] Error parsing path "${String(t)}":\n${String(e)}`)}};class c extends Error{constructor(t,e){super(t),this.url=void 0,this.status=void 0,this.aborted=void 0,this.timedOut=void 0,this.name="FetchError",this.url=e.url,this.status=e.status,this.aborted=e.aborted||!1,this.timedOut=e.timedOut||!1}}async function u(t,e={}){var s;t=l.fromUrl(t).url;const n=i({},this.options.requestHeaders,e.headers),o=null!=(s=e.timeout)?s:this.options.timeout,r=new AbortController,{signal:a}=r;e=i({},e,{headers:n,signal:a});let h,u=!1,d=null;o&&o>0&&(d=setTimeout(()=>{u=!0,r.abort("timeout")},o));try{h=await this.hooks.call("fetch:request",{url:t,options:e},(t,{url:e,options:i})=>fetch(e,i)),d&&clearTimeout(d)}catch(e){if(u)throw this.hooks.call("fetch:timeout",{url:t}),new c(`Request timed out: ${t}`,{url:t,timedOut:u});if("AbortError"===(null==e?void 0:e.name)||a.aborted)throw new c(`Request aborted: ${t}`,{url:t,aborted:!0});throw e}const{status:p,url:m}=h,g=await h.text();if(500===p)throw this.hooks.call("fetch:error",{status:p,response:h,url:m}),new c(`Server error: ${m}`,{status:p,url:m});if(!g)throw new c(`Empty response: ${m}`,{status:p,url:m});const{url:f}=l.fromUrl(m),w={url:f,html:g};return!this.visit.cache.write||e.method&&"GET"!==e.method||t!==f||this.cache.set(w.url,w),w}class d{constructor(t){this.swup=void 0,this.pages=new Map,this.swup=t}get size(){return this.pages.size}get all(){const t=new Map;return this.pages.forEach((e,s)=>{t.set(s,i({},e))}),t}has(t){return this.pages.has(this.resolve(t))}get(t){const e=this.pages.get(this.resolve(t));return e?i({},e):e}set(t,e){e=i({},e,{url:t=this.resolve(t)}),this.pages.set(t,e),this.swup.hooks.callSync("cache:set",{page:e})}update(t,e){t=this.resolve(t);const s=i({},this.get(t),e,{url:t});this.pages.set(t,s)}delete(t){this.pages.delete(this.resolve(t))}clear(){this.pages.clear(),this.swup.hooks.callSync("cache:clear",void 0)}prune(t){this.pages.forEach((e,i)=>{t(i,e)&&this.delete(i)})}resolve(t){const{url:e}=l.fromUrl(t);return this.swup.resolveUrl(e)}}const p=(t,e=document)=>e.querySelector(t),m=(t,e=document)=>Array.from(e.querySelectorAll(t)),g=()=>new Promise(t=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{t()})})});function f(t){return!!t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}function w(t,e=[]){return new Promise((i,s)=>{const n=t(...e);f(n)?n.then(i,s):i(n)})}function v(t){var e;return null==(e=t=t||document.body)?void 0:e.offsetHeight}const y=t=>window.CSS&&window.CSS.escape?CSS.escape(t):t,k=t=>1e3*Number(t.slice(0,-1).replace(",","."));class S{constructor(t){this.swup=void 0,this.swupClasses=["to-","is-changing","is-rendering","is-popstate","is-animating"],this.swup=t}get selectors(){const{scope:t}=this.swup.visit.animation;return"containers"===t?this.swup.visit.containers:"html"===t?["html"]:Array.isArray(t)?t:[]}get selector(){return this.selectors.join(",")}get targets(){return this.selector.trim()?m(this.selector):[]}add(...t){this.targets.forEach(e=>e.classList.add(...t))}remove(...t){this.targets.forEach(e=>e.classList.remove(...t))}clear(){this.targets.forEach(t=>{const e=t.className.split(" ").filter(t=>this.isSwupClass(t));t.classList.remove(...e)})}isSwupClass(t){return this.swupClasses.some(e=>t.startsWith(e))}}function b({to:t,from:e=this.currentPageUrl,hash:i,el:s,event:n}){return{id:Math.random(),from:{url:e},to:{url:t,hash:i},containers:this.options.containers,animation:{animate:!0,wait:!1,name:void 0,scope:this.options.animationScope,selector:this.options.animationSelector},trigger:{el:s,event:n},cache:{read:this.options.cache,write:this.options.cache},history:{action:"push",popstate:!1,direction:void 0},scroll:{reset:!0,target:void 0}}}class E{constructor(t){this.swup=void 0,this.registry=new Map,this.hooks=["animation:out:start","animation:out:await","animation:out:end","animation:in:start","animation:in:await","animation:in:end","animation:skip","cache:clear","cache:set","content:replace","content:scroll","enable","disable","fetch:request","fetch:error","fetch:timeout","history:popstate","link:click","link:self","link:anchor","link:newtab","page:load","page:view","scroll:top","scroll:anchor","visit:start","visit:transition","visit:end"],this.swup=t,this.init()}init(){this.hooks.forEach(t=>this.create(t))}create(t){this.registry.has(t)||this.registry.set(t,new Map)}exists(t){return this.registry.has(t)}get(t){const e=this.registry.get(t);if(e)return e;console.error(`Unknown hook '${t}'`)}clear(){this.registry.forEach(t=>t.clear())}on(t,e,s={}){const n=this.get(t);if(!n)return console.warn(`Hook '${t}' not found.`),()=>{};const o=i({},s,{id:n.size+1,hook:t,handler:e});return n.set(e,o),()=>this.off(t,e)}before(t,e,s={}){return this.on(t,e,i({},s,{before:!0}))}replace(t,e,s={}){return this.on(t,e,i({},s,{replace:!0}))}once(t,e,s={}){return this.on(t,e,i({},s,{once:!0}))}off(t,e){const i=this.get(t);i&&e?i.delete(e)||console.warn(`Handler for hook '${t}' not found.`):i&&i.clear()}async call(t,e,i){const{before:s,handler:n,after:o}=this.getHandlers(t,i);await this.run(s,e);const[r]=await this.run(n,e);return await this.run(o,e),this.dispatchDomEvent(t,e),r}callSync(t,e,i){const{before:s,handler:n,after:o}=this.getHandlers(t,i);this.runSync(s,e);const[r]=this.runSync(n,e);return this.runSync(o,e),this.dispatchDomEvent(t,e),r}async run(t,e){const i=[];for(const{hook:s,handler:n,defaultHandler:o,once:r}of t){const t=await w(n,[this.swup.visit,e,o]);i.push(t),r&&this.off(s,n)}return i}runSync(t,e){const i=[];for(const{hook:s,handler:n,defaultHandler:o,once:r}of t){const t=n(this.swup.visit,e,o);i.push(t),f(t)&&console.warn(`Promise returned from handler for synchronous hook '${s}'.Swup will not wait for it to resolve.`),r&&this.off(s,n)}return i}getHandlers(t,e){const i=this.get(t);if(!i)return{found:!1,before:[],handler:[],after:[],replaced:!1};const s=Array.from(i.values()),n=this.sortRegistrations,o=s.filter(({before:t,replace:e})=>t&&!e).sort(n),r=s.filter(({replace:t})=>t).filter(t=>!0).sort(n),a=s.filter(({before:t,replace:e})=>!t&&!e).sort(n),l=r.length>0;let h=[];if(e&&(h=[{id:0,hook:t,handler:e}],l)){const i=r.length-1,s=t=>{const i=r[t-1];return i?(e,n)=>i.handler(e,n,s(t-1)):e};h=[{id:0,hook:t,handler:r[i].handler,defaultHandler:s(i)}]}return{found:!0,before:o,handler:h,after:a,replaced:l}}sortRegistrations(t,e){var i,s;return(null!=(i=t.priority)?i:0)-(null!=(s=e.priority)?s:0)||t.id-e.id||0}dispatchDomEvent(t,e){document.dispatchEvent(new CustomEvent(`swup:${t}`,{detail:{hook:t,args:e,visit:this.swup.visit}}))}}const P=t=>{if(t&&"#"===t.charAt(0)&&(t=t.substring(1)),!t)return null;const e=decodeURIComponent(t);let i=document.getElementById(t)||document.getElementById(e)||p(`a[name='${y(t)}']`)||p(`a[name='${y(e)}']`);return i||"top"!==t||(i=document.body),i},U="transition",C="animation";async function $({elements:t,selector:e}){if(!1===e&&!t)return;let i=[];if(t)i=Array.from(t);else if(e&&(i=m(e,document.body),!i.length))return void console.warn(`[swup] No elements found matching animationSelector \`${e}\``);const s=i.map(t=>function(t){const{type:e,timeout:i,propCount:s}=function(t,e){const i=window.getComputedStyle(t),s=x(i,`${U}Delay`),n=x(i,`${U}Duration`),o=H(s,n),r=x(i,`${C}Delay`),a=x(i,`${C}Duration`),l=H(r,a);let h=null,c=0,u=0;return c=Math.max(o,l),h=c>0?o>l?U:C:null,u=h?h===U?n.length:a.length:0,{type:h,timeout:c,propCount:u}}(t);return!(!e||!i)&&new Promise(n=>{const o=`${e}end`,r=performance.now();let a=0;const l=()=>{t.removeEventListener(o,h),n()},h=e=>{if(e.target===t){if(!function(t){return[`${U}end`,`${C}end`].includes(t.type)}(e))throw new Error("Not a transition or animation event.");(performance.now()-r)/1e3<e.elapsedTime||++a>=s&&l()}};setTimeout(()=>{a<s&&l()},i+1),t.addEventListener(o,h)})}(t));s.filter(Boolean).length>0?await Promise.all(s):e&&console.warn(`[swup] No CSS animation duration defined on elements matching \`${e}\``)}function x(t,e){return(t[e]||"").split(", ")}function H(t,e){for(;t.length<e.length;)t=t.concat(t);return Math.max(...e.map((e,i)=>k(e)+k(t[i])))}function A(t,e={},s={}){if("string"!=typeof t)throw new Error("swup.navigate() requires a URL parameter");if(this.shouldIgnoreVisit(t,{el:s.el,event:s.event}))return void(window.location.href=t);const{url:n,hash:o}=l.fromUrl(t);this.visit=this.createVisit(i({},s,{to:n,hash:o})),this.performNavigation(e)}async function q(t={}){this.navigating=!0;const e=this.visit,{el:i}=e.trigger;t.referrer=t.referrer||this.currentPageUrl,!1===t.animate&&(e.animation.animate=!1),e.animation.animate||this.classes.clear();const s=t.history||(null==i?void 0:i.getAttribute("data-swup-history"))||void 0;s&&["push","replace"].includes(s)&&(e.history.action=s);const a=t.animation||(null==i?void 0:i.getAttribute("data-swup-animation"))||void 0;var l,h;a&&(e.animation.name=a),"object"==typeof t.cache?(e.cache.read=null!=(l=t.cache.read)?l:e.cache.read,e.cache.write=null!=(h=t.cache.write)?h:e.cache.write):void 0!==t.cache&&(e.cache={read:!!t.cache,write:!!t.cache}),delete t.cache;try{await this.hooks.call("visit:start",void 0);const i=this.hooks.call("page:load",{options:t},async(t,e)=>{let i;return t.cache.read&&(i=this.cache.get(t.to.url)),e.page=i||await this.fetchPage(t.to.url,e.options),e.cache=!!i,e.page});if(!e.history.popstate){const t=e.to.url+e.to.hash;"replace"===e.history.action||e.to.url===this.currentPageUrl?r(t):(this.currentHistoryIndex++,o(t,{index:this.currentHistoryIndex}))}if(this.currentPageUrl=n(),e.animation.wait){const{html:t}=await i;e.to.html=t}await this.hooks.call("visit:transition",void 0,async t=>{const e=this.animatePageOut(),[s]=await Promise.all([i,e]);return t.id===this.visit.id&&(await this.renderPage(s),await this.animatePageIn(),!0)}),await this.hooks.call("visit:end",void 0,()=>this.classes.clear()),this.navigating=!1}catch(t){if(!t||null!=t&&t.aborted)return;console.error(t),this.options.skipPopStateHandling=()=>(window.location.href=e.to.url+e.to.hash,!0),window.history.go(-1)}}const I=async function(){this.visit.animation.animate?(await this.hooks.call("animation:out:start",void 0,t=>{this.classes.add("is-changing","is-leaving","is-animating"),t.history.popstate&&this.classes.add("is-popstate"),t.animation.name&&this.classes.add(`to-${s(t.animation.name)}`)}),await this.hooks.call("animation:out:await",{skip:!1},async(t,{skip:e})=>{e||await this.awaitAnimations({selector:t.animation.selector})}),await this.hooks.call("animation:out:end",void 0)):await this.hooks.call("animation:skip",void 0)},R=function({html:t},{containers:e}=this.options){var i;const s=(new DOMParser).parseFromString(t,"text/html"),n=(null==(i=s.querySelector("title"))?void 0:i.innerText)||"";document.title=n;const o=m('[data-swup-persist]:not([data-swup-persist=""])'),r=e.map(t=>{const e=document.querySelector(t),i=s.querySelector(t);return e&&i?(e.replaceWith(i),!0):(e||console.warn(`[swup] Container missing in current document: ${t}`),i||console.warn(`[swup] Container missing in incoming document: ${t}`),!1)}).filter(Boolean);return o.forEach(t=>{const e=t.getAttribute("data-swup-persist"),i=p(`[data-swup-persist="${e}"]`);i&&i!==t&&i.replaceWith(t)}),r.length===e.length},L=function(){const t={behavior:"auto"},{target:e,reset:s}=this.visit.scroll,n=null!=e?e:this.visit.to.hash;let o=!1;return n&&(o=this.hooks.callSync("scroll:anchor",{hash:n,options:t},(t,{hash:e,options:i})=>{const s=this.getAnchorElement(e);return s&&s.scrollIntoView(i),!!s})),s&&!o&&(o=this.hooks.callSync("scroll:top",{options:t},(t,{options:e})=>(window.scrollTo(i({top:0,left:0},e)),!0))),o},N=async function(){if(!this.visit.animation.animate)return;const t=this.hooks.call("animation:in:await",{skip:!1},async(t,{skip:e})=>{e||await this.awaitAnimations({selector:t.animation.selector})});await g(),await this.hooks.call("animation:in:start",void 0,()=>{this.classes.remove("is-animating")}),await t,await this.hooks.call("animation:in:end",void 0)},T=async function(t){const{url:e,html:i}=t;this.classes.remove("is-leaving"),this.isSameResolvedUrl(n(),e)||(r(e),this.currentPageUrl=n(),this.visit.to.url=this.currentPageUrl),this.visit.animation.animate&&this.classes.add("is-rendering"),this.visit.to.html=i,await this.hooks.call("content:replace",{page:t},(t,{page:e})=>{if(!this.replaceContent(e,{containers:t.containers}))throw new Error("[swup] Container mismatch, aborting");t.animation.animate&&(this.classes.add("is-animating","is-changing","is-rendering"),t.animation.name&&this.classes.add(`to-${s(t.animation.name)}`))}),await this.hooks.call("content:scroll",void 0,()=>this.scrollToContent()),await this.hooks.call("page:view",{url:this.currentPageUrl,title:document.title})},D=function(t){var e;if(e=t,Boolean(null==e?void 0:e.isSwupPlugin)){if(t.swup=this,!t._checkRequirements||t._checkRequirements())return t._beforeMount&&t._beforeMount(),t.mount(),this.plugins.push(t),this.plugins}else console.error("Not a swup plugin instance",t)};function O(t){const e=this.findPlugin(t);if(e)return e.unmount(),e._afterUnmount&&e._afterUnmount(),this.plugins=this.plugins.filter(t=>t!==e),this.plugins;console.error("No such plugin",e)}function M(t){return this.plugins.find(e=>e===t||e.name===t||e.name===`Swup${String(t)}`)}function V(t){if("function"!=typeof this.options.resolveUrl)return console.warn("[swup] options.resolveUrl expects a callback function."),t;const e=this.options.resolveUrl(t);return e&&"string"==typeof e?e.startsWith("//")||e.startsWith("http")?(console.warn("[swup] options.resolveUrl needs to return a relative url"),t):e:(console.warn("[swup] options.resolveUrl needs to return a url"),t)}function W(t,e){return this.resolveUrl(t)===this.resolveUrl(e)}const B={animateHistoryBrowsing:!1,animationSelector:'[class*="transition-"]',animationScope:"html",cache:!0,containers:["#swup"],ignoreVisit:(t,{el:e}={})=>!(null==e||!e.closest("[data-no-swup]")),linkSelector:"a[href]",linkToSelf:"scroll",plugins:[],resolveUrl:t=>t,requestHeaders:{"X-Requested-With":"swup",Accept:"text/html, application/xhtml+xml"},skipPopStateHandling:t=>{var e;return"swup"!==(null==(e=t.state)?void 0:e.source)},timeout:0};class _{constructor(t={}){var e,s;this.version="4.4.2",this.options=void 0,this.defaults=B,this.plugins=[],this.visit=void 0,this.cache=void 0,this.hooks=void 0,this.classes=void 0,this.currentPageUrl=n(),this.currentHistoryIndex=void 0,this.clickDelegate=void 0,this.navigating=!1,this.use=D,this.unuse=O,this.findPlugin=M,this.log=()=>{},this.navigate=A,this.performNavigation=q,this.createVisit=b,this.delegateEvent=a,this.fetchPage=u,this.awaitAnimations=$,this.renderPage=T,this.replaceContent=R,this.animatePageIn=N,this.animatePageOut=I,this.scrollToContent=L,this.getAnchorElement=P,this.getCurrentUrl=n,this.resolveUrl=V,this.isSameResolvedUrl=W,this.options=i({},this.defaults,t),this.handleLinkClick=this.handleLinkClick.bind(this),this.handlePopState=this.handlePopState.bind(this),this.cache=new d(this),this.classes=new S(this),this.hooks=new E(this),this.visit=this.createVisit({to:""}),this.currentHistoryIndex=null!=(e=null==(s=history.state)?void 0:s.index)?e:1,this.checkRequirements()&&this.enable()}checkRequirements(){return"undefined"!=typeof Promise||(console.warn("Promise is not supported"),!1)}async enable(){var t;const{linkSelector:e}=this.options;this.clickDelegate=this.delegateEvent(e,"click",this.handleLinkClick),window.addEventListener("popstate",this.handlePopState),this.options.animateHistoryBrowsing&&(window.history.scrollRestoration="manual"),this.options.plugins.forEach(t=>this.use(t)),"swup"!==(null==(t=history.state)?void 0:t.source)&&r(null,{index:this.currentHistoryIndex}),await g(),await this.hooks.call("enable",void 0,()=>{document.documentElement.classList.add("swup-enabled")})}async destroy(){this.clickDelegate.destroy(),window.removeEventListener("popstate",this.handlePopState),this.cache.clear(),this.options.plugins.forEach(t=>this.unuse(t)),await this.hooks.call("disable",void 0,()=>{document.documentElement.classList.remove("swup-enabled")}),this.hooks.clear()}shouldIgnoreVisit(t,{el:e,event:i}={}){const{origin:s,url:n,hash:o}=l.fromUrl(t);return s!==window.location.origin||!(!e||!this.triggerWillOpenNewWindow(e))||!!this.options.ignoreVisit(n+o,{el:e,event:i})}handleLinkClick(t){const e=t.delegateTarget,{href:i,url:s,hash:n}=l.fromElement(e);this.shouldIgnoreVisit(i,{el:e,event:t})||(this.navigating&&s===this.visit.to.url?t.preventDefault():(this.visit=this.createVisit({to:s,hash:n,el:e,event:t}),t.metaKey||t.ctrlKey||t.shiftKey||t.altKey?this.hooks.call("link:newtab",{href:i}):0===t.button&&this.hooks.callSync("link:click",{el:e,event:t},()=>{var e;const i=null!=(e=this.visit.from.url)?e:"";t.preventDefault(),s&&s!==i?this.isSameResolvedUrl(s,i)||this.performNavigation():n?this.hooks.callSync("link:anchor",{hash:n},()=>{r(s+n),this.scrollToContent()}):this.hooks.callSync("link:self",void 0,()=>"navigate"===this.options.linkToSelf?this.performNavigation():(r(s),this.scrollToContent()))})))}handlePopState(t){var e,i,s,o;const r=null!=(e=null==(i=t.state)?void 0:i.url)?e:location.href;if(this.options.skipPopStateHandling(t))return;if(this.isSameResolvedUrl(n(),this.currentPageUrl))return;const{url:a,hash:h}=l.fromUrl(r);this.visit=this.createVisit({to:a,hash:h,event:t}),this.visit.history.popstate=!0;const c=null!=(s=null==(o=t.state)?void 0:o.index)?s:0;c&&c!==this.currentHistoryIndex&&(this.visit.history.direction=c-this.currentHistoryIndex>0?"forwards":"backwards",this.currentHistoryIndex=c),this.visit.animation.animate=!1,this.visit.scroll.reset=!1,this.visit.scroll.target=!1,this.options.animateHistoryBrowsing&&(this.visit.animation.animate=!0,this.visit.scroll.reset=!0),this.hooks.callSync("history:popstate",{event:t},()=>{this.performNavigation()})}triggerWillOpenNewWindow(t){return!!t.matches('[download], [target="_blank"]')}}export{l as Location,s as classify,o as createHistoryRecord,_ as default,a as delegateEvent,y as escapeCssIdentifier,v as forceReflow,n as getCurrentUrl,f as isPromise,h as matchPath,g as nextTick,p as query,m as queryAll,w as runAsPromise,k as toMs,r as updateHistoryRecord};
|
|
1
|
+
import t from"delegate-it";import{match as e}from"path-to-regexp";function i(){return i=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(t[s]=i[s])}return t},i.apply(this,arguments)}const s=(t,e)=>String(t).toLowerCase().replace(/[\s/_.]+/g,"-").replace(/[^\w-]+/g,"").replace(/--+/g,"-").replace(/^-+|-+$/g,"")||e||"",n=({hash:t}={})=>location.pathname+location.search+(t?location.hash:""),o=(t,e={})=>{const s=i({url:t=t||n({hash:!0}),random:Math.random(),source:"swup"},e);history.pushState(s,"",t)},r=(t=null,e={})=>{t=t||n({hash:!0});const s=i({},history.state||{},{url:t,random:Math.random(),source:"swup"},e);history.replaceState(s,"",t)},a=(e,s,n,o)=>{const r=new AbortController;return o=i({},o,{signal:r.signal}),t(e,s,n,o),{destroy:()=>r.abort()}};class l extends URL{constructor(t,e=document.baseURI){super(t.toString(),e),Object.setPrototypeOf(this,l.prototype)}get url(){return this.pathname+this.search}static fromElement(t){const e=t.getAttribute("href")||t.getAttribute("xlink:href")||"";return new l(e)}static fromUrl(t){return new l(t)}}const h=(t,i)=>{try{return e(t,i)}catch(e){throw new Error(`[swup] Error parsing path "${String(t)}":\n${String(e)}`)}};class c extends Error{constructor(t,e){super(t),this.url=void 0,this.status=void 0,this.aborted=void 0,this.timedOut=void 0,this.name="FetchError",this.url=e.url,this.status=e.status,this.aborted=e.aborted||!1,this.timedOut=e.timedOut||!1}}async function u(t,e={}){var s;t=l.fromUrl(t).url;const n=i({},this.options.requestHeaders,e.headers),o=null!=(s=e.timeout)?s:this.options.timeout,r=new AbortController,{signal:a}=r;e=i({},e,{headers:n,signal:a});let h,u=!1,d=null;o&&o>0&&(d=setTimeout(()=>{u=!0,r.abort("timeout")},o));try{h=await this.hooks.call("fetch:request",{url:t,options:e},(t,{url:e,options:i})=>fetch(e,i)),d&&clearTimeout(d)}catch(e){if(u)throw this.hooks.call("fetch:timeout",{url:t}),new c(`Request timed out: ${t}`,{url:t,timedOut:u});if("AbortError"===(null==e?void 0:e.name)||a.aborted)throw new c(`Request aborted: ${t}`,{url:t,aborted:!0});throw e}const{status:p,url:m}=h,g=await h.text();if(500===p)throw this.hooks.call("fetch:error",{status:p,response:h,url:m}),new c(`Server error: ${m}`,{status:p,url:m});if(!g)throw new c(`Empty response: ${m}`,{status:p,url:m});const{url:f}=l.fromUrl(m),w={url:f,html:g};return!this.visit.cache.write||e.method&&"GET"!==e.method||t!==f||this.cache.set(w.url,w),w}class d{constructor(t){this.swup=void 0,this.pages=new Map,this.swup=t}get size(){return this.pages.size}get all(){const t=new Map;return this.pages.forEach((e,s)=>{t.set(s,i({},e))}),t}has(t){return this.pages.has(this.resolve(t))}get(t){const e=this.pages.get(this.resolve(t));return e?i({},e):e}set(t,e){e=i({},e,{url:t=this.resolve(t)}),this.pages.set(t,e),this.swup.hooks.callSync("cache:set",{page:e})}update(t,e){t=this.resolve(t);const s=i({},this.get(t),e,{url:t});this.pages.set(t,s)}delete(t){this.pages.delete(this.resolve(t))}clear(){this.pages.clear(),this.swup.hooks.callSync("cache:clear",void 0)}prune(t){this.pages.forEach((e,i)=>{t(i,e)&&this.delete(i)})}resolve(t){const{url:e}=l.fromUrl(t);return this.swup.resolveUrl(e)}}const p=(t,e=document)=>e.querySelector(t),m=(t,e=document)=>Array.from(e.querySelectorAll(t)),g=()=>new Promise(t=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>{t()})})});function f(t){return!!t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then}function w(t,e=[]){return new Promise((i,s)=>{const n=t(...e);f(n)?n.then(i,s):i(n)})}function v(t){var e;return null==(e=t=t||document.body)?void 0:e.offsetHeight}const y=t=>window.CSS&&window.CSS.escape?CSS.escape(t):t,k=t=>1e3*Number(t.slice(0,-1).replace(",","."));class b{constructor(t){this.swup=void 0,this.swupClasses=["to-","is-changing","is-rendering","is-popstate","is-animating"],this.swup=t}get selectors(){const{scope:t}=this.swup.visit.animation;return"containers"===t?this.swup.visit.containers:"html"===t?["html"]:Array.isArray(t)?t:[]}get selector(){return this.selectors.join(",")}get targets(){return this.selector.trim()?m(this.selector):[]}add(...t){this.targets.forEach(e=>e.classList.add(...t))}remove(...t){this.targets.forEach(e=>e.classList.remove(...t))}clear(){this.targets.forEach(t=>{const e=t.className.split(" ").filter(t=>this.isSwupClass(t));t.classList.remove(...e)})}isSwupClass(t){return this.swupClasses.some(e=>t.startsWith(e))}}function S({to:t,from:e=this.currentPageUrl,hash:i,el:s,event:n}){return{id:Math.random(),from:{url:e},to:{url:t,hash:i},containers:this.options.containers,animation:{animate:!0,wait:!1,name:void 0,scope:this.options.animationScope,selector:this.options.animationSelector},trigger:{el:s,event:n},cache:{read:this.options.cache,write:this.options.cache},history:{action:"push",popstate:!1,direction:void 0},scroll:{reset:!0,target:void 0}}}class E{constructor(t){this.swup=void 0,this.registry=new Map,this.hooks=["animation:out:start","animation:out:await","animation:out:end","animation:in:start","animation:in:await","animation:in:end","animation:skip","cache:clear","cache:set","content:replace","content:scroll","enable","disable","fetch:request","fetch:error","fetch:timeout","history:popstate","link:click","link:self","link:anchor","link:newtab","page:load","page:view","scroll:top","scroll:anchor","visit:start","visit:transition","visit:end"],this.swup=t,this.init()}init(){this.hooks.forEach(t=>this.create(t))}create(t){this.registry.has(t)||this.registry.set(t,new Map)}exists(t){return this.registry.has(t)}get(t){const e=this.registry.get(t);if(e)return e;console.error(`Unknown hook '${t}'`)}clear(){this.registry.forEach(t=>t.clear())}on(t,e,s={}){const n=this.get(t);if(!n)return console.warn(`Hook '${t}' not found.`),()=>{};const o=i({},s,{id:n.size+1,hook:t,handler:e});return n.set(e,o),()=>this.off(t,e)}before(t,e,s={}){return this.on(t,e,i({},s,{before:!0}))}replace(t,e,s={}){return this.on(t,e,i({},s,{replace:!0}))}once(t,e,s={}){return this.on(t,e,i({},s,{once:!0}))}off(t,e){const i=this.get(t);i&&e?i.delete(e)||console.warn(`Handler for hook '${t}' not found.`):i&&i.clear()}async call(t,e,i){const{before:s,handler:n,after:o}=this.getHandlers(t,i);await this.run(s,e);const[r]=await this.run(n,e);return await this.run(o,e),this.dispatchDomEvent(t,e),r}callSync(t,e,i){const{before:s,handler:n,after:o}=this.getHandlers(t,i);this.runSync(s,e);const[r]=this.runSync(n,e);return this.runSync(o,e),this.dispatchDomEvent(t,e),r}async run(t,e){const i=[];for(const{hook:s,handler:n,defaultHandler:o,once:r}of t){const t=await w(n,[this.swup.visit,e,o]);i.push(t),r&&this.off(s,n)}return i}runSync(t,e){const i=[];for(const{hook:s,handler:n,defaultHandler:o,once:r}of t){const t=n(this.swup.visit,e,o);i.push(t),f(t)&&console.warn(`Promise returned from handler for synchronous hook '${s}'.Swup will not wait for it to resolve.`),r&&this.off(s,n)}return i}getHandlers(t,e){const i=this.get(t);if(!i)return{found:!1,before:[],handler:[],after:[],replaced:!1};const s=Array.from(i.values()),n=this.sortRegistrations,o=s.filter(({before:t,replace:e})=>t&&!e).sort(n),r=s.filter(({replace:t})=>t).filter(t=>!0).sort(n),a=s.filter(({before:t,replace:e})=>!t&&!e).sort(n),l=r.length>0;let h=[];if(e&&(h=[{id:0,hook:t,handler:e}],l)){const i=r.length-1,s=t=>{const i=r[t-1];return i?(e,n)=>i.handler(e,n,s(t-1)):e};h=[{id:0,hook:t,handler:r[i].handler,defaultHandler:s(i)}]}return{found:!0,before:o,handler:h,after:a,replaced:l}}sortRegistrations(t,e){var i,s;return(null!=(i=t.priority)?i:0)-(null!=(s=e.priority)?s:0)||t.id-e.id||0}dispatchDomEvent(t,e){const i={hook:t,args:e,visit:this.swup.visit};document.dispatchEvent(new CustomEvent("swup:any",{detail:i,bubbles:!0})),document.dispatchEvent(new CustomEvent(`swup:${t}`,{detail:i,bubbles:!0}))}}const P=t=>{if(t&&"#"===t.charAt(0)&&(t=t.substring(1)),!t)return null;const e=decodeURIComponent(t);let i=document.getElementById(t)||document.getElementById(e)||p(`a[name='${y(t)}']`)||p(`a[name='${y(e)}']`);return i||"top"!==t||(i=document.body),i},U="transition",C="animation";async function $({elements:t,selector:e}){if(!1===e&&!t)return;let i=[];if(t)i=Array.from(t);else if(e&&(i=m(e,document.body),!i.length))return void console.warn(`[swup] No elements found matching animationSelector \`${e}\``);const s=i.map(t=>function(t){const{type:e,timeout:i,propCount:s}=function(t,e){const i=window.getComputedStyle(t),s=x(i,`${U}Delay`),n=x(i,`${U}Duration`),o=H(s,n),r=x(i,`${C}Delay`),a=x(i,`${C}Duration`),l=H(r,a);let h=null,c=0,u=0;return c=Math.max(o,l),h=c>0?o>l?U:C:null,u=h?h===U?n.length:a.length:0,{type:h,timeout:c,propCount:u}}(t);return!(!e||!i)&&new Promise(n=>{const o=`${e}end`,r=performance.now();let a=0;const l=()=>{t.removeEventListener(o,h),n()},h=e=>{if(e.target===t){if(!function(t){return[`${U}end`,`${C}end`].includes(t.type)}(e))throw new Error("Not a transition or animation event.");(performance.now()-r)/1e3<e.elapsedTime||++a>=s&&l()}};setTimeout(()=>{a<s&&l()},i+1),t.addEventListener(o,h)})}(t));s.filter(Boolean).length>0?await Promise.all(s):e&&console.warn(`[swup] No CSS animation duration defined on elements matching \`${e}\``)}function x(t,e){return(t[e]||"").split(", ")}function H(t,e){for(;t.length<e.length;)t=t.concat(t);return Math.max(...e.map((e,i)=>k(e)+k(t[i])))}function A(t,e={},s={}){if("string"!=typeof t)throw new Error("swup.navigate() requires a URL parameter");if(this.shouldIgnoreVisit(t,{el:s.el,event:s.event}))return void(window.location.href=t);const{url:n,hash:o}=l.fromUrl(t);this.visit=this.createVisit(i({},s,{to:n,hash:o})),this.performNavigation(e)}async function q(t={}){this.navigating=!0;const e=this.visit,{el:i}=e.trigger;t.referrer=t.referrer||this.currentPageUrl,!1===t.animate&&(e.animation.animate=!1),e.animation.animate||this.classes.clear();const s=t.history||(null==i?void 0:i.getAttribute("data-swup-history"))||void 0;s&&["push","replace"].includes(s)&&(e.history.action=s);const a=t.animation||(null==i?void 0:i.getAttribute("data-swup-animation"))||void 0;var l,h;a&&(e.animation.name=a),"object"==typeof t.cache?(e.cache.read=null!=(l=t.cache.read)?l:e.cache.read,e.cache.write=null!=(h=t.cache.write)?h:e.cache.write):void 0!==t.cache&&(e.cache={read:!!t.cache,write:!!t.cache}),delete t.cache;try{await this.hooks.call("visit:start",void 0);const i=this.hooks.call("page:load",{options:t},async(t,e)=>{let i;return t.cache.read&&(i=this.cache.get(t.to.url)),e.page=i||await this.fetchPage(t.to.url,e.options),e.cache=!!i,e.page});if(!e.history.popstate){const t=e.to.url+e.to.hash;"replace"===e.history.action||e.to.url===this.currentPageUrl?r(t):(this.currentHistoryIndex++,o(t,{index:this.currentHistoryIndex}))}if(this.currentPageUrl=n(),e.animation.wait){const{html:t}=await i;e.to.html=t}await this.hooks.call("visit:transition",void 0,async t=>{const e=this.animatePageOut(),[s]=await Promise.all([i,e]);return t.id===this.visit.id&&(await this.renderPage(s),await this.animatePageIn(),!0)}),await this.hooks.call("visit:end",void 0,()=>this.classes.clear()),this.navigating=!1}catch(t){if(!t||null!=t&&t.aborted)return;console.error(t),this.options.skipPopStateHandling=()=>(window.location.href=e.to.url+e.to.hash,!0),window.history.go(-1)}}const I=async function(){this.visit.animation.animate?(await this.hooks.call("animation:out:start",void 0,t=>{this.classes.add("is-changing","is-leaving","is-animating"),t.history.popstate&&this.classes.add("is-popstate"),t.animation.name&&this.classes.add(`to-${s(t.animation.name)}`)}),await this.hooks.call("animation:out:await",{skip:!1},async(t,{skip:e})=>{e||await this.awaitAnimations({selector:t.animation.selector})}),await this.hooks.call("animation:out:end",void 0)):await this.hooks.call("animation:skip",void 0)},R=function({html:t},{containers:e}=this.options){var i;const s=(new DOMParser).parseFromString(t,"text/html"),n=(null==(i=s.querySelector("title"))?void 0:i.innerText)||"";document.title=n;const o=m('[data-swup-persist]:not([data-swup-persist=""])'),r=e.map(t=>{const e=document.querySelector(t),i=s.querySelector(t);return e&&i?(e.replaceWith(i),!0):(e||console.warn(`[swup] Container missing in current document: ${t}`),i||console.warn(`[swup] Container missing in incoming document: ${t}`),!1)}).filter(Boolean);return o.forEach(t=>{const e=t.getAttribute("data-swup-persist"),i=p(`[data-swup-persist="${e}"]`);i&&i!==t&&i.replaceWith(t)}),r.length===e.length},L=function(){const t={behavior:"auto"},{target:e,reset:s}=this.visit.scroll,n=null!=e?e:this.visit.to.hash;let o=!1;return n&&(o=this.hooks.callSync("scroll:anchor",{hash:n,options:t},(t,{hash:e,options:i})=>{const s=this.getAnchorElement(e);return s&&s.scrollIntoView(i),!!s})),s&&!o&&(o=this.hooks.callSync("scroll:top",{options:t},(t,{options:e})=>(window.scrollTo(i({top:0,left:0},e)),!0))),o},O=async function(){if(!this.visit.animation.animate)return;const t=this.hooks.call("animation:in:await",{skip:!1},async(t,{skip:e})=>{e||await this.awaitAnimations({selector:t.animation.selector})});await g(),await this.hooks.call("animation:in:start",void 0,()=>{this.classes.remove("is-animating")}),await t,await this.hooks.call("animation:in:end",void 0)},N=async function(t){const{url:e,html:i}=t;this.classes.remove("is-leaving"),this.isSameResolvedUrl(n(),e)||(r(e),this.currentPageUrl=n(),this.visit.to.url=this.currentPageUrl),this.visit.animation.animate&&this.classes.add("is-rendering"),this.visit.to.html=i,await this.hooks.call("content:replace",{page:t},(t,{page:e})=>{if(!this.replaceContent(e,{containers:t.containers}))throw new Error("[swup] Container mismatch, aborting");t.animation.animate&&(this.classes.add("is-animating","is-changing","is-rendering"),t.animation.name&&this.classes.add(`to-${s(t.animation.name)}`))}),await this.hooks.call("content:scroll",void 0,()=>this.scrollToContent()),await this.hooks.call("page:view",{url:this.currentPageUrl,title:document.title})},T=function(t){var e;if(e=t,Boolean(null==e?void 0:e.isSwupPlugin)){if(t.swup=this,!t._checkRequirements||t._checkRequirements())return t._beforeMount&&t._beforeMount(),t.mount(),this.plugins.push(t),this.plugins}else console.error("Not a swup plugin instance",t)};function D(t){const e=this.findPlugin(t);if(e)return e.unmount(),e._afterUnmount&&e._afterUnmount(),this.plugins=this.plugins.filter(t=>t!==e),this.plugins;console.error("No such plugin",e)}function M(t){return this.plugins.find(e=>e===t||e.name===t||e.name===`Swup${String(t)}`)}function V(t){if("function"!=typeof this.options.resolveUrl)return console.warn("[swup] options.resolveUrl expects a callback function."),t;const e=this.options.resolveUrl(t);return e&&"string"==typeof e?e.startsWith("//")||e.startsWith("http")?(console.warn("[swup] options.resolveUrl needs to return a relative url"),t):e:(console.warn("[swup] options.resolveUrl needs to return a url"),t)}function W(t,e){return this.resolveUrl(t)===this.resolveUrl(e)}const B={animateHistoryBrowsing:!1,animationSelector:'[class*="transition-"]',animationScope:"html",cache:!0,containers:["#swup"],ignoreVisit:(t,{el:e}={})=>!(null==e||!e.closest("[data-no-swup]")),linkSelector:"a[href]",linkToSelf:"scroll",plugins:[],resolveUrl:t=>t,requestHeaders:{"X-Requested-With":"swup",Accept:"text/html, application/xhtml+xml"},skipPopStateHandling:t=>{var e;return"swup"!==(null==(e=t.state)?void 0:e.source)},timeout:0};class _{constructor(t={}){var e,s;this.version="4.4.4",this.options=void 0,this.defaults=B,this.plugins=[],this.visit=void 0,this.cache=void 0,this.hooks=void 0,this.classes=void 0,this.currentPageUrl=n(),this.currentHistoryIndex=void 0,this.clickDelegate=void 0,this.navigating=!1,this.use=T,this.unuse=D,this.findPlugin=M,this.log=()=>{},this.navigate=A,this.performNavigation=q,this.createVisit=S,this.delegateEvent=a,this.fetchPage=u,this.awaitAnimations=$,this.renderPage=N,this.replaceContent=R,this.animatePageIn=O,this.animatePageOut=I,this.scrollToContent=L,this.getAnchorElement=P,this.getCurrentUrl=n,this.resolveUrl=V,this.isSameResolvedUrl=W,this.options=i({},this.defaults,t),this.handleLinkClick=this.handleLinkClick.bind(this),this.handlePopState=this.handlePopState.bind(this),this.cache=new d(this),this.classes=new b(this),this.hooks=new E(this),this.visit=this.createVisit({to:""}),this.currentHistoryIndex=null!=(e=null==(s=history.state)?void 0:s.index)?e:1,this.checkRequirements()&&this.enable()}checkRequirements(){return"undefined"!=typeof Promise||(console.warn("Promise is not supported"),!1)}async enable(){var t;const{linkSelector:e}=this.options;this.clickDelegate=this.delegateEvent(e,"click",this.handleLinkClick),window.addEventListener("popstate",this.handlePopState),this.options.animateHistoryBrowsing&&(window.history.scrollRestoration="manual"),this.options.plugins.forEach(t=>this.use(t)),"swup"!==(null==(t=history.state)?void 0:t.source)&&r(null,{index:this.currentHistoryIndex}),await g(),await this.hooks.call("enable",void 0,()=>{document.documentElement.classList.add("swup-enabled")})}async destroy(){this.clickDelegate.destroy(),window.removeEventListener("popstate",this.handlePopState),this.cache.clear(),this.options.plugins.forEach(t=>this.unuse(t)),await this.hooks.call("disable",void 0,()=>{document.documentElement.classList.remove("swup-enabled")}),this.hooks.clear()}shouldIgnoreVisit(t,{el:e,event:i}={}){const{origin:s,url:n,hash:o}=l.fromUrl(t);return s!==window.location.origin||!(!e||!this.triggerWillOpenNewWindow(e))||!!this.options.ignoreVisit(n+o,{el:e,event:i})}handleLinkClick(t){const e=t.delegateTarget,{href:i,url:s,hash:n}=l.fromElement(e);this.shouldIgnoreVisit(i,{el:e,event:t})||(this.navigating&&s===this.visit.to.url?t.preventDefault():(this.visit=this.createVisit({to:s,hash:n,el:e,event:t}),t.metaKey||t.ctrlKey||t.shiftKey||t.altKey?this.hooks.call("link:newtab",{href:i}):0===t.button&&this.hooks.callSync("link:click",{el:e,event:t},()=>{var e;const i=null!=(e=this.visit.from.url)?e:"";t.preventDefault(),s&&s!==i?this.isSameResolvedUrl(s,i)||this.performNavigation():n?this.hooks.callSync("link:anchor",{hash:n},()=>{r(s+n),this.scrollToContent()}):this.hooks.callSync("link:self",void 0,()=>"navigate"===this.options.linkToSelf?this.performNavigation():(r(s),this.scrollToContent()))})))}handlePopState(t){var e,i,s,o;const r=null!=(e=null==(i=t.state)?void 0:i.url)?e:location.href;if(this.options.skipPopStateHandling(t))return;if(this.isSameResolvedUrl(n(),this.currentPageUrl))return;const{url:a,hash:h}=l.fromUrl(r);this.visit=this.createVisit({to:a,hash:h,event:t}),this.visit.history.popstate=!0;const c=null!=(s=null==(o=t.state)?void 0:o.index)?s:0;c&&c!==this.currentHistoryIndex&&(this.visit.history.direction=c-this.currentHistoryIndex>0?"forwards":"backwards",this.currentHistoryIndex=c),this.visit.animation.animate=!1,this.visit.scroll.reset=!1,this.visit.scroll.target=!1,this.options.animateHistoryBrowsing&&(this.visit.animation.animate=!0,this.visit.scroll.reset=!0),this.hooks.callSync("history:popstate",{event:t},()=>{this.performNavigation()})}triggerWillOpenNewWindow(t){return!!t.matches('[download], [target="_blank"]')}}export{l as Location,s as classify,o as createHistoryRecord,_ as default,a as delegateEvent,y as escapeCssIdentifier,v as forceReflow,n as getCurrentUrl,f as isPromise,h as matchPath,g as nextTick,p as query,m as queryAll,w as runAsPromise,k as toMs,r as updateHistoryRecord};
|
|
2
2
|
//# sourceMappingURL=Swup.modern.js.map
|