2023-03-21 10:49:35 +08:00

1 line
2.7 KiB
JavaScript

(()=>{function s(t,e){this.tocList=t,this.elementList=function t(e,n){if(null==e)return null;var i=e.children;if(0===i.length)return null;for(var s=[],o=0;o<i.length;o++){var l=i[o];-1!==n.indexOf(l.tagName)&&s.push(l),s.push.apply(s,t(l,n))}return s}(e,this.tocList),this.eIndex=0,this.build=function(){return null==this.elementList||0===this.elementList.length?"":this.analysis(-1,this.tocList.indexOf(this.elementList[this.eIndex].tagName))},this.analysis=function(t,e){for(var n="<ul class='menu-list'>";this.eIndex<this.elementList.length;){var i=this.elementList[this.eIndex],s=this.tocList.indexOf(i.tagName);if(t<s&&s<=e){e=s;var o=i.id,l=i.innerText;if(null!=o&&""!==o||(o=l+"_"+this.eIndex,i.setAttribute("id",o)),n+=`<li><a data-id="#${o}"><i class="fa fa-paperclip"></i>${l}</a>`,this.eIndex++,this.eIndex>=this.elementList.length){n+="</li>";break}(s=this.tocList.indexOf(this.elementList[this.eIndex].tagName))>e&&(n+=this.analysis(e,s)),n+="</li>"}else if(s<=t)break}return n+"</ul>"}}const r=[];function t(t){const i=new Set,s=new Map,o=Array.from(t.querySelectorAll(".menu-list > li > a"));for(const t of o){const r=t.getAttribute("data-id").trim().slice(1),i=document.getElementById(r);i&&s.set(i,t)}const l=Array.from(s.keys()),e=new IntersectionObserver(e=>{for(const n of e)n.isIntersecting?i.add(n.target):i.delete(n.target);let n;if(i.size?n=[...i].sort((t,e)=>t.offsetTop-e.offsetTop)[0]:l.length&&(n=l.filter(t=>t.offsetTop<window.scrollY).sort((t,e)=>e.offsetTop-t.offsetTop)[0]),n&&s.has(n)){o.forEach(t=>t.classList.remove("is-active"));const e=s.get(n);e.classList.add("is-active");let t=e.parentElement.parentElement;for(;t.classList.contains("menu-list")&&"li"===t.parentElement.tagName.toLowerCase();)t.parentElement.children[0].classList.add("is-active"),t=t.parentElement.parentElement}},{threshold:0});for(const t of l){if(e.observe(t),s.has(t)){const r=s.get(t);r.addEventListener("click",()=>{let n,t=document.getElementById(r.getAttribute("data-id").substring(1)).getBoundingClientRect(),i=window.pageYOffset,s=i+t.top-50,o=(s-i)/20,l=i>s?-1:1;window.requestAnimationFrame(function t(e){(i+=o)*l<s*l?(window.scrollTo(0,i),n=window.requestAnimationFrame(t)):(window.scrollTo(0,s),window.cancelAnimationFrame(n))})})}s.has(t)&&(t.style.scrollMargin="1em")}r.push(e)}s.init=function(t){var e=t.tocList,n=t.contentElement,t=t.tocElement;if(null==e||0===e.length||null==n)return $(t).children().remove(),!1;for(var i=0;i<e.length;i++)e[i]=e[i].toUpperCase();n=new s(e,n).build();$(t).html(n)},window.tocPjax=function(){r.forEach(t=>{t.disconnect()}),r.splice(0),s.init({tocList:["h1","h2","h3","h4","h5"],contentElement:$(".main-content:not(.not-toc)")[0],tocElement:".toc-content"}),void 0!==window.IntersectionObserver&&document.querySelectorAll(".toc-content").forEach(t)}})();