@ones-editor/editor 0.0.3-beta.55 → 0.0.3-beta.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8,23 +8,23 @@
8
8
  * @author Roy Revelt, Codsen Ltd
9
9
  * @license MIT
10
10
  * {@link https://codsen.com/os/string-character-is-astral-surrogate/}
11
- */function _7(n){if(typeof n=="string")return n.length===0?!1:n.charCodeAt(0)>=55296&&n.charCodeAt(0)<=56319;if(n===void 0)return!1;throw new TypeError(`string-character-is-astral-surrogate/isHighSurrogate(): the input is not string but ${typeof n}`)}function Ya(n){if(typeof n=="string")return n.length===0?!1:n.charCodeAt(0)>=56320&&n.charCodeAt(0)<=57343;if(n===void 0)return!1;throw new TypeError(`string-character-is-astral-surrogate/isLowSurrogate(): the input is not string but ${typeof n}`)}const Ti="\u200B";function N7(n){return[...n].length}function $7(n,t,e){const r=[...n];let i;return e===void 0?i=r.length:i=t+e,r.slice(t,i).join("")}const Lo=w("dom-utils");function A(n,...t){n&&n.nodeType===Node.ELEMENT_NODE&&n.classList.add(...t)}function nt(n,t){return n instanceof HTMLElement?n.classList.contains(t):!1}function z(n,...t){n&&n.nodeType===Node.ELEMENT_NODE&&n.classList.remove(...t),n.classList.length===0&&n.removeAttribute("class")}function b(n,t,e,o){const r=document.createElement(n);return t&&t.length>0&&A(r,...t),e&&e.appendChild(r),o&&(typeof o=="string"?r.innerText=o:Ka(r,o)),r}function vr(n,t,e){const o=b("button",t,e);return o.innerHTML=n,o}function tm(n,t,e){const o=b("img",t,e);return o.src=n,o}function em(n,t){try{const e=document.createRange();return e.setStart(n,t),e}catch(e){d(Lo,!1,`failed to create range: ${n.childNodes.length}, ${t}, ${e.message}`)}}function ul(n,t,e,o){try{const r=document.createRange();return r.setStart(n,t),r.setEnd(e,o),r}catch(r){d(Lo,!1,`failed to create expanded range: ${n.childNodes.length}, ${t}, ${e.childNodes.length}, ${o}, ${r.message}`)}}function hl(n){const t=n.getClientRects();return d(Lo,t.length>=1,"getFirstClientRect: no rects"),t[0]}function Mo(n){const t=n.getClientRects();return d(Lo,t.length>=1,"getLastClientRect: no rects"),t[t.length-1]}function Cn(n,t,e){const o=n.left+n.width/2,r=n.top+n.height/2;return(o-t)**2+(r-e)**2}function nm(n,t,e){const o=n.data;d(Lo,o,"invalid text node, no data");let r=Number.MAX_SAFE_INTEGER,i=0;const s=document.createRange();for(let l=0;l<=o.length;l++){if(l<o.length&&Ya(o[l]))continue;s.setStart(n,l);const c=s.getClientRects();for(let a=0;a<c.length;a++){const u=c[a],f=Cn(u,t,e);f<r&&(r=f,i=l)}}return i}function fl(n,t){if(n===t)return 0;if((!n.parentElement||!t.parentElement)&&d(Lo,!1,"invalid dom node to compare"),n.parentElement===t.parentElement){const i=Array.from(n.parentElement.children);return i.indexOf(n)-i.indexOf(t)}const e=i=>{const s=[i];for(;i.parentElement;)s.unshift(i.parentElement),i=i.parentElement;return s},o=e(n),r=e(t);o[0]!==r[0]&&d(Lo,!1,"invalid dom node to compare, different tree");for(let i=1;;i++){const s=o[i],l=r[i];if(s===l)continue;const c=o[i-1],a=Array.from(c.children);return a.indexOf(s)-a.indexOf(l)}}function Qa(n){var r,i;const t=window.getComputedStyle(n),e=(r=Number.parseInt(t.paddingLeft,10))!=null?r:0,o=(i=Number.parseInt(t.paddingRight,10))!=null?i:0;return e+o}function om(n){return!document.documentElement.contains(n)}function It(n,t){let e=t;for(;e;){if(n===e)return!0;e=e.parentNode}return!1}function rm(n,t,e){if(document.getElementById(t)){setTimeout(e);return}const r=document.createElement("script");r.async=!0,r.src=n,r.id=t,document.head.appendChild(r),r.onload=()=>e(),r.onerror=i=>{if(i instanceof Event){const s=i.target;let l="";s&&(l=s.src),e(new URIError(`The script ${l} didn't load correctly.`))}else e(new URIError(`The script ${i} didn't load correctly.`))}}async function Ro(n,t){const e=new Promise((o,r)=>{rm(n,t,i=>{i?r(i):o(void 0)})});try{await qe.lock(t),await e}finally{qe.release(t)}}function Ka(n,t){Object.entries(t).forEach(([e,o])=>{n.dataset[e]=`${o}`})}function Ja(n,t){Object.entries(t).forEach(([e,o])=>{n.setAttribute(e,o)})}function Xa(n,t){Object.entries(t).forEach(([e,o])=>{n.style.setProperty(e,o)})}function Si(n){let t=0,e=0,o=n;do t+=o.offsetTop||0,e+=o.offsetLeft||0,o=o.offsetParent;while(o);return{top:t,left:e}}function Di(n,t){return!n.target||!(n.target instanceof Element)?null:n.target.closest(t)}class P7{constructor(t){h(this,"element");this.element=t}getHorizontalScroll(){return this.element.scrollLeft}getVerticalScroll(){return this.element.scrollTop}getMaxHorizontalScroll(){return this.element.scrollWidth-this.element.clientWidth}getMaxVerticalScroll(){return this.element.scrollHeight-this.element.clientHeight}getHorizontalElementScrollOffset(t,e){return Si(t).left-Si(e).left}getVerticalElementScrollOffset(t,e){return Si(t).top-Si(e).top}scrollTo(t,e){this.element.scrollLeft=t,this.element.scrollTop=e}}class j7{constructor(){h(this,"element",window)}getHorizontalScroll(){return window.scrollX||document.documentElement.scrollLeft}getVerticalScroll(){return window.scrollY||document.documentElement.scrollTop}getMaxHorizontalScroll(){return Math.max(document.body.scrollWidth,document.documentElement.scrollWidth,document.body.offsetWidth,document.documentElement.offsetWidth,document.body.clientWidth,document.documentElement.clientWidth)-window.innerWidth}getMaxVerticalScroll(){return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight,document.body.clientHeight,document.documentElement.clientHeight)-window.innerHeight}getHorizontalElementScrollOffset(t){return(window.scrollX||document.documentElement.scrollLeft)+t.getBoundingClientRect().left}getVerticalElementScrollOffset(t){return(window.scrollY||document.documentElement.scrollTop)+t.getBoundingClientRect().top}scrollTo(t,e){window.scrollTo(t,e)}}const Nn={elements:[],cancelMethods:[],add:(n,t)=>{Nn.elements.push(n),Nn.cancelMethods.push(t)},remove:(n,t)=>{const e=Nn.elements.indexOf(n);e>-1&&(t&&Nn.cancelMethods[e](),Nn.elements.splice(e,1),Nn.cancelMethods.splice(e,1))}},im=typeof window<"u",H7={cancelOnUserAction:!0,easing:n=>--n*n*n+1,elementToScroll:im?window:null,horizontalOffset:0,maxDuration:3e3,minDuration:250,speed:500,verticalOffset:0};async function td(n,t={}){if(!im)return new Promise(R=>{R(!1)});if(!window.Promise)throw"Browser doesn't support Promises, and animated-scroll-to depends on it, please provide a polyfill.";let e,o,r;const i={...H7,...t},s=i.elementToScroll===window,l=!!i.elementToScroll.nodeName;if(!s&&!l)throw"Element to scroll needs to be either window or DOM element.";const c=s?document.documentElement:i.elementToScroll;getComputedStyle(c).getPropertyValue("scroll-behavior")==="smooth"&&console.warn(`${c.tagName} has "scroll-behavior: smooth" which can mess up with animated-scroll-to's animations`);const u=s?new j7:new P7(i.elementToScroll);if(n instanceof Element){if(r=n,l&&(!i.elementToScroll.contains(r)||i.elementToScroll.isSameNode(r)))throw"options.elementToScroll has to be a parent of scrollToElement";e=u.getHorizontalElementScrollOffset(r,i.elementToScroll),o=u.getVerticalElementScrollOffset(r,i.elementToScroll)}else if(typeof n=="number")e=u.getHorizontalScroll(),o=n;else if(Array.isArray(n)&&n.length===2)e=n[0]===null?u.getHorizontalScroll():n[0],o=n[1]===null?u.getVerticalScroll():n[1];else throw`Wrong function signature. Check documentation.
11
+ */function _7(n){if(typeof n=="string")return n.length===0?!1:n.charCodeAt(0)>=55296&&n.charCodeAt(0)<=56319;if(n===void 0)return!1;throw new TypeError(`string-character-is-astral-surrogate/isHighSurrogate(): the input is not string but ${typeof n}`)}function Ya(n){if(typeof n=="string")return n.length===0?!1:n.charCodeAt(0)>=56320&&n.charCodeAt(0)<=57343;if(n===void 0)return!1;throw new TypeError(`string-character-is-astral-surrogate/isLowSurrogate(): the input is not string but ${typeof n}`)}const Ti="\u200B";function N7(n){return[...n].length}function $7(n,t,e){const r=[...n];let i;return e===void 0?i=r.length:i=t+e,r.slice(t,i).join("")}const Lo=w("dom-utils");function A(n,...t){n&&n.nodeType===Node.ELEMENT_NODE&&n.classList.add(...t)}function nt(n,t){return n instanceof HTMLElement?n.classList.contains(t):!1}function z(n,...t){n&&n.nodeType===Node.ELEMENT_NODE&&n.classList.remove(...t),n.classList.length===0&&n.removeAttribute("class")}function b(n,t,e,o){const r=document.createElement(n);return t&&t.length>0&&A(r,...t),e&&e.appendChild(r),o&&(typeof o=="string"?r.innerText=o:Ka(r,o)),r}function vr(n,t,e){const o=b("button",t,e);return o.innerHTML=n,o}function tm(n,t,e){const o=b("img",t,e);return o.src=n,o}function em(n,t){try{const e=document.createRange();return e.setStart(n,t),e}catch(e){d(Lo,!1,`failed to create range: ${n.childNodes.length}, ${t}, ${e.message}`)}}function ul(n,t,e,o){try{const r=document.createRange();return r.setStart(n,t),r.setEnd(e,o),r}catch(r){d(Lo,!1,`failed to create expanded range: ${n.childNodes.length}, ${t}, ${e.childNodes.length}, ${o}, ${r.message}`)}}function hl(n){const t=n.getClientRects();return d(Lo,t.length>=1,"getFirstClientRect: no rects"),t[0]}function Mo(n){const t=n.getClientRects();return d(Lo,t.length>=1,"getLastClientRect: no rects"),t[t.length-1]}function Cn(n,t,e){const o=n.left+n.width/2,r=n.top+n.height/2;return(o-t)**2+(r-e)**2}function nm(n,t,e){const o=n.data;d(Lo,o,"invalid text node, no data");let r=Number.MAX_SAFE_INTEGER,i=0;const s=document.createRange();for(let l=0;l<=o.length;l++){if(l<o.length&&Ya(o[l]))continue;s.setStart(n,l);const c=s.getClientRects();for(let a=0;a<c.length;a++){const u=c[a],f=Cn(u,t,e);f<r&&(r=f,i=l)}}return i}function fl(n,t){if(n===t)return 0;if((!n.parentElement||!t.parentElement)&&d(Lo,!1,"invalid dom node to compare"),n.parentElement===t.parentElement){const i=Array.from(n.parentElement.children);return i.indexOf(n)-i.indexOf(t)}const e=i=>{const s=[i];for(;i.parentElement;)s.unshift(i.parentElement),i=i.parentElement;return s},o=e(n),r=e(t);o[0]!==r[0]&&d(Lo,!1,"invalid dom node to compare, different tree");for(let i=1;;i++){const s=o[i],l=r[i];if(s===l)continue;const c=o[i-1],a=Array.from(c.children);return a.indexOf(s)-a.indexOf(l)}}function Qa(n){var r,i;const t=window.getComputedStyle(n),e=(r=Number.parseInt(t.paddingLeft,10))!=null?r:0,o=(i=Number.parseInt(t.paddingRight,10))!=null?i:0;return e+o}function om(n){return!document.documentElement.contains(n)}function It(n,t){let e=t;for(;e;){if(n===e)return!0;e=e.parentNode}return!1}function rm(n,t,e){if(document.getElementById(t)){setTimeout(e);return}const r=document.createElement("script");r.async=!0,r.src=n,r.id=t,document.head.appendChild(r),r.onload=()=>e(),r.onerror=i=>{if(i instanceof Event){const s=i.target;let l="";s&&(l=s.src),e(new URIError(`The script ${l} didn't load correctly.`))}else e(new URIError(`The script ${i} didn't load correctly.`))}}async function Ro(n,t){const e=new Promise((o,r)=>{rm(n,t,i=>{i?r(i):o(void 0)})});try{await qe.lock(t),await e}finally{qe.release(t)}}function Ka(n,t){Object.entries(t).forEach(([e,o])=>{n.dataset[e]=`${o}`})}function Ja(n,t){Object.entries(t).forEach(([e,o])=>{n.setAttribute(e,o)})}function Xa(n,t){Object.entries(t).forEach(([e,o])=>{n.style.setProperty(e,o)})}function Si(n){let t=0,e=0,o=n;do t+=o.offsetTop||0,e+=o.offsetLeft||0,o=o.offsetParent;while(o);return{top:t,left:e}}function Di(n,t){return!n.target||!(n.target instanceof Element)?null:n.target.closest(t)}class P7{constructor(t){h(this,"element");this.element=t}getHorizontalScroll(){return this.element.scrollLeft}getVerticalScroll(){return this.element.scrollTop}getMaxHorizontalScroll(){return this.element.scrollWidth-this.element.clientWidth}getMaxVerticalScroll(){return this.element.scrollHeight-this.element.clientHeight}getHorizontalElementScrollOffset(t,e){return Si(t).left-Si(e).left}getVerticalElementScrollOffset(t,e){return Si(t).top-Si(e).top}scrollTo(t,e){this.element.scrollLeft=t,this.element.scrollTop=e}}class j7{constructor(){h(this,"element",window)}getHorizontalScroll(){return window.scrollX||document.documentElement.scrollLeft}getVerticalScroll(){return window.scrollY||document.documentElement.scrollTop}getMaxHorizontalScroll(){return Math.max(document.body.scrollWidth,document.documentElement.scrollWidth,document.body.offsetWidth,document.documentElement.offsetWidth,document.body.clientWidth,document.documentElement.clientWidth)-window.innerWidth}getMaxVerticalScroll(){return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight,document.body.clientHeight,document.documentElement.clientHeight)-window.innerHeight}getHorizontalElementScrollOffset(t){return(window.scrollX||document.documentElement.scrollLeft)+t.getBoundingClientRect().left}getVerticalElementScrollOffset(t){return(window.scrollY||document.documentElement.scrollTop)+t.getBoundingClientRect().top}scrollTo(t,e){window.scrollTo(t,e)}}const $n={elements:[],cancelMethods:[],add:(n,t)=>{$n.elements.push(n),$n.cancelMethods.push(t)},remove:(n,t)=>{const e=$n.elements.indexOf(n);e>-1&&(t&&$n.cancelMethods[e](),$n.elements.splice(e,1),$n.cancelMethods.splice(e,1))}},im=typeof window<"u",H7={cancelOnUserAction:!0,easing:n=>--n*n*n+1,elementToScroll:im?window:null,horizontalOffset:0,maxDuration:3e3,minDuration:250,speed:500,verticalOffset:0};async function td(n,t={}){if(!im)return new Promise(R=>{R(!1)});if(!window.Promise)throw"Browser doesn't support Promises, and animated-scroll-to depends on it, please provide a polyfill.";let e,o,r;const i={...H7,...t},s=i.elementToScroll===window,l=!!i.elementToScroll.nodeName;if(!s&&!l)throw"Element to scroll needs to be either window or DOM element.";const c=s?document.documentElement:i.elementToScroll;getComputedStyle(c).getPropertyValue("scroll-behavior")==="smooth"&&console.warn(`${c.tagName} has "scroll-behavior: smooth" which can mess up with animated-scroll-to's animations`);const u=s?new j7:new P7(i.elementToScroll);if(n instanceof Element){if(r=n,l&&(!i.elementToScroll.contains(r)||i.elementToScroll.isSameNode(r)))throw"options.elementToScroll has to be a parent of scrollToElement";e=u.getHorizontalElementScrollOffset(r,i.elementToScroll),o=u.getVerticalElementScrollOffset(r,i.elementToScroll)}else if(typeof n=="number")e=u.getHorizontalScroll(),o=n;else if(Array.isArray(n)&&n.length===2)e=n[0]===null?u.getHorizontalScroll():n[0],o=n[1]===null?u.getVerticalScroll():n[1];else throw`Wrong function signature. Check documentation.
12
12
  Available method signatures are:
13
13
  animateScrollTo(y:number, options)
14
14
  animateScrollTo([x:number | null, y:number | null], options)
15
- animateScrollTo(scrollToElement:Element, options)`;e+=i.horizontalOffset,o+=i.verticalOffset;const f=u.getMaxHorizontalScroll(),m=u.getHorizontalScroll();e>f&&(e=f);const C=e-m,v=u.getMaxVerticalScroll(),B=u.getVerticalScroll();B<o?o-=window.innerHeight*3/4:o-=window.innerHeight*1/4,o>v&&(o=v);const y=o-B,S=Math.abs(Math.round(C/1e3*i.speed)),I=Math.abs(Math.round(y/1e3*i.speed));let M=S>I?S:I;return M<i.minDuration?M=i.minDuration:M>i.maxDuration&&(M=i.maxDuration),new Promise((R,$)=>{C===0&&y===0&&R(!0),Nn.remove(u.element,!0);let Z;const ot=()=>{se(),cancelAnimationFrame(Z),R(!1)};Nn.add(u.element,ot);const st=Ue=>Ue.preventDefault(),mt=i.cancelOnUserAction?ot:st,ut=i.cancelOnUserAction?{passive:!0}:{passive:!1},yt=["wheel","touchstart","keydown","mousedown"],se=()=>{yt.forEach(Ue=>{u.element.removeEventListener(Ue,mt,ut)})};yt.forEach(Ue=>{u.element.addEventListener(Ue,mt,ut)});const eo=Date.now(),ee=()=>{const Ue=Date.now()-eo,Eo=Ue/M,gr=Math.round(m+C*i.easing(Eo)),pr=Math.round(B+y*i.easing(Eo));Ue<M&&(gr!==e||pr!==o)?(u.scrollTo(gr,pr),Z=requestAnimationFrame(ee)):(u.scrollTo(e,o),cancelAnimationFrame(Z),se(),Nn.remove(u.element,!1),R(!0))};Z=requestAnimationFrame(ee)})}function Ao(n,t,e){return n.left<=t&&t<=n.right&&n.top<=e&&e<=n.bottom}function F7(n){const t="\xA0";if(!n)return"";if(n===" ")return t;let e=n;return e.startsWith(" ")&&(e=t+e.substr(1)),e.endsWith(" ")&&(e=e.substr(0,e.length-1)+t),e=e.replace(/ {2}/g,` ${t}`),e}function sm(n){if(!/["'&<>]/.exec(n))return n;const o={'"':"&quot;","'":"&#39;","&":"&amp;","<":"&lt;",">":"&gt;"};return n.split("").map(l=>o[l]||l).join("")}function lm(n){const t=document.getElementById(n);t&&t.remove()}function cm(n,t){const e=document.getElementById(t);if(e)return e.textContent=n,e;const o=document.createElement("style");return o.id=t,o.textContent=n,document.head.append(o),o}function Li(n){const t="custom-cursor-style";if(n){const e=`body * { cursor: ${n} !important}`;cm(e,t)}else lm(t)}const am=3,dm=w("drag-drop");class um{constructor(t){h(this,"dragStarted",!1);h(this,"mouseDownEvent",null);h(this,"_dragOffsetX",0);h(this,"_dragOffsetY",0);h(this,"handleMouseDown",t=>{t.preventDefault(),t.stopPropagation(),this.mouseDownEvent=t;const e=this.options.elem.getBoundingClientRect();this._dragOffsetX=this.mouseDownEvent.x-e.left,this._dragOffsetY=this.mouseDownEvent.y-e.top,this.bindEvents()});h(this,"handleMouseMove",t=>{var i;t.preventDefault(),t.stopPropagation(),d(dm,this.mouseDownEvent,"no mouse down event");const e=t.x-this.mouseDownEvent.x,o=t.y-this.mouseDownEvent.y;if(this.dragStarted){this.onDragging(t,e,o);return}const r=(i=this.options.minThreshold)!=null?i:am;(Math.abs(e)>=r||Math.abs(o)>=r)&&this.onDragStart(this.mouseDownEvent)});h(this,"handleMouseUp",t=>{if(t.button===0){d(dm,this.mouseDownEvent,"no mouse down event");const e=t.x-this.mouseDownEvent.x,o=t.y-this.mouseDownEvent.y;this.onDragEnd(t,e,o),t.preventDefault(),t.stopPropagation()}});this.options=t,this.options.mouseDownEvent?this.handleMouseDown(this.options.mouseDownEvent):this.trackEvents()}get data(){return this.options.data}get dragOffsetX(){return this._dragOffsetX}get dragOffsetY(){return this._dragOffsetY}get dragOffset(){return{x:this._dragOffsetX,y:this._dragOffsetY}}trackEvents(){this.options.elem.addEventListener("mousedown",this.handleMouseDown)}untrackEvents(){this.options.elem.removeEventListener("mousedown",this.handleMouseDown)}bindEvents(){document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp)}unbindEvents(){document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}onDragStart(t){this.dragStarted=!0,this.options.cursor&&Li(this.options.cursor),this.options.onDragStart(this,t,this.options.elem)}onDragging(t,e,o){this.options.onDragging(this,t,this.options.elem,e,o)}onDragEnd(t,e,o){this.options.cursor&&Li(null),this.dragStarted&&this.options.onDragEnd(this,t,this.options.elem,e,o),this.unbindEvents(),this.dragStarted=!1}destroy(){this.unbindEvents(),this.untrackEvents()}}function ed(n){return new um(n)}const z7=w("character");function hm(n,t){for(let e=0;e<t.length;e++){const o=t[e][0],r=t[e].length>1?t[e][1]:null;if(r===null&&n===o||r!==null&&n>=o&&n<=r)return!0}return!1}function fm(n){const t=n.charAt(0);return t>="0"&&t<="9"}function mm(n){const t=n.charAt(0);return t>="a"&&t<="z"||t>="A"&&t<="Z"||t.toUpperCase()!==t.toLowerCase()?!0:RegExp(/^\p{L}/,"u").test(t)}function ml(n){const t=[[9,13],[32],[160]];return hm(n.charCodeAt(0),t)}function gm(n){const t=[[12352,12687],[13056,13183],[13312,15661],[19968,40959],[63744,64255],[44032,55215]];return hm(n.charCodeAt(0),t)}function nd(n,t){let e=t;return d(z7,e.length===1,"invalid char length"),e==="]"&&(e="\\]"),e==="\\"&&(e="\\\\"),n.replace(new RegExp(`^[${e}]+|[${e}]+$`,"g"),"")}const $n=navigator.userAgent;function pm(){const n=navigator.userAgent.toLowerCase();return n.indexOf("safari")!==-1&&!(n.indexOf("chrome")>-1)}function od(){return navigator.userAgent.toLowerCase().indexOf("firefox")>-1}const xt={isAndroid:!!$n.match(/Android/i),isIOS:!!$n.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/i),isIPad:!!$n.match(/iPad/i),isIPhone:!!$n.match(/iPhone/i),isLinux:!!$n.match(/Linux/i),isMac:!!$n.match(/Macintosh/i),isMobile:!!$n.match(/AppleWebKit.*Mobile.*/i),isWindows:!!$n.match(/Window/i),isIe:!!$n.match(/msie|trident/i),isSafari:pm(),isMobileSafari:!1};xt.isMobileSafari=xt.isMobile&&xt.isSafari;function rd(n){return n?n.length===1||n==="Process"||n==="Unidentified"&&xt.isAndroid:!1}function Cm(n){switch(n){case"ArrowDown":case"ArrowUp":case"ArrowLeft":case"ArrowRight":case"End":case"Home":case"PageDown":case"PageUp":return!0;default:return!1}}function U7(n){return Cm(n.key)}function V7(n){switch(n){case"ArrowUp":case"ArrowLeft":case"Home":case"PageUp":return!0;default:return!1}}function Oo(n){return n.ctrlKey||n.altKey||n.shiftKey||n.metaKey}function q7(n){return n.key?!!(n.ctrlKey||n.metaKey||n.altKey):!1}function bm(n){return xt.isMac?n.metaKey&&!n.ctrlKey:!n.metaKey&&n.ctrlKey}function W7(n){return bm(n)&&!n.altKey&&!n.shiftKey}function G7(n){return!n.metaKey&&!n.ctrlKey&&!n.shiftKey&&n.altKey}function vm(n){return!Oo(n)&&n.key==="Enter"}function Z7(n){return n.key==="Enter"&&n.shiftKey&&!n.altKey&&!n.ctrlKey&&!n.metaKey}function id(n){return!Oo(n)&&n.key==="Escape"}function Y7(n){return!Oo(n)&&n.key==="Delete"}function km(n){return!Oo(n)&&n.key==="Backspace"}function Q7(n){return!Oo(n)&&n.key==="Tab"}function K7(n){return n.shiftKey&&n.key==="Tab"&&!n.ctrlKey&&!n.metaKey}function J7(n){if(!n)return"";if(xt.isMac){const t=n.replace("CtrlOrCmd","\u2318").replace("Shift","\u21E7").replace("Ctrl","\u2303").replace("Alt","\u2325").replace(/\+(?!$)/gm,""),e={"\u2318":4,"\u21E7":3,"\u2325":2,"\u2303":1};return t.split(/(?=[\s\S])/u).sort((r,i)=>{var c,a;const s=(c=e[r])!=null?c:5,l=(a=e[i])!=null?a:5;return s-l}).join("")}return n.replace("CtrlOrCmd","Ctrl")}function ym(n){const t={ctrl:!1,alt:!1,shift:!1,cmd:!1,key:""},e=n.toLocaleUpperCase().split("+");for(let o=0;o<e.length;o++){const r=e[o];r==="CTRL"||r==="CONTROL"?t.ctrl=!0:r==="ALT"||r==="OPTION"?t.alt=!0:r==="SHIFT"?t.shift=!0:r==="CMD"||r==="COMMAND"?t.cmd=!0:r==="CMDORCTRL"||r==="CTRLORCMD"?xt.isMac?t.cmd=!0:t.ctrl=!0:r==="SPACE"?t.key=" ":t.key=r.substring(0,1)+r.substring(1).toLocaleLowerCase()}return t}function Pn(n,t){const e=ym(t);return e.ctrl!==n.ctrlKey||e.alt!==n.altKey||e.shift!==n.shiftKey||xt.isMac&&e.cmd!==n.metaKey?!1:e.key.length===1?e.key===n.key.toUpperCase():e.key.toUpperCase()===n.key.toUpperCase()}function sd(n,t){return z9.stringifyUrl({url:n,query:t})}function _o(n){return typeof n=="string"?Bi.Base64.encode(n,!0):Bi.Base64.fromUint8Array(n,!0)}function gl(n){return Bi.Base64.decode(n)}function X7(n){return Bi.Base64.toUint8Array(n)}function wm(n){return new Blob([Bi.Base64.toUint8Array(n)])}const t8=oo.init([oo.classModule,oo.styleModule,oo.datasetModule,oo.attributesModule,oo.propsModule]);function Mi(n,t){const e=oo.toVNode(n),o=oo.toVNode(t);t8(e,o)}async function Bm(n,t){const e=new FileReader,o=new Promise((i,s)=>{e.onload=i,e.onerror=s});return e.readAsDataURL(new Blob([n],{type:t})),await o,e.result}async function pl(n){const t=new FileReader,e=new Promise((r,i)=>{t.onload=r,t.onerror=i});return t.readAsDataURL(n),await e,t.result}function e8(n,...t){const e=n.tagName.toLowerCase();for(let o=0,r=t.length;o<r;o++)if(e===t[o].toLowerCase())return!0;return!1}function We(n,t){let e=n;for(;e;){const o=window.getComputedStyle(e);if(t!=null&&t.horizontal){if(/auto|scroll/i.test(o.overflowX))break}else if(/auto|scroll/i.test(o.overflowY))break;e=e.parentElement}return(!e||e8(e,"body"))&&(e=document.documentElement),e}function Em(n){n.preventDefault(),n.stopPropagation()}function Im(n){if(document.querySelector(`.editor-disable-scroll[data-scroll-id="${n}"]`))return;const t=b("div",["editor-disable-scroll"],null);t.setAttribute("data-scroll-id",n),t.addEventListener("wheel",Em,{passive:!1}),document.body.appendChild(t)}function xm(n){const t=document.querySelector(`.editor-disable-scroll[data-scroll-id="${n}"]`);t&&(t.removeEventListener("wheel",Em),t.remove())}function ld(n,t,e){const o=new Blob([n]),r=new File([o],e,{type:t});return URL.createObjectURL(r)}function Cl(n){const t=document.createElement("template");if("content"in t)return t.innerHTML=n,document.importNode(t.content,!0);const e=document.createDocumentFragment(),o=document.createElement("div");for(o.innerHTML=n;o.firstChild;)e.appendChild(o.firstChild);return e}function Tm(n){const t=document.createElement("div");return t.appendChild(n),t.innerHTML}function Sm(n){let t=n.getPropertyValue("font");if(t)return t;const e=n.getPropertyValue("font-style"),o=n.getPropertyValue("font-variant"),r=n.getPropertyValue("font-weight"),i=n.getPropertyValue("font-size"),s=n.getPropertyValue("font-family");return t=`${e} ${o} ${r} ${i} ${s}`.replace(/ +/g," ").trim(),t}function bl(n,t){const o=(bl.canvas||(bl.canvas=document.createElement("canvas"))).getContext("2d");return o?(typeof t=="string"?t?o.font=t:o.font=Sm(window.getComputedStyle(document.body)):t instanceof Element&&(o.font=Sm(window.getComputedStyle(t))),o.measureText(n).width+4):200}const n8=w("editor-clipboard");async function o8(n,t){if(t.clipboardData){const e=t.clipboardData;for(const o of n)e.setData(o.type,o.data);return!0}return!1}async function vl(n){try{const t={};n.forEach(o=>{t[o.type]=o.data});const e=new ClipboardItem(t);return await navigator.clipboard.write([e]),!0}catch(t){return n8.error(t),!1}}function No(n,t){return new Promise((e,o)=>{const r=document.createElement("input");r.type="file",r.style.display="none",t!=null&&t.multiple&&(r.multiple=!0),r.accept=n,r.onchange=()=>{const i=r.files;if(i){const s=t!=null&&t.multiple?Array.from(i):i[0];e(s)}r.remove()},r.onerror=i=>{o(i),r.remove()},r.click()})}function kl(n){return Array.isArray(n)?n.every(t=>t instanceof File):!1}function Dm(n){const t=n;if(!t)return"";const e=t.lastIndexOf(".");return e===-1?"":t.slice(e+1)}function yl(n,t){const e=document.createElement("a");e.setAttribute("download",`${t||""}`),e.setAttribute("href",`${n}`),e.click(),e.remove()}const Lm=w("auto-scroll");function Mm(n,t){return!(n.scrollHeight===n.clientHeight||t==="top"&&n.scrollTop===0||t==="bottom"&&n.scrollTop+n.clientHeight===n.scrollHeight||t==="left"&&n.scrollLeft===0||t==="right"&&n.scrollLeft+n.clientWidth===n.scrollWidth)}function Rm(n,{direction:t,step:e}){let o=null;const r=t==="left"||t==="right",i=()=>{if(!Mm(n,t))return Lm.debug("No need for scroll"),null;if(r){const s=n.scrollLeft,l=t==="left"?s-e:s+e;n.scrollLeft=l}else{const s=n.scrollTop,l=t==="top"?s-e:s+e;n.scrollTop=l}return o=requestAnimationFrame(i),o};return o=requestAnimationFrame(i),()=>{o&&cancelAnimationFrame(o)}}class Am{constructor(t){h(this,"cancelScroll",null);h(this,"options");h(this,"scrollDomInfo");h(this,"scrolling",!1);h(this,"getScrollingDirection",t=>{const{x:e,y:o}=t,{top:r,bottom:i,left:s,right:l}=this.scrollDomInfo,{edge:c}=this.options;return c.top&&o>=r&&o<=c.top+r?"top":c.bottom&&o<=i&&o>=i-c.bottom?"bottom":c.left&&e>=s&&e<=s+c.left?"left":c.right&&e<=l&&e>=l-c.right?"right":null});h(this,"handleMouseMove",t=>{var s;const{scrollElement:e,step:o=10,onDirectionChange:r}=this.options,i=this.getScrollingDirection(t);if(i){if(this.scrolling)return;Lm.debug(`scroll direction: ${i}`),this.cancelScroll=Rm(e,{direction:i,step:o}),r==null||r(i),this.scrolling=!0}else(s=this.cancelScroll)==null||s.call(this),this.scrolling=!1});this.options=t,this.scrollDomInfo=this.getScrollDomInfo()}getScrollDomInfo(){const{scrollElement:t}=this.options,e=t.clientTop,o=t.clientLeft,r=t.clientHeight,i=t.clientWidth;return{left:o,top:e,right:i,bottom:r}}active(){const{trackMouseEvent:t="mousemove"}=this.options;window.addEventListener(t,this.handleMouseMove,!0)}inactive(){var e;const{trackMouseEvent:t="mousemove"}=this.options;window.removeEventListener(t,this.handleMouseMove,!0),(e=this.cancelScroll)==null||e.call(this),this.scrolling=!1}}function Om(n,t){if(n===0)return"0 Bytes";const e=1024,o=t||2,r=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],i=Math.floor(Math.log(n)/Math.log(e));return`${parseFloat((n/e**i).toFixed(o))} ${r[i]}`}function cd(n,t){let e=`${n}`;const o=t-e.length;for(let r=0;r<o;r++)e=`0${e}`;return e}const{t:$o}=T;function ad(n,t){const e=new Date(n).getTime()+864e5*t;return new Date(e)}function r8(n,t){const e=n,o=Math.floor(t/12),r=t-o*12;return o&&e.setFullYear(e.getFullYear()+o),r&&e.setMonth(e.getMonth()+r),e}function i8(n,t){return ad(n,t)}function dd(n,t){const e=new Date(n),o=new Date(t);return e.getDate()===o.getDate()&&e.getMonth()===o.getMonth()&&e.getFullYear()===o.getFullYear()}function _m(n){const t=new Date,e=new Date(n);return dd(t,e)}function Nm(n){const t=ad(new Date,-1);return dd(t,n)}function s8(n,t){return Math.round((n.getTime()-t.getTime())/864e5)}function $m(n,t){const e=new Date(n);if(t){const o=e.getFullYear(),r=e.getMonth()+1,i=e.getDate();let s=t;return s=s.replace("yyyy",`${o}`),s=s.replace("mm",cd(r,2)),s=s.replace("dd",cd(i,2)),s=s.replace("m",`${r}`),s=s.replace("d",`${i}`),s}return n.toLocaleDateString()}function ud(n,t){const e=new Date(n),o=new Date;if(e.getTime()-o.getTime()>10*1e3)return T.t("date.dateFromFuture");if(_m(e)){const i=(o.getTime()-n.getTime())/1e3;if(i<10*60)return $o("date.dateJustNow");if(i<60*60)return $o("date.dateMinutesAgo",{num:`${Math.floor(i/60)}`});const s=Math.floor(i/60/60);return s===1?$o("date.date1HourAgo"):$o("date.dateHoursAgo",{num:`${s}`})}if(Nm(n))return $o("date.dateYesterday");const r=Math.floor((o.getTime()-n.getTime())/1e3/24/60/60)+1;return r<14?$o("date.dateDaysAgo",{num:`${r}`}):r<28?$o("date.dateWeeksAgo",{num:`${Math.round(r/7)}`}):$m(n,t)}function hd(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function l8(n,t,e){return n.replace(new RegExp(hd(t),"g"),e)}function c8(n,t,e){return n.replace(new RegExp(hd(t),"gi"),e)}const Pm=w("container-children");function Mt(n){const t=Array.from(n.querySelectorAll(":scope > .container-blocks > div[data-type=editor-block]"));return d(Pm,t.length>0,"container have not any child block"),t}function Vt(n){const t=n.querySelector(":scope > .container-blocks > div[data-type=editor-block]");return d(Pm,t,"container have not any child block"),t}function Qt(n){const t=Mt(n);return t[t.length-1]}function Ge(n){return Mt(n).length}function kr(n,t){return Mt(n)[t]}const Ze=w("block-dom");function Po(n){return n instanceof HTMLDivElement?n.getAttribute("data-type")==="editor-block":!1}function jm(n){A(n,"block-hidden")}function Hm(n){z(n,"block-hidden")}function wl(n){return!nt(n,"block-hidden")}function q(n){const{id:t}=n;return d(Ze,t,"no block id"),t}function rt(n){const t=n.getAttribute("data-block-type");return d(Ze,t,"invalid block dom, no data-type"),t}function F(n){const t=n instanceof Element?n:n.parentElement;if(!t)return null;const e=t.closest("div[data-type=editor-block]");return e||null}function H(n){const t=n.closest("div[data-type=editor-container]");return d(Ze,t,"failed to get block container"),t}function it(n){const t=n.querySelector(":scope >div[data-type=block-content]");return d(Ze,t,"no block content"),t}function Rt(n){let t=n.querySelector(":scope >div[data-type=block-tools]");return t||(t=b("div",[],n),t.setAttribute("data-type","block-tools")),d(Ze,t,"no block tools"),t}function Bl(n){const t=n.querySelector(":scope >div[data-type=block-tools]");return t||null}function Fm(n){let t=n.querySelector(":scope > div[data-type=block-background]");return t||(t=b("div",[],n),t.setAttribute("data-type","block-background")),t}function zm(n,t,e){const o=n.editorDecorators.decorateBlock(t,e),{id:r,type:i}=o;d(Ze,r,"no block id");const s=b("div",[`${i}-block`],null);s.id=r,s.setAttribute("data-type","editor-block"),s.setAttribute("data-block-type",i);const l=n.editorBlockRenders.renderBlock(n,t,e);return l.classes&&A(s,...l.classes),l.attributes&&Object.entries(l.attributes).forEach(([c,a])=>{s.setAttribute(c,a)}),l.styles&&Object.entries(l.styles).forEach(([c,a])=>{s.style.setProperty(c,a)}),s}function ro(n,t){const e=b(t,[],null);return e.setAttribute("data-type","block-content"),n&&n.appendChild(e),e}function Um(n){const t=b("span",[`${n.type}-box`],null);return t.setAttribute("data-type","editor-box"),t.setAttribute("data-box-type",n.type),t.id=n.id,t}function Ri(n){const t=n.getAttribute("data-box-type");return d(Ze,t,"not a valid box element, no type"),t}function fd(n){return n instanceof HTMLSpanElement?n.getAttribute("data-type")==="editor-box":!1}function Vm(n){const{id:t}=n;return d(Ze,t,"no box id"),t}function md(n){const t=n instanceof Element?n:n.parentElement;if(!t)return null;const e=t.closest("span[data-type=editor-box]");return e||null}function qm(n){n.innerHTML="",b("span",["box-space-start"],n,Ti);const t=b("span",[],n);return t.setAttribute("data-type","box-content"),b("span",["box-space-start"],n,Ti),t}function gd(n){const t=n.querySelector("span[data-type=box-content]");return d(Ze,t,"invalid box dom, no content"),t}function Wm(n,t){const e=b("span",[`${n}-insertion`],null);return e.setAttribute("data-type","editor-insertion"),e.setAttribute("data-insertion-id",t),e}function Gm(n,t){return n.rootContainer.querySelector(`[data-insertion-id=${t}]`)}function Zm(n){n.innerHTML="",b("span",["insertion-space-start"],n,Ti);const t=b("span",[],n);return t.setAttribute("data-type","insertion-content"),b("span",["insertion-space-start"],n,Ti),t}function pd(n){const t=n.querySelector("span[data-type=insertion-content]");return d(Ze,t,"invalid insertion-child dom, no content"),t}function gt(n){let t=n.previousElementSibling;for(;t;){if(Po(t))return t;t=t.nextElementSibling}return null}function dt(n){let t=n.nextElementSibling;for(;t;){if(Po(t))return t;t=t.nextElementSibling}return null}function yr(n){let t=n.previousElementSibling;for(;t;){if(Po(t)&&wl(t))return t;t=t.previousElementSibling}return null}function wr(n){let t=n.nextElementSibling;for(;t;){if(Po(t)&&wl(t))return t;t=t.nextElementSibling}return null}function J(n){const t=H(n),o=Mt(t).indexOf(n);return d(Ze,o!==-1,"invalid block & container dom, failed to get block index"),o}function Cd(n){return!n||!(n instanceof Node)?!1:!!F(n)}function Ai(n){if(!Cd(n))return!1;const t=n,e=t instanceof Element?t:t.parentElement;return e?!!e.closest("div[data-type=block-tools]"):!1}const Ym=w("element");function bd(n,t,e){const o=b("div",[t],n);return o.setAttribute("data-type","editor-container"),o.setAttribute("data-container-id",e),b("div",["container-blocks"],o),o}function Br(n,t){const e=n.rootElement.querySelector(`[data-container-id=${t}`);return d(Ym,e,`no container: ${t}`),e}function Qm(n,t){return n.rootElement.querySelector(`[data-container-id=${t}`)}function El(n){const t=n.querySelector(":scope > .container-blocks");return d(Ym,t,"no container blocks element"),t}function a8(n){let t=n.querySelector(":scope > .container-tools");return t||(t=b("div",["container-tools"],n)),t}const Km=w("container");function bn(n){return n.getAttribute("data-type")==="editor-container"}function pt(n){return nt(n,"root")}function Ye(n){return nt(n,"child")}function U(n){const t=n.getAttribute("data-container-id");return d(Km,t,"no id for container"),pt(n)&&d(Km,t==="root",`invalid root container id, : ${t}`),t}function Jm(n,t){const e=U(n);return t.getContainerBlocks(e)}const Xm=w("block-path");function jo(n){const t=[];let e=n;for(;e;){const o=H(e);if(t.unshift({containerId:U(o),blockIndex:J(e)}),pt(o))return t;const r=F(o);d(Xm,r,"no parent block"),e=r}return d(Xm,!1,"no parent block"),[]}const d8=w("child-container-path");function tg(n){if(pt(n))return[];const t=F(n);return d(d8,t,"no parent block"),jo(t)}const eg=w("load-blocks");function vd(n,t,e){const o=U(t),r=Jm(t,n.doc);d(eg,r.length>0,"no blocks in container");const i=document.createDocumentFragment();r.forEach((l,c)=>{const a=n.editorBlocks.createBlock([...e,{containerId:o,blockIndex:c}],t,l);i.appendChild(a)}),El(t).appendChild(i)}function u8(n,t,e){const o=El(n),r=Mt(n);return d(eg,t>=0&&t<=r.length,"invalid block index"),t===r.length?o.appendChild(e):o.insertBefore(e,r[t]),e}function h8(n,t,e,o){const r=tg(t);r.push({containerId:U(t),blockIndex:e});const i=n.editorBlocks.createBlock(r,t,o);return u8(t,e,i),i}const ng=w("root-container");class f8{constructor(t,e){h(this,"resizeObserver");h(this,"handleContextMenu",t=>{t.preventDefault()});h(this,"handleResize",()=>{try{this.editor.selection.updateSelection(null),this.editor.emit("resize",this.editor)}catch(t){ng.warn(`failed to update selection while container resizing: ${t.message}`)}});h(this,"handleClick",t=>{var o,r;this.editor.emit("click",this.editor,t);const e=t.target;if(!Ai(e)&&(t.detail===1&&this.editor.input.focus(),t.detail===3&&this.editor.selectionHandler.handleTripleClick(t),t.detail===1&&t.button===0)){const i=document.elementFromPoint(t.clientX,t.clientY);if(i&&It(this.rootContainer,i)){const s=md(i);if(s){const l=F(s);d(ng,l,"no parent block"),(r=(o=this.editor.editorBoxes.getBoxClass(Ri(s)))==null?void 0:o.handleClickBox)==null||r.call(o,this.editor,s,t)}}}});h(this,"handleDblClick",t=>{Ai(t.target)||this.editor.selectionHandler.handleDblClick(t)});h(this,"handleMouseDown",t=>{const e=t.target;if(!!e&&e instanceof Node&&!Ai(e)){if(e instanceof HTMLElement&&e.draggable){this.editor.selectionHandler.handleMouseDown(t),this.editor.selectionHandler.stopSelection(),this.editor.input.focus();return}t.button===0&&(document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp),this.editor.selectionHandler.handleMouseDown(t)),xt.isMobileSafari||(t.preventDefault(),this.editor.input.focus()),t.button===2&&t.stopPropagation()}});h(this,"handleMouseMove",t=>{this.editor.selectionHandler.handleMouseMove(t)});h(this,"handleMouseUp",t=>{t.button===0&&(this.editor.selectionHandler.handleMouseUp(t),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp))});this.editor=t,this.rootContainer=e,this.editor=t,this.resizeObserver=new ResizeObserver(this.handleResize),this.bindEvents(e)}bindEvents(t){this.resizeObserver.observe(t);const e=this.editor.rootElement;e.onmousedown=this.handleMouseDown,e.ondblclick=this.handleDblClick,e.onclick=this.handleClick,e.oncontextmenu=this.handleContextMenu}unbindEvents(){this.resizeObserver.disconnect();const t=this.editor.rootElement;t.onmousedown=null,t.ondblclick=null,t.onclick=null,t.oncontextmenu=null}destroy(){this.unbindEvents()}reload(){const t=this.editor.selection.range,e=El(this.rootContainer);e.innerHTML="",vd(this.editor,this.rootContainer,[]);const o=this.editor.findBlockById(t.start.blockId);if(o)this.editor.selection.selectBlock(o,0);else{const r=Vt(this.rootContainer);this.editor.selection.selectBlock(r,0)}}}function og(n){const t=bd(n.contentElement,"root","root");return n.rootContainer=t,vd(n,t,[]),new f8(n,t)}function rg(n,t,e,o){const r=Qm(n,o);if(r)return e.appendChild(r),r;const i=bd(e,"child",o);return vd(n,i,t),i}const ig=w("block-class");function bt(n,t){return n.editorBlocks.getBlockClass(rt(t))}function sg(n,t){const e=n.editorBlocks.getBlockClass(rt(t));return d(ig,e.blockKind==="text",`is not a text block, ${e.blockType}`),e}function xe(n,t){const e=n.editorBlocks.getBlockClass(rt(t));return d(ig,e.blockKind==="complex",`is not a text block, ${e.blockType}`),e}function Er(n,t){return n.editorBlocks.getBlockClass(t)}const kd=w("block");function W(n,t){return bt(n,t).getBlockTextLength(t)}function lg(n){n.editorBlocks.forEach(t=>{t.clearSelection(n)})}function cg(n,t,e,o){bt(n,t).updateSelection(n,t,e,o)}function yd(n){for(;;){const t=H(n);if(pt(t))return n;const e=F(t);d(kd,e,"no parent block exists for child container"),n=e}}function ag(n,t){const e=bt(n,t);if(!!e.getMinWidth)return e.getMinWidth(n,t)}function dg(n,t,e){const o=bt(n,t);o.handleBlockElementUpdated&&o.handleBlockElementUpdated(n,t,e)}function Oi(n,t,e,o){try{const r=Er(n,e).convertFrom;return r?r(n,t,o):null}catch{return kd.debug(`unsupported block type: ${e}`),null}}function Ho(n,t,e){const o=bt(n,t);return o.getClientRects?o.getClientRects(n,t,e):[t.getBoundingClientRect()]}function m8(n,t){const e=bt(n,t);if(e.getBlockStyles)return e.getBlockStyles(n,t);const o=n.getBlockData(t),r=Object.fromEntries(Object.entries(o).filter(([i])=>i.startsWith("style-")));return Object.entries(r).forEach(([,i])=>{const s=typeof i;d(kd,s==="string"||s==="number"||s==="boolean","invalid style value")}),r}function ug(n,t){const e=n.getBoundingClientRect().width;return t.withPadding?e:e-Qa(n)}function wd(n,t){let e=Number.MAX_SAFE_INTEGER;const o=Mt(t);for(let i=0;i<o.length;i++){const s=o[i],l=ag(n,s);l&&(e=Math.min(e,l))}return e===Number.MAX_SAFE_INTEGER?void 0:e+Qa(t)}function j(n,t){return bt(n,t).blockKind==="text"}function _i(n,t){return n.editorBlocks.getBlockClass(t).blockKind==="text"}function at(n,t){return bt(n,t).blockKind==="complex"}function g8(n,t){return!at(n,t)}function Qe(n,t){return bt(n,t).blockKind}function Tt(n,t){return Qe(n,t)==="text"?W(n,t)===0:!1}function Bd(n,t){const e=Mt(t);return e.length!==1?!1:Tt(n,e[0])}function Ke(n,t,e){return bt(n,t).getCaretRect(t,e)}function p8(n,t){var r,i;const e=bt(n,t);return(i=(r=e.getOptions)==null?void 0:r.call(e,n))!=null?i:{name:rt(t)}}function hg(n,t){var r;const e=bt(n,t);return(r=e.getBlockProperties)==null?void 0:r.call(e,n,t)}function Ed(n,t){var i,s;const e=bt(n,t),o=(i=e.getBlockProperties)==null?void 0:i.call(e,n,t);let r={};o!=null&&o.blockCommands&&(r={...o.blockCommands});for(const l of n.blockHooks){const c=(s=l.commands)==null?void 0:s.call(l,n,t);c&&(r[c.group]=c)}return r}function fg(n,t,e){var s,l,c,a;const o=bt(n,t),r=(s=o.getBlockProperties)==null?void 0:s.call(o,n,t);let i={};r!=null&&r.blockCommands&&(i={...r.blockCommands});for(const u of n.blockHooks){const f=(l=u.commands)==null?void 0:l.call(u,n,t);f&&(i[f.group]=f)}return(a=(c=i[e])==null?void 0:c.commands)!=null?a:[]}const mg=w("embed-block-common");function Te(n){return rt(n)==="embed"}function Oe(n){d(mg,Te(n),"not an embed block");const t=n.getAttribute("data-embed-type");return d(mg,t,"no embed data type"),t}function C8(n,t){return n.editorEmbeds.getEmbedClass(Oe(t))}function Fo(n,t){return n.editorEmbeds.getEmbedClass(t)}async function Id(n,t,e,o,r){const i=Fo(n,t);if(!i.getOptions)return null;const s=i.getOptions(n);if(!s.insertEmbedCommandItems||!s.insertEmbedCommandItems||s.insertEmbedCommandItems.length===0||!s.handleInsertEmptyEmbed)return null;const l=s.insertEmbedCommandItems[0];return s.handleInsertEmptyEmbed(n,{item:l,containerId:e,blockIndex:o,data:r})}function b8(n,t,e,o,r){var l,c;const i=(c=(l=Er(n,t)).getOptions)==null?void 0:c.call(l,n);if(!i||!i.insertBlockCommandItems||i.insertBlockCommandItems.length===0||!i.handleInsertEmptyBlock)return null;const s=i.insertBlockCommandItems[0];return i.handleInsertEmptyBlock(n,{item:s,containerId:e,blockIndex:o,data:r})}const v8=w("execute-block-command");function gg(n,t,e,o){var a;d(v8,Te(t),"not a embed block");const r=Oe(t),i=Fo(n,r);if(!i.getOptions)return;const s=(a=i.getBlockProperties)==null?void 0:a.call(i,n,t),l=s==null?void 0:s.blockCommands;if(!l)return;const c=Object.entries(l);for(const u of c)if(u[0]===e)return u[1].executeCommand(n,t,o)}function pg(n,t,e,o){const r=Ed(n,t);if(!r)return;const i=Object.entries(r);for(const s of i)if(s[0]===e)return s[1].executeCommand(n,t,o)}const k8=w("complex-block-position");class Je{constructor(t,e,o){h(this,"blockId");h(this,"childContainerId");h(this,"custom");t instanceof HTMLElement?this.blockId=q(t):(d(k8,typeof t=="string",`not a valid block id: ${t}`),this.blockId=t),this.childContainerId=e,o!==void 0&&(this.custom=o)}isSimple(){return!1}}const y8=w("simple-block-position");class qt{constructor(t,e,o){h(this,"blockId");h(this,"offset");h(this,"type");t instanceof HTMLElement?this.blockId=q(t):(d(y8,typeof t=="string",`not a valid block id: ${t}`),this.blockId=t),this.offset=e,this.type=o}isSimple(){return!0}}const xd=w("editor-position");function P(n,t,e){return new qt(n,t,e)}function wt(n,t,e){return new Je(n,t,e)}function Ir(n){return n instanceof qt}function Td(n){return n instanceof Je}function Sd(n,t,e){if(Ir(t)&&Ir(e)){const o=t,r=e;if(o.blockId===r.blockId)return o.offset-r.offset;const i=n.getBlockById(t.blockId),s=n.getBlockById(e.blockId);return d(xd,i!==s,"comparePosition: blocks are the same"),fl(i,s)}if(Td(t)&&Td(e)){const o=t,r=e;if(o.childContainerId===r.childContainerId)return 0;const i=n.getContainerById(o.childContainerId),s=n.getContainerById(r.childContainerId);return d(xd,i!==s,"comparePosition: containers are the same"),fl(i,s)}return d(xd,!1,"invalid "),0}const Il=w("simple-range");class ce{constructor(t,e){h(this,"editor");h(this,"_anchor");h(this,"_focus");h(this,"reverse");this.editor=t,this._anchor=e.anchor,this._focus=e.focus,this.reverse=Sd(this.editor,this._anchor,this._focus)>0}isCollapsed(){return this.start.blockId===this.end.blockId&&this.start.offset===this.end.offset}isEqual(t){if(!(t instanceof ce))return!1;const e=t,{start:o,end:r}=e;return this.start.blockId===o.blockId&&this.start.offset===o.offset&&this.start.type===o.type&&this.end.blockId===r.blockId&&this.end.offset===r.offset&&this.end.type===r.type}isSimple(){return!0}isReverse(){return this.reverse}getEditor(){return this.editor}get start(){return this.reverse?this._focus:this._anchor}get end(){return this.reverse?this._anchor:this._focus}get anchor(){return this._anchor}get focus(){return this._focus}getSelectedBlocks(){const{editor:t}=this,e=t.getBlockById(this.start.blockId),o=t.getBlockById(this.end.blockId);d(Il,e,"no start block"),d(Il,o,"no end block");const r=H(e),i=H(o);d(Il,r===i,"invalid range");const s=[];if(e===o)s.push({block:e,start:this.start,end:this.end});else{const l=J(e),c=J(o);d(Il,l<c,"invalid range, start > index"),s.push({block:e,start:this.start,end:P(e,W(this.editor,e),"end")});const a=Mt(r);for(let u=l+1;u<c;u+=1){const f=a[u];s.push({block:f,start:P(f,0,"home"),end:P(f,W(this.editor,f),"end")})}s.push({block:o,start:P(o,0,"home"),end:this.end})}return s}getSelectedContainers(){return[]}getAnchorPos(){return this.isReverse()?this.end:this.start}getFocusedPos(){return this.isReverse()?this.start:this.end}clone(){return new ce(this.editor,this)}toDocRange(){return{anchor:this.anchor,focus:this.focus}}}w("unknown-block");function w8(n,t,e,o,r){A(o,"unknown-block");const i=ro(o,"div");return i.innerText=`unknown block (${r.type}): ${JSON.stringify(r)}`,i}function B8(n){return 1}function E8(n,t,e,o){return null}function I8(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t))return null;const i=q(t),s=P(i,0,"home"),l=P(i,1,"end");return new ce(n,{anchor:s,focus:l})}function x8(n,t){const o=it(n).getBoundingClientRect();return new DOMRect(o.left+o.width/2,o.top,1,o.height)}function T8(n,t,e,o){A(t,"selected")}function S8(n){n.rootContainer.querySelectorAll("div.unknown-block[data-type=editor-block]").forEach(t=>{z(t,"selected")})}function D8(n,t,e,o){return`[unknown block, ${t.type}]`}const L8={blockType:"unknown-block",blockKind:"embed",createBlockContent:w8,getBlockTextLength:B8,getRangeFromPoint:I8,moveCaret:E8,getCaretRect:x8,updateSelection:T8,clearSelection:S8,convertTo:D8},Dd=w("editor-blocks");class Cg{constructor(t){h(this,"blocks",new Map);this.editor=t}registerBlockClass(t){const e=t.blockType,o=this.blocks.get(e);d(Dd,!o,`duplicated block type: ${e}`),this.blocks.set(e,t)}getBlockClass(t){const e=this.blocks.get(t);return d(Dd,e,`unknown block type: ${t}`),e}hasBlock(t){return this.blocks.has(t)}createBlock(t,e,o){const r=zm(this.editor,t,o);let i;this.hasBlock(o.type)?i=this.getBlockClass(o.type):i=this.registerUnknownBlock(o.type);const s=i.createBlockContent(this.editor,t,e,r,o);return s.parentElement!==r&&(Dd.warn("content parent is not block"),r.appendChild(s)),this.editor.blockHooks.forEach(l=>{var c;(c=l.create)==null||c.call(l,this.editor,t,e,r,o)}),r}forEach(t){this.blocks.forEach(t)}registerUnknownBlock(t){const e={...L8,blockType:t};return this.editor.editorBlocks.registerBlockClass(e),e}}const bg=w("editor-embeds");class vg{constructor(t){h(this,"objects",new Map);this.editor=t}registerEmbedClass(t){const e=t.embedType,o=this.objects.get(e);d(bg,!o,`duplicated embed object type: ${e}`),this.objects.set(e,t)}getEmbedClass(t){const e=this.objects.get(t);return d(bg,e,`unknown embed type: ${t}`),e}getEmbedClassFromBlock(t){return this.getEmbedClass(Oe(t))}forEach(t){this.objects.forEach(t)}}const kg=w("embed-block");function M8(n,t,e,o,r){const i=ro(o,"div");d(kg,r.type==="embed",`not an embed data: ${JSON.stringify(r)}`);const s=r;return d(kg,s.embedType&&s.embedData,`not an embed data: ${JSON.stringify(s)}`),n.editorEmbeds.getEmbedClass(s.embedType).createEmbedContent(n,i,s,t,e,o),o.setAttribute("data-embed-type",s.embedType),i}function R8(n){return 1}function A8(n,t,e,o){return null}function O8(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t))return null;const i=q(t),s=P(i,0,"home"),l=P(i,1,"end");return new ce(n,{anchor:s,focus:l})}function _8(n,t){const o=it(n).getBoundingClientRect();return new DOMRect(o.left+o.width/2,o.top,1,o.height)}function N8(n,t,e,o){A(t,"selected")}function $8(n){n.rootContainer.querySelectorAll("div.embed-block[data-type=editor-block][data-block-type=embed]").forEach(t=>{z(t,"selected")})}function P8(n,t,e){let o=null;return n.editorEmbeds.forEach(r=>{var s,l;const i=(l=(s=r.convertFrom)==null?void 0:s.call(r,n,t,e))!=null?l:null;i&&(o=i)}),o}function j8(n,t,e,o){const r=Fo(n,t.embedType);return r.convertTo?r.convertTo(n,t,e,o):""}function H8(n,t){const e=C8(n,t);return e.getBlockProperties?e.getBlockProperties(n,t):{}}function F8(n){const t=new Map,e=[];return n.editorEmbeds.forEach(o=>{if(o.getOptions){const r=o.getOptions(n);r.insertEmbedCommandItems&&r.insertEmbedCommandItems.forEach(i=>{e.push(i),t.set(i.id,o)})}}),{name:"EmbedBlock",insertBlockCommandItems:e,async handleInsertEmptyBlock(o,r){const i=t.get(r.item.id);if(!i||!i.getOptions)return null;const s=i.getOptions(o);return s.handleInsertEmptyEmbed?s.handleInsertEmptyEmbed(o,r):null}}}function z8(n,t,e,o){const r=Oe(t),i=Fo(n,r);!i.handleDeleteBlock||i.handleDeleteBlock(n,t,e,o)}function U8(n,t,e){const o=Oe(t),r=Fo(n,o);return r.handleUpdateBlock?r.handleUpdateBlock(n,t,e):!1}function V8(n,t,e,o,r){const i=Oe(t),s=Fo(n,i);if(s.handleDropOver)return s.handleDropOver(n,t,e,o,r)}function q8(n,t,e,o,r){const i=Oe(t),s=Fo(n,i);if(s.handleDrop&&n.isWritable())return s.handleDrop(n,t,e,o,r)}const yg={blockType:"embed",blockKind:"embed",createBlockContent:M8,getBlockTextLength:R8,getRangeFromPoint:O8,moveCaret:A8,getCaretRect:_8,updateSelection:N8,clearSelection:$8,convertFrom:P8,convertTo:j8,getBlockProperties:H8,getOptions:F8,handleDeleteBlock:z8,handleUpdateBlock:U8,handleDropOver:V8,handleDrop:q8},ae=w("complex-block-helper");function Se(n,t){return xe(n,t).getChildContainers(n,t)}function xr(n,t,e,o){return e.isSimple()?(d(ae,o.isSimple(),"invalid start and end position"),Se(n,t)):(d(ae,!e.isSimple(),"invalid start pos"),d(ae,!o.isSimple(),"invalid end pos"),xe(n,t).getSelectedContainers(n,t,e,o))}function W8(n,t){if(J(t)!==0)return!1;const e=F(H(t));if(!e)return!1;d(ae,at(n,e),"not a complex block");const o=H(t),i=Se(n,e).indexOf(o);return d(ae,i>=0,"not valid child container"),i===0}function Ld(n,t){const e=Se(n,t);if(e.length===0)return null;const o=e[0],r=Vt(o);return at(n,r)?Ld(n,r):r}function Ni(n,t){const e=Se(n,t);if(e.length===0)return null;const o=e[e.length-1],r=Qt(o);return at(n,r)?Ni(n,r):r}function wg(n,t){d(ae,Ye(t),"not a child container");const e=F(t);d(ae,e,"no parent block"),d(ae,at(n,e),"not a complex block");const o=Se(n,e),r=o.indexOf(t);if(d(ae,r!==-1,"child container not found"),r===0){const l=gt(e);return l?at(n,l)?Ni(n,l):l:null}const i=o[r-1],s=Qt(i);return at(n,s)?Ni(n,s):s}function Bg(n,t){d(ae,at(n,t),"not a complex block");const e=Se(n,t);if(d(ae,e.length>0,"no child container"),e.length===1)return e;const o=e[0],r=o.getBoundingClientRect();let i=r.left,s=r.right;const l=[o];for(let c=1;c<e.length;c++){const a=e[c],u=a.getBoundingClientRect();if(u.right<=i){l.push(a),i=u.left;continue}if(u.left>=s){s=u.right;continue}}return l}function Eg(n,t){d(ae,at(n,t),"not a complex block");const e=Se(n,t);if(d(ae,e.length>0,"no child container"),e.length===1)return e;const o=e[e.length-1],r=o.getBoundingClientRect();let i=r.left,s=r.right;const l=[o];for(let c=e.length-2;c>=0;c--){const a=e[c],u=a.getBoundingClientRect();if(u.right<=i){l.push(a),i=u.left;continue}if(u.left>=s){s=u.right;continue}}return l}function Ig(n,t,e,o){const r=t.getBoundingClientRect(),i=o<r.top,s=i?Bg(n,t):Eg(n,t);let l=s[0],c=Cn(l.getBoundingClientRect(),e,o);for(let a=1;a<s.length;a++){const u=s[a],f=u.getBoundingClientRect(),m=Cn(f,e,o);m<c&&(l=u,c=m)}return i?Vt(l):Qt(l)}function xl(n,t,e,o){const r=q(t);d(ae,r===e.blockId,"invalid start pos"),d(ae,r===o.blockId,"invalid end pos");const i=xe(n,t);return i.adjustSelectionPos?i.adjustSelectionPos(n,t,e,o):{anchor:e,focus:o}}class Xe{constructor(t,e){h(this,"editor");h(this,"reverse");h(this,"_anchor");h(this,"_focus");this.editor=t,this._anchor=e.anchor,this._focus=e.focus,this.reverse=Sd(this.editor,this._anchor,this._focus)>0}isCollapsed(){return!1}isEqual(t){if(!(t instanceof Xe))return!1;const e=t,{anchor:o,focus:r}=e;return this._anchor.blockId===o.blockId&&this._anchor.childContainerId===o.childContainerId&&this._focus.blockId===r.blockId&&this._focus.childContainerId===r.childContainerId&&this._anchor.custom===o.custom&&this._focus.custom===r.custom}isReverse(){return this.reverse}isSimple(){return!1}getEditor(){return this.editor}get anchor(){return this._anchor}get focus(){return this._focus}get start(){return this.reverse?this._focus:this._anchor}get end(){return this.reverse?this._anchor:this._focus}getSelectedBlocks(){const t=this.start,e=this.end;return[{block:this.editor.getBlockById(t.blockId),start:t,end:e}]}getAnchorPos(){return this._anchor}getFocusedPos(){return this._focus}getSelectedContainers(){const t=this.editor.getBlockById(this._anchor.blockId);return xr(this.editor,t,this.start,this.end)}clone(){return new Xe(this.editor,this)}toDocRange(){return{anchor:this._anchor,focus:this._focus}}}const G8=w("selection-range");function Wt(n,t){const{anchor:e,focus:o}=t;return e instanceof qt&&o instanceof qt?new ce(n,{anchor:e,focus:o}):(d(G8,e instanceof Je&&o instanceof Je,"start position type does not math end type"),new Xe(n,{anchor:e,focus:o}))}function At(n,t,e,o){const r=new qt(t,e,"normal"),i=new qt(t,o!=null?o:e,"normal");return Wt(n,{anchor:r,focus:i})}function Z8(n){return!!n.anchor.childContainerId}function io(n,t){var r,i;if(Z8(t)){const s=wt(t.anchor.blockId,t.anchor.childContainerId,(r=t.anchor)==null?void 0:r.custom),l=wt(t.focus.blockId,t.focus.childContainerId,(i=t.focus)==null?void 0:i.custom);return Wt(n,{anchor:s,focus:l})}const e=P(t.anchor.blockId,t.anchor.offset,"normal"),o=P(t.focus.blockId,t.focus.offset,"normal");return Wt(n,{anchor:e,focus:o})}const Y8=w("range-from-point");function Tl(n,t,e){const o=[0,-12,12];for(let r=0;r<o.length;r++){const i=document.elementsFromPoint(t,e+o[r])[0];if(!i||!n.rootContainer.contains(i))continue;const s=F(i);if(!s||!n.contains(s))continue;const l=bt(n,s).getRangeFromPoint(n,s,t,e+o[r]);if(l)return l}return null}function xg(n,t,e,o){const r=t.getBoundingClientRect();if(o<=r.top){const l=Vt(t),c=P(l,0,"home");return new ce(n,{anchor:c,focus:c})}const i=Qt(t),s=P(i,W(n,i),"end");return new ce(n,{anchor:s,focus:s})}function Tg(n,t,e){const o=Tl(n,t,e);if(o){if(o instanceof ce)return o;d(Y8,o instanceof Xe,`invalid range type: ${typeof o}`);const c=o,a=n.getContainerById(c.start.childContainerId);return xg(n,a,t,e)}const r=document.elementsFromPoint(t,e)[0];if(!r)return null;const{children:i}=r,s=Array.from(i).filter(c=>bn(c));if(s.length===0)return null;const l=s.reduce((c,a)=>{const u=c.getBoundingClientRect(),f=a.getBoundingClientRect();return Cn(u,t,e)>Cn(f,t,e)?a:c});return xg(n,l,t,e)}function Md(n,t){const e=[];return Mt(t).forEach(r=>{e.push(r),at(n,r)&&Se(n,r).forEach(s=>{e.push(...Md(n,s))})}),e}function Rd(n,t){let e=Md(n,n.rootContainer);return t!=null&&t.simpleBlockOnly&&(e=e.filter(o=>!at(n,o))),e}function tn(n,t){const e=n.selection.range.getSelectedBlocks(),o=[];for(const r of e)o.push(r),at(n,r.block)&&xr(n,r.block,r.start,r.end).forEach(s=>{const c=Md(n,s).map(a=>({block:a,start:P(a,0,"home"),end:P(a,W(n,a),"home")}));o.push(...c)});return t!=null&&t.simpleBlockOnly?o.filter(r=>!at(n,r.block)):o}const ez="",jn=w("text-block-child");function $i(n){return n.tagName==="SPAN"}function _e(n){return d(jn,$i(n),"not a valid text child"),n.getAttribute("data-type")==="editor-box"}function Hn(n){return d(jn,$i(n),"not a valid text child"),n.getAttribute("data-type")==="editor-insertion"}function Pi(n){return!_e(n)&&!Hn(n)}function Sg(n){return d(jn,$i(n),"not a valid text child"),_e(n)?"box":Hn(n)?"insertion":"text"}function Ne(n){const t=Sg(n);return t==="insertion"?0:t==="box"?1:(d(jn,n.textContent!==null,"text block content is undefined"),d(jn,n.textContent.length>=0,"text block content length is negative"),n.textContent.length)}function Fn(n){const t=it(n),e=Array.from(t.children);return e.forEach(o=>{d(jn,$i(o),"not a valid text child")}),e}function Sl(n,t){const e=Fn(n);let o=0;for(let r=0;r<e.length;r++){const i=e[r],s=Ne(i);if(o+s<t){o+=s;continue}if(o===t)return{prev:e[r-1],next:i,offset:0};if(o+s===t)return{prev:i,next:e[r+1],offset:0};const l=t-o;return d(jn,l>0,"invalid offset value"),d(jn,!_e(i),"invalid box child"),{prev:i,next:i,offset:l}}d(jn,!1,`invalid block child at position: ${t}`)}const Kt=w("text-range");function Q8(n,t){const e=(i,s)=>{if(Hn(i))return d(Kt,s===0,`invalid offset for insertion child: ${s}`),{child:i,container:i,offset:2};if(_e(i))return d(Kt,s===0||s===1,`invalid offset for box: ${s}`),{child:i,container:i,offset:s===0?1:2};const l=i.firstChild;return d(Kt,l,"no child node for text child"),d(Kt,l instanceof Text||l instanceof HTMLBRElement,`invalid child for text child, ${l.nodeName}`),l instanceof HTMLBRElement?(d(Kt,s>=0&&s<=0,"invalid offset for text child"),{child:i,container:l,offset:s}):(d(Kt,s>=0&&s<=l.data.length,"invalid offset for text child"),{child:i,container:l,offset:s})};let o=0;const r=Fn(n);for(let i=0;i<r.length;i++){const s=r[i],l=Ne(s);if(t===o)return[e(s,0)];if(t<o+l)return[e(s,t-o)];if(t===o+l){const c=[];c.push(e(s,Ne(s)));const a=r[i+1];return a&&c.push(e(a,0)),c}o+=l}d(Kt,!1,"failed to get range info")}function K8(n,t,e){if(t===e?d(Kt,Hn(n),"only insertion child can be zero offset"):d(Kt,t<e,`invalid start & end: ${t}, ${e}`),Hn(n)){d(Kt,t===e,`invalid insertion child range offset: ${t}, ${e}`),d(Kt,t===0,`invalid insertion child range start: ${t}`);const i=n;return d(Kt,i.children.length===3,`invalid insertion dom, children.length = ${i.children.length}`),ul(i,1,i,2)}if(_e(n)){d(Kt,t+1===e,`invalid box child range offset: ${t}, ${e}`),d(Kt,t===0,`invalid box child range start: ${t}`);const i=n;return d(Kt,i.children.length===3,`invalid box dom, children.length = ${i.children.length}`),ul(i,1,i,2)}const o=Ne(n);d(Kt,e<=o,`invalid child end: ${e}, ${o}`);const r=n.firstChild;return d(Kt,r instanceof Text,"invalid block text child"),d(Kt,r.data.length>=e,`invalid range end: ${e}, ${r.data.length}`),ul(r,t,r,e)}const en=w("caret-rect");function J8(n,t){if(fd(t)){const e=t,o=gd(e);if(e.getAttribute("data-box-type")==="br"){const r=it(n),i=Number.parseFloat(window.getComputedStyle(r).lineHeight)||o.getBoundingClientRect().height,s=Array.from(o.getClientRects());d(en,s.length>0,"no box client rects");const l=r.getBoundingClientRect(),c=s[0],a=new DOMRect(l.left,c.bottom,1,i);return s.push(a),s}return o.getClientRects()}return pd(t).getClientRects()}function De(n,t){var l,c;const e=Q8(n,t.offset);if(e[1]&&e[0].child!==((l=e[1])==null?void 0:l.child)){if(t.type==="end"){const u=Mo(e[0].child);return new DOMRect(u.right,u.top,1,u.height)}d(en,e[1],"invalid ranges");const a=hl(e[1].child);return new DOMRect(a.left,a.top,1,a.height)}let r=e[0];if(d(en,e.length>=1,"failed to get block range"),e.length===1)r=e[0];else{if(d(en,e.length>=2,`invalid range info length: ${e.length}`),Hn(e[e.length-1].child)){r=e[e.length-1];const a=r.child,f=pd(a).getClientRects();d(en,f.length>=1,"no client rects for box content");const m=f[f.length-1];return new DOMRect(m.right,m.y,1,m.height)}t.type==="home"?r=e[1]:t.type==="end"||Pi(e[0].child)?r=e[0]:Pi(e[1].child)&&(r=e[1])}if(r.container instanceof HTMLBRElement){d(en,t.offset===0,"invalid offset for empty block text");const a=(c=r.container.parentElement)==null?void 0:c.parentElement;d(en,a===it(n),"invalid br parent, is not block parent");const u=a.getBoundingClientRect();return new DOMRect(u.left,u.top,1,u.height)}const s=em(r.container,r.offset).getClientRects();if(s.length===0){d(en,!Pi(r.child),"only box or insertion child range has zero client rect"),d(en,r.offset===1||r.offset===2,"invalid offset for box or insertion child");const a=r.child,u=J8(n,a);if(d(en,u.length>=1,"no client rects for box content"),r.offset===1){const m=u[0];return new DOMRect(m.x,m.y,1,m.height)}const f=u[u.length-1];return t.type==="end"||r.offset===2?new DOMRect(f.right,f.y,1,f.height):new DOMRect(f.x,f.y,1,f.height)}return d(en,s.length>0,"no client rects for range"),t.type==="home"?s[s.length-1]:s[0]}const X8=w("core");function zo(n,t,e,o){const r=Rt(t);let i=r.querySelector(`.block-anchor[data-id=${e}]`);i||(i=b("div",["block-anchor"],r),i.setAttribute("data-id",e));const s=o!=null?o:t.getBoundingClientRect(),l=t.getBoundingClientRect(),c=new DOMRect(s.left-l.left,s.top-l.top,s.width,s.height);return i.style.left=`${c.left}px`,i.style.top=`${c.top}px`,i.style.width=`${c.width}px`,i.style.height=`${c.height}px`,i}function Dg(n,t,e,o){d(X8,j(n,t),"not a text kind block");const r=De(t,P(t,e,"normal")),i=t.getBoundingClientRect(),s=Rt(t);let l=s.querySelector(`.block-anchor[data-id=${o}]`);l||(l=b("div",["block-anchor"],s),l.setAttribute("data-id",o));const c=new DOMRect(r.left-i.left,r.top-i.top,r.width,r.height);return l.style.left=`${c.left}px`,l.style.top=`${c.top}px`,l.style.width=`${c.width}px`,l.style.height=`${c.height}px`,l}function ji(n){const t=Fn(n);let e=0;return t.forEach(o=>{e+=Ne(o)}),e}const Lg=w("box");function Hi(n){return!n.attributes||!n.attributes.box?!1:(d(Lg,n.attributes.box===!0,`invalid op attribute box property, ${n.attributes.box}`),d(Lg,n.attributes.type,`no box type: ${JSON.stringify(n)}`),!0)}const Mg=w("rich-text-length");function Ad(n){return d(Mg,typeof n.insert=="string","op.insert is not string"),n.insert.length}function de(n){let t=0;return n.forEach(e=>{e.insert&&(d(Mg,typeof e.insert=="string","op.insert is not string"),t+=Ad(e))}),t}const vn=w("split-text");function be(n,t,e){if(n=Y.default(n),t===0)return{left:[],right:n};if(t===-1)return{left:n,right:[]};let o=0;for(let r=0;r<n.length;r++){const i=n[r];d(vn,typeof i=="object",`invalid op type, ${typeof i}`),d(vn,typeof i.insert=="string",`invalid op.insert type, ${typeof i.insert}`);const s=Ad(i);if(o+s<t)o+=s;else{if(o+s===t)return{left:n.slice(0,r+1),right:n.slice(r+1)};{d(vn,o+s>t,`invalid offset, ${o}, ${s}, ${t}`);const l=t-o,c=Y.default(i);d(vn,c.insert,"no copied.insert"),d(vn,typeof c.insert=="string","invalid copied.insert type"),c.insert=c.insert.substr(0,l),i.insert=i.insert.substr(l),c.insert===""&&d(vn,!1,"invalid copied.insert, is empty string"),i.insert===""&&d(vn,!1,"invalid op.insert, is empty string");const a=[i,...n.slice(r+1)],u=[...n.splice(0,r),c];return e&&(e.sourceOp=i),{left:u,right:a}}}}throw new Error(`invalid split offset: ${t}, ${JSON.stringify(n)}`)}function Gt(n,t,e){d(vn,t>=0,"invalid offset, < 0"),d(vn,e>0,"invalid length, <= 0"),d(vn,t+e<=de(n),"invalid offset + length < text length");const{left:o,right:r}=be(n,t+e),{left:i,right:s}=be(o,t);return{left:i,middle:s,right:r}}function Rg(n,t){const e=Array.from(new Set(t)).sort((i,s)=>i-s),o=[];let r=n;for(let i=e.length-1;i>=0;i--){const s=e[i],{left:l,right:c}=be(r,s);r=l,o.unshift(c)}return r.length>0&&o.unshift(r),o}function Ag(n,t,e){return Gt(n,t,e).middle}const Tr=w("text-block-content");function tb(n,t,e,o,r){if(d(Tr,o,"no text for block"),o.length===0&&(!r||r.size===0)){e.innerHTML="<span><br></span>";return}const i=[];r&&i.push(...r.keys());const s=f=>n.editorInsertions.createInsertion(e,f),l=(f,m)=>{const C=r==null?void 0:r.get(m);C&&(C.forEach(v=>{f.appendChild(s(v))}),r==null||r.delete(m))},c=document.createDocumentFragment();let a=0;const u=Rg(o,i);for(let f=0;f<u.length;f++){l(c,a);const m=u[f];a+=de(m);for(let C=0;C<m.length;C++){const v=m[C];if(Hi(v)){d(Tr,v.attributes,`op is not an valid box: ${JSON.stringify(v)}`);const y=n.editorBoxes.createBox(e,v.attributes);d(Tr,y instanceof HTMLSpanElement,`invalid box element: ${y.tagName}`),c.appendChild(y);continue}d(Tr,v.insert,`no insert in op: ${JSON.stringify(v)}`);const B=b("span",["text"],c,v.insert);if(v.attributes){const y=n.editorBlockRenders.renderText(t,v.attributes);y.classes&&A(B,...y.classes),y.attributes&&Object.entries(y.attributes).forEach(([S,I])=>{B.setAttribute(S,I)}),y.styles&&Object.entries(y.styles).forEach(([S,I])=>{B.style.setProperty(S,I)})}c.appendChild(B)}}l(c,a),e.innerHTML="",e.appendChild(c)}function Dl(n,t,e,o,r){const{text:i,insertions:s}=n.editorDecorators.decorateText(t,r),l=n.compositingText;if(l){const c=n.selection.range.start;d(Tr,c.isSimple(),"not an simple position while compositing"),c.blockId===e&&s.set(c.offset,[{type:"inputting",id:N(),text:l}])}return tb(n,t,o,i,s)}function eb(n){const t=n.rootContainer.querySelectorAll('span[data-type="editor-insertion"].inputting-insertion');t.length&&Tr.debug(`remove ${t.length} temp composition span`),Array.from(t).forEach(e=>e.remove())}const kn=w("client-rects");function nb(n){const t=Fn(n);let e=0;const o=[];for(let r=0;r<t.length;r++){const i=t[r],s=Ne(i);o.push({child:i,startBlockOffset:e,endBlockOffset:e+s}),e+=s}return o}function ob(n,t,e,o){d(kn,e<o,`invalid from & to: ${e}, ${o}`);const r=W(n,t);d(kn,e>=0&&o>=0&&e<=r&&o<=r,`invalid offset: ${e}, ${o}, length: ${r}`);const i=nb(t),s=i.findIndex(C=>C.startBlockOffset<=e&&e<C.endBlockOffset),l=i.findIndex(C=>C.startBlockOffset<o&&o<=C.endBlockOffset);if(d(kn,s!==-1,"failed to find start child"),d(kn,l!==-1,"failed to find end child"),d(kn,s<=l,`invalid start index & end index: ${s}, ${l}`),s===l){const C=i[s];return[{child:C.child,startChildOffset:e-C.startBlockOffset,endChildOffset:o-C.startBlockOffset}]}const c=[],a=i[s],u={child:a.child,startChildOffset:e-a.startBlockOffset,endChildOffset:Ne(a.child)};c.push(u);for(let C=s+1;C<l;C++){const v=i[C],B={child:v.child,startChildOffset:0,endChildOffset:v.endBlockOffset-v.startBlockOffset};c.push(B)}const f=i[l],m={child:f.child,startChildOffset:0,endChildOffset:o-f.startBlockOffset};return c.push(m),c}function rb(n){const t=(o,r)=>o.left<=r.left&&o.top<=r.top&&o.right>=r.right&&o.bottom>=r.bottom&&(o.width!==r.width||o.height!==r.height);n=n.filter(o=>!n.find(i=>t(o,i)));const e=[];return n=n.filter(o=>e.find(r=>r.left===o.left&&r.top===o.top&&r.width===o.width&&r.height===o.height)?!1:(e.push(o),!0)),n}function Og(n,t,e,o){if(W(n,t)===0){const u=it(t).getBoundingClientRect();return[new DOMRect(u.left,u.top,4,u.height)]}const r=e.offset,i=o.offset;if(r===i)return[De(t,e)];const l=ob(n,t,r,i).map(a=>K8(a.child,a.startChildOffset,a.endChildOffset)),c=[];return l.forEach(a=>{const u=rb(Array.from(a.getClientRects()));c.push(...u)}),c}function ib(n,t,e){d(kn,e instanceof ce,"invalid range");const o=e.start,r=e.end;return d(kn,o.isSimple(),"text block only allow simple position"),d(kn,r.isSimple(),"text block only allow simple position"),d(kn,o.blockId===r.blockId,"only allow update one text block selection"),d(kn,o.blockId===q(t),"only allow update one text block selection"),Og(n,t,o,r)}const Od=w("selection-background");function sb(n,t,e,o){d(Od,e.isSimple(),"text block only allow simple position"),d(Od,o.isSimple(),"text block only allow simple position"),d(Od,e.blockId===o.blockId,"only allow update one text block selection");const r=e.offset,i=o.offset;if(r===i&&(W(n,t)!==0||n.selection.range.isCollapsed()))return;const s=Og(n,t,e,o),l=t.getBoundingClientRect(),c=Fm(t);c.innerHTML="",s.forEach(a=>{const u=b("div",["editor-selection-background"],c);u.style.left=`${a.left-l.left}px`,u.style.top=`${a.top-l.top}px`,u.style.width=`${a.width}px`,u.style.height=`${a.height}px`})}function lb(n){n.rootContainer.querySelectorAll("div[data-type=block-background]").forEach(t=>{t.remove()})}const Uo=w("text-offset"),_g="\u200D";function so(n,t){const e=Fn(n);let o=0;for(let r=0;r<e.length;r++){const i=e[r],s=Ne(i);if(i===t){const l=o+s;return{start:o,end:l}}o+=s}d(Uo,!1,"can not find child in children")}function re(n,t){d(Uo,t>=0,`invalid offset: ${t}`);const e=Sl(n,t),{prev:o,next:r,offset:i}=e;if(!o&&!r&&d(Uo,!1,"invalid offset, no prev & next child at offset"),o!==r)return!0;const s=o;if(d(Uo,s,"no child"),_e(s))return d(Uo,i===0||i===1,`invalid box child offset: ${i}`),!0;const l=s.textContent;d(Uo,l,"no content for text child");const c=l.charAt(i-1),a=l.charAt(i);return!(c===_g||a===_g||Ya(l[i]))}function lo(n,t){if(t===0)return 0;const e=t-1;if(re(n,e))return e;let o=e-1;for(;!re(n,o);)o-=1;return o}function Vo(n,t){const e=ji(n);if(d(Uo,t>=0&&t<=e,`invalid offset: ${t}, ${e}`),t===e)return e;const o=t+1;if(re(n,o))return o;let r=o+1;for(;!re(n,r);)r+=1;return r}const qo=w("line-breaker");function Fi(n){const t=c=>{const a=hl(c);return Mo(c).top>a.top+a.height/2},e=(c,a)=>{const u=Mo(c);return hl(a).left<u.right},o=(c,a)=>{const u=Mo(c),f=Mo(a);return f.top+f.height/2>u.bottom},r=c=>{if(c.length===0||c.length===1)return!1;const a=c[0],u=c[c.length-1];return a.right-u.left>10},i=[];let s=0;const l=Fn(n);for(let c=0;c<l.length;c++){const a=l[c];if(Hn(a)){const y=a,S=l[c+1];if(!S)break;const I=l[c-1];if(I&&o(I,y)&&i.push({offset:s,type:"betweenChild",childInfo:{prevChild:I,nextChild:y,wrap:"nextWrapped",prevWrapped:t(I),nextWrapped:t(y)}}),e(y,S)){i.push({offset:s,type:"betweenChild",childInfo:{prevChild:I,nextChild:y,wrap:"nowrap",prevWrapped:t(I),nextWrapped:t(y)}});continue}continue}if(_e(a)){const y=a,S=l[c+1];if(!S)break;const I=l[c-1];if(I&&o(I,y)&&i.push({offset:s,type:"betweenChild",childInfo:{prevChild:I,nextChild:y,wrap:"nextWrapped",prevWrapped:t(I),nextWrapped:t(y)}}),e(y,S)){s+=1,i.push({offset:s,type:"betweenChild",childInfo:{prevChild:I,nextChild:a,wrap:"nowrap",prevWrapped:t(I),nextWrapped:t(a)}});continue}s+=1;continue}const u=a,f=u.getClientRects();if(d(qo,f.length>0,"invalid text child dom"),f.length===1){const y=l[c+1];if(!y)break;if(e(u,y)){s+=Ne(u),i.push({offset:s,type:"betweenChild",childInfo:{prevChild:u,nextChild:y,wrap:"nowrap",prevWrapped:t(u),nextWrapped:t(y)}});continue}s+=Ne(u);continue}const m=u.firstChild;d(qo,m,"invalid text child, no text node"),d(qo,m instanceof Text,`invalid text child, not a valid text node: ${typeof m}`);const C=document.createRange(),v=document.createRange(),B=Ne(u);d(qo,m.data.length===B,"text node data length not equal child text length");for(let y=0;y<m.data.length;y++){if(!re(n,s+y))continue;C.setStart(m,y),od()&&C.selectNodeContents(m);const S=C.getClientRects();if(d(qo,S.length>=1,"invalid text node, no client rects"),r(S)){const Z=s+y;i.push({offset:Z,type:"textBreakWord",childInfo:{prevChild:a,nextChild:a,wrap:"nowrap",prevWrapped:t(a),nextWrapped:t(a)}});continue}let I=y+1;re(n,s+I)||(I=y+2),v.setStart(m,I);const M=v.getClientRects(),R=S[0];M[0].left<R.right&&d(qo,!1,"span pre-wrap should not has a line-wrap by white space")}s+=B}return i}function _d(n,t){const e=Fi(n);for(let o=0;o<e.length;o++){const{offset:r,type:i}=e[o];if(t.offset<r)return{lineIndex:o,lineBreaks:e};if(t.offset===r&&t.type==="end")return{lineIndex:o,lineBreaks:e}}return d(qo,t.offset<=ji(n),"invalid position, offset > block length"),{lineIndex:e.length,lineBreaks:e}}const cb=w("line-offset");function Nd(n){const t=Fi(n),e=[];let o=0;for(let r=0;r<t.length;r++){const i=t[r];e.push({start:o,end:i.offset}),o=i.offset}return e.push({start:o,end:ji(n)}),e}function Ll(n,t){const e=Nd(n);return d(cb,t>=0&&t<e.length,`invalid line index: ${t}, ${e.length}`),e[t]}function Ng(n,t){const{lineIndex:e}=_d(n,t);return Ll(n,e)}function ab(n){const t=Nd(n),e=n.getBoundingClientRect(),o=[];return t.forEach(({start:r,end:i})=>{const s=P(n,r,"home");let l=De(n,s);const c=P(n,i,"end"),a=De(n,c);l.top+l.height/2<a.top&&(l=new DOMRect(e.left-1e4,a.top,1,a.height));const u=new DOMRect(l.left,a.top,a.left-l.left,a.height),f=new DOMRect(e.left,a.top,e.width,a.height);o.push({start:r,end:i,rect:f,contentRect:u})}),o}function db(n,t,e){const r=ab(n).find(s=>Ao(s.rect,t,e));if(!r)return null;const i=r.contentRect;return t-i.left<i.right-t?P(n,r.start,"home"):P(n,r.end,"end")}function $g(n,t,e){const o=De(n,t),r=De(n,e),i=o.top+o.height/2,s=r.top+r.height/2,l=r.top<i&&i<r.bottom,c=o.top<s&&s<o.bottom;return l&&c}function Pg(n){return Nd(n).length}const Wo=w("find-text-position");function jg(n,t){const{start:e,end:o}=Ll(n,t),r=q(n),i=De(n,P(r,e,"home"));if(!(De(n,P(r,o,"end")).top>i.top+i.height/2))return!1;const c=Sl(n,e);return d(Wo,c.next,"no next child at offset"),d(Wo,!Pi(c.next),"next child is not text child"),!0}function ub(n,t){const e=q(n);d(Wo,jg(n,t),"line is not wrapped");const{start:o,end:r}=Ll(n,t),i=P(e,o,"home");for(let s=o+1;s<=r;s+=1){let l="normal";s===o?l="home":s===r&&(l="end");const c=P(e,s,l);if(!$g(n,i,c))return s-1}return d(Wo,!1,"failed to find wrapped offset"),0}function Ml(n,t,e,o,r,i,s){d(Wo,j(n,t),`not a text kind block: ${rt(t)}`);const{start:l,end:c}=Ll(t,e);let a=l;const u=q(t);if(t===o&&jg(t,e)){const y=ub(t,e);(i==="up"||i==="down"&&$g(t,r,P(u,l,"home")))&&(a=y+1)}let f=Number.MAX_SAFE_INTEGER;const m=Ke(n,o,r),C=s!=null?s:m.left+m.width/2,v=m.top+m.height/2;let B=P(u,a,"home");for(let y=a;y<=c;y++){if(!re(t,y))continue;let S="normal";y===l?S="home":y===c&&(S="end");const I=P(u,y,S),M=De(t,I),R=Cn(M,C,v);R<f&&(f=R,B=I)}return B}function hb(n,t,e,o,r){return d(Wo,j(n,t),"not a text block"),Ml(n,t,Pg(t)-1,e,o,"up",r)}function fb(n,t,e,o,r){return d(Wo,j(n,t),"not a text block"),Ml(n,t,0,e,o,"down",r)}function mb(n,t,e,o){const{lineIndex:r}=_d(t,e);if(r===Pg(t)-1)return null;const i=Ml(n,t,r+1,t,e,"down",o);return i||null}function gb(n,t){if(t.offset===0)return null;const e=Fi(n),o=e.find(r=>r.offset===t.offset);if(!o){const r=lo(n,t.offset);return e.find(s=>s.offset===r)?{offset:r,type:"home"}:{offset:r,type:"normal"}}if(o.type==="betweenChild"){if(t.type==="home"&&o.childInfo.wrap==="nowrap")return{offset:t.offset,type:"end"};if(o.childInfo.prevWrapped)return{offset:lo(n,t.offset),type:"normal"}}return{offset:lo(n,t.offset),type:"normal"}}function pb(n,t){const e=ji(n);if(t.offset===e)return null;const o=Fi(n),r=o.find(i=>i.offset===t.offset);if(!r){const i=Vo(n,t.offset),s=o.find(l=>l.offset===i);return s?s.type==="betweenChild"?{offset:i,type:"end"}:{offset:i,type:"home"}:{offset:i,type:"normal"}}return r.type==="betweenChild"?r.childInfo.wrap==="nowrap"&&t.type==="end"?{offset:t.offset,type:"home"}:{offset:Vo(n,t.offset),type:"home"}:{offset:Vo(n,t.offset),type:"normal"}}function Cb(n,t,e,o){const{lineIndex:r}=_d(t,e);if(r===0)return null;const i=Ml(n,t,r-1,t,e,"up",o);return i||null}const bb=w("move-caret");function vb(n,t,e,o){if(o==="ArrowLeft"){const r=gb(t,e);return r?P(q(t),r.offset,r.type):null}if(o==="ArrowRight"){const r=pb(t,e);return r?P(q(t),r.offset,r.type):null}if(o==="ArrowUp"){const r=Cb(n,t,e,n.selection.getSuggestedCaretX());return r?P(q(t),r.offset,r.type):null}if(o==="ArrowDown"){const r=mb(n,t,e,n.selection.getSuggestedCaretX());return r?P(q(t),r.offset,r.type):null}d(bb,!1,`invalid navigation direction: ${o}`)}const $d=w("text-range");function kb(n){const t=[];return Fn(n).forEach(o=>{const r=Array.from(o.getClientRects()).map(i=>({rect:i,child:o}));t.push(...r)}),t}function yb(n,t,e){const o=kb(n);for(let r=1;r<o.length;r++){const i=o[r-1],s=o[r];if(t>=i.rect.right&&t<=s.rect.left&&e>=i.rect.top&&e<=i.rect.bottom&&e>=s.rect.top&&e<=s.rect.bottom)return so(n,s.child).start}return null}function wb(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t))return null;const i=r.closest("div[data-type=block-content]>span");if(!i){const S=t.getBoundingClientRect();if(!Ao(S,e,o))return null;const I=yb(t,e,o);if(I!==null){const R=P(t,I,"normal");return new ce(n,{anchor:R,focus:R})}const M=db(t,e,o);return M?new ce(n,{anchor:M,focus:M}):null}const s=Fn(t);d($d,s.indexOf(i)!==-1,"failed to find child in children");const l=so(t,i);d($d,l,"failed to get child offset");const{start:c}=l;let a,u;Hn(i)||_e(i)?(a=c,u=0):(d($d,i.firstChild instanceof Text,"child is not text"),a=c+nm(i.firstChild,e,o),u=0);const f=q(t),C=Fi(t).find(S=>S.offset===a);let v="normal";if(C){const S=P(f,a,"home"),I=P(f,a,"end"),M=De(t,S),R=De(t,I),$=Cn(M,e,o),Z=Cn(R,e,o);v=$<Z?"home":"end"}const B=P(f,a,v);let y;return u&&(y=P(f,a+u,v)),new ce(n,{anchor:B,focus:y!=null?y:B})}const Bb=w("create-text-op");function $e(n,t){d(Bb,n,"text is empty");const e={insert:n};return t&&Object.keys(t).length>0&&(e.attributes=t),e}function Pd(n,t){if(n.length===0)return[];if(n.indexOf(`
15
+ animateScrollTo(scrollToElement:Element, options)`;e+=i.horizontalOffset,o+=i.verticalOffset;const f=u.getMaxHorizontalScroll(),m=u.getHorizontalScroll();e>f&&(e=f);const C=e-m,v=u.getMaxVerticalScroll(),B=u.getVerticalScroll();B<o?o-=window.innerHeight*3/4:o-=window.innerHeight*1/4,o>v&&(o=v);const y=o-B,S=Math.abs(Math.round(C/1e3*i.speed)),I=Math.abs(Math.round(y/1e3*i.speed));let M=S>I?S:I;return M<i.minDuration?M=i.minDuration:M>i.maxDuration&&(M=i.maxDuration),new Promise((R,$)=>{C===0&&y===0&&R(!0),$n.remove(u.element,!0);let Z;const ot=()=>{se(),cancelAnimationFrame(Z),R(!1)};$n.add(u.element,ot);const st=Ue=>Ue.preventDefault(),mt=i.cancelOnUserAction?ot:st,ut=i.cancelOnUserAction?{passive:!0}:{passive:!1},yt=["wheel","touchstart","keydown","mousedown"],se=()=>{yt.forEach(Ue=>{u.element.removeEventListener(Ue,mt,ut)})};yt.forEach(Ue=>{u.element.addEventListener(Ue,mt,ut)});const eo=Date.now(),ee=()=>{const Ue=Date.now()-eo,Eo=Ue/M,gr=Math.round(m+C*i.easing(Eo)),pr=Math.round(B+y*i.easing(Eo));Ue<M&&(gr!==e||pr!==o)?(u.scrollTo(gr,pr),Z=requestAnimationFrame(ee)):(u.scrollTo(e,o),cancelAnimationFrame(Z),se(),$n.remove(u.element,!1),R(!0))};Z=requestAnimationFrame(ee)})}function Ao(n,t,e){return n.left<=t&&t<=n.right&&n.top<=e&&e<=n.bottom}function F7(n){const t="\xA0";if(!n)return"";if(n===" ")return t;let e=n;return e.startsWith(" ")&&(e=t+e.substr(1)),e.endsWith(" ")&&(e=e.substr(0,e.length-1)+t),e=e.replace(/ {2}/g,` ${t}`),e}function sm(n){if(!/["'&<>]/.exec(n))return n;const o={'"':"&quot;","'":"&#39;","&":"&amp;","<":"&lt;",">":"&gt;"};return n.split("").map(l=>o[l]||l).join("")}function lm(n){const t=document.getElementById(n);t&&t.remove()}function cm(n,t){const e=document.getElementById(t);if(e)return e.textContent=n,e;const o=document.createElement("style");return o.id=t,o.textContent=n,document.head.append(o),o}function Li(n){const t="custom-cursor-style";if(n){const e=`body * { cursor: ${n} !important}`;cm(e,t)}else lm(t)}const am=3,dm=w("drag-drop");class um{constructor(t){h(this,"dragStarted",!1);h(this,"mouseDownEvent",null);h(this,"_dragOffsetX",0);h(this,"_dragOffsetY",0);h(this,"handleMouseDown",t=>{t.preventDefault(),t.stopPropagation(),this.mouseDownEvent=t;const e=this.options.elem.getBoundingClientRect();this._dragOffsetX=this.mouseDownEvent.x-e.left,this._dragOffsetY=this.mouseDownEvent.y-e.top,this.bindEvents()});h(this,"handleMouseMove",t=>{var i;t.preventDefault(),t.stopPropagation(),d(dm,this.mouseDownEvent,"no mouse down event");const e=t.x-this.mouseDownEvent.x,o=t.y-this.mouseDownEvent.y;if(this.dragStarted){this.onDragging(t,e,o);return}const r=(i=this.options.minThreshold)!=null?i:am;(Math.abs(e)>=r||Math.abs(o)>=r)&&this.onDragStart(this.mouseDownEvent)});h(this,"handleMouseUp",t=>{if(t.button===0){d(dm,this.mouseDownEvent,"no mouse down event");const e=t.x-this.mouseDownEvent.x,o=t.y-this.mouseDownEvent.y;this.onDragEnd(t,e,o),t.preventDefault(),t.stopPropagation()}});this.options=t,this.options.mouseDownEvent?this.handleMouseDown(this.options.mouseDownEvent):this.trackEvents()}get data(){return this.options.data}get dragOffsetX(){return this._dragOffsetX}get dragOffsetY(){return this._dragOffsetY}get dragOffset(){return{x:this._dragOffsetX,y:this._dragOffsetY}}trackEvents(){this.options.elem.addEventListener("mousedown",this.handleMouseDown)}untrackEvents(){this.options.elem.removeEventListener("mousedown",this.handleMouseDown)}bindEvents(){document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp)}unbindEvents(){document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}onDragStart(t){this.dragStarted=!0,this.options.cursor&&Li(this.options.cursor),this.options.onDragStart(this,t,this.options.elem)}onDragging(t,e,o){this.options.onDragging(this,t,this.options.elem,e,o)}onDragEnd(t,e,o){this.options.cursor&&Li(null),this.dragStarted&&this.options.onDragEnd(this,t,this.options.elem,e,o),this.unbindEvents(),this.dragStarted=!1}destroy(){this.unbindEvents(),this.untrackEvents()}}function ed(n){return new um(n)}const z7=w("character");function hm(n,t){for(let e=0;e<t.length;e++){const o=t[e][0],r=t[e].length>1?t[e][1]:null;if(r===null&&n===o||r!==null&&n>=o&&n<=r)return!0}return!1}function fm(n){const t=n.charAt(0);return t>="0"&&t<="9"}function mm(n){const t=n.charAt(0);return t>="a"&&t<="z"||t>="A"&&t<="Z"||t.toUpperCase()!==t.toLowerCase()?!0:RegExp(/^\p{L}/,"u").test(t)}function ml(n){const t=[[9,13],[32],[160]];return hm(n.charCodeAt(0),t)}function gm(n){const t=[[12352,12687],[13056,13183],[13312,15661],[19968,40959],[63744,64255],[44032,55215]];return hm(n.charCodeAt(0),t)}function nd(n,t){let e=t;return d(z7,e.length===1,"invalid char length"),e==="]"&&(e="\\]"),e==="\\"&&(e="\\\\"),n.replace(new RegExp(`^[${e}]+|[${e}]+$`,"g"),"")}const Pn=navigator.userAgent;function pm(){const n=navigator.userAgent.toLowerCase();return n.indexOf("safari")!==-1&&!(n.indexOf("chrome")>-1)}function od(){return navigator.userAgent.toLowerCase().indexOf("firefox")>-1}const xt={isAndroid:!!Pn.match(/Android/i),isIOS:!!Pn.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/i),isIPad:!!Pn.match(/iPad/i),isIPhone:!!Pn.match(/iPhone/i),isLinux:!!Pn.match(/Linux/i),isMac:!!Pn.match(/Macintosh/i),isMobile:!!Pn.match(/AppleWebKit.*Mobile.*/i),isWindows:!!Pn.match(/Window/i),isIe:!!Pn.match(/msie|trident/i),isSafari:pm(),isMobileSafari:!1};xt.isMobileSafari=xt.isMobile&&xt.isSafari;function rd(n){return n?n.length===1||n==="Process"||n==="Unidentified"&&xt.isAndroid:!1}function Cm(n){switch(n){case"ArrowDown":case"ArrowUp":case"ArrowLeft":case"ArrowRight":case"End":case"Home":case"PageDown":case"PageUp":return!0;default:return!1}}function U7(n){return Cm(n.key)}function V7(n){switch(n){case"ArrowUp":case"ArrowLeft":case"Home":case"PageUp":return!0;default:return!1}}function Oo(n){return n.ctrlKey||n.altKey||n.shiftKey||n.metaKey}function q7(n){return n.key?!!(n.ctrlKey||n.metaKey||n.altKey):!1}function bm(n){return xt.isMac?n.metaKey&&!n.ctrlKey:!n.metaKey&&n.ctrlKey}function W7(n){return bm(n)&&!n.altKey&&!n.shiftKey}function G7(n){return!n.metaKey&&!n.ctrlKey&&!n.shiftKey&&n.altKey}function vm(n){return!Oo(n)&&n.key==="Enter"}function Z7(n){return n.key==="Enter"&&n.shiftKey&&!n.altKey&&!n.ctrlKey&&!n.metaKey}function id(n){return!Oo(n)&&n.key==="Escape"}function Y7(n){return!Oo(n)&&n.key==="Delete"}function km(n){return!Oo(n)&&n.key==="Backspace"}function Q7(n){return!Oo(n)&&n.key==="Tab"}function K7(n){return n.shiftKey&&n.key==="Tab"&&!n.ctrlKey&&!n.metaKey}function J7(n){if(!n)return"";if(xt.isMac){const t=n.replace("CtrlOrCmd","\u2318").replace("Shift","\u21E7").replace("Ctrl","\u2303").replace("Alt","\u2325").replace(/\+(?!$)/gm,""),e={"\u2318":4,"\u21E7":3,"\u2325":2,"\u2303":1};return t.split(/(?=[\s\S])/u).sort((r,i)=>{var c,a;const s=(c=e[r])!=null?c:5,l=(a=e[i])!=null?a:5;return s-l}).join("")}return n.replace("CtrlOrCmd","Ctrl")}function ym(n){const t={ctrl:!1,alt:!1,shift:!1,cmd:!1,key:""},e=n.toLocaleUpperCase().split("+");for(let o=0;o<e.length;o++){const r=e[o];r==="CTRL"||r==="CONTROL"?t.ctrl=!0:r==="ALT"||r==="OPTION"?t.alt=!0:r==="SHIFT"?t.shift=!0:r==="CMD"||r==="COMMAND"?t.cmd=!0:r==="CMDORCTRL"||r==="CTRLORCMD"?xt.isMac?t.cmd=!0:t.ctrl=!0:r==="SPACE"?t.key=" ":t.key=r.substring(0,1)+r.substring(1).toLocaleLowerCase()}return t}function jn(n,t){const e=ym(t);return e.ctrl!==n.ctrlKey||e.alt!==n.altKey||e.shift!==n.shiftKey||xt.isMac&&e.cmd!==n.metaKey?!1:e.key.length===1?e.key===n.key.toUpperCase():e.key.toUpperCase()===n.key.toUpperCase()}function sd(n,t){return z9.stringifyUrl({url:n,query:t})}function _o(n){return typeof n=="string"?Bi.Base64.encode(n,!0):Bi.Base64.fromUint8Array(n,!0)}function gl(n){return Bi.Base64.decode(n)}function X7(n){return Bi.Base64.toUint8Array(n)}function wm(n){return new Blob([Bi.Base64.toUint8Array(n)])}const t8=oo.init([oo.classModule,oo.styleModule,oo.datasetModule,oo.attributesModule,oo.propsModule]);function Mi(n,t){const e=oo.toVNode(n),o=oo.toVNode(t);t8(e,o)}async function Bm(n,t){const e=new FileReader,o=new Promise((i,s)=>{e.onload=i,e.onerror=s});return e.readAsDataURL(new Blob([n],{type:t})),await o,e.result}async function pl(n){const t=new FileReader,e=new Promise((r,i)=>{t.onload=r,t.onerror=i});return t.readAsDataURL(n),await e,t.result}function e8(n,...t){const e=n.tagName.toLowerCase();for(let o=0,r=t.length;o<r;o++)if(e===t[o].toLowerCase())return!0;return!1}function We(n,t){let e=n;for(;e;){const o=window.getComputedStyle(e);if(t!=null&&t.horizontal){if(/auto|scroll/i.test(o.overflowX))break}else if(/auto|scroll/i.test(o.overflowY))break;e=e.parentElement}return(!e||e8(e,"body"))&&(e=document.documentElement),e}function Em(n){n.preventDefault(),n.stopPropagation()}function Im(n){if(document.querySelector(`.editor-disable-scroll[data-scroll-id="${n}"]`))return;const t=b("div",["editor-disable-scroll"],null);t.setAttribute("data-scroll-id",n),t.addEventListener("wheel",Em,{passive:!1}),document.body.appendChild(t)}function xm(n){const t=document.querySelector(`.editor-disable-scroll[data-scroll-id="${n}"]`);t&&(t.removeEventListener("wheel",Em),t.remove())}function ld(n,t,e){const o=new Blob([n]),r=new File([o],e,{type:t});return URL.createObjectURL(r)}function Cl(n){const t=document.createElement("template");if("content"in t)return t.innerHTML=n,document.importNode(t.content,!0);const e=document.createDocumentFragment(),o=document.createElement("div");for(o.innerHTML=n;o.firstChild;)e.appendChild(o.firstChild);return e}function Tm(n){const t=document.createElement("div");return t.appendChild(n),t.innerHTML}function Sm(n){let t=n.getPropertyValue("font");if(t)return t;const e=n.getPropertyValue("font-style"),o=n.getPropertyValue("font-variant"),r=n.getPropertyValue("font-weight"),i=n.getPropertyValue("font-size"),s=n.getPropertyValue("font-family");return t=`${e} ${o} ${r} ${i} ${s}`.replace(/ +/g," ").trim(),t}function bl(n,t){const o=(bl.canvas||(bl.canvas=document.createElement("canvas"))).getContext("2d");return o?(typeof t=="string"?t?o.font=t:o.font=Sm(window.getComputedStyle(document.body)):t instanceof Element&&(o.font=Sm(window.getComputedStyle(t))),o.measureText(n).width+4):200}const n8=w("editor-clipboard");async function o8(n,t){if(t.clipboardData){const e=t.clipboardData;for(const o of n)e.setData(o.type,o.data);return!0}return!1}async function vl(n){try{const t={};n.forEach(o=>{t[o.type]=o.data});const e=new ClipboardItem(t);return await navigator.clipboard.write([e]),!0}catch(t){return n8.error(t),!1}}function No(n,t){return new Promise((e,o)=>{const r=document.createElement("input");r.type="file",r.style.display="none",t!=null&&t.multiple&&(r.multiple=!0),r.accept=n,r.onchange=()=>{const i=r.files;if(i){const s=t!=null&&t.multiple?Array.from(i):i[0];e(s)}r.remove()},r.onerror=i=>{o(i),r.remove()},r.click()})}function kl(n){return Array.isArray(n)?n.every(t=>t instanceof File):!1}function Dm(n){const t=n;if(!t)return"";const e=t.lastIndexOf(".");return e===-1?"":t.slice(e+1)}function yl(n,t){const e=document.createElement("a");e.setAttribute("download",`${t||""}`),e.setAttribute("href",`${n}`),e.click(),e.remove()}const Lm=w("auto-scroll");function Mm(n,t){return!(n.scrollHeight===n.clientHeight||t==="top"&&n.scrollTop===0||t==="bottom"&&n.scrollTop+n.clientHeight===n.scrollHeight||t==="left"&&n.scrollLeft===0||t==="right"&&n.scrollLeft+n.clientWidth===n.scrollWidth)}function Rm(n,{direction:t,step:e}){let o=null;const r=t==="left"||t==="right",i=()=>{if(!Mm(n,t))return Lm.debug("No need for scroll"),null;if(r){const s=n.scrollLeft,l=t==="left"?s-e:s+e;n.scrollLeft=l}else{const s=n.scrollTop,l=t==="top"?s-e:s+e;n.scrollTop=l}return o=requestAnimationFrame(i),o};return o=requestAnimationFrame(i),()=>{o&&cancelAnimationFrame(o)}}class Am{constructor(t){h(this,"cancelScroll",null);h(this,"options");h(this,"scrollDomInfo");h(this,"scrolling",!1);h(this,"getScrollingDirection",t=>{const{x:e,y:o}=t,{top:r,bottom:i,left:s,right:l}=this.scrollDomInfo,{edge:c}=this.options;return c.top&&o>=r&&o<=c.top+r?"top":c.bottom&&o<=i&&o>=i-c.bottom?"bottom":c.left&&e>=s&&e<=s+c.left?"left":c.right&&e<=l&&e>=l-c.right?"right":null});h(this,"handleMouseMove",t=>{var s;const{scrollElement:e,step:o=10,onDirectionChange:r}=this.options,i=this.getScrollingDirection(t);if(i){if(this.scrolling)return;Lm.debug(`scroll direction: ${i}`),this.cancelScroll=Rm(e,{direction:i,step:o}),r==null||r(i),this.scrolling=!0}else(s=this.cancelScroll)==null||s.call(this),this.scrolling=!1});this.options=t,this.scrollDomInfo=this.getScrollDomInfo()}getScrollDomInfo(){const{scrollElement:t}=this.options,e=t.clientTop,o=t.clientLeft,r=t.clientHeight,i=t.clientWidth;return{left:o,top:e,right:i,bottom:r}}active(){const{trackMouseEvent:t="mousemove"}=this.options;window.addEventListener(t,this.handleMouseMove,!0)}inactive(){var e;const{trackMouseEvent:t="mousemove"}=this.options;window.removeEventListener(t,this.handleMouseMove,!0),(e=this.cancelScroll)==null||e.call(this),this.scrolling=!1}}function Om(n,t){if(n===0)return"0 Bytes";const e=1024,o=t||2,r=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],i=Math.floor(Math.log(n)/Math.log(e));return`${parseFloat((n/e**i).toFixed(o))} ${r[i]}`}function cd(n,t){let e=`${n}`;const o=t-e.length;for(let r=0;r<o;r++)e=`0${e}`;return e}const{t:$o}=T;function ad(n,t){const e=new Date(n).getTime()+864e5*t;return new Date(e)}function r8(n,t){const e=n,o=Math.floor(t/12),r=t-o*12;return o&&e.setFullYear(e.getFullYear()+o),r&&e.setMonth(e.getMonth()+r),e}function i8(n,t){return ad(n,t)}function dd(n,t){const e=new Date(n),o=new Date(t);return e.getDate()===o.getDate()&&e.getMonth()===o.getMonth()&&e.getFullYear()===o.getFullYear()}function _m(n){const t=new Date,e=new Date(n);return dd(t,e)}function Nm(n){const t=ad(new Date,-1);return dd(t,n)}function s8(n,t){return Math.round((n.getTime()-t.getTime())/864e5)}function $m(n,t){const e=new Date(n);if(t){const o=e.getFullYear(),r=e.getMonth()+1,i=e.getDate();let s=t;return s=s.replace("yyyy",`${o}`),s=s.replace("mm",cd(r,2)),s=s.replace("dd",cd(i,2)),s=s.replace("m",`${r}`),s=s.replace("d",`${i}`),s}return n.toLocaleDateString()}function ud(n,t){const e=new Date(n),o=new Date;if(e.getTime()-o.getTime()>10*1e3)return T.t("date.dateFromFuture");if(_m(e)){const i=(o.getTime()-n.getTime())/1e3;if(i<10*60)return $o("date.dateJustNow");if(i<60*60)return $o("date.dateMinutesAgo",{num:`${Math.floor(i/60)}`});const s=Math.floor(i/60/60);return s===1?$o("date.date1HourAgo"):$o("date.dateHoursAgo",{num:`${s}`})}if(Nm(n))return $o("date.dateYesterday");const r=Math.floor((o.getTime()-n.getTime())/1e3/24/60/60)+1;return r<14?$o("date.dateDaysAgo",{num:`${r}`}):r<28?$o("date.dateWeeksAgo",{num:`${Math.round(r/7)}`}):$m(n,t)}function hd(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function l8(n,t,e){return n.replace(new RegExp(hd(t),"g"),e)}function c8(n,t,e){return n.replace(new RegExp(hd(t),"gi"),e)}const Pm=w("container-children");function Mt(n){const t=Array.from(n.querySelectorAll(":scope > .container-blocks > div[data-type=editor-block]"));return d(Pm,t.length>0,"container have not any child block"),t}function Vt(n){const t=n.querySelector(":scope > .container-blocks > div[data-type=editor-block]");return d(Pm,t,"container have not any child block"),t}function Qt(n){const t=Mt(n);return t[t.length-1]}function Ge(n){return Mt(n).length}function kr(n,t){return Mt(n)[t]}const Ze=w("block-dom");function Po(n){return n instanceof HTMLDivElement?n.getAttribute("data-type")==="editor-block":!1}function jm(n){A(n,"block-hidden")}function Hm(n){z(n,"block-hidden")}function wl(n){return!nt(n,"block-hidden")}function q(n){const{id:t}=n;return d(Ze,t,"no block id"),t}function rt(n){const t=n.getAttribute("data-block-type");return d(Ze,t,"invalid block dom, no data-type"),t}function F(n){const t=n instanceof Element?n:n.parentElement;if(!t)return null;const e=t.closest("div[data-type=editor-block]");return e||null}function H(n){const t=n.closest("div[data-type=editor-container]");return d(Ze,t,"failed to get block container"),t}function it(n){const t=n.querySelector(":scope >div[data-type=block-content]");return d(Ze,t,"no block content"),t}function Rt(n){let t=n.querySelector(":scope >div[data-type=block-tools]");return t||(t=b("div",[],n),t.setAttribute("data-type","block-tools")),d(Ze,t,"no block tools"),t}function Bl(n){const t=n.querySelector(":scope >div[data-type=block-tools]");return t||null}function Fm(n){let t=n.querySelector(":scope > div[data-type=block-background]");return t||(t=b("div",[],n),t.setAttribute("data-type","block-background")),t}function zm(n,t,e){const o=n.editorDecorators.decorateBlock(t,e),{id:r,type:i}=o;d(Ze,r,"no block id");const s=b("div",[`${i}-block`],null);s.id=r,s.setAttribute("data-type","editor-block"),s.setAttribute("data-block-type",i);const l=n.editorBlockRenders.renderBlock(n,t,e);return l.classes&&A(s,...l.classes),l.attributes&&Object.entries(l.attributes).forEach(([c,a])=>{s.setAttribute(c,a)}),l.styles&&Object.entries(l.styles).forEach(([c,a])=>{s.style.setProperty(c,a)}),s}function ro(n,t){const e=b(t,[],null);return e.setAttribute("data-type","block-content"),n&&n.appendChild(e),e}function Um(n){const t=b("span",[`${n.type}-box`],null);return t.setAttribute("data-type","editor-box"),t.setAttribute("data-box-type",n.type),t.id=n.id,t}function Ri(n){const t=n.getAttribute("data-box-type");return d(Ze,t,"not a valid box element, no type"),t}function fd(n){return n instanceof HTMLSpanElement?n.getAttribute("data-type")==="editor-box":!1}function Vm(n){const{id:t}=n;return d(Ze,t,"no box id"),t}function md(n){const t=n instanceof Element?n:n.parentElement;if(!t)return null;const e=t.closest("span[data-type=editor-box]");return e||null}function qm(n){n.innerHTML="",b("span",["box-space-start"],n,Ti);const t=b("span",[],n);return t.setAttribute("data-type","box-content"),b("span",["box-space-start"],n,Ti),t}function gd(n){const t=n.querySelector("span[data-type=box-content]");return d(Ze,t,"invalid box dom, no content"),t}function Wm(n,t){const e=b("span",[`${n}-insertion`],null);return e.setAttribute("data-type","editor-insertion"),e.setAttribute("data-insertion-id",t),e}function Gm(n,t){return n.rootContainer.querySelector(`[data-insertion-id=${t}]`)}function Zm(n){n.innerHTML="",b("span",["insertion-space-start"],n,Ti);const t=b("span",[],n);return t.setAttribute("data-type","insertion-content"),b("span",["insertion-space-start"],n,Ti),t}function pd(n){const t=n.querySelector("span[data-type=insertion-content]");return d(Ze,t,"invalid insertion-child dom, no content"),t}function gt(n){let t=n.previousElementSibling;for(;t;){if(Po(t))return t;t=t.nextElementSibling}return null}function dt(n){let t=n.nextElementSibling;for(;t;){if(Po(t))return t;t=t.nextElementSibling}return null}function yr(n){let t=n.previousElementSibling;for(;t;){if(Po(t)&&wl(t))return t;t=t.previousElementSibling}return null}function wr(n){let t=n.nextElementSibling;for(;t;){if(Po(t)&&wl(t))return t;t=t.nextElementSibling}return null}function J(n){const t=H(n),o=Mt(t).indexOf(n);return d(Ze,o!==-1,"invalid block & container dom, failed to get block index"),o}function Cd(n){return!n||!(n instanceof Node)?!1:!!F(n)}function Ai(n){if(!Cd(n))return!1;const t=n,e=t instanceof Element?t:t.parentElement;return e?!!e.closest("div[data-type=block-tools]"):!1}const Ym=w("element");function bd(n,t,e){const o=b("div",[t],n);return o.setAttribute("data-type","editor-container"),o.setAttribute("data-container-id",e),b("div",["container-blocks"],o),o}function Br(n,t){const e=n.rootElement.querySelector(`[data-container-id=${t}`);return d(Ym,e,`no container: ${t}`),e}function Qm(n,t){return n.rootElement.querySelector(`[data-container-id=${t}`)}function El(n){const t=n.querySelector(":scope > .container-blocks");return d(Ym,t,"no container blocks element"),t}function a8(n){let t=n.querySelector(":scope > .container-tools");return t||(t=b("div",["container-tools"],n)),t}const Km=w("container");function bn(n){return n.getAttribute("data-type")==="editor-container"}function pt(n){return nt(n,"root")}function Ye(n){return nt(n,"child")}function U(n){const t=n.getAttribute("data-container-id");return d(Km,t,"no id for container"),pt(n)&&d(Km,t==="root",`invalid root container id, : ${t}`),t}function Jm(n,t){const e=U(n);return t.getContainerBlocks(e)}const Xm=w("block-path");function jo(n){const t=[];let e=n;for(;e;){const o=H(e);if(t.unshift({containerId:U(o),blockIndex:J(e)}),pt(o))return t;const r=F(o);d(Xm,r,"no parent block"),e=r}return d(Xm,!1,"no parent block"),[]}const d8=w("child-container-path");function tg(n){if(pt(n))return[];const t=F(n);return d(d8,t,"no parent block"),jo(t)}const eg=w("load-blocks");function vd(n,t,e){const o=U(t),r=Jm(t,n.doc);d(eg,r.length>0,"no blocks in container");const i=document.createDocumentFragment();r.forEach((l,c)=>{const a=n.editorBlocks.createBlock([...e,{containerId:o,blockIndex:c}],t,l);i.appendChild(a)}),El(t).appendChild(i)}function u8(n,t,e){const o=El(n),r=Mt(n);return d(eg,t>=0&&t<=r.length,"invalid block index"),t===r.length?o.appendChild(e):o.insertBefore(e,r[t]),e}function h8(n,t,e,o){const r=tg(t);r.push({containerId:U(t),blockIndex:e});const i=n.editorBlocks.createBlock(r,t,o);return u8(t,e,i),i}const ng=w("root-container");class f8{constructor(t,e){h(this,"resizeObserver");h(this,"handleContextMenu",t=>{t.preventDefault()});h(this,"handleResize",()=>{try{this.editor.selection.updateSelection(null),this.editor.emit("resize",this.editor)}catch(t){ng.warn(`failed to update selection while container resizing: ${t.message}`)}});h(this,"handleClick",t=>{var o,r;this.editor.emit("click",this.editor,t);const e=t.target;if(!Ai(e)&&(t.detail===1&&this.editor.input.focus(),t.detail===3&&this.editor.selectionHandler.handleTripleClick(t),t.detail===1&&t.button===0)){const i=document.elementFromPoint(t.clientX,t.clientY);if(i&&It(this.rootContainer,i)){const s=md(i);if(s){const l=F(s);d(ng,l,"no parent block"),(r=(o=this.editor.editorBoxes.getBoxClass(Ri(s)))==null?void 0:o.handleClickBox)==null||r.call(o,this.editor,s,t)}}}});h(this,"handleDblClick",t=>{Ai(t.target)||this.editor.selectionHandler.handleDblClick(t)});h(this,"handleMouseDown",t=>{const e=t.target;if(!!e&&e instanceof Node&&!Ai(e)){if(e instanceof HTMLElement&&e.draggable){this.editor.selectionHandler.handleMouseDown(t),this.editor.selectionHandler.stopSelection(),this.editor.input.focus();return}t.button===0&&(document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp),this.editor.selectionHandler.handleMouseDown(t)),xt.isMobileSafari||(t.preventDefault(),this.editor.input.focus()),t.button===2&&t.stopPropagation()}});h(this,"handleMouseMove",t=>{this.editor.selectionHandler.handleMouseMove(t)});h(this,"handleMouseUp",t=>{t.button===0&&(this.editor.selectionHandler.handleMouseUp(t),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp))});this.editor=t,this.rootContainer=e,this.editor=t,this.resizeObserver=new ResizeObserver(this.handleResize),this.bindEvents(e)}bindEvents(t){this.resizeObserver.observe(t);const e=this.editor.rootElement;e.onmousedown=this.handleMouseDown,e.ondblclick=this.handleDblClick,e.onclick=this.handleClick,e.oncontextmenu=this.handleContextMenu}unbindEvents(){this.resizeObserver.disconnect();const t=this.editor.rootElement;t.onmousedown=null,t.ondblclick=null,t.onclick=null,t.oncontextmenu=null}destroy(){this.unbindEvents()}reload(){const t=this.editor.selection.range,e=El(this.rootContainer);e.innerHTML="",vd(this.editor,this.rootContainer,[]);const o=this.editor.findBlockById(t.start.blockId);if(o)this.editor.selection.selectBlock(o,0);else{const r=Vt(this.rootContainer);this.editor.selection.selectBlock(r,0)}}}function og(n){const t=bd(n.contentElement,"root","root");return n.rootContainer=t,vd(n,t,[]),new f8(n,t)}function rg(n,t,e,o){const r=Qm(n,o);if(r)return e.appendChild(r),r;const i=bd(e,"child",o);return vd(n,i,t),i}const ig=w("block-class");function bt(n,t){return n.editorBlocks.getBlockClass(rt(t))}function sg(n,t){const e=n.editorBlocks.getBlockClass(rt(t));return d(ig,e.blockKind==="text",`is not a text block, ${e.blockType}`),e}function xe(n,t){const e=n.editorBlocks.getBlockClass(rt(t));return d(ig,e.blockKind==="complex",`is not a text block, ${e.blockType}`),e}function Er(n,t){return n.editorBlocks.getBlockClass(t)}const kd=w("block");function W(n,t){return bt(n,t).getBlockTextLength(t)}function lg(n){n.editorBlocks.forEach(t=>{t.clearSelection(n)})}function cg(n,t,e,o){bt(n,t).updateSelection(n,t,e,o)}function yd(n){for(;;){const t=H(n);if(pt(t))return n;const e=F(t);d(kd,e,"no parent block exists for child container"),n=e}}function ag(n,t){const e=bt(n,t);if(!!e.getMinWidth)return e.getMinWidth(n,t)}function dg(n,t,e){const o=bt(n,t);o.handleBlockElementUpdated&&o.handleBlockElementUpdated(n,t,e)}function Oi(n,t,e,o){try{const r=Er(n,e).convertFrom;return r?r(n,t,o):null}catch{return kd.debug(`unsupported block type: ${e}`),null}}function Ho(n,t,e){const o=bt(n,t);return o.getClientRects?o.getClientRects(n,t,e):[t.getBoundingClientRect()]}function m8(n,t){const e=bt(n,t);if(e.getBlockStyles)return e.getBlockStyles(n,t);const o=n.getBlockData(t),r=Object.fromEntries(Object.entries(o).filter(([i])=>i.startsWith("style-")));return Object.entries(r).forEach(([,i])=>{const s=typeof i;d(kd,s==="string"||s==="number"||s==="boolean","invalid style value")}),r}function ug(n,t){const e=n.getBoundingClientRect().width;return t.withPadding?e:e-Qa(n)}function wd(n,t){let e=Number.MAX_SAFE_INTEGER;const o=Mt(t);for(let i=0;i<o.length;i++){const s=o[i],l=ag(n,s);l&&(e=Math.min(e,l))}return e===Number.MAX_SAFE_INTEGER?void 0:e+Qa(t)}function j(n,t){return bt(n,t).blockKind==="text"}function _i(n,t){return n.editorBlocks.getBlockClass(t).blockKind==="text"}function at(n,t){return bt(n,t).blockKind==="complex"}function g8(n,t){return!at(n,t)}function Qe(n,t){return bt(n,t).blockKind}function Tt(n,t){return Qe(n,t)==="text"?W(n,t)===0:!1}function Bd(n,t){const e=Mt(t);return e.length!==1?!1:Tt(n,e[0])}function Ke(n,t,e){return bt(n,t).getCaretRect(t,e)}function p8(n,t){var r,i;const e=bt(n,t);return(i=(r=e.getOptions)==null?void 0:r.call(e,n))!=null?i:{name:rt(t)}}function hg(n,t){var r;const e=bt(n,t);return(r=e.getBlockProperties)==null?void 0:r.call(e,n,t)}function Ed(n,t){var i,s;const e=bt(n,t),o=(i=e.getBlockProperties)==null?void 0:i.call(e,n,t);let r={};o!=null&&o.blockCommands&&(r={...o.blockCommands});for(const l of n.blockHooks){const c=(s=l.commands)==null?void 0:s.call(l,n,t);c&&(r[c.group]=c)}return r}function fg(n,t,e){var s,l,c,a;const o=bt(n,t),r=(s=o.getBlockProperties)==null?void 0:s.call(o,n,t);let i={};r!=null&&r.blockCommands&&(i={...r.blockCommands});for(const u of n.blockHooks){const f=(l=u.commands)==null?void 0:l.call(u,n,t);f&&(i[f.group]=f)}return(a=(c=i[e])==null?void 0:c.commands)!=null?a:[]}const mg=w("embed-block-common");function Te(n){return rt(n)==="embed"}function Oe(n){d(mg,Te(n),"not an embed block");const t=n.getAttribute("data-embed-type");return d(mg,t,"no embed data type"),t}function C8(n,t){return n.editorEmbeds.getEmbedClass(Oe(t))}function Fo(n,t){return n.editorEmbeds.getEmbedClass(t)}async function Id(n,t,e,o,r){const i=Fo(n,t);if(!i.getOptions)return null;const s=i.getOptions(n);if(!s.insertEmbedCommandItems||!s.insertEmbedCommandItems||s.insertEmbedCommandItems.length===0||!s.handleInsertEmptyEmbed)return null;const l=s.insertEmbedCommandItems[0];return s.handleInsertEmptyEmbed(n,{item:l,containerId:e,blockIndex:o,data:r})}function b8(n,t,e,o,r){var l,c;const i=(c=(l=Er(n,t)).getOptions)==null?void 0:c.call(l,n);if(!i||!i.insertBlockCommandItems||i.insertBlockCommandItems.length===0||!i.handleInsertEmptyBlock)return null;const s=i.insertBlockCommandItems[0];return i.handleInsertEmptyBlock(n,{item:s,containerId:e,blockIndex:o,data:r})}const v8=w("execute-block-command");function gg(n,t,e,o){var a;d(v8,Te(t),"not a embed block");const r=Oe(t),i=Fo(n,r);if(!i.getOptions)return;const s=(a=i.getBlockProperties)==null?void 0:a.call(i,n,t),l=s==null?void 0:s.blockCommands;if(!l)return;const c=Object.entries(l);for(const u of c)if(u[0]===e)return u[1].executeCommand(n,t,o)}function pg(n,t,e,o){const r=Ed(n,t);if(!r)return;const i=Object.entries(r);for(const s of i)if(s[0]===e)return s[1].executeCommand(n,t,o)}const k8=w("complex-block-position");class Je{constructor(t,e,o){h(this,"blockId");h(this,"childContainerId");h(this,"custom");t instanceof HTMLElement?this.blockId=q(t):(d(k8,typeof t=="string",`not a valid block id: ${t}`),this.blockId=t),this.childContainerId=e,o!==void 0&&(this.custom=o)}isSimple(){return!1}}const y8=w("simple-block-position");class qt{constructor(t,e,o){h(this,"blockId");h(this,"offset");h(this,"type");t instanceof HTMLElement?this.blockId=q(t):(d(y8,typeof t=="string",`not a valid block id: ${t}`),this.blockId=t),this.offset=e,this.type=o}isSimple(){return!0}}const xd=w("editor-position");function P(n,t,e){return new qt(n,t,e)}function wt(n,t,e){return new Je(n,t,e)}function Ir(n){return n instanceof qt}function Td(n){return n instanceof Je}function Sd(n,t,e){if(Ir(t)&&Ir(e)){const o=t,r=e;if(o.blockId===r.blockId)return o.offset-r.offset;const i=n.getBlockById(t.blockId),s=n.getBlockById(e.blockId);return d(xd,i!==s,"comparePosition: blocks are the same"),fl(i,s)}if(Td(t)&&Td(e)){const o=t,r=e;if(o.childContainerId===r.childContainerId)return 0;const i=n.getContainerById(o.childContainerId),s=n.getContainerById(r.childContainerId);return d(xd,i!==s,"comparePosition: containers are the same"),fl(i,s)}return d(xd,!1,"invalid "),0}const Il=w("simple-range");class ce{constructor(t,e){h(this,"editor");h(this,"_anchor");h(this,"_focus");h(this,"reverse");this.editor=t,this._anchor=e.anchor,this._focus=e.focus,this.reverse=Sd(this.editor,this._anchor,this._focus)>0}isCollapsed(){return this.start.blockId===this.end.blockId&&this.start.offset===this.end.offset}isEqual(t){if(!(t instanceof ce))return!1;const e=t,{start:o,end:r}=e;return this.start.blockId===o.blockId&&this.start.offset===o.offset&&this.start.type===o.type&&this.end.blockId===r.blockId&&this.end.offset===r.offset&&this.end.type===r.type}isSimple(){return!0}isReverse(){return this.reverse}getEditor(){return this.editor}get start(){return this.reverse?this._focus:this._anchor}get end(){return this.reverse?this._anchor:this._focus}get anchor(){return this._anchor}get focus(){return this._focus}getSelectedBlocks(){const{editor:t}=this,e=t.getBlockById(this.start.blockId),o=t.getBlockById(this.end.blockId);d(Il,e,"no start block"),d(Il,o,"no end block");const r=H(e),i=H(o);d(Il,r===i,"invalid range");const s=[];if(e===o)s.push({block:e,start:this.start,end:this.end});else{const l=J(e),c=J(o);d(Il,l<c,"invalid range, start > index"),s.push({block:e,start:this.start,end:P(e,W(this.editor,e),"end")});const a=Mt(r);for(let u=l+1;u<c;u+=1){const f=a[u];s.push({block:f,start:P(f,0,"home"),end:P(f,W(this.editor,f),"end")})}s.push({block:o,start:P(o,0,"home"),end:this.end})}return s}getSelectedContainers(){return[]}getAnchorPos(){return this.isReverse()?this.end:this.start}getFocusedPos(){return this.isReverse()?this.start:this.end}clone(){return new ce(this.editor,this)}toDocRange(){return{anchor:this.anchor,focus:this.focus}}}w("unknown-block");function w8(n,t,e,o,r){A(o,"unknown-block");const i=ro(o,"div");return i.innerText=`unknown block (${r.type}): ${JSON.stringify(r)}`,i}function B8(n){return 1}function E8(n,t,e,o){return null}function I8(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t))return null;const i=q(t),s=P(i,0,"home"),l=P(i,1,"end");return new ce(n,{anchor:s,focus:l})}function x8(n,t){const o=it(n).getBoundingClientRect();return new DOMRect(o.left+o.width/2,o.top,1,o.height)}function T8(n,t,e,o){A(t,"selected")}function S8(n){n.rootContainer.querySelectorAll("div.unknown-block[data-type=editor-block]").forEach(t=>{z(t,"selected")})}function D8(n,t,e,o){return`[unknown block, ${t.type}]`}const L8={blockType:"unknown-block",blockKind:"embed",createBlockContent:w8,getBlockTextLength:B8,getRangeFromPoint:I8,moveCaret:E8,getCaretRect:x8,updateSelection:T8,clearSelection:S8,convertTo:D8},Dd=w("editor-blocks");class Cg{constructor(t){h(this,"blocks",new Map);this.editor=t}registerBlockClass(t){const e=t.blockType,o=this.blocks.get(e);d(Dd,!o,`duplicated block type: ${e}`),this.blocks.set(e,t)}getBlockClass(t){const e=this.blocks.get(t);return d(Dd,e,`unknown block type: ${t}`),e}hasBlock(t){return this.blocks.has(t)}createBlock(t,e,o){const r=zm(this.editor,t,o);let i;this.hasBlock(o.type)?i=this.getBlockClass(o.type):i=this.registerUnknownBlock(o.type);const s=i.createBlockContent(this.editor,t,e,r,o);return s.parentElement!==r&&(Dd.warn("content parent is not block"),r.appendChild(s)),this.editor.blockHooks.forEach(l=>{var c;(c=l.create)==null||c.call(l,this.editor,t,e,r,o)}),r}forEach(t){this.blocks.forEach(t)}registerUnknownBlock(t){const e={...L8,blockType:t};return this.editor.editorBlocks.registerBlockClass(e),e}}const bg=w("editor-embeds");class vg{constructor(t){h(this,"objects",new Map);this.editor=t}registerEmbedClass(t){const e=t.embedType,o=this.objects.get(e);d(bg,!o,`duplicated embed object type: ${e}`),this.objects.set(e,t)}getEmbedClass(t){const e=this.objects.get(t);return d(bg,e,`unknown embed type: ${t}`),e}getEmbedClassFromBlock(t){return this.getEmbedClass(Oe(t))}forEach(t){this.objects.forEach(t)}}const kg=w("embed-block");function M8(n,t,e,o,r){const i=ro(o,"div");d(kg,r.type==="embed",`not an embed data: ${JSON.stringify(r)}`);const s=r;return d(kg,s.embedType&&s.embedData,`not an embed data: ${JSON.stringify(s)}`),n.editorEmbeds.getEmbedClass(s.embedType).createEmbedContent(n,i,s,t,e,o),o.setAttribute("data-embed-type",s.embedType),i}function R8(n){return 1}function A8(n,t,e,o){return null}function O8(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t))return null;const i=q(t),s=P(i,0,"home"),l=P(i,1,"end");return new ce(n,{anchor:s,focus:l})}function _8(n,t){const o=it(n).getBoundingClientRect();return new DOMRect(o.left+o.width/2,o.top,1,o.height)}function N8(n,t,e,o){A(t,"selected")}function $8(n){n.rootContainer.querySelectorAll("div.embed-block[data-type=editor-block][data-block-type=embed]").forEach(t=>{z(t,"selected")})}function P8(n,t,e){let o=null;return n.editorEmbeds.forEach(r=>{var s,l;const i=(l=(s=r.convertFrom)==null?void 0:s.call(r,n,t,e))!=null?l:null;i&&(o=i)}),o}function j8(n,t,e,o){const r=Fo(n,t.embedType);return r.convertTo?r.convertTo(n,t,e,o):""}function H8(n,t){const e=C8(n,t);return e.getBlockProperties?e.getBlockProperties(n,t):{}}function F8(n){const t=new Map,e=[];return n.editorEmbeds.forEach(o=>{if(o.getOptions){const r=o.getOptions(n);r.insertEmbedCommandItems&&r.insertEmbedCommandItems.forEach(i=>{e.push(i),t.set(i.id,o)})}}),{name:"EmbedBlock",insertBlockCommandItems:e,async handleInsertEmptyBlock(o,r){const i=t.get(r.item.id);if(!i||!i.getOptions)return null;const s=i.getOptions(o);return s.handleInsertEmptyEmbed?s.handleInsertEmptyEmbed(o,r):null}}}function z8(n,t,e,o){const r=Oe(t),i=Fo(n,r);!i.handleDeleteBlock||i.handleDeleteBlock(n,t,e,o)}function U8(n,t,e){const o=Oe(t),r=Fo(n,o);return r.handleUpdateBlock?r.handleUpdateBlock(n,t,e):!1}function V8(n,t,e,o,r){const i=Oe(t),s=Fo(n,i);if(s.handleDropOver)return s.handleDropOver(n,t,e,o,r)}function q8(n,t,e,o,r){const i=Oe(t),s=Fo(n,i);if(s.handleDrop&&n.isWritable())return s.handleDrop(n,t,e,o,r)}const yg={blockType:"embed",blockKind:"embed",createBlockContent:M8,getBlockTextLength:R8,getRangeFromPoint:O8,moveCaret:A8,getCaretRect:_8,updateSelection:N8,clearSelection:$8,convertFrom:P8,convertTo:j8,getBlockProperties:H8,getOptions:F8,handleDeleteBlock:z8,handleUpdateBlock:U8,handleDropOver:V8,handleDrop:q8},ae=w("complex-block-helper");function Se(n,t){return xe(n,t).getChildContainers(n,t)}function xr(n,t,e,o){return e.isSimple()?(d(ae,o.isSimple(),"invalid start and end position"),Se(n,t)):(d(ae,!e.isSimple(),"invalid start pos"),d(ae,!o.isSimple(),"invalid end pos"),xe(n,t).getSelectedContainers(n,t,e,o))}function W8(n,t){if(J(t)!==0)return!1;const e=F(H(t));if(!e)return!1;d(ae,at(n,e),"not a complex block");const o=H(t),i=Se(n,e).indexOf(o);return d(ae,i>=0,"not valid child container"),i===0}function Ld(n,t){const e=Se(n,t);if(e.length===0)return null;const o=e[0],r=Vt(o);return at(n,r)?Ld(n,r):r}function Ni(n,t){const e=Se(n,t);if(e.length===0)return null;const o=e[e.length-1],r=Qt(o);return at(n,r)?Ni(n,r):r}function wg(n,t){d(ae,Ye(t),"not a child container");const e=F(t);d(ae,e,"no parent block"),d(ae,at(n,e),"not a complex block");const o=Se(n,e),r=o.indexOf(t);if(d(ae,r!==-1,"child container not found"),r===0){const l=gt(e);return l?at(n,l)?Ni(n,l):l:null}const i=o[r-1],s=Qt(i);return at(n,s)?Ni(n,s):s}function Bg(n,t){d(ae,at(n,t),"not a complex block");const e=Se(n,t);if(d(ae,e.length>0,"no child container"),e.length===1)return e;const o=e[0],r=o.getBoundingClientRect();let i=r.left,s=r.right;const l=[o];for(let c=1;c<e.length;c++){const a=e[c],u=a.getBoundingClientRect();if(u.right<=i){l.push(a),i=u.left;continue}if(u.left>=s){s=u.right;continue}}return l}function Eg(n,t){d(ae,at(n,t),"not a complex block");const e=Se(n,t);if(d(ae,e.length>0,"no child container"),e.length===1)return e;const o=e[e.length-1],r=o.getBoundingClientRect();let i=r.left,s=r.right;const l=[o];for(let c=e.length-2;c>=0;c--){const a=e[c],u=a.getBoundingClientRect();if(u.right<=i){l.push(a),i=u.left;continue}if(u.left>=s){s=u.right;continue}}return l}function Ig(n,t,e,o){const r=t.getBoundingClientRect(),i=o<r.top,s=i?Bg(n,t):Eg(n,t);let l=s[0],c=Cn(l.getBoundingClientRect(),e,o);for(let a=1;a<s.length;a++){const u=s[a],f=u.getBoundingClientRect(),m=Cn(f,e,o);m<c&&(l=u,c=m)}return i?Vt(l):Qt(l)}function xl(n,t,e,o){const r=q(t);d(ae,r===e.blockId,"invalid start pos"),d(ae,r===o.blockId,"invalid end pos");const i=xe(n,t);return i.adjustSelectionPos?i.adjustSelectionPos(n,t,e,o):{anchor:e,focus:o}}class Xe{constructor(t,e){h(this,"editor");h(this,"reverse");h(this,"_anchor");h(this,"_focus");this.editor=t,this._anchor=e.anchor,this._focus=e.focus,this.reverse=Sd(this.editor,this._anchor,this._focus)>0}isCollapsed(){return!1}isEqual(t){if(!(t instanceof Xe))return!1;const e=t,{anchor:o,focus:r}=e;return this._anchor.blockId===o.blockId&&this._anchor.childContainerId===o.childContainerId&&this._focus.blockId===r.blockId&&this._focus.childContainerId===r.childContainerId&&this._anchor.custom===o.custom&&this._focus.custom===r.custom}isReverse(){return this.reverse}isSimple(){return!1}getEditor(){return this.editor}get anchor(){return this._anchor}get focus(){return this._focus}get start(){return this.reverse?this._focus:this._anchor}get end(){return this.reverse?this._anchor:this._focus}getSelectedBlocks(){const t=this.start,e=this.end;return[{block:this.editor.getBlockById(t.blockId),start:t,end:e}]}getAnchorPos(){return this._anchor}getFocusedPos(){return this._focus}getSelectedContainers(){const t=this.editor.getBlockById(this._anchor.blockId);return xr(this.editor,t,this.start,this.end)}clone(){return new Xe(this.editor,this)}toDocRange(){return{anchor:this._anchor,focus:this._focus}}}const G8=w("selection-range");function Wt(n,t){const{anchor:e,focus:o}=t;return e instanceof qt&&o instanceof qt?new ce(n,{anchor:e,focus:o}):(d(G8,e instanceof Je&&o instanceof Je,"start position type does not math end type"),new Xe(n,{anchor:e,focus:o}))}function At(n,t,e,o){const r=new qt(t,e,"normal"),i=new qt(t,o!=null?o:e,"normal");return Wt(n,{anchor:r,focus:i})}function Z8(n){return!!n.anchor.childContainerId}function io(n,t){var r,i;if(Z8(t)){const s=wt(t.anchor.blockId,t.anchor.childContainerId,(r=t.anchor)==null?void 0:r.custom),l=wt(t.focus.blockId,t.focus.childContainerId,(i=t.focus)==null?void 0:i.custom);return Wt(n,{anchor:s,focus:l})}const e=P(t.anchor.blockId,t.anchor.offset,"normal"),o=P(t.focus.blockId,t.focus.offset,"normal");return Wt(n,{anchor:e,focus:o})}const Y8=w("range-from-point");function Tl(n,t,e){const o=[0,-12,12];for(let r=0;r<o.length;r++){const i=document.elementsFromPoint(t,e+o[r])[0];if(!i||!n.rootContainer.contains(i))continue;const s=F(i);if(!s||!n.contains(s))continue;const l=bt(n,s).getRangeFromPoint(n,s,t,e+o[r]);if(l)return l}return null}function xg(n,t,e,o){const r=t.getBoundingClientRect();if(o<=r.top){const l=Vt(t),c=P(l,0,"home");return new ce(n,{anchor:c,focus:c})}const i=Qt(t),s=P(i,W(n,i),"end");return new ce(n,{anchor:s,focus:s})}function Tg(n,t,e){const o=Tl(n,t,e);if(o){if(o instanceof ce)return o;d(Y8,o instanceof Xe,`invalid range type: ${typeof o}`);const c=o,a=n.getContainerById(c.start.childContainerId);return xg(n,a,t,e)}const r=document.elementsFromPoint(t,e)[0];if(!r)return null;const{children:i}=r,s=Array.from(i).filter(c=>bn(c));if(s.length===0)return null;const l=s.reduce((c,a)=>{const u=c.getBoundingClientRect(),f=a.getBoundingClientRect();return Cn(u,t,e)>Cn(f,t,e)?a:c});return xg(n,l,t,e)}function Md(n,t){const e=[];return Mt(t).forEach(r=>{e.push(r),at(n,r)&&Se(n,r).forEach(s=>{e.push(...Md(n,s))})}),e}function Rd(n,t){let e=Md(n,n.rootContainer);return t!=null&&t.simpleBlockOnly&&(e=e.filter(o=>!at(n,o))),e}function tn(n,t){const e=n.selection.range.getSelectedBlocks(),o=[];for(const r of e)o.push(r),at(n,r.block)&&xr(n,r.block,r.start,r.end).forEach(s=>{const c=Md(n,s).map(a=>({block:a,start:P(a,0,"home"),end:P(a,W(n,a),"home")}));o.push(...c)});return t!=null&&t.simpleBlockOnly?o.filter(r=>!at(n,r.block)):o}const ez="",Hn=w("text-block-child");function $i(n){return n.tagName==="SPAN"}function _e(n){return d(Hn,$i(n),"not a valid text child"),n.getAttribute("data-type")==="editor-box"}function Fn(n){return d(Hn,$i(n),"not a valid text child"),n.getAttribute("data-type")==="editor-insertion"}function Pi(n){return!_e(n)&&!Fn(n)}function Sg(n){return d(Hn,$i(n),"not a valid text child"),_e(n)?"box":Fn(n)?"insertion":"text"}function Ne(n){const t=Sg(n);return t==="insertion"?0:t==="box"?1:(d(Hn,n.textContent!==null,"text block content is undefined"),d(Hn,n.textContent.length>=0,"text block content length is negative"),n.textContent.length)}function zn(n){const t=it(n),e=Array.from(t.children);return e.forEach(o=>{d(Hn,$i(o),"not a valid text child")}),e}function Sl(n,t){const e=zn(n);let o=0;for(let r=0;r<e.length;r++){const i=e[r],s=Ne(i);if(o+s<t){o+=s;continue}if(o===t)return{prev:e[r-1],next:i,offset:0};if(o+s===t)return{prev:i,next:e[r+1],offset:0};const l=t-o;return d(Hn,l>0,"invalid offset value"),d(Hn,!_e(i),"invalid box child"),{prev:i,next:i,offset:l}}d(Hn,!1,`invalid block child at position: ${t}`)}const Kt=w("text-range");function Q8(n,t){const e=(i,s)=>{if(Fn(i))return d(Kt,s===0,`invalid offset for insertion child: ${s}`),{child:i,container:i,offset:2};if(_e(i))return d(Kt,s===0||s===1,`invalid offset for box: ${s}`),{child:i,container:i,offset:s===0?1:2};const l=i.firstChild;return d(Kt,l,"no child node for text child"),d(Kt,l instanceof Text||l instanceof HTMLBRElement,`invalid child for text child, ${l.nodeName}`),l instanceof HTMLBRElement?(d(Kt,s>=0&&s<=0,"invalid offset for text child"),{child:i,container:l,offset:s}):(d(Kt,s>=0&&s<=l.data.length,"invalid offset for text child"),{child:i,container:l,offset:s})};let o=0;const r=zn(n);for(let i=0;i<r.length;i++){const s=r[i],l=Ne(s);if(t===o)return[e(s,0)];if(t<o+l)return[e(s,t-o)];if(t===o+l){const c=[];c.push(e(s,Ne(s)));const a=r[i+1];return a&&c.push(e(a,0)),c}o+=l}d(Kt,!1,"failed to get range info")}function K8(n,t,e){if(t===e?d(Kt,Fn(n),"only insertion child can be zero offset"):d(Kt,t<e,`invalid start & end: ${t}, ${e}`),Fn(n)){d(Kt,t===e,`invalid insertion child range offset: ${t}, ${e}`),d(Kt,t===0,`invalid insertion child range start: ${t}`);const i=n;return d(Kt,i.children.length===3,`invalid insertion dom, children.length = ${i.children.length}`),ul(i,1,i,2)}if(_e(n)){d(Kt,t+1===e,`invalid box child range offset: ${t}, ${e}`),d(Kt,t===0,`invalid box child range start: ${t}`);const i=n;return d(Kt,i.children.length===3,`invalid box dom, children.length = ${i.children.length}`),ul(i,1,i,2)}const o=Ne(n);d(Kt,e<=o,`invalid child end: ${e}, ${o}`);const r=n.firstChild;return d(Kt,r instanceof Text,"invalid block text child"),d(Kt,r.data.length>=e,`invalid range end: ${e}, ${r.data.length}`),ul(r,t,r,e)}const en=w("caret-rect");function J8(n,t){if(fd(t)){const e=t,o=gd(e);if(e.getAttribute("data-box-type")==="br"){const r=it(n),i=Number.parseFloat(window.getComputedStyle(r).lineHeight)||o.getBoundingClientRect().height,s=Array.from(o.getClientRects());d(en,s.length>0,"no box client rects");const l=r.getBoundingClientRect(),c=s[0],a=new DOMRect(l.left,c.bottom,1,i);return s.push(a),s}return o.getClientRects()}return pd(t).getClientRects()}function De(n,t){var l,c;const e=Q8(n,t.offset);if(e[1]&&e[0].child!==((l=e[1])==null?void 0:l.child)){if(t.type==="end"){const u=Mo(e[0].child);return new DOMRect(u.right,u.top,1,u.height)}d(en,e[1],"invalid ranges");const a=hl(e[1].child);return new DOMRect(a.left,a.top,1,a.height)}let r=e[0];if(d(en,e.length>=1,"failed to get block range"),e.length===1)r=e[0];else{if(d(en,e.length>=2,`invalid range info length: ${e.length}`),Fn(e[e.length-1].child)){r=e[e.length-1];const a=r.child,f=pd(a).getClientRects();d(en,f.length>=1,"no client rects for box content");const m=f[f.length-1];return new DOMRect(m.right,m.y,1,m.height)}t.type==="home"?r=e[1]:t.type==="end"||Pi(e[0].child)?r=e[0]:Pi(e[1].child)&&(r=e[1])}if(r.container instanceof HTMLBRElement){d(en,t.offset===0,"invalid offset for empty block text");const a=(c=r.container.parentElement)==null?void 0:c.parentElement;d(en,a===it(n),"invalid br parent, is not block parent");const u=a.getBoundingClientRect();return new DOMRect(u.left,u.top,1,u.height)}const s=em(r.container,r.offset).getClientRects();if(s.length===0){d(en,!Pi(r.child),"only box or insertion child range has zero client rect"),d(en,r.offset===1||r.offset===2,"invalid offset for box or insertion child");const a=r.child,u=J8(n,a);if(d(en,u.length>=1,"no client rects for box content"),r.offset===1){const m=u[0];return new DOMRect(m.x,m.y,1,m.height)}const f=u[u.length-1];return t.type==="end"||r.offset===2?new DOMRect(f.right,f.y,1,f.height):new DOMRect(f.x,f.y,1,f.height)}return d(en,s.length>0,"no client rects for range"),t.type==="home"?s[s.length-1]:s[0]}const X8=w("core");function zo(n,t,e,o){const r=Rt(t);let i=r.querySelector(`.block-anchor[data-id=${e}]`);i||(i=b("div",["block-anchor"],r),i.setAttribute("data-id",e));const s=o!=null?o:t.getBoundingClientRect(),l=t.getBoundingClientRect(),c=new DOMRect(s.left-l.left,s.top-l.top,s.width,s.height);return i.style.left=`${c.left}px`,i.style.top=`${c.top}px`,i.style.width=`${c.width}px`,i.style.height=`${c.height}px`,i}function Dg(n,t,e,o){d(X8,j(n,t),"not a text kind block");const r=De(t,P(t,e,"normal")),i=t.getBoundingClientRect(),s=Rt(t);let l=s.querySelector(`.block-anchor[data-id=${o}]`);l||(l=b("div",["block-anchor"],s),l.setAttribute("data-id",o));const c=new DOMRect(r.left-i.left,r.top-i.top,r.width,r.height);return l.style.left=`${c.left}px`,l.style.top=`${c.top}px`,l.style.width=`${c.width}px`,l.style.height=`${c.height}px`,l}function ji(n){const t=zn(n);let e=0;return t.forEach(o=>{e+=Ne(o)}),e}const Lg=w("box");function Hi(n){return!n.attributes||!n.attributes.box?!1:(d(Lg,n.attributes.box===!0,`invalid op attribute box property, ${n.attributes.box}`),d(Lg,n.attributes.type,`no box type: ${JSON.stringify(n)}`),!0)}const Mg=w("rich-text-length");function Ad(n){return d(Mg,typeof n.insert=="string","op.insert is not string"),n.insert.length}function de(n){let t=0;return n.forEach(e=>{e.insert&&(d(Mg,typeof e.insert=="string","op.insert is not string"),t+=Ad(e))}),t}const vn=w("split-text");function be(n,t,e){if(n=Y.default(n),t===0)return{left:[],right:n};if(t===-1)return{left:n,right:[]};let o=0;for(let r=0;r<n.length;r++){const i=n[r];d(vn,typeof i=="object",`invalid op type, ${typeof i}`),d(vn,typeof i.insert=="string",`invalid op.insert type, ${typeof i.insert}`);const s=Ad(i);if(o+s<t)o+=s;else{if(o+s===t)return{left:n.slice(0,r+1),right:n.slice(r+1)};{d(vn,o+s>t,`invalid offset, ${o}, ${s}, ${t}`);const l=t-o,c=Y.default(i);d(vn,c.insert,"no copied.insert"),d(vn,typeof c.insert=="string","invalid copied.insert type"),c.insert=c.insert.substr(0,l),i.insert=i.insert.substr(l),c.insert===""&&d(vn,!1,"invalid copied.insert, is empty string"),i.insert===""&&d(vn,!1,"invalid op.insert, is empty string");const a=[i,...n.slice(r+1)],u=[...n.splice(0,r),c];return e&&(e.sourceOp=i),{left:u,right:a}}}}throw new Error(`invalid split offset: ${t}, ${JSON.stringify(n)}`)}function Gt(n,t,e){d(vn,t>=0,"invalid offset, < 0"),d(vn,e>0,"invalid length, <= 0"),d(vn,t+e<=de(n),"invalid offset + length < text length");const{left:o,right:r}=be(n,t+e),{left:i,right:s}=be(o,t);return{left:i,middle:s,right:r}}function Rg(n,t){const e=Array.from(new Set(t)).sort((i,s)=>i-s),o=[];let r=n;for(let i=e.length-1;i>=0;i--){const s=e[i],{left:l,right:c}=be(r,s);r=l,o.unshift(c)}return r.length>0&&o.unshift(r),o}function Ag(n,t,e){return Gt(n,t,e).middle}const Tr=w("text-block-content");function tb(n,t,e,o,r){if(d(Tr,o,"no text for block"),o.length===0&&(!r||r.size===0)){e.innerHTML="<span><br></span>";return}const i=[];r&&i.push(...r.keys());const s=f=>n.editorInsertions.createInsertion(e,f),l=(f,m)=>{const C=r==null?void 0:r.get(m);C&&(C.forEach(v=>{f.appendChild(s(v))}),r==null||r.delete(m))},c=document.createDocumentFragment();let a=0;const u=Rg(o,i);for(let f=0;f<u.length;f++){l(c,a);const m=u[f];a+=de(m);for(let C=0;C<m.length;C++){const v=m[C];if(Hi(v)){d(Tr,v.attributes,`op is not an valid box: ${JSON.stringify(v)}`);const y=n.editorBoxes.createBox(e,v.attributes);d(Tr,y instanceof HTMLSpanElement,`invalid box element: ${y.tagName}`),c.appendChild(y);continue}d(Tr,v.insert,`no insert in op: ${JSON.stringify(v)}`);const B=b("span",["text"],c,v.insert);if(v.attributes){const y=n.editorBlockRenders.renderText(t,v.attributes);y.classes&&A(B,...y.classes),y.attributes&&Object.entries(y.attributes).forEach(([S,I])=>{B.setAttribute(S,I)}),y.styles&&Object.entries(y.styles).forEach(([S,I])=>{B.style.setProperty(S,I)})}c.appendChild(B)}}l(c,a),e.innerHTML="",e.appendChild(c)}function Dl(n,t,e,o,r){const{text:i,insertions:s}=n.editorDecorators.decorateText(t,r),l=n.compositingText;if(l){const c=n.selection.range.start;d(Tr,c.isSimple(),"not an simple position while compositing"),c.blockId===e&&s.set(c.offset,[{type:"inputting",id:N(),text:l}])}return tb(n,t,o,i,s)}function eb(n){const t=n.rootContainer.querySelectorAll('span[data-type="editor-insertion"].inputting-insertion');t.length&&Tr.debug(`remove ${t.length} temp composition span`),Array.from(t).forEach(e=>e.remove())}const kn=w("client-rects");function nb(n){const t=zn(n);let e=0;const o=[];for(let r=0;r<t.length;r++){const i=t[r],s=Ne(i);o.push({child:i,startBlockOffset:e,endBlockOffset:e+s}),e+=s}return o}function ob(n,t,e,o){d(kn,e<o,`invalid from & to: ${e}, ${o}`);const r=W(n,t);d(kn,e>=0&&o>=0&&e<=r&&o<=r,`invalid offset: ${e}, ${o}, length: ${r}`);const i=nb(t),s=i.findIndex(C=>C.startBlockOffset<=e&&e<C.endBlockOffset),l=i.findIndex(C=>C.startBlockOffset<o&&o<=C.endBlockOffset);if(d(kn,s!==-1,"failed to find start child"),d(kn,l!==-1,"failed to find end child"),d(kn,s<=l,`invalid start index & end index: ${s}, ${l}`),s===l){const C=i[s];return[{child:C.child,startChildOffset:e-C.startBlockOffset,endChildOffset:o-C.startBlockOffset}]}const c=[],a=i[s],u={child:a.child,startChildOffset:e-a.startBlockOffset,endChildOffset:Ne(a.child)};c.push(u);for(let C=s+1;C<l;C++){const v=i[C],B={child:v.child,startChildOffset:0,endChildOffset:v.endBlockOffset-v.startBlockOffset};c.push(B)}const f=i[l],m={child:f.child,startChildOffset:0,endChildOffset:o-f.startBlockOffset};return c.push(m),c}function rb(n){const t=(o,r)=>o.left<=r.left&&o.top<=r.top&&o.right>=r.right&&o.bottom>=r.bottom&&(o.width!==r.width||o.height!==r.height);n=n.filter(o=>!n.find(i=>t(o,i)));const e=[];return n=n.filter(o=>e.find(r=>r.left===o.left&&r.top===o.top&&r.width===o.width&&r.height===o.height)?!1:(e.push(o),!0)),n}function Og(n,t,e,o){if(W(n,t)===0){const u=it(t).getBoundingClientRect();return[new DOMRect(u.left,u.top,4,u.height)]}const r=e.offset,i=o.offset;if(r===i)return[De(t,e)];const l=ob(n,t,r,i).map(a=>K8(a.child,a.startChildOffset,a.endChildOffset)),c=[];return l.forEach(a=>{const u=rb(Array.from(a.getClientRects()));c.push(...u)}),c}function ib(n,t,e){d(kn,e instanceof ce,"invalid range");const o=e.start,r=e.end;return d(kn,o.isSimple(),"text block only allow simple position"),d(kn,r.isSimple(),"text block only allow simple position"),d(kn,o.blockId===r.blockId,"only allow update one text block selection"),d(kn,o.blockId===q(t),"only allow update one text block selection"),Og(n,t,o,r)}const Od=w("selection-background");function sb(n,t,e,o){d(Od,e.isSimple(),"text block only allow simple position"),d(Od,o.isSimple(),"text block only allow simple position"),d(Od,e.blockId===o.blockId,"only allow update one text block selection");const r=e.offset,i=o.offset;if(r===i&&(W(n,t)!==0||n.selection.range.isCollapsed()))return;const s=Og(n,t,e,o),l=t.getBoundingClientRect(),c=Fm(t);c.innerHTML="",s.forEach(a=>{const u=b("div",["editor-selection-background"],c);u.style.left=`${a.left-l.left}px`,u.style.top=`${a.top-l.top}px`,u.style.width=`${a.width}px`,u.style.height=`${a.height}px`})}function lb(n){n.rootContainer.querySelectorAll("div[data-type=block-background]").forEach(t=>{t.remove()})}const Uo=w("text-offset"),_g="\u200D";function so(n,t){const e=zn(n);let o=0;for(let r=0;r<e.length;r++){const i=e[r],s=Ne(i);if(i===t){const l=o+s;return{start:o,end:l}}o+=s}d(Uo,!1,"can not find child in children")}function re(n,t){d(Uo,t>=0,`invalid offset: ${t}`);const e=Sl(n,t),{prev:o,next:r,offset:i}=e;if(!o&&!r&&d(Uo,!1,"invalid offset, no prev & next child at offset"),o!==r)return!0;const s=o;if(d(Uo,s,"no child"),_e(s))return d(Uo,i===0||i===1,`invalid box child offset: ${i}`),!0;const l=s.textContent;d(Uo,l,"no content for text child");const c=l.charAt(i-1),a=l.charAt(i);return!(c===_g||a===_g||Ya(l[i]))}function lo(n,t){if(t===0)return 0;const e=t-1;if(re(n,e))return e;let o=e-1;for(;!re(n,o);)o-=1;return o}function Vo(n,t){const e=ji(n);if(d(Uo,t>=0&&t<=e,`invalid offset: ${t}, ${e}`),t===e)return e;const o=t+1;if(re(n,o))return o;let r=o+1;for(;!re(n,r);)r+=1;return r}const qo=w("line-breaker");function Fi(n){const t=c=>{const a=hl(c);return Mo(c).top>a.top+a.height/2},e=(c,a)=>{const u=Mo(c);return hl(a).left<u.right},o=(c,a)=>{const u=Mo(c),f=Mo(a);return f.top+f.height/2>u.bottom},r=c=>{if(c.length===0||c.length===1)return!1;const a=c[0],u=c[c.length-1];return a.right-u.left>10},i=[];let s=0;const l=zn(n);for(let c=0;c<l.length;c++){const a=l[c];if(Fn(a)){const y=a,S=l[c+1];if(!S)break;const I=l[c-1];if(I&&o(I,y)&&i.push({offset:s,type:"betweenChild",childInfo:{prevChild:I,nextChild:y,wrap:"nextWrapped",prevWrapped:t(I),nextWrapped:t(y)}}),e(y,S)){i.push({offset:s,type:"betweenChild",childInfo:{prevChild:I,nextChild:y,wrap:"nowrap",prevWrapped:t(I),nextWrapped:t(y)}});continue}continue}if(_e(a)){const y=a,S=l[c+1];if(!S)break;const I=l[c-1];if(I&&o(I,y)&&i.push({offset:s,type:"betweenChild",childInfo:{prevChild:I,nextChild:y,wrap:"nextWrapped",prevWrapped:t(I),nextWrapped:t(y)}}),e(y,S)){s+=1,i.push({offset:s,type:"betweenChild",childInfo:{prevChild:I,nextChild:a,wrap:"nowrap",prevWrapped:t(I),nextWrapped:t(a)}});continue}s+=1;continue}const u=a,f=u.getClientRects();if(d(qo,f.length>0,"invalid text child dom"),f.length===1){const y=l[c+1];if(!y)break;if(e(u,y)){s+=Ne(u),i.push({offset:s,type:"betweenChild",childInfo:{prevChild:u,nextChild:y,wrap:"nowrap",prevWrapped:t(u),nextWrapped:t(y)}});continue}s+=Ne(u);continue}const m=u.firstChild;d(qo,m,"invalid text child, no text node"),d(qo,m instanceof Text,`invalid text child, not a valid text node: ${typeof m}`);const C=document.createRange(),v=document.createRange(),B=Ne(u);d(qo,m.data.length===B,"text node data length not equal child text length");for(let y=0;y<m.data.length;y++){if(!re(n,s+y))continue;C.setStart(m,y),od()&&C.selectNodeContents(m);const S=C.getClientRects();if(d(qo,S.length>=1,"invalid text node, no client rects"),r(S)){const Z=s+y;i.push({offset:Z,type:"textBreakWord",childInfo:{prevChild:a,nextChild:a,wrap:"nowrap",prevWrapped:t(a),nextWrapped:t(a)}});continue}let I=y+1;re(n,s+I)||(I=y+2),v.setStart(m,I);const M=v.getClientRects(),R=S[0];M[0].left<R.right&&d(qo,!1,"span pre-wrap should not has a line-wrap by white space")}s+=B}return i}function _d(n,t){const e=Fi(n);for(let o=0;o<e.length;o++){const{offset:r,type:i}=e[o];if(t.offset<r)return{lineIndex:o,lineBreaks:e};if(t.offset===r&&t.type==="end")return{lineIndex:o,lineBreaks:e}}return d(qo,t.offset<=ji(n),"invalid position, offset > block length"),{lineIndex:e.length,lineBreaks:e}}const cb=w("line-offset");function Nd(n){const t=Fi(n),e=[];let o=0;for(let r=0;r<t.length;r++){const i=t[r];e.push({start:o,end:i.offset}),o=i.offset}return e.push({start:o,end:ji(n)}),e}function Ll(n,t){const e=Nd(n);return d(cb,t>=0&&t<e.length,`invalid line index: ${t}, ${e.length}`),e[t]}function Ng(n,t){const{lineIndex:e}=_d(n,t);return Ll(n,e)}function ab(n){const t=Nd(n),e=n.getBoundingClientRect(),o=[];return t.forEach(({start:r,end:i})=>{const s=P(n,r,"home");let l=De(n,s);const c=P(n,i,"end"),a=De(n,c);l.top+l.height/2<a.top&&(l=new DOMRect(e.left-1e4,a.top,1,a.height));const u=new DOMRect(l.left,a.top,a.left-l.left,a.height),f=new DOMRect(e.left,a.top,e.width,a.height);o.push({start:r,end:i,rect:f,contentRect:u})}),o}function db(n,t,e){const r=ab(n).find(s=>Ao(s.rect,t,e));if(!r)return null;const i=r.contentRect;return t-i.left<i.right-t?P(n,r.start,"home"):P(n,r.end,"end")}function $g(n,t,e){const o=De(n,t),r=De(n,e),i=o.top+o.height/2,s=r.top+r.height/2,l=r.top<i&&i<r.bottom,c=o.top<s&&s<o.bottom;return l&&c}function Pg(n){return Nd(n).length}const Wo=w("find-text-position");function jg(n,t){const{start:e,end:o}=Ll(n,t),r=q(n),i=De(n,P(r,e,"home"));if(!(De(n,P(r,o,"end")).top>i.top+i.height/2))return!1;const c=Sl(n,e);return d(Wo,c.next,"no next child at offset"),d(Wo,!Pi(c.next),"next child is not text child"),!0}function ub(n,t){const e=q(n);d(Wo,jg(n,t),"line is not wrapped");const{start:o,end:r}=Ll(n,t),i=P(e,o,"home");for(let s=o+1;s<=r;s+=1){let l="normal";s===o?l="home":s===r&&(l="end");const c=P(e,s,l);if(!$g(n,i,c))return s-1}return d(Wo,!1,"failed to find wrapped offset"),0}function Ml(n,t,e,o,r,i,s){d(Wo,j(n,t),`not a text kind block: ${rt(t)}`);const{start:l,end:c}=Ll(t,e);let a=l;const u=q(t);if(t===o&&jg(t,e)){const y=ub(t,e);(i==="up"||i==="down"&&$g(t,r,P(u,l,"home")))&&(a=y+1)}let f=Number.MAX_SAFE_INTEGER;const m=Ke(n,o,r),C=s!=null?s:m.left+m.width/2,v=m.top+m.height/2;let B=P(u,a,"home");for(let y=a;y<=c;y++){if(!re(t,y))continue;let S="normal";y===l?S="home":y===c&&(S="end");const I=P(u,y,S),M=De(t,I),R=Cn(M,C,v);R<f&&(f=R,B=I)}return B}function hb(n,t,e,o,r){return d(Wo,j(n,t),"not a text block"),Ml(n,t,Pg(t)-1,e,o,"up",r)}function fb(n,t,e,o,r){return d(Wo,j(n,t),"not a text block"),Ml(n,t,0,e,o,"down",r)}function mb(n,t,e,o){const{lineIndex:r}=_d(t,e);if(r===Pg(t)-1)return null;const i=Ml(n,t,r+1,t,e,"down",o);return i||null}function gb(n,t){if(t.offset===0)return null;const e=Fi(n),o=e.find(r=>r.offset===t.offset);if(!o){const r=lo(n,t.offset);return e.find(s=>s.offset===r)?{offset:r,type:"home"}:{offset:r,type:"normal"}}if(o.type==="betweenChild"){if(t.type==="home"&&o.childInfo.wrap==="nowrap")return{offset:t.offset,type:"end"};if(o.childInfo.prevWrapped)return{offset:lo(n,t.offset),type:"normal"}}return{offset:lo(n,t.offset),type:"normal"}}function pb(n,t){const e=ji(n);if(t.offset===e)return null;const o=Fi(n),r=o.find(i=>i.offset===t.offset);if(!r){const i=Vo(n,t.offset),s=o.find(l=>l.offset===i);return s?s.type==="betweenChild"?{offset:i,type:"end"}:{offset:i,type:"home"}:{offset:i,type:"normal"}}return r.type==="betweenChild"?r.childInfo.wrap==="nowrap"&&t.type==="end"?{offset:t.offset,type:"home"}:{offset:Vo(n,t.offset),type:"home"}:{offset:Vo(n,t.offset),type:"normal"}}function Cb(n,t,e,o){const{lineIndex:r}=_d(t,e);if(r===0)return null;const i=Ml(n,t,r-1,t,e,"up",o);return i||null}const bb=w("move-caret");function vb(n,t,e,o){if(o==="ArrowLeft"){const r=gb(t,e);return r?P(q(t),r.offset,r.type):null}if(o==="ArrowRight"){const r=pb(t,e);return r?P(q(t),r.offset,r.type):null}if(o==="ArrowUp"){const r=Cb(n,t,e,n.selection.getSuggestedCaretX());return r?P(q(t),r.offset,r.type):null}if(o==="ArrowDown"){const r=mb(n,t,e,n.selection.getSuggestedCaretX());return r?P(q(t),r.offset,r.type):null}d(bb,!1,`invalid navigation direction: ${o}`)}const $d=w("text-range");function kb(n){const t=[];return zn(n).forEach(o=>{const r=Array.from(o.getClientRects()).map(i=>({rect:i,child:o}));t.push(...r)}),t}function yb(n,t,e){const o=kb(n);for(let r=1;r<o.length;r++){const i=o[r-1],s=o[r];if(t>=i.rect.right&&t<=s.rect.left&&e>=i.rect.top&&e<=i.rect.bottom&&e>=s.rect.top&&e<=s.rect.bottom)return so(n,s.child).start}return null}function wb(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t))return null;const i=r.closest("div[data-type=block-content]>span");if(!i){const S=t.getBoundingClientRect();if(!Ao(S,e,o))return null;const I=yb(t,e,o);if(I!==null){const R=P(t,I,"normal");return new ce(n,{anchor:R,focus:R})}const M=db(t,e,o);return M?new ce(n,{anchor:M,focus:M}):null}const s=zn(t);d($d,s.indexOf(i)!==-1,"failed to find child in children");const l=so(t,i);d($d,l,"failed to get child offset");const{start:c}=l;let a,u;Fn(i)||_e(i)?(a=c,u=0):(d($d,i.firstChild instanceof Text,"child is not text"),a=c+nm(i.firstChild,e,o),u=0);const f=q(t),C=Fi(t).find(S=>S.offset===a);let v="normal";if(C){const S=P(f,a,"home"),I=P(f,a,"end"),M=De(t,S),R=De(t,I),$=Cn(M,e,o),Z=Cn(R,e,o);v=$<Z?"home":"end"}const B=P(f,a,v);let y;return u&&(y=P(f,a+u,v)),new ce(n,{anchor:B,focus:y!=null?y:B})}const Bb=w("create-text-op");function $e(n,t){d(Bb,n,"text is empty");const e={insert:n};return t&&Object.keys(t).length>0&&(e.attributes=t),e}function Pd(n,t){if(n.length===0)return[];if(n.indexOf(`
16
16
  `)===-1)return[$e(n,t)];const e=n.replace(/\r\n/g,`
17
17
  `).replace(/\r/g,`
18
18
  `).replace(/\n/g," "),o=[];return e&&o.push($e(e,t)),o}const Rl=w("merge-ops");function jd(n){if(n.length<=1)return n;const t=(r,i)=>r.insert===void 0||i.insert===void 0||r.delete!==void 0||i.delete!==void 0||r.retain!==void 0||i.retain!==void 0||r.attributes!==void 0&&i.attributes===void 0||r.attributes===void 0&&i.attributes!==void 0?!1:r.attributes===void 0?(d(Rl,i.attributes===void 0,"op2.attributes is not undefined"),!0):(d(Rl,r.attributes&&i.attributes,"op1.attributes && op2.attributes is undefined"),cl.default(r.attributes,i.attributes)),e=[];let o=n[0];e.push(o);for(let r=1;r<n.length;r+=1){const i=n[r];t(o,i)?(d(Rl,typeof o.insert=="string","before.insert is not string"),d(Rl,typeof i.insert=="string","op.insert is not string"),o.insert+=i.insert):(e.push(i),o=i)}return e}function Eb(n){let t;for(t=n.length-1;t>=0;t--){const e=n[t];if(!e.attributes||!e.attributes.box||e.attributes.type!=="br")break}return t===n.length-1?n:n.slice(0,t+1)}const Hg=w("delete-text");function Hd(n,t,e){const{left:o,right:r}=Gt(n,t,e),i=[...o,...r];return jd(i)}function Fg(n,t){d(Hg,n>=0,`invalid offset: ${n}`),d(Hg,t>=1,`invalid delete count: ${t}`);const e=[];return n!==0&&e.push({retain:n}),e.push({delete:t}),e}const zg=w("delta");function Ug(n,t){const e=new oe.default(n),o=new oe.default(t);return e.diff(o).ops}function Ib(n,t,e){return new oe.default(t).transformPosition(n,!e)}function xb(n){d(zg,n,"ops is null or undefined");for(let t=0;t<n.length;t++){const e=n[t];if(e.insert===null||e.insert===void 0||e.retain!==void 0||e.delete!==void 0)return!1}return!0}function Tb(n,t){const e=new oe.default(n),o=new oe.default(t);return e.compose(o).ops}class ie{static ensureValidText(t){d(zg,xb(t),`text is not a valid text, ${JSON.stringify(t)}`)}static diff(t,e){return this.ensureValidText(t),this.ensureValidText(e),Ug(t,e)}static transformCursor(t,e,o){return Ib(t,e,o)}static transformOffset(t,e,o){const r=Ug(t,e),i=new oe.default(r);return o.map(s=>i.transformPosition(s))}static apply(t,e){this.ensureValidText(t);const o=Tb(t,e);return this.ensureValidText(o),o}}const Vg=w("insert-text");function Sr(n,t,e,o){d(Vg,e,`invalid text to insert: ${e}`);const{left:r,right:i}=be(n,t),s=typeof e=="string"?[$e(e,o)]:e,l=[...r,...s,...i];return jd(l)}function qg(n){return{insert:" ",attributes:n}}function Al(n,t,e){if(d(Vg,n>=0,`invalid offset: ${n}`),t.length===0)return[];const o=[];if(n>0&&o.push({retain:n}),typeof t!="string")return o.push(...t),o;const i={insert:t.replaceAll(`\r
19
19
  `," ").replaceAll(`
20
- `," ").replaceAll("\r"," ")};return e&&Object.keys(e).length>0&&(i.attributes=e),o.push(i),o}function Sb(n,t){return[...n,...t]}const Wg=w("text-op");function Fd(n){return d(Wg,typeof n.insert=="string","invalid op, no insert"),n.insert.length}function Gg(n,t){const e=n;let o=0;for(let r=0;r<e.length;r++){const i=e[r];d(Wg,typeof i.insert=="string","invalid text op, no insert");const s=o+Fd(i);if(s>t)return[i];if(s===t){const l=[i];return r<e.length-1&&l.push(e[r+1]),l}o=s}return[]}const zd="style-color-",Ud="style-bg-color-";function Ol(n,t,e){const o=Y.default(n);return o.forEach(r=>{if(!(r.attributes&&r.attributes.box===!0))if(e===void 0){if(!r.attributes||r.attributes[t]===void 0)return;delete r.attributes[t],Object.keys(r.attributes).length===0&&delete r.attributes}else r.attributes||(r.attributes={}),r.attributes[t]=e}),o}function Vd(n,t,e,o){const r=Y.default(n);return r.forEach(i=>{i.attributes&&i.attributes.box===!0||i.attributes&&((o==null?void 0:o.ignoreValue)||i.attributes[t]===e)&&(delete i.attributes[t],Object.keys(i.attributes).length===0&&delete i.attributes)}),r}function _l(n,t,e,o,r){if(t===0)return e;const i=Gt(e,n,t);return[...i.left,...Ol(i.middle,o,r),...i.right]}function Dr(n,t,e,o,r,i){if(t===0)return e;const s=Gt(e,n,t);return[...s.left,...Vd(s.middle,o,r,i),...s.right]}function Nl(n,t){const e=Gg(n,t);if(e.length===1)return e[0].attributes;if(e.length===2)return e[1].attributes}function Zg(n,t,e,o){if(t===0)return e;const r=Gt(e,n,t),i=r.middle.map(s=>o(s));return[...r.left,...i,...r.right]}function Yg(n,t){t==="color"?Object.keys(n).forEach(e=>{e.startsWith("style-color-")&&delete n[e]}):t==="backgroundColor"&&Object.keys(n).forEach(e=>{e.startsWith("style-bg-color-")&&delete n[e]})}function Db(n,t){if(!n.attributes||n.attributes.box)return;const e=n.attributes;Yg(e,t),Object.keys(e).length===0&&delete n.attributes}function Lb(n,t,e){n.attributes||(n.attributes={}),!n.attributes.box&&(t==="color"?n.attributes[`style-color-${e}`]=!0:n.attributes[`style-bg-color-${e}`]=!0)}function Qg(n,t,e,o,r){const i=Y.default(e);return Zg(n,t,i,l=>(Db(l,o),r!==null&&Lb(l,o,r),l))}function qd(n){var r,i;if(!n||n.box)return[null,null];const t=Array.from(Object.keys(n));let e=null,o=null;for(let s=0;s<t.length;s++){const l=t[s];l.startsWith(zd)?e=(r=Number.parseInt(l.substring(zd.length),10))!=null?r:null:l.startsWith(Ud)&&(o=(i=Number.parseInt(l.substring(Ud.length),10))!=null?i:null)}return[e,o]}function Kg(n,t,e){Yg(n,t),t==="color"?n[`style-color-${e}`]=!0:n[`style-bg-color-${e}`]=!0}function Jg(n){return n.attributes?n.attributes.box?[null,null]:qd(n.attributes):[null,null]}function Xg(n,t,e){let o=[];if(t===0?n!==0&&(o=Gt(e,n-1,1).middle):o=Gt(e,n,t).middle,o.length===0)return[null,null];let[r,i]=Jg(o[0]);if(r===null&&i===null)return[r,i];for(let s=1;s<o.length;s++){const l=o[s];if(!l.attributes)return[null,null];if(l.attributes.box)continue;const[c,a]=Jg(l);c===null||r===null?r=null:r=c===r?r:null,a===null||i===null?i=null:i=a===i?i:null}return[r,i]}function tp(n){return Y.default(n)}const Mb=w("update-op-attribute");function ep(n,t,e,o){const r=tp(n),i=r.findIndex(l=>l.attributes?l.attributes[t]===e:!1);d(Mb,i!==-1,`can not find op by key: ${t}, value: ${e}`);const s=r[i];return s.attributes={...s.attributes,...o},r}const Rb="\u200B",Ab=w("to-plain-text");function vt(n,t){let e="";return n.forEach(o=>{if(d(Ab,typeof o.insert=="string","invalid op"),o.attributes&&o.attributes.box===!0){if(t!=null&&t.boxReplacement){e+=t.boxReplacement;return}if(o.attributes.text){e+=o.attributes.text;return}e+=" "}e+=o.insert}),e}function $l(n,t,e,o){const r=Nl(n,t),i=Hd(n,t,e-t);return o?Sr(i,t,o,r!=null?r:null):i}function Wd(n,t){if(!t)return[];const e=t.length,o=vt(n,{boxReplacement:" "}).toLowerCase();t=t.toLowerCase();let r=o.indexOf(t,0);const i=[];for(;r!==-1;)i.push({start:r,end:r+e}),r=o.indexOf(t,r+e);return i}function np(n,t,e,o){const r=Wd(n,t);let i=Y.default(n);return r.length===0||(r.reverse().forEach(s=>{i=$l(i,s.start,s.end,e)}),o&&(o.count=r.length)),i}function Go(n,t){return n?[{insert:n,attributes:t}]:[]}function zn(n,t){return{id:N(),type:"text",text:typeof n=="string"?Go(n):n,...t}}function Pl(n){return zn(n!=null?n:"")}function Zo(n,t){return{blocks:{root:(n!=null?n:"").replaceAll("\r","").split(`
21
- `).map((r,i)=>{const l=i===0&&(t==null?void 0:t.firstLineAsTitle)?{heading:1}:void 0;return zn(r,l)})},meta:{},comments:{}}}function jl(n){const t=n.blocks.root;if(t.length!==1)return!1;const e=t[0];return!(!e.text||de(e.text))}function op(n,t){const e=N();return n.localInsertChildContainer(e,t),e}function yn(n,t){return op(n,[Pl(t)])}function rp(n){return typeof n.offset=="number"}function Hl(n){return rp(n.anchor)}function Ob(n){return Hl(n)&&n.anchor.offset===n.focus.offset&&n.anchor.blockId===n.focus.blockId}function ip(n,t){return{blockId:n,offset:t}}function Fl(n,t){const e=ip(n,t);return{anchor:e,focus:e}}function sp(n,t){return{blockId:n,childContainerId:t}}function _b(n,t){const e=sp(n,t);return{anchor:e,focus:e}}const Nb=w("block-to-text");function $b(n,t,e){let o="";return t.forEach(r=>{if(d(Nb,typeof r.insert=="string","invalid op"),r.attributes&&r.attributes.box===!0){const i=r.attributes,s=n.editorBoxes.getBoxClass(i.type);if(s!=null&&s.convertTo){o+=s.convertTo(n,i,e,"text");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${i.type}]`}o+=r.insert}),o}const Pb=w("block-to-text");function jb(n,t,e){let o="";return t.forEach(r=>{if(d(Pb,typeof r.insert=="string","invalid op"),r.attributes&&r.attributes.box===!0){const s=r.attributes,l=n.editorBoxes.getBoxClass(s.type);if(l!=null&&l.convertTo){o+=l.convertTo(n,s,e,"markdown");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${s.type}]`}const i=r.attributes;if(i){let s=r.insert;i.link&&(s=`[${s}](${i.link})`);const l=[];i["style-code"]?l.push("`"):(i["style-bold"]&&l.push("**"),i["style-italic"]&&l.push("*"),i["style-underline"]&&l.push("__"),i["style-strikethrough"]&&l.push("~~"));const c=l.join("");o.endsWith(c.substring(0,1))&&(o+=" ");const a=l.reverse().join("");o+=c+s+a;return}o+=r.insert}),o}function Hb(n,t,e){const o=t.text||[];let i=jb(n,o,e);if(t.heading){const s=t.heading;i=`${"#".repeat(s)} ${i}`}return t.quoted&&(i=`> ${i}`),t.type==="text"&&(i=`${i}
20
+ `," ").replaceAll("\r"," ")};return e&&Object.keys(e).length>0&&(i.attributes=e),o.push(i),o}function Sb(n,t){return[...n,...t]}const Wg=w("text-op");function Fd(n){return d(Wg,typeof n.insert=="string","invalid op, no insert"),n.insert.length}function Gg(n,t){const e=n;let o=0;for(let r=0;r<e.length;r++){const i=e[r];d(Wg,typeof i.insert=="string","invalid text op, no insert");const s=o+Fd(i);if(s>t)return[i];if(s===t){const l=[i];return r<e.length-1&&l.push(e[r+1]),l}o=s}return[]}const zd="style-color-",Ud="style-bg-color-";function Ol(n,t,e){const o=Y.default(n);return o.forEach(r=>{if(!(r.attributes&&r.attributes.box===!0))if(e===void 0){if(!r.attributes||r.attributes[t]===void 0)return;delete r.attributes[t],Object.keys(r.attributes).length===0&&delete r.attributes}else r.attributes||(r.attributes={}),r.attributes[t]=e}),o}function Vd(n,t,e,o){const r=Y.default(n);return r.forEach(i=>{i.attributes&&i.attributes.box===!0||i.attributes&&((o==null?void 0:o.ignoreValue)||i.attributes[t]===e)&&(delete i.attributes[t],Object.keys(i.attributes).length===0&&delete i.attributes)}),r}function _l(n,t,e,o,r){if(t===0)return e;const i=Gt(e,n,t);return[...i.left,...Ol(i.middle,o,r),...i.right]}function Dr(n,t,e,o,r,i){if(t===0)return e;const s=Gt(e,n,t);return[...s.left,...Vd(s.middle,o,r,i),...s.right]}function Nl(n,t){const e=Gg(n,t);if(e.length===1)return e[0].attributes;if(e.length===2)return e[1].attributes}function Zg(n,t,e,o){if(t===0)return e;const r=Gt(e,n,t),i=r.middle.map(s=>o(s));return[...r.left,...i,...r.right]}function Yg(n,t){t==="color"?Object.keys(n).forEach(e=>{e.startsWith("style-color-")&&delete n[e]}):t==="backgroundColor"&&Object.keys(n).forEach(e=>{e.startsWith("style-bg-color-")&&delete n[e]})}function Db(n,t){if(!n.attributes||n.attributes.box)return;const e=n.attributes;Yg(e,t),Object.keys(e).length===0&&delete n.attributes}function Lb(n,t,e){n.attributes||(n.attributes={}),!n.attributes.box&&(t==="color"?n.attributes[`style-color-${e}`]=!0:n.attributes[`style-bg-color-${e}`]=!0)}function Qg(n,t,e,o,r){const i=Y.default(e);return Zg(n,t,i,l=>(Db(l,o),r!==null&&Lb(l,o,r),l))}function qd(n){var r,i;if(!n||n.box)return[null,null];const t=Array.from(Object.keys(n));let e=null,o=null;for(let s=0;s<t.length;s++){const l=t[s];l.startsWith(zd)?e=(r=Number.parseInt(l.substring(zd.length),10))!=null?r:null:l.startsWith(Ud)&&(o=(i=Number.parseInt(l.substring(Ud.length),10))!=null?i:null)}return[e,o]}function Kg(n,t,e){Yg(n,t),t==="color"?n[`style-color-${e}`]=!0:n[`style-bg-color-${e}`]=!0}function Jg(n){return n.attributes?n.attributes.box?[null,null]:qd(n.attributes):[null,null]}function Xg(n,t,e){let o=[];if(t===0?n!==0&&(o=Gt(e,n-1,1).middle):o=Gt(e,n,t).middle,o.length===0)return[null,null];let[r,i]=Jg(o[0]);if(r===null&&i===null)return[r,i];for(let s=1;s<o.length;s++){const l=o[s];if(!l.attributes)return[null,null];if(l.attributes.box)continue;const[c,a]=Jg(l);c===null||r===null?r=null:r=c===r?r:null,a===null||i===null?i=null:i=a===i?i:null}return[r,i]}function tp(n){return Y.default(n)}const Mb=w("update-op-attribute");function ep(n,t,e,o){const r=tp(n),i=r.findIndex(l=>l.attributes?l.attributes[t]===e:!1);d(Mb,i!==-1,`can not find op by key: ${t}, value: ${e}`);const s=r[i];return s.attributes={...s.attributes,...o},r}const Rb="\u200B",Ab=w("to-plain-text");function vt(n,t){let e="";return n.forEach(o=>{if(d(Ab,typeof o.insert=="string","invalid op"),o.attributes&&o.attributes.box===!0){if(t!=null&&t.boxReplacement){e+=t.boxReplacement;return}if(o.attributes.text){e+=o.attributes.text;return}e+=" "}e+=o.insert}),e}function $l(n,t,e,o){const r=Nl(n,t),i=Hd(n,t,e-t);return o?Sr(i,t,o,r!=null?r:null):i}function Wd(n,t){if(!t)return[];const e=t.length,o=vt(n,{boxReplacement:" "}).toLowerCase();t=t.toLowerCase();let r=o.indexOf(t,0);const i=[];for(;r!==-1;)i.push({start:r,end:r+e}),r=o.indexOf(t,r+e);return i}function np(n,t,e,o){const r=Wd(n,t);let i=Y.default(n);return r.length===0||(r.reverse().forEach(s=>{i=$l(i,s.start,s.end,e)}),o&&(o.count=r.length)),i}function Go(n,t){return n?[{insert:n,attributes:t}]:[]}function Un(n,t){return{id:N(),type:"text",text:typeof n=="string"?Go(n):n,...t}}function Pl(n){return Un(n!=null?n:"")}function Zo(n,t){return{blocks:{root:(n!=null?n:"").replaceAll("\r","").split(`
21
+ `).map((r,i)=>{const l=i===0&&(t==null?void 0:t.firstLineAsTitle)?{heading:1}:void 0;return Un(r,l)})},meta:{},comments:{}}}function jl(n){const t=n.blocks.root;if(t.length!==1)return!1;const e=t[0];return!(!e.text||de(e.text))}function op(n,t){const e=N();return n.localInsertChildContainer(e,t),e}function yn(n,t){return op(n,[Pl(t)])}function rp(n){return typeof n.offset=="number"}function Hl(n){return rp(n.anchor)}function Ob(n){return Hl(n)&&n.anchor.offset===n.focus.offset&&n.anchor.blockId===n.focus.blockId}function ip(n,t){return{blockId:n,offset:t}}function Fl(n,t){const e=ip(n,t);return{anchor:e,focus:e}}function sp(n,t){return{blockId:n,childContainerId:t}}function _b(n,t){const e=sp(n,t);return{anchor:e,focus:e}}const Nb=w("block-to-text");function $b(n,t,e){let o="";return t.forEach(r=>{if(d(Nb,typeof r.insert=="string","invalid op"),r.attributes&&r.attributes.box===!0){const i=r.attributes,s=n.editorBoxes.getBoxClass(i.type);if(s!=null&&s.convertTo){o+=s.convertTo(n,i,e,"text");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${i.type}]`}o+=r.insert}),o}const Pb=w("block-to-text");function jb(n,t,e){let o="";return t.forEach(r=>{if(d(Pb,typeof r.insert=="string","invalid op"),r.attributes&&r.attributes.box===!0){const s=r.attributes,l=n.editorBoxes.getBoxClass(s.type);if(l!=null&&l.convertTo){o+=l.convertTo(n,s,e,"markdown");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${s.type}]`}const i=r.attributes;if(i){let s=r.insert;i.link&&(s=`[${s}](${i.link})`);const l=[];i["style-code"]?l.push("`"):(i["style-bold"]&&l.push("**"),i["style-italic"]&&l.push("*"),i["style-underline"]&&l.push("__"),i["style-strikethrough"]&&l.push("~~"));const c=l.join("");o.endsWith(c.substring(0,1))&&(o+=" ");const a=l.reverse().join("");o+=c+s+a;return}o+=r.insert}),o}function Hb(n,t,e){const o=t.text||[];let i=jb(n,o,e);if(t.heading){const s=t.heading;i=`${"#".repeat(s)} ${i}`}return t.quoted&&(i=`> ${i}`),t.type==="text"&&(i=`${i}
22
22
  `),i}const Fb=w("block-to-text");function zb(n,t,e){let o="";return t.forEach(r=>{if(d(Fb,typeof r.insert=="string","invalid op"),r.attributes&&r.attributes.box===!0){const s=r.attributes,l=n.editorBoxes.getBoxClass(s.type);if(l!=null&&l.convertTo){o+=l.convertTo(n,s,e,"html");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${s.type}]`}const i=r.attributes;if(i){let s=r.insert;i.link&&(s=`<a href="${i.link}">${s}</a>`);const l=[];i.bold&&l.push("strong"),i.italic&&l.push("em"),i.underline&&l.push("u"),i.strike&&l.push("s"),i.code&&l.push("code");const c=l.map(u=>`<${u}>`).join(""),a=l.reverse().map(u=>`</${u}>`).join("");o+=c+s+a;return}o+=r.insert}),o||(o="<br>"),`<p>${o}</p>`}const zi=w("text-block");function Ub(n,t,e,o,r){const{text:i}=r;d(zi,i,"no text for text block");const s=ro(o,"div");return Dl(n,t,r.id,s,i),s}function Vb(n,t,e){d(zi,e,"no text to update");const o=ro(null,"div");Dl(n,jo(t),q(t),o,e);const r=it(t);Mi(r,o)}function qb(n,t,e){return ib(n,t,e)}function lp(n,t){let e="";return t.forEach(o=>{if(!!o.insert){if(o.attributes&&o.attributes.box===!0&&o.attributes.type==="math"){e+=`[${T.t("mathjax.abstract")}] `;return}e+=o.insert}}),e}function Wb(n,t){d(zi,j(n,t),"block in not textBlock");const e=n.selection.range;let o="";if(e.isCollapsed()){const r=n.getBlockText(t);o=lp(n,r)}else{const r=q(t),i=tn(n,{simpleBlockOnly:!0}).find(s=>q(s.block)===r);if(i&&!Tt(n,i.block)){d(zi,i.block===t,"block not match");const s=n.getBlockText(t),{start:l,end:c}=i,a=l.offset,u=c.offset-a;if(u>0){const{middle:f}=Gt(s,a,u);o=lp(n,f)}}}return{abstract:o.trim()}}function Gb(n,t,e,o){return d(zi,t.text,"no text for text block"),o==="text"?$b(n,t.text,e):o==="markdown"?Hb(n,t,e):zb(n,t.text,e)}const ve={blockType:"text",blockKind:"text",createBlockContent:Ub,getBlockTextLength:ji,getRangeFromPoint:wb,moveCaret:vb,updateSelection:sb,clearSelection:lb,getCaretRect:De,getClientRects:qb,setBlockText:Vb,getBlockProperties:Wb,convertTo:Gb},Zb=Dl,zl=w("action-helper");function co(n,t){const e=H(t),o=U(e),r=J(t);return n.doc.getBlockData(o,r)}function ue(n,t){d(zl,j(n,t),"not a text kind block");const o=co(n,t).text;return d(zl,o,"no text in block"),o}function Ul(n,t,e){return be(ue(n,t),e).left}function cp(n,t){const e=F(t);d(zl,e,"no parent block");const o=ue(n,e),r=Vm(t),i=o.find(s=>{const l=s.attributes;return l?l.box&&l.id===r:!1});return d(zl,i,"failed to find box"),i.attributes}const St=w("block-text");function Yb(n,t,e){d(St,j(n,t),"not a text kind block"),d(St,re(t,e),"not a valid offset"),d(St,e>=0&&e<W(n,t),`invalid offset: ${e}`);const r=Vo(t,e)-e;r===0&&d(St,!1,`no text after offset: ${e}`);const i=ue(n,t),{middle:s}=Gt(i,e,r);d(St,s.length===1,"failed to split text to 3 parts");const l=s[0];return Hi(l)?" ":(d(St,l.insert.length===1||l.insert.length===2,"invalid op"),l.insert)}function Qb(n,t,e){d(St,j(n,t),"not a text kind block"),d(St,re(t,e),"not a valid offset"),d(St,e>0&&e<=W(n,t),`invalid offset: ${e}`);const o=lo(t,e),r=e-o;r===0&&d(St,!1,`no text before offset: ${e}`);const i=ue(n,t),{middle:s}=Gt(i,o,r);d(St,s.length===1,"failed to split text to 3 parts");const l=s[0];return Hi(l)?" ":(d(St,l.insert.length===1||l.insert.length===2,"invalid op"),l.insert)}function Vl(n,t,e){d(St,j(n,t),"not a text kind block"),d(St,re(t,e),"not a valid offset"),d(St,e>0&&e<=W(n,t),`invalid offset: ${e}`);const o=lo(t,e),r=e-o;r===0&&d(St,!1,`no text before offset: ${e}`);const i=ue(n,t),{middle:s}=Gt(i,o,r);d(St,s.length===1,"failed to split text to 3 parts");const l=s[0];return Hi(l)?{op:l,charType:"box",offset:o,length:1}:{op:l,charType:ml(l.insert)?"space":"text",offset:o,length:l.insert.length}}function Ui(n,t,e){d(St,j(n,t),"not a text kind block"),d(St,re(t,e),"not a valid offset"),d(St,e>=0&&e<W(n,t),`invalid offset: ${e}`);const r=Vo(t,e)-e;r===0&&d(St,!1,`no text after offset: ${e}`);const i=ue(n,t),{middle:s}=Gt(i,e,r);d(St,s.length===1,"failed to split text to 3 parts");const l=s[0];return Hi(l)?{op:l,charType:"box",offset:e,length:1}:{op:l,charType:ml(l.insert)?"space":"text",offset:e,length:l.insert.length}}function Kb(n,t,e,o){let r=e;for(;r>0;){const i=Vl(n,t,r);if(i.charType===o)return i;r-=i.length}return null}function Jb(n,t,e,o){const r=W(n,t);let i=e;for(;i<r;){const s=Ui(n,t,i);if(s.charType===o)return s;i+=s.length}return null}function Gd(n,t,e,o){let r=e;for(;r>0;){const i=Vl(n,t,r);if(i.charType!==o)return i;r-=i.length}return null}function Zd(n,t,e,o){const r=W(n,t);let i=e;for(;i<r;){const s=Ui(n,t,i);if(s.charType!==o)return s;i+=s.length}return null}function Yd(n,t,e){if(d(St,j(n,t),"invalid blok type"),Tt(n,t))return 0;const o=Vl(n,t,e);if(o.charType==="box")return e-1;let r=e;if(o.charType==="space"){const s=Gd(n,t,r,"space");if(!s||s.offset===0)return 0;if(s.charType==="box")return s.offset;r=s.offset}const i=Gd(n,t,r,"text");return i?i.offset+i.length:0}function Qd(n,t,e){if(d(St,j(n,t),"invalid blok type"),Tt(n,t))return 0;const o=Ui(n,t,e);if(o.charType==="box")return e+1;let r=e;if(o.charType==="space"){const s=Zd(n,t,r,"space");if(!s||s.offset===0)return W(n,t);if(s.charType==="box")return s.offset;r=s.offset}const i=Zd(n,t,r,"text");return i?i.offset:W(n,t)}const ap=w("text-box");function Xb(n,t,e,o){d(ap,o.text,`no text for text box data: ${JSON.stringify(o)}`),d(ap,typeof o.text=="string",`invalid text type for text box data: ${JSON.stringify(o)}`),b("span",[],e,o.text)}function tv(n,t,e,o){var r;return(r=t.text)!=null?r:""}const dp={boxType:"text",updateBoxContent:Xb,convertTo:tv},ev="data:image/svg+xml;base64,Cjxzdmcgdmlld0JveD0iMCAwIDI0IDI0IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNMTguMjQ0NSA2QzE3LjgyNzQgNiAxNy41MzYzIDYuMjkxMTcgMTcuNTM2MyA2LjcwODI2QzE3LjUzNjMgNi45ODM3IDE3LjU1OTkgNy4yMzU1MyAxNy41NTk5IDcuNjEzMjdDMTcuNTU5OSAxMC4yODExIDE2LjYyMzQgMTEuMzc0OSAxMy45NzkyIDExLjM3NDlIOC45NDI2Nkw3LjEyNDc5IDExLjQ4NTFMOS41NDA3NSA5LjI4MTYyTDExLjE5MzQgNy41OTc1M0MxMS4zMjcxIDcuNDcxNjEgMTEuMzk4IDcuMjgyNzQgMTEuMzk4IDcuMDkzODdDMTEuMzk4IDYuNjkyNTIgMTEuMDk4OSA2LjQwMTM1IDEwLjY5NzYgNi40MDEzNUMxMC41MDg3IDYuNDAxMzUgMTAuMzM1NiA2LjQ3MjE4IDEwLjE3ODIgNi42MjE3TDUuMjQzOTYgMTEuNTQ4MUM1LjA4NjU3IDExLjcwNTUgNSAxMS44OTQzIDUgMTIuMDkxMUM1IDEyLjI4NzggNS4wODY1NyAxMi40NzY3IDUuMjQzOTYgMTIuNjI2MkwxMC4xNjI1IDE3LjUzNjhDMTAuMzM1NiAxNy43MDk5IDEwLjUwODcgMTcuNzgwOCAxMC42OTc2IDE3Ljc4MDhDMTEuMDk4OSAxNy43ODA4IDExLjM5OCAxNy40ODk2IDExLjM5OCAxNy4wODgzQzExLjM5OCAxNi44OTE1IDExLjMyNzEgMTYuNzEwNSAxMS4xOTM0IDE2LjU4NDZMOS41NDA3NSAxNC45MDA1TDcuMTMyNjYgMTIuNjk3TDguOTQyNjYgMTIuODA3MkgxNC4wNTc5QzE3LjU1OTkgMTIuODA3MiAxOSAxMS4yNDExIDE5IDcuNjc2MjJDMTkgNy4yMzU1MyAxOC45OTIxIDYuODY1NjUgMTguOTM3IDYuNjEzODNDMTguODc0MSA2LjI5OTA0IDE4LjY3NzMgNiAxOC4yNDQ1IDZaIiBmaWxsPSIjQjJCQ0NEIi8+Cjwvc3ZnPgo=";function nv(n,t,e,o){tm(ev,[],e),b("br",[],e)}function ov(n,t,e,o){return o==="text"?`
23
23
  `:o==="html"?"<br>":o==="markdown"?`
24
24
  `:""}const up={boxType:"br",updateBoxContent:nv,convertTo:ov},hp=w("editor-boxes");class fp{constructor(t){h(this,"boxes",new Map);this.editor=t}registerBoxClass(t){const e=t.boxType,o=this.boxes.get(e);d(hp,!o,`duplicated box type: ${e}`),this.boxes.set(e,t)}getBoxClass(t){const e=this.boxes.get(t);return d(hp,e,`unknown box type: ${t}`),e}createBox(t,e){const o=Um(e),r=qm(o);return this.getBoxClass(e.type).updateBoxContent(this.editor,o,r,e),o}}function rv(n,t,e,o){b("span",[],e,o.text)}const mp={insertionType:"inputting",updateInsertionContent:rv},gp=w("editor-insertion");class pp{constructor(t){h(this,"insertions",new Map);this.editor=t}registerInsertionClass(t){const e=t.insertionType,o=this.insertions.get(e);d(gp,!o,`duplicated insertion type: ${e}`),this.insertions.set(e,t)}getInsertionClass(t){const e=this.insertions.get(t);return d(gp,e,`unknown insertion type: ${t}`),e}createInsertion(t,e){const o=Wm(e.type,e.id),r=Zm(o);return this.getInsertionClass(e.type).updateInsertionContent(this.editor,o,r,e),o}}class iv{constructor(t){h(this,"cursors",new Map);h(this,"timer");this.editor=t,this.timer=this.startTimer()}add(t,e){this.cursors.set(t,e)}startTimer(){return setInterval(()=>{const t=Date.now();Array.from(this.cursors).forEach(([e,o])=>{if(t-o>3e3){const r=Gm(this.editor,e);r&&z(r,"active"),this.cursors.delete(e)}})},1e3)}destroy(){clearInterval(this.timer)}}function sv(n,t,e,o){var l;const r=o;Date.now()-r.time<5*1e3&&(n.addCustom("active-cursors",a=>new iv(a)).add(r.id,r.time),A(t,"active")),b("span",[],e,"|").setAttribute("data-cursor-name",r.name),t.style.setProperty("--cursor-color",n.getColor((l=r.rainbowIndex)!=null?l:0))}const Kd={insertionType:"remote-cursor",updateInsertionContent:sv};class Cp{constructor(t){h(this,"decorators",[]);this.editor=t}registerDecorator(t){this.decorators.push(t)}decorateBlock(t,e){let o=e;return this.decorators.forEach(r=>{if(r.decorateBlock){const i=r.decorateBlock(this.editor,t,e);i&&(o=Y.default(i))}}),o}decorateText(t,e){let o=e;const r=new Map;return this.decorators.forEach(i=>{if(i.decorateText){const s=i.decorateText(this.editor,t,e);if(s){const{insertions:l,text:c}=s;l&&Array.from(l.entries()).forEach(([a,u])=>{const f=r.get(a);f?f.push(...u):r.set(a,u)}),c&&(o=Y.default(c))}}}),{insertions:r,text:o}}}const Jd=w("editor-input");class lv{constructor(t,e){h(this,"editor");h(this,"composing",!1);h(this,"callbacks");h(this,"inputElement");h(this,"handleDocumentSelectionChange",()=>{setTimeout(()=>{var e;const t=(e=document.getSelection())==null?void 0:e.focusNode;t&&this.editor.contains(t)&&!Ai(t)?(this.editor.emit("focus",this.editor),this.callbacks.onFocus(),this.editor.input.focus()):(this.editor.emit("blur",this.editor),this.callbacks.onBlur())},100)});h(this,"handleEditorSelectionChanged",()=>{const e=!this.editor.isWritable();this.inputElement.readOnly=e});h(this,"handleReadonlyChanged",()=>{this.handleEditorSelectionChanged()});h(this,"handleCompositionstart",t=>{this.composing=!0,this.callbacks.onCompositionStart(t)});h(this,"handleCompositionend",t=>{this.composing=!1,this.callbacks.onUpdateCompositionText(t,this.inputElement.value,!0),this.inputElement.value=""});h(this,"handleInput",t=>{if(t instanceof InputEvent&&!!t.data){if(this.editor.readonly){this.inputElement.value="";return}this.composing?this.callbacks.onUpdateCompositionText(t,t.data,!1):(this.callbacks.onInsertText(t,t.data),this.inputElement.value="")}});h(this,"handleKeyDown",t=>{if(!this.composing){if(this.callbacks.onKeyDown(t)){t.preventDefault(),t.stopPropagation();return}setTimeout(()=>{this.composing||(this.inputElement.value="")})}});h(this,"handleCopy",t=>{this.callbacks.onCopy(t)});h(this,"handleCut",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}Jd.debug("on cut")});h(this,"handlePaste",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}this.callbacks.onPaste(t)});h(this,"handlePasteText",t=>{this.callbacks.onPasteText(t)});this.editor=t,this.callbacks=e;const o=b("input",["editor-input"],t.contentElement);o.type="text",o.name="editor-input",o.onkeydown=this.handleKeyDown,o.oninput=this.handleInput,o.oncopy=this.handleCopy,o.onpaste=this.handlePaste,o.oncut=this.handleCut,o.addEventListener("compositionstart",this.handleCompositionstart),o.addEventListener("compositionend",this.handleCompositionend),this.inputElement=o,document.addEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.addListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}destroy(){this.callbacks.destroy(),document.removeEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.removeListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged);const t=this.inputElement;t.removeEventListener("compositionstart",this.handleCompositionstart),t.removeEventListener("compositionend",this.handleCompositionend),t.onkeydown=null,t.oninput=null,t.oncopy=null,t.onpaste=null,t.oncut=null}getInput(){return this.inputElement}focus(){this.editor.selection.caret.visible()||this.editor.selection.caret.update(),xt.isMobileSafari?this.inputElement.focus():setTimeout(()=>{this.inputElement.focus()})}handleChanged(t){this.callbacks.onChanged(t)}handleRemoteChanged(t){this.callbacks.onRemoteChanged(t)}addHandler(t){this.callbacks.addHandler(t)}removeHandler(t){this.callbacks.removeHandler(t)}defaultInsertText(t,e,o,r,i){d(Jd,t===this.editor,"invalid editor"),this.callbacks.defaultInsertText(t,e,o,r,i)}defaultHandleKeydown(t,e){return d(Jd,t===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(t,e)}}function bp(n){const e=n.rootElement.getBoundingClientRect(),o=window.innerWidth,r=window.innerHeight,i=e.left<0?0:e.left,s=e.top<0?0:e.top,l=e.right>o?o:e.right,c=e.bottom>r?r:e.bottom,a=(i+l)/2,u=(s+c)/2,f=0-e.left+a,m=0-e.top+u,C=n.input.inputElement;C.style.left=`${f}px`,C.style.top=`${m}px`}const Xd=w("editor-caret");class cv{constructor(t){h(this,"editor");h(this,"caretElem");h(this,"handleReadOnlyChanged",()=>{this.update()});this.editor=t,this.caretElem=b("div",["editor-cursor"],this.editor.contentElement),this.editor.on("readonlyChanged",this.handleReadOnlyChanged)}destroy(){this.editor.off("readonlyChanged",this.handleReadOnlyChanged)}visible(){const t=window.getComputedStyle(this.caretElem);return t.display!=="none"&&t.opacity!=="0"}hasCaret(){if(this.editor.readonly||!this.editor.selection.range.isCollapsed())return!1;const t=this.editor.selection.range.start;if(!(t instanceof qt))return!1;const e=this.editor.getBlockById(t.blockId);return!!j(this.editor,e)}update(){if(om(this.editor.rootElement))return;const t=this.caretElem;if(this.hasCaret())t.style.display="";else{t.style.display="none",bp(this.editor);return}const{range:e}=this.editor.selection;d(Xd,e.isCollapsed,"range is not collapsed");const o=e.start;d(Xd,o instanceof qt,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);d(Xd,j(this.editor,r),"only text kind block can has caret");let i;const s=r.querySelector("span.inputting-insertion");s?(i=Mo(s),i=new DOMRect(i.right,i.top,1,i.height)):i=De(r,o);const l=this.editor.contentElement.getBoundingClientRect(),c=i.left-l.left,a=i.top-l.top;t.style.left=`${c}px`,t.style.top=`${a}px`,t.style.height=`${i.height}px`;const u=this.editor.input.inputElement;u.style.left=`${c}px`,u.style.top=`${a+i.height-24}px`,xt.isMobileSafari&&(u.style.left=`${c-4}px`,u.style.height=`${i.height}px`);const m=We(r,{horizontal:!0}).getBoundingClientRect(),C=m.left-l.left,v=C+m.width;c<C||c>v?(bp(this.editor),t.style.opacity="0"):t.style.opacity="1"}}function av(n){lg(n),n.selection.range.getSelectedBlocks().forEach(t=>cg(n,t.block,t.start,t.end))}function vp(n){return We(n.rootContainer).clientHeight}function dv(n){return n.getFirstBlock().getBoundingClientRect().top}function uv(n){return n.getLastBlock().getBoundingClientRect().bottom}function tu(n){const e=We(n.rootContainer).getBoundingClientRect(),o=e.x<0?0:e.x,r=e.y<0?0:e.y,i=e.right>window.innerWidth?window.innerWidth:e.right,s=e.bottom>window.innerHeight?window.innerHeight:e.bottom;return new DOMRect(o,r,i-o,s-r)}function hv(n,t){const e=tu(n),o=n.getBlockById(t.blockId),i=Ke(n,o,t);return Ao(e,i.x,i.y)&&Ao(e,i.right,i.bottom)}function fv(n,t){const e=tu(n),o=t.getBoundingClientRect();return o.top>=e.top&&o.top<=e.bottom||o.bottom<=e.bottom&&o.bottom>=e.top}function mv(n,t){const e=tu(n),o=t.getBoundingClientRect();return Ao(e,o.x,o.y)||Ao(e,o.right,o.bottom)}function gv(n){const t=n.selection,e=t.range.focus;if(!e.isSimple()){const a=e,u=n.getContainerById(a.childContainerId);mv(n,u)||u.scrollIntoView();return}if(t.range.start.blockId===t.range.end.blockId){const a=n.getBlockById(t.range.start.blockId);if(Te(a)&&fv(n,a))return}const o=e,r=n.getBlockById(o.blockId);if(hv(n,o))return;const i=Ke(n,r,o),s=r.getBoundingClientRect(),l=Rt(r),c=b("div",["editor-block-anchor"],l);c.style.top=`${i.top-s.top}px`,td(c,{elementToScroll:We(n.rootContainer)}),setTimeout(()=>{c.remove()},200)}function pv(n,t){if(t.isCollapsed())return!1;const e=Vt(n.rootContainer),o=Qt(n.rootContainer),{start:r,end:i}=t;return r.blockId===q(e)&&r.offset===0&&i.blockId===q(o)&&i.offset===W(n,o)}const kp=w("range-in-block");function yp(n,t){const e=t.getEditor(),o=e.getBlockById(t.start.blockId),r=e.getBlockById(t.end.blockId),i=o===n||It(n,o),s=r===n||It(n,r);return!!(i||s)}function wp(n,t){const e=n.doc.toJSON(),o=new Set(Object.values(e.blocks).map(s=>s.map(l=>l.id)).flat());let r,i=gt(t);if(i){for(;i&&!o.has(q(i));)i=gt(i);d(kp,i,"no prev block while deleting a block"),r=At(n,i,W(n,i))}else{const s=dt(t);d(kp,s,"no prev and next block while deleting a block"),r=At(n,s,0)}return r}const Cv=w("block-to-html");function eu(n,t,e,o){const r=Er(n,t.type);if(r.convertTo)return r.convertTo(n,t,e,"html",o);if(r.blockKind!=="text")return`[${t.type}]`;d(Cv,t.text,"no text");const i=vt(t.text);return`<div>${sm(i)}</div>`}const Bp=w("block-to-text");function bv(n,t,e){let o="";return t.forEach(r=>{if(d(Bp,typeof r.insert=="string","invalid op"),r.attributes&&r.attributes.box===!0){const i=r.attributes,s=n.editorBoxes.getBoxClass(i.type);if(s!=null&&s.convertTo){o+=s.convertTo(n,i,e,"text");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${i.type}]`}o+=r.insert}),o}function ql(n,t,e,o){const r=Er(n,t.type);return r.convertTo?r.convertTo(n,t,e,"text",o):r.blockKind!=="text"?`[${t.type}]`:(d(Bp,t.text,"no text"),bv(n,t.text,e))}function nu(n,t,e,o){const r=Er(n,t.type);return r.convertTo?r.convertTo(n,t,e,"markdown",o):ql(n,t,e,o)}function Vi(n,t){return t.blocks.root.map((r,i)=>eu(n,r,t,[{containerId:"root",blockIndex:i}])).join(`
25
25
  `)}function Ep(n,t){return`<!doctype html><html><head><meta charset="utf8" /></head><body>${Vi(n,t)}</body></html>`}function Wl(n,t){return t.blocks.root.map((r,i)=>ql(n,r,t,[{containerId:"root",blockIndex:i}])).join(`
26
26
  `)}function qi(n,t){return t.blocks.root.map((r,i)=>nu(n,r,t,[{containerId:"root",blockIndex:i}])).join(`
27
- `)}const vv=w("get-text-position");function Lr(n,t){const e=t!=null?t:n.selection.range.start;e instanceof qt||d(vv,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=J(r),s=H(r),l=U(s),{offset:c}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:c}}const Wi=w("insert-text");function Ip(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(d(Wi,r,"no block data"),d(Wi,r.text,"no block text"),de(r.text)===0)return d(Wi,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=Gt(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function kv(n,t,e){const o=H(t),r=U(o),i=J(t);return Ip(n,r,i,e)}function xp(n,t,e,o,r){const i=H(t),s=U(i),l=J(t),c=kv(n,t,e),a=Al(e,o,c!=null?c:null);return n.doc.localUpdateBlockText(s,l,a,r),ue(n,t)}function Tp(n,t,e,o){const r=H(t),i=U(r),s=J(t),l=Al(e," ",o);return n.doc.localUpdateBlockText(i,s,l),ue(n,t)}function ou(n,t,e,o,r){const i=n.doc.getBlockData(e,o);d(Wi,i,"no block data"),d(Wi,i.text,"no block text");const s=Ip(n,e,o,r),l=Al(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),ue(n,n.getBlockById(i.id))}function ru(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=Lr(n);ou(n,t,e,o,r)}const Gl=w("update-composition-text");function Sp(n){const t=n.selection.range.start;t instanceof qt||d(Gl,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);d(Gl,j(n,o),"not a text kind block");const r=H(o),i=U(r),s=J(o),l=n.doc.getBlockData(i,s);d(Gl,l,"no block data in doc"),d(Gl,l.text,"no text data in text block");const c=it(o);Dl(n,jo(o),e,c,l.text)}function Dp(n){eb(n)}function Mr(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const Zl=w("delete-block-text");function iu(n,t,e,o,r){d(Zl,j(n,t),"block is not a text kind block");const i=H(t),s=U(i),l=J(t),c=n.doc.getBlockData(s,l);d(Zl,c,"no block data in doc"),d(Zl,c.text,"no text data in text block");let a=e;re(t,e)||(a=lo(t,a));let u=e+o;d(Zl,u<=W(n,t),`invalid offset and count: ${e}, ${o}`),re(t,u)||(u=Vo(t,u));const f=u-a,m=Fg(a,f);return n.doc.localUpdateBlockText(s,l,m,r),f}const su=w("break-text-block");function Lp(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Rr(n,t,e,o){d(su,j(n,t),`block is not a text kind block: ${rt(t)}`),d(su,e>=0&&e<=W(n,t),`invalid offset: ${e}`);const r=H(t),i=U(r),s=J(t),l=o!=null&&o.copyBlockAttributes?Lp(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===W(n,t))){const C=e===0?s:s+1,v={...zn(""),...l,...o==null?void 0:o.newBlockData},B=At(n,t.id,0),y=Mr(n,i,C,v,B);return{block:t,newBlock:y}}d(su,re(t,e),"not a valid offset");const c=ue(n,t),{right:a}=be(c,e),u=de(a);u>0&&iu(n,t,e,u);const f={...zn(a),...l,...o==null?void 0:o.newBlockData},m=Mr(n,i,s+1,f,At(n,f.id,0));return{block:t,newBlock:m}}const yv=w("prepare-insert-new-block");function wv(n,t,e){if(t&&e!==void 0&&e!==null){const a=n.getContainerById(t),u=Mt(a);return d(yv,e>=0&&e<=u.length,`invalid blockIndex: ${e}`),{containerId:t,blockIndex:e}}const o=n.selection.range.start;if(!o.isSimple())return null;const r=n.getBlockById(o.blockId);if(t=U(H(r)),e=J(r),!j(n,r))return{containerId:t,blockIndex:e+1};const s=o.offset;if(s===0||s===W(n,r))return{containerId:t,blockIndex:s===0?e:e+1};const c=Rr(n,r,s).newBlock;return{containerId:t,blockIndex:J(c)}}const Bv=w("auto-insert-block");function Mp(n,t,e,o,r,i){const s=wv(n,e,o);d(Bv,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},c={anchor:l,focus:l};return Mr(n,s.containerId,s.blockIndex,t,r!=null?r:c,i)}const Ev=w("delete-block");function Yl(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{Yl(n,i,e)})}))}function lu(n,t,e){const o=H(t),r=U(o),i=J(t),s=n.doc.getBlockData(r,i);return d(Ev,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Wt(n,{anchor:e.start,focus:e.end})),s}function cu(n,t,e){return n.undoManager.runInGroup(()=>{const o=H(t);Ge(o)===1&&n.insertTextBlock("",U(o),0);let r=e?io(n,e):null;if(!r){const l=n.selection.range;yp(t,l)?r=wp(n,t):r=l}const i=lu(n,t,r),s=[];return Yl(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function Iv(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{Yl(n,r,e)}),n.doc.localDeleteChildContainers(e)}function Rp(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{Yl(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const au=w("merge-text-block");function Ap(n,t,e){d(au,j(n,t),"only text block can be merged"),d(au,j(n,e),"only text block can be merged");const o=co(n,t),r=co(n,e),i=o.text,s=r.text;d(au,i&&s,"block data has no text");const l=H(t),c=U(l),a=J(t),u=W(n,t),f=ou(n,s,c,a,u),m=At(n,t,de(i));return cu(n,e,m),f}const wn=w("clear-selected-contents");function Ql(n,t){d(wn,j(n,t.block),"not a text kind block");const{start:e,end:o}=t;d(wn,e.isSimple(),"not a simple block position"),d(wn,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;d(wn,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function Op(n,t,e){const o=U(t),r=Mt(t),i=e.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",o,0,{newRange:i});e.focus&&n.selection.selectBlock(s,0),r.reverse().forEach(l=>{n.deleteBlock(l)})}function xv(n,t){const{block:e,start:o,end:r}=t;if(j(n,e)){Ql(n,t);return}if(Te(e)||o.isSimple()){d(wn,r.isSimple(),"invalid range");const s=H(e),l=J(e),c=n.insertTextBlock("",U(s),l);n.selection.selectBlock(c,0),n.deleteBlock(e);return}d(wn,at(n,e),"invalid block kind"),d(wn,!o.isSimple()&&!r.isSimple(),"invalid range"),xr(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{Op(n,s,{focus:l===0})})}function Tv(n){const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(d(wn,e.length>0,"no selected block"),e.length===1){xv(n,e[0]);return}const o=e[0],r=o.block,i=H(r);d(wn,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(j(n,r)){Ql(n,o);const u=At(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(m=>n.deleteBlock(m.block)),j(n,l)){Ql(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(u);return}n.deleteBlock(l),n.selection.setRange(u);return}if(j(n,l)){Ql(n,s),e.slice(0,e.length-1).reverse().forEach(u=>n.deleteBlock(u.block)),n.selection.selectBlock(s.block,0);return}if(e.length===Ge(i)){Op(n,i,{focus:!0});return}const c=gt(r),a=dt(l);d(wn,c||a,"no prev or next block"),e.forEach(u=>n.deleteBlock(u.block))}function du(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),Tv(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}function _p(n,t,e){const o=H(t),r=U(o),i=J(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),ue(n,t)}function Np(n,t,e){const o=n.getBlockText(t),r=ie.diff(o,e);_p(n,t,r)}function Kl(n,t,e){const o=ue(n,t),r=typeof e=="string"?Go(e):e,i=ie.diff(o,r);return _p(n,t,i)}const Gi=w("update-block-data");function Jl(n,t,e,o){const r=H(t),i=U(r),s=J(t),l=n.doc.getBlockData(i,s),c={insert:{},delete:[]},a=new Set(Object.keys(l)),u=new Set(Object.keys(e));return a.forEach(m=>{if(!u.has(m)){if(m==="id"||m==="type"||m==="text")return;Gi.debug(`delete key: ${m}`),c.delete.push(m)}}),Object.entries(e).forEach(([m,C])=>{d(Gi,m!=="id"&&m!=="type",`invalid block data delta, ${m}`);const v=l[m];if(C==null){v!=null&&(Gi.debug(`delete key: ${m}`),c.delete.push(m));return}v!==C&&(cl.default(v,C)||m==="text"&&ie.diff(v,C).length===0||(a.has(m)?(Gi.debug(`replace key: ${m}`),c.delete.push(m)):Gi.debug(`insert key: ${m}`),c.insert[m]=C))}),n.doc.localUpdateBlockData(i,s,c,o),co(n,t)}function $p(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function uu(n,t,e){if(!at(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=xe(n,t).getChildContainers(n,t)[0],i=Vt(r);uu(n,i,e)}function Yo(n){const t=[];let e={};return n.forEach(o=>{t.push(...o.blocks.root);const{root:r,...i}=o.blocks;e={...e,...i}}),{blocks:{...e,root:t},meta:{},comments:{}}}const Zi=w("clone-block");function ao(n,t,e,o){const r=n.getBlockClass(e.type);if(r.blockToDoc)return r.blockToDoc(t,e,(u,f)=>(d(Zi,e!==f,"invalid child block"),ao(n,u,e,o)));let i={};const s=new Map,l=Y.default(e);l.children&&(l.children=l.children.map(u=>{const f=N(),m=t.blocks[u];d(Zi,Array.isArray(m),"invalid child blocks");const C=m.map(S=>ao(n,t,S,o)),v=Yo(C),{root:B,...y}=v.blocks;return i={...i,...y},i[f]=v.blocks.root,s.set(u,f),f}));const c=Array.from(s.entries()),a=u=>{for(const f of c){const[m,C]=f;{const v=`${m}/`;if(u.startsWith(v)){const B=u.substring(v.length),y=`${C}/${B}`;return Zi.debug(`replace key: ${u} -> ${y}`),y}}{const v=`${m}_`;if(u.startsWith(v)){const B=u.substring(v.length),y=`${C}_${B}`;return Zi.debug(`replace key: ${u} -> ${y}`),y}}}return u};return Array.from(Object.entries(l)).forEach(([u,f])=>{const m=a(u);m!==u&&delete l.key,l[m]=f}),l.id=N(),o&&(o.blockIdMap.set(e.id,l.id),s.forEach((u,f)=>o.containerIdMap.set(f,u))),{blocks:{root:[l],...i},meta:{},comments:{}}}function hu(n,t,e,o){const r=t.blocks[e];d(Zi,Array.isArray(r),"invalid child blocks");const i=r.map(l=>ao(n,t,l,o));return Yo(i)}function fu(n,t,e){const o=t.blocks.root.map(r=>ao(n.editorBlocks,t,r,e));return Y.default(Yo(o))}const Pp=w("insert-doc");function jp(n,t,e,o,r){if(at(n,t)){Pp.warn("failed to insert doc into a complex block");return}const i=fu(n,o,r),s=H(t),l=J(t),c=U(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var I,M,R;Object.entries(i.blocks).forEach(([$,Z])=>{$!=="root"&&n.doc.localInsertChildContainer($,Z)});const a=i.blocks.root;if(Te(t)){n.deleteBlock(t);let $;a.reverse().forEach(Z=>{const ot=n.insertBlock(c,l,Z);$||($=ot)}),$&&n.selection.selectBlock($,W(n,$));return}if(d(Pp,j(n,t),"not a text block"),Tt(n,t)){const $=J(t);let Z;a.forEach((ot,st)=>{const mt=n.insertBlock(c,$+st,ot);st===a.length-1&&(Z=mt)}),Z&&n.selection.selectBlock(Z,W(n,Z));return}if(a.length===1){const $=a[0];if(_i(n,$.type)){n.insertTextToBlock(t,e,(I=$.text)!=null?I:[]);return}n.breakTextBlock(t,e),n.insertBlock(c,l+1,$);return}const u=e===W(n,t),f=e===0,m=a[0],C=a[a.length-1];let v;!u&&!f?v=n.breakTextBlock(t,e,{forceInsertAfter:!0}):v=t;const B=f?l:l+1;u?(v=n.insertBlock(c,l+1,C),n.selection.selectBlock(v,W(n,v))):(n.selection.selectBlock(v,0),_i(n,C.type)?n.insertTextToBlock(v,0,(M=C.text)!=null?M:[]):n.insertBlock(c,B,C));const y=n.selection.range;let S=B;_i(n,m.type)?f?(n.insertBlock(c,B,m),S+=1):n.insertTextToBlock(t,e,(R=m.text)!=null?R:[]):(n.insertBlock(c,B,m),S+=1),a.slice(1,a.length-1).reverse().forEach($=>{n.insertBlock(c,S,$)}),n.selection.setRange(y)}),n.doc.endBatchUpdate()}function mu(n,t,e,o,r){const i=fu(n,o,r),s=U(t),l=[];return n.undoManager.runInGroup(()=>{Object.entries(i.blocks).forEach(([a,u])=>{a!=="root"&&n.doc.localInsertChildContainer(a,u)}),i.blocks.root.reverse().forEach(a=>{const u=n.insertBlock(s,e,a);l.push(u)})}),l}function Hp(n,t,e){const o=Ge(t);mu(n,t,o,e);for(let r=0;r<o;r++){const i=Vt(t);n.deleteBlock(i)}}const Yi=w("add-text-attribute");function Sv(n,t,e,o){const{start:r,end:i}=e;d(Yi,r.blockId===i.blockId&&r.blockId===q(t),"invalid range"),d(Yi,o,"invalid attribute name");const s=n.getBlockText(t),l=Dr(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function Fp(n,t,e,o,r){const{start:i,end:s}=e;d(Yi,i.blockId===s.blockId&&i.blockId===q(t),"invalid range"),d(Yi,o,"invalid attribute name");const l=n.getBlockText(t),c=_l(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,c),c}function Ar(n,t,e,o,r){const{start:i,end:s}=e;d(Yi,i.blockId===s.blockId&&i.blockId===q(t),"invalid range");const l=n.getBlockText(t),c=Qg(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,c),c}function zp(n,t,e,o){const r=tn(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:c}=i;if(!j(n,s))return;if(Tt(n,s)){o(n,q(s),t,e);return}const a=Wt(n,{anchor:l,focus:c});t==="color"||t==="backgroundColor"?Ar(n,s,a,t,e):(Ar(n,s,a,"color",null),Ar(n,s,a,"backgroundColor",null))})})}function Up(n,t,e){const o=tn(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!j(n,i))return;if(Tt(n,i)){(t==="clearColor"||t==="clearAll")&&e(n,q(i),"color",null),(t==="clearBackground"||t==="clearAll")&&e(n,q(i),"backgroundColor",null);return}const c=Wt(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&Ar(n,i,c,"color",null),(t==="clearBackground"||t==="clearAll")&&Ar(n,i,c,"backgroundColor",null)})})}function gu(n,t){const e=tn(n,{simpleBlockOnly:!0}).filter(s=>j(n,s.block));if(e.length===0)return[null,null];const o=s=>{if(W(n,s.block)===0)return t(n,q(s.block));const l=s.start,c=s.end,a=n.getBlockText(s.block);return Xg(l.offset,c.offset-l.offset,a)};let[r,i]=o(e[0]);return r===null&&i===null?[r,i]:(e.forEach(s=>{const[l,c]=o(s);l===null||r===null?r=null:r=l===r?r:null,c===null||i===null?i=null:i=c===i?i:null}),[r,i])}const ke=w("adjust-selection-pos");function Vp(n){const t=[];for(;n;){const e=H(n);if(t.unshift(e),pt(e))return t;const o=F(e);d(ke,o,"child container has not parent container"),n=o}d(ke,!1,"should not come here: getParentContainers")}function qp(n,t){for(;t;){const e=H(t);if(e===n)return t;const o=F(e);d(ke,o,"could not find parent block for a child container"),t=o}d(ke,!1,"no parent block in specified container")}function Dv(n,t){const e=Vp(n),o=Vp(t);d(ke,e.length>0&&o.length>0,"block has not parent container"),d(ke,e[0]===o[0],"root container does not equal");let r=e[0];for(let l=1;l<e.length||o.length;l++)if(e[l]!==o[l]){r=e[l-1];break}const i=qp(r,n),s=qp(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function Wp(n,t){let e=F(t);for(d(ke,e,"element is not in a block");e;){const o=H(e);d(ke,Ye(o),"not a child container");const r=F(o);if(d(ke,r,"child container has not parent block"),r===n)return o;e=r}d(ke,!1,"failed to find parent container in complex block")}function Xl(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof qt&&e instanceof qt?{anchor:t,focus:e}:(d(ke,t instanceof Je&&e instanceof Je,"both start and end are not simple or complex"),xl(n,o,t,e));const i=H(o),s=H(r);if(i===s)return t instanceof Je&&(t=P(o,0,"home")),e instanceof Je&&(e=P(r,W(n,r),"end")),d(ke,t instanceof qt,"not valid position type"),d(ke,e instanceof qt,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof qt&&e instanceof Je){const v=n.getContainerById(e.childContainerId);if(v===i)return{anchor:e,focus:e};const B=F(i);if(B&&B===F(v)){const y=wt(B,U(i)),S=wt(B,U(v));return xl(n,B,y,S)}}return null}const l=fl(o,r)>0,{newBlock1:c,newBlock2:a}=Dv(o,r);if(c===a){const v=c,B=Wp(v,o),y=Wp(v,r);return t=wt(c,U(B)),e=wt(c,U(y)),ke.debug(`select in complex block: ${B.id}, ${y.id}`),xl(n,v,t,e)}let u=l?W(n,c):0;c===o&&t instanceof qt&&(u=t.offset);let m=l?0:W(n,a);return a===r&&e instanceof qt&&(m=e.offset),t=P(c,u,l?"end":"home"),e=P(a,m,l?"home":"end"),{anchor:t,focus:e}}const Lv=w("move-complex-block-position");function Mv(n,t,e){const o=n.getBlockById(t.blockId);d(Lv,at(n,o),"is not a complex block");const r=xe(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?wt(o,U(s)):null}const Qi=w("move-simple-block-position");function Gp(n,t){const e=Se(n,t);d(Qi,e.length>0,"complex block has not any child container");const o=e[0];return Vt(o)}function Zp(n,t){const e=Se(n,t);d(Qi,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Qt(o)}function Yp(n,t,e){const o=e?Gp(n,t):Zp(n,t);return at(n,o)?Yp(n,o,e):o}function Rv(n,t){const e=n.getBlockById(t.blockId);return at(n,e)&&t.offset===0?Gp(n,e):wr(e)}function Av(n,t){const e=n.getBlockById(t.blockId);return at(n,e)&&t.offset===1?Zp(n,e):yr(e)}function pu(n){return n==="ArrowLeft"||n==="ArrowUp"}function Cu(n,t,e){const o=H(t);if(pt(o))return null;const r=F(o);d(Qi,r,"child container has not parent block"),d(Qi,at(n,r),"is not a complex block");const i=xe(n,r).getNextContainer(n,r,o,e);return i?pu(e)?Qt(i):Vt(i):Cu(n,r,e)}function Ov(n,t,e){const o=H(t);if(pt(o))return null;const r=F(o);if(d(Qi,r,"child container has not parent block"),pu(e)){const l=gt(r);if(l)return l}else{const l=dt(r);if(l)return l}const i=Cu(n,r,e);if(i)return i;let s=r;for(;!pt(H(s));)s=F(H(s));return pu(e)?gt(s):dt(s)}function _v(n,t,e){return!at(n,t)||xe(n,t).enableKeyboardSelect?t:Yp(n,t,e==="ArrowDown"||e==="ArrowRight")}function Nv(n,t,e){const o=n.getBlockById(t.blockId),i=bt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?Rv(n,t):Av(n,t);if(s||(s=Cu(n,o,e),s||(s=Ov(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!pt(H(o)))return null;const l=n.insertTextBlock("",U(n.rootContainer),Ge(n.rootContainer));return P(l,0,"home")}return null}if(s=_v(n,s,e),j(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return fb(n,s,o,t,l);if(e==="ArrowUp")return hb(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?P(s,W(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?P(s,0,"home"):null}function $v(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(j(n,r))return o;const i=dt(r);if(i)return P(i,0,"home");if(!pt(H(r))||n.readonly)return o;const s=n.insertTextBlock("",U(n.rootContainer),Ge(n.rootContainer));return P(s,0,"home")}function Pv(n,t,e){const o=n.selection.range;let r;if(o instanceof ce)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=$v(n,t,o):r=Nv(n,o.getFocusedPos(),t);else if(r=Mv(n,o.focus,t),e==="move"){const i=r!=null?r:o.focus,s=n.getContainerById(i.childContainerId);if(t==="ArrowLeft"||t==="ArrowUp"){const l=Qt(s);r=P(l,0,"home")}else{const l=Vt(s);r=P(l,W(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:Xl(n,o.anchor,r):null}function uo(n,t,e){const o=Pv(n,t,e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),(t==="ArrowLeft"||t==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function Qp(n){return uo(n,"ArrowLeft","move"),!0}function Kp(n){return uo(n,"ArrowRight","move"),!0}function Jp(n){return uo(n,"ArrowUp","move"),!0}function Xp(n){if(uo(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=H(t);if(pt(e)||Qt(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",U(o),Ge(o)),!0}function t0(n){return uo(n,"ArrowDown","select"),!0}function e0(n){return uo(n,"ArrowLeft","select"),!0}function n0(n){return uo(n,"ArrowRight","select"),!0}function o0(n){return uo(n,"ArrowUp","select"),!0}const r0=w("word-offset");function bu(n,t){const e=n.selection.range.focus;d(r0,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(Tt(n,o))return P(o,0,"home");if(e.offset===0||!j(n,o)){const s=gt(o);if(!s)return null;const l=P(s,W(n,s),"end");if(t==="select"&&j(n,s)){const c=Yd(n,s,l.offset);return P(s,c,"normal")}return l}const r=Yd(n,o,e.offset);return P(o,r,"normal")}function vu(n,t){const e=n.selection.range.focus;d(r0,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(Tt(n,o))return P(o,0,"end");if(e.offset===W(n,o)||!j(n,o)){const s=dt(o);if(!s)return null;const l=P(s,0,"home");if(t==="select"&&j(n,s)){const c=Qd(n,s,l.offset);return P(s,c,"end")}return l}const r=Qd(n,o,e.offset);return P(o,r,"normal")}function i0(n){if(!n.selection.range.focus.isSimple())return!1;const e=bu(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function s0(n){if(!n.selection.range.focus.isSimple())return!1;const e=vu(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function l0(n){if(!n.selection.range.focus.isSimple())return!1;const e=bu(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function c0(n){if(!n.selection.range.focus.isSimple())return!1;const e=vu(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}w("find-block");function ku(n,t){if(!at(n,t))return t;const o=xe(n,t).getChildContainers(n,t)[0],i=Mt(o)[0];return ku(n,i)}function yu(n,t){if(!at(n,t))return t;const e=xe(n,t).getChildContainers(n,t),o=e[e.length-1],r=Mt(o),i=r[r.length-1];return yu(n,i)}function a0(n){const t=yu(n,Qt(n.rootContainer)),e=P(t,W(n,t),"end");return n.selection.setSelection(e),!0}function d0(n){const t=ku(n,n.getFirstBlock()),e=P(t,0,"home");return n.selection.setSelection(e),!0}function u0(n){const t=ku(n,n.getFirstBlock()),e=P(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function wu(n){const t=yu(n,Qt(n.rootContainer)),e=P(t,W(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}const h0=w("line-offset");function f0(n){const t=n.selection.range.focus;d(h0,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!j(n,e))return P(e,0,"home");let r=Ng(e,t).start;const{next:i}=Sl(e,r);return i&&_e(i)&&Ri(i)==="br"&&(r+=1),P(e,r,"home")}function m0(n){const t=n.selection.range.focus;d(h0,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===W(n,e)||!j(n,e))return P(e,W(n,e),"end");const o=Ng(e,t);return P(e,o.end,"end")}function g0(n){if(!n.selection.range.focus.isSimple())return!1;const e=f0(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function p0(n){if(!n.selection.range.focus.isSimple())return!1;const e=m0(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function C0(n){if(!n.selection.range.focus.isSimple())return!1;const e=f0(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function b0(n){if(!n.selection.range.focus.isSimple())return!1;const e=m0(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const v0=w("find-block-position");function jv(n,t,e,o){d(v0,at(n,t),"is not a complex block");const r=xe(n,t).getChildContainers(n,t);d(v0,r.length>0,"complex block has not any child container");const i=Ke(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,c=Ig(n,t,s,l);return Bu(n,c,e,o)}function Bu(n,t,e,o){if(at(n,t))return jv(n,t,e,o);const r=q(t);let i=Number.MAX_SAFE_INTEGER;const s=Ke(n,e,o),l=s.left+s.width/2,c=s.top+s.height/2;let a=P(r,0,"home");const u=W(n,t);for(let f=0;f<=u;f++){const m=P(r,f,"normal"),C=Ke(n,t,m),v=Cn(C,l,c);v<i&&(i=v,a=m)}return a}const k0=w("page-offset");function Hv(n,t){const e=vp(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<dv(n))return n.getFirstBlock();const i=gt(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=gt(s)}return n.getFirstBlock()}function Fv(n,t){const e=vp(n)*.9,o=t.getBoundingClientRect(),r=uv(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=dt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=dt(l)}return n.getLastBlock()}function y0(n){const t=n.selection.range.focus;d(k0,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=Hv(n,e);let r;return o===n.getFirstBlock()?r=P(o,0,"home"):r=Bu(n,o,e,t),r}function w0(n){const t=n.selection.range.focus;d(k0,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=Fv(n,e);let r;return o===n.getLastBlock()?r=P(o,W(n,o),"end"):r=Bu(n,o,e,t),r}function B0(n){if(!n.selection.range.focus.isSimple())return!1;const e=y0(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function E0(n){if(!n.selection.range.focus.isSimple())return!1;const e=w0(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function I0(n){if(!n.selection.range.focus.isSimple())return!1;const e=y0(n);if(!e)return!1;const o=Xl(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}function x0(n){if(!n.selection.range.focus.isSimple())return!1;const e=w0(n);if(!e)return!1;const o=Xl(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}const Ki=w("select-all");function T0(n,t){const e=Vt(n),o=Qt(n);return t.start.offset===0&&t.start.blockId===q(e)&&t.end.offset===W(t.getEditor(),o)&&t.end.blockId===q(o)}function zv(n,t){const e=t.getEditor(),o=xe(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=q(n);return t.start.blockId===s&&t.start.childContainerId===U(r)&&t.end.blockId===s&&t.end.childContainerId===U(i)}function Uv(n,t){d(Ki,t,"no parent block"),d(Ki,at(n,t),"not a complex block");const e=xe(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(Wt(n,{anchor:wt(t,U(o)),focus:wt(t,U(r))}))}function S0(n,t){const e=H(t);Eu(n,e)}function D0(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&j(n,t)){const r=e.start,i=e.end,s=W(n,t);if(r.offset>0||i.offset<s)return n.selection.selectBlock(t,0,s),!1}return A(n.rootContainer,"select-all"),S0(n,Vt(n.rootContainer)),!1}return d(Ki,!e.isSimple(),"invalid range type"),zv(t,e)?(S0(n,t),!1):(d(Ki,t,"no parent block"),d(Ki,at(n,t),"not a complex block"),Uv(n,t),!0)}function Eu(n,t){const e=Mt(t),o=e[0],r=e[e.length-1],i=P(o,0,"home"),s=P(r,W(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function L0(n){wu(n),n.focus()}const Iu=w("selected-block-to-doc");function M0(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{M0(n,i,e)}),e.blocks[o]=Y.default(r)})}function tc(n,t,e={ignoreLockInfo:!0}){const o=bt(n,t.block);if(o.selectionToDoc)return o.selectionToDoc(n,t);const r=Y.default(co(n,t.block));if(!e.ignoreLockInfo&&r.lock&&delete r.lock,j(n,t.block)){const s=t.start,l=t.end;if(d(Iu,r.text,"no block text"),s.offset===l.offset)return{blocks:{root:[{...r,text:[]}]},meta:{},comments:{}};const{middle:c}=Gt(r.text,s.offset,l.offset-s.offset);return{blocks:{root:[{...r,text:c}]},meta:{},comments:{}}}if(Te(t.block))return{blocks:{root:[r]},meta:{},comments:{}};d(Iu,at(n,t.block),"not complex block"),d(Iu,r.children,"no children");const i={blocks:{root:[r]},meta:{},comments:{}};return M0(n,r,i),i}function xu(n,t,e=!0){const o=P(t,0,"normal"),r=P(t,W(n,t),"end");return tc(n,{block:t,start:o,end:r},{ignoreLockInfo:e})}const Vv=w("block-to-doc");function qv(n,t){d(Vv,t.length>0,"invalid params, no blocks");const e=t.map(o=>xu(n,o));return Yo(e)}function Ji(n){const e=n.selection.range.getSelectedBlocks().map(o=>tc(n,o));return Yo(e)}function R0(n,t){const e=n.getContainerById(t),i=Mt(e).map(s=>({start:P(s,0,"home"),end:P(s,W(n,s),"end"),block:s})).map(s=>tc(n,s));return Yo(i)}const ec=w("editor-selection");class Wv{constructor(t){h(this,"editor");h(this,"caret");h(this,"_range");h(this,"lastCaretRect");h(this,"handleBlockDelete",(t,e,o,r)=>{if(o||r.child)return;const i=this.range;if(yp(e,i)){ec.debug("adjust selection because remote deleted current block");const s=wp(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=q(e);this.caret=new cv(t);const r=P(o,0,"normal");this._range=Wt(t,{anchor:r,focus:r}),this.lastCaretRect=null,this.editor.addListener("blockDeleted",this.handleBlockDelete),setTimeout(()=>{this.updateFocusedBlock(null)})}destroy(){this.caret.destroy()}get range(){return this._range}get focusedBlock(){return this.getFocusedBlock()}get startBlock(){return this.getStartBlock()}get endBlock(){return this.getEndBlock()}getFocusedBlock(){const t=this.range.focus;return this.editor.getBlockById(t.blockId)}getStartBlock(){const t=this.range.start;return this.editor.getBlockById(t.blockId)}getEndBlock(){const t=this.range.end;return this.editor.getBlockById(t.blockId)}selectBlock(t,e,o){const r=P(t,e,"normal");let i;o&&(i=P(t,o,"normal")),this.setSelection(r,i)}setSelection(t,e,o){if(e||(e=t),this.verifyPos(t),this.verifyPos(e),!this.selectionChanging(t,e))return this.range;const r=Wt(this.editor,{anchor:t,focus:e});if(this.range.isEqual(r))return this.range;const i=this._range;return this._range=r,this.selectionChanged(),this.updateFocusedBlock(i),nt(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!pv(this.editor,r))&&z(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(t,e){return this.setSelection(t.anchor,t.focus,e)}updateSelection(){this.caret.update(),av(this.editor)}getFocusedPos(){return this.range.focus}getAnchorPos(){return this.range.anchor}selectionChanging(t,e){return!0}selectionChanged(){this.updateSelection(),this.editor.emit("selectionChanged",this.editor)}updateLastCaretRect(){const t=this.range.focus;if(!Ir(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Ke(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){gv(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=W(this.editor,e)||d(ec,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||d(ec,!1,"invalid complex block position, no container found")}}updateFocusedBlock(t){if(t&&this.range.start.blockId===t.start.blockId)return;let e;t&&t.start.blockId===t.end.blockId&&(e=this.editor.findBlockById(t.start.blockId));let o;(this.range.isCollapsed()||!this.range.isSimple()||this.range.start.blockId===this.range.end.blockId)&&(o=this.editor.getBlockById(this.range.start.blockId));let r=!1;e&&nt(e,"focused")&&(z(e,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,e!=null?e:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(t){const e=Ji(this.editor);return t==="text"?Wl(this.editor,e):t==="markdown"?qi(this.editor,e):Ep(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{z(t,"focused"),z(t,"child-focused")})}setBlockFocused(t){if(nt(t,"focused"))return!1;A(t,"focused");let e=H(t);for(;Ye(e);){const o=F(e);d(ec,o,"parent block not found"),A(o,"child-focused"),e=H(o)}return!0}}function Gv(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);!e||n.selection.selectBlock(e,0,W(n,e))}function Zv(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!j(n,e))return;let o=bu(n,"select"),r=vu(n,"select");if(!o||!r)return;const i=t.blockId;o.blockId!==i&&(o=P(e,0,"home")),r.blockId!==i&&(r=P(e,W(n,e),"end")),n.selection.setSelection(o,r)}class Yv{constructor(t){h(this,"editor");h(this,"startPos",null);h(this,"lastCaretRect");h(this,"mouseDownEvent",null);h(this,"handleMouseDown",t=>{this.mouseDownEvent=t;const e=Tg(this.editor,t.x,t.y);if(e){if(e instanceof Xe)return;const o=this.editor.selection.range;if(t.shiftKey&&o.isSimple()){const r=o.anchor;this.editor.selection.setSelection(r,e.focus),this.startPos=e.start}else this.editor.selection.setSelection(e.anchor,e.focus),this.startPos=e.start;this.editor.selection.updateLastCaretRect()}});h(this,"handleMouseMove",t=>{if(!this.startPos||!this.mouseDownEvent||Math.abs(this.mouseDownEvent.x-t.x)<3&&Math.abs(this.mouseDownEvent.y-t.y)<3)return;const e=Tl(this.editor,t.x,t.y);if(!e)return;const o=Xl(this.editor,this.startPos,e.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});h(this,"handleMouseUp",t=>{this.startPos=null});this.editor=t,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(t){Zv(this.editor)}handleTripleClick(t){Gv(this.editor)}}function Qv(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function Kv(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const A0=w("delete-text");function O0(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof qt||d(A0,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);d(A0,j(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!re(s,l-e)){const c=lo(s,l);e=l-c}}else if(t==="forward"&&l+e>W(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function _0(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const Jv=w("handle-backspace");function Tu(n,t){if(!Tt(n,t))return;const e=H(t);Ge(e)!==1&&n.deleteBlock(t)}function Xv(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(j(n,o))if(e.offset===0){if(_0(n,o))return;const r=gt(o);if(r)if(j(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(at(n,r)){Tu(n,o);const i=Ni(n,r);i?n.selection.selectBlock(i,W(n,i)):n.selection.selectBlock(r,0,W(n,r))}else Tu(n,o),d(Jv,Te(r),"prev block is not embed block"),n.selection.selectBlock(r,1);else{const i=H(o);if(Ye(i)){const s=wg(n,i);s&&(Tu(n,o),n.selection.selectBlock(s,W(n,s)))}}}else O0(n,"backward",1,null);else{const r=J(o),i=H(o);n.insertTextBlock("",U(i),r),n.deleteBlock(o)}}function tk(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(j(n,o))if(e.offset===W(n,o)){const r=dt(o);r&&(j(n,r)?n.mergeTextBlock(o,r,{focus:!0}):Tt(n,o)?n.deleteBlock(o,At(n,r,0)):n.deleteBlock(r))}else O0(n,"forward",1,null);else{const r=J(o),i=H(o);n.insertTextBlock("",U(i),r),n.deleteBlock(o)}}function ek(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const e=n.getFocusedBlock();if(j(n,e)){if(Tt(n,e)&&_0(n,e))return;const o=n.selection.range.start,r=n.breakTextBlock(e,o.offset,{copyBlockAttributes:!0});o.offset!==0?n.selection.selectBlock(r,0):n.selection.scrollIntoView()}else{const o=n.insertTextBlock();n.selection.selectBlock(o,0)}}function nk(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!j(n,o))return!1;const r=e.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:N(),box:!0,created:Date.now()}),!0}const ok=w("input-handler-actions");function rk(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(ek(n),!0))}function ik(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(tk(n),!0))}function sk(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Xv(n),!0))}function lk(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(nk(n),!0))}function ck(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t)}).catch(t=>{ok.error(t)}),!0)}function N0(n,t,e){if(t.type==="embed"){const s=t.embedData.src;s&&typeof s=="string"&&e.add(s);return}const o=t.text;o&&o.forEach(i=>{i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"&&e.add(i.attributes.src)});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{N0(n,l,e)})})}function ak(n,t){const e=new Set;return t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.getResources?i.getResources(r).forEach(s=>{e.add(s)}):N0(t,r,e)}),Array.from(e)}function Su(n,t){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${_o(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Du(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=ak(n,t),r={};o.forEach(c=>{const a=n.doc.buildResourceUrl(c,{withToken:!0});r[c]=a}),t.meta={...e,resources:r}}function dk(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let o=Ji(n);const r=e==null?void 0:e(n,t,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Du(n,o);const i=Vi(n,o),s=qi(n,o),l=Su(i,o);t.clipboardData.setData("text/html",l),t.clipboardData.setData("text/plain",s),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(o))}function uk(n){if(n.selection.range.isCollapsed())return;const t=Ji(n);Du(n,t);const e=Vi(n,t),o=Su(e,t),r=qi(n,t),i=new Blob([o],{type:"text/html"});vl([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:i}])}async function nc(n,t){const e=xu(n,t,!1);Du(n,e);const o=Vi(n,e),r=qi(n,e),i=Su(o,e);return vl([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}function hk(n){return uk(n),du(n),!0}const oc={ArrowDown:Xp,ArrowUp:Jp,ArrowLeft:Qp,ArrowRight:Kp,"Shift+ArrowDown":t0,"Shift+ArrowUp":o0,"Shift+ArrowLeft":e0,"Shift+ArrowRight":n0,"CtrlOrCmd+ArrowLeft":i0,"CtrlOrCmd+ArrowRight":s0,"CtrlOrCmd+Shift+ArrowLeft":l0,"CtrlOrCmd+Shift+ArrowRight":c0,"CtrlOrCmd+ArrowUp":d0,"CtrlOrCmd+ArrowDown":a0,"CtrlOrCmd+Shift+ArrowUp":u0,"CtrlOrCmd+Shift+ArrowDown":wu,"CtrlOrCmd+A":D0,Home:C0,End:b0,"Shift+Home":g0,"Shift+End":p0,PageUp:B0,PageDown:E0,"Shift+PageUp":I0,"Shift+PageDown":x0,"CtrlOrCmd+X":hk,"CtrlOrCmd+Z":Qv,"CtrlOrCmd+Shift+Z":Kv,Enter:rk,Delete:ik,Backspace:sk,"Shift+Enter":lk,"CtrlOrCmd+Shift+V":ck};function $0(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function P0(n,t,e){if(t.type==="embed"){const i=t.embedData,s=i.src;if(s&&typeof s=="string"){const l=e.get(s);l&&(i.src=l)}return}const o=t.text;o&&o.forEach(i=>{if(i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"){const s=e.get(i.attributes.src);s&&(i.attributes.src=s)}});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{P0(n,l,e)})})}function j0(n,t,e){if(e.size===0)return;t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.replaceResources?i.replaceResources(r,e):P0(t,r,e)})}async function fk(n,t){const e=t.filter(i=>i.indexOf(":")===-1),o=await n.doc.addResources(e),r=new Map;if(e.length!==o.length)return r;for(let i=0;i<e.length;i++)r.set(e[i],o[i]);return r}function mk(n,t){var i,s;const o=t.meta.serverId;if(!o||typeof o!="string")return!1;const r=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i);return!(!r||r.serverId!==o)}async function gk(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(mk(n,t)){const s=Array.from(Object.keys(o));r=await fk(n,s),j0(n,t,r)}const i=new Map;Object.entries(o).forEach(([s,l])=>{r.get(s)===void 0&&s!==l&&i.set(s,l)}),i.size!==0&&j0(n,t,i)}async function pk(n,t){await gk(n,t),n.undoManager.runInGroup(()=>{n.clearSelectedContents();const{block:e,offset:o}=Lr(n);n.insertDoc(e,o,t)})}const Ck=["text/x-ones-editor-doc","image/*","text/html","text/plain","text/markdown","*"];function bk(n){let t;for(const e of Ck)if(t=n[e],t)break;return t||null}class vk{constructor(t){h(this,"editor");h(this,"handlers",[]);h(this,"onPasteText",async t=>{const e=new DataTransfer;e.setData("text/plain",t);const o=await this.editor.dataConverter.fromData(this.editor,e);o&&this.pasteDocs(o,null)});this.editor=t}onInsertText(t,e){if(!j(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=Lr(this.editor);this.handleBeforeInsertText(o,r,i,e)||(this.defaultInsertText(this.editor,o,r,i,e),this.handleAfterInsertText(o,r,i,e))}onKeyDown(t){if(this.handleBeforeKeyDown(t))return!0;const e=this.defaultHandleKeydown(this.editor,t);return this.handleAfterKeyDown(t)?!0:e}onChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleChanged&&o.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleRemoteChanged&&o.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:o,offset:r}=Lr(this.editor);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,o,r)}}onUpdateCompositionText(t,e,o){this.editor.updateCompositionText(e,o),this.editor.selection.caret.update();const{containerId:r,blockIndex:i,offset:s}=Lr(this.editor);for(let l=0;l<this.handlers.length;l++){const c=this.handlers[l];c.handleUpdateCompositionText&&c.handleUpdateCompositionText(this.editor,r,i,s,o)}}onCopy(t){dk(this.editor,t,(e,o,r)=>{for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeCopy){const l=s.handleBeforeCopy(this.editor,o,r);if(l===!0)return!0;if(typeof l=="object"&&l!=null)return l}}})}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;this.editor.dataConverter.fromData(this.editor,t.clipboardData).then(async o=>{o&&this.pasteDocs(o,t)})}onFocus(){A(this.editor.rootElement,"active")}onBlur(){z(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t)}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,o,r))return!0}return!1}handleAfterInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,o,r))return!0}return!1}handleBeforeKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,o,r,i){ru(this.editor,i)}defaultHandleKeydown(t,e){return $0(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];if(o.handleBeforePasteDoc&&await o.handleBeforePasteDoc(this.editor,t))return}await pk(this.editor,t);for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];if(o.handleAfterPasteDoc&&await o.handleAfterPasteDoc(this.editor,t))return}}async pasteDocs(t,e){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePaste&&await i.handleBeforePaste(this.editor,e,t))return}const o=bk(t);if(!!o){await this.pasteDoc(o);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPaste&&await i.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function kk(n,t,e){const o=kr(t,e);return o.remove(),o}w("copy-dom-attributes");const H0=["onabort","onanimationcancel","onanimationend","onanimationiteration","onanimationstart","onauxclick","onblur","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextmenu","oncuechange","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","onformdata","ongotpointercapture","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onload","onloadeddata","onloadedmetadata","onloadstart","onlostpointercapture","onmousedown","onmouseenter","onmouseleave","onmousemove","onmouseout","onmouseover","onmouseup","onpause","onplay","onplaying","onpointercancel","onpointerdown","onpointerenter","onpointerleave","onpointermove","onpointerout","onpointerover","onpointerup","onprogress","onratechange","onreset","onresize","onscroll","onsecuritypolicyviolation","onseeked","onseeking","onselect","onselectionchange","onselectstart","onslotchange","onstalled","onsubmit","onsuspend","ontimeupdate","ontoggle","ontouchcancel","ontouchend","ontouchmove","ontouchstart","ontransitioncancel","ontransitionend","ontransitionrun","ontransitionstart","onvolumechange","onwaiting","onwebkitanimationend","onwebkitanimationiteration","onwebkitanimationstart","onwebkittransitionend","onwheel"];function yk(n,t){for(let l=0;l<H0.length;l++){const c=H0[l];t[c]=n[c]}const e=n.attributes,o=t.attributes,r=[],i=[];for(let l=0;l<e.length;l++){const c=e[l],a=o.getNamedItem(c.name);a?a.value!==c.value&&(a.value=c.value,i.push(c)):r.push(c)}const s=[];for(let l=0;l<o.length;l++){const c=o[l];e.getNamedItem(c.name)||s.push(c)}r.forEach(l=>{t.setAttribute(l.name,l.value)}),i.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function F0(n){const t=Array.from(n.childNodes);return t.forEach(e=>{e instanceof HTMLElement&&e.getAttribute("data-type")==="block-tools"||e.remove()}),t}function z0(n,t,e){var a;const o=n.getContainerById(t),r=kr(o,e),i=jo(r),s=n.doc.getBlockData(t,e),l=bt(n,r);if((a=l==null?void 0:l.handleUpdateBlock)==null?void 0:a.call(l,n,r,s))n.editorBlockRenders.updateBlock(n,i,r,s);else{const u=n.editorBlocks.createBlock(i,o,s),f=F0(u);F0(r),f.forEach(C=>r.appendChild(C));const m=Bl(u);if(m){const C=Bl(r);C&&C.remove(),r.appendChild(m)}yk(u,r)}dg(n,r,s),n.blockHooks.forEach(u=>{var f;(f=u.update)==null||f.call(u,n,i,o,r,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const wk=w("transform-selection");function U0(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;d(wk,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const a=ie.transformCursor(i.offset,e,o);l=P(t,a,"normal")}let c=s;if(s.blockId===t){const a=ie.transformCursor(s.offset,e,o);c=P(t,a,"normal")}return Wt(n,{anchor:l,focus:c})}const Bk=w("handle-block-text-changed");function Ek(n,t,e,o,r){const i=n.getContainerById(t),s=kr(i,e),l=n.doc.getBlockData(t,e);if(d(Bk,l.text,"no block text"),sg(n,s).setBlockText(n,s,l.text),!r){const c=U0(n,l.id,o,r);n.selection.setRange(c,{noScroll:!0})}}function Ik(n,t){const e=Y.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function V0(n,t,e,o){const r=bt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function xk(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{V0(n,i,o,{child:!0})}),V0(n,r,o,{child:!1})}const Un=w("editor-doc");class Tk extends xi{constructor(e,o,r){super();h(this,"localEvents",[]);this.editor=e,this.externalDoc=o,this.externalDoc.registerCallback(this),this.registerLocalEvents(r)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var o,r;return(r=(o=this.externalDoc).getVersionHelper)==null?void 0:r.call(o)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}getBlockData(e,o){return this.externalDoc.getBlockData(e,o)}localUpdateBlockText(e,o,r,i){d(Un,this.editor.isWritable(),"editor is readonly");const s=this.getBlockData(e,o),l=s.text;d(Un,l,`no text, ${e}, ${o}`);const c=U0(this.editor,s.id,r,!0),a=ie.apply(l,r);this.localEvents.forEach(f=>f.onBeforeUpdateBlockText(e,s.id,l,a,c.toDocRange()));const u=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(c,i),u}localUpdateBlockData(e,o,r,i){d(Un,this.editor.isWritable(),"editor is readonly");const s=Y.default(this.getBlockData(e,o)),l=Y.default(Ik(s,r));this.localEvents.forEach(a=>a.onBeforeUpdateBlockData(e,s.id,s,l,i));const c=this.externalDoc.localUpdateBlockData(e,o,r,i);return this.editor.selection.setRange(io(this.editor,i)),c}localInsertBlock(e,o,r,i,s){d(Un,this.editor.isWritable(),"editor is readonly"),this.localEvents.forEach(c=>c.onBeforeInsertBlock(e,o,r,i));const l=this.externalDoc.localInsertBlock(e,o,r,i);return this.editor.selection.setRange(io(this.editor,i),s),l}localDeleteBlock(e,o,r){d(Un,this.editor.isWritable(),"editor is readonly");const i=Y.default(this.getBlockData(e,o));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,o,i,r));const s=this.externalDoc.localDeleteBlock(e,o,r);return this.editor.selection.setRange(io(this.editor,r)),s}localDeleteChildContainers(e){return d(Un,this.editor.isWritable(),"editor is readonly"),e.forEach(o=>{const r=Y.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainer(e,o){return d(Un,this.editor.isWritable(),"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(e,Y.default(o))),this.externalDoc.localInsertChildContainer(e,o)}onRequestReload(e){Un.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)});const o=!1;this.editor.emit("docChanged",this.editor,o)}onUpdateBlockText(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,o,r,i)}),Ek(this.editor,e,o,r,i),this.editor.emit("docChanged",this.editor,i)}onUpdateBlockData(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,i)}),z0(this.editor,e,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(e,o,r,i){this.callbacks.forEach(l=>{var c;return(c=l.onInsertBlock)==null?void 0:c.call(l,e,o,r,i)});const s=this.editor.getContainerById(e);h8(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){xk(this.editor,e,o,r),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,r)});const i=this.editor.getContainerById(e);kk(this.editor,i,o),this.editor.emit("docChanged",this.editor,r)}onInsertChildContainer(e,o,r){this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,e,o,r)})}onDeleteChildContainer(e,o){this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){this.callbacks.forEach(o=>{var r;return(r=o.onCustomMessage)==null?void 0:r.call(o,e)})}onStatusChanged(e){this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)})}onError(e){this.callbacks.forEach(o=>{var r;return(r=o.onError)==null?void 0:r.call(o,e)})}uploadResource(e,o){return this.externalDoc.uploadResource(e,o)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,o){return this.externalDoc.buildResourceUrl(e,o)}request(e,o){return this.externalDoc.request(e,o)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,o,r;return(r=(o=(e=this.externalDoc).getServerMeta)==null?void 0:o.call(e))!=null?r:{}}reset(e){Un.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function q0(n,t){if(n.length===0){n.push(t);return}const e=n[n.length-1];if(!e.combinable(t)){n.push(t);return}e.combine(t)}const Lu=w("undo-action");class Or{constructor(t,e,o){h(this,"beforeRange");h(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=o}undo(t){return!1}redo(t){return!1}combinable(t){return d(Lu,t,"no other action"),!1}combine(t){d(Lu,!1,"no other")}setAfterRange(t){this.afterRange&&Lu.warn("after range has already set"),this.afterRange=t}}const Sk=w("block-action");class W0 extends Or{constructor(e,o,r,i,s){super(e,o,s);h(this,"blockData");h(this,"blockIndex");this.blockData=Y.default(i),this.blockIndex=r}deleteBlock(e,o){if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockData.id);return i?(d(Sk,this.blockIndex===J(i),"invalid block index"),lu(e,i,io(e,o)),!0):!1}insertBlock(e,o){return Mr(e,this.containerId,this.blockIndex,Y.default(this.blockData),o),!0}}class Dk extends W0{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class Lk extends W0{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class Mk extends Or{constructor(e){super(e,U(e.rootContainer),e.selection.range.toDocRange());h(this,"actions",[])}addAction(e){q0(this.actions,e),this.afterRange=e.afterRange}undo(e){let o=!1;return this.actions.concat().reverse().forEach(r=>{r.undo(e)&&(o=!0)}),o}redo(e){let o=!1;return this.actions.forEach(r=>{r.redo(e)&&(o=!0)}),o}setAfterRange(e){this.afterRange=e;const o=this.actions[this.actions.length-1];!o||o instanceof Or&&(o.afterRange||o.setAfterRange(e))}}const Qo=w("update-block-data-action");class rc extends Or{constructor(e,o,r,i,s,l){super(e,o,l);h(this,"beforeBlockData");h(this,"afterBlockData");h(this,"blockId");this.blockId=r,d(Qo,this.blockId===i.id,"invalid block id"),d(Qo,this.blockId===s.id,"invalid block id"),this.beforeBlockData=Y.default(i),this.afterBlockData=Y.default(s),d(Qo,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){d(Qo,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return d(Qo,r,"no container"),Jl(e,o,rc.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){d(Qo,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return d(Qo,r,"no container"),Jl(e,o,rc.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=Y.default(e);return delete o.id,delete o.type,o}}const Mu=w("update-block-text-action");class Xi extends Or{constructor(e,o,r,i,s,l){super(e,o,l);h(this,"beforeRichTextData");h(this,"afterRichTextData");h(this,"blockId");h(this,"type");this.blockId=r,this.beforeRichTextData=Y.default(i),this.afterRichTextData=Y.default(s),this.type=Xi.calType(i,s)}static calType(e,o){d(Mu,e,"no old data"),d(Mu,o,"no new data");const i=ie.diff(e,o),s=new Set;let l=!1;const c=u=>gm(u)?`cjk_${u}`:fm(u)?"number":ml(u)?"space":mm(u)?"letter":"unknown";let a=!1;return i.forEach(u=>{u.insert?u.insert===" "?s.add("insert_letter"):typeof u.insert=="string"&&u.insert.startsWith(" ")&&u.insert.length>1?(l=!0,a=!0,s.add(`insert_${c(u.insert.substr(1))}`)):s.add(`insert_${c(u.insert)}`):u.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:a}}undo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Kl(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Kl(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof Xi)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const o=e.beforeRange,r=o.anchor;if(!r.isSimple())return!1;const i=this.afterRange;if(!i)return!1;const s=i.anchor;return!(!s.isSimple()||s.blockId!==o.anchor.blockId||s.offset!==r.offset)}combine(e){d(Mu,e instanceof Xi,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class G0 extends Or{constructor(t,e,o){super(t,e,t.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(t){return t.doc.localDeleteChildContainers([this.containerId]),!0}insertChildContainer(t){return t.doc.localInsertChildContainer(this.containerId,Y.default(this.blocks)),!0}}class Rk extends G0{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class Ak extends G0{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const nn=w("undo");class Ok{constructor(t){h(this,"editor");h(this,"actions",[]);h(this,"undoCursor");h(this,"currentGroup",null);h(this,"groupCounter",0);h(this,"undoRedoing",!1);h(this,"handleSelectionChange",t=>{if(this.currentGroup){this.currentGroup.setAfterRange(t.selection.range.toDocRange());return}const e=this.actions[this.actions.length-1];!e||e.afterRange||e.setAfterRange(t.selection.range.toDocRange())});this.editor=t,this.undoCursor=-1,this.editor.addListener("selectionChanged",this.handleSelectionChange)}reset(){this.actions=[],this.undoCursor=-1}prepareSaveUndoState(){this.undoCursor!==-1&&(this.actions.splice(this.undoCursor),this.undoCursor=-1)}addAction(t){this.currentGroup?this.currentGroup.addAction(t):(q0(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(d(nn,!this.currentGroup,"current group already exists"),this.currentGroup=new Mk(this.editor),this.groupCounter=1):(d(nn,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){d(nn,this.currentGroup,"current group not exists"),d(nn,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?nn.warn("empty undo group, skip it"):(this.actions.push(this.currentGroup),this.editor.input.handleChanged(this.currentGroup)),this.currentGroup=null)}hasGroup(){return this.groupCounter>0}runInGroup(t){this.beginGroup();try{const e=t();return setTimeout(()=>this.editor.selection.caret.update()),e}catch(e){throw nn.error(`failed to run action: ${e.message}`),e}finally{this.endGroup()}}undo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor>0;){this.undoCursor-=1;const t=this.actions[this.undoCursor];if(t.undo(this.editor)){try{this.editor.selection.setRange(io(this.editor,t.beforeRange))}catch(e){nn.error(`undo: failed to restore caret pos: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}redo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor<this.actions.length;){const t=this.actions[this.undoCursor];if(this.undoCursor+=1,t.redo(this.editor)){try{const e=t.afterRange;e?this.editor.selection.setRange(io(this.editor,e)):nn.warn("no after range")}catch(e){nn.error(`redo: failed to set caret pos after redo: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}canUndo(){return!(this.actions.length===0||this.undoCursor===0)}canRedo(){return!(this.actions.length===0||this.undoCursor===-1||this.undoCursor===this.actions.length)}lastAction(){var e;const t=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(e=this.actions[t])!=null?e:null}undoTo(t){for(;;){const e=this.lastAction();if(!e||e===t)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(t,e,o,r,i){this.undoRedoing||(this.prepareSaveUndoState(),ie.diff(o,r).length!==0&&this.addAction(new Xi(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new rc(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),d(nn,e>=0,"invalid block index"),d(nn,o,"no block data"),this.addAction(new Dk(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new Lk(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new Rk(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new Ak(this.editor,t,e)))}}class _k{async fromData(t,e){const o=e.getData("text/x-ones-editor-doc");if(o)return{"text/x-ones-editor-doc":JSON.parse(o)}}}class Nk{constructor(){h(this,"converters",[]);this.addConverter(new _k)}async fromData(t,e){let o={};for(const r of this.converters){const i=await r.fromData(t,e);i&&(o={...o,...i})}return o}addConverter(t){this.converters.push(t)}}class $k{constructor(t){h(this,"renders",[]);this.editor=t}registerRender(t){this.renders.push(t)}renderText(t,e){const o={classes:[],attributes:{},styles:{}};return this.renders.forEach(r=>{if(r.renderText){const i=r.renderText(this.editor,t,e);i.classes&&o.classes.push(...i.classes),i.attributes&&(o.attributes={...o.attributes,...i.attributes}),i.styles&&(o.styles={...o.styles,...i.styles})}}),o}renderBlock(t,e,o){const r={classes:[],attributes:{},styles:{}};return this.renders.forEach(i=>{if(i.renderBlock){const s=i.renderBlock(this.editor,e,o);s.classes&&r.classes.push(...s.classes),s.attributes&&(r.attributes={...r.attributes,...s.attributes}),s.styles&&(r.styles={...r.styles,...s.styles})}}),r}updateBlock(t,e,o,r){this.renders.forEach(i=>{var s;(s=i.updateBlock)==null||s.call(i,t,e,o,r)})}}class Nt extends Yt.TypedEmitter{constructor(e){super();h(this,"hoveringBlock",null);h(this,"hoveringTextChild",null);h(this,"filters",[]);h(this,"finders",[]);h(this,"handleDocumentMouseMove",e=>{if(this.hoveringBlock){for(const s of this.filters)if(s.isInBlock(this.hoveringBlock,e))return}const o=document.elementFromPoint(e.x,e.y);if(!o){this.setHoveringBlock(null,e,null);return}let r=F(o);if((!r||!It(this.editor.rootContainer,r))&&(r=this.findBlockByFinders(e),!r)){this.setHoveringBlock(null,e,null);return}const i=this.getParentTextContentChild(r,o);this.setHoveringBlock(r,e,i)});this.editor=e,document.addEventListener("mousemove",this.handleDocumentMouseMove)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.filters.forEach(e=>e.destroy()),this.filters=[],this.finders.forEach(e=>e.destroy()),this.finders=[]}addFilter(e){this.filters.push(e)}addFinder(e){this.finders.push(e)}hoveringBlockId(){return this.hoveringBlock?q(this.hoveringBlock):""}findBlockByFinders(e){for(let o=0;o<this.finders.length;o++){const i=this.finders[o].findTargetBlock(this.editor,e);if(i)return i}return null}setHoveringBlock(e,o,r){if(this.hoveringBlock===e&&this.hoveringTextChild===r)return;if(this.hoveringBlock!==e){const s=this.hoveringBlock&&It(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&z(s,"hover"),e&&A(e,"hover"),this.hoveringBlock=e,this.emit("change",this.hoveringBlock,s,o)}const i=this.hoveringTextChild;this.hoveringTextChild=r,this.emit("childChange",this.hoveringBlock,r,i,o)}static get(e){return e.addCustom("standard-hovering-block",()=>new Nt(e))}getParentTextContentChild(e,o){if(!j(this.editor,e))return null;const r=it(e);return o.parentElement===r?o:md(o)}}const Z0="style-color-",Y0="style-bg-color-";class Pk{renderText(t,e,o){const r=[],i={};return Object.entries(o).forEach(([s,l])=>{l===!0?s.startsWith(Z0)?i["data-style-color"]=s.substring(Z0.length):s.startsWith(Y0)?i["data-style-bg-color"]=s.substring(Y0.length):s.startsWith("style")&&r.push(s):typeof l=="string"&&s==="link"&&(r.push("link"),i.link=l)}),{classes:r,attributes:i}}renderBlock(t,e,o){var l,c;const r={};Object.entries(o).filter(a=>a[0].startsWith("style-")).forEach(([a,u])=>{r[`data-${a}`]=`${u}`});const s=[];return((c=(l=t.selection)==null?void 0:l.range)==null?void 0:c.start.blockId)===o.id&&s.push("focused"),typeof o.align=="string"&&o.align&&(r["data-style-align"]=o.align),o.heading&&(r["data-style-heading"]=String(o.heading)),o.quoted&&(r["data-style-quoted"]="true"),Nt.get(t).hoveringBlockId()===o.id&&s.push("hover"),{attributes:r,classes:s}}updateBlock(t,e,o,r){var s,l;Array.from(o.attributes).forEach(c=>{c.name.startsWith("data-style-")&&o.removeAttribute(c.name)}),Object.entries(r).filter(c=>c[0].startsWith("style-")).forEach(([c,a])=>{o.setAttribute(`data-${c}`,`${a}`)}),((l=(s=t.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&A(o,"focused"),Nt.get(t).hoveringBlockId()===r.id&&A(o,"hover")}}function jk(n){n.editorBlocks.registerBlockClass(ve),n.editorBlocks.registerBlockClass(yg),n.editorBoxes.registerBoxClass(dp),n.editorBoxes.registerBoxClass(up),n.editorInsertions.registerInsertionClass(mp),n.editorBlockRenders.registerRender(new Pk)}function Hk(n,t){jk(n),t!=null&&t.blocks&&t.blocks.forEach(e=>n.editorBlocks.registerBlockClass(e)),t!=null&&t.boxes&&t.boxes.forEach(e=>n.editorBoxes.registerBoxClass(e)),t!=null&&t.embeds&&t.embeds.forEach(e=>n.editorEmbeds.registerEmbedClass(e)),t!=null&&t.insertions&&t.insertions.forEach(e=>n.editorInsertions.registerInsertionClass(e)),t!=null&&t.decorators&&t.decorators.forEach(e=>n.editorDecorators.registerDecorator(e)),t!=null&&t.dataConverters&&t.dataConverters.forEach(e=>n.dataConverter.addConverter(e)),t!=null&&t.commandProviders&&t.commandProviders.forEach(e=>n.editorCommandProviders.registerCommandProvider(e)),t!=null&&t.textRenders&&t.textRenders.forEach(e=>n.editorBlockRenders.registerRender(e))}const Q0=w("range-commands");function K0(n,t){n.forEach(e=>{e.source=t,e.children&&K0(e.children,t)})}function J0(n,t,e){const o=q(t);d(Q0,o===e.start.blockId,"invalid start range"),d(Q0,o===e.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];return r.forEach(s=>{const l=s.getAvailableCommands(n,t,e);K0(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,i);l&&(i=l)}}),at(n,t)&&xr(n,t,e.start,e.end).forEach(l=>{Mt(l).forEach(a=>{const u=W(n,a),f=Wt(n,{anchor:P(a,0,"home"),focus:P(a,u,"end")}),m=J0(n,a,f);i.push(...m)})}),i}function X0(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=Wt(t,{anchor:r.start,focus:r.end});J0(t,r.block,i).forEach(l=>{o.push(l)})}),o}function t2(n,t,e,o,r,i){var u;const s=n.editorCommandProviders.getCommandProviders();for(let f=0;f<s.length;f++){const m=s[f];if(m.beforeExecuteCommand&&m.beforeExecuteCommand(n,t,e,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),c={};if((u=l.executeCommand)!=null&&u.call(l,n,t,e,o,r,{}))return i[q(t)]=c,!0;let a=!1;return at(n,t)&&xr(n,t,e.start,e.end).forEach(m=>{Mt(m).forEach(v=>{const B=W(n,v),y=Wt(n,{anchor:P(v,0,"home"),focus:P(v,B,"end")});t2(n,v,y,o,r,i)&&(a=!0)})}),s.forEach(f=>{f.afterExecuteCommand&&f.afterExecuteCommand(n,t,e,o,r,i)}),a}function e2(n,t,e){const o=n.getEditor(),r={},i=o.editorCommandProviders.getCommandProvider(t.source);return i.executeRangeCommand&&i.executeRangeCommand(o,n,t,e,r)||n.getSelectedBlocks().forEach(l=>{const c=Wt(o,{anchor:l.start,focus:l.end});t2(o,l.block,c,t,e,r)}),r}const Fk=w("command-providers");class n2{constructor(t){h(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(o=>o.id===t);return d(Fk,e,`no command provider, id=${t}`),e}getCommands(t){return X0(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>e2(t,e,o))}getEmptyBlockTextAttributes(t,e){let o={};if(this.providers.forEach(r=>{var s;const i=(s=r.getEmptyBlockTextAttributes)==null?void 0:s.call(r,t,e);i&&(o={...o,...i})}),Object.keys(o).length!==0)return o}}function zk(n,t){const e=H(t),o=U(e),r=J(t);z0(n,o,r)}const Uk=w("table-scroll");class o2{constructor(t,e,o,r,i){h(this,"handleEvent",t=>{this.handler(this.editor,t,this.data)});this.editor=t,this.dom=e,this.name=o,this.handler=r,this.data=i,e.addEventListener(o,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class Vk{constructor(t){h(this,"handlers",new Map);this.editor=t}destroy(){Array.from(this.handlers.entries()).forEach(([t,e])=>{e.forEach(o=>o.destroy()),this.handlers.delete(t)})}addEventListener(t,e,o,r){const i=this.handlers.get(t);if(i){if(i.find(s=>s.handler===o&&s.name===e)){Uk.warn(`event has already registered: ${e}`);return}i.push(new o2(this.editor,t,e,o,r))}else{const s=new o2(this.editor,t,e,o,r);this.handlers.set(t,[s])}}removeEventListener(t,e,o){if(!t){for(const[i,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const c=s[l];if(e)e===c.name&&o===c.handler&&s.splice(l,1);else if(o===c.handler){s.splice(l,1),c.destroy(),s.length===0&&this.handlers.delete(i);continue}}return}const r=this.handlers.get(t);if(r){const i=r.findIndex(s=>s.handler===o&&s.name===e);if(i!==-1){const s=r[i];r.splice(i,1),s.destroy(),r.length===0&&this.handlers.delete(t)}}}removeAllListeners(t,e){const o=this.handlers.get(t);if(o)if(e)for(let r=0;r<o.length;r++){const i=o[r];i.name===e&&(o.splice(r,1),i.destroy())}else o.forEach(r=>{r.destroy()}),this.handlers.delete(t)}}const r2=w("update-block-text");function qk(n,t){const e=n.getBoxById(t.id),o=F(e);d(r2,o,"no parent block"),d(r2,j(n,o),"not a text block");const r=n.getBlockText(o),i=ep(r,"id",t.id,t);Np(n,o,i)}function Wk(n,t){for(const e of n.blockHooks)if(e.writable){const o=e.writable(n,t);if(typeof o=="boolean")return o}return!0}function Gk(n){return n.readonly?!1:!tn(n).find(o=>!n.isBlockWritable(o.block))}class Zk{constructor(t){this.editor=t}getKey(t){return`${this.editor.id}-${t}`}async getItem(t){return window.localStorage.getItem(this.getKey(t))}async setItem(t,e){if(!e){this.removeItem(t);return}window.localStorage.setItem(this.getKey(t),e)}async removeItem(t){window.localStorage.removeItem(this.getKey(t))}}class Yk{constructor(){h(this,"shortcuts",[])}handleKeyboardEvents(t,e){const o=this.shortcuts;for(const r of o){const i=Object.entries(r);for(const[s,l]of i)if(Pn(e,s)){const c=l(t,e);if(c!==void 0)return c}}}}const Vn=w("editor");class Qk extends Yt.TypedEmitter{constructor(e,o,r){var i,s,l,c,a,u,f;super();h(this,"parent");h(this,"rootElement");h(this,"contentElement");h(this,"rootContainerObject");h(this,"rootContainer");h(this,"input");h(this,"selection");h(this,"selectionHandler");h(this,"doc");h(this,"id");h(this,"clientId");h(this,"compositingText","");h(this,"undoManager");h(this,"shortcuts",new Yk);h(this,"dataConverter",new Nk);h(this,"editorBlocks",new Cg(this));h(this,"editorBoxes",new fp(this));h(this,"editorInsertions",new pp(this));h(this,"editorEmbeds",new vg(this));h(this,"editorDecorators",new Cp(this));h(this,"editorCommandProviders",new n2(this));h(this,"editorBlockRenders",new $k(this));h(this,"blockHooks",[]);h(this,"domEvents",new Vk(this));h(this,"customs",new Map);h(this,"options");h(this,"inputHandlers",new vk(this));h(this,"settingsProvider");h(this,"_readonly",!1);Vn.debug("create editor"),this.setMaxListeners(100),this.options={colors:(i=r==null?void 0:r.colors)!=null?i:["#9923E9","#4587C2","#8BDB7A","#FB28D3","#CBC619","#10FEEB","#812A1A","#8A3F25","#22D742","#A53E74","#555C87","#57E0AA"],componentsOptions:(l=(s=r==null?void 0:r.components)==null?void 0:s.options)!=null?l:{},scrollContainer:r==null?void 0:r.scrollContainer},this.settingsProvider=(c=r==null?void 0:r.settingsProvider)!=null?c:new Zk(this),Hk(this,r==null?void 0:r.components),this.blockHooks.push(...(u=(a=r==null?void 0:r.components)==null?void 0:a.blockHooks)!=null?u:[]),this.id=(f=r==null?void 0:r.id)!=null?f:N(),this.clientId=N(),this.undoManager=new Ok(this),this.doc=new Tk(this,o,this.undoManager),this.parent=e,this.rootElement=b("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=b("div",["editor-content"],this.rootElement),this.rootContainerObject=og(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new lv(this,this.inputHandlers),this.selection=new Wv(this),this.selectionHandler=new Yv(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),xt.isMobile&&A(this.rootElement,"mobile"),xt.isSafari&&A(this.rootElement,"safari"),this._readonly&&A(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?A(this.rootElement,"readonly"):z(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:We(this.rootContainer)}addCustom(e,o){const r=this.customs.get(e);if(r)return r;const i=o(this);return this.customs.set(e,i),i}getCustom(e){const o=this.customs.get(e);return d(Vn,o,`${e} does not exists`),o}replaceCustom(e,o){const r=this.customs.get(e);return r&&r.destroy(),this.customs.set(e,o),o}findCustom(e){return this.customs.get(e)}findCustomByType(e){const o=this.customs.values();for(const r of o)if(r instanceof e)return r;return null}destroyCustom(e){const o=this.customs.get(e);o&&(this.customs.delete(e),o.destroy())}getComponentOptions(e){return this.options.componentsOptions[e]}registerLocalEvents(e){this.doc.registerLocalEvents(e)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(e,o,r){return this.editorBlocks.createBlock(e,o,r)}createBox(e,o){return this.editorBoxes.createBox(e,o)}createInsertion(e,o){return this.editorInsertions.createInsertion(e,o)}destroy(){Vn.debug("destroy editor"),this.emit("destroy",this),this.input.destroy(),this.rootContainerObject.destroy(),this.rootElement.remove(),this.doc.destroy(),this.customs.forEach(e=>e.destroy()),this.customs.clear(),this.selection.destroy(),this.domEvents.destroy(),this.removeAllListeners(),this.inputHandlers.destroy()}focus(){this.input.focus()}focusToBlock(e,o){uu(this,e,o)}isWritable(){return Gk(this)}isBlockWritable(e){return Wk(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return d(Vn,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),d(Vn,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(e,o,r){return rg(this,e,o,r)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const e=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return e[e.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&d(Vn,Po(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&d(Vn,fd(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return d(Vn,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return d(Vn,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return kr(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return J(o)}return J(e)}getContainerById(e){return Br(this,e)}getParentContainer(e){return H(e)}reloadBlock(e){zk(this,e)}contains(e){const o=e instanceof Element?e:e.parentElement;return o?o.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,o,r,i,s){const l={blockId:r.id,offset:0},c={anchor:l,focus:l};return Mr(this,e,o,r,i!=null?i:c,s)}insertEmbed(e,o,r,i,s){const l={id:N(),type:"embed",embedType:r,embedData:i};return this.insertBlock(e,o,l,s)}deleteBlock(e,o){cu(this,e,o)}mergeTextBlock(e,o){return Ap(this,e,o)}breakTextBlock(e,o,r){return Rr(this,e,o,r).newBlock}getTextPosition(){return Lr(this)}getBlockString(e,o){const r=this.getBlockText(e);return vt(r,o)}getBlockData(e){return co(this,e)}getBoxData(e){return cp(this,e)}getBlockText(e){return ue(this,e)}setBlockText(e,o){Np(this,e,o)}deleteTextFromBlock(e,o,r,i){return iu(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return xp(this,e,o,r,i)}insertBoxToBlock(e,o,r){return Tp(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){jp(this,e,o,r,i)}insertDocAt(e,o,r,i){return mu(this,e,o,r,i)}deleteChildContainers(e){Rp(this,e)}replaceBlockText(e,o){return Kl(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...c}=i;return Jl(this,e,c,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return $p(this,e,o,r)}updateBoxData(e){qk(this,e)}getSelectedText(){const e=Ji(this);return Wl(this,e)}clearSelectedContents(){du(this)}insertTextBlock(e,o,r,i){const s=zn(e!=null?e:"");return Mp(this,s,o,r,i==null?void 0:i.newRange,i==null?void 0:i.insertBlockOptions)}updateCompositionText(e,o){if(e&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!o){Dp(this);return}o?(this.compositingText="",od()||ru(this,e)):(this.compositingText=e,Sp(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function ts(n,t,e){return new Qk(n,t,e)}function Kk(n){const t=(o,r)=>{const i=o.findIndex(l=>l.id===r.id);if(i===-1){o.push(r);return}const s=o[i];if(s.value!==r.value){o.splice(i,1);return}if(!!s.states){if(!r.states){s.states=[];return}s.states=Za.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const Jk=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class ic extends Yt.TypedEmitter{constructor(e){super();h(this,"users",new Map);h(this,"cursors",new Map);h(this,"addingUser",!1);h(this,"colors");this.colors=e&&e.length>0?e:Jk}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&cl.default(o,e))return;this.cursors.set(e.user.userId,e);const r=new Set([e.range.anchor.blockId,e.range.focus.blockId]),i=new Set(r);o&&new Set([o.range.anchor.blockId,o.range.focus.blockId]).forEach(l=>{r.has(l)||i.add(l)}),this.emit("remote-carets-change",[...i])}addUsers(e){this.addingUser=!0,e.forEach(o=>this.addUser(o)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(e){this.users.set(e.userId,e),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(e){var o;return(o=this.users.get(e))!=null?o:null}removeUser(e){this.users.delete(e),this.cursors.delete(e),this.emit("change",Array.from(this.users.values()))}updateUsers(e){this.users.clear(),this.addingUser=!0;try{e.forEach(o=>{this.addUser(o)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const o=new Map;return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e&&Hl(r.range)).forEach(r=>{const i=r.range.focus.offset;let s=o.get(i);s||(s=[],o.set(i,s)),s.push(r)}),o}getCursors(e){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===e||o.range.focus.blockId===e)}onUpdateBlockText(e,o,r){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(Hl(l.range)){const{anchor:c,focus:a}=l.range;c.blockId===e.id&&(c.offset=ie.transformCursor(c.offset,o,r)),a.blockId===e.id&&(a.offset=ie.transformCursor(a.offset,o,r))}})}getFixedUserColor(e,o){let r=0;Array.from(e).forEach(s=>{r+=s.charCodeAt(0)});const i=r%this.colors.length;return this.colors[i]}destroy(){this.removeAllListeners()}}const te=w("local-doc");class Ru extends xi{constructor(e,o){super();h(this,"doc");h(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[zn("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return Y.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,o){const r=this.getContainerBlocks(e);d(te,r,`no container data: ${e}`);const i=r[o];return d(te,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);d(te,i.text,"no text for data");const s=ie.apply(i.text,r);return i.text=s,d(te,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var c;return(c=l.onUpdateBlockText)==null?void 0:c.call(l,e,o,r,!0)}),s}localUpdateBlockData(e,o,r){const i=this.getBlockData(e,o);return r.delete.forEach(s=>delete i[s]),Object.entries(r.insert).forEach(([s,l])=>{i[s]=l}),d(te,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,!0)}),i}localInsertBlock(e,o,r){const i=this.getContainerBlocks(e);return d(te,i,`no container data: ${e}`),d(te,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),d(te,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,o,r,!0)}),r}localDeleteBlock(e,o){const r=this.getContainerBlocks(e);d(te,r,`no container data: ${e}`),d(te,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),d(te,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,!0)}),i}localInsertChildContainer(e,o){this.doc.blocks[e]=o,d(te,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onInsertChildContainer)==null?void 0:i.call(r,e,o,!0)})}localDeleteChildContainers(e){te.debug(`delete child containers: ${e}`),e.forEach(o=>{d(te,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{d(te,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,o,!0)})})}uploadResource(e,o){d(te,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){d(te,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new ic}setDoc(e){this.doc=Y.default(e),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}function Ko(n){return pt(H(n))}class Xk{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function Au(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new Xk(o)})}const ty=w("remote-cursor");class ey{constructor(){h(this,"remoteUsers",new ic)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):ty.debug(`unknown remote message received: ${t}`)}handleUpdateUsers(t){this.remoteUsers.updateUsers(t)}handleUpdateCaret(t){const e=this.remoteUsers.findUser(t.userId);!e||this.remoteUsers.setCursor({oneseditor:"cursor",user:e,range:t.range,time:Date.now()})}destroy(){this.remoteUsers.destroy()}}function ny(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function es(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=ny(Y.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function ho(n){return n==="root"?"blocks":n}function _r(n){return n==="blocks"?"root":n}const oy={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new oe.default(n)},apply(n,t){const e=new oe.default(n),o=new oe.default(t);return e.compose(o).ops},compose(n,t){const e=new oe.default(n),o=new oe.default(t);return e.compose(o).ops},diff(n,t){const e=new oe.default(n),o=new oe.default(t);return e.diff(o).ops},transform(n,t,e){const o=new oe.default(n);return new oe.default(t).transform(o,e==="left").ops},transformCursor(n,t,e){return t.transformPosition(n,!e)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,t,e){if(!n)return null;const o=new oe.default(t),r=this.transformCursor(n.index,o,e),i=this.transformCursor(n.index+n.length,o,e);return{...n,index:r,length:i-r}}}};var ns=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},fo={},Ou=Wf.default.EventEmitter;fo.EventEmitter=Ou,fo.mixin=ry;function ry(n){for(var t in Ou.prototype)n.prototype[t]=Ou.prototype[t]}var i2=["info","warn","error"];function s2(){var n={};i2.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var iy=s2;s2.prototype.setMethods=function(n){n=n||{};var t=this;i2.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var sy=iy,ly=new sy,l2=ly;function Jo(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,Jo):this.stack=new Error().stack}Jo.prototype=Object.create(Error.prototype),Jo.prototype.constructor=Jo,Jo.prototype.name="ShareDBError",Jo.CODES={ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT:"ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT",ERR_APPLY_SNAPSHOT_NOT_PROVIDED:"ERR_APPLY_SNAPSHOT_NOT_PROVIDED",ERR_CLIENT_ID_BADLY_FORMED:"ERR_CLIENT_ID_BADLY_FORMED",ERR_CANNOT_PING_OFFLINE:"ERR_CANNOT_PING_OFFLINE",ERR_CONNECTION_SEQ_INTEGER_OVERFLOW:"ERR_CONNECTION_SEQ_INTEGER_OVERFLOW",ERR_CONNECTION_STATE_TRANSITION_INVALID:"ERR_CONNECTION_STATE_TRANSITION_INVALID",ERR_DATABASE_ADAPTER_NOT_FOUND:"ERR_DATABASE_ADAPTER_NOT_FOUND",ERR_DATABASE_DOES_NOT_SUPPORT_SUBSCRIBE:"ERR_DATABASE_DOES_NOT_SUPPORT_SUBSCRIBE",ERR_DATABASE_METHOD_NOT_IMPLEMENTED:"ERR_DATABASE_METHOD_NOT_IMPLEMENTED",ERR_DEFAULT_TYPE_MISMATCH:"ERR_DEFAULT_TYPE_MISMATCH",ERR_DOC_MISSING_VERSION:"ERR_DOC_MISSING_VERSION",ERR_DOC_ALREADY_CREATED:"ERR_DOC_ALREADY_CREATED",ERR_DOC_DOES_NOT_EXIST:"ERR_DOC_DOES_NOT_EXIST",ERR_DOC_TYPE_NOT_RECOGNIZED:"ERR_DOC_TYPE_NOT_RECOGNIZED",ERR_DOC_WAS_DELETED:"ERR_DOC_WAS_DELETED",ERR_INFLIGHT_OP_MISSING:"ERR_INFLIGHT_OP_MISSING",ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION:"ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION",ERR_MAX_SUBMIT_RETRIES_EXCEEDED:"ERR_MAX_SUBMIT_RETRIES_EXCEEDED",ERR_MESSAGE_BADLY_FORMED:"ERR_MESSAGE_BADLY_FORMED",ERR_MILESTONE_ARGUMENT_INVALID:"ERR_MILESTONE_ARGUMENT_INVALID",ERR_OP_ALREADY_SUBMITTED:"ERR_OP_ALREADY_SUBMITTED",ERR_OP_NOT_ALLOWED_IN_PROJECTION:"ERR_OP_NOT_ALLOWED_IN_PROJECTION",ERR_OP_SUBMIT_REJECTED:"ERR_OP_SUBMIT_REJECTED",ERR_OP_VERSION_MISMATCH_AFTER_TRANSFORM:"ERR_OP_VERSION_MISMATCH_AFTER_TRANSFORM",ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM:"ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM",ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT:"ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT",ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED:"ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED",ERR_OT_OP_BADLY_FORMED:"ERR_OT_OP_BADLY_FORMED",ERR_OT_OP_NOT_APPLIED:"ERR_OT_OP_NOT_APPLIED",ERR_OT_OP_NOT_PROVIDED:"ERR_OT_OP_NOT_PROVIDED",ERR_PRESENCE_TRANSFORM_FAILED:"ERR_PRESENCE_TRANSFORM_FAILED",ERR_PROTOCOL_VERSION_NOT_SUPPORTED:"ERR_PROTOCOL_VERSION_NOT_SUPPORTED",ERR_QUERY_EMITTER_LISTENER_NOT_ASSIGNED:"ERR_QUERY_EMITTER_LISTENER_NOT_ASSIGNED",ERR_SNAPSHOT_READ_SILENT_REJECTION:"ERR_SNAPSHOT_READ_SILENT_REJECTION",ERR_SNAPSHOT_READS_REJECTED:"ERR_SNAPSHOT_READS_REJECTED",ERR_SUBMIT_TRANSFORM_OPS_NOT_FOUND:"ERR_SUBMIT_TRANSFORM_OPS_NOT_FOUND",ERR_TYPE_CANNOT_BE_PROJECTED:"ERR_TYPE_CANNOT_BE_PROJECTED",ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE:"ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE",ERR_UNKNOWN_ERROR:"ERR_UNKNOWN_ERROR"};var sc=Jo,os={},c2=cy;function cy(n,t,e,o){var r=function(s,l,c,a){t(c,s,l,"left"),t(a,l,s,"right")},i=n.transformX=function(s,l){e(s),e(l);for(var c=[],a=0;a<l.length;a++){for(var u=l[a],f=[],m=0;m<s.length;){var C=[];if(r(s[m],u,f,C),m++,C.length===1)u=C[0];else if(C.length===0){for(var v=m;v<s.length;v++)o(f,s[v]);u=null;break}else{for(var B=i(s.slice(m),C),y=0;y<B[0].length;y++)o(f,B[0][y]);for(var S=0;S<B[1].length;S++)o(c,B[1][S]);u=null;break}}u!=null&&o(c,u),s=f}return[s,c]};n.transform=function(s,l,c){if(!(c==="left"||c==="right"))throw new Error("type must be 'left' or 'right'");return l.length===0?s:s.length===1&&l.length===1?t([],s[0],l[0],c):c==="left"?i(s,l)[0]:i(l,s)[1]}}var a2={exports:{}},mo=a2.exports={name:"text0",uri:"http://sharejs.org/types/textv0",create:function(n){if(n!=null&&typeof n!="string")throw new Error("Initial data must be a string");return n||""}},_u=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},Nu=function(n){if(typeof n.p!="number")throw new Error("component missing position field");if(typeof n.i=="string"==(typeof n.d=="string"))throw new Error("component needs an i or d field");if(n.p<0)throw new Error("position cannot be negative")},lc=function(n){for(var t=0;t<n.length;t++)Nu(n[t])};mo.apply=function(n,t){var e;lc(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=_u(n,r.p,r.i);else{if(e=n.slice(r.p,r.p+r.d.length),r.d!==e)throw new Error("Delete component '"+r.d+"' does not match deleted text '"+e+"'");n=n.slice(0,r.p)+n.slice(r.p+r.d.length)}}return n};var qn=mo._append=function(n,t){if(!(t.i===""||t.d===""))if(n.length===0)n.push(t);else{var e=n[n.length-1];e.i!=null&&t.i!=null&&e.p<=t.p&&t.p<=e.p+e.i.length?n[n.length-1]={i:_u(e.i,t.p-e.p,t.i),p:e.p}:e.d!=null&&t.d!=null&&t.p<=e.p&&e.p<=t.p+t.d.length?n[n.length-1]={d:_u(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};mo.compose=function(n,t){lc(n),lc(t);for(var e=n.slice(),o=0;o<t.length;o++)qn(e,t[o]);return e},mo.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=0),qn(t,o)}return t};var $u=function(n,t,e){return t.i!=null?t.p<n||t.p===n&&e?n+t.i.length:n:n<=t.p?n:n<=t.p+t.d.length?t.p:n-t.d.length};mo.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=$u(n,t[r],o);return n};var ay=mo._tc=function(n,t,e,o){if(Nu(t),Nu(e),t.i!=null)qn(n,{i:t.i,p:$u(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(qn(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&qn(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)qn(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)qn(n,t);else{var i={d:"",p:t.p};t.p<e.p&&(i.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(i.d+=t.d.slice(e.p+e.d.length-t.p));var s=Math.max(t.p,e.p),l=Math.min(t.p+t.d.length,e.p+e.d.length),c=t.d.slice(s-t.p,l-t.p),a=e.d.slice(s-e.p,l-e.p);if(c!==a)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=$u(i.p,e),qn(n,i))}return n},dy=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};mo.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=dy(n[t]);return n},c2(mo,ay,lc,qn);var cc=function(n){return Object.prototype.toString.call(n)=="[object Array]"},uy=function(n){return!!n&&n.constructor===Object},on=function(n){return JSON.parse(JSON.stringify(n))},tt={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Wn={};tt.registerSubtype=function(n){Wn[n.name]=n},tt.create=function(n){return n===void 0?null:on(n)},tt.invertComponent=function(n){var t={p:n.p};return n.t&&Wn[n.t]&&(t.t=n.t,t.o=Wn[n.t].invert(n.o)),n.si!==void 0&&(t.sd=n.si),n.sd!==void 0&&(t.si=n.sd),n.oi!==void 0&&(t.od=n.oi),n.od!==void 0&&(t.oi=n.od),n.li!==void 0&&(t.ld=n.li),n.ld!==void 0&&(t.li=n.ld),n.na!==void 0&&(t.na=-n.na),n.lm!==void 0&&(t.lm=n.p[n.p.length-1],t.p=n.p.slice(0,n.p.length-1).concat([n.lm])),t},tt.invert=function(n){for(var t=n.slice().reverse(),e=[],o=0;o<t.length;o++)e.push(tt.invertComponent(t[o]));return e},tt.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!cc(n[t].p))throw new Error("Missing path")},tt.checkList=function(n){if(!cc(n))throw new Error("Referenced element not a list")},tt.checkObj=function(n){if(!uy(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function rs(n){n.t="text0";var t={p:n.p.pop()};n.si!=null&&(t.i=n.si),n.sd!=null&&(t.d=n.sd),n.o=[t]}function is(n){n.p.push(n.o[0].p),n.o[0].i!=null&&(n.si=n.o[0].i),n.o[0].d!=null&&(n.sd=n.o[0].d),delete n.t,delete n.o}tt.apply=function(n,t){tt.checkValidOp(t),t=on(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&rs(r);for(var i=null,s=e,l="data",c=0;c<r.p.length;c++){var a=r.p[c];if(i=s,s=s[l],l=a,i==null)throw new Error("Path invalid")}if(r.t&&r.o!==void 0&&Wn[r.t])s[l]=Wn[r.t].apply(s[l],r.o);else if(r.na!==void 0){if(typeof s[l]!="number")throw new Error("Referenced element not a number");s[l]+=r.na}else if(r.li!==void 0&&r.ld!==void 0)tt.checkList(s),s[l]=r.li;else if(r.li!==void 0)tt.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)tt.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(tt.checkList(s),r.lm!=l){var u=s[l];s.splice(l,1),s.splice(r.lm,0,u)}}else if(r.oi!==void 0)tt.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)tt.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},tt.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},tt.incrementalApply=function(n,t,e){for(var o=0;o<t.length;o++){var r=[t[o]];n=tt.apply(n,r),e(r,n)}return n};var hy=tt.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==t[o]&&(!e||o!==n.length-1))return!1;return!0};tt.append=function(n,t){if(t=on(t),n.length===0){n.push(t);return}var e=n[n.length-1];if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(rs(t),rs(e)),hy(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Wn[t.t]){if(e.o=Wn[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var o=t.p,r=0;r<e.o.length-1;r++)t.o=[e.o.pop()],t.p=o.slice(),is(t),n.push(t);is(e)}}else e.na!=null&&t.na!=null?n[n.length-1]={p:e.p,na:e.na+t.na}:e.li!==void 0&&t.li===void 0&&t.ld===e.li?e.ld!==void 0?delete e.li:n.pop():e.od!==void 0&&e.oi===void 0&&t.oi!==void 0&&t.od===void 0?e.oi=t.oi:e.oi!==void 0&&t.od!==void 0?t.oi!==void 0?e.oi=t.oi:e.od!==void 0?delete e.oi:n.pop():t.lm!==void 0&&t.p[t.p.length-1]===t.lm||n.push(t);else(t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(is(t),is(e)),n.push(t)},tt.compose=function(n,t){tt.checkValidOp(n),tt.checkValidOp(t);for(var e=on(n),o=0;o<t.length;o++)tt.append(e,t[o]);return e},tt.normalize=function(n){var t=[];n=cc(n)?n:[n];for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=[]),tt.append(t,o)}return t},tt.commonLengthForOps=function(n,t){var e=n.p.length,o=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&o++,e===0)return-1;if(o===0)return null;e--,o--;for(var r=0;r<e;r++){var i=n.p[r];if(r>=o||i!==t.p[r])return null}return e},tt.canOpAffectPath=function(n,t){return tt.commonLengthForOps({p:t},n)!=null},tt.transformComponent=function(n,t,e,o){t=on(t);var r=tt.commonLengthForOps(e,t),i=tt.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,i!=null&&l>s&&t.p[i]==e.p[i]){if(t.ld!==void 0){var c=on(e);c.p=c.p.slice(s),t.ld=tt.apply(on(t.ld),[c])}else if(t.od!==void 0){var c=on(e);c.p=c.p.slice(s),t.od=tt.apply(on(t.od),[c])}}if(r!=null){var a=s==l,c=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(rs(t),c=on(e),rs(c)),c.t&&Wn[c.t]){if(t.t&&t.t===c.t){var u=Wn[t.t].transform(t.o,c.o,o);if(t.si!=null||t.sd!=null)for(var f=t.p,m=0;m<u.length;m++)t.o=[u[m]],t.p=f.slice(),is(t),tt.append(n,t);else(!cc(u)||u.length>0)&&(t.o=u,tt.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[r]===t.p[r])if(a){if(t.ld!==void 0)if(t.li!==void 0&&o==="left")t.ld=on(e.li);else return n}else return n}else if(e.li!==void 0)t.li!==void 0&&t.ld===void 0&&a&&t.p[r]===e.p[r]?o==="right"&&t.p[r]++:e.p[r]<=t.p[r]&&t.p[r]++,t.lm!==void 0&&a&&e.p[r]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&a){if(e.p[r]===t.p[r])return n;var f=e.p[r],C=t.p[r],v=t.lm;(f<v||f===v&&C<v)&&t.lm--}if(e.p[r]<t.p[r])t.p[r]--;else if(e.p[r]===t.p[r]){if(l<s)return n;if(t.ld!==void 0)if(t.li!==void 0)delete t.ld;else return n}}else if(e.lm!==void 0)if(t.lm!==void 0&&s===l){var C=t.p[r],v=t.lm,B=e.p[r],y=e.lm;if(B!==y)if(C===B)if(o==="left")t.p[r]=y,C===v&&(t.lm=y);else return n;else C>B&&t.p[r]--,C>y?t.p[r]++:C===y&&B>y&&(t.p[r]++,C===v&&t.lm++),(v>B||v===B&&v>C)&&t.lm--,v>y?t.lm++:v===y&&(y>B&&v>C||y<B&&v<C?o==="right"&&t.lm++:v>C?t.lm++:v===B&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&a){var C=e.p[r],v=e.lm;f=t.p[r],f>C&&t.p[r]--,f>v&&t.p[r]++}else{var C=e.p[r],v=e.lm;f=t.p[r],f===C?t.p[r]=v:(f>C&&t.p[r]--,(f>v||f===v&&C>v)&&t.p[r]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[r]===e.p[r])if(t.oi!==void 0&&a){if(o==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[r]===e.p[r])if(o==="left")tt.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[r]==e.p[r]){if(!a)return n;if(t.oi!==void 0)delete t.od;else return n}}}return tt.append(n,t),n},c2(tt,tt.transformComponent,tt.checkValidOp,tt.append);var fy=a2.exports;tt.registerSubtype(fy);var my=tt,gy={type:my};(function(n){n.defaultType=gy.type,n.map={},n.register=function(t){t.name&&(n.map[t.name]=t),t.uri&&(n.map[t.uri]=t)},n.register(n.defaultType)})(os);var rn={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var o in e)return!0;return!1},n.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e},n.isValidVersion=function(e){return e===null?!0:n.isInteger(e)&&e>=0},n.isValidTimestamp=function(e){return n.isValidVersion(e)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var e=arguments[0],o=1;o<arguments.length;o++){var r=arguments[o];e=e[r]||(o===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],o=arguments[arguments.length-1],r=1;r<arguments.length-1;r++){var i=arguments[r];e=e[i]||(e[i]=r===arguments.length-2?o():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],o=[e],r=1;r<arguments.length-1;r++){var i=arguments[r];if(!e.hasOwnProperty(i))break;e=e[i],o.push(e)}for(var r=o.length-1;r>=0;r--){var s=o[r],i=arguments[r+1],l=s[i];(r===o.length-1||!n.hasKeys(l))&&delete s[i]}},n.supportsPresence=function(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,o){var r=!1;return e.forEach(function(i){i&&(i(o),r=!0)}),r},n.truthy=function(e){return!!e},n.nextTick=function(e){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];setTimeout(function(){e.apply(null,o)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})(rn);var d2=Array.isArray,u2=Object.keys,py=Object.prototype.hasOwnProperty,Cy=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=d2(t),r=d2(e),i,s,l;if(o&&r){if(s=t.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!n(t[i],e[i]))return!1;return!0}if(o!=r)return!1;var c=t instanceof Date,a=e instanceof Date;if(c!=a)return!1;if(c&&a)return t.getTime()==e.getTime();var u=t instanceof RegExp,f=e instanceof RegExp;if(u!=f)return!1;if(u&&f)return t.toString()==e.toString();var m=u2(t);if(s=m.length,s!==u2(e).length)return!1;for(i=s;i--!==0;)if(!py.call(e,m[i]))return!1;for(i=s;i--!==0;)if(l=m[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},h2=fo,by=l2,Le=sc,ac=os,sn=rn,vy=sn.clone,ky=Cy,ye=Le.CODES,yy=lt;function lt(n,t,e){h2.EventEmitter.call(this),this.connection=n,this.collection=t,this.id=e,this.version=null,this.type=null,this.data=void 0,this.inflightFetch=[],this.inflightSubscribe=null,this.pendingFetch=[],this.pendingSubscribe=[],this.subscribed=!1,this.wantSubscribe=!1,this._wantsDestroy=!1,this.inflightOp=null,this.pendingOps=[],this.type=null,this.applyStack=null,this.preventCompose=!1,this.submitSource=!1,this.paused=!1,this._dataStateVersion=0}h2.mixin(lt),lt.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this;t.whenNothingPending(function(){t.wantSubscribe?t.unsubscribe(function(e){if(e)return n?n(e):t.emit("error",e);t.connection._destroyDoc(t),n&&n()}):(t.connection._destroyDoc(t),n&&n())})},lt.prototype._setType=function(n){if(typeof n=="string"&&(n=ac.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new Le(ye.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},lt.prototype._setData=function(n){this.data=n,this._dataStateVersion++},lt.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new Le(ye.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION,"Missing version in ingested snapshot. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}if(this.type||this.hasWritePending()){if(this.version==null){if(this.hasWritePending())return t&&this.once("no write pending",t);var e=new Le(ye.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}return n.v>this.version?this.fetch(t):t&&t()}if(this.version>n.v)return t&&t();this.version=n.v;var o=n.type===void 0?ac.defaultType:n.type;this._setType(o),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),t&&t()},lt.prototype.whenNothingPending=function(n){var t=this;sn.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},lt.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},lt.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},lt.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},lt.prototype._emitResponseError=function(n,t){if(n&&n.code===ye.ERR_SNAPSHOT_READ_SILENT_REJECTION){this.wantSubscribe=!1,t&&t(),this._emitNothingPending();return}if(t){t(n),this._emitNothingPending();return}this._emitNothingPending(),this.emit("error",n)},lt.prototype._handleFetch=function(n,t){var e=this.pendingFetch;this.pendingFetch=[];var o=this.inflightFetch.shift();if(o&&e.push(o),e.length&&(o=function(r){sn.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},lt.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var o=this.pendingFetch;this.pendingFetch=[],e.callback&&o.push(e.callback);var r;if(o.length&&(r=function(i){sn.callEach(o,i)}),n)return this._emitResponseError(n,r);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,r):r&&r(),this._emitNothingPending(),this._flushSubscribe()},lt.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===ye.ERR_OP_SUBMIT_REJECTED&&(n=null),this._rollback(n)):this.emit("error",n);if(this.inflightOp&&t.src===this.inflightOp.src&&t.seq===this.inflightOp.seq){this._opAcknowledged(t);return}if(this.version==null||t.v>this.version){this.fetch();return}if(!(t.v<this.version)){if(this.inflightOp){var e=dc(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=dc(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},lt.prototype._onConnectionStateChanged=function(){this.connection.canSend?(this.flush(),this._resubscribe()):(this.inflightOp&&(this.pendingOps.unshift(this.inflightOp),this.inflightOp=null),this.subscribed=!1,this.inflightSubscribe&&(this.inflightSubscribe.wantSubscribe?(this.pendingSubscribe.unshift(this.inflightSubscribe),this.inflightSubscribe=null):this._handleSubscribe()),this.inflightFetch.length&&(this.pendingFetch=this.pendingFetch.concat(this.inflightFetch),this.inflightFetch.length=0))},lt.prototype._resubscribe=function(){if(!this.pendingSubscribe.length&&this.wantSubscribe)return this.subscribe();var n=this.pendingSubscribe.some(function(t){return t.wantSubscribe});!n&&this.pendingFetch.length&&this.fetch(),this._flushSubscribe()},lt.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);wy(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},lt.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},lt.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},lt.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=e&&e.wantSubscribe===n;if(o){e.callback=By([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},lt.prototype._flushSubscribe=function(){if(!(this.inflightSubscribe||!this.pendingSubscribe.length)){if(this.connection.canSend){this.inflightSubscribe=this.pendingSubscribe.shift(),this.wantSubscribe=this.inflightSubscribe.wantSubscribe,this.wantSubscribe?this.connection.sendSubscribe(this):(this.subscribed=!1,this.connection.sendUnsubscribe(this));return}if(!this.pendingSubscribe[0].wantSubscribe){this.inflightSubscribe=this.pendingSubscribe.shift();var n=this;sn.nextTick(function(){n._handleSubscribe()})}}};function wy(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function By(n){return n=n.filter(sn.truthy),n.length?function(t){sn.callEach(n,t)}:null}lt.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function Ey(n){delete n.op,delete n.create,delete n.del}function dc(n,t){if(n.del)return Ey(t);if(t.del)return new Le(ye.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new Le(ye.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new Le(ye.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var e=n.type.transformX(n.op,t.op);n.op=e[0],t.op=e[1]}else{var o=n.type.transform(n.op,t.op,"left"),r=n.type.transform(t.op,n.op,"right");n.op=o,t.op=r}}}lt.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new Le(ye.ERR_DOC_DOES_NOT_EXIST,"Cannot apply op to uncreated document. "+this.collection+"."+this.id);if(this.emit("before op batch",n.op,t),!t&&this.type===ac.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,o=0;o<n.op.length;o++){var r=n.op[o],i={op:[r]};this.emit("before op",i.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=dc(this.applyStack[s],i);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,i.op)),this.emit("op",i.op,t,n.src)}this.emit("op batch",n.op,t),this._popApplyStack(e);return}this.emit("before op",n.op,t,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,t,n.src),this.emit("op batch",n.op,t);return}if(n.create){this._setType(n.create.type),this.type.deserialize?this.type.createDeserialized?this._setData(this.type.createDeserialized(n.create.data)):this._setData(this.type.deserialize(this.type.create(n.create.data))):this._setData(this.type.create(n.create.data)),this.emit("create",t);return}if(n.del){var c=this.data;this._setType(null),this.emit("del",c,t);return}},lt.prototype._sendOp=function(){if(!!this.connection.canSend){var n=this.connection.id;this.inflightOp||(this.inflightOp=this.pendingOps.shift());var t=this.inflightOp;if(!t){var e=new Le(ye.ERR_INFLIGHT_OP_MISSING,"No op to send on call to _sendOp");return this.emit("error",e)}if(t.sentAt=Date.now(),t.retries=t.retries==null?0:t.retries+1,t.seq==null){if(this.connection.seq>=sn.MAX_SAFE_INTEGER)return this.emit("error",new Le(ye.ERR_CONNECTION_SEQ_INTEGER_OVERFLOW,"Connection seq has exceeded the max safe integer, maybe from being open for too long"));t.seq=this.connection.seq++}this.connection.sendOp(this,t),t.src==null&&(t.src=n)}},lt.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var o=new Le(ye.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return e?e(o):this.emit("error",o)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(i){return this._hardRollback(i)}var r=this;sn.nextTick(function(){r.flush()})},lt.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var o=this._tryCompose(n);if(o){o.callbacks.push(e);return}}n.type=this.type,n.callbacks=[e],this.pendingOps.push(n)},lt.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var t=this.applyStack[0];if(this.applyStack=null,!!t){var e=this.pendingOps.indexOf(t);if(e!==-1)for(var o=this.pendingOps.splice(e),e=0;e<o.length;e++){var t=o[e],r=this._tryCompose(t);r?r.callbacks=r.callbacks.concat(t.callbacks):this.pendingOps.push(t)}}},lt.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!ky(n.source,t.source))){if(t.create&&"op"in n)return t.create.data=this.type.apply(t.create.data,n.op),t;if("op"in t&&"op"in n&&this.type.compose)return t.op=this.type.compose(t.op,n.op),t}}},lt.prototype.submitOp=function(n,t,e){typeof t=="function"&&(e=t,t=null);var o={op:n},r=t&&t.source;this._submit(o,r,e)},lt.prototype.create=function(n,t,e,o){if(typeof t=="function"?(o=t,e=null,t=null):typeof e=="function"&&(o=e,e=null),t||(t=ac.defaultType.uri),this.type){var r=new Le(ye.ERR_DOC_ALREADY_CREATED,"Document already exists");return o?o(r):this.emit("error",r)}var i={create:{type:t,data:n}},s=e&&e.source;this._submit(i,s,o)},lt.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new Le(ye.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var o={del:!0},r=n&&n.source;this._submit(o,r,t)},lt.prototype.pause=function(){this.paused=!0},lt.prototype.resume=function(){this.paused=!1,this.flush()},lt.prototype.toSnapshot=function(){return{v:this.version,data:vy(this.data),type:this.type.uri}},lt.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return by.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},lt.prototype._rollback=function(n){var t=this.inflightOp;if("op"in t&&t.type.invert){try{t.op=t.type.invert(t.op)}catch{return this._hardRollback(n)}for(var e=0;e<this.pendingOps.length;e++){var o=dc(this.pendingOps[e],t);if(o)return this._hardRollback(o)}try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}this._clearInflightOp(n);return}this._hardRollback(n)},lt.prototype._hardRollback=function(n){var t=[];this.inflightOp&&t.push(this.inflightOp),t=t.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var e=this;this.fetch(function(){for(var o=!!t.length,r=0;r<t.length;r++)o=sn.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},lt.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=sn.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var Xo={};Xo.ACTIONS={initLegacy:"init",handshake:"hs",queryFetch:"qf",querySubscribe:"qs",queryUnsubscribe:"qu",queryUpdate:"q",bulkFetch:"bf",bulkSubscribe:"bs",bulkUnsubscribe:"bu",fetch:"f",subscribe:"s",unsubscribe:"u",op:"op",snapshotFetch:"nf",snapshotFetchByTimestamp:"nt",pingPong:"pp",presence:"p",presenceSubscribe:"ps",presenceUnsubscribe:"pu",presenceRequest:"pr"};var f2=fo,m2=Xo.ACTIONS,Iy=rn,xy=we;function we(n,t,e,o,r,i,s){f2.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,this.collection=o,this.query=r,this.results=null,i&&i.results&&(this.results=i.results,delete i.results),this.extra=void 0,this.options=i,this.callback=s,this.ready=!1,this.sent=!1}f2.mixin(we),we.prototype.hasPending=function(){return!this.ready},we.prototype.send=function(){if(!!this.connection.canSend){var n={a:this.action,id:this.id,c:this.collection,q:this.query};if(this.options&&(n.o=this.options),this.results){for(var t=[],e=0;e<this.results.length;e++){var o=this.results[e];t.push([o.id,o.version])}n.r=t}this.connection.send(n),this.sent=!0}},we.prototype.destroy=function(n){this.connection.canSend&&this.action===m2.querySubscribe&&this.connection.send({a:m2.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&Iy.nextTick(n)},we.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},we.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},we.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},we.prototype._handleResponse=function(n,t,e){var o=this.callback;if(this.callback=null,n)return this._finishResponse(n,o);if(!t)return this._finishResponse(null,o);var r=this,i=1,s=function(u){if(u)return r._finishResponse(u,o);--i||r._finishResponse(null,o)};if(Array.isArray(t))i+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){i++;var c=t[l],a=this.connection.get(c.c||this.collection,l);a.ingestSnapshot(c,s)}s()},we.prototype._ingestSnapshots=function(n,t){for(var e=[],o=0;o<n.length;o++){var r=n[o],i=this.connection.get(r.c||this.collection,r.d);i.ingestSnapshot(r,t),e.push(i)}return e},we.prototype._finishResponse=function(n,t){if(this.emit("ready"),this.ready=!0,n)return this.connection._destroyQuery(this),t?t(n):this.emit("error",n);t&&t(null,this.results,this.extra)},we.prototype._handleError=function(n){this.emit("error",n)},we.prototype._handleDiff=function(n){for(var t=0;t<n.length;t++){var e=n[t];e.type==="insert"&&(e.values=this._ingestSnapshots(e.values))}for(var t=0;t<n.length;t++){var e=n[t];switch(e.type){case"insert":var o=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(o)),this.emit("insert",o,e.index);break;case"remove":var i=e.howMany||1,r=this.results.splice(e.index,i);this.emit("remove",r,e.index);break;case"move":var i=e.howMany||1,s=this.results.splice(e.from,i);Array.prototype.splice.apply(this.results,[e.to,0].concat(s)),this.emit("move",s,e.from,e.to);break}}this.emit("changed",this.results)},we.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var g2=fo,Ty=Xo.ACTIONS,Sy=rn,p2=Bn;function Bn(n,t){if(g2.EventEmitter.call(this),!t||typeof t!="string")throw new Error("LocalPresence presenceId must be a string");this.presence=n,this.presenceId=t,this.connection=n.connection,this.presenceVersion=0,this.value=null,this._pendingMessages=[],this._callbacksByPresenceVersion={}}g2.mixin(Bn),Bn.prototype.submit=function(n,t){this.value=n,this.send(t)},Bn.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},Bn.prototype.destroy=function(n){var t=this;this.submit(null,function(e){if(e)return t._callbackOrEmit(e,n);delete t.presence.localPresences[t.presenceId],n&&n()})},Bn.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},Bn.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},Bn.prototype._message=function(){return{a:Ty.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},Bn.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},Bn.prototype._callbackOrEmit=function(n,t){if(t)return Sy.nextTick(t,n);n&&this.emit("error",n)};var Dy=rn,C2=Pu;function Pu(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}Pu.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},Pu.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&Dy.nextTick(n)};var ju={exports:{}};(function(n,t){(function(e,o){o(t)})(ns,function(e){function o(p,k){k=k|0;for(var E=Math.max(p.length-k,0),x=Array(E),L=0;L<E;L++)x[L]=p[k+L];return x}var r=function(p){var k=o(arguments,1);return function(){var E=o(arguments);return p.apply(null,k.concat(E))}},i=function(p){return function(){var k=o(arguments),E=k.pop();p.call(this,k,E)}};function s(p){var k=typeof p;return p!=null&&(k=="object"||k=="function")}var l=typeof setImmediate=="function"&&setImmediate,c=typeof process=="object"&&typeof process.nextTick=="function";function a(p){setTimeout(p,0)}function u(p){return function(k){var E=o(arguments,1);p(function(){k.apply(null,E)})}}var f;l?f=setImmediate:c?f=process.nextTick:f=a;var m=u(f);function C(p){return i(function(k,E){var x;try{x=p.apply(this,k)}catch(L){return E(L)}s(x)&&typeof x.then=="function"?x.then(function(L){v(E,null,L)},function(L){v(E,L.message?L:new Error(L))}):E(null,x)})}function v(p,k,E){try{p(k,E)}catch(x){m(B,x)}}function B(p){throw p}var y=typeof Symbol=="function";function S(p){return y&&p[Symbol.toStringTag]==="AsyncFunction"}function I(p){return S(p)?C(p):p}function M(p){return function(k){var E=o(arguments,1),x=i(function(L,D){var O=this;return p(k,function(_,V){I(_).apply(O,L.concat(V))},D)});return E.length?x.apply(this,E):x}}var R=typeof ns=="object"&&ns&&ns.Object===Object&&ns,$=typeof self=="object"&&self&&self.Object===Object&&self,Z=R||$||Function("return this")(),ot=Z.Symbol,st=Object.prototype,mt=st.hasOwnProperty,ut=st.toString,yt=ot?ot.toStringTag:void 0;function se(p){var k=mt.call(p,yt),E=p[yt];try{p[yt]=void 0;var x=!0}catch{}var L=ut.call(p);return x&&(k?p[yt]=E:delete p[yt]),L}var eo=Object.prototype,ee=eo.toString;function Ue(p){return ee.call(p)}var Eo="[object Null]",gr="[object Undefined]",pr=ot?ot.toStringTag:void 0;function Io(p){return p==null?p===void 0?gr:Eo:pr&&pr in Object(p)?se(p):Ue(p)}var ya="[object AsyncFunction]",LP="[object Function]",MP="[object GeneratorFunction]",RP="[object Proxy]";function AP(p){if(!s(p))return!1;var k=Io(p);return k==LP||k==MP||k==ya||k==RP}var OP=9007199254740991;function SC(p){return typeof p=="number"&&p>-1&&p%1==0&&p<=OP}function Ks(p){return p!=null&&SC(p.length)&&!AP(p)}var If={};function ht(){}function xo(p){return function(){if(p!==null){var k=p;p=null,k.apply(this,arguments)}}}var xf=typeof Symbol=="function"&&Symbol.iterator,_P=function(p){return xf&&p[xf]&&p[xf]()};function NP(p,k){for(var E=-1,x=Array(p);++E<p;)x[E]=k(E);return x}function wa(p){return p!=null&&typeof p=="object"}var $P="[object Arguments]";function DC(p){return wa(p)&&Io(p)==$P}var LC=Object.prototype,PP=LC.hasOwnProperty,jP=LC.propertyIsEnumerable,HP=DC(function(){return arguments}())?DC:function(p){return wa(p)&&PP.call(p,"callee")&&!jP.call(p,"callee")},gn=Array.isArray;function FP(){return!1}var MC=typeof e=="object"&&e&&!e.nodeType&&e,RC=MC&&!0&&n&&!n.nodeType&&n,zP=RC&&RC.exports===MC,AC=zP?Z.Buffer:void 0,UP=AC?AC.isBuffer:void 0,VP=UP||FP,qP=9007199254740991,WP=/^(?:0|[1-9]\d*)$/;function GP(p,k){var E=typeof p;return k=k==null?qP:k,!!k&&(E=="number"||E!="symbol"&&WP.test(p))&&p>-1&&p%1==0&&p<k}var ZP="[object Arguments]",YP="[object Array]",QP="[object Boolean]",KP="[object Date]",JP="[object Error]",XP="[object Function]",tj="[object Map]",ej="[object Number]",nj="[object Object]",oj="[object RegExp]",rj="[object Set]",ij="[object String]",sj="[object WeakMap]",lj="[object ArrayBuffer]",cj="[object DataView]",aj="[object Float32Array]",dj="[object Float64Array]",uj="[object Int8Array]",hj="[object Int16Array]",fj="[object Int32Array]",mj="[object Uint8Array]",gj="[object Uint8ClampedArray]",pj="[object Uint16Array]",Cj="[object Uint32Array]",Bt={};Bt[aj]=Bt[dj]=Bt[uj]=Bt[hj]=Bt[fj]=Bt[mj]=Bt[gj]=Bt[pj]=Bt[Cj]=!0,Bt[ZP]=Bt[YP]=Bt[lj]=Bt[QP]=Bt[cj]=Bt[KP]=Bt[JP]=Bt[XP]=Bt[tj]=Bt[ej]=Bt[nj]=Bt[oj]=Bt[rj]=Bt[ij]=Bt[sj]=!1;function bj(p){return wa(p)&&SC(p.length)&&!!Bt[Io(p)]}function vj(p){return function(k){return p(k)}}var OC=typeof e=="object"&&e&&!e.nodeType&&e,Js=OC&&!0&&n&&!n.nodeType&&n,kj=Js&&Js.exports===OC,Tf=kj&&R.process,_C=function(){try{var p=Js&&Js.require&&Js.require("util").types;return p||Tf&&Tf.binding&&Tf.binding("util")}catch{}}(),NC=_C&&_C.isTypedArray,yj=NC?vj(NC):bj,wj=Object.prototype,Bj=wj.hasOwnProperty;function Ej(p,k){var E=gn(p),x=!E&&HP(p),L=!E&&!x&&VP(p),D=!E&&!x&&!L&&yj(p),O=E||x||L||D,_=O?NP(p.length,String):[],V=_.length;for(var Q in p)(k||Bj.call(p,Q))&&!(O&&(Q=="length"||L&&(Q=="offset"||Q=="parent")||D&&(Q=="buffer"||Q=="byteLength"||Q=="byteOffset")||GP(Q,V)))&&_.push(Q);return _}var Ij=Object.prototype;function xj(p){var k=p&&p.constructor,E=typeof k=="function"&&k.prototype||Ij;return p===E}function Tj(p,k){return function(E){return p(k(E))}}var Sj=Tj(Object.keys,Object),Dj=Object.prototype,Lj=Dj.hasOwnProperty;function Mj(p){if(!xj(p))return Sj(p);var k=[];for(var E in Object(p))Lj.call(p,E)&&E!="constructor"&&k.push(E);return k}function Sf(p){return Ks(p)?Ej(p):Mj(p)}function Rj(p){var k=-1,E=p.length;return function(){return++k<E?{value:p[k],key:k}:null}}function Aj(p){var k=-1;return function(){var x=p.next();return x.done?null:(k++,{value:x.value,key:k})}}function Oj(p){var k=Sf(p),E=-1,x=k.length;return function L(){var D=k[++E];return D==="__proto__"?L():E<x?{value:p[D],key:D}:null}}function _j(p){if(Ks(p))return Rj(p);var k=_P(p);return k?Aj(k):Oj(p)}function An(p){return function(){if(p===null)throw new Error("Callback was already called.");var k=p;p=null,k.apply(this,arguments)}}function Ba(p){return function(k,E,x){if(x=xo(x||ht),p<=0||!k)return x(null);var L=_j(k),D=!1,O=0,_=!1;function V(G,X){if(O-=1,G)D=!0,x(G);else{if(X===If||D&&O<=0)return D=!0,x(null);_||Q()}}function Q(){for(_=!0;O<p&&!D;){var G=L();if(G===null){D=!0,O<=0&&x(null);return}O+=1,E(G.value,G.key,An(V))}_=!1}Q()}}function Cr(p,k,E,x){Ba(k)(p,I(E),x)}function ne(p,k){return function(E,x,L){return p(E,k,x,L)}}function Nj(p,k,E){E=xo(E||ht);var x=0,L=0,D=p.length;D===0&&E(null);function O(_,V){_?E(_):(++L===D||V===If)&&E(null)}for(;x<D;x++)k(p[x],x,An(O))}var $j=ne(Cr,1/0),To=function(p,k,E){var x=Ks(p)?Nj:$j;x(p,I(k),E)};function pi(p){return function(k,E,x){return p(To,k,I(E),x)}}function $C(p,k,E,x){x=x||ht,k=k||[];var L=[],D=0,O=I(E);p(k,function(_,V,Q){var G=D++;O(_,function(X,Et){L[G]=Et,Q(X)})},function(_){x(_,L)})}var Ea=pi($C),PC=M(Ea);function Ci(p){return function(k,E,x,L){return p(Ba(E),k,I(x),L)}}var bi=Ci($C),Df=ne(bi,1),jC=M(Df);function Ia(p,k){for(var E=-1,x=p==null?0:p.length;++E<x&&k(p[E],E,p)!==!1;);return p}function Pj(p){return function(k,E,x){for(var L=-1,D=Object(k),O=x(k),_=O.length;_--;){var V=O[p?_:++L];if(E(D[V],V,D)===!1)break}return k}}var jj=Pj();function Xs(p,k){return p&&jj(p,k,Sf)}function Hj(p,k,E,x){for(var L=p.length,D=E+(x?1:-1);x?D--:++D<L;)if(k(p[D],D,p))return D;return-1}function Fj(p){return p!==p}function zj(p,k,E){for(var x=E-1,L=p.length;++x<L;)if(p[x]===k)return x;return-1}function xa(p,k,E){return k===k?zj(p,k,E):Hj(p,Fj,E)}var Lf=function(p,k,E){typeof k=="function"&&(E=k,k=null),E=xo(E||ht);var x=Sf(p),L=x.length;if(!L)return E(null);k||(k=L);var D={},O=0,_=!1,V=Object.create(null),Q=[],G=[],X={};Xs(p,function(Dt,Lt){if(!gn(Dt)){Et(Lt,[Dt]),G.push(Lt);return}var Jt=Dt.slice(0,Dt.length-1),no=Jt.length;if(no===0){Et(Lt,Dt),G.push(Lt);return}X[Lt]=no,Ia(Jt,function(wi){if(!p[wi])throw new Error("async.auto task `"+Lt+"` has a non-existent dependency `"+wi+"` in "+Jt.join(", "));On(wi,function(){no--,no===0&&Et(Lt,Dt)})})}),OH(),le();function Et(Dt,Lt){Q.push(function(){_n(Dt,Lt)})}function le(){if(Q.length===0&&O===0)return E(null,D);for(;Q.length&&O<k;){var Dt=Q.shift();Dt()}}function On(Dt,Lt){var Jt=V[Dt];Jt||(Jt=V[Dt]=[]),Jt.push(Lt)}function Ve(Dt){var Lt=V[Dt]||[];Ia(Lt,function(Jt){Jt()}),le()}function _n(Dt,Lt){if(!_){var Jt=An(function(wi,zf){if(O--,arguments.length>2&&(zf=o(arguments,1)),wi){var Uf={};Xs(D,function(NH,$H){Uf[$H]=NH}),Uf[Dt]=zf,_=!0,V=Object.create(null),E(wi,Uf)}else D[Dt]=zf,Ve(Dt)});O++;var no=I(Lt[Lt.length-1]);Lt.length>1?no(D,Jt):no(Jt)}}function OH(){for(var Dt,Lt=0;G.length;)Dt=G.pop(),Lt++,Ia(_H(Dt),function(Jt){--X[Jt]===0&&G.push(Jt)});if(Lt!==L)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function _H(Dt){var Lt=[];return Xs(p,function(Jt,no){gn(Jt)&&xa(Jt,Dt,0)>=0&&Lt.push(no)}),Lt}};function vi(p,k){for(var E=-1,x=p==null?0:p.length,L=Array(x);++E<x;)L[E]=k(p[E],E,p);return L}var Uj="[object Symbol]";function Vj(p){return typeof p=="symbol"||wa(p)&&Io(p)==Uj}var qj=1/0,HC=ot?ot.prototype:void 0,FC=HC?HC.toString:void 0;function Mf(p){if(typeof p=="string")return p;if(gn(p))return vi(p,Mf)+"";if(Vj(p))return FC?FC.call(p):"";var k=p+"";return k=="0"&&1/p==-qj?"-0":k}function Wj(p,k,E){var x=-1,L=p.length;k<0&&(k=-k>L?0:L+k),E=E>L?L:E,E<0&&(E+=L),L=k>E?0:E-k>>>0,k>>>=0;for(var D=Array(L);++x<L;)D[x]=p[x+k];return D}function Gj(p,k,E){var x=p.length;return E=E===void 0?x:E,!k&&E>=x?p:Wj(p,k,E)}function Zj(p,k){for(var E=p.length;E--&&xa(k,p[E],0)>-1;);return E}function Yj(p,k){for(var E=-1,x=p.length;++E<x&&xa(k,p[E],0)>-1;);return E}function Qj(p){return p.split("")}var Kj="\\ud800-\\udfff",Jj="\\u0300-\\u036f",Xj="\\ufe20-\\ufe2f",tH="\\u20d0-\\u20ff",eH=Jj+Xj+tH,nH="\\ufe0e\\ufe0f",oH="\\u200d",rH=RegExp("["+oH+Kj+eH+nH+"]");function iH(p){return rH.test(p)}var zC="\\ud800-\\udfff",sH="\\u0300-\\u036f",lH="\\ufe20-\\ufe2f",cH="\\u20d0-\\u20ff",aH=sH+lH+cH,dH="\\ufe0e\\ufe0f",uH="["+zC+"]",Rf="["+aH+"]",Af="\\ud83c[\\udffb-\\udfff]",hH="(?:"+Rf+"|"+Af+")",UC="[^"+zC+"]",VC="(?:\\ud83c[\\udde6-\\uddff]){2}",qC="[\\ud800-\\udbff][\\udc00-\\udfff]",fH="\\u200d",WC=hH+"?",GC="["+dH+"]?",mH="(?:"+fH+"(?:"+[UC,VC,qC].join("|")+")"+GC+WC+")*",gH=GC+WC+mH,pH="(?:"+[UC+Rf+"?",Rf,VC,qC,uH].join("|")+")",CH=RegExp(Af+"(?="+Af+")|"+pH+gH,"g");function bH(p){return p.match(CH)||[]}function ZC(p){return iH(p)?bH(p):Qj(p)}function vH(p){return p==null?"":Mf(p)}var kH=/^\s+|\s+$/g;function yH(p,k,E){if(p=vH(p),p&&(E||k===void 0))return p.replace(kH,"");if(!p||!(k=Mf(k)))return p;var x=ZC(p),L=ZC(k),D=Yj(x,L),O=Zj(x,L)+1;return Gj(x,D,O).join("")}var wH=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,BH=/,/,EH=/(=.+)?(\s*)$/,IH=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function xH(p){return p=p.toString().replace(IH,""),p=p.match(wH)[2].replace(" ",""),p=p?p.split(BH):[],p=p.map(function(k){return yH(k.replace(EH,""))}),p}function YC(p,k){var E={};Xs(p,function(x,L){var D,O=S(x),_=!O&&x.length===1||O&&x.length===0;if(gn(x))D=x.slice(0,-1),x=x[x.length-1],E[L]=D.concat(D.length>0?V:x);else if(_)E[L]=x;else{if(D=xH(x),x.length===0&&!O&&D.length===0)throw new Error("autoInject task functions require explicit parameters.");O||D.pop(),E[L]=D.concat(V)}function V(Q,G){var X=vi(D,function(Et){return Q[Et]});X.push(G),I(x).apply(null,X)}}),Lf(E,k)}function pn(){this.head=this.tail=null,this.length=0}function QC(p,k){p.length=1,p.head=p.tail=k}pn.prototype.removeLink=function(p){return p.prev?p.prev.next=p.next:this.head=p.next,p.next?p.next.prev=p.prev:this.tail=p.prev,p.prev=p.next=null,this.length-=1,p},pn.prototype.empty=function(){for(;this.head;)this.shift();return this},pn.prototype.insertAfter=function(p,k){k.prev=p,k.next=p.next,p.next?p.next.prev=k:this.tail=k,p.next=k,this.length+=1},pn.prototype.insertBefore=function(p,k){k.prev=p.prev,k.next=p,p.prev?p.prev.next=k:this.head=k,p.prev=k,this.length+=1},pn.prototype.unshift=function(p){this.head?this.insertBefore(this.head,p):QC(this,p)},pn.prototype.push=function(p){this.tail?this.insertAfter(this.tail,p):QC(this,p)},pn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},pn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},pn.prototype.toArray=function(){for(var p=Array(this.length),k=this.head,E=0;E<this.length;E++)p[E]=k.data,k=k.next;return p},pn.prototype.remove=function(p){for(var k=this.head;k;){var E=k.next;p(k)&&this.removeLink(k),k=E}return this};function KC(p,k,E){if(k==null)k=1;else if(k===0)throw new Error("Concurrency must not be zero");var x=I(p),L=0,D=[],O=!1;function _(X,Et,le){if(le!=null&&typeof le!="function")throw new Error("task callback must be a function");if(G.started=!0,gn(X)||(X=[X]),X.length===0&&G.idle())return m(function(){G.drain()});for(var On=0,Ve=X.length;On<Ve;On++){var _n={data:X[On],callback:le||ht};Et?G._tasks.unshift(_n):G._tasks.push(_n)}O||(O=!0,m(function(){O=!1,G.process()}))}function V(X){return function(Et){L-=1;for(var le=0,On=X.length;le<On;le++){var Ve=X[le],_n=xa(D,Ve,0);_n===0?D.shift():_n>0&&D.splice(_n,1),Ve.callback.apply(Ve,arguments),Et!=null&&G.error(Et,Ve.data)}L<=G.concurrency-G.buffer&&G.unsaturated(),G.idle()&&G.drain(),G.process()}}var Q=!1,G={_tasks:new pn,concurrency:k,payload:E,saturated:ht,unsaturated:ht,buffer:k/4,empty:ht,drain:ht,error:ht,started:!1,paused:!1,push:function(X,Et){_(X,!1,Et)},kill:function(){G.drain=ht,G._tasks.empty()},unshift:function(X,Et){_(X,!0,Et)},remove:function(X){G._tasks.remove(X)},process:function(){if(!Q){for(Q=!0;!G.paused&&L<G.concurrency&&G._tasks.length;){var X=[],Et=[],le=G._tasks.length;G.payload&&(le=Math.min(le,G.payload));for(var On=0;On<le;On++){var Ve=G._tasks.shift();X.push(Ve),D.push(Ve),Et.push(Ve.data)}L+=1,G._tasks.length===0&&G.empty(),L===G.concurrency&&G.saturated();var _n=An(V(X));x(Et,_n)}Q=!1}},length:function(){return G._tasks.length},running:function(){return L},workersList:function(){return D},idle:function(){return G._tasks.length+L===0},pause:function(){G.paused=!0},resume:function(){G.paused!==!1&&(G.paused=!1,m(G.process))}};return G}function JC(p,k){return KC(p,1,k)}var ki=ne(Cr,1);function So(p,k,E,x){x=xo(x||ht);var L=I(E);ki(p,function(D,O,_){L(k,D,function(V,Q){k=Q,_(V)})},function(D){x(D,k)})}function Of(){var p=vi(arguments,I);return function(){var k=o(arguments),E=this,x=k[k.length-1];typeof x=="function"?k.pop():x=ht,So(p,k,function(L,D,O){D.apply(E,L.concat(function(_){var V=o(arguments,1);O(_,V)}))},function(L,D){x.apply(E,[L].concat(D))})}}var XC=function(){return Of.apply(null,o(arguments).reverse())},TH=Array.prototype.concat,Ta=function(p,k,E,x){x=x||ht;var L=I(E);bi(p,k,function(D,O){L(D,function(_){return _?O(_):O(null,o(arguments,1))})},function(D,O){for(var _=[],V=0;V<O.length;V++)O[V]&&(_=TH.apply(_,O[V]));return x(D,_)})},t9=ne(Ta,1/0),e9=ne(Ta,1),n9=function(){var p=o(arguments),k=[null].concat(p);return function(){var E=arguments[arguments.length-1];return E.apply(this,k)}};function tl(p){return p}function yi(p,k){return function(E,x,L,D){D=D||ht;var O=!1,_;E(x,function(V,Q,G){L(V,function(X,Et){X?G(X):p(Et)&&!_?(O=!0,_=k(!0,V),G(null,If)):G()})},function(V){V?D(V):D(null,O?_:k(!1))})}}function o9(p,k){return k}var Sa=pi(yi(tl,o9)),el=Ci(yi(tl,o9)),Da=ne(el,1);function r9(p){return function(k){var E=o(arguments,1);E.push(function(x){var L=o(arguments,1);typeof console=="object"&&(x?console.error&&console.error(x):console[p]&&Ia(L,function(D){console[p](D)}))}),I(k).apply(null,E)}}var i9=r9("dir");function s9(p,k,E){E=An(E||ht);var x=I(p),L=I(k);function D(_){if(_)return E(_);var V=o(arguments,1);V.push(O),L.apply(this,V)}function O(_,V){if(_)return E(_);if(!V)return E(null);x(D)}O(null,!0)}function _f(p,k,E){E=An(E||ht);var x=I(p),L=function(D){if(D)return E(D);var O=o(arguments,1);if(k.apply(this,O))return x(L);E.apply(null,[null].concat(O))};x(L)}function l9(p,k,E){_f(p,function(){return!k.apply(this,arguments)},E)}function c9(p,k,E){E=An(E||ht);var x=I(k),L=I(p);function D(_){if(_)return E(_);L(O)}function O(_,V){if(_)return E(_);if(!V)return E(null);x(D)}L(O)}function a9(p){return function(k,E,x){return p(k,x)}}function La(p,k,E){To(p,a9(I(k)),E)}function nl(p,k,E,x){Ba(k)(p,a9(I(E)),x)}var ol=ne(nl,1);function Nf(p){return S(p)?p:i(function(k,E){var x=!0;k.push(function(){var L=arguments;x?m(function(){E.apply(null,L)}):E.apply(null,L)}),p.apply(this,k),x=!1})}function Ma(p){return!p}var Ra=pi(yi(Ma,Ma)),rl=Ci(yi(Ma,Ma)),Aa=ne(rl,1);function d9(p){return function(k){return k==null?void 0:k[p]}}function SH(p,k,E,x){var L=new Array(k.length);p(k,function(D,O,_){E(D,function(V,Q){L[O]=!!Q,_(V)})},function(D){if(D)return x(D);for(var O=[],_=0;_<k.length;_++)L[_]&&O.push(k[_]);x(null,O)})}function DH(p,k,E,x){var L=[];p(k,function(D,O,_){E(D,function(V,Q){V?_(V):(Q&&L.push({index:O,value:D}),_())})},function(D){D?x(D):x(null,vi(L.sort(function(O,_){return O.index-_.index}),d9("value")))})}function $f(p,k,E,x){var L=Ks(k)?SH:DH;L(p,k,I(E),x||ht)}var Oa=pi($f),il=Ci($f),_a=ne(il,1);function u9(p,k){var E=An(k||ht),x=I(Nf(p));function L(D){if(D)return E(D);x(L)}L()}var Na=function(p,k,E,x){x=x||ht;var L=I(E);bi(p,k,function(D,O){L(D,function(_,V){return _?O(_):O(null,{key:V,val:D})})},function(D,O){for(var _={},V=Object.prototype.hasOwnProperty,Q=0;Q<O.length;Q++)if(O[Q]){var G=O[Q].key,X=O[Q].val;V.call(_,G)?_[G].push(X):_[G]=[X]}return x(D,_)})},h9=ne(Na,1/0),f9=ne(Na,1),m9=r9("log");function $a(p,k,E,x){x=xo(x||ht);var L={},D=I(E);Cr(p,k,function(O,_,V){D(O,_,function(Q,G){if(Q)return V(Q);L[_]=G,V()})},function(O){x(O,L)})}var g9=ne($a,1/0),p9=ne($a,1);function C9(p,k){return k in p}function b9(p,k){var E=Object.create(null),x=Object.create(null);k=k||tl;var L=I(p),D=i(function(_,V){var Q=k.apply(null,_);C9(E,Q)?m(function(){V.apply(null,E[Q])}):C9(x,Q)?x[Q].push(V):(x[Q]=[V],L.apply(null,_.concat(function(){var G=o(arguments);E[Q]=G;var X=x[Q];delete x[Q];for(var Et=0,le=X.length;Et<le;Et++)X[Et].apply(null,G)})))});return D.memo=E,D.unmemoized=p,D}var Pa;c?Pa=process.nextTick:l?Pa=setImmediate:Pa=a;var v9=u(Pa);function Pf(p,k,E){E=E||ht;var x=Ks(k)?[]:{};p(k,function(L,D,O){I(L)(function(_,V){arguments.length>2&&(V=o(arguments,1)),x[D]=V,O(_)})},function(L){E(L,x)})}function k9(p,k){Pf(To,p,k)}function y9(p,k,E){Pf(Ba(k),p,E)}var jf=function(p,k){var E=I(p);return KC(function(x,L){E(x[0],L)},k,1)},w9=function(p,k){var E=jf(p,k);return E.push=function(x,L,D){if(D==null&&(D=ht),typeof D!="function")throw new Error("task callback must be a function");if(E.started=!0,gn(x)||(x=[x]),x.length===0)return m(function(){E.drain()});L=L||0;for(var O=E._tasks.head;O&&L>=O.priority;)O=O.next;for(var _=0,V=x.length;_<V;_++){var Q={data:x[_],priority:L,callback:D};O?E._tasks.insertBefore(O,Q):E._tasks.push(Q)}m(E.process)},delete E.unshift,E};function B9(p,k){if(k=xo(k||ht),!gn(p))return k(new TypeError("First argument to race must be an array of functions"));if(!p.length)return k();for(var E=0,x=p.length;E<x;E++)I(p[E])(k)}function ja(p,k,E,x){var L=o(p).reverse();So(L,k,E,x)}function Ha(p){var k=I(p);return i(function(x,L){return x.push(function(O,_){if(O)L(null,{error:O});else{var V;arguments.length<=2?V=_:V=o(arguments,1),L(null,{value:V})}}),k.apply(this,x)})}function E9(p){var k;return gn(p)?k=vi(p,Ha):(k={},Xs(p,function(E,x){k[x]=Ha.call(this,E)})),k}function I9(p,k,E,x){$f(p,k,function(L,D){E(L,function(O,_){D(O,!_)})},x)}var x9=pi(I9),Hf=Ci(I9),T9=ne(Hf,1);function S9(p){return function(){return p}}function Fa(p,k,E){var x=5,L=0,D={times:x,intervalFunc:S9(L)};function O(G,X){if(typeof X=="object")G.times=+X.times||x,G.intervalFunc=typeof X.interval=="function"?X.interval:S9(+X.interval||L),G.errorFilter=X.errorFilter;else if(typeof X=="number"||typeof X=="string")G.times=+X||x;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof p=="function"?(E=k||ht,k=p):(O(D,p),E=E||ht),typeof k!="function")throw new Error("Invalid arguments for async.retry");var _=I(k),V=1;function Q(){_(function(G){G&&V++<D.times&&(typeof D.errorFilter!="function"||D.errorFilter(G))?setTimeout(Q,D.intervalFunc(V)):E.apply(null,arguments)})}Q()}var D9=function(p,k){k||(k=p,p=null);var E=I(k);return i(function(x,L){function D(O){E.apply(null,x.concat(O))}p?Fa(p,D,L):Fa(D,L)})};function L9(p,k){Pf(ki,p,k)}var za=pi(yi(Boolean,tl)),sl=Ci(yi(Boolean,tl)),Ua=ne(sl,1);function M9(p,k,E){var x=I(k);Ea(p,function(D,O){x(D,function(_,V){if(_)return O(_);O(null,{value:D,criteria:V})})},function(D,O){if(D)return E(D);E(null,vi(O.sort(L),d9("value")))});function L(D,O){var _=D.criteria,V=O.criteria;return _<V?-1:_>V?1:0}}function R9(p,k,E){var x=I(p);return i(function(L,D){var O=!1,_;function V(){var Q=p.name||"anonymous",G=new Error('Callback function "'+Q+'" timed out.');G.code="ETIMEDOUT",E&&(G.info=E),O=!0,D(G)}L.push(function(){O||(D.apply(null,arguments),clearTimeout(_))}),_=setTimeout(V,k),x.apply(null,L)})}var LH=Math.ceil,MH=Math.max;function RH(p,k,E,x){for(var L=-1,D=MH(LH((k-p)/(E||1)),0),O=Array(D);D--;)O[x?D:++L]=p,p+=E;return O}function Va(p,k,E,x){var L=I(E);bi(RH(0,p,1),k,L,x)}var A9=ne(Va,1/0),O9=ne(Va,1);function _9(p,k,E,x){arguments.length<=3&&(x=E,E=k,k=gn(p)?[]:{}),x=xo(x||ht);var L=I(E);To(p,function(D,O,_){L(k,D,O,_)},function(D){x(D,k)})}function N9(p,k){var E=null,x;k=k||ht,ol(p,function(L,D){I(L)(function(O,_){arguments.length>2?x=o(arguments,1):x=_,E=O,D(!O)})},function(){k(E,x)})}function $9(p){return function(){return(p.unmemoized||p).apply(null,arguments)}}function Ff(p,k,E){E=An(E||ht);var x=I(k);if(!p())return E(null);var L=function(D){if(D)return E(D);if(p())return x(L);var O=o(arguments,1);E.apply(null,[null].concat(O))};x(L)}function P9(p,k,E){Ff(function(){return!p.apply(this,arguments)},k,E)}var j9=function(p,k){if(k=xo(k||ht),!gn(p))return k(new Error("First argument to waterfall must be an array of functions"));if(!p.length)return k();var E=0;function x(D){var O=I(p[E++]);D.push(An(L)),O.apply(null,D)}function L(D){if(D||E===p.length)return k.apply(null,arguments);x(o(arguments,1))}x([])},AH={apply:r,applyEach:PC,applyEachSeries:jC,asyncify:C,auto:Lf,autoInject:YC,cargo:JC,compose:XC,concat:t9,concatLimit:Ta,concatSeries:e9,constant:n9,detect:Sa,detectLimit:el,detectSeries:Da,dir:i9,doDuring:s9,doUntil:l9,doWhilst:_f,during:c9,each:La,eachLimit:nl,eachOf:To,eachOfLimit:Cr,eachOfSeries:ki,eachSeries:ol,ensureAsync:Nf,every:Ra,everyLimit:rl,everySeries:Aa,filter:Oa,filterLimit:il,filterSeries:_a,forever:u9,groupBy:h9,groupByLimit:Na,groupBySeries:f9,log:m9,map:Ea,mapLimit:bi,mapSeries:Df,mapValues:g9,mapValuesLimit:$a,mapValuesSeries:p9,memoize:b9,nextTick:v9,parallel:k9,parallelLimit:y9,priorityQueue:w9,queue:jf,race:B9,reduce:So,reduceRight:ja,reflect:Ha,reflectAll:E9,reject:x9,rejectLimit:Hf,rejectSeries:T9,retry:Fa,retryable:D9,seq:Of,series:L9,setImmediate:m,some:za,someLimit:sl,someSeries:Ua,sortBy:M9,timeout:R9,times:A9,timesLimit:Va,timesSeries:O9,transform:_9,tryEach:N9,unmemoize:$9,until:P9,waterfall:j9,whilst:Ff,all:Ra,allLimit:rl,allSeries:Aa,any:za,anyLimit:sl,anySeries:Ua,find:Sa,findLimit:el,findSeries:Da,forEach:La,forEachSeries:ol,forEachLimit:nl,forEachOf:To,forEachOfSeries:ki,forEachOfLimit:Cr,inject:So,foldl:So,foldr:ja,select:Oa,selectLimit:il,selectSeries:_a,wrapSync:C};e.default=AH,e.apply=r,e.applyEach=PC,e.applyEachSeries=jC,e.asyncify=C,e.auto=Lf,e.autoInject=YC,e.cargo=JC,e.compose=XC,e.concat=t9,e.concatLimit=Ta,e.concatSeries=e9,e.constant=n9,e.detect=Sa,e.detectLimit=el,e.detectSeries=Da,e.dir=i9,e.doDuring=s9,e.doUntil=l9,e.doWhilst=_f,e.during=c9,e.each=La,e.eachLimit=nl,e.eachOf=To,e.eachOfLimit=Cr,e.eachOfSeries=ki,e.eachSeries=ol,e.ensureAsync=Nf,e.every=Ra,e.everyLimit=rl,e.everySeries=Aa,e.filter=Oa,e.filterLimit=il,e.filterSeries=_a,e.forever=u9,e.groupBy=h9,e.groupByLimit=Na,e.groupBySeries=f9,e.log=m9,e.map=Ea,e.mapLimit=bi,e.mapSeries=Df,e.mapValues=g9,e.mapValuesLimit=$a,e.mapValuesSeries=p9,e.memoize=b9,e.nextTick=v9,e.parallel=k9,e.parallelLimit=y9,e.priorityQueue=w9,e.queue=jf,e.race=B9,e.reduce=So,e.reduceRight=ja,e.reflect=Ha,e.reflectAll=E9,e.reject=x9,e.rejectLimit=Hf,e.rejectSeries=T9,e.retry=Fa,e.retryable=D9,e.seq=Of,e.series=L9,e.setImmediate=m,e.some=za,e.someLimit=sl,e.someSeries=Ua,e.sortBy=M9,e.timeout=R9,e.times=A9,e.timesLimit=Va,e.timesSeries=O9,e.transform=_9,e.tryEach=N9,e.unmemoize=$9,e.until=P9,e.waterfall=j9,e.whilst=Ff,e.all=Ra,e.allLimit=rl,e.allSeries=Aa,e.any=za,e.anyLimit=sl,e.anySeries=Ua,e.find=Sa,e.findLimit=el,e.findSeries=Da,e.forEach=La,e.forEachSeries=ol,e.forEachLimit=nl,e.forEachOf=To,e.forEachOfSeries=ki,e.forEachOfLimit=Cr,e.inject=So,e.foldl=So,e.foldr=ja,e.select=Oa,e.selectLimit=il,e.selectSeries=_a,e.wrapSync=C,Object.defineProperty(e,"__esModule",{value:!0})})})(ju,ju.exports);var b2={exports:{}},Hu=b2.exports=function(n,t){if(t||(t=16),n===void 0&&(n=128),n<=0)return"0";for(var e=Math.log(Math.pow(2,n))/Math.log(t),o=2;e===1/0;o*=2)e=Math.log(Math.pow(2,n/o))/Math.log(t)*o;for(var r=e-Math.floor(e),i="",o=0;o<Math.floor(e);o++){var s=Math.floor(Math.random()*t).toString(t);i=s+i}if(r){var l=Math.pow(t,r),s=Math.floor(Math.random()*l).toString(t);i=s+i}var c=parseInt(i,t);return c!==1/0&&c>=Math.pow(2,n)?Hu(n,t):i};Hu.rack=function(n,t,e){var o=function(i){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=Hu(n,t)}while(Object.hasOwnProperty.call(r,l));return r[l]=i,l},r=o.hats={};return o.get=function(i){return o.hats[i]},o.set=function(i,s){return o.hats[i]=s,o},o.bits=n||128,o.base=t||16,o};var v2=fo,Ly=p2,My=C2,uc=rn,Fu=ju.exports,Ry=b2.exports,k2=Xo.ACTIONS,y2=Pt;function Pt(n,t){if(v2.EventEmitter.call(this),!t||typeof t!="string")throw new Error("Presence channel must be provided");this.connection=n,this.channel=t,this.wantSubscribe=!1,this.subscribed=!1,this.remotePresences={},this.localPresences={},this._remotePresenceInstances={},this._subscriptionCallbacksBySeq={},this._wantsDestroy=!1}v2.mixin(Pt),Pt.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Pt.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Pt.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||Ry();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Pt.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(o){if(o)return t._callbackOrEmit(o,n);var r=Object.keys(t._remotePresenceInstances);Fu.parallel([function(i){Fu.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();Fu.each(r,function(s,l){t._remotePresenceInstances[s].destroy(l)},i)}],function(i){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(i,n)})})},Pt.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?k2.presenceSubscribe:k2.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,o,this)},Pt.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Pt.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Pt.prototype._receiveUpdate=function(n,t){var e=uc.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=uc.digOrCreate(this._remotePresenceInstances,t.id,function(){return o._createRemotePresence(t.id)});r.receiveUpdate(t)},Pt.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Pt.prototype._broadcastAllLocalPresence=function(n){if(n)return this.emit("error",n);for(var t in this.localPresences){var e=this.localPresences[t];e.value!==null&&e.send()}},Pt.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Pt.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Pt.prototype._resubscribe=function(){var n=[];for(var t in this._subscriptionCallbacksBySeq){var e=this._subscriptionCallback(t);n.push(e)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var o=this;this.subscribe(function(r){o._callEachOrEmit(n,r)})},Pt.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Pt.prototype._callbackOrEmit=function(n,t){if(t)return uc.nextTick(t,n);n&&this.emit("error",n)},Pt.prototype._createLocalPresence=function(n){return new Ly(this,n)},Pt.prototype._createRemotePresence=function(n){return new My(this,n)},Pt.prototype._callEachOrEmit=function(n,t){var e=uc.callEach(n,t);!e&&t&&this.emit("error",t)};var ss=p2,w2=sc,Ay=rn,B2=w2.CODES,Oy=ln;function ln(n,t){ss.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this._doc=this.connection.get(this.collection,this.id),this._isSending=!1,this._docDataVersionByPresenceVersion={},this._opHandler=this._transformAgainstOp.bind(this),this._createOrDelHandler=this._handleCreateOrDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._destroyHandler=this.destroy.bind(this),this._registerWithDoc()}ln.prototype=Object.create(ss.prototype),ln.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:B2.ERR_DOC_DOES_NOT_EXIST,message:"Cannot submit presence. Document has not been created"};return this._callbackOrEmit(e,t)}this._docDataVersionByPresenceVersion[this.presenceVersion]=this._doc._dataStateVersion,ss.prototype.submit.call(this,n,t)},ln.prototype.destroy=function(n){this._doc.removeListener("op",this._opHandler),this._doc.removeListener("create",this._createOrDelHandler),this._doc.removeListener("del",this._createOrDelHandler),this._doc.removeListener("load",this._loadHandler),this._doc.removeListener("destroy",this._destroyHandler),ss.prototype.destroy.call(this,n)},ln.prototype._sendPending=function(){if(!this._isSending){this._isSending=!0;var n=this;this._doc.whenNothingPending(function(){n._isSending=!1,n.connection.canSend&&(n._pendingMessages.forEach(function(t){t.t=n._doc.type.uri,t.v=n._doc.version,n.connection.send(t)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},ln.prototype._registerWithDoc=function(){this._doc.on("op",this._opHandler),this._doc.on("create",this._createOrDelHandler),this._doc.on("del",this._createOrDelHandler),this._doc.on("load",this._loadHandler),this._doc.on("destroy",this._destroyHandler)},ln.prototype._transformAgainstOp=function(n,t){var e=this,o=this._doc._dataStateVersion;this._pendingMessages.forEach(function(r){var i=e._docDataVersionByPresenceVersion[r.pv];if(!(i>=o))try{r.p=e._transformPresence(r.p,n,t),e._docDataVersionByPresenceVersion[r.pv]=o}catch(l){var s=e._getCallback(r.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(r){this.emit("error",r)}},ln.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},ln.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},ln.prototype._message=function(){var n=ss.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},ln.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!Ay.supportsPresence(o))throw new w2(B2.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var E2={};(function(n){var t=os,e=sc,o=rn,r=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var c=l.create.type;if(typeof c!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var a=t.map[c];if(a==null||typeof a!="object")return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(r.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(r.ERR_OT_OP_BADLY_FORMED,"seq must be a number");if(l.src==null&&l.seq!=null||l.src!=null&&l.seq==null)return new e(r.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return t.map[l]&&t.map[l].uri},n.apply=function(l,c){if(typeof l!="object")return new e(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&c.v!=null&&l.v!==c.v)return new e(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(c.create){if(l.type)return new e(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var a=c.create,u=t.map[a.type];if(!u)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=u.create(a.data),l.type=u.uri,l.v++}catch(m){return m}}else if(c.del)l.data=void 0,l.type=null,l.v++;else if("op"in c){var f=i(l,c.op);if(f)return f;l.v++}else l.v++};function i(l,c){if(!l.type)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(c===void 0)return new e(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var a=t.map[l.type];if(!a)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=a.apply(l.data,c)}catch(u){return new e(r.ERR_OT_OP_NOT_APPLIED,u.message)}}n.transform=function(l,c,a){if(c.v!=null&&c.v!==a.v)return new e(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(a.del){if(c.create||"op"in c)return new e(r.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(a.create&&("op"in c||c.create||c.del)||"op"in a&&c.create)return new e(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in a&&"op"in c){if(!l)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{c.op=l.transform(c.op,a.op,"left")}catch(u){return u}}}c.v!=null&&c.v++},n.applyOps=function(l,c,a){a=a||{};for(var u=0;u<c.length;u++){var f=c[u];if(a._normalizeLegacyJson0Ops)try{s(l,f)}catch{return new e(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=f.v;var m=n.apply(l,f);if(m)return m}},n.transformPresence=function(l,c,a){var u=this.checkOp(c);if(u)return u;var f=l.t;if(typeof f=="string"&&(f=t.map[f]),!f)return{code:r.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!o.supportsPresence(f))return{code:r.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(c.create||c.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:f.transformPresence(l.p,c.op,a)}catch(m){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:m.message||m}}l.v++};function s(l,c){if(l.type===t.defaultType.uri){var a=c.op;if(!!a){var u=l.data;a.length>1&&(u=o.clone(u));for(var f=0;f<a.length;f++){var m=a[f];typeof m.lm=="string"&&(m.lm=+m.lm);for(var C=m.p,v=u,B=0;B<C.length;B++){var y=C[B];Object.prototype.toString.call(v)=="[object Array]"?C[B]=+y:v.constructor===Object&&(C[B]=y.toString()),v=v[y]}f<a.length-1&&(u=t.defaultType.apply(u,[m]))}}}}})(E2);var ls=C2,_y=E2,Ny=Pe;function Pe(n,t){ls.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this.src=null,this.presenceVersion=null,this._doc=this.connection.get(this.collection,this.id),this._pending=null,this._opCache=null,this._pendingSetPending=!1,this._opHandler=this._handleOp.bind(this),this._createDelHandler=this._handleCreateDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._registerWithDoc()}Pe.prototype=Object.create(ls.prototype),Pe.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},Pe.prototype.destroy=function(n){this._doc.removeListener("op",this._opHandler),this._doc.removeListener("create",this._createDelHandler),this._doc.removeListener("del",this._createDelHandler),this._doc.removeListener("load",this._loadHandler),ls.prototype.destroy.call(this,n)},Pe.prototype._registerWithDoc=function(){this._doc.on("op",this._opHandler),this._doc.on("create",this._createDelHandler),this._doc.on("del",this._createDelHandler),this._doc.on("load",this._loadHandler)},Pe.prototype._setPendingPresence=function(){if(!this._pendingSetPending){this._pendingSetPending=!0;var n=this;this._doc.whenNothingPending(function(){if(n._pendingSetPending=!1,!!n._pending){if(n._pending.pv<n.presenceVersion)return n._pending=null;if(n._pending.v>n._doc.version)return n._doc.fetch();!n._catchUpStalePresence()||(n.value=n._pending.p,n.presenceVersion=n._pending.pv,n._pending=null,n.presence._updateRemotePresence(n))}})}},Pe.prototype._handleOp=function(n,t,e){var o=e===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},ls.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},ls.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},Pe.prototype._transformAgainstOp=function(n,t){if(!!this.value){try{this.value=this._doc.type.transformPresence(this.value,n,t)}catch(e){return this.presence.emit("error",e)}this.presence._updateRemotePresence(this)}},Pe.prototype._catchUpStalePresence=function(){if(this._pending.v>=this._doc.version)return!0;if(!this._opCache)return this._startCachingOps(),this._doc.fetch(),this.presence.subscribe(),!1;for(;this._opCache[this._pending.v];){var n=this._opCache[this._pending.v],t=n.op,e=n.isOwnOp;t===null?(this._pending.p=null,this._pending.v++):_y.transformPresence(this._pending,t,e)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},Pe.prototype._startCachingOps=function(){this._opCache=[]},Pe.prototype._stopCachingOps=function(){this._opCache=null},Pe.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var I2=y2,$y=Oy,Py=Ny;function Nr(n,t,e){var o=Nr.channel(t,e);I2.call(this,n,o),this.collection=t,this.id=e}var jy=Nr;Nr.prototype=Object.create(I2.prototype),Nr.channel=function(n,t){return n+"."+t},Nr.prototype._createLocalPresence=function(n){return new $y(this,n)},Nr.prototype._createRemotePresence=function(n){return new Py(this,n)};var Hy=Fy;function Fy(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var zy=Hy,x2=fo,T2=cs;function cs(n,t,e,o,r){if(x2.EventEmitter.call(this),typeof r!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=o,this.collection=e,this.callback=r,this.sent=!1}x2.mixin(cs),cs.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},cs.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},cs.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new zy(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var S2=T2,Uy=rn,Vy=Xo.ACTIONS,qy=zu;function zu(n,t,e,o,r,i){if(S2.call(this,n,t,e,o,i),!Uy.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}zu.prototype=Object.create(S2.prototype),zu.prototype._message=function(){return{a:Vy.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var D2=T2,Wy=rn,Gy=Xo.ACTIONS,Zy=Uu;function Uu(n,t,e,o,r,i){if(D2.call(this,n,t,e,o,i),!Wy.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}Uu.prototype=Object.create(D2.prototype),Uu.prototype._message=function(){return{a:Gy.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var Yy=yy,Qy=xy,Ky=y2,L2=jy,Jy=qy,Xy=Zy,M2=fo,$r=sc,Ct=Xo.ACTIONS,R2=os,cn=rn,as=l2,ds=$r.CODES;function A2(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var tw=K;function K(n){M2.EventEmitter.call(this),this.collections={},this.nextQueryId=1,this.nextSnapshotRequestId=1,this.queries={},this._presences={},this._snapshotRequests={},this.seq=1,this._presenceSeq=1,this.id=null,this.agent=null,this.debug=!1,this.state=A2(n),this.bindToSocket(n)}M2.mixin(K),K.prototype.bindToSocket=function(n){this.socket&&(this.socket.close(),this.socket.onmessage=null,this.socket.onopen=null,this.socket.onerror=null,this.socket.onclose=null),this.socket=n;var t=A2(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(o){try{var r=typeof o.data=="string"?JSON.parse(o.data):o.data}catch{as.warn("Failed to parse message",o);return}e.debug&&as.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){cn.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(o){e.emit("connection error",o)},n.onclose=function(o){o==="closed"||o==="Closed"?e._setState("closed",o):o==="stopped"||o==="Stopped by server"?e._setState("stopped",o):e._setState("disconnected",o)}},K.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=O2(n.error,n),delete n.error),n.a){case Ct.initLegacy:return this._handleLegacyInit(n);case Ct.handshake:return this._handleHandshake(t,n);case Ct.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case Ct.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case Ct.queryUnsubscribe:return;case Ct.queryUpdate:var e=this.queries[n.id];if(!e)return;if(t)return e._handleError(t);n.diff&&e._handleDiff(n.diff),n.hasOwnProperty("extra")&&e._handleExtra(n.extra);return;case Ct.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case Ct.bulkSubscribe:case Ct.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case Ct.snapshotFetch:case Ct.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case Ct.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case Ct.subscribe:case Ct.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case Ct.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case Ct.presence:return this._handlePresence(t,n);case Ct.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case Ct.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case Ct.presenceRequest:return this._handlePresenceRequest(t,n);case Ct.pingPong:return this._handlePingPong(t);default:as.warn("Ignoring unrecognized message",n)}};function O2(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}K.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var o in t.data){var r=t.data[o],i=this.getExisting(t.c,o);i&&(n?i[e](n):r.error?i[e](O2(r.error)):i[e](null,r))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var o=t.b[s],i=this.getExisting(t.c,o);i&&i[e](n)}else if(t.b)for(var o in t.b){var i=this.getExisting(t.c,o);i&&i[e](n)}else as.error("Invalid bulk message",t)},K.prototype._reset=function(){this.agent=null},K.prototype._setState=function(n,t){if(this.state!==n){if(n==="connecting"&&this.state!=="disconnected"&&this.state!=="stopped"&&this.state!=="closed"||n==="connected"&&this.state!=="connecting"){var e=new $r(ds.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",e)}this.state=n,this.canSend=n==="connected",(n==="disconnected"||n==="stopped"||n==="closed")&&this._reset(),this.startBulk();for(var o in this.queries){var r=this.queries[o];r._onConnectionStateChanged()}for(var i in this.collections){var s=this.collections[i];for(var o in s)s[o]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var o in this._snapshotRequests){var c=this._snapshotRequests[o];c._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},K.prototype.startBulk=function(){this.bulk||(this.bulk={})},K.prototype.endBulk=function(){if(this.bulk)for(var n in this.bulk){var t=this.bulk[n];this._sendBulk("f",n,t.f),this._sendBulk("s",n,t.s),this._sendBulk("u",n,t.u)}this.bulk=null},K.prototype._sendBulk=function(n,t,e){if(!!e){var o=[],r={},i=0,s;for(var l in e){var c=e[l];c==null?o.push(l):(r[l]=c,s=l,i++)}if(o.length===1){var l=o[0];this.send({a:n,c:t,d:l})}else o.length&&this.send({a:"b"+n,c:t,b:o});if(i===1){var a=r[s];this.send({a:n,c:t,d:s,v:a})}else i&&this.send({a:"b"+n,c:t,b:r})}},K.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var o=this.bulk[t.collection]||(this.bulk[t.collection]={}),r=o[n]||(o[n]={}),i=r.hasOwnProperty(t.id);return r[t.id]=e,i}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},K.prototype.sendFetch=function(n){return this._sendActions(Ct.fetch,n,n.version)},K.prototype.sendSubscribe=function(n){return this._sendActions(Ct.subscribe,n,n.version)},K.prototype.sendUnsubscribe=function(n){return this._sendActions(Ct.unsubscribe,n)},K.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:Ct.op,c:n.collection,d:n.id,v:n.version,src:t.src,seq:t.seq,x:{}};"op"in t&&(e.op=t.op),t.create&&(e.create=t.create),t.del&&(e.del=t.del),n.submitSource&&(e.x.source=t.source),this.send(e)},K.prototype.send=function(n){this.debug&&as.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},K.prototype.ping=function(){if(!this.canSend)throw new $r(ds.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:Ct.pingPong};this.send(n)},K.prototype.close=function(){this.socket.close()},K.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},K.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new Yy(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},K.prototype._destroyDoc=function(n){!n._wantsDestroy||(cn.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},K.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},K.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new Qy(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},K.prototype._destroyQuery=function(n){delete this.queries[n.id]},K.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(Ct.queryFetch,n,t,e,o)},K.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(Ct.querySubscribe,n,t,e,o)},K.prototype.hasPending=function(){return!!(this._firstDoc(hc)||this._firstQuery(hc)||this._firstSnapshotRequest())};function hc(n){return n.hasPending()}K.prototype.hasWritePending=function(){return!!this._firstDoc(ew)};function ew(n){return n.hasWritePending()}K.prototype.whenNothingPending=function(n){var t=this._firstDoc(hc);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(hc);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}cn.nextTick(n)},K.prototype._nothingPendingRetry=function(n){var t=this;return function(){cn.nextTick(function(){t.whenNothingPending(n)})}},K.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var o in e){var r=e[o];if(n(r))return r}}},K.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},K.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},K.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new Jy(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},K.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new Xy(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},K.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},K.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},K.prototype._initializeHandshake=function(){this.send({a:Ct.handshake,id:this.id})},K.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},K.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},K.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new $r(ds.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(R2.map[n.type]!==R2.defaultType)return this.emit("error",new $r(ds.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new $r(ds.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},K.prototype.getPresence=function(n){var t=this,e=cn.digOrCreate(this._presences,n,function(){return new Ky(t,n)});return e._wantsDestroy=!1,e},K.prototype.getDocPresence=function(n,t){var e=L2.channel(n,t),o=this,r=cn.digOrCreate(this._presences,e,function(){return new L2(o,n,t)});return r._wantsDestroy=!1,r},K.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},K.prototype._addPresence=function(n){cn.digOrCreate(this._presences,n.channel,function(){return n})},K.prototype._handlePresenceSubscribe=function(n,t){var e=cn.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},K.prototype._handlePresenceUnsubscribe=function(n,t){var e=cn.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},K.prototype._handlePresence=function(n,t){var e=cn.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},K.prototype._handlePresenceRequest=function(n,t){var e=cn.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var _2=tw,nw=os;const fc={err:1001,msg:"user auth error",name:"AuthError"},ow={err:1002,msg:"you don't have required permission",name:"PermissionError"},Vu={err:1003,msg:"Too many user connected",name:"MaxUserError"},us={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},rw={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},iw={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},hs="x-live-editor-token",mc="x-live-editor-base-url",he=w("auth-connection");function sw(n){try{n()}catch(t){he.error(t)}}class lw{constructor(t,e){h(this,"connection");h(this,"ws");h(this,"retryCount");h(this,"events",new Vf.EventEmitter);h(this,"token",null);h(this,"resourceToken",null);this.url=t,this.reauthFunc=e,this.retryCount=0}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return _o(this.getBaseURL())}async auth(t){d(he,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[hs]:t.token,[mc]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.token=t.token,await o.json()}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[mc]:_o(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new f7.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(_2.prototype),d(he,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})};const o=this.connection.handleMessage.bind(this.connection);this.connection.handleMessage=r=>{var s;const i=r;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in i||i.a==="pong")this.handleMessage(i);else{Object.prototype.hasOwnProperty.call(i,"a")&&i.a!=="init"&&i.a!=="hs"&&(this.retryCount=0);try{o(i)}catch(l){if((l==null?void 0:l.type)==="writeConflict"){this.emitWriteConflictError(l,i);return}if((s=l==null?void 0:l.message)!=null&&s.startsWith("Cannot invert subtype")){this.emitWriteConflictError(l,i);return}throw l}}},_2.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,he.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();await this.auth(t),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){he.error(t),setTimeout(()=>this.handleAuthError(),0)}}else he.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(fc.msg);t.code=fc.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(us.msg);t.code=us.err,this.events.emit("requestReloadError",t)}emitWriteConflictError(t,e){t.orgMsg=e,this.events.emit("writeConflictError",t)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(t){const e=t;if(e.a==="pong")return;const o=e.err;if(o===fc.err)he.warn("auth error"),this.handleAuthError();else if(o===Vu.err)he.warn(Vu.msg),this.emitMaxUsersError();else if(o===us.err){he.warn(us.msg);try{this.emitRequestReloadError()}catch(r){he.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else he.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError()}get(t,e){return d(he,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(d(he,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){d(he,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){d(he,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.reauthFunc=void 0,this.events.removeAllListeners(),sw(()=>{var o;return(o=this.connection)==null?void 0:o.close()}),this.connection=void 0,(e=this.ws)==null||e.close(),this.ws=void 0,t&&this.logout()}}w("utils/file");function cw(){function n(){return new Promise(t=>{const e=new FileReader;e.onload=()=>{t(e.result)},e.readAsArrayBuffer(this)})}File.prototype.arrayBuffer=File.prototype.arrayBuffer||n,Blob.prototype.arrayBuffer=Blob.prototype.arrayBuffer||n}cw();async function aw(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new m7.Hash;for(let s=0;s<o;s++){const l=s*102400;let c=l+102400;c>e&&(c=e);const u=await n.slice(l,c,n.type).arrayBuffer();r.update(new Uint8Array(u))}const i=r.digest();return _o(i)}const En=w("sharedb-doc/client");class dw{constructor(t,e,o){h(this,"connection");h(this,"auth");h(this,"doc",null);h(this,"reauthFunc");h(this,"clientId",N());h(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});d(En,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),En.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;nw.register(al.type),this.connection=new lw(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return d(En,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}close(t){this.connection.end(t),this.doc=null}on(t,e){this.connection.addEventListener(t,o=>{(t==="error"||this.doc)&&e(o)})}onWriteConflictError(t){this.connection.onWriteConflictError(t)}onMaxUsersError(t){this.connection.onMaxUsersError(t)}onRequestReloadError(t){this.connection.onRequestReloadError(t)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const t=this.connection.url;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}async getFileUrlByHash(t,e,o,r,i){try{const s=`${t}/${e}`,l=await this.request(s,{method:"post",headers:{...i},data:{name:o,size:r}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(t){const o=`${this.apiServer()}/resources`;let r=[];t.forEach(l=>{const c=l.split("|");r.push(...c)}),r=Array.from(new Set(r));const i=r.map(l=>this.getFileUrlByHash(o,l,"",0,{[hs]:this.connection.token}));return await Promise.all(i)}async uploadFile(t,e,o,r,i){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=C=>{En.info(`on progress: ${C.loaded}`);let v=C.loaded*100/s;v>100&&(v=100),r(v)},c=await aw(e),a=await this.getFileUrlByHash(t,c,e.name,e.size,o);if(a)return r(-1),a;let u=t;i!=null&&i.thumbnail&&(u+="/thumbnail");const f=new FormData;f.append("file-size",`${e.size}`),f.append("file-hash",c),f.append("file",e,e.name);const m=await this.request(u,{method:"post",data:f,withCredentials:!0,headers:{...o},onUploadProgress:l});return En.info(m),r(100),Array.isArray(m.data)?m.data[0]:m.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;d(En,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[hs]:this.connection.token},e,o);return d(En,s,"no result"),s}async request(t,e){var i,s;let o=this.connection.token,r;for(let l=0;l<2;l++){const c=e||{};c.url=t,c.headers||(c.headers={}),d(En,o,"no token"),c.headers={...c.headers,[hs]:o,[mc]:this.connection.getBase64BaseURL()};try{return await u7.default(t,c)}catch(a){if(r=a,((i=a==null?void 0:a.response)==null?void 0:i.status)===403&&this.reauthFunc){const u=await this.reauthFunc();if(await this.connection.auth(u),!u.token)throw a;o=u.token;continue}throw(s=a.response)!=null&&s.data&&(a.responseData=a.response.data),a}}throw d(En,r,"no error"),r}async getVersions(){const e=`${this.apiServer()}/versions`,o=await this.request(e),r=o.data.versions,i=o.data.latest;return i&&r.findIndex(s=>s.version===i)===-1&&r.unshift({version:-1,tag:"",published:!1}),r}async getVersion(t){const o=`${this.apiServer()}/versions/${t}`,r=await this.request(o);return JSON.parse(r.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,o=await this.request(e);return JSON.parse(o.data.data)}async getVersionOps(t,e){let r=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(r+=`&from=${e}`);const i=await this.request(r),s=i.data.ops,l=h7.default(s,u=>!!u.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let a;return c?(d(En,c.create,"no createDoc.create"),a=c.create.data):a=JSON.parse(i.data.data),a.blocks||(a.blocks=[]),{doc:a,ops:i.data.ops}}async revertVersion(t){const o=`${this.apiServer()}/versions/revert/${t}`;await this.request(o,{method:"post",data:{}})}async createVersion(t,e){const r=`${this.apiServer()}/versions`;return(await this.request(r,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const o=`${this.apiServer()}/resources/external/${_o(t)}`;return(await this.request(o)).data}buildResourceUrl(t,e){if(!t)return"";if(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;let r=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const i=[];if(e!=null&&e.withToken&&i.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&i.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),i.length>0){const s=i.join("&");r+=`?${s}`}return r}}function uw(){return{blocks:[{id:N(),type:"text",text:[]}],comments:{},meta:{}}}const qu=w("block-ids");class hw{constructor(){h(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((r,i)=>i-r);for(let r=0;r<e.length;r++){const i=e[r];if(i>=t){const s=this.ids.get(i);d(qu,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=N();this.ids.set(t,o)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((o,r)=>o-r);for(let o=0;o<e.length;o++){const r=e[o];if(r>t){const i=this.ids.get(r);d(qu,i!==void 0,"old id is not exists"),this.ids.delete(r),this.ids.set(r-1,i)}}}getId(t){let e=this.ids.get(t);return e||(e=N(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class fw{constructor(){h(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new hw,this.ids.set(t,e)),e}onInsertBlock(t,e){this.getContainerIds(t).onInsertBlock(e)}onDeleteBlock(t,e){this.getContainerIds(t).onDeleteBlock(e)}getBlockId(t,e){return this.getContainerIds(t).getId(e)}getBlockIndexById(t){const e=Array.from(this.ids.entries());for(let o=0;o<e.length;o++){const r=e[o],i=r[1].getById(t);if(i)return{containerId:r[0],blockIndex:i[0]}}return d(qu,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class N2{constructor(t=new Set,e=new Map){this.deletedKeys=t,this.insertedValues=e}insert(t,e){this.insertedValues.set(t,e)}delete(t){this.deletedKeys.add(t)}toDocBlockDelta(){const t={};return this.insertedValues.forEach((e,o)=>{t[o]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const $t=w("op-parser");function Pr(n){return n==="blocks"?"root":n}class mw{constructor(t,e){h(this,"updatingBlockDataDeltaMap",new Map);h(this,"blockIds",new fw);this.handler=t,this.local=e}onDeleteBlock(t,e){const o=this.blockIds.getBlockId(t,e);this.blockIds.onDeleteBlock(t,e);const r=this.updatingBlockDataDeltaMap.get(o);r&&($t.debug(`ignore update object data before delete block: ${JSON.stringify(r)}`),this.updatingBlockDataDeltaMap.delete(o)),this.handler.onDeleteBlock(Pr(t),e,this.local)}onInsertBlock(t,e,o){this.blockIds.onInsertBlock(t,e),this.handler.onInsertBlock(Pr(t),e,o,this.local)}onUpdateBlockText(t,e,o){this.handler.onUpdateBlockText(Pr(t),e,o,this.local)}onDeleteBlockData(t,e,o){const r=this.blockIds.getBlockId(t,e);let i=this.updatingBlockDataDeltaMap.get(r);i||(i=new N2,this.updatingBlockDataDeltaMap.set(r,i)),i.delete(o)}onInsertBlockData(t,e,o,r){const i=this.blockIds.getBlockId(t,e);let s=this.updatingBlockDataDeltaMap.get(i);s||(s=new N2,this.updatingBlockDataDeltaMap.set(i,s)),s.insert(o,r)}executeUpdateBlockDataActions(){Array.from(this.updatingBlockDataDeltaMap.entries()).forEach(([t,e])=>{const{containerId:o,blockIndex:r}=this.blockIds.getBlockIndexById(t);this.handler.onUpdateBlockData(Pr(o),r,e.toDocBlockDelta(),this.local)})}}class $2{}class Wu{constructor(t){h(this,"key");this.key=t}}function gw(n,t,e){const o=t.concat(),r=o[0];if(typeof r!="number"||(o.shift(),o.length===1))return!1;const i=o[0];if(typeof i!="object"||!i.i||Object.keys(i).length!==1)return!1;for(let l=1;l<o.length;l++){const c=o[l];if(!Array.isArray(c)||c.length!==2||typeof c[0]!="string")return!1;const u=c[1];if(typeof u!="object"||u.i===void 0||Object.keys(u).length!==1)return!1}const s=i.i;d($t,s.id,"block id is required"),d($t,s.type,"block type is required");for(let l=1;l<o.length;l++){const c=o[l],a=c[0],u=c[1];s[a]=u.i}return e.onInsertBlock(n,r,s),!0}function Gu(n,t,e,o){if(e==="upsert"&&gw(n,t,o))return;d($t,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const r=t.concat(),i=r[0];r.shift();const s=[];for(;r.length>0;){const l=r[0];if(l==="text"){const c=r[1];if(d($t,typeof c=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),d($t,c.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),r.splice(0,2),e==="upsert"){const u=c.e;o.onUpdateBlockText(n,i,u)}d($t,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){d($t,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const c=l[0];d($t,typeof c=="string",`invalid block op: key ${JSON.stringify(c)}`);const a=l[1];if(c==="text"){if(d($t,typeof a=="object",`invalid opData type, ${JSON.stringify(a)}`),a.i&&e==="upsert"&&o.onInsertBlockData(n,i,c,a.i),a.r&&e==="remove"&&o.onDeleteBlockData(n,i,c),a.et==="rich-text"&&e==="upsert"){const f=a.e;o.onUpdateBlockText(n,i,f)}}else e==="remove"&&a.r&&s.push(new Wu(c)),e==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i);r.shift()}else if(typeof l=="object"){const c=l;e==="remove"&&c.r&&s.push(new $2),e==="upsert"&&c.i&&o.onInsertBlock(n,i,c.i),r.shift()}else{d($t,typeof l=="string","data is not string"),d($t,l!=="text","data !== 'text'"),d($t,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const c=l,a=r[1];e==="remove"&&a.r&&s.push(new Wu(c)),e==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof $2?o.onDeleteBlock(n,i):l instanceof Wu?o.onDeleteBlockData(n,i,l.key):d($t,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function pw(n,t,e,o){$t.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function Cw(n,t,e,o){const r=n[1],i=n[2];d($t,r,`invalid comment op, no commentId: ${JSON.stringify(n)}`),d($t,i,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof i=="string"?$t.error(`unknown comment op, ${JSON.stringify(n)}`):i.i&&i.r?t==="upsert"&&o.onUpdateComment(r,e.local):i.i?t==="upsert"&&o.onCreateComment(r,e.local):i.r?t==="remove"&&o.onDeleteComment(r,e.local):$t.error(`unknown comment op, ${JSON.stringify(n)}`)}function Zu(n,t,e,o){const r=n[0];if(Array.isArray(r)){r.forEach(l=>{Zu(l,t,e,o)});return}const i=r;if(d($t,typeof i=="string",`invalid container id: ${JSON.stringify(n)}`),i==="meta"){pw(n);return}if(i==="comments"){Cw(n,t,e,o);return}const s=i;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(l=>{Gu(s,l,t,e)}):n.slice(1).forEach(l=>{Gu(s,l,t,e)});else if(typeof n[1]=="object"){const l=n[1];l.r&&t==="remove"&&o.onDeleteContainer(Pr(s),e.local),l.i&&t==="upsert"&&o.onCreateContainer(Pr(s),l.i,e.local)}else d($t,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Gu(s,n.slice(1),t,e)}function P2(n,t,e){const o=new mw(t,e);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=Y.default(n),l=s[0];Array.isArray(l)?s.forEach(c=>{Zu(c,i,o,t)}):Zu(s,i,o,t)}o.executeUpdateBlockDataActions()}const bw=w("sharedb-comments");function Yu(n){if(n.doc)return Y.default(n.doc);const t=n.blocks;d(bw,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([o,r])=>{Array.isArray(r)&&(e.blocks[o]=r)}),Y.default(e)}function j2(n){const{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:c}=n;return{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:c}}function Qu(n,t){const e={...n,doc:t};return delete e.blocks,Y.default(e)}const kt=w("sharedb-doc/doc-container"),H2="ot-json1";al.type.registerSubtype(oy.type),al.type.name=H2,al.type.invert=null;class fs extends xi{constructor(e,o,r=!0){super();h(this,"doc");h(this,"client");h(this,"localPresence");h(this,"remoteCaretHandler",new ey);h(this,"batching",0);h(this,"status","clean");h(this,"disableLogout");h(this,"destroyed",!1);h(this,"handleNothingPending",()=>{this.setStatus("clean")});h(this,"handleCreate",()=>{this.handleReload("doc created")});h(this,"handleDel",()=>{});h(this,"handleReload",e=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})});h(this,"handleReset",async e=>{const o=new Error(`reset doc: ${e}`);o.code="ResetDoc",this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,o)}),this.destroy()});h(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});h(this,"insertObject",async(e,o,r)=>{const i=[e,o,{i:r}];return this.submitOp(i)});h(this,"deleteObject",async(e,o)=>{const r=[e,o,{r:!0}];return this.submitOp(r)});h(this,"replaceObject",async(e,o,r)=>{const i=[e,o,{r:!0,i:r}];return this.submitOp(i)});h(this,"updateObject",async(e,o,r)=>{const i=this.data()[e][o],s=[e,o];return Object.entries(r).forEach(([l,c])=>{if(!cl.default(i[l],c))if(i[l]===void 0){if(c!=null){const a={i:c};s.push([l,a])}}else if(c==null){const a={r:!0};s.push([l,a])}else{const a={r:!0,i:c};s.push([l,a])}}),Object.entries(i).forEach(([l,c])=>{if((r[l]===void 0||r[l]===null)&&c!==void 0){const a={r:!0};s.push([l,a])}}),s.length<=2?Promise.resolve():this.submitOp(s)});h(this,"broadcastMessage",async e=>{const o={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});h(this,"data",()=>this.doc.data);h(this,"submitOp",async e=>new Promise((o,r)=>{if(this.destroyed){kt.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(kt.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),kt.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(kt.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));h(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,H2,i=>{i?r(i):o()})}));h(this,"submitInsertChildContainer",async(e,o)=>{const r=[ho(e),{i:o}];return this.submitOp(r)});h(this,"submitDeleteChildContainer",async e=>{const o=[ho(e),{r:!0}];return this.submitOp(o)});h(this,"submitInsertBlock",async(e,o,r)=>{const i=[ho(e),o,{i:r}];return this.submitOp(i)});h(this,"submitDeleteBlock",async(e,o)=>{const r=[ho(e),o,{r:!0}];return this.submitOp(r)});h(this,"submitUpdateBlockData",async(e,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[ho(e),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c)){const u={r:!0,i:a};i.push([c,u])}});const l=new Set(Object.keys(r.insert));return r.delete.forEach(c=>{if(l.has(c))return;const a={r:!0};i.push([c,a])}),Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c))return;const u={i:a};i.push([c,u])}),this.submitOp(i)});h(this,"submitUpdateRichText",async(e,o,r)=>{const i=[ho(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});h(this,"handleOp",(e,o,r)=>{if(this.destroyed){kt.warn("handleOp: destroyed");return}P2(e,this,!!o)});this.client=e,this.doc=o,this.doc.preventCompose=!0,this.disableLogout=r,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,d(kt,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new dw(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new fs(o,r,e.disableLogout);if(r.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await i.createDoc(e.templateData||uw())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw kt.error(o),kt.error(`failed to load doc: ${JSON.stringify(o)}`),o}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),this.client.onWriteConflictError(this.handleWriteConflictError)}clearEvents(){this.doc.off("nothing pending",this.handleNothingPending),this.doc.off("create",this.handleCreate),this.doc.off("del",this.handleDel)}initPresence(){return new Promise((e,o)=>{if(this.localPresence)e();else{const r=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);r.on("receive",(i,s)=>{this.onCustomMessage(s)}),r.subscribe(i=>{i?o(i):(this.localPresence=r.create(N()),e())})}})}subscribe(){return new Promise((e,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return es(this.data())}getContainerBlocks(e){const o=this.data();d(kt,o,"no doc data");const r=o[ho(e)];return d(kt,r,`no container data: ${e}`),Y.default(r)}getBlockData(e,o){const r=this.data();d(kt,r,"no doc data");const i=r[ho(e)];d(kt,i,`no container data: ${e}`);const s=i[o];return d(kt,s,`no block data: ${o}`),Y.default(s)}localInsertBlock(e,o,r){return this.submitInsertBlock(e,o,r),this.getBlockData(e,o)}localDeleteBlock(e,o){const r=this.getBlockData(e,o);return this.submitDeleteBlock(e,o),r}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);d(kt,i.text,"no block text");const s=Y.default(i.text);this.submitUpdateRichText(e,o,r);const l=ie.apply(s,r);return d(kt,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=Y.default(this.getBlockData(e,o));return this.submitUpdateBlockData(e,o,r),i}localInsertChildContainer(e,o){this.submitInsertChildContainer(e,o)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>j2(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return Yu(o)}localCreateComment(e,o){const r=Qu(e,o),s=["comments",r.id,{i:r}];return this.submitOp(s)}localDeleteComment(e){const o=["comments",e,{r:!0}];return this.submitOp(o)}localUpdateComment(e,o){const r=Qu(e,o),i=["comments",e.id,{r:!0,i:r}];return this.submitOp(i)}destroy(){var e;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(e=this.localPresence)==null||e.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(e,o,r){d(kt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,_r(e),o,r)})}onInsertBlock(e,o,r,i){d(kt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,_r(e),o,r,i)})}onUpdateBlockData(e,o,r,i){d(kt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,_r(e),o,r,i)})}onUpdateBlockText(e,o,r,i){d(kt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,_r(e),o,r,i)})}onDeleteContainer(e,o){d(kt,this.callbacks.length>0,"no callbacks"),d(kt,e!=="root","should not delete root container in doc"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,_r(e),o)})}onCreateContainer(e,o,r){d(kt,this.callbacks.length>0,"no callbacks"),d(kt,e!=="root","should not create root container in doc"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,_r(e),o,r)})}onDeleteComment(e,o){d(kt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteComment)==null?void 0:i.call(r,e,o)})}onCreateComment(e,o){d(kt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onCreateComment)==null?void 0:i.call(r,e,o)})}onUpdateComment(e,o){d(kt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onUpdateComment)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){const o=e;(o==null?void 0:o.type)==="custom"&&(o==null?void 0:o.clientId)!==this.client.clientId?this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,o.data)}):(o==null?void 0:o.type)==="onlineUsers"&&setTimeout(()=>{const r={type:"custom",data:e,clientId:"-"};this.onCustomMessage(r)})}async addResources(e){return await this.client.getFileUrlsByHashes(e)}async uploadResource(e,o){var i;return{resourceId:await this.client.uploadResource(e,(i=o==null?void 0:o.onProgress)!=null?i:()=>{})}}buildResourceUrl(e,o){return this.client.buildResourceUrl(e,o)}request(e,o){return this.client.request(e,o)}getUser(){const e=this.client.clientId,{permission:o,userId:r,displayName:i,avatarUrl:s}=this.client.auth;return{permission:o,clientId:e,userId:r,displayName:i,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const o=await this.client.getVersion(e);return es(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return es(e)}async getHistoryData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o),s=i.map(l=>({user:l.meta.createdBy,data:l}));return{doc:es(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:es(r),versionData:i}}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,o){return this.client.createVersion(e,o)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,o){P2(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}w("remote-cursor");class F2{constructor(t){h(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});h(this,"broadcastCaretPos",Xt.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));h(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const o=this.editor.findBlockById(e);o&&this.editor.reloadBlock(o)})});this.editor=t,this.editor.addListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().addListener("remote-carets-change",this.handleRemoteCaretsChanged)}destroy(){this.editor.removeListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().removeListener("remote-carets-change",this.handleRemoteCaretsChanged)}}const z2=w("remote-cursor-decorator");class Ku{decorateText(t,e,o){const r=t.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=e[e.length-1];d(z2,typeof s=="string","invalid path containerId"),d(z2,typeof l=="number","invalid path blockIndex");const c=t.doc.getBlockData(s,l),a=de(o);return r.getSimpleCursors(c.id).forEach((f,m)=>{m>a&&(m=a);const C=f.map(B=>({id:N(),type:"remote-cursor",name:B.user.displayName,time:B.time,rainbowIndex:B.user.rainbowIndex})),v=i.get(m);v?v.push(...C):i.set(m,C)}),{insertions:i}}}class U2 extends Yt.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(pt(Br(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=F(this.editor.getContainerById(t));i&&this.emit("change",this.editor,i,r,o)}onUpdateBlockData(t,e){this.handleChild(t,e,"data-change")}onUpdateBlockText(t,e){this.handleChild(t,e,"text-change")}destroy(){this.editor.doc.unregisterCallback(this)}}function vw(n,t){n.addCustom("child-block-tracker",()=>new U2(n)).addListener("change",t)}function kw(n,t){n.addCustom("child-block-tracker",()=>new U2(n)).removeListener("change",t)}const nz="",yw={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4",name:"\u6587\u672C\u989C\u8272"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},ww={colorPalette:{colorDesc:"Text Color",name:"Text Color",backgroundDesc:"Background Color",reset:"Reset"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}};T.mergeLang({"zh-CN":yw,"en-US":ww});const oz="";w("button");function go(n,t,e,o,r){const i=b("button",["editor-button"],null);return i.setAttribute("data-button-id",n),r&&i.setAttribute(`data-editor-tooltip-${r}`,t),e?typeof e=="string"?e.startsWith("<")?i.innerHTML=e:i.innerText=e:i.appendChild(e):i.innerText=t,o&&(o.indexOf("checked")!==-1&&A(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0)),i}function V2(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}const rz="",jr=w("ui-command-bar-base"),Bw={itemElementTag:"div",tippyArrow:!1},Bf=class extends Yt.TypedEmitter{constructor(e,o,r){var i,s;super();h(this,"content");h(this,"items");h(this,"subBar",null);h(this,"parentItem",null);h(this,"closeable",null);h(this,"options");h(this,"id");h(this,"handleDocumentKeydown",e=>{if(!!this.isVisible&&!e.isComposing){if(this.subBar){this.subBar.handleDocumentKeydown(e);return}if(this.items.length!==0){if(e.key==="Escape"){this.close();return}if(e.key==="ArrowUp"){const o=this.getPrevItemIndex(this.getSelectedItemIndex());this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowRight"){const o=this.getSelectedItem();o&&o.children&&this.showSubCommandBar(o.childrenMenuId)}else if(e.key==="ArrowLeft")this.parentItem&&this.close();else if(e.key==="Enter"){const o=this.getSelectedItemIndex();if(o===-1)return;const r=this.items[o],i=this.getItemElementById(r.id);i&&this.emit("click",this,r,i)}}}});h(this,"handleDocumentMouseDown",e=>{e.target instanceof Element&&(this.isInCommandBar(e.target)||this.close())});h(this,"handleHidden",()=>{this.close(),this.emit("close",this),xm(this.id)});h(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&A(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&Im(this.id)});h(this,"handleItemMouseEnter",e=>{const o=this.getParentCommandItemElement(e.target);if(!o)return;const r=this.getItemElementId(o),i=this.getItemById(r);if(this.selectItem(r),i.manualShowChildren)return;const s=i.childrenMenuId||"";this.showSubCommandBar(s)});h(this,"handleItemMouseLeave",e=>{var r,i;const o=this.getParentCommandItemElement(e.target);!o||((i=(r=this.subBar)==null?void 0:r.parentItem)==null?void 0:i.id)!==this.getItemElementId(o)&&(z(o,"selected"),this.emit("selectionChange",this,""))});h(this,"handleItemClick",e=>{const o=this.getParentCommandItemElement(e.target);if(!o)return;const r=this.getItemElementId(o),i=this.items.find(s=>s.id===r);if(!!i&&!(i.states&&i.states.indexOf("disabled")!==-1)){if(i.children&&i.children.length>0&&i.manualShowChildren){this.showSubCommandBar(i.childrenMenuId);return}i.element||(this.emit("click",this,i,o),this.options.autoClose&&this.close())}});h(this,"handleWheel",e=>{if(!this.options.disablePageScroll&&!document.querySelector(".editor-disable-scroll"))return;const o=e.target;if(!o||!(o instanceof Node))return;const r=o instanceof HTMLElement?o:o.parentElement;if(!r)return;const i=We(r);if(!It(this.content,i)){e.stopPropagation(),e.preventDefault();return}e.deltaY<0?i.scrollTop===0&&(e.stopPropagation(),e.preventDefault()):e.deltaY>0&&i.scrollTop+i.clientHeight>=i.scrollHeight&&(e.stopPropagation(),e.preventDefault())});this.id=(i=r==null?void 0:r.id)!=null?i:N(),this.options={...Bw,...r},this.items=e,this.parentItem=(s=r==null?void 0:r.parentItem)!=null?s:null,this.closeable=o!=null?o:null,this.content=this.createCommandBarContent(e)}close(){this.subBar&&this.subBar.close(),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}click(e,o){this.emit("click",this,e,o)}createPopperOptions(){var r;const e={modifiers:[]},o=this.options.overflowBoundary;return o&&((r=e==null?void 0:e.modifiers)==null||r.push({name:"flip",options:{boundary:o,fallbackPlacements:["top","bottom"]}})),e}destroy(){var e;this.close(),this.removeAllListeners(),(e=this.subBar)==null||e.destroy(),this.subBar=null,this.closeable=null,this.content.removeEventListener("wheel",this.handleWheel)}get isSubCommandBar(){return!!this.parentItem}updateItems(e){var r;this.subBar&&e.findIndex(s=>{var l,c;return s.id===((c=(l=this.subBar)==null?void 0:l.parentItem)==null?void 0:c.id)})===-1&&((r=this.subBar)==null||r.destroy(),this.subBar=null),this.items=e;const o=this.createCommandBarContent(e);this.content.innerHTML="",Array.from(o.children).forEach(i=>{this.content.appendChild(i)})}get popper(){return this.content.closest("[data-tippy-root]")}getSelectedItemIndex(){const e=this.getSelectedItem();return e?this.items.indexOf(e):-1}getPrevItemIndex(e){if(e<=0)return this.items.length-1;let o=e-1;for(;;){const r=this.items[o].type;if(r!=="separator"&&r!=="section")return o;if(o-=1,o<=0)return this.items.length-1}}getNextItemIndex(e){let o=e+1;for(;;){if(!this.items[o])return this.getNextItemIndex(-1);const r=this.items[o].type;if(r!=="separator"&&r!=="section")return o;if(o+=1,o>this.items.length-1)return 0}}clearSelectedItem(){const e=this.getSelectedItem();if(!e)return;const o=this.getItemElementById(e.id);o&&z(o,"selected")}selectItem(e){const o=this.getSelectedItem();if(o){if(o.id===e)return;const i=o.id,s=this.getItemElementById(i);s&&z(s,"selected")}const r=this.getItemElementById(e);r?(A(r,"selected"),this.emit("selectionChange",this,r.getAttribute("data-id")||""),r.scrollIntoView({block:"nearest"})):this.emit("selectionChange",this,"")}showSubCommandBar(e){var s,l;const o=this.getSelectedItem();if(!o)return;if(this.subBar){if(((s=this.subBar.parentItem)==null?void 0:s.id)===o.id){o.manualShowChildren&&this.subBar.close();return}this.subBar.destroy(),this.subBar=null}if(!o.children)return;const r=this.getItemElementById(o.id);if(!r)return;const i=Bf.createSubCommandBar(o,(l=this.closeable)!=null?l:this,e?{id:e}:{});this.subBar=i,this.subBar.on("click",(c,a,u)=>{this.emit("click",c,a,u)}),this.subBar.on("close",()=>{var c;(c=this.subBar)==null||c.destroy(),this.subBar=null,z(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),A(r,"active")}isInCommandBar(e){if(!e||!(e instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&It(o,e)||It(this.content,e)?!0:this.subBar?this.subBar.isInCommandBar(e):!1}createCommandItem(e){var i,s,l,c;let o=(i=this.options.itemElementTag)!=null?i:"div";e.element&&(o="div");const r=b(o,["command-item"],null);return r.setAttribute("data-id",e.id),e.type==="separator"?r.classList.add("separator"):e.type==="section"?(r.classList.add("section","text"),e.element&&(typeof e.element=="function"?r.appendChild(e.element(e)):r.appendChild(e.element))):((s=e.states)!=null&&s.includes("selected")&&r.classList.add("selected"),(l=e.states)!=null&&l.includes("checked")&&r.classList.add("checked"),(c=e.states)!=null&&c.includes("disabled")&&r.classList.add("disabled"),r.onclick=this.handleItemClick,r.onmouseenter=this.handleItemMouseEnter,r.onmouseleave=this.handleItemMouseLeave,e.element?typeof e.element=="function"?r.appendChild(e.element(e)):r.appendChild(e.element):r.classList.add("standard")),this.initItemElement(e,r),r}getItemById(e){const o=this.items.find(r=>r.id===e);return d(jr,o,`can not find command item for id: ${e}`),o}getSelectedItem(){const e=this.content.querySelector(":scope >.editor-command-bar >.command-item.selected");if(e){const o=this.getItemElementId(e),r=this.items.find(i=>i.id===o);return d(jr,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(e){const o=e.getAttribute("data-id");return d(jr,o,"no data-id attribute"),o}getItemElementById(e){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${e}"]`);return d(jr,o,`no exists command item, id=${e}`),o}getParentCommandItemElement(e){if(!e||!(e instanceof Element))return null;if(nt(e,"command-item"))return e;const o=e.closest(".command-item");return o||null}createCommandBarContent(e){this.content&&this.content.removeEventListener("wheel",this.handleWheel);const o=b("div",["editor-command-bar-root"],null),r=b("div",["editor-command-bar"],o);return e.forEach(i=>{var l;const s=this.createCommandItem(i);r.appendChild(s),i.element&&i.setCloseable&&i.setCloseable((l=this.closeable)!=null?l:this)}),this.initCommandBarElement(r),o.addEventListener("wheel",this.handleWheel,{passive:!1}),o}getSubBarOptions(e){var o;return{placement:(o=e.childrenPlacement)!=null?o:"right-start"}}static registerManualCommandBar(e,o){this.commandBarCreators.set(e,o)}static createSubCommandBar(e,o,r){var l;d(jr,e.children&&e.children.length>0,"no item children");const i=(l=e.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return d(jr,s,`no creator for command type: ${i}`),s(e,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let Hr=Bf;h(Hr,"commandBarCreators",new Map),w("ui-command-bar");class gc extends Hr{constructor(){super(...arguments);h(this,"tippyInstance",null)}manualShow(e,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=g7.default(e,{interactive:!0,content:this.content,trigger:"manual",triggerTarget:null,hideOnClick:!1,placement:(r=o==null?void 0:o.placement)!=null?r:"bottom-start",maxWidth:650,arrow:this.options.tippyArrow,appendTo:document.body,onShow:this.handleShow,onHidden:this.handleHidden,theme:o==null?void 0:o.theme,getReferenceClientRect:o==null?void 0:o.getReferenceClientRect,offset:(i=o==null?void 0:o.offset)!=null?i:[0,0],popperOptions:this.createPopperOptions()}),o!=null&&o.point){const{x:s,y:l}=o.point;this.tippyInstance.setProps({getReferenceClientRect:()=>new DOMRect(s,l,0,0)})}this.clearSelectedItem(),this.tippyInstance.show(),this.parentItem||(document.addEventListener("keydown",this.handleDocumentKeydown),document.addEventListener("mousedown",this.handleDocumentMouseDown)),this.popper&&this.options.id&&this.popper.setAttribute("data-command-bar-id",this.options.id)}}close(){var e;super.close(),this.isVisible&&((e=this.tippyInstance)==null||e.hide())}destroy(){var e;(e=this.tippyInstance)==null||e.destroy(),this.tippyInstance=null,super.destroy()}getCommandBarRoot(){return this.content.closest("[data-tippy-root]")}get isVisible(){var e,o;return(o=(e=this.tippyInstance)==null?void 0:e.state.isVisible)!=null?o:!1}get popper(){return this.content.closest("[data-tippy-root]")}}const q2=w("ui-base");class ms extends gc{constructor(t,e){var i;const r=[{id:(i=e==null?void 0:e.id)!=null?i:`popup-${N()}`,name:"",element:t}];super(r,void 0,{disablePageScroll:!0})}initCommandBarElement(t){A(t,"popper")}initItemElement(t,e){}get popupContent(){const t=this.items[0];d(q2,t,"no dialog item");const e=typeof t.element=="function"?t.element(t):t.element;return d(q2,e,"no item element"),e}}const po=w("filterable-list");function Ew(n){var e;const t=b("div",["list-item"],null);return t.setAttribute("data-id",n.id),t.appendChild(b("div",["list-item-text"],null,n.name)),(e=n.states)!=null&&e.includes("selected")&&A(t,"selected"),t}function W2(n){const t=b("div",["list-root"],null);return n.forEach(e=>{t.appendChild(Ew(e))}),t}function G2(n,t){let e=n;return t&&(e=n.map(o=>({...o,states:o.id===t?["selected"]:void 0}))),e}function Iw(n,t){const e=b("div",["filterable-list"],null),o=b("div",["filter"],e),r=b("div",["filter-container"],o),i=b("input",["filter-input"],r);t&&t.placeholder&&(i.placeholder=t.placeholder);const s=b("div",["list"],e),l=W2(G2(n,t==null?void 0:t.initialSelectedId));return s.appendChild(l),e}function Z2(n,t,e){const o=n.querySelector(".list");d(po,o,"no list root");const r=W2(G2(t,e)),i=o.querySelector(".list-root");if(d(po,i,"no exists menu"),Mi(i,r),e){const s=o.querySelector(".list-item.selected");s&&(d(po,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class xw{constructor(t,e){h(this,"root");h(this,"visibleItems");h(this,"selectedId");h(this,"filter","");h(this,"onSelected",null);h(this,"handleKeydown",t=>{this.processKeyDown(t)});h(this,"handleInputChanged",()=>{const t=this.root.querySelector(".filter-input");d(po,t,"no input");const e=t.value.toLocaleLowerCase();this.setFilter(e)});h(this,"handleClick",t=>{this.processClick(t)});var o;this.items=t,this.options=e,this.root=Iw(t,e),this.bindEvents(),this.selectedId=(o=e==null?void 0:e.initialSelectedId)!=null?o:"",this.visibleItems=t}bindEvents(){const t=this.root.querySelector(".filter-input");d(po,t,"no input"),t.addEventListener("keyup",this.handleInputChanged),t.addEventListener("keydown",this.handleKeydown),this.root.addEventListener("click",this.handleClick)}unbindEvents(){const t=this.root.querySelector(".filter-input");d(po,t,"no input"),t.removeEventListener("keyup",this.handleInputChanged),t.removeEventListener("keydown",this.handleKeydown),this.root.removeEventListener("click",this.handleClick)}destroy(){this.unbindEvents(),this.onSelected=null}getSelectedIndex(){return this.selectedId?this.visibleItems.findIndex(t=>t.id===this.selectedId):-1}setSelectedId(t){this.selectedId=t,Z2(this.root,this.visibleItems,t)}focus(){const t=this.root.querySelector(".filter-input");d(po,t,"no input"),t.focus()}reset(){this.setFilter("");const t=this.root.querySelector(".filter-input");d(po,t,"no input"),t.value=""}setFilter(t){this.filter!==t&&(this.filter=t,this.visibleItems=this.items.filter(e=>e.name.toLocaleLowerCase().includes(t)),Z2(this.root,this.visibleItems,this.selectedId))}processClick(t){var s,l;const e=t.target;if(!(e instanceof HTMLElement))return;const o=e.closest(".list-item");if(!o)return;const r=(s=o.getAttribute("data-id"))!=null?s:"",i=(l=this.visibleItems.find(c=>c.id===r))!=null?l:null;this.onSelected&&this.onSelected(this,i)}processKeyDown(t){var e;if(t.key==="ArrowUp"){let o=this.getSelectedIndex();o===-1?o=this.visibleItems.length-1:o>0&&(o-=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(t.key==="ArrowDown"){let o=this.getSelectedIndex();o===-1?o=0:o<this.visibleItems.length-1&&(o+=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(t.key==="Enter"){const o=(e=this.visibleItems.find(r=>r.id===this.selectedId))!=null?e:null;this.onSelected&&this.onSelected(this,o)}}}class Tw extends xw{constructor(e,o,r){super(e,r);h(this,"popup");h(this,"onShow",null);h(this,"onHide",null);h(this,"custom",null);h(this,"handleShow",()=>{this.onShow&&this.onShow(this)});h(this,"handleHide",()=>{this.onHide&&this.onHide(this)});h(this,"handleShown",()=>{this.focus()});this.popup=new ms(this.root)}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(e){this.reset(),this.popup.manualShow(e,{theme:"dropdown-list"}),this.focus()}processKeyDown(e){super.processKeyDown(e),(e.key==="Esc"||e.key==="Enter")&&this.popup.close()}processClick(e){super.processClick(e);const o=e.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.popup.close()}}const iz="",sz="";function Sw(n,t){const e=document.createElement("div");e.classList.add("toast","show"),t!=null&&t.theme&&e.setAttribute("data-theme",t.theme),t!=null&&t.id&&e.setAttribute("data-id",t.id),t!=null&&t.html?e.innerHTML=n:e.textContent=n,t!=null&&t.position&&(e.style.left=`${t.position.x}px`,e.style.top=`${t.position.y}px`,e.classList.add("positioned")),document.body.appendChild(e),setTimeout(()=>{e.classList.remove("show"),setTimeout(()=>{e.remove()},500)},(t==null?void 0:t.duration)||3e3)}const Y2=`<?xml version="1.0" ?>
27
+ `)}const vv=w("get-text-position");function Lr(n,t){const e=t!=null?t:n.selection.range.start;e instanceof qt||d(vv,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=J(r),s=H(r),l=U(s),{offset:c}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:c}}const Wi=w("insert-text");function Ip(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(d(Wi,r,"no block data"),d(Wi,r.text,"no block text"),de(r.text)===0)return d(Wi,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=Gt(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function kv(n,t,e){const o=H(t),r=U(o),i=J(t);return Ip(n,r,i,e)}function xp(n,t,e,o,r){const i=H(t),s=U(i),l=J(t),c=kv(n,t,e),a=Al(e,o,c!=null?c:null);return n.doc.localUpdateBlockText(s,l,a,r),ue(n,t)}function Tp(n,t,e,o){const r=H(t),i=U(r),s=J(t),l=Al(e," ",o);return n.doc.localUpdateBlockText(i,s,l),ue(n,t)}function ou(n,t,e,o,r){const i=n.doc.getBlockData(e,o);d(Wi,i,"no block data"),d(Wi,i.text,"no block text");const s=Ip(n,e,o,r),l=Al(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),ue(n,n.getBlockById(i.id))}function ru(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=Lr(n);ou(n,t,e,o,r)}const Gl=w("update-composition-text");function Sp(n){const t=n.selection.range.start;t instanceof qt||d(Gl,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);d(Gl,j(n,o),"not a text kind block");const r=H(o),i=U(r),s=J(o),l=n.doc.getBlockData(i,s);d(Gl,l,"no block data in doc"),d(Gl,l.text,"no text data in text block");const c=it(o);Dl(n,jo(o),e,c,l.text)}function Dp(n){eb(n)}function Mr(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const Zl=w("delete-block-text");function iu(n,t,e,o,r){d(Zl,j(n,t),"block is not a text kind block");const i=H(t),s=U(i),l=J(t),c=n.doc.getBlockData(s,l);d(Zl,c,"no block data in doc"),d(Zl,c.text,"no text data in text block");let a=e;re(t,e)||(a=lo(t,a));let u=e+o;d(Zl,u<=W(n,t),`invalid offset and count: ${e}, ${o}`),re(t,u)||(u=Vo(t,u));const f=u-a,m=Fg(a,f);return n.doc.localUpdateBlockText(s,l,m,r),f}const su=w("break-text-block");function Lp(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Rr(n,t,e,o){d(su,j(n,t),`block is not a text kind block: ${rt(t)}`),d(su,e>=0&&e<=W(n,t),`invalid offset: ${e}`);const r=H(t),i=U(r),s=J(t),l=o!=null&&o.copyBlockAttributes?Lp(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===W(n,t))){const C=e===0?s:s+1,v={...Un(""),...l,...o==null?void 0:o.newBlockData},B=At(n,t.id,0),y=Mr(n,i,C,v,B);return{block:t,newBlock:y}}d(su,re(t,e),"not a valid offset");const c=ue(n,t),{right:a}=be(c,e),u=de(a);u>0&&iu(n,t,e,u);const f={...Un(a),...l,...o==null?void 0:o.newBlockData},m=Mr(n,i,s+1,f,At(n,f.id,0));return{block:t,newBlock:m}}const yv=w("prepare-insert-new-block");function wv(n,t,e){if(t&&e!==void 0&&e!==null){const a=n.getContainerById(t),u=Mt(a);return d(yv,e>=0&&e<=u.length,`invalid blockIndex: ${e}`),{containerId:t,blockIndex:e}}const o=n.selection.range.start;if(!o.isSimple())return null;const r=n.getBlockById(o.blockId);if(t=U(H(r)),e=J(r),!j(n,r))return{containerId:t,blockIndex:e+1};const s=o.offset;if(s===0||s===W(n,r))return{containerId:t,blockIndex:s===0?e:e+1};const c=Rr(n,r,s).newBlock;return{containerId:t,blockIndex:J(c)}}const Bv=w("auto-insert-block");function Mp(n,t,e,o,r,i){const s=wv(n,e,o);d(Bv,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},c={anchor:l,focus:l};return Mr(n,s.containerId,s.blockIndex,t,r!=null?r:c,i)}const Ev=w("delete-block");function Yl(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{Yl(n,i,e)})}))}function lu(n,t,e){const o=H(t),r=U(o),i=J(t),s=n.doc.getBlockData(r,i);return d(Ev,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Wt(n,{anchor:e.start,focus:e.end})),s}function cu(n,t,e){return n.undoManager.runInGroup(()=>{const o=H(t);Ge(o)===1&&n.insertTextBlock("",U(o),0);let r=e?io(n,e):null;if(!r){const l=n.selection.range;yp(t,l)?r=wp(n,t):r=l}const i=lu(n,t,r),s=[];return Yl(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function Iv(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{Yl(n,r,e)}),n.doc.localDeleteChildContainers(e)}function Rp(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{Yl(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const au=w("merge-text-block");function Ap(n,t,e){d(au,j(n,t),"only text block can be merged"),d(au,j(n,e),"only text block can be merged");const o=co(n,t),r=co(n,e),i=o.text,s=r.text;d(au,i&&s,"block data has no text");const l=H(t),c=U(l),a=J(t),u=W(n,t),f=ou(n,s,c,a,u),m=At(n,t,de(i));return cu(n,e,m),f}const wn=w("clear-selected-contents");function Ql(n,t){d(wn,j(n,t.block),"not a text kind block");const{start:e,end:o}=t;d(wn,e.isSimple(),"not a simple block position"),d(wn,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;d(wn,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function Op(n,t,e){const o=U(t),r=Mt(t),i=e.focus?void 0:n.selection.range.toDocRange(),s=n.insertTextBlock("",o,0,{newRange:i});e.focus&&n.selection.selectBlock(s,0),r.reverse().forEach(l=>{n.deleteBlock(l)})}function xv(n,t){const{block:e,start:o,end:r}=t;if(j(n,e)){Ql(n,t);return}if(Te(e)||o.isSimple()){d(wn,r.isSimple(),"invalid range");const s=H(e),l=J(e),c=n.insertTextBlock("",U(s),l);n.selection.selectBlock(c,0),n.deleteBlock(e);return}d(wn,at(n,e),"invalid block kind"),d(wn,!o.isSimple()&&!r.isSimple(),"invalid range"),xr(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{Op(n,s,{focus:l===0})})}function Tv(n){const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(d(wn,e.length>0,"no selected block"),e.length===1){xv(n,e[0]);return}const o=e[0],r=o.block,i=H(r);d(wn,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(j(n,r)){Ql(n,o);const u=At(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(m=>n.deleteBlock(m.block)),j(n,l)){Ql(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(u);return}n.deleteBlock(l),n.selection.setRange(u);return}if(j(n,l)){Ql(n,s),e.slice(0,e.length-1).reverse().forEach(u=>n.deleteBlock(u.block)),n.selection.selectBlock(s.block,0);return}if(e.length===Ge(i)){Op(n,i,{focus:!0});return}const c=gt(r),a=dt(l);d(wn,c||a,"no prev or next block"),e.forEach(u=>n.deleteBlock(u.block))}function du(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),Tv(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}function _p(n,t,e){const o=H(t),r=U(o),i=J(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),ue(n,t)}function Np(n,t,e){const o=n.getBlockText(t),r=ie.diff(o,e);_p(n,t,r)}function Kl(n,t,e){const o=ue(n,t),r=typeof e=="string"?Go(e):e,i=ie.diff(o,r);return _p(n,t,i)}const Gi=w("update-block-data");function Jl(n,t,e,o){const r=H(t),i=U(r),s=J(t),l=n.doc.getBlockData(i,s),c={insert:{},delete:[]},a=new Set(Object.keys(l)),u=new Set(Object.keys(e));return a.forEach(m=>{if(!u.has(m)){if(m==="id"||m==="type"||m==="text")return;Gi.debug(`delete key: ${m}`),c.delete.push(m)}}),Object.entries(e).forEach(([m,C])=>{d(Gi,m!=="id"&&m!=="type",`invalid block data delta, ${m}`);const v=l[m];if(C==null){v!=null&&(Gi.debug(`delete key: ${m}`),c.delete.push(m));return}v!==C&&(cl.default(v,C)||m==="text"&&ie.diff(v,C).length===0||(a.has(m)?(Gi.debug(`replace key: ${m}`),c.delete.push(m)):Gi.debug(`insert key: ${m}`),c.insert[m]=C))}),n.doc.localUpdateBlockData(i,s,c,o),co(n,t)}function $p(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function uu(n,t,e){if(!at(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=xe(n,t).getChildContainers(n,t)[0],i=Vt(r);uu(n,i,e)}function Yo(n){const t=[];let e={};return n.forEach(o=>{t.push(...o.blocks.root);const{root:r,...i}=o.blocks;e={...e,...i}}),{blocks:{...e,root:t},meta:{},comments:{}}}const Zi=w("clone-block");function ao(n,t,e,o){const r=n.getBlockClass(e.type);if(r.blockToDoc)return r.blockToDoc(t,e,(u,f)=>(d(Zi,e!==f,"invalid child block"),ao(n,u,e,o)));let i={};const s=new Map,l=Y.default(e);l.children&&(l.children=l.children.map(u=>{const f=N(),m=t.blocks[u];d(Zi,Array.isArray(m),"invalid child blocks");const C=m.map(S=>ao(n,t,S,o)),v=Yo(C),{root:B,...y}=v.blocks;return i={...i,...y},i[f]=v.blocks.root,s.set(u,f),f}));const c=Array.from(s.entries()),a=u=>{for(const f of c){const[m,C]=f;{const v=`${m}/`;if(u.startsWith(v)){const B=u.substring(v.length),y=`${C}/${B}`;return Zi.debug(`replace key: ${u} -> ${y}`),y}}{const v=`${m}_`;if(u.startsWith(v)){const B=u.substring(v.length),y=`${C}_${B}`;return Zi.debug(`replace key: ${u} -> ${y}`),y}}}return u};return Array.from(Object.entries(l)).forEach(([u,f])=>{const m=a(u);m!==u&&delete l.key,l[m]=f}),l.id=N(),o&&(o.blockIdMap.set(e.id,l.id),s.forEach((u,f)=>o.containerIdMap.set(f,u))),{blocks:{root:[l],...i},meta:{},comments:{}}}function hu(n,t,e,o){const r=t.blocks[e];d(Zi,Array.isArray(r),"invalid child blocks");const i=r.map(l=>ao(n,t,l,o));return Yo(i)}function fu(n,t,e){const o=t.blocks.root.map(r=>ao(n.editorBlocks,t,r,e));return Y.default(Yo(o))}const Pp=w("insert-doc");function jp(n,t,e,o,r){if(at(n,t)){Pp.warn("failed to insert doc into a complex block");return}const i=fu(n,o,r),s=H(t),l=J(t),c=U(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var I,M,R;Object.entries(i.blocks).forEach(([$,Z])=>{$!=="root"&&n.doc.localInsertChildContainer($,Z)});const a=i.blocks.root;if(Te(t)){n.deleteBlock(t);let $;a.reverse().forEach(Z=>{const ot=n.insertBlock(c,l,Z);$||($=ot)}),$&&n.selection.selectBlock($,W(n,$));return}if(d(Pp,j(n,t),"not a text block"),Tt(n,t)){const $=J(t);let Z;a.forEach((ot,st)=>{const mt=n.insertBlock(c,$+st,ot);st===a.length-1&&(Z=mt)}),Z&&n.selection.selectBlock(Z,W(n,Z));return}if(a.length===1){const $=a[0];if(_i(n,$.type)){n.insertTextToBlock(t,e,(I=$.text)!=null?I:[]);return}n.breakTextBlock(t,e),n.insertBlock(c,l+1,$);return}const u=e===W(n,t),f=e===0,m=a[0],C=a[a.length-1];let v;!u&&!f?v=n.breakTextBlock(t,e,{forceInsertAfter:!0}):v=t;const B=f?l:l+1;u?(v=n.insertBlock(c,l+1,C),n.selection.selectBlock(v,W(n,v))):(n.selection.selectBlock(v,0),_i(n,C.type)?n.insertTextToBlock(v,0,(M=C.text)!=null?M:[]):n.insertBlock(c,B,C));const y=n.selection.range;let S=B;_i(n,m.type)?f?(n.insertBlock(c,B,m),S+=1):n.insertTextToBlock(t,e,(R=m.text)!=null?R:[]):(n.insertBlock(c,B,m),S+=1),a.slice(1,a.length-1).reverse().forEach($=>{n.insertBlock(c,S,$)}),n.selection.setRange(y)}),n.doc.endBatchUpdate()}function mu(n,t,e,o,r){const i=fu(n,o,r),s=U(t),l=[];return n.undoManager.runInGroup(()=>{Object.entries(i.blocks).forEach(([a,u])=>{a!=="root"&&n.doc.localInsertChildContainer(a,u)}),i.blocks.root.reverse().forEach(a=>{const u=n.insertBlock(s,e,a);l.push(u)})}),l}function Hp(n,t,e){const o=Ge(t);mu(n,t,o,e);for(let r=0;r<o;r++){const i=Vt(t);n.deleteBlock(i)}}const Yi=w("add-text-attribute");function Sv(n,t,e,o){const{start:r,end:i}=e;d(Yi,r.blockId===i.blockId&&r.blockId===q(t),"invalid range"),d(Yi,o,"invalid attribute name");const s=n.getBlockText(t),l=Dr(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function Fp(n,t,e,o,r){const{start:i,end:s}=e;d(Yi,i.blockId===s.blockId&&i.blockId===q(t),"invalid range"),d(Yi,o,"invalid attribute name");const l=n.getBlockText(t),c=_l(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,c),c}function Ar(n,t,e,o,r){const{start:i,end:s}=e;d(Yi,i.blockId===s.blockId&&i.blockId===q(t),"invalid range");const l=n.getBlockText(t),c=Qg(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,c),c}function zp(n,t,e,o){const r=tn(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:c}=i;if(!j(n,s))return;if(Tt(n,s)){o(n,q(s),t,e);return}const a=Wt(n,{anchor:l,focus:c});t==="color"||t==="backgroundColor"?Ar(n,s,a,t,e):(Ar(n,s,a,"color",null),Ar(n,s,a,"backgroundColor",null))})})}function Up(n,t,e){const o=tn(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!j(n,i))return;if(Tt(n,i)){(t==="clearColor"||t==="clearAll")&&e(n,q(i),"color",null),(t==="clearBackground"||t==="clearAll")&&e(n,q(i),"backgroundColor",null);return}const c=Wt(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&Ar(n,i,c,"color",null),(t==="clearBackground"||t==="clearAll")&&Ar(n,i,c,"backgroundColor",null)})})}function gu(n,t){const e=tn(n,{simpleBlockOnly:!0}).filter(s=>j(n,s.block));if(e.length===0)return[null,null];const o=s=>{if(W(n,s.block)===0)return t(n,q(s.block));const l=s.start,c=s.end,a=n.getBlockText(s.block);return Xg(l.offset,c.offset-l.offset,a)};let[r,i]=o(e[0]);return r===null&&i===null?[r,i]:(e.forEach(s=>{const[l,c]=o(s);l===null||r===null?r=null:r=l===r?r:null,c===null||i===null?i=null:i=c===i?i:null}),[r,i])}const ke=w("adjust-selection-pos");function Vp(n){const t=[];for(;n;){const e=H(n);if(t.unshift(e),pt(e))return t;const o=F(e);d(ke,o,"child container has not parent container"),n=o}d(ke,!1,"should not come here: getParentContainers")}function qp(n,t){for(;t;){const e=H(t);if(e===n)return t;const o=F(e);d(ke,o,"could not find parent block for a child container"),t=o}d(ke,!1,"no parent block in specified container")}function Dv(n,t){const e=Vp(n),o=Vp(t);d(ke,e.length>0&&o.length>0,"block has not parent container"),d(ke,e[0]===o[0],"root container does not equal");let r=e[0];for(let l=1;l<e.length||o.length;l++)if(e[l]!==o[l]){r=e[l-1];break}const i=qp(r,n),s=qp(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function Wp(n,t){let e=F(t);for(d(ke,e,"element is not in a block");e;){const o=H(e);d(ke,Ye(o),"not a child container");const r=F(o);if(d(ke,r,"child container has not parent block"),r===n)return o;e=r}d(ke,!1,"failed to find parent container in complex block")}function Xl(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof qt&&e instanceof qt?{anchor:t,focus:e}:(d(ke,t instanceof Je&&e instanceof Je,"both start and end are not simple or complex"),xl(n,o,t,e));const i=H(o),s=H(r);if(i===s)return t instanceof Je&&(t=P(o,0,"home")),e instanceof Je&&(e=P(r,W(n,r),"end")),d(ke,t instanceof qt,"not valid position type"),d(ke,e instanceof qt,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof qt&&e instanceof Je){const v=n.getContainerById(e.childContainerId);if(v===i)return{anchor:e,focus:e};const B=F(i);if(B&&B===F(v)){const y=wt(B,U(i)),S=wt(B,U(v));return xl(n,B,y,S)}}return null}const l=fl(o,r)>0,{newBlock1:c,newBlock2:a}=Dv(o,r);if(c===a){const v=c,B=Wp(v,o),y=Wp(v,r);return t=wt(c,U(B)),e=wt(c,U(y)),ke.debug(`select in complex block: ${B.id}, ${y.id}`),xl(n,v,t,e)}let u=l?W(n,c):0;c===o&&t instanceof qt&&(u=t.offset);let m=l?0:W(n,a);return a===r&&e instanceof qt&&(m=e.offset),t=P(c,u,l?"end":"home"),e=P(a,m,l?"home":"end"),{anchor:t,focus:e}}const Lv=w("move-complex-block-position");function Mv(n,t,e){const o=n.getBlockById(t.blockId);d(Lv,at(n,o),"is not a complex block");const r=xe(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?wt(o,U(s)):null}const Qi=w("move-simple-block-position");function Gp(n,t){const e=Se(n,t);d(Qi,e.length>0,"complex block has not any child container");const o=e[0];return Vt(o)}function Zp(n,t){const e=Se(n,t);d(Qi,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Qt(o)}function Yp(n,t,e){const o=e?Gp(n,t):Zp(n,t);return at(n,o)?Yp(n,o,e):o}function Rv(n,t){const e=n.getBlockById(t.blockId);return at(n,e)&&t.offset===0?Gp(n,e):wr(e)}function Av(n,t){const e=n.getBlockById(t.blockId);return at(n,e)&&t.offset===1?Zp(n,e):yr(e)}function pu(n){return n==="ArrowLeft"||n==="ArrowUp"}function Cu(n,t,e){const o=H(t);if(pt(o))return null;const r=F(o);d(Qi,r,"child container has not parent block"),d(Qi,at(n,r),"is not a complex block");const i=xe(n,r).getNextContainer(n,r,o,e);return i?pu(e)?Qt(i):Vt(i):Cu(n,r,e)}function Ov(n,t,e){const o=H(t);if(pt(o))return null;const r=F(o);if(d(Qi,r,"child container has not parent block"),pu(e)){const l=gt(r);if(l)return l}else{const l=dt(r);if(l)return l}const i=Cu(n,r,e);if(i)return i;let s=r;for(;!pt(H(s));)s=F(H(s));return pu(e)?gt(s):dt(s)}function _v(n,t,e){return!at(n,t)||xe(n,t).enableKeyboardSelect?t:Yp(n,t,e==="ArrowDown"||e==="ArrowRight")}function Nv(n,t,e){const o=n.getBlockById(t.blockId),i=bt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?Rv(n,t):Av(n,t);if(s||(s=Cu(n,o,e),s||(s=Ov(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!pt(H(o)))return null;const l=n.insertTextBlock("",U(n.rootContainer),Ge(n.rootContainer));return P(l,0,"home")}return null}if(s=_v(n,s,e),j(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return fb(n,s,o,t,l);if(e==="ArrowUp")return hb(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?P(s,W(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?P(s,0,"home"):null}function $v(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(j(n,r))return o;const i=dt(r);if(i)return P(i,0,"home");if(!pt(H(r))||n.readonly)return o;const s=n.insertTextBlock("",U(n.rootContainer),Ge(n.rootContainer));return P(s,0,"home")}function Pv(n,t,e){const o=n.selection.range;let r;if(o instanceof ce)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=$v(n,t,o):r=Nv(n,o.getFocusedPos(),t);else if(r=Mv(n,o.focus,t),e==="move"){const i=r!=null?r:o.focus,s=n.getContainerById(i.childContainerId);if(t==="ArrowLeft"||t==="ArrowUp"){const l=Qt(s);r=P(l,0,"home")}else{const l=Vt(s);r=P(l,W(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:Xl(n,o.anchor,r):null}function uo(n,t,e){const o=Pv(n,t,e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),(t==="ArrowLeft"||t==="ArrowRight")&&n.selection.updateLastCaretRect(),!0}function Qp(n){return uo(n,"ArrowLeft","move"),!0}function Kp(n){return uo(n,"ArrowRight","move"),!0}function Jp(n){return uo(n,"ArrowUp","move"),!0}function Xp(n){if(uo(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=H(t);if(pt(e)||Qt(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",U(o),Ge(o)),!0}function t0(n){return uo(n,"ArrowDown","select"),!0}function e0(n){return uo(n,"ArrowLeft","select"),!0}function n0(n){return uo(n,"ArrowRight","select"),!0}function o0(n){return uo(n,"ArrowUp","select"),!0}const r0=w("word-offset");function bu(n,t){const e=n.selection.range.focus;d(r0,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(Tt(n,o))return P(o,0,"home");if(e.offset===0||!j(n,o)){const s=gt(o);if(!s)return null;const l=P(s,W(n,s),"end");if(t==="select"&&j(n,s)){const c=Yd(n,s,l.offset);return P(s,c,"normal")}return l}const r=Yd(n,o,e.offset);return P(o,r,"normal")}function vu(n,t){const e=n.selection.range.focus;d(r0,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(Tt(n,o))return P(o,0,"end");if(e.offset===W(n,o)||!j(n,o)){const s=dt(o);if(!s)return null;const l=P(s,0,"home");if(t==="select"&&j(n,s)){const c=Qd(n,s,l.offset);return P(s,c,"end")}return l}const r=Qd(n,o,e.offset);return P(o,r,"normal")}function i0(n){if(!n.selection.range.focus.isSimple())return!1;const e=bu(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function s0(n){if(!n.selection.range.focus.isSimple())return!1;const e=vu(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function l0(n){if(!n.selection.range.focus.isSimple())return!1;const e=bu(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function c0(n){if(!n.selection.range.focus.isSimple())return!1;const e=vu(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}w("find-block");function ku(n,t){if(!at(n,t))return t;const o=xe(n,t).getChildContainers(n,t)[0],i=Mt(o)[0];return ku(n,i)}function yu(n,t){if(!at(n,t))return t;const e=xe(n,t).getChildContainers(n,t),o=e[e.length-1],r=Mt(o),i=r[r.length-1];return yu(n,i)}function a0(n){const t=yu(n,Qt(n.rootContainer)),e=P(t,W(n,t),"end");return n.selection.setSelection(e),!0}function d0(n){const t=ku(n,n.getFirstBlock()),e=P(t,0,"home");return n.selection.setSelection(e),!0}function u0(n){const t=ku(n,n.getFirstBlock()),e=P(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function wu(n){const t=yu(n,Qt(n.rootContainer)),e=P(t,W(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}const h0=w("line-offset");function f0(n){const t=n.selection.range.focus;d(h0,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!j(n,e))return P(e,0,"home");let r=Ng(e,t).start;const{next:i}=Sl(e,r);return i&&_e(i)&&Ri(i)==="br"&&(r+=1),P(e,r,"home")}function m0(n){const t=n.selection.range.focus;d(h0,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===W(n,e)||!j(n,e))return P(e,W(n,e),"end");const o=Ng(e,t);return P(e,o.end,"end")}function g0(n){if(!n.selection.range.focus.isSimple())return!1;const e=f0(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function p0(n){if(!n.selection.range.focus.isSimple())return!1;const e=m0(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function C0(n){if(!n.selection.range.focus.isSimple())return!1;const e=f0(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function b0(n){if(!n.selection.range.focus.isSimple())return!1;const e=m0(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const v0=w("find-block-position");function jv(n,t,e,o){d(v0,at(n,t),"is not a complex block");const r=xe(n,t).getChildContainers(n,t);d(v0,r.length>0,"complex block has not any child container");const i=Ke(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,c=Ig(n,t,s,l);return Bu(n,c,e,o)}function Bu(n,t,e,o){if(at(n,t))return jv(n,t,e,o);const r=q(t);let i=Number.MAX_SAFE_INTEGER;const s=Ke(n,e,o),l=s.left+s.width/2,c=s.top+s.height/2;let a=P(r,0,"home");const u=W(n,t);for(let f=0;f<=u;f++){const m=P(r,f,"normal"),C=Ke(n,t,m),v=Cn(C,l,c);v<i&&(i=v,a=m)}return a}const k0=w("page-offset");function Hv(n,t){const e=vp(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<dv(n))return n.getFirstBlock();const i=gt(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=gt(s)}return n.getFirstBlock()}function Fv(n,t){const e=vp(n)*.9,o=t.getBoundingClientRect(),r=uv(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=dt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=dt(l)}return n.getLastBlock()}function y0(n){const t=n.selection.range.focus;d(k0,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=Hv(n,e);let r;return o===n.getFirstBlock()?r=P(o,0,"home"):r=Bu(n,o,e,t),r}function w0(n){const t=n.selection.range.focus;d(k0,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=Fv(n,e);let r;return o===n.getLastBlock()?r=P(o,W(n,o),"end"):r=Bu(n,o,e,t),r}function B0(n){if(!n.selection.range.focus.isSimple())return!1;const e=y0(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function E0(n){if(!n.selection.range.focus.isSimple())return!1;const e=w0(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function I0(n){if(!n.selection.range.focus.isSimple())return!1;const e=y0(n);if(!e)return!1;const o=Xl(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}function x0(n){if(!n.selection.range.focus.isSimple())return!1;const e=w0(n);if(!e)return!1;const o=Xl(n,n.selection.getAnchorPos(),e);if(!o)return!1;const{anchor:r,focus:i}=o;return n.selection.setSelection(r,i),n.selection.updateLastCaretRect(),!0}const Ki=w("select-all");function T0(n,t){const e=Vt(n),o=Qt(n);return t.start.offset===0&&t.start.blockId===q(e)&&t.end.offset===W(t.getEditor(),o)&&t.end.blockId===q(o)}function zv(n,t){const e=t.getEditor(),o=xe(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=q(n);return t.start.blockId===s&&t.start.childContainerId===U(r)&&t.end.blockId===s&&t.end.childContainerId===U(i)}function Uv(n,t){d(Ki,t,"no parent block"),d(Ki,at(n,t),"not a complex block");const e=xe(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(Wt(n,{anchor:wt(t,U(o)),focus:wt(t,U(r))}))}function S0(n,t){const e=H(t);Eu(n,e)}function D0(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&j(n,t)){const r=e.start,i=e.end,s=W(n,t);if(r.offset>0||i.offset<s)return n.selection.selectBlock(t,0,s),!1}return A(n.rootContainer,"select-all"),S0(n,Vt(n.rootContainer)),!1}return d(Ki,!e.isSimple(),"invalid range type"),zv(t,e)?(S0(n,t),!1):(d(Ki,t,"no parent block"),d(Ki,at(n,t),"not a complex block"),Uv(n,t),!0)}function Eu(n,t){const e=Mt(t),o=e[0],r=e[e.length-1],i=P(o,0,"home"),s=P(r,W(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function L0(n){wu(n),n.focus()}const Iu=w("selected-block-to-doc");function M0(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{M0(n,i,e)}),e.blocks[o]=Y.default(r)})}function tc(n,t,e={ignoreLockInfo:!0}){const o=bt(n,t.block);if(o.selectionToDoc)return o.selectionToDoc(n,t);const r=Y.default(co(n,t.block));if(!e.ignoreLockInfo&&r.lock&&delete r.lock,j(n,t.block)){const s=t.start,l=t.end;if(d(Iu,r.text,"no block text"),s.offset===l.offset)return{blocks:{root:[{...r,text:[]}]},meta:{},comments:{}};const{middle:c}=Gt(r.text,s.offset,l.offset-s.offset);return{blocks:{root:[{...r,text:c}]},meta:{},comments:{}}}if(Te(t.block))return{blocks:{root:[r]},meta:{},comments:{}};d(Iu,at(n,t.block),"not complex block"),d(Iu,r.children,"no children");const i={blocks:{root:[r]},meta:{},comments:{}};return M0(n,r,i),i}function xu(n,t,e=!0){const o=P(t,0,"normal"),r=P(t,W(n,t),"end");return tc(n,{block:t,start:o,end:r},{ignoreLockInfo:e})}const Vv=w("block-to-doc");function qv(n,t){d(Vv,t.length>0,"invalid params, no blocks");const e=t.map(o=>xu(n,o));return Yo(e)}function Ji(n){const e=n.selection.range.getSelectedBlocks().map(o=>tc(n,o));return Yo(e)}function R0(n,t){const e=n.getContainerById(t),i=Mt(e).map(s=>({start:P(s,0,"home"),end:P(s,W(n,s),"end"),block:s})).map(s=>tc(n,s));return Yo(i)}const ec=w("editor-selection");class Wv{constructor(t){h(this,"editor");h(this,"caret");h(this,"_range");h(this,"lastCaretRect");h(this,"handleBlockDelete",(t,e,o,r)=>{if(o||r.child)return;const i=this.range;if(yp(e,i)){ec.debug("adjust selection because remote deleted current block");const s=wp(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=q(e);this.caret=new cv(t);const r=P(o,0,"normal");this._range=Wt(t,{anchor:r,focus:r}),this.lastCaretRect=null,this.editor.addListener("blockDeleted",this.handleBlockDelete),setTimeout(()=>{this.updateFocusedBlock(null)})}destroy(){this.caret.destroy()}get range(){return this._range}get focusedBlock(){return this.getFocusedBlock()}get startBlock(){return this.getStartBlock()}get endBlock(){return this.getEndBlock()}getFocusedBlock(){const t=this.range.focus;return this.editor.getBlockById(t.blockId)}getStartBlock(){const t=this.range.start;return this.editor.getBlockById(t.blockId)}getEndBlock(){const t=this.range.end;return this.editor.getBlockById(t.blockId)}selectBlock(t,e,o){const r=P(t,e,"normal");let i;o&&(i=P(t,o,"normal")),this.setSelection(r,i)}setSelection(t,e,o){if(e||(e=t),this.verifyPos(t),this.verifyPos(e),!this.selectionChanging(t,e))return this.range;const r=Wt(this.editor,{anchor:t,focus:e});if(this.range.isEqual(r))return this.range;const i=this._range;return this._range=r,this.selectionChanged(),this.updateFocusedBlock(i),nt(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!pv(this.editor,r))&&z(this.editor.rootContainer,"select-all"),o!=null&&o.noScroll||this.scrollIntoView(),this.range}setRange(t,e){return this.setSelection(t.anchor,t.focus,e)}updateSelection(){this.caret.update(),av(this.editor)}getFocusedPos(){return this.range.focus}getAnchorPos(){return this.range.anchor}selectionChanging(t,e){return!0}selectionChanged(){this.updateSelection(),this.editor.emit("selectionChanged",this.editor)}updateLastCaretRect(){const t=this.range.focus;if(!Ir(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Ke(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){gv(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=W(this.editor,e)||d(ec,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||d(ec,!1,"invalid complex block position, no container found")}}updateFocusedBlock(t){if(t&&this.range.start.blockId===t.start.blockId)return;let e;t&&t.start.blockId===t.end.blockId&&(e=this.editor.findBlockById(t.start.blockId));let o;(this.range.isCollapsed()||!this.range.isSimple()||this.range.start.blockId===this.range.end.blockId)&&(o=this.editor.getBlockById(this.range.start.blockId));let r=!1;e&&nt(e,"focused")&&(z(e,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,e!=null?e:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(t){const e=Ji(this.editor);return t==="text"?Wl(this.editor,e):t==="markdown"?qi(this.editor,e):Ep(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{z(t,"focused"),z(t,"child-focused")})}setBlockFocused(t){if(nt(t,"focused"))return!1;A(t,"focused");let e=H(t);for(;Ye(e);){const o=F(e);d(ec,o,"parent block not found"),A(o,"child-focused"),e=H(o)}return!0}}function Gv(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);!e||n.selection.selectBlock(e,0,W(n,e))}function Zv(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!j(n,e))return;let o=bu(n,"select"),r=vu(n,"select");if(!o||!r)return;const i=t.blockId;o.blockId!==i&&(o=P(e,0,"home")),r.blockId!==i&&(r=P(e,W(n,e),"end")),n.selection.setSelection(o,r)}class Yv{constructor(t){h(this,"editor");h(this,"startPos",null);h(this,"lastCaretRect");h(this,"mouseDownEvent",null);h(this,"handleMouseDown",t=>{this.mouseDownEvent=t;const e=Tg(this.editor,t.x,t.y);if(e){if(e instanceof Xe)return;const o=this.editor.selection.range;if(t.shiftKey&&o.isSimple()){const r=o.anchor;this.editor.selection.setSelection(r,e.focus),this.startPos=e.start}else this.editor.selection.setSelection(e.anchor,e.focus),this.startPos=e.start;this.editor.selection.updateLastCaretRect()}});h(this,"handleMouseMove",t=>{if(!this.startPos||!this.mouseDownEvent||Math.abs(this.mouseDownEvent.x-t.x)<3&&Math.abs(this.mouseDownEvent.y-t.y)<3)return;const e=Tl(this.editor,t.x,t.y);if(!e)return;const o=Xl(this.editor,this.startPos,e.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});h(this,"handleMouseUp",t=>{this.startPos=null});this.editor=t,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(t){Zv(this.editor)}handleTripleClick(t){Gv(this.editor)}}function Qv(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function Kv(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const A0=w("delete-text");function O0(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof qt||d(A0,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);d(A0,j(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!re(s,l-e)){const c=lo(s,l);e=l-c}}else if(t==="forward"&&l+e>W(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function _0(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const Jv=w("handle-backspace");function Tu(n,t){if(!Tt(n,t))return;const e=H(t);Ge(e)!==1&&n.deleteBlock(t)}function Xv(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(j(n,o))if(e.offset===0){if(_0(n,o))return;const r=gt(o);if(r)if(j(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(at(n,r)){Tu(n,o);const i=Ni(n,r);i?n.selection.selectBlock(i,W(n,i)):n.selection.selectBlock(r,0,W(n,r))}else Tu(n,o),d(Jv,Te(r),"prev block is not embed block"),n.selection.selectBlock(r,1);else{const i=H(o);if(Ye(i)){const s=wg(n,i);s&&(Tu(n,o),n.selection.selectBlock(s,W(n,s)))}}}else O0(n,"backward",1,null);else{const r=J(o),i=H(o);n.insertTextBlock("",U(i),r),n.deleteBlock(o)}}function tk(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(j(n,o))if(e.offset===W(n,o)){const r=dt(o);r&&(j(n,r)?n.mergeTextBlock(o,r,{focus:!0}):Tt(n,o)?n.deleteBlock(o,At(n,r,0)):n.deleteBlock(r))}else O0(n,"forward",1,null);else{const r=J(o),i=H(o);n.insertTextBlock("",U(i),r),n.deleteBlock(o)}}function ek(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const e=n.getFocusedBlock();if(j(n,e)){if(Tt(n,e)&&_0(n,e))return;const o=n.selection.range.start,r=n.breakTextBlock(e,o.offset,{copyBlockAttributes:!0});o.offset!==0?n.selection.selectBlock(r,0):n.selection.scrollIntoView()}else{const o=n.insertTextBlock();n.selection.selectBlock(o,0)}}function nk(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!j(n,o))return!1;const r=e.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:N(),box:!0,created:Date.now()}),!0}const ok=w("input-handler-actions");function rk(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(ek(n),!0))}function ik(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(tk(n),!0))}function sk(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Xv(n),!0))}function lk(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(nk(n),!0))}function ck(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t)}).catch(t=>{ok.error(t)}),!0)}function N0(n,t,e){if(t.type==="embed"){const s=t.embedData.src;s&&typeof s=="string"&&e.add(s);return}const o=t.text;o&&o.forEach(i=>{i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"&&e.add(i.attributes.src)});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{N0(n,l,e)})})}function ak(n,t){const e=new Set;return t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.getResources?i.getResources(r).forEach(s=>{e.add(s)}):N0(t,r,e)}),Array.from(e)}function Su(n,t){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${_o(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Du(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=ak(n,t),r={};o.forEach(c=>{const a=n.doc.buildResourceUrl(c,{withToken:!0});r[c]=a}),t.meta={...e,resources:r}}function dk(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let o=Ji(n);const r=e==null?void 0:e(n,t,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Du(n,o);const i=Vi(n,o),s=qi(n,o),l=Su(i,o);t.clipboardData.setData("text/html",l),t.clipboardData.setData("text/plain",s),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(o))}function uk(n){if(n.selection.range.isCollapsed())return;const t=Ji(n);Du(n,t);const e=Vi(n,t),o=Su(e,t),r=qi(n,t),i=new Blob([o],{type:"text/html"});vl([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:i}])}async function nc(n,t){const e=xu(n,t,!1);Du(n,e);const o=Vi(n,e),r=qi(n,e),i=Su(o,e);return vl([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}function hk(n){return uk(n),du(n),!0}const oc={ArrowDown:Xp,ArrowUp:Jp,ArrowLeft:Qp,ArrowRight:Kp,"Shift+ArrowDown":t0,"Shift+ArrowUp":o0,"Shift+ArrowLeft":e0,"Shift+ArrowRight":n0,"CtrlOrCmd+ArrowLeft":i0,"CtrlOrCmd+ArrowRight":s0,"CtrlOrCmd+Shift+ArrowLeft":l0,"CtrlOrCmd+Shift+ArrowRight":c0,"CtrlOrCmd+ArrowUp":d0,"CtrlOrCmd+ArrowDown":a0,"CtrlOrCmd+Shift+ArrowUp":u0,"CtrlOrCmd+Shift+ArrowDown":wu,"CtrlOrCmd+A":D0,Home:C0,End:b0,"Shift+Home":g0,"Shift+End":p0,PageUp:B0,PageDown:E0,"Shift+PageUp":I0,"Shift+PageDown":x0,"CtrlOrCmd+X":hk,"CtrlOrCmd+Z":Qv,"CtrlOrCmd+Shift+Z":Kv,Enter:rk,Delete:ik,Backspace:sk,"Shift+Enter":lk,"CtrlOrCmd+Shift+V":ck};function $0(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function P0(n,t,e){if(t.type==="embed"){const i=t.embedData,s=i.src;if(s&&typeof s=="string"){const l=e.get(s);l&&(i.src=l)}return}const o=t.text;o&&o.forEach(i=>{if(i.attributes&&i.attributes.src&&typeof i.attributes.src=="string"){const s=e.get(i.attributes.src);s&&(i.attributes.src=s)}});const r=t.children;r&&r.forEach(i=>{n.blocks[i].forEach(l=>{P0(n,l,e)})})}function j0(n,t,e){if(e.size===0)return;t.blocks.root.forEach(r=>{const i=n.editorBlocks.getBlockClass(r.type);i.replaceResources?i.replaceResources(r,e):P0(t,r,e)})}async function fk(n,t){const e=t.filter(i=>i.indexOf(":")===-1),o=await n.doc.addResources(e),r=new Map;if(e.length!==o.length)return r;for(let i=0;i<e.length;i++)r.set(e[i],o[i]);return r}function mk(n,t){var i,s;const o=t.meta.serverId;if(!o||typeof o!="string")return!1;const r=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i);return!(!r||r.serverId!==o)}async function gk(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(mk(n,t)){const s=Array.from(Object.keys(o));r=await fk(n,s),j0(n,t,r)}const i=new Map;Object.entries(o).forEach(([s,l])=>{r.get(s)===void 0&&s!==l&&i.set(s,l)}),i.size!==0&&j0(n,t,i)}async function pk(n,t){await gk(n,t),n.undoManager.runInGroup(()=>{n.clearSelectedContents();const{block:e,offset:o}=Lr(n);n.insertDoc(e,o,t)})}const Ck=["text/x-ones-editor-doc","image/*","text/html","text/plain","text/markdown","*"];function bk(n){let t;for(const e of Ck)if(t=n[e],t)break;return t||null}class vk{constructor(t){h(this,"editor");h(this,"handlers",[]);h(this,"onPasteText",async t=>{const e=new DataTransfer;e.setData("text/plain",t);const o=await this.editor.dataConverter.fromData(this.editor,e);o&&this.pasteDocs(o,null)});this.editor=t}onInsertText(t,e){if(!j(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=Lr(this.editor);this.handleBeforeInsertText(o,r,i,e)||(this.defaultInsertText(this.editor,o,r,i,e),this.handleAfterInsertText(o,r,i,e))}onKeyDown(t){if(this.handleBeforeKeyDown(t))return!0;const e=this.defaultHandleKeydown(this.editor,t);return this.handleAfterKeyDown(t)?!0:e}onChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleChanged&&o.handleChanged(this.editor,t)}}onRemoteChanged(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];o.handleRemoteChanged&&o.handleRemoteChanged(this.editor,t)}}onCompositionStart(t){this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:o,offset:r}=Lr(this.editor);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];s.handleCompositionStart&&s.handleCompositionStart(this.editor,e,o,r)}}onUpdateCompositionText(t,e,o){this.editor.updateCompositionText(e,o),this.editor.selection.caret.update();const{containerId:r,blockIndex:i,offset:s}=Lr(this.editor);for(let l=0;l<this.handlers.length;l++){const c=this.handlers[l];c.handleUpdateCompositionText&&c.handleUpdateCompositionText(this.editor,r,i,s,o)}}onCopy(t){dk(this.editor,t,(e,o,r)=>{for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeCopy){const l=s.handleBeforeCopy(this.editor,o,r);if(l===!0)return!0;if(typeof l=="object"&&l!=null)return l}}})}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;this.editor.dataConverter.fromData(this.editor,t.clipboardData).then(async o=>{o&&this.pasteDocs(o,t)})}onFocus(){A(this.editor.rootElement,"active")}onBlur(){z(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t)}removeHandler(t){const e=this.handlers.indexOf(t);e!==-1&&this.handlers.splice(e)}handleBeforeInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeInsertText&&s.handleBeforeInsertText(this.editor,t,e,o,r))return!0}return!1}handleAfterInsertText(t,e,o,r){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterInsertText&&s.handleAfterInsertText(this.editor,t,e,o,r))return!0}return!1}handleBeforeKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}handleAfterKeyDown(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeKeyDown&&r.handleBeforeKeyDown(this.editor,t))return!0}const e=this.defaultHandleKeydown(this.editor,t);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterKeyDown&&r.handleAfterKeyDown(this.editor,t))return!0}return e}defaultInsertText(t,e,o,r,i){ru(this.editor,i)}defaultHandleKeydown(t,e){return $0(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];if(o.handleBeforePasteDoc&&await o.handleBeforePasteDoc(this.editor,t))return}await pk(this.editor,t);for(let e=0;e<this.handlers.length;e++){const o=this.handlers[e];if(o.handleAfterPasteDoc&&await o.handleAfterPasteDoc(this.editor,t))return}}async pasteDocs(t,e){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePaste&&await i.handleBeforePaste(this.editor,e,t))return}const o=bk(t);if(!!o){await this.pasteDoc(o);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPaste&&await i.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function kk(n,t,e){const o=kr(t,e);return o.remove(),o}w("copy-dom-attributes");const H0=["onabort","onanimationcancel","onanimationend","onanimationiteration","onanimationstart","onauxclick","onblur","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextmenu","oncuechange","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","onformdata","ongotpointercapture","oninput","oninvalid","onkeydown","onkeypress","onkeyup","onload","onloadeddata","onloadedmetadata","onloadstart","onlostpointercapture","onmousedown","onmouseenter","onmouseleave","onmousemove","onmouseout","onmouseover","onmouseup","onpause","onplay","onplaying","onpointercancel","onpointerdown","onpointerenter","onpointerleave","onpointermove","onpointerout","onpointerover","onpointerup","onprogress","onratechange","onreset","onresize","onscroll","onsecuritypolicyviolation","onseeked","onseeking","onselect","onselectionchange","onselectstart","onslotchange","onstalled","onsubmit","onsuspend","ontimeupdate","ontoggle","ontouchcancel","ontouchend","ontouchmove","ontouchstart","ontransitioncancel","ontransitionend","ontransitionrun","ontransitionstart","onvolumechange","onwaiting","onwebkitanimationend","onwebkitanimationiteration","onwebkitanimationstart","onwebkittransitionend","onwheel"];function yk(n,t){for(let l=0;l<H0.length;l++){const c=H0[l];t[c]=n[c]}const e=n.attributes,o=t.attributes,r=[],i=[];for(let l=0;l<e.length;l++){const c=e[l],a=o.getNamedItem(c.name);a?a.value!==c.value&&(a.value=c.value,i.push(c)):r.push(c)}const s=[];for(let l=0;l<o.length;l++){const c=o[l];e.getNamedItem(c.name)||s.push(c)}r.forEach(l=>{t.setAttribute(l.name,l.value)}),i.forEach(l=>{t.setAttribute(l.name,l.value)}),s.forEach(l=>{t.removeAttribute(l.name)})}function F0(n){const t=Array.from(n.childNodes);return t.forEach(e=>{e instanceof HTMLElement&&e.getAttribute("data-type")==="block-tools"||e.remove()}),t}function z0(n,t,e){var a;const o=n.getContainerById(t),r=kr(o,e),i=jo(r),s=n.doc.getBlockData(t,e),l=bt(n,r);if((a=l==null?void 0:l.handleUpdateBlock)==null?void 0:a.call(l,n,r,s))n.editorBlockRenders.updateBlock(n,i,r,s);else{const u=n.editorBlocks.createBlock(i,o,s),f=F0(u);F0(r),f.forEach(C=>r.appendChild(C));const m=Bl(u);if(m){const C=Bl(r);C&&C.remove(),r.appendChild(m)}yk(u,r)}dg(n,r,s),n.blockHooks.forEach(u=>{var f;(f=u.update)==null||f.call(u,n,i,o,r,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const wk=w("transform-selection");function U0(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;d(wk,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const a=ie.transformCursor(i.offset,e,o);l=P(t,a,"normal")}let c=s;if(s.blockId===t){const a=ie.transformCursor(s.offset,e,o);c=P(t,a,"normal")}return Wt(n,{anchor:l,focus:c})}const Bk=w("handle-block-text-changed");function Ek(n,t,e,o,r){const i=n.getContainerById(t),s=kr(i,e),l=n.doc.getBlockData(t,e);if(d(Bk,l.text,"no block text"),sg(n,s).setBlockText(n,s,l.text),!r){const c=U0(n,l.id,o,r);n.selection.setRange(c,{noScroll:!0})}}function Ik(n,t){const e=Y.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function V0(n,t,e,o){const r=bt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function xk(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{V0(n,i,o,{child:!0})}),V0(n,r,o,{child:!1})}const Vn=w("editor-doc");class Tk extends xi{constructor(e,o,r){super();h(this,"localEvents",[]);this.editor=e,this.externalDoc=o,this.externalDoc.registerCallback(this),this.registerLocalEvents(r)}beginBatchUpdate(){return this.externalDoc.beginBatchUpdate()}endBatchUpdate(){return this.externalDoc.endBatchUpdate()}registerLocalEvents(e){this.localEvents.push(e)}toJSON(){return this.externalDoc.toJSON()}getVersionHelper(){var o,r;return(r=(o=this.externalDoc).getVersionHelper)==null?void 0:r.call(o)}getContainerBlocks(e){return this.externalDoc.getContainerBlocks(e)}getBlockData(e,o){return this.externalDoc.getBlockData(e,o)}localUpdateBlockText(e,o,r,i){d(Vn,this.editor.isWritable(),"editor is readonly");const s=this.getBlockData(e,o),l=s.text;d(Vn,l,`no text, ${e}, ${o}`);const c=U0(this.editor,s.id,r,!0),a=ie.apply(l,r);this.localEvents.forEach(f=>f.onBeforeUpdateBlockText(e,s.id,l,a,c.toDocRange()));const u=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(c,i),u}localUpdateBlockData(e,o,r,i){d(Vn,this.editor.isWritable(),"editor is readonly");const s=Y.default(this.getBlockData(e,o)),l=Y.default(Ik(s,r));this.localEvents.forEach(a=>a.onBeforeUpdateBlockData(e,s.id,s,l,i));const c=this.externalDoc.localUpdateBlockData(e,o,r,i);return this.editor.selection.setRange(io(this.editor,i)),c}localInsertBlock(e,o,r,i,s){d(Vn,this.editor.isWritable(),"editor is readonly"),this.localEvents.forEach(c=>c.onBeforeInsertBlock(e,o,r,i));const l=this.externalDoc.localInsertBlock(e,o,r,i);return this.editor.selection.setRange(io(this.editor,i),s),l}localDeleteBlock(e,o,r){d(Vn,this.editor.isWritable(),"editor is readonly");const i=Y.default(this.getBlockData(e,o));this.localEvents.forEach(l=>l.onBeforeDeleteBlock(e,o,i,r));const s=this.externalDoc.localDeleteBlock(e,o,r);return this.editor.selection.setRange(io(this.editor,r)),s}localDeleteChildContainers(e){return d(Vn,this.editor.isWritable(),"editor is readonly"),e.forEach(o=>{const r=Y.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainer(e,o){return d(Vn,this.editor.isWritable(),"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(e,Y.default(o))),this.externalDoc.localInsertChildContainer(e,o)}onRequestReload(e){Vn.debug(`reload doc: ${e}`),this.editor.reload(),this.callbacks.forEach(r=>{var i;return(i=r.onRequestReload)==null?void 0:i.call(r,e)});const o=!1;this.editor.emit("docChanged",this.editor,o)}onUpdateBlockText(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,e,o,r,i)}),Ek(this.editor,e,o,r,i),this.editor.emit("docChanged",this.editor,i)}onUpdateBlockData(e,o,r,i){this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,i)}),z0(this.editor,e,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(e,o,r,i){this.callbacks.forEach(l=>{var c;return(c=l.onInsertBlock)==null?void 0:c.call(l,e,o,r,i)});const s=this.editor.getContainerById(e);h8(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){xk(this.editor,e,o,r),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,r)});const i=this.editor.getContainerById(e);kk(this.editor,i,o),this.editor.emit("docChanged",this.editor,r)}onInsertChildContainer(e,o,r){this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,e,o,r)})}onDeleteChildContainer(e,o){this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){this.callbacks.forEach(o=>{var r;return(r=o.onCustomMessage)==null?void 0:r.call(o,e)})}onStatusChanged(e){this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)})}onError(e){this.callbacks.forEach(o=>{var r;return(r=o.onError)==null?void 0:r.call(o,e)})}uploadResource(e,o){return this.externalDoc.uploadResource(e,o)}addResources(e){return this.externalDoc.addResources(e)}buildResourceUrl(e,o){return this.externalDoc.buildResourceUrl(e,o)}request(e,o){return this.externalDoc.request(e,o)}broadcastMessage(e){return this.externalDoc.broadcastMessage(e)}getUser(){return this.externalDoc.getUser()}getRemoteUsers(){return this.externalDoc.getRemoteUsers()}destroy(){this.externalDoc.destroy(),this.clearCallbacks()}getServerMeta(){var e,o,r;return(r=(o=(e=this.externalDoc).getServerMeta)==null?void 0:o.call(e))!=null?r:{}}reset(e){Vn.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function q0(n,t){if(n.length===0){n.push(t);return}const e=n[n.length-1];if(!e.combinable(t)){n.push(t);return}e.combine(t)}const Lu=w("undo-action");class Or{constructor(t,e,o){h(this,"beforeRange");h(this,"afterRange");this.containerId=e,this.beforeRange=t.selection.range.clone().toDocRange(),this.afterRange=o}undo(t){return!1}redo(t){return!1}combinable(t){return d(Lu,t,"no other action"),!1}combine(t){d(Lu,!1,"no other")}setAfterRange(t){this.afterRange&&Lu.warn("after range has already set"),this.afterRange=t}}const Sk=w("block-action");class W0 extends Or{constructor(e,o,r,i,s){super(e,o,s);h(this,"blockData");h(this,"blockIndex");this.blockData=Y.default(i),this.blockIndex=r}deleteBlock(e,o){if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockData.id);return i?(d(Sk,this.blockIndex===J(i),"invalid block index"),lu(e,i,io(e,o)),!0):!1}insertBlock(e,o){return Mr(e,this.containerId,this.blockIndex,Y.default(this.blockData),o),!0}}class Dk extends W0{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class Lk extends W0{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class Mk extends Or{constructor(e){super(e,U(e.rootContainer),e.selection.range.toDocRange());h(this,"actions",[])}addAction(e){q0(this.actions,e),this.afterRange=e.afterRange}undo(e){let o=!1;return this.actions.concat().reverse().forEach(r=>{r.undo(e)&&(o=!0)}),o}redo(e){let o=!1;return this.actions.forEach(r=>{r.redo(e)&&(o=!0)}),o}setAfterRange(e){this.afterRange=e;const o=this.actions[this.actions.length-1];!o||o instanceof Or&&(o.afterRange||o.setAfterRange(e))}}const Qo=w("update-block-data-action");class rc extends Or{constructor(e,o,r,i,s,l){super(e,o,l);h(this,"beforeBlockData");h(this,"afterBlockData");h(this,"blockId");this.blockId=r,d(Qo,this.blockId===i.id,"invalid block id"),d(Qo,this.blockId===s.id,"invalid block id"),this.beforeBlockData=Y.default(i),this.afterBlockData=Y.default(s),d(Qo,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){d(Qo,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return d(Qo,r,"no container"),Jl(e,o,rc.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){d(Qo,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return d(Qo,r,"no container"),Jl(e,o,rc.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=Y.default(e);return delete o.id,delete o.type,o}}const Mu=w("update-block-text-action");class Xi extends Or{constructor(e,o,r,i,s,l){super(e,o,l);h(this,"beforeRichTextData");h(this,"afterRichTextData");h(this,"blockId");h(this,"type");this.blockId=r,this.beforeRichTextData=Y.default(i),this.afterRichTextData=Y.default(s),this.type=Xi.calType(i,s)}static calType(e,o){d(Mu,e,"no old data"),d(Mu,o,"no new data");const i=ie.diff(e,o),s=new Set;let l=!1;const c=u=>gm(u)?`cjk_${u}`:fm(u)?"number":ml(u)?"space":mm(u)?"letter":"unknown";let a=!1;return i.forEach(u=>{u.insert?u.insert===" "?s.add("insert_letter"):typeof u.insert=="string"&&u.insert.startsWith(" ")&&u.insert.length>1?(l=!0,a=!0,s.add(`insert_${c(u.insert.substr(1))}`)):s.add(`insert_${c(u.insert)}`):u.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:a}}undo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Kl(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Kl(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof Xi)||e.type.begin||this.type.textType!==e.type.textType||e.blockId!==this.blockId)return!1;const o=e.beforeRange,r=o.anchor;if(!r.isSimple())return!1;const i=this.afterRange;if(!i)return!1;const s=i.anchor;return!(!s.isSimple()||s.blockId!==o.anchor.blockId||s.offset!==r.offset)}combine(e){d(Mu,e instanceof Xi,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class G0 extends Or{constructor(t,e,o){super(t,e,t.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(t){return t.doc.localDeleteChildContainers([this.containerId]),!0}insertChildContainer(t){return t.doc.localInsertChildContainer(this.containerId,Y.default(this.blocks)),!0}}class Rk extends G0{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class Ak extends G0{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const nn=w("undo");class Ok{constructor(t){h(this,"editor");h(this,"actions",[]);h(this,"undoCursor");h(this,"currentGroup",null);h(this,"groupCounter",0);h(this,"undoRedoing",!1);h(this,"handleSelectionChange",t=>{if(this.currentGroup){this.currentGroup.setAfterRange(t.selection.range.toDocRange());return}const e=this.actions[this.actions.length-1];!e||e.afterRange||e.setAfterRange(t.selection.range.toDocRange())});this.editor=t,this.undoCursor=-1,this.editor.addListener("selectionChanged",this.handleSelectionChange)}reset(){this.actions=[],this.undoCursor=-1}prepareSaveUndoState(){this.undoCursor!==-1&&(this.actions.splice(this.undoCursor),this.undoCursor=-1)}addAction(t){this.currentGroup?this.currentGroup.addAction(t):(q0(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(d(nn,!this.currentGroup,"current group already exists"),this.currentGroup=new Mk(this.editor),this.groupCounter=1):(d(nn,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){d(nn,this.currentGroup,"current group not exists"),d(nn,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?nn.warn("empty undo group, skip it"):(this.actions.push(this.currentGroup),this.editor.input.handleChanged(this.currentGroup)),this.currentGroup=null)}hasGroup(){return this.groupCounter>0}runInGroup(t){this.beginGroup();try{const e=t();return setTimeout(()=>this.editor.selection.caret.update()),e}catch(e){throw nn.error(`failed to run action: ${e.message}`),e}finally{this.endGroup()}}undo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor>0;){this.undoCursor-=1;const t=this.actions[this.undoCursor];if(t.undo(this.editor)){try{this.editor.selection.setRange(io(this.editor,t.beforeRange))}catch(e){nn.error(`undo: failed to restore caret pos: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}redo(){this.undoCursor===-1&&(this.undoCursor=this.actions.length);try{for(this.undoRedoing=!0;this.undoCursor<this.actions.length;){const t=this.actions[this.undoCursor];if(this.undoCursor+=1,t.redo(this.editor)){try{const e=t.afterRange;e?this.editor.selection.setRange(io(this.editor,e)):nn.warn("no after range")}catch(e){nn.error(`redo: failed to set caret pos after redo: ${e.message}`)}return this.editor.input.handleChanged(t),!0}}return!1}finally{this.undoRedoing=!1}}canUndo(){return!(this.actions.length===0||this.undoCursor===0)}canRedo(){return!(this.actions.length===0||this.undoCursor===-1||this.undoCursor===this.actions.length)}lastAction(){var e;const t=this.undoCursor===-1?this.actions.length-1:this.undoCursor-1;return(e=this.actions[t])!=null?e:null}undoTo(t){for(;;){const e=this.lastAction();if(!e||e===t)return!0;if(!this.undo())return!1}}onBeforeUpdateBlockText(t,e,o,r,i){this.undoRedoing||(this.prepareSaveUndoState(),ie.diff(o,r).length!==0&&this.addAction(new Xi(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new rc(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),d(nn,e>=0,"invalid block index"),d(nn,o,"no block data"),this.addAction(new Dk(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new Lk(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new Rk(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new Ak(this.editor,t,e)))}}class _k{async fromData(t,e){const o=e.getData("text/x-ones-editor-doc");if(o)return{"text/x-ones-editor-doc":JSON.parse(o)}}}class Nk{constructor(){h(this,"converters",[]);this.addConverter(new _k)}async fromData(t,e){let o={};for(const r of this.converters){const i=await r.fromData(t,e);i&&(o={...o,...i})}return o}addConverter(t){this.converters.push(t)}}class $k{constructor(t){h(this,"renders",[]);this.editor=t}registerRender(t){this.renders.push(t)}renderText(t,e){const o={classes:[],attributes:{},styles:{}};return this.renders.forEach(r=>{if(r.renderText){const i=r.renderText(this.editor,t,e);i.classes&&o.classes.push(...i.classes),i.attributes&&(o.attributes={...o.attributes,...i.attributes}),i.styles&&(o.styles={...o.styles,...i.styles})}}),o}renderBlock(t,e,o){const r={classes:[],attributes:{},styles:{}};return this.renders.forEach(i=>{if(i.renderBlock){const s=i.renderBlock(this.editor,e,o);s.classes&&r.classes.push(...s.classes),s.attributes&&(r.attributes={...r.attributes,...s.attributes}),s.styles&&(r.styles={...r.styles,...s.styles})}}),r}updateBlock(t,e,o,r){this.renders.forEach(i=>{var s;(s=i.updateBlock)==null||s.call(i,t,e,o,r)})}}class Nt extends Yt.TypedEmitter{constructor(e){super();h(this,"hoveringBlock",null);h(this,"hoveringTextChild",null);h(this,"filters",[]);h(this,"finders",[]);h(this,"handleDocumentMouseMove",e=>{if(this.hoveringBlock){for(const s of this.filters)if(s.isInBlock(this.hoveringBlock,e))return}const o=document.elementFromPoint(e.x,e.y);if(!o){this.setHoveringBlock(null,e,null);return}let r=F(o);if((!r||!It(this.editor.rootContainer,r))&&(r=this.findBlockByFinders(e),!r)){this.setHoveringBlock(null,e,null);return}const i=this.getParentTextContentChild(r,o);this.setHoveringBlock(r,e,i)});this.editor=e,document.addEventListener("mousemove",this.handleDocumentMouseMove)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.filters.forEach(e=>e.destroy()),this.filters=[],this.finders.forEach(e=>e.destroy()),this.finders=[]}addFilter(e){this.filters.push(e)}addFinder(e){this.finders.push(e)}hoveringBlockId(){return this.hoveringBlock?q(this.hoveringBlock):""}findBlockByFinders(e){for(let o=0;o<this.finders.length;o++){const i=this.finders[o].findTargetBlock(this.editor,e);if(i)return i}return null}setHoveringBlock(e,o,r){if(this.hoveringBlock===e&&this.hoveringTextChild===r)return;if(this.hoveringBlock!==e){const s=this.hoveringBlock&&It(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&z(s,"hover"),e&&A(e,"hover"),this.hoveringBlock=e,this.emit("change",this.hoveringBlock,s,o)}const i=this.hoveringTextChild;this.hoveringTextChild=r,this.emit("childChange",this.hoveringBlock,r,i,o)}static get(e){return e.addCustom("standard-hovering-block",()=>new Nt(e))}getParentTextContentChild(e,o){if(!j(this.editor,e))return null;const r=it(e);return o.parentElement===r?o:md(o)}}const Z0="style-color-",Y0="style-bg-color-";class Pk{renderText(t,e,o){const r=[],i={};return Object.entries(o).forEach(([s,l])=>{l===!0?s.startsWith(Z0)?i["data-style-color"]=s.substring(Z0.length):s.startsWith(Y0)?i["data-style-bg-color"]=s.substring(Y0.length):s.startsWith("style")&&r.push(s):typeof l=="string"&&s==="link"&&(r.push("link"),i.link=l)}),{classes:r,attributes:i}}renderBlock(t,e,o){var l,c;const r={};Object.entries(o).filter(a=>a[0].startsWith("style-")).forEach(([a,u])=>{r[`data-${a}`]=`${u}`});const s=[];return((c=(l=t.selection)==null?void 0:l.range)==null?void 0:c.start.blockId)===o.id&&s.push("focused"),typeof o.align=="string"&&o.align&&(r["data-style-align"]=o.align),o.heading&&(r["data-style-heading"]=String(o.heading)),o.quoted&&(r["data-style-quoted"]="true"),Nt.get(t).hoveringBlockId()===o.id&&s.push("hover"),{attributes:r,classes:s}}updateBlock(t,e,o,r){var s,l;Array.from(o.attributes).forEach(c=>{c.name.startsWith("data-style-")&&o.removeAttribute(c.name)}),Object.entries(r).filter(c=>c[0].startsWith("style-")).forEach(([c,a])=>{o.setAttribute(`data-${c}`,`${a}`)}),((l=(s=t.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&A(o,"focused"),Nt.get(t).hoveringBlockId()===r.id&&A(o,"hover")}}function jk(n){n.editorBlocks.registerBlockClass(ve),n.editorBlocks.registerBlockClass(yg),n.editorBoxes.registerBoxClass(dp),n.editorBoxes.registerBoxClass(up),n.editorInsertions.registerInsertionClass(mp),n.editorBlockRenders.registerRender(new Pk)}function Hk(n,t){jk(n),t!=null&&t.blocks&&t.blocks.forEach(e=>n.editorBlocks.registerBlockClass(e)),t!=null&&t.boxes&&t.boxes.forEach(e=>n.editorBoxes.registerBoxClass(e)),t!=null&&t.embeds&&t.embeds.forEach(e=>n.editorEmbeds.registerEmbedClass(e)),t!=null&&t.insertions&&t.insertions.forEach(e=>n.editorInsertions.registerInsertionClass(e)),t!=null&&t.decorators&&t.decorators.forEach(e=>n.editorDecorators.registerDecorator(e)),t!=null&&t.dataConverters&&t.dataConverters.forEach(e=>n.dataConverter.addConverter(e)),t!=null&&t.commandProviders&&t.commandProviders.forEach(e=>n.editorCommandProviders.registerCommandProvider(e)),t!=null&&t.textRenders&&t.textRenders.forEach(e=>n.editorBlockRenders.registerRender(e))}const Q0=w("range-commands");function K0(n,t){n.forEach(e=>{e.source=t,e.children&&K0(e.children,t)})}function J0(n,t,e){const o=q(t);d(Q0,o===e.start.blockId,"invalid start range"),d(Q0,o===e.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];return r.forEach(s=>{const l=s.getAvailableCommands(n,t,e);K0(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,i);l&&(i=l)}}),at(n,t)&&xr(n,t,e.start,e.end).forEach(l=>{Mt(l).forEach(a=>{const u=W(n,a),f=Wt(n,{anchor:P(a,0,"home"),focus:P(a,u,"end")}),m=J0(n,a,f);i.push(...m)})}),i}function X0(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=Wt(t,{anchor:r.start,focus:r.end});J0(t,r.block,i).forEach(l=>{o.push(l)})}),o}function t2(n,t,e,o,r,i){var u;const s=n.editorCommandProviders.getCommandProviders();for(let f=0;f<s.length;f++){const m=s[f];if(m.beforeExecuteCommand&&m.beforeExecuteCommand(n,t,e,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),c={};if((u=l.executeCommand)!=null&&u.call(l,n,t,e,o,r,{}))return i[q(t)]=c,!0;let a=!1;return at(n,t)&&xr(n,t,e.start,e.end).forEach(m=>{Mt(m).forEach(v=>{const B=W(n,v),y=Wt(n,{anchor:P(v,0,"home"),focus:P(v,B,"end")});t2(n,v,y,o,r,i)&&(a=!0)})}),s.forEach(f=>{f.afterExecuteCommand&&f.afterExecuteCommand(n,t,e,o,r,i)}),a}function e2(n,t,e){const o=n.getEditor(),r={},i=o.editorCommandProviders.getCommandProvider(t.source);return i.executeRangeCommand&&i.executeRangeCommand(o,n,t,e,r)||n.getSelectedBlocks().forEach(l=>{const c=Wt(o,{anchor:l.start,focus:l.end});t2(o,l.block,c,t,e,r)}),r}const Fk=w("command-providers");class n2{constructor(t){h(this,"providers",[]);this.editor=t}registerCommandProvider(t){this.providers.push(t)}getCommandProviders(){return this.providers}getCommandProvider(t){const e=this.providers.find(o=>o.id===t);return d(Fk,e,`no command provider, id=${t}`),e}getCommands(t){return X0(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>e2(t,e,o))}getEmptyBlockTextAttributes(t,e){let o={};if(this.providers.forEach(r=>{var s;const i=(s=r.getEmptyBlockTextAttributes)==null?void 0:s.call(r,t,e);i&&(o={...o,...i})}),Object.keys(o).length!==0)return o}}function zk(n,t){const e=H(t),o=U(e),r=J(t);z0(n,o,r)}const Uk=w("table-scroll");class o2{constructor(t,e,o,r,i){h(this,"handleEvent",t=>{this.handler(this.editor,t,this.data)});this.editor=t,this.dom=e,this.name=o,this.handler=r,this.data=i,e.addEventListener(o,this.handleEvent)}destroy(){this.dom.removeEventListener(this.name,this.handleEvent)}}class Vk{constructor(t){h(this,"handlers",new Map);this.editor=t}destroy(){Array.from(this.handlers.entries()).forEach(([t,e])=>{e.forEach(o=>o.destroy()),this.handlers.delete(t)})}addEventListener(t,e,o,r){const i=this.handlers.get(t);if(i){if(i.find(s=>s.handler===o&&s.name===e)){Uk.warn(`event has already registered: ${e}`);return}i.push(new o2(this.editor,t,e,o,r))}else{const s=new o2(this.editor,t,e,o,r);this.handlers.set(t,[s])}}removeEventListener(t,e,o){if(!t){for(const[i,s]of Array.from(this.handlers.entries()))for(let l=s.length-1;l>=0;l--){const c=s[l];if(e)e===c.name&&o===c.handler&&s.splice(l,1);else if(o===c.handler){s.splice(l,1),c.destroy(),s.length===0&&this.handlers.delete(i);continue}}return}const r=this.handlers.get(t);if(r){const i=r.findIndex(s=>s.handler===o&&s.name===e);if(i!==-1){const s=r[i];r.splice(i,1),s.destroy(),r.length===0&&this.handlers.delete(t)}}}removeAllListeners(t,e){const o=this.handlers.get(t);if(o)if(e)for(let r=0;r<o.length;r++){const i=o[r];i.name===e&&(o.splice(r,1),i.destroy())}else o.forEach(r=>{r.destroy()}),this.handlers.delete(t)}}const r2=w("update-block-text");function qk(n,t){const e=n.getBoxById(t.id),o=F(e);d(r2,o,"no parent block"),d(r2,j(n,o),"not a text block");const r=n.getBlockText(o),i=ep(r,"id",t.id,t);Np(n,o,i)}function Wk(n,t){for(const e of n.blockHooks)if(e.writable){const o=e.writable(n,t);if(typeof o=="boolean")return o}return!0}function Gk(n){return n.readonly?!1:!tn(n).find(o=>!n.isBlockWritable(o.block))}class Zk{constructor(t){this.editor=t}getKey(t){return`${this.editor.id}-${t}`}async getItem(t){return window.localStorage.getItem(this.getKey(t))}async setItem(t,e){if(!e){this.removeItem(t);return}window.localStorage.setItem(this.getKey(t),e)}async removeItem(t){window.localStorage.removeItem(this.getKey(t))}}class Yk{constructor(){h(this,"shortcuts",[])}handleKeyboardEvents(t,e){const o=this.shortcuts;for(const r of o){const i=Object.entries(r);for(const[s,l]of i)if(jn(e,s)){const c=l(t,e);if(c!==void 0)return c}}}}const Bn=w("editor");class Qk extends Yt.TypedEmitter{constructor(e,o,r){var i,s,l,c,a,u,f,m;super();h(this,"parent");h(this,"rootElement");h(this,"contentElement");h(this,"rootContainerObject");h(this,"rootContainer");h(this,"input");h(this,"selection");h(this,"selectionHandler");h(this,"doc");h(this,"id");h(this,"clientId");h(this,"compositingText","");h(this,"undoManager");h(this,"shortcuts",new Yk);h(this,"dataConverter",new Nk);h(this,"editorBlocks",new Cg(this));h(this,"editorBoxes",new fp(this));h(this,"editorInsertions",new pp(this));h(this,"editorEmbeds",new vg(this));h(this,"editorDecorators",new Cp(this));h(this,"editorCommandProviders",new n2(this));h(this,"editorBlockRenders",new $k(this));h(this,"blockHooks",[]);h(this,"domEvents",new Vk(this));h(this,"customs",new Map);h(this,"options");h(this,"inputHandlers",new vk(this));h(this,"settingsProvider");h(this,"_readonly",!1);Bn.debug("create editor"),this.setMaxListeners(100),this.options={colors:(i=r==null?void 0:r.colors)!=null?i:["#9923E9","#4587C2","#8BDB7A","#FB28D3","#CBC619","#10FEEB","#812A1A","#8A3F25","#22D742","#A53E74","#555C87","#57E0AA"],componentsOptions:(l=(s=r==null?void 0:r.components)==null?void 0:s.options)!=null?l:{},scrollContainer:r==null?void 0:r.scrollContainer},this.settingsProvider=(c=r==null?void 0:r.settingsProvider)!=null?c:new Zk(this),Hk(this,r==null?void 0:r.components),Bn.debug(((a=r==null?void 0:r.components)==null?void 0:a.blockHooks)||[],"register block hooks"),this.blockHooks.push(...(f=(u=r==null?void 0:r.components)==null?void 0:u.blockHooks)!=null?f:[]),this.id=(m=r==null?void 0:r.id)!=null?m:N(),this.clientId=N(),this.undoManager=new Ok(this),this.doc=new Tk(this,o,this.undoManager),this.parent=e,this.rootElement=b("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=b("div",["editor-content"],this.rootElement),this.rootContainerObject=og(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new lv(this,this.inputHandlers),this.selection=new Wv(this),this.selectionHandler=new Yv(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),xt.isMobile&&A(this.rootElement,"mobile"),xt.isSafari&&A(this.rootElement,"safari"),this._readonly&&A(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?A(this.rootElement,"readonly"):z(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:We(this.rootContainer)}addCustom(e,o){const r=this.customs.get(e);if(r)return r;const i=o(this);return this.customs.set(e,i),i}getCustom(e){const o=this.customs.get(e);return d(Bn,o,`${e} does not exists`),o}replaceCustom(e,o){const r=this.customs.get(e);return r&&r.destroy(),this.customs.set(e,o),o}findCustom(e){return this.customs.get(e)}findCustomByType(e){const o=this.customs.values();for(const r of o)if(r instanceof e)return r;return null}destroyCustom(e){const o=this.customs.get(e);o&&(this.customs.delete(e),o.destroy())}getComponentOptions(e){return this.options.componentsOptions[e]}registerLocalEvents(e){this.doc.registerLocalEvents(e)}reload(){this.rootContainerObject.reload(),this.emit("load",this,!0)}createBlock(e,o,r){return this.editorBlocks.createBlock(e,o,r)}createBox(e,o){return this.editorBoxes.createBox(e,o)}createInsertion(e,o){return this.editorInsertions.createInsertion(e,o)}destroy(){Bn.debug("destroy editor"),this.emit("destroy",this),this.input.destroy(),this.rootContainerObject.destroy(),this.rootElement.remove(),this.doc.destroy(),this.customs.forEach(e=>e.destroy()),this.customs.clear(),this.selection.destroy(),this.domEvents.destroy(),this.removeAllListeners(),this.inputHandlers.destroy()}focus(){this.input.focus()}focusToBlock(e,o){uu(this,e,o)}isWritable(){return Gk(this)}isBlockWritable(e){return Wk(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return d(Bn,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),d(Bn,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(e,o,r){return rg(this,e,o,r)}getFirstBlock(){return this.rootContainer.querySelector("[data-type=editor-block]")}getLastBlock(){const e=Array.from(this.rootContainer.querySelectorAll(":scope [data-type=editor-block]"));return e[e.length-1]}getFocusedBlock(){return this.selection.getFocusedBlock()}findBlockById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&d(Bn,Po(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&d(Bn,fd(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return d(Bn,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return d(Bn,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return kr(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return J(o)}return J(e)}getContainerById(e){return Br(this,e)}getParentContainer(e){return H(e)}reloadBlock(e){zk(this,e)}contains(e){const o=e instanceof Element?e:e.parentElement;return o?o.closest("div.editor-root")===this.rootElement:!1}insertBlock(e,o,r,i,s){const l={blockId:r.id,offset:0},c={anchor:l,focus:l};return Mr(this,e,o,r,i!=null?i:c,s)}insertEmbed(e,o,r,i,s){const l={id:N(),type:"embed",embedType:r,embedData:i};return this.insertBlock(e,o,l,s)}deleteBlock(e,o){cu(this,e,o)}mergeTextBlock(e,o){return Ap(this,e,o)}breakTextBlock(e,o,r){return Rr(this,e,o,r).newBlock}getTextPosition(){return Lr(this)}getBlockString(e,o){const r=this.getBlockText(e);return vt(r,o)}getBlockData(e){return co(this,e)}getBoxData(e){return cp(this,e)}getBlockText(e){return ue(this,e)}setBlockText(e,o){Np(this,e,o)}deleteTextFromBlock(e,o,r,i){return iu(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return xp(this,e,o,r,i)}insertBoxToBlock(e,o,r){return Tp(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){jp(this,e,o,r,i)}insertDocAt(e,o,r,i){return mu(this,e,o,r,i)}deleteChildContainers(e){Rp(this,e)}replaceBlockText(e,o){return Kl(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...c}=i;return Jl(this,e,c,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return $p(this,e,o,r)}updateBoxData(e){qk(this,e)}getSelectedText(){const e=Ji(this);return Wl(this,e)}clearSelectedContents(){du(this)}insertTextBlock(e,o,r,i){const s=Un(e!=null?e:"");return Mp(this,s,o,r,i==null?void 0:i.newRange,i==null?void 0:i.insertBlockOptions)}updateCompositionText(e,o){if(e&&!o&&(this.selection.range.isCollapsed()||this.clearSelectedContents()),!e&&!o){Dp(this);return}o?(this.compositingText="",od()||ru(this,e)):(this.compositingText=e,Sp(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function ts(n,t,e){return new Qk(n,t,e)}function Kk(n){const t=(o,r)=>{const i=o.findIndex(l=>l.id===r.id);if(i===-1){o.push(r);return}const s=o[i];if(s.value!==r.value){o.splice(i,1);return}if(!!s.states){if(!r.states){s.states=[];return}s.states=Za.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const Jk=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class ic extends Yt.TypedEmitter{constructor(e){super();h(this,"users",new Map);h(this,"cursors",new Map);h(this,"addingUser",!1);h(this,"colors");this.colors=e&&e.length>0?e:Jk}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&cl.default(o,e))return;this.cursors.set(e.user.userId,e);const r=new Set([e.range.anchor.blockId,e.range.focus.blockId]),i=new Set(r);o&&new Set([o.range.anchor.blockId,o.range.focus.blockId]).forEach(l=>{r.has(l)||i.add(l)}),this.emit("remote-carets-change",[...i])}addUsers(e){this.addingUser=!0,e.forEach(o=>this.addUser(o)),this.addingUser=!1,this.emit("change",Array.from(this.users.values()))}addUser(e){this.users.set(e.userId,e),this.addingUser||this.emit("change",Array.from(this.users.values()))}findUser(e){var o;return(o=this.users.get(e))!=null?o:null}removeUser(e){this.users.delete(e),this.cursors.delete(e),this.emit("change",Array.from(this.users.values()))}updateUsers(e){this.users.clear(),this.addingUser=!0;try{e.forEach(o=>{this.addUser(o)})}finally{this.addingUser=!1}setTimeout(()=>{this.emit("change",Array.from(this.users.values()))},300)}getSimpleCursors(e){const o=new Map;return Array.from(this.cursors.values()).filter(r=>r.range.anchor.blockId===e&&Hl(r.range)).forEach(r=>{const i=r.range.focus.offset;let s=o.get(i);s||(s=[],o.set(i,s)),s.push(r)}),o}getCursors(e){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===e||o.range.focus.blockId===e)}onUpdateBlockText(e,o,r){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(Hl(l.range)){const{anchor:c,focus:a}=l.range;c.blockId===e.id&&(c.offset=ie.transformCursor(c.offset,o,r)),a.blockId===e.id&&(a.offset=ie.transformCursor(a.offset,o,r))}})}getFixedUserColor(e,o){let r=0;Array.from(e).forEach(s=>{r+=s.charCodeAt(0)});const i=r%this.colors.length;return this.colors[i]}destroy(){this.removeAllListeners()}}const te=w("local-doc");class Ru extends xi{constructor(e,o){super();h(this,"doc");h(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[Un("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return Y.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,o){const r=this.getContainerBlocks(e);d(te,r,`no container data: ${e}`);const i=r[o];return d(te,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);d(te,i.text,"no text for data");const s=ie.apply(i.text,r);return i.text=s,d(te,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var c;return(c=l.onUpdateBlockText)==null?void 0:c.call(l,e,o,r,!0)}),s}localUpdateBlockData(e,o,r){const i=this.getBlockData(e,o);return r.delete.forEach(s=>delete i[s]),Object.entries(r.insert).forEach(([s,l])=>{i[s]=l}),d(te,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,e,o,r,!0)}),i}localInsertBlock(e,o,r){const i=this.getContainerBlocks(e);return d(te,i,`no container data: ${e}`),d(te,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),d(te,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,e,o,r,!0)}),r}localDeleteBlock(e,o){const r=this.getContainerBlocks(e);d(te,r,`no container data: ${e}`),d(te,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),d(te,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onDeleteBlock)==null?void 0:l.call(s,e,o,!0)}),i}localInsertChildContainer(e,o){this.doc.blocks[e]=o,d(te,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onInsertChildContainer)==null?void 0:i.call(r,e,o,!0)})}localDeleteChildContainers(e){te.debug(`delete child containers: ${e}`),e.forEach(o=>{d(te,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{d(te,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,o,!0)})})}uploadResource(e,o){d(te,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){d(te,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new ic}setDoc(e){this.doc=Y.default(e),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}function Ko(n){return pt(H(n))}class Xk{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function Au(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new Xk(o)})}const ty=w("remote-cursor");class ey{constructor(){h(this,"remoteUsers",new ic)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):ty.debug(`unknown remote message received: ${t}`)}handleUpdateUsers(t){this.remoteUsers.updateUsers(t)}handleUpdateCaret(t){const e=this.remoteUsers.findUser(t.userId);!e||this.remoteUsers.setCursor({oneseditor:"cursor",user:e,range:t.range,time:Date.now()})}destroy(){this.remoteUsers.destroy()}}function ny(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function es(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=ny(Y.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function ho(n){return n==="root"?"blocks":n}function _r(n){return n==="blocks"?"root":n}const oy={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new oe.default(n)},apply(n,t){const e=new oe.default(n),o=new oe.default(t);return e.compose(o).ops},compose(n,t){const e=new oe.default(n),o=new oe.default(t);return e.compose(o).ops},diff(n,t){const e=new oe.default(n),o=new oe.default(t);return e.diff(o).ops},transform(n,t,e){const o=new oe.default(n);return new oe.default(t).transform(o,e==="left").ops},transformCursor(n,t,e){return t.transformPosition(n,!e)},normalize(n){return n},serialize(n){return n.ops},deserialize(n){return n},transformPresence(n,t,e){if(!n)return null;const o=new oe.default(t),r=this.transformCursor(n.index,o,e),i=this.transformCursor(n.index+n.length,o,e);return{...n,index:r,length:i-r}}}};var ns=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},fo={},Ou=Wf.default.EventEmitter;fo.EventEmitter=Ou,fo.mixin=ry;function ry(n){for(var t in Ou.prototype)n.prototype[t]=Ou.prototype[t]}var i2=["info","warn","error"];function s2(){var n={};i2.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var iy=s2;s2.prototype.setMethods=function(n){n=n||{};var t=this;i2.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var sy=iy,ly=new sy,l2=ly;function Jo(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,Jo):this.stack=new Error().stack}Jo.prototype=Object.create(Error.prototype),Jo.prototype.constructor=Jo,Jo.prototype.name="ShareDBError",Jo.CODES={ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT:"ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT",ERR_APPLY_SNAPSHOT_NOT_PROVIDED:"ERR_APPLY_SNAPSHOT_NOT_PROVIDED",ERR_CLIENT_ID_BADLY_FORMED:"ERR_CLIENT_ID_BADLY_FORMED",ERR_CANNOT_PING_OFFLINE:"ERR_CANNOT_PING_OFFLINE",ERR_CONNECTION_SEQ_INTEGER_OVERFLOW:"ERR_CONNECTION_SEQ_INTEGER_OVERFLOW",ERR_CONNECTION_STATE_TRANSITION_INVALID:"ERR_CONNECTION_STATE_TRANSITION_INVALID",ERR_DATABASE_ADAPTER_NOT_FOUND:"ERR_DATABASE_ADAPTER_NOT_FOUND",ERR_DATABASE_DOES_NOT_SUPPORT_SUBSCRIBE:"ERR_DATABASE_DOES_NOT_SUPPORT_SUBSCRIBE",ERR_DATABASE_METHOD_NOT_IMPLEMENTED:"ERR_DATABASE_METHOD_NOT_IMPLEMENTED",ERR_DEFAULT_TYPE_MISMATCH:"ERR_DEFAULT_TYPE_MISMATCH",ERR_DOC_MISSING_VERSION:"ERR_DOC_MISSING_VERSION",ERR_DOC_ALREADY_CREATED:"ERR_DOC_ALREADY_CREATED",ERR_DOC_DOES_NOT_EXIST:"ERR_DOC_DOES_NOT_EXIST",ERR_DOC_TYPE_NOT_RECOGNIZED:"ERR_DOC_TYPE_NOT_RECOGNIZED",ERR_DOC_WAS_DELETED:"ERR_DOC_WAS_DELETED",ERR_INFLIGHT_OP_MISSING:"ERR_INFLIGHT_OP_MISSING",ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION:"ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION",ERR_MAX_SUBMIT_RETRIES_EXCEEDED:"ERR_MAX_SUBMIT_RETRIES_EXCEEDED",ERR_MESSAGE_BADLY_FORMED:"ERR_MESSAGE_BADLY_FORMED",ERR_MILESTONE_ARGUMENT_INVALID:"ERR_MILESTONE_ARGUMENT_INVALID",ERR_OP_ALREADY_SUBMITTED:"ERR_OP_ALREADY_SUBMITTED",ERR_OP_NOT_ALLOWED_IN_PROJECTION:"ERR_OP_NOT_ALLOWED_IN_PROJECTION",ERR_OP_SUBMIT_REJECTED:"ERR_OP_SUBMIT_REJECTED",ERR_OP_VERSION_MISMATCH_AFTER_TRANSFORM:"ERR_OP_VERSION_MISMATCH_AFTER_TRANSFORM",ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM:"ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM",ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT:"ERR_OP_VERSION_NEWER_THAN_CURRENT_SNAPSHOT",ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED:"ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED",ERR_OT_OP_BADLY_FORMED:"ERR_OT_OP_BADLY_FORMED",ERR_OT_OP_NOT_APPLIED:"ERR_OT_OP_NOT_APPLIED",ERR_OT_OP_NOT_PROVIDED:"ERR_OT_OP_NOT_PROVIDED",ERR_PRESENCE_TRANSFORM_FAILED:"ERR_PRESENCE_TRANSFORM_FAILED",ERR_PROTOCOL_VERSION_NOT_SUPPORTED:"ERR_PROTOCOL_VERSION_NOT_SUPPORTED",ERR_QUERY_EMITTER_LISTENER_NOT_ASSIGNED:"ERR_QUERY_EMITTER_LISTENER_NOT_ASSIGNED",ERR_SNAPSHOT_READ_SILENT_REJECTION:"ERR_SNAPSHOT_READ_SILENT_REJECTION",ERR_SNAPSHOT_READS_REJECTED:"ERR_SNAPSHOT_READS_REJECTED",ERR_SUBMIT_TRANSFORM_OPS_NOT_FOUND:"ERR_SUBMIT_TRANSFORM_OPS_NOT_FOUND",ERR_TYPE_CANNOT_BE_PROJECTED:"ERR_TYPE_CANNOT_BE_PROJECTED",ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE:"ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE",ERR_UNKNOWN_ERROR:"ERR_UNKNOWN_ERROR"};var sc=Jo,os={},c2=cy;function cy(n,t,e,o){var r=function(s,l,c,a){t(c,s,l,"left"),t(a,l,s,"right")},i=n.transformX=function(s,l){e(s),e(l);for(var c=[],a=0;a<l.length;a++){for(var u=l[a],f=[],m=0;m<s.length;){var C=[];if(r(s[m],u,f,C),m++,C.length===1)u=C[0];else if(C.length===0){for(var v=m;v<s.length;v++)o(f,s[v]);u=null;break}else{for(var B=i(s.slice(m),C),y=0;y<B[0].length;y++)o(f,B[0][y]);for(var S=0;S<B[1].length;S++)o(c,B[1][S]);u=null;break}}u!=null&&o(c,u),s=f}return[s,c]};n.transform=function(s,l,c){if(!(c==="left"||c==="right"))throw new Error("type must be 'left' or 'right'");return l.length===0?s:s.length===1&&l.length===1?t([],s[0],l[0],c):c==="left"?i(s,l)[0]:i(l,s)[1]}}var a2={exports:{}},mo=a2.exports={name:"text0",uri:"http://sharejs.org/types/textv0",create:function(n){if(n!=null&&typeof n!="string")throw new Error("Initial data must be a string");return n||""}},_u=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},Nu=function(n){if(typeof n.p!="number")throw new Error("component missing position field");if(typeof n.i=="string"==(typeof n.d=="string"))throw new Error("component needs an i or d field");if(n.p<0)throw new Error("position cannot be negative")},lc=function(n){for(var t=0;t<n.length;t++)Nu(n[t])};mo.apply=function(n,t){var e;lc(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=_u(n,r.p,r.i);else{if(e=n.slice(r.p,r.p+r.d.length),r.d!==e)throw new Error("Delete component '"+r.d+"' does not match deleted text '"+e+"'");n=n.slice(0,r.p)+n.slice(r.p+r.d.length)}}return n};var qn=mo._append=function(n,t){if(!(t.i===""||t.d===""))if(n.length===0)n.push(t);else{var e=n[n.length-1];e.i!=null&&t.i!=null&&e.p<=t.p&&t.p<=e.p+e.i.length?n[n.length-1]={i:_u(e.i,t.p-e.p,t.i),p:e.p}:e.d!=null&&t.d!=null&&t.p<=e.p&&e.p<=t.p+t.d.length?n[n.length-1]={d:_u(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};mo.compose=function(n,t){lc(n),lc(t);for(var e=n.slice(),o=0;o<t.length;o++)qn(e,t[o]);return e},mo.normalize=function(n){var t=[];(n.i!=null||n.p!=null)&&(n=[n]);for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=0),qn(t,o)}return t};var $u=function(n,t,e){return t.i!=null?t.p<n||t.p===n&&e?n+t.i.length:n:n<=t.p?n:n<=t.p+t.d.length?t.p:n-t.d.length};mo.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=$u(n,t[r],o);return n};var ay=mo._tc=function(n,t,e,o){if(Nu(t),Nu(e),t.i!=null)qn(n,{i:t.i,p:$u(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(qn(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&qn(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)qn(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)qn(n,t);else{var i={d:"",p:t.p};t.p<e.p&&(i.d=t.d.slice(0,e.p-t.p)),t.p+t.d.length>e.p+e.d.length&&(i.d+=t.d.slice(e.p+e.d.length-t.p));var s=Math.max(t.p,e.p),l=Math.min(t.p+t.d.length,e.p+e.d.length),c=t.d.slice(s-t.p,l-t.p),a=e.d.slice(s-e.p,l-e.p);if(c!==a)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=$u(i.p,e),qn(n,i))}return n},dy=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};mo.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=dy(n[t]);return n},c2(mo,ay,lc,qn);var cc=function(n){return Object.prototype.toString.call(n)=="[object Array]"},uy=function(n){return!!n&&n.constructor===Object},on=function(n){return JSON.parse(JSON.stringify(n))},tt={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Wn={};tt.registerSubtype=function(n){Wn[n.name]=n},tt.create=function(n){return n===void 0?null:on(n)},tt.invertComponent=function(n){var t={p:n.p};return n.t&&Wn[n.t]&&(t.t=n.t,t.o=Wn[n.t].invert(n.o)),n.si!==void 0&&(t.sd=n.si),n.sd!==void 0&&(t.si=n.sd),n.oi!==void 0&&(t.od=n.oi),n.od!==void 0&&(t.oi=n.od),n.li!==void 0&&(t.ld=n.li),n.ld!==void 0&&(t.li=n.ld),n.na!==void 0&&(t.na=-n.na),n.lm!==void 0&&(t.lm=n.p[n.p.length-1],t.p=n.p.slice(0,n.p.length-1).concat([n.lm])),t},tt.invert=function(n){for(var t=n.slice().reverse(),e=[],o=0;o<t.length;o++)e.push(tt.invertComponent(t[o]));return e},tt.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!cc(n[t].p))throw new Error("Missing path")},tt.checkList=function(n){if(!cc(n))throw new Error("Referenced element not a list")},tt.checkObj=function(n){if(!uy(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function rs(n){n.t="text0";var t={p:n.p.pop()};n.si!=null&&(t.i=n.si),n.sd!=null&&(t.d=n.sd),n.o=[t]}function is(n){n.p.push(n.o[0].p),n.o[0].i!=null&&(n.si=n.o[0].i),n.o[0].d!=null&&(n.sd=n.o[0].d),delete n.t,delete n.o}tt.apply=function(n,t){tt.checkValidOp(t),t=on(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&rs(r);for(var i=null,s=e,l="data",c=0;c<r.p.length;c++){var a=r.p[c];if(i=s,s=s[l],l=a,i==null)throw new Error("Path invalid")}if(r.t&&r.o!==void 0&&Wn[r.t])s[l]=Wn[r.t].apply(s[l],r.o);else if(r.na!==void 0){if(typeof s[l]!="number")throw new Error("Referenced element not a number");s[l]+=r.na}else if(r.li!==void 0&&r.ld!==void 0)tt.checkList(s),s[l]=r.li;else if(r.li!==void 0)tt.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)tt.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(tt.checkList(s),r.lm!=l){var u=s[l];s.splice(l,1),s.splice(r.lm,0,u)}}else if(r.oi!==void 0)tt.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)tt.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},tt.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},tt.incrementalApply=function(n,t,e){for(var o=0;o<t.length;o++){var r=[t[o]];n=tt.apply(n,r),e(r,n)}return n};var hy=tt.pathMatches=function(n,t,e){if(n.length!=t.length)return!1;for(var o=0;o<n.length;o++)if(n[o]!==t[o]&&(!e||o!==n.length-1))return!1;return!0};tt.append=function(n,t){if(t=on(t),n.length===0){n.push(t);return}var e=n[n.length-1];if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(rs(t),rs(e)),hy(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Wn[t.t]){if(e.o=Wn[t.t].compose(e.o,t.o),t.si!=null||t.sd!=null){for(var o=t.p,r=0;r<e.o.length-1;r++)t.o=[e.o.pop()],t.p=o.slice(),is(t),n.push(t);is(e)}}else e.na!=null&&t.na!=null?n[n.length-1]={p:e.p,na:e.na+t.na}:e.li!==void 0&&t.li===void 0&&t.ld===e.li?e.ld!==void 0?delete e.li:n.pop():e.od!==void 0&&e.oi===void 0&&t.oi!==void 0&&t.od===void 0?e.oi=t.oi:e.oi!==void 0&&t.od!==void 0?t.oi!==void 0?e.oi=t.oi:e.od!==void 0?delete e.oi:n.pop():t.lm!==void 0&&t.p[t.p.length-1]===t.lm||n.push(t);else(t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(is(t),is(e)),n.push(t)},tt.compose=function(n,t){tt.checkValidOp(n),tt.checkValidOp(t);for(var e=on(n),o=0;o<t.length;o++)tt.append(e,t[o]);return e},tt.normalize=function(n){var t=[];n=cc(n)?n:[n];for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=[]),tt.append(t,o)}return t},tt.commonLengthForOps=function(n,t){var e=n.p.length,o=t.p.length;if((n.na!=null||n.t)&&e++,(t.na!=null||t.t)&&o++,e===0)return-1;if(o===0)return null;e--,o--;for(var r=0;r<e;r++){var i=n.p[r];if(r>=o||i!==t.p[r])return null}return e},tt.canOpAffectPath=function(n,t){return tt.commonLengthForOps({p:t},n)!=null},tt.transformComponent=function(n,t,e,o){t=on(t);var r=tt.commonLengthForOps(e,t),i=tt.commonLengthForOps(t,e),s=t.p.length,l=e.p.length;if((t.na!=null||t.t)&&s++,(e.na!=null||e.t)&&l++,i!=null&&l>s&&t.p[i]==e.p[i]){if(t.ld!==void 0){var c=on(e);c.p=c.p.slice(s),t.ld=tt.apply(on(t.ld),[c])}else if(t.od!==void 0){var c=on(e);c.p=c.p.slice(s),t.od=tt.apply(on(t.od),[c])}}if(r!=null){var a=s==l,c=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(rs(t),c=on(e),rs(c)),c.t&&Wn[c.t]){if(t.t&&t.t===c.t){var u=Wn[t.t].transform(t.o,c.o,o);if(t.si!=null||t.sd!=null)for(var f=t.p,m=0;m<u.length;m++)t.o=[u[m]],t.p=f.slice(),is(t),tt.append(n,t);else(!cc(u)||u.length>0)&&(t.o=u,tt.append(n,t));return n}}else if(e.na===void 0){if(e.li!==void 0&&e.ld!==void 0){if(e.p[r]===t.p[r])if(a){if(t.ld!==void 0)if(t.li!==void 0&&o==="left")t.ld=on(e.li);else return n}else return n}else if(e.li!==void 0)t.li!==void 0&&t.ld===void 0&&a&&t.p[r]===e.p[r]?o==="right"&&t.p[r]++:e.p[r]<=t.p[r]&&t.p[r]++,t.lm!==void 0&&a&&e.p[r]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&a){if(e.p[r]===t.p[r])return n;var f=e.p[r],C=t.p[r],v=t.lm;(f<v||f===v&&C<v)&&t.lm--}if(e.p[r]<t.p[r])t.p[r]--;else if(e.p[r]===t.p[r]){if(l<s)return n;if(t.ld!==void 0)if(t.li!==void 0)delete t.ld;else return n}}else if(e.lm!==void 0)if(t.lm!==void 0&&s===l){var C=t.p[r],v=t.lm,B=e.p[r],y=e.lm;if(B!==y)if(C===B)if(o==="left")t.p[r]=y,C===v&&(t.lm=y);else return n;else C>B&&t.p[r]--,C>y?t.p[r]++:C===y&&B>y&&(t.p[r]++,C===v&&t.lm++),(v>B||v===B&&v>C)&&t.lm--,v>y?t.lm++:v===y&&(y>B&&v>C||y<B&&v<C?o==="right"&&t.lm++:v>C?t.lm++:v===B&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&a){var C=e.p[r],v=e.lm;f=t.p[r],f>C&&t.p[r]--,f>v&&t.p[r]++}else{var C=e.p[r],v=e.lm;f=t.p[r],f===C?t.p[r]=v:(f>C&&t.p[r]--,(f>v||f===v&&C>v)&&t.p[r]++)}else if(e.oi!==void 0&&e.od!==void 0){if(t.p[r]===e.p[r])if(t.oi!==void 0&&a){if(o==="right")return n;t.od=e.oi}else return n}else if(e.oi!==void 0){if(t.oi!==void 0&&t.p[r]===e.p[r])if(o==="left")tt.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[r]==e.p[r]){if(!a)return n;if(t.oi!==void 0)delete t.od;else return n}}}return tt.append(n,t),n},c2(tt,tt.transformComponent,tt.checkValidOp,tt.append);var fy=a2.exports;tt.registerSubtype(fy);var my=tt,gy={type:my};(function(n){n.defaultType=gy.type,n.map={},n.register=function(t){t.name&&(n.map[t.name]=t),t.uri&&(n.map[t.uri]=t)},n.register(n.defaultType)})(os);var rn={};(function(n){n.doNothing=t;function t(){}n.hasKeys=function(e){for(var o in e)return!0;return!1},n.isInteger=Number.isInteger||function(e){return typeof e=="number"&&isFinite(e)&&Math.floor(e)===e},n.isValidVersion=function(e){return e===null?!0:n.isInteger(e)&&e>=0},n.isValidTimestamp=function(e){return n.isValidVersion(e)},n.MAX_SAFE_INTEGER=9007199254740991,n.dig=function(){for(var e=arguments[0],o=1;o<arguments.length;o++){var r=arguments[o];e=e[r]||(o===arguments.length-1?void 0:{})}return e},n.digOrCreate=function(){for(var e=arguments[0],o=arguments[arguments.length-1],r=1;r<arguments.length-1;r++){var i=arguments[r];e=e[i]||(e[i]=r===arguments.length-2?o():{})}return e},n.digAndRemove=function(){for(var e=arguments[0],o=[e],r=1;r<arguments.length-1;r++){var i=arguments[r];if(!e.hasOwnProperty(i))break;e=e[i],o.push(e)}for(var r=o.length-1;r>=0;r--){var s=o[r],i=arguments[r+1],l=s[i];(r===o.length-1||!n.hasKeys(l))&&delete s[i]}},n.supportsPresence=function(e){return e&&typeof e.transformPresence=="function"},n.callEach=function(e,o){var r=!1;return e.forEach(function(i){i&&(i(o),r=!0)}),r},n.truthy=function(e){return!!e},n.nextTick=function(e){if(typeof process<"u"&&process.nextTick)return process.nextTick.apply(null,arguments);for(var o=[],r=1;r<arguments.length;r++)o[r-1]=arguments[r];setTimeout(function(){e.apply(null,o)})},n.clone=function(e){return e===void 0?void 0:JSON.parse(JSON.stringify(e))}})(rn);var d2=Array.isArray,u2=Object.keys,py=Object.prototype.hasOwnProperty,Cy=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=d2(t),r=d2(e),i,s,l;if(o&&r){if(s=t.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!n(t[i],e[i]))return!1;return!0}if(o!=r)return!1;var c=t instanceof Date,a=e instanceof Date;if(c!=a)return!1;if(c&&a)return t.getTime()==e.getTime();var u=t instanceof RegExp,f=e instanceof RegExp;if(u!=f)return!1;if(u&&f)return t.toString()==e.toString();var m=u2(t);if(s=m.length,s!==u2(e).length)return!1;for(i=s;i--!==0;)if(!py.call(e,m[i]))return!1;for(i=s;i--!==0;)if(l=m[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},h2=fo,by=l2,Le=sc,ac=os,sn=rn,vy=sn.clone,ky=Cy,ye=Le.CODES,yy=lt;function lt(n,t,e){h2.EventEmitter.call(this),this.connection=n,this.collection=t,this.id=e,this.version=null,this.type=null,this.data=void 0,this.inflightFetch=[],this.inflightSubscribe=null,this.pendingFetch=[],this.pendingSubscribe=[],this.subscribed=!1,this.wantSubscribe=!1,this._wantsDestroy=!1,this.inflightOp=null,this.pendingOps=[],this.type=null,this.applyStack=null,this.preventCompose=!1,this.submitSource=!1,this.paused=!1,this._dataStateVersion=0}h2.mixin(lt),lt.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this;t.whenNothingPending(function(){t.wantSubscribe?t.unsubscribe(function(e){if(e)return n?n(e):t.emit("error",e);t.connection._destroyDoc(t),n&&n()}):(t.connection._destroyDoc(t),n&&n())})},lt.prototype._setType=function(n){if(typeof n=="string"&&(n=ac.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new Le(ye.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},lt.prototype._setData=function(n){this.data=n,this._dataStateVersion++},lt.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new Le(ye.ERR_INGESTED_SNAPSHOT_HAS_NO_VERSION,"Missing version in ingested snapshot. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}if(this.type||this.hasWritePending()){if(this.version==null){if(this.hasWritePending())return t&&this.once("no write pending",t);var e=new Le(ye.ERR_DOC_MISSING_VERSION,"Cannot ingest snapshot in doc with null version. "+this.collection+"."+this.id);return t?t(e):this.emit("error",e)}return n.v>this.version?this.fetch(t):t&&t()}if(this.version>n.v)return t&&t();this.version=n.v;var o=n.type===void 0?ac.defaultType:n.type;this._setType(o),this._setData(this.type&&this.type.deserialize?this.type.deserialize(n.data):n.data),this.emit("load"),t&&t()},lt.prototype.whenNothingPending=function(n){var t=this;sn.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},lt.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},lt.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},lt.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},lt.prototype._emitResponseError=function(n,t){if(n&&n.code===ye.ERR_SNAPSHOT_READ_SILENT_REJECTION){this.wantSubscribe=!1,t&&t(),this._emitNothingPending();return}if(t){t(n),this._emitNothingPending();return}this._emitNothingPending(),this.emit("error",n)},lt.prototype._handleFetch=function(n,t){var e=this.pendingFetch;this.pendingFetch=[];var o=this.inflightFetch.shift();if(o&&e.push(o),e.length&&(o=function(r){sn.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},lt.prototype._handleSubscribe=function(n,t){var e=this.inflightSubscribe;this.inflightSubscribe=null;var o=this.pendingFetch;this.pendingFetch=[],e.callback&&o.push(e.callback);var r;if(o.length&&(r=function(i){sn.callEach(o,i)}),n)return this._emitResponseError(n,r);this.subscribed=e.wantSubscribe,this.subscribed?this.ingestSnapshot(t,r):r&&r(),this._emitNothingPending(),this._flushSubscribe()},lt.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===ye.ERR_OP_SUBMIT_REJECTED&&(n=null),this._rollback(n)):this.emit("error",n);if(this.inflightOp&&t.src===this.inflightOp.src&&t.seq===this.inflightOp.seq){this._opAcknowledged(t);return}if(this.version==null||t.v>this.version){this.fetch();return}if(!(t.v<this.version)){if(this.inflightOp){var e=dc(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=dc(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},lt.prototype._onConnectionStateChanged=function(){this.connection.canSend?(this.flush(),this._resubscribe()):(this.inflightOp&&(this.pendingOps.unshift(this.inflightOp),this.inflightOp=null),this.subscribed=!1,this.inflightSubscribe&&(this.inflightSubscribe.wantSubscribe?(this.pendingSubscribe.unshift(this.inflightSubscribe),this.inflightSubscribe=null):this._handleSubscribe()),this.inflightFetch.length&&(this.pendingFetch=this.pendingFetch.concat(this.inflightFetch),this.inflightFetch.length=0))},lt.prototype._resubscribe=function(){if(!this.pendingSubscribe.length&&this.wantSubscribe)return this.subscribe();var n=this.pendingSubscribe.some(function(t){return t.wantSubscribe});!n&&this.pendingFetch.length&&this.fetch(),this._flushSubscribe()},lt.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);wy(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},lt.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},lt.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},lt.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=e&&e.wantSubscribe===n;if(o){e.callback=By([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},lt.prototype._flushSubscribe=function(){if(!(this.inflightSubscribe||!this.pendingSubscribe.length)){if(this.connection.canSend){this.inflightSubscribe=this.pendingSubscribe.shift(),this.wantSubscribe=this.inflightSubscribe.wantSubscribe,this.wantSubscribe?this.connection.sendSubscribe(this):(this.subscribed=!1,this.connection.sendUnsubscribe(this));return}if(!this.pendingSubscribe[0].wantSubscribe){this.inflightSubscribe=this.pendingSubscribe.shift();var n=this;sn.nextTick(function(){n._handleSubscribe()})}}};function wy(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function By(n){return n=n.filter(sn.truthy),n.length?function(t){sn.callEach(n,t)}:null}lt.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function Ey(n){delete n.op,delete n.create,delete n.del}function dc(n,t){if(n.del)return Ey(t);if(t.del)return new Le(ye.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new Le(ye.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new Le(ye.ERR_DOC_ALREADY_CREATED,"Document already created");if(n.type.transformX){var e=n.type.transformX(n.op,t.op);n.op=e[0],t.op=e[1]}else{var o=n.type.transform(n.op,t.op,"left"),r=n.type.transform(t.op,n.op,"right");n.op=o,t.op=r}}}lt.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new Le(ye.ERR_DOC_DOES_NOT_EXIST,"Cannot apply op to uncreated document. "+this.collection+"."+this.id);if(this.emit("before op batch",n.op,t),!t&&this.type===ac.defaultType&&n.op.length>1){this.applyStack||(this.applyStack=[]);for(var e=this.applyStack.length,o=0;o<n.op.length;o++){var r=n.op[o],i={op:[r]};this.emit("before op",i.op,t,n.src);for(var s=e;s<this.applyStack.length;s++){var l=dc(this.applyStack[s],i);if(l)return this._hardRollback(l)}this._setData(this.type.apply(this.data,i.op)),this.emit("op",i.op,t,n.src)}this.emit("op batch",n.op,t),this._popApplyStack(e);return}this.emit("before op",n.op,t,n.src),this._setData(this.type.apply(this.data,n.op)),this.emit("op",n.op,t,n.src),this.emit("op batch",n.op,t);return}if(n.create){this._setType(n.create.type),this.type.deserialize?this.type.createDeserialized?this._setData(this.type.createDeserialized(n.create.data)):this._setData(this.type.deserialize(this.type.create(n.create.data))):this._setData(this.type.create(n.create.data)),this.emit("create",t);return}if(n.del){var c=this.data;this._setType(null),this.emit("del",c,t);return}},lt.prototype._sendOp=function(){if(!!this.connection.canSend){var n=this.connection.id;this.inflightOp||(this.inflightOp=this.pendingOps.shift());var t=this.inflightOp;if(!t){var e=new Le(ye.ERR_INFLIGHT_OP_MISSING,"No op to send on call to _sendOp");return this.emit("error",e)}if(t.sentAt=Date.now(),t.retries=t.retries==null?0:t.retries+1,t.seq==null){if(this.connection.seq>=sn.MAX_SAFE_INTEGER)return this.emit("error",new Le(ye.ERR_CONNECTION_SEQ_INTEGER_OVERFLOW,"Connection seq has exceeded the max safe integer, maybe from being open for too long"));t.seq=this.connection.seq++}this.connection.sendOp(this,t),t.src==null&&(t.src=n)}},lt.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var o=new Le(ye.ERR_DOC_DOES_NOT_EXIST,"Cannot submit op. Document has not been created. "+this.collection+"."+this.id);return e?e(o):this.emit("error",o)}this.type.normalize&&(n.op=this.type.normalize(n.op))}try{this._pushOp(n,t,e),this._otApply(n,t)}catch(i){return this._hardRollback(i)}var r=this;sn.nextTick(function(){r.flush()})},lt.prototype._pushOp=function(n,t,e){if(n.source=t,this.applyStack)this.applyStack.push(n);else{var o=this._tryCompose(n);if(o){o.callbacks.push(e);return}}n.type=this.type,n.callbacks=[e],this.pendingOps.push(n)},lt.prototype._popApplyStack=function(n){if(n>0){this.applyStack.length=n;return}var t=this.applyStack[0];if(this.applyStack=null,!!t){var e=this.pendingOps.indexOf(t);if(e!==-1)for(var o=this.pendingOps.splice(e),e=0;e<o.length;e++){var t=o[e],r=this._tryCompose(t);r?r.callbacks=r.callbacks.concat(t.callbacks):this.pendingOps.push(t)}}},lt.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!ky(n.source,t.source))){if(t.create&&"op"in n)return t.create.data=this.type.apply(t.create.data,n.op),t;if("op"in t&&"op"in n&&this.type.compose)return t.op=this.type.compose(t.op,n.op),t}}},lt.prototype.submitOp=function(n,t,e){typeof t=="function"&&(e=t,t=null);var o={op:n},r=t&&t.source;this._submit(o,r,e)},lt.prototype.create=function(n,t,e,o){if(typeof t=="function"?(o=t,e=null,t=null):typeof e=="function"&&(o=e,e=null),t||(t=ac.defaultType.uri),this.type){var r=new Le(ye.ERR_DOC_ALREADY_CREATED,"Document already exists");return o?o(r):this.emit("error",r)}var i={create:{type:t,data:n}},s=e&&e.source;this._submit(i,s,o)},lt.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new Le(ye.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");return t?t(e):this.emit("error",e)}var o={del:!0},r=n&&n.source;this._submit(o,r,t)},lt.prototype.pause=function(){this.paused=!0},lt.prototype.resume=function(){this.paused=!1,this.flush()},lt.prototype.toSnapshot=function(){return{v:this.version,data:vy(this.data),type:this.type.uri}},lt.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return by.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},lt.prototype._rollback=function(n){var t=this.inflightOp;if("op"in t&&t.type.invert){try{t.op=t.type.invert(t.op)}catch{return this._hardRollback(n)}for(var e=0;e<this.pendingOps.length;e++){var o=dc(this.pendingOps[e],t);if(o)return this._hardRollback(o)}try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}this._clearInflightOp(n);return}this._hardRollback(n)},lt.prototype._hardRollback=function(n){var t=[];this.inflightOp&&t.push(this.inflightOp),t=t.concat(this.pendingOps),this._setType(null),this.version=null,this.inflightOp=null,this.pendingOps=[];var e=this;this.fetch(function(){for(var o=!!t.length,r=0;r<t.length;r++)o=sn.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},lt.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=sn.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var Xo={};Xo.ACTIONS={initLegacy:"init",handshake:"hs",queryFetch:"qf",querySubscribe:"qs",queryUnsubscribe:"qu",queryUpdate:"q",bulkFetch:"bf",bulkSubscribe:"bs",bulkUnsubscribe:"bu",fetch:"f",subscribe:"s",unsubscribe:"u",op:"op",snapshotFetch:"nf",snapshotFetchByTimestamp:"nt",pingPong:"pp",presence:"p",presenceSubscribe:"ps",presenceUnsubscribe:"pu",presenceRequest:"pr"};var f2=fo,m2=Xo.ACTIONS,Iy=rn,xy=we;function we(n,t,e,o,r,i,s){f2.EventEmitter.call(this),this.action=n,this.connection=t,this.id=e,this.collection=o,this.query=r,this.results=null,i&&i.results&&(this.results=i.results,delete i.results),this.extra=void 0,this.options=i,this.callback=s,this.ready=!1,this.sent=!1}f2.mixin(we),we.prototype.hasPending=function(){return!this.ready},we.prototype.send=function(){if(!!this.connection.canSend){var n={a:this.action,id:this.id,c:this.collection,q:this.query};if(this.options&&(n.o=this.options),this.results){for(var t=[],e=0;e<this.results.length;e++){var o=this.results[e];t.push([o.id,o.version])}n.r=t}this.connection.send(n),this.sent=!0}},we.prototype.destroy=function(n){this.connection.canSend&&this.action===m2.querySubscribe&&this.connection.send({a:m2.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&Iy.nextTick(n)},we.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},we.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},we.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},we.prototype._handleResponse=function(n,t,e){var o=this.callback;if(this.callback=null,n)return this._finishResponse(n,o);if(!t)return this._finishResponse(null,o);var r=this,i=1,s=function(u){if(u)return r._finishResponse(u,o);--i||r._finishResponse(null,o)};if(Array.isArray(t))i+=t.length,this.results=this._ingestSnapshots(t,s),this.extra=e;else for(var l in t){i++;var c=t[l],a=this.connection.get(c.c||this.collection,l);a.ingestSnapshot(c,s)}s()},we.prototype._ingestSnapshots=function(n,t){for(var e=[],o=0;o<n.length;o++){var r=n[o],i=this.connection.get(r.c||this.collection,r.d);i.ingestSnapshot(r,t),e.push(i)}return e},we.prototype._finishResponse=function(n,t){if(this.emit("ready"),this.ready=!0,n)return this.connection._destroyQuery(this),t?t(n):this.emit("error",n);t&&t(null,this.results,this.extra)},we.prototype._handleError=function(n){this.emit("error",n)},we.prototype._handleDiff=function(n){for(var t=0;t<n.length;t++){var e=n[t];e.type==="insert"&&(e.values=this._ingestSnapshots(e.values))}for(var t=0;t<n.length;t++){var e=n[t];switch(e.type){case"insert":var o=e.values;Array.prototype.splice.apply(this.results,[e.index,0].concat(o)),this.emit("insert",o,e.index);break;case"remove":var i=e.howMany||1,r=this.results.splice(e.index,i);this.emit("remove",r,e.index);break;case"move":var i=e.howMany||1,s=this.results.splice(e.from,i);Array.prototype.splice.apply(this.results,[e.to,0].concat(s)),this.emit("move",s,e.from,e.to);break}}this.emit("changed",this.results)},we.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var g2=fo,Ty=Xo.ACTIONS,Sy=rn,p2=En;function En(n,t){if(g2.EventEmitter.call(this),!t||typeof t!="string")throw new Error("LocalPresence presenceId must be a string");this.presence=n,this.presenceId=t,this.connection=n.connection,this.presenceVersion=0,this.value=null,this._pendingMessages=[],this._callbacksByPresenceVersion={}}g2.mixin(En),En.prototype.submit=function(n,t){this.value=n,this.send(t)},En.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},En.prototype.destroy=function(n){var t=this;this.submit(null,function(e){if(e)return t._callbackOrEmit(e,n);delete t.presence.localPresences[t.presenceId],n&&n()})},En.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},En.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},En.prototype._message=function(){return{a:Ty.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},En.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},En.prototype._callbackOrEmit=function(n,t){if(t)return Sy.nextTick(t,n);n&&this.emit("error",n)};var Dy=rn,C2=Pu;function Pu(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}Pu.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},Pu.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&Dy.nextTick(n)};var ju={exports:{}};(function(n,t){(function(e,o){o(t)})(ns,function(e){function o(p,k){k=k|0;for(var E=Math.max(p.length-k,0),x=Array(E),L=0;L<E;L++)x[L]=p[k+L];return x}var r=function(p){var k=o(arguments,1);return function(){var E=o(arguments);return p.apply(null,k.concat(E))}},i=function(p){return function(){var k=o(arguments),E=k.pop();p.call(this,k,E)}};function s(p){var k=typeof p;return p!=null&&(k=="object"||k=="function")}var l=typeof setImmediate=="function"&&setImmediate,c=typeof process=="object"&&typeof process.nextTick=="function";function a(p){setTimeout(p,0)}function u(p){return function(k){var E=o(arguments,1);p(function(){k.apply(null,E)})}}var f;l?f=setImmediate:c?f=process.nextTick:f=a;var m=u(f);function C(p){return i(function(k,E){var x;try{x=p.apply(this,k)}catch(L){return E(L)}s(x)&&typeof x.then=="function"?x.then(function(L){v(E,null,L)},function(L){v(E,L.message?L:new Error(L))}):E(null,x)})}function v(p,k,E){try{p(k,E)}catch(x){m(B,x)}}function B(p){throw p}var y=typeof Symbol=="function";function S(p){return y&&p[Symbol.toStringTag]==="AsyncFunction"}function I(p){return S(p)?C(p):p}function M(p){return function(k){var E=o(arguments,1),x=i(function(L,D){var O=this;return p(k,function(_,V){I(_).apply(O,L.concat(V))},D)});return E.length?x.apply(this,E):x}}var R=typeof ns=="object"&&ns&&ns.Object===Object&&ns,$=typeof self=="object"&&self&&self.Object===Object&&self,Z=R||$||Function("return this")(),ot=Z.Symbol,st=Object.prototype,mt=st.hasOwnProperty,ut=st.toString,yt=ot?ot.toStringTag:void 0;function se(p){var k=mt.call(p,yt),E=p[yt];try{p[yt]=void 0;var x=!0}catch{}var L=ut.call(p);return x&&(k?p[yt]=E:delete p[yt]),L}var eo=Object.prototype,ee=eo.toString;function Ue(p){return ee.call(p)}var Eo="[object Null]",gr="[object Undefined]",pr=ot?ot.toStringTag:void 0;function Io(p){return p==null?p===void 0?gr:Eo:pr&&pr in Object(p)?se(p):Ue(p)}var ya="[object AsyncFunction]",LP="[object Function]",MP="[object GeneratorFunction]",RP="[object Proxy]";function AP(p){if(!s(p))return!1;var k=Io(p);return k==LP||k==MP||k==ya||k==RP}var OP=9007199254740991;function SC(p){return typeof p=="number"&&p>-1&&p%1==0&&p<=OP}function Ks(p){return p!=null&&SC(p.length)&&!AP(p)}var If={};function ht(){}function xo(p){return function(){if(p!==null){var k=p;p=null,k.apply(this,arguments)}}}var xf=typeof Symbol=="function"&&Symbol.iterator,_P=function(p){return xf&&p[xf]&&p[xf]()};function NP(p,k){for(var E=-1,x=Array(p);++E<p;)x[E]=k(E);return x}function wa(p){return p!=null&&typeof p=="object"}var $P="[object Arguments]";function DC(p){return wa(p)&&Io(p)==$P}var LC=Object.prototype,PP=LC.hasOwnProperty,jP=LC.propertyIsEnumerable,HP=DC(function(){return arguments}())?DC:function(p){return wa(p)&&PP.call(p,"callee")&&!jP.call(p,"callee")},gn=Array.isArray;function FP(){return!1}var MC=typeof e=="object"&&e&&!e.nodeType&&e,RC=MC&&!0&&n&&!n.nodeType&&n,zP=RC&&RC.exports===MC,AC=zP?Z.Buffer:void 0,UP=AC?AC.isBuffer:void 0,VP=UP||FP,qP=9007199254740991,WP=/^(?:0|[1-9]\d*)$/;function GP(p,k){var E=typeof p;return k=k==null?qP:k,!!k&&(E=="number"||E!="symbol"&&WP.test(p))&&p>-1&&p%1==0&&p<k}var ZP="[object Arguments]",YP="[object Array]",QP="[object Boolean]",KP="[object Date]",JP="[object Error]",XP="[object Function]",tj="[object Map]",ej="[object Number]",nj="[object Object]",oj="[object RegExp]",rj="[object Set]",ij="[object String]",sj="[object WeakMap]",lj="[object ArrayBuffer]",cj="[object DataView]",aj="[object Float32Array]",dj="[object Float64Array]",uj="[object Int8Array]",hj="[object Int16Array]",fj="[object Int32Array]",mj="[object Uint8Array]",gj="[object Uint8ClampedArray]",pj="[object Uint16Array]",Cj="[object Uint32Array]",Bt={};Bt[aj]=Bt[dj]=Bt[uj]=Bt[hj]=Bt[fj]=Bt[mj]=Bt[gj]=Bt[pj]=Bt[Cj]=!0,Bt[ZP]=Bt[YP]=Bt[lj]=Bt[QP]=Bt[cj]=Bt[KP]=Bt[JP]=Bt[XP]=Bt[tj]=Bt[ej]=Bt[nj]=Bt[oj]=Bt[rj]=Bt[ij]=Bt[sj]=!1;function bj(p){return wa(p)&&SC(p.length)&&!!Bt[Io(p)]}function vj(p){return function(k){return p(k)}}var OC=typeof e=="object"&&e&&!e.nodeType&&e,Js=OC&&!0&&n&&!n.nodeType&&n,kj=Js&&Js.exports===OC,Tf=kj&&R.process,_C=function(){try{var p=Js&&Js.require&&Js.require("util").types;return p||Tf&&Tf.binding&&Tf.binding("util")}catch{}}(),NC=_C&&_C.isTypedArray,yj=NC?vj(NC):bj,wj=Object.prototype,Bj=wj.hasOwnProperty;function Ej(p,k){var E=gn(p),x=!E&&HP(p),L=!E&&!x&&VP(p),D=!E&&!x&&!L&&yj(p),O=E||x||L||D,_=O?NP(p.length,String):[],V=_.length;for(var Q in p)(k||Bj.call(p,Q))&&!(O&&(Q=="length"||L&&(Q=="offset"||Q=="parent")||D&&(Q=="buffer"||Q=="byteLength"||Q=="byteOffset")||GP(Q,V)))&&_.push(Q);return _}var Ij=Object.prototype;function xj(p){var k=p&&p.constructor,E=typeof k=="function"&&k.prototype||Ij;return p===E}function Tj(p,k){return function(E){return p(k(E))}}var Sj=Tj(Object.keys,Object),Dj=Object.prototype,Lj=Dj.hasOwnProperty;function Mj(p){if(!xj(p))return Sj(p);var k=[];for(var E in Object(p))Lj.call(p,E)&&E!="constructor"&&k.push(E);return k}function Sf(p){return Ks(p)?Ej(p):Mj(p)}function Rj(p){var k=-1,E=p.length;return function(){return++k<E?{value:p[k],key:k}:null}}function Aj(p){var k=-1;return function(){var x=p.next();return x.done?null:(k++,{value:x.value,key:k})}}function Oj(p){var k=Sf(p),E=-1,x=k.length;return function L(){var D=k[++E];return D==="__proto__"?L():E<x?{value:p[D],key:D}:null}}function _j(p){if(Ks(p))return Rj(p);var k=_P(p);return k?Aj(k):Oj(p)}function On(p){return function(){if(p===null)throw new Error("Callback was already called.");var k=p;p=null,k.apply(this,arguments)}}function Ba(p){return function(k,E,x){if(x=xo(x||ht),p<=0||!k)return x(null);var L=_j(k),D=!1,O=0,_=!1;function V(G,X){if(O-=1,G)D=!0,x(G);else{if(X===If||D&&O<=0)return D=!0,x(null);_||Q()}}function Q(){for(_=!0;O<p&&!D;){var G=L();if(G===null){D=!0,O<=0&&x(null);return}O+=1,E(G.value,G.key,On(V))}_=!1}Q()}}function Cr(p,k,E,x){Ba(k)(p,I(E),x)}function ne(p,k){return function(E,x,L){return p(E,k,x,L)}}function Nj(p,k,E){E=xo(E||ht);var x=0,L=0,D=p.length;D===0&&E(null);function O(_,V){_?E(_):(++L===D||V===If)&&E(null)}for(;x<D;x++)k(p[x],x,On(O))}var $j=ne(Cr,1/0),To=function(p,k,E){var x=Ks(p)?Nj:$j;x(p,I(k),E)};function pi(p){return function(k,E,x){return p(To,k,I(E),x)}}function $C(p,k,E,x){x=x||ht,k=k||[];var L=[],D=0,O=I(E);p(k,function(_,V,Q){var G=D++;O(_,function(X,Et){L[G]=Et,Q(X)})},function(_){x(_,L)})}var Ea=pi($C),PC=M(Ea);function Ci(p){return function(k,E,x,L){return p(Ba(E),k,I(x),L)}}var bi=Ci($C),Df=ne(bi,1),jC=M(Df);function Ia(p,k){for(var E=-1,x=p==null?0:p.length;++E<x&&k(p[E],E,p)!==!1;);return p}function Pj(p){return function(k,E,x){for(var L=-1,D=Object(k),O=x(k),_=O.length;_--;){var V=O[p?_:++L];if(E(D[V],V,D)===!1)break}return k}}var jj=Pj();function Xs(p,k){return p&&jj(p,k,Sf)}function Hj(p,k,E,x){for(var L=p.length,D=E+(x?1:-1);x?D--:++D<L;)if(k(p[D],D,p))return D;return-1}function Fj(p){return p!==p}function zj(p,k,E){for(var x=E-1,L=p.length;++x<L;)if(p[x]===k)return x;return-1}function xa(p,k,E){return k===k?zj(p,k,E):Hj(p,Fj,E)}var Lf=function(p,k,E){typeof k=="function"&&(E=k,k=null),E=xo(E||ht);var x=Sf(p),L=x.length;if(!L)return E(null);k||(k=L);var D={},O=0,_=!1,V=Object.create(null),Q=[],G=[],X={};Xs(p,function(Dt,Lt){if(!gn(Dt)){Et(Lt,[Dt]),G.push(Lt);return}var Jt=Dt.slice(0,Dt.length-1),no=Jt.length;if(no===0){Et(Lt,Dt),G.push(Lt);return}X[Lt]=no,Ia(Jt,function(wi){if(!p[wi])throw new Error("async.auto task `"+Lt+"` has a non-existent dependency `"+wi+"` in "+Jt.join(", "));_n(wi,function(){no--,no===0&&Et(Lt,Dt)})})}),OH(),le();function Et(Dt,Lt){Q.push(function(){Nn(Dt,Lt)})}function le(){if(Q.length===0&&O===0)return E(null,D);for(;Q.length&&O<k;){var Dt=Q.shift();Dt()}}function _n(Dt,Lt){var Jt=V[Dt];Jt||(Jt=V[Dt]=[]),Jt.push(Lt)}function Ve(Dt){var Lt=V[Dt]||[];Ia(Lt,function(Jt){Jt()}),le()}function Nn(Dt,Lt){if(!_){var Jt=On(function(wi,zf){if(O--,arguments.length>2&&(zf=o(arguments,1)),wi){var Uf={};Xs(D,function(NH,$H){Uf[$H]=NH}),Uf[Dt]=zf,_=!0,V=Object.create(null),E(wi,Uf)}else D[Dt]=zf,Ve(Dt)});O++;var no=I(Lt[Lt.length-1]);Lt.length>1?no(D,Jt):no(Jt)}}function OH(){for(var Dt,Lt=0;G.length;)Dt=G.pop(),Lt++,Ia(_H(Dt),function(Jt){--X[Jt]===0&&G.push(Jt)});if(Lt!==L)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function _H(Dt){var Lt=[];return Xs(p,function(Jt,no){gn(Jt)&&xa(Jt,Dt,0)>=0&&Lt.push(no)}),Lt}};function vi(p,k){for(var E=-1,x=p==null?0:p.length,L=Array(x);++E<x;)L[E]=k(p[E],E,p);return L}var Uj="[object Symbol]";function Vj(p){return typeof p=="symbol"||wa(p)&&Io(p)==Uj}var qj=1/0,HC=ot?ot.prototype:void 0,FC=HC?HC.toString:void 0;function Mf(p){if(typeof p=="string")return p;if(gn(p))return vi(p,Mf)+"";if(Vj(p))return FC?FC.call(p):"";var k=p+"";return k=="0"&&1/p==-qj?"-0":k}function Wj(p,k,E){var x=-1,L=p.length;k<0&&(k=-k>L?0:L+k),E=E>L?L:E,E<0&&(E+=L),L=k>E?0:E-k>>>0,k>>>=0;for(var D=Array(L);++x<L;)D[x]=p[x+k];return D}function Gj(p,k,E){var x=p.length;return E=E===void 0?x:E,!k&&E>=x?p:Wj(p,k,E)}function Zj(p,k){for(var E=p.length;E--&&xa(k,p[E],0)>-1;);return E}function Yj(p,k){for(var E=-1,x=p.length;++E<x&&xa(k,p[E],0)>-1;);return E}function Qj(p){return p.split("")}var Kj="\\ud800-\\udfff",Jj="\\u0300-\\u036f",Xj="\\ufe20-\\ufe2f",tH="\\u20d0-\\u20ff",eH=Jj+Xj+tH,nH="\\ufe0e\\ufe0f",oH="\\u200d",rH=RegExp("["+oH+Kj+eH+nH+"]");function iH(p){return rH.test(p)}var zC="\\ud800-\\udfff",sH="\\u0300-\\u036f",lH="\\ufe20-\\ufe2f",cH="\\u20d0-\\u20ff",aH=sH+lH+cH,dH="\\ufe0e\\ufe0f",uH="["+zC+"]",Rf="["+aH+"]",Af="\\ud83c[\\udffb-\\udfff]",hH="(?:"+Rf+"|"+Af+")",UC="[^"+zC+"]",VC="(?:\\ud83c[\\udde6-\\uddff]){2}",qC="[\\ud800-\\udbff][\\udc00-\\udfff]",fH="\\u200d",WC=hH+"?",GC="["+dH+"]?",mH="(?:"+fH+"(?:"+[UC,VC,qC].join("|")+")"+GC+WC+")*",gH=GC+WC+mH,pH="(?:"+[UC+Rf+"?",Rf,VC,qC,uH].join("|")+")",CH=RegExp(Af+"(?="+Af+")|"+pH+gH,"g");function bH(p){return p.match(CH)||[]}function ZC(p){return iH(p)?bH(p):Qj(p)}function vH(p){return p==null?"":Mf(p)}var kH=/^\s+|\s+$/g;function yH(p,k,E){if(p=vH(p),p&&(E||k===void 0))return p.replace(kH,"");if(!p||!(k=Mf(k)))return p;var x=ZC(p),L=ZC(k),D=Yj(x,L),O=Zj(x,L)+1;return Gj(x,D,O).join("")}var wH=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,BH=/,/,EH=/(=.+)?(\s*)$/,IH=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function xH(p){return p=p.toString().replace(IH,""),p=p.match(wH)[2].replace(" ",""),p=p?p.split(BH):[],p=p.map(function(k){return yH(k.replace(EH,""))}),p}function YC(p,k){var E={};Xs(p,function(x,L){var D,O=S(x),_=!O&&x.length===1||O&&x.length===0;if(gn(x))D=x.slice(0,-1),x=x[x.length-1],E[L]=D.concat(D.length>0?V:x);else if(_)E[L]=x;else{if(D=xH(x),x.length===0&&!O&&D.length===0)throw new Error("autoInject task functions require explicit parameters.");O||D.pop(),E[L]=D.concat(V)}function V(Q,G){var X=vi(D,function(Et){return Q[Et]});X.push(G),I(x).apply(null,X)}}),Lf(E,k)}function pn(){this.head=this.tail=null,this.length=0}function QC(p,k){p.length=1,p.head=p.tail=k}pn.prototype.removeLink=function(p){return p.prev?p.prev.next=p.next:this.head=p.next,p.next?p.next.prev=p.prev:this.tail=p.prev,p.prev=p.next=null,this.length-=1,p},pn.prototype.empty=function(){for(;this.head;)this.shift();return this},pn.prototype.insertAfter=function(p,k){k.prev=p,k.next=p.next,p.next?p.next.prev=k:this.tail=k,p.next=k,this.length+=1},pn.prototype.insertBefore=function(p,k){k.prev=p.prev,k.next=p,p.prev?p.prev.next=k:this.head=k,p.prev=k,this.length+=1},pn.prototype.unshift=function(p){this.head?this.insertBefore(this.head,p):QC(this,p)},pn.prototype.push=function(p){this.tail?this.insertAfter(this.tail,p):QC(this,p)},pn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},pn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},pn.prototype.toArray=function(){for(var p=Array(this.length),k=this.head,E=0;E<this.length;E++)p[E]=k.data,k=k.next;return p},pn.prototype.remove=function(p){for(var k=this.head;k;){var E=k.next;p(k)&&this.removeLink(k),k=E}return this};function KC(p,k,E){if(k==null)k=1;else if(k===0)throw new Error("Concurrency must not be zero");var x=I(p),L=0,D=[],O=!1;function _(X,Et,le){if(le!=null&&typeof le!="function")throw new Error("task callback must be a function");if(G.started=!0,gn(X)||(X=[X]),X.length===0&&G.idle())return m(function(){G.drain()});for(var _n=0,Ve=X.length;_n<Ve;_n++){var Nn={data:X[_n],callback:le||ht};Et?G._tasks.unshift(Nn):G._tasks.push(Nn)}O||(O=!0,m(function(){O=!1,G.process()}))}function V(X){return function(Et){L-=1;for(var le=0,_n=X.length;le<_n;le++){var Ve=X[le],Nn=xa(D,Ve,0);Nn===0?D.shift():Nn>0&&D.splice(Nn,1),Ve.callback.apply(Ve,arguments),Et!=null&&G.error(Et,Ve.data)}L<=G.concurrency-G.buffer&&G.unsaturated(),G.idle()&&G.drain(),G.process()}}var Q=!1,G={_tasks:new pn,concurrency:k,payload:E,saturated:ht,unsaturated:ht,buffer:k/4,empty:ht,drain:ht,error:ht,started:!1,paused:!1,push:function(X,Et){_(X,!1,Et)},kill:function(){G.drain=ht,G._tasks.empty()},unshift:function(X,Et){_(X,!0,Et)},remove:function(X){G._tasks.remove(X)},process:function(){if(!Q){for(Q=!0;!G.paused&&L<G.concurrency&&G._tasks.length;){var X=[],Et=[],le=G._tasks.length;G.payload&&(le=Math.min(le,G.payload));for(var _n=0;_n<le;_n++){var Ve=G._tasks.shift();X.push(Ve),D.push(Ve),Et.push(Ve.data)}L+=1,G._tasks.length===0&&G.empty(),L===G.concurrency&&G.saturated();var Nn=On(V(X));x(Et,Nn)}Q=!1}},length:function(){return G._tasks.length},running:function(){return L},workersList:function(){return D},idle:function(){return G._tasks.length+L===0},pause:function(){G.paused=!0},resume:function(){G.paused!==!1&&(G.paused=!1,m(G.process))}};return G}function JC(p,k){return KC(p,1,k)}var ki=ne(Cr,1);function So(p,k,E,x){x=xo(x||ht);var L=I(E);ki(p,function(D,O,_){L(k,D,function(V,Q){k=Q,_(V)})},function(D){x(D,k)})}function Of(){var p=vi(arguments,I);return function(){var k=o(arguments),E=this,x=k[k.length-1];typeof x=="function"?k.pop():x=ht,So(p,k,function(L,D,O){D.apply(E,L.concat(function(_){var V=o(arguments,1);O(_,V)}))},function(L,D){x.apply(E,[L].concat(D))})}}var XC=function(){return Of.apply(null,o(arguments).reverse())},TH=Array.prototype.concat,Ta=function(p,k,E,x){x=x||ht;var L=I(E);bi(p,k,function(D,O){L(D,function(_){return _?O(_):O(null,o(arguments,1))})},function(D,O){for(var _=[],V=0;V<O.length;V++)O[V]&&(_=TH.apply(_,O[V]));return x(D,_)})},t9=ne(Ta,1/0),e9=ne(Ta,1),n9=function(){var p=o(arguments),k=[null].concat(p);return function(){var E=arguments[arguments.length-1];return E.apply(this,k)}};function tl(p){return p}function yi(p,k){return function(E,x,L,D){D=D||ht;var O=!1,_;E(x,function(V,Q,G){L(V,function(X,Et){X?G(X):p(Et)&&!_?(O=!0,_=k(!0,V),G(null,If)):G()})},function(V){V?D(V):D(null,O?_:k(!1))})}}function o9(p,k){return k}var Sa=pi(yi(tl,o9)),el=Ci(yi(tl,o9)),Da=ne(el,1);function r9(p){return function(k){var E=o(arguments,1);E.push(function(x){var L=o(arguments,1);typeof console=="object"&&(x?console.error&&console.error(x):console[p]&&Ia(L,function(D){console[p](D)}))}),I(k).apply(null,E)}}var i9=r9("dir");function s9(p,k,E){E=On(E||ht);var x=I(p),L=I(k);function D(_){if(_)return E(_);var V=o(arguments,1);V.push(O),L.apply(this,V)}function O(_,V){if(_)return E(_);if(!V)return E(null);x(D)}O(null,!0)}function _f(p,k,E){E=On(E||ht);var x=I(p),L=function(D){if(D)return E(D);var O=o(arguments,1);if(k.apply(this,O))return x(L);E.apply(null,[null].concat(O))};x(L)}function l9(p,k,E){_f(p,function(){return!k.apply(this,arguments)},E)}function c9(p,k,E){E=On(E||ht);var x=I(k),L=I(p);function D(_){if(_)return E(_);L(O)}function O(_,V){if(_)return E(_);if(!V)return E(null);x(D)}L(O)}function a9(p){return function(k,E,x){return p(k,x)}}function La(p,k,E){To(p,a9(I(k)),E)}function nl(p,k,E,x){Ba(k)(p,a9(I(E)),x)}var ol=ne(nl,1);function Nf(p){return S(p)?p:i(function(k,E){var x=!0;k.push(function(){var L=arguments;x?m(function(){E.apply(null,L)}):E.apply(null,L)}),p.apply(this,k),x=!1})}function Ma(p){return!p}var Ra=pi(yi(Ma,Ma)),rl=Ci(yi(Ma,Ma)),Aa=ne(rl,1);function d9(p){return function(k){return k==null?void 0:k[p]}}function SH(p,k,E,x){var L=new Array(k.length);p(k,function(D,O,_){E(D,function(V,Q){L[O]=!!Q,_(V)})},function(D){if(D)return x(D);for(var O=[],_=0;_<k.length;_++)L[_]&&O.push(k[_]);x(null,O)})}function DH(p,k,E,x){var L=[];p(k,function(D,O,_){E(D,function(V,Q){V?_(V):(Q&&L.push({index:O,value:D}),_())})},function(D){D?x(D):x(null,vi(L.sort(function(O,_){return O.index-_.index}),d9("value")))})}function $f(p,k,E,x){var L=Ks(k)?SH:DH;L(p,k,I(E),x||ht)}var Oa=pi($f),il=Ci($f),_a=ne(il,1);function u9(p,k){var E=On(k||ht),x=I(Nf(p));function L(D){if(D)return E(D);x(L)}L()}var Na=function(p,k,E,x){x=x||ht;var L=I(E);bi(p,k,function(D,O){L(D,function(_,V){return _?O(_):O(null,{key:V,val:D})})},function(D,O){for(var _={},V=Object.prototype.hasOwnProperty,Q=0;Q<O.length;Q++)if(O[Q]){var G=O[Q].key,X=O[Q].val;V.call(_,G)?_[G].push(X):_[G]=[X]}return x(D,_)})},h9=ne(Na,1/0),f9=ne(Na,1),m9=r9("log");function $a(p,k,E,x){x=xo(x||ht);var L={},D=I(E);Cr(p,k,function(O,_,V){D(O,_,function(Q,G){if(Q)return V(Q);L[_]=G,V()})},function(O){x(O,L)})}var g9=ne($a,1/0),p9=ne($a,1);function C9(p,k){return k in p}function b9(p,k){var E=Object.create(null),x=Object.create(null);k=k||tl;var L=I(p),D=i(function(_,V){var Q=k.apply(null,_);C9(E,Q)?m(function(){V.apply(null,E[Q])}):C9(x,Q)?x[Q].push(V):(x[Q]=[V],L.apply(null,_.concat(function(){var G=o(arguments);E[Q]=G;var X=x[Q];delete x[Q];for(var Et=0,le=X.length;Et<le;Et++)X[Et].apply(null,G)})))});return D.memo=E,D.unmemoized=p,D}var Pa;c?Pa=process.nextTick:l?Pa=setImmediate:Pa=a;var v9=u(Pa);function Pf(p,k,E){E=E||ht;var x=Ks(k)?[]:{};p(k,function(L,D,O){I(L)(function(_,V){arguments.length>2&&(V=o(arguments,1)),x[D]=V,O(_)})},function(L){E(L,x)})}function k9(p,k){Pf(To,p,k)}function y9(p,k,E){Pf(Ba(k),p,E)}var jf=function(p,k){var E=I(p);return KC(function(x,L){E(x[0],L)},k,1)},w9=function(p,k){var E=jf(p,k);return E.push=function(x,L,D){if(D==null&&(D=ht),typeof D!="function")throw new Error("task callback must be a function");if(E.started=!0,gn(x)||(x=[x]),x.length===0)return m(function(){E.drain()});L=L||0;for(var O=E._tasks.head;O&&L>=O.priority;)O=O.next;for(var _=0,V=x.length;_<V;_++){var Q={data:x[_],priority:L,callback:D};O?E._tasks.insertBefore(O,Q):E._tasks.push(Q)}m(E.process)},delete E.unshift,E};function B9(p,k){if(k=xo(k||ht),!gn(p))return k(new TypeError("First argument to race must be an array of functions"));if(!p.length)return k();for(var E=0,x=p.length;E<x;E++)I(p[E])(k)}function ja(p,k,E,x){var L=o(p).reverse();So(L,k,E,x)}function Ha(p){var k=I(p);return i(function(x,L){return x.push(function(O,_){if(O)L(null,{error:O});else{var V;arguments.length<=2?V=_:V=o(arguments,1),L(null,{value:V})}}),k.apply(this,x)})}function E9(p){var k;return gn(p)?k=vi(p,Ha):(k={},Xs(p,function(E,x){k[x]=Ha.call(this,E)})),k}function I9(p,k,E,x){$f(p,k,function(L,D){E(L,function(O,_){D(O,!_)})},x)}var x9=pi(I9),Hf=Ci(I9),T9=ne(Hf,1);function S9(p){return function(){return p}}function Fa(p,k,E){var x=5,L=0,D={times:x,intervalFunc:S9(L)};function O(G,X){if(typeof X=="object")G.times=+X.times||x,G.intervalFunc=typeof X.interval=="function"?X.interval:S9(+X.interval||L),G.errorFilter=X.errorFilter;else if(typeof X=="number"||typeof X=="string")G.times=+X||x;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof p=="function"?(E=k||ht,k=p):(O(D,p),E=E||ht),typeof k!="function")throw new Error("Invalid arguments for async.retry");var _=I(k),V=1;function Q(){_(function(G){G&&V++<D.times&&(typeof D.errorFilter!="function"||D.errorFilter(G))?setTimeout(Q,D.intervalFunc(V)):E.apply(null,arguments)})}Q()}var D9=function(p,k){k||(k=p,p=null);var E=I(k);return i(function(x,L){function D(O){E.apply(null,x.concat(O))}p?Fa(p,D,L):Fa(D,L)})};function L9(p,k){Pf(ki,p,k)}var za=pi(yi(Boolean,tl)),sl=Ci(yi(Boolean,tl)),Ua=ne(sl,1);function M9(p,k,E){var x=I(k);Ea(p,function(D,O){x(D,function(_,V){if(_)return O(_);O(null,{value:D,criteria:V})})},function(D,O){if(D)return E(D);E(null,vi(O.sort(L),d9("value")))});function L(D,O){var _=D.criteria,V=O.criteria;return _<V?-1:_>V?1:0}}function R9(p,k,E){var x=I(p);return i(function(L,D){var O=!1,_;function V(){var Q=p.name||"anonymous",G=new Error('Callback function "'+Q+'" timed out.');G.code="ETIMEDOUT",E&&(G.info=E),O=!0,D(G)}L.push(function(){O||(D.apply(null,arguments),clearTimeout(_))}),_=setTimeout(V,k),x.apply(null,L)})}var LH=Math.ceil,MH=Math.max;function RH(p,k,E,x){for(var L=-1,D=MH(LH((k-p)/(E||1)),0),O=Array(D);D--;)O[x?D:++L]=p,p+=E;return O}function Va(p,k,E,x){var L=I(E);bi(RH(0,p,1),k,L,x)}var A9=ne(Va,1/0),O9=ne(Va,1);function _9(p,k,E,x){arguments.length<=3&&(x=E,E=k,k=gn(p)?[]:{}),x=xo(x||ht);var L=I(E);To(p,function(D,O,_){L(k,D,O,_)},function(D){x(D,k)})}function N9(p,k){var E=null,x;k=k||ht,ol(p,function(L,D){I(L)(function(O,_){arguments.length>2?x=o(arguments,1):x=_,E=O,D(!O)})},function(){k(E,x)})}function $9(p){return function(){return(p.unmemoized||p).apply(null,arguments)}}function Ff(p,k,E){E=On(E||ht);var x=I(k);if(!p())return E(null);var L=function(D){if(D)return E(D);if(p())return x(L);var O=o(arguments,1);E.apply(null,[null].concat(O))};x(L)}function P9(p,k,E){Ff(function(){return!p.apply(this,arguments)},k,E)}var j9=function(p,k){if(k=xo(k||ht),!gn(p))return k(new Error("First argument to waterfall must be an array of functions"));if(!p.length)return k();var E=0;function x(D){var O=I(p[E++]);D.push(On(L)),O.apply(null,D)}function L(D){if(D||E===p.length)return k.apply(null,arguments);x(o(arguments,1))}x([])},AH={apply:r,applyEach:PC,applyEachSeries:jC,asyncify:C,auto:Lf,autoInject:YC,cargo:JC,compose:XC,concat:t9,concatLimit:Ta,concatSeries:e9,constant:n9,detect:Sa,detectLimit:el,detectSeries:Da,dir:i9,doDuring:s9,doUntil:l9,doWhilst:_f,during:c9,each:La,eachLimit:nl,eachOf:To,eachOfLimit:Cr,eachOfSeries:ki,eachSeries:ol,ensureAsync:Nf,every:Ra,everyLimit:rl,everySeries:Aa,filter:Oa,filterLimit:il,filterSeries:_a,forever:u9,groupBy:h9,groupByLimit:Na,groupBySeries:f9,log:m9,map:Ea,mapLimit:bi,mapSeries:Df,mapValues:g9,mapValuesLimit:$a,mapValuesSeries:p9,memoize:b9,nextTick:v9,parallel:k9,parallelLimit:y9,priorityQueue:w9,queue:jf,race:B9,reduce:So,reduceRight:ja,reflect:Ha,reflectAll:E9,reject:x9,rejectLimit:Hf,rejectSeries:T9,retry:Fa,retryable:D9,seq:Of,series:L9,setImmediate:m,some:za,someLimit:sl,someSeries:Ua,sortBy:M9,timeout:R9,times:A9,timesLimit:Va,timesSeries:O9,transform:_9,tryEach:N9,unmemoize:$9,until:P9,waterfall:j9,whilst:Ff,all:Ra,allLimit:rl,allSeries:Aa,any:za,anyLimit:sl,anySeries:Ua,find:Sa,findLimit:el,findSeries:Da,forEach:La,forEachSeries:ol,forEachLimit:nl,forEachOf:To,forEachOfSeries:ki,forEachOfLimit:Cr,inject:So,foldl:So,foldr:ja,select:Oa,selectLimit:il,selectSeries:_a,wrapSync:C};e.default=AH,e.apply=r,e.applyEach=PC,e.applyEachSeries=jC,e.asyncify=C,e.auto=Lf,e.autoInject=YC,e.cargo=JC,e.compose=XC,e.concat=t9,e.concatLimit=Ta,e.concatSeries=e9,e.constant=n9,e.detect=Sa,e.detectLimit=el,e.detectSeries=Da,e.dir=i9,e.doDuring=s9,e.doUntil=l9,e.doWhilst=_f,e.during=c9,e.each=La,e.eachLimit=nl,e.eachOf=To,e.eachOfLimit=Cr,e.eachOfSeries=ki,e.eachSeries=ol,e.ensureAsync=Nf,e.every=Ra,e.everyLimit=rl,e.everySeries=Aa,e.filter=Oa,e.filterLimit=il,e.filterSeries=_a,e.forever=u9,e.groupBy=h9,e.groupByLimit=Na,e.groupBySeries=f9,e.log=m9,e.map=Ea,e.mapLimit=bi,e.mapSeries=Df,e.mapValues=g9,e.mapValuesLimit=$a,e.mapValuesSeries=p9,e.memoize=b9,e.nextTick=v9,e.parallel=k9,e.parallelLimit=y9,e.priorityQueue=w9,e.queue=jf,e.race=B9,e.reduce=So,e.reduceRight=ja,e.reflect=Ha,e.reflectAll=E9,e.reject=x9,e.rejectLimit=Hf,e.rejectSeries=T9,e.retry=Fa,e.retryable=D9,e.seq=Of,e.series=L9,e.setImmediate=m,e.some=za,e.someLimit=sl,e.someSeries=Ua,e.sortBy=M9,e.timeout=R9,e.times=A9,e.timesLimit=Va,e.timesSeries=O9,e.transform=_9,e.tryEach=N9,e.unmemoize=$9,e.until=P9,e.waterfall=j9,e.whilst=Ff,e.all=Ra,e.allLimit=rl,e.allSeries=Aa,e.any=za,e.anyLimit=sl,e.anySeries=Ua,e.find=Sa,e.findLimit=el,e.findSeries=Da,e.forEach=La,e.forEachSeries=ol,e.forEachLimit=nl,e.forEachOf=To,e.forEachOfSeries=ki,e.forEachOfLimit=Cr,e.inject=So,e.foldl=So,e.foldr=ja,e.select=Oa,e.selectLimit=il,e.selectSeries=_a,e.wrapSync=C,Object.defineProperty(e,"__esModule",{value:!0})})})(ju,ju.exports);var b2={exports:{}},Hu=b2.exports=function(n,t){if(t||(t=16),n===void 0&&(n=128),n<=0)return"0";for(var e=Math.log(Math.pow(2,n))/Math.log(t),o=2;e===1/0;o*=2)e=Math.log(Math.pow(2,n/o))/Math.log(t)*o;for(var r=e-Math.floor(e),i="",o=0;o<Math.floor(e);o++){var s=Math.floor(Math.random()*t).toString(t);i=s+i}if(r){var l=Math.pow(t,r),s=Math.floor(Math.random()*l).toString(t);i=s+i}var c=parseInt(i,t);return c!==1/0&&c>=Math.pow(2,n)?Hu(n,t):i};Hu.rack=function(n,t,e){var o=function(i){var s=0;do{if(s++>10)if(e)n+=e;else throw new Error("too many ID collisions, use more bits");var l=Hu(n,t)}while(Object.hasOwnProperty.call(r,l));return r[l]=i,l},r=o.hats={};return o.get=function(i){return o.hats[i]},o.set=function(i,s){return o.hats[i]=s,o},o.bits=n||128,o.base=t||16,o};var v2=fo,Ly=p2,My=C2,uc=rn,Fu=ju.exports,Ry=b2.exports,k2=Xo.ACTIONS,y2=Pt;function Pt(n,t){if(v2.EventEmitter.call(this),!t||typeof t!="string")throw new Error("Presence channel must be provided");this.connection=n,this.channel=t,this.wantSubscribe=!1,this.subscribed=!1,this.remotePresences={},this.localPresences={},this._remotePresenceInstances={},this._subscriptionCallbacksBySeq={},this._wantsDestroy=!1}v2.mixin(Pt),Pt.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Pt.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Pt.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||Ry();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Pt.prototype.destroy=function(n){this._wantsDestroy=!0;var t=this,e=Object.keys(t.localPresences);this.unsubscribe(function(o){if(o)return t._callbackOrEmit(o,n);var r=Object.keys(t._remotePresenceInstances);Fu.parallel([function(i){Fu.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();Fu.each(r,function(s,l){t._remotePresenceInstances[s].destroy(l)},i)}],function(i){t._wantsDestroy&&delete t.connection._presences[t.channel],t._callbackOrEmit(i,n)})})},Pt.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?k2.presenceSubscribe:k2.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,o,this)},Pt.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Pt.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Pt.prototype._receiveUpdate=function(n,t){var e=uc.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=uc.digOrCreate(this._remotePresenceInstances,t.id,function(){return o._createRemotePresence(t.id)});r.receiveUpdate(t)},Pt.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Pt.prototype._broadcastAllLocalPresence=function(n){if(n)return this.emit("error",n);for(var t in this.localPresences){var e=this.localPresences[t];e.value!==null&&e.send()}},Pt.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Pt.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Pt.prototype._resubscribe=function(){var n=[];for(var t in this._subscriptionCallbacksBySeq){var e=this._subscriptionCallback(t);n.push(e)}if(!this.wantSubscribe)return this._callEachOrEmit(n);var o=this;this.subscribe(function(r){o._callEachOrEmit(n,r)})},Pt.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Pt.prototype._callbackOrEmit=function(n,t){if(t)return uc.nextTick(t,n);n&&this.emit("error",n)},Pt.prototype._createLocalPresence=function(n){return new Ly(this,n)},Pt.prototype._createRemotePresence=function(n){return new My(this,n)},Pt.prototype._callEachOrEmit=function(n,t){var e=uc.callEach(n,t);!e&&t&&this.emit("error",t)};var ss=p2,w2=sc,Ay=rn,B2=w2.CODES,Oy=ln;function ln(n,t){ss.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this._doc=this.connection.get(this.collection,this.id),this._isSending=!1,this._docDataVersionByPresenceVersion={},this._opHandler=this._transformAgainstOp.bind(this),this._createOrDelHandler=this._handleCreateOrDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._destroyHandler=this.destroy.bind(this),this._registerWithDoc()}ln.prototype=Object.create(ss.prototype),ln.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:B2.ERR_DOC_DOES_NOT_EXIST,message:"Cannot submit presence. Document has not been created"};return this._callbackOrEmit(e,t)}this._docDataVersionByPresenceVersion[this.presenceVersion]=this._doc._dataStateVersion,ss.prototype.submit.call(this,n,t)},ln.prototype.destroy=function(n){this._doc.removeListener("op",this._opHandler),this._doc.removeListener("create",this._createOrDelHandler),this._doc.removeListener("del",this._createOrDelHandler),this._doc.removeListener("load",this._loadHandler),this._doc.removeListener("destroy",this._destroyHandler),ss.prototype.destroy.call(this,n)},ln.prototype._sendPending=function(){if(!this._isSending){this._isSending=!0;var n=this;this._doc.whenNothingPending(function(){n._isSending=!1,n.connection.canSend&&(n._pendingMessages.forEach(function(t){t.t=n._doc.type.uri,t.v=n._doc.version,n.connection.send(t)}),n._pendingMessages=[],n._docDataVersionByPresenceVersion={})})}},ln.prototype._registerWithDoc=function(){this._doc.on("op",this._opHandler),this._doc.on("create",this._createOrDelHandler),this._doc.on("del",this._createOrDelHandler),this._doc.on("load",this._loadHandler),this._doc.on("destroy",this._destroyHandler)},ln.prototype._transformAgainstOp=function(n,t){var e=this,o=this._doc._dataStateVersion;this._pendingMessages.forEach(function(r){var i=e._docDataVersionByPresenceVersion[r.pv];if(!(i>=o))try{r.p=e._transformPresence(r.p,n,t),e._docDataVersionByPresenceVersion[r.pv]=o}catch(l){var s=e._getCallback(r.pv);e._callbackOrEmit(l,s)}});try{this.value=this._transformPresence(this.value,n,t)}catch(r){this.emit("error",r)}},ln.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},ln.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},ln.prototype._message=function(){var n=ss.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},ln.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!Ay.supportsPresence(o))throw new w2(B2.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var E2={};(function(n){var t=os,e=sc,o=rn,r=e.CODES;n.checkOp=function(l){if(l==null||typeof l!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Op must be an object");if(l.create!=null){if(typeof l.create!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"Create data must be an object");var c=l.create.type;if(typeof c!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var a=t.map[c];if(a==null||typeof a!="object")return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type")}else if(l.del!=null){if(l.del!==!0)return new e(r.ERR_OT_OP_BADLY_FORMED,"del value must be true")}else if(!("op"in l))return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing op, create, or del");if(l.src!=null&&typeof l.src!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"src must be a string");if(l.seq!=null&&typeof l.seq!="number")return new e(r.ERR_OT_OP_BADLY_FORMED,"seq must be a number");if(l.src==null&&l.seq!=null||l.src!=null&&l.seq==null)return new e(r.ERR_OT_OP_BADLY_FORMED,"Both src and seq must be set together");if(l.m!=null&&typeof l.m!="object")return new e(r.ERR_OT_OP_BADLY_FORMED,"op.m must be an object or null")},n.normalizeType=function(l){return t.map[l]&&t.map[l].uri},n.apply=function(l,c){if(typeof l!="object")return new e(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&c.v!=null&&l.v!==c.v)return new e(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(c.create){if(l.type)return new e(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var a=c.create,u=t.map[a.type];if(!u)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=u.create(a.data),l.type=u.uri,l.v++}catch(m){return m}}else if(c.del)l.data=void 0,l.type=null,l.v++;else if("op"in c){var f=i(l,c.op);if(f)return f;l.v++}else l.v++};function i(l,c){if(!l.type)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(c===void 0)return new e(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var a=t.map[l.type];if(!a)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=a.apply(l.data,c)}catch(u){return new e(r.ERR_OT_OP_NOT_APPLIED,u.message)}}n.transform=function(l,c,a){if(c.v!=null&&c.v!==a.v)return new e(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(a.del){if(c.create||"op"in c)return new e(r.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(a.create&&("op"in c||c.create||c.del)||"op"in a&&c.create)return new e(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in a&&"op"in c){if(!l)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(typeof l=="string"&&(l=t.map[l],!l))return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{c.op=l.transform(c.op,a.op,"left")}catch(u){return u}}}c.v!=null&&c.v++},n.applyOps=function(l,c,a){a=a||{};for(var u=0;u<c.length;u++){var f=c[u];if(a._normalizeLegacyJson0Ops)try{s(l,f)}catch{return new e(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=f.v;var m=n.apply(l,f);if(m)return m}},n.transformPresence=function(l,c,a){var u=this.checkOp(c);if(u)return u;var f=l.t;if(typeof f=="string"&&(f=t.map[f]),!f)return{code:r.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!o.supportsPresence(f))return{code:r.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(c.create||c.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:f.transformPresence(l.p,c.op,a)}catch(m){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:m.message||m}}l.v++};function s(l,c){if(l.type===t.defaultType.uri){var a=c.op;if(!!a){var u=l.data;a.length>1&&(u=o.clone(u));for(var f=0;f<a.length;f++){var m=a[f];typeof m.lm=="string"&&(m.lm=+m.lm);for(var C=m.p,v=u,B=0;B<C.length;B++){var y=C[B];Object.prototype.toString.call(v)=="[object Array]"?C[B]=+y:v.constructor===Object&&(C[B]=y.toString()),v=v[y]}f<a.length-1&&(u=t.defaultType.apply(u,[m]))}}}}})(E2);var ls=C2,_y=E2,Ny=Pe;function Pe(n,t){ls.call(this,n,t),this.collection=this.presence.collection,this.id=this.presence.id,this.src=null,this.presenceVersion=null,this._doc=this.connection.get(this.collection,this.id),this._pending=null,this._opCache=null,this._pendingSetPending=!1,this._opHandler=this._handleOp.bind(this),this._createDelHandler=this._handleCreateDel.bind(this),this._loadHandler=this._handleLoad.bind(this),this._registerWithDoc()}Pe.prototype=Object.create(ls.prototype),Pe.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},Pe.prototype.destroy=function(n){this._doc.removeListener("op",this._opHandler),this._doc.removeListener("create",this._createDelHandler),this._doc.removeListener("del",this._createDelHandler),this._doc.removeListener("load",this._loadHandler),ls.prototype.destroy.call(this,n)},Pe.prototype._registerWithDoc=function(){this._doc.on("op",this._opHandler),this._doc.on("create",this._createDelHandler),this._doc.on("del",this._createDelHandler),this._doc.on("load",this._loadHandler)},Pe.prototype._setPendingPresence=function(){if(!this._pendingSetPending){this._pendingSetPending=!0;var n=this;this._doc.whenNothingPending(function(){if(n._pendingSetPending=!1,!!n._pending){if(n._pending.pv<n.presenceVersion)return n._pending=null;if(n._pending.v>n._doc.version)return n._doc.fetch();!n._catchUpStalePresence()||(n.value=n._pending.p,n.presenceVersion=n._pending.pv,n._pending=null,n.presence._updateRemotePresence(n))}})}},Pe.prototype._handleOp=function(n,t,e){var o=e===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},ls.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},ls.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},Pe.prototype._transformAgainstOp=function(n,t){if(!!this.value){try{this.value=this._doc.type.transformPresence(this.value,n,t)}catch(e){return this.presence.emit("error",e)}this.presence._updateRemotePresence(this)}},Pe.prototype._catchUpStalePresence=function(){if(this._pending.v>=this._doc.version)return!0;if(!this._opCache)return this._startCachingOps(),this._doc.fetch(),this.presence.subscribe(),!1;for(;this._opCache[this._pending.v];){var n=this._opCache[this._pending.v],t=n.op,e=n.isOwnOp;t===null?(this._pending.p=null,this._pending.v++):_y.transformPresence(this._pending,t,e)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},Pe.prototype._startCachingOps=function(){this._opCache=[]},Pe.prototype._stopCachingOps=function(){this._opCache=null},Pe.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var I2=y2,$y=Oy,Py=Ny;function Nr(n,t,e){var o=Nr.channel(t,e);I2.call(this,n,o),this.collection=t,this.id=e}var jy=Nr;Nr.prototype=Object.create(I2.prototype),Nr.channel=function(n,t){return n+"."+t},Nr.prototype._createLocalPresence=function(n){return new $y(this,n)},Nr.prototype._createRemotePresence=function(n){return new Py(this,n)};var Hy=Fy;function Fy(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var zy=Hy,x2=fo,T2=cs;function cs(n,t,e,o,r){if(x2.EventEmitter.call(this),typeof r!="function")throw new Error("Callback is required for SnapshotRequest");this.requestId=t,this.connection=n,this.id=o,this.collection=e,this.callback=r,this.sent=!1}x2.mixin(cs),cs.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},cs.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},cs.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new zy(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var S2=T2,Uy=rn,Vy=Xo.ACTIONS,qy=zu;function zu(n,t,e,o,r,i){if(S2.call(this,n,t,e,o,i),!Uy.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}zu.prototype=Object.create(S2.prototype),zu.prototype._message=function(){return{a:Vy.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var D2=T2,Wy=rn,Gy=Xo.ACTIONS,Zy=Uu;function Uu(n,t,e,o,r,i){if(D2.call(this,n,t,e,o,i),!Wy.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}Uu.prototype=Object.create(D2.prototype),Uu.prototype._message=function(){return{a:Gy.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var Yy=yy,Qy=xy,Ky=y2,L2=jy,Jy=qy,Xy=Zy,M2=fo,$r=sc,Ct=Xo.ACTIONS,R2=os,cn=rn,as=l2,ds=$r.CODES;function A2(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var tw=K;function K(n){M2.EventEmitter.call(this),this.collections={},this.nextQueryId=1,this.nextSnapshotRequestId=1,this.queries={},this._presences={},this._snapshotRequests={},this.seq=1,this._presenceSeq=1,this.id=null,this.agent=null,this.debug=!1,this.state=A2(n),this.bindToSocket(n)}M2.mixin(K),K.prototype.bindToSocket=function(n){this.socket&&(this.socket.close(),this.socket.onmessage=null,this.socket.onopen=null,this.socket.onerror=null,this.socket.onclose=null),this.socket=n;var t=A2(n);this._setState(t),this.canSend=!1;var e=this;n.onmessage=function(o){try{var r=typeof o.data=="string"?JSON.parse(o.data):o.data}catch{as.warn("Failed to parse message",o);return}e.debug&&as.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){cn.nextTick(function(){e.emit("error",s)})}},n.readyState===1&&e._initializeHandshake(),n.onopen=function(){e._setState("connecting"),e._initializeHandshake()},n.onerror=function(o){e.emit("connection error",o)},n.onclose=function(o){o==="closed"||o==="Closed"?e._setState("closed",o):o==="stopped"||o==="Stopped by server"?e._setState("stopped",o):e._setState("disconnected",o)}},K.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=O2(n.error,n),delete n.error),n.a){case Ct.initLegacy:return this._handleLegacyInit(n);case Ct.handshake:return this._handleHandshake(t,n);case Ct.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case Ct.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case Ct.queryUnsubscribe:return;case Ct.queryUpdate:var e=this.queries[n.id];if(!e)return;if(t)return e._handleError(t);n.diff&&e._handleDiff(n.diff),n.hasOwnProperty("extra")&&e._handleExtra(n.extra);return;case Ct.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case Ct.bulkSubscribe:case Ct.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case Ct.snapshotFetch:case Ct.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case Ct.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case Ct.subscribe:case Ct.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case Ct.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case Ct.presence:return this._handlePresence(t,n);case Ct.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case Ct.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case Ct.presenceRequest:return this._handlePresenceRequest(t,n);case Ct.pingPong:return this._handlePingPong(t);default:as.warn("Ignoring unrecognized message",n)}};function O2(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}K.prototype._handleBulkMessage=function(n,t,e){if(t.data)for(var o in t.data){var r=t.data[o],i=this.getExisting(t.c,o);i&&(n?i[e](n):r.error?i[e](O2(r.error)):i[e](null,r))}else if(Array.isArray(t.b))for(var s=0;s<t.b.length;s++){var o=t.b[s],i=this.getExisting(t.c,o);i&&i[e](n)}else if(t.b)for(var o in t.b){var i=this.getExisting(t.c,o);i&&i[e](n)}else as.error("Invalid bulk message",t)},K.prototype._reset=function(){this.agent=null},K.prototype._setState=function(n,t){if(this.state!==n){if(n==="connecting"&&this.state!=="disconnected"&&this.state!=="stopped"&&this.state!=="closed"||n==="connected"&&this.state!=="connecting"){var e=new $r(ds.ERR_CONNECTION_STATE_TRANSITION_INVALID,"Cannot transition directly from "+this.state+" to "+n);return this.emit("error",e)}this.state=n,this.canSend=n==="connected",(n==="disconnected"||n==="stopped"||n==="closed")&&this._reset(),this.startBulk();for(var o in this.queries){var r=this.queries[o];r._onConnectionStateChanged()}for(var i in this.collections){var s=this.collections[i];for(var o in s)s[o]._onConnectionStateChanged()}for(var l in this._presences)this._presences[l]._onConnectionStateChanged();for(var o in this._snapshotRequests){var c=this._snapshotRequests[o];c._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},K.prototype.startBulk=function(){this.bulk||(this.bulk={})},K.prototype.endBulk=function(){if(this.bulk)for(var n in this.bulk){var t=this.bulk[n];this._sendBulk("f",n,t.f),this._sendBulk("s",n,t.s),this._sendBulk("u",n,t.u)}this.bulk=null},K.prototype._sendBulk=function(n,t,e){if(!!e){var o=[],r={},i=0,s;for(var l in e){var c=e[l];c==null?o.push(l):(r[l]=c,s=l,i++)}if(o.length===1){var l=o[0];this.send({a:n,c:t,d:l})}else o.length&&this.send({a:"b"+n,c:t,b:o});if(i===1){var a=r[s];this.send({a:n,c:t,d:s,v:a})}else i&&this.send({a:"b"+n,c:t,b:r})}},K.prototype._sendActions=function(n,t,e){if(this._addDoc(t),this.bulk){var o=this.bulk[t.collection]||(this.bulk[t.collection]={}),r=o[n]||(o[n]={}),i=r.hasOwnProperty(t.id);return r[t.id]=e,i}else{var s={a:n,c:t.collection,d:t.id,v:e};this.send(s)}},K.prototype.sendFetch=function(n){return this._sendActions(Ct.fetch,n,n.version)},K.prototype.sendSubscribe=function(n){return this._sendActions(Ct.subscribe,n,n.version)},K.prototype.sendUnsubscribe=function(n){return this._sendActions(Ct.unsubscribe,n)},K.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:Ct.op,c:n.collection,d:n.id,v:n.version,src:t.src,seq:t.seq,x:{}};"op"in t&&(e.op=t.op),t.create&&(e.create=t.create),t.del&&(e.del=t.del),n.submitSource&&(e.x.source=t.source),this.send(e)},K.prototype.send=function(n){this.debug&&as.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},K.prototype.ping=function(){if(!this.canSend)throw new $r(ds.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:Ct.pingPong};this.send(n)},K.prototype.close=function(){this.socket.close()},K.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},K.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new Yy(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},K.prototype._destroyDoc=function(n){!n._wantsDestroy||(cn.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},K.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},K.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new Qy(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},K.prototype._destroyQuery=function(n){delete this.queries[n.id]},K.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(Ct.queryFetch,n,t,e,o)},K.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(Ct.querySubscribe,n,t,e,o)},K.prototype.hasPending=function(){return!!(this._firstDoc(hc)||this._firstQuery(hc)||this._firstSnapshotRequest())};function hc(n){return n.hasPending()}K.prototype.hasWritePending=function(){return!!this._firstDoc(ew)};function ew(n){return n.hasWritePending()}K.prototype.whenNothingPending=function(n){var t=this._firstDoc(hc);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(hc);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}cn.nextTick(n)},K.prototype._nothingPendingRetry=function(n){var t=this;return function(){cn.nextTick(function(){t.whenNothingPending(n)})}},K.prototype._firstDoc=function(n){for(var t in this.collections){var e=this.collections[t];for(var o in e){var r=e[o];if(n(r))return r}}},K.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},K.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},K.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new Jy(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},K.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new Xy(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},K.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},K.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},K.prototype._initializeHandshake=function(){this.send({a:Ct.handshake,id:this.id})},K.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},K.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},K.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new $r(ds.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(R2.map[n.type]!==R2.defaultType)return this.emit("error",new $r(ds.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new $r(ds.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},K.prototype.getPresence=function(n){var t=this,e=cn.digOrCreate(this._presences,n,function(){return new Ky(t,n)});return e._wantsDestroy=!1,e},K.prototype.getDocPresence=function(n,t){var e=L2.channel(n,t),o=this,r=cn.digOrCreate(this._presences,e,function(){return new L2(o,n,t)});return r._wantsDestroy=!1,r},K.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},K.prototype._addPresence=function(n){cn.digOrCreate(this._presences,n.channel,function(){return n})},K.prototype._handlePresenceSubscribe=function(n,t){var e=cn.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},K.prototype._handlePresenceUnsubscribe=function(n,t){var e=cn.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},K.prototype._handlePresence=function(n,t){var e=cn.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},K.prototype._handlePresenceRequest=function(n,t){var e=cn.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var _2=tw,nw=os;const fc={err:1001,msg:"user auth error",name:"AuthError"},ow={err:1002,msg:"you don't have required permission",name:"PermissionError"},Vu={err:1003,msg:"Too many user connected",name:"MaxUserError"},us={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},rw={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},iw={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},hs="x-live-editor-token",mc="x-live-editor-base-url",he=w("auth-connection");function sw(n){try{n()}catch(t){he.error(t)}}class lw{constructor(t,e){h(this,"connection");h(this,"ws");h(this,"retryCount");h(this,"events",new Vf.EventEmitter);h(this,"token",null);h(this,"resourceToken",null);this.url=t,this.reauthFunc=e,this.retryCount=0}getBaseURL(){const t=new URL(this.url);return`${t.protocol==="wss:"?"https:":"http:"}//${t.host}${t.pathname}`}getBase64BaseURL(){return _o(this.getBaseURL())}async auth(t){d(he,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[hs]:t.token,[mc]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.token=t.token,await o.json()}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[mc]:_o(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new f7.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(_2.prototype),d(he,this.connection,"no this.connection"),this.ws,this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})};const o=this.connection.handleMessage.bind(this.connection);this.connection.handleMessage=r=>{var s;const i=r;if(this.connection&&(this.connection.lastReceiveTime=Date.now()),"err"in i||i.a==="pong")this.handleMessage(i);else{Object.prototype.hasOwnProperty.call(i,"a")&&i.a!=="init"&&i.a!=="hs"&&(this.retryCount=0);try{o(i)}catch(l){if((l==null?void 0:l.type)==="writeConflict"){this.emitWriteConflictError(l,i);return}if((s=l==null?void 0:l.message)!=null&&s.startsWith("Cannot invert subtype")){this.emitWriteConflictError(l,i);return}throw l}}},_2.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,he.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();await this.auth(t),this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){he.error(t),setTimeout(()=>this.handleAuthError(),0)}}else he.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(fc.msg);t.code=fc.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(us.msg);t.code=us.err,this.events.emit("requestReloadError",t)}emitWriteConflictError(t,e){t.orgMsg=e,this.events.emit("writeConflictError",t)}emitMaxUsersError(){this.events.emit("maxUsersError"),this.end(!1)}handleMessage(t){const e=t;if(e.a==="pong")return;const o=e.err;if(o===fc.err)he.warn("auth error"),this.handleAuthError();else if(o===Vu.err)he.warn(Vu.msg),this.emitMaxUsersError();else if(o===us.err){he.warn(us.msg);try{this.emitRequestReloadError()}catch(r){he.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else he.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError()}get(t,e){return d(he,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(d(he,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){d(he,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){d(he,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.reauthFunc=void 0,this.events.removeAllListeners(),sw(()=>{var o;return(o=this.connection)==null?void 0:o.close()}),this.connection=void 0,(e=this.ws)==null||e.close(),this.ws=void 0,t&&this.logout()}}w("utils/file");function cw(){function n(){return new Promise(t=>{const e=new FileReader;e.onload=()=>{t(e.result)},e.readAsArrayBuffer(this)})}File.prototype.arrayBuffer=File.prototype.arrayBuffer||n,Blob.prototype.arrayBuffer=Blob.prototype.arrayBuffer||n}cw();async function aw(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new m7.Hash;for(let s=0;s<o;s++){const l=s*102400;let c=l+102400;c>e&&(c=e);const u=await n.slice(l,c,n.type).arrayBuffer();r.update(new Uint8Array(u))}const i=r.digest();return _o(i)}const In=w("sharedb-doc/client");class dw{constructor(t,e,o){h(this,"connection");h(this,"auth");h(this,"doc",null);h(this,"reauthFunc");h(this,"clientId",N());h(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});d(In,!this.doc,"This websocket has opened a doc."),await this.connection.init(this.auth);const e=this.connection.get(this.auth.appId,this.auth.docId);return this.doc=e,await t(e),In.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;nw.register(al.type),this.connection=new lw(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return d(In,t.endsWith(e),`invalid api server: ${t}, ${e}`),t.substr(0,t.length-e.length)}close(t){this.connection.end(t),this.doc=null}on(t,e){this.connection.addEventListener(t,o=>{(t==="error"||this.doc)&&e(o)})}onWriteConflictError(t){this.connection.onWriteConflictError(t)}onMaxUsersError(t){this.connection.onMaxUsersError(t)}onRequestReloadError(t){this.connection.onRequestReloadError(t)}async authOnly(){await this.connection.auth(this.auth)}getResourceToken(){return this.connection.resourceToken}hasDocContainer(){return!!this.doc}apiServer(){const t=this.connection.url;if(t.startsWith("ws://"))return`http://${t.substring(5)}`;if(t.startsWith("wss://"))return`https://${t.substring(6)}`;throw new Error(`invalid server url: ${t}`)}async getFileUrlByHash(t,e,o,r,i){try{const s=`${t}/${e}`,l=await this.request(s,{method:"post",headers:{...i},data:{name:o,size:r}});return l.data&&Array.isArray(l.data)&&l.data.length===1?l.data[0]:""}catch{return""}}async getFileUrlsByHashes(t){const o=`${this.apiServer()}/resources`;let r=[];t.forEach(l=>{const c=l.split("|");r.push(...c)}),r=Array.from(new Set(r));const i=r.map(l=>this.getFileUrlByHash(o,l,"",0,{[hs]:this.connection.token}));return await Promise.all(i)}async uploadFile(t,e,o,r,i){let s=e.size;if(s===0)throw new Error("file is empty");s+=500;const l=C=>{In.info(`on progress: ${C.loaded}`);let v=C.loaded*100/s;v>100&&(v=100),r(v)},c=await aw(e),a=await this.getFileUrlByHash(t,c,e.name,e.size,o);if(a)return r(-1),a;let u=t;i!=null&&i.thumbnail&&(u+="/thumbnail");const f=new FormData;f.append("file-size",`${e.size}`),f.append("file-hash",c),f.append("file",e,e.name);const m=await this.request(u,{method:"post",data:f,withCredentials:!0,headers:{...o},onUploadProgress:l});return In.info(m),r(100),Array.isArray(m.data)?m.data[0]:m.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;d(In,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[hs]:this.connection.token},e,o);return d(In,s,"no result"),s}async request(t,e){var i,s;let o=this.connection.token,r;for(let l=0;l<2;l++){const c=e||{};c.url=t,c.headers||(c.headers={}),d(In,o,"no token"),c.headers={...c.headers,[hs]:o,[mc]:this.connection.getBase64BaseURL()};try{return await u7.default(t,c)}catch(a){if(r=a,((i=a==null?void 0:a.response)==null?void 0:i.status)===403&&this.reauthFunc){const u=await this.reauthFunc();if(await this.connection.auth(u),!u.token)throw a;o=u.token;continue}throw(s=a.response)!=null&&s.data&&(a.responseData=a.response.data),a}}throw d(In,r,"no error"),r}async getVersions(){const e=`${this.apiServer()}/versions`,o=await this.request(e),r=o.data.versions,i=o.data.latest;return i&&r.findIndex(s=>s.version===i)===-1&&r.unshift({version:-1,tag:"",published:!1}),r}async getVersion(t){const o=`${this.apiServer()}/versions/${t}`,r=await this.request(o);return JSON.parse(r.data.data)}async getLatestVersion(){const e=`${this.apiServer()}/versions/latest`,o=await this.request(e);return JSON.parse(o.data.data)}async getVersionOps(t,e){let r=`${this.apiServer()}/versions/before/${t}?withOp=true`;e!==void 0&&e!==0&&(r+=`&from=${e}`);const i=await this.request(r),s=i.data.ops,l=h7.default(s,u=>!!u.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let a;return c?(d(In,c.create,"no createDoc.create"),a=c.create.data):a=JSON.parse(i.data.data),a.blocks||(a.blocks=[]),{doc:a,ops:i.data.ops}}async revertVersion(t){const o=`${this.apiServer()}/versions/revert/${t}`;await this.request(o,{method:"post",data:{}})}async createVersion(t,e){const r=`${this.apiServer()}/versions`;return(await this.request(r,{method:"post",data:{publish:e,tag:t}})).data}async recognizeLink(t){const o=`${this.apiServer()}/resources/external/${_o(t)}`;return(await this.request(o)).data}buildResourceUrl(t,e){if(!t)return"";if(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("file:")||t.startsWith("data:")||t.startsWith("blob:"))return t;let r=`${this.apiServer()}/resources/${encodeURIComponent(t)}`;const i=[];if(e!=null&&e.withToken&&i.push(`token=${this.getResourceToken()}`),e!=null&&e.downloadFileName&&i.push(`&fileName=${encodeURIComponent(e.downloadFileName)}`),i.length>0){const s=i.join("&");r+=`?${s}`}return r}}function uw(){return{blocks:[{id:N(),type:"text",text:[]}],comments:{},meta:{}}}const qu=w("block-ids");class hw{constructor(){h(this,"ids",new Map)}onInsertBlock(t){const e=Array.from(this.ids.keys()).sort((r,i)=>i-r);for(let r=0;r<e.length;r++){const i=e[r];if(i>=t){const s=this.ids.get(i);d(qu,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=N();this.ids.set(t,o)}onDeleteBlock(t){this.ids.delete(t);const e=Array.from(this.ids.keys()).sort((o,r)=>o-r);for(let o=0;o<e.length;o++){const r=e[o];if(r>t){const i=this.ids.get(r);d(qu,i!==void 0,"old id is not exists"),this.ids.delete(r),this.ids.set(r-1,i)}}}getId(t){let e=this.ids.get(t);return e||(e=N(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class fw{constructor(){h(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new hw,this.ids.set(t,e)),e}onInsertBlock(t,e){this.getContainerIds(t).onInsertBlock(e)}onDeleteBlock(t,e){this.getContainerIds(t).onDeleteBlock(e)}getBlockId(t,e){return this.getContainerIds(t).getId(e)}getBlockIndexById(t){const e=Array.from(this.ids.entries());for(let o=0;o<e.length;o++){const r=e[o],i=r[1].getById(t);if(i)return{containerId:r[0],blockIndex:i[0]}}return d(qu,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class N2{constructor(t=new Set,e=new Map){this.deletedKeys=t,this.insertedValues=e}insert(t,e){this.insertedValues.set(t,e)}delete(t){this.deletedKeys.add(t)}toDocBlockDelta(){const t={};return this.insertedValues.forEach((e,o)=>{t[o]=e}),{insert:t,delete:Array.from(this.deletedKeys)}}}const $t=w("op-parser");function Pr(n){return n==="blocks"?"root":n}class mw{constructor(t,e){h(this,"updatingBlockDataDeltaMap",new Map);h(this,"blockIds",new fw);this.handler=t,this.local=e}onDeleteBlock(t,e){const o=this.blockIds.getBlockId(t,e);this.blockIds.onDeleteBlock(t,e);const r=this.updatingBlockDataDeltaMap.get(o);r&&($t.debug(`ignore update object data before delete block: ${JSON.stringify(r)}`),this.updatingBlockDataDeltaMap.delete(o)),this.handler.onDeleteBlock(Pr(t),e,this.local)}onInsertBlock(t,e,o){this.blockIds.onInsertBlock(t,e),this.handler.onInsertBlock(Pr(t),e,o,this.local)}onUpdateBlockText(t,e,o){this.handler.onUpdateBlockText(Pr(t),e,o,this.local)}onDeleteBlockData(t,e,o){const r=this.blockIds.getBlockId(t,e);let i=this.updatingBlockDataDeltaMap.get(r);i||(i=new N2,this.updatingBlockDataDeltaMap.set(r,i)),i.delete(o)}onInsertBlockData(t,e,o,r){const i=this.blockIds.getBlockId(t,e);let s=this.updatingBlockDataDeltaMap.get(i);s||(s=new N2,this.updatingBlockDataDeltaMap.set(i,s)),s.insert(o,r)}executeUpdateBlockDataActions(){Array.from(this.updatingBlockDataDeltaMap.entries()).forEach(([t,e])=>{const{containerId:o,blockIndex:r}=this.blockIds.getBlockIndexById(t);this.handler.onUpdateBlockData(Pr(o),r,e.toDocBlockDelta(),this.local)})}}class $2{}class Wu{constructor(t){h(this,"key");this.key=t}}function gw(n,t,e){const o=t.concat(),r=o[0];if(typeof r!="number"||(o.shift(),o.length===1))return!1;const i=o[0];if(typeof i!="object"||!i.i||Object.keys(i).length!==1)return!1;for(let l=1;l<o.length;l++){const c=o[l];if(!Array.isArray(c)||c.length!==2||typeof c[0]!="string")return!1;const u=c[1];if(typeof u!="object"||u.i===void 0||Object.keys(u).length!==1)return!1}const s=i.i;d($t,s.id,"block id is required"),d($t,s.type,"block type is required");for(let l=1;l<o.length;l++){const c=o[l],a=c[0],u=c[1];s[a]=u.i}return e.onInsertBlock(n,r,s),!0}function Gu(n,t,e,o){if(e==="upsert"&&gw(n,t,o))return;d($t,Array.isArray(t),`invalid block op: ${n}, ${JSON.stringify(t)}`);const r=t.concat(),i=r[0];r.shift();const s=[];for(;r.length>0;){const l=r[0];if(l==="text"){const c=r[1];if(d($t,typeof c=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),d($t,c.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),r.splice(0,2),e==="upsert"){const u=c.e;o.onUpdateBlockText(n,i,u)}d($t,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){d($t,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const c=l[0];d($t,typeof c=="string",`invalid block op: key ${JSON.stringify(c)}`);const a=l[1];if(c==="text"){if(d($t,typeof a=="object",`invalid opData type, ${JSON.stringify(a)}`),a.i&&e==="upsert"&&o.onInsertBlockData(n,i,c,a.i),a.r&&e==="remove"&&o.onDeleteBlockData(n,i,c),a.et==="rich-text"&&e==="upsert"){const f=a.e;o.onUpdateBlockText(n,i,f)}}else e==="remove"&&a.r&&s.push(new Wu(c)),e==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i);r.shift()}else if(typeof l=="object"){const c=l;e==="remove"&&c.r&&s.push(new $2),e==="upsert"&&c.i&&o.onInsertBlock(n,i,c.i),r.shift()}else{d($t,typeof l=="string","data is not string"),d($t,l!=="text","data !== 'text'"),d($t,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const c=l,a=r[1];e==="remove"&&a.r&&s.push(new Wu(c)),e==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof $2?o.onDeleteBlock(n,i):l instanceof Wu?o.onDeleteBlockData(n,i,l.key):d($t,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function pw(n,t,e,o){$t.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function Cw(n,t,e,o){const r=n[1],i=n[2];d($t,r,`invalid comment op, no commentId: ${JSON.stringify(n)}`),d($t,i,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof i=="string"?$t.error(`unknown comment op, ${JSON.stringify(n)}`):i.i&&i.r?t==="upsert"&&o.onUpdateComment(r,e.local):i.i?t==="upsert"&&o.onCreateComment(r,e.local):i.r?t==="remove"&&o.onDeleteComment(r,e.local):$t.error(`unknown comment op, ${JSON.stringify(n)}`)}function Zu(n,t,e,o){const r=n[0];if(Array.isArray(r)){r.forEach(l=>{Zu(l,t,e,o)});return}const i=r;if(d($t,typeof i=="string",`invalid container id: ${JSON.stringify(n)}`),i==="meta"){pw(n);return}if(i==="comments"){Cw(n,t,e,o);return}const s=i;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(l=>{Gu(s,l,t,e)}):n.slice(1).forEach(l=>{Gu(s,l,t,e)});else if(typeof n[1]=="object"){const l=n[1];l.r&&t==="remove"&&o.onDeleteContainer(Pr(s),e.local),l.i&&t==="upsert"&&o.onCreateContainer(Pr(s),l.i,e.local)}else d($t,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Gu(s,n.slice(1),t,e)}function P2(n,t,e){const o=new mw(t,e);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=Y.default(n),l=s[0];Array.isArray(l)?s.forEach(c=>{Zu(c,i,o,t)}):Zu(s,i,o,t)}o.executeUpdateBlockDataActions()}const bw=w("sharedb-comments");function Yu(n){if(n.doc)return Y.default(n.doc);const t=n.blocks;d(bw,t,"no comment blocks");const e={blocks:{root:t},meta:{},comments:{}};return Object.entries(n).forEach(([o,r])=>{Array.isArray(r)&&(e.blocks[o]=r)}),Y.default(e)}function j2(n){const{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:c}=n;return{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:c}}function Qu(n,t){const e={...n,doc:t};return delete e.blocks,Y.default(e)}const kt=w("sharedb-doc/doc-container"),H2="ot-json1";al.type.registerSubtype(oy.type),al.type.name=H2,al.type.invert=null;class fs extends xi{constructor(e,o,r=!0){super();h(this,"doc");h(this,"client");h(this,"localPresence");h(this,"remoteCaretHandler",new ey);h(this,"batching",0);h(this,"status","clean");h(this,"disableLogout");h(this,"destroyed",!1);h(this,"handleNothingPending",()=>{this.setStatus("clean")});h(this,"handleCreate",()=>{this.handleReload("doc created")});h(this,"handleDel",()=>{});h(this,"handleReload",e=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})});h(this,"handleReset",async e=>{const o=new Error(`reset doc: ${e}`);o.code="ResetDoc",this.callbacks.forEach(r=>{var i;return(i=r.onError)==null?void 0:i.call(r,o)}),this.destroy()});h(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});h(this,"insertObject",async(e,o,r)=>{const i=[e,o,{i:r}];return this.submitOp(i)});h(this,"deleteObject",async(e,o)=>{const r=[e,o,{r:!0}];return this.submitOp(r)});h(this,"replaceObject",async(e,o,r)=>{const i=[e,o,{r:!0,i:r}];return this.submitOp(i)});h(this,"updateObject",async(e,o,r)=>{const i=this.data()[e][o],s=[e,o];return Object.entries(r).forEach(([l,c])=>{if(!cl.default(i[l],c))if(i[l]===void 0){if(c!=null){const a={i:c};s.push([l,a])}}else if(c==null){const a={r:!0};s.push([l,a])}else{const a={r:!0,i:c};s.push([l,a])}}),Object.entries(i).forEach(([l,c])=>{if((r[l]===void 0||r[l]===null)&&c!==void 0){const a={r:!0};s.push([l,a])}}),s.length<=2?Promise.resolve():this.submitOp(s)});h(this,"broadcastMessage",async e=>{const o={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});h(this,"data",()=>this.doc.data);h(this,"submitOp",async e=>new Promise((o,r)=>{if(this.destroyed){kt.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(kt.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),kt.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(kt.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));h(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,H2,i=>{i?r(i):o()})}));h(this,"submitInsertChildContainer",async(e,o)=>{const r=[ho(e),{i:o}];return this.submitOp(r)});h(this,"submitDeleteChildContainer",async e=>{const o=[ho(e),{r:!0}];return this.submitOp(o)});h(this,"submitInsertBlock",async(e,o,r)=>{const i=[ho(e),o,{i:r}];return this.submitOp(i)});h(this,"submitDeleteBlock",async(e,o)=>{const r=[ho(e),o,{r:!0}];return this.submitOp(r)});h(this,"submitUpdateBlockData",async(e,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[ho(e),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c)){const u={r:!0,i:a};i.push([c,u])}});const l=new Set(Object.keys(r.insert));return r.delete.forEach(c=>{if(l.has(c))return;const a={r:!0};i.push([c,a])}),Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c))return;const u={i:a};i.push([c,u])}),this.submitOp(i)});h(this,"submitUpdateRichText",async(e,o,r)=>{const i=[ho(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});h(this,"handleOp",(e,o,r)=>{if(this.destroyed){kt.warn("handleOp: destroyed");return}P2(e,this,!!o)});this.client=e,this.doc=o,this.doc.preventCompose=!0,this.disableLogout=r,this.registerCallback(this.remoteCaretHandler)}beginBatchUpdate(){return this.doc.preventCompose=!1,this.batching++,this.batching}endBatchUpdate(){return this.batching--,d(kt,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new dw(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new fs(o,r,e.disableLogout);if(r.type===null){if(e.autoCreateDoc===!1){const s=new Error("doc not exists");throw s.code="DocNotExists",s}await i.createDoc(e.templateData||uw())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw kt.error(o),kt.error(`failed to load doc: ${JSON.stringify(o)}`),o}}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(o=>{var r;return(r=o.onStatusChanged)==null?void 0:r.call(o,e)}))}initEvents(){this.doc.on("nothing pending",this.handleNothingPending),this.doc.on("create",this.handleCreate),this.doc.on("del",this.handleDel),this.client.onWriteConflictError(this.handleWriteConflictError)}clearEvents(){this.doc.off("nothing pending",this.handleNothingPending),this.doc.off("create",this.handleCreate),this.doc.off("del",this.handleDel)}initPresence(){return new Promise((e,o)=>{if(this.localPresence)e();else{const r=this.doc.connection.getPresence(`${this.doc.collection}:${this.doc.id}`);r.on("receive",(i,s)=>{this.onCustomMessage(s)}),r.subscribe(i=>{i?o(i):(this.localPresence=r.create(N()),e())})}})}subscribe(){return new Promise((e,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return es(this.data())}getContainerBlocks(e){const o=this.data();d(kt,o,"no doc data");const r=o[ho(e)];return d(kt,r,`no container data: ${e}`),Y.default(r)}getBlockData(e,o){const r=this.data();d(kt,r,"no doc data");const i=r[ho(e)];d(kt,i,`no container data: ${e}`);const s=i[o];return d(kt,s,`no block data: ${o}`),Y.default(s)}localInsertBlock(e,o,r){return this.submitInsertBlock(e,o,r),this.getBlockData(e,o)}localDeleteBlock(e,o){const r=this.getBlockData(e,o);return this.submitDeleteBlock(e,o),r}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);d(kt,i.text,"no block text");const s=Y.default(i.text);this.submitUpdateRichText(e,o,r);const l=ie.apply(s,r);return d(kt,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=Y.default(this.getBlockData(e,o));return this.submitUpdateBlockData(e,o,r),i}localInsertChildContainer(e,o){this.submitInsertChildContainer(e,o)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>j2(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return Yu(o)}localCreateComment(e,o){const r=Qu(e,o),s=["comments",r.id,{i:r}];return this.submitOp(s)}localDeleteComment(e){const o=["comments",e,{r:!0}];return this.submitOp(o)}localUpdateComment(e,o){const r=Qu(e,o),i=["comments",e.id,{r:!0,i:r}];return this.submitOp(i)}destroy(){var e;this.destroyed=!0,this.clearEvents(),this.clearCallbacks(),this.doc.destroy(),(e=this.localPresence)==null||e.destroy(),this.client.close(!this.disableLogout),this.remoteCaretHandler.destroy()}onDeleteBlock(e,o,r){d(kt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,_r(e),o,r)})}onInsertBlock(e,o,r,i){d(kt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,_r(e),o,r,i)})}onUpdateBlockData(e,o,r,i){d(kt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,_r(e),o,r,i)})}onUpdateBlockText(e,o,r,i){d(kt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,_r(e),o,r,i)})}onDeleteContainer(e,o){d(kt,this.callbacks.length>0,"no callbacks"),d(kt,e!=="root","should not delete root container in doc"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteChildContainer)==null?void 0:i.call(r,_r(e),o)})}onCreateContainer(e,o,r){d(kt,this.callbacks.length>0,"no callbacks"),d(kt,e!=="root","should not create root container in doc"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,_r(e),o,r)})}onDeleteComment(e,o){d(kt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onDeleteComment)==null?void 0:i.call(r,e,o)})}onCreateComment(e,o){d(kt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onCreateComment)==null?void 0:i.call(r,e,o)})}onUpdateComment(e,o){d(kt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(r=>{var i;return(i=r.onUpdateComment)==null?void 0:i.call(r,e,o)})}onCustomMessage(e){const o=e;(o==null?void 0:o.type)==="custom"&&(o==null?void 0:o.clientId)!==this.client.clientId?this.callbacks.forEach(r=>{var i;return(i=r.onCustomMessage)==null?void 0:i.call(r,o.data)}):(o==null?void 0:o.type)==="onlineUsers"&&setTimeout(()=>{const r={type:"custom",data:e,clientId:"-"};this.onCustomMessage(r)})}async addResources(e){return await this.client.getFileUrlsByHashes(e)}async uploadResource(e,o){var i;return{resourceId:await this.client.uploadResource(e,(i=o==null?void 0:o.onProgress)!=null?i:()=>{})}}buildResourceUrl(e,o){return this.client.buildResourceUrl(e,o)}request(e,o){return this.client.request(e,o)}getUser(){const e=this.client.clientId,{permission:o,userId:r,displayName:i,avatarUrl:s}=this.client.auth;return{permission:o,clientId:e,userId:r,displayName:i,avatarUrl:s,rainbowIndex:0}}getRemoteUsers(){return this.remoteCaretHandler.remoteUsers}getVersionHelper(){return this}getVersions(){return this.client.getVersions()}async getVersion(e){const o=await this.client.getVersion(e);return es(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return es(e)}async getHistoryData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o),s=i.map(l=>({user:l.meta.createdBy,data:l}));return{doc:es(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:es(r),versionData:i}}revertVersion(e){return this.client.revertVersion(e)}createVersion(e,o){return this.client.createVersion(e,o)}async recognizeLink(e){return this.client.recognizeLink(e)}parseHistoryData(e,o){P2(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}w("remote-cursor");class F2{constructor(t){h(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});h(this,"broadcastCaretPos",Xt.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));h(this,"handleRemoteCaretsChanged",t=>{t.forEach(e=>{const o=this.editor.findBlockById(e);o&&this.editor.reloadBlock(o)})});this.editor=t,this.editor.addListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().addListener("remote-carets-change",this.handleRemoteCaretsChanged)}destroy(){this.editor.removeListener("selectionChanged",this.handleDocSelectionChange),this.editor.doc.getRemoteUsers().removeListener("remote-carets-change",this.handleRemoteCaretsChanged)}}const z2=w("remote-cursor-decorator");class Ku{decorateText(t,e,o){const r=t.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=e[e.length-1];d(z2,typeof s=="string","invalid path containerId"),d(z2,typeof l=="number","invalid path blockIndex");const c=t.doc.getBlockData(s,l),a=de(o);return r.getSimpleCursors(c.id).forEach((f,m)=>{m>a&&(m=a);const C=f.map(B=>({id:N(),type:"remote-cursor",name:B.user.displayName,time:B.time,rainbowIndex:B.user.rainbowIndex})),v=i.get(m);v?v.push(...C):i.set(m,C)}),{insertions:i}}}class U2 extends Yt.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(pt(Br(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=F(this.editor.getContainerById(t));i&&this.emit("change",this.editor,i,r,o)}onUpdateBlockData(t,e){this.handleChild(t,e,"data-change")}onUpdateBlockText(t,e){this.handleChild(t,e,"text-change")}destroy(){this.editor.doc.unregisterCallback(this)}}function vw(n,t){n.addCustom("child-block-tracker",()=>new U2(n)).addListener("change",t)}function kw(n,t){n.addCustom("child-block-tracker",()=>new U2(n)).removeListener("change",t)}const nz="",yw={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4",name:"\u6587\u672C\u989C\u8272"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},ww={colorPalette:{colorDesc:"Text Color",name:"Text Color",backgroundDesc:"Background Color",reset:"Reset"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}};T.mergeLang({"zh-CN":yw,"en-US":ww});const oz="";w("button");function go(n,t,e,o,r){const i=b("button",["editor-button"],null);return i.setAttribute("data-button-id",n),r&&i.setAttribute(`data-editor-tooltip-${r}`,t),e?typeof e=="string"?e.startsWith("<")?i.innerHTML=e:i.innerText=e:i.appendChild(e):i.innerText=t,o&&(o.indexOf("checked")!==-1&&A(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0)),i}function V2(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}const rz="",jr=w("ui-command-bar-base"),Bw={itemElementTag:"div",tippyArrow:!1},Bf=class extends Yt.TypedEmitter{constructor(e,o,r){var i,s;super();h(this,"content");h(this,"items");h(this,"subBar",null);h(this,"parentItem",null);h(this,"closeable",null);h(this,"options");h(this,"id");h(this,"handleDocumentKeydown",e=>{if(!!this.isVisible&&!e.isComposing){if(this.subBar){this.subBar.handleDocumentKeydown(e);return}if(this.items.length!==0){if(e.key==="Escape"){this.close();return}if(e.key==="ArrowUp"){const o=this.getPrevItemIndex(this.getSelectedItemIndex());this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowRight"){const o=this.getSelectedItem();o&&o.children&&this.showSubCommandBar(o.childrenMenuId)}else if(e.key==="ArrowLeft")this.parentItem&&this.close();else if(e.key==="Enter"){const o=this.getSelectedItemIndex();if(o===-1)return;const r=this.items[o],i=this.getItemElementById(r.id);i&&this.emit("click",this,r,i)}}}});h(this,"handleDocumentMouseDown",e=>{e.target instanceof Element&&(this.isInCommandBar(e.target)||this.close())});h(this,"handleHidden",()=>{this.close(),this.emit("close",this),xm(this.id)});h(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&A(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&Im(this.id)});h(this,"handleItemMouseEnter",e=>{const o=this.getParentCommandItemElement(e.target);if(!o)return;const r=this.getItemElementId(o),i=this.getItemById(r);if(this.selectItem(r),i.manualShowChildren)return;const s=i.childrenMenuId||"";this.showSubCommandBar(s)});h(this,"handleItemMouseLeave",e=>{var r,i;const o=this.getParentCommandItemElement(e.target);!o||((i=(r=this.subBar)==null?void 0:r.parentItem)==null?void 0:i.id)!==this.getItemElementId(o)&&(z(o,"selected"),this.emit("selectionChange",this,""))});h(this,"handleItemClick",e=>{const o=this.getParentCommandItemElement(e.target);if(!o)return;const r=this.getItemElementId(o),i=this.items.find(s=>s.id===r);if(!!i&&!(i.states&&i.states.indexOf("disabled")!==-1)){if(i.children&&i.children.length>0&&i.manualShowChildren){this.showSubCommandBar(i.childrenMenuId);return}i.element||(this.emit("click",this,i,o),this.options.autoClose&&this.close())}});h(this,"handleWheel",e=>{if(!this.options.disablePageScroll&&!document.querySelector(".editor-disable-scroll"))return;const o=e.target;if(!o||!(o instanceof Node))return;const r=o instanceof HTMLElement?o:o.parentElement;if(!r)return;const i=We(r);if(!It(this.content,i)){e.stopPropagation(),e.preventDefault();return}e.deltaY<0?i.scrollTop===0&&(e.stopPropagation(),e.preventDefault()):e.deltaY>0&&i.scrollTop+i.clientHeight>=i.scrollHeight&&(e.stopPropagation(),e.preventDefault())});this.id=(i=r==null?void 0:r.id)!=null?i:N(),this.options={...Bw,...r},this.items=e,this.parentItem=(s=r==null?void 0:r.parentItem)!=null?s:null,this.closeable=o!=null?o:null,this.content=this.createCommandBarContent(e)}close(){this.subBar&&this.subBar.close(),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}click(e,o){this.emit("click",this,e,o)}createPopperOptions(){var r;const e={modifiers:[]},o=this.options.overflowBoundary;return o&&((r=e==null?void 0:e.modifiers)==null||r.push({name:"flip",options:{boundary:o,fallbackPlacements:["top","bottom"]}})),e}destroy(){var e;this.close(),this.removeAllListeners(),(e=this.subBar)==null||e.destroy(),this.subBar=null,this.closeable=null,this.content.removeEventListener("wheel",this.handleWheel)}get isSubCommandBar(){return!!this.parentItem}updateItems(e){var r;this.subBar&&e.findIndex(s=>{var l,c;return s.id===((c=(l=this.subBar)==null?void 0:l.parentItem)==null?void 0:c.id)})===-1&&((r=this.subBar)==null||r.destroy(),this.subBar=null),this.items=e;const o=this.createCommandBarContent(e);this.content.innerHTML="",Array.from(o.children).forEach(i=>{this.content.appendChild(i)})}get popper(){return this.content.closest("[data-tippy-root]")}getSelectedItemIndex(){const e=this.getSelectedItem();return e?this.items.indexOf(e):-1}getPrevItemIndex(e){if(e<=0)return this.items.length-1;let o=e-1;for(;;){const r=this.items[o].type;if(r!=="separator"&&r!=="section")return o;if(o-=1,o<=0)return this.items.length-1}}getNextItemIndex(e){let o=e+1;for(;;){if(!this.items[o])return this.getNextItemIndex(-1);const r=this.items[o].type;if(r!=="separator"&&r!=="section")return o;if(o+=1,o>this.items.length-1)return 0}}clearSelectedItem(){const e=this.getSelectedItem();if(!e)return;const o=this.getItemElementById(e.id);o&&z(o,"selected")}selectItem(e){const o=this.getSelectedItem();if(o){if(o.id===e)return;const i=o.id,s=this.getItemElementById(i);s&&z(s,"selected")}const r=this.getItemElementById(e);r?(A(r,"selected"),this.emit("selectionChange",this,r.getAttribute("data-id")||""),r.scrollIntoView({block:"nearest"})):this.emit("selectionChange",this,"")}showSubCommandBar(e){var s,l;const o=this.getSelectedItem();if(!o)return;if(this.subBar){if(((s=this.subBar.parentItem)==null?void 0:s.id)===o.id){o.manualShowChildren&&this.subBar.close();return}this.subBar.destroy(),this.subBar=null}if(!o.children)return;const r=this.getItemElementById(o.id);if(!r)return;const i=Bf.createSubCommandBar(o,(l=this.closeable)!=null?l:this,e?{id:e}:{});this.subBar=i,this.subBar.on("click",(c,a,u)=>{this.emit("click",c,a,u)}),this.subBar.on("close",()=>{var c;(c=this.subBar)==null||c.destroy(),this.subBar=null,z(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),A(r,"active")}isInCommandBar(e){if(!e||!(e instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&It(o,e)||It(this.content,e)?!0:this.subBar?this.subBar.isInCommandBar(e):!1}createCommandItem(e){var i,s,l,c;let o=(i=this.options.itemElementTag)!=null?i:"div";e.element&&(o="div");const r=b(o,["command-item"],null);return r.setAttribute("data-id",e.id),e.type==="separator"?r.classList.add("separator"):e.type==="section"?(r.classList.add("section","text"),e.element&&(typeof e.element=="function"?r.appendChild(e.element(e)):r.appendChild(e.element))):((s=e.states)!=null&&s.includes("selected")&&r.classList.add("selected"),(l=e.states)!=null&&l.includes("checked")&&r.classList.add("checked"),(c=e.states)!=null&&c.includes("disabled")&&r.classList.add("disabled"),r.onclick=this.handleItemClick,r.onmouseenter=this.handleItemMouseEnter,r.onmouseleave=this.handleItemMouseLeave,e.element?typeof e.element=="function"?r.appendChild(e.element(e)):r.appendChild(e.element):r.classList.add("standard")),this.initItemElement(e,r),r}getItemById(e){const o=this.items.find(r=>r.id===e);return d(jr,o,`can not find command item for id: ${e}`),o}getSelectedItem(){const e=this.content.querySelector(":scope >.editor-command-bar >.command-item.selected");if(e){const o=this.getItemElementId(e),r=this.items.find(i=>i.id===o);return d(jr,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(e){const o=e.getAttribute("data-id");return d(jr,o,"no data-id attribute"),o}getItemElementById(e){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${e}"]`);return d(jr,o,`no exists command item, id=${e}`),o}getParentCommandItemElement(e){if(!e||!(e instanceof Element))return null;if(nt(e,"command-item"))return e;const o=e.closest(".command-item");return o||null}createCommandBarContent(e){this.content&&this.content.removeEventListener("wheel",this.handleWheel);const o=b("div",["editor-command-bar-root"],null),r=b("div",["editor-command-bar"],o);return e.forEach(i=>{var l;const s=this.createCommandItem(i);r.appendChild(s),i.element&&i.setCloseable&&i.setCloseable((l=this.closeable)!=null?l:this)}),this.initCommandBarElement(r),o.addEventListener("wheel",this.handleWheel,{passive:!1}),o}getSubBarOptions(e){var o;return{placement:(o=e.childrenPlacement)!=null?o:"right-start"}}static registerManualCommandBar(e,o){this.commandBarCreators.set(e,o)}static createSubCommandBar(e,o,r){var l;d(jr,e.children&&e.children.length>0,"no item children");const i=(l=e.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return d(jr,s,`no creator for command type: ${i}`),s(e,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let Hr=Bf;h(Hr,"commandBarCreators",new Map),w("ui-command-bar");class gc extends Hr{constructor(){super(...arguments);h(this,"tippyInstance",null)}manualShow(e,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=g7.default(e,{interactive:!0,content:this.content,trigger:"manual",triggerTarget:null,hideOnClick:!1,placement:(r=o==null?void 0:o.placement)!=null?r:"bottom-start",maxWidth:650,arrow:this.options.tippyArrow,appendTo:document.body,onShow:this.handleShow,onHidden:this.handleHidden,theme:o==null?void 0:o.theme,getReferenceClientRect:o==null?void 0:o.getReferenceClientRect,offset:(i=o==null?void 0:o.offset)!=null?i:[0,0],popperOptions:this.createPopperOptions()}),o!=null&&o.point){const{x:s,y:l}=o.point;this.tippyInstance.setProps({getReferenceClientRect:()=>new DOMRect(s,l,0,0)})}this.clearSelectedItem(),this.tippyInstance.show(),this.parentItem||(document.addEventListener("keydown",this.handleDocumentKeydown),document.addEventListener("mousedown",this.handleDocumentMouseDown)),this.popper&&this.options.id&&this.popper.setAttribute("data-command-bar-id",this.options.id)}}close(){var e;super.close(),this.isVisible&&((e=this.tippyInstance)==null||e.hide())}destroy(){var e;(e=this.tippyInstance)==null||e.destroy(),this.tippyInstance=null,super.destroy()}getCommandBarRoot(){return this.content.closest("[data-tippy-root]")}get isVisible(){var e,o;return(o=(e=this.tippyInstance)==null?void 0:e.state.isVisible)!=null?o:!1}get popper(){return this.content.closest("[data-tippy-root]")}}const q2=w("ui-base");class ms extends gc{constructor(t,e){var i;const r=[{id:(i=e==null?void 0:e.id)!=null?i:`popup-${N()}`,name:"",element:t}];super(r,void 0,{disablePageScroll:!0})}initCommandBarElement(t){A(t,"popper")}initItemElement(t,e){}get popupContent(){const t=this.items[0];d(q2,t,"no dialog item");const e=typeof t.element=="function"?t.element(t):t.element;return d(q2,e,"no item element"),e}}const po=w("filterable-list");function Ew(n){var e;const t=b("div",["list-item"],null);return t.setAttribute("data-id",n.id),t.appendChild(b("div",["list-item-text"],null,n.name)),(e=n.states)!=null&&e.includes("selected")&&A(t,"selected"),t}function W2(n){const t=b("div",["list-root"],null);return n.forEach(e=>{t.appendChild(Ew(e))}),t}function G2(n,t){let e=n;return t&&(e=n.map(o=>({...o,states:o.id===t?["selected"]:void 0}))),e}function Iw(n,t){const e=b("div",["filterable-list"],null),o=b("div",["filter"],e),r=b("div",["filter-container"],o),i=b("input",["filter-input"],r);t&&t.placeholder&&(i.placeholder=t.placeholder);const s=b("div",["list"],e),l=W2(G2(n,t==null?void 0:t.initialSelectedId));return s.appendChild(l),e}function Z2(n,t,e){const o=n.querySelector(".list");d(po,o,"no list root");const r=W2(G2(t,e)),i=o.querySelector(".list-root");if(d(po,i,"no exists menu"),Mi(i,r),e){const s=o.querySelector(".list-item.selected");s&&(d(po,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class xw{constructor(t,e){h(this,"root");h(this,"visibleItems");h(this,"selectedId");h(this,"filter","");h(this,"onSelected",null);h(this,"handleKeydown",t=>{this.processKeyDown(t)});h(this,"handleInputChanged",()=>{const t=this.root.querySelector(".filter-input");d(po,t,"no input");const e=t.value.toLocaleLowerCase();this.setFilter(e)});h(this,"handleClick",t=>{this.processClick(t)});var o;this.items=t,this.options=e,this.root=Iw(t,e),this.bindEvents(),this.selectedId=(o=e==null?void 0:e.initialSelectedId)!=null?o:"",this.visibleItems=t}bindEvents(){const t=this.root.querySelector(".filter-input");d(po,t,"no input"),t.addEventListener("keyup",this.handleInputChanged),t.addEventListener("keydown",this.handleKeydown),this.root.addEventListener("click",this.handleClick)}unbindEvents(){const t=this.root.querySelector(".filter-input");d(po,t,"no input"),t.removeEventListener("keyup",this.handleInputChanged),t.removeEventListener("keydown",this.handleKeydown),this.root.removeEventListener("click",this.handleClick)}destroy(){this.unbindEvents(),this.onSelected=null}getSelectedIndex(){return this.selectedId?this.visibleItems.findIndex(t=>t.id===this.selectedId):-1}setSelectedId(t){this.selectedId=t,Z2(this.root,this.visibleItems,t)}focus(){const t=this.root.querySelector(".filter-input");d(po,t,"no input"),t.focus()}reset(){this.setFilter("");const t=this.root.querySelector(".filter-input");d(po,t,"no input"),t.value=""}setFilter(t){this.filter!==t&&(this.filter=t,this.visibleItems=this.items.filter(e=>e.name.toLocaleLowerCase().includes(t)),Z2(this.root,this.visibleItems,this.selectedId))}processClick(t){var s,l;const e=t.target;if(!(e instanceof HTMLElement))return;const o=e.closest(".list-item");if(!o)return;const r=(s=o.getAttribute("data-id"))!=null?s:"",i=(l=this.visibleItems.find(c=>c.id===r))!=null?l:null;this.onSelected&&this.onSelected(this,i)}processKeyDown(t){var e;if(t.key==="ArrowUp"){let o=this.getSelectedIndex();o===-1?o=this.visibleItems.length-1:o>0&&(o-=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(t.key==="ArrowDown"){let o=this.getSelectedIndex();o===-1?o=0:o<this.visibleItems.length-1&&(o+=1);let r="";o!==-1&&(r=this.visibleItems[o].id),this.setSelectedId(r);return}if(t.key==="Enter"){const o=(e=this.visibleItems.find(r=>r.id===this.selectedId))!=null?e:null;this.onSelected&&this.onSelected(this,o)}}}class Tw extends xw{constructor(e,o,r){super(e,r);h(this,"popup");h(this,"onShow",null);h(this,"onHide",null);h(this,"custom",null);h(this,"handleShow",()=>{this.onShow&&this.onShow(this)});h(this,"handleHide",()=>{this.onHide&&this.onHide(this)});h(this,"handleShown",()=>{this.focus()});this.popup=new ms(this.root)}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(e){this.reset(),this.popup.manualShow(e,{theme:"dropdown-list"}),this.focus()}processKeyDown(e){super.processKeyDown(e),(e.key==="Esc"||e.key==="Enter")&&this.popup.close()}processClick(e){super.processClick(e);const o=e.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.popup.close()}}const iz="",sz="";function Sw(n,t){const e=document.createElement("div");e.classList.add("toast","show"),t!=null&&t.theme&&e.setAttribute("data-theme",t.theme),t!=null&&t.id&&e.setAttribute("data-id",t.id),t!=null&&t.html?e.innerHTML=n:e.textContent=n,t!=null&&t.position&&(e.style.left=`${t.position.x}px`,e.style.top=`${t.position.y}px`,e.classList.add("positioned")),document.body.appendChild(e),setTimeout(()=>{e.classList.remove("show"),setTimeout(()=>{e.remove()},500)},(t==null?void 0:t.duration)||3e3)}const Y2=`<?xml version="1.0" ?>
28
28
  <svg
29
29
  fill="currentColor"
30
30
  xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
@@ -334,7 +334,7 @@ xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
334
334
  <path d="M5.27137 5.61819C6.60787 5.61819 7.69131 4.53475 7.69131 3.19825C7.69131 1.86176 6.60787 0.77832 5.27137 0.77832C3.93488 0.77832 2.85144 1.86176 2.85144 3.19825C2.85144 4.53475 3.93488 5.61819 5.27137 5.61819Z" stroke="#999999" stroke-linejoin="round" fill="none"/>
335
335
  <path d="M9.07413 10.8036H13.2226M11.1484 8.91895V13.1009V8.91895Z" stroke="#999999" stroke-linecap="square" fill="none"/>
336
336
  <path d="M8.03712 8.38281H5.20234C3.65344 8.38281 2.87899 8.38281 2.28739 8.68423C1.76699 8.94939 1.3439 9.3725 1.07875 9.89289C0.777313 10.4845 0.777313 11.2589 0.777313 12.8078V13.2227H8.03712" stroke="#999999" stroke-linecap="square" stroke-linejoin="round" fill="none"/>
337
- </svg>`;function gB(n,t){var e;if(A(t,"menu-item"),!n.element){if(n.type==="section"){const o=b("div",["section-name"],null,n.name);t.appendChild(o)}else if(n.type!=="separator"){if(n.icon){const r=b("div",["menu-item-icon"],null);n.icon&&(r.innerHTML=n.icon),t.appendChild(r)}const o=b("div",["menu-item-name","text"],null,n.name);if(t.appendChild(o),n.subText&&b("div",["item-subtext","text"],t,n.subText),n.children&&!n.element){const r=b("div",["menu-item-sub-indicator"],null);r.innerHTML=J2,t.appendChild(r)}if((e=n.states)!=null&&e.includes("checked")){const r=b("div",["menu-item-checked-icon"],null);r.innerHTML=Yw,t.appendChild(r)}}}}class tr extends gc{constructor(t,e,o){super(t,e,{autoClose:!0,disablePageScroll:!0,...o})}manualShow(t,e){const o={theme:"menu",...e};super.manualShow(t,o)}initCommandBarElement(t){A(t,"menu")}initItemElement(t,e){gB(t,e)}}function pB(n,t,e){var o;return new tr((o=n.children)!=null?o:[],t,{...e,parentItem:n})}class ps extends gc{constructor(t,e,o){super(t,e,{itemElementTag:"button",tippyArrow:!1,...o})}getSubBarOptions(t){var r,i;const e=()=>{const s=this.getItemElementById(t.id),c=this.content.getBoundingClientRect(),a=s.getBoundingClientRect();return new DOMRect(a.left,c.top,a.width,c.height)};return{placement:(r=t.childrenPlacement)!=null?r:"top",getReferenceClientRect:e,offset:(i=t.childrenOffset)!=null?i:[0,4]}}manualShow(t,e){const o={theme:"toolbar",...e};super.manualShow(t,o)}initCommandBarElement(t){A(t,"toolbar")}initItemElement(t,e){e.setAttribute("data-button-id",t.id),this.options.tooltipId&&t.name&&!t.disableTooltip&&(e.setAttribute(`data-editor-tooltip-${this.options.tooltipId}`,t.name),t.desc&&e.setAttribute(`data-editor-tooltip-desc-${this.options.tooltipId}`,t.desc));const o=e;if(!t.element)if(t.icon){const r=b("span",["toolbar-item-icon-container"],o);t.icon.trim().startsWith("<")?r.innerHTML=t.icon:r.innerText=t.icon}else{const r=b("span",["toolbar-item-name-container"],o);r.innerText=t.name}if(t.dropdown){e.setAttribute("data-dropdown","true");const r=b("span",["toolbar-item-dropdown-container"],o);r.innerHTML=Ju}t.states&&(t.states.indexOf("checked")!==-1&&A(o,"checked"),t.states.indexOf("disabled")!==-1&&(o.disabled=!0))}}function CB(n,t,e){var o;return new ps((o=n.children)!=null?o:[],t,{...e,parentItem:n})}const lz="";Hr.registerManualCommandBar("menu",pB),Hr.registerManualCommandBar("toolbar",CB);const cz="",l5=w("ui-base");class bc extends gc{constructor(e,o){super(bc.getCommandItems(e,o),void 0,{disablePageScroll:!0,...o});h(this,"handleDocumentMouseDown",e=>{})}initCommandBarElement(e){A(e,"dialog","manual")}initItemElement(e,o){}show(e,o){this.manualShow(e,{...o,theme:"light"})}get dialogContent(){const e=this.items[0];d(l5,e,"no dialog item");const o=e.element;return d(l5,o,"no item element"),o}static getCommandItems(e,o){var s;return[{id:(s=o==null?void 0:o.id)!=null?s:`manual-dialog-${N()}`,name:"",element:e}]}}const bB=[-1,6,0,1,2,3,4,5],vB=[-1,6,0,1,2,3,4,5,14,13,7,8,9,10,11,12],c5=w("color-palette");function a5(n,t,e,o){d(c5,n>0,"no color in palette");const r=t||1;d(c5,r>0,`invalid palette rows: ${r}`);const i=n/r,s=b("div",["palette-container",o],null);for(let l=0;l<r;l++){const c=b("div",["palette-container-row"],s);for(let a=0;a<i;a++){const u=e(l*i+a);c.appendChild(u)}}return s}function kB(n){const t=b("button",["color-button"],null),e=bB[n];return t.setAttribute("data-color-index",`${e}`),t.innerHTML=K2,t}function yB(n){const t=b("button",["background-color-button"],null),e=vB[n];return t.setAttribute("data-color-index",`${e}`),t}function wB(){const n=b("div",["clear-button-container"],null),t=b("button",["clear-button"],n);return t.innerText=T.t("colorPalette.reset"),n}function BB(n){const t=b("div",["color-palette"],null);return n.color!==!1&&(b("div",["bar-desc"],t,T.t("colorPalette.colorDesc")),t.appendChild(a5(8,1,kB,"color"))),n.backgroundColor!==!1&&(b("div",["bar-desc"],t,T.t("colorPalette.backgroundDesc")),t.appendChild(a5(16,2,yB,"background-color"))),n.clearColorButton!==!1&&t.appendChild(wB()),t}function EB(n,t,e){const o=t==="color"?"color":"background-color",r=n.querySelector(`.${o} button.selected`);r&&z(r,"selected"),e===null&&(e=-1);const i=n.querySelector(`.${o} button[data-color-index="${e}"]`);i&&A(i,"selected")}const az="",IB={};class xB extends Yt.TypedEmitter{constructor(e=IB){super();h(this,"root");h(this,"handleClick",e=>{const o=e.target;if(!o||!(o instanceof Element))return;const r=o.closest("button");if(!r)return;if(nt(r,"clear-button")){this.setColor("backgroundColor",null),this.setColor("color",null),this.emit("onClick","clearColor",0);return}const i=r.getAttribute("data-color-index");if(!i)return;const s=Number.parseInt(i,10);Number.isNaN(s)||(nt(r,"color-button")?s===-1?(this.setColor("color",null),this.emit("onClick","clearColor",1)):(this.setColor("color",s),this.emit("onClick","color",s)):s===-1?(this.setColor("backgroundColor",null),this.emit("onClick","clearColor",2)):(this.setColor("backgroundColor",s),this.emit("onClick","backgroundColor",s)))});this.options=e,this.root=BB(e),this.root.addEventListener("click",this.handleClick)}destroy(){this.removeAllListeners(),this.root.removeEventListener("click",this.handleClick)}setColor(e,o){EB(this.root,e,o)}}class d5{constructor(t,e){h(this,"name","Color Palette");h(this,"element");h(this,"palette");h(this,"closeable",null);this.id=t,this.palette=new xB(e),this.element=this.palette.root}setCloseable(t){this.closeable=t}destroy(){this.palette.destroy(),this.closeable=null}}function TB(){const n=b("button",["color-button"],null);return n.innerHTML=K2,n}function dh(n,t){const[e,o]=t;e===null?n.removeAttribute("data-color"):n.setAttribute("data-color",`${e}`),o===null?n.removeAttribute("data-background-color"):n.setAttribute("data-background-color",`${o}`)}class SB extends Yt.TypedEmitter{constructor(e){super();h(this,"id","text-color-item");h(this,"name",T.t("colorPalette.name"));h(this,"dropdown",!0);h(this,"manualShowChildren",!0);h(this,"children",[]);h(this,"element");h(this,"colorPaletteItem");h(this,"latestColors",[null,null]);h(this,"handlePaletteClick",(e,o)=>{this.emit("onClick",e,o),e==="color"||e==="backgroundColor"?e==="color"?this.latestColors[0]=o:this.latestColors[1]=o:this.latestColors=[null,null],dh(this.element,this.latestColors)});h(this,"beforePopup",()=>{this.emit("beforePopup")});this.editor=e,this.colorPaletteItem=new d5("text-color-palette-item"),this.colorPaletteItem.palette.addListener("onClick",this.handlePaletteClick),this.children.push(this.colorPaletteItem),this.element=TB()}destroy(){this.colorPaletteItem.destroy()}updatePaletteColor(e){this.colorPaletteItem.palette.setColor("color",e[0]),this.colorPaletteItem.palette.setColor("backgroundColor",e[1]),this.latestColors=e,dh(this.element,this.latestColors)}updateButtonColor(e){this.latestColors=e,dh(this.element,this.latestColors)}}const dz="";function uh(n,t){const e=b("div",["editor-input-wrap"],n);t!=null&&t.className&&A(e,t==null?void 0:t.className);const o=b("div",["editor-input-label"],e);b("span",[],o,t.label),t.required&&A(o,"required");const r=b("div",["editor-input-container"],e),i=b("input",["editor-input"],r);t.placeholder&&(i.placeholder=t.placeholder),t.defaultValue&&(i.value=t.defaultValue);const s=b("div",["editor-input-error"],e);return i.addEventListener("input",l=>{var c;(c=t.onChange)==null||c.call(t,l),z(e,"error")}),i.addEventListener("keydown",l=>{var c;(c=t.onKeyDown)==null||c.call(t,l)}),{getField:()=>i,getInputValue:()=>i.value,setFieldError:l=>{A(e,"error"),s.innerText=l},focus:()=>{setTimeout(()=>{i.focus()})}}}function hh(n){const t=document.getSelection();if(!t)return!0;const e=t.focusNode;if(!e)return!0;const o=t.focusOffset,r=e.childNodes[o];if(!r)return!0;if(r instanceof HTMLElement){const i=r.tagName.toLowerCase();if(r===n.input.inputElement)return!0;if(i==="input"||i==="textarea")return!1}return!0}const DB=w("ui-base");class LB{constructor(t,e){h(this,"menu");h(this,"currentText","");h(this,"handleClick",(t,e)=>{this.options.onClickItem(this,e)});h(this,"handleClose",()=>{hh(this.editor)&&this.editor.focus()});h(this,"handleKeydown",t=>{this.menu.handleDocumentKeydown(t)});this.editor=t,this.options=e,this.menu=new tr([],void 0,{id:e.id}),this.menu.addListener("click",this.handleClick),this.menu.addListener("close",this.handleClose)}setItems(t){if(this.menu.updateItems(t),t.length>0){const e=t.find(o=>o.type!=="section"&&o.type!=="separator");e&&this.menu.selectItem(e.id)}}async popup(t,e,o){var a,u;if(((u=(a=this.options).onShow)==null?void 0:u.call(a,this,t,e,o))===!1)return;this.options.showLoading&&this.showLoading();const r=this.editor.getBlockByIndex(t,e);if(!It(this.editor.rootContainer,r)||W(this.editor,r)<o)return;const i=Ho(this.editor,r,At(this.editor,r,o));if(i.length===0)return;const s=i[0],l=zo(this.editor,r,"editor-auto-suggest-menu",s);this.menu.manualShow(l),this.options.placeholder&&this.showPlaceholder();const c=await this.options.queryItems(this,"");this.highlightText(""),this.setItems(c)}showLoading(){!this.options.showLoading||(this.options.loadingElement?this.setItems([{id:"loading",name:"",element:this.options.loadingElement,states:["disabled"]}]):this.setItems([{id:"loading",name:"loading",states:["disabled"]}]))}showPlaceholder(){this.setItems([{id:"placeholder",name:"enter text to search",states:["disabled"]}])}showNoResultMessage(t){if(this.options.noResultMessage){const e={name:"",id:"placeholder",states:["disabled"]};typeof this.options.noResultMessage=="string"?e.name=this.options.noResultMessage:(this.options.noResultMessage instanceof HTMLElement||typeof this.options.noResultMessage=="function")&&(e.element=this.options.noResultMessage),this.setItems([e])}else this.setItems([{id:"placeholder",name:T.t("search.emptyTips"),states:["disabled"]}])}close(){this.menu.close()}get isVisible(){return this.menu.isVisible}destroy(){this.menu.close(),this.menu.removeAllListeners(),this.menu.destroy()}async handleSearchText(t){this.currentText=t;const e="auto-suggest";try{await qe.lock(e),this.showLoading();const o=this.currentText,r=await this.options.queryItems(this,o);if(this.currentText===o&&(this.currentText=""),r.length===0){this.showNoResultMessage(t);return}this.setItems(r),this.options.highlight&&this.highlightText(o.replace(/^\s+|\s+$/g,""))}finally{qe.release(e)}}highlightText(t){DB.debug(`highlight menu text: ${t}`);const e=this.menu.content,o=(i,s)=>{if(!s)return i;let l="";const c=s.length,a=s.toLocaleLowerCase();let u=0;for(u=0;u<=i.length-c;u){let f=i.substring(u,u+c);if(f.toLocaleLowerCase()===a){u+=c;const m=i.charAt(u);let C=!1;f.endsWith(" ")&&(C=!0,f=f.trimEnd()),l+=`<span class="highlight">${f}${m===" "||C?"&nbsp":""}</span>`}else l+=i.charAt(u),u++}return u<i.length&&(l+=i.substring(u)),l},r=i=>{if(nt(i,"text")){const s=i.textContent;if(!s)return;const l=o(s,t);i.innerHTML=l;return}Array.from(i.children).forEach(r)};r(e)}}const fh=w("auto-suggest-menu");class mh{constructor(t,e){h(this,"menu");h(this,"anchor",null);h(this,"handleSelectionChanged",t=>{var o,r;if(!((o=this.menu)!=null&&o.isVisible))return;const e=t.selection.range.start;if(e.isSimple()&&e.blockId===((r=this.anchor)==null?void 0:r.blockId)&&e.offset>=this.anchor.offset){const i=t.getBlockById(e.blockId);if(vt(be(ue(t,i),e.offset).left).startsWith(this.anchor.leftText))return}this.menu.close()});h(this,"deleteTrigger",()=>{const t=this.editor,e=t.selection.range.start;if(!e.isSimple()||!this.anchor)return!1;const{blockId:o,offset:r}=e,i=t.getBlockById(o),s=vt(Ul(t,i,r));if(d(fh,this.anchor,"no anchor"),!s.startsWith(this.anchor.leftText))return!1;const l=this.anchor.offset-this.anchor.trigger.length,c=r-l;return t.selection.selectBlock(i,l),c&&(t.deleteTextFromBlock(i,l,c),this.anchor.offset-=this.anchor.trigger.length),this.anchor.trigger.length||this.menu.close(),!0});h(this,"onShow",(t,e,o,r)=>{var i;if((i=this.options)!=null&&i.onShow)return this.options.onShow(this,e,o,r)});h(this,"onClickItem",(t,e)=>{!this.anchor||(this.options.autoDeleteTrigger&&this.deleteTrigger(),this.options.onClickItem(this,e,this.anchor))});h(this,"queryItems",(t,e)=>this.options.queryItems(this,e));h(this,"renderMenuItem",(t,e)=>{var r,i;return(i=(r=this.options).renderMenuItem)==null?void 0:i.call(r,this,e)});this.editor=t,this.options=e,this.menu=new LB(t,{id:e.id,showLoading:e.showLoading,loadingElement:e.loadingElement,placeholder:e.placeholder,noResultMessage:e.noResultMessage,highlight:e.highlight,onShow:this.onShow,onClickItem:this.onClickItem,queryItems:this.queryItems,renderMenuItem:this.renderMenuItem}),t.input.addHandler(this),t.addListener("selectionChanged",this.handleSelectionChanged)}handleBeforeKeyDown(t,e){var o;return!((o=this.menu)!=null&&o.isVisible)||rd(e.key)?!1:km(e)&&!Oo(e)?(setTimeout(()=>{this.resetItems()}),!1):id(e)?(this.menu.close(),!0):(this.menu.handleKeydown(e),!0)}popup(t,e,o,r){this.anchor={blockId:q(t),offset:e,leftText:o,trigger:r};const i=U(H(t)),s=J(t);this.menu.popup(i,s,e)}handleAfterInsertText(t,e,o,r,i){var u;const s=t.selection.range.start;if(!s.isSimple()||e==="root"&&o===0)return!1;const{blockId:l,offset:c}=s,a=t.getBlockByIndex(e,o);if(q(a)!==l)return!1;if((u=this.menu)!=null&&u.isVisible)this.resetItems();else if(this.options.trigger.indexOf(i)!==-1){if(r>0&&this.options.needSpaceBeforeTrigger&&t.getBlockString(a)[r-1]!==" ")return!1;const f=vt(Ul(t,a,c));this.popup(a,c,f,i)}return!1}handleUpdateCompositionText(t,e,o,r,i){var a;const s=t.selection.range.start;if(!s.isSimple())return!1;const{blockId:l}=s,c=t.getBlockByIndex(e,o);return q(c)!==l||(a=this.menu)!=null&&a.isVisible&&this.resetItems(),!1}resetItems(){var l;if(!((l=this.menu)!=null&&l.isVisible))return;const t=this.editor,e=t.selection.range.start;if(!e.isSimple())return;const{blockId:o,offset:r}=e,i=t.getBlockById(o),s=vt(Ul(t,i,r));if(d(fh,this.anchor,"no anchor"),s.startsWith(this.anchor.leftText)){const c=s.substring(this.anchor.leftText.length);fh.debug(`search text: ${c}`),this.menu.handleSearchText(c)}}destroy(){var t;this.editor.input.removeHandler(this),this.editor.removeListener("selectionChanged",this.handleSelectionChanged),(t=this.menu)==null||t.destroy()}}function MB(){const n={};for(let t=1;t<=8;t++)n[`heading-${t}`]={shortcut:`/h${t}`};return n}const RB={"insert-hr":{shortcut:"/hr"},"insert-uml":{shortcut:"/uml"},"insert-table":{shortcut:"/table"},"insert-image":{shortcut:"/image"},"insert-code":{shortcut:"/code"},"insert-link":{shortcut:"/link"},"insert-drawio":{shortcut:"/uml"},"insert-video":{shortcut:"/video"},"insert-audio":{shortcut:"/audio"},"insert-math":{shortcut:"/math"},"insert-webPage":{shortcut:"/web"},"insert-bilibili":{shortcut:"/bilibili"},"insert-youku":{shortcut:"/youku"},"insert-figma":{shortcut:"/figma"},"insert-modao":{shortcut:"/modao"},"insert-tencent":{shortcut:"/tencent"},"insert-unordered":{shortcut:"/bl"},"insert-ordered":{shortcut:"/nu"},"insert-checkbox":{shortcut:"/todo"},"insert-quote":{shortcut:"/quote"},...MB()};function fe(n){var t;return(t=RB[n])==null?void 0:t.shortcut}function AB(n){var t;return(t=n.subText)!=null?t:""}const In=w("table-dom");function Co(n){return`${q(n)}_scroll`}function jt(n){const t=n.querySelector("div[data-type=table-content] >table");return d(In,t instanceof HTMLTableElement,"invalid table"),t}function xn(n,t){const o=n.getCustom(Co(t)).contentElement.firstElementChild;d(In,o instanceof HTMLElement,"invalid table content");let r=o.querySelector(":scope >div[data-type=table-tools]");return r||(r=b("div",[],o),r.setAttribute("data-type","table-tools")),d(In,r,"no table tools"),r}function u5(n){const t=[];return Array.from(n.rows).forEach(e=>{t.push(...Array.from(e.cells))}),t}function Cs(n){const t=n.querySelector(":scope div[data-type=editor-container]");return d(In,t,"no child container in cell"),t}function OB(n){const o=u5(n).map(r=>{const i=Cs(r),s=U(i),l=r.colSpan,c=r.rowSpan;return`${s}/${l}/${c}`}).join();return Ei.default(o)}function Ht(n){return rt(n)==="table"}function gh(n){const t=H(n);if(pt(t))return null;const e=F(t);return d(In,e,"no parent block"),Ht(e)?t:gh(e)}function Me(n){if(Ht(n))return n;const t=H(n);if(pt(t))return null;const e=F(t);return d(In,e,"no parent block"),Ht(e)?e:Me(e)}function _B(n,t){const e=n.querySelector("colgroup");d(In,e,"no colgroup");const o=e.children[t];return d(In,o,"no col"),d(In,o instanceof HTMLTableColElement,`invalid col: ${o.tagName}`),o}function h5(n){try{return jt(n),!0}catch{return!1}}function NB(n){return Rt(n).querySelector(":scope > .block-helper")}function f5(n){const t=F(n.contentElement);d(In,t,"no block");const e=NB(t);if(e){const o=Math.min(n.contentElement.offsetLeft,n.rootElement.scrollLeft),r=t.getBoundingClientRect().width;e.style.right=`${o+r}px`}}const Re=w("doc-table-grid");class $B{constructor(t){h(this,"_cells",[]);for(let e=0;e<t;e++)this._cells.push(void 0)}cols(){return this._cells.length}setCell(t,e){d(Re,t>=0&&t<this.cols(),`set cell, invalid col: ${t}`),this._cells[t]=e}getCell(t){d(Re,t>=0&&t<this.cols(),`get cell, invalid col: ${t}`);const e=this._cells[t];return d(Re,e,"get cell, no cell"),e}getCellAllowEmpty(t){return d(Re,t>=0&&t<this.cols(),`get cell, invalid col, ${t}`),this._cells[t]}getNextNonVirtualCell(t){return this._cells.slice(t+1).find(e=>!e.virtual)}forEach(t){this._cells.forEach(t)}}class vc{constructor(t){h(this,"_data");h(this,"_rows");this._data=t,this._rows=[];for(let e=0;e<this.rowCount;e++)this._rows.push(new $B(this.colCount));this.fillGrid(),d(Re,t.colsWidth,"no colsWidth"),d(Re,this.colCount===t.colsWidth.length,"invalid col count")}get rowCount(){return this._data.rows}get colCount(){return this._data.cols}getNextEmptyCell(t,e){let o=t,r=e;for(;;){if(o+=1,o===this.colCount&&(o=0,r+=1),r>=this.rowCount)return null;if(this._rows[r].getCellAllowEmpty(o)===void 0)return{col:o,row:r}}}fillGrid(){const t=this._data.children;d(Re,t,"no children");let e=0,o=0;t.forEach((r,i)=>{const s=this._data[`${r}_colSpan`]||1,l=this._data[`${r}_rowSpan`]||1;for(let a=0;a<l;a++)for(let u=0;u<s;u++)this._rows[o+a].setCell(e+u,{col:e,row:o,containerId:r,virtual:u!==0||a!==0,colSpan:s,rowSpan:l});const c=this.getNextEmptyCell(e,o);c?(e=c.col,o=c.row):d(Re,i===t.length-1,`invalid table data, no next empty cell: ${JSON.stringify(this._data)}`)}),this._rows.forEach(r=>{r.forEach(i=>{d(Re,i,"no cell"),d(Re,i.containerId,"no containerId")})})}getCell(t){const{col:e,row:o}=t,r=this._rows[o];d(Re,r,`get cell, no row: ${o}`);const i=r.getCell(e);return d(Re,i,`get cell, no cell: ${e}`),i}getRow(t){const e=this._rows[t];return d(Re,e,`get row, no row: ${t}`),e}forEach(t){this._rows.forEach(t)}}const kc=w("table-data");function PB(n){const t=n.firstElementChild;return d(kc,t,"no child element for cell"),d(kc,bn(t),"cell first child is not a container"),d(kc,Ye(t),"cell first child is not a container"),t}function jB(n){const t=F(n);d(kc,t,"no parent block for table");const e=[],o={};Array.from(n.rows).forEach(l=>{Array.from(l.cells).forEach(c=>{const a=PB(c),u=U(a);e.push(u),(c.colSpan>1||c.rowSpan>1)&&(o[`${u}_colSpan`]=c.colSpan,o[`${u}_rowSpan`]=c.rowSpan)})});const r=n.rows.length,i=Array.from(n.rows[0].cells).map(l=>l.colSpan).reduce((l,c)=>l+c,0);return{id:q(t),type:rt(t),rows:r,cols:i,children:e,colsWidth:Array(i).fill(100),...o}}function er(n){return new vc(n)}function HB(n){return er(jB(n))}const Zt=w("table-grid"),FB=60;class zB{constructor(t,e){h(this,"containerId");h(this,"row");h(this,"col");h(this,"colSpan");h(this,"rowSpan");h(this,"virtual");h(this,"table");this.table=t,this.containerId=e.containerId,this.row=e.row,this.col=e.col,this.colSpan=e.colSpan,this.rowSpan=e.rowSpan,this.virtual=e.virtual}get cell(){const e=this.container.closest("td");return d(Zt,e,"no parent cell for child container"),e}get container(){const t=this.table.querySelectorAll(`[data-container-id=${this.containerId}]`);d(Zt,t.length===1,"containers !== 1"),d(Zt,bn(t[0]),"not a container");const e=t[0];return d(Zt,Ye(e),"not a child container"),e}}class UB{constructor(t,e){h(this,"_cells",[]);e.forEach(o=>{this._cells.push(new zB(t,o))})}get cells(){return this._cells}getCell(t){return d(Zt,t<this._cells.length,"get cell, invalid col"),this._cells[t]}getNextNonVirtualCell(t){return this._cells.slice(t+1).find(e=>!e.virtual)}getSpannedCell(){return this._cells.find(t=>t.virtual||t.colSpan>1||t.rowSpan>1)}}const Ef=class{constructor(t){h(this,"_rows",[]);this.table=t,HB(t).forEach(r=>{this._rows.push(new UB(t,r))});const o=this.colCount;this._rows.forEach(r=>{d(Zt,r.cells.length===o,"row.cells.length !== colCount")})}get rowCount(){return this._rows.length}get colCount(){return this._rows.length===0?0:(d(Zt,this.rowCount>0,"rowCount <= 0"),this.getRow(0).cells.length)}getRow(t){return this._rows[t]}getCell(t){const e=this.getRow(t.row);return d(Zt,e,"no row"),e.getCell(t.col)}getCellContainer(t){return this.getCell(t).container}getFirstCellContainer(){return this.getCellContainer({row:0,col:0})}getLastCellContainer(){const t=this.rowCount-1,e=this.colCount-1;return this.getCellContainer({row:t,col:e})}getColumnCells(t){d(Zt,t>=0&&t<this.colCount,"colIndex out of range");const e=this.rowCount,o=[];for(let r=0;r<e;r++){const i=this.getCell({row:r,col:t});o.push(i)}return o}toRealCells(t){const e=[];return t.forEach(o=>{const r=this.getRealCell(o);e.findIndex(i=>i.containerId===r.containerId)===-1&&e.push(r)}),e}getColumnRealCells(t){const e=this.getColumnCells(t);return this.toRealCells(e)}getRowRealCells(t){const e=this.getRow(t).cells;return this.toRealCells(e)}getFirstSpannedCell(t){d(Zt,t>=0&&t<this.colCount,"colIndex out of range");const e=this.rowCount;for(let o=0;o<e;o++){const r=this.getCell({row:o,col:t});if(r.virtual||r.colSpan>1||r.rowSpan>1)return r}}getRealCell(t){const e=this.getCell(t);if(!e.virtual)return e;const o=this.getCellById(e.containerId);return d(Zt,!o.virtual,"found a virtual cell"),o}getColumnSpannedRange(t){const e=this.getColumnRealCells(t);let o=1e5,r=-1;return e.forEach(i=>{o=Math.min(i.col,o),r=Math.max(i.col+i.colSpan-1,r)}),d(Zt,o<=r,"min > max"),d(Zt,o>=0,"min < 0"),d(Zt,r<this.colCount,"max >= colCount"),[o,r]}getRowSpannedRange(t){const e=this.getRowRealCells(t);let o=1e5,r=-1;return e.forEach(i=>{o=Math.min(i.row,o),r=Math.max(i.row+i.rowSpan-1,r)}),d(Zt,o<=r,"min > max"),d(Zt,o>=0,"min < 0"),d(Zt,r<this.rowCount,"max >= rowCount"),[o,r]}getSpannedRange(t,e){const o=Math.min(t.row,e.row),r=Math.max(t.row,e.row),i=Math.min(t.col,e.col),s=Math.max(t.col,e.col),l=[];for(let C=o;C<=r;C++)for(let v=i;v<=s;v++)l.push(this.getCell({row:C,col:v}));const c=this.toRealCells(l);let a=1e4,u=1e4,f=-1,m=-1;return c.forEach(C=>{u=Math.min(C.col,u),a=Math.min(C.row,a),m=Math.max(C.col+C.colSpan-1,m),f=Math.max(C.row+C.rowSpan-1,f)}),[{row:a,col:u},{row:f,col:m}]}getAllCells(){return this.getCells({col:0,row:0},{col:this.colCount-1,row:this.rowCount-1})}sub(t,e){const o=[];for(let r=t.row;r<=e.row;r++){const i=[];for(let s=t.col;s<=e.col;s++){const l=this.getCell({row:r,col:s});i.push(l)}o.push(i)}return o}getAllContainers(){return this.getAllCells().map(e=>e.container)}getCells(t,e){const o=[],r=this.getSpannedRange(t,e),i=r[0],s=r[1],l=Math.min(i.row,s.row),c=Math.max(i.row,s.row),a=Math.min(i.col,s.col),u=Math.max(i.col,s.col);for(let f=l;f<=c;f++)for(let m=a;m<=u;m++){const C=this.getCell({row:f,col:m});C.virtual||o.push(C)}return o}map(t){const e=[];for(let o=0;o<this.rowCount;o++){const r=[];for(let i=0;i<this.colCount;i++){const s=this.getCell({row:o,col:i});r.push(t(s))}e.push(r)}return e}getBottomCell(t){const e=this.rowCount;let o=t,r=t.row;for(;o.containerId===t.containerId;){if(r+=1,r>=e)return null;o=this.getCell({row:r,col:t.col})}return this.getRealCell(o)}getTopCell(t){let e=t,o=t.row;for(;e.containerId===t.containerId;){if(o-=1,o<0)return null;e=this.getCell({row:o,col:t.col})}return this.getRealCell(e)}get cells(){let t=[];return this._rows.forEach(e=>{t=t.concat(e.cells)}),t}getVirtualCellContainersGrid(){return this.map(t=>t.containerId)}static virtualCellContainersGridToChildren(t){const e=t,o=[];return e.forEach(r=>{r.forEach(i=>{o.indexOf(i)===-1&&o.push(i)})}),o}getCellById(t){const o=this.cells.find(r=>r.containerId===t);return d(Zt,o,"cell not found"),o}getCellByCellElement(t){const e=Cs(t);return this.getCellByContainerId(U(e))}getCellByContainerId(t){return this.getCellById(t)}static fromTable(t){const e=OB(t),o=this.caches.getSync(e,()=>(Zt.debug("create table grid"),new Ef(t)));return o.table!==t?(this.caches.delete(e),this.fromTable(t)):o}static fromBlock(t){return this.fromTable(jt(t))}};let et=Ef;h(et,"caches",new Xf(FB));function yc(n,t){Object.entries(n).forEach(([e])=>{e.startsWith(`${t}/`)&&delete n[e]})}const VB=w("table-selection-range");function an(n,t,e){var I,M,R,$;const o=et.fromBlock(n),r=t,i=e,s=o.getCellByContainerId(r.childContainerId),l=o.getCellByContainerId(i.childContainerId),c=r.custom,a=i.custom,u=(I=c==null?void 0:c.rowIndex)!=null?I:s.row,f=(M=c==null?void 0:c.colIndex)!=null?M:s.col,m=(R=a==null?void 0:a.rowIndex)!=null?R:l.row+l.rowSpan-1,C=($=a==null?void 0:a.colIndex)!=null?$:l.col+l.colSpan-1,v=Math.min(u,m),B=Math.max(u,m),y=Math.min(f,C),S=Math.max(f,C);return{fromRow:v,toRow:B,fromCol:y,toCol:S}}function ph(n,t){const e=new Set,o=new Set,r=n.selection.range;if(!r.isSimple()&&r.start.blockId===q(t)){const i=et.fromBlock(t),{start:s,end:l}=r;d(VB,!s.isSimple()&&!l.isSimple(),"invalid range");const{fromCol:c,toCol:a,fromRow:u,toRow:f}=an(t,s,l);if(u===0&&f===i.rowCount-1)for(let m=c;m<=a;m++)o.add(m);if(c===0&&a===i.colCount-1)for(let m=u;m<=f;m++)e.add(m)}return{selectedRows:e,selectedColumns:o}}const Fr=w("delete-columns");function m5(n,t,e){const{start:o,end:r}=e;if(o.blockId!==r.blockId||e.isSimple()||n.getBlockById(o.blockId)!==t||rt(t)!=="table")return!1;const{fromRow:s,toRow:l}=an(t,e.start,e.end),c=et.fromBlock(t);return s===0&&l===c.rowCount-1}function Ch(n){var M;const t=n.getEditor(),e=t.getBlockById(n.start.blockId);if(!m5(t,e,n))return;if(n.isSimple()){t.deleteBlock(e);return}const{fromCol:o,toCol:r}=an(e,n.start,n.end),i=et.fromBlock(e);if(o===0&&r===i.colCount-1){t.deleteBlock(e);return}const s=new Set,l=i.map(R=>R.containerId);for(let R=0;R<l.length;R++){const $=l[R];for(let Z=o;Z<=r;Z++){const ot=$[Z];s.add(ot)}$.splice(o,r-o+1)}const c=new Set(l.flat()),a=new Set(Array.from(s).filter(R=>!c.has(R))),u=r-o+1,f=new Map,m=new Map;s.forEach(R=>{if(a.has(R))return;const $=i.getCellByContainerId(R);if(d(Fr,$.colSpan>1,"invalid effected cell, colSpan === 1"),$.col<o){d(Fr,c.has(R),"invalid effected cell, not exists");let yt=$.col+$.colSpan-1;yt>r&&(yt=r);const se=yt-o+1,eo=$.colSpan-se;f.set(R,eo);return}d(Fr,$.col<=r,"invalid effected cell, col > endCol");const Z=$.col,ot=$.col+$.colSpan-1,st=$.col-o,mt=ot-Z+1-u+st;d(Fr,mt>0,"invalid effected cell, newSpanned <= 0");const ut=yn(t.doc);m.set(R,{newContainerId:ut,colSpan:mt})});for(let R=0;R<l.length;R++){const $=l[R];for(let Z=o;Z<$.length;Z++){const ot=$[Z],st=m.get(ot);st&&($[Z]=st.newContainerId)}}const C=Y.default(t.getBlockData(e));C.colsWidth.splice(o,r-o+1),a.forEach(R=>{yc(C,R)}),f.forEach((R,$)=>{d(Fr,R>=1,"invalid modified colSpan, colSpan < 1"),R===1?C[`${$}_colSpan`]=void 0:C[`${$}_colSpan`]=R}),m.forEach((R,$)=>{yc(C,$);const{newContainerId:Z,colSpan:ot}=R;d(Fr,ot>=1,"invalid newContainerData, colSpan < 1"),ot>1&&(C[`${Z}_colSpan`]=ot);const st=i.getCellByContainerId($).rowSpan;st>1&&(C[`${Z}_rowSpan`]=st)});const B=(M=l[0][o])!=null?M:l[0][o-1],y=t.getChildContainerData(B)[0],S=et.virtualCellContainersGridToChildren(l),I={...C,cols:C.cols-u,children:S};er(I),t.undoManager.runInGroup(()=>{t.updateBlockData(e,I,At(t,y.id,0)),t.deleteChildContainers(Array.from(a)),t.deleteChildContainers(Array.from(m.keys()))})}const zr=w("delete-rows");function g5(n,t,e){const{start:o,end:r}=e;if(o.blockId!==r.blockId||e.isSimple()||n.getBlockById(o.blockId)!==t||rt(t)!=="table")return!1;const{fromCol:s,toCol:l}=an(t,e.start,e.end),c=et.fromBlock(t);return s===0&&l===c.colCount-1}function bh(n){const t=n.getEditor(),e=t.getBlockById(n.start.blockId);if(!g5(t,e,n))return;if(n.isSimple()){t.deleteBlock(e);return}const{fromRow:o,toRow:r}=an(e,n.start,n.end),i=et.fromBlock(e);if(o===0&&r===i.rowCount-1){t.deleteBlock(e);return}const s=new Set,l=i.map(I=>I.containerId);for(let I=r;I>=o;I--)l[I].forEach(R=>s.add(R)),l.splice(I,1);const c=new Set(l.flat()),a=new Set(Array.from(s).filter(I=>!c.has(I))),u=r-o+1,f=new Map,m=new Map;s.forEach(I=>{if(a.has(I))return;const M=i.getCellByContainerId(I);if(d(zr,M.rowSpan>1,"invalid effected cell, rowSpan === 1"),M.row<o){d(zr,c.has(I),"invalid effected cell, not exists");let mt=M.row+M.rowSpan-1;mt>r&&(mt=r);const ut=mt-o+1,yt=M.rowSpan-ut;f.set(I,yt);return}d(zr,M.row<=r,"invalid effected cell, col > endCol");const R=M.row,$=M.row+M.rowSpan-1,Z=M.row-o,ot=$-R+1-u+Z;d(zr,ot>0,"invalid effected cell, newSpanned <= 0");const st=yn(t.doc);m.set(I,{newContainerId:st,rowSpan:ot})});for(let I=o;I<l.length;I++){const M=l[I];for(let R=0;R<M.length;R++){const $=M[R],Z=m.get($);Z&&(M[R]=Z.newContainerId)}}const C=Y.default(t.getBlockData(e));a.forEach(I=>{yc(C,I)}),f.forEach((I,M)=>{d(zr,I>=1,"invalid modified rowSpan, rowSpan < 1"),I===1?delete C[`${M}_rowSpan`]:C[`${M}_rowSpan`]=I}),m.forEach((I,M)=>{yc(C,M);const{newContainerId:R,rowSpan:$}=I;d(zr,$>=1,"invalid newContainerData, rowSpan < 1"),$>1&&(C[`${R}_rowSpan`]=$);const Z=i.getCellByContainerId(M).colSpan;Z>1&&(C[`${R}_colSpan`]=Z)});const v=l[o]?l[o][0]:l[o-1][0],B=t.getChildContainerData(v)[0],y=et.virtualCellContainersGridToChildren(l),S={...C,rows:C.rows-u,children:y};er(S),t.undoManager.runInGroup(()=>{t.updateBlockData(e,S,At(t,B.id,0)),t.deleteChildContainers(Array.from(a)),t.deleteChildContainers(Array.from(m.keys()))})}const bs=w("table-range");function wc(n){d(bs,!n.isSimple(),"must be complex selection range");const{anchor:t,focus:e}=n;d(bs,!t.isSimple(),"invalid start pos type"),d(bs,!e.isSimple(),"invalid end pos type");const o=n.getEditor();d(bs,t.blockId===e.blockId,"invalid range, not same block");const r=o.getBlockById(t.blockId);d(bs,rt(r)==="table","invalid block type, not a table block");const i=jt(r),s=et.fromTable(i),l=s.getCellByContainerId(t.childContainerId),c=s.getCellByContainerId(e.childContainerId),a=Math.min(l.row,c.row),u=Math.max(l.row,c.row),f=Math.min(l.col,c.col),m=Math.max(l.col,c.col),C=s.getCell({row:a,col:f}),v=s.getCell({row:u,col:m});return{editor:o,block:r,table:i,startCell:C,endCell:v,startRow:a,startCol:f,endRow:u,endCol:m}}const vh=w("split-cell");function kh(n,t,e){const o=et.fromBlock(t),r=o.getRealCell(e);d(vh,!r.virtual,"should not split virtual cell"),d(vh,r.colSpan>1||r.rowSpan>1,"cell does not has span data");const i=o.getVirtualCellContainersGrid();for(let f=0;f<r.rowSpan;f++)for(let m=0;m<r.colSpan;m++){if(f===0&&m===0)continue;const C=f+r.row,v=m+r.col,B=yn(n.doc);i[C][v]=B}const s=n.getBlockData(t),l=Y.default(s);l[`${r.containerId}_colSpan`]=null,l[`${r.containerId}_rowSpan`]=null,l.children=et.virtualCellContainersGridToChildren(i);const a=n.getChildContainerData(r.containerId)[0];d(vh,a,"no child block");const u=At(n,a.id,0);er(l),n.updateBlockData(t,l,u)}function qB(n,t,e){e.forEach(o=>{const r=et.fromBlock(t).getCell(o);(r.virtual||r.colSpan>1||r.rowSpan>1)&&kh(n,t,o)})}function p5(n,t,e){if(e.isSimple())return!1;const{start:o,end:r}=e;if(o.blockId!==r.blockId||n.getBlockById(o.blockId)!==t||rt(t)!=="table")return!1;const{startCell:s,endCell:l}=wc(e);return!(s.cell!==l.cell||s.colSpan===1&&s.rowSpan===1)}function yh(n){const{editor:t,block:e,startRow:o,startCol:r,endRow:i,endCol:s}=wc(n),l=[];for(let c=o;c<=i;c++)for(let a=r;a<=s;a++)l.push({row:c,col:a});return qB(t,e,l),!0}const Ur=w("merge-cells");function C5(n,t,e){if(e.isSimple())return!1;const{start:o,end:r}=e;if(o.blockId!==r.blockId||n.getBlockById(o.blockId)!==t||rt(t)!=="table")return!1;const{startCell:s,endCell:l}=wc(e);return s.cell!==l.cell}function b5(n){const t=wc(n),e=t.endCell,o=e.row+e.rowSpan-1,r=e.col+e.colSpan-1,i=q(t.block),s=t.editor;yh(n);const l=s.getBlockById(i),c=jt(l),{startRow:a,startCol:u}=t,f=Y.default(s.getBlockData(l));d(Ur,f.children,"no table children");const m=et.fromTable(c),C=[];for(let mt=a;mt<=o;mt++)for(let ut=u;ut<=r;ut++){const yt=m.getCell({row:mt,col:ut});d(Ur,!yt.virtual,"cell is virtual"),C.push(yt)}d(Ur,C.length>0,"no selected cells");const v=C[0],B=C.slice(1),y=m.getCellByContainerId(v.containerId).container,S=[];B.forEach(mt=>{const ut=m.getCellByContainerId(mt.containerId).container,yt=U(ut);if(!Bd(s,ut)){const se=R0(s,yt);s.insertDocAt(y,Ge(y),se)}S.push(yt)});const I=U(y),M=r-u+1,R=o-a+1;f[`${I}_colSpan`]=M,f[`${I}_rowSpan`]=R,S.forEach(mt=>{d(Ur,f.children,"no table children");const ut=f.children.indexOf(mt);d(Ur,ut>0,"no deleted container"),f.children.splice(ut,1)});const $=f,ot=s.getChildContainerData(I)[0];d(Ur,ot,"no child block");const st=At(s,ot.id,0);er($),s.updateBlockData(l,$,st),s.deleteChildContainers(S)}const wh=10,WB=["table/merge-cells","table/split-cell","table/insert-column","table/insert-row","table/delete-rows","table/delete-columns","table/delete"];class Bh{constructor(){h(this,"id","TableBlockCommandProvider")}getAvailableCommands(t,e,o){if(rt(e)!=="table")return[];const r={blockId:q(e),blockKind:Qe(t,e),blockType:rt(e)},i=[];C5(t,e,o)&&i.push({id:"table/merge-cells",name:T.t("table.mergeCell"),icon:Aw,groupIndex:wh,...r}),p5(t,e,o)&&i.push({id:"table/split-cell",name:T.t("table.splitCell"),icon:Ow,groupIndex:wh,...r});const s=m5(t,e,o),l=g5(t,e,o);return s&&l&&i.push({id:"table/delete",name:T.t("table.deleteTable"),icon:_w,groupIndex:wh,...r}),i}executeCommand(t,e,o,r,i,s){return rt(e)!=="table"||!new Set(WB).has(r.id)?!1:r.id==="table/merge-cells"?(b5(o),!0):r.id==="table/split-cell"?(yh(o),!0):r.id==="table/delete-columns"?(Ch(o),!0):r.id==="table/delete-rows"?(bh(o),!0):r.id==="table/delete"?(t.deleteBlock(e),!0):!1}}var v5=(n=>(n.COL_TITLE_TABLE="col-title-table",n.COL_TITLE_ITEM="col-title-item",n.STRIPE_STYLE_TABLE="stripe-style-table",n.NO_BORDER="table-no-border",n))(v5||{});const Eh=6,vs=20;function GB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasColTitle:!0};n.updateBlockData(t,o)}function ZB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasColTitle:!1};n.updateBlockData(t,o)}function YB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasRowTitle:!0};n.updateBlockData(t,o)}function QB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasRowTitle:!1};n.updateBlockData(t,o)}function KB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),isStripeStyle:!0};n.updateBlockData(t,o)}function JB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),isStripeStyle:!1};n.updateBlockData(t,o)}function XB(n,t,e){if(!n.isBlockWritable(t))return;const r={...Y.default(n.getBlockData(t)),noBorder:!e};n.updateBlockData(t,r)}const Ih=w("get-selected-containers");function xh(n,t,e,o){d(Ih,e.blockId===o.blockId,"only allow select in single table block"),d(Ih,q(t)===e.blockId,"only allow select in single table block");const r=et.fromBlock(t),i=r.getCellByContainerId(e.childContainerId),s=r.getCellByContainerId(o.childContainerId);if(e.custom===void 0||o.custom===void 0)return r.getCells(i,s).map(y=>r.getCellContainer(y));const{fromCol:l,toCol:c,fromRow:a,toRow:u}=an(t,e,o),f=new Set,m=[];return r.sub({row:a,col:l},{row:u,col:c}).forEach(v=>{v.forEach(B=>{const y=r.getCellByContainerId(B.containerId);y.col<l||y.row<a||y.col+y.colSpan-1>c||y.row+y.rowSpan-1>u||f.has(B.containerId)||(f.add(B.containerId),m.push(y.container))})}),m}function tE(n,t,e){d(Ih,t.blockId===e.blockId,"only allow select in single table block");const o=n.getBlockById(t.blockId);return xh(n,o,t,e)}const nr=w("table-cell-dom");function eE(n,t,e){let o=n.getBlockById(e);for(;o;){const r=o.closest("td");d(nr,r,"no parent cell");const i=F(r);if(d(nr,i,"no parent block"),i===t)return r;o=i}return d(nr,!1,"filed to get cell by child block id"),null}function Gn(n,t,e){if(n.getBlockById(e.blockId)===t&&!e.isSimple())return d(nr,e.childContainerId,"block position must have childContainerId attribute"),e;const r=eE(n,t,e.blockId),i=U(Cs(r));return wt(t,i)}function Th(n,t){const e=n.selection.range,o=Gn(n,t,e.start),r=Gn(n,t,e.end);return an(t,o,r)}function k5(n,t,e,o){d(nr,Ht(t),"invalid table block");const r=xn(n,t),i=()=>{const l=r.querySelector(".table-border-bar-container.top");d(nr,l,"no top border bar container"),l.querySelectorAll(".table-border-bar-cell.top").forEach(a=>{const u=parseInt(a.getAttribute("data-top-index")||"0",10);o.includes(u)?A(a,"danger"):z(a,"danger")})},s=()=>{const l=r.querySelector(".table-border-bar-container.left");d(nr,l,"no left border bar container"),l.querySelectorAll(".table-border-bar-cell.left").forEach(a=>{const u=parseInt(a.getAttribute("data-left-index")||"0",10);e.includes(u)?A(a,"danger"):z(a,"danger")})};i(),s()}function Vr(n,t,e=!0,o){const i=et.fromBlock(t).map(u=>u),{fromCol:s,toCol:l,fromRow:c,toRow:a}=Th(n,t);for(let u=0;u<i.length;u++){const f=i[u];for(let m=0;m<f.length;m++){const C=f[m],v=o?m>=s&&m+C.colSpan-1<=l:u>=c&&u+C.rowSpan-1<=a;e&&v?C.virtual||A(C.cell,"danger"):C.virtual||z(C.cell,"danger")}}}function qr(n,t,e=!0,o){const r=new Set,i=new Set;if(!e){k5(n,t,Array.from(r),Array.from(i));return}const{fromCol:s,toCol:l,fromRow:c,toRow:a}=Th(n,t);if(o)for(let u=s;u<=l;u++)i.add(u);else for(let u=c;u<=a;u++)r.add(u);k5(n,t,Array.from(r),Array.from(i))}function y5(n,t,e){const{fromCol:o,toCol:r,fromRow:i,toRow:s}=Th(n,t),l=et.fromBlock(t);let c=null,a=null;return e?(c=l.getCell({col:o,row:0}),a=l.getCell({col:r,row:l.rowCount-1}),Wt(n,{anchor:wt(t,c.containerId,{colIndex:o,rowIndex:0}),focus:wt(t,a.containerId,{colIndex:r,rowIndex:l.rowCount-1})})):(c=l.getCell({col:0,row:i}),a=l.getCell({col:l.colCount-1,row:s}),Wt(n,{anchor:wt(t,c.containerId,{colIndex:0,rowIndex:i}),focus:wt(t,a.containerId,{colIndex:l.colCount-1,rowIndex:s})}))}function nE(n,t){const e=n.selection.range,o=Gn(n,t,e.start),r=Gn(n,t,e.end);return xh(n,t,o,r)}const w5=["style-bg-color-0","style-bg-color-1","style-bg-color-2","style-bg-color-3","style-bg-color-4","style-bg-color-5","style-bg-color-6","style-bg-color-7","style-bg-color-8","style-bg-color-9","style-bg-color-10","style-bg-color-11","style-bg-color-12","style-bg-color-13"];function B5(n){return`style-bg-color-${n}`}function ks(n){return`${n}_background`}function oE(n,t,e){const o=jt(n),s=(e!=null?e:et.fromTable(o)).getCell(t).cell;for(let l=0;l<w5.length;l++){const c=w5[l];if(nt(s,c))return c}}function E5(n,t,e){if(!n.isBlockWritable(t))return;const o=n.selection.range,i={...Y.default(n.getBlockData(t))},s=Gn(n,t,o.start),l=Gn(n,t,o.end);if(o.isSimple()){const c=s.childContainerId;e===-1?i[ks(c)]=void 0:i[ks(c)]=B5(e)}else{const c=et.fromBlock(t),a=an(t,s,l),u=new Set;for(let f=a.fromRow;f<=a.toRow;f++)for(let m=a.fromCol;m<=a.toCol;m++){const C=c.getCell({row:f,col:m});!u.has(C.containerId)&&C.col>=a.fromCol&&C.row>=a.fromRow&&C.col+C.colSpan-1<=a.toCol&&C.row+C.rowSpan-1<=a.toRow&&(u.add(C.containerId),e===-1?i[ks(C.containerId)]=void 0:i[ks(C.containerId)]=B5(e))}}n.updateBlockData(t,i)}function rE(n,t,e){if(!n.isBlockWritable(t))return;const r={...Y.default(n.getBlockData(t)),chart:e};n.updateBlockData(t,r)}const I5=w("table-chart");function iE(n,t){const e=xn(n,t);if(e){const o=e.querySelector(".editor-table-chart");if(o){const r=o.chartObject;r&&r.destroy(),o.remove()}}}async function sE(n,t){if(!n.isBlockWritable(t))return;if(!!!n.getBlockData(t).chart){iE(n,t);return}const r=[],i=et.fromBlock(t),s=["line","bar","pie","radar"];let l=i.getCell({row:0,col:0}).container.innerText.trim().toLowerCase();new Set(s).has(l)||(l=s[0]);const c=[];for(let B=1;B<i.colCount;B++)c.push(i.getCell({row:0,col:B}).container.innerText);for(let B=1;B<i.rowCount;B++){const y=i.getCell({row:B,col:0}),I=y.container.innerText,M=[];for(let se=1;se<i.colCount;se++){const eo=i.getCell({row:B,col:se}).container.innerText,ee=Number.parseFloat(eo)||0;M.push(ee)}let R;const $=oE(t,y,i);$?R=window.getComputedStyle(n.rootElement).getPropertyValue(`--${$}`).trim():R=window.getComputedStyle(n.rootElement).getPropertyValue("--background-color").trim();let[Z,ot,st,mt]=R?Wa.fromString(R).toRgbaArray():[];if(!Z&&!ot&&!st&&!mt){const se=(B-1)%n.options.colors.length;R=n.options.colors[se],[Z,ot,st,mt]=Wa.fromString(R).toRgbaArray()}const ut=R,yt=Wa.fromRgba([Z,ot,st,mt/3]).toHexString();r.push({label:I,data:M,borderColor:ut,backgroundColor:yt,borderWidth:2})}const a=xn(n,t);let u=null,f=a.querySelector(".editor-table-chart");f?u=f.chartObject:f=b("div",["editor-table-chart"],a);const m=f;d(I5,m,"no chart container");const C=n.getComponentOptions("table"),v=(C==null?void 0:C.chartCdn)||"https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js";try{await Ro(v,"editor-chartjs"),u&&l!==u.config.type&&(u.destroy(),u=null,Array.from(f.querySelectorAll(".editor-chartjs-canvas")).forEach(S=>{S.remove()}));const B=Ga.default({},{type:l,data:{datasets:r,labels:c},options:{onClick:()=>{n.selection.selectBlock(t,0,0)}}});if(u)Ga.default(u.config,B),u.update();else{const S=b("canvas",["editor-chartjs-canvas"],m).getContext("2d");u=new window.Chart(S,B),f.chartObject=u}}catch(B){I5.error(`failed to resolve chart cdn: ${JSON.stringify(B)}`)}}async function x5(n,t){await qe.lock("updateTableChart");try{await sE(n,t)}finally{qe.release("updateTableChart")}}const T5=Xt.default(x5,1e3);let S5=null;function Sh(n,t,e){if(S5!==t&&(T5.flush(),S5=t),e.updateNow){x5(n,t);return}T5(n,t)}function Dh(n,t){Ht(t)&&Sh(n,t,{updateNow:!1})}function lE(n,t){Ht(t)&&Sh(n,t,{updateNow:!0})}const je={SCROLL:"container-scroll-tool",COMMON:"container-border-shadow",RIGHT:"container-right-border-shadow",LEFT:"container-left-border-shadow",LAYOUT_SIGN:"container-layout-border-shadow",ACTIVE:"active"},Bc={SCROLL_BAR:"container-scrollbar",FIXED:"fixed"},bo={SCROLL_CONTAINER:"scroll-container",TOOL:"container-scroll-tool",CONTAINER:"scroll-container-root",MAC:"mac",SCROLL_AREA:"scroll-area"};function Ec(n,t){return n.containers.get(t)}function D5(n){return n.closest(`.${bo.SCROLL_CONTAINER}`)}function dn(n){return n.firstElementChild}function Ae(n){return n.closest(`.${bo.CONTAINER}`)}function ys(n){const t=Ae(n);let e=t.querySelector(`:scope >.${bo.TOOL}`);return e||(e=b("div",[bo.TOOL],t)),e}function cE(n){return Ae(n).firstElementChild}function Ic(n){let t;return n instanceof HTMLElement?t=n.offsetWidth:t=Number.parseInt(getComputedStyle(n).width,10),n.getBoundingClientRect().width/t}function He(n,t){const e=Ic(n);return t/e}function ws(n){const t=window.getComputedStyle(n),e=Ic(n);return{paddingBottom:parseFloat(t.paddingBottom)*e,paddingTop:parseFloat(t.paddingTop)*e,paddingLeft:parseFloat(t.paddingLeft)*e,paddingRight:parseFloat(t.paddingRight)*e}}function Wr(n){const t=Ic(n);return{scrollLeft:n.scrollLeft*t,scrollWidth:n.scrollWidth*t,clientWidth:n.clientWidth*t,clientHeight:n.clientHeight*t}}function aE(n,t){const e=Ic(n);return n[t]*e}function Lh(n,t){const e=Ae(t),o=Ec(n,e),r=(o==null?void 0:o.safeRightSpace)||0,i=(o==null?void 0:o.safeLeftSpace)||0,l=(o==null?void 0:o.locatingContainer).getBoundingClientRect(),c=e.getBoundingClientRect(),a=c.width;let u=Math.floor(c.left-l.left-i);u<0&&(u=0);let f=l.right;f-=r;let m=f-c.right;return m<0&&(m=0),u=Math.round(u),m=Math.round(m),{originWidth:a,maxLeft:u,maxRight:m}}function dE(n,t){const e=Lh(n,t),{maxLeft:o}=e;t.style.marginLeft=`${He(t,0-o)}px`,t.style.paddingLeft=`${He(t,o)}px`}function uE(n,t){const e=Lh(n,t);t.style.marginRight=`${He(t,0-e.maxRight)}px`}function hE(n){if(n!==document.documentElement&&n!==document.body)return n.getBoundingClientRect();const t=0,e=0,o=document.documentElement.clientWidth,r=document.documentElement.clientHeight;return new DOMRect(t,e,o,r)}const L5=w("scroll-bar-handle"),fE=2;function Gr(n){const t=ys(n);let e=t.querySelector(`.${Bc.SCROLL_BAR}`);return e||(e=b("div",[Bc.SCROLL_BAR],t)),d(L5,e instanceof HTMLDivElement,"invalid child for container tools"),e.firstElementChild||b("div",[],e),e}function xc(n,t){const e=D5(t),o=Gr(e),{scrollWidth:r,clientWidth:i}=Wr(e),{paddingLeft:s,paddingRight:l}=ws(t);e.style.marginLeft="",e.style.paddingLeft="",e.style.marginRight="";const c=Lh(n,e),{originWidth:a,maxRight:u}=c;uE(n,e),dE(n,e);const f=r-i;d(L5,o.firstElementChild instanceof HTMLDivElement,"invalid child for scroll bar"),o.style.width=`${He(e,a+u-s-l)}px`,o.firstElementChild.style.width=`${He(e,a+u+f-s-l)}px`}function mE(n,t){const e=dn(n),{paddingLeft:o}=ws(e);if(nt(t,"fixed")){const i=Ae(n).getBoundingClientRect();t.style.left=`${He(n,i.left+o)}px`}else t.style.left=`${He(n,o)}px`}function Zr(n,t){var I;const e=n.getParentScrollContainer(),o=hE(e),r=t.getBoundingClientRect(),i=Gr(t),s=i.getBoundingClientRect(),l=Ec(n,Ae(t)),c=(l==null?void 0:l.barFloatWindowBottom)||0,a=dn(t),{paddingTop:u,paddingBottom:f}=ws(a),{scrollWidth:m,clientWidth:C}=Wr(t),v=document.documentElement.clientHeight-c,B=o.top+Wr(e).clientHeight-v,y=v+Math.min(0,B);if(m>C&&r.top+u<y-s.height&&r.bottom>y-s.height+f&&!((I=l==null?void 0:l.isSetScale)!=null&&I.call(l))){A(i,Bc.FIXED);const M=B>0?c:0;i.style.bottom=`${Math.max(document.documentElement.clientHeight-o.bottom,0)+fE+M}px`}else z(i,Bc.FIXED),i.style.bottom=`${He(t,f-s.height)}px`;mE(t,i)}class gE{constructor(t,e){h(this,"intersectionObserver");h(this,"handleIntersection",t=>{t.forEach(e=>{this.containers.get(Ae(e.target))?(this.handleIntersectionEntry(e),this.callback(e)):this.intersectionObserver.unobserve(e.target)})});h(this,"handleIntersectionEntry",t=>{const e=t.target;Zr(this.scrollCore,e);const o=dn(e);xc(this.scrollCore,o)});this.scrollCore=t,this.callback=e;const r={root:this.scrollCore.getParentScrollContainer(),rootMargin:"20px",threshold:0};this.intersectionObserver=new IntersectionObserver(this.handleIntersection,r)}get containers(){return this.scrollCore.containers}bind(t){this.unbind(t),this.intersectionObserver.observe(t)}unbind(t){this.intersectionObserver.unobserve(t)}destroy(){this.intersectionObserver.disconnect()}}const or=w("container-scroll-shadow");function M5(n,t,e){const o=n,r=t.getBoundingClientRect(),i=e.getBoundingClientRect(),{paddingTop:s,paddingBottom:l}=ws(e);o.style.top=`${He(t,i.top-r.top+s)}px`,o.style.bottom=`${He(t,r.bottom-i.bottom+l)}px`}function R5(n,t){const e=n;t<24?e.style.width=`${(t/3).toFixed(2)}px`:e.style.width=""}function pE(n){const t=ys(n);d(or,t,"no container tools");let e=t.querySelector(`.${je.LEFT}`);if(!e){const l=dn(n),c=[je.COMMON,je.LEFT];e=b("div",c,t),d(or,e instanceof HTMLDivElement,"invalid child for container tools"),M5(e,n,l)}d(or,e instanceof HTMLElement,"invalid child for container tools");const r=Ae(n).getBoundingClientRect(),i=n.getBoundingClientRect();e.style.left=`${He(n,i.left-r.left)}px`;const s=Wr(n).scrollLeft;d(or,e instanceof HTMLDivElement,"invalid child for container tools"),R5(e,s),A(e,je.ACTIVE)}function CE(n){const t=ys(n);let e=t.querySelector(`.${je.RIGHT}`);if(!e){const u=dn(n),f=[je.COMMON,je.RIGHT];e=b("div",f,t),d(or,e instanceof HTMLDivElement,"no div, create shadow failed"),M5(e,n,u)}d(or,e instanceof HTMLElement,"");const r=Ae(n).getBoundingClientRect(),i=n.getBoundingClientRect();e.style.right=`${He(n,r.right-i.right)}px`;const{scrollWidth:s,scrollLeft:l,clientWidth:c}=Wr(n),a=s-l-c;d(or,e instanceof HTMLDivElement,"no shadow element"),R5(e,a),A(e,je.ACTIVE)}function bE(n){const e=ys(n).querySelector(`.${je.LEFT}`);e&&z(e,je.ACTIVE)}function vE(n){const e=ys(n).querySelector(`.${je.RIGHT}`);e&&z(e,je.ACTIVE)}function Bs(n){const{scrollLeft:t,scrollWidth:e,clientWidth:o}=Wr(n),r=dn(n),{paddingLeft:i,paddingRight:s}=ws(r),l=aE(r,"offsetLeft");e-i<=o-s||e-i<=t+o-s?vE(n):CE(n),r&&t>=l+i?pE(n):bE(n)}class kE{constructor(t,e){h(this,"resizeObserver");h(this,"handleResizeEntry",t=>{const e=t.target,o=dn(e);Bs(e),xc(this.scrollCore,o),Zr(this.scrollCore,e),this.callback(e)});h(this,"handleContentResize",t=>{t.forEach(e=>{this.containers.get(Ae(e.target))?this.handleResizeEntry(e):this.unbind(e.target)})});this.scrollCore=t,this.callback=e,this.resizeObserver=new ResizeObserver(this.handleContentResize)}get containers(){return this.scrollCore.containers}bind(t){this.unbind(t),this.resizeObserver.observe(t)}unbind(t){this.resizeObserver.unobserve(t)}destroy(){this.resizeObserver.disconnect()}}const A5=w("container-scroll-observer");class yE{constructor(t,e){h(this,"handleContentScroll",t=>{const e=t.target;d(A5,e instanceof Element,"invalid target for scroll event");const o=Gr(e);o.removeEventListener("scroll",this.handleScroll);const r=!0;this.fixScrollXPos(e,e.scrollLeft,r),this.bind(o),Bs(e),this.callback(e)});h(this,"handleScroll",t=>{const e=t.target;d(A5,e instanceof HTMLElement,"");const o=e.scrollLeft,r=!1,i=cE(e);this.unbindContentScroll(i),this.fixScrollXPos(i,o,r),this.bindContentScroll(i),Bs(i),this.callback(i)});h(this,"handlePrevent",t=>{t.stopPropagation()});h(this,"bindContentScrollCore",t=>{this.unbindContentScroll(t),t.addEventListener("scroll",this.handleContentScroll)});h(this,"unbindContentScroll",t=>{t.removeEventListener("scroll",this.handleContentScroll)});h(this,"bindContentScroll",Xt.default(this.bindContentScrollCore,300));h(this,"bind",Xt.default(this.bindCore,200));this.scrollCore=t,this.callback=e}fixScrollXPos(t,e,o){const r=Gr(t);o||(t.scrollLeft=e),o&&r.scrollLeft!==e&&(r.scrollLeft=e)}bindCore(t){this.unbind(t),t.addEventListener("scroll",this.handleScroll),t.addEventListener("mousedown",this.handlePrevent)}unbind(t){t.removeEventListener("scroll",this.handleScroll),t.removeEventListener("mousedown",this.handlePrevent)}}class wE{constructor(t){h(this,"scrollContainers",new Set);h(this,"handleParentContainerScroll",()=>{this.scrollContainers.forEach(t=>{Zr(this.scrollCore,t)})});h(this,"bindScrollContainer",t=>{const e=this.scrollContainers.size===0;this.scrollContainers.add(t),e&&this.eventTarget.addEventListener("scroll",this.handleParentContainerScroll)});h(this,"unbindScrollContainer",t=>{let e=!1;this.scrollContainers.has(t)&&(this.scrollContainers.delete(t),e=this.scrollContainers.size===0),e&&this.eventTarget.removeEventListener("scroll",this.handleParentContainerScroll)});this.scrollCore=t}get eventTarget(){const t=this.scrollCore.getParentScrollContainer();return t===document.documentElement?document:t}destroy(){this.eventTarget.removeEventListener("scroll",this.handleParentContainerScroll),this.scrollContainers.clear()}}const BE=w("scroll-wrap-resize-observer");class EE{constructor(t){h(this,"resizeObserver");h(this,"handleScrollWrapResize",t=>{t.forEach(e=>{this.containers.get(Ae(e.target))?this.handleScrollWrapResizeEntry(e):this.unbind(e.target)})});h(this,"handleScrollWrapResizeEntry",t=>{const e=t.target;d(BE,e instanceof HTMLElement,"invalid target for observer entry");const o=D5(e);xc(this.scrollCore,e),Bs(o),Zr(this.scrollCore,o)});this.scrollCore=t,this.resizeObserver=new ResizeObserver(this.handleScrollWrapResize)}get containers(){return this.scrollCore.containers}bind(t){this.unbind(t),this.resizeObserver.observe(t)}unbind(t){this.resizeObserver.unobserve(t)}destroy(){this.resizeObserver.disconnect()}}class IE{constructor(t,e){h(this,"resizeObserver");h(this,"scrollContainersMap",new Map);h(this,"handleResizeEntry",t=>{t==null||t.forEach(e=>{const o=dn(e);Bs(e),xc(this.scrollCore,o),Zr(this.scrollCore,e),this.callback(e)})});h(this,"handleResize",t=>{t.forEach(e=>{const o=this.scrollContainersMap.get(e.target);o!=null&&o.length&&this.handleResizeEntry(o)})});this.scrollCore=t,this.callback=e,this.resizeObserver=new ResizeObserver(this.handleResize)}bind(t){var r,i;const e=Ae(t),o=(r=Ec(this.scrollCore,e))==null?void 0:r.locatingContainer;this.scrollContainersMap.has(o)?(i=this.scrollContainersMap.get(o))==null||i.push(t):(this.scrollContainersMap.set(o,[t]),this.resizeObserver.observe(o))}unbind(t){var i,s;const e=Ae(t),o=(i=Ec(this.scrollCore,e))==null?void 0:i.locatingContainer;if(!o)return;const r=this.scrollContainersMap.get(o);this.scrollContainersMap.set(o,(r==null?void 0:r.filter(l=>l!==t))||[]),(s=this.scrollContainersMap.get(o))!=null&&s.length||(this.resizeObserver.unobserve(o),this.scrollContainersMap.delete(o))}destroy(){this.scrollContainersMap.clear(),this.resizeObserver.disconnect()}}const uz="";class xE extends Yt.TypedEmitter{constructor(e){super();h(this,"containerIntersectionObserver",null);h(this,"containerResizeObserver",null);h(this,"containerScrollObserver",null);h(this,"parentContainerScrollObserver",null);h(this,"scrollWrapResizeObserve",null);h(this,"locatingContainerResizeObserver",null);h(this,"isWindowEventBind",!1);h(this,"containers",new Map);h(this,"handleScrollContainerScroll",e=>{this.emit("scroll",this,e)});h(this,"handleResize",e=>{this.emit("resize",this,e)});h(this,"handleIntersection",e=>{const o=e.target,r=dn(o);e.isIntersecting?(this.load(),this.bindCore(o,r)):this.unbindCore(o,r)});h(this,"handleWindowEffect",()=>{var e;(e=this.getScrollContainerInViewable())==null||e.forEach(o=>{Zr(this,o)})});this.parentContainer=e}load(){this.containerResizeObserver||(this.containerResizeObserver=new kE(this,this.handleResize)),this.containerScrollObserver||(this.containerScrollObserver=new yE(this,this.handleScrollContainerScroll)),this.parentContainerScrollObserver||(this.parentContainerScrollObserver=new wE(this)),this.scrollWrapResizeObserve||(this.scrollWrapResizeObserve=new EE(this)),this.locatingContainerResizeObserver||(this.locatingContainerResizeObserver=new IE(this,this.handleResize)),this.isWindowEventBind||(window.addEventListener("resize",this.handleWindowEffect),this.getParentScrollContainer()!==document.documentElement&&window.addEventListener("scroll",this.handleWindowEffect))}getParentScrollContainer(){return this.parentContainer}getScrollContainerInViewable(){var e;return(e=this.parentContainerScrollObserver)==null?void 0:e.scrollContainers}unbindCore(e,o){var i,s,l,c,a,u;const r=Gr(e);(i=this.containerScrollObserver)==null||i.unbindContentScroll(e),(s=this.containerScrollObserver)==null||s.unbind(r),(l=this.scrollWrapResizeObserve)==null||l.unbind(o),(c=this.containerResizeObserver)==null||c.unbind(e),(a=this.parentContainerScrollObserver)==null||a.unbindScrollContainer(e),(u=this.locatingContainerResizeObserver)==null||u.unbind(e)}bindCore(e,o){var i,s,l,c,a,u;if(this.unbindCore(e,o),!e.closest("body"))return;const r=Gr(e);(i=this.containerScrollObserver)==null||i.bindContentScrollCore(e),(s=this.containerScrollObserver)==null||s.bindCore(r),(l=this.scrollWrapResizeObserve)==null||l.bind(o),(c=this.containerResizeObserver)==null||c.bind(e),(a=this.parentContainerScrollObserver)==null||a.bindScrollContainer(e),(u=this.locatingContainerResizeObserver)==null||u.bind(e)}bind(e,o){this.containers.set(e,o);const r=e.firstElementChild;this.containerIntersectionObserver||(this.containerIntersectionObserver=new gE(this,this.handleIntersection)),this.containerIntersectionObserver.bind(r)}unbind(e){var i;const o=e.firstElementChild,r=dn(o);this.unbindCore(o,r),this.containers.delete(e),(i=this.containerIntersectionObserver)==null||i.unbind(o),this.containers.size||this.destroy()}destroy(){var e,o,r,i,s;this.containers.forEach((l,c)=>{this.unbind(c)}),this.containers.clear(),(e=this.parentContainerScrollObserver)==null||e.destroy(),(o=this.containerIntersectionObserver)==null||o.destroy(),(r=this.containerResizeObserver)==null||r.destroy(),(i=this.scrollWrapResizeObserve)==null||i.destroy(),(s=this.locatingContainerResizeObserver)==null||s.destroy(),window.removeEventListener("resize",this.handleWindowEffect),window.removeEventListener("scroll",this.handleWindowEffect)}}const O5=w("scroll-container"),Tc=new Map;class TE extends Yt.TypedEmitter{constructor(){super(...arguments);h(this,"scrollListener");h(this,"options");h(this,"scrollContainerElement");h(this,"init",e=>{this.options=e;const o=b("div",[bo.CONTAINER],e.parentElement);xt.isMac&&A(o,bo.MAC);const r=b("div",[bo.SCROLL_CONTAINER],o),i=b("div",[bo.SCROLL_AREA],r);i.style.paddingLeft=e.paddingLeft?`${e.paddingLeft}px`:"",i.style.paddingTop=e.paddingTop?`${e.paddingTop}px`:"",i.style.paddingBottom=e.paddingBottom?`${e.paddingBottom}px`:"",i.style.paddingRight=e.paddingRight?`${e.paddingRight}px`:"",i.appendChild(e.childElement);const s=e.parentContainer;this.scrollListener=Tc.get(s),this.scrollListener||(this.scrollListener=new xE(s),Tc.set(s,this.scrollListener)),this.scrollListener.unbind(o),this.scrollListener.bind(o,e),this.scrollListener.on("scroll",this.handleContainerScroll),this.scrollListener.on("resize",this.handleResize),this.scrollContainerElement=r});h(this,"handleContainerScroll",(e,o)=>{o===this.scrollContainerElement&&this.emit("scroll",this)});h(this,"handleResize",(e,o)=>{o===this.scrollContainerElement&&this.emit("scroll",this)})}get rootElement(){return this.scrollContainerElement}get contentElement(){return d(O5,this.scrollContainerElement,"scrollContainerElement cannot be undefined"),dn(this.scrollContainerElement)}get scrollOptions(){return d(O5,this.options,"options cannot be undefined"),{...this.options}}handleBaseListenerDestroy(e){e.destroy()}destroy(){var o;(o=this.scrollListener)==null||o.off("scroll",this.handleContainerScroll);const e=Ae(this.contentElement);e&&Tc.forEach((r,i)=>{r.unbind(e),r.containers.size===0&&(this.handleBaseListenerDestroy(r),Tc.delete(i))})}}function SE(){return new TE}const Sc=100,DE=40,Mh=w("column-width");function LE(n,t,e){_B(n,t).style.width=`${e}px`}function ME(n){const e=Array.from(n.querySelector("colgroup").children).map(c=>c.getBoundingClientRect().width);if(e[0]!==0)return e;const o=et.fromTable(n),r=Array(o.colCount).fill(-1),i=n.getBoundingClientRect().left;o.toRealCells(o.cells).forEach(c=>{const a=c.col+c.colSpan-1;r[a]===-1&&(r[a]=c.cell.getBoundingClientRect().right-i)}),Mh.debug(`cellRightOffsets1: ${r.join()}`);for(let c=0;c<r.length;c++){const a=r[c];if(a===-1||c===0)continue;let u=c-1;for(;r[u]===-1&&(u--,u!==-1););const f=u===-1?0:r[u],C=(a-f)/(c-u);for(let v=u+1;v<c;v++)r[v]=f+C*(v-u)}Mh.debug(`cellRightOffsets2: ${r.join()}`);const s=[];let l=0;for(let c=0;c<r.length;c++){const a=r[c];s.push(a-l),l=a}return Mh.debug(`widths: ${s.join()}`),s}function Es(n){return Array.from(n.querySelector("colgroup").children).map(o=>o.getBoundingClientRect().width||Number.parseInt(o.style.width,10)||100)}const RE=w("table-resize-gripper"),_5=7,Rh=(_5-1)/2,AE=3;function OE(n,t,e){const{rows:o}=n;for(let r=0;r<o.length;r++){const i=o[r],s=Array.from(i.cells);for(let l=0;l<s.length;l++){const c=s[l],a=c.getBoundingClientRect(),u=Math.round(a.right);if(Math.abs(t-u)<=Rh&&a.top<=e&&e<=a.bottom)return c}}return null}function _E(n){return!!n.rootContainer.querySelector(".table-resize-gripper")}function Ah(n,t){return xn(n,t).querySelector(".table-resize-gripper")}function N5(n,t){const e=Ah(n,t);d(RE,!e,"resize gripper has already exists");const o=xn(n,t),r=b("div",["table-resize-gripper","table-indicator"],o);return b("div",["table-resize-gripper-indicator"],r),r}function $5(n,t,e){let o=Ah(n,t);o||(o=N5(n,t));const i=jt(t).getBoundingClientRect(),s=e.getBoundingClientRect(),l=0,c=i.height,a=n.getCustom(Co(t)).contentElement.getBoundingClientRect(),u=s.right-a.left;o.style.left=`${u-Rh-Eh-vs}px`,o.style.top=`${l}px`,o.style.height=`${c}px`,o.style.width=`${_5}px`}function Oh(n){n.rootContainer.querySelectorAll(".table-resize-gripper").forEach(t=>{t.remove()})}function NE(n,t,e){const r={...n.getBlockData(t),colsWidth:e};n.updateBlockData(t,r)}function $E(n,t,e,o){const r=t,i=et.fromTable(e),s=i.getCellByCellElement(r),l=s.col+s.colSpan-1,c=Es(e);let a=o;const u=(m,C)=>{const v=C+1,B=m.col+m.colSpan;return c.slice(v,B).reduce((S,I)=>S+I,0)},f=new Set;for(let m=0;m<i.rowCount;m++){const C=i.getCell({row:m,col:l});if(f.has(C.cell))continue;f.add(C.cell);const v=C.cell,B=v.getBoundingClientRect();let y=o-B.left+Rh-AE;const S=Cs(v),I=wd(n,S)||DE*C.colSpan,M=u(C,l),R=I-M;y<R&&(y=R);const $=B.left+y;a=Math.max(a,$)}return a}const PE=w("table-resize-drag-drop");class jE{constructor(t,e,o,r){h(this,"cursor","col-resize");this.editor=t,this.elem=e,this.data=o,this.onEnd=r}onDragStart(t,e,o){}onDragging(t,e,o,r,i){const{table:s,block:l,draggingRefCell:c}=t.data,u=$E(this.editor,c,s,e.x-t.dragOffsetX)-s.getBoundingClientRect().left;d(PE,c,"no dragging cell");const m=et.fromTable(s).getCellByCellElement(c),C=m.col+m.colSpan-1,B=Es(s).slice(0,C).reduce((S,I)=>S+I,0),y=u-B;LE(s,C,y),$5(this.editor,l,c),this.editor.selection.caret.update()}onDragEnd(t,e,o,r,i){const s=Es(t.data.table);NE(this.editor,t.data.block,s),Oh(this.editor),this.onEnd&&(this.onEnd(e),this.onEnd=null)}}function HE(n,t){const e=document.elementFromPoint(t.x,t.y);if(!e)return null;const o=F(e);return!o||!n.contains(o)||!Ht(o)?null:o}w("table-resize");class FE{constructor(t){h(this,"draggingRefCell",null);h(this,"handleMouseMove",(t,e)=>{if(t.readonly||t.selectionHandler.isSelecting()&&!this.draggingRefCell||this.draggingRefCell)return;const o=e.target;if(!(o instanceof Element)||o.closest(".table-indicator"))return;const i=e,s=HE(t,i);if(!s||!h5(s)){Oh(t);return}this.updateGripper(s,i.x,i.y)});this.editor=t,t.domEvents.addEventListener(document,"mousemove",this.handleMouseMove)}destroy(){this.editor.domEvents.removeEventListener(document,"mousemove",this.handleMouseMove)}updateGripper(t,e,o){const r=jt(t),i=OE(r,e,o);if(i){if(!Ah(this.editor,t)){if(_E(this.editor))return;const l=N5(this.editor,t),c={block:t,table:r,draggingRefCell:i};ed(new jE(this.editor,l,c,a=>{this.updateGripper(t,a.x,a.y)}))}$5(this.editor,t,i)}else Oh(this.editor)}}function P5(n){n.addCustom("table-mouse-event-handler",t=>new FE(t))}const j5=w("table-insert-column");function H5(n,t,e){const o=jt(t),r=et.fromTable(o),i=r.colCount;d(j5,e>=0&&e<=i,`insert index ${e} is out of range [0, ${i}]`);const s=r.map(m=>m.containerId),l=new Set;n.doc.beginBatchUpdate();for(let m=0;m<s.length;m++){const C=s[m],v=C[e-1],B=C[e];if(e===0||e===C.length||v!==B){const y=yn(n.doc);C.splice(e,0,y)}else C.splice(e,0,v),l.add(v)}n.doc.endBatchUpdate();const c=Y.default(n.getBlockData(t));l.forEach(m=>{const C=`${m}_colSpan`,v=c[C];d(j5,typeof v=="number"&&v>1,`no colSpan for containerId ${m}, ${v}`),c[C]=v+1});const a=c.colsWidth.concat();a.splice(e,0,Sc);const u=et.virtualCellContainersGridToChildren(s),f={...c,cols:c.cols+1,children:u,colsWidth:a};er(f),n.updateBlockData(t,f)}const Dc=w("table-insert-row");function F5(n,t,e){const o=jt(t),r=et.fromTable(o),i=r.rowCount;d(Dc,e>=0&&e<=i,`insert index ${e} is out of range [0, ${i}]`);const s=r.map(m=>m.containerId),l=new Set;n.doc.beginBatchUpdate();const c=[];for(let m=0;m<r.colCount;m++){const C=e>0&&s[e-1][m],v=e<r.rowCount&&s[e][m];if(d(Dc,C||v,"no top and bottom cell"),e===0||e===r.rowCount||C!==v){const B=yn(n.doc);c.push(B)}else d(Dc,C,"no top cell"),c.push(C),l.add(C)}n.doc.endBatchUpdate(),s.splice(e,0,c);const a=Y.default(n.getBlockData(t));l.forEach(m=>{const C=`${m}_rowSpan`,v=a[C];d(Dc,typeof v=="number"&&v>1,`no rowSpan for containerId ${m}, ${v}`),a[C]=v+1});const u=et.virtualCellContainersGridToChildren(s),f={...a,rows:a.rows+1,children:u};er(f),n.updateBlockData(t,f)}const _h=w("paste-table-in-table-block");function zE(n,t,e,o){let r=et.fromBlock(e);const i=t.blocks.root[0];d(_h,i,"no table data"),d(_h,i.type==="table",`table data type is not table, but ${i.type}`);const s=i,l=r.getCellByCellElement(o),c=s.cols,a=s.rows,u=l.col,f=l.row,m=u+c,C=f+a,v=[];for(let B=u;B<m&&B<r.colCount;B++)for(let y=f;y<C&&y<r.rowCount;y++){const S=r.getCell({col:B,row:y});S.virtual?S.virtual&&v.push({col:B,row:y}):(S.colSpan>1||S.rowSpan>1)&&v.push({col:B,row:y})}n.undoManager.runInGroup(()=>{if(v.forEach(I=>{const M=et.fromBlock(e).getCell(I);(M.colSpan>1||M.rowSpan>1)&&kh(n,e,I)}),m>r.colCount)for(let I=r.colCount;I<m;I++)H5(n,e,I);if(C>r.rowCount)for(let I=r.rowCount;I<C;I++)F5(n,e,I);r=et.fromBlock(e);const B=new vc(s);let y;for(let I=0;I<B.colCount;I++)for(let M=0;M<B.rowCount;M++){const R=B.getCell({col:I,row:M});if(!R.virtual){const $=hu(n.editorBlocks,t,R.containerId),Z=u+I,ot=f+M,st={col:Z,row:ot},mt=r.getCellContainer(st);Hp(n,mt,$),y=mt}}d(_h,y,"no last container");const S=Qt(y);n.selection.selectBlock(S,W(n,S))})}const z5=w("paste-in-table-block");class UE{constructor(t){this.editor=t,setTimeout(()=>{t.input.addHandler(this)})}destroy(){}async handleBeforePasteDoc(t,e){if(!t.selection.range.isSimple()||t.selection.range.start.offset!==0)return!1;const r=t.selection.startBlock,i=H(r);if(pt(i)||!Bd(t,i))return!1;const s=F(i);if(d(z5,s,"no parent block"),!Ht(s)||e.blocks.root.length!==1||e.blocks.root[0].type!=="table")return!1;z5.debug("paste child table in table");const a=et.fromBlock(s).getCellByContainerId(U(i)).cell;return zE(t,e,s,a),!0}}function U5(n){n.addCustom("table-block-paste-event",t=>new UE(t))}const Nh=w("table-select-columns");function VE(n,t,e,o,r){d(Nh,Ht(t),"is not a table block");const i=et.fromBlock(t);d(Nh,e>=0&&e<i.colCount,"invalid from"),d(Nh,o>0&&e+o<=i.colCount,"invalid count");const s=i.getCell({row:0,col:e}),l=i.getCell({row:i.rowCount-1,col:e+o-1}),c=wt(t,s.containerId,{colIndex:e,rowIndex:0}),a=wt(t,l.containerId,{colIndex:e+o-1,rowIndex:i.rowCount-1});r!=null&&r.reverse?n.selection.setSelection(a,c):n.selection.setSelection(c,a)}const $h=w("table-select-columns");function qE(n,t,e,o,r){d($h,Ht(t),"is not a table block");const i=et.fromBlock(t);d($h,e>=0&&e<i.rowCount,"invalid from"),d($h,o>0&&e+o<=i.rowCount,"invalid count");const s=i.getCell({row:e,col:0}),l=i.getCell({row:e+o-1,col:i.colCount-1}),c=wt(t,s.containerId,{rowIndex:e,colIndex:0}),a=wt(t,l.containerId,{rowIndex:e+o-1,colIndex:i.colCount-1});r!=null&&r.reverse?n.selection.setSelection(a,c):n.selection.setSelection(c,a)}const hz="",V5=w("get-toolbar-reference-client");function WE(n,t){const e=n.selection.range;if(!e.isSimple()){d(V5,e.start.blockId===e.end.blockId,"invalid selection range");const s=n.getBlockById(e.start.blockId);d(V5,at(n,s),"not a complex block");const l=bt(n,s);if(l.getTextToolbarReferenceClient){const c=l.getTextToolbarReferenceClient(n,s);if(c)return c}}const o=e.isReverse()?t.start:t.end,r=Wt(n,{anchor:o,focus:o}),i=Ho(n,t.block,r);if(i.length!==0)return i[0]}function GE(n){var t,e;if(n.children){let o=!1;const r=[];for(const i of n.children){if((t=i.states)!=null&&t.includes("checked")){o=!0;break}(e=n.defaultCheckedChildren)!=null&&e.includes(i.id)&&r.push(i)}if(!o&&(r==null?void 0:r.length))for(const i of r)Array.isArray(i.states)?i.states.push("checked"):i.states=["checked"]}}function Lc(n){const t=(r,i)=>{const s=r.findIndex(c=>c.id===i.id);if(s===-1){r.push(i);return}const l=r[s];if(l.value!==i.value&&delete l.value,!!l.states){if(!i.states){l.states=[];return}l.states=Za.default(l.states,i.states)}},e=[],o=new Map;return n.forEach(r=>{var i,s;(i=r.children)!=null&&i.length&&(o.has(r.id)?(s=o.get(r.id))==null||s.push(...r.children):o.set(r.id,[...r.children])),t(e,r)}),o.forEach((r,i)=>{const s=e.find(l=>l.id===i);s&&(s.children=Lc(r),GE(s))}),e}function Mc(n){return n.getCustom("toolbar-handler")}const fz="";class ZE{constructor(){h(this,"linkPopup",null);h(this,"form",{});h(this,"onFinished",null);h(this,"onClose",null);h(this,"handleOk",async()=>{var t;try{await this.checkValue();const{linkText:e,linkUrl:o}=this.form;(t=this.onFinished)==null||t.call(this,e.getInputValue()||o.getInputValue(),o.getInputValue()),this._destroy()}catch{}});h(this,"handleClose",()=>{var t;(t=this.onClose)==null||t.call(this),this._destroy()});h(this,"onShow",()=>{setTimeout(()=>{var t;(t=this.form.linkText)==null||t.getField().focus()},400)});h(this,"onChange",()=>{var e;const t=(e=this.linkPopup)==null?void 0:e.content.querySelector(".submit-button");t.disabled=!1});h(this,"handleTextKeyboard",t=>{var e;if(!t.isComposing){if(t.key==="Enter"){(e=this.form.linkUrl)==null||e.getField().focus(),t.stopPropagation();return}t.key==="Escape"&&this.handleClose()}});h(this,"handleUrlKeyboard",t=>{if(!t.isComposing){if(t.key==="Enter"){this.handleOk(),t.preventDefault();return}t.key==="Escape"&&this.handleClose()}})}async checkValue(){const{linkUrl:t}=this.form;if(!t.getInputValue())throw t.setFieldError(T.t("link.urlPlaceholder")),new Error(T.t("link.urlPlaceholder"))}editLink(t){var u,f;const{target:e,linkText:o,linkUrl:r,onFinished:i,onClose:s,placement:l="bottom-start"}=t;this.linkPopup=new ms(this.createPopupContent(o,r)),this.linkPopup.addListener("show",this.onShow),this.linkPopup.manualShow(e,{theme:"light",placement:l}),this.onFinished=i,s&&(this.onClose=s);const c=(u=this.linkPopup)==null?void 0:u.content.querySelector(".submit-button"),a=(f=this.linkPopup)==null?void 0:f.content.querySelector(".cancel-button");c==null||c.addEventListener("click",this.handleOk),a==null||a.addEventListener("click",this.handleClose)}createPopupContent(t,e){const o=b("div",["link-popup-content"],null);this.form.linkText=uh(o,{label:T.t("link.textLabel"),required:!1,placeholder:T.t("link.textPlaceholder"),defaultValue:t,onChange:this.onChange,onKeyDown:this.handleTextKeyboard}),this.form.linkUrl=uh(o,{className:"link-popup-gap",label:T.t("link.urlLabel"),required:!0,placeholder:T.t("link.urlPlaceholder"),defaultValue:e,onChange:this.onChange,onKeyDown:this.handleUrlKeyboard});const r=b("div",["link-popup-footer"],o);b("button",["cancel-button"],r,T.t("link.cancelText"));const i=b("button",["submit-button"],r,T.t("link.submitText"));return i.disabled=!0,o}_destroy(){var o,r,i,s;const t=(o=this.linkPopup)==null?void 0:o.content.querySelector(".submit-button"),e=(r=this.linkPopup)==null?void 0:r.content.querySelector(".cancel-button");t==null||t.removeEventListener("click",this.handleOk),e==null||e.removeEventListener("click",this.handleClose),this.onFinished=null,this.onClose=null,this.form={},(i=this.linkPopup)==null||i.removeAllListeners(),(s=this.linkPopup)==null||s.destroy()}destroy(){this._destroy()}}function Rc(n,t){n.addCustom("link-editor",()=>new ZE).editLink(t)}const YE=w("link-popup");function QE(n){return nt(n,"link")}function Ac(n){var t,e;return(e=(t=n.getAttribute("link"))!=null?t:n.textContent)!=null?e:""}function KE(n,t,e){var r,i,s,l;if(n.isBlockWritable(t)&&e&&_e(e)){const c=e,a=(i=(r=n.editorBoxes.getBoxClass(Ri(c))).getBoxProperties)==null?void 0:i.call(r,n,c);return a!=null&&a.boxCommands?(l=(s=a.boxCommands["hovering-toolbar"])==null?void 0:s.commands)!=null?l:[]:[]}return n.isWritable()&&e&&j(n,t)&&QE(e)?[{id:"link-text",name:Ac(e),disableTooltip:!0,element:b("span",["link-href-button"],null,Ac(e))},{id:"edit-link",name:"Edit",icon:ah},{id:"remove-link",name:"Remove link",icon:Vw}]:fg(n,t,"hovering-toolbar")}function JE(n,t,e){var c;const o=so(t,e);n.selection.selectBlock(t,o.start,o.end);const r=(c=e.textContent)!=null?c:"",i=Ac(e);Rc(n,{target:e,linkText:r,linkUrl:i,onFinished:(a,u)=>{try{const f=n.getBlockText(t),m=Hd(f,o.start,o.end-o.start),C=Sr(m,o.start,a,{link:u});n.setBlockText(t,C),n.selection.selectBlock(t,o.start+a.length),n.focus()}catch(f){YE.error(f)}},onClose:()=>{n.selection.selectBlock(t,o.end),n.focus()}})}function XE(n,t,e){const o=so(t,e),r=n.getBlockText(t),i=Ac(e),s=Dr(o.start,o.end-o.start,r,"link",i);n.setBlockText(t,s),n.selection.selectBlock(t,o.end)}function tI(n,t,e,o){var s,l,c;if(e){if(n.isBlockWritable(t)&&_e(e)){const u=e,f=(l=(s=n.editorBoxes.getBoxClass(Ri(u))).getBoxProperties)==null?void 0:l.call(s,n,u);if(f!=null&&f.boxCommands){f.boxCommands["hovering-toolbar"].executeCommand(n,t,u,o);return}return}const a=Mc(n);a.disableTextToolbar(),a.hide(),setTimeout(()=>{a.enableTextToolbar()},1e4),o.id==="edit-link"?JE(n,t,e):o.id==="remove-link"&&XE(n,t,e);return}const r=hg(n,t);if(!r)return;const i=(c=r.blockCommands)==null?void 0:c["hovering-toolbar"];!i||i.executeCommand(n,t,o)}function Oc(){let n=8;for(;n>0&&!document.querySelector(`div[data-style-heading='${n}']`);)n--;return n}const eI=[Xu,th,eh,nh,oh,rh,ih,sh];class nI{constructor(t){h(this,"id","BlockTurnIntoCommandProvider");this.editor=t}getHeadingIndex(){let t=Oc();return t<=4?t=5:t<8&&(t+=1),t}getAvailableCommands(t,e,o){if(j(t,e)){const r=q(e),i=rt(e),s=Qe(t,e),c=t.getBlockData(e).heading,a=[];for(let f=0;f<this.getHeadingIndex();f++)a.push({id:`heading-${f+1}`,name:T.t("commands.heading",{name:`${f+1}`}),icon:eI[f],states:c===f+1?["checked"]:[],value:`${f+1}`});const u=f=>{var C;const m=b("span",["toolbar-item-name-container"],null);for(const v of f.children)if((C=v.states)!=null&&C.includes("checked"))return m.innerHTML=v.icon||Cc,m;return m.innerHTML=Cc,m};return[{id:"turn-into",name:T.t("commands.headingGroup"),blockId:r,blockType:i,blockKind:s,element:u,groupIndex:200,dropdown:!0,manualShowChildren:!0,childrenPlacement:"bottom-start",defaultCheckedChildren:["text"],children:[{id:"text",name:T.t("commands.text"),icon:Cc,states:c?[]:["checked"]},...a],childrenType:"menu"}]}return[]}applyHeadingStyle(t,e,o){t.updateBlockData(e,{heading:o})}executeCommand(t,e,o,r){if(j(t,e)&&(r.id.startsWith("heading-")||r.id==="text")){const i=r.value?Number(r.value):null;return this.applyHeadingStyle(t,e,i),!0}return!1}}function _c(n){const t=n.getAttribute("block-padding-level");return t?Number(t):null}function oI(n,t){let e;const o=_c(t);if(!o)e=1;else{if(o>=12)return e=12,!1;e=o+1}return n.updateBlockData(t,{...n.getBlockData(t),padding:e}),!0}function q5(n,t){const e=_c(t);if(!e)return!1;const o=n.getBlockData(t);return e>1?(n.updateBlockData(t,{...o,padding:e-1}),!0):(n.updateBlockData(t,{...o,padding:null}),!0)}function Ph(n){return n.readonly||!n.isWritable()}function rI(n){return n.selection.range.getSelectedBlocks().forEach(e=>{const o=e.block;j(n,o)&&oI(n,o)}),!0}function iI(n){return n.selection.range.getSelectedBlocks().forEach(e=>{const o=e.block;j(n,o)&&q5(n,o)}),!0}function sI(n){return Ph(n)?!1:n.undoManager.runInGroup(()=>(rI(n),!0))}function lI(n){return Ph(n)?!1:n.undoManager.runInGroup(()=>(iI(n),!0))}function cI(n){if(Ph(n))return!1;if(!n.selection.range.isCollapsed())return;const t=n.selection.focusedBlock;if(!j(n,t))return;const e=n.selection.range.focus;if(!(!e.isSimple()||e.offset!==0||!_c(t)))return q5(n,t),!0}class aI{renderBlock(t,e,o){const{padding:r}=o;return r?{attributes:{"block-padding-level":r}}:{}}}const mz="",dI={Tab:sI,"Shift+Tab":lI,Backspace:cI},Nc=w("list-block");function ct(n){return rt(n)==="list"}function Ft(n){d(Nc,ct(n),"not a list block")}function Fe(n){Ft(n);const t=n.getAttribute("data-list-type");return d(Nc,t,"no list type"),t}function $c(n){return ct(n)&&Fe(n)==="text-only"}function un(n){var t,e;return Ft(n),(e=Number.parseInt((t=n.getAttribute("data-list-start"))!=null?t:"1",10))!=null?e:1}function me(n){var t,e;return Ft(n),(e=Number.parseInt((t=n.getAttribute("data-list-level"))!=null?t:"1",10))!=null?e:1}function Yr(n){Ft(n);const t=n.getAttribute("data-list-group-id");return d(Nc,t,"no group id"),t}function vo(n){var i,s,l,c,a;Ft(n);const t=(i=n.getAttribute("data-list-type"))!=null?i:"ordered",e=(l=Number.parseInt((s=n.getAttribute("data-list-start"))!=null?s:"1",10))!=null?l:1,o=(a=Number.parseInt((c=n.getAttribute("data-list-level"))!=null?c:"1",10))!=null?a:1,r=n.getAttribute("data-list-group-id");return d(Nc,r,"no group id"),{type:t,start:e,level:o,groupId:r}}function jh(n){switch(n){case"ordered":return{ordered:!0,checkbox:null,textOnly:null};case"unordered":return{ordered:!1,checkbox:null,textOnly:null};case"checked":return{checkbox:"checked",ordered:!1,textOnly:null};case"unchecked":return{checkbox:"unchecked",ordered:!1,textOnly:null};case"text-only":return{checkbox:null,ordered:!1,textOnly:!0};default:return{checkbox:null,ordered:!0,textOnly:!1}}}function Zn(n){Ft(n);const{level:t,groupId:e,type:o}=vo(n);let r=gt(n);for(;r;){if(!ct(r))return null;const{level:i,groupId:s,type:l}=vo(r);if(i<t)return null;if(t===i&&e===s&&(l==="text-only"||o==="text-only"||o===l))return r;r=gt(r)}return null}function rr(n){Ft(n);const{level:t,groupId:e,type:o}=vo(n);let r=dt(n);for(;r;){if(ct(r)){const{level:i,groupId:s,type:l}=vo(r);if(t===i&&e===s&&(l==="text-only"||o==="text-only"||o===l))return r;if(i<t)return null}r=dt(r)}return null}function W5(n){Ft(n);const t=[];let e=Zn(n);for(;e;)t.unshift(e),e=Zn(e);return t}function Is(n){Ft(n);const t=[];let e=rr(n);for(;e;)t.push(e),e=rr(e);return t}function xs(n){Ft(n);let t=Zn(n);for(;t;){const e=Zn(t);if(!e)return t;t=e}return n}function uI(n){Ft(n);let t=rr(n);for(;t;){const e=rr(t);if(!e)return t;t=e}return null}function G5(n,t){const e=W5(n),o=Is(n);return t.withSelf?[...e,n,...o]:[...e,...o]}function Ts(n,t,e,o){var i;const r=(i=o==null?void 0:o.groupId)!=null?i:N();t.forEach(s=>{const l=n.getBlockData(s);if(l.start!==e||(o==null?void 0:o.resetGroupId)){const c={...l,start:e};o!=null&&o.resetGroupId&&(c.groupId=r),n.updateBlockData(s,c)}l.textOnly||(e+=1)})}function Hh(n,t,e,o){const r=G5(t,{withSelf:!0});r.length!==0&&Ts(n,r,e,o)}function hI(n){const t={M:1e3,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1};let e="",o=n;return Object.entries(t).forEach(([r,i])=>{for(;o>=i;)e+=r,o-=i}),e.toLowerCase()}const fI="abcdefghijklmnopqrstuvwxyz";function Z5(n){if(n<=0)return`${n}`;const t=(n-1)%26,e=Math.floor((n-1)/26),o=fI[t];return e?Z5(e)+o:o}function mI(n){return`${n}`}const Y5=[mI,Z5,hI];function gI(n,t){const e=Y5[(n-1)%Y5.length];return e(t)}function pI(n){return["\u2022","\u25E6","\u25AA"][(n-1)%3]}class ir{constructor(t,e,o){h(this,"listStart");h(this,"listBrother",null);this.editor=t,this.options=o;const r=xs(e),i=un(r);this.listStart=i,this.listBrother=r,o!=null&&o.resetStart&&(this.listStart=1)}fix(){!this.listBrother||Hh(this.editor,this.listBrother,this.listStart,this.options)}}function CI(n,t,e=1){if(!t)return null;let o=gt(n);for(;o;){const r=o.getAttribute("data-style-heading"),i=Number(o.getAttribute("data-list-level"));if(r){if(r<t)return null;if(r===t&&i===e)return ct(o)?o:null}o=gt(o)}return null}function bI(n,t){const e=n.getAttribute("data-style-heading"),o=CI(n,e);if(o)return o;const r=gt(n);if(r&&ct(r)&&Fe(r)===t)return r;const i=dt(n);return i&&ct(i)&&Fe(i)===t?i:null}function vI(n,t,e){var y,S,I,M;const o=(y=e.data)!=null?y:{};let r=1;if(ct(t))r=me(t);else{const R=_c(t);R&&(r=R+1),r>8&&(r=8)}const i=(S=o.listType)!=null?S:"ordered";if(i==="text-only")return null;const s=n.getBlockData(t);let l=(I=s.text)!=null?I:[];const c=n.selection.range.focus;if(!c.isSimple())return null;let u=vt(l);const f=(M=e.offset)!=null?M:c.offset;f<=de(l)&&(l=be(l,f).right,u=u.substring(0,f));let m=1;i==="ordered"&&(m=Number.parseInt(u,10)||1);let C=N();const v=bI(t,i);if(v){if(J(t)>J(v))m=un(v)+1;else{const R=un(v);R>1&&(m=R-1)}C=Yr(v)}const B={id:N(),type:"list",level:r,start:m,groupId:C,ordered:!1,text:l};return s.quoted&&(B.quoted=!0),s.heading&&(B.heading=s.heading),i==="ordered"?B.ordered=!0:(i==="checked"||i==="unchecked")&&(B.checkbox=i),{blockData:B,onConverted:(R,$)=>{new ir(R,$).fix()}}}function Qr(n){return n.textOnly?"text-only":n.checkbox?n.checkbox:n.ordered?"ordered":"unordered"}function kI(n){var e,o;if(n.checkbox||n.textOnly)return"";const t=(e=n.level)!=null?e:1;return n.ordered?`${gI(t,(o=n.start)!=null?o:1)}.`:pI(t)}function Pc(n){return n==="checked"||n==="unchecked"}function Q5(n,t,e,o){const r=t,{containerId:i,blockIndex:s}=o[o.length-1];if(s===0)return!0;const l=e.blocks[i][s-1];if(l.type!=="list")return!0;const c=Qr(r),a=Qr(l);return c!==a&&(!Pc(c)||!Pc(a))||r.level>l.level}function K5(n,t,e,o){const r=t,{containerId:i,blockIndex:s}=o[o.length-1];if(s===e.blocks[i].length-1)return!0;const l=e.blocks[i][s+1];if(l.type!=="list")return!0;const c=Qr(r),a=Qr(l);return c!==a&&(!Pc(c)||!Pc(a))||r.level>l.level}function yI(n,t,e,o,r){var s,l,c;const i=t;if(o==="text"){let a=((s=ve.convertTo)==null?void 0:s.call(ve,n,t,e,"text",r))||"";i.checkbox==="checked"?a=`[x] ${a}`:i.checkbox==="unchecked"&&(a=`[ ] ${a}`),i.ordered?a=`${i.start}. ${a}`:a=`- ${a}`;const u=i.level||0;return a=(u>0?" ".repeat(u-1):"")+a,a}if(o==="markdown"){let a=((l=ve.convertTo)==null?void 0:l.call(ve,n,t,e,"markdown",r))||"";i.checkbox==="checked"?a=`[x] ${a}`:i.checkbox==="unchecked"&&(a=`[ ] ${a}`),i.ordered?a=`${i.start}. ${a}`:a=`- ${a}`;const u=i.level||0;return a=(u>0?" ".repeat(u-1):"")+a,Q5(n,t,e,r)&&(a=`${a}`),K5(n,t,e,r)&&(a=`${a}`,u<=1&&(a+=`
337
+ </svg>`;function gB(n,t){var e;if(A(t,"menu-item"),!n.element){if(n.type==="section"){const o=b("div",["section-name"],null,n.name);t.appendChild(o)}else if(n.type!=="separator"){if(n.icon){const r=b("div",["menu-item-icon"],null);n.icon&&(r.innerHTML=n.icon),t.appendChild(r)}const o=b("div",["menu-item-name","text"],null,n.name);if(t.appendChild(o),n.subText&&b("div",["item-subtext","text"],t,n.subText),n.children&&!n.element){const r=b("div",["menu-item-sub-indicator"],null);r.innerHTML=J2,t.appendChild(r)}if((e=n.states)!=null&&e.includes("checked")){const r=b("div",["menu-item-checked-icon"],null);r.innerHTML=Yw,t.appendChild(r)}}}}class tr extends gc{constructor(t,e,o){super(t,e,{autoClose:!0,disablePageScroll:!0,...o})}manualShow(t,e){const o={theme:"menu",...e};super.manualShow(t,o)}initCommandBarElement(t){A(t,"menu")}initItemElement(t,e){gB(t,e)}}function pB(n,t,e){var o;return new tr((o=n.children)!=null?o:[],t,{...e,parentItem:n})}class ps extends gc{constructor(t,e,o){super(t,e,{itemElementTag:"button",tippyArrow:!1,...o})}getSubBarOptions(t){var r,i;const e=()=>{const s=this.getItemElementById(t.id),c=this.content.getBoundingClientRect(),a=s.getBoundingClientRect();return new DOMRect(a.left,c.top,a.width,c.height)};return{placement:(r=t.childrenPlacement)!=null?r:"top",getReferenceClientRect:e,offset:(i=t.childrenOffset)!=null?i:[0,4]}}manualShow(t,e){const o={theme:"toolbar",...e};super.manualShow(t,o)}initCommandBarElement(t){A(t,"toolbar")}initItemElement(t,e){e.setAttribute("data-button-id",t.id),this.options.tooltipId&&t.name&&!t.disableTooltip&&(e.setAttribute(`data-editor-tooltip-${this.options.tooltipId}`,t.name),t.desc&&e.setAttribute(`data-editor-tooltip-desc-${this.options.tooltipId}`,t.desc));const o=e;if(!t.element)if(t.icon){const r=b("span",["toolbar-item-icon-container"],o);t.icon.trim().startsWith("<")?r.innerHTML=t.icon:r.innerText=t.icon}else{const r=b("span",["toolbar-item-name-container"],o);r.innerText=t.name}if(t.dropdown){e.setAttribute("data-dropdown","true");const r=b("span",["toolbar-item-dropdown-container"],o);r.innerHTML=Ju}t.states&&(t.states.indexOf("checked")!==-1&&A(o,"checked"),t.states.indexOf("disabled")!==-1&&(o.disabled=!0))}}function CB(n,t,e){var o;return new ps((o=n.children)!=null?o:[],t,{...e,parentItem:n})}const lz="";Hr.registerManualCommandBar("menu",pB),Hr.registerManualCommandBar("toolbar",CB);const cz="",l5=w("ui-base");class bc extends gc{constructor(e,o){super(bc.getCommandItems(e,o),void 0,{disablePageScroll:!0,...o});h(this,"handleDocumentMouseDown",e=>{})}initCommandBarElement(e){A(e,"dialog","manual")}initItemElement(e,o){}show(e,o){this.manualShow(e,{...o,theme:"light"})}get dialogContent(){const e=this.items[0];d(l5,e,"no dialog item");const o=e.element;return d(l5,o,"no item element"),o}static getCommandItems(e,o){var s;return[{id:(s=o==null?void 0:o.id)!=null?s:`manual-dialog-${N()}`,name:"",element:e}]}}const bB=[-1,6,0,1,2,3,4,5],vB=[-1,6,0,1,2,3,4,5,14,13,7,8,9,10,11,12],c5=w("color-palette");function a5(n,t,e,o){d(c5,n>0,"no color in palette");const r=t||1;d(c5,r>0,`invalid palette rows: ${r}`);const i=n/r,s=b("div",["palette-container",o],null);for(let l=0;l<r;l++){const c=b("div",["palette-container-row"],s);for(let a=0;a<i;a++){const u=e(l*i+a);c.appendChild(u)}}return s}function kB(n){const t=b("button",["color-button"],null),e=bB[n];return t.setAttribute("data-color-index",`${e}`),t.innerHTML=K2,t}function yB(n){const t=b("button",["background-color-button"],null),e=vB[n];return t.setAttribute("data-color-index",`${e}`),t}function wB(){const n=b("div",["clear-button-container"],null),t=b("button",["clear-button"],n);return t.innerText=T.t("colorPalette.reset"),n}function BB(n){const t=b("div",["color-palette"],null);return n.color!==!1&&(b("div",["bar-desc"],t,T.t("colorPalette.colorDesc")),t.appendChild(a5(8,1,kB,"color"))),n.backgroundColor!==!1&&(b("div",["bar-desc"],t,T.t("colorPalette.backgroundDesc")),t.appendChild(a5(16,2,yB,"background-color"))),n.clearColorButton!==!1&&t.appendChild(wB()),t}function EB(n,t,e){const o=t==="color"?"color":"background-color",r=n.querySelector(`.${o} button.selected`);r&&z(r,"selected"),e===null&&(e=-1);const i=n.querySelector(`.${o} button[data-color-index="${e}"]`);i&&A(i,"selected")}const az="",IB={};class xB extends Yt.TypedEmitter{constructor(e=IB){super();h(this,"root");h(this,"handleClick",e=>{const o=e.target;if(!o||!(o instanceof Element))return;const r=o.closest("button");if(!r)return;if(nt(r,"clear-button")){this.setColor("backgroundColor",null),this.setColor("color",null),this.emit("onClick","clearColor",0);return}const i=r.getAttribute("data-color-index");if(!i)return;const s=Number.parseInt(i,10);Number.isNaN(s)||(nt(r,"color-button")?s===-1?(this.setColor("color",null),this.emit("onClick","clearColor",1)):(this.setColor("color",s),this.emit("onClick","color",s)):s===-1?(this.setColor("backgroundColor",null),this.emit("onClick","clearColor",2)):(this.setColor("backgroundColor",s),this.emit("onClick","backgroundColor",s)))});this.options=e,this.root=BB(e),this.root.addEventListener("click",this.handleClick)}destroy(){this.removeAllListeners(),this.root.removeEventListener("click",this.handleClick)}setColor(e,o){EB(this.root,e,o)}}class d5{constructor(t,e){h(this,"name","Color Palette");h(this,"element");h(this,"palette");h(this,"closeable",null);this.id=t,this.palette=new xB(e),this.element=this.palette.root}setCloseable(t){this.closeable=t}destroy(){this.palette.destroy(),this.closeable=null}}function TB(){const n=b("button",["color-button"],null);return n.innerHTML=K2,n}function dh(n,t){const[e,o]=t;e===null?n.removeAttribute("data-color"):n.setAttribute("data-color",`${e}`),o===null?n.removeAttribute("data-background-color"):n.setAttribute("data-background-color",`${o}`)}class SB extends Yt.TypedEmitter{constructor(e){super();h(this,"id","text-color-item");h(this,"name",T.t("colorPalette.name"));h(this,"dropdown",!0);h(this,"manualShowChildren",!0);h(this,"children",[]);h(this,"element");h(this,"colorPaletteItem");h(this,"latestColors",[null,null]);h(this,"handlePaletteClick",(e,o)=>{this.emit("onClick",e,o),e==="color"||e==="backgroundColor"?e==="color"?this.latestColors[0]=o:this.latestColors[1]=o:this.latestColors=[null,null],dh(this.element,this.latestColors)});h(this,"beforePopup",()=>{this.emit("beforePopup")});this.editor=e,this.colorPaletteItem=new d5("text-color-palette-item"),this.colorPaletteItem.palette.addListener("onClick",this.handlePaletteClick),this.children.push(this.colorPaletteItem),this.element=TB()}destroy(){this.colorPaletteItem.destroy()}updatePaletteColor(e){this.colorPaletteItem.palette.setColor("color",e[0]),this.colorPaletteItem.palette.setColor("backgroundColor",e[1]),this.latestColors=e,dh(this.element,this.latestColors)}updateButtonColor(e){this.latestColors=e,dh(this.element,this.latestColors)}}const dz="";function uh(n,t){const e=b("div",["editor-input-wrap"],n);t!=null&&t.className&&A(e,t==null?void 0:t.className);const o=b("div",["editor-input-label"],e);b("span",[],o,t.label),t.required&&A(o,"required");const r=b("div",["editor-input-container"],e),i=b("input",["editor-input"],r);t.placeholder&&(i.placeholder=t.placeholder),t.defaultValue&&(i.value=t.defaultValue);const s=b("div",["editor-input-error"],e);return i.addEventListener("input",l=>{var c;(c=t.onChange)==null||c.call(t,l),z(e,"error")}),i.addEventListener("keydown",l=>{var c;(c=t.onKeyDown)==null||c.call(t,l)}),{getField:()=>i,getInputValue:()=>i.value,setFieldError:l=>{A(e,"error"),s.innerText=l},focus:()=>{setTimeout(()=>{i.focus()})}}}function hh(n){const t=document.getSelection();if(!t)return!0;const e=t.focusNode;if(!e)return!0;const o=t.focusOffset,r=e.childNodes[o];if(!r)return!0;if(r instanceof HTMLElement){const i=r.tagName.toLowerCase();if(r===n.input.inputElement)return!0;if(i==="input"||i==="textarea")return!1}return!0}const DB=w("ui-base");class LB{constructor(t,e){h(this,"menu");h(this,"currentText","");h(this,"handleClick",(t,e)=>{this.options.onClickItem(this,e)});h(this,"handleClose",()=>{hh(this.editor)&&this.editor.focus()});h(this,"handleKeydown",t=>{this.menu.handleDocumentKeydown(t)});this.editor=t,this.options=e,this.menu=new tr([],void 0,{id:e.id}),this.menu.addListener("click",this.handleClick),this.menu.addListener("close",this.handleClose)}setItems(t){if(this.menu.updateItems(t),t.length>0){const e=t.find(o=>o.type!=="section"&&o.type!=="separator");e&&this.menu.selectItem(e.id)}}async popup(t,e,o){var a,u;if(((u=(a=this.options).onShow)==null?void 0:u.call(a,this,t,e,o))===!1)return;this.options.showLoading&&this.showLoading();const r=this.editor.getBlockByIndex(t,e);if(!It(this.editor.rootContainer,r)||W(this.editor,r)<o)return;const i=Ho(this.editor,r,At(this.editor,r,o));if(i.length===0)return;const s=i[0],l=zo(this.editor,r,"editor-auto-suggest-menu",s);this.menu.manualShow(l),this.options.placeholder&&this.showPlaceholder();const c=await this.options.queryItems(this,"");this.highlightText(""),this.setItems(c)}showLoading(){!this.options.showLoading||(this.options.loadingElement?this.setItems([{id:"loading",name:"",element:this.options.loadingElement,states:["disabled"]}]):this.setItems([{id:"loading",name:"loading",states:["disabled"]}]))}showPlaceholder(){this.setItems([{id:"placeholder",name:"enter text to search",states:["disabled"]}])}showNoResultMessage(t){if(this.options.noResultMessage){const e={name:"",id:"placeholder",states:["disabled"]};typeof this.options.noResultMessage=="string"?e.name=this.options.noResultMessage:(this.options.noResultMessage instanceof HTMLElement||typeof this.options.noResultMessage=="function")&&(e.element=this.options.noResultMessage),this.setItems([e])}else this.setItems([{id:"placeholder",name:T.t("search.emptyTips"),states:["disabled"]}])}close(){this.menu.close()}get isVisible(){return this.menu.isVisible}destroy(){this.menu.close(),this.menu.removeAllListeners(),this.menu.destroy()}async handleSearchText(t){this.currentText=t;const e="auto-suggest";try{await qe.lock(e),this.showLoading();const o=this.currentText,r=await this.options.queryItems(this,o);if(this.currentText===o&&(this.currentText=""),r.length===0){this.showNoResultMessage(t);return}this.setItems(r),this.options.highlight&&this.highlightText(o.replace(/^\s+|\s+$/g,""))}finally{qe.release(e)}}highlightText(t){DB.debug(`highlight menu text: ${t}`);const e=this.menu.content,o=(i,s)=>{if(!s)return i;let l="";const c=s.length,a=s.toLocaleLowerCase();let u=0;for(u=0;u<=i.length-c;u){let f=i.substring(u,u+c);if(f.toLocaleLowerCase()===a){u+=c;const m=i.charAt(u);let C=!1;f.endsWith(" ")&&(C=!0,f=f.trimEnd()),l+=`<span class="highlight">${f}${m===" "||C?"&nbsp":""}</span>`}else l+=i.charAt(u),u++}return u<i.length&&(l+=i.substring(u)),l},r=i=>{if(nt(i,"text")){const s=i.textContent;if(!s)return;const l=o(s,t);i.innerHTML=l;return}Array.from(i.children).forEach(r)};r(e)}}const fh=w("auto-suggest-menu");class mh{constructor(t,e){h(this,"menu");h(this,"anchor",null);h(this,"handleSelectionChanged",t=>{var o,r;if(!((o=this.menu)!=null&&o.isVisible))return;const e=t.selection.range.start;if(e.isSimple()&&e.blockId===((r=this.anchor)==null?void 0:r.blockId)&&e.offset>=this.anchor.offset){const i=t.getBlockById(e.blockId);if(vt(be(ue(t,i),e.offset).left).startsWith(this.anchor.leftText))return}this.menu.close()});h(this,"deleteTrigger",()=>{const t=this.editor,e=t.selection.range.start;if(!e.isSimple()||!this.anchor)return!1;const{blockId:o,offset:r}=e,i=t.getBlockById(o),s=vt(Ul(t,i,r));if(d(fh,this.anchor,"no anchor"),!s.startsWith(this.anchor.leftText))return!1;const l=this.anchor.offset-this.anchor.trigger.length,c=r-l;return t.selection.selectBlock(i,l),c&&(t.deleteTextFromBlock(i,l,c),this.anchor.offset-=this.anchor.trigger.length),this.anchor.trigger.length||this.menu.close(),!0});h(this,"onShow",(t,e,o,r)=>{var i;if((i=this.options)!=null&&i.onShow)return this.options.onShow(this,e,o,r)});h(this,"onClickItem",(t,e)=>{!this.anchor||(this.options.autoDeleteTrigger&&this.deleteTrigger(),this.options.onClickItem(this,e,this.anchor))});h(this,"queryItems",(t,e)=>this.options.queryItems(this,e));h(this,"renderMenuItem",(t,e)=>{var r,i;return(i=(r=this.options).renderMenuItem)==null?void 0:i.call(r,this,e)});this.editor=t,this.options=e,this.menu=new LB(t,{id:e.id,showLoading:e.showLoading,loadingElement:e.loadingElement,placeholder:e.placeholder,noResultMessage:e.noResultMessage,highlight:e.highlight,onShow:this.onShow,onClickItem:this.onClickItem,queryItems:this.queryItems,renderMenuItem:this.renderMenuItem}),t.input.addHandler(this),t.addListener("selectionChanged",this.handleSelectionChanged)}handleBeforeKeyDown(t,e){var o;return!((o=this.menu)!=null&&o.isVisible)||rd(e.key)?!1:km(e)&&!Oo(e)?(setTimeout(()=>{this.resetItems()}),!1):id(e)?(this.menu.close(),!0):(this.menu.handleKeydown(e),!0)}popup(t,e,o,r){this.anchor={blockId:q(t),offset:e,leftText:o,trigger:r};const i=U(H(t)),s=J(t);this.menu.popup(i,s,e)}handleAfterInsertText(t,e,o,r,i){var u;const s=t.selection.range.start;if(!s.isSimple()||e==="root"&&o===0)return!1;const{blockId:l,offset:c}=s,a=t.getBlockByIndex(e,o);if(q(a)!==l)return!1;if((u=this.menu)!=null&&u.isVisible)this.resetItems();else if(this.options.trigger.indexOf(i)!==-1){if(r>0&&this.options.needSpaceBeforeTrigger&&t.getBlockString(a)[r-1]!==" ")return!1;const f=vt(Ul(t,a,c));this.popup(a,c,f,i)}return!1}handleUpdateCompositionText(t,e,o,r,i){var a;const s=t.selection.range.start;if(!s.isSimple())return!1;const{blockId:l}=s,c=t.getBlockByIndex(e,o);return q(c)!==l||(a=this.menu)!=null&&a.isVisible&&this.resetItems(),!1}resetItems(){var l;if(!((l=this.menu)!=null&&l.isVisible))return;const t=this.editor,e=t.selection.range.start;if(!e.isSimple())return;const{blockId:o,offset:r}=e,i=t.getBlockById(o),s=vt(Ul(t,i,r));if(d(fh,this.anchor,"no anchor"),s.startsWith(this.anchor.leftText)){const c=s.substring(this.anchor.leftText.length);fh.debug(`search text: ${c}`),this.menu.handleSearchText(c)}}destroy(){var t;this.editor.input.removeHandler(this),this.editor.removeListener("selectionChanged",this.handleSelectionChanged),(t=this.menu)==null||t.destroy()}}function MB(){const n={};for(let t=1;t<=8;t++)n[`heading-${t}`]={shortcut:`/h${t}`};return n}const RB={"insert-hr":{shortcut:"/hr"},"insert-uml":{shortcut:"/uml"},"insert-table":{shortcut:"/table"},"insert-image":{shortcut:"/image"},"insert-code":{shortcut:"/code"},"insert-link":{shortcut:"/link"},"insert-drawio":{shortcut:"/uml"},"insert-video":{shortcut:"/video"},"insert-audio":{shortcut:"/audio"},"insert-math":{shortcut:"/math"},"insert-webPage":{shortcut:"/web"},"insert-bilibili":{shortcut:"/bilibili"},"insert-youku":{shortcut:"/youku"},"insert-figma":{shortcut:"/figma"},"insert-modao":{shortcut:"/modao"},"insert-tencent":{shortcut:"/tencent"},"insert-unordered":{shortcut:"/bl"},"insert-ordered":{shortcut:"/nu"},"insert-checkbox":{shortcut:"/todo"},"insert-quote":{shortcut:"/quote"},...MB()};function fe(n){var t;return(t=RB[n])==null?void 0:t.shortcut}function AB(n){var t;return(t=n.subText)!=null?t:""}const xn=w("table-dom");function Co(n){return`${q(n)}_scroll`}function jt(n){const t=n.querySelector("div[data-type=table-content] >table");return d(xn,t instanceof HTMLTableElement,"invalid table"),t}function Tn(n,t){const o=n.getCustom(Co(t)).contentElement.firstElementChild;d(xn,o instanceof HTMLElement,"invalid table content");let r=o.querySelector(":scope >div[data-type=table-tools]");return r||(r=b("div",[],o),r.setAttribute("data-type","table-tools")),d(xn,r,"no table tools"),r}function u5(n){const t=[];return Array.from(n.rows).forEach(e=>{t.push(...Array.from(e.cells))}),t}function Cs(n){const t=n.querySelector(":scope div[data-type=editor-container]");return d(xn,t,"no child container in cell"),t}function OB(n){const o=u5(n).map(r=>{const i=Cs(r),s=U(i),l=r.colSpan,c=r.rowSpan;return`${s}/${l}/${c}`}).join();return Ei.default(o)}function Ht(n){return rt(n)==="table"}function gh(n){const t=H(n);if(pt(t))return null;const e=F(t);return d(xn,e,"no parent block"),Ht(e)?t:gh(e)}function Me(n){if(Ht(n))return n;const t=H(n);if(pt(t))return null;const e=F(t);return d(xn,e,"no parent block"),Ht(e)?e:Me(e)}function _B(n,t){const e=n.querySelector("colgroup");d(xn,e,"no colgroup");const o=e.children[t];return d(xn,o,"no col"),d(xn,o instanceof HTMLTableColElement,`invalid col: ${o.tagName}`),o}function h5(n){try{return jt(n),!0}catch{return!1}}function NB(n){return Rt(n).querySelector(":scope > .block-helper")}function f5(n){const t=F(n.contentElement);d(xn,t,"no block");const e=NB(t);if(e){const o=Math.min(n.contentElement.offsetLeft,n.rootElement.scrollLeft),r=t.getBoundingClientRect().width;e.style.right=`${o+r}px`}}const Re=w("doc-table-grid");class $B{constructor(t){h(this,"_cells",[]);for(let e=0;e<t;e++)this._cells.push(void 0)}cols(){return this._cells.length}setCell(t,e){d(Re,t>=0&&t<this.cols(),`set cell, invalid col: ${t}`),this._cells[t]=e}getCell(t){d(Re,t>=0&&t<this.cols(),`get cell, invalid col: ${t}`);const e=this._cells[t];return d(Re,e,"get cell, no cell"),e}getCellAllowEmpty(t){return d(Re,t>=0&&t<this.cols(),`get cell, invalid col, ${t}`),this._cells[t]}getNextNonVirtualCell(t){return this._cells.slice(t+1).find(e=>!e.virtual)}forEach(t){this._cells.forEach(t)}}class vc{constructor(t){h(this,"_data");h(this,"_rows");this._data=t,this._rows=[];for(let e=0;e<this.rowCount;e++)this._rows.push(new $B(this.colCount));this.fillGrid(),d(Re,t.colsWidth,"no colsWidth"),d(Re,this.colCount===t.colsWidth.length,"invalid col count")}get rowCount(){return this._data.rows}get colCount(){return this._data.cols}getNextEmptyCell(t,e){let o=t,r=e;for(;;){if(o+=1,o===this.colCount&&(o=0,r+=1),r>=this.rowCount)return null;if(this._rows[r].getCellAllowEmpty(o)===void 0)return{col:o,row:r}}}fillGrid(){const t=this._data.children;d(Re,t,"no children");let e=0,o=0;t.forEach((r,i)=>{const s=this._data[`${r}_colSpan`]||1,l=this._data[`${r}_rowSpan`]||1;for(let a=0;a<l;a++)for(let u=0;u<s;u++)this._rows[o+a].setCell(e+u,{col:e,row:o,containerId:r,virtual:u!==0||a!==0,colSpan:s,rowSpan:l});const c=this.getNextEmptyCell(e,o);c?(e=c.col,o=c.row):d(Re,i===t.length-1,`invalid table data, no next empty cell: ${JSON.stringify(this._data)}`)}),this._rows.forEach(r=>{r.forEach(i=>{d(Re,i,"no cell"),d(Re,i.containerId,"no containerId")})})}getCell(t){const{col:e,row:o}=t,r=this._rows[o];d(Re,r,`get cell, no row: ${o}`);const i=r.getCell(e);return d(Re,i,`get cell, no cell: ${e}`),i}getRow(t){const e=this._rows[t];return d(Re,e,`get row, no row: ${t}`),e}forEach(t){this._rows.forEach(t)}}const kc=w("table-data");function PB(n){const t=n.firstElementChild;return d(kc,t,"no child element for cell"),d(kc,bn(t),"cell first child is not a container"),d(kc,Ye(t),"cell first child is not a container"),t}function jB(n){const t=F(n);d(kc,t,"no parent block for table");const e=[],o={};Array.from(n.rows).forEach(l=>{Array.from(l.cells).forEach(c=>{const a=PB(c),u=U(a);e.push(u),(c.colSpan>1||c.rowSpan>1)&&(o[`${u}_colSpan`]=c.colSpan,o[`${u}_rowSpan`]=c.rowSpan)})});const r=n.rows.length,i=Array.from(n.rows[0].cells).map(l=>l.colSpan).reduce((l,c)=>l+c,0);return{id:q(t),type:rt(t),rows:r,cols:i,children:e,colsWidth:Array(i).fill(100),...o}}function er(n){return new vc(n)}function HB(n){return er(jB(n))}const Zt=w("table-grid"),FB=60;class zB{constructor(t,e){h(this,"containerId");h(this,"row");h(this,"col");h(this,"colSpan");h(this,"rowSpan");h(this,"virtual");h(this,"table");this.table=t,this.containerId=e.containerId,this.row=e.row,this.col=e.col,this.colSpan=e.colSpan,this.rowSpan=e.rowSpan,this.virtual=e.virtual}get cell(){const e=this.container.closest("td");return d(Zt,e,"no parent cell for child container"),e}get container(){const t=this.table.querySelectorAll(`[data-container-id=${this.containerId}]`);d(Zt,t.length===1,"containers !== 1"),d(Zt,bn(t[0]),"not a container");const e=t[0];return d(Zt,Ye(e),"not a child container"),e}}class UB{constructor(t,e){h(this,"_cells",[]);e.forEach(o=>{this._cells.push(new zB(t,o))})}get cells(){return this._cells}getCell(t){return d(Zt,t<this._cells.length,"get cell, invalid col"),this._cells[t]}getNextNonVirtualCell(t){return this._cells.slice(t+1).find(e=>!e.virtual)}getSpannedCell(){return this._cells.find(t=>t.virtual||t.colSpan>1||t.rowSpan>1)}}const Ef=class{constructor(t){h(this,"_rows",[]);this.table=t,HB(t).forEach(r=>{this._rows.push(new UB(t,r))});const o=this.colCount;this._rows.forEach(r=>{d(Zt,r.cells.length===o,"row.cells.length !== colCount")})}get rowCount(){return this._rows.length}get colCount(){return this._rows.length===0?0:(d(Zt,this.rowCount>0,"rowCount <= 0"),this.getRow(0).cells.length)}getRow(t){return this._rows[t]}getCell(t){const e=this.getRow(t.row);return d(Zt,e,"no row"),e.getCell(t.col)}getCellContainer(t){return this.getCell(t).container}getFirstCellContainer(){return this.getCellContainer({row:0,col:0})}getLastCellContainer(){const t=this.rowCount-1,e=this.colCount-1;return this.getCellContainer({row:t,col:e})}getColumnCells(t){d(Zt,t>=0&&t<this.colCount,"colIndex out of range");const e=this.rowCount,o=[];for(let r=0;r<e;r++){const i=this.getCell({row:r,col:t});o.push(i)}return o}toRealCells(t){const e=[];return t.forEach(o=>{const r=this.getRealCell(o);e.findIndex(i=>i.containerId===r.containerId)===-1&&e.push(r)}),e}getColumnRealCells(t){const e=this.getColumnCells(t);return this.toRealCells(e)}getRowRealCells(t){const e=this.getRow(t).cells;return this.toRealCells(e)}getFirstSpannedCell(t){d(Zt,t>=0&&t<this.colCount,"colIndex out of range");const e=this.rowCount;for(let o=0;o<e;o++){const r=this.getCell({row:o,col:t});if(r.virtual||r.colSpan>1||r.rowSpan>1)return r}}getRealCell(t){const e=this.getCell(t);if(!e.virtual)return e;const o=this.getCellById(e.containerId);return d(Zt,!o.virtual,"found a virtual cell"),o}getColumnSpannedRange(t){const e=this.getColumnRealCells(t);let o=1e5,r=-1;return e.forEach(i=>{o=Math.min(i.col,o),r=Math.max(i.col+i.colSpan-1,r)}),d(Zt,o<=r,"min > max"),d(Zt,o>=0,"min < 0"),d(Zt,r<this.colCount,"max >= colCount"),[o,r]}getRowSpannedRange(t){const e=this.getRowRealCells(t);let o=1e5,r=-1;return e.forEach(i=>{o=Math.min(i.row,o),r=Math.max(i.row+i.rowSpan-1,r)}),d(Zt,o<=r,"min > max"),d(Zt,o>=0,"min < 0"),d(Zt,r<this.rowCount,"max >= rowCount"),[o,r]}getSpannedRange(t,e){const o=Math.min(t.row,e.row),r=Math.max(t.row,e.row),i=Math.min(t.col,e.col),s=Math.max(t.col,e.col),l=[];for(let C=o;C<=r;C++)for(let v=i;v<=s;v++)l.push(this.getCell({row:C,col:v}));const c=this.toRealCells(l);let a=1e4,u=1e4,f=-1,m=-1;return c.forEach(C=>{u=Math.min(C.col,u),a=Math.min(C.row,a),m=Math.max(C.col+C.colSpan-1,m),f=Math.max(C.row+C.rowSpan-1,f)}),[{row:a,col:u},{row:f,col:m}]}getAllCells(){return this.getCells({col:0,row:0},{col:this.colCount-1,row:this.rowCount-1})}sub(t,e){const o=[];for(let r=t.row;r<=e.row;r++){const i=[];for(let s=t.col;s<=e.col;s++){const l=this.getCell({row:r,col:s});i.push(l)}o.push(i)}return o}getAllContainers(){return this.getAllCells().map(e=>e.container)}getCells(t,e){const o=[],r=this.getSpannedRange(t,e),i=r[0],s=r[1],l=Math.min(i.row,s.row),c=Math.max(i.row,s.row),a=Math.min(i.col,s.col),u=Math.max(i.col,s.col);for(let f=l;f<=c;f++)for(let m=a;m<=u;m++){const C=this.getCell({row:f,col:m});C.virtual||o.push(C)}return o}map(t){const e=[];for(let o=0;o<this.rowCount;o++){const r=[];for(let i=0;i<this.colCount;i++){const s=this.getCell({row:o,col:i});r.push(t(s))}e.push(r)}return e}getBottomCell(t){const e=this.rowCount;let o=t,r=t.row;for(;o.containerId===t.containerId;){if(r+=1,r>=e)return null;o=this.getCell({row:r,col:t.col})}return this.getRealCell(o)}getTopCell(t){let e=t,o=t.row;for(;e.containerId===t.containerId;){if(o-=1,o<0)return null;e=this.getCell({row:o,col:t.col})}return this.getRealCell(e)}get cells(){let t=[];return this._rows.forEach(e=>{t=t.concat(e.cells)}),t}getVirtualCellContainersGrid(){return this.map(t=>t.containerId)}static virtualCellContainersGridToChildren(t){const e=t,o=[];return e.forEach(r=>{r.forEach(i=>{o.indexOf(i)===-1&&o.push(i)})}),o}getCellById(t){const o=this.cells.find(r=>r.containerId===t);return d(Zt,o,"cell not found"),o}getCellByCellElement(t){const e=Cs(t);return this.getCellByContainerId(U(e))}getCellByContainerId(t){return this.getCellById(t)}static fromTable(t){const e=OB(t),o=this.caches.getSync(e,()=>(Zt.debug("create table grid"),new Ef(t)));return o.table!==t?(this.caches.delete(e),this.fromTable(t)):o}static fromBlock(t){return this.fromTable(jt(t))}};let et=Ef;h(et,"caches",new Xf(FB));function yc(n,t){Object.entries(n).forEach(([e])=>{e.startsWith(`${t}/`)&&delete n[e]})}const VB=w("table-selection-range");function an(n,t,e){var I,M,R,$;const o=et.fromBlock(n),r=t,i=e,s=o.getCellByContainerId(r.childContainerId),l=o.getCellByContainerId(i.childContainerId),c=r.custom,a=i.custom,u=(I=c==null?void 0:c.rowIndex)!=null?I:s.row,f=(M=c==null?void 0:c.colIndex)!=null?M:s.col,m=(R=a==null?void 0:a.rowIndex)!=null?R:l.row+l.rowSpan-1,C=($=a==null?void 0:a.colIndex)!=null?$:l.col+l.colSpan-1,v=Math.min(u,m),B=Math.max(u,m),y=Math.min(f,C),S=Math.max(f,C);return{fromRow:v,toRow:B,fromCol:y,toCol:S}}function ph(n,t){const e=new Set,o=new Set,r=n.selection.range;if(!r.isSimple()&&r.start.blockId===q(t)){const i=et.fromBlock(t),{start:s,end:l}=r;d(VB,!s.isSimple()&&!l.isSimple(),"invalid range");const{fromCol:c,toCol:a,fromRow:u,toRow:f}=an(t,s,l);if(u===0&&f===i.rowCount-1)for(let m=c;m<=a;m++)o.add(m);if(c===0&&a===i.colCount-1)for(let m=u;m<=f;m++)e.add(m)}return{selectedRows:e,selectedColumns:o}}const Fr=w("delete-columns");function m5(n,t,e){const{start:o,end:r}=e;if(o.blockId!==r.blockId||e.isSimple()||n.getBlockById(o.blockId)!==t||rt(t)!=="table")return!1;const{fromRow:s,toRow:l}=an(t,e.start,e.end),c=et.fromBlock(t);return s===0&&l===c.rowCount-1}function Ch(n){var M;const t=n.getEditor(),e=t.getBlockById(n.start.blockId);if(!m5(t,e,n))return;if(n.isSimple()){t.deleteBlock(e);return}const{fromCol:o,toCol:r}=an(e,n.start,n.end),i=et.fromBlock(e);if(o===0&&r===i.colCount-1){t.deleteBlock(e);return}const s=new Set,l=i.map(R=>R.containerId);for(let R=0;R<l.length;R++){const $=l[R];for(let Z=o;Z<=r;Z++){const ot=$[Z];s.add(ot)}$.splice(o,r-o+1)}const c=new Set(l.flat()),a=new Set(Array.from(s).filter(R=>!c.has(R))),u=r-o+1,f=new Map,m=new Map;s.forEach(R=>{if(a.has(R))return;const $=i.getCellByContainerId(R);if(d(Fr,$.colSpan>1,"invalid effected cell, colSpan === 1"),$.col<o){d(Fr,c.has(R),"invalid effected cell, not exists");let yt=$.col+$.colSpan-1;yt>r&&(yt=r);const se=yt-o+1,eo=$.colSpan-se;f.set(R,eo);return}d(Fr,$.col<=r,"invalid effected cell, col > endCol");const Z=$.col,ot=$.col+$.colSpan-1,st=$.col-o,mt=ot-Z+1-u+st;d(Fr,mt>0,"invalid effected cell, newSpanned <= 0");const ut=yn(t.doc);m.set(R,{newContainerId:ut,colSpan:mt})});for(let R=0;R<l.length;R++){const $=l[R];for(let Z=o;Z<$.length;Z++){const ot=$[Z],st=m.get(ot);st&&($[Z]=st.newContainerId)}}const C=Y.default(t.getBlockData(e));C.colsWidth.splice(o,r-o+1),a.forEach(R=>{yc(C,R)}),f.forEach((R,$)=>{d(Fr,R>=1,"invalid modified colSpan, colSpan < 1"),R===1?C[`${$}_colSpan`]=void 0:C[`${$}_colSpan`]=R}),m.forEach((R,$)=>{yc(C,$);const{newContainerId:Z,colSpan:ot}=R;d(Fr,ot>=1,"invalid newContainerData, colSpan < 1"),ot>1&&(C[`${Z}_colSpan`]=ot);const st=i.getCellByContainerId($).rowSpan;st>1&&(C[`${Z}_rowSpan`]=st)});const B=(M=l[0][o])!=null?M:l[0][o-1],y=t.getChildContainerData(B)[0],S=et.virtualCellContainersGridToChildren(l),I={...C,cols:C.cols-u,children:S};er(I),t.undoManager.runInGroup(()=>{t.updateBlockData(e,I,At(t,y.id,0)),t.deleteChildContainers(Array.from(a)),t.deleteChildContainers(Array.from(m.keys()))})}const zr=w("delete-rows");function g5(n,t,e){const{start:o,end:r}=e;if(o.blockId!==r.blockId||e.isSimple()||n.getBlockById(o.blockId)!==t||rt(t)!=="table")return!1;const{fromCol:s,toCol:l}=an(t,e.start,e.end),c=et.fromBlock(t);return s===0&&l===c.colCount-1}function bh(n){const t=n.getEditor(),e=t.getBlockById(n.start.blockId);if(!g5(t,e,n))return;if(n.isSimple()){t.deleteBlock(e);return}const{fromRow:o,toRow:r}=an(e,n.start,n.end),i=et.fromBlock(e);if(o===0&&r===i.rowCount-1){t.deleteBlock(e);return}const s=new Set,l=i.map(I=>I.containerId);for(let I=r;I>=o;I--)l[I].forEach(R=>s.add(R)),l.splice(I,1);const c=new Set(l.flat()),a=new Set(Array.from(s).filter(I=>!c.has(I))),u=r-o+1,f=new Map,m=new Map;s.forEach(I=>{if(a.has(I))return;const M=i.getCellByContainerId(I);if(d(zr,M.rowSpan>1,"invalid effected cell, rowSpan === 1"),M.row<o){d(zr,c.has(I),"invalid effected cell, not exists");let mt=M.row+M.rowSpan-1;mt>r&&(mt=r);const ut=mt-o+1,yt=M.rowSpan-ut;f.set(I,yt);return}d(zr,M.row<=r,"invalid effected cell, col > endCol");const R=M.row,$=M.row+M.rowSpan-1,Z=M.row-o,ot=$-R+1-u+Z;d(zr,ot>0,"invalid effected cell, newSpanned <= 0");const st=yn(t.doc);m.set(I,{newContainerId:st,rowSpan:ot})});for(let I=o;I<l.length;I++){const M=l[I];for(let R=0;R<M.length;R++){const $=M[R],Z=m.get($);Z&&(M[R]=Z.newContainerId)}}const C=Y.default(t.getBlockData(e));a.forEach(I=>{yc(C,I)}),f.forEach((I,M)=>{d(zr,I>=1,"invalid modified rowSpan, rowSpan < 1"),I===1?delete C[`${M}_rowSpan`]:C[`${M}_rowSpan`]=I}),m.forEach((I,M)=>{yc(C,M);const{newContainerId:R,rowSpan:$}=I;d(zr,$>=1,"invalid newContainerData, rowSpan < 1"),$>1&&(C[`${R}_rowSpan`]=$);const Z=i.getCellByContainerId(M).colSpan;Z>1&&(C[`${R}_colSpan`]=Z)});const v=l[o]?l[o][0]:l[o-1][0],B=t.getChildContainerData(v)[0],y=et.virtualCellContainersGridToChildren(l),S={...C,rows:C.rows-u,children:y};er(S),t.undoManager.runInGroup(()=>{t.updateBlockData(e,S,At(t,B.id,0)),t.deleteChildContainers(Array.from(a)),t.deleteChildContainers(Array.from(m.keys()))})}const bs=w("table-range");function wc(n){d(bs,!n.isSimple(),"must be complex selection range");const{anchor:t,focus:e}=n;d(bs,!t.isSimple(),"invalid start pos type"),d(bs,!e.isSimple(),"invalid end pos type");const o=n.getEditor();d(bs,t.blockId===e.blockId,"invalid range, not same block");const r=o.getBlockById(t.blockId);d(bs,rt(r)==="table","invalid block type, not a table block");const i=jt(r),s=et.fromTable(i),l=s.getCellByContainerId(t.childContainerId),c=s.getCellByContainerId(e.childContainerId),a=Math.min(l.row,c.row),u=Math.max(l.row,c.row),f=Math.min(l.col,c.col),m=Math.max(l.col,c.col),C=s.getCell({row:a,col:f}),v=s.getCell({row:u,col:m});return{editor:o,block:r,table:i,startCell:C,endCell:v,startRow:a,startCol:f,endRow:u,endCol:m}}const vh=w("split-cell");function kh(n,t,e){const o=et.fromBlock(t),r=o.getRealCell(e);d(vh,!r.virtual,"should not split virtual cell"),d(vh,r.colSpan>1||r.rowSpan>1,"cell does not has span data");const i=o.getVirtualCellContainersGrid();for(let f=0;f<r.rowSpan;f++)for(let m=0;m<r.colSpan;m++){if(f===0&&m===0)continue;const C=f+r.row,v=m+r.col,B=yn(n.doc);i[C][v]=B}const s=n.getBlockData(t),l=Y.default(s);l[`${r.containerId}_colSpan`]=null,l[`${r.containerId}_rowSpan`]=null,l.children=et.virtualCellContainersGridToChildren(i);const a=n.getChildContainerData(r.containerId)[0];d(vh,a,"no child block");const u=At(n,a.id,0);er(l),n.updateBlockData(t,l,u)}function qB(n,t,e){e.forEach(o=>{const r=et.fromBlock(t).getCell(o);(r.virtual||r.colSpan>1||r.rowSpan>1)&&kh(n,t,o)})}function p5(n,t,e){if(e.isSimple())return!1;const{start:o,end:r}=e;if(o.blockId!==r.blockId||n.getBlockById(o.blockId)!==t||rt(t)!=="table")return!1;const{startCell:s,endCell:l}=wc(e);return!(s.cell!==l.cell||s.colSpan===1&&s.rowSpan===1)}function yh(n){const{editor:t,block:e,startRow:o,startCol:r,endRow:i,endCol:s}=wc(n),l=[];for(let c=o;c<=i;c++)for(let a=r;a<=s;a++)l.push({row:c,col:a});return qB(t,e,l),!0}const Ur=w("merge-cells");function C5(n,t,e){if(e.isSimple())return!1;const{start:o,end:r}=e;if(o.blockId!==r.blockId||n.getBlockById(o.blockId)!==t||rt(t)!=="table")return!1;const{startCell:s,endCell:l}=wc(e);return s.cell!==l.cell}function b5(n){const t=wc(n),e=t.endCell,o=e.row+e.rowSpan-1,r=e.col+e.colSpan-1,i=q(t.block),s=t.editor;yh(n);const l=s.getBlockById(i),c=jt(l),{startRow:a,startCol:u}=t,f=Y.default(s.getBlockData(l));d(Ur,f.children,"no table children");const m=et.fromTable(c),C=[];for(let mt=a;mt<=o;mt++)for(let ut=u;ut<=r;ut++){const yt=m.getCell({row:mt,col:ut});d(Ur,!yt.virtual,"cell is virtual"),C.push(yt)}d(Ur,C.length>0,"no selected cells");const v=C[0],B=C.slice(1),y=m.getCellByContainerId(v.containerId).container,S=[];B.forEach(mt=>{const ut=m.getCellByContainerId(mt.containerId).container,yt=U(ut);if(!Bd(s,ut)){const se=R0(s,yt);s.insertDocAt(y,Ge(y),se)}S.push(yt)});const I=U(y),M=r-u+1,R=o-a+1;f[`${I}_colSpan`]=M,f[`${I}_rowSpan`]=R,S.forEach(mt=>{d(Ur,f.children,"no table children");const ut=f.children.indexOf(mt);d(Ur,ut>0,"no deleted container"),f.children.splice(ut,1)});const $=f,ot=s.getChildContainerData(I)[0];d(Ur,ot,"no child block");const st=At(s,ot.id,0);er($),s.updateBlockData(l,$,st),s.deleteChildContainers(S)}const wh=10,WB=["table/merge-cells","table/split-cell","table/insert-column","table/insert-row","table/delete-rows","table/delete-columns","table/delete"];class Bh{constructor(){h(this,"id","TableBlockCommandProvider")}getAvailableCommands(t,e,o){if(rt(e)!=="table")return[];const r={blockId:q(e),blockKind:Qe(t,e),blockType:rt(e)},i=[];C5(t,e,o)&&i.push({id:"table/merge-cells",name:T.t("table.mergeCell"),icon:Aw,groupIndex:wh,...r}),p5(t,e,o)&&i.push({id:"table/split-cell",name:T.t("table.splitCell"),icon:Ow,groupIndex:wh,...r});const s=m5(t,e,o),l=g5(t,e,o);return s&&l&&i.push({id:"table/delete",name:T.t("table.deleteTable"),icon:_w,groupIndex:wh,...r}),i}executeCommand(t,e,o,r,i,s){return rt(e)!=="table"||!new Set(WB).has(r.id)?!1:r.id==="table/merge-cells"?(b5(o),!0):r.id==="table/split-cell"?(yh(o),!0):r.id==="table/delete-columns"?(Ch(o),!0):r.id==="table/delete-rows"?(bh(o),!0):r.id==="table/delete"?(t.deleteBlock(e),!0):!1}}var v5=(n=>(n.COL_TITLE_TABLE="col-title-table",n.COL_TITLE_ITEM="col-title-item",n.STRIPE_STYLE_TABLE="stripe-style-table",n.NO_BORDER="table-no-border",n))(v5||{});const Eh=6,vs=20;function GB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasColTitle:!0};n.updateBlockData(t,o)}function ZB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasColTitle:!1};n.updateBlockData(t,o)}function YB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasRowTitle:!0};n.updateBlockData(t,o)}function QB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasRowTitle:!1};n.updateBlockData(t,o)}function KB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),isStripeStyle:!0};n.updateBlockData(t,o)}function JB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),isStripeStyle:!1};n.updateBlockData(t,o)}function XB(n,t,e){if(!n.isBlockWritable(t))return;const r={...Y.default(n.getBlockData(t)),noBorder:!e};n.updateBlockData(t,r)}const Ih=w("get-selected-containers");function xh(n,t,e,o){d(Ih,e.blockId===o.blockId,"only allow select in single table block"),d(Ih,q(t)===e.blockId,"only allow select in single table block");const r=et.fromBlock(t),i=r.getCellByContainerId(e.childContainerId),s=r.getCellByContainerId(o.childContainerId);if(e.custom===void 0||o.custom===void 0)return r.getCells(i,s).map(y=>r.getCellContainer(y));const{fromCol:l,toCol:c,fromRow:a,toRow:u}=an(t,e,o),f=new Set,m=[];return r.sub({row:a,col:l},{row:u,col:c}).forEach(v=>{v.forEach(B=>{const y=r.getCellByContainerId(B.containerId);y.col<l||y.row<a||y.col+y.colSpan-1>c||y.row+y.rowSpan-1>u||f.has(B.containerId)||(f.add(B.containerId),m.push(y.container))})}),m}function tE(n,t,e){d(Ih,t.blockId===e.blockId,"only allow select in single table block");const o=n.getBlockById(t.blockId);return xh(n,o,t,e)}const nr=w("table-cell-dom");function eE(n,t,e){let o=n.getBlockById(e);for(;o;){const r=o.closest("td");d(nr,r,"no parent cell");const i=F(r);if(d(nr,i,"no parent block"),i===t)return r;o=i}return d(nr,!1,"filed to get cell by child block id"),null}function Gn(n,t,e){if(n.getBlockById(e.blockId)===t&&!e.isSimple())return d(nr,e.childContainerId,"block position must have childContainerId attribute"),e;const r=eE(n,t,e.blockId),i=U(Cs(r));return wt(t,i)}function Th(n,t){const e=n.selection.range,o=Gn(n,t,e.start),r=Gn(n,t,e.end);return an(t,o,r)}function k5(n,t,e,o){d(nr,Ht(t),"invalid table block");const r=Tn(n,t),i=()=>{const l=r.querySelector(".table-border-bar-container.top");d(nr,l,"no top border bar container"),l.querySelectorAll(".table-border-bar-cell.top").forEach(a=>{const u=parseInt(a.getAttribute("data-top-index")||"0",10);o.includes(u)?A(a,"danger"):z(a,"danger")})},s=()=>{const l=r.querySelector(".table-border-bar-container.left");d(nr,l,"no left border bar container"),l.querySelectorAll(".table-border-bar-cell.left").forEach(a=>{const u=parseInt(a.getAttribute("data-left-index")||"0",10);e.includes(u)?A(a,"danger"):z(a,"danger")})};i(),s()}function Vr(n,t,e=!0,o){const i=et.fromBlock(t).map(u=>u),{fromCol:s,toCol:l,fromRow:c,toRow:a}=Th(n,t);for(let u=0;u<i.length;u++){const f=i[u];for(let m=0;m<f.length;m++){const C=f[m],v=o?m>=s&&m+C.colSpan-1<=l:u>=c&&u+C.rowSpan-1<=a;e&&v?C.virtual||A(C.cell,"danger"):C.virtual||z(C.cell,"danger")}}}function qr(n,t,e=!0,o){const r=new Set,i=new Set;if(!e){k5(n,t,Array.from(r),Array.from(i));return}const{fromCol:s,toCol:l,fromRow:c,toRow:a}=Th(n,t);if(o)for(let u=s;u<=l;u++)i.add(u);else for(let u=c;u<=a;u++)r.add(u);k5(n,t,Array.from(r),Array.from(i))}function y5(n,t,e){const{fromCol:o,toCol:r,fromRow:i,toRow:s}=Th(n,t),l=et.fromBlock(t);let c=null,a=null;return e?(c=l.getCell({col:o,row:0}),a=l.getCell({col:r,row:l.rowCount-1}),Wt(n,{anchor:wt(t,c.containerId,{colIndex:o,rowIndex:0}),focus:wt(t,a.containerId,{colIndex:r,rowIndex:l.rowCount-1})})):(c=l.getCell({col:0,row:i}),a=l.getCell({col:l.colCount-1,row:s}),Wt(n,{anchor:wt(t,c.containerId,{colIndex:0,rowIndex:i}),focus:wt(t,a.containerId,{colIndex:l.colCount-1,rowIndex:s})}))}function nE(n,t){const e=n.selection.range,o=Gn(n,t,e.start),r=Gn(n,t,e.end);return xh(n,t,o,r)}const w5=["style-bg-color-0","style-bg-color-1","style-bg-color-2","style-bg-color-3","style-bg-color-4","style-bg-color-5","style-bg-color-6","style-bg-color-7","style-bg-color-8","style-bg-color-9","style-bg-color-10","style-bg-color-11","style-bg-color-12","style-bg-color-13"];function B5(n){return`style-bg-color-${n}`}function ks(n){return`${n}_background`}function oE(n,t,e){const o=jt(n),s=(e!=null?e:et.fromTable(o)).getCell(t).cell;for(let l=0;l<w5.length;l++){const c=w5[l];if(nt(s,c))return c}}function E5(n,t,e){if(!n.isBlockWritable(t))return;const o=n.selection.range,i={...Y.default(n.getBlockData(t))},s=Gn(n,t,o.start),l=Gn(n,t,o.end);if(o.isSimple()){const c=s.childContainerId;e===-1?i[ks(c)]=void 0:i[ks(c)]=B5(e)}else{const c=et.fromBlock(t),a=an(t,s,l),u=new Set;for(let f=a.fromRow;f<=a.toRow;f++)for(let m=a.fromCol;m<=a.toCol;m++){const C=c.getCell({row:f,col:m});!u.has(C.containerId)&&C.col>=a.fromCol&&C.row>=a.fromRow&&C.col+C.colSpan-1<=a.toCol&&C.row+C.rowSpan-1<=a.toRow&&(u.add(C.containerId),e===-1?i[ks(C.containerId)]=void 0:i[ks(C.containerId)]=B5(e))}}n.updateBlockData(t,i)}function rE(n,t,e){if(!n.isBlockWritable(t))return;const r={...Y.default(n.getBlockData(t)),chart:e};n.updateBlockData(t,r)}const I5=w("table-chart");function iE(n,t){const e=Tn(n,t);if(e){const o=e.querySelector(".editor-table-chart");if(o){const r=o.chartObject;r&&r.destroy(),o.remove()}}}async function sE(n,t){if(!n.isBlockWritable(t))return;if(!!!n.getBlockData(t).chart){iE(n,t);return}const r=[],i=et.fromBlock(t),s=["line","bar","pie","radar"];let l=i.getCell({row:0,col:0}).container.innerText.trim().toLowerCase();new Set(s).has(l)||(l=s[0]);const c=[];for(let B=1;B<i.colCount;B++)c.push(i.getCell({row:0,col:B}).container.innerText);for(let B=1;B<i.rowCount;B++){const y=i.getCell({row:B,col:0}),I=y.container.innerText,M=[];for(let se=1;se<i.colCount;se++){const eo=i.getCell({row:B,col:se}).container.innerText,ee=Number.parseFloat(eo)||0;M.push(ee)}let R;const $=oE(t,y,i);$?R=window.getComputedStyle(n.rootElement).getPropertyValue(`--${$}`).trim():R=window.getComputedStyle(n.rootElement).getPropertyValue("--background-color").trim();let[Z,ot,st,mt]=R?Wa.fromString(R).toRgbaArray():[];if(!Z&&!ot&&!st&&!mt){const se=(B-1)%n.options.colors.length;R=n.options.colors[se],[Z,ot,st,mt]=Wa.fromString(R).toRgbaArray()}const ut=R,yt=Wa.fromRgba([Z,ot,st,mt/3]).toHexString();r.push({label:I,data:M,borderColor:ut,backgroundColor:yt,borderWidth:2})}const a=Tn(n,t);let u=null,f=a.querySelector(".editor-table-chart");f?u=f.chartObject:f=b("div",["editor-table-chart"],a);const m=f;d(I5,m,"no chart container");const C=n.getComponentOptions("table"),v=(C==null?void 0:C.chartCdn)||"https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js";try{await Ro(v,"editor-chartjs"),u&&l!==u.config.type&&(u.destroy(),u=null,Array.from(f.querySelectorAll(".editor-chartjs-canvas")).forEach(S=>{S.remove()}));const B=Ga.default({},{type:l,data:{datasets:r,labels:c},options:{onClick:()=>{n.selection.selectBlock(t,0,0)}}});if(u)Ga.default(u.config,B),u.update();else{const S=b("canvas",["editor-chartjs-canvas"],m).getContext("2d");u=new window.Chart(S,B),f.chartObject=u}}catch(B){I5.error(`failed to resolve chart cdn: ${JSON.stringify(B)}`)}}async function x5(n,t){await qe.lock("updateTableChart");try{await sE(n,t)}finally{qe.release("updateTableChart")}}const T5=Xt.default(x5,1e3);let S5=null;function Sh(n,t,e){if(S5!==t&&(T5.flush(),S5=t),e.updateNow){x5(n,t);return}T5(n,t)}function Dh(n,t){Ht(t)&&Sh(n,t,{updateNow:!1})}function lE(n,t){Ht(t)&&Sh(n,t,{updateNow:!0})}const je={SCROLL:"container-scroll-tool",COMMON:"container-border-shadow",RIGHT:"container-right-border-shadow",LEFT:"container-left-border-shadow",LAYOUT_SIGN:"container-layout-border-shadow",ACTIVE:"active"},Bc={SCROLL_BAR:"container-scrollbar",FIXED:"fixed"},bo={SCROLL_CONTAINER:"scroll-container",TOOL:"container-scroll-tool",CONTAINER:"scroll-container-root",MAC:"mac",SCROLL_AREA:"scroll-area"};function Ec(n,t){return n.containers.get(t)}function D5(n){return n.closest(`.${bo.SCROLL_CONTAINER}`)}function dn(n){return n.firstElementChild}function Ae(n){return n.closest(`.${bo.CONTAINER}`)}function ys(n){const t=Ae(n);let e=t.querySelector(`:scope >.${bo.TOOL}`);return e||(e=b("div",[bo.TOOL],t)),e}function cE(n){return Ae(n).firstElementChild}function Ic(n){let t;return n instanceof HTMLElement?t=n.offsetWidth:t=Number.parseInt(getComputedStyle(n).width,10),n.getBoundingClientRect().width/t}function He(n,t){const e=Ic(n);return t/e}function ws(n){const t=window.getComputedStyle(n),e=Ic(n);return{paddingBottom:parseFloat(t.paddingBottom)*e,paddingTop:parseFloat(t.paddingTop)*e,paddingLeft:parseFloat(t.paddingLeft)*e,paddingRight:parseFloat(t.paddingRight)*e}}function Wr(n){const t=Ic(n);return{scrollLeft:n.scrollLeft*t,scrollWidth:n.scrollWidth*t,clientWidth:n.clientWidth*t,clientHeight:n.clientHeight*t}}function aE(n,t){const e=Ic(n);return n[t]*e}function Lh(n,t){const e=Ae(t),o=Ec(n,e),r=(o==null?void 0:o.safeRightSpace)||0,i=(o==null?void 0:o.safeLeftSpace)||0,l=(o==null?void 0:o.locatingContainer).getBoundingClientRect(),c=e.getBoundingClientRect(),a=c.width;let u=Math.floor(c.left-l.left-i);u<0&&(u=0);let f=l.right;f-=r;let m=f-c.right;return m<0&&(m=0),u=Math.round(u),m=Math.round(m),{originWidth:a,maxLeft:u,maxRight:m}}function dE(n,t){const e=Lh(n,t),{maxLeft:o}=e;t.style.marginLeft=`${He(t,0-o)}px`,t.style.paddingLeft=`${He(t,o)}px`}function uE(n,t){const e=Lh(n,t);t.style.marginRight=`${He(t,0-e.maxRight)}px`}function hE(n){if(n!==document.documentElement&&n!==document.body)return n.getBoundingClientRect();const t=0,e=0,o=document.documentElement.clientWidth,r=document.documentElement.clientHeight;return new DOMRect(t,e,o,r)}const L5=w("scroll-bar-handle"),fE=2;function Gr(n){const t=ys(n);let e=t.querySelector(`.${Bc.SCROLL_BAR}`);return e||(e=b("div",[Bc.SCROLL_BAR],t)),d(L5,e instanceof HTMLDivElement,"invalid child for container tools"),e.firstElementChild||b("div",[],e),e}function xc(n,t){const e=D5(t),o=Gr(e),{scrollWidth:r,clientWidth:i}=Wr(e),{paddingLeft:s,paddingRight:l}=ws(t);e.style.marginLeft="",e.style.paddingLeft="",e.style.marginRight="";const c=Lh(n,e),{originWidth:a,maxRight:u}=c;uE(n,e),dE(n,e);const f=r-i;d(L5,o.firstElementChild instanceof HTMLDivElement,"invalid child for scroll bar"),o.style.width=`${He(e,a+u-s-l)}px`,o.firstElementChild.style.width=`${He(e,a+u+f-s-l)}px`}function mE(n,t){const e=dn(n),{paddingLeft:o}=ws(e);if(nt(t,"fixed")){const i=Ae(n).getBoundingClientRect();t.style.left=`${He(n,i.left+o)}px`}else t.style.left=`${He(n,o)}px`}function Zr(n,t){var I;const e=n.getParentScrollContainer(),o=hE(e),r=t.getBoundingClientRect(),i=Gr(t),s=i.getBoundingClientRect(),l=Ec(n,Ae(t)),c=(l==null?void 0:l.barFloatWindowBottom)||0,a=dn(t),{paddingTop:u,paddingBottom:f}=ws(a),{scrollWidth:m,clientWidth:C}=Wr(t),v=document.documentElement.clientHeight-c,B=o.top+Wr(e).clientHeight-v,y=v+Math.min(0,B);if(m>C&&r.top+u<y-s.height&&r.bottom>y-s.height+f&&!((I=l==null?void 0:l.isSetScale)!=null&&I.call(l))){A(i,Bc.FIXED);const M=B>0?c:0;i.style.bottom=`${Math.max(document.documentElement.clientHeight-o.bottom,0)+fE+M}px`}else z(i,Bc.FIXED),i.style.bottom=`${He(t,f-s.height)}px`;mE(t,i)}class gE{constructor(t,e){h(this,"intersectionObserver");h(this,"handleIntersection",t=>{t.forEach(e=>{this.containers.get(Ae(e.target))?(this.handleIntersectionEntry(e),this.callback(e)):this.intersectionObserver.unobserve(e.target)})});h(this,"handleIntersectionEntry",t=>{const e=t.target;Zr(this.scrollCore,e);const o=dn(e);xc(this.scrollCore,o)});this.scrollCore=t,this.callback=e;const r={root:this.scrollCore.getParentScrollContainer(),rootMargin:"20px",threshold:0};this.intersectionObserver=new IntersectionObserver(this.handleIntersection,r)}get containers(){return this.scrollCore.containers}bind(t){this.unbind(t),this.intersectionObserver.observe(t)}unbind(t){this.intersectionObserver.unobserve(t)}destroy(){this.intersectionObserver.disconnect()}}const or=w("container-scroll-shadow");function M5(n,t,e){const o=n,r=t.getBoundingClientRect(),i=e.getBoundingClientRect(),{paddingTop:s,paddingBottom:l}=ws(e);o.style.top=`${He(t,i.top-r.top+s)}px`,o.style.bottom=`${He(t,r.bottom-i.bottom+l)}px`}function R5(n,t){const e=n;t<24?e.style.width=`${(t/3).toFixed(2)}px`:e.style.width=""}function pE(n){const t=ys(n);d(or,t,"no container tools");let e=t.querySelector(`.${je.LEFT}`);if(!e){const l=dn(n),c=[je.COMMON,je.LEFT];e=b("div",c,t),d(or,e instanceof HTMLDivElement,"invalid child for container tools"),M5(e,n,l)}d(or,e instanceof HTMLElement,"invalid child for container tools");const r=Ae(n).getBoundingClientRect(),i=n.getBoundingClientRect();e.style.left=`${He(n,i.left-r.left)}px`;const s=Wr(n).scrollLeft;d(or,e instanceof HTMLDivElement,"invalid child for container tools"),R5(e,s),A(e,je.ACTIVE)}function CE(n){const t=ys(n);let e=t.querySelector(`.${je.RIGHT}`);if(!e){const u=dn(n),f=[je.COMMON,je.RIGHT];e=b("div",f,t),d(or,e instanceof HTMLDivElement,"no div, create shadow failed"),M5(e,n,u)}d(or,e instanceof HTMLElement,"");const r=Ae(n).getBoundingClientRect(),i=n.getBoundingClientRect();e.style.right=`${He(n,r.right-i.right)}px`;const{scrollWidth:s,scrollLeft:l,clientWidth:c}=Wr(n),a=s-l-c;d(or,e instanceof HTMLDivElement,"no shadow element"),R5(e,a),A(e,je.ACTIVE)}function bE(n){const e=ys(n).querySelector(`.${je.LEFT}`);e&&z(e,je.ACTIVE)}function vE(n){const e=ys(n).querySelector(`.${je.RIGHT}`);e&&z(e,je.ACTIVE)}function Bs(n){const{scrollLeft:t,scrollWidth:e,clientWidth:o}=Wr(n),r=dn(n),{paddingLeft:i,paddingRight:s}=ws(r),l=aE(r,"offsetLeft");e-i<=o-s||e-i<=t+o-s?vE(n):CE(n),r&&t>=l+i?pE(n):bE(n)}class kE{constructor(t,e){h(this,"resizeObserver");h(this,"handleResizeEntry",t=>{const e=t.target,o=dn(e);Bs(e),xc(this.scrollCore,o),Zr(this.scrollCore,e),this.callback(e)});h(this,"handleContentResize",t=>{t.forEach(e=>{this.containers.get(Ae(e.target))?this.handleResizeEntry(e):this.unbind(e.target)})});this.scrollCore=t,this.callback=e,this.resizeObserver=new ResizeObserver(this.handleContentResize)}get containers(){return this.scrollCore.containers}bind(t){this.unbind(t),this.resizeObserver.observe(t)}unbind(t){this.resizeObserver.unobserve(t)}destroy(){this.resizeObserver.disconnect()}}const A5=w("container-scroll-observer");class yE{constructor(t,e){h(this,"handleContentScroll",t=>{const e=t.target;d(A5,e instanceof Element,"invalid target for scroll event");const o=Gr(e);o.removeEventListener("scroll",this.handleScroll);const r=!0;this.fixScrollXPos(e,e.scrollLeft,r),this.bind(o),Bs(e),this.callback(e)});h(this,"handleScroll",t=>{const e=t.target;d(A5,e instanceof HTMLElement,"");const o=e.scrollLeft,r=!1,i=cE(e);this.unbindContentScroll(i),this.fixScrollXPos(i,o,r),this.bindContentScroll(i),Bs(i),this.callback(i)});h(this,"handlePrevent",t=>{t.stopPropagation()});h(this,"bindContentScrollCore",t=>{this.unbindContentScroll(t),t.addEventListener("scroll",this.handleContentScroll)});h(this,"unbindContentScroll",t=>{t.removeEventListener("scroll",this.handleContentScroll)});h(this,"bindContentScroll",Xt.default(this.bindContentScrollCore,300));h(this,"bind",Xt.default(this.bindCore,200));this.scrollCore=t,this.callback=e}fixScrollXPos(t,e,o){const r=Gr(t);o||(t.scrollLeft=e),o&&r.scrollLeft!==e&&(r.scrollLeft=e)}bindCore(t){this.unbind(t),t.addEventListener("scroll",this.handleScroll),t.addEventListener("mousedown",this.handlePrevent)}unbind(t){t.removeEventListener("scroll",this.handleScroll),t.removeEventListener("mousedown",this.handlePrevent)}}class wE{constructor(t){h(this,"scrollContainers",new Set);h(this,"handleParentContainerScroll",()=>{this.scrollContainers.forEach(t=>{Zr(this.scrollCore,t)})});h(this,"bindScrollContainer",t=>{const e=this.scrollContainers.size===0;this.scrollContainers.add(t),e&&this.eventTarget.addEventListener("scroll",this.handleParentContainerScroll)});h(this,"unbindScrollContainer",t=>{let e=!1;this.scrollContainers.has(t)&&(this.scrollContainers.delete(t),e=this.scrollContainers.size===0),e&&this.eventTarget.removeEventListener("scroll",this.handleParentContainerScroll)});this.scrollCore=t}get eventTarget(){const t=this.scrollCore.getParentScrollContainer();return t===document.documentElement?document:t}destroy(){this.eventTarget.removeEventListener("scroll",this.handleParentContainerScroll),this.scrollContainers.clear()}}const BE=w("scroll-wrap-resize-observer");class EE{constructor(t){h(this,"resizeObserver");h(this,"handleScrollWrapResize",t=>{t.forEach(e=>{this.containers.get(Ae(e.target))?this.handleScrollWrapResizeEntry(e):this.unbind(e.target)})});h(this,"handleScrollWrapResizeEntry",t=>{const e=t.target;d(BE,e instanceof HTMLElement,"invalid target for observer entry");const o=D5(e);xc(this.scrollCore,e),Bs(o),Zr(this.scrollCore,o)});this.scrollCore=t,this.resizeObserver=new ResizeObserver(this.handleScrollWrapResize)}get containers(){return this.scrollCore.containers}bind(t){this.unbind(t),this.resizeObserver.observe(t)}unbind(t){this.resizeObserver.unobserve(t)}destroy(){this.resizeObserver.disconnect()}}class IE{constructor(t,e){h(this,"resizeObserver");h(this,"scrollContainersMap",new Map);h(this,"handleResizeEntry",t=>{t==null||t.forEach(e=>{const o=dn(e);Bs(e),xc(this.scrollCore,o),Zr(this.scrollCore,e),this.callback(e)})});h(this,"handleResize",t=>{t.forEach(e=>{const o=this.scrollContainersMap.get(e.target);o!=null&&o.length&&this.handleResizeEntry(o)})});this.scrollCore=t,this.callback=e,this.resizeObserver=new ResizeObserver(this.handleResize)}bind(t){var r,i;const e=Ae(t),o=(r=Ec(this.scrollCore,e))==null?void 0:r.locatingContainer;this.scrollContainersMap.has(o)?(i=this.scrollContainersMap.get(o))==null||i.push(t):(this.scrollContainersMap.set(o,[t]),this.resizeObserver.observe(o))}unbind(t){var i,s;const e=Ae(t),o=(i=Ec(this.scrollCore,e))==null?void 0:i.locatingContainer;if(!o)return;const r=this.scrollContainersMap.get(o);this.scrollContainersMap.set(o,(r==null?void 0:r.filter(l=>l!==t))||[]),(s=this.scrollContainersMap.get(o))!=null&&s.length||(this.resizeObserver.unobserve(o),this.scrollContainersMap.delete(o))}destroy(){this.scrollContainersMap.clear(),this.resizeObserver.disconnect()}}const uz="";class xE extends Yt.TypedEmitter{constructor(e){super();h(this,"containerIntersectionObserver",null);h(this,"containerResizeObserver",null);h(this,"containerScrollObserver",null);h(this,"parentContainerScrollObserver",null);h(this,"scrollWrapResizeObserve",null);h(this,"locatingContainerResizeObserver",null);h(this,"isWindowEventBind",!1);h(this,"containers",new Map);h(this,"handleScrollContainerScroll",e=>{this.emit("scroll",this,e)});h(this,"handleResize",e=>{this.emit("resize",this,e)});h(this,"handleIntersection",e=>{const o=e.target,r=dn(o);e.isIntersecting?(this.load(),this.bindCore(o,r)):this.unbindCore(o,r)});h(this,"handleWindowEffect",()=>{var e;(e=this.getScrollContainerInViewable())==null||e.forEach(o=>{Zr(this,o)})});this.parentContainer=e}load(){this.containerResizeObserver||(this.containerResizeObserver=new kE(this,this.handleResize)),this.containerScrollObserver||(this.containerScrollObserver=new yE(this,this.handleScrollContainerScroll)),this.parentContainerScrollObserver||(this.parentContainerScrollObserver=new wE(this)),this.scrollWrapResizeObserve||(this.scrollWrapResizeObserve=new EE(this)),this.locatingContainerResizeObserver||(this.locatingContainerResizeObserver=new IE(this,this.handleResize)),this.isWindowEventBind||(window.addEventListener("resize",this.handleWindowEffect),this.getParentScrollContainer()!==document.documentElement&&window.addEventListener("scroll",this.handleWindowEffect))}getParentScrollContainer(){return this.parentContainer}getScrollContainerInViewable(){var e;return(e=this.parentContainerScrollObserver)==null?void 0:e.scrollContainers}unbindCore(e,o){var i,s,l,c,a,u;const r=Gr(e);(i=this.containerScrollObserver)==null||i.unbindContentScroll(e),(s=this.containerScrollObserver)==null||s.unbind(r),(l=this.scrollWrapResizeObserve)==null||l.unbind(o),(c=this.containerResizeObserver)==null||c.unbind(e),(a=this.parentContainerScrollObserver)==null||a.unbindScrollContainer(e),(u=this.locatingContainerResizeObserver)==null||u.unbind(e)}bindCore(e,o){var i,s,l,c,a,u;if(this.unbindCore(e,o),!e.closest("body"))return;const r=Gr(e);(i=this.containerScrollObserver)==null||i.bindContentScrollCore(e),(s=this.containerScrollObserver)==null||s.bindCore(r),(l=this.scrollWrapResizeObserve)==null||l.bind(o),(c=this.containerResizeObserver)==null||c.bind(e),(a=this.parentContainerScrollObserver)==null||a.bindScrollContainer(e),(u=this.locatingContainerResizeObserver)==null||u.bind(e)}bind(e,o){this.containers.set(e,o);const r=e.firstElementChild;this.containerIntersectionObserver||(this.containerIntersectionObserver=new gE(this,this.handleIntersection)),this.containerIntersectionObserver.bind(r)}unbind(e){var i;const o=e.firstElementChild,r=dn(o);this.unbindCore(o,r),this.containers.delete(e),(i=this.containerIntersectionObserver)==null||i.unbind(o),this.containers.size||this.destroy()}destroy(){var e,o,r,i,s;this.containers.forEach((l,c)=>{this.unbind(c)}),this.containers.clear(),(e=this.parentContainerScrollObserver)==null||e.destroy(),(o=this.containerIntersectionObserver)==null||o.destroy(),(r=this.containerResizeObserver)==null||r.destroy(),(i=this.scrollWrapResizeObserve)==null||i.destroy(),(s=this.locatingContainerResizeObserver)==null||s.destroy(),window.removeEventListener("resize",this.handleWindowEffect),window.removeEventListener("scroll",this.handleWindowEffect)}}const O5=w("scroll-container"),Tc=new Map;class TE extends Yt.TypedEmitter{constructor(){super(...arguments);h(this,"scrollListener");h(this,"options");h(this,"scrollContainerElement");h(this,"init",e=>{this.options=e;const o=b("div",[bo.CONTAINER],e.parentElement);xt.isMac&&A(o,bo.MAC);const r=b("div",[bo.SCROLL_CONTAINER],o),i=b("div",[bo.SCROLL_AREA],r);i.style.paddingLeft=e.paddingLeft?`${e.paddingLeft}px`:"",i.style.paddingTop=e.paddingTop?`${e.paddingTop}px`:"",i.style.paddingBottom=e.paddingBottom?`${e.paddingBottom}px`:"",i.style.paddingRight=e.paddingRight?`${e.paddingRight}px`:"",i.appendChild(e.childElement);const s=e.parentContainer;this.scrollListener=Tc.get(s),this.scrollListener||(this.scrollListener=new xE(s),Tc.set(s,this.scrollListener)),this.scrollListener.unbind(o),this.scrollListener.bind(o,e),this.scrollListener.on("scroll",this.handleContainerScroll),this.scrollListener.on("resize",this.handleResize),this.scrollContainerElement=r});h(this,"handleContainerScroll",(e,o)=>{o===this.scrollContainerElement&&this.emit("scroll",this)});h(this,"handleResize",(e,o)=>{o===this.scrollContainerElement&&this.emit("scroll",this)})}get rootElement(){return this.scrollContainerElement}get contentElement(){return d(O5,this.scrollContainerElement,"scrollContainerElement cannot be undefined"),dn(this.scrollContainerElement)}get scrollOptions(){return d(O5,this.options,"options cannot be undefined"),{...this.options}}handleBaseListenerDestroy(e){e.destroy()}destroy(){var o;(o=this.scrollListener)==null||o.off("scroll",this.handleContainerScroll);const e=Ae(this.contentElement);e&&Tc.forEach((r,i)=>{r.unbind(e),r.containers.size===0&&(this.handleBaseListenerDestroy(r),Tc.delete(i))})}}function SE(){return new TE}const Sc=100,DE=40,Mh=w("column-width");function LE(n,t,e){_B(n,t).style.width=`${e}px`}function ME(n){const e=Array.from(n.querySelector("colgroup").children).map(c=>c.getBoundingClientRect().width);if(e[0]!==0)return e;const o=et.fromTable(n),r=Array(o.colCount).fill(-1),i=n.getBoundingClientRect().left;o.toRealCells(o.cells).forEach(c=>{const a=c.col+c.colSpan-1;r[a]===-1&&(r[a]=c.cell.getBoundingClientRect().right-i)}),Mh.debug(`cellRightOffsets1: ${r.join()}`);for(let c=0;c<r.length;c++){const a=r[c];if(a===-1||c===0)continue;let u=c-1;for(;r[u]===-1&&(u--,u!==-1););const f=u===-1?0:r[u],C=(a-f)/(c-u);for(let v=u+1;v<c;v++)r[v]=f+C*(v-u)}Mh.debug(`cellRightOffsets2: ${r.join()}`);const s=[];let l=0;for(let c=0;c<r.length;c++){const a=r[c];s.push(a-l),l=a}return Mh.debug(`widths: ${s.join()}`),s}function Es(n){return Array.from(n.querySelector("colgroup").children).map(o=>o.getBoundingClientRect().width||Number.parseInt(o.style.width,10)||100)}const RE=w("table-resize-gripper"),_5=7,Rh=(_5-1)/2,AE=3;function OE(n,t,e){const{rows:o}=n;for(let r=0;r<o.length;r++){const i=o[r],s=Array.from(i.cells);for(let l=0;l<s.length;l++){const c=s[l],a=c.getBoundingClientRect(),u=Math.round(a.right);if(Math.abs(t-u)<=Rh&&a.top<=e&&e<=a.bottom)return c}}return null}function _E(n){return!!n.rootContainer.querySelector(".table-resize-gripper")}function Ah(n,t){return Tn(n,t).querySelector(".table-resize-gripper")}function N5(n,t){const e=Ah(n,t);d(RE,!e,"resize gripper has already exists");const o=Tn(n,t),r=b("div",["table-resize-gripper","table-indicator"],o);return b("div",["table-resize-gripper-indicator"],r),r}function $5(n,t,e){let o=Ah(n,t);o||(o=N5(n,t));const i=jt(t).getBoundingClientRect(),s=e.getBoundingClientRect(),l=0,c=i.height,a=n.getCustom(Co(t)).contentElement.getBoundingClientRect(),u=s.right-a.left;o.style.left=`${u-Rh-Eh-vs}px`,o.style.top=`${l}px`,o.style.height=`${c}px`,o.style.width=`${_5}px`}function Oh(n){n.rootContainer.querySelectorAll(".table-resize-gripper").forEach(t=>{t.remove()})}function NE(n,t,e){const r={...n.getBlockData(t),colsWidth:e};n.updateBlockData(t,r)}function $E(n,t,e,o){const r=t,i=et.fromTable(e),s=i.getCellByCellElement(r),l=s.col+s.colSpan-1,c=Es(e);let a=o;const u=(m,C)=>{const v=C+1,B=m.col+m.colSpan;return c.slice(v,B).reduce((S,I)=>S+I,0)},f=new Set;for(let m=0;m<i.rowCount;m++){const C=i.getCell({row:m,col:l});if(f.has(C.cell))continue;f.add(C.cell);const v=C.cell,B=v.getBoundingClientRect();let y=o-B.left+Rh-AE;const S=Cs(v),I=wd(n,S)||DE*C.colSpan,M=u(C,l),R=I-M;y<R&&(y=R);const $=B.left+y;a=Math.max(a,$)}return a}const PE=w("table-resize-drag-drop");class jE{constructor(t,e,o,r){h(this,"cursor","col-resize");this.editor=t,this.elem=e,this.data=o,this.onEnd=r}onDragStart(t,e,o){}onDragging(t,e,o,r,i){const{table:s,block:l,draggingRefCell:c}=t.data,u=$E(this.editor,c,s,e.x-t.dragOffsetX)-s.getBoundingClientRect().left;d(PE,c,"no dragging cell");const m=et.fromTable(s).getCellByCellElement(c),C=m.col+m.colSpan-1,B=Es(s).slice(0,C).reduce((S,I)=>S+I,0),y=u-B;LE(s,C,y),$5(this.editor,l,c),this.editor.selection.caret.update()}onDragEnd(t,e,o,r,i){const s=Es(t.data.table);NE(this.editor,t.data.block,s),Oh(this.editor),this.onEnd&&(this.onEnd(e),this.onEnd=null)}}function HE(n,t){const e=document.elementFromPoint(t.x,t.y);if(!e)return null;const o=F(e);return!o||!n.contains(o)||!Ht(o)?null:o}w("table-resize");class FE{constructor(t){h(this,"draggingRefCell",null);h(this,"handleMouseMove",(t,e)=>{if(t.readonly||t.selectionHandler.isSelecting()&&!this.draggingRefCell||this.draggingRefCell)return;const o=e.target;if(!(o instanceof Element)||o.closest(".table-indicator"))return;const i=e,s=HE(t,i);if(!s||!h5(s)){Oh(t);return}this.updateGripper(s,i.x,i.y)});this.editor=t,t.domEvents.addEventListener(document,"mousemove",this.handleMouseMove)}destroy(){this.editor.domEvents.removeEventListener(document,"mousemove",this.handleMouseMove)}updateGripper(t,e,o){const r=jt(t),i=OE(r,e,o);if(i){if(!Ah(this.editor,t)){if(_E(this.editor))return;const l=N5(this.editor,t),c={block:t,table:r,draggingRefCell:i};ed(new jE(this.editor,l,c,a=>{this.updateGripper(t,a.x,a.y)}))}$5(this.editor,t,i)}else Oh(this.editor)}}function P5(n){n.addCustom("table-mouse-event-handler",t=>new FE(t))}const j5=w("table-insert-column");function H5(n,t,e){const o=jt(t),r=et.fromTable(o),i=r.colCount;d(j5,e>=0&&e<=i,`insert index ${e} is out of range [0, ${i}]`);const s=r.map(m=>m.containerId),l=new Set;n.doc.beginBatchUpdate();for(let m=0;m<s.length;m++){const C=s[m],v=C[e-1],B=C[e];if(e===0||e===C.length||v!==B){const y=yn(n.doc);C.splice(e,0,y)}else C.splice(e,0,v),l.add(v)}n.doc.endBatchUpdate();const c=Y.default(n.getBlockData(t));l.forEach(m=>{const C=`${m}_colSpan`,v=c[C];d(j5,typeof v=="number"&&v>1,`no colSpan for containerId ${m}, ${v}`),c[C]=v+1});const a=c.colsWidth.concat();a.splice(e,0,Sc);const u=et.virtualCellContainersGridToChildren(s),f={...c,cols:c.cols+1,children:u,colsWidth:a};er(f),n.updateBlockData(t,f)}const Dc=w("table-insert-row");function F5(n,t,e){const o=jt(t),r=et.fromTable(o),i=r.rowCount;d(Dc,e>=0&&e<=i,`insert index ${e} is out of range [0, ${i}]`);const s=r.map(m=>m.containerId),l=new Set;n.doc.beginBatchUpdate();const c=[];for(let m=0;m<r.colCount;m++){const C=e>0&&s[e-1][m],v=e<r.rowCount&&s[e][m];if(d(Dc,C||v,"no top and bottom cell"),e===0||e===r.rowCount||C!==v){const B=yn(n.doc);c.push(B)}else d(Dc,C,"no top cell"),c.push(C),l.add(C)}n.doc.endBatchUpdate(),s.splice(e,0,c);const a=Y.default(n.getBlockData(t));l.forEach(m=>{const C=`${m}_rowSpan`,v=a[C];d(Dc,typeof v=="number"&&v>1,`no rowSpan for containerId ${m}, ${v}`),a[C]=v+1});const u=et.virtualCellContainersGridToChildren(s),f={...a,rows:a.rows+1,children:u};er(f),n.updateBlockData(t,f)}const _h=w("paste-table-in-table-block");function zE(n,t,e,o){let r=et.fromBlock(e);const i=t.blocks.root[0];d(_h,i,"no table data"),d(_h,i.type==="table",`table data type is not table, but ${i.type}`);const s=i,l=r.getCellByCellElement(o),c=s.cols,a=s.rows,u=l.col,f=l.row,m=u+c,C=f+a,v=[];for(let B=u;B<m&&B<r.colCount;B++)for(let y=f;y<C&&y<r.rowCount;y++){const S=r.getCell({col:B,row:y});S.virtual?S.virtual&&v.push({col:B,row:y}):(S.colSpan>1||S.rowSpan>1)&&v.push({col:B,row:y})}n.undoManager.runInGroup(()=>{if(v.forEach(I=>{const M=et.fromBlock(e).getCell(I);(M.colSpan>1||M.rowSpan>1)&&kh(n,e,I)}),m>r.colCount)for(let I=r.colCount;I<m;I++)H5(n,e,I);if(C>r.rowCount)for(let I=r.rowCount;I<C;I++)F5(n,e,I);r=et.fromBlock(e);const B=new vc(s);let y;for(let I=0;I<B.colCount;I++)for(let M=0;M<B.rowCount;M++){const R=B.getCell({col:I,row:M});if(!R.virtual){const $=hu(n.editorBlocks,t,R.containerId),Z=u+I,ot=f+M,st={col:Z,row:ot},mt=r.getCellContainer(st);Hp(n,mt,$),y=mt}}d(_h,y,"no last container");const S=Qt(y);n.selection.selectBlock(S,W(n,S))})}const z5=w("paste-in-table-block");class UE{constructor(t){this.editor=t,setTimeout(()=>{t.input.addHandler(this)})}destroy(){}async handleBeforePasteDoc(t,e){if(!t.selection.range.isSimple()||t.selection.range.start.offset!==0)return!1;const r=t.selection.startBlock,i=H(r);if(pt(i)||!Bd(t,i))return!1;const s=F(i);if(d(z5,s,"no parent block"),!Ht(s)||e.blocks.root.length!==1||e.blocks.root[0].type!=="table")return!1;z5.debug("paste child table in table");const a=et.fromBlock(s).getCellByContainerId(U(i)).cell;return zE(t,e,s,a),!0}}function U5(n){n.addCustom("table-block-paste-event",t=>new UE(t))}const Nh=w("table-select-columns");function VE(n,t,e,o,r){d(Nh,Ht(t),"is not a table block");const i=et.fromBlock(t);d(Nh,e>=0&&e<i.colCount,"invalid from"),d(Nh,o>0&&e+o<=i.colCount,"invalid count");const s=i.getCell({row:0,col:e}),l=i.getCell({row:i.rowCount-1,col:e+o-1}),c=wt(t,s.containerId,{colIndex:e,rowIndex:0}),a=wt(t,l.containerId,{colIndex:e+o-1,rowIndex:i.rowCount-1});r!=null&&r.reverse?n.selection.setSelection(a,c):n.selection.setSelection(c,a)}const $h=w("table-select-columns");function qE(n,t,e,o,r){d($h,Ht(t),"is not a table block");const i=et.fromBlock(t);d($h,e>=0&&e<i.rowCount,"invalid from"),d($h,o>0&&e+o<=i.rowCount,"invalid count");const s=i.getCell({row:e,col:0}),l=i.getCell({row:e+o-1,col:i.colCount-1}),c=wt(t,s.containerId,{rowIndex:e,colIndex:0}),a=wt(t,l.containerId,{rowIndex:e+o-1,colIndex:i.colCount-1});r!=null&&r.reverse?n.selection.setSelection(a,c):n.selection.setSelection(c,a)}const hz="",V5=w("get-toolbar-reference-client");function WE(n,t){const e=n.selection.range;if(!e.isSimple()){d(V5,e.start.blockId===e.end.blockId,"invalid selection range");const s=n.getBlockById(e.start.blockId);d(V5,at(n,s),"not a complex block");const l=bt(n,s);if(l.getTextToolbarReferenceClient){const c=l.getTextToolbarReferenceClient(n,s);if(c)return c}}const o=e.isReverse()?t.start:t.end,r=Wt(n,{anchor:o,focus:o}),i=Ho(n,t.block,r);if(i.length!==0)return i[0]}function GE(n){var t,e;if(n.children){let o=!1;const r=[];for(const i of n.children){if((t=i.states)!=null&&t.includes("checked")){o=!0;break}(e=n.defaultCheckedChildren)!=null&&e.includes(i.id)&&r.push(i)}if(!o&&(r==null?void 0:r.length))for(const i of r)Array.isArray(i.states)?i.states.push("checked"):i.states=["checked"]}}function Lc(n){const t=(r,i)=>{const s=r.findIndex(c=>c.id===i.id);if(s===-1){r.push(i);return}const l=r[s];if(l.value!==i.value&&delete l.value,!!l.states){if(!i.states){l.states=[];return}l.states=Za.default(l.states,i.states)}},e=[],o=new Map;return n.forEach(r=>{var i,s;(i=r.children)!=null&&i.length&&(o.has(r.id)?(s=o.get(r.id))==null||s.push(...r.children):o.set(r.id,[...r.children])),t(e,r)}),o.forEach((r,i)=>{const s=e.find(l=>l.id===i);s&&(s.children=Lc(r),GE(s))}),e}function Mc(n){return n.getCustom("toolbar-handler")}const fz="";class ZE{constructor(){h(this,"linkPopup",null);h(this,"form",{});h(this,"onFinished",null);h(this,"onClose",null);h(this,"handleOk",async()=>{var t;try{await this.checkValue();const{linkText:e,linkUrl:o}=this.form;(t=this.onFinished)==null||t.call(this,e.getInputValue()||o.getInputValue(),o.getInputValue()),this._destroy()}catch{}});h(this,"handleClose",()=>{var t;(t=this.onClose)==null||t.call(this),this._destroy()});h(this,"onShow",()=>{setTimeout(()=>{var t;(t=this.form.linkText)==null||t.getField().focus()},400)});h(this,"onChange",()=>{var e;const t=(e=this.linkPopup)==null?void 0:e.content.querySelector(".submit-button");t.disabled=!1});h(this,"handleTextKeyboard",t=>{var e;if(!t.isComposing){if(t.key==="Enter"){(e=this.form.linkUrl)==null||e.getField().focus(),t.stopPropagation();return}t.key==="Escape"&&this.handleClose()}});h(this,"handleUrlKeyboard",t=>{if(!t.isComposing){if(t.key==="Enter"){this.handleOk(),t.preventDefault();return}t.key==="Escape"&&this.handleClose()}})}async checkValue(){const{linkUrl:t}=this.form;if(!t.getInputValue())throw t.setFieldError(T.t("link.urlPlaceholder")),new Error(T.t("link.urlPlaceholder"))}editLink(t){var u,f;const{target:e,linkText:o,linkUrl:r,onFinished:i,onClose:s,placement:l="bottom-start"}=t;this.linkPopup=new ms(this.createPopupContent(o,r)),this.linkPopup.addListener("show",this.onShow),this.linkPopup.manualShow(e,{theme:"light",placement:l}),this.onFinished=i,s&&(this.onClose=s);const c=(u=this.linkPopup)==null?void 0:u.content.querySelector(".submit-button"),a=(f=this.linkPopup)==null?void 0:f.content.querySelector(".cancel-button");c==null||c.addEventListener("click",this.handleOk),a==null||a.addEventListener("click",this.handleClose)}createPopupContent(t,e){const o=b("div",["link-popup-content"],null);this.form.linkText=uh(o,{label:T.t("link.textLabel"),required:!1,placeholder:T.t("link.textPlaceholder"),defaultValue:t,onChange:this.onChange,onKeyDown:this.handleTextKeyboard}),this.form.linkUrl=uh(o,{className:"link-popup-gap",label:T.t("link.urlLabel"),required:!0,placeholder:T.t("link.urlPlaceholder"),defaultValue:e,onChange:this.onChange,onKeyDown:this.handleUrlKeyboard});const r=b("div",["link-popup-footer"],o);b("button",["cancel-button"],r,T.t("link.cancelText"));const i=b("button",["submit-button"],r,T.t("link.submitText"));return i.disabled=!0,o}_destroy(){var o,r,i,s;const t=(o=this.linkPopup)==null?void 0:o.content.querySelector(".submit-button"),e=(r=this.linkPopup)==null?void 0:r.content.querySelector(".cancel-button");t==null||t.removeEventListener("click",this.handleOk),e==null||e.removeEventListener("click",this.handleClose),this.onFinished=null,this.onClose=null,this.form={},(i=this.linkPopup)==null||i.removeAllListeners(),(s=this.linkPopup)==null||s.destroy()}destroy(){this._destroy()}}function Rc(n,t){n.addCustom("link-editor",()=>new ZE).editLink(t)}const YE=w("link-popup");function QE(n){return nt(n,"link")}function Ac(n){var t,e;return(e=(t=n.getAttribute("link"))!=null?t:n.textContent)!=null?e:""}function KE(n,t,e){var r,i,s,l;if(n.isBlockWritable(t)&&e&&_e(e)){const c=e,a=(i=(r=n.editorBoxes.getBoxClass(Ri(c))).getBoxProperties)==null?void 0:i.call(r,n,c);return a!=null&&a.boxCommands?(l=(s=a.boxCommands["hovering-toolbar"])==null?void 0:s.commands)!=null?l:[]:[]}return n.isWritable()&&e&&j(n,t)&&QE(e)?[{id:"link-text",name:Ac(e),disableTooltip:!0,element:b("span",["link-href-button"],null,Ac(e))},{id:"edit-link",name:"Edit",icon:ah},{id:"remove-link",name:"Remove link",icon:Vw}]:fg(n,t,"hovering-toolbar")}function JE(n,t,e){var c;const o=so(t,e);n.selection.selectBlock(t,o.start,o.end);const r=(c=e.textContent)!=null?c:"",i=Ac(e);Rc(n,{target:e,linkText:r,linkUrl:i,onFinished:(a,u)=>{try{const f=n.getBlockText(t),m=Hd(f,o.start,o.end-o.start),C=Sr(m,o.start,a,{link:u});n.setBlockText(t,C),n.selection.selectBlock(t,o.start+a.length),n.focus()}catch(f){YE.error(f)}},onClose:()=>{n.selection.selectBlock(t,o.end),n.focus()}})}function XE(n,t,e){const o=so(t,e),r=n.getBlockText(t),i=Ac(e),s=Dr(o.start,o.end-o.start,r,"link",i);n.setBlockText(t,s),n.selection.selectBlock(t,o.end)}function tI(n,t,e,o){var s,l,c;if(e){if(n.isBlockWritable(t)&&_e(e)){const u=e,f=(l=(s=n.editorBoxes.getBoxClass(Ri(u))).getBoxProperties)==null?void 0:l.call(s,n,u);if(f!=null&&f.boxCommands){f.boxCommands["hovering-toolbar"].executeCommand(n,t,u,o);return}return}const a=Mc(n);a.disableTextToolbar(),a.hide(),setTimeout(()=>{a.enableTextToolbar()},1e4),o.id==="edit-link"?JE(n,t,e):o.id==="remove-link"&&XE(n,t,e);return}const r=hg(n,t);if(!r)return;const i=(c=r.blockCommands)==null?void 0:c["hovering-toolbar"];!i||i.executeCommand(n,t,o)}function Oc(){let n=8;for(;n>0&&!document.querySelector(`div[data-style-heading='${n}']`);)n--;return n}const eI=[Xu,th,eh,nh,oh,rh,ih,sh];class nI{constructor(t){h(this,"id","BlockTurnIntoCommandProvider");this.editor=t}getHeadingIndex(){let t=Oc();return t<=4?t=5:t<8&&(t+=1),t}getAvailableCommands(t,e,o){if(j(t,e)){const r=q(e),i=rt(e),s=Qe(t,e),c=t.getBlockData(e).heading,a=[];for(let f=0;f<this.getHeadingIndex();f++)a.push({id:`heading-${f+1}`,name:T.t("commands.heading",{name:`${f+1}`}),icon:eI[f],states:c===f+1?["checked"]:[],value:`${f+1}`});const u=f=>{var C;const m=b("span",["toolbar-item-name-container"],null);for(const v of f.children)if((C=v.states)!=null&&C.includes("checked"))return m.innerHTML=v.icon||Cc,m;return m.innerHTML=Cc,m};return[{id:"turn-into",name:T.t("commands.headingGroup"),blockId:r,blockType:i,blockKind:s,element:u,groupIndex:200,dropdown:!0,manualShowChildren:!0,childrenPlacement:"bottom-start",defaultCheckedChildren:["text"],children:[{id:"text",name:T.t("commands.text"),icon:Cc,states:c?[]:["checked"]},...a],childrenType:"menu"}]}return[]}applyHeadingStyle(t,e,o){t.updateBlockData(e,{heading:o})}executeCommand(t,e,o,r){if(j(t,e)&&(r.id.startsWith("heading-")||r.id==="text")){const i=r.value?Number(r.value):null;return this.applyHeadingStyle(t,e,i),!0}return!1}}function _c(n){const t=n.getAttribute("block-padding-level");return t?Number(t):null}function oI(n,t){let e;const o=_c(t);if(!o)e=1;else{if(o>=12)return e=12,!1;e=o+1}return n.updateBlockData(t,{...n.getBlockData(t),padding:e}),!0}function q5(n,t){const e=_c(t);if(!e)return!1;const o=n.getBlockData(t);return e>1?(n.updateBlockData(t,{...o,padding:e-1}),!0):(n.updateBlockData(t,{...o,padding:null}),!0)}function Ph(n){return n.readonly||!n.isWritable()}function rI(n){return n.selection.range.getSelectedBlocks().forEach(e=>{const o=e.block;j(n,o)&&oI(n,o)}),!0}function iI(n){return n.selection.range.getSelectedBlocks().forEach(e=>{const o=e.block;j(n,o)&&q5(n,o)}),!0}function sI(n){return Ph(n)?!1:n.undoManager.runInGroup(()=>(rI(n),!0))}function lI(n){return Ph(n)?!1:n.undoManager.runInGroup(()=>(iI(n),!0))}function cI(n){if(Ph(n))return!1;if(!n.selection.range.isCollapsed())return;const t=n.selection.focusedBlock;if(!j(n,t))return;const e=n.selection.range.focus;if(!(!e.isSimple()||e.offset!==0||!_c(t)))return q5(n,t),!0}class aI{renderBlock(t,e,o){const{padding:r}=o;return r?{attributes:{"block-padding-level":r}}:{}}}const mz="",dI={Tab:sI,"Shift+Tab":lI,Backspace:cI},Nc=w("list-block");function ct(n){return rt(n)==="list"}function Ft(n){d(Nc,ct(n),"not a list block")}function Fe(n){Ft(n);const t=n.getAttribute("data-list-type");return d(Nc,t,"no list type"),t}function $c(n){return ct(n)&&Fe(n)==="text-only"}function un(n){var t,e;return Ft(n),(e=Number.parseInt((t=n.getAttribute("data-list-start"))!=null?t:"1",10))!=null?e:1}function me(n){var t,e;return Ft(n),(e=Number.parseInt((t=n.getAttribute("data-list-level"))!=null?t:"1",10))!=null?e:1}function Yr(n){Ft(n);const t=n.getAttribute("data-list-group-id");return d(Nc,t,"no group id"),t}function vo(n){var i,s,l,c,a;Ft(n);const t=(i=n.getAttribute("data-list-type"))!=null?i:"ordered",e=(l=Number.parseInt((s=n.getAttribute("data-list-start"))!=null?s:"1",10))!=null?l:1,o=(a=Number.parseInt((c=n.getAttribute("data-list-level"))!=null?c:"1",10))!=null?a:1,r=n.getAttribute("data-list-group-id");return d(Nc,r,"no group id"),{type:t,start:e,level:o,groupId:r}}function jh(n){switch(n){case"ordered":return{ordered:!0,checkbox:null,textOnly:null};case"unordered":return{ordered:!1,checkbox:null,textOnly:null};case"checked":return{checkbox:"checked",ordered:!1,textOnly:null};case"unchecked":return{checkbox:"unchecked",ordered:!1,textOnly:null};case"text-only":return{checkbox:null,ordered:!1,textOnly:!0};default:return{checkbox:null,ordered:!0,textOnly:!1}}}function Zn(n){Ft(n);const{level:t,groupId:e,type:o}=vo(n);let r=gt(n);for(;r;){if(!ct(r))return null;const{level:i,groupId:s,type:l}=vo(r);if(i<t)return null;if(t===i&&e===s&&(l==="text-only"||o==="text-only"||o===l))return r;r=gt(r)}return null}function rr(n){Ft(n);const{level:t,groupId:e,type:o}=vo(n);let r=dt(n);for(;r;){if(ct(r)){const{level:i,groupId:s,type:l}=vo(r);if(t===i&&e===s&&(l==="text-only"||o==="text-only"||o===l))return r;if(i<t)return null}r=dt(r)}return null}function W5(n){Ft(n);const t=[];let e=Zn(n);for(;e;)t.unshift(e),e=Zn(e);return t}function Is(n){Ft(n);const t=[];let e=rr(n);for(;e;)t.push(e),e=rr(e);return t}function xs(n){Ft(n);let t=Zn(n);for(;t;){const e=Zn(t);if(!e)return t;t=e}return n}function uI(n){Ft(n);let t=rr(n);for(;t;){const e=rr(t);if(!e)return t;t=e}return null}function G5(n,t){const e=W5(n),o=Is(n);return t.withSelf?[...e,n,...o]:[...e,...o]}function Ts(n,t,e,o){var i;const r=(i=o==null?void 0:o.groupId)!=null?i:N();t.forEach(s=>{const l=n.getBlockData(s);if(l.start!==e||(o==null?void 0:o.resetGroupId)){const c={...l,start:e};o!=null&&o.resetGroupId&&(c.groupId=r),n.updateBlockData(s,c)}l.textOnly||(e+=1)})}function Hh(n,t,e,o){const r=G5(t,{withSelf:!0});r.length!==0&&Ts(n,r,e,o)}function hI(n){const t={M:1e3,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1};let e="",o=n;return Object.entries(t).forEach(([r,i])=>{for(;o>=i;)e+=r,o-=i}),e.toLowerCase()}const fI="abcdefghijklmnopqrstuvwxyz";function Z5(n){if(n<=0)return`${n}`;const t=(n-1)%26,e=Math.floor((n-1)/26),o=fI[t];return e?Z5(e)+o:o}function mI(n){return`${n}`}const Y5=[mI,Z5,hI];function gI(n,t){const e=Y5[(n-1)%Y5.length];return e(t)}function pI(n){return["\u2022","\u25E6","\u25AA"][(n-1)%3]}class ir{constructor(t,e,o){h(this,"listStart");h(this,"listBrother",null);this.editor=t,this.options=o;const r=xs(e),i=un(r);this.listStart=i,this.listBrother=r,o!=null&&o.resetStart&&(this.listStart=1)}fix(){!this.listBrother||Hh(this.editor,this.listBrother,this.listStart,this.options)}}function CI(n,t,e=1){if(!t)return null;let o=gt(n);for(;o;){const r=o.getAttribute("data-style-heading"),i=Number(o.getAttribute("data-list-level"));if(r){if(r<t)return null;if(r===t&&i===e)return ct(o)?o:null}o=gt(o)}return null}function bI(n,t){const e=n.getAttribute("data-style-heading"),o=CI(n,e);if(o)return o;const r=gt(n);if(r&&ct(r)&&Fe(r)===t)return r;const i=dt(n);return i&&ct(i)&&Fe(i)===t?i:null}function vI(n,t,e){var y,S,I,M;const o=(y=e.data)!=null?y:{};let r=1;if(ct(t))r=me(t);else{const R=_c(t);R&&(r=R+1),r>8&&(r=8)}const i=(S=o.listType)!=null?S:"ordered";if(i==="text-only")return null;const s=n.getBlockData(t);let l=(I=s.text)!=null?I:[];const c=n.selection.range.focus;if(!c.isSimple())return null;let u=vt(l);const f=(M=e.offset)!=null?M:c.offset;f<=de(l)&&(l=be(l,f).right,u=u.substring(0,f));let m=1;i==="ordered"&&(m=Number.parseInt(u,10)||1);let C=N();const v=bI(t,i);if(v){if(J(t)>J(v))m=un(v)+1;else{const R=un(v);R>1&&(m=R-1)}C=Yr(v)}const B={id:N(),type:"list",level:r,start:m,groupId:C,ordered:!1,text:l};return s.quoted&&(B.quoted=!0),s.heading&&(B.heading=s.heading),i==="ordered"?B.ordered=!0:(i==="checked"||i==="unchecked")&&(B.checkbox=i),{blockData:B,onConverted:(R,$)=>{new ir(R,$).fix()}}}function Qr(n){return n.textOnly?"text-only":n.checkbox?n.checkbox:n.ordered?"ordered":"unordered"}function kI(n){var e,o;if(n.checkbox||n.textOnly)return"";const t=(e=n.level)!=null?e:1;return n.ordered?`${gI(t,(o=n.start)!=null?o:1)}.`:pI(t)}function Pc(n){return n==="checked"||n==="unchecked"}function Q5(n,t,e,o){const r=t,{containerId:i,blockIndex:s}=o[o.length-1];if(s===0)return!0;const l=e.blocks[i][s-1];if(l.type!=="list")return!0;const c=Qr(r),a=Qr(l);return c!==a&&(!Pc(c)||!Pc(a))||r.level>l.level}function K5(n,t,e,o){const r=t,{containerId:i,blockIndex:s}=o[o.length-1];if(s===e.blocks[i].length-1)return!0;const l=e.blocks[i][s+1];if(l.type!=="list")return!0;const c=Qr(r),a=Qr(l);return c!==a&&(!Pc(c)||!Pc(a))||r.level>l.level}function yI(n,t,e,o,r){var s,l,c;const i=t;if(o==="text"){let a=((s=ve.convertTo)==null?void 0:s.call(ve,n,t,e,"text",r))||"";i.checkbox==="checked"?a=`[x] ${a}`:i.checkbox==="unchecked"&&(a=`[ ] ${a}`),i.ordered?a=`${i.start}. ${a}`:a=`- ${a}`;const u=i.level||0;return a=(u>0?" ".repeat(u-1):"")+a,a}if(o==="markdown"){let a=((l=ve.convertTo)==null?void 0:l.call(ve,n,t,e,"markdown",r))||"";i.checkbox==="checked"?a=`[x] ${a}`:i.checkbox==="unchecked"&&(a=`[ ] ${a}`),i.ordered?a=`${i.start}. ${a}`:a=`- ${a}`;const u=i.level||0;return a=(u>0?" ".repeat(u-1):"")+a,Q5(n,t,e,r)&&(a=`${a}`),K5(n,t,e,r)&&(a=`${a}`,u<=1&&(a+=`
338
338
  `)),a}if(o==="html"){let a=((c=ve.convertTo)==null?void 0:c.call(ve,n,t,e,"html",r))||"";a=a.replace("<p>","").replace("</p>",""),i.checkbox==="checked"?a=`<input type="checkbox" checked="checked" disabled="disabled" /> ${a}`:i.checkbox==="unchecked"&&(a=`<input type="checkbox" disabled="disabled" /> ${a}`);let u="ul";return i.ordered?(a=`<li value="${i.start}">${a}</li>`,u="ol"):a=`<li>${a}</li>`,Q5(n,t,e,r)&&(a=`<${u}>${a}`),K5(n,t,e,r)&&(a=`${a}</${u}>`),a}return""}const wI=8,Ot=w("list-block");class jc{constructor(t,e){h(this,"listStart",0);h(this,"listBrother",null);if(this.editor=t,$c(e))return;const o=xs(e),r=un(o);this.listStart=r,o===e?this.listBrother=rr(o):this.listBrother=o}fix(){!this.listBrother||Hh(this.editor,this.listBrother,this.listStart)}}function BI(n,t,e){n.getBlockData(t).quoted&&(e.quoted=!0)}function Fh(n,t,e,o){if(Ot.debug("drag a block on a list block"),!j(n,t))return!1;d(Ot,ct(e),"target is not a list block");const{type:r,start:i,level:s,groupId:l}=vo(e),c=o==="after"?i+1:i,a=n.getBlockData(t),u={id:N(),type:"list",groupId:l,level:s,start:c,text:a.text,...jh(r)};BI(n,e,u);let f=J(e);const m=H(e);o==="after"&&(f+=1);let C=null;ct(t)&&(C=new jc(n,t));const v=n.insertBlock(U(m),f,u,Fl(u.id,0));return n.deleteBlock(t),new ir(n,v).fix(),C==null||C.fix(),!0}function EI(n,t,e,o){if(Ot.debug("drag a list between text blocks"),o==="after"){const a=dt(e);if(a&&ct(a))return Fh(n,t,a,"before")}if(o==="before"){const a=gt(e);if(a&&ct(a))return Fh(n,t,a,"after")}const i={...n.getBlockData(t),groupId:N(),start:1,level:1};let s=J(e);const l=H(e);o==="after"&&(s+=1),n.insertBlock(U(l),s,i,Fl(i.id,0));const c=new jc(n,t);return n.deleteBlock(t),c.fix(),!0}function II(n,t,e,o,r){if(kl(e))return!1;const{blockId:i}=e,s=n.getBlockById(i);d(Ot,s,"no dragged block");const{isSourceBlock:l,targetBlock:c}=r;return!l&&c?(d(Ot,t===c,"block !== target block"),d(Ot,ct(c),"target is not a list block"),Fh(n,s,c,o)):EI(n,s,c,o)}const xI=`<?xml version="1.0" ?>
339
339
  <svg t="1666868766077" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3547" width="16" height="16">
340
340
  <path d="M864 128H160c-17.6 0-32 14.4-32 32v704c0 17.6 14.4 32 32 32h704c17.6 0 32-14.4 32-32V160c0-17.6-14.4-32-32-32zM428 718.4l-45.6 45.6-45.6-45.6-116-117.6 45.6-45.6L383.2 672l367.2-367.2 45.6 45.6-368 368z" p-id="3548" fill="#1296db"></path>
@@ -356,7 +356,7 @@ xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
356
356
  <path d="M9.99978 5.99611L14.5 1.49609" stroke="currentColor" stroke-width="2"/>
357
357
  <path d="M1 10.0039H5.99738L5.99608 15" stroke="currentColor" stroke-width="2"/>
358
358
  <path d="M14.9971 5.99611H9.99969L10.001 1" stroke="currentColor" stroke-width="2"/>
359
- </svg>`;async function $I(n,t,e){const o=Rt(t),r=o.querySelector('[data-button-id="mindmap-fullscreen"]');d(Ot,r,"no full screen button");const i=()=>{setTimeout(()=>{e.toMindmap(n,t,{},{reset:!0,mindmapTools:e})},300)},s=()=>{z(o,"fullscreen"),r.innerHTML=X5,V2(r,"Full screen",n.clientId),e4(t)&&setTimeout(()=>{i()},300)};if(document.fullscreenElement===o){try{await t4()}catch(l){Ot.error(l)}s()}else{try{A(o,"fullscreen"),await OI(o),i()}catch(l){Ot.error(l)}r.innerHTML=NI,V2(r,T.t("mindmap.exitFullscreen"),n.clientId)}o.onfullscreenchange=()=>{document.fullscreenElement||s()}}function Uh(n,t,e,o,r){if(t.querySelector(`[data-button-id="${e}"]`))return null;const s=go(e,o,r,[],n.clientId);return A(s,"mindmap-button"),t.appendChild(s),s}function Vh(n,t){return n.querySelector(`[data-button-id="${t}"]`)}function PI(n){return Vh(n,"mindmap-fullscreen")}function jI(n){return Vh(n,"mindmap-fit")}function HI(n){return Vh(n,"mindmap-close")}function FI(n,t,e,o){const r=Uh(n,t,"mindmap-close",T.t("mindmap.close"),RI);!r||n.domEvents.addEventListener(r,"click",()=>{o.closeMindmap(n,e)})}function zI(n,t,e,o){const r=Uh(n,t,"mindmap-fit",T.t("mindmap.autoFit"),AI);!r||n.domEvents.addEventListener(r,"click",()=>{o.fitMindmap(n,e)})}function UI(n,t,e,o){if(navigator.userAgent.includes("Mobile")&&!navigator.userAgent.includes("iPad"))return;const i=Uh(n,t,"mindmap-fullscreen",T.t("mindmap.fullScreen"),X5);!i||n.domEvents.addEventListener(i,"click",()=>{$I(n,e,o)})}function VI(n,t){const e=Bl(t);if(!e)return;const o=jI(e);o&&(o.remove(),n.domEvents.removeAllListeners(o));const r=HI(e);r&&(r.remove(),n.domEvents.removeAllListeners(r));const i=PI(e);i&&(i.remove(),n.domEvents.removeAllListeners(i))}const Kr=new Map;function qh(n,t,e){const o=(s,l)=>{s.forEach(c=>{l?A(c.block,"to-mindmap-highlight"):z(c.block,"to-mindmap-highlight"),o(c.children,l)})},r=J5(n,t);if(r.length===0)return;const i=r[0].block;if(e){const s=Kr.get(i);s&&(s.forEach(l=>l.cancel()),Kr.delete(i)),o(r,!0)}else{const s=setTimeout(()=>{o(r,!1),Kr.delete(i)},300),l=()=>{clearTimeout(s),Kr.delete(i)},c=Kr.get(i);c?c.push({cancel:l}):Kr.set(i,[{cancel:l}])}}const{Markmap:qI}=C7;function WI(n,t){Ft(t);const e=J5(n,t),o=e[0].block,r=a=>({t:"text",v:it(a.block).textContent,d:1,c:a.children.length>0?a.children.map(f=>r(f)):void 0});let i=null;e.length>1?i={t:"root",v:"root",d:0,c:e.length>0?e.map(a=>r(a)):void 0}:i=r(e[0]);const l=a=>{if(a.length===0)return null;const u=a[a.length-1];return u.children&&u.children.length>0?l(u.children):u},c=l(e);return{root:i,block:o,nodes:e,last:c}}function Wh(n,t,e,o){const{root:r,block:i,last:s}=WI(n,t);o.selectBlock&&n.selection.selectBlock(i,0,0),qh(n,i,!1),o.saveData&&n.updateBlockData(i,{viewAsMindmap:!0});const l=Rt(i);let c=l.querySelector(".editor-mindmap-svg");if(o.reset&&(c&&c.remove(),c=null),c)c.innerHTML="";else{const S="http://www.w3.org/2000/svg",I=l.getBoundingClientRect(),M=document.fullscreenElement===l,R=M?`${I.width}`:`${t.getBoundingClientRect().width}`,$=M?`${I.height}`:"600",Z=document.createElementNS(S,"svg");Z.setAttributeNS(null,"viewBox",`0 0 ${R} ${$}`),Z.setAttributeNS(null,"width","100%"),Z.setAttributeNS(null,"height",$),Z.style.display="block",Z.style.width="100%",Z.style.height=`${$}px`,Z.classList.add("editor-mindmap-svg"),l.appendChild(Z),c=Z}const a=i,f=`editor-mindmap-root-${q(i)}`;A(a,"editor-in-mindmap-first",f,"readonly"),a.contentEditable="false";const m=dt(i);m&&J(m)<=J(s.block)&&_I(m,s.block,["block-hidden",f]);const C=(S,I)=>{if(I.length>0){const M=I[0].parentElement;M&&(M.style.width="100vw",M.style.maxWidth="200px")}I.forEach(M=>{A(M,"editor-mindmap-node")})},v=new qI(c,{...e,autoFit:!0});v.viewHooks.transformHtml.tap(C),v.setData(r),v.fit();const B=Rt(i);let y=B.querySelector(".mindmap-toolbar");y||(y=b("div",["mindmap-toolbar"],B)),zI(n,y,a,o.mindmapTools),UI(n,y,a,o.mindmapTools),FI(n,y,a,o.mindmapTools),n.domEvents.addEventListener(c,"click",()=>{n.selection.selectBlock(i,0),n.input.focus()}),a.mindMap=v}function GI(n){const t=n.classList,e="editor-mindmap-root-";return Array.from(t).find(r=>{if(r.startsWith(e))return r})}async function n4(n,t){const e=GI(t);if(!e)return;n.updateBlockData(t,{viewAsMindmap:null});const o=H(t);Mt(o).forEach(l=>{nt(l,e)&&z(l,e,"editor-in-mindmap-first","block-hidden")});const i=Rt(t);document.fullscreenElement===i&&await t4();const s=i.querySelector(".editor-mindmap-svg");d(Ot,s,"no mindmap svg"),s.remove(),n.domEvents.removeAllListeners(s),t.contentEditable="inherit",VI(n,t),n.selection.selectBlock(t,0)}function ZI(n,t){const e=t.mindMap;e&&e.fit()}const o4={toMindmap:Wh,closeMindmap:n4,fitMindmap:ZI};function r4(n){let t=dt(n);if(!t)return null;const e=rr(n);for(;t!==e;){if(d(Ot,t,"no next block"),ct(t))return me(t)>me(n)?t:null;if(t=dt(t),!t)return null}return null}function Gh(n){const t=[];let e=r4(n);if(!e)return t;for(;e;){const o=rr(e);t.push({block:e,children:Gh(e)}),e=o}return t}function YI(n){const t=(o,r)=>{r.push(o.block),o.children.forEach(i=>t(i,r))},e=[];return n.forEach(o=>t(o,e)),e}function i4(n,t){return me(t)!==1}function s4(n,t,e){t.forEach(o=>{const r=n.getBlockData(o.block);n.updateBlockData(o.block,{...r,groupId:e,level:r.level-1}),o.children.length&&s4(n,o.children,r.groupId)})}function Zh(n,t){if(!i4(n,t))return!1;const e=me(t);if(e===1)return!1;let o=N(),r=1,i=Fe(t);const s=e-1,l=zh(t);l&&(o=Yr(l),r=un(l)+1,i!=="text-only"&&(i=Fe(l)));const c=Gh(t),a=n.getBlockData(t),u={...a,groupId:o,level:s,start:r,...jh(i)};n.updateBlockData(t,u),n.doc.beginBatchUpdate(),s4(n,c,a.groupId),n.doc.endBatchUpdate(),new ir(n,t).fix();const m=r4(t);return m&&new ir(n,m,{resetStart:!0,resetGroupId:!0}).fix(),!0}function Jr(n,t){Ft(t);const e=n.getBlockData(t),o={id:N(),type:"text",text:e.text};e.heading&&(o.heading=e.heading),e.heading&&(o.heading=e.heading);const r=new jc(n,t),i=H(t),s=J(t);n.deleteBlock(t);const l=Fl(o.id,0);n.insertBlock(U(i),s,o,l),r.fix()}function QI(n){if(!n.selection.range.isCollapsed())return!1;const t=n.selection.focusedBlock;if(!ct(t))return!1;const e=n.selection.range.focus;return!e.isSimple()||e.offset!==0?!1:me(t)===1?(Jr(n,t),!0):(Zh(n,t),!0)}const KI=w("list-block");function JI(n,t,e){d(KI,ct(t),"not a list block");const o={...n.getBlockData(t),id:N()};return e!=null&&e.level&&(o.level=e.level),e!=null&&e.start&&(o.start=e.start),e!=null&&e.keepText||delete o.text,o}function XI(n){if(Ft(n),!$c(n))return n;let t=Zn(n);for(;t;){if(!$c(t))return t;t=Zn(t)}return null}function tx(n,t,e,o){const r=new ir(n,o),i=un(o)+1;Rr(n,t,e,{forceInsertAfter:!0,newBlockData:JI(n,o,{start:i})}),r.fix()}function ex(n){var s;if(n.selection.range.isCollapsed()){const l=n.selection.focusedBlock;if(ct(l)&&W(n,l)===0)return Jr(n,l),!0}n.clearSelectedContents();const t=n.selection.focusedBlock;if(!ct(t))return!1;const e=n.selection.range.focus;if(!e.isSimple())return!1;const o=e.offset,i=(s=o===W(n,t)?XI(t):t)!=null?s:t;return tx(n,t,o,i),!0}function l4(n){d(Ot,ct(n),"not a list block");const{level:t}=vo(n);let e=gt(n);for(;e;){if(ct(e)){const{level:o}=vo(e);if(t===o)return e;if(o<t)return null}e=gt(e)}return null}function c4(n,t){return Ft(t),l4(t)?me(t)<wI:!1}function nx(n,t,e){let o=gt(t);d(Ot,o,"no prev brother");const r=me(e);for(;o;){if(o===e)return null;if(ct(o)&&me(o)===r+1)return o;o=gt(o)}return null}function a4(n,t){if(!c4(n,t))return!1;Ft(t);const e=l4(t);d(Ot,e,"no list prev brother");const o=e,r=nx(n,t,o),i=me(o)+1;let s=N(),l=1,c=Fe(t);r&&(s=Yr(r),l=un(r)+1,c=Fe(r));const a=Gh(t),f={...n.getBlockData(t),groupId:s,level:i,start:l,...jh(c)};return n.updateBlockData(t,f),n.doc.beginBatchUpdate(),YI(a).forEach(C=>{const v=n.getBlockData(C);n.updateBlockData(C,{...v,level:v.level+1})}),n.doc.endBatchUpdate(),!0}function ox(n,t,e){return t.length===0||!t.every(o=>ct(o.block))?!1:e==="increase"?c4(n,t[0].block):i4(n,t[0].block)}function d4(n,t,e){if(!ox(n,t,e))return!1;const o=t[0].block,r=me(o),i=t.filter(a=>me(a.block)<=r),s=G5(o,{withSelf:!1}),l=new Set(i.map(a=>a.block)),c=s.filter(a=>!l.has(a));return n.undoManager.runInGroup(()=>{let a=null;c.length>0&&(a=new ir(n,c[0])),i.forEach(u=>{e==="increase"?a4(n,u.block):Zh(n,u.block)}),a==null||a.fix()}),!0}function rx(n,t){return a4(n,t)}function ix(n,t){return Zh(n,t)}function sx(n){const t=n.selection.range.getSelectedBlocks();if(t.length>1)return d4(n,t,"increase"),!0;const e=t[0].block;if(!ct(e))return!1;const o=new jc(n,e);return rx(n,e)&&(o.fix(),new ir(n,e).fix()),!0}function lx(n){const t=n.selection.range.getSelectedBlocks();if(t.length>1)return d4(n,t,"decrease"),!0;const e=t[0].block;return ct(e)?(ix(n,e),!0):!1}class cx{constructor(t){this.editor=t}handleBeforeKeyDown(t,e){const o=t.selection.range.getSelectedBlocks();if(o.length===0||!o.some(i=>ct(i.block)))return!1;switch(e.key){case"Enter":return this.handleEnter(e);case"Backspace":return this.handleBackspace();case"Tab":return this.handleTab(e);default:return!1}}handleEnter(t){const e=this.editor.selection.range.getSelectedBlocks()[0];return!e.block||!ct(e.block)||Pn(t,"Shift+Enter")?!1:this.editor.undoManager.runInGroup(()=>ex(this.editor))}handleBackspace(){return this.editor.undoManager.runInGroup(()=>QI(this.editor))}handleTab(t){return Pn(t,"Shift+Tab")?this.editor.undoManager.runInGroup(()=>lx(this.editor)):this.editor.undoManager.runInGroup(()=>sx(this.editor))}}class ax{constructor(t){h(this,"effectedBlockIds",new Map);h(this,"handleBeforeClearSelection",()=>{this.effectedBlockIds.clear();const t=this.editor.selection.range.getSelectedBlocks();if(t.length===0)return;const e=new Set;t.forEach(r=>{const i=r.block;ct(i)&&e.add(i)});const o=new Map;Array.from(e.values()).forEach(r=>{var c;const i=xs(r),{start:s}=vo(i);o.set(q(i),s);const l=(c=uI(r))!=null?c:r;o.set(q(l),s)}),this.effectedBlockIds=o});h(this,"handleAfterClearSelection",()=>{Array.from(this.effectedBlockIds.entries()).forEach(([t,e])=>{const o=this.editor.findBlockById(t);!o||Hh(this.editor,o,e)}),this.effectedBlockIds.clear()});this.editor=t,this.editor.addListener("beforeClearSelection",this.handleBeforeClearSelection),this.editor.addListener("afterClearSelection",this.handleAfterClearSelection)}destroy(){this.editor.removeListener("beforeClearSelection",this.handleBeforeClearSelection),this.editor.removeListener("afterClearSelection",this.handleAfterClearSelection)}}const dx=w("customize-list-start-menu");class ux{constructor(t){h(this,"popup");h(this,"block",null);h(this,"show",(t,e)=>{const o=e.querySelector("div.list-container");d(dx,o,"list-block mark does not exist"),this.block=e,this.popup.manualShow(o,{theme:"light"})});h(this,"createDialogContent",()=>{const t=b("div",["customize-start-panel"],null);b("span",["customize-start-panel-title"],t,T.t("list.numberLabel"));const e=b("input",["customize-start-panel-input"],t);e.type="number",e.setAttribute("min","1");const o=b("button",["customize-start-panel-button"],t,T.t("list.confirm"));return this.editor.domEvents.addEventListener(t,"keydown",this.handleKeydown),this.editor.domEvents.addEventListener(o,"click",this.handleOk),t});h(this,"handleDialogShow",()=>{const t=this.block;if(!t)return;const e=this.popup.popupContent,o=e.querySelector("button.customize-start-panel-button"),r=e.querySelector("input.customize-start-panel-input"),i=un(t);!o||!r||requestAnimationFrame(()=>{r.focus(),r.value=String(i)})});h(this,"handleOk",()=>{const e=this.popup.popupContent.querySelector("input.customize-start-panel-input"),o=this.block;if(!o)return;const r=Number(e.value);!r||(this.editor.undoManager.runInGroup(()=>{Ts(this.editor,[o,...Is(o)],r,{resetGroupId:!0})}),this.popup.close())});h(this,"handleKeydown",(t,e)=>{const o=e;o.isComposing||o.key==="Escape"&&this.popup.close()});this.editor=t,this.popup=new ms(this.createDialogContent()),this.popup.on("show",this.handleDialogShow)}destroy(){this.popup.destroy()}}function hx(n,t){return Yr(n)===Yr(t)}function fx(n,t){const e=Zn(t),o=gt(t);return!e&&!o||!o||!ct(o)?!1:ct(o)&&hx(o,t)?un(o)!==un(t)-1:!0}function mx(n,t){return!!Zn(t)}function gx(n,t){Ft(t);const e=[{id:"continue-numbering",name:T.t("list.continueList")},{id:"start-new-list",name:T.t("list.restartList")},{id:"set-numbering-value",name:T.t("list.changeNumber")}];return fx(n,t)||(e[0].states=["disabled"]),mx(n,t)||(e[1].states=["disabled"]),e}function px(n,t,e){var o,r;if(Ft(t),e.id==="continue-numbering"){const i=gt(t),s=Zn(t)||(i&&ct(i)?i:null);s&&Ts(n,[t,...Is(t)],un(s)+1,{resetGroupId:!0,groupId:Yr(s)})}if(e.id==="start-new-list"&&n.undoManager.runInGroup(()=>{Ts(n,[t,...Is(t)],1,{resetGroupId:!0})}),e.id==="set-numbering-value"){const i=(o=n.options.componentsOptions)==null?void 0:o.list;if((r=i==null?void 0:i.onChangeStart)!=null&&r.call(i,n,t,e))return;n.addCustom("list-customize-start-dialog",()=>new ux(n)).show(n,t)}}class Cx{constructor(t){h(this,"menu");h(this,"handleClick",(t,e)=>{const o=Di(e,"div.list-container");if(o&&this.editor.isWritable()){const r=F(o);d(Ot,r,"no parent block"),Ft(r);const i=t.getBlockData(r);if(i&&i.checkbox){t.updateBlockData(r,{...i,checkbox:i.checkbox==="checked"?"unchecked":"checked"});return}this.menu.updateItems(this.getCommandItems(r)),this.menu.manualShow(o),this.activeList(o,!0)}});h(this,"handleMenuClose",()=>{var e;const t=(e=this.menu.tippyInstance)==null?void 0:e.reference;t&&this.activeList(t,!1)});h(this,"handleMenuClick",(t,e)=>{var r;const o=(r=this.menu.tippyInstance)==null?void 0:r.reference;if(o){const i=F(o);i&&px(this.editor,i,e)}});this.editor=t,this.editor.addListener("click",this.handleClick),this.menu=new tr([]),this.menu.addListener("close",this.handleMenuClose),this.menu.addListener("click",this.handleMenuClick)}destroy(){this.editor.removeListener("click",this.handleClick),this.menu.removeListener("close",this.handleMenuClose)}getCommandItems(t){return gx(this.editor,t)}activeList(t,e){const o=F(t);!o||(e?(A(t,"active"),A(o,"active")):(z(t,"active"),z(o,"active")))}}class bx{constructor(t){this.editor=t}handleBeforeKeyDown(t,e){const o=t.selection.range.getSelectedBlocks();if(o.length===0)return!1;const r=o[0].block;if(!ct(r)||!e4(r))return!1;if(e.key==="ArrowUp"||e.key==="ArrowLeft"){const i=yr(r);return i&&t.selection.selectBlock(i,W(t,i)),!0}if(e.key==="ArrowDown"||e.key==="ArrowRight"){const i=wr(r);return i&&t.selection.selectBlock(i,0),!0}return(e.key==="Delete"||e.key==="Backspace"||e.key==="Escape")&&n4(t,r),!0}}function vx(n,t,e,o,r){Au(n,"list-block-init",()=>{setTimeout(()=>{n.input.addHandler(new bx(n)),n.input.addHandler(new cx(n)),n.addCustom("list-clear-selection-handler",()=>new ax(n)),n.addCustom("list-marker-menu",()=>new Cx(n))})});const i=ve.createBlockContent(n,t,e,o,r),s=r,{level:l,start:c,groupId:a}=s,u=Qr(s);o.setAttribute("data-list-level",`${l}`),o.setAttribute("data-list-start",`${c||1}`),o.setAttribute("data-list-group-id",`${a}`),o.setAttribute("data-list-type",u);const f=DI(s);return o.insertBefore(f,i),s.viewAsMindmap&&setTimeout(()=>{const m=n.getBlockById(r.id);m&&Wh(n,m,{},{mindmapTools:o4,saveData:!1})}),i}const kx=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
359
+ </svg>`;async function $I(n,t,e){const o=Rt(t),r=o.querySelector('[data-button-id="mindmap-fullscreen"]');d(Ot,r,"no full screen button");const i=()=>{setTimeout(()=>{e.toMindmap(n,t,{},{reset:!0,mindmapTools:e})},300)},s=()=>{z(o,"fullscreen"),r.innerHTML=X5,V2(r,"Full screen",n.clientId),e4(t)&&setTimeout(()=>{i()},300)};if(document.fullscreenElement===o){try{await t4()}catch(l){Ot.error(l)}s()}else{try{A(o,"fullscreen"),await OI(o),i()}catch(l){Ot.error(l)}r.innerHTML=NI,V2(r,T.t("mindmap.exitFullscreen"),n.clientId)}o.onfullscreenchange=()=>{document.fullscreenElement||s()}}function Uh(n,t,e,o,r){if(t.querySelector(`[data-button-id="${e}"]`))return null;const s=go(e,o,r,[],n.clientId);return A(s,"mindmap-button"),t.appendChild(s),s}function Vh(n,t){return n.querySelector(`[data-button-id="${t}"]`)}function PI(n){return Vh(n,"mindmap-fullscreen")}function jI(n){return Vh(n,"mindmap-fit")}function HI(n){return Vh(n,"mindmap-close")}function FI(n,t,e,o){const r=Uh(n,t,"mindmap-close",T.t("mindmap.close"),RI);!r||n.domEvents.addEventListener(r,"click",()=>{o.closeMindmap(n,e)})}function zI(n,t,e,o){const r=Uh(n,t,"mindmap-fit",T.t("mindmap.autoFit"),AI);!r||n.domEvents.addEventListener(r,"click",()=>{o.fitMindmap(n,e)})}function UI(n,t,e,o){if(navigator.userAgent.includes("Mobile")&&!navigator.userAgent.includes("iPad"))return;const i=Uh(n,t,"mindmap-fullscreen",T.t("mindmap.fullScreen"),X5);!i||n.domEvents.addEventListener(i,"click",()=>{$I(n,e,o)})}function VI(n,t){const e=Bl(t);if(!e)return;const o=jI(e);o&&(o.remove(),n.domEvents.removeAllListeners(o));const r=HI(e);r&&(r.remove(),n.domEvents.removeAllListeners(r));const i=PI(e);i&&(i.remove(),n.domEvents.removeAllListeners(i))}const Kr=new Map;function qh(n,t,e){const o=(s,l)=>{s.forEach(c=>{l?A(c.block,"to-mindmap-highlight"):z(c.block,"to-mindmap-highlight"),o(c.children,l)})},r=J5(n,t);if(r.length===0)return;const i=r[0].block;if(e){const s=Kr.get(i);s&&(s.forEach(l=>l.cancel()),Kr.delete(i)),o(r,!0)}else{const s=setTimeout(()=>{o(r,!1),Kr.delete(i)},300),l=()=>{clearTimeout(s),Kr.delete(i)},c=Kr.get(i);c?c.push({cancel:l}):Kr.set(i,[{cancel:l}])}}const{Markmap:qI}=C7;function WI(n,t){Ft(t);const e=J5(n,t),o=e[0].block,r=a=>({t:"text",v:it(a.block).textContent,d:1,c:a.children.length>0?a.children.map(f=>r(f)):void 0});let i=null;e.length>1?i={t:"root",v:"root",d:0,c:e.length>0?e.map(a=>r(a)):void 0}:i=r(e[0]);const l=a=>{if(a.length===0)return null;const u=a[a.length-1];return u.children&&u.children.length>0?l(u.children):u},c=l(e);return{root:i,block:o,nodes:e,last:c}}function Wh(n,t,e,o){const{root:r,block:i,last:s}=WI(n,t);o.selectBlock&&n.selection.selectBlock(i,0,0),qh(n,i,!1),o.saveData&&n.updateBlockData(i,{viewAsMindmap:!0});const l=Rt(i);let c=l.querySelector(".editor-mindmap-svg");if(o.reset&&(c&&c.remove(),c=null),c)c.innerHTML="";else{const S="http://www.w3.org/2000/svg",I=l.getBoundingClientRect(),M=document.fullscreenElement===l,R=M?`${I.width}`:`${t.getBoundingClientRect().width}`,$=M?`${I.height}`:"600",Z=document.createElementNS(S,"svg");Z.setAttributeNS(null,"viewBox",`0 0 ${R} ${$}`),Z.setAttributeNS(null,"width","100%"),Z.setAttributeNS(null,"height",$),Z.style.display="block",Z.style.width="100%",Z.style.height=`${$}px`,Z.classList.add("editor-mindmap-svg"),l.appendChild(Z),c=Z}const a=i,f=`editor-mindmap-root-${q(i)}`;A(a,"editor-in-mindmap-first",f,"readonly"),a.contentEditable="false";const m=dt(i);m&&J(m)<=J(s.block)&&_I(m,s.block,["block-hidden",f]);const C=(S,I)=>{if(I.length>0){const M=I[0].parentElement;M&&(M.style.width="100vw",M.style.maxWidth="200px")}I.forEach(M=>{A(M,"editor-mindmap-node")})},v=new qI(c,{...e,autoFit:!0});v.viewHooks.transformHtml.tap(C),v.setData(r),v.fit();const B=Rt(i);let y=B.querySelector(".mindmap-toolbar");y||(y=b("div",["mindmap-toolbar"],B)),zI(n,y,a,o.mindmapTools),UI(n,y,a,o.mindmapTools),FI(n,y,a,o.mindmapTools),n.domEvents.addEventListener(c,"click",()=>{n.selection.selectBlock(i,0),n.input.focus()}),a.mindMap=v}function GI(n){const t=n.classList,e="editor-mindmap-root-";return Array.from(t).find(r=>{if(r.startsWith(e))return r})}async function n4(n,t){const e=GI(t);if(!e)return;n.updateBlockData(t,{viewAsMindmap:null});const o=H(t);Mt(o).forEach(l=>{nt(l,e)&&z(l,e,"editor-in-mindmap-first","block-hidden")});const i=Rt(t);document.fullscreenElement===i&&await t4();const s=i.querySelector(".editor-mindmap-svg");d(Ot,s,"no mindmap svg"),s.remove(),n.domEvents.removeAllListeners(s),t.contentEditable="inherit",VI(n,t),n.selection.selectBlock(t,0)}function ZI(n,t){const e=t.mindMap;e&&e.fit()}const o4={toMindmap:Wh,closeMindmap:n4,fitMindmap:ZI};function r4(n){let t=dt(n);if(!t)return null;const e=rr(n);for(;t!==e;){if(d(Ot,t,"no next block"),ct(t))return me(t)>me(n)?t:null;if(t=dt(t),!t)return null}return null}function Gh(n){const t=[];let e=r4(n);if(!e)return t;for(;e;){const o=rr(e);t.push({block:e,children:Gh(e)}),e=o}return t}function YI(n){const t=(o,r)=>{r.push(o.block),o.children.forEach(i=>t(i,r))},e=[];return n.forEach(o=>t(o,e)),e}function i4(n,t){return me(t)!==1}function s4(n,t,e){t.forEach(o=>{const r=n.getBlockData(o.block);n.updateBlockData(o.block,{...r,groupId:e,level:r.level-1}),o.children.length&&s4(n,o.children,r.groupId)})}function Zh(n,t){if(!i4(n,t))return!1;const e=me(t);if(e===1)return!1;let o=N(),r=1,i=Fe(t);const s=e-1,l=zh(t);l&&(o=Yr(l),r=un(l)+1,i!=="text-only"&&(i=Fe(l)));const c=Gh(t),a=n.getBlockData(t),u={...a,groupId:o,level:s,start:r,...jh(i)};n.updateBlockData(t,u),n.doc.beginBatchUpdate(),s4(n,c,a.groupId),n.doc.endBatchUpdate(),new ir(n,t).fix();const m=r4(t);return m&&new ir(n,m,{resetStart:!0,resetGroupId:!0}).fix(),!0}function Jr(n,t){Ft(t);const e=n.getBlockData(t),o={id:N(),type:"text",text:e.text};e.heading&&(o.heading=e.heading),e.heading&&(o.heading=e.heading);const r=new jc(n,t),i=H(t),s=J(t);n.deleteBlock(t);const l=Fl(o.id,0);n.insertBlock(U(i),s,o,l),r.fix()}function QI(n){if(!n.selection.range.isCollapsed())return!1;const t=n.selection.focusedBlock;if(!ct(t))return!1;const e=n.selection.range.focus;return!e.isSimple()||e.offset!==0?!1:me(t)===1?(Jr(n,t),!0):(Zh(n,t),!0)}const KI=w("list-block");function JI(n,t,e){d(KI,ct(t),"not a list block");const o={...n.getBlockData(t),id:N()};return e!=null&&e.level&&(o.level=e.level),e!=null&&e.start&&(o.start=e.start),e!=null&&e.keepText||delete o.text,o}function XI(n){if(Ft(n),!$c(n))return n;let t=Zn(n);for(;t;){if(!$c(t))return t;t=Zn(t)}return null}function tx(n,t,e,o){const r=new ir(n,o),i=un(o)+1;Rr(n,t,e,{forceInsertAfter:!0,newBlockData:JI(n,o,{start:i})}),r.fix()}function ex(n){var s;if(n.selection.range.isCollapsed()){const l=n.selection.focusedBlock;if(ct(l)&&W(n,l)===0)return Jr(n,l),!0}n.clearSelectedContents();const t=n.selection.focusedBlock;if(!ct(t))return!1;const e=n.selection.range.focus;if(!e.isSimple())return!1;const o=e.offset,i=(s=o===W(n,t)?XI(t):t)!=null?s:t;return tx(n,t,o,i),!0}function l4(n){d(Ot,ct(n),"not a list block");const{level:t}=vo(n);let e=gt(n);for(;e;){if(ct(e)){const{level:o}=vo(e);if(t===o)return e;if(o<t)return null}e=gt(e)}return null}function c4(n,t){return Ft(t),l4(t)?me(t)<wI:!1}function nx(n,t,e){let o=gt(t);d(Ot,o,"no prev brother");const r=me(e);for(;o;){if(o===e)return null;if(ct(o)&&me(o)===r+1)return o;o=gt(o)}return null}function a4(n,t){if(!c4(n,t))return!1;Ft(t);const e=l4(t);d(Ot,e,"no list prev brother");const o=e,r=nx(n,t,o),i=me(o)+1;let s=N(),l=1,c=Fe(t);r&&(s=Yr(r),l=un(r)+1,c=Fe(r));const a=Gh(t),f={...n.getBlockData(t),groupId:s,level:i,start:l,...jh(c)};return n.updateBlockData(t,f),n.doc.beginBatchUpdate(),YI(a).forEach(C=>{const v=n.getBlockData(C);n.updateBlockData(C,{...v,level:v.level+1})}),n.doc.endBatchUpdate(),!0}function ox(n,t,e){return t.length===0||!t.every(o=>ct(o.block))?!1:e==="increase"?c4(n,t[0].block):i4(n,t[0].block)}function d4(n,t,e){if(!ox(n,t,e))return!1;const o=t[0].block,r=me(o),i=t.filter(a=>me(a.block)<=r),s=G5(o,{withSelf:!1}),l=new Set(i.map(a=>a.block)),c=s.filter(a=>!l.has(a));return n.undoManager.runInGroup(()=>{let a=null;c.length>0&&(a=new ir(n,c[0])),i.forEach(u=>{e==="increase"?a4(n,u.block):Zh(n,u.block)}),a==null||a.fix()}),!0}function rx(n,t){return a4(n,t)}function ix(n,t){return Zh(n,t)}function sx(n){const t=n.selection.range.getSelectedBlocks();if(t.length>1)return d4(n,t,"increase"),!0;const e=t[0].block;if(!ct(e))return!1;const o=new jc(n,e);return rx(n,e)&&(o.fix(),new ir(n,e).fix()),!0}function lx(n){const t=n.selection.range.getSelectedBlocks();if(t.length>1)return d4(n,t,"decrease"),!0;const e=t[0].block;return ct(e)?(ix(n,e),!0):!1}class cx{constructor(t){this.editor=t}handleBeforeKeyDown(t,e){const o=t.selection.range.getSelectedBlocks();if(o.length===0||!o.some(i=>ct(i.block)))return!1;switch(e.key){case"Enter":return this.handleEnter(e);case"Backspace":return this.handleBackspace();case"Tab":return this.handleTab(e);default:return!1}}handleEnter(t){const e=this.editor.selection.range.getSelectedBlocks()[0];return!e.block||!ct(e.block)||jn(t,"Shift+Enter")?!1:this.editor.undoManager.runInGroup(()=>ex(this.editor))}handleBackspace(){return this.editor.undoManager.runInGroup(()=>QI(this.editor))}handleTab(t){return jn(t,"Shift+Tab")?this.editor.undoManager.runInGroup(()=>lx(this.editor)):this.editor.undoManager.runInGroup(()=>sx(this.editor))}}class ax{constructor(t){h(this,"effectedBlockIds",new Map);h(this,"handleBeforeClearSelection",()=>{this.effectedBlockIds.clear();const t=this.editor.selection.range.getSelectedBlocks();if(t.length===0)return;const e=new Set;t.forEach(r=>{const i=r.block;ct(i)&&e.add(i)});const o=new Map;Array.from(e.values()).forEach(r=>{var c;const i=xs(r),{start:s}=vo(i);o.set(q(i),s);const l=(c=uI(r))!=null?c:r;o.set(q(l),s)}),this.effectedBlockIds=o});h(this,"handleAfterClearSelection",()=>{Array.from(this.effectedBlockIds.entries()).forEach(([t,e])=>{const o=this.editor.findBlockById(t);!o||Hh(this.editor,o,e)}),this.effectedBlockIds.clear()});this.editor=t,this.editor.addListener("beforeClearSelection",this.handleBeforeClearSelection),this.editor.addListener("afterClearSelection",this.handleAfterClearSelection)}destroy(){this.editor.removeListener("beforeClearSelection",this.handleBeforeClearSelection),this.editor.removeListener("afterClearSelection",this.handleAfterClearSelection)}}const dx=w("customize-list-start-menu");class ux{constructor(t){h(this,"popup");h(this,"block",null);h(this,"show",(t,e)=>{const o=e.querySelector("div.list-container");d(dx,o,"list-block mark does not exist"),this.block=e,this.popup.manualShow(o,{theme:"light"})});h(this,"createDialogContent",()=>{const t=b("div",["customize-start-panel"],null);b("span",["customize-start-panel-title"],t,T.t("list.numberLabel"));const e=b("input",["customize-start-panel-input"],t);e.type="number",e.setAttribute("min","1");const o=b("button",["customize-start-panel-button"],t,T.t("list.confirm"));return this.editor.domEvents.addEventListener(t,"keydown",this.handleKeydown),this.editor.domEvents.addEventListener(o,"click",this.handleOk),t});h(this,"handleDialogShow",()=>{const t=this.block;if(!t)return;const e=this.popup.popupContent,o=e.querySelector("button.customize-start-panel-button"),r=e.querySelector("input.customize-start-panel-input"),i=un(t);!o||!r||requestAnimationFrame(()=>{r.focus(),r.value=String(i)})});h(this,"handleOk",()=>{const e=this.popup.popupContent.querySelector("input.customize-start-panel-input"),o=this.block;if(!o)return;const r=Number(e.value);!r||(this.editor.undoManager.runInGroup(()=>{Ts(this.editor,[o,...Is(o)],r,{resetGroupId:!0})}),this.popup.close())});h(this,"handleKeydown",(t,e)=>{const o=e;o.isComposing||o.key==="Escape"&&this.popup.close()});this.editor=t,this.popup=new ms(this.createDialogContent()),this.popup.on("show",this.handleDialogShow)}destroy(){this.popup.destroy()}}function hx(n,t){return Yr(n)===Yr(t)}function fx(n,t){const e=Zn(t),o=gt(t);return!e&&!o||!o||!ct(o)?!1:ct(o)&&hx(o,t)?un(o)!==un(t)-1:!0}function mx(n,t){return!!Zn(t)}function gx(n,t){Ft(t);const e=[{id:"continue-numbering",name:T.t("list.continueList")},{id:"start-new-list",name:T.t("list.restartList")},{id:"set-numbering-value",name:T.t("list.changeNumber")}];return fx(n,t)||(e[0].states=["disabled"]),mx(n,t)||(e[1].states=["disabled"]),e}function px(n,t,e){var o,r;if(Ft(t),e.id==="continue-numbering"){const i=gt(t),s=Zn(t)||(i&&ct(i)?i:null);s&&Ts(n,[t,...Is(t)],un(s)+1,{resetGroupId:!0,groupId:Yr(s)})}if(e.id==="start-new-list"&&n.undoManager.runInGroup(()=>{Ts(n,[t,...Is(t)],1,{resetGroupId:!0})}),e.id==="set-numbering-value"){const i=(o=n.options.componentsOptions)==null?void 0:o.list;if((r=i==null?void 0:i.onChangeStart)!=null&&r.call(i,n,t,e))return;n.addCustom("list-customize-start-dialog",()=>new ux(n)).show(n,t)}}class Cx{constructor(t){h(this,"menu");h(this,"handleClick",(t,e)=>{const o=Di(e,"div.list-container");if(o&&this.editor.isWritable()){const r=F(o);d(Ot,r,"no parent block"),Ft(r);const i=t.getBlockData(r);if(i&&i.checkbox){t.updateBlockData(r,{...i,checkbox:i.checkbox==="checked"?"unchecked":"checked"});return}this.menu.updateItems(this.getCommandItems(r)),this.menu.manualShow(o),this.activeList(o,!0)}});h(this,"handleMenuClose",()=>{var e;const t=(e=this.menu.tippyInstance)==null?void 0:e.reference;t&&this.activeList(t,!1)});h(this,"handleMenuClick",(t,e)=>{var r;const o=(r=this.menu.tippyInstance)==null?void 0:r.reference;if(o){const i=F(o);i&&px(this.editor,i,e)}});this.editor=t,this.editor.addListener("click",this.handleClick),this.menu=new tr([]),this.menu.addListener("close",this.handleMenuClose),this.menu.addListener("click",this.handleMenuClick)}destroy(){this.editor.removeListener("click",this.handleClick),this.menu.removeListener("close",this.handleMenuClose)}getCommandItems(t){return gx(this.editor,t)}activeList(t,e){const o=F(t);!o||(e?(A(t,"active"),A(o,"active")):(z(t,"active"),z(o,"active")))}}class bx{constructor(t){this.editor=t}handleBeforeKeyDown(t,e){const o=t.selection.range.getSelectedBlocks();if(o.length===0)return!1;const r=o[0].block;if(!ct(r)||!e4(r))return!1;if(e.key==="ArrowUp"||e.key==="ArrowLeft"){const i=yr(r);return i&&t.selection.selectBlock(i,W(t,i)),!0}if(e.key==="ArrowDown"||e.key==="ArrowRight"){const i=wr(r);return i&&t.selection.selectBlock(i,0),!0}return(e.key==="Delete"||e.key==="Backspace"||e.key==="Escape")&&n4(t,r),!0}}function vx(n,t,e,o,r){Au(n,"list-block-init",()=>{setTimeout(()=>{n.input.addHandler(new bx(n)),n.input.addHandler(new cx(n)),n.addCustom("list-clear-selection-handler",()=>new ax(n)),n.addCustom("list-marker-menu",()=>new Cx(n))})});const i=ve.createBlockContent(n,t,e,o,r),s=r,{level:l,start:c,groupId:a}=s,u=Qr(s);o.setAttribute("data-list-level",`${l}`),o.setAttribute("data-list-start",`${c||1}`),o.setAttribute("data-list-group-id",`${a}`),o.setAttribute("data-list-type",u);const f=DI(s);return o.insertBefore(f,i),s.viewAsMindmap&&setTimeout(()=>{const m=n.getBlockById(r.id);m&&Wh(n,m,{},{mindmapTools:o4,saveData:!1})}),i}const kx=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
360
360
  <path d="M8 8H15" stroke="currentColor" stroke-linecap="square" stroke-linejoin="round"></path>
361
361
  <path d="M8 14H15" stroke="currentColor" stroke-linecap="square" stroke-linejoin="round"></path>
362
362
  <path d="M8 2H15" stroke="currentColor" stroke-linecap="square" stroke-linejoin="round"></path>
@@ -364,7 +364,7 @@ xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
364
364
  </svg>
365
365
  `;function yx(n){return go("list-to-mindmap",T.t("mindmap.viewAsMindMap"),kx,[],n.clientId)}const gz="";class Hc{constructor(t){h(this,"toMindmapButton");h(this,"currentBlock",null);h(this,"handleHoveringBlock",t=>{!this.editor.isWritable()||(t&&ct(t)&&Fe(t)!=="unchecked"&&Fe(t)!=="checked"?Rt(t).appendChild(this.toMindmapButton):this.toMindmapButton.remove())});h(this,"handleMouseEnter",()=>{const t=F(this.toMindmapButton);d(Ot,t&&ct(t),"no parent list"),qh(this.editor,t,!0),this.currentBlock=t});h(this,"handleMouseLeave",()=>{this.currentBlock&&(qh(this.editor,this.currentBlock,!1),this.currentBlock=null)});h(this,"handleClick",()=>{const t=F(this.toMindmapButton);d(Ot,t&&ct(t),"no parent list"),Wh(this.editor,t,{},{saveData:!0,selectBlock:!0,mindmapTools:o4})});this.editor=t,Nt.get(this.editor).addListener("change",this.handleHoveringBlock),this.toMindmapButton=yx(t),t.domEvents.addEventListener(this.toMindmapButton,"mouseenter",this.handleMouseEnter),t.domEvents.addEventListener(this.toMindmapButton,"mouseleave",this.handleMouseLeave),t.domEvents.addEventListener(this.toMindmapButton,"click",this.handleClick)}static get(t){return t.findCustomByType(Hc)}destroy(){Nt.get(this.editor).removeListener("change",this.handleHoveringBlock)}hide(){this.currentBlock&&(this.currentBlock=null),this.toMindmapButton.remove()}}const wx={list:{confirm:"\u786E\u5B9A",setStart:"\u8BBE\u7F6E\u7F16\u53F7",continueList:"\u7EE7\u7EED\u7F16\u53F7",restartList:"\u5F00\u59CB\u65B0\u5217\u8868",changeNumber:"\u4FEE\u6539\u7F16\u53F7\u503C",numberLabel:"\u7F16\u53F7\u987A\u5E8F",mention:{tooltip:"\u63D0\u53CA\u4EBA\u5458\u5E76\u901A\u77E5"}},mindmap:{viewAsMindMap:"\u663E\u793A\u4E3A\u8111\u56FE",autoFit:"\u81EA\u52A8\u7F29\u653E",fullScreen:"\u5168\u5C4F\u67E5\u770B",close:"\u5173\u95ED",exitFullscreen:"\u9000\u51FA\u5168\u5C4F"}},Bx={list:{confirm:"OK",setStart:"Set the number",continueList:"Continue numbering",restartList:"Start a new list",changeNumber:"Set numbering value",numberLabel:"Numbering order",mention:{tooltip:"@Mention someone"}},mindmap:{viewAsMindMap:"View as MindMap",autoFit:"Auto fit",fullScreen:"Fullscreen",close:"Close",exitFullscreen:"Exit fullscreen"}};T.mergeLang({"zh-CN":wx,"en-US":Bx});const pz="";function Ex(n,t,e){var o;t==="beginDrag"&&((o=Hc.get(n))==null||o.hide())}const u4={...ve,blockType:"list",createBlockContent:vx,convertFrom:vI,convertTo:yI,handleDrop:II,notify:Ex},Yh=w("paragraph");class Ix{constructor(t){h(this,"id","BlockParagraphProvider");this.editor=t}isChecked(t,e){return!!(t[e]||t.level&&(t.ordered===!0&&!t.checkbox&&e==="ordered-list"||t.ordered===!1&&!t.checkbox&&e==="unordered-list")||e==="check-list"&&t.checkbox)}getAvailableCommands(t,e){const o=[],r={"unordered-list":[T.t("commands.unordered"),xt.isMac?T.t("commandDesc.mac.unordered"):T.t("commandDesc.window.unordered"),$w],"ordered-list":[T.t("commands.ordered"),xt.isMac?T.t("commandDesc.mac.ordered"):T.t("commandDesc.window.ordered"),Nw],"check-list":[T.t("commands.check"),void 0,Pw],link:[T.t("commands.link"),xt.isMac?T.t("commandDesc.mac.link"):T.t("commandDesc.window.link"),n5],quoted:[T.t("commands.quote"),void 0,jw]};if(j(t,e)){const i=q(e),s=rt(e),l=Qe(t,e),c=t.getBlockData(e);Object.entries(r).forEach(([a,[u,f,m]])=>{const C=[];if(this.isChecked(c,a)&&C.push("checked"),a==="link"){if(!t.selection.range.isSimple())return;t.selection.range.getSelectedBlocks().length!==1&&C.push("disabled")}o.push({blockId:i,blockType:s,blockKind:l,id:a,name:u,desc:f,states:C,icon:m,groupIndex:600})})}return o}convertLink(t,e,o){d(Yh,Ir(e.start),""),d(Yh,Ir(e.start),"");const r="bottom-start",i=e.start.offset,s=e.end.offset,l=(C,v)=>{t.undoManager.runInGroup(()=>{try{let B=$l(t.getBlockText(o),i,s,C);B=_l(i,C.length,B,"link",v),t.setBlockText(o,B),t.selection.selectBlock(o,i+C.length),t.focus()}catch(B){Yh.error(B)}})},c=()=>{t.focus()},a=Ho(t,o,e)[0];if(!a)return;const u=zo(t,o,"link-button-anchor",a),f=t.getBlockText(o),m=Nl(f,i);Rc(t,{target:u,linkText:t.getSelectedText(),linkUrl:(m==null?void 0:m.link)||"",onFinished:l,onClose:c,placement:r})}convertToList(t,e,o){const r=Oi(t,e,"list",{offset:0,data:{listType:o}});r&&t.undoManager.runInGroup(()=>{const i=J(e),s=H(e);t.deleteBlock(e),t.insertBlock(U(s),i,r.blockData)})}executeCommand(t,e,o,r){var c;if(!j(t,e))return!1;const i=r.id,s=(c=r.states)==null?void 0:c.includes("checked");let l=!1;if(i==="unordered-list"&&(s?Jr(t,e):this.convertToList(t,e,"unordered"),l=!0),i==="ordered-list"&&(s?Jr(t,e):this.convertToList(t,e,"ordered"),l=!0),i==="check-list"&&(s?Jr(t,e):this.convertToList(t,e,"unchecked"),l=!0),i==="quoted"){const u=t.getBlockData(e).quoted;t.updateBlockData(e,{quoted:u?void 0:!0}),l=!0}if(i==="link"){const a=Mc(t);a.disableTextToolbar(),a.hide(),setTimeout(()=>{a.enableTextToolbar()},1e3),this.convertLink(t,o,e),l=!0}return l}}const xx={left:gs,right:lh,center:ch};class Tx{constructor(t){h(this,"id","BlockAlignProvider");this.editor=t}applyAlignStyle(t,e,o){Object.keys(xx).includes(o)?t.updateBlockData(e,{align:o}):t.updateBlockData(e,{align:null})}isChecked(t,e){return t.align===e}getAvailableCommands(t,e,o){if(j(t,e)){const r=q(e),i=rt(e),s=Qe(t,e),l=t.getBlockData(e),c=a=>{var f;const u=b("span",["toolbar-item-name-container"],null);for(const m of a.children)if((f=m.states)!=null&&f.includes("checked"))return u.innerHTML=m.icon||gs,u;return u.innerHTML=gs,u};return[{id:"align",name:T.t("commands.alignGroup"),blockId:r,blockType:i,blockKind:s,groupIndex:700,dropdown:!0,element:c,manualShowChildren:!0,childrenPlacement:"bottom-start",defaultCheckedChildren:["align-left"],children:[{id:"align-left",name:T.t("commands.alignLeft"),icon:gs,states:this.isChecked(l,"left")?["checked"]:[]},{id:"align-center",name:T.t("commands.alignCenter"),icon:ch,states:this.isChecked(l,"center")?["checked"]:[]},{id:"align-right",name:T.t("commands.alignRight"),icon:lh,states:this.isChecked(l,"right")?["checked"]:[]}],childrenType:"menu"}]}return[]}executeCommand(t,e,o,r){if(r.id.startsWith("align")){const i=r.id.replace(/^align-/,"");return this.applyAlignStyle(t,e,i),!0}return!1}}function Sx(n){const e=n.selection.range;if(e.isCollapsed()||e.start.blockId!==e.end.blockId||!e.start.isSimple()||!e.end.isSimple()||e.end.offset-e.start.offset!==1)return!1;const o=n.getBlockById(e.start.blockId);return Ui(n,o,e.start.offset).charType==="box"}const Dx=w("toolbar-handler"),Lx={id:"",name:"",type:"separator"};class Xr{constructor(t){h(this,"toolbar");h(this,"toolbarType","object");h(this,"mouseDown",!1);h(this,"oldRange",null);h(this,"hoveringBlock",null);h(this,"hoveringTextChild",null);h(this,"_disableTextToolbar",!1);h(this,"handleButtonClick",(t,e)=>{this.toolbarType==="text"?(this.editor.editorCommandProviders.executeCommand(this.editor.selection.range,e,{}),this.showTextToolbar("click")):this.hoveringBlock&&tI(this.editor,this.hoveringBlock,this.hoveringTextChild,e)});h(this,"handleClose",()=>{hh(this.editor)&&this.editor.focus()});h(this,"handleDocumentMouseDown",t=>{t.button===0&&(document.addEventListener("mouseup",this.handleDocumentMouseUp),this.mouseDown=!0)});h(this,"handleDocumentMouseUp",()=>{document.removeEventListener("mouseup",this.handleDocumentMouseUp),this.mouseDown=!1,this.handleSelectionChange(this.editor)});h(this,"handleHoveringBlockChildChange",(t,e,o,r)=>{if(!(this.hoveringBlock===t&&this.hoveringTextChild===e)&&(this.hoveringBlock=t,this.hoveringTextChild=e,!(this.toolbar.isVisible&&this.toolbarType==="text"))){if(!t){this.toolbar.close();return}this.showObjectToolbar()}});h(this,"handleSelectionChange",Xt.default(t=>{if(d(Dx,t===this.editor,"editor mismatch"),t.selection.range.isCollapsed()||this.mouseDown){this.toolbar.close(),this.oldRange=null;return}if(t.selection.range.getSelectedBlocks().length===0){this.toolbar.close(),this.oldRange=null;return}this.oldRange&&this.oldRange.isEqual(t.selection.range)||(this.oldRange=t.selection.range,this.showTextToolbar("selectionChange"))},50));this.editor=t;const e=t.options.componentsOptions.popover;this.toolbar=new ps([],void 0,{tooltipId:t.clientId,id:"editor-toolbar",overflowBoundary:e==null?void 0:e.overflowBoundary,refuseOverflow:!0}),this.toolbar.on("click",this.handleButtonClick),this.toolbar.on("close",this.handleClose),this.bindEvents(),t.addListener("selectionChanged",this.handleSelectionChange),Nt.get(t).addListener("childChange",this.handleHoveringBlockChildChange),Nt.get(t).addFilter(this),t.editorCommandProviders.registerCommandProvider(new nI(t)),t.editorCommandProviders.registerCommandProvider(new Ix(t)),t.editorCommandProviders.registerCommandProvider(new Tx(t))}disableTextToolbar(){this._disableTextToolbar=!0}enableTextToolbar(){this._disableTextToolbar=!1}hide(){this.toolbar.close()}destroy(){this.unbindEvents(),this.toolbar.destroy(),this.editor.removeListener("selectionChanged",this.handleSelectionChange),Nt.get(this.editor).removeListener("childChange",this.handleHoveringBlockChildChange)}isInBlock(t,e){return t!==this.hoveringBlock?!1:!!(e.target&&e.target instanceof Node&&this.toolbar.popper&&It(this.toolbar.popper,e.target))}bindEvents(){document.addEventListener("mousedown",this.handleDocumentMouseDown)}unbindEvents(){document.removeEventListener("mousedown",this.handleDocumentMouseDown)}update(t){this.showTextToolbar(t)}showTextToolbar(t){if(this._disableTextToolbar||!this.editor.isWritable())return;const o=this.editor.selection.range.getSelectedBlocks();if(o.length===0)return;const r=o[0];if(!r)return;if(o.length===1&&Te(r.block)){t==="click"&&this.showObjectToolbar();return}if(Sx(this.editor))return;const i=this.editor.editorCommandProviders.getCommands(this.editor.selection.range),s=new Map;i.forEach(u=>{const f=u.groupIndex,m=s.get(f);m?m.push(u):s.set(f,[u])});const l=[[]],c=Array.from(s.entries()).sort((u,f)=>u[0]-f[0]);for(let u=0;u<c.length;u++){const[,f]=c[u];if(f.length===0)continue;let m=l[l.length-1];m.length>0&&m[m.length-1].groupIndex!==f[f.length-1].groupIndex&&(m=[],l.push(m)),m.push(...Lc(f))}if(l.length===0){this.toolbar.close();return}this.toolbarType="text";const a=[];if(l.forEach((u,f)=>{const m=u.sort((C,v)=>{var B,y;return((B=C.order)!=null?B:0)-((y=v.order)!=null?y:0)});a.push(...m),f!==l.length-1&&a.push(Lx)}),a.length===0){this.toolbar.close();return}if(this.toolbar.updateItems(a),!this.toolbar.isVisible){const u=o[o.length-1],f=!this.editor.selection.range.isReverse()&&u!==r,m=f?u:r,C=WE(this.editor,m),v=zo(this.editor,m.block,"editor-quick-menu",C);this.toolbar.manualShow(v,{placement:f?"bottom":"top"})}}showObjectToolbar(){var r,i;if(!this.hoveringBlock)return;const t=this.hoveringBlock,e=this.hoveringTextChild,o=KE(this.editor,t,e);if(!o.length){this.toolbar.close();return}this.toolbarType="object",this.toolbar.isVisible&&((i=(r=this.toolbar)==null?void 0:r.tippyInstance)==null?void 0:i.reference)!==t&&this.toolbar.close(),this.toolbar.updateItems(o),this.toolbar.isVisible||this.toolbar.manualShow(e||it(t),{placement:e?"bottom":"top"})}static register(t){return t.addCustom("toolbar-handler",e=>new Xr(e))}static get(t){return t.getCustom("toolbar-handler")}}const Mx=[Xu,th,eh,nh,oh,rh,ih,sh],Rx={Unordered:i5,Ordered:s5,Checkbox:o5,Quote:r5};function Qh(n,t){const e=n;e.blockOptions=t,e.itemType="insert-block",n.children&&n.children.forEach(o=>Qh(o,t))}function Ax(n,t,e){n.getBlockData(t).heading===e?n.updateBlockData(t,{heading:null}):n.updateBlockData(t,{heading:e})}function Kh(n=1){var r;const t={name:"basic",insertBlockCommandItems:[]};let e=Oc();e<=4?e=5:e<8&&(e+=1);let o=n;for(;o<=e;){const i=`heading-${o}`;(r=t.insertBlockCommandItems)==null||r.push({id:i,icon:Mx[o-1],name:T.t("quickMenu.basic.heading.title",{heading:String(o)}),order:o,group:"basics",value:String(o),subText:fe(i)}),o++}return t}function Ox(){const n={name:"basic",insertBlockCommandItems:[]};return["Unordered","Ordered","Checkbox","Quote"].forEach((e,o)=>{var i;const r=`insert-${e.toLocaleLowerCase()}`;(i=n.insertBlockCommandItems)==null||i.push({id:r,name:T.t(`quickMenu.basic.${e.toLocaleLowerCase()}`),icon:Rx[e],value:e.toLocaleLowerCase(),group:"basics",order:10+o,subText:fe(r)})}),n}class h4{getCommands(){const t=Kh(),e=Ox();return[...t.insertBlockCommandItems||[],...e.insertBlockCommandItems||[]]}updateBlock(t,e,o,r){const{value:i,id:s}=r;if(s.startsWith("heading-"))Ax(t,o,Number.parseInt(i!=null?i:"1",10)||1);else if(i==="ordered"||i==="unordered"||i==="checkbox"){if(!t.selection.range.focus.isSimple())return null;const c=Oi(t,o,"list",{offset:0,data:{listType:i==="checkbox"?"unchecked":i}});if(c){const a=t.getBlockIndex(o);t.deleteBlock(o),t.insertBlock(e,a,c.blockData)}}else i==="quote"&&t.updateBlockData(o,{quoted:!0});return null}async handleUpdateBlockCore(t,e){const o=t.getBlockByIndex(e.containerId,e.blockIndex);return this.updateBlock(t,e.containerId,o,e.item)}async handleInsertEmptyBlockCore(t,e){const{containerId:o,blockIndex:r}=e,i=t.insertTextBlock(void 0,o,r);return this.updateBlock(t,e.containerId,i,e.item)}async executeCommand(t,e,o){if(o.from==="quick-menu"){const r=t.getBlockById(o.blockId),i=t.getParentContainer(r),s=U(i),l=t.getBlockIndex(r);t.undoManager.runInGroup(()=>this.handleUpdateBlockCore(t,{item:e,containerId:s,blockIndex:l}))}else o.from==="block-menu"&&t.undoManager.runInGroup(()=>this.handleInsertEmptyBlockCore(t,{item:e,containerId:o.containerId,blockIndex:o.blockIndex}));return null}}class Jh{constructor(){h(this,"dataUrl","");h(this,"error",null)}destroy(){}setDataUrl(t){this.error=null,this.dataUrl=t}setError(t){this.dataUrl="",this.error=t}}const _x=w("mathjax-converter"),Nx="MathJax-script";async function $x(n){var o;window.MathJax||(window.MathJax={options:{skipHtmlTags:["script","noscript","style","textarea","pre","code","annotation","annotation-xml","body"]}});const t=n.getComponentOptions("mathjax"),e=((o=t==null?void 0:t.cdn)==null?void 0:o.mathjax)||"https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js";await Ro(e,Nx)}function Px(){try{window.MathJax&&window.MathJax.texReset()}catch{}}async function f4(n,t){const e="mathjax2Svg";try{await qe.lock(e),Px(),await $x(n);const o=await window.MathJax.tex2svgPromise(t),r=o.querySelector("merror");if(r)throw new Error(r.textContent);return o.querySelector("svg").outerHTML}catch(o){throw _x.error(o),o}finally{qe.release(e)}}async function m4(n,t){const e=await f4(n,t);return e?await Bm(e,"image/svg+xml"):""}async function Xh(n,t){const o=await f4(n,t),r=new File([o],"math.svg");return(await n.doc.uploadResource(r)).resourceId}const g4=w("edit-mathjax");class jx{constructor(){h(this,"editMathjaxPopup",null);h(this,"onChange",null);h(this,"tex","");h(this,"handleShow",()=>{setTimeout(()=>{this.getTextarea().focus()})});h(this,"handleClose",t=>{var o;const e=t.content.querySelector("textarea");if(e){const r=e.value;r!==this.tex&&((o=this.onChange)==null||o.call(this,r))}});h(this,"handleKeyup",t=>{var e;t.isComposing||(t.key==="Escape"&&((e=this.editMathjaxPopup)==null||e.close()),this.handleChange(t.target.value))});h(this,"handleChange",Xt.default(t=>{var e;(e=this.onChange)==null||e.call(this,t)},300))}editMathjax(t,e,o){if(!this.editMathjaxPopup)this.editMathjaxPopup=new ms(this.createPopupContent(e));else{const r=this.getTextarea();r.value=e}this.tex=e,this.editMathjaxPopup.addListener("show",this.handleShow),this.editMathjaxPopup.manualShow(t,{theme:"light"}),this.editMathjaxPopup.removeAllListeners("close"),this.editMathjaxPopup.addListener("close",this.handleClose),this.onChange=o}createPopupContent(t){const e=b("textarea",["mathjax-editor-textarea"],null);return e.value=t,e.addEventListener("keyup",this.handleKeyup),e}getTextarea(){d(g4,this.editMathjaxPopup,"no exists mathjax editor popup");const t=this.editMathjaxPopup.content.querySelector("textarea");return d(g4,t,"no textarea"),t}destroy(){var t;this.onChange=null,(t=this.editMathjaxPopup)==null||t.removeAllListeners()}}function p4(n,t,e,o){n.addCustom("mathjax-editor",()=>new jx).editMathjax(t,e.trim(),o)}function Hx(){return{insert:" ",attributes:{id:N(),box:!0,type:"math",tex:" ",src:"",created:Date.now()}}}function t1(n,t){const e=n.getBoxData(t),o=F(t);if(!o)return;const r=so(o,t);n.selection.selectBlock(o,r.start,r.end);const i=async s=>{if(!s.trim()){n.updateBoxData({...e,tex:s,src:null});return}try{await qe.lock("convertAndUploadMathjax");const l=await Xh(n,s);n.updateBoxData({...e,tex:s,src:l})}catch(l){const c=n.getBoxData(t);n.addCustom(`mathjax-box-${c.id}`,()=>new Jh).setError(l),n.updateBoxData({...e,tex:s,src:""})}finally{qe.release("convertAndUploadMathjax")}};p4(n,t,e.tex,i)}const Fx=w("mathjax-box");function e1(n,t){n.selection.updateSelection(null);const e=t.target;!e||!(e instanceof HTMLElement)||n.domEvents.removeEventListener(e,null,e1)}async function zx(n,t,e){try{if(!t.tex.trim())return;const o=await m4(n,t.tex),r=n.findBoxById(t.id);if(!r)return;const i=gd(r);i.innerHTML="";const s=b("img",["mathjax"],i);s.src=o,e.setDataUrl(o),n.domEvents.addEventListener(s,"load",e1)}catch(o){e.setError(o);const r=n.findBoxById(t.id);if(!r)return;const i=r.querySelector(".mathjax-tex-text");A(i,"mathjax-error"),i.innerText=o.message,n.selection.updateSelection(null)}}function Ux(n,t,e,o){const r=o,i=n.addCustom(`mathjax-box-${r.id}`,()=>new Jh);if(r.src||i.dataUrl){const c=b("img",["mathjax"],e);c.src=n.doc.buildResourceUrl(r.src||i.dataUrl),n.domEvents.addEventListener(c,"load",e1);return}const s=["mathjax-tex-text"];let l=r.tex;l.trim()?i.error&&(l=i.error.message,s.push("mathjax-error")):l=T.t("mathjax.emptyText"),b("span",s,e,l),zx(n,r,i)}function Vx(n,t){const e={id:N(),box:!0,type:"math",tex:t,src:"",created:Date.now()};return Xh(n,t).then(o=>{if(!n.findBoxById(e.id))return;const i={...e,src:o};n.updateBoxData(i)}).catch(o=>{Fx.error(`failed to convert and upload mathjax: ${JSON.stringify(o)}`)}),e}function qx(n,t,e,o){const r=t;return o==="text"?r.tex:o==="markdown"?` $${r.tex}$ `:r.src?`<img src="${n.doc.buildResourceUrl(r.src,{withToken:!0})}" />`:`<code>$${r.tex}$</code>`}function Wx(n,t,e){t1(n,t)}const Fc={boxType:"math",updateBoxContent:Ux,convertFrom:Vx,convertTo:qx,handleClickBox:Wx};async function Gx(n,t,e){try{const o=t.embedData,r=await m4(n,o.mathjaxText),i=n.findBlockById(t.id);if(!i)return;const s=it(i);s.innerHTML="";const l=b("img",["mathjax"],s);l.src=r,e.setDataUrl(r)}catch(o){e.setError(o)}}function Zx(n,t){if(n.readonly||!t.target||!(t.target instanceof Node))return;const e=F(t.target);if(!e||!Te(e)||Oe(e)!=="math")return;const o=it(e),r=o.querySelector("img")||o.querySelector("span.mathjax-tex-text");if(!r||!It(r,t.target))return;const s=n.getBlockData(e).embedData;p4(n,r,s.mathjaxText,async l=>{const c=await Xh(n,l),a={mathjaxText:l,src:c};n.updateEmbedData(e,a)})}function Yx(n,t,e){const o=e.embedData,r=n.addCustom(`mathjax-block-${e.id}`,()=>new Jh);if(n.domEvents.addEventListener(t,"click",Zx),o.src||r.dataUrl){const i=b("img",["mathjax"],t);i.src=n.doc.buildResourceUrl(o.src||r.dataUrl);return}r.error,b("span",["mathjax-tex-text"],t,o.mathjaxText),Gx(n,e,r)}function Qx(n,t,e){if(!j(n,t))return null;const o=n.getBlockString(t).trim();if(!o||!o.startsWith("$$")||!o.endsWith("$$"))return null;const r=nd(o,"$");if(!r)return null;const i={mathjaxText:r,src:""};return{blockData:{id:N(),type:"embed",embedType:"math",embedData:i}}}function Kx(n){return{name:"Mathjax"}}function Jx(n,t){const e=it(t);n.domEvents.removeAllListeners(e)}function Xx(n,t,e,o){const r=t.embedData;return o==="html"?`<img src="${n.doc.buildResourceUrl(r.src,{withToken:!0})}" />`:o==="markdown"?`
366
366
  $$${r.mathjaxText}$$
367
- `:r.mathjaxText}const n1={embedType:"math",createEmbedContent:Yx,getOptions:Kx,convertFrom:Qx,handleDeleteBlock:Jx,convertTo:Xx},Cz="",tT={mathjax:{emptyText:"\u7A7A\u7684\u516C\u5F0F",abstract:"\u516C\u5F0F"}},eT={mathjax:{emptyText:"Empty Tex",abstract:"TeX"}};T.mergeLang({"zh-CN":tT,"en-US":eT});function nT(n,t,e,o){const r=n.getBlockByIndex(t,e),i=n.getBlockText(r),{left:s}=be(i,o);if(!vt(s).endsWith("$$$$"))return!1;const c=o-4,a=o,u={id:N(),box:!0,type:"math",tex:" ",src:"",created:Date.now()};return n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,c,a-c),n.insertBoxToBlock(r,c,u),setTimeout(()=>{const f=n.getBoxById(u.id);t1(n,f)})}),!0}class oT{handleAfterInsertText(t,e,o,r,i){return!!(i===" "&&nT(t,e,o,r))}}const C4=w("inline-box-items");function rT(n,t,e){return n.undoManager.runInGroup(()=>{var s;let o=n.getBlockByIndex(t,e);Tt(n,o)||(o=n.insertTextBlock([],t,e));const r=Hx();n.setBlockText(o,[r]);const i=(s=r.attributes)==null?void 0:s.id;return d(C4,i,"mathjax box id is empty"),setTimeout(()=>{const l=n.getBoxById(i);t1(n,l)},100),o})}function iT(n,t,e){let o=n.getBlockByIndex(t,e),r="bottom-start";return Tt(n,o)||(r="top-start"),Rc(n,{target:o,linkText:"",linkUrl:"",onFinished:(l,c)=>{n.undoManager.runInGroup(()=>{try{Tt(n,o)||(o=n.insertTextBlock([],t,e));const a=$e(l,{link:c}),u=$e(" ",null),f=[a,u];n.insertTextToBlock(o,0,f),n.selection.selectBlock(o,de(f)),n.focus()}catch(a){C4.error(a)}})},onClose:()=>{n.focus()},placement:r}),o}async function sT(n,t){switch(t.item.id){case"insert-math":return rT(n,t.containerId,t.blockIndex);case"insert-link":return iT(n,t.containerId,t.blockIndex);default:return null}}function lT(){return{name:"text",insertBlockCommandItems:[{id:"insert-math",name:T.t("quickMenu.inlineBox.math"),icon:qw,order:900,group:"common",subText:fe("insert-math")},{id:"insert-link",name:T.t("quickMenu.inlineBox.link"),icon:n5,order:400,group:"common",subText:fe("insert-link")}],handleInsertEmptyBlock:sT}}const cT={basics:100,system:200,common:300,thirdParty:400};function aT(n){var o,r;const t=(r=(o=n.options.componentsOptions)==null?void 0:o.quickMenu)==null?void 0:r.commandProviders;if(!t)return[];const e=[];return[...t,new h4].forEach(i=>{const s=i.getCommands(n);e.push(...s.map(l=>({...l,itemType:"insert-block",commandProvider:i})))}),e}function dT(n){const t=[];n.editorBlocks.forEach(o=>{if(!o.getOptions)return;const r=o.getOptions(n);!r.insertBlockCommandItems||(r.insertBlockCommandItems.forEach(i=>{Qh(i,r)}),t.push(...r.insertBlockCommandItems))});const e=lT();return e.insertBlockCommandItems.forEach(o=>{Qh(o,e)}),t.push(...e.insertBlockCommandItems),t.push(...aT(n)),t}function o1(n){const t=dT(n),e=new Map;t.forEach(i=>{var c;const s=(c=i.group)!=null?c:"";let l=e.get(s);l?l.items.push(i):(l={group:s,order:i.groupOrder||cT[s]||1e3,items:[i]},e.set(s,l))});const o=Array.from(e.values());o.sort((i,s)=>i.order-s.order),o.forEach(i=>{i.items.sort((s,l)=>{var c,a;return((c=s.order)!=null?c:0)-((a=l.order)!=null?a:0)})});const r=[];return o.forEach((i,s)=>{const l=T.t(`blockMenu.section.${i.group||"common"}`),c=l===i.group?i.group:l;r.push({id:`section-${s}`,name:c,type:"section",group:i.group,itemType:"insert-block"}),r.push(...i.items.map(a=>({...a})))}),r}function uT(n,t,e){const o=n.getFocusedBlock();if(!o)return;const r=n.getParentContainer(o),i=U(r);let l=n.getBlockIndex(o);if(Tt(n,o)||(l+=1),t.commandProvider){t.commandProvider.executeCommand(n,t,{from:"quick-menu",...e});return}!t.blockOptions||!t.blockOptions.handleInsertEmptyBlock||t.blockOptions.handleInsertEmptyBlock(n,{containerId:i,blockIndex:l,item:t})}const b4=w("quick-menu"),hT={id:"quick-menu",trigger:["/"]};class zc{constructor(t,e=hT){h(this,"suggest");h(this,"items");h(this,"maxHeading");h(this,"queryItems",async(t,e)=>{if(this.items.length===0?this.initMenuItems():this.refreshMenuItems(),e){const o=new Set,r=e.toLocaleLowerCase().replace(/^\s+|\s+$/g,"");return this.items.filter(i=>{var s;return i.type==="section"?!0:i.name.toLocaleLowerCase().indexOf(r)!==-1||AB(i).toLocaleLowerCase().indexOf(r)!==-1||i.group&&((s=i.group)==null?void 0:s.toLocaleLowerCase().indexOf(r))!==-1?(o.add(i.group),!0):!1}).filter(i=>i.type==="section"?o.has(i.group):!0)}return this.items});h(this,"onShow",(t,e,o,r)=>{const i=this.editor.getBlockByIndex(e,o);if(!Ko(i)){const s=F(H(i));if(s&&rt(s)==="code")return!1}return!0});h(this,"onClickItem",(t,e)=>{const o=e;o.itemType==="insert-block"&&(d(b4,o.blockOptions||o.commandProvider,"invalid quick item, no block options or command provider"),d(b4,this.suggest.anchor,"invalid suggest, no anchor"),uT(this.editor,o,this.suggest.anchor))});this.editor=t,this.options=e,this.items=[],this.maxHeading=Oc(),this.suggest=new mh(t,{id:e.id||"quick-menu",trigger:e.trigger,needSpaceBeforeTrigger:!0,autoDeleteTrigger:!0,highlight:!0,onShow:this.onShow,onClickItem:this.onClickItem,queryItems:this.queryItems})}get menu(){return this.suggest.menu.menu}destroy(){this.suggest.destroy()}initMenuItems(){const t=o1(this.editor);this.items=t}refreshMenuItems(){let t=null,e=0;const o=Oc();if(o!==this.maxHeading){const r=new h4,s=r.getCommands().map(l=>({...l,itemType:"insert-block",commandProvider:r}));for(let l=0;l<this.items.length;l++)this.items[l].group==="basics"&&(t||(t=l),t&&e++);t&&e&&this.items.splice(t,e,...s),this.maxHeading=o}}}class r1{constructor(t){h(this,"instance");h(this,"mousedown",!1);h(this,"currentInstance",null);h(this,"attributeName","");h(this,"attributeDesc","");h(this,"observer",null);h(this,"observerCallback",null);h(this,"createContent",t=>{var i;const e=(i=t.getAttribute(this.attributeName))!=null?i:"",o=t.getAttribute(this.attributeDesc);if(!o)return e;const r=b("div",[],null);return b("span",[],r,e),o&&b("span",["editor-tooltip-desc"],r,o),r});h(this,"handleDocumentMouseDown",()=>{this.mousedown=!0,this.editor.domEvents.addEventListener(document,"mouseup",this.handleDocumentMouseUp)});h(this,"handleDocumentMouseUp",()=>{this.mousedown=!1,this.editor.domEvents.removeEventListener(document,"mouseup",this.handleDocumentMouseUp)});h(this,"handleShown",t=>{this.currentInstance&&this.hide(),this.currentInstance=t,this.createObserver()});h(this,"handleHidden",()=>{this.destroyObserver(),this.currentInstance=null});h(this,"handleShow",t=>{var r;const e=t.reference;if(!e||!It(document.body,e)||window.isDragging||this.mousedown)return!1;const o=Number.parseInt((r=e.getAttribute("data-tooltip-hide-at"))!=null?r:"",10);return!(o&&Date.now()-o<1e3)});this.editor=t;const e=t.clientId;this.attributeName=`data-editor-tooltip-${e}`,this.attributeDesc=`data-editor-tooltip-desc-${e}`,this.instance=qa.delegate(document.body,{delay:200,target:`[${this.attributeName}]`,content:this.createContent,onShow:this.handleShow,onShown:this.handleShown,onHide:this.handleHidden}),t.domEvents.addEventListener(document,"mousedown",this.handleDocumentMouseDown)}visible(){var t;return(t=this.currentInstance)==null?void 0:t.state.isVisible}hide(){var t;(t=this.currentInstance)!=null&&t.state.isVisible&&this.currentInstance.hide()}destroy(){this.destroyObserver(),this.instance.destroy(),this.editor.domEvents.removeEventListener(document,"mousedown",this.handleDocumentMouseDown),this.editor.domEvents.removeEventListener(document,"mouseup",this.handleDocumentMouseUp)}createObserver(){this.destroyObserver();const t=this.currentInstance;if(!t||!t.reference)return;this.observerCallback=Xt.default(()=>{t.reference.closest("body")||(t.hide(),this.destroyObserver())},200),this.observer=new MutationObserver(this.observerCallback);const e=document.body,o={childList:!0,attributes:!1,subtree:!0};this.observer.observe(e,o)}destroyObserver(){this.observer&&(this.observer.disconnect(),this.observer=null),this.observerCallback&&(this.observerCallback.cancel(),this.observerCallback=null)}}const fT={"text/style-bold":"bold","text/style-italic":"italic","text/style-underline":"underline","text/style-strikethrough":"line-through","text/style-code":"code","text/style-subscript":"subscript","text/style-superscript":"superscript"};function mT(n,t){const e=new Set(Object.keys(fT)),o=t.filter(i=>e.has(i.id));return Lc(o)}function Uc(n,t){if(!n.isWritable())return!1;const e=n.selection.range,o=n.editorCommandProviders.getCommands(e),i=mT(n,o).find(s=>s.id===`text/${t}`);return i?(n.editorCommandProviders.executeCommand(e,i,{}),Xr.get(n).update("selectionChange"),!0):!1}const i1={"CtrlOrCmd+B":n=>Uc(n,"style-bold"),"CtrlOrCmd+I":n=>Uc(n,"style-italic"),"CtrlOrCmd+U":n=>Uc(n,"style-underline"),"CtrlOrCmd+D":n=>Uc(n,"style-strikethrough")},gT={quickMenu:{basic:{heading:{title:"\u6807\u9898 {heading}",space:"{markdown}\u7A7A\u683C"},unordered:"\u65E0\u5E8F\u5217\u8868",ordered:"\u6709\u5E8F\u5217\u8868",checkbox:"\u5F85\u529E\u4E8B\u9879",quote:"\u5F15\u7528"},inlineBox:{math:"\u516C\u5F0F",link:"\u94FE\u63A5"}},link:{textLabel:"\u6587\u672C",urlLabel:"\u94FE\u63A5\u5730\u5740",textPlaceholder:"\u8BF7\u8F93\u5165\u6587\u672C",urlPlaceholder:"\u8BF7\u8F93\u5165\u94FE\u63A5\u5730\u5740",submitText:"\u786E\u5B9A",cancelText:"\u53D6\u6D88"},commands:{unordered:"\u65E0\u5E8F\u5217\u8868",ordered:"\u6709\u5E8F\u5217\u8868",check:"\u5F85\u529E\u5217\u8868",link:"\u94FE\u63A5",quote:"\u5F15\u7528",alignLeft:"\u5DE6\u5BF9\u9F50",alignRight:"\u53F3\u5BF9\u9F50",alignCenter:"\u5C45\u4E2D\u5BF9\u9F50",alignGroup:"\u5BF9\u9F50\u65B9\u5F0F",heading:"\u6807\u9898 {name}",headingGroup:"\u6807\u9898\u6837\u5F0F",text:"\u6B63\u6587"},commandDesc:{mac:{unordered:"\u2318+\u21E7+L",ordered:"\u2318+\u21E7+U",link:"\u2318+K"},window:{unordered:"Ctrl+Shift+L",ordered:"Ctrl+Shift+U",link:"Ctrl+K"}}},pT={quickMenu:{basic:{heading:{title:"Heading {heading}",space:"{markdown}space"},unordered:"Bulleted list",ordered:"Numbered list",checkbox:"Todo list",quote:"Quote"},inlineBox:{math:"Math",link:"Link"},link:{textLabel:"Text",urlLabel:"Link Address",textPlaceholder:"Please enter text",urlPlaceholder:"Please enter the link address",submitText:"Ok",cancelText:"Cancel"}},commands:{unordered:"Bulleted list",ordered:"Numberer list",check:"Todo list",link:"Link",quote:"Quote",alignLeft:"Align left",alignRight:"Align right",alignCenter:"Align center",alignGroup:"Alignment",heading:"Heading {name}",headingGroup:"Text style",text:"Text"},commandDesc:{mac:{unordered:"\u2318+\u21E7+L",ordered:"\u2318+\u21E7+U",link:"\u2318+K"},window:{unordered:"Ctrl+Shift+L",ordered:"Ctrl+Shift+U",link:"Ctrl+K"}}};T.mergeLang({"zh-CN":gT,"en-US":pT});const bz="";function sr(n,...t){const e=go(...t);return e.classList.remove("editor-button"),e.classList.add("editor-text-button"),n.append(e),e}function v4(n){Mc(n).hide();const e=n.getCustom("table-border-bar");e==null||e.closeToolbar()}function CT(n){return b("div",["insert-column-button","drop-marker"],n)}const k4=w("row-height");function y4(n){const t=et.fromTable(n),e=n.rows;d(k4,e.length===t.rowCount,"row count mismatch");const o=Array(t.rowCount).fill(0);for(let r=0;r<e.length;){let i=1,l=e[r].getBoundingClientRect().height,c=r+1;for(;c<e.length;){const a=e[c];if(a.cells.length!==0)break;i++,c++,l+=a.getBoundingClientRect().height}for(let a=0;a<i;a++)o[r+a]=l/i;r=c}return k4.debug("heights",o.join(", ")),o}const ko=w("table-border-bar-dom");function Ss(n,t){d(ko,Ht(t),"invalid table block");const e=jt(t),o=xn(n,t),r=(a,u,f)=>{const m=b("div",["button-root",u],a),C=b("div",["button-container",u],m);m.setAttribute(`data-${u}-index`,`${f}`),C.setAttribute(`data-editor-tooltip-${n.clientId}`,u==="left"?T.t("table.insertRow"):T.t("table.insertCol")),b("span",["insert-indicator"],C),CT(C)},{selectedRows:i,selectedColumns:s}=ph(n,t),l=()=>{const a=o.querySelector(".table-border-bar-container.top");d(ko,a,"no top border bar container");const u=b("div",["table-border-bar-container","top"],null),f=b("div",["table-border-bar","top"],u),m=ME(e);b("span",["table-border-bar-cell","corner"],f);const v=et.fromTable(e).colCount;n.selection.range.isSimple()&&r(f,"top",0);for(let B=0;B<v;B++){const y=B===v-1?m[B]+2:m[B],S=b("span",["table-border-bar-cell","top"],f);s.has(B)&&S.classList.add("selected"),S.setAttribute("data-top-index",`${B}`),S.style.width=`${y}px`,n.selection.range.isSimple()&&r(f,"top",B+1)}Mi(a,u)},c=()=>{const a=o.querySelector(".table-border-bar-container.left");d(ko,a,"no left border bar container");const u=b("div",["table-border-bar-container","left"],null),f=b("div",["table-border-bar","left"],u),m=y4(e);n.selection.range.isSimple()&&r(f,"left",0),Array.from(e.rows).forEach((C,v,B)=>{const y=b("span",["table-border-bar-cell","left"],f);i.has(v)&&y.classList.add("selected"),y.setAttribute("data-left-index",`${v}`);const S=v===B.length-1?m[v]+2:m[v];y.style.height=`${S}px`,n.selection.range.isSimple()&&r(f,"left",v+1)}),Mi(a,u)};l(),c()}function w4(n,t){const e=t.target;if(!(e instanceof Element))return;const o=F(e);d(ko,o&&Ht(o),"invalid table block"),Ss(n,o),n.selection.caret.update()}function s1(n,t){const e=t.target;if(!(e instanceof Element))return;const o=F(e);d(ko,o&&Ht(o),"invalid table block");const r=e.closest(".button-root");if(r){if(r.classList.contains("top")){const i=parseInt(r.getAttribute("data-top-index")||"0",10);H5(n,o,i),Ss(n,o)}else if(r.classList.contains("left")){const i=parseInt(r.getAttribute("data-left-index")||"0",10);F5(n,o,i),Ss(n,o)}}}function l1(n,t){var s;v4(n),t.preventDefault(),t.stopPropagation();let e=null,o,r;const i=l=>{var c;if(l.target instanceof HTMLElement&&o&&e&&r!==void 0){const a=F(l.target),u=l.target.closest(".table-border-bar");if(a===e&&u){const f=parseInt((c=l.target.getAttribute(`data-${o}-index`))!=null?c:"0",10),m=Math.min(r,f),C=Math.abs(r-f)+1;nt(l.target,"top")&&o==="top"?VE(n,a,m,C,{reverse:!0}):nt(l.target,"left")&&o==="left"&&qE(n,a,m,C,{reverse:!0})}}l.type==="mouseup"&&(e=null,r=void 0,o=void 0,document.body.removeEventListener("mousemove",i),document.body.removeEventListener("mouseup",i))};t.target instanceof HTMLElement&&nt(t.target,"table-border-bar-cell")&&(e=F(t.target),nt(t.target,"top")?o="top":nt(t.target,"left")&&(o="left"),o&&e&&(r=parseInt((s=t.target.getAttribute(`data-${o}-index`))!=null?s:"0",10),document.body.addEventListener("mousemove",i),document.body.addEventListener("mouseup",i)))}function bT(n,t){d(ko,Ht(t),"invalid table block");const e=xn(n,t),o=b("div",["table-border-bar-container","top"],e),r=b("div",["table-border-bar-container","left"],e);Ss(n,t),n.domEvents.addEventListener(it(t),"scroll",w4),n.domEvents.addEventListener(o,"click",s1),n.domEvents.addEventListener(r,"click",s1),n.domEvents.addEventListener(o,"mousedown",l1),n.domEvents.addEventListener(r,"mousedown",l1)}function B4(n,t){if(!n.isWritable())return;if(xn(n,t).querySelector(".table-border-bar-container")){Ss(n,t);return}bT(n,t)}function E4(n,t){d(ko,Ht(t),"invalid table block"),xn(n,t).querySelectorAll(".table-border-bar-container").forEach(r=>{n.domEvents.removeEventListener(r,"click",s1),n.domEvents.removeEventListener(r,"mousedown",l1),r.remove()}),n.domEvents.removeEventListener(it(t),"scroll",w4)}function vT(n,t){d(ko,Ht(t),"invalid table block");const o=xn(n,t).querySelector(".table-border-bar-container.top");return o?o.getBoundingClientRect().height:0}class kT{constructor(t,e){h(this,"toolbar");h(this,"handleSelectionChange",(t,e)=>{e==="delete-columns"?(Vr(this.editor,this.tableBlock,!0,!0),qr(this.editor,this.tableBlock,!0,!0)):e==="delete-rows"?(Vr(this.editor,this.tableBlock,!0,!1),qr(this.editor,this.tableBlock,!0,!1)):(Vr(this.editor,this.tableBlock,!1),qr(this.editor,this.tableBlock,!1))});h(this,"handleClick",(t,e,o)=>{e.id==="delete-columns"?Ch(this.editor.selection.range):e.id==="delete-rows"&&bh(this.editor.selection.range)});this.editor=t,this.tableBlock=e;const o=t.options.componentsOptions.popover;this.toolbar=new ps([],void 0,{overflowBoundary:o==null?void 0:o.overflowBoundary,refuseOverflow:!0,tooltipId:this.editor.clientId}),this.toolbar.addListener("selectionChange",this.handleSelectionChange),this.toolbar.addListener("click",this.handleClick)}close(){this.toolbar.close()}update(){const{selectedColumns:t,selectedRows:e}=ph(this.editor,this.tableBlock);if(!this.editor.isWritable())return;if(t.size>0&&e.size>0){this.toolbar.close();return}if(t.size===0&&e.size===0){this.toolbar.close();return}const o=Ho(this.editor,this.tableBlock,this.editor.selection.range)[0];if(!o){this.toolbar.close();return}if(t.size>0){const r={id:"delete-columns",name:T.t("table.deleteCol"),icon:Rw};this.toolbar.updateItems([r]);const i=zo(this.editor,this.tableBlock,"editor-quick-menu",o);this.toolbar.manualShow(i,{placement:"top"})}else{const r={id:"delete-rows",name:T.t("table.deleteRow"),icon:Mw};this.toolbar.updateItems([r]);const i=new DOMRect(o.left-15,o.top,o.width,o.height),s=zo(this.editor,this.tableBlock,"editor-quick-menu",i);this.toolbar.manualShow(s,{placement:"left"})}}destroy(){this.toolbar.destroy(),this.toolbar.removeAllListeners()}}const Vc=w("table-border-bar");class yT{constructor(t,e){h(this,"toolbar");h(this,"resizeObserver");h(this,"handleReadonlyChanged",t=>{t.isWritable()?this.update():E4(this.editor,this.tableBlock)});h(this,"handleBlockUpdated",()=>{this.resizeObserver.disconnect(),setTimeout(()=>{const t=this.editor.getBlockById(q(this.tableBlock));this.resizeObserver.observe(jt(t))})});h(this,"handleTableResize",()=>{!this.editor.isWritable()||(console.log("resize"),this.update())});this.editor=t,this.tableBlock=e,d(Vc,this.tableBlock,"no table block"),Vc.debug("create table border bar"),B4(this.editor,this.tableBlock),this.resizeObserver=new ResizeObserver(this.handleTableResize),this.resizeObserver.observe(jt(this.tableBlock)),this.toolbar=new kT(this.editor,this.tableBlock),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}close(){this.toolbar.close()}destroy(){Vc.debug("destroy table border bar"),this.resizeObserver.disconnect(),E4(this.editor,this.tableBlock),this.toolbar.destroy(),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged)}update(){Vc.debug("update table border bar"),B4(this.editor,this.tableBlock),this.toolbar.update()}}const wT=w("table-border-bar");class BT{constructor(t){h(this,"activeTableBar",null);h(this,"handleBlockDeleted",(t,e)=>{!this.activeTableBar||(e===this.activeTableBar.tableBlock||It(e,this.activeTableBar.tableBlock))&&(this.activeTableBar.destroy(),this.activeTableBar=null)});h(this,"handleSelectionChanged",t=>{var r;const e=t.selection.range;let o=null;if(e.isCollapsed()&&e.isSimple()){const i=t.getBlockById(e.start.blockId);if(Ht(i)){const s=H(i),l=F(s);l&&(o=Me(l))}else o=Me(i)}else{const i=t.getBlockById(e.start.blockId),s=Me(i),l=t.getBlockById(e.end.blockId),c=Me(l);s===c&&(o=s)}((r=this.activeTableBar)==null?void 0:r.tableBlock)!==o&&this.activeTableBar&&this.hide(),o&&this.show(o)});this.editor=t,this.editor.addListener("blockDeleted",this.handleBlockDeleted),this.editor.addListener("selectionChanged",this.handleSelectionChanged)}destroy(){this.editor.removeListener("blockDeleted",this.handleBlockDeleted),this.editor.removeListener("selectionChanged",this.handleSelectionChanged)}show(t){this.activeTableBar?(this.activeTableBar.tableBlock!==t&&this.hide(),this.activeTableBar.update()):this.activeTableBar=new yT(this.editor,t)}update(){var t;(t=this.activeTableBar)==null||t.handleBlockUpdated()}closeToolbar(){var t;(t=this.activeTableBar)==null||t.close()}hide(){!this.activeTableBar||(d(wT,this.activeTableBar,"no active table bar"),this.activeTableBar.destroy(),this.activeTableBar=null)}}function I4(n,t){const e=n.addCustom("table-border-bar",o=>new BT(o));t==="update"&&e.update()}const Be=w("table-cell-menu"),ET="style-bg-color-";class IT{constructor(t){h(this,"activeTableBlock",null);h(this,"targetButton",null);h(this,"manualMenu",null);h(this,"colorPaletteItem",null);h(this,"handlePrevent",(t,e)=>{e.stopPropagation()});h(this,"handleReadonlyChanged",t=>{t.isWritable()||this.hide()});h(this,"handleSelectionChanged",t=>{const e=t.selection.range;let o=null;if(e.isCollapsed()&&e.isSimple()){const r=t.getBlockById(e.start.blockId);if(Ht(r)){const i=H(r),s=F(i);s&&(o=Me(s))}else o=Me(r)}else{const r=t.getBlockById(e.start.blockId),i=Me(r),s=t.getBlockById(e.end.blockId),l=Me(s);i===l&&(o=i)}if(this.hide(),this.activeTableBlock!==o&&(this.activeTableBlock=o),this.activeTableBlock){const r=et.fromBlock(this.activeTableBlock),i=e.isReverse()?e.start:e.end;let s=null;e.isCollapsed()?s=this.getCellByChildBlockId(r,i.blockId):i instanceof Je&&(t.getBlockById(i.blockId)===this.activeTableBlock?s=r.getCellByContainerId(i.childContainerId):s=this.getCellByChildBlockId(r,i.blockId)),s&&this.editor.isWritable()&&this.showCellMenuButton(s)}});h(this,"handleBeforePopupPalette",()=>{var e;const t=this.getSelectedBkgColorIndex();(e=this.colorPaletteItem)==null||e.palette.setColor("backgroundColor",t)});h(this,"createBkgColorItem",()=>{const t=b("div",["cell-background-color-item"],null);b("span",[],t,T.t("table.cellBackground"));const e=this.getSelectedBkgColorIndex();b("button",["item-button"],t).setAttribute("data-color-index",`${e}`);const r=b("span",["item-sub-indicator"],t);return r.innerHTML=J2,t});h(this,"handleCommand",t=>{var r;d(Be,this.activeTableBlock,"no target table block");const e=((r=t.states)==null?void 0:r.includes("checked"))||!1,o=t.value;switch(t.id){case"delete-select-row":bh(y5(this.editor,this.activeTableBlock,!1));break;case"delete-select-col":Ch(y5(this.editor,this.activeTableBlock,!0));break;case"merge-cell":b5(this.editor.selection.range);break;case"split-cell":this.handleSplitCell();break;case"row-title":this.handleRowTitle(e);break;case"col-title":this.handleColTitle(e);break;case"stripe-style":this.handleStripeStyle(e);break;case"hide-border":XB(this.editor,this.activeTableBlock,o==="show-border");break;case"show-chart":rE(this.editor,this.activeTableBlock,o==="show-chart"),Sh(this.editor,this.activeTableBlock,{updateNow:!0});break}});h(this,"handleSelectionChange",(t,e)=>{d(Be,this.activeTableBlock,"no target table block"),e==="cell-background-color"&&this.handleBeforePopupPalette(),e==="delete-select-row"?(Vr(this.editor,this.activeTableBlock,!0,!1),qr(this.editor,this.activeTableBlock,!0,!1)):e==="delete-select-col"?(Vr(this.editor,this.activeTableBlock,!0,!0),qr(this.editor,this.activeTableBlock,!0,!0)):(Vr(this.editor,this.activeTableBlock,!1),qr(this.editor,this.activeTableBlock,!1))});h(this,"handleClick",()=>{var t;d(Be,this.activeTableBlock,"no target table block"),d(Be,this.targetButton,"no target button"),v4(this.editor),nt(this.targetButton,"active")?(z(this.targetButton,"active"),(t=this.manualMenu)==null||t.close()):(A(this.targetButton,"active"),this.manualMenu?this.manualMenu.updateItems(this.createCommandMenu()):(this.manualMenu=new tr(this.createCommandMenu()),this.manualMenu.on("click",(e,o)=>{var r;this.handleCommand(o),(r=this.manualMenu)==null||r.close()}),this.manualMenu.on("selectionChange",this.handleSelectionChange),this.manualMenu.on("close",()=>{this.targetButton&&z(this.targetButton,"active"),this.editor.focus()})),this.manualMenu.manualShow(this.targetButton,{placement:"right-start"}))});this.editor=t,this.editor.addListener("selectionChanged",this.handleSelectionChanged),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}destroy(){var t,e;this.activeTableBlock=null,this.targetButton=null,this.editor.removeListener("selectionChanged",this.handleSelectionChanged),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged),(t=this.manualMenu)==null||t.destroy(),(e=this.colorPaletteItem)==null||e.destroy()}hide(){var t;(t=this.manualMenu)==null||t.close(),this.targetButton&&(z(this.targetButton,"active"),this.targetButton.style.display="none")}getCellByChildBlockId(t,e){let o=this.editor.getBlockById(e);for(;o;){const r=o.closest("td");d(Be,r,"no parent cell");const i=F(r);if(d(Be,i,"no parent block"),jt(i)===t.table)return t.getCellByCellElement(r);o=i}return d(Be,!1,"filed to get cell by child block id"),null}createTargetButton(t){this.targetButton?t.querySelector(":scope > .table-cell-menu-btn")||t.appendChild(this.targetButton):(this.targetButton=b("button",["table-cell-menu-btn"],t),this.targetButton.innerHTML=Ju,this.editor.domEvents.addEventListener(this.targetButton,"click",this.handleClick),this.editor.domEvents.addEventListener(this.targetButton,"mousedown",this.handlePrevent))}showCellMenuButton(t){this.createTargetButton(t.cell),d(Be,this.targetButton,"no target button"),this.targetButton.style.display="inline-block"}handleSplitCell(){if(this.activeTableBlock){const t=et.fromBlock(this.activeTableBlock),e=this.editor.selection.range;if(e.isSimple()){const{col:o,row:r}=this.getCellByChildBlockId(t,e.start.blockId);kh(this.editor,this.activeTableBlock,{col:o,row:r})}else yh(this.editor.selection.range)}}getSelectedBkgColorIndex(){var r;d(Be,this.activeTableBlock,"no target table block");const t=nE(this.editor,this.activeTableBlock),e=this.editor.getBlockData(this.activeTableBlock),o=new Set;for(const i of t){if(o.size>1)break;const s=U(i),l=e[`${s}_background`];if(l)o.add(Number.parseInt((r=l.substring(ET.length))!=null?r:"0",10));else{o.add(-1);break}}return o.size===1&&[...o][0]!==-1?[...o][0]:-1}createCommandMenu(){d(Be,this.activeTableBlock,"no target table block");const t=this.editor.getBlockData(this.activeTableBlock),e=C5(this.editor,this.activeTableBlock,this.editor.selection.range);let o=this.editor.selection.range;if(o.isSimple()){const u=Gn(this.editor,this.activeTableBlock,o.start);o=Wt(this.editor,{anchor:u,focus:u})}const r=p5(this.editor,this.activeTableBlock,o),i=t.hasRowTitle,s=t.hasColTitle,l=t.isStripeStyle,c=t.noBorder,a=t.chart;return this.colorPaletteItem=new d5("cell-background-color",{color:!1}),this.colorPaletteItem.palette.on("onClick",(u,f)=>{var m;switch(d(Be,this.activeTableBlock,"no target table block"),u){case"clearColor":E5(this.editor,this.activeTableBlock,-1);break;case"backgroundColor":E5(this.editor,this.activeTableBlock,f);break}(m=this.manualMenu)==null||m.close()}),[{id:"cell-background-color",name:T.t("table.cellBackground"),element:this.createBkgColorItem(),children:[this.colorPaletteItem]},{id:"separator",name:"",type:"separator"},{id:"merge-cell",name:T.t("table.mergeCell"),states:e?[]:["disabled"]},{id:"split-cell",name:T.t("table.splitCell"),states:r?[]:["disabled"]},{id:"separator",name:"",type:"separator"},{id:"delete-select-row",name:T.t("table.deleteSelectRow")},{id:"delete-select-col",name:T.t("table.deleteSelectCol")},{id:"separator",name:"",type:"separator"},{id:"table-config",name:T.t("table.tableConfigKey"),children:[{id:"row-title",name:T.t("table.tableConfig.rowTitle"),states:i?["checked"]:[]},{id:"col-title",name:T.t("table.tableConfig.colTitle"),states:s?["checked"]:[]},{id:"stripe-style",name:T.t("table.tableConfig.stripeStyle"),states:l?["checked"]:[]},{id:"hide-border",name:c?T.t("table.tableConfig.showBorder"):T.t("table.tableConfig.hideBorder"),value:c?"show-border":"hide-border"},{id:"show-chart",name:a?T.t("table.tableConfig.hideChart"):T.t("table.tableConfig.showChart"),value:a?"hide-chart":"show-chart"}]}]}handleRowTitle(t){d(Be,this.activeTableBlock,"no target table block"),t?QB(this.editor,this.activeTableBlock):YB(this.editor,this.activeTableBlock)}handleColTitle(t){d(Be,this.activeTableBlock,"no target table block"),t?ZB(this.editor,this.activeTableBlock):GB(this.editor,this.activeTableBlock)}handleStripeStyle(t){d(Be,this.activeTableBlock,"no target table block"),t?JB(this.editor,this.activeTableBlock):KB(this.editor,this.activeTableBlock)}}function x4(n){n.addCustom("table-cell-menu",t=>new IT(t))}const qc=w("table-container");function c1(n){const t=n.closest("td");return d(qc,t,"no parent cell for a table cell container"),t}function T4(n){const t=jt(n);return Array.from(t.querySelectorAll(':scope > tbody > tr > td > [data-type="editor-container"].child'))}function a1(n,t,e,o){const r=et.fromBlock(n),i=r.getCellByContainerId(U(t));if(e==="ArrowDown"){const s=r.getBottomCell(i);return s?s.container:null}if(e==="ArrowUp"){const s=r.getTopCell(i);return s?s.container:null}if(e==="ArrowLeft"){const s=r.getAllContainers(),l=s.indexOf(t);if(d(qc,l>=0,"not a valid child container"),l===0)return null;const c=s[l-1];return o!=null&&o.noWrap&&r.getCellByContainerId(U(c)).row!==i.row?null:c}if(e==="ArrowRight"){const s=r.getAllContainers(),l=s.indexOf(t);if(d(qc,l>=0,"not a valid child container"),l===s.length-1)return null;const c=s[l+1];return o!=null&&o.noWrap&&r.getCellByContainerId(U(c)).row!==i.row?null:c}d(qc,!1,`invalid navigation type: ${e}`)}const xT=12,TT=90,Wc=23,S4=2;class ST{constructor(t){h(this,"scrollTableBlock",null);h(this,"autoScrollDir",null);h(this,"autoScrollTimer",null);h(this,"handleMouseDown",t=>{const e=document.elementFromPoint(t.clientX,t.clientY);if(e&&e instanceof HTMLElement){const o=F(e);if(o&&It(this.editor.rootContainer,o)){const r=Me(o);r&&(this.scrollTableBlock=r,document.addEventListener("mousemove",this.handleAutoScroll))}}});h(this,"handleAutoScroll",b7.default(t=>{if(this.scrollTableBlock){const e=this.editor.getCustom(Co(this.scrollTableBlock)),o=e.rootElement,r=e.scrollOptions.parentContainer,i=o.getBoundingClientRect(),s=window.innerHeight-(e.scrollOptions.barFloatWindowBottom||0),l=r.getBoundingClientRect(),c=Math.min(l.bottom,s),a=Math.max(l.top,0);i.bottom>c&&t.clientY>=c?this.setAutoScroll("bottom"):i.top<a&&t.clientY<=a?this.setAutoScroll("top"):o.scrollLeft>0&&t.clientX<i.left?this.setAutoScroll("left"):o.scrollLeft<o.scrollWidth-o.offsetWidth&&t.clientX>i.right?this.setAutoScroll("right"):this.clearAutoScroll()}},15));h(this,"handleMouseUp",()=>{document.removeEventListener("mousemove",this.handleAutoScroll),setTimeout(()=>{this.scrollTableBlock=null})});h(this,"handleSelectionChanged",t=>{const e=t.selection.range;if(e.isCollapsed()&&e.isSimple()){const o=t.getBlockById(e.start.blockId),r=Me(o);if(r){const i=t.getCustom(Co(r)),s=i.rootElement.getBoundingClientRect(),l=Ke(t,o,e.start);if(s.left>l.left){const c=e.start.offset===0?xT:S4;i.rootElement.scrollLeft-=s.left-l.left+c}else if(l.right>s.right){const c=e.start.offset===0?TT:S4;i.rootElement.scrollLeft+=l.right-s.right+c}}}else{const o=t.getBlockById(e.start.blockId),r=Me(o),i=t.getBlockById(e.end.blockId),s=Me(i);if(r&&r===s){const l=t.getCustom(Co(r)),c=l.rootElement.getBoundingClientRect();let a=null;if(e.isSimple())a=e.isReverse()?Ke(t,o,e.start):Ke(t,i,e.end);else{const u=c1(Br(t,e.start.childContainerId)),f=c1(Br(t,e.end.childContainerId));a=e.isReverse()?u.getBoundingClientRect():f.getBoundingClientRect()}c.left>a.left&&e.isReverse()?l.rootElement.scrollLeft-=c.left-a.left:c.right<a.right&&!e.isReverse()&&(l.rootElement.scrollLeft+=a.right-c.right)}}});h(this,"handleScroll",t=>{f5(t),this.editor.selection.caret.update()});h(this,"handleReset",t=>{f5(t),this.editor.selection.caret.update()});this.editor=t,this.editor.addListener("selectionChanged",this.handleSelectionChanged),document.addEventListener("mousedown",this.handleMouseDown),document.addEventListener("mouseup",this.handleMouseUp)}clearAutoScroll(){this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null,this.autoScrollDir=null)}setAutoScroll(t){this.autoScrollDir&&this.autoScrollDir!==t&&this.clearAutoScroll(),this.autoScrollTimer||(this.autoScrollDir=t,this.autoScrollTimer=window.setInterval(()=>{if(this.scrollTableBlock){const e=this.editor.getCustom(Co(this.scrollTableBlock)),o=e.rootElement,r=e.scrollOptions.parentContainer,i=o.getBoundingClientRect(),s=r===document.documentElement?window.innerHeight:r.offsetHeight,l=window.innerHeight-(e.scrollOptions.barFloatWindowBottom||0),c=r.getBoundingClientRect(),a=Math.min(c.bottom,l),u=Math.max(c.top,0);this.autoScrollDir==="left"&&(o.scrollLeft-=Wc,o.scrollLeft<=0&&this.clearAutoScroll()),this.autoScrollDir==="right"&&(o.scrollLeft+=Wc,o.scrollLeft>=o.scrollWidth-o.offsetWidth&&this.clearAutoScroll()),this.autoScrollDir==="bottom"&&(r.scrollTop+=Wc,(r.scrollTop>=r.scrollHeight-s||i.bottom<=a)&&this.clearAutoScroll()),this.autoScrollDir==="top"&&(r.scrollTop-=Wc,(r.scrollTop<=0||i.top>=u)&&this.clearAutoScroll())}},100))}destroy(){document.removeEventListener("mousedown",this.handleMouseDown),document.removeEventListener("mouseup",this.handleMouseUp),this.editor.removeListener("selectionChanged",this.handleSelectionChanged)}}function D4(n){return n.addCustom("table-scroll-events",t=>new ST(t))}const Tn=w("create-content");function L4(n,t,e){const o=new vc(e),r=e.rows,i=e.cols;d(Tn,r>=1,`invalid rows: ${r}`),d(Tn,i>=1,`invalid cols: ${i}`),d(Tn,e.children,"no table children");const s=b("table",[],null),l=e.colsWidth,c=b("colgroup",[],s);for(let f=0;f<o.colCount;f++){const m=b("col",[],c);m.style.width=`${l[f]||Sc}px`}const a=b("tbody",[],s);let u=0;for(let f=0;f<r;f++){const m=b("tr",[],a);for(let C=0;C<i;C++){const v=o.getCell({col:C,row:f});if(v.virtual)d(Tn,v.colSpan>1||v.rowSpan>1,"virtual cell should have colSpan or rowSpan");else{const B=e.children[u],y=b("td",[],m);v.colSpan>1&&(y.colSpan=v.colSpan),v.rowSpan>1&&(y.rowSpan=v.rowSpan);const S=e[ks(B)];S&&A(y,S),C===0&&e.hasColTitle&&A(y,v5.COL_TITLE_ITEM),n.createChildContainer(t,y,B),u+=1}}}return d(Tn,u===e.children.length,"container count mismatch"),e.noBorder&&A(s,"no-border"),e.chart&&A(s,"editor-table-chart"),e.isStripeStyle&&A(s,"stripe"),e.hasRowTitle&&A(s,"row-title"),e.hasColTitle&&A(s,"col-title"),s}function DT(n,t,e,o,r){d(Tn,r.type==="table","not table data"),d(Tn,U(e)===t[t.length-1].containerId,"invalid path");const i=r,s=ro(o,"div");try{const l=b("div",[],null);l.setAttribute("data-type","table-content");const c=L4(n,t,i);c.classList.add("drag-preview-element"),l.appendChild(c),P5(n),U5(n),I4(n,"create"),x4(n),vw(n,Dh);const a=n.getComponentOptions("table"),u=n.addCustom(Co(o),()=>SE());u.init({parentElement:s,childElement:l,safeRightSpace:50,safeLeftSpace:40,parentContainer:pt(e)?n.scrollContainer:e,locatingContainer:pt(e)?(a==null?void 0:a.locatingContainer)||n.parent:e,paddingLeft:Eh+vs,paddingTop:Eh+vs,paddingBottom:vs/2,paddingRight:vs/2,barFloatWindowBottom:a==null?void 0:a.barFloatWindowBottom,isSetScale:a==null?void 0:a.isSetScale});const f=D4(n);u.on("scroll",f.handleReset),u.on("resize",f.handleReset),setTimeout(()=>{lE(n,o)})}catch{const c=`invalid table data: ${JSON.stringify(i)}`;Tn.error(c);const a=b("div",["error"],s);a.innerText=c}return s}function LT(n,t,e){d(Tn,e.type==="table","not table data");const o=e,r=it(t);try{const i=jt(t),s=jo(t),l=L4(n,s,o);l.classList.add("drag-preview-element"),i.insertAdjacentElement("afterend",l),i.remove(),P5(n),U5(n),I4(n,"update"),x4(n),Dh(n,t)}catch{const s=`invalid table data: ${JSON.stringify(o)}`;Tn.error(s);const l=b("div",["error"],r);l.innerText=s}}function MT(n,t){let e,o,r=!1;if([...t].every(m=>m==="|")?(o=t.length,e=Array(o).fill(""),r=!0):(e=nd(t,"|").split("|"),o=e.length),o<2)return null;const i=3,s=o,l=[];for(let m=0;m<3;m++)e.forEach(C=>{l.push(yn(n.doc,m===0?C:""))});const c=Array(s).fill(Sc),a=l[r?0:s],u=n.doc.getContainerBlocks(a)[0].id;return{blockData:{id:N(),type:"table",rows:i,cols:s,children:l,colsWidth:c},focusBlockId:u}}function RT(n,t){const e=t.rows,o=t.cols;if(e<1||o<1)return null;const r=[];for(let a=0;a<e;a++)for(let u=0;u<o;u++)r.push(yn(n.doc));const i=Array(o).fill(Sc),s=r[0],l=n.doc.getContainerBlocks(s)[0].id;return{blockData:{id:N(),type:"table",rows:e,cols:o,children:r,colsWidth:i},focusBlockId:l}}const M4=w("table-selection-to-doc");function AT(n,t){const{start:e,end:o,block:r}=t,i=rt(r);d(M4,i==="table",`invalid block type: ${i}`);const s=n.getBlockData(r);if(e.isSimple()&&o.isSimple())return ao(n.editorBlocks,n.doc.toJSON(),s);d(M4,!e.isSimple()&&!o.isSimple(),"invalid block pos type");const l=et.fromBlock(r),{fromCol:c,toCol:a,fromRow:u,toRow:f}=an(r,e,o),m={},C=[],v=n.doc.toJSON();let B={};l.sub({row:u,col:c},{row:f,col:a}).forEach((Z,ot)=>{Z.forEach((st,mt)=>{const ut=st.containerId;if(C.indexOf(ut)!==-1)return;C.push(ut);let yt;if(st.virtual){const ee=l.getCellByContainerId(st.containerId),Ue=c+mt;let Eo=ee.col+ee.colSpan-1;Eo>a&&(Eo=a);const gr=Eo-Ue+1;gr>1&&(m[`${ut}_colSpan`]=gr);const pr=u+ot;let Io=ee.row+ee.rowSpan-1;Io>f&&(Io=f);const ya=Io-pr+1;ya>1&&(m[`${ut}_rowSpan`]=ya),yt=Zo()}else{if(yt=hu(n.editorBlocks,v,ut),st.col+st.colSpan>a+1){const ee=a-st.col+1;ee>1&&(m[`${ut}_colSpan`]=ee)}else st.colSpan>1&&(m[`${ut}_colSpan`]=st.colSpan);if(st.row+st.rowSpan>f+1){const ee=f-st.row+1;ee>1&&(m[`${ut}_rowSpan`]=ee)}else st.rowSpan>1&&(m[`${ut}_rowSpan`]=st.rowSpan)}const{root:se,...eo}=yt.blocks;B={...B,...eo,[ut]:se}})});const S=Es(jt(r)).slice(c,a+1);return{blocks:{root:[{id:N(),type:i,children:C,colsWidth:S,rows:f-u+1,cols:a-c+1,...m}],...B},meta:{},comments:{}}}function OT(n,t){if(t.top===0)return!0;for(let e=t.left;e<=t.right;e++)if(n[t.top-1][e]===n[t.top][e])return!1;return!0}function _T(n,t){if(t.left===0)return!0;for(let e=t.top;e<=t.bottom;e++)if(n[e][t.left-1]===n[e][t.left])return!1;return!0}function NT(n,t){if(t.bottom===n.length-1)return!0;for(let e=t.left;e<=t.right;e++)if(n[t.bottom][e]===n[t.bottom+1][e])return!1;return!0}function $T(n,t){if(t.right===n[0].length-1)return!0;for(let e=t.top;e<=t.bottom;e++)if(n[e][t.right]===n[e][t.right+1])return!1;return!0}function PT(n,t,e){const o=t.col,r=t.row,i=e.col,s=e.row,l={left:o,top:r,right:i,bottom:s};let c=!1;do{if(c=!1,!OT(n,l)){l.top--,c=!0;continue}if(!_T(n,l)){l.left--,c=!0;continue}if(!NT(n,l)){l.bottom++,c=!0;continue}if(!$T(n,l)){l.right++,c=!0;continue}}while(c);return l}function jT(n,t,e,o){if(e.custom!==void 0||o.custom!==void 0)return{anchor:e,focus:o};const r=et.fromBlock(t),i=r.map(M=>M.containerId),s=r.getCellByContainerId(e.childContainerId),l=r.getCellByContainerId(o.childContainerId),c=Math.min(s.row,l.row),a=Math.max(s.row,l.row),u=Math.min(s.col,l.col),f=Math.max(s.col,l.col),m=PT(i,{row:c,col:u},{row:a,col:f}),C=r.getCell({row:m.top,col:m.left}),v=r.getCell({row:m.bottom,col:m.right}),B=r.getCell({row:m.top,col:m.right}),y=r.getCell({row:m.bottom,col:m.left});let S,I;return s.row<=l.row?s.col<=l.col?(S=C,I=v):(S=B,I=y):s.col<l.col?(S=y,I=B):(S=v,I=C),console.log(`move ${S.col}, ${S.row}, -> ${I.col}, ${I.row}`),{anchor:wt(t,S.containerId),focus:wt(t,I.containerId)}}function R4(n,t,e){if(e.isSimple())return[jt(t).getBoundingClientRect()];const o=jt(t),r=o.getBoundingClientRect(),{fromCol:i,fromRow:s,toCol:l,toRow:c}=an(t,e.start,e.end),a=Es(o),u=a.slice(0,i).reduce((B,y)=>B+y,0),f=u+a.slice(i,l+1).reduce((B,y)=>B+y,0),m=y4(o);let C=m.slice(0,s).reduce((B,y)=>B+y,0);const v=C+m.slice(s,c+1).reduce((B,y)=>B+y,0);if(s===0){const B=vT(n,t);C-=B}return[new DOMRect(r.left+u,r.top+C,f-u,v-C)]}w("table-size");const HT=40;function Gc(n){const t=n.querySelector("td");if(!t)return 0;const e=window.getComputedStyle(t),o=Number.parseInt(e.borderLeft,10),r=Number.parseInt(e.borderRight,10);return(o+r)/2}function FT(n,t,e){const o=wd(n,e.container);return o!==void 0?o+Gc(t):HT*e.colSpan-Gc(t)}function zT(n,t,e,o){let r=0;const i=e.colCount;for(let s=0;s<i;s++){const l=e.getRealCell({col:s,row:o});if(l.virtual)continue;let c=FT(n,t,l);const a=ug(l.container,{withPadding:!0});a&&a>c&&(c=a),r+=c+Gc(t)}return r}function UT(n,t){const e=jt(t),o=et.fromTable(e);let r=0;for(let s=0;s<o.rowCount;s++)r=Math.max(r,zT(n,e,o,s));const i=Gc(e);return r+=i,r}const Yn=w("table-creator");async function VT(n,t){return n.undoManager.runInGroup(()=>{var c,a;const e=t.item,o=(c=e.colCount)!=null?c:5,r=(a=e.rowCount)!=null?a:3,i=RT(n,{cols:o,rows:r});if(!i)return null;const{blockData:s,focusBlockId:l}=i;return n.insertBlock(t.containerId,t.blockIndex,s,At(n,l,0))})}class qT{constructor(){h(this,"id","insert-table");h(this,"name","Create table");h(this,"element");h(this,"closeable",null);h(this,"colCount");h(this,"rowCount");h(this,"setCloseable",t=>{this.closeable=t});h(this,"destroy",()=>{this.closeable=null});h(this,"getTableCreatorCellId",(t,e)=>`table-creator-cell-${t}-${e}`);h(this,"handleTableCreatorClick",t=>{var m,C;t.preventDefault(),t.stopPropagation();const e=t.target;d(Yn,e instanceof HTMLElement,"invalid event target");const o=e.closest(".table-creator");d(Yn,o,"no table creator");const r=o.querySelectorAll(".active");if(r.length===0)return;const s=r[r.length-1].id;d(Yn,s,"no cell id");const l="table-creator-cell-";if(!s.startsWith(l))return;const a=s.substring(l.length).split("-");d(Yn,a.length===2,"invalid cell id");const u=Number.parseInt(a[0],10)+1,f=Number.parseInt(a[1],10)+1;Yn.debug(`${u}, ${f}`),this.colCount=f,this.rowCount=u,(m=this.closeable)==null||m.click(this,this.element),(C=this.closeable)==null||C.close(),this.handleTableCreatorLeave()});h(this,"handleTableCreatorLeave",()=>{for(let t=0;t<9;t++)for(let e=0;e<9;e++){const o=this.getTableCreatorCellId(t,e),r=document.getElementById(o);r&&z(r,"active")}});h(this,"handleTableCreatorCellEnter",t=>{const e=t.target;d(Yn,e instanceof HTMLElement,"invalid event target");const o=e.id,r="table-creator-cell-";d(Yn,o.startsWith(r),"invalid cell id");const s=o.substring(r.length).split("-");d(Yn,s.length===2,"invalid cell id");let l=Number.parseInt(s[0],10),c=Number.parseInt(s[1],10);l===0&&c===0&&(l=-1,c=-1);for(let a=0;a<9;a++)for(let u=0;u<9;u++){const f=this.getTableCreatorCellId(a,u),m=document.getElementById(f);d(Yn,m,"no cell"),a<=l&&u<=c?A(m,"active"):z(m,"active")}});this.element=this.createTableCreatorElement()}createTableCreatorElement(){const t=b("div",["table-creator"],null),e=(o,r,i)=>{const s=b("div",["table-creator-cell"],o);return s.id=this.getTableCreatorCellId(r,i),s};t.addEventListener("click",this.handleTableCreatorClick),t.addEventListener("mouseleave",this.handleTableCreatorLeave);for(let o=0;o<9;o++){const r=b("div",["table-creator-row"],t);for(let i=0;i<9;i++)e(r,o,i).addEventListener("mouseenter",this.handleTableCreatorCellEnter)}return t}}function WT(){return new qT}function GT(n){const t=/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g,e=n.match(t);return e?e.length:0}function A4(n){const t=GT(n);return n.length+t}function ZT(n,t){const e=A4(n),o=t-e;return o>0?n+" ".repeat(o):n}function YT(n,t,e,o,r){const i=t,s=new vc(i);if(o==="markdown"||o==="text"){const l=y=>e.blocks[y].map((M,R)=>o==="markdown"?nu(n,M,e,[...r,{containerId:y,blockIndex:R}]):ql(n,M,e,[...r,{containerId:y,blockIndex:R}])),c=y=>l(y).join(" ").replace(/\n/g," ").trim(),a=new Map,u=new Map;for(let y=0;y<s.colCount;y++){let S=0;for(let I=0;I<s.rowCount;I++){const M=s.getCell({row:I,col:y});let R="";M.virtual||(R=c(M.containerId)),a.set(`${I},${y}`,R),S=Math.max(S,A4(R))}u.set(y,S)}const f=y=>{const S=a.get(`${y.row},${y.col}`)||"",I=u.get(y.col)||0;return ZT(S,I)},m=[];let C="|",v="|";for(let y=0;y<s.colCount;y++){const S=f({row:0,col:y});C+=` ${S} |`;const I="-".repeat((u.get(y)||0)+2);v+=`${I}|`}m.push(C),m.push(v);for(let y=1;y<s.rowCount;y++){let S="|";for(let I=0;I<s.colCount;I++){const M=f({row:y,col:I});S+=` ${M} |`}m.push(S)}return`${m.join(`
367
+ `:r.mathjaxText}const n1={embedType:"math",createEmbedContent:Yx,getOptions:Kx,convertFrom:Qx,handleDeleteBlock:Jx,convertTo:Xx},Cz="",tT={mathjax:{emptyText:"\u7A7A\u7684\u516C\u5F0F",abstract:"\u516C\u5F0F"}},eT={mathjax:{emptyText:"Empty Tex",abstract:"TeX"}};T.mergeLang({"zh-CN":tT,"en-US":eT});function nT(n,t,e,o){const r=n.getBlockByIndex(t,e),i=n.getBlockText(r),{left:s}=be(i,o);if(!vt(s).endsWith("$$$$"))return!1;const c=o-4,a=o,u={id:N(),box:!0,type:"math",tex:" ",src:"",created:Date.now()};return n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,c,a-c),n.insertBoxToBlock(r,c,u),setTimeout(()=>{const f=n.getBoxById(u.id);t1(n,f)})}),!0}class oT{handleAfterInsertText(t,e,o,r,i){return!!(i===" "&&nT(t,e,o,r))}}const C4=w("inline-box-items");function rT(n,t,e){return n.undoManager.runInGroup(()=>{var s;let o=n.getBlockByIndex(t,e);Tt(n,o)||(o=n.insertTextBlock([],t,e));const r=Hx();n.setBlockText(o,[r]);const i=(s=r.attributes)==null?void 0:s.id;return d(C4,i,"mathjax box id is empty"),setTimeout(()=>{const l=n.getBoxById(i);t1(n,l)},100),o})}function iT(n,t,e){let o=n.getBlockByIndex(t,e),r="bottom-start";return Tt(n,o)||(r="top-start"),Rc(n,{target:o,linkText:"",linkUrl:"",onFinished:(l,c)=>{n.undoManager.runInGroup(()=>{try{Tt(n,o)||(o=n.insertTextBlock([],t,e));const a=$e(l,{link:c}),u=$e(" ",null),f=[a,u];n.insertTextToBlock(o,0,f),n.selection.selectBlock(o,de(f)),n.focus()}catch(a){C4.error(a)}})},onClose:()=>{n.focus()},placement:r}),o}async function sT(n,t){switch(t.item.id){case"insert-math":return rT(n,t.containerId,t.blockIndex);case"insert-link":return iT(n,t.containerId,t.blockIndex);default:return null}}function lT(){return{name:"text",insertBlockCommandItems:[{id:"insert-math",name:T.t("quickMenu.inlineBox.math"),icon:qw,order:900,group:"common",subText:fe("insert-math")},{id:"insert-link",name:T.t("quickMenu.inlineBox.link"),icon:n5,order:400,group:"common",subText:fe("insert-link")}],handleInsertEmptyBlock:sT}}const cT={basics:100,system:200,common:300,thirdParty:400};function aT(n){var o,r;const t=(r=(o=n.options.componentsOptions)==null?void 0:o.quickMenu)==null?void 0:r.commandProviders;if(!t)return[];const e=[];return[...t,new h4].forEach(i=>{const s=i.getCommands(n);e.push(...s.map(l=>({...l,itemType:"insert-block",commandProvider:i})))}),e}function dT(n){const t=[];n.editorBlocks.forEach(o=>{if(!o.getOptions)return;const r=o.getOptions(n);!r.insertBlockCommandItems||(r.insertBlockCommandItems.forEach(i=>{Qh(i,r)}),t.push(...r.insertBlockCommandItems))});const e=lT();return e.insertBlockCommandItems.forEach(o=>{Qh(o,e)}),t.push(...e.insertBlockCommandItems),t.push(...aT(n)),t}function o1(n){const t=dT(n),e=new Map;t.forEach(i=>{var c;const s=(c=i.group)!=null?c:"";let l=e.get(s);l?l.items.push(i):(l={group:s,order:i.groupOrder||cT[s]||1e3,items:[i]},e.set(s,l))});const o=Array.from(e.values());o.sort((i,s)=>i.order-s.order),o.forEach(i=>{i.items.sort((s,l)=>{var c,a;return((c=s.order)!=null?c:0)-((a=l.order)!=null?a:0)})});const r=[];return o.forEach((i,s)=>{const l=T.t(`blockMenu.section.${i.group||"common"}`),c=l===i.group?i.group:l;r.push({id:`section-${s}`,name:c,type:"section",group:i.group,itemType:"insert-block"}),r.push(...i.items.map(a=>({...a})))}),r}function uT(n,t,e){const o=n.getFocusedBlock();if(!o)return;const r=n.getParentContainer(o),i=U(r);let l=n.getBlockIndex(o);if(Tt(n,o)||(l+=1),t.commandProvider){t.commandProvider.executeCommand(n,t,{from:"quick-menu",...e});return}!t.blockOptions||!t.blockOptions.handleInsertEmptyBlock||t.blockOptions.handleInsertEmptyBlock(n,{containerId:i,blockIndex:l,item:t})}const b4=w("quick-menu"),hT={id:"quick-menu",trigger:["/"]};class zc{constructor(t,e=hT){h(this,"suggest");h(this,"items");h(this,"maxHeading");h(this,"queryItems",async(t,e)=>{if(this.items.length===0?this.initMenuItems():this.refreshMenuItems(),e){const o=new Set,r=e.toLocaleLowerCase().replace(/^\s+|\s+$/g,"");return this.items.filter(i=>{var s;return i.type==="section"?!0:i.name.toLocaleLowerCase().indexOf(r)!==-1||AB(i).toLocaleLowerCase().indexOf(r)!==-1||i.group&&((s=i.group)==null?void 0:s.toLocaleLowerCase().indexOf(r))!==-1?(o.add(i.group),!0):!1}).filter(i=>i.type==="section"?o.has(i.group):!0)}return this.items});h(this,"onShow",(t,e,o,r)=>{const i=this.editor.getBlockByIndex(e,o);if(!Ko(i)){const s=F(H(i));if(s&&rt(s)==="code")return!1}return!0});h(this,"onClickItem",(t,e)=>{const o=e;o.itemType==="insert-block"&&(d(b4,o.blockOptions||o.commandProvider,"invalid quick item, no block options or command provider"),d(b4,this.suggest.anchor,"invalid suggest, no anchor"),uT(this.editor,o,this.suggest.anchor))});this.editor=t,this.options=e,this.items=[],this.maxHeading=Oc(),this.suggest=new mh(t,{id:e.id||"quick-menu",trigger:e.trigger,needSpaceBeforeTrigger:!0,autoDeleteTrigger:!0,highlight:!0,onShow:this.onShow,onClickItem:this.onClickItem,queryItems:this.queryItems})}get menu(){return this.suggest.menu.menu}destroy(){this.suggest.destroy()}initMenuItems(){const t=o1(this.editor);this.items=t}refreshMenuItems(){let t=null,e=0;const o=Oc();if(o!==this.maxHeading){const r=new h4,s=r.getCommands().map(l=>({...l,itemType:"insert-block",commandProvider:r}));for(let l=0;l<this.items.length;l++)this.items[l].group==="basics"&&(t||(t=l),t&&e++);t&&e&&this.items.splice(t,e,...s),this.maxHeading=o}}}class r1{constructor(t){h(this,"instance");h(this,"mousedown",!1);h(this,"currentInstance",null);h(this,"attributeName","");h(this,"attributeDesc","");h(this,"observer",null);h(this,"observerCallback",null);h(this,"createContent",t=>{var i;const e=(i=t.getAttribute(this.attributeName))!=null?i:"",o=t.getAttribute(this.attributeDesc);if(!o)return e;const r=b("div",[],null);return b("span",[],r,e),o&&b("span",["editor-tooltip-desc"],r,o),r});h(this,"handleDocumentMouseDown",()=>{this.mousedown=!0,this.editor.domEvents.addEventListener(document,"mouseup",this.handleDocumentMouseUp)});h(this,"handleDocumentMouseUp",()=>{this.mousedown=!1,this.editor.domEvents.removeEventListener(document,"mouseup",this.handleDocumentMouseUp)});h(this,"handleShown",t=>{this.currentInstance&&this.hide(),this.currentInstance=t,this.createObserver()});h(this,"handleHidden",()=>{this.destroyObserver(),this.currentInstance=null});h(this,"handleShow",t=>{var r;const e=t.reference;if(!e||!It(document.body,e)||window.isDragging||this.mousedown)return!1;const o=Number.parseInt((r=e.getAttribute("data-tooltip-hide-at"))!=null?r:"",10);return!(o&&Date.now()-o<1e3)});this.editor=t;const e=t.clientId;this.attributeName=`data-editor-tooltip-${e}`,this.attributeDesc=`data-editor-tooltip-desc-${e}`,this.instance=qa.delegate(document.body,{delay:200,target:`[${this.attributeName}]`,content:this.createContent,onShow:this.handleShow,onShown:this.handleShown,onHide:this.handleHidden}),t.domEvents.addEventListener(document,"mousedown",this.handleDocumentMouseDown)}visible(){var t;return(t=this.currentInstance)==null?void 0:t.state.isVisible}hide(){var t;(t=this.currentInstance)!=null&&t.state.isVisible&&this.currentInstance.hide()}destroy(){this.destroyObserver(),this.instance.destroy(),this.editor.domEvents.removeEventListener(document,"mousedown",this.handleDocumentMouseDown),this.editor.domEvents.removeEventListener(document,"mouseup",this.handleDocumentMouseUp)}createObserver(){this.destroyObserver();const t=this.currentInstance;if(!t||!t.reference)return;this.observerCallback=Xt.default(()=>{t.reference.closest("body")||(t.hide(),this.destroyObserver())},200),this.observer=new MutationObserver(this.observerCallback);const e=document.body,o={childList:!0,attributes:!1,subtree:!0};this.observer.observe(e,o)}destroyObserver(){this.observer&&(this.observer.disconnect(),this.observer=null),this.observerCallback&&(this.observerCallback.cancel(),this.observerCallback=null)}}const fT={"text/style-bold":"bold","text/style-italic":"italic","text/style-underline":"underline","text/style-strikethrough":"line-through","text/style-code":"code","text/style-subscript":"subscript","text/style-superscript":"superscript"};function mT(n,t){const e=new Set(Object.keys(fT)),o=t.filter(i=>e.has(i.id));return Lc(o)}function Uc(n,t){if(!n.isWritable())return!1;const e=n.selection.range,o=n.editorCommandProviders.getCommands(e),i=mT(n,o).find(s=>s.id===`text/${t}`);return i?(n.editorCommandProviders.executeCommand(e,i,{}),Xr.get(n).update("selectionChange"),!0):!1}const i1={"CtrlOrCmd+B":n=>Uc(n,"style-bold"),"CtrlOrCmd+I":n=>Uc(n,"style-italic"),"CtrlOrCmd+U":n=>Uc(n,"style-underline"),"CtrlOrCmd+D":n=>Uc(n,"style-strikethrough")},gT={quickMenu:{basic:{heading:{title:"\u6807\u9898 {heading}",space:"{markdown}\u7A7A\u683C"},unordered:"\u65E0\u5E8F\u5217\u8868",ordered:"\u6709\u5E8F\u5217\u8868",checkbox:"\u5F85\u529E\u4E8B\u9879",quote:"\u5F15\u7528"},inlineBox:{math:"\u516C\u5F0F",link:"\u94FE\u63A5"}},link:{textLabel:"\u6587\u672C",urlLabel:"\u94FE\u63A5\u5730\u5740",textPlaceholder:"\u8BF7\u8F93\u5165\u6587\u672C",urlPlaceholder:"\u8BF7\u8F93\u5165\u94FE\u63A5\u5730\u5740",submitText:"\u786E\u5B9A",cancelText:"\u53D6\u6D88"},commands:{unordered:"\u65E0\u5E8F\u5217\u8868",ordered:"\u6709\u5E8F\u5217\u8868",check:"\u5F85\u529E\u5217\u8868",link:"\u94FE\u63A5",quote:"\u5F15\u7528",alignLeft:"\u5DE6\u5BF9\u9F50",alignRight:"\u53F3\u5BF9\u9F50",alignCenter:"\u5C45\u4E2D\u5BF9\u9F50",alignGroup:"\u5BF9\u9F50\u65B9\u5F0F",heading:"\u6807\u9898 {name}",headingGroup:"\u6807\u9898\u6837\u5F0F",text:"\u6B63\u6587"},commandDesc:{mac:{unordered:"\u2318+\u21E7+L",ordered:"\u2318+\u21E7+U",link:"\u2318+K"},window:{unordered:"Ctrl+Shift+L",ordered:"Ctrl+Shift+U",link:"Ctrl+K"}}},pT={quickMenu:{basic:{heading:{title:"Heading {heading}",space:"{markdown}space"},unordered:"Bulleted list",ordered:"Numbered list",checkbox:"Todo list",quote:"Quote"},inlineBox:{math:"Math",link:"Link"},link:{textLabel:"Text",urlLabel:"Link Address",textPlaceholder:"Please enter text",urlPlaceholder:"Please enter the link address",submitText:"Ok",cancelText:"Cancel"}},commands:{unordered:"Bulleted list",ordered:"Numberer list",check:"Todo list",link:"Link",quote:"Quote",alignLeft:"Align left",alignRight:"Align right",alignCenter:"Align center",alignGroup:"Alignment",heading:"Heading {name}",headingGroup:"Text style",text:"Text"},commandDesc:{mac:{unordered:"\u2318+\u21E7+L",ordered:"\u2318+\u21E7+U",link:"\u2318+K"},window:{unordered:"Ctrl+Shift+L",ordered:"Ctrl+Shift+U",link:"Ctrl+K"}}};T.mergeLang({"zh-CN":gT,"en-US":pT});const bz="";function sr(n,...t){const e=go(...t);return e.classList.remove("editor-button"),e.classList.add("editor-text-button"),n.append(e),e}function v4(n){Mc(n).hide();const e=n.getCustom("table-border-bar");e==null||e.closeToolbar()}function CT(n){return b("div",["insert-column-button","drop-marker"],n)}const k4=w("row-height");function y4(n){const t=et.fromTable(n),e=n.rows;d(k4,e.length===t.rowCount,"row count mismatch");const o=Array(t.rowCount).fill(0);for(let r=0;r<e.length;){let i=1,l=e[r].getBoundingClientRect().height,c=r+1;for(;c<e.length;){const a=e[c];if(a.cells.length!==0)break;i++,c++,l+=a.getBoundingClientRect().height}for(let a=0;a<i;a++)o[r+a]=l/i;r=c}return k4.debug("heights",o.join(", ")),o}const ko=w("table-border-bar-dom");function Ss(n,t){d(ko,Ht(t),"invalid table block");const e=jt(t),o=Tn(n,t),r=(a,u,f)=>{const m=b("div",["button-root",u],a),C=b("div",["button-container",u],m);m.setAttribute(`data-${u}-index`,`${f}`),C.setAttribute(`data-editor-tooltip-${n.clientId}`,u==="left"?T.t("table.insertRow"):T.t("table.insertCol")),b("span",["insert-indicator"],C),CT(C)},{selectedRows:i,selectedColumns:s}=ph(n,t),l=()=>{const a=o.querySelector(".table-border-bar-container.top");d(ko,a,"no top border bar container");const u=b("div",["table-border-bar-container","top"],null),f=b("div",["table-border-bar","top"],u),m=ME(e);b("span",["table-border-bar-cell","corner"],f);const v=et.fromTable(e).colCount;n.selection.range.isSimple()&&r(f,"top",0);for(let B=0;B<v;B++){const y=B===v-1?m[B]+2:m[B],S=b("span",["table-border-bar-cell","top"],f);s.has(B)&&S.classList.add("selected"),S.setAttribute("data-top-index",`${B}`),S.style.width=`${y}px`,n.selection.range.isSimple()&&r(f,"top",B+1)}Mi(a,u)},c=()=>{const a=o.querySelector(".table-border-bar-container.left");d(ko,a,"no left border bar container");const u=b("div",["table-border-bar-container","left"],null),f=b("div",["table-border-bar","left"],u),m=y4(e);n.selection.range.isSimple()&&r(f,"left",0),Array.from(e.rows).forEach((C,v,B)=>{const y=b("span",["table-border-bar-cell","left"],f);i.has(v)&&y.classList.add("selected"),y.setAttribute("data-left-index",`${v}`);const S=v===B.length-1?m[v]+2:m[v];y.style.height=`${S}px`,n.selection.range.isSimple()&&r(f,"left",v+1)}),Mi(a,u)};l(),c()}function w4(n,t){const e=t.target;if(!(e instanceof Element))return;const o=F(e);d(ko,o&&Ht(o),"invalid table block"),Ss(n,o),n.selection.caret.update()}function s1(n,t){const e=t.target;if(!(e instanceof Element))return;const o=F(e);d(ko,o&&Ht(o),"invalid table block");const r=e.closest(".button-root");if(r){if(r.classList.contains("top")){const i=parseInt(r.getAttribute("data-top-index")||"0",10);H5(n,o,i),Ss(n,o)}else if(r.classList.contains("left")){const i=parseInt(r.getAttribute("data-left-index")||"0",10);F5(n,o,i),Ss(n,o)}}}function l1(n,t){var s;v4(n),t.preventDefault(),t.stopPropagation();let e=null,o,r;const i=l=>{var c;if(l.target instanceof HTMLElement&&o&&e&&r!==void 0){const a=F(l.target),u=l.target.closest(".table-border-bar");if(a===e&&u){const f=parseInt((c=l.target.getAttribute(`data-${o}-index`))!=null?c:"0",10),m=Math.min(r,f),C=Math.abs(r-f)+1;nt(l.target,"top")&&o==="top"?VE(n,a,m,C,{reverse:!0}):nt(l.target,"left")&&o==="left"&&qE(n,a,m,C,{reverse:!0})}}l.type==="mouseup"&&(e=null,r=void 0,o=void 0,document.body.removeEventListener("mousemove",i),document.body.removeEventListener("mouseup",i))};t.target instanceof HTMLElement&&nt(t.target,"table-border-bar-cell")&&(e=F(t.target),nt(t.target,"top")?o="top":nt(t.target,"left")&&(o="left"),o&&e&&(r=parseInt((s=t.target.getAttribute(`data-${o}-index`))!=null?s:"0",10),document.body.addEventListener("mousemove",i),document.body.addEventListener("mouseup",i)))}function bT(n,t){d(ko,Ht(t),"invalid table block");const e=Tn(n,t),o=b("div",["table-border-bar-container","top"],e),r=b("div",["table-border-bar-container","left"],e);Ss(n,t),n.domEvents.addEventListener(it(t),"scroll",w4),n.domEvents.addEventListener(o,"click",s1),n.domEvents.addEventListener(r,"click",s1),n.domEvents.addEventListener(o,"mousedown",l1),n.domEvents.addEventListener(r,"mousedown",l1)}function B4(n,t){if(!n.isWritable())return;if(Tn(n,t).querySelector(".table-border-bar-container")){Ss(n,t);return}bT(n,t)}function E4(n,t){d(ko,Ht(t),"invalid table block"),Tn(n,t).querySelectorAll(".table-border-bar-container").forEach(r=>{n.domEvents.removeEventListener(r,"click",s1),n.domEvents.removeEventListener(r,"mousedown",l1),r.remove()}),n.domEvents.removeEventListener(it(t),"scroll",w4)}function vT(n,t){d(ko,Ht(t),"invalid table block");const o=Tn(n,t).querySelector(".table-border-bar-container.top");return o?o.getBoundingClientRect().height:0}class kT{constructor(t,e){h(this,"toolbar");h(this,"handleSelectionChange",(t,e)=>{e==="delete-columns"?(Vr(this.editor,this.tableBlock,!0,!0),qr(this.editor,this.tableBlock,!0,!0)):e==="delete-rows"?(Vr(this.editor,this.tableBlock,!0,!1),qr(this.editor,this.tableBlock,!0,!1)):(Vr(this.editor,this.tableBlock,!1),qr(this.editor,this.tableBlock,!1))});h(this,"handleClick",(t,e,o)=>{e.id==="delete-columns"?Ch(this.editor.selection.range):e.id==="delete-rows"&&bh(this.editor.selection.range)});this.editor=t,this.tableBlock=e;const o=t.options.componentsOptions.popover;this.toolbar=new ps([],void 0,{overflowBoundary:o==null?void 0:o.overflowBoundary,refuseOverflow:!0,tooltipId:this.editor.clientId}),this.toolbar.addListener("selectionChange",this.handleSelectionChange),this.toolbar.addListener("click",this.handleClick)}close(){this.toolbar.close()}update(){const{selectedColumns:t,selectedRows:e}=ph(this.editor,this.tableBlock);if(!this.editor.isWritable())return;if(t.size>0&&e.size>0){this.toolbar.close();return}if(t.size===0&&e.size===0){this.toolbar.close();return}const o=Ho(this.editor,this.tableBlock,this.editor.selection.range)[0];if(!o){this.toolbar.close();return}if(t.size>0){const r={id:"delete-columns",name:T.t("table.deleteCol"),icon:Rw};this.toolbar.updateItems([r]);const i=zo(this.editor,this.tableBlock,"editor-quick-menu",o);this.toolbar.manualShow(i,{placement:"top"})}else{const r={id:"delete-rows",name:T.t("table.deleteRow"),icon:Mw};this.toolbar.updateItems([r]);const i=new DOMRect(o.left-15,o.top,o.width,o.height),s=zo(this.editor,this.tableBlock,"editor-quick-menu",i);this.toolbar.manualShow(s,{placement:"left"})}}destroy(){this.toolbar.destroy(),this.toolbar.removeAllListeners()}}const Vc=w("table-border-bar");class yT{constructor(t,e){h(this,"toolbar");h(this,"resizeObserver");h(this,"handleReadonlyChanged",t=>{t.isWritable()?this.update():E4(this.editor,this.tableBlock)});h(this,"handleBlockUpdated",()=>{this.resizeObserver.disconnect(),setTimeout(()=>{const t=this.editor.getBlockById(q(this.tableBlock));this.resizeObserver.observe(jt(t))})});h(this,"handleTableResize",()=>{!this.editor.isWritable()||(console.log("resize"),this.update())});this.editor=t,this.tableBlock=e,d(Vc,this.tableBlock,"no table block"),Vc.debug("create table border bar"),B4(this.editor,this.tableBlock),this.resizeObserver=new ResizeObserver(this.handleTableResize),this.resizeObserver.observe(jt(this.tableBlock)),this.toolbar=new kT(this.editor,this.tableBlock),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}close(){this.toolbar.close()}destroy(){Vc.debug("destroy table border bar"),this.resizeObserver.disconnect(),E4(this.editor,this.tableBlock),this.toolbar.destroy(),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged)}update(){Vc.debug("update table border bar"),B4(this.editor,this.tableBlock),this.toolbar.update()}}const wT=w("table-border-bar");class BT{constructor(t){h(this,"activeTableBar",null);h(this,"handleBlockDeleted",(t,e)=>{!this.activeTableBar||(e===this.activeTableBar.tableBlock||It(e,this.activeTableBar.tableBlock))&&(this.activeTableBar.destroy(),this.activeTableBar=null)});h(this,"handleSelectionChanged",t=>{var r;const e=t.selection.range;let o=null;if(e.isCollapsed()&&e.isSimple()){const i=t.getBlockById(e.start.blockId);if(Ht(i)){const s=H(i),l=F(s);l&&(o=Me(l))}else o=Me(i)}else{const i=t.getBlockById(e.start.blockId),s=Me(i),l=t.getBlockById(e.end.blockId),c=Me(l);s===c&&(o=s)}((r=this.activeTableBar)==null?void 0:r.tableBlock)!==o&&this.activeTableBar&&this.hide(),o&&this.show(o)});this.editor=t,this.editor.addListener("blockDeleted",this.handleBlockDeleted),this.editor.addListener("selectionChanged",this.handleSelectionChanged)}destroy(){this.editor.removeListener("blockDeleted",this.handleBlockDeleted),this.editor.removeListener("selectionChanged",this.handleSelectionChanged)}show(t){this.activeTableBar?(this.activeTableBar.tableBlock!==t&&this.hide(),this.activeTableBar.update()):this.activeTableBar=new yT(this.editor,t)}update(){var t;(t=this.activeTableBar)==null||t.handleBlockUpdated()}closeToolbar(){var t;(t=this.activeTableBar)==null||t.close()}hide(){!this.activeTableBar||(d(wT,this.activeTableBar,"no active table bar"),this.activeTableBar.destroy(),this.activeTableBar=null)}}function I4(n,t){const e=n.addCustom("table-border-bar",o=>new BT(o));t==="update"&&e.update()}const Be=w("table-cell-menu"),ET="style-bg-color-";class IT{constructor(t){h(this,"activeTableBlock",null);h(this,"targetButton",null);h(this,"manualMenu",null);h(this,"colorPaletteItem",null);h(this,"handlePrevent",(t,e)=>{e.stopPropagation()});h(this,"handleReadonlyChanged",t=>{t.isWritable()||this.hide()});h(this,"handleSelectionChanged",t=>{const e=t.selection.range;let o=null;if(e.isCollapsed()&&e.isSimple()){const r=t.getBlockById(e.start.blockId);if(Ht(r)){const i=H(r),s=F(i);s&&(o=Me(s))}else o=Me(r)}else{const r=t.getBlockById(e.start.blockId),i=Me(r),s=t.getBlockById(e.end.blockId),l=Me(s);i===l&&(o=i)}if(this.hide(),this.activeTableBlock!==o&&(this.activeTableBlock=o),this.activeTableBlock){const r=et.fromBlock(this.activeTableBlock),i=e.isReverse()?e.start:e.end;let s=null;e.isCollapsed()?s=this.getCellByChildBlockId(r,i.blockId):i instanceof Je&&(t.getBlockById(i.blockId)===this.activeTableBlock?s=r.getCellByContainerId(i.childContainerId):s=this.getCellByChildBlockId(r,i.blockId)),s&&this.editor.isWritable()&&this.showCellMenuButton(s)}});h(this,"handleBeforePopupPalette",()=>{var e;const t=this.getSelectedBkgColorIndex();(e=this.colorPaletteItem)==null||e.palette.setColor("backgroundColor",t)});h(this,"createBkgColorItem",()=>{const t=b("div",["cell-background-color-item"],null);b("span",[],t,T.t("table.cellBackground"));const e=this.getSelectedBkgColorIndex();b("button",["item-button"],t).setAttribute("data-color-index",`${e}`);const r=b("span",["item-sub-indicator"],t);return r.innerHTML=J2,t});h(this,"handleCommand",t=>{var r;d(Be,this.activeTableBlock,"no target table block");const e=((r=t.states)==null?void 0:r.includes("checked"))||!1,o=t.value;switch(t.id){case"delete-select-row":bh(y5(this.editor,this.activeTableBlock,!1));break;case"delete-select-col":Ch(y5(this.editor,this.activeTableBlock,!0));break;case"merge-cell":b5(this.editor.selection.range);break;case"split-cell":this.handleSplitCell();break;case"row-title":this.handleRowTitle(e);break;case"col-title":this.handleColTitle(e);break;case"stripe-style":this.handleStripeStyle(e);break;case"hide-border":XB(this.editor,this.activeTableBlock,o==="show-border");break;case"show-chart":rE(this.editor,this.activeTableBlock,o==="show-chart"),Sh(this.editor,this.activeTableBlock,{updateNow:!0});break}});h(this,"handleSelectionChange",(t,e)=>{d(Be,this.activeTableBlock,"no target table block"),e==="cell-background-color"&&this.handleBeforePopupPalette(),e==="delete-select-row"?(Vr(this.editor,this.activeTableBlock,!0,!1),qr(this.editor,this.activeTableBlock,!0,!1)):e==="delete-select-col"?(Vr(this.editor,this.activeTableBlock,!0,!0),qr(this.editor,this.activeTableBlock,!0,!0)):(Vr(this.editor,this.activeTableBlock,!1),qr(this.editor,this.activeTableBlock,!1))});h(this,"handleClick",()=>{var t;d(Be,this.activeTableBlock,"no target table block"),d(Be,this.targetButton,"no target button"),v4(this.editor),nt(this.targetButton,"active")?(z(this.targetButton,"active"),(t=this.manualMenu)==null||t.close()):(A(this.targetButton,"active"),this.manualMenu?this.manualMenu.updateItems(this.createCommandMenu()):(this.manualMenu=new tr(this.createCommandMenu()),this.manualMenu.on("click",(e,o)=>{var r;this.handleCommand(o),(r=this.manualMenu)==null||r.close()}),this.manualMenu.on("selectionChange",this.handleSelectionChange),this.manualMenu.on("close",()=>{this.targetButton&&z(this.targetButton,"active"),this.editor.focus()})),this.manualMenu.manualShow(this.targetButton,{placement:"right-start"}))});this.editor=t,this.editor.addListener("selectionChanged",this.handleSelectionChanged),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}destroy(){var t,e;this.activeTableBlock=null,this.targetButton=null,this.editor.removeListener("selectionChanged",this.handleSelectionChanged),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged),(t=this.manualMenu)==null||t.destroy(),(e=this.colorPaletteItem)==null||e.destroy()}hide(){var t;(t=this.manualMenu)==null||t.close(),this.targetButton&&(z(this.targetButton,"active"),this.targetButton.style.display="none")}getCellByChildBlockId(t,e){let o=this.editor.getBlockById(e);for(;o;){const r=o.closest("td");d(Be,r,"no parent cell");const i=F(r);if(d(Be,i,"no parent block"),jt(i)===t.table)return t.getCellByCellElement(r);o=i}return d(Be,!1,"filed to get cell by child block id"),null}createTargetButton(t){this.targetButton?t.querySelector(":scope > .table-cell-menu-btn")||t.appendChild(this.targetButton):(this.targetButton=b("button",["table-cell-menu-btn"],t),this.targetButton.innerHTML=Ju,this.editor.domEvents.addEventListener(this.targetButton,"click",this.handleClick),this.editor.domEvents.addEventListener(this.targetButton,"mousedown",this.handlePrevent))}showCellMenuButton(t){this.createTargetButton(t.cell),d(Be,this.targetButton,"no target button"),this.targetButton.style.display="inline-block"}handleSplitCell(){if(this.activeTableBlock){const t=et.fromBlock(this.activeTableBlock),e=this.editor.selection.range;if(e.isSimple()){const{col:o,row:r}=this.getCellByChildBlockId(t,e.start.blockId);kh(this.editor,this.activeTableBlock,{col:o,row:r})}else yh(this.editor.selection.range)}}getSelectedBkgColorIndex(){var r;d(Be,this.activeTableBlock,"no target table block");const t=nE(this.editor,this.activeTableBlock),e=this.editor.getBlockData(this.activeTableBlock),o=new Set;for(const i of t){if(o.size>1)break;const s=U(i),l=e[`${s}_background`];if(l)o.add(Number.parseInt((r=l.substring(ET.length))!=null?r:"0",10));else{o.add(-1);break}}return o.size===1&&[...o][0]!==-1?[...o][0]:-1}createCommandMenu(){d(Be,this.activeTableBlock,"no target table block");const t=this.editor.getBlockData(this.activeTableBlock),e=C5(this.editor,this.activeTableBlock,this.editor.selection.range);let o=this.editor.selection.range;if(o.isSimple()){const u=Gn(this.editor,this.activeTableBlock,o.start);o=Wt(this.editor,{anchor:u,focus:u})}const r=p5(this.editor,this.activeTableBlock,o),i=t.hasRowTitle,s=t.hasColTitle,l=t.isStripeStyle,c=t.noBorder,a=t.chart;return this.colorPaletteItem=new d5("cell-background-color",{color:!1}),this.colorPaletteItem.palette.on("onClick",(u,f)=>{var m;switch(d(Be,this.activeTableBlock,"no target table block"),u){case"clearColor":E5(this.editor,this.activeTableBlock,-1);break;case"backgroundColor":E5(this.editor,this.activeTableBlock,f);break}(m=this.manualMenu)==null||m.close()}),[{id:"cell-background-color",name:T.t("table.cellBackground"),element:this.createBkgColorItem(),children:[this.colorPaletteItem]},{id:"separator",name:"",type:"separator"},{id:"merge-cell",name:T.t("table.mergeCell"),states:e?[]:["disabled"]},{id:"split-cell",name:T.t("table.splitCell"),states:r?[]:["disabled"]},{id:"separator",name:"",type:"separator"},{id:"delete-select-row",name:T.t("table.deleteSelectRow")},{id:"delete-select-col",name:T.t("table.deleteSelectCol")},{id:"separator",name:"",type:"separator"},{id:"table-config",name:T.t("table.tableConfigKey"),children:[{id:"row-title",name:T.t("table.tableConfig.rowTitle"),states:i?["checked"]:[]},{id:"col-title",name:T.t("table.tableConfig.colTitle"),states:s?["checked"]:[]},{id:"stripe-style",name:T.t("table.tableConfig.stripeStyle"),states:l?["checked"]:[]},{id:"hide-border",name:c?T.t("table.tableConfig.showBorder"):T.t("table.tableConfig.hideBorder"),value:c?"show-border":"hide-border"},{id:"show-chart",name:a?T.t("table.tableConfig.hideChart"):T.t("table.tableConfig.showChart"),value:a?"hide-chart":"show-chart"}]}]}handleRowTitle(t){d(Be,this.activeTableBlock,"no target table block"),t?QB(this.editor,this.activeTableBlock):YB(this.editor,this.activeTableBlock)}handleColTitle(t){d(Be,this.activeTableBlock,"no target table block"),t?ZB(this.editor,this.activeTableBlock):GB(this.editor,this.activeTableBlock)}handleStripeStyle(t){d(Be,this.activeTableBlock,"no target table block"),t?JB(this.editor,this.activeTableBlock):KB(this.editor,this.activeTableBlock)}}function x4(n){n.addCustom("table-cell-menu",t=>new IT(t))}const qc=w("table-container");function c1(n){const t=n.closest("td");return d(qc,t,"no parent cell for a table cell container"),t}function T4(n){const t=jt(n);return Array.from(t.querySelectorAll(':scope > tbody > tr > td > [data-type="editor-container"].child'))}function a1(n,t,e,o){const r=et.fromBlock(n),i=r.getCellByContainerId(U(t));if(e==="ArrowDown"){const s=r.getBottomCell(i);return s?s.container:null}if(e==="ArrowUp"){const s=r.getTopCell(i);return s?s.container:null}if(e==="ArrowLeft"){const s=r.getAllContainers(),l=s.indexOf(t);if(d(qc,l>=0,"not a valid child container"),l===0)return null;const c=s[l-1];return o!=null&&o.noWrap&&r.getCellByContainerId(U(c)).row!==i.row?null:c}if(e==="ArrowRight"){const s=r.getAllContainers(),l=s.indexOf(t);if(d(qc,l>=0,"not a valid child container"),l===s.length-1)return null;const c=s[l+1];return o!=null&&o.noWrap&&r.getCellByContainerId(U(c)).row!==i.row?null:c}d(qc,!1,`invalid navigation type: ${e}`)}const xT=12,TT=90,Wc=23,S4=2;class ST{constructor(t){h(this,"scrollTableBlock",null);h(this,"autoScrollDir",null);h(this,"autoScrollTimer",null);h(this,"handleMouseDown",t=>{const e=document.elementFromPoint(t.clientX,t.clientY);if(e&&e instanceof HTMLElement){const o=F(e);if(o&&It(this.editor.rootContainer,o)){const r=Me(o);r&&(this.scrollTableBlock=r,document.addEventListener("mousemove",this.handleAutoScroll))}}});h(this,"handleAutoScroll",b7.default(t=>{if(this.scrollTableBlock){const e=this.editor.getCustom(Co(this.scrollTableBlock)),o=e.rootElement,r=e.scrollOptions.parentContainer,i=o.getBoundingClientRect(),s=window.innerHeight-(e.scrollOptions.barFloatWindowBottom||0),l=r.getBoundingClientRect(),c=Math.min(l.bottom,s),a=Math.max(l.top,0);i.bottom>c&&t.clientY>=c?this.setAutoScroll("bottom"):i.top<a&&t.clientY<=a?this.setAutoScroll("top"):o.scrollLeft>0&&t.clientX<i.left?this.setAutoScroll("left"):o.scrollLeft<o.scrollWidth-o.offsetWidth&&t.clientX>i.right?this.setAutoScroll("right"):this.clearAutoScroll()}},15));h(this,"handleMouseUp",()=>{document.removeEventListener("mousemove",this.handleAutoScroll),setTimeout(()=>{this.scrollTableBlock=null})});h(this,"handleSelectionChanged",t=>{const e=t.selection.range;if(e.isCollapsed()&&e.isSimple()){const o=t.getBlockById(e.start.blockId),r=Me(o);if(r){const i=t.getCustom(Co(r)),s=i.rootElement.getBoundingClientRect(),l=Ke(t,o,e.start);if(s.left>l.left){const c=e.start.offset===0?xT:S4;i.rootElement.scrollLeft-=s.left-l.left+c}else if(l.right>s.right){const c=e.start.offset===0?TT:S4;i.rootElement.scrollLeft+=l.right-s.right+c}}}else{const o=t.getBlockById(e.start.blockId),r=Me(o),i=t.getBlockById(e.end.blockId),s=Me(i);if(r&&r===s){const l=t.getCustom(Co(r)),c=l.rootElement.getBoundingClientRect();let a=null;if(e.isSimple())a=e.isReverse()?Ke(t,o,e.start):Ke(t,i,e.end);else{const u=c1(Br(t,e.start.childContainerId)),f=c1(Br(t,e.end.childContainerId));a=e.isReverse()?u.getBoundingClientRect():f.getBoundingClientRect()}c.left>a.left&&e.isReverse()?l.rootElement.scrollLeft-=c.left-a.left:c.right<a.right&&!e.isReverse()&&(l.rootElement.scrollLeft+=a.right-c.right)}}});h(this,"handleScroll",t=>{f5(t),this.editor.selection.caret.update()});h(this,"handleReset",t=>{f5(t),this.editor.selection.caret.update()});this.editor=t,this.editor.addListener("selectionChanged",this.handleSelectionChanged),document.addEventListener("mousedown",this.handleMouseDown),document.addEventListener("mouseup",this.handleMouseUp)}clearAutoScroll(){this.autoScrollTimer&&(clearInterval(this.autoScrollTimer),this.autoScrollTimer=null,this.autoScrollDir=null)}setAutoScroll(t){this.autoScrollDir&&this.autoScrollDir!==t&&this.clearAutoScroll(),this.autoScrollTimer||(this.autoScrollDir=t,this.autoScrollTimer=window.setInterval(()=>{if(this.scrollTableBlock){const e=this.editor.getCustom(Co(this.scrollTableBlock)),o=e.rootElement,r=e.scrollOptions.parentContainer,i=o.getBoundingClientRect(),s=r===document.documentElement?window.innerHeight:r.offsetHeight,l=window.innerHeight-(e.scrollOptions.barFloatWindowBottom||0),c=r.getBoundingClientRect(),a=Math.min(c.bottom,l),u=Math.max(c.top,0);this.autoScrollDir==="left"&&(o.scrollLeft-=Wc,o.scrollLeft<=0&&this.clearAutoScroll()),this.autoScrollDir==="right"&&(o.scrollLeft+=Wc,o.scrollLeft>=o.scrollWidth-o.offsetWidth&&this.clearAutoScroll()),this.autoScrollDir==="bottom"&&(r.scrollTop+=Wc,(r.scrollTop>=r.scrollHeight-s||i.bottom<=a)&&this.clearAutoScroll()),this.autoScrollDir==="top"&&(r.scrollTop-=Wc,(r.scrollTop<=0||i.top>=u)&&this.clearAutoScroll())}},100))}destroy(){document.removeEventListener("mousedown",this.handleMouseDown),document.removeEventListener("mouseup",this.handleMouseUp),this.editor.removeListener("selectionChanged",this.handleSelectionChanged)}}function D4(n){return n.addCustom("table-scroll-events",t=>new ST(t))}const Sn=w("create-content");function L4(n,t,e){const o=new vc(e),r=e.rows,i=e.cols;d(Sn,r>=1,`invalid rows: ${r}`),d(Sn,i>=1,`invalid cols: ${i}`),d(Sn,e.children,"no table children");const s=b("table",[],null),l=e.colsWidth,c=b("colgroup",[],s);for(let f=0;f<o.colCount;f++){const m=b("col",[],c);m.style.width=`${l[f]||Sc}px`}const a=b("tbody",[],s);let u=0;for(let f=0;f<r;f++){const m=b("tr",[],a);for(let C=0;C<i;C++){const v=o.getCell({col:C,row:f});if(v.virtual)d(Sn,v.colSpan>1||v.rowSpan>1,"virtual cell should have colSpan or rowSpan");else{const B=e.children[u],y=b("td",[],m);v.colSpan>1&&(y.colSpan=v.colSpan),v.rowSpan>1&&(y.rowSpan=v.rowSpan);const S=e[ks(B)];S&&A(y,S),C===0&&e.hasColTitle&&A(y,v5.COL_TITLE_ITEM),n.createChildContainer(t,y,B),u+=1}}}return d(Sn,u===e.children.length,"container count mismatch"),e.noBorder&&A(s,"no-border"),e.chart&&A(s,"editor-table-chart"),e.isStripeStyle&&A(s,"stripe"),e.hasRowTitle&&A(s,"row-title"),e.hasColTitle&&A(s,"col-title"),s}function DT(n,t,e,o,r){d(Sn,r.type==="table","not table data"),d(Sn,U(e)===t[t.length-1].containerId,"invalid path");const i=r,s=ro(o,"div");try{const l=b("div",[],null);l.setAttribute("data-type","table-content");const c=L4(n,t,i);c.classList.add("drag-preview-element"),l.appendChild(c),P5(n),U5(n),I4(n,"create"),x4(n),vw(n,Dh);const a=n.getComponentOptions("table"),u=n.addCustom(Co(o),()=>SE());u.init({parentElement:s,childElement:l,safeRightSpace:50,safeLeftSpace:40,parentContainer:pt(e)?n.scrollContainer:e,locatingContainer:pt(e)?(a==null?void 0:a.locatingContainer)||n.parent:e,paddingLeft:Eh+vs,paddingTop:Eh+vs,paddingBottom:vs/2,paddingRight:vs/2,barFloatWindowBottom:a==null?void 0:a.barFloatWindowBottom,isSetScale:a==null?void 0:a.isSetScale});const f=D4(n);u.on("scroll",f.handleReset),u.on("resize",f.handleReset),setTimeout(()=>{lE(n,o)})}catch{const c=`invalid table data: ${JSON.stringify(i)}`;Sn.error(c);const a=b("div",["error"],s);a.innerText=c}return s}function LT(n,t,e){d(Sn,e.type==="table","not table data");const o=e,r=it(t);try{const i=jt(t),s=jo(t),l=L4(n,s,o);l.classList.add("drag-preview-element"),i.insertAdjacentElement("afterend",l),i.remove(),P5(n),U5(n),I4(n,"update"),x4(n),Dh(n,t)}catch{const s=`invalid table data: ${JSON.stringify(o)}`;Sn.error(s);const l=b("div",["error"],r);l.innerText=s}}function MT(n,t){let e,o,r=!1;if([...t].every(m=>m==="|")?(o=t.length,e=Array(o).fill(""),r=!0):(e=nd(t,"|").split("|"),o=e.length),o<2)return null;const i=3,s=o,l=[];for(let m=0;m<3;m++)e.forEach(C=>{l.push(yn(n.doc,m===0?C:""))});const c=Array(s).fill(Sc),a=l[r?0:s],u=n.doc.getContainerBlocks(a)[0].id;return{blockData:{id:N(),type:"table",rows:i,cols:s,children:l,colsWidth:c},focusBlockId:u}}function RT(n,t){const e=t.rows,o=t.cols;if(e<1||o<1)return null;const r=[];for(let a=0;a<e;a++)for(let u=0;u<o;u++)r.push(yn(n.doc));const i=Array(o).fill(Sc),s=r[0],l=n.doc.getContainerBlocks(s)[0].id;return{blockData:{id:N(),type:"table",rows:e,cols:o,children:r,colsWidth:i},focusBlockId:l}}const M4=w("table-selection-to-doc");function AT(n,t){const{start:e,end:o,block:r}=t,i=rt(r);d(M4,i==="table",`invalid block type: ${i}`);const s=n.getBlockData(r);if(e.isSimple()&&o.isSimple())return ao(n.editorBlocks,n.doc.toJSON(),s);d(M4,!e.isSimple()&&!o.isSimple(),"invalid block pos type");const l=et.fromBlock(r),{fromCol:c,toCol:a,fromRow:u,toRow:f}=an(r,e,o),m={},C=[],v=n.doc.toJSON();let B={};l.sub({row:u,col:c},{row:f,col:a}).forEach((Z,ot)=>{Z.forEach((st,mt)=>{const ut=st.containerId;if(C.indexOf(ut)!==-1)return;C.push(ut);let yt;if(st.virtual){const ee=l.getCellByContainerId(st.containerId),Ue=c+mt;let Eo=ee.col+ee.colSpan-1;Eo>a&&(Eo=a);const gr=Eo-Ue+1;gr>1&&(m[`${ut}_colSpan`]=gr);const pr=u+ot;let Io=ee.row+ee.rowSpan-1;Io>f&&(Io=f);const ya=Io-pr+1;ya>1&&(m[`${ut}_rowSpan`]=ya),yt=Zo()}else{if(yt=hu(n.editorBlocks,v,ut),st.col+st.colSpan>a+1){const ee=a-st.col+1;ee>1&&(m[`${ut}_colSpan`]=ee)}else st.colSpan>1&&(m[`${ut}_colSpan`]=st.colSpan);if(st.row+st.rowSpan>f+1){const ee=f-st.row+1;ee>1&&(m[`${ut}_rowSpan`]=ee)}else st.rowSpan>1&&(m[`${ut}_rowSpan`]=st.rowSpan)}const{root:se,...eo}=yt.blocks;B={...B,...eo,[ut]:se}})});const S=Es(jt(r)).slice(c,a+1);return{blocks:{root:[{id:N(),type:i,children:C,colsWidth:S,rows:f-u+1,cols:a-c+1,...m}],...B},meta:{},comments:{}}}function OT(n,t){if(t.top===0)return!0;for(let e=t.left;e<=t.right;e++)if(n[t.top-1][e]===n[t.top][e])return!1;return!0}function _T(n,t){if(t.left===0)return!0;for(let e=t.top;e<=t.bottom;e++)if(n[e][t.left-1]===n[e][t.left])return!1;return!0}function NT(n,t){if(t.bottom===n.length-1)return!0;for(let e=t.left;e<=t.right;e++)if(n[t.bottom][e]===n[t.bottom+1][e])return!1;return!0}function $T(n,t){if(t.right===n[0].length-1)return!0;for(let e=t.top;e<=t.bottom;e++)if(n[e][t.right]===n[e][t.right+1])return!1;return!0}function PT(n,t,e){const o=t.col,r=t.row,i=e.col,s=e.row,l={left:o,top:r,right:i,bottom:s};let c=!1;do{if(c=!1,!OT(n,l)){l.top--,c=!0;continue}if(!_T(n,l)){l.left--,c=!0;continue}if(!NT(n,l)){l.bottom++,c=!0;continue}if(!$T(n,l)){l.right++,c=!0;continue}}while(c);return l}function jT(n,t,e,o){if(e.custom!==void 0||o.custom!==void 0)return{anchor:e,focus:o};const r=et.fromBlock(t),i=r.map(M=>M.containerId),s=r.getCellByContainerId(e.childContainerId),l=r.getCellByContainerId(o.childContainerId),c=Math.min(s.row,l.row),a=Math.max(s.row,l.row),u=Math.min(s.col,l.col),f=Math.max(s.col,l.col),m=PT(i,{row:c,col:u},{row:a,col:f}),C=r.getCell({row:m.top,col:m.left}),v=r.getCell({row:m.bottom,col:m.right}),B=r.getCell({row:m.top,col:m.right}),y=r.getCell({row:m.bottom,col:m.left});let S,I;return s.row<=l.row?s.col<=l.col?(S=C,I=v):(S=B,I=y):s.col<l.col?(S=y,I=B):(S=v,I=C),console.log(`move ${S.col}, ${S.row}, -> ${I.col}, ${I.row}`),{anchor:wt(t,S.containerId),focus:wt(t,I.containerId)}}function R4(n,t,e){if(e.isSimple())return[jt(t).getBoundingClientRect()];const o=jt(t),r=o.getBoundingClientRect(),{fromCol:i,fromRow:s,toCol:l,toRow:c}=an(t,e.start,e.end),a=Es(o),u=a.slice(0,i).reduce((B,y)=>B+y,0),f=u+a.slice(i,l+1).reduce((B,y)=>B+y,0),m=y4(o);let C=m.slice(0,s).reduce((B,y)=>B+y,0);const v=C+m.slice(s,c+1).reduce((B,y)=>B+y,0);if(s===0){const B=vT(n,t);C-=B}return[new DOMRect(r.left+u,r.top+C,f-u,v-C)]}w("table-size");const HT=40;function Gc(n){const t=n.querySelector("td");if(!t)return 0;const e=window.getComputedStyle(t),o=Number.parseInt(e.borderLeft,10),r=Number.parseInt(e.borderRight,10);return(o+r)/2}function FT(n,t,e){const o=wd(n,e.container);return o!==void 0?o+Gc(t):HT*e.colSpan-Gc(t)}function zT(n,t,e,o){let r=0;const i=e.colCount;for(let s=0;s<i;s++){const l=e.getRealCell({col:s,row:o});if(l.virtual)continue;let c=FT(n,t,l);const a=ug(l.container,{withPadding:!0});a&&a>c&&(c=a),r+=c+Gc(t)}return r}function UT(n,t){const e=jt(t),o=et.fromTable(e);let r=0;for(let s=0;s<o.rowCount;s++)r=Math.max(r,zT(n,e,o,s));const i=Gc(e);return r+=i,r}const Yn=w("table-creator");async function VT(n,t){return n.undoManager.runInGroup(()=>{var c,a;const e=t.item,o=(c=e.colCount)!=null?c:5,r=(a=e.rowCount)!=null?a:3,i=RT(n,{cols:o,rows:r});if(!i)return null;const{blockData:s,focusBlockId:l}=i;return n.insertBlock(t.containerId,t.blockIndex,s,At(n,l,0))})}class qT{constructor(){h(this,"id","insert-table");h(this,"name","Create table");h(this,"element");h(this,"closeable",null);h(this,"colCount");h(this,"rowCount");h(this,"setCloseable",t=>{this.closeable=t});h(this,"destroy",()=>{this.closeable=null});h(this,"getTableCreatorCellId",(t,e)=>`table-creator-cell-${t}-${e}`);h(this,"handleTableCreatorClick",t=>{var m,C;t.preventDefault(),t.stopPropagation();const e=t.target;d(Yn,e instanceof HTMLElement,"invalid event target");const o=e.closest(".table-creator");d(Yn,o,"no table creator");const r=o.querySelectorAll(".active");if(r.length===0)return;const s=r[r.length-1].id;d(Yn,s,"no cell id");const l="table-creator-cell-";if(!s.startsWith(l))return;const a=s.substring(l.length).split("-");d(Yn,a.length===2,"invalid cell id");const u=Number.parseInt(a[0],10)+1,f=Number.parseInt(a[1],10)+1;Yn.debug(`${u}, ${f}`),this.colCount=f,this.rowCount=u,(m=this.closeable)==null||m.click(this,this.element),(C=this.closeable)==null||C.close(),this.handleTableCreatorLeave()});h(this,"handleTableCreatorLeave",()=>{for(let t=0;t<9;t++)for(let e=0;e<9;e++){const o=this.getTableCreatorCellId(t,e),r=document.getElementById(o);r&&z(r,"active")}});h(this,"handleTableCreatorCellEnter",t=>{const e=t.target;d(Yn,e instanceof HTMLElement,"invalid event target");const o=e.id,r="table-creator-cell-";d(Yn,o.startsWith(r),"invalid cell id");const s=o.substring(r.length).split("-");d(Yn,s.length===2,"invalid cell id");let l=Number.parseInt(s[0],10),c=Number.parseInt(s[1],10);l===0&&c===0&&(l=-1,c=-1);for(let a=0;a<9;a++)for(let u=0;u<9;u++){const f=this.getTableCreatorCellId(a,u),m=document.getElementById(f);d(Yn,m,"no cell"),a<=l&&u<=c?A(m,"active"):z(m,"active")}});this.element=this.createTableCreatorElement()}createTableCreatorElement(){const t=b("div",["table-creator"],null),e=(o,r,i)=>{const s=b("div",["table-creator-cell"],o);return s.id=this.getTableCreatorCellId(r,i),s};t.addEventListener("click",this.handleTableCreatorClick),t.addEventListener("mouseleave",this.handleTableCreatorLeave);for(let o=0;o<9;o++){const r=b("div",["table-creator-row"],t);for(let i=0;i<9;i++)e(r,o,i).addEventListener("mouseenter",this.handleTableCreatorCellEnter)}return t}}function WT(){return new qT}function GT(n){const t=/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g,e=n.match(t);return e?e.length:0}function A4(n){const t=GT(n);return n.length+t}function ZT(n,t){const e=A4(n),o=t-e;return o>0?n+" ".repeat(o):n}function YT(n,t,e,o,r){const i=t,s=new vc(i);if(o==="markdown"||o==="text"){const l=y=>e.blocks[y].map((M,R)=>o==="markdown"?nu(n,M,e,[...r,{containerId:y,blockIndex:R}]):ql(n,M,e,[...r,{containerId:y,blockIndex:R}])),c=y=>l(y).join(" ").replace(/\n/g," ").trim(),a=new Map,u=new Map;for(let y=0;y<s.colCount;y++){let S=0;for(let I=0;I<s.rowCount;I++){const M=s.getCell({row:I,col:y});let R="";M.virtual||(R=c(M.containerId)),a.set(`${I},${y}`,R),S=Math.max(S,A4(R))}u.set(y,S)}const f=y=>{const S=a.get(`${y.row},${y.col}`)||"",I=u.get(y.col)||0;return ZT(S,I)},m=[];let C="|",v="|";for(let y=0;y<s.colCount;y++){const S=f({row:0,col:y});C+=` ${S} |`;const I="-".repeat((u.get(y)||0)+2);v+=`${I}|`}m.push(C),m.push(v);for(let y=1;y<s.rowCount;y++){let S="|";for(let I=0;I<s.colCount;I++){const M=f({row:y,col:I});S+=` ${M} |`}m.push(S)}return`${m.join(`
368
368
  `)}
369
369
  `}if(o==="html"){const l=a=>e.blocks[a].map((m,C)=>eu(n,m,e,[...r,{containerId:a,blockIndex:C}])).join(`
370
370
  `),c=[];c.push("<table>");for(let a=0;a<s.rowCount;a++){let u="<tr>";for(let f=0;f<s.colCount;f++){const m=s.getCell({row:a,col:f});if(m.virtual)u+="<td></td>";else{const C=l(m.containerId);u+=`<td colSpan="${m.colSpan}" rowSpan="${m.rowSpan}">${C}</td>`}}u+="</tr>",c.push(u)}return c.push("</table>"),c.join(`
@@ -373,7 +373,7 @@ $$${r.mathjaxText}$$
373
373
  <path fill-rule="evenodd" clip-rule="evenodd" d="M12 7.61719C11.4477 7.61719 11 7.16947 11 6.61719V3.61719C11 3.0649 11.4477 2.61719 12 2.61719C12.5523 2.61719 13 3.0649 13 3.61719V6.61719C13 7.16947 12.5523 7.61719 12 7.61719ZM4.92893 5.54612C5.31946 5.15559 5.95262 5.1556 6.34315 5.54612L8.46447 7.66744C8.85499 8.05796 8.85499 8.69113 8.46447 9.08165C8.07394 9.47218 7.44078 9.47218 7.05025 9.08165L4.92893 6.96033C4.53841 6.56981 4.53841 5.93664 4.92893 5.54612ZM15.5355 9.08165C15.145 8.69113 15.145 8.05796 15.5355 7.66744L17.6569 5.54612C18.0474 5.1556 18.6805 5.1556 19.0711 5.54612C19.4616 5.93664 19.4616 6.56981 19.0711 6.96033L16.9497 9.08165C16.5592 9.47218 15.9261 9.47218 15.5355 9.08165ZM2 12.6172C2 12.0649 2.44772 11.6172 3 11.6172L6 11.6172C6.55229 11.6172 7 12.0649 7 12.6172C7 13.1695 6.55228 13.6172 6 13.6172L3 13.6172C2.44772 13.6172 2 13.1695 2 12.6172ZM17 12.6172C17 12.0649 17.4477 11.6172 18 11.6172L21 11.6172C21.5523 11.6172 22 12.0649 22 12.6172C22 13.1695 21.5523 13.6172 21 13.6172L18 13.6172C17.4477 13.6172 17 13.1695 17 12.6172ZM15.5355 16.1527C15.9261 15.7622 16.5592 15.7622 16.9497 16.1527L19.0711 18.274C19.4616 18.6646 19.4616 19.2977 19.0711 19.6883C18.6805 20.0788 18.0474 20.0788 17.6569 19.6883L15.5355 17.5669C15.145 17.1764 15.145 16.5432 15.5355 16.1527ZM4.92893 19.6883C4.53841 19.2977 4.53841 18.6646 4.92893 18.274L7.05025 16.1527C7.44078 15.7622 8.07394 15.7622 8.46447 16.1527C8.85499 16.5432 8.85499 17.1764 8.46447 17.5669L6.34315 19.6883C5.95262 20.0788 5.31946 20.0788 4.92893 19.6883ZM12 22.6172C11.4477 22.6172 11 22.1695 11 21.6172V18.6172C11 18.0649 11.4477 17.6172 12 17.6172C12.5523 17.6172 13 18.0649 13 18.6172V21.6172C13 22.1695 12.5523 22.6172 12 22.6172Z" fill="#5587F0"/>
374
374
  <animateTransform attributeType="xml" attributeName="transform" type="rotate" values="0 12 12.5;360 12 12.5" dur="2s" repeatCount="indefinite" />
375
375
  </g>
376
- </svg>`,u1=w("webpage");class gS{constructor(t,e){h(this,"currentSrc","");h(this,"loading",null);h(this,"handleMaskMouseMove",(t,e)=>{if(!window.isDragging){if(e.target&&e.target instanceof Element){const o=e.target.closest("webpage-mask");o&&(o.style.display="none")}t.domEvents.addEventListener(document,"mousemove",this.handleDocumentMouseMove)}});h(this,"handleDocumentMouseMove",(t,e)=>{if(!e.target||!(e.target instanceof Element))return;const o=this.editor.findBlockById(this.blockData.id);if(o){const r=this.getExistsMask(o);if(r){if(It(o,e.target)){r.style.display="none";return}r.style.display=""}}});this.editor=t,this.blockData=e}create(t,e,o,r){const i=e.src,s=b("div",["editor-embed"],null),l=b("iframe",["editor-preview-iframe"],s);this.loading=this.createLoading(s);const c=()=>{d(u1,this.loading,"not created"),this.loading.hide(),this.currentSrc=i};t.domEvents.addEventListener(l,"load",c),l.src=i,this.loading.show(),o.append(s),this.createMask(t,r)}update(t,e,o){if(d(u1,this.loading,"not created"),this.currentSrc===o.src)return;const r=e.querySelector(".editor-preview-iframe");d(u1,r,"no exists iframe"),this.loading.show(),r.src=o.src,this.createMask(t,e)}createLoading(t){const e=b("div",["editor-preview-iframe-loading"],null),o=b("span",[],e);return o.innerHTML=mS,{show(){t.append(e)},hide(){const r=t.querySelector(":scope > .editor-preview-iframe-loading");!r||r.remove()}}}getExistsMask(t){return Rt(t).querySelector(".webpage-mask")}createMask(t,e){const o=Rt(e);let r=this.getExistsMask(e);if(r){r.style.display="";return}r=b("div",["webpage-mask"],o),t.domEvents.addEventListener(r,"mousemove",this.handleMaskMouseMove)}destroy(){const t=this.editor.findBlockById(this.blockData.id);if(t){const e=this.getExistsMask(t);e&&(this.editor.domEvents.removeEventListener(e,"mousemove",this.handleMaskMouseMove),this.editor.domEvents.removeEventListener(document,"mousemove",this.handleDocumentMouseMove))}}}function pS(n,t){b("div",["resize-gripper",t],n).setAttribute("data-resize-type",t)}function h1(n){return Rt(n).querySelector(".block-resizer")}function CS(n){const t=h1(n);t&&z(t,"active")}function P4(n,t,e){const o=n.getBoundingClientRect(),r=t.getBoundingClientRect(),i=r.top-o.top,s=r.left-o.left,l=r.width,c=r.height;e.style.top=`${i}px`,e.style.left=`${s}px`,e.style.width=`${l}px`,e.style.height=`${c}px`}function bS(n,t,e,o){const r=h1(n);if(r)return A(r,"active"),P4(n,t,r),r;const i=Rt(n),s=b("div",["block-resizer"],i);return P4(n,t,s),e.resize.forEach(l=>{pS(s,l)}),s.addEventListener("mousedown",o),A(s,"active"),s}function j4(n,t){const e=h1(n);if(!e)return;const o=n.getBoundingClientRect(),r=t.getBoundingClientRect(),i=r.top-o.top,s=r.left-o.left,l=r.width,c=r.height;e.style.top=`${i}px`,e.style.left=`${s}px`,e.style.width=`${l}px`,e.style.height=`${c}px`}const yz="",vS=w("block-resizer");class Yc extends Yt.TypedEmitter{constructor(e,o){super();h(this,"resizableElement");h(this,"block",null);h(this,"startRect",null);h(this,"startPos",null);h(this,"resizeType",null);h(this,"enabled",!1);h(this,"handleMouseDown",e=>{e.preventDefault(),e.stopPropagation();const o=this.getResizableElement();if(!o||e.button!==0)return;const r=e.target;if(!r||!(r instanceof HTMLElement))return;const i=r.getAttribute("data-resize-type");!i||(this.bindEvents(),this.startRect=o.getBoundingClientRect(),this.startPos=e,this.resizeType=i,Li(window.getComputedStyle(r).cursor),this.block&&this.editor.selection.selectBlock(this.block,0))});h(this,"handleMouseMove",e=>{if(!this.startPos||!this.startRect||!this.resizeType)return;const o=this.getResizableElement();if(!o||!this.block)return;const r=e.x-this.startPos.x,i=e.y-this.startPos.y,s=this.startRect;let{top:l,left:c,right:a,bottom:u}=s;(this.resizeType==="bottom"||this.resizeType==="bottom-left"||this.resizeType==="bottom-right")&&(u+=i),(this.resizeType==="top"||this.resizeType==="top-left"||this.resizeType==="top-right")&&(l+=i),(this.resizeType==="left"||this.resizeType==="top-left"||this.resizeType==="bottom-left")&&(c+=r),(this.resizeType==="right"||this.resizeType==="top-right"||this.resizeType==="bottom-right")&&(a+=r);const f=a>c?a-c:0,m=u>l?u-l:0,C=new DOMRect(c,l,f,m);this.emit("resizing",this,C),j4(this.block,o)});h(this,"handleMouseUp",e=>{if(e.button!==0)return;Li(""),this.unbindEvents(),this.emit("resized",this);const o=this.getResizableElement();!o||!this.block||j4(this.block,o)});this.editor=e,this.options=o}enableResize(e,o){this.block=e,this.resizableElement=o,this.createResizer(),this.enabled=!0}disableResize(){!this.block||(CS(this.block),this.enabled=!1)}update(e,o){this.block=e,this.resizableElement=o,this.getResizableElement()&&this.enabled&&this.createResizer()}getBlock(){return this.block}destroy(){}getResizableElement(){return this.resizableElement?this.resizableElement:this.block?it(this.block):null}createResizer(){const e=this.getResizableElement();!e||!this.block||(d(vS,It(this.block,e),"not a block child element"),bS(this.block,e,this.options,this.handleMouseDown))}bindEvents(){document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp)}unbindEvents(){document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}}function H4(n){return n&&Te(n)&&Oe(n)==="webpage"}const kS=1e3,yS=100;class wS{constructor(t){h(this,"currentBlockElement",null);h(this,"resizing",!1);h(this,"handleHoveringBlockChange",(t,e)=>{this.resizing||!this.editor.isWritable()||(e&&H4(e)&&this.disableBlockResize(e),t&&H4(t)&&this.enableBlockResize(t))});h(this,"handleResizing",(t,e)=>{this.resizing=!0;const o=t.getBlock();if(!o)return;const r=Math.max(Math.min(e.height,kS),yS);o.style.height=`${r}px`,A(o,"resizing")});h(this,"handleResized",t=>{this.resizing=!1;const e=t.getBlock();if(!e)return;z(e,"resizing");const o=this.editor.getBlockData(e),r=e.getBoundingClientRect().height;this.editor.updateBlockData(e,{...o,height:r})});this.editor=t,Nt.get(t).addListener("change",this.handleHoveringBlockChange)}destroy(){this.currentBlockElement=null,Nt.get(this.editor).removeListener("change",this.handleHoveringBlockChange)}disableBlockResize(t){const e=this.editor.findCustom(`${q(t)}-resizer`);e&&e.disableResize()}enableBlockResize(t){const e=this.editor.addCustom(`${q(t)}-resizer`,()=>new Yc(this.editor,{resize:["bottom"]}));e.enableResize(t),e.removeListener("resizing",this.handleResizing),e.removeListener("resized",this.handleResized),e.addListener("resizing",this.handleResizing),e.addListener("resized",this.handleResized),this.currentBlockElement=t}}const wz="",BS=w("editor-dialog");function ES(n,t){const e=b("div",["editor-dialog-container"],null),o=b("div",["dialog-header"],e);b("span",["dialog-header-title"],o,t.title);const r=b("span",["close-icon"],o);r.innerHTML=Y2,b("div",["dialog-content"],e).appendChild(n);const s=b("div",["dialog-footer"],e);return b("button",["cancel-button"],s,"Cancel"),b("button",["submit-button"],s,"Ok"),e}class IS extends bc{constructor(e,o){super(ES(e,o),o);h(this,"_options");h(this,"getReferenceClientRect",()=>{const e=document.documentElement.clientHeight/2,o=document.documentElement.clientWidth/2,r=this.getCommandBarRoot();d(BS,r,"no command bar root");const{width:i,height:s}=r.getBoundingClientRect();return new DOMRect(Math.max(o-i/2,0),Math.max(e-s/2,0),0,0)});h(this,"handleOk",async()=>{var e,o;try{await((o=(e=this._options).onOk)==null?void 0:o.call(e)),this.destroy()}catch{}});h(this,"handleClose",()=>{var e,o;(o=(e=this._options).onClose)==null||o.call(e),this.destroy()});const r=this.content.querySelector(".submit-button"),i=this.content.querySelector(".cancel-button"),s=this.content.querySelector(".close-icon");r==null||r.addEventListener("click",this.handleOk),s==null||s.addEventListener("click",this.handleClose),i==null||i.addEventListener("click",this.handleClose),this._options=o}show(){super.show(document.documentElement,{getReferenceClientRect:this.getReferenceClientRect})}destroy(){const e=this.content.querySelector(".submit-button"),o=this.content.querySelector(".cancel-button"),r=this.content.querySelector(".close-icon");e==null||e.removeEventListener("click",this.handleOk),o==null||o.removeEventListener("click",this.handleClose),r==null||r.removeEventListener("click",this.handleClose),super.destroy()}}const F4=()=>[{name:T.t("webpage.bilibili"),id:"insert-bilibili",icon:Qw,group:"thirdParty",subText:fe("insert-bilibili")},{name:T.t("webpage.youku"),id:"insert-youku",icon:Kw,group:"thirdParty",subText:fe("insert-youku")},{name:T.t("webpage.figma"),id:"insert-figma",icon:Jw,group:"thirdParty",subText:fe("insert-figma")},{name:T.t("webpage.modao"),id:"insert-modao",icon:Xw,group:"thirdParty",subText:fe("insert-modao")},{name:T.t("webpage.tencent"),id:"insert-tencent",icon:tB,group:"thirdParty",subText:fe("insert-tencent")},{id:"insert-webPage",name:T.t("webpage.title"),icon:eB,group:"common",order:1e3,subText:fe("insert-webPage")}];function f1(n){return n==="insert-webPage"}async function xS(n,t){return n.doc.externalDoc.recognizeLink?n.doc.externalDoc.recognizeLink(t):null}function TS(n){return n&&!n.startsWith("http://")&&!n.startsWith("https://")&&!n.startsWith("//")?`//${n}`:n}async function SS(n){if(!n)throw new Error(T.t("webpage.dialog.errorEnterUrl"));let t=n;t.startsWith("//")&&(t=`http:${t}`);try{new URL(t)}catch{throw new Error(T.t("webpage.dialog.unsupportedUrl"))}}async function DS(n,t){const e=t.item.id,o=F4().find(a=>a.id===e),r=b("div",["webpage-content"],null);if(f1(e)){const a=b("div",["help-container"],r),u=b("div",["help-content"],a),f=b("span",["help-icon"],u);f.innerHTML=X2,b("span",[],u,T.t("webpage.dialog.helpContent"))}const{getInputValue:i,setFieldError:s,focus:l,getField:c}=uh(r,{required:!0,label:T.t("webpage.dialog.label"),placeholder:T.t("webpage.dialog.placeholder")});if(!f1(e)){const a=b("div",["help-link-container"],r),u=b("a",["help-link-content"],a);b("span",[],u,T.t("webpage.dialog.helpLink"));const f=b("span",["help-link-icon"],u);f.innerHTML=e5;const m=n.getComponentOptions("webpage");u.href=(m==null?void 0:m.helpLink)||"",u.target="_blank"}try{const a=await new Promise((m,C)=>{const v=new IS(r,{title:T.t("webpage.dialog.title",{name:(o==null?void 0:o.name)||""}),async onOk(){var S;const y=TS(i());try{await SS(y);const I=await xS(n,y);m((I==null?void 0:I.url)||"")}catch(I){if(((S=I==null?void 0:I.responseData)==null?void 0:S.statusCode)===415)if(f1(e))m(y);else throw s(T.t("webpage.dialog.unsupportedUrl")),I;else throw s(I.message||""),I}},onClose(){n.focus(),C()}});v.addListener("show",l),v.show(),c().addEventListener("keydown",async y=>{if(!y.isComposing){if(y.key==="Enter"){await v.handleOk(),y.preventDefault();return}y.key==="Escape"&&v.handleClose()}})}),u={id:N(),type:"embed",embedType:"webpage",embedData:{src:a}},f=n.insertBlock(t.containerId,t.blockIndex,u);return n.focus(),f}catch{return null}}const z4=w("embed-block-properties");function m1(n,t){var e;for(const o of n.blockHooks){const r=(e=o.commands)==null?void 0:e.call(o,n,t);if(!!r&&r.group==="block-comment-actions")return r.executeCommand(n,t,r.commands[0]),!0}return!1}class g1{constructor(t,e){h(this,"group","hovering-toolbar");h(this,"_commands",[{id:"edit",name:"Edit",icon:ah},{id:"add-comment",name:"Add Comment",icon:pc}]);this.editor=t,this.properties=e}get commands(){var e,o,r;if(!this.editor.isWritable())return[];const t=(e=this.properties)!=null&&e.presetIds?this._commands.filter(i=>{var s,l;return(l=(s=this.properties)==null?void 0:s.presetIds)==null?void 0:l.includes(i.id)}):[...this._commands];return(r=(o=this.properties)==null?void 0:o.extCommands)!=null&&r.length&&(t.push({id:N(),type:"separator",name:""}),t.push(...this.properties.extCommands)),t}executeCommand(t,e,o){var r,i;if(!((i=(r=this.properties)==null?void 0:r.handleExecuteCommand)!=null&&i.call(r,t,e,o))){if(o.id==="add-comment"){m1(t,e)||z4.error("failed to add comment to block");return}z4.error(`unknown command: ${JSON.stringify(o)}`),alert(o.id)}}}function p1(n,t,e){return{blockCommands:{"hovering-toolbar":new g1(n,e)}}}function LS(n){const t=n.querySelector(".editor-preview-iframe"),e=t.src;t.src="about:blank";const o=setTimeout(()=>{t.src=e,clearTimeout(o)},300);return!0}function MS(n,t){const e=n.getBlockData(t),{embedData:o}=e,r=o.src;return window.open(r,"_blank"),!0}function RS(n,t){const e=p1(n,t,{presetIds:["add-comment"],extCommands:[{id:"refresh",name:"Refresh page",icon:Gw},{id:"open-page",name:"Open the original page",icon:e5}],handleExecuteCommand:(r,i,s)=>{switch(s.id){case"refresh":return LS(i);case"open-page":return MS(r,i)}return!1}}),o=`[${T.t("webpage.abstract")}]`;return{...e,abstract:o}}const AS=w("webpage-embed");function OS(n,t,e,o,r,i){const{embedData:s,id:l}=e,{src:c}=s,a=n.addCustom(`webpage-${l}`,()=>new gS(n,e));d(AS,c,"The src from blockData is invalid "),a.create(n,s,t,i),n.addCustom("webpage-resizer",()=>new wS(n)),e.height&&(i.style.height=`${e.height}px`)}function _S(n,t,e){const{embedData:o,id:r}=e;return n.getCustom(`webpage-${r}`).update(n,t,o),e.height&&(t.style.height=`${e.height}px`),!0}function NS(){return{name:"WebPage",insertEmbedCommandItems:F4(),handleInsertEmptyEmbed:DS}}function $S(n,t,e,o){const i=t.embedData.src;return o==="html"?`<iframe src="${i}" ></iframe>`:o==="markdown"?`[${i}](${i})`:i}const C1={embedType:"webpage",createEmbedContent:OS,getBlockProperties:RS,getOptions:NS,handleUpdateBlock:_S,convertTo:$S},PS={webpage:{title:"\u7F51\u9875",youku:"\u4F18\u9177\u89C6\u9891",modao:"\u58A8\u5200",tencent:"\u817E\u8BAF\u89C6\u9891",bilibili:"Bilibili",figma:"Figma",dialog:{helpContent:"\u56E0\u76EE\u6807\u7F51\u9875\u7684\u9650\u5236\uFF0C\u90E8\u5206\u7F51\u9875\u53EF\u80FD\u65E0\u6CD5\u6210\u529F\u9884\u89C8\u3002",helpLink:"\u5982\u4F55\u83B7\u53D6\u94FE\u63A5",label:"\u7F51\u9875\u5730\u5740",placeholder:"\u8BF7\u8F93\u5165",title:"\u63D2\u5165{name}",errorEnterUrl:"\u8BF7\u8F93\u5165\u7F51\u9875\u5730\u5740",unsupportedUrl:"\u6682\u4E0D\u652F\u6301\u63D2\u5165\u8BE5\u94FE\u63A5\u5185\u5BB9"},abstract:"\u7F51\u9875"}},jS={webpage:{title:"Webpage",youku:"Youku",modao:"Modao",tencent:"Tencent Video",bilibili:"Bilibili",figma:"Figma",dialog:{helpContent:"Due to the limitation of the landing page, some pages may not be previewed successfully.",helpLink:"How to get the URL link",label:"Please enter webpage address",placeholder:"Please enter url",title:"Insert {name}",errorEnterUrl:"Please enter the webpage address",unsupportedUrl:"Unsupported url"},abstract:"Webpage"}};T.mergeLang({"zh-CN":PS,"en-US":jS});const Bz="";function HS(n,t,e,o){var f;const r=n.getBlockByIndex(t,e);if(W(n,r)!==o)return!1;const i=vt(n.getBlockText(r));if(![...i].every(m=>m==="|")||i.length<3||!n.editorBlocks.hasBlock("table"))return!1;const s=n.editorBlocks.getBlockClass("table");if(!s.convertFrom)return!1;const l=s.convertFrom(n,r,{offset:o});if(!l)return!1;const{blockData:c,focusBlockId:a}=l;if(!c)return!1;const u=n.insertBlock(t,e,c,At(n,a!=null?a:c.id,0));return n.deleteBlock(r),(f=l.onConverted)==null||f.call(l,n,u),!0}const FS={mermaid:{blockType:"embed",reg:/^```mermaid$/,data:{embedType:"mermaid"}},flowchart:{blockType:"embed",reg:/^```flowchart$/,data:{embedType:"flowchart"}},plantuml:{blockType:"embed",reg:/^```plantuml$/,data:{embedType:"plantuml"}},code:{blockType:"code",reg:/^```\S+$/},code2:{blockType:"code",reg:/^```$/},table:{blockType:"table",reg:/^\|.+\|.+\|$/},math:{blockType:"embed",reg:/^\$\$.+\$\$$/},image:{blockType:"embed",reg:/^!\[[^\]]*\]\((?<filename>.*?)(?="|\))(?<optionalPart>".*")?\)/,data:{embedType:"image"}},dividing:{blockType:"embed",reg:/^-{3,}$/,data:{embedType:"dividing-line"}},toc:{blockType:"embed",reg:/^\[toc\]/,data:{embedType:"toc"}}},zS={orderedList:{reg:/^(\d)+(\.|。)$/,blockType:"list",data:{listType:"ordered"}},unorderedList1:{reg:/^\*$/,blockType:"list",data:{listType:"unordered"}},unorderedList2:{reg:/^-$/,blockType:"list",data:{listType:"unordered"}},checkList1:{reg:/^\[\s?\]$/,blockType:"list",data:{listType:"unchecked"}},checkList2:{reg:/^\[X\]$/i,blockType:"list",data:{listType:"checked"}},image:{blockType:"embed",reg:/^!\[[^\]]*\]\((?<filename>.*?)(?="|\))(?<optionalPart>".*")?\)/,data:{embedType:"image"}}};function U4(n,t,e,o,r){if(r==="enter"&&HS(n,t,e,o))return!0;const i=n.getBlockByIndex(t,e),s=vt(be(n.getBlockText(i),o).left).trim(),l=r==="enter"?FS:zS;for(const[,c]of Object.entries(l)){if(!s.match(c.reg))continue;return!!n.undoManager.runInGroup(()=>{var v;const u=Oi(n,i,c.blockType,{offset:o,data:c.data});if(!u)return null;const{blockData:f,focusBlockId:m}=u;if(!f)return null;const C=n.insertBlock(t,e,f,At(n,m!=null?m:f.id,0));return n.deleteBlock(i),(v=u.onConverted)==null||v.call(u,n,C),{newBlock:C,focusBlockId:m}})}return!1}function US(n,t,e,o){const r=n.getBlockByIndex(t,e);return n.getBlockString(r,{boxReplacement:" "}).substring(0,o)!==">"?!1:(n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,0,o+1),n.updateBlockData(r,{quoted:!0},At(n,r,0))}),!0)}const VS={"#":1,"##":2,"###":3,"####":4,"#####":5,"######":6,"#######":7,"########":8};function qS(n,t,e,o){const r=n.getBlockByIndex(t,e),i=n.getBlockString(r,{boxReplacement:" "}).substring(0,o);let s=VS[i];if(!s)return!1;const l=n.getBlockData(r).heading;return l&&l==s&&(s=null),n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,0,o+1),n.updateBlockData(r,{heading:s},At(n,r,0))}),!0}function WS(n,t,e,o){return!!(qS(n,t,e,o)||US(n,t,e,o))}const GS=w("match-text-style");function ZS(n){let t="";for(let e=n.length-1;e>=0;e--){const o=n[e];if(!o.attributes||Object.keys(o.attributes).length===0){t+=o.insert;continue}break}return t}function YS(n,t){if(n.length<t.length*2+1||!n.endsWith(t)||n.substring(0,n.length-1).endsWith(t))return-1;const e=n.substring(0,n.length-t.length),o=e.lastIndexOf(t);return o===-1?-1:o===0?0:e.substring(o-1).startsWith(t)?-1:o}const QS={"*":{type:"style",styles:["style-italic"],boxType:""},"**":{type:"style",styles:["style-bold"],boxType:""},"***":{type:"style",styles:["style-bold","style-italic"],boxType:""},"~~":{type:"style",styles:["style-strikethrough"],boxType:""},"`":{type:"style",styles:["style-code"],boxType:""},$$:{type:"box",styles:[],boxType:"math"}};function KS(n,t,e,o){var u,f;const r=n.getBlockByIndex(t,e),i=n.getBlockText(r),{left:s}=be(i,o),l=ZS(s),c=de(s)-l.length,a=Object.entries(QS);for(const[m,C]of a){const v=YS(l,m);if(v===-1)continue;const B=c+v,y=o,S=m.length,I=vt(Gt(i,B+S,y-B-S*2).middle);if(C.type==="style"){const M={};C.styles.forEach($=>{M[$]=!0});const R=Go(I,M);n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,B,y-B),n.insertTextToBlock(r,B,R)})}else if(C.type==="box")try{const M=(f=(u=n.editorBoxes.getBoxClass(C.boxType)).convertFrom)==null?void 0:f.call(u,n,I);if(!M)continue;n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,B,y-B),n.insertBoxToBlock(r,B,M)})}catch(M){GS.warn(`failed to convert to box, ${M.message}`);continue}return!0}return!1}class Qc{handleAfterInsertText(t,e,o,r,i){return!!(i===" "&&(WS(t,e,o,r)||KS(t,e,o,r)))}handleBeforeKeyDown(t,e){if(!t.selection.range.isSimple())return!1;const{containerId:r,blockIndex:i,offset:s}=t.getTextPosition();if(j(t,t.getBlockByIndex(r,i))){if(Pn(e,"Enter")){if(U4(t,r,i,s,"enter"))return!0}else if(Pn(e,"Space")&&U4(t,r,i,s,"space"))return!0}return!1}}const JS={"en-US":{placeholder:{default:"Type \u2018/\u2019 for commands",heading:"Heading {heading}",list:"List",mention:"Quickly assign tasks @mention yourself or others",quote:"Quote",title:"Enter document title"}},"zh-CN":{placeholder:{default:"\u8F93\u5165\u300C/\u300D\u5FEB\u901F\u63D2\u5165",heading:"\u6807\u9898{heading}",list:"\u5217\u8868",mention:"\u5FEB\u901F\u5206\u914D\u4EFB\u52A1\uFF0C@\u63D0\u53CA\u81EA\u5DF1\u6216\u4ED6\u4EBA",quote:"\u5F15\u7528",title:"\u8BF7\u8F93\u5165\u6587\u6863\u6807\u9898"}}};T.mergeLang(JS);function Ls(n,t){const e=co(n,t);return!!(e.text&&de(e.text)===0&&!t.querySelector(".inputting-insertion"))}function V4(n,t){var o;it(t).removeAttribute("data-content-placeholder"),(o=t.querySelector("[data-type=block-tools] .block-placeholder-container"))==null||o.remove()}function Kc(n,t,e){var r;if(!Ls(n,t)){V4(n,t);return}const o=it(t);if(typeof e=="string")o.setAttribute("data-content-placeholder",e);else{const i=Rt(t),s=(r=i.querySelector(".block-placeholder-container"))!=null?r:b("div",["block-placeholder-container"],i);s.innerHTML="",s.appendChild(e)}}function XS(n){const t=n.getAttribute("data-style-heading");return t?T.t("placeholder.heading",{heading:t}):n.getAttribute("data-style-quoted")?T.t("placeholder.quote"):null}function tD(n){const t=n.getAttribute("data-list-type");return t?t==="ordered"||t==="unordered"?T.t("placeholder.list"):T.t("placeholder.mention"):null}function q4(n){switch(rt(n)){case"text":return XS(n);case"list":return tD(n);default:return null}}function eD(n){if(Ko(n))return!1;const t=F(H(n));return t?rt(t)==="code":!1}function nD(n,t){var u,f;const e=rt(n.selection.focusedBlock),o=t.contentPlaceholder||T.t("placeholder.default");let r=o;const i=n.selection.focusedBlock;if(e&&_i(n,e)&&i){if(eD(i))return;r=(u=q4(i))!=null?u:r}const s=n.getFirstBlock(),l=dt(s);if(!l)return;const c=dt(l);if(c&&!t.addPlaceholderToAllCurrentEmptyBlock)return;if(!c){Ls(n,l)&&Kc(n,l,(f=q4(l))!=null?f:o);return}const a=n.getFocusedBlock();!Ls(n,a)||a!==s&&Kc(n,a,r)}function oD(n,t){var r,i;const e=n.getFirstBlock(),o=it(e);Ls(n,e)?(o.setAttribute("data-title-placeholder",(r=t.titlePlaceholder)!=null?r:T.t("placeholder.title")),o.setAttribute("data-title-placeholder-readonly",(i=t.readonlyTitlePlaceholder)!=null?i:"")):(o.removeAttribute("data-title-placeholder"),o.removeAttribute("data-title-placeholder-readonly"))}function rD(n){n.rootContainer.querySelectorAll("[data-content-placeholder").forEach(t=>{t.removeAttribute("data-content-placeholder")}),n.rootContainer.querySelectorAll("[data-type=block-tools] .block-placeholder-container").forEach(t=>{t.remove()})}function iD(n,t){rD(n),n.selection.range.isCollapsed()&&(oD(n,t),nD(n,t))}const xz="",sD=w("enforce-title");class Ms{constructor(t,e={headingLevel:1}){h(this,"handleSelectionChange",t=>{setTimeout(()=>{this.applyPlaceholder(t)})});this.options=e,this.handleChanged(t),this.applyPlaceholder(t),t.addListener("selectionChanged",this.handleSelectionChange)}destroy(t){t.removeListener("selectionChanged",this.handleSelectionChange)}handleBeforeKeyDown(t,e){if(!t.selection.range.isSimple())return!1;const{containerId:r,blockIndex:i,offset:s}=t.getTextPosition();if(!Ms.isDocumentTitleBlock(r,i)||!Pn(e,"Enter"))return!1;let l=!1,c=null;Ge(t.rootContainer)===2&&(c=kr(t.rootContainer,1),W(t,c)===0&&(l=!0));const a=t.getFirstBlock();return t.undoManager.runInGroup(()=>{t.breakTextBlock(a,s,{forceInsertAfter:!0}),l&&c&&t.deleteBlock(c)}),!0}handleChanged(t){var e;try{const o=t.doc.getContainerBlocks(U(t.rootContainer));d(sD,o.length>0,"root container is empty");const r=o[0];if(r.type!=="text"||r.heading!==this.options.headingLevel){const i=zn("",{heading:(e=this.options.headingLevel)!=null?e:1});t.insertBlock(U(t.rootContainer),0,i);return}if(o.length>1)return;t.insertTextBlock("",U(t.rootContainer),1,{newRange:t.selection.range.toDocRange()})}finally{this.applyPlaceholder(t)}}handleRemoteChanged(t){setTimeout(()=>{this.applyPlaceholder(t)})}handleUpdateCompositionText(t){this.applyPlaceholder(t)}applyPlaceholder(t){var e,o;!((e=this.options)!=null&&e.titlePlaceholder)&&!((o=this.options)!=null&&o.contentPlaceholder)||iD(t,this.options)}static isDocumentTitleBlock(t,e){return t==="root"&&e===0}}const W4=w("code-dom");function yo(n){return rt(n)==="code"}function G4(n,t,e){e.language?t.setAttribute("data-language",e.language):t.removeAttribute("data-language"),e.nowrap?z(t,"wrap"):A(t,"wrap")}function b1(n){const t=n.closest("div[data-type=editor-block][data-block-type=code]");return d(W4,t,"no parent code block"),d(W4,yo(t),"not a code block"),t}const Jc={plain:{name:"Plain Text",aliases:["txt","text"]},abap:{name:"ABAP",aliases:["abap"]},arduino:{name:"Arduino",aliases:["ino"]},bash:{name:"Bash",aliases:["sh","shell"]},basic:{name:"BASIC",aliases:["bas"]},c:{name:"C",aliases:["c"]},clojure:{name:"Clojure",aliases:["clj"]},cofeescript:{name:"CoffeeScript",aliases:["coffee"]},cpp:{name:"C++",aliases:["cpp","cxx"]},csharp:{name:"C#",aliases:["cs"]},css:{name:"CSS",aliases:["css"]},dart:{name:"Dart",aliases:["dart"]},diff:{name:"Diff",aliases:["diff","patch"]},docker:{name:"Docker",aliases:["dockerfile"]},elixir:{name:"Elixir",aliases:["ex","exs"]},elm:{name:"Elm",aliases:["elm"]},erlang:{name:"Erlang",aliases:["erl"]},flow:{name:"Flow",aliases:["flow"]},fortran:{name:"Fortran",aliases:["f","for","f77","f90"]},fsharp:{name:"F#",aliases:["fsharp"]},gherkin:{name:"Gherkin",aliases:["feature"]},glsl:{name:"GLSL",aliases:["glsl"]},go:{name:"Go",aliases:["go"]},graphql:{name:"GraphQL",aliases:["graphql"]},groovy:{name:"Groovy",aliases:["groovy"]},haskell:{name:"Haskell",aliases:["hs"]},java:{name:"Java",aliases:["java"]},js:{name:"JavaScript",aliases:["js","jsx"]},json:{name:"JSON",aliases:["json"]},julia:{name:"Julia",aliases:["jl"]},kotlin:{name:"Kotlin",aliases:["kt","ktm","kts"]},latex:{name:"LaTeX",aliases:["tex"]},less:{name:"LESS",aliases:["less"]},lisp:{name:"Lisp",aliases:["lisp"]},livescript:{name:"LiveScript",aliases:["ls"]},lua:{name:"Lua",aliases:["lua"]},makefile:{name:"Makefile",aliases:["mk","mak"]},markdown:{name:"Markdown",aliases:["md","mkdown","mkd"]},markup:{name:"HTML / XML",aliases:["html","htm","xml","xsd","xsl","xslt","wsdl"]},matlab:{name:"MATLAB",aliases:["matlab"]},mermaid:{name:"Mermaid",aliases:["mermaid"]},nix:{name:"Nix",aliases:["nix"]},objectivec:{name:"Objective-C",aliases:["m","mm"]},ocaml:{name:"OCaml",aliases:["ml"]},pascal:{name:"Pascal",aliases:["pas"]},perl:{name:"Perl",aliases:["pl","pm"]},php:{name:"PHP",aliases:["php"]},powershell:{name:"PowerShell",aliases:["ps","ps1"]},prolog:{name:"Prolog",aliases:["plg"]},protobuf:{name:"Protocol Buffers",aliases:["proto"]},python:{name:"Python",aliases:["py"]},r:{name:"R",aliases:["r"]},reason:{name:"Reason",aliases:["re","rei"]},ruby:{name:"Ruby",aliases:["rb"]},rust:{name:"Rust",aliases:["rs"]},sass:{name:"Sass",aliases:["sass"]},scala:{name:"Scala",aliases:["scala"]},scheme:{name:"Scheme",aliases:["scm","sm"]},scss:{name:"SCSS",aliases:["scss"]},solidity:{name:"Solidity",aliases:["sol"]},sql:{name:"SQL",aliases:["sql"]},swift:{name:"Swift",aliases:["swift"]},typescript:{name:"TypeScript",aliases:["ts","tsx"]},vbnet:{name:"VB.Net",aliases:["vbnet"]},verilog:{name:"Verilog",aliases:["v"]},vhdl:{name:"VHDL",aliases:["vhdl"]},"visual-basic":{name:"Visual Basic",aliases:["vb","vba"]},wasm:{name:"WebAssembly",aliases:["wasm"]},yaml:{name:"YAML",aliases:["yaml"]}};function lD(n){const t=n.toLocaleLowerCase();let e="plain";return Object.entries(Jc).forEach(([o,r])=>{(o===t||r.aliases.includes(t)||r.name.toLocaleLowerCase()===t)&&(e=o)}),e}const cD=w("convert-to-code");function aD(n,t){if(!j(n,t))return null;const e={id:N(),type:"text",text:[]},o=N();n.doc.localInsertChildContainer(o,[e]);const r=n.getBlockData(t).text;d(cD,r,"no text");let i=vt(r);i.startsWith("```")&&(i=i.substring(3));const s=lD(i);return{blockData:{id:N(),type:"code",language:s,children:[o]},focusBlockId:e.id}}const Tz="",v1=w("code-block-child-container");function ti(n){d(v1,yo(n),"not a code block");const e=it(n).querySelector(":scope > div.editor-code-root > div.code-text-root [data-type=editor-container].child");return d(v1,e,"no code text container"),e}function ei(n){d(v1,yo(n),"not a code block");const e=it(n).querySelector(":scope > div.editor-code-root > div.code-caption-root [data-type=editor-container].child");return e||null}function Xc(n){const t=[ti(n)],e=ei(n);return e&&t.push(e),t}function ni(n){const t=H(n),e=F(t);return e?yo(e)?t===ti(e):rt(n)==="code":!1}const k1=w("code-caption");function dD(n,t){if(n.readonly)return;const e=ei(t);if(e){const c=Vt(e);n.selection.selectBlock(c,0);return}const o=yn(n.doc),r=n.getBlockData(t);d(k1,r.children.length===1,"code block should have only one child");const i={...r,children:[r.children[0],o]};n.updateBlockData(t,i);const s=n.getContainerById(o),l=Vt(s);n.selection.selectBlock(l,0)}function Z4(n,t){const e=H(t);if(pt(e))return!1;const o=F(e);if(d(k1,o,"no parent block"),!yo(o))return!1;const i=ei(o);return e===i}function uD(n,t){if(n.readonly||!ei(t))return;const o=ti(t),r=Qt(o);n.selection.selectBlock(r,W(n,r));const i=n.getBlockData(t);d(k1,i.children.length===2,"code block should have only one child");const s=i.children[1],l={...i,children:[i.children[0]]};n.updateBlockData(t,l),n.deleteChildContainers([s])}const hD=w("paste-in-table-block");class fD{constructor(t){this.editor=t,setTimeout(()=>{t.input.addHandler(this)})}destroy(){}async handleBeforePaste(t,e,o){if(!t.selection.range.isSimple())return!1;const r=t.selection.range.start,i=t.getBlockById(r.blockId),s=H(i);if(pt(s))return!1;const l=F(s);if(d(hD,l,"no parent block"),!yo(l)||Z4(t,i))return!1;const c=o["text/plain"];return c&&t.undoManager.runInGroup(()=>{t.clearSelectedContents(),t.insertDoc(i,r.offset,c)}),!0}}function mD(n){n.addCustom("code-block-paste-event",t=>new fD(t))}class gD{constructor(t){h(this,"id","CodeBlockCommandProvider");setTimeout(()=>{t.editorCommandProviders.registerCommandProvider(this)})}destroy(){}getAvailableCommands(){return[]}executeCommand(){return!1}filterCommands(t,e,o,r){if(ni(e))return[]}beforeExecuteCommand(t,e,o,r,i){return!!ni(e)}}function pD(n){n.addCustom("code-block-command-provider",t=>new gD(t))}const CD=w("code-caption-input-handler");function y1(n){if(!n.selection.range.isSimple())return null;const t=n.selection.range.start;if(!t.isSimple())return null;const e=n.getBlockById(t.blockId);return Z4(n,e)?e:null}function bD(n){const t=y1(n);if(!t)return!1;const e=b1(t),o=dt(e);return o?(n.selection.selectBlock(o,0),!0):(n.insertTextBlock("",U(H(e)),J(e)+1),!0)}function vD(n){const t=y1(n);if(!t)return!1;if(Tt(n,t)){const e=b1(t);return uD(n,e),!0}return!1}class w1{constructor(t){setTimeout(()=>{t.input.addHandler(this)})}destroy(){}handleBeforeKeyDown(t,e){return e.key==="Enter"?bD(t):e.key==="Backspace"?vD(t):!1}async handleBeforePaste(t,e,o){const r=y1(t);if(!r)return!1;const i=o["text/plain"];if(!i)return!0;const s=Wl(t,i);return s&&t.undoManager.runInGroup(()=>{t.clearSelectedContents();const l=t.selection.range.start;d(CD,l.isSimple(),"not simple position"),t.insertTextToBlock(r,l.offset,s)}),!0}static init(t){t.addCustom("code-block-caption-input-handler",e=>new w1(e))}}const kD=`
376
+ </svg>`,u1=w("webpage");class gS{constructor(t,e){h(this,"currentSrc","");h(this,"loading",null);h(this,"handleMaskMouseMove",(t,e)=>{if(!window.isDragging){if(e.target&&e.target instanceof Element){const o=e.target.closest("webpage-mask");o&&(o.style.display="none")}t.domEvents.addEventListener(document,"mousemove",this.handleDocumentMouseMove)}});h(this,"handleDocumentMouseMove",(t,e)=>{if(!e.target||!(e.target instanceof Element))return;const o=this.editor.findBlockById(this.blockData.id);if(o){const r=this.getExistsMask(o);if(r){if(It(o,e.target)){r.style.display="none";return}r.style.display=""}}});this.editor=t,this.blockData=e}create(t,e,o,r){const i=e.src,s=b("div",["editor-embed"],null),l=b("iframe",["editor-preview-iframe"],s);this.loading=this.createLoading(s);const c=()=>{d(u1,this.loading,"not created"),this.loading.hide(),this.currentSrc=i};t.domEvents.addEventListener(l,"load",c),l.src=i,this.loading.show(),o.append(s),this.createMask(t,r)}update(t,e,o){if(d(u1,this.loading,"not created"),this.currentSrc===o.src)return;const r=e.querySelector(".editor-preview-iframe");d(u1,r,"no exists iframe"),this.loading.show(),r.src=o.src,this.createMask(t,e)}createLoading(t){const e=b("div",["editor-preview-iframe-loading"],null),o=b("span",[],e);return o.innerHTML=mS,{show(){t.append(e)},hide(){const r=t.querySelector(":scope > .editor-preview-iframe-loading");!r||r.remove()}}}getExistsMask(t){return Rt(t).querySelector(".webpage-mask")}createMask(t,e){const o=Rt(e);let r=this.getExistsMask(e);if(r){r.style.display="";return}r=b("div",["webpage-mask"],o),t.domEvents.addEventListener(r,"mousemove",this.handleMaskMouseMove)}destroy(){const t=this.editor.findBlockById(this.blockData.id);if(t){const e=this.getExistsMask(t);e&&(this.editor.domEvents.removeEventListener(e,"mousemove",this.handleMaskMouseMove),this.editor.domEvents.removeEventListener(document,"mousemove",this.handleDocumentMouseMove))}}}function pS(n,t){b("div",["resize-gripper",t],n).setAttribute("data-resize-type",t)}function h1(n){return Rt(n).querySelector(".block-resizer")}function CS(n){const t=h1(n);t&&z(t,"active")}function P4(n,t,e){const o=n.getBoundingClientRect(),r=t.getBoundingClientRect(),i=r.top-o.top,s=r.left-o.left,l=r.width,c=r.height;e.style.top=`${i}px`,e.style.left=`${s}px`,e.style.width=`${l}px`,e.style.height=`${c}px`}function bS(n,t,e,o){const r=h1(n);if(r)return A(r,"active"),P4(n,t,r),r;const i=Rt(n),s=b("div",["block-resizer"],i);return P4(n,t,s),e.resize.forEach(l=>{pS(s,l)}),s.addEventListener("mousedown",o),A(s,"active"),s}function j4(n,t){const e=h1(n);if(!e)return;const o=n.getBoundingClientRect(),r=t.getBoundingClientRect(),i=r.top-o.top,s=r.left-o.left,l=r.width,c=r.height;e.style.top=`${i}px`,e.style.left=`${s}px`,e.style.width=`${l}px`,e.style.height=`${c}px`}const yz="",vS=w("block-resizer");class Yc extends Yt.TypedEmitter{constructor(e,o){super();h(this,"resizableElement");h(this,"block",null);h(this,"startRect",null);h(this,"startPos",null);h(this,"resizeType",null);h(this,"enabled",!1);h(this,"handleMouseDown",e=>{e.preventDefault(),e.stopPropagation();const o=this.getResizableElement();if(!o||e.button!==0)return;const r=e.target;if(!r||!(r instanceof HTMLElement))return;const i=r.getAttribute("data-resize-type");!i||(this.bindEvents(),this.startRect=o.getBoundingClientRect(),this.startPos=e,this.resizeType=i,Li(window.getComputedStyle(r).cursor),this.block&&this.editor.selection.selectBlock(this.block,0))});h(this,"handleMouseMove",e=>{if(!this.startPos||!this.startRect||!this.resizeType)return;const o=this.getResizableElement();if(!o||!this.block)return;const r=e.x-this.startPos.x,i=e.y-this.startPos.y,s=this.startRect;let{top:l,left:c,right:a,bottom:u}=s;(this.resizeType==="bottom"||this.resizeType==="bottom-left"||this.resizeType==="bottom-right")&&(u+=i),(this.resizeType==="top"||this.resizeType==="top-left"||this.resizeType==="top-right")&&(l+=i),(this.resizeType==="left"||this.resizeType==="top-left"||this.resizeType==="bottom-left")&&(c+=r),(this.resizeType==="right"||this.resizeType==="top-right"||this.resizeType==="bottom-right")&&(a+=r);const f=a>c?a-c:0,m=u>l?u-l:0,C=new DOMRect(c,l,f,m);this.emit("resizing",this,C),j4(this.block,o)});h(this,"handleMouseUp",e=>{if(e.button!==0)return;Li(""),this.unbindEvents(),this.emit("resized",this);const o=this.getResizableElement();!o||!this.block||j4(this.block,o)});this.editor=e,this.options=o}enableResize(e,o){this.block=e,this.resizableElement=o,this.createResizer(),this.enabled=!0}disableResize(){!this.block||(CS(this.block),this.enabled=!1)}update(e,o){this.block=e,this.resizableElement=o,this.getResizableElement()&&this.enabled&&this.createResizer()}getBlock(){return this.block}destroy(){}getResizableElement(){return this.resizableElement?this.resizableElement:this.block?it(this.block):null}createResizer(){const e=this.getResizableElement();!e||!this.block||(d(vS,It(this.block,e),"not a block child element"),bS(this.block,e,this.options,this.handleMouseDown))}bindEvents(){document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("mouseup",this.handleMouseUp)}unbindEvents(){document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp)}}function H4(n){return n&&Te(n)&&Oe(n)==="webpage"}const kS=1e3,yS=100;class wS{constructor(t){h(this,"currentBlockElement",null);h(this,"resizing",!1);h(this,"handleHoveringBlockChange",(t,e)=>{this.resizing||!this.editor.isWritable()||(e&&H4(e)&&this.disableBlockResize(e),t&&H4(t)&&this.enableBlockResize(t))});h(this,"handleResizing",(t,e)=>{this.resizing=!0;const o=t.getBlock();if(!o)return;const r=Math.max(Math.min(e.height,kS),yS);o.style.height=`${r}px`,A(o,"resizing")});h(this,"handleResized",t=>{this.resizing=!1;const e=t.getBlock();if(!e)return;z(e,"resizing");const o=this.editor.getBlockData(e),r=e.getBoundingClientRect().height;this.editor.updateBlockData(e,{...o,height:r})});this.editor=t,Nt.get(t).addListener("change",this.handleHoveringBlockChange)}destroy(){this.currentBlockElement=null,Nt.get(this.editor).removeListener("change",this.handleHoveringBlockChange)}disableBlockResize(t){const e=this.editor.findCustom(`${q(t)}-resizer`);e&&e.disableResize()}enableBlockResize(t){const e=this.editor.addCustom(`${q(t)}-resizer`,()=>new Yc(this.editor,{resize:["bottom"]}));e.enableResize(t),e.removeListener("resizing",this.handleResizing),e.removeListener("resized",this.handleResized),e.addListener("resizing",this.handleResizing),e.addListener("resized",this.handleResized),this.currentBlockElement=t}}const wz="",BS=w("editor-dialog");function ES(n,t){const e=b("div",["editor-dialog-container"],null),o=b("div",["dialog-header"],e);b("span",["dialog-header-title"],o,t.title);const r=b("span",["close-icon"],o);r.innerHTML=Y2,b("div",["dialog-content"],e).appendChild(n);const s=b("div",["dialog-footer"],e);return b("button",["cancel-button"],s,"Cancel"),b("button",["submit-button"],s,"Ok"),e}class IS extends bc{constructor(e,o){super(ES(e,o),o);h(this,"_options");h(this,"getReferenceClientRect",()=>{const e=document.documentElement.clientHeight/2,o=document.documentElement.clientWidth/2,r=this.getCommandBarRoot();d(BS,r,"no command bar root");const{width:i,height:s}=r.getBoundingClientRect();return new DOMRect(Math.max(o-i/2,0),Math.max(e-s/2,0),0,0)});h(this,"handleOk",async()=>{var e,o;try{await((o=(e=this._options).onOk)==null?void 0:o.call(e)),this.destroy()}catch{}});h(this,"handleClose",()=>{var e,o;(o=(e=this._options).onClose)==null||o.call(e),this.destroy()});const r=this.content.querySelector(".submit-button"),i=this.content.querySelector(".cancel-button"),s=this.content.querySelector(".close-icon");r==null||r.addEventListener("click",this.handleOk),s==null||s.addEventListener("click",this.handleClose),i==null||i.addEventListener("click",this.handleClose),this._options=o}show(){super.show(document.documentElement,{getReferenceClientRect:this.getReferenceClientRect})}destroy(){const e=this.content.querySelector(".submit-button"),o=this.content.querySelector(".cancel-button"),r=this.content.querySelector(".close-icon");e==null||e.removeEventListener("click",this.handleOk),o==null||o.removeEventListener("click",this.handleClose),r==null||r.removeEventListener("click",this.handleClose),super.destroy()}}const F4=()=>[{name:T.t("webpage.bilibili"),id:"insert-bilibili",icon:Qw,group:"thirdParty",subText:fe("insert-bilibili")},{name:T.t("webpage.youku"),id:"insert-youku",icon:Kw,group:"thirdParty",subText:fe("insert-youku")},{name:T.t("webpage.figma"),id:"insert-figma",icon:Jw,group:"thirdParty",subText:fe("insert-figma")},{name:T.t("webpage.modao"),id:"insert-modao",icon:Xw,group:"thirdParty",subText:fe("insert-modao")},{name:T.t("webpage.tencent"),id:"insert-tencent",icon:tB,group:"thirdParty",subText:fe("insert-tencent")},{id:"insert-webPage",name:T.t("webpage.title"),icon:eB,group:"common",order:1e3,subText:fe("insert-webPage")}];function f1(n){return n==="insert-webPage"}async function xS(n,t){return n.doc.externalDoc.recognizeLink?n.doc.externalDoc.recognizeLink(t):null}function TS(n){return n&&!n.startsWith("http://")&&!n.startsWith("https://")&&!n.startsWith("//")?`//${n}`:n}async function SS(n){if(!n)throw new Error(T.t("webpage.dialog.errorEnterUrl"));let t=n;t.startsWith("//")&&(t=`http:${t}`);try{new URL(t)}catch{throw new Error(T.t("webpage.dialog.unsupportedUrl"))}}async function DS(n,t){const e=t.item.id,o=F4().find(a=>a.id===e),r=b("div",["webpage-content"],null);if(f1(e)){const a=b("div",["help-container"],r),u=b("div",["help-content"],a),f=b("span",["help-icon"],u);f.innerHTML=X2,b("span",[],u,T.t("webpage.dialog.helpContent"))}const{getInputValue:i,setFieldError:s,focus:l,getField:c}=uh(r,{required:!0,label:T.t("webpage.dialog.label"),placeholder:T.t("webpage.dialog.placeholder")});if(!f1(e)){const a=b("div",["help-link-container"],r),u=b("a",["help-link-content"],a);b("span",[],u,T.t("webpage.dialog.helpLink"));const f=b("span",["help-link-icon"],u);f.innerHTML=e5;const m=n.getComponentOptions("webpage");u.href=(m==null?void 0:m.helpLink)||"",u.target="_blank"}try{const a=await new Promise((m,C)=>{const v=new IS(r,{title:T.t("webpage.dialog.title",{name:(o==null?void 0:o.name)||""}),async onOk(){var S;const y=TS(i());try{await SS(y);const I=await xS(n,y);m((I==null?void 0:I.url)||"")}catch(I){if(((S=I==null?void 0:I.responseData)==null?void 0:S.statusCode)===415)if(f1(e))m(y);else throw s(T.t("webpage.dialog.unsupportedUrl")),I;else throw s(I.message||""),I}},onClose(){n.focus(),C()}});v.addListener("show",l),v.show(),c().addEventListener("keydown",async y=>{if(!y.isComposing){if(y.key==="Enter"){await v.handleOk(),y.preventDefault();return}y.key==="Escape"&&v.handleClose()}})}),u={id:N(),type:"embed",embedType:"webpage",embedData:{src:a}},f=n.insertBlock(t.containerId,t.blockIndex,u);return n.focus(),f}catch{return null}}const z4=w("embed-block-properties");function m1(n,t){var e;for(const o of n.blockHooks){const r=(e=o.commands)==null?void 0:e.call(o,n,t);if(!!r&&r.group==="block-comment-actions")return r.executeCommand(n,t,r.commands[0]),!0}return!1}class g1{constructor(t,e){h(this,"group","hovering-toolbar");h(this,"_commands",[{id:"edit",name:"Edit",icon:ah},{id:"add-comment",name:"Add Comment",icon:pc}]);this.editor=t,this.properties=e}get commands(){var e,o,r;if(!this.editor.isWritable())return[];const t=(e=this.properties)!=null&&e.presetIds?this._commands.filter(i=>{var s,l;return(l=(s=this.properties)==null?void 0:s.presetIds)==null?void 0:l.includes(i.id)}):[...this._commands];return(r=(o=this.properties)==null?void 0:o.extCommands)!=null&&r.length&&(t.push({id:N(),type:"separator",name:""}),t.push(...this.properties.extCommands)),t}executeCommand(t,e,o){var r,i;if(!((i=(r=this.properties)==null?void 0:r.handleExecuteCommand)!=null&&i.call(r,t,e,o))){if(o.id==="add-comment"){m1(t,e)||z4.error("failed to add comment to block");return}z4.error(`unknown command: ${JSON.stringify(o)}`),alert(o.id)}}}function p1(n,t,e){return{blockCommands:{"hovering-toolbar":new g1(n,e)}}}function LS(n){const t=n.querySelector(".editor-preview-iframe"),e=t.src;t.src="about:blank";const o=setTimeout(()=>{t.src=e,clearTimeout(o)},300);return!0}function MS(n,t){const e=n.getBlockData(t),{embedData:o}=e,r=o.src;return window.open(r,"_blank"),!0}function RS(n,t){const e=p1(n,t,{presetIds:["add-comment"],extCommands:[{id:"refresh",name:"Refresh page",icon:Gw},{id:"open-page",name:"Open the original page",icon:e5}],handleExecuteCommand:(r,i,s)=>{switch(s.id){case"refresh":return LS(i);case"open-page":return MS(r,i)}return!1}}),o=`[${T.t("webpage.abstract")}]`;return{...e,abstract:o}}const AS=w("webpage-embed");function OS(n,t,e,o,r,i){const{embedData:s,id:l}=e,{src:c}=s,a=n.addCustom(`webpage-${l}`,()=>new gS(n,e));d(AS,c,"The src from blockData is invalid "),a.create(n,s,t,i),n.addCustom("webpage-resizer",()=>new wS(n)),e.height&&(i.style.height=`${e.height}px`)}function _S(n,t,e){const{embedData:o,id:r}=e;return n.getCustom(`webpage-${r}`).update(n,t,o),e.height&&(t.style.height=`${e.height}px`),!0}function NS(){return{name:"WebPage",insertEmbedCommandItems:F4(),handleInsertEmptyEmbed:DS}}function $S(n,t,e,o){const i=t.embedData.src;return o==="html"?`<iframe src="${i}" ></iframe>`:o==="markdown"?`[${i}](${i})`:i}const C1={embedType:"webpage",createEmbedContent:OS,getBlockProperties:RS,getOptions:NS,handleUpdateBlock:_S,convertTo:$S},PS={webpage:{title:"\u7F51\u9875",youku:"\u4F18\u9177\u89C6\u9891",modao:"\u58A8\u5200",tencent:"\u817E\u8BAF\u89C6\u9891",bilibili:"Bilibili",figma:"Figma",dialog:{helpContent:"\u56E0\u76EE\u6807\u7F51\u9875\u7684\u9650\u5236\uFF0C\u90E8\u5206\u7F51\u9875\u53EF\u80FD\u65E0\u6CD5\u6210\u529F\u9884\u89C8\u3002",helpLink:"\u5982\u4F55\u83B7\u53D6\u94FE\u63A5",label:"\u7F51\u9875\u5730\u5740",placeholder:"\u8BF7\u8F93\u5165",title:"\u63D2\u5165{name}",errorEnterUrl:"\u8BF7\u8F93\u5165\u7F51\u9875\u5730\u5740",unsupportedUrl:"\u6682\u4E0D\u652F\u6301\u63D2\u5165\u8BE5\u94FE\u63A5\u5185\u5BB9"},abstract:"\u7F51\u9875"}},jS={webpage:{title:"Webpage",youku:"Youku",modao:"Modao",tencent:"Tencent Video",bilibili:"Bilibili",figma:"Figma",dialog:{helpContent:"Due to the limitation of the landing page, some pages may not be previewed successfully.",helpLink:"How to get the URL link",label:"Please enter webpage address",placeholder:"Please enter url",title:"Insert {name}",errorEnterUrl:"Please enter the webpage address",unsupportedUrl:"Unsupported url"},abstract:"Webpage"}};T.mergeLang({"zh-CN":PS,"en-US":jS});const Bz="";function HS(n,t,e,o){var f;const r=n.getBlockByIndex(t,e);if(W(n,r)!==o)return!1;const i=vt(n.getBlockText(r));if(![...i].every(m=>m==="|")||i.length<3||!n.editorBlocks.hasBlock("table"))return!1;const s=n.editorBlocks.getBlockClass("table");if(!s.convertFrom)return!1;const l=s.convertFrom(n,r,{offset:o});if(!l)return!1;const{blockData:c,focusBlockId:a}=l;if(!c)return!1;const u=n.insertBlock(t,e,c,At(n,a!=null?a:c.id,0));return n.deleteBlock(r),(f=l.onConverted)==null||f.call(l,n,u),!0}const FS={mermaid:{blockType:"embed",reg:/^```mermaid$/,data:{embedType:"mermaid"}},flowchart:{blockType:"embed",reg:/^```flowchart$/,data:{embedType:"flowchart"}},plantuml:{blockType:"embed",reg:/^```plantuml$/,data:{embedType:"plantuml"}},code:{blockType:"code",reg:/^```\S+$/},code2:{blockType:"code",reg:/^```$/},table:{blockType:"table",reg:/^\|.+\|.+\|$/},math:{blockType:"embed",reg:/^\$\$.+\$\$$/},image:{blockType:"embed",reg:/^!\[[^\]]*\]\((?<filename>.*?)(?="|\))(?<optionalPart>".*")?\)/,data:{embedType:"image"}},dividing:{blockType:"embed",reg:/^-{3,}$/,data:{embedType:"dividing-line"}},toc:{blockType:"embed",reg:/^\[toc\]/,data:{embedType:"toc"}}},zS={orderedList:{reg:/^(\d)+(\.|。)$/,blockType:"list",data:{listType:"ordered"}},unorderedList1:{reg:/^\*$/,blockType:"list",data:{listType:"unordered"}},unorderedList2:{reg:/^-$/,blockType:"list",data:{listType:"unordered"}},checkList1:{reg:/^\[\s?\]$/,blockType:"list",data:{listType:"unchecked"}},checkList2:{reg:/^\[X\]$/i,blockType:"list",data:{listType:"checked"}},image:{blockType:"embed",reg:/^!\[[^\]]*\]\((?<filename>.*?)(?="|\))(?<optionalPart>".*")?\)/,data:{embedType:"image"}}};function U4(n,t,e,o,r){if(r==="enter"&&HS(n,t,e,o))return!0;const i=n.getBlockByIndex(t,e),s=vt(be(n.getBlockText(i),o).left).trim(),l=r==="enter"?FS:zS;for(const[,c]of Object.entries(l)){if(!s.match(c.reg))continue;return!!n.undoManager.runInGroup(()=>{var v;const u=Oi(n,i,c.blockType,{offset:o,data:c.data});if(!u)return null;const{blockData:f,focusBlockId:m}=u;if(!f)return null;const C=n.insertBlock(t,e,f,At(n,m!=null?m:f.id,0));return n.deleteBlock(i),(v=u.onConverted)==null||v.call(u,n,C),{newBlock:C,focusBlockId:m}})}return!1}function US(n,t,e,o){const r=n.getBlockByIndex(t,e);return n.getBlockString(r,{boxReplacement:" "}).substring(0,o)!==">"?!1:(n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,0,o+1),n.updateBlockData(r,{quoted:!0},At(n,r,0))}),!0)}const VS={"#":1,"##":2,"###":3,"####":4,"#####":5,"######":6,"#######":7,"########":8};function qS(n,t,e,o){const r=n.getBlockByIndex(t,e),i=n.getBlockString(r,{boxReplacement:" "}).substring(0,o);let s=VS[i];if(!s)return!1;const l=n.getBlockData(r).heading;return l&&l==s&&(s=null),n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,0,o+1),n.updateBlockData(r,{heading:s},At(n,r,0))}),!0}function WS(n,t,e,o){return!!(qS(n,t,e,o)||US(n,t,e,o))}const GS=w("match-text-style");function ZS(n){let t="";for(let e=n.length-1;e>=0;e--){const o=n[e];if(!o.attributes||Object.keys(o.attributes).length===0){t+=o.insert;continue}break}return t}function YS(n,t){if(n.length<t.length*2+1||!n.endsWith(t)||n.substring(0,n.length-1).endsWith(t))return-1;const e=n.substring(0,n.length-t.length),o=e.lastIndexOf(t);return o===-1?-1:o===0?0:e.substring(o-1).startsWith(t)?-1:o}const QS={"*":{type:"style",styles:["style-italic"],boxType:""},"**":{type:"style",styles:["style-bold"],boxType:""},"***":{type:"style",styles:["style-bold","style-italic"],boxType:""},"~~":{type:"style",styles:["style-strikethrough"],boxType:""},"`":{type:"style",styles:["style-code"],boxType:""},$$:{type:"box",styles:[],boxType:"math"}};function KS(n,t,e,o){var u,f;const r=n.getBlockByIndex(t,e),i=n.getBlockText(r),{left:s}=be(i,o),l=ZS(s),c=de(s)-l.length,a=Object.entries(QS);for(const[m,C]of a){const v=YS(l,m);if(v===-1)continue;const B=c+v,y=o,S=m.length,I=vt(Gt(i,B+S,y-B-S*2).middle);if(C.type==="style"){const M={};C.styles.forEach($=>{M[$]=!0});const R=Go(I,M);n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,B,y-B),n.insertTextToBlock(r,B,R)})}else if(C.type==="box")try{const M=(f=(u=n.editorBoxes.getBoxClass(C.boxType)).convertFrom)==null?void 0:f.call(u,n,I);if(!M)continue;n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,B,y-B),n.insertBoxToBlock(r,B,M)})}catch(M){GS.warn(`failed to convert to box, ${M.message}`);continue}return!0}return!1}class Qc{handleAfterInsertText(t,e,o,r,i){return!!(i===" "&&(WS(t,e,o,r)||KS(t,e,o,r)))}handleBeforeKeyDown(t,e){if(!t.selection.range.isSimple())return!1;const{containerId:r,blockIndex:i,offset:s}=t.getTextPosition();if(j(t,t.getBlockByIndex(r,i))){if(jn(e,"Enter")){if(U4(t,r,i,s,"enter"))return!0}else if(jn(e,"Space")&&U4(t,r,i,s,"space"))return!0}return!1}}const JS={"en-US":{placeholder:{default:"Type \u2018/\u2019 for commands",heading:"Heading {heading}",list:"List",mention:"Quickly assign tasks @mention yourself or others",quote:"Quote",title:"Enter document title"}},"zh-CN":{placeholder:{default:"\u8F93\u5165\u300C/\u300D\u5FEB\u901F\u63D2\u5165",heading:"\u6807\u9898{heading}",list:"\u5217\u8868",mention:"\u5FEB\u901F\u5206\u914D\u4EFB\u52A1\uFF0C@\u63D0\u53CA\u81EA\u5DF1\u6216\u4ED6\u4EBA",quote:"\u5F15\u7528",title:"\u8BF7\u8F93\u5165\u6587\u6863\u6807\u9898"}}};T.mergeLang(JS);function Ls(n,t){const e=co(n,t);return!!(e.text&&de(e.text)===0&&!t.querySelector(".inputting-insertion"))}function V4(n,t){var o;it(t).removeAttribute("data-content-placeholder"),(o=t.querySelector("[data-type=block-tools] .block-placeholder-container"))==null||o.remove()}function Kc(n,t,e){var r;if(!Ls(n,t)){V4(n,t);return}const o=it(t);if(typeof e=="string")o.setAttribute("data-content-placeholder",e);else{const i=Rt(t),s=(r=i.querySelector(".block-placeholder-container"))!=null?r:b("div",["block-placeholder-container"],i);s.innerHTML="",s.appendChild(e)}}function XS(n){const t=n.getAttribute("data-style-heading");return t?T.t("placeholder.heading",{heading:t}):n.getAttribute("data-style-quoted")?T.t("placeholder.quote"):null}function tD(n){const t=n.getAttribute("data-list-type");return t?t==="ordered"||t==="unordered"?T.t("placeholder.list"):T.t("placeholder.mention"):null}function q4(n){switch(rt(n)){case"text":return XS(n);case"list":return tD(n);default:return null}}function eD(n){if(Ko(n))return!1;const t=F(H(n));return t?rt(t)==="code":!1}function nD(n,t){var u,f;const e=rt(n.selection.focusedBlock),o=t.contentPlaceholder||T.t("placeholder.default");let r=o;const i=n.selection.focusedBlock;if(e&&_i(n,e)&&i){if(eD(i))return;r=(u=q4(i))!=null?u:r}const s=n.getFirstBlock(),l=dt(s);if(!l)return;const c=dt(l);if(c&&!t.addPlaceholderToAllCurrentEmptyBlock)return;if(!c){Ls(n,l)&&Kc(n,l,(f=q4(l))!=null?f:o);return}const a=n.getFocusedBlock();!Ls(n,a)||a!==s&&Kc(n,a,r)}function oD(n,t){var r,i;const e=n.getFirstBlock(),o=it(e);Ls(n,e)?(o.setAttribute("data-title-placeholder",(r=t.titlePlaceholder)!=null?r:T.t("placeholder.title")),o.setAttribute("data-title-placeholder-readonly",(i=t.readonlyTitlePlaceholder)!=null?i:"")):(o.removeAttribute("data-title-placeholder"),o.removeAttribute("data-title-placeholder-readonly"))}function rD(n){n.rootContainer.querySelectorAll("[data-content-placeholder").forEach(t=>{t.removeAttribute("data-content-placeholder")}),n.rootContainer.querySelectorAll("[data-type=block-tools] .block-placeholder-container").forEach(t=>{t.remove()})}function iD(n,t){rD(n),n.selection.range.isCollapsed()&&(oD(n,t),nD(n,t))}const xz="",sD=w("enforce-title");class Ms{constructor(t,e={headingLevel:1}){h(this,"handleSelectionChange",t=>{setTimeout(()=>{this.applyPlaceholder(t)})});this.options=e,this.handleChanged(t),this.applyPlaceholder(t),t.addListener("selectionChanged",this.handleSelectionChange)}destroy(t){t.removeListener("selectionChanged",this.handleSelectionChange)}handleBeforeKeyDown(t,e){if(!t.selection.range.isSimple())return!1;const{containerId:r,blockIndex:i,offset:s}=t.getTextPosition();if(!Ms.isDocumentTitleBlock(r,i)||!jn(e,"Enter"))return!1;let l=!1,c=null;Ge(t.rootContainer)===2&&(c=kr(t.rootContainer,1),W(t,c)===0&&(l=!0));const a=t.getFirstBlock();return t.undoManager.runInGroup(()=>{t.breakTextBlock(a,s,{forceInsertAfter:!0}),l&&c&&t.deleteBlock(c)}),!0}handleChanged(t){var e;try{const o=t.doc.getContainerBlocks(U(t.rootContainer));d(sD,o.length>0,"root container is empty");const r=o[0];if(r.type!=="text"||r.heading!==this.options.headingLevel){const i=Un("",{heading:(e=this.options.headingLevel)!=null?e:1});t.insertBlock(U(t.rootContainer),0,i);return}if(o.length>1)return;t.insertTextBlock("",U(t.rootContainer),1,{newRange:t.selection.range.toDocRange()})}finally{this.applyPlaceholder(t)}}handleRemoteChanged(t){setTimeout(()=>{this.applyPlaceholder(t)})}handleUpdateCompositionText(t){this.applyPlaceholder(t)}applyPlaceholder(t){var e,o;!((e=this.options)!=null&&e.titlePlaceholder)&&!((o=this.options)!=null&&o.contentPlaceholder)||iD(t,this.options)}static isDocumentTitleBlock(t,e){return t==="root"&&e===0}}const W4=w("code-dom");function yo(n){return rt(n)==="code"}function G4(n,t,e){e.language?t.setAttribute("data-language",e.language):t.removeAttribute("data-language"),e.nowrap?z(t,"wrap"):A(t,"wrap")}function b1(n){const t=n.closest("div[data-type=editor-block][data-block-type=code]");return d(W4,t,"no parent code block"),d(W4,yo(t),"not a code block"),t}const Jc={plain:{name:"Plain Text",aliases:["txt","text"]},abap:{name:"ABAP",aliases:["abap"]},arduino:{name:"Arduino",aliases:["ino"]},bash:{name:"Bash",aliases:["sh","shell"]},basic:{name:"BASIC",aliases:["bas"]},c:{name:"C",aliases:["c"]},clojure:{name:"Clojure",aliases:["clj"]},cofeescript:{name:"CoffeeScript",aliases:["coffee"]},cpp:{name:"C++",aliases:["cpp","cxx"]},csharp:{name:"C#",aliases:["cs"]},css:{name:"CSS",aliases:["css"]},dart:{name:"Dart",aliases:["dart"]},diff:{name:"Diff",aliases:["diff","patch"]},docker:{name:"Docker",aliases:["dockerfile"]},elixir:{name:"Elixir",aliases:["ex","exs"]},elm:{name:"Elm",aliases:["elm"]},erlang:{name:"Erlang",aliases:["erl"]},flow:{name:"Flow",aliases:["flow"]},fortran:{name:"Fortran",aliases:["f","for","f77","f90"]},fsharp:{name:"F#",aliases:["fsharp"]},gherkin:{name:"Gherkin",aliases:["feature"]},glsl:{name:"GLSL",aliases:["glsl"]},go:{name:"Go",aliases:["go"]},graphql:{name:"GraphQL",aliases:["graphql"]},groovy:{name:"Groovy",aliases:["groovy"]},haskell:{name:"Haskell",aliases:["hs"]},java:{name:"Java",aliases:["java"]},js:{name:"JavaScript",aliases:["js","jsx"]},json:{name:"JSON",aliases:["json"]},julia:{name:"Julia",aliases:["jl"]},kotlin:{name:"Kotlin",aliases:["kt","ktm","kts"]},latex:{name:"LaTeX",aliases:["tex"]},less:{name:"LESS",aliases:["less"]},lisp:{name:"Lisp",aliases:["lisp"]},livescript:{name:"LiveScript",aliases:["ls"]},lua:{name:"Lua",aliases:["lua"]},makefile:{name:"Makefile",aliases:["mk","mak"]},markdown:{name:"Markdown",aliases:["md","mkdown","mkd"]},markup:{name:"HTML / XML",aliases:["html","htm","xml","xsd","xsl","xslt","wsdl"]},matlab:{name:"MATLAB",aliases:["matlab"]},mermaid:{name:"Mermaid",aliases:["mermaid"]},nix:{name:"Nix",aliases:["nix"]},objectivec:{name:"Objective-C",aliases:["m","mm"]},ocaml:{name:"OCaml",aliases:["ml"]},pascal:{name:"Pascal",aliases:["pas"]},perl:{name:"Perl",aliases:["pl","pm"]},php:{name:"PHP",aliases:["php"]},powershell:{name:"PowerShell",aliases:["ps","ps1"]},prolog:{name:"Prolog",aliases:["plg"]},protobuf:{name:"Protocol Buffers",aliases:["proto"]},python:{name:"Python",aliases:["py"]},r:{name:"R",aliases:["r"]},reason:{name:"Reason",aliases:["re","rei"]},ruby:{name:"Ruby",aliases:["rb"]},rust:{name:"Rust",aliases:["rs"]},sass:{name:"Sass",aliases:["sass"]},scala:{name:"Scala",aliases:["scala"]},scheme:{name:"Scheme",aliases:["scm","sm"]},scss:{name:"SCSS",aliases:["scss"]},solidity:{name:"Solidity",aliases:["sol"]},sql:{name:"SQL",aliases:["sql"]},swift:{name:"Swift",aliases:["swift"]},typescript:{name:"TypeScript",aliases:["ts","tsx"]},vbnet:{name:"VB.Net",aliases:["vbnet"]},verilog:{name:"Verilog",aliases:["v"]},vhdl:{name:"VHDL",aliases:["vhdl"]},"visual-basic":{name:"Visual Basic",aliases:["vb","vba"]},wasm:{name:"WebAssembly",aliases:["wasm"]},yaml:{name:"YAML",aliases:["yaml"]}};function lD(n){const t=n.toLocaleLowerCase();let e="plain";return Object.entries(Jc).forEach(([o,r])=>{(o===t||r.aliases.includes(t)||r.name.toLocaleLowerCase()===t)&&(e=o)}),e}const cD=w("convert-to-code");function aD(n,t){if(!j(n,t))return null;const e={id:N(),type:"text",text:[]},o=N();n.doc.localInsertChildContainer(o,[e]);const r=n.getBlockData(t).text;d(cD,r,"no text");let i=vt(r);i.startsWith("```")&&(i=i.substring(3));const s=lD(i);return{blockData:{id:N(),type:"code",language:s,children:[o]},focusBlockId:e.id}}const Tz="",v1=w("code-block-child-container");function ti(n){d(v1,yo(n),"not a code block");const e=it(n).querySelector(":scope > div.editor-code-root > div.code-text-root [data-type=editor-container].child");return d(v1,e,"no code text container"),e}function ei(n){d(v1,yo(n),"not a code block");const e=it(n).querySelector(":scope > div.editor-code-root > div.code-caption-root [data-type=editor-container].child");return e||null}function Xc(n){const t=[ti(n)],e=ei(n);return e&&t.push(e),t}function ni(n){const t=H(n),e=F(t);return e?yo(e)?t===ti(e):rt(n)==="code":!1}const k1=w("code-caption");function dD(n,t){if(n.readonly)return;const e=ei(t);if(e){const c=Vt(e);n.selection.selectBlock(c,0);return}const o=yn(n.doc),r=n.getBlockData(t);d(k1,r.children.length===1,"code block should have only one child");const i={...r,children:[r.children[0],o]};n.updateBlockData(t,i);const s=n.getContainerById(o),l=Vt(s);n.selection.selectBlock(l,0)}function Z4(n,t){const e=H(t);if(pt(e))return!1;const o=F(e);if(d(k1,o,"no parent block"),!yo(o))return!1;const i=ei(o);return e===i}function uD(n,t){if(n.readonly||!ei(t))return;const o=ti(t),r=Qt(o);n.selection.selectBlock(r,W(n,r));const i=n.getBlockData(t);d(k1,i.children.length===2,"code block should have only one child");const s=i.children[1],l={...i,children:[i.children[0]]};n.updateBlockData(t,l),n.deleteChildContainers([s])}const hD=w("paste-in-table-block");class fD{constructor(t){this.editor=t,setTimeout(()=>{t.input.addHandler(this)})}destroy(){}async handleBeforePaste(t,e,o){if(!t.selection.range.isSimple())return!1;const r=t.selection.range.start,i=t.getBlockById(r.blockId),s=H(i);if(pt(s))return!1;const l=F(s);if(d(hD,l,"no parent block"),!yo(l)||Z4(t,i))return!1;const c=o["text/plain"];return c&&t.undoManager.runInGroup(()=>{t.clearSelectedContents(),t.insertDoc(i,r.offset,c)}),!0}}function mD(n){n.addCustom("code-block-paste-event",t=>new fD(t))}class gD{constructor(t){h(this,"id","CodeBlockCommandProvider");setTimeout(()=>{t.editorCommandProviders.registerCommandProvider(this)})}destroy(){}getAvailableCommands(){return[]}executeCommand(){return!1}filterCommands(t,e,o,r){if(ni(e))return[]}beforeExecuteCommand(t,e,o,r,i){return!!ni(e)}}function pD(n){n.addCustom("code-block-command-provider",t=>new gD(t))}const CD=w("code-caption-input-handler");function y1(n){if(!n.selection.range.isSimple())return null;const t=n.selection.range.start;if(!t.isSimple())return null;const e=n.getBlockById(t.blockId);return Z4(n,e)?e:null}function bD(n){const t=y1(n);if(!t)return!1;const e=b1(t),o=dt(e);return o?(n.selection.selectBlock(o,0),!0):(n.insertTextBlock("",U(H(e)),J(e)+1),!0)}function vD(n){const t=y1(n);if(!t)return!1;if(Tt(n,t)){const e=b1(t);return uD(n,e),!0}return!1}class w1{constructor(t){setTimeout(()=>{t.input.addHandler(this)})}destroy(){}handleBeforeKeyDown(t,e){return e.key==="Enter"?bD(t):e.key==="Backspace"?vD(t):!1}async handleBeforePaste(t,e,o){const r=y1(t);if(!r)return!1;const i=o["text/plain"];if(!i)return!0;const s=Wl(t,i);return s&&t.undoManager.runInGroup(()=>{t.clearSelectedContents();const l=t.selection.range.start;d(CD,l.isSimple(),"not simple position"),t.insertTextToBlock(r,l.offset,s)}),!0}static init(t){t.addCustom("code-block-caption-input-handler",e=>new w1(e))}}const kD=`
377
377
  <svg fill="currentColor" focusable="false" viewBox="0 0 24 24" aria-hidden="true" tabindex="-1">
378
378
  <path d="M8.12 9.29 12 13.17l3.88-3.88c.39-.39 1.02-.39 1.41 0 .39.39.39 1.02 0 1.41l-4.59 4.59c-.39.39-1.02.39-1.41 0L6.7 10.7a.9959.9959 0 0 1 0-1.41c.39-.38 1.03-.39 1.42 0z"></path>
379
379
  </svg>`,yD=`
@@ -384,7 +384,7 @@ $$${r.mathjaxText}$$
384
384
  <svg focusable="false" viewBox="0 0 24 24" aria-hidden="true" tabindex="-1">
385
385
  <path fill="currentColor" d="M4 19h6v-2H4v2zM20 5H4v2h16V5zm-3 6H4v2h13.25c1.1 0 2 .9 2 2s-.9 2-2 2H15v-2l-3 3 3 3v-2h2c2.21 0 4-1.79 4-4s-1.79-4-4-4z"></path>
386
386
  </svg>
387
- `;function BD(n,t,e){const r={...n.getBlockData(t),language:e};n.updateBlockData(t,r),Se(n,t).forEach(s=>{Mt(s).forEach(l=>{n.reloadBlock(l)})})}function ED(n,t,e){const r={...n.getBlockData(t),nowrap:e};n.updateBlockData(t,r)}async function ID(n){const t=await n.settingsProvider.getItem("editor-code-lang");return t!=null?t:"plain"}async function xD(n,t){return n.settingsProvider.setItem("editor-code-lang",t)}const lr=w("code-block-header"),TD=Object.entries(Jc).map(([n,t])=>({id:n,name:t.name,language:t}));function Y4(n,t,e){d(lr,yo(t),"not a code block");const o=Vt(ti(t));n.selection.selectBlock(o,0),e.focusToEditor&&n.focus()}function SD(n,t){if(t){const e=n,{editor:o,codeBlock:r}=e.custom;BD(o,r,t.id);const i=r.querySelector(".code-block-header .language-select .name-label");i.innerText=t.name,xD(o,t.id),o.focus()}}function DD(n,t,e){n.addCustom("code-header-language-select-dropdown",i=>{const s=new Tw(TD,i.rootElement,{placeholder:"Search for a language..."});return s.onSelected=SD,s});const o=b("div",["language-select"],null);b("span",["name-label"],o,e);const r=b("span",["arrow-icon"],o);return r.innerHTML=kD,n.domEvents.addEventListener(o,"click",(i,s)=>{const c=s.target.closest(".language-select"),a=F(c);d(lr,a,"no parent block"),d(lr,rt(a)==="code","not a code block");const u=i.getBlockData(a),f=i.getCustom("code-header-language-select-dropdown");f.custom={codeBlock:a,editor:i},f.setSelectedId(u.language),f.show(c),Y4(i,a,{focusToEditor:!1}),A(t,"editing-language"),f.onHide=()=>{z(t,"editing-language")}}),o}function LD(){return b("div",["code-header-spacer"],null)}function MD(n,t){const e=t.target,o=e.closest(".code-header-button");d(lr,o,"no button");const r=F(e);d(lr,r,"no parent block");const i=o.getAttribute("data-id");if(d(lr,rt(r)==="code","not a code block"),i==="wrap"){const s=n.getBlockData(r);ED(n,r,!s.nowrap);return}if(i==="copy"){Y4(n,r,{focusToEditor:!0}),nc(n,r).then(()=>{const s=o.getBoundingClientRect();Sw("Copied to clipboard",{position:{x:s.x+s.width/2,y:s.bottom+30}})}).catch(s=>{lr.error(s.message)});return}i==="caption"&&(dD(n,r),setTimeout(()=>{n.focus()}))}function B1(n,t,e,o){const r=b("button",["code-header-button"],null);if(r.setAttribute("data-id",t),o){const i=b("span",["button-icon"],r);i.innerHTML=o}if(e){const i=b("span",["button-label"],r);i.innerHTML=e}return n.domEvents.addEventListener(r,"click",MD),r}function RD(n,t,e){const o=Rt(t),r=b("div",["code-block-header"],o),i=Jc[e.language]||Jc.plain;r.appendChild(DD(n,t,i.name)),r.appendChild(LD()),r.appendChild(B1(n,"copy","Copy",yD)),r.appendChild(B1(n,"wrap","Wrap",wD)),r.appendChild(B1(n,"caption","Caption",null))}function AD(n,t){!t.target||setTimeout(()=>{n.selection.caret.update()})}function OD(n,t,e,o){w1.init(n);const r=o.children,i=ro(e,"div");i.setAttribute("data-language",o.language||"text"),G4(n,e,o);const s=b("div",["editor-code-root"],i),l=b("div",["code-text-root"],s),c=n.createChildContainer(t,l,r[0]);if(r.length===2){const a=b("div",["code-caption-root"],s);n.createChildContainer(t,a,r[1])}return n.domEvents.addEventListener(c,"scroll",AD),RD(n,e,o),i}async function _D(n){const t={id:N(),type:"text",text:[]},e=N();n.doc.localInsertChildContainer(e,[t]);const o=await ID(n);return{blockData:{id:N(),type:"code",language:o,children:[e]},focusBlockId:t.id}}const Sn=w("list-block");function ND(n,t,e,o,r){mD(n),pD(n),d(Sn,r.type==="code","invalid block data type");const i=r;return d(Sn,i.children,"invalid block data children"),d(Sn,i.children.length===1||i.children.length===2,"invalid block data children length"),OD(n,t,o,i)}function $D(n){return 1}function PD(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t)||!bn(r))return null;const i=Xc(t);if(!bn(r))return null;const s=r;if(i.indexOf(s)===-1||Ge(s)>1)return null;const l=wt(t,U(s));return new Xe(n,{anchor:l,focus:l})}function jD(n,t,e,o){return null}function HD(n,t){return n.getBoundingClientRect()}function FD(n,t,e,o){if(e.isSimple()){d(Sn,o.isSimple(),"from is simple position but to is not simple position"),Sn.debug("full select list"),A(t,"full-selected");return}d(Sn,!o.isSimple(),"from is complex position but end is simple position");const r=e,i=o;d(Sn,r.blockId===i.blockId,"only allow update one table selection"),Xc(t).forEach(l=>{const c=U(l);(c===r.childContainerId||c===i.childContainerId)&&A(l,"selected")})}function zD(n){n.rootContainer.querySelectorAll('[data-type="editor-block"][data-block-type="code"]').forEach(t=>{z(t,"full-selected"),t.querySelectorAll("div[data-type=editor-container].child.selected").forEach(e=>{z(e,"selected")})})}function UD(n,t){return Xc(t)}function VD(n,t,e,o,r){if(o==="ArrowDown"||o==="ArrowRight"){if(e===ti(t))return ei(t)}else if(e===ei(t))return ti(t);return null}function qD(n,t,e,o){const r=Xc(t),i=r.map(U),s=i.indexOf(e.childContainerId),l=i.indexOf(o.childContainerId);d(Sn,s!==-1,"invalid start pos"),d(Sn,l!==-1,"invalid end pos");const c=[r[s]];return s!==l&&c.push(r[l]),c}function WD(n,t,e){d(Sn,yo(t),"invalid block type"),G4(n,t,e)}async function GD(n,t){const e=await _D(n);if(!e)return null;const{blockData:o,focusBlockId:r}=e;return n.insertBlock(t.containerId,t.blockIndex,o,At(n,r,0))}function ZD(n){return{name:"CodeBlock",insertBlockCommandItems:[{id:"insert-code",name:T.t("code.title"),icon:sB,order:300,group:"common",subText:fe("insert-code")}],handleInsertEmptyBlock:GD}}function YD(){return{abstract:`[${T.t("code.abstract")}]`}}function QD(n,t,e,o){const r=t,i=c=>{const a=[];return e.blocks[c].forEach(f=>{var m;a.push(vt((m=f.text)!=null?m:[]))}),a.join(`
387
+ `;function BD(n,t,e){const r={...n.getBlockData(t),language:e};n.updateBlockData(t,r),Se(n,t).forEach(s=>{Mt(s).forEach(l=>{n.reloadBlock(l)})})}function ED(n,t,e){const r={...n.getBlockData(t),nowrap:e};n.updateBlockData(t,r)}async function ID(n){const t=await n.settingsProvider.getItem("editor-code-lang");return t!=null?t:"plain"}async function xD(n,t){return n.settingsProvider.setItem("editor-code-lang",t)}const lr=w("code-block-header"),TD=Object.entries(Jc).map(([n,t])=>({id:n,name:t.name,language:t}));function Y4(n,t,e){d(lr,yo(t),"not a code block");const o=Vt(ti(t));n.selection.selectBlock(o,0),e.focusToEditor&&n.focus()}function SD(n,t){if(t){const e=n,{editor:o,codeBlock:r}=e.custom;BD(o,r,t.id);const i=r.querySelector(".code-block-header .language-select .name-label");i.innerText=t.name,xD(o,t.id),o.focus()}}function DD(n,t,e){n.addCustom("code-header-language-select-dropdown",i=>{const s=new Tw(TD,i.rootElement,{placeholder:"Search for a language..."});return s.onSelected=SD,s});const o=b("div",["language-select"],null);b("span",["name-label"],o,e);const r=b("span",["arrow-icon"],o);return r.innerHTML=kD,n.domEvents.addEventListener(o,"click",(i,s)=>{const c=s.target.closest(".language-select"),a=F(c);d(lr,a,"no parent block"),d(lr,rt(a)==="code","not a code block");const u=i.getBlockData(a),f=i.getCustom("code-header-language-select-dropdown");f.custom={codeBlock:a,editor:i},f.setSelectedId(u.language),f.show(c),Y4(i,a,{focusToEditor:!1}),A(t,"editing-language"),f.onHide=()=>{z(t,"editing-language")}}),o}function LD(){return b("div",["code-header-spacer"],null)}function MD(n,t){const e=t.target,o=e.closest(".code-header-button");d(lr,o,"no button");const r=F(e);d(lr,r,"no parent block");const i=o.getAttribute("data-id");if(d(lr,rt(r)==="code","not a code block"),i==="wrap"){const s=n.getBlockData(r);ED(n,r,!s.nowrap);return}if(i==="copy"){Y4(n,r,{focusToEditor:!0}),nc(n,r).then(()=>{const s=o.getBoundingClientRect();Sw("Copied to clipboard",{position:{x:s.x+s.width/2,y:s.bottom+30}})}).catch(s=>{lr.error(s.message)});return}i==="caption"&&(dD(n,r),setTimeout(()=>{n.focus()}))}function B1(n,t,e,o){const r=b("button",["code-header-button"],null);if(r.setAttribute("data-id",t),o){const i=b("span",["button-icon"],r);i.innerHTML=o}if(e){const i=b("span",["button-label"],r);i.innerHTML=e}return n.domEvents.addEventListener(r,"click",MD),r}function RD(n,t,e){const o=Rt(t),r=b("div",["code-block-header"],o),i=Jc[e.language]||Jc.plain;r.appendChild(DD(n,t,i.name)),r.appendChild(LD()),r.appendChild(B1(n,"copy","Copy",yD)),r.appendChild(B1(n,"wrap","Wrap",wD)),r.appendChild(B1(n,"caption","Caption",null))}function AD(n,t){!t.target||setTimeout(()=>{n.selection.caret.update()})}function OD(n,t,e,o){w1.init(n);const r=o.children,i=ro(e,"div");i.setAttribute("data-language",o.language||"text"),G4(n,e,o);const s=b("div",["editor-code-root"],i),l=b("div",["code-text-root"],s),c=n.createChildContainer(t,l,r[0]);if(r.length===2){const a=b("div",["code-caption-root"],s);n.createChildContainer(t,a,r[1])}return n.domEvents.addEventListener(c,"scroll",AD),RD(n,e,o),i}async function _D(n){const t={id:N(),type:"text",text:[]},e=N();n.doc.localInsertChildContainer(e,[t]);const o=await ID(n);return{blockData:{id:N(),type:"code",language:o,children:[e]},focusBlockId:t.id}}const Dn=w("list-block");function ND(n,t,e,o,r){mD(n),pD(n),d(Dn,r.type==="code","invalid block data type");const i=r;return d(Dn,i.children,"invalid block data children"),d(Dn,i.children.length===1||i.children.length===2,"invalid block data children length"),OD(n,t,o,i)}function $D(n){return 1}function PD(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t)||!bn(r))return null;const i=Xc(t);if(!bn(r))return null;const s=r;if(i.indexOf(s)===-1||Ge(s)>1)return null;const l=wt(t,U(s));return new Xe(n,{anchor:l,focus:l})}function jD(n,t,e,o){return null}function HD(n,t){return n.getBoundingClientRect()}function FD(n,t,e,o){if(e.isSimple()){d(Dn,o.isSimple(),"from is simple position but to is not simple position"),Dn.debug("full select list"),A(t,"full-selected");return}d(Dn,!o.isSimple(),"from is complex position but end is simple position");const r=e,i=o;d(Dn,r.blockId===i.blockId,"only allow update one table selection"),Xc(t).forEach(l=>{const c=U(l);(c===r.childContainerId||c===i.childContainerId)&&A(l,"selected")})}function zD(n){n.rootContainer.querySelectorAll('[data-type="editor-block"][data-block-type="code"]').forEach(t=>{z(t,"full-selected"),t.querySelectorAll("div[data-type=editor-container].child.selected").forEach(e=>{z(e,"selected")})})}function UD(n,t){return Xc(t)}function VD(n,t,e,o,r){if(o==="ArrowDown"||o==="ArrowRight"){if(e===ti(t))return ei(t)}else if(e===ei(t))return ti(t);return null}function qD(n,t,e,o){const r=Xc(t),i=r.map(U),s=i.indexOf(e.childContainerId),l=i.indexOf(o.childContainerId);d(Dn,s!==-1,"invalid start pos"),d(Dn,l!==-1,"invalid end pos");const c=[r[s]];return s!==l&&c.push(r[l]),c}function WD(n,t,e){d(Dn,yo(t),"invalid block type"),G4(n,t,e)}async function GD(n,t){const e=await _D(n);if(!e)return null;const{blockData:o,focusBlockId:r}=e;return n.insertBlock(t.containerId,t.blockIndex,o,At(n,r,0))}function ZD(n){return{name:"CodeBlock",insertBlockCommandItems:[{id:"insert-code",name:T.t("code.title"),icon:sB,order:300,group:"common",subText:fe("insert-code")}],handleInsertEmptyBlock:GD}}function YD(){return{abstract:`[${T.t("code.abstract")}]`}}function QD(n,t,e,o){const r=t,i=c=>{const a=[];return e.blocks[c].forEach(f=>{var m;a.push(vt((m=f.text)!=null?m:[]))}),a.join(`
388
388
  `)},s=i(r.children[0]),l=r.children[1]?i(r.children[1]):"";return o==="text"?`${s}
389
389
  ${l}`:o==="markdown"?`\`\`\`${r.language}
390
390
  ${s}
@@ -570,10 +570,10 @@ ${i.flowchartText}
570
570
 
571
571
  > ${o}
572
572
 
573
- `}})}class XA{constructor(t){h(this,"_grid",[]);h(this,"_needFixSpanData",!1);Array.from(t.rows).forEach((e,o)=>{Array.from(e.cells).forEach(r=>{this._addCell(o,r)})})}_addCell(t,e){const o=this._getNextColIndex(t),r=e.colSpan,i=e.rowSpan;for(let s=0;s<i;s++)for(let l=0;l<r;l++){const c=t+s,a=o+l;if(this._getCell({row:c,col:a})){this._needFixSpanData=!0,console.warn(`invalid table data, cell data already exists, ${c}, ${a}`);continue}this._setCell({row:c,col:a},{cell:e,virtual:!(l===0&&s===0)})}}_getNextColIndex(t){const e=this._grid[t];if(!e)return 0;let o=0;for(let r=0;r<e.length;r++)if(e[r])o+=1;else return o;return o}_setCell(t,e){if(!(e.cell.colSpan===0||e.cell.rowSpan===0)){for(;this._grid.length<=t.row;)this._grid.push([]);for(let o=0;o<this._grid.length;o++){const r=this._grid[o];for(;r.length<=t.col;)r.push(null)}this._grid[t.row][t.col]=e}}_getCell(t){var o;const e=this._grid[t.row];return e&&(o=e[t.col])!=null?o:null}get rowCount(){return this._grid.length}get colCount(){return this._grid[0].length}getCellData(t){const e=this._getCell(t);return e||null}getCellSpan(t){const e=this._getCell(t);if(!e)return{colSpan:1,rowSpan:1};if(e.virtual)return{colSpan:1,rowSpan:1};const o=()=>{let l=t.col+1;for(;;){const c=this._getCell({row:t.row,col:l});if(!c||c.cell!==e.cell)return l-t.col;l+=1}},r=()=>{let l=t.row+1;for(;;){const c=this._getCell({row:l,col:t.col});if(!c||c.cell!==e.cell)return l-t.row;l+=1}},i=o(),s=r();return i!==e.cell.colSpan&&console.warn(`invalid colSpan: ${i} -> ${e.cell.colSpan}`),s!==e.cell.rowSpan&&console.warn(`invalid rowSpan: ${s} -> ${e.cell.rowSpan}`),{colSpan:i,rowSpan:s}}getColumnWidth(t){const r=Array(this.rowCount).fill(0).map((s,l)=>{const c=this.getCellData({row:l,col:t});if(c&&!c.virtual){const a=c.cell.getAttribute("width")||c.cell.style.width;if(a){if(a.endsWith("%")){const f=a.substr(0,a.length-1),m=Number.parseInt(f,10);if(m>0&&m<=100)return Math.floor(720*m/100)}const u=Number.parseInt(a,10);if(u)return u}return c.cell.getBoundingClientRect().width}return 1e9}),i=Math.min(...r);return i===1e9||Number.isNaN(i)||i<30?0:i}}function tO(n){return new XA(n)}function z6(n,t){var c;const e=tO(n),o=[],r={},i=e.rowCount,s=e.colCount,l=Array(s).fill(100);for(let a=0;a<i;a++)for(let u=0;u<s;u++){let f;const m=e.getCellData({row:a,col:u});if(m&&m.virtual)continue;m&&!m.virtual&&(f=t.htmlToBlocks(m.cell.innerHTML,t)),(!f||f.length===0)&&(f=[{id:N(),type:"text",text:[]}]);const C=N();o.push(C);const{colSpan:v,rowSpan:B}=e.getCellSpan({row:a,col:u});B>1&&(r[`${C}_rowSpan`]=B),v>1&&(r[`${C}_colSpan`]=v),t.doc.blocks[C]=f,m&&!m.virtual&&(l[u]=Math.max(l[u],j6((c=t.font)!=null?c:"",f)))}for(let a=0;a<e.colCount;a++)l[a]=e.getColumnWidth(a)||l[a];return o.length===0?[]:[{cols:e.colCount,rows:e.rowCount,id:N(),type:"table",children:o,...r,colsWidth:l}]}function U6(n,t){var e;if(n.tagName==="TABLE"){const o={blocks:{root:[]},meta:{},comments:{}},r=z6(n,{doc:o,...t});if(r.length===0||((e=r[0].children)==null?void 0:e.length)===0)return;o.blocks.root=r;const i=JSON.stringify(o),s=_o(i),l=document.createElement("div");l.classList.add("highlight-text-wizdoc");const c=document.createElement("pre");l.appendChild(c),c.innerText=s,n.insertAdjacentElement("beforebegin",l),n.remove();return}Array.from(n.children).forEach(o=>U6(o,t))}function V6(n){if(n instanceof HTMLStyleElement){n.remove();return}Array.from(n.children).forEach(V6)}function q6(n){if(n instanceof HTMLElement){if(n.style.display==="none"){n.remove();return}if(n.style.visibility==="hidden"){n.remove();return}}Array.from(n.children).forEach(q6)}function eO(n,t){const e=Cl(n);return e.querySelectorAll("td.js-line-number").forEach(r=>r.remove()),e.querySelectorAll("div.copy-button").forEach(r=>r.remove()),e.querySelectorAll("div.code-copy-button").forEach(r=>r.remove()),e.querySelectorAll("noscript").forEach(r=>r.remove()),Array.from(e.children).forEach(q6),Array.from(e.children).forEach(r=>U6(r,t)),Array.from(e.children).forEach(V6),F6(e),Tm(e)}const Kn=new k7.default;Kn.use(WA),Kn.use(GA),Kn.use(ZA),Kn.use(YA),Kn.use(QA),Kn.use(KA),Kn.use(JA),Kn.use(s7.gfm);function nO(n,t){const e=W6(n,t);if(!e)return[];const{root:o,...r}=e.blocks;return t.doc.blocks={...t.doc.blocks,...r},o}function W6(n,t){const e=Kn.turndown(n);return H6(e,{htmlToDoc:o=>G6(o,t)})}function G6(n,t){const e=eO(n,{font:t==null?void 0:t.font,htmlToBlocks:nO});return W6(e)}function Z6(n){return n.indexOf('xmlns:o="urn:schemas-microsoft-com:office:office"')!==-1}function da(n){return["A","B","DEL","I","U","S","SPAN","SUB","SUP"].indexOf(n.tagName)!==-1}function oO(n){return["P","H1","H2","H3","H4","H5","H6","H7","H8","LI"].indexOf(n.tagName)!==-1}function Y6(n){return n.replace(/\r\n/g," ").replace(/\n/g," ").replace(/\r/g," ")}function rO(n){if(!n.tagName)return!1;if(n.tagName.toLocaleLowerCase()==="img")return!0;const t=n.querySelectorAll("img");for(let e=0;e<t.length;e+=1){const o=t[e];if(!o.src||o.getAttribute("width")==="0"||o.getAttribute("height")==="0")return!1}return t.length}function iO(n){return(n.tagName.toLocaleLowerCase()==="img"?[n]:Array.from(n.querySelectorAll("img"))).map(r=>({id:N(),type:"embed",embedType:"image",embedData:{src:r.src,width:r.width,height:r.height}}))}function Q6(n){var e;return Array.from(((e=n.getAttribute("style"))!=null?e:"").split(" ")).findIndex(o=>o.startsWith("level"))!==-1}function sO(n){var e;const t=Array.from(((e=n.getAttribute("style"))!=null?e:"").split(" "));for(let o=0;o<t.length;o++){const r=t[o];if(r.startsWith("mso-list:"))return r}return""}function K6(n){var e,o;const t=Array.from(((e=n.getAttribute("style"))!=null?e:"").split(" "));for(let r=0;r<t.length;r++){const i=t[r];if(i.startsWith("level")){const s=(o=Number.parseInt(i.substring(5),10))!=null?o:void 0;if(s)return s}}return 1}function lO(n,t){n.setAttribute("data-group-id",t)}function cO(n){const t={},e=r=>{Array.from(Object.keys(t)).forEach(i=>{Number.parseInt(i,10)>r&&delete t[i]})};let o="";Array.from(n.children).forEach(r=>{if(Q6(r)){const i=sO(r);o!==i&&(e(0),o=i);const s=K6(r);e(s);let l=t[`${s}`];l||(l=N(),t[`${s}`]=l),lO(r,l)}})}function J6(n){if(!Q6(n))return{};const t=K6(n),e=n.getAttribute("data-group-id")||N();return{start:1,level:t,groupId:e,ordered:!0,type:"list"}}const aO=w("office-list");function X6(n){return n instanceof HTMLOListElement||n instanceof HTMLUListElement}function dO(n,t){d(aO,X6(n),"not list group element");let e=!1,o=1;const r=N();n instanceof HTMLOListElement&&(e=!0,o=n.start);const i=n,s=[];let l;return Array.from(i.children).forEach(c=>{if(c instanceof HTMLLIElement){const u=J6(c),f=t.textElementToBlocks(c,t);l||(l=u.level);const m=f[0];s.push({...m,type:"list",ordered:e,level:l,groupId:r,start:o}),o+=1,s.push(...f.slice(1));return}const a=t.blockElementToBlocks(c,t);s.push(...a)}),s}function t3(n,t){if(n.nodeName==="META")return[];if(n instanceof HTMLTableElement)return z6(n,t);if(X6(n))return[...dO(n,t)];if(rO(n))return[...iO(n)];if(oO(n))return[...t.textElementToBlocks(n,t)];if(!n.children)return[];const e=[];return Array.from(n.children).forEach(o=>{const r=t3(o,t);e.push(...r)}),e}function e3(n,t){const e=[];return n.forEach(o=>{var r;if(o instanceof Element)if(da(o)){const i=document.createElement("p");i.appendChild(o);const s=t.blockElementToBlocks(i,t);e.push(...s)}else{const i=t.blockElementToBlocks(o,t);e.push(...i)}else if(o instanceof Text){const i=zn(Y6((r=o.textContent)!=null?r:""));e.push(i)}}),e}function uO(n){const t=Array.from(n.children);for(let e=0;e<t.length;e++){const o=t[e];if(!da(o))continue;let r=e+1;for(;r<t.length&&da(t[r]);)r+=1;const i=document.createElement("p");o.insertAdjacentElement("beforebegin",i);for(let s=e;s<r;s++)i.appendChild(t[s]);e=r-1}}function hO(n,t){const e=Cl(n);return e3(Array.from(e.childNodes),t)}function fO(n){if(!(n instanceof HTMLElement))return{};const t={};if(n.style.textAlign==="right"?t.align="right":n.style.textAlign==="center"&&(t.align="center"),n.style.marginLeft){const e=Math.ceil(Number.parseInt(n.style.marginLeft,10)/20);e>=1&&e<=12&&(t.padding=e)}return t}function mO(n,t){var o;const e=Y6((o=n.nodeValue)!=null?o:" ");return t&&Object.keys(t).length>0?{insert:e,attributes:t}:{insert:e}}function gO(n,t){if(n.nodeName==="B")return{...t,"style-bold":!0};if(n.nodeName==="I")return{...t,"style-italic":!0};if(n.nodeName==="U")return{...t,"style-underline":!0};if(n.nodeName==="S"||n.nodeName==="DEL")return{...t,"style-strikethrough":!0};if(n.nodeName==="SUB")return{...t,"style-sub":!0};if(n.nodeName==="SUP")return{...t,"style-super":!0};if(n.nodeName==="A"&&n.href){const o=n.href;if(o.startsWith("http:")||o.startsWith("https:"))return{...t,link:n.href}}const e={...t};return n instanceof HTMLSpanElement?(n.style.backgroundColor&&(e["inline-style-background-color"]=n.style.backgroundColor),n.style.color&&(e["inline-style-color"]=n.style.color),n.style.fontSize&&(e["inline-style-font-size"]=n.style.fontSize),n.style.fontFamily&&(e["inline-style-font-family"]=n.style.fontFamily),e):t}function n3(n,t,e){if(n instanceof HTMLSpanElement&&n.getAttribute("style")==="mso-list:Ignore")return;const o=gO(n,t);if(n instanceof Text&&n.nodeValue){e.push(mO(n,o));return}n.childNodes.length>0&&Array.from(n.childNodes).forEach(r=>{n3(r,o,e)})}function o3(n){return n instanceof Element?da(n):!0}function Z1(n){return!o3(n)}function pO(n){if(n.length===0)return[];if(n.length===1)return[n];const t=[];let e=[n[0]],o=Z1(n[0]);for(let r=1;r<n.length;r++){const i=n[r];o===Z1(i)?e.push(i):(t.push(e),e=[i],o=Z1(i))}return t.push(e),t}function CO(n,t){const e={};if(n.tagName.startsWith("H")){const i=Number.parseInt(n.tagName.substr(1),10);i>=1&&i<=8&&(e.heading=i)}const o=pO(Array.from(n.childNodes)),r=[];return o.forEach((i,s)=>{if(o3(i[0])){const l=[],c={};Array.from(n.childNodes).forEach(u=>{n3(u,c,l)});let a={};s===0&&(a=J6(n)),r.push({id:N(),type:"text",text:l,...a,...e,...fO(n)})}i.forEach(l=>{const c=t.blockElementToBlocks(l,t);r.push(...c)})}),r}function bO(n,t){const e=Cl(n);cO(e),uO(e);const o={blocks:{root:[]},meta:{},comments:{}},r={font:t==null?void 0:t.font,doc:o,blockElementToBlocks:t3,textElementToBlocks:CO,htmlToBlocks:hO},i=e3(Array.from(e.children),r);if(i.length!==0)return o.blocks.root=i,o}const vO=w("html-to-doc");function r3(n,t){if(!n)return null;const e=CA(n);if(e)return e;if(Z6(n)){const o=bO(n,t);if(o)return o}try{return G6(n,t)}catch(o){vO.error(o)}return null}class kO{async fromData(t,e){const o={},r=e.getData("text/html");if(r){const i=r3(r,{font:t.rootContainer});i&&(Z6(r)?o["text/office-html"]=i:o["text/html"]=i)}return o}}class yO{async fromData(t,e){const o=e.getData("text/plain");if(!o)return;const r=H6(o,{font:t.rootContainer,htmlToDoc:r3});if(!!r)return{"text/markdown":r}}}function wO(n){return/^([\d\w\u4e00-\u9fa5\s]*[\u4e00-\u9fa5\s]{1}|)((https|http|ftp)?:\/\/)[^\s]+/.test(n)}function BO(n){const t=[],e=n.split(/https|http|ftp/)[0],o=n.substring(e.length).trim();if(e&&e.length){const i=$e(e,null);t.push(i,$e(" ",null))}const r=$e(o,{link:o});return t.push(r,$e(" ",null)),t}class EO{async fromData(t,e){const o={},r=e.getData("text/plain");if(r){const l={blocks:{root:r.replace(/\r\n/g,`
573
+ `}})}class XA{constructor(t){h(this,"_grid",[]);h(this,"_needFixSpanData",!1);Array.from(t.rows).forEach((e,o)=>{Array.from(e.cells).forEach(r=>{this._addCell(o,r)})})}_addCell(t,e){const o=this._getNextColIndex(t),r=e.colSpan,i=e.rowSpan;for(let s=0;s<i;s++)for(let l=0;l<r;l++){const c=t+s,a=o+l;if(this._getCell({row:c,col:a})){this._needFixSpanData=!0,console.warn(`invalid table data, cell data already exists, ${c}, ${a}`);continue}this._setCell({row:c,col:a},{cell:e,virtual:!(l===0&&s===0)})}}_getNextColIndex(t){const e=this._grid[t];if(!e)return 0;let o=0;for(let r=0;r<e.length;r++)if(e[r])o+=1;else return o;return o}_setCell(t,e){if(!(e.cell.colSpan===0||e.cell.rowSpan===0)){for(;this._grid.length<=t.row;)this._grid.push([]);for(let o=0;o<this._grid.length;o++){const r=this._grid[o];for(;r.length<=t.col;)r.push(null)}this._grid[t.row][t.col]=e}}_getCell(t){var o;const e=this._grid[t.row];return e&&(o=e[t.col])!=null?o:null}get rowCount(){return this._grid.length}get colCount(){return this._grid[0].length}getCellData(t){const e=this._getCell(t);return e||null}getCellSpan(t){const e=this._getCell(t);if(!e)return{colSpan:1,rowSpan:1};if(e.virtual)return{colSpan:1,rowSpan:1};const o=()=>{let l=t.col+1;for(;;){const c=this._getCell({row:t.row,col:l});if(!c||c.cell!==e.cell)return l-t.col;l+=1}},r=()=>{let l=t.row+1;for(;;){const c=this._getCell({row:l,col:t.col});if(!c||c.cell!==e.cell)return l-t.row;l+=1}},i=o(),s=r();return i!==e.cell.colSpan&&console.warn(`invalid colSpan: ${i} -> ${e.cell.colSpan}`),s!==e.cell.rowSpan&&console.warn(`invalid rowSpan: ${s} -> ${e.cell.rowSpan}`),{colSpan:i,rowSpan:s}}getColumnWidth(t){const r=Array(this.rowCount).fill(0).map((s,l)=>{const c=this.getCellData({row:l,col:t});if(c&&!c.virtual){const a=c.cell.getAttribute("width")||c.cell.style.width;if(a){if(a.endsWith("%")){const f=a.substr(0,a.length-1),m=Number.parseInt(f,10);if(m>0&&m<=100)return Math.floor(720*m/100)}const u=Number.parseInt(a,10);if(u)return u}return c.cell.getBoundingClientRect().width}return 1e9}),i=Math.min(...r);return i===1e9||Number.isNaN(i)||i<30?0:i}}function tO(n){return new XA(n)}function z6(n,t){var c;const e=tO(n),o=[],r={},i=e.rowCount,s=e.colCount,l=Array(s).fill(100);for(let a=0;a<i;a++)for(let u=0;u<s;u++){let f;const m=e.getCellData({row:a,col:u});if(m&&m.virtual)continue;m&&!m.virtual&&(f=t.htmlToBlocks(m.cell.innerHTML,t)),(!f||f.length===0)&&(f=[{id:N(),type:"text",text:[]}]);const C=N();o.push(C);const{colSpan:v,rowSpan:B}=e.getCellSpan({row:a,col:u});B>1&&(r[`${C}_rowSpan`]=B),v>1&&(r[`${C}_colSpan`]=v),t.doc.blocks[C]=f,m&&!m.virtual&&(l[u]=Math.max(l[u],j6((c=t.font)!=null?c:"",f)))}for(let a=0;a<e.colCount;a++)l[a]=e.getColumnWidth(a)||l[a];return o.length===0?[]:[{cols:e.colCount,rows:e.rowCount,id:N(),type:"table",children:o,...r,colsWidth:l}]}function U6(n,t){var e;if(n.tagName==="TABLE"){const o={blocks:{root:[]},meta:{},comments:{}},r=z6(n,{doc:o,...t});if(r.length===0||((e=r[0].children)==null?void 0:e.length)===0)return;o.blocks.root=r;const i=JSON.stringify(o),s=_o(i),l=document.createElement("div");l.classList.add("highlight-text-wizdoc");const c=document.createElement("pre");l.appendChild(c),c.innerText=s,n.insertAdjacentElement("beforebegin",l),n.remove();return}Array.from(n.children).forEach(o=>U6(o,t))}function V6(n){if(n instanceof HTMLStyleElement){n.remove();return}Array.from(n.children).forEach(V6)}function q6(n){if(n instanceof HTMLElement){if(n.style.display==="none"){n.remove();return}if(n.style.visibility==="hidden"){n.remove();return}}Array.from(n.children).forEach(q6)}function eO(n,t){const e=Cl(n);return e.querySelectorAll("td.js-line-number").forEach(r=>r.remove()),e.querySelectorAll("div.copy-button").forEach(r=>r.remove()),e.querySelectorAll("div.code-copy-button").forEach(r=>r.remove()),e.querySelectorAll("noscript").forEach(r=>r.remove()),Array.from(e.children).forEach(q6),Array.from(e.children).forEach(r=>U6(r,t)),Array.from(e.children).forEach(V6),F6(e),Tm(e)}const Kn=new k7.default;Kn.use(WA),Kn.use(GA),Kn.use(ZA),Kn.use(YA),Kn.use(QA),Kn.use(KA),Kn.use(JA),Kn.use(s7.gfm);function nO(n,t){const e=W6(n,t);if(!e)return[];const{root:o,...r}=e.blocks;return t.doc.blocks={...t.doc.blocks,...r},o}function W6(n,t){const e=Kn.turndown(n);return H6(e,{htmlToDoc:o=>G6(o,t)})}function G6(n,t){const e=eO(n,{font:t==null?void 0:t.font,htmlToBlocks:nO});return W6(e)}function Z6(n){return n.indexOf('xmlns:o="urn:schemas-microsoft-com:office:office"')!==-1}function da(n){return["A","B","DEL","I","U","S","SPAN","SUB","SUP"].indexOf(n.tagName)!==-1}function oO(n){return["P","H1","H2","H3","H4","H5","H6","H7","H8","LI"].indexOf(n.tagName)!==-1}function Y6(n){return n.replace(/\r\n/g," ").replace(/\n/g," ").replace(/\r/g," ")}function rO(n){if(!n.tagName)return!1;if(n.tagName.toLocaleLowerCase()==="img")return!0;const t=n.querySelectorAll("img");for(let e=0;e<t.length;e+=1){const o=t[e];if(!o.src||o.getAttribute("width")==="0"||o.getAttribute("height")==="0")return!1}return t.length}function iO(n){return(n.tagName.toLocaleLowerCase()==="img"?[n]:Array.from(n.querySelectorAll("img"))).map(r=>({id:N(),type:"embed",embedType:"image",embedData:{src:r.src,width:r.width,height:r.height}}))}function Q6(n){var e;return Array.from(((e=n.getAttribute("style"))!=null?e:"").split(" ")).findIndex(o=>o.startsWith("level"))!==-1}function sO(n){var e;const t=Array.from(((e=n.getAttribute("style"))!=null?e:"").split(" "));for(let o=0;o<t.length;o++){const r=t[o];if(r.startsWith("mso-list:"))return r}return""}function K6(n){var e,o;const t=Array.from(((e=n.getAttribute("style"))!=null?e:"").split(" "));for(let r=0;r<t.length;r++){const i=t[r];if(i.startsWith("level")){const s=(o=Number.parseInt(i.substring(5),10))!=null?o:void 0;if(s)return s}}return 1}function lO(n,t){n.setAttribute("data-group-id",t)}function cO(n){const t={},e=r=>{Array.from(Object.keys(t)).forEach(i=>{Number.parseInt(i,10)>r&&delete t[i]})};let o="";Array.from(n.children).forEach(r=>{if(Q6(r)){const i=sO(r);o!==i&&(e(0),o=i);const s=K6(r);e(s);let l=t[`${s}`];l||(l=N(),t[`${s}`]=l),lO(r,l)}})}function J6(n){if(!Q6(n))return{};const t=K6(n),e=n.getAttribute("data-group-id")||N();return{start:1,level:t,groupId:e,ordered:!0,type:"list"}}const aO=w("office-list");function X6(n){return n instanceof HTMLOListElement||n instanceof HTMLUListElement}function dO(n,t){d(aO,X6(n),"not list group element");let e=!1,o=1;const r=N();n instanceof HTMLOListElement&&(e=!0,o=n.start);const i=n,s=[];let l;return Array.from(i.children).forEach(c=>{if(c instanceof HTMLLIElement){const u=J6(c),f=t.textElementToBlocks(c,t);l||(l=u.level);const m=f[0];s.push({...m,type:"list",ordered:e,level:l,groupId:r,start:o}),o+=1,s.push(...f.slice(1));return}const a=t.blockElementToBlocks(c,t);s.push(...a)}),s}function t3(n,t){if(n.nodeName==="META")return[];if(n instanceof HTMLTableElement)return z6(n,t);if(X6(n))return[...dO(n,t)];if(rO(n))return[...iO(n)];if(oO(n))return[...t.textElementToBlocks(n,t)];if(!n.children)return[];const e=[];return Array.from(n.children).forEach(o=>{const r=t3(o,t);e.push(...r)}),e}function e3(n,t){const e=[];return n.forEach(o=>{var r;if(o instanceof Element)if(da(o)){const i=document.createElement("p");i.appendChild(o);const s=t.blockElementToBlocks(i,t);e.push(...s)}else{const i=t.blockElementToBlocks(o,t);e.push(...i)}else if(o instanceof Text){const i=Un(Y6((r=o.textContent)!=null?r:""));e.push(i)}}),e}function uO(n){const t=Array.from(n.children);for(let e=0;e<t.length;e++){const o=t[e];if(!da(o))continue;let r=e+1;for(;r<t.length&&da(t[r]);)r+=1;const i=document.createElement("p");o.insertAdjacentElement("beforebegin",i);for(let s=e;s<r;s++)i.appendChild(t[s]);e=r-1}}function hO(n,t){const e=Cl(n);return e3(Array.from(e.childNodes),t)}function fO(n){if(!(n instanceof HTMLElement))return{};const t={};if(n.style.textAlign==="right"?t.align="right":n.style.textAlign==="center"&&(t.align="center"),n.style.marginLeft){const e=Math.ceil(Number.parseInt(n.style.marginLeft,10)/20);e>=1&&e<=12&&(t.padding=e)}return t}function mO(n,t){var o;const e=Y6((o=n.nodeValue)!=null?o:" ");return t&&Object.keys(t).length>0?{insert:e,attributes:t}:{insert:e}}function gO(n,t){if(n.nodeName==="B")return{...t,"style-bold":!0};if(n.nodeName==="I")return{...t,"style-italic":!0};if(n.nodeName==="U")return{...t,"style-underline":!0};if(n.nodeName==="S"||n.nodeName==="DEL")return{...t,"style-strikethrough":!0};if(n.nodeName==="SUB")return{...t,"style-sub":!0};if(n.nodeName==="SUP")return{...t,"style-super":!0};if(n.nodeName==="A"&&n.href){const o=n.href;if(o.startsWith("http:")||o.startsWith("https:"))return{...t,link:n.href}}const e={...t};return n instanceof HTMLSpanElement?(n.style.backgroundColor&&(e["inline-style-background-color"]=n.style.backgroundColor),n.style.color&&(e["inline-style-color"]=n.style.color),n.style.fontSize&&(e["inline-style-font-size"]=n.style.fontSize),n.style.fontFamily&&(e["inline-style-font-family"]=n.style.fontFamily),e):t}function n3(n,t,e){if(n instanceof HTMLSpanElement&&n.getAttribute("style")==="mso-list:Ignore")return;const o=gO(n,t);if(n instanceof Text&&n.nodeValue){e.push(mO(n,o));return}n.childNodes.length>0&&Array.from(n.childNodes).forEach(r=>{n3(r,o,e)})}function o3(n){return n instanceof Element?da(n):!0}function Z1(n){return!o3(n)}function pO(n){if(n.length===0)return[];if(n.length===1)return[n];const t=[];let e=[n[0]],o=Z1(n[0]);for(let r=1;r<n.length;r++){const i=n[r];o===Z1(i)?e.push(i):(t.push(e),e=[i],o=Z1(i))}return t.push(e),t}function CO(n,t){const e={};if(n.tagName.startsWith("H")){const i=Number.parseInt(n.tagName.substr(1),10);i>=1&&i<=8&&(e.heading=i)}const o=pO(Array.from(n.childNodes)),r=[];return o.forEach((i,s)=>{if(o3(i[0])){const l=[],c={};Array.from(n.childNodes).forEach(u=>{n3(u,c,l)});let a={};s===0&&(a=J6(n)),r.push({id:N(),type:"text",text:l,...a,...e,...fO(n)})}i.forEach(l=>{const c=t.blockElementToBlocks(l,t);r.push(...c)})}),r}function bO(n,t){const e=Cl(n);cO(e),uO(e);const o={blocks:{root:[]},meta:{},comments:{}},r={font:t==null?void 0:t.font,doc:o,blockElementToBlocks:t3,textElementToBlocks:CO,htmlToBlocks:hO},i=e3(Array.from(e.children),r);if(i.length!==0)return o.blocks.root=i,o}const vO=w("html-to-doc");function r3(n,t){if(!n)return null;const e=CA(n);if(e)return e;if(Z6(n)){const o=bO(n,t);if(o)return o}try{return G6(n,t)}catch(o){vO.error(o)}return null}class kO{async fromData(t,e){const o={},r=e.getData("text/html");if(r){const i=r3(r,{font:t.rootContainer});i&&(Z6(r)?o["text/office-html"]=i:o["text/html"]=i)}return o}}class yO{async fromData(t,e){const o=e.getData("text/plain");if(!o)return;const r=H6(o,{font:t.rootContainer,htmlToDoc:r3});if(!!r)return{"text/markdown":r}}}function wO(n){return/^([\d\w\u4e00-\u9fa5\s]*[\u4e00-\u9fa5\s]{1}|)((https|http|ftp)?:\/\/)[^\s]+/.test(n)}function BO(n){const t=[],e=n.split(/https|http|ftp/)[0],o=n.substring(e.length).trim();if(e&&e.length){const i=$e(e,null);t.push(i,$e(" ",null))}const r=$e(o,{link:o});return t.push(r,$e(" ",null)),t}class EO{async fromData(t,e){const o={},r=e.getData("text/plain");if(r){const l={blocks:{root:r.replace(/\r\n/g,`
574
574
  `).replace(/\r/g,`
575
575
  `).split(`
576
- `).map(c=>{const a={id:N(),type:"text"};if(wO(c))return a.text=BO(c),a;const u=c?[$e(c,null)]:[];return a.text=u,a})},meta:{},comments:{}};o["text/plain"]=l}return o}}function IO(n){const t=[];for(let e=0;e<n.length;e++){const o=n[e];o.type.toLocaleLowerCase().startsWith("image/")&&t.push(o)}return t}class i3{constructor(t){t.dataConverter.addConverter(new kO),t.dataConverter.addConverter(new EO),t.dataConverter.addConverter(new yO)}async handleBeforePaste(t,e,o){if(!e)return!1;const r=e.clipboardData;if(r){const i=IO(r.files);if(i.length>0&&!o["text/office-html"])return await this.handleInsertImages(t,i),!0}return!1}async handleInsertImages(t,e){const o=t.selection.focusedBlock,r=H(o),i=J(o),s=U(r);let l=i;Tt(t,o)||(l+=1);for(let c=0;c<e.length;c++){const a=e[c],u=await Id(t,"image",s,l+c,{file:a});u&&gg(t,u,"image",{id:"replace-image",name:"Replace image",data:{block:u,image:a}})}}}function s3(n){return xt.isSafari&&!!n&&Date.now()-n<100}const l3=w("highlight-data");class ua{constructor(t){h(this,"data",new Map);this.editor=t}add(t,e,o){const r={id:N(),blockId:q(t),oldText:this.editor.getBlockText(t),start:e,end:o};return this.data.set(r.id,r),r}get(t){const e=this.data.get(t);return d(l3,e,`no highligh data: ${t}`),e}remove(t){this.data.delete(t)}clearBlockData(t){Array.from(this.data.values()).forEach(e=>{e.blockId===t&&this.data.delete(e.id)})}destroy(){}static getData(t){return t.addCustom("highligh-data",()=>new ua(t))}}function xO(n,t,e,o,r){const s=ua.getData(n).add(t,e,o);return r.setAttribute("data-highlight-id",s.id),s}function ha(n,t){const e=t.getAttribute("data-highlight-id");return d(l3,e,"invalid highlight elem, no id"),ua.getData(n).get(e)}const Us=w("highligh-dom");function TO(n){return nt(n,"editor-highlight")}function Dn(n){const t=n.rootContainer.querySelectorAll(".editor-highlight");return Array.from(t)}function SO(n){const t=n.rootContainer.querySelectorAll(".editor-replace-result-highlight");return Array.from(t)}function Y1(n){const t=n.querySelectorAll(".editor-highlight");return Array.from(t)}function DO(n){Y1(n).forEach(t=>{t.remove()})}function ci(n){return Dn(n).length}function LO(n,t){d(Us,t>=0,`invalid highlight index: ${t}`);const e=Dn(n);return e.length===0?null:(d(Us,t<e.length,`invalid highlight index: ${t}/${e.length}`),e[t])}function MO(n,t,{left:e,top:o,width:r,height:i},s){const l=["editor-highlight-child"];s&&l.push("editor-highlight-readonly");const c=b("div",l,n);c.style.top=`${o}px`,c.style.left=`${e}px`,c.style.width=`${r}px`,c.style.height=`${i}px`}function c3(n,t,e,o,r){d(Us,o>0,`invalid end: ${o}`);const i=Rt(t),s=t.getBoundingClientRect(),l=Ho(n,t,At(n,t,e,o)),a=b("div",[r==="find"?"editor-highlight":"editor-replace-result-highlight"],i);l.forEach(u=>{MO(a,t,{left:u.left-s.left,width:u.width,top:u.top-s.top,height:u.height})}),xO(n,t,e,o,a)}function RO(n,t,e,o){return c3(n,t,e,o,"find")}function a3(n,t,e,o){return c3(n,t,e,o,"replace")}function fa(n,t){Dn(n).forEach(l=>{nt(l,"active")&&z(l,"active")}),A(t,"active"),d(Us,t.firstChild instanceof HTMLElement,"invalid highligh dom, invalid elem child");const o=t.firstChild,r=o.getBoundingClientRect(),i=We(n.rootContainer);let s=r.y;s===0&&(s=o.getBoundingClientRect().y),td(i,{elementToScroll:n.scrollContainer})}function Vs(n){const t=n.rootContainer.querySelector(".editor-highlight.active");return t||null}function d3(n){return d(Us,n,"no highlight elem"),nt(n,"editor-highlight-readonly")}const ai=w("highligh-text");function AO(n){SO(n).forEach(e=>{e.remove()})}function Q1(n,t){Dn(n).forEach(o=>{o.remove()}),t!=null&&t.keepReplaceResult||AO(n)}function u3(n){const t=Vs(n);if(!t)return-1;const o=Dn(n).indexOf(t);return d(ai,o!==-1,`invalid highlight index: ${o}`),o}function OO(n){const t=Dn(n);if(t.length===0)return 0;const e=Vs(n);let o=e?t.indexOf(e):-1;!e||o===-1||o===t.length-1?o=0:o+=1;const r=t[o];return fa(n,r),o}function _O(n){const t=Dn(n);if(t.length===0)return 0;const e=Vs(n);let o=e?t.indexOf(e):-1;!e||o===-1||o===0?o=t.length-1:o-=1;const r=t[o];return fa(n,r),o}function NO(n,t){const e=Dn(n);e.length>0&&t<e.length&&fa(n,e[t])}function $O(n,t,e){const o=Vs(n);if(!o)return!1;const r=F(o);if(d(ai,r,"no parent block"),!n.isBlockWritable(r))return!1;const i=ci(n);let s=u3(n);if(!d3(o)&&n.isBlockWritable(r)){const a=ha(n,o),u=n.getBlockText(r),{start:f,end:m}=ha(n,o),[C,v]=ie.transformOffset(a.oldText,u,[f,m]),B=Ag(u,C,v-C);if(vt(B).toLowerCase()!==t.toLowerCase())return!1;const y=$l(u,C,v,e);n.setBlockText(r,y),DO(r),h3(n,r,t),e&&a3(n,r,C,C+e.length)}const l=ci(n);s>=l?s=0:l>i&&(s+=1);const c=LO(n,s);return c&&fa(n,c),!0}function PO(n,t,e,o){if(!j(n,t)||!n.isBlockWritable(t))return 0;const r=n.getBlockText(t);d(ai,r,"no block text");const i={count:0},s=np(r,e,o,i);return vt(r)===vt(s)?0:(n.setBlockText(t,s),i.count)}function jO(n,t,e){if(d(ai,TO(t),"not a highlight elem"),d3(t))return;d(ai,e>0,"invalid highlight length");const o=ha(n,t),r=F(t);d(ai,r,"no parent block"),a3(n,r,o.start,o.start+e)}function HO(n,t){Dn(n).forEach(o=>{jO(n,o,t)})}function FO(n,t,e){if(n.readonly)return 0;const o=i=>{let s=0;return Mt(i).forEach(c=>{at(n,c)?Se(n,c).forEach(u=>{s+=o(u)}):s+=PO(n,c,t,e)}),s},r=o(n.rootContainer);return e.length>0&&HO(n,e.length),r}function zO(n){const t=n.selection.range.end,e=n.getBlockById(t.blockId),o=t.isSimple()?t.offset:1,r=Y1(e);for(let l=0;l<r.length;l++){const c=r[l],{end:a}=ha(n,c);if(a>=o)return c}const i=Rd(n,{simpleBlockOnly:!0}),s=i.indexOf(e);if(s===-1)return null;for(let l=s+1;l<i.length;l++){const c=i[l],a=Y1(c);if(a.length>0)return a[0]}return null}function UO(n){const t=Dn(n),e=zO(n);return e?t.indexOf(e):0}function h3(n,t,e){if(!!e&&j(n,t)){const o=n.getBlockText(t),r=Wd(o,e);r.length>0&&r.forEach(({start:i,end:s})=>{RO(n,t,i,s)})}}function VO(n,t){if(Q1(n),!t)return;Rd(n,{simpleBlockOnly:!0}).forEach(o=>{h3(n,o,t)})}class qO{constructor(t){h(this,"dialog",null);h(this,"root");h(this,"oldText","");h(this,"_compositionEndTime",0);h(this,"components");h(this,"handleFindChanged",()=>{this.doSearch({keepReplaceResult:!1,gotoFirstSearchResult:!0})});h(this,"handleCompositionEnd",()=>{this._compositionEndTime=Date.now(),this.handleFindChanged()});h(this,"handleInput",t=>{if(t.isComposing||s3(this._compositionEndTime)){this.doSearch.cancel();return}this.handleFindChanged()});h(this,"handleFind",()=>{this.findNext({keepSearchResult:!1})});h(this,"handleReplace",()=>{const t=this.components.findInput.value;if(!t||!Vs(this.editor))return;const o=this.components.replaceInput.value;if(t===o)return;if($O(this.editor,t,o)){const i=u3(this.editor),s=ci(this.editor);this.updateSearchStatus(i,s)}this.findNext({keepSearchResult:!0})});h(this,"handleReplaceAll",()=>{const t=this.components.findInput.value;if(!t)return;const e=this.components.replaceInput.value;if(t===e)return;FO(this.editor,t,e)>0&&(this.oldText="",this.doSearchNow({keepReplaceResult:!0,gotoFirstSearchResult:!0}),this.clearFind({keepReplaceResult:!0}))});h(this,"doSearch",Xt.default(this.doSearchNow,300));this.editor=t;const e=b("div",["editor-find-dialog"],null),o=b("div",["editor-find-content"],e),r=b("div",["editor-find-dialog-row"],o),i=vr(Y2,["editor-find-dialog-button-close"],e),s=b("label",["editor-find-dialog-label"],r,T.t("find.findLabel"));s.htmlFor="";const l=b("div",["editor-find-dialog-input-container"],r),c=b("input",["editor-find-dialog-input"],l);c.type="text",c.placeholder=T.t("find.findPlaceholder");const a=b("div",["editor-find-dialog-status"],l),u=vr(Dw,["editor-find-dialog-icon-button"],a),f=b("div",["editor-find-dialog-curr"],a,"0/0"),m=vr(Lw,["editor-find-dialog-icon-button"],a);let C;T.t("find.moreButton")?C=b("button",["editor-find-dialog-button"],r,T.t("find.moreButton")):C=vr(Q2,["editor-find-dialog-icon-button-border"],r);const v=b("div",["editor-find-dialog-row"],o),B=b("label",["editor-find-dialog-label"],v,T.t("find.replaceLabel"));B.htmlFor="";const y=b("div",["editor-find-dialog-input-container"],v),S=b("input",["editor-find-dialog-input"],y);S.type="text",S.placeholder=T.t("find.replacePlaceholder");const I=b("div",["editor-find-dialog-row"],o);b("div",["editor-find-dialog-space"],I);const M=b("button",["editor-find-dialog-button"],I,T.t("find.findButton")),R=b("button",["editor-find-dialog-button"],I,T.t("find.replaceButton")),$=b("button",["editor-find-dialog-button"],I,T.t("find.replaceAllButton"));C.onclick=()=>{this.showReplace()},i.onclick=()=>{this.hide()},c.onkeydown=Z=>{if(Z.isComposing||s3(this._compositionEndTime)){this.doSearch.cancel();return}vm(Z)?(this.doSearch.cancel(),this.doSearchNow({keepReplaceResult:!1,gotoFirstSearchResult:!0})):id(Z)&&this.hide()},c.oninput=this.handleInput,c.onpaste=this.handleFindChanged,c.oncut=this.handleFindChanged,c.addEventListener("compositionend",this.handleCompositionEnd),c.maxLength=50,M.onclick=this.handleFind,R.onclick=this.handleReplace,$.onclick=this.handleReplaceAll,S.maxLength=50,m.onclick=()=>{this.gotoNext()},u.onclick=()=>{this.gotoPrev()},this.components={findInput:c,findPrev:u,findCurrent:f,findNext:m,replaceInput:S,findButton:M,replaceButton:R,replaceAllButton:$,closeButton:i,showReplaceButton:C,rowReplace:v,rowActions:I,statusContainer:a},this.root=e}findNext(t){this.doSearch.cancel(),this.doSearchNow({keepReplaceResult:t.keepSearchResult,gotoFirstSearchResult:!0})}doSearchNow(t){const e=this.components.findInput.value;if(e||this.clearFind(t),this.oldText===e){this.gotoNext();return}this.oldText=e,VO(this.editor,e);const o=ci(this.editor),r=UO(this.editor);t.gotoFirstSearchResult&&NO(this.editor,r),this.updateSearchStatus(r,o)}gotoNext(){const t=ci(this.editor),e=OO(this.editor);this.updateSearchStatus(e,t)}gotoPrev(){const t=ci(this.editor),e=_O(this.editor);this.updateSearchStatus(e,t)}updateSearchStatus(t,e){if(this.oldText?this.components.statusContainer.style.display="flex":this.components.statusContainer.style.display="none",e===0)this.components.findCurrent.innerText="0/0",this.components.replaceAllButton.disabled=!0,this.components.replaceButton.disabled=!0,this.components.findButton.disabled=!0;else{this.components.findCurrent.innerText=`${t+1}/${e}`;const o=this.editor.readonly;this.components.replaceAllButton.disabled=o,this.components.replaceButton.disabled=o,this.components.findButton.disabled=!1}}clearFind(t){Q1(this.editor),this.updateSearchStatus(0,0)}showFindOnly(){this.components.rowReplace.style.display="none",this.components.rowActions.style.display="none",this.components.showReplaceButton.style.display="flex"}showReplace(){this.components.rowReplace.style.display="flex",this.components.rowActions.style.display="flex",this.components.showReplaceButton.style.display="none",this.components.replaceInput.focus(),this.components.replaceInput.select()}hideSearchResult(){this.components.statusContainer.style.display="none"}showSearchResult(){this.components.statusContainer.style.display="flex"}show(t){const e=this.editor.getSelectedText();e.length>0&&e.length<50&&(this.components.findInput.value=e),this.root.style.display="flex",t!=null&&t.showFindAndReplace?(this.showReplace(),this.components.findInput.value&&setTimeout(()=>{this.components.replaceInput.focus()})):this.showFindOnly(),this.hideSearchResult(),this.oldText="",this.doSearchNow({keepReplaceResult:!1,gotoFirstSearchResult:!0});const o=this.editor.readonly;this.components.replaceButton.disabled=o,this.components.replaceAllButton.disabled=o,this.components.replaceInput.disabled=o,this.dialog||(this.dialog=new bc(this.root,{disablePageScroll:!1}));const r=this.editor.options.componentsOptions.findDialog,i=(r==null?void 0:r.popoverTarget)||this.editor.rootContainer,s=()=>{var f,m,C,v;const l=r==null?void 0:r.getReferenceClientRect;if(l&&((m=(f=this.dialog)==null?void 0:f.tippyInstance)==null?void 0:m.popper))return l(i,(v=(C=this.dialog)==null?void 0:C.tippyInstance)==null?void 0:v.popper);const c=i.getBoundingClientRect(),a=c.top<0?12:c.top+12,u=c.right-this.root.clientWidth-12;return new DOMRect(u,a,0,0)};this.dialog.show(i,{getReferenceClientRect:s}),setTimeout(()=>{this.components.findInput.focus(),this.components.findInput.select()},300)}hide(){var t;(t=this.dialog)==null||t.close(),Q1(this.editor)}isVisible(){return this.dialog&&this.dialog.isVisible}research(){this.oldText="",this.doSearch({keepReplaceResult:!0,gotoFirstSearchResult:!1})}destroy(){var t;(t=this.dialog)==null||t.destroy()}}const WO={find:{findLabel:"\u67E5\u627E:",replaceLabel:"\u66FF\u6362:",findButton:"\u67E5\u627E",replaceButton:"\u66FF\u6362",replaceAllButton:"\u5168\u90E8\u66FF\u6362",moreButton:"",findPlaceholder:"\u5728\u6587\u6863\u5185\u67E5\u627E",replacePlaceholder:"\u66FF\u6362\u4E3A"}},GO={find:{findLabel:"Find:",replaceLabel:"Replace:",findButton:"Find",replaceButton:"Replace",replaceAllButton:"Replace All",moreButton:"",findPlaceholder:"Find text in document",replacePlaceholder:"Replace to"}};T.mergeLang({"zh-CN":WO,"en-US":GO});function f3(n){return n.addCustom("find-dialog",()=>new qO(n)).show(),!0}const m3={"CtrlOrCmd+F":f3},jz="";function ZO(n){f3(n)}function K1(n,t){return t.map(e=>{var i,s;const o=bt(n,e),r=(i=o.getBlockProperties)==null?void 0:i.call(o,n,e);return(s=r==null?void 0:r.abstract)!=null?s:""}).join(" ")}function ma(n){const{editor:t,commentGroupId:e,abstract:o="text"}=n,r=N(),i=t.doc.getUser(),s=Date.now(),l=e!=null?e:r;return{id:r,groupId:l,userId:i.userId,displayName:i.displayName,avatarUrl:i.avatarUrl,abstract:o,created:s,modified:s}}function g3(n,t,e){const o=e.id,i=n.getBlockData(t).comments;let s;i?s=[...i,o]:s=[o];const l={comments:s};n.updateBlockData(t,l)}function J1(n,t,e){const o=K1(n,[t]),r=ma({editor:n,abstract:o});g3(n,t,r);const i=Zo();return e.localCreateComment(r,i),r}const YO=w("standard-block-actions");class QO{constructor(t,e){h(this,"executeCommand",(t,e,o)=>{const r=o.data;try{this.editorComments.showCommentList();const i=t.getBlockById(r);J1(t,i,this.provider)}catch(i){YO.error(`failed to execute block command: ${JSON.stringify(i)}`)}});this.provider=t,this.editorComments=e}commands(t,e){return{group:"block-comment-actions",commands:[{id:"comment",name:"Add comment",data:q(e),order:100}],executeCommand:this.executeCommand}}}var ft=(n=>(n.SwitchUp="switch-up",n.SwitchDown="switch-down",n.CommentItemReply="comment-item-reply",n.CommentItemMore="comment-item-more",n.CommentItemOk="comment-item-ok",n.CommentItemCancel="comment-item-cancel",n.CommentItemDelete="comment-item-delete",n.CommentItemEdit="comment-item-edit",n.QuickReply="quick-reply",n.QuickReplyOk="quick-reply-ok",n.QuickReplyCancel="quick-reply-cancel",n))(ft||{});const X1="group-item-action",p3="last-comment-item",Jn="disabled",C3=500;function dr(n){return n.id!==n.groupId}function b3(n,t=".comment-item-root"){return n.querySelectorAll(t).length}function KO(n){const t=n.closest(".comment-item-root");return t?t.id:null}function Xn(n,t){n.setAttribute(X1,t)}function JO(n){return n.closest(`[${X1}]`)}function XO(n){var t;return(t=n.getAttribute(X1))!=null?t:""}function t_(n){return nt(n,Jn)}function v3(n,t){const e=n.rootContainer.querySelector(`[comment-${t.toLocaleLowerCase()}=${t}`);if(!e)return null;const o=e.closest('[data-type="editor-block"]');return o?o.id:null}function k3(n){return Array.from(n.attributes).map(e=>e.name).filter(e=>e.startsWith("comment-")).map(e=>e.replace("comment-",""))}const y3=w("doc-comments");function w3(n,t,e,o){if(t.comments){const i=t.comments;Array.isArray(i)&&i.forEach(s=>{o.has(s)||(o.add(s),e.push(s))})}t.text&&t.text.forEach(s=>{if(s.attributes){const l="comment-";Object.entries(s.attributes).forEach(([c,a])=>{if(c.startsWith(l)){const u=a;o.has(u)||(o.add(u),e.push(u))}})}});const r=t.children;!r||r.forEach(i=>{n.blocks[i].forEach(l=>{w3(n,l,e,o)})})}function e_(n){const t=[],e=new Set;n.blocks.root.forEach(r=>{w3(n,r,t,e)});const o=new Map;return t.forEach((r,i)=>o.set(r,i)),o}function n_(n){const t=new Map;n.forEach(r=>{if(dr(r)){const i=t.get(r.groupId);i?i.push(r):t.set(r.groupId,[r])}});const e=[];return n.forEach(r=>{var i;if(!dr(r)){const s=(i=t.get(r.id))!=null?i:[];t.delete(r.id);const l={...r,children:s};e.push(l)}}),Array.from(t.values()).forEach(r=>{const i=r[0],s=r.slice(1),l={...i,children:s};e.push(l)}),e}function wo(n,t){const e=n.doc.toJSON(),o=e_(e);return n_(t.getComments()).filter(s=>o.has(s.groupId)).sort((s,l)=>{const c=o.get(s.groupId),a=o.get(l.groupId);return d(y3,c!==void 0,`comment not exists in doc, ${s.groupId}`),d(y3,a!==void 0,`comment not exists in doc, ${l.groupId}`),c-a})}function tf(n){const{children:t,...e}=n,o=[e];return t.forEach(r=>{o.push(r)}),o}function o_(n,t){return wo(n,t).map(tf).reduce((r,i)=>i.length+r,0)}function ef(n,t){const e=[],o=n.getBlockById(t.blockId);if(j(n,o)){const i=t.blockId,s=t.offset,l=n.getBlockById(i),c=n.getBlockText(l),a=Nl(c,s);a&&Object.entries(a).forEach(([u,f])=>{u.startsWith("comment-")&&e.push(f)})}const r=o.attributes;for(let i=0;i<r.length;i++){const s=r[i];s.name.startsWith("comment-")&&e.push(s.value)}return e}function r_(n){const t=n.selection.range;if(!t.isSimple())return[];if(t.start.blockId!==t.end.blockId)return[];if(t.isCollapsed())return ef(n,t.start);const{start:e,end:o}=t,r=ef(n,e),i=ef(n,o);return Za.default(r,i)}const i_=w("active-comments");function B3(n,t){n.rootContainer.querySelectorAll(`span.text.comment[comment-${t}],[data-type=editor-block].comment[comment-${t}]`).forEach(o=>{z(o,"active")})}function E3(n,t){const e=n.rootContainer.querySelector("span.text.comment.active,[data-type=editor-block].comment.active");if(!t)e&&k3(e).forEach(r=>B3(n,r));else{const o=t.toLocaleLowerCase();if(e){const i=k3(e);if(i.length===1&&i[0]===o)return;i.forEach(s=>B3(n,s))}const r=n.rootContainer.querySelectorAll(`span.text.comment[comment-${o}],[data-type=editor-block].comment[comment-${o}]`);if(r){r.forEach(s=>{A(s,"active")});const i=r[0];if(Po(i))n.selection.selectBlock(i,0);else{const s=F(i);d(i_,s,"block not found");const l=so(s,i);n.selection.selectBlock(s,l.start)}n.focus()}}}const Hz="";w("comment-editor");const{t:s_}=T,nf="comment-editor-readonly",qs="comment-editor-editing";class of{constructor(t,e,o){h(this,"root");h(this,"components");h(this,"handleEditorBlur",()=>{this.inactiveEditor()});h(this,"handleEditorFocus",()=>{this.editor.readonly||this.activeEditor()});h(this,"activeEditor",()=>{nt(this.root,qs)||A(this.root,qs)});h(this,"inactiveEditor",()=>{z(this.root,qs)});h(this,"handleInsertImg",async()=>{const{editor:t}=this.components,e=U(t.rootContainer),o=await No("image/*",{}),r={src:"",widthPercent:50},i={id:N(),type:"embed",embedType:"image",embedData:r},s=t.options.componentsOptions.image;s!=null&&s.defaultAlign&&(i.align=s.defaultAlign);const l=t.getFocusedBlock(),c=t.getBlockIndex(l),a=t.insertBlock(e,c+1,i);zt.getImageObject(t,a).replaceImage(0,o)});h(this,"handleReadonlyChange",t=>{t.readonly?(z(this.root,qs),A(this.root,nf)):(A(this.root,qs),z(this.root,nf))});h(this,"setDoc",t=>{const{components:{editor:e}}=this;e.doc.externalDoc.setDoc(t)});h(this,"getDoc",()=>{const{components:{editor:t}}=this;return t.doc.toJSON()});h(this,"isEmpty",()=>jl(this.getDoc()));h(this,"edit",()=>{const{editor:t}=this.components;t.readonly=!1,L0(t),this.activeEditor()});h(this,"clear",()=>{const t=Zo();this.setDoc(t)});h(this,"readonly",()=>{const{editor:t}=this.components;t.readonly=!0});h(this,"destroy",()=>{const{root:t,components:{editor:e,insertImgButton:o}}=this;o.onclick=null,e.destroy(),t.remove()});this.mainEditor=t,this.commentsProvider=e,this.doc=o,this.root=b("div",["comment-editor",nf],null),this.components=this.createEditor()}createEditor(){const t=b("div",["comment-editor-root"],this.root),{commentsProvider:e,mainEditor:o}=this,r=e.createCommentEditor(t,new Ru(this.doc));r.readonly=!0,r.addListener("readonlyChanged",this.handleReadonlyChange),r.addListener("focus",this.handleEditorFocus),r.addListener("blur",this.handleEditorBlur);const i=sr(this.root,"comment-editor-img",s_("comment.image"),Hw,void 0,o.clientId);return i.classList.add("comment-editor-img"),i.onclick=this.handleInsertImg,{editor:r,insertImgButton:i}}get editor(){return this.components.editor}}class l_{constructor(t){h(this,"handleBeforeKeyDown",(t,e)=>{if(Pn(e,"Enter")){const{quickReply:o,updateLastCommentItem:r}=this.groupItem;return o.getReplyEditor().isEmpty()?(o.hideReplyEditor(),!0):(o.reply(),r(),!0)}return!1});this.groupItem=t}}class c_{constructor(t,e,o){h(this,"handleBeforeKeyDown",(t,e)=>{if(Pn(e,"Enter")){const{quickReply:o}=this.groupItem,{comment:r,getCommentEditor:i}=this.commentItem,s=i();if(s.isEmpty())this.commentsProvider.localDeleteComment(r.id);else{const l=s.getDoc();this.commentsProvider.localUpdateComment(r,l),s.readonly()}return o.show(),!0}return!1});this.commentsProvider=t,this.groupItem=e,this.commentItem=o}}const a_=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
576
+ `).map(c=>{const a={id:N(),type:"text"};if(wO(c))return a.text=BO(c),a;const u=c?[$e(c,null)]:[];return a.text=u,a})},meta:{},comments:{}};o["text/plain"]=l}return o}}function IO(n){const t=[];for(let e=0;e<n.length;e++){const o=n[e];o.type.toLocaleLowerCase().startsWith("image/")&&t.push(o)}return t}class i3{constructor(t){t.dataConverter.addConverter(new kO),t.dataConverter.addConverter(new EO),t.dataConverter.addConverter(new yO)}async handleBeforePaste(t,e,o){if(!e)return!1;const r=e.clipboardData;if(r){const i=IO(r.files);if(i.length>0&&!o["text/office-html"])return await this.handleInsertImages(t,i),!0}return!1}async handleInsertImages(t,e){const o=t.selection.focusedBlock,r=H(o),i=J(o),s=U(r);let l=i;Tt(t,o)||(l+=1);for(let c=0;c<e.length;c++){const a=e[c],u=await Id(t,"image",s,l+c,{file:a});u&&gg(t,u,"image",{id:"replace-image",name:"Replace image",data:{block:u,image:a}})}}}function s3(n){return xt.isSafari&&!!n&&Date.now()-n<100}const l3=w("highlight-data");class ua{constructor(t){h(this,"data",new Map);this.editor=t}add(t,e,o){const r={id:N(),blockId:q(t),oldText:this.editor.getBlockText(t),start:e,end:o};return this.data.set(r.id,r),r}get(t){const e=this.data.get(t);return d(l3,e,`no highligh data: ${t}`),e}remove(t){this.data.delete(t)}clearBlockData(t){Array.from(this.data.values()).forEach(e=>{e.blockId===t&&this.data.delete(e.id)})}destroy(){}static getData(t){return t.addCustom("highligh-data",()=>new ua(t))}}function xO(n,t,e,o,r){const s=ua.getData(n).add(t,e,o);return r.setAttribute("data-highlight-id",s.id),s}function ha(n,t){const e=t.getAttribute("data-highlight-id");return d(l3,e,"invalid highlight elem, no id"),ua.getData(n).get(e)}const Us=w("highligh-dom");function TO(n){return nt(n,"editor-highlight")}function Ln(n){const t=n.rootContainer.querySelectorAll(".editor-highlight");return Array.from(t)}function SO(n){const t=n.rootContainer.querySelectorAll(".editor-replace-result-highlight");return Array.from(t)}function Y1(n){const t=n.querySelectorAll(".editor-highlight");return Array.from(t)}function DO(n){Y1(n).forEach(t=>{t.remove()})}function ci(n){return Ln(n).length}function LO(n,t){d(Us,t>=0,`invalid highlight index: ${t}`);const e=Ln(n);return e.length===0?null:(d(Us,t<e.length,`invalid highlight index: ${t}/${e.length}`),e[t])}function MO(n,t,{left:e,top:o,width:r,height:i},s){const l=["editor-highlight-child"];s&&l.push("editor-highlight-readonly");const c=b("div",l,n);c.style.top=`${o}px`,c.style.left=`${e}px`,c.style.width=`${r}px`,c.style.height=`${i}px`}function c3(n,t,e,o,r){d(Us,o>0,`invalid end: ${o}`);const i=Rt(t),s=t.getBoundingClientRect(),l=Ho(n,t,At(n,t,e,o)),a=b("div",[r==="find"?"editor-highlight":"editor-replace-result-highlight"],i);l.forEach(u=>{MO(a,t,{left:u.left-s.left,width:u.width,top:u.top-s.top,height:u.height})}),xO(n,t,e,o,a)}function RO(n,t,e,o){return c3(n,t,e,o,"find")}function a3(n,t,e,o){return c3(n,t,e,o,"replace")}function fa(n,t){Ln(n).forEach(l=>{nt(l,"active")&&z(l,"active")}),A(t,"active"),d(Us,t.firstChild instanceof HTMLElement,"invalid highligh dom, invalid elem child");const o=t.firstChild,r=o.getBoundingClientRect(),i=We(n.rootContainer);let s=r.y;s===0&&(s=o.getBoundingClientRect().y),td(i,{elementToScroll:n.scrollContainer})}function Vs(n){const t=n.rootContainer.querySelector(".editor-highlight.active");return t||null}function d3(n){return d(Us,n,"no highlight elem"),nt(n,"editor-highlight-readonly")}const ai=w("highligh-text");function AO(n){SO(n).forEach(e=>{e.remove()})}function Q1(n,t){Ln(n).forEach(o=>{o.remove()}),t!=null&&t.keepReplaceResult||AO(n)}function u3(n){const t=Vs(n);if(!t)return-1;const o=Ln(n).indexOf(t);return d(ai,o!==-1,`invalid highlight index: ${o}`),o}function OO(n){const t=Ln(n);if(t.length===0)return 0;const e=Vs(n);let o=e?t.indexOf(e):-1;!e||o===-1||o===t.length-1?o=0:o+=1;const r=t[o];return fa(n,r),o}function _O(n){const t=Ln(n);if(t.length===0)return 0;const e=Vs(n);let o=e?t.indexOf(e):-1;!e||o===-1||o===0?o=t.length-1:o-=1;const r=t[o];return fa(n,r),o}function NO(n,t){const e=Ln(n);e.length>0&&t<e.length&&fa(n,e[t])}function $O(n,t,e){const o=Vs(n);if(!o)return!1;const r=F(o);if(d(ai,r,"no parent block"),!n.isBlockWritable(r))return!1;const i=ci(n);let s=u3(n);if(!d3(o)&&n.isBlockWritable(r)){const a=ha(n,o),u=n.getBlockText(r),{start:f,end:m}=ha(n,o),[C,v]=ie.transformOffset(a.oldText,u,[f,m]),B=Ag(u,C,v-C);if(vt(B).toLowerCase()!==t.toLowerCase())return!1;const y=$l(u,C,v,e);n.setBlockText(r,y),DO(r),h3(n,r,t),e&&a3(n,r,C,C+e.length)}const l=ci(n);s>=l?s=0:l>i&&(s+=1);const c=LO(n,s);return c&&fa(n,c),!0}function PO(n,t,e,o){if(!j(n,t)||!n.isBlockWritable(t))return 0;const r=n.getBlockText(t);d(ai,r,"no block text");const i={count:0},s=np(r,e,o,i);return vt(r)===vt(s)?0:(n.setBlockText(t,s),i.count)}function jO(n,t,e){if(d(ai,TO(t),"not a highlight elem"),d3(t))return;d(ai,e>0,"invalid highlight length");const o=ha(n,t),r=F(t);d(ai,r,"no parent block"),a3(n,r,o.start,o.start+e)}function HO(n,t){Ln(n).forEach(o=>{jO(n,o,t)})}function FO(n,t,e){if(n.readonly)return 0;const o=i=>{let s=0;return Mt(i).forEach(c=>{at(n,c)?Se(n,c).forEach(u=>{s+=o(u)}):s+=PO(n,c,t,e)}),s},r=o(n.rootContainer);return e.length>0&&HO(n,e.length),r}function zO(n){const t=n.selection.range.end,e=n.getBlockById(t.blockId),o=t.isSimple()?t.offset:1,r=Y1(e);for(let l=0;l<r.length;l++){const c=r[l],{end:a}=ha(n,c);if(a>=o)return c}const i=Rd(n,{simpleBlockOnly:!0}),s=i.indexOf(e);if(s===-1)return null;for(let l=s+1;l<i.length;l++){const c=i[l],a=Y1(c);if(a.length>0)return a[0]}return null}function UO(n){const t=Ln(n),e=zO(n);return e?t.indexOf(e):0}function h3(n,t,e){if(!!e&&j(n,t)){const o=n.getBlockText(t),r=Wd(o,e);r.length>0&&r.forEach(({start:i,end:s})=>{RO(n,t,i,s)})}}function VO(n,t){if(Q1(n),!t)return;Rd(n,{simpleBlockOnly:!0}).forEach(o=>{h3(n,o,t)})}class qO{constructor(t){h(this,"dialog",null);h(this,"root");h(this,"oldText","");h(this,"_compositionEndTime",0);h(this,"components");h(this,"handleFindChanged",()=>{this.doSearch({keepReplaceResult:!1,gotoFirstSearchResult:!0})});h(this,"handleCompositionEnd",()=>{this._compositionEndTime=Date.now(),this.handleFindChanged()});h(this,"handleInput",t=>{if(t.isComposing||s3(this._compositionEndTime)){this.doSearch.cancel();return}this.handleFindChanged()});h(this,"handleFind",()=>{this.findNext({keepSearchResult:!1})});h(this,"handleReplace",()=>{const t=this.components.findInput.value;if(!t||!Vs(this.editor))return;const o=this.components.replaceInput.value;if(t===o)return;if($O(this.editor,t,o)){const i=u3(this.editor),s=ci(this.editor);this.updateSearchStatus(i,s)}this.findNext({keepSearchResult:!0})});h(this,"handleReplaceAll",()=>{const t=this.components.findInput.value;if(!t)return;const e=this.components.replaceInput.value;if(t===e)return;FO(this.editor,t,e)>0&&(this.oldText="",this.doSearchNow({keepReplaceResult:!0,gotoFirstSearchResult:!0}),this.clearFind({keepReplaceResult:!0}))});h(this,"doSearch",Xt.default(this.doSearchNow,300));this.editor=t;const e=b("div",["editor-find-dialog"],null),o=b("div",["editor-find-content"],e),r=b("div",["editor-find-dialog-row"],o),i=vr(Y2,["editor-find-dialog-button-close"],e),s=b("label",["editor-find-dialog-label"],r,T.t("find.findLabel"));s.htmlFor="";const l=b("div",["editor-find-dialog-input-container"],r),c=b("input",["editor-find-dialog-input"],l);c.type="text",c.placeholder=T.t("find.findPlaceholder");const a=b("div",["editor-find-dialog-status"],l),u=vr(Dw,["editor-find-dialog-icon-button"],a),f=b("div",["editor-find-dialog-curr"],a,"0/0"),m=vr(Lw,["editor-find-dialog-icon-button"],a);let C;T.t("find.moreButton")?C=b("button",["editor-find-dialog-button"],r,T.t("find.moreButton")):C=vr(Q2,["editor-find-dialog-icon-button-border"],r);const v=b("div",["editor-find-dialog-row"],o),B=b("label",["editor-find-dialog-label"],v,T.t("find.replaceLabel"));B.htmlFor="";const y=b("div",["editor-find-dialog-input-container"],v),S=b("input",["editor-find-dialog-input"],y);S.type="text",S.placeholder=T.t("find.replacePlaceholder");const I=b("div",["editor-find-dialog-row"],o);b("div",["editor-find-dialog-space"],I);const M=b("button",["editor-find-dialog-button"],I,T.t("find.findButton")),R=b("button",["editor-find-dialog-button"],I,T.t("find.replaceButton")),$=b("button",["editor-find-dialog-button"],I,T.t("find.replaceAllButton"));C.onclick=()=>{this.showReplace()},i.onclick=()=>{this.hide()},c.onkeydown=Z=>{if(Z.isComposing||s3(this._compositionEndTime)){this.doSearch.cancel();return}vm(Z)?(this.doSearch.cancel(),this.doSearchNow({keepReplaceResult:!1,gotoFirstSearchResult:!0})):id(Z)&&this.hide()},c.oninput=this.handleInput,c.onpaste=this.handleFindChanged,c.oncut=this.handleFindChanged,c.addEventListener("compositionend",this.handleCompositionEnd),c.maxLength=50,M.onclick=this.handleFind,R.onclick=this.handleReplace,$.onclick=this.handleReplaceAll,S.maxLength=50,m.onclick=()=>{this.gotoNext()},u.onclick=()=>{this.gotoPrev()},this.components={findInput:c,findPrev:u,findCurrent:f,findNext:m,replaceInput:S,findButton:M,replaceButton:R,replaceAllButton:$,closeButton:i,showReplaceButton:C,rowReplace:v,rowActions:I,statusContainer:a},this.root=e}findNext(t){this.doSearch.cancel(),this.doSearchNow({keepReplaceResult:t.keepSearchResult,gotoFirstSearchResult:!0})}doSearchNow(t){const e=this.components.findInput.value;if(e||this.clearFind(t),this.oldText===e){this.gotoNext();return}this.oldText=e,VO(this.editor,e);const o=ci(this.editor),r=UO(this.editor);t.gotoFirstSearchResult&&NO(this.editor,r),this.updateSearchStatus(r,o)}gotoNext(){const t=ci(this.editor),e=OO(this.editor);this.updateSearchStatus(e,t)}gotoPrev(){const t=ci(this.editor),e=_O(this.editor);this.updateSearchStatus(e,t)}updateSearchStatus(t,e){if(this.oldText?this.components.statusContainer.style.display="flex":this.components.statusContainer.style.display="none",e===0)this.components.findCurrent.innerText="0/0",this.components.replaceAllButton.disabled=!0,this.components.replaceButton.disabled=!0,this.components.findButton.disabled=!0;else{this.components.findCurrent.innerText=`${t+1}/${e}`;const o=this.editor.readonly;this.components.replaceAllButton.disabled=o,this.components.replaceButton.disabled=o,this.components.findButton.disabled=!1}}clearFind(t){Q1(this.editor),this.updateSearchStatus(0,0)}showFindOnly(){this.components.rowReplace.style.display="none",this.components.rowActions.style.display="none",this.components.showReplaceButton.style.display="flex"}showReplace(){this.components.rowReplace.style.display="flex",this.components.rowActions.style.display="flex",this.components.showReplaceButton.style.display="none",this.components.replaceInput.focus(),this.components.replaceInput.select()}hideSearchResult(){this.components.statusContainer.style.display="none"}showSearchResult(){this.components.statusContainer.style.display="flex"}show(t){const e=this.editor.getSelectedText();e.length>0&&e.length<50&&(this.components.findInput.value=e),this.root.style.display="flex",t!=null&&t.showFindAndReplace?(this.showReplace(),this.components.findInput.value&&setTimeout(()=>{this.components.replaceInput.focus()})):this.showFindOnly(),this.hideSearchResult(),this.oldText="",this.doSearchNow({keepReplaceResult:!1,gotoFirstSearchResult:!0});const o=this.editor.readonly;this.components.replaceButton.disabled=o,this.components.replaceAllButton.disabled=o,this.components.replaceInput.disabled=o,this.dialog||(this.dialog=new bc(this.root,{disablePageScroll:!1}));const r=this.editor.options.componentsOptions.findDialog,i=(r==null?void 0:r.popoverTarget)||this.editor.rootContainer,s=()=>{var f,m,C,v;const l=r==null?void 0:r.getReferenceClientRect;if(l&&((m=(f=this.dialog)==null?void 0:f.tippyInstance)==null?void 0:m.popper))return l(i,(v=(C=this.dialog)==null?void 0:C.tippyInstance)==null?void 0:v.popper);const c=i.getBoundingClientRect(),a=c.top<0?12:c.top+12,u=c.right-this.root.clientWidth-12;return new DOMRect(u,a,0,0)};this.dialog.show(i,{getReferenceClientRect:s}),setTimeout(()=>{this.components.findInput.focus(),this.components.findInput.select()},300)}hide(){var t;(t=this.dialog)==null||t.close(),Q1(this.editor)}isVisible(){return this.dialog&&this.dialog.isVisible}research(){this.oldText="",this.doSearch({keepReplaceResult:!0,gotoFirstSearchResult:!1})}destroy(){var t;(t=this.dialog)==null||t.destroy()}}const WO={find:{findLabel:"\u67E5\u627E:",replaceLabel:"\u66FF\u6362:",findButton:"\u67E5\u627E",replaceButton:"\u66FF\u6362",replaceAllButton:"\u5168\u90E8\u66FF\u6362",moreButton:"",findPlaceholder:"\u5728\u6587\u6863\u5185\u67E5\u627E",replacePlaceholder:"\u66FF\u6362\u4E3A"}},GO={find:{findLabel:"Find:",replaceLabel:"Replace:",findButton:"Find",replaceButton:"Replace",replaceAllButton:"Replace All",moreButton:"",findPlaceholder:"Find text in document",replacePlaceholder:"Replace to"}};T.mergeLang({"zh-CN":WO,"en-US":GO});function f3(n){return n.addCustom("find-dialog",()=>new qO(n)).show(),!0}const m3={"CtrlOrCmd+F":f3},jz="";function ZO(n){f3(n)}function K1(n,t){return t.map(e=>{var i,s;const o=bt(n,e),r=(i=o.getBlockProperties)==null?void 0:i.call(o,n,e);return(s=r==null?void 0:r.abstract)!=null?s:""}).join(" ")}function ma(n){const{editor:t,commentGroupId:e,abstract:o="text"}=n,r=N(),i=t.doc.getUser(),s=Date.now(),l=e!=null?e:r;return{id:r,groupId:l,userId:i.userId,displayName:i.displayName,avatarUrl:i.avatarUrl,abstract:o,created:s,modified:s}}function g3(n,t,e){const o=e.id,i=n.getBlockData(t).comments;let s;i?s=[...i,o]:s=[o];const l={comments:s};n.updateBlockData(t,l)}function J1(n,t,e){const o=K1(n,[t]),r=ma({editor:n,abstract:o});g3(n,t,r);const i=Zo();return e.localCreateComment(r,i),r}const YO=w("standard-block-actions");class QO{constructor(t,e){h(this,"executeCommand",(t,e,o)=>{const r=o.data;try{this.editorComments.showCommentList();const i=t.getBlockById(r);J1(t,i,this.provider)}catch(i){YO.error(`failed to execute block command: ${JSON.stringify(i)}`)}});this.provider=t,this.editorComments=e}commands(t,e){return{group:"block-comment-actions",commands:[{id:"comment",name:"Add comment",data:q(e),order:100}],executeCommand:this.executeCommand}}}var ft=(n=>(n.SwitchUp="switch-up",n.SwitchDown="switch-down",n.CommentItemReply="comment-item-reply",n.CommentItemMore="comment-item-more",n.CommentItemOk="comment-item-ok",n.CommentItemCancel="comment-item-cancel",n.CommentItemDelete="comment-item-delete",n.CommentItemEdit="comment-item-edit",n.QuickReply="quick-reply",n.QuickReplyOk="quick-reply-ok",n.QuickReplyCancel="quick-reply-cancel",n))(ft||{});const X1="group-item-action",p3="last-comment-item",Jn="disabled",C3=500;function dr(n){return n.id!==n.groupId}function b3(n,t=".comment-item-root"){return n.querySelectorAll(t).length}function KO(n){const t=n.closest(".comment-item-root");return t?t.id:null}function Xn(n,t){n.setAttribute(X1,t)}function JO(n){return n.closest(`[${X1}]`)}function XO(n){var t;return(t=n.getAttribute(X1))!=null?t:""}function t_(n){return nt(n,Jn)}function v3(n,t){const e=n.rootContainer.querySelector(`[comment-${t.toLocaleLowerCase()}=${t}`);if(!e)return null;const o=e.closest('[data-type="editor-block"]');return o?o.id:null}function k3(n){return Array.from(n.attributes).map(e=>e.name).filter(e=>e.startsWith("comment-")).map(e=>e.replace("comment-",""))}const y3=w("doc-comments");function w3(n,t,e,o){if(t.comments){const i=t.comments;Array.isArray(i)&&i.forEach(s=>{o.has(s)||(o.add(s),e.push(s))})}t.text&&t.text.forEach(s=>{if(s.attributes){const l="comment-";Object.entries(s.attributes).forEach(([c,a])=>{if(c.startsWith(l)){const u=a;o.has(u)||(o.add(u),e.push(u))}})}});const r=t.children;!r||r.forEach(i=>{n.blocks[i].forEach(l=>{w3(n,l,e,o)})})}function e_(n){const t=[],e=new Set;n.blocks.root.forEach(r=>{w3(n,r,t,e)});const o=new Map;return t.forEach((r,i)=>o.set(r,i)),o}function n_(n){const t=new Map;n.forEach(r=>{if(dr(r)){const i=t.get(r.groupId);i?i.push(r):t.set(r.groupId,[r])}});const e=[];return n.forEach(r=>{var i;if(!dr(r)){const s=(i=t.get(r.id))!=null?i:[];t.delete(r.id);const l={...r,children:s};e.push(l)}}),Array.from(t.values()).forEach(r=>{const i=r[0],s=r.slice(1),l={...i,children:s};e.push(l)}),e}function wo(n,t){const e=n.doc.toJSON(),o=e_(e);return n_(t.getComments()).filter(s=>o.has(s.groupId)).sort((s,l)=>{const c=o.get(s.groupId),a=o.get(l.groupId);return d(y3,c!==void 0,`comment not exists in doc, ${s.groupId}`),d(y3,a!==void 0,`comment not exists in doc, ${l.groupId}`),c-a})}function tf(n){const{children:t,...e}=n,o=[e];return t.forEach(r=>{o.push(r)}),o}function o_(n,t){return wo(n,t).map(tf).reduce((r,i)=>i.length+r,0)}function ef(n,t){const e=[],o=n.getBlockById(t.blockId);if(j(n,o)){const i=t.blockId,s=t.offset,l=n.getBlockById(i),c=n.getBlockText(l),a=Nl(c,s);a&&Object.entries(a).forEach(([u,f])=>{u.startsWith("comment-")&&e.push(f)})}const r=o.attributes;for(let i=0;i<r.length;i++){const s=r[i];s.name.startsWith("comment-")&&e.push(s.value)}return e}function r_(n){const t=n.selection.range;if(!t.isSimple())return[];if(t.start.blockId!==t.end.blockId)return[];if(t.isCollapsed())return ef(n,t.start);const{start:e,end:o}=t,r=ef(n,e),i=ef(n,o);return Za.default(r,i)}const i_=w("active-comments");function B3(n,t){n.rootContainer.querySelectorAll(`span.text.comment[comment-${t}],[data-type=editor-block].comment[comment-${t}]`).forEach(o=>{z(o,"active")})}function E3(n,t){const e=n.rootContainer.querySelector("span.text.comment.active,[data-type=editor-block].comment.active");if(!t)e&&k3(e).forEach(r=>B3(n,r));else{const o=t.toLocaleLowerCase();if(e){const i=k3(e);if(i.length===1&&i[0]===o)return;i.forEach(s=>B3(n,s))}const r=n.rootContainer.querySelectorAll(`span.text.comment[comment-${o}],[data-type=editor-block].comment[comment-${o}]`);if(r){r.forEach(s=>{A(s,"active")});const i=r[0];if(Po(i))n.selection.selectBlock(i,0);else{const s=F(i);d(i_,s,"block not found");const l=so(s,i);n.selection.selectBlock(s,l.start)}n.focus()}}}const Hz="";w("comment-editor");const{t:s_}=T,nf="comment-editor-readonly",qs="comment-editor-editing";class of{constructor(t,e,o){h(this,"root");h(this,"components");h(this,"handleEditorBlur",()=>{this.inactiveEditor()});h(this,"handleEditorFocus",()=>{this.editor.readonly||this.activeEditor()});h(this,"activeEditor",()=>{nt(this.root,qs)||A(this.root,qs)});h(this,"inactiveEditor",()=>{z(this.root,qs)});h(this,"handleInsertImg",async()=>{const{editor:t}=this.components,e=U(t.rootContainer),o=await No("image/*",{}),r={src:"",widthPercent:50},i={id:N(),type:"embed",embedType:"image",embedData:r},s=t.options.componentsOptions.image;s!=null&&s.defaultAlign&&(i.align=s.defaultAlign);const l=t.getFocusedBlock(),c=t.getBlockIndex(l),a=t.insertBlock(e,c+1,i);zt.getImageObject(t,a).replaceImage(0,o)});h(this,"handleReadonlyChange",t=>{t.readonly?(z(this.root,qs),A(this.root,nf)):(A(this.root,qs),z(this.root,nf))});h(this,"setDoc",t=>{const{components:{editor:e}}=this;e.doc.externalDoc.setDoc(t)});h(this,"getDoc",()=>{const{components:{editor:t}}=this;return t.doc.toJSON()});h(this,"isEmpty",()=>jl(this.getDoc()));h(this,"edit",()=>{const{editor:t}=this.components;t.readonly=!1,L0(t),this.activeEditor()});h(this,"clear",()=>{const t=Zo();this.setDoc(t)});h(this,"readonly",()=>{const{editor:t}=this.components;t.readonly=!0});h(this,"destroy",()=>{const{root:t,components:{editor:e,insertImgButton:o}}=this;o.onclick=null,e.destroy(),t.remove()});this.mainEditor=t,this.commentsProvider=e,this.doc=o,this.root=b("div",["comment-editor",nf],null),this.components=this.createEditor()}createEditor(){const t=b("div",["comment-editor-root"],this.root),{commentsProvider:e,mainEditor:o}=this,r=e.createCommentEditor(t,new Ru(this.doc));r.readonly=!0,r.addListener("readonlyChanged",this.handleReadonlyChange),r.addListener("focus",this.handleEditorFocus),r.addListener("blur",this.handleEditorBlur);const i=sr(this.root,"comment-editor-img",s_("comment.image"),Hw,void 0,o.clientId);return i.classList.add("comment-editor-img"),i.onclick=this.handleInsertImg,{editor:r,insertImgButton:i}}get editor(){return this.components.editor}}class l_{constructor(t){h(this,"handleBeforeKeyDown",(t,e)=>{if(jn(e,"Enter")){const{quickReply:o,updateLastCommentItem:r}=this.groupItem;return o.getReplyEditor().isEmpty()?(o.hideReplyEditor(),!0):(o.reply(),r(),!0)}return!1});this.groupItem=t}}class c_{constructor(t,e,o){h(this,"handleBeforeKeyDown",(t,e)=>{if(jn(e,"Enter")){const{quickReply:o}=this.groupItem,{comment:r,getCommentEditor:i}=this.commentItem,s=i();if(s.isEmpty())this.commentsProvider.localDeleteComment(r.id);else{const l=s.getDoc();this.commentsProvider.localUpdateComment(r,l),s.readonly()}return o.show(),!0}return!1});this.commentsProvider=t,this.groupItem=e,this.commentItem=o}}const a_=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
577
577
  <path fill-rule="evenodd" clip-rule="evenodd" d="M3.65499 6.6665C3.09433 6.6665 2.66699 7.1275 2.66699 7.67617C2.66699 8.2255 3.02633 8.64284 3.65499 8.6645C4.23833 8.6645 4.66399 8.26917 4.66399 7.67617C4.66399 7.1275 4.23899 6.6665 3.65499 6.6665ZM12.9883 6.6665C12.4277 6.6665 12.0003 7.1275 12.0003 7.67617C12.0003 8.2255 12.3597 8.64284 12.9883 8.6645C13.5717 8.6645 13.9973 8.26917 13.9973 7.67617C13.9973 7.1275 13.5723 6.6665 12.9883 6.6665ZM8.32166 6.6665C7.76099 6.6665 7.33399 7.1275 7.33399 7.67617C7.33399 8.2255 7.69299 8.64284 8.32166 8.6645C8.90499 8.6645 9.33066 8.26917 9.33066 7.67617C9.33066 7.1275 8.90566 6.6665 8.32166 6.6665Z" fill="currentColor"></path>
578
578
  </svg>`,d_=`<svg
579
579
  fill="currentColor"
@@ -604,7 +604,7 @@ width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
604
604
  <path d="M1.00098 12.9985L10.9995 2.99998" stroke="currentColor"/>
605
605
  <path d="M11.9113 6.16809L13.7433 3.79209C13.946 3.52009 14.0473 3.26142 14.0473 3.01609V2.90409C14.0473 2.71209 13.994 2.56009 13.8873 2.44809C13.786 2.33609 13.6473 2.28009 13.4713 2.28009C13.2953 2.28009 13.1567 2.33876 13.0553 2.45609C12.954 2.57342 12.9033 2.73609 12.9033 2.94409V3.07209H11.8873V2.88009C11.8873 2.59209 11.9513 2.33609 12.0793 2.11209C12.2127 1.88809 12.402 1.71209 12.6473 1.58409C12.8927 1.45609 13.1807 1.39209 13.5113 1.39209C13.8313 1.39209 14.1113 1.45876 14.3513 1.59209C14.5967 1.72542 14.7833 1.90409 14.9113 2.12809C15.0447 2.35209 15.1113 2.60009 15.1113 2.87209V3.00809C15.1113 3.24809 15.0687 3.46942 14.9833 3.67209C14.898 3.87476 14.7727 4.08276 14.6073 4.29609L13.2313 6.08009H15.1113V7.00009H11.9113V6.16809Z" fill="currentColor"/>
606
606
  </svg>
607
- `,ur=w("text-commands");function P3(n){const t={id:"more",name:T.t("commands.more"),icon:Q2,childrenType:"menu",childrenPlacement:"bottom-start",manualShowChildren:!0,children:[]},e={"style-bold":[T.t("commands.bold"),xt.isMac?T.t("commandDesc.mac.bold"):T.t("commandDesc.window.bold"),V_],"style-italic":[T.t("commands.italic"),xt.isMac?T.t("commandDesc.mac.italic"):T.t("commandDesc.window.italic"),q_],"style-underline":[T.t("commands.underline"),xt.isMac?T.t("commandDesc.mac.underline"):T.t("commandDesc.window.underline"),W_],"style-strikethrough":[T.t("commands.strikethrough"),xt.isMac?T.t("commandDesc.mac.strikethrough"):T.t("commandDesc.window.strikethrough"),G_],"style-code":[T.t("commands.code"),void 0,Z_]},o={"style-subscript":[T.t("commands.subscript"),void 0,Y_],"style-superscript":[T.t("commands.superscript"),void 0,Q_]};if(de(n)===0){const l=Object.entries(e).map(([c,[a,u,f]])=>({id:c,name:a,icon:f,desc:u}));return t.children=Object.entries(o).map(([c,[a,u,f]])=>({id:c,name:a,icon:f,desc:u})),l.concat(t)}const r=z_(n);function i([l,[c,a,u]]){const f=r.get(l);return f!==void 0?{id:l,name:c,value:f,states:f===!0?["checked"]:void 0,icon:u,desc:a}:{id:l,name:c,icon:u,desc:a}}const s=Object.entries(e).map(i);return t.children=Object.entries(o).map(i),s.concat(t)}function K_(n,t){const e=q(t),o=rt(t),r=Qe(n,t);return P3([]).map(i=>({blockId:e,blockType:o,blockKind:r,...i,groupIndex:500}))}function J_(n,t,e){d(ur,e.isSimple(),"nor a simple range");const{start:o,end:r}=e;d(ur,o.isSimple(),"is not a simple block position"),d(ur,r.isSimple(),"is not a simple block position"),d(ur,j(n,t),"invalid block type, not a text kind block");const i=q(t);d(ur,o.blockId===i&&r.blockId===i,"invalid range");const s=n.getBlockText(t);let l=[];o.offset===r.offset?o.offset!==0&&(l=Gt(s,o.offset-1,1).middle):l=Gt(s,o.offset,r.offset-o.offset).middle;const c=rt(t),a=Qe(n,t);return P3(l).map((u,f)=>({blockId:i,blockType:c,blockKind:a,...u,groupIndex:500,order:f*100}))}function X_(n,t,e,o,r,i){if(!j(n,t))return!1;if(!o.startsWith("style-"))return ur.warn(`unknown command: ${o}`),!1;const s=r==null?void 0:r.value,l=typeof s;if(l!=="string"&&l!=="number"&&l!=="boolean"&&l!=="undefined")return ur.warn(`invalid value type, accept string | number | boolean | undefined, current is ${l}`),!1;const c=U_(n,t,e,o,s);return i.result=c,!0}const tN=w("text-command-provider");class Ln{constructor(t){h(this,"id","TextCommandProvider");h(this,"emptyTextBlockAttributes",new Map);h(this,"colorItem");h(this,"updateButtonColor",()=>{const t=gu(this.editor,this.getEmptyTextBlockColor);this.colorItem.updateButtonColor(t)});h(this,"handleChangeColor",(t,e)=>{if(t==="color"||t==="backgroundColor")zp(this.editor,t,e,this.setEmptyTextBlockColor);else{const o=["clearAll","clearColor","clearBackground"];Up(this.editor,o[e],this.setEmptyTextBlockColor)}});h(this,"handleBeforePopupPalette",()=>{const t=gu(this.editor,this.getEmptyTextBlockColor);this.colorItem.updatePaletteColor(t)});h(this,"getEmptyTextBlockColor",(t,e)=>{const o=this.getEmptyBlockTextAttributes(t,e);return qd(o)});h(this,"setEmptyTextBlockColor",(t,e,o,r)=>{var s;const i=(s=this.emptyTextBlockAttributes.get(e))!=null?s:{};Kg(i,o,r),this.emptyTextBlockAttributes.set(e,i)});this.editor=t,this.colorItem=t.addCustom("text-color-item",()=>new SB(t)),this.colorItem.addListener("onClick",this.handleChangeColor),this.colorItem.addListener("beforePopup",this.handleBeforePopupPalette)}destroy(){this.colorItem.destroy()}getAvailableCommands(t,e,o){if(!j(t,e))return[];let r;if(W(t,e)===0?r=this.getCommandsOnEmptyText(t,e).map(Ln.toTextCommand):r=J_(t,e,o).map(Ln.toTextCommand),t.selection.range.isSimple()){this.updateButtonColor();const l={...this.colorItem,blockId:q(e),blockKind:Qe(t,e),blockType:rt(e),groupIndex:500,order:350};r.push(l)}return r}executeCommand(t,e,o,r,i,s){if(!j(t,e))return!1;let l=i.value;l===void 0&&(l=!r.value);const c=Ln.fromTextCommandId(r.id);return c.startsWith("style-")&&W(t,e)===0?this.executeCommandOnEmptyText(e,r,{value:l}):X_(t,e,o,c,{value:l},s)}executeCommandOnEmptyText(t,e,o){let r=this.emptyTextBlockAttributes.get(q(t));r||(r={},this.emptyTextBlockAttributes.set(q(t),r));const i=Ln.fromTextCommandId(e.id),s=o.value;return s==null||s===!1?(delete r[i],!0):(r[i]=o.value,!0)}getCommandsOnEmptyText(t,e){var l;const o=q(e),r=(l=this.emptyTextBlockAttributes.get(o))!=null?l:{};return K_(t,e).map(c=>{const a=r[c.id];return{...c,value:a,states:a?["checked"]:void 0}})}getEmptyBlockTextAttributes(t,e){var r;const o=Y.default((r=this.emptyTextBlockAttributes.get(e))!=null?r:{});if(Array.from(Object.entries(o)).forEach(([i,s])=>{s||delete o[i]}),Object.keys(o).length!==0)return o}static toTextCommand(t){return t.children&&(t.children=t.children.map(Ln.toTextCommand)),{...t,id:`text/${t.id}`}}static fromTextCommandId(t){const e="text/";return d(tN,t.startsWith(e),`invalid item id: ${t}`),t.substring(e.length)}static fromTextCommand(t){return{...t,id:this.fromTextCommandId(t.id)}}static toTextCommands(t){return t.map(Ln.toTextCommand)}static fromTextCommands(t){return t.map(Ln.fromTextCommand)}}const eN={commands:{bold:"\u7C97\u4F53",italic:"\u659C\u4F53",underline:"\u4E0B\u5212\u7EBF",strikethrough:"\u5220\u9664\u7EBF",code:"\u884C\u5185\u4EE3\u7801",subscript:"\u4E0B\u6807",superscript:"\u4E0A\u6807",more:"\u66F4\u591A"},commandDesc:{mac:{bold:"\u2318+B",italic:"\u2318+I",underline:"\u2318+U",strikethrough:"\u2318+D"},window:{bold:"Ctrl+B",italic:"Ctrl+I",underline:"Ctrl+U",strikethrough:"Ctrl+D"}}},nN={commands:{bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",code:"Inline Code",subscript:"Subscript",superscript:"Superscript",more:"More"},commandDesc:{mac:{bold:"\u2318+B",italic:"\u2318+I",underline:"\u2318+U",strikethrough:"\u2318+D"},window:{bold:"Ctrl+B",italic:"Ctrl+I",underline:"Ctrl+U",strikethrough:"Ctrl+D"}}};T.mergeLang({"zh-CN":eN,"en-US":nN});var j3=(n=>(n.Card="card",n.Preview="preview",n))(j3||{});const oN=`<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="none">
607
+ `,ur=w("text-commands");function P3(n){const t={id:"more",name:T.t("commands.more"),icon:Q2,childrenType:"menu",childrenPlacement:"bottom-start",manualShowChildren:!0,children:[]},e={"style-bold":[T.t("commands.bold"),xt.isMac?T.t("commandDesc.mac.bold"):T.t("commandDesc.window.bold"),V_],"style-italic":[T.t("commands.italic"),xt.isMac?T.t("commandDesc.mac.italic"):T.t("commandDesc.window.italic"),q_],"style-underline":[T.t("commands.underline"),xt.isMac?T.t("commandDesc.mac.underline"):T.t("commandDesc.window.underline"),W_],"style-strikethrough":[T.t("commands.strikethrough"),xt.isMac?T.t("commandDesc.mac.strikethrough"):T.t("commandDesc.window.strikethrough"),G_],"style-code":[T.t("commands.code"),void 0,Z_]},o={"style-subscript":[T.t("commands.subscript"),void 0,Y_],"style-superscript":[T.t("commands.superscript"),void 0,Q_]};if(de(n)===0){const l=Object.entries(e).map(([c,[a,u,f]])=>({id:c,name:a,icon:f,desc:u}));return t.children=Object.entries(o).map(([c,[a,u,f]])=>({id:c,name:a,icon:f,desc:u})),l.concat(t)}const r=z_(n);function i([l,[c,a,u]]){const f=r.get(l);return f!==void 0?{id:l,name:c,value:f,states:f===!0?["checked"]:void 0,icon:u,desc:a}:{id:l,name:c,icon:u,desc:a}}const s=Object.entries(e).map(i);return t.children=Object.entries(o).map(i),s.concat(t)}function K_(n,t){const e=q(t),o=rt(t),r=Qe(n,t);return P3([]).map(i=>({blockId:e,blockType:o,blockKind:r,...i,groupIndex:500}))}function J_(n,t,e){d(ur,e.isSimple(),"nor a simple range");const{start:o,end:r}=e;d(ur,o.isSimple(),"is not a simple block position"),d(ur,r.isSimple(),"is not a simple block position"),d(ur,j(n,t),"invalid block type, not a text kind block");const i=q(t);d(ur,o.blockId===i&&r.blockId===i,"invalid range");const s=n.getBlockText(t);let l=[];o.offset===r.offset?o.offset!==0&&(l=Gt(s,o.offset-1,1).middle):l=Gt(s,o.offset,r.offset-o.offset).middle;const c=rt(t),a=Qe(n,t);return P3(l).map((u,f)=>({blockId:i,blockType:c,blockKind:a,...u,groupIndex:500,order:f*100}))}function X_(n,t,e,o,r,i){if(!j(n,t))return!1;if(!o.startsWith("style-"))return ur.warn(`unknown command: ${o}`),!1;const s=r==null?void 0:r.value,l=typeof s;if(l!=="string"&&l!=="number"&&l!=="boolean"&&l!=="undefined")return ur.warn(`invalid value type, accept string | number | boolean | undefined, current is ${l}`),!1;const c=U_(n,t,e,o,s);return i.result=c,!0}const tN=w("text-command-provider");class Mn{constructor(t){h(this,"id","TextCommandProvider");h(this,"emptyTextBlockAttributes",new Map);h(this,"colorItem");h(this,"updateButtonColor",()=>{const t=gu(this.editor,this.getEmptyTextBlockColor);this.colorItem.updateButtonColor(t)});h(this,"handleChangeColor",(t,e)=>{if(t==="color"||t==="backgroundColor")zp(this.editor,t,e,this.setEmptyTextBlockColor);else{const o=["clearAll","clearColor","clearBackground"];Up(this.editor,o[e],this.setEmptyTextBlockColor)}});h(this,"handleBeforePopupPalette",()=>{const t=gu(this.editor,this.getEmptyTextBlockColor);this.colorItem.updatePaletteColor(t)});h(this,"getEmptyTextBlockColor",(t,e)=>{const o=this.getEmptyBlockTextAttributes(t,e);return qd(o)});h(this,"setEmptyTextBlockColor",(t,e,o,r)=>{var s;const i=(s=this.emptyTextBlockAttributes.get(e))!=null?s:{};Kg(i,o,r),this.emptyTextBlockAttributes.set(e,i)});this.editor=t,this.colorItem=t.addCustom("text-color-item",()=>new SB(t)),this.colorItem.addListener("onClick",this.handleChangeColor),this.colorItem.addListener("beforePopup",this.handleBeforePopupPalette)}destroy(){this.colorItem.destroy()}getAvailableCommands(t,e,o){if(!j(t,e))return[];let r;if(W(t,e)===0?r=this.getCommandsOnEmptyText(t,e).map(Mn.toTextCommand):r=J_(t,e,o).map(Mn.toTextCommand),t.selection.range.isSimple()){this.updateButtonColor();const l={...this.colorItem,blockId:q(e),blockKind:Qe(t,e),blockType:rt(e),groupIndex:500,order:350};r.push(l)}return r}executeCommand(t,e,o,r,i,s){if(!j(t,e))return!1;let l=i.value;l===void 0&&(l=!r.value);const c=Mn.fromTextCommandId(r.id);return c.startsWith("style-")&&W(t,e)===0?this.executeCommandOnEmptyText(e,r,{value:l}):X_(t,e,o,c,{value:l},s)}executeCommandOnEmptyText(t,e,o){let r=this.emptyTextBlockAttributes.get(q(t));r||(r={},this.emptyTextBlockAttributes.set(q(t),r));const i=Mn.fromTextCommandId(e.id),s=o.value;return s==null||s===!1?(delete r[i],!0):(r[i]=o.value,!0)}getCommandsOnEmptyText(t,e){var l;const o=q(e),r=(l=this.emptyTextBlockAttributes.get(o))!=null?l:{};return K_(t,e).map(c=>{const a=r[c.id];return{...c,value:a,states:a?["checked"]:void 0}})}getEmptyBlockTextAttributes(t,e){var r;const o=Y.default((r=this.emptyTextBlockAttributes.get(e))!=null?r:{});if(Array.from(Object.entries(o)).forEach(([i,s])=>{s||delete o[i]}),Object.keys(o).length!==0)return o}static toTextCommand(t){return t.children&&(t.children=t.children.map(Mn.toTextCommand)),{...t,id:`text/${t.id}`}}static fromTextCommandId(t){const e="text/";return d(tN,t.startsWith(e),`invalid item id: ${t}`),t.substring(e.length)}static fromTextCommand(t){return{...t,id:this.fromTextCommandId(t.id)}}static toTextCommands(t){return t.map(Mn.toTextCommand)}static fromTextCommands(t){return t.map(Mn.fromTextCommand)}}const eN={commands:{bold:"\u7C97\u4F53",italic:"\u659C\u4F53",underline:"\u4E0B\u5212\u7EBF",strikethrough:"\u5220\u9664\u7EBF",code:"\u884C\u5185\u4EE3\u7801",subscript:"\u4E0B\u6807",superscript:"\u4E0A\u6807",more:"\u66F4\u591A"},commandDesc:{mac:{bold:"\u2318+B",italic:"\u2318+I",underline:"\u2318+U",strikethrough:"\u2318+D"},window:{bold:"Ctrl+B",italic:"Ctrl+I",underline:"Ctrl+U",strikethrough:"Ctrl+D"}}},nN={commands:{bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",code:"Inline Code",subscript:"Subscript",superscript:"Superscript",more:"More"},commandDesc:{mac:{bold:"\u2318+B",italic:"\u2318+I",underline:"\u2318+U",strikethrough:"\u2318+D"},window:{bold:"Ctrl+B",italic:"Ctrl+I",underline:"Ctrl+U",strikethrough:"Ctrl+D"}}};T.mergeLang({"zh-CN":eN,"en-US":nN});var j3=(n=>(n.Card="card",n.Preview="preview",n))(j3||{});const oN=`<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="none">
608
608
  <g clip-path="url(#clip0)">
609
609
  <path d="M6.01 10.4886C5.85 10.4886 5.7 10.4286 5.58 10.3086L3.98 8.71859C3.35 8.07859 3 7.23859 3 6.34859C3 5.45859 3.35 4.60859 3.98 3.97859C5.29 2.66859 7.41 2.66859 8.72 3.97859L10.31 5.56859C10.55 5.80859 10.55 6.18859 10.31 6.42859C10.07 6.66859 9.69 6.66859 9.45 6.42859L7.86 4.83859C7.03 4.00859 5.68 4.00859 4.85 4.83859C4.45 5.23859 4.23 5.77859 4.23 6.34859C4.23 6.91859 4.45 7.44859 4.85 7.85859L6.44 9.44859C6.68 9.68859 6.68 10.0686 6.44 10.3086C6.32 10.4286 6.16 10.4886 6.01 10.4886ZM11.65 14.9986C10.79 14.9986 9.93 14.6686 9.28 14.0186L7.4 12.1386C7.16 11.8986 7.16 11.5186 7.4 11.2786C7.64 11.0386 8.02 11.0386 8.26 11.2786L10.14 13.1586C10.97 13.9886 12.32 13.9886 13.15 13.1586C13.55 12.7586 13.77 12.2186 13.77 11.6486C13.77 11.0786 13.55 10.5486 13.15 10.1386L11.28 8.25859C11.04 8.01859 11.04 7.63859 11.28 7.39859C11.52 7.15859 11.9 7.15859 12.14 7.39859L14.02 9.27859C14.65 9.90859 15 10.7486 15 11.6486C15 12.5386 14.65 13.3886 14.02 14.0186C13.37 14.6686 12.51 14.9986 11.65 14.9986Z" fill="#5587F0"/>
610
610
  <path d="M10.88 10.8604C10.67 11.0704 10.32 11.0704 10.1 10.8604L7.64004 8.40039C7.43004 8.19039 7.43004 7.84039 7.64004 7.62039C7.85004 7.41039 8.20004 7.41039 8.42004 7.62039L10.88 10.0804C11.1 10.3004 11.1 10.6404 10.88 10.8604Z" fill="#5587F0"/>
@@ -683,4 +683,4 @@ width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
683
683
  `:`[${i.fileName}]
684
684
  `:i.src?`[${i.fileName}](${n.doc.buildResourceUrl(i.src,{withToken:!0})})`:`[${i.fileName}]`}const IN={embedType:"office",createEmbedContent:yN,getBlockProperties:BN,convertTo:EN},Zz="",xN={media:{upload:{failed:'<div class="line-1">{name} \u4E0A\u4F20\u5931\u8D25</div><div class="line-2">\u7F51\u7EDC\u670D\u52A1\u5F02\u5E38\uFF0C\u4F60\u53EF\u4EE5 <a href="" class="retry-upload">\u91CD\u8BD5</a></div>'},load:{failed:'<div class="line-1">{name} \u52A0\u8F7D\u5931\u8D25</div><div class="line-2">\u7F51\u7EDC\u670D\u52A1\u5F02\u5E38\uFF0C\u4F60\u53EF\u4EE5 <a href="" class="retry-upload">\u91CD\u8BD5</a></div>'},audio:{menuItem:"\u97F3\u9891",abstract:"\u97F3\u9891"},video:{menuItem:"\u89C6\u9891",abstract:"\u89C6\u9891"}}},TN={media:{upload:{failed:'<div class="line-1">{name} upload failed</div><div class="line-2">The network service is abnormal, you can <a href="" class="retry-upload">Try again</a></div>'},load:{failed:'<div class="line-1">{name} loading failed</div><div class="line-2">The network service is abnormal, you can <a href="" class="retry-upload">Try again</a></div>'},audio:{menuItem:"Audio",abstract:"Audio"},video:{menuItem:"Video",abstract:"Video"}}};T.mergeLang({"zh-CN":xN,"en-US":TN});var mn=(n=>(n.AUDIO="audio",n.VIDEO="video",n))(mn||{}),Gs=(n=>(n.Empty="empty",n.Progress="progress",n.Error="error",n))(Gs||{});const G3=10*1024*1024,SN=["wav","mp3","aac","ogg","webm","flac"],DN=["ogg","mp4","webm"],LN=()=>{};function Z3(n){var u,f,m,C,v,B;const t=(u=n.getComponentOptions("media"))!=null?u:{},{allowedMedias:e,maxSize:o,callbacks:r}=t,i=(f=e==null?void 0:e.audio)!=null?f:SN,s=(m=e==null?void 0:e.video)!=null?m:DN,l=(C=o==null?void 0:o.audio)!=null?C:G3,c=(v=o==null?void 0:o.video)!=null?v:G3,a=(B=r==null?void 0:r.onError)!=null?B:LN;return{allowedMedias:{audio:i,video:s},maxSize:{audio:l,video:c},callbacks:{onError:a}}}const MN=w("file-utils");function RN(n){d(MN,n instanceof File,`The file: ${n} isn't instance of File`);const{name:t}=n;if(!t)return"";const e=t.lastIndexOf(".");return e===-1?"":t.slice(e+1)}function Y3(n,t){const e=i=>i.map(s=>`.${s}`).join(","),{allowedMedias:o}=Z3(n),r=o[t];return r?e(r):"*"}function AN(n,t,e){const{maxSize:o,callbacks:r,allowedMedias:i}=Z3(t),{[e]:s}=o,{[e]:l}=i;if(s&&n.size>s){const a=new Error("media is too large");return a.code=`MaxMediaSize-${e}`,r!=null&&r.onError&&(r==null||r.onError(t,a)),a}const c=RN(n);if(l&&!l.includes(c)){const a=new Error(`media file is not allowed: ${c}`);return a.code="NotAllowedFile",r!=null&&r.onError&&(r==null||r.onError(t,a)),a}return!0}function ON(n){return n===Gs.Empty||n===Gs.Error}const pe=w("media");class _N{constructor(t){h(this,"mediaContainer",null);h(this,"media",null);h(this,"abstract",null);h(this,"handleMediaLoadError",(t,e)=>{if(!e.target||!(e.target instanceof Node)||!(e.target instanceof Element?e.target:e.target.parentElement))return;const r=F(e.target);if(!r||!r.contains(this.mediaContainer))return;const i=this.renderError();this.updateMediaContent(i)});h(this,"handleRetry",async t=>{if(t.readonly)return;d(pe,this.abstract,"no abstract");const{mediaType:e}=this.abstract,o=Y3(t,e),r=await No(o);this.handleUploadFile(r)});h(this,"handleUploadFile",async t=>{d(pe,this.abstract,"no abstract"),d(pe,this.mediaContainer,"The media element not exist");const{editor:e}=this.options,{mediaType:o}=this.abstract,r=F(this.mediaContainer);d(pe,r,"The block element not exist");const i=e.getBlockData(r);if(!!AN(t,e,o))try{const{resourceId:s}=await e.doc.uploadResource(t,{onProgress:f=>{this.renderProgress(f,t)}}),{name:l,type:c,size:a}=t,u={...i,embedData:{...i.embedData,src:s,fileName:l,fileSize:a,fileType:c}};e.updateBlockData(r,u)}catch{this.renderRetry()}});h(this,"destroy",()=>{this.mediaContainer=null});this.options=t}bindMediaEvent(){const{editor:t}=this.options;this.media&&t.domEvents.addEventListener(this.media,"error",this.handleMediaLoadError)}unbindMediaEvent(){const{editor:t}=this.options;this.media&&t.domEvents.removeEventListener(this.media,"error",this.handleMediaLoadError)}updateMediaContent(t){d(pe,this.mediaContainer,"The media element not exist"),this.mediaContainer.innerHTML="",this.mediaContainer.append(t)}renderError(){d(pe,this.abstract,"no abstract");const{editor:t,createMediaElement:e}=this.options,{mediaIcon:o,mediaName:r}=this.abstract;d(pe,this.mediaContainer,"The media element not exist");const i=F(this.mediaContainer);d(pe,i,"The block element not exist");const s=t.getBlockData(i),l=s.embedData.src,c=b("div",["media-error","embed-selected-content","embed-hover-content"],null),a=b("span",["media-error-icon"],c);a.innerHTML=o;const u=b("div",[],c);u.innerHTML=T.t("media.load.failed",{name:r}),c.appendChild(u);const f=u.querySelector("a");return d(pe,f,"The element not exist"),t.domEvents.addEventListener(f,"click",(m,C)=>{if(C.preventDefault(),C.target instanceof HTMLElement&&C.target.tagName==="A"){const v=b("div",["media-element"],null),B=this.getResourceUrl(l),y=e(m,v,s,B);this.unbindMediaEvent(),this.media=y,this.bindMediaEvent(),this.updateMediaContent(v)}}),c}renderRetry(){d(pe,this.abstract,"no abstract");const{editor:t}=this.options,{mediaIcon:e,mediaName:o}=this.abstract,r=b("div",["media-error","embed-selected-content","embed-hover-content"],null),i=b("span",["media-error-icon"],r);i.innerHTML=e;const s=b("div",[],r);s.innerHTML=T.t("media.upload.failed",{name:o}),r.appendChild(s);const l=s.querySelector("a");d(pe,l,"The element not exist"),t.domEvents.addEventListener(l,"click",this.handleRetry),this.updateMediaContent(r)}renderProgress(t,e){d(pe,this.mediaContainer,"The media element not exist");const o=this.mediaContainer.querySelector(":scope .media-progress"),r=t===-1||t===100?100:t;if(o){const{updateProgressElement:i}=this.options;i(o,r)}else{const{createProgressElement:i}=this.options,s=b("div",["media-progress"],null);i(s,r,e),this.updateMediaContent(s)}}renderMediaElement(t){d(pe,this.mediaContainer,"The media element not exist");const e=this.mediaContainer.querySelector(":scope > .media-element"),{createMediaElement:o,updateMediaElement:r,editor:i}=this.options,s=this.getResourceUrl(t.embedData.src);if(e){const l=r(i,e,t,s);this.unbindMediaEvent(),this.media=l,this.bindMediaEvent()}else{const l=b("div",["media-element"],null),c=o(i,l,t,s);this.unbindMediaEvent(),this.media=c,this.bindMediaEvent(),this.updateMediaContent(l)}}renderEmpty(){d(pe,this.abstract,"no abstract"),d(pe,this.mediaContainer,"The media element not exist");const t=b("div",["media-empty","embed-selected-content","embed-hover-content"],this.mediaContainer);t.innerHTML=this.abstract.mediaIcon,this.updateMediaContent(t)}getResourceUrl(t){const{editor:e}=this.options;return e.doc.buildResourceUrl(t)}render(t,e){const{src:o}=t.embedData;(!this.mediaContainer||!e.contains(this.mediaContainer))&&(this.mediaContainer=b("div",["media"],e)),ON(o)?o===Gs.Empty&&this.renderEmpty():this.renderMediaElement(t)}setAbstract(t){this.abstract=t}}w("media-embed");class Q3{constructor(){h(this,"handleInsertEmptyEmbed",async(t,e)=>{var u;const{containerId:o,blockIndex:r}=e;let i;(u=e.data)!=null&&u.file&&(i=e.data.file);const s=Y3(t,this.embedType);if(i=i!=null?i:await No(s,{}),!i)return null;const l={id:N(),type:"embed",embedType:this.embedType,embedData:{src:Gs.Empty}},c=t.insertBlock(o,r,l);return await this.getMedia(t,l.id).handleUploadFile(i),c})}getMedia(t,e){const o=t.addCustom(`media-${e}`,()=>new _N({editor:t,createMediaElement:this.createMediaElement,updateMediaElement:this.updateMediaElement,createProgressElement:this.createProgressElement,updateProgressElement:this.updateProgressElement}));return o.setAbstract({...this.abstract}),o}getOptions(){const{menuItem:t,mediaIcon:e,mediaName:o,order:r,group:i}=this.abstract;return{name:o,insertEmbedCommandItems:[{id:`insert-${this.embedType}`,name:t,icon:e,order:r,group:i,subText:fe(`insert-${this.embedType}`)}],handleInsertEmptyEmbed:this.handleInsertEmptyEmbed}}createEmbedContent(t,e,o){const{id:r}=o;this.getMedia(t,r).render(o,e)}handleUpdateBlock(t,e,o){const{id:r}=o,i=this.getMedia(t,r),s=it(e);return i.render(o,s),!0}handleDeleteBlock(t,e){const o=e.id;this.getMedia(t,o).destroy()}convertTo(t,e,o,r){const i=e.embedData,s=t.doc.buildResourceUrl(i.src,{withToken:!0});return r==="html"?`<${i.type} src="${s}" />`:r==="markdown"?`![${i.src}](${s})`:s}}function K3(n,t){const e=b("div",["uploading-progress-mask"],n),o=b("div",["uploading-progress-bar"],e),r=b("div",["uploading-progress-bar-value"],o);r.style.width=`${t}%`}function J3(n,t){const e=n.querySelector(".uploading-progress-bar-value");e&&(e.style.width=`${t}%`)}const NN=w("media-audio");class $N extends Q3{constructor(){super(...arguments);h(this,"embedType",mn.AUDIO);h(this,"abstract",{mediaIcon:nB,mediaName:T.t(`media.${mn.AUDIO}.menuItem`),menuItem:T.t(`media.${mn.AUDIO}.menuItem`),order:800,mediaType:mn.AUDIO,group:"common"});h(this,"updateProgressElement",J3)}getBlockProperties(){return{abstract:`[${T.t(`media.${mn.AUDIO}.abstract`)}]`}}createMediaElement(e,o,r,i){const s=b("div",["audio-container","embed-hover-content","embed-selected-content"],o),l=b("audio",[],s);return l.innerHTML="Your browser does not support the <code>audio</code> element.",l.controls=!0,l.src=i,l}updateMediaElement(e,o,r,i){const s=o.querySelector(":scope .audio-container > audio");return d(NN,s,"The media element not exist"),s.src!==i&&(s.src=i),s}createProgressElement(e,o){const r=b("audio",[],e);r.innerHTML="Your browser does not support the <code>audio</code> element.",r.controls=!0,r.src="about:blank",K3(e,o)}}const df=new $N;w("video-resizer");function X3(n){return n&&Te(n)&&Oe(n)==="video"}const PN=50;class jN{constructor(t){h(this,"currentResizableElement",null);h(this,"resizing",!1);h(this,"handleHoveringBlockChange",(t,e)=>{if(!this.resizing&&(e&&X3(e)&&this.disableBlockResize(e),t&&X3(t))){const o=this.getVideoElement(t);if(!o)return;this.enableBlockResize(t,o)}});h(this,"handleResizing",(t,e)=>{if(this.resizing=!0,!this.currentResizableElement)return;const o=t.getBlock();if(!o)return;const r=o.getBoundingClientRect().width,i=Math.min(Math.max(e.width,PN),r);this.currentResizableElement.style.width=`${i}px`});h(this,"handleResized",t=>{this.resizing=!1;const e=t.getBlock();if(!this.currentResizableElement||!e)return;const o=this.editor.getBlockData(e),{width:r}=this.currentResizableElement.getBoundingClientRect();this.editor.updateBlockData(e,{...o,width:r})});this.editor=t,Nt.get(t).addListener("change",this.handleHoveringBlockChange)}destroy(){this.currentResizableElement=null,Nt.get(this.editor).removeListener("change",this.handleHoveringBlockChange)}getVideoElement(t){return it(t).querySelector(":scope .video-container > video")}disableBlockResize(t){const e=this.editor.findCustom(`${q(t)}-resizer`);e&&e.disableResize()}enableBlockResize(t,e){const o=this.editor.addCustom(`${q(t)}-resizer`,()=>new Yc(this.editor,{resize:["top-left","top-right","bottom-left","bottom-right"]}));o.enableResize(t,e),o.removeListener("resizing",this.handleResizing),o.removeListener("resized",this.handleResized),o.addListener("resizing",this.handleResizing),o.addListener("resized",this.handleResized),this.currentResizableElement=e}}const HN=w("video");class FN extends Q3{constructor(){super(...arguments);h(this,"embedType",mn.VIDEO);h(this,"abstract",{mediaName:T.t(`media.${mn.VIDEO}.menuItem`),mediaIcon:oB,menuItem:T.t(`media.${mn.VIDEO}.menuItem`),order:700,mediaType:mn.VIDEO,group:"common"});h(this,"updateProgressElement",J3);h(this,"createProgressElement",(e,o,r)=>{const i=b("video",["progress-video"],e);i.innerHTML="Your browser does not support the <code>audio</code> element.",i.controls=!0,K3(e,o),pl(r).then(s=>{const l=e.querySelector(".progress-video");l&&Cd(e)&&(l.src=s)})})}getBlockProperties(){return{abstract:`[${T.t(`media.${mn.VIDEO}.abstract`)}]`}}createMediaElement(e,o,r,i){const s=b("div",["video-container","embed-selected-content","drag-preview-element"],o),l=b("video",[],s);return l.innerHTML="Your browser does not support the <code>video</code> element.",l.controls=!0,l.src=i,e.addCustom("video-resizer",()=>new jN(e)),r.width&&(l.style.width=`${r.width}px`),l}updateMediaElement(e,o,r,i){const s=o.querySelector(":scope .video-container > video");return d(HN,s,"The media element not exist"),s.src!==i&&(s.src=i),s}}const uf=new FN,Yz="",zN={version:{latest:"\u5F53\u524D\u7248\u672C",insert:"{name} \u6DFB\u52A0",delete:"{name} \u5220\u9664",goBack:"\u8FD4\u56DE",revertVersion:"\u8FD8\u539F\u5185\u5BB9",play:"\u64AD\u653E\u5386\u53F2\u64CD\u4F5C",versionList:"\u5386\u53F2\u8BB0\u5F55 {count}",unknown:"\u672A\u77E5\u7248\u672C",restoreFrom:"\u56DE\u6EDA\u81EA\u7248\u672C {from}",restoreInfo:"\u56DE\u6EDA\u7684\u7248\u672C\u6682\u4E0D\u652F\u6301\u4E0E\u4E0A\u4E00\u7248\u672C\u5BF9\u6BD4"}},UN={version:{latest:"Latest",insert:"Added by {name}",delete:"Deleted by {name}",goBack:"Back",revertVersion:"Revert",play:"Play",versionList:"Versions ({count})",unknown:"Unknown version",restoreFrom:"Reverted from {from}",restoreInfo:"The rolled back version does not currently support comparison with the previous version."}};T.mergeLang({"zh-CN":zN,"en-US":UN});var tC=(n=>(n.NEW="history-new",n.NEW_CHILD="history-new-child",n.DELETED="history-deleted",n.UPDATED="history-updated",n.HISTORY="history",n))(tC||{});const ui="--op-color",hi="--op-selected-color",Qz="";class VN{constructor(t){h(this,"root");this.content=t;const e=b("div",["dialog-root"],null);e.append(t),this.root=e}show(t=document.body){t.append(this.root)}hide(){this.root.remove()}destroy(){}}const{t:fi}=T,eC=w("version-list");class qN{constructor(t){h(this,"activeVersionElement");h(this,"versionsList");h(this,"versionsListHeader");h(this,"handleClickVersionItem",t=>{const o=t.target.closest(".dialog-version-list-item");if(this.isVersionElement(o)){this.toggleActiveVersionElement(o);const r=this.getVersionFromElement(o),{onSelectVersion:i}=this.options;i(r)}});this.options=t;const{versions:e,defaultSelectedIndex:o=0}=t,r=b("div",["version-dialog-list-header"],null,"count");r.innerText=fi("version.versionList",{count:`${e.length}`});const i=b("div",["version-dialog-list"],null),s=this.convertVersionsToFragment(e);i.append(s);const l=i.children[o];A(l,"active"),this.activeVersionElement=l,this.versionsList=i,this.versionsListHeader=r,i.onclick=this.handleClickVersionItem}get isSelectedFirstVersion(){return!!this.activeVersionElement&&this.versionsList.firstChild===this.activeVersionElement}get isSelectedLastVersion(){return!!this.activeVersionElement&&this.versionsList.lastChild===this.activeVersionElement}get beforeVersion(){return d(eC,this.activeVersionElement,"No active version element"),this.activeVersionElement.nextElementSibling?this.activeVersionElement.nextElementSibling.versionData:null}get beforeMajorVersion(){d(eC,this.activeVersionElement,"No active version element");let t=this.activeVersionElement.nextElementSibling;for(;t;){if(t.versionData.type)return t.versionData;t=t.nextElementSibling}return null}convertVersionsToFragment(t){const e=document.createDocumentFragment(),o=i=>{var l;let s;if(i.version!==-1){const c=new Date((l=i.created)!=null?l:i.version);s=`${c.toLocaleDateString()} ${c.toLocaleTimeString()}`}else s=fi("version.latest");return s},r=(i,s,l,c=!1)=>{var C;const a=b("div",["dialog-version-list-item"],e);a.versionData=i,s&&A(a,"child");const u=b("div",["dialog-version-list-item-title"],a);if(b("div",["dialog-version-list-item-date"],u,o(i)),c&&b("div",["dialog-version-list-item-now-ver"],u,fi("version.latest")),typeof i.source=="object"&&((C=i.source)==null?void 0:C.restore)){const v=i.source.restore,B=l.find(R=>R.version==v),y=B?o(B):fi("version.unknown"),S=fi("version.restoreFrom",{from:y}),I=fi("version.restoreInfo"),M=b("div",["dialog-version-item-from-container"],a);b("div",["dialog-version-item-from-main"],M,S),b("div",["dialog-version-item-from-info"],M,I)}const f=b("ul",["dialog-version-list-item-authors"],a),m=v=>{const B=b("li",["dialog-version-list-item-author"],f),y=b("span",["dialog-version-list-item-mark-author"],B);y.style.background=this.options.getMarkColor(v),b("span",["dialog-version-list-item-author-name"],B,v.displayName)};if(this.options.useCreatedBy)if(i.createdBy){const v=i.createdBy;m(v)}else i.authors&&i.authors.length>0&&i.authors.forEach(v=>{m(v)});else if(i.authors&&i.authors.length>0)i.authors.forEach(v=>{m(v)});else if(i.createdBy){const v=i.createdBy;m(v)}};return t.forEach((i,s)=>{r(i,!1,t,s===0),i.minorVersions&&i.minorVersions.length>0&&i.minorVersions.forEach(l=>{r(l,!0,t,!1)})}),e}isVersionElement(t){return t?nt(t,"dialog-version-list-item"):!1}getVersionFromElement(t){return t.versionData}get activeVersion(){return this.getVersionFromElement(this.activeVersionElement)}toggleActiveVersionElement(t){this.activeVersionElement!==t&&(z(this.activeVersionElement,"active"),A(t,"active"),this.activeVersionElement=t)}selectVersionByVersionNum(t){const e=Array.from(this.versionsList.children).find(o=>o.versionData.version===t);return this.isVersionElement(e)?(this.toggleActiveVersionElement(e),this.getVersionFromElement(e)):null}render(t){t.innerHTML="",t.append(this.versionsListHeader,this.versionsList)}destroy(){this.versionsList.onclick=null}}class WN{constructor(t,e){this.doc=t,this.user=e}onDeleteBlock(t,e){this.doc.onDeleteBlock(t,e,this.user)}onInsertBlock(t,e,o){this.doc.onInsertBlock(t,e,o,this.user)}onUpdateBlockText(t,e,o){this.doc.onUpdateBlockText(t,e,o,this.user)}onUpdateBlockData(t,e,o){this.doc.onUpdateBlockData(t,e,o,this.user)}onCreateContainer(t,e){this.doc.onCreateContainer(t,e,this.user)}onCreateComment(){}onDeleteComment(){}onDeleteContainer(){}onUpdateComment(){}}function GN(n){return new Promise(t=>{setTimeout(t,n)})}async function ZN(n,t,e,o){for(const r of e){const i=new WN(n,r.user);t.parseHistoryData(r,i),o.play&&await GN(o.speed||150)}}const YN=`<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
685
685
  <path d="M0 0h24v24H0z" fill="none"/><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
686
- </svg>`,{t:hf}=T;class QN{constructor(t){h(this,"goBackButton");h(this,"playButton");h(this,"revertButton");this.options=t;const e=b("button",["dialog-text-button"],null),o=b("span",["dialog-button-icon"],e);o.innerHTML=YN,b("span",["dialog-button-text"],e,hf("version.goBack"));const r=b("button",["dialog-version-button"],null,hf("version.play")),i=b("button",["dialog-version-button"],null,hf("version.revertVersion"));this.goBackButton=e,this.playButton=r,this.revertButton=i,this.bindEvent()}bindEvent(){const{onBack:t,onPlay:e,onRevert:o}=this.options;this.playButton.onclick=e,this.goBackButton.onclick=t,this.revertButton.onclick=o}disabledButton(){}render(t,e=!1){e||t.append(this.goBackButton,this.playButton,this.revertButton)}destroy(){this.playButton.onclick=null,this.goBackButton.onclick=null,this.revertButton.onclick=null}}const Ce=w("split-text-actions");function nC(n){return n.length>2?!1:n.length===1?n[0].insert!==void 0:(d(Ce,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].insert!==void 0)}function oC(n){return n.length>2?!1:n.length===1?n[0].delete!==void 0:(d(Ce,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].delete!==void 0)}function rC(n){return n.length>2?!1:n.length===1?n[0].insert===void 0&&n[0].delete===void 0&&n[0].attributes!==void 0:(d(Ce,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].attributes!==void 0)}function KN(n){const t=[],e=Y.default(n);if(e.length===0)return[];if(e.length===1)return[n];if(e.length===2&&(oC(n)||nC(n)||rC(n)))return[n];const o=(i,s)=>i>0?[{retain:i},s]:[s];let r=0;for(;e.length>0;){const i=e[0];if(i.retain!==void 0&&i.attributes===void 0){d(Ce,i.retain>0,`invalid text op: ${JSON.stringify(i)}`),d(Ce,e.length>1,`invalid text op: ${JSON.stringify(i)}`);const s=e[1];d(Ce,s.delete||s.insert!==void 0||s.attributes!==void 0,`invalid next text op: ${JSON.stringify(s)}`),r+=i.retain,t.push(o(r,s)),s.delete!==void 0?r-=s.delete:s.insert!==void 0?r+=s.insert.length:(d(Ce,s.attributes!==void 0,`invalid next text op: ${JSON.stringify(s)}`),d(Ce,s.retain!==void 0,`invalid next text op: ${JSON.stringify(s)}`),r+=s.retain),e.splice(0,2)}else d(Ce,i.delete||i.insert!==void 0||i.attributes!==void 0,`invalid next text op: ${JSON.stringify(i)}`),t.push(o(r,i)),e.shift(),i.retain!==void 0&&(d(Ce,i.attributes!==void 0,`invalid next text op: ${JSON.stringify(i)}`),r+=i.retain),i.insert&&(r+=i.insert.length)}return t}function iC(n){if(d(Ce,n.length===1||n.length===2,`not a single action op: ${JSON.stringify(n)}`),n.length===1)return 0;const t=n[0].retain;return d(Ce,typeof t=="number"&&t>0,`invalid retain: ${JSON.stringify(n)}`),t}let sC=0;function JN(n,t,e){const o=sC;sC+=1;const r=vt(n);return{insert:" ",attributes:{box:!0,id:N(),type:"history-deleted-box",user:e,created:Date.now(),text:r,deletedOffset:t,deletedOrder:o}}}function XN(n,t,e){const o=iC(t),r=t.length===1?t[0].delete:t[1].delete;d(Ce,typeof r=="number",`not a delete op: ${JSON.stringify(t)}`);const{left:i,middle:s,right:l}=Gt(n,o,r),c=JN(s,o,e);return[...i,c,...l]}function t$(n,t,e){const o=iC(t),r=t.length===1?t[0].insert:t[1].insert;d(Ce,typeof r=="string",`invalid insert op: ${JSON.stringify(t)}`);const i=t.length===1?t[0].attributes:t[1].attributes,l=Ol([{insert:r,attributes:i}],"insertedBy",e);return Sr(n,o,l,null)}function e$(n,t,e){const o=KN(t).reverse();let r=n;for(const i of o)oC(i)?r=XN(r,i,e):nC(i)?r=t$(r,i,e):(d(Ce,rC(i),`unknown op: ${JSON.stringify(i)}`),r=ie.apply(r,i));return r}const n$=w("history-update-block-text");function lC(n){const t=[],e=[];let o=0;return n.forEach(r=>{var i;if((i=r.attributes)!=null&&i.box){const s=r.attributes;if(s.type==="history-deleted-box"){t.push({boxData:s,offset:o});return}}e.push(r),o+=Fd(r)}),t.sort((r,i)=>i.offset-r.offset),{deletedBoxes:t,newText:e}}function o$(n,t,e){let o=n;return t.forEach(r=>{const i=ie.transformCursor(r.offset,e,!1);o=Sr(o,i,[{insert:" ",attributes:r.boxData}],null)}),o}function r$(n){n.sort((t,e)=>t.boxData.deletedOffset!==e.boxData.deletedOffset?t.boxData.deletedOffset-e.boxData.deletedOffset:t.boxData.deletedOrder-e.boxData.deletedOrder)}function i$(n){if(n.length<=1)return n;const t=n[0].offset;n.forEach(e=>{d(n$,e.offset===t,`invalid boxes group, ${JSON.stringify(n)}`)}),r$(n);for(let e=n.length-1;e>=1;e--){const o=n[e],r=n[e-1];o.boxData.user.userId===r.boxData.user.userId&&(r.boxData.text+=o.boxData.text,n.splice(e,1))}return n}function s$(n){let{newText:t,deletedBoxes:e}=lC(n);const o=new Map;return e.forEach(i=>{let s=o.get(i.offset);s||(s=[],o.set(i.offset,s)),s.push(i),s.sort((l,c)=>l.boxData.deletedOffset-c.boxData.deletedOffset)}),Array.from(o.values()).sort((i,s)=>s[0].offset-i[0].offset).forEach(i=>{const s=i[0].offset;i$(i).reverse().forEach(l=>{t=Sr(t,s,[{insert:" ",attributes:l.boxData}],null)})}),t}function l$(n,t,e){let{newText:o,deletedBoxes:r}=lC(n);return o=e$(o,t,e),o=o$(o,r,t),o=s$(o),o}const Mn=w("history-doc");function Rn(n){d(Mn,!1,"no local actions for history doc")}class c$ extends xi{constructor(e,o){super();h(this,"doc");h(this,"editor");this.doc=Y.default(e),this.editor=o}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return Y.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,o){const r=this.getContainerBlocks(e);d(Mn,r,`no container data: ${e}`);const i=r[o];return d(Mn,i,`no block data: ${o}`),i}localUpdateBlockText(){Rn()}localUpdateBlockData(){Rn()}localInsertBlock(){Rn()}localDeleteBlock(){Rn()}localInsertChildContainer(){Rn()}localDeleteChildContainers(){Rn()}uploadResource(){Rn()}async addResources(e){Rn()}getServerMeta(){var e,o,r;return(r=(o=(e=this.editor.doc.externalDoc).getServerMeta)==null?void 0:o.call(e))!=null?r:{}}buildResourceUrl(e){return this.editor.doc.externalDoc.buildResourceUrl(e)}request(){Rn()}broadcastMessage(){Rn()}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new ic}destroy(){this.clearCallbacks()}transformBlockIndex(e,o,r){const i=this.doc.blocks[e];d(Mn,i,`no container blocks: ${e}`);let s=0;for(let l=0;l<i.length;l++)if(!i[l].deletedBy){if(s===o)return l;s++}return r&&d(Mn,!1,`invalid block index: ${o}, blocks: ${JSON.stringify(i)}`),d(Mn,s===o,`invalid block index: ${o}, blocks: ${JSON.stringify(i)}`),i.length}onDeleteBlock(e,o,r){const i=this.transformBlockIndex(e,o,!0),l=this.doc.blocks[e][i];d(Mn,!l.deleted,`block has already deleted: ${e}/${o}`),l.deletedBy=r,this.callbacks.forEach(c=>{var a;return(a=c.onUpdateBlockData)==null?void 0:a.call(c,e,i,{insert:{},delete:[]},!0)})}onInsertBlock(e,o,r,i){const s=this.transformBlockIndex(e,o,!1),l=this.doc.blocks[e],c=Y.default(r);c.insertedBy=i,l.splice(s,0,c),this.callbacks.forEach(a=>{var u;return(u=a.onInsertBlock)==null?void 0:u.call(a,e,s,c,!0)})}onUpdateBlockText(e,o,r,i){const s=this.transformBlockIndex(e,o,!0),c=this.doc.blocks[e][s];d(Mn,!c.deleted,`block has already deleted: ${e}/${o}`);const a=c.text;d(Mn,a,`no text for block: ${JSON.stringify(c)}`);const u=l$(a,r,i);c.text=u,this.callbacks.forEach(f=>{var m;return(m=f.onUpdateBlockText)==null?void 0:m.call(f,e,o,r,!0)})}onUpdateBlockData(e,o,r,i){const s=this.transformBlockIndex(e,o,!0),l=this.doc.blocks[e],c=l[s];d(Mn,!c.deleted,`block has already deleted: ${e}/${o}`);const a=Y.default(c);a.updatedBy=i,r.delete.forEach(u=>delete a[u]),Object.entries(r.insert).forEach(([u,f])=>{a[u]=f}),l[s]=a,this.callbacks.forEach(u=>{var f;return(f=u.onUpdateBlockData)==null?void 0:f.call(u,e,s,r,!0)})}onCreateContainer(e,o,r){this.doc.blocks[e]=Y.default(o),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,e,o,!0)})}}const{t:cC}=T;function mi(n,t){return t==="insert"?cC("version.insert",{name:n.displayName}):cC("version.delete",{name:n.displayName})}function hr(n,t){const{userId:e}=t;return["flag","selection"].reduce((r,i)=>{const s=n.doc.getRemoteUsers().getFixedUserColor(e,i);return r[i]=s,r},{})}class a${renderText(t,e,o){if(!o.box&&o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=hr(t,o.insertedBy);return{classes:["history-inserted-text"],attributes:{"history-inserted-by":r.displayName,"data-op-description":mi(r,"insert")},styles:{[ui]:i,[hi]:s}}}return{}}renderBlock(t,e,o){if(o.deletedBy){const r=o.deletedBy,{flag:i,selection:s}=hr(t,r);return{classes:["history-deleted-block"],attributes:{"history-deleted-by":r.displayName,"data-op-description":mi(r,"delete")},styles:{[ui]:i,[hi]:s}}}if(o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=hr(t,r);return{classes:["history-inserted-block"],attributes:{"history-inserted-by":r.displayName,"data-op-description":mi(r,"insert")},styles:{[ui]:i,[hi]:s}}}return{}}updateBlock(t,e,o,r){if(r.deletedBy){const i=r.deletedBy,{flag:s,selection:l}=hr(t,i);A(o,"history-deleted-block"),Ja(o,{"history-inserted-by":i.displayName,"data-op-description":mi(i,"delete")}),Xa(o,{[ui]:s,[hi]:l});return}if(r.insertedBy){const i=r.insertedBy,{flag:s,selection:l}=hr(t,i);A(o,"history-inserted-block"),Ja(o,{"history-inserted-by":i.displayName,"data-op-description":mi(i,"insert")}),Xa(o,{[ui]:s,[hi]:l})}}}const aC=w("history-deleted-box");function d$(n,t,e,o){const r=o;d(aC,r.text,`no text for text box data: ${JSON.stringify(o)}`),d(aC,typeof r.text=="string",`invalid text type for text box data: ${JSON.stringify(o)}`);const i=b("span",["history-deleted-box"],e,r.text),s=r.user,{flag:l,selection:c}=hr(n,s);i.setAttribute("history-deleted-by",s.displayName),i.setAttribute("data-op-description",mi(s,"delete")),i.style.setProperty(ui,l),i.style.setProperty(hi,c)}function u$(n,t,e,o){return t.text}const h$={boxType:"history-deleted-box",updateBoxContent:d$,convertTo:u$},Ee=w("version-dialog");class f${constructor(t,e){h(this,"editor");h(this,"dialog",null);h(this,"oldViewer",null);h(this,"versionOptions");h(this,"versionList",null);h(this,"actionButtons",null);h(this,"provider");h(this,"components");h(this,"handleClose",()=>{var t;(t=this.dialog)==null||t.hide()});h(this,"handlePlay",()=>{var e;d(Ee,this.versionList,"The versionList did not render");const t=(e=this.versionList)==null?void 0:e.activeVersion;d(Ee,t,`The version: ${t} is invalid`),this.viewVersion(t,{play:!0,speed:150})});h(this,"handleRevert",async()=>{var e,o;d(Ee,this.versionList,"The versionList did not render");const t=(e=this.versionList)==null?void 0:e.activeVersion;d(Ee,t,`The version: ${t} is invalid`),await this.versionHelper.revertVersion(t.version),(o=this.dialog)==null||o.hide()});h(this,"handleSelectVersion",t=>{d(Ee,t,`The version: ${t} is invalid`),this.viewVersion(t)});h(this,"viewVersion",async(t,e={play:!1,speed:1e3})=>{var C,v,B;this.oldViewer&&(this.oldViewer.destroy(),this.oldViewer=null),d(Ee,this.versionList,"The versionList did not render"),d(Ee,this.actionButtons,"The actionButtons did not render");const o=t.type==="minor"?this.versionList.beforeVersion:this.versionList.beforeMajorVersion,r=o?o.version:0,i=this.versionList.isSelectedFirstVersion,s=this.versionList.isSelectedLastVersion;this.actionButtons.revertButton.disabled=i,this.actionButtons.playButton.disabled=i;let l=(C=this.versionOptions)==null?void 0:C.hideOps;if((v=this.versionOptions)!=null&&v.onWillChangeVersion){const y=this.versionOptions.onWillChangeVersion(this.editor,t,i,s);y!=null&&y.hideOps&&(l=!0)}let c,a;if(l)c=await this.versionHelper.getVersion(t.version),a=[];else{const y=await this.versionHelper.getHistoryData(t.version,r);c=y.doc,a=y.historyData}const{editorElement:u}=this.components;u.innerHTML="";const f=new c$(c,this.editor),m=this.provider.createHistoryEditor(u,f);m.editorBlockRenders.registerRender(new a$),m.editorBoxes.registerBoxClass(h$),A(m.rootElement,tC.HISTORY);try{await ZN(f,this.versionHelper,a,e)}finally{this.oldViewer=m}(B=this.versionOptions)!=null&&B.onVersionChanged&&this.versionOptions.onVersionChanged(this.editor,m,t,i,s)});h(this,"setShowOps",t=>{var e;if(this.versionOptions){this.versionOptions.hideOps=!t;const o=(e=this.versionList)==null?void 0:e.activeVersion;d(Ee,o,`The version: ${o} is invalid`),this.viewVersion(o)}});this.editor=t,this.provider=e;const o=b("div",["version-dialog"],null),r=b("div",["version-dialog-note-viewer"],o),i=b("div",["version-dialog-action-container"],r),s=b("div",["version-dialog-editor"],r),l=b("div",["version-dialog-versions-list"],o);this.components={root:o,editorElement:s,actionContainer:i,versionsListContainer:l}}get versionHelper(){d(Ee,this.editor.doc.getVersionHelper,"Can not get getVersionHelper from doc");const t=this.editor.doc.getVersionHelper();return d(Ee,t,"current doc does not support version"),t}renderContent(t){var s,l;const{actionContainer:e,versionsListContainer:o}=this.components;e.innerHTML="";const r=new QN({onBack:this.handleClose,onPlay:this.handlePlay,onRevert:this.handleRevert});r.render(e,(s=this.versionOptions)==null?void 0:s.hideActions),this.actionButtons=r,o.innerHTML="";const i=new qN({versions:t,useCreatedBy:(l=this.versionOptions)==null?void 0:l.useCreatedBy,onSelectVersion:this.handleSelectVersion,getMarkColor:c=>{const{flag:a}=hr(this.editor,c);return a}});i.render(o),this.versionList=i}initViewVersion(){var t;if((t=this.versionOptions)!=null&&t.initSelectedVersion){d(Ee,this.versionList,"The versionList did not render");const{initSelectedVersion:e}=this.versionOptions,o=this.versionList.selectVersionByVersionNum(e);d(Ee,o,`The version: ${o} is invalid`),this.viewVersion(o)}else{d(Ee,this.versionList,"The versionList did not render");const e=this.versionList.activeVersion;d(Ee,e,`The version: ${e} is invalid`),this.viewVersion(e)}}async show(t){this.versionOptions={...this.versionOptions,...t};const e=await this.versionHelper.getVersions();if(this.versionOptions.hideNonVersionedOps&&e.length&&e[0].version===-1&&e.shift(),this.versionOptions.onVersionsLoaded&&this.versionOptions.onVersionsLoaded(this.editor,e),this.renderContent(e),this.initViewVersion(),!this.dialog){const{root:o}=this.components;this.dialog=new VN(o)}this.dialog.show(t.container)}destroy(){var t,e,o;(t=this.dialog)==null||t.destroy(),(e=this.versionList)==null||e.destroy(),(o=this.actionButtons)==null||o.destroy()}}function m$(n,t,e){const o=n.addCustom("version-dialog",()=>new f$(n,t));return o.show(e),{setShowOps:o.setShowOps}}const Kz="",g$=w("heading-collapse");function ff(n){var e;const t=Number.parseInt((e=n.getAttribute("data-style-heading"))!=null?e:"",10);return d(g$,t,"not a heading block"),t}function ze(n){return!!n.getAttribute("data-style-heading")}function p$(n){return!nt(n,"heading-collapsed")}function fr(n){return nt(n,"heading-collapsed")}function dC(n){if(gt(n))return!1;const e=H(n);return pt(e)}const C$=w("heading-collapse");function mf(n){d(C$,ze(n),"not a heading block");const t=[],e=ff(n);let o=dt(n);for(;o&&!(ze(o)&&ff(o)<=e);)t.push(o),o=dt(o);return t}function uC(n,t){if(!Ko(t))return;n.selection.selectBlock(t,0),mf(t).forEach(o=>{jm(o)}),A(t,"heading-collapsed")}function gi(n,t){mf(t).forEach(o=>{Hm(o)}),z(t,"heading-collapsed")}function b$(n,t){p$(t)?uC(n,t):gi(n,t)}const v$=[Xu,th,eh,nh,oh,rh,ih,sh];function k$(n){const t=b("button",["heading-collapse-button"],null);return t.setAttribute(`data-editor-tooltip-${n.clientId}`,"Collapse / Expand"),t.innerHTML=Ju,t}function hC(n){return oa(n).querySelector("button.heading-collapse-button")}function fC(n,t){hC(t)||dC(t)||!Ko(t)||T1(t,k$(n),-1)}function y$(n){var t;(t=hC(n))==null||t.remove()}function mC(n,t){oa(t).querySelector("button.heading-collapse-button")||fC(n,t)}function w$(n){const t=ff(n),e=b("button",["heading-marker"],null);return e.innerHTML=v$[t-1],e}function gC(n){return oa(n).querySelector("button.heading-marker")}function gf(n){gC(n)||dC(n)||!Ko(n)||T1(n,w$(n),1)}function pC(n){const t=gC(n);t==null||t.remove()}function CC(n){pC(n),ze(n)&&gf(n)}class B${handleDrop(t,e,o,r){if(kl(e)||!ze(e)||!fr(e))return;const i=mf(e);i.unshift(e);const s=i.reverse();let l=null;return t.doc.beginBatchUpdate(),s.forEach((c,a,u)=>{const f=t.getBlockData(c),m=ao(t.editorBlocks,t.doc.toJSON(),f),C=t.insertDocAt(o,r,m)[0];a===u.length-1&&(l=C)}),t.doc.endBatchUpdate(),t.doc.beginBatchUpdate(),s.forEach(c=>{t.deleteBlock(c)}),t.doc.endBatchUpdate(),l&&uC(t,l),!0}}const E$=w("heading-collapse");class I${constructor(t){h(this,"handleLoad",()=>{this.showCollapseButtons()});h(this,"handleHoverBlock",(t,e)=>{e&&(z(e,"hovering-heading"),ze(e)&&pt(H(e))&&(gf(e),fr(e)||y$(e))),t&&ze(t)&&pt(H(t))&&(A(t,"hovering-heading"),pC(t),fC(this.editor,t))});h(this,"handleClick",(t,e)=>{const o=Di(e,"button.heading-collapse-button");if(!o)return;const r=F(o);!r||(d(E$,ze(r),"not a heading block"),b$(this.editor,r),mC(this.editor,r))});this.editor=t,t.addListener("load",this.handleLoad),t.addListener("click",this.handleClick),Nt.get(t).addListener("change",this.handleHoverBlock),this.showCollapseButtons(),setTimeout(()=>{Hs.get(t).addHandler(new B$)})}showCollapseButtons(){const t=Mt(this.editor.rootContainer).filter(ze);t.length!==0&&(t[0]===Vt(this.editor.rootContainer)&&t.splice(0,1),t.forEach(gf))}destroy(){this.editor.removeListener("load",this.handleLoad),this.editor.removeListener("click",this.handleClick)}}function va(n){const t=n.selection.range;if(t.isCollapsed()||t.start.blockId===t.end.blockId)return;const e=n.getBlockById(t.start.blockId),o=n.getBlockById(t.end.blockId);fr(e)&&gi(n,e),fr(o)&&gi(n,o)}function x$(n){va(n);const t=n.getFocusedBlock();!ze(t)||fr(t)&&gi(n,t)}function T$(n){va(n);const t=n.getFocusedBlock();if(!ze(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===W(n,t)&&fr(t)&&gi(n,t)}function S$(n){va(n);const t=n.getFocusedBlock();if(!ze(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===0&&fr(t)&&gi(n,t)}class D${handleBeforeKeyDown(t,e){return rd(e.key)&&va(t),e.key==="Enter"?(x$(t),!1):e.key==="Delete"?(T$(t),!1):(e.key==="Backspace"&&S$(t),!1)}}class L${constructor(t){this.editor=t}onInsertBlock(t,e,o,r){this.updateBlockIfNeeded(o.id)}onUpdateBlockData(t,e,o,r){const i=this.editor.doc.getBlockData(t,e);this.updateBlockIfNeeded(i.id,o)}updateBlockIfNeeded(t,e){setTimeout(()=>{const o=this.editor.findBlockById(t);if(!!o){if(!ze(o)){e&&e.delete.includes("heading")&&CC(o);return}nt(o,"hovering-heading")&&mC(this.editor,o),CC(o)}},100)}}function M$(n){return!!n.heading}function bC(n){var e;const t=n.heading;return(e=Number.parseInt(`${t}`,10))!=null?e:1}function vC(n,t){var e;return{parentNode:t,children:[],text:vt((e=n.text)!=null?e:[]),level:bC(n),block:n}}class Zs{constructor(){h(this,"nodes",[])}appendBlock(t){const e=this.findParent(bC(t),this.nodes);e?e.children.push(vC(t,e)):this.nodes.push(vC(t,null))}findParent(t,e){const o=e[e.length-1];if(!o||t<=1)return null;if(o.level===t-1)return o;const r=this.findParent(t,o.children);return r||(o.level<t?o:null)}static buildToc(t){const e=new Zs,o=t.blocks.root;for(let r=0;r<o.length;r++){const i=o[r];M$(i)&&e.appendBlock(i)}return e}}class mr extends Yt.TypedEmitter{constructor(e){super();h(this,"toc",new Zs);h(this,"updateToc",Xt.default(()=>{this.updateTocNow()},500));this.editor=e,e.doc.registerCallback(this),this.updateToc()}destroy(){this.editor.doc.unregisterCallback(this)}isHeadingBlock(e){return!!e.heading}onInsertBlock(e,o,r,i){e==="root"&&this.isHeadingBlock(r)&&this.updateToc()}onDeleteBlock(e,o,r){e==="root"&&this.updateToc()}onUpdateBlockText(e,o,r,i){if(e!=="root")return;const s=this.editor.doc.getBlockData(e,o);this.isHeadingBlock(s)&&this.updateToc()}onUpdateBlockData(e,o,r,i){if(e!=="root")return;const s=this.editor.doc.getBlockData(e,o);this.isHeadingBlock(s)&&this.updateToc()}static register(e){return e.addCustom("editor-toc",()=>new mr(e))}static get(e){return e.getCustom("editor-toc")}updateTocNow(){this.toc=Zs.buildToc(this.editor.doc.toJSON()),this.emit("change",this.editor,this.toc)}}const Jz="";function R$(n){return n.nodes.length===0?!0:n.nodes.length>1?!1:n.nodes[0].children.length===0}function pf(n,t){t.forEach(e=>{const o=b("div",["toc-node"],n),r=b("div",["toc-title"],o);if(b("span",["toc-text"],r,e.text).setAttribute("data-block-id",e.block.id),e.children.length>0){const s=b("div",["toc-children"],o);pf(s,e.children)}})}function A$(n,t){const e=Di(t,".toc-text");if(!e)return;const o=e.getAttribute("data-block-id");if(!o)return;const r=n.findBlockById(o);!r||(t.preventDefault(),t.stopPropagation(),n.selection.selectBlock(r,0))}function kC(n,t,e){if(z(t,"loading"),t.innerHTML="",R$(e)){b("div",["toc-empty-message"],t,"No toc");return}e.nodes.length===1?pf(t,e.nodes[0].children):pf(t,e.nodes),Au(n,"toc-click-handler",()=>{n.addListener("click",A$)})}class O${constructor(t){h(this,"handleUpdateToc",(t,e)=>{Array.from(t.rootContainer.querySelectorAll('.embed-block[data-type="editor-block"][data-embed-type="toc"]')).forEach(r=>{const i=r.querySelector(".editor-toc-container");i&&kC(t,i,e)})});this.editor=t,mr.register(t).addListener("change",this.handleUpdateToc)}destroy(){mr.register(this.editor).removeListener("change",this.handleUpdateToc)}get toc(){return mr.register(this.editor).toc}}function _$(n,t){const e=b("div",["editor-toc-container","embed-selected-content"],t),r=n.addCustom("init-editor-toc",()=>new O$(n)).toc;r.nodes.length===0?A(e,"loading"):kC(n,e,r)}function N$(n,t,e,o){return o==="markdown"?"[toc]":""}function $$(n,t,e){const{data:o}=e;if(!o||o.embedType!=="toc"||!j(n,t))return null;const r={};return{blockData:{id:N(),type:"embed",embedType:"toc",embedData:r}}}const yC={embedType:"toc",createEmbedContent:_$,convertTo:N$,convertFrom:$$};function P$(n){return!!n.getAttribute("data-style-heading")}function Cf(n,t){return P$(t)&&W(n,t)>0}function j$(n){const t=We(n.rootElement);let e=0,o=0,r=0;if(t===document.documentElement){const i=n.rootContainer.getBoundingClientRect();e=i.left+i.width/2,o=10,r=t.offsetHeight}else{const i=t.getBoundingClientRect();e=i.left+i.width/2,o=i.top+10,r=i.bottom}for(;o<r;){const i=document.elementsFromPoint(e,o);for(let s=0;s<i.length;s++){const l=F(i[s]);if(l&&n.rootContainer.contains(l))return l}o+=10}return null}function bf(n,t){let e=t;for(;e&&!Cf(n,e);)e=dt(e);return e}function wC(n){if(gt(n))return!1;const e=H(n);return pt(e)}function ka(n,t){let e=t;for(;e&&!Cf(n,e);)e=gt(e),e&&wC(e)&&(e=null);return e}const H$=.3;class F$ extends Yt.TypedEmitter{constructor(e){super();h(this,"scrollContainer");h(this,"scrollEventTarget");h(this,"scrollStatus",{curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null});h(this,"handleScroll",Xt.default(()=>{const e={curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null};let o=j$(this.editor);if(o&&(o=yd(o)),!o||!this.scrollContainer){this.setStatus(e);return}if(wC(o)&&(o=dt(o)),!o){this.setStatus(e);return}if(Cf(this.editor,o)){e.curHeadingBlock=o,e.previousHeadingBlock=ka(this.editor,o),e.nextHeadingBlock=bf(this.editor,o),this.setStatus(e);return}const r=this.scrollContainer.getBoundingClientRect(),i=bf(this.editor,o);if(i){const l=i.getBoundingClientRect();if(l.top>r.top&&l.top<r.top+r.height*H$){e.curHeadingBlock=i,e.previousHeadingBlock=ka(this.editor,i),e.nextHeadingBlock=bf(this.editor,i),this.setStatus(e);return}e.nextHeadingBlock=i}const s=ka(this.editor,o);s&&(e.curHeadingBlock=s,e.previousHeadingBlock=ka(this.editor,s)),this.setStatus(e)},200));this.editor=e,setTimeout(()=>{this.start()},50)}setStatus(e){this.scrollStatus.previousHeadingBlock===e.previousHeadingBlock&&this.scrollStatus.nextHeadingBlock===e.nextHeadingBlock&&this.scrollStatus.previousHeadingBlock===e.previousHeadingBlock||(this.scrollStatus=e,this.emit("change",this.editor,e))}start(){this.stop(),this.scrollContainer=We(this.editor.rootElement),this.scrollEventTarget=this.scrollContainer===document.documentElement?document:this.scrollContainer,this.scrollEventTarget.addEventListener("scroll",this.handleScroll),this.handleScroll()}stop(){this.scrollEventTarget&&this.scrollEventTarget.removeEventListener("scroll",this.handleScroll)}destroy(){this.stop(),this.scrollEventTarget=void 0}}class z${constructor(t,e){h(this,"suggest");h(this,"onShow",(t,e,o,r)=>{const i=this.editor.getBlockByIndex(e,o);if(!Ko(i)){const s=F(H(i));if(s&&rt(s)==="code")return!1}return!0});h(this,"onClickItem",(t,e,o)=>{const r=e.data,i={id:N(),type:"mention",box:!0,created:Date.now(),iconUrl:r.avatarUrl,text:r.displayName,mentionId:r.userId},s=this.editor.selection.range;if(!s.isCollapsed()||!s.isSimple())return;const l=s.focus,c=this.editor.getBlockById(l.blockId);this.editor.insertBoxToBlock(c,l.offset,i)});h(this,"queryItems",async(t,e)=>(await this.options.queryUsers(this.editor,e)).map(i=>({id:i.userId,name:i.displayName,icon:`<img src="${i.avatarUrl}" class="mention-user-avatar">`,element:i.element,data:i,subText:i.email})));this.editor=t,this.options=e,this.suggest=new mh(t,{id:"editor-mention",trigger:["@"],autoDeleteTrigger:!0,showLoading:!0,onShow:this.onShow,onClickItem:this.onClickItem,queryItems:this.queryItems})}destroy(){}}w("mathjax-box");function U$(n,t,e,o){const r=o,i=b("a",["mention-container"],e);b("span",["mention-name"],i,`@${r.text}`),i.setAttribute("data-mention-id",r.mentionId)}function V$(n,t,e){}function q$(n,t,e,o){return`@${t.text}`}const vf={boxType:"mention",updateBoxContent:U$,handleClickBox:V$,convertTo:q$};function W$(n){return go("list-block-mention",T.t("list.mention.tooltip"),mB,[],n.clientId)}class G${constructor(t){h(this,"mentionButton");h(this,"handleHoveringBlock",t=>{var e;!this.editor.isWritable()||(t&&this.shouldBlockShowMention(t)?Rt(t).appendChild(this.mentionButton):(e=this.mentionButton)==null||e.remove())});h(this,"handleMouseDown",(t,e)=>{e.preventDefault(),e.stopPropagation();const o=F(this.mentionButton);if(!o||!j(t,o))return;const r=t.selection.range.focus;if(!r.isSimple())return;let i;t.selection.focusedBlock!==o?i=W(t,o):i=r.offset,setTimeout(()=>{const s=t.insertTextToBlock(o,i,"@");i+=1;const l=vt(be(s,i).left);this.editor.selection.selectBlock(o,i),this.editor.focus(),t.getCustom("mention").suggest.popup(o,i,l,"@")})});h(this,"destroy",()=>{Nt.get(this.editor).removeListener("change",this.handleHoveringBlock)});this.editor=t,this.mentionButton=W$(t),Nt.get(this.editor).addListener("change",this.handleHoveringBlock),t.domEvents.addEventListener(this.mentionButton,"mousedown",this.handleMouseDown)}shouldBlockShowMention(t){if(!j(this.editor,t)||!ct(t))return!1;const e=Fe(t);return!(e==="ordered"||e==="unordered")}}const Xz="",Z$={templates:{title:"\u9009\u62E9\u6A21\u677F\uFF0C\u5FEB\u901F\u521B\u5EFA",create:"\u65B0\u5EFA\u6A21\u677F",choose:"\u5168\u90E8\u6A21\u677F",customizedMark:"\u81EA\u5B9A\u4E49"}},Y$={templates:{title:"Choose a template",create:"New template",choose:"All templates",customizedMark:"Custom"}};T.mergeLang({"zh-CN":Z$,"en-US":Y$});const tU="",Q$="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjEyMCIgaGVpZ2h0PSIxMjAiIHZpZXdCb3g9IjAgMCAxMjAgMTIwIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cmVjdCB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTQ4IDU5QzQ4IDU0LjU4MTcgNTEuNTgxNyA1MSA1NiA1MUg5M0M5OC41MjI4IDUxIDEwMyA1NS40NzcyIDEwMyA2MVY4OEMxMDMgOTEuODY2IDk5Ljg2NiA5NSA5NiA5NUg1NkM1MS41ODE3IDk1IDQ4IDkxLjQxODMgNDggODdWNTlaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGQ9Ik0xOCA2NEMxOCA2Mi4zNDMxIDE5LjM0MzEgNjEgMjEgNjFINTZDNjAuNDE4MyA2MSA2NCA2NC41ODE3IDY0IDY5VjgzQzY0IDg1LjIwOTEgNjIuMjA5MSA4NyA2MCA4N0gyNkMyMS41ODE3IDg3IDE4IDgzLjQxODMgMTggNzlWNjRaIiBmaWxsPSIjRUFFNEY2Ii8+CjxyZWN0IHg9IjI0IiB5PSIzMSIgd2lkdGg9IjY1IiBoZWlnaHQ9IjUwIiByeD0iNSIgZmlsbD0iIzk5QzdGMiIvPgo8cmVjdCB4PSIzMy41IiB5PSI0MyIgd2lkdGg9IjQ2IiBoZWlnaHQ9IjUiIHJ4PSIyLjUiIGZpbGw9IndoaXRlIi8+CjxyZWN0IHg9IjMzLjUiIHk9IjU0IiB3aWR0aD0iNDYiIGhlaWdodD0iNSIgcng9IjIuNSIgZmlsbD0id2hpdGUiLz4KPHJlY3QgeD0iMjQiIHk9IjMxIiB3aWR0aD0iNjUiIGhlaWdodD0iNTAiIHJ4PSI1IiBzdHJva2U9IiNGOEY4RjgiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik01MCA4NS4yNjhDNTMuODI2MyA4My4wNTg5IDU1LjEzNzMgNzguMTY2MiA1Mi45MjgyIDc0LjMzOThMNjMuMzIwNSA2OC4zMzk4QzY4Ljg0MzMgNzcuOTA1NyA2NS41NjU4IDkwLjEzNzUgNTYgOTUuNjYwNEM0Ni40MzQxIDEwMS4xODMgMzQuMjAyMyA5Ny45MDU3IDI4LjY3OTQgODguMzM5OEwzOS4wNzE3IDgyLjMzOThDNDEuMjgwOSA4Ni4xNjYyIDQ2LjE3MzYgODcuNDc3MiA1MCA4NS4yNjhaIiBmaWxsPSIjQUI5M0RDIi8+CjxyZWN0IHg9IjU5IiB5PSI2NSIgd2lkdGg9IjQyIiBoZWlnaHQ9IjI4IiByeD0iNSIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTYzIDg4VjczLjA4MDhDNjMgNzEuNzA5NiA2My4zNjE0IDcwLjY4NjcgNjQuMDg0MSA3MC4wMTJDNjQuODI4NyA2OS4zMzczIDY1Ljg1OCA2OSA2Ny4xNzIgNjlIOTIuODYwOUM5NS42MjAzIDY5IDk3IDcwLjM2MDMgOTcgNzMuMDgwOFY4OEg5My41MTc5TDg3LjM3NDkgODAuNjIyQzg3LjA5MDIgODAuMzE3MyA4Ni43NjE3IDgwLjA4ODggODYuMzg5NCA3OS45MzY0Qzg2LjAxNzEgNzkuNzg0MSA4NS42NDQ4IDc5LjcwNzkgODUuMjcyNSA3OS43MDc5Qzg0LjkwMDIgNzkuNzA3OSA4NC41Mjc5IDc5Ljc4NDEgODQuMTU1NiA3OS45MzY0QzgzLjgwNTIgODAuMDg4OCA4My40NTQ4IDgwLjMxNzMgODMuMTA0MyA4MC42MjJMNzYuNzMxNCA4Ni4yMzcxTDc0LjIwMTkgODMuOTUxOUM3My42MzI1IDgzLjQyOTYgNzMuMDA4NCA4My4xNjg0IDcyLjMyOTUgODMuMTY4NEM3MS42NTA2IDgzLjE2ODQgNzEuMDM3NCA4My40Mjk2IDcwLjQ4OTkgODMuOTUxOUw2Ni40NDkzIDg4SDYzWk03NC40NjQ3IDgwLjYyMkM3NS4zNjI2IDgwLjYyMiA3Ni4xNDAxIDgwLjI5NTUgNzYuNzk3MSA3OS42NDI2Qzc3LjQ3NiA3OC45ODk3IDc3LjgxNTUgNzguMjE3MSA3Ny44MTU1IDc3LjMyNDdDNzcuODE1NSA3Ni40MTA3IDc3LjQ3NiA3NS42MzggNzYuNzk3MSA3NS4wMDY5Qzc2LjE0MDEgNzQuMzU0IDc1LjM2MjYgNzQuMDE2NiA3NC40NjQ3IDczLjk5NDhDNzMuNTQ0OSA3My45NTEzIDcyLjc1NjUgNzQuMjY2OSA3Mi4wOTk1IDc0Ljk0MTZDNzEuNDQyNSA3NS42MTYzIDcxLjExNCA3Ni40MTA3IDcxLjExNCA3Ny4zMjQ3QzcxLjExNCA3OC4yMTcxIDcxLjQ0MjUgNzguOTg5NyA3Mi4wOTk1IDc5LjY0MjZDNzIuNzU2NSA4MC4yOTU1IDczLjU0NDkgODAuNjIyIDc0LjQ2NDcgODAuNjIyWiIgZmlsbD0iI0Y3RDA3RiIvPgo8Y2lyY2xlIGN4PSI5NSIgY3k9IjQyIiByPSIyIiBzdHJva2U9IiM1MEMzOTgiIHN0cm9rZS13aWR0aD0iMiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTk0Ljc1MDEgMjQuNDY4N0wxMDAuNzgxIDI3LjkxNDlMOTQuNzE5IDMxLjQxNDlMOTQuNzUwMSAyNC40Njg3WiIgc3Ryb2tlPSIjNUNBNUVBIiBzdHJva2Utd2lkdGg9IjEuOCIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwNSAzOEMxMDUgMzguNTUyMyAxMDUuNDQ4IDM5IDEwNiAzOUMxMDYuNTUyIDM5IDEwNyAzOC41NTIzIDEwNyAzOFYzNkgxMDlDMTA5LjU1MiAzNiAxMTAgMzUuNTUyMyAxMTAgMzVDMTEwIDM0LjQ0NzcgMTA5LjU1MiAzNCAxMDkgMzRIMTA3VjMyQzEwNyAzMS40NDc3IDEwNi41NTIgMzEgMTA2IDMxQzEwNS40NDggMzEgMTA1IDMxLjQ0NzcgMTA1IDMyVjM0SDEwM0MxMDIuNDQ4IDM0IDEwMiAzNC40NDc3IDEwMiAzNUMxMDIgMzUuNTUyMyAxMDIuNDQ4IDM2IDEwMyAzNkgxMDVWMzhaIiBmaWxsPSIjQUI5M0RDIi8+Cjwvc3ZnPgo=",K$="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgdmlld0JveD0iMCAwIDM3MiAyNzkiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMF8xMjU2XzM3MTY4KSI+CjxyZWN0IHdpZHRoPSIzNzIiIGhlaWdodD0iMjc5IiBmaWxsPSJ3aGl0ZSIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIzOS41NzQ3IiB3aWR0aD0iMTE4LjcyMyIgaGVpZ2h0PSIxNS44Mjk4IiByeD0iNy45MTQ4OSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI3MS4yMzM5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI5MS4wMjE1IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIxMTAuODA5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSI0MC41NjM4IiB5PSIxMzUuNTQzIiB3aWR0aD0iMjkwLjg3MiIgaGVpZ2h0PSIxMDAuOTE1IiByeD0iMi45NjgwOSIgc3Ryb2tlPSIjRUFGM0ZDIiBzdHJva2Utd2lkdGg9IjEuOTc4NzIiLz4KPHBhdGggZD0iTTM5LjU3NDUgMTM4LjUxMUMzOS41NzQ1IDEzNi4zMjUgNDEuMzQ2MyAxMzQuNTUzIDQzLjUzMTkgMTM0LjU1M0gzMjguNDY4QzMzMC42NTQgMTM0LjU1MyAzMzIuNDI2IDEzNi4zMjUgMzMyLjQyNiAxMzguNTExVjE1Mi4zNjJIMzkuNTc0NVYxMzguNTExWiIgZmlsbD0iI0Q2RTlGQSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTg3LjA2MzcgMTY5LjE4MUM4Ny4wNjM3IDE2Ny41NDIgODguMzkyNiAxNjYuMjEzIDkwLjAzMTggMTY2LjIxM0gzMTcuNTg1QzMxOS4yMjQgMTY2LjIxMyAzMjAuNTUzIDE2Ny41NDIgMzIwLjU1MyAxNjkuMTgxQzMyMC41NTMgMTcwLjgyIDMxOS4yMjQgMTcyLjE0OSAzMTcuNTg1IDE3Mi4xNDlIOTAuMDMxOEM4OC4zOTI2IDE3Mi4xNDkgODcuMDYzNyAxNzAuODIgODcuMDYzNyAxNjkuMTgxWk0xMDQuODcyIDE5Mi45MjZDMTA0Ljg3MiAxOTEuMjg2IDEwNi4yMDEgMTg5Ljk1NyAxMDcuODQgMTg5Ljk1N0gzMTcuNTg1QzMxOS4yMjQgMTg5Ljk1NyAzMjAuNTUzIDE5MS4yODYgMzIwLjU1MyAxOTIuOTI2QzMyMC41NTMgMTk0LjU2NSAzMTkuMjI0IDE5NS44OTQgMzE3LjU4NSAxOTUuODk0SDEwNy44NEMxMDYuMjAxIDE5NS44OTQgMTA0Ljg3MiAxOTQuNTY1IDEwNC44NzIgMTkyLjkyNlpNMTA3Ljg0IDIxMy43MDJDMTA2LjIwMSAyMTMuNzAyIDEwNC44NzIgMjE1LjAzMSAxMDQuODcyIDIxNi42N0MxMDQuODcyIDIxOC4zMDkgMTA2LjIwMSAyMTkuNjM4IDEwNy44NCAyMTkuNjM4SDMxNy41ODVDMzE5LjIyNCAyMTkuNjM4IDMyMC41NTMgMjE4LjMwOSAzMjAuNTUzIDIxNi42N0MzMjAuNTUzIDIxNS4wMzEgMzE5LjIyNCAyMTMuNzAyIDMxNy41ODUgMjEzLjcwMkgxMDcuODRaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNTEuNDQ2OCAxNjkuMTgxQzUxLjQ0NjggMTY3LjU0MiA1Mi43NzU2IDE2Ni4yMTMgNTQuNDE0OSAxNjYuMjEzSDYwLjM1MUM2MS45OTAzIDE2Ni4yMTMgNjMuMzE5MSAxNjcuNTQyIDYzLjMxOTEgMTY5LjE4MUM2My4zMTkxIDE3MC44MiA2MS45OTAzIDE3Mi4xNDkgNjAuMzUxIDE3Mi4xNDlINTQuNDE0OUM1Mi43NzU2IDE3Mi4xNDkgNTEuNDQ2OCAxNzAuODIgNTEuNDQ2OCAxNjkuMTgxWk01MS40NDY4IDE5Mi45MjZDNTEuNDQ2OCAxOTEuMjg2IDUyLjc3NTcgMTg5Ljk1NyA1NC40MTQ5IDE4OS45NTdINjAuMzUxMUM2MS45OTAzIDE4OS45NTcgNjMuMzE5MSAxOTEuMjg2IDYzLjMxOTEgMTkyLjkyNkM2My4zMTkxIDE5NC41NjUgNjEuOTkwMyAxOTUuODk0IDYwLjM1MTEgMTk1Ljg5NEg1NC40MTQ5QzUyLjc3NTcgMTk1Ljg5NCA1MS40NDY4IDE5NC41NjUgNTEuNDQ2OCAxOTIuOTI2Wk01NC40MTQ5IDIxMy43MDJDNTIuNzc1NyAyMTMuNzAyIDUxLjQ0NjggMjE1LjAzMSA1MS40NDY4IDIxNi42N0M1MS40NDY4IDIxOC4zMDkgNTIuNzc1NyAyMTkuNjM4IDU0LjQxNDkgMjE5LjYzOEg2MC4zNTExQzYxLjk5MDMgMjE5LjYzOCA2My4zMTkxIDIxOC4zMDkgNjMuMzE5MSAyMTYuNjdDNjMuMzE5MSAyMTUuMDMxIDYxLjk5MDMgMjEzLjcwMiA2MC4zNTExIDIxMy43MDJINTQuNDE0OVoiIGZpbGw9IiM5OUM3RjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik02OS4yNTU0IDE2OS4xODFDNjkuMjU1NCAxNjcuNTQyIDcwLjU4NDMgMTY2LjIxMyA3Mi4yMjM1IDE2Ni4yMTNINzguMTU5N0M3OS43OTg5IDE2Ni4yMTMgODEuMTI3OCAxNjcuNTQyIDgxLjEyNzggMTY5LjE4MUM4MS4xMjc4IDE3MC44MiA3OS43OTg5IDE3Mi4xNDkgNzguMTU5NyAxNzIuMTQ5SDcyLjIyMzVDNzAuNTg0MyAxNzIuMTQ5IDY5LjI1NTQgMTcwLjgyIDY5LjI1NTQgMTY5LjE4MVpNNjkuMjU1NCAxOTIuOTI2QzY5LjI1NTQgMTkxLjI4NiA3MC41ODQyIDE4OS45NTcgNzIuMjIzNSAxODkuOTU3SDc4LjE1OTZDNzkuNzk4OSAxODkuOTU3IDgxLjEyNzcgMTkxLjI4NiA4MS4xMjc3IDE5Mi45MjZDODEuMTI3NyAxOTQuNTY1IDc5Ljc5ODkgMTk1Ljg5NCA3OC4xNTk2IDE5NS44OTRINzIuMjIzNUM3MC41ODQyIDE5NS44OTQgNjkuMjU1NCAxOTQuNTY1IDY5LjI1NTQgMTkyLjkyNlpNNzIuMjIzNSAyMTMuNzAyQzcwLjU4NDIgMjEzLjcwMiA2OS4yNTU0IDIxNS4wMzEgNjkuMjU1NCAyMTYuNjdDNjkuMjU1NCAyMTguMzA5IDcwLjU4NDIgMjE5LjYzOCA3Mi4yMjM1IDIxOS42MzhINzguMTU5NkM3OS43OTg5IDIxOS42MzggODEuMTI3NyAyMTguMzA5IDgxLjEyNzcgMjE2LjY3QzgxLjEyNzcgMjE1LjAzMSA3OS43OTg5IDIxMy43MDIgNzguMTU5NiAyMTMuNzAySDcyLjIyMzVaIiBmaWxsPSIjRjdEMDdGIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNOTAuMDMxOCAxODkuOTU4Qzg4LjM5MjYgMTg5Ljk1OCA4Ny4wNjM3IDE5MS4yODYgODcuMDYzNyAxOTIuOTI2Qzg3LjA2MzcgMTk0LjU2NSA4OC4zOTI2IDE5NS44OTQgOTAuMDMxOCAxOTUuODk0SDk1Ljk2OEM5Ny42MDcyIDE5NS44OTQgOTguOTM2MSAxOTQuNTY1IDk4LjkzNjEgMTkyLjkyNkM5OC45MzYxIDE5MS4yODYgOTcuNjA3MiAxODkuOTU4IDk1Ljk2OCAxODkuOTU4SDkwLjAzMThaTTkwLjAzMTkgMjEzLjcwMkM4OC4zOTI3IDIxMy43MDIgODcuMDYzOCAyMTUuMDMxIDg3LjA2MzggMjE2LjY3Qzg3LjA2MzggMjE4LjMwOSA4OC4zOTI3IDIxOS42MzggOTAuMDMxOSAyMTkuNjM4SDk1Ljk2ODFDOTcuNjA3MyAyMTkuNjM4IDk4LjkzNjIgMjE4LjMwOSA5OC45MzYyIDIxNi42N0M5OC45MzYyIDIxNS4wMzEgOTcuNjA3MyAyMTMuNzAyIDk1Ljk2ODEgMjEzLjcwMkg5MC4wMzE5WiIgZmlsbD0iIzkxRDlCRSIvPgo8L2c+CjxkZWZzPgo8Y2xpcFBhdGggaWQ9ImNsaXAwXzEyNTZfMzcxNjgiPgo8cmVjdCB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgZmlsbD0id2hpdGUiLz4KPC9jbGlwUGF0aD4KPC9kZWZzPgo8L3N2Zz4K",BC=w("templates");function kf(n){const t=n.rootElement.querySelector(":scope .editor-templates");if(!t)return null;const e=t.querySelector(":scope .editor-templates-cards");return d(BC,e,"no card container"),{root:t,cardContainer:e}}function J$(n){const t=kf(n);if(t)return t.cardContainer.innerHTML="",t;const e=b("div",["editor-templates"],n.rootElement);b("div",["editor-templates-title"],e,T.t("templates.title"));const o=b("div",["editor-templates-cards"],e);return{root:e,cardContainer:o}}function EC(n,t,e,o,r){var f;const i=(f=n.options.componentsOptions)==null?void 0:f.templates,s=b("div",["editor-template-card",...o],null),l=b("div",["editor-template-thumb-container"],s),c=b("img",["editor-template-thumb"],l);c.src=t,c.style.display="none",c.onerror=()=>{var C;const m=(C=i==null?void 0:i.placeHolderImageSrc)!=null?C:K$;c.src!==m&&(c.src=m)},c.onload=()=>{c.style.display=""};const a=b("div",["editor-template-name"],s),u=b("span",[],a,e);return i!=null&&i.showTemplateTitleAttr&&u.setAttribute("title",e),s.onclick=()=>r(s),s}function X$(n,t){return t.thumbnailUrl?t.thumbnailUrl:n.doc.buildResourceUrl("thumbnail.png")}function tP(n,t){const e=X$(n,t);return EC(n,e,t.name,[],async()=>{var r,i;const o=(r=n.options.componentsOptions)==null?void 0:r.templates;(i=o==null?void 0:o.onApplyTemplate)==null||i.call(o,n,t)})}function eP(n,t){return EC(n,t,T.t("templates.choose"),["more"],()=>{var o,r;const e=(o=n.options.componentsOptions)==null?void 0:o.templates;(r=e==null?void 0:e.onChooseTemplate)==null||r.call(e,n)})}function nP(n,t){var f,m;const e=(f=n.options.componentsOptions)==null?void 0:f.templates;if(!e)return;const r=Qt(n.rootContainer).getBoundingClientRect().width;let i=1;const s=Q$,l=kf(n);if(l){if(t!=null&&t.reset){const C=Array.from(l.cardContainer.children),v=l.cardContainer.firstElementChild;if(d(BC,v,"no first card"),nt(v,"new")||nt(v,"more"))return;const B=window.getComputedStyle(v),y=parseFloat(B.marginLeft),S=parseFloat(B.marginRight),I=v.getBoundingClientRect().width+y+S;i=Math.floor(r/I);const R=Math.max(1,i-1-1),$=C.length-1;C.forEach((Z,ot)=>{ot>R&&ot<$?Z.style.display="none":(ot>=$&&nt(Z,"more"),Z.style.display="")})}return}const c=e.templates,{cardContainer:a}=J$(n);c.forEach((C,v)=>{const B=tP(n,C);if(v>0&&v>=i&&(B.style.display="none"),a.appendChild(B),v===0){const y=window.getComputedStyle(B),S=parseFloat(y.marginLeft),I=parseFloat(y.marginRight),M=B.getBoundingClientRect().width+S+I;i=Math.floor(r/M)-1}});const u=eP(n,s);a.appendChild(u),(m=e==null?void 0:e.onTemplateChooserStatusChanged)==null||m.call(e,n,a,"visible")}const IC=Xt.default(nP,50);function oP(n){var o,r;const t=kf(n);if(!t)return;t.root.remove();const e=(o=n.options.componentsOptions)==null?void 0:o.templates;(r=e==null?void 0:e.onTemplateChooserStatusChanged)==null||r.call(e,n,null,"hide")}function rP(n){const t=n.blocks.root;if(t.length===0)return!0;if(t.length>5)return!1;const e=[...t];e[0].type==="text"&&e[0].heading&&e.splice(0,1);const o=r=>{var i;return r.type!=="text"&&r.type!=="list"?!1:r.text?((i=r.text)==null?void 0:i.length)===0:!0};return e.every(r=>o(r))}function yf(n,t){rP(n.doc.toJSON())?IC(n,t):(IC.cancel(),oP(n))}const iP=800;class sP{constructor(t){h(this,"longPressTimeout",0);h(this,"handleSelectionChange",()=>{});h(this,"handleLongPress",t=>{const e=t.touches[0],o=Tl(this.editor,e.clientX,e.clientY);!o||console.log(o)});h(this,"handleTouchStart",t=>{t.touches.length===1&&(this.longPressTimeout=window.setTimeout(()=>{this.handleLongPress(t)},iP))});h(this,"handleTouchEnd",t=>{this.longPressTimeout&&(window.clearTimeout(this.longPressTimeout),this.longPressTimeout=0)});this.editor=t,this.editor.addListener("selectionChanged",this.handleSelectionChange),document.addEventListener("touchstart",this.handleTouchStart),document.addEventListener("touchend",this.handleTouchEnd)}destroy(){this.editor.removeListener("selectionChanged",this.handleSelectionChange),document.removeEventListener("touchstart",this.handleTouchStart),document.removeEventListener("touchend",this.handleTouchEnd)}}class Ys{constructor(t,e){h(this,"_decrypted",!1);this.editor=t,this.blockData=e}get decrypted(){return this._decrypted||this.blockData.owner===this.editor.doc.getUser().userId}setDecrypted(){this._decrypted=!0}destroy(){}static getState(t,e){return t.addCustom(`encrypted-block-${e.id}`,()=>new Ys(t,e))}}const eU="",Bo=w("encrypted-block");function lP(n,t,e,o,r){const i=r,s=ro(o,"div"),l=Ys.getState(n,i);if(l.decrypted)n.createChildContainer(t,s,i.children[0]),A(o,"decrypted");else{A(o,"encrypted");const c=Rt(o),a=b("div",["password-container"],c),u=b("input",[],a);u.type="text",u.onkeydown=f=>{if(f.key==="Enter"){const m=u.value;if(i.password===Ei.default(`${i.owner}-${m}`)){l.setDecrypted(),n.reloadBlock(o);const C=Ld(n,n.getBlockById(i.id));C&&(n.selection.selectBlock(C,0),n.focus())}}}}return s}function cP(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t)||!bn(r))return null;const i=r;if(n.getBlockData(t).children[0]!==U(i))return null;const l=wt(t,U(i));return new Xe(n,{anchor:l,focus:l})}function aP(n,t,e,o){if(Ys.getState(n,n.getBlockData(t)).decrypted)return null;if(o==="ArrowDown"||o==="ArrowRight"){const s=dt(t);return s?P(s,W(n,s),"end"):P(t,1,"end")}const i=gt(t);return P(i||t,0,"home")}function dP(n,t){return n.getBoundingClientRect()}function uP(n,t,e,o){if(e.isSimple()){d(Bo,o.isSimple(),"from is simple position but to is not simple position"),Bo.debug("full select table"),A(t,"full-selected");return}d(Bo,!o.isSimple(),"from is complex position but end is simple position");const r=e,i=o;d(Bo,r.blockId===i.blockId,"only allow update one table selection"),d(Bo,r.childContainerId===i.childContainerId,"only one container");const s=n.getBlockData(t),l=n.getContainerById(s.children[0]);A(l,"selected")}function hP(n){n.rootContainer.querySelectorAll('[data-type="editor-block"][data-block-type="encrypted"]').forEach(t=>{z(t,"full-selected"),t.querySelectorAll("selected").forEach(e=>{z(e,"selected")})})}function fP(n,t){const e=n.getBlockData(t);return Ys.getState(n,e).decrypted?[n.getContainerById(e.children[0])]:[]}function mP(n,t,e,o,r){return null}function gP(n,t,e,o){d(Bo,e.blockId===o.blockId,"only allow select in single block"),d(Bo,q(t)===e.blockId,"only allow select in single block");const r=n.getBlockData(t);return d(Bo,e.childContainerId===r.children[0],"only one container"),[n.getContainerById(r.children[0])]}function pP(n){return{name:"EncryptedBlock",insertBlockCommandItems:[{id:"insert-encrypted-block",name:"Encrypted Block"}],async handleInsertEmptyBlock(t,e){const o=yn(t.doc),r={id:N(),type:"encrypted",children:[o],owner:t.doc.getUser().userId,ownerDisplayName:t.doc.getUser().displayName,password:Ei.default(`${t.doc.getUser().userId}-1234`)},i=t.doc.getContainerBlocks(o)[0];return t.insertBlock(e.containerId,e.blockIndex,r,At(t,i.id,0))}}}function CP(n,t,e,o){return o==="text"||o==="markdown"?"[Encrypted Block]":"<p>[Encrypted Block]</p>"}const bP={blockType:"encrypted",blockKind:"complex",enableKeyboardSelect:!0,createBlockContent:lP,getBlockTextLength:()=>1,getRangeFromPoint:cP,moveCaret:aP,getCaretRect:dP,updateSelection:uP,clearSelection:hP,getChildContainers:fP,getNextContainer:mP,getSelectedContainers:gP,getOptions:pP,convertTo:CP};function vP(n,t,e){const o=ts(n,t,{components:{blocks:[Ds,Rs,bP],decorators:[new Os],embeds:[ca,C1,H1,F1,z1,n1,U1,uf,df],boxes:[Fc],options:{...e.componentsOptions}}});return o.readonly=!0,o}class kP{constructor(t){this.createOptions=t}createHistoryEditor(t,e){return vP(t,e,this.createOptions)}}w("create-editor");function xC({root:n,childDoc:t,doc:e}){t.uploadResource=e.uploadResource.bind(e),t.buildResourceUrl=e.buildResourceUrl.bind(e);const o=ts(n,t,{shortcuts:[oc],components:{blocks:[Ds,Rs],decorators:[new Os],embeds:[B6,ca,C1,H1,F1,z1,n1,U1,uf,df],boxes:[Fc,vf],options:{}}});return o.input.addHandler(new Qc),o.input.addHandler(new V1(o)),o.input.addHandler(new P_(o)),o}function yP(n,t){const e=Array.from(n.rootContainer.querySelectorAll(`[comment-${t.toLocaleLowerCase()}="${t}"]`)),o=new Set;e.forEach(r=>{const i=F(r);i&&o.add(i)}),o.forEach(r=>{j_(n,r,t)})}class wP{constructor(t){h(this,"listeners",new Set);h(this,"doc");this.editor=t,this.doc=this.editor.doc.externalDoc,this.doc.registerCallback(this)}getComments(){return this.doc.getComments()}getComment(t){return this.doc.getComment(t)}getCommentDoc(t){return this.doc.getCommentDoc(t)}localCreateComment(t,e){this.doc.localCreateComment(t,e)}localDeleteComment(t){const e=this.getComment(t);this.doc.localDeleteComment(t);const o=e.groupId;this.getComments().filter(i=>i.groupId===o).length===0&&yP(this.editor,o)}localUpdateComment(t,e){this.doc.localUpdateComment(t,e)}onCreateComment(t,e){Array.from(this.listeners.values()).forEach(o=>o.onCreateComment(t,e))}onDeleteComment(t,e){Array.from(this.listeners.values()).forEach(o=>o.onDeleteComment(t,e))}onUpdateComment(t,e){Array.from(this.listeners.values()).forEach(o=>o.onUpdateComment(t,e))}addListener(t){this.listeners.add(t)}removeListener(t){this.listeners.delete(t)}createCommentEditor(t,e){return xC({root:t,childDoc:e,doc:this.doc})}}class BP{constructor(t,e){h(this,"listeners",new Set);this.editor=t,this.localDoc=e}get doc(){return this.localDoc.toJSON()}getComments(){return Object.values(this.doc.comments)}getComment(t){return this.doc.comments[t]}getCommentDoc(t){const e=this.doc.comments[t];return Yu(e)}addListener(t){this.listeners.add(t)}removeListener(t){this.listeners.delete(t)}localCreateComment(t,e){}localDeleteComment(t){}localUpdateComment(t,e){}createCommentEditor(t,e){return xC({root:t,childDoc:e,doc:this.localDoc})}}const EP={placeholder:{common:{title:"\u8BF7\u8F93\u5165\u6807\u9898",readonlyTitle:"\u8BF7\u8F93\u5165\u6807\u9898",content:"\u70B9\u51FB + \uFF0C\u6216\u8F93\u5165 / \u5FEB\u6377\u63D2\u5165\u7EC4\u4EF6"},local:{readonlyTitle:"\u672A\u547D\u540D"}}},IP={placeholder:{common:{title:"Enter a title",readonlyTitle:"Enter a title",content:'Click "+", or enter "/" to insert components quickly'},local:{readonlyTitle:"Untitled"}}};T.mergeLang({"zh-CN":EP,"en-US":IP});const wf=w("create-editor"),TC=[ca,C1,H1,F1,z1,n1,U1,uf,df,B6,yC,IN];async function xP(n,t){var s,l,c,a,u,f,m,C,v,B,y,S;d(wf,n,"app does not exists"),t.lang&&T.setLang(t.lang);const e=t.onReauth?async()=>{var $;const I=t.user.userId,M=t.docId,R=await(($=t.onReauth)==null?void 0:$.call(t,I,M,t.permission));return{userId:I,docId:M,permission:t.permission,appId:t.appId,token:R,displayName:t.user.displayName,avatarUrl:t.user.avatarUrl}}:void 0,o={auth:{appId:t.appId,docId:t.docId,userId:t.user.userId,permission:t.permission,token:t.token,displayName:t.user.displayName,avatarUrl:t.user.avatarUrl},serverUrl:t.serverUrl,reauthFunc:e,disableLogout:t.disableLogout},r=await fs.load(o),i=ts(n,r,{id:t.id,components:{blocks:[Ds,Rs,E1,u4],commandProviders:[new Bh,...((s=t.components)==null?void 0:s.commandProviders)||[]],decorators:[new Os,new Ku],embeds:[...TC,...((l=t.components)==null?void 0:l.embeds)||[]],boxes:[Fc,vf,U3,...((c=t.components)==null?void 0:c.boxes)||[]],insertions:[Kd],blockHooks:[new g6,...((a=t.components)==null?void 0:a.blockHooks)||[]],textRenders:[new $3,new aI],options:{...t.componentsOptions}},shortcuts:[nL,$M,d1,m3,dI,i1,oc],colors:["#338FE5","#24B47E","#F0A100","#E52727","#9678D3","#2CB2AE","#EB6414","#8AAB3F"]});if(i.editorCommandProviders.registerCommandProvider(new Ln(i)),i.input.addHandler(new D$),i.input.addHandler(new Qc),i.input.addHandler(new oT),i.input.addHandler(new LM),i.input.addHandler(new Ms(i,{headingLevel:1,titlePlaceholder:T.t("placeholder.common.title"),contentPlaceholder:T.t("placeholder.common.content"),readonlyTitlePlaceholder:T.t("placeholder.common.readonlyTitle"),addPlaceholderToAllCurrentEmptyBlock:!0})),i.input.addHandler(new zc(i,(u=t.componentsOptions)==null?void 0:u.quickMenu)),i.input.addHandler(new V1(i)),i.input.addHandler(new i3(i)),i.input.addHandler(new JD),i.doc.registerCallback(new L$(i)),i.addCustom("remote-cursor",()=>new F2(i)),i.addCustom("block-menu",I=>new v6(I)),i.addCustom("editor-tooltip",()=>new r1(i)),t!=null&&t.enableComments&&i.addCustom("editor-comments",I=>new N3(I,new wP(I))),i.addCustom("create-options",()=>new Kf(i,t)),i.addCustom("drop-target",()=>new Hs(i)),i.addCustom("list-to-mindmap",()=>new Hc(i)),i.addCustom("list-to-mention",()=>new G$(i)),i.addCustom("mobile-helper",()=>new sP(i)),i.addCustom("code-caret",()=>new KD(i)),(f=t.componentsOptions)!=null&&f.mention){const I=t.componentsOptions.mention;i.addCustom("mention",()=>new z$(i,I))}if(i.addCustom("heading-collapse",()=>new I$(i)),Xr.register(i),Hs.register(i),mr.register(i),(C=(m=t.componentsOptions)==null?void 0:m.remoteCarets)!=null&&C.onUserChanged){const I=(B=(v=t.componentsOptions)==null?void 0:v.remoteCarets)==null?void 0:B.onUserChanged;i.doc.getRemoteUsers().on("change",M=>{I(i,M)})}return(S=(y=t.componentsOptions)==null?void 0:y.templates)!=null&&S.templates.length&&(i.addListener("docChanged",()=>{yf(i)}),i.addListener("resize",()=>{yf(i,{reset:!0})}),setTimeout(()=>{yf(i)},100)),i.doc.registerCallback({onError:async I=>{if(I.code==="ResetDoc"){wf.error(`reset doc: ${I.message}`);const M=await fs.load(o);i.doc.reset(M)}}}),i}function TP(n){return n.toJSON!==void 0}async function SP(n,t,e){var i,s,l;d(wf,n,"app does not exists");const o=TP(t)?t:new Ru(t,{serverUrl:e.serverUrl||""});e.lang&&T.setLang(e.lang);const r=ts(n,o,{id:e.id,components:{blocks:[Ds,Rs,E1,u4],commandProviders:[new Bh],decorators:[new Os,new Ku],embeds:[...TC,...((i=e.components)==null?void 0:i.embeds)||[]],boxes:[Fc,vf,U3],insertions:[Kd],blockHooks:[new g6,...((s=e.components)==null?void 0:s.blockHooks)||[]],textRenders:[new $3],options:{...e.componentsOptions}},shortcuts:[d1,m3,i1,oc]});return r.editorCommandProviders.registerCommandProvider(new Ln(r)),r.input.addHandler(new Qc),r.input.addHandler(new Ms(r,{headingLevel:1,titlePlaceholder:T.t("placeholder.common.title"),contentPlaceholder:T.t("placeholder.common.content"),readonlyTitlePlaceholder:T.t("placeholder.local.readonlyTitle"),addPlaceholderToAllCurrentEmptyBlock:!0})),r.input.addHandler(new zc(r,(l=e.componentsOptions)==null?void 0:l.quickMenu)),r.input.addHandler(new V1(r)),r.input.addHandler(new i3(r)),r.addCustom("block-menu",c=>new v6(c)),r.addCustom("editor-tooltip",()=>new r1(r)),e!=null&&e.enableComments&&r.addCustom("editor-comments",c=>new N3(c,new BP(c,o))),Xr.register(r),r}function DP(n,t){var l;const e=n.doc;if(!((l=e.getVersionHelper)==null?void 0:l.call(e)))throw new Error("the editor does not support to show versions");const r=n.getCustom("create-options");if(!r)throw new Error("the editor does not support to show versions");const i=r.getData(),s=new kP(i);return m$(n,s,t)}g.tippy=p7,g.AuthError=fc,g.AuthHeader=hs,g.AutoScroll=Am,g.BaseURLHeader=mc,g.BlockResizer=Yc,g.BrBox=up,g.CodeBlock=Rs,g.CodeLineBlock=E1,g.CodeTextDecorator=Os,g.DefaultShortcuts=oc,g.DocIdError=rw,g.DragDrop=um,g.DrawioEmbed=ca,g.EditorBlocks=Cg,g.EditorBoxes=fp,g.EditorCommandProviders=n2,g.EditorComplexBlockPosition=Je,g.EditorComplexSelectionRange=Xe,g.EditorDecorators=Cp,g.EditorEmbeds=vg,g.EditorInsertions=pp,g.EditorSimpleBlockPosition=qt,g.EditorSimpleSelectionRange=ce,g.EmbedBlock=yg,g.EnforceWithDocumentTitleHandler=Ms,g.EventCallbacks=xi,g.FILL_CHAR=Rb,g.FileExtError=iw,g.HeadingBlockScrollListener=F$,g.InputtingInsertion=mp,g.LocalDoc=Ru,g.Logger=br,g.MIN_DISTANCE_THRESHOLD=am,g.ManualMenu=tr,g.ManualToolbar=ps,g.MarkdownInputHandler=Qc,g.MaxUserError=Vu,g.OnesEditorAutoSuggest=mh,g.OnesEditorCustomDataWrapper=Kf,g.OnesEditorHoveringBlock=Nt,g.OnesEditorQuickMenu=zc,g.OnesEditorToc=Zs,g.OnesEditorTocProvider=mr,g.OnesEditorToolbar=Xr,g.OnesEditorTooltip=r1,g.PermissionError=ow,g.Popup=ms,g.RemoteCarets=F2,g.RemoteCaretsDecorator=Ku,g.RemoteCaretsInsertion=Kd,g.RemoteUsers=ic,g.RequestReloadError=us,g.RichText=ie,g.ShareDBDoc=fs,g.SimpleCache=Xf,g.StandardEmbedBlockCommands=g1,g.TEXT_STYLE_BACKGROUND_COLOR_PREFIX=Ud,g.TEXT_STYLE_COLOR_PREFIX=zd,g.TableBlock=Ds,g.TableBlockCommandProvider=Bh,g.TableShortcuts=d1,g.TextBlock=ve,g.TextBox=dp,g.TextStyleShortcuts=i1,g.TocEmbed=yC,g.ZERO_WIDTH_SPACE_CHAR=Ti,g.addAttribute=Ol,g.addClass=A,g.addCommentToBlock=m1,g.addDays=i8,g.addMonths=r8,g.animateScrollTo=td,g.applyPlaceholderToBlock=Kc,g.assert=d,g.blockToDoc=xu,g.blockToHtml=eu,g.blockToMarkdown=nu,g.blockToText=ql,g.blocksToDoc=qv,g.clearAllSelection=lg,g.clientType=xt,g.cloneBlock=ao,g.cloneChildContainer=hu,g.cloneDoc=fu,g.cloneText=tp,g.commentToShareDbComment=Qu,g.compareElement=fl,g.comparePosition=Sd,g.complexBlockAdjustSelectionPos=xl,g.complexBlockFindNearestChildBlock=Ig,g.complexBlockGeFirstSimpleChild=Ld,g.complexBlockGetAllChildContainers=Se,g.complexBlockGetBottomChildContainers=Eg,g.complexBlockGetLastSimpleChild=Ni,g.complexBlockGetSelectedContainers=xr,g.complexBlockGetTopChildContainers=Bg,g.containerToDoc=R0,g.continuousScroll=Rm,g.convertBlockFrom=Oi,g.copyBlockAttributes=Lp,g.createBlockAnchor=zo,g.createBlockCaretAnchor=Dg,g.createBlockContentElement=ro,g.createBlockElement=zm,g.createBlockSimpleDocRange=Fl,g.createBlockSimpleRange=At,g.createBoxContentElement=qm,g.createBoxElement=Um,g.createBoxOp=qg,g.createChildContainer=rg,g.createComplexBlockPosition=wt,g.createComplexDocPos=sp,g.createComplexDocRange=_b,g.createContainer=op,g.createContainerElement=bd,g.createDeleteOps=Fg,g.createEditor=ts,g.createEditorSelectionRange=Wt,g.createElement=b,g.createEmptyContainer=yn,g.createEmptyDoc=Zo,g.createEmptyTextBlockData=Pl,g.createExpandedRange=ul,g.createIconButton=vr,g.createImage=tm,g.createInsertOps=Al,g.createInsertionContentElement=Zm,g.createInsertionElement=Wm,g.createLocalEditor=SP,g.createOnesEditor=xP,g.createRange=em,g.createRichText=Go,g.createRootContainer=og,g.createSimpleBlockPosition=P,g.createSimpleDocPos=ip,g.createTextBlockData=zn,g.createTextButton=sr,g.createTextOp=$e,g.createTextWithReplaceSoftReturn=Pd,g.daysAfter=ad,g.deleteText=Hd,g.diffDays=s8,g.disablePageScroll=Im,g.docToHtml=Ep,g.docToHtmlFragment=Vi,g.docToMarkdown=qi,g.docToText=Wl,g.downloadObjectToFile=_1,g.downloadSvgToString=I6,g.editLink=Rc,g.editorAddComment=F_,g.editorAddTextAttribute=Fp,g.editorAutoInsertBlock=Mp,g.editorBreakTextBlock=Rr,g.editorClearCompositionText=Dp,g.editorClearSelectedContents=du,g.editorCopyBlock=nc,g.editorDeleteBlock=cu,g.editorDeleteBlockText=iu,g.editorDeleteBlockWithoutChildren=lu,g.editorDeleteChildContainer=Iv,g.editorDeleteChildContainers=Rp,g.editorFocusToBlock=uu,g.editorFocusToEnd=L0,g.editorGetBlockData=co,g.editorGetBlockText=ue,g.editorGetBlockTextEx=Ul,g.editorGetBoxData=cp,g.editorHandleKeyboardEvent=$0,g.editorInsertBlock=Mr,g.editorInsertBoxToBlock=Tp,g.editorInsertDoc=jp,g.editorInsertDocAt=mu,g.editorInsertText=ru,g.editorInsertTextToBlock=xp,g.editorInsertTextToBlockEx=ou,g.editorMergeTextBlock=Ap,g.editorMoveDown=Xp,g.editorMoveEnd=a0,g.editorMoveHome=d0,g.editorMoveLeft=Qp,g.editorMoveLineEnd=b0,g.editorMoveLineHome=C0,g.editorMovePageDown=E0,g.editorMovePageUp=B0,g.editorMoveRight=Kp,g.editorMoveUp=Jp,g.editorMoveWordEnd=s0,g.editorMoveWordLeft=i0,g.editorRangeClearColor=Up,g.editorRangeGetColor=gu,g.editorRangeSetColor=zp,g.editorRemoveTextAttribute=Sv,g.editorReplaceBlockText=Kl,g.editorReplaceContainer=Hp,g.editorRunOnce=Au,g.editorSelectAll=D0,g.editorSelectContainer=Eu,g.editorSelectDown=t0,g.editorSelectEnd=wu,g.editorSelectHome=u0,g.editorSelectLeft=e0,g.editorSelectLineEnd=p0,g.editorSelectLineHome=g0,g.editorSelectPageDown=x0,g.editorSelectPageUp=I0,g.editorSelectRight=n0,g.editorSelectUp=o0,g.editorSelectWordEnd=c0,g.editorSelectWordLeft=l0,g.editorSetTextColor=Ar,g.editorShowFindDialog=ZO,g.editorUpdateBlockData=Jl,g.editorUpdateCompositionText=Sp,g.editorUpdateEmbedData=$p,g.enablePageScroll=xm,g.escapeHtmlText=sm,g.escapeRegExp=hd,g.escapeSpace=F7,g.executeBlockCommand=pg,g.executeEmbedBlockCommand=gg,g.executeRangeCommand=e2,g.fileToDataUrl=pl,g.findAfterOffsetNotType=Zd,g.findAllText=Wd,g.findInsertionById=Gm,g.findNextOffset=Jb,g.findPrevOffset=Kb,g.findPrevOffsetNotType=Gd,g.findPrevSimpleBlockBeforeChildContainer=wg,g.findTarget=Di,g.findWordEnd=Qd,g.findWordLeft=Yd,g.format=cd,g.formatBytes=Om,g.formatDate=$m,g.fragmentToHtml=Tm,g.fromBase64=gl,g.fromBase64ToBlob=wm,g.fromBase64ToUint8Array=X7,g.fromDocRange=io,g.fromNowString=ud,g.genId=N,g.getAllChildBlocks=Rd,g.getAllQuickMenuItems=o1,g.getAllSelectedBlocks=tn,g.getAttributesAt=Nl,g.getBlockBackground=Fm,g.getBlockByIndex=kr,g.getBlockCaretRect=Ke,g.getBlockClass=bt,g.getBlockClassByType=Er,g.getBlockClientRects=Ho,g.getBlockCommandsWithHook=Ed,g.getBlockContent=it,g.getBlockId=q,g.getBlockIndex=J,g.getBlockKind=Qe,g.getBlockMinWidth=ag,g.getBlockNearestRangeFromPoint=Tg,g.getBlockOptions=p8,g.getBlockPath=jo,g.getBlockProperties=hg,g.getBlockRangeFromPoint=Tl,g.getBlockStyles=m8,g.getBlockTextLength=W,g.getBlockTools=Rt,g.getBlockType=rt,g.getBoxContent=gd,g.getBoxId=Vm,g.getBoxTypeFromElement=Ri,g.getChildBlockCount=Ge,g.getChildBlocks=Mt,g.getChildOffset=so,g.getColorFromAttributes=qd,g.getComplexBlockClass=xe,g.getContainerBlockPath=tg,g.getContainerBlocks=Jm,g.getContainerBlocksElement=El,g.getContainerById=Br,g.getContainerId=U,g.getContainerMinWidth=wd,g.getContainerToolsElement=a8,g.getContainerWidth=ug,g.getDistanceSquare=Cn,g.getElementOffset=Si,g.getEmbedType=Oe,g.getExistsBlockTools=Bl,g.getExistsContainerById=Qm,g.getFileExt=Dm,g.getFirstChildBlock=Vt,g.getFirstClientRect=hl,g.getHeadingMenuOptions=Kh,g.getHorizontalPadding=Qa,g.getInsertionContent=pd,g.getLastChildBlock=Qt,g.getLastClientRect=Mo,g.getListAllNextBrothers=Is,g.getLogger=w,g.getNextBlock=dt,g.getNextValidOffset=Vo,g.getNextVisibleBlock=wr,g.getOffsetInfoAfter=Ui,g.getOffsetInfoBefore=Vl,g.getOpAt=Gg,g.getOpLength=Fd,g.getParentBlock=F,g.getParentBox=md,g.getParentContainer=H,g.getPrevBlock=gt,g.getPrevValidOffset=lo,g.getPrevVisibleBlock=yr,g.getRangeCommands=X0,g.getRootBlock=yd,g.getScrollContainer=We,g.getSpecialBlockCommands=fg,g.getStandardEmbedBlockProperties=p1,g.getTextAfterOffset=Yb,g.getTextBeforeOffset=Qb,g.getTextBlockChild=Sl,g.getTextBlockClass=sg,g.getTextBlockContentChildTextLength=Ne,g.getTextBlockContentChildType=Sg,g.getTextBlockContentChildren=Fn,g.getTextLength=de,g.getTextOpLength=Ad,g.getTextWidth=bl,g.getToolbar=Mc,g.handleBlockElementUpdated=dg,g.hasAltOnly=G7,g.hasClass=nt,g.hasCtrlOrCmd=bm,g.hasCtrlOrCmdOnly=W7,g.hideBlock=jm,g.htmlToFragment=Cl,g.i18n=T,g.injectStyle=cm,g.insertEmptyBlock=b8,g.insertEmptyEmbedBlock=Id,g.insertText=Sr,g.intersectionCommands=Kk,g.isBackspace=km,g.isBlock=Po,g.isBox=fd,g.isCJK=gm,g.isChildContainer=Ye,g.isChildNode=It,g.isCollapsedRange=Ob,g.isComplexBlockPosition=Td,g.isComplexKindBlock=at,g.isContainer=bn,g.isContainerSelectedAllChildBlocks=T0,g.isControlEvent=Oo,g.isDelete=Y7,g.isDraggingFiles=kl,g.isEmbedBlock=Te,g.isEmptyContainer=Bd,g.isEmptyDoc=jl,g.isEmptyTextBlock=Tt,g.isEmptyTextBlockWithoutCompositionText=Ls,g.isEnterOnly=vm,g.isEscape=id,g.isFirefox=od,g.isFirstChildBlockInComplexBlock=W8,g.isHighSurrogate=_7,g.isInBlock=Cd,g.isInBlockTools=Ai,g.isLetter=mm,g.isLowSurrogate=Ya,g.isMatchShortcut=Pn,g.isMoveForward=V7,g.isNavigationEvent=U7,g.isNavigationKey=Cm,g.isNodeRemoved=om,g.isNumber=fm,g.isPrintableKey=rd,g.isRootBlock=Ko,g.isRootContainer=pt,g.isSafari=pm,g.isSameDay=dd,g.isShiftEnter=Z7,g.isShiftTab=K7,g.isShortcutEvent=q7,g.isSimpleBlock=g8,g.isSimpleBlockPosition=Ir,g.isSimplePos=rp,g.isSimpleRange=Hl,g.isSpace=ml,g.isTab=Q7,g.isTextBlockContentBoxChild=_e,g.isTextBlockContentChild=$i,g.isTextBlockContentInsertionChild=Hn,g.isTextBlockContentTextChild=Pi,g.isTextKindBlock=j,g.isTextKindBlockType=_i,g.isToday=_m,g.isValidOffset=re,g.isVisibleBlock=wl,g.isYesterday=Nm,g.loadJs=rm,g.loadJsPromise=Ro,g.lockers=qe,g.mergeCommands=Lc,g.mergeDocs=Yo,g.mergeOps=jd,g.mergeText=Sb,g.multiSplitText=Rg,g.parseShortcut=ym,g.patchNode=Mi,g.pointInRect=Ao,g.rangeAddAttribute=_l,g.rangeGetTextColor=Xg,g.rangeRemoveAttribute=Dr,g.rangeSetTextColor=Qg,g.rangeTransformText=Zg,g.registerDragDrop=ed,g.removeAttribute=Vd,g.removeClass=z,g.removeLastBr=Eb,g.removePlaceholderFromBlock=V4,g.removeStyle=lm,g.replaceAll=l8,g.replaceAllCaseInsensitive=c8,g.replaceAllText=np,g.replaceText=$l,g.requestDownload=yl,g.resetListStart=Ts,g.scrollable=Mm,g.selectFile=No,g.selectedBlockToDoc=tc,g.selectionToDoc=Ji,g.setAttributes=Ja,g.setClipboardData=vl,g.setClipboardDataByEvent=o8,g.setColorToAttributes=Kg,g.setDataset=Ka,g.setDefaultCursor=Li,g.setStyles=Xa,g.shareDBCommentToDocObject=Yu,g.shareDBDocCommentToComment=j2,g.shortcutToDisplayText=J7,g.showBlock=Hm,g.showDocVersions=DP,g.splitText=be,g.splitToThree=Gt,g.stringToDataUrl=Bm,g.stringToObjectUrl=ld,g.subText=Ag,g.textNodeOffsetFromPoint=nm,g.toBase64URL=_o,g.toPlainText=vt,g.trimChar=nd,g.unicodeLength=N7,g.unicodeSubstr=$7,g.updateBlockSelection=cg,g.updateOpAttributes=ep,g.updateTextBlockContent=Zb,g.updateUrl=sd,Object.defineProperties(g,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
686
+ </svg>`,{t:hf}=T;class QN{constructor(t){h(this,"goBackButton");h(this,"playButton");h(this,"revertButton");this.options=t;const e=b("button",["dialog-text-button"],null),o=b("span",["dialog-button-icon"],e);o.innerHTML=YN,b("span",["dialog-button-text"],e,hf("version.goBack"));const r=b("button",["dialog-version-button"],null,hf("version.play")),i=b("button",["dialog-version-button"],null,hf("version.revertVersion"));this.goBackButton=e,this.playButton=r,this.revertButton=i,this.bindEvent()}bindEvent(){const{onBack:t,onPlay:e,onRevert:o}=this.options;this.playButton.onclick=e,this.goBackButton.onclick=t,this.revertButton.onclick=o}disabledButton(){}render(t,e=!1){e||t.append(this.goBackButton,this.playButton,this.revertButton)}destroy(){this.playButton.onclick=null,this.goBackButton.onclick=null,this.revertButton.onclick=null}}const Ce=w("split-text-actions");function nC(n){return n.length>2?!1:n.length===1?n[0].insert!==void 0:(d(Ce,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].insert!==void 0)}function oC(n){return n.length>2?!1:n.length===1?n[0].delete!==void 0:(d(Ce,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].delete!==void 0)}function rC(n){return n.length>2?!1:n.length===1?n[0].insert===void 0&&n[0].delete===void 0&&n[0].attributes!==void 0:(d(Ce,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].attributes!==void 0)}function KN(n){const t=[],e=Y.default(n);if(e.length===0)return[];if(e.length===1)return[n];if(e.length===2&&(oC(n)||nC(n)||rC(n)))return[n];const o=(i,s)=>i>0?[{retain:i},s]:[s];let r=0;for(;e.length>0;){const i=e[0];if(i.retain!==void 0&&i.attributes===void 0){d(Ce,i.retain>0,`invalid text op: ${JSON.stringify(i)}`),d(Ce,e.length>1,`invalid text op: ${JSON.stringify(i)}`);const s=e[1];d(Ce,s.delete||s.insert!==void 0||s.attributes!==void 0,`invalid next text op: ${JSON.stringify(s)}`),r+=i.retain,t.push(o(r,s)),s.delete!==void 0?r-=s.delete:s.insert!==void 0?r+=s.insert.length:(d(Ce,s.attributes!==void 0,`invalid next text op: ${JSON.stringify(s)}`),d(Ce,s.retain!==void 0,`invalid next text op: ${JSON.stringify(s)}`),r+=s.retain),e.splice(0,2)}else d(Ce,i.delete||i.insert!==void 0||i.attributes!==void 0,`invalid next text op: ${JSON.stringify(i)}`),t.push(o(r,i)),e.shift(),i.retain!==void 0&&(d(Ce,i.attributes!==void 0,`invalid next text op: ${JSON.stringify(i)}`),r+=i.retain),i.insert&&(r+=i.insert.length)}return t}function iC(n){if(d(Ce,n.length===1||n.length===2,`not a single action op: ${JSON.stringify(n)}`),n.length===1)return 0;const t=n[0].retain;return d(Ce,typeof t=="number"&&t>0,`invalid retain: ${JSON.stringify(n)}`),t}let sC=0;function JN(n,t,e){const o=sC;sC+=1;const r=vt(n);return{insert:" ",attributes:{box:!0,id:N(),type:"history-deleted-box",user:e,created:Date.now(),text:r,deletedOffset:t,deletedOrder:o}}}function XN(n,t,e){const o=iC(t),r=t.length===1?t[0].delete:t[1].delete;d(Ce,typeof r=="number",`not a delete op: ${JSON.stringify(t)}`);const{left:i,middle:s,right:l}=Gt(n,o,r),c=JN(s,o,e);return[...i,c,...l]}function t$(n,t,e){const o=iC(t),r=t.length===1?t[0].insert:t[1].insert;d(Ce,typeof r=="string",`invalid insert op: ${JSON.stringify(t)}`);const i=t.length===1?t[0].attributes:t[1].attributes,l=Ol([{insert:r,attributes:i}],"insertedBy",e);return Sr(n,o,l,null)}function e$(n,t,e){const o=KN(t).reverse();let r=n;for(const i of o)oC(i)?r=XN(r,i,e):nC(i)?r=t$(r,i,e):(d(Ce,rC(i),`unknown op: ${JSON.stringify(i)}`),r=ie.apply(r,i));return r}const n$=w("history-update-block-text");function lC(n){const t=[],e=[];let o=0;return n.forEach(r=>{var i;if((i=r.attributes)!=null&&i.box){const s=r.attributes;if(s.type==="history-deleted-box"){t.push({boxData:s,offset:o});return}}e.push(r),o+=Fd(r)}),t.sort((r,i)=>i.offset-r.offset),{deletedBoxes:t,newText:e}}function o$(n,t,e){let o=n;return t.forEach(r=>{const i=ie.transformCursor(r.offset,e,!1);o=Sr(o,i,[{insert:" ",attributes:r.boxData}],null)}),o}function r$(n){n.sort((t,e)=>t.boxData.deletedOffset!==e.boxData.deletedOffset?t.boxData.deletedOffset-e.boxData.deletedOffset:t.boxData.deletedOrder-e.boxData.deletedOrder)}function i$(n){if(n.length<=1)return n;const t=n[0].offset;n.forEach(e=>{d(n$,e.offset===t,`invalid boxes group, ${JSON.stringify(n)}`)}),r$(n);for(let e=n.length-1;e>=1;e--){const o=n[e],r=n[e-1];o.boxData.user.userId===r.boxData.user.userId&&(r.boxData.text+=o.boxData.text,n.splice(e,1))}return n}function s$(n){let{newText:t,deletedBoxes:e}=lC(n);const o=new Map;return e.forEach(i=>{let s=o.get(i.offset);s||(s=[],o.set(i.offset,s)),s.push(i),s.sort((l,c)=>l.boxData.deletedOffset-c.boxData.deletedOffset)}),Array.from(o.values()).sort((i,s)=>s[0].offset-i[0].offset).forEach(i=>{const s=i[0].offset;i$(i).reverse().forEach(l=>{t=Sr(t,s,[{insert:" ",attributes:l.boxData}],null)})}),t}function l$(n,t,e){let{newText:o,deletedBoxes:r}=lC(n);return o=e$(o,t,e),o=o$(o,r,t),o=s$(o),o}const Rn=w("history-doc");function An(n){d(Rn,!1,"no local actions for history doc")}class c$ extends xi{constructor(e,o){super();h(this,"doc");h(this,"editor");this.doc=Y.default(e),this.editor=o}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return Y.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,o){const r=this.getContainerBlocks(e);d(Rn,r,`no container data: ${e}`);const i=r[o];return d(Rn,i,`no block data: ${o}`),i}localUpdateBlockText(){An()}localUpdateBlockData(){An()}localInsertBlock(){An()}localDeleteBlock(){An()}localInsertChildContainer(){An()}localDeleteChildContainers(){An()}uploadResource(){An()}async addResources(e){An()}getServerMeta(){var e,o,r;return(r=(o=(e=this.editor.doc.externalDoc).getServerMeta)==null?void 0:o.call(e))!=null?r:{}}buildResourceUrl(e){return this.editor.doc.externalDoc.buildResourceUrl(e)}request(){An()}broadcastMessage(){An()}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new ic}destroy(){this.clearCallbacks()}transformBlockIndex(e,o,r){const i=this.doc.blocks[e];d(Rn,i,`no container blocks: ${e}`);let s=0;for(let l=0;l<i.length;l++)if(!i[l].deletedBy){if(s===o)return l;s++}return r&&d(Rn,!1,`invalid block index: ${o}, blocks: ${JSON.stringify(i)}`),d(Rn,s===o,`invalid block index: ${o}, blocks: ${JSON.stringify(i)}`),i.length}onDeleteBlock(e,o,r){const i=this.transformBlockIndex(e,o,!0),l=this.doc.blocks[e][i];d(Rn,!l.deleted,`block has already deleted: ${e}/${o}`),l.deletedBy=r,this.callbacks.forEach(c=>{var a;return(a=c.onUpdateBlockData)==null?void 0:a.call(c,e,i,{insert:{},delete:[]},!0)})}onInsertBlock(e,o,r,i){const s=this.transformBlockIndex(e,o,!1),l=this.doc.blocks[e],c=Y.default(r);c.insertedBy=i,l.splice(s,0,c),this.callbacks.forEach(a=>{var u;return(u=a.onInsertBlock)==null?void 0:u.call(a,e,s,c,!0)})}onUpdateBlockText(e,o,r,i){const s=this.transformBlockIndex(e,o,!0),c=this.doc.blocks[e][s];d(Rn,!c.deleted,`block has already deleted: ${e}/${o}`);const a=c.text;d(Rn,a,`no text for block: ${JSON.stringify(c)}`);const u=l$(a,r,i);c.text=u,this.callbacks.forEach(f=>{var m;return(m=f.onUpdateBlockText)==null?void 0:m.call(f,e,o,r,!0)})}onUpdateBlockData(e,o,r,i){const s=this.transformBlockIndex(e,o,!0),l=this.doc.blocks[e],c=l[s];d(Rn,!c.deleted,`block has already deleted: ${e}/${o}`);const a=Y.default(c);a.updatedBy=i,r.delete.forEach(u=>delete a[u]),Object.entries(r.insert).forEach(([u,f])=>{a[u]=f}),l[s]=a,this.callbacks.forEach(u=>{var f;return(f=u.onUpdateBlockData)==null?void 0:f.call(u,e,s,r,!0)})}onCreateContainer(e,o,r){this.doc.blocks[e]=Y.default(o),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,e,o,!0)})}}const{t:cC}=T;function mi(n,t){return t==="insert"?cC("version.insert",{name:n.displayName}):cC("version.delete",{name:n.displayName})}function hr(n,t){const{userId:e}=t;return["flag","selection"].reduce((r,i)=>{const s=n.doc.getRemoteUsers().getFixedUserColor(e,i);return r[i]=s,r},{})}class a${renderText(t,e,o){if(!o.box&&o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=hr(t,o.insertedBy);return{classes:["history-inserted-text"],attributes:{"history-inserted-by":r.displayName,"data-op-description":mi(r,"insert")},styles:{[ui]:i,[hi]:s}}}return{}}renderBlock(t,e,o){if(o.deletedBy){const r=o.deletedBy,{flag:i,selection:s}=hr(t,r);return{classes:["history-deleted-block"],attributes:{"history-deleted-by":r.displayName,"data-op-description":mi(r,"delete")},styles:{[ui]:i,[hi]:s}}}if(o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=hr(t,r);return{classes:["history-inserted-block"],attributes:{"history-inserted-by":r.displayName,"data-op-description":mi(r,"insert")},styles:{[ui]:i,[hi]:s}}}return{}}updateBlock(t,e,o,r){if(r.deletedBy){const i=r.deletedBy,{flag:s,selection:l}=hr(t,i);A(o,"history-deleted-block"),Ja(o,{"history-inserted-by":i.displayName,"data-op-description":mi(i,"delete")}),Xa(o,{[ui]:s,[hi]:l});return}if(r.insertedBy){const i=r.insertedBy,{flag:s,selection:l}=hr(t,i);A(o,"history-inserted-block"),Ja(o,{"history-inserted-by":i.displayName,"data-op-description":mi(i,"insert")}),Xa(o,{[ui]:s,[hi]:l})}}}const aC=w("history-deleted-box");function d$(n,t,e,o){const r=o;d(aC,r.text,`no text for text box data: ${JSON.stringify(o)}`),d(aC,typeof r.text=="string",`invalid text type for text box data: ${JSON.stringify(o)}`);const i=b("span",["history-deleted-box"],e,r.text),s=r.user,{flag:l,selection:c}=hr(n,s);i.setAttribute("history-deleted-by",s.displayName),i.setAttribute("data-op-description",mi(s,"delete")),i.style.setProperty(ui,l),i.style.setProperty(hi,c)}function u$(n,t,e,o){return t.text}const h$={boxType:"history-deleted-box",updateBoxContent:d$,convertTo:u$},Ee=w("version-dialog");class f${constructor(t,e){h(this,"editor");h(this,"dialog",null);h(this,"oldViewer",null);h(this,"versionOptions");h(this,"versionList",null);h(this,"actionButtons",null);h(this,"provider");h(this,"components");h(this,"handleClose",()=>{var t;(t=this.dialog)==null||t.hide()});h(this,"handlePlay",()=>{var e;d(Ee,this.versionList,"The versionList did not render");const t=(e=this.versionList)==null?void 0:e.activeVersion;d(Ee,t,`The version: ${t} is invalid`),this.viewVersion(t,{play:!0,speed:150})});h(this,"handleRevert",async()=>{var e,o;d(Ee,this.versionList,"The versionList did not render");const t=(e=this.versionList)==null?void 0:e.activeVersion;d(Ee,t,`The version: ${t} is invalid`),await this.versionHelper.revertVersion(t.version),(o=this.dialog)==null||o.hide()});h(this,"handleSelectVersion",t=>{d(Ee,t,`The version: ${t} is invalid`),this.viewVersion(t)});h(this,"viewVersion",async(t,e={play:!1,speed:1e3})=>{var C,v,B;this.oldViewer&&(this.oldViewer.destroy(),this.oldViewer=null),d(Ee,this.versionList,"The versionList did not render"),d(Ee,this.actionButtons,"The actionButtons did not render");const o=t.type==="minor"?this.versionList.beforeVersion:this.versionList.beforeMajorVersion,r=o?o.version:0,i=this.versionList.isSelectedFirstVersion,s=this.versionList.isSelectedLastVersion;this.actionButtons.revertButton.disabled=i,this.actionButtons.playButton.disabled=i;let l=(C=this.versionOptions)==null?void 0:C.hideOps;if((v=this.versionOptions)!=null&&v.onWillChangeVersion){const y=this.versionOptions.onWillChangeVersion(this.editor,t,i,s);y!=null&&y.hideOps&&(l=!0)}let c,a;if(l)c=await this.versionHelper.getVersion(t.version),a=[];else{const y=await this.versionHelper.getHistoryData(t.version,r);c=y.doc,a=y.historyData}const{editorElement:u}=this.components;u.innerHTML="";const f=new c$(c,this.editor),m=this.provider.createHistoryEditor(u,f);m.editorBlockRenders.registerRender(new a$),m.editorBoxes.registerBoxClass(h$),A(m.rootElement,tC.HISTORY);try{await ZN(f,this.versionHelper,a,e)}finally{this.oldViewer=m}(B=this.versionOptions)!=null&&B.onVersionChanged&&this.versionOptions.onVersionChanged(this.editor,m,t,i,s)});h(this,"setShowOps",t=>{var e;if(this.versionOptions){this.versionOptions.hideOps=!t;const o=(e=this.versionList)==null?void 0:e.activeVersion;d(Ee,o,`The version: ${o} is invalid`),this.viewVersion(o)}});this.editor=t,this.provider=e;const o=b("div",["version-dialog"],null),r=b("div",["version-dialog-note-viewer"],o),i=b("div",["version-dialog-action-container"],r),s=b("div",["version-dialog-editor"],r),l=b("div",["version-dialog-versions-list"],o);this.components={root:o,editorElement:s,actionContainer:i,versionsListContainer:l}}get versionHelper(){d(Ee,this.editor.doc.getVersionHelper,"Can not get getVersionHelper from doc");const t=this.editor.doc.getVersionHelper();return d(Ee,t,"current doc does not support version"),t}renderContent(t){var s,l;const{actionContainer:e,versionsListContainer:o}=this.components;e.innerHTML="";const r=new QN({onBack:this.handleClose,onPlay:this.handlePlay,onRevert:this.handleRevert});r.render(e,(s=this.versionOptions)==null?void 0:s.hideActions),this.actionButtons=r,o.innerHTML="";const i=new qN({versions:t,useCreatedBy:(l=this.versionOptions)==null?void 0:l.useCreatedBy,onSelectVersion:this.handleSelectVersion,getMarkColor:c=>{const{flag:a}=hr(this.editor,c);return a}});i.render(o),this.versionList=i}initViewVersion(){var t;if((t=this.versionOptions)!=null&&t.initSelectedVersion){d(Ee,this.versionList,"The versionList did not render");const{initSelectedVersion:e}=this.versionOptions,o=this.versionList.selectVersionByVersionNum(e);d(Ee,o,`The version: ${o} is invalid`),this.viewVersion(o)}else{d(Ee,this.versionList,"The versionList did not render");const e=this.versionList.activeVersion;d(Ee,e,`The version: ${e} is invalid`),this.viewVersion(e)}}async show(t){this.versionOptions={...this.versionOptions,...t};const e=await this.versionHelper.getVersions();if(this.versionOptions.hideNonVersionedOps&&e.length&&e[0].version===-1&&e.shift(),this.versionOptions.onVersionsLoaded&&this.versionOptions.onVersionsLoaded(this.editor,e),this.renderContent(e),this.initViewVersion(),!this.dialog){const{root:o}=this.components;this.dialog=new VN(o)}this.dialog.show(t.container)}destroy(){var t,e,o;(t=this.dialog)==null||t.destroy(),(e=this.versionList)==null||e.destroy(),(o=this.actionButtons)==null||o.destroy()}}function m$(n,t,e){const o=n.addCustom("version-dialog",()=>new f$(n,t));return o.show(e),{setShowOps:o.setShowOps}}const Kz="",g$=w("heading-collapse");function ff(n){var e;const t=Number.parseInt((e=n.getAttribute("data-style-heading"))!=null?e:"",10);return d(g$,t,"not a heading block"),t}function ze(n){return!!n.getAttribute("data-style-heading")}function p$(n){return!nt(n,"heading-collapsed")}function fr(n){return nt(n,"heading-collapsed")}function dC(n){if(gt(n))return!1;const e=H(n);return pt(e)}const C$=w("heading-collapse");function mf(n){d(C$,ze(n),"not a heading block");const t=[],e=ff(n);let o=dt(n);for(;o&&!(ze(o)&&ff(o)<=e);)t.push(o),o=dt(o);return t}function uC(n,t){if(!Ko(t))return;n.selection.selectBlock(t,0),mf(t).forEach(o=>{jm(o)}),A(t,"heading-collapsed")}function gi(n,t){mf(t).forEach(o=>{Hm(o)}),z(t,"heading-collapsed")}function b$(n,t){p$(t)?uC(n,t):gi(n,t)}const v$=[Xu,th,eh,nh,oh,rh,ih,sh];function k$(n){const t=b("button",["heading-collapse-button"],null);return t.setAttribute(`data-editor-tooltip-${n.clientId}`,"Collapse / Expand"),t.innerHTML=Ju,t}function hC(n){return oa(n).querySelector("button.heading-collapse-button")}function fC(n,t){hC(t)||dC(t)||!Ko(t)||T1(t,k$(n),-1)}function y$(n){var t;(t=hC(n))==null||t.remove()}function mC(n,t){oa(t).querySelector("button.heading-collapse-button")||fC(n,t)}function w$(n){const t=ff(n),e=b("button",["heading-marker"],null);return e.innerHTML=v$[t-1],e}function gC(n){return oa(n).querySelector("button.heading-marker")}function gf(n){gC(n)||dC(n)||!Ko(n)||T1(n,w$(n),1)}function pC(n){const t=gC(n);t==null||t.remove()}function CC(n){pC(n),ze(n)&&gf(n)}class B${handleDrop(t,e,o,r){if(kl(e)||!ze(e)||!fr(e))return;const i=mf(e);i.unshift(e);const s=i.reverse();let l=null;return t.doc.beginBatchUpdate(),s.forEach((c,a,u)=>{const f=t.getBlockData(c),m=ao(t.editorBlocks,t.doc.toJSON(),f),C=t.insertDocAt(o,r,m)[0];a===u.length-1&&(l=C)}),t.doc.endBatchUpdate(),t.doc.beginBatchUpdate(),s.forEach(c=>{t.deleteBlock(c)}),t.doc.endBatchUpdate(),l&&uC(t,l),!0}}const E$=w("heading-collapse");class I${constructor(t){h(this,"handleLoad",()=>{this.showCollapseButtons()});h(this,"handleHoverBlock",(t,e)=>{e&&(z(e,"hovering-heading"),ze(e)&&pt(H(e))&&(gf(e),fr(e)||y$(e))),t&&ze(t)&&pt(H(t))&&(A(t,"hovering-heading"),pC(t),fC(this.editor,t))});h(this,"handleClick",(t,e)=>{const o=Di(e,"button.heading-collapse-button");if(!o)return;const r=F(o);!r||(d(E$,ze(r),"not a heading block"),b$(this.editor,r),mC(this.editor,r))});this.editor=t,t.addListener("load",this.handleLoad),t.addListener("click",this.handleClick),Nt.get(t).addListener("change",this.handleHoverBlock),this.showCollapseButtons(),setTimeout(()=>{Hs.get(t).addHandler(new B$)})}showCollapseButtons(){const t=Mt(this.editor.rootContainer).filter(ze);t.length!==0&&(t[0]===Vt(this.editor.rootContainer)&&t.splice(0,1),t.forEach(gf))}destroy(){this.editor.removeListener("load",this.handleLoad),this.editor.removeListener("click",this.handleClick)}}function va(n){const t=n.selection.range;if(t.isCollapsed()||t.start.blockId===t.end.blockId)return;const e=n.getBlockById(t.start.blockId),o=n.getBlockById(t.end.blockId);fr(e)&&gi(n,e),fr(o)&&gi(n,o)}function x$(n){va(n);const t=n.getFocusedBlock();!ze(t)||fr(t)&&gi(n,t)}function T$(n){va(n);const t=n.getFocusedBlock();if(!ze(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===W(n,t)&&fr(t)&&gi(n,t)}function S$(n){va(n);const t=n.getFocusedBlock();if(!ze(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===0&&fr(t)&&gi(n,t)}class D${handleBeforeKeyDown(t,e){return rd(e.key)&&va(t),e.key==="Enter"?(x$(t),!1):e.key==="Delete"?(T$(t),!1):(e.key==="Backspace"&&S$(t),!1)}}class L${constructor(t){this.editor=t}onInsertBlock(t,e,o,r){this.updateBlockIfNeeded(o.id)}onUpdateBlockData(t,e,o,r){const i=this.editor.doc.getBlockData(t,e);this.updateBlockIfNeeded(i.id,o)}updateBlockIfNeeded(t,e){setTimeout(()=>{const o=this.editor.findBlockById(t);if(!!o){if(!ze(o)){e&&e.delete.includes("heading")&&CC(o);return}nt(o,"hovering-heading")&&mC(this.editor,o),CC(o)}},100)}}function M$(n){return!!n.heading}function bC(n){var e;const t=n.heading;return(e=Number.parseInt(`${t}`,10))!=null?e:1}function vC(n,t){var e;return{parentNode:t,children:[],text:vt((e=n.text)!=null?e:[]),level:bC(n),block:n}}class Zs{constructor(){h(this,"nodes",[])}appendBlock(t){const e=this.findParent(bC(t),this.nodes);e?e.children.push(vC(t,e)):this.nodes.push(vC(t,null))}findParent(t,e){const o=e[e.length-1];if(!o||t<=1)return null;if(o.level===t-1)return o;const r=this.findParent(t,o.children);return r||(o.level<t?o:null)}static buildToc(t){const e=new Zs,o=t.blocks.root;for(let r=0;r<o.length;r++){const i=o[r];M$(i)&&e.appendBlock(i)}return e}}class mr extends Yt.TypedEmitter{constructor(e){super();h(this,"toc",new Zs);h(this,"updateToc",Xt.default(()=>{this.updateTocNow()},500));this.editor=e,e.doc.registerCallback(this),this.updateToc()}destroy(){this.editor.doc.unregisterCallback(this)}isHeadingBlock(e){return!!e.heading}onInsertBlock(e,o,r,i){e==="root"&&this.isHeadingBlock(r)&&this.updateToc()}onDeleteBlock(e,o,r){e==="root"&&this.updateToc()}onUpdateBlockText(e,o,r,i){if(e!=="root")return;const s=this.editor.doc.getBlockData(e,o);this.isHeadingBlock(s)&&this.updateToc()}onUpdateBlockData(e,o,r,i){if(e!=="root")return;const s=this.editor.doc.getBlockData(e,o);this.isHeadingBlock(s)&&this.updateToc()}static register(e){return e.addCustom("editor-toc",()=>new mr(e))}static get(e){return e.getCustom("editor-toc")}updateTocNow(){this.toc=Zs.buildToc(this.editor.doc.toJSON()),this.emit("change",this.editor,this.toc)}}const Jz="";function R$(n){return n.nodes.length===0?!0:n.nodes.length>1?!1:n.nodes[0].children.length===0}function pf(n,t){t.forEach(e=>{const o=b("div",["toc-node"],n),r=b("div",["toc-title"],o);if(b("span",["toc-text"],r,e.text).setAttribute("data-block-id",e.block.id),e.children.length>0){const s=b("div",["toc-children"],o);pf(s,e.children)}})}function A$(n,t){const e=Di(t,".toc-text");if(!e)return;const o=e.getAttribute("data-block-id");if(!o)return;const r=n.findBlockById(o);!r||(t.preventDefault(),t.stopPropagation(),n.selection.selectBlock(r,0))}function kC(n,t,e){if(z(t,"loading"),t.innerHTML="",R$(e)){b("div",["toc-empty-message"],t,"No toc");return}e.nodes.length===1?pf(t,e.nodes[0].children):pf(t,e.nodes),Au(n,"toc-click-handler",()=>{n.addListener("click",A$)})}class O${constructor(t){h(this,"handleUpdateToc",(t,e)=>{Array.from(t.rootContainer.querySelectorAll('.embed-block[data-type="editor-block"][data-embed-type="toc"]')).forEach(r=>{const i=r.querySelector(".editor-toc-container");i&&kC(t,i,e)})});this.editor=t,mr.register(t).addListener("change",this.handleUpdateToc)}destroy(){mr.register(this.editor).removeListener("change",this.handleUpdateToc)}get toc(){return mr.register(this.editor).toc}}function _$(n,t){const e=b("div",["editor-toc-container","embed-selected-content"],t),r=n.addCustom("init-editor-toc",()=>new O$(n)).toc;r.nodes.length===0?A(e,"loading"):kC(n,e,r)}function N$(n,t,e,o){return o==="markdown"?"[toc]":""}function $$(n,t,e){const{data:o}=e;if(!o||o.embedType!=="toc"||!j(n,t))return null;const r={};return{blockData:{id:N(),type:"embed",embedType:"toc",embedData:r}}}const yC={embedType:"toc",createEmbedContent:_$,convertTo:N$,convertFrom:$$};function P$(n){return!!n.getAttribute("data-style-heading")}function Cf(n,t){return P$(t)&&W(n,t)>0}function j$(n){const t=We(n.rootElement);let e=0,o=0,r=0;if(t===document.documentElement){const i=n.rootContainer.getBoundingClientRect();e=i.left+i.width/2,o=10,r=t.offsetHeight}else{const i=t.getBoundingClientRect();e=i.left+i.width/2,o=i.top+10,r=i.bottom}for(;o<r;){const i=document.elementsFromPoint(e,o);for(let s=0;s<i.length;s++){const l=F(i[s]);if(l&&n.rootContainer.contains(l))return l}o+=10}return null}function bf(n,t){let e=t;for(;e&&!Cf(n,e);)e=dt(e);return e}function wC(n){if(gt(n))return!1;const e=H(n);return pt(e)}function ka(n,t){let e=t;for(;e&&!Cf(n,e);)e=gt(e),e&&wC(e)&&(e=null);return e}const H$=.3;class F$ extends Yt.TypedEmitter{constructor(e){super();h(this,"scrollContainer");h(this,"scrollEventTarget");h(this,"scrollStatus",{curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null});h(this,"handleScroll",Xt.default(()=>{const e={curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null};let o=j$(this.editor);if(o&&(o=yd(o)),!o||!this.scrollContainer){this.setStatus(e);return}if(wC(o)&&(o=dt(o)),!o){this.setStatus(e);return}if(Cf(this.editor,o)){e.curHeadingBlock=o,e.previousHeadingBlock=ka(this.editor,o),e.nextHeadingBlock=bf(this.editor,o),this.setStatus(e);return}const r=this.scrollContainer.getBoundingClientRect(),i=bf(this.editor,o);if(i){const l=i.getBoundingClientRect();if(l.top>r.top&&l.top<r.top+r.height*H$){e.curHeadingBlock=i,e.previousHeadingBlock=ka(this.editor,i),e.nextHeadingBlock=bf(this.editor,i),this.setStatus(e);return}e.nextHeadingBlock=i}const s=ka(this.editor,o);s&&(e.curHeadingBlock=s,e.previousHeadingBlock=ka(this.editor,s)),this.setStatus(e)},200));this.editor=e,setTimeout(()=>{this.start()},50)}setStatus(e){this.scrollStatus.previousHeadingBlock===e.previousHeadingBlock&&this.scrollStatus.nextHeadingBlock===e.nextHeadingBlock&&this.scrollStatus.previousHeadingBlock===e.previousHeadingBlock||(this.scrollStatus=e,this.emit("change",this.editor,e))}start(){this.stop(),this.scrollContainer=We(this.editor.rootElement),this.scrollEventTarget=this.scrollContainer===document.documentElement?document:this.scrollContainer,this.scrollEventTarget.addEventListener("scroll",this.handleScroll),this.handleScroll()}stop(){this.scrollEventTarget&&this.scrollEventTarget.removeEventListener("scroll",this.handleScroll)}destroy(){this.stop(),this.scrollEventTarget=void 0}}class z${constructor(t,e){h(this,"suggest");h(this,"onShow",(t,e,o,r)=>{const i=this.editor.getBlockByIndex(e,o);if(!Ko(i)){const s=F(H(i));if(s&&rt(s)==="code")return!1}return!0});h(this,"onClickItem",(t,e,o)=>{const r=e.data,i={id:N(),type:"mention",box:!0,created:Date.now(),iconUrl:r.avatarUrl,text:r.displayName,mentionId:r.userId},s=this.editor.selection.range;if(!s.isCollapsed()||!s.isSimple())return;const l=s.focus,c=this.editor.getBlockById(l.blockId);this.editor.insertBoxToBlock(c,l.offset,i)});h(this,"queryItems",async(t,e)=>(await this.options.queryUsers(this.editor,e)).map(i=>({id:i.userId,name:i.displayName,icon:`<img src="${i.avatarUrl}" class="mention-user-avatar">`,element:i.element,data:i,subText:i.email})));this.editor=t,this.options=e,this.suggest=new mh(t,{id:"editor-mention",trigger:["@"],autoDeleteTrigger:!0,showLoading:!0,onShow:this.onShow,onClickItem:this.onClickItem,queryItems:this.queryItems})}destroy(){}}w("mathjax-box");function U$(n,t,e,o){const r=o,i=b("a",["mention-container"],e);b("span",["mention-name"],i,`@${r.text}`),i.setAttribute("data-mention-id",r.mentionId)}function V$(n,t,e){}function q$(n,t,e,o){return`@${t.text}`}const vf={boxType:"mention",updateBoxContent:U$,handleClickBox:V$,convertTo:q$};function W$(n){return go("list-block-mention",T.t("list.mention.tooltip"),mB,[],n.clientId)}class G${constructor(t){h(this,"mentionButton");h(this,"handleHoveringBlock",t=>{var e;!this.editor.isWritable()||(t&&this.shouldBlockShowMention(t)?Rt(t).appendChild(this.mentionButton):(e=this.mentionButton)==null||e.remove())});h(this,"handleMouseDown",(t,e)=>{e.preventDefault(),e.stopPropagation();const o=F(this.mentionButton);if(!o||!j(t,o))return;const r=t.selection.range.focus;if(!r.isSimple())return;let i;t.selection.focusedBlock!==o?i=W(t,o):i=r.offset,setTimeout(()=>{const s=t.insertTextToBlock(o,i,"@");i+=1;const l=vt(be(s,i).left);this.editor.selection.selectBlock(o,i),this.editor.focus(),t.getCustom("mention").suggest.popup(o,i,l,"@")})});h(this,"destroy",()=>{Nt.get(this.editor).removeListener("change",this.handleHoveringBlock)});this.editor=t,this.mentionButton=W$(t),Nt.get(this.editor).addListener("change",this.handleHoveringBlock),t.domEvents.addEventListener(this.mentionButton,"mousedown",this.handleMouseDown)}shouldBlockShowMention(t){if(!j(this.editor,t)||!ct(t))return!1;const e=Fe(t);return!(e==="ordered"||e==="unordered")}}const Xz="",Z$={templates:{title:"\u9009\u62E9\u6A21\u677F\uFF0C\u5FEB\u901F\u521B\u5EFA",create:"\u65B0\u5EFA\u6A21\u677F",choose:"\u5168\u90E8\u6A21\u677F",customizedMark:"\u81EA\u5B9A\u4E49"}},Y$={templates:{title:"Choose a template",create:"New template",choose:"All templates",customizedMark:"Custom"}};T.mergeLang({"zh-CN":Z$,"en-US":Y$});const tU="",Q$="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjEyMCIgaGVpZ2h0PSIxMjAiIHZpZXdCb3g9IjAgMCAxMjAgMTIwIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cmVjdCB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTQ4IDU5QzQ4IDU0LjU4MTcgNTEuNTgxNyA1MSA1NiA1MUg5M0M5OC41MjI4IDUxIDEwMyA1NS40NzcyIDEwMyA2MVY4OEMxMDMgOTEuODY2IDk5Ljg2NiA5NSA5NiA5NUg1NkM1MS41ODE3IDk1IDQ4IDkxLjQxODMgNDggODdWNTlaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGQ9Ik0xOCA2NEMxOCA2Mi4zNDMxIDE5LjM0MzEgNjEgMjEgNjFINTZDNjAuNDE4MyA2MSA2NCA2NC41ODE3IDY0IDY5VjgzQzY0IDg1LjIwOTEgNjIuMjA5MSA4NyA2MCA4N0gyNkMyMS41ODE3IDg3IDE4IDgzLjQxODMgMTggNzlWNjRaIiBmaWxsPSIjRUFFNEY2Ii8+CjxyZWN0IHg9IjI0IiB5PSIzMSIgd2lkdGg9IjY1IiBoZWlnaHQ9IjUwIiByeD0iNSIgZmlsbD0iIzk5QzdGMiIvPgo8cmVjdCB4PSIzMy41IiB5PSI0MyIgd2lkdGg9IjQ2IiBoZWlnaHQ9IjUiIHJ4PSIyLjUiIGZpbGw9IndoaXRlIi8+CjxyZWN0IHg9IjMzLjUiIHk9IjU0IiB3aWR0aD0iNDYiIGhlaWdodD0iNSIgcng9IjIuNSIgZmlsbD0id2hpdGUiLz4KPHJlY3QgeD0iMjQiIHk9IjMxIiB3aWR0aD0iNjUiIGhlaWdodD0iNTAiIHJ4PSI1IiBzdHJva2U9IiNGOEY4RjgiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik01MCA4NS4yNjhDNTMuODI2MyA4My4wNTg5IDU1LjEzNzMgNzguMTY2MiA1Mi45MjgyIDc0LjMzOThMNjMuMzIwNSA2OC4zMzk4QzY4Ljg0MzMgNzcuOTA1NyA2NS41NjU4IDkwLjEzNzUgNTYgOTUuNjYwNEM0Ni40MzQxIDEwMS4xODMgMzQuMjAyMyA5Ny45MDU3IDI4LjY3OTQgODguMzM5OEwzOS4wNzE3IDgyLjMzOThDNDEuMjgwOSA4Ni4xNjYyIDQ2LjE3MzYgODcuNDc3MiA1MCA4NS4yNjhaIiBmaWxsPSIjQUI5M0RDIi8+CjxyZWN0IHg9IjU5IiB5PSI2NSIgd2lkdGg9IjQyIiBoZWlnaHQ9IjI4IiByeD0iNSIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTYzIDg4VjczLjA4MDhDNjMgNzEuNzA5NiA2My4zNjE0IDcwLjY4NjcgNjQuMDg0MSA3MC4wMTJDNjQuODI4NyA2OS4zMzczIDY1Ljg1OCA2OSA2Ny4xNzIgNjlIOTIuODYwOUM5NS42MjAzIDY5IDk3IDcwLjM2MDMgOTcgNzMuMDgwOFY4OEg5My41MTc5TDg3LjM3NDkgODAuNjIyQzg3LjA5MDIgODAuMzE3MyA4Ni43NjE3IDgwLjA4ODggODYuMzg5NCA3OS45MzY0Qzg2LjAxNzEgNzkuNzg0MSA4NS42NDQ4IDc5LjcwNzkgODUuMjcyNSA3OS43MDc5Qzg0LjkwMDIgNzkuNzA3OSA4NC41Mjc5IDc5Ljc4NDEgODQuMTU1NiA3OS45MzY0QzgzLjgwNTIgODAuMDg4OCA4My40NTQ4IDgwLjMxNzMgODMuMTA0MyA4MC42MjJMNzYuNzMxNCA4Ni4yMzcxTDc0LjIwMTkgODMuOTUxOUM3My42MzI1IDgzLjQyOTYgNzMuMDA4NCA4My4xNjg0IDcyLjMyOTUgODMuMTY4NEM3MS42NTA2IDgzLjE2ODQgNzEuMDM3NCA4My40Mjk2IDcwLjQ4OTkgODMuOTUxOUw2Ni40NDkzIDg4SDYzWk03NC40NjQ3IDgwLjYyMkM3NS4zNjI2IDgwLjYyMiA3Ni4xNDAxIDgwLjI5NTUgNzYuNzk3MSA3OS42NDI2Qzc3LjQ3NiA3OC45ODk3IDc3LjgxNTUgNzguMjE3MSA3Ny44MTU1IDc3LjMyNDdDNzcuODE1NSA3Ni40MTA3IDc3LjQ3NiA3NS42MzggNzYuNzk3MSA3NS4wMDY5Qzc2LjE0MDEgNzQuMzU0IDc1LjM2MjYgNzQuMDE2NiA3NC40NjQ3IDczLjk5NDhDNzMuNTQ0OSA3My45NTEzIDcyLjc1NjUgNzQuMjY2OSA3Mi4wOTk1IDc0Ljk0MTZDNzEuNDQyNSA3NS42MTYzIDcxLjExNCA3Ni40MTA3IDcxLjExNCA3Ny4zMjQ3QzcxLjExNCA3OC4yMTcxIDcxLjQ0MjUgNzguOTg5NyA3Mi4wOTk1IDc5LjY0MjZDNzIuNzU2NSA4MC4yOTU1IDczLjU0NDkgODAuNjIyIDc0LjQ2NDcgODAuNjIyWiIgZmlsbD0iI0Y3RDA3RiIvPgo8Y2lyY2xlIGN4PSI5NSIgY3k9IjQyIiByPSIyIiBzdHJva2U9IiM1MEMzOTgiIHN0cm9rZS13aWR0aD0iMiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTk0Ljc1MDEgMjQuNDY4N0wxMDAuNzgxIDI3LjkxNDlMOTQuNzE5IDMxLjQxNDlMOTQuNzUwMSAyNC40Njg3WiIgc3Ryb2tlPSIjNUNBNUVBIiBzdHJva2Utd2lkdGg9IjEuOCIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwNSAzOEMxMDUgMzguNTUyMyAxMDUuNDQ4IDM5IDEwNiAzOUMxMDYuNTUyIDM5IDEwNyAzOC41NTIzIDEwNyAzOFYzNkgxMDlDMTA5LjU1MiAzNiAxMTAgMzUuNTUyMyAxMTAgMzVDMTEwIDM0LjQ0NzcgMTA5LjU1MiAzNCAxMDkgMzRIMTA3VjMyQzEwNyAzMS40NDc3IDEwNi41NTIgMzEgMTA2IDMxQzEwNS40NDggMzEgMTA1IDMxLjQ0NzcgMTA1IDMyVjM0SDEwM0MxMDIuNDQ4IDM0IDEwMiAzNC40NDc3IDEwMiAzNUMxMDIgMzUuNTUyMyAxMDIuNDQ4IDM2IDEwMyAzNkgxMDVWMzhaIiBmaWxsPSIjQUI5M0RDIi8+Cjwvc3ZnPgo=",K$="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgdmlld0JveD0iMCAwIDM3MiAyNzkiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMF8xMjU2XzM3MTY4KSI+CjxyZWN0IHdpZHRoPSIzNzIiIGhlaWdodD0iMjc5IiBmaWxsPSJ3aGl0ZSIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIzOS41NzQ3IiB3aWR0aD0iMTE4LjcyMyIgaGVpZ2h0PSIxNS44Mjk4IiByeD0iNy45MTQ4OSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI3MS4yMzM5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI5MS4wMjE1IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIxMTAuODA5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSI0MC41NjM4IiB5PSIxMzUuNTQzIiB3aWR0aD0iMjkwLjg3MiIgaGVpZ2h0PSIxMDAuOTE1IiByeD0iMi45NjgwOSIgc3Ryb2tlPSIjRUFGM0ZDIiBzdHJva2Utd2lkdGg9IjEuOTc4NzIiLz4KPHBhdGggZD0iTTM5LjU3NDUgMTM4LjUxMUMzOS41NzQ1IDEzNi4zMjUgNDEuMzQ2MyAxMzQuNTUzIDQzLjUzMTkgMTM0LjU1M0gzMjguNDY4QzMzMC42NTQgMTM0LjU1MyAzMzIuNDI2IDEzNi4zMjUgMzMyLjQyNiAxMzguNTExVjE1Mi4zNjJIMzkuNTc0NVYxMzguNTExWiIgZmlsbD0iI0Q2RTlGQSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTg3LjA2MzcgMTY5LjE4MUM4Ny4wNjM3IDE2Ny41NDIgODguMzkyNiAxNjYuMjEzIDkwLjAzMTggMTY2LjIxM0gzMTcuNTg1QzMxOS4yMjQgMTY2LjIxMyAzMjAuNTUzIDE2Ny41NDIgMzIwLjU1MyAxNjkuMTgxQzMyMC41NTMgMTcwLjgyIDMxOS4yMjQgMTcyLjE0OSAzMTcuNTg1IDE3Mi4xNDlIOTAuMDMxOEM4OC4zOTI2IDE3Mi4xNDkgODcuMDYzNyAxNzAuODIgODcuMDYzNyAxNjkuMTgxWk0xMDQuODcyIDE5Mi45MjZDMTA0Ljg3MiAxOTEuMjg2IDEwNi4yMDEgMTg5Ljk1NyAxMDcuODQgMTg5Ljk1N0gzMTcuNTg1QzMxOS4yMjQgMTg5Ljk1NyAzMjAuNTUzIDE5MS4yODYgMzIwLjU1MyAxOTIuOTI2QzMyMC41NTMgMTk0LjU2NSAzMTkuMjI0IDE5NS44OTQgMzE3LjU4NSAxOTUuODk0SDEwNy44NEMxMDYuMjAxIDE5NS44OTQgMTA0Ljg3MiAxOTQuNTY1IDEwNC44NzIgMTkyLjkyNlpNMTA3Ljg0IDIxMy43MDJDMTA2LjIwMSAyMTMuNzAyIDEwNC44NzIgMjE1LjAzMSAxMDQuODcyIDIxNi42N0MxMDQuODcyIDIxOC4zMDkgMTA2LjIwMSAyMTkuNjM4IDEwNy44NCAyMTkuNjM4SDMxNy41ODVDMzE5LjIyNCAyMTkuNjM4IDMyMC41NTMgMjE4LjMwOSAzMjAuNTUzIDIxNi42N0MzMjAuNTUzIDIxNS4wMzEgMzE5LjIyNCAyMTMuNzAyIDMxNy41ODUgMjEzLjcwMkgxMDcuODRaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNTEuNDQ2OCAxNjkuMTgxQzUxLjQ0NjggMTY3LjU0MiA1Mi43NzU2IDE2Ni4yMTMgNTQuNDE0OSAxNjYuMjEzSDYwLjM1MUM2MS45OTAzIDE2Ni4yMTMgNjMuMzE5MSAxNjcuNTQyIDYzLjMxOTEgMTY5LjE4MUM2My4zMTkxIDE3MC44MiA2MS45OTAzIDE3Mi4xNDkgNjAuMzUxIDE3Mi4xNDlINTQuNDE0OUM1Mi43NzU2IDE3Mi4xNDkgNTEuNDQ2OCAxNzAuODIgNTEuNDQ2OCAxNjkuMTgxWk01MS40NDY4IDE5Mi45MjZDNTEuNDQ2OCAxOTEuMjg2IDUyLjc3NTcgMTg5Ljk1NyA1NC40MTQ5IDE4OS45NTdINjAuMzUxMUM2MS45OTAzIDE4OS45NTcgNjMuMzE5MSAxOTEuMjg2IDYzLjMxOTEgMTkyLjkyNkM2My4zMTkxIDE5NC41NjUgNjEuOTkwMyAxOTUuODk0IDYwLjM1MTEgMTk1Ljg5NEg1NC40MTQ5QzUyLjc3NTcgMTk1Ljg5NCA1MS40NDY4IDE5NC41NjUgNTEuNDQ2OCAxOTIuOTI2Wk01NC40MTQ5IDIxMy43MDJDNTIuNzc1NyAyMTMuNzAyIDUxLjQ0NjggMjE1LjAzMSA1MS40NDY4IDIxNi42N0M1MS40NDY4IDIxOC4zMDkgNTIuNzc1NyAyMTkuNjM4IDU0LjQxNDkgMjE5LjYzOEg2MC4zNTExQzYxLjk5MDMgMjE5LjYzOCA2My4zMTkxIDIxOC4zMDkgNjMuMzE5MSAyMTYuNjdDNjMuMzE5MSAyMTUuMDMxIDYxLjk5MDMgMjEzLjcwMiA2MC4zNTExIDIxMy43MDJINTQuNDE0OVoiIGZpbGw9IiM5OUM3RjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik02OS4yNTU0IDE2OS4xODFDNjkuMjU1NCAxNjcuNTQyIDcwLjU4NDMgMTY2LjIxMyA3Mi4yMjM1IDE2Ni4yMTNINzguMTU5N0M3OS43OTg5IDE2Ni4yMTMgODEuMTI3OCAxNjcuNTQyIDgxLjEyNzggMTY5LjE4MUM4MS4xMjc4IDE3MC44MiA3OS43OTg5IDE3Mi4xNDkgNzguMTU5NyAxNzIuMTQ5SDcyLjIyMzVDNzAuNTg0MyAxNzIuMTQ5IDY5LjI1NTQgMTcwLjgyIDY5LjI1NTQgMTY5LjE4MVpNNjkuMjU1NCAxOTIuOTI2QzY5LjI1NTQgMTkxLjI4NiA3MC41ODQyIDE4OS45NTcgNzIuMjIzNSAxODkuOTU3SDc4LjE1OTZDNzkuNzk4OSAxODkuOTU3IDgxLjEyNzcgMTkxLjI4NiA4MS4xMjc3IDE5Mi45MjZDODEuMTI3NyAxOTQuNTY1IDc5Ljc5ODkgMTk1Ljg5NCA3OC4xNTk2IDE5NS44OTRINzIuMjIzNUM3MC41ODQyIDE5NS44OTQgNjkuMjU1NCAxOTQuNTY1IDY5LjI1NTQgMTkyLjkyNlpNNzIuMjIzNSAyMTMuNzAyQzcwLjU4NDIgMjEzLjcwMiA2OS4yNTU0IDIxNS4wMzEgNjkuMjU1NCAyMTYuNjdDNjkuMjU1NCAyMTguMzA5IDcwLjU4NDIgMjE5LjYzOCA3Mi4yMjM1IDIxOS42MzhINzguMTU5NkM3OS43OTg5IDIxOS42MzggODEuMTI3NyAyMTguMzA5IDgxLjEyNzcgMjE2LjY3QzgxLjEyNzcgMjE1LjAzMSA3OS43OTg5IDIxMy43MDIgNzguMTU5NiAyMTMuNzAySDcyLjIyMzVaIiBmaWxsPSIjRjdEMDdGIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNOTAuMDMxOCAxODkuOTU4Qzg4LjM5MjYgMTg5Ljk1OCA4Ny4wNjM3IDE5MS4yODYgODcuMDYzNyAxOTIuOTI2Qzg3LjA2MzcgMTk0LjU2NSA4OC4zOTI2IDE5NS44OTQgOTAuMDMxOCAxOTUuODk0SDk1Ljk2OEM5Ny42MDcyIDE5NS44OTQgOTguOTM2MSAxOTQuNTY1IDk4LjkzNjEgMTkyLjkyNkM5OC45MzYxIDE5MS4yODYgOTcuNjA3MiAxODkuOTU4IDk1Ljk2OCAxODkuOTU4SDkwLjAzMThaTTkwLjAzMTkgMjEzLjcwMkM4OC4zOTI3IDIxMy43MDIgODcuMDYzOCAyMTUuMDMxIDg3LjA2MzggMjE2LjY3Qzg3LjA2MzggMjE4LjMwOSA4OC4zOTI3IDIxOS42MzggOTAuMDMxOSAyMTkuNjM4SDk1Ljk2ODFDOTcuNjA3MyAyMTkuNjM4IDk4LjkzNjIgMjE4LjMwOSA5OC45MzYyIDIxNi42N0M5OC45MzYyIDIxNS4wMzEgOTcuNjA3MyAyMTMuNzAyIDk1Ljk2ODEgMjEzLjcwMkg5MC4wMzE5WiIgZmlsbD0iIzkxRDlCRSIvPgo8L2c+CjxkZWZzPgo8Y2xpcFBhdGggaWQ9ImNsaXAwXzEyNTZfMzcxNjgiPgo8cmVjdCB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgZmlsbD0id2hpdGUiLz4KPC9jbGlwUGF0aD4KPC9kZWZzPgo8L3N2Zz4K",BC=w("templates");function kf(n){const t=n.rootElement.querySelector(":scope .editor-templates");if(!t)return null;const e=t.querySelector(":scope .editor-templates-cards");return d(BC,e,"no card container"),{root:t,cardContainer:e}}function J$(n){const t=kf(n);if(t)return t.cardContainer.innerHTML="",t;const e=b("div",["editor-templates"],n.rootElement);b("div",["editor-templates-title"],e,T.t("templates.title"));const o=b("div",["editor-templates-cards"],e);return{root:e,cardContainer:o}}function EC(n,t,e,o,r){var f;const i=(f=n.options.componentsOptions)==null?void 0:f.templates,s=b("div",["editor-template-card",...o],null),l=b("div",["editor-template-thumb-container"],s),c=b("img",["editor-template-thumb"],l);c.src=t,c.style.display="none",c.onerror=()=>{var C;const m=(C=i==null?void 0:i.placeHolderImageSrc)!=null?C:K$;c.src!==m&&(c.src=m)},c.onload=()=>{c.style.display=""};const a=b("div",["editor-template-name"],s),u=b("span",[],a,e);return i!=null&&i.showTemplateTitleAttr&&u.setAttribute("title",e),s.onclick=()=>r(s),s}function X$(n,t){return t.thumbnailUrl?t.thumbnailUrl:n.doc.buildResourceUrl("thumbnail.png")}function tP(n,t){const e=X$(n,t);return EC(n,e,t.name,[],async()=>{var r,i;const o=(r=n.options.componentsOptions)==null?void 0:r.templates;(i=o==null?void 0:o.onApplyTemplate)==null||i.call(o,n,t)})}function eP(n,t){return EC(n,t,T.t("templates.choose"),["more"],()=>{var o,r;const e=(o=n.options.componentsOptions)==null?void 0:o.templates;(r=e==null?void 0:e.onChooseTemplate)==null||r.call(e,n)})}function nP(n,t){var f,m;const e=(f=n.options.componentsOptions)==null?void 0:f.templates;if(!e)return;const r=Qt(n.rootContainer).getBoundingClientRect().width;let i=1;const s=Q$,l=kf(n);if(l){if(t!=null&&t.reset){const C=Array.from(l.cardContainer.children),v=l.cardContainer.firstElementChild;if(d(BC,v,"no first card"),nt(v,"new")||nt(v,"more"))return;const B=window.getComputedStyle(v),y=parseFloat(B.marginLeft),S=parseFloat(B.marginRight),I=v.getBoundingClientRect().width+y+S;i=Math.floor(r/I);const R=Math.max(1,i-1-1),$=C.length-1;C.forEach((Z,ot)=>{ot>R&&ot<$?Z.style.display="none":(ot>=$&&nt(Z,"more"),Z.style.display="")})}return}const c=e.templates,{cardContainer:a}=J$(n);c.forEach((C,v)=>{const B=tP(n,C);if(v>0&&v>=i&&(B.style.display="none"),a.appendChild(B),v===0){const y=window.getComputedStyle(B),S=parseFloat(y.marginLeft),I=parseFloat(y.marginRight),M=B.getBoundingClientRect().width+S+I;i=Math.floor(r/M)-1}});const u=eP(n,s);a.appendChild(u),(m=e==null?void 0:e.onTemplateChooserStatusChanged)==null||m.call(e,n,a,"visible")}const IC=Xt.default(nP,50);function oP(n){var o,r;const t=kf(n);if(!t)return;t.root.remove();const e=(o=n.options.componentsOptions)==null?void 0:o.templates;(r=e==null?void 0:e.onTemplateChooserStatusChanged)==null||r.call(e,n,null,"hide")}function rP(n){const t=n.blocks.root;if(t.length===0)return!0;if(t.length>5)return!1;const e=[...t];e[0].type==="text"&&e[0].heading&&e.splice(0,1);const o=r=>{var i;return r.type!=="text"&&r.type!=="list"?!1:r.text?((i=r.text)==null?void 0:i.length)===0:!0};return e.every(r=>o(r))}function yf(n,t){rP(n.doc.toJSON())?IC(n,t):(IC.cancel(),oP(n))}const iP=800;class sP{constructor(t){h(this,"longPressTimeout",0);h(this,"handleSelectionChange",()=>{});h(this,"handleLongPress",t=>{const e=t.touches[0],o=Tl(this.editor,e.clientX,e.clientY);!o||console.log(o)});h(this,"handleTouchStart",t=>{t.touches.length===1&&(this.longPressTimeout=window.setTimeout(()=>{this.handleLongPress(t)},iP))});h(this,"handleTouchEnd",t=>{this.longPressTimeout&&(window.clearTimeout(this.longPressTimeout),this.longPressTimeout=0)});this.editor=t,this.editor.addListener("selectionChanged",this.handleSelectionChange),document.addEventListener("touchstart",this.handleTouchStart),document.addEventListener("touchend",this.handleTouchEnd)}destroy(){this.editor.removeListener("selectionChanged",this.handleSelectionChange),document.removeEventListener("touchstart",this.handleTouchStart),document.removeEventListener("touchend",this.handleTouchEnd)}}class Ys{constructor(t,e){h(this,"_decrypted",!1);this.editor=t,this.blockData=e}get decrypted(){return this._decrypted||this.blockData.owner===this.editor.doc.getUser().userId}setDecrypted(){this._decrypted=!0}destroy(){}static getState(t,e){return t.addCustom(`encrypted-block-${e.id}`,()=>new Ys(t,e))}}const eU="",Bo=w("encrypted-block");function lP(n,t,e,o,r){const i=r,s=ro(o,"div"),l=Ys.getState(n,i);if(l.decrypted)n.createChildContainer(t,s,i.children[0]),A(o,"decrypted");else{A(o,"encrypted");const c=Rt(o),a=b("div",["password-container"],c),u=b("input",[],a);u.type="text",u.onkeydown=f=>{if(f.key==="Enter"){const m=u.value;if(i.password===Ei.default(`${i.owner}-${m}`)){l.setDecrypted(),n.reloadBlock(o);const C=Ld(n,n.getBlockById(i.id));C&&(n.selection.selectBlock(C,0),n.focus())}}}}return s}function cP(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t)||!bn(r))return null;const i=r;if(n.getBlockData(t).children[0]!==U(i))return null;const l=wt(t,U(i));return new Xe(n,{anchor:l,focus:l})}function aP(n,t,e,o){if(Ys.getState(n,n.getBlockData(t)).decrypted)return null;if(o==="ArrowDown"||o==="ArrowRight"){const s=dt(t);return s?P(s,W(n,s),"end"):P(t,1,"end")}const i=gt(t);return P(i||t,0,"home")}function dP(n,t){return n.getBoundingClientRect()}function uP(n,t,e,o){if(e.isSimple()){d(Bo,o.isSimple(),"from is simple position but to is not simple position"),Bo.debug("full select table"),A(t,"full-selected");return}d(Bo,!o.isSimple(),"from is complex position but end is simple position");const r=e,i=o;d(Bo,r.blockId===i.blockId,"only allow update one table selection"),d(Bo,r.childContainerId===i.childContainerId,"only one container");const s=n.getBlockData(t),l=n.getContainerById(s.children[0]);A(l,"selected")}function hP(n){n.rootContainer.querySelectorAll('[data-type="editor-block"][data-block-type="encrypted"]').forEach(t=>{z(t,"full-selected"),t.querySelectorAll("selected").forEach(e=>{z(e,"selected")})})}function fP(n,t){const e=n.getBlockData(t);return Ys.getState(n,e).decrypted?[n.getContainerById(e.children[0])]:[]}function mP(n,t,e,o,r){return null}function gP(n,t,e,o){d(Bo,e.blockId===o.blockId,"only allow select in single block"),d(Bo,q(t)===e.blockId,"only allow select in single block");const r=n.getBlockData(t);return d(Bo,e.childContainerId===r.children[0],"only one container"),[n.getContainerById(r.children[0])]}function pP(n){return{name:"EncryptedBlock",insertBlockCommandItems:[{id:"insert-encrypted-block",name:"Encrypted Block"}],async handleInsertEmptyBlock(t,e){const o=yn(t.doc),r={id:N(),type:"encrypted",children:[o],owner:t.doc.getUser().userId,ownerDisplayName:t.doc.getUser().displayName,password:Ei.default(`${t.doc.getUser().userId}-1234`)},i=t.doc.getContainerBlocks(o)[0];return t.insertBlock(e.containerId,e.blockIndex,r,At(t,i.id,0))}}}function CP(n,t,e,o){return o==="text"||o==="markdown"?"[Encrypted Block]":"<p>[Encrypted Block]</p>"}const bP={blockType:"encrypted",blockKind:"complex",enableKeyboardSelect:!0,createBlockContent:lP,getBlockTextLength:()=>1,getRangeFromPoint:cP,moveCaret:aP,getCaretRect:dP,updateSelection:uP,clearSelection:hP,getChildContainers:fP,getNextContainer:mP,getSelectedContainers:gP,getOptions:pP,convertTo:CP};function vP(n,t,e){const o=ts(n,t,{components:{blocks:[Ds,Rs,bP],decorators:[new Os],embeds:[ca,C1,H1,F1,z1,n1,U1,uf,df],boxes:[Fc],options:{...e.componentsOptions}}});return o.readonly=!0,o}class kP{constructor(t){this.createOptions=t}createHistoryEditor(t,e){return vP(t,e,this.createOptions)}}w("create-editor");function xC({root:n,childDoc:t,doc:e}){t.uploadResource=e.uploadResource.bind(e),t.buildResourceUrl=e.buildResourceUrl.bind(e);const o=ts(n,t,{shortcuts:[oc],components:{blocks:[Ds,Rs],decorators:[new Os],embeds:[B6,ca,C1,H1,F1,z1,n1,U1,uf,df],boxes:[Fc,vf],options:{}}});return o.input.addHandler(new Qc),o.input.addHandler(new V1(o)),o.input.addHandler(new P_(o)),o}function yP(n,t){const e=Array.from(n.rootContainer.querySelectorAll(`[comment-${t.toLocaleLowerCase()}="${t}"]`)),o=new Set;e.forEach(r=>{const i=F(r);i&&o.add(i)}),o.forEach(r=>{j_(n,r,t)})}class wP{constructor(t){h(this,"listeners",new Set);h(this,"doc");this.editor=t,this.doc=this.editor.doc.externalDoc,this.doc.registerCallback(this)}getComments(){return this.doc.getComments()}getComment(t){return this.doc.getComment(t)}getCommentDoc(t){return this.doc.getCommentDoc(t)}localCreateComment(t,e){this.doc.localCreateComment(t,e)}localDeleteComment(t){const e=this.getComment(t);this.doc.localDeleteComment(t);const o=e.groupId;this.getComments().filter(i=>i.groupId===o).length===0&&yP(this.editor,o)}localUpdateComment(t,e){this.doc.localUpdateComment(t,e)}onCreateComment(t,e){Array.from(this.listeners.values()).forEach(o=>o.onCreateComment(t,e))}onDeleteComment(t,e){Array.from(this.listeners.values()).forEach(o=>o.onDeleteComment(t,e))}onUpdateComment(t,e){Array.from(this.listeners.values()).forEach(o=>o.onUpdateComment(t,e))}addListener(t){this.listeners.add(t)}removeListener(t){this.listeners.delete(t)}createCommentEditor(t,e){return xC({root:t,childDoc:e,doc:this.doc})}}class BP{constructor(t,e){h(this,"listeners",new Set);this.editor=t,this.localDoc=e}get doc(){return this.localDoc.toJSON()}getComments(){return Object.values(this.doc.comments)}getComment(t){return this.doc.comments[t]}getCommentDoc(t){const e=this.doc.comments[t];return Yu(e)}addListener(t){this.listeners.add(t)}removeListener(t){this.listeners.delete(t)}localCreateComment(t,e){}localDeleteComment(t){}localUpdateComment(t,e){}createCommentEditor(t,e){return xC({root:t,childDoc:e,doc:this.localDoc})}}const EP={placeholder:{common:{title:"\u8BF7\u8F93\u5165\u6807\u9898",readonlyTitle:"\u8BF7\u8F93\u5165\u6807\u9898",content:"\u70B9\u51FB + \uFF0C\u6216\u8F93\u5165 / \u5FEB\u6377\u63D2\u5165\u7EC4\u4EF6"},local:{readonlyTitle:"\u672A\u547D\u540D"}}},IP={placeholder:{common:{title:"Enter a title",readonlyTitle:"Enter a title",content:'Click "+", or enter "/" to insert components quickly'},local:{readonlyTitle:"Untitled"}}};T.mergeLang({"zh-CN":EP,"en-US":IP});const wf=w("create-editor"),TC=[ca,C1,H1,F1,z1,n1,U1,uf,df,B6,yC,IN];async function xP(n,t){var s,l,c,a,u,f,m,C,v,B,y,S;d(wf,n,"app does not exists"),t.lang&&T.setLang(t.lang);const e=t.onReauth?async()=>{var $;const I=t.user.userId,M=t.docId,R=await(($=t.onReauth)==null?void 0:$.call(t,I,M,t.permission));return{userId:I,docId:M,permission:t.permission,appId:t.appId,token:R,displayName:t.user.displayName,avatarUrl:t.user.avatarUrl}}:void 0,o={auth:{appId:t.appId,docId:t.docId,userId:t.user.userId,permission:t.permission,token:t.token,displayName:t.user.displayName,avatarUrl:t.user.avatarUrl},serverUrl:t.serverUrl,reauthFunc:e,disableLogout:t.disableLogout},r=await fs.load(o),i=ts(n,r,{id:t.id,components:{blocks:[Ds,Rs,E1,u4],commandProviders:[new Bh,...((s=t.components)==null?void 0:s.commandProviders)||[]],decorators:[new Os,new Ku],embeds:[...TC,...((l=t.components)==null?void 0:l.embeds)||[]],boxes:[Fc,vf,U3,...((c=t.components)==null?void 0:c.boxes)||[]],insertions:[Kd],blockHooks:[new g6,...((a=t.components)==null?void 0:a.blockHooks)||[]],textRenders:[new $3,new aI],options:{...t.componentsOptions}},shortcuts:[nL,$M,d1,m3,dI,i1,oc],colors:["#338FE5","#24B47E","#F0A100","#E52727","#9678D3","#2CB2AE","#EB6414","#8AAB3F"]});if(i.editorCommandProviders.registerCommandProvider(new Mn(i)),i.input.addHandler(new D$),i.input.addHandler(new Qc),i.input.addHandler(new oT),i.input.addHandler(new LM),i.input.addHandler(new Ms(i,{headingLevel:1,titlePlaceholder:T.t("placeholder.common.title"),contentPlaceholder:T.t("placeholder.common.content"),readonlyTitlePlaceholder:T.t("placeholder.common.readonlyTitle"),addPlaceholderToAllCurrentEmptyBlock:!0})),i.input.addHandler(new zc(i,(u=t.componentsOptions)==null?void 0:u.quickMenu)),i.input.addHandler(new V1(i)),i.input.addHandler(new i3(i)),i.input.addHandler(new JD),i.doc.registerCallback(new L$(i)),i.addCustom("remote-cursor",()=>new F2(i)),i.addCustom("block-menu",I=>new v6(I)),i.addCustom("editor-tooltip",()=>new r1(i)),t!=null&&t.enableComments&&i.addCustom("editor-comments",I=>new N3(I,new wP(I))),i.addCustom("create-options",()=>new Kf(i,t)),i.addCustom("drop-target",()=>new Hs(i)),i.addCustom("list-to-mindmap",()=>new Hc(i)),i.addCustom("list-to-mention",()=>new G$(i)),i.addCustom("mobile-helper",()=>new sP(i)),i.addCustom("code-caret",()=>new KD(i)),(f=t.componentsOptions)!=null&&f.mention){const I=t.componentsOptions.mention;i.addCustom("mention",()=>new z$(i,I))}if(i.addCustom("heading-collapse",()=>new I$(i)),Xr.register(i),Hs.register(i),mr.register(i),(C=(m=t.componentsOptions)==null?void 0:m.remoteCarets)!=null&&C.onUserChanged){const I=(B=(v=t.componentsOptions)==null?void 0:v.remoteCarets)==null?void 0:B.onUserChanged;i.doc.getRemoteUsers().on("change",M=>{I(i,M)})}return(S=(y=t.componentsOptions)==null?void 0:y.templates)!=null&&S.templates.length&&(i.addListener("docChanged",()=>{yf(i)}),i.addListener("resize",()=>{yf(i,{reset:!0})}),setTimeout(()=>{yf(i)},100)),i.doc.registerCallback({onError:async I=>{if(I.code==="ResetDoc"){wf.error(`reset doc: ${I.message}`);const M=await fs.load(o);i.doc.reset(M)}}}),i}function TP(n){return n.toJSON!==void 0}async function SP(n,t,e){var i,s,l;d(wf,n,"app does not exists");const o=TP(t)?t:new Ru(t,{serverUrl:e.serverUrl||""});e.lang&&T.setLang(e.lang);const r=ts(n,o,{id:e.id,components:{blocks:[Ds,Rs,E1,u4],commandProviders:[new Bh],decorators:[new Os,new Ku],embeds:[...TC,...((i=e.components)==null?void 0:i.embeds)||[]],boxes:[Fc,vf,U3],insertions:[Kd],blockHooks:[new g6,...((s=e.components)==null?void 0:s.blockHooks)||[]],textRenders:[new $3],options:{...e.componentsOptions}},shortcuts:[d1,m3,i1,oc]});return r.editorCommandProviders.registerCommandProvider(new Mn(r)),r.input.addHandler(new Qc),r.input.addHandler(new Ms(r,{headingLevel:1,titlePlaceholder:T.t("placeholder.common.title"),contentPlaceholder:T.t("placeholder.common.content"),readonlyTitlePlaceholder:T.t("placeholder.local.readonlyTitle"),addPlaceholderToAllCurrentEmptyBlock:!0})),r.input.addHandler(new zc(r,(l=e.componentsOptions)==null?void 0:l.quickMenu)),r.input.addHandler(new V1(r)),r.input.addHandler(new i3(r)),r.addCustom("block-menu",c=>new v6(c)),r.addCustom("editor-tooltip",()=>new r1(r)),e!=null&&e.enableComments&&r.addCustom("editor-comments",c=>new N3(c,new BP(c,o))),Xr.register(r),r}function DP(n,t){var l;const e=n.doc;if(!((l=e.getVersionHelper)==null?void 0:l.call(e)))throw new Error("the editor does not support to show versions");const r=n.getCustom("create-options");if(!r)throw new Error("the editor does not support to show versions");const i=r.getData(),s=new kP(i);return m$(n,s,t)}g.tippy=p7,g.AuthError=fc,g.AuthHeader=hs,g.AutoScroll=Am,g.BaseURLHeader=mc,g.BlockResizer=Yc,g.BrBox=up,g.CodeBlock=Rs,g.CodeLineBlock=E1,g.CodeTextDecorator=Os,g.DefaultShortcuts=oc,g.DocIdError=rw,g.DragDrop=um,g.DrawioEmbed=ca,g.EditorBlocks=Cg,g.EditorBoxes=fp,g.EditorCommandProviders=n2,g.EditorComplexBlockPosition=Je,g.EditorComplexSelectionRange=Xe,g.EditorDecorators=Cp,g.EditorEmbeds=vg,g.EditorInsertions=pp,g.EditorSimpleBlockPosition=qt,g.EditorSimpleSelectionRange=ce,g.EmbedBlock=yg,g.EnforceWithDocumentTitleHandler=Ms,g.EventCallbacks=xi,g.FILL_CHAR=Rb,g.FileExtError=iw,g.HeadingBlockScrollListener=F$,g.InputtingInsertion=mp,g.LocalDoc=Ru,g.Logger=br,g.MIN_DISTANCE_THRESHOLD=am,g.ManualMenu=tr,g.ManualToolbar=ps,g.MarkdownInputHandler=Qc,g.MaxUserError=Vu,g.OnesEditorAutoSuggest=mh,g.OnesEditorCustomDataWrapper=Kf,g.OnesEditorHoveringBlock=Nt,g.OnesEditorQuickMenu=zc,g.OnesEditorToc=Zs,g.OnesEditorTocProvider=mr,g.OnesEditorToolbar=Xr,g.OnesEditorTooltip=r1,g.PermissionError=ow,g.Popup=ms,g.RemoteCarets=F2,g.RemoteCaretsDecorator=Ku,g.RemoteCaretsInsertion=Kd,g.RemoteUsers=ic,g.RequestReloadError=us,g.RichText=ie,g.ShareDBDoc=fs,g.SimpleCache=Xf,g.StandardEmbedBlockCommands=g1,g.TEXT_STYLE_BACKGROUND_COLOR_PREFIX=Ud,g.TEXT_STYLE_COLOR_PREFIX=zd,g.TableBlock=Ds,g.TableBlockCommandProvider=Bh,g.TableShortcuts=d1,g.TextBlock=ve,g.TextBox=dp,g.TextStyleShortcuts=i1,g.TocEmbed=yC,g.ZERO_WIDTH_SPACE_CHAR=Ti,g.addAttribute=Ol,g.addClass=A,g.addCommentToBlock=m1,g.addDays=i8,g.addMonths=r8,g.animateScrollTo=td,g.applyPlaceholderToBlock=Kc,g.assert=d,g.blockToDoc=xu,g.blockToHtml=eu,g.blockToMarkdown=nu,g.blockToText=ql,g.blocksToDoc=qv,g.clearAllSelection=lg,g.clientType=xt,g.cloneBlock=ao,g.cloneChildContainer=hu,g.cloneDoc=fu,g.cloneText=tp,g.commentToShareDbComment=Qu,g.compareElement=fl,g.comparePosition=Sd,g.complexBlockAdjustSelectionPos=xl,g.complexBlockFindNearestChildBlock=Ig,g.complexBlockGeFirstSimpleChild=Ld,g.complexBlockGetAllChildContainers=Se,g.complexBlockGetBottomChildContainers=Eg,g.complexBlockGetLastSimpleChild=Ni,g.complexBlockGetSelectedContainers=xr,g.complexBlockGetTopChildContainers=Bg,g.containerToDoc=R0,g.continuousScroll=Rm,g.convertBlockFrom=Oi,g.copyBlockAttributes=Lp,g.createBlockAnchor=zo,g.createBlockCaretAnchor=Dg,g.createBlockContentElement=ro,g.createBlockElement=zm,g.createBlockSimpleDocRange=Fl,g.createBlockSimpleRange=At,g.createBoxContentElement=qm,g.createBoxElement=Um,g.createBoxOp=qg,g.createChildContainer=rg,g.createComplexBlockPosition=wt,g.createComplexDocPos=sp,g.createComplexDocRange=_b,g.createContainer=op,g.createContainerElement=bd,g.createDeleteOps=Fg,g.createEditor=ts,g.createEditorSelectionRange=Wt,g.createElement=b,g.createEmptyContainer=yn,g.createEmptyDoc=Zo,g.createEmptyTextBlockData=Pl,g.createExpandedRange=ul,g.createIconButton=vr,g.createImage=tm,g.createInsertOps=Al,g.createInsertionContentElement=Zm,g.createInsertionElement=Wm,g.createLocalEditor=SP,g.createOnesEditor=xP,g.createRange=em,g.createRichText=Go,g.createRootContainer=og,g.createSimpleBlockPosition=P,g.createSimpleDocPos=ip,g.createTextBlockData=Un,g.createTextButton=sr,g.createTextOp=$e,g.createTextWithReplaceSoftReturn=Pd,g.daysAfter=ad,g.deleteText=Hd,g.diffDays=s8,g.disablePageScroll=Im,g.docToHtml=Ep,g.docToHtmlFragment=Vi,g.docToMarkdown=qi,g.docToText=Wl,g.downloadObjectToFile=_1,g.downloadSvgToString=I6,g.editLink=Rc,g.editorAddComment=F_,g.editorAddTextAttribute=Fp,g.editorAutoInsertBlock=Mp,g.editorBreakTextBlock=Rr,g.editorClearCompositionText=Dp,g.editorClearSelectedContents=du,g.editorCopyBlock=nc,g.editorDeleteBlock=cu,g.editorDeleteBlockText=iu,g.editorDeleteBlockWithoutChildren=lu,g.editorDeleteChildContainer=Iv,g.editorDeleteChildContainers=Rp,g.editorFocusToBlock=uu,g.editorFocusToEnd=L0,g.editorGetBlockData=co,g.editorGetBlockText=ue,g.editorGetBlockTextEx=Ul,g.editorGetBoxData=cp,g.editorHandleKeyboardEvent=$0,g.editorInsertBlock=Mr,g.editorInsertBoxToBlock=Tp,g.editorInsertDoc=jp,g.editorInsertDocAt=mu,g.editorInsertText=ru,g.editorInsertTextToBlock=xp,g.editorInsertTextToBlockEx=ou,g.editorMergeTextBlock=Ap,g.editorMoveDown=Xp,g.editorMoveEnd=a0,g.editorMoveHome=d0,g.editorMoveLeft=Qp,g.editorMoveLineEnd=b0,g.editorMoveLineHome=C0,g.editorMovePageDown=E0,g.editorMovePageUp=B0,g.editorMoveRight=Kp,g.editorMoveUp=Jp,g.editorMoveWordEnd=s0,g.editorMoveWordLeft=i0,g.editorRangeClearColor=Up,g.editorRangeGetColor=gu,g.editorRangeSetColor=zp,g.editorRemoveTextAttribute=Sv,g.editorReplaceBlockText=Kl,g.editorReplaceContainer=Hp,g.editorRunOnce=Au,g.editorSelectAll=D0,g.editorSelectContainer=Eu,g.editorSelectDown=t0,g.editorSelectEnd=wu,g.editorSelectHome=u0,g.editorSelectLeft=e0,g.editorSelectLineEnd=p0,g.editorSelectLineHome=g0,g.editorSelectPageDown=x0,g.editorSelectPageUp=I0,g.editorSelectRight=n0,g.editorSelectUp=o0,g.editorSelectWordEnd=c0,g.editorSelectWordLeft=l0,g.editorSetTextColor=Ar,g.editorShowFindDialog=ZO,g.editorUpdateBlockData=Jl,g.editorUpdateCompositionText=Sp,g.editorUpdateEmbedData=$p,g.enablePageScroll=xm,g.escapeHtmlText=sm,g.escapeRegExp=hd,g.escapeSpace=F7,g.executeBlockCommand=pg,g.executeEmbedBlockCommand=gg,g.executeRangeCommand=e2,g.fileToDataUrl=pl,g.findAfterOffsetNotType=Zd,g.findAllText=Wd,g.findInsertionById=Gm,g.findNextOffset=Jb,g.findPrevOffset=Kb,g.findPrevOffsetNotType=Gd,g.findPrevSimpleBlockBeforeChildContainer=wg,g.findTarget=Di,g.findWordEnd=Qd,g.findWordLeft=Yd,g.format=cd,g.formatBytes=Om,g.formatDate=$m,g.fragmentToHtml=Tm,g.fromBase64=gl,g.fromBase64ToBlob=wm,g.fromBase64ToUint8Array=X7,g.fromDocRange=io,g.fromNowString=ud,g.genId=N,g.getAllChildBlocks=Rd,g.getAllQuickMenuItems=o1,g.getAllSelectedBlocks=tn,g.getAttributesAt=Nl,g.getBlockBackground=Fm,g.getBlockByIndex=kr,g.getBlockCaretRect=Ke,g.getBlockClass=bt,g.getBlockClassByType=Er,g.getBlockClientRects=Ho,g.getBlockCommandsWithHook=Ed,g.getBlockContent=it,g.getBlockId=q,g.getBlockIndex=J,g.getBlockKind=Qe,g.getBlockMinWidth=ag,g.getBlockNearestRangeFromPoint=Tg,g.getBlockOptions=p8,g.getBlockPath=jo,g.getBlockProperties=hg,g.getBlockRangeFromPoint=Tl,g.getBlockStyles=m8,g.getBlockTextLength=W,g.getBlockTools=Rt,g.getBlockType=rt,g.getBoxContent=gd,g.getBoxId=Vm,g.getBoxTypeFromElement=Ri,g.getChildBlockCount=Ge,g.getChildBlocks=Mt,g.getChildOffset=so,g.getColorFromAttributes=qd,g.getComplexBlockClass=xe,g.getContainerBlockPath=tg,g.getContainerBlocks=Jm,g.getContainerBlocksElement=El,g.getContainerById=Br,g.getContainerId=U,g.getContainerMinWidth=wd,g.getContainerToolsElement=a8,g.getContainerWidth=ug,g.getDistanceSquare=Cn,g.getElementOffset=Si,g.getEmbedType=Oe,g.getExistsBlockTools=Bl,g.getExistsContainerById=Qm,g.getFileExt=Dm,g.getFirstChildBlock=Vt,g.getFirstClientRect=hl,g.getHeadingMenuOptions=Kh,g.getHorizontalPadding=Qa,g.getInsertionContent=pd,g.getLastChildBlock=Qt,g.getLastClientRect=Mo,g.getListAllNextBrothers=Is,g.getLogger=w,g.getNextBlock=dt,g.getNextValidOffset=Vo,g.getNextVisibleBlock=wr,g.getOffsetInfoAfter=Ui,g.getOffsetInfoBefore=Vl,g.getOpAt=Gg,g.getOpLength=Fd,g.getParentBlock=F,g.getParentBox=md,g.getParentContainer=H,g.getPrevBlock=gt,g.getPrevValidOffset=lo,g.getPrevVisibleBlock=yr,g.getRangeCommands=X0,g.getRootBlock=yd,g.getScrollContainer=We,g.getSpecialBlockCommands=fg,g.getStandardEmbedBlockProperties=p1,g.getTextAfterOffset=Yb,g.getTextBeforeOffset=Qb,g.getTextBlockChild=Sl,g.getTextBlockClass=sg,g.getTextBlockContentChildTextLength=Ne,g.getTextBlockContentChildType=Sg,g.getTextBlockContentChildren=zn,g.getTextLength=de,g.getTextOpLength=Ad,g.getTextWidth=bl,g.getToolbar=Mc,g.handleBlockElementUpdated=dg,g.hasAltOnly=G7,g.hasClass=nt,g.hasCtrlOrCmd=bm,g.hasCtrlOrCmdOnly=W7,g.hideBlock=jm,g.htmlToFragment=Cl,g.i18n=T,g.injectStyle=cm,g.insertEmptyBlock=b8,g.insertEmptyEmbedBlock=Id,g.insertText=Sr,g.intersectionCommands=Kk,g.isBackspace=km,g.isBlock=Po,g.isBox=fd,g.isCJK=gm,g.isChildContainer=Ye,g.isChildNode=It,g.isCollapsedRange=Ob,g.isComplexBlockPosition=Td,g.isComplexKindBlock=at,g.isContainer=bn,g.isContainerSelectedAllChildBlocks=T0,g.isControlEvent=Oo,g.isDelete=Y7,g.isDraggingFiles=kl,g.isEmbedBlock=Te,g.isEmptyContainer=Bd,g.isEmptyDoc=jl,g.isEmptyTextBlock=Tt,g.isEmptyTextBlockWithoutCompositionText=Ls,g.isEnterOnly=vm,g.isEscape=id,g.isFirefox=od,g.isFirstChildBlockInComplexBlock=W8,g.isHighSurrogate=_7,g.isInBlock=Cd,g.isInBlockTools=Ai,g.isLetter=mm,g.isLowSurrogate=Ya,g.isMatchShortcut=jn,g.isMoveForward=V7,g.isNavigationEvent=U7,g.isNavigationKey=Cm,g.isNodeRemoved=om,g.isNumber=fm,g.isPrintableKey=rd,g.isRootBlock=Ko,g.isRootContainer=pt,g.isSafari=pm,g.isSameDay=dd,g.isShiftEnter=Z7,g.isShiftTab=K7,g.isShortcutEvent=q7,g.isSimpleBlock=g8,g.isSimpleBlockPosition=Ir,g.isSimplePos=rp,g.isSimpleRange=Hl,g.isSpace=ml,g.isTab=Q7,g.isTextBlockContentBoxChild=_e,g.isTextBlockContentChild=$i,g.isTextBlockContentInsertionChild=Fn,g.isTextBlockContentTextChild=Pi,g.isTextKindBlock=j,g.isTextKindBlockType=_i,g.isToday=_m,g.isValidOffset=re,g.isVisibleBlock=wl,g.isYesterday=Nm,g.loadJs=rm,g.loadJsPromise=Ro,g.lockers=qe,g.mergeCommands=Lc,g.mergeDocs=Yo,g.mergeOps=jd,g.mergeText=Sb,g.multiSplitText=Rg,g.parseShortcut=ym,g.patchNode=Mi,g.pointInRect=Ao,g.rangeAddAttribute=_l,g.rangeGetTextColor=Xg,g.rangeRemoveAttribute=Dr,g.rangeSetTextColor=Qg,g.rangeTransformText=Zg,g.registerDragDrop=ed,g.removeAttribute=Vd,g.removeClass=z,g.removeLastBr=Eb,g.removePlaceholderFromBlock=V4,g.removeStyle=lm,g.replaceAll=l8,g.replaceAllCaseInsensitive=c8,g.replaceAllText=np,g.replaceText=$l,g.requestDownload=yl,g.resetListStart=Ts,g.scrollable=Mm,g.selectFile=No,g.selectedBlockToDoc=tc,g.selectionToDoc=Ji,g.setAttributes=Ja,g.setClipboardData=vl,g.setClipboardDataByEvent=o8,g.setColorToAttributes=Kg,g.setDataset=Ka,g.setDefaultCursor=Li,g.setStyles=Xa,g.shareDBCommentToDocObject=Yu,g.shareDBDocCommentToComment=j2,g.shortcutToDisplayText=J7,g.showBlock=Hm,g.showDocVersions=DP,g.splitText=be,g.splitToThree=Gt,g.stringToDataUrl=Bm,g.stringToObjectUrl=ld,g.subText=Ag,g.textNodeOffsetFromPoint=nm,g.toBase64URL=_o,g.toPlainText=vt,g.trimChar=nd,g.unicodeLength=N7,g.unicodeSubstr=$7,g.updateBlockSelection=cg,g.updateOpAttributes=ep,g.updateTextBlockContent=Zb,g.updateUrl=sd,Object.defineProperties(g,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});