diff --git a/public/dist/app.js b/public/dist/app.js index 25d1a6121..5009a25ad 100644 --- a/public/dist/app.js +++ b/public/dist/app.js @@ -15,17 +15,17 @@ var Bu=Object.create;var _e=Object.defineProperty;var Pu=Object.getOwnPropertyDe `);return i};be.prototype.render=function(n,t,e){var i,r,o,s="",a=this.rules;for(i=0,r=n.length;i{"use strict";function Ct(){this.__rules__=[],this.__cache__=null}Ct.prototype.__find__=function(n){for(var t=0;t{"use strict";var Sd=/\r\n?|\n/g,Ad=/\0/g;ya.exports=function(t){var e;e=t.src.replace(Sd,` `),e=e.replace(Ad,"\uFFFD"),t.src=e}});var Ca=_((Qb,ka)=>{"use strict";ka.exports=function(t){var e;t.inlineMode?(e=new t.Token("inline","",0),e.content=t.src,e.map=[0,1],e.children=[],t.tokens.push(e)):t.md.block.parse(t.src,t.md,t.env,t.tokens)}});var _a=_((tv,Ea)=>{"use strict";Ea.exports=function(t){var e=t.tokens,i,r,o;for(r=0,o=e.length;r{"use strict";var Dd=N().arrayReplaceAt;function Ld(n){return/^\s]/i.test(n)}function Td(n){return/^<\/a\s*>/i.test(n)}Sa.exports=function(t){var e,i,r,o,s,a,l,c,u,h,d,f,p,m,w,v,b=t.tokens,k;if(t.md.options.linkify){for(i=0,r=b.length;i=0;e--){if(a=o[e],a.type==="link_close"){for(e--;o[e].level!==a.level&&o[e].type!=="link_open";)e--;continue}if(a.type==="html_inline"&&(Ld(a.content)&&p>0&&p--,Td(a.content)&&p++),!(p>0)&&a.type==="text"&&t.md.linkify.test(a.content)){for(u=a.content,k=t.md.linkify.match(u),l=[],f=a.level,d=0,k.length>0&&k[0].index===0&&e>0&&o[e-1].type==="text_special"&&(k=k.slice(1)),c=0;cd&&(s=new t.Token("text","",0),s.content=u.slice(d,h),s.level=f,l.push(s)),s=new t.Token("link_open","a",1),s.attrs=[["href",w]],s.level=f++,s.markup="linkify",s.info="auto",l.push(s),s=new t.Token("text","",0),s.content=v,s.level=f,l.push(s),s=new t.Token("link_close","a",-1),s.level=--f,s.markup="linkify",s.info="auto",l.push(s),d=k[c].lastIndex);d{"use strict";var Da=/\+-|\.\.|\?\?\?\?|!!!!|,,|--/,$d=/\((c|tm|r)\)/i,Id=/\((c|tm|r)\)/ig,Md={c:"\xA9",r:"\xAE",tm:"\u2122"};function Fd(n,t){return Md[t.toLowerCase()]}function qd(n){var t,e,i=0;for(t=n.length-1;t>=0;t--)e=n[t],e.type==="text"&&!i&&(e.content=e.content.replace(Id,Fd)),e.type==="link_open"&&e.info==="auto"&&i--,e.type==="link_close"&&e.info==="auto"&&i++}function Bd(n){var t,e,i=0;for(t=n.length-1;t>=0;t--)e=n[t],e.type==="text"&&!i&&Da.test(e.content)&&(e.content=e.content.replace(/\+-/g,"\xB1").replace(/\.{2,}/g,"\u2026").replace(/([?!])…/g,"$1..").replace(/([?!]){4,}/g,"$1$1$1").replace(/,{2,}/g,",").replace(/(^|[^-])---(?=[^-]|$)/mg,"$1\u2014").replace(/(^|\s)--(?=\s|$)/mg,"$1\u2013").replace(/(^|[^-\s])--(?=[^-\s]|$)/mg,"$1\u2013")),e.type==="link_open"&&e.info==="auto"&&i--,e.type==="link_close"&&e.info==="auto"&&i++}La.exports=function(t){var e;if(t.md.options.typographer)for(e=t.tokens.length-1;e>=0;e--)t.tokens[e].type==="inline"&&($d.test(t.tokens[e].content)&&qd(t.tokens[e].children),Da.test(t.tokens[e].content)&&Bd(t.tokens[e].children))}});var Pa=_((iv,Ba)=>{"use strict";var $a=N().isWhiteSpace,Ia=N().isPunctChar,Ma=N().isMdAsciiPunct,Pd=/['"]/,Fa=/['"]/g,qa="\u2019";function hi(n,t,e){return n.slice(0,t)+e+n.slice(t+1)}function Od(n,t){var e,i,r,o,s,a,l,c,u,h,d,f,p,m,w,v,b,k,x,E,y;for(x=[],e=0;e=0&&!(x[b].level<=l);b--);if(x.length=b+1,i.type==="text"){r=i.content,s=0,a=r.length;t:for(;s=0)u=r.charCodeAt(o.index-1);else for(b=e-1;b>=0&&!(n[b].type==="softbreak"||n[b].type==="hardbreak");b--)if(n[b].content){u=n[b].content.charCodeAt(n[b].content.length-1);break}if(h=32,s=48&&u<=57&&(v=w=!1),w&&v&&(w=d,v=f),!w&&!v){k&&(i.content=hi(i.content,o.index,qa));continue}if(v){for(b=x.length-1;b>=0&&(c=x[b],!(x[b].level=0;e--)t.tokens[e].type!=="inline"||!Pd.test(t.tokens[e].content)||Od(t.tokens[e].children,t)}});var Ra=_((rv,Oa)=>{"use strict";Oa.exports=function(t){var e,i,r,o,s,a,l=t.tokens;for(e=0,i=l.length;e{"use strict";function ve(n,t,e){this.type=n,this.tag=t,this.attrs=null,this.map=null,this.nesting=e,this.level=0,this.children=null,this.content="",this.markup="",this.info="",this.meta=null,this.block=!1,this.hidden=!1}ve.prototype.attrIndex=function(t){var e,i,r;if(!this.attrs)return-1;for(e=this.attrs,i=0,r=e.length;i=0&&(i=this.attrs[e][1]),i};ve.prototype.attrJoin=function(t,e){var i=this.attrIndex(t);i<0?this.attrPush([t,e]):this.attrs[i][1]=this.attrs[i][1]+" "+e};Na.exports=ve});var Ua=_((sv,Ha)=>{"use strict";var Rd=di();function za(n,t,e){this.src=n,this.env=e,this.tokens=[],this.inlineMode=!1,this.md=t}za.prototype.Token=Rd;Ha.exports=za});var Va=_((av,ja)=>{"use strict";var Nd=ui(),Jr=[["normalize",xa()],["block",Ca()],["inline",_a()],["linkify",Aa()],["replacements",Ta()],["smartquotes",Pa()],["text_join",Ra()]];function Qr(){this.ruler=new Nd;for(var n=0;n{"use strict";var to=N().isSpace;function eo(n,t){var e=n.bMarks[t]+n.tShift[t],i=n.eMarks[t];return n.src.slice(e,i)}function Wa(n){var t=[],e=0,i=n.length,r,o=!1,s=0,a="";for(r=n.charCodeAt(e);ei||(u=e+1,t.sCount[u]=4||(a=t.bMarks[u]+t.tShift[u],a>=t.eMarks[u])||(E=t.src.charCodeAt(a++),E!==124&&E!==45&&E!==58)||a>=t.eMarks[u]||(y=t.src.charCodeAt(a++),y!==124&&y!==45&&y!==58&&!to(y))||E===45&&to(y))return!1;for(;a=4||(h=Wa(s),h.length&&h[0]===""&&h.shift(),h.length&&h[h.length-1]===""&&h.pop(),d=h.length,d===0||d!==p.length))return!1;if(r)return!0;for(b=t.parentType,t.parentType="table",x=t.md.block.ruler.getRules("blockquote"),f=t.push("table_open","table",1),f.map=w=[e,0],f=t.push("thead_open","thead",1),f.map=[e,e+1],f=t.push("tr_open","tr",1),f.map=[e,e+1],l=0;l=4)break;for(h=Wa(s),h.length&&h[0]===""&&h.shift(),h.length&&h[h.length-1]===""&&h.pop(),u===e+2&&(f=t.push("tbody_open","tbody",1),f.map=v=[e+2,0]),f=t.push("tr_open","tr",1),f.map=[u,u+1],l=0;l{"use strict";Za.exports=function(t,e,i){var r,o,s;if(t.sCount[e]-t.blkIndent<4)return!1;for(o=r=e+1;r=4){r++,o=r;continue}break}return t.line=o,s=t.push("code_block","code",0),s.content=t.getLines(e,o,4+t.blkIndent,!1)+` `,s.map=[e,t.line],!0}});var Ja=_((uv,Ya)=>{"use strict";Ya.exports=function(t,e,i,r){var o,s,a,l,c,u,h,d=!1,f=t.bMarks[e]+t.tShift[e],p=t.eMarks[e];if(t.sCount[e]-t.blkIndent>=4||f+3>p||(o=t.src.charCodeAt(f),o!==126&&o!==96)||(c=f,f=t.skipChars(f,o),s=f-c,s<3)||(h=t.src.slice(c,f),a=t.src.slice(f,p),o===96&&a.indexOf(String.fromCharCode(o))>=0))return!1;if(r)return!0;for(l=e;l++,!(l>=i||(f=c=t.bMarks[l]+t.tShift[l],p=t.eMarks[l],f=4)&&(f=t.skipChars(f,o),!(f-c{"use strict";var zd=N().isSpace;Qa.exports=function(t,e,i,r){var o,s,a,l,c,u,h,d,f,p,m,w,v,b,k,x,E,y,A,D,M=t.lineMax,T=t.bMarks[e]+t.tShift[e],P=t.eMarks[e];if(t.sCount[e]-t.blkIndent>=4||t.src.charCodeAt(T)!==62)return!1;if(r)return!0;for(p=[],m=[],b=[],k=[],y=t.md.block.ruler.getRules("blockquote"),v=t.parentType,t.parentType="blockquote",d=e;d=P));d++){if(t.src.charCodeAt(T++)===62&&!D){for(l=t.sCount[d]+1,t.src.charCodeAt(T)===32?(T++,l++,o=!1,x=!0):t.src.charCodeAt(T)===9?(x=!0,(t.bsCount[d]+l)%4===3?(T++,l++,o=!1):o=!0):x=!1,f=l,p.push(t.bMarks[d]),t.bMarks[d]=T;T=P,m.push(t.bsCount[d]),t.bsCount[d]=t.sCount[d]+1+(x?1:0),b.push(t.sCount[d]),t.sCount[d]=f-l,k.push(t.tShift[d]),t.tShift[d]=T-t.bMarks[d];continue}if(u)break;for(E=!1,a=0,c=y.length;a",A.map=h=[e,0],t.md.block.tokenize(t,e,d),A=t.push("blockquote_close","blockquote",-1),A.markup=">",t.lineMax=M,t.parentType=v,h[1]=t.line,a=0;a{"use strict";var Hd=N().isSpace;el.exports=function(t,e,i,r){var o,s,a,l,c=t.bMarks[e]+t.tShift[e],u=t.eMarks[e];if(t.sCount[e]-t.blkIndent>=4||(o=t.src.charCodeAt(c++),o!==42&&o!==45&&o!==95))return!1;for(s=1;c{"use strict";var ol=N().isSpace;function il(n,t){var e,i,r,o;return i=n.bMarks[t]+n.tShift[t],r=n.eMarks[t],e=n.src.charCodeAt(i++),e!==42&&e!==45&&e!==43||i=o||(e=n.src.charCodeAt(r++),e<48||e>57))return-1;for(;;){if(r>=o)return-1;if(e=n.src.charCodeAt(r++),e>=48&&e<=57){if(r-i>=10)return-1;continue}if(e===41||e===46)break;return-1}return r=4||t.listIndent>=0&&t.sCount[$]-t.listIndent>=4&&t.sCount[$]=t.blkIndent&&(Ot=!0),(T=rl(t,$))>=0){if(h=!0,H=t.bMarks[$]+t.tShift[$],v=Number(t.src.slice(H,T-1)),Ot&&v!==1)return!1}else if((T=il(t,$))>=0)h=!1;else return!1;if(Ot&&t.skipSpaces(T)>=t.eMarks[$])return!1;if(r)return!0;for(w=t.src.charCodeAt(T-1),m=t.tokens.length,h?(W=t.push("ordered_list_open","ol",1),v!==1&&(W.attrs=[["start",v]])):W=t.push("bullet_list_open","ul",1),W.map=p=[$,0],W.markup=String.fromCharCode(w),P=!1,et=t.md.block.ruler.getRules("list"),E=t.parentType,t.parentType="list";$=b?c=1:c=k-u,c>4&&(c=1),l=u+c,W=t.push("list_item_open","li",1),W.markup=String.fromCharCode(w),W.map=d=[$,0],h&&(W.info=t.src.slice(H,T-1)),D=t.tight,A=t.tShift[$],y=t.sCount[$],x=t.listIndent,t.listIndent=t.blkIndent,t.blkIndent=l,t.tight=!0,t.tShift[$]=s-t.bMarks[$],t.sCount[$]=k,s>=b&&t.isEmpty($+1)?t.line=Math.min(t.line+2,i):t.md.block.tokenize(t,$,i,!0),(!t.tight||P)&&(Rt=!1),P=t.line-$>1&&t.isEmpty(t.line-1),t.blkIndent=t.listIndent,t.listIndent=x,t.tShift[$]=A,t.sCount[$]=y,t.tight=D,W=t.push("list_item_close","li",-1),W.markup=String.fromCharCode(w),$=t.line,d[1]=$,$>=i||t.sCount[$]=4)break;for(U=!1,a=0,f=et.length;a{"use strict";var jd=N().normalizeReference,pi=N().isSpace;ll.exports=function(t,e,i,r){var o,s,a,l,c,u,h,d,f,p,m,w,v,b,k,x,E=0,y=t.bMarks[e]+t.tShift[e],A=t.eMarks[e],D=e+1;if(t.sCount[e]-t.blkIndent>=4||t.src.charCodeAt(y)!==91)return!1;for(;++y3)&&!(t.sCount[D]<0)){for(b=!1,u=0,h=k.length;u"u"&&(t.env.references={}),typeof t.env.references[d]>"u"&&(t.env.references[d]={title:x,href:c}),t.parentType=p,t.line=e+E+1),!0)}});var hl=_((mv,ul)=>{"use strict";ul.exports=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","section","source","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"]});var io=_((gv,no)=>{"use strict";var Vd="[a-zA-Z_:][a-zA-Z0-9:._-]*",Wd="[^\"'=<>`\\x00-\\x20]+",Gd="'[^']*'",Kd='"[^"]*"',Zd="(?:"+Wd+"|"+Gd+"|"+Kd+")",Xd="(?:\\s+"+Vd+"(?:\\s*=\\s*"+Zd+")?)",dl="<[A-Za-z][A-Za-z0-9\\-]*"+Xd+"*\\s*\\/?>",pl="<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>",Yd="|",Jd="<[?][\\s\\S]*?[?]>",Qd="]*>",tp="",ep=new RegExp("^(?:"+dl+"|"+pl+"|"+Yd+"|"+Jd+"|"+Qd+"|"+tp+")"),np=new RegExp("^(?:"+dl+"|"+pl+")");no.exports.HTML_TAG_RE=ep;no.exports.HTML_OPEN_CLOSE_TAG_RE=np});var ml=_((bv,fl)=>{"use strict";var ip=hl(),rp=io().HTML_OPEN_CLOSE_TAG_RE,we=[[/^<(script|pre|style|textarea)(?=(\s|>|$))/i,/<\/(script|pre|style|textarea)>/i,!0],[/^/,!0],[/^<\?/,/\?>/,!0],[/^/,!0],[/^/,!0],[new RegExp("^|$))","i"),/^$/,!0],[new RegExp(rp.source+"\\s*$"),/^$/,!1]];fl.exports=function(t,e,i,r){var o,s,a,l,c=t.bMarks[e]+t.tShift[e],u=t.eMarks[e];if(t.sCount[e]-t.blkIndent>=4||!t.md.options.html||t.src.charCodeAt(c)!==60)return!1;for(l=t.src.slice(c,u),o=0;o{"use strict";var gl=N().isSpace;bl.exports=function(t,e,i,r){var o,s,a,l,c=t.bMarks[e]+t.tShift[e],u=t.eMarks[e];if(t.sCount[e]-t.blkIndent>=4||(o=t.src.charCodeAt(c),o!==35||c>=u))return!1;for(s=1,o=t.src.charCodeAt(++c);o===35&&c6||cc&&gl(t.src.charCodeAt(a-1))&&(u=a),t.line=e+1,l=t.push("heading_open","h"+String(s),1),l.markup="########".slice(0,s),l.map=[e,t.line],l=t.push("inline","",0),l.content=t.src.slice(c,u).trim(),l.map=[e,t.line],l.children=[],l=t.push("heading_close","h"+String(s),-1),l.markup="########".slice(0,s)),!0)}});var yl=_((wv,wl)=>{"use strict";wl.exports=function(t,e,i){var r,o,s,a,l,c,u,h,d,f=e+1,p,m=t.md.block.ruler.getRules("paragraph");if(t.sCount[e]-t.blkIndent>=4)return!1;for(p=t.parentType,t.parentType="paragraph";f3)){if(t.sCount[f]>=t.blkIndent&&(c=t.bMarks[f]+t.tShift[f],u=t.eMarks[f],c=u)))){h=d===61?1:2;break}if(!(t.sCount[f]<0)){for(o=!1,s=0,a=m.length;s{"use strict";xl.exports=function(t,e,i){var r,o,s,a,l,c,u=e+1,h=t.md.block.ruler.getRules("paragraph");for(c=t.parentType,t.parentType="paragraph";u3)&&!(t.sCount[u]<0)){for(o=!1,s=0,a=h.length;s{"use strict";var Cl=di(),fi=N().isSpace;function Lt(n,t,e,i){var r,o,s,a,l,c,u,h;for(this.src=n,this.md=t,this.env=e,this.tokens=i,this.bMarks=[],this.eMarks=[],this.tShift=[],this.sCount=[],this.bsCount=[],this.blkIndent=0,this.line=0,this.lineMax=0,this.tight=!1,this.ddIndent=-1,this.listIndent=-1,this.parentType="root",this.level=0,this.result="",o=this.src,h=!1,s=a=c=u=0,l=o.length;a0&&this.level++,this.tokens.push(i),i};Lt.prototype.isEmpty=function(t){return this.bMarks[t]+this.tShift[t]>=this.eMarks[t]};Lt.prototype.skipEmptyLines=function(t){for(var e=this.lineMax;te;)if(!fi(this.src.charCodeAt(--t)))return t+1;return t};Lt.prototype.skipChars=function(t,e){for(var i=this.src.length;ti;)if(e!==this.src.charCodeAt(--t))return t+1;return t};Lt.prototype.getLines=function(t,e,i,r){var o,s,a,l,c,u,h,d=t;if(t>=e)return"";for(u=new Array(e-t),o=0;di?u[o]=new Array(s-i+1).join(" ")+this.src.slice(l,c):u[o]=this.src.slice(l,c)}return u.join("")};Lt.prototype.Token=Cl;El.exports=Lt});var Al=_((kv,Sl)=>{"use strict";var op=ui(),mi=[["table",Ka(),["paragraph","reference"]],["code",Xa()],["fence",Ja(),["paragraph","reference","blockquote","list"]],["blockquote",tl(),["paragraph","reference","blockquote","list"]],["hr",nl(),["paragraph","reference","blockquote","list"]],["list",al(),["paragraph","reference","blockquote"]],["reference",cl()],["html_block",ml(),["paragraph","reference","blockquote"]],["heading",vl(),["paragraph","reference","blockquote"]],["lheading",yl()],["paragraph",kl()]];function gi(){this.ruler=new op;for(var n=0;n=e||n.sCount[l]=u){n.line=e;break}for(o=n.line,r=0;r=n.line)throw new Error("block rule didn't increment state.line");break}if(!i)throw new Error("none of the block rules matched");n.tight=!c,n.isEmpty(n.line-1)&&(c=!0),l=n.line,l{"use strict";function sp(n){switch(n){case 10:case 33:case 35:case 36:case 37:case 38:case 42:case 43:case 45:case 58:case 60:case 61:case 62:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 125:case 126:return!0;default:return!1}}Dl.exports=function(t,e){for(var i=t.pos;i{"use strict";var ap=/(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$/i;Tl.exports=function(t,e){var i,r,o,s,a,l,c,u;return!t.md.options.linkify||t.linkLevel>0||(i=t.pos,r=t.posMax,i+3>r)||t.src.charCodeAt(i)!==58||t.src.charCodeAt(i+1)!==47||t.src.charCodeAt(i+2)!==47||(o=t.pending.match(ap),!o)||(s=o[1],a=t.md.linkify.matchAtStart(t.src.slice(i-s.length)),!a)||(l=a.url,l.length<=s.length)||(l=l.replace(/\*+$/,""),c=t.md.normalizeLink(l),!t.md.validateLink(c))?!1:(e||(t.pending=t.pending.slice(0,-s.length),u=t.push("link_open","a",1),u.attrs=[["href",c]],u.markup="linkify",u.info="auto",u=t.push("text","",0),u.content=t.md.normalizeLinkText(l),u=t.push("link_close","a",-1),u.markup="linkify",u.info="auto"),t.pos+=l.length-s.length,!0)}});var Ml=_((_v,Il)=>{"use strict";var lp=N().isSpace;Il.exports=function(t,e){var i,r,o,s=t.pos;if(t.src.charCodeAt(s)!==10)return!1;if(i=t.pending.length-1,r=t.posMax,!e)if(i>=0&&t.pending.charCodeAt(i)===32)if(i>=1&&t.pending.charCodeAt(i-1)===32){for(o=i-1;o>=1&&t.pending.charCodeAt(o-1)===32;)o--;t.pending=t.pending.slice(0,o),t.push("hardbreak","br",0)}else t.pending=t.pending.slice(0,-1),t.push("softbreak","br",0);else t.push("softbreak","br",0);for(s++;s{"use strict";var cp=N().isSpace,oo=[];for(ro=0;ro<256;ro++)oo.push(0);var ro;"\\!\"#$%&'()*+,./:;<=>?@[]^_`{|}~-".split("").forEach(function(n){oo[n.charCodeAt(0)]=1});Fl.exports=function(t,e){var i,r,o,s,a,l=t.pos,c=t.posMax;if(t.src.charCodeAt(l)!==92||(l++,l>=c))return!1;if(i=t.src.charCodeAt(l),i===10){for(e||t.push("hardbreak","br",0),l++;l=55296&&i<=56319&&l+1=56320&&r<=57343&&(s+=t.src[l+1],l++)),o="\\"+s,e||(a=t.push("text_special","",0),i<256&&oo[i]!==0?a.content=s:a.content=o,a.markup=o,a.info="escape"),t.pos=l+1,!0}});var Pl=_((Av,Bl)=>{"use strict";Bl.exports=function(t,e){var i,r,o,s,a,l,c,u,h=t.pos,d=t.src.charCodeAt(h);if(d!==96)return!1;for(i=h,h++,r=t.posMax;h{"use strict";so.exports.tokenize=function(t,e){var i,r,o,s,a,l=t.pos,c=t.src.charCodeAt(l);if(e||c!==126||(r=t.scanDelims(t.pos,!0),s=r.length,a=String.fromCharCode(c),s<2))return!1;for(s%2&&(o=t.push("text","",0),o.content=a,s--),i=0;i{"use strict";lo.exports.tokenize=function(t,e){var i,r,o,s=t.pos,a=t.src.charCodeAt(s);if(e||a!==95&&a!==42)return!1;for(r=t.scanDelims(t.pos,a===42),i=0;i=0;e--)i=t[e],!(i.marker!==95&&i.marker!==42)&&i.end!==-1&&(r=t[i.end],a=e>0&&t[e-1].end===i.end+1&&t[e-1].marker===i.marker&&t[e-1].token===i.token-1&&t[i.end+1].token===r.token+1,s=String.fromCharCode(i.marker),o=n.tokens[i.token],o.type=a?"strong_open":"em_open",o.tag=a?"strong":"em",o.nesting=1,o.markup=a?s+s:s,o.content="",o=n.tokens[r.token],o.type=a?"strong_close":"em_close",o.tag=a?"strong":"em",o.nesting=-1,o.markup=a?s+s:s,o.content="",a&&(n.tokens[t[e-1].token].content="",n.tokens[t[i.end+1].token].content="",e--))}lo.exports.postProcess=function(t){var e,i=t.tokens_meta,r=t.tokens_meta.length;for(Rl(t,t.delimiters),e=0;e{"use strict";var up=N().normalizeReference,uo=N().isSpace;Nl.exports=function(t,e){var i,r,o,s,a,l,c,u,h,d="",f="",p=t.pos,m=t.posMax,w=t.pos,v=!0;if(t.src.charCodeAt(t.pos)!==91||(a=t.pos+1,s=t.md.helpers.parseLinkLabel(t,t.pos,!0),s<0))return!1;if(l=s+1,l=m)return!1;if(w=l,c=t.md.helpers.parseLinkDestination(t.src,l,t.posMax),c.ok){for(d=t.md.normalizeLink(c.str),t.md.validateLink(d)?l=c.pos:d="",w=l;l=m||t.src.charCodeAt(l)!==41)&&(v=!0),l++}if(v){if(typeof t.env.references>"u")return!1;if(l=0?o=t.src.slice(w,l++):l=s+1):l=s+1,o||(o=t.src.slice(a,s)),u=t.env.references[up(o)],!u)return t.pos=p,!1;d=u.href,f=u.title}return e||(t.pos=a,t.posMax=s,h=t.push("link_open","a",1),h.attrs=i=[["href",d]],f&&i.push(["title",f]),t.linkLevel++,t.md.inline.tokenize(t),t.linkLevel--,h=t.push("link_close","a",-1)),t.pos=l,t.posMax=m,!0}});var Ul=_(($v,Hl)=>{"use strict";var hp=N().normalizeReference,ho=N().isSpace;Hl.exports=function(t,e){var i,r,o,s,a,l,c,u,h,d,f,p,m,w="",v=t.pos,b=t.posMax;if(t.src.charCodeAt(t.pos)!==33||t.src.charCodeAt(t.pos+1)!==91||(l=t.pos+2,a=t.md.helpers.parseLinkLabel(t,t.pos+1,!1),a<0))return!1;if(c=a+1,c=b)return!1;for(m=c,h=t.md.helpers.parseLinkDestination(t.src,c,t.posMax),h.ok&&(w=t.md.normalizeLink(h.str),t.md.validateLink(w)?c=h.pos:w=""),m=c;c=b||t.src.charCodeAt(c)!==41)return t.pos=v,!1;c++}else{if(typeof t.env.references>"u")return!1;if(c=0?s=t.src.slice(m,c++):c=a+1):c=a+1,s||(s=t.src.slice(l,a)),u=t.env.references[hp(s)],!u)return t.pos=v,!1;w=u.href,d=u.title}return e||(o=t.src.slice(l,a),t.md.inline.parse(o,t.md,t.env,p=[]),f=t.push("image","img",0),f.attrs=i=[["src",w],["alt",""]],f.children=p,f.content=o,d&&i.push(["title",d])),t.pos=c,t.posMax=b,!0}});var Vl=_((Iv,jl)=>{"use strict";var dp=/^([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/,pp=/^([a-zA-Z][a-zA-Z0-9+.\-]{1,31}):([^<>\x00-\x20]*)$/;jl.exports=function(t,e){var i,r,o,s,a,l,c=t.pos;if(t.src.charCodeAt(c)!==60)return!1;for(a=t.pos,l=t.posMax;;){if(++c>=l||(s=t.src.charCodeAt(c),s===60))return!1;if(s===62)break}return i=t.src.slice(a+1,c),pp.test(i)?(r=t.md.normalizeLink(i),t.md.validateLink(r)?(e||(o=t.push("link_open","a",1),o.attrs=[["href",r]],o.markup="autolink",o.info="auto",o=t.push("text","",0),o.content=t.md.normalizeLinkText(i),o=t.push("link_close","a",-1),o.markup="autolink",o.info="auto"),t.pos+=i.length+2,!0):!1):dp.test(i)?(r=t.md.normalizeLink("mailto:"+i),t.md.validateLink(r)?(e||(o=t.push("link_open","a",1),o.attrs=[["href",r]],o.markup="autolink",o.info="auto",o=t.push("text","",0),o.content=t.md.normalizeLinkText(i),o=t.push("link_close","a",-1),o.markup="autolink",o.info="auto"),t.pos+=i.length+2,!0):!1):!1}});var Gl=_((Mv,Wl)=>{"use strict";var fp=io().HTML_TAG_RE;function mp(n){return/^\s]/i.test(n)}function gp(n){return/^<\/a\s*>/i.test(n)}function bp(n){var t=n|32;return t>=97&&t<=122}Wl.exports=function(t,e){var i,r,o,s,a=t.pos;return!t.md.options.html||(o=t.posMax,t.src.charCodeAt(a)!==60||a+2>=o)||(i=t.src.charCodeAt(a+1),i!==33&&i!==63&&i!==47&&!bp(i))||(r=t.src.slice(a).match(fp),!r)?!1:(e||(s=t.push("html_inline","",0),s.content=r[0],mp(s.content)&&t.linkLevel++,gp(s.content)&&t.linkLevel--),t.pos+=r[0].length,!0)}});var Yl=_((Fv,Xl)=>{"use strict";var Kl=Gr(),vp=N().has,wp=N().isValidEntityCode,Zl=N().fromCodePoint,yp=/^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i,xp=/^&([a-z][a-z0-9]{1,31});/i;Xl.exports=function(t,e){var i,r,o,s,a=t.pos,l=t.posMax;if(t.src.charCodeAt(a)!==38||a+1>=l)return!1;if(i=t.src.charCodeAt(a+1),i===35){if(o=t.src.slice(a).match(yp),o)return e||(r=o[1][0].toLowerCase()==="x"?parseInt(o[1].slice(1),16):parseInt(o[1],10),s=t.push("text_special","",0),s.content=wp(r)?Zl(r):Zl(65533),s.markup=o[0],s.info="entity"),t.pos+=o[0].length,!0}else if(o=t.src.slice(a).match(xp),o&&vp(Kl,o[1]))return e||(s=t.push("text_special","",0),s.content=Kl[o[1]],s.markup=o[0],s.info="entity"),t.pos+=o[0].length,!0;return!1}});var tc=_((qv,Ql)=>{"use strict";function Jl(n){var t,e,i,r,o,s,a,l,c={},u=n.length;if(u){var h=0,d=-2,f=[];for(t=0;to;e-=f[e]+1)if(r=n[e],r.marker===i.marker&&r.open&&r.end<0&&(a=!1,(r.close||i.open)&&(r.length+i.length)%3===0&&(r.length%3!==0||i.length%3!==0)&&(a=!0),!a)){l=e>0&&!n[e-1].open?f[e-1]+1:0,f[t]=t-e+l,f[e]=l,i.open=!1,r.end=t,r.close=!1,s=-1,d=-2;break}s!==-1&&(c[i.marker][(i.open?3:0)+(i.length||0)%3]=s)}}}Ql.exports=function(t){var e,i=t.tokens_meta,r=t.tokens_meta.length;for(Jl(t.delimiters),e=0;e{"use strict";ec.exports=function(t){var e,i,r=0,o=t.tokens,s=t.tokens.length;for(e=i=0;e0&&r++,o[e].type==="text"&&e+1{"use strict";var po=di(),ic=N().isWhiteSpace,rc=N().isPunctChar,oc=N().isMdAsciiPunct;function Ze(n,t,e,i){this.src=n,this.env=e,this.md=t,this.tokens=i,this.tokens_meta=Array(i.length),this.pos=0,this.posMax=this.src.length,this.level=0,this.pending="",this.pendingLevel=0,this.cache={},this.delimiters=[],this._prev_delimiters=[],this.backticks={},this.backticksScanned=!1,this.linkLevel=0}Ze.prototype.pushPending=function(){var n=new po("text","",0);return n.content=this.pending,n.level=this.pendingLevel,this.tokens.push(n),this.pending="",n};Ze.prototype.push=function(n,t,e){this.pending&&this.pushPending();var i=new po(n,t,e),r=null;return e<0&&(this.level--,this.delimiters=this._prev_delimiters.pop()),i.level=this.level,e>0&&(this.level++,this._prev_delimiters.push(this.delimiters),this.delimiters=[],r={delimiters:this.delimiters}),this.pendingLevel=this.level,this.tokens.push(i),this.tokens_meta.push(r),i};Ze.prototype.scanDelims=function(n,t){var e=n,i,r,o,s,a,l,c,u,h,d=!0,f=!0,p=this.posMax,m=this.src.charCodeAt(n);for(i=n>0?this.src.charCodeAt(n-1):32;e{"use strict";var lc=ui(),fo=[["text",Ll()],["linkify",$l()],["newline",Ml()],["escape",ql()],["backticks",Pl()],["strikethrough",ao().tokenize],["emphasis",co().tokenize],["link",zl()],["image",Ul()],["autolink",Vl()],["html_inline",Gl()],["entity",Yl()]],mo=[["balance_pairs",tc()],["strikethrough",ao().postProcess],["emphasis",co().postProcess],["fragments_join",nc()]];function Xe(){var n;for(this.ruler=new lc,n=0;n=n.pos)throw new Error("inline rule didn't increment state.pos");break}}else n.pos=n.posMax;t||n.pos++,a[i]=n.pos};Xe.prototype.tokenize=function(n){for(var t,e,i,r=this.ruler.getRules(""),o=r.length,s=n.posMax,a=n.md.options.maxNesting;n.pos=n.pos)throw new Error("inline rule didn't increment state.pos");break}}if(t){if(n.pos>=s)break;continue}n.pending+=n.src[n.pos++]}n.pending&&n.pushPending()};Xe.prototype.parse=function(n,t,e,i){var r,o,s,a=new this.State(n,t,e,i);for(this.tokenize(a),o=this.ruler2.getRules(""),s=o.length,r=0;r{"use strict";hc.exports=function(n){var t={};n=n||{},t.src_Any=Zr().source,t.src_Cc=Xr().source,t.src_Z=Yr().source,t.src_P=oi().source,t.src_ZPCc=[t.src_Z,t.src_P,t.src_Cc].join("|"),t.src_ZCc=[t.src_Z,t.src_Cc].join("|");var e="[><\uFF5C]";return t.src_pseudo_letter="(?:(?!"+e+"|"+t.src_ZPCc+")"+t.src_Any+")",t.src_ip4="(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",t.src_auth="(?:(?:(?!"+t.src_ZCc+"|[@/\\[\\]()]).)+@)?",t.src_port="(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?",t.src_host_terminator="(?=$|"+e+"|"+t.src_ZPCc+")(?!"+(n["---"]?"-(?!--)|":"-|")+"_|:\\d|\\.-|\\.(?!$|"+t.src_ZPCc+"))",t.src_path="(?:[/?#](?:(?!"+t.src_ZCc+"|"+e+`|[()[\\]{}.,"'?!\\-;]).|\\[(?:(?!`+t.src_ZCc+"|\\]).)*\\]|\\((?:(?!"+t.src_ZCc+"|[)]).)*\\)|\\{(?:(?!"+t.src_ZCc+'|[}]).)*\\}|\\"(?:(?!'+t.src_ZCc+`|["]).)+\\"|\\'(?:(?!`+t.src_ZCc+"|[']).)+\\'|\\'(?="+t.src_pseudo_letter+"|[-])|\\.{2,}[a-zA-Z0-9%/&]|\\.(?!"+t.src_ZCc+"|[.]|$)|"+(n["---"]?"\\-(?!--(?:[^-]|$))(?:-*)|":"\\-+|")+",(?!"+t.src_ZCc+"|$)|;(?!"+t.src_ZCc+"|$)|\\!+(?!"+t.src_ZCc+"|[!]|$)|\\?(?!"+t.src_ZCc+"|[?]|$))+|\\/)?",t.src_email_name='[\\-;:&=\\+\\$,\\.a-zA-Z0-9_][\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]*',t.src_xn="xn--[a-z0-9\\-]{1,59}",t.src_domain_root="(?:"+t.src_xn+"|"+t.src_pseudo_letter+"{1,63})",t.src_domain="(?:"+t.src_xn+"|(?:"+t.src_pseudo_letter+")|(?:"+t.src_pseudo_letter+"(?:-|"+t.src_pseudo_letter+"){0,61}"+t.src_pseudo_letter+"))",t.src_host="(?:(?:(?:(?:"+t.src_domain+")\\.)*"+t.src_domain+"))",t.tpl_host_fuzzy="(?:"+t.src_ip4+"|(?:(?:(?:"+t.src_domain+")\\.)+(?:%TLDS%)))",t.tpl_host_no_ip_fuzzy="(?:(?:(?:"+t.src_domain+")\\.)+(?:%TLDS%))",t.src_host_strict=t.src_host+t.src_host_terminator,t.tpl_host_fuzzy_strict=t.tpl_host_fuzzy+t.src_host_terminator,t.src_host_port_strict=t.src_host+t.src_port+t.src_host_terminator,t.tpl_host_port_fuzzy_strict=t.tpl_host_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_port_no_ip_fuzzy_strict=t.tpl_host_no_ip_fuzzy+t.src_port+t.src_host_terminator,t.tpl_host_fuzzy_test="localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:"+t.src_ZPCc+"|>|$))",t.tpl_email_fuzzy="(^|"+e+'|"|\\(|'+t.src_ZCc+")("+t.src_email_name+"@"+t.tpl_host_fuzzy_strict+")",t.tpl_link_fuzzy="(^|(?![.:/\\-_@])(?:[$+<=>^`|\uFF5C]|"+t.src_ZPCc+"))((?![$+<=>^`|\uFF5C])"+t.tpl_host_port_fuzzy_strict+t.src_path+")",t.tpl_link_no_ip_fuzzy="(^|(?![.:/\\-_@])(?:[$+<=>^`|\uFF5C]|"+t.src_ZPCc+"))((?![$+<=>^`|\uFF5C])"+t.tpl_host_port_no_ip_fuzzy_strict+t.src_path+")",t}});var bc=_((Nv,gc)=>{"use strict";function go(n){var t=Array.prototype.slice.call(arguments,1);return t.forEach(function(e){e&&Object.keys(e).forEach(function(i){n[i]=e[i]})}),n}function vi(n){return Object.prototype.toString.call(n)}function kp(n){return vi(n)==="[object String]"}function Cp(n){return vi(n)==="[object Object]"}function Ep(n){return vi(n)==="[object RegExp]"}function pc(n){return vi(n)==="[object Function]"}function _p(n){return n.replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}var mc={fuzzyLink:!0,fuzzyEmail:!0,fuzzyIP:!1};function Sp(n){return Object.keys(n||{}).reduce(function(t,e){return t||mc.hasOwnProperty(e)},!1)}var Ap={"http:":{validate:function(n,t,e){var i=n.slice(t);return e.re.http||(e.re.http=new RegExp("^\\/\\/"+e.re.src_auth+e.re.src_host_port_strict+e.re.src_path,"i")),e.re.http.test(i)?i.match(e.re.http)[0].length:0}},"https:":"http:","ftp:":"http:","//":{validate:function(n,t,e){var i=n.slice(t);return e.re.no_http||(e.re.no_http=new RegExp("^"+e.re.src_auth+"(?:localhost|(?:(?:"+e.re.src_domain+")\\.)+"+e.re.src_domain_root+")"+e.re.src_port+e.re.src_host_terminator+e.re.src_path,"i")),e.re.no_http.test(i)?t>=3&&n[t-3]===":"||t>=3&&n[t-3]==="/"?0:i.match(e.re.no_http)[0].length:0}},"mailto:":{validate:function(n,t,e){var i=n.slice(t);return e.re.mailto||(e.re.mailto=new RegExp("^"+e.re.src_email_name+"@"+e.re.src_host_strict,"i")),e.re.mailto.test(i)?i.match(e.re.mailto)[0].length:0}}},Dp="a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]",Lp="biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|\u0440\u0444".split("|");function Tp(n){n.__index__=-1,n.__text_cache__=""}function $p(n){return function(t,e){var i=t.slice(e);return n.test(i)?i.match(n)[0].length:0}}function fc(){return function(n,t){t.normalize(n)}}function bi(n){var t=n.re=dc()(n.__opts__),e=n.__tlds__.slice();n.onCompile(),n.__tlds_replaced__||e.push(Dp),e.push(t.src_xn),t.src_tlds=e.join("|");function i(a){return a.replace("%TLDS%",t.src_tlds)}t.email_fuzzy=RegExp(i(t.tpl_email_fuzzy),"i"),t.link_fuzzy=RegExp(i(t.tpl_link_fuzzy),"i"),t.link_no_ip_fuzzy=RegExp(i(t.tpl_link_no_ip_fuzzy),"i"),t.host_fuzzy_test=RegExp(i(t.tpl_host_fuzzy_test),"i");var r=[];n.__compiled__={};function o(a,l){throw new Error('(LinkifyIt) Invalid schema "'+a+'": '+l)}Object.keys(n.__schemas__).forEach(function(a){var l=n.__schemas__[a];if(l!==null){var c={validate:null,link:null};if(n.__compiled__[a]=c,Cp(l)){Ep(l.validate)?c.validate=$p(l.validate):pc(l.validate)?c.validate=l.validate:o(a,l),pc(l.normalize)?c.normalize=l.normalize:l.normalize?o(a,l):c.normalize=fc();return}if(kp(l)){r.push(a);return}o(a,l)}}),r.forEach(function(a){n.__compiled__[n.__schemas__[a]]&&(n.__compiled__[a].validate=n.__compiled__[n.__schemas__[a]].validate,n.__compiled__[a].normalize=n.__compiled__[n.__schemas__[a]].normalize)}),n.__compiled__[""]={validate:null,normalize:fc()};var s=Object.keys(n.__compiled__).filter(function(a){return a.length>0&&n.__compiled__[a]}).map(_p).join("|");n.re.schema_test=RegExp("(^|(?!_)(?:[><\uFF5C]|"+t.src_ZPCc+"))("+s+")","i"),n.re.schema_search=RegExp("(^|(?!_)(?:[><\uFF5C]|"+t.src_ZPCc+"))("+s+")","ig"),n.re.schema_at_start=RegExp("^"+n.re.schema_search.source,"i"),n.re.pretest=RegExp("("+n.re.schema_test.source+")|("+n.re.host_fuzzy_test.source+")|@","i"),Tp(n)}function Ip(n,t){var e=n.__index__,i=n.__last_index__,r=n.__text_cache__.slice(e,i);this.schema=n.__schema__.toLowerCase(),this.index=e+t,this.lastIndex=i+t,this.raw=r,this.text=r,this.url=r}function bo(n,t){var e=new Ip(n,t);return n.__compiled__[e.schema].normalize(e,n),e}function gt(n,t){if(!(this instanceof gt))return new gt(n,t);t||Sp(n)&&(t=n,n={}),this.__opts__=go({},mc,t),this.__index__=-1,this.__last_index__=-1,this.__schema__="",this.__text_cache__="",this.__schemas__=go({},Ap,n),this.__compiled__={},this.__tlds__=Lp,this.__tlds_replaced__=!1,this.re={},bi(this)}gt.prototype.add=function(t,e){return this.__schemas__[t]=e,bi(this),this};gt.prototype.set=function(t){return this.__opts__=go(this.__opts__,t),this};gt.prototype.test=function(t){if(this.__text_cache__=t,this.__index__=-1,!t.length)return!1;var e,i,r,o,s,a,l,c,u;if(this.re.schema_test.test(t)){for(l=this.re.schema_search,l.lastIndex=0;(e=l.exec(t))!==null;)if(o=this.testSchemaAt(t,e[2],l.lastIndex),o){this.__schema__=e[2],this.__index__=e.index+e[1].length,this.__last_index__=e.index+e[0].length+o;break}}return this.__opts__.fuzzyLink&&this.__compiled__["http:"]&&(c=t.search(this.re.host_fuzzy_test),c>=0&&(this.__index__<0||c=0&&(r=t.match(this.re.email_fuzzy))!==null&&(s=r.index+r[1].length,a=r.index+r[0].length,(this.__index__<0||sthis.__last_index__)&&(this.__schema__="mailto:",this.__index__=s,this.__last_index__=a))),this.__index__>=0};gt.prototype.pretest=function(t){return this.re.pretest.test(t)};gt.prototype.testSchemaAt=function(t,e,i){return this.__compiled__[e.toLowerCase()]?this.__compiled__[e.toLowerCase()].validate(t,i,this):0};gt.prototype.match=function(t){var e=0,i=[];this.__index__>=0&&this.__text_cache__===t&&(i.push(bo(this,e)),e=this.__last_index__);for(var r=e?t.slice(e):t;this.test(r);)i.push(bo(this,e)),r=r.slice(this.__last_index__),e+=this.__last_index__;return i.length?i:null};gt.prototype.matchAtStart=function(t){if(this.__text_cache__=t,this.__index__=-1,!t.length)return null;var e=this.re.schema_at_start.exec(t);if(!e)return null;var i=this.testSchemaAt(t,e[2],e[0].length);return i?(this.__schema__=e[2],this.__index__=e.index+e[1].length,this.__last_index__=e.index+e[0].length+i,bo(this,0)):null};gt.prototype.tlds=function(t,e){return t=Array.isArray(t)?t:[t],e?(this.__tlds__=this.__tlds__.concat(t).sort().filter(function(i,r,o){return i!==o[r-1]}).reverse(),bi(this),this):(this.__tlds__=t.slice(),this.__tlds_replaced__=!0,bi(this),this)};gt.prototype.normalize=function(t){t.schema||(t.url="http://"+t.url),t.schema==="mailto:"&&!/^mailto:/i.test(t.url)&&(t.url="mailto:"+t.url)};gt.prototype.onCompile=function(){};gc.exports=gt});var _c={};Se(_c,{decode:()=>xo,default:()=>Np,encode:()=>ko,toASCII:()=>Ec,toUnicode:()=>Cc,ucs2decode:()=>yo,ucs2encode:()=>xc});function Vt(n){throw new RangeError(Bp[n])}function Pp(n,t){let e=[],i=n.length;for(;i--;)e[i]=t(n[i]);return e}function yc(n,t){let e=n.split("@"),i="";e.length>1&&(i=e[0]+"@",n=e[1]),n=n.replace(qp,".");let r=n.split("."),o=Pp(r,t).join(".");return i+o}function yo(n){let t=[],e=0,i=n.length;for(;e=55296&&r<=56319&&e{"use strict";wc="-",Mp=/^xn--/,Fp=/[^\0-\x7F]/,qp=/[\x2E\u3002\uFF0E\uFF61]/g,Bp={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},vo=36-1,Tt=Math.floor,wo=String.fromCharCode;xc=n=>String.fromCodePoint(...n),Op=function(n){return n>=48&&n<58?26+(n-48):n>=65&&n<91?n-65:n>=97&&n<123?n-97:36},vc=function(n,t){return n+22+75*(n<26)-((t!=0)<<5)},kc=function(n,t,e){let i=0;for(n=e?Tt(n/700):n>>1,n+=Tt(n/t);n>vo*26>>1;i+=36)n=Tt(n/vo);return Tt(i+(vo+1)*n/(n+38))},xo=function(n){let t=[],e=n.length,i=0,r=128,o=72,s=n.lastIndexOf(wc);s<0&&(s=0);for(let a=0;a=128&&Vt("not-basic"),t.push(n.charCodeAt(a));for(let a=s>0?s+1:0;a=e&&Vt("invalid-input");let d=Op(n.charCodeAt(a++));d>=36&&Vt("invalid-input"),d>Tt((2147483647-i)/u)&&Vt("overflow"),i+=d*u;let f=h<=o?1:h>=o+26?26:h-o;if(dTt(2147483647/p)&&Vt("overflow"),u*=p}let c=t.length+1;o=kc(i-l,c,l==0),Tt(i/c)>2147483647-r&&Vt("overflow"),r+=Tt(i/c),i%=c,t.splice(i++,0,r)}return String.fromCodePoint(...t)},ko=function(n){let t=[];n=yo(n);let e=n.length,i=128,r=0,o=72;for(let l of n)l<128&&t.push(wo(l));let s=t.length,a=s;for(s&&t.push(wc);a=i&&uTt((2147483647-r)/c)&&Vt("overflow"),r+=(l-i)*c,i=l;for(let u of n)if(u2147483647&&Vt("overflow"),u===i){let h=r;for(let d=36;;d+=36){let f=d<=o?1:d>=o+26?26:d-o;if(h{"use strict";Ac.exports={options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"\u201C\u201D\u2018\u2019",highlight:null,maxNesting:100},components:{core:{},block:{},inline:{}}}});var Tc=_((Hv,Lc)=>{"use strict";Lc.exports={options:{html:!1,xhtmlOut:!1,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"\u201C\u201D\u2018\u2019",highlight:null,maxNesting:20},components:{core:{rules:["normalize","block","inline","text_join"]},block:{rules:["paragraph"]},inline:{rules:["text"],rules2:["balance_pairs","fragments_join"]}}}});var Ic=_((Uv,$c)=>{"use strict";$c.exports={options:{html:!0,xhtmlOut:!0,breaks:!1,langPrefix:"language-",linkify:!1,typographer:!1,quotes:"\u201C\u201D\u2018\u2019",highlight:null,maxNesting:20},components:{core:{rules:["normalize","block","inline","text_join"]},block:{rules:["blockquote","code","fence","heading","hr","html_block","lheading","list","reference","paragraph"]},inline:{rules:["autolink","backticks","emphasis","entity","escape","html_inline","image","link","newline","text"],rules2:["balance_pairs","emphasis","fragments_join"]}}}});var Bc=_((jv,qc)=>{"use strict";var Ye=N(),zp=ga(),Hp=va(),Up=Va(),jp=Al(),Vp=uc(),Wp=bc(),Qt=Kr(),Mc=(Sc(),Uu(_c)),Gp={default:Dc(),zero:Tc(),commonmark:Ic()},Kp=/^(vbscript|javascript|file|data):/,Zp=/^data:image\/(gif|png|jpeg|webp);/;function Xp(n){var t=n.trim().toLowerCase();return Kp.test(t)?!!Zp.test(t):!0}var Fc=["http:","https:","mailto:"];function Yp(n){var t=Qt.parse(n,!0);if(t.hostname&&(!t.protocol||Fc.indexOf(t.protocol)>=0))try{t.hostname=Mc.toASCII(t.hostname)}catch{}return Qt.encode(Qt.format(t))}function Jp(n){var t=Qt.parse(n,!0);if(t.hostname&&(!t.protocol||Fc.indexOf(t.protocol)>=0))try{t.hostname=Mc.toUnicode(t.hostname)}catch{}return Qt.decode(Qt.format(t),Qt.decode.defaultChars+"%")}function bt(n,t){if(!(this instanceof bt))return new bt(n,t);t||Ye.isString(n)||(t=n||{},n="default"),this.inline=new Vp,this.block=new jp,this.core=new Up,this.renderer=new Hp,this.linkify=new Wp,this.validateLink=Xp,this.normalizeLink=Yp,this.normalizeLinkText=Jp,this.utils=Ye,this.helpers=Ye.assign({},zp),this.options={},this.configure(n),t&&this.set(t)}bt.prototype.set=function(n){return Ye.assign(this.options,n),this};bt.prototype.configure=function(n){var t=this,e;if(Ye.isString(n)&&(e=n,n=Gp[e],!n))throw new Error('Wrong `markdown-it` preset "'+e+'", check name');if(!n)throw new Error("Wrong `markdown-it` preset, can't be empty");return n.options&&t.set(n.options),n.components&&Object.keys(n.components).forEach(function(i){n.components[i].rules&&t[i].ruler.enableOnly(n.components[i].rules),n.components[i].rules2&&t[i].ruler2.enableOnly(n.components[i].rules2)}),this};bt.prototype.enable=function(n,t){var e=[];Array.isArray(n)||(n=[n]),["core","block","inline"].forEach(function(r){e=e.concat(this[r].ruler.enable(n,!0))},this),e=e.concat(this.inline.ruler2.enable(n,!0));var i=n.filter(function(r){return e.indexOf(r)<0});if(i.length&&!t)throw new Error("MarkdownIt. Failed to enable unknown rule(s): "+i);return this};bt.prototype.disable=function(n,t){var e=[];Array.isArray(n)||(n=[n]),["core","block","inline"].forEach(function(r){e=e.concat(this[r].ruler.disable(n,!0))},this),e=e.concat(this.inline.ruler2.disable(n,!0));var i=n.filter(function(r){return e.indexOf(r)<0});if(i.length&&!t)throw new Error("MarkdownIt. Failed to disable unknown rule(s): "+i);return this};bt.prototype.use=function(n){var t=[this].concat(Array.prototype.slice.call(arguments,1));return n.apply(n,t),this};bt.prototype.parse=function(n,t){if(typeof n!="string")throw new Error("Input data should be a String");var e=new this.core.State(n,this,t);return this.core.process(e),e.tokens};bt.prototype.render=function(n,t){return t=t||{},this.renderer.render(this.parse(n,t),this.options,t)};bt.prototype.parseInline=function(n,t){var e=new this.core.State(n,this,t);return e.inlineMode=!0,this.core.process(e),e.tokens};bt.prototype.renderInline=function(n,t){return t=t||{},this.renderer.render(this.parseInline(n,t),this.options,t)};qc.exports=bt});var Oc=_((Vv,Pc)=>{"use strict";Pc.exports=Bc()});var Uc=_((Wv,Hc)=>{var Co=!0,Nc=!1,zc=!1;Hc.exports=function(n,t){t&&(Co=!t.enabled,Nc=!!t.label,zc=!!t.labelAfter),n.core.ruler.after("inline","github-task-lists",function(e){for(var i=e.tokens,r=2;r=0;i--)if(n[i].level===e)return i;return-1}function tf(n,t){return af(n[t])&&lf(n[t-1])&&cf(n[t-2])&&uf(n[t])}function ef(n,t){if(n.children.unshift(nf(n,t)),n.children[1].content=n.children[1].content.slice(3),n.content=n.content.slice(3),Nc)if(zc){n.children.pop();var e="task-item-"+Math.ceil(Math.random()*(1e4*1e3)-1e3);n.children[0].content=n.children[0].content.slice(0,-1)+' id="'+e+'">',n.children.push(sf(n.content,e,t))}else n.children.unshift(rf(t)),n.children.push(of(t))}function nf(n,t){var e=new t("html_inline","",0),i=Co?' disabled="" ':"";return n.content.indexOf("[ ] ")===0?e.content='':(n.content.indexOf("[x] ")===0||n.content.indexOf("[X] ")===0)&&(e.content=''),e}function rf(n){var t=new n("html_inline","",0);return t.content="",t}function sf(n,t,e){var i=new e("html_inline","",0);return i.content='",i.attrs=[{for:t}],i}function af(n){return n.type==="inline"}function lf(n){return n.type==="paragraph_open"}function cf(n){return n.type==="list_item_open"}function uf(n){return n.content.indexOf("[ ] ")===0||n.content.indexOf("[x] ")===0||n.content.indexOf("[X] ")===0}});var pr={};Se(pr,{emit:()=>hr,emitPublic:()=>Gu,error:()=>dr,listen:()=>Wu,showResponseError:()=>Xu,showValidationErrors:()=>Zu,success:()=>Ku});var on={},Vu=[];function hr(n,t){Vu.push({name:n,data:t});let e=on[n]||[];for(let i of e)i(t)}function Wu(n,t){typeof on[n]>"u"&&(on[n]=[]),on[n].push(t)}function Gu(n,t,e){let i=new CustomEvent(t,{detail:e,bubbles:!0});n.dispatchEvent(i)}function Ku(n){hr("success",n)}function dr(n){hr("error",n)}function Zu(n){if(n.status&&n.status===422&&n.data){let t=Object.values(n.data).flat().join(` -`);dr(t)}}function Xu(n){n.status&&n.status>=400&&n.data&&n.data.message&&dr(n.data.message)}var fr={};Se(fr,{HttpError:()=>sn,createXMLHttpRequest:()=>Ju,delete:()=>ih,get:()=>Qu,patch:()=>nh,post:()=>th,put:()=>eh});async function Yu(n){if(n.status===204)return null;let e=(n.headers.get("Content-Type")||"").split(";")[0].split("/").pop();return e==="javascript"||e==="json"?n.json():n.text()}var sn=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 Ju(n,t,e={}){let i=document.querySelector("meta[name=token]").getAttribute("content"),r=new XMLHttpRequest;for(let[o,s]of Object.entries(e))r.addEventListener(o,s.bind(r));return r.open(n,t),r.withCredentials=!0,r.setRequestHeader("X-CSRF-TOKEN",i),r}async function Ko(n,t={}){let e=n;if(e.startsWith("http")||(e=window.baseUrl(e)),t.params){let l=new URL(e);for(let c of Object.keys(t.params)){let u=t.params[c];typeof u<"u"&&u!==null&&l.searchParams.set(c,u)}e=l.toString()}let i=document.querySelector("meta[name=token]").getAttribute("content"),r={...t,credentials:"same-origin"};r.headers={...r.headers||{},baseURL:window.baseUrl(""),"X-CSRF-TOKEN":i};let o=await fetch(e,r),s=await Yu(o),a={data:s,headers:o.headers,redirected:o.redirected,status:o.status,statusText:o.statusText,url:o.url,original:o};if(!o.ok)throw new sn(o,s);return a}async function an(n,t,e=null){let i={method:n,body:e};return typeof e=="object"&&!(e instanceof FormData)&&(i.headers={"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},i.body=JSON.stringify(e)),e instanceof FormData&&n!=="post"&&(e.append("_method",n),i.method="post"),Ko(t,i)}async function Qu(n,t={}){return Ko(n,{method:"GET",params:t})}async function th(n,t=null){return an("POST",n,t)}async function eh(n,t=null){return an("PUT",n,t)}async function nh(n,t=null){return an("PATCH",n,t)}async function ih(n,t=null){return an("DELETE",n,t)}var mr=class{constructor(){this.store=new Map,this.parseTranslations()}parseTranslations(){let t=document.querySelectorAll('meta[name="translation"]');for(let e of t){let i=e.getAttribute("key"),r=e.getAttribute("value");this.store.set(i,r)}}get(t,e){let i=this.getTransText(t);return this.performReplacements(i,e)}getPlural(t,e,i){let r=this.getTransText(t);return this.parsePlural(r,e,i)}parsePlural(t,e,i){let r=t.split("|"),o=/^{([0-9]+)}/,s=/^\[([0-9]+),([0-9*]+)]/,a=null;for(let l of r){let c=l.match(o);if(c!==null&&Number(c[1])===e){a=l.replace(o,"").trim();break}let u=l.match(s);if(u!==null&&Number(u[1])<=e&&(u[2]==="*"||Number(u[2])>=e)){a=l.replace(s,"").trim();break}}return a===null&&r.length>1&&(a=e===1?r[0]:r[1]),a===null&&(a=r[0]),this.performReplacements(a,i)}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 i=t.match(/:(\S+)/g);if(i===null)return t;let r=t;return i.forEach(o=>{let s=o.substring(1);typeof e[s]>"u"||(r=r.replace(o,e[s]))}),r}},Zo=mr;var yr={};Se(yr,{first:()=>ah,firstOnElement:()=>ch,get:()=>lh,init:()=>vr,register:()=>wr});function gr(n){let t=i=>i.slice(0,1).toUpperCase()+i.slice(1),e=n.split("-");return e[0]+e.slice(1).map(t).join("")}function Xo(n){return n.replace(/[A-Z]/g,(t,e)=>(e>0?"-":"")+t.toLowerCase())}var Ae={},Yo={},br=new WeakMap;function rh(n,t){let e={},i={},r=`${n}@`,o=`[refs*="${r}"]`,s=[...t.querySelectorAll(o)];t.matches(o)&&s.push(t);for(let a of s){let l=a.getAttribute("refs").split(" ").filter(c=>c.startsWith(r)).map(c=>c.replace(r,"")).map(gr);for(let c of l)e[c]=a,typeof i[c]>"u"&&(i[c]=[]),i[c].push(a)}return{refs:e,manyRefs:i}}function oh(n,t){let e={},i=`option:${n}:`;for(let{name:r,value:o}of t.attributes)if(r.startsWith(i)){let s=r.replace(i,"");e[gr(s)]=o||""}return e}function sh(n,t){let e=Yo[n];if(e===void 0)return;let i;try{i=new e,i.$name=n,i.$el=t;let o=rh(n,t);i.$refs=o.refs,i.$manyRefs=o.manyRefs,i.$opts=oh(n,t),i.setup()}catch(o){console.error("Failed to create component",o,n,t)}typeof Ae[n]>"u"&&(Ae[n]=[]),Ae[n].push(i);let r=br.get(t)||{};r[n]=i,br.set(t,r)}function vr(n=document){let t=n.querySelectorAll("[component],[components]");for(let e of t){let i=`${e.getAttribute("component")||""} ${e.getAttribute("components")}`.toLowerCase().split(" ").filter(Boolean);for(let r of i)sh(r,e)}}function wr(n){let t=Object.keys(n);for(let e of t)Yo[Xo(e)]=n[e]}function ah(n){return(Ae[n]||[null])[0]}function lh(n){return Ae[n]||[]}function ch(n,t){return(br.get(n)||{})[t]||null}var jo={};Se(jo,{AddRemoveRows:()=>cn,AjaxDeleteRow:()=>un,AjaxForm:()=>hn,Attachments:()=>dn,AttachmentsList:()=>pn,AutoSubmit:()=>mn,AutoSuggest:()=>fn,BackToTop:()=>gn,BookSort:()=>Fn,ChapterContents:()=>Bn,CodeEditor:()=>Pn,CodeHighlighter:()=>On,CodeTextarea:()=>Rn,Collapsible:()=>Nn,ConfirmDialog:()=>zn,CustomCheckbox:()=>Hn,DetailsHighlighter:()=>Un,Dropdown:()=>jn,DropdownSearch:()=>Vn,Dropzone:()=>Wn,EditorToolbox:()=>Gn,EntityPermissions:()=>Kn,EntitySearch:()=>Zn,EntitySelector:()=>Xn,EntitySelectorPopup:()=>Yn,EventEmitSelect:()=>Jn,ExpandToggle:()=>Qn,GlobalSearch:()=>ti,HeaderMobileToggle:()=>ei,ImageManager:()=>ni,ImagePicker:()=>ii,ListSortControl:()=>ri,MarkdownEditor:()=>Mi,NewUserPassword:()=>Fi,Notification:()=>qi,OptionalInput:()=>Bi,PageComment:()=>Pi,PageComments:()=>Oi,PageDisplay:()=>Ri,PageEditor:()=>Ni,PagePicker:()=>Hi,PermissionsTable:()=>Ui,Pointer:()=>ji,Popup:()=>Vi,SettingAppColorScheme:()=>Wi,SettingColorPicker:()=>Gi,SettingHomepageControl:()=>Ki,ShelfSort:()=>Zi,ShortcutInput:()=>Yi,Shortcuts:()=>Xi,SortableList:()=>Ji,SubmitOnChange:()=>Qi,Tabs:()=>tr,TagManager:()=>er,TemplateManager:()=>nr,ToggleSwitch:()=>ir,TriLayout:()=>rr,UserSelect:()=>or,WebhookEvents:()=>sr,WysiwygEditor:()=>cr,WysiwygInput:()=>ur});function Et(n,t={},e=[]){let i=document.createElement(n);for(let[r,o]of Object.entries(t))o===null?i.removeAttribute(r):i.setAttribute(r,o);for(let r of e)typeof r=="string"?i.append(document.createTextNode(r)):i.append(r);return i}function xr(n,t){let e=document.querySelectorAll(n);for(let i of e)t(i)}function ln(n,t,e){for(let i of t)n.addEventListener(i,e)}function R(n,t){Array.isArray(n)||(n=[n]);for(let e of n)e.addEventListener("click",t),e.addEventListener("keydown",i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),t(i))})}function Jo(n,t,e){Array.isArray(t)||(t=[t]);let i=r=>{r.key===n&&e(r)};t.forEach(r=>r.addEventListener("keydown",i))}function se(n,t){Jo("Enter",n,t)}function Qo(n,t){Jo("Escape",n,t)}function K(n,t,e,i){n.addEventListener(e,r=>{let o=r.target.closest(t);o&&i.call(o,r,o)})}function ts(n,t){let e=document.querySelectorAll(n);t=t.toLowerCase();for(let i of e)if(i.textContent.toLowerCase().includes(t))return i;return null}function De(n){n.innerHTML='
'}function ae(){let n=document.createElement("div");return n.classList.add("loading-container"),n.innerHTML="
",n}function Le(n){let t=n.querySelectorAll(".loading-container");for(let e of t)e.remove()}function _t(n){let t=document.createElement("div");return t.innerHTML=n,window.$components.init(t),t.children[0]}function Nt(n,t,e){let i;return function(...o){let s=this,a=function(){i=null,e||n.apply(s,o)},l=e&&!i;clearTimeout(i),i=setTimeout(a,t),l&&n.apply(s,o)}}function Cr(n){if(!n)return;let t=n.closest("details");t&&!t.open&&(t.open=!0),n.scrollIntoView({behavior:"smooth"});let e=getComputedStyle(document.body).getPropertyValue("--color-link");n.style.outline=`2px dashed ${e}`,n.style.outlineOffset="5px",n.style.transition=null,setTimeout(()=>{n.style.transition="outline linear 3s",n.style.outline="2px dashed rgba(0, 0, 0, 0)";let i=()=>{n.removeEventListener("transitionend",i),n.style.transition=null,n.style.outline=null,n.style.outlineOffset=null};n.addEventListener("transitionend",i)},1e3)}function es(n){return n.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function ns(){let n=()=>((1+Math.random())*65536|0).toString(16).substring(1);return`${n()+n()}-${n()}-${n()}-${n()}-${n()}${n()}${n()}`}function is(n){return new Promise(t=>{setTimeout(t,n)})}var g=class{constructor(){at(this,"$name","");at(this,"$el",null);at(this,"$refs",{});at(this,"$manyRefs",{});at(this,"$opts",{})}setup(){}$emit(t,e={}){e.from=this;let i=this.$name,r=new CustomEvent(`${i}-${t}`,{bubbles:!0,detail:e});this.$el.dispatchEvent(r)}};var cn=class extends g{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)),K(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(),i=t.querySelectorAll('[name*="randrowid"]');for(let r of i)r.name=r.name.split("randrowid").join(e)}};var un=class extends g{setup(){this.row=this.$el,this.url=this.$opts.url,this.deleteButtons=this.$manyRefs.delete,R(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 hn=class extends g{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}se(this.container,t=>{this.submitFakeForm(),t.preventDefault()}),this.submitButtons.forEach(t=>R(t,this.submitFakeForm.bind(this)))}submitFakeForm(){let t=new FormData,e=this.container.querySelectorAll("[name]");for(let i of e)t.append(i.getAttribute("name"),i.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 dn=class extends g{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 i=e.target.closest("[data-drag-content]").getAttribute("data-drag-content"),r=JSON.parse(i);window.$events.emit("editor::insert",{html:r["text/html"],markdown:r["text/plain"]})}),this.attachLinkButton.addEventListener("click",()=>{this.showSection("links")})}showSection(t){let e={links:this.linksContainer,edit:this.editContainer,list:this.listContainer};for(let[i,r]of Object.entries(e))r.toggleAttribute("hidden",i!==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"),De(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 pn=class extends g{setup(){this.container=this.$el,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(){let t=this.container.querySelectorAll("a.attachment-file");for(let e of t)e.href.split("?")[1]!=="open=true"&&(e.href+="?open=true",e.setAttribute("target","_blank"))}removeOpenQueryFromLinks(){let t=this.container.querySelectorAll("a.attachment-file");for(let e of t)e.href=e.href.split("?")[0],e.removeAttribute("target")}};var Te,Er,$e,_r,zt=class{constructor(t,e=null,i=null){ot(this,Te);ot(this,$e);this.containers=[t],this.onEscape=e,this.onEnter=i,t.addEventListener("keydown",L(this,Te,Er).bind(this))}shareHandlingToEl(t){this.containers.push(t),t.addEventListener("keydown",L(this,Te,Er).bind(this))}focusNext(){let t=L(this,$e,_r).call(this),i=t.indexOf(document.activeElement)+1;i>=t.length&&(i=0),t[i].focus()}focusPrevious(){let t=L(this,$e,_r).call(this),i=t.indexOf(document.activeElement)-1;i<0&&(i=t.length-1),t[i].focus()}};Te=new WeakSet,Er=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))},$e=new WeakSet,_r=function(){let t=[],e='[tabindex]:not([tabindex="-1"]),[href],button:not([tabindex="-1"],[disabled]),input:not([type=hidden])';for(let i of this.containers)t.push(...i.querySelectorAll(e));return t};var Sr={},fn=class extends g{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 zt(this.list,()=>{this.input.focus(),setTimeout(()=>this.hideSuggestions(),1)},e=>{e.preventDefault();let i=e.target.textContent;i&&this.selectSuggestion(i)}).shareHandlingToEl(this.input),K(this.list,".text-item","click",(e,i)=>{this.selectSuggestion(i.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(),r=(await this.loadSuggestions(e,t)).filter(o=>e===""||o.toLowerCase().startsWith(e)).slice(0,10);this.displaySuggestions(r)}getNameFilterIfNeeded(){return this.type!=="value"?null:this.parent.querySelector("input").value}async loadSuggestions(t,e=null){t=t.slice(0,4);let i={search:t,name:e},r=`${this.url}:${JSON.stringify(i)}`;if(Sr[r])return Sr[r];let o=await window.$http.get(this.url,i);return Sr[r]=o.data,o.data}displaySuggestions(t){if(t.length===0){this.hideSuggestions();return}this.list.innerHTML=t.map(e=>`
  • ${es(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 mn=class extends g{setup(){this.form=this.$el,this.form.submit()}};var gn=class extends g{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,i=300,r=Date.now(),o=this.targetElem.getBoundingClientRect().top;function s(){let a=1-(Date.now()-r)/i,l=Math.abs(a*o);a>0?(e.scrollTop=l,requestAnimationFrame(s.bind(this))):e.scrollTop=t}requestAnimationFrame(s.bind(this))}};function rs(n,t){var e=Object.keys(n);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(n);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(n,r).enumerable})),e.push.apply(e,i)}return e}function At(n){for(var t=1;t=0)&&(e[r]=n[r]);return e}function dh(n,t){if(n==null)return{};var e=hh(n,t),i,r;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(n);for(r=0;r=0)&&Object.prototype.propertyIsEnumerable.call(n,i)&&(e[i]=n[i])}return e}function ph(n){return fh(n)||mh(n)||gh(n)||bh()}function fh(n){if(Array.isArray(n))return Pr(n)}function mh(n){if(typeof Symbol<"u"&&n[Symbol.iterator]!=null||n["@@iterator"]!=null)return Array.from(n)}function gh(n,t){if(n){if(typeof n=="string")return Pr(n,t);var e=Object.prototype.toString.call(n).slice(8,-1);if(e==="Object"&&n.constructor&&(e=n.constructor.name),e==="Map"||e==="Set")return Array.from(n);if(e==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e))return Pr(n,t)}}function Pr(n,t){(t==null||t>n.length)&&(t=n.length);for(var e=0,i=new Array(t);e"&&(t=t.substring(1)),n)try{if(n.matches)return n.matches(t);if(n.msMatchesSelector)return n.msMatchesSelector(t);if(n.webkitMatchesSelector)return n.webkitMatchesSelector(t)}catch{return!1}return!1}}function wh(n){return n.host&&n!==document&&n.host.nodeType?n.host:n.parentNode}function xt(n,t,e,i){if(n){e=e||document;do{if(t!=null&&(t[0]===">"?n.parentNode===e&&Dn(n,t):Dn(n,t))||i&&n===e)return n;if(n===e)break}while(n=wh(n))}return null}var ss=/\s+/g;function Y(n,t,e){if(n&&t)if(n.classList)n.classList[e?"add":"remove"](t);else{var i=(" "+n.className+" ").replace(ss," ").replace(" "+t+" "," ");n.className=(i+(e?" "+t:"")).replace(ss," ")}}function S(n,t,e){var i=n&&n.style;if(i){if(e===void 0)return document.defaultView&&document.defaultView.getComputedStyle?e=document.defaultView.getComputedStyle(n,""):n.currentStyle&&(e=n.currentStyle),t===void 0?e:e[t];!(t in i)&&t.indexOf("webkit")===-1&&(t="-webkit-"+t),i[t]=e+(typeof e=="string"?"":"px")}}function Xt(n,t){var e="";if(typeof n=="string")e=n;else do{var i=S(n,"transform");i&&i!=="none"&&(e=i+" "+e)}while(!t&&(n=n.parentNode));var r=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return r&&new r(e)}function vs(n,t,e){if(n){var i=n.getElementsByTagName(t),r=0,o=i.length;if(e)for(;r=o:s=r<=o,!s)return i;if(i===St())break;i=jt(i,!1)}return!1}function pe(n,t,e,i){for(var r=0,o=0,s=n.children;o2&&arguments[2]!==void 0?arguments[2]:{},r=i.evt,o=dh(i,Sh);Ve.pluginEvent.bind(I)(t,e,At({dragEl:C,parentEl:Z,ghostEl:q,rootEl:V,nextEl:Zt,lastDownEl:En,cloneEl:G,cloneHidden:Ut,dragStarted:Be,putSortable:tt,activeSortable:I.active,originalEvent:r,oldIndex:de,oldDraggableIndex:ze,newIndex:mt,newDraggableIndex:Ht,hideGhostForTarget:_s,unhideGhostForTarget:Ss,cloneNowHidden:function(){Ut=!0},cloneNowShown:function(){Ut=!1},dispatchSortableEvent:function(a){st({sortable:e,name:a,originalEvent:r})}},o))};function st(n){qe(At({putSortable:tt,cloneEl:G,targetEl:C,rootEl:V,oldIndex:de,oldDraggableIndex:ze,newIndex:mt,newDraggableIndex:Ht},n))}var C,Z,q,V,Zt,En,G,Ut,de,mt,ze,Ht,bn,tt,he=!1,Ln=!1,Tn=[],Gt,wt,Tr,$r,us,hs,Be,ce,He,Ue=!1,vn=!1,_n,nt,Ir=[],Or=!1,$n=[],Mn=typeof document<"u",wn=ms,ds=je||Mt?"cssFloat":"float",Ah=Mn&&!gs&&!ms&&"draggable"in document.createElement("div"),ks=function(){if(Mn){if(Mt)return!1;var n=document.createElement("x");return n.style.cssText="pointer-events:auto",n.style.pointerEvents==="auto"}}(),Cs=function(t,e){var i=S(t),r=parseInt(i.width)-parseInt(i.paddingLeft)-parseInt(i.paddingRight)-parseInt(i.borderLeftWidth)-parseInt(i.borderRightWidth),o=pe(t,0,e),s=pe(t,1,e),a=o&&S(o),l=s&&S(s),c=a&&parseInt(a.marginLeft)+parseInt(a.marginRight)+j(o).width,u=l&&parseInt(l.marginLeft)+parseInt(l.marginRight)+j(s).width;if(i.display==="flex")return i.flexDirection==="column"||i.flexDirection==="column-reverse"?"vertical":"horizontal";if(i.display==="grid")return i.gridTemplateColumns.split(" ").length<=1?"vertical":"horizontal";if(o&&a.float&&a.float!=="none"){var h=a.float==="left"?"left":"right";return s&&(l.clear==="both"||l.clear===h)?"vertical":"horizontal"}return o&&(a.display==="block"||a.display==="flex"||a.display==="table"||a.display==="grid"||c>=r&&i[ds]==="none"||s&&i[ds]==="none"&&c+u>r)?"vertical":"horizontal"},Dh=function(t,e,i){var r=i?t.left:t.top,o=i?t.right:t.bottom,s=i?t.width:t.height,a=i?e.left:e.top,l=i?e.right:e.bottom,c=i?e.width:e.height;return r===a||o===l||r+s/2===a+c/2},Lh=function(t,e){var i;return Tn.some(function(r){var o=r[it].options.emptyInsertThreshold;if(!(!o||Hr(r))){var s=j(r),a=t>=s.left-o&&t<=s.right+o,l=e>=s.top-o&&e<=s.bottom+o;if(a&&l)return i=r}}),i},Es=function(t){function e(o,s){return function(a,l,c,u){var h=a.options.group.name&&l.options.group.name&&a.options.group.name===l.options.group.name;if(o==null&&(s||h))return!0;if(o==null||o===!1)return!1;if(s&&o==="clone")return o;if(typeof o=="function")return e(o(a,l,c,u),s)(a,l,c,u);var d=(s?a:l).options.group.name;return o===!0||typeof o=="string"&&o===d||o.join&&o.indexOf(d)>-1}}var i={},r=t.group;(!r||Cn(r)!="object")&&(r={name:r}),i.name=r.name,i.checkPull=e(r.pull,!0),i.checkPut=e(r.put),i.revertClone=r.revertClone,t.group=i},_s=function(){!ks&&q&&S(q,"display","none")},Ss=function(){!ks&&q&&S(q,"display","")};Mn&&!gs&&document.addEventListener("click",function(n){if(Ln)return n.preventDefault(),n.stopPropagation&&n.stopPropagation(),n.stopImmediatePropagation&&n.stopImmediatePropagation(),Ln=!1,!1},!0);var Kt=function(t){if(C){t=t.touches?t.touches[0]:t;var e=Lh(t.clientX,t.clientY);if(e){var i={};for(var r in t)t.hasOwnProperty(r)&&(i[r]=t[r]);i.target=i.rootEl=e,i.preventDefault=void 0,i.stopPropagation=void 0,e[it]._onDragOver(i)}}},Th=function(t){C&&C.parentNode[it]._isOutsideThisEl(t.target)};function I(n,t){if(!(n&&n.nodeType&&n.nodeType===1))throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(n));this.el=n,this.options=t=kt({},t),n[it]=this;var e={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(n.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return Cs(n,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(s,a){s.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:I.supportPointer!==!1&&"PointerEvent"in window&&!Re,emptyInsertThreshold:5};Ve.initializePlugins(this,n,e);for(var i in e)!(i in t)&&(t[i]=e[i]);Es(t);for(var r in this)r.charAt(0)==="_"&&typeof this[r]=="function"&&(this[r]=this[r].bind(this));this.nativeDraggable=t.forceFallback?!1:Ah,this.nativeDraggable&&(this.options.touchStartThreshold=1),t.supportPointer?O(n,"pointerdown",this._onTapStart):(O(n,"mousedown",this._onTapStart),O(n,"touchstart",this._onTapStart)),this.nativeDraggable&&(O(n,"dragover",this),O(n,"dragenter",this)),Tn.push(this.el),t.store&&t.store.get&&this.sort(t.store.get(this)||[]),kt(this,Ch())}I.prototype={constructor:I,_isOutsideThisEl:function(t){!this.el.contains(t)&&t!==this.el&&(ce=null)},_getDirection:function(t,e){return typeof this.options.direction=="function"?this.options.direction.call(this,t,e,C):this.options.direction},_onTapStart:function(t){if(t.cancelable){var e=this,i=this.el,r=this.options,o=r.preventOnFilter,s=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,u=r.filter;if(Oh(i),!C&&!(/mousedown|pointerdown/.test(s)&&t.button!==0||r.disabled)&&!c.isContentEditable&&!(!this.nativeDraggable&&Re&&l&&l.tagName.toUpperCase()==="SELECT")&&(l=xt(l,r.draggable,i,!1),!(l&&l.animated)&&En!==l)){if(de=J(l),ze=J(l,r.draggable),typeof u=="function"){if(u.call(this,t,l,this)){st({sortable:e,rootEl:c,name:"filter",targetEl:l,toEl:i,fromEl:i}),lt("filter",e,{evt:t}),o&&t.cancelable&&t.preventDefault();return}}else if(u&&(u=u.split(",").some(function(h){if(h=xt(c,h.trim(),i,!1),h)return st({sortable:e,rootEl:h,name:"filter",targetEl:l,fromEl:i,toEl:i}),lt("filter",e,{evt:t}),!0}),u)){o&&t.cancelable&&t.preventDefault();return}r.handle&&!xt(c,r.handle,i,!1)||this._prepareDragStart(t,a,l)}}},_prepareDragStart:function(t,e,i){var r=this,o=r.el,s=r.options,a=o.ownerDocument,l;if(i&&!C&&i.parentNode===o){var c=j(i);if(V=o,C=i,Z=C.parentNode,Zt=C.nextSibling,En=i,bn=s.group,I.dragged=C,Gt={target:C,clientX:(e||t).clientX,clientY:(e||t).clientY},us=Gt.clientX-c.left,hs=Gt.clientY-c.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,C.style["will-change"]="all",l=function(){if(lt("delayEnded",r,{evt:t}),I.eventCanceled){r._onDrop();return}r._disableDelayedDragEvents(),!os&&r.nativeDraggable&&(C.draggable=!0),r._triggerDragStart(t,e),st({sortable:r,name:"choose",originalEvent:t}),Y(C,s.chosenClass,!0)},s.ignore.split(",").forEach(function(u){vs(C,u.trim(),Mr)}),O(a,"dragover",Kt),O(a,"mousemove",Kt),O(a,"touchmove",Kt),O(a,"mouseup",r._onDrop),O(a,"touchend",r._onDrop),O(a,"touchcancel",r._onDrop),os&&this.nativeDraggable&&(this.options.touchStartThreshold=4,C.draggable=!0),lt("delayStart",this,{evt:t}),s.delay&&(!s.delayOnTouchOnly||e)&&(!this.nativeDraggable||!(je||Mt))){if(I.eventCanceled){this._onDrop();return}O(a,"mouseup",r._disableDelayedDrag),O(a,"touchend",r._disableDelayedDrag),O(a,"touchcancel",r._disableDelayedDrag),O(a,"mousemove",r._delayedDragTouchMoveHandler),O(a,"touchmove",r._delayedDragTouchMoveHandler),s.supportPointer&&O(a,"pointermove",r._delayedDragTouchMoveHandler),r._dragStartTimer=setTimeout(l,s.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(){C&&Mr(C),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var t=this.el.ownerDocument;B(t,"mouseup",this._disableDelayedDrag),B(t,"touchend",this._disableDelayedDrag),B(t,"touchcancel",this._disableDelayedDrag),B(t,"mousemove",this._delayedDragTouchMoveHandler),B(t,"touchmove",this._delayedDragTouchMoveHandler),B(t,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(t,e){e=e||t.pointerType=="touch"&&t,!this.nativeDraggable||e?this.options.supportPointer?O(document,"pointermove",this._onTouchMove):e?O(document,"touchmove",this._onTouchMove):O(document,"mousemove",this._onTouchMove):(O(C,"dragend",this),O(V,"dragstart",this._onDragStart));try{document.selection?Sn(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},_dragStarted:function(t,e){if(he=!1,V&&C){lt("dragStarted",this,{evt:e}),this.nativeDraggable&&O(document,"dragover",Th);var i=this.options;!t&&Y(C,i.dragClass,!1),Y(C,i.ghostClass,!0),I.active=this,t&&this._appendGhost(),st({sortable:this,name:"start",originalEvent:e})}else this._nulling()},_emulateDragOver:function(){if(wt){this._lastX=wt.clientX,this._lastY=wt.clientY,_s();for(var t=document.elementFromPoint(wt.clientX,wt.clientY),e=t;t&&t.shadowRoot&&(t=t.shadowRoot.elementFromPoint(wt.clientX,wt.clientY),t!==e);)e=t;if(C.parentNode[it]._isOutsideThisEl(t),e)do{if(e[it]){var i=void 0;if(i=e[it]._onDragOver({clientX:wt.clientX,clientY:wt.clientY,target:t,rootEl:e}),i&&!this.options.dragoverBubble)break}t=e}while(e=e.parentNode);Ss()}},_onTouchMove:function(t){if(Gt){var e=this.options,i=e.fallbackTolerance,r=e.fallbackOffset,o=t.touches?t.touches[0]:t,s=q&&Xt(q,!0),a=q&&s&&s.a,l=q&&s&&s.d,c=wn&&nt&&ls(nt),u=(o.clientX-Gt.clientX+r.x)/(a||1)+(c?c[0]-Ir[0]:0)/(a||1),h=(o.clientY-Gt.clientY+r.y)/(l||1)+(c?c[1]-Ir[1]:0)/(l||1);if(!I.active&&!he){if(i&&Math.max(Math.abs(o.clientX-this._lastX),Math.abs(o.clientY-this._lastY))=0&&(st({rootEl:Z,name:"add",toEl:Z,fromEl:V,originalEvent:t}),st({sortable:this,name:"remove",toEl:Z,originalEvent:t}),st({rootEl:Z,name:"sort",toEl:Z,fromEl:V,originalEvent:t}),st({sortable:this,name:"sort",toEl:Z,originalEvent:t})),tt&&tt.save()):mt!==de&&mt>=0&&(st({sortable:this,name:"update",toEl:Z,originalEvent:t}),st({sortable:this,name:"sort",toEl:Z,originalEvent:t})),I.active&&((mt==null||mt===-1)&&(mt=de,Ht=ze),st({sortable:this,name:"end",toEl:Z,originalEvent:t}),this.save()))),this._nulling()},_nulling:function(){lt("nulling",this),V=C=Z=q=Zt=G=En=Ut=Gt=wt=Be=mt=Ht=de=ze=ce=He=tt=bn=I.dragged=I.ghost=I.clone=I.active=null,$n.forEach(function(t){t.checked=!0}),$n.length=Tr=$r=0},handleEvent:function(t){switch(t.type){case"drop":case"dragend":this._onDrop(t);break;case"dragenter":case"dragover":C&&(this._onDragOver(t),$h(t));break;case"selectstart":t.preventDefault();break}},toArray:function(){for(var t=[],e,i=this.el.children,r=0,o=i.length,s=this.options;rr.right+o||n.clientY>i.bottom&&n.clientX>i.left:n.clientY>r.bottom+o||n.clientX>i.right&&n.clientY>i.top}function qh(n,t,e,i,r,o,s,a){var l=i?n.clientY:n.clientX,c=i?e.height:e.width,u=i?e.top:e.left,h=i?e.bottom:e.right,d=!1;if(!s){if(a&&_nu+c*o/2:lh-_n)return-He}else if(l>u+c*(1-r)/2&&lh-c*o/2)?l>u+c/2?1:-1:0}function Bh(n){return J(C)1&&(F.forEach(function(a){o.addAnimationState({target:a,rect:ct?j(a):s}),Dr(a),a.fromRect=s,i.removeAnimationState(a)}),ct=!1,Nh(!this.options.removeCloneOnHide,r))},dragOverCompleted:function(e){var i=e.sortable,r=e.isOwner,o=e.insertion,s=e.activeSortable,a=e.parentEl,l=e.putSortable,c=this.options;if(o){if(r&&s._hideClone(),Me=!1,c.animation&&F.length>1&&(ct||!r&&!s.options.sort&&!l)){var u=j(z,!1,!0,!0);F.forEach(function(d){d!==z&&(cs(d,u),a.appendChild(d))}),ct=!0}if(!r)if(ct||kn(),F.length>1){var h=xn;s._showClone(i),s.options.animation&&!xn&&h&&ft.forEach(function(d){s.addAnimationState({target:d,rect:Fe}),d.fromRect=Fe,d.thisAnimationDuration=null})}else s._showClone(i)}},dragOverAnimationCapture:function(e){var i=e.dragRect,r=e.isOwner,o=e.activeSortable;if(F.forEach(function(a){a.thisAnimationDuration=null}),o.options.animation&&!r&&o.multiDrag.isMultiDrag){Fe=kt({},i);var s=Xt(z,!0);Fe.top-=s.f,Fe.left-=s.e}},dragOverAnimationComplete:function(){ct&&(ct=!1,kn())},drop:function(e){var i=e.originalEvent,r=e.rootEl,o=e.parentEl,s=e.sortable,a=e.dispatchSortableEvent,l=e.oldIndex,c=e.putSortable,u=c||this.sortable;if(i){var h=this.options,d=o.children;if(!ue)if(h.multiDragKey&&!this.multiDragKeyDown&&this._deselectMultiDrag(),Y(z,h.selectedClass,!~F.indexOf(z)),~F.indexOf(z))F.splice(F.indexOf(z),1),Ie=null,qe({sortable:s,rootEl:r,name:"deselect",targetEl:z,originalEvent:i});else{if(F.push(z),qe({sortable:s,rootEl:r,name:"select",targetEl:z,originalEvent:i}),i.shiftKey&&Ie&&s.el.contains(Ie)){var f=J(Ie),p=J(z);if(~f&&~p&&f!==p){var m,w;for(p>f?(w=f,m=p):(w=p,m=f+1);w1){var v=j(z),b=J(z,":not(."+this.options.selectedClass+")");if(!Me&&h.animation&&(z.thisAnimationDuration=null),u.captureAnimationState(),!Me&&(h.animation&&(z.fromRect=v,F.forEach(function(x){if(x.thisAnimationDuration=null,x!==z){var E=ct?j(x):v;x.fromRect=E,u.addAnimationState({target:x,rect:E})}})),kn(),F.forEach(function(x){d[b]?o.insertBefore(x,d[b]):o.appendChild(x),b++}),l===J(z))){var k=!1;F.forEach(function(x){if(x.sortableIndex!==J(x)){k=!0;return}}),k&&(a("update"),a("sort"))}F.forEach(function(x){Dr(x)}),u.animateAll()}yt=u}(r===o||c&&c.lastPutMode!=="clone")&&ft.forEach(function(x){x.parentNode&&x.parentNode.removeChild(x)})}},nullingGlobal:function(){this.isMultiDrag=ue=!1,ft.length=0},destroyGlobal:function(){this._deselectMultiDrag(),B(document,"pointerup",this._deselectMultiDrag),B(document,"mouseup",this._deselectMultiDrag),B(document,"touchend",this._deselectMultiDrag),B(document,"keydown",this._checkKeyDown),B(document,"keyup",this._checkKeyUp)},_deselectMultiDrag:function(e){if(!(typeof ue<"u"&&ue)&&yt===this.sortable&&!(e&&xt(e.target,this.options.draggable,this.sortable.el,!1))&&!(e&&e.button!==0))for(;F.length;){var i=F[0];Y(i,this.options.selectedClass,!1),F.shift(),qe({sortable:this.sortable,rootEl:this.sortable.el,name:"deselect",targetEl:i,originalEvent:e})}},_checkKeyDown:function(e){e.key===this.options.multiDragKey&&(this.multiDragKeyDown=!0)},_checkKeyUp:function(e){e.key===this.options.multiDragKey&&(this.multiDragKeyDown=!1)}},kt(n,{pluginName:"multiDrag",utils:{select:function(e){var i=e.parentNode[it];!i||!i.options.multiDrag||~F.indexOf(e)||(yt&&yt!==i&&(yt.multiDrag._deselectMultiDrag(),yt=i),Y(e,i.options.selectedClass,!0),F.push(e))},deselect:function(e){var i=e.parentNode[it],r=F.indexOf(e);!i||!i.options.multiDrag||!~r||(Y(e,i.options.selectedClass,!1),F.splice(r,1))}},eventProperties:function(){var e=this,i=[],r=[];return F.forEach(function(o){i.push({multiDragElement:o,index:o.sortableIndex});var s;ct&&o!==z?s=-1:ct?s=J(o,":not(."+e.options.selectedClass+")"):s=J(o),r.push({multiDragElement:o,index:s})}),{items:ph(F),clones:[].concat(ft),oldIndicies:i,newIndicies:r}},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 Nh(n,t){F.forEach(function(e,i){var r=t.children[e.sortableIndex+(n?Number(i):0)];r?t.insertBefore(e,r):t.appendChild(e)})}function fs(n,t){ft.forEach(function(e,i){var r=t.children[e.sortableIndex+(n?Number(i):0)];r?t.insertBefore(e,r):t.appendChild(e)})}function kn(){F.forEach(function(n){n!==z&&n.parentNode&&n.parentNode.removeChild(n)})}I.mount(new Rh);I.mount(Vr,jr);var Yt=I;var Ls={name(n,t){let e=n.getAttribute("data-name").trim().toLowerCase(),i=t.getAttribute("data-name").trim().toLowerCase();return e.localeCompare(i)},created(n,t){let e=Number(n.getAttribute("data-created"));return Number(t.getAttribute("data-created"))-e},updated(n,t){let e=Number(n.getAttribute("data-updated"));return Number(t.getAttribute("data-updated"))-e},chaptersFirst(n,t){let e=n.getAttribute("data-type"),i=t.getAttribute("data-type");return e===i?0:e==="chapter"?-1:1},chaptersLast(n,t){let e=n.getAttribute("data-type"),i=t.getAttribute("data-type");return e===i?0:e==="chapter"?1:-1}},Ts={up:{active(n,t){return!(n.previousElementSibling===null&&!t)},run(n,t){(n.previousElementSibling||t).insertAdjacentElement("beforebegin",n)}},down:{active(n,t){return!(n.nextElementSibling===null&&!t)},run(n,t){(n.nextElementSibling||t).insertAdjacentElement("afterend",n)}},next_book:{active(n,t,e){return e.nextElementSibling!==null},run(n,t,e){e.nextElementSibling.querySelector("ul").prepend(n)}},prev_book:{active(n,t,e){return e.previousElementSibling!==null},run(n,t,e){e.previousElementSibling.querySelector("ul").appendChild(n)}},next_chapter:{active(n,t){return n.dataset.type==="page"&&this.getNextChapter(n,t)},run(n,t){this.getNextChapter(n,t).querySelector("ul").prepend(n)},getNextChapter(n,t){let e=t||n,i=Array.from(e.parentElement.children),r=i.indexOf(e);return i.slice(r+1).find(o=>o.dataset.type==="chapter")}},prev_chapter:{active(n,t){return n.dataset.type==="page"&&this.getPrevChapter(n,t)},run(n,t){this.getPrevChapter(n,t).querySelector("ul").append(n)},getPrevChapter(n,t){let e=t||n,i=Array.from(e.parentElement.children),r=i.indexOf(e);return i.slice(0,r).reverse().find(o=>o.dataset.type==="chapter")}},book_end:{active(n,t){return t||t===null&&n.nextElementSibling},run(n,t,e){e.querySelector("ul").append(n)}},book_start:{active(n,t){return t||t===null&&n.previousElementSibling},run(n,t,e){e.querySelector("ul").prepend(n)}},before_chapter:{active(n,t){return t},run(n,t){t.insertAdjacentElement("beforebegin",n)}},after_chapter:{active(n,t){return t},run(n,t){t.insertAdjacentElement("afterend",n)}}},Fn=class extends g{setup(){this.container=this.$el,this.sortContainer=this.$refs.sortContainer,this.input=this.$refs.input,Yt.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"),i=t.target.closest("[data-id]");this.runSortAction(i,e)}}),this.updateMoveActionStateForAll()}setupSortPresets(){let t="",e=!1,i=["name","created","updated"];this.sortContainer.addEventListener("click",r=>{let o=r.target.closest(".sort-box-options [data-sort]");if(!o)return;r.preventDefault();let s=o.closest(".sort-box").querySelectorAll("ul"),a=o.getAttribute("data-sort");e=t===a?!e:!1;let l=Ls[a];e&&i.includes(a)&&(l=function(u,h){return 0-Ls[a](u,h)});for(let c of s)Array.from(c.children).filter(h=>h.matches("li")).sort(l).forEach(h=>{c.appendChild(h)});t=a,this.updateMapInput()})}bookSelect(t){if(this.container.querySelector(`[data-type="book"][data-id="${t.id}"]`)!==null)return;let i=`${t.link}/sort-item`;window.$http.get(i).then(r=>{let o=_t(r.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")),i={name:"book",pull:["book","chapter"],put:["book","chapter"]},r={name:"chapter",pull:["book","chapter"],put(o,s,a){return a.getAttribute("data-type")==="page"}};for(let o of e)Yt.create(o,{group:o.classList.contains("sort-list")?i:r,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 i of e){let r=i.closest('[data-type="book"]').getAttribute("data-id"),o=Array.from(i.children).filter(s=>s.matches('[data-type="page"], [data-type="chapter"]'));for(let s=0;s{for(let s of r)n.style[s]=null;n.style.transition=null,n.removeEventListener("transitionend",o),qn.delete(n),i&&i()};setTimeout(()=>{n.style.transition=`all ease-in-out ${e}ms`;for(let s of r)n.style[s]=t[s][1];n.addEventListener("transitionend",o),qn.set(n,o)},15)}function Ge(n){qn.has(n)&&qn.get(n)()}function $s(n,t=400,e=null){Ge(n),n.style.display="block",We(n,{opacity:["0","1"]},t,()=>{e&&e()})}function Is(n,t=400,e=null){Ge(n),We(n,{opacity:["1","0"]},t,()=>{n.style.display="none",e&&e()})}function fe(n,t=400){Ge(n);let e=n.getBoundingClientRect().height,i=getComputedStyle(n),r=i.getPropertyValue("padding-top"),o=i.getPropertyValue("padding-bottom"),s={maxHeight:[`${e}px`,"0px"],overflow:["hidden","hidden"],paddingTop:[r,"0px"],paddingBottom:[o,"0px"]};We(n,s,t,()=>{n.style.display="none"})}function me(n,t=400){Ge(n),n.style.display="block";let e=n.getBoundingClientRect().height,i=getComputedStyle(n),r=i.getPropertyValue("padding-top"),o=i.getPropertyValue("padding-bottom"),s={maxHeight:["0px",`${e}px`],overflow:["hidden","hidden"],paddingTop:["0px",r],paddingBottom:["0px",o]};We(n,s,t)}function Ms(n,t=400){let e=n.getBoundingClientRect().height,i=getComputedStyle(n),r=i.getPropertyValue("padding-top"),o=i.getPropertyValue("padding-bottom");return()=>{Ge(n);let s=n.getBoundingClientRect().height,a=getComputedStyle(n),l=a.getPropertyValue("padding-top"),c=a.getPropertyValue("padding-bottom"),u={height:[`${e}px`,`${s}px`],overflow:["hidden","hidden"],paddingTop:[r,l],paddingBottom:[o,c]};We(n,u,t)}}var Bn=class extends g{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"),me(this.list,180),this.isOpen=!0}close(){this.toggle.classList.remove("open"),this.toggle.setAttribute("aria-expanded","false"),fe(this.list,180),this.isOpen=!1}click(t){t.preventDefault(),this.isOpen?this.close():this.open()}};var Pn=class extends g{constructor(){super(...arguments);at(this,"editor",null);at(this,"saveCallback",null);at(this,"cancelCallback",null);at(this,"history",{});at(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()}),R(this.languageButtons,e=>{let i=e.target.dataset.lang;this.languageInput.value=i,this.languageInputChange(i)}),se(this.languageInput,()=>this.save()),this.languageInput.addEventListener("input",()=>this.languageInputChange(this.languageInput.value)),R(this.saveButton,()=>this.save()),K(this.historyList,"button","click",(e,i)=>{e.preventDefault();let r=i.dataset.time;this.editor&&this.editor.setContent(this.history[r])})}setupFavourites(){for(let e of this.languageButtons)this.setupFavouritesForButton(e);this.sortLanguageList()}setupFavouritesForButton(e){let i=e.dataset.lang,r=this.favourites.has(i);e.setAttribute("data-favourite",r?"true":"false"),K(e.parentElement,".lang-option-favorite-toggle","click",()=>{r=!r,r?this.favourites.add(i):this.favourites.delete(i),e.setAttribute("data-favourite",r?"true":"false"),window.$http.patch("/preferences/update-code-language-favourite",{language:i,active:r}),this.sortLanguageList(),r&&e.scrollIntoView({block:"center",behavior:"smooth"})})}sortLanguageList(){let e=this.languageButtons.sort((i,r)=>{let o=i.dataset.favourite==="true",s=r.dataset.favourite==="true";return o&&!s?-1:s&&!o||i.dataset.lang>r.dataset.lang?1:-1}).map(i=>i.parentElement);for(let i of e)this.languageOptionsContainer.append(i)}save(){this.saveCallback&&this.saveCallback(this.editor.getContent(),this.languageInput.value),this.hide()}async open(e,i,r,o){this.languageInput.value=i,this.saveCallback=r,this.cancelCallback=o,await this.show(),this.languageInputChange(i),this.editor.setContent(e)}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()})}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 i=e.toLowerCase();for(let r of this.languageButtons){let o=r.dataset.lang.toLowerCase().trim(),s=i===o;r.classList.toggle("active",s),s&&r.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(i=>{let r=new Date(parseInt(i,10)).toLocaleTimeString();return`
  • `}).join("")}addHistory(){if(!this.editor)return;let e=this.editor.getContent();if(!e)return;let i=Object.keys(this.history).pop();if(this.history[i]===e)return;this.history[String(Date.now())]=e;let r=JSON.stringify(this.history);window.sessionStorage.setItem(this.historyKey,r)}};var On=class extends g{setup(){let t=this.$el;t.querySelectorAll("pre").length>0&&window.importVersioned("code").then(i=>{i.highlightWithin(t)})}};var Rn=class extends g{async setup(){let{mode:t}=this.$opts;(await window.importVersioned("code")).inlineEditor(this.$el,t)}};var Nn=class extends g{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"),me(this.content,300)}close(){this.container.classList.remove("open"),this.trigger.setAttribute("aria-expanded","false"),fe(this.content,300)}toggle(){this.container.classList.contains("open")?this.close():this.open()}openIfContainsError(){this.content.querySelector(".text-neg.text-small")&&this.open()}};var zn=class extends g{setup(){this.container=this.$el,this.confirmButton=this.$refs.confirm,this.res=null,R(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 Hn=class extends g{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 Un=class extends g{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 jn=class extends g{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(),i=0,r=this.toggle.getBoundingClientRect().height,o=e.bottom>window.innerHeight,s=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?i=window.innerHeight-e.top-r/2:i=e.top),o){this.menu.style.top="initial",this.menu.style.bottom=`${i}px`;let c=window.innerHeight-40-(window.innerHeight-s.bottom);this.menu.style.maxHeight=`${Math.floor(c)}px`}else{this.menu.style.top=`${i}px`,this.menu.style.bottom="initial";let c=window.innerHeight-40-s.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 zt(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()}),R(this.toggle,e=>{e.stopPropagation(),e.preventDefault(),this.show(e),e instanceof KeyboardEvent&&t.focusNext()})}};var Vn=class extends g{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=Nt(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 i of e){let r=!t||i.textContent.toLowerCase().includes(t);i.style.display=r?"flex":"none",i.classList.toggle("hidden",!r)}}async loadList(t=""){this.listContainerElem.innerHTML="",this.toggleLoading(!0);try{let e=await window.$http.get(this.getAjaxUrl(t)),i=Ms(this.listContainerElem,80);this.listContainerElem.innerHTML=e.data,i()}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 Ft=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 r of t)if(r.includes("image")){let o=this.data.getData(r);e.push(o.getAsFile())}let i=this.getFiles().filter(r=>r.type.includes("image"));return e.push(...i),e}getFiles(){let{files:t}=this.data;return[...t]}};async function Wr(n){if(window.isSecureContext&&navigator.clipboard){await navigator.clipboard.writeText(n);return}let t=document.createElement("textarea");t.style="position: absolute; left: -1000px; top: -1000px;",t.value=n,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t)}var Wn=class extends g{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(){R(this.selectButtons,this.manualSelectHandler.bind(this)),this.setupDropTargetHandlers()}setupDropTargetHandlers(){let t=0,e=()=>{this.hideOverlay(),t=0};this.dropTarget.addEventListener("dragenter",i=>{i.preventDefault(),t+=1,t===1&&this.isActive&&this.showOverlay()}),this.dropTarget.addEventListener("dragover",i=>{i.preventDefault()}),this.dropTarget.addEventListener("dragend",e),this.dropTarget.addEventListener("dragleave",()=>{t-=1,t===0&&e()}),this.dropTarget.addEventListener("drop",i=>{if(i.preventDefault(),e(),!this.isActive)return;let o=new Ft(i.dataTransfer).getFiles();for(let s of o)this.createUploadFromFile(s)})}manualSelectHandler(){let t=Et("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=Et("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:i,progress:r,dismiss:o}=this.createDomForFile(t);this.statusArea.append(e);let s=this,a={file:t,dom:e,updateProgress(l){r.textContent=`${l}%`,r.style.width=`${l}%`},markError(l){i.setAttribute("data-status","error"),i.textContent=l,Le(e),this.updateProgress(100)},markSuccess(l){i.setAttribute("data-status","success"),i.textContent=l,Le(e),setTimeout(o,2400),s.$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 i=this,r=window.$http.createXMLHttpRequest("POST",this.url,{error(){t.markError(i.errorMessage)},readystatechange(){if(this.readyState===XMLHttpRequest.DONE&&this.status===200)t.markSuccess(i.successMessage);else if(this.readyState===XMLHttpRequest.DONE&&this.status>=400){let o=this.responseText,s=o.startsWith("{")?JSON.parse(o):{message:o},a=s?.message||s?.error||o;t.markError(a)}}});r.upload.addEventListener("progress",o=>{let s=Math.min(Math.ceil(o.loaded/o.total*100),100);t.updateProgress(s)}),r.setRequestHeader("Accept","application/json"),r.send(e)}createDomForFile(t){let e=Et("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"}),i=Et("div",{class:"dropzone-file-item-status"},[]),r=Et("div",{class:"dropzone-file-item-progress"}),o=Et("div",{class:"dropzone-file-item-image-wrap"},[e]),s=Et("div",{class:"dropzone-file-item"},[o,Et("div",{class:"dropzone-file-item-text-wrap"},[Et("div",{class:"dropzone-file-item-label"},[t.name]),ae(),i]),r]);t.type.startsWith("image/")&&(e.src=URL.createObjectURL(t));let a=()=>{s.classList.add("dismiss"),s.addEventListener("animationend",()=>{s.remove()})};return s.addEventListener("click",a),{dom:s,progress:r,status:i,dismiss:a}}};var Gn=class extends g{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 i=e.dataset.tab;this.setActiveTab(i,!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 i of this.buttons)i.classList.remove("active"),i.dataset.tab===t&&i.classList.add("active");for(let i of this.contentElements)i.style.display="none",i.dataset.tabContent===t&&(i.style.display="block");e&&!this.container.classList.contains("open")&&this.toggle()}};var Kn=class extends g{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,i=document.querySelectorAll('input[name^="permissions[0]["]');for(let r of i)r.disabled=e,r.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 i=await window.$http.get(`/permissions/form-row/${this.entityType}/${t}`),r=_t(i.data);this.roleContainer.append(r),this.roleSelect.disabled=!1}removeRowOnButtonClick(t){let e=t.closest(".item-list-row"),{roleId:i}=t.dataset,{roleName:r}=t.dataset,o=document.createElement("option");o.value=i,o.textContent=r,this.roleSelect.append(o),e.remove()}};var Zn=class extends g{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()}),R(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(i=>{this.searchResults.innerHTML=i.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 Xn=class extends g{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||""},this.search="",this.lastClick=0,this.setupListeners(),this.showLoading(),this.searchOptions.searchEndpoint&&this.initialLoad()}configureSearchOptions(t){Object.assign(this.searchOptions,t),this.reset()}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()}),K(this.$el,"[data-entity-type]","keydown",e=>{if(e.ctrlKey&&e.code==="Enter"){let i=this.$el.closest("form");if(i){i.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]")),i=e.indexOf(document.activeElement),r=e[i+(t?1:-1)]||e[0];r&&r.focus()}reset(){this.searchInput.value="",this.showLoading(),this.initialLoad()}focusSearch(){this.searchInput.focus()}searchText(t){this.searchInput.value=t,this.searchEntities(t)}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");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(i=>{this.resultsContainer.innerHTML=i.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(),i=t.getAttribute("data-entity-type"),r=t.getAttribute("data-entity-id"),o=!t.classList.contains("selected")||e;this.unselectAll(),this.input.value=o?`${i}:${r}`:"";let s=t.getAttribute("href"),a=t.querySelector(".entity-list-item-name").textContent,l={id:Number(r),name:a,link:s};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 Yn=class extends g{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="",i={}){this.callback=t,this.getSelector().configureSearchOptions(i),this.getPopup().show(),e&&this.getSelector().searchText(e),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 Jn=class extends g{setup(){this.container=this.$el,this.name=this.$opts.name,R(this.$el,()=>{this.$emit(this.name,this.$opts)})}};var Qn=class extends g{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){me(t,200)}close(t){fe(t,200)}click(t){t.preventDefault();let e=document.querySelectorAll(this.targetSelector);for(let i of e)(this.isOpen?this.close:this.open)(i);this.isOpen=!this.isOpen,this.updateSystemAjax(this.isOpen)}updateSystemAjax(t){window.$http.patch(this.updateEndpoint,{expand:t?"true":"false"})}};var ti=class extends g{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=Nt(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 zt(this.container,()=>{this.hideSuggestions()})}async updateSuggestions(t){let{data:e}=await window.$http.get("/search/suggest",{term:t});if(!this.input.value)return;let i=_t(e);this.suggestionResultsWrap.innerHTML="",this.suggestionResultsWrap.style.opacity="1",this.loadingWrap.style.display="none",this.suggestionResultsWrap.append(i),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 ei=class extends g{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 ni=class extends g{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(){R(this.filterTabs,i=>{this.resetAll(),this.filter=i.target.dataset.filter,this.setActiveFilterTab(this.filter),this.loadGallery()}),this.searchForm.addEventListener("submit",i=>{this.resetListView(),this.loadGallery(),this.cancelSearch.toggleAttribute("hidden",!this.searchInput.value),i.preventDefault()}),R(this.cancelSearch,()=>{this.resetListView(),this.resetSearchView(),this.loadGallery()}),K(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",i=>{i.target.src=window.baseUrl("loading_error.png")},!0),R(this.selectButton,()=>{this.callback&&this.callback(this.lastSelected),this.hide()}),K(this.formContainer,"#image-manager-delete","click",()=>{this.lastSelected&&this.loadImageEditForm(this.lastSelected.id,!0)}),K(this.formContainer,"#image-manager-rebuild-thumbs","click",async(i,r)=>{r.disabled=!0,this.lastSelected&&await this.rebuildThumbnails(this.lastSelected.id),r.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",i=>{if(!(Math.ceil(t.scrollHeight-t.scrollTop)===t.clientHeight)||i.deltaY<1)return;let s=Date.now()-1e3;e.push(Date.now()),e=e.filter(a=>a>=s),e.length>5&&this.canLoadMore()&&this.runLoadMore()})}show(t,e="gallery"){this.resetAll(),this.callback=t,this.type=e,this.getPopup().show();let i=e!=="gallery";this.dropzoneContainer.classList.toggle("hidden",i),this.uploadButton.classList.toggle("hidden",i),this.uploadHint.classList.toggle("hidden",i),window.$components.firstOnElement(this.container,"dropzone").toggleActive(!i),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),Le(this.listContainer)}addReturnedHtmlElementsToList(t){let e=document.createElement("div");e.innerHTML=t;let i=e.querySelector(".load-more");i&&(i.remove(),this.loadMore.innerHTML=i.innerHTML),this.loadMore.toggleAttribute("hidden",!i),window.$components.init(e);for(let r of[...e.children])this.listContainer.appendChild(r)}setActiveFilterTab(t){for(let e of this.filterTabs){let i=e.dataset.filter===t;e.setAttribute("aria-selected",i?"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(){De(this.listContainer),this.page=1}refreshGallery(){this.resetListView(),this.loadGallery()}async onImageSelectEvent(t){let e=JSON.parse(t.detail.data),i=e&&e.id===this.lastSelected.id&&Date.now()-this.lastSelectedTime<400,r=t.target.classList.contains("selected");[...this.listContainer.querySelectorAll(".selected")].forEach(o=>{o.classList.remove("selected")}),!r&&!i?(t.target.classList.add("selected"),e=await this.loadImageEditForm(e.id)):i?i&&(e=this.lastSelected):this.resetEditForm(),this.selectButton.classList.toggle("hidden",r),i&&this.callback&&(this.callback(e),this.hide()),this.lastSelected=e,this.lastSelectedTime=Date.now()}async loadImageEditForm(t,e=!1){e||(this.formContainer.innerHTML="");let i=e?{delete:!0}:{},{data:r}=await window.$http.get(`/images/edit/${t}`,i);this.formContainer.innerHTML=r,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(){De(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 ii=class extends g{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 ri=class extends g{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 jc=Go(Oc()),Vc=Go(Uc()),wi=class{constructor(){this.renderer=new jc.default({html:!0}),this.renderer.use(Vc.default,{label:!0})}getRenderer(){return this.renderer}render(t){return this.renderer.render(t)}};function hf(n,t){return document.createElement(n,t)}function df(n,t,e){return document.createElementNS(n,t,e)}function pf(){return te(document.createDocumentFragment())}function ff(n){return document.createTextNode(n)}function mf(n){return document.createComment(n)}function gf(n,t,e){if(qt(n)){let i=n;for(;i&&qt(i);)i=te(i).parent;n=i??n}qt(t)&&(t=te(t,n)),e&&qt(e)&&(e=te(e).firstChildNode),n.insertBefore(t,e)}function bf(n,t){n.removeChild(t)}function vf(n,t){qt(t)&&(t=te(t,n)),n.appendChild(t)}function Wc(n){if(qt(n)){for(;n&&qt(n);)n=te(n).parent;return n??null}return n.parentNode}function wf(n){var t;if(qt(n)){let e=te(n),i=Wc(e);if(i&&e.lastChildNode){let r=Array.from(i.childNodes),o=r.indexOf(e.lastChildNode);return(t=r[o+1])!==null&&t!==void 0?t:null}return null}return n.nextSibling}function yf(n){return n.tagName}function xf(n,t){n.textContent=t}function kf(n){return n.textContent}function Cf(n){return n.nodeType===1}function Ef(n){return n.nodeType===3}function _f(n){return n.nodeType===8}function qt(n){return n.nodeType===11}function te(n,t){var e,i,r;let o=n;return(e=o.parent)!==null&&e!==void 0||(o.parent=t??null),(i=o.firstChildNode)!==null&&i!==void 0||(o.firstChildNode=n.firstChild),(r=o.lastChildNode)!==null&&r!==void 0||(o.lastChildNode=n.lastChild),o}var yi={createElement:hf,createElementNS:df,createTextNode:ff,createDocumentFragment:pf,createComment:mf,insertBefore:gf,removeChild:bf,appendChild:vf,parentNode:Wc,nextSibling:wf,tagName:yf,setTextContent:xf,getTextContent:kf,isElement:Cf,isText:Ef,isComment:_f,isDocumentFragment:qt};function Bt(n,t,e,i,r){let o=t===void 0?void 0:t.key;return{sel:n,data:t,children:e,text:i,elm:r,key:o}}var Gc=Array.isArray;function Kc(n){return typeof n=="string"||typeof n=="number"||n instanceof String||n instanceof Number}function Eo(n){return n===void 0}function ut(n){return n!==void 0}var _o=Bt("",{},[],void 0,void 0);function Je(n,t){var e,i;let r=n.key===t.key,o=((e=n.data)===null||e===void 0?void 0:e.is)===((i=t.data)===null||i===void 0?void 0:i.is),s=n.sel===t.sel,a=!n.sel&&n.sel===t.sel?typeof n.text==typeof t.text:!0;return s&&r&&o&&a}function Af(){throw new Error("The document fragment is not supported on this platform.")}function Df(n,t){return n.isElement(t)}function Lf(n,t){return n.isDocumentFragment(t)}function Tf(n,t,e){var i;let r={};for(let o=t;o<=e;++o){let s=(i=n[o])===null||i===void 0?void 0:i.key;s!==void 0&&(r[s]=o)}return r}var $f=["create","update","remove","destroy","pre","post"];function So(n,t,e){let i={create:[],update:[],remove:[],destroy:[],pre:[],post:[]},r=t!==void 0?t:yi;for(let p of $f)for(let m of n){let w=m[p];w!==void 0&&i[p].push(w)}function o(p){let m=p.id?"#"+p.id:"",w=p.getAttribute("class"),v=w?"."+w.split(" ").join("."):"";return Bt(r.tagName(p).toLowerCase()+m+v,{},[],void 0,p)}function s(p){return Bt(void 0,{},[],void 0,p)}function a(p,m){return function(){if(--m===0){let v=r.parentNode(p);r.removeChild(v,p)}}}function l(p,m){var w,v,b,k;let x,E=p.data;if(E!==void 0){let D=(w=E.hook)===null||w===void 0?void 0:w.init;ut(D)&&(D(p),E=p.data)}let y=p.children,A=p.sel;if(A==="!")Eo(p.text)&&(p.text=""),p.elm=r.createComment(p.text);else if(A!==void 0){let D=A.indexOf("#"),M=A.indexOf(".",D),T=D>0?D:A.length,P=M>0?M:A.length,H=D!==-1||M!==-1?A.slice(0,Math.min(T,P)):A,U=p.elm=ut(E)&&ut(x=E.ns)?r.createElementNS(x,H,E):r.createElement(H,E);for(T0&&U.setAttribute("class",A.slice(P+1).replace(/\./g," ")),x=0;x0&&(u.attrs=l),Object.keys(c).length>0&&(u.dataset=c),a[0]==="s"&&a[1]==="v"&&a[2]==="g"&&(a.length===3||a[3]==="."||a[3]==="#")&&Ao(u,h,a),Bt(a,u,h,void 0,n)}else return e.isText(n)?(i=e.getTextContent(n),Bt(void 0,void 0,void 0,i,n)):e.isComment(n)?(i=e.getTextContent(n),Bt("!",{},[],i,n)):Bt("",{},[],void 0,n)}var If="http://www.w3.org/1999/xlink",Mf="http://www.w3.org/XML/1998/namespace";function Zc(n,t){let e,i=t.elm,r=n.data.attrs,o=t.data.attrs;if(!(!r&&!o)&&r!==o){r=r||{},o=o||{};for(e in o){let s=o[e];r[e]!==s&&(s===!0?i.setAttribute(e,""):s===!1?i.removeAttribute(e):e.charCodeAt(0)!==120?i.setAttribute(e,s):e.charCodeAt(3)===58?i.setAttributeNS(Mf,e,s):e.charCodeAt(5)===58?i.setAttributeNS(If,e,s):i.setAttribute(e,s))}for(e in r)e in o||i.removeAttribute(e)}}var Do={create:Zc,update:Zc};var xi;function Ff(){return xi||(xi=So([Do]),xi)}function Xc(n,t){let e=document.createElement("div");e.innerHTML=t,Ff()(Qe(n),Qe(e))}var ki=class{constructor(t){this.editor=t,this.container=t.config.displayEl,this.doc=null,this.lastDisplayClick=0,this.container.contentDocument.readyState==="complete"?this.onLoad():this.container.addEventListener("load",this.onLoad.bind(this)),this.updateVisibility(t.settings.get("showPreview")),t.settings.onChange("showPreview",e=>this.updateVisibility(e))}updateVisibility(t){let e=this.container.closest(".markdown-editor-wrap");e.style.display=t?null:"none"}onLoad(){this.doc=this.container.contentDocument,this.loadStylesIntoDisplay(),this.doc.body.className="page-content",this.doc.addEventListener("click",this.onDisplayClick.bind(this))}onDisplayClick(t){let e=Date.now()-this.lastDisplayClick<300,i=t.target.closest("a");if(i!==null){t.preventDefault(),window.open(i.getAttribute("href"));return}let r=t.target.closest("[drawio-diagram]");if(r!==null&&e){this.editor.actions.editDrawing(r);return}this.lastDisplayClick=Date.now()}loadStylesIntoDisplay(){this.doc.documentElement.classList.add("markdown-editor-display"),document.documentElement.classList.contains("dark-mode")&&(this.doc.documentElement.style.backgroundColor="#222",this.doc.documentElement.classList.add("dark-mode")),this.doc.head.innerHTML="";let t=document.head.querySelectorAll("style,link[rel=stylesheet]");for(let e of t){let i=e.cloneNode(!0);this.doc.head.appendChild(i)}}patchWithHtml(t){let{body:e}=this.doc;if(e.children.length===0){let r=document.createElement("div");this.doc.body.append(r)}let i=e.children[0];Xc(i,t)}scrollToIndex(t){let e=this.doc.body?.children[0]?.children;if(e&&e.length<=t)return;(t===-1?e[e.length-1]:e[t]).scrollIntoView({block:"start",inline:"nearest",behavior:"smooth"})}};function Ci(n){return new Promise((t,e)=>{n.oncomplete=n.onsuccess=()=>t(n.result),n.onabort=n.onerror=()=>e(n.error)})}function qf(n,t){let e=indexedDB.open(n);e.onupgradeneeded=()=>e.result.createObjectStore(t);let i=Ci(e);return(r,o)=>i.then(s=>o(s.transaction(t,r).objectStore(t)))}var Lo;function To(){return Lo||(Lo=qf("keyval-store","keyval")),Lo}function $o(n,t=To()){return t("readonly",e=>Ci(e.get(n)))}function Io(n,t,e=To()){return e("readwrite",i=>(i.put(t,n),Ci(i.transaction)))}function Mo(n,t=To()){return t("readwrite",e=>(e.delete(n),Ci(e.transaction)))}var $t=null,Bo,Ei,Fo,qo="last-drawing-save";function Po(n){$t.contentWindow.postMessage(JSON.stringify(n),Bo)}function Pf(n){Io(qo,n.data),Fo&&Fo(n.data).then(()=>{Mo(qo)})}function Of(n){Po({action:"export",format:"xmlpng",xml:n.xml,spin:"Updating drawing"})}function Rf(){Ei&&Ei().then(n=>{Po({action:"load",autosave:1,xml:n})})}function Nf(){let n={};window.$events.emitPublic($t,"editor-drawio::configure",{config:n}),Po({action:"configure",config:n})}function Yc(){window.removeEventListener("message",Jc),$t&&document.body.removeChild($t)}function Jc(n){if(!n.data||n.data.length<1||n.origin!==Bo)return;let t=JSON.parse(n.data);t.event==="init"?Rf():t.event==="exit"?Yc():t.event==="save"?Of(t):t.event==="export"?Pf(t):t.event==="configure"&&Nf()}async function zf(){let n=await $o(qo),t=document.getElementById("unsaved-drawing-dialog");t||console.error("Missing expected unsaved-drawing dialog"),n&&await window.$components.firstOnElement(t,"confirm-dialog").show()&&(Ei=async()=>n)}async function tn(n,t,e){Ei=t,Fo=e,await zf(),$t=document.createElement("iframe"),$t.setAttribute("frameborder","0"),window.addEventListener("message",Jc),$t.setAttribute("src",n),$t.setAttribute("class","fullscreen"),$t.style.backgroundColor="#FFFFFF",document.body.appendChild($t),Bo=new URL(n).origin}async function Oo(n,t){let e={image:n,uploaded_to:t};return(await window.$http.post(window.baseUrl("/images/drawio"),e)).data}function ee(){Yc()}async function _i(n){try{return`data:image/png;base64,${(await window.$http.get(window.baseUrl(`/images/drawio/base64/${n}`))).data.content}`}catch(t){throw t instanceof window.$http.HttpError&&window.$events.showResponseError(t),ee(),t}}var en,Ro,xe,Si,ke,Ai,Pt,ne,Wt,ye,rt,ht,nn,No,rn,zo,Ce,Di,dt,vt,Ti,tu,Li=class{constructor(t){ot(this,en);ot(this,xe);ot(this,ke);ot(this,Pt);ot(this,Wt);ot(this,rt);ot(this,nn);ot(this,rn);ot(this,Ce);ot(this,dt);ot(this,Ti);this.editor=t,this.lastContent={html:"",markdown:""}}updateAndRender(){let t=L(this,xe,Si).call(this);this.editor.config.inputEl.value=t;let e=this.editor.markdown.render(t);window.$events.emit("editor-html-change",""),window.$events.emit("editor-markdown-change",""),this.lastContent.html=e,this.lastContent.markdown=t,this.editor.display.patchWithHtml(e)}getContent(){return this.lastContent}showImageInsert(){window.$components.first("image-manager").show(e=>{let i=e.thumbs?.display||e.url,o=`[![${L(this,Wt,ye).call(this)||e.name}](${i})](${e.url})`;L(this,Pt,ne).call(this,o,o.length)},"gallery")}insertImage(){let t=`![${L(this,Wt,ye).call(this)}](http://)`;L(this,Pt,ne).call(this,t,t.length-1)}insertLink(){let t=L(this,Wt,ye).call(this),e=`[${t}]()`,i=t===""?-3:-1;L(this,Pt,ne).call(this,e,e.length+i)}showImageManager(){let t=L(this,rt,ht).call(this);window.$components.first("image-manager").show(i=>{L(this,en,Ro).call(this,i,t)},"drawio")}showLinkSelector(){let t=L(this,rt,ht).call(this),e=window.$components.first("entity-selector-popup"),i=L(this,Wt,ye).call(this,t);e.show(r=>{let s=`[${i||r.name}](${r.link})`;L(this,Pt,ne).call(this,s,s.length,t)},i,{searchEndpoint:"/search/entity-selector",entityTypes:"page,book,chapter,bookshelf",entityPermission:"view"})}startDrawing(){let t=this.editor.config.drawioUrl;if(!t)return;let e=L(this,rt,ht).call(this);tn(t,()=>Promise.resolve(""),async i=>{let r={image:i,uploaded_to:Number(this.editor.config.pageId)};try{let o=await window.$http.post("/images/drawio",r);L(this,en,Ro).call(this,o.data,e),ee()}catch(o){throw this.handleDrawingUploadError(o),new Error(`Failed to save image with error: ${o}`)}})}editDrawing(t){let{drawioUrl:e}=this.editor.config;if(!e)return;let i=L(this,rt,ht).call(this),r=t.getAttribute("drawio-diagram");tn(e,()=>_i(r),async o=>{let s={image:o,uploaded_to:Number(this.editor.config.pageId)};try{let a=await window.$http.post("/images/drawio",s),l=`
    `,c=L(this,xe,Si).call(this).split(` +`);dr(t)}}function Xu(n){n.status&&n.status>=400&&n.data&&n.data.message&&dr(n.data.message)}var fr={};Se(fr,{HttpError:()=>sn,createXMLHttpRequest:()=>Ju,delete:()=>ih,get:()=>Qu,patch:()=>nh,post:()=>th,put:()=>eh});async function Yu(n){if(n.status===204)return null;let e=(n.headers.get("Content-Type")||"").split(";")[0].split("/").pop();return e==="javascript"||e==="json"?n.json():n.text()}var sn=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 Ju(n,t,e={}){let i=document.querySelector("meta[name=token]").getAttribute("content"),r=new XMLHttpRequest;for(let[o,s]of Object.entries(e))r.addEventListener(o,s.bind(r));return r.open(n,t),r.withCredentials=!0,r.setRequestHeader("X-CSRF-TOKEN",i),r}async function Ko(n,t={}){let e=n;if(e.startsWith("http")||(e=window.baseUrl(e)),t.params){let l=new URL(e);for(let c of Object.keys(t.params)){let u=t.params[c];typeof u<"u"&&u!==null&&l.searchParams.set(c,u)}e=l.toString()}let i=document.querySelector("meta[name=token]").getAttribute("content"),r={...t,credentials:"same-origin"};r.headers={...r.headers||{},baseURL:window.baseUrl(""),"X-CSRF-TOKEN":i};let o=await fetch(e,r),s=await Yu(o),a={data:s,headers:o.headers,redirected:o.redirected,status:o.status,statusText:o.statusText,url:o.url,original:o};if(!o.ok)throw new sn(o,s);return a}async function an(n,t,e=null){let i={method:n,body:e};return typeof e=="object"&&!(e instanceof FormData)&&(i.headers={"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},i.body=JSON.stringify(e)),e instanceof FormData&&n!=="post"&&(e.append("_method",n),i.method="post"),Ko(t,i)}async function Qu(n,t={}){return Ko(n,{method:"GET",params:t})}async function th(n,t=null){return an("POST",n,t)}async function eh(n,t=null){return an("PUT",n,t)}async function nh(n,t=null){return an("PATCH",n,t)}async function ih(n,t=null){return an("DELETE",n,t)}var mr=class{constructor(){this.store=new Map,this.parseTranslations()}parseTranslations(){let t=document.querySelectorAll('meta[name="translation"]');for(let e of t){let i=e.getAttribute("key"),r=e.getAttribute("value");this.store.set(i,r)}}get(t,e){let i=this.getTransText(t);return this.performReplacements(i,e)}getPlural(t,e,i){let r=this.getTransText(t);return this.parsePlural(r,e,i)}parsePlural(t,e,i){let r=t.split("|"),o=/^{([0-9]+)}/,s=/^\[([0-9]+),([0-9*]+)]/,a=null;for(let l of r){let c=l.match(o);if(c!==null&&Number(c[1])===e){a=l.replace(o,"").trim();break}let u=l.match(s);if(u!==null&&Number(u[1])<=e&&(u[2]==="*"||Number(u[2])>=e)){a=l.replace(s,"").trim();break}}return a===null&&r.length>1&&(a=e===1?r[0]:r[1]),a===null&&(a=r[0]),this.performReplacements(a,i)}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 i=t.match(/:(\S+)/g);if(i===null)return t;let r=t;return i.forEach(o=>{let s=o.substring(1);typeof e[s]>"u"||(r=r.replace(o,e[s]))}),r}},Zo=mr;var yr={};Se(yr,{first:()=>ah,firstOnElement:()=>ch,get:()=>lh,init:()=>vr,register:()=>wr});function gr(n){let t=i=>i.slice(0,1).toUpperCase()+i.slice(1),e=n.split("-");return e[0]+e.slice(1).map(t).join("")}function Xo(n){return n.replace(/[A-Z]/g,(t,e)=>(e>0?"-":"")+t.toLowerCase())}var Ae={},Yo={},br=new WeakMap;function rh(n,t){let e={},i={},r=`${n}@`,o=`[refs*="${r}"]`,s=[...t.querySelectorAll(o)];t.matches(o)&&s.push(t);for(let a of s){let l=a.getAttribute("refs").split(" ").filter(c=>c.startsWith(r)).map(c=>c.replace(r,"")).map(gr);for(let c of l)e[c]=a,typeof i[c]>"u"&&(i[c]=[]),i[c].push(a)}return{refs:e,manyRefs:i}}function oh(n,t){let e={},i=`option:${n}:`;for(let{name:r,value:o}of t.attributes)if(r.startsWith(i)){let s=r.replace(i,"");e[gr(s)]=o||""}return e}function sh(n,t){let e=Yo[n];if(e===void 0)return;let i;try{i=new e,i.$name=n,i.$el=t;let o=rh(n,t);i.$refs=o.refs,i.$manyRefs=o.manyRefs,i.$opts=oh(n,t),i.setup()}catch(o){console.error("Failed to create component",o,n,t)}typeof Ae[n]>"u"&&(Ae[n]=[]),Ae[n].push(i);let r=br.get(t)||{};r[n]=i,br.set(t,r)}function vr(n=document){let t=n.querySelectorAll("[component],[components]");for(let e of t){let i=`${e.getAttribute("component")||""} ${e.getAttribute("components")}`.toLowerCase().split(" ").filter(Boolean);for(let r of i)sh(r,e)}}function wr(n){let t=Object.keys(n);for(let e of t)Yo[Xo(e)]=n[e]}function ah(n){return(Ae[n]||[null])[0]}function lh(n){return Ae[n]||[]}function ch(n,t){return(br.get(n)||{})[t]||null}var jo={};Se(jo,{AddRemoveRows:()=>cn,AjaxDeleteRow:()=>un,AjaxForm:()=>hn,Attachments:()=>dn,AttachmentsList:()=>pn,AutoSubmit:()=>mn,AutoSuggest:()=>fn,BackToTop:()=>gn,BookSort:()=>Fn,ChapterContents:()=>Bn,CodeEditor:()=>Pn,CodeHighlighter:()=>On,CodeTextarea:()=>Rn,Collapsible:()=>Nn,ConfirmDialog:()=>zn,CustomCheckbox:()=>Hn,DetailsHighlighter:()=>Un,Dropdown:()=>jn,DropdownSearch:()=>Vn,Dropzone:()=>Wn,EditorToolbox:()=>Gn,EntityPermissions:()=>Kn,EntitySearch:()=>Zn,EntitySelector:()=>Xn,EntitySelectorPopup:()=>Yn,EventEmitSelect:()=>Jn,ExpandToggle:()=>Qn,GlobalSearch:()=>ti,HeaderMobileToggle:()=>ei,ImageManager:()=>ni,ImagePicker:()=>ii,ListSortControl:()=>ri,MarkdownEditor:()=>Mi,NewUserPassword:()=>Fi,Notification:()=>qi,OptionalInput:()=>Bi,PageComment:()=>Pi,PageComments:()=>Oi,PageDisplay:()=>Ri,PageEditor:()=>Ni,PagePicker:()=>Hi,PermissionsTable:()=>Ui,Pointer:()=>ji,Popup:()=>Vi,SettingAppColorScheme:()=>Wi,SettingColorPicker:()=>Gi,SettingHomepageControl:()=>Ki,ShelfSort:()=>Zi,ShortcutInput:()=>Yi,Shortcuts:()=>Xi,SortableList:()=>Ji,SubmitOnChange:()=>Qi,Tabs:()=>tr,TagManager:()=>er,TemplateManager:()=>nr,ToggleSwitch:()=>ir,TriLayout:()=>rr,UserSelect:()=>or,WebhookEvents:()=>sr,WysiwygEditor:()=>cr,WysiwygInput:()=>ur});function Et(n,t={},e=[]){let i=document.createElement(n);for(let[r,o]of Object.entries(t))o===null?i.removeAttribute(r):i.setAttribute(r,o);for(let r of e)typeof r=="string"?i.append(document.createTextNode(r)):i.append(r);return i}function xr(n,t){let e=document.querySelectorAll(n);for(let i of e)t(i)}function ln(n,t,e){for(let i of t)n.addEventListener(i,e)}function R(n,t){Array.isArray(n)||(n=[n]);for(let e of n)e.addEventListener("click",t),e.addEventListener("keydown",i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),t(i))})}function Jo(n,t,e){Array.isArray(t)||(t=[t]);let i=r=>{r.key===n&&e(r)};t.forEach(r=>r.addEventListener("keydown",i))}function se(n,t){Jo("Enter",n,t)}function Qo(n,t){Jo("Escape",n,t)}function K(n,t,e,i){n.addEventListener(e,r=>{let o=r.target.closest(t);o&&i.call(o,r,o)})}function ts(n,t){let e=document.querySelectorAll(n);t=t.toLowerCase();for(let i of e)if(i.textContent.toLowerCase().includes(t))return i;return null}function De(n){n.innerHTML='
    '}function ae(){let n=document.createElement("div");return n.classList.add("loading-container"),n.innerHTML="
    ",n}function Le(n){let t=n.querySelectorAll(".loading-container");for(let e of t)e.remove()}function _t(n){let t=document.createElement("div");return t.innerHTML=n,window.$components.init(t),t.children[0]}function Nt(n,t,e){let i;return function(...o){let s=this,a=function(){i=null,e||n.apply(s,o)},l=e&&!i;clearTimeout(i),i=setTimeout(a,t),l&&n.apply(s,o)}}function Cr(n){if(!n)return;let t=n.closest("details");t&&!t.open&&(t.open=!0),n.scrollIntoView({behavior:"smooth"});let e=getComputedStyle(document.body).getPropertyValue("--color-link");n.style.outline=`2px dashed ${e}`,n.style.outlineOffset="5px",n.style.transition=null,setTimeout(()=>{n.style.transition="outline linear 3s",n.style.outline="2px dashed rgba(0, 0, 0, 0)";let i=()=>{n.removeEventListener("transitionend",i),n.style.transition=null,n.style.outline=null,n.style.outlineOffset=null};n.addEventListener("transitionend",i)},1e3)}function es(n){return n.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function ns(){let n=()=>((1+Math.random())*65536|0).toString(16).substring(1);return`${n()+n()}-${n()}-${n()}-${n()}-${n()}${n()}${n()}`}function is(n){return new Promise(t=>{setTimeout(t,n)})}var g=class{constructor(){at(this,"$name","");at(this,"$el",null);at(this,"$refs",{});at(this,"$manyRefs",{});at(this,"$opts",{})}setup(){}$emit(t,e={}){e.from=this;let i=this.$name,r=new CustomEvent(`${i}-${t}`,{bubbles:!0,detail:e});this.$el.dispatchEvent(r)}};var cn=class extends g{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)),K(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(),i=t.querySelectorAll('[name*="randrowid"]');for(let r of i)r.name=r.name.split("randrowid").join(e)}};var un=class extends g{setup(){this.row=this.$el,this.url=this.$opts.url,this.deleteButtons=this.$manyRefs.delete,R(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 hn=class extends g{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}se(this.container,t=>{this.submitFakeForm(),t.preventDefault()}),this.submitButtons.forEach(t=>R(t,this.submitFakeForm.bind(this)))}submitFakeForm(){let t=new FormData,e=this.container.querySelectorAll("[name]");for(let i of e)t.append(i.getAttribute("name"),i.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 dn=class extends g{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 i=e.target.closest("[data-drag-content]").getAttribute("data-drag-content"),r=JSON.parse(i);window.$events.emit("editor::insert",{html:r["text/html"],markdown:r["text/plain"]})}),this.attachLinkButton.addEventListener("click",()=>{this.showSection("links")})}showSection(t){let e={links:this.linksContainer,edit:this.editContainer,list:this.listContainer};for(let[i,r]of Object.entries(e))r.toggleAttribute("hidden",i!==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"),De(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 pn=class extends g{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 Te,Er,$e,_r,zt=class{constructor(t,e=null,i=null){ot(this,Te);ot(this,$e);this.containers=[t],this.onEscape=e,this.onEnter=i,t.addEventListener("keydown",L(this,Te,Er).bind(this))}shareHandlingToEl(t){this.containers.push(t),t.addEventListener("keydown",L(this,Te,Er).bind(this))}focusNext(){let t=L(this,$e,_r).call(this),i=t.indexOf(document.activeElement)+1;i>=t.length&&(i=0),t[i].focus()}focusPrevious(){let t=L(this,$e,_r).call(this),i=t.indexOf(document.activeElement)-1;i<0&&(i=t.length-1),t[i].focus()}};Te=new WeakSet,Er=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))},$e=new WeakSet,_r=function(){let t=[],e='[tabindex]:not([tabindex="-1"]),[href],button:not([tabindex="-1"],[disabled]),input:not([type=hidden])';for(let i of this.containers)t.push(...i.querySelectorAll(e));return t};var Sr={},fn=class extends g{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 zt(this.list,()=>{this.input.focus(),setTimeout(()=>this.hideSuggestions(),1)},e=>{e.preventDefault();let i=e.target.textContent;i&&this.selectSuggestion(i)}).shareHandlingToEl(this.input),K(this.list,".text-item","click",(e,i)=>{this.selectSuggestion(i.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(),r=(await this.loadSuggestions(e,t)).filter(o=>e===""||o.toLowerCase().startsWith(e)).slice(0,10);this.displaySuggestions(r)}getNameFilterIfNeeded(){return this.type!=="value"?null:this.parent.querySelector("input").value}async loadSuggestions(t,e=null){t=t.slice(0,4);let i={search:t,name:e},r=`${this.url}:${JSON.stringify(i)}`;if(Sr[r])return Sr[r];let o=await window.$http.get(this.url,i);return Sr[r]=o.data,o.data}displaySuggestions(t){if(t.length===0){this.hideSuggestions();return}this.list.innerHTML=t.map(e=>`
  • ${es(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 mn=class extends g{setup(){this.form=this.$el,this.form.submit()}};var gn=class extends g{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,i=300,r=Date.now(),o=this.targetElem.getBoundingClientRect().top;function s(){let a=1-(Date.now()-r)/i,l=Math.abs(a*o);a>0?(e.scrollTop=l,requestAnimationFrame(s.bind(this))):e.scrollTop=t}requestAnimationFrame(s.bind(this))}};function rs(n,t){var e=Object.keys(n);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(n);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(n,r).enumerable})),e.push.apply(e,i)}return e}function At(n){for(var t=1;t=0)&&(e[r]=n[r]);return e}function dh(n,t){if(n==null)return{};var e=hh(n,t),i,r;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(n);for(r=0;r=0)&&Object.prototype.propertyIsEnumerable.call(n,i)&&(e[i]=n[i])}return e}function ph(n){return fh(n)||mh(n)||gh(n)||bh()}function fh(n){if(Array.isArray(n))return Pr(n)}function mh(n){if(typeof Symbol<"u"&&n[Symbol.iterator]!=null||n["@@iterator"]!=null)return Array.from(n)}function gh(n,t){if(n){if(typeof n=="string")return Pr(n,t);var e=Object.prototype.toString.call(n).slice(8,-1);if(e==="Object"&&n.constructor&&(e=n.constructor.name),e==="Map"||e==="Set")return Array.from(n);if(e==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e))return Pr(n,t)}}function Pr(n,t){(t==null||t>n.length)&&(t=n.length);for(var e=0,i=new Array(t);e"&&(t=t.substring(1)),n)try{if(n.matches)return n.matches(t);if(n.msMatchesSelector)return n.msMatchesSelector(t);if(n.webkitMatchesSelector)return n.webkitMatchesSelector(t)}catch{return!1}return!1}}function wh(n){return n.host&&n!==document&&n.host.nodeType?n.host:n.parentNode}function xt(n,t,e,i){if(n){e=e||document;do{if(t!=null&&(t[0]===">"?n.parentNode===e&&Dn(n,t):Dn(n,t))||i&&n===e)return n;if(n===e)break}while(n=wh(n))}return null}var ss=/\s+/g;function Y(n,t,e){if(n&&t)if(n.classList)n.classList[e?"add":"remove"](t);else{var i=(" "+n.className+" ").replace(ss," ").replace(" "+t+" "," ");n.className=(i+(e?" "+t:"")).replace(ss," ")}}function S(n,t,e){var i=n&&n.style;if(i){if(e===void 0)return document.defaultView&&document.defaultView.getComputedStyle?e=document.defaultView.getComputedStyle(n,""):n.currentStyle&&(e=n.currentStyle),t===void 0?e:e[t];!(t in i)&&t.indexOf("webkit")===-1&&(t="-webkit-"+t),i[t]=e+(typeof e=="string"?"":"px")}}function Xt(n,t){var e="";if(typeof n=="string")e=n;else do{var i=S(n,"transform");i&&i!=="none"&&(e=i+" "+e)}while(!t&&(n=n.parentNode));var r=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return r&&new r(e)}function vs(n,t,e){if(n){var i=n.getElementsByTagName(t),r=0,o=i.length;if(e)for(;r=o:s=r<=o,!s)return i;if(i===St())break;i=jt(i,!1)}return!1}function pe(n,t,e,i){for(var r=0,o=0,s=n.children;o2&&arguments[2]!==void 0?arguments[2]:{},r=i.evt,o=dh(i,Sh);Ve.pluginEvent.bind(I)(t,e,At({dragEl:C,parentEl:Z,ghostEl:q,rootEl:V,nextEl:Zt,lastDownEl:En,cloneEl:G,cloneHidden:Ut,dragStarted:Be,putSortable:tt,activeSortable:I.active,originalEvent:r,oldIndex:de,oldDraggableIndex:ze,newIndex:mt,newDraggableIndex:Ht,hideGhostForTarget:_s,unhideGhostForTarget:Ss,cloneNowHidden:function(){Ut=!0},cloneNowShown:function(){Ut=!1},dispatchSortableEvent:function(a){st({sortable:e,name:a,originalEvent:r})}},o))};function st(n){qe(At({putSortable:tt,cloneEl:G,targetEl:C,rootEl:V,oldIndex:de,oldDraggableIndex:ze,newIndex:mt,newDraggableIndex:Ht},n))}var C,Z,q,V,Zt,En,G,Ut,de,mt,ze,Ht,bn,tt,he=!1,Ln=!1,Tn=[],Gt,wt,Tr,$r,us,hs,Be,ce,He,Ue=!1,vn=!1,_n,nt,Ir=[],Or=!1,$n=[],Mn=typeof document<"u",wn=ms,ds=je||Mt?"cssFloat":"float",Ah=Mn&&!gs&&!ms&&"draggable"in document.createElement("div"),ks=function(){if(Mn){if(Mt)return!1;var n=document.createElement("x");return n.style.cssText="pointer-events:auto",n.style.pointerEvents==="auto"}}(),Cs=function(t,e){var i=S(t),r=parseInt(i.width)-parseInt(i.paddingLeft)-parseInt(i.paddingRight)-parseInt(i.borderLeftWidth)-parseInt(i.borderRightWidth),o=pe(t,0,e),s=pe(t,1,e),a=o&&S(o),l=s&&S(s),c=a&&parseInt(a.marginLeft)+parseInt(a.marginRight)+j(o).width,u=l&&parseInt(l.marginLeft)+parseInt(l.marginRight)+j(s).width;if(i.display==="flex")return i.flexDirection==="column"||i.flexDirection==="column-reverse"?"vertical":"horizontal";if(i.display==="grid")return i.gridTemplateColumns.split(" ").length<=1?"vertical":"horizontal";if(o&&a.float&&a.float!=="none"){var h=a.float==="left"?"left":"right";return s&&(l.clear==="both"||l.clear===h)?"vertical":"horizontal"}return o&&(a.display==="block"||a.display==="flex"||a.display==="table"||a.display==="grid"||c>=r&&i[ds]==="none"||s&&i[ds]==="none"&&c+u>r)?"vertical":"horizontal"},Dh=function(t,e,i){var r=i?t.left:t.top,o=i?t.right:t.bottom,s=i?t.width:t.height,a=i?e.left:e.top,l=i?e.right:e.bottom,c=i?e.width:e.height;return r===a||o===l||r+s/2===a+c/2},Lh=function(t,e){var i;return Tn.some(function(r){var o=r[it].options.emptyInsertThreshold;if(!(!o||Hr(r))){var s=j(r),a=t>=s.left-o&&t<=s.right+o,l=e>=s.top-o&&e<=s.bottom+o;if(a&&l)return i=r}}),i},Es=function(t){function e(o,s){return function(a,l,c,u){var h=a.options.group.name&&l.options.group.name&&a.options.group.name===l.options.group.name;if(o==null&&(s||h))return!0;if(o==null||o===!1)return!1;if(s&&o==="clone")return o;if(typeof o=="function")return e(o(a,l,c,u),s)(a,l,c,u);var d=(s?a:l).options.group.name;return o===!0||typeof o=="string"&&o===d||o.join&&o.indexOf(d)>-1}}var i={},r=t.group;(!r||Cn(r)!="object")&&(r={name:r}),i.name=r.name,i.checkPull=e(r.pull,!0),i.checkPut=e(r.put),i.revertClone=r.revertClone,t.group=i},_s=function(){!ks&&q&&S(q,"display","none")},Ss=function(){!ks&&q&&S(q,"display","")};Mn&&!gs&&document.addEventListener("click",function(n){if(Ln)return n.preventDefault(),n.stopPropagation&&n.stopPropagation(),n.stopImmediatePropagation&&n.stopImmediatePropagation(),Ln=!1,!1},!0);var Kt=function(t){if(C){t=t.touches?t.touches[0]:t;var e=Lh(t.clientX,t.clientY);if(e){var i={};for(var r in t)t.hasOwnProperty(r)&&(i[r]=t[r]);i.target=i.rootEl=e,i.preventDefault=void 0,i.stopPropagation=void 0,e[it]._onDragOver(i)}}},Th=function(t){C&&C.parentNode[it]._isOutsideThisEl(t.target)};function I(n,t){if(!(n&&n.nodeType&&n.nodeType===1))throw"Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(n));this.el=n,this.options=t=kt({},t),n[it]=this;var e={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(n.nodeName)?">li":">*",swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return Cs(n,this.options)},ghostClass:"sortable-ghost",chosenClass:"sortable-chosen",dragClass:"sortable-drag",ignore:"a, img",filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(s,a){s.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:I.supportPointer!==!1&&"PointerEvent"in window&&!Re,emptyInsertThreshold:5};Ve.initializePlugins(this,n,e);for(var i in e)!(i in t)&&(t[i]=e[i]);Es(t);for(var r in this)r.charAt(0)==="_"&&typeof this[r]=="function"&&(this[r]=this[r].bind(this));this.nativeDraggable=t.forceFallback?!1:Ah,this.nativeDraggable&&(this.options.touchStartThreshold=1),t.supportPointer?O(n,"pointerdown",this._onTapStart):(O(n,"mousedown",this._onTapStart),O(n,"touchstart",this._onTapStart)),this.nativeDraggable&&(O(n,"dragover",this),O(n,"dragenter",this)),Tn.push(this.el),t.store&&t.store.get&&this.sort(t.store.get(this)||[]),kt(this,Ch())}I.prototype={constructor:I,_isOutsideThisEl:function(t){!this.el.contains(t)&&t!==this.el&&(ce=null)},_getDirection:function(t,e){return typeof this.options.direction=="function"?this.options.direction.call(this,t,e,C):this.options.direction},_onTapStart:function(t){if(t.cancelable){var e=this,i=this.el,r=this.options,o=r.preventOnFilter,s=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,u=r.filter;if(Oh(i),!C&&!(/mousedown|pointerdown/.test(s)&&t.button!==0||r.disabled)&&!c.isContentEditable&&!(!this.nativeDraggable&&Re&&l&&l.tagName.toUpperCase()==="SELECT")&&(l=xt(l,r.draggable,i,!1),!(l&&l.animated)&&En!==l)){if(de=J(l),ze=J(l,r.draggable),typeof u=="function"){if(u.call(this,t,l,this)){st({sortable:e,rootEl:c,name:"filter",targetEl:l,toEl:i,fromEl:i}),lt("filter",e,{evt:t}),o&&t.cancelable&&t.preventDefault();return}}else if(u&&(u=u.split(",").some(function(h){if(h=xt(c,h.trim(),i,!1),h)return st({sortable:e,rootEl:h,name:"filter",targetEl:l,fromEl:i,toEl:i}),lt("filter",e,{evt:t}),!0}),u)){o&&t.cancelable&&t.preventDefault();return}r.handle&&!xt(c,r.handle,i,!1)||this._prepareDragStart(t,a,l)}}},_prepareDragStart:function(t,e,i){var r=this,o=r.el,s=r.options,a=o.ownerDocument,l;if(i&&!C&&i.parentNode===o){var c=j(i);if(V=o,C=i,Z=C.parentNode,Zt=C.nextSibling,En=i,bn=s.group,I.dragged=C,Gt={target:C,clientX:(e||t).clientX,clientY:(e||t).clientY},us=Gt.clientX-c.left,hs=Gt.clientY-c.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,C.style["will-change"]="all",l=function(){if(lt("delayEnded",r,{evt:t}),I.eventCanceled){r._onDrop();return}r._disableDelayedDragEvents(),!os&&r.nativeDraggable&&(C.draggable=!0),r._triggerDragStart(t,e),st({sortable:r,name:"choose",originalEvent:t}),Y(C,s.chosenClass,!0)},s.ignore.split(",").forEach(function(u){vs(C,u.trim(),Mr)}),O(a,"dragover",Kt),O(a,"mousemove",Kt),O(a,"touchmove",Kt),O(a,"mouseup",r._onDrop),O(a,"touchend",r._onDrop),O(a,"touchcancel",r._onDrop),os&&this.nativeDraggable&&(this.options.touchStartThreshold=4,C.draggable=!0),lt("delayStart",this,{evt:t}),s.delay&&(!s.delayOnTouchOnly||e)&&(!this.nativeDraggable||!(je||Mt))){if(I.eventCanceled){this._onDrop();return}O(a,"mouseup",r._disableDelayedDrag),O(a,"touchend",r._disableDelayedDrag),O(a,"touchcancel",r._disableDelayedDrag),O(a,"mousemove",r._delayedDragTouchMoveHandler),O(a,"touchmove",r._delayedDragTouchMoveHandler),s.supportPointer&&O(a,"pointermove",r._delayedDragTouchMoveHandler),r._dragStartTimer=setTimeout(l,s.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(){C&&Mr(C),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var t=this.el.ownerDocument;B(t,"mouseup",this._disableDelayedDrag),B(t,"touchend",this._disableDelayedDrag),B(t,"touchcancel",this._disableDelayedDrag),B(t,"mousemove",this._delayedDragTouchMoveHandler),B(t,"touchmove",this._delayedDragTouchMoveHandler),B(t,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(t,e){e=e||t.pointerType=="touch"&&t,!this.nativeDraggable||e?this.options.supportPointer?O(document,"pointermove",this._onTouchMove):e?O(document,"touchmove",this._onTouchMove):O(document,"mousemove",this._onTouchMove):(O(C,"dragend",this),O(V,"dragstart",this._onDragStart));try{document.selection?Sn(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},_dragStarted:function(t,e){if(he=!1,V&&C){lt("dragStarted",this,{evt:e}),this.nativeDraggable&&O(document,"dragover",Th);var i=this.options;!t&&Y(C,i.dragClass,!1),Y(C,i.ghostClass,!0),I.active=this,t&&this._appendGhost(),st({sortable:this,name:"start",originalEvent:e})}else this._nulling()},_emulateDragOver:function(){if(wt){this._lastX=wt.clientX,this._lastY=wt.clientY,_s();for(var t=document.elementFromPoint(wt.clientX,wt.clientY),e=t;t&&t.shadowRoot&&(t=t.shadowRoot.elementFromPoint(wt.clientX,wt.clientY),t!==e);)e=t;if(C.parentNode[it]._isOutsideThisEl(t),e)do{if(e[it]){var i=void 0;if(i=e[it]._onDragOver({clientX:wt.clientX,clientY:wt.clientY,target:t,rootEl:e}),i&&!this.options.dragoverBubble)break}t=e}while(e=e.parentNode);Ss()}},_onTouchMove:function(t){if(Gt){var e=this.options,i=e.fallbackTolerance,r=e.fallbackOffset,o=t.touches?t.touches[0]:t,s=q&&Xt(q,!0),a=q&&s&&s.a,l=q&&s&&s.d,c=wn&&nt&&ls(nt),u=(o.clientX-Gt.clientX+r.x)/(a||1)+(c?c[0]-Ir[0]:0)/(a||1),h=(o.clientY-Gt.clientY+r.y)/(l||1)+(c?c[1]-Ir[1]:0)/(l||1);if(!I.active&&!he){if(i&&Math.max(Math.abs(o.clientX-this._lastX),Math.abs(o.clientY-this._lastY))=0&&(st({rootEl:Z,name:"add",toEl:Z,fromEl:V,originalEvent:t}),st({sortable:this,name:"remove",toEl:Z,originalEvent:t}),st({rootEl:Z,name:"sort",toEl:Z,fromEl:V,originalEvent:t}),st({sortable:this,name:"sort",toEl:Z,originalEvent:t})),tt&&tt.save()):mt!==de&&mt>=0&&(st({sortable:this,name:"update",toEl:Z,originalEvent:t}),st({sortable:this,name:"sort",toEl:Z,originalEvent:t})),I.active&&((mt==null||mt===-1)&&(mt=de,Ht=ze),st({sortable:this,name:"end",toEl:Z,originalEvent:t}),this.save()))),this._nulling()},_nulling:function(){lt("nulling",this),V=C=Z=q=Zt=G=En=Ut=Gt=wt=Be=mt=Ht=de=ze=ce=He=tt=bn=I.dragged=I.ghost=I.clone=I.active=null,$n.forEach(function(t){t.checked=!0}),$n.length=Tr=$r=0},handleEvent:function(t){switch(t.type){case"drop":case"dragend":this._onDrop(t);break;case"dragenter":case"dragover":C&&(this._onDragOver(t),$h(t));break;case"selectstart":t.preventDefault();break}},toArray:function(){for(var t=[],e,i=this.el.children,r=0,o=i.length,s=this.options;rr.right+o||n.clientY>i.bottom&&n.clientX>i.left:n.clientY>r.bottom+o||n.clientX>i.right&&n.clientY>i.top}function qh(n,t,e,i,r,o,s,a){var l=i?n.clientY:n.clientX,c=i?e.height:e.width,u=i?e.top:e.left,h=i?e.bottom:e.right,d=!1;if(!s){if(a&&_nu+c*o/2:lh-_n)return-He}else if(l>u+c*(1-r)/2&&lh-c*o/2)?l>u+c/2?1:-1:0}function Bh(n){return J(C)1&&(F.forEach(function(a){o.addAnimationState({target:a,rect:ct?j(a):s}),Dr(a),a.fromRect=s,i.removeAnimationState(a)}),ct=!1,Nh(!this.options.removeCloneOnHide,r))},dragOverCompleted:function(e){var i=e.sortable,r=e.isOwner,o=e.insertion,s=e.activeSortable,a=e.parentEl,l=e.putSortable,c=this.options;if(o){if(r&&s._hideClone(),Me=!1,c.animation&&F.length>1&&(ct||!r&&!s.options.sort&&!l)){var u=j(z,!1,!0,!0);F.forEach(function(d){d!==z&&(cs(d,u),a.appendChild(d))}),ct=!0}if(!r)if(ct||kn(),F.length>1){var h=xn;s._showClone(i),s.options.animation&&!xn&&h&&ft.forEach(function(d){s.addAnimationState({target:d,rect:Fe}),d.fromRect=Fe,d.thisAnimationDuration=null})}else s._showClone(i)}},dragOverAnimationCapture:function(e){var i=e.dragRect,r=e.isOwner,o=e.activeSortable;if(F.forEach(function(a){a.thisAnimationDuration=null}),o.options.animation&&!r&&o.multiDrag.isMultiDrag){Fe=kt({},i);var s=Xt(z,!0);Fe.top-=s.f,Fe.left-=s.e}},dragOverAnimationComplete:function(){ct&&(ct=!1,kn())},drop:function(e){var i=e.originalEvent,r=e.rootEl,o=e.parentEl,s=e.sortable,a=e.dispatchSortableEvent,l=e.oldIndex,c=e.putSortable,u=c||this.sortable;if(i){var h=this.options,d=o.children;if(!ue)if(h.multiDragKey&&!this.multiDragKeyDown&&this._deselectMultiDrag(),Y(z,h.selectedClass,!~F.indexOf(z)),~F.indexOf(z))F.splice(F.indexOf(z),1),Ie=null,qe({sortable:s,rootEl:r,name:"deselect",targetEl:z,originalEvent:i});else{if(F.push(z),qe({sortable:s,rootEl:r,name:"select",targetEl:z,originalEvent:i}),i.shiftKey&&Ie&&s.el.contains(Ie)){var f=J(Ie),p=J(z);if(~f&&~p&&f!==p){var m,w;for(p>f?(w=f,m=p):(w=p,m=f+1);w1){var v=j(z),b=J(z,":not(."+this.options.selectedClass+")");if(!Me&&h.animation&&(z.thisAnimationDuration=null),u.captureAnimationState(),!Me&&(h.animation&&(z.fromRect=v,F.forEach(function(x){if(x.thisAnimationDuration=null,x!==z){var E=ct?j(x):v;x.fromRect=E,u.addAnimationState({target:x,rect:E})}})),kn(),F.forEach(function(x){d[b]?o.insertBefore(x,d[b]):o.appendChild(x),b++}),l===J(z))){var k=!1;F.forEach(function(x){if(x.sortableIndex!==J(x)){k=!0;return}}),k&&(a("update"),a("sort"))}F.forEach(function(x){Dr(x)}),u.animateAll()}yt=u}(r===o||c&&c.lastPutMode!=="clone")&&ft.forEach(function(x){x.parentNode&&x.parentNode.removeChild(x)})}},nullingGlobal:function(){this.isMultiDrag=ue=!1,ft.length=0},destroyGlobal:function(){this._deselectMultiDrag(),B(document,"pointerup",this._deselectMultiDrag),B(document,"mouseup",this._deselectMultiDrag),B(document,"touchend",this._deselectMultiDrag),B(document,"keydown",this._checkKeyDown),B(document,"keyup",this._checkKeyUp)},_deselectMultiDrag:function(e){if(!(typeof ue<"u"&&ue)&&yt===this.sortable&&!(e&&xt(e.target,this.options.draggable,this.sortable.el,!1))&&!(e&&e.button!==0))for(;F.length;){var i=F[0];Y(i,this.options.selectedClass,!1),F.shift(),qe({sortable:this.sortable,rootEl:this.sortable.el,name:"deselect",targetEl:i,originalEvent:e})}},_checkKeyDown:function(e){e.key===this.options.multiDragKey&&(this.multiDragKeyDown=!0)},_checkKeyUp:function(e){e.key===this.options.multiDragKey&&(this.multiDragKeyDown=!1)}},kt(n,{pluginName:"multiDrag",utils:{select:function(e){var i=e.parentNode[it];!i||!i.options.multiDrag||~F.indexOf(e)||(yt&&yt!==i&&(yt.multiDrag._deselectMultiDrag(),yt=i),Y(e,i.options.selectedClass,!0),F.push(e))},deselect:function(e){var i=e.parentNode[it],r=F.indexOf(e);!i||!i.options.multiDrag||!~r||(Y(e,i.options.selectedClass,!1),F.splice(r,1))}},eventProperties:function(){var e=this,i=[],r=[];return F.forEach(function(o){i.push({multiDragElement:o,index:o.sortableIndex});var s;ct&&o!==z?s=-1:ct?s=J(o,":not(."+e.options.selectedClass+")"):s=J(o),r.push({multiDragElement:o,index:s})}),{items:ph(F),clones:[].concat(ft),oldIndicies:i,newIndicies:r}},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 Nh(n,t){F.forEach(function(e,i){var r=t.children[e.sortableIndex+(n?Number(i):0)];r?t.insertBefore(e,r):t.appendChild(e)})}function fs(n,t){ft.forEach(function(e,i){var r=t.children[e.sortableIndex+(n?Number(i):0)];r?t.insertBefore(e,r):t.appendChild(e)})}function kn(){F.forEach(function(n){n!==z&&n.parentNode&&n.parentNode.removeChild(n)})}I.mount(new Rh);I.mount(Vr,jr);var Yt=I;var Ls={name(n,t){let e=n.getAttribute("data-name").trim().toLowerCase(),i=t.getAttribute("data-name").trim().toLowerCase();return e.localeCompare(i)},created(n,t){let e=Number(n.getAttribute("data-created"));return Number(t.getAttribute("data-created"))-e},updated(n,t){let e=Number(n.getAttribute("data-updated"));return Number(t.getAttribute("data-updated"))-e},chaptersFirst(n,t){let e=n.getAttribute("data-type"),i=t.getAttribute("data-type");return e===i?0:e==="chapter"?-1:1},chaptersLast(n,t){let e=n.getAttribute("data-type"),i=t.getAttribute("data-type");return e===i?0:e==="chapter"?1:-1}},Ts={up:{active(n,t){return!(n.previousElementSibling===null&&!t)},run(n,t){(n.previousElementSibling||t).insertAdjacentElement("beforebegin",n)}},down:{active(n,t){return!(n.nextElementSibling===null&&!t)},run(n,t){(n.nextElementSibling||t).insertAdjacentElement("afterend",n)}},next_book:{active(n,t,e){return e.nextElementSibling!==null},run(n,t,e){e.nextElementSibling.querySelector("ul").prepend(n)}},prev_book:{active(n,t,e){return e.previousElementSibling!==null},run(n,t,e){e.previousElementSibling.querySelector("ul").appendChild(n)}},next_chapter:{active(n,t){return n.dataset.type==="page"&&this.getNextChapter(n,t)},run(n,t){this.getNextChapter(n,t).querySelector("ul").prepend(n)},getNextChapter(n,t){let e=t||n,i=Array.from(e.parentElement.children),r=i.indexOf(e);return i.slice(r+1).find(o=>o.dataset.type==="chapter")}},prev_chapter:{active(n,t){return n.dataset.type==="page"&&this.getPrevChapter(n,t)},run(n,t){this.getPrevChapter(n,t).querySelector("ul").append(n)},getPrevChapter(n,t){let e=t||n,i=Array.from(e.parentElement.children),r=i.indexOf(e);return i.slice(0,r).reverse().find(o=>o.dataset.type==="chapter")}},book_end:{active(n,t){return t||t===null&&n.nextElementSibling},run(n,t,e){e.querySelector("ul").append(n)}},book_start:{active(n,t){return t||t===null&&n.previousElementSibling},run(n,t,e){e.querySelector("ul").prepend(n)}},before_chapter:{active(n,t){return t},run(n,t){t.insertAdjacentElement("beforebegin",n)}},after_chapter:{active(n,t){return t},run(n,t){t.insertAdjacentElement("afterend",n)}}},Fn=class extends g{setup(){this.container=this.$el,this.sortContainer=this.$refs.sortContainer,this.input=this.$refs.input,Yt.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"),i=t.target.closest("[data-id]");this.runSortAction(i,e)}}),this.updateMoveActionStateForAll()}setupSortPresets(){let t="",e=!1,i=["name","created","updated"];this.sortContainer.addEventListener("click",r=>{let o=r.target.closest(".sort-box-options [data-sort]");if(!o)return;r.preventDefault();let s=o.closest(".sort-box").querySelectorAll("ul"),a=o.getAttribute("data-sort");e=t===a?!e:!1;let l=Ls[a];e&&i.includes(a)&&(l=function(u,h){return 0-Ls[a](u,h)});for(let c of s)Array.from(c.children).filter(h=>h.matches("li")).sort(l).forEach(h=>{c.appendChild(h)});t=a,this.updateMapInput()})}bookSelect(t){if(this.container.querySelector(`[data-type="book"][data-id="${t.id}"]`)!==null)return;let i=`${t.link}/sort-item`;window.$http.get(i).then(r=>{let o=_t(r.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")),i={name:"book",pull:["book","chapter"],put:["book","chapter"]},r={name:"chapter",pull:["book","chapter"],put(o,s,a){return a.getAttribute("data-type")==="page"}};for(let o of e)Yt.create(o,{group:o.classList.contains("sort-list")?i:r,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 i of e){let r=i.closest('[data-type="book"]').getAttribute("data-id"),o=Array.from(i.children).filter(s=>s.matches('[data-type="page"], [data-type="chapter"]'));for(let s=0;s{for(let s of r)n.style[s]=null;n.style.transition=null,n.removeEventListener("transitionend",o),qn.delete(n),i&&i()};setTimeout(()=>{n.style.transition=`all ease-in-out ${e}ms`;for(let s of r)n.style[s]=t[s][1];n.addEventListener("transitionend",o),qn.set(n,o)},15)}function Ge(n){qn.has(n)&&qn.get(n)()}function $s(n,t=400,e=null){Ge(n),n.style.display="block",We(n,{opacity:["0","1"]},t,()=>{e&&e()})}function Is(n,t=400,e=null){Ge(n),We(n,{opacity:["1","0"]},t,()=>{n.style.display="none",e&&e()})}function fe(n,t=400){Ge(n);let e=n.getBoundingClientRect().height,i=getComputedStyle(n),r=i.getPropertyValue("padding-top"),o=i.getPropertyValue("padding-bottom"),s={maxHeight:[`${e}px`,"0px"],overflow:["hidden","hidden"],paddingTop:[r,"0px"],paddingBottom:[o,"0px"]};We(n,s,t,()=>{n.style.display="none"})}function me(n,t=400){Ge(n),n.style.display="block";let e=n.getBoundingClientRect().height,i=getComputedStyle(n),r=i.getPropertyValue("padding-top"),o=i.getPropertyValue("padding-bottom"),s={maxHeight:["0px",`${e}px`],overflow:["hidden","hidden"],paddingTop:["0px",r],paddingBottom:["0px",o]};We(n,s,t)}function Ms(n,t=400){let e=n.getBoundingClientRect().height,i=getComputedStyle(n),r=i.getPropertyValue("padding-top"),o=i.getPropertyValue("padding-bottom");return()=>{Ge(n);let s=n.getBoundingClientRect().height,a=getComputedStyle(n),l=a.getPropertyValue("padding-top"),c=a.getPropertyValue("padding-bottom"),u={height:[`${e}px`,`${s}px`],overflow:["hidden","hidden"],paddingTop:[r,l],paddingBottom:[o,c]};We(n,u,t)}}var Bn=class extends g{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"),me(this.list,180),this.isOpen=!0}close(){this.toggle.classList.remove("open"),this.toggle.setAttribute("aria-expanded","false"),fe(this.list,180),this.isOpen=!1}click(t){t.preventDefault(),this.isOpen?this.close():this.open()}};var Pn=class extends g{constructor(){super(...arguments);at(this,"editor",null);at(this,"saveCallback",null);at(this,"cancelCallback",null);at(this,"history",{});at(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()}),R(this.languageButtons,e=>{let i=e.target.dataset.lang;this.languageInput.value=i,this.languageInputChange(i)}),se(this.languageInput,()=>this.save()),this.languageInput.addEventListener("input",()=>this.languageInputChange(this.languageInput.value)),R(this.saveButton,()=>this.save()),K(this.historyList,"button","click",(e,i)=>{e.preventDefault();let r=i.dataset.time;this.editor&&this.editor.setContent(this.history[r])})}setupFavourites(){for(let e of this.languageButtons)this.setupFavouritesForButton(e);this.sortLanguageList()}setupFavouritesForButton(e){let i=e.dataset.lang,r=this.favourites.has(i);e.setAttribute("data-favourite",r?"true":"false"),K(e.parentElement,".lang-option-favorite-toggle","click",()=>{r=!r,r?this.favourites.add(i):this.favourites.delete(i),e.setAttribute("data-favourite",r?"true":"false"),window.$http.patch("/preferences/update-code-language-favourite",{language:i,active:r}),this.sortLanguageList(),r&&e.scrollIntoView({block:"center",behavior:"smooth"})})}sortLanguageList(){let e=this.languageButtons.sort((i,r)=>{let o=i.dataset.favourite==="true",s=r.dataset.favourite==="true";return o&&!s?-1:s&&!o||i.dataset.lang>r.dataset.lang?1:-1}).map(i=>i.parentElement);for(let i of e)this.languageOptionsContainer.append(i)}save(){this.saveCallback&&this.saveCallback(this.editor.getContent(),this.languageInput.value),this.hide()}async open(e,i,r,o){this.languageInput.value=i,this.saveCallback=r,this.cancelCallback=o,await this.show(),this.languageInputChange(i),this.editor.setContent(e)}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()})}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 i=e.toLowerCase();for(let r of this.languageButtons){let o=r.dataset.lang.toLowerCase().trim(),s=i===o;r.classList.toggle("active",s),s&&r.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(i=>{let r=new Date(parseInt(i,10)).toLocaleTimeString();return`
  • `}).join("")}addHistory(){if(!this.editor)return;let e=this.editor.getContent();if(!e)return;let i=Object.keys(this.history).pop();if(this.history[i]===e)return;this.history[String(Date.now())]=e;let r=JSON.stringify(this.history);window.sessionStorage.setItem(this.historyKey,r)}};var On=class extends g{setup(){let t=this.$el;t.querySelectorAll("pre").length>0&&window.importVersioned("code").then(i=>{i.highlightWithin(t)})}};var Rn=class extends g{async setup(){let{mode:t}=this.$opts;(await window.importVersioned("code")).inlineEditor(this.$el,t)}};var Nn=class extends g{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"),me(this.content,300)}close(){this.container.classList.remove("open"),this.trigger.setAttribute("aria-expanded","false"),fe(this.content,300)}toggle(){this.container.classList.contains("open")?this.close():this.open()}openIfContainsError(){this.content.querySelector(".text-neg.text-small")&&this.open()}};var zn=class extends g{setup(){this.container=this.$el,this.confirmButton=this.$refs.confirm,this.res=null,R(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 Hn=class extends g{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 Un=class extends g{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 jn=class extends g{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(),i=0,r=this.toggle.getBoundingClientRect().height,o=e.bottom>window.innerHeight,s=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?i=window.innerHeight-e.top-r/2:i=e.top),o){this.menu.style.top="initial",this.menu.style.bottom=`${i}px`;let c=window.innerHeight-40-(window.innerHeight-s.bottom);this.menu.style.maxHeight=`${Math.floor(c)}px`}else{this.menu.style.top=`${i}px`,this.menu.style.bottom="initial";let c=window.innerHeight-40-s.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 zt(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()}),R(this.toggle,e=>{e.stopPropagation(),e.preventDefault(),this.show(e),e instanceof KeyboardEvent&&t.focusNext()})}};var Vn=class extends g{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=Nt(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 i of e){let r=!t||i.textContent.toLowerCase().includes(t);i.style.display=r?"flex":"none",i.classList.toggle("hidden",!r)}}async loadList(t=""){this.listContainerElem.innerHTML="",this.toggleLoading(!0);try{let e=await window.$http.get(this.getAjaxUrl(t)),i=Ms(this.listContainerElem,80);this.listContainerElem.innerHTML=e.data,i()}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 Ft=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 r of t)if(r.includes("image")){let o=this.data.getData(r);e.push(o.getAsFile())}let i=this.getFiles().filter(r=>r.type.includes("image"));return e.push(...i),e}getFiles(){let{files:t}=this.data;return[...t]}};async function Wr(n){if(window.isSecureContext&&navigator.clipboard){await navigator.clipboard.writeText(n);return}let t=document.createElement("textarea");t.style="position: absolute; left: -1000px; top: -1000px;",t.value=n,document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t)}var Wn=class extends g{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(){R(this.selectButtons,this.manualSelectHandler.bind(this)),this.setupDropTargetHandlers()}setupDropTargetHandlers(){let t=0,e=()=>{this.hideOverlay(),t=0};this.dropTarget.addEventListener("dragenter",i=>{i.preventDefault(),t+=1,t===1&&this.isActive&&this.showOverlay()}),this.dropTarget.addEventListener("dragover",i=>{i.preventDefault()}),this.dropTarget.addEventListener("dragend",e),this.dropTarget.addEventListener("dragleave",()=>{t-=1,t===0&&e()}),this.dropTarget.addEventListener("drop",i=>{if(i.preventDefault(),e(),!this.isActive)return;let o=new Ft(i.dataTransfer).getFiles();for(let s of o)this.createUploadFromFile(s)})}manualSelectHandler(){let t=Et("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=Et("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:i,progress:r,dismiss:o}=this.createDomForFile(t);this.statusArea.append(e);let s=this,a={file:t,dom:e,updateProgress(l){r.textContent=`${l}%`,r.style.width=`${l}%`},markError(l){i.setAttribute("data-status","error"),i.textContent=l,Le(e),this.updateProgress(100)},markSuccess(l){i.setAttribute("data-status","success"),i.textContent=l,Le(e),setTimeout(o,2400),s.$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 i=this,r=window.$http.createXMLHttpRequest("POST",this.url,{error(){t.markError(i.errorMessage)},readystatechange(){if(this.readyState===XMLHttpRequest.DONE&&this.status===200)t.markSuccess(i.successMessage);else if(this.readyState===XMLHttpRequest.DONE&&this.status>=400){let o=this.responseText,s=o.startsWith("{")?JSON.parse(o):{message:o},a=s?.message||s?.error||o;t.markError(a)}}});r.upload.addEventListener("progress",o=>{let s=Math.min(Math.ceil(o.loaded/o.total*100),100);t.updateProgress(s)}),r.setRequestHeader("Accept","application/json"),r.send(e)}createDomForFile(t){let e=Et("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"}),i=Et("div",{class:"dropzone-file-item-status"},[]),r=Et("div",{class:"dropzone-file-item-progress"}),o=Et("div",{class:"dropzone-file-item-image-wrap"},[e]),s=Et("div",{class:"dropzone-file-item"},[o,Et("div",{class:"dropzone-file-item-text-wrap"},[Et("div",{class:"dropzone-file-item-label"},[t.name]),ae(),i]),r]);t.type.startsWith("image/")&&(e.src=URL.createObjectURL(t));let a=()=>{s.classList.add("dismiss"),s.addEventListener("animationend",()=>{s.remove()})};return s.addEventListener("click",a),{dom:s,progress:r,status:i,dismiss:a}}};var Gn=class extends g{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 i=e.dataset.tab;this.setActiveTab(i,!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 i of this.buttons)i.classList.remove("active"),i.dataset.tab===t&&i.classList.add("active");for(let i of this.contentElements)i.style.display="none",i.dataset.tabContent===t&&(i.style.display="block");e&&!this.container.classList.contains("open")&&this.toggle()}};var Kn=class extends g{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,i=document.querySelectorAll('input[name^="permissions[0]["]');for(let r of i)r.disabled=e,r.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 i=await window.$http.get(`/permissions/form-row/${this.entityType}/${t}`),r=_t(i.data);this.roleContainer.append(r),this.roleSelect.disabled=!1}removeRowOnButtonClick(t){let e=t.closest(".item-list-row"),{roleId:i}=t.dataset,{roleName:r}=t.dataset,o=document.createElement("option");o.value=i,o.textContent=r,this.roleSelect.append(o),e.remove()}};var Zn=class extends g{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()}),R(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(i=>{this.searchResults.innerHTML=i.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 Xn=class extends g{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()}),K(this.$el,"[data-entity-type]","keydown",e=>{if(e.ctrlKey&&e.code==="Enter"){let i=this.$el.closest("form");if(i){i.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]")),i=e.indexOf(document.activeElement),r=e[i+(t?1:-1)]||e[0];r&&r.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(i=>{this.resultsContainer.innerHTML=i.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(),i=t.getAttribute("data-entity-type"),r=t.getAttribute("data-entity-id"),o=!t.classList.contains("selected")||e;this.unselectAll(),this.input.value=o?`${i}:${r}`:"";let s=t.getAttribute("href"),a=t.querySelector(".entity-list-item-name").textContent,l={id:Number(r),name:a,link:s};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 Yn=class extends g{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 Jn=class extends g{setup(){this.container=this.$el,this.name=this.$opts.name,R(this.$el,()=>{this.$emit(this.name,this.$opts)})}};var Qn=class extends g{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){me(t,200)}close(t){fe(t,200)}click(t){t.preventDefault();let e=document.querySelectorAll(this.targetSelector);for(let i of e)(this.isOpen?this.close:this.open)(i);this.isOpen=!this.isOpen,this.updateSystemAjax(this.isOpen)}updateSystemAjax(t){window.$http.patch(this.updateEndpoint,{expand:t?"true":"false"})}};var ti=class extends g{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=Nt(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 zt(this.container,()=>{this.hideSuggestions()})}async updateSuggestions(t){let{data:e}=await window.$http.get("/search/suggest",{term:t});if(!this.input.value)return;let i=_t(e);this.suggestionResultsWrap.innerHTML="",this.suggestionResultsWrap.style.opacity="1",this.loadingWrap.style.display="none",this.suggestionResultsWrap.append(i),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 ei=class extends g{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 ni=class extends g{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(){R(this.filterTabs,i=>{this.resetAll(),this.filter=i.target.dataset.filter,this.setActiveFilterTab(this.filter),this.loadGallery()}),this.searchForm.addEventListener("submit",i=>{this.resetListView(),this.loadGallery(),this.cancelSearch.toggleAttribute("hidden",!this.searchInput.value),i.preventDefault()}),R(this.cancelSearch,()=>{this.resetListView(),this.resetSearchView(),this.loadGallery()}),K(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",i=>{i.target.src=window.baseUrl("loading_error.png")},!0),R(this.selectButton,()=>{this.callback&&this.callback(this.lastSelected),this.hide()}),K(this.formContainer,"#image-manager-delete","click",()=>{this.lastSelected&&this.loadImageEditForm(this.lastSelected.id,!0)}),K(this.formContainer,"#image-manager-rebuild-thumbs","click",async(i,r)=>{r.disabled=!0,this.lastSelected&&await this.rebuildThumbnails(this.lastSelected.id),r.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",i=>{if(!(Math.ceil(t.scrollHeight-t.scrollTop)===t.clientHeight)||i.deltaY<1)return;let s=Date.now()-1e3;e.push(Date.now()),e=e.filter(a=>a>=s),e.length>5&&this.canLoadMore()&&this.runLoadMore()})}show(t,e="gallery"){this.resetAll(),this.callback=t,this.type=e,this.getPopup().show();let i=e!=="gallery";this.dropzoneContainer.classList.toggle("hidden",i),this.uploadButton.classList.toggle("hidden",i),this.uploadHint.classList.toggle("hidden",i),window.$components.firstOnElement(this.container,"dropzone").toggleActive(!i),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),Le(this.listContainer)}addReturnedHtmlElementsToList(t){let e=document.createElement("div");e.innerHTML=t;let i=e.querySelector(".load-more");i&&(i.remove(),this.loadMore.innerHTML=i.innerHTML),this.loadMore.toggleAttribute("hidden",!i),window.$components.init(e);for(let r of[...e.children])this.listContainer.appendChild(r)}setActiveFilterTab(t){for(let e of this.filterTabs){let i=e.dataset.filter===t;e.setAttribute("aria-selected",i?"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(){De(this.listContainer),this.page=1}refreshGallery(){this.resetListView(),this.loadGallery()}async onImageSelectEvent(t){let e=JSON.parse(t.detail.data),i=e&&e.id===this.lastSelected.id&&Date.now()-this.lastSelectedTime<400,r=t.target.classList.contains("selected");[...this.listContainer.querySelectorAll(".selected")].forEach(o=>{o.classList.remove("selected")}),!r&&!i?(t.target.classList.add("selected"),e=await this.loadImageEditForm(e.id)):i?i&&(e=this.lastSelected):this.resetEditForm(),this.selectButton.classList.toggle("hidden",r),i&&this.callback&&(this.callback(e),this.hide()),this.lastSelected=e,this.lastSelectedTime=Date.now()}async loadImageEditForm(t,e=!1){e||(this.formContainer.innerHTML="");let i=e?{delete:!0}:{},{data:r}=await window.$http.get(`/images/edit/${t}`,i);this.formContainer.innerHTML=r,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(){De(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 ii=class extends g{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 ri=class extends g{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 jc=Go(Oc()),Vc=Go(Uc()),wi=class{constructor(){this.renderer=new jc.default({html:!0}),this.renderer.use(Vc.default,{label:!0})}getRenderer(){return this.renderer}render(t){return this.renderer.render(t)}};function hf(n,t){return document.createElement(n,t)}function df(n,t,e){return document.createElementNS(n,t,e)}function pf(){return te(document.createDocumentFragment())}function ff(n){return document.createTextNode(n)}function mf(n){return document.createComment(n)}function gf(n,t,e){if(qt(n)){let i=n;for(;i&&qt(i);)i=te(i).parent;n=i??n}qt(t)&&(t=te(t,n)),e&&qt(e)&&(e=te(e).firstChildNode),n.insertBefore(t,e)}function bf(n,t){n.removeChild(t)}function vf(n,t){qt(t)&&(t=te(t,n)),n.appendChild(t)}function Wc(n){if(qt(n)){for(;n&&qt(n);)n=te(n).parent;return n??null}return n.parentNode}function wf(n){var t;if(qt(n)){let e=te(n),i=Wc(e);if(i&&e.lastChildNode){let r=Array.from(i.childNodes),o=r.indexOf(e.lastChildNode);return(t=r[o+1])!==null&&t!==void 0?t:null}return null}return n.nextSibling}function yf(n){return n.tagName}function xf(n,t){n.textContent=t}function kf(n){return n.textContent}function Cf(n){return n.nodeType===1}function Ef(n){return n.nodeType===3}function _f(n){return n.nodeType===8}function qt(n){return n.nodeType===11}function te(n,t){var e,i,r;let o=n;return(e=o.parent)!==null&&e!==void 0||(o.parent=t??null),(i=o.firstChildNode)!==null&&i!==void 0||(o.firstChildNode=n.firstChild),(r=o.lastChildNode)!==null&&r!==void 0||(o.lastChildNode=n.lastChild),o}var yi={createElement:hf,createElementNS:df,createTextNode:ff,createDocumentFragment:pf,createComment:mf,insertBefore:gf,removeChild:bf,appendChild:vf,parentNode:Wc,nextSibling:wf,tagName:yf,setTextContent:xf,getTextContent:kf,isElement:Cf,isText:Ef,isComment:_f,isDocumentFragment:qt};function Bt(n,t,e,i,r){let o=t===void 0?void 0:t.key;return{sel:n,data:t,children:e,text:i,elm:r,key:o}}var Gc=Array.isArray;function Kc(n){return typeof n=="string"||typeof n=="number"||n instanceof String||n instanceof Number}function Eo(n){return n===void 0}function ut(n){return n!==void 0}var _o=Bt("",{},[],void 0,void 0);function Je(n,t){var e,i;let r=n.key===t.key,o=((e=n.data)===null||e===void 0?void 0:e.is)===((i=t.data)===null||i===void 0?void 0:i.is),s=n.sel===t.sel,a=!n.sel&&n.sel===t.sel?typeof n.text==typeof t.text:!0;return s&&r&&o&&a}function Af(){throw new Error("The document fragment is not supported on this platform.")}function Df(n,t){return n.isElement(t)}function Lf(n,t){return n.isDocumentFragment(t)}function Tf(n,t,e){var i;let r={};for(let o=t;o<=e;++o){let s=(i=n[o])===null||i===void 0?void 0:i.key;s!==void 0&&(r[s]=o)}return r}var $f=["create","update","remove","destroy","pre","post"];function So(n,t,e){let i={create:[],update:[],remove:[],destroy:[],pre:[],post:[]},r=t!==void 0?t:yi;for(let p of $f)for(let m of n){let w=m[p];w!==void 0&&i[p].push(w)}function o(p){let m=p.id?"#"+p.id:"",w=p.getAttribute("class"),v=w?"."+w.split(" ").join("."):"";return Bt(r.tagName(p).toLowerCase()+m+v,{},[],void 0,p)}function s(p){return Bt(void 0,{},[],void 0,p)}function a(p,m){return function(){if(--m===0){let v=r.parentNode(p);r.removeChild(v,p)}}}function l(p,m){var w,v,b,k;let x,E=p.data;if(E!==void 0){let D=(w=E.hook)===null||w===void 0?void 0:w.init;ut(D)&&(D(p),E=p.data)}let y=p.children,A=p.sel;if(A==="!")Eo(p.text)&&(p.text=""),p.elm=r.createComment(p.text);else if(A!==void 0){let D=A.indexOf("#"),M=A.indexOf(".",D),T=D>0?D:A.length,P=M>0?M:A.length,H=D!==-1||M!==-1?A.slice(0,Math.min(T,P)):A,U=p.elm=ut(E)&&ut(x=E.ns)?r.createElementNS(x,H,E):r.createElement(H,E);for(T0&&U.setAttribute("class",A.slice(P+1).replace(/\./g," ")),x=0;x0&&(u.attrs=l),Object.keys(c).length>0&&(u.dataset=c),a[0]==="s"&&a[1]==="v"&&a[2]==="g"&&(a.length===3||a[3]==="."||a[3]==="#")&&Ao(u,h,a),Bt(a,u,h,void 0,n)}else return e.isText(n)?(i=e.getTextContent(n),Bt(void 0,void 0,void 0,i,n)):e.isComment(n)?(i=e.getTextContent(n),Bt("!",{},[],i,n)):Bt("",{},[],void 0,n)}var If="http://www.w3.org/1999/xlink",Mf="http://www.w3.org/XML/1998/namespace";function Zc(n,t){let e,i=t.elm,r=n.data.attrs,o=t.data.attrs;if(!(!r&&!o)&&r!==o){r=r||{},o=o||{};for(e in o){let s=o[e];r[e]!==s&&(s===!0?i.setAttribute(e,""):s===!1?i.removeAttribute(e):e.charCodeAt(0)!==120?i.setAttribute(e,s):e.charCodeAt(3)===58?i.setAttributeNS(Mf,e,s):e.charCodeAt(5)===58?i.setAttributeNS(If,e,s):i.setAttribute(e,s))}for(e in r)e in o||i.removeAttribute(e)}}var Do={create:Zc,update:Zc};var xi;function Ff(){return xi||(xi=So([Do]),xi)}function Xc(n,t){let e=document.createElement("div");e.innerHTML=t,Ff()(Qe(n),Qe(e))}var ki=class{constructor(t){this.editor=t,this.container=t.config.displayEl,this.doc=null,this.lastDisplayClick=0,this.container.contentDocument.readyState==="complete"?this.onLoad():this.container.addEventListener("load",this.onLoad.bind(this)),this.updateVisibility(t.settings.get("showPreview")),t.settings.onChange("showPreview",e=>this.updateVisibility(e))}updateVisibility(t){let e=this.container.closest(".markdown-editor-wrap");e.style.display=t?null:"none"}onLoad(){this.doc=this.container.contentDocument,this.loadStylesIntoDisplay(),this.doc.body.className="page-content",this.doc.addEventListener("click",this.onDisplayClick.bind(this))}onDisplayClick(t){let e=Date.now()-this.lastDisplayClick<300,i=t.target.closest("a");if(i!==null){t.preventDefault(),window.open(i.getAttribute("href"));return}let r=t.target.closest("[drawio-diagram]");if(r!==null&&e){this.editor.actions.editDrawing(r);return}this.lastDisplayClick=Date.now()}loadStylesIntoDisplay(){this.doc.documentElement.classList.add("markdown-editor-display"),document.documentElement.classList.contains("dark-mode")&&(this.doc.documentElement.style.backgroundColor="#222",this.doc.documentElement.classList.add("dark-mode")),this.doc.head.innerHTML="";let t=document.head.querySelectorAll("style,link[rel=stylesheet]");for(let e of t){let i=e.cloneNode(!0);this.doc.head.appendChild(i)}}patchWithHtml(t){let{body:e}=this.doc;if(e.children.length===0){let r=document.createElement("div");this.doc.body.append(r)}let i=e.children[0];Xc(i,t)}scrollToIndex(t){let e=this.doc.body?.children[0]?.children;if(e&&e.length<=t)return;(t===-1?e[e.length-1]:e[t]).scrollIntoView({block:"start",inline:"nearest",behavior:"smooth"})}};function Ci(n){return new Promise((t,e)=>{n.oncomplete=n.onsuccess=()=>t(n.result),n.onabort=n.onerror=()=>e(n.error)})}function qf(n,t){let e=indexedDB.open(n);e.onupgradeneeded=()=>e.result.createObjectStore(t);let i=Ci(e);return(r,o)=>i.then(s=>o(s.transaction(t,r).objectStore(t)))}var Lo;function To(){return Lo||(Lo=qf("keyval-store","keyval")),Lo}function $o(n,t=To()){return t("readonly",e=>Ci(e.get(n)))}function Io(n,t,e=To()){return e("readwrite",i=>(i.put(t,n),Ci(i.transaction)))}function Mo(n,t=To()){return t("readwrite",e=>(e.delete(n),Ci(e.transaction)))}var $t=null,Bo,Ei,Fo,qo="last-drawing-save";function Po(n){$t.contentWindow.postMessage(JSON.stringify(n),Bo)}function Pf(n){Io(qo,n.data),Fo&&Fo(n.data).then(()=>{Mo(qo)})}function Of(n){Po({action:"export",format:"xmlpng",xml:n.xml,spin:"Updating drawing"})}function Rf(){Ei&&Ei().then(n=>{Po({action:"load",autosave:1,xml:n})})}function Nf(){let n={};window.$events.emitPublic($t,"editor-drawio::configure",{config:n}),Po({action:"configure",config:n})}function Yc(){window.removeEventListener("message",Jc),$t&&document.body.removeChild($t)}function Jc(n){if(!n.data||n.data.length<1||n.origin!==Bo)return;let t=JSON.parse(n.data);t.event==="init"?Rf():t.event==="exit"?Yc():t.event==="save"?Of(t):t.event==="export"?Pf(t):t.event==="configure"&&Nf()}async function zf(){let n=await $o(qo),t=document.getElementById("unsaved-drawing-dialog");t||console.error("Missing expected unsaved-drawing dialog"),n&&await window.$components.firstOnElement(t,"confirm-dialog").show()&&(Ei=async()=>n)}async function tn(n,t,e){Ei=t,Fo=e,await zf(),$t=document.createElement("iframe"),$t.setAttribute("frameborder","0"),window.addEventListener("message",Jc),$t.setAttribute("src",n),$t.setAttribute("class","fullscreen"),$t.style.backgroundColor="#FFFFFF",document.body.appendChild($t),Bo=new URL(n).origin}async function Oo(n,t){let e={image:n,uploaded_to:t};return(await window.$http.post(window.baseUrl("/images/drawio"),e)).data}function ee(){Yc()}async function _i(n){try{return`data:image/png;base64,${(await window.$http.get(window.baseUrl(`/images/drawio/base64/${n}`))).data.content}`}catch(t){throw t instanceof window.$http.HttpError&&window.$events.showResponseError(t),ee(),t}}var en,Ro,xe,Si,ke,Ai,Pt,ne,Wt,ye,rt,ht,nn,No,rn,zo,Ce,Di,dt,vt,Ti,tu,Li=class{constructor(t){ot(this,en);ot(this,xe);ot(this,ke);ot(this,Pt);ot(this,Wt);ot(this,rt);ot(this,nn);ot(this,rn);ot(this,Ce);ot(this,dt);ot(this,Ti);this.editor=t,this.lastContent={html:"",markdown:""}}updateAndRender(){let t=L(this,xe,Si).call(this);this.editor.config.inputEl.value=t;let e=this.editor.markdown.render(t);window.$events.emit("editor-html-change",""),window.$events.emit("editor-markdown-change",""),this.lastContent.html=e,this.lastContent.markdown=t,this.editor.display.patchWithHtml(e)}getContent(){return this.lastContent}showImageInsert(){window.$components.first("image-manager").show(e=>{let i=e.thumbs?.display||e.url,o=`[![${L(this,Wt,ye).call(this)||e.name}](${i})](${e.url})`;L(this,Pt,ne).call(this,o,o.length)},"gallery")}insertImage(){let t=`![${L(this,Wt,ye).call(this)}](http://)`;L(this,Pt,ne).call(this,t,t.length-1)}insertLink(){let t=L(this,Wt,ye).call(this),e=`[${t}]()`,i=t===""?-3:-1;L(this,Pt,ne).call(this,e,e.length+i)}showImageManager(){let t=L(this,rt,ht).call(this);window.$components.first("image-manager").show(i=>{L(this,en,Ro).call(this,i,t)},"drawio")}showLinkSelector(){let t=L(this,rt,ht).call(this),e=window.$components.first("entity-selector-popup"),i=L(this,Wt,ye).call(this,t);e.show(r=>{let s=`[${i||r.name}](${r.link})`;L(this,Pt,ne).call(this,s,s.length,t)},{initialValue:i,searchEndpoint:"/search/entity-selector",entityTypes:"page,book,chapter,bookshelf",entityPermission:"view"})}startDrawing(){let t=this.editor.config.drawioUrl;if(!t)return;let e=L(this,rt,ht).call(this);tn(t,()=>Promise.resolve(""),async i=>{let r={image:i,uploaded_to:Number(this.editor.config.pageId)};try{let o=await window.$http.post("/images/drawio",r);L(this,en,Ro).call(this,o.data,e),ee()}catch(o){throw this.handleDrawingUploadError(o),new Error(`Failed to save image with error: ${o}`)}})}editDrawing(t){let{drawioUrl:e}=this.editor.config;if(!e)return;let i=L(this,rt,ht).call(this),r=t.getAttribute("drawio-diagram");tn(e,()=>_i(r),async o=>{let s={image:o,uploaded_to:Number(this.editor.config.pageId)};try{let a=await window.$http.post("/images/drawio",s),l=`
    `,c=L(this,xe,Si).call(this).split(` `).map(u=>u.indexOf(`drawio-diagram="${r}"`)!==-1?l:u).join(` `);L(this,ke,Ai).call(this,c,i),ee()}catch(a){throw this.handleDrawingUploadError(a),new Error(`Failed to save image with error: ${a}`)}})}handleDrawingUploadError(t){t.status===413?window.$events.emit("error",this.editor.config.text.serverUploadLimit):window.$events.emit("error",this.editor.config.text.imageUploadError),console.error(t)}fullScreen(){let{container:t}=this.editor.config,e=t.classList.contains("fullscreen");t.classList.toggle("fullscreen",!e),document.body.classList.toggle("markdown-fullscreen",!e)}scrollToText(t){if(!t)return;let e=this.editor.cm.state.doc,i=1,r=-1;for(let s of e.iterLines()){if(s.includes(t)){r=i;break}i+=1}if(r===-1)return;let o=e.line(r);L(this,Ti,tu).call(this,o.from,o.to,!0),this.focus()}focus(){this.editor.cm.hasFocus||this.editor.cm.focus()}insertContent(t){L(this,Pt,ne).call(this,t,t.length)}prependContent(t){t=L(this,nn,No).call(this,t);let i=L(this,rt,ht).call(this).from+t.length+1;L(this,dt,vt).call(this,0,0,`${t} `,i),this.focus()}appendContent(t){t=L(this,nn,No).call(this,t),L(this,dt,vt).call(this,this.editor.cm.state.doc.length,` ${t}`),this.focus()}replaceContent(t){L(this,ke,Ai).call(this,t)}replaceLineStart(t){let e=L(this,rt,ht).call(this),i=this.editor.cm.state.doc.lineAt(e.from),r=i.text,o=r.split(" ")[0];if(o===t){let c=r.replace(`${t} `,""),u=e.from+(c.length-r.length);L(this,dt,vt).call(this,i.from,i.to,c,u);return}let s=r;/^[#>`]/.test(o)?s=r.replace(o,t).trim():t!==""&&(s=`${t} ${r}`);let l=e.from+(s.length-r.length);L(this,dt,vt).call(this,i.from,i.to,s,l)}wrapSelection(t,e){let i=L(this,rt,ht).call(this),r=L(this,Wt,ye).call(this,i);if(!r){L(this,Ce,Di).call(this,t,e);return}let o=r,s;r.startsWith(t)&&r.endsWith(e)?(o=r.slice(t.length,r.length-e.length),s=i.extend(i.from,i.to-(t.length+e.length))):(o=`${t}${r}${e}`,s=i.extend(i.from,i.to+(t.length+e.length))),L(this,dt,vt).call(this,i.from,i.to,o,s.anchor,s.head)}replaceLineStartForOrderedList(){let t=L(this,rt,ht).call(this),e=this.editor.cm.state.doc.lineAt(t.from),r=this.editor.cm.state.doc.line(e.number-1).text.match(/^(\s*)(\d)([).])\s/)||[],o=(Number(r[2])||0)+1,s=r[1]||"",a=r[3]||".",l=`${s}${o}${a}`;return this.replaceLineStart(l)}cycleCalloutTypeAtSelection(){let t=L(this,rt,ht).call(this),e=this.editor.cm.state.doc.lineAt(t.from),i=["info","success","warning","danger"],r=i.join("|"),s=new RegExp(`class="((${r})\\s+callout|callout\\s+(${r}))"`,"i").exec(e.text),a=(s?s[2]||s[3]:"").toLowerCase();if(a===i[i.length-1])L(this,Ce,Di).call(this,`

    `,"

    ");else if(a==="")L(this,Ce,Di).call(this,'

    ',"

    ");else{let l=i.indexOf(a)+1,c=i[l],u=e.text.replace(s[0],s[0].replace(a,c)),h=u.length-e.text.length;L(this,dt,vt).call(this,e.from,e.to,u,t.anchor+h,t.head+h)}}syncDisplayPosition(t){let e=t.target;if(Math.abs(e.scrollHeight-e.clientHeight-e.scrollTop)<1){this.editor.display.scrollToIndex(-1);return}let r=this.editor.cm.lineBlockAtHeight(e.scrollTop),o=this.editor.cm.state.sliceDoc(0,r.from),l=new DOMParser().parseFromString(this.editor.markdown.render(o),"text/html").documentElement.querySelectorAll("body > *");this.editor.display.scrollToIndex(l.length)}async insertTemplate(t,e,i){let r=this.editor.cm.posAtCoords({x:e,y:i},!1),{data:o}=await window.$http.get(`/templates/${t}`),s=o.markdown||o.html;L(this,dt,vt).call(this,r,r,s,r)}insertClipboardImages(t,e,i){let r=this.editor.cm.posAtCoords({x:e,y:i},!1);for(let o of t)this.uploadImage(o,r)}async uploadImage(t,e=null){if(t===null||t.type.indexOf("image")!==0)return;let i="png";if(e===null&&(e=L(this,rt,ht).call(this).from),t.name){let c=t.name.match(/\.(.+)$/);c.length>1&&(i=c[1])}let r=`image-${Math.random().toString(16).slice(2)}`,s=`![](${window.baseUrl(`/loading.gif#upload${r}`)})`;L(this,dt,vt).call(this,e,e,s,e);let a=`image-${Date.now()}.${i}`,l=new FormData;l.append("file",t,a),l.append("uploaded_to",this.editor.config.pageId);try{let{data:c}=await window.$http.post("/images/gallery",l),u=`[![](${c.thumbs.display})](${c.url})`;L(this,rn,zo).call(this,s,u)}catch(c){window.$events.error(c?.data?.message||this.editor.config.text.imageUploadError),L(this,rn,zo).call(this,s,""),console.error(c)}}};en=new WeakSet,Ro=function(t,e){let i=`
    `;L(this,Pt,ne).call(this,i,i.length,e)},xe=new WeakSet,Si=function(){return this.editor.cm.state.doc.toString()},ke=new WeakSet,Ai=function(t,e=null){e=e||L(this,rt,ht).call(this);let i=this.editor.cm.state.toText(t),r=Math.min(e.from,i.length);L(this,dt,vt).call(this,0,this.editor.cm.state.doc.length,t,r),this.focus()},Pt=new WeakSet,ne=function(t,e=0,i=null){i=i||this.editor.cm.state.selection.main;let r=i.from+e;L(this,dt,vt).call(this,i.from,i.to,t,r),this.focus()},Wt=new WeakSet,ye=function(t=null){return t=t||L(this,rt,ht).call(this),this.editor.cm.state.sliceDoc(t.from,t.to)},rt=new WeakSet,ht=function(){return this.editor.cm.state.selection.main},nn=new WeakSet,No=function(t){return t.replace(/\r\n|\r/g,` `)},rn=new WeakSet,zo=function(t,e){let i=L(this,xe,Si).call(this).replace(t,e);L(this,ke,Ai).call(this,i)},Ce=new WeakSet,Di=function(t,e){let i=L(this,rt,ht).call(this),r=this.editor.cm.state.doc.lineAt(i.from),o=r.text,s,a=0;o.startsWith(t)&&o.endsWith(e)?(s=o.slice(t.length,o.length-e.length),a=-t.length):(s=`${t}${o}${e}`,a=t.length),L(this,dt,vt).call(this,r.from,r.to,s,i.from+a)},dt=new WeakSet,vt=function(t,e=null,i=null,r=null,o=null){let s={changes:{from:t,to:e,insert:i}};r&&(s.selection={anchor:r},o&&(s.selection.head=o)),this.editor.cm.dispatch(s)},Ti=new WeakSet,tu=function(t,e,i=!1){this.editor.cm.dispatch({selection:{anchor:t,head:e},scrollIntoView:i})};var $i=class{constructor(t){this.settingMap={scrollSync:!0,showPreview:!0,editorWidth:50},this.changeListeners={},this.loadFromLocalStorage(),this.applyToInputs(t),this.listenToInputChanges(t)}applyToInputs(t){for(let e of t){let i=e.getAttribute("name").replace("md-","");e.checked=this.settingMap[i]}}listenToInputChanges(t){for(let e of t)e.addEventListener("change",()=>{let i=e.getAttribute("name").replace("md-","");this.set(i,e.checked)})}loadFromLocalStorage(){let t=window.localStorage.getItem("md-editor-settings");if(!t)return;let e=JSON.parse(t);for(let[i,r]of Object.entries(e))r!==null&&this.settingMap[i]!==void 0&&(this.settingMap[i]=r)}set(t,e){this.settingMap[t]=e,window.localStorage.setItem("md-editor-settings",JSON.stringify(this.settingMap));for(let i of this.changeListeners[t]||[])i(e)}get(t){return this.settingMap[t]||null}onChange(t,e){let i=this.changeListeners[t]||[];i.push(e),this.changeListeners[t]=i}};function Ii({html:n,markdown:t}){return t||n}function eu(n){window.$events.listen("editor::replace",t=>{let e=Ii(t);n.actions.replaceContent(e)}),window.$events.listen("editor::append",t=>{let e=Ii(t);n.actions.appendContent(e)}),window.$events.listen("editor::prepend",t=>{let e=Ii(t);n.actions.prependContent(e)}),window.$events.listen("editor::insert",t=>{let e=Ii(t);n.actions.insertContent(e)}),window.$events.listen("editor::focus",()=>{n.actions.focus()})}function Hf(n){let t={};return t["Shift-Mod-i"]=()=>n.actions.insertImage(),t["Mod-s"]=()=>window.$events.emit("editor-save-draft"),t["Mod-Enter"]=()=>window.$events.emit("editor-save-page"),t["Shift-Mod-k"]=()=>n.actions.showLinkSelector(),t["Mod-k"]=()=>n.actions.insertLink(),t["Mod-1"]=()=>n.actions.replaceLineStart("##"),t["Mod-2"]=()=>n.actions.replaceLineStart("###"),t["Mod-3"]=()=>n.actions.replaceLineStart("####"),t["Mod-4"]=()=>n.actions.replaceLineStart("#####"),t["Mod-5"]=()=>n.actions.replaceLineStart(""),t["Mod-d"]=()=>n.actions.replaceLineStart(""),t["Mod-6"]=()=>n.actions.replaceLineStart(">"),t["Mod-q"]=()=>n.actions.replaceLineStart(">"),t["Mod-7"]=()=>n.actions.wrapSelection("\n```\n","\n```"),t["Mod-8"]=()=>n.actions.wrapSelection("`","`"),t["Shift-Mod-e"]=()=>n.actions.wrapSelection("`","`"),t["Mod-9"]=()=>n.actions.cycleCalloutTypeAtSelection(),t["Mod-p"]=()=>n.actions.replaceLineStart("-"),t["Mod-o"]=()=>n.actions.replaceLineStartForOrderedList(),t}function nu(n){let t=Hf(n),e=[],i=r=>()=>(r(),!0);for(let[r,o]of Object.entries(t))e.push({key:r,run:i(o),preventDefault:!0});return e}async function iu(n){let t=await window.importVersioned("code");function e(a){a.docChanged&&n.actions.updateAndRender()}let i=Nt(n.actions.syncDisplayPosition.bind(n.actions),100,!1),r=n.settings.get("scrollSync");n.settings.onChange("scrollSync",a=>{r=a});let o={scroll:a=>r&&i(a),drop:a=>{let l=a.dataTransfer.getData("bookstack/template");l&&(a.preventDefault(),n.actions.insertTemplate(l,a.pageX,a.pageY));let u=new Ft(a.dataTransfer).getImages();u.length>0&&(a.stopPropagation(),a.preventDefault(),n.actions.insertClipboardImages(u,a.pageX,a.pageY))},paste:a=>{let l=new Ft(a.clipboardData||a.dataTransfer);if(!l.hasItems()||l.containsTabularData())return;let c=l.getImages();for(let u of c)n.actions.uploadImage(u)}},s=t.markdownEditor(n.config.inputEl,e,o,nu(n));return window.mdEditorView=s,s}async function ru(n){let t={config:n,markdown:new wi,settings:new $i(n.settingInputs)};return t.actions=new Li(t),t.display=new ki(t),t.cm=await iu(t),eu(t),t}var Mi=class extends g{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,ru({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(i=>{this.editor=i,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 i=e.getAttribute("data-action");if(i==="insertImage"&&this.editor.actions.showImageInsert(),i==="insertLink"&&this.editor.actions.showLinkSelector(),i==="insertDrawing"&&(t.ctrlKey||t.metaKey)){this.editor.actions.showImageManager();return}i==="insertDrawing"&&this.editor.actions.startDrawing(),i==="fullscreen"&&this.editor.actions.fullScreen()}),this.elem.addEventListener("click",t=>{let e=t.target.closest(".editor-toolbar-label");if(!e)return;let i=this.elem.querySelectorAll(".markdown-editor-wrap");for(let r of i)r.classList.remove("active");e.closest(".markdown-editor-wrap").classList.add("active")}),this.handleDividerDrag()}handleDividerDrag(){this.divider.addEventListener("pointerdown",()=>{let e=this.elem.getBoundingClientRect(),i=o=>{let s=o.pageX-e.left,a=Math.min(Math.max(20,Math.floor(s/e.width*100)),80);this.displayWrap.style.flexBasis=`${100-a}%`,this.editor.settings.set("editorWidth",a)},r=()=>{window.removeEventListener("pointermove",i),window.removeEventListener("pointerup",r),this.display.style.pointerEvents=null,document.body.style.userSelect=null};this.display.style.pointerEvents="none",document.body.style.userSelect="none",window.addEventListener("pointermove",i),window.addEventListener("pointerup",r)});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 Fi=class extends g{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 i of e)i.disabled=t;this.inputContainer.style.display=t?"none":"block"}};var qi=class extends g{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,i=Math.max(2e3,1e3+250*e);setTimeout(this.hide.bind(this),i)}}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 g{setup(){this.removeButton=this.$refs.remove,this.showButton=this.$refs.show,this.input=this.$refs.input,this.setupListeners()}setupListeners(){R(this.removeButton,()=>{this.input.value="",this.input.classList.add("hidden"),this.removeButton.classList.add("hidden"),this.showButton.classList.remove("hidden")}),R(this.showButton,()=>{this.input.classList.remove("hidden"),this.removeButton.classList.remove("hidden"),this.showButton.classList.add("hidden")})}};var Pi=class extends g{setup(){this.commentId=this.$opts.commentId,this.commentLocalId=this.$opts.commentLocalId,this.commentParentId=this.$opts.commentParentId,this.deletedText=this.$opts.deletedText,this.updatedText=this.$opts.updatedText,this.container=this.$el,this.contentContainer=this.$refs.contentContainer,this.form=this.$refs.form,this.formCancel=this.$refs.formCancel,this.editButton=this.$refs.editButton,this.deleteButton=this.$refs.deleteButton,this.replyButton=this.$refs.replyButton,this.input=this.$refs.input,this.setupListeners()}setupListeners(){this.replyButton&&this.replyButton.addEventListener("click",()=>this.$emit("reply",{id:this.commentLocalId,element:this.container})),this.editButton&&(this.editButton.addEventListener("click",this.startEdit.bind(this)),this.form.addEventListener("submit",this.update.bind(this)),this.formCancel.addEventListener("click",()=>this.toggleEditMode(!1))),this.deleteButton&&this.deleteButton.addEventListener("click",this.delete.bind(this))}toggleEditMode(t){this.contentContainer.toggleAttribute("hidden",t),this.form.toggleAttribute("hidden",!t)}startEdit(){this.toggleEditMode(!0);let t=this.$refs.input.value.split(` -`).length;this.$refs.input.style.height=`${t*20+40}px`}async update(t){t.preventDefault();let e=this.showLoading();this.form.toggleAttribute("hidden",!0);let i={text:this.input.value,parent_id:this.parentId||null};try{let r=await window.$http.put(`/comment/${this.commentId}`,i),o=_t(r.data);this.container.replaceWith(o),window.$events.success(this.updatedText)}catch(r){console.error(r),window.$events.showValidationErrors(r),this.form.toggleAttribute("hidden",!1),e.remove()}}async delete(){this.showLoading(),await window.$http.delete(`/comment/${this.commentId}`),this.container.closest(".comment-branch").remove(),window.$events.success(this.deletedText),this.$emit("delete")}showLoading(){let t=ae();return t.classList.add("px-l"),this.container.append(t),t}};var Oi=class extends g{setup(){this.elem=this.$el,this.pageId=Number(this.$opts.pageId),this.container=this.$refs.commentContainer,this.commentCountBar=this.$refs.commentCountBar,this.commentsTitle=this.$refs.commentsTitle,this.addButtonContainer=this.$refs.addButtonContainer,this.replyToRow=this.$refs.replyToRow,this.formContainer=this.$refs.formContainer,this.form=this.$refs.form,this.formInput=this.$refs.formInput,this.formReplyLink=this.$refs.formReplyLink,this.addCommentButton=this.$refs.addCommentButton,this.hideFormButton=this.$refs.hideFormButton,this.removeReplyToButton=this.$refs.removeReplyToButton,this.createdText=this.$opts.createdText,this.countText=this.$opts.countText,this.parentId=null,this.formReplyText=this.formReplyLink?.textContent||"",this.setupListeners()}setupListeners(){this.elem.addEventListener("page-comment-delete",()=>{this.updateCount(),this.hideForm()}),this.elem.addEventListener("page-comment-reply",t=>{this.setReply(t.detail.id,t.detail.element)}),this.form&&(this.removeReplyToButton.addEventListener("click",this.removeReplyTo.bind(this)),this.hideFormButton.addEventListener("click",this.hideForm.bind(this)),this.addCommentButton.addEventListener("click",this.showForm.bind(this)),this.form.addEventListener("submit",this.saveComment.bind(this)))}saveComment(t){t.preventDefault(),t.stopPropagation();let e=ae();e.classList.add("px-l"),this.form.after(e),this.form.toggleAttribute("hidden",!0);let r={text:this.formInput.value,parent_id:this.parentId||null};window.$http.post(`/comment/${this.pageId}`,r).then(o=>{let s=_t(o.data);this.formContainer.after(s),window.$events.success(this.createdText),this.hideForm(),this.updateCount()}).catch(o=>{this.form.toggleAttribute("hidden",!1),window.$events.showValidationErrors(o)}),this.form.toggleAttribute("hidden",!1),e.remove()}updateCount(){let t=this.getCommentCount();this.commentsTitle.textContent=window.trans_plural(this.countText,t,{count:t})}resetForm(){this.formInput.value="",this.parentId=null,this.replyToRow.toggleAttribute("hidden",!0),this.container.append(this.formContainer)}showForm(){this.formContainer.toggleAttribute("hidden",!1),this.addButtonContainer.toggleAttribute("hidden",!0),this.formContainer.scrollIntoView({behavior:"smooth",block:"nearest"}),setTimeout(()=>{this.formInput.focus()},100)}hideForm(){this.resetForm(),this.formContainer.toggleAttribute("hidden",!0),this.getCommentCount()>0?this.elem.append(this.addButtonContainer):this.commentCountBar.append(this.addButtonContainer),this.addButtonContainer.toggleAttribute("hidden",!1)}getCommentCount(){return this.container.querySelectorAll('[component="page-comment"]').length}setReply(t,e){e.closest(".comment-branch").querySelector(".comment-branch-children").append(this.formContainer),this.showForm(),this.parentId=t,this.replyToRow.toggleAttribute("hidden",!1),this.formReplyLink.textContent=this.formReplyText.replace("1234",this.parentId),this.formReplyLink.href=`#comment${this.parentId}`}removeReplyTo(){this.parentId=null,this.replyToRow.toggleAttribute("hidden",!0),this.container.append(this.formContainer),this.showForm()}};function Uf(n,t){xr(`#page-navigation a[href="#${n}"]`,e=>{e.closest("li").classList.toggle("current-heading",t)})}function jf(n){for(let t of n){let e=t.intersectionRatio===1;Uf(t.target.id,e)}}function Vf(n){let t={rootMargin:"0px 0px 0px 0px",threshold:1},e=new IntersectionObserver(jf,t);for(let i of n)e.observe(i)}var Ri=class extends g{setup(){if(this.container=this.$el,this.pageId=this.$opts.pageId,window.importVersioned("code").then(e=>e.highlight()),this.setupNavHighlighting(),window.location.hash){let e=window.location.hash.replace(/%20/g," ").substring(1);this.goToText(e)}let t=document.querySelector(".sidebar-page-nav");t&&K(t,"a","click",(e,i)=>{e.preventDefault(),window.$components.first("tri-layout").showContent();let r=i.getAttribute("href").substr(1);this.goToText(r),window.history.pushState(null,null,`#${r}`)})}goToText(t){let e=document.getElementById(t);if(xr(".page-content [data-highlighted]",i=>{i.removeAttribute("data-highlighted"),i.style.backgroundColor=null}),e!==null)Cr(e);else{let i=ts(".page-content > div > *",t);i&&Cr(i)}}setupNavHighlighting(){let t=document.querySelector(".sidebar-page-nav"),e=document.querySelector(".page-content").querySelectorAll("h1, h2, h3, h4, h5, h6");e.length>0&&t!==null&&Vf(e)}};function ou(n){let t=new Date(n*1e3),e=t.getHours(),i=t.getMinutes();return`${(e>9?"":"0")+e}:${(i>9?"":"0")+i}`}var Ni=class extends g{setup(){this.draftsEnabled=this.$opts.draftsEnabled==="true",this.editorType=this.$opts.editorType,this.pageId=Number(this.$opts.pageId),this.isNewDraft=this.$opts.pageNewDraft==="true",this.hasDefaultTitle=this.$opts.hasDefaultTitle||!1,this.container=this.$el,this.titleElem=this.$refs.titleContainer.querySelector("input"),this.saveDraftButton=this.$refs.saveDraft,this.discardDraftButton=this.$refs.discardDraft,this.discardDraftWrap=this.$refs.discardDraftWrap,this.deleteDraftButton=this.$refs.deleteDraft,this.deleteDraftWrap=this.$refs.deleteDraftWrap,this.draftDisplay=this.$refs.draftDisplay,this.draftDisplayIcon=this.$refs.draftDisplayIcon,this.changelogInput=this.$refs.changelogInput,this.changelogDisplay=this.$refs.changelogDisplay,this.changeEditorButtons=this.$manyRefs.changeEditor||[],this.switchDialogContainer=this.$refs.switchDialog,this.deleteDraftDialogContainer=this.$refs.deleteDraftDialog,this.draftText=this.$opts.draftText,this.autosaveFailText=this.$opts.autosaveFailText,this.editingPageText=this.$opts.editingPageText,this.draftDiscardedText=this.$opts.draftDiscardedText,this.draftDeleteText=this.$opts.draftDeleteText,this.draftDeleteFailText=this.$opts.draftDeleteFailText,this.setChangelogText=this.$opts.setChangelogText,this.autoSave={interval:null,frequency:3e4,last:0,pendingChange:!1},this.shownWarningsCache=new Set,this.pageId!==0&&this.draftsEnabled&&window.setTimeout(()=>{this.startAutoSave()},1e3),this.draftDisplay.innerHTML=this.draftText,this.setupListeners(),this.setInitialFocus()}setupListeners(){window.$events.listen("editor-save-draft",this.saveDraft.bind(this)),window.$events.listen("editor-save-page",this.savePage.bind(this));let t=()=>{this.autoSave.pendingChange=!0};window.$events.listen("editor-html-change",t),window.$events.listen("editor-markdown-change",t),this.titleElem.addEventListener("input",t);let e=Nt(this.updateChangelogDisplay.bind(this),300,!1);this.changelogInput.addEventListener("input",e),R(this.saveDraftButton,this.saveDraft.bind(this)),R(this.discardDraftButton,this.discardDraft.bind(this)),R(this.deleteDraftButton,this.deleteDraft.bind(this)),R(this.changeEditorButtons,this.changeEditor.bind(this))}setInitialFocus(){if(this.hasDefaultTitle){this.titleElem.select();return}window.setTimeout(()=>{window.$events.emit("editor::focus","")},500)}startAutoSave(){this.autoSave.interval=window.setInterval(this.runAutoSave.bind(this),this.autoSave.frequency)}runAutoSave(){Date.now()-this.autoSave.last{this.draftDisplayIcon.classList.remove("visible")},2e3)}async discardDraft(t=!0){let e;try{e=await window.$http.get(`/ajax/page/${this.pageId}`)}catch(i){console.error(i);return}this.autoSave.interval&&window.clearInterval(this.autoSave.interval),this.draftDisplay.innerText=this.editingPageText,this.discardDraftWrap.toggleAttribute("hidden",!0),window.$events.emit("editor::replace",{html:e.data.html,markdown:e.data.markdown}),this.titleElem.value=e.data.name,window.setTimeout(()=>{this.startAutoSave()},1e3),t&&window.$events.success(this.draftDiscardedText)}async deleteDraft(){if(await window.$components.firstOnElement(this.deleteDraftDialogContainer,"confirm-dialog").show())try{let i=this.discardDraft(!1),r=window.$http.delete(`/page-revisions/user-drafts/${this.pageId}`);await Promise.all([i,r]),window.$events.success(this.draftDeleteText),this.deleteDraftWrap.toggleAttribute("hidden",!0)}catch(i){console.error(i),window.$events.error(this.draftDeleteFailText)}}updateChangelogDisplay(){let t=this.changelogInput.value.trim();t.length===0?t=this.setChangelogText:t.length>16&&(t=`${t.slice(0,16)}...`),this.changelogDisplay.innerText=t}async changeEditor(t){t.preventDefault();let e=t.target.closest("a").href,i=window.$components.firstOnElement(this.switchDialogContainer,"confirm-dialog"),[r,o]=await Promise.all([this.saveDraft(),i.show()]);r&&o&&(window.location=e)}getEditorComponent(){return window.$components.first("markdown-editor")||window.$components.first("wysiwyg-editor")}};function zi(n,t){n.toggleAttribute("hidden",!t)}var Hi=class extends g{setup(){this.input=this.$refs.input,this.resetButton=this.$refs.resetButton,this.selectButton=this.$refs.selectButton,this.display=this.$refs.display,this.defaultDisplay=this.$refs.defaultDisplay,this.buttonSep=this.$refs.buttonSeperator,this.selectorEndpoint=this.$opts.selectorEndpoint,this.value=this.input.value,this.setupListeners()}setupListeners(){this.selectButton.addEventListener("click",this.showPopup.bind(this)),this.display.parentElement.addEventListener("click",this.showPopup.bind(this)),this.display.addEventListener("click",t=>t.stopPropagation()),this.resetButton.addEventListener("click",()=>{this.setValue("","")})}showPopup(){window.$components.first("entity-selector-popup").show(e=>{this.setValue(e.id,e.name)},"",{searchEndpoint:this.selectorEndpoint,entityTypes:"page",entityPermission:"view"})}setValue(t,e){this.value=t,this.input.value=t,this.controlView(e)}controlView(t){let e=this.value&&this.value!==0;if(zi(this.resetButton,e),zi(this.buttonSep,e),zi(this.defaultDisplay,!e),zi(this.display,e),e){let i=this.getAssetIdFromVal();this.display.textContent=`#${i}, ${t}`,this.display.href=window.baseUrl(`/link/${i}`)}}getAssetIdFromVal(){return Number(this.value)}};var Ui=class extends g{setup(){this.container=this.$el,this.cellSelector=this.$opts.cellSelector||"td,th",this.rowSelector=this.$opts.rowSelector||"tr";for(let t of this.$manyRefs.toggleAll||[])t.addEventListener("click",this.toggleAllClick.bind(this));for(let t of this.$manyRefs.toggleRow||[])t.addEventListener("click",this.toggleRowClick.bind(this));for(let t of this.$manyRefs.toggleColumn||[])t.addEventListener("click",this.toggleColumnClick.bind(this))}toggleAllClick(t){t.preventDefault(),this.toggleAllInElement(this.container)}toggleRowClick(t){t.preventDefault(),this.toggleAllInElement(t.target.closest(this.rowSelector))}toggleColumnClick(t){t.preventDefault();let e=t.target.closest(this.cellSelector),i=Array.from(e.parentElement.children).indexOf(e),r=this.container.querySelectorAll(this.rowSelector),o=[];for(let s of r){let a=s.children[i];a&&o.push(...a.querySelectorAll("input[type=checkbox]"))}this.toggleAllInputs(o)}toggleAllInElement(t){let e=t.querySelectorAll("input[type=checkbox]");this.toggleAllInputs(e)}toggleAllInputs(t){let e=t.length>0?t[0].checked:!1;for(let i of t)i.checked=!e,i.dispatchEvent(new Event("change"))}};var ji=class extends g{setup(){this.container=this.$el,this.pointer=this.$refs.pointer,this.linkInput=this.$refs.linkInput,this.linkButton=this.$refs.linkButton,this.includeInput=this.$refs.includeInput,this.includeButton=this.$refs.includeButton,this.sectionModeButton=this.$refs.sectionModeButton,this.modeToggles=this.$manyRefs.modeToggle,this.modeSections=this.$manyRefs.modeSection,this.pageId=this.$opts.pageId,this.showing=!1,this.isSelection=!1,this.setupListeners()}setupListeners(){this.includeButton.addEventListener("click",()=>Wr(this.includeInput.value)),this.linkButton.addEventListener("click",()=>Wr(this.linkInput.value)),R([this.includeInput,this.linkInput],e=>{e.target.select(),e.stopPropagation()}),ln(this.pointer,["click","focus"],e=>{e.stopPropagation()}),ln(document.body,["click","focus"],()=>{!this.showing||this.isSelection||this.hidePointer()}),Qo(this.pointer,this.hidePointer.bind(this));let t=document.querySelector(".page-content");ln(t,["mouseup","keyup"],e=>{e.stopPropagation();let i=e.target.closest('[id^="bkmrk"]');i&&window.getSelection().toString().length>0&&this.showPointerAtTarget(i,e.pageX,!1)}),R(this.sectionModeButton,this.enterSectionSelectMode.bind(this)),R(this.modeToggles,e=>{for(let i of this.modeSections){let r=!i.contains(e.target);i.toggleAttribute("hidden",!r)}this.modeToggles.find(i=>i!==e.target).focus()})}hidePointer(){this.pointer.style.display=null,this.showing=!1}showPointerAtTarget(t,e,i){this.updateForTarget(t),this.pointer.style.display="block";let r=t.getBoundingClientRect(),o=this.pointer.getBoundingClientRect(),a=Math.min(Math.max(e,r.left),r.right)-o.width/2,l=r.top-o.height-16;this.pointer.style.left=`${a}px`,this.pointer.style.top=`${l}px`,this.showing=!0,this.isSelection=!0,setTimeout(()=>{this.isSelection=!1},100);let c=()=>{this.hidePointer(),window.removeEventListener("scroll",c,{passive:!0})};t.parentElement.insertBefore(this.pointer,t),i||window.addEventListener("scroll",c,{passive:!0})}updateForTarget(t){let e=window.baseUrl(`/link/${this.pageId}#${t.id}`),i=`{{@${this.pageId}#${t.id}}}`;this.linkInput.value=e,this.includeInput.value=i;let r=this.pointer.querySelector("#pointer-edit");if(r&&t){let{editHref:o}=r.dataset,s=t.id,a=t.textContent&&t.textContent.substring(0,50);r.href=`${o}?content-id=${s}&content-text=${encodeURIComponent(a)}`}}enterSectionSelectMode(){let t=Array.from(document.querySelectorAll('.page-content [id^="bkmrk"]'));for(let e of t)e.setAttribute("tabindex","0");t[0].focus(),se(t,e=>{this.showPointerAtTarget(e.target,0,!0),this.pointer.focus()})}};var Vi=class extends g{setup(){this.container=this.$el,this.hideButtons=this.$manyRefs.hide||[],this.onkeyup=null,this.onHide=null,this.setupListeners()}setupListeners(){let t=null;this.container.addEventListener("mousedown",e=>{t=e.target}),this.container.addEventListener("click",e=>{e.target===this.container&&t===this.container&&this.hide()}),R(this.hideButtons,()=>this.hide())}hide(t=null){Is(this.container,120,t),this.onkeyup&&(window.removeEventListener("keyup",this.onkeyup),this.onkeyup=null),this.onHide&&this.onHide()}show(t=null,e=null){$s(this.container,120,t),this.onkeyup=i=>{i.key==="Escape"&&this.hide()},window.addEventListener("keyup",this.onkeyup),this.onHide=e}};var Wi=class extends g{setup(){this.container=this.$el,this.mode=this.$opts.mode,this.lightContainer=this.$refs.lightContainer,this.darkContainer=this.$refs.darkContainer,this.container.addEventListener("tabs-change",e=>{let r=e.detail.showing==="color-scheme-panel-light"?"light":"dark";this.handleModeChange(r)});let t=e=>{this.updateAppColorsFromInputs(),e.target.name.startsWith("setting-app-color")&&this.updateLightForInput(e.target)};this.container.addEventListener("change",t),this.container.addEventListener("input",t)}handleModeChange(t){this.mode=t;let e=t==="dark";document.documentElement.classList.toggle("dark-mode",e),this.updateAppColorsFromInputs()}updateAppColorsFromInputs(){let e=(this.mode==="dark"?this.darkContainer:this.lightContainer).querySelectorAll('input[type="color"]');for(let i of e){let r=i.name.split("-"),o=r.indexOf("color"),s=r.slice(1,o).join("-");s==="app"&&(s="primary");let a=`--color-${s}`;document.body.style.setProperty(a,i.value)}}updateLightForInput(t){let e=t.name.replace("-color","-color-light"),i=t.value,r=this.hexToRgb(i),o=`rgba(${[r.r,r.g,r.b,"0.15"].join(",")})`,s=this.container.querySelector(`input[name="${e}"][type="hidden"]`);s.value=o}hexToRgb(t){let e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return{r:e?parseInt(e[1],16):0,g:e?parseInt(e[2],16):0,b:e?parseInt(e[3],16):0}}};var Gi=class extends g{setup(){this.colorInput=this.$refs.input,this.resetButton=this.$refs.resetButton,this.defaultButton=this.$refs.defaultButton,this.currentColor=this.$opts.current,this.defaultColor=this.$opts.default,this.resetButton.addEventListener("click",()=>this.setValue(this.currentColor)),this.defaultButton.addEventListener("click",()=>this.setValue(this.defaultColor))}setValue(t){this.colorInput.value=t,this.colorInput.dispatchEvent(new Event("change",{bubbles:!0}))}};var Ki=class extends g{setup(){this.typeControl=this.$refs.typeControl,this.pagePickerContainer=this.$refs.pagePickerContainer,this.typeControl.addEventListener("change",this.controlPagePickerVisibility.bind(this)),this.controlPagePickerVisibility()}controlPagePickerVisibility(){let t=this.typeControl.value==="page";this.pagePickerContainer.style.display=t?"block":"none"}};var Gf={move_up(n){let t=n.parentNode,e=Array.from(t.children).indexOf(n),i=Math.max(e-1,0);t.insertBefore(n,t.children[i]||null)},move_down(n){let t=n.parentNode,e=Array.from(t.children).indexOf(n),i=Math.min(e+2,t.children.length);t.insertBefore(n,t.children[i]||null)},remove(n,t,e){e.appendChild(n)},add(n,t){t.appendChild(n)}},Zi=class extends g{setup(){this.elem=this.$el,this.input=this.$refs.input,this.shelfBookList=this.$refs.shelfBookList,this.allBookList=this.$refs.allBookList,this.bookSearchInput=this.$refs.bookSearch,this.sortButtonContainer=this.$refs.sortButtonContainer,this.lastSort=null,this.initSortable(),this.setupListeners()}initSortable(){let t=this.elem.querySelectorAll(".scroll-box");for(let e of t)new Yt(e,{group:"shelf-books",ghostClass:"primary-background-light",handle:".handle",animation:150,onSort:this.onChange.bind(this)})}setupListeners(){this.elem.addEventListener("click",t=>{let e=t.target.closest(".scroll-box-item button[data-action]");e&&this.sortItemActionClick(e)}),this.bookSearchInput.addEventListener("input",()=>{this.filterBooksByName(this.bookSearchInput.value)}),this.sortButtonContainer.addEventListener("click",t=>{let e=t.target.closest("button[data-sort]");e&&this.sortShelfBooks(e.dataset.sort)})}filterBooksByName(t){this.allBookList.style.height||(this.allBookList.style.height=`${this.allBookList.getBoundingClientRect().height}px`);let e=this.allBookList.children,i=t.trim().toLowerCase();for(let r of e){let o=!t||r.textContent.toLowerCase().includes(i);r.style.display=o?null:"none"}}sortItemActionClick(t){let e=t.closest(".scroll-box-item"),{action:i}=t.dataset,r=Gf[i];r(e,this.shelfBookList,this.allBookList),this.onChange()}onChange(){let t=Array.from(this.shelfBookList.querySelectorAll("[data-id]"));this.input.value=t.map(e=>e.getAttribute("data-id")).join(",")}sortShelfBooks(t){let e=Array.from(this.shelfBookList.children),i=t===this.lastSort;e.sort((r,o)=>{let s=r.dataset[t].toLowerCase(),a=o.dataset[t].toLowerCase();return i?a.localeCompare(s):s.localeCompare(a)});for(let r of e)this.shelfBookList.append(r);this.lastSort=this.lastSort===t?null:t,this.onChange()}};function Kf(n){let t={};for(let[e,i]of Object.entries(n))t[i]=e;return t}var Xi=class extends g{setup(){this.container=this.$el,this.mapById=JSON.parse(this.$opts.keyMap),this.mapByShortcut=Kf(this.mapById),this.hintsShowing=!1,this.hideHints=this.hideHints.bind(this),this.hintAbortController=null,this.setupListeners()}setupListeners(){window.addEventListener("keydown",t=>{if(!t.target.closest("input, select, textarea, .cm-editor")){if(t.key==="?"){this.hintsShowing?this.hideHints():this.showHints();return}this.handleShortcutPress(t)}})}handleShortcutPress(t){let i=[t.ctrlKey?"Ctrl":"",t.metaKey?"Cmd":"",t.key].filter(o=>!!o).join(" + "),r=this.mapByShortcut[i];r&&this.runShortcut(r)&&t.preventDefault()}runShortcut(t){let e=this.container.querySelector(`[data-shortcut="${t}"]`);return e?e.matches("input, textarea, select")?(e.focus(),!0):e.matches("a, button")?(e.click(),!0):e.matches("div[tabindex]")?(e.click(),e.focus(),!0):(console.error("Shortcut attempted to be ran for element type that does not have handling setup",e),!1):!1}showHints(){let t=document.createElement("div");t.classList.add("shortcut-container"),this.container.append(t);let e=this.container.querySelectorAll("[data-shortcut]"),i=new Set;for(let o of e){let s=o.getAttribute("data-shortcut");if(i.has(s))continue;let a=this.mapById[s];this.showHintLabel(o,a,t),i.add(s)}this.hintAbortController=new AbortController;let r=this.hintAbortController.signal;window.addEventListener("scroll",this.hideHints,{signal:r}),window.addEventListener("focus",this.hideHints,{signal:r}),window.addEventListener("blur",this.hideHints,{signal:r}),window.addEventListener("click",this.hideHints,{signal:r}),this.hintsShowing=!0}showHintLabel(t,e,i){let r=t.getBoundingClientRect(),o=document.createElement("div");o.classList.add("shortcut-hint"),o.textContent=e;let s=document.createElement("div");s.classList.add("shortcut-linkage"),s.style.left=`${r.x}px`,s.style.top=`${r.y}px`,s.style.width=`${r.width}px`,s.style.height=`${r.height}px`,i.append(o,s);let a=o.getBoundingClientRect();o.style.insetInlineStart=`${r.x+r.width-(a.width+6)}px`,o.style.insetBlockStart=`${r.y+(r.height-a.height)/2}px`}hideHints(){this.container.querySelector(".shortcut-container").remove(),this.hintAbortController?.abort(),this.hintsShowing=!1}};var Zf=["Control","Alt","Shift","Meta","Super"," ","+","Tab","Escape"],Yi=class extends g{setup(){this.input=this.$el,this.setupListeners()}setupListeners(){this.listenerRecordKey=this.listenerRecordKey.bind(this),this.input.addEventListener("focus",()=>{this.startListeningForInput()}),this.input.addEventListener("blur",()=>{this.stopListeningForInput()})}startListeningForInput(){this.input.addEventListener("keydown",this.listenerRecordKey)}listenerRecordKey(t){if(Zf.includes(t.key))return;let e=[t.ctrlKey?"Ctrl":"",t.metaKey?"Cmd":"",t.key];this.input.value=e.filter(i=>!!i).join(" + ")}stopListeningForInput(){this.input.removeEventListener("keydown",this.listenerRecordKey)}};var Ji=class extends g{setup(){this.container=this.$el,this.handleSelector=this.$opts.handleSelector;let t=new Yt(this.container,{handle:this.handleSelector,animation:150,onSort:()=>{this.$emit("sort",{ids:t.toArray()})},setData(e,i){let r=i.getAttribute("data-drag-content");if(r){let o=JSON.parse(r);for(let[s,a]of Object.entries(o))e.setData(s,a)}},revertOnSpill:!0,dropBubble:!0,dragoverBubble:!1})}};var Qi=class extends g{setup(){this.filter=this.$opts.filter,this.$el.addEventListener("change",t=>{if(this.filter&&!t.target.matches(this.filter))return;let e=this.$el.closest("form");e&&e.submit()})}};var tr=class extends g{setup(){this.container=this.$el,this.tabList=this.container.querySelector('[role="tablist"]'),this.tabs=Array.from(this.tabList.querySelectorAll('[role="tab"]')),this.panels=Array.from(this.container.querySelectorAll(':scope > [role="tabpanel"], :scope > * > [role="tabpanel"]')),this.activeUnder=this.$opts.activeUnder?Number(this.$opts.activeUnder):1e4,this.active=null,this.container.addEventListener("click",t=>{let e=t.target.closest('[role="tab"]');e&&this.tabs.includes(e)&&this.show(e.getAttribute("aria-controls"))}),window.addEventListener("resize",this.updateActiveState.bind(this),{passive:!0}),this.updateActiveState()}show(t){for(let e of this.panels)e.toggleAttribute("hidden",e.id!==t);for(let e of this.tabs){let r=e.getAttribute("aria-controls")===t;e.setAttribute("aria-selected",r?"true":"false")}this.$emit("change",{showing:t})}updateActiveState(){let t=window.innerWidth!e.hasAttribute("hidden"))||this.panels[0];this.show(t.id),this.tabList.toggleAttribute("hidden",!1)}deactivate(){for(let t of this.panels)t.removeAttribute("hidden");for(let t of this.tabs)t.setAttribute("aria-selected","false");this.tabList.toggleAttribute("hidden",!0)}};var er=class extends g{setup(){this.addRemoveComponentEl=this.$refs.addRemove,this.container=this.$el,this.rowSelector=this.$opts.rowSelector,this.setupListeners()}setupListeners(){this.container.addEventListener("input",t=>{let e=window.$components.firstOnElement(this.addRemoveComponentEl,"add-remove-rows");!this.hasEmptyRows()&&t.target.value&&e.add()})}hasEmptyRows(){return[...this.container.querySelectorAll(this.rowSelector)].find(i=>[...i.querySelectorAll("input")].filter(r=>r.value).length===0)!==void 0}};var nr=class extends g{setup(){this.container=this.$el,this.list=this.$refs.list,this.searchInput=this.$refs.searchInput,this.searchButton=this.$refs.searchButton,this.searchCancel=this.$refs.searchCancel,this.setupListeners()}setupListeners(){K(this.container,"[template-action]","click",this.handleTemplateActionClick.bind(this)),K(this.container,".pagination a","click",this.handlePaginationClick.bind(this)),K(this.container,".template-item-content","click",this.handleTemplateItemClick.bind(this)),K(this.container,".template-item","dragstart",this.handleTemplateItemDragStart.bind(this)),this.searchInput.addEventListener("keypress",t=>{t.key==="Enter"&&(t.preventDefault(),this.performSearch())}),this.searchButton.addEventListener("click",()=>this.performSearch()),this.searchCancel.addEventListener("click",()=>{this.searchInput.value="",this.performSearch()})}handleTemplateItemClick(t,e){let i=e.closest("[template-id]").getAttribute("template-id");this.insertTemplate(i,"replace")}handleTemplateItemDragStart(t,e){let i=e.closest("[template-id]").getAttribute("template-id");t.dataTransfer.setData("bookstack/template",i),t.dataTransfer.setData("text/plain",i)}handleTemplateActionClick(t,e){t.stopPropagation();let i=e.getAttribute("template-action"),r=e.closest("[template-id]").getAttribute("template-id");this.insertTemplate(r,i)}async insertTemplate(t,e="replace"){let i=await window.$http.get(`/templates/${t}`),r=`editor::${e}`;window.$events.emit(r,i.data)}async handlePaginationClick(t,e){t.preventDefault();let i=e.getAttribute("href"),r=await window.$http.get(i);this.list.innerHTML=r.data}async performSearch(){let t=this.searchInput.value,e=await window.$http.get("/templates",{search:t});this.searchCancel.style.display=t?"block":"none",this.list.innerHTML=e.data}};var ir=class extends g{setup(){this.input=this.$el.querySelector("input[type=hidden]"),this.checkbox=this.$el.querySelector("input[type=checkbox]"),this.checkbox.addEventListener("change",this.stateChange.bind(this))}stateChange(){this.input.value=this.checkbox.checked?"true":"false";let t=new Event("change");this.input.dispatchEvent(t)}};var rr=class extends g{setup(){this.container=this.$refs.container,this.tabs=this.$manyRefs.tab,this.lastLayoutType="none",this.onDestroy=null,this.scrollCache={content:0,info:0},this.lastTabShown="content",this.mobileTabClick=this.mobileTabClick.bind(this),this.updateLayout(),window.addEventListener("resize",()=>{this.updateLayout()},{passive:!0})}updateLayout(){let t="tablet";window.innerWidth<=1e3&&(t="mobile"),window.innerWidth>=1400&&(t="desktop"),t!==this.lastLayoutType&&(this.onDestroy&&(this.onDestroy(),this.onDestroy=null),t==="desktop"?this.setupDesktop():t==="mobile"&&this.setupMobile(),this.lastLayoutType=t)}setupMobile(){for(let t of this.tabs)t.addEventListener("click",this.mobileTabClick);this.onDestroy=()=>{for(let t of this.tabs)t.removeEventListener("click",this.mobileTabClick)}}setupDesktop(){}mobileTabClick(t){let{tab:e}=t.target.dataset;this.showTab(e)}showContent(){this.showTab("content",!1)}showTab(t,e=!0){this.scrollCache[this.lastTabShown]=document.documentElement.scrollTop;for(let r of this.tabs){let o=r.dataset.tab===t;r.setAttribute("aria-selected",o?"true":"false")}let i=t==="info";if(this.container.classList.toggle("show-info",i),e){let o=document.querySelector("header").getBoundingClientRect().bottom;document.documentElement.scrollTop=this.scrollCache[t]||o,setTimeout(()=>{document.documentElement.scrollTop=this.scrollCache[t]||o},50)}this.lastTabShown=t}};var or=class extends g{setup(){this.container=this.$el,this.input=this.$refs.input,this.userInfoContainer=this.$refs.userInfo,K(this.container,"a.dropdown-search-item","click",this.selectUser.bind(this))}selectUser(t,e){t.preventDefault(),this.input.value=e.getAttribute("data-id"),this.userInfoContainer.innerHTML=e.innerHTML,this.input.dispatchEvent(new Event("change",{bubbles:!0})),this.hide()}hide(){window.$components.firstOnElement(this.container,"dropdown").hide()}};var sr=class extends g{setup(){this.checkboxes=this.$el.querySelectorAll('input[type="checkbox"]'),this.allCheckbox=this.$el.querySelector('input[type="checkbox"][value="all"]'),this.$el.addEventListener("change",t=>{t.target.checked&&t.target===this.allCheckbox?this.deselectIndividualEvents():t.target.checked&&(this.allCheckbox.checked=!1)})}deselectIndividualEvents(){for(let t of this.checkboxes)t!==this.allCheckbox&&(t.checked=!1)}};function su(n){for(let t=1;t<5;t++)n.shortcuts.add(`meta+${t}`,"",["FormatBlock",!1,`h${t+1}`]);n.shortcuts.add("meta+5","",["FormatBlock",!1,"p"]),n.shortcuts.add("meta+d","",["FormatBlock",!1,"p"]),n.shortcuts.add("meta+6","",["FormatBlock",!1,"blockquote"]),n.shortcuts.add("meta+q","",["FormatBlock",!1,"blockquote"]),n.shortcuts.add("meta+7","",["codeeditor",!1,"pre"]),n.shortcuts.add("meta+e","",["codeeditor",!1,"pre"]),n.shortcuts.add("meta+8","",["FormatBlock",!1,"code"]),n.shortcuts.add("meta+shift+E","",["FormatBlock",!1,"code"]),n.shortcuts.add("meta+o","","InsertOrderedList"),n.shortcuts.add("meta+p","","InsertUnorderedList"),n.shortcuts.add("meta+S","",()=>{window.$events.emit("editor-save-draft")}),n.shortcuts.add("meta+13","",()=>{window.$events.emit("editor-save-page")}),n.shortcuts.add("meta+9","",()=>{let t=n.selection.getNode(),e=t?t.closest(".callout"):null,i=["info","success","warning","danger"],o=(i.findIndex(a=>e&&e.classList.contains(a))+1)%i.length,s=i[o];n.formatter.apply(`callout${s}`)}),n.shortcuts.add("meta+shift+K","",()=>{let t=window.$components.first("entity-selector-popup"),e=n.selection.getContent({format:"text"}).trim();t.show(i=>{n.selection.isCollapsed()?n.insertContent(n.dom.createHTML("a",{href:i.link},n.dom.encode(i.name))):n.formatter.apply("link",{href:i.link}),n.selection.collapse(!1),n.focus()},e,{searchEndpoint:"/search/entity-selector",entityTypes:"page,book,chapter,bookshelf",entityPermission:"view"})})}function au(n){window.$events.listen("editor::replace",({html:t})=>{n.setContent(t)}),window.$events.listen("editor::append",({html:t})=>{let e=n.getContent()+t;n.setContent(e)}),window.$events.listen("editor::prepend",({html:t})=>{let e=t+n.getContent();n.setContent(e)}),window.$events.listen("editor::insert",({html:t})=>{n.insertContent(t)}),window.$events.listen("editor::focus",()=>{n.initialized&&n.focus()})}function Xf(n,t){let e=n.dom.get(encodeURIComponent(t).replace(/!/g,"%21"));e&&(e.scrollIntoView(),n.selection.select(e,!0),n.selection.collapse(!1),n.focus())}function lu(n){let e=new URL(window.location).searchParams.get("content-id");e&&Xf(n,e)}var ie,ar;function Yf(n){return n&&!!(n.textContent||n.innerText)}async function Jf(n,t){if(n===null||n.type.indexOf("image")!==0)throw new Error("Not an image file");let e=n.name||`image-${Date.now()}.png`,i=new FormData;return i.append("file",n,e),i.append("uploaded_to",t),(await window.$http.post(window.baseUrl("/images/gallery"),i)).data}function cu(n,t,e){let i=new Ft(e.clipboardData||e.dataTransfer);if(!i.hasItems()||i.containsTabularData())return;let r=i.getImages();for(let o of r){let s=`image-${Math.random().toString(16).slice(2)}`,a=window.baseUrl("/loading.gif");e.preventDefault(),setTimeout(()=>{n.insertContent(`

    `),Jf(o,t.pageId).then(l=>{let c=l.name.replace(/"/g,""),u=`${c}`,h=n.dom.create("a",{target:"_blank",href:l.url},u);n.dom.replace(h,s)}).catch(l=>{n.dom.remove(s),window.$events.error(l?.data?.message||t.translations.imageUploadErrorText),console.error(l)})},10)}}function Qf(n){let t=n.selection.getNode();t.nodeName==="IMG"&&(ie=n.dom.getParent(t,".mceTemp"),!ie&&t.parentNode.nodeName==="A"&&!Yf(t.parentNode)&&(ie=t.parentNode)),t.hasAttribute("contenteditable")&&t.getAttribute("contenteditable")==="false"&&(ar=t)}function tm(n,t,e){let{dom:i}=n,r=window.tinymce.dom.RangeUtils.getCaretRangeFromPoint(e.clientX,e.clientY,n.getDoc()),o=e.dataTransfer&&e.dataTransfer.getData("bookstack/template");o&&(e.preventDefault(),window.$http.get(`/templates/${o}`).then(s=>{n.selection.setRng(r),n.undoManager.transact(()=>{n.execCommand("mceInsertContent",!1,s.data.html)})})),i.getParent(r.startContainer,".mceTemp")?e.preventDefault():ie&&(e.preventDefault(),n.undoManager.transact(()=>{n.selection.setRng(r),n.selection.setNode(ie),i.remove(ie)})),!e.isDefaultPrevented()&&ar&&(e.preventDefault(),n.undoManager.transact(()=>{let s=n.selection.getNode(),a=n.selection.getRng(),l=s.closest("body > *");a.startOffset>a.startContainer.length/2?l.after(ar):l.before(ar)})),e.isDefaultPrevented()||cu(n,t,e),ie=null}function uu(n,t){n.on("dragstart",()=>Qf(n)),n.on("drop",e=>tm(n,t,e)),n.on("paste",e=>cu(n,t,e))}function hu(n){return["undo redo","styles","bold italic underline forecolor backcolor formatoverflow","alignleft aligncenter alignright alignjustify","bullist numlist listoverflow",n.textDirection==="rtl"?"ltr rtl":"","link table imagemanager-insert insertoverflow","code about fullscreen"].filter(i=>!!i).join(" | ")}function em(n){n.ui.registry.addGroupToolbarButton("formatoverflow",{icon:"more-drawer",tooltip:"More",items:"strikethrough superscript subscript inlinecode removeformat"}),n.ui.registry.addGroupToolbarButton("listoverflow",{icon:"more-drawer",tooltip:"More",items:"tasklist outdent indent"}),n.ui.registry.addGroupToolbarButton("insertoverflow",{icon:"more-drawer",tooltip:"More",items:"customhr codeeditor drawio media details"})}function nm(n){n.ui.registry.addContextToolbar("linkcontexttoolbar",{predicate(t){return t.closest("a")!==null},position:"node",scope:"node",items:"link unlink openlink"})}function im(n){n.ui.registry.addContextToolbar("imagecontexttoolbar",{predicate(t){return t.closest("img")!==null},position:"node",scope:"node",items:"image"})}function du(n){em(n),nm(n),im(n)}var rm={"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 pu(n){for(let[t,e]of Object.entries(rm))n.ui.registry.addIcon(t,e)}function om(n){n.serializer.addNodeFilter("br",t=>{for(let e of t)if(e.parent&&e.parent.name==="code"){let i=window.tinymce.html.Node.create("#text");i.value=` +`).length;this.$refs.input.style.height=`${t*20+40}px`}async update(t){t.preventDefault();let e=this.showLoading();this.form.toggleAttribute("hidden",!0);let i={text:this.input.value,parent_id:this.parentId||null};try{let r=await window.$http.put(`/comment/${this.commentId}`,i),o=_t(r.data);this.container.replaceWith(o),window.$events.success(this.updatedText)}catch(r){console.error(r),window.$events.showValidationErrors(r),this.form.toggleAttribute("hidden",!1),e.remove()}}async delete(){this.showLoading(),await window.$http.delete(`/comment/${this.commentId}`),this.container.closest(".comment-branch").remove(),window.$events.success(this.deletedText),this.$emit("delete")}showLoading(){let t=ae();return t.classList.add("px-l"),this.container.append(t),t}};var Oi=class extends g{setup(){this.elem=this.$el,this.pageId=Number(this.$opts.pageId),this.container=this.$refs.commentContainer,this.commentCountBar=this.$refs.commentCountBar,this.commentsTitle=this.$refs.commentsTitle,this.addButtonContainer=this.$refs.addButtonContainer,this.replyToRow=this.$refs.replyToRow,this.formContainer=this.$refs.formContainer,this.form=this.$refs.form,this.formInput=this.$refs.formInput,this.formReplyLink=this.$refs.formReplyLink,this.addCommentButton=this.$refs.addCommentButton,this.hideFormButton=this.$refs.hideFormButton,this.removeReplyToButton=this.$refs.removeReplyToButton,this.createdText=this.$opts.createdText,this.countText=this.$opts.countText,this.parentId=null,this.formReplyText=this.formReplyLink?.textContent||"",this.setupListeners()}setupListeners(){this.elem.addEventListener("page-comment-delete",()=>{this.updateCount(),this.hideForm()}),this.elem.addEventListener("page-comment-reply",t=>{this.setReply(t.detail.id,t.detail.element)}),this.form&&(this.removeReplyToButton.addEventListener("click",this.removeReplyTo.bind(this)),this.hideFormButton.addEventListener("click",this.hideForm.bind(this)),this.addCommentButton.addEventListener("click",this.showForm.bind(this)),this.form.addEventListener("submit",this.saveComment.bind(this)))}saveComment(t){t.preventDefault(),t.stopPropagation();let e=ae();e.classList.add("px-l"),this.form.after(e),this.form.toggleAttribute("hidden",!0);let r={text:this.formInput.value,parent_id:this.parentId||null};window.$http.post(`/comment/${this.pageId}`,r).then(o=>{let s=_t(o.data);this.formContainer.after(s),window.$events.success(this.createdText),this.hideForm(),this.updateCount()}).catch(o=>{this.form.toggleAttribute("hidden",!1),window.$events.showValidationErrors(o)}),this.form.toggleAttribute("hidden",!1),e.remove()}updateCount(){let t=this.getCommentCount();this.commentsTitle.textContent=window.trans_plural(this.countText,t,{count:t})}resetForm(){this.formInput.value="",this.parentId=null,this.replyToRow.toggleAttribute("hidden",!0),this.container.append(this.formContainer)}showForm(){this.formContainer.toggleAttribute("hidden",!1),this.addButtonContainer.toggleAttribute("hidden",!0),this.formContainer.scrollIntoView({behavior:"smooth",block:"nearest"}),setTimeout(()=>{this.formInput.focus()},100)}hideForm(){this.resetForm(),this.formContainer.toggleAttribute("hidden",!0),this.getCommentCount()>0?this.elem.append(this.addButtonContainer):this.commentCountBar.append(this.addButtonContainer),this.addButtonContainer.toggleAttribute("hidden",!1)}getCommentCount(){return this.container.querySelectorAll('[component="page-comment"]').length}setReply(t,e){e.closest(".comment-branch").querySelector(".comment-branch-children").append(this.formContainer),this.showForm(),this.parentId=t,this.replyToRow.toggleAttribute("hidden",!1),this.formReplyLink.textContent=this.formReplyText.replace("1234",this.parentId),this.formReplyLink.href=`#comment${this.parentId}`}removeReplyTo(){this.parentId=null,this.replyToRow.toggleAttribute("hidden",!0),this.container.append(this.formContainer),this.showForm()}};function Uf(n,t){xr(`#page-navigation a[href="#${n}"]`,e=>{e.closest("li").classList.toggle("current-heading",t)})}function jf(n){for(let t of n){let e=t.intersectionRatio===1;Uf(t.target.id,e)}}function Vf(n){let t={rootMargin:"0px 0px 0px 0px",threshold:1},e=new IntersectionObserver(jf,t);for(let i of n)e.observe(i)}var Ri=class extends g{setup(){if(this.container=this.$el,this.pageId=this.$opts.pageId,window.importVersioned("code").then(e=>e.highlight()),this.setupNavHighlighting(),window.location.hash){let e=window.location.hash.replace(/%20/g," ").substring(1);this.goToText(e)}let t=document.querySelector(".sidebar-page-nav");t&&K(t,"a","click",(e,i)=>{e.preventDefault(),window.$components.first("tri-layout").showContent();let r=i.getAttribute("href").substr(1);this.goToText(r),window.history.pushState(null,null,`#${r}`)})}goToText(t){let e=document.getElementById(t);if(xr(".page-content [data-highlighted]",i=>{i.removeAttribute("data-highlighted"),i.style.backgroundColor=null}),e!==null)Cr(e);else{let i=ts(".page-content > div > *",t);i&&Cr(i)}}setupNavHighlighting(){let t=document.querySelector(".sidebar-page-nav"),e=document.querySelector(".page-content").querySelectorAll("h1, h2, h3, h4, h5, h6");e.length>0&&t!==null&&Vf(e)}};function ou(n){let t=new Date(n*1e3),e=t.getHours(),i=t.getMinutes();return`${(e>9?"":"0")+e}:${(i>9?"":"0")+i}`}var Ni=class extends g{setup(){this.draftsEnabled=this.$opts.draftsEnabled==="true",this.editorType=this.$opts.editorType,this.pageId=Number(this.$opts.pageId),this.isNewDraft=this.$opts.pageNewDraft==="true",this.hasDefaultTitle=this.$opts.hasDefaultTitle||!1,this.container=this.$el,this.titleElem=this.$refs.titleContainer.querySelector("input"),this.saveDraftButton=this.$refs.saveDraft,this.discardDraftButton=this.$refs.discardDraft,this.discardDraftWrap=this.$refs.discardDraftWrap,this.deleteDraftButton=this.$refs.deleteDraft,this.deleteDraftWrap=this.$refs.deleteDraftWrap,this.draftDisplay=this.$refs.draftDisplay,this.draftDisplayIcon=this.$refs.draftDisplayIcon,this.changelogInput=this.$refs.changelogInput,this.changelogDisplay=this.$refs.changelogDisplay,this.changeEditorButtons=this.$manyRefs.changeEditor||[],this.switchDialogContainer=this.$refs.switchDialog,this.deleteDraftDialogContainer=this.$refs.deleteDraftDialog,this.draftText=this.$opts.draftText,this.autosaveFailText=this.$opts.autosaveFailText,this.editingPageText=this.$opts.editingPageText,this.draftDiscardedText=this.$opts.draftDiscardedText,this.draftDeleteText=this.$opts.draftDeleteText,this.draftDeleteFailText=this.$opts.draftDeleteFailText,this.setChangelogText=this.$opts.setChangelogText,this.autoSave={interval:null,frequency:3e4,last:0,pendingChange:!1},this.shownWarningsCache=new Set,this.pageId!==0&&this.draftsEnabled&&window.setTimeout(()=>{this.startAutoSave()},1e3),this.draftDisplay.innerHTML=this.draftText,this.setupListeners(),this.setInitialFocus()}setupListeners(){window.$events.listen("editor-save-draft",this.saveDraft.bind(this)),window.$events.listen("editor-save-page",this.savePage.bind(this));let t=()=>{this.autoSave.pendingChange=!0};window.$events.listen("editor-html-change",t),window.$events.listen("editor-markdown-change",t),this.titleElem.addEventListener("input",t);let e=Nt(this.updateChangelogDisplay.bind(this),300,!1);this.changelogInput.addEventListener("input",e),R(this.saveDraftButton,this.saveDraft.bind(this)),R(this.discardDraftButton,this.discardDraft.bind(this)),R(this.deleteDraftButton,this.deleteDraft.bind(this)),R(this.changeEditorButtons,this.changeEditor.bind(this))}setInitialFocus(){if(this.hasDefaultTitle){this.titleElem.select();return}window.setTimeout(()=>{window.$events.emit("editor::focus","")},500)}startAutoSave(){this.autoSave.interval=window.setInterval(this.runAutoSave.bind(this),this.autoSave.frequency)}runAutoSave(){Date.now()-this.autoSave.last{this.draftDisplayIcon.classList.remove("visible")},2e3)}async discardDraft(t=!0){let e;try{e=await window.$http.get(`/ajax/page/${this.pageId}`)}catch(i){console.error(i);return}this.autoSave.interval&&window.clearInterval(this.autoSave.interval),this.draftDisplay.innerText=this.editingPageText,this.discardDraftWrap.toggleAttribute("hidden",!0),window.$events.emit("editor::replace",{html:e.data.html,markdown:e.data.markdown}),this.titleElem.value=e.data.name,window.setTimeout(()=>{this.startAutoSave()},1e3),t&&window.$events.success(this.draftDiscardedText)}async deleteDraft(){if(await window.$components.firstOnElement(this.deleteDraftDialogContainer,"confirm-dialog").show())try{let i=this.discardDraft(!1),r=window.$http.delete(`/page-revisions/user-drafts/${this.pageId}`);await Promise.all([i,r]),window.$events.success(this.draftDeleteText),this.deleteDraftWrap.toggleAttribute("hidden",!0)}catch(i){console.error(i),window.$events.error(this.draftDeleteFailText)}}updateChangelogDisplay(){let t=this.changelogInput.value.trim();t.length===0?t=this.setChangelogText:t.length>16&&(t=`${t.slice(0,16)}...`),this.changelogDisplay.innerText=t}async changeEditor(t){t.preventDefault();let e=t.target.closest("a").href,i=window.$components.firstOnElement(this.switchDialogContainer,"confirm-dialog"),[r,o]=await Promise.all([this.saveDraft(),i.show()]);r&&o&&(window.location=e)}getEditorComponent(){return window.$components.first("markdown-editor")||window.$components.first("wysiwyg-editor")}};function zi(n,t){n.toggleAttribute("hidden",!t)}var Hi=class extends g{setup(){this.input=this.$refs.input,this.resetButton=this.$refs.resetButton,this.selectButton=this.$refs.selectButton,this.display=this.$refs.display,this.defaultDisplay=this.$refs.defaultDisplay,this.buttonSep=this.$refs.buttonSeperator,this.selectorEndpoint=this.$opts.selectorEndpoint,this.value=this.input.value,this.setupListeners()}setupListeners(){this.selectButton.addEventListener("click",this.showPopup.bind(this)),this.display.parentElement.addEventListener("click",this.showPopup.bind(this)),this.display.addEventListener("click",t=>t.stopPropagation()),this.resetButton.addEventListener("click",()=>{this.setValue("","")})}showPopup(){window.$components.first("entity-selector-popup").show(e=>{this.setValue(e.id,e.name)},{initialValue:"",searchEndpoint:this.selectorEndpoint,entityTypes:"page",entityPermission:"view"})}setValue(t,e){this.value=t,this.input.value=t,this.controlView(e)}controlView(t){let e=this.value&&this.value!==0;if(zi(this.resetButton,e),zi(this.buttonSep,e),zi(this.defaultDisplay,!e),zi(this.display,e),e){let i=this.getAssetIdFromVal();this.display.textContent=`#${i}, ${t}`,this.display.href=window.baseUrl(`/link/${i}`)}}getAssetIdFromVal(){return Number(this.value)}};var Ui=class extends g{setup(){this.container=this.$el,this.cellSelector=this.$opts.cellSelector||"td,th",this.rowSelector=this.$opts.rowSelector||"tr";for(let t of this.$manyRefs.toggleAll||[])t.addEventListener("click",this.toggleAllClick.bind(this));for(let t of this.$manyRefs.toggleRow||[])t.addEventListener("click",this.toggleRowClick.bind(this));for(let t of this.$manyRefs.toggleColumn||[])t.addEventListener("click",this.toggleColumnClick.bind(this))}toggleAllClick(t){t.preventDefault(),this.toggleAllInElement(this.container)}toggleRowClick(t){t.preventDefault(),this.toggleAllInElement(t.target.closest(this.rowSelector))}toggleColumnClick(t){t.preventDefault();let e=t.target.closest(this.cellSelector),i=Array.from(e.parentElement.children).indexOf(e),r=this.container.querySelectorAll(this.rowSelector),o=[];for(let s of r){let a=s.children[i];a&&o.push(...a.querySelectorAll("input[type=checkbox]"))}this.toggleAllInputs(o)}toggleAllInElement(t){let e=t.querySelectorAll("input[type=checkbox]");this.toggleAllInputs(e)}toggleAllInputs(t){let e=t.length>0?t[0].checked:!1;for(let i of t)i.checked=!e,i.dispatchEvent(new Event("change"))}};var ji=class extends g{setup(){this.container=this.$el,this.pointer=this.$refs.pointer,this.linkInput=this.$refs.linkInput,this.linkButton=this.$refs.linkButton,this.includeInput=this.$refs.includeInput,this.includeButton=this.$refs.includeButton,this.sectionModeButton=this.$refs.sectionModeButton,this.modeToggles=this.$manyRefs.modeToggle,this.modeSections=this.$manyRefs.modeSection,this.pageId=this.$opts.pageId,this.showing=!1,this.isSelection=!1,this.setupListeners()}setupListeners(){this.includeButton.addEventListener("click",()=>Wr(this.includeInput.value)),this.linkButton.addEventListener("click",()=>Wr(this.linkInput.value)),R([this.includeInput,this.linkInput],e=>{e.target.select(),e.stopPropagation()}),ln(this.pointer,["click","focus"],e=>{e.stopPropagation()}),ln(document.body,["click","focus"],()=>{!this.showing||this.isSelection||this.hidePointer()}),Qo(this.pointer,this.hidePointer.bind(this));let t=document.querySelector(".page-content");ln(t,["mouseup","keyup"],e=>{e.stopPropagation();let i=e.target.closest('[id^="bkmrk"]');i&&window.getSelection().toString().length>0&&this.showPointerAtTarget(i,e.pageX,!1)}),R(this.sectionModeButton,this.enterSectionSelectMode.bind(this)),R(this.modeToggles,e=>{for(let i of this.modeSections){let r=!i.contains(e.target);i.toggleAttribute("hidden",!r)}this.modeToggles.find(i=>i!==e.target).focus()})}hidePointer(){this.pointer.style.display=null,this.showing=!1}showPointerAtTarget(t,e,i){this.updateForTarget(t),this.pointer.style.display="block";let r=t.getBoundingClientRect(),o=this.pointer.getBoundingClientRect(),a=Math.min(Math.max(e,r.left),r.right)-o.width/2,l=r.top-o.height-16;this.pointer.style.left=`${a}px`,this.pointer.style.top=`${l}px`,this.showing=!0,this.isSelection=!0,setTimeout(()=>{this.isSelection=!1},100);let c=()=>{this.hidePointer(),window.removeEventListener("scroll",c,{passive:!0})};t.parentElement.insertBefore(this.pointer,t),i||window.addEventListener("scroll",c,{passive:!0})}updateForTarget(t){let e=window.baseUrl(`/link/${this.pageId}#${t.id}`),i=`{{@${this.pageId}#${t.id}}}`;this.linkInput.value=e,this.includeInput.value=i;let r=this.pointer.querySelector("#pointer-edit");if(r&&t){let{editHref:o}=r.dataset,s=t.id,a=t.textContent&&t.textContent.substring(0,50);r.href=`${o}?content-id=${s}&content-text=${encodeURIComponent(a)}`}}enterSectionSelectMode(){let t=Array.from(document.querySelectorAll('.page-content [id^="bkmrk"]'));for(let e of t)e.setAttribute("tabindex","0");t[0].focus(),se(t,e=>{this.showPointerAtTarget(e.target,0,!0),this.pointer.focus()})}};var Vi=class extends g{setup(){this.container=this.$el,this.hideButtons=this.$manyRefs.hide||[],this.onkeyup=null,this.onHide=null,this.setupListeners()}setupListeners(){let t=null;this.container.addEventListener("mousedown",e=>{t=e.target}),this.container.addEventListener("click",e=>{e.target===this.container&&t===this.container&&this.hide()}),R(this.hideButtons,()=>this.hide())}hide(t=null){Is(this.container,120,t),this.onkeyup&&(window.removeEventListener("keyup",this.onkeyup),this.onkeyup=null),this.onHide&&this.onHide()}show(t=null,e=null){$s(this.container,120,t),this.onkeyup=i=>{i.key==="Escape"&&this.hide()},window.addEventListener("keyup",this.onkeyup),this.onHide=e}};var Wi=class extends g{setup(){this.container=this.$el,this.mode=this.$opts.mode,this.lightContainer=this.$refs.lightContainer,this.darkContainer=this.$refs.darkContainer,this.container.addEventListener("tabs-change",e=>{let r=e.detail.showing==="color-scheme-panel-light"?"light":"dark";this.handleModeChange(r)});let t=e=>{this.updateAppColorsFromInputs(),e.target.name.startsWith("setting-app-color")&&this.updateLightForInput(e.target)};this.container.addEventListener("change",t),this.container.addEventListener("input",t)}handleModeChange(t){this.mode=t;let e=t==="dark";document.documentElement.classList.toggle("dark-mode",e),this.updateAppColorsFromInputs()}updateAppColorsFromInputs(){let e=(this.mode==="dark"?this.darkContainer:this.lightContainer).querySelectorAll('input[type="color"]');for(let i of e){let r=i.name.split("-"),o=r.indexOf("color"),s=r.slice(1,o).join("-");s==="app"&&(s="primary");let a=`--color-${s}`;document.body.style.setProperty(a,i.value)}}updateLightForInput(t){let e=t.name.replace("-color","-color-light"),i=t.value,r=this.hexToRgb(i),o=`rgba(${[r.r,r.g,r.b,"0.15"].join(",")})`,s=this.container.querySelector(`input[name="${e}"][type="hidden"]`);s.value=o}hexToRgb(t){let e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return{r:e?parseInt(e[1],16):0,g:e?parseInt(e[2],16):0,b:e?parseInt(e[3],16):0}}};var Gi=class extends g{setup(){this.colorInput=this.$refs.input,this.resetButton=this.$refs.resetButton,this.defaultButton=this.$refs.defaultButton,this.currentColor=this.$opts.current,this.defaultColor=this.$opts.default,this.resetButton.addEventListener("click",()=>this.setValue(this.currentColor)),this.defaultButton.addEventListener("click",()=>this.setValue(this.defaultColor))}setValue(t){this.colorInput.value=t,this.colorInput.dispatchEvent(new Event("change",{bubbles:!0}))}};var Ki=class extends g{setup(){this.typeControl=this.$refs.typeControl,this.pagePickerContainer=this.$refs.pagePickerContainer,this.typeControl.addEventListener("change",this.controlPagePickerVisibility.bind(this)),this.controlPagePickerVisibility()}controlPagePickerVisibility(){let t=this.typeControl.value==="page";this.pagePickerContainer.style.display=t?"block":"none"}};var Gf={move_up(n){let t=n.parentNode,e=Array.from(t.children).indexOf(n),i=Math.max(e-1,0);t.insertBefore(n,t.children[i]||null)},move_down(n){let t=n.parentNode,e=Array.from(t.children).indexOf(n),i=Math.min(e+2,t.children.length);t.insertBefore(n,t.children[i]||null)},remove(n,t,e){e.appendChild(n)},add(n,t){t.appendChild(n)}},Zi=class extends g{setup(){this.elem=this.$el,this.input=this.$refs.input,this.shelfBookList=this.$refs.shelfBookList,this.allBookList=this.$refs.allBookList,this.bookSearchInput=this.$refs.bookSearch,this.sortButtonContainer=this.$refs.sortButtonContainer,this.lastSort=null,this.initSortable(),this.setupListeners()}initSortable(){let t=this.elem.querySelectorAll(".scroll-box");for(let e of t)new Yt(e,{group:"shelf-books",ghostClass:"primary-background-light",handle:".handle",animation:150,onSort:this.onChange.bind(this)})}setupListeners(){this.elem.addEventListener("click",t=>{let e=t.target.closest(".scroll-box-item button[data-action]");e&&this.sortItemActionClick(e)}),this.bookSearchInput.addEventListener("input",()=>{this.filterBooksByName(this.bookSearchInput.value)}),this.sortButtonContainer.addEventListener("click",t=>{let e=t.target.closest("button[data-sort]");e&&this.sortShelfBooks(e.dataset.sort)})}filterBooksByName(t){this.allBookList.style.height||(this.allBookList.style.height=`${this.allBookList.getBoundingClientRect().height}px`);let e=this.allBookList.children,i=t.trim().toLowerCase();for(let r of e){let o=!t||r.textContent.toLowerCase().includes(i);r.style.display=o?null:"none"}}sortItemActionClick(t){let e=t.closest(".scroll-box-item"),{action:i}=t.dataset,r=Gf[i];r(e,this.shelfBookList,this.allBookList),this.onChange()}onChange(){let t=Array.from(this.shelfBookList.querySelectorAll("[data-id]"));this.input.value=t.map(e=>e.getAttribute("data-id")).join(",")}sortShelfBooks(t){let e=Array.from(this.shelfBookList.children),i=t===this.lastSort;e.sort((r,o)=>{let s=r.dataset[t].toLowerCase(),a=o.dataset[t].toLowerCase();return i?a.localeCompare(s):s.localeCompare(a)});for(let r of e)this.shelfBookList.append(r);this.lastSort=this.lastSort===t?null:t,this.onChange()}};function Kf(n){let t={};for(let[e,i]of Object.entries(n))t[i]=e;return t}var Xi=class extends g{setup(){this.container=this.$el,this.mapById=JSON.parse(this.$opts.keyMap),this.mapByShortcut=Kf(this.mapById),this.hintsShowing=!1,this.hideHints=this.hideHints.bind(this),this.hintAbortController=null,this.setupListeners()}setupListeners(){window.addEventListener("keydown",t=>{if(!t.target.closest("input, select, textarea, .cm-editor")){if(t.key==="?"){this.hintsShowing?this.hideHints():this.showHints();return}this.handleShortcutPress(t)}})}handleShortcutPress(t){let i=[t.ctrlKey?"Ctrl":"",t.metaKey?"Cmd":"",t.key].filter(o=>!!o).join(" + "),r=this.mapByShortcut[i];r&&this.runShortcut(r)&&t.preventDefault()}runShortcut(t){let e=this.container.querySelector(`[data-shortcut="${t}"]`);return e?e.matches("input, textarea, select")?(e.focus(),!0):e.matches("a, button")?(e.click(),!0):e.matches("div[tabindex]")?(e.click(),e.focus(),!0):(console.error("Shortcut attempted to be ran for element type that does not have handling setup",e),!1):!1}showHints(){let t=document.createElement("div");t.classList.add("shortcut-container"),this.container.append(t);let e=this.container.querySelectorAll("[data-shortcut]"),i=new Set;for(let o of e){let s=o.getAttribute("data-shortcut");if(i.has(s))continue;let a=this.mapById[s];this.showHintLabel(o,a,t),i.add(s)}this.hintAbortController=new AbortController;let r=this.hintAbortController.signal;window.addEventListener("scroll",this.hideHints,{signal:r}),window.addEventListener("focus",this.hideHints,{signal:r}),window.addEventListener("blur",this.hideHints,{signal:r}),window.addEventListener("click",this.hideHints,{signal:r}),this.hintsShowing=!0}showHintLabel(t,e,i){let r=t.getBoundingClientRect(),o=document.createElement("div");o.classList.add("shortcut-hint"),o.textContent=e;let s=document.createElement("div");s.classList.add("shortcut-linkage"),s.style.left=`${r.x}px`,s.style.top=`${r.y}px`,s.style.width=`${r.width}px`,s.style.height=`${r.height}px`,i.append(o,s);let a=o.getBoundingClientRect();o.style.insetInlineStart=`${r.x+r.width-(a.width+6)}px`,o.style.insetBlockStart=`${r.y+(r.height-a.height)/2}px`}hideHints(){this.container.querySelector(".shortcut-container").remove(),this.hintAbortController?.abort(),this.hintsShowing=!1}};var Zf=["Control","Alt","Shift","Meta","Super"," ","+","Tab","Escape"],Yi=class extends g{setup(){this.input=this.$el,this.setupListeners()}setupListeners(){this.listenerRecordKey=this.listenerRecordKey.bind(this),this.input.addEventListener("focus",()=>{this.startListeningForInput()}),this.input.addEventListener("blur",()=>{this.stopListeningForInput()})}startListeningForInput(){this.input.addEventListener("keydown",this.listenerRecordKey)}listenerRecordKey(t){if(Zf.includes(t.key))return;let e=[t.ctrlKey?"Ctrl":"",t.metaKey?"Cmd":"",t.key];this.input.value=e.filter(i=>!!i).join(" + ")}stopListeningForInput(){this.input.removeEventListener("keydown",this.listenerRecordKey)}};var Ji=class extends g{setup(){this.container=this.$el,this.handleSelector=this.$opts.handleSelector;let t=new Yt(this.container,{handle:this.handleSelector,animation:150,onSort:()=>{this.$emit("sort",{ids:t.toArray()})},setData(e,i){let r=i.getAttribute("data-drag-content");if(r){let o=JSON.parse(r);for(let[s,a]of Object.entries(o))e.setData(s,a)}},revertOnSpill:!0,dropBubble:!0,dragoverBubble:!1})}};var Qi=class extends g{setup(){this.filter=this.$opts.filter,this.$el.addEventListener("change",t=>{if(this.filter&&!t.target.matches(this.filter))return;let e=this.$el.closest("form");e&&e.submit()})}};var tr=class extends g{setup(){this.container=this.$el,this.tabList=this.container.querySelector('[role="tablist"]'),this.tabs=Array.from(this.tabList.querySelectorAll('[role="tab"]')),this.panels=Array.from(this.container.querySelectorAll(':scope > [role="tabpanel"], :scope > * > [role="tabpanel"]')),this.activeUnder=this.$opts.activeUnder?Number(this.$opts.activeUnder):1e4,this.active=null,this.container.addEventListener("click",t=>{let e=t.target.closest('[role="tab"]');e&&this.tabs.includes(e)&&this.show(e.getAttribute("aria-controls"))}),window.addEventListener("resize",this.updateActiveState.bind(this),{passive:!0}),this.updateActiveState()}show(t){for(let e of this.panels)e.toggleAttribute("hidden",e.id!==t);for(let e of this.tabs){let r=e.getAttribute("aria-controls")===t;e.setAttribute("aria-selected",r?"true":"false")}this.$emit("change",{showing:t})}updateActiveState(){let t=window.innerWidth!e.hasAttribute("hidden"))||this.panels[0];this.show(t.id),this.tabList.toggleAttribute("hidden",!1)}deactivate(){for(let t of this.panels)t.removeAttribute("hidden");for(let t of this.tabs)t.setAttribute("aria-selected","false");this.tabList.toggleAttribute("hidden",!0)}};var er=class extends g{setup(){this.addRemoveComponentEl=this.$refs.addRemove,this.container=this.$el,this.rowSelector=this.$opts.rowSelector,this.setupListeners()}setupListeners(){this.container.addEventListener("input",t=>{let e=window.$components.firstOnElement(this.addRemoveComponentEl,"add-remove-rows");!this.hasEmptyRows()&&t.target.value&&e.add()})}hasEmptyRows(){return[...this.container.querySelectorAll(this.rowSelector)].find(i=>[...i.querySelectorAll("input")].filter(r=>r.value).length===0)!==void 0}};var nr=class extends g{setup(){this.container=this.$el,this.list=this.$refs.list,this.searchInput=this.$refs.searchInput,this.searchButton=this.$refs.searchButton,this.searchCancel=this.$refs.searchCancel,this.setupListeners()}setupListeners(){K(this.container,"[template-action]","click",this.handleTemplateActionClick.bind(this)),K(this.container,".pagination a","click",this.handlePaginationClick.bind(this)),K(this.container,".template-item-content","click",this.handleTemplateItemClick.bind(this)),K(this.container,".template-item","dragstart",this.handleTemplateItemDragStart.bind(this)),this.searchInput.addEventListener("keypress",t=>{t.key==="Enter"&&(t.preventDefault(),this.performSearch())}),this.searchButton.addEventListener("click",()=>this.performSearch()),this.searchCancel.addEventListener("click",()=>{this.searchInput.value="",this.performSearch()})}handleTemplateItemClick(t,e){let i=e.closest("[template-id]").getAttribute("template-id");this.insertTemplate(i,"replace")}handleTemplateItemDragStart(t,e){let i=e.closest("[template-id]").getAttribute("template-id");t.dataTransfer.setData("bookstack/template",i),t.dataTransfer.setData("text/plain",i)}handleTemplateActionClick(t,e){t.stopPropagation();let i=e.getAttribute("template-action"),r=e.closest("[template-id]").getAttribute("template-id");this.insertTemplate(r,i)}async insertTemplate(t,e="replace"){let i=await window.$http.get(`/templates/${t}`),r=`editor::${e}`;window.$events.emit(r,i.data)}async handlePaginationClick(t,e){t.preventDefault();let i=e.getAttribute("href"),r=await window.$http.get(i);this.list.innerHTML=r.data}async performSearch(){let t=this.searchInput.value,e=await window.$http.get("/templates",{search:t});this.searchCancel.style.display=t?"block":"none",this.list.innerHTML=e.data}};var ir=class extends g{setup(){this.input=this.$el.querySelector("input[type=hidden]"),this.checkbox=this.$el.querySelector("input[type=checkbox]"),this.checkbox.addEventListener("change",this.stateChange.bind(this))}stateChange(){this.input.value=this.checkbox.checked?"true":"false";let t=new Event("change");this.input.dispatchEvent(t)}};var rr=class extends g{setup(){this.container=this.$refs.container,this.tabs=this.$manyRefs.tab,this.lastLayoutType="none",this.onDestroy=null,this.scrollCache={content:0,info:0},this.lastTabShown="content",this.mobileTabClick=this.mobileTabClick.bind(this),this.updateLayout(),window.addEventListener("resize",()=>{this.updateLayout()},{passive:!0})}updateLayout(){let t="tablet";window.innerWidth<=1e3&&(t="mobile"),window.innerWidth>=1400&&(t="desktop"),t!==this.lastLayoutType&&(this.onDestroy&&(this.onDestroy(),this.onDestroy=null),t==="desktop"?this.setupDesktop():t==="mobile"&&this.setupMobile(),this.lastLayoutType=t)}setupMobile(){for(let t of this.tabs)t.addEventListener("click",this.mobileTabClick);this.onDestroy=()=>{for(let t of this.tabs)t.removeEventListener("click",this.mobileTabClick)}}setupDesktop(){}mobileTabClick(t){let{tab:e}=t.target.dataset;this.showTab(e)}showContent(){this.showTab("content",!1)}showTab(t,e=!0){this.scrollCache[this.lastTabShown]=document.documentElement.scrollTop;for(let r of this.tabs){let o=r.dataset.tab===t;r.setAttribute("aria-selected",o?"true":"false")}let i=t==="info";if(this.container.classList.toggle("show-info",i),e){let o=document.querySelector("header").getBoundingClientRect().bottom;document.documentElement.scrollTop=this.scrollCache[t]||o,setTimeout(()=>{document.documentElement.scrollTop=this.scrollCache[t]||o},50)}this.lastTabShown=t}};var or=class extends g{setup(){this.container=this.$el,this.input=this.$refs.input,this.userInfoContainer=this.$refs.userInfo,K(this.container,"a.dropdown-search-item","click",this.selectUser.bind(this))}selectUser(t,e){t.preventDefault(),this.input.value=e.getAttribute("data-id"),this.userInfoContainer.innerHTML=e.innerHTML,this.input.dispatchEvent(new Event("change",{bubbles:!0})),this.hide()}hide(){window.$components.firstOnElement(this.container,"dropdown").hide()}};var sr=class extends g{setup(){this.checkboxes=this.$el.querySelectorAll('input[type="checkbox"]'),this.allCheckbox=this.$el.querySelector('input[type="checkbox"][value="all"]'),this.$el.addEventListener("change",t=>{t.target.checked&&t.target===this.allCheckbox?this.deselectIndividualEvents():t.target.checked&&(this.allCheckbox.checked=!1)})}deselectIndividualEvents(){for(let t of this.checkboxes)t!==this.allCheckbox&&(t.checked=!1)}};function su(n){for(let t=1;t<5;t++)n.shortcuts.add(`meta+${t}`,"",["FormatBlock",!1,`h${t+1}`]);n.shortcuts.add("meta+5","",["FormatBlock",!1,"p"]),n.shortcuts.add("meta+d","",["FormatBlock",!1,"p"]),n.shortcuts.add("meta+6","",["FormatBlock",!1,"blockquote"]),n.shortcuts.add("meta+q","",["FormatBlock",!1,"blockquote"]),n.shortcuts.add("meta+7","",["codeeditor",!1,"pre"]),n.shortcuts.add("meta+e","",["codeeditor",!1,"pre"]),n.shortcuts.add("meta+8","",["FormatBlock",!1,"code"]),n.shortcuts.add("meta+shift+E","",["FormatBlock",!1,"code"]),n.shortcuts.add("meta+o","","InsertOrderedList"),n.shortcuts.add("meta+p","","InsertUnorderedList"),n.shortcuts.add("meta+S","",()=>{window.$events.emit("editor-save-draft")}),n.shortcuts.add("meta+13","",()=>{window.$events.emit("editor-save-page")}),n.shortcuts.add("meta+9","",()=>{let t=n.selection.getNode(),e=t?t.closest(".callout"):null,i=["info","success","warning","danger"],o=(i.findIndex(a=>e&&e.classList.contains(a))+1)%i.length,s=i[o];n.formatter.apply(`callout${s}`)}),n.shortcuts.add("meta+shift+K","",()=>{let t=window.$components.first("entity-selector-popup"),e=n.selection.getContent({format:"text"}).trim();t.show(i=>{n.selection.isCollapsed()?n.insertContent(n.dom.createHTML("a",{href:i.link},n.dom.encode(i.name))):n.formatter.apply("link",{href:i.link}),n.selection.collapse(!1),n.focus()},{initialValue:e,searchEndpoint:"/search/entity-selector",entityTypes:"page,book,chapter,bookshelf",entityPermission:"view"})})}function au(n){window.$events.listen("editor::replace",({html:t})=>{n.setContent(t)}),window.$events.listen("editor::append",({html:t})=>{let e=n.getContent()+t;n.setContent(e)}),window.$events.listen("editor::prepend",({html:t})=>{let e=t+n.getContent();n.setContent(e)}),window.$events.listen("editor::insert",({html:t})=>{n.insertContent(t)}),window.$events.listen("editor::focus",()=>{n.initialized&&n.focus()})}function Xf(n,t){let e=n.dom.get(encodeURIComponent(t).replace(/!/g,"%21"));e&&(e.scrollIntoView(),n.selection.select(e,!0),n.selection.collapse(!1),n.focus())}function lu(n){let e=new URL(window.location).searchParams.get("content-id");e&&Xf(n,e)}var ie,ar;function Yf(n){return n&&!!(n.textContent||n.innerText)}async function Jf(n,t){if(n===null||n.type.indexOf("image")!==0)throw new Error("Not an image file");let e=n.name||`image-${Date.now()}.png`,i=new FormData;return i.append("file",n,e),i.append("uploaded_to",t),(await window.$http.post(window.baseUrl("/images/gallery"),i)).data}function cu(n,t,e){let i=new Ft(e.clipboardData||e.dataTransfer);if(!i.hasItems()||i.containsTabularData())return;let r=i.getImages();for(let o of r){let s=`image-${Math.random().toString(16).slice(2)}`,a=window.baseUrl("/loading.gif");e.preventDefault(),setTimeout(()=>{n.insertContent(`

    `),Jf(o,t.pageId).then(l=>{let c=l.name.replace(/"/g,""),u=`${c}`,h=n.dom.create("a",{target:"_blank",href:l.url},u);n.dom.replace(h,s)}).catch(l=>{n.dom.remove(s),window.$events.error(l?.data?.message||t.translations.imageUploadErrorText),console.error(l)})},10)}}function Qf(n){let t=n.selection.getNode();t.nodeName==="IMG"&&(ie=n.dom.getParent(t,".mceTemp"),!ie&&t.parentNode.nodeName==="A"&&!Yf(t.parentNode)&&(ie=t.parentNode)),t.hasAttribute("contenteditable")&&t.getAttribute("contenteditable")==="false"&&(ar=t)}function tm(n,t,e){let{dom:i}=n,r=window.tinymce.dom.RangeUtils.getCaretRangeFromPoint(e.clientX,e.clientY,n.getDoc()),o=e.dataTransfer&&e.dataTransfer.getData("bookstack/template");o&&(e.preventDefault(),window.$http.get(`/templates/${o}`).then(s=>{n.selection.setRng(r),n.undoManager.transact(()=>{n.execCommand("mceInsertContent",!1,s.data.html)})})),i.getParent(r.startContainer,".mceTemp")?e.preventDefault():ie&&(e.preventDefault(),n.undoManager.transact(()=>{n.selection.setRng(r),n.selection.setNode(ie),i.remove(ie)})),!e.isDefaultPrevented()&&ar&&(e.preventDefault(),n.undoManager.transact(()=>{let s=n.selection.getNode(),a=n.selection.getRng(),l=s.closest("body > *");a.startOffset>a.startContainer.length/2?l.after(ar):l.before(ar)})),e.isDefaultPrevented()||cu(n,t,e),ie=null}function uu(n,t){n.on("dragstart",()=>Qf(n)),n.on("drop",e=>tm(n,t,e)),n.on("paste",e=>cu(n,t,e))}function hu(n){return["undo redo","styles","bold italic underline forecolor backcolor formatoverflow","alignleft aligncenter alignright alignjustify","bullist numlist listoverflow",n.textDirection==="rtl"?"ltr rtl":"","link table imagemanager-insert insertoverflow","code about fullscreen"].filter(i=>!!i).join(" | ")}function em(n){n.ui.registry.addGroupToolbarButton("formatoverflow",{icon:"more-drawer",tooltip:"More",items:"strikethrough superscript subscript inlinecode removeformat"}),n.ui.registry.addGroupToolbarButton("listoverflow",{icon:"more-drawer",tooltip:"More",items:"tasklist outdent indent"}),n.ui.registry.addGroupToolbarButton("insertoverflow",{icon:"more-drawer",tooltip:"More",items:"customhr codeeditor drawio media details"})}function nm(n){n.ui.registry.addContextToolbar("linkcontexttoolbar",{predicate(t){return t.closest("a")!==null},position:"node",scope:"node",items:"link unlink openlink"})}function im(n){n.ui.registry.addContextToolbar("imagecontexttoolbar",{predicate(t){return t.closest("img")!==null},position:"node",scope:"node",items:"image"})}function du(n){em(n),nm(n),im(n)}var rm={"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 pu(n){for(let[t,e]of Object.entries(rm))n.ui.registry.addIcon(t,e)}function om(n){n.serializer.addNodeFilter("br",t=>{for(let e of t)if(e.parent&&e.parent.name==="code"){let i=window.tinymce.html.Node.create("#text");i.value=` `,e.replace(i)}})}function sm(n){n.parser.addNodeFilter("div",t=>{for(let e of t){let i=e.attr("id")||"",r=e.attr("class")||"";(i==="pointer"||r.includes("pointer"))&&e.remove()}})}function fu(n){om(n),sm(n)}function mu(n){return n.tagName.toLowerCase()==="code-block"}function bu(n,t,e,i){let r=window.$components.first("code-editor"),o=n.selection.getBookmark();r.open(t,e,(s,a)=>{i(s,a),n.focus(),n.selection.moveToBookmark(o)},()=>{n.focus(),n.selection.moveToBookmark(o)})}function gu(n,t){bu(n,t.getContent(),t.getLanguage(),(e,i)=>{t.setContent(e,i)})}function am(n){let t=n.getDoc(),e=t.defaultView;class i extends e.HTMLElement{constructor(){super();at(this,"editor",null);this.attachShadow({mode:"open"});let s=document.head.querySelectorAll('link[rel="stylesheet"]:not([media="print"]),style'),a=Array.from(s).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 s=c=>(c.split(" ").filter(h=>h.startsWith("language-"))[0]||"").replace("language-",""),a=this.querySelector("code"),l=this.querySelector("pre");return s(l.className)||a&&s(a.className)||""}setContent(s,a){this.editor&&(this.editor.setContent(s),this.editor.setMode(a,s));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=s,c.className=`language-${a}`}getContent(){let s=this.querySelector("code")||this.querySelector("pre"),a=document.createElement("pre");a.innerHTML=s.innerHTML.replace(/\ufeff/g,"");let l=a.querySelectorAll("br");for(let c of l)c.replaceWith(` `);return a.textContent}connectedCallback(){let s=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 u=this.shadowRoot.querySelector(".CodeMirrorContainer"),h=d=>{this.editor=d.wysiwygView(u,this.shadowRoot,a,this.getLanguage()),setTimeout(()=>{this.style.height=null},12)};window.importVersioned("code").then(d=>{let f=Date.now()-s<20?20:0;setTimeout(()=>h(d),f)})}cleanChildContent(){let s=this.querySelector("pre");if(s)for(let a of s.childNodes)a.nodeName==="#text"&&a.textContent==="\uFEFF"&&a.remove()}}e.customElements.define("code-block",i)}function lm(n){n.ui.registry.addIcon("codeblock",''),n.ui.registry.addButton("codeeditor",{tooltip:"Insert code block",icon:"codeblock",onAction(){n.execCommand("codeeditor")}}),n.ui.registry.addButton("editcodeeditor",{tooltip:"Edit code block",icon:"edit-block",onAction(){n.execCommand("codeeditor")}}),n.addCommand("codeeditor",()=>{let t=n.selection.getNode(),e=t.ownerDocument;if(mu(t))gu(n,t);else{let i=n.selection.getContent({format:"text"});bu(n,i,"",(r,o)=>{let s=e.createElement("pre"),a=e.createElement("code");a.classList.add(`language-${o}`),a.innerText=r,s.append(a),n.insertContent(s.outerHTML)})}}),n.on("dblclick",()=>{let t=n.selection.getNode();mu(t)&&gu(n,t)}),n.on("PreInit",()=>{n.parser.addNodeFilter("pre",t=>{for(let e of t){let i=window.tinymce.html.Node.create("code-block",{contenteditable:"false"}),r=e.getAll("span");for(let o of r)o.unwrap();e.attr("style",null),e.wrap(i)}}),n.parser.addNodeFilter("code-block",t=>{for(let e of t)e.attr("contenteditable","false")}),n.serializer.addNodeFilter("code-block",t=>{for(let e of t)e.unwrap()})}),n.ui.registry.addContextToolbar("codeeditor",{predicate(t){return t.nodeName.toLowerCase()==="code-block"},items:"editcodeeditor",position:"node",scope:"node"}),n.on("PreInit",()=>{am(n)})}function vu(){return lm}var pt=null,oe=null,re={};function Ho(n){return n.hasAttribute("drawio-diagram")}function cm(n,t=null){pt=n,oe=t,window.$components.first("image-manager").show(i=>{if(t){let r=t.querySelector("img");pt.undoManager.transact(()=>{pt.dom.setAttrib(r,"src",i.url),pt.dom.setAttrib(t,"drawio-diagram",i.id)})}else{let r=`
    `;pt.insertContent(r)}},"drawio")}async function um(n){let t=window.baseUrl("/loading.gif"),e=o=>{o.status===413?window.$events.emit("error",re.translations.serverUploadLimitText):window.$events.emit("error",re.translations.imageUploadErrorText),console.error(o)};if(oe){ee();let o=oe.querySelector("img");try{let s=await Oo(n,re.pageId);pt.undoManager.transact(()=>{pt.dom.setAttrib(o,"src",s.url),pt.dom.setAttrib(oe,"drawio-diagram",s.id)})}catch(s){throw e(s),new Error(`Failed to save image with error: ${s}`)}return}await is(5);let i=`drawing-${Math.random().toString(16).slice(2)}`,r=`drawing-wrap-${Math.random().toString(16).slice(2)}`;pt.insertContent(`
    `),ee();try{let o=await Oo(n,re.pageId);pt.undoManager.transact(()=>{pt.dom.setAttrib(i,"src",o.url),pt.dom.setAttrib(r,"drawio-diagram",o.id)})}catch(o){throw pt.dom.remove(r),e(o),new Error(`Failed to save image with error: ${o}`)}}function hm(){if(!oe)return Promise.resolve("");let n=oe.getAttribute("drawio-diagram");return _i(n)}function wu(n,t=null){pt=n,oe=t,tn(re.drawioUrl,hm,um)}function dm(n){n.addCommand("drawio",()=>{let t=n.selection.getNode();wu(n,Ho(t)?t:null)}),n.ui.registry.addIcon("diagram",``),n.ui.registry.addSplitButton("drawio",{tooltip:"Insert/edit drawing",icon:"diagram",onAction(){n.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 i=n.selection.getNode();cm(n,Ho(i)?i:null)}}}),n.on("dblclick",()=>{let t=n.selection.getNode();Ho(t)&&wu(n,t)}),n.on("SetContent",()=>{let t=n.dom.select("body > div[drawio-diagram]");t.length&&n.undoManager.transact(()=>{for(let e of t)e.setAttribute("contenteditable","false")})})}function yu(n){return re=n,dm}function pm(n){n.addCommand("InsertHorizontalRule",()=>{let t=document.createElement("hr"),e=n.selection.getNode(),{parentNode:i}=e;i.insertBefore(t,e)}),n.ui.registry.addButton("customhr",{icon:"horizontal-rule",tooltip:"Insert horizontal line",onAction(){n.execCommand("InsertHorizontalRule")}})}function xu(){return pm}function fm(n){n.ui.registry.addButton("imagemanager-insert",{title:"Insert image",icon:"image",tooltip:"Insert image",onAction(){window.$components.first("image-manager").show(e=>{let i=e.thumbs?.display||e.url,r=``;r+=`${e.name}`,r+="",n.execCommand("mceInsertContent",!1,r)},"gallery")}})}function ku(){return fm}function mm(n){let t={title:"About the WYSIWYG Editor",url:window.baseUrl("/help/wysiwyg")};n.ui.registry.addButton("about",{icon:"help",tooltip:"About the editor",onAction(){window.tinymce.activeEditor.windowManager.openUrl(t)}})}function Cu(){return mm}var Eu=["p","h1","h2","h3","h4","h5","h6","div","blockquote","pre","code-block","details","ul","ol","table","hr"];function lr(n){return n.selection.getNode().closest("details")}function gm(n,t){let e=lr(n);e&&n.undoManager.transact(()=>{let i=e.querySelector("summary");i||(i=document.createElement("summary"),e.prepend(i)),i.textContent=t})}function bm(n){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();gm(n,e),t.close()}}}function vm(n){let t=n.querySelector("summary");return t?t.textContent:""}function _u(n){let t=lr(n);n.windowManager.open(bm(n)).setData({summary:vm(t)})}function wm(n){let t=n.selection.getNode().closest("details"),e=n.selection.getBookmark();if(t){let i=t.querySelectorAll("details > *:not(summary, doc-root), doc-root > *");n.undoManager.transact(()=>{for(let r of i)t.parentNode.insertBefore(r,t);t.remove()})}n.focus(),n.selection.moveToBookmark(e)}function Uo(n){n.attr("contenteditable",null);let t=!1;for(let e of n.children())e.name==="doc-root"&&(e.unwrap(),t=!0);t&&Uo(n)}function ym(n){Uo(n),n.attr("contenteditable","false");let t=window.tinymce.html.Node.create("doc-root",{contenteditable:"true"}),e=null;for(let i of n.children()){if(i.name==="summary")continue;Eu.includes(i.name)?(t.append(i),e=null):(e||(e=window.tinymce.html.Node.create("p"),t.append(e)),e.append(i))}n.append(t)}function xm(n){n.parser.addNodeFilter("details",t=>{for(let e of t)ym(e)}),n.serializer.addNodeFilter("details",t=>{for(let e of t)Uo(e),e.attr("open",null)}),n.serializer.addNodeFilter("doc-root",t=>{for(let e of t)e.unwrap()})}function km(n){n.ui.registry.addIcon("details",''),n.ui.registry.addIcon("togglefold",''),n.ui.registry.addIcon("togglelabel",''),n.ui.registry.addButton("details",{icon:"details",tooltip:"Insert collapsible block",onAction(){n.execCommand("InsertDetailsBlock")}}),n.ui.registry.addButton("removedetails",{icon:"table-delete-table",tooltip:"Unwrap",onAction(){wm(n)}}),n.ui.registry.addButton("editdetials",{icon:"togglelabel",tooltip:"Edit label",onAction(){_u(n)}}),n.on("dblclick",t=>{!lr(n)||t.target.closest("doc-root")||_u(n)}),n.ui.registry.addButton("toggledetails",{icon:"togglefold",tooltip:"Toggle open/closed",onAction(){lr(n).toggleAttribute("open"),n.focus()}}),n.addCommand("InsertDetailsBlock",()=>{let t=n.selection.getContent({format:"html"}),e=document.createElement("details"),i=document.createElement("summary"),r=`details-${Date.now()}`;e.setAttribute("data-id",r),e.appendChild(i),t||(t="


    "),e.innerHTML+=t,n.insertContent(e.outerHTML),n.focus();let o=n.dom.select(`[data-id="${r}"]`)[0]||null;if(o){let s=o.querySelector("doc-root > *");s&&s.focus(),o.removeAttribute("data-id")}}),n.ui.registry.addContextToolbar("details",{predicate(t){return t.nodeName.toLowerCase()==="details"},items:"editdetials toggledetails removedetails",position:"node",scope:"node"}),n.on("PreInit",()=>{xm(n)})}function Su(){return km}function Cm(n){let t=n.closest("li");return t&&t.parentNode.nodeName==="UL"&&t.classList.contains("task-list-item")}function Em(n,t,e){let i=t.getBoundingClientRect();n.clientX<=i.right&&n.clientX>=i.left&&n.clientY>=i.top&&n.clientY<=i.bottom||e.undoManager.transact(()=>{t.hasAttribute("checked")?t.removeAttribute("checked"):t.setAttribute("checked","checked")})}function _m(n){n.attr("class","task-list-item");for(let t of n.children())t.name==="input"&&(t.attr("checked")==="checked"&&n.attr("checked","checked"),t.remove())}function Sm(n){let t=n.attr("checked")==="checked";n.attr("checked",null);let e={type:"checkbox",disabled:"disabled"};t&&(e.checked="checked");let i=window.tinymce.html.Node.create("input",e);i.shortEnded=!0,n.firstChild?n.insert(i,n.firstChild,!0):n.append(i)}function Am(n){n.ui.registry.addIcon("tasklist",''),n.ui.registry.addToggleButton("tasklist",{tooltip:"Task list",icon:"tasklist",active:!1,onAction(i){i.isActive()?n.execCommand("RemoveList"):n.execCommand("InsertUnorderedList",null,{"list-item-attributes":{class:"task-list-item"},"list-style-type":"tasklist"})},onSetup(i){n.on("NodeChange",r=>{let o=r.parents.find(a=>a.nodeName==="LI"),s=o&&o.classList.contains("task-list-item");i.setActive(!!s)})}});let t=n.ui.registry.getAll().buttons.bullist;t.onSetup=function(r){n.on("NodeChange",o=>{let s=o.parents.find(c=>c.nodeName==="LI"),a=s&&s.classList.contains("task-list-item"),l=s&&s.parentNode.nodeName==="UL";r.setActive(!!(l&&!a))})},t.onAction=function(){Cm(n.selection.getNode())&&n.execCommand("InsertOrderedList",null,{"list-item-attributes":{class:null}}),n.execCommand("InsertUnorderedList",null,{"list-item-attributes":{class:null}})};let e=n.ui.registry.getAll().buttons.numlist;e.onAction=function(){n.execCommand("InsertOrderedList",null,{"list-item-attributes":{class:null}})},n.on("PreInit",()=>{n.parser.addNodeFilter("li",i=>{for(let r of i)r.attributes.map.class==="task-list-item"&&_m(r)}),n.serializer.addNodeFilter("li",i=>{for(let r of i)r.attributes.map.class==="task-list-item"&&Sm(r)})}),n.on("click",i=>{let r=i.target;r.nodeName==="LI"&&r.classList.contains("task-list-item")&&(Em(i,r,n),i.preventDefault())})}function Au(){return Am}function Du(n){function t(e){let i=e.querySelector("iframe, video");if(!i)return;let r=[...i.classList.values()].filter(s=>s.startsWith("align-")),o=[...e.classList.values()].filter(s=>s.startsWith("align-"));e.classList.remove(...o),e.classList.add(...r)}n.on("SetContent",()=>{let e=n.dom.select("span.mce-preview-object");for(let i of e)t(i)}),n.on("FormatApply",e=>{let i=e.format.startsWith("align");if(!e.node||!e.node.matches(".mce-preview-object"))return;let r=e.node.querySelector("iframe, video");if(i&&r){let o=(n.formatter.get(e.format)[0]?.classes||[])[0],s=!r.classList.contains(o),l=(e.node.getAttribute("data-mce-p-class")||"").split(" ").filter(u=>!u.startsWith("align-"));s&&l.push(o);let c=l.join(" ");e.node.setAttribute("data-mce-p-class",c),r.setAttribute("class",c),n.formatter.apply(e.format,{},r),t(e.node)}})}var Dm=[{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"}]}],Lm={alignleft:{selector:"p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img,iframe,video,span",classes:"align-left"},aligncenter:{selector:"p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img,iframe,video,span",classes:"align-center"},alignright:{selector:"p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img,iframe,video,span",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"}}},Tm=["#BFEDD2","","#FBEEB8","","#F8CAC6","","#ECCAFA","","#C2E0F4","","#2DC26B","","#F1C40F","","#E03E2D","","#B96AD9","","#3598DB","","#169179","","#E67E23","","#BA372A","","#843FA1","","#236FA1","","#ECF0F1","","#CED4D9","","#95A5A6","","#7E8C8D","","#34495E","","#000000","","#ffffff",""];function Lu(n,t,e){if(e.filetype==="file"){let i=window.$components.first("entity-selector-popup"),r=this.selection.getContent({format:"text"}).trim();i.show(o=>{n(o.link,{text:o.name,title:o.name})},r,{searchEndpoint:"/search/entity-selector",entityTypes:"page,book,chapter,bookshelf",entityPermission:"view"})}e.filetype==="image"&&window.$components.first("image-manager").show(r=>{n(r.url,{alt:r.name})},"gallery")}function $m(n){let t=["image","table","link","autolink","fullscreen","code","customhr","autosave","lists","codeeditor","media","imagemanager","about","details","tasklist",n.textDirection==="rtl"?"directionality":""];return window.tinymce.PluginManager.add("codeeditor",vu()),window.tinymce.PluginManager.add("customhr",xu()),window.tinymce.PluginManager.add("imagemanager",ku()),window.tinymce.PluginManager.add("about",Cu()),window.tinymce.PluginManager.add("details",Su()),window.tinymce.PluginManager.add("tasklist",Au()),n.drawioUrl&&(window.tinymce.PluginManager.add("drawio",yu(n)),t.push("drawio")),t.filter(e=>!!e)}function Tu(){let n=document.head.innerHTML.split(` +`).length*19.2+18+24;this.style.height=`${c}px`;let u=this.shadowRoot.querySelector(".CodeMirrorContainer"),h=d=>{this.editor=d.wysiwygView(u,this.shadowRoot,a,this.getLanguage()),setTimeout(()=>{this.style.height=null},12)};window.importVersioned("code").then(d=>{let f=Date.now()-s<20?20:0;setTimeout(()=>h(d),f)})}cleanChildContent(){let s=this.querySelector("pre");if(s)for(let a of s.childNodes)a.nodeName==="#text"&&a.textContent==="\uFEFF"&&a.remove()}}e.customElements.define("code-block",i)}function lm(n){n.ui.registry.addIcon("codeblock",''),n.ui.registry.addButton("codeeditor",{tooltip:"Insert code block",icon:"codeblock",onAction(){n.execCommand("codeeditor")}}),n.ui.registry.addButton("editcodeeditor",{tooltip:"Edit code block",icon:"edit-block",onAction(){n.execCommand("codeeditor")}}),n.addCommand("codeeditor",()=>{let t=n.selection.getNode(),e=t.ownerDocument;if(mu(t))gu(n,t);else{let i=n.selection.getContent({format:"text"});bu(n,i,"",(r,o)=>{let s=e.createElement("pre"),a=e.createElement("code");a.classList.add(`language-${o}`),a.innerText=r,s.append(a),n.insertContent(s.outerHTML)})}}),n.on("dblclick",()=>{let t=n.selection.getNode();mu(t)&&gu(n,t)}),n.on("PreInit",()=>{n.parser.addNodeFilter("pre",t=>{for(let e of t){let i=window.tinymce.html.Node.create("code-block",{contenteditable:"false"}),r=e.getAll("span");for(let o of r)o.unwrap();e.attr("style",null),e.wrap(i)}}),n.parser.addNodeFilter("code-block",t=>{for(let e of t)e.attr("contenteditable","false")}),n.serializer.addNodeFilter("code-block",t=>{for(let e of t)e.unwrap()})}),n.ui.registry.addContextToolbar("codeeditor",{predicate(t){return t.nodeName.toLowerCase()==="code-block"},items:"editcodeeditor",position:"node",scope:"node"}),n.on("PreInit",()=>{am(n)})}function vu(){return lm}var pt=null,oe=null,re={};function Ho(n){return n.hasAttribute("drawio-diagram")}function cm(n,t=null){pt=n,oe=t,window.$components.first("image-manager").show(i=>{if(t){let r=t.querySelector("img");pt.undoManager.transact(()=>{pt.dom.setAttrib(r,"src",i.url),pt.dom.setAttrib(t,"drawio-diagram",i.id)})}else{let r=`
    `;pt.insertContent(r)}},"drawio")}async function um(n){let t=window.baseUrl("/loading.gif"),e=o=>{o.status===413?window.$events.emit("error",re.translations.serverUploadLimitText):window.$events.emit("error",re.translations.imageUploadErrorText),console.error(o)};if(oe){ee();let o=oe.querySelector("img");try{let s=await Oo(n,re.pageId);pt.undoManager.transact(()=>{pt.dom.setAttrib(o,"src",s.url),pt.dom.setAttrib(oe,"drawio-diagram",s.id)})}catch(s){throw e(s),new Error(`Failed to save image with error: ${s}`)}return}await is(5);let i=`drawing-${Math.random().toString(16).slice(2)}`,r=`drawing-wrap-${Math.random().toString(16).slice(2)}`;pt.insertContent(`
    `),ee();try{let o=await Oo(n,re.pageId);pt.undoManager.transact(()=>{pt.dom.setAttrib(i,"src",o.url),pt.dom.setAttrib(r,"drawio-diagram",o.id)})}catch(o){throw pt.dom.remove(r),e(o),new Error(`Failed to save image with error: ${o}`)}}function hm(){if(!oe)return Promise.resolve("");let n=oe.getAttribute("drawio-diagram");return _i(n)}function wu(n,t=null){pt=n,oe=t,tn(re.drawioUrl,hm,um)}function dm(n){n.addCommand("drawio",()=>{let t=n.selection.getNode();wu(n,Ho(t)?t:null)}),n.ui.registry.addIcon("diagram",``),n.ui.registry.addSplitButton("drawio",{tooltip:"Insert/edit drawing",icon:"diagram",onAction(){n.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 i=n.selection.getNode();cm(n,Ho(i)?i:null)}}}),n.on("dblclick",()=>{let t=n.selection.getNode();Ho(t)&&wu(n,t)}),n.on("SetContent",()=>{let t=n.dom.select("body > div[drawio-diagram]");t.length&&n.undoManager.transact(()=>{for(let e of t)e.setAttribute("contenteditable","false")})})}function yu(n){return re=n,dm}function pm(n){n.addCommand("InsertHorizontalRule",()=>{let t=document.createElement("hr"),e=n.selection.getNode(),{parentNode:i}=e;i.insertBefore(t,e)}),n.ui.registry.addButton("customhr",{icon:"horizontal-rule",tooltip:"Insert horizontal line",onAction(){n.execCommand("InsertHorizontalRule")}})}function xu(){return pm}function fm(n){n.ui.registry.addButton("imagemanager-insert",{title:"Insert image",icon:"image",tooltip:"Insert image",onAction(){window.$components.first("image-manager").show(e=>{let i=e.thumbs?.display||e.url,r=``;r+=`${e.name}`,r+="",n.execCommand("mceInsertContent",!1,r)},"gallery")}})}function ku(){return fm}function mm(n){let t={title:"About the WYSIWYG Editor",url:window.baseUrl("/help/wysiwyg")};n.ui.registry.addButton("about",{icon:"help",tooltip:"About the editor",onAction(){window.tinymce.activeEditor.windowManager.openUrl(t)}})}function Cu(){return mm}var Eu=["p","h1","h2","h3","h4","h5","h6","div","blockquote","pre","code-block","details","ul","ol","table","hr"];function lr(n){return n.selection.getNode().closest("details")}function gm(n,t){let e=lr(n);e&&n.undoManager.transact(()=>{let i=e.querySelector("summary");i||(i=document.createElement("summary"),e.prepend(i)),i.textContent=t})}function bm(n){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();gm(n,e),t.close()}}}function vm(n){let t=n.querySelector("summary");return t?t.textContent:""}function _u(n){let t=lr(n);n.windowManager.open(bm(n)).setData({summary:vm(t)})}function wm(n){let t=n.selection.getNode().closest("details"),e=n.selection.getBookmark();if(t){let i=t.querySelectorAll("details > *:not(summary, doc-root), doc-root > *");n.undoManager.transact(()=>{for(let r of i)t.parentNode.insertBefore(r,t);t.remove()})}n.focus(),n.selection.moveToBookmark(e)}function Uo(n){n.attr("contenteditable",null);let t=!1;for(let e of n.children())e.name==="doc-root"&&(e.unwrap(),t=!0);t&&Uo(n)}function ym(n){Uo(n),n.attr("contenteditable","false");let t=window.tinymce.html.Node.create("doc-root",{contenteditable:"true"}),e=null;for(let i of n.children()){if(i.name==="summary")continue;Eu.includes(i.name)?(t.append(i),e=null):(e||(e=window.tinymce.html.Node.create("p"),t.append(e)),e.append(i))}n.append(t)}function xm(n){n.parser.addNodeFilter("details",t=>{for(let e of t)ym(e)}),n.serializer.addNodeFilter("details",t=>{for(let e of t)Uo(e),e.attr("open",null)}),n.serializer.addNodeFilter("doc-root",t=>{for(let e of t)e.unwrap()})}function km(n){n.ui.registry.addIcon("details",''),n.ui.registry.addIcon("togglefold",''),n.ui.registry.addIcon("togglelabel",''),n.ui.registry.addButton("details",{icon:"details",tooltip:"Insert collapsible block",onAction(){n.execCommand("InsertDetailsBlock")}}),n.ui.registry.addButton("removedetails",{icon:"table-delete-table",tooltip:"Unwrap",onAction(){wm(n)}}),n.ui.registry.addButton("editdetials",{icon:"togglelabel",tooltip:"Edit label",onAction(){_u(n)}}),n.on("dblclick",t=>{!lr(n)||t.target.closest("doc-root")||_u(n)}),n.ui.registry.addButton("toggledetails",{icon:"togglefold",tooltip:"Toggle open/closed",onAction(){lr(n).toggleAttribute("open"),n.focus()}}),n.addCommand("InsertDetailsBlock",()=>{let t=n.selection.getContent({format:"html"}),e=document.createElement("details"),i=document.createElement("summary"),r=`details-${Date.now()}`;e.setAttribute("data-id",r),e.appendChild(i),t||(t="


    "),e.innerHTML+=t,n.insertContent(e.outerHTML),n.focus();let o=n.dom.select(`[data-id="${r}"]`)[0]||null;if(o){let s=o.querySelector("doc-root > *");s&&s.focus(),o.removeAttribute("data-id")}}),n.ui.registry.addContextToolbar("details",{predicate(t){return t.nodeName.toLowerCase()==="details"},items:"editdetials toggledetails removedetails",position:"node",scope:"node"}),n.on("PreInit",()=>{xm(n)})}function Su(){return km}function Cm(n){let t=n.closest("li");return t&&t.parentNode.nodeName==="UL"&&t.classList.contains("task-list-item")}function Em(n,t,e){let i=t.getBoundingClientRect();n.clientX<=i.right&&n.clientX>=i.left&&n.clientY>=i.top&&n.clientY<=i.bottom||e.undoManager.transact(()=>{t.hasAttribute("checked")?t.removeAttribute("checked"):t.setAttribute("checked","checked")})}function _m(n){n.attr("class","task-list-item");for(let t of n.children())t.name==="input"&&(t.attr("checked")==="checked"&&n.attr("checked","checked"),t.remove())}function Sm(n){let t=n.attr("checked")==="checked";n.attr("checked",null);let e={type:"checkbox",disabled:"disabled"};t&&(e.checked="checked");let i=window.tinymce.html.Node.create("input",e);i.shortEnded=!0,n.firstChild?n.insert(i,n.firstChild,!0):n.append(i)}function Am(n){n.ui.registry.addIcon("tasklist",''),n.ui.registry.addToggleButton("tasklist",{tooltip:"Task list",icon:"tasklist",active:!1,onAction(i){i.isActive()?n.execCommand("RemoveList"):n.execCommand("InsertUnorderedList",null,{"list-item-attributes":{class:"task-list-item"},"list-style-type":"tasklist"})},onSetup(i){n.on("NodeChange",r=>{let o=r.parents.find(a=>a.nodeName==="LI"),s=o&&o.classList.contains("task-list-item");i.setActive(!!s)})}});let t=n.ui.registry.getAll().buttons.bullist;t.onSetup=function(r){n.on("NodeChange",o=>{let s=o.parents.find(c=>c.nodeName==="LI"),a=s&&s.classList.contains("task-list-item"),l=s&&s.parentNode.nodeName==="UL";r.setActive(!!(l&&!a))})},t.onAction=function(){Cm(n.selection.getNode())&&n.execCommand("InsertOrderedList",null,{"list-item-attributes":{class:null}}),n.execCommand("InsertUnorderedList",null,{"list-item-attributes":{class:null}})};let e=n.ui.registry.getAll().buttons.numlist;e.onAction=function(){n.execCommand("InsertOrderedList",null,{"list-item-attributes":{class:null}})},n.on("PreInit",()=>{n.parser.addNodeFilter("li",i=>{for(let r of i)r.attributes.map.class==="task-list-item"&&_m(r)}),n.serializer.addNodeFilter("li",i=>{for(let r of i)r.attributes.map.class==="task-list-item"&&Sm(r)})}),n.on("click",i=>{let r=i.target;r.nodeName==="LI"&&r.classList.contains("task-list-item")&&(Em(i,r,n),i.preventDefault())})}function Au(){return Am}function Du(n){function t(e){let i=e.querySelector("iframe, video");if(!i)return;let r=[...i.classList.values()].filter(s=>s.startsWith("align-")),o=[...e.classList.values()].filter(s=>s.startsWith("align-"));e.classList.remove(...o),e.classList.add(...r)}n.on("SetContent",()=>{let e=n.dom.select("span.mce-preview-object");for(let i of e)t(i)}),n.on("FormatApply",e=>{let i=e.format.startsWith("align");if(!e.node||!e.node.matches(".mce-preview-object"))return;let r=e.node.querySelector("iframe, video");if(i&&r){let o=(n.formatter.get(e.format)[0]?.classes||[])[0],s=!r.classList.contains(o),l=(e.node.getAttribute("data-mce-p-class")||"").split(" ").filter(u=>!u.startsWith("align-"));s&&l.push(o);let c=l.join(" ");e.node.setAttribute("data-mce-p-class",c),r.setAttribute("class",c),n.formatter.apply(e.format,{},r),t(e.node)}})}var Dm=[{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"}]}],Lm={alignleft:{selector:"p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img,iframe,video,span",classes:"align-left"},aligncenter:{selector:"p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img,iframe,video,span",classes:"align-center"},alignright:{selector:"p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img,iframe,video,span",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"}}},Tm=["#BFEDD2","","#FBEEB8","","#F8CAC6","","#ECCAFA","","#C2E0F4","","#2DC26B","","#F1C40F","","#E03E2D","","#B96AD9","","#3598DB","","#169179","","#E67E23","","#BA372A","","#843FA1","","#236FA1","","#ECF0F1","","#CED4D9","","#95A5A6","","#7E8C8D","","#34495E","","#000000","","#ffffff",""];function Lu(n,t,e){if(e.filetype==="file"){let i=window.$components.first("entity-selector-popup"),r=this.selection.getContent({format:"text"}).trim();i.show(o=>{n(o.link,{text:o.name,title:o.name})},{initialValue:r,searchEndpoint:"/search/entity-selector",entityTypes:"page,book,chapter,bookshelf",entityPermission:"view"})}e.filetype==="image"&&window.$components.first("image-manager").show(r=>{n(r.url,{alt:r.name})},"gallery")}function $m(n){let t=["image","table","link","autolink","fullscreen","code","customhr","autosave","lists","codeeditor","media","imagemanager","about","details","tasklist",n.textDirection==="rtl"?"directionality":""];return window.tinymce.PluginManager.add("codeeditor",vu()),window.tinymce.PluginManager.add("customhr",xu()),window.tinymce.PluginManager.add("imagemanager",ku()),window.tinymce.PluginManager.add("about",Cu()),window.tinymce.PluginManager.add("details",Su()),window.tinymce.PluginManager.add("tasklist",Au()),n.drawioUrl&&(window.tinymce.PluginManager.add("drawio",yu(n)),t.push("drawio")),t.filter(e=>!!e)}function Tu(){let n=document.head.innerHTML.split(` `),t=n.findIndex(i=>i.trim()===""),e=n.findIndex(i=>i.trim()==="");return t===-1||e===-1?"":n.slice(t+1,e).join(` `)}function Im(n){return function(e){function i(){n.darkMode&&e.contentDocument.documentElement.classList.add("dark-mode"),window.$events.emit("editor-html-change","")}e.on("ExecCommand change input NodeChange ObjectResized",i),au(e),uu(e,n),e.on("init",()=>{i(),lu(e),window.editor=e,su(e)}),e.on("PreInit",()=>{fu(e)}),Du(e),window.$events.emitPublic(n.containerElement,"editor-tinymce::setup",{editor:e}),e.ui.registry.addButton("inlinecode",{tooltip:"Inline code",icon:"sourcecode",onAction(){e.execCommand("mceToggleFormat",!1,"code")}})}}function $u(n){return` html, body, html.dark-mode { diff --git a/version b/version index 6a54901b0..524938b53 100644 --- a/version +++ b/version @@ -1 +1 @@ -v23.12.1 +v23.12.2