diff --git a/public/dist/app.js b/public/dist/app.js
index 07971db87..d2139ad7a 100644
--- a/public/dist/app.js
+++ b/public/dist/app.js
@@ -1,12 +1,12 @@
// See the "/licenses" URI for full package license details
-var Xn=Object.defineProperty;var yo=(i,t,e)=>t in i?Xn(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var fe=(i,t)=>{for(var e in t)Xn(i,e,{get:t[e],enumerable:!0})};var U=(i,t,e)=>(yo(i,typeof t!="symbol"?t+"":t,e),e),Co=(i,t,e)=>{if(!t.has(i))throw TypeError("Cannot "+e)};var Yi=(i,t,e)=>{if(t.has(i))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(i):t.set(i,e)};var jt=(i,t,e)=>(Co(i,t,"access private method"),e);var Qi={};fe(Qi,{emit:()=>Zi,emitPublic:()=>So,error:()=>Ji,listen:()=>xo,showResponseError:()=>$o,showValidationErrors:()=>Lo,success:()=>ko});var me={},Eo=[];function Zi(i,t){Eo.push({name:i,data:t});let e=me[i]||[];for(let n of e)n(t)}function xo(i,t){typeof me[i]>"u"&&(me[i]=[]),me[i].push(t)}function So(i,t,e){let n=new CustomEvent(t,{detail:e,bubbles:!0});i.dispatchEvent(n)}function ko(i){Zi("success",i)}function Ji(i){Zi("error",i)}function Lo(i){if(i.status&&i.status===422&&i.data){let t=Object.values(i.data).flat().join(`
-`);Ji(t)}}function $o(i){i.status&&i.status>=400&&i.data&&i.data.message&&Ji(i.data.message)}var tn={};fe(tn,{HttpError:()=>ge,createXMLHttpRequest:()=>Do,delete:()=>Po,get:()=>Ao,patch:()=>Bo,post:()=>Io,put:()=>Mo});async function To(i){if(i.status===204)return null;let e=(i.headers.get("Content-Type")||"").split(";")[0].split("/").pop();return e==="javascript"||e==="json"?i.json():i.text()}var ge=class extends Error{constructor(t,e){super(t.statusText),this.data=e,this.headers=t.headers,this.redirected=t.redirected,this.status=t.status,this.statusText=t.statusText,this.url=t.url,this.original=t}};function Do(i,t,e={}){let n=document.querySelector("meta[name=token]").getAttribute("content"),s=new XMLHttpRequest;for(let[o,r]of Object.entries(e))s.addEventListener(o,r.bind(s));return s.open(i,t),s.withCredentials=!0,s.setRequestHeader("X-CSRF-TOKEN",n),s}async function Gn(i,t={}){let e=i;if(e.startsWith("http")||(e=window.baseUrl(e)),t.params){let l=new URL(e);for(let c of Object.keys(t.params)){let h=t.params[c];typeof h<"u"&&h!==null&&l.searchParams.set(c,h)}e=l.toString()}let n=document.querySelector("meta[name=token]").getAttribute("content"),s={...t,credentials:"same-origin"};s.headers={...s.headers||{},baseURL:window.baseUrl(""),"X-CSRF-TOKEN":n};let o=await fetch(e,s),r=await To(o),a={data:r,headers:o.headers,redirected:o.redirected,status:o.status,statusText:o.statusText,url:o.url,original:o};if(!o.ok)throw new ge(o,r);return a}async function we(i,t,e=null){let n={method:i,body:e};return typeof e=="object"&&!(e instanceof FormData)&&(n.headers={"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},n.body=JSON.stringify(e)),e instanceof FormData&&i!=="post"&&(e.append("_method",i),n.method="post"),Gn(t,n)}async function Ao(i,t={}){return Gn(i,{method:"GET",params:t})}async function Io(i,t=null){return we("POST",i,t)}async function Mo(i,t=null){return we("PUT",i,t)}async function Bo(i,t=null){return we("PATCH",i,t)}async function Po(i,t=null){return we("DELETE",i,t)}var en=class{constructor(){this.store=new Map,this.parseTranslations()}parseTranslations(){let t=document.querySelectorAll('meta[name="translation"]');for(let e of t){let n=e.getAttribute("key"),s=e.getAttribute("value");this.store.set(n,s)}}get(t,e){let n=this.getTransText(t);return this.performReplacements(n,e)}getPlural(t,e,n){let s=this.getTransText(t);return this.parsePlural(s,e,n)}parsePlural(t,e,n){let s=t.split("|"),o=/^{([0-9]+)}/,r=/^\[([0-9]+),([0-9*]+)]/,a=null;for(let l of s){let c=l.match(o);if(c!==null&&Number(c[1])===e){a=l.replace(o,"").trim();break}let h=l.match(r);if(h!==null&&Number(h[1])<=e&&(h[2]==="*"||Number(h[2])>=e)){a=l.replace(r,"").trim();break}}return a===null&&s.length>1&&(a=e===1?s[0]:s[1]),a===null&&(a=s[0]),this.performReplacements(a,n)}getTransText(t){let e=this.store.get(t);return e===void 0&&console.warn(`Translation with key "${t}" does not exist`),e}performReplacements(t,e){if(!e)return t;let n=t.match(/:(\S+)/g);if(n===null)return t;let s=t;return n.forEach(o=>{let r=o.substring(1);typeof e[r]>"u"||(s=s.replace(o,e[r]))}),s}},Yn=en;var an={};fe(an,{first:()=>Fo,firstOnElement:()=>Ho,get:()=>Ro,init:()=>on,register:()=>rn});function nn(i){let t=n=>n.slice(0,1).toUpperCase()+n.slice(1),e=i.split("-");return e[0]+e.slice(1).map(t).join("")}function Zn(i){return i.replace(/[A-Z]/g,(t,e)=>(e>0?"-":"")+t.toLowerCase())}var Wt={},Jn={},sn=new WeakMap;function Oo(i,t){let e={},n={},s=`${i}@`,o=`[refs*="${s}"]`,r=[...t.querySelectorAll(o)];t.matches(o)&&r.push(t);for(let a of r){let l=a.getAttribute("refs").split(" ").filter(c=>c.startsWith(s)).map(c=>c.replace(s,"")).map(nn);for(let c of l)e[c]=a,typeof n[c]>"u"&&(n[c]=[]),n[c].push(a)}return{refs:e,manyRefs:n}}function _o(i,t){let e={},n=`option:${i}:`;for(let{name:s,value:o}of t.attributes)if(s.startsWith(n)){let r=s.replace(n,"");e[nn(r)]=o||""}return e}function No(i,t){let e=Jn[i];if(e===void 0)return;let n;try{n=new e,n.$name=i,n.$el=t;let o=Oo(i,t);n.$refs=o.refs,n.$manyRefs=o.manyRefs,n.$opts=_o(i,t),n.setup()}catch(o){console.error("Failed to create component",o,i,t)}typeof Wt[i]>"u"&&(Wt[i]=[]),Wt[i].push(n);let s=sn.get(t)||{};s[i]=n,sn.set(t,s)}function on(i=document){let t=i.querySelectorAll("[component],[components]");for(let e of t){let n=`${e.getAttribute("component")||""} ${e.getAttribute("components")}`.toLowerCase().split(" ").filter(Boolean);for(let s of n)No(s,e)}}function rn(i){let t=Object.keys(i);for(let e of t)Jn[Zn(e)]=i[e]}function Fo(i){return(Wt[i]||[null])[0]}function Ro(i){return Wt[i]||[]}function Ho(i,t){return(sn.get(i)||{})[t]||null}var Wn={};fe(Wn,{AddRemoveRows:()=>ve,AjaxDeleteRow:()=>ye,AjaxForm:()=>Ce,Attachments:()=>Ee,AttachmentsList:()=>xe,AutoSubmit:()=>ke,AutoSuggest:()=>Se,BackToTop:()=>Le,BookSort:()=>ze,ChapterContents:()=>We,CodeEditor:()=>Ke,CodeHighlighter:()=>Xe,CodeTextarea:()=>Ge,Collapsible:()=>Ye,ConfirmDialog:()=>Ze,CustomCheckbox:()=>Je,DetailsHighlighter:()=>Qe,Dropdown:()=>ti,DropdownSearch:()=>ei,Dropzone:()=>ii,EditorToolbox:()=>ni,EntityPermissions:()=>si,EntitySearch:()=>oi,EntitySelector:()=>ri,EntitySelectorPopup:()=>ai,EventEmitSelect:()=>li,ExpandToggle:()=>ci,GlobalSearch:()=>di,HeaderMobileToggle:()=>hi,ImageManager:()=>ui,ImagePicker:()=>pi,ListSortControl:()=>fi,MarkdownEditor:()=>mi,NewUserPassword:()=>gi,Notification:()=>wi,OptionalInput:()=>bi,PageComment:()=>Si,PageComments:()=>ki,PageDisplay:()=>Li,PageEditor:()=>$i,PagePicker:()=>Di,PermissionsTable:()=>Ai,Pointer:()=>Ii,Popup:()=>Mi,SettingAppColorScheme:()=>Bi,SettingColorPicker:()=>Pi,SettingHomepageControl:()=>Oi,ShelfSort:()=>_i,ShortcutInput:()=>Fi,Shortcuts:()=>Ni,SortableList:()=>Ri,SubmitOnChange:()=>Hi,Tabs:()=>qi,TagManager:()=>Ui,TemplateManager:()=>Vi,ToggleSwitch:()=>zi,TriLayout:()=>ji,UserSelect:()=>Wi,WebhookEvents:()=>Ki,WysiwygEditor:()=>Xi,WysiwygInput:()=>Gi});function it(i,t={},e=[]){let n=document.createElement(i);for(let[s,o]of Object.entries(t))o===null?n.removeAttribute(s):n.setAttribute(s,o);for(let s of e)typeof s=="string"?n.append(document.createTextNode(s)):n.append(s);return n}function ln(i,t){let e=document.querySelectorAll(i);for(let n of e)t(n)}function be(i,t,e){for(let n of t)i.addEventListener(n,e)}function x(i,t){Array.isArray(i)||(i=[i]);for(let e of i)e.addEventListener("click",t),e.addEventListener("keydown",n=>{(n.key==="Enter"||n.key===" ")&&(n.preventDefault(),t(n))})}function Qn(i,t,e){Array.isArray(t)||(t=[t]);let n=s=>{s.key===i&&e(s)};t.forEach(s=>s.addEventListener("keydown",n))}function Lt(i,t){Qn("Enter",i,t)}function ts(i,t){Qn("Escape",i,t)}function A(i,t,e,n){i.addEventListener(e,s=>{let o=s.target.closest(t);o&&n.call(o,s,o)})}function es(i,t){let e=document.querySelectorAll(i);t=t.toLowerCase();for(let n of e)if(n.textContent.toLowerCase().includes(t))return n;return null}function Kt(i){i.innerHTML='
'}function $t(){let i=document.createElement("div");return i.classList.add("loading-container"),i.innerHTML="",i}function Xt(i){let t=i.querySelectorAll(".loading-container");for(let e of t)e.remove()}function nt(i){let t=document.createElement("div");return t.innerHTML=i,window.$components.init(t),t.children[0]}function Tt(i,t,e){let n;return function(...o){let r=this,a=function(){n=null,e||i.apply(r,o)},l=e&&!n;clearTimeout(n),n=setTimeout(a,t),l&&i.apply(r,o)}}function dn(i){if(!i)return;let t=i;for(;t.parentElement;)t=t.parentElement,t.nodeName==="DETAILS"&&!t.open&&(t.open=!0);i.scrollIntoView({behavior:"smooth"});let e=getComputedStyle(document.body).getPropertyValue("--color-link");i.style.outline=`2px dashed ${e}`,i.style.outlineOffset="5px",i.style.transition=null,setTimeout(()=>{i.style.transition="outline linear 3s",i.style.outline="2px dashed rgba(0, 0, 0, 0)";let n=()=>{i.removeEventListener("transitionend",n),i.style.transition=null,i.style.outline=null,i.style.outlineOffset=null};i.addEventListener("transitionend",n)},1e3)}function is(i){return i.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function ns(){let i=()=>((1+Math.random())*65536|0).toString(16).substring(1);return`${i()+i()}-${i()}-${i()}-${i()}-${i()}${i()}${i()}`}function ss(i){return new Promise(t=>{setTimeout(t,i)})}var d=class{constructor(){U(this,"$name","");U(this,"$el",null);U(this,"$refs",{});U(this,"$manyRefs",{});U(this,"$opts",{})}setup(){}$emit(t,e={}){e.from=this;let n=this.$name,s=new CustomEvent(`${n}-${t}`,{bubbles:!0,detail:e});this.$el.dispatchEvent(s)}};var ve=class extends d{setup(){this.modelRow=this.$refs.model,this.addButton=this.$refs.add,this.removeSelector=this.$opts.removeSelector,this.rowSelector=this.$opts.rowSelector,this.setupListeners()}setupListeners(){this.addButton.addEventListener("click",this.add.bind(this)),A(this.$el,this.removeSelector,"click",t=>{t.target.closest(this.rowSelector).remove()})}add(){let t=this.modelRow.cloneNode(!0);t.classList.remove("hidden"),this.setClonedInputNames(t),this.modelRow.parentNode.insertBefore(t,this.modelRow),window.$components.init(t)}setClonedInputNames(t){let e=ns(),n=t.querySelectorAll('[name*="randrowid"]');for(let s of n)s.name=s.name.split("randrowid").join(e)}};var ye=class extends d{setup(){this.row=this.$el,this.url=this.$opts.url,this.deleteButtons=this.$manyRefs.delete,x(this.deleteButtons,this.runDelete.bind(this))}runDelete(){this.row.style.opacity="0.7",this.row.style.pointerEvents="none",window.$http.delete(this.url).then(t=>{typeof t.data=="object"&&t.data.message&&window.$events.emit("success",t.data.message),this.row.remove()}).catch(()=>{this.row.style.opacity=null,this.row.style.pointerEvents=null})}};var Ce=class extends d{setup(){this.container=this.$el,this.responseContainer=this.container,this.url=this.$opts.url,this.method=this.$opts.method||"post",this.successMessage=this.$opts.successMessage,this.submitButtons=this.$manyRefs.submit||[],this.$opts.responseContainer&&(this.responseContainer=this.container.closest(this.$opts.responseContainer)),this.setupListeners()}setupListeners(){if(this.container.tagName==="FORM"){this.container.addEventListener("submit",this.submitRealForm.bind(this));return}Lt(this.container,t=>{this.submitFakeForm(),t.preventDefault()}),this.submitButtons.forEach(t=>x(t,this.submitFakeForm.bind(this)))}submitFakeForm(){let t=new FormData,e=this.container.querySelectorAll("[name]");for(let n of e)t.append(n.getAttribute("name"),n.value);this.submit(t)}submitRealForm(t){t.preventDefault();let e=new FormData(this.container);this.submit(e)}async submit(t){this.responseContainer.style.opacity="0.7",this.responseContainer.style.pointerEvents="none";try{let e=await window.$http[this.method.toLowerCase()](this.url,t);this.$emit("success",{formData:t}),this.responseContainer.innerHTML=e.data,this.successMessage&&window.$events.emit("success",this.successMessage)}catch(e){this.responseContainer.innerHTML=e.data}window.$components.init(this.responseContainer),this.responseContainer.style.opacity=null,this.responseContainer.style.pointerEvents=null}};var Ee=class extends d{setup(){this.container=this.$el,this.pageId=this.$opts.pageId,this.editContainer=this.$refs.editContainer,this.listContainer=this.$refs.listContainer,this.linksContainer=this.$refs.linksContainer,this.listPanel=this.$refs.listPanel,this.attachLinkButton=this.$refs.attachLinkButton,this.setupListeners()}setupListeners(){let t=this.reloadList.bind(this);this.container.addEventListener("dropzone-upload-success",t),this.container.addEventListener("ajax-form-success",t),this.container.addEventListener("sortable-list-sort",e=>{this.updateOrder(e.detail.ids)}),this.container.addEventListener("event-emit-select-edit",e=>{this.startEdit(e.detail.id)}),this.container.addEventListener("event-emit-select-edit-back",()=>{this.stopEdit()}),this.container.addEventListener("event-emit-select-insert",e=>{let n=e.target.closest("[data-drag-content]").getAttribute("data-drag-content"),s=JSON.parse(n);window.$events.emit("editor::insert",{html:s["text/html"],markdown:s["text/plain"]})}),this.attachLinkButton.addEventListener("click",()=>{this.showSection("links")})}showSection(t){let e={links:this.linksContainer,edit:this.editContainer,list:this.listContainer};for(let[n,s]of Object.entries(e))s.toggleAttribute("hidden",n!==t)}reloadList(){this.stopEdit(),window.$http.get(`/attachments/get/page/${this.pageId}`).then(t=>{this.listPanel.innerHTML=t.data,window.$components.init(this.listPanel)})}updateOrder(t){window.$http.put(`/attachments/sort/page/${this.pageId}`,{order:t}).then(e=>{window.$events.emit("success",e.data.message)})}async startEdit(t){this.showSection("edit"),Kt(this.editContainer);let e=await window.$http.get(`/attachments/edit/${t}`);this.editContainer.innerHTML=e.data,window.$components.init(this.editContainer)}stopEdit(){this.showSection("list")}};var xe=class extends d{setup(){this.container=this.$el,this.fileLinks=this.$manyRefs.linkTypeFile,this.setupListeners()}setupListeners(){let t=e=>e.key==="Control"||e.key==="Meta";window.addEventListener("keydown",e=>{t(e)&&this.addOpenQueryToLinks()},{passive:!0}),window.addEventListener("keyup",e=>{t(e)&&this.removeOpenQueryFromLinks()},{passive:!0})}addOpenQueryToLinks(){for(let t of this.fileLinks)t.href.split("?")[1]!=="open=true"&&(t.href+="?open=true",t.setAttribute("target","_blank"))}removeOpenQueryFromLinks(){for(let t of this.fileLinks)t.href=t.href.split("?")[0],t.removeAttribute("target")}};var Gt,hn,Yt,un,ut=class{constructor(t,e=null,n=null){Yi(this,Gt);Yi(this,Yt);this.containers=[t],this.onEscape=e,this.onEnter=n,t.addEventListener("keydown",jt(this,Gt,hn).bind(this))}shareHandlingToEl(t){this.containers.push(t),t.addEventListener("keydown",jt(this,Gt,hn).bind(this))}focusNext(){let t=jt(this,Yt,un).call(this),n=t.indexOf(document.activeElement)+1;n>=t.length&&(n=0),t[n].focus()}focusPrevious(){let t=jt(this,Yt,un).call(this),n=t.indexOf(document.activeElement)-1;n<0&&(n=t.length-1),t[n].focus()}};Gt=new WeakSet,hn=function(t){t.target.matches("input")&&(t.key==="ArrowRight"||t.key==="ArrowLeft")||(t.key==="ArrowDown"||t.key==="ArrowRight"?(this.focusNext(),t.preventDefault()):t.key==="ArrowUp"||t.key==="ArrowLeft"?(this.focusPrevious(),t.preventDefault()):t.key==="Escape"?this.onEscape?this.onEscape(t):document.activeElement&&document.activeElement.blur():t.key==="Enter"&&this.onEnter&&this.onEnter(t))},Yt=new WeakSet,un=function(){let t=[],e='[tabindex]:not([tabindex="-1"]),[href],button:not([tabindex="-1"],[disabled]),input:not([type=hidden])';for(let n of this.containers)t.push(...n.querySelectorAll(e));return t};var pn={},Se=class extends d{setup(){this.parent=this.$el.parentElement,this.container=this.$el,this.type=this.$opts.type,this.url=this.$opts.url,this.input=this.$refs.input,this.list=this.$refs.list,this.lastPopulated=0,this.setupListeners()}setupListeners(){new ut(this.list,()=>{this.input.focus(),setTimeout(()=>this.hideSuggestions(),1)},e=>{e.preventDefault();let n=e.target.textContent;n&&this.selectSuggestion(n)}).shareHandlingToEl(this.input),A(this.list,".text-item","click",(e,n)=>{this.selectSuggestion(n.textContent)}),this.input.addEventListener("input",this.requestSuggestions.bind(this)),this.input.addEventListener("focus",this.requestSuggestions.bind(this)),this.input.addEventListener("blur",this.hideSuggestionsIfFocusedLost.bind(this)),this.input.addEventListener("keydown",e=>{e.key==="Tab"&&this.hideSuggestions()})}selectSuggestion(t){this.input.value=t,this.lastPopulated=Date.now(),this.input.focus(),this.input.dispatchEvent(new Event("input",{bubbles:!0})),this.input.dispatchEvent(new Event("change",{bubbles:!0})),this.hideSuggestions()}async requestSuggestions(){if(Date.now()-this.lastPopulated<50)return;let t=this.getNameFilterIfNeeded(),e=this.input.value.toLowerCase(),s=(await this.loadSuggestions(e,t)).filter(o=>e===""||o.toLowerCase().startsWith(e)).slice(0,10);this.displaySuggestions(s)}getNameFilterIfNeeded(){return this.type!=="value"?null:this.parent.querySelector("input").value}async loadSuggestions(t,e=null){t=t.slice(0,4);let n={search:t,name:e},s=`${this.url}:${JSON.stringify(n)}`;if(pn[s])return pn[s];let o=await window.$http.get(this.url,n);return pn[s]=o.data,o.data}displaySuggestions(t){if(t.length===0){this.hideSuggestions();return}this.list.innerHTML=t.map(e=>`
${is(e)}
`).join(""),this.list.style.display="block";for(let e of this.list.querySelectorAll(".text-item"))e.addEventListener("blur",this.hideSuggestionsIfFocusedLost.bind(this))}hideSuggestions(){this.list.style.display="none"}hideSuggestionsIfFocusedLost(t){this.container.contains(t.relatedTarget)||this.hideSuggestions()}};var ke=class extends d{setup(){this.form=this.$el,this.form.submit()}};var Le=class extends d{setup(){if(this.button=this.$el,this.targetElem=document.getElementById("header"),this.showing=!1,this.breakPoint=1200,document.body.classList.contains("flexbox")){this.button.style.display="none";return}this.button.addEventListener("click",this.scrollToTop.bind(this)),window.addEventListener("scroll",this.onPageScroll.bind(this))}onPageScroll(){let t=document.documentElement.scrollTop||document.body.scrollTop||0;!this.showing&&t>this.breakPoint?(this.button.style.display="block",this.showing=!0,setTimeout(()=>{this.button.style.opacity=.4},1)):this.showing&&t{this.button.style.display="none"},500))}scrollToTop(){let t=this.targetElem.getBoundingClientRect().top,e=document.documentElement.scrollTop?document.documentElement:document.body,n=300,s=Date.now(),o=this.targetElem.getBoundingClientRect().top;function r(){let a=1-(Date.now()-s)/n,l=Math.abs(a*o);a>0?(e.scrollTop=l,requestAnimationFrame(r.bind(this))):e.scrollTop=t}requestAnimationFrame(r.bind(this))}};function os(i,t){var e=Object.keys(i);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(i);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(i,s).enumerable})),e.push.apply(e,n)}return e}function ot(i){for(var t=1;t=0)&&(e[s]=i[s]);return e}function Vo(i,t){if(i==null)return{};var e=Uo(i,t),n,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(i);for(s=0;s=0)&&Object.prototype.propertyIsEnumerable.call(i,n)&&(e[n]=i[n])}return e}function zo(i){return jo(i)||Wo(i)||Ko(i)||Xo()}function jo(i){if(Array.isArray(i))return Sn(i)}function Wo(i){if(typeof Symbol<"u"&&i[Symbol.iterator]!=null||i["@@iterator"]!=null)return Array.from(i)}function Ko(i,t){if(i){if(typeof i=="string")return Sn(i,t);var e=Object.prototype.toString.call(i).slice(8,-1);if(e==="Object"&&i.constructor&&(e=i.constructor.name),e==="Map"||e==="Set")return Array.from(i);if(e==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e))return Sn(i,t)}}function Sn(i,t){(t==null||t>i.length)&&(t=i.length);for(var e=0,n=new Array(t);e"&&(t=t.substring(1)),i)try{if(i.matches)return i.matches(t);if(i.msMatchesSelector)return i.msMatchesSelector(t);if(i.webkitMatchesSelector)return i.webkitMatchesSelector(t)}catch{return!1}return!1}}function Yo(i){return i.host&&i!==document&&i.host.nodeType?i.host:i.parentNode}function Y(i,t,e,n){if(i){e=e||document;do{if(t!=null&&(t[0]===">"?i.parentNode===e&&Fe(i,t):Fe(i,t))||n&&i===e)return i;if(i===e)break}while(i=Yo(i))}return null}var as=/\s+/g;function P(i,t,e){if(i&&t)if(i.classList)i.classList[e?"add":"remove"](t);else{var n=(" "+i.className+" ").replace(as," ").replace(" "+t+" "," ");i.className=(n+(e?" "+t:"")).replace(as," ")}}function f(i,t,e){var n=i&&i.style;if(n){if(e===void 0)return document.defaultView&&document.defaultView.getComputedStyle?e=document.defaultView.getComputedStyle(i,""):i.currentStyle&&(e=i.currentStyle),t===void 0?e:e[t];!(t in n)&&t.indexOf("webkit")===-1&&(t="-webkit-"+t),n[t]=e+(typeof e=="string"?"":"px")}}function Ct(i,t){var e="";if(typeof i=="string")e=i;else do{var n=f(i,"transform");n&&n!=="none"&&(e=n+" "+e)}while(!t&&(i=i.parentNode));var s=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return s&&new s(e)}function vs(i,t,e){if(i){var n=i.getElementsByTagName(t),s=0,o=n.length;if(e)for(;s=o:r=s<=o,!r)return n;if(n===st())break;n=mt(n,!1)}return!1}function Pt(i,t,e,n){for(var s=0,o=0,r=i.children;o2&&arguments[2]!==void 0?arguments[2]:{},s=n.evt,o=Vo(n,nr);de.pluginEvent.bind(g)(t,e,ot({dragEl:p,parentEl:I,ghostEl:b,rootEl:T,nextEl:yt,lastDownEl:Pe,cloneEl:D,cloneHidden:ft,dragStarted:ee,putSortable:N,activeSortable:g.active,originalEvent:s,oldIndex:Bt,oldDraggableIndex:re,newIndex:X,newDraggableIndex:pt,hideGhostForTarget:Ls,unhideGhostForTarget:$s,cloneNowHidden:function(){ft=!0},cloneNowShown:function(){ft=!1},dispatchSortableEvent:function(a){H({sortable:e,name:a,originalEvent:s})}},o))};function H(i){te(ot({putSortable:N,cloneEl:D,targetEl:p,rootEl:T,oldIndex:Bt,oldDraggableIndex:re,newIndex:X,newDraggableIndex:pt},i))}var p,I,b,T,yt,Pe,D,ft,Bt,X,re,pt,$e,N,Mt=!1,Re=!1,He=[],bt,Z,wn,bn,hs,us,ee,At,ae,le=!1,Te=!1,Oe,F,vn=[],kn=!1,qe=[],Ve=typeof document<"u",De=gs,ps=ce||ct?"cssFloat":"float",sr=Ve&&!ws&&!gs&&"draggable"in document.createElement("div"),xs=function(){if(Ve){if(ct)return!1;var i=document.createElement("x");return i.style.cssText="pointer-events:auto",i.style.pointerEvents==="auto"}}(),Ss=function(t,e){var n=f(t),s=parseInt(n.width)-parseInt(n.paddingLeft)-parseInt(n.paddingRight)-parseInt(n.borderLeftWidth)-parseInt(n.borderRightWidth),o=Pt(t,0,e),r=Pt(t,1,e),a=o&&f(o),l=r&&f(r),c=a&&parseInt(a.marginLeft)+parseInt(a.marginRight)+$(o).width,h=l&&parseInt(l.marginLeft)+parseInt(l.marginRight)+$(r).width;if(n.display==="flex")return n.flexDirection==="column"||n.flexDirection==="column-reverse"?"vertical":"horizontal";if(n.display==="grid")return n.gridTemplateColumns.split(" ").length<=1?"vertical":"horizontal";if(o&&a.float&&a.float!=="none"){var u=a.float==="left"?"left":"right";return r&&(l.clear==="both"||l.clear===u)?"vertical":"horizontal"}return o&&(a.display==="block"||a.display==="flex"||a.display==="table"||a.display==="grid"||c>=s&&n[ps]==="none"||r&&n[ps]==="none"&&c+h>s)?"vertical":"horizontal"},or=function(t,e,n){var s=n?t.left:t.top,o=n?t.right:t.bottom,r=n?t.width:t.height,a=n?e.left:e.top,l=n?e.right:e.bottom,c=n?e.width:e.height;return s===a||o===l||s+r/2===a+c/2},rr=function(t,e){var n;return He.some(function(s){var o=s[R].options.emptyInsertThreshold;if(!(!o||Dn(s))){var r=$(s),a=t>=r.left-o&&t<=r.right+o,l=e>=r.top-o&&e<=r.bottom+o;if(a&&l)return n=s}}),n},ks=function(t){function e(o,r){return function(a,l,c,h){var u=a.options.group.name&&l.options.group.name&&a.options.group.name===l.options.group.name;if(o==null&&(r||u))return!0;if(o==null||o===!1)return!1;if(r&&o==="clone")return o;if(typeof o=="function")return e(o(a,l,c,h),r)(a,l,c,h);var m=(r?a:l).options.group.name;return o===!0||typeof o=="string"&&o===m||o.join&&o.indexOf(m)>-1}}var n={},s=t.group;(!s||Be(s)!="object")&&(s={name:s}),n.name=s.name,n.checkPull=e(s.pull,!0),n.checkPut=e(s.put),n.revertClone=s.revertClone,t.group=n},Ls=function(){!xs&&b&&f(b,"display","none")},$s=function(){!xs&&b&&f(b,"display","")};Ve&&!ws&&document.addEventListener("click",function(i){if(Re)return i.preventDefault(),i.stopPropagation&&i.stopPropagation(),i.stopImmediatePropagation&&i.stopImmediatePropagation(),Re=!1,!1},!0);var vt=function(t){if(p){t=t.touches?t.touches[0]:t;var e=rr(t.clientX,t.clientY);if(e){var n={};for(var s in t)t.hasOwnProperty(s)&&(n[s]=t[s]);n.target=n.rootEl=e,n.preventDefault=void 0,n.stopPropagation=void 0,e[R]._onDragOver(n)}}},ar=function(t){p&&p.parentNode[R]._isOutsideThisEl(t.target)};function g(i,t){if(!(i&&i.nodeType&&i.nodeType===1))throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(i));this.el=i,this.options=t=Q({},t),i[R]=this;var e={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(i.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return Ss(i,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(r,a){r.setData("Text",a.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:g.supportPointer!==!1&&"PointerEvent"in window&&!se,emptyInsertThreshold:5};de.initializePlugins(this,i,e);for(var n in e)!(n in t)&&(t[n]=e[n]);ks(t);for(var s in this)s.charAt(0)==="_"&&typeof this[s]=="function"&&(this[s]=this[s].bind(this));this.nativeDraggable=t.forceFallback?!1:sr,this.nativeDraggable&&(this.options.touchStartThreshold=1),t.supportPointer?E(i,"pointerdown",this._onTapStart):(E(i,"mousedown",this._onTapStart),E(i,"touchstart",this._onTapStart)),this.nativeDraggable&&(E(i,"dragover",this),E(i,"dragenter",this)),He.push(this.el),t.store&&t.store.get&&this.sort(t.store.get(this)||[]),Q(this,tr())}g.prototype={constructor:g,_isOutsideThisEl:function(t){!this.el.contains(t)&&t!==this.el&&(At=null)},_getDirection:function(t,e){return typeof this.options.direction=="function"?this.options.direction.call(this,t,e,p):this.options.direction},_onTapStart:function(t){if(t.cancelable){var e=this,n=this.el,s=this.options,o=s.preventOnFilter,r=t.type,a=t.touches&&t.touches[0]||t.pointerType&&t.pointerType==="touch"&&t,l=(a||t).target,c=t.target.shadowRoot&&(t.path&&t.path[0]||t.composedPath&&t.composedPath()[0])||l,h=s.filter;if(mr(n),!p&&!(/mousedown|pointerdown/.test(r)&&t.button!==0||s.disabled)&&!c.isContentEditable&&!(!this.nativeDraggable&&se&&l&&l.tagName.toUpperCase()==="SELECT")&&(l=Y(l,s.draggable,n,!1),!(l&&l.animated)&&Pe!==l)){if(Bt=O(l),re=O(l,s.draggable),typeof h=="function"){if(h.call(this,t,l,this)){H({sortable:e,rootEl:c,name:"filter",targetEl:l,toEl:n,fromEl:n}),V("filter",e,{evt:t}),o&&t.cancelable&&t.preventDefault();return}}else if(h&&(h=h.split(",").some(function(u){if(u=Y(c,u.trim(),n,!1),u)return H({sortable:e,rootEl:u,name:"filter",targetEl:l,fromEl:n,toEl:n}),V("filter",e,{evt:t}),!0}),h)){o&&t.cancelable&&t.preventDefault();return}s.handle&&!Y(c,s.handle,n,!1)||this._prepareDragStart(t,a,l)}}},_prepareDragStart:function(t,e,n){var s=this,o=s.el,r=s.options,a=o.ownerDocument,l;if(n&&!p&&n.parentNode===o){var c=$(n);if(T=o,p=n,I=p.parentNode,yt=p.nextSibling,Pe=n,$e=r.group,g.dragged=p,bt={target:p,clientX:(e||t).clientX,clientY:(e||t).clientY},hs=bt.clientX-c.left,us=bt.clientY-c.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,p.style["will-change"]="all",l=function(){if(V("delayEnded",s,{evt:t}),g.eventCanceled){s._onDrop();return}s._disableDelayedDragEvents(),!rs&&s.nativeDraggable&&(p.draggable=!0),s._triggerDragStart(t,e),H({sortable:s,name:"choose",originalEvent:t}),P(p,r.chosenClass,!0)},r.ignore.split(",").forEach(function(h){vs(p,h.trim(),yn)}),E(a,"dragover",vt),E(a,"mousemove",vt),E(a,"touchmove",vt),E(a,"mouseup",s._onDrop),E(a,"touchend",s._onDrop),E(a,"touchcancel",s._onDrop),rs&&this.nativeDraggable&&(this.options.touchStartThreshold=4,p.draggable=!0),V("delayStart",this,{evt:t}),r.delay&&(!r.delayOnTouchOnly||e)&&(!this.nativeDraggable||!(ce||ct))){if(g.eventCanceled){this._onDrop();return}E(a,"mouseup",s._disableDelayedDrag),E(a,"touchend",s._disableDelayedDrag),E(a,"touchcancel",s._disableDelayedDrag),E(a,"mousemove",s._delayedDragTouchMoveHandler),E(a,"touchmove",s._delayedDragTouchMoveHandler),r.supportPointer&&E(a,"pointermove",s._delayedDragTouchMoveHandler),s._dragStartTimer=setTimeout(l,r.delay)}else l()}},_delayedDragTouchMoveHandler:function(t){var e=t.touches?t.touches[0]:t;Math.max(Math.abs(e.clientX-this._lastX),Math.abs(e.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){p&&yn(p),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var t=this.el.ownerDocument;y(t,"mouseup",this._disableDelayedDrag),y(t,"touchend",this._disableDelayedDrag),y(t,"touchcancel",this._disableDelayedDrag),y(t,"mousemove",this._delayedDragTouchMoveHandler),y(t,"touchmove",this._delayedDragTouchMoveHandler),y(t,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(t,e){e=e||t.pointerType=="touch"&&t,!this.nativeDraggable||e?this.options.supportPointer?E(document,"pointermove",this._onTouchMove):e?E(document,"touchmove",this._onTouchMove):E(document,"mousemove",this._onTouchMove):(E(p,"dragend",this),E(T,"dragstart",this._onDragStart));try{document.selection?_e(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},_dragStarted:function(t,e){if(Mt=!1,T&&p){V("dragStarted",this,{evt:e}),this.nativeDraggable&&E(document,"dragover",ar);var n=this.options;!t&&P(p,n.dragClass,!1),P(p,n.ghostClass,!0),g.active=this,t&&this._appendGhost(),H({sortable:this,name:"start",originalEvent:e})}else this._nulling()},_emulateDragOver:function(){if(Z){this._lastX=Z.clientX,this._lastY=Z.clientY,Ls();for(var t=document.elementFromPoint(Z.clientX,Z.clientY),e=t;t&&t.shadowRoot&&(t=t.shadowRoot.elementFromPoint(Z.clientX,Z.clientY),t!==e);)e=t;if(p.parentNode[R]._isOutsideThisEl(t),e)do{if(e[R]){var n=void 0;if(n=e[R]._onDragOver({clientX:Z.clientX,clientY:Z.clientY,target:t,rootEl:e}),n&&!this.options.dragoverBubble)break}t=e}while(e=e.parentNode);$s()}},_onTouchMove:function(t){if(bt){var e=this.options,n=e.fallbackTolerance,s=e.fallbackOffset,o=t.touches?t.touches[0]:t,r=b&&Ct(b,!0),a=b&&r&&r.a,l=b&&r&&r.d,c=De&&F&&cs(F),h=(o.clientX-bt.clientX+s.x)/(a||1)+(c?c[0]-vn[0]:0)/(a||1),u=(o.clientY-bt.clientY+s.y)/(l||1)+(c?c[1]-vn[1]:0)/(l||1);if(!g.active&&!Mt){if(n&&Math.max(Math.abs(o.clientX-this._lastX),Math.abs(o.clientY-this._lastY))=0&&(H({rootEl:I,name:"add",toEl:I,fromEl:T,originalEvent:t}),H({sortable:this,name:"remove",toEl:I,originalEvent:t}),H({rootEl:I,name:"sort",toEl:I,fromEl:T,originalEvent:t}),H({sortable:this,name:"sort",toEl:I,originalEvent:t})),N&&N.save()):X!==Bt&&X>=0&&(H({sortable:this,name:"update",toEl:I,originalEvent:t}),H({sortable:this,name:"sort",toEl:I,originalEvent:t})),g.active&&((X==null||X===-1)&&(X=Bt,pt=re),H({sortable:this,name:"end",toEl:I,originalEvent:t}),this.save()))),this._nulling()},_nulling:function(){V("nulling",this),T=p=I=b=yt=D=Pe=ft=bt=Z=ee=X=pt=Bt=re=At=ae=N=$e=g.dragged=g.ghost=g.clone=g.active=null,qe.forEach(function(t){t.checked=!0}),qe.length=wn=bn=0},handleEvent:function(t){switch(t.type){case"drop":case"dragend":this._onDrop(t);break;case"dragenter":case"dragover":p&&(this._onDragOver(t),lr(t));break;case"selectstart":t.preventDefault();break}},toArray:function(){for(var t=[],e,n=this.el.children,s=0,o=n.length,r=this.options;ss.right+o||i.clientY>n.bottom&&i.clientX>n.left:i.clientY>s.bottom+o||i.clientX>n.right&&i.clientY>n.top}function ur(i,t,e,n,s,o,r,a){var l=n?i.clientY:i.clientX,c=n?e.height:e.width,h=n?e.top:e.left,u=n?e.bottom:e.right,m=!1;if(!r){if(a&&Oeh+c*o/2:lu-Oe)return-ae}else if(l>h+c*(1-s)/2&&lu-c*o/2)?l>h+c/2?1:-1:0}function pr(i){return O(p)1&&(w.forEach(function(a){o.addAnimationState({target:a,rect:z?$(a):r}),mn(a),a.fromRect=r,n.removeAnimationState(a)}),z=!1,wr(!this.options.removeCloneOnHide,s))},dragOverCompleted:function(e){var n=e.sortable,s=e.isOwner,o=e.insertion,r=e.activeSortable,a=e.parentEl,l=e.putSortable,c=this.options;if(o){if(s&&r._hideClone(),Jt=!1,c.animation&&w.length>1&&(z||!s&&!r.options.sort&&!l)){var h=$(L,!1,!0,!0);w.forEach(function(m){m!==L&&(ds(m,h),a.appendChild(m))}),z=!0}if(!s)if(z||Me(),w.length>1){var u=Ie;r._showClone(n),r.options.animation&&!Ie&&u&&K.forEach(function(m){r.addAnimationState({target:m,rect:Qt}),m.fromRect=Qt,m.thisAnimationDuration=null})}else r._showClone(n)}},dragOverAnimationCapture:function(e){var n=e.dragRect,s=e.isOwner,o=e.activeSortable;if(w.forEach(function(a){a.thisAnimationDuration=null}),o.options.animation&&!s&&o.multiDrag.isMultiDrag){Qt=Q({},n);var r=Ct(L,!0);Qt.top-=r.f,Qt.left-=r.e}},dragOverAnimationComplete:function(){z&&(z=!1,Me())},drop:function(e){var n=e.originalEvent,s=e.rootEl,o=e.parentEl,r=e.sortable,a=e.dispatchSortableEvent,l=e.oldIndex,c=e.putSortable,h=c||this.sortable;if(n){var u=this.options,m=o.children;if(!It)if(u.multiDragKey&&!this.multiDragKeyDown&&this._deselectMultiDrag(),P(L,u.selectedClass,!~w.indexOf(L)),~w.indexOf(L))w.splice(w.indexOf(L),1),Zt=null,te({sortable:r,rootEl:s,name:"deselect",targetEl:L,originalEvent:n});else{if(w.push(L),te({sortable:r,rootEl:s,name:"select",targetEl:L,originalEvent:n}),n.shiftKey&&Zt&&r.el.contains(Zt)){var C=O(Zt),v=O(L);if(~C&&~v&&C!==v){var S,M;for(v>C?(M=C,S=v):(M=v,S=C+1);M1){var G=$(L),_=O(L,":not(."+this.options.selectedClass+")");if(!Jt&&u.animation&&(L.thisAnimationDuration=null),h.captureAnimationState(),!Jt&&(u.animation&&(L.fromRect=G,w.forEach(function(k){if(k.thisAnimationDuration=null,k!==L){var tt=z?$(k):G;k.fromRect=tt,h.addAnimationState({target:k,rect:tt})}})),Me(),w.forEach(function(k){m[_]?o.insertBefore(k,m[_]):o.appendChild(k),_++}),l===O(L))){var q=!1;w.forEach(function(k){if(k.sortableIndex!==O(k)){q=!0;return}}),q&&(a("update"),a("sort"))}w.forEach(function(k){mn(k)}),h.animateAll()}J=h}(s===o||c&&c.lastPutMode!=="clone")&&K.forEach(function(k){k.parentNode&&k.parentNode.removeChild(k)})}},nullingGlobal:function(){this.isMultiDrag=It=!1,K.length=0},destroyGlobal:function(){this._deselectMultiDrag(),y(document,"pointerup",this._deselectMultiDrag),y(document,"mouseup",this._deselectMultiDrag),y(document,"touchend",this._deselectMultiDrag),y(document,"keydown",this._checkKeyDown),y(document,"keyup",this._checkKeyUp)},_deselectMultiDrag:function(e){if(!(typeof It<"u"&&It)&&J===this.sortable&&!(e&&Y(e.target,this.options.draggable,this.sortable.el,!1))&&!(e&&e.button!==0))for(;w.length;){var n=w[0];P(n,this.options.selectedClass,!1),w.shift(),te({sortable:this.sortable,rootEl:this.sortable.el,name:"deselect",targetEl:n,originalEvent:e})}},_checkKeyDown:function(e){e.key===this.options.multiDragKey&&(this.multiDragKeyDown=!0)},_checkKeyUp:function(e){e.key===this.options.multiDragKey&&(this.multiDragKeyDown=!1)}},Q(i,{pluginName:"multiDrag",utils:{select:function(e){var n=e.parentNode[R];!n||!n.options.multiDrag||~w.indexOf(e)||(J&&J!==n&&(J.multiDrag._deselectMultiDrag(),J=n),P(e,n.options.selectedClass,!0),w.push(e))},deselect:function(e){var n=e.parentNode[R],s=w.indexOf(e);!n||!n.options.multiDrag||!~s||(P(e,n.options.selectedClass,!1),w.splice(s,1))}},eventProperties:function(){var e=this,n=[],s=[];return w.forEach(function(o){n.push({multiDragElement:o,index:o.sortableIndex});var r;z&&o!==L?r=-1:z?r=O(o,":not(."+e.options.selectedClass+")"):r=O(o),s.push({multiDragElement:o,index:r})}),{items:zo(w),clones:[].concat(K),oldIndicies:n,newIndicies:s}},optionListeners:{multiDragKey:function(e){return e=e.toLowerCase(),e==="ctrl"?e="Control":e.length>1&&(e=e.charAt(0).toUpperCase()+e.substr(1)),e}}})}function wr(i,t){w.forEach(function(e,n){var s=t.children[e.sortableIndex+(i?Number(n):0)];s?t.insertBefore(e,s):t.appendChild(e)})}function ms(i,t){K.forEach(function(e,n){var s=t.children[e.sortableIndex+(i?Number(n):0)];s?t.insertBefore(e,s):t.appendChild(e)})}function Me(){w.forEach(function(i){i!==L&&i.parentNode&&i.parentNode.removeChild(i)})}g.mount(new gr);g.mount(Mn,In);var Et=g;var As={name(i,t){let e=i.getAttribute("data-name").trim().toLowerCase(),n=t.getAttribute("data-name").trim().toLowerCase();return e.localeCompare(n)},created(i,t){let e=Number(i.getAttribute("data-created"));return Number(t.getAttribute("data-created"))-e},updated(i,t){let e=Number(i.getAttribute("data-updated"));return Number(t.getAttribute("data-updated"))-e},chaptersFirst(i,t){let e=i.getAttribute("data-type"),n=t.getAttribute("data-type");return e===n?0:e==="chapter"?-1:1},chaptersLast(i,t){let e=i.getAttribute("data-type"),n=t.getAttribute("data-type");return e===n?0:e==="chapter"?1:-1}},Is={up:{active(i,t){return!(i.previousElementSibling===null&&!t)},run(i,t){(i.previousElementSibling||t).insertAdjacentElement("beforebegin",i)}},down:{active(i,t){return!(i.nextElementSibling===null&&!t)},run(i,t){(i.nextElementSibling||t).insertAdjacentElement("afterend",i)}},next_book:{active(i,t,e){return e.nextElementSibling!==null},run(i,t,e){e.nextElementSibling.querySelector("ul").prepend(i)}},prev_book:{active(i,t,e){return e.previousElementSibling!==null},run(i,t,e){e.previousElementSibling.querySelector("ul").appendChild(i)}},next_chapter:{active(i,t){return i.dataset.type==="page"&&this.getNextChapter(i,t)},run(i,t){this.getNextChapter(i,t).querySelector("ul").prepend(i)},getNextChapter(i,t){let e=t||i,n=Array.from(e.parentElement.children),s=n.indexOf(e);return n.slice(s+1).find(o=>o.dataset.type==="chapter")}},prev_chapter:{active(i,t){return i.dataset.type==="page"&&this.getPrevChapter(i,t)},run(i,t){this.getPrevChapter(i,t).querySelector("ul").append(i)},getPrevChapter(i,t){let e=t||i,n=Array.from(e.parentElement.children),s=n.indexOf(e);return n.slice(0,s).reverse().find(o=>o.dataset.type==="chapter")}},book_end:{active(i,t){return t||t===null&&i.nextElementSibling},run(i,t,e){e.querySelector("ul").append(i)}},book_start:{active(i,t){return t||t===null&&i.previousElementSibling},run(i,t,e){e.querySelector("ul").prepend(i)}},before_chapter:{active(i,t){return t},run(i,t){t.insertAdjacentElement("beforebegin",i)}},after_chapter:{active(i,t){return t},run(i,t){t.insertAdjacentElement("afterend",i)}}},ze=class extends d{setup(){this.container=this.$el,this.sortContainer=this.$refs.sortContainer,this.input=this.$refs.input,Et.mount(new Ds);let t=this.container.querySelector(".sort-box");this.setupBookSortable(t),this.setupSortPresets(),this.setupMoveActions(),window.$events.listen("entity-select-change",this.bookSelect.bind(this))}setupMoveActions(){this.container.addEventListener("click",t=>{if(t.target.matches("[data-move]")){let e=t.target.getAttribute("data-move"),n=t.target.closest("[data-id]");this.runSortAction(n,e)}}),this.updateMoveActionStateForAll()}setupSortPresets(){let t="",e=!1,n=["name","created","updated"];this.sortContainer.addEventListener("click",s=>{let o=s.target.closest(".sort-box-options [data-sort]");if(!o)return;s.preventDefault();let r=o.closest(".sort-box").querySelectorAll("ul"),a=o.getAttribute("data-sort");e=t===a?!e:!1;let l=As[a];e&&n.includes(a)&&(l=function(h,u){return 0-As[a](h,u)});for(let c of r)Array.from(c.children).filter(u=>u.matches("li")).sort(l).forEach(u=>{c.appendChild(u)});t=a,this.updateMapInput()})}bookSelect(t){if(this.container.querySelector(`[data-type="book"][data-id="${t.id}"]`)!==null)return;let n=`${t.link}/sort-item`;window.$http.get(n).then(s=>{let o=nt(s.data);this.sortContainer.append(o),this.setupBookSortable(o),this.updateMoveActionStateForAll(),o.querySelector("summary").focus()})}setupBookSortable(t){let e=Array.from(t.querySelectorAll(".sort-list, .sortable-page-sublist")),n={name:"book",pull:["book","chapter"],put:["book","chapter"]},s={name:"chapter",pull:["book","chapter"],put(o,r,a){return a.getAttribute("data-type")==="page"}};for(let o of e)Et.create(o,{group:o.classList.contains("sort-list")?n:s,animation:150,fallbackOnBody:!0,swapThreshold:.65,onSort:()=>{this.ensureNoNestedChapters(),this.updateMapInput(),this.updateMoveActionStateForAll()},dragClass:"bg-white",ghostClass:"primary-background-light",multiDrag:!0,multiDragKey:"Control",selectedClass:"sortable-selected"})}ensureNoNestedChapters(){let t=this.container.querySelectorAll('[data-type="chapter"] [data-type="chapter"]');for(let e of t)e.parentElement.closest('[data-type="chapter"]').insertAdjacentElement("afterend",e)}updateMapInput(){let t=this.buildEntityMap();this.input.value=JSON.stringify(t)}buildEntityMap(){let t=[],e=this.container.querySelectorAll(".sort-list");for(let n of e){let s=n.closest('[data-type="book"]').getAttribute("data-id"),o=Array.from(n.children).filter(r=>r.matches('[data-type="page"], [data-type="chapter"]'));for(let r=0;r{for(let r of s)i.style[r]=null;i.style.transition=null,i.removeEventListener("transitionend",o),je.delete(i),n&&n()};setTimeout(()=>{i.style.transition=`all ease-in-out ${e}ms`;for(let r of s)i.style[r]=t[r][1];i.addEventListener("transitionend",o),je.set(i,o)},15)}function ue(i){je.has(i)&&je.get(i)()}function Ms(i,t=400,e=null){ue(i),i.style.display="block",he(i,{opacity:["0","1"]},t,()=>{e&&e()})}function Bs(i,t=400,e=null){ue(i),he(i,{opacity:["1","0"]},t,()=>{i.style.display="none",e&&e()})}function Ot(i,t=400){ue(i);let e=i.getBoundingClientRect().height,n=getComputedStyle(i),s=n.getPropertyValue("padding-top"),o=n.getPropertyValue("padding-bottom"),r={maxHeight:[`${e}px`,"0px"],overflow:["hidden","hidden"],paddingTop:[s,"0px"],paddingBottom:[o,"0px"]};he(i,r,t,()=>{i.style.display="none"})}function _t(i,t=400){ue(i),i.style.display="block";let e=i.getBoundingClientRect().height,n=getComputedStyle(i),s=n.getPropertyValue("padding-top"),o=n.getPropertyValue("padding-bottom"),r={maxHeight:["0px",`${e}px`],overflow:["hidden","hidden"],paddingTop:["0px",s],paddingBottom:["0px",o]};he(i,r,t)}function Ps(i,t=400){let e=i.getBoundingClientRect().height,n=getComputedStyle(i),s=n.getPropertyValue("padding-top"),o=n.getPropertyValue("padding-bottom");return()=>{ue(i);let r=i.getBoundingClientRect().height,a=getComputedStyle(i),l=a.getPropertyValue("padding-top"),c=a.getPropertyValue("padding-bottom"),h={height:[`${e}px`,`${r}px`],overflow:["hidden","hidden"],paddingTop:[s,l],paddingBottom:[o,c]};he(i,h,t)}}var We=class extends d{setup(){this.list=this.$refs.list,this.toggle=this.$refs.toggle,this.isOpen=this.toggle.classList.contains("open"),this.toggle.addEventListener("click",this.click.bind(this))}open(){this.toggle.classList.add("open"),this.toggle.setAttribute("aria-expanded","true"),_t(this.list,180),this.isOpen=!0}close(){this.toggle.classList.remove("open"),this.toggle.setAttribute("aria-expanded","false"),Ot(this.list,180),this.isOpen=!1}click(t){t.preventDefault(),this.isOpen?this.close():this.open()}};var Ke=class extends d{constructor(){super(...arguments);U(this,"editor",null);U(this,"saveCallback",null);U(this,"cancelCallback",null);U(this,"history",{});U(this,"historyKey","code_history")}setup(){this.container=this.$refs.container,this.popup=this.$el,this.editorInput=this.$refs.editor,this.languageButtons=this.$manyRefs.languageButton,this.languageOptionsContainer=this.$refs.languageOptionsContainer,this.saveButton=this.$refs.saveButton,this.languageInput=this.$refs.languageInput,this.historyDropDown=this.$refs.historyDropDown,this.historyList=this.$refs.historyList,this.favourites=new Set(this.$opts.favourites.split(",")),this.setupListeners(),this.setupFavourites()}setupListeners(){this.container.addEventListener("keydown",e=>{e.ctrlKey&&e.key==="Enter"&&this.save()}),x(this.languageButtons,e=>{let n=e.target.dataset.lang;this.languageInput.value=n,this.languageInputChange(n)}),Lt(this.languageInput,()=>this.save()),this.languageInput.addEventListener("input",()=>this.languageInputChange(this.languageInput.value)),x(this.saveButton,()=>this.save()),A(this.historyList,"button","click",(e,n)=>{e.preventDefault();let s=n.dataset.time;this.editor&&this.editor.setContent(this.history[s])})}setupFavourites(){for(let e of this.languageButtons)this.setupFavouritesForButton(e);this.sortLanguageList()}setupFavouritesForButton(e){let n=e.dataset.lang,s=this.favourites.has(n);e.setAttribute("data-favourite",s?"true":"false"),A(e.parentElement,".lang-option-favorite-toggle","click",()=>{s=!s,s?this.favourites.add(n):this.favourites.delete(n),e.setAttribute("data-favourite",s?"true":"false"),window.$http.patch("/preferences/update-code-language-favourite",{language:n,active:s}),this.sortLanguageList(),s&&e.scrollIntoView({block:"center",behavior:"smooth"})})}sortLanguageList(){let e=this.languageButtons.sort((n,s)=>{let o=n.dataset.favourite==="true",r=s.dataset.favourite==="true";return o&&!r?-1:r&&!o||n.dataset.lang>s.dataset.lang?1:-1}).map(n=>n.parentElement);for(let n of e)this.languageOptionsContainer.append(n)}save(){this.saveCallback&&this.saveCallback(this.editor.getContent(),this.languageInput.value),this.hide()}async open(e,n,s,o,r){this.languageInput.value=n,this.saveCallback=o,this.cancelCallback=r,await this.show(),this.languageInputChange(n),this.editor.setContent(e),this.setDirection(s)}async show(){let e=await window.importVersioned("code");this.editor||(this.editor=e.popupEditor(this.editorInput,this.languageInput.value)),this.loadHistory(),this.getPopup().show(()=>{this.editor.focus()},()=>{this.addHistory(),this.cancelCallback&&this.cancelCallback()})}setDirection(e){let n=this.editorInput.parentElement;e?n.setAttribute("dir",e):n.removeAttribute("dir")}hide(){this.getPopup().hide(),this.addHistory()}getPopup(){return window.$components.firstOnElement(this.popup,"popup")}async updateEditorMode(e){this.editor.setMode(e,this.editor.getContent())}languageInputChange(e){this.updateEditorMode(e);let n=e.toLowerCase();for(let s of this.languageButtons){let o=s.dataset.lang.toLowerCase().trim(),r=n===o;s.classList.toggle("active",r),r&&s.scrollIntoView({block:"center",behavior:"smooth"})}}loadHistory(){this.history=JSON.parse(window.sessionStorage.getItem(this.historyKey)||"{}");let e=Object.keys(this.history).reverse();this.historyDropDown.classList.toggle("hidden",e.length===0),this.historyList.innerHTML=e.map(n=>{let s=new Date(parseInt(n,10)).toLocaleTimeString();return``}).join("")}addHistory(){if(!this.editor)return;let e=this.editor.getContent();if(!e)return;let n=Object.keys(this.history).pop();if(this.history[n]===e)return;this.history[String(Date.now())]=e;let s=JSON.stringify(this.history);window.sessionStorage.setItem(this.historyKey,s)}};var Xe=class extends d{setup(){let t=this.$el;t.querySelectorAll("pre").length>0&&window.importVersioned("code").then(n=>{n.highlightWithin(t)})}};var Ge=class extends d{async setup(){let{mode:t}=this.$opts;(await window.importVersioned("code")).inlineEditor(this.$el,t)}};var Ye=class extends d{setup(){this.container=this.$el,this.trigger=this.$refs.trigger,this.content=this.$refs.content,this.trigger&&(this.trigger.addEventListener("click",this.toggle.bind(this)),this.openIfContainsError())}open(){this.container.classList.add("open"),this.trigger.setAttribute("aria-expanded","true"),_t(this.content,300)}close(){this.container.classList.remove("open"),this.trigger.setAttribute("aria-expanded","false"),Ot(this.content,300)}toggle(){this.container.classList.contains("open")?this.close():this.open()}openIfContainsError(){this.content.querySelector(".text-neg.text-small")&&this.open()}};var Ze=class extends d{setup(){this.container=this.$el,this.confirmButton=this.$refs.confirm,this.res=null,x(this.confirmButton,()=>{this.sendResult(!0),this.getPopup().hide()})}show(){return this.getPopup().show(null,()=>{this.sendResult(!1)}),new Promise(t=>{this.res=t})}getPopup(){return window.$components.firstOnElement(this.container,"popup")}sendResult(t){this.res&&(this.res(t),this.res=null)}};var Je=class extends d{setup(){this.container=this.$el,this.checkbox=this.container.querySelector("input[type=checkbox]"),this.display=this.container.querySelector('[role="checkbox"]'),this.checkbox.addEventListener("change",this.stateChange.bind(this)),this.container.addEventListener("keydown",this.onKeyDown.bind(this))}onKeyDown(t){(t.key===" "||t.key==="Enter")&&(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)}};var Qe=class extends d{setup(){this.container=this.$el,this.dealtWith=!1,this.container.addEventListener("toggle",this.onToggle.bind(this))}onToggle(){this.dealtWith||(this.container.querySelector("pre")&&window.importVersioned("code").then(t=>{t.highlightWithin(this.container)}),this.dealtWith=!0)}};var ti=class extends d{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.hide=this.hide.bind(this),this.setupListeners()}show(t=null){this.hideAll(),this.menu.style.display="block",this.menu.classList.add("anim","menuIn"),this.toggle.setAttribute("aria-expanded","true");let e=this.menu.getBoundingClientRect(),n=0,s=this.toggle.getBoundingClientRect().height,o=e.bottom>window.innerHeight,r=this.container.getBoundingClientRect();if(this.moveMenu&&(this.body.appendChild(this.menu),this.menu.style.position="fixed",this.menu.style.width=`${e.width}px`,this.menu.style.left=`${e.left}px`,o?n=window.innerHeight-e.top-s/2:n=e.top),o){this.menu.style.top="initial",this.menu.style.bottom=`${n}px`;let c=window.innerHeight-40-(window.innerHeight-r.bottom);this.menu.style.maxHeight=`${Math.floor(c)}px`}else{this.menu.style.top=`${n}px`,this.menu.style.bottom="initial";let c=window.innerHeight-40-r.top;this.menu.style.maxHeight=`${Math.floor(c)}px`}this.menu.addEventListener("mouseleave",this.hide),window.addEventListener("click",c=>{this.menu.contains(c.target)||this.hide()});let a=this.menu.querySelector("input");a!==null&&a.focus(),this.showing=!0;let l=new Event("show");this.container.dispatchEvent(l),t&&t.stopPropagation()}hideAll(){for(let t of window.$components.get("dropdown"))t.hide()}hide(){this.menu.style.display="none",this.menu.classList.remove("anim","menuIn"),this.toggle.setAttribute("aria-expanded","false"),this.menu.style.top="",this.menu.style.bottom="",this.menu.style.maxHeight="",this.moveMenu&&(this.menu.style.position="",this.menu.style[this.direction]="",this.menu.style.width="",this.menu.style.left="",this.container.appendChild(this.menu)),this.showing=!1}setupListeners(){let t=new ut(this.container,e=>{this.hide(),this.toggle.focus(),this.bubbleEscapes||e.stopPropagation()},e=>{e.target.nodeName==="INPUT"&&(e.preventDefault(),e.stopPropagation()),this.hide()});this.moveMenu&&t.shareHandlingToEl(this.menu),this.container.addEventListener("click",e=>{Array.from(this.menu.querySelectorAll("a")).includes(e.target)&&this.hide()}),x(this.toggle,e=>{e.stopPropagation(),e.preventDefault(),this.show(e),e instanceof KeyboardEvent&&t.focusNext()})}};var ei=class extends d{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=Tt(this.runAjaxSearch,300,!1)}onShow(){this.loadList()}onSearch(){let t=this.searchInput.value.toLowerCase().trim();this.localSearchSelector?this.runLocalSearch(t):(this.toggleLoading(!0),this.listContainerElem.innerHTML="",this.runAjaxSearch(t))}runAjaxSearch(t){this.loadList(t)}runLocalSearch(t){let e=this.listContainerElem.querySelectorAll(this.localSearchSelector);for(let n of e){let s=!t||n.textContent.toLowerCase().includes(t);n.style.display=s?"flex":"none",n.classList.toggle("hidden",!s)}}async loadList(t=""){this.listContainerElem.innerHTML="",this.toggleLoading(!0);try{let e=await window.$http.get(this.getAjaxUrl(t)),n=Ps(this.listContainerElem,80);this.listContainerElem.innerHTML=e.data,n()}catch(e){console.error(e)}this.toggleLoading(!1),this.localSearchSelector&&this.onSearch()}getAjaxUrl(t=null){if(!t)return this.url;let e=this.url.includes("?")?"&":"?";return`${this.url}${e}search=${encodeURIComponent(t)}`}toggleLoading(t=!1){this.loadingElem.style.display=t?"block":"none"}};var Nt=class{constructor(t){this.data=t}hasItems(){return!!this.data&&!!this.data.types&&this.data.types.length>0}containsTabularData(){let t=this.data.getData("text/rtf");return t&&t.includes("\\trowd")}getImages(){let{types:t}=this.data,e=[];for(let s of t)if(s.includes("image")){let o=this.data.getData(s);e.push(o.getAsFile())}let n=this.getFiles().filter(s=>s.type.includes("image"));return e.push(...n),e}getFiles(){let{files:t}=this.data;return[...t]}};async function Bn(i){if(window.isSecureContext&&navigator.clipboard){await navigator.clipboard.writeText(i);return}let t=document.createElement("textarea");t.style="position: absolute; left: -1000px; top: -1000px;",t.value=i,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t)}var ii=class extends d{setup(){this.container=this.$el,this.statusArea=this.$refs.statusArea,this.dropTarget=this.$refs.dropTarget,this.selectButtons=this.$manyRefs.selectButton||[],this.isActive=!0,this.url=this.$opts.url,this.method=(this.$opts.method||"post").toUpperCase(),this.successMessage=this.$opts.successMessage,this.errorMessage=this.$opts.errorMessage,this.uploadLimitMb=Number(this.$opts.uploadLimit),this.uploadLimitMessage=this.$opts.uploadLimitMessage,this.zoneText=this.$opts.zoneText,this.fileAcceptTypes=this.$opts.fileAccept,this.allowMultiple=this.$opts.allowMultiple==="true",this.setupListeners()}toggleActive(t){this.isActive=t}setupListeners(){x(this.selectButtons,this.manualSelectHandler.bind(this)),this.setupDropTargetHandlers()}setupDropTargetHandlers(){let t=0,e=()=>{this.hideOverlay(),t=0};this.dropTarget.addEventListener("dragenter",n=>{n.preventDefault(),t+=1,t===1&&this.isActive&&this.showOverlay()}),this.dropTarget.addEventListener("dragover",n=>{n.preventDefault()}),this.dropTarget.addEventListener("dragend",e),this.dropTarget.addEventListener("dragleave",()=>{t-=1,t===0&&e()}),this.dropTarget.addEventListener("drop",n=>{if(n.preventDefault(),e(),!this.isActive)return;let o=new Nt(n.dataTransfer).getFiles();for(let r of o)this.createUploadFromFile(r)})}manualSelectHandler(){let t=it("input",{type:"file",style:"left: -400px; visibility: hidden; position: fixed;",accept:this.fileAcceptTypes,multiple:this.allowMultiple?"":null});this.container.append(t),t.click(),t.addEventListener("change",()=>{for(let e of t.files)this.createUploadFromFile(e);t.remove()})}showOverlay(){if(!this.dropTarget.querySelector(".dropzone-overlay")){let e=it("div",{class:"dropzone-overlay"},[this.zoneText]);this.dropTarget.append(e)}}hideOverlay(){let t=this.dropTarget.querySelector(".dropzone-overlay");t&&t.remove()}createUploadFromFile(t){let{dom:e,status:n,progress:s,dismiss:o}=this.createDomForFile(t);this.statusArea.append(e);let r=this,a={file:t,dom:e,updateProgress(l){s.textContent=`${l}%`,s.style.width=`${l}%`},markError(l){n.setAttribute("data-status","error"),n.textContent=l,Xt(e),this.updateProgress(100)},markSuccess(l){n.setAttribute("data-status","success"),n.textContent=l,Xt(e),setTimeout(o,2400),r.$emit("upload-success",{name:t.name})}};return t.size>this.uploadLimitMb*1e6?(a.markError(this.uploadLimitMessage),a):(this.startXhrForUpload(a),a)}startXhrForUpload(t){let e=new FormData;e.append("file",t.file,t.file.name),this.method!=="POST"&&e.append("_method",this.method);let n=this,s=window.$http.createXMLHttpRequest("POST",this.url,{error(){t.markError(n.errorMessage)},readystatechange(){if(this.readyState===XMLHttpRequest.DONE&&this.status===200)t.markSuccess(n.successMessage);else if(this.readyState===XMLHttpRequest.DONE&&this.status>=400){let o=this.responseText,r=o.startsWith("{")?JSON.parse(o):{message:o},a=r?.message||r?.error||o;t.markError(a)}}});s.upload.addEventListener("progress",o=>{let r=Math.min(Math.ceil(o.loaded/o.total*100),100);t.updateProgress(r)}),s.setRequestHeader("Accept","application/json"),s.send(e)}createDomForFile(t){let e=it("img",{src:"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M9.224 7.373a.924.924 0 0 0-.92.925l-.006 7.404c0 .509.412.925.921.925h5.557a.928.928 0 0 0 .926-.925v-5.553l-2.777-2.776Zm3.239 3.239V8.067l2.545 2.545z' style='fill:%23000;fill-opacity:.75'/%3E%3C/svg%3E"}),n=it("div",{class:"dropzone-file-item-status"},[]),s=it("div",{class:"dropzone-file-item-progress"}),o=it("div",{class:"dropzone-file-item-image-wrap"},[e]),r=it("div",{class:"dropzone-file-item"},[o,it("div",{class:"dropzone-file-item-text-wrap"},[it("div",{class:"dropzone-file-item-label"},[t.name]),$t(),n]),s]);t.type.startsWith("image/")&&(e.src=URL.createObjectURL(t));let a=()=>{r.classList.add("dismiss"),r.addEventListener("animationend",()=>{r.remove()})};return r.addEventListener("click",a),{dom:r,progress:s,status:n,dismiss:a}}};var ni=class extends d{setup(){this.container=this.$el,this.buttons=this.$manyRefs.tabButton,this.contentElements=this.$manyRefs.tabContent,this.toggleButton=this.$refs.toggle,this.editorWrapEl=this.container.closest(".page-editor"),this.setupListeners(),this.setActiveTab(this.contentElements[0].dataset.tabContent)}setupListeners(){this.toggleButton.addEventListener("click",()=>this.toggle()),this.container.addEventListener("click",t=>{let e=t.target.closest("button");if(this.buttons.includes(e)){let n=e.dataset.tab;this.setActiveTab(n,!0)}})}toggle(){this.container.classList.toggle("open");let t=this.container.classList.contains("open");this.toggleButton.setAttribute("aria-expanded",t?"true":"false"),this.editorWrapEl.classList.toggle("toolbox-open",t)}setActiveTab(t,e=!1){for(let n of this.buttons)n.classList.remove("active"),n.dataset.tab===t&&n.classList.add("active");for(let n of this.contentElements)n.style.display="none",n.dataset.tabContent===t&&(n.style.display="block");e&&!this.container.classList.contains("open")&&this.toggle()}};var si=class extends d{setup(){this.container=this.$el,this.entityType=this.$opts.entityType,this.everyoneInheritToggle=this.$refs.everyoneInherit,this.roleSelect=this.$refs.roleSelect,this.roleContainer=this.$refs.roleContainer,this.setupListeners()}setupListeners(){this.everyoneInheritToggle.addEventListener("change",t=>{let e=t.target.checked,n=document.querySelectorAll('input[name^="permissions[0]["]');for(let s of n)s.disabled=e,s.checked=!1}),this.container.addEventListener("click",t=>{let e=t.target.closest("button");e&&e.dataset.roleId&&this.removeRowOnButtonClick(e)}),this.roleSelect.addEventListener("change",()=>{let t=this.roleSelect.value;t&&this.addRoleRow(t)})}async addRoleRow(t){this.roleSelect.disabled=!0;let e=this.roleSelect.querySelector(`option[value="${t}"]`);e&&e.remove();let n=await window.$http.get(`/permissions/form-row/${this.entityType}/${t}`),s=nt(n.data);this.roleContainer.append(s),this.roleSelect.disabled=!1}removeRowOnButtonClick(t){let e=t.closest(".item-list-row"),{roleId:n}=t.dataset,{roleName:s}=t.dataset,o=document.createElement("option");o.value=n,o.textContent=s,this.roleSelect.append(o),e.remove()}};var oi=class extends d{setup(){this.entityId=this.$opts.entityId,this.entityType=this.$opts.entityType,this.contentView=this.$refs.contentView,this.searchView=this.$refs.searchView,this.searchResults=this.$refs.searchResults,this.searchInput=this.$refs.searchInput,this.searchForm=this.$refs.searchForm,this.clearButton=this.$refs.clearButton,this.loadingBlock=this.$refs.loadingBlock,this.setupListeners()}setupListeners(){this.searchInput.addEventListener("change",this.runSearch.bind(this)),this.searchForm.addEventListener("submit",t=>{t.preventDefault(),this.runSearch()}),x(this.clearButton,this.clearSearch.bind(this))}runSearch(){let t=this.searchInput.value.trim();if(t.length===0){this.clearSearch();return}this.searchView.classList.remove("hidden"),this.contentView.classList.add("hidden"),this.loadingBlock.classList.remove("hidden");let e=window.baseUrl(`/search/${this.entityType}/${this.entityId}`);window.$http.get(e,{term:t}).then(n=>{this.searchResults.innerHTML=n.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=""}};var ri=class extends d{setup(){this.elem=this.$el,this.input=this.$refs.input,this.searchInput=this.$refs.search,this.loading=this.$refs.loading,this.resultsContainer=this.$refs.results,this.searchOptions={entityTypes:this.$opts.entityTypes||"page,book,chapter",entityPermission:this.$opts.entityPermission||"view",searchEndpoint:this.$opts.searchEndpoint||"",initialValue:this.searchInput.value||""},this.search="",this.lastClick=0,this.setupListeners(),this.showLoading(),this.searchOptions.searchEndpoint&&this.initialLoad()}configureSearchOptions(t){Object.assign(this.searchOptions,t),this.reset(),this.searchInput.value=this.searchOptions.initialValue}setupListeners(){this.elem.addEventListener("click",this.onClick.bind(this));let t=0;this.searchInput.addEventListener("input",()=>{t=Date.now(),this.showLoading(),setTimeout(()=>{Date.now()-t<199||this.searchEntities(this.searchInput.value)},200)}),this.searchInput.addEventListener("keydown",e=>{e.keyCode===13&&e.preventDefault()}),A(this.$el,"[data-entity-type]","keydown",e=>{if(e.ctrlKey&&e.code==="Enter"){let n=this.$el.closest("form");if(n){n.submit(),e.preventDefault();return}}e.code==="ArrowDown"&&this.focusAdjacent(!0),e.code==="ArrowUp"&&this.focusAdjacent(!1)}),this.searchInput.addEventListener("keydown",e=>{e.code==="ArrowDown"&&this.focusAdjacent(!0)})}focusAdjacent(t=!0){let e=Array.from(this.resultsContainer.querySelectorAll("[data-entity-type]")),n=e.indexOf(document.activeElement),s=e[n+(t?1:-1)]||e[0];s&&s.focus()}reset(){this.searchInput.value="",this.showLoading(),this.initialLoad()}focusSearch(){this.searchInput.focus()}showLoading(){this.loading.style.display="block",this.resultsContainer.style.display="none"}hideLoading(){this.loading.style.display="none",this.resultsContainer.style.display="block"}initialLoad(){if(!this.searchOptions.searchEndpoint)throw new Error("Search endpoint not set for entity-selector load");if(this.searchOptions.initialValue){this.searchEntities(this.searchOptions.initialValue);return}window.$http.get(this.searchUrl()).then(t=>{this.resultsContainer.innerHTML=t.data,this.hideLoading()})}searchUrl(){let t=`types=${encodeURIComponent(this.searchOptions.entityTypes)}&permission=${encodeURIComponent(this.searchOptions.entityPermission)}`;return`${this.searchOptions.searchEndpoint}?${t}`}searchEntities(t){if(!this.searchOptions.searchEndpoint)throw new Error("Search endpoint not set for entity-selector load");this.input.value="";let e=`${this.searchUrl()}&term=${encodeURIComponent(t)}`;window.$http.get(e).then(n=>{this.resultsContainer.innerHTML=n.data,this.hideLoading()})}isDoubleClick(){let t=Date.now(),e=t-this.lastClick<300;return this.lastClick=t,e}onClick(t){let e=t.target.closest("[data-entity-type]");e&&(t.preventDefault(),t.stopPropagation(),this.selectItem(e))}selectItem(t){let e=this.isDoubleClick(),n=t.getAttribute("data-entity-type"),s=t.getAttribute("data-entity-id"),o=!t.classList.contains("selected")||e;this.unselectAll(),this.input.value=o?`${n}:${s}`:"";let r=t.getAttribute("href"),a=t.querySelector(".entity-list-item-name").textContent,l={id:Number(s),name:a,link:r};o?t.classList.add("selected"):window.$events.emit("entity-select-change",null),!(!e&&!o)&&(e&&this.confirmSelection(l),o&&window.$events.emit("entity-select-change",l))}confirmSelection(t){window.$events.emit("entity-select-confirm",t)}unselectAll(){let t=this.elem.querySelectorAll(".selected");for(let e of t)e.classList.remove("selected","primary-background")}};var ai=class extends d{setup(){this.container=this.$el,this.selectButton=this.$refs.select,this.selectorEl=this.$refs.selector,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.handleConfirmedSelection.bind(this))}show(t,e={}){this.callback=t,this.getSelector().configureSearchOptions(e),this.getPopup().show(),this.getSelector().focusSearch()}hide(){this.getPopup().hide()}getPopup(){return window.$components.firstOnElement(this.container,"popup")}getSelector(){return window.$components.firstOnElement(this.selectorEl,"entity-selector")}onSelectButtonClick(){this.handleConfirmedSelection(this.selection)}onSelectionChange(t){this.selection=t,t===null?this.selectButton.setAttribute("disabled","true"):this.selectButton.removeAttribute("disabled")}handleConfirmedSelection(t){this.hide(),this.getSelector().reset(),this.callback&&t&&this.callback(t)}};var li=class extends d{setup(){this.container=this.$el,this.name=this.$opts.name,x(this.$el,()=>{this.$emit(this.name,this.$opts)})}};var ci=class extends d{setup(){this.targetSelector=this.$opts.targetSelector,this.isOpen=this.$opts.isOpen==="true",this.updateEndpoint=this.$opts.updateEndpoint,this.$el.addEventListener("click",this.click.bind(this))}open(t){_t(t,200)}close(t){Ot(t,200)}click(t){t.preventDefault();let e=document.querySelectorAll(this.targetSelector);for(let n of e)(this.isOpen?this.close:this.open)(n);this.isOpen=!this.isOpen,this.updateSystemAjax(this.isOpen)}updateSystemAjax(t){window.$http.patch(this.updateEndpoint,{expand:t?"true":"false"})}};var di=class extends d{setup(){this.container=this.$el,this.input=this.$refs.input,this.suggestions=this.$refs.suggestions,this.suggestionResultsWrap=this.$refs.suggestionResults,this.loadingWrap=this.$refs.loading,this.button=this.$refs.button,this.setupListeners()}setupListeners(){let t=Tt(this.updateSuggestions.bind(this),200,!1);this.input.addEventListener("input",()=>{let{value:e}=this.input;e.length>0?(this.loadingWrap.style.display="block",this.suggestionResultsWrap.style.opacity="0.5",t(e)):this.hideSuggestions()}),this.input.addEventListener("dblclick",()=>{this.input.setAttribute("autocomplete","on"),this.button.focus(),this.input.focus()}),new ut(this.container,()=>{this.hideSuggestions()})}async updateSuggestions(t){let{data:e}=await window.$http.get("/search/suggest",{term:t});if(!this.input.value)return;let n=nt(e);this.suggestionResultsWrap.innerHTML="",this.suggestionResultsWrap.style.opacity="1",this.loadingWrap.style.display="none",this.suggestionResultsWrap.append(n),this.container.classList.contains("search-active")||this.showSuggestions()}showSuggestions(){this.container.classList.add("search-active"),window.requestAnimationFrame(()=>{this.suggestions.classList.add("search-suggestions-animation")})}hideSuggestions(){this.container.classList.remove("search-active"),this.suggestions.classList.remove("search-suggestions-animation"),this.suggestionResultsWrap.innerHTML=""}};var hi=class extends d{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)}};var ui=class extends d{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.uploadButton=this.$refs.uploadButton,this.uploadHint=this.$refs.uploadHint,this.formContainer=this.$refs.formContainer,this.formContainerPlaceholder=this.$refs.formContainerPlaceholder,this.dropzoneContainer=this.$refs.dropzoneContainer,this.loadMore=this.$refs.loadMore,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()}setupListeners(){x(this.filterTabs,n=>{this.resetAll(),this.filter=n.target.dataset.filter,this.setActiveFilterTab(this.filter),this.loadGallery()}),this.searchForm.addEventListener("submit",n=>{this.resetListView(),this.loadGallery(),this.cancelSearch.toggleAttribute("hidden",!this.searchInput.value),n.preventDefault()}),x(this.cancelSearch,()=>{this.resetListView(),this.resetSearchView(),this.loadGallery()}),A(this.container,".load-more button","click",this.runLoadMore.bind(this)),this.listContainer.addEventListener("event-emit-select-image",this.onImageSelectEvent.bind(this)),this.listContainer.addEventListener("error",n=>{n.target.src=window.baseUrl("loading_error.png")},!0),x(this.selectButton,()=>{this.callback&&this.callback(this.lastSelected),this.hide()}),A(this.formContainer,"#image-manager-delete","click",()=>{this.lastSelected&&this.loadImageEditForm(this.lastSelected.id,!0)}),A(this.formContainer,"#image-manager-rebuild-thumbs","click",async(n,s)=>{s.disabled=!0,this.lastSelected&&await this.rebuildThumbnails(this.lastSelected.id),s.disabled=!1}),this.formContainer.addEventListener("ajax-form-success",()=>{this.refreshGallery(),this.resetEditForm()}),this.container.addEventListener("dropzone-upload-success",this.refreshGallery.bind(this));let t=this.listContainer.parentElement,e=[];t.addEventListener("wheel",n=>{if(!(Math.ceil(t.scrollHeight-t.scrollTop)===t.clientHeight)||n.deltaY<1)return;let r=Date.now()-1e3;e.push(Date.now()),e=e.filter(a=>a>=r),e.length>5&&this.canLoadMore()&&this.runLoadMore()})}show(t,e="gallery"){this.resetAll(),this.callback=t,this.type=e,this.getPopup().show();let n=e!=="gallery";this.dropzoneContainer.classList.toggle("hidden",n),this.uploadButton.classList.toggle("hidden",n),this.uploadHint.classList.toggle("hidden",n),window.$components.firstOnElement(this.container,"dropzone").toggleActive(!n),this.hasData||(this.loadGallery(),this.hasData=!0)}hide(){this.getPopup().hide()}getPopup(){return window.$components.firstOnElement(this.popupEl,"popup")}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:e}=await window.$http.get(`images/${this.type}`,t);t.page===1&&(this.listContainer.innerHTML=""),this.addReturnedHtmlElementsToList(e),Xt(this.listContainer)}addReturnedHtmlElementsToList(t){let e=document.createElement("div");e.innerHTML=t;let n=e.querySelector(".load-more");n&&(n.remove(),this.loadMore.innerHTML=n.innerHTML),this.loadMore.toggleAttribute("hidden",!n),window.$components.init(e);for(let s of[...e.children])this.listContainer.appendChild(s)}setActiveFilterTab(t){for(let e of this.filterTabs){let n=e.dataset.filter===t;e.setAttribute("aria-selected",n?"true":"false")}}resetAll(){this.resetState(),this.resetListView(),this.resetSearchView(),this.resetEditForm(),this.setActiveFilterTab("all"),this.selectButton.classList.add("hidden")}resetSearchView(){this.searchInput.value="",this.cancelSearch.toggleAttribute("hidden",!0)}resetEditForm(){this.formContainer.innerHTML="",this.formContainerPlaceholder.removeAttribute("hidden")}resetListView(){Kt(this.listContainer),this.page=1}refreshGallery(){this.resetListView(),this.loadGallery()}async onImageSelectEvent(t){let e=JSON.parse(t.detail.data),n=e&&e.id===this.lastSelected.id&&Date.now()-this.lastSelectedTime<400,s=t.target.classList.contains("selected");[...this.listContainer.querySelectorAll(".selected")].forEach(o=>{o.classList.remove("selected")}),!s&&!n?(t.target.classList.add("selected"),e=await this.loadImageEditForm(e.id)):n?n&&(e=this.lastSelected):this.resetEditForm(),this.selectButton.classList.toggle("hidden",s),n&&this.callback&&(this.callback(e),this.hide()),this.lastSelected=e,this.lastSelectedTime=Date.now()}async loadImageEditForm(t,e=!1){e||(this.formContainer.innerHTML="");let n=e?{delete:!0}:{},{data:s}=await window.$http.get(`/images/edit/${t}`,n);this.formContainer.innerHTML=s,this.formContainerPlaceholder.setAttribute("hidden",""),window.$components.init(this.formContainer);let o=this.formContainer.querySelector("#image-manager-form-image-data");return JSON.parse(o.text)}runLoadMore(){Kt(this.loadMore),this.page+=1,this.loadGallery()}canLoadMore(){return this.loadMore.querySelector("button")&&!this.loadMore.hasAttribute("hidden")}async rebuildThumbnails(t){try{let e=await window.$http.put(`/images/${t}/rebuild-thumbnails`);window.$events.success(e.data),this.refreshGallery()}catch(e){window.$events.showResponseError(e)}}};var pi=class extends d{setup(){this.imageElem=this.$refs.image,this.imageInput=this.$refs.imageInput,this.resetInput=this.$refs.resetInput,this.removeInput=this.$refs.removeInput,this.resetButton=this.$refs.resetButton,this.removeButton=this.$refs.removeButton||null,this.defaultImage=this.$opts.defaultImage,this.setupListeners()}setupListeners(){this.resetButton.addEventListener("click",this.reset.bind(this)),this.removeButton&&this.removeButton.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")}};var fi=class extends d{setup(){this.elem=this.$el,this.menu=this.$refs.menu,this.sortInput=this.$refs.sort,this.orderInput=this.$refs.order,this.form=this.$refs.form,this.setupListeners()}setupListeners(){this.menu.addEventListener("click",t=>{t.target.closest("[data-sort-value]")!==null&&this.sortOptionClick(t)}),this.elem.addEventListener("click",t=>{t.target.closest("[data-sort-dir]")!==null&&this.sortDirectionClick(t)})}sortOptionClick(t){let e=t.target.closest("[data-sort-value]");this.sortInput.value=e.getAttribute("data-sort-value"),t.preventDefault(),this.form.submit()}sortDirectionClick(t){let e=this.orderInput.value;this.orderInput.value=e==="asc"?"desc":"asc",t.preventDefault(),this.form.submit()}};var mi=class extends d{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.display=this.$refs.display,this.input=this.$refs.input,this.divider=this.$refs.divider,this.displayWrap=this.$refs.displayWrap;let{settingContainer:t}=this.$refs,e=t.querySelectorAll('input[type="checkbox"]');this.editor=null,window.importVersioned("markdown").then(n=>n.init({pageId:this.pageId,container:this.elem,displayEl:this.display,inputEl:this.input,drawioUrl:this.getDrawioUrl(),settingInputs:Array.from(e),text:{serverUploadLimit:this.serverUploadLimitText,imageUploadError:this.imageUploadErrorText}})).then(n=>{this.editor=n,this.setupListeners(),this.emitEditorEvents(),this.scrollToTextIfNeeded(),this.editor.actions.updateAndRender()})}emitEditorEvents(){window.$events.emitPublic(this.elem,"editor-markdown::setup",{markdownIt:this.editor.markdown.getRenderer(),displayEl:this.display,cmEditorView:this.editor.cm})}setupListeners(){this.elem.addEventListener("click",t=>{let e=t.target.closest("button[data-action]");if(e===null)return;let n=e.getAttribute("data-action");if(n==="insertImage"&&this.editor.actions.showImageInsert(),n==="insertLink"&&this.editor.actions.showLinkSelector(),n==="insertDrawing"&&(t.ctrlKey||t.metaKey)){this.editor.actions.showImageManager();return}n==="insertDrawing"&&this.editor.actions.startDrawing(),n==="fullscreen"&&this.editor.actions.fullScreen()}),this.elem.addEventListener("click",t=>{let e=t.target.closest(".editor-toolbar-label");if(!e)return;let n=this.elem.querySelectorAll(".markdown-editor-wrap");for(let s of n)s.classList.remove("active");e.closest(".markdown-editor-wrap").classList.add("active")}),this.handleDividerDrag()}handleDividerDrag(){this.divider.addEventListener("pointerdown",()=>{let e=this.elem.getBoundingClientRect(),n=o=>{let r=o.pageX-e.left,a=Math.min(Math.max(20,Math.floor(r/e.width*100)),80);this.displayWrap.style.flexBasis=`${100-a}%`,this.editor.settings.set("editorWidth",a)},s=()=>{window.removeEventListener("pointermove",n),window.removeEventListener("pointerup",s),this.display.style.pointerEvents=null,document.body.style.userSelect=null};this.display.style.pointerEvents="none",document.body.style.userSelect="none",window.addEventListener("pointermove",n),window.addEventListener("pointerup",s)});let t=this.editor.settings.get("editorWidth");t&&(this.displayWrap.style.flexBasis=`${100-t}%`)}scrollToTextIfNeeded(){let e=new URL(window.location).searchParams.get("content-text");e&&this.editor.actions.scrollToText(e)}getDrawioUrl(){let t=document.querySelector("[drawio-url]");return t&&t.getAttribute("drawio-url")||""}getContent(){return this.editor.actions.getContent()}};var gi=class extends d{setup(){this.container=this.$el,this.inputContainer=this.$refs.inputContainer,this.inviteOption=this.container.querySelector("input[name=send_invite]"),this.inviteOption&&(this.inviteOption.addEventListener("change",this.inviteOptionChange.bind(this)),this.inviteOptionChange())}inviteOptionChange(){let t=this.inviteOption.value==="true",e=this.container.querySelectorAll("input[type=password]");for(let n of e)n.disabled=t;this.inputContainer.style.display=t?"none":"block"}};var wi=class extends d{setup(){this.container=this.$el,this.type=this.$opts.type,this.textElem=this.container.querySelector("span"),this.autoHide=this.$opts.autoHide==="true",this.initialShow=this.$opts.show==="true",this.container.style.display="grid",window.$events.listen(this.type,t=>{this.show(t)}),this.container.addEventListener("click",this.hide.bind(this)),this.initialShow&&setTimeout(()=>this.show(this.textElem.textContent),100),this.hideCleanup=this.hideCleanup.bind(this)}show(t=""){if(this.container.removeEventListener("transitionend",this.hideCleanup),this.textElem.textContent=t,this.container.style.display="grid",setTimeout(()=>{this.container.classList.add("showing")},1),this.autoHide){let e=t.split(" ").length,n=Math.max(2e3,1e3+250*e);setTimeout(this.hide.bind(this),n)}}hide(){this.container.classList.remove("showing"),this.container.addEventListener("transitionend",this.hideCleanup)}hideCleanup(){this.container.style.display="none",this.container.removeEventListener("transitionend",this.hideCleanup)}};var bi=class extends d{setup(){this.removeButton=this.$refs.remove,this.showButton=this.$refs.show,this.input=this.$refs.input,this.setupListeners()}setupListeners(){x(this.removeButton,()=>{this.input.value="",this.input.classList.add("hidden"),this.removeButton.classList.add("hidden"),this.showButton.classList.remove("hidden")}),x(this.showButton,()=>{this.input.classList.remove("hidden"),this.removeButton.classList.remove("hidden"),this.showButton.classList.add("hidden")})}};function Os(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+o","","InsertOrderedList"),i.shortcuts.add("meta+p","","InsertUnorderedList"),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","",()=>{let t=i.selection.getNode(),e=t?t.closest(".callout"):null,n=["info","success","warning","danger"],o=(n.findIndex(a=>e&&e.classList.contains(a))+1)%n.length,r=n[o];i.formatter.apply(`callout${r}`)}),i.shortcuts.add("meta+shift+K","",()=>{let t=window.$components.first("entity-selector-popup"),e=i.selection.getContent({format:"text"}).trim();t.show(n=>{i.selection.isCollapsed()?i.insertContent(i.dom.createHTML("a",{href:n.link},i.dom.encode(n.name))):i.formatter.apply("link",{href:n.link}),i.selection.collapse(!1),i.focus()},{initialValue:e,searchEndpoint:"/search/entity-selector",entityTypes:"page,book,chapter,bookshelf",entityPermission:"view"})})}function _s(i){window.$events.listen("editor::replace",({html:t})=>{i.setContent(t)}),window.$events.listen("editor::append",({html:t})=>{let e=i.getContent()+t;i.setContent(e)}),window.$events.listen("editor::prepend",({html:t})=>{let e=t+i.getContent();i.setContent(e)}),window.$events.listen("editor::insert",({html:t})=>{i.insertContent(t)}),window.$events.listen("editor::focus",()=>{i.initialized&&i.focus()})}function br(i,t){let e=i.dom.get(encodeURIComponent(t).replace(/!/g,"%21"));e&&(e.scrollIntoView(),i.selection.select(e,!0),i.selection.collapse(!1),i.focus())}function Ns(i){let e=new URL(window.location).searchParams.get("content-id");e&&br(i,e)}var xt,vi;function vr(i){return i&&!!(i.textContent||i.innerText)}async function yr(i,t){if(i===null||i.type.indexOf("image")!==0)throw new Error("Not an image file");let e=i.name||`image-${Date.now()}.png`,n=new FormData;return n.append("file",i,e),n.append("uploaded_to",t),(await window.$http.post(window.baseUrl("/images/gallery"),n)).data}function Fs(i,t,e){let n=new Nt(e.clipboardData||e.dataTransfer);if(!n.hasItems()||n.containsTabularData())return;let s=n.getImages();for(let o of s){let r=`image-${Math.random().toString(16).slice(2)}`,a=window.baseUrl("/loading.gif");e.preventDefault(),setTimeout(()=>{i.insertContent(``),yr(o,t.pageId).then(l=>{let c=l.name.replace(/"/g,""),h=``,u=i.dom.create("a",{target:"_blank",href:l.url},h);i.dom.replace(u,r)}).catch(l=>{i.dom.remove(r),window.$events.error(l?.data?.message||t.translations.imageUploadErrorText),console.error(l)})},10)}}function Cr(i){let t=i.selection.getNode();t.nodeName==="IMG"&&(xt=i.dom.getParent(t,".mceTemp"),!xt&&t.parentNode.nodeName==="A"&&!vr(t.parentNode)&&(xt=t.parentNode)),t.hasAttribute("contenteditable")&&t.getAttribute("contenteditable")==="false"&&(vi=t)}function Er(i,t,e){let{dom:n}=i,s=window.tinymce.dom.RangeUtils.getCaretRangeFromPoint(e.clientX,e.clientY,i.getDoc()),o=e.dataTransfer&&e.dataTransfer.getData("bookstack/template");o&&(e.preventDefault(),window.$http.get(`/templates/${o}`).then(r=>{i.selection.setRng(s),i.undoManager.transact(()=>{i.execCommand("mceInsertContent",!1,r.data.html)})})),n.getParent(s.startContainer,".mceTemp")?e.preventDefault():xt&&(e.preventDefault(),i.undoManager.transact(()=>{i.selection.setRng(s),i.selection.setNode(xt),n.remove(xt)})),!e.isDefaultPrevented()&&vi&&(e.preventDefault(),i.undoManager.transact(()=>{let r=i.selection.getNode(),a=i.selection.getRng(),l=r.closest("body > *");a.startOffset>a.startContainer.length/2?l.after(vi):l.before(vi)})),e.isDefaultPrevented()||Fs(i,t,e),xt=null}function xr(i,t){t.preventDefault(),i.focus();let n=window.tinymce.dom.RangeUtils.getCaretRangeFromPoint(t.clientX??0,t.clientY??0,i.getDoc());i.selection.setRng(n)}function Rs(i,t){i.on("dragover",e=>xr(i,e)),i.on("dragstart",()=>Cr(i)),i.on("drop",e=>Er(i,t,e)),i.on("paste",e=>Fs(i,t,e))}function Hs(i){return["undo redo","styles","bold italic underline forecolor backcolor formatoverflow","alignleft aligncenter alignright alignjustify","bullist numlist listoverflow",i.textDirection==="rtl"?"ltr rtl":"","link customtable imagemanager-insert insertoverflow","code about fullscreen"].filter(n=>!!n).join(" | ")}function Sr(i){i.ui.registry.addGroupToolbarButton("formatoverflow",{icon:"more-drawer",tooltip:"More",items:"strikethrough superscript subscript inlinecode removeformat"}),i.ui.registry.addGroupToolbarButton("listoverflow",{icon:"more-drawer",tooltip:"More",items:"tasklist outdent indent"}),i.ui.registry.addGroupToolbarButton("insertoverflow",{icon:"more-drawer",tooltip:"More",items:"customhr codeeditor drawio media details"})}function kr(i){i.ui.registry.addContextToolbar("linkcontexttoolbar",{predicate(t){return t.closest("a")!==null},position:"node",scope:"node",items:"link unlink openlink"})}function Lr(i){i.ui.registry.addContextToolbar("imagecontexttoolbar",{predicate(t){return t.closest("img")!==null&&!t.hasAttribute("data-mce-object")},position:"node",scope:"node",items:"image"})}function $r(i){i.ui.registry.addContextToolbar("objectcontexttoolbar",{predicate(t){return t.closest("img")!==null&&t.hasAttribute("data-mce-object")},position:"node",scope:"node",items:"media"})}function qs(i){Sr(i),kr(i),Lr(i),$r(i)}var Tr={"table-delete-column":'',"table-delete-row":'',"table-insert-column-after":'',"table-insert-column-before":'',"table-insert-row-above":'',"table-insert-row-after":'',table:'',"table-delete-table":''};function Us(i){for(let[t,e]of Object.entries(Tr))i.ui.registry.addIcon(t,e)}function Dr(i){i.serializer.addNodeFilter("br",t=>{for(let e of t)if(e.parent&&e.parent.name==="code"){let n=window.tinymce.html.Node.create("#text");n.value=`
-`,e.replace(n)}})}function Ar(i){i.parser.addNodeFilter("div",t=>{for(let e of t){let n=e.attr("id")||"",s=e.attr("class")||"";(n==="pointer"||s.includes("pointer"))&&e.remove()}})}function Vs(i){Dr(i),Ar(i)}function zs(i){return i.tagName.toLowerCase()==="code-block"}function Ws(i,t,e,n,s){let o=window.$components.first("code-editor"),r=i.selection.getBookmark();o.open(t,e,n,(a,l)=>{s(a,l),i.focus(),i.selection.moveToBookmark(r)},()=>{i.focus(),i.selection.moveToBookmark(r)})}function js(i,t){let e=t.getAttribute("dir")||"";Ws(i,t.getContent(),t.getLanguage(),e,(n,s)=>{t.setContent(n,s)})}function Ir(i){let t=i.getDoc(),e=t.defaultView;class n extends e.HTMLElement{constructor(){super();U(this,"editor",null);this.attachShadow({mode:"open"});let r=document.head.querySelectorAll('link[rel="stylesheet"]:not([media="print"]),style'),a=Array.from(r).map(c=>c.cloneNode(!0)),l=document.createElement("div");l.style.pointerEvents="none",l.contentEditable="false",l.classList.add("CodeMirrorContainer"),l.classList.toggle("dark-mode",document.documentElement.classList.contains("dark-mode")),this.shadowRoot.append(...a,l)}getLanguage(){let r=c=>(c.split(" ").filter(u=>u.startsWith("language-"))[0]||"").replace("language-",""),a=this.querySelector("code"),l=this.querySelector("pre");return r(l.className)||a&&r(a.className)||""}setContent(r,a){this.editor&&(this.editor.setContent(r),this.editor.setMode(a,r));let l=this.querySelector("pre");l||(l=t.createElement("pre"),this.append(l)),l.innerHTML="";let c=t.createElement("code");l.append(c),c.innerText=r,c.className=`language-${a}`}getContent(){let r=this.querySelector("code")||this.querySelector("pre"),a=document.createElement("pre");a.innerHTML=r.innerHTML.replace(/\ufeff/g,"");let l=a.querySelectorAll("br");for(let c of l)c.replaceWith(`
+var Gn=Object.defineProperty;var Co=(i,t,e)=>t in i?Gn(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var fe=(i,t)=>{for(var e in t)Gn(i,e,{get:t[e],enumerable:!0})};var U=(i,t,e)=>(Co(i,typeof t!="symbol"?t+"":t,e),e),Eo=(i,t,e)=>{if(!t.has(i))throw TypeError("Cannot "+e)};var Yi=(i,t,e)=>{if(t.has(i))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(i):t.set(i,e)};var jt=(i,t,e)=>(Eo(i,t,"access private method"),e);var Qi={};fe(Qi,{emit:()=>Ji,emitPublic:()=>ko,error:()=>Zi,listen:()=>So,showResponseError:()=>To,showValidationErrors:()=>$o,success:()=>Lo});var me={},xo=[];function Ji(i,t){xo.push({name:i,data:t});let e=me[i]||[];for(let n of e)n(t)}function So(i,t){typeof me[i]>"u"&&(me[i]=[]),me[i].push(t)}function ko(i,t,e){let n=new CustomEvent(t,{detail:e,bubbles:!0});i.dispatchEvent(n)}function Lo(i){Ji("success",i)}function Zi(i){Ji("error",i)}function $o(i){if(i.status&&i.status===422&&i.data){let t=Object.values(i.data).flat().join(`
+`);Zi(t)}}function To(i){i.status&&i.status>=400&&i.data&&i.data.message&&Zi(i.data.message)}var tn={};fe(tn,{HttpError:()=>ge,createXMLHttpRequest:()=>Ao,delete:()=>Oo,formatErrorResponseText:()=>_o,get:()=>Io,patch:()=>Po,post:()=>Mo,put:()=>Bo});async function Do(i){if(i.status===204)return null;let e=(i.headers.get("Content-Type")||"").split(";")[0].split("/").pop();return e==="javascript"||e==="json"?i.json():i.text()}var ge=class extends Error{constructor(t,e){super(t.statusText),this.data=e,this.headers=t.headers,this.redirected=t.redirected,this.status=t.status,this.statusText=t.statusText,this.url=t.url,this.original=t}};function Ao(i,t,e={}){let n=document.querySelector("meta[name=token]").getAttribute("content"),s=new XMLHttpRequest;for(let[o,r]of Object.entries(e))s.addEventListener(o,r.bind(s));return s.open(i,t),s.withCredentials=!0,s.setRequestHeader("X-CSRF-TOKEN",n),s}async function Yn(i,t={}){let e=i;if(e.startsWith("http")||(e=window.baseUrl(e)),t.params){let l=new URL(e);for(let c of Object.keys(t.params)){let h=t.params[c];typeof h<"u"&&h!==null&&l.searchParams.set(c,h)}e=l.toString()}let n=document.querySelector("meta[name=token]").getAttribute("content"),s={...t,credentials:"same-origin"};s.headers={...s.headers||{},baseURL:window.baseUrl(""),"X-CSRF-TOKEN":n};let o=await fetch(e,s),r=await Do(o),a={data:r,headers:o.headers,redirected:o.redirected,status:o.status,statusText:o.statusText,url:o.url,original:o};if(!o.ok)throw new ge(o,r);return a}async function we(i,t,e=null){let n={method:i,body:e};return typeof e=="object"&&!(e instanceof FormData)&&(n.headers={"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},n.body=JSON.stringify(e)),e instanceof FormData&&i!=="post"&&(e.append("_method",i),n.method="post"),Yn(t,n)}async function Io(i,t={}){return Yn(i,{method:"GET",params:t})}async function Mo(i,t=null){return we("POST",i,t)}async function Bo(i,t=null){return we("PUT",i,t)}async function Po(i,t=null){return we("PATCH",i,t)}async function Oo(i,t=null){return we("DELETE",i,t)}function _o(i){let t=i.startsWith("{")?JSON.parse(i):{message:i};if(!t)return i;if(t.message||t.error)return t.message||t.error;let e=Object.values(t);return e.every(s=>Array.isArray(s)||s.every(o=>typeof o=="string"))?e.flat().join(" "):i}var en=class{constructor(){this.store=new Map,this.parseTranslations()}parseTranslations(){let t=document.querySelectorAll('meta[name="translation"]');for(let e of t){let n=e.getAttribute("key"),s=e.getAttribute("value");this.store.set(n,s)}}get(t,e){let n=this.getTransText(t);return this.performReplacements(n,e)}getPlural(t,e,n){let s=this.getTransText(t);return this.parsePlural(s,e,n)}parsePlural(t,e,n){let s=t.split("|"),o=/^{([0-9]+)}/,r=/^\[([0-9]+),([0-9*]+)]/,a=null;for(let l of s){let c=l.match(o);if(c!==null&&Number(c[1])===e){a=l.replace(o,"").trim();break}let h=l.match(r);if(h!==null&&Number(h[1])<=e&&(h[2]==="*"||Number(h[2])>=e)){a=l.replace(r,"").trim();break}}return a===null&&s.length>1&&(a=e===1?s[0]:s[1]),a===null&&(a=s[0]),this.performReplacements(a,n)}getTransText(t){let e=this.store.get(t);return e===void 0&&console.warn(`Translation with key "${t}" does not exist`),e}performReplacements(t,e){if(!e)return t;let n=t.match(/:(\S+)/g);if(n===null)return t;let s=t;return n.forEach(o=>{let r=o.substring(1);typeof e[r]>"u"||(s=s.replace(o,e[r]))}),s}},Jn=en;var an={};fe(an,{first:()=>Ho,firstOnElement:()=>Uo,get:()=>qo,init:()=>on,register:()=>rn});function nn(i){let t=n=>n.slice(0,1).toUpperCase()+n.slice(1),e=i.split("-");return e[0]+e.slice(1).map(t).join("")}function Zn(i){return i.replace(/[A-Z]/g,(t,e)=>(e>0?"-":"")+t.toLowerCase())}var Wt={},Qn={},sn=new WeakMap;function No(i,t){let e={},n={},s=`${i}@`,o=`[refs*="${s}"]`,r=[...t.querySelectorAll(o)];t.matches(o)&&r.push(t);for(let a of r){let l=a.getAttribute("refs").split(" ").filter(c=>c.startsWith(s)).map(c=>c.replace(s,"")).map(nn);for(let c of l)e[c]=a,typeof n[c]>"u"&&(n[c]=[]),n[c].push(a)}return{refs:e,manyRefs:n}}function Fo(i,t){let e={},n=`option:${i}:`;for(let{name:s,value:o}of t.attributes)if(s.startsWith(n)){let r=s.replace(n,"");e[nn(r)]=o||""}return e}function Ro(i,t){let e=Qn[i];if(e===void 0)return;let n;try{n=new e,n.$name=i,n.$el=t;let o=No(i,t);n.$refs=o.refs,n.$manyRefs=o.manyRefs,n.$opts=Fo(i,t),n.setup()}catch(o){console.error("Failed to create component",o,i,t)}typeof Wt[i]>"u"&&(Wt[i]=[]),Wt[i].push(n);let s=sn.get(t)||{};s[i]=n,sn.set(t,s)}function on(i=document){let t=i.querySelectorAll("[component],[components]");for(let e of t){let n=`${e.getAttribute("component")||""} ${e.getAttribute("components")}`.toLowerCase().split(" ").filter(Boolean);for(let s of n)Ro(s,e)}}function rn(i){let t=Object.keys(i);for(let e of t)Qn[Zn(e)]=i[e]}function Ho(i){return(Wt[i]||[null])[0]}function qo(i){return Wt[i]||[]}function Uo(i,t){return(sn.get(i)||{})[t]||null}var Kn={};fe(Kn,{AddRemoveRows:()=>be,AjaxDeleteRow:()=>ye,AjaxForm:()=>Ce,Attachments:()=>Ee,AttachmentsList:()=>xe,AutoSubmit:()=>ke,AutoSuggest:()=>Se,BackToTop:()=>Le,BookSort:()=>ze,ChapterContents:()=>We,CodeEditor:()=>Ke,CodeHighlighter:()=>Xe,CodeTextarea:()=>Ge,Collapsible:()=>Ye,ConfirmDialog:()=>Je,CustomCheckbox:()=>Ze,DetailsHighlighter:()=>Qe,Dropdown:()=>ti,DropdownSearch:()=>ei,Dropzone:()=>ii,EditorToolbox:()=>ni,EntityPermissions:()=>si,EntitySearch:()=>oi,EntitySelector:()=>ri,EntitySelectorPopup:()=>ai,EventEmitSelect:()=>li,ExpandToggle:()=>ci,GlobalSearch:()=>di,HeaderMobileToggle:()=>hi,ImageManager:()=>ui,ImagePicker:()=>pi,ListSortControl:()=>fi,MarkdownEditor:()=>mi,NewUserPassword:()=>gi,Notification:()=>wi,OptionalInput:()=>vi,PageComment:()=>Si,PageComments:()=>ki,PageDisplay:()=>Li,PageEditor:()=>$i,PagePicker:()=>Di,PermissionsTable:()=>Ai,Pointer:()=>Ii,Popup:()=>Mi,SettingAppColorScheme:()=>Bi,SettingColorPicker:()=>Pi,SettingHomepageControl:()=>Oi,ShelfSort:()=>_i,ShortcutInput:()=>Fi,Shortcuts:()=>Ni,SortableList:()=>Ri,SubmitOnChange:()=>Hi,Tabs:()=>qi,TagManager:()=>Ui,TemplateManager:()=>Vi,ToggleSwitch:()=>zi,TriLayout:()=>ji,UserSelect:()=>Wi,WebhookEvents:()=>Ki,WysiwygEditor:()=>Xi,WysiwygInput:()=>Gi});function it(i,t={},e=[]){let n=document.createElement(i);for(let[s,o]of Object.entries(t))o===null?n.removeAttribute(s):n.setAttribute(s,o);for(let s of e)typeof s=="string"?n.append(document.createTextNode(s)):n.append(s);return n}function ln(i,t){let e=document.querySelectorAll(i);for(let n of e)t(n)}function ve(i,t,e){for(let n of t)i.addEventListener(n,e)}function x(i,t){Array.isArray(i)||(i=[i]);for(let e of i)e.addEventListener("click",t),e.addEventListener("keydown",n=>{(n.key==="Enter"||n.key===" ")&&(n.preventDefault(),t(n))})}function ts(i,t,e){Array.isArray(t)||(t=[t]);let n=s=>{s.key===i&&e(s)};t.forEach(s=>s.addEventListener("keydown",n))}function Lt(i,t){ts("Enter",i,t)}function es(i,t){ts("Escape",i,t)}function A(i,t,e,n){i.addEventListener(e,s=>{let o=s.target.closest(t);o&&n.call(o,s,o)})}function is(i,t){let e=document.querySelectorAll(i);t=t.toLowerCase();for(let n of e)if(n.textContent.toLowerCase().includes(t))return n;return null}function Kt(i){i.innerHTML='
'}function $t(){let i=document.createElement("div");return i.classList.add("loading-container"),i.innerHTML="",i}function Xt(i){let t=i.querySelectorAll(".loading-container");for(let e of t)e.remove()}function nt(i){let t=document.createElement("div");return t.innerHTML=i,window.$components.init(t),t.children[0]}function Tt(i,t,e){let n;return function(...o){let r=this,a=function(){n=null,e||i.apply(r,o)},l=e&&!n;clearTimeout(n),n=setTimeout(a,t),l&&i.apply(r,o)}}function dn(i){if(!i)return;let t=i;for(;t.parentElement;)t=t.parentElement,t.nodeName==="DETAILS"&&!t.open&&(t.open=!0);i.scrollIntoView({behavior:"smooth"});let e=getComputedStyle(document.body).getPropertyValue("--color-link");i.style.outline=`2px dashed ${e}`,i.style.outlineOffset="5px",i.style.transition=null,setTimeout(()=>{i.style.transition="outline linear 3s",i.style.outline="2px dashed rgba(0, 0, 0, 0)";let n=()=>{i.removeEventListener("transitionend",n),i.style.transition=null,i.style.outline=null,i.style.outlineOffset=null};i.addEventListener("transitionend",n)},1e3)}function ns(i){return i.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function ss(){let i=()=>((1+Math.random())*65536|0).toString(16).substring(1);return`${i()+i()}-${i()}-${i()}-${i()}-${i()}${i()}${i()}`}function os(i){return new Promise(t=>{setTimeout(t,i)})}var d=class{constructor(){U(this,"$name","");U(this,"$el",null);U(this,"$refs",{});U(this,"$manyRefs",{});U(this,"$opts",{})}setup(){}$emit(t,e={}){e.from=this;let n=this.$name,s=new CustomEvent(`${n}-${t}`,{bubbles:!0,detail:e});this.$el.dispatchEvent(s)}};var be=class extends d{setup(){this.modelRow=this.$refs.model,this.addButton=this.$refs.add,this.removeSelector=this.$opts.removeSelector,this.rowSelector=this.$opts.rowSelector,this.setupListeners()}setupListeners(){this.addButton.addEventListener("click",this.add.bind(this)),A(this.$el,this.removeSelector,"click",t=>{t.target.closest(this.rowSelector).remove()})}add(){let t=this.modelRow.cloneNode(!0);t.classList.remove("hidden"),this.setClonedInputNames(t),this.modelRow.parentNode.insertBefore(t,this.modelRow),window.$components.init(t)}setClonedInputNames(t){let e=ss(),n=t.querySelectorAll('[name*="randrowid"]');for(let s of n)s.name=s.name.split("randrowid").join(e)}};var ye=class extends d{setup(){this.row=this.$el,this.url=this.$opts.url,this.deleteButtons=this.$manyRefs.delete,x(this.deleteButtons,this.runDelete.bind(this))}runDelete(){this.row.style.opacity="0.7",this.row.style.pointerEvents="none",window.$http.delete(this.url).then(t=>{typeof t.data=="object"&&t.data.message&&window.$events.emit("success",t.data.message),this.row.remove()}).catch(()=>{this.row.style.opacity=null,this.row.style.pointerEvents=null})}};var Ce=class extends d{setup(){this.container=this.$el,this.responseContainer=this.container,this.url=this.$opts.url,this.method=this.$opts.method||"post",this.successMessage=this.$opts.successMessage,this.submitButtons=this.$manyRefs.submit||[],this.$opts.responseContainer&&(this.responseContainer=this.container.closest(this.$opts.responseContainer)),this.setupListeners()}setupListeners(){if(this.container.tagName==="FORM"){this.container.addEventListener("submit",this.submitRealForm.bind(this));return}Lt(this.container,t=>{this.submitFakeForm(),t.preventDefault()}),this.submitButtons.forEach(t=>x(t,this.submitFakeForm.bind(this)))}submitFakeForm(){let t=new FormData,e=this.container.querySelectorAll("[name]");for(let n of e)t.append(n.getAttribute("name"),n.value);this.submit(t)}submitRealForm(t){t.preventDefault();let e=new FormData(this.container);this.submit(e)}async submit(t){this.responseContainer.style.opacity="0.7",this.responseContainer.style.pointerEvents="none";try{let e=await window.$http[this.method.toLowerCase()](this.url,t);this.$emit("success",{formData:t}),this.responseContainer.innerHTML=e.data,this.successMessage&&window.$events.emit("success",this.successMessage)}catch(e){this.responseContainer.innerHTML=e.data}window.$components.init(this.responseContainer),this.responseContainer.style.opacity=null,this.responseContainer.style.pointerEvents=null}};var Ee=class extends d{setup(){this.container=this.$el,this.pageId=this.$opts.pageId,this.editContainer=this.$refs.editContainer,this.listContainer=this.$refs.listContainer,this.linksContainer=this.$refs.linksContainer,this.listPanel=this.$refs.listPanel,this.attachLinkButton=this.$refs.attachLinkButton,this.setupListeners()}setupListeners(){let t=this.reloadList.bind(this);this.container.addEventListener("dropzone-upload-success",t),this.container.addEventListener("ajax-form-success",t),this.container.addEventListener("sortable-list-sort",e=>{this.updateOrder(e.detail.ids)}),this.container.addEventListener("event-emit-select-edit",e=>{this.startEdit(e.detail.id)}),this.container.addEventListener("event-emit-select-edit-back",()=>{this.stopEdit()}),this.container.addEventListener("event-emit-select-insert",e=>{let n=e.target.closest("[data-drag-content]").getAttribute("data-drag-content"),s=JSON.parse(n);window.$events.emit("editor::insert",{html:s["text/html"],markdown:s["text/plain"]})}),this.attachLinkButton.addEventListener("click",()=>{this.showSection("links")})}showSection(t){let e={links:this.linksContainer,edit:this.editContainer,list:this.listContainer};for(let[n,s]of Object.entries(e))s.toggleAttribute("hidden",n!==t)}reloadList(){this.stopEdit(),window.$http.get(`/attachments/get/page/${this.pageId}`).then(t=>{this.listPanel.innerHTML=t.data,window.$components.init(this.listPanel)})}updateOrder(t){window.$http.put(`/attachments/sort/page/${this.pageId}`,{order:t}).then(e=>{window.$events.emit("success",e.data.message)})}async startEdit(t){this.showSection("edit"),Kt(this.editContainer);let e=await window.$http.get(`/attachments/edit/${t}`);this.editContainer.innerHTML=e.data,window.$components.init(this.editContainer)}stopEdit(){this.showSection("list")}};var xe=class extends d{setup(){this.container=this.$el,this.fileLinks=this.$manyRefs.linkTypeFile,this.setupListeners()}setupListeners(){let t=e=>e.key==="Control"||e.key==="Meta";window.addEventListener("keydown",e=>{t(e)&&this.addOpenQueryToLinks()},{passive:!0}),window.addEventListener("keyup",e=>{t(e)&&this.removeOpenQueryFromLinks()},{passive:!0})}addOpenQueryToLinks(){for(let t of this.fileLinks)t.href.split("?")[1]!=="open=true"&&(t.href+="?open=true",t.setAttribute("target","_blank"))}removeOpenQueryFromLinks(){for(let t of this.fileLinks)t.href=t.href.split("?")[0],t.removeAttribute("target")}};var Gt,hn,Yt,un,ut=class{constructor(t,e=null,n=null){Yi(this,Gt);Yi(this,Yt);this.containers=[t],this.onEscape=e,this.onEnter=n,t.addEventListener("keydown",jt(this,Gt,hn).bind(this))}shareHandlingToEl(t){this.containers.push(t),t.addEventListener("keydown",jt(this,Gt,hn).bind(this))}focusNext(){let t=jt(this,Yt,un).call(this),n=t.indexOf(document.activeElement)+1;n>=t.length&&(n=0),t[n].focus()}focusPrevious(){let t=jt(this,Yt,un).call(this),n=t.indexOf(document.activeElement)-1;n<0&&(n=t.length-1),t[n].focus()}};Gt=new WeakSet,hn=function(t){t.target.matches("input")&&(t.key==="ArrowRight"||t.key==="ArrowLeft")||(t.key==="ArrowDown"||t.key==="ArrowRight"?(this.focusNext(),t.preventDefault()):t.key==="ArrowUp"||t.key==="ArrowLeft"?(this.focusPrevious(),t.preventDefault()):t.key==="Escape"?this.onEscape?this.onEscape(t):document.activeElement&&document.activeElement.blur():t.key==="Enter"&&this.onEnter&&this.onEnter(t))},Yt=new WeakSet,un=function(){let t=[],e='[tabindex]:not([tabindex="-1"]),[href],button:not([tabindex="-1"],[disabled]),input:not([type=hidden])';for(let n of this.containers)t.push(...n.querySelectorAll(e));return t};var pn={},Se=class extends d{setup(){this.parent=this.$el.parentElement,this.container=this.$el,this.type=this.$opts.type,this.url=this.$opts.url,this.input=this.$refs.input,this.list=this.$refs.list,this.lastPopulated=0,this.setupListeners()}setupListeners(){new ut(this.list,()=>{this.input.focus(),setTimeout(()=>this.hideSuggestions(),1)},e=>{e.preventDefault();let n=e.target.textContent;n&&this.selectSuggestion(n)}).shareHandlingToEl(this.input),A(this.list,".text-item","click",(e,n)=>{this.selectSuggestion(n.textContent)}),this.input.addEventListener("input",this.requestSuggestions.bind(this)),this.input.addEventListener("focus",this.requestSuggestions.bind(this)),this.input.addEventListener("blur",this.hideSuggestionsIfFocusedLost.bind(this)),this.input.addEventListener("keydown",e=>{e.key==="Tab"&&this.hideSuggestions()})}selectSuggestion(t){this.input.value=t,this.lastPopulated=Date.now(),this.input.focus(),this.input.dispatchEvent(new Event("input",{bubbles:!0})),this.input.dispatchEvent(new Event("change",{bubbles:!0})),this.hideSuggestions()}async requestSuggestions(){if(Date.now()-this.lastPopulated<50)return;let t=this.getNameFilterIfNeeded(),e=this.input.value.toLowerCase(),s=(await this.loadSuggestions(e,t)).filter(o=>e===""||o.toLowerCase().startsWith(e)).slice(0,10);this.displaySuggestions(s)}getNameFilterIfNeeded(){return this.type!=="value"?null:this.parent.querySelector("input").value}async loadSuggestions(t,e=null){t=t.slice(0,4);let n={search:t,name:e},s=`${this.url}:${JSON.stringify(n)}`;if(pn[s])return pn[s];let o=await window.$http.get(this.url,n);return pn[s]=o.data,o.data}displaySuggestions(t){if(t.length===0){this.hideSuggestions();return}this.list.innerHTML=t.map(e=>`
${ns(e)}
`).join(""),this.list.style.display="block";for(let e of this.list.querySelectorAll(".text-item"))e.addEventListener("blur",this.hideSuggestionsIfFocusedLost.bind(this))}hideSuggestions(){this.list.style.display="none"}hideSuggestionsIfFocusedLost(t){this.container.contains(t.relatedTarget)||this.hideSuggestions()}};var ke=class extends d{setup(){this.form=this.$el,this.form.submit()}};var Le=class extends d{setup(){if(this.button=this.$el,this.targetElem=document.getElementById("header"),this.showing=!1,this.breakPoint=1200,document.body.classList.contains("flexbox")){this.button.style.display="none";return}this.button.addEventListener("click",this.scrollToTop.bind(this)),window.addEventListener("scroll",this.onPageScroll.bind(this))}onPageScroll(){let t=document.documentElement.scrollTop||document.body.scrollTop||0;!this.showing&&t>this.breakPoint?(this.button.style.display="block",this.showing=!0,setTimeout(()=>{this.button.style.opacity=.4},1)):this.showing&&t{this.button.style.display="none"},500))}scrollToTop(){let t=this.targetElem.getBoundingClientRect().top,e=document.documentElement.scrollTop?document.documentElement:document.body,n=300,s=Date.now(),o=this.targetElem.getBoundingClientRect().top;function r(){let a=1-(Date.now()-s)/n,l=Math.abs(a*o);a>0?(e.scrollTop=l,requestAnimationFrame(r.bind(this))):e.scrollTop=t}requestAnimationFrame(r.bind(this))}};function rs(i,t){var e=Object.keys(i);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(i);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(i,s).enumerable})),e.push.apply(e,n)}return e}function ot(i){for(var t=1;t=0)&&(e[s]=i[s]);return e}function jo(i,t){if(i==null)return{};var e=zo(i,t),n,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(i);for(s=0;s=0)&&Object.prototype.propertyIsEnumerable.call(i,n)&&(e[n]=i[n])}return e}function Wo(i){return Ko(i)||Xo(i)||Go(i)||Yo()}function Ko(i){if(Array.isArray(i))return Sn(i)}function Xo(i){if(typeof Symbol<"u"&&i[Symbol.iterator]!=null||i["@@iterator"]!=null)return Array.from(i)}function Go(i,t){if(i){if(typeof i=="string")return Sn(i,t);var e=Object.prototype.toString.call(i).slice(8,-1);if(e==="Object"&&i.constructor&&(e=i.constructor.name),e==="Map"||e==="Set")return Array.from(i);if(e==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e))return Sn(i,t)}}function Sn(i,t){(t==null||t>i.length)&&(t=i.length);for(var e=0,n=new Array(t);e"&&(t=t.substring(1)),i)try{if(i.matches)return i.matches(t);if(i.msMatchesSelector)return i.msMatchesSelector(t);if(i.webkitMatchesSelector)return i.webkitMatchesSelector(t)}catch{return!1}return!1}}function Zo(i){return i.host&&i!==document&&i.host.nodeType?i.host:i.parentNode}function Y(i,t,e,n){if(i){e=e||document;do{if(t!=null&&(t[0]===">"?i.parentNode===e&&Fe(i,t):Fe(i,t))||n&&i===e)return i;if(i===e)break}while(i=Zo(i))}return null}var ls=/\s+/g;function P(i,t,e){if(i&&t)if(i.classList)i.classList[e?"add":"remove"](t);else{var n=(" "+i.className+" ").replace(ls," ").replace(" "+t+" "," ");i.className=(n+(e?" "+t:"")).replace(ls," ")}}function f(i,t,e){var n=i&&i.style;if(n){if(e===void 0)return document.defaultView&&document.defaultView.getComputedStyle?e=document.defaultView.getComputedStyle(i,""):i.currentStyle&&(e=i.currentStyle),t===void 0?e:e[t];!(t in n)&&t.indexOf("webkit")===-1&&(t="-webkit-"+t),n[t]=e+(typeof e=="string"?"":"px")}}function Ct(i,t){var e="";if(typeof i=="string")e=i;else do{var n=f(i,"transform");n&&n!=="none"&&(e=n+" "+e)}while(!t&&(i=i.parentNode));var s=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return s&&new s(e)}function ys(i,t,e){if(i){var n=i.getElementsByTagName(t),s=0,o=n.length;if(e)for(;s=o:r=s<=o,!r)return n;if(n===st())break;n=mt(n,!1)}return!1}function Pt(i,t,e,n){for(var s=0,o=0,r=i.children;o2&&arguments[2]!==void 0?arguments[2]:{},s=n.evt,o=jo(n,or);de.pluginEvent.bind(g)(t,e,ot({dragEl:p,parentEl:I,ghostEl:v,rootEl:T,nextEl:yt,lastDownEl:Pe,cloneEl:D,cloneHidden:ft,dragStarted:ee,putSortable:N,activeSortable:g.active,originalEvent:s,oldIndex:Bt,oldDraggableIndex:re,newIndex:X,newDraggableIndex:pt,hideGhostForTarget:$s,unhideGhostForTarget:Ts,cloneNowHidden:function(){ft=!0},cloneNowShown:function(){ft=!1},dispatchSortableEvent:function(a){H({sortable:e,name:a,originalEvent:s})}},o))};function H(i){te(ot({putSortable:N,cloneEl:D,targetEl:p,rootEl:T,oldIndex:Bt,oldDraggableIndex:re,newIndex:X,newDraggableIndex:pt},i))}var p,I,v,T,yt,Pe,D,ft,Bt,X,re,pt,$e,N,Mt=!1,Re=!1,He=[],vt,J,wn,vn,us,ps,ee,At,ae,le=!1,Te=!1,Oe,F,bn=[],kn=!1,qe=[],Ve=typeof document<"u",De=ws,fs=ce||ct?"cssFloat":"float",rr=Ve&&!vs&&!ws&&"draggable"in document.createElement("div"),Ss=function(){if(Ve){if(ct)return!1;var i=document.createElement("x");return i.style.cssText="pointer-events:auto",i.style.pointerEvents==="auto"}}(),ks=function(t,e){var n=f(t),s=parseInt(n.width)-parseInt(n.paddingLeft)-parseInt(n.paddingRight)-parseInt(n.borderLeftWidth)-parseInt(n.borderRightWidth),o=Pt(t,0,e),r=Pt(t,1,e),a=o&&f(o),l=r&&f(r),c=a&&parseInt(a.marginLeft)+parseInt(a.marginRight)+$(o).width,h=l&&parseInt(l.marginLeft)+parseInt(l.marginRight)+$(r).width;if(n.display==="flex")return n.flexDirection==="column"||n.flexDirection==="column-reverse"?"vertical":"horizontal";if(n.display==="grid")return n.gridTemplateColumns.split(" ").length<=1?"vertical":"horizontal";if(o&&a.float&&a.float!=="none"){var u=a.float==="left"?"left":"right";return r&&(l.clear==="both"||l.clear===u)?"vertical":"horizontal"}return o&&(a.display==="block"||a.display==="flex"||a.display==="table"||a.display==="grid"||c>=s&&n[fs]==="none"||r&&n[fs]==="none"&&c+h>s)?"vertical":"horizontal"},ar=function(t,e,n){var s=n?t.left:t.top,o=n?t.right:t.bottom,r=n?t.width:t.height,a=n?e.left:e.top,l=n?e.right:e.bottom,c=n?e.width:e.height;return s===a||o===l||s+r/2===a+c/2},lr=function(t,e){var n;return He.some(function(s){var o=s[R].options.emptyInsertThreshold;if(!(!o||Dn(s))){var r=$(s),a=t>=r.left-o&&t<=r.right+o,l=e>=r.top-o&&e<=r.bottom+o;if(a&&l)return n=s}}),n},Ls=function(t){function e(o,r){return function(a,l,c,h){var u=a.options.group.name&&l.options.group.name&&a.options.group.name===l.options.group.name;if(o==null&&(r||u))return!0;if(o==null||o===!1)return!1;if(r&&o==="clone")return o;if(typeof o=="function")return e(o(a,l,c,h),r)(a,l,c,h);var m=(r?a:l).options.group.name;return o===!0||typeof o=="string"&&o===m||o.join&&o.indexOf(m)>-1}}var n={},s=t.group;(!s||Be(s)!="object")&&(s={name:s}),n.name=s.name,n.checkPull=e(s.pull,!0),n.checkPut=e(s.put),n.revertClone=s.revertClone,t.group=n},$s=function(){!Ss&&v&&f(v,"display","none")},Ts=function(){!Ss&&v&&f(v,"display","")};Ve&&!vs&&document.addEventListener("click",function(i){if(Re)return i.preventDefault(),i.stopPropagation&&i.stopPropagation(),i.stopImmediatePropagation&&i.stopImmediatePropagation(),Re=!1,!1},!0);var bt=function(t){if(p){t=t.touches?t.touches[0]:t;var e=lr(t.clientX,t.clientY);if(e){var n={};for(var s in t)t.hasOwnProperty(s)&&(n[s]=t[s]);n.target=n.rootEl=e,n.preventDefault=void 0,n.stopPropagation=void 0,e[R]._onDragOver(n)}}},cr=function(t){p&&p.parentNode[R]._isOutsideThisEl(t.target)};function g(i,t){if(!(i&&i.nodeType&&i.nodeType===1))throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(i));this.el=i,this.options=t=Q({},t),i[R]=this;var e={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(i.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return ks(i,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(r,a){r.setData("Text",a.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:"data-id",delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:"sortable-fallback",fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:g.supportPointer!==!1&&"PointerEvent"in window&&!se,emptyInsertThreshold:5};de.initializePlugins(this,i,e);for(var n in e)!(n in t)&&(t[n]=e[n]);Ls(t);for(var s in this)s.charAt(0)==="_"&&typeof this[s]=="function"&&(this[s]=this[s].bind(this));this.nativeDraggable=t.forceFallback?!1:rr,this.nativeDraggable&&(this.options.touchStartThreshold=1),t.supportPointer?E(i,"pointerdown",this._onTapStart):(E(i,"mousedown",this._onTapStart),E(i,"touchstart",this._onTapStart)),this.nativeDraggable&&(E(i,"dragover",this),E(i,"dragenter",this)),He.push(this.el),t.store&&t.store.get&&this.sort(t.store.get(this)||[]),Q(this,ir())}g.prototype={constructor:g,_isOutsideThisEl:function(t){!this.el.contains(t)&&t!==this.el&&(At=null)},_getDirection:function(t,e){return typeof this.options.direction=="function"?this.options.direction.call(this,t,e,p):this.options.direction},_onTapStart:function(t){if(t.cancelable){var e=this,n=this.el,s=this.options,o=s.preventOnFilter,r=t.type,a=t.touches&&t.touches[0]||t.pointerType&&t.pointerType==="touch"&&t,l=(a||t).target,c=t.target.shadowRoot&&(t.path&&t.path[0]||t.composedPath&&t.composedPath()[0])||l,h=s.filter;if(wr(n),!p&&!(/mousedown|pointerdown/.test(r)&&t.button!==0||s.disabled)&&!c.isContentEditable&&!(!this.nativeDraggable&&se&&l&&l.tagName.toUpperCase()==="SELECT")&&(l=Y(l,s.draggable,n,!1),!(l&&l.animated)&&Pe!==l)){if(Bt=O(l),re=O(l,s.draggable),typeof h=="function"){if(h.call(this,t,l,this)){H({sortable:e,rootEl:c,name:"filter",targetEl:l,toEl:n,fromEl:n}),V("filter",e,{evt:t}),o&&t.cancelable&&t.preventDefault();return}}else if(h&&(h=h.split(",").some(function(u){if(u=Y(c,u.trim(),n,!1),u)return H({sortable:e,rootEl:u,name:"filter",targetEl:l,fromEl:n,toEl:n}),V("filter",e,{evt:t}),!0}),h)){o&&t.cancelable&&t.preventDefault();return}s.handle&&!Y(c,s.handle,n,!1)||this._prepareDragStart(t,a,l)}}},_prepareDragStart:function(t,e,n){var s=this,o=s.el,r=s.options,a=o.ownerDocument,l;if(n&&!p&&n.parentNode===o){var c=$(n);if(T=o,p=n,I=p.parentNode,yt=p.nextSibling,Pe=n,$e=r.group,g.dragged=p,vt={target:p,clientX:(e||t).clientX,clientY:(e||t).clientY},us=vt.clientX-c.left,ps=vt.clientY-c.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,p.style["will-change"]="all",l=function(){if(V("delayEnded",s,{evt:t}),g.eventCanceled){s._onDrop();return}s._disableDelayedDragEvents(),!as&&s.nativeDraggable&&(p.draggable=!0),s._triggerDragStart(t,e),H({sortable:s,name:"choose",originalEvent:t}),P(p,r.chosenClass,!0)},r.ignore.split(",").forEach(function(h){ys(p,h.trim(),yn)}),E(a,"dragover",bt),E(a,"mousemove",bt),E(a,"touchmove",bt),E(a,"mouseup",s._onDrop),E(a,"touchend",s._onDrop),E(a,"touchcancel",s._onDrop),as&&this.nativeDraggable&&(this.options.touchStartThreshold=4,p.draggable=!0),V("delayStart",this,{evt:t}),r.delay&&(!r.delayOnTouchOnly||e)&&(!this.nativeDraggable||!(ce||ct))){if(g.eventCanceled){this._onDrop();return}E(a,"mouseup",s._disableDelayedDrag),E(a,"touchend",s._disableDelayedDrag),E(a,"touchcancel",s._disableDelayedDrag),E(a,"mousemove",s._delayedDragTouchMoveHandler),E(a,"touchmove",s._delayedDragTouchMoveHandler),r.supportPointer&&E(a,"pointermove",s._delayedDragTouchMoveHandler),s._dragStartTimer=setTimeout(l,r.delay)}else l()}},_delayedDragTouchMoveHandler:function(t){var e=t.touches?t.touches[0]:t;Math.max(Math.abs(e.clientX-this._lastX),Math.abs(e.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){p&&yn(p),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var t=this.el.ownerDocument;y(t,"mouseup",this._disableDelayedDrag),y(t,"touchend",this._disableDelayedDrag),y(t,"touchcancel",this._disableDelayedDrag),y(t,"mousemove",this._delayedDragTouchMoveHandler),y(t,"touchmove",this._delayedDragTouchMoveHandler),y(t,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(t,e){e=e||t.pointerType=="touch"&&t,!this.nativeDraggable||e?this.options.supportPointer?E(document,"pointermove",this._onTouchMove):e?E(document,"touchmove",this._onTouchMove):E(document,"mousemove",this._onTouchMove):(E(p,"dragend",this),E(T,"dragstart",this._onDragStart));try{document.selection?_e(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},_dragStarted:function(t,e){if(Mt=!1,T&&p){V("dragStarted",this,{evt:e}),this.nativeDraggable&&E(document,"dragover",cr);var n=this.options;!t&&P(p,n.dragClass,!1),P(p,n.ghostClass,!0),g.active=this,t&&this._appendGhost(),H({sortable:this,name:"start",originalEvent:e})}else this._nulling()},_emulateDragOver:function(){if(J){this._lastX=J.clientX,this._lastY=J.clientY,$s();for(var t=document.elementFromPoint(J.clientX,J.clientY),e=t;t&&t.shadowRoot&&(t=t.shadowRoot.elementFromPoint(J.clientX,J.clientY),t!==e);)e=t;if(p.parentNode[R]._isOutsideThisEl(t),e)do{if(e[R]){var n=void 0;if(n=e[R]._onDragOver({clientX:J.clientX,clientY:J.clientY,target:t,rootEl:e}),n&&!this.options.dragoverBubble)break}t=e}while(e=e.parentNode);Ts()}},_onTouchMove:function(t){if(vt){var e=this.options,n=e.fallbackTolerance,s=e.fallbackOffset,o=t.touches?t.touches[0]:t,r=v&&Ct(v,!0),a=v&&r&&r.a,l=v&&r&&r.d,c=De&&F&&ds(F),h=(o.clientX-vt.clientX+s.x)/(a||1)+(c?c[0]-bn[0]:0)/(a||1),u=(o.clientY-vt.clientY+s.y)/(l||1)+(c?c[1]-bn[1]:0)/(l||1);if(!g.active&&!Mt){if(n&&Math.max(Math.abs(o.clientX-this._lastX),Math.abs(o.clientY-this._lastY))=0&&(H({rootEl:I,name:"add",toEl:I,fromEl:T,originalEvent:t}),H({sortable:this,name:"remove",toEl:I,originalEvent:t}),H({rootEl:I,name:"sort",toEl:I,fromEl:T,originalEvent:t}),H({sortable:this,name:"sort",toEl:I,originalEvent:t})),N&&N.save()):X!==Bt&&X>=0&&(H({sortable:this,name:"update",toEl:I,originalEvent:t}),H({sortable:this,name:"sort",toEl:I,originalEvent:t})),g.active&&((X==null||X===-1)&&(X=Bt,pt=re),H({sortable:this,name:"end",toEl:I,originalEvent:t}),this.save()))),this._nulling()},_nulling:function(){V("nulling",this),T=p=I=v=yt=D=Pe=ft=vt=J=ee=X=pt=Bt=re=At=ae=N=$e=g.dragged=g.ghost=g.clone=g.active=null,qe.forEach(function(t){t.checked=!0}),qe.length=wn=vn=0},handleEvent:function(t){switch(t.type){case"drop":case"dragend":this._onDrop(t);break;case"dragenter":case"dragover":p&&(this._onDragOver(t),dr(t));break;case"selectstart":t.preventDefault();break}},toArray:function(){for(var t=[],e,n=this.el.children,s=0,o=n.length,r=this.options;ss.right+o||i.clientY>n.bottom&&i.clientX>n.left:i.clientY>s.bottom+o||i.clientX>n.right&&i.clientY>n.top}function fr(i,t,e,n,s,o,r,a){var l=n?i.clientY:i.clientX,c=n?e.height:e.width,h=n?e.top:e.left,u=n?e.bottom:e.right,m=!1;if(!r){if(a&&Oeh+c*o/2:lu-Oe)return-ae}else if(l>h+c*(1-s)/2&&lu-c*o/2)?l>h+c/2?1:-1:0}function mr(i){return O(p)1&&(w.forEach(function(a){o.addAnimationState({target:a,rect:z?$(a):r}),mn(a),a.fromRect=r,n.removeAnimationState(a)}),z=!1,br(!this.options.removeCloneOnHide,s))},dragOverCompleted:function(e){var n=e.sortable,s=e.isOwner,o=e.insertion,r=e.activeSortable,a=e.parentEl,l=e.putSortable,c=this.options;if(o){if(s&&r._hideClone(),Zt=!1,c.animation&&w.length>1&&(z||!s&&!r.options.sort&&!l)){var h=$(L,!1,!0,!0);w.forEach(function(m){m!==L&&(hs(m,h),a.appendChild(m))}),z=!0}if(!s)if(z||Me(),w.length>1){var u=Ie;r._showClone(n),r.options.animation&&!Ie&&u&&K.forEach(function(m){r.addAnimationState({target:m,rect:Qt}),m.fromRect=Qt,m.thisAnimationDuration=null})}else r._showClone(n)}},dragOverAnimationCapture:function(e){var n=e.dragRect,s=e.isOwner,o=e.activeSortable;if(w.forEach(function(a){a.thisAnimationDuration=null}),o.options.animation&&!s&&o.multiDrag.isMultiDrag){Qt=Q({},n);var r=Ct(L,!0);Qt.top-=r.f,Qt.left-=r.e}},dragOverAnimationComplete:function(){z&&(z=!1,Me())},drop:function(e){var n=e.originalEvent,s=e.rootEl,o=e.parentEl,r=e.sortable,a=e.dispatchSortableEvent,l=e.oldIndex,c=e.putSortable,h=c||this.sortable;if(n){var u=this.options,m=o.children;if(!It)if(u.multiDragKey&&!this.multiDragKeyDown&&this._deselectMultiDrag(),P(L,u.selectedClass,!~w.indexOf(L)),~w.indexOf(L))w.splice(w.indexOf(L),1),Jt=null,te({sortable:r,rootEl:s,name:"deselect",targetEl:L,originalEvent:n});else{if(w.push(L),te({sortable:r,rootEl:s,name:"select",targetEl:L,originalEvent:n}),n.shiftKey&&Jt&&r.el.contains(Jt)){var C=O(Jt),b=O(L);if(~C&&~b&&C!==b){var S,M;for(b>C?(M=C,S=b):(M=b,S=C+1);M1){var G=$(L),_=O(L,":not(."+this.options.selectedClass+")");if(!Zt&&u.animation&&(L.thisAnimationDuration=null),h.captureAnimationState(),!Zt&&(u.animation&&(L.fromRect=G,w.forEach(function(k){if(k.thisAnimationDuration=null,k!==L){var tt=z?$(k):G;k.fromRect=tt,h.addAnimationState({target:k,rect:tt})}})),Me(),w.forEach(function(k){m[_]?o.insertBefore(k,m[_]):o.appendChild(k),_++}),l===O(L))){var q=!1;w.forEach(function(k){if(k.sortableIndex!==O(k)){q=!0;return}}),q&&(a("update"),a("sort"))}w.forEach(function(k){mn(k)}),h.animateAll()}Z=h}(s===o||c&&c.lastPutMode!=="clone")&&K.forEach(function(k){k.parentNode&&k.parentNode.removeChild(k)})}},nullingGlobal:function(){this.isMultiDrag=It=!1,K.length=0},destroyGlobal:function(){this._deselectMultiDrag(),y(document,"pointerup",this._deselectMultiDrag),y(document,"mouseup",this._deselectMultiDrag),y(document,"touchend",this._deselectMultiDrag),y(document,"keydown",this._checkKeyDown),y(document,"keyup",this._checkKeyUp)},_deselectMultiDrag:function(e){if(!(typeof It<"u"&&It)&&Z===this.sortable&&!(e&&Y(e.target,this.options.draggable,this.sortable.el,!1))&&!(e&&e.button!==0))for(;w.length;){var n=w[0];P(n,this.options.selectedClass,!1),w.shift(),te({sortable:this.sortable,rootEl:this.sortable.el,name:"deselect",targetEl:n,originalEvent:e})}},_checkKeyDown:function(e){e.key===this.options.multiDragKey&&(this.multiDragKeyDown=!0)},_checkKeyUp:function(e){e.key===this.options.multiDragKey&&(this.multiDragKeyDown=!1)}},Q(i,{pluginName:"multiDrag",utils:{select:function(e){var n=e.parentNode[R];!n||!n.options.multiDrag||~w.indexOf(e)||(Z&&Z!==n&&(Z.multiDrag._deselectMultiDrag(),Z=n),P(e,n.options.selectedClass,!0),w.push(e))},deselect:function(e){var n=e.parentNode[R],s=w.indexOf(e);!n||!n.options.multiDrag||!~s||(P(e,n.options.selectedClass,!1),w.splice(s,1))}},eventProperties:function(){var e=this,n=[],s=[];return w.forEach(function(o){n.push({multiDragElement:o,index:o.sortableIndex});var r;z&&o!==L?r=-1:z?r=O(o,":not(."+e.options.selectedClass+")"):r=O(o),s.push({multiDragElement:o,index:r})}),{items:Wo(w),clones:[].concat(K),oldIndicies:n,newIndicies:s}},optionListeners:{multiDragKey:function(e){return e=e.toLowerCase(),e==="ctrl"?e="Control":e.length>1&&(e=e.charAt(0).toUpperCase()+e.substr(1)),e}}})}function br(i,t){w.forEach(function(e,n){var s=t.children[e.sortableIndex+(i?Number(n):0)];s?t.insertBefore(e,s):t.appendChild(e)})}function gs(i,t){K.forEach(function(e,n){var s=t.children[e.sortableIndex+(i?Number(n):0)];s?t.insertBefore(e,s):t.appendChild(e)})}function Me(){w.forEach(function(i){i!==L&&i.parentNode&&i.parentNode.removeChild(i)})}g.mount(new vr);g.mount(Mn,In);var Et=g;var Is={name(i,t){let e=i.getAttribute("data-name").trim().toLowerCase(),n=t.getAttribute("data-name").trim().toLowerCase();return e.localeCompare(n)},created(i,t){let e=Number(i.getAttribute("data-created"));return Number(t.getAttribute("data-created"))-e},updated(i,t){let e=Number(i.getAttribute("data-updated"));return Number(t.getAttribute("data-updated"))-e},chaptersFirst(i,t){let e=i.getAttribute("data-type"),n=t.getAttribute("data-type");return e===n?0:e==="chapter"?-1:1},chaptersLast(i,t){let e=i.getAttribute("data-type"),n=t.getAttribute("data-type");return e===n?0:e==="chapter"?1:-1}},Ms={up:{active(i,t){return!(i.previousElementSibling===null&&!t)},run(i,t){(i.previousElementSibling||t).insertAdjacentElement("beforebegin",i)}},down:{active(i,t){return!(i.nextElementSibling===null&&!t)},run(i,t){(i.nextElementSibling||t).insertAdjacentElement("afterend",i)}},next_book:{active(i,t,e){return e.nextElementSibling!==null},run(i,t,e){e.nextElementSibling.querySelector("ul").prepend(i)}},prev_book:{active(i,t,e){return e.previousElementSibling!==null},run(i,t,e){e.previousElementSibling.querySelector("ul").appendChild(i)}},next_chapter:{active(i,t){return i.dataset.type==="page"&&this.getNextChapter(i,t)},run(i,t){this.getNextChapter(i,t).querySelector("ul").prepend(i)},getNextChapter(i,t){let e=t||i,n=Array.from(e.parentElement.children),s=n.indexOf(e);return n.slice(s+1).find(o=>o.dataset.type==="chapter")}},prev_chapter:{active(i,t){return i.dataset.type==="page"&&this.getPrevChapter(i,t)},run(i,t){this.getPrevChapter(i,t).querySelector("ul").append(i)},getPrevChapter(i,t){let e=t||i,n=Array.from(e.parentElement.children),s=n.indexOf(e);return n.slice(0,s).reverse().find(o=>o.dataset.type==="chapter")}},book_end:{active(i,t){return t||t===null&&i.nextElementSibling},run(i,t,e){e.querySelector("ul").append(i)}},book_start:{active(i,t){return t||t===null&&i.previousElementSibling},run(i,t,e){e.querySelector("ul").prepend(i)}},before_chapter:{active(i,t){return t},run(i,t){t.insertAdjacentElement("beforebegin",i)}},after_chapter:{active(i,t){return t},run(i,t){t.insertAdjacentElement("afterend",i)}}},ze=class extends d{setup(){this.container=this.$el,this.sortContainer=this.$refs.sortContainer,this.input=this.$refs.input,Et.mount(new As);let t=this.container.querySelector(".sort-box");this.setupBookSortable(t),this.setupSortPresets(),this.setupMoveActions(),window.$events.listen("entity-select-change",this.bookSelect.bind(this))}setupMoveActions(){this.container.addEventListener("click",t=>{if(t.target.matches("[data-move]")){let e=t.target.getAttribute("data-move"),n=t.target.closest("[data-id]");this.runSortAction(n,e)}}),this.updateMoveActionStateForAll()}setupSortPresets(){let t="",e=!1,n=["name","created","updated"];this.sortContainer.addEventListener("click",s=>{let o=s.target.closest(".sort-box-options [data-sort]");if(!o)return;s.preventDefault();let r=o.closest(".sort-box").querySelectorAll("ul"),a=o.getAttribute("data-sort");e=t===a?!e:!1;let l=Is[a];e&&n.includes(a)&&(l=function(h,u){return 0-Is[a](h,u)});for(let c of r)Array.from(c.children).filter(u=>u.matches("li")).sort(l).forEach(u=>{c.appendChild(u)});t=a,this.updateMapInput()})}bookSelect(t){if(this.container.querySelector(`[data-type="book"][data-id="${t.id}"]`)!==null)return;let n=`${t.link}/sort-item`;window.$http.get(n).then(s=>{let o=nt(s.data);this.sortContainer.append(o),this.setupBookSortable(o),this.updateMoveActionStateForAll(),o.querySelector("summary").focus()})}setupBookSortable(t){let e=Array.from(t.querySelectorAll(".sort-list, .sortable-page-sublist")),n={name:"book",pull:["book","chapter"],put:["book","chapter"]},s={name:"chapter",pull:["book","chapter"],put(o,r,a){return a.getAttribute("data-type")==="page"}};for(let o of e)Et.create(o,{group:o.classList.contains("sort-list")?n:s,animation:150,fallbackOnBody:!0,swapThreshold:.65,onSort:()=>{this.ensureNoNestedChapters(),this.updateMapInput(),this.updateMoveActionStateForAll()},dragClass:"bg-white",ghostClass:"primary-background-light",multiDrag:!0,multiDragKey:"Control",selectedClass:"sortable-selected"})}ensureNoNestedChapters(){let t=this.container.querySelectorAll('[data-type="chapter"] [data-type="chapter"]');for(let e of t)e.parentElement.closest('[data-type="chapter"]').insertAdjacentElement("afterend",e)}updateMapInput(){let t=this.buildEntityMap();this.input.value=JSON.stringify(t)}buildEntityMap(){let t=[],e=this.container.querySelectorAll(".sort-list");for(let n of e){let s=n.closest('[data-type="book"]').getAttribute("data-id"),o=Array.from(n.children).filter(r=>r.matches('[data-type="page"], [data-type="chapter"]'));for(let r=0;r{for(let r of s)i.style[r]=null;i.style.transition=null,i.removeEventListener("transitionend",o),je.delete(i),n&&n()};setTimeout(()=>{i.style.transition=`all ease-in-out ${e}ms`;for(let r of s)i.style[r]=t[r][1];i.addEventListener("transitionend",o),je.set(i,o)},15)}function ue(i){je.has(i)&&je.get(i)()}function Bs(i,t=400,e=null){ue(i),i.style.display="block",he(i,{opacity:["0","1"]},t,()=>{e&&e()})}function Ps(i,t=400,e=null){ue(i),he(i,{opacity:["1","0"]},t,()=>{i.style.display="none",e&&e()})}function Ot(i,t=400){ue(i);let e=i.getBoundingClientRect().height,n=getComputedStyle(i),s=n.getPropertyValue("padding-top"),o=n.getPropertyValue("padding-bottom"),r={maxHeight:[`${e}px`,"0px"],overflow:["hidden","hidden"],paddingTop:[s,"0px"],paddingBottom:[o,"0px"]};he(i,r,t,()=>{i.style.display="none"})}function _t(i,t=400){ue(i),i.style.display="block";let e=i.getBoundingClientRect().height,n=getComputedStyle(i),s=n.getPropertyValue("padding-top"),o=n.getPropertyValue("padding-bottom"),r={maxHeight:["0px",`${e}px`],overflow:["hidden","hidden"],paddingTop:["0px",s],paddingBottom:["0px",o]};he(i,r,t)}function Os(i,t=400){let e=i.getBoundingClientRect().height,n=getComputedStyle(i),s=n.getPropertyValue("padding-top"),o=n.getPropertyValue("padding-bottom");return()=>{ue(i);let r=i.getBoundingClientRect().height,a=getComputedStyle(i),l=a.getPropertyValue("padding-top"),c=a.getPropertyValue("padding-bottom"),h={height:[`${e}px`,`${r}px`],overflow:["hidden","hidden"],paddingTop:[s,l],paddingBottom:[o,c]};he(i,h,t)}}var We=class extends d{setup(){this.list=this.$refs.list,this.toggle=this.$refs.toggle,this.isOpen=this.toggle.classList.contains("open"),this.toggle.addEventListener("click",this.click.bind(this))}open(){this.toggle.classList.add("open"),this.toggle.setAttribute("aria-expanded","true"),_t(this.list,180),this.isOpen=!0}close(){this.toggle.classList.remove("open"),this.toggle.setAttribute("aria-expanded","false"),Ot(this.list,180),this.isOpen=!1}click(t){t.preventDefault(),this.isOpen?this.close():this.open()}};var Ke=class extends d{constructor(){super(...arguments);U(this,"editor",null);U(this,"saveCallback",null);U(this,"cancelCallback",null);U(this,"history",{});U(this,"historyKey","code_history")}setup(){this.container=this.$refs.container,this.popup=this.$el,this.editorInput=this.$refs.editor,this.languageButtons=this.$manyRefs.languageButton,this.languageOptionsContainer=this.$refs.languageOptionsContainer,this.saveButton=this.$refs.saveButton,this.languageInput=this.$refs.languageInput,this.historyDropDown=this.$refs.historyDropDown,this.historyList=this.$refs.historyList,this.favourites=new Set(this.$opts.favourites.split(",")),this.setupListeners(),this.setupFavourites()}setupListeners(){this.container.addEventListener("keydown",e=>{e.ctrlKey&&e.key==="Enter"&&this.save()}),x(this.languageButtons,e=>{let n=e.target.dataset.lang;this.languageInput.value=n,this.languageInputChange(n)}),Lt(this.languageInput,()=>this.save()),this.languageInput.addEventListener("input",()=>this.languageInputChange(this.languageInput.value)),x(this.saveButton,()=>this.save()),A(this.historyList,"button","click",(e,n)=>{e.preventDefault();let s=n.dataset.time;this.editor&&this.editor.setContent(this.history[s])})}setupFavourites(){for(let e of this.languageButtons)this.setupFavouritesForButton(e);this.sortLanguageList()}setupFavouritesForButton(e){let n=e.dataset.lang,s=this.favourites.has(n);e.setAttribute("data-favourite",s?"true":"false"),A(e.parentElement,".lang-option-favorite-toggle","click",()=>{s=!s,s?this.favourites.add(n):this.favourites.delete(n),e.setAttribute("data-favourite",s?"true":"false"),window.$http.patch("/preferences/update-code-language-favourite",{language:n,active:s}),this.sortLanguageList(),s&&e.scrollIntoView({block:"center",behavior:"smooth"})})}sortLanguageList(){let e=this.languageButtons.sort((n,s)=>{let o=n.dataset.favourite==="true",r=s.dataset.favourite==="true";return o&&!r?-1:r&&!o||n.dataset.lang>s.dataset.lang?1:-1}).map(n=>n.parentElement);for(let n of e)this.languageOptionsContainer.append(n)}save(){this.saveCallback&&this.saveCallback(this.editor.getContent(),this.languageInput.value),this.hide()}async open(e,n,s,o,r){this.languageInput.value=n,this.saveCallback=o,this.cancelCallback=r,await this.show(),this.languageInputChange(n),this.editor.setContent(e),this.setDirection(s)}async show(){let e=await window.importVersioned("code");this.editor||(this.editor=e.popupEditor(this.editorInput,this.languageInput.value)),this.loadHistory(),this.getPopup().show(()=>{this.editor.focus()},()=>{this.addHistory(),this.cancelCallback&&this.cancelCallback()})}setDirection(e){let n=this.editorInput.parentElement;e?n.setAttribute("dir",e):n.removeAttribute("dir")}hide(){this.getPopup().hide(),this.addHistory()}getPopup(){return window.$components.firstOnElement(this.popup,"popup")}async updateEditorMode(e){this.editor.setMode(e,this.editor.getContent())}languageInputChange(e){this.updateEditorMode(e);let n=e.toLowerCase();for(let s of this.languageButtons){let o=s.dataset.lang.toLowerCase().trim(),r=n===o;s.classList.toggle("active",r),r&&s.scrollIntoView({block:"center",behavior:"smooth"})}}loadHistory(){this.history=JSON.parse(window.sessionStorage.getItem(this.historyKey)||"{}");let e=Object.keys(this.history).reverse();this.historyDropDown.classList.toggle("hidden",e.length===0),this.historyList.innerHTML=e.map(n=>{let s=new Date(parseInt(n,10)).toLocaleTimeString();return``}).join("")}addHistory(){if(!this.editor)return;let e=this.editor.getContent();if(!e)return;let n=Object.keys(this.history).pop();if(this.history[n]===e)return;this.history[String(Date.now())]=e;let s=JSON.stringify(this.history);window.sessionStorage.setItem(this.historyKey,s)}};var Xe=class extends d{setup(){let t=this.$el;t.querySelectorAll("pre").length>0&&window.importVersioned("code").then(n=>{n.highlightWithin(t)})}};var Ge=class extends d{async setup(){let{mode:t}=this.$opts;(await window.importVersioned("code")).inlineEditor(this.$el,t)}};var Ye=class extends d{setup(){this.container=this.$el,this.trigger=this.$refs.trigger,this.content=this.$refs.content,this.trigger&&(this.trigger.addEventListener("click",this.toggle.bind(this)),this.openIfContainsError())}open(){this.container.classList.add("open"),this.trigger.setAttribute("aria-expanded","true"),_t(this.content,300)}close(){this.container.classList.remove("open"),this.trigger.setAttribute("aria-expanded","false"),Ot(this.content,300)}toggle(){this.container.classList.contains("open")?this.close():this.open()}openIfContainsError(){this.content.querySelector(".text-neg.text-small")&&this.open()}};var Je=class extends d{setup(){this.container=this.$el,this.confirmButton=this.$refs.confirm,this.res=null,x(this.confirmButton,()=>{this.sendResult(!0),this.getPopup().hide()})}show(){return this.getPopup().show(null,()=>{this.sendResult(!1)}),new Promise(t=>{this.res=t})}getPopup(){return window.$components.firstOnElement(this.container,"popup")}sendResult(t){this.res&&(this.res(t),this.res=null)}};var Ze=class extends d{setup(){this.container=this.$el,this.checkbox=this.container.querySelector("input[type=checkbox]"),this.display=this.container.querySelector('[role="checkbox"]'),this.checkbox.addEventListener("change",this.stateChange.bind(this)),this.container.addEventListener("keydown",this.onKeyDown.bind(this))}onKeyDown(t){(t.key===" "||t.key==="Enter")&&(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)}};var Qe=class extends d{setup(){this.container=this.$el,this.dealtWith=!1,this.container.addEventListener("toggle",this.onToggle.bind(this))}onToggle(){this.dealtWith||(this.container.querySelector("pre")&&window.importVersioned("code").then(t=>{t.highlightWithin(this.container)}),this.dealtWith=!0)}};var ti=class extends d{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.hide=this.hide.bind(this),this.setupListeners()}show(t=null){this.hideAll(),this.menu.style.display="block",this.menu.classList.add("anim","menuIn"),this.toggle.setAttribute("aria-expanded","true");let e=this.menu.getBoundingClientRect(),n=0,s=this.toggle.getBoundingClientRect().height,o=e.bottom>window.innerHeight,r=this.container.getBoundingClientRect();if(this.moveMenu&&(this.body.appendChild(this.menu),this.menu.style.position="fixed",this.menu.style.width=`${e.width}px`,this.menu.style.left=`${e.left}px`,o?n=window.innerHeight-e.top-s/2:n=e.top),o){this.menu.style.top="initial",this.menu.style.bottom=`${n}px`;let c=window.innerHeight-40-(window.innerHeight-r.bottom);this.menu.style.maxHeight=`${Math.floor(c)}px`}else{this.menu.style.top=`${n}px`,this.menu.style.bottom="initial";let c=window.innerHeight-40-r.top;this.menu.style.maxHeight=`${Math.floor(c)}px`}this.menu.addEventListener("mouseleave",this.hide),window.addEventListener("click",c=>{this.menu.contains(c.target)||this.hide()});let a=this.menu.querySelector("input");a!==null&&a.focus(),this.showing=!0;let l=new Event("show");this.container.dispatchEvent(l),t&&t.stopPropagation()}hideAll(){for(let t of window.$components.get("dropdown"))t.hide()}hide(){this.menu.style.display="none",this.menu.classList.remove("anim","menuIn"),this.toggle.setAttribute("aria-expanded","false"),this.menu.style.top="",this.menu.style.bottom="",this.menu.style.maxHeight="",this.moveMenu&&(this.menu.style.position="",this.menu.style[this.direction]="",this.menu.style.width="",this.menu.style.left="",this.container.appendChild(this.menu)),this.showing=!1}setupListeners(){let t=new ut(this.container,e=>{this.hide(),this.toggle.focus(),this.bubbleEscapes||e.stopPropagation()},e=>{e.target.nodeName==="INPUT"&&(e.preventDefault(),e.stopPropagation()),this.hide()});this.moveMenu&&t.shareHandlingToEl(this.menu),this.container.addEventListener("click",e=>{Array.from(this.menu.querySelectorAll("a")).includes(e.target)&&this.hide()}),x(this.toggle,e=>{e.stopPropagation(),e.preventDefault(),this.show(e),e instanceof KeyboardEvent&&t.focusNext()})}};var ei=class extends d{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=Tt(this.runAjaxSearch,300,!1)}onShow(){this.loadList()}onSearch(){let t=this.searchInput.value.toLowerCase().trim();this.localSearchSelector?this.runLocalSearch(t):(this.toggleLoading(!0),this.listContainerElem.innerHTML="",this.runAjaxSearch(t))}runAjaxSearch(t){this.loadList(t)}runLocalSearch(t){let e=this.listContainerElem.querySelectorAll(this.localSearchSelector);for(let n of e){let s=!t||n.textContent.toLowerCase().includes(t);n.style.display=s?"flex":"none",n.classList.toggle("hidden",!s)}}async loadList(t=""){this.listContainerElem.innerHTML="",this.toggleLoading(!0);try{let e=await window.$http.get(this.getAjaxUrl(t)),n=Os(this.listContainerElem,80);this.listContainerElem.innerHTML=e.data,n()}catch(e){console.error(e)}this.toggleLoading(!1),this.localSearchSelector&&this.onSearch()}getAjaxUrl(t=null){if(!t)return this.url;let e=this.url.includes("?")?"&":"?";return`${this.url}${e}search=${encodeURIComponent(t)}`}toggleLoading(t=!1){this.loadingElem.style.display=t?"block":"none"}};var Nt=class{constructor(t){this.data=t}hasItems(){return!!this.data&&!!this.data.types&&this.data.types.length>0}containsTabularData(){let t=this.data.getData("text/rtf");return t&&t.includes("\\trowd")}getImages(){let{types:t}=this.data,e=[];for(let s of t)if(s.includes("image")){let o=this.data.getData(s);e.push(o.getAsFile())}let n=this.getFiles().filter(s=>s.type.includes("image"));return e.push(...n),e}getFiles(){let{files:t}=this.data;return[...t]}};async function Bn(i){if(window.isSecureContext&&navigator.clipboard){await navigator.clipboard.writeText(i);return}let t=document.createElement("textarea");t.style="position: absolute; left: -1000px; top: -1000px;",t.value=i,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t)}var ii=class extends d{setup(){this.container=this.$el,this.statusArea=this.$refs.statusArea,this.dropTarget=this.$refs.dropTarget,this.selectButtons=this.$manyRefs.selectButton||[],this.isActive=!0,this.url=this.$opts.url,this.method=(this.$opts.method||"post").toUpperCase(),this.successMessage=this.$opts.successMessage,this.errorMessage=this.$opts.errorMessage,this.uploadLimitMb=Number(this.$opts.uploadLimit),this.uploadLimitMessage=this.$opts.uploadLimitMessage,this.zoneText=this.$opts.zoneText,this.fileAcceptTypes=this.$opts.fileAccept,this.allowMultiple=this.$opts.allowMultiple==="true",this.setupListeners()}toggleActive(t){this.isActive=t}setupListeners(){x(this.selectButtons,this.manualSelectHandler.bind(this)),this.setupDropTargetHandlers()}setupDropTargetHandlers(){let t=0,e=()=>{this.hideOverlay(),t=0};this.dropTarget.addEventListener("dragenter",n=>{n.preventDefault(),t+=1,t===1&&this.isActive&&this.showOverlay()}),this.dropTarget.addEventListener("dragover",n=>{n.preventDefault()}),this.dropTarget.addEventListener("dragend",e),this.dropTarget.addEventListener("dragleave",()=>{t-=1,t===0&&e()}),this.dropTarget.addEventListener("drop",n=>{if(n.preventDefault(),e(),!this.isActive)return;let o=new Nt(n.dataTransfer).getFiles();for(let r of o)this.createUploadFromFile(r)})}manualSelectHandler(){let t=it("input",{type:"file",style:"left: -400px; visibility: hidden; position: fixed;",accept:this.fileAcceptTypes,multiple:this.allowMultiple?"":null});this.container.append(t),t.click(),t.addEventListener("change",()=>{for(let e of t.files)this.createUploadFromFile(e);t.remove()})}showOverlay(){if(!this.dropTarget.querySelector(".dropzone-overlay")){let e=it("div",{class:"dropzone-overlay"},[this.zoneText]);this.dropTarget.append(e)}}hideOverlay(){let t=this.dropTarget.querySelector(".dropzone-overlay");t&&t.remove()}createUploadFromFile(t){let{dom:e,status:n,progress:s,dismiss:o}=this.createDomForFile(t);this.statusArea.append(e);let r=this,a={file:t,dom:e,updateProgress(l){s.textContent=`${l}%`,s.style.width=`${l}%`},markError(l){n.setAttribute("data-status","error"),n.textContent=l,Xt(e),this.updateProgress(100)},markSuccess(l){n.setAttribute("data-status","success"),n.textContent=l,Xt(e),setTimeout(o,2400),r.$emit("upload-success",{name:t.name})}};return t.size>this.uploadLimitMb*1e6?(a.markError(this.uploadLimitMessage),a):(this.startXhrForUpload(a),a)}startXhrForUpload(t){let e=new FormData;e.append("file",t.file,t.file.name),this.method!=="POST"&&e.append("_method",this.method);let n=this,s=window.$http.createXMLHttpRequest("POST",this.url,{error(){t.markError(n.errorMessage)},readystatechange(){this.readyState===XMLHttpRequest.DONE&&this.status===200?t.markSuccess(n.successMessage):this.readyState===XMLHttpRequest.DONE&&this.status>=400&&t.markError(window.$http.formatErrorResponseText(this.responseText))}});s.upload.addEventListener("progress",o=>{let r=Math.min(Math.ceil(o.loaded/o.total*100),100);t.updateProgress(r)}),s.setRequestHeader("Accept","application/json"),s.send(e)}createDomForFile(t){let e=it("img",{src:"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M9.224 7.373a.924.924 0 0 0-.92.925l-.006 7.404c0 .509.412.925.921.925h5.557a.928.928 0 0 0 .926-.925v-5.553l-2.777-2.776Zm3.239 3.239V8.067l2.545 2.545z' style='fill:%23000;fill-opacity:.75'/%3E%3C/svg%3E"}),n=it("div",{class:"dropzone-file-item-status"},[]),s=it("div",{class:"dropzone-file-item-progress"}),o=it("div",{class:"dropzone-file-item-image-wrap"},[e]),r=it("div",{class:"dropzone-file-item"},[o,it("div",{class:"dropzone-file-item-text-wrap"},[it("div",{class:"dropzone-file-item-label"},[t.name]),$t(),n]),s]);t.type.startsWith("image/")&&(e.src=URL.createObjectURL(t));let a=()=>{r.classList.add("dismiss"),r.addEventListener("animationend",()=>{r.remove()})};return r.addEventListener("click",a),{dom:r,progress:s,status:n,dismiss:a}}};var ni=class extends d{setup(){this.container=this.$el,this.buttons=this.$manyRefs.tabButton,this.contentElements=this.$manyRefs.tabContent,this.toggleButton=this.$refs.toggle,this.editorWrapEl=this.container.closest(".page-editor"),this.setupListeners(),this.setActiveTab(this.contentElements[0].dataset.tabContent)}setupListeners(){this.toggleButton.addEventListener("click",()=>this.toggle()),this.container.addEventListener("click",t=>{let e=t.target.closest("button");if(this.buttons.includes(e)){let n=e.dataset.tab;this.setActiveTab(n,!0)}})}toggle(){this.container.classList.toggle("open");let t=this.container.classList.contains("open");this.toggleButton.setAttribute("aria-expanded",t?"true":"false"),this.editorWrapEl.classList.toggle("toolbox-open",t)}setActiveTab(t,e=!1){for(let n of this.buttons)n.classList.remove("active"),n.dataset.tab===t&&n.classList.add("active");for(let n of this.contentElements)n.style.display="none",n.dataset.tabContent===t&&(n.style.display="block");e&&!this.container.classList.contains("open")&&this.toggle()}};var si=class extends d{setup(){this.container=this.$el,this.entityType=this.$opts.entityType,this.everyoneInheritToggle=this.$refs.everyoneInherit,this.roleSelect=this.$refs.roleSelect,this.roleContainer=this.$refs.roleContainer,this.setupListeners()}setupListeners(){this.everyoneInheritToggle.addEventListener("change",t=>{let e=t.target.checked,n=document.querySelectorAll('input[name^="permissions[0]["]');for(let s of n)s.disabled=e,s.checked=!1}),this.container.addEventListener("click",t=>{let e=t.target.closest("button");e&&e.dataset.roleId&&this.removeRowOnButtonClick(e)}),this.roleSelect.addEventListener("change",()=>{let t=this.roleSelect.value;t&&this.addRoleRow(t)})}async addRoleRow(t){this.roleSelect.disabled=!0;let e=this.roleSelect.querySelector(`option[value="${t}"]`);e&&e.remove();let n=await window.$http.get(`/permissions/form-row/${this.entityType}/${t}`),s=nt(n.data);this.roleContainer.append(s),this.roleSelect.disabled=!1}removeRowOnButtonClick(t){let e=t.closest(".item-list-row"),{roleId:n}=t.dataset,{roleName:s}=t.dataset,o=document.createElement("option");o.value=n,o.textContent=s,this.roleSelect.append(o),e.remove()}};var oi=class extends d{setup(){this.entityId=this.$opts.entityId,this.entityType=this.$opts.entityType,this.contentView=this.$refs.contentView,this.searchView=this.$refs.searchView,this.searchResults=this.$refs.searchResults,this.searchInput=this.$refs.searchInput,this.searchForm=this.$refs.searchForm,this.clearButton=this.$refs.clearButton,this.loadingBlock=this.$refs.loadingBlock,this.setupListeners()}setupListeners(){this.searchInput.addEventListener("change",this.runSearch.bind(this)),this.searchForm.addEventListener("submit",t=>{t.preventDefault(),this.runSearch()}),x(this.clearButton,this.clearSearch.bind(this))}runSearch(){let t=this.searchInput.value.trim();if(t.length===0){this.clearSearch();return}this.searchView.classList.remove("hidden"),this.contentView.classList.add("hidden"),this.loadingBlock.classList.remove("hidden");let e=window.baseUrl(`/search/${this.entityType}/${this.entityId}`);window.$http.get(e,{term:t}).then(n=>{this.searchResults.innerHTML=n.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=""}};var ri=class extends d{setup(){this.elem=this.$el,this.input=this.$refs.input,this.searchInput=this.$refs.search,this.loading=this.$refs.loading,this.resultsContainer=this.$refs.results,this.searchOptions={entityTypes:this.$opts.entityTypes||"page,book,chapter",entityPermission:this.$opts.entityPermission||"view",searchEndpoint:this.$opts.searchEndpoint||"",initialValue:this.searchInput.value||""},this.search="",this.lastClick=0,this.setupListeners(),this.showLoading(),this.searchOptions.searchEndpoint&&this.initialLoad()}configureSearchOptions(t){Object.assign(this.searchOptions,t),this.reset(),this.searchInput.value=this.searchOptions.initialValue}setupListeners(){this.elem.addEventListener("click",this.onClick.bind(this));let t=0;this.searchInput.addEventListener("input",()=>{t=Date.now(),this.showLoading(),setTimeout(()=>{Date.now()-t<199||this.searchEntities(this.searchInput.value)},200)}),this.searchInput.addEventListener("keydown",e=>{e.keyCode===13&&e.preventDefault()}),A(this.$el,"[data-entity-type]","keydown",e=>{if(e.ctrlKey&&e.code==="Enter"){let n=this.$el.closest("form");if(n){n.submit(),e.preventDefault();return}}e.code==="ArrowDown"&&this.focusAdjacent(!0),e.code==="ArrowUp"&&this.focusAdjacent(!1)}),this.searchInput.addEventListener("keydown",e=>{e.code==="ArrowDown"&&this.focusAdjacent(!0)})}focusAdjacent(t=!0){let e=Array.from(this.resultsContainer.querySelectorAll("[data-entity-type]")),n=e.indexOf(document.activeElement),s=e[n+(t?1:-1)]||e[0];s&&s.focus()}reset(){this.searchInput.value="",this.showLoading(),this.initialLoad()}focusSearch(){this.searchInput.focus()}showLoading(){this.loading.style.display="block",this.resultsContainer.style.display="none"}hideLoading(){this.loading.style.display="none",this.resultsContainer.style.display="block"}initialLoad(){if(!this.searchOptions.searchEndpoint)throw new Error("Search endpoint not set for entity-selector load");if(this.searchOptions.initialValue){this.searchEntities(this.searchOptions.initialValue);return}window.$http.get(this.searchUrl()).then(t=>{this.resultsContainer.innerHTML=t.data,this.hideLoading()})}searchUrl(){let t=`types=${encodeURIComponent(this.searchOptions.entityTypes)}&permission=${encodeURIComponent(this.searchOptions.entityPermission)}`;return`${this.searchOptions.searchEndpoint}?${t}`}searchEntities(t){if(!this.searchOptions.searchEndpoint)throw new Error("Search endpoint not set for entity-selector load");this.input.value="";let e=`${this.searchUrl()}&term=${encodeURIComponent(t)}`;window.$http.get(e).then(n=>{this.resultsContainer.innerHTML=n.data,this.hideLoading()})}isDoubleClick(){let t=Date.now(),e=t-this.lastClick<300;return this.lastClick=t,e}onClick(t){let e=t.target.closest("[data-entity-type]");e&&(t.preventDefault(),t.stopPropagation(),this.selectItem(e))}selectItem(t){let e=this.isDoubleClick(),n=t.getAttribute("data-entity-type"),s=t.getAttribute("data-entity-id"),o=!t.classList.contains("selected")||e;this.unselectAll(),this.input.value=o?`${n}:${s}`:"";let r=t.getAttribute("href"),a=t.querySelector(".entity-list-item-name").textContent,l={id:Number(s),name:a,link:r};o?t.classList.add("selected"):window.$events.emit("entity-select-change",null),!(!e&&!o)&&(e&&this.confirmSelection(l),o&&window.$events.emit("entity-select-change",l))}confirmSelection(t){window.$events.emit("entity-select-confirm",t)}unselectAll(){let t=this.elem.querySelectorAll(".selected");for(let e of t)e.classList.remove("selected","primary-background")}};var ai=class extends d{setup(){this.container=this.$el,this.selectButton=this.$refs.select,this.selectorEl=this.$refs.selector,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.handleConfirmedSelection.bind(this))}show(t,e={}){this.callback=t,this.getSelector().configureSearchOptions(e),this.getPopup().show(),this.getSelector().focusSearch()}hide(){this.getPopup().hide()}getPopup(){return window.$components.firstOnElement(this.container,"popup")}getSelector(){return window.$components.firstOnElement(this.selectorEl,"entity-selector")}onSelectButtonClick(){this.handleConfirmedSelection(this.selection)}onSelectionChange(t){this.selection=t,t===null?this.selectButton.setAttribute("disabled","true"):this.selectButton.removeAttribute("disabled")}handleConfirmedSelection(t){this.hide(),this.getSelector().reset(),this.callback&&t&&this.callback(t)}};var li=class extends d{setup(){this.container=this.$el,this.name=this.$opts.name,x(this.$el,()=>{this.$emit(this.name,this.$opts)})}};var ci=class extends d{setup(){this.targetSelector=this.$opts.targetSelector,this.isOpen=this.$opts.isOpen==="true",this.updateEndpoint=this.$opts.updateEndpoint,this.$el.addEventListener("click",this.click.bind(this))}open(t){_t(t,200)}close(t){Ot(t,200)}click(t){t.preventDefault();let e=document.querySelectorAll(this.targetSelector);for(let n of e)(this.isOpen?this.close:this.open)(n);this.isOpen=!this.isOpen,this.updateSystemAjax(this.isOpen)}updateSystemAjax(t){window.$http.patch(this.updateEndpoint,{expand:t?"true":"false"})}};var di=class extends d{setup(){this.container=this.$el,this.input=this.$refs.input,this.suggestions=this.$refs.suggestions,this.suggestionResultsWrap=this.$refs.suggestionResults,this.loadingWrap=this.$refs.loading,this.button=this.$refs.button,this.setupListeners()}setupListeners(){let t=Tt(this.updateSuggestions.bind(this),200,!1);this.input.addEventListener("input",()=>{let{value:e}=this.input;e.length>0?(this.loadingWrap.style.display="block",this.suggestionResultsWrap.style.opacity="0.5",t(e)):this.hideSuggestions()}),this.input.addEventListener("dblclick",()=>{this.input.setAttribute("autocomplete","on"),this.button.focus(),this.input.focus()}),new ut(this.container,()=>{this.hideSuggestions()})}async updateSuggestions(t){let{data:e}=await window.$http.get("/search/suggest",{term:t});if(!this.input.value)return;let n=nt(e);this.suggestionResultsWrap.innerHTML="",this.suggestionResultsWrap.style.opacity="1",this.loadingWrap.style.display="none",this.suggestionResultsWrap.append(n),this.container.classList.contains("search-active")||this.showSuggestions()}showSuggestions(){this.container.classList.add("search-active"),window.requestAnimationFrame(()=>{this.suggestions.classList.add("search-suggestions-animation")})}hideSuggestions(){this.container.classList.remove("search-active"),this.suggestions.classList.remove("search-suggestions-animation"),this.suggestionResultsWrap.innerHTML=""}};var hi=class extends d{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)}};var ui=class extends d{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.uploadButton=this.$refs.uploadButton,this.uploadHint=this.$refs.uploadHint,this.formContainer=this.$refs.formContainer,this.formContainerPlaceholder=this.$refs.formContainerPlaceholder,this.dropzoneContainer=this.$refs.dropzoneContainer,this.loadMore=this.$refs.loadMore,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()}setupListeners(){x(this.filterTabs,n=>{this.resetAll(),this.filter=n.target.dataset.filter,this.setActiveFilterTab(this.filter),this.loadGallery()}),this.searchForm.addEventListener("submit",n=>{this.resetListView(),this.loadGallery(),this.cancelSearch.toggleAttribute("hidden",!this.searchInput.value),n.preventDefault()}),x(this.cancelSearch,()=>{this.resetListView(),this.resetSearchView(),this.loadGallery()}),A(this.container,".load-more button","click",this.runLoadMore.bind(this)),this.listContainer.addEventListener("event-emit-select-image",this.onImageSelectEvent.bind(this)),this.listContainer.addEventListener("error",n=>{n.target.src=window.baseUrl("loading_error.png")},!0),x(this.selectButton,()=>{this.callback&&this.callback(this.lastSelected),this.hide()}),A(this.formContainer,"#image-manager-delete","click",()=>{this.lastSelected&&this.loadImageEditForm(this.lastSelected.id,!0)}),A(this.formContainer,"#image-manager-rebuild-thumbs","click",async(n,s)=>{s.disabled=!0,this.lastSelected&&await this.rebuildThumbnails(this.lastSelected.id),s.disabled=!1}),this.formContainer.addEventListener("ajax-form-success",()=>{this.refreshGallery(),this.resetEditForm()}),this.container.addEventListener("dropzone-upload-success",this.refreshGallery.bind(this));let t=this.listContainer.parentElement,e=[];t.addEventListener("wheel",n=>{if(!(Math.ceil(t.scrollHeight-t.scrollTop)===t.clientHeight)||n.deltaY<1)return;let r=Date.now()-1e3;e.push(Date.now()),e=e.filter(a=>a>=r),e.length>5&&this.canLoadMore()&&this.runLoadMore()})}show(t,e="gallery"){this.resetAll(),this.callback=t,this.type=e,this.getPopup().show();let n=e!=="gallery";this.dropzoneContainer.classList.toggle("hidden",n),this.uploadButton.classList.toggle("hidden",n),this.uploadHint.classList.toggle("hidden",n),window.$components.firstOnElement(this.container,"dropzone").toggleActive(!n),this.hasData||(this.loadGallery(),this.hasData=!0)}hide(){this.getPopup().hide()}getPopup(){return window.$components.firstOnElement(this.popupEl,"popup")}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:e}=await window.$http.get(`images/${this.type}`,t);t.page===1&&(this.listContainer.innerHTML=""),this.addReturnedHtmlElementsToList(e),Xt(this.listContainer)}addReturnedHtmlElementsToList(t){let e=document.createElement("div");e.innerHTML=t;let n=e.querySelector(".load-more");n&&(n.remove(),this.loadMore.innerHTML=n.innerHTML),this.loadMore.toggleAttribute("hidden",!n),window.$components.init(e);for(let s of[...e.children])this.listContainer.appendChild(s)}setActiveFilterTab(t){for(let e of this.filterTabs){let n=e.dataset.filter===t;e.setAttribute("aria-selected",n?"true":"false")}}resetAll(){this.resetState(),this.resetListView(),this.resetSearchView(),this.resetEditForm(),this.setActiveFilterTab("all"),this.selectButton.classList.add("hidden")}resetSearchView(){this.searchInput.value="",this.cancelSearch.toggleAttribute("hidden",!0)}resetEditForm(){this.formContainer.innerHTML="",this.formContainerPlaceholder.removeAttribute("hidden")}resetListView(){Kt(this.listContainer),this.page=1}refreshGallery(){this.resetListView(),this.loadGallery()}async onImageSelectEvent(t){let e=JSON.parse(t.detail.data),n=e&&e.id===this.lastSelected.id&&Date.now()-this.lastSelectedTime<400,s=t.target.classList.contains("selected");[...this.listContainer.querySelectorAll(".selected")].forEach(o=>{o.classList.remove("selected")}),!s&&!n?(t.target.classList.add("selected"),e=await this.loadImageEditForm(e.id)):n?n&&(e=this.lastSelected):this.resetEditForm(),this.selectButton.classList.toggle("hidden",s),n&&this.callback&&(this.callback(e),this.hide()),this.lastSelected=e,this.lastSelectedTime=Date.now()}async loadImageEditForm(t,e=!1){e||(this.formContainer.innerHTML="");let n=e?{delete:!0}:{},{data:s}=await window.$http.get(`/images/edit/${t}`,n);this.formContainer.innerHTML=s,this.formContainerPlaceholder.setAttribute("hidden",""),window.$components.init(this.formContainer);let o=this.formContainer.querySelector("#image-manager-form-image-data");return JSON.parse(o.text)}runLoadMore(){Kt(this.loadMore),this.page+=1,this.loadGallery()}canLoadMore(){return this.loadMore.querySelector("button")&&!this.loadMore.hasAttribute("hidden")}async rebuildThumbnails(t){try{let e=await window.$http.put(`/images/${t}/rebuild-thumbnails`);window.$events.success(e.data),this.refreshGallery()}catch(e){window.$events.showResponseError(e)}}};var pi=class extends d{setup(){this.imageElem=this.$refs.image,this.imageInput=this.$refs.imageInput,this.resetInput=this.$refs.resetInput,this.removeInput=this.$refs.removeInput,this.resetButton=this.$refs.resetButton,this.removeButton=this.$refs.removeButton||null,this.defaultImage=this.$opts.defaultImage,this.setupListeners()}setupListeners(){this.resetButton.addEventListener("click",this.reset.bind(this)),this.removeButton&&this.removeButton.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")}};var fi=class extends d{setup(){this.elem=this.$el,this.menu=this.$refs.menu,this.sortInput=this.$refs.sort,this.orderInput=this.$refs.order,this.form=this.$refs.form,this.setupListeners()}setupListeners(){this.menu.addEventListener("click",t=>{t.target.closest("[data-sort-value]")!==null&&this.sortOptionClick(t)}),this.elem.addEventListener("click",t=>{t.target.closest("[data-sort-dir]")!==null&&this.sortDirectionClick(t)})}sortOptionClick(t){let e=t.target.closest("[data-sort-value]");this.sortInput.value=e.getAttribute("data-sort-value"),t.preventDefault(),this.form.submit()}sortDirectionClick(t){let e=this.orderInput.value;this.orderInput.value=e==="asc"?"desc":"asc",t.preventDefault(),this.form.submit()}};var mi=class extends d{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.display=this.$refs.display,this.input=this.$refs.input,this.divider=this.$refs.divider,this.displayWrap=this.$refs.displayWrap;let{settingContainer:t}=this.$refs,e=t.querySelectorAll('input[type="checkbox"]');this.editor=null,window.importVersioned("markdown").then(n=>n.init({pageId:this.pageId,container:this.elem,displayEl:this.display,inputEl:this.input,drawioUrl:this.getDrawioUrl(),settingInputs:Array.from(e),text:{serverUploadLimit:this.serverUploadLimitText,imageUploadError:this.imageUploadErrorText}})).then(n=>{this.editor=n,this.setupListeners(),this.emitEditorEvents(),this.scrollToTextIfNeeded(),this.editor.actions.updateAndRender()})}emitEditorEvents(){window.$events.emitPublic(this.elem,"editor-markdown::setup",{markdownIt:this.editor.markdown.getRenderer(),displayEl:this.display,cmEditorView:this.editor.cm})}setupListeners(){this.elem.addEventListener("click",t=>{let e=t.target.closest("button[data-action]");if(e===null)return;let n=e.getAttribute("data-action");if(n==="insertImage"&&this.editor.actions.showImageInsert(),n==="insertLink"&&this.editor.actions.showLinkSelector(),n==="insertDrawing"&&(t.ctrlKey||t.metaKey)){this.editor.actions.showImageManager();return}n==="insertDrawing"&&this.editor.actions.startDrawing(),n==="fullscreen"&&this.editor.actions.fullScreen()}),this.elem.addEventListener("click",t=>{let e=t.target.closest(".editor-toolbar-label");if(!e)return;let n=this.elem.querySelectorAll(".markdown-editor-wrap");for(let s of n)s.classList.remove("active");e.closest(".markdown-editor-wrap").classList.add("active")}),this.handleDividerDrag()}handleDividerDrag(){this.divider.addEventListener("pointerdown",()=>{let e=this.elem.getBoundingClientRect(),n=o=>{let r=o.pageX-e.left,a=Math.min(Math.max(20,Math.floor(r/e.width*100)),80);this.displayWrap.style.flexBasis=`${100-a}%`,this.editor.settings.set("editorWidth",a)},s=()=>{window.removeEventListener("pointermove",n),window.removeEventListener("pointerup",s),this.display.style.pointerEvents=null,document.body.style.userSelect=null};this.display.style.pointerEvents="none",document.body.style.userSelect="none",window.addEventListener("pointermove",n),window.addEventListener("pointerup",s)});let t=this.editor.settings.get("editorWidth");t&&(this.displayWrap.style.flexBasis=`${100-t}%`)}scrollToTextIfNeeded(){let e=new URL(window.location).searchParams.get("content-text");e&&this.editor.actions.scrollToText(e)}getDrawioUrl(){let t=document.querySelector("[drawio-url]");return t&&t.getAttribute("drawio-url")||""}getContent(){return this.editor.actions.getContent()}};var gi=class extends d{setup(){this.container=this.$el,this.inputContainer=this.$refs.inputContainer,this.inviteOption=this.container.querySelector("input[name=send_invite]"),this.inviteOption&&(this.inviteOption.addEventListener("change",this.inviteOptionChange.bind(this)),this.inviteOptionChange())}inviteOptionChange(){let t=this.inviteOption.value==="true",e=this.container.querySelectorAll("input[type=password]");for(let n of e)n.disabled=t;this.inputContainer.style.display=t?"none":"block"}};var wi=class extends d{setup(){this.container=this.$el,this.type=this.$opts.type,this.textElem=this.container.querySelector("span"),this.autoHide=this.$opts.autoHide==="true",this.initialShow=this.$opts.show==="true",this.container.style.display="grid",window.$events.listen(this.type,t=>{this.show(t)}),this.container.addEventListener("click",this.hide.bind(this)),this.initialShow&&setTimeout(()=>this.show(this.textElem.textContent),100),this.hideCleanup=this.hideCleanup.bind(this)}show(t=""){if(this.container.removeEventListener("transitionend",this.hideCleanup),this.textElem.textContent=t,this.container.style.display="grid",setTimeout(()=>{this.container.classList.add("showing")},1),this.autoHide){let e=t.split(" ").length,n=Math.max(2e3,1e3+250*e);setTimeout(this.hide.bind(this),n)}}hide(){this.container.classList.remove("showing"),this.container.addEventListener("transitionend",this.hideCleanup)}hideCleanup(){this.container.style.display="none",this.container.removeEventListener("transitionend",this.hideCleanup)}};var vi=class extends d{setup(){this.removeButton=this.$refs.remove,this.showButton=this.$refs.show,this.input=this.$refs.input,this.setupListeners()}setupListeners(){x(this.removeButton,()=>{this.input.value="",this.input.classList.add("hidden"),this.removeButton.classList.add("hidden"),this.showButton.classList.remove("hidden")}),x(this.showButton,()=>{this.input.classList.remove("hidden"),this.removeButton.classList.remove("hidden"),this.showButton.classList.add("hidden")})}};function _s(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+o","","InsertOrderedList"),i.shortcuts.add("meta+p","","InsertUnorderedList"),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","",()=>{let t=i.selection.getNode(),e=t?t.closest(".callout"):null,n=["info","success","warning","danger"],o=(n.findIndex(a=>e&&e.classList.contains(a))+1)%n.length,r=n[o];i.formatter.apply(`callout${r}`)}),i.shortcuts.add("meta+shift+K","",()=>{let t=window.$components.first("entity-selector-popup"),e=i.selection.getContent({format:"text"}).trim();t.show(n=>{i.selection.isCollapsed()?i.insertContent(i.dom.createHTML("a",{href:n.link},i.dom.encode(n.name))):i.formatter.apply("link",{href:n.link}),i.selection.collapse(!1),i.focus()},{initialValue:e,searchEndpoint:"/search/entity-selector",entityTypes:"page,book,chapter,bookshelf",entityPermission:"view"})})}function Ns(i){window.$events.listen("editor::replace",({html:t})=>{i.setContent(t)}),window.$events.listen("editor::append",({html:t})=>{let e=i.getContent()+t;i.setContent(e)}),window.$events.listen("editor::prepend",({html:t})=>{let e=t+i.getContent();i.setContent(e)}),window.$events.listen("editor::insert",({html:t})=>{i.insertContent(t)}),window.$events.listen("editor::focus",()=>{i.initialized&&i.focus()})}function yr(i,t){let e=i.dom.get(encodeURIComponent(t).replace(/!/g,"%21"));e&&(e.scrollIntoView(),i.selection.select(e,!0),i.selection.collapse(!1),i.focus())}function Fs(i){let e=new URL(window.location).searchParams.get("content-id");e&&yr(i,e)}var xt,bi;function Cr(i){return i&&!!(i.textContent||i.innerText)}async function Er(i,t){if(i===null||i.type.indexOf("image")!==0)throw new Error("Not an image file");let e=i.name||`image-${Date.now()}.png`,n=new FormData;return n.append("file",i,e),n.append("uploaded_to",t),(await window.$http.post(window.baseUrl("/images/gallery"),n)).data}function Rs(i,t,e){let n=new Nt(e.clipboardData||e.dataTransfer);if(!n.hasItems()||n.containsTabularData())return;let s=n.getImages();for(let o of s){let r=`image-${Math.random().toString(16).slice(2)}`,a=window.baseUrl("/loading.gif");e.preventDefault(),setTimeout(()=>{i.insertContent(``),Er(o,t.pageId).then(l=>{let c=l.name.replace(/"/g,""),h=``,u=i.dom.create("a",{target:"_blank",href:l.url},h);i.dom.replace(u,r)}).catch(l=>{i.dom.remove(r),window.$events.error(l?.data?.message||t.translations.imageUploadErrorText),console.error(l)})},10)}}function xr(i){let t=i.selection.getNode();t.nodeName==="IMG"&&(xt=i.dom.getParent(t,".mceTemp"),!xt&&t.parentNode.nodeName==="A"&&!Cr(t.parentNode)&&(xt=t.parentNode)),t.hasAttribute("contenteditable")&&t.getAttribute("contenteditable")==="false"&&(bi=t)}function Sr(i,t,e){let{dom:n}=i,s=window.tinymce.dom.RangeUtils.getCaretRangeFromPoint(e.clientX,e.clientY,i.getDoc()),o=e.dataTransfer&&e.dataTransfer.getData("bookstack/template");o&&(e.preventDefault(),window.$http.get(`/templates/${o}`).then(r=>{i.selection.setRng(s),i.undoManager.transact(()=>{i.execCommand("mceInsertContent",!1,r.data.html)})})),n.getParent(s.startContainer,".mceTemp")?e.preventDefault():xt&&(e.preventDefault(),i.undoManager.transact(()=>{i.selection.setRng(s),i.selection.setNode(xt),n.remove(xt)})),!e.isDefaultPrevented()&&bi&&(e.preventDefault(),i.undoManager.transact(()=>{let r=i.selection.getNode(),a=i.selection.getRng(),l=r.closest("body > *");a.startOffset>a.startContainer.length/2?l.after(bi):l.before(bi)})),e.isDefaultPrevented()||Rs(i,t,e),xt=null}function kr(i,t){t.preventDefault(),i.focus();let n=window.tinymce.dom.RangeUtils.getCaretRangeFromPoint(t.clientX??0,t.clientY??0,i.getDoc());i.selection.setRng(n)}function Hs(i,t){i.on("dragover",e=>kr(i,e)),i.on("dragstart",()=>xr(i)),i.on("drop",e=>Sr(i,t,e)),i.on("paste",e=>Rs(i,t,e))}function qs(i){return["undo redo","styles","bold italic underline forecolor backcolor formatoverflow","alignleft aligncenter alignright alignjustify","bullist numlist listoverflow",i.textDirection==="rtl"?"ltr rtl":"","link customtable imagemanager-insert insertoverflow","code about fullscreen"].filter(n=>!!n).join(" | ")}function Lr(i){i.ui.registry.addGroupToolbarButton("formatoverflow",{icon:"more-drawer",tooltip:"More",items:"strikethrough superscript subscript inlinecode removeformat"}),i.ui.registry.addGroupToolbarButton("listoverflow",{icon:"more-drawer",tooltip:"More",items:"tasklist outdent indent"}),i.ui.registry.addGroupToolbarButton("insertoverflow",{icon:"more-drawer",tooltip:"More",items:"customhr codeeditor drawio media details"})}function $r(i){i.ui.registry.addContextToolbar("linkcontexttoolbar",{predicate(t){return t.closest("a")!==null},position:"node",scope:"node",items:"link unlink openlink"})}function Tr(i){i.ui.registry.addContextToolbar("imagecontexttoolbar",{predicate(t){return t.closest("img")!==null&&!t.hasAttribute("data-mce-object")},position:"node",scope:"node",items:"image"})}function Dr(i){i.ui.registry.addContextToolbar("objectcontexttoolbar",{predicate(t){return t.closest("img")!==null&&t.hasAttribute("data-mce-object")},position:"node",scope:"node",items:"media"})}function Us(i){Lr(i),$r(i),Tr(i),Dr(i)}var Ar={"table-delete-column":'',"table-delete-row":'',"table-insert-column-after":'',"table-insert-column-before":'',"table-insert-row-above":'',"table-insert-row-after":'',table:'',"table-delete-table":''};function Vs(i){for(let[t,e]of Object.entries(Ar))i.ui.registry.addIcon(t,e)}function Ir(i){i.serializer.addNodeFilter("br",t=>{for(let e of t)if(e.parent&&e.parent.name==="code"){let n=window.tinymce.html.Node.create("#text");n.value=`
+`,e.replace(n)}})}function Mr(i){i.parser.addNodeFilter("div",t=>{for(let e of t){let n=e.attr("id")||"",s=e.attr("class")||"";(n==="pointer"||s.includes("pointer"))&&e.remove()}})}function zs(i){Ir(i),Mr(i)}function js(i){return i.tagName.toLowerCase()==="code-block"}function Ks(i,t,e,n,s){let o=window.$components.first("code-editor"),r=i.selection.getBookmark();o.open(t,e,n,(a,l)=>{s(a,l),i.focus(),i.selection.moveToBookmark(r)},()=>{i.focus(),i.selection.moveToBookmark(r)})}function Ws(i,t){let e=t.getAttribute("dir")||"";Ks(i,t.getContent(),t.getLanguage(),e,(n,s)=>{t.setContent(n,s)})}function Br(i){let t=i.getDoc(),e=t.defaultView;class n extends e.HTMLElement{constructor(){super();U(this,"editor",null);this.attachShadow({mode:"open"});let r=document.head.querySelectorAll('link[rel="stylesheet"]:not([media="print"]),style'),a=Array.from(r).map(c=>c.cloneNode(!0)),l=document.createElement("div");l.style.pointerEvents="none",l.contentEditable="false",l.classList.add("CodeMirrorContainer"),l.classList.toggle("dark-mode",document.documentElement.classList.contains("dark-mode")),this.shadowRoot.append(...a,l)}getLanguage(){let r=c=>(c.split(" ").filter(u=>u.startsWith("language-"))[0]||"").replace("language-",""),a=this.querySelector("code"),l=this.querySelector("pre");return r(l.className)||a&&r(a.className)||""}setContent(r,a){this.editor&&(this.editor.setContent(r),this.editor.setMode(a,r));let l=this.querySelector("pre");l||(l=t.createElement("pre"),this.append(l)),l.innerHTML="";let c=t.createElement("code");l.append(c),c.innerText=r,c.className=`language-${a}`}getContent(){let r=this.querySelector("code")||this.querySelector("pre"),a=document.createElement("pre");a.innerHTML=r.innerHTML.replace(/\ufeff/g,"");let l=a.querySelectorAll("br");for(let c of l)c.replaceWith(`
`);return a.textContent}connectedCallback(){let r=Date.now();if(this.editor)return;this.cleanChildContent();let a=this.getContent(),c=a.split(`
-`).length*19.2+18+24;this.style.height=`${c}px`;let h=this.shadowRoot.querySelector(".CodeMirrorContainer"),u=m=>{this.editor=m.wysiwygView(h,this.shadowRoot,a,this.getLanguage()),setTimeout(()=>{this.style.height=null},12)};window.importVersioned("code").then(m=>{let C=Date.now()-r<20?20:0;setTimeout(()=>u(m),C)})}cleanChildContent(){let r=this.querySelector("pre");if(r)for(let a of r.childNodes)a.nodeName==="#text"&&a.textContent==="\uFEFF"&&a.remove()}}e.customElements.define("code-block",n)}function Mr(i){i.ui.registry.addIcon("codeblock",''),i.ui.registry.addButton("codeeditor",{tooltip:"Insert code block",icon:"codeblock",onAction(){i.execCommand("codeeditor")}}),i.ui.registry.addButton("editcodeeditor",{tooltip:"Edit code block",icon:"edit-block",onAction(){i.execCommand("codeeditor")}}),i.addCommand("codeeditor",()=>{let t=i.selection.getNode(),e=t.ownerDocument;if(zs(t))js(i,t);else{let n=i.selection.getContent({format:"text"}),s=document.dir==="rtl"?"ltr":"";Ws(i,n,"",s,(o,r)=>{let a=e.createElement("pre"),l=e.createElement("code");l.classList.add(`language-${r}`),l.innerText=o,s&&a.setAttribute("dir",s),a.append(l),i.insertContent(a.outerHTML)})}}),i.on("dblclick",()=>{let t=i.selection.getNode();zs(t)&&js(i,t)}),i.on("PreInit",()=>{i.parser.addNodeFilter("pre",t=>{for(let e of t){let n=window.tinymce.html.Node.create("code-block",{contenteditable:"false"}),s=e.children().filter(a=>a.name==="code")[0]||null,o=e.attr("dir")||s&&s.attr("dir")||"";o&&n.attr("dir",o);let r=e.getAll("span");for(let a of r)a.unwrap();e.attr("style",null),e.wrap(n)}}),i.parser.addNodeFilter("code-block",t=>{for(let e of t)e.attr("contenteditable","false")}),i.serializer.addNodeFilter("code-block",t=>{for(let e of t){let n=e.attr("dir");n&&e.firstChild?e.firstChild.attr("dir",n):e.firstChild&&e.firstChild.attr("dir",null),e.unwrap()}})}),i.ui.registry.addContextToolbar("codeeditor",{predicate(t){return t.nodeName.toLowerCase()==="code-block"},items:"editcodeeditor",position:"node",scope:"node"}),i.on("PreInit",()=>{Ir(i)})}function Ks(){return Mr}function yi(i){return new Promise((t,e)=>{i.oncomplete=i.onsuccess=()=>t(i.result),i.onabort=i.onerror=()=>e(i.error)})}function Br(i,t){let e=indexedDB.open(i);e.onupgradeneeded=()=>e.result.createObjectStore(t);let n=yi(e);return(s,o)=>n.then(r=>o(r.transaction(t,s).objectStore(t)))}var Pn;function On(){return Pn||(Pn=Br("keyval-store","keyval")),Pn}function _n(i,t=On()){return t("readonly",e=>yi(e.get(i)))}function Nn(i,t,e=On()){return e("readwrite",n=>(n.put(t,i),yi(n.transaction)))}function Fn(i,t=On()){return t("readwrite",e=>(e.delete(i),yi(e.transaction)))}var rt=null,qn,Ci,Rn,Hn="last-drawing-save";function Un(i){rt.contentWindow.postMessage(JSON.stringify(i),qn)}function Or(i){Nn(Hn,i.data),Rn&&Rn(i.data).then(()=>{Fn(Hn)})}function _r(i){Un({action:"export",format:"xmlpng",xml:i.xml,spin:"Updating drawing"})}function Nr(){Ci&&Ci().then(i=>{Un({action:"load",autosave:1,xml:i})})}function Fr(){let i={};window.$events.emitPublic(rt,"editor-drawio::configure",{config:i}),Un({action:"configure",config:i})}function Xs(){window.removeEventListener("message",Gs),rt&&document.body.removeChild(rt)}function Gs(i){if(!i.data||i.data.length<1||i.origin!==qn)return;let t=JSON.parse(i.data);t.event==="init"?Nr():t.event==="exit"?Xs():t.event==="save"?_r(t):t.event==="export"?Or(t):t.event==="configure"&&Fr()}async function Rr(){let i=await _n(Hn),t=document.getElementById("unsaved-drawing-dialog");t||console.error("Missing expected unsaved-drawing dialog"),i&&await window.$components.firstOnElement(t,"confirm-dialog").show()&&(Ci=async()=>i)}async function Ys(i,t,e){Ci=t,Rn=e,await Rr(),rt=document.createElement("iframe"),rt.setAttribute("frameborder","0"),window.addEventListener("message",Gs),rt.setAttribute("src",i),rt.setAttribute("class","fullscreen"),rt.style.backgroundColor="#FFFFFF",document.body.appendChild(rt),qn=new URL(i).origin}async function Vn(i,t){let e={image:i,uploaded_to:t};return(await window.$http.post(window.baseUrl("/images/drawio"),e)).data}function Ei(){Xs()}async function Zs(i){try{return`data:image/png;base64,${(await window.$http.get(window.baseUrl(`/images/drawio/base64/${i}`))).data.content}`}catch(t){throw t instanceof window.$http.HttpError&&window.$events.showResponseError(t),Ei(),t}}var j=null,kt=null,St={};function zn(i){return i.hasAttribute("drawio-diagram")}function qr(i,t=null){j=i,kt=t,window.$components.first("image-manager").show(n=>{if(t){let s=t.querySelector("img");j.undoManager.transact(()=>{j.dom.setAttrib(s,"src",n.url),j.dom.setAttrib(t,"drawio-diagram",n.id)})}else{let s=``;j.insertContent(s)}},"drawio")}async function Ur(i){let t=window.baseUrl("/loading.gif"),e=o=>{o.status===413?window.$events.emit("error",St.translations.serverUploadLimitText):window.$events.emit("error",St.translations.imageUploadErrorText),console.error(o)};if(kt){Ei();let o=kt.querySelector("img");try{let r=await Vn(i,St.pageId);j.undoManager.transact(()=>{j.dom.setAttrib(o,"src",r.url),j.dom.setAttrib(kt,"drawio-diagram",r.id)})}catch(r){throw e(r),new Error(`Failed to save image with error: ${r}`)}return}await ss(5);let n=`drawing-${Math.random().toString(16).slice(2)}`,s=`drawing-wrap-${Math.random().toString(16).slice(2)}`;j.insertContent(``),Ei();try{let o=await Vn(i,St.pageId);j.undoManager.transact(()=>{j.dom.setAttrib(n,"src",o.url),j.dom.setAttrib(s,"drawio-diagram",o.id)})}catch(o){throw j.dom.remove(s),e(o),new Error(`Failed to save image with error: ${o}`)}}function Vr(){if(!kt)return Promise.resolve("");let i=kt.getAttribute("drawio-diagram");return Zs(i)}function Js(i,t=null){j=i,kt=t,Ys(St.drawioUrl,Vr,Ur)}function zr(i){i.addCommand("drawio",()=>{let t=i.selection.getNode();Js(i,zn(t)?t:null)}),i.ui.registry.addIcon("diagram",``),i.ui.registry.addSplitButton("drawio",{tooltip:"Insert/edit drawing",icon:"diagram",onAction(){i.execCommand("drawio"),window.document.body.dispatchEvent(new Event("mousedown",{bubbles:!0}))},fetch(t){t([{type:"choiceitem",text:"Drawing manager",value:"drawing-manager"}])},onItemAction(t,e){if(e==="drawing-manager"){let n=i.selection.getNode();qr(i,zn(n)?n:null)}}}),i.on("dblclick",()=>{let t=i.selection.getNode();zn(t)&&Js(i,t)}),i.on("SetContent",()=>{let t=i.dom.select("body > div[drawio-diagram]");t.length&&i.undoManager.transact(()=>{for(let e of t)e.setAttribute("contenteditable","false")})})}function Qs(i){return St=i,zr}function jr(i){i.addCommand("InsertHorizontalRule",()=>{let t=document.createElement("hr"),e=i.selection.getNode(),{parentNode:n}=e;n.insertBefore(t,e)}),i.ui.registry.addButton("customhr",{icon:"horizontal-rule",tooltip:"Insert horizontal line",onAction(){i.execCommand("InsertHorizontalRule")}})}function to(){return jr}function Wr(i){i.ui.registry.addButton("imagemanager-insert",{title:"Insert image",icon:"image",tooltip:"Insert image",onAction(){window.$components.first("image-manager").show(e=>{let n=e.thumbs?.display||e.url,s=``;s+=``,s+="",i.execCommand("mceInsertContent",!1,s)},"gallery")}})}function eo(){return Wr}function Kr(i){let t={title:"About the WYSIWYG Editor",url:window.baseUrl("/help/wysiwyg")};i.ui.registry.addButton("about",{icon:"help",tooltip:"About the editor",onAction(){window.tinymce.activeEditor.windowManager.openUrl(t)}})}function io(){return Kr}var no=["p","h1","h2","h3","h4","h5","h6","div","blockquote","pre","code-block","details","ul","ol","table","hr"];function xi(i){return i.selection.getNode().closest("details")}function Xr(i,t){let e=xi(i);e&&i.undoManager.transact(()=>{let n=e.querySelector("summary");n||(n=document.createElement("summary"),e.prepend(n)),n.textContent=t})}function Gr(i){return{title:"Edit collapsible block",body:{type:"panel",items:[{type:"input",name:"summary",label:"Toggle label"}]},buttons:[{type:"cancel",text:"Cancel"},{type:"submit",text:"Save",primary:!0}],onSubmit(t){let{summary:e}=t.getData();Xr(i,e),t.close()}}}function Yr(i){let t=i.querySelector("summary");return t?t.textContent:""}function so(i){let t=xi(i);i.windowManager.open(Gr(i)).setData({summary:Yr(t)})}function Zr(i){let t=i.selection.getNode().closest("details"),e=i.selection.getBookmark();if(t){let n=t.querySelectorAll("details > *:not(summary, doc-root), doc-root > *");i.undoManager.transact(()=>{for(let s of n)t.parentNode.insertBefore(s,t);t.remove()})}i.focus(),i.selection.moveToBookmark(e)}function jn(i){i.attr("contenteditable",null);let t=!1;for(let e of i.children())e.name==="doc-root"&&(e.unwrap(),t=!0);t&&jn(i)}function Jr(i){jn(i),i.attr("contenteditable","false");let t=window.tinymce.html.Node.create("doc-root",{contenteditable:"true"}),e=null;for(let n of i.children()){if(n.name==="summary")continue;no.includes(n.name)?(t.append(n),e=null):(e||(e=window.tinymce.html.Node.create("p"),t.append(e)),e.append(n))}i.append(t)}function Qr(i){i.parser.addNodeFilter("details",t=>{for(let e of t)Jr(e)}),i.serializer.addNodeFilter("details",t=>{for(let e of t)jn(e),e.attr("open",null)}),i.serializer.addNodeFilter("doc-root",t=>{for(let e of t)e.unwrap()})}function ta(i){i.ui.registry.addIcon("details",''),i.ui.registry.addIcon("togglefold",''),i.ui.registry.addIcon("togglelabel",''),i.ui.registry.addButton("details",{icon:"details",tooltip:"Insert collapsible block",onAction(){i.execCommand("InsertDetailsBlock")}}),i.ui.registry.addButton("removedetails",{icon:"table-delete-table",tooltip:"Unwrap",onAction(){Zr(i)}}),i.ui.registry.addButton("editdetials",{icon:"togglelabel",tooltip:"Edit label",onAction(){so(i)}}),i.on("dblclick",t=>{!xi(i)||t.target.closest("doc-root")||so(i)}),i.ui.registry.addButton("toggledetails",{icon:"togglefold",tooltip:"Toggle open/closed",onAction(){xi(i).toggleAttribute("open"),i.focus()}}),i.addCommand("InsertDetailsBlock",()=>{let t=i.selection.getContent({format:"html"}),e=document.createElement("details"),n=document.createElement("summary"),s=`details-${Date.now()}`;e.setAttribute("data-id",s),e.appendChild(n),t||(t="
"),e.innerHTML+=t,i.insertContent(e.outerHTML),i.focus();let o=i.dom.select(`[data-id="${s}"]`)[0]||null;if(o){let r=o.querySelector("doc-root > *");r&&r.focus(),o.removeAttribute("data-id")}}),i.ui.registry.addContextToolbar("details",{predicate(t){return t.nodeName.toLowerCase()==="details"},items:"editdetials toggledetails removedetails",position:"node",scope:"node"}),i.on("PreInit",()=>{Qr(i)})}function oo(){return ta}function ea(i){i.ui.registry.addIcon("tableclearformatting",'');let t={items:" | tablerowheader",predicate(n){let s=n.nodeName.toLowerCase()==="table",o=i.selection.getNode(),r=o.closest("table");return!s||!r?!1:r.querySelector("tr").contains(o)},position:"node",scope:"node"};i.ui.registry.addContextToolbar("customtabletoolbarfirstrow",t),i.addCommand("tableclearformatting",()=>{let n=i.dom.getParent(i.selection.getStart(),"table");if(!n)return;let s=["class","style","width","height"],o=[n,...n.querySelectorAll(s.map(r=>`[${r}]`).join(","))];for(let r of o)for(let a of s)r.removeAttribute(a)}),i.addCommand("tableclearsizes",()=>{let n=i.dom.getParent(i.selection.getStart(),"table");if(!n)return;let s=[n,...n.querySelectorAll("tr,td,th,tbody,thead,tfoot,th>*,td>*")];for(let o of s)o.removeAttribute("width"),o.removeAttribute("height"),o.style.height=null,o.style.width=null});let e=()=>{let n=i.ui.registry.getAll().buttons;i.ui.registry.addMenuButton("customtable",{...n.table,fetch:s=>s("inserttable | cell row column | advtablesort | tableprops tableclearformatting tableclearsizes deletetable")}),i.ui.registry.addMenuItem("tableclearformatting",{icon:"tableclearformatting",text:"Clear table formatting",onSetup:n.tableprops.onSetup,onAction(){i.execCommand("tableclearformatting")}}),i.ui.registry.addMenuItem("tableclearsizes",{icon:"resize",text:"Resize to contents",onSetup:n.tableprops.onSetup,onAction(){i.execCommand("tableclearsizes")}}),i.off("PreInit",e)};i.on("PreInit",e)}function ro(){return ea}function ia(i){let t=i.closest("li");return t&&t.parentNode.nodeName==="UL"&&t.classList.contains("task-list-item")}function na(i,t,e){let n=t.getBoundingClientRect();i.clientX<=n.right&&i.clientX>=n.left&&i.clientY>=n.top&&i.clientY<=n.bottom||e.undoManager.transact(()=>{t.hasAttribute("checked")?t.removeAttribute("checked"):t.setAttribute("checked","checked")})}function sa(i){i.attr("class","task-list-item");for(let t of i.children())t.name==="input"&&(t.attr("checked")==="checked"&&i.attr("checked","checked"),t.remove())}function oa(i){let t=i.attr("checked")==="checked";i.attr("checked",null);let e={type:"checkbox",disabled:"disabled"};t&&(e.checked="checked");let n=window.tinymce.html.Node.create("input",e);n.shortEnded=!0,i.firstChild?i.insert(n,i.firstChild,!0):i.append(n)}function ra(i){i.ui.registry.addIcon("tasklist",''),i.ui.registry.addToggleButton("tasklist",{tooltip:"Task list",icon:"tasklist",active:!1,onAction(n){n.isActive()?i.execCommand("RemoveList"):i.execCommand("InsertUnorderedList",null,{"list-item-attributes":{class:"task-list-item"},"list-style-type":"tasklist"})},onSetup(n){i.on("NodeChange",s=>{let o=s.parents.find(a=>a.nodeName==="LI"),r=o&&o.classList.contains("task-list-item");n.setActive(!!r)})}});let t=i.ui.registry.getAll().buttons.bullist;t.onSetup=function(s){i.on("NodeChange",o=>{let r=o.parents.find(c=>c.nodeName==="LI"),a=r&&r.classList.contains("task-list-item"),l=r&&r.parentNode.nodeName==="UL";s.setActive(!!(l&&!a))})},t.onAction=function(){ia(i.selection.getNode())&&i.execCommand("InsertOrderedList",null,{"list-item-attributes":{class:null}}),i.execCommand("InsertUnorderedList",null,{"list-item-attributes":{class:null}})};let e=i.ui.registry.getAll().buttons.numlist;e.onAction=function(){i.execCommand("InsertOrderedList",null,{"list-item-attributes":{class:null}})},i.on("PreInit",()=>{i.parser.addNodeFilter("li",n=>{for(let s of n)s.attributes.map.class==="task-list-item"&&sa(s)}),i.serializer.addNodeFilter("li",n=>{for(let s of n)s.attributes.map.class==="task-list-item"&&oa(s)})}),i.on("click",n=>{let s=n.target;s.nodeName==="LI"&&s.classList.contains("task-list-item")&&(na(n,s,i),n.preventDefault())})}function ao(){return ra}function lo(i){function t(e){let n=e.querySelector("iframe, video");if(!n)return;let s=[...n.classList.values()].filter(r=>r.startsWith("align-")),o=[...e.classList.values()].filter(r=>r.startsWith("align-"));e.classList.remove(...o),e.classList.add(...s)}i.on("SetContent",()=>{let e=i.dom.select("span.mce-preview-object");for(let n of e)t(n)}),i.on("FormatApply",e=>{let n=e.format.startsWith("align");if(!(e.node instanceof i.dom.doc.defaultView.HTMLElement)||!n||!e.node.matches(".mce-preview-object"))return;let o=e.node.querySelector("iframe, video");if(o){let r=(i.formatter.get(e.format)[0]?.classes||[])[0],a=!o.classList.contains(r),c=(e.node.getAttribute("data-mce-p-class")||"").split(" ").filter(u=>!u.startsWith("align-"));a&&c.push(r);let h=c.join(" ");e.node.setAttribute("data-mce-p-class",h),o.setAttribute("class",h),i.formatter.apply(e.format,{},o),t(e.node)}})}function co(i){let t=i.querySelectorAll('[dir],[style*="direction"],[style*="text-align"]');for(let e of t)e.removeAttribute("dir"),e.style.direction=null,e.style.textAlign=null;i.style.direction=null,i.style.textAlign=null}function ho(i){let t=[];i.on("TableSelectionChange",n=>{t=(n.cells||[]).map(s=>s.dom)}),i.on("TableSelectionClear",()=>{t=[]});let e=["class","style","width","height"];i.on("ExecCommand",n=>{if(n.command==="RemoveFormat")for(let s of t)for(let o of e)s.removeAttribute(o)}),i.on("ExecCommand",n=>{let s=n.command;if(s!=="mceDirectionLTR"&&s!=="mceDirectionRTL")return;let o=s==="mceDirectionLTR"?"ltr":"rtl";for(let r of t)r.setAttribute("dir",o),co(r)})}function uo(i){i.on("ExecCommand",t=>{let e=t.command;if(e!=="mceDirectionLTR"&&e!=="mceDirectionRTL")return;let n=i.selection.getSelectedBlocks();for(let s of n)co(s)})}var aa=[{title:"Large Header",format:"h2",preview:"color: blue;"},{title:"Medium Header",format:"h3"},{title:"Small Header",format:"h4"},{title:"Tiny Header",format:"h5"},{title:"Paragraph",format:"p",exact:!0,classes:""},{title:"Blockquote",format:"blockquote"},{title:"Callouts",items:[{title:"Information",format:"calloutinfo"},{title:"Success",format:"calloutsuccess"},{title:"Warning",format:"calloutwarning"},{title:"Danger",format:"calloutdanger"}]}],la={alignleft:{selector:"p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img,iframe,video",classes:"align-left"},aligncenter:{selector:"p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img,iframe,video",classes:"align-center"},alignright:{selector:"p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img,iframe,video",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"}}},ca=["#BFEDD2","","#FBEEB8","","#F8CAC6","","#ECCAFA","","#C2E0F4","","#2DC26B","","#F1C40F","","#E03E2D","","#B96AD9","","#3598DB","","#169179","","#E67E23","","#BA372A","","#843FA1","","#236FA1","","#ECF0F1","","#CED4D9","","#95A5A6","","#7E8C8D","","#34495E","","#000000","","#ffffff",""];function po(i,t,e){if(e.filetype==="file"){let n=window.$components.first("entity-selector-popup"),s=this.selection.getContent({format:"text"}).trim();n.show(o=>{i(o.link,{text:o.name,title:o.name})},{initialValue:s,searchEndpoint:"/search/entity-selector",entityTypes:"page,book,chapter,bookshelf",entityPermission:"view"})}e.filetype==="image"&&window.$components.first("image-manager").show(s=>{i(s.url,{alt:s.name})},"gallery")}function da(i){let t=["image","table","link","autolink","fullscreen","code","customhr","autosave","lists","codeeditor","media","imagemanager","about","details","tasklist","tableadditions",i.textDirection==="rtl"?"directionality":""];return window.tinymce.PluginManager.add("codeeditor",Ks()),window.tinymce.PluginManager.add("customhr",to()),window.tinymce.PluginManager.add("imagemanager",eo()),window.tinymce.PluginManager.add("about",io()),window.tinymce.PluginManager.add("details",oo()),window.tinymce.PluginManager.add("tasklist",ao()),window.tinymce.PluginManager.add("tableadditions",ro()),i.drawioUrl&&(window.tinymce.PluginManager.add("drawio",Qs(i)),t.push("drawio")),t.filter(e=>!!e)}function fo(i){let t=document.head.innerHTML.split(`
+`).length*19.2+18+24;this.style.height=`${c}px`;let h=this.shadowRoot.querySelector(".CodeMirrorContainer"),u=m=>{this.editor=m.wysiwygView(h,this.shadowRoot,a,this.getLanguage()),setTimeout(()=>{this.style.height=null},12)};window.importVersioned("code").then(m=>{let C=Date.now()-r<20?20:0;setTimeout(()=>u(m),C)})}cleanChildContent(){let r=this.querySelector("pre");if(r)for(let a of r.childNodes)a.nodeName==="#text"&&a.textContent==="\uFEFF"&&a.remove()}}e.customElements.define("code-block",n)}function Pr(i){i.ui.registry.addIcon("codeblock",''),i.ui.registry.addButton("codeeditor",{tooltip:"Insert code block",icon:"codeblock",onAction(){i.execCommand("codeeditor")}}),i.ui.registry.addButton("editcodeeditor",{tooltip:"Edit code block",icon:"edit-block",onAction(){i.execCommand("codeeditor")}}),i.addCommand("codeeditor",()=>{let t=i.selection.getNode(),e=t.ownerDocument;if(js(t))Ws(i,t);else{let n=i.selection.getContent({format:"text"}),s=document.dir==="rtl"?"ltr":"";Ks(i,n,"",s,(o,r)=>{let a=e.createElement("pre"),l=e.createElement("code");l.classList.add(`language-${r}`),l.innerText=o,s&&a.setAttribute("dir",s),a.append(l),i.insertContent(a.outerHTML)})}}),i.on("dblclick",()=>{let t=i.selection.getNode();js(t)&&Ws(i,t)}),i.on("PreInit",()=>{i.parser.addNodeFilter("pre",t=>{for(let e of t){let n=window.tinymce.html.Node.create("code-block",{contenteditable:"false"}),s=e.children().filter(a=>a.name==="code")[0]||null,o=e.attr("dir")||s&&s.attr("dir")||"";o&&n.attr("dir",o);let r=e.getAll("span");for(let a of r)a.unwrap();e.attr("style",null),e.wrap(n)}}),i.parser.addNodeFilter("code-block",t=>{for(let e of t)e.attr("contenteditable","false")}),i.serializer.addNodeFilter("code-block",t=>{for(let e of t){let n=e.attr("dir");n&&e.firstChild?e.firstChild.attr("dir",n):e.firstChild&&e.firstChild.attr("dir",null),e.unwrap()}})}),i.ui.registry.addContextToolbar("codeeditor",{predicate(t){return t.nodeName.toLowerCase()==="code-block"},items:"editcodeeditor",position:"node",scope:"node"}),i.on("PreInit",()=>{Br(i)})}function Xs(){return Pr}function yi(i){return new Promise((t,e)=>{i.oncomplete=i.onsuccess=()=>t(i.result),i.onabort=i.onerror=()=>e(i.error)})}function Or(i,t){let e=indexedDB.open(i);e.onupgradeneeded=()=>e.result.createObjectStore(t);let n=yi(e);return(s,o)=>n.then(r=>o(r.transaction(t,s).objectStore(t)))}var Pn;function On(){return Pn||(Pn=Or("keyval-store","keyval")),Pn}function _n(i,t=On()){return t("readonly",e=>yi(e.get(i)))}function Nn(i,t,e=On()){return e("readwrite",n=>(n.put(t,i),yi(n.transaction)))}function Fn(i,t=On()){return t("readwrite",e=>(e.delete(i),yi(e.transaction)))}var rt=null,qn,Ci,Rn,Hn="last-drawing-save";function Un(i){rt.contentWindow.postMessage(JSON.stringify(i),qn)}function Nr(i){Nn(Hn,i.data),Rn&&Rn(i.data).then(()=>{Fn(Hn)})}function Fr(i){Un({action:"export",format:"xmlpng",xml:i.xml,spin:"Updating drawing"})}function Rr(){Ci&&Ci().then(i=>{Un({action:"load",autosave:1,xml:i})})}function Hr(){let i={};window.$events.emitPublic(rt,"editor-drawio::configure",{config:i}),Un({action:"configure",config:i})}function Gs(){window.removeEventListener("message",Ys),rt&&document.body.removeChild(rt)}function Ys(i){if(!i.data||i.data.length<1||i.origin!==qn)return;let t=JSON.parse(i.data);t.event==="init"?Rr():t.event==="exit"?Gs():t.event==="save"?Fr(t):t.event==="export"?Nr(t):t.event==="configure"&&Hr()}async function qr(){let i=await _n(Hn),t=document.getElementById("unsaved-drawing-dialog");t||console.error("Missing expected unsaved-drawing dialog"),i&&await window.$components.firstOnElement(t,"confirm-dialog").show()&&(Ci=async()=>i)}async function Js(i,t,e){Ci=t,Rn=e,await qr(),rt=document.createElement("iframe"),rt.setAttribute("frameborder","0"),window.addEventListener("message",Ys),rt.setAttribute("src",i),rt.setAttribute("class","fullscreen"),rt.style.backgroundColor="#FFFFFF",document.body.appendChild(rt),qn=new URL(i).origin}async function Vn(i,t){let e={image:i,uploaded_to:t};return(await window.$http.post(window.baseUrl("/images/drawio"),e)).data}function Ei(){Gs()}async function Zs(i){try{return`data:image/png;base64,${(await window.$http.get(window.baseUrl(`/images/drawio/base64/${i}`))).data.content}`}catch(t){throw t instanceof window.$http.HttpError&&window.$events.showResponseError(t),Ei(),t}}var j=null,kt=null,St={};function zn(i){return i.hasAttribute("drawio-diagram")}function Vr(i,t=null){j=i,kt=t,window.$components.first("image-manager").show(n=>{if(t){let s=t.querySelector("img");j.undoManager.transact(()=>{j.dom.setAttrib(s,"src",n.url),j.dom.setAttrib(t,"drawio-diagram",n.id)})}else{let s=``;j.insertContent(s)}},"drawio")}async function zr(i){let t=window.baseUrl("/loading.gif"),e=o=>{o.status===413?window.$events.emit("error",St.translations.serverUploadLimitText):window.$events.emit("error",St.translations.imageUploadErrorText),console.error(o)};if(kt){Ei();let o=kt.querySelector("img");try{let r=await Vn(i,St.pageId);j.undoManager.transact(()=>{j.dom.setAttrib(o,"src",r.url),j.dom.setAttrib(kt,"drawio-diagram",r.id)})}catch(r){throw e(r),new Error(`Failed to save image with error: ${r}`)}return}await os(5);let n=`drawing-${Math.random().toString(16).slice(2)}`,s=`drawing-wrap-${Math.random().toString(16).slice(2)}`;j.insertContent(``),Ei();try{let o=await Vn(i,St.pageId);j.undoManager.transact(()=>{j.dom.setAttrib(n,"src",o.url),j.dom.setAttrib(s,"drawio-diagram",o.id)})}catch(o){throw j.dom.remove(s),e(o),new Error(`Failed to save image with error: ${o}`)}}function jr(){if(!kt)return Promise.resolve("");let i=kt.getAttribute("drawio-diagram");return Zs(i)}function Qs(i,t=null){j=i,kt=t,Js(St.drawioUrl,jr,zr)}function Wr(i){i.addCommand("drawio",()=>{let t=i.selection.getNode();Qs(i,zn(t)?t:null)}),i.ui.registry.addIcon("diagram",``),i.ui.registry.addSplitButton("drawio",{tooltip:"Insert/edit drawing",icon:"diagram",onAction(){i.execCommand("drawio"),window.document.body.dispatchEvent(new Event("mousedown",{bubbles:!0}))},fetch(t){t([{type:"choiceitem",text:"Drawing manager",value:"drawing-manager"}])},onItemAction(t,e){if(e==="drawing-manager"){let n=i.selection.getNode();Vr(i,zn(n)?n:null)}}}),i.on("dblclick",()=>{let t=i.selection.getNode();zn(t)&&Qs(i,t)}),i.on("SetContent",()=>{let t=i.dom.select("body > div[drawio-diagram]");t.length&&i.undoManager.transact(()=>{for(let e of t)e.setAttribute("contenteditable","false")})})}function to(i){return St=i,Wr}function Kr(i){i.addCommand("InsertHorizontalRule",()=>{let t=document.createElement("hr"),e=i.selection.getNode(),{parentNode:n}=e;n.insertBefore(t,e)}),i.ui.registry.addButton("customhr",{icon:"horizontal-rule",tooltip:"Insert horizontal line",onAction(){i.execCommand("InsertHorizontalRule")}})}function eo(){return Kr}function Xr(i){i.ui.registry.addButton("imagemanager-insert",{title:"Insert image",icon:"image",tooltip:"Insert image",onAction(){window.$components.first("image-manager").show(e=>{let n=e.thumbs?.display||e.url,s=``;s+=``,s+="",i.execCommand("mceInsertContent",!1,s)},"gallery")}})}function io(){return Xr}function Gr(i){let t={title:"About the WYSIWYG Editor",url:window.baseUrl("/help/wysiwyg")};i.ui.registry.addButton("about",{icon:"help",tooltip:"About the editor",onAction(){window.tinymce.activeEditor.windowManager.openUrl(t)}})}function no(){return Gr}var so=["p","h1","h2","h3","h4","h5","h6","div","blockquote","pre","code-block","details","ul","ol","table","hr"];function xi(i){return i.selection.getNode().closest("details")}function Yr(i,t){let e=xi(i);e&&i.undoManager.transact(()=>{let n=e.querySelector("summary");n||(n=document.createElement("summary"),e.prepend(n)),n.textContent=t})}function Jr(i){return{title:"Edit collapsible block",body:{type:"panel",items:[{type:"input",name:"summary",label:"Toggle label"}]},buttons:[{type:"cancel",text:"Cancel"},{type:"submit",text:"Save",primary:!0}],onSubmit(t){let{summary:e}=t.getData();Yr(i,e),t.close()}}}function Zr(i){let t=i.querySelector("summary");return t?t.textContent:""}function oo(i){let t=xi(i);i.windowManager.open(Jr(i)).setData({summary:Zr(t)})}function Qr(i){let t=i.selection.getNode().closest("details"),e=i.selection.getBookmark();if(t){let n=t.querySelectorAll("details > *:not(summary, doc-root), doc-root > *");i.undoManager.transact(()=>{for(let s of n)t.parentNode.insertBefore(s,t);t.remove()})}i.focus(),i.selection.moveToBookmark(e)}function jn(i){i.attr("contenteditable",null);let t=!1;for(let e of i.children())e.name==="doc-root"&&(e.unwrap(),t=!0);t&&jn(i)}function ta(i){jn(i),i.attr("contenteditable","false");let t=window.tinymce.html.Node.create("doc-root",{contenteditable:"true"}),e=null;for(let n of i.children()){if(n.name==="summary")continue;so.includes(n.name)?(t.append(n),e=null):(e||(e=window.tinymce.html.Node.create("p"),t.append(e)),e.append(n))}i.append(t)}function ea(i){i.parser.addNodeFilter("details",t=>{for(let e of t)ta(e)}),i.serializer.addNodeFilter("details",t=>{for(let e of t)jn(e),e.attr("open",null)}),i.serializer.addNodeFilter("doc-root",t=>{for(let e of t)e.unwrap()})}function ia(i){i.ui.registry.addIcon("details",''),i.ui.registry.addIcon("togglefold",''),i.ui.registry.addIcon("togglelabel",''),i.ui.registry.addButton("details",{icon:"details",tooltip:"Insert collapsible block",onAction(){i.execCommand("InsertDetailsBlock")}}),i.ui.registry.addButton("removedetails",{icon:"table-delete-table",tooltip:"Unwrap",onAction(){Qr(i)}}),i.ui.registry.addButton("editdetials",{icon:"togglelabel",tooltip:"Edit label",onAction(){oo(i)}}),i.on("dblclick",t=>{!xi(i)||t.target.closest("doc-root")||oo(i)}),i.ui.registry.addButton("toggledetails",{icon:"togglefold",tooltip:"Toggle open/closed",onAction(){xi(i).toggleAttribute("open"),i.focus()}}),i.addCommand("InsertDetailsBlock",()=>{let t=i.selection.getContent({format:"html"}),e=document.createElement("details"),n=document.createElement("summary"),s=`details-${Date.now()}`;e.setAttribute("data-id",s),e.appendChild(n),t||(t="