UNPKG

@vtbag/turn-signal

Version:

Turn-Signal is a lightweight script that enhances cross-document navigation by detecting the direction of browser navigation. It enables developers to create smooth, responsive transitions that adjust based on forward or backward navigation, delivering a

2 lines (1 loc) 2.44 kB
"use strict";(()=>{var g,o,s,d,l,c=t=>{history.state?.vtbagId??history.replaceState({vtbagId:history.length},""),o=parseInt(sessionStorage.getItem("vtbag-id")??"NaN",10),d=history.state.vtbagId,g=sessionStorage.getItem("vtbag-navigation-type"),sessionStorage.setItem("vtbag-id",""+d),s=sessionStorage.getItem("vtbag-from"),l=sessionStorage.getItem("vtbag-to")};addEventListener("pagereveal",c);var m=t=>{t.activation&&(g=t.activation.navigationType,s=t.activation.from?.url??"",l=t.activation.entry.url??"",o=history.state?.vtbagId,d=g==="push"?o+(s===l?0:1):g==="replace"?o:t.activation.entry.index!==-1?o+(t.activation.entry.index-(t.activation.from?.index??-1)):NaN,sessionStorage.setItem("vtbag-navigation-type",g),sessionStorage.setItem("vtbag-from",s),sessionStorage.setItem("vtbag-to",l))};addEventListener("pageswap",m);var u=document.currentScript;function p(t,a){let e,n,i=["backward","same","forward"],r=u.dataset.directionAttribute;return r&&(i=r.trim().split(/\s*,\s*/),i.length!==4?console.error(`[turn-signal] syntax error: data-direction-attribute value "${r}" does not match "attributeName, backwardValue, sameValue, forwardValue"`):(n=i.shift(),e=t<a?i[0]:t===a?i[1]:i[2])),{attributeName:n,value:e}}function b(t,a){let e=["backward","same","forward"],n=u.dataset.directionTypes;if(n&&(e=n.trim().split(/\s*,\s*/),e.length!==3)){console.error(`[turn-signal] syntax error: data-direction-types value "${n}" does not match "backwardValue, sameValue, forwardValue"`);return}return t<a?e[0]:t===a?e[1]:e[2]}function v(t){if(!t.viewTransition)return;let a=d,e=o,n=f();if(n.length&&(e=n.indexOf(new URL(s??".",location.href).pathname),a=n.indexOf(new URL(l??".",location.href).pathname)),sessionStorage.removeItem("vtbag-signal-attribute"),sessionStorage.removeItem("vtbag-signal-type"),!isNaN(a)){let{attributeName:i,value:r}=p(a,e);i&&r&&(document.documentElement.setAttribute(i,r),t.viewTransition.finished.then(()=>document.documentElement.removeAttribute(i)),sessionStorage.setItem("vtbag-signal-attribute",`${i} ${r}`)),r=b(a,e),r&&(t.viewTransition.types?.add(r),sessionStorage.setItem("vtbag-signal-type",r))}t.viewTransition.types?.add(t.type==="pageswap"?"old":"new")}function f(){let t=u.dataset.selector;return t?[...document.querySelectorAll(t)].map(e=>new URL(e.href??".",location.href).pathname):[]}"onpageswap"in window&&addEventListener("pageswap",v);"onpagereveal"in window&&addEventListener("pagereveal",v);})();