l.right+c||i.clientX<=l.right&&i.clientY>l.bottom&&i.clientX>=l.left:i.clientX>l.right&&i.clientY>l.top||i.clientX<=l.right&&i.clientY>l.bottom+c}function Jx(i,t,n,l,c,d,a,h){var f=l?i.clientY:i.clientX,p=l?n.height:n.width,y=l?n.top:n.left,g=l?n.bottom:n.right,v=!1;if(!a){if(h&&lay+p*d/2:fg-la)return-so}else if(f>y+p*(1-c)/2&&fg-p*d/2)?f>y+p/2?1:-1:0}function e0(i){return Br(Ze)
{let d=c.target.closest(".sort-box-options [data-sort]");if(!d)return;c.preventDefault();let a=d.closest(".sort-box").querySelectorAll("ul"),h=d.getAttribute("data-sort");n=t===h?!n:!1;let f=Tf[h];n&&l.includes(h)&&(f=function(p,y){return 0-Tf[h](p,y)});for(let p of a)Array.from(p.children).filter(g=>g.matches("li")).sort(f).forEach(g=>{p.appendChild(g)});t=h,this.updateMapInput()})}bookSelect(t){if(this.elem.querySelector(`[data-type="book"][data-id="${t.id}"]`)!==null)return;let l=t.link+"/sort-item";window.$http.get(l).then(c=>{let d=document.createElement("div");d.innerHTML=c.data;let a=d.children[0];this.sortContainer.append(a),this.setupBookSortable(a)})}setupBookSortable(t){let n=[t.querySelector(".sort-list")];n.push(...t.querySelectorAll(".entity-list-item + ul"));let l={name:"book",pull:["book","chapter"],put:["book","chapter"]},c={name:"chapter",pull:["book","chapter"],put:function(d,a,h){return h.getAttribute("data-type")==="page"}};for(let d of n)new gi(d,{group:d.classList.contains("sort-list")?l:c,animation:150,fallbackOnBody:!0,swapThreshold:.65,onSort:this.updateMapInput.bind(this),dragClass:"bg-white",ghostClass:"primary-background-light",multiDrag:!0,multiDragKey:"CTRL",selectedClass:"sortable-selected"})}updateMapInput(){let t=this.buildEntityMap();this.input.value=JSON.stringify(t)}buildEntityMap(){let t=[],n=this.elem.querySelectorAll(".sort-list");for(let l of n){let c=l.closest('[data-type="book"]').getAttribute("data-id"),d=Array.from(l.children).filter(a=>a.matches('[data-type="page"], [data-type="chapter"]'));for(let a=0;a{n&&n()})}function ga(i,t=400,n=null){ya(i),va(i,{opacity:["1","0"]},t,()=>{i.style.display="none",n&&n()})}function vi(i,t=400){ya(i);let n=i.getBoundingClientRect().height,l=getComputedStyle(i),c=l.getPropertyValue("padding-top"),d=l.getPropertyValue("padding-bottom"),a={height:[`${n}px`,"0px"],overflow:["hidden","hidden"],paddingTop:[c,"0px"],paddingBottom:[d,"0px"]};va(i,a,t,()=>{i.style.display="none"})}function yi(i,t=400){ya(i),i.style.display="block";let n=i.getBoundingClientRect().height,l=getComputedStyle(i),c=l.getPropertyValue("padding-top"),d=l.getPropertyValue("padding-bottom"),a={height:["0px",`${n}px`],overflow:["hidden","hidden"],paddingTop:["0px",c],paddingBottom:["0px",d]};va(i,a,t)}function va(i,t,n=400,l=null){let c=Object.keys(t);for(let a of c)i.style[a]=t[a][0];let d=()=>{for(let a of c)i.style[a]=null;i.style.transition=null,i.removeEventListener("transitionend",d),ma.delete(i),l&&l()};setTimeout(()=>{i.style.transition=`all ease-in-out ${n}ms`;for(let a of c)i.style[a]=t[a][1];i.addEventListener("transitionend",d),ma.set(i,d)},15)}function ya(i){ma.has(i)&&ma.get(i)()}var If=class{constructor(t){this.elem=t,this.isOpen=t.classList.contains("open"),t.addEventListener("click",this.click.bind(this))}open(){let t=this.elem.parentNode.querySelector(".inset-list");this.elem.classList.add("open"),this.elem.setAttribute("aria-expanded","true"),yi(t,240)}close(){let t=this.elem.parentNode.querySelector(".inset-list");this.elem.classList.remove("open"),this.elem.setAttribute("aria-expanded","false"),vi(t,240)}click(t){t.preventDefault(),this.isOpen?this.close():this.open(),this.isOpen=!this.isOpen}},Ff=If;var jn=St(At()),ch=St(Qs()),__=St(Js()),S_=St(el()),E_=St(Bf()),C_=St($f()),T_=St(Wf()),A_=St(Vf()),L_=St(rl()),D_=St(tl()),I_=St(nd()),F_=St(ad()),M_=St(dd()),O_=St(md()),P_=St(yd()),R_=St(wd()),z_=St(Sd()),N_=St(Td()),B_=St(Dd()),q_=St(Md()),j_=St(Rd()),$_=St(Bd()),U_=St(Wd()),H_=St(Vd()),W_=St(Zd()),G_=St(eh()),K_=St(nh()),V_=St(ba()),Y_=St(ah()),X_=St(uh()),nl={css:"css",c:"text/x-csrc",java:"text/x-java",scala:"text/x-scala",kotlin:"text/x-kotlin","c++":"text/x-c++src","c#":"text/x-csharp",csharp:"text/x-csharp",diff:"diff",for:"fortran",fortran:"fortran",go:"go",haskell:"haskell",hs:"haskell",html:"htmlmixed",ini:"properties",javascript:"javascript",json:{name:"javascript",json:!0},js:"javascript",jl:"julia",julia:"julia",lua:"lua",md:"markdown",mdown:"markdown",markdown:"markdown",ml:"mllike",nginx:"nginx",perl:"perl",pl:"perl",powershell:"powershell",properties:"properties",ocaml:"mllike",pascal:"text/x-pascal",pas:"text/x-pascal",php:i=>i.includes("/gi,`
`);let n=i.textContent.trimEnd(),l="";if(t!==null){let d=t.className.replace("language-","");l=xa(d,n)}let c=(0,jn.default)(function(d){i.parentNode.replaceChild(d,i)},{value:n,mode:l,lineNumbers:!0,lineWrapping:!1,theme:wa(),readOnly:!0});a0(c)}function a0(i){let t='',n=document.createElement("div");n.classList.add("CodeMirror-copy"),n.innerHTML=t,i.display.wrapper.appendChild(n),new ch.default(n,{text:function(c){return i.getValue()}}).on("success",c=>{n.classList.add("success"),setTimeout(()=>{n.classList.remove("success")},240)})}function xa(i,t){i=i.trim().replace(/^\./g,"").toLowerCase();let n=typeof nl[i];return n==="undefined"?"":n==="function"?nl[i](t):nl[i]}function wa(){let i=document.documentElement.classList.contains("dark-mode");return window.codeTheme||(i?"darcula":"default")}function s0(i){let t=i.ownerDocument,n=i.querySelector("code"),l=(i.className||"").replace("language-","");l===""&&n&&(l=(n.className||"").replace("language-","")),i.innerHTML=i.innerHTML.replace(/
/gi,`
`);let c=i.textContent,d=t.createElement("div"),a=t.createElement("textarea");d.className="CodeMirrorContainer",d.setAttribute("data-lang",l),d.setAttribute("dir","ltr"),a.style.display="none",i.parentNode.replaceChild(d,i),d.appendChild(a),d.contentEditable=!1,a.textContent=c;let h=(0,jn.default)(function(f){d.appendChild(f)},{value:c,mode:xa(l,c),lineNumbers:!0,lineWrapping:!1,theme:wa(),readOnly:!0});return{wrap:d,editor:h}}function l0(i,t){let n=i.textContent;return(0,jn.default)(function(l){i.parentNode.insertBefore(l,i),i.style.display="none"},{value:n,mode:xa(t,n),lineNumbers:!0,lineWrapping:!1,theme:wa()})}function u0(i,t,n){i.setOption("mode",xa(t,n))}function c0(i,t){i.setValue(t),setTimeout(()=>{dh(i)},10)}function dh(i){i.refresh()}function f0(i){let n={value:i.textContent,mode:"markdown",lineNumbers:!0,lineWrapping:!0,theme:wa(),scrollPastEnd:!0};return window.$events.emitPublic(i,"editor-markdown-cm::pre-init",{config:n}),(0,jn.default)(function(l){i.parentNode.insertBefore(l,i),i.style.display="none"},n)}function d0(){return jn.default.keyMap.default==jn.default.keyMap.macDefault?"Cmd":"Ctrl"}var ur={highlight:i0,highlightWithin:o0,wysiwygView:s0,popupEditor:l0,setMode:u0,setContent:c0,updateLayout:dh,markdownEditor:f0,getMetaKey:d0};var hh=class{setup(){this.container=this.$refs.container,this.popup=this.$el,this.editorInput=this.$refs.editor,this.languageLinks=this.$manyRefs.languageLink,this.saveButton=this.$refs.saveButton,this.languageInput=this.$refs.languageInput,this.historyDropDown=this.$refs.historyDropDown,this.historyList=this.$refs.historyList,this.callback=null,this.editor=null,this.history={},this.historyKey="code_history",this.setupListeners()}setupListeners(){this.container.addEventListener("keydown",t=>{t.ctrlKey&&t.key==="Enter"&&this.save()}),Rt(this.languageLinks,t=>{let n=t.target.dataset.lang;this.languageInput.value=n,this.updateEditorMode(n)}),Qo(this.languageInput,t=>this.save()),Rt(this.saveButton,t=>this.save()),$t(this.historyList,"button","click",(t,n)=>{t.preventDefault();let l=n.dataset.time;this.editor&&this.editor.setValue(this.history[l])})}save(){this.callback&&this.callback(this.editor.getValue(),this.languageInput.value),this.hide()}open(t,n,l){this.languageInput.value=n,this.callback=l,this.show(),this.updateEditorMode(n),ur.setContent(this.editor,t)}show(){this.editor||(this.editor=ur.popupEditor(this.editorInput,this.languageInput.value)),this.loadHistory(),this.popup.components.popup.show(()=>{ur.updateLayout(this.editor),this.editor.focus()},()=>{this.addHistory()})}hide(){this.popup.components.popup.hide(),this.addHistory()}updateEditorMode(t){ur.setMode(this.editor,t,this.editor.getValue())}loadHistory(){this.history=JSON.parse(window.sessionStorage.getItem(this.historyKey)||"{}");let t=Object.keys(this.history).reverse();this.historyDropDown.classList.toggle("hidden",t.length===0),this.historyList.innerHTML=t.map(n=>{let l=new Date(parseInt(n)).toLocaleTimeString();return``}).join("")}addHistory(){if(!this.editor)return;let t=this.editor.getValue();if(!t)return;let n=Object.keys(this.history).pop();if(this.history[n]===t)return;this.history[String(Date.now())]=t;let l=JSON.stringify(this.history);window.sessionStorage.setItem(this.historyKey,l)}},ph=hh;var mh=class{constructor(t){ur.highlightWithin(t)}},gh=mh;var vh=class{constructor(t){this.elem=t,this.trigger=t.querySelector("[collapsible-trigger]"),this.content=t.querySelector("[collapsible-content]"),!!this.trigger&&(this.trigger.addEventListener("click",this.toggle.bind(this)),this.openIfContainsError())}open(){this.elem.classList.add("open"),this.trigger.setAttribute("aria-expanded","true"),yi(this.content,300)}close(){this.elem.classList.remove("open"),this.trigger.setAttribute("aria-expanded","false"),vi(this.content,300)}toggle(){this.elem.classList.contains("open")?this.close():this.open()}openIfContainsError(){this.content.querySelector(".text-neg.text-small")&&this.open()}},yh=vh;var bh=class{constructor(t){this.elem=t,this.checkbox=t.querySelector("input[type=checkbox]"),this.display=t.querySelector('[role="checkbox"]'),this.checkbox.addEventListener("change",this.stateChange.bind(this)),this.elem.addEventListener("keydown",this.onKeyDown.bind(this))}onKeyDown(t){(t.keyCode===32||t.keyCode===13)&&(t.preventDefault(),this.toggle())}toggle(){this.checkbox.checked=!this.checkbox.checked,this.checkbox.dispatchEvent(new Event("change")),this.stateChange()}stateChange(){let t=this.checkbox.checked?"true":"false";this.display.setAttribute("aria-checked",t)}},xh=bh;var wh=class{constructor(t){this.elem=t,this.dealtWith=!1,t.addEventListener("toggle",this.onToggle.bind(this))}onToggle(){this.dealtWith||(ur.highlightWithin(this.elem),this.dealtWith=!0)}},kh=wh;var _h=class{setup(){this.container=this.$el,this.menu=this.$refs.menu,this.toggle=this.$refs.toggle,this.moveMenu=this.$opts.moveMenu,this.bubbleEscapes=this.$opts.bubbleEscapes==="true",this.direction=document.dir==="rtl"?"right":"left",this.body=document.body,this.showing=!1,this.setupListeners(),this.hide=this.hide.bind(this)}show(t=null){this.hideAll(),this.menu.style.display="block",this.menu.classList.add("anim","menuIn"),this.toggle.setAttribute("aria-expanded","true"),this.moveMenu&&(this.rect=this.menu.getBoundingClientRect(),this.body.appendChild(this.menu),this.menu.style.position="fixed",this.direction==="right"?this.menu.style.right=`${this.rect.right-this.rect.width}px`:this.menu.style.left=`${this.rect.left}px`,this.menu.style.top=`${this.rect.top}px`,this.menu.style.width=`${this.rect.width}px`),this.menu.addEventListener("mouseleave",this.hide.bind(this)),window.addEventListener("click",c=>{this.menu.contains(c.target)||this.hide()});let n=this.menu.querySelector("input");n!==null&&n.focus(),this.showing=!0;let l=new Event("show");this.container.dispatchEvent(l),t&&t.stopPropagation()}hideAll(){for(let t of window.components.dropdown)t.hide()}hide(){this.menu.style.display="none",this.menu.classList.remove("anim","menuIn"),this.toggle.setAttribute("aria-expanded","false"),this.moveMenu&&(this.menu.style.position="",this.menu.style[this.direction]="",this.menu.style.top="",this.menu.style.width="",this.container.appendChild(this.menu)),this.showing=!1}getFocusable(){return Array.from(this.menu.querySelectorAll("[tabindex],[href],button,input:not([type=hidden])"))}focusNext(){let t=this.getFocusable(),l=t.indexOf(document.activeElement)+1;l>=t.length&&(l=0),t[l].focus()}focusPrevious(){let t=this.getFocusable(),l=t.indexOf(document.activeElement)-1;l<0&&(l=t.length-1),t[l].focus()}setupListeners(){this.container.addEventListener("click",n=>{Array.from(this.menu.querySelectorAll("a")).includes(n.target)&&this.hide()}),Rt(this.toggle,n=>{n.stopPropagation(),this.show(n),n instanceof KeyboardEvent&&this.focusNext()});let t=n=>{n.key==="ArrowDown"||n.key==="ArrowRight"?(this.focusNext(),n.preventDefault()):n.key==="ArrowUp"||n.key==="ArrowLeft"?(this.focusPrevious(),n.preventDefault()):n.key==="Escape"&&(this.hide(),this.toggle.focus(),this.bubbleEscapes||n.stopPropagation())};this.container.addEventListener("keydown",t),this.moveMenu&&this.menu.addEventListener("keydown",t),this.menu.addEventListener("keydown ",n=>{n.key==="Enter"&&(n.preventDefault(),n.stopPropagation(),this.hide())})}},Sh=_h;var Eh=class{setup(){this.elem=this.$el,this.searchInput=this.$refs.searchInput,this.loadingElem=this.$refs.loading,this.listContainerElem=this.$refs.listContainer,this.localSearchSelector=this.$opts.localSearchSelector,this.url=this.$opts.url,this.elem.addEventListener("show",this.onShow.bind(this)),this.searchInput.addEventListener("input",this.onSearch.bind(this)),this.runAjaxSearch=Jo(this.runAjaxSearch,300,!1)}onShow(){this.loadList()}onSearch(){let t=this.searchInput.value.toLowerCase().trim();this.localSearchSelector?this.runLocalSearch(t):(this.toggleLoading(!0),this.runAjaxSearch(t))}runAjaxSearch(t){this.loadList(t)}runLocalSearch(t){let n=this.listContainerElem.querySelectorAll(this.localSearchSelector);for(let l of n){let c=!t||l.textContent.toLowerCase().includes(t);l.style.display=c?"flex":"none",l.classList.toggle("hidden",!c)}}async loadList(t=""){this.listContainerElem.innerHTML="",this.toggleLoading(!0);try{let n=await window.$http.get(this.getAjaxUrl(t));this.listContainerElem.innerHTML=n.data}catch(n){console.error(n)}this.toggleLoading(!1),this.localSearchSelector&&this.onSearch()}getAjaxUrl(t=null){if(!t)return this.url;let n=this.url.includes("?")?"&":"?";return`${this.url}${n}search=${encodeURIComponent(t)}`}toggleLoading(t=!1){this.loadingElem.style.display=t?"block":"none"}},Ch=Eh;var Ah=St(Th());var Lh=class{setup(){this.container=this.$el,this.url=this.$opts.url,this.successMessage=this.$opts.successMessage,this.removeMessage=this.$opts.removeMessage,this.uploadLimitMessage=this.$opts.uploadLimitMessage,this.timeoutMessage=this.$opts.timeoutMessage;let t=this;this.dz=new Ah.default(this.container,{addRemoveLinks:!0,dictRemoveFile:this.removeMessage,timeout:Number(window.uploadTimeout)||6e4,maxFilesize:Number(window.uploadLimit)||256,url:this.url,withCredentials:!0,init(){this.dz=this,this.dz.on("sending",t.onSending.bind(t)),this.dz.on("success",t.onSuccess.bind(t)),this.dz.on("error",t.onError.bind(t))}})}onSending(t,n,l){let c=window.document.querySelector("meta[name=token]").getAttribute("content");l.append("_token",c),n.ontimeout=d=>{this.dz.emit("complete",t),this.dz.emit("error",t,this.timeoutMessage)}}onSuccess(t,n){this.$emit("success",{file:t,data:n}),this.successMessage&&window.$events.emit("success",this.successMessage),ga(t.previewElement,800,()=>{this.dz.removeFile(t)})}onError(t,n,l){this.$emit("error",{file:t,errorMessage:n,xhr:l});let c=d=>{let a=t.previewElement.querySelector("[data-dz-errormessage]");a.textContent=d};l&&l.status===413?c(this.uploadLimitMessage):n.file&&c(n.file)}removeAll(){this.dz.removeAllFiles(!0)}},Dh=Lh;var Ih=class{constructor(t){this.elem=t,this.buttons=t.querySelectorAll("[toolbox-tab-button]"),this.contentElements=t.querySelectorAll("[toolbox-tab-content]"),this.toggleButton=t.querySelector("[toolbox-toggle]"),this.toggleButton.addEventListener("click",this.toggle.bind(this)),this.elem.addEventListener("click",n=>{let l=n.target.closest("[toolbox-tab-button]");if(l===null)return;let c=l.getAttribute("toolbox-tab-button");this.setActiveTab(c,!0)}),this.setActiveTab(this.contentElements[0].getAttribute("toolbox-tab-content"))}toggle(){this.elem.classList.toggle("open");let t=this.elem.classList.contains("open")?"true":"false";this.toggleButton.setAttribute("aria-expanded",t)}setActiveTab(t,n=!1){for(let l=0,c=this.buttons.length;l{t.preventDefault(),this.runSearch()}),Rt(this.clearButton,this.clearSearch.bind(this))}runSearch(){let t=this.searchInput.value.trim();if(t.length===0)return this.clearSearch();this.searchView.classList.remove("hidden"),this.contentView.classList.add("hidden"),this.loadingBlock.classList.remove("hidden");let n=window.baseUrl(`/search/${this.entityType}/${this.entityId}`);window.$http.get(n,{term:t}).then(l=>{this.searchResults.innerHTML=l.data}).catch(console.error).then(()=>{this.loadingBlock.classList.add("hidden")})}clearSearch(){this.searchView.classList.add("hidden"),this.contentView.classList.remove("hidden"),this.loadingBlock.classList.add("hidden"),this.searchInput.value=""}},Rh=Ph;var zh=class{setup(){this.elem=this.$el,this.entityTypes=this.$opts.entityTypes||"page,book,chapter",this.entityPermission=this.$opts.entityPermission||"view",this.input=this.$refs.input,this.searchInput=this.$refs.search,this.loading=this.$refs.loading,this.resultsContainer=this.$refs.results,this.addButton=this.$refs.add,this.search="",this.lastClick=0,this.selectedItemData=null,this.setupListeners(),this.showLoading(),this.initialLoad()}setupListeners(){this.elem.addEventListener("click",this.onClick.bind(this));let t=0;this.searchInput.addEventListener("input",n=>{t=Date.now(),this.showLoading(),setTimeout(()=>{Date.now()-t<199||this.searchEntities(this.searchInput.value)},200)}),this.searchInput.addEventListener("keydown",n=>{n.keyCode===13&&n.preventDefault()}),this.addButton&&this.addButton.addEventListener("click",n=>{this.selectedItemData&&(this.confirmSelection(this.selectedItemData),this.unselectAll())}),$t(this.$el,"[data-entity-type]","keydown",(n,l)=>{if(n.ctrlKey&&n.code==="Enter"){let c=this.$el.closest("form");if(c){c.submit(),n.preventDefault();return}}n.code==="ArrowDown"&&this.focusAdjacent(!0),n.code==="ArrowUp"&&this.focusAdjacent(!1)}),this.searchInput.addEventListener("keydown",n=>{n.code==="ArrowDown"&&this.focusAdjacent(!0)})}focusAdjacent(t=!0){let n=Array.from(this.resultsContainer.querySelectorAll("[data-entity-type]")),l=n.indexOf(document.activeElement),c=n[l+(t?1:-1)]||n[0];c&&c.focus()}showLoading(){this.loading.style.display="block",this.resultsContainer.style.display="none"}hideLoading(){this.loading.style.display="none",this.resultsContainer.style.display="block"}initialLoad(){window.$http.get(this.searchUrl()).then(t=>{this.resultsContainer.innerHTML=t.data,this.hideLoading()})}searchUrl(){return`/ajax/search/entities?types=${encodeURIComponent(this.entityTypes)}&permission=${encodeURIComponent(this.entityPermission)}`}searchEntities(t){this.input.value="";let n=`${this.searchUrl()}&term=${encodeURIComponent(t)}`;window.$http.get(n).then(l=>{this.resultsContainer.innerHTML=l.data,this.hideLoading()})}isDoubleClick(){let t=Date.now(),n=t-this.lastClick<300;return this.lastClick=t,n}onClick(t){let n=t.target.closest("[data-entity-type]");n&&(t.preventDefault(),t.stopPropagation(),this.selectItem(n))}selectItem(t){let n=this.isDoubleClick(),l=t.getAttribute("data-entity-type"),c=t.getAttribute("data-entity-id"),d=!t.classList.contains("selected")||n;this.unselectAll(),this.input.value=d?`${l}:${c}`:"";let a=t.getAttribute("href"),h=t.querySelector(".entity-list-item-name").textContent,f={id:Number(c),name:h,link:a};d?(t.classList.add("selected"),this.selectedItemData=f):window.$events.emit("entity-select-change",null),!(!n&&!d)&&(n&&this.confirmSelection(f),d&&window.$events.emit("entity-select-change",f))}confirmSelection(t){window.$events.emit("entity-select-confirm",t)}unselectAll(){let t=this.elem.querySelectorAll(".selected");for(let n of t)n.classList.remove("selected","primary-background");this.selectedItemData=null}},Nh=zh;var Bh=class{setup(){this.elem=this.$el,this.selectButton=this.$refs.select,window.EntitySelectorPopup=this,this.callback=null,this.selection=null,this.selectButton.addEventListener("click",this.onSelectButtonClick.bind(this)),window.$events.listen("entity-select-change",this.onSelectionChange.bind(this)),window.$events.listen("entity-select-confirm",this.onSelectionConfirm.bind(this))}show(t){this.callback=t,this.elem.components.popup.show()}hide(){this.elem.components.popup.hide()}onSelectButtonClick(){this.hide(),this.selection!==null&&this.callback&&this.callback(this.selection)}onSelectionConfirm(t){this.hide(),this.callback&&t&&this.callback(t)}onSelectionChange(t){this.selection=t,t===null?this.selectButton.setAttribute("disabled","true"):this.selectButton.removeAttribute("disabled")}},qh=Bh;var jh=class{setup(){this.container=this.$el,this.name=this.$opts.name,Rt(this.$el,()=>{this.$emit(this.name,this.$opts)})}},$h=jh;var Uh=class{constructor(t){this.elem=t,this.isOpen=t.getAttribute("expand-toggle-is-open")==="yes",this.updateEndpoint=t.getAttribute("expand-toggle-update-endpoint"),this.selector=t.getAttribute("expand-toggle"),t.addEventListener("click",this.click.bind(this))}open(t){yi(t,200)}close(t){vi(t,200)}click(t){t.preventDefault();let n=document.querySelectorAll(this.selector);for(let l of n)this.isOpen?this.close(l):this.open(l);this.isOpen=!this.isOpen,this.updateSystemAjax(this.isOpen)}updateSystemAjax(t){window.$http.patch(this.updateEndpoint,{expand:t?"true":"false"})}},Hh=Uh;var Wh=class{setup(){this.elem=this.$el,this.toggleButton=this.$refs.toggle,this.menu=this.$refs.menu,this.open=!1,this.toggleButton.addEventListener("click",this.onToggle.bind(this)),this.onWindowClick=this.onWindowClick.bind(this),this.onKeyDown=this.onKeyDown.bind(this)}onToggle(t){this.open=!this.open,this.menu.classList.toggle("show",this.open),this.toggleButton.setAttribute("aria-expanded",this.open?"true":"false"),this.open?(this.elem.addEventListener("keydown",this.onKeyDown),window.addEventListener("click",this.onWindowClick)):(this.elem.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("click",this.onWindowClick)),t.stopPropagation()}onKeyDown(t){t.code==="Escape"&&this.onToggle(t)}onWindowClick(t){this.onToggle(t)}},Gh=Wh;var Kh=class{constructor(t){this.elem=t,this.typeControl=t.querySelector('[name="setting-app-homepage-type"]'),this.pagePickerContainer=t.querySelector("[page-picker-container]"),this.typeControl.addEventListener("change",this.controlPagePickerVisibility.bind(this)),this.controlPagePickerVisibility()}controlPagePickerVisibility(){let t=this.typeControl.value==="page";this.pagePickerContainer.style.display=t?"block":"none"}},Vh=Kh;var Yh=class{setup(){this.uploadedTo=this.$opts.uploadedTo,this.container=this.$el,this.popupEl=this.$refs.popup,this.searchForm=this.$refs.searchForm,this.searchInput=this.$refs.searchInput,this.cancelSearch=this.$refs.cancelSearch,this.listContainer=this.$refs.listContainer,this.filterTabs=this.$manyRefs.filterTabs,this.selectButton=this.$refs.selectButton,this.formContainer=this.$refs.formContainer,this.dropzoneContainer=this.$refs.dropzoneContainer,this.type="gallery",this.lastSelected={},this.lastSelectedTime=0,this.callback=null,this.resetState=()=>{this.hasData=!1,this.page=1,this.filter="all"},this.resetState(),this.setupListeners(),window.ImageManager=this}setupListeners(){Rt(this.filterTabs,t=>{this.resetAll(),this.filter=t.target.dataset.filter,this.setActiveFilterTab(this.filter),this.loadGallery()}),this.searchForm.addEventListener("submit",t=>{this.resetListView(),this.loadGallery(),t.preventDefault()}),Rt(this.cancelSearch,t=>{this.resetListView(),this.resetSearchView(),this.loadGallery(),this.cancelSearch.classList.remove("active")}),this.searchInput.addEventListener("input",t=>{this.cancelSearch.classList.toggle("active",this.searchInput.value.trim())}),$t(this.listContainer,".load-more","click",async t=>{Ji(t.target),this.page++,await this.loadGallery(),t.target.remove()}),this.listContainer.addEventListener("event-emit-select-image",this.onImageSelectEvent.bind(this)),Rt(this.selectButton,()=>{this.callback&&this.callback(this.lastSelected),this.hide()}),$t(this.formContainer,"#image-manager-delete","click",t=>{this.lastSelected&&this.loadImageEditForm(this.lastSelected.id,!0)}),this.formContainer.addEventListener("ajax-form-success",this.refreshGallery.bind(this)),this.container.addEventListener("dropzone-success",this.refreshGallery.bind(this))}show(t,n="gallery"){this.resetAll(),this.callback=t,this.type=n,this.popupEl.components.popup.show(),this.dropzoneContainer.classList.toggle("hidden",n!=="gallery"),this.hasData||(this.loadGallery(),this.hasData=!0)}hide(){this.popupEl.components.popup.hide()}async loadGallery(){let t={page:this.page,search:this.searchInput.value||null,uploaded_to:this.uploadedTo,filter_type:this.filter==="all"?null:this.filter},{data:n}=await window.$http.get(`images/${this.type}`,t);this.addReturnedHtmlElementsToList(n),Uc(this.listContainer)}addReturnedHtmlElementsToList(t){let n=document.createElement("div");n.innerHTML=t,window.components.init(n);for(let l of[...n.children])this.listContainer.appendChild(l)}setActiveFilterTab(t){this.filterTabs.forEach(l=>l.classList.remove("selected"));let n=this.filterTabs.find(l=>l.dataset.filter===t);n&&n.classList.add("selected")}resetAll(){this.resetState(),this.resetListView(),this.resetSearchView(),this.resetEditForm(),this.setActiveFilterTab("all"),this.selectButton.classList.add("hidden")}resetSearchView(){this.searchInput.value=""}resetEditForm(){this.formContainer.innerHTML=""}resetListView(){Ji(this.listContainer),this.page=1}refreshGallery(){this.resetListView(),this.loadGallery()}onImageSelectEvent(t){let n=JSON.parse(t.detail.data),l=n&&n.id===this.lastSelected.id&&Date.now()-this.lastSelectedTime<400,c=t.target.classList.contains("selected");[...this.listContainer.querySelectorAll(".selected")].forEach(d=>{d.classList.remove("selected")}),c?this.resetEditForm():(t.target.classList.add("selected"),this.loadImageEditForm(n.id)),this.selectButton.classList.toggle("hidden",c),l&&this.callback&&(this.callback(n),this.hide()),this.lastSelected=n,this.lastSelectedTime=Date.now()}async loadImageEditForm(t,n=!1){n||(this.formContainer.innerHTML="");let l=n?{delete:!0}:{},{data:c}=await window.$http.get(`/images/edit/${t}`,l);this.formContainer.innerHTML=c,window.components.init(this.formContainer)}},Xh=Yh;var Zh=class{constructor(t){this.elem=t,this.imageElem=t.querySelector("img"),this.imageInput=t.querySelector("input[type=file]"),this.resetInput=t.querySelector("input[data-reset-input]"),this.removeInput=t.querySelector("input[data-remove-input]"),this.defaultImage=t.getAttribute("data-default-image"),t.querySelector('button[data-action="reset-image"]').addEventListener("click",this.reset.bind(this));let l=t.querySelector('button[data-action="remove-image"]');l&&l.addEventListener("click",this.removeImage.bind(this)),this.imageInput.addEventListener("change",this.fileInputChange.bind(this))}fileInputChange(){this.resetInput.setAttribute("disabled","disabled"),this.removeInput&&this.removeInput.setAttribute("disabled","disabled");for(let t of this.imageInput.files)this.imageElem.src=window.URL.createObjectURL(t);this.imageElem.classList.remove("none")}reset(){this.imageInput.value="",this.imageElem.src=this.defaultImage,this.resetInput.removeAttribute("disabled"),this.removeInput&&this.removeInput.setAttribute("disabled","disabled"),this.imageElem.classList.remove("none")}removeImage(){this.imageInput.value="",this.imageElem.classList.add("none"),this.removeInput.removeAttribute("disabled"),this.resetInput.setAttribute("disabled","disabled")}},Qh=Zh;var Jh=class{constructor(t){this.elem=t,this.menu=t.querySelector("ul"),this.sortInput=t.querySelector('[name="sort"]'),this.orderInput=t.querySelector('[name="order"]'),this.form=t.querySelector("form"),this.menu.addEventListener("click",n=>{n.target.closest("[data-sort-value]")!==null&&this.sortOptionClick(n)}),this.elem.addEventListener("click",n=>{n.target.closest("[data-sort-dir]")!==null&&this.sortDirectionClick(n)})}sortOptionClick(t){let n=t.target.closest("[data-sort-value]");this.sortInput.value=n.getAttribute("data-sort-value"),t.preventDefault(),this.form.submit()}sortDirectionClick(t){let l=this.orderInput.value==="asc"?"desc":"asc";this.orderInput.value=l,t.preventDefault(),this.form.submit()}},ep=Jh;var gv=St(av()),vv=St(fv());var dv=class{constructor(t){this.data=t}hasItems(){return Boolean(this.data)&&Boolean(this.data.types)&&this.data.types.length>0}containsTabularData(){let t=this.data.getData("text/rtf");return t&&t.includes("\\trowd")}getImages(){let t=this.data.types,n=this.data.files,l=[];for(let c of t)if(c.includes("image")){let d=this.data.getData(c);l.push(d.getAsFile())}for(let c of n)c.type.includes("image")&&l.push(c);return l}},yo=dv;var pn=null,Ol,Pl,Rl;function Ok(i,t,n){Pl=t,Rl=n,pn=document.createElement("iframe"),pn.setAttribute("frameborder","0"),window.addEventListener("message",hv),pn.setAttribute("src",i),pn.setAttribute("class","fullscreen"),pn.style.backgroundColor="#FFFFFF",document.body.appendChild(pn),Ol=new URL(i).origin}function Pk(){pv()}function hv(i){if(!i.data||i.data.length<1||i.origin!==Ol)return;let t=JSON.parse(i.data);t.event==="init"?Nk():t.event==="exit"?pv():t.event==="save"?zk(t):t.event==="export"&&Rk(t)}function Rk(i){Rl&&Rl(i.data)}function zk(i){mv({action:"export",format:"xmlpng",xml:i.xml,spin:"Updating drawing"})}function Nk(){!Pl||Pl().then(i=>{mv({action:"load",autosave:1,xml:i})})}function pv(){window.removeEventListener("message",hv),pn&&document.body.removeChild(pn)}function mv(i){pn.contentWindow.postMessage(JSON.stringify(i),Ol)}async function Bk(i,t){let n={image:i,uploaded_to:t};return(await window.$http.post(window.baseUrl("/images/drawio"),n)).data}async function qk(i){return`data:image/png;base64,${(await window.$http.get(window.baseUrl(`/images/drawio/base64/${i}`))).data.content}`}var Nr={show:Ok,close:Pk,upload:Bk,load:qk};var yv=class{setup(){this.elem=this.$el,this.pageId=this.$opts.pageId,this.textDirection=this.$opts.textDirection,this.imageUploadErrorText=this.$opts.imageUploadErrorText,this.serverUploadLimitText=this.$opts.serverUploadLimitText,this.markdown=new gv.default({html:!0}),this.markdown.use(vv.default,{label:!0}),this.display=this.elem.querySelector(".markdown-display"),this.displayStylesLoaded=!1,this.input=this.elem.querySelector("textarea"),this.cm=ur.markdownEditor(this.input),this.onMarkdownScroll=this.onMarkdownScroll.bind(this);let t=()=>{this.displayDoc=this.display.contentDocument,this.init()};this.display.contentDocument.readyState==="complete"?t():this.display.addEventListener("load",t.bind(this)),window.$events.emitPublic(this.elem,"editor-markdown::setup",{markdownIt:this.markdown,displayEl:this.display,codeMirrorInstance:this.cm})}init(){let t=0;this.displayDoc.addEventListener("click",c=>{let d=Date.now()-t<300,a=c.target.closest("a");if(a!==null){c.preventDefault(),window.open(a.getAttribute("href"));return}let h=c.target.closest("[drawio-diagram]");if(h!==null&&d){this.actionEditDrawing(h);return}t=Date.now()}),this.elem.addEventListener("click",c=>{let d=c.target.closest("button[data-action]");if(d===null)return;let a=d.getAttribute("data-action");if(a==="insertImage"&&this.actionInsertImage(),a==="insertLink"&&this.actionShowLinkSelector(),a==="insertDrawing"&&(c.ctrlKey||c.metaKey)){this.actionShowImageManager();return}a==="insertDrawing"&&this.actionStartDrawing(),a==="fullscreen"&&this.actionFullScreen()}),this.elem.addEventListener("click",c=>{let d=c.target.closest(".editor-toolbar-label");if(!d)return;let a=this.elem.querySelectorAll(".markdown-editor-wrap");for(let h of a)h.classList.remove("active");d.closest(".markdown-editor-wrap").classList.add("active")}),window.$events.listen("editor-markdown-update",c=>{this.cm.setValue(c),this.updateAndRender()}),this.codeMirrorSetup(),this.listenForBookStackEditorEvents();let l=new URL(window.location).searchParams.get("content-text");l&&this.scrollToText(l)}updateAndRender(){let t=this.cm.getValue();this.input.value=t;let n=this.markdown.render(t);window.$events.emit("editor-html-change",n),window.$events.emit("editor-markdown-change",t),this.displayDoc.body.className="page-content",this.displayDoc.body.innerHTML=n,this.loadStylesIntoDisplay()}loadStylesIntoDisplay(){if(this.displayStylesLoaded)return;this.displayDoc.documentElement.classList.add("markdown-editor-display"),document.documentElement.classList.contains("dark-mode")&&(this.displayDoc.documentElement.style.backgroundColor="#222",this.displayDoc.documentElement.classList.add("dark-mode")),this.displayDoc.head.innerHTML="";let t=document.head.querySelectorAll("style,link[rel=stylesheet]");for(let n of t){let l=n.cloneNode(!0);this.displayDoc.head.appendChild(l)}this.displayStylesLoaded=!0}onMarkdownScroll(t){let n=this.displayDoc.body.children;if(n.length<=t)return;(t===-1?n[n.length-1]:n[t]).scrollIntoView({block:"start",inline:"nearest",behavior:"smooth"})}codeMirrorSetup(){let t=this.cm,n=this;t.setOption("direction","ltr");let l=ur.getMetaKey(),c={};c[`${l}-Alt-I`]=function(v){let k=`![${v.getSelection()}](http://)`,_=v.getCursor("from");v.replaceSelection(k),v.setCursor(_.line,_.ch+k.length-1)},c[`${l}-S`]=v=>{window.$events.emit("editor-save-draft")},c[`${l}-Enter`]=v=>{window.$events.emit("editor-save-page")},c[`Shift-${l}-K`]=v=>{this.actionShowLinkSelector()},c[`${l}-K`]=v=>{g()},c[`${l}-1`]=v=>{h("##")},c[`${l}-2`]=v=>{h("###")},c[`${l}-3`]=v=>{h("####")},c[`${l}-4`]=v=>{h("#####")},c[`${l}-5`]=v=>{h("")},c[`${l}-d`]=v=>{h("")},c[`${l}-6`]=v=>{h(">")},c[`${l}-q`]=v=>{h(">")},c[`${l}-7`]=v=>{p("\n```\n","\n```")},c[`${l}-8`]=v=>{p("`","`")},c[`Shift-${l}-E`]=v=>{p("`","`")},c[`${l}-9`]=v=>{p('',"
")},t.setOption("extraKeys",c),t.on("change",(v,b)=>{this.updateAndRender()});let d=Jo(v=>{let b=v.getScrollInfo();if(b.top+b.clientHeight===b.height){this.onMarkdownScroll(-1);return}let _=v.lineAtHeight(b.top,"local"),w=v.getRange({line:0,ch:null},{line:_,ch:null}),R=new DOMParser().parseFromString(this.markdown.render(w),"text/html").documentElement.querySelectorAll("body > *");this.onMarkdownScroll(R.length)},100);t.on("scroll",v=>{d(v)}),t.on("paste",(v,b)=>{let k=new yo(b.clipboardData||b.dataTransfer);if(!k.hasItems()||k.containsTabularData())return;let _=k.getImages();for(let w of _)y(w)}),t.on("drop",(v,b)=>{let k=b.dataTransfer.getData("bookstack/template");if(k){let w=v.coordsChar({left:b.pageX,top:b.pageY});v.setCursor(w),b.preventDefault(),window.$http.get(`/templates/${k}`).then(I=>{let S=I.data.markdown||I.data.html;v.replaceSelection(S)})}let _=new yo(b.dataTransfer);if(_.hasItems()&&_.getImages().length>0){let w=v.coordsChar({left:b.pageX,top:b.pageY});v.setCursor(w),b.stopPropagation(),b.preventDefault();let I=_.getImages();for(let S of I)y(S)}});function a(v,b){let k=t.getValue(),_=t.listSelections();t.setValue(k.replace(v,b)),t.setSelections(_)}function h(v){let b=t.getCursor(),k=t.getLine(b.line),_=k.length,w=k.split(" ")[0];if(w===v){k=k.replace(`${v} `,""),t.replaceRange(k,{line:b.line,ch:0},{line:b.line,ch:_}),t.setCursor({line:b.line,ch:b.ch-(v.length+1)});return}let I=/^[#>`]/.test(w),S=0;I?(S=v.length-w.length,k=k.replace(w,v).trim()):v!==""&&(S=v.length+1,k=v+" "+k),t.replaceRange(k,{line:b.line,ch:0},{line:b.line,ch:_}),t.setCursor({line:b.line,ch:b.ch+S})}function f(v,b){let k=t.getCursor(),_=t.getLine(k.line),w=_.length,I=_;_.indexOf(v)===0&&_.slice(-b.length)===b?I=_.slice(v.length,_.length-b.length):I=`${v}${_}${b}`,t.replaceRange(I,{line:k.line,ch:0},{line:k.line,ch:w}),t.setCursor({line:k.line,ch:k.ch+v.length})}function p(v,b){let k=t.getSelection();if(k==="")return f(v,b);let _=k,w=0,I=0;k.indexOf(v)===0&&k.slice(-b.length)===b?(_=k.slice(v.length,k.length-b.length),I=-(b.length+v.length)):(_=`${v}${k}${b}`,I=v.length+b.length);let S=t.listSelections()[0];t.replaceSelection(_);let R=S.head.ch<=S.anchor.ch;S.head.ch+=R?w:I,S.anchor.ch+=R?I:w,t.setSelections([S])}function y(v){if(v===null||v.type.indexOf("image")!==0)return;let b="png";if(v.name){let U=v.name.match(/\.(.+)$/);U.length>1&&(b=U[1])}let k="image-"+Math.random().toString(16).slice(2),_=window.baseUrl(`/loading.gif#upload${k}`),w=t.getSelection(),I=`![${w}](${_})`,S=t.getCursor();t.replaceSelection(I),t.setCursor({line:S.line,ch:S.ch+w.length+3});let R="image-"+Date.now()+"."+b,O=new FormData;O.append("file",v,R),O.append("uploaded_to",n.pageId),window.$http.post("/images/gallery",O).then(U=>{let $=`[![${w}](${U.data.thumbs.display})](${U.data.url})`;a(I,$)}).catch(U=>{window.$events.emit("error",n.imageUploadErrorText),a(I,w),console.log(U)})}function g(){let v=t.getCursor("from"),b=t.getSelection()||"",k=`[${b}]()`;t.focus(),t.replaceSelection(k);let _=b===""?-3:-1;t.setCursor(v.line,v.ch+k.length+_)}this.updateAndRender()}actionInsertImage(){let t=this.cm.getCursor("from");window.ImageManager.show(n=>{let l=this.cm.getSelection(),c="[!["+(l||n.name)+"]("+n.thumbs.display+")]("+n.url+")";this.cm.focus(),this.cm.replaceSelection(c),this.cm.setCursor(t.line,t.ch+c.length)},"gallery")}actionShowImageManager(){let t=this.cm.getCursor("from");window.ImageManager.show(n=>{this.insertDrawing(n,t)},"drawio")}actionShowLinkSelector(){let t=this.cm.getCursor("from");window.EntitySelectorPopup.show(n=>{let c=`[${this.cm.getSelection()||n.name}](${n.link})`;this.cm.focus(),this.cm.replaceSelection(c),this.cm.setCursor(t.line,t.ch+c.length)})}getDrawioUrl(){let t=document.querySelector("[drawio-url]");return t?t.getAttribute("drawio-url"):!1}actionStartDrawing(){let t=this.getDrawioUrl();if(!t)return;let n=this.cm.getCursor("from");Nr.show(t,()=>Promise.resolve(""),l=>{let c={image:l,uploaded_to:Number(this.pageId)};window.$http.post("/images/drawio",c).then(d=>{this.insertDrawing(d.data,n),Nr.close()}).catch(d=>{this.handleDrawingUploadError(d)})})}insertDrawing(t,n){let l=``;this.cm.focus(),this.cm.replaceSelection(l),this.cm.setCursor(n.line,n.ch+l.length)}actionEditDrawing(t){let n=this.getDrawioUrl();if(!n)return;let l=this.cm.getCursor("from"),c=t.getAttribute("drawio-diagram");Nr.show(n,()=>Nr.load(c),d=>{let a={image:d,uploaded_to:Number(this.pageId)};window.$http.post("/images/drawio",a).then(h=>{let f=``,p=this.cm.getValue().split(`
`).map(y=>y.indexOf(`drawio-diagram="${c}"`)!==-1?f:y).join(`
`);this.cm.setValue(p),this.cm.setCursor(l),this.cm.focus(),Nr.close()}).catch(h=>{this.handleDrawingUploadError(h)})})}handleDrawingUploadError(t){t.status===413?window.$events.emit("error",this.serverUploadLimitText):window.$events.emit("error",this.imageUploadErrorText),console.log(t)}actionFullScreen(){let t=this.elem.classList.contains("fullscreen");this.elem.classList.toggle("fullscreen",!t),document.body.classList.toggle("markdown-fullscreen",!t)}scrollToText(t){if(!t)return;let l=this.cm.getValue().split(/\r?\n/),c=l.findIndex(d=>d&&d.indexOf(t)!==-1);c!==-1&&(this.cm.scrollIntoView({line:c},200),this.cm.focus(),this.cm.setCursor({line:c,char:l[c].length}))}listenForBookStackEditorEvents(){function t({html:n,markdown:l}){return l||n}window.$events.listen("editor::replace",n=>{let l=t(n);this.cm.setValue(l)}),window.$events.listen("editor::append",n=>{let l=this.cm.getCursor("from"),c=t(n),d=this.cm.getValue()+`
`+c;this.cm.setValue(d),this.cm.setCursor(l.line,l.ch)}),window.$events.listen("editor::prepend",n=>{let l=this.cm.getCursor("from"),c=t(n),d=c+`
`+this.cm.getValue();this.cm.setValue(d);let a=c.split(`
`).length;this.cm.setCursor(l.line+a,l.ch)}),window.$events.listen("editor::insert",n=>{let l=t(n);this.cm.replaceSelection(l)}),window.$events.listen("editor::focus",()=>{this.cm.focus()})}},bv=yv;var xv=class{constructor(t){this.elem=t,this.inviteOption=t.querySelector("input[name=send_invite]"),this.inviteOption&&(this.inviteOption.addEventListener("change",this.inviteOptionChange.bind(this)),this.inviteOptionChange())}inviteOptionChange(){let t=this.inviteOption.value==="true",n=this.elem.querySelectorAll("input[type=password]");for(let c of n)c.disabled=t;let l=this.elem.querySelector("#password-input-container");l&&(l.style.display=t?"none":"block")}},wv=xv;var kv=class{constructor(t){this.elem=t,this.type=t.getAttribute("notification"),this.textElem=t.querySelector("span"),this.autohide=this.elem.hasAttribute("data-autohide"),this.elem.style.display="grid",window.$events.listen(this.type,n=>{this.show(n)}),t.addEventListener("click",this.hide.bind(this)),t.hasAttribute("data-show")&&setTimeout(()=>this.show(this.textElem.textContent),100),this.hideCleanup=this.hideCleanup.bind(this)}show(t=""){if(this.elem.removeEventListener("transitionend",this.hideCleanup),this.textElem.textContent=t,this.elem.style.display="grid",setTimeout(()=>{this.elem.classList.add("showing")},1),this.autohide){let n=t.split(" ").length,l=Math.max(2e3,1e3+250*n);setTimeout(this.hide.bind(this),l)}}hide(){this.elem.classList.remove("showing"),this.elem.addEventListener("transitionend",this.hideCleanup)}hideCleanup(){this.elem.style.display="none",this.elem.removeEventListener("transitionend",this.hideCleanup)}},_v=kv;var Sv=class{setup(){this.removeButton=this.$refs.remove,this.showButton=this.$refs.show,this.input=this.$refs.input,this.setupListeners()}setupListeners(){Rt(this.removeButton,()=>{this.input.value="",this.input.classList.add("hidden"),this.removeButton.classList.add("hidden"),this.showButton.classList.remove("hidden")}),Rt(this.showButton,()=>{this.input.classList.remove("hidden"),this.removeButton.classList.remove("hidden"),this.showButton.classList.add("hidden")})}},Ev=Sv;var Cv=class{setup(){this.elem=this.$el,this.pageId=Number(this.$opts.pageId),this.container=this.$refs.commentContainer,this.formContainer=this.$refs.formContainer,this.commentCountBar=this.$refs.commentCountBar,this.addButtonContainer=this.$refs.addButtonContainer,this.replyToRow=this.$refs.replyToRow,this.updatedText=this.$opts.updatedText,this.deletedText=this.$opts.deletedText,this.createdText=this.$opts.createdText,this.countText=this.$opts.countText,this.editingComment=null,this.parentId=null,this.formContainer&&(this.form=this.formContainer.querySelector("form"),this.formInput=this.form.querySelector("textarea"),this.form.addEventListener("submit",this.saveComment.bind(this))),this.elem.addEventListener("click",this.handleAction.bind(this)),this.elem.addEventListener("submit",this.updateComment.bind(this))}handleAction(t){let n=t.target.closest("[action]");if(t.target.matches('a[href^="#"]')){let d=t.target.href.split("#")[1];eo(document.querySelector("#"+d))}if(n===null)return;t.preventDefault();let l=n.getAttribute("action"),c=n.closest("[comment]");l==="edit"&&this.editComment(c),l==="closeUpdateForm"&&this.closeUpdateForm(),l==="delete"&&this.deleteComment(c),l==="addComment"&&this.showForm(),l==="hideForm"&&this.hideForm(),l==="reply"&&this.setReply(c),l==="remove-reply-to"&&this.removeReplyTo()}closeUpdateForm(){!this.editingComment||(this.editingComment.querySelector("[comment-content]").style.display="block",this.editingComment.querySelector("[comment-edit-container]").style.display="none")}editComment(t){this.hideForm(),this.editingComment&&this.closeUpdateForm(),t.querySelector("[comment-content]").style.display="none",t.querySelector("[comment-edit-container]").style.display="block";let n=t.querySelector("[comment-edit-container] textarea"),l=n.value.split(`
`).length;n.style.height=l*20+40+"px",this.editingComment=t}updateComment(t){let n=t.target;t.preventDefault();let c={text:n.querySelector("textarea").value,parent_id:this.parentId||null};this.showLoading(n);let d=this.editingComment.getAttribute("comment");window.$http.put(`/comment/${d}`,c).then(a=>{let h=document.createElement("div");h.innerHTML=a.data,this.editingComment.innerHTML=h.children[0].innerHTML,window.$events.success(this.updatedText),window.components.init(this.editingComment),this.closeUpdateForm(),this.editingComment=null}).catch(window.$events.showValidationErrors).then(()=>{this.hideLoading(n)})}deleteComment(t){let n=t.getAttribute("comment");this.showLoading(t.querySelector("[comment-content]")),window.$http.delete(`/comment/${n}`).then(l=>{t.parentNode.removeChild(t),window.$events.success(this.deletedText),this.updateCount(),this.hideForm()})}saveComment(t){t.preventDefault(),t.stopPropagation();let l={text:this.formInput.value,parent_id:this.parentId||null};this.showLoading(this.form),window.$http.post(`/comment/${this.pageId}`,l).then(c=>{let d=document.createElement("div");d.innerHTML=c.data;let a=d.children[0];this.container.appendChild(a),window.components.init(a),window.$events.success(this.createdText),this.resetForm(),this.updateCount()}).catch(c=>{window.$events.showValidationErrors(c),this.hideLoading(this.form)})}updateCount(){let t=this.container.children.length;this.elem.querySelector("[comments-title]").textContent=window.trans_plural(this.countText,t,{count:t})}resetForm(){this.formInput.value="",this.formContainer.appendChild(this.form),this.hideForm(),this.removeReplyTo(),this.hideLoading(this.form)}showForm(){this.formContainer.style.display="block",this.formContainer.parentNode.style.display="block",this.addButtonContainer.style.display="none",this.formInput.focus(),this.formInput.scrollIntoView({behavior:"smooth"})}hideForm(){this.formContainer.style.display="none",this.formContainer.parentNode.style.display="none",this.getCommentCount()>0?this.elem.appendChild(this.addButtonContainer):this.commentCountBar.appendChild(this.addButtonContainer),this.addButtonContainer.style.display="block"}getCommentCount(){return this.elem.querySelectorAll(".comment-box[comment]").length}setReply(t){this.showForm(),this.parentId=Number(t.getAttribute("local-id")),this.replyToRow.style.display="block";let n=this.replyToRow.querySelector("a");n.textContent=`#${this.parentId}`,n.href=`#comment${this.parentId}`}removeReplyTo(){this.parentId=null,this.replyToRow.style.display="none"}showLoading(t){let n=t.querySelectorAll(".form-group");for(let l of n)l.style.display="none";t.querySelector(".form-group.loading").style.display="block"}hideLoading(t){let n=t.querySelectorAll(".form-group");for(let l of n)l.style.display="block";t.querySelector(".form-group.loading").style.display="none"}},Tv=Cv;var Av=St(Qs());var Lv=class{constructor(t){if(this.elem=t,this.pageId=t.getAttribute("page-display"),ur.highlight(),this.setupPointer(),this.setupNavHighlighting(),this.setupDetailsCodeBlockRefresh(),window.location.hash){let l=window.location.hash.replace(/\%20/g," ").substr(1);this.goToText(l)}let n=document.querySelector(".sidebar-page-nav");n&&$t(n,"a","click",(l,c)=>{l.preventDefault(),window.components["tri-layout"][0].showContent();let d=c.getAttribute("href").substr(1);this.goToText(d),window.history.pushState(null,null,"#"+d)})}goToText(t){let n=document.getElementById(t);if(Xo(".page-content [data-highlighted]",l=>{l.removeAttribute("data-highlighted"),l.style.backgroundColor=null}),n!==null)eo(n);else{let l=$c(".page-content > div > *",t);l&&eo(l)}}setupPointer(){let t=document.getElementById("pointer");if(!t)return;t=t.parentNode.removeChild(t);let n=t.querySelector("div.pointer"),l=!1,c=!1,d=!0,a="";$t(t,"input","click",(f,p)=>{p.select(),f.stopPropagation()}),Zo(t,["click","focus"],f=>{f.stopPropagation()}),$t(t,"span.icon","click",(f,p)=>{f.stopPropagation(),d=!d,p.querySelector('[data-icon="include"]').style.display=d?"none":"inline",p.querySelector('[data-icon="link"]').style.display=d?"inline":"none",h()}),new Av.default(t.querySelector("button")),Zo(document.body,["click","focus"],f=>{!l||c||(t=t.parentElement.removeChild(t),l=!1)});let h=f=>{let p=d?window.baseUrl(`/link/${this.pageId}#${a}`):`{{@${this.pageId}#${a}}}`;d&&!p.startsWith("http")&&(p=window.location.protocol+"//"+window.location.host+p),t.querySelector("input").value=p;let y=t.querySelector("#pointer-edit");if(y&&f){let g=y.dataset.editHref,v=f.id,b=f.textContent&&f.textContent.substring(0,50);y.href=`${g}?content-id=${v}&content-text=${encodeURIComponent(b)}`}};Xo('.page-content [id^="bkmrk"]',f=>{Zo(f,["mouseup","keyup"],p=>{p.stopPropagation(),window.getSelection().toString().length!==0&&(a=f.id,h(f),f.parentNode.insertBefore(t,f),t.style.display="block",l=!0,c=!0,requestAnimationFrame(()=>{let g=f.getBoundingClientRect(),v=p.pageX-g.left-164;v<0&&(v=0);let b=v/g.width*100;n.style.left=b+"%",setTimeout(()=>{c=!1},100)}))})})}setupNavHighlighting(){if(!("IntersectionObserver"in window)||!("IntersectionObserverEntry"in window)||!("intersectionRatio"in window.IntersectionObserverEntry.prototype))return;let t=document.querySelector(".sidebar-page-nav"),n=document.querySelector(".page-content").querySelectorAll("h1, h2, h3, h4, h5, h6");n.length>0&&t!==null&&l(n);function l(a){let h={rootMargin:"0px 0px 0px 0px",threshold:1},f=new IntersectionObserver(c,h);for(let p of a)f.observe(p)}function c(a,h){for(let f of a){let p=f.intersectionRatio===1;d(f.target.id,p)}}function d(a,h){Xo('a[href="#'+a+'"]',f=>{f.closest("li").classList.toggle("current-heading",h)})}}setupDetailsCodeBlockRefresh(){let t=l=>{[...l.target.querySelectorAll(".CodeMirror")].forEach(d=>d.CodeMirror&&d.CodeMirror.refresh())};[...this.elem.querySelectorAll("details")].forEach(l=>l.addEventListener("toggle",t))}},Dv=Lv;function Iv(i){let t=new Date(i*1e3),n=t.getHours(),l=t.getMinutes();return`${(n>9?"":"0")+n}:${(l>9?"":"0")+l}`}var Fv=class{setup(){this.draftsEnabled=this.$opts.draftsEnabled==="true",this.editorType=this.$opts.editorType,this.pageId=Number(this.$opts.pageId),this.isNewDraft=this.$opts.pageNewDraft==="true",this.hasDefaultTitle=this.$opts.hasDefaultTitle||!1,this.container=this.$el,this.titleElem=this.$refs.titleContainer.querySelector("input"),this.saveDraftButton=this.$refs.saveDraft,this.discardDraftButton=this.$refs.discardDraft,this.discardDraftWrap=this.$refs.discardDraftWrap,this.draftDisplay=this.$refs.draftDisplay,this.draftDisplayIcon=this.$refs.draftDisplayIcon,this.changelogInput=this.$refs.changelogInput,this.changelogDisplay=this.$refs.changelogDisplay,this.draftText=this.$opts.draftText,this.autosaveFailText=this.$opts.autosaveFailText,this.editingPageText=this.$opts.editingPageText,this.draftDiscardedText=this.$opts.draftDiscardedText,this.setChangelogText=this.$opts.setChangelogText,this.editorHTML="",this.editorMarkdown="",this.autoSave={interval:null,frequency:3e4,last:0},this.pageId!==0&&this.draftsEnabled&&window.setTimeout(()=>{this.startAutoSave()},1e3),this.draftDisplay.innerHTML=this.draftText,this.setupListeners(),this.setInitialFocus()}setupListeners(){window.$events.listen("editor-save-draft",this.saveDraft.bind(this)),window.$events.listen("editor-save-page",this.savePage.bind(this)),window.$events.listen("editor-html-change",t=>{this.editorHTML=t}),window.$events.listen("editor-markdown-change",t=>{this.editorMarkdown=t}),this.changelogInput.addEventListener("change",this.updateChangelogDisplay.bind(this)),Rt(this.saveDraftButton,this.saveDraft.bind(this)),Rt(this.discardDraftButton,this.discardDraft.bind(this))}setInitialFocus(){if(this.hasDefaultTitle)return this.titleElem.select();window.setTimeout(()=>{window.$events.emit("editor::focus","")},500)}startAutoSave(){let t=this.titleElem.value.trim()+"::"+this.editorHTML;this.autoSaveInterval=window.setInterval(()=>{if(Date.now()-this.autoSave.last{this.draftDisplayIcon.classList.remove("visible")},2e3)}async discardDraft(){let t;try{t=await window.$http.get(`/ajax/page/${this.pageId}`)}catch(n){return console.error(n)}this.autoSave.interval&&window.clearInterval(this.autoSave.interval),this.draftDisplay.innerText=this.editingPageText,this.toggleDiscardDraftVisibility(!1),window.$events.emit("editor-html-update",t.data.html||""),window.$events.emit("editor-markdown-update",t.data.markdown||t.data.html),this.titleElem.value=t.data.name,window.setTimeout(()=>{this.startAutoSave()},1e3),window.$events.emit("success",this.draftDiscardedText)}updateChangelogDisplay(){let t=this.changelogInput.value.trim();t.length===0?t=this.setChangelogText:t.length>16&&(t=t.slice(0,16)+"..."),this.changelogDisplay.innerText=t}toggleDiscardDraftVisibility(t){this.discardDraftWrap.classList.toggle("hidden",!t)}},Mv=Fv;var Ov=class{constructor(t){this.elem=t,this.input=t.querySelector("input"),this.resetButton=t.querySelector("[page-picker-reset]"),this.selectButton=t.querySelector("[page-picker-select]"),this.display=t.querySelector("[page-picker-display]"),this.defaultDisplay=t.querySelector("[page-picker-default]"),this.buttonSep=t.querySelector("span.sep"),this.value=this.input.value,this.setupListeners()}setupListeners(){this.selectButton.addEventListener("click",this.showPopup.bind(this)),this.display.parentElement.addEventListener("click",this.showPopup.bind(this)),this.resetButton.addEventListener("click",t=>{this.setValue("","")})}showPopup(){window.EntitySelectorPopup.show(t=>{this.setValue(t.id,t.name)})}setValue(t,n){this.value=t,this.input.value=t,this.controlView(n)}controlView(t){let n=this.value&&this.value!==0;if(za(this.resetButton,n),za(this.buttonSep,n),za(this.defaultDisplay,!n),za(this.display,n),n){let l=this.getAssetIdFromVal();this.display.textContent=`#${l}, ${t}`,this.display.href=window.baseUrl(`/link/${l}`)}}getAssetIdFromVal(){return Number(this.value)}};function za(i,t){let n=i.tagName==="BUTTON"||i.tagName==="SPAN"?"inline-block":"block";i.style.display=t?n:"none"}var Pv=Ov;var Rv=class{constructor(t){this.container=t,t.querySelector("[permissions-table-toggle-all]").addEventListener("click",this.toggleAllClick.bind(this));let l=t.querySelectorAll("[permissions-table-toggle-all-in-row]");for(let d of l)d.addEventListener("click",this.toggleRowClick.bind(this));let c=t.querySelectorAll("[permissions-table-toggle-all-in-column]");for(let d of c)d.addEventListener("click",this.toggleColumnClick.bind(this))}toggleAllClick(t){t.preventDefault(),this.toggleAllInElement(this.container)}toggleRowClick(t){t.preventDefault(),this.toggleAllInElement(t.target.closest("tr"))}toggleColumnClick(t){t.preventDefault();let n=t.target.closest("th,td"),l=Array.from(n.parentElement.children).indexOf(n),c=n.closest("table").querySelectorAll("tr"),d=[];for(let a of c){let h=a.children[l];h&&d.push(...h.querySelectorAll("input[type=checkbox]"))}this.toggleAllInputs(d)}toggleAllInElement(t){let n=t.querySelectorAll("input[type=checkbox]");this.toggleAllInputs(n)}toggleAllInputs(t){let n=t.length>0?t[0].checked:!1;for(let l of t)l.checked=!n,l.dispatchEvent(new Event("change"))}},zv=Rv;var Nv=class{setup(){this.container=this.$el,this.hideButtons=this.$manyRefs.hide||[],this.onkeyup=null,this.onHide=null,this.setupListeners()}setupListeners(){let t=null;this.container.addEventListener("mousedown",n=>{t=n.target}),this.container.addEventListener("click",n=>{if(n.target===this.container&&t===this.container)return this.hide()}),Rt(this.hideButtons,n=>this.hide())}hide(t=null){ga(this.container,240,t),this.onkeyup&&(window.removeEventListener("keyup",this.onkeyup),this.onkeyup=null),this.onHide&&this.onHide()}show(t=null,n=null){Df(this.container,240,t),this.onkeyup=l=>{l.key==="Escape"&&this.hide()},window.addEventListener("keyup",this.onkeyup),this.onHide=n}},Bv=Nv;var qv=class{constructor(t){this.elem=t,this.colorInput=t.querySelector("input[type=color]"),this.lightColorInput=t.querySelector('input[name="setting-app-color-light"]'),this.resetButton=t.querySelector("[setting-app-color-picker-reset]"),this.defaultButton=t.querySelector("[setting-app-color-picker-default]"),this.colorInput.addEventListener("change",this.updateColor.bind(this)),this.colorInput.addEventListener("input",this.updateColor.bind(this)),this.resetButton.addEventListener("click",n=>{this.colorInput.value=this.colorInput.dataset.current,this.updateColor()}),this.defaultButton.addEventListener("click",n=>{this.colorInput.value=this.colorInput.dataset.default,this.updateColor()})}updateColor(){let t=this.colorInput.value,n=this.hexToRgb(t),l="rgba("+[n.r,n.g,n.b,"0.15"].join(",")+")";this.lightColorInput.value=l;let c=document.getElementById("custom-styles"),d=c.getAttribute("data-color"),a=c.getAttribute("data-color-light");c.innerHTML=c.innerHTML.split(d).join(t),c.innerHTML=c.innerHTML.split(a).join(l),c.setAttribute("data-color",t),c.setAttribute("data-color-light",l)}hexToRgb(t){let n=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return{r:n?parseInt(n[1],16):0,g:n?parseInt(n[2],16):0,b:n?parseInt(n[3],16):0}}},jv=qv;var $v=class{constructor(t){this.elem=t,this.colorInput=t.querySelector("input[type=color]"),this.resetButton=t.querySelector("[setting-color-picker-reset]"),this.defaultButton=t.querySelector("[setting-color-picker-default]"),this.resetButton.addEventListener("click",n=>{this.colorInput.value=this.colorInput.dataset.current}),this.defaultButton.addEventListener("click",n=>{this.colorInput.value=this.colorInput.dataset.default})}},Uv=$v;var Hv=class{constructor(t){this.elem=t,this.input=document.getElementById("books-input"),this.shelfBooksList=t.querySelector("[shelf-sort-assigned-books]"),this.initSortable(),this.setupListeners()}initSortable(){let t=this.elem.querySelectorAll(".scroll-box");for(let n of t)new gi(n,{group:"shelf-books",ghostClass:"primary-background-light",animation:150,onSort:this.onChange.bind(this)})}setupListeners(){this.elem.addEventListener("click",t=>{let n=t.target.closest(".scroll-box-item:not(.instruction)");n&&(t.preventDefault(),this.sortItemClick(n))})}sortItemClick(t){let n=this.elem.querySelectorAll(".scroll-box"),l=Array.from(n).filter(c=>t.parentElement!==c);l.length>0&&l[0].appendChild(t),this.onChange()}onChange(){let t=Array.from(this.shelfBooksList.querySelectorAll("[data-id]"));this.input.value=t.map(n=>n.getAttribute("data-id")).join(",")}},Wv=Hv;var Gv=class{constructor(t){this.elem=t,this.toggleElem=t.querySelector(".sidebar-toggle"),this.toggleElem.addEventListener("click",this.toggle.bind(this))}toggle(t=!0){this.elem.classList.toggle("open")}},Kv=Gv;var Vv=class{setup(){this.container=this.$el,this.handleSelector=this.$opts.handleSelector;let t=new gi(this.container,{handle:this.handleSelector,animation:150,onSort:()=>{this.$emit("sort",{ids:t.toArray()})},setData(n,l){let c=l.getAttribute("data-drag-content");if(c){let d=JSON.parse(c);for(let[a,h]of Object.entries(d))n.setData(a,h)}},revertOnSpill:!0,dropBubble:!0,dragoverBubble:!1})}},Yv=Vv;var Xv=class{setup(){this.$el.addEventListener("change",()=>{let t=this.$el.closest("form");t&&t.submit()})}},Zv=Xv;var Qv=class{setup(){this.tabContentsByName={},this.tabButtonsByName={},this.allContents=[],this.allButtons=[];for(let[t,n]of Object.entries(this.$manyRefs||{})){if(t.startsWith("toggle")){let l=t.replace("toggle","").toLowerCase();Rt(n,c=>this.show(l)),this.allButtons.push(...n),this.tabButtonsByName[l]=n}if(t.startsWith("content")){let l=t.replace("content","").toLowerCase();this.tabContentsByName[l]=n,this.allContents.push(...n)}}}show(t){this.allContents.forEach(c=>{c.classList.add("hidden"),c.classList.remove("selected")}),this.allButtons.forEach(c=>c.classList.remove("selected"));let n=this.tabContentsByName[t]||[],l=this.tabButtonsByName[t]||[];n.length>0&&(n.forEach(c=>{c.classList.remove("hidden"),c.classList.add("selected")}),l.forEach(c=>c.classList.add("selected")))}},Jv=Qv;var ey=class{setup(){this.addRemoveComponentEl=this.$refs.addRemove,this.container=this.$el,this.rowSelector=this.$opts.rowSelector,this.setupListeners()}setupListeners(){this.container.addEventListener("change",t=>{let n=this.addRemoveComponentEl.components["add-remove-rows"];this.hasEmptyRows()||n.add()})}hasEmptyRows(){return[...this.container.querySelectorAll(this.rowSelector)].find(l=>[...l.querySelectorAll("input")].filter(c=>c.value).length===0)!==void 0}},ty=ey;var ry=class{constructor(t){this.elem=t,this.list=t.querySelector("[template-manager-list]"),this.searching=!1,$t(this.elem,"[template-action]","click",this.handleTemplateActionClick.bind(this)),$t(this.elem,".pagination a","click",this.handlePaginationClick.bind(this)),$t(this.elem,".template-item-content","click",this.handleTemplateItemClick.bind(this)),$t(this.elem,".template-item","dragstart",this.handleTemplateItemDragStart.bind(this)),this.setupSearchBox()}handleTemplateItemClick(t,n){let l=n.closest("[template-id]").getAttribute("template-id");this.insertTemplate(l,"replace")}handleTemplateItemDragStart(t,n){let l=n.closest("[template-id]").getAttribute("template-id");t.dataTransfer.setData("bookstack/template",l),t.dataTransfer.setData("text/plain",l)}handleTemplateActionClick(t,n){t.stopPropagation();let l=n.getAttribute("template-action"),c=n.closest("[template-id]").getAttribute("template-id");this.insertTemplate(c,l)}async insertTemplate(t,n="replace"){let l=await window.$http.get(`/templates/${t}`),c="editor::"+n;window.$events.emit(c,l.data)}async handlePaginationClick(t,n){t.preventDefault();let l=n.getAttribute("href"),c=await window.$http.get(l);this.list.innerHTML=c.data}setupSearchBox(){let t=this.elem.querySelector(".search-box");if(!t)return;let n=t.querySelector("input"),l=t.querySelector("button"),c=t.querySelector("button.search-box-cancel");async function d(){let a=n.value,h=await window.$http.get("/templates",{search:a});c.style.display=a?"block":"none",this.list.innerHTML=h.data}d=d.bind(this),t.addEventListener("keypress",a=>{a.key==="Enter"&&(a.preventDefault(),d())}),l.addEventListener("click",a=>{d()}),c.addEventListener("click",a=>{n.value="",d()})}},ny=ry;var iy=class{constructor(t){this.elem=t,this.input=t.querySelector("input[type=hidden]"),this.checkbox=t.querySelector("input[type=checkbox]"),this.checkbox.addEventListener("change",this.stateChange.bind(this))}stateChange(){this.input.value=this.checkbox.checked?"true":"false";let t=new Event("change");this.input.dispatchEvent(t)}},oy=iy;var ay=class{setup(){this.container=this.$refs.container,this.tabs=this.$manyRefs.tab,this.lastLayoutType="none",this.onDestroy=null,this.scrollCache={content:0,info:0},this.lastTabShown="content",this.mobileTabClick=this.mobileTabClick.bind(this),this.updateLayout(),window.addEventListener("resize",t=>{this.updateLayout()},{passive:!0})}updateLayout(){let t="tablet";window.innerWidth<=1e3&&(t="mobile"),window.innerWidth>=1400&&(t="desktop"),t!==this.lastLayoutType&&(this.onDestroy&&(this.onDestroy(),this.onDestroy=null),t==="desktop"?this.setupDesktop():t==="mobile"&&this.setupMobile(),this.lastLayoutType=t)}setupMobile(){for(let t of this.tabs)t.addEventListener("click",this.mobileTabClick);this.onDestroy=()=>{for(let t of this.tabs)t.removeEventListener("click",this.mobileTabClick)}}setupDesktop(){}mobileTabClick(t){let n=t.target.dataset.tab;this.showTab(n)}showContent(){this.showTab("content",!1)}showTab(t,n=!0){this.scrollCache[this.lastTabShown]=document.documentElement.scrollTop;for(let c of this.tabs){let d=c.dataset.tab===t;c.setAttribute("aria-selected",d?"true":"false")}let l=t==="info";if(this.container.classList.toggle("show-info",l),n){let d=document.querySelector("header").getBoundingClientRect().bottom;document.documentElement.scrollTop=this.scrollCache[t]||d,setTimeout(()=>{document.documentElement.scrollTop=this.scrollCache[t]||d},50)}this.lastTabShown=t}},sy=ay;var ly=class{setup(){this.input=this.$refs.input,this.userInfoContainer=this.$refs.userInfo,this.hide=this.$el.components.dropdown.hide,$t(this.$el,"a.dropdown-search-item","click",this.selectUser.bind(this))}selectUser(t,n){t.preventDefault();let l=n.getAttribute("data-id");this.input.value=l,this.userInfoContainer.innerHTML=n.innerHTML,this.input.dispatchEvent(new Event("change",{bubbles:!0})),this.hide()}},uy=ly;function cy(i,t,n){let l=new yo(i.clipboardData||i.dataTransfer);if(!l.hasItems()||l.containsTabularData())return;let c=l.getImages();for(let d of c){let a="image-"+Math.random().toString(16).slice(2),h=window.baseUrl("/loading.gif");i.preventDefault(),setTimeout(()=>{t.insertContent(``),jk(d,n).then(f=>{let p=f.name.replace(/"/g,""),y=``,g=t.dom.create("a",{target:"_blank",href:f.url},y);t.dom.replace(g,a)}).catch(f=>{t.dom.remove(a),window.$events.emit("error",n.imageUploadErrorText),console.log(f)})},10)}}async function jk(i,t){if(i===null||i.type.indexOf("image")!==0)throw new Error("Not an image file");let n="png";if(i.name){let a=i.name.match(/\.(.+)$/);a.length>1&&(n=a[1])}let l="image-"+Date.now()+"."+n,c=new FormData;return c.append("file",i,l),c.append("uploaded_to",t.pageId),(await window.$http.post(window.baseUrl("/images/gallery"),c)).data}function $k(i){for(let t=1;t<5;t++)i.shortcuts.add("meta+"+t,"",["FormatBlock",!1,"h"+(t+1)]);i.shortcuts.add("meta+5","",["FormatBlock",!1,"p"]),i.shortcuts.add("meta+d","",["FormatBlock",!1,"p"]),i.shortcuts.add("meta+6","",["FormatBlock",!1,"blockquote"]),i.shortcuts.add("meta+q","",["FormatBlock",!1,"blockquote"]),i.shortcuts.add("meta+7","",["codeeditor",!1,"pre"]),i.shortcuts.add("meta+e","",["codeeditor",!1,"pre"]),i.shortcuts.add("meta+8","",["FormatBlock",!1,"code"]),i.shortcuts.add("meta+shift+E","",["FormatBlock",!1,"code"]),i.shortcuts.add("meta+S","",()=>{window.$events.emit("editor-save-draft")}),i.shortcuts.add("meta+13","",()=>{window.$events.emit("editor-save-page")}),i.shortcuts.add("meta+9","",function(){let t=i.selection.getNode(),n=t?t.closest(".callout"):null,l=["info","success","warning","danger"],d=(l.findIndex(h=>n&&n.classList.contains(h))+1)%l.length,a=l[d];i.formatter.apply("callout"+a)})}function Uk(i){window.$http.get(window.baseUrl("/custom-head-content")).then(t=>{if(!t.data)return;let n=i.getDoc().querySelector("head");n.innerHTML+=t.data})}function Hk(){function i(l){return l.className==="CodeMirrorContainer"}function t(l){let c=l.selection.getNode();if(!i(c)){let h=l.selection.getNode().textContent;window.components.first("code-editor").open(h,"",(f,p)=>{let y=document.createElement("div");y.innerHTML=`
`,y.querySelector("code").innerText=f,l.formatter.toggle("pre");let g=l.selection.getNode();l.dom.setHTML(g,y.querySelector("pre").innerHTML),l.fire("SetContent"),l.focus()});return}let d=c.hasAttribute("data-lang")?c.getAttribute("data-lang"):"",a=c.querySelector("textarea").textContent;window.components.first("code-editor").open(a,d,(h,f)=>{let y=c.querySelector(".CodeMirror").CodeMirror;y&&(ur.setContent(y,h),ur.setMode(y,f,h));let g=c.querySelector("textarea");g&&(g.textContent=h),c.setAttribute("data-lang",f),l.focus()})}function n(l){let d=l.querySelector("textarea").textContent,a=l.getAttribute("data-lang");l.removeAttribute("contentEditable");let h=document.createElement("pre"),f=document.createElement("code");f.classList.add(`language-${a}`),f.textContent=d,h.appendChild(f),l.parentElement.replaceChild(h,l)}window.tinymce.PluginManager.add("codeeditor",function(l,c){let d=l.$;l.addButton("codeeditor",{text:"Code block",icon:!1,cmd:"codeeditor"}),l.addCommand("codeeditor",()=>{t(l)}),l.on("PreProcess",function(h){d("div.CodeMirrorContainer",h.node).each((f,p)=>{n(p)})}),l.on("dblclick",h=>{let f=l.selection.getNode();!i(f)||t(l)});function a(){d(".CodeMirrorContainer").filter((f,p)=>typeof p.querySelector(".CodeMirror").CodeMirror=="undefined").each((f,p)=>{n(p)}),d("body > pre").filter((f,p)=>p.contentEditable!=="false").each((f,p)=>{ur.wysiwygView(p)})}l.on("init",function(){l.undoManager.transact(function(){a()}),setTimeout(()=>{l.on("SetContent",()=>{setTimeout(a,100)})},200)})})}function Wk(i,t,n,l){let c=null,d=null;function a(g){return g.hasAttribute("drawio-diagram")}function h(g,v=null){c=g,d=v,window.ImageManager.show(function(b){if(v){let k=v.querySelector("img");c.dom.setAttrib(k,"src",b.url),c.dom.setAttrib(v,"drawio-diagram",b.id)}else{let k=``;c.insertContent(k)}},"drawio")}function f(g,v=null){c=g,d=v,Nr.show(i,y,p)}async function p(g){let v="image-"+Math.random().toString(16).slice(2),b=window.baseUrl("/loading.gif"),k=_=>{_.status===413?window.$events.emit("error",l.serverUploadLimitText):window.$events.emit("error",l.imageUploadErrorText),console.log(_)};if(d){Nr.close();let _=d.querySelector("img");try{let w=await Nr.upload(g,n);c.dom.setAttrib(_,"src",w.url),c.dom.setAttrib(d,"drawio-diagram",w.id)}catch(w){k(w)}return}setTimeout(async()=>{c.insertContent(``),Nr.close();try{let _=await Nr.upload(g,n);c.dom.setAttrib(v,"src",_.url),c.dom.get(v).parentNode.setAttribute("drawio-diagram",_.id)}catch(_){c.dom.remove(v),k(_)}},5)}function y(){if(!d)return Promise.resolve("");let g=d.getAttribute("drawio-diagram");return Nr.load(g)}window.tinymce.PluginManager.add("drawio",function(g,v){g.addCommand("drawio",()=>{let b=g.selection.getNode();f(g,a(b)?b:null)}),g.addButton("drawio",{type:"splitbutton",tooltip:"Drawing",image:`data:image/svg+xml;base64,${btoa(``)}`,cmd:"drawio",menu:[{text:"Drawing Manager",onclick(){let b=g.selection.getNode();h(g,a(b)?b:null)}}]}),g.on("dblclick",b=>{let k=g.selection.getNode();!a(k)||f(g,k)}),g.on("SetContent",function(){let b=g.$("body > div[drawio-diagram]");!b.length||g.undoManager.transact(function(){b.each((k,_)=>{_.setAttribute("contenteditable","false")})})})})}function Gk(){window.tinymce.PluginManager.add("customhr",function(i){i.addCommand("InsertHorizontalRule",function(){let t=document.createElement("hr"),n=i.selection.getNode();n.parentNode.insertBefore(t,n)}),i.addButton("hr",{icon:"hr",tooltip:"Horizontal line",cmd:"InsertHorizontalRule"}),i.addMenuItem("hr",{icon:"hr",text:"Horizontal line",cmd:"InsertHorizontalRule",context:"insert"})})}function Kk(i){window.$events.listen("editor::replace",({html:t})=>{i.setContent(t)}),window.$events.listen("editor::append",({html:t})=>{let n=i.getContent()+t;i.setContent(n)}),window.$events.listen("editor::prepend",({html:t})=>{let n=t+i.getContent();i.setContent(n)}),window.$events.listen("editor::insert",({html:t})=>{i.insertContent(t)}),window.$events.listen("editor::focus",()=>{i.focus()})}var fy=class{setup(){this.elem=this.$el,this.pageId=this.$opts.pageId,this.textDirection=this.$opts.textDirection,this.imageUploadErrorText=this.$opts.imageUploadErrorText,this.serverUploadLimitText=this.$opts.serverUploadLimitText,this.isDarkMode=document.documentElement.classList.contains("dark-mode"),this.plugins="image imagetools table textcolor paste link autolink fullscreen code customhr autosave lists codeeditor media",this.loadPlugins(),this.tinyMceConfig=this.getTinyMceConfig(),window.$events.emitPublic(this.elem,"editor-tinymce::pre-init",{config:this.tinyMceConfig}),window.tinymce.init(this.tinyMceConfig)}loadPlugins(){Hk(),Gk();let t=document.querySelector("[drawio-url]");if(t){let n=t.getAttribute("drawio-url");Wk(n,this.isDarkMode,this.pageId,this),this.plugins+=" drawio"}this.textDirection==="rtl"&&(this.plugins+=" directionality")}getToolBar(){return`undo redo | styleselect | bold italic underline strikethrough superscript subscript | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | table image-insert link hr drawio media | removeformat code ${this.textDirection==="rtl"?"ltr rtl":""} fullscreen`}getTinyMceConfig(){let t=this;return{selector:"#html-editor",content_css:[window.baseUrl("/dist/styles.css")],branding:!1,skin:this.isDarkMode?"dark":"lightgray",body_class:"page-content",browser_spellcheck:!0,relative_urls:!1,directionality:this.textDirection,remove_script_host:!1,document_base_url:window.baseUrl("/"),end_container_on_empty_block:!0,statusbar:!1,menubar:!1,paste_data_images:!1,extended_valid_elements:"pre[*],svg[*],div[drawio-diagram]",automatic_uploads:!1,valid_children:"-div[p|h1|h2|h3|h4|h5|h6|blockquote],+div[pre],+div[img]",plugins:this.plugins,imagetools_toolbar:"imageoptions",toolbar:this.getToolBar(),content_style:`html, body, html.dark-mode {background: ${this.isDarkMode?"#222":"#fff"};} body {padding-left: 15px !important; padding-right: 15px !important; margin:0!important; margin-left:auto!important;margin-right:auto!important;}`,style_formats:[{title:"Header Large",format:"h2"},{title:"Header Medium",format:"h3"},{title:"Header Small",format:"h4"},{title:"Header Tiny",format:"h5"},{title:"Paragraph",format:"p",exact:!0,classes:""},{title:"Blockquote",format:"blockquote"},{title:"Code Block",icon:"code",cmd:"codeeditor",format:"codeeditor"},{title:"Inline Code",icon:"code",inline:"code"},{title:"Callouts",items:[{title:"Info",format:"calloutinfo"},{title:"Success",format:"calloutsuccess"},{title:"Warning",format:"calloutwarning"},{title:"Danger",format:"calloutdanger"}]}],style_formats_merge:!1,media_alt_source:!1,media_poster:!1,formats:{codeeditor:{selector:"p,h1,h2,h3,h4,h5,h6,td,th,div"},alignleft:{selector:"p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img",classes:"align-left"},aligncenter:{selector:"p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img",classes:"align-center"},alignright:{selector:"p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img",classes:"align-right"},calloutsuccess:{block:"p",exact:!0,attributes:{class:"callout success"}},calloutinfo:{block:"p",exact:!0,attributes:{class:"callout info"}},calloutwarning:{block:"p",exact:!0,attributes:{class:"callout warning"}},calloutdanger:{block:"p",exact:!0,attributes:{class:"callout danger"}}},file_browser_callback:function(n,l,c,d){c==="file"&&window.EntitySelectorPopup.show(function(a){let h=d.document.getElementById(n);h.value=a.link;let p=h.closest(".mce-form").querySelectorAll("input");p[1].value||(p[1].value=a.name),p[2].value=a.name}),c==="image"&&window.ImageManager.show(function(a){if(d.document.getElementById(n).value=a.url,"createEvent"in document){let f=document.createEvent("HTMLEvents");f.initEvent("change",!1,!0),d.document.getElementById(n).dispatchEvent(f)}else d.document.getElementById(n).fireEvent("onchange");let h=``;h+=``,h+="",d.tinyMCE.activeEditor.execCommand("mceInsertContent",!1,h)},"gallery")},paste_preprocess:function(n,l){l.content.indexOf('{l();let p=new URL(window.location).searchParams.get("content-id");p&&c(p);let g=n.getContainer().querySelectorAll(".mce-btn");for(let v of g)v.addEventListener("touchstart",b=>{b.stopPropagation()});window.editor=n});function l(){let f=n.getContent();t.isDarkMode&&n.contentDocument.documentElement.classList.add("dark-mode"),window.$events.emit("editor-html-change",f)}function c(f){let p=n.dom.get(encodeURIComponent(f).replace(/!/g,"%21"));!p||(p.scrollIntoView(),n.selection.select(p,!0),n.selection.collapse(!1),n.focus())}Kk(n),window.$events.listen("editor-html-update",f=>{n.setContent(f),n.selection.select(n.getBody(),!0),n.selection.collapse(!1),l(f)}),$k(n);let d,a;function h(f){return f&&!!(f.textContent||f.innerText)}n.on("dragstart",function(){let f=n.selection.getNode();f.nodeName==="IMG"&&(d=n.dom.getParent(f,".mceTemp"),!d&&f.parentNode.nodeName==="A"&&!h(f.parentNode)&&(d=f.parentNode)),f.hasAttribute("contenteditable")&&f.getAttribute("contenteditable")==="false"&&(a=f)}),n.on("drop",function(f){let p=n.dom,y=tinymce.dom.RangeUtils.getCaretRangeFromPoint(f.clientX,f.clientY,n.getDoc()),g=f.dataTransfer&&f.dataTransfer.getData("bookstack/template");g&&(f.preventDefault(),window.$http.get(`/templates/${g}`).then(v=>{n.selection.setRng(y),n.undoManager.transact(function(){n.execCommand("mceInsertContent",!1,v.data.html)})})),p.getParent(y.startContainer,".mceTemp")?f.preventDefault():d&&(f.preventDefault(),n.undoManager.transact(function(){n.selection.setRng(y),n.selection.setNode(d),p.remove(d)})),!f.isDefaultPrevented()&&a&&(f.preventDefault(),n.undoManager.transact(function(){let v=n.selection.getNode(),b=n.selection.getRng(),k=v.closest("body > *");b.startOffset>b.startContainer.length/2?n.$(k).after(a):n.$(k).before(a)})),f.isDefaultPrevented()||cy(f,n,t),d=null}),n.addButton("image-insert",{title:"My title",icon:"image",tooltip:"Insert an image",onclick:function(){window.ImageManager.show(function(f){let p=``;p+=``,p+="",n.execCommand("mceInsertContent",!1,p)},"gallery")}}),n.on("paste",f=>cy(f,n,t)),window.$events.emitPublic(t.elem,"editor-tinymce::setup",{editor:n})}}}},dy=fy;var hy={"add-remove-rows":Kc,"ajax-delete-row":Yc,"ajax-form":Zc,attachments:Jc,"attachments-list":tf,"auto-suggest":nf,"back-to-top":af,"book-sort":Lf,"chapter-toggle":Ff,"code-editor":ph,"code-highlighter":gh,collapsible:yh,"custom-checkbox":xh,"details-highlighter":kh,dropdown:Sh,"dropdown-search":Ch,dropzone:Dh,"editor-toolbox":Fh,"entity-permissions-editor":Oh,"entity-search":Rh,"entity-selector":Nh,"entity-selector-popup":qh,"event-emit-select":$h,"expand-toggle":Hh,"header-mobile-toggle":Gh,"homepage-control":Vh,"image-manager":Xh,"image-picker":Qh,index:Na,"list-sort-control":ep,"markdown-editor":bv,"new-user-password":wv,notification:_v,"optional-input":Ev,"page-comments":Tv,"page-display":Dv,"page-editor":Mv,"page-picker":Pv,"permissions-table":zv,popup:Bv,"setting-app-color-picker":jv,"setting-color-picker":Uv,"shelf-sort":Wv,sidebar:Kv,"sortable-list":Yv,"submit-on-change":Zv,tabs:Jv,"tag-manager":ty,"template-manager":ny,"toggle-switch":oy,"tri-layout":sy,"user-select":uy,"wysiwyg-editor":dy};window.components={};function Vk(i,t){let n=t.querySelectorAll(`[${i}]`);for(let l=0,c=n.length;l{a.from=l;let h=new CustomEvent(`${i}-${d}`,{bubbles:!0,detail:a});l.$el.dispatchEvent(h)},typeof l.setup=="function"&&l.setup()}catch(c){console.error("Failed to create component",c,i,t)}typeof window.components[i]=="undefined"&&(window.components[i]=[]),window.components[i].push(l),typeof t.components=="undefined"&&(t.components={}),t.components[i]=l}function Yk(i,t){let n={},l={},c=`${i}@`,d=`[refs*="${c}"]`,a=[...t.querySelectorAll(d)];t.matches(d)&&a.push(t);for(let h of a){let f=h.getAttribute("refs").split(" ").filter(p=>p.startsWith(c)).map(p=>p.replace(c,"")).map(my);for(let p of f)n[p]=h,typeof l[p]=="undefined"&&(l[p]=[]),l[p].push(h)}return{refs:n,manyRefs:l}}function Xk(i,t){let n={},l=`option:${i}:`;for(let{name:c,value:d}of t.attributes)if(c.startsWith(l)){let a=c.replace(l,"");n[my(a)]=d||""}return n}function my(i){let t=l=>l.slice(0,1).toUpperCase()+l.slice(1),n=i.split("-");return n[0]+n.slice(1).map(t).join("")}function gy(i){typeof i=="undefined"&&(i=document);for(let n of Object.keys(hy))Vk(n,i);let t=i.querySelectorAll("[component],[components]");for(let n of t){let l=`${n.getAttribute("component")||""} ${n.getAttribute("components")}`.toLowerCase().split(" ").filter(Boolean);for(let c of l)py(c,n)}}window.components.init=gy;window.components.first=i=>(window.components[i]||[null])[0];var Na=gy;window.baseUrl=function(i){let t=document.querySelector('meta[name="base-url"]').getAttribute("content");return t[t.length-1]==="/"&&(t=t.slice(0,t.length-1)),i[0]==="/"&&(i=i.slice(1)),t+"/"+i};window.$http=Bc;window.$events=zc;var Si=new jc;window.trans=Si.get.bind(Si);window.trans_choice=Si.getPlural.bind(Si);window.trans_plural=Si.parsePlural.bind(Si);Na();})();
/*!
* clipboard.js v2.0.8
* https://clipboardjs.com/
*
* Licensed MIT © Zeno Rocha
*/
/**!
* Sortable 1.13.0
* @author RubaXa
* @author owenm
* @license MIT
*/
//# sourceMappingURL=app.js.map