import{pageBreakManager as e}from"./page-break-manager.js";import{normalizeEventPath as t}from"../../utils/utils.js";export class PageBreakOutline extends HTMLElement{constructor(){super(),this.windowControllers=new AbortController,this.target=null,this.selector=null,this.div=globalThis.document.createElement("div"),this.appendChild(this.div),this.basePath="",this.addEventListener("click",this.clickHandler.bind(this))}static get tag(){return"page-break-outline"}static get observedAttributes(){return["selector","base-path"]}attributeChangedCallback(e,t,r){"base-path"===e&&r&&(this.basePath=r),"selector"===e&&r&&(this.selector=r,this.target=globalThis.document.querySelector(this.selector),this.render(this.div))}connectedCallback(){setTimeout((()=>{globalThis.addEventListener("page-break-change",this.rerender.bind(this),{signal:this.windowControllers.signal})}),0),this.render(this.div)}disconnectedCallback(){this.windowControllers.abort()}clickHandler(r){var a=t(r)[0];if("A"===a.tagName){r.preventDefault(),r.stopPropagation(),r.stopImmediatePropagation();for(var i=0;i<e.breaks.length;i++)if(e.breaks[i].path===a.getAttribute("href")){e.breaks[i].scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"});break}}}rerender(){this.__lock||(this.__lock=!0,setTimeout((()=>{let e=this.div.cloneNode(!1);this.render(e),this.replaceChild(e,this.div),this.div=e,this.__lock=!1}),0))}render(e){if(this.target&&this.target.children&&this.target.children.length>0){var t="<ul>\n",r=[];const a=this.target.querySelectorAll("page-break");for(let e=0;e<a.length;e++){let i=a[e];if(r.length>0)if(i.parent&&-1!==r.indexOf(i.parent))for(;-1!==r.indexOf(i.parent);)t+="</ul></li>\n",r.shift();else if(i.parent&&-1===r.indexOf(i.parent));else{for(;r.length>0;)t+="</ul></li>\n",r.shift();t+="</ul></li>\n"}let n=0;0!==e&&i.parent&&this.target.querySelector(`page-break[path="${i.parent}"]`)&&(n=this.target.querySelector(`page-break[path="${i.parent}"]`).depth+1),t+=`<li>\n<a href="${this.basePath+i.path}" data-path="${i.path}" data-parent="${i.parent}" data-depth="${n}">${i.title}</a>\n`,i.depth=n,e!=a.length&&a[e+1]&&a[e+1].parent===i.path?(t+="<ul>\n",i.parent&&r.unshift(i.parent)):t+="</li>\n"}t+="</ul>\n",e.innerHTML=t}}}customElements.define(PageBreakOutline.tag,PageBreakOutline);