@ones-editor/editor 0.0.3-beta.47 → 0.0.3-beta.48
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/@ones-editor/tsconfig.tsbuildinfo +1 -1
- package/dist/index.js +14 -14
- package/dist/types.d.ts +2 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -8,11 +8,11 @@
|
|
|
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 W9(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 Ha(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 ki="\u200B";function G9(n){return[...n].length}function Z9(n,t,e){const r=[...n];let i;return e===void 0?i=r.length:i=t+e,r.slice(t,i).join("")}const Eo=y("dom-utils");function M(n,...t){n&&n.nodeType===Node.ELEMENT_NODE&&n.classList.add(...t)}function lt(n,t){return n instanceof HTMLElement?n.classList.contains(t):!1}function F(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&&M(r,...t),e&&e.appendChild(r),o&&(typeof o=="string"?r.innerText=o:za(r,o)),r}function hr(n,t,e){const o=b("button",t,e);return o.innerHTML=n,o}function Af(n,t,e){const o=b("img",t,e);return o.src=n,o}function _f(n,t){try{const e=document.createRange();return e.setStart(n,t),e}catch(e){d(Eo,!1,`failed to create range: ${n.childNodes.length}, ${t}, ${e.message}`)}}function Ks(n,t,e,o){try{const r=document.createRange();return r.setStart(n,t),r.setEnd(e,o),r}catch(r){d(Eo,!1,`failed to create expanded range: ${n.childNodes.length}, ${t}, ${e.childNodes.length}, ${o}, ${r.message}`)}}function Js(n){const t=n.getClientRects();return d(Eo,t.length>=1,"getFirstClientRect: no rects"),t[0]}function Io(n){const t=n.getClientRects();return d(Eo,t.length>=1,"getLastClientRect: no rects"),t[t.length-1]}function fn(n,t,e){const o=n.left+n.width/2,r=n.top+n.height/2;return(o-t)**2+(r-e)**2}function Nf(n,t,e){const o=n.data;d(Eo,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&&Ha(o[l]))continue;s.setStart(n,l);const c=s.getClientRects();for(let a=0;a<c.length;a++){const h=c[a],f=fn(h,t,e);f<r&&(r=f,i=l)}}return i}function Xs(n,t){if(n===t)return 0;if((!n.parentElement||!t.parentElement)&&d(Eo,!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(Eo,!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 Fa(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 Pf(n){return!document.documentElement.contains(n)}function vt(n,t){let e=t;for(;e;){if(n===e)return!0;e=e.parentNode}return!1}function $f(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 xo(n,t){const e=new Promise((o,r)=>{$f(n,t,i=>{i?r(i):o(void 0)})});try{await Ue.lock(t),await e}finally{Ue.release(t)}}function za(n,t){Object.entries(t).forEach(([e,o])=>{n.dataset[e]=`${o}`})}function Ua(n,t){Object.entries(t).forEach(([e,o])=>{n.setAttribute(e,o)})}function Va(n,t){Object.entries(t).forEach(([e,o])=>{n.style.setProperty(e,o)})}function yi(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 wi(n,t){return!n.target||!(n.target instanceof Element)?null:n.target.closest(t)}class Y9{constructor(t){u(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 yi(t).left-yi(e).left}getVerticalElementScrollOffset(t,e){return yi(t).top-yi(e).top}scrollTo(t,e){this.element.scrollLeft=t,this.element.scrollTop=e}}class Q9{constructor(){u(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 Rn={elements:[],cancelMethods:[],add:(n,t)=>{Rn.elements.push(n),Rn.cancelMethods.push(t)},remove:(n,t)=>{const e=Rn.elements.indexOf(n);e>-1&&(t&&Rn.cancelMethods[e](),Rn.elements.splice(e,1),Rn.cancelMethods.splice(e,1))}},jf=typeof window<"u",K9={cancelOnUserAction:!0,easing:n=>--n*n*n+1,elementToScroll:jf?window:null,horizontalOffset:0,maxDuration:3e3,minDuration:250,speed:500,verticalOffset:0};async function Bi(n,t={}){if(!jf)return new Promise(
|
|
11
|
+
*/function W9(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 Ha(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 ki="\u200B";function G9(n){return[...n].length}function Z9(n,t,e){const r=[...n];let i;return e===void 0?i=r.length:i=t+e,r.slice(t,i).join("")}const Eo=y("dom-utils");function M(n,...t){n&&n.nodeType===Node.ELEMENT_NODE&&n.classList.add(...t)}function lt(n,t){return n instanceof HTMLElement?n.classList.contains(t):!1}function F(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&&M(r,...t),e&&e.appendChild(r),o&&(typeof o=="string"?r.innerText=o:za(r,o)),r}function hr(n,t,e){const o=b("button",t,e);return o.innerHTML=n,o}function Af(n,t,e){const o=b("img",t,e);return o.src=n,o}function _f(n,t){try{const e=document.createRange();return e.setStart(n,t),e}catch(e){d(Eo,!1,`failed to create range: ${n.childNodes.length}, ${t}, ${e.message}`)}}function Ks(n,t,e,o){try{const r=document.createRange();return r.setStart(n,t),r.setEnd(e,o),r}catch(r){d(Eo,!1,`failed to create expanded range: ${n.childNodes.length}, ${t}, ${e.childNodes.length}, ${o}, ${r.message}`)}}function Js(n){const t=n.getClientRects();return d(Eo,t.length>=1,"getFirstClientRect: no rects"),t[0]}function Io(n){const t=n.getClientRects();return d(Eo,t.length>=1,"getLastClientRect: no rects"),t[t.length-1]}function fn(n,t,e){const o=n.left+n.width/2,r=n.top+n.height/2;return(o-t)**2+(r-e)**2}function Nf(n,t,e){const o=n.data;d(Eo,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&&Ha(o[l]))continue;s.setStart(n,l);const c=s.getClientRects();for(let a=0;a<c.length;a++){const h=c[a],f=fn(h,t,e);f<r&&(r=f,i=l)}}return i}function Xs(n,t){if(n===t)return 0;if((!n.parentElement||!t.parentElement)&&d(Eo,!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(Eo,!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 Fa(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 Pf(n){return!document.documentElement.contains(n)}function vt(n,t){let e=t;for(;e;){if(n===e)return!0;e=e.parentNode}return!1}function $f(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 xo(n,t){const e=new Promise((o,r)=>{$f(n,t,i=>{i?r(i):o(void 0)})});try{await Ue.lock(t),await e}finally{Ue.release(t)}}function za(n,t){Object.entries(t).forEach(([e,o])=>{n.dataset[e]=`${o}`})}function Ua(n,t){Object.entries(t).forEach(([e,o])=>{n.setAttribute(e,o)})}function Va(n,t){Object.entries(t).forEach(([e,o])=>{n.style.setProperty(e,o)})}function yi(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 wi(n,t){return!n.target||!(n.target instanceof Element)?null:n.target.closest(t)}class Y9{constructor(t){u(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 yi(t).left-yi(e).left}getVerticalElementScrollOffset(t,e){return yi(t).top-yi(e).top}scrollTo(t,e){this.element.scrollLeft=t,this.element.scrollTop=e}}class Q9{constructor(){u(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 Rn={elements:[],cancelMethods:[],add:(n,t)=>{Rn.elements.push(n),Rn.cancelMethods.push(t)},remove:(n,t)=>{const e=Rn.elements.indexOf(n);e>-1&&(t&&Rn.cancelMethods[e](),Rn.elements.splice(e,1),Rn.cancelMethods.splice(e,1))}},jf=typeof window<"u",K9={cancelOnUserAction:!0,easing:n=>--n*n*n+1,elementToScroll:jf?window:null,horizontalOffset:0,maxDuration:3e3,minDuration:250,speed:500,verticalOffset:0};async function Bi(n,t={}){if(!jf)return new Promise(A=>{A(!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={...K9,...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 h=s?new Q9:new Y9(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=h.getHorizontalElementScrollOffset(r,i.elementToScroll),o=h.getVerticalElementScrollOffset(r,i.elementToScroll)}else if(typeof n=="number")e=h.getHorizontalScroll(),o=n;else if(Array.isArray(n)&&n.length===2)e=n[0]===null?h.getHorizontalScroll():n[0],o=n[1]===null?h.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=h.getMaxHorizontalScroll(),m=h.getHorizontalScroll();e>f&&(e=f);const C=e-m,v=h.getMaxVerticalScroll(),w=h.getVerticalScroll();w<o?o-=window.innerHeight*3/4:o-=window.innerHeight*1/4,o>v&&(o=v);const E=o-w,D=Math.abs(Math.round(C/1e3*i.speed)),x=Math.abs(Math.round(E/1e3*i.speed));let A=D>x?D:x;return A<i.minDuration?A=i.minDuration:A>i.maxDuration&&(A=i.maxDuration),new Promise((O,P)=>{C===0&&E===0&&O(!0),Rn.remove(h.element,!0);let V;const nt=()=>{re(),cancelAnimationFrame(V),O(!1)};Rn.add(h.element,nt);const ot=Fe=>Fe.preventDefault(),ut=i.cancelOnUserAction?nt:ot,dt=i.cancelOnUserAction?{passive:!0}:{passive:!1},Et=["wheel","touchstart","keydown","mousedown"],re=()=>{Et.forEach(Fe=>{h.element.removeEventListener(Fe,ut,dt)})};Et.forEach(Fe=>{h.element.addEventListener(Fe,ut,dt)});const Xn=Date.now(),te=()=>{const Fe=Date.now()-Xn,bo=Fe/A,cr=Math.round(m+C*i.easing(bo)),ar=Math.round(w+E*i.easing(bo));Fe<A&&(cr!==e||ar!==o)?(h.scrollTo(cr,ar),V=requestAnimationFrame(te)):(h.scrollTo(e,o),cancelAnimationFrame(V),re(),Rn.remove(h.element,!1),O(!0))};V=requestAnimationFrame(te)})}function So(n,t,e){return n.left<=t&&t<=n.right&&n.top<=e&&e<=n.bottom}function J9(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 Hf(n){if(!/["'&<>]/.exec(n))return n;const o={'"':""","'":"'","&":"&","<":"<",">":">"};return n.split("").map(l=>o[l]||l).join("")}function Ff(n){const t=document.getElementById(n);t&&t.remove()}function zf(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 Ei(n){const t="custom-cursor-style";if(n){const e=`body * { cursor: ${n} !important}`;zf(e,t)}else Ff(t)}const Uf=3,Vf=y("drag-drop");class qf{constructor(t){u(this,"dragStarted",!1);u(this,"mouseDownEvent",null);u(this,"_dragOffsetX",0);u(this,"_dragOffsetY",0);u(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()});u(this,"handleMouseMove",t=>{var i;t.preventDefault(),t.stopPropagation(),d(Vf,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:Uf;(Math.abs(e)>=r||Math.abs(o)>=r)&&this.onDragStart(this.mouseDownEvent)});u(this,"handleMouseUp",t=>{if(t.button===0){d(Vf,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&&Ei(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&&Ei(null),this.dragStarted&&this.options.onDragEnd(this,t,this.options.elem,e,o),this.unbindEvents(),this.dragStarted=!1}destroy(){this.unbindEvents(),this.untrackEvents()}}function qa(n){return new qf(n)}const X9=y("character");function Wf(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 Gf(n){const t=n.charAt(0);return t>="0"&&t<="9"}function Zf(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 tl(n){const t=[[9,13],[32],[160]];return Wf(n.charCodeAt(0),t)}function Yf(n){const t=[[12352,12687],[13056,13183],[13312,15661],[19968,40959],[63744,64255],[44032,55215]];return Wf(n.charCodeAt(0),t)}function Wa(n,t){let e=t;return d(X9,e.length===1,"invalid char length"),e==="]"&&(e="\\]"),e==="\\"&&(e="\\\\"),n.replace(new RegExp(`^[${e}]+|[${e}]+$`,"g"),"")}const On=navigator.userAgent;function Qf(){const n=navigator.userAgent.toLowerCase();return n.indexOf("safari")!==-1&&!(n.indexOf("chrome")>-1)}function Ga(){return navigator.userAgent.toLowerCase().indexOf("firefox")>-1}const St={isAndroid:!!On.match(/Android/i),isIOS:!!On.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/i),isIPad:!!On.match(/iPad/i),isIPhone:!!On.match(/iPhone/i),isLinux:!!On.match(/Linux/i),isMac:!!On.match(/Macintosh/i),isMobile:!!On.match(/AppleWebKit.*Mobile.*/i),isWindows:!!On.match(/Window/i),isIe:!!On.match(/msie|trident/i),isSafari:Qf(),isMobileSafari:!1};St.isMobileSafari=St.isMobile&&St.isSafari;function Za(n){return n?n.length===1||n==="Process"||n==="Unidentified"&&St.isAndroid:!1}function Kf(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 t7(n){return Kf(n.key)}function e7(n){switch(n){case"ArrowUp":case"ArrowLeft":case"Home":case"PageUp":return!0;default:return!1}}function To(n){return n.ctrlKey||n.altKey||n.shiftKey||n.metaKey}function n7(n){return n.key?!!(n.ctrlKey||n.metaKey||n.altKey):!1}function Jf(n){return St.isMac?n.metaKey&&!n.ctrlKey:!n.metaKey&&n.ctrlKey}function o7(n){return Jf(n)&&!n.altKey&&!n.shiftKey}function r7(n){return!n.metaKey&&!n.ctrlKey&&!n.shiftKey&&n.altKey}function Xf(n){return!To(n)&&n.key==="Enter"}function i7(n){return n.key==="Enter"&&n.shiftKey&&!n.altKey&&!n.ctrlKey&&!n.metaKey}function Ya(n){return!To(n)&&n.key==="Escape"}function s7(n){return!To(n)&&n.key==="Delete"}function tm(n){return!To(n)&&n.key==="Backspace"}function l7(n){return!To(n)&&n.key==="Tab"}function c7(n){return n.shiftKey&&n.key==="Tab"&&!n.ctrlKey&&!n.metaKey}function a7(n){if(!n)return"";if(St.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 em(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"?St.isMac?t.cmd=!0:t.ctrl=!0:r==="SPACE"?t.key=" ":t.key=r.substring(0,1)+r.substring(1).toLocaleLowerCase()}return t}function An(n,t){const e=em(t);return e.ctrl!==n.ctrlKey||e.alt!==n.altKey||e.shift!==n.shiftKey||St.isMac&&e.cmd!==n.metaKey?!1:e.key.length===1?e.key===n.key.toUpperCase():e.key.toUpperCase()===n.key.toUpperCase()}function Qa(n,t){return JC.stringifyUrl({url:n,query:t})}function Do(n){return typeof n=="string"?pi.Base64.encode(n,!0):pi.Base64.fromUint8Array(n,!0)}function el(n){return pi.Base64.decode(n)}function d7(n){return pi.Base64.toUint8Array(n)}function nm(n){return new Blob([pi.Base64.toUint8Array(n)])}const u7=eo.init([eo.classModule,eo.styleModule,eo.datasetModule,eo.attributesModule,eo.propsModule]);function Ii(n,t){const e=eo.toVNode(n),o=eo.toVNode(t);u7(e,o)}async function om(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 nl(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 h7(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 _n(n){let t=n;for(;t;){const e=window.getComputedStyle(t);if(/auto|scroll/i.test(e.overflowY))break;t=t.parentElement}return(!t||h7(t,"body"))&&(t=document.documentElement),t}function rm(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",rm,{passive:!1}),document.body.appendChild(t)}function sm(n){const t=document.querySelector(`.editor-disable-scroll[data-scroll-id="${n}"]`);t&&(t.removeEventListener("wheel",rm),t.remove())}function Ka(n,t,e){const o=new Blob([n]),r=new File([o],e,{type:t});return URL.createObjectURL(r)}function ol(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 lm(n){const t=document.createElement("div");return t.appendChild(n),t.innerHTML}function cm(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 rl(n,t){const o=(rl.canvas||(rl.canvas=document.createElement("canvas"))).getContext("2d");return o?(typeof t=="string"?t?o.font=t:o.font=cm(window.getComputedStyle(document.body)):t instanceof Element&&(o.font=cm(window.getComputedStyle(t))),o.measureText(n).width+4):200}const f7=y("editor-clipboard");async function m7(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 il(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 f7.error(t),!1}}function Lo(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 sl(n){return Array.isArray(n)?n.every(t=>t instanceof File):!1}function am(n){const t=n;if(!t)return"";const e=t.lastIndexOf(".");return e===-1?"":t.slice(e+1)}function ll(n,t){const e=document.createElement("a");e.setAttribute("download",`${t||""}`),e.setAttribute("href",`${n}`),e.click(),e.remove()}const dm=y("auto-scroll");function um(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 hm(n,{direction:t,step:e}){let o=null;const r=t==="left"||t==="right",i=()=>{if(!um(n,t))return dm.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 fm{constructor(t){u(this,"cancelScroll",null);u(this,"options");u(this,"scrollDomInfo");u(this,"scrolling",!1);u(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});u(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;dm.debug(`scroll direction: ${i}`),this.cancelScroll=hm(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 mm(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 Ja(n,t){let e=`${n}`;const o=t-e.length;for(let r=0;r<o;r++)e=`0${e}`;return e}const{t:Mo}=S;function Xa(n,t){const e=new Date(n).getTime()+864e5*t;return new Date(e)}function g7(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 p7(n,t){return Xa(n,t)}function td(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 gm(n){const t=new Date,e=new Date(n);return td(t,e)}function pm(n){const t=Xa(new Date,-1);return td(t,n)}function C7(n,t){return Math.round((n.getTime()-t.getTime())/864e5)}function Cm(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",Ja(r,2)),s=s.replace("dd",Ja(i,2)),s=s.replace("m",`${r}`),s=s.replace("d",`${i}`),s}return n.toLocaleDateString()}function ed(n,t){const e=new Date(n),o=new Date;if(e.getTime()-o.getTime()>10*1e3)return S.t("date.dateFromFuture");if(gm(e)){const i=(o.getTime()-n.getTime())/1e3;if(i<10*60)return Mo("date.dateJustNow");if(i<60*60)return Mo("date.dateMinutesAgo",{num:`${Math.floor(i/60)}`});const s=Math.floor(i/60/60);return s===1?Mo("date.date1HourAgo"):Mo("date.dateHoursAgo",{num:`${s}`})}if(pm(n))return Mo("date.dateYesterday");const r=Math.floor((o.getTime()-n.getTime())/1e3/24/60/60)+1;return r<14?Mo("date.dateDaysAgo",{num:`${r}`}):r<28?Mo("date.dateWeeksAgo",{num:`${Math.round(r/7)}`}):Cm(n,t)}function nd(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function b7(n,t,e){return n.replace(new RegExp(nd(t),"g"),e)}function v7(n,t,e){return n.replace(new RegExp(nd(t),"gi"),e)}const bm=y("container-children");function Ot(n){const t=Array.from(n.querySelectorAll(":scope > .container-blocks > div[data-type=editor-block]"));return d(bm,t.length>0,"container have not any child block"),t}function Kt(n){const t=n.querySelector(":scope > .container-blocks > div[data-type=editor-block]");return d(bm,t,"container have not any child block"),t}function Gt(n){const t=Ot(n);return t[t.length-1]}function Ve(n){return Ot(n).length}function fr(n,t){return Ot(n)[t]}const qe=y("block-dom");function mr(n){return n instanceof HTMLDivElement?n.getAttribute("data-type")==="editor-block":!1}function vm(n){M(n,"block-hidden")}function km(n){F(n,"block-hidden")}function cl(n){return!lt(n,"block-hidden")}function G(n){const{id:t}=n;return d(qe,t,"no block id"),t}function it(n){const t=n.getAttribute("data-block-type");return d(qe,t,"invalid block dom, no data-type"),t}function z(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 j(n){const t=n.closest("div[data-type=editor-container]");return d(qe,t,"failed to get block container"),t}function rt(n){const t=n.querySelector(":scope >div[data-type=block-content]");return d(qe,t,"no block content"),t}function At(n){let t=n.querySelector(":scope >div[data-type=block-tools]");return t||(t=b("div",[],n),t.setAttribute("data-type","block-tools")),d(qe,t,"no block tools"),t}function al(n){const t=n.querySelector(":scope >div[data-type=block-tools]");return t||null}function ym(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 wm(n,t,e){const o=n.editorDecorators.decorateBlock(t,e),{id:r,type:i}=o;d(qe,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&&M(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 no(n,t){const e=b(t,[],null);return e.setAttribute("data-type","block-content"),n&&n.appendChild(e),e}function Bm(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 xi(n){const t=n.getAttribute("data-box-type");return d(qe,t,"not a valid box element, no type"),t}function od(n){return n instanceof HTMLSpanElement?n.getAttribute("data-type")==="editor-box":!1}function Em(n){const{id:t}=n;return d(qe,t,"no box id"),t}function rd(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 Im(n){n.innerHTML="",b("span",["box-space-start"],n,ki);const t=b("span",[],n);return t.setAttribute("data-type","box-content"),b("span",["box-space-start"],n,ki),t}function id(n){const t=n.querySelector("span[data-type=box-content]");return d(qe,t,"invalid box dom, no content"),t}function xm(n,t){const e=b("span",[`${n}-insertion`],null);return e.setAttribute("data-type","editor-insertion"),e.setAttribute("data-insertion-id",t),e}function Sm(n,t){return n.rootContainer.querySelector(`[data-insertion-id=${t}]`)}function Tm(n){n.innerHTML="",b("span",["insertion-space-start"],n,ki);const t=b("span",[],n);return t.setAttribute("data-type","insertion-content"),b("span",["insertion-space-start"],n,ki),t}function sd(n){const t=n.querySelector("span[data-type=insertion-content]");return d(qe,t,"invalid insertion-child dom, no content"),t}function gt(n){let t=n.previousElementSibling;for(;t;){if(mr(t))return t;t=t.nextElementSibling}return null}function ht(n){let t=n.nextElementSibling;for(;t;){if(mr(t))return t;t=t.nextElementSibling}return null}function gr(n){let t=n.previousElementSibling;for(;t;){if(mr(t)&&cl(t))return t;t=t.previousElementSibling}return null}function pr(n){let t=n.nextElementSibling;for(;t;){if(mr(t)&&cl(t))return t;t=t.nextElementSibling}return null}function K(n){const t=j(n),o=Ot(t).indexOf(n);return d(qe,o!==-1,"invalid block & container dom, failed to get block index"),o}function ld(n){return!n||!(n instanceof Node)?!1:!!z(n)}function Si(n){if(!ld(n))return!1;const t=n,e=t instanceof Element?t:t.parentElement;return e?!!e.closest("div[data-type=block-tools]"):!1}const Dm=y("element");function cd(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 Cr(n,t){const e=n.rootElement.querySelector(`[data-container-id=${t}`);return d(Dm,e,`no container: ${t}`),e}function Lm(n,t){return n.rootElement.querySelector(`[data-container-id=${t}`)}function dl(n){const t=n.querySelector(":scope > .container-blocks");return d(Dm,t,"no container blocks element"),t}function k7(n){let t=n.querySelector(":scope > .container-tools");return t||(t=b("div",["container-tools"],n)),t}const Mm=y("container");function mn(n){return n.getAttribute("data-type")==="editor-container"}function Ct(n){return lt(n,"root")}function We(n){return lt(n,"child")}function U(n){const t=n.getAttribute("data-container-id");return d(Mm,t,"no id for container"),Ct(n)&&d(Mm,t==="root",`invalid root container id, : ${t}`),t}function Rm(n,t){const e=U(n);return t.getContainerBlocks(e)}const Om=y("block-path");function Ro(n){const t=[];let e=n;for(;e;){const o=j(e);if(t.unshift({containerId:U(o),blockIndex:K(e)}),Ct(o))return t;const r=z(o);d(Om,r,"no parent block"),e=r}return d(Om,!1,"no parent block"),[]}const y7=y("child-container-path");function Am(n){if(Ct(n))return[];const t=z(n);return d(y7,t,"no parent block"),Ro(t)}const _m=y("load-blocks");function ad(n,t,e){const o=U(t),r=Rm(t,n.doc);d(_m,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)}),dl(t).appendChild(i)}function w7(n,t,e){const o=dl(n),r=Ot(n);return d(_m,t>=0&&t<=r.length,"invalid block index"),t===r.length?o.appendChild(e):o.insertBefore(e,r[t]),e}function B7(n,t,e,o){const r=Am(t);r.push({containerId:U(t),blockIndex:e});const i=n.editorBlocks.createBlock(r,t,o);return w7(t,e,i),i}const Nm=y("root-container");class E7{constructor(t,e){u(this,"resizeObserver");u(this,"handleContextMenu",t=>{t.preventDefault()});u(this,"handleResize",()=>{try{this.editor.selection.updateSelection(null),this.editor.emit("resize",this.editor)}catch(t){Nm.warn(`failed to update selection while container resizing: ${t.message}`)}});u(this,"handleClick",t=>{var o,r;this.editor.emit("click",this.editor,t);const e=t.target;if(!Si(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&&vt(this.rootContainer,i)){const s=rd(i);if(s){const l=z(s);d(Nm,l,"no parent block"),(r=(o=this.editor.editorBoxes.getBoxClass(xi(s)))==null?void 0:o.handleClickBox)==null||r.call(o,this.editor,s,t)}}}});u(this,"handleDblClick",t=>{Si(t.target)||this.editor.selectionHandler.handleDblClick(t)});u(this,"handleMouseDown",t=>{const e=t.target;if(!!e&&e instanceof Node&&!Si(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)),St.isMobileSafari||(t.preventDefault(),this.editor.input.focus()),t.button===2&&t.stopPropagation()}});u(this,"handleMouseMove",t=>{this.editor.selectionHandler.handleMouseMove(t)});u(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=dl(this.rootContainer);e.innerHTML="",ad(this.editor,this.rootContainer,[]);const o=this.editor.findBlockById(t.start.blockId);if(o)this.editor.selection.selectBlock(o,0);else{const r=Kt(this.rootContainer);this.editor.selection.selectBlock(r,0)}}}function Pm(n){const t=cd(n.contentElement,"root","root");return n.rootContainer=t,ad(n,t,[]),new E7(n,t)}function $m(n,t,e,o){const r=Lm(n,o);if(r)return e.appendChild(r),r;const i=cd(e,"child",o);return ad(n,i,t),i}const jm=y("block-class");function kt(n,t){return n.editorBlocks.getBlockClass(it(t))}function Hm(n,t){const e=n.editorBlocks.getBlockClass(it(t));return d(jm,e.blockKind==="text",`is not a text block, ${e.blockType}`),e}function ye(n,t){const e=n.editorBlocks.getBlockClass(it(t));return d(jm,e.blockKind==="complex",`is not a text block, ${e.blockType}`),e}function br(n,t){return n.editorBlocks.getBlockClass(t)}const dd=y("block");function Z(n,t){return kt(n,t).getBlockTextLength(t)}function Fm(n){n.editorBlocks.forEach(t=>{t.clearSelection(n)})}function zm(n,t,e,o){kt(n,t).updateSelection(n,t,e,o)}function ul(n){for(;;){const t=j(n);if(Ct(t))return n;const e=z(t);d(dd,e,"no parent block exists for child container"),n=e}}function Um(n,t){const e=kt(n,t);if(!!e.getMinWidth)return e.getMinWidth(n,t)}function Vm(n,t,e){const o=kt(n,t);o.handleBlockElementUpdated&&o.handleBlockElementUpdated(n,t,e)}function hl(n,t,e,o){try{const r=br(n,e).convertFrom;return r?r(n,t,o):null}catch{return dd.debug(`unsupported block type: ${e}`),null}}function Oo(n,t,e){const o=kt(n,t);return o.getClientRects?o.getClientRects(n,t,e):[t.getBoundingClientRect()]}function I7(n,t){const e=kt(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(dd,s==="string"||s==="number"||s==="boolean","invalid style value")}),r}function qm(n,t){const e=n.getBoundingClientRect().width;return t.withPadding?e:e-Fa(n)}function ud(n,t){let e=Number.MAX_SAFE_INTEGER;const o=Ot(t);for(let i=0;i<o.length;i++){const s=o[i],l=Um(n,s);l&&(e=Math.min(e,l))}return e===Number.MAX_SAFE_INTEGER?void 0:e+Fa(t)}function H(n,t){return kt(n,t).blockKind==="text"}function Ti(n,t){return n.editorBlocks.getBlockClass(t).blockKind==="text"}function ct(n,t){return kt(n,t).blockKind==="complex"}function x7(n,t){return!ct(n,t)}function Ge(n,t){return kt(n,t).blockKind}function yt(n,t){return Ge(n,t)==="text"?Z(n,t)===0:!1}function hd(n,t){const e=Ot(t);return e.length!==1?!1:yt(n,e[0])}function Ze(n,t,e){return kt(n,t).getCaretRect(t,e)}function S7(n,t){var r,i;const e=kt(n,t);return(i=(r=e.getOptions)==null?void 0:r.call(e,n))!=null?i:{name:it(t)}}function Wm(n,t){var r;const e=kt(n,t);return(r=e.getBlockProperties)==null?void 0:r.call(e,n,t)}function fd(n,t){var i,s;const e=kt(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 Gm(n,t,e){var s,l,c,a;const o=kt(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 h of n.blockHooks){const f=(l=h.commands)==null?void 0:l.call(h,n,t);f&&(i[f.group]=f)}return(a=(c=i[e])==null?void 0:c.commands)!=null?a:[]}const Zm=y("embed-block-common");function De(n){return it(n)==="embed"}function Le(n){d(Zm,De(n),"not an embed block");const t=n.getAttribute("data-embed-type");return d(Zm,t,"no embed data type"),t}function T7(n,t){return n.editorEmbeds.getEmbedClass(Le(t))}function Ao(n,t){return n.editorEmbeds.getEmbedClass(t)}async function md(n,t,e,o,r){const i=Ao(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 D7(n,t,e,o,r){var l,c;const i=(c=(l=br(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 L7=y("execute-block-command");function Ym(n,t,e,o){var a;d(L7,De(t),"not a embed block");const r=Le(t),i=Ao(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 h of c)if(h[0]===e)return h[1].executeCommand(n,t,o)}function Qm(n,t,e,o){const r=fd(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 M7=y("complex-block-position");class Ye{constructor(t,e,o){u(this,"blockId");u(this,"childContainerId");u(this,"custom");t instanceof HTMLElement?this.blockId=G(t):(d(M7,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 R7=y("simple-block-position");class Ut{constructor(t,e,o){u(this,"blockId");u(this,"offset");u(this,"type");t instanceof HTMLElement?this.blockId=G(t):(d(R7,typeof t=="string",`not a valid block id: ${t}`),this.blockId=t),this.offset=e,this.type=o}isSimple(){return!0}}const gd=y("editor-position");function $(n,t,e){return new Ut(n,t,e)}function bt(n,t,e){return new Ye(n,t,e)}function vr(n){return n instanceof Ut}function pd(n){return n instanceof Ye}function Cd(n,t,e){if(vr(t)&&vr(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(gd,i!==s,"comparePosition: blocks are the same"),Xs(i,s)}if(pd(t)&&pd(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(gd,i!==s,"comparePosition: containers are the same"),Xs(i,s)}return d(gd,!1,"invalid "),0}const fl=y("simple-range");class se{constructor(t,e){u(this,"editor");u(this,"_anchor");u(this,"_focus");u(this,"reverse");this.editor=t,this._anchor=e.anchor,this._focus=e.focus,this.reverse=Cd(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 se))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(fl,e,"no start block"),d(fl,o,"no end block");const r=j(e),i=j(o);d(fl,r===i,"invalid range");const s=[];if(e===o)s.push({block:e,start:this.start,end:this.end});else{const l=K(e),c=K(o);d(fl,l<c,"invalid range, start > index"),s.push({block:e,start:this.start,end:$(e,Z(this.editor,e),"end")});const a=Ot(r);for(let h=l+1;h<c;h+=1){const f=a[h];s.push({block:f,start:$(f,0,"home"),end:$(f,Z(this.editor,f),"end")})}s.push({block:o,start:$(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 se(this.editor,this)}toDocRange(){return{anchor:this.anchor,focus:this.focus}}}y("unknown-block");function O7(n,t,e,o,r){M(o,"unknown-block");const i=no(o,"div");return i.innerText=`unknown block (${r.type}): ${JSON.stringify(r)}`,i}function A7(n){return 1}function _7(n,t,e,o){return null}function N7(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t))return null;const i=G(t),s=$(i,0,"home"),l=$(i,1,"end");return new se(n,{anchor:s,focus:l})}function P7(n,t){const o=rt(n).getBoundingClientRect();return new DOMRect(o.left+o.width/2,o.top,1,o.height)}function $7(n,t,e,o){M(t,"selected")}function j7(n){n.rootContainer.querySelectorAll("div.unknown-block[data-type=editor-block]").forEach(t=>{F(t,"selected")})}const H7={blockType:"unknown-block",blockKind:"embed",createBlockContent:O7,getBlockTextLength:A7,getRangeFromPoint:N7,moveCaret:_7,getCaretRect:P7,updateSelection:$7,clearSelection:j7},bd=y("editor-blocks");class Km{constructor(t){u(this,"blocks",new Map);this.editor=t}registerBlockClass(t){const e=t.blockType,o=this.blocks.get(e);d(bd,!o,`duplicated block type: ${e}`),this.blocks.set(e,t)}getBlockClass(t){const e=this.blocks.get(t);return d(bd,e,`unknown block type: ${t}`),e}hasBlock(t){return this.blocks.has(t)}createBlock(t,e,o){const r=wm(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&&(bd.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={...H7,blockType:t};return this.editor.editorBlocks.registerBlockClass(e),e}}const Jm=y("editor-embeds");class Xm{constructor(t){u(this,"objects",new Map);this.editor=t}registerEmbedClass(t){const e=t.embedType,o=this.objects.get(e);d(Jm,!o,`duplicated embed object type: ${e}`),this.objects.set(e,t)}getEmbedClass(t){const e=this.objects.get(t);return d(Jm,e,`unknown embed type: ${t}`),e}getEmbedClassFromBlock(t){return this.getEmbedClass(Le(t))}forEach(t){this.objects.forEach(t)}}const tg=y("embed-block");function F7(n,t,e,o,r){const i=no(o,"div");d(tg,r.type==="embed",`not an embed data: ${JSON.stringify(r)}`);const s=r;return d(tg,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 z7(n){return 1}function U7(n,t,e,o){return null}function V7(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t))return null;const i=G(t),s=$(i,0,"home"),l=$(i,1,"end");return new se(n,{anchor:s,focus:l})}function q7(n,t){const o=rt(n).getBoundingClientRect();return new DOMRect(o.left+o.width/2,o.top,1,o.height)}function W7(n,t,e,o){M(t,"selected")}function G7(n){n.rootContainer.querySelectorAll("div.embed-block[data-type=editor-block][data-block-type=embed]").forEach(t=>{F(t,"selected")})}function Z7(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 Y7(n,t,e,o){const r=Ao(n,t.embedType);return r.convertTo?r.convertTo(n,t,e,o):""}function Q7(n,t){const e=T7(n,t);return e.getBlockProperties?e.getBlockProperties(n,t):{}}function K7(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 J7(n,t,e,o){const r=Le(t),i=Ao(n,r);!i.handleDeleteBlock||i.handleDeleteBlock(n,t,e,o)}function X7(n,t,e){const o=Le(t),r=Ao(n,o);return r.handleUpdateBlock?r.handleUpdateBlock(n,t,e):!1}function t8(n,t,e,o,r){const i=Le(t),s=Ao(n,i);if(s.handleDropOver)return s.handleDropOver(n,t,e,o,r)}function e8(n,t,e,o,r){const i=Le(t),s=Ao(n,i);if(s.handleDrop&&n.isWritable())return s.handleDrop(n,t,e,o,r)}const eg={blockType:"embed",blockKind:"embed",createBlockContent:F7,getBlockTextLength:z7,getRangeFromPoint:V7,moveCaret:U7,getCaretRect:q7,updateSelection:W7,clearSelection:G7,convertFrom:Z7,convertTo:Y7,getBlockProperties:Q7,getOptions:K7,handleDeleteBlock:J7,handleUpdateBlock:X7,handleDropOver:t8,handleDrop:e8},le=y("complex-block-helper");function Me(n,t){return ye(n,t).getChildContainers(n,t)}function kr(n,t,e,o){return e.isSimple()?(d(le,o.isSimple(),"invalid start and end position"),Me(n,t)):(d(le,!e.isSimple(),"invalid start pos"),d(le,!o.isSimple(),"invalid end pos"),ye(n,t).getSelectedContainers(n,t,e,o))}function n8(n,t){if(K(t)!==0)return!1;const e=z(j(t));if(!e)return!1;d(le,ct(n,e),"not a complex block");const o=j(t),i=Me(n,e).indexOf(o);return d(le,i>=0,"not valid child container"),i===0}function vd(n,t){const e=Me(n,t);if(e.length===0)return null;const o=e[0],r=Kt(o);return ct(n,r)?vd(n,r):r}function yr(n,t){const e=Me(n,t);if(e.length===0)return null;const o=e[e.length-1],r=Gt(o);return ct(n,r)?yr(n,r):r}function ng(n,t){d(le,We(t),"not a child container");const e=z(t);d(le,e,"no parent block"),d(le,ct(n,e),"not a complex block");const o=Me(n,e),r=o.indexOf(t);if(d(le,r!==-1,"child container not found"),r===0){const l=gt(e);return l?ct(n,l)?yr(n,l):l:null}const i=o[r-1],s=Gt(i);return ct(n,s)?yr(n,s):s}function og(n,t){d(le,ct(n,t),"not a complex block");const e=Me(n,t);if(d(le,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],h=a.getBoundingClientRect();if(h.right<=i){l.push(a),i=h.left;continue}if(h.left>=s){s=h.right;continue}}return l}function rg(n,t){d(le,ct(n,t),"not a complex block");const e=Me(n,t);if(d(le,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],h=a.getBoundingClientRect();if(h.right<=i){l.push(a),i=h.left;continue}if(h.left>=s){s=h.right;continue}}return l}function ig(n,t,e,o){const r=t.getBoundingClientRect(),i=o<r.top,s=i?og(n,t):rg(n,t);let l=s[0],c=fn(l.getBoundingClientRect(),e,o);for(let a=1;a<s.length;a++){const h=s[a],f=h.getBoundingClientRect(),m=fn(f,e,o);m<c&&(l=h,c=m)}return i?Kt(l):Gt(l)}function ml(n,t,e,o){const r=G(t);d(le,r===e.blockId,"invalid start pos"),d(le,r===o.blockId,"invalid end pos");const i=ye(n,t);return i.adjustSelectionPos?i.adjustSelectionPos(n,t,e,o):{anchor:e,focus:o}}class Qe{constructor(t,e){u(this,"editor");u(this,"reverse");u(this,"_anchor");u(this,"_focus");this.editor=t,this._anchor=e.anchor,this._focus=e.focus,this.reverse=Cd(this.editor,this._anchor,this._focus)>0}isCollapsed(){return!1}isEqual(t){if(!(t instanceof Qe))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 kr(this.editor,t,this.start,this.end)}clone(){return new Qe(this.editor,this)}toDocRange(){return{anchor:this._anchor,focus:this._focus}}}const o8=y("selection-range");function Vt(n,t){const{anchor:e,focus:o}=t;return e instanceof Ut&&o instanceof Ut?new se(n,{anchor:e,focus:o}):(d(o8,e instanceof Ye&&o instanceof Ye,"start position type does not math end type"),new Qe(n,{anchor:e,focus:o}))}function Lt(n,t,e,o){const r=new Ut(t,e,"normal"),i=new Ut(t,o!=null?o:e,"normal");return Vt(n,{anchor:r,focus:i})}function r8(n){return!!n.anchor.childContainerId}function oo(n,t){var r,i;if(r8(t)){const s=bt(t.anchor.blockId,t.anchor.childContainerId,(r=t.anchor)==null?void 0:r.custom),l=bt(t.focus.blockId,t.focus.childContainerId,(i=t.focus)==null?void 0:i.custom);return Vt(n,{anchor:s,focus:l})}const e=$(t.anchor.blockId,t.anchor.offset,"normal"),o=$(t.focus.blockId,t.focus.offset,"normal");return Vt(n,{anchor:e,focus:o})}function kd(n,t){const e=[];return Ot(t).forEach(r=>{e.push(r),ct(n,r)&&Me(n,r).forEach(s=>{e.push(...kd(n,s))})}),e}function yd(n,t){let e=kd(n,n.rootContainer);return t!=null&&t.simpleBlockOnly&&(e=e.filter(o=>!ct(n,o))),e}function Ke(n,t){const e=n.selection.range.getSelectedBlocks(),o=[];for(const r of e)o.push(r),ct(n,r.block)&&kr(n,r.block,r.start,r.end).forEach(s=>{const c=kd(n,s).map(a=>({block:a,start:$(a,0,"home"),end:$(a,Z(n,a),"home")}));o.push(...c)});return t!=null&&t.simpleBlockOnly?o.filter(r=>!ct(n,r.block)):o}const KH="";function _o(n,t,e,o){const r=At(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}const Nn=y("text-block-child");function Di(n){return n.tagName==="SPAN"}function Re(n){return d(Nn,Di(n),"not a valid text child"),n.getAttribute("data-type")==="editor-box"}function Pn(n){return d(Nn,Di(n),"not a valid text child"),n.getAttribute("data-type")==="editor-insertion"}function Li(n){return!Re(n)&&!Pn(n)}function sg(n){return d(Nn,Di(n),"not a valid text child"),Re(n)?"box":Pn(n)?"insertion":"text"}function Oe(n){const t=sg(n);return t==="insertion"?0:t==="box"?1:(d(Nn,n.textContent!==null,"text block content is undefined"),d(Nn,n.textContent.length>=0,"text block content length is negative"),n.textContent.length)}function $n(n){const t=rt(n),e=Array.from(t.children);return e.forEach(o=>{d(Nn,Di(o),"not a valid text child")}),e}function gl(n,t){const e=$n(n);let o=0;for(let r=0;r<e.length;r++){const i=e[r],s=Oe(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(Nn,l>0,"invalid offset value"),d(Nn,!Re(i),"invalid box child"),{prev:i,next:i,offset:l}}d(Nn,!1,`invalid block child at position: ${t}`)}function Mi(n){const t=$n(n);let e=0;return t.forEach(o=>{e+=Oe(o)}),e}const lg=y("box");function wd(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 cg=y("rich-text-length");function Bd(n){return d(cg,typeof n.insert=="string","op.insert is not string"),n.insert.length}function ce(n){let t=0;return n.forEach(e=>{e.insert&&(d(cg,typeof e.insert=="string","op.insert is not string"),t+=Bd(e))}),t}const gn=y("split-text");function fe(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(gn,typeof i=="object",`invalid op type, ${typeof i}`),d(gn,typeof i.insert=="string",`invalid op.insert type, ${typeof i.insert}`);const s=Bd(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(gn,o+s>t,`invalid offset, ${o}, ${s}, ${t}`);const l=t-o,c=Y.default(i);d(gn,c.insert,"no copied.insert"),d(gn,typeof c.insert=="string","invalid copied.insert type"),c.insert=c.insert.substr(0,l),i.insert=i.insert.substr(l),c.insert===""&&d(gn,!1,"invalid copied.insert, is empty string"),i.insert===""&&d(gn,!1,"invalid op.insert, is empty string");const a=[i,...n.slice(r+1)],h=[...n.splice(0,r),c];return e&&(e.sourceOp=i),{left:h,right:a}}}}throw new Error(`invalid split offset: ${t}, ${JSON.stringify(n)}`)}function Jt(n,t,e){d(gn,t>=0,"invalid offset, < 0"),d(gn,e>0,"invalid length, <= 0"),d(gn,t+e<=ce(n),"invalid offset + length < text length");const{left:o,right:r}=fe(n,t+e),{left:i,right:s}=fe(o,t);return{left:i,middle:s,right:r}}function ag(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}=fe(r,s);r=l,o.unshift(c)}return r.length>0&&o.unshift(r),o}function dg(n,t,e){return Jt(n,t,e).middle}const wr=y("text-block-content");function i8(n,t,e,o,r){if(d(wr,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 h=ag(o,i);for(let f=0;f<h.length;f++){l(c,a);const m=h[f];a+=ce(m);for(let C=0;C<m.length;C++){const v=m[C];if(wd(v)){d(wr,v.attributes,`op is not an valid box: ${JSON.stringify(v)}`);const E=n.editorBoxes.createBox(e,v.attributes);d(wr,E instanceof HTMLSpanElement,`invalid box element: ${E.tagName}`),c.appendChild(E);continue}d(wr,v.insert,`no insert in op: ${JSON.stringify(v)}`);const w=b("span",["text"],c,v.insert);if(v.attributes){const E=n.editorBlockRenders.renderText(t,v.attributes);E.classes&&M(w,...E.classes),E.attributes&&Object.entries(E.attributes).forEach(([D,x])=>{w.setAttribute(D,x)}),E.styles&&Object.entries(E.styles).forEach(([D,x])=>{w.style.setProperty(D,x)})}c.appendChild(w)}}l(c,a),e.innerHTML="",e.appendChild(c)}function pl(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(wr,c.isSimple(),"not an simple position while compositing"),c.blockId===e&&s.set(c.offset,[{type:"inputting",id:N(),text:l}])}return i8(n,t,o,i,s)}function s8(n){const t=n.rootContainer.querySelectorAll('span[data-type="editor-insertion"].inputting-insertion');t.length&&wr.debug(`remove ${t.length} temp composition span`),Array.from(t).forEach(e=>e.remove())}const Zt=y("text-range");function l8(n,t){const e=(i,s)=>{if(Pn(i))return d(Zt,s===0,`invalid offset for insertion child: ${s}`),{child:i,container:i,offset:2};if(Re(i))return d(Zt,s===0||s===1,`invalid offset for box: ${s}`),{child:i,container:i,offset:s===0?1:2};const l=i.firstChild;return d(Zt,l,"no child node for text child"),d(Zt,l instanceof Text||l instanceof HTMLBRElement,`invalid child for text child, ${l.nodeName}`),l instanceof HTMLBRElement?(d(Zt,s>=0&&s<=0,"invalid offset for text child"),{child:i,container:l,offset:s}):(d(Zt,s>=0&&s<=l.data.length,"invalid offset for text child"),{child:i,container:l,offset:s})};let o=0;const r=$n(n);for(let i=0;i<r.length;i++){const s=r[i],l=Oe(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,Oe(s)));const a=r[i+1];return a&&c.push(e(a,0)),c}o+=l}d(Zt,!1,"failed to get range info")}function c8(n,t,e){if(t===e?d(Zt,Pn(n),"only insertion child can be zero offset"):d(Zt,t<e,`invalid start & end: ${t}, ${e}`),Pn(n)){d(Zt,t===e,`invalid insertion child range offset: ${t}, ${e}`),d(Zt,t===0,`invalid insertion child range start: ${t}`);const i=n;return d(Zt,i.children.length===3,`invalid insertion dom, children.length = ${i.children.length}`),Ks(i,1,i,2)}if(Re(n)){d(Zt,t+1===e,`invalid box child range offset: ${t}, ${e}`),d(Zt,t===0,`invalid box child range start: ${t}`);const i=n;return d(Zt,i.children.length===3,`invalid box dom, children.length = ${i.children.length}`),Ks(i,1,i,2)}const o=Oe(n);d(Zt,e<=o,`invalid child end: ${e}, ${o}`);const r=n.firstChild;return d(Zt,r instanceof Text,"invalid block text child"),d(Zt,r.data.length>=e,`invalid range end: ${e}, ${r.data.length}`),Ks(r,t,r,e)}const Je=y("caret-rect");function a8(n,t){if(od(t)){const e=t,o=id(e);if(e.getAttribute("data-box-type")==="br"){const r=rt(n),i=Number.parseFloat(window.getComputedStyle(r).lineHeight)||o.getBoundingClientRect().height,s=Array.from(o.getClientRects());d(Je,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 sd(t).getClientRects()}function Ae(n,t){var l,c;const e=l8(n,t.offset);if(e[1]&&e[0].child!==((l=e[1])==null?void 0:l.child)){if(t.type==="end"){const h=Io(e[0].child);return new DOMRect(h.right,h.top,1,h.height)}d(Je,e[1],"invalid ranges");const a=Js(e[1].child);return new DOMRect(a.left,a.top,1,a.height)}let r=e[0];if(d(Je,e.length>=1,"failed to get block range"),e.length===1)r=e[0];else{if(d(Je,e.length>=2,`invalid range info length: ${e.length}`),Pn(e[e.length-1].child)){r=e[e.length-1];const a=r.child,f=sd(a).getClientRects();d(Je,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"||Li(e[0].child)?r=e[0]:Li(e[1].child)&&(r=e[1])}if(r.container instanceof HTMLBRElement){d(Je,t.offset===0,"invalid offset for empty block text");const a=(c=r.container.parentElement)==null?void 0:c.parentElement;d(Je,a===rt(n),"invalid br parent, is not block parent");const h=a.getBoundingClientRect();return new DOMRect(h.left,h.top,1,h.height)}const s=_f(r.container,r.offset).getClientRects();if(s.length===0){d(Je,!Li(r.child),"only box or insertion child range has zero client rect"),d(Je,r.offset===1||r.offset===2,"invalid offset for box or insertion child");const a=r.child,h=a8(n,a);if(d(Je,h.length>=1,"no client rects for box content"),r.offset===1){const m=h[0];return new DOMRect(m.x,m.y,1,m.height)}const f=h[h.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(Je,s.length>0,"no client rects for range"),t.type==="home"?s[s.length-1]:s[0]}const pn=y("client-rects");function d8(n){const t=$n(n);let e=0;const o=[];for(let r=0;r<t.length;r++){const i=t[r],s=Oe(i);o.push({child:i,startBlockOffset:e,endBlockOffset:e+s}),e+=s}return o}function u8(n,t,e,o){d(pn,e<o,`invalid from & to: ${e}, ${o}`);const r=Z(n,t);d(pn,e>=0&&o>=0&&e<=r&&o<=r,`invalid offset: ${e}, ${o}, length: ${r}`);const i=d8(t),s=i.findIndex(C=>C.startBlockOffset<=e&&e<C.endBlockOffset),l=i.findIndex(C=>C.startBlockOffset<o&&o<=C.endBlockOffset);if(d(pn,s!==-1,"failed to find start child"),d(pn,l!==-1,"failed to find end child"),d(pn,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],h={child:a.child,startChildOffset:e-a.startBlockOffset,endChildOffset:Oe(a.child)};c.push(h);for(let C=s+1;C<l;C++){const v=i[C],w={child:v.child,startChildOffset:0,endChildOffset:v.endBlockOffset-v.startBlockOffset};c.push(w)}const f=i[l],m={child:f.child,startChildOffset:0,endChildOffset:o-f.startBlockOffset};return c.push(m),c}function h8(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 ug(n,t,e,o){if(Z(n,t)===0){const h=rt(t).getBoundingClientRect();return[new DOMRect(h.left,h.top,4,h.height)]}const r=e.offset,i=o.offset;if(r===i)return[Ae(t,e)];const l=u8(n,t,r,i).map(a=>c8(a.child,a.startChildOffset,a.endChildOffset)),c=[];return l.forEach(a=>{const h=h8(Array.from(a.getClientRects()));c.push(...h)}),c}function f8(n,t,e){d(pn,e instanceof se,"invalid range");const o=e.start,r=e.end;return d(pn,o.isSimple(),"text block only allow simple position"),d(pn,r.isSimple(),"text block only allow simple position"),d(pn,o.blockId===r.blockId,"only allow update one text block selection"),d(pn,o.blockId===G(t),"only allow update one text block selection"),ug(n,t,o,r)}const Ed=y("selection-background");function m8(n,t,e,o){d(Ed,e.isSimple(),"text block only allow simple position"),d(Ed,o.isSimple(),"text block only allow simple position"),d(Ed,e.blockId===o.blockId,"only allow update one text block selection");const r=e.offset,i=o.offset;if(r===i&&(Z(n,t)!==0||n.selection.range.isCollapsed()))return;const s=ug(n,t,e,o),l=t.getBoundingClientRect(),c=ym(t);c.innerHTML="",s.forEach(a=>{const h=b("div",["editor-selection-background"],c);h.style.left=`${a.left-l.left}px`,h.style.top=`${a.top-l.top}px`,h.style.width=`${a.width}px`,h.style.height=`${a.height}px`})}function g8(n){n.rootContainer.querySelectorAll("div[data-type=block-background]").forEach(t=>{t.remove()})}const No=y("text-offset"),hg="\u200D";function Br(n,t){const e=$n(n);let o=0;for(let r=0;r<e.length;r++){const i=e[r],s=Oe(i);if(i===t){const l=o+s;return{start:o,end:l}}o+=s}d(No,!1,"can not find child in children")}function me(n,t){d(No,t>=0,`invalid offset: ${t}`);const e=gl(n,t),{prev:o,next:r,offset:i}=e;if(!o&&!r&&d(No,!1,"invalid offset, no prev & next child at offset"),o!==r)return!0;const s=o;if(d(No,s,"no child"),Re(s))return d(No,i===0||i===1,`invalid box child offset: ${i}`),!0;const l=s.textContent;d(No,l,"no content for text child");const c=l.charAt(i-1),a=l.charAt(i);return!(c===hg||a===hg||Ha(l[i]))}function Po(n,t){if(t===0)return 0;const e=t-1;if(me(n,e))return e;let o=e-1;for(;!me(n,o);)o-=1;return o}function Er(n,t){const e=Mi(n);if(d(No,t>=0&&t<=e,`invalid offset: ${t}, ${e}`),t===e)return e;const o=t+1;if(me(n,o))return o;let r=o+1;for(;!me(n,r);)r+=1;return r}const $o=y("line-breaker");function Ri(n){const t=c=>{const a=Js(c);return Io(c).top>a.top+a.height/2},e=(c,a)=>{const h=Io(c);return Js(a).left<h.right},o=(c,a)=>{const h=Io(c),f=Io(a);return f.top+f.height/2>h.bottom},r=c=>{if(c.length===0||c.length===1)return!1;const a=c[0],h=c[c.length-1];return a.right-h.left>10},i=[];let s=0;const l=$n(n);for(let c=0;c<l.length;c++){const a=l[c];if(Pn(a)){const E=a,D=l[c+1];if(!D)break;const x=l[c-1];if(x&&o(x,E)&&i.push({offset:s,type:"betweenChild",childInfo:{prevChild:x,nextChild:E,wrap:"nextWrapped",prevWrapped:t(x),nextWrapped:t(E)}}),e(E,D)){i.push({offset:s,type:"betweenChild",childInfo:{prevChild:x,nextChild:E,wrap:"nowrap",prevWrapped:t(x),nextWrapped:t(E)}});continue}continue}if(Re(a)){const E=a,D=l[c+1];if(!D)break;const x=l[c-1];if(x&&o(x,E)&&i.push({offset:s,type:"betweenChild",childInfo:{prevChild:x,nextChild:E,wrap:"nextWrapped",prevWrapped:t(x),nextWrapped:t(E)}}),e(E,D)){s+=1,i.push({offset:s,type:"betweenChild",childInfo:{prevChild:x,nextChild:a,wrap:"nowrap",prevWrapped:t(x),nextWrapped:t(a)}});continue}s+=1;continue}const h=a,f=h.getClientRects();if(d($o,f.length>0,"invalid text child dom"),f.length===1){const E=l[c+1];if(!E)break;if(e(h,E)){s+=Oe(h),i.push({offset:s,type:"betweenChild",childInfo:{prevChild:h,nextChild:E,wrap:"nowrap",prevWrapped:t(h),nextWrapped:t(E)}});continue}s+=Oe(h);continue}const m=h.firstChild;d($o,m,"invalid text child, no text node"),d($o,m instanceof Text,`invalid text child, not a valid text node: ${typeof m}`);const C=document.createRange(),v=document.createRange(),w=Oe(h);d($o,m.data.length===w,"text node data length not equal child text length");for(let E=0;E<m.data.length;E++){if(!me(n,s+E))continue;C.setStart(m,E),Ga()&&C.selectNodeContents(m);const D=C.getClientRects();if(d($o,D.length>=1,"invalid text node, no client rects"),r(D)){const V=s+E;i.push({offset:V,type:"textBreakWord",childInfo:{prevChild:a,nextChild:a,wrap:"nowrap",prevWrapped:t(a),nextWrapped:t(a)}});continue}let x=E+1;me(n,s+x)||(x=E+2),v.setStart(m,x);const A=v.getClientRects(),O=D[0];A[0].left<O.right&&d($o,!1,"span pre-wrap should not has a line-wrap by white space")}s+=w}return i}function Id(n,t){const e=Ri(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($o,t.offset<=Mi(n),"invalid position, offset > block length"),{lineIndex:e.length,lineBreaks:e}}const p8=y("line-offset");function xd(n){const t=Ri(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:Mi(n)}),e}function Cl(n,t){const e=xd(n);return d(p8,t>=0&&t<e.length,`invalid line index: ${t}, ${e.length}`),e[t]}function fg(n,t){const{lineIndex:e}=Id(n,t);return Cl(n,e)}function C8(n){const t=xd(n),e=n.getBoundingClientRect(),o=[];return t.forEach(({start:r,end:i})=>{const s=$(n,r,"home");let l=Ae(n,s);const c=$(n,i,"end"),a=Ae(n,c);l.top+l.height/2<a.top&&(l=new DOMRect(e.left-1e4,a.top,1,a.height));const h=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:h})}),o}function b8(n,t,e){const r=C8(n).find(s=>So(s.rect,t,e));if(!r)return null;const i=r.contentRect;return t-i.left<i.right-t?$(n,r.start,"home"):$(n,r.end,"end")}function mg(n,t,e){const o=Ae(n,t),r=Ae(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 gg(n){return xd(n).length}const jo=y("find-text-position");function pg(n,t){const{start:e,end:o}=Cl(n,t),r=G(n),i=Ae(n,$(r,e,"home"));if(!(Ae(n,$(r,o,"end")).top>i.top+i.height/2))return!1;const c=gl(n,e);return d(jo,c.next,"no next child at offset"),d(jo,!Li(c.next),"next child is not text child"),!0}function v8(n,t){const e=G(n);d(jo,pg(n,t),"line is not wrapped");const{start:o,end:r}=Cl(n,t),i=$(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=$(e,s,l);if(!mg(n,i,c))return s-1}return d(jo,!1,"failed to find wrapped offset"),0}function bl(n,t,e,o,r,i,s){d(jo,H(n,t),`not a text kind block: ${it(t)}`);const{start:l,end:c}=Cl(t,e);let a=l;const h=G(t);if(t===o&&pg(t,e)){const E=v8(t,e);(i==="up"||i==="down"&&mg(t,r,$(h,l,"home")))&&(a=E+1)}let f=Number.MAX_SAFE_INTEGER;const m=Ze(n,o,r),C=s!=null?s:m.left+m.width/2,v=m.top+m.height/2;let w=$(h,a,"home");for(let E=a;E<=c;E++){if(!me(t,E))continue;let D="normal";E===l?D="home":E===c&&(D="end");const x=$(h,E,D),A=Ae(t,x),O=fn(A,C,v);O<f&&(f=O,w=x)}return w}function k8(n,t,e,o,r){return d(jo,H(n,t),"not a text block"),bl(n,t,gg(t)-1,e,o,"up",r)}function y8(n,t,e,o,r){return d(jo,H(n,t),"not a text block"),bl(n,t,0,e,o,"down",r)}function w8(n,t,e,o){const{lineIndex:r}=Id(t,e);if(r===gg(t)-1)return null;const i=bl(n,t,r+1,t,e,"down",o);return i||null}function B8(n,t){if(t.offset===0)return null;const e=Ri(n),o=e.find(r=>r.offset===t.offset);if(!o){const r=Po(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:Po(n,t.offset),type:"normal"}}return{offset:Po(n,t.offset),type:"normal"}}function E8(n,t){const e=Mi(n);if(t.offset===e)return null;const o=Ri(n),r=o.find(i=>i.offset===t.offset);if(!r){const i=Er(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:Er(n,t.offset),type:"home"}:{offset:Er(n,t.offset),type:"normal"}}function I8(n,t,e,o){const{lineIndex:r}=Id(t,e);if(r===0)return null;const i=bl(n,t,r-1,t,e,"up",o);return i||null}const x8=y("move-caret");function S8(n,t,e,o){if(o==="ArrowLeft"){const r=B8(t,e);return r?$(G(t),r.offset,r.type):null}if(o==="ArrowRight"){const r=E8(t,e);return r?$(G(t),r.offset,r.type):null}if(o==="ArrowUp"){const r=I8(n,t,e,n.selection.getSuggestedCaretX());return r?$(G(t),r.offset,r.type):null}if(o==="ArrowDown"){const r=w8(n,t,e,n.selection.getSuggestedCaretX());return r?$(G(t),r.offset,r.type):null}d(x8,!1,`invalid navigation direction: ${o}`)}const Sd=y("text-range");function T8(n){const t=[];return $n(n).forEach(o=>{const r=Array.from(o.getClientRects()).map(i=>({rect:i,child:o}));t.push(...r)}),t}function D8(n,t,e){const o=T8(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 Br(n,s.child).start}return null}function L8(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 D=t.getBoundingClientRect();if(!So(D,e,o))return null;const x=D8(t,e,o);if(x!==null){const O=$(t,x,"normal");return new se(n,{anchor:O,focus:O})}const A=b8(t,e,o);return A?new se(n,{anchor:A,focus:A}):null}const s=$n(t);d(Sd,s.indexOf(i)!==-1,"failed to find child in children");const l=Br(t,i);d(Sd,l,"failed to get child offset");const{start:c}=l;let a,h;Pn(i)||Re(i)?(a=c,h=0):(d(Sd,i.firstChild instanceof Text,"child is not text"),a=c+Nf(i.firstChild,e,o),h=0);const f=G(t),C=Ri(t).find(D=>D.offset===a);let v="normal";if(C){const D=$(f,a,"home"),x=$(f,a,"end"),A=Ae(t,D),O=Ae(t,x),P=fn(A,e,o),V=fn(O,e,o);v=P<V?"home":"end"}const w=$(f,a,v);let E;return h&&(E=$(f,a+h,v)),new se(n,{anchor:w,focus:E!=null?E:w})}const M8=y("create-text-op");function _e(n,t){d(M8,n,"text is empty");const e={insert:n};return t&&Object.keys(t).length>0&&(e.attributes=t),e}function Td(n,t){if(n.length===0)return[];if(n.indexOf(`
|
|
15
|
+
animateScrollTo(scrollToElement:Element, options)`;e+=i.horizontalOffset,o+=i.verticalOffset;const f=h.getMaxHorizontalScroll(),m=h.getHorizontalScroll();e>f&&(e=f);const C=e-m,v=h.getMaxVerticalScroll(),w=h.getVerticalScroll();w<o?o-=window.innerHeight*3/4:o-=window.innerHeight*1/4,o>v&&(o=v);const E=o-w,L=Math.abs(Math.round(C/1e3*i.speed)),x=Math.abs(Math.round(E/1e3*i.speed));let O=L>x?L:x;return O<i.minDuration?O=i.minDuration:O>i.maxDuration&&(O=i.maxDuration),new Promise((A,P)=>{C===0&&E===0&&A(!0),Rn.remove(h.element,!0);let V;const nt=()=>{re(),cancelAnimationFrame(V),A(!1)};Rn.add(h.element,nt);const ot=Fe=>Fe.preventDefault(),ut=i.cancelOnUserAction?nt:ot,dt=i.cancelOnUserAction?{passive:!0}:{passive:!1},Et=["wheel","touchstart","keydown","mousedown"],re=()=>{Et.forEach(Fe=>{h.element.removeEventListener(Fe,ut,dt)})};Et.forEach(Fe=>{h.element.addEventListener(Fe,ut,dt)});const Xn=Date.now(),te=()=>{const Fe=Date.now()-Xn,bo=Fe/O,cr=Math.round(m+C*i.easing(bo)),ar=Math.round(w+E*i.easing(bo));Fe<O&&(cr!==e||ar!==o)?(h.scrollTo(cr,ar),V=requestAnimationFrame(te)):(h.scrollTo(e,o),cancelAnimationFrame(V),re(),Rn.remove(h.element,!1),A(!0))};V=requestAnimationFrame(te)})}function So(n,t,e){return n.left<=t&&t<=n.right&&n.top<=e&&e<=n.bottom}function J9(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 Hf(n){if(!/["'&<>]/.exec(n))return n;const o={'"':""","'":"'","&":"&","<":"<",">":">"};return n.split("").map(l=>o[l]||l).join("")}function Ff(n){const t=document.getElementById(n);t&&t.remove()}function zf(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 Ei(n){const t="custom-cursor-style";if(n){const e=`body * { cursor: ${n} !important}`;zf(e,t)}else Ff(t)}const Uf=3,Vf=y("drag-drop");class qf{constructor(t){u(this,"dragStarted",!1);u(this,"mouseDownEvent",null);u(this,"_dragOffsetX",0);u(this,"_dragOffsetY",0);u(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()});u(this,"handleMouseMove",t=>{var i;t.preventDefault(),t.stopPropagation(),d(Vf,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:Uf;(Math.abs(e)>=r||Math.abs(o)>=r)&&this.onDragStart(this.mouseDownEvent)});u(this,"handleMouseUp",t=>{if(t.button===0){d(Vf,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&&Ei(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&&Ei(null),this.dragStarted&&this.options.onDragEnd(this,t,this.options.elem,e,o),this.unbindEvents(),this.dragStarted=!1}destroy(){this.unbindEvents(),this.untrackEvents()}}function qa(n){return new qf(n)}const X9=y("character");function Wf(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 Gf(n){const t=n.charAt(0);return t>="0"&&t<="9"}function Zf(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 tl(n){const t=[[9,13],[32],[160]];return Wf(n.charCodeAt(0),t)}function Yf(n){const t=[[12352,12687],[13056,13183],[13312,15661],[19968,40959],[63744,64255],[44032,55215]];return Wf(n.charCodeAt(0),t)}function Wa(n,t){let e=t;return d(X9,e.length===1,"invalid char length"),e==="]"&&(e="\\]"),e==="\\"&&(e="\\\\"),n.replace(new RegExp(`^[${e}]+|[${e}]+$`,"g"),"")}const On=navigator.userAgent;function Qf(){const n=navigator.userAgent.toLowerCase();return n.indexOf("safari")!==-1&&!(n.indexOf("chrome")>-1)}function Ga(){return navigator.userAgent.toLowerCase().indexOf("firefox")>-1}const St={isAndroid:!!On.match(/Android/i),isIOS:!!On.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/i),isIPad:!!On.match(/iPad/i),isIPhone:!!On.match(/iPhone/i),isLinux:!!On.match(/Linux/i),isMac:!!On.match(/Macintosh/i),isMobile:!!On.match(/AppleWebKit.*Mobile.*/i),isWindows:!!On.match(/Window/i),isIe:!!On.match(/msie|trident/i),isSafari:Qf(),isMobileSafari:!1};St.isMobileSafari=St.isMobile&&St.isSafari;function Za(n){return n?n.length===1||n==="Process"||n==="Unidentified"&&St.isAndroid:!1}function Kf(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 t7(n){return Kf(n.key)}function e7(n){switch(n){case"ArrowUp":case"ArrowLeft":case"Home":case"PageUp":return!0;default:return!1}}function To(n){return n.ctrlKey||n.altKey||n.shiftKey||n.metaKey}function n7(n){return n.key?!!(n.ctrlKey||n.metaKey||n.altKey):!1}function Jf(n){return St.isMac?n.metaKey&&!n.ctrlKey:!n.metaKey&&n.ctrlKey}function o7(n){return Jf(n)&&!n.altKey&&!n.shiftKey}function r7(n){return!n.metaKey&&!n.ctrlKey&&!n.shiftKey&&n.altKey}function Xf(n){return!To(n)&&n.key==="Enter"}function i7(n){return n.key==="Enter"&&n.shiftKey&&!n.altKey&&!n.ctrlKey&&!n.metaKey}function Ya(n){return!To(n)&&n.key==="Escape"}function s7(n){return!To(n)&&n.key==="Delete"}function tm(n){return!To(n)&&n.key==="Backspace"}function l7(n){return!To(n)&&n.key==="Tab"}function c7(n){return n.shiftKey&&n.key==="Tab"&&!n.ctrlKey&&!n.metaKey}function a7(n){if(!n)return"";if(St.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 em(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"?St.isMac?t.cmd=!0:t.ctrl=!0:r==="SPACE"?t.key=" ":t.key=r.substring(0,1)+r.substring(1).toLocaleLowerCase()}return t}function An(n,t){const e=em(t);return e.ctrl!==n.ctrlKey||e.alt!==n.altKey||e.shift!==n.shiftKey||St.isMac&&e.cmd!==n.metaKey?!1:e.key.length===1?e.key===n.key.toUpperCase():e.key.toUpperCase()===n.key.toUpperCase()}function Qa(n,t){return JC.stringifyUrl({url:n,query:t})}function Do(n){return typeof n=="string"?pi.Base64.encode(n,!0):pi.Base64.fromUint8Array(n,!0)}function el(n){return pi.Base64.decode(n)}function d7(n){return pi.Base64.toUint8Array(n)}function nm(n){return new Blob([pi.Base64.toUint8Array(n)])}const u7=eo.init([eo.classModule,eo.styleModule,eo.datasetModule,eo.attributesModule,eo.propsModule]);function Ii(n,t){const e=eo.toVNode(n),o=eo.toVNode(t);u7(e,o)}async function om(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 nl(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 h7(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 _n(n){let t=n;for(;t;){const e=window.getComputedStyle(t);if(/auto|scroll/i.test(e.overflowY))break;t=t.parentElement}return(!t||h7(t,"body"))&&(t=document.documentElement),t}function rm(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",rm,{passive:!1}),document.body.appendChild(t)}function sm(n){const t=document.querySelector(`.editor-disable-scroll[data-scroll-id="${n}"]`);t&&(t.removeEventListener("wheel",rm),t.remove())}function Ka(n,t,e){const o=new Blob([n]),r=new File([o],e,{type:t});return URL.createObjectURL(r)}function ol(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 lm(n){const t=document.createElement("div");return t.appendChild(n),t.innerHTML}function cm(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 rl(n,t){const o=(rl.canvas||(rl.canvas=document.createElement("canvas"))).getContext("2d");return o?(typeof t=="string"?t?o.font=t:o.font=cm(window.getComputedStyle(document.body)):t instanceof Element&&(o.font=cm(window.getComputedStyle(t))),o.measureText(n).width+4):200}const f7=y("editor-clipboard");async function m7(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 il(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 f7.error(t),!1}}function Lo(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 sl(n){return Array.isArray(n)?n.every(t=>t instanceof File):!1}function am(n){const t=n;if(!t)return"";const e=t.lastIndexOf(".");return e===-1?"":t.slice(e+1)}function ll(n,t){const e=document.createElement("a");e.setAttribute("download",`${t||""}`),e.setAttribute("href",`${n}`),e.click(),e.remove()}const dm=y("auto-scroll");function um(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 hm(n,{direction:t,step:e}){let o=null;const r=t==="left"||t==="right",i=()=>{if(!um(n,t))return dm.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 fm{constructor(t){u(this,"cancelScroll",null);u(this,"options");u(this,"scrollDomInfo");u(this,"scrolling",!1);u(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});u(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;dm.debug(`scroll direction: ${i}`),this.cancelScroll=hm(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 mm(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 Ja(n,t){let e=`${n}`;const o=t-e.length;for(let r=0;r<o;r++)e=`0${e}`;return e}const{t:Mo}=S;function Xa(n,t){const e=new Date(n).getTime()+864e5*t;return new Date(e)}function g7(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 p7(n,t){return Xa(n,t)}function td(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 gm(n){const t=new Date,e=new Date(n);return td(t,e)}function pm(n){const t=Xa(new Date,-1);return td(t,n)}function C7(n,t){return Math.round((n.getTime()-t.getTime())/864e5)}function Cm(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",Ja(r,2)),s=s.replace("dd",Ja(i,2)),s=s.replace("m",`${r}`),s=s.replace("d",`${i}`),s}return n.toLocaleDateString()}function ed(n,t){const e=new Date(n),o=new Date;if(e.getTime()-o.getTime()>10*1e3)return S.t("date.dateFromFuture");if(gm(e)){const i=(o.getTime()-n.getTime())/1e3;if(i<10*60)return Mo("date.dateJustNow");if(i<60*60)return Mo("date.dateMinutesAgo",{num:`${Math.floor(i/60)}`});const s=Math.floor(i/60/60);return s===1?Mo("date.date1HourAgo"):Mo("date.dateHoursAgo",{num:`${s}`})}if(pm(n))return Mo("date.dateYesterday");const r=Math.floor((o.getTime()-n.getTime())/1e3/24/60/60)+1;return r<14?Mo("date.dateDaysAgo",{num:`${r}`}):r<28?Mo("date.dateWeeksAgo",{num:`${Math.round(r/7)}`}):Cm(n,t)}function nd(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function b7(n,t,e){return n.replace(new RegExp(nd(t),"g"),e)}function v7(n,t,e){return n.replace(new RegExp(nd(t),"gi"),e)}const bm=y("container-children");function Ot(n){const t=Array.from(n.querySelectorAll(":scope > .container-blocks > div[data-type=editor-block]"));return d(bm,t.length>0,"container have not any child block"),t}function Kt(n){const t=n.querySelector(":scope > .container-blocks > div[data-type=editor-block]");return d(bm,t,"container have not any child block"),t}function Gt(n){const t=Ot(n);return t[t.length-1]}function Ve(n){return Ot(n).length}function fr(n,t){return Ot(n)[t]}const qe=y("block-dom");function mr(n){return n instanceof HTMLDivElement?n.getAttribute("data-type")==="editor-block":!1}function vm(n){M(n,"block-hidden")}function km(n){F(n,"block-hidden")}function cl(n){return!lt(n,"block-hidden")}function G(n){const{id:t}=n;return d(qe,t,"no block id"),t}function it(n){const t=n.getAttribute("data-block-type");return d(qe,t,"invalid block dom, no data-type"),t}function z(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 j(n){const t=n.closest("div[data-type=editor-container]");return d(qe,t,"failed to get block container"),t}function rt(n){const t=n.querySelector(":scope >div[data-type=block-content]");return d(qe,t,"no block content"),t}function At(n){let t=n.querySelector(":scope >div[data-type=block-tools]");return t||(t=b("div",[],n),t.setAttribute("data-type","block-tools")),d(qe,t,"no block tools"),t}function al(n){const t=n.querySelector(":scope >div[data-type=block-tools]");return t||null}function ym(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 wm(n,t,e){const o=n.editorDecorators.decorateBlock(t,e),{id:r,type:i}=o;d(qe,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&&M(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 no(n,t){const e=b(t,[],null);return e.setAttribute("data-type","block-content"),n&&n.appendChild(e),e}function Bm(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 xi(n){const t=n.getAttribute("data-box-type");return d(qe,t,"not a valid box element, no type"),t}function od(n){return n instanceof HTMLSpanElement?n.getAttribute("data-type")==="editor-box":!1}function Em(n){const{id:t}=n;return d(qe,t,"no box id"),t}function rd(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 Im(n){n.innerHTML="",b("span",["box-space-start"],n,ki);const t=b("span",[],n);return t.setAttribute("data-type","box-content"),b("span",["box-space-start"],n,ki),t}function id(n){const t=n.querySelector("span[data-type=box-content]");return d(qe,t,"invalid box dom, no content"),t}function xm(n,t){const e=b("span",[`${n}-insertion`],null);return e.setAttribute("data-type","editor-insertion"),e.setAttribute("data-insertion-id",t),e}function Sm(n,t){return n.rootContainer.querySelector(`[data-insertion-id=${t}]`)}function Tm(n){n.innerHTML="",b("span",["insertion-space-start"],n,ki);const t=b("span",[],n);return t.setAttribute("data-type","insertion-content"),b("span",["insertion-space-start"],n,ki),t}function sd(n){const t=n.querySelector("span[data-type=insertion-content]");return d(qe,t,"invalid insertion-child dom, no content"),t}function gt(n){let t=n.previousElementSibling;for(;t;){if(mr(t))return t;t=t.nextElementSibling}return null}function ht(n){let t=n.nextElementSibling;for(;t;){if(mr(t))return t;t=t.nextElementSibling}return null}function gr(n){let t=n.previousElementSibling;for(;t;){if(mr(t)&&cl(t))return t;t=t.previousElementSibling}return null}function pr(n){let t=n.nextElementSibling;for(;t;){if(mr(t)&&cl(t))return t;t=t.nextElementSibling}return null}function K(n){const t=j(n),o=Ot(t).indexOf(n);return d(qe,o!==-1,"invalid block & container dom, failed to get block index"),o}function ld(n){return!n||!(n instanceof Node)?!1:!!z(n)}function Si(n){if(!ld(n))return!1;const t=n,e=t instanceof Element?t:t.parentElement;return e?!!e.closest("div[data-type=block-tools]"):!1}const Dm=y("element");function cd(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 Cr(n,t){const e=n.rootElement.querySelector(`[data-container-id=${t}`);return d(Dm,e,`no container: ${t}`),e}function Lm(n,t){return n.rootElement.querySelector(`[data-container-id=${t}`)}function dl(n){const t=n.querySelector(":scope > .container-blocks");return d(Dm,t,"no container blocks element"),t}function k7(n){let t=n.querySelector(":scope > .container-tools");return t||(t=b("div",["container-tools"],n)),t}const Mm=y("container");function mn(n){return n.getAttribute("data-type")==="editor-container"}function Ct(n){return lt(n,"root")}function We(n){return lt(n,"child")}function U(n){const t=n.getAttribute("data-container-id");return d(Mm,t,"no id for container"),Ct(n)&&d(Mm,t==="root",`invalid root container id, : ${t}`),t}function Rm(n,t){const e=U(n);return t.getContainerBlocks(e)}const Om=y("block-path");function Ro(n){const t=[];let e=n;for(;e;){const o=j(e);if(t.unshift({containerId:U(o),blockIndex:K(e)}),Ct(o))return t;const r=z(o);d(Om,r,"no parent block"),e=r}return d(Om,!1,"no parent block"),[]}const y7=y("child-container-path");function Am(n){if(Ct(n))return[];const t=z(n);return d(y7,t,"no parent block"),Ro(t)}const _m=y("load-blocks");function ad(n,t,e){const o=U(t),r=Rm(t,n.doc);d(_m,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)}),dl(t).appendChild(i)}function w7(n,t,e){const o=dl(n),r=Ot(n);return d(_m,t>=0&&t<=r.length,"invalid block index"),t===r.length?o.appendChild(e):o.insertBefore(e,r[t]),e}function B7(n,t,e,o){const r=Am(t);r.push({containerId:U(t),blockIndex:e});const i=n.editorBlocks.createBlock(r,t,o);return w7(t,e,i),i}const Nm=y("root-container");class E7{constructor(t,e){u(this,"resizeObserver");u(this,"handleContextMenu",t=>{t.preventDefault()});u(this,"handleResize",()=>{try{this.editor.selection.updateSelection(null),this.editor.emit("resize",this.editor)}catch(t){Nm.warn(`failed to update selection while container resizing: ${t.message}`)}});u(this,"handleClick",t=>{var o,r;this.editor.emit("click",this.editor,t);const e=t.target;if(!Si(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&&vt(this.rootContainer,i)){const s=rd(i);if(s){const l=z(s);d(Nm,l,"no parent block"),(r=(o=this.editor.editorBoxes.getBoxClass(xi(s)))==null?void 0:o.handleClickBox)==null||r.call(o,this.editor,s,t)}}}});u(this,"handleDblClick",t=>{Si(t.target)||this.editor.selectionHandler.handleDblClick(t)});u(this,"handleMouseDown",t=>{const e=t.target;if(!!e&&e instanceof Node&&!Si(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)),St.isMobileSafari||(t.preventDefault(),this.editor.input.focus()),t.button===2&&t.stopPropagation()}});u(this,"handleMouseMove",t=>{this.editor.selectionHandler.handleMouseMove(t)});u(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=dl(this.rootContainer);e.innerHTML="",ad(this.editor,this.rootContainer,[]);const o=this.editor.findBlockById(t.start.blockId);if(o)this.editor.selection.selectBlock(o,0);else{const r=Kt(this.rootContainer);this.editor.selection.selectBlock(r,0)}}}function Pm(n){const t=cd(n.contentElement,"root","root");return n.rootContainer=t,ad(n,t,[]),new E7(n,t)}function $m(n,t,e,o){const r=Lm(n,o);if(r)return e.appendChild(r),r;const i=cd(e,"child",o);return ad(n,i,t),i}const jm=y("block-class");function kt(n,t){return n.editorBlocks.getBlockClass(it(t))}function Hm(n,t){const e=n.editorBlocks.getBlockClass(it(t));return d(jm,e.blockKind==="text",`is not a text block, ${e.blockType}`),e}function ye(n,t){const e=n.editorBlocks.getBlockClass(it(t));return d(jm,e.blockKind==="complex",`is not a text block, ${e.blockType}`),e}function br(n,t){return n.editorBlocks.getBlockClass(t)}const dd=y("block");function Z(n,t){return kt(n,t).getBlockTextLength(t)}function Fm(n){n.editorBlocks.forEach(t=>{t.clearSelection(n)})}function zm(n,t,e,o){kt(n,t).updateSelection(n,t,e,o)}function ul(n){for(;;){const t=j(n);if(Ct(t))return n;const e=z(t);d(dd,e,"no parent block exists for child container"),n=e}}function Um(n,t){const e=kt(n,t);if(!!e.getMinWidth)return e.getMinWidth(n,t)}function Vm(n,t,e){const o=kt(n,t);o.handleBlockElementUpdated&&o.handleBlockElementUpdated(n,t,e)}function hl(n,t,e,o){try{const r=br(n,e).convertFrom;return r?r(n,t,o):null}catch{return dd.debug(`unsupported block type: ${e}`),null}}function Oo(n,t,e){const o=kt(n,t);return o.getClientRects?o.getClientRects(n,t,e):[t.getBoundingClientRect()]}function I7(n,t){const e=kt(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(dd,s==="string"||s==="number"||s==="boolean","invalid style value")}),r}function qm(n,t){const e=n.getBoundingClientRect().width;return t.withPadding?e:e-Fa(n)}function ud(n,t){let e=Number.MAX_SAFE_INTEGER;const o=Ot(t);for(let i=0;i<o.length;i++){const s=o[i],l=Um(n,s);l&&(e=Math.min(e,l))}return e===Number.MAX_SAFE_INTEGER?void 0:e+Fa(t)}function H(n,t){return kt(n,t).blockKind==="text"}function Ti(n,t){return n.editorBlocks.getBlockClass(t).blockKind==="text"}function ct(n,t){return kt(n,t).blockKind==="complex"}function x7(n,t){return!ct(n,t)}function Ge(n,t){return kt(n,t).blockKind}function yt(n,t){return Ge(n,t)==="text"?Z(n,t)===0:!1}function hd(n,t){const e=Ot(t);return e.length!==1?!1:yt(n,e[0])}function Ze(n,t,e){return kt(n,t).getCaretRect(t,e)}function S7(n,t){var r,i;const e=kt(n,t);return(i=(r=e.getOptions)==null?void 0:r.call(e,n))!=null?i:{name:it(t)}}function Wm(n,t){var r;const e=kt(n,t);return(r=e.getBlockProperties)==null?void 0:r.call(e,n,t)}function fd(n,t){var i,s;const e=kt(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 Gm(n,t,e){var s,l,c,a;const o=kt(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 h of n.blockHooks){const f=(l=h.commands)==null?void 0:l.call(h,n,t);f&&(i[f.group]=f)}return(a=(c=i[e])==null?void 0:c.commands)!=null?a:[]}const Zm=y("embed-block-common");function De(n){return it(n)==="embed"}function Le(n){d(Zm,De(n),"not an embed block");const t=n.getAttribute("data-embed-type");return d(Zm,t,"no embed data type"),t}function T7(n,t){return n.editorEmbeds.getEmbedClass(Le(t))}function Ao(n,t){return n.editorEmbeds.getEmbedClass(t)}async function md(n,t,e,o,r){const i=Ao(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 D7(n,t,e,o,r){var l,c;const i=(c=(l=br(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 L7=y("execute-block-command");function Ym(n,t,e,o){var a;d(L7,De(t),"not a embed block");const r=Le(t),i=Ao(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 h of c)if(h[0]===e)return h[1].executeCommand(n,t,o)}function Qm(n,t,e,o){const r=fd(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 M7=y("complex-block-position");class Ye{constructor(t,e,o){u(this,"blockId");u(this,"childContainerId");u(this,"custom");t instanceof HTMLElement?this.blockId=G(t):(d(M7,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 R7=y("simple-block-position");class Ut{constructor(t,e,o){u(this,"blockId");u(this,"offset");u(this,"type");t instanceof HTMLElement?this.blockId=G(t):(d(R7,typeof t=="string",`not a valid block id: ${t}`),this.blockId=t),this.offset=e,this.type=o}isSimple(){return!0}}const gd=y("editor-position");function $(n,t,e){return new Ut(n,t,e)}function bt(n,t,e){return new Ye(n,t,e)}function vr(n){return n instanceof Ut}function pd(n){return n instanceof Ye}function Cd(n,t,e){if(vr(t)&&vr(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(gd,i!==s,"comparePosition: blocks are the same"),Xs(i,s)}if(pd(t)&&pd(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(gd,i!==s,"comparePosition: containers are the same"),Xs(i,s)}return d(gd,!1,"invalid "),0}const fl=y("simple-range");class se{constructor(t,e){u(this,"editor");u(this,"_anchor");u(this,"_focus");u(this,"reverse");this.editor=t,this._anchor=e.anchor,this._focus=e.focus,this.reverse=Cd(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 se))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(fl,e,"no start block"),d(fl,o,"no end block");const r=j(e),i=j(o);d(fl,r===i,"invalid range");const s=[];if(e===o)s.push({block:e,start:this.start,end:this.end});else{const l=K(e),c=K(o);d(fl,l<c,"invalid range, start > index"),s.push({block:e,start:this.start,end:$(e,Z(this.editor,e),"end")});const a=Ot(r);for(let h=l+1;h<c;h+=1){const f=a[h];s.push({block:f,start:$(f,0,"home"),end:$(f,Z(this.editor,f),"end")})}s.push({block:o,start:$(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 se(this.editor,this)}toDocRange(){return{anchor:this.anchor,focus:this.focus}}}y("unknown-block");function O7(n,t,e,o,r){M(o,"unknown-block");const i=no(o,"div");return i.innerText=`unknown block (${r.type}): ${JSON.stringify(r)}`,i}function A7(n){return 1}function _7(n,t,e,o){return null}function N7(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t))return null;const i=G(t),s=$(i,0,"home"),l=$(i,1,"end");return new se(n,{anchor:s,focus:l})}function P7(n,t){const o=rt(n).getBoundingClientRect();return new DOMRect(o.left+o.width/2,o.top,1,o.height)}function $7(n,t,e,o){M(t,"selected")}function j7(n){n.rootContainer.querySelectorAll("div.unknown-block[data-type=editor-block]").forEach(t=>{F(t,"selected")})}const H7={blockType:"unknown-block",blockKind:"embed",createBlockContent:O7,getBlockTextLength:A7,getRangeFromPoint:N7,moveCaret:_7,getCaretRect:P7,updateSelection:$7,clearSelection:j7},bd=y("editor-blocks");class Km{constructor(t){u(this,"blocks",new Map);this.editor=t}registerBlockClass(t){const e=t.blockType,o=this.blocks.get(e);d(bd,!o,`duplicated block type: ${e}`),this.blocks.set(e,t)}getBlockClass(t){const e=this.blocks.get(t);return d(bd,e,`unknown block type: ${t}`),e}hasBlock(t){return this.blocks.has(t)}createBlock(t,e,o){const r=wm(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&&(bd.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={...H7,blockType:t};return this.editor.editorBlocks.registerBlockClass(e),e}}const Jm=y("editor-embeds");class Xm{constructor(t){u(this,"objects",new Map);this.editor=t}registerEmbedClass(t){const e=t.embedType,o=this.objects.get(e);d(Jm,!o,`duplicated embed object type: ${e}`),this.objects.set(e,t)}getEmbedClass(t){const e=this.objects.get(t);return d(Jm,e,`unknown embed type: ${t}`),e}getEmbedClassFromBlock(t){return this.getEmbedClass(Le(t))}forEach(t){this.objects.forEach(t)}}const tg=y("embed-block");function F7(n,t,e,o,r){const i=no(o,"div");d(tg,r.type==="embed",`not an embed data: ${JSON.stringify(r)}`);const s=r;return d(tg,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 z7(n){return 1}function U7(n,t,e,o){return null}function V7(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t))return null;const i=G(t),s=$(i,0,"home"),l=$(i,1,"end");return new se(n,{anchor:s,focus:l})}function q7(n,t){const o=rt(n).getBoundingClientRect();return new DOMRect(o.left+o.width/2,o.top,1,o.height)}function W7(n,t,e,o){M(t,"selected")}function G7(n){n.rootContainer.querySelectorAll("div.embed-block[data-type=editor-block][data-block-type=embed]").forEach(t=>{F(t,"selected")})}function Z7(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 Y7(n,t,e,o){const r=Ao(n,t.embedType);return r.convertTo?r.convertTo(n,t,e,o):""}function Q7(n,t){const e=T7(n,t);return e.getBlockProperties?e.getBlockProperties(n,t):{}}function K7(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 J7(n,t,e,o){const r=Le(t),i=Ao(n,r);!i.handleDeleteBlock||i.handleDeleteBlock(n,t,e,o)}function X7(n,t,e){const o=Le(t),r=Ao(n,o);return r.handleUpdateBlock?r.handleUpdateBlock(n,t,e):!1}function t8(n,t,e,o,r){const i=Le(t),s=Ao(n,i);if(s.handleDropOver)return s.handleDropOver(n,t,e,o,r)}function e8(n,t,e,o,r){const i=Le(t),s=Ao(n,i);if(s.handleDrop&&n.isWritable())return s.handleDrop(n,t,e,o,r)}const eg={blockType:"embed",blockKind:"embed",createBlockContent:F7,getBlockTextLength:z7,getRangeFromPoint:V7,moveCaret:U7,getCaretRect:q7,updateSelection:W7,clearSelection:G7,convertFrom:Z7,convertTo:Y7,getBlockProperties:Q7,getOptions:K7,handleDeleteBlock:J7,handleUpdateBlock:X7,handleDropOver:t8,handleDrop:e8},le=y("complex-block-helper");function Me(n,t){return ye(n,t).getChildContainers(n,t)}function kr(n,t,e,o){return e.isSimple()?(d(le,o.isSimple(),"invalid start and end position"),Me(n,t)):(d(le,!e.isSimple(),"invalid start pos"),d(le,!o.isSimple(),"invalid end pos"),ye(n,t).getSelectedContainers(n,t,e,o))}function n8(n,t){if(K(t)!==0)return!1;const e=z(j(t));if(!e)return!1;d(le,ct(n,e),"not a complex block");const o=j(t),i=Me(n,e).indexOf(o);return d(le,i>=0,"not valid child container"),i===0}function vd(n,t){const e=Me(n,t);if(e.length===0)return null;const o=e[0],r=Kt(o);return ct(n,r)?vd(n,r):r}function yr(n,t){const e=Me(n,t);if(e.length===0)return null;const o=e[e.length-1],r=Gt(o);return ct(n,r)?yr(n,r):r}function ng(n,t){d(le,We(t),"not a child container");const e=z(t);d(le,e,"no parent block"),d(le,ct(n,e),"not a complex block");const o=Me(n,e),r=o.indexOf(t);if(d(le,r!==-1,"child container not found"),r===0){const l=gt(e);return l?ct(n,l)?yr(n,l):l:null}const i=o[r-1],s=Gt(i);return ct(n,s)?yr(n,s):s}function og(n,t){d(le,ct(n,t),"not a complex block");const e=Me(n,t);if(d(le,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],h=a.getBoundingClientRect();if(h.right<=i){l.push(a),i=h.left;continue}if(h.left>=s){s=h.right;continue}}return l}function rg(n,t){d(le,ct(n,t),"not a complex block");const e=Me(n,t);if(d(le,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],h=a.getBoundingClientRect();if(h.right<=i){l.push(a),i=h.left;continue}if(h.left>=s){s=h.right;continue}}return l}function ig(n,t,e,o){const r=t.getBoundingClientRect(),i=o<r.top,s=i?og(n,t):rg(n,t);let l=s[0],c=fn(l.getBoundingClientRect(),e,o);for(let a=1;a<s.length;a++){const h=s[a],f=h.getBoundingClientRect(),m=fn(f,e,o);m<c&&(l=h,c=m)}return i?Kt(l):Gt(l)}function ml(n,t,e,o){const r=G(t);d(le,r===e.blockId,"invalid start pos"),d(le,r===o.blockId,"invalid end pos");const i=ye(n,t);return i.adjustSelectionPos?i.adjustSelectionPos(n,t,e,o):{anchor:e,focus:o}}class Qe{constructor(t,e){u(this,"editor");u(this,"reverse");u(this,"_anchor");u(this,"_focus");this.editor=t,this._anchor=e.anchor,this._focus=e.focus,this.reverse=Cd(this.editor,this._anchor,this._focus)>0}isCollapsed(){return!1}isEqual(t){if(!(t instanceof Qe))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 kr(this.editor,t,this.start,this.end)}clone(){return new Qe(this.editor,this)}toDocRange(){return{anchor:this._anchor,focus:this._focus}}}const o8=y("selection-range");function Vt(n,t){const{anchor:e,focus:o}=t;return e instanceof Ut&&o instanceof Ut?new se(n,{anchor:e,focus:o}):(d(o8,e instanceof Ye&&o instanceof Ye,"start position type does not math end type"),new Qe(n,{anchor:e,focus:o}))}function Lt(n,t,e,o){const r=new Ut(t,e,"normal"),i=new Ut(t,o!=null?o:e,"normal");return Vt(n,{anchor:r,focus:i})}function r8(n){return!!n.anchor.childContainerId}function oo(n,t){var r,i;if(r8(t)){const s=bt(t.anchor.blockId,t.anchor.childContainerId,(r=t.anchor)==null?void 0:r.custom),l=bt(t.focus.blockId,t.focus.childContainerId,(i=t.focus)==null?void 0:i.custom);return Vt(n,{anchor:s,focus:l})}const e=$(t.anchor.blockId,t.anchor.offset,"normal"),o=$(t.focus.blockId,t.focus.offset,"normal");return Vt(n,{anchor:e,focus:o})}function kd(n,t){const e=[];return Ot(t).forEach(r=>{e.push(r),ct(n,r)&&Me(n,r).forEach(s=>{e.push(...kd(n,s))})}),e}function yd(n,t){let e=kd(n,n.rootContainer);return t!=null&&t.simpleBlockOnly&&(e=e.filter(o=>!ct(n,o))),e}function Ke(n,t){const e=n.selection.range.getSelectedBlocks(),o=[];for(const r of e)o.push(r),ct(n,r.block)&&kr(n,r.block,r.start,r.end).forEach(s=>{const c=kd(n,s).map(a=>({block:a,start:$(a,0,"home"),end:$(a,Z(n,a),"home")}));o.push(...c)});return t!=null&&t.simpleBlockOnly?o.filter(r=>!ct(n,r.block)):o}const KH="";function _o(n,t,e,o){const r=At(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}const Nn=y("text-block-child");function Di(n){return n.tagName==="SPAN"}function Re(n){return d(Nn,Di(n),"not a valid text child"),n.getAttribute("data-type")==="editor-box"}function Pn(n){return d(Nn,Di(n),"not a valid text child"),n.getAttribute("data-type")==="editor-insertion"}function Li(n){return!Re(n)&&!Pn(n)}function sg(n){return d(Nn,Di(n),"not a valid text child"),Re(n)?"box":Pn(n)?"insertion":"text"}function Oe(n){const t=sg(n);return t==="insertion"?0:t==="box"?1:(d(Nn,n.textContent!==null,"text block content is undefined"),d(Nn,n.textContent.length>=0,"text block content length is negative"),n.textContent.length)}function $n(n){const t=rt(n),e=Array.from(t.children);return e.forEach(o=>{d(Nn,Di(o),"not a valid text child")}),e}function gl(n,t){const e=$n(n);let o=0;for(let r=0;r<e.length;r++){const i=e[r],s=Oe(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(Nn,l>0,"invalid offset value"),d(Nn,!Re(i),"invalid box child"),{prev:i,next:i,offset:l}}d(Nn,!1,`invalid block child at position: ${t}`)}function Mi(n){const t=$n(n);let e=0;return t.forEach(o=>{e+=Oe(o)}),e}const lg=y("box");function wd(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 cg=y("rich-text-length");function Bd(n){return d(cg,typeof n.insert=="string","op.insert is not string"),n.insert.length}function ce(n){let t=0;return n.forEach(e=>{e.insert&&(d(cg,typeof e.insert=="string","op.insert is not string"),t+=Bd(e))}),t}const gn=y("split-text");function fe(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(gn,typeof i=="object",`invalid op type, ${typeof i}`),d(gn,typeof i.insert=="string",`invalid op.insert type, ${typeof i.insert}`);const s=Bd(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(gn,o+s>t,`invalid offset, ${o}, ${s}, ${t}`);const l=t-o,c=Y.default(i);d(gn,c.insert,"no copied.insert"),d(gn,typeof c.insert=="string","invalid copied.insert type"),c.insert=c.insert.substr(0,l),i.insert=i.insert.substr(l),c.insert===""&&d(gn,!1,"invalid copied.insert, is empty string"),i.insert===""&&d(gn,!1,"invalid op.insert, is empty string");const a=[i,...n.slice(r+1)],h=[...n.splice(0,r),c];return e&&(e.sourceOp=i),{left:h,right:a}}}}throw new Error(`invalid split offset: ${t}, ${JSON.stringify(n)}`)}function Jt(n,t,e){d(gn,t>=0,"invalid offset, < 0"),d(gn,e>0,"invalid length, <= 0"),d(gn,t+e<=ce(n),"invalid offset + length < text length");const{left:o,right:r}=fe(n,t+e),{left:i,right:s}=fe(o,t);return{left:i,middle:s,right:r}}function ag(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}=fe(r,s);r=l,o.unshift(c)}return r.length>0&&o.unshift(r),o}function dg(n,t,e){return Jt(n,t,e).middle}const wr=y("text-block-content");function i8(n,t,e,o,r){if(d(wr,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 h=ag(o,i);for(let f=0;f<h.length;f++){l(c,a);const m=h[f];a+=ce(m);for(let C=0;C<m.length;C++){const v=m[C];if(wd(v)){d(wr,v.attributes,`op is not an valid box: ${JSON.stringify(v)}`);const E=n.editorBoxes.createBox(e,v.attributes);d(wr,E instanceof HTMLSpanElement,`invalid box element: ${E.tagName}`),c.appendChild(E);continue}d(wr,v.insert,`no insert in op: ${JSON.stringify(v)}`);const w=b("span",["text"],c,v.insert);if(v.attributes){const E=n.editorBlockRenders.renderText(t,v.attributes);E.classes&&M(w,...E.classes),E.attributes&&Object.entries(E.attributes).forEach(([L,x])=>{w.setAttribute(L,x)}),E.styles&&Object.entries(E.styles).forEach(([L,x])=>{w.style.setProperty(L,x)})}c.appendChild(w)}}l(c,a),e.innerHTML="",e.appendChild(c)}function pl(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(wr,c.isSimple(),"not an simple position while compositing"),c.blockId===e&&s.set(c.offset,[{type:"inputting",id:N(),text:l}])}return i8(n,t,o,i,s)}function s8(n){const t=n.rootContainer.querySelectorAll('span[data-type="editor-insertion"].inputting-insertion');t.length&&wr.debug(`remove ${t.length} temp composition span`),Array.from(t).forEach(e=>e.remove())}const Zt=y("text-range");function l8(n,t){const e=(i,s)=>{if(Pn(i))return d(Zt,s===0,`invalid offset for insertion child: ${s}`),{child:i,container:i,offset:2};if(Re(i))return d(Zt,s===0||s===1,`invalid offset for box: ${s}`),{child:i,container:i,offset:s===0?1:2};const l=i.firstChild;return d(Zt,l,"no child node for text child"),d(Zt,l instanceof Text||l instanceof HTMLBRElement,`invalid child for text child, ${l.nodeName}`),l instanceof HTMLBRElement?(d(Zt,s>=0&&s<=0,"invalid offset for text child"),{child:i,container:l,offset:s}):(d(Zt,s>=0&&s<=l.data.length,"invalid offset for text child"),{child:i,container:l,offset:s})};let o=0;const r=$n(n);for(let i=0;i<r.length;i++){const s=r[i],l=Oe(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,Oe(s)));const a=r[i+1];return a&&c.push(e(a,0)),c}o+=l}d(Zt,!1,"failed to get range info")}function c8(n,t,e){if(t===e?d(Zt,Pn(n),"only insertion child can be zero offset"):d(Zt,t<e,`invalid start & end: ${t}, ${e}`),Pn(n)){d(Zt,t===e,`invalid insertion child range offset: ${t}, ${e}`),d(Zt,t===0,`invalid insertion child range start: ${t}`);const i=n;return d(Zt,i.children.length===3,`invalid insertion dom, children.length = ${i.children.length}`),Ks(i,1,i,2)}if(Re(n)){d(Zt,t+1===e,`invalid box child range offset: ${t}, ${e}`),d(Zt,t===0,`invalid box child range start: ${t}`);const i=n;return d(Zt,i.children.length===3,`invalid box dom, children.length = ${i.children.length}`),Ks(i,1,i,2)}const o=Oe(n);d(Zt,e<=o,`invalid child end: ${e}, ${o}`);const r=n.firstChild;return d(Zt,r instanceof Text,"invalid block text child"),d(Zt,r.data.length>=e,`invalid range end: ${e}, ${r.data.length}`),Ks(r,t,r,e)}const Je=y("caret-rect");function a8(n,t){if(od(t)){const e=t,o=id(e);if(e.getAttribute("data-box-type")==="br"){const r=rt(n),i=Number.parseFloat(window.getComputedStyle(r).lineHeight)||o.getBoundingClientRect().height,s=Array.from(o.getClientRects());d(Je,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 sd(t).getClientRects()}function Ae(n,t){var l,c;const e=l8(n,t.offset);if(e[1]&&e[0].child!==((l=e[1])==null?void 0:l.child)){if(t.type==="end"){const h=Io(e[0].child);return new DOMRect(h.right,h.top,1,h.height)}d(Je,e[1],"invalid ranges");const a=Js(e[1].child);return new DOMRect(a.left,a.top,1,a.height)}let r=e[0];if(d(Je,e.length>=1,"failed to get block range"),e.length===1)r=e[0];else{if(d(Je,e.length>=2,`invalid range info length: ${e.length}`),Pn(e[e.length-1].child)){r=e[e.length-1];const a=r.child,f=sd(a).getClientRects();d(Je,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"||Li(e[0].child)?r=e[0]:Li(e[1].child)&&(r=e[1])}if(r.container instanceof HTMLBRElement){d(Je,t.offset===0,"invalid offset for empty block text");const a=(c=r.container.parentElement)==null?void 0:c.parentElement;d(Je,a===rt(n),"invalid br parent, is not block parent");const h=a.getBoundingClientRect();return new DOMRect(h.left,h.top,1,h.height)}const s=_f(r.container,r.offset).getClientRects();if(s.length===0){d(Je,!Li(r.child),"only box or insertion child range has zero client rect"),d(Je,r.offset===1||r.offset===2,"invalid offset for box or insertion child");const a=r.child,h=a8(n,a);if(d(Je,h.length>=1,"no client rects for box content"),r.offset===1){const m=h[0];return new DOMRect(m.x,m.y,1,m.height)}const f=h[h.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(Je,s.length>0,"no client rects for range"),t.type==="home"?s[s.length-1]:s[0]}const pn=y("client-rects");function d8(n){const t=$n(n);let e=0;const o=[];for(let r=0;r<t.length;r++){const i=t[r],s=Oe(i);o.push({child:i,startBlockOffset:e,endBlockOffset:e+s}),e+=s}return o}function u8(n,t,e,o){d(pn,e<o,`invalid from & to: ${e}, ${o}`);const r=Z(n,t);d(pn,e>=0&&o>=0&&e<=r&&o<=r,`invalid offset: ${e}, ${o}, length: ${r}`);const i=d8(t),s=i.findIndex(C=>C.startBlockOffset<=e&&e<C.endBlockOffset),l=i.findIndex(C=>C.startBlockOffset<o&&o<=C.endBlockOffset);if(d(pn,s!==-1,"failed to find start child"),d(pn,l!==-1,"failed to find end child"),d(pn,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],h={child:a.child,startChildOffset:e-a.startBlockOffset,endChildOffset:Oe(a.child)};c.push(h);for(let C=s+1;C<l;C++){const v=i[C],w={child:v.child,startChildOffset:0,endChildOffset:v.endBlockOffset-v.startBlockOffset};c.push(w)}const f=i[l],m={child:f.child,startChildOffset:0,endChildOffset:o-f.startBlockOffset};return c.push(m),c}function h8(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 ug(n,t,e,o){if(Z(n,t)===0){const h=rt(t).getBoundingClientRect();return[new DOMRect(h.left,h.top,4,h.height)]}const r=e.offset,i=o.offset;if(r===i)return[Ae(t,e)];const l=u8(n,t,r,i).map(a=>c8(a.child,a.startChildOffset,a.endChildOffset)),c=[];return l.forEach(a=>{const h=h8(Array.from(a.getClientRects()));c.push(...h)}),c}function f8(n,t,e){d(pn,e instanceof se,"invalid range");const o=e.start,r=e.end;return d(pn,o.isSimple(),"text block only allow simple position"),d(pn,r.isSimple(),"text block only allow simple position"),d(pn,o.blockId===r.blockId,"only allow update one text block selection"),d(pn,o.blockId===G(t),"only allow update one text block selection"),ug(n,t,o,r)}const Ed=y("selection-background");function m8(n,t,e,o){d(Ed,e.isSimple(),"text block only allow simple position"),d(Ed,o.isSimple(),"text block only allow simple position"),d(Ed,e.blockId===o.blockId,"only allow update one text block selection");const r=e.offset,i=o.offset;if(r===i&&(Z(n,t)!==0||n.selection.range.isCollapsed()))return;const s=ug(n,t,e,o),l=t.getBoundingClientRect(),c=ym(t);c.innerHTML="",s.forEach(a=>{const h=b("div",["editor-selection-background"],c);h.style.left=`${a.left-l.left}px`,h.style.top=`${a.top-l.top}px`,h.style.width=`${a.width}px`,h.style.height=`${a.height}px`})}function g8(n){n.rootContainer.querySelectorAll("div[data-type=block-background]").forEach(t=>{t.remove()})}const No=y("text-offset"),hg="\u200D";function Br(n,t){const e=$n(n);let o=0;for(let r=0;r<e.length;r++){const i=e[r],s=Oe(i);if(i===t){const l=o+s;return{start:o,end:l}}o+=s}d(No,!1,"can not find child in children")}function me(n,t){d(No,t>=0,`invalid offset: ${t}`);const e=gl(n,t),{prev:o,next:r,offset:i}=e;if(!o&&!r&&d(No,!1,"invalid offset, no prev & next child at offset"),o!==r)return!0;const s=o;if(d(No,s,"no child"),Re(s))return d(No,i===0||i===1,`invalid box child offset: ${i}`),!0;const l=s.textContent;d(No,l,"no content for text child");const c=l.charAt(i-1),a=l.charAt(i);return!(c===hg||a===hg||Ha(l[i]))}function Po(n,t){if(t===0)return 0;const e=t-1;if(me(n,e))return e;let o=e-1;for(;!me(n,o);)o-=1;return o}function Er(n,t){const e=Mi(n);if(d(No,t>=0&&t<=e,`invalid offset: ${t}, ${e}`),t===e)return e;const o=t+1;if(me(n,o))return o;let r=o+1;for(;!me(n,r);)r+=1;return r}const $o=y("line-breaker");function Ri(n){const t=c=>{const a=Js(c);return Io(c).top>a.top+a.height/2},e=(c,a)=>{const h=Io(c);return Js(a).left<h.right},o=(c,a)=>{const h=Io(c),f=Io(a);return f.top+f.height/2>h.bottom},r=c=>{if(c.length===0||c.length===1)return!1;const a=c[0],h=c[c.length-1];return a.right-h.left>10},i=[];let s=0;const l=$n(n);for(let c=0;c<l.length;c++){const a=l[c];if(Pn(a)){const E=a,L=l[c+1];if(!L)break;const x=l[c-1];if(x&&o(x,E)&&i.push({offset:s,type:"betweenChild",childInfo:{prevChild:x,nextChild:E,wrap:"nextWrapped",prevWrapped:t(x),nextWrapped:t(E)}}),e(E,L)){i.push({offset:s,type:"betweenChild",childInfo:{prevChild:x,nextChild:E,wrap:"nowrap",prevWrapped:t(x),nextWrapped:t(E)}});continue}continue}if(Re(a)){const E=a,L=l[c+1];if(!L)break;const x=l[c-1];if(x&&o(x,E)&&i.push({offset:s,type:"betweenChild",childInfo:{prevChild:x,nextChild:E,wrap:"nextWrapped",prevWrapped:t(x),nextWrapped:t(E)}}),e(E,L)){s+=1,i.push({offset:s,type:"betweenChild",childInfo:{prevChild:x,nextChild:a,wrap:"nowrap",prevWrapped:t(x),nextWrapped:t(a)}});continue}s+=1;continue}const h=a,f=h.getClientRects();if(d($o,f.length>0,"invalid text child dom"),f.length===1){const E=l[c+1];if(!E)break;if(e(h,E)){s+=Oe(h),i.push({offset:s,type:"betweenChild",childInfo:{prevChild:h,nextChild:E,wrap:"nowrap",prevWrapped:t(h),nextWrapped:t(E)}});continue}s+=Oe(h);continue}const m=h.firstChild;d($o,m,"invalid text child, no text node"),d($o,m instanceof Text,`invalid text child, not a valid text node: ${typeof m}`);const C=document.createRange(),v=document.createRange(),w=Oe(h);d($o,m.data.length===w,"text node data length not equal child text length");for(let E=0;E<m.data.length;E++){if(!me(n,s+E))continue;C.setStart(m,E),Ga()&&C.selectNodeContents(m);const L=C.getClientRects();if(d($o,L.length>=1,"invalid text node, no client rects"),r(L)){const V=s+E;i.push({offset:V,type:"textBreakWord",childInfo:{prevChild:a,nextChild:a,wrap:"nowrap",prevWrapped:t(a),nextWrapped:t(a)}});continue}let x=E+1;me(n,s+x)||(x=E+2),v.setStart(m,x);const O=v.getClientRects(),A=L[0];O[0].left<A.right&&d($o,!1,"span pre-wrap should not has a line-wrap by white space")}s+=w}return i}function Id(n,t){const e=Ri(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($o,t.offset<=Mi(n),"invalid position, offset > block length"),{lineIndex:e.length,lineBreaks:e}}const p8=y("line-offset");function xd(n){const t=Ri(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:Mi(n)}),e}function Cl(n,t){const e=xd(n);return d(p8,t>=0&&t<e.length,`invalid line index: ${t}, ${e.length}`),e[t]}function fg(n,t){const{lineIndex:e}=Id(n,t);return Cl(n,e)}function C8(n){const t=xd(n),e=n.getBoundingClientRect(),o=[];return t.forEach(({start:r,end:i})=>{const s=$(n,r,"home");let l=Ae(n,s);const c=$(n,i,"end"),a=Ae(n,c);l.top+l.height/2<a.top&&(l=new DOMRect(e.left-1e4,a.top,1,a.height));const h=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:h})}),o}function b8(n,t,e){const r=C8(n).find(s=>So(s.rect,t,e));if(!r)return null;const i=r.contentRect;return t-i.left<i.right-t?$(n,r.start,"home"):$(n,r.end,"end")}function mg(n,t,e){const o=Ae(n,t),r=Ae(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 gg(n){return xd(n).length}const jo=y("find-text-position");function pg(n,t){const{start:e,end:o}=Cl(n,t),r=G(n),i=Ae(n,$(r,e,"home"));if(!(Ae(n,$(r,o,"end")).top>i.top+i.height/2))return!1;const c=gl(n,e);return d(jo,c.next,"no next child at offset"),d(jo,!Li(c.next),"next child is not text child"),!0}function v8(n,t){const e=G(n);d(jo,pg(n,t),"line is not wrapped");const{start:o,end:r}=Cl(n,t),i=$(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=$(e,s,l);if(!mg(n,i,c))return s-1}return d(jo,!1,"failed to find wrapped offset"),0}function bl(n,t,e,o,r,i,s){d(jo,H(n,t),`not a text kind block: ${it(t)}`);const{start:l,end:c}=Cl(t,e);let a=l;const h=G(t);if(t===o&&pg(t,e)){const E=v8(t,e);(i==="up"||i==="down"&&mg(t,r,$(h,l,"home")))&&(a=E+1)}let f=Number.MAX_SAFE_INTEGER;const m=Ze(n,o,r),C=s!=null?s:m.left+m.width/2,v=m.top+m.height/2;let w=$(h,a,"home");for(let E=a;E<=c;E++){if(!me(t,E))continue;let L="normal";E===l?L="home":E===c&&(L="end");const x=$(h,E,L),O=Ae(t,x),A=fn(O,C,v);A<f&&(f=A,w=x)}return w}function k8(n,t,e,o,r){return d(jo,H(n,t),"not a text block"),bl(n,t,gg(t)-1,e,o,"up",r)}function y8(n,t,e,o,r){return d(jo,H(n,t),"not a text block"),bl(n,t,0,e,o,"down",r)}function w8(n,t,e,o){const{lineIndex:r}=Id(t,e);if(r===gg(t)-1)return null;const i=bl(n,t,r+1,t,e,"down",o);return i||null}function B8(n,t){if(t.offset===0)return null;const e=Ri(n),o=e.find(r=>r.offset===t.offset);if(!o){const r=Po(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:Po(n,t.offset),type:"normal"}}return{offset:Po(n,t.offset),type:"normal"}}function E8(n,t){const e=Mi(n);if(t.offset===e)return null;const o=Ri(n),r=o.find(i=>i.offset===t.offset);if(!r){const i=Er(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:Er(n,t.offset),type:"home"}:{offset:Er(n,t.offset),type:"normal"}}function I8(n,t,e,o){const{lineIndex:r}=Id(t,e);if(r===0)return null;const i=bl(n,t,r-1,t,e,"up",o);return i||null}const x8=y("move-caret");function S8(n,t,e,o){if(o==="ArrowLeft"){const r=B8(t,e);return r?$(G(t),r.offset,r.type):null}if(o==="ArrowRight"){const r=E8(t,e);return r?$(G(t),r.offset,r.type):null}if(o==="ArrowUp"){const r=I8(n,t,e,n.selection.getSuggestedCaretX());return r?$(G(t),r.offset,r.type):null}if(o==="ArrowDown"){const r=w8(n,t,e,n.selection.getSuggestedCaretX());return r?$(G(t),r.offset,r.type):null}d(x8,!1,`invalid navigation direction: ${o}`)}const Sd=y("text-range");function T8(n){const t=[];return $n(n).forEach(o=>{const r=Array.from(o.getClientRects()).map(i=>({rect:i,child:o}));t.push(...r)}),t}function D8(n,t,e){const o=T8(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 Br(n,s.child).start}return null}function L8(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 L=t.getBoundingClientRect();if(!So(L,e,o))return null;const x=D8(t,e,o);if(x!==null){const A=$(t,x,"normal");return new se(n,{anchor:A,focus:A})}const O=b8(t,e,o);return O?new se(n,{anchor:O,focus:O}):null}const s=$n(t);d(Sd,s.indexOf(i)!==-1,"failed to find child in children");const l=Br(t,i);d(Sd,l,"failed to get child offset");const{start:c}=l;let a,h;Pn(i)||Re(i)?(a=c,h=0):(d(Sd,i.firstChild instanceof Text,"child is not text"),a=c+Nf(i.firstChild,e,o),h=0);const f=G(t),C=Ri(t).find(L=>L.offset===a);let v="normal";if(C){const L=$(f,a,"home"),x=$(f,a,"end"),O=Ae(t,L),A=Ae(t,x),P=fn(O,e,o),V=fn(A,e,o);v=P<V?"home":"end"}const w=$(f,a,v);let E;return h&&(E=$(f,a+h,v)),new se(n,{anchor:w,focus:E!=null?E:w})}const M8=y("create-text-op");function _e(n,t){d(M8,n,"text is empty");const e={insert:n};return t&&Object.keys(t).length>0&&(e.attributes=t),e}function Td(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 vl=y("merge-ops");function Dd(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(vl,i.attributes===void 0,"op2.attributes is not undefined"),!0):(d(vl,r.attributes&&i.attributes,"op1.attributes && op2.attributes is undefined"),Zs.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(vl,typeof o.insert=="string","before.insert is not string"),d(vl,typeof i.insert=="string","op.insert is not string"),o.insert+=i.insert):(e.push(i),o=i)}return e}function R8(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 Cg=y("delete-text");function Ld(n,t,e){const{left:o,right:r}=Jt(n,t,e),i=[...o,...r];return Dd(i)}function bg(n,t){d(Cg,n>=0,`invalid offset: ${n}`),d(Cg,t>=1,`invalid delete count: ${t}`);const e=[];return n!==0&&e.push({retain:n}),e.push({delete:t}),e}const vg=y("delta");function kg(n,t){const e=new ne.default(n),o=new ne.default(t);return e.diff(o).ops}function O8(n,t,e){return new ne.default(t).transformPosition(n,!e)}function A8(n){d(vg,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 _8(n,t){const e=new ne.default(n),o=new ne.default(t);return e.compose(o).ops}class oe{static ensureValidText(t){d(vg,A8(t),`text is not a valid text, ${JSON.stringify(t)}`)}static diff(t,e){return this.ensureValidText(t),this.ensureValidText(e),kg(t,e)}static transformCursor(t,e,o){return O8(t,e,o)}static transformOffset(t,e,o){const r=kg(t,e),i=new ne.default(r);return o.map(s=>i.transformPosition(s))}static apply(t,e){this.ensureValidText(t);const o=_8(t,e);return this.ensureValidText(o),o}}const yg=y("insert-text");function Ir(n,t,e,o){d(yg,e,`invalid text to insert: ${e}`);const{left:r,right:i}=fe(n,t),s=typeof e=="string"?[_e(e,o)]:e,l=[...r,...s,...i];return Dd(l)}function wg(n){return{insert:" ",attributes:n}}function kl(n,t,e){if(d(yg,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
|
|
@@ -21,9 +21,9 @@ Available method signatures are:
|
|
|
21
21
|
`).map((r,i)=>{const l=i===0&&(t==null?void 0:t.firstLineAsTitle)?{heading:1}:void 0;return jn(r,l)})},meta:{},comments:{}}}function xl(n){const t=n.blocks.root;if(t.length!==1)return!1;const e=t[0];return!(!e.text||ce(e.text))}function Ag(n,t){const e=N();return n.localInsertChildContainer(e,t),e}function Cn(n,t){return Ag(n,[Il(t)])}function _g(n){return typeof n.offset=="number"}function Sl(n){return _g(n.anchor)}function Ng(n){return Sl(n)&&n.anchor.offset===n.focus.offset&&n.anchor.blockId===n.focus.blockId}function Pg(n,t){return{blockId:n,offset:t}}function Tl(n,t){const e=Pg(n,t);return{anchor:e,focus:e}}function $g(n,t){return{blockId:n,childContainerId:t}}function z8(n,t){const e=$g(n,t);return{anchor:e,focus:e}}const Dl=y("text-block");function U8(n,t,e,o,r){const{text:i}=r;d(Dl,i,"no text for text block");const s=no(o,"div");return o.classList.add("drag-preview-element"),pl(n,t,r.id,s,i),s}function V8(n,t,e){d(Dl,e,"no text to update");const o=no(null,"div");o.classList.add("drag-preview-element"),pl(n,Ro(t),G(t),o,e);const r=rt(t);Ii(r,o)}function q8(n,t,e){return f8(n,t,e)}function jg(n,t){let e="";return t.forEach(o=>{if(!!o.insert){if(o.attributes&&o.attributes.box===!0&&o.attributes.type==="math"){e+=`[${S.t("mathjax.abstract")}] `;return}e+=o.insert}}),e}function W8(n,t){d(Dl,H(n,t),"block in not textBlock");const e=n.selection.range;let o="";if(e.isCollapsed()){const r=n.getBlockText(t);o=jg(n,r)}else{const r=G(t),i=Ke(n,{simpleBlockOnly:!0}).find(s=>G(s.block)===r);if(i&&!yt(n,i.block)){d(Dl,i.block===t,"block not match");const s=n.getBlockText(t),{start:l,end:c}=i,a=l.offset,h=c.offset-a;if(h>0){const{middle:f}=Jt(s,a,h);o=jg(n,f)}}}return{abstract:o.trim()}}const Ai={blockType:"text",blockKind:"text",createBlockContent:U8,getBlockTextLength:Mi,getRangeFromPoint:L8,moveCaret:S8,updateSelection:m8,clearSelection:g8,getCaretRect:Ae,getClientRects:q8,setBlockText:V8,getBlockProperties:W8},G8=pl,Hg=y("text-box");function Z8(n,t,e,o){d(Hg,o.text,`no text for text box data: ${JSON.stringify(o)}`),d(Hg,typeof o.text=="string",`invalid text type for text box data: ${JSON.stringify(o)}`),b("span",[],e,o.text)}const Fg={boxType:"text",updateBoxContent:Z8},Y8="data:image/svg+xml;base64,Cjxzdmcgdmlld0JveD0iMCAwIDI0IDI0IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNMTguMjQ0NSA2QzE3LjgyNzQgNiAxNy41MzYzIDYuMjkxMTcgMTcuNTM2MyA2LjcwODI2QzE3LjUzNjMgNi45ODM3IDE3LjU1OTkgNy4yMzU1MyAxNy41NTk5IDcuNjEzMjdDMTcuNTU5OSAxMC4yODExIDE2LjYyMzQgMTEuMzc0OSAxMy45NzkyIDExLjM3NDlIOC45NDI2Nkw3LjEyNDc5IDExLjQ4NTFMOS41NDA3NSA5LjI4MTYyTDExLjE5MzQgNy41OTc1M0MxMS4zMjcxIDcuNDcxNjEgMTEuMzk4IDcuMjgyNzQgMTEuMzk4IDcuMDkzODdDMTEuMzk4IDYuNjkyNTIgMTEuMDk4OSA2LjQwMTM1IDEwLjY5NzYgNi40MDEzNUMxMC41MDg3IDYuNDAxMzUgMTAuMzM1NiA2LjQ3MjE4IDEwLjE3ODIgNi42MjE3TDUuMjQzOTYgMTEuNTQ4MUM1LjA4NjU3IDExLjcwNTUgNSAxMS44OTQzIDUgMTIuMDkxMUM1IDEyLjI4NzggNS4wODY1NyAxMi40NzY3IDUuMjQzOTYgMTIuNjI2MkwxMC4xNjI1IDE3LjUzNjhDMTAuMzM1NiAxNy43MDk5IDEwLjUwODcgMTcuNzgwOCAxMC42OTc2IDE3Ljc4MDhDMTEuMDk4OSAxNy43ODA4IDExLjM5OCAxNy40ODk2IDExLjM5OCAxNy4wODgzQzExLjM5OCAxNi44OTE1IDExLjMyNzEgMTYuNzEwNSAxMS4xOTM0IDE2LjU4NDZMOS41NDA3NSAxNC45MDA1TDcuMTMyNjYgMTIuNjk3TDguOTQyNjYgMTIuODA3MkgxNC4wNTc5QzE3LjU1OTkgMTIuODA3MiAxOSAxMS4yNDExIDE5IDcuNjc2MjJDMTkgNy4yMzU1MyAxOC45OTIxIDYuODY1NjUgMTguOTM3IDYuNjEzODNDMTguODc0MSA2LjI5OTA0IDE4LjY3NzMgNiAxOC4yNDQ1IDZaIiBmaWxsPSIjQjJCQ0NEIi8+Cjwvc3ZnPgo=";function Q8(n,t,e,o){Af(Y8,[],e),b("br",[],e)}const zg={boxType:"br",updateBoxContent:Q8},Ug=y("editor-boxes");class Vg{constructor(t){u(this,"boxes",new Map);this.editor=t}registerBoxClass(t){const e=t.boxType,o=this.boxes.get(e);d(Ug,!o,`duplicated box type: ${e}`),this.boxes.set(e,t)}getBoxClass(t){const e=this.boxes.get(t);return d(Ug,e,`unknown box type: ${t}`),e}createBox(t,e){const o=Bm(e),r=Im(o);return this.getBoxClass(e.type).updateBoxContent(this.editor,o,r,e),o}}function K8(n,t,e,o){b("span",[],e,o.text)}const qg={insertionType:"inputting",updateInsertionContent:K8},Wg=y("editor-insertion");class Gg{constructor(t){u(this,"insertions",new Map);this.editor=t}registerInsertionClass(t){const e=t.insertionType,o=this.insertions.get(e);d(Wg,!o,`duplicated insertion type: ${e}`),this.insertions.set(e,t)}getInsertionClass(t){const e=this.insertions.get(t);return d(Wg,e,`unknown insertion type: ${t}`),e}createInsertion(t,e){const o=xm(e.type,e.id),r=Tm(o);return this.getInsertionClass(e.type).updateInsertionContent(this.editor,o,r,e),o}}class J8{constructor(t){u(this,"cursors",new Map);u(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=Sm(this.editor,e);r&&F(r,"active"),this.cursors.delete(e)}})},1e3)}destroy(){clearInterval(this.timer)}}function X8(n,t,e,o){var l;const r=o;Date.now()-r.time<5*1e3&&(n.addCustom("active-cursors",a=>new J8(a)).add(r.id,r.time),M(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 Pd={insertionType:"remote-cursor",updateInsertionContent:X8};class Zg{constructor(t){u(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,h])=>{const f=r.get(a);f?f.push(...h):r.set(a,h)}),c&&(o=Y.default(c))}}}),{insertions:r,text:o}}}const tb=y("block-to-html");function $d(n,t,e){const o=br(n,t.type);if(o.convertTo)return o.convertTo(n,t,e,"html");if(o.blockKind!=="text")return`[${t.type}]`;d(tb,t.text,"no text");const r=wt(t.text);return`<div>${Hf(r)}</div>`}const eb=y("block-to-text");function Ll(n,t,e){const o=br(n,t.type);return o.convertTo?o.convertTo(n,t,e,"text"):o.blockKind!=="text"?`[${t.type}]`:(d(eb,t.text,"no text"),wt(t.text))}function Yg(n,t,e){const o=br(n,t.type);return o.convertTo?o.convertTo(n,t,e,"markdown"):Ll(n,t,e)}function Qg(n,t){return t.blocks.root.map(r=>$d(n,r,t)).join(`
|
|
22
22
|
`)}function nb(n,t){return`<!doctype html><html><head><meta charset="utf8" /></head><body>${Qg(n,t)}</body></html>`}function Kg(n,t){return t.blocks.root.map(r=>Ll(n,r,t)).join(`
|
|
23
23
|
`)}function ob(n,t){return t.blocks.root.map(r=>Yg(n,r,t)).join(`
|
|
24
|
-
`)}const Ml=y("action-helper");function io(n,t){const e=j(t),o=U(e),r=K(t);return n.doc.getBlockData(o,r)}function we(n,t){d(Ml,H(n,t),"not a text kind block");const o=io(n,t).text;return d(Ml,o,"no text in block"),o}function Rl(n,t,e){return fe(we(n,t),e).left}function Jg(n,t){const e=z(t);d(Ml,e,"no parent block");const o=we(n,e),r=Em(t),i=o.find(s=>{const l=s.attributes;return l?l.box&&l.id===r:!1});return d(Ml,i,"failed to find box"),i.attributes}const rb=y("get-text-position");function Sr(n,t){const e=t!=null?t:n.selection.range.start;e instanceof Ut||d(rb,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=K(r),s=j(r),l=U(s),{offset:c}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:c}}const _i=y("insert-text");function Xg(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(d(_i,r,"no block data"),d(_i,r.text,"no block text"),ce(r.text)===0)return d(_i,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=Jt(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function ib(n,t,e){const o=j(t),r=U(o),i=K(t);return Xg(n,r,i,e)}function tp(n,t,e,o,r){const i=j(t),s=U(i),l=K(t),c=ib(n,t,e),a=kl(e,o,c!=null?c:null);return n.doc.localUpdateBlockText(s,l,a,r),we(n,t)}function ep(n,t,e,o){const r=j(t),i=U(r),s=K(t),l=kl(e," ",o);return n.doc.localUpdateBlockText(i,s,l),we(n,t)}function jd(n,t,e,o,r){const i=n.doc.getBlockData(e,o);d(_i,i,"no block data"),d(_i,i.text,"no block text");const s=Xg(n,e,o,r),l=kl(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),we(n,n.getBlockById(i.id))}function Hd(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=Sr(n);jd(n,t,e,o,r)}const Ol=y("update-composition-text");function np(n){const t=n.selection.range.start;t instanceof Ut||d(Ol,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);d(Ol,H(n,o),"not a text kind block");const r=j(o),i=U(r),s=K(o),l=n.doc.getBlockData(i,s);d(Ol,l,"no block data in doc"),d(Ol,l.text,"no text data in text block");const c=rt(o);pl(n,Ro(o),e,c,l.text)}function op(n){s8(n)}function Tr(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const Al=y("delete-block-text");function Fd(n,t,e,o,r){d(Al,H(n,t),"block is not a text kind block");const i=j(t),s=U(i),l=K(t),c=n.doc.getBlockData(s,l);d(Al,c,"no block data in doc"),d(Al,c.text,"no text data in text block");let a=e;me(t,e)||(a=Po(t,a));let h=e+o;d(Al,h<=Z(n,t),`invalid offset and count: ${e}, ${o}`),me(t,h)||(h=Er(t,h));const f=h-a,m=bg(a,f);return n.doc.localUpdateBlockText(s,l,m,r),f}const zd=y("break-text-block");function rp(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Dr(n,t,e,o){d(zd,H(n,t),`block is not a text kind block: ${it(t)}`),d(zd,e>=0&&e<=Z(n,t),`invalid offset: ${e}`);const r=j(t),i=U(r),s=K(t),l=o!=null&&o.copyBlockAttributes?rp(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===Z(n,t))){const C=e===0?s:s+1,v={...jn(""),...l,...o==null?void 0:o.newBlockData},w=Lt(n,t.id,0),E=Tr(n,i,C,v,w);return{block:t,newBlock:E}}d(zd,me(t,e),"not a valid offset");const c=we(n,t),{right:a}=fe(c,e),h=ce(a);h>0&&Fd(n,t,e,h);const f={...jn(a),...l,...o==null?void 0:o.newBlockData},m=Tr(n,i,s+1,f,Lt(n,f.id,0));return{block:t,newBlock:m}}const sb=y("prepare-insert-new-block");function lb(n,t,e){if(t&&e!==void 0&&e!==null){const a=n.getContainerById(t),h=Ot(a);return d(sb,e>=0&&e<=h.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(j(r)),e=K(r),!H(n,r))return{containerId:t,blockIndex:e+1};const s=o.offset;if(s===0||s===Z(n,r))return{containerId:t,blockIndex:s===0?e:e+1};const c=Dr(n,r,s).newBlock;return{containerId:t,blockIndex:K(c)}}const cb=y("auto-insert-block");function ip(n,t,e,o,r,i){const s=lb(n,e,o);d(cb,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},c={anchor:l,focus:l};return Tr(n,s.containerId,s.blockIndex,t,r!=null?r:c,i)}const sp=y("range-in-block");function lp(n,t){const e=t.getEditor(),o=e.getBlockById(t.start.blockId),r=e.getBlockById(t.end.blockId),i=o===n||vt(n,o),s=r===n||vt(n,r);return!!(i||s)}function cp(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(G(i));)i=gt(i);d(sp,i,"no prev block while deleting a block"),r=Lt(n,i,Z(n,i))}else{const s=ht(t);d(sp,s,"no prev and next block while deleting a block"),r=Lt(n,s,0)}return r}const ab=y("delete-block");function _l(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{_l(n,i,e)})}))}function Ud(n,t,e){const o=j(t),r=U(o),i=K(t),s=n.doc.getBlockData(r,i);return d(ab,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Vt(n,{anchor:e.start,focus:e.end})),s}function Vd(n,t,e){const o=j(t);Ve(o)===1&&n.insertTextBlock("",U(o),0);let r=e?oo(n,e):null;if(!r){const l=n.selection.range;lp(t,l)?r=cp(n,t):r=l}const i=Ud(n,t,r),s=[];return _l(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i}function db(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{_l(n,r,e)}),n.doc.localDeleteChildContainers(e)}function ap(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{_l(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const qd=y("merge-text-block");function dp(n,t,e){d(qd,H(n,t),"only text block can be merged"),d(qd,H(n,e),"only text block can be merged");const o=io(n,t),r=io(n,e),i=o.text,s=r.text;d(qd,i&&s,"block data has no text");const l=j(t),c=U(l),a=K(t),h=Z(n,t),f=jd(n,s,c,a,h),m=Lt(n,t,ce(i));return Vd(n,e,m),f}const bn=y("clear-selected-contents");function Nl(n,t){d(bn,H(n,t.block),"not a text kind block");const{start:e,end:o}=t;d(bn,e.isSimple(),"not a simple block position"),d(bn,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;d(bn,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function up(n,t,e){const o=U(t),r=Ot(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 ub(n,t){const{block:e,start:o,end:r}=t;if(H(n,e)){Nl(n,t);return}if(De(e)||o.isSimple()){d(bn,r.isSimple(),"invalid range");const s=j(e),l=K(e),c=n.insertTextBlock("",U(s),l);n.selection.selectBlock(c,0),n.deleteBlock(e);return}d(bn,ct(n,e),"invalid block kind"),d(bn,!o.isSimple()&&!r.isSimple(),"invalid range"),kr(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{up(n,s,{focus:l===0})})}function hb(n){const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(d(bn,e.length>0,"no selected block"),e.length===1){ub(n,e[0]);return}const o=e[0],r=o.block,i=j(r);d(bn,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(H(n,r)){Nl(n,o);const h=Lt(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(m=>n.deleteBlock(m.block)),H(n,l)){Nl(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(H(n,l)){Nl(n,s),e.slice(0,e.length-1).reverse().forEach(h=>n.deleteBlock(h.block)),n.selection.selectBlock(s.block,0);return}if(e.length===Ve(i)){up(n,i,{focus:!0});return}const c=gt(r),a=ht(l);d(bn,c||a,"no prev or next block"),e.forEach(h=>n.deleteBlock(h.block))}function Wd(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),hb(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}function hp(n,t,e){const o=j(t),r=U(o),i=K(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),we(n,t)}function fp(n,t,e){const o=n.getBlockText(t),r=oe.diff(o,e);hp(n,t,r)}function Pl(n,t,e){const o=we(n,t),r=typeof e=="string"?Oi(e):e,i=oe.diff(o,r);return hp(n,t,i)}const Ni=y("update-block-data");function $l(n,t,e,o){const r=j(t),i=U(r),s=K(t),l=n.doc.getBlockData(i,s),c={insert:{},delete:[]},a=new Set(Object.keys(l)),h=new Set(Object.keys(e));return a.forEach(m=>{if(!h.has(m)){if(m==="id"||m==="type"||m==="text")return;Ni.debug(`delete key: ${m}`),c.delete.push(m)}}),Object.entries(e).forEach(([m,C])=>{d(Ni,m!=="id"&&m!=="type",`invalid block data delta, ${m}`);const v=l[m];if(C==null){v!=null&&(Ni.debug(`delete key: ${m}`),c.delete.push(m));return}v!==C&&(Zs.default(v,C)||m==="text"&&oe.diff(v,C).length===0||(a.has(m)?(Ni.debug(`replace key: ${m}`),c.delete.push(m)):Ni.debug(`insert key: ${m}`),c.insert[m]=C))}),n.doc.localUpdateBlockData(i,s,c,o),io(n,t)}function mp(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function Gd(n,t,e){if(!ct(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=ye(n,t).getChildContainers(n,t)[0],i=Kt(r);Gd(n,i,e)}function Ho(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 jl=y("clone-block");function Fo(n,t,e,o){const r=n.getBlockClass(e.type);if(r.blockToDoc)return r.blockToDoc(t,e,(h,f)=>(d(jl,e!==f,"invalid child block"),Fo(n,h,e,o)));let i={};const s=new Map,l=Y.default(e);l.children&&(l.children=l.children.map(h=>{const f=N(),m=t.blocks[h];d(jl,Array.isArray(m),"invalid child blocks");const C=m.map(D=>Fo(n,t,D,o)),v=Ho(C),{root:w,...E}=v.blocks;return i={...i,...E},i[f]=v.blocks.root,s.set(h,f),f}));const c=Array.from(s.entries()),a=h=>{for(const f of c){const[m,C]=f,v=`${m}/`;if(h.startsWith(v)){const w=h.substring(v.length),E=`${C}/${w}`;return jl.debug(`replace key: ${h} -> ${E}`),E}}return h};return Array.from(Object.entries(l)).forEach(([h,f])=>{const m=a(h);m!==h&&delete l.key,l[m]=f}),l.id=N(),o&&(o.blockIdMap.set(e.id,l.id),s.forEach((h,f)=>o.containerIdMap.set(f,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function Zd(n,t,e,o){const r=t.blocks[e];d(jl,Array.isArray(r),"invalid child blocks");const i=r.map(l=>Fo(n,t,l,o));return Ho(i)}function Yd(n,t,e){const o=t.blocks.root.map(r=>Fo(n.editorBlocks,t,r,e));return Y.default(Ho(o))}const gp=y("insert-doc");function pp(n,t,e,o,r){if(ct(n,t)){gp.warn("failed to insert doc into a complex block");return}const i=Yd(n,o,r),s=j(t),l=K(t),c=U(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var x,A,O;Object.entries(i.blocks).forEach(([P,V])=>{P!=="root"&&n.doc.localInsertChildContainer(P,V)});const a=i.blocks.root;if(De(t)){n.deleteBlock(t);let P;a.reverse().forEach(V=>{const nt=n.insertBlock(c,l,V);P||(P=nt)}),P&&n.selection.selectBlock(P,Z(n,P));return}if(d(gp,H(n,t),"not a text block"),yt(n,t)){const P=K(t);let V;a.forEach((nt,ot)=>{const ut=n.insertBlock(c,P+ot,nt);ot===a.length-1&&(V=ut)}),V&&n.selection.selectBlock(V,Z(n,V));return}if(a.length===1){const P=a[0];if(Ti(n,P.type)){n.insertTextToBlock(t,e,(x=P.text)!=null?x:[]);return}n.breakTextBlock(t,e),n.insertBlock(c,l+1,P);return}const h=e===Z(n,t),f=e===0,m=a[0],C=a[a.length-1];let v;!h&&!f?v=n.breakTextBlock(t,e,{forceInsertAfter:!0}):v=t;const w=f?l:l+1;h?(v=n.insertBlock(c,l+1,C),n.selection.selectBlock(v,Z(n,v))):(n.selection.selectBlock(v,0),Ti(n,C.type)?n.insertTextToBlock(v,0,(A=C.text)!=null?A:[]):n.insertBlock(c,w,C));const E=n.selection.range;let D=w;Ti(n,m.type)?f?(n.insertBlock(c,w,m),D+=1):n.insertTextToBlock(t,e,(O=m.text)!=null?O:[]):(n.insertBlock(c,w,m),D+=1),a.slice(1,a.length-1).reverse().forEach(P=>{n.insertBlock(c,D,P)}),n.selection.setRange(E)}),n.doc.endBatchUpdate()}function Qd(n,t,e,o,r){const i=Yd(n,o,r),s=U(t),l=[];return n.undoManager.runInGroup(()=>{Object.entries(i.blocks).forEach(([a,h])=>{a!=="root"&&n.doc.localInsertChildContainer(a,h)}),i.blocks.root.reverse().forEach(a=>{const h=n.insertBlock(s,e,a);l.push(h)})}),l}function Cp(n,t,e){const o=Ve(t);Qd(n,t,o,e);for(let r=0;r<o;r++){const i=Kt(t);n.deleteBlock(i)}}const Pi=y("add-text-attribute");function fb(n,t,e,o){const{start:r,end:i}=e;d(Pi,r.blockId===i.blockId&&r.blockId===G(t),"invalid range"),d(Pi,o,"invalid attribute name");const s=n.getBlockText(t),l=xr(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function bp(n,t,e,o,r){const{start:i,end:s}=e;d(Pi,i.blockId===s.blockId&&i.blockId===G(t),"invalid range"),d(Pi,o,"invalid attribute name");const l=n.getBlockText(t),c=wl(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,c),c}function Lr(n,t,e,o,r){const{start:i,end:s}=e;d(Pi,i.blockId===s.blockId&&i.blockId===G(t),"invalid range");const l=n.getBlockText(t),c=Sg(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,c),c}function vp(n,t,e,o){const r=Ke(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:c}=i;if(!H(n,s))return;if(yt(n,s)){o(n,G(s),t,e);return}const a=Vt(n,{anchor:l,focus:c});t==="color"||t==="backgroundColor"?Lr(n,s,a,t,e):(Lr(n,s,a,"color",null),Lr(n,s,a,"backgroundColor",null))})})}function kp(n,t,e){const o=Ke(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!H(n,i))return;if(yt(n,i)){(t==="clearColor"||t==="clearAll")&&e(n,G(i),"color",null),(t==="clearBackground"||t==="clearAll")&&e(n,G(i),"backgroundColor",null);return}const c=Vt(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&Lr(n,i,c,"color",null),(t==="clearBackground"||t==="clearAll")&&Lr(n,i,c,"backgroundColor",null)})})}function Kd(n,t){const e=Ke(n,{simpleBlockOnly:!0}).filter(s=>H(n,s.block));if(e.length===0)return[null,null];const o=s=>{if(Z(n,s.block)===0)return t(n,G(s.block));const l=s.start,c=s.end,a=n.getBlockText(s.block);return Lg(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])}function yp(n){let t=Gt(n.rootContainer);if(ct(n,t)){const e=yr(n,t);e&&(t=e)}n.selection.selectBlock(t,Z(n,t))}function wp(n){yp(n),n.focus()}const Jd=y("selected-block-to-doc");function Bp(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{Bp(n,i,e)}),e.blocks[o]=Y.default(r)})}function Hl(n,t,e={ignoreLockInfo:!0}){const o=kt(n,t.block);if(o.selectionToDoc)return o.selectionToDoc(n,t);const r=Y.default(io(n,t.block));if(!e.ignoreLockInfo&&r.lock&&delete r.lock,H(n,t.block)){const s=t.start,l=t.end;if(d(Jd,r.text,"no block text"),s.offset===l.offset)return{blocks:{root:[{...r,text:[]}]},meta:{},comments:{}};const{middle:c}=Jt(r.text,s.offset,l.offset-s.offset);return{blocks:{root:[{...r,text:c}]},meta:{},comments:{}}}if(De(t.block))return{blocks:{root:[r]},meta:{},comments:{}};d(Jd,ct(n,t.block),"not complex block"),d(Jd,r.children,"no children");const i={blocks:{root:[r]},meta:{},comments:{}};return Bp(n,r,i),i}function Xd(n,t,e=!0){const o=$(t,0,"normal"),r=$(t,Z(n,t),"end");return Hl(n,{block:t,start:o,end:r},{ignoreLockInfo:e})}const mb=y("block-to-doc");function gb(n,t){d(mb,t.length>0,"invalid params, no blocks");const e=t.map(o=>Xd(n,o));return Ho(e)}function Fl(n){const e=n.selection.range.getSelectedBlocks().map(o=>Hl(n,o));return Ho(e)}function tu(n,t){const e=n.getContainerById(t),i=Ot(e).map(s=>({start:$(s,0,"home"),end:$(s,Z(n,s),"end"),block:s})).map(s=>Hl(n,s));return Ho(i)}function Ep(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=>{Ep(n,l,e)})})}function pb(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)}):Ep(t,r,e)}),Array.from(e)}function eu(n,t){return t.blocks.root.map(r=>$d(n,r,t)).join(`
|
|
24
|
+
`)}const Ml=y("action-helper");function io(n,t){const e=j(t),o=U(e),r=K(t);return n.doc.getBlockData(o,r)}function we(n,t){d(Ml,H(n,t),"not a text kind block");const o=io(n,t).text;return d(Ml,o,"no text in block"),o}function Rl(n,t,e){return fe(we(n,t),e).left}function Jg(n,t){const e=z(t);d(Ml,e,"no parent block");const o=we(n,e),r=Em(t),i=o.find(s=>{const l=s.attributes;return l?l.box&&l.id===r:!1});return d(Ml,i,"failed to find box"),i.attributes}const rb=y("get-text-position");function Sr(n,t){const e=t!=null?t:n.selection.range.start;e instanceof Ut||d(rb,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=K(r),s=j(r),l=U(s),{offset:c}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:c}}const _i=y("insert-text");function Xg(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(d(_i,r,"no block data"),d(_i,r.text,"no block text"),ce(r.text)===0)return d(_i,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=Jt(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function ib(n,t,e){const o=j(t),r=U(o),i=K(t);return Xg(n,r,i,e)}function tp(n,t,e,o,r){const i=j(t),s=U(i),l=K(t),c=ib(n,t,e),a=kl(e,o,c!=null?c:null);return n.doc.localUpdateBlockText(s,l,a,r),we(n,t)}function ep(n,t,e,o){const r=j(t),i=U(r),s=K(t),l=kl(e," ",o);return n.doc.localUpdateBlockText(i,s,l),we(n,t)}function jd(n,t,e,o,r){const i=n.doc.getBlockData(e,o);d(_i,i,"no block data"),d(_i,i.text,"no block text");const s=Xg(n,e,o,r),l=kl(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),we(n,n.getBlockById(i.id))}function Hd(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=Sr(n);jd(n,t,e,o,r)}const Ol=y("update-composition-text");function np(n){const t=n.selection.range.start;t instanceof Ut||d(Ol,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);d(Ol,H(n,o),"not a text kind block");const r=j(o),i=U(r),s=K(o),l=n.doc.getBlockData(i,s);d(Ol,l,"no block data in doc"),d(Ol,l.text,"no text data in text block");const c=rt(o);pl(n,Ro(o),e,c,l.text)}function op(n){s8(n)}function Tr(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const Al=y("delete-block-text");function Fd(n,t,e,o,r){d(Al,H(n,t),"block is not a text kind block");const i=j(t),s=U(i),l=K(t),c=n.doc.getBlockData(s,l);d(Al,c,"no block data in doc"),d(Al,c.text,"no text data in text block");let a=e;me(t,e)||(a=Po(t,a));let h=e+o;d(Al,h<=Z(n,t),`invalid offset and count: ${e}, ${o}`),me(t,h)||(h=Er(t,h));const f=h-a,m=bg(a,f);return n.doc.localUpdateBlockText(s,l,m,r),f}const zd=y("break-text-block");function rp(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Dr(n,t,e,o){d(zd,H(n,t),`block is not a text kind block: ${it(t)}`),d(zd,e>=0&&e<=Z(n,t),`invalid offset: ${e}`);const r=j(t),i=U(r),s=K(t),l=o!=null&&o.copyBlockAttributes?rp(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===Z(n,t))){const C=e===0?s:s+1,v={...jn(""),...l,...o==null?void 0:o.newBlockData},w=Lt(n,t.id,0),E=Tr(n,i,C,v,w);return{block:t,newBlock:E}}d(zd,me(t,e),"not a valid offset");const c=we(n,t),{right:a}=fe(c,e),h=ce(a);h>0&&Fd(n,t,e,h);const f={...jn(a),...l,...o==null?void 0:o.newBlockData},m=Tr(n,i,s+1,f,Lt(n,f.id,0));return{block:t,newBlock:m}}const sb=y("prepare-insert-new-block");function lb(n,t,e){if(t&&e!==void 0&&e!==null){const a=n.getContainerById(t),h=Ot(a);return d(sb,e>=0&&e<=h.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(j(r)),e=K(r),!H(n,r))return{containerId:t,blockIndex:e+1};const s=o.offset;if(s===0||s===Z(n,r))return{containerId:t,blockIndex:s===0?e:e+1};const c=Dr(n,r,s).newBlock;return{containerId:t,blockIndex:K(c)}}const cb=y("auto-insert-block");function ip(n,t,e,o,r,i){const s=lb(n,e,o);d(cb,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},c={anchor:l,focus:l};return Tr(n,s.containerId,s.blockIndex,t,r!=null?r:c,i)}const sp=y("range-in-block");function lp(n,t){const e=t.getEditor(),o=e.getBlockById(t.start.blockId),r=e.getBlockById(t.end.blockId),i=o===n||vt(n,o),s=r===n||vt(n,r);return!!(i||s)}function cp(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(G(i));)i=gt(i);d(sp,i,"no prev block while deleting a block"),r=Lt(n,i,Z(n,i))}else{const s=ht(t);d(sp,s,"no prev and next block while deleting a block"),r=Lt(n,s,0)}return r}const ab=y("delete-block");function _l(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{_l(n,i,e)})}))}function Ud(n,t,e){const o=j(t),r=U(o),i=K(t),s=n.doc.getBlockData(r,i);return d(ab,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Vt(n,{anchor:e.start,focus:e.end})),s}function Vd(n,t,e){const o=j(t);Ve(o)===1&&n.insertTextBlock("",U(o),0);let r=e?oo(n,e):null;if(!r){const l=n.selection.range;lp(t,l)?r=cp(n,t):r=l}const i=Ud(n,t,r),s=[];return _l(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i}function db(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{_l(n,r,e)}),n.doc.localDeleteChildContainers(e)}function ap(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{_l(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const qd=y("merge-text-block");function dp(n,t,e){d(qd,H(n,t),"only text block can be merged"),d(qd,H(n,e),"only text block can be merged");const o=io(n,t),r=io(n,e),i=o.text,s=r.text;d(qd,i&&s,"block data has no text");const l=j(t),c=U(l),a=K(t),h=Z(n,t),f=jd(n,s,c,a,h),m=Lt(n,t,ce(i));return Vd(n,e,m),f}const bn=y("clear-selected-contents");function Nl(n,t){d(bn,H(n,t.block),"not a text kind block");const{start:e,end:o}=t;d(bn,e.isSimple(),"not a simple block position"),d(bn,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;d(bn,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function up(n,t,e){const o=U(t),r=Ot(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 ub(n,t){const{block:e,start:o,end:r}=t;if(H(n,e)){Nl(n,t);return}if(De(e)||o.isSimple()){d(bn,r.isSimple(),"invalid range");const s=j(e),l=K(e),c=n.insertTextBlock("",U(s),l);n.selection.selectBlock(c,0),n.deleteBlock(e);return}d(bn,ct(n,e),"invalid block kind"),d(bn,!o.isSimple()&&!r.isSimple(),"invalid range"),kr(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{up(n,s,{focus:l===0})})}function hb(n){const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(d(bn,e.length>0,"no selected block"),e.length===1){ub(n,e[0]);return}const o=e[0],r=o.block,i=j(r);d(bn,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(H(n,r)){Nl(n,o);const h=Lt(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(m=>n.deleteBlock(m.block)),H(n,l)){Nl(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(H(n,l)){Nl(n,s),e.slice(0,e.length-1).reverse().forEach(h=>n.deleteBlock(h.block)),n.selection.selectBlock(s.block,0);return}if(e.length===Ve(i)){up(n,i,{focus:!0});return}const c=gt(r),a=ht(l);d(bn,c||a,"no prev or next block"),e.forEach(h=>n.deleteBlock(h.block))}function Wd(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),hb(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}function hp(n,t,e){const o=j(t),r=U(o),i=K(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),we(n,t)}function fp(n,t,e){const o=n.getBlockText(t),r=oe.diff(o,e);hp(n,t,r)}function Pl(n,t,e){const o=we(n,t),r=typeof e=="string"?Oi(e):e,i=oe.diff(o,r);return hp(n,t,i)}const Ni=y("update-block-data");function $l(n,t,e,o){const r=j(t),i=U(r),s=K(t),l=n.doc.getBlockData(i,s),c={insert:{},delete:[]},a=new Set(Object.keys(l)),h=new Set(Object.keys(e));return a.forEach(m=>{if(!h.has(m)){if(m==="id"||m==="type"||m==="text")return;Ni.debug(`delete key: ${m}`),c.delete.push(m)}}),Object.entries(e).forEach(([m,C])=>{d(Ni,m!=="id"&&m!=="type",`invalid block data delta, ${m}`);const v=l[m];if(C==null){v!=null&&(Ni.debug(`delete key: ${m}`),c.delete.push(m));return}v!==C&&(Zs.default(v,C)||m==="text"&&oe.diff(v,C).length===0||(a.has(m)?(Ni.debug(`replace key: ${m}`),c.delete.push(m)):Ni.debug(`insert key: ${m}`),c.insert[m]=C))}),n.doc.localUpdateBlockData(i,s,c,o),io(n,t)}function mp(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function Gd(n,t,e){if(!ct(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=ye(n,t).getChildContainers(n,t)[0],i=Kt(r);Gd(n,i,e)}function Ho(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 jl=y("clone-block");function Fo(n,t,e,o){const r=n.getBlockClass(e.type);if(r.blockToDoc)return r.blockToDoc(t,e,(h,f)=>(d(jl,e!==f,"invalid child block"),Fo(n,h,e,o)));let i={};const s=new Map,l=Y.default(e);l.children&&(l.children=l.children.map(h=>{const f=N(),m=t.blocks[h];d(jl,Array.isArray(m),"invalid child blocks");const C=m.map(L=>Fo(n,t,L,o)),v=Ho(C),{root:w,...E}=v.blocks;return i={...i,...E},i[f]=v.blocks.root,s.set(h,f),f}));const c=Array.from(s.entries()),a=h=>{for(const f of c){const[m,C]=f,v=`${m}/`;if(h.startsWith(v)){const w=h.substring(v.length),E=`${C}/${w}`;return jl.debug(`replace key: ${h} -> ${E}`),E}}return h};return Array.from(Object.entries(l)).forEach(([h,f])=>{const m=a(h);m!==h&&delete l.key,l[m]=f}),l.id=N(),o&&(o.blockIdMap.set(e.id,l.id),s.forEach((h,f)=>o.containerIdMap.set(f,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function Zd(n,t,e,o){const r=t.blocks[e];d(jl,Array.isArray(r),"invalid child blocks");const i=r.map(l=>Fo(n,t,l,o));return Ho(i)}function Yd(n,t,e){const o=t.blocks.root.map(r=>Fo(n.editorBlocks,t,r,e));return Y.default(Ho(o))}const gp=y("insert-doc");function pp(n,t,e,o,r){if(ct(n,t)){gp.warn("failed to insert doc into a complex block");return}const i=Yd(n,o,r),s=j(t),l=K(t),c=U(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var x,O,A;Object.entries(i.blocks).forEach(([P,V])=>{P!=="root"&&n.doc.localInsertChildContainer(P,V)});const a=i.blocks.root;if(De(t)){n.deleteBlock(t);let P;a.reverse().forEach(V=>{const nt=n.insertBlock(c,l,V);P||(P=nt)}),P&&n.selection.selectBlock(P,Z(n,P));return}if(d(gp,H(n,t),"not a text block"),yt(n,t)){const P=K(t);let V;a.forEach((nt,ot)=>{const ut=n.insertBlock(c,P+ot,nt);ot===a.length-1&&(V=ut)}),V&&n.selection.selectBlock(V,Z(n,V));return}if(a.length===1){const P=a[0];if(Ti(n,P.type)){n.insertTextToBlock(t,e,(x=P.text)!=null?x:[]);return}n.breakTextBlock(t,e),n.insertBlock(c,l+1,P);return}const h=e===Z(n,t),f=e===0,m=a[0],C=a[a.length-1];let v;!h&&!f?v=n.breakTextBlock(t,e,{forceInsertAfter:!0}):v=t;const w=f?l:l+1;h?(v=n.insertBlock(c,l+1,C),n.selection.selectBlock(v,Z(n,v))):(n.selection.selectBlock(v,0),Ti(n,C.type)?n.insertTextToBlock(v,0,(O=C.text)!=null?O:[]):n.insertBlock(c,w,C));const E=n.selection.range;let L=w;Ti(n,m.type)?f?(n.insertBlock(c,w,m),L+=1):n.insertTextToBlock(t,e,(A=m.text)!=null?A:[]):(n.insertBlock(c,w,m),L+=1),a.slice(1,a.length-1).reverse().forEach(P=>{n.insertBlock(c,L,P)}),n.selection.setRange(E)}),n.doc.endBatchUpdate()}function Qd(n,t,e,o,r){const i=Yd(n,o,r),s=U(t),l=[];return n.undoManager.runInGroup(()=>{Object.entries(i.blocks).forEach(([a,h])=>{a!=="root"&&n.doc.localInsertChildContainer(a,h)}),i.blocks.root.reverse().forEach(a=>{const h=n.insertBlock(s,e,a);l.push(h)})}),l}function Cp(n,t,e){const o=Ve(t);Qd(n,t,o,e);for(let r=0;r<o;r++){const i=Kt(t);n.deleteBlock(i)}}const Pi=y("add-text-attribute");function fb(n,t,e,o){const{start:r,end:i}=e;d(Pi,r.blockId===i.blockId&&r.blockId===G(t),"invalid range"),d(Pi,o,"invalid attribute name");const s=n.getBlockText(t),l=xr(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function bp(n,t,e,o,r){const{start:i,end:s}=e;d(Pi,i.blockId===s.blockId&&i.blockId===G(t),"invalid range"),d(Pi,o,"invalid attribute name");const l=n.getBlockText(t),c=wl(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,c),c}function Lr(n,t,e,o,r){const{start:i,end:s}=e;d(Pi,i.blockId===s.blockId&&i.blockId===G(t),"invalid range");const l=n.getBlockText(t),c=Sg(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,c),c}function vp(n,t,e,o){const r=Ke(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:c}=i;if(!H(n,s))return;if(yt(n,s)){o(n,G(s),t,e);return}const a=Vt(n,{anchor:l,focus:c});t==="color"||t==="backgroundColor"?Lr(n,s,a,t,e):(Lr(n,s,a,"color",null),Lr(n,s,a,"backgroundColor",null))})})}function kp(n,t,e){const o=Ke(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!H(n,i))return;if(yt(n,i)){(t==="clearColor"||t==="clearAll")&&e(n,G(i),"color",null),(t==="clearBackground"||t==="clearAll")&&e(n,G(i),"backgroundColor",null);return}const c=Vt(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&Lr(n,i,c,"color",null),(t==="clearBackground"||t==="clearAll")&&Lr(n,i,c,"backgroundColor",null)})})}function Kd(n,t){const e=Ke(n,{simpleBlockOnly:!0}).filter(s=>H(n,s.block));if(e.length===0)return[null,null];const o=s=>{if(Z(n,s.block)===0)return t(n,G(s.block));const l=s.start,c=s.end,a=n.getBlockText(s.block);return Lg(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])}function yp(n){let t=Gt(n.rootContainer);if(ct(n,t)){const e=yr(n,t);e&&(t=e)}n.selection.selectBlock(t,Z(n,t))}function wp(n){yp(n),n.focus()}const Jd=y("selected-block-to-doc");function Bp(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{Bp(n,i,e)}),e.blocks[o]=Y.default(r)})}function Hl(n,t,e={ignoreLockInfo:!0}){const o=kt(n,t.block);if(o.selectionToDoc)return o.selectionToDoc(n,t);const r=Y.default(io(n,t.block));if(!e.ignoreLockInfo&&r.lock&&delete r.lock,H(n,t.block)){const s=t.start,l=t.end;if(d(Jd,r.text,"no block text"),s.offset===l.offset)return{blocks:{root:[{...r,text:[]}]},meta:{},comments:{}};const{middle:c}=Jt(r.text,s.offset,l.offset-s.offset);return{blocks:{root:[{...r,text:c}]},meta:{},comments:{}}}if(De(t.block))return{blocks:{root:[r]},meta:{},comments:{}};d(Jd,ct(n,t.block),"not complex block"),d(Jd,r.children,"no children");const i={blocks:{root:[r]},meta:{},comments:{}};return Bp(n,r,i),i}function Xd(n,t,e=!0){const o=$(t,0,"normal"),r=$(t,Z(n,t),"end");return Hl(n,{block:t,start:o,end:r},{ignoreLockInfo:e})}const mb=y("block-to-doc");function gb(n,t){d(mb,t.length>0,"invalid params, no blocks");const e=t.map(o=>Xd(n,o));return Ho(e)}function Fl(n){const e=n.selection.range.getSelectedBlocks().map(o=>Hl(n,o));return Ho(e)}function tu(n,t){const e=n.getContainerById(t),i=Ot(e).map(s=>({start:$(s,0,"home"),end:$(s,Z(n,s),"end"),block:s})).map(s=>Hl(n,s));return Ho(i)}function Ep(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=>{Ep(n,l,e)})})}function pb(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)}):Ep(t,r,e)}),Array.from(e)}function eu(n,t){return t.blocks.root.map(r=>$d(n,r,t)).join(`
|
|
25
25
|
`)}function nu(n,t){return t.blocks.root.map(r=>Ll(n,r,t)).join(`
|
|
26
|
-
`)}function ou(n,t){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Do(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function ru(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=pb(n,t),r={};o.forEach(c=>{const a=n.doc.buildResourceUrl(c,{withToken:!0});r[c]=a}),t.meta={...e,resources:r}}function Cb(n,t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData||n.selection.range.isCollapsed())return;const e=Fl(n);ru(n,e);const o=eu(n,e),r=nu(n,e),i=ou(o,e);t.clipboardData.setData("text/html",i),t.clipboardData.setData("text/plain",r),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(e))}function bb(n){if(n.selection.range.isCollapsed())return;const t=Fl(n);ru(n,t);const e=eu(n,t),o=ou(e,t),r=new Blob([o],{type:"text/html"});il([{type:"text/html",data:r}])}async function iu(n,t){const e=Xd(n,t,!1);ru(n,e);const o=eu(n,e),r=nu(n,e),i=ou(o,e);return il([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}const su=y("editor-input");class vb{constructor(t,e){u(this,"editor");u(this,"composing",!1);u(this,"callbacks");u(this,"inputElement");u(this,"handleDocumentSelectionChange",()=>{setTimeout(()=>{var e;const t=(e=document.getSelection())==null?void 0:e.focusNode;t&&this.editor.contains(t)&&!Si(t)?(this.editor.emit("focus",this.editor),this.callbacks.onFocus(),this.editor.input.focus()):(this.editor.emit("blur",this.editor),this.callbacks.onBlur())},100)});u(this,"handleEditorSelectionChanged",()=>{const e=!this.editor.isWritable();this.inputElement.readOnly=e});u(this,"handleReadonlyChanged",()=>{this.handleEditorSelectionChanged()});u(this,"handleCompositionstart",t=>{this.composing=!0,this.callbacks.onCompositionStart(t)});u(this,"handleCompositionend",t=>{this.composing=!1,this.callbacks.onUpdateCompositionText(t,this.inputElement.value,!0),this.inputElement.value=""});u(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="")}});u(this,"handleKeyDown",t=>{if(!this.composing){if(this.callbacks.onKeyDown(t)){t.preventDefault(),t.stopPropagation();return}setTimeout(()=>{this.composing||(this.inputElement.value="")})}});u(this,"handleCopy",t=>{Cb(this.editor,t)});u(this,"handleCut",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}su.debug("on cut")});u(this,"handlePaste",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}this.callbacks.onPaste(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(),St.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(su,t===this.editor,"invalid editor"),this.callbacks.defaultInsertText(t,e,o,r,i)}defaultHandleKeydown(t,e){return d(su,t===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(t,e)}}function kb(n){const e=n.rootElement.getBoundingClientRect(),o=window.innerWidth,r=window.innerHeight,i=0-e.top+r/2,s=0-e.left+o/2,l=n.input.inputElement;l.style.left=`${s}px`,l.style.top=`${i}px`}const lu=y("editor-caret");class yb{constructor(t){u(this,"editor");u(this,"caretElem");u(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 Ut))return!1;const e=this.editor.getBlockById(t.blockId);return!!H(this.editor,e)}update(){if(Pf(this.editor.rootElement))return;const t=this.caretElem;if(this.hasCaret())t.style.display="";else{t.style.display="none",kb(this.editor);return}const{range:e}=this.editor.selection;d(lu,e.isCollapsed,"range is not collapsed");const o=e.start;d(lu,o instanceof Ut,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);d(lu,H(this.editor,r),"only text kind block can has caret");let i;const s=r.querySelector("span.inputting-insertion");s?(i=Io(s),i=new DOMRect(i.right,i.top,1,i.height)):i=Ae(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 h=this.editor.input.inputElement;h.style.left=`${c}px`,h.style.top=`${a+i.height-24}px`,St.isMobileSafari&&(h.style.left=`${c-4}px`,h.style.height=`${i.height}px`)}}function wb(n){Fm(n),n.selection.range.getSelectedBlocks().forEach(t=>zm(n,t.block,t.start,t.end))}function Ip(n){return _n(n.rootContainer).clientHeight}function Bb(n){return n.getFirstBlock().getBoundingClientRect().top}function Eb(n){return n.getLastBlock().getBoundingClientRect().bottom}function cu(n){const t=_n(n.rootContainer);return new DOMRect(t.clientLeft,t.clientTop,t.clientWidth,t.clientHeight)}function Ib(n,t){const e=cu(n),o=n.getBlockById(t.blockId),i=Ze(n,o,t);return So(e,i.x,i.y)&&So(e,i.right,i.bottom)}function xb(n,t){const e=cu(n),o=t.getBoundingClientRect();return o.top>=e.top&&o.top<=e.bottom||o.bottom<=e.bottom&&o.bottom>=e.top}function Sb(n,t){const e=cu(n),o=t.getBoundingClientRect();return So(e,o.x,o.y)||So(e,o.right,o.bottom)}function Tb(n){const t=n.selection,e=t.range.focus;if(!e.isSimple()){const a=e,h=n.getContainerById(a.childContainerId);Sb(n,h)||h.scrollIntoView();return}if(t.range.start.blockId===t.range.end.blockId){const a=n.getBlockById(t.range.start.blockId);if(De(a)&&xb(n,a))return}const o=e,r=n.getBlockById(o.blockId);if(Ib(n,o))return;const i=Ze(n,r,o),s=r.getBoundingClientRect(),l=At(r),c=b("div",["editor-block-anchor"],l);c.style.top=`${i.top-s.top}px`,Bi(c),setTimeout(()=>{c.remove()})}function Db(n,t){if(t.isCollapsed())return!1;const e=Kt(n.rootContainer),o=Gt(n.rootContainer),{start:r,end:i}=t;return r.blockId===G(e)&&r.offset===0&&i.blockId===G(o)&&i.offset===Z(n,o)}const zl=y("editor-selection");class Lb{constructor(t){u(this,"editor");u(this,"caret");u(this,"_range");u(this,"lastCaretRect");u(this,"handleBlockDelete",(t,e,o,r)=>{if(o||r.child)return;const i=this.range;if(lp(e,i)){zl.debug("adjust selection because remote deleted current block");const s=cp(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=G(e);this.caret=new yb(t);const r=$(o,0,"normal");this._range=Vt(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=$(t,e,"normal");let i;o&&(i=$(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=Vt(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),lt(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!Db(this.editor,r))&&F(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(),wb(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(!vr(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Ze(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){Tb(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=Z(this.editor,e)||d(zl,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||d(zl,!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&<(e,"focused")&&(F(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)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{F(t,"focused"),F(t,"child-focused")})}setBlockFocused(t){if(lt(t,"focused"))return!1;M(t,"focused");let e=j(t);for(;We(e);){const o=z(e);d(zl,o,"parent block not found"),M(o,"child-focused"),e=j(o)}return!0}}const xp=y("line-offset");function au(n){const t=n.selection.range.focus;d(xp,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!H(n,e))return $(e,0,"home");let r=fg(e,t).start;const{next:i}=gl(e,r);return i&&Re(i)&&xi(i)==="br"&&(r+=1),$(e,r,"home")}function du(n){const t=n.selection.range.focus;d(xp,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===Z(n,e)||!H(n,e))return $(e,0,"end");const o=fg(e,t);return $(e,o.end,"end")}function Mb(n){if(!n.selection.range.focus.isSimple())return;const e=au(n),o=du(n);!e||!o||n.selection.setSelection(e,o)}const Ne=y("block-text");function Sp(n,t,e){d(Ne,H(n,t),"not a text kind block"),d(Ne,me(t,e),"not a valid offset"),d(Ne,e>0&&e<=Z(n,t),`invalid offset: ${e}`);const o=Po(t,e),r=e-o;r===0&&d(Ne,!1,`no text before offset: ${e}`);const i=we(n,t),{middle:s}=Jt(i,o,r);d(Ne,s.length===1,"failed to split text to 3 parts");const l=s[0];return wd(l)?{op:l,charType:"box",offset:o,length:1}:{op:l,charType:tl(l.insert)?"space":"text",offset:o,length:l.insert.length}}function Tp(n,t,e){d(Ne,H(n,t),"not a text kind block"),d(Ne,me(t,e),"not a valid offset"),d(Ne,e>=0&&e<Z(n,t),`invalid offset: ${e}`);const r=Er(t,e)-e;r===0&&d(Ne,!1,`no text after offset: ${e}`);const i=we(n,t),{middle:s}=Jt(i,e,r);d(Ne,s.length===1,"failed to split text to 3 parts");const l=s[0];return wd(l)?{op:l,charType:"box",offset:e,length:1}:{op:l,charType:tl(l.insert)?"space":"text",offset:e,length:l.insert.length}}function Dp(n,t,e,o){let r=e;for(;r>0;){const i=Sp(n,t,r);if(i.charType!==o)return i;r-=i.length}return null}function Lp(n,t,e,o){const r=Z(n,t);let i=e;for(;i<r;){const s=Tp(n,t,i);if(s.charType!==o)return s;i+=s.length}return null}function Mp(n,t,e){if(d(Ne,H(n,t),"invalid blok type"),yt(n,t))return 0;const o=Sp(n,t,e);if(o.charType==="box")return e-1;let r=e;if(o.charType==="space"){const s=Dp(n,t,r,"space");if(!s||s.offset===0)return 0;if(s.charType==="box")return s.offset;r=s.offset}const i=Dp(n,t,r,"text");return i?i.offset+i.length:0}function Rp(n,t,e){if(d(Ne,H(n,t),"invalid blok type"),yt(n,t))return 0;const o=Tp(n,t,e);if(o.charType==="box")return e+1;let r=e;if(o.charType==="space"){const s=Lp(n,t,r,"space");if(!s||s.offset===0)return Z(n,t);if(s.charType==="box")return s.offset;r=s.offset}const i=Lp(n,t,r,"text");return i?i.offset:Z(n,t)}const Op=y("word-offset");function uu(n,t){const e=n.selection.range.focus;d(Op,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(yt(n,o))return $(o,0,"home");if(e.offset===0||!H(n,o)){const s=gt(o);if(!s)return null;const l=$(s,Z(n,s),"end");if(t==="select"&&H(n,s)){const c=Mp(n,s,l.offset);return $(s,c,"normal")}return l}const r=Mp(n,o,e.offset);return $(o,r,"normal")}function hu(n,t){const e=n.selection.range.focus;d(Op,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(yt(n,o))return $(o,0,"end");if(e.offset===Z(n,o)||!H(n,o)){const s=ht(o);if(!s)return null;const l=$(s,0,"home");if(t==="select"&&H(n,s)){const c=Rp(n,s,l.offset);return $(s,c,"end")}return l}const r=Rp(n,o,e.offset);return $(o,r,"normal")}function Rb(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!H(n,e))return;const o=uu(n,"select"),r=hu(n,"select");!o||!r||n.selection.setSelection(o,r)}const ge=y("adjust-selection-pos");function Ap(n){const t=[];for(;n;){const e=j(n);if(t.unshift(e),Ct(e))return t;const o=z(e);d(ge,o,"child container has not parent container"),n=o}d(ge,!1,"should not come here: getParentContainers")}function _p(n,t){for(;t;){const e=j(t);if(e===n)return t;const o=z(e);d(ge,o,"could not find parent block for a child container"),t=o}d(ge,!1,"no parent block in specified container")}function Ob(n,t){const e=Ap(n),o=Ap(t);d(ge,e.length>0&&o.length>0,"block has not parent container"),d(ge,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=_p(r,n),s=_p(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function Np(n,t){let e=z(t);for(d(ge,e,"element is not in a block");e;){const o=j(e);d(ge,We(o),"not a child container");const r=z(o);if(d(ge,r,"child container has not parent block"),r===n)return o;e=r}d(ge,!1,"failed to find parent container in complex block")}function Ul(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof Ut&&e instanceof Ut?{anchor:t,focus:e}:(d(ge,t instanceof Ye&&e instanceof Ye,"both start and end are not simple or complex"),ml(n,o,t,e));const i=j(o),s=j(r);if(i===s)return t instanceof Ye&&(t=$(o,0,"home")),e instanceof Ye&&(e=$(r,Z(n,r),"end")),d(ge,t instanceof Ut,"not valid position type"),d(ge,e instanceof Ut,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof Ut&&e instanceof Ye){const v=n.getContainerById(e.childContainerId);if(v===i)return{anchor:e,focus:e};const w=z(i);if(w&&w===z(v)){const E=bt(w,U(i)),D=bt(w,U(v));return ml(n,w,E,D)}}return null}const l=Xs(o,r)>0,{newBlock1:c,newBlock2:a}=Ob(o,r);if(c===a){const v=c,w=Np(v,o),E=Np(v,r);return t=bt(c,U(w)),e=bt(c,U(E)),ge.debug(`select in complex block: ${w.id}, ${E.id}`),ml(n,v,t,e)}let h=l?Z(n,c):0;c===o&&t instanceof Ut&&(h=t.offset);let m=l?0:Z(n,a);return a===r&&e instanceof Ut&&(m=e.offset),t=$(c,h,l?"end":"home"),e=$(a,m,l?"home":"end"),{anchor:t,focus:e}}const Ab=y("range-from-point");function Pp(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=z(i);if(!s||!n.contains(s))continue;const l=kt(n,s).getRangeFromPoint(n,s,t,e+o[r]);if(l)return l}return null}function $p(n,t,e,o){const r=t.getBoundingClientRect();if(o<=r.top){const l=Kt(t),c=$(l,0,"home");return new se(n,{anchor:c,focus:c})}const i=Gt(t),s=$(i,Z(n,i),"end");return new se(n,{anchor:s,focus:s})}function _b(n,t,e){const o=Pp(n,t,e);if(o){if(o instanceof se)return o;d(Ab,o instanceof Qe,`invalid range type: ${typeof o}`);const c=o,a=n.getContainerById(c.start.childContainerId);return $p(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=>mn(c));if(s.length===0)return null;const l=s.reduce((c,a)=>{const h=c.getBoundingClientRect(),f=a.getBoundingClientRect();return fn(h,t,e)>fn(f,t,e)?a:c});return $p(n,l,t,e)}class Nb{constructor(t){u(this,"editor");u(this,"startPos",null);u(this,"lastCaretRect");u(this,"mouseDownEvent",null);u(this,"handleMouseDown",t=>{this.mouseDownEvent=t;const e=_b(this.editor,t.x,t.y);if(e){if(e instanceof Qe)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()}});u(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=Pp(this.editor,t.x,t.y);if(!e)return;const o=Ul(this.editor,this.startPos,e.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});u(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){Rb(this.editor)}handleTripleClick(t){Mb(this.editor)}}const Pb=y("move-complex-block-position");function $b(n,t,e){const o=n.getBlockById(t.blockId);d(Pb,ct(n,o),"is not a complex block");const r=ye(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?bt(o,U(s)):null}const $i=y("move-simple-block-position");function jp(n,t){const e=Me(n,t);d($i,e.length>0,"complex block has not any child container");const o=e[0];return Kt(o)}function Hp(n,t){const e=Me(n,t);d($i,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Gt(o)}function Fp(n,t,e){const o=e?jp(n,t):Hp(n,t);return ct(n,o)?Fp(n,o,e):o}function jb(n,t){const e=n.getBlockById(t.blockId);return ct(n,e)&&t.offset===0?jp(n,e):pr(e)}function Hb(n,t){const e=n.getBlockById(t.blockId);return ct(n,e)&&t.offset===1?Hp(n,e):gr(e)}function fu(n){return n==="ArrowLeft"||n==="ArrowUp"}function mu(n,t,e){const o=j(t);if(Ct(o))return null;const r=z(o);d($i,r,"child container has not parent block"),d($i,ct(n,r),"is not a complex block");const i=ye(n,r).getNextContainer(n,r,o,e);return i?fu(e)?Gt(i):Kt(i):mu(n,r,e)}function Fb(n,t,e){const o=j(t);if(Ct(o))return null;const r=z(o);if(d($i,r,"child container has not parent block"),fu(e)){const l=gt(r);if(l)return l}else{const l=ht(r);if(l)return l}const i=mu(n,r,e);if(i)return i;let s=r;for(;!Ct(j(s));)s=z(j(s));return fu(e)?gt(s):ht(s)}function zb(n,t,e){return!ct(n,t)||ye(n,t).enableKeyboardSelect?t:Fp(n,t,e==="ArrowDown"||e==="ArrowRight")}function Ub(n,t,e){const o=n.getBlockById(t.blockId),i=kt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?jb(n,t):Hb(n,t);if(s||(s=mu(n,o,e),s||(s=Fb(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Ct(j(o)))return null;const l=n.insertTextBlock("",U(n.rootContainer),Ve(n.rootContainer));return $(l,0,"home")}return null}if(s=zb(n,s,e),H(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return y8(n,s,o,t,l);if(e==="ArrowUp")return k8(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?$(s,Z(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?$(s,0,"home"):null}function Vb(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(H(n,r))return o;const i=ht(r);if(i)return $(i,0,"home");if(!Ct(j(r))||n.readonly)return o;const s=n.insertTextBlock("",U(n.rootContainer),Ve(n.rootContainer));return $(s,0,"home")}function qb(n,t,e){const o=n.selection.range;let r;if(o instanceof se)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=Vb(n,t,o):r=Ub(n,o.getFocusedPos(),t);else if(r=$b(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=Gt(s);r=$(l,0,"home")}else{const l=Kt(s);r=$(l,Z(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:Ul(n,o.anchor,r):null}function so(n,t,e){const o=qb(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 Wb(n){return so(n,"ArrowLeft","move"),!0}function Gb(n){return so(n,"ArrowRight","move"),!0}function Zb(n){return so(n,"ArrowUp","move"),!0}function Yb(n){if(so(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=j(t);if(Ct(e)||Gt(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",U(o),Ve(o)),!0}function Qb(n){return so(n,"ArrowDown","select"),!0}function Kb(n){return so(n,"ArrowLeft","select"),!0}function Jb(n){return so(n,"ArrowRight","select"),!0}function Xb(n){return so(n,"ArrowUp","select"),!0}function tv(n){if(!n.selection.range.focus.isSimple())return!1;const e=uu(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function ev(n){if(!n.selection.range.focus.isSimple())return!1;const e=hu(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function nv(n){if(!n.selection.range.focus.isSimple())return!1;const e=uu(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function ov(n){if(!n.selection.range.focus.isSimple())return!1;const e=hu(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}y("find-block");function gu(n,t){if(!ct(n,t))return t;const o=ye(n,t).getChildContainers(n,t)[0],i=Ot(o)[0];return gu(n,i)}function pu(n,t){if(!ct(n,t))return t;const e=ye(n,t).getChildContainers(n,t),o=e[e.length-1],r=Ot(o),i=r[r.length-1];return pu(n,i)}function rv(n){const t=pu(n,Gt(n.rootContainer)),e=$(t,Z(n,t),"end");return n.selection.setSelection(e),!0}function iv(n){const t=gu(n,n.getFirstBlock()),e=$(t,0,"home");return n.selection.setSelection(e),!0}function sv(n){const t=gu(n,n.getFirstBlock()),e=$(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function lv(n){const t=pu(n,Gt(n.rootContainer)),e=$(t,Z(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function cv(n){if(!n.selection.range.focus.isSimple())return!1;const e=au(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function av(n){if(!n.selection.range.focus.isSimple())return!1;const e=du(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function dv(n){if(!n.selection.range.focus.isSimple())return!1;const e=au(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function uv(n){if(!n.selection.range.focus.isSimple())return!1;const e=du(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const zp=y("find-block-position");function hv(n,t,e,o){d(zp,ct(n,t),"is not a complex block");const r=ye(n,t).getChildContainers(n,t);d(zp,r.length>0,"complex block has not any child container");const i=Ze(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,c=ig(n,t,s,l);return Cu(n,c,e,o)}function Cu(n,t,e,o){if(ct(n,t))return hv(n,t,e,o);const r=G(t);let i=Number.MAX_SAFE_INTEGER;const s=Ze(n,e,o),l=s.left+s.width/2,c=s.top+s.height/2;let a=$(r,0,"home");const h=Z(n,t);for(let f=0;f<=h;f++){const m=$(r,f,"normal"),C=Ze(n,t,m),v=fn(C,l,c);v<i&&(i=v,a=m)}return a}const Up=y("page-offset");function fv(n,t){const e=Ip(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<Bb(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 mv(n,t){const e=Ip(n)*.9,o=t.getBoundingClientRect(),r=Eb(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=ht(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=ht(l)}return n.getLastBlock()}function Vp(n){const t=n.selection.range.focus;d(Up,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=fv(n,e);let r;return o===n.getFirstBlock()?r=$(o,0,"home"):r=Cu(n,o,e,t),r}function qp(n){const t=n.selection.range.focus;d(Up,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=mv(n,e);let r;return o===n.getLastBlock()?r=$(o,Z(n,o),"end"):r=Cu(n,o,e,t),r}function gv(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vp(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function pv(n){if(!n.selection.range.focus.isSimple())return!1;const e=qp(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function Cv(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vp(n);if(!e)return!1;const o=Ul(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 bv(n){if(!n.selection.range.focus.isSimple())return!1;const e=qp(n);if(!e)return!1;const o=Ul(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 ji=y("select-all");function vv(n,t){const e=t.getEditor(),o=ye(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=G(n);return t.start.blockId===s&&t.start.childContainerId===U(r)&&t.end.blockId===s&&t.end.childContainerId===U(i)}function kv(n,t){d(ji,t,"no parent block"),d(ji,ct(n,t),"not a complex block");const e=ye(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(Vt(n,{anchor:bt(t,U(o)),focus:bt(t,U(r))}))}function Wp(n,t){const e=j(t),o=Ot(e),r=o[0],i=o[o.length-1],s=$(r,0,"home"),l=$(i,Z(n,i),"end");n.selection.setSelection(s,l,{noScroll:!0})}function yv(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&H(n,t)){const r=e.start,i=e.end,s=Z(n,t);if(r.offset>0||i.offset<s)return n.selection.selectBlock(t,0,s),!1}return M(n.rootContainer,"select-all"),Wp(n,Kt(n.rootContainer)),!1}return d(ji,!e.isSimple(),"invalid range type"),vv(t,e)?(Wp(n,t),!1):(d(ji,t,"no parent block"),d(ji,ct(n,t),"not a complex block"),kv(n,t),!0)}function wv(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function Bv(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const Gp=y("delete-text");function Zp(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof Ut||d(Gp,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);d(Gp,H(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!me(s,l-e)){const c=Po(s,l);e=l-c}}else if(t==="forward"&&l+e>Z(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function Yp(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const Ev=y("handle-backspace");function bu(n,t){if(!yt(n,t))return;const e=j(t);Ve(e)!==1&&n.deleteBlock(t)}function Iv(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(H(n,o))if(e.offset===0){if(Yp(n,o))return;const r=gt(o);if(r)if(H(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(ct(n,r)){bu(n,o);const i=yr(n,r);i?n.selection.selectBlock(i,Z(n,i)):n.selection.selectBlock(r,0,Z(n,r))}else bu(n,o),d(Ev,De(r),"prev block is not embed block"),n.selection.selectBlock(r,1);else{const i=j(o);if(We(i)){const s=ng(n,i);s&&(bu(n,o),n.selection.selectBlock(s,Z(n,s)))}}}else Zp(n,"backward",1,null);else{const r=K(o),i=j(o);n.insertTextBlock("",U(i),r),n.deleteBlock(o)}}function xv(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(H(n,o))if(e.offset===Z(n,o)){const r=ht(o);r&&(H(n,r)?n.mergeTextBlock(o,r,{focus:!0}):yt(n,o)?n.deleteBlock(o,Lt(n,r,0)):n.deleteBlock(r))}else Zp(n,"forward",1,null);else{const r=K(o),i=j(o);n.insertTextBlock("",U(i),r),n.deleteBlock(o)}}function Sv(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const e=n.getFocusedBlock();if(H(n,e)){if(yt(n,e)&&Yp(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 Tv(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!H(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 Dv=y("input-handler-actions");function Lv(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Sv(n),!0))}function Mv(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(xv(n),!0))}function Rv(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Iv(n),!0))}function Ov(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Tv(n),!0))}function Av(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{const e=n.selection.focusedBlock,o=n.selection.range.start;d(Dv,o.isSimple(),"not simple position"),n.insertTextToBlock(e,o.offset,t)}),!0)}function _v(n){return bb(n),Wd(n),!0}const Vl={ArrowDown:Yb,ArrowUp:Zb,ArrowLeft:Wb,ArrowRight:Gb,"Shift+ArrowDown":Qb,"Shift+ArrowUp":Xb,"Shift+ArrowLeft":Kb,"Shift+ArrowRight":Jb,"CtrlOrCmd+ArrowLeft":tv,"CtrlOrCmd+ArrowRight":ev,"CtrlOrCmd+Shift+ArrowLeft":nv,"CtrlOrCmd+Shift+ArrowRight":ov,"CtrlOrCmd+ArrowUp":iv,"CtrlOrCmd+ArrowDown":rv,"CtrlOrCmd+Shift+ArrowUp":sv,"CtrlOrCmd+Shift+ArrowDown":lv,"CtrlOrCmd+A":yv,Home:dv,End:uv,"Shift+Home":cv,"Shift+End":av,PageUp:gv,PageDown:pv,"Shift+PageUp":Cv,"Shift+PageDown":bv,"CtrlOrCmd+X":_v,"CtrlOrCmd+Z":wv,"CtrlOrCmd+Shift+Z":Bv,Enter:Lv,Delete:Mv,Backspace:Rv,"Shift+Enter":Ov,"CtrlOrCmd+Shift+V":Av};function Qp(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function Kp(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=>{Kp(n,l,e)})})}function Jp(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):Kp(t,r,e)})}async function Nv(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 Pv(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 $v(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(Pv(n,t)){const s=Array.from(Object.keys(o));r=await Nv(n,s),Jp(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&&Jp(n,t,i)}async function jv(n,t){await $v(n,t),n.undoManager.runInGroup(()=>{n.clearSelectedContents();const{block:e,offset:o}=Sr(n);n.insertDoc(e,o,t)})}const Hv=["text/x-ones-editor-doc","image/*","text/html","text/plain","text/markdown","*"];function Fv(n){let t;for(const e of Hv)if(t=n[e],t)break;return t||null}class zv{constructor(t){u(this,"editor");u(this,"handlers",[]);this.editor=t}onInsertText(t,e){if(!H(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=Sr(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}=Sr(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}=Sr(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)}}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;this.editor.dataConverter.fromData(this.editor,t.clipboardData).then(async o=>{if(!o)return;for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforePaste&&await s.handleBeforePaste(this.editor,t,o))return}const r=Fv(o);if(!!r){await this.pasteDoc(r);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterPaste&&await s.handleAfterPaste(this.editor,t,o))return}}})}onFocus(){M(this.editor.rootElement,"active")}onBlur(){F(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){Hd(this.editor,i)}defaultHandleKeydown(t,e){return Qp(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 jv(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}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function Uv(n,t,e){const o=fr(t,e);return o.remove(),o}y("copy-dom-attributes");const Xp=["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 Vv(n,t){for(let l=0;l<Xp.length;l++){const c=Xp[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 t2(n){const t=Array.from(n.childNodes);return t.forEach(e=>{e instanceof HTMLElement&&e.getAttribute("data-type")==="block-tools"||e.remove()}),t}function e2(n,t,e){var a;const o=n.getContainerById(t),r=fr(o,e),i=Ro(r),s=n.doc.getBlockData(t,e),l=kt(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 h=n.editorBlocks.createBlock(i,o,s),f=t2(h);t2(r),f.forEach(C=>r.appendChild(C));const m=al(h);if(m){const C=al(r);C&&C.remove(),r.appendChild(m)}Vv(h,r)}Vm(n,r,s),n.blockHooks.forEach(h=>{var f;(f=h.update)==null||f.call(h,n,i,o,r,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const qv=y("transform-selection");function n2(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;d(qv,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const a=oe.transformCursor(i.offset,e,o);l=$(t,a,"normal")}let c=s;if(s.blockId===t){const a=oe.transformCursor(s.offset,e,o);c=$(t,a,"normal")}return Vt(n,{anchor:l,focus:c})}const Wv=y("handle-block-text-changed");function Gv(n,t,e,o,r){const i=n.getContainerById(t),s=fr(i,e),l=n.doc.getBlockData(t,e);if(d(Wv,l.text,"no block text"),Hm(n,s).setBlockText(n,s,l.text),!r){const c=n2(n,l.id,o,r);n.selection.setRange(c,{noScroll:!0})}}function Zv(n,t){const e=Y.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function o2(n,t,e,o){const r=kt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function Yv(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{o2(n,i,o,{child:!0})}),o2(n,r,o,{child:!1})}const Hn=y("editor-doc");class Qv extends vi{constructor(e,o,r){super();u(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(Hn,this.editor.isWritable(),"editor is readonly");const s=this.getBlockData(e,o),l=s.text;d(Hn,l,`no text, ${e}, ${o}`);const c=n2(this.editor,s.id,r,!0),a=oe.apply(l,r);this.localEvents.forEach(f=>f.onBeforeUpdateBlockText(e,s.id,l,a,c.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(c,i),h}localUpdateBlockData(e,o,r,i){d(Hn,this.editor.isWritable(),"editor is readonly");const s=Y.default(this.getBlockData(e,o)),l=Y.default(Zv(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(oo(this.editor,i)),c}localInsertBlock(e,o,r,i,s){d(Hn,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(oo(this.editor,i),s),l}localDeleteBlock(e,o,r){d(Hn,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(oo(this.editor,r)),s}localDeleteChildContainers(e){return d(Hn,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(Hn,this.editor.isWritable(),"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(e,Y.default(o))),this.externalDoc.localInsertChildContainer(e,o)}onRequestReload(e){Hn.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)}),Gv(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)}),e2(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);B7(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){Yv(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);Uv(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){Hn.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function r2(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 vu=y("undo-action");class Mr{constructor(t,e,o){u(this,"beforeRange");u(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(vu,t,"no other action"),!1}combine(t){d(vu,!1,"no other")}setAfterRange(t){this.afterRange&&vu.warn("after range has already set"),this.afterRange=t}}const Kv=y("block-action");class i2 extends Mr{constructor(e,o,r,i,s){super(e,o,s);u(this,"blockData");u(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(Kv,this.blockIndex===K(i),"invalid block index"),Ud(e,i,oo(e,o)),!0):!1}insertBlock(e,o){return Tr(e,this.containerId,this.blockIndex,Y.default(this.blockData),o),!0}}class Jv extends i2{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class Xv extends i2{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class tk extends Mr{constructor(e){super(e,U(e.rootContainer),e.selection.range.toDocRange());u(this,"actions",[])}addAction(e){r2(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 Mr&&(o.afterRange||o.setAfterRange(e))}}const zo=y("update-block-data-action");class ql extends Mr{constructor(e,o,r,i,s,l){super(e,o,l);u(this,"beforeBlockData");u(this,"afterBlockData");u(this,"blockId");this.blockId=r,d(zo,this.blockId===i.id,"invalid block id"),d(zo,this.blockId===s.id,"invalid block id"),this.beforeBlockData=Y.default(i),this.afterBlockData=Y.default(s),d(zo,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){d(zo,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return d(zo,r,"no container"),$l(e,o,ql.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){d(zo,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return d(zo,r,"no container"),$l(e,o,ql.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=Y.default(e);return delete o.id,delete o.type,o}}const ku=y("update-block-text-action");class Hi extends Mr{constructor(e,o,r,i,s,l){super(e,o,l);u(this,"beforeRichTextData");u(this,"afterRichTextData");u(this,"blockId");u(this,"type");this.blockId=r,this.beforeRichTextData=Y.default(i),this.afterRichTextData=Y.default(s),this.type=Hi.calType(i,s)}static calType(e,o){d(ku,e,"no old data"),d(ku,o,"no new data");const i=oe.diff(e,o),s=new Set;let l=!1;const c=h=>Yf(h)?`cjk_${h}`:Gf(h)?"number":tl(h)?"space":Zf(h)?"letter":"unknown";let a=!1;return i.forEach(h=>{h.insert?h.insert===" "?s.add("insert_letter"):typeof h.insert=="string"&&h.insert.startsWith(" ")&&h.insert.length>1?(l=!0,a=!0,s.add(`insert_${c(h.insert.substr(1))}`)):s.add(`insert_${c(h.insert)}`):h.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?(Pl(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Pl(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof Hi)||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(ku,e instanceof Hi,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class s2 extends Mr{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 ek extends s2{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class nk extends s2{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Xe=y("undo");class ok{constructor(t){u(this,"editor");u(this,"actions",[]);u(this,"undoCursor");u(this,"currentGroup",null);u(this,"groupCounter",0);u(this,"undoRedoing",!1);u(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):(r2(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(d(Xe,!this.currentGroup,"current group already exists"),this.currentGroup=new tk(this.editor),this.groupCounter=1):(d(Xe,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){d(Xe,this.currentGroup,"current group not exists"),d(Xe,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Xe.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 Xe.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(oo(this.editor,t.beforeRange))}catch(e){Xe.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(oo(this.editor,e)):Xe.warn("no after range")}catch(e){Xe.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(),oe.diff(o,r).length!==0&&this.addAction(new Hi(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new ql(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),d(Xe,e>=0,"invalid block index"),d(Xe,o,"no block data"),this.addAction(new Jv(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new Xv(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new ek(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new nk(this.editor,t,e)))}}class rk{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 ik{constructor(){u(this,"converters",[]);this.addConverter(new rk)}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 sk{constructor(t){u(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 _t extends Wt.TypedEmitter{constructor(e){super();u(this,"hoveringBlock",null);u(this,"hoveringTextChild",null);u(this,"filters",[]);u(this,"finders",[]);u(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=z(o);if((!r||!vt(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?G(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&&vt(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&F(s,"hover"),e&&M(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 _t(e))}getParentTextContentChild(e,o){if(!H(this.editor,e))return null;const r=rt(e);return o.parentElement===r?o:rd(o)}}const l2="style-color-",c2="style-bg-color-";class lk{renderText(t,e,o){const r=[],i={};return Object.entries(o).forEach(([s,l])=>{l===!0?s.startsWith(l2)?i["data-style-color"]=s.substring(l2.length):s.startsWith(c2)?i["data-style-bg-color"]=s.substring(c2.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,h])=>{r[`data-${a}`]=`${h}`});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"),_t.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&&M(o,"focused"),_t.get(t).hoveringBlockId()===r.id&&M(o,"hover")}}function ck(n){n.editorBlocks.registerBlockClass(Ai),n.editorBlocks.registerBlockClass(eg),n.editorBoxes.registerBoxClass(Fg),n.editorBoxes.registerBoxClass(zg),n.editorInsertions.registerInsertionClass(qg),n.editorBlockRenders.registerRender(new lk)}function ak(n,t){ck(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 a2=y("range-commands");function d2(n,t){n.forEach(e=>{e.source=t,e.children&&d2(e.children,t)})}function u2(n,t,e){const o=G(t);d(a2,o===e.start.blockId,"invalid start range"),d(a2,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);d2(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,i);l&&(i=l)}}),ct(n,t)&&kr(n,t,e.start,e.end).forEach(l=>{Ot(l).forEach(a=>{const h=Z(n,a),f=Vt(n,{anchor:$(a,0,"home"),focus:$(a,h,"end")}),m=u2(n,a,f);i.push(...m)})}),i}function h2(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=Vt(t,{anchor:r.start,focus:r.end});u2(t,r.block,i).forEach(l=>{o.push(l)})}),o}function f2(n,t,e,o,r,i){var h;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((h=l.executeCommand)!=null&&h.call(l,n,t,e,o,r,{}))return i[G(t)]=c,!0;let a=!1;return ct(n,t)&&kr(n,t,e.start,e.end).forEach(m=>{Ot(m).forEach(v=>{const w=Z(n,v),E=Vt(n,{anchor:$(v,0,"home"),focus:$(v,w,"end")});f2(n,v,E,o,r,i)&&(a=!0)})}),s.forEach(f=>{f.afterExecuteCommand&&f.afterExecuteCommand(n,t,e,o,r,i)}),a}function m2(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=Vt(o,{anchor:l.start,focus:l.end});f2(o,l.block,c,t,e,r)}),r}const dk=y("command-providers");class g2{constructor(t){u(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(dk,e,`no command provider, id=${t}`),e}getCommands(t){return h2(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>m2(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 uk(n,t){const e=j(t),o=U(e),r=K(t);e2(n,o,r)}const hk=y("table-scroll");class p2{constructor(t,e,o,r,i){u(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 fk{constructor(t){u(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)){hk.warn(`event has already registered: ${e}`);return}i.push(new p2(this.editor,t,e,o,r))}else{const s=new p2(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 C2=y("update-block-text");function mk(n,t){const e=n.getBoxById(t.id),o=z(e);d(C2,o,"no parent block"),d(C2,H(n,o),"not a text block");const r=n.getBlockText(o),i=Rg(r,"id",t.id,t);fp(n,o,i)}function gk(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 pk(n){return n.readonly?!1:!Ke(n).find(o=>!n.isBlockWritable(o.block))}class Ck{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 bk{constructor(){u(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(An(e,s)){const c=l(t,e);if(c!==void 0)return c}}}}const Fn=y("editor");class vk extends Wt.TypedEmitter{constructor(e,o,r){var i,s,l,c,a,h,f;super();u(this,"parent");u(this,"rootElement");u(this,"contentElement");u(this,"rootContainerObject");u(this,"rootContainer");u(this,"input");u(this,"selection");u(this,"selectionHandler");u(this,"doc");u(this,"id");u(this,"clientId");u(this,"compositingText","");u(this,"undoManager");u(this,"shortcuts",new bk);u(this,"dataConverter",new ik);u(this,"editorBlocks",new Km(this));u(this,"editorBoxes",new Vg(this));u(this,"editorInsertions",new Gg(this));u(this,"editorEmbeds",new Xm(this));u(this,"editorDecorators",new Zg(this));u(this,"editorCommandProviders",new g2(this));u(this,"editorBlockRenders",new sk(this));u(this,"blockHooks",[]);u(this,"domEvents",new fk(this));u(this,"customs",new Map);u(this,"options");u(this,"inputHandlers",new zv(this));u(this,"settingsProvider");u(this,"_readonly",!1);Fn.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 Ck(this),ak(this,r==null?void 0:r.components),this.blockHooks.push(...(h=(a=r==null?void 0:r.components)==null?void 0:a.blockHooks)!=null?h:[]),this.id=(f=r==null?void 0:r.id)!=null?f:N(),this.clientId=N(),this.undoManager=new ok(this),this.doc=new Qv(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=Pm(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new vb(this,this.inputHandlers),this.selection=new Lb(this),this.selectionHandler=new Nb(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),St.isMobile&&M(this.rootElement,"mobile"),St.isSafari&&M(this.rootElement,"safari"),this._readonly&&M(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?M(this.rootElement,"readonly"):F(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:_n(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(Fn,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(){Fn.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){Gd(this,e,o)}isWritable(){return pk(this)}isBlockWritable(e){return gk(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return d(Fn,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),d(Fn,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(e,o,r){return $m(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(Fn,mr(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&d(Fn,od(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return d(Fn,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return d(Fn,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return fr(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return K(o)}return K(e)}getContainerById(e){return Cr(this,e)}getParentContainer(e){return j(e)}reloadBlock(e){uk(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 Tr(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){Vd(this,e,o)}mergeTextBlock(e,o){return dp(this,e,o)}breakTextBlock(e,o,r){return Dr(this,e,o,r).newBlock}getTextPosition(){return Sr(this)}getBlockString(e,o){const r=this.getBlockText(e);return wt(r,o)}getBlockData(e){return io(this,e)}getBoxData(e){return Jg(this,e)}getBlockText(e){return we(this,e)}setBlockText(e,o){fp(this,e,o)}deleteTextFromBlock(e,o,r,i){return Fd(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return tp(this,e,o,r,i)}insertBoxToBlock(e,o,r){return ep(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){pp(this,e,o,r,i)}insertDocAt(e,o,r,i){return Qd(this,e,o,r,i)}deleteChildContainers(e){ap(this,e)}replaceBlockText(e,o){return Pl(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...c}=i;return $l(this,e,c,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return mp(this,e,o,r)}updateBoxData(e){mk(this,e)}getSelectedText(){const e=Fl(this);return nu(this,e)}clearSelectedContents(){Wd(this)}insertTextBlock(e,o,r,i){const s=jn(e!=null?e:"");return ip(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){op(this);return}o?(this.compositingText="",Ga()||Hd(this,e)):(this.compositingText=e,np(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function Fi(n,t,e){return new vk(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=ja.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const yk=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class Wl extends Wt.TypedEmitter{constructor(e){super();u(this,"users",new Map);u(this,"cursors",new Map);u(this,"addingUser",!1);u(this,"colors");this.colors=e&&e.length>0?e:yk}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&Zs.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&&Sl(r.range)&&Ng(r.range)).forEach(r=>{const i=r.range.anchor.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(Sl(l.range)){const{anchor:c,focus:a}=l.range;c.blockId===e.id&&(c.offset=oe.transformCursor(c.offset,o,r)),a.blockId===e.id&&(a.offset=oe.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 Xt=y("local-doc");class yu extends vi{constructor(e,o){super();u(this,"doc");u(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[jn("")]}},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(Xt,r,`no container data: ${e}`);const i=r[o];return d(Xt,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);d(Xt,i.text,"no text for data");const s=oe.apply(i.text,r);return i.text=s,d(Xt,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(Xt,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(Xt,i,`no container data: ${e}`),d(Xt,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),d(Xt,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(Xt,r,`no container data: ${e}`),d(Xt,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),d(Xt,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(Xt,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){Xt.debug(`delete child containers: ${e}`),e.forEach(o=>{d(Xt,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{d(Xt,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(Xt,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){d(Xt,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new Wl}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 Uo(n){return Ct(j(n))}class wk{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function wu(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new wk(o)})}const Bk=y("remote-cursor");class Ek{constructor(){u(this,"remoteUsers",new Wl)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):Bk.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 Ik(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function zi(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=Ik(Y.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function lo(n){return n==="root"?"blocks":n}function Rr(n){return n==="blocks"?"root":n}const xk={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new ne.default(n)},apply(n,t){const e=new ne.default(n),o=new ne.default(t);return e.compose(o).ops},compose(n,t){const e=new ne.default(n),o=new ne.default(t);return e.compose(o).ops},diff(n,t){const e=new ne.default(n),o=new ne.default(t);return e.diff(o).ops},transform(n,t,e){const o=new ne.default(n);return new ne.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 ne.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 Ui=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},co={},Bu=xf.default.EventEmitter;co.EventEmitter=Bu,co.mixin=Sk;function Sk(n){for(var t in Bu.prototype)n.prototype[t]=Bu.prototype[t]}var b2=["info","warn","error"];function v2(){var n={};b2.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var Tk=v2;v2.prototype.setMethods=function(n){n=n||{};var t=this;b2.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var Dk=Tk,Lk=new Dk,k2=Lk;function Vo(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,Vo):this.stack=new Error().stack}Vo.prototype=Object.create(Error.prototype),Vo.prototype.constructor=Vo,Vo.prototype.name="ShareDBError",Vo.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 Gl=Vo,Vi={},y2=Mk;function Mk(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 h=l[a],f=[],m=0;m<s.length;){var C=[];if(r(s[m],h,f,C),m++,C.length===1)h=C[0];else if(C.length===0){for(var v=m;v<s.length;v++)o(f,s[v]);h=null;break}else{for(var w=i(s.slice(m),C),E=0;E<w[0].length;E++)o(f,w[0][E]);for(var D=0;D<w[1].length;D++)o(c,w[1][D]);h=null;break}}h!=null&&o(c,h),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 w2={exports:{}},ao=w2.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||""}},Eu=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},Iu=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")},Zl=function(n){for(var t=0;t<n.length;t++)Iu(n[t])};ao.apply=function(n,t){var e;Zl(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=Eu(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 zn=ao._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:Eu(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:Eu(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};ao.compose=function(n,t){Zl(n),Zl(t);for(var e=n.slice(),o=0;o<t.length;o++)zn(e,t[o]);return e},ao.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),zn(t,o)}return t};var xu=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};ao.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=xu(n,t[r],o);return n};var Rk=ao._tc=function(n,t,e,o){if(Iu(t),Iu(e),t.i!=null)zn(n,{i:t.i,p:xu(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(zn(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&zn(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)zn(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)zn(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=xu(i.p,e),zn(n,i))}return n},Ok=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};ao.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=Ok(n[t]);return n},y2(ao,Rk,Zl,zn);var Yl=function(n){return Object.prototype.toString.call(n)=="[object Array]"},Ak=function(n){return!!n&&n.constructor===Object},tn=function(n){return JSON.parse(JSON.stringify(n))},tt={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Un={};tt.registerSubtype=function(n){Un[n.name]=n},tt.create=function(n){return n===void 0?null:tn(n)},tt.invertComponent=function(n){var t={p:n.p};return n.t&&Un[n.t]&&(t.t=n.t,t.o=Un[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(!Yl(n[t].p))throw new Error("Missing path")},tt.checkList=function(n){if(!Yl(n))throw new Error("Referenced element not a list")},tt.checkObj=function(n){if(!Ak(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function qi(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 Wi(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=tn(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&qi(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&&Un[r.t])s[l]=Un[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 h=s[l];s.splice(l,1),s.splice(r.lm,0,h)}}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 _k=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=tn(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)&&(qi(t),qi(e)),_k(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Un[t.t]){if(e.o=Un[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(),Wi(t),n.push(t);Wi(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)&&(Wi(t),Wi(e)),n.push(t)},tt.compose=function(n,t){tt.checkValidOp(n),tt.checkValidOp(t);for(var e=tn(n),o=0;o<t.length;o++)tt.append(e,t[o]);return e},tt.normalize=function(n){var t=[];n=Yl(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=tn(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=tn(e);c.p=c.p.slice(s),t.ld=tt.apply(tn(t.ld),[c])}else if(t.od!==void 0){var c=tn(e);c.p=c.p.slice(s),t.od=tt.apply(tn(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)&&(qi(t),c=tn(e),qi(c)),c.t&&Un[c.t]){if(t.t&&t.t===c.t){var h=Un[t.t].transform(t.o,c.o,o);if(t.si!=null||t.sd!=null)for(var f=t.p,m=0;m<h.length;m++)t.o=[h[m]],t.p=f.slice(),Wi(t),tt.append(n,t);else(!Yl(h)||h.length>0)&&(t.o=h,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=tn(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,w=e.p[r],E=e.lm;if(w!==E)if(C===w)if(o==="left")t.p[r]=E,C===v&&(t.lm=E);else return n;else C>w&&t.p[r]--,C>E?t.p[r]++:C===E&&w>E&&(t.p[r]++,C===v&&t.lm++),(v>w||v===w&&v>C)&&t.lm--,v>E?t.lm++:v===E&&(E>w&&v>C||E<w&&v<C?o==="right"&&t.lm++:v>C?t.lm++:v===w&&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},y2(tt,tt.transformComponent,tt.checkValidOp,tt.append);var Nk=w2.exports;tt.registerSubtype(Nk);var Pk=tt,$k={type:Pk};(function(n){n.defaultType=$k.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)})(Vi);var en={};(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))}})(en);var B2=Array.isArray,E2=Object.keys,jk=Object.prototype.hasOwnProperty,Hk=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=B2(t),r=B2(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 h=t instanceof RegExp,f=e instanceof RegExp;if(h!=f)return!1;if(h&&f)return t.toString()==e.toString();var m=E2(t);if(s=m.length,s!==E2(e).length)return!1;for(i=s;i--!==0;)if(!jk.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},I2=co,Fk=k2,Be=Gl,Ql=Vi,nn=en,zk=nn.clone,Uk=Hk,pe=Be.CODES,Vk=st;function st(n,t,e){I2.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}I2.mixin(st),st.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())})},st.prototype._setType=function(n){if(typeof n=="string"&&(n=Ql.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new Be(pe.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},st.prototype._setData=function(n){this.data=n,this._dataStateVersion++},st.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new Be(pe.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 Be(pe.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?Ql.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()},st.prototype.whenNothingPending=function(n){var t=this;nn.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},st.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},st.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},st.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},st.prototype._emitResponseError=function(n,t){if(n&&n.code===pe.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)},st.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){nn.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},st.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){nn.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()},st.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===pe.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=Kl(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=Kl(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},st.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))},st.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()},st.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);qk(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},st.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},st.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},st.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=e&&e.wantSubscribe===n;if(o){e.callback=Wk([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},st.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;nn.nextTick(function(){n._handleSubscribe()})}}};function qk(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function Wk(n){return n=n.filter(nn.truthy),n.length?function(t){nn.callEach(n,t)}:null}st.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function Gk(n){delete n.op,delete n.create,delete n.del}function Kl(n,t){if(n.del)return Gk(t);if(t.del)return new Be(pe.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new Be(pe.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new Be(pe.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}}}st.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new Be(pe.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===Ql.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=Kl(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}},st.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 Be(pe.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>=nn.MAX_SAFE_INTEGER)return this.emit("error",new Be(pe.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)}},st.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var o=new Be(pe.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;nn.nextTick(function(){r.flush()})},st.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)},st.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)}}},st.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!Uk(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}}},st.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)},st.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=Ql.defaultType.uri),this.type){var r=new Be(pe.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)},st.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new Be(pe.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)},st.prototype.pause=function(){this.paused=!0},st.prototype.resume=function(){this.paused=!1,this.flush()},st.prototype.toSnapshot=function(){return{v:this.version,data:zk(this.data),type:this.type.uri}},st.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return Fk.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},st.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=Kl(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)},st.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=nn.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},st.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=nn.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var qo={};qo.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 x2=co,S2=qo.ACTIONS,Zk=en,Yk=Ce;function Ce(n,t,e,o,r,i,s){x2.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}x2.mixin(Ce),Ce.prototype.hasPending=function(){return!this.ready},Ce.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}},Ce.prototype.destroy=function(n){this.connection.canSend&&this.action===S2.querySubscribe&&this.connection.send({a:S2.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&Zk.nextTick(n)},Ce.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Ce.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Ce.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Ce.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(h){if(h)return r._finishResponse(h,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()},Ce.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},Ce.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)},Ce.prototype._handleError=function(n){this.emit("error",n)},Ce.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)},Ce.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var T2=co,Qk=qo.ACTIONS,Kk=en,D2=vn;function vn(n,t){if(T2.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={}}T2.mixin(vn),vn.prototype.submit=function(n,t){this.value=n,this.send(t)},vn.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},vn.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()})},vn.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},vn.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},vn.prototype._message=function(){return{a:Qk.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},vn.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},vn.prototype._callbackOrEmit=function(n,t){if(t)return Kk.nextTick(t,n);n&&this.emit("error",n)};var Jk=en,L2=Su;function Su(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}Su.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},Su.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&Jk.nextTick(n)};var Tu={exports:{}};(function(n,t){(function(e,o){o(t)})(Ui,function(e){function o(p,k){k=k|0;for(var B=Math.max(p.length-k,0),I=Array(B),L=0;L<B;L++)I[L]=p[k+L];return I}var r=function(p){var k=o(arguments,1);return function(){var B=o(arguments);return p.apply(null,k.concat(B))}},i=function(p){return function(){var k=o(arguments),B=k.pop();p.call(this,k,B)}};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 h(p){return function(k){var B=o(arguments,1);p(function(){k.apply(null,B)})}}var f;l?f=setImmediate:c?f=process.nextTick:f=a;var m=h(f);function C(p){return i(function(k,B){var I;try{I=p.apply(this,k)}catch(L){return B(L)}s(I)&&typeof I.then=="function"?I.then(function(L){v(B,null,L)},function(L){v(B,L.message?L:new Error(L))}):B(null,I)})}function v(p,k,B){try{p(k,B)}catch(I){m(w,I)}}function w(p){throw p}var E=typeof Symbol=="function";function D(p){return E&&p[Symbol.toStringTag]==="AsyncFunction"}function x(p){return D(p)?C(p):p}function A(p){return function(k){var B=o(arguments,1),I=i(function(L,T){var R=this;return p(k,function(_,q){x(_).apply(R,L.concat(q))},T)});return B.length?I.apply(this,B):I}}var O=typeof Ui=="object"&&Ui&&Ui.Object===Object&&Ui,P=typeof self=="object"&&self&&self.Object===Object&&self,V=O||P||Function("return this")(),nt=V.Symbol,ot=Object.prototype,ut=ot.hasOwnProperty,dt=ot.toString,Et=nt?nt.toStringTag:void 0;function re(p){var k=ut.call(p,Et),B=p[Et];try{p[Et]=void 0;var I=!0}catch{}var L=dt.call(p);return I&&(k?p[Et]=B:delete p[Et]),L}var Xn=Object.prototype,te=Xn.toString;function Fe(p){return te.call(p)}var bo="[object Null]",cr="[object Undefined]",ar=nt?nt.toStringTag:void 0;function vo(p){return p==null?p===void 0?cr:bo:ar&&ar in Object(p)?re(p):Fe(p)}var ha="[object AsyncFunction]",xP="[object Function]",SP="[object GeneratorFunction]",TP="[object Proxy]";function DP(p){if(!s(p))return!1;var k=vo(p);return k==xP||k==SP||k==ha||k==TP}var LP=9007199254740991;function $3(p){return typeof p=="number"&&p>-1&&p%1==0&&p<=LP}function Ps(p){return p!=null&&$3(p.length)&&!DP(p)}var sf={};function ft(){}function ko(p){return function(){if(p!==null){var k=p;p=null,k.apply(this,arguments)}}}var lf=typeof Symbol=="function"&&Symbol.iterator,MP=function(p){return lf&&p[lf]&&p[lf]()};function RP(p,k){for(var B=-1,I=Array(p);++B<p;)I[B]=k(B);return I}function fa(p){return p!=null&&typeof p=="object"}var OP="[object Arguments]";function j3(p){return fa(p)&&vo(p)==OP}var H3=Object.prototype,AP=H3.hasOwnProperty,_P=H3.propertyIsEnumerable,NP=j3(function(){return arguments}())?j3:function(p){return fa(p)&&AP.call(p,"callee")&&!_P.call(p,"callee")},un=Array.isArray;function PP(){return!1}var F3=typeof e=="object"&&e&&!e.nodeType&&e,z3=F3&&!0&&n&&!n.nodeType&&n,$P=z3&&z3.exports===F3,U3=$P?V.Buffer:void 0,jP=U3?U3.isBuffer:void 0,HP=jP||PP,FP=9007199254740991,zP=/^(?:0|[1-9]\d*)$/;function UP(p,k){var B=typeof p;return k=k==null?FP:k,!!k&&(B=="number"||B!="symbol"&&zP.test(p))&&p>-1&&p%1==0&&p<k}var VP="[object Arguments]",qP="[object Array]",WP="[object Boolean]",GP="[object Date]",ZP="[object Error]",YP="[object Function]",QP="[object Map]",KP="[object Number]",JP="[object Object]",XP="[object RegExp]",t$="[object Set]",e$="[object String]",n$="[object WeakMap]",o$="[object ArrayBuffer]",r$="[object DataView]",i$="[object Float32Array]",s$="[object Float64Array]",l$="[object Int8Array]",c$="[object Int16Array]",a$="[object Int32Array]",d$="[object Uint8Array]",u$="[object Uint8ClampedArray]",h$="[object Uint16Array]",f$="[object Uint32Array]",It={};It[i$]=It[s$]=It[l$]=It[c$]=It[a$]=It[d$]=It[u$]=It[h$]=It[f$]=!0,It[VP]=It[qP]=It[o$]=It[WP]=It[r$]=It[GP]=It[ZP]=It[YP]=It[QP]=It[KP]=It[JP]=It[XP]=It[t$]=It[e$]=It[n$]=!1;function m$(p){return fa(p)&&$3(p.length)&&!!It[vo(p)]}function g$(p){return function(k){return p(k)}}var V3=typeof e=="object"&&e&&!e.nodeType&&e,$s=V3&&!0&&n&&!n.nodeType&&n,p$=$s&&$s.exports===V3,cf=p$&&O.process,q3=function(){try{var p=$s&&$s.require&&$s.require("util").types;return p||cf&&cf.binding&&cf.binding("util")}catch{}}(),W3=q3&&q3.isTypedArray,C$=W3?g$(W3):m$,b$=Object.prototype,v$=b$.hasOwnProperty;function k$(p,k){var B=un(p),I=!B&&NP(p),L=!B&&!I&&HP(p),T=!B&&!I&&!L&&C$(p),R=B||I||L||T,_=R?RP(p.length,String):[],q=_.length;for(var Q in p)(k||v$.call(p,Q))&&!(R&&(Q=="length"||L&&(Q=="offset"||Q=="parent")||T&&(Q=="buffer"||Q=="byteLength"||Q=="byteOffset")||UP(Q,q)))&&_.push(Q);return _}var y$=Object.prototype;function w$(p){var k=p&&p.constructor,B=typeof k=="function"&&k.prototype||y$;return p===B}function B$(p,k){return function(B){return p(k(B))}}var E$=B$(Object.keys,Object),I$=Object.prototype,x$=I$.hasOwnProperty;function S$(p){if(!w$(p))return E$(p);var k=[];for(var B in Object(p))x$.call(p,B)&&B!="constructor"&&k.push(B);return k}function af(p){return Ps(p)?k$(p):S$(p)}function T$(p){var k=-1,B=p.length;return function(){return++k<B?{value:p[k],key:k}:null}}function D$(p){var k=-1;return function(){var I=p.next();return I.done?null:(k++,{value:I.value,key:k})}}function L$(p){var k=af(p),B=-1,I=k.length;return function L(){var T=k[++B];return T==="__proto__"?L():B<I?{value:p[T],key:T}:null}}function M$(p){if(Ps(p))return T$(p);var k=MP(p);return k?D$(k):L$(p)}function Dn(p){return function(){if(p===null)throw new Error("Callback was already called.");var k=p;p=null,k.apply(this,arguments)}}function ma(p){return function(k,B,I){if(I=ko(I||ft),p<=0||!k)return I(null);var L=M$(k),T=!1,R=0,_=!1;function q(W,X){if(R-=1,W)T=!0,I(W);else{if(X===sf||T&&R<=0)return T=!0,I(null);_||Q()}}function Q(){for(_=!0;R<p&&!T;){var W=L();if(W===null){T=!0,R<=0&&I(null);return}R+=1,B(W.value,W.key,Dn(q))}_=!1}Q()}}function dr(p,k,B,I){ma(k)(p,x(B),I)}function ee(p,k){return function(B,I,L){return p(B,k,I,L)}}function R$(p,k,B){B=ko(B||ft);var I=0,L=0,T=p.length;T===0&&B(null);function R(_,q){_?B(_):(++L===T||q===sf)&&B(null)}for(;I<T;I++)k(p[I],I,Dn(R))}var O$=ee(dr,1/0),yo=function(p,k,B){var I=Ps(p)?R$:O$;I(p,x(k),B)};function ai(p){return function(k,B,I){return p(yo,k,x(B),I)}}function G3(p,k,B,I){I=I||ft,k=k||[];var L=[],T=0,R=x(B);p(k,function(_,q,Q){var W=T++;R(_,function(X,xt){L[W]=xt,Q(X)})},function(_){I(_,L)})}var ga=ai(G3),Z3=A(ga);function di(p){return function(k,B,I,L){return p(ma(B),k,x(I),L)}}var ui=di(G3),df=ee(ui,1),Y3=A(df);function pa(p,k){for(var B=-1,I=p==null?0:p.length;++B<I&&k(p[B],B,p)!==!1;);return p}function A$(p){return function(k,B,I){for(var L=-1,T=Object(k),R=I(k),_=R.length;_--;){var q=R[p?_:++L];if(B(T[q],q,T)===!1)break}return k}}var _$=A$();function js(p,k){return p&&_$(p,k,af)}function N$(p,k,B,I){for(var L=p.length,T=B+(I?1:-1);I?T--:++T<L;)if(k(p[T],T,p))return T;return-1}function P$(p){return p!==p}function $$(p,k,B){for(var I=B-1,L=p.length;++I<L;)if(p[I]===k)return I;return-1}function Ca(p,k,B){return k===k?$$(p,k,B):N$(p,P$,B)}var uf=function(p,k,B){typeof k=="function"&&(B=k,k=null),B=ko(B||ft);var I=af(p),L=I.length;if(!L)return B(null);k||(k=L);var T={},R=0,_=!1,q=Object.create(null),Q=[],W=[],X={};js(p,function(Tt,Dt){if(!un(Tt)){xt(Dt,[Tt]),W.push(Dt);return}var Yt=Tt.slice(0,Tt.length-1),to=Yt.length;if(to===0){xt(Dt,Tt),W.push(Dt);return}X[Dt]=to,pa(Yt,function(gi){if(!p[gi])throw new Error("async.auto task `"+Dt+"` has a non-existent dependency `"+gi+"` in "+Yt.join(", "));Ln(gi,function(){to--,to===0&&xt(Dt,Tt)})})}),Lj(),ie();function xt(Tt,Dt){Q.push(function(){Mn(Tt,Dt)})}function ie(){if(Q.length===0&&R===0)return B(null,T);for(;Q.length&&R<k;){var Tt=Q.shift();Tt()}}function Ln(Tt,Dt){var Yt=q[Tt];Yt||(Yt=q[Tt]=[]),Yt.push(Dt)}function ze(Tt){var Dt=q[Tt]||[];pa(Dt,function(Yt){Yt()}),ie()}function Mn(Tt,Dt){if(!_){var Yt=Dn(function(gi,Bf){if(R--,arguments.length>2&&(Bf=o(arguments,1)),gi){var Ef={};js(T,function(Rj,Oj){Ef[Oj]=Rj}),Ef[Tt]=Bf,_=!0,q=Object.create(null),B(gi,Ef)}else T[Tt]=Bf,ze(Tt)});R++;var to=x(Dt[Dt.length-1]);Dt.length>1?to(T,Yt):to(Yt)}}function Lj(){for(var Tt,Dt=0;W.length;)Tt=W.pop(),Dt++,pa(Mj(Tt),function(Yt){--X[Yt]===0&&W.push(Yt)});if(Dt!==L)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function Mj(Tt){var Dt=[];return js(p,function(Yt,to){un(Yt)&&Ca(Yt,Tt,0)>=0&&Dt.push(to)}),Dt}};function hi(p,k){for(var B=-1,I=p==null?0:p.length,L=Array(I);++B<I;)L[B]=k(p[B],B,p);return L}var j$="[object Symbol]";function H$(p){return typeof p=="symbol"||fa(p)&&vo(p)==j$}var F$=1/0,Q3=nt?nt.prototype:void 0,K3=Q3?Q3.toString:void 0;function hf(p){if(typeof p=="string")return p;if(un(p))return hi(p,hf)+"";if(H$(p))return K3?K3.call(p):"";var k=p+"";return k=="0"&&1/p==-F$?"-0":k}function z$(p,k,B){var I=-1,L=p.length;k<0&&(k=-k>L?0:L+k),B=B>L?L:B,B<0&&(B+=L),L=k>B?0:B-k>>>0,k>>>=0;for(var T=Array(L);++I<L;)T[I]=p[I+k];return T}function U$(p,k,B){var I=p.length;return B=B===void 0?I:B,!k&&B>=I?p:z$(p,k,B)}function V$(p,k){for(var B=p.length;B--&&Ca(k,p[B],0)>-1;);return B}function q$(p,k){for(var B=-1,I=p.length;++B<I&&Ca(k,p[B],0)>-1;);return B}function W$(p){return p.split("")}var G$="\\ud800-\\udfff",Z$="\\u0300-\\u036f",Y$="\\ufe20-\\ufe2f",Q$="\\u20d0-\\u20ff",K$=Z$+Y$+Q$,J$="\\ufe0e\\ufe0f",X$="\\u200d",tj=RegExp("["+X$+G$+K$+J$+"]");function ej(p){return tj.test(p)}var J3="\\ud800-\\udfff",nj="\\u0300-\\u036f",oj="\\ufe20-\\ufe2f",rj="\\u20d0-\\u20ff",ij=nj+oj+rj,sj="\\ufe0e\\ufe0f",lj="["+J3+"]",ff="["+ij+"]",mf="\\ud83c[\\udffb-\\udfff]",cj="(?:"+ff+"|"+mf+")",X3="[^"+J3+"]",tC="(?:\\ud83c[\\udde6-\\uddff]){2}",eC="[\\ud800-\\udbff][\\udc00-\\udfff]",aj="\\u200d",nC=cj+"?",oC="["+sj+"]?",dj="(?:"+aj+"(?:"+[X3,tC,eC].join("|")+")"+oC+nC+")*",uj=oC+nC+dj,hj="(?:"+[X3+ff+"?",ff,tC,eC,lj].join("|")+")",fj=RegExp(mf+"(?="+mf+")|"+hj+uj,"g");function mj(p){return p.match(fj)||[]}function rC(p){return ej(p)?mj(p):W$(p)}function gj(p){return p==null?"":hf(p)}var pj=/^\s+|\s+$/g;function Cj(p,k,B){if(p=gj(p),p&&(B||k===void 0))return p.replace(pj,"");if(!p||!(k=hf(k)))return p;var I=rC(p),L=rC(k),T=q$(I,L),R=V$(I,L)+1;return U$(I,T,R).join("")}var bj=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,vj=/,/,kj=/(=.+)?(\s*)$/,yj=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function wj(p){return p=p.toString().replace(yj,""),p=p.match(bj)[2].replace(" ",""),p=p?p.split(vj):[],p=p.map(function(k){return Cj(k.replace(kj,""))}),p}function iC(p,k){var B={};js(p,function(I,L){var T,R=D(I),_=!R&&I.length===1||R&&I.length===0;if(un(I))T=I.slice(0,-1),I=I[I.length-1],B[L]=T.concat(T.length>0?q:I);else if(_)B[L]=I;else{if(T=wj(I),I.length===0&&!R&&T.length===0)throw new Error("autoInject task functions require explicit parameters.");R||T.pop(),B[L]=T.concat(q)}function q(Q,W){var X=hi(T,function(xt){return Q[xt]});X.push(W),x(I).apply(null,X)}}),uf(B,k)}function hn(){this.head=this.tail=null,this.length=0}function sC(p,k){p.length=1,p.head=p.tail=k}hn.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},hn.prototype.empty=function(){for(;this.head;)this.shift();return this},hn.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},hn.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},hn.prototype.unshift=function(p){this.head?this.insertBefore(this.head,p):sC(this,p)},hn.prototype.push=function(p){this.tail?this.insertAfter(this.tail,p):sC(this,p)},hn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},hn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},hn.prototype.toArray=function(){for(var p=Array(this.length),k=this.head,B=0;B<this.length;B++)p[B]=k.data,k=k.next;return p},hn.prototype.remove=function(p){for(var k=this.head;k;){var B=k.next;p(k)&&this.removeLink(k),k=B}return this};function lC(p,k,B){if(k==null)k=1;else if(k===0)throw new Error("Concurrency must not be zero");var I=x(p),L=0,T=[],R=!1;function _(X,xt,ie){if(ie!=null&&typeof ie!="function")throw new Error("task callback must be a function");if(W.started=!0,un(X)||(X=[X]),X.length===0&&W.idle())return m(function(){W.drain()});for(var Ln=0,ze=X.length;Ln<ze;Ln++){var Mn={data:X[Ln],callback:ie||ft};xt?W._tasks.unshift(Mn):W._tasks.push(Mn)}R||(R=!0,m(function(){R=!1,W.process()}))}function q(X){return function(xt){L-=1;for(var ie=0,Ln=X.length;ie<Ln;ie++){var ze=X[ie],Mn=Ca(T,ze,0);Mn===0?T.shift():Mn>0&&T.splice(Mn,1),ze.callback.apply(ze,arguments),xt!=null&&W.error(xt,ze.data)}L<=W.concurrency-W.buffer&&W.unsaturated(),W.idle()&&W.drain(),W.process()}}var Q=!1,W={_tasks:new hn,concurrency:k,payload:B,saturated:ft,unsaturated:ft,buffer:k/4,empty:ft,drain:ft,error:ft,started:!1,paused:!1,push:function(X,xt){_(X,!1,xt)},kill:function(){W.drain=ft,W._tasks.empty()},unshift:function(X,xt){_(X,!0,xt)},remove:function(X){W._tasks.remove(X)},process:function(){if(!Q){for(Q=!0;!W.paused&&L<W.concurrency&&W._tasks.length;){var X=[],xt=[],ie=W._tasks.length;W.payload&&(ie=Math.min(ie,W.payload));for(var Ln=0;Ln<ie;Ln++){var ze=W._tasks.shift();X.push(ze),T.push(ze),xt.push(ze.data)}L+=1,W._tasks.length===0&&W.empty(),L===W.concurrency&&W.saturated();var Mn=Dn(q(X));I(xt,Mn)}Q=!1}},length:function(){return W._tasks.length},running:function(){return L},workersList:function(){return T},idle:function(){return W._tasks.length+L===0},pause:function(){W.paused=!0},resume:function(){W.paused!==!1&&(W.paused=!1,m(W.process))}};return W}function cC(p,k){return lC(p,1,k)}var fi=ee(dr,1);function wo(p,k,B,I){I=ko(I||ft);var L=x(B);fi(p,function(T,R,_){L(k,T,function(q,Q){k=Q,_(q)})},function(T){I(T,k)})}function gf(){var p=hi(arguments,x);return function(){var k=o(arguments),B=this,I=k[k.length-1];typeof I=="function"?k.pop():I=ft,wo(p,k,function(L,T,R){T.apply(B,L.concat(function(_){var q=o(arguments,1);R(_,q)}))},function(L,T){I.apply(B,[L].concat(T))})}}var aC=function(){return gf.apply(null,o(arguments).reverse())},Bj=Array.prototype.concat,ba=function(p,k,B,I){I=I||ft;var L=x(B);ui(p,k,function(T,R){L(T,function(_){return _?R(_):R(null,o(arguments,1))})},function(T,R){for(var _=[],q=0;q<R.length;q++)R[q]&&(_=Bj.apply(_,R[q]));return I(T,_)})},dC=ee(ba,1/0),uC=ee(ba,1),hC=function(){var p=o(arguments),k=[null].concat(p);return function(){var B=arguments[arguments.length-1];return B.apply(this,k)}};function Hs(p){return p}function mi(p,k){return function(B,I,L,T){T=T||ft;var R=!1,_;B(I,function(q,Q,W){L(q,function(X,xt){X?W(X):p(xt)&&!_?(R=!0,_=k(!0,q),W(null,sf)):W()})},function(q){q?T(q):T(null,R?_:k(!1))})}}function fC(p,k){return k}var va=ai(mi(Hs,fC)),Fs=di(mi(Hs,fC)),ka=ee(Fs,1);function mC(p){return function(k){var B=o(arguments,1);B.push(function(I){var L=o(arguments,1);typeof console=="object"&&(I?console.error&&console.error(I):console[p]&&pa(L,function(T){console[p](T)}))}),x(k).apply(null,B)}}var gC=mC("dir");function pC(p,k,B){B=Dn(B||ft);var I=x(p),L=x(k);function T(_){if(_)return B(_);var q=o(arguments,1);q.push(R),L.apply(this,q)}function R(_,q){if(_)return B(_);if(!q)return B(null);I(T)}R(null,!0)}function pf(p,k,B){B=Dn(B||ft);var I=x(p),L=function(T){if(T)return B(T);var R=o(arguments,1);if(k.apply(this,R))return I(L);B.apply(null,[null].concat(R))};I(L)}function CC(p,k,B){pf(p,function(){return!k.apply(this,arguments)},B)}function bC(p,k,B){B=Dn(B||ft);var I=x(k),L=x(p);function T(_){if(_)return B(_);L(R)}function R(_,q){if(_)return B(_);if(!q)return B(null);I(T)}L(R)}function vC(p){return function(k,B,I){return p(k,I)}}function ya(p,k,B){yo(p,vC(x(k)),B)}function zs(p,k,B,I){ma(k)(p,vC(x(B)),I)}var Us=ee(zs,1);function Cf(p){return D(p)?p:i(function(k,B){var I=!0;k.push(function(){var L=arguments;I?m(function(){B.apply(null,L)}):B.apply(null,L)}),p.apply(this,k),I=!1})}function wa(p){return!p}var Ba=ai(mi(wa,wa)),Vs=di(mi(wa,wa)),Ea=ee(Vs,1);function kC(p){return function(k){return k==null?void 0:k[p]}}function Ej(p,k,B,I){var L=new Array(k.length);p(k,function(T,R,_){B(T,function(q,Q){L[R]=!!Q,_(q)})},function(T){if(T)return I(T);for(var R=[],_=0;_<k.length;_++)L[_]&&R.push(k[_]);I(null,R)})}function Ij(p,k,B,I){var L=[];p(k,function(T,R,_){B(T,function(q,Q){q?_(q):(Q&&L.push({index:R,value:T}),_())})},function(T){T?I(T):I(null,hi(L.sort(function(R,_){return R.index-_.index}),kC("value")))})}function bf(p,k,B,I){var L=Ps(k)?Ej:Ij;L(p,k,x(B),I||ft)}var Ia=ai(bf),qs=di(bf),xa=ee(qs,1);function yC(p,k){var B=Dn(k||ft),I=x(Cf(p));function L(T){if(T)return B(T);I(L)}L()}var Sa=function(p,k,B,I){I=I||ft;var L=x(B);ui(p,k,function(T,R){L(T,function(_,q){return _?R(_):R(null,{key:q,val:T})})},function(T,R){for(var _={},q=Object.prototype.hasOwnProperty,Q=0;Q<R.length;Q++)if(R[Q]){var W=R[Q].key,X=R[Q].val;q.call(_,W)?_[W].push(X):_[W]=[X]}return I(T,_)})},wC=ee(Sa,1/0),BC=ee(Sa,1),EC=mC("log");function Ta(p,k,B,I){I=ko(I||ft);var L={},T=x(B);dr(p,k,function(R,_,q){T(R,_,function(Q,W){if(Q)return q(Q);L[_]=W,q()})},function(R){I(R,L)})}var IC=ee(Ta,1/0),xC=ee(Ta,1);function SC(p,k){return k in p}function TC(p,k){var B=Object.create(null),I=Object.create(null);k=k||Hs;var L=x(p),T=i(function(_,q){var Q=k.apply(null,_);SC(B,Q)?m(function(){q.apply(null,B[Q])}):SC(I,Q)?I[Q].push(q):(I[Q]=[q],L.apply(null,_.concat(function(){var W=o(arguments);B[Q]=W;var X=I[Q];delete I[Q];for(var xt=0,ie=X.length;xt<ie;xt++)X[xt].apply(null,W)})))});return T.memo=B,T.unmemoized=p,T}var Da;c?Da=process.nextTick:l?Da=setImmediate:Da=a;var DC=h(Da);function vf(p,k,B){B=B||ft;var I=Ps(k)?[]:{};p(k,function(L,T,R){x(L)(function(_,q){arguments.length>2&&(q=o(arguments,1)),I[T]=q,R(_)})},function(L){B(L,I)})}function LC(p,k){vf(yo,p,k)}function MC(p,k,B){vf(ma(k),p,B)}var kf=function(p,k){var B=x(p);return lC(function(I,L){B(I[0],L)},k,1)},RC=function(p,k){var B=kf(p,k);return B.push=function(I,L,T){if(T==null&&(T=ft),typeof T!="function")throw new Error("task callback must be a function");if(B.started=!0,un(I)||(I=[I]),I.length===0)return m(function(){B.drain()});L=L||0;for(var R=B._tasks.head;R&&L>=R.priority;)R=R.next;for(var _=0,q=I.length;_<q;_++){var Q={data:I[_],priority:L,callback:T};R?B._tasks.insertBefore(R,Q):B._tasks.push(Q)}m(B.process)},delete B.unshift,B};function OC(p,k){if(k=ko(k||ft),!un(p))return k(new TypeError("First argument to race must be an array of functions"));if(!p.length)return k();for(var B=0,I=p.length;B<I;B++)x(p[B])(k)}function La(p,k,B,I){var L=o(p).reverse();wo(L,k,B,I)}function Ma(p){var k=x(p);return i(function(I,L){return I.push(function(R,_){if(R)L(null,{error:R});else{var q;arguments.length<=2?q=_:q=o(arguments,1),L(null,{value:q})}}),k.apply(this,I)})}function AC(p){var k;return un(p)?k=hi(p,Ma):(k={},js(p,function(B,I){k[I]=Ma.call(this,B)})),k}function _C(p,k,B,I){bf(p,k,function(L,T){B(L,function(R,_){T(R,!_)})},I)}var NC=ai(_C),yf=di(_C),PC=ee(yf,1);function $C(p){return function(){return p}}function Ra(p,k,B){var I=5,L=0,T={times:I,intervalFunc:$C(L)};function R(W,X){if(typeof X=="object")W.times=+X.times||I,W.intervalFunc=typeof X.interval=="function"?X.interval:$C(+X.interval||L),W.errorFilter=X.errorFilter;else if(typeof X=="number"||typeof X=="string")W.times=+X||I;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof p=="function"?(B=k||ft,k=p):(R(T,p),B=B||ft),typeof k!="function")throw new Error("Invalid arguments for async.retry");var _=x(k),q=1;function Q(){_(function(W){W&&q++<T.times&&(typeof T.errorFilter!="function"||T.errorFilter(W))?setTimeout(Q,T.intervalFunc(q)):B.apply(null,arguments)})}Q()}var jC=function(p,k){k||(k=p,p=null);var B=x(k);return i(function(I,L){function T(R){B.apply(null,I.concat(R))}p?Ra(p,T,L):Ra(T,L)})};function HC(p,k){vf(fi,p,k)}var Oa=ai(mi(Boolean,Hs)),Ws=di(mi(Boolean,Hs)),Aa=ee(Ws,1);function FC(p,k,B){var I=x(k);ga(p,function(T,R){I(T,function(_,q){if(_)return R(_);R(null,{value:T,criteria:q})})},function(T,R){if(T)return B(T);B(null,hi(R.sort(L),kC("value")))});function L(T,R){var _=T.criteria,q=R.criteria;return _<q?-1:_>q?1:0}}function zC(p,k,B){var I=x(p);return i(function(L,T){var R=!1,_;function q(){var Q=p.name||"anonymous",W=new Error('Callback function "'+Q+'" timed out.');W.code="ETIMEDOUT",B&&(W.info=B),R=!0,T(W)}L.push(function(){R||(T.apply(null,arguments),clearTimeout(_))}),_=setTimeout(q,k),I.apply(null,L)})}var xj=Math.ceil,Sj=Math.max;function Tj(p,k,B,I){for(var L=-1,T=Sj(xj((k-p)/(B||1)),0),R=Array(T);T--;)R[I?T:++L]=p,p+=B;return R}function _a(p,k,B,I){var L=x(B);ui(Tj(0,p,1),k,L,I)}var UC=ee(_a,1/0),VC=ee(_a,1);function qC(p,k,B,I){arguments.length<=3&&(I=B,B=k,k=un(p)?[]:{}),I=ko(I||ft);var L=x(B);yo(p,function(T,R,_){L(k,T,R,_)},function(T){I(T,k)})}function WC(p,k){var B=null,I;k=k||ft,Us(p,function(L,T){x(L)(function(R,_){arguments.length>2?I=o(arguments,1):I=_,B=R,T(!R)})},function(){k(B,I)})}function GC(p){return function(){return(p.unmemoized||p).apply(null,arguments)}}function wf(p,k,B){B=Dn(B||ft);var I=x(k);if(!p())return B(null);var L=function(T){if(T)return B(T);if(p())return I(L);var R=o(arguments,1);B.apply(null,[null].concat(R))};I(L)}function ZC(p,k,B){wf(function(){return!p.apply(this,arguments)},k,B)}var YC=function(p,k){if(k=ko(k||ft),!un(p))return k(new Error("First argument to waterfall must be an array of functions"));if(!p.length)return k();var B=0;function I(T){var R=x(p[B++]);T.push(Dn(L)),R.apply(null,T)}function L(T){if(T||B===p.length)return k.apply(null,arguments);I(o(arguments,1))}I([])},Dj={apply:r,applyEach:Z3,applyEachSeries:Y3,asyncify:C,auto:uf,autoInject:iC,cargo:cC,compose:aC,concat:dC,concatLimit:ba,concatSeries:uC,constant:hC,detect:va,detectLimit:Fs,detectSeries:ka,dir:gC,doDuring:pC,doUntil:CC,doWhilst:pf,during:bC,each:ya,eachLimit:zs,eachOf:yo,eachOfLimit:dr,eachOfSeries:fi,eachSeries:Us,ensureAsync:Cf,every:Ba,everyLimit:Vs,everySeries:Ea,filter:Ia,filterLimit:qs,filterSeries:xa,forever:yC,groupBy:wC,groupByLimit:Sa,groupBySeries:BC,log:EC,map:ga,mapLimit:ui,mapSeries:df,mapValues:IC,mapValuesLimit:Ta,mapValuesSeries:xC,memoize:TC,nextTick:DC,parallel:LC,parallelLimit:MC,priorityQueue:RC,queue:kf,race:OC,reduce:wo,reduceRight:La,reflect:Ma,reflectAll:AC,reject:NC,rejectLimit:yf,rejectSeries:PC,retry:Ra,retryable:jC,seq:gf,series:HC,setImmediate:m,some:Oa,someLimit:Ws,someSeries:Aa,sortBy:FC,timeout:zC,times:UC,timesLimit:_a,timesSeries:VC,transform:qC,tryEach:WC,unmemoize:GC,until:ZC,waterfall:YC,whilst:wf,all:Ba,allLimit:Vs,allSeries:Ea,any:Oa,anyLimit:Ws,anySeries:Aa,find:va,findLimit:Fs,findSeries:ka,forEach:ya,forEachSeries:Us,forEachLimit:zs,forEachOf:yo,forEachOfSeries:fi,forEachOfLimit:dr,inject:wo,foldl:wo,foldr:La,select:Ia,selectLimit:qs,selectSeries:xa,wrapSync:C};e.default=Dj,e.apply=r,e.applyEach=Z3,e.applyEachSeries=Y3,e.asyncify=C,e.auto=uf,e.autoInject=iC,e.cargo=cC,e.compose=aC,e.concat=dC,e.concatLimit=ba,e.concatSeries=uC,e.constant=hC,e.detect=va,e.detectLimit=Fs,e.detectSeries=ka,e.dir=gC,e.doDuring=pC,e.doUntil=CC,e.doWhilst=pf,e.during=bC,e.each=ya,e.eachLimit=zs,e.eachOf=yo,e.eachOfLimit=dr,e.eachOfSeries=fi,e.eachSeries=Us,e.ensureAsync=Cf,e.every=Ba,e.everyLimit=Vs,e.everySeries=Ea,e.filter=Ia,e.filterLimit=qs,e.filterSeries=xa,e.forever=yC,e.groupBy=wC,e.groupByLimit=Sa,e.groupBySeries=BC,e.log=EC,e.map=ga,e.mapLimit=ui,e.mapSeries=df,e.mapValues=IC,e.mapValuesLimit=Ta,e.mapValuesSeries=xC,e.memoize=TC,e.nextTick=DC,e.parallel=LC,e.parallelLimit=MC,e.priorityQueue=RC,e.queue=kf,e.race=OC,e.reduce=wo,e.reduceRight=La,e.reflect=Ma,e.reflectAll=AC,e.reject=NC,e.rejectLimit=yf,e.rejectSeries=PC,e.retry=Ra,e.retryable=jC,e.seq=gf,e.series=HC,e.setImmediate=m,e.some=Oa,e.someLimit=Ws,e.someSeries=Aa,e.sortBy=FC,e.timeout=zC,e.times=UC,e.timesLimit=_a,e.timesSeries=VC,e.transform=qC,e.tryEach=WC,e.unmemoize=GC,e.until=ZC,e.waterfall=YC,e.whilst=wf,e.all=Ba,e.allLimit=Vs,e.allSeries=Ea,e.any=Oa,e.anyLimit=Ws,e.anySeries=Aa,e.find=va,e.findLimit=Fs,e.findSeries=ka,e.forEach=ya,e.forEachSeries=Us,e.forEachLimit=zs,e.forEachOf=yo,e.forEachOfSeries=fi,e.forEachOfLimit=dr,e.inject=wo,e.foldl=wo,e.foldr=La,e.select=Ia,e.selectLimit=qs,e.selectSeries=xa,e.wrapSync=C,Object.defineProperty(e,"__esModule",{value:!0})})})(Tu,Tu.exports);var M2={exports:{}},Du=M2.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)?Du(n,t):i};Du.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=Du(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 R2=co,Xk=D2,ty=L2,Jl=en,Lu=Tu.exports,ey=M2.exports,O2=qo.ACTIONS,A2=Pt;function Pt(n,t){if(R2.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}R2.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||ey();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);Lu.parallel([function(i){Lu.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();Lu.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?O2.presenceSubscribe:O2.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=Jl.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=Jl.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 Jl.nextTick(t,n);n&&this.emit("error",n)},Pt.prototype._createLocalPresence=function(n){return new Xk(this,n)},Pt.prototype._createRemotePresence=function(n){return new ty(this,n)},Pt.prototype._callEachOrEmit=function(n,t){var e=Jl.callEach(n,t);!e&&t&&this.emit("error",t)};var Gi=D2,_2=Gl,ny=en,N2=_2.CODES,oy=on;function on(n,t){Gi.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()}on.prototype=Object.create(Gi.prototype),on.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:N2.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,Gi.prototype.submit.call(this,n,t)},on.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),Gi.prototype.destroy.call(this,n)},on.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={})})}},on.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)},on.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)}},on.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},on.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},on.prototype._message=function(){var n=Gi.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},on.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!ny.supportsPresence(o))throw new _2(N2.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var P2={};(function(n){var t=Vi,e=Gl,o=en,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,h=t.map[a.type];if(!h)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(a.data),l.type=h.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(h){return new e(r.ERR_OT_OP_NOT_APPLIED,h.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(h){return h}}}c.v!=null&&c.v++},n.applyOps=function(l,c,a){a=a||{};for(var h=0;h<c.length;h++){var f=c[h];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 h=this.checkOp(c);if(h)return h;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 h=l.data;a.length>1&&(h=o.clone(h));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=h,w=0;w<C.length;w++){var E=C[w];Object.prototype.toString.call(v)=="[object Array]"?C[w]=+E:v.constructor===Object&&(C[w]=E.toString()),v=v[E]}f<a.length-1&&(h=t.defaultType.apply(h,[m]))}}}}})(P2);var Zi=L2,ry=P2,iy=Pe;function Pe(n,t){Zi.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(Zi.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),Zi.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()},Zi.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Zi.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++):ry.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 $2=A2,sy=oy,ly=iy;function Or(n,t,e){var o=Or.channel(t,e);$2.call(this,n,o),this.collection=t,this.id=e}var cy=Or;Or.prototype=Object.create($2.prototype),Or.channel=function(n,t){return n+"."+t},Or.prototype._createLocalPresence=function(n){return new sy(this,n)},Or.prototype._createRemotePresence=function(n){return new ly(this,n)};var ay=dy;function dy(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var uy=ay,j2=co,H2=Yi;function Yi(n,t,e,o,r){if(j2.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}j2.mixin(Yi),Yi.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Yi.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Yi.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new uy(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var F2=H2,hy=en,fy=qo.ACTIONS,my=Mu;function Mu(n,t,e,o,r,i){if(F2.call(this,n,t,e,o,i),!hy.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}Mu.prototype=Object.create(F2.prototype),Mu.prototype._message=function(){return{a:fy.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var z2=H2,gy=en,py=qo.ACTIONS,Cy=Ru;function Ru(n,t,e,o,r,i){if(z2.call(this,n,t,e,o,i),!gy.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}Ru.prototype=Object.create(z2.prototype),Ru.prototype._message=function(){return{a:py.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var by=Vk,vy=Yk,ky=A2,U2=cy,yy=my,wy=Cy,V2=co,Ar=Gl,pt=qo.ACTIONS,q2=Vi,rn=en,Qi=k2,Ki=Ar.CODES;function W2(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var By=J;function J(n){V2.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=W2(n),this.bindToSocket(n)}V2.mixin(J),J.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=W2(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{Qi.warn("Failed to parse message",o);return}e.debug&&Qi.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){rn.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)}},J.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=G2(n.error,n),delete n.error),n.a){case pt.initLegacy:return this._handleLegacyInit(n);case pt.handshake:return this._handleHandshake(t,n);case pt.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case pt.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case pt.queryUnsubscribe:return;case pt.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 pt.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case pt.bulkSubscribe:case pt.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case pt.snapshotFetch:case pt.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case pt.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case pt.subscribe:case pt.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case pt.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case pt.presence:return this._handlePresence(t,n);case pt.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case pt.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case pt.presenceRequest:return this._handlePresenceRequest(t,n);case pt.pingPong:return this._handlePingPong(t);default:Qi.warn("Ignoring unrecognized message",n)}};function G2(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}J.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](G2(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 Qi.error("Invalid bulk message",t)},J.prototype._reset=function(){this.agent=null},J.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 Ar(Ki.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)}},J.prototype.startBulk=function(){this.bulk||(this.bulk={})},J.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},J.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})}},J.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)}},J.prototype.sendFetch=function(n){return this._sendActions(pt.fetch,n,n.version)},J.prototype.sendSubscribe=function(n){return this._sendActions(pt.subscribe,n,n.version)},J.prototype.sendUnsubscribe=function(n){return this._sendActions(pt.unsubscribe,n)},J.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:pt.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)},J.prototype.send=function(n){this.debug&&Qi.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},J.prototype.ping=function(){if(!this.canSend)throw new Ar(Ki.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:pt.pingPong};this.send(n)},J.prototype.close=function(){this.socket.close()},J.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},J.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new by(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},J.prototype._destroyDoc=function(n){!n._wantsDestroy||(rn.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},J.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},J.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new vy(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},J.prototype._destroyQuery=function(n){delete this.queries[n.id]},J.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(pt.queryFetch,n,t,e,o)},J.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(pt.querySubscribe,n,t,e,o)},J.prototype.hasPending=function(){return!!(this._firstDoc(Xl)||this._firstQuery(Xl)||this._firstSnapshotRequest())};function Xl(n){return n.hasPending()}J.prototype.hasWritePending=function(){return!!this._firstDoc(Ey)};function Ey(n){return n.hasWritePending()}J.prototype.whenNothingPending=function(n){var t=this._firstDoc(Xl);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Xl);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}rn.nextTick(n)},J.prototype._nothingPendingRetry=function(n){var t=this;return function(){rn.nextTick(function(){t.whenNothingPending(n)})}},J.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}}},J.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},J.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},J.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new yy(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},J.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new wy(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},J.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},J.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},J.prototype._initializeHandshake=function(){this.send({a:pt.handshake,id:this.id})},J.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},J.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},J.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new Ar(Ki.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(q2.map[n.type]!==q2.defaultType)return this.emit("error",new Ar(Ki.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new Ar(Ki.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},J.prototype.getPresence=function(n){var t=this,e=rn.digOrCreate(this._presences,n,function(){return new ky(t,n)});return e._wantsDestroy=!1,e},J.prototype.getDocPresence=function(n,t){var e=U2.channel(n,t),o=this,r=rn.digOrCreate(this._presences,e,function(){return new U2(o,n,t)});return r._wantsDestroy=!1,r},J.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},J.prototype._addPresence=function(n){rn.digOrCreate(this._presences,n.channel,function(){return n})},J.prototype._handlePresenceSubscribe=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},J.prototype._handlePresenceUnsubscribe=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},J.prototype._handlePresence=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},J.prototype._handlePresenceRequest=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var Z2=By,Iy=Vi;const tc={err:1001,msg:"user auth error",name:"AuthError"},xy={err:1002,msg:"you don't have required permission",name:"PermissionError"},Ou={err:1003,msg:"Too many user connected",name:"MaxUserError"},Ji={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},Sy={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},Ty={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},Xi="x-live-editor-token",ec="x-live-editor-base-url",ae=y("auth-connection");function Dy(n){try{n()}catch(t){ae.error(t)}}class Ly{constructor(t,e){u(this,"connection");u(this,"ws");u(this,"retryCount");u(this,"events",new If.EventEmitter);u(this,"token",null);u(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 Do(this.getBaseURL())}async auth(t){d(ae,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[Xi]:t.token,[ec]: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:{[ec]:Do(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new E9.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(Z2.prototype),d(ae,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}}},Z2.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,ae.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){ae.error(t),setTimeout(()=>this.handleAuthError(),0)}}else ae.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(tc.msg);t.code=tc.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(Ji.msg);t.code=Ji.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===tc.err)ae.warn("auth error"),this.handleAuthError();else if(o===Ou.err)ae.warn(Ou.msg),this.emitMaxUsersError();else if(o===Ji.err){ae.warn(Ji.msg);try{this.emitRequestReloadError()}catch(r){ae.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else ae.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError()}get(t,e){return d(ae,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(d(ae,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){d(ae,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){d(ae,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(),Dy(()=>{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()}}y("utils/file");function My(){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}My();async function Ry(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new I9.Hash;for(let s=0;s<o;s++){const l=s*102400;let c=l+102400;c>e&&(c=e);const h=await n.slice(l,c,n.type).arrayBuffer();r.update(new Uint8Array(h))}const i=r.digest();return Do(i)}const kn=y("sharedb-doc/client");class Oy{constructor(t,e,o){u(this,"connection");u(this,"auth");u(this,"doc",null);u(this,"reauthFunc");u(this,"clientId",N());u(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});d(kn,!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),kn.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;Iy.register(Ys.type),this.connection=new Ly(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return d(kn,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,{[Xi]: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=>{kn.info(`on progress: ${C.loaded}`);let v=C.loaded*100/s;v>100&&(v=100),r(v)},c=await Ry(e),a=await this.getFileUrlByHash(t,c,e.name,e.size,o);if(a)return r(-1),a;let h=t;i!=null&&i.thumbnail&&(h+="/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(h,{method:"post",data:f,withCredentials:!0,headers:{...o},onUploadProgress:l});return kn.info(m),r(100),Array.isArray(m.data)?m.data[0]:m.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;d(kn,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[Xi]:this.connection.token},e,o);return d(kn,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(kn,o,"no token"),c.headers={...c.headers,[Xi]:o,[ec]:this.connection.getBase64BaseURL()};try{return await w9.default(t,c)}catch(a){if(r=a,((i=a==null?void 0:a.response)==null?void 0:i.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw a;o=h.token;continue}throw(s=a.response)!=null&&s.data&&(a.responseData=a.response.data),a}}throw d(kn,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=B9.default(s,h=>!!h.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let a;return c?(d(kn,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/${Do(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 Ay(){return{blocks:[{id:N(),type:"text",text:[]}],comments:{},meta:{}}}const Au=y("block-ids");class _y{constructor(){u(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(Au,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(Au,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 Ny{constructor(){u(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new _y,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(Au,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class Y2{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 Nt=y("op-parser");function _r(n){return n==="blocks"?"root":n}class Py{constructor(t,e){u(this,"updatingBlockDataDeltaMap",new Map);u(this,"blockIds",new Ny);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&&(Nt.debug(`ignore update object data before delete block: ${JSON.stringify(r)}`),this.updatingBlockDataDeltaMap.delete(o)),this.handler.onDeleteBlock(_r(t),e,this.local)}onInsertBlock(t,e,o){this.blockIds.onInsertBlock(t,e),this.handler.onInsertBlock(_r(t),e,o,this.local)}onUpdateBlockText(t,e,o){this.handler.onUpdateBlockText(_r(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 Y2,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 Y2,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(_r(o),r,e.toDocBlockDelta(),this.local)})}}class Q2{}class _u{constructor(t){u(this,"key");this.key=t}}function $y(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 h=c[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=i.i;d(Nt,s.id,"block id is required"),d(Nt,s.type,"block type is required");for(let l=1;l<o.length;l++){const c=o[l],a=c[0],h=c[1];s[a]=h.i}return e.onInsertBlock(n,r,s),!0}function Nu(n,t,e,o){if(e==="upsert"&&$y(n,t,o))return;d(Nt,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(Nt,typeof c=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),d(Nt,c.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),r.splice(0,2),e==="upsert"){const h=c.e;o.onUpdateBlockText(n,i,h)}d(Nt,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){d(Nt,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const c=l[0];d(Nt,typeof c=="string",`invalid block op: key ${JSON.stringify(c)}`);const a=l[1];if(c==="text"){if(d(Nt,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 _u(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 Q2),e==="upsert"&&c.i&&o.onInsertBlock(n,i,c.i),r.shift()}else{d(Nt,typeof l=="string","data is not string"),d(Nt,l!=="text","data !== 'text'"),d(Nt,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 _u(c)),e==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Q2?o.onDeleteBlock(n,i):l instanceof _u?o.onDeleteBlockData(n,i,l.key):d(Nt,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function jy(n,t,e,o){Nt.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function Hy(n,t,e,o){const r=n[1],i=n[2];d(Nt,r,`invalid comment op, no commentId: ${JSON.stringify(n)}`),d(Nt,i,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof i=="string"?Nt.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):Nt.error(`unknown comment op, ${JSON.stringify(n)}`)}function Pu(n,t,e,o){const r=n[0];if(Array.isArray(r)){r.forEach(l=>{Pu(l,t,e,o)});return}const i=r;if(d(Nt,typeof i=="string",`invalid container id: ${JSON.stringify(n)}`),i==="meta"){jy(n);return}if(i==="comments"){Hy(n,t,e,o);return}const s=i;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(l=>{Nu(s,l,t,e)}):n.slice(1).forEach(l=>{Nu(s,l,t,e)});else if(typeof n[1]=="object"){const l=n[1];l.r&&t==="remove"&&o.onDeleteContainer(_r(s),e.local),l.i&&t==="upsert"&&o.onCreateContainer(_r(s),l.i,e.local)}else d(Nt,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Nu(s,n.slice(1),t,e)}function K2(n,t,e){const o=new Py(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=>{Pu(c,i,o,t)}):Pu(s,i,o,t)}o.executeUpdateBlockDataActions()}const Fy=y("sharedb-comments");function $u(n){if(n.doc)return Y.default(n.doc);const t=n.blocks;d(Fy,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 ju(n,t){const e={...n,doc:t};return delete e.blocks,Y.default(e)}const Bt=y("sharedb-doc/doc-container"),X2="ot-json1";Ys.type.registerSubtype(xk.type),Ys.type.name=X2,Ys.type.invert=null;class ts extends vi{constructor(e,o,r=!0){super();u(this,"doc");u(this,"client");u(this,"localPresence");u(this,"remoteCaretHandler",new Ek);u(this,"batching",0);u(this,"status","clean");u(this,"disableLogout");u(this,"destroyed",!1);u(this,"handleNothingPending",()=>{this.setStatus("clean")});u(this,"handleCreate",()=>{this.handleReload("doc created")});u(this,"handleDel",()=>{});u(this,"handleReload",e=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})});u(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()});u(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});u(this,"insertObject",async(e,o,r)=>{const i=[e,o,{i:r}];return this.submitOp(i)});u(this,"deleteObject",async(e,o)=>{const r=[e,o,{r:!0}];return this.submitOp(r)});u(this,"replaceObject",async(e,o,r)=>{const i=[e,o,{r:!0,i:r}];return this.submitOp(i)});u(this,"updateObject",async(e,o,r)=>{const i=this.data()[e][o],s=[e,o];return Object.entries(r).forEach(([l,c])=>{if(!Zs.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)});u(this,"broadcastMessage",async e=>{const o={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});u(this,"data",()=>this.doc.data);u(this,"submitOp",async e=>new Promise((o,r)=>{if(this.destroyed){Bt.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(Bt.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),Bt.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(Bt.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));u(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,X2,i=>{i?r(i):o()})}));u(this,"submitInsertChildContainer",async(e,o)=>{const r=[lo(e),{i:o}];return this.submitOp(r)});u(this,"submitDeleteChildContainer",async e=>{const o=[lo(e),{r:!0}];return this.submitOp(o)});u(this,"submitInsertBlock",async(e,o,r)=>{const i=[lo(e),o,{i:r}];return this.submitOp(i)});u(this,"submitDeleteBlock",async(e,o)=>{const r=[lo(e),o,{r:!0}];return this.submitOp(r)});u(this,"submitUpdateBlockData",async(e,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[lo(e),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c)){const h={r:!0,i:a};i.push([c,h])}});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 h={i:a};i.push([c,h])}),this.submitOp(i)});u(this,"submitUpdateRichText",async(e,o,r)=>{const i=[lo(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});u(this,"handleOp",(e,o,r)=>{if(this.destroyed){Bt.warn("handleOp: destroyed");return}K2(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(Bt,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new Oy(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new ts(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||Ay())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw Bt.error(o),Bt.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 zi(this.data())}getContainerBlocks(e){const o=this.data();d(Bt,o,"no doc data");const r=o[lo(e)];return d(Bt,r,`no container data: ${e}`),Y.default(r)}getBlockData(e,o){const r=this.data();d(Bt,r,"no doc data");const i=r[lo(e)];d(Bt,i,`no container data: ${e}`);const s=i[o];return d(Bt,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(Bt,i.text,"no block text");const s=Y.default(i.text);this.submitUpdateRichText(e,o,r);const l=oe.apply(s,r);return d(Bt,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 $u(o)}localCreateComment(e,o){const r=ju(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=ju(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(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Rr(e),o,r)})}onInsertBlock(e,o,r,i){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Rr(e),o,r,i)})}onUpdateBlockData(e,o,r,i){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Rr(e),o,r,i)})}onUpdateBlockText(e,o,r,i){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Rr(e),o,r,i)})}onDeleteContainer(e,o){d(Bt,this.callbacks.length>0,"no callbacks"),d(Bt,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,Rr(e),o)})}onCreateContainer(e,o,r){d(Bt,this.callbacks.length>0,"no callbacks"),d(Bt,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,Rr(e),o,r)})}onDeleteComment(e,o){d(Bt,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(Bt,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(Bt,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 zi(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return zi(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:zi(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:zi(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){K2(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}y("remote-cursor");class t0{constructor(t){u(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});u(this,"broadcastCaretPos",Qt.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));u(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 e0=y("remote-cursor-decorator");class Hu{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(e0,typeof s=="string","invalid path containerId"),d(e0,typeof l=="number","invalid path blockIndex");const c=t.doc.getBlockData(s,l),a=ce(o);return r.getSimpleCursors(c.id).forEach((f,m)=>{m>a&&(m=a);const C=f.map(w=>({id:N(),type:"remote-cursor",name:w.user.displayName,time:w.time,rainbowIndex:w.user.rainbowIndex})),v=i.get(m);v?v.push(...C):i.set(m,C)}),{insertions:i}}}class n0 extends Wt.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Ct(Cr(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=z(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 zy(n,t){n.addCustom("child-block-tracker",()=>new n0(n)).addListener("change",t)}function Uy(n,t){n.addCustom("child-block-tracker",()=>new n0(n)).removeListener("change",t)}const JH="",Vy={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},qy={colorPalette:{colorDesc:"Text Color",backgroundDesc:"Background Color",reset:"Reset"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}};S.mergeLang({"zh-CN":Vy,"en-US":qy});const XH="";y("button");function Vn(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&&M(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0)),i}function o0(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}const uo=y("filterable-list");function Wy(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")&&M(t,"selected"),t}function r0(n){const t=b("div",["list-root"],null);return n.forEach(e=>{t.appendChild(Wy(e))}),t}function i0(n,t){let e=n;return t&&(e=n.map(o=>({...o,states:o.id===t?["selected"]:void 0}))),e}function Gy(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=r0(i0(n,t==null?void 0:t.initialSelectedId));return s.appendChild(l),e}function s0(n,t,e){const o=n.querySelector(".list");d(uo,o,"no list root");const r=r0(i0(t,e)),i=o.querySelector(".list-root");if(d(uo,i,"no exists menu"),Ii(i,r),e){const s=o.querySelector(".list-item.selected");s&&(d(uo,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class Zy{constructor(t,e){u(this,"root");u(this,"visibleItems");u(this,"selectedId");u(this,"filter","");u(this,"onSelected",null);u(this,"handleKeydown",t=>{this.processKeyDown(t)});u(this,"handleInputChanged",()=>{const t=this.root.querySelector(".filter-input");d(uo,t,"no input");const e=t.value.toLocaleLowerCase();this.setFilter(e)});u(this,"handleClick",t=>{this.processClick(t)});var o;this.items=t,this.options=e,this.root=Gy(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(uo,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(uo,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,s0(this.root,this.visibleItems,t)}focus(){const t=this.root.querySelector(".filter-input");d(uo,t,"no input"),t.focus()}reset(){this.setFilter("");const t=this.root.querySelector(".filter-input");d(uo,t,"no input"),t.value=""}setFilter(t){this.filter!==t&&(this.filter=t,this.visibleItems=this.items.filter(e=>e.name.toLocaleLowerCase().includes(t)),s0(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 Yy extends Zy{constructor(e,o,r){super(e,r);u(this,"tippyInstance");u(this,"onShow",null);u(this,"onHide",null);u(this,"custom",null);u(this,"handleShow",()=>{this.onShow&&this.onShow(this)});u(this,"handleHide",()=>{this.onHide&&this.onHide(this)});u(this,"handleShown",()=>{this.focus()});this.tippyInstance=Sf.default(o,{interactive:!0,content:this.root,trigger:"manual",triggerTarget:null,hideOnClick:!0,arrow:!1,theme:"dropdown-list",offset:[0,0],onHide:this.handleHide,onShow:this.handleShow,onShown:this.handleShown})}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(e){this.tippyInstance.setProps({getReferenceClientRect:()=>e.getBoundingClientRect()}),this.reset(),this.tippyInstance.show(),this.focus()}processKeyDown(e){super.processKeyDown(e),(e.key==="Esc"||e.key==="Enter")&&this.tippyInstance.hide()}processClick(e){super.processClick(e);const o=e.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.tippyInstance.hide()}}const tF="",eF="";function Qy(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 nF="",Nr=y("ui-command-bar-base"),Ky={itemElementTag:"div",tippyArrow:!1},of=class extends Wt.TypedEmitter{constructor(e,o,r){var i,s;super();u(this,"content");u(this,"items");u(this,"subBar",null);u(this,"parentItem",null);u(this,"closeable",null);u(this,"options");u(this,"id");u(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)}}}});u(this,"handleDocumentMouseDown",e=>{e.target instanceof Element&&(this.isInCommandBar(e.target)||this.close())});u(this,"handleHidden",()=>{this.close(),this.emit("close",this),sm(this.id)});u(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&M(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&im(this.id)});u(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)});u(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)&&(F(o,"selected"),this.emit("selectionChange",this,""))});u(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())}});u(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=_n(r);if(!vt(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={...Ky,...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&&F(o,"selected")}selectItem(e){const o=this.getSelectedItem();if(o){if(o.id===e)return;const i=o.id,s=this.getItemElementById(i);s&&F(s,"selected")}const r=this.getItemElementById(e);r?(M(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=of.createSubCommandBar(o,(l=this.closeable)!=null?l:this,e?{id:e}:{});this.subBar=i,this.subBar.on("click",(c,a,h)=>{this.emit("click",c,a,h)}),this.subBar.on("close",()=>{var c;(c=this.subBar)==null||c.destroy(),this.subBar=null,F(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),M(r,"active")}isInCommandBar(e){if(!e||!(e instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&vt(o,e)||vt(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(Nr,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(Nr,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(e){const o=e.getAttribute("data-id");return d(Nr,o,"no data-id attribute"),o}getItemElementById(e){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${e}"]`);return d(Nr,o,`no exists command item, id=${e}`),o}getParentCommandItemElement(e){if(!e||!(e instanceof Element))return null;if(lt(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(Nr,e.children&&e.children.length>0,"no item children");const i=(l=e.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return d(Nr,s,`no creator for command type: ${i}`),s(e,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let Pr=of;u(Pr,"commandBarCreators",new Map),y("ui-command-bar");class nc extends Pr{constructor(){super(...arguments);u(this,"tippyInstance",null)}manualShow(e,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=Sf.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]")}}function Jy(){const n={};for(let t=1;t<=8;t++)n[`heading-${t}`]={shortcut:`/h${t}`};return n}const Xy={"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"},...Jy()};function l0(n){var t,e,o;return(o=(e=n.shortcut)!=null?e:(t=Xy[n.id])==null?void 0:t.shortcut)!=null?o:""}const c0=`<?xml version="1.0" ?>
|
|
26
|
+
`)}function ou(n,t){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Do(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function ru(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=pb(n,t),r={};o.forEach(c=>{const a=n.doc.buildResourceUrl(c,{withToken:!0});r[c]=a}),t.meta={...e,resources:r}}function Cb(n,t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData||n.selection.range.isCollapsed())return;const e=Fl(n);ru(n,e);const o=eu(n,e),r=nu(n,e),i=ou(o,e);t.clipboardData.setData("text/html",i),t.clipboardData.setData("text/plain",r),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(e))}function bb(n){if(n.selection.range.isCollapsed())return;const t=Fl(n);ru(n,t);const e=eu(n,t),o=ou(e,t),r=new Blob([o],{type:"text/html"});il([{type:"text/html",data:r}])}async function iu(n,t){const e=Xd(n,t,!1);ru(n,e);const o=eu(n,e),r=nu(n,e),i=ou(o,e);return il([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}const su=y("editor-input");class vb{constructor(t,e){u(this,"editor");u(this,"composing",!1);u(this,"callbacks");u(this,"inputElement");u(this,"handleDocumentSelectionChange",()=>{setTimeout(()=>{var e;const t=(e=document.getSelection())==null?void 0:e.focusNode;t&&this.editor.contains(t)&&!Si(t)?(this.editor.emit("focus",this.editor),this.callbacks.onFocus(),this.editor.input.focus()):(this.editor.emit("blur",this.editor),this.callbacks.onBlur())},100)});u(this,"handleEditorSelectionChanged",()=>{const e=!this.editor.isWritable();this.inputElement.readOnly=e});u(this,"handleReadonlyChanged",()=>{this.handleEditorSelectionChanged()});u(this,"handleCompositionstart",t=>{this.composing=!0,this.callbacks.onCompositionStart(t)});u(this,"handleCompositionend",t=>{this.composing=!1,this.callbacks.onUpdateCompositionText(t,this.inputElement.value,!0),this.inputElement.value=""});u(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="")}});u(this,"handleKeyDown",t=>{if(!this.composing){if(this.callbacks.onKeyDown(t)){t.preventDefault(),t.stopPropagation();return}setTimeout(()=>{this.composing||(this.inputElement.value="")})}});u(this,"handleCopy",t=>{Cb(this.editor,t)});u(this,"handleCut",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}su.debug("on cut")});u(this,"handlePaste",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}this.callbacks.onPaste(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(),St.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(su,t===this.editor,"invalid editor"),this.callbacks.defaultInsertText(t,e,o,r,i)}defaultHandleKeydown(t,e){return d(su,t===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(t,e)}}function kb(n){const e=n.rootElement.getBoundingClientRect(),o=window.innerWidth,r=window.innerHeight,i=0-e.top+r/2,s=0-e.left+o/2,l=n.input.inputElement;l.style.left=`${s}px`,l.style.top=`${i}px`}const lu=y("editor-caret");class yb{constructor(t){u(this,"editor");u(this,"caretElem");u(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 Ut))return!1;const e=this.editor.getBlockById(t.blockId);return!!H(this.editor,e)}update(){if(Pf(this.editor.rootElement))return;const t=this.caretElem;if(this.hasCaret())t.style.display="";else{t.style.display="none",kb(this.editor);return}const{range:e}=this.editor.selection;d(lu,e.isCollapsed,"range is not collapsed");const o=e.start;d(lu,o instanceof Ut,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);d(lu,H(this.editor,r),"only text kind block can has caret");let i;const s=r.querySelector("span.inputting-insertion");s?(i=Io(s),i=new DOMRect(i.right,i.top,1,i.height)):i=Ae(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 h=this.editor.input.inputElement;h.style.left=`${c}px`,h.style.top=`${a+i.height-24}px`,St.isMobileSafari&&(h.style.left=`${c-4}px`,h.style.height=`${i.height}px`)}}function wb(n){Fm(n),n.selection.range.getSelectedBlocks().forEach(t=>zm(n,t.block,t.start,t.end))}function Ip(n){return _n(n.rootContainer).clientHeight}function Bb(n){return n.getFirstBlock().getBoundingClientRect().top}function Eb(n){return n.getLastBlock().getBoundingClientRect().bottom}function cu(n){const t=_n(n.rootContainer);return new DOMRect(t.clientLeft,t.clientTop,t.clientWidth,t.clientHeight)}function Ib(n,t){const e=cu(n),o=n.getBlockById(t.blockId),i=Ze(n,o,t);return So(e,i.x,i.y)&&So(e,i.right,i.bottom)}function xb(n,t){const e=cu(n),o=t.getBoundingClientRect();return o.top>=e.top&&o.top<=e.bottom||o.bottom<=e.bottom&&o.bottom>=e.top}function Sb(n,t){const e=cu(n),o=t.getBoundingClientRect();return So(e,o.x,o.y)||So(e,o.right,o.bottom)}function Tb(n){const t=n.selection,e=t.range.focus;if(!e.isSimple()){const a=e,h=n.getContainerById(a.childContainerId);Sb(n,h)||h.scrollIntoView();return}if(t.range.start.blockId===t.range.end.blockId){const a=n.getBlockById(t.range.start.blockId);if(De(a)&&xb(n,a))return}const o=e,r=n.getBlockById(o.blockId);if(Ib(n,o))return;const i=Ze(n,r,o),s=r.getBoundingClientRect(),l=At(r),c=b("div",["editor-block-anchor"],l);c.style.top=`${i.top-s.top}px`,Bi(c),setTimeout(()=>{c.remove()})}function Db(n,t){if(t.isCollapsed())return!1;const e=Kt(n.rootContainer),o=Gt(n.rootContainer),{start:r,end:i}=t;return r.blockId===G(e)&&r.offset===0&&i.blockId===G(o)&&i.offset===Z(n,o)}const zl=y("editor-selection");class Lb{constructor(t){u(this,"editor");u(this,"caret");u(this,"_range");u(this,"lastCaretRect");u(this,"handleBlockDelete",(t,e,o,r)=>{if(o||r.child)return;const i=this.range;if(lp(e,i)){zl.debug("adjust selection because remote deleted current block");const s=cp(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=G(e);this.caret=new yb(t);const r=$(o,0,"normal");this._range=Vt(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=$(t,e,"normal");let i;o&&(i=$(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=Vt(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),lt(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!Db(this.editor,r))&&F(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(),wb(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(!vr(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Ze(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){Tb(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=Z(this.editor,e)||d(zl,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||d(zl,!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&<(e,"focused")&&(F(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)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{F(t,"focused"),F(t,"child-focused")})}setBlockFocused(t){if(lt(t,"focused"))return!1;M(t,"focused");let e=j(t);for(;We(e);){const o=z(e);d(zl,o,"parent block not found"),M(o,"child-focused"),e=j(o)}return!0}}const xp=y("line-offset");function au(n){const t=n.selection.range.focus;d(xp,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!H(n,e))return $(e,0,"home");let r=fg(e,t).start;const{next:i}=gl(e,r);return i&&Re(i)&&xi(i)==="br"&&(r+=1),$(e,r,"home")}function du(n){const t=n.selection.range.focus;d(xp,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===Z(n,e)||!H(n,e))return $(e,0,"end");const o=fg(e,t);return $(e,o.end,"end")}function Mb(n){if(!n.selection.range.focus.isSimple())return;const e=au(n),o=du(n);!e||!o||n.selection.setSelection(e,o)}const Ne=y("block-text");function Sp(n,t,e){d(Ne,H(n,t),"not a text kind block"),d(Ne,me(t,e),"not a valid offset"),d(Ne,e>0&&e<=Z(n,t),`invalid offset: ${e}`);const o=Po(t,e),r=e-o;r===0&&d(Ne,!1,`no text before offset: ${e}`);const i=we(n,t),{middle:s}=Jt(i,o,r);d(Ne,s.length===1,"failed to split text to 3 parts");const l=s[0];return wd(l)?{op:l,charType:"box",offset:o,length:1}:{op:l,charType:tl(l.insert)?"space":"text",offset:o,length:l.insert.length}}function Tp(n,t,e){d(Ne,H(n,t),"not a text kind block"),d(Ne,me(t,e),"not a valid offset"),d(Ne,e>=0&&e<Z(n,t),`invalid offset: ${e}`);const r=Er(t,e)-e;r===0&&d(Ne,!1,`no text after offset: ${e}`);const i=we(n,t),{middle:s}=Jt(i,e,r);d(Ne,s.length===1,"failed to split text to 3 parts");const l=s[0];return wd(l)?{op:l,charType:"box",offset:e,length:1}:{op:l,charType:tl(l.insert)?"space":"text",offset:e,length:l.insert.length}}function Dp(n,t,e,o){let r=e;for(;r>0;){const i=Sp(n,t,r);if(i.charType!==o)return i;r-=i.length}return null}function Lp(n,t,e,o){const r=Z(n,t);let i=e;for(;i<r;){const s=Tp(n,t,i);if(s.charType!==o)return s;i+=s.length}return null}function Mp(n,t,e){if(d(Ne,H(n,t),"invalid blok type"),yt(n,t))return 0;const o=Sp(n,t,e);if(o.charType==="box")return e-1;let r=e;if(o.charType==="space"){const s=Dp(n,t,r,"space");if(!s||s.offset===0)return 0;if(s.charType==="box")return s.offset;r=s.offset}const i=Dp(n,t,r,"text");return i?i.offset+i.length:0}function Rp(n,t,e){if(d(Ne,H(n,t),"invalid blok type"),yt(n,t))return 0;const o=Tp(n,t,e);if(o.charType==="box")return e+1;let r=e;if(o.charType==="space"){const s=Lp(n,t,r,"space");if(!s||s.offset===0)return Z(n,t);if(s.charType==="box")return s.offset;r=s.offset}const i=Lp(n,t,r,"text");return i?i.offset:Z(n,t)}const Op=y("word-offset");function uu(n,t){const e=n.selection.range.focus;d(Op,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(yt(n,o))return $(o,0,"home");if(e.offset===0||!H(n,o)){const s=gt(o);if(!s)return null;const l=$(s,Z(n,s),"end");if(t==="select"&&H(n,s)){const c=Mp(n,s,l.offset);return $(s,c,"normal")}return l}const r=Mp(n,o,e.offset);return $(o,r,"normal")}function hu(n,t){const e=n.selection.range.focus;d(Op,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(yt(n,o))return $(o,0,"end");if(e.offset===Z(n,o)||!H(n,o)){const s=ht(o);if(!s)return null;const l=$(s,0,"home");if(t==="select"&&H(n,s)){const c=Rp(n,s,l.offset);return $(s,c,"end")}return l}const r=Rp(n,o,e.offset);return $(o,r,"normal")}function Rb(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!H(n,e))return;const o=uu(n,"select"),r=hu(n,"select");!o||!r||n.selection.setSelection(o,r)}const ge=y("adjust-selection-pos");function Ap(n){const t=[];for(;n;){const e=j(n);if(t.unshift(e),Ct(e))return t;const o=z(e);d(ge,o,"child container has not parent container"),n=o}d(ge,!1,"should not come here: getParentContainers")}function _p(n,t){for(;t;){const e=j(t);if(e===n)return t;const o=z(e);d(ge,o,"could not find parent block for a child container"),t=o}d(ge,!1,"no parent block in specified container")}function Ob(n,t){const e=Ap(n),o=Ap(t);d(ge,e.length>0&&o.length>0,"block has not parent container"),d(ge,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=_p(r,n),s=_p(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function Np(n,t){let e=z(t);for(d(ge,e,"element is not in a block");e;){const o=j(e);d(ge,We(o),"not a child container");const r=z(o);if(d(ge,r,"child container has not parent block"),r===n)return o;e=r}d(ge,!1,"failed to find parent container in complex block")}function Ul(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof Ut&&e instanceof Ut?{anchor:t,focus:e}:(d(ge,t instanceof Ye&&e instanceof Ye,"both start and end are not simple or complex"),ml(n,o,t,e));const i=j(o),s=j(r);if(i===s)return t instanceof Ye&&(t=$(o,0,"home")),e instanceof Ye&&(e=$(r,Z(n,r),"end")),d(ge,t instanceof Ut,"not valid position type"),d(ge,e instanceof Ut,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof Ut&&e instanceof Ye){const v=n.getContainerById(e.childContainerId);if(v===i)return{anchor:e,focus:e};const w=z(i);if(w&&w===z(v)){const E=bt(w,U(i)),L=bt(w,U(v));return ml(n,w,E,L)}}return null}const l=Xs(o,r)>0,{newBlock1:c,newBlock2:a}=Ob(o,r);if(c===a){const v=c,w=Np(v,o),E=Np(v,r);return t=bt(c,U(w)),e=bt(c,U(E)),ge.debug(`select in complex block: ${w.id}, ${E.id}`),ml(n,v,t,e)}let h=l?Z(n,c):0;c===o&&t instanceof Ut&&(h=t.offset);let m=l?0:Z(n,a);return a===r&&e instanceof Ut&&(m=e.offset),t=$(c,h,l?"end":"home"),e=$(a,m,l?"home":"end"),{anchor:t,focus:e}}const Ab=y("range-from-point");function Pp(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=z(i);if(!s||!n.contains(s))continue;const l=kt(n,s).getRangeFromPoint(n,s,t,e+o[r]);if(l)return l}return null}function $p(n,t,e,o){const r=t.getBoundingClientRect();if(o<=r.top){const l=Kt(t),c=$(l,0,"home");return new se(n,{anchor:c,focus:c})}const i=Gt(t),s=$(i,Z(n,i),"end");return new se(n,{anchor:s,focus:s})}function _b(n,t,e){const o=Pp(n,t,e);if(o){if(o instanceof se)return o;d(Ab,o instanceof Qe,`invalid range type: ${typeof o}`);const c=o,a=n.getContainerById(c.start.childContainerId);return $p(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=>mn(c));if(s.length===0)return null;const l=s.reduce((c,a)=>{const h=c.getBoundingClientRect(),f=a.getBoundingClientRect();return fn(h,t,e)>fn(f,t,e)?a:c});return $p(n,l,t,e)}class Nb{constructor(t){u(this,"editor");u(this,"startPos",null);u(this,"lastCaretRect");u(this,"mouseDownEvent",null);u(this,"handleMouseDown",t=>{this.mouseDownEvent=t;const e=_b(this.editor,t.x,t.y);if(e){if(e instanceof Qe)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()}});u(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=Pp(this.editor,t.x,t.y);if(!e)return;const o=Ul(this.editor,this.startPos,e.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});u(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){Rb(this.editor)}handleTripleClick(t){Mb(this.editor)}}const Pb=y("move-complex-block-position");function $b(n,t,e){const o=n.getBlockById(t.blockId);d(Pb,ct(n,o),"is not a complex block");const r=ye(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?bt(o,U(s)):null}const $i=y("move-simple-block-position");function jp(n,t){const e=Me(n,t);d($i,e.length>0,"complex block has not any child container");const o=e[0];return Kt(o)}function Hp(n,t){const e=Me(n,t);d($i,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Gt(o)}function Fp(n,t,e){const o=e?jp(n,t):Hp(n,t);return ct(n,o)?Fp(n,o,e):o}function jb(n,t){const e=n.getBlockById(t.blockId);return ct(n,e)&&t.offset===0?jp(n,e):pr(e)}function Hb(n,t){const e=n.getBlockById(t.blockId);return ct(n,e)&&t.offset===1?Hp(n,e):gr(e)}function fu(n){return n==="ArrowLeft"||n==="ArrowUp"}function mu(n,t,e){const o=j(t);if(Ct(o))return null;const r=z(o);d($i,r,"child container has not parent block"),d($i,ct(n,r),"is not a complex block");const i=ye(n,r).getNextContainer(n,r,o,e);return i?fu(e)?Gt(i):Kt(i):mu(n,r,e)}function Fb(n,t,e){const o=j(t);if(Ct(o))return null;const r=z(o);if(d($i,r,"child container has not parent block"),fu(e)){const l=gt(r);if(l)return l}else{const l=ht(r);if(l)return l}const i=mu(n,r,e);if(i)return i;let s=r;for(;!Ct(j(s));)s=z(j(s));return fu(e)?gt(s):ht(s)}function zb(n,t,e){return!ct(n,t)||ye(n,t).enableKeyboardSelect?t:Fp(n,t,e==="ArrowDown"||e==="ArrowRight")}function Ub(n,t,e){const o=n.getBlockById(t.blockId),i=kt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?jb(n,t):Hb(n,t);if(s||(s=mu(n,o,e),s||(s=Fb(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Ct(j(o)))return null;const l=n.insertTextBlock("",U(n.rootContainer),Ve(n.rootContainer));return $(l,0,"home")}return null}if(s=zb(n,s,e),H(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return y8(n,s,o,t,l);if(e==="ArrowUp")return k8(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?$(s,Z(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?$(s,0,"home"):null}function Vb(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(H(n,r))return o;const i=ht(r);if(i)return $(i,0,"home");if(!Ct(j(r))||n.readonly)return o;const s=n.insertTextBlock("",U(n.rootContainer),Ve(n.rootContainer));return $(s,0,"home")}function qb(n,t,e){const o=n.selection.range;let r;if(o instanceof se)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=Vb(n,t,o):r=Ub(n,o.getFocusedPos(),t);else if(r=$b(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=Gt(s);r=$(l,0,"home")}else{const l=Kt(s);r=$(l,Z(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:Ul(n,o.anchor,r):null}function so(n,t,e){const o=qb(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 Wb(n){return so(n,"ArrowLeft","move"),!0}function Gb(n){return so(n,"ArrowRight","move"),!0}function Zb(n){return so(n,"ArrowUp","move"),!0}function Yb(n){if(so(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=j(t);if(Ct(e)||Gt(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",U(o),Ve(o)),!0}function Qb(n){return so(n,"ArrowDown","select"),!0}function Kb(n){return so(n,"ArrowLeft","select"),!0}function Jb(n){return so(n,"ArrowRight","select"),!0}function Xb(n){return so(n,"ArrowUp","select"),!0}function tv(n){if(!n.selection.range.focus.isSimple())return!1;const e=uu(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function ev(n){if(!n.selection.range.focus.isSimple())return!1;const e=hu(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function nv(n){if(!n.selection.range.focus.isSimple())return!1;const e=uu(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function ov(n){if(!n.selection.range.focus.isSimple())return!1;const e=hu(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}y("find-block");function gu(n,t){if(!ct(n,t))return t;const o=ye(n,t).getChildContainers(n,t)[0],i=Ot(o)[0];return gu(n,i)}function pu(n,t){if(!ct(n,t))return t;const e=ye(n,t).getChildContainers(n,t),o=e[e.length-1],r=Ot(o),i=r[r.length-1];return pu(n,i)}function rv(n){const t=pu(n,Gt(n.rootContainer)),e=$(t,Z(n,t),"end");return n.selection.setSelection(e),!0}function iv(n){const t=gu(n,n.getFirstBlock()),e=$(t,0,"home");return n.selection.setSelection(e),!0}function sv(n){const t=gu(n,n.getFirstBlock()),e=$(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function lv(n){const t=pu(n,Gt(n.rootContainer)),e=$(t,Z(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function cv(n){if(!n.selection.range.focus.isSimple())return!1;const e=au(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function av(n){if(!n.selection.range.focus.isSimple())return!1;const e=du(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function dv(n){if(!n.selection.range.focus.isSimple())return!1;const e=au(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function uv(n){if(!n.selection.range.focus.isSimple())return!1;const e=du(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const zp=y("find-block-position");function hv(n,t,e,o){d(zp,ct(n,t),"is not a complex block");const r=ye(n,t).getChildContainers(n,t);d(zp,r.length>0,"complex block has not any child container");const i=Ze(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,c=ig(n,t,s,l);return Cu(n,c,e,o)}function Cu(n,t,e,o){if(ct(n,t))return hv(n,t,e,o);const r=G(t);let i=Number.MAX_SAFE_INTEGER;const s=Ze(n,e,o),l=s.left+s.width/2,c=s.top+s.height/2;let a=$(r,0,"home");const h=Z(n,t);for(let f=0;f<=h;f++){const m=$(r,f,"normal"),C=Ze(n,t,m),v=fn(C,l,c);v<i&&(i=v,a=m)}return a}const Up=y("page-offset");function fv(n,t){const e=Ip(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<Bb(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 mv(n,t){const e=Ip(n)*.9,o=t.getBoundingClientRect(),r=Eb(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=ht(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=ht(l)}return n.getLastBlock()}function Vp(n){const t=n.selection.range.focus;d(Up,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=fv(n,e);let r;return o===n.getFirstBlock()?r=$(o,0,"home"):r=Cu(n,o,e,t),r}function qp(n){const t=n.selection.range.focus;d(Up,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=mv(n,e);let r;return o===n.getLastBlock()?r=$(o,Z(n,o),"end"):r=Cu(n,o,e,t),r}function gv(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vp(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function pv(n){if(!n.selection.range.focus.isSimple())return!1;const e=qp(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function Cv(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vp(n);if(!e)return!1;const o=Ul(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 bv(n){if(!n.selection.range.focus.isSimple())return!1;const e=qp(n);if(!e)return!1;const o=Ul(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 ji=y("select-all");function vv(n,t){const e=t.getEditor(),o=ye(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=G(n);return t.start.blockId===s&&t.start.childContainerId===U(r)&&t.end.blockId===s&&t.end.childContainerId===U(i)}function kv(n,t){d(ji,t,"no parent block"),d(ji,ct(n,t),"not a complex block");const e=ye(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(Vt(n,{anchor:bt(t,U(o)),focus:bt(t,U(r))}))}function Wp(n,t){const e=j(t),o=Ot(e),r=o[0],i=o[o.length-1],s=$(r,0,"home"),l=$(i,Z(n,i),"end");n.selection.setSelection(s,l,{noScroll:!0})}function yv(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&H(n,t)){const r=e.start,i=e.end,s=Z(n,t);if(r.offset>0||i.offset<s)return n.selection.selectBlock(t,0,s),!1}return M(n.rootContainer,"select-all"),Wp(n,Kt(n.rootContainer)),!1}return d(ji,!e.isSimple(),"invalid range type"),vv(t,e)?(Wp(n,t),!1):(d(ji,t,"no parent block"),d(ji,ct(n,t),"not a complex block"),kv(n,t),!0)}function wv(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function Bv(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const Gp=y("delete-text");function Zp(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof Ut||d(Gp,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);d(Gp,H(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!me(s,l-e)){const c=Po(s,l);e=l-c}}else if(t==="forward"&&l+e>Z(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function Yp(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const Ev=y("handle-backspace");function bu(n,t){if(!yt(n,t))return;const e=j(t);Ve(e)!==1&&n.deleteBlock(t)}function Iv(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(H(n,o))if(e.offset===0){if(Yp(n,o))return;const r=gt(o);if(r)if(H(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(ct(n,r)){bu(n,o);const i=yr(n,r);i?n.selection.selectBlock(i,Z(n,i)):n.selection.selectBlock(r,0,Z(n,r))}else bu(n,o),d(Ev,De(r),"prev block is not embed block"),n.selection.selectBlock(r,1);else{const i=j(o);if(We(i)){const s=ng(n,i);s&&(bu(n,o),n.selection.selectBlock(s,Z(n,s)))}}}else Zp(n,"backward",1,null);else{const r=K(o),i=j(o);n.insertTextBlock("",U(i),r),n.deleteBlock(o)}}function xv(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(H(n,o))if(e.offset===Z(n,o)){const r=ht(o);r&&(H(n,r)?n.mergeTextBlock(o,r,{focus:!0}):yt(n,o)?n.deleteBlock(o,Lt(n,r,0)):n.deleteBlock(r))}else Zp(n,"forward",1,null);else{const r=K(o),i=j(o);n.insertTextBlock("",U(i),r),n.deleteBlock(o)}}function Sv(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const e=n.getFocusedBlock();if(H(n,e)){if(yt(n,e)&&Yp(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 Tv(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!H(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 Dv=y("input-handler-actions");function Lv(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Sv(n),!0))}function Mv(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(xv(n),!0))}function Rv(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Iv(n),!0))}function Ov(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(Tv(n),!0))}function Av(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{const e=n.selection.focusedBlock,o=n.selection.range.start;d(Dv,o.isSimple(),"not simple position"),n.insertTextToBlock(e,o.offset,t)}),!0)}function _v(n){return bb(n),Wd(n),!0}const Vl={ArrowDown:Yb,ArrowUp:Zb,ArrowLeft:Wb,ArrowRight:Gb,"Shift+ArrowDown":Qb,"Shift+ArrowUp":Xb,"Shift+ArrowLeft":Kb,"Shift+ArrowRight":Jb,"CtrlOrCmd+ArrowLeft":tv,"CtrlOrCmd+ArrowRight":ev,"CtrlOrCmd+Shift+ArrowLeft":nv,"CtrlOrCmd+Shift+ArrowRight":ov,"CtrlOrCmd+ArrowUp":iv,"CtrlOrCmd+ArrowDown":rv,"CtrlOrCmd+Shift+ArrowUp":sv,"CtrlOrCmd+Shift+ArrowDown":lv,"CtrlOrCmd+A":yv,Home:dv,End:uv,"Shift+Home":cv,"Shift+End":av,PageUp:gv,PageDown:pv,"Shift+PageUp":Cv,"Shift+PageDown":bv,"CtrlOrCmd+X":_v,"CtrlOrCmd+Z":wv,"CtrlOrCmd+Shift+Z":Bv,Enter:Lv,Delete:Mv,Backspace:Rv,"Shift+Enter":Ov,"CtrlOrCmd+Shift+V":Av};function Qp(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function Kp(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=>{Kp(n,l,e)})})}function Jp(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):Kp(t,r,e)})}async function Nv(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 Pv(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 $v(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(Pv(n,t)){const s=Array.from(Object.keys(o));r=await Nv(n,s),Jp(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&&Jp(n,t,i)}async function jv(n,t){await $v(n,t),n.undoManager.runInGroup(()=>{n.clearSelectedContents();const{block:e,offset:o}=Sr(n);n.insertDoc(e,o,t)})}const Hv=["text/x-ones-editor-doc","image/*","text/html","text/plain","text/markdown","*"];function Fv(n){let t;for(const e of Hv)if(t=n[e],t)break;return t||null}class zv{constructor(t){u(this,"editor");u(this,"handlers",[]);this.editor=t}onInsertText(t,e){if(!H(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=Sr(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}=Sr(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}=Sr(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)}}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;this.editor.dataConverter.fromData(this.editor,t.clipboardData).then(async o=>{if(!o)return;for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforePaste&&await s.handleBeforePaste(this.editor,t,o))return}const r=Fv(o);if(!!r){await this.pasteDoc(r);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterPaste&&await s.handleAfterPaste(this.editor,t,o))return}}})}onFocus(){M(this.editor.rootElement,"active")}onBlur(){F(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){Hd(this.editor,i)}defaultHandleKeydown(t,e){return Qp(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 jv(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}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function Uv(n,t,e){const o=fr(t,e);return o.remove(),o}y("copy-dom-attributes");const Xp=["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 Vv(n,t){for(let l=0;l<Xp.length;l++){const c=Xp[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 t2(n){const t=Array.from(n.childNodes);return t.forEach(e=>{e instanceof HTMLElement&&e.getAttribute("data-type")==="block-tools"||e.remove()}),t}function e2(n,t,e){var a;const o=n.getContainerById(t),r=fr(o,e),i=Ro(r),s=n.doc.getBlockData(t,e),l=kt(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 h=n.editorBlocks.createBlock(i,o,s),f=t2(h);t2(r),f.forEach(C=>r.appendChild(C));const m=al(h);if(m){const C=al(r);C&&C.remove(),r.appendChild(m)}Vv(h,r)}Vm(n,r,s),n.blockHooks.forEach(h=>{var f;(f=h.update)==null||f.call(h,n,i,o,r,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const qv=y("transform-selection");function n2(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;d(qv,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const a=oe.transformCursor(i.offset,e,o);l=$(t,a,"normal")}let c=s;if(s.blockId===t){const a=oe.transformCursor(s.offset,e,o);c=$(t,a,"normal")}return Vt(n,{anchor:l,focus:c})}const Wv=y("handle-block-text-changed");function Gv(n,t,e,o,r){const i=n.getContainerById(t),s=fr(i,e),l=n.doc.getBlockData(t,e);if(d(Wv,l.text,"no block text"),Hm(n,s).setBlockText(n,s,l.text),!r){const c=n2(n,l.id,o,r);n.selection.setRange(c,{noScroll:!0})}}function Zv(n,t){const e=Y.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function o2(n,t,e,o){const r=kt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function Yv(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{o2(n,i,o,{child:!0})}),o2(n,r,o,{child:!1})}const Hn=y("editor-doc");class Qv extends vi{constructor(e,o,r){super();u(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(Hn,this.editor.isWritable(),"editor is readonly");const s=this.getBlockData(e,o),l=s.text;d(Hn,l,`no text, ${e}, ${o}`);const c=n2(this.editor,s.id,r,!0),a=oe.apply(l,r);this.localEvents.forEach(f=>f.onBeforeUpdateBlockText(e,s.id,l,a,c.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(c,i),h}localUpdateBlockData(e,o,r,i){d(Hn,this.editor.isWritable(),"editor is readonly");const s=Y.default(this.getBlockData(e,o)),l=Y.default(Zv(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(oo(this.editor,i)),c}localInsertBlock(e,o,r,i,s){d(Hn,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(oo(this.editor,i),s),l}localDeleteBlock(e,o,r){d(Hn,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(oo(this.editor,r)),s}localDeleteChildContainers(e){return d(Hn,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(Hn,this.editor.isWritable(),"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(e,Y.default(o))),this.externalDoc.localInsertChildContainer(e,o)}onRequestReload(e){Hn.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)}),Gv(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)}),e2(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);B7(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){Yv(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);Uv(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){Hn.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function r2(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 vu=y("undo-action");class Mr{constructor(t,e,o){u(this,"beforeRange");u(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(vu,t,"no other action"),!1}combine(t){d(vu,!1,"no other")}setAfterRange(t){this.afterRange&&vu.warn("after range has already set"),this.afterRange=t}}const Kv=y("block-action");class i2 extends Mr{constructor(e,o,r,i,s){super(e,o,s);u(this,"blockData");u(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(Kv,this.blockIndex===K(i),"invalid block index"),Ud(e,i,oo(e,o)),!0):!1}insertBlock(e,o){return Tr(e,this.containerId,this.blockIndex,Y.default(this.blockData),o),!0}}class Jv extends i2{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class Xv extends i2{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class tk extends Mr{constructor(e){super(e,U(e.rootContainer),e.selection.range.toDocRange());u(this,"actions",[])}addAction(e){r2(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 Mr&&(o.afterRange||o.setAfterRange(e))}}const zo=y("update-block-data-action");class ql extends Mr{constructor(e,o,r,i,s,l){super(e,o,l);u(this,"beforeBlockData");u(this,"afterBlockData");u(this,"blockId");this.blockId=r,d(zo,this.blockId===i.id,"invalid block id"),d(zo,this.blockId===s.id,"invalid block id"),this.beforeBlockData=Y.default(i),this.afterBlockData=Y.default(s),d(zo,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){d(zo,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return d(zo,r,"no container"),$l(e,o,ql.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){d(zo,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return d(zo,r,"no container"),$l(e,o,ql.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=Y.default(e);return delete o.id,delete o.type,o}}const ku=y("update-block-text-action");class Hi extends Mr{constructor(e,o,r,i,s,l){super(e,o,l);u(this,"beforeRichTextData");u(this,"afterRichTextData");u(this,"blockId");u(this,"type");this.blockId=r,this.beforeRichTextData=Y.default(i),this.afterRichTextData=Y.default(s),this.type=Hi.calType(i,s)}static calType(e,o){d(ku,e,"no old data"),d(ku,o,"no new data");const i=oe.diff(e,o),s=new Set;let l=!1;const c=h=>Yf(h)?`cjk_${h}`:Gf(h)?"number":tl(h)?"space":Zf(h)?"letter":"unknown";let a=!1;return i.forEach(h=>{h.insert?h.insert===" "?s.add("insert_letter"):typeof h.insert=="string"&&h.insert.startsWith(" ")&&h.insert.length>1?(l=!0,a=!0,s.add(`insert_${c(h.insert.substr(1))}`)):s.add(`insert_${c(h.insert)}`):h.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?(Pl(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Pl(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof Hi)||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(ku,e instanceof Hi,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class s2 extends Mr{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 ek extends s2{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class nk extends s2{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Xe=y("undo");class ok{constructor(t){u(this,"editor");u(this,"actions",[]);u(this,"undoCursor");u(this,"currentGroup",null);u(this,"groupCounter",0);u(this,"undoRedoing",!1);u(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):(r2(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(d(Xe,!this.currentGroup,"current group already exists"),this.currentGroup=new tk(this.editor),this.groupCounter=1):(d(Xe,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){d(Xe,this.currentGroup,"current group not exists"),d(Xe,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Xe.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 Xe.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(oo(this.editor,t.beforeRange))}catch(e){Xe.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(oo(this.editor,e)):Xe.warn("no after range")}catch(e){Xe.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(),oe.diff(o,r).length!==0&&this.addAction(new Hi(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new ql(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),d(Xe,e>=0,"invalid block index"),d(Xe,o,"no block data"),this.addAction(new Jv(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new Xv(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new ek(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new nk(this.editor,t,e)))}}class rk{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 ik{constructor(){u(this,"converters",[]);this.addConverter(new rk)}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 sk{constructor(t){u(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 _t extends Wt.TypedEmitter{constructor(e){super();u(this,"hoveringBlock",null);u(this,"hoveringTextChild",null);u(this,"filters",[]);u(this,"finders",[]);u(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=z(o);if((!r||!vt(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?G(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&&vt(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&F(s,"hover"),e&&M(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 _t(e))}getParentTextContentChild(e,o){if(!H(this.editor,e))return null;const r=rt(e);return o.parentElement===r?o:rd(o)}}const l2="style-color-",c2="style-bg-color-";class lk{renderText(t,e,o){const r=[],i={};return Object.entries(o).forEach(([s,l])=>{l===!0?s.startsWith(l2)?i["data-style-color"]=s.substring(l2.length):s.startsWith(c2)?i["data-style-bg-color"]=s.substring(c2.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,h])=>{r[`data-${a}`]=`${h}`});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"),_t.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&&M(o,"focused"),_t.get(t).hoveringBlockId()===r.id&&M(o,"hover")}}function ck(n){n.editorBlocks.registerBlockClass(Ai),n.editorBlocks.registerBlockClass(eg),n.editorBoxes.registerBoxClass(Fg),n.editorBoxes.registerBoxClass(zg),n.editorInsertions.registerInsertionClass(qg),n.editorBlockRenders.registerRender(new lk)}function ak(n,t){ck(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 a2=y("range-commands");function d2(n,t){n.forEach(e=>{e.source=t,e.children&&d2(e.children,t)})}function u2(n,t,e){const o=G(t);d(a2,o===e.start.blockId,"invalid start range"),d(a2,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);d2(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,i);l&&(i=l)}}),ct(n,t)&&kr(n,t,e.start,e.end).forEach(l=>{Ot(l).forEach(a=>{const h=Z(n,a),f=Vt(n,{anchor:$(a,0,"home"),focus:$(a,h,"end")}),m=u2(n,a,f);i.push(...m)})}),i}function h2(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=Vt(t,{anchor:r.start,focus:r.end});u2(t,r.block,i).forEach(l=>{o.push(l)})}),o}function f2(n,t,e,o,r,i){var h;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((h=l.executeCommand)!=null&&h.call(l,n,t,e,o,r,{}))return i[G(t)]=c,!0;let a=!1;return ct(n,t)&&kr(n,t,e.start,e.end).forEach(m=>{Ot(m).forEach(v=>{const w=Z(n,v),E=Vt(n,{anchor:$(v,0,"home"),focus:$(v,w,"end")});f2(n,v,E,o,r,i)&&(a=!0)})}),s.forEach(f=>{f.afterExecuteCommand&&f.afterExecuteCommand(n,t,e,o,r,i)}),a}function m2(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=Vt(o,{anchor:l.start,focus:l.end});f2(o,l.block,c,t,e,r)}),r}const dk=y("command-providers");class g2{constructor(t){u(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(dk,e,`no command provider, id=${t}`),e}getCommands(t){return h2(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>m2(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 uk(n,t){const e=j(t),o=U(e),r=K(t);e2(n,o,r)}const hk=y("table-scroll");class p2{constructor(t,e,o,r,i){u(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 fk{constructor(t){u(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)){hk.warn(`event has already registered: ${e}`);return}i.push(new p2(this.editor,t,e,o,r))}else{const s=new p2(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 C2=y("update-block-text");function mk(n,t){const e=n.getBoxById(t.id),o=z(e);d(C2,o,"no parent block"),d(C2,H(n,o),"not a text block");const r=n.getBlockText(o),i=Rg(r,"id",t.id,t);fp(n,o,i)}function gk(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 pk(n){return n.readonly?!1:!Ke(n).find(o=>!n.isBlockWritable(o.block))}class Ck{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 bk{constructor(){u(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(An(e,s)){const c=l(t,e);if(c!==void 0)return c}}}}const Fn=y("editor");class vk extends Wt.TypedEmitter{constructor(e,o,r){var i,s,l,c,a,h,f;super();u(this,"parent");u(this,"rootElement");u(this,"contentElement");u(this,"rootContainerObject");u(this,"rootContainer");u(this,"input");u(this,"selection");u(this,"selectionHandler");u(this,"doc");u(this,"id");u(this,"clientId");u(this,"compositingText","");u(this,"undoManager");u(this,"shortcuts",new bk);u(this,"dataConverter",new ik);u(this,"editorBlocks",new Km(this));u(this,"editorBoxes",new Vg(this));u(this,"editorInsertions",new Gg(this));u(this,"editorEmbeds",new Xm(this));u(this,"editorDecorators",new Zg(this));u(this,"editorCommandProviders",new g2(this));u(this,"editorBlockRenders",new sk(this));u(this,"blockHooks",[]);u(this,"domEvents",new fk(this));u(this,"customs",new Map);u(this,"options");u(this,"inputHandlers",new zv(this));u(this,"settingsProvider");u(this,"_readonly",!1);Fn.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 Ck(this),ak(this,r==null?void 0:r.components),this.blockHooks.push(...(h=(a=r==null?void 0:r.components)==null?void 0:a.blockHooks)!=null?h:[]),this.id=(f=r==null?void 0:r.id)!=null?f:N(),this.clientId=N(),this.undoManager=new ok(this),this.doc=new Qv(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=Pm(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new vb(this,this.inputHandlers),this.selection=new Lb(this),this.selectionHandler=new Nb(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),St.isMobile&&M(this.rootElement,"mobile"),St.isSafari&&M(this.rootElement,"safari"),this._readonly&&M(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?M(this.rootElement,"readonly"):F(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:_n(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(Fn,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(){Fn.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){Gd(this,e,o)}isWritable(){return pk(this)}isBlockWritable(e){return gk(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return d(Fn,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),d(Fn,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(e,o,r){return $m(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(Fn,mr(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&d(Fn,od(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return d(Fn,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return d(Fn,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return fr(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return K(o)}return K(e)}getContainerById(e){return Cr(this,e)}getParentContainer(e){return j(e)}reloadBlock(e){uk(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 Tr(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){Vd(this,e,o)}mergeTextBlock(e,o){return dp(this,e,o)}breakTextBlock(e,o,r){return Dr(this,e,o,r).newBlock}getTextPosition(){return Sr(this)}getBlockString(e,o){const r=this.getBlockText(e);return wt(r,o)}getBlockData(e){return io(this,e)}getBoxData(e){return Jg(this,e)}getBlockText(e){return we(this,e)}setBlockText(e,o){fp(this,e,o)}deleteTextFromBlock(e,o,r,i){return Fd(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return tp(this,e,o,r,i)}insertBoxToBlock(e,o,r){return ep(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){pp(this,e,o,r,i)}insertDocAt(e,o,r,i){return Qd(this,e,o,r,i)}deleteChildContainers(e){ap(this,e)}replaceBlockText(e,o){return Pl(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...c}=i;return $l(this,e,c,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return mp(this,e,o,r)}updateBoxData(e){mk(this,e)}getSelectedText(){const e=Fl(this);return nu(this,e)}clearSelectedContents(){Wd(this)}insertTextBlock(e,o,r,i){const s=jn(e!=null?e:"");return ip(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){op(this);return}o?(this.compositingText="",Ga()||Hd(this,e)):(this.compositingText=e,np(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function Fi(n,t,e){return new vk(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=ja.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const yk=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class Wl extends Wt.TypedEmitter{constructor(e){super();u(this,"users",new Map);u(this,"cursors",new Map);u(this,"addingUser",!1);u(this,"colors");this.colors=e&&e.length>0?e:yk}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&Zs.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&&Sl(r.range)&&Ng(r.range)).forEach(r=>{const i=r.range.anchor.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(Sl(l.range)){const{anchor:c,focus:a}=l.range;c.blockId===e.id&&(c.offset=oe.transformCursor(c.offset,o,r)),a.blockId===e.id&&(a.offset=oe.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 Xt=y("local-doc");class yu extends vi{constructor(e,o){super();u(this,"doc");u(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[jn("")]}},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(Xt,r,`no container data: ${e}`);const i=r[o];return d(Xt,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);d(Xt,i.text,"no text for data");const s=oe.apply(i.text,r);return i.text=s,d(Xt,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(Xt,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(Xt,i,`no container data: ${e}`),d(Xt,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),d(Xt,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(Xt,r,`no container data: ${e}`),d(Xt,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),d(Xt,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(Xt,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){Xt.debug(`delete child containers: ${e}`),e.forEach(o=>{d(Xt,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{d(Xt,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(Xt,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){d(Xt,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new Wl}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 Uo(n){return Ct(j(n))}class wk{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function wu(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new wk(o)})}const Bk=y("remote-cursor");class Ek{constructor(){u(this,"remoteUsers",new Wl)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):Bk.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 Ik(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function zi(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=Ik(Y.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function lo(n){return n==="root"?"blocks":n}function Rr(n){return n==="blocks"?"root":n}const xk={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new ne.default(n)},apply(n,t){const e=new ne.default(n),o=new ne.default(t);return e.compose(o).ops},compose(n,t){const e=new ne.default(n),o=new ne.default(t);return e.compose(o).ops},diff(n,t){const e=new ne.default(n),o=new ne.default(t);return e.diff(o).ops},transform(n,t,e){const o=new ne.default(n);return new ne.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 ne.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 Ui=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},co={},Bu=xf.default.EventEmitter;co.EventEmitter=Bu,co.mixin=Sk;function Sk(n){for(var t in Bu.prototype)n.prototype[t]=Bu.prototype[t]}var b2=["info","warn","error"];function v2(){var n={};b2.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var Tk=v2;v2.prototype.setMethods=function(n){n=n||{};var t=this;b2.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var Dk=Tk,Lk=new Dk,k2=Lk;function Vo(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,Vo):this.stack=new Error().stack}Vo.prototype=Object.create(Error.prototype),Vo.prototype.constructor=Vo,Vo.prototype.name="ShareDBError",Vo.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 Gl=Vo,Vi={},y2=Mk;function Mk(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 h=l[a],f=[],m=0;m<s.length;){var C=[];if(r(s[m],h,f,C),m++,C.length===1)h=C[0];else if(C.length===0){for(var v=m;v<s.length;v++)o(f,s[v]);h=null;break}else{for(var w=i(s.slice(m),C),E=0;E<w[0].length;E++)o(f,w[0][E]);for(var L=0;L<w[1].length;L++)o(c,w[1][L]);h=null;break}}h!=null&&o(c,h),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 w2={exports:{}},ao=w2.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||""}},Eu=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},Iu=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")},Zl=function(n){for(var t=0;t<n.length;t++)Iu(n[t])};ao.apply=function(n,t){var e;Zl(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=Eu(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 zn=ao._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:Eu(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:Eu(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};ao.compose=function(n,t){Zl(n),Zl(t);for(var e=n.slice(),o=0;o<t.length;o++)zn(e,t[o]);return e},ao.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),zn(t,o)}return t};var xu=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};ao.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=xu(n,t[r],o);return n};var Rk=ao._tc=function(n,t,e,o){if(Iu(t),Iu(e),t.i!=null)zn(n,{i:t.i,p:xu(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(zn(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&zn(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)zn(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)zn(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=xu(i.p,e),zn(n,i))}return n},Ok=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};ao.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=Ok(n[t]);return n},y2(ao,Rk,Zl,zn);var Yl=function(n){return Object.prototype.toString.call(n)=="[object Array]"},Ak=function(n){return!!n&&n.constructor===Object},tn=function(n){return JSON.parse(JSON.stringify(n))},tt={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Un={};tt.registerSubtype=function(n){Un[n.name]=n},tt.create=function(n){return n===void 0?null:tn(n)},tt.invertComponent=function(n){var t={p:n.p};return n.t&&Un[n.t]&&(t.t=n.t,t.o=Un[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(!Yl(n[t].p))throw new Error("Missing path")},tt.checkList=function(n){if(!Yl(n))throw new Error("Referenced element not a list")},tt.checkObj=function(n){if(!Ak(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function qi(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 Wi(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=tn(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&qi(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&&Un[r.t])s[l]=Un[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 h=s[l];s.splice(l,1),s.splice(r.lm,0,h)}}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 _k=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=tn(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)&&(qi(t),qi(e)),_k(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Un[t.t]){if(e.o=Un[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(),Wi(t),n.push(t);Wi(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)&&(Wi(t),Wi(e)),n.push(t)},tt.compose=function(n,t){tt.checkValidOp(n),tt.checkValidOp(t);for(var e=tn(n),o=0;o<t.length;o++)tt.append(e,t[o]);return e},tt.normalize=function(n){var t=[];n=Yl(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=tn(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=tn(e);c.p=c.p.slice(s),t.ld=tt.apply(tn(t.ld),[c])}else if(t.od!==void 0){var c=tn(e);c.p=c.p.slice(s),t.od=tt.apply(tn(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)&&(qi(t),c=tn(e),qi(c)),c.t&&Un[c.t]){if(t.t&&t.t===c.t){var h=Un[t.t].transform(t.o,c.o,o);if(t.si!=null||t.sd!=null)for(var f=t.p,m=0;m<h.length;m++)t.o=[h[m]],t.p=f.slice(),Wi(t),tt.append(n,t);else(!Yl(h)||h.length>0)&&(t.o=h,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=tn(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,w=e.p[r],E=e.lm;if(w!==E)if(C===w)if(o==="left")t.p[r]=E,C===v&&(t.lm=E);else return n;else C>w&&t.p[r]--,C>E?t.p[r]++:C===E&&w>E&&(t.p[r]++,C===v&&t.lm++),(v>w||v===w&&v>C)&&t.lm--,v>E?t.lm++:v===E&&(E>w&&v>C||E<w&&v<C?o==="right"&&t.lm++:v>C?t.lm++:v===w&&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},y2(tt,tt.transformComponent,tt.checkValidOp,tt.append);var Nk=w2.exports;tt.registerSubtype(Nk);var Pk=tt,$k={type:Pk};(function(n){n.defaultType=$k.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)})(Vi);var en={};(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))}})(en);var B2=Array.isArray,E2=Object.keys,jk=Object.prototype.hasOwnProperty,Hk=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=B2(t),r=B2(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 h=t instanceof RegExp,f=e instanceof RegExp;if(h!=f)return!1;if(h&&f)return t.toString()==e.toString();var m=E2(t);if(s=m.length,s!==E2(e).length)return!1;for(i=s;i--!==0;)if(!jk.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},I2=co,Fk=k2,Be=Gl,Ql=Vi,nn=en,zk=nn.clone,Uk=Hk,pe=Be.CODES,Vk=st;function st(n,t,e){I2.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}I2.mixin(st),st.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())})},st.prototype._setType=function(n){if(typeof n=="string"&&(n=Ql.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new Be(pe.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},st.prototype._setData=function(n){this.data=n,this._dataStateVersion++},st.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new Be(pe.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 Be(pe.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?Ql.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()},st.prototype.whenNothingPending=function(n){var t=this;nn.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},st.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},st.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},st.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},st.prototype._emitResponseError=function(n,t){if(n&&n.code===pe.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)},st.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){nn.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},st.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){nn.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()},st.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===pe.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=Kl(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=Kl(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},st.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))},st.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()},st.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);qk(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},st.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},st.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},st.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=e&&e.wantSubscribe===n;if(o){e.callback=Wk([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},st.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;nn.nextTick(function(){n._handleSubscribe()})}}};function qk(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function Wk(n){return n=n.filter(nn.truthy),n.length?function(t){nn.callEach(n,t)}:null}st.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function Gk(n){delete n.op,delete n.create,delete n.del}function Kl(n,t){if(n.del)return Gk(t);if(t.del)return new Be(pe.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new Be(pe.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new Be(pe.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}}}st.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new Be(pe.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===Ql.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=Kl(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}},st.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 Be(pe.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>=nn.MAX_SAFE_INTEGER)return this.emit("error",new Be(pe.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)}},st.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var o=new Be(pe.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;nn.nextTick(function(){r.flush()})},st.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)},st.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)}}},st.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!Uk(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}}},st.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)},st.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=Ql.defaultType.uri),this.type){var r=new Be(pe.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)},st.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new Be(pe.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)},st.prototype.pause=function(){this.paused=!0},st.prototype.resume=function(){this.paused=!1,this.flush()},st.prototype.toSnapshot=function(){return{v:this.version,data:zk(this.data),type:this.type.uri}},st.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return Fk.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},st.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=Kl(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)},st.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=nn.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},st.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=nn.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var qo={};qo.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 x2=co,S2=qo.ACTIONS,Zk=en,Yk=Ce;function Ce(n,t,e,o,r,i,s){x2.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}x2.mixin(Ce),Ce.prototype.hasPending=function(){return!this.ready},Ce.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}},Ce.prototype.destroy=function(n){this.connection.canSend&&this.action===S2.querySubscribe&&this.connection.send({a:S2.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&Zk.nextTick(n)},Ce.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Ce.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Ce.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Ce.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(h){if(h)return r._finishResponse(h,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()},Ce.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},Ce.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)},Ce.prototype._handleError=function(n){this.emit("error",n)},Ce.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)},Ce.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var T2=co,Qk=qo.ACTIONS,Kk=en,D2=vn;function vn(n,t){if(T2.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={}}T2.mixin(vn),vn.prototype.submit=function(n,t){this.value=n,this.send(t)},vn.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},vn.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()})},vn.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},vn.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},vn.prototype._message=function(){return{a:Qk.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},vn.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},vn.prototype._callbackOrEmit=function(n,t){if(t)return Kk.nextTick(t,n);n&&this.emit("error",n)};var Jk=en,L2=Su;function Su(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}Su.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},Su.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&Jk.nextTick(n)};var Tu={exports:{}};(function(n,t){(function(e,o){o(t)})(Ui,function(e){function o(p,k){k=k|0;for(var B=Math.max(p.length-k,0),I=Array(B),D=0;D<B;D++)I[D]=p[k+D];return I}var r=function(p){var k=o(arguments,1);return function(){var B=o(arguments);return p.apply(null,k.concat(B))}},i=function(p){return function(){var k=o(arguments),B=k.pop();p.call(this,k,B)}};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 h(p){return function(k){var B=o(arguments,1);p(function(){k.apply(null,B)})}}var f;l?f=setImmediate:c?f=process.nextTick:f=a;var m=h(f);function C(p){return i(function(k,B){var I;try{I=p.apply(this,k)}catch(D){return B(D)}s(I)&&typeof I.then=="function"?I.then(function(D){v(B,null,D)},function(D){v(B,D.message?D:new Error(D))}):B(null,I)})}function v(p,k,B){try{p(k,B)}catch(I){m(w,I)}}function w(p){throw p}var E=typeof Symbol=="function";function L(p){return E&&p[Symbol.toStringTag]==="AsyncFunction"}function x(p){return L(p)?C(p):p}function O(p){return function(k){var B=o(arguments,1),I=i(function(D,T){var R=this;return p(k,function(_,q){x(_).apply(R,D.concat(q))},T)});return B.length?I.apply(this,B):I}}var A=typeof Ui=="object"&&Ui&&Ui.Object===Object&&Ui,P=typeof self=="object"&&self&&self.Object===Object&&self,V=A||P||Function("return this")(),nt=V.Symbol,ot=Object.prototype,ut=ot.hasOwnProperty,dt=ot.toString,Et=nt?nt.toStringTag:void 0;function re(p){var k=ut.call(p,Et),B=p[Et];try{p[Et]=void 0;var I=!0}catch{}var D=dt.call(p);return I&&(k?p[Et]=B:delete p[Et]),D}var Xn=Object.prototype,te=Xn.toString;function Fe(p){return te.call(p)}var bo="[object Null]",cr="[object Undefined]",ar=nt?nt.toStringTag:void 0;function vo(p){return p==null?p===void 0?cr:bo:ar&&ar in Object(p)?re(p):Fe(p)}var ha="[object AsyncFunction]",xP="[object Function]",SP="[object GeneratorFunction]",TP="[object Proxy]";function DP(p){if(!s(p))return!1;var k=vo(p);return k==xP||k==SP||k==ha||k==TP}var LP=9007199254740991;function $3(p){return typeof p=="number"&&p>-1&&p%1==0&&p<=LP}function Ps(p){return p!=null&&$3(p.length)&&!DP(p)}var sf={};function ft(){}function ko(p){return function(){if(p!==null){var k=p;p=null,k.apply(this,arguments)}}}var lf=typeof Symbol=="function"&&Symbol.iterator,MP=function(p){return lf&&p[lf]&&p[lf]()};function RP(p,k){for(var B=-1,I=Array(p);++B<p;)I[B]=k(B);return I}function fa(p){return p!=null&&typeof p=="object"}var OP="[object Arguments]";function j3(p){return fa(p)&&vo(p)==OP}var H3=Object.prototype,AP=H3.hasOwnProperty,_P=H3.propertyIsEnumerable,NP=j3(function(){return arguments}())?j3:function(p){return fa(p)&&AP.call(p,"callee")&&!_P.call(p,"callee")},un=Array.isArray;function PP(){return!1}var F3=typeof e=="object"&&e&&!e.nodeType&&e,z3=F3&&!0&&n&&!n.nodeType&&n,$P=z3&&z3.exports===F3,U3=$P?V.Buffer:void 0,jP=U3?U3.isBuffer:void 0,HP=jP||PP,FP=9007199254740991,zP=/^(?:0|[1-9]\d*)$/;function UP(p,k){var B=typeof p;return k=k==null?FP:k,!!k&&(B=="number"||B!="symbol"&&zP.test(p))&&p>-1&&p%1==0&&p<k}var VP="[object Arguments]",qP="[object Array]",WP="[object Boolean]",GP="[object Date]",ZP="[object Error]",YP="[object Function]",QP="[object Map]",KP="[object Number]",JP="[object Object]",XP="[object RegExp]",t$="[object Set]",e$="[object String]",n$="[object WeakMap]",o$="[object ArrayBuffer]",r$="[object DataView]",i$="[object Float32Array]",s$="[object Float64Array]",l$="[object Int8Array]",c$="[object Int16Array]",a$="[object Int32Array]",d$="[object Uint8Array]",u$="[object Uint8ClampedArray]",h$="[object Uint16Array]",f$="[object Uint32Array]",It={};It[i$]=It[s$]=It[l$]=It[c$]=It[a$]=It[d$]=It[u$]=It[h$]=It[f$]=!0,It[VP]=It[qP]=It[o$]=It[WP]=It[r$]=It[GP]=It[ZP]=It[YP]=It[QP]=It[KP]=It[JP]=It[XP]=It[t$]=It[e$]=It[n$]=!1;function m$(p){return fa(p)&&$3(p.length)&&!!It[vo(p)]}function g$(p){return function(k){return p(k)}}var V3=typeof e=="object"&&e&&!e.nodeType&&e,$s=V3&&!0&&n&&!n.nodeType&&n,p$=$s&&$s.exports===V3,cf=p$&&A.process,q3=function(){try{var p=$s&&$s.require&&$s.require("util").types;return p||cf&&cf.binding&&cf.binding("util")}catch{}}(),W3=q3&&q3.isTypedArray,C$=W3?g$(W3):m$,b$=Object.prototype,v$=b$.hasOwnProperty;function k$(p,k){var B=un(p),I=!B&&NP(p),D=!B&&!I&&HP(p),T=!B&&!I&&!D&&C$(p),R=B||I||D||T,_=R?RP(p.length,String):[],q=_.length;for(var Q in p)(k||v$.call(p,Q))&&!(R&&(Q=="length"||D&&(Q=="offset"||Q=="parent")||T&&(Q=="buffer"||Q=="byteLength"||Q=="byteOffset")||UP(Q,q)))&&_.push(Q);return _}var y$=Object.prototype;function w$(p){var k=p&&p.constructor,B=typeof k=="function"&&k.prototype||y$;return p===B}function B$(p,k){return function(B){return p(k(B))}}var E$=B$(Object.keys,Object),I$=Object.prototype,x$=I$.hasOwnProperty;function S$(p){if(!w$(p))return E$(p);var k=[];for(var B in Object(p))x$.call(p,B)&&B!="constructor"&&k.push(B);return k}function af(p){return Ps(p)?k$(p):S$(p)}function T$(p){var k=-1,B=p.length;return function(){return++k<B?{value:p[k],key:k}:null}}function D$(p){var k=-1;return function(){var I=p.next();return I.done?null:(k++,{value:I.value,key:k})}}function L$(p){var k=af(p),B=-1,I=k.length;return function D(){var T=k[++B];return T==="__proto__"?D():B<I?{value:p[T],key:T}:null}}function M$(p){if(Ps(p))return T$(p);var k=MP(p);return k?D$(k):L$(p)}function Dn(p){return function(){if(p===null)throw new Error("Callback was already called.");var k=p;p=null,k.apply(this,arguments)}}function ma(p){return function(k,B,I){if(I=ko(I||ft),p<=0||!k)return I(null);var D=M$(k),T=!1,R=0,_=!1;function q(W,X){if(R-=1,W)T=!0,I(W);else{if(X===sf||T&&R<=0)return T=!0,I(null);_||Q()}}function Q(){for(_=!0;R<p&&!T;){var W=D();if(W===null){T=!0,R<=0&&I(null);return}R+=1,B(W.value,W.key,Dn(q))}_=!1}Q()}}function dr(p,k,B,I){ma(k)(p,x(B),I)}function ee(p,k){return function(B,I,D){return p(B,k,I,D)}}function R$(p,k,B){B=ko(B||ft);var I=0,D=0,T=p.length;T===0&&B(null);function R(_,q){_?B(_):(++D===T||q===sf)&&B(null)}for(;I<T;I++)k(p[I],I,Dn(R))}var O$=ee(dr,1/0),yo=function(p,k,B){var I=Ps(p)?R$:O$;I(p,x(k),B)};function ai(p){return function(k,B,I){return p(yo,k,x(B),I)}}function G3(p,k,B,I){I=I||ft,k=k||[];var D=[],T=0,R=x(B);p(k,function(_,q,Q){var W=T++;R(_,function(X,xt){D[W]=xt,Q(X)})},function(_){I(_,D)})}var ga=ai(G3),Z3=O(ga);function di(p){return function(k,B,I,D){return p(ma(B),k,x(I),D)}}var ui=di(G3),df=ee(ui,1),Y3=O(df);function pa(p,k){for(var B=-1,I=p==null?0:p.length;++B<I&&k(p[B],B,p)!==!1;);return p}function A$(p){return function(k,B,I){for(var D=-1,T=Object(k),R=I(k),_=R.length;_--;){var q=R[p?_:++D];if(B(T[q],q,T)===!1)break}return k}}var _$=A$();function js(p,k){return p&&_$(p,k,af)}function N$(p,k,B,I){for(var D=p.length,T=B+(I?1:-1);I?T--:++T<D;)if(k(p[T],T,p))return T;return-1}function P$(p){return p!==p}function $$(p,k,B){for(var I=B-1,D=p.length;++I<D;)if(p[I]===k)return I;return-1}function Ca(p,k,B){return k===k?$$(p,k,B):N$(p,P$,B)}var uf=function(p,k,B){typeof k=="function"&&(B=k,k=null),B=ko(B||ft);var I=af(p),D=I.length;if(!D)return B(null);k||(k=D);var T={},R=0,_=!1,q=Object.create(null),Q=[],W=[],X={};js(p,function(Tt,Dt){if(!un(Tt)){xt(Dt,[Tt]),W.push(Dt);return}var Yt=Tt.slice(0,Tt.length-1),to=Yt.length;if(to===0){xt(Dt,Tt),W.push(Dt);return}X[Dt]=to,pa(Yt,function(gi){if(!p[gi])throw new Error("async.auto task `"+Dt+"` has a non-existent dependency `"+gi+"` in "+Yt.join(", "));Ln(gi,function(){to--,to===0&&xt(Dt,Tt)})})}),Lj(),ie();function xt(Tt,Dt){Q.push(function(){Mn(Tt,Dt)})}function ie(){if(Q.length===0&&R===0)return B(null,T);for(;Q.length&&R<k;){var Tt=Q.shift();Tt()}}function Ln(Tt,Dt){var Yt=q[Tt];Yt||(Yt=q[Tt]=[]),Yt.push(Dt)}function ze(Tt){var Dt=q[Tt]||[];pa(Dt,function(Yt){Yt()}),ie()}function Mn(Tt,Dt){if(!_){var Yt=Dn(function(gi,Bf){if(R--,arguments.length>2&&(Bf=o(arguments,1)),gi){var Ef={};js(T,function(Rj,Oj){Ef[Oj]=Rj}),Ef[Tt]=Bf,_=!0,q=Object.create(null),B(gi,Ef)}else T[Tt]=Bf,ze(Tt)});R++;var to=x(Dt[Dt.length-1]);Dt.length>1?to(T,Yt):to(Yt)}}function Lj(){for(var Tt,Dt=0;W.length;)Tt=W.pop(),Dt++,pa(Mj(Tt),function(Yt){--X[Yt]===0&&W.push(Yt)});if(Dt!==D)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function Mj(Tt){var Dt=[];return js(p,function(Yt,to){un(Yt)&&Ca(Yt,Tt,0)>=0&&Dt.push(to)}),Dt}};function hi(p,k){for(var B=-1,I=p==null?0:p.length,D=Array(I);++B<I;)D[B]=k(p[B],B,p);return D}var j$="[object Symbol]";function H$(p){return typeof p=="symbol"||fa(p)&&vo(p)==j$}var F$=1/0,Q3=nt?nt.prototype:void 0,K3=Q3?Q3.toString:void 0;function hf(p){if(typeof p=="string")return p;if(un(p))return hi(p,hf)+"";if(H$(p))return K3?K3.call(p):"";var k=p+"";return k=="0"&&1/p==-F$?"-0":k}function z$(p,k,B){var I=-1,D=p.length;k<0&&(k=-k>D?0:D+k),B=B>D?D:B,B<0&&(B+=D),D=k>B?0:B-k>>>0,k>>>=0;for(var T=Array(D);++I<D;)T[I]=p[I+k];return T}function U$(p,k,B){var I=p.length;return B=B===void 0?I:B,!k&&B>=I?p:z$(p,k,B)}function V$(p,k){for(var B=p.length;B--&&Ca(k,p[B],0)>-1;);return B}function q$(p,k){for(var B=-1,I=p.length;++B<I&&Ca(k,p[B],0)>-1;);return B}function W$(p){return p.split("")}var G$="\\ud800-\\udfff",Z$="\\u0300-\\u036f",Y$="\\ufe20-\\ufe2f",Q$="\\u20d0-\\u20ff",K$=Z$+Y$+Q$,J$="\\ufe0e\\ufe0f",X$="\\u200d",tj=RegExp("["+X$+G$+K$+J$+"]");function ej(p){return tj.test(p)}var J3="\\ud800-\\udfff",nj="\\u0300-\\u036f",oj="\\ufe20-\\ufe2f",rj="\\u20d0-\\u20ff",ij=nj+oj+rj,sj="\\ufe0e\\ufe0f",lj="["+J3+"]",ff="["+ij+"]",mf="\\ud83c[\\udffb-\\udfff]",cj="(?:"+ff+"|"+mf+")",X3="[^"+J3+"]",tC="(?:\\ud83c[\\udde6-\\uddff]){2}",eC="[\\ud800-\\udbff][\\udc00-\\udfff]",aj="\\u200d",nC=cj+"?",oC="["+sj+"]?",dj="(?:"+aj+"(?:"+[X3,tC,eC].join("|")+")"+oC+nC+")*",uj=oC+nC+dj,hj="(?:"+[X3+ff+"?",ff,tC,eC,lj].join("|")+")",fj=RegExp(mf+"(?="+mf+")|"+hj+uj,"g");function mj(p){return p.match(fj)||[]}function rC(p){return ej(p)?mj(p):W$(p)}function gj(p){return p==null?"":hf(p)}var pj=/^\s+|\s+$/g;function Cj(p,k,B){if(p=gj(p),p&&(B||k===void 0))return p.replace(pj,"");if(!p||!(k=hf(k)))return p;var I=rC(p),D=rC(k),T=q$(I,D),R=V$(I,D)+1;return U$(I,T,R).join("")}var bj=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,vj=/,/,kj=/(=.+)?(\s*)$/,yj=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function wj(p){return p=p.toString().replace(yj,""),p=p.match(bj)[2].replace(" ",""),p=p?p.split(vj):[],p=p.map(function(k){return Cj(k.replace(kj,""))}),p}function iC(p,k){var B={};js(p,function(I,D){var T,R=L(I),_=!R&&I.length===1||R&&I.length===0;if(un(I))T=I.slice(0,-1),I=I[I.length-1],B[D]=T.concat(T.length>0?q:I);else if(_)B[D]=I;else{if(T=wj(I),I.length===0&&!R&&T.length===0)throw new Error("autoInject task functions require explicit parameters.");R||T.pop(),B[D]=T.concat(q)}function q(Q,W){var X=hi(T,function(xt){return Q[xt]});X.push(W),x(I).apply(null,X)}}),uf(B,k)}function hn(){this.head=this.tail=null,this.length=0}function sC(p,k){p.length=1,p.head=p.tail=k}hn.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},hn.prototype.empty=function(){for(;this.head;)this.shift();return this},hn.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},hn.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},hn.prototype.unshift=function(p){this.head?this.insertBefore(this.head,p):sC(this,p)},hn.prototype.push=function(p){this.tail?this.insertAfter(this.tail,p):sC(this,p)},hn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},hn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},hn.prototype.toArray=function(){for(var p=Array(this.length),k=this.head,B=0;B<this.length;B++)p[B]=k.data,k=k.next;return p},hn.prototype.remove=function(p){for(var k=this.head;k;){var B=k.next;p(k)&&this.removeLink(k),k=B}return this};function lC(p,k,B){if(k==null)k=1;else if(k===0)throw new Error("Concurrency must not be zero");var I=x(p),D=0,T=[],R=!1;function _(X,xt,ie){if(ie!=null&&typeof ie!="function")throw new Error("task callback must be a function");if(W.started=!0,un(X)||(X=[X]),X.length===0&&W.idle())return m(function(){W.drain()});for(var Ln=0,ze=X.length;Ln<ze;Ln++){var Mn={data:X[Ln],callback:ie||ft};xt?W._tasks.unshift(Mn):W._tasks.push(Mn)}R||(R=!0,m(function(){R=!1,W.process()}))}function q(X){return function(xt){D-=1;for(var ie=0,Ln=X.length;ie<Ln;ie++){var ze=X[ie],Mn=Ca(T,ze,0);Mn===0?T.shift():Mn>0&&T.splice(Mn,1),ze.callback.apply(ze,arguments),xt!=null&&W.error(xt,ze.data)}D<=W.concurrency-W.buffer&&W.unsaturated(),W.idle()&&W.drain(),W.process()}}var Q=!1,W={_tasks:new hn,concurrency:k,payload:B,saturated:ft,unsaturated:ft,buffer:k/4,empty:ft,drain:ft,error:ft,started:!1,paused:!1,push:function(X,xt){_(X,!1,xt)},kill:function(){W.drain=ft,W._tasks.empty()},unshift:function(X,xt){_(X,!0,xt)},remove:function(X){W._tasks.remove(X)},process:function(){if(!Q){for(Q=!0;!W.paused&&D<W.concurrency&&W._tasks.length;){var X=[],xt=[],ie=W._tasks.length;W.payload&&(ie=Math.min(ie,W.payload));for(var Ln=0;Ln<ie;Ln++){var ze=W._tasks.shift();X.push(ze),T.push(ze),xt.push(ze.data)}D+=1,W._tasks.length===0&&W.empty(),D===W.concurrency&&W.saturated();var Mn=Dn(q(X));I(xt,Mn)}Q=!1}},length:function(){return W._tasks.length},running:function(){return D},workersList:function(){return T},idle:function(){return W._tasks.length+D===0},pause:function(){W.paused=!0},resume:function(){W.paused!==!1&&(W.paused=!1,m(W.process))}};return W}function cC(p,k){return lC(p,1,k)}var fi=ee(dr,1);function wo(p,k,B,I){I=ko(I||ft);var D=x(B);fi(p,function(T,R,_){D(k,T,function(q,Q){k=Q,_(q)})},function(T){I(T,k)})}function gf(){var p=hi(arguments,x);return function(){var k=o(arguments),B=this,I=k[k.length-1];typeof I=="function"?k.pop():I=ft,wo(p,k,function(D,T,R){T.apply(B,D.concat(function(_){var q=o(arguments,1);R(_,q)}))},function(D,T){I.apply(B,[D].concat(T))})}}var aC=function(){return gf.apply(null,o(arguments).reverse())},Bj=Array.prototype.concat,ba=function(p,k,B,I){I=I||ft;var D=x(B);ui(p,k,function(T,R){D(T,function(_){return _?R(_):R(null,o(arguments,1))})},function(T,R){for(var _=[],q=0;q<R.length;q++)R[q]&&(_=Bj.apply(_,R[q]));return I(T,_)})},dC=ee(ba,1/0),uC=ee(ba,1),hC=function(){var p=o(arguments),k=[null].concat(p);return function(){var B=arguments[arguments.length-1];return B.apply(this,k)}};function Hs(p){return p}function mi(p,k){return function(B,I,D,T){T=T||ft;var R=!1,_;B(I,function(q,Q,W){D(q,function(X,xt){X?W(X):p(xt)&&!_?(R=!0,_=k(!0,q),W(null,sf)):W()})},function(q){q?T(q):T(null,R?_:k(!1))})}}function fC(p,k){return k}var va=ai(mi(Hs,fC)),Fs=di(mi(Hs,fC)),ka=ee(Fs,1);function mC(p){return function(k){var B=o(arguments,1);B.push(function(I){var D=o(arguments,1);typeof console=="object"&&(I?console.error&&console.error(I):console[p]&&pa(D,function(T){console[p](T)}))}),x(k).apply(null,B)}}var gC=mC("dir");function pC(p,k,B){B=Dn(B||ft);var I=x(p),D=x(k);function T(_){if(_)return B(_);var q=o(arguments,1);q.push(R),D.apply(this,q)}function R(_,q){if(_)return B(_);if(!q)return B(null);I(T)}R(null,!0)}function pf(p,k,B){B=Dn(B||ft);var I=x(p),D=function(T){if(T)return B(T);var R=o(arguments,1);if(k.apply(this,R))return I(D);B.apply(null,[null].concat(R))};I(D)}function CC(p,k,B){pf(p,function(){return!k.apply(this,arguments)},B)}function bC(p,k,B){B=Dn(B||ft);var I=x(k),D=x(p);function T(_){if(_)return B(_);D(R)}function R(_,q){if(_)return B(_);if(!q)return B(null);I(T)}D(R)}function vC(p){return function(k,B,I){return p(k,I)}}function ya(p,k,B){yo(p,vC(x(k)),B)}function zs(p,k,B,I){ma(k)(p,vC(x(B)),I)}var Us=ee(zs,1);function Cf(p){return L(p)?p:i(function(k,B){var I=!0;k.push(function(){var D=arguments;I?m(function(){B.apply(null,D)}):B.apply(null,D)}),p.apply(this,k),I=!1})}function wa(p){return!p}var Ba=ai(mi(wa,wa)),Vs=di(mi(wa,wa)),Ea=ee(Vs,1);function kC(p){return function(k){return k==null?void 0:k[p]}}function Ej(p,k,B,I){var D=new Array(k.length);p(k,function(T,R,_){B(T,function(q,Q){D[R]=!!Q,_(q)})},function(T){if(T)return I(T);for(var R=[],_=0;_<k.length;_++)D[_]&&R.push(k[_]);I(null,R)})}function Ij(p,k,B,I){var D=[];p(k,function(T,R,_){B(T,function(q,Q){q?_(q):(Q&&D.push({index:R,value:T}),_())})},function(T){T?I(T):I(null,hi(D.sort(function(R,_){return R.index-_.index}),kC("value")))})}function bf(p,k,B,I){var D=Ps(k)?Ej:Ij;D(p,k,x(B),I||ft)}var Ia=ai(bf),qs=di(bf),xa=ee(qs,1);function yC(p,k){var B=Dn(k||ft),I=x(Cf(p));function D(T){if(T)return B(T);I(D)}D()}var Sa=function(p,k,B,I){I=I||ft;var D=x(B);ui(p,k,function(T,R){D(T,function(_,q){return _?R(_):R(null,{key:q,val:T})})},function(T,R){for(var _={},q=Object.prototype.hasOwnProperty,Q=0;Q<R.length;Q++)if(R[Q]){var W=R[Q].key,X=R[Q].val;q.call(_,W)?_[W].push(X):_[W]=[X]}return I(T,_)})},wC=ee(Sa,1/0),BC=ee(Sa,1),EC=mC("log");function Ta(p,k,B,I){I=ko(I||ft);var D={},T=x(B);dr(p,k,function(R,_,q){T(R,_,function(Q,W){if(Q)return q(Q);D[_]=W,q()})},function(R){I(R,D)})}var IC=ee(Ta,1/0),xC=ee(Ta,1);function SC(p,k){return k in p}function TC(p,k){var B=Object.create(null),I=Object.create(null);k=k||Hs;var D=x(p),T=i(function(_,q){var Q=k.apply(null,_);SC(B,Q)?m(function(){q.apply(null,B[Q])}):SC(I,Q)?I[Q].push(q):(I[Q]=[q],D.apply(null,_.concat(function(){var W=o(arguments);B[Q]=W;var X=I[Q];delete I[Q];for(var xt=0,ie=X.length;xt<ie;xt++)X[xt].apply(null,W)})))});return T.memo=B,T.unmemoized=p,T}var Da;c?Da=process.nextTick:l?Da=setImmediate:Da=a;var DC=h(Da);function vf(p,k,B){B=B||ft;var I=Ps(k)?[]:{};p(k,function(D,T,R){x(D)(function(_,q){arguments.length>2&&(q=o(arguments,1)),I[T]=q,R(_)})},function(D){B(D,I)})}function LC(p,k){vf(yo,p,k)}function MC(p,k,B){vf(ma(k),p,B)}var kf=function(p,k){var B=x(p);return lC(function(I,D){B(I[0],D)},k,1)},RC=function(p,k){var B=kf(p,k);return B.push=function(I,D,T){if(T==null&&(T=ft),typeof T!="function")throw new Error("task callback must be a function");if(B.started=!0,un(I)||(I=[I]),I.length===0)return m(function(){B.drain()});D=D||0;for(var R=B._tasks.head;R&&D>=R.priority;)R=R.next;for(var _=0,q=I.length;_<q;_++){var Q={data:I[_],priority:D,callback:T};R?B._tasks.insertBefore(R,Q):B._tasks.push(Q)}m(B.process)},delete B.unshift,B};function OC(p,k){if(k=ko(k||ft),!un(p))return k(new TypeError("First argument to race must be an array of functions"));if(!p.length)return k();for(var B=0,I=p.length;B<I;B++)x(p[B])(k)}function La(p,k,B,I){var D=o(p).reverse();wo(D,k,B,I)}function Ma(p){var k=x(p);return i(function(I,D){return I.push(function(R,_){if(R)D(null,{error:R});else{var q;arguments.length<=2?q=_:q=o(arguments,1),D(null,{value:q})}}),k.apply(this,I)})}function AC(p){var k;return un(p)?k=hi(p,Ma):(k={},js(p,function(B,I){k[I]=Ma.call(this,B)})),k}function _C(p,k,B,I){bf(p,k,function(D,T){B(D,function(R,_){T(R,!_)})},I)}var NC=ai(_C),yf=di(_C),PC=ee(yf,1);function $C(p){return function(){return p}}function Ra(p,k,B){var I=5,D=0,T={times:I,intervalFunc:$C(D)};function R(W,X){if(typeof X=="object")W.times=+X.times||I,W.intervalFunc=typeof X.interval=="function"?X.interval:$C(+X.interval||D),W.errorFilter=X.errorFilter;else if(typeof X=="number"||typeof X=="string")W.times=+X||I;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof p=="function"?(B=k||ft,k=p):(R(T,p),B=B||ft),typeof k!="function")throw new Error("Invalid arguments for async.retry");var _=x(k),q=1;function Q(){_(function(W){W&&q++<T.times&&(typeof T.errorFilter!="function"||T.errorFilter(W))?setTimeout(Q,T.intervalFunc(q)):B.apply(null,arguments)})}Q()}var jC=function(p,k){k||(k=p,p=null);var B=x(k);return i(function(I,D){function T(R){B.apply(null,I.concat(R))}p?Ra(p,T,D):Ra(T,D)})};function HC(p,k){vf(fi,p,k)}var Oa=ai(mi(Boolean,Hs)),Ws=di(mi(Boolean,Hs)),Aa=ee(Ws,1);function FC(p,k,B){var I=x(k);ga(p,function(T,R){I(T,function(_,q){if(_)return R(_);R(null,{value:T,criteria:q})})},function(T,R){if(T)return B(T);B(null,hi(R.sort(D),kC("value")))});function D(T,R){var _=T.criteria,q=R.criteria;return _<q?-1:_>q?1:0}}function zC(p,k,B){var I=x(p);return i(function(D,T){var R=!1,_;function q(){var Q=p.name||"anonymous",W=new Error('Callback function "'+Q+'" timed out.');W.code="ETIMEDOUT",B&&(W.info=B),R=!0,T(W)}D.push(function(){R||(T.apply(null,arguments),clearTimeout(_))}),_=setTimeout(q,k),I.apply(null,D)})}var xj=Math.ceil,Sj=Math.max;function Tj(p,k,B,I){for(var D=-1,T=Sj(xj((k-p)/(B||1)),0),R=Array(T);T--;)R[I?T:++D]=p,p+=B;return R}function _a(p,k,B,I){var D=x(B);ui(Tj(0,p,1),k,D,I)}var UC=ee(_a,1/0),VC=ee(_a,1);function qC(p,k,B,I){arguments.length<=3&&(I=B,B=k,k=un(p)?[]:{}),I=ko(I||ft);var D=x(B);yo(p,function(T,R,_){D(k,T,R,_)},function(T){I(T,k)})}function WC(p,k){var B=null,I;k=k||ft,Us(p,function(D,T){x(D)(function(R,_){arguments.length>2?I=o(arguments,1):I=_,B=R,T(!R)})},function(){k(B,I)})}function GC(p){return function(){return(p.unmemoized||p).apply(null,arguments)}}function wf(p,k,B){B=Dn(B||ft);var I=x(k);if(!p())return B(null);var D=function(T){if(T)return B(T);if(p())return I(D);var R=o(arguments,1);B.apply(null,[null].concat(R))};I(D)}function ZC(p,k,B){wf(function(){return!p.apply(this,arguments)},k,B)}var YC=function(p,k){if(k=ko(k||ft),!un(p))return k(new Error("First argument to waterfall must be an array of functions"));if(!p.length)return k();var B=0;function I(T){var R=x(p[B++]);T.push(Dn(D)),R.apply(null,T)}function D(T){if(T||B===p.length)return k.apply(null,arguments);I(o(arguments,1))}I([])},Dj={apply:r,applyEach:Z3,applyEachSeries:Y3,asyncify:C,auto:uf,autoInject:iC,cargo:cC,compose:aC,concat:dC,concatLimit:ba,concatSeries:uC,constant:hC,detect:va,detectLimit:Fs,detectSeries:ka,dir:gC,doDuring:pC,doUntil:CC,doWhilst:pf,during:bC,each:ya,eachLimit:zs,eachOf:yo,eachOfLimit:dr,eachOfSeries:fi,eachSeries:Us,ensureAsync:Cf,every:Ba,everyLimit:Vs,everySeries:Ea,filter:Ia,filterLimit:qs,filterSeries:xa,forever:yC,groupBy:wC,groupByLimit:Sa,groupBySeries:BC,log:EC,map:ga,mapLimit:ui,mapSeries:df,mapValues:IC,mapValuesLimit:Ta,mapValuesSeries:xC,memoize:TC,nextTick:DC,parallel:LC,parallelLimit:MC,priorityQueue:RC,queue:kf,race:OC,reduce:wo,reduceRight:La,reflect:Ma,reflectAll:AC,reject:NC,rejectLimit:yf,rejectSeries:PC,retry:Ra,retryable:jC,seq:gf,series:HC,setImmediate:m,some:Oa,someLimit:Ws,someSeries:Aa,sortBy:FC,timeout:zC,times:UC,timesLimit:_a,timesSeries:VC,transform:qC,tryEach:WC,unmemoize:GC,until:ZC,waterfall:YC,whilst:wf,all:Ba,allLimit:Vs,allSeries:Ea,any:Oa,anyLimit:Ws,anySeries:Aa,find:va,findLimit:Fs,findSeries:ka,forEach:ya,forEachSeries:Us,forEachLimit:zs,forEachOf:yo,forEachOfSeries:fi,forEachOfLimit:dr,inject:wo,foldl:wo,foldr:La,select:Ia,selectLimit:qs,selectSeries:xa,wrapSync:C};e.default=Dj,e.apply=r,e.applyEach=Z3,e.applyEachSeries=Y3,e.asyncify=C,e.auto=uf,e.autoInject=iC,e.cargo=cC,e.compose=aC,e.concat=dC,e.concatLimit=ba,e.concatSeries=uC,e.constant=hC,e.detect=va,e.detectLimit=Fs,e.detectSeries=ka,e.dir=gC,e.doDuring=pC,e.doUntil=CC,e.doWhilst=pf,e.during=bC,e.each=ya,e.eachLimit=zs,e.eachOf=yo,e.eachOfLimit=dr,e.eachOfSeries=fi,e.eachSeries=Us,e.ensureAsync=Cf,e.every=Ba,e.everyLimit=Vs,e.everySeries=Ea,e.filter=Ia,e.filterLimit=qs,e.filterSeries=xa,e.forever=yC,e.groupBy=wC,e.groupByLimit=Sa,e.groupBySeries=BC,e.log=EC,e.map=ga,e.mapLimit=ui,e.mapSeries=df,e.mapValues=IC,e.mapValuesLimit=Ta,e.mapValuesSeries=xC,e.memoize=TC,e.nextTick=DC,e.parallel=LC,e.parallelLimit=MC,e.priorityQueue=RC,e.queue=kf,e.race=OC,e.reduce=wo,e.reduceRight=La,e.reflect=Ma,e.reflectAll=AC,e.reject=NC,e.rejectLimit=yf,e.rejectSeries=PC,e.retry=Ra,e.retryable=jC,e.seq=gf,e.series=HC,e.setImmediate=m,e.some=Oa,e.someLimit=Ws,e.someSeries=Aa,e.sortBy=FC,e.timeout=zC,e.times=UC,e.timesLimit=_a,e.timesSeries=VC,e.transform=qC,e.tryEach=WC,e.unmemoize=GC,e.until=ZC,e.waterfall=YC,e.whilst=wf,e.all=Ba,e.allLimit=Vs,e.allSeries=Ea,e.any=Oa,e.anyLimit=Ws,e.anySeries=Aa,e.find=va,e.findLimit=Fs,e.findSeries=ka,e.forEach=ya,e.forEachSeries=Us,e.forEachLimit=zs,e.forEachOf=yo,e.forEachOfSeries=fi,e.forEachOfLimit=dr,e.inject=wo,e.foldl=wo,e.foldr=La,e.select=Ia,e.selectLimit=qs,e.selectSeries=xa,e.wrapSync=C,Object.defineProperty(e,"__esModule",{value:!0})})})(Tu,Tu.exports);var M2={exports:{}},Du=M2.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)?Du(n,t):i};Du.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=Du(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 R2=co,Xk=D2,ty=L2,Jl=en,Lu=Tu.exports,ey=M2.exports,O2=qo.ACTIONS,A2=Pt;function Pt(n,t){if(R2.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}R2.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||ey();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);Lu.parallel([function(i){Lu.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();Lu.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?O2.presenceSubscribe:O2.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=Jl.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=Jl.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 Jl.nextTick(t,n);n&&this.emit("error",n)},Pt.prototype._createLocalPresence=function(n){return new Xk(this,n)},Pt.prototype._createRemotePresence=function(n){return new ty(this,n)},Pt.prototype._callEachOrEmit=function(n,t){var e=Jl.callEach(n,t);!e&&t&&this.emit("error",t)};var Gi=D2,_2=Gl,ny=en,N2=_2.CODES,oy=on;function on(n,t){Gi.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()}on.prototype=Object.create(Gi.prototype),on.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:N2.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,Gi.prototype.submit.call(this,n,t)},on.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),Gi.prototype.destroy.call(this,n)},on.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={})})}},on.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)},on.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)}},on.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},on.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},on.prototype._message=function(){var n=Gi.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},on.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!ny.supportsPresence(o))throw new _2(N2.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var P2={};(function(n){var t=Vi,e=Gl,o=en,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,h=t.map[a.type];if(!h)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(a.data),l.type=h.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(h){return new e(r.ERR_OT_OP_NOT_APPLIED,h.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(h){return h}}}c.v!=null&&c.v++},n.applyOps=function(l,c,a){a=a||{};for(var h=0;h<c.length;h++){var f=c[h];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 h=this.checkOp(c);if(h)return h;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 h=l.data;a.length>1&&(h=o.clone(h));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=h,w=0;w<C.length;w++){var E=C[w];Object.prototype.toString.call(v)=="[object Array]"?C[w]=+E:v.constructor===Object&&(C[w]=E.toString()),v=v[E]}f<a.length-1&&(h=t.defaultType.apply(h,[m]))}}}}})(P2);var Zi=L2,ry=P2,iy=Pe;function Pe(n,t){Zi.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(Zi.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),Zi.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()},Zi.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},Zi.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++):ry.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 $2=A2,sy=oy,ly=iy;function Or(n,t,e){var o=Or.channel(t,e);$2.call(this,n,o),this.collection=t,this.id=e}var cy=Or;Or.prototype=Object.create($2.prototype),Or.channel=function(n,t){return n+"."+t},Or.prototype._createLocalPresence=function(n){return new sy(this,n)},Or.prototype._createRemotePresence=function(n){return new ly(this,n)};var ay=dy;function dy(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var uy=ay,j2=co,H2=Yi;function Yi(n,t,e,o,r){if(j2.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}j2.mixin(Yi),Yi.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Yi.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Yi.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new uy(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var F2=H2,hy=en,fy=qo.ACTIONS,my=Mu;function Mu(n,t,e,o,r,i){if(F2.call(this,n,t,e,o,i),!hy.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}Mu.prototype=Object.create(F2.prototype),Mu.prototype._message=function(){return{a:fy.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var z2=H2,gy=en,py=qo.ACTIONS,Cy=Ru;function Ru(n,t,e,o,r,i){if(z2.call(this,n,t,e,o,i),!gy.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}Ru.prototype=Object.create(z2.prototype),Ru.prototype._message=function(){return{a:py.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var by=Vk,vy=Yk,ky=A2,U2=cy,yy=my,wy=Cy,V2=co,Ar=Gl,pt=qo.ACTIONS,q2=Vi,rn=en,Qi=k2,Ki=Ar.CODES;function W2(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var By=J;function J(n){V2.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=W2(n),this.bindToSocket(n)}V2.mixin(J),J.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=W2(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{Qi.warn("Failed to parse message",o);return}e.debug&&Qi.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){rn.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)}},J.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=G2(n.error,n),delete n.error),n.a){case pt.initLegacy:return this._handleLegacyInit(n);case pt.handshake:return this._handleHandshake(t,n);case pt.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case pt.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case pt.queryUnsubscribe:return;case pt.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 pt.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case pt.bulkSubscribe:case pt.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case pt.snapshotFetch:case pt.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case pt.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case pt.subscribe:case pt.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case pt.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case pt.presence:return this._handlePresence(t,n);case pt.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case pt.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case pt.presenceRequest:return this._handlePresenceRequest(t,n);case pt.pingPong:return this._handlePingPong(t);default:Qi.warn("Ignoring unrecognized message",n)}};function G2(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}J.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](G2(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 Qi.error("Invalid bulk message",t)},J.prototype._reset=function(){this.agent=null},J.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 Ar(Ki.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)}},J.prototype.startBulk=function(){this.bulk||(this.bulk={})},J.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},J.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})}},J.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)}},J.prototype.sendFetch=function(n){return this._sendActions(pt.fetch,n,n.version)},J.prototype.sendSubscribe=function(n){return this._sendActions(pt.subscribe,n,n.version)},J.prototype.sendUnsubscribe=function(n){return this._sendActions(pt.unsubscribe,n)},J.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:pt.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)},J.prototype.send=function(n){this.debug&&Qi.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},J.prototype.ping=function(){if(!this.canSend)throw new Ar(Ki.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:pt.pingPong};this.send(n)},J.prototype.close=function(){this.socket.close()},J.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},J.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new by(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},J.prototype._destroyDoc=function(n){!n._wantsDestroy||(rn.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},J.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},J.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new vy(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},J.prototype._destroyQuery=function(n){delete this.queries[n.id]},J.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(pt.queryFetch,n,t,e,o)},J.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(pt.querySubscribe,n,t,e,o)},J.prototype.hasPending=function(){return!!(this._firstDoc(Xl)||this._firstQuery(Xl)||this._firstSnapshotRequest())};function Xl(n){return n.hasPending()}J.prototype.hasWritePending=function(){return!!this._firstDoc(Ey)};function Ey(n){return n.hasWritePending()}J.prototype.whenNothingPending=function(n){var t=this._firstDoc(Xl);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Xl);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}rn.nextTick(n)},J.prototype._nothingPendingRetry=function(n){var t=this;return function(){rn.nextTick(function(){t.whenNothingPending(n)})}},J.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}}},J.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},J.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},J.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new yy(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},J.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new wy(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},J.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},J.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},J.prototype._initializeHandshake=function(){this.send({a:pt.handshake,id:this.id})},J.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},J.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},J.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new Ar(Ki.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(q2.map[n.type]!==q2.defaultType)return this.emit("error",new Ar(Ki.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new Ar(Ki.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},J.prototype.getPresence=function(n){var t=this,e=rn.digOrCreate(this._presences,n,function(){return new ky(t,n)});return e._wantsDestroy=!1,e},J.prototype.getDocPresence=function(n,t){var e=U2.channel(n,t),o=this,r=rn.digOrCreate(this._presences,e,function(){return new U2(o,n,t)});return r._wantsDestroy=!1,r},J.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},J.prototype._addPresence=function(n){rn.digOrCreate(this._presences,n.channel,function(){return n})},J.prototype._handlePresenceSubscribe=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},J.prototype._handlePresenceUnsubscribe=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},J.prototype._handlePresence=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},J.prototype._handlePresenceRequest=function(n,t){var e=rn.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var Z2=By,Iy=Vi;const tc={err:1001,msg:"user auth error",name:"AuthError"},xy={err:1002,msg:"you don't have required permission",name:"PermissionError"},Ou={err:1003,msg:"Too many user connected",name:"MaxUserError"},Ji={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},Sy={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},Ty={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},Xi="x-live-editor-token",ec="x-live-editor-base-url",ae=y("auth-connection");function Dy(n){try{n()}catch(t){ae.error(t)}}class Ly{constructor(t,e){u(this,"connection");u(this,"ws");u(this,"retryCount");u(this,"events",new If.EventEmitter);u(this,"token",null);u(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 Do(this.getBaseURL())}async auth(t){d(ae,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[Xi]:t.token,[ec]: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:{[ec]:Do(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new E9.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(Z2.prototype),d(ae,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}}},Z2.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,ae.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){ae.error(t),setTimeout(()=>this.handleAuthError(),0)}}else ae.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(tc.msg);t.code=tc.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(Ji.msg);t.code=Ji.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===tc.err)ae.warn("auth error"),this.handleAuthError();else if(o===Ou.err)ae.warn(Ou.msg),this.emitMaxUsersError();else if(o===Ji.err){ae.warn(Ji.msg);try{this.emitRequestReloadError()}catch(r){ae.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else ae.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError()}get(t,e){return d(ae,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(d(ae,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){d(ae,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){d(ae,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(),Dy(()=>{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()}}y("utils/file");function My(){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}My();async function Ry(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new I9.Hash;for(let s=0;s<o;s++){const l=s*102400;let c=l+102400;c>e&&(c=e);const h=await n.slice(l,c,n.type).arrayBuffer();r.update(new Uint8Array(h))}const i=r.digest();return Do(i)}const kn=y("sharedb-doc/client");class Oy{constructor(t,e,o){u(this,"connection");u(this,"auth");u(this,"doc",null);u(this,"reauthFunc");u(this,"clientId",N());u(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});d(kn,!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),kn.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;Iy.register(Ys.type),this.connection=new Ly(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return d(kn,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,{[Xi]: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=>{kn.info(`on progress: ${C.loaded}`);let v=C.loaded*100/s;v>100&&(v=100),r(v)},c=await Ry(e),a=await this.getFileUrlByHash(t,c,e.name,e.size,o);if(a)return r(-1),a;let h=t;i!=null&&i.thumbnail&&(h+="/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(h,{method:"post",data:f,withCredentials:!0,headers:{...o},onUploadProgress:l});return kn.info(m),r(100),Array.isArray(m.data)?m.data[0]:m.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;d(kn,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[Xi]:this.connection.token},e,o);return d(kn,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(kn,o,"no token"),c.headers={...c.headers,[Xi]:o,[ec]:this.connection.getBase64BaseURL()};try{return await w9.default(t,c)}catch(a){if(r=a,((i=a==null?void 0:a.response)==null?void 0:i.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw a;o=h.token;continue}throw(s=a.response)!=null&&s.data&&(a.responseData=a.response.data),a}}throw d(kn,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=B9.default(s,h=>!!h.create);let c=null;l!==-1&&(c=s[l],s.splice(0,l+1));let a;return c?(d(kn,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/${Do(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 Ay(){return{blocks:[{id:N(),type:"text",text:[]}],comments:{},meta:{}}}const Au=y("block-ids");class _y{constructor(){u(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(Au,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(Au,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 Ny{constructor(){u(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new _y,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(Au,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class Y2{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 Nt=y("op-parser");function _r(n){return n==="blocks"?"root":n}class Py{constructor(t,e){u(this,"updatingBlockDataDeltaMap",new Map);u(this,"blockIds",new Ny);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&&(Nt.debug(`ignore update object data before delete block: ${JSON.stringify(r)}`),this.updatingBlockDataDeltaMap.delete(o)),this.handler.onDeleteBlock(_r(t),e,this.local)}onInsertBlock(t,e,o){this.blockIds.onInsertBlock(t,e),this.handler.onInsertBlock(_r(t),e,o,this.local)}onUpdateBlockText(t,e,o){this.handler.onUpdateBlockText(_r(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 Y2,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 Y2,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(_r(o),r,e.toDocBlockDelta(),this.local)})}}class Q2{}class _u{constructor(t){u(this,"key");this.key=t}}function $y(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 h=c[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=i.i;d(Nt,s.id,"block id is required"),d(Nt,s.type,"block type is required");for(let l=1;l<o.length;l++){const c=o[l],a=c[0],h=c[1];s[a]=h.i}return e.onInsertBlock(n,r,s),!0}function Nu(n,t,e,o){if(e==="upsert"&&$y(n,t,o))return;d(Nt,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(Nt,typeof c=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),d(Nt,c.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),r.splice(0,2),e==="upsert"){const h=c.e;o.onUpdateBlockText(n,i,h)}d(Nt,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){d(Nt,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const c=l[0];d(Nt,typeof c=="string",`invalid block op: key ${JSON.stringify(c)}`);const a=l[1];if(c==="text"){if(d(Nt,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 _u(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 Q2),e==="upsert"&&c.i&&o.onInsertBlock(n,i,c.i),r.shift()}else{d(Nt,typeof l=="string","data is not string"),d(Nt,l!=="text","data !== 'text'"),d(Nt,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 _u(c)),e==="upsert"&&a.i&&o.onInsertBlockData(n,i,c,a.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Q2?o.onDeleteBlock(n,i):l instanceof _u?o.onDeleteBlockData(n,i,l.key):d(Nt,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function jy(n,t,e,o){Nt.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function Hy(n,t,e,o){const r=n[1],i=n[2];d(Nt,r,`invalid comment op, no commentId: ${JSON.stringify(n)}`),d(Nt,i,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof i=="string"?Nt.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):Nt.error(`unknown comment op, ${JSON.stringify(n)}`)}function Pu(n,t,e,o){const r=n[0];if(Array.isArray(r)){r.forEach(l=>{Pu(l,t,e,o)});return}const i=r;if(d(Nt,typeof i=="string",`invalid container id: ${JSON.stringify(n)}`),i==="meta"){jy(n);return}if(i==="comments"){Hy(n,t,e,o);return}const s=i;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(l=>{Nu(s,l,t,e)}):n.slice(1).forEach(l=>{Nu(s,l,t,e)});else if(typeof n[1]=="object"){const l=n[1];l.r&&t==="remove"&&o.onDeleteContainer(_r(s),e.local),l.i&&t==="upsert"&&o.onCreateContainer(_r(s),l.i,e.local)}else d(Nt,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Nu(s,n.slice(1),t,e)}function K2(n,t,e){const o=new Py(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=>{Pu(c,i,o,t)}):Pu(s,i,o,t)}o.executeUpdateBlockDataActions()}const Fy=y("sharedb-comments");function $u(n){if(n.doc)return Y.default(n.doc);const t=n.blocks;d(Fy,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 ju(n,t){const e={...n,doc:t};return delete e.blocks,Y.default(e)}const Bt=y("sharedb-doc/doc-container"),X2="ot-json1";Ys.type.registerSubtype(xk.type),Ys.type.name=X2,Ys.type.invert=null;class ts extends vi{constructor(e,o,r=!0){super();u(this,"doc");u(this,"client");u(this,"localPresence");u(this,"remoteCaretHandler",new Ek);u(this,"batching",0);u(this,"status","clean");u(this,"disableLogout");u(this,"destroyed",!1);u(this,"handleNothingPending",()=>{this.setStatus("clean")});u(this,"handleCreate",()=>{this.handleReload("doc created")});u(this,"handleDel",()=>{});u(this,"handleReload",e=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})});u(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()});u(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});u(this,"insertObject",async(e,o,r)=>{const i=[e,o,{i:r}];return this.submitOp(i)});u(this,"deleteObject",async(e,o)=>{const r=[e,o,{r:!0}];return this.submitOp(r)});u(this,"replaceObject",async(e,o,r)=>{const i=[e,o,{r:!0,i:r}];return this.submitOp(i)});u(this,"updateObject",async(e,o,r)=>{const i=this.data()[e][o],s=[e,o];return Object.entries(r).forEach(([l,c])=>{if(!Zs.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)});u(this,"broadcastMessage",async e=>{const o={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});u(this,"data",()=>this.doc.data);u(this,"submitOp",async e=>new Promise((o,r)=>{if(this.destroyed){Bt.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(Bt.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),Bt.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(Bt.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));u(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,X2,i=>{i?r(i):o()})}));u(this,"submitInsertChildContainer",async(e,o)=>{const r=[lo(e),{i:o}];return this.submitOp(r)});u(this,"submitDeleteChildContainer",async e=>{const o=[lo(e),{r:!0}];return this.submitOp(o)});u(this,"submitInsertBlock",async(e,o,r)=>{const i=[lo(e),o,{i:r}];return this.submitOp(i)});u(this,"submitDeleteBlock",async(e,o)=>{const r=[lo(e),o,{r:!0}];return this.submitOp(r)});u(this,"submitUpdateBlockData",async(e,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[lo(e),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([c,a])=>{if(s.has(c)){const h={r:!0,i:a};i.push([c,h])}});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 h={i:a};i.push([c,h])}),this.submitOp(i)});u(this,"submitUpdateRichText",async(e,o,r)=>{const i=[lo(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});u(this,"handleOp",(e,o,r)=>{if(this.destroyed){Bt.warn("handleOp: destroyed");return}K2(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(Bt,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new Oy(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new ts(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||Ay())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw Bt.error(o),Bt.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 zi(this.data())}getContainerBlocks(e){const o=this.data();d(Bt,o,"no doc data");const r=o[lo(e)];return d(Bt,r,`no container data: ${e}`),Y.default(r)}getBlockData(e,o){const r=this.data();d(Bt,r,"no doc data");const i=r[lo(e)];d(Bt,i,`no container data: ${e}`);const s=i[o];return d(Bt,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(Bt,i.text,"no block text");const s=Y.default(i.text);this.submitUpdateRichText(e,o,r);const l=oe.apply(s,r);return d(Bt,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 $u(o)}localCreateComment(e,o){const r=ju(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=ju(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(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Rr(e),o,r)})}onInsertBlock(e,o,r,i){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Rr(e),o,r,i)})}onUpdateBlockData(e,o,r,i){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Rr(e),o,r,i)})}onUpdateBlockText(e,o,r,i){d(Bt,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Rr(e),o,r,i)})}onDeleteContainer(e,o){d(Bt,this.callbacks.length>0,"no callbacks"),d(Bt,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,Rr(e),o)})}onCreateContainer(e,o,r){d(Bt,this.callbacks.length>0,"no callbacks"),d(Bt,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,Rr(e),o,r)})}onDeleteComment(e,o){d(Bt,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(Bt,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(Bt,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 zi(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return zi(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:zi(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:zi(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){K2(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}y("remote-cursor");class t0{constructor(t){u(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});u(this,"broadcastCaretPos",Qt.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));u(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 e0=y("remote-cursor-decorator");class Hu{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(e0,typeof s=="string","invalid path containerId"),d(e0,typeof l=="number","invalid path blockIndex");const c=t.doc.getBlockData(s,l),a=ce(o);return r.getSimpleCursors(c.id).forEach((f,m)=>{m>a&&(m=a);const C=f.map(w=>({id:N(),type:"remote-cursor",name:w.user.displayName,time:w.time,rainbowIndex:w.user.rainbowIndex})),v=i.get(m);v?v.push(...C):i.set(m,C)}),{insertions:i}}}class n0 extends Wt.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Ct(Cr(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=z(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 zy(n,t){n.addCustom("child-block-tracker",()=>new n0(n)).addListener("change",t)}function Uy(n,t){n.addCustom("child-block-tracker",()=>new n0(n)).removeListener("change",t)}const JH="",Vy={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},qy={colorPalette:{colorDesc:"Text Color",backgroundDesc:"Background Color",reset:"Reset"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}};S.mergeLang({"zh-CN":Vy,"en-US":qy});const XH="";y("button");function Vn(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&&M(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0)),i}function o0(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}const uo=y("filterable-list");function Wy(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")&&M(t,"selected"),t}function r0(n){const t=b("div",["list-root"],null);return n.forEach(e=>{t.appendChild(Wy(e))}),t}function i0(n,t){let e=n;return t&&(e=n.map(o=>({...o,states:o.id===t?["selected"]:void 0}))),e}function Gy(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=r0(i0(n,t==null?void 0:t.initialSelectedId));return s.appendChild(l),e}function s0(n,t,e){const o=n.querySelector(".list");d(uo,o,"no list root");const r=r0(i0(t,e)),i=o.querySelector(".list-root");if(d(uo,i,"no exists menu"),Ii(i,r),e){const s=o.querySelector(".list-item.selected");s&&(d(uo,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class Zy{constructor(t,e){u(this,"root");u(this,"visibleItems");u(this,"selectedId");u(this,"filter","");u(this,"onSelected",null);u(this,"handleKeydown",t=>{this.processKeyDown(t)});u(this,"handleInputChanged",()=>{const t=this.root.querySelector(".filter-input");d(uo,t,"no input");const e=t.value.toLocaleLowerCase();this.setFilter(e)});u(this,"handleClick",t=>{this.processClick(t)});var o;this.items=t,this.options=e,this.root=Gy(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(uo,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(uo,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,s0(this.root,this.visibleItems,t)}focus(){const t=this.root.querySelector(".filter-input");d(uo,t,"no input"),t.focus()}reset(){this.setFilter("");const t=this.root.querySelector(".filter-input");d(uo,t,"no input"),t.value=""}setFilter(t){this.filter!==t&&(this.filter=t,this.visibleItems=this.items.filter(e=>e.name.toLocaleLowerCase().includes(t)),s0(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 Yy extends Zy{constructor(e,o,r){super(e,r);u(this,"tippyInstance");u(this,"onShow",null);u(this,"onHide",null);u(this,"custom",null);u(this,"handleShow",()=>{this.onShow&&this.onShow(this)});u(this,"handleHide",()=>{this.onHide&&this.onHide(this)});u(this,"handleShown",()=>{this.focus()});this.tippyInstance=Sf.default(o,{interactive:!0,content:this.root,trigger:"manual",triggerTarget:null,hideOnClick:!0,arrow:!1,theme:"dropdown-list",offset:[0,0],onHide:this.handleHide,onShow:this.handleShow,onShown:this.handleShown})}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(e){this.tippyInstance.setProps({getReferenceClientRect:()=>e.getBoundingClientRect()}),this.reset(),this.tippyInstance.show(),this.focus()}processKeyDown(e){super.processKeyDown(e),(e.key==="Esc"||e.key==="Enter")&&this.tippyInstance.hide()}processClick(e){super.processClick(e);const o=e.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.tippyInstance.hide()}}const tF="",eF="";function Qy(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 nF="",Nr=y("ui-command-bar-base"),Ky={itemElementTag:"div",tippyArrow:!1},of=class extends Wt.TypedEmitter{constructor(e,o,r){var i,s;super();u(this,"content");u(this,"items");u(this,"subBar",null);u(this,"parentItem",null);u(this,"closeable",null);u(this,"options");u(this,"id");u(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)}}}});u(this,"handleDocumentMouseDown",e=>{e.target instanceof Element&&(this.isInCommandBar(e.target)||this.close())});u(this,"handleHidden",()=>{this.close(),this.emit("close",this),sm(this.id)});u(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&M(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&im(this.id)});u(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)});u(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)&&(F(o,"selected"),this.emit("selectionChange",this,""))});u(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())}});u(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=_n(r);if(!vt(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={...Ky,...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&&F(o,"selected")}selectItem(e){const o=this.getSelectedItem();if(o){if(o.id===e)return;const i=o.id,s=this.getItemElementById(i);s&&F(s,"selected")}const r=this.getItemElementById(e);r?(M(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=of.createSubCommandBar(o,(l=this.closeable)!=null?l:this,e?{id:e}:{});this.subBar=i,this.subBar.on("click",(c,a,h)=>{this.emit("click",c,a,h)}),this.subBar.on("close",()=>{var c;(c=this.subBar)==null||c.destroy(),this.subBar=null,F(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),M(r,"active")}isInCommandBar(e){if(!e||!(e instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&vt(o,e)||vt(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(Nr,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(Nr,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(e){const o=e.getAttribute("data-id");return d(Nr,o,"no data-id attribute"),o}getItemElementById(e){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${e}"]`);return d(Nr,o,`no exists command item, id=${e}`),o}getParentCommandItemElement(e){if(!e||!(e instanceof Element))return null;if(lt(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(Nr,e.children&&e.children.length>0,"no item children");const i=(l=e.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return d(Nr,s,`no creator for command type: ${i}`),s(e,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let Pr=of;u(Pr,"commandBarCreators",new Map),y("ui-command-bar");class nc extends Pr{constructor(){super(...arguments);u(this,"tippyInstance",null)}manualShow(e,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=Sf.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]")}}function Jy(){const n={};for(let t=1;t<=8;t++)n[`heading-${t}`]={shortcut:`/h${t}`};return n}const Xy={"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"},...Jy()};function l0(n){var t,e,o;return(o=(e=n.shortcut)!=null?e:(t=Xy[n.id])==null?void 0:t.shortcut)!=null?o:""}const c0=`<?xml version="1.0" ?>
|
|
27
27
|
<svg
|
|
28
28
|
fill="currentColor"
|
|
29
29
|
xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
|
|
@@ -331,7 +331,7 @@ xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
|
|
|
331
331
|
<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"/>
|
|
332
332
|
<path d="M9.07413 10.8036H13.2226M11.1484 8.91895V13.1009V8.91895Z" stroke="#999999" stroke-linecap="square" fill="none"/>
|
|
333
333
|
<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"/>
|
|
334
|
-
</svg>`;function $w(n,t){var e;if(M(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 i=b("div",["menu-item-icon"],null);n.icon&&(i.innerHTML=n.icon),t.appendChild(i)}const o=b("div",["menu-item-name"],null,n.name);t.appendChild(o);const r=l0(n);if(r&&b("div",["item-shortcut","text"],t,r),n.children&&!n.element){const i=b("div",["menu-item-sub-indicator"],null);i.innerHTML=u0,t.appendChild(i)}if((e=n.states)!=null&&e.includes("checked")){const i=b("div",["menu-item-checked-icon"],null);i.innerHTML=bw,t.appendChild(i)}}}}class Wo extends nc{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){M(t,"menu")}initItemElement(t,e){$w(t,e)}}function jw(n,t,e){var o;return new Wo((o=n.children)!=null?o:[],t,{...e,parentItem:n})}class rc extends nc{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){M(t,"toolbar")}initItemElement(t,e){e.setAttribute("data-button-id",t.id),(!t.children||t.children.length===0)&&this.options.tooltipId&&(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=Fu}t.states&&(t.states.indexOf("checked")!==-1&&M(o,"checked"),t.states.indexOf("disabled")!==-1&&(o.disabled=!0))}}function Hw(n,t,e){var o;return new rc((o=n.children)!=null?o:[],t,{...e,parentItem:n})}const oF="";Pr.registerManualCommandBar("menu",jw),Pr.registerManualCommandBar("toolbar",Hw);const y0=y("ui-base");class ic extends nc{constructor(t,e){var i;const r=[{id:(i=e==null?void 0:e.id)!=null?i:`popup-${N()}`,name:"",element:t}];super(r)}initCommandBarElement(t){M(t,"popper")}initItemElement(t,e){}get popupContent(){const t=this.items[0];d(y0,t,"no dialog item");const e=typeof t.element=="function"?t.element(t):t.element;return d(y0,e,"no item element"),e}}const rF="",w0=y("ui-base");class sc extends nc{constructor(e,o){super(sc.getCommandItems(e,o),void 0,{disablePageScroll:!0,...o});u(this,"handleDocumentMouseDown",e=>{})}initCommandBarElement(e){M(e,"dialog","manual")}initItemElement(e,o){}show(e,o){this.manualShow(e,{...o,theme:"light"})}get dialogContent(){const e=this.items[0];d(w0,e,"no dialog item");const o=e.element;return d(w0,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 Fw=[-1,6,0,1,2,3,4,5],zw=[-1,6,0,1,2,3,4,5,14,13,7,8,9,10,11,12],B0=y("color-palette");function E0(n,t,e,o){d(B0,n>0,"no color in palette");const r=t||1;d(B0,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 h=e(l*i+a);c.appendChild(h)}}return s}function Uw(n){const t=b("button",["color-button"],null),e=Fw[n];return t.setAttribute("data-color-index",`${e}`),t.innerHTML=d0,t}function Vw(n){const t=b("button",["background-color-button"],null),e=zw[n];return t.setAttribute("data-color-index",`${e}`),t}function qw(){const n=b("div",["clear-button-container"],null),t=b("button",["clear-button"],n);return t.innerText=S.t("colorPalette.reset"),n}function Ww(n){const t=b("div",["color-palette"],null);return n.color!==!1&&(b("div",["bar-desc"],t,S.t("colorPalette.colorDesc")),t.appendChild(E0(8,1,Uw,"color"))),n.backgroundColor!==!1&&(b("div",["bar-desc"],t,S.t("colorPalette.backgroundDesc")),t.appendChild(E0(16,2,Vw,"background-color"))),n.clearColorButton!==!1&&t.appendChild(qw()),t}function Gw(n,t,e){const o=t==="color"?"color":"background-color",r=n.querySelector(`.${o} button.selected`);r&&F(r,"selected"),e===null&&(e=-1);const i=n.querySelector(`.${o} button[data-color-index="${e}"]`);i&&M(i,"selected")}const iF="",Zw={};class Yw extends Wt.TypedEmitter{constructor(e=Zw){super();u(this,"root");u(this,"handleClick",e=>{const o=e.target;if(!o||!(o instanceof Element))return;const r=o.closest("button");if(!r)return;if(lt(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)||(lt(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=Ww(e),this.root.addEventListener("click",this.handleClick)}destroy(){this.removeAllListeners(),this.root.removeEventListener("click",this.handleClick)}setColor(e,o){Gw(this.root,e,o)}}class I0{constructor(t,e){u(this,"name","Color Palette");u(this,"element");u(this,"palette");u(this,"closeable",null);this.id=t,this.palette=new Yw(e),this.element=this.palette.root}setCloseable(t){this.closeable=t}destroy(){this.palette.destroy(),this.closeable=null}}function Qw(){const n=b("button",["color-button"],null);return n.innerHTML=d0,n}function Xu(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 Kw extends Wt.TypedEmitter{constructor(e){super();u(this,"id","text-color-item");u(this,"name","Text color");u(this,"dropdown",!0);u(this,"manualShowChildren",!0);u(this,"children",[]);u(this,"element");u(this,"colorPaletteItem");u(this,"latestColors",[null,null]);u(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],Xu(this.element,this.latestColors)});u(this,"beforePopup",()=>{this.emit("beforePopup")});this.editor=e,this.colorPaletteItem=new I0("text-color-palette-item"),this.colorPaletteItem.palette.addListener("onClick",this.handlePaletteClick),this.children.push(this.colorPaletteItem),this.element=Qw()}destroy(){this.colorPaletteItem.destroy()}updatePaletteColor(e){this.colorPaletteItem.palette.setColor("color",e[0]),this.colorPaletteItem.palette.setColor("backgroundColor",e[1]),this.latestColors=e,Xu(this.element,this.latestColors)}updateButtonColor(e){this.latestColors=e,Xu(this.element,this.latestColors)}}const sF="";function th(n,t){const e=b("div",["editor-input-wrap"],n);t!=null&&t.className&&M(e,t==null?void 0:t.className);const o=b("div",["editor-input-label"],e);b("span",[],o,t.label),t.required&&M(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),F(e,"error")}),i.addEventListener("keydown",l=>{var c;(c=t.onKeyDown)==null||c.call(t,l)}),{getField:()=>i,getInputValue:()=>i.value,setFieldError:l=>{M(e,"error"),s.innerText=l}}}function Jw(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 Xw=y("ui-base");class tB{constructor(t,e){u(this,"menu");u(this,"currentText","");u(this,"handleClick",(t,e)=>{this.options.onClickItem(this,e)});u(this,"handleClose",()=>{Jw(this.editor)&&this.editor.focus()});u(this,"handleKeydown",t=>{this.menu.handleDocumentKeydown(t)});this.editor=t,this.options=e,this.menu=new Wo([],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,h;if(((h=(a=this.options).onShow)==null?void 0:h.call(a,this,t,e,o))===!1)return;this.options.showLoading&&this.showLoading();const r=this.editor.getBlockByIndex(t,e);if(!vt(this.editor.rootContainer,r)||Z(this.editor,r)<o)return;const i=Oo(this.editor,r,Lt(this.editor,r,o));if(i.length===0)return;const s=i[0],l=_o(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:S.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 Ue.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)}finally{Ue.release(e)}}highlightText(t){Xw.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 h=0;for(h=0;h<=i.length-c;h){const f=i.substring(h,h+c);f.toLocaleLowerCase()===a?(l+=`<span class="highlight">${f}</span>`,h+=c):(l+=i.charAt(h),h++)}return h<i.length&&(l+=i.substring(h)),l},r=i=>{if(lt(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 eh=y("auto-suggest-menu");class nh{constructor(t,e){u(this,"menu");u(this,"anchor",null);u(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(wt(fe(we(t,i),e.offset).left).startsWith(this.anchor.leftText))return}this.menu.close()});u(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=wt(Rl(t,i,r));if(d(eh,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});u(this,"onShow",(t,e,o,r)=>{var i;if((i=this.options)!=null&&i.onShow)return this.options.onShow(this,e,o,r)});u(this,"onClickItem",(t,e)=>{!this.anchor||(this.options.autoDeleteTrigger&&this.deleteTrigger(),this.options.onClickItem(this,e,this.anchor))});u(this,"queryItems",(t,e)=>this.options.queryItems(this,e));u(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 tB(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)||Za(e.key)?!1:tm(e)&&!To(e)?(setTimeout(()=>{this.resetItems()}),!1):Ya(e)?(this.menu.close(),!0):(this.menu.handleKeydown(e),!0)}popup(t,e,o,r){this.anchor={blockId:G(t),offset:e,leftText:o,trigger:r};const i=U(j(t)),s=K(t);this.menu.popup(i,s,e)}handleAfterInsertText(t,e,o,r,i){var h;const s=t.selection.range.start;if(!s.isSimple())return!1;const{blockId:l,offset:c}=s,a=t.getBlockByIndex(e,o);if(G(a)!==l)return!1;if((h=this.menu)!=null&&h.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=wt(Rl(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 G(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=wt(Rl(t,i,r));if(d(eh,this.anchor,"no anchor"),s.startsWith(this.anchor.leftText)){const c=s.substring(this.anchor.leftText.length);eh.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()}}const yn=y("table-dom");function ho(n){return`${G(n)}_scroll`}function $t(n){const t=n.querySelector("div[data-type=table-content] >table");return d(yn,t instanceof HTMLTableElement,"invalid table"),t}function wn(n,t){const o=n.getCustom(ho(t)).contentElement.firstElementChild;d(yn,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(yn,r,"no table tools"),r}function x0(n){const t=[];return Array.from(n.rows).forEach(e=>{t.push(...Array.from(e.cells))}),t}function os(n){const t=n.querySelector(":scope div[data-type=editor-container]");return d(yn,t,"no child container in cell"),t}function eB(n){const o=x0(n).map(r=>{const i=os(r),s=U(i),l=r.colSpan,c=r.rowSpan;return`${s}/${l}/${c}`}).join();return Ci.default(o)}function jt(n){return it(n)==="table"}function oh(n){const t=j(n);if(Ct(t))return null;const e=z(t);return d(yn,e,"no parent block"),jt(e)?t:oh(e)}function Ee(n){if(jt(n))return n;const t=j(n);if(Ct(t))return null;const e=z(t);return d(yn,e,"no parent block"),jt(e)?e:Ee(e)}function nB(n,t){const e=n.querySelector("colgroup");d(yn,e,"no colgroup");const o=e.children[t];return d(yn,o,"no col"),d(yn,o instanceof HTMLTableColElement,`invalid col: ${o.tagName}`),o}function S0(n){try{return $t(n),!0}catch{return!1}}function oB(n){return At(n).querySelector(":scope > .block-helper")}function rB(n){const t=z(n.contentElement);d(yn,t,"no block");const e=oB(t);if(e){const o=Math.min(n.contentElement.offsetLeft,n.rootElement.scrollLeft),r=t.getBoundingClientRect().width;e.style.right=`${o+r}px`}}const Ie=y("doc-table-grid");class iB{constructor(t){u(this,"_cells",[]);for(let e=0;e<t;e++)this._cells.push(void 0)}cols(){return this._cells.length}setCell(t,e){d(Ie,t>=0&&t<this.cols(),`set cell, invalid col: ${t}`),this._cells[t]=e}getCell(t){d(Ie,t>=0&&t<this.cols(),`get cell, invalid col: ${t}`);const e=this._cells[t];return d(Ie,e,"get cell, no cell"),e}getCellAllowEmpty(t){return d(Ie,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 rh{constructor(t){u(this,"_data");u(this,"_rows");this._data=t,this._rows=[];for(let e=0;e<this.rowCount;e++)this._rows.push(new iB(this.colCount));this.fillGrid(),d(Ie,t.colsWidth,"no colsWidth"),d(Ie,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(Ie,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 h=0;h<s;h++)this._rows[o+a].setCell(e+h,{col:e,row:o,containerId:r,virtual:h!==0||a!==0,colSpan:s,rowSpan:l});const c=this.getNextEmptyCell(e,o);c?(e=c.col,o=c.row):d(Ie,i===t.length-1,`invalid table data, no next empty cell: ${JSON.stringify(this._data)}`)}),this._rows.forEach(r=>{r.forEach(i=>{d(Ie,i,"no cell"),d(Ie,i.containerId,"no containerId")})})}getCell(t){const{col:e,row:o}=t,r=this._rows[o];d(Ie,r,`get cell, no row: ${o}`);const i=r.getCell(e);return d(Ie,i,`get cell, no cell: ${e}`),i}getRow(t){const e=this._rows[t];return d(Ie,e,`get row, no row: ${t}`),e}forEach(t){this._rows.forEach(t)}}const lc=y("table-data");function sB(n){const t=n.firstElementChild;return d(lc,t,"no child element for cell"),d(lc,mn(t),"cell first child is not a container"),d(lc,We(t),"cell first child is not a container"),t}function lB(n){const t=z(n);d(lc,t,"no parent block for table");const e=[],o={};Array.from(n.rows).forEach(l=>{Array.from(l.cells).forEach(c=>{const a=sB(c),h=U(a);e.push(h),(c.colSpan>1||c.rowSpan>1)&&(o[`${h}_colSpan`]=c.colSpan,o[`${h}_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:G(t),type:it(t),rows:r,cols:i,children:e,colsWidth:Array(i).fill(100),...o}}function Go(n){return new rh(n)}function cB(n){return Go(lB(n))}const qt=y("table-grid"),aB=60;class dB{constructor(t,e){u(this,"containerId");u(this,"row");u(this,"col");u(this,"colSpan");u(this,"rowSpan");u(this,"virtual");u(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(qt,e,"no parent cell for child container"),e}get container(){const t=this.table.querySelectorAll(`[data-container-id=${this.containerId}]`);d(qt,t.length===1,"containers !== 1"),d(qt,mn(t[0]),"not a container");const e=t[0];return d(qt,We(e),"not a child container"),e}}class uB{constructor(t,e){u(this,"_cells",[]);e.forEach(o=>{this._cells.push(new dB(t,o))})}get cells(){return this._cells}getCell(t){return d(qt,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 rf=class{constructor(t){u(this,"_rows",[]);this.table=t,cB(t).forEach(r=>{this._rows.push(new uB(t,r))});const o=this.colCount;this._rows.forEach(r=>{d(qt,r.cells.length===o,"row.cells.length !== colCount")})}get rowCount(){return this._rows.length}get colCount(){return this._rows.length===0?0:(d(qt,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(qt,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(qt,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(qt,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(qt,!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(qt,o<=r,"min > max"),d(qt,o>=0,"min < 0"),d(qt,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(qt,o<=r,"min > max"),d(qt,o>=0,"min < 0"),d(qt,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,h=1e4,f=-1,m=-1;return c.forEach(C=>{h=Math.min(C.col,h),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:h},{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),h=Math.max(i.col,s.col);for(let f=l;f<=c;f++)for(let m=a;m<=h;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(qt,o,"cell not found"),o}getCellByCellElement(t){const e=os(t);return this.getCellByContainerId(U(e))}getCellByContainerId(t){return this.getCellById(t)}static fromTable(t){const e=eB(t),o=this.caches.getSync(e,()=>(qt.debug("create table grid"),new rf(t)));return o.table!==t?(this.caches.delete(e),this.fromTable(t)):o}static fromBlock(t){return this.fromTable($t(t))}};let et=rf;u(et,"caches",new Of(aB));function cc(n,t){Object.entries(n).forEach(([e])=>{e.startsWith(`${t}/`)&&delete n[e]})}const hB=y("table-selection-range");function sn(n,t,e){var x,A,O,P;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,h=(x=c==null?void 0:c.rowIndex)!=null?x:s.row,f=(A=c==null?void 0:c.colIndex)!=null?A:s.col,m=(O=a==null?void 0:a.rowIndex)!=null?O:l.row+l.rowSpan-1,C=(P=a==null?void 0:a.colIndex)!=null?P:l.col+l.colSpan-1,v=Math.min(h,m),w=Math.max(h,m),E=Math.min(f,C),D=Math.max(f,C);return{fromRow:v,toRow:w,fromCol:E,toCol:D}}function ih(n,t){const e=new Set,o=new Set,r=n.selection.range;if(!r.isSimple()&&r.start.blockId===G(t)){const i=et.fromBlock(t),{start:s,end:l}=r;d(hB,!s.isSimple()&&!l.isSimple(),"invalid range");const{fromCol:c,toCol:a,fromRow:h,toRow:f}=sn(t,s,l);if(h===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=h;m<=f;m++)e.add(m)}return{selectedRows:e,selectedColumns:o}}const $r=y("delete-columns");function T0(n,t,e){const{start:o,end:r}=e;if(o.blockId!==r.blockId||e.isSimple()||n.getBlockById(o.blockId)!==t||it(t)!=="table")return!1;const{fromRow:s,toRow:l}=sn(t,e.start,e.end),c=et.fromBlock(t);return s===0&&l===c.rowCount-1}function sh(n){var A;const t=n.getEditor(),e=t.getBlockById(n.start.blockId);if(!T0(t,e,n))return;if(n.isSimple()){t.deleteBlock(e);return}const{fromCol:o,toCol:r}=sn(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(O=>O.containerId);for(let O=0;O<l.length;O++){const P=l[O];for(let V=o;V<=r;V++){const nt=P[V];s.add(nt)}P.splice(o,r-o+1)}const c=new Set(l.flat()),a=new Set(Array.from(s).filter(O=>!c.has(O))),h=r-o+1,f=new Map,m=new Map;s.forEach(O=>{if(a.has(O))return;const P=i.getCellByContainerId(O);if(d($r,P.colSpan>1,"invalid effected cell, colSpan === 1"),P.col<o){d($r,c.has(O),"invalid effected cell, not exists");let Et=P.col+P.colSpan-1;Et>r&&(Et=r);const re=Et-o+1,Xn=P.colSpan-re;f.set(O,Xn);return}d($r,P.col<=r,"invalid effected cell, col > endCol");const V=P.col,nt=P.col+P.colSpan-1,ot=P.col-o,ut=nt-V+1-h+ot;d($r,ut>0,"invalid effected cell, newSpanned <= 0");const dt=Cn(t.doc);m.set(O,{newContainerId:dt,colSpan:ut})});for(let O=0;O<l.length;O++){const P=l[O];for(let V=o;V<P.length;V++){const nt=P[V],ot=m.get(nt);ot&&(P[V]=ot.newContainerId)}}const C=Y.default(t.getBlockData(e));C.colsWidth.splice(o,r-o+1),a.forEach(O=>{cc(C,O)}),f.forEach((O,P)=>{d($r,O>=1,"invalid modified colSpan, colSpan < 1"),O===1?delete C[`${P}_colSpan`]:C[`${P}_colSpan`]=O}),m.forEach((O,P)=>{cc(C,P);const{newContainerId:V,colSpan:nt}=O;d($r,nt>=1,"invalid newContainerData, colSpan < 1"),nt>1&&(C[`${V}_colSpan`]=nt);const ot=i.getCellByContainerId(P).rowSpan;ot>1&&(C[`${V}_rowSpan`]=ot)});const w=(A=l[0][o])!=null?A:l[0][o-1],E=t.getChildContainerData(w)[0],D=et.virtualCellContainersGridToChildren(l),x={...C,cols:C.cols-h,children:D};Go(x),t.updateBlockData(e,x,Lt(t,E.id,0)),t.deleteChildContainers(Array.from(a)),t.deleteChildContainers(Array.from(m.keys()))}const jr=y("delete-rows");function D0(n,t,e){const{start:o,end:r}=e;if(o.blockId!==r.blockId||e.isSimple()||n.getBlockById(o.blockId)!==t||it(t)!=="table")return!1;const{fromCol:s,toCol:l}=sn(t,e.start,e.end),c=et.fromBlock(t);return s===0&&l===c.colCount-1}function lh(n){const t=n.getEditor(),e=t.getBlockById(n.start.blockId);if(!D0(t,e,n))return;if(n.isSimple()){t.deleteBlock(e);return}const{fromRow:o,toRow:r}=sn(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(x=>x.containerId);for(let x=r;x>=o;x--)l[x].forEach(O=>s.add(O)),l.splice(x,1);const c=new Set(l.flat()),a=new Set(Array.from(s).filter(x=>!c.has(x))),h=r-o+1,f=new Map,m=new Map;s.forEach(x=>{if(a.has(x))return;const A=i.getCellByContainerId(x);if(d(jr,A.rowSpan>1,"invalid effected cell, rowSpan === 1"),A.row<o){d(jr,c.has(x),"invalid effected cell, not exists");let ut=A.row+A.rowSpan-1;ut>r&&(ut=r);const dt=ut-o+1,Et=A.rowSpan-dt;f.set(x,Et);return}d(jr,A.row<=r,"invalid effected cell, col > endCol");const O=A.row,P=A.row+A.rowSpan-1,V=A.row-o,nt=P-O+1-h+V;d(jr,nt>0,"invalid effected cell, newSpanned <= 0");const ot=Cn(t.doc);m.set(x,{newContainerId:ot,rowSpan:nt})});for(let x=o;x<l.length;x++){const A=l[x];for(let O=0;O<A.length;O++){const P=A[O],V=m.get(P);V&&(A[O]=V.newContainerId)}}const C=Y.default(t.getBlockData(e));a.forEach(x=>{cc(C,x)}),f.forEach((x,A)=>{d(jr,x>=1,"invalid modified rowSpan, rowSpan < 1"),x===1?delete C[`${A}_rowSpan`]:C[`${A}_rowSpan`]=x}),m.forEach((x,A)=>{cc(C,A);const{newContainerId:O,rowSpan:P}=x;d(jr,P>=1,"invalid newContainerData, rowSpan < 1"),P>1&&(C[`${O}_rowSpan`]=P);const V=i.getCellByContainerId(A).colSpan;V>1&&(C[`${O}_colSpan`]=V)});const v=l[o]?l[o][0]:l[o-1][0],w=t.getChildContainerData(v)[0],E=et.virtualCellContainersGridToChildren(l),D={...C,rows:C.rows-h,children:E};Go(D),t.updateBlockData(e,D,Lt(t,w.id,0)),t.deleteChildContainers(Array.from(a)),t.deleteChildContainers(Array.from(m.keys()))}const rs=y("table-range");function ac(n){d(rs,!n.isSimple(),"must be complex selection range");const{anchor:t,focus:e}=n;d(rs,!t.isSimple(),"invalid start pos type"),d(rs,!e.isSimple(),"invalid end pos type");const o=n.getEditor();d(rs,t.blockId===e.blockId,"invalid range, not same block");const r=o.getBlockById(t.blockId);d(rs,it(r)==="table","invalid block type, not a table block");const i=$t(r),s=et.fromTable(i),l=s.getCellByContainerId(t.childContainerId),c=s.getCellByContainerId(e.childContainerId),a=Math.min(l.row,c.row),h=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:h,col:m});return{editor:o,block:r,table:i,startCell:C,endCell:v,startRow:a,startCol:f,endRow:h,endCol:m}}const ch=y("split-cell");function ah(n,t,e){const o=et.fromBlock(t),r=o.getRealCell(e);d(ch,!r.virtual,"should not split virtual cell"),d(ch,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,w=Cn(n.doc);i[C][v]=w}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(ch,a,"no child block");const h=Lt(n,a.id,0);Go(l),n.updateBlockData(t,l,h)}function fB(n,t,e){e.forEach(o=>{const r=et.fromBlock(t).getCell(o);(r.virtual||r.colSpan>1||r.rowSpan>1)&&ah(n,t,o)})}function L0(n,t,e){if(e.isSimple())return!1;const{start:o,end:r}=e;if(o.blockId!==r.blockId||n.getBlockById(o.blockId)!==t||it(t)!=="table")return!1;const{startCell:s,endCell:l}=ac(e);return!(s.cell!==l.cell||s.colSpan===1&&s.rowSpan===1)}function dh(n){const{editor:t,block:e,startRow:o,startCol:r,endRow:i,endCol:s}=ac(n),l=[];for(let c=o;c<=i;c++)for(let a=r;a<=s;a++)l.push({row:c,col:a});return fB(t,e,l),!0}const Hr=y("merge-cells");function M0(n,t,e){if(e.isSimple())return!1;const{start:o,end:r}=e;if(o.blockId!==r.blockId||n.getBlockById(o.blockId)!==t||it(t)!=="table")return!1;const{startCell:s,endCell:l}=ac(e);return s.cell!==l.cell}function R0(n){const t=ac(n),e=t.endCell,o=e.row+e.rowSpan-1,r=e.col+e.colSpan-1,i=G(t.block),s=t.editor;dh(n);const l=s.getBlockById(i),c=$t(l),{startRow:a,startCol:h}=t,f=Y.default(s.getBlockData(l));d(Hr,f.children,"no table children");const m=et.fromTable(c),C=[];for(let ut=a;ut<=o;ut++)for(let dt=h;dt<=r;dt++){const Et=m.getCell({row:ut,col:dt});d(Hr,!Et.virtual,"cell is virtual"),C.push(Et)}d(Hr,C.length>0,"no selected cells");const v=C[0],w=C.slice(1),E=m.getCellByContainerId(v.containerId).container,D=[];w.forEach(ut=>{const dt=m.getCellByContainerId(ut.containerId).container,Et=U(dt);if(!hd(s,dt)){const re=tu(s,Et);s.insertDocAt(E,Ve(E),re)}D.push(Et)});const x=U(E),A=r-h+1,O=o-a+1;f[`${x}_colSpan`]=A,f[`${x}_rowSpan`]=O,D.forEach(ut=>{d(Hr,f.children,"no table children");const dt=f.children.indexOf(ut);d(Hr,dt>0,"no deleted container"),f.children.splice(dt,1)});const P=f,nt=s.getChildContainerData(x)[0];d(Hr,nt,"no child block");const ot=Lt(s,nt.id,0);Go(P),s.updateBlockData(l,P,ot),s.deleteChildContainers(D)}const uh=10,mB=["table/merge-cells","table/split-cell","table/insert-column","table/insert-row","table/delete-rows","table/delete-columns","table/delete"];class hh{constructor(){u(this,"id","TableBlockCommandProvider")}getAvailableCommands(t,e,o){if(it(e)!=="table")return[];const r={blockId:G(e),blockKind:Ge(t,e),blockType:it(e)},i=[];M0(t,e,o)&&i.push({id:"table/merge-cells",name:"merge cells",icon:nw,groupIndex:uh,...r}),L0(t,e,o)&&i.push({id:"table/split-cell",name:"split cell",icon:ow,groupIndex:uh,...r});const s=T0(t,e,o),l=D0(t,e,o);return s&&l&&i.push({id:"table/delete",name:"delete tables",icon:rw,groupIndex:uh,...r}),i}executeCommand(t,e,o,r,i,s){return it(e)!=="table"||!new Set(mB).has(r.id)?!1:r.id==="table/merge-cells"?(R0(o),!0):r.id==="table/split-cell"?(dh(o),!0):r.id==="table/delete-columns"?(sh(o),!0):r.id==="table/delete-rows"?(lh(o),!0):r.id==="table/delete"?(t.deleteBlock(e),!0):!1}}var O0=(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))(O0||{});const fh=6,is=20;function gB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasColTitle:!0};n.updateBlockData(t,o)}function pB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasColTitle:!1};n.updateBlockData(t,o)}function CB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasRowTitle:!0};n.updateBlockData(t,o)}function bB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasRowTitle:!1};n.updateBlockData(t,o)}function vB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),isStripeStyle:!0};n.updateBlockData(t,o)}function kB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),isStripeStyle:!1};n.updateBlockData(t,o)}function yB(n,t,e){if(!n.isBlockWritable(t))return;const r={...Y.default(n.getBlockData(t)),noBorder:!e};n.updateBlockData(t,r)}const mh=y("get-selected-containers");function gh(n,t,e,o){d(mh,e.blockId===o.blockId,"only allow select in single table block"),d(mh,G(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(E=>r.getCellContainer(E));const{fromCol:l,toCol:c,fromRow:a,toRow:h}=sn(t,e,o),f=new Set,m=[];return r.sub({row:a,col:l},{row:h,col:c}).forEach(v=>{v.forEach(w=>{const E=r.getCellByContainerId(w.containerId);E.col<l||E.row<a||E.col+E.colSpan-1>c||E.row+E.rowSpan-1>h||f.has(w.containerId)||(f.add(w.containerId),m.push(E.container))})}),m}function wB(n,t,e){d(mh,t.blockId===e.blockId,"only allow select in single table block");const o=n.getBlockById(t.blockId);return gh(n,o,t,e)}const Zo=y("table-cell-dom");function BB(n,t,e){let o=n.getBlockById(e);for(;o;){const r=o.closest("td");d(Zo,r,"no parent cell");const i=z(r);if(d(Zo,i,"no parent block"),i===t)return r;o=i}return d(Zo,!1,"filed to get cell by child block id"),null}function qn(n,t,e){if(n.getBlockById(e.blockId)===t&&!e.isSimple())return d(Zo,e.childContainerId,"block position must have childContainerId attribute"),e;const r=BB(n,t,e.blockId),i=U(os(r));return bt(t,i)}function ph(n,t){const e=n.selection.range,o=qn(n,t,e.start),r=qn(n,t,e.end);return sn(t,o,r)}function A0(n,t,e,o){d(Zo,jt(t),"invalid table block");const r=wn(n,t),i=()=>{const l=r.querySelector(".table-border-bar-container.top");d(Zo,l,"no top border bar container"),l.querySelectorAll(".table-border-bar-cell.top").forEach(a=>{const h=parseInt(a.getAttribute("data-top-index")||"0",10);o.includes(h)?M(a,"danger"):F(a,"danger")})},s=()=>{const l=r.querySelector(".table-border-bar-container.left");d(Zo,l,"no left border bar container"),l.querySelectorAll(".table-border-bar-cell.left").forEach(a=>{const h=parseInt(a.getAttribute("data-left-index")||"0",10);e.includes(h)?M(a,"danger"):F(a,"danger")})};i(),s()}function Fr(n,t,e=!0,o){const i=et.fromBlock(t).map(h=>h),{fromCol:s,toCol:l,fromRow:c,toRow:a}=ph(n,t);for(let h=0;h<i.length;h++){const f=i[h];for(let m=0;m<f.length;m++){const C=f[m],v=o?m>=s&&m+C.colSpan-1<=l:h>=c&&h+C.rowSpan-1<=a;e&&v?C.virtual||M(C.cell,"danger"):C.virtual||F(C.cell,"danger")}}}function zr(n,t,e=!0,o){const r=new Set,i=new Set;if(!e){A0(n,t,Array.from(r),Array.from(i));return}const{fromCol:s,toCol:l,fromRow:c,toRow:a}=ph(n,t);if(o)for(let h=s;h<=l;h++)i.add(h);else for(let h=c;h<=a;h++)r.add(h);A0(n,t,Array.from(r),Array.from(i))}function _0(n,t,e){const{fromCol:o,toCol:r,fromRow:i,toRow:s}=ph(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}),Vt(n,{anchor:bt(t,c.containerId,{colIndex:o,rowIndex:0}),focus:bt(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}),Vt(n,{anchor:bt(t,c.containerId,{colIndex:0,rowIndex:i}),focus:bt(t,a.containerId,{colIndex:l.colCount-1,rowIndex:s})}))}function EB(n,t){const e=n.selection.range,o=qn(n,t,e.start),r=qn(n,t,e.end);return gh(n,t,o,r)}const N0=["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 P0(n){return`style-bg-color-${n}`}function ss(n){return`${n}_background`}function IB(n,t,e){const o=$t(n),s=(e!=null?e:et.fromTable(o)).getCell(t).cell;for(let l=0;l<N0.length;l++){const c=N0[l];if(lt(s,c))return c}}function $0(n,t,e){if(!n.isBlockWritable(t))return;const o=n.selection.range,i={...Y.default(n.getBlockData(t))},s=qn(n,t,o.start),l=qn(n,t,o.end);if(o.isSimple()){const c=s.childContainerId;e===-1?i[ss(c)]=void 0:i[ss(c)]=P0(e)}else{const c=et.fromBlock(t),a=sn(t,s,l),h=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});!h.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&&(h.add(C.containerId),e===-1?i[ss(C.containerId)]=void 0:i[ss(C.containerId)]=P0(e))}}n.updateBlockData(t,i)}function xB(n,t,e){if(!n.isBlockWritable(t))return;const r={...Y.default(n.getBlockData(t)),chart:e};n.updateBlockData(t,r)}const j0=y("table-chart");function SB(n,t){const e=wn(n,t);if(e){const o=e.querySelector(".editor-table-chart");if(o){const r=o.chartObject;r&&r.destroy(),o.remove()}}}async function TB(n,t){if(!n.isBlockWritable(t))return;if(!!!n.getBlockData(t).chart){SB(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 w=1;w<i.colCount;w++)c.push(i.getCell({row:0,col:w}).container.innerText);for(let w=1;w<i.rowCount;w++){const E=i.getCell({row:w,col:0}),x=E.container.innerText,A=[];for(let re=1;re<i.colCount;re++){const Xn=i.getCell({row:w,col:re}).container.innerText,te=Number.parseFloat(Xn)||0;A.push(te)}let O;const P=IB(t,E,i);P?O=window.getComputedStyle(n.rootElement).getPropertyValue(`--${P}`).trim():O=window.getComputedStyle(n.rootElement).getPropertyValue("--background-color").trim();let[V,nt,ot,ut]=O?Pa.fromString(O).toRgbaArray():[];if(!V&&!nt&&!ot&&!ut){const re=(w-1)%n.options.colors.length;O=n.options.colors[re],[V,nt,ot,ut]=Pa.fromString(O).toRgbaArray()}const dt=O,Et=Pa.fromRgba([V,nt,ot,ut/3]).toHexString();r.push({label:x,data:A,borderColor:dt,backgroundColor:Et,borderWidth:2})}const a=wn(n,t);let h=null,f=a.querySelector(".editor-table-chart");f?h=f.chartObject:f=b("div",["editor-table-chart"],a);const m=f;d(j0,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 xo(v,"editor-chartjs"),h&&l!==h.config.type&&(h.destroy(),h=null,Array.from(f.querySelectorAll(".editor-chartjs-canvas")).forEach(D=>{D.remove()}));const w=$a.default({},{type:l,data:{datasets:r,labels:c},options:{onClick:()=>{n.selection.selectBlock(t,0,0)}}});if(h)$a.default(h.config,w),h.update();else{const D=b("canvas",["editor-chartjs-canvas"],m).getContext("2d");h=new window.Chart(D,w),f.chartObject=h}}catch(w){j0.error(`failed to resolve chart cdn: ${JSON.stringify(w)}`)}}async function H0(n,t){await Ue.lock("updateTableChart");try{await TB(n,t)}finally{Ue.release("updateTableChart")}}const F0=Qt.default(H0,1e3);let z0=null;function Ch(n,t,e){if(z0!==t&&(F0.flush(),z0=t),e.updateNow){H0(n,t);return}F0(n,t)}function bh(n,t){jt(t)&&Ch(n,t,{updateNow:!1})}function DB(n,t){jt(t)&&Ch(n,t,{updateNow:!0})}const $e={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"},dc={SCROLL_BAR:"container-scrollbar",FIXED:"fixed"},fo={SCROLL_CONTAINER:"scroll-container",TOOL:"container-scroll-tool",CONTAINER:"scroll-container-root",MAC:"mac",SCROLL_AREA:"scroll-area"};function uc(n,t){return n.containers.get(t)}function U0(n){return n.closest(`.${fo.SCROLL_CONTAINER}`)}function ln(n){return n.firstElementChild}function xe(n){return n.closest(`.${fo.CONTAINER}`)}function ls(n){const t=xe(n);let e=t.querySelector(`:scope >.${fo.TOOL}`);return e||(e=b("div",[fo.TOOL],t)),e}function LB(n){return xe(n).firstElementChild}function cs(n){const t=window.getComputedStyle(n);return{paddingBottom:parseFloat(t.paddingBottom),paddingTop:parseFloat(t.paddingTop),paddingLeft:parseFloat(t.paddingLeft),paddingRight:parseFloat(t.paddingRight)}}function vh(n,t){const e=xe(t),o=uc(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 h=Math.floor(c.left-l.left-i);h<0&&(h=0);let f=l.right;f-=r;let m=f-c.right;return m<0&&(m=0),h=Math.round(h),m=Math.round(m),{originWidth:a,maxLeft:h,maxRight:m}}function MB(n,t){const e=vh(n,t),{maxLeft:o}=e;t.style.marginLeft=`${0-o}px`,t.style.paddingLeft=`${o}px`}function RB(n,t){const e=vh(n,t);t.style.marginRight=`${0-e.maxRight}px`}function OB(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 V0=y("scroll-bar-handle"),AB=2;function Ur(n){const t=ls(n);let e=t.querySelector(`.${dc.SCROLL_BAR}`);return e||(e=b("div",[dc.SCROLL_BAR],t)),d(V0,e instanceof HTMLDivElement,"invalid child for container tools"),e.firstElementChild||b("div",[],e),e}function hc(n,t){const e=U0(t),o=Ur(e),{paddingLeft:r,paddingRight:i}=cs(t);e.style.marginLeft="",e.style.paddingLeft="",e.style.marginRight="";const s=vh(n,e),{originWidth:l,maxRight:c}=s;RB(n,e),MB(n,e);const a=e.scrollWidth-e.clientWidth;d(V0,o.firstElementChild instanceof HTMLDivElement,"invalid child for scroll bar"),o.style.width=`${l+c-r-i}px`,o.firstElementChild.style.width=`${l+c+a-r-i}px`}function _B(n,t){const e=ln(n),{paddingLeft:o}=cs(e);if(lt(t,"fixed")){const i=xe(n).getBoundingClientRect();t.style.left=`${i.left+o}px`}else t.style.left=`${o}px`}function Vr(n,t){const e=n.getParentScrollContainer(),o=OB(e),r=t.getBoundingClientRect(),i=Ur(t),s=i.getBoundingClientRect(),l=uc(n,xe(t)),c=(l==null?void 0:l.barFloatWindowBottom)||0,a=ln(t),{paddingTop:h,paddingBottom:f}=cs(a),m=document.documentElement.clientHeight-c,C=o.top+e.clientHeight-m,v=m+Math.min(0,C);if(t.scrollWidth>t.clientWidth&&r.top+h<v-s.height&&r.bottom>v-s.height+f){M(i,dc.FIXED);const E=C>0?c:0;i.style.bottom=`${Math.max(document.documentElement.clientHeight-o.bottom,0)+AB+E}px`}else F(i,dc.FIXED),i.style.bottom=`${f-s.height}px`;_B(t,i)}class NB{constructor(t,e){u(this,"intersectionObserver");u(this,"handleIntersection",t=>{t.forEach(e=>{this.containers.get(xe(e.target))?(this.handleIntersectionEntry(e),this.callback(e)):this.intersectionObserver.unobserve(e.target)})});u(this,"handleIntersectionEntry",t=>{const e=t.target;Vr(this.scrollCore,e);const o=ln(e);hc(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 Yo=y("container-scroll-shadow");function q0(n,t,e){const o=n,r=t.getBoundingClientRect(),i=e.getBoundingClientRect(),{paddingTop:s,paddingBottom:l}=cs(e);o.style.top=`${i.top-r.top+s}px`,o.style.bottom=`${r.bottom-i.bottom+l}px`}function W0(n,t){const e=n;t<24?e.style.width=`${(t/3).toFixed(2)}px`:e.style.width=""}function PB(n){const t=ls(n);d(Yo,t,"no container tools");let e=t.querySelector(`.${$e.LEFT}`);if(!e){const l=ln(n),c=[$e.COMMON,$e.LEFT];e=b("div",c,t),d(Yo,e instanceof HTMLDivElement,"invalid child for container tools"),q0(e,n,l)}d(Yo,e instanceof HTMLElement,"invalid child for container tools");const r=xe(n).getBoundingClientRect(),i=n.getBoundingClientRect();e.style.left=`${i.left-r.left}px`;const s=n.scrollLeft;d(Yo,e instanceof HTMLDivElement,"invalid child for container tools"),W0(e,s),M(e,$e.ACTIVE)}function $B(n){const t=ls(n);let e=t.querySelector(`.${$e.RIGHT}`);if(!e){const l=ln(n),c=[$e.COMMON,$e.RIGHT];e=b("div",c,t),d(Yo,e instanceof HTMLDivElement,"no div, create shadow failed"),q0(e,n,l)}d(Yo,e instanceof HTMLElement,"");const r=xe(n).getBoundingClientRect(),i=n.getBoundingClientRect();e.style.right=`${r.right-i.right}px`;const s=n.scrollWidth-n.scrollLeft-n.clientWidth;d(Yo,e instanceof HTMLDivElement,"no shadow element"),W0(e,s),M(e,$e.ACTIVE)}function jB(n){const e=ls(n).querySelector(`.${$e.LEFT}`);e&&F(e,$e.ACTIVE)}function HB(n){const e=ls(n).querySelector(`.${$e.RIGHT}`);e&&F(e,$e.ACTIVE)}function as(n){const t=Math.round(n.scrollLeft),e=ln(n),{paddingLeft:o,paddingRight:r}=cs(e);n.scrollWidth-o<=n.clientWidth-r||n.scrollWidth-o<=t+n.clientWidth-r?HB(n):$B(n),e&&n.scrollLeft>=e.offsetLeft+o?PB(n):jB(n)}class FB{constructor(t){u(this,"resizeObserver");u(this,"handleResizeEntry",t=>{const e=t.target,o=ln(e);as(e),hc(this.scrollCore,o),Vr(this.scrollCore,e)});u(this,"handleContentResize",t=>{t.forEach(e=>{this.containers.get(xe(e.target))?this.handleResizeEntry(e):this.unbind(e.target)})});this.scrollCore=t,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 G0=y("container-scroll-observer");class zB{constructor(t,e){u(this,"handleContentScroll",t=>{const e=t.target;d(G0,e instanceof Element,"invalid target for scroll event");const o=Ur(e);o.removeEventListener("scroll",this.handleScroll);const r=!0;this.fixScrollXPos(e,e.scrollLeft,r),this.bind(o),as(e),this.callback(e)});u(this,"handleScroll",t=>{const e=t.target;d(G0,e instanceof HTMLElement,"");const o=e.scrollLeft,r=!1,i=LB(e);this.unbindContentScroll(i),this.fixScrollXPos(i,o,r),this.bindContentScroll(i),as(i),this.callback(i)});u(this,"handlePrevent",t=>{t.stopPropagation()});u(this,"bindContentScrollCore",t=>{this.unbindContentScroll(t),t.addEventListener("scroll",this.handleContentScroll)});u(this,"unbindContentScroll",t=>{t.removeEventListener("scroll",this.handleContentScroll)});u(this,"bindContentScroll",Qt.default(this.bindContentScrollCore,300));u(this,"bind",Qt.default(this.bindCore,200));this.scrollCore=t,this.callback=e}fixScrollXPos(t,e,o){const r=Ur(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 UB{constructor(t){u(this,"scrollContainers",new Set);u(this,"handleParentContainerScroll",()=>{this.scrollContainers.forEach(t=>{Vr(this.scrollCore,t)})});u(this,"bindScrollContainer",t=>{const e=this.scrollContainers.size===0;this.scrollContainers.add(t),e&&this.eventTarget.addEventListener("scroll",this.handleParentContainerScroll)});u(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 VB=y("scroll-wrap-resize-observer");class qB{constructor(t){u(this,"resizeObserver");u(this,"handleScrollWrapResize",t=>{t.forEach(e=>{this.containers.get(xe(e.target))?this.handleScrollWrapResizeEntry(e):this.unbind(e.target)})});u(this,"handleScrollWrapResizeEntry",t=>{const e=t.target;d(VB,e instanceof HTMLElement,"invalid target for observer entry");const o=U0(e);hc(this.scrollCore,e),as(o),Vr(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 WB{constructor(t){u(this,"resizeObserver");u(this,"scrollContainersMap",new Map);u(this,"handleResizeEntry",t=>{t==null||t.forEach(e=>{const o=ln(e);as(e),hc(this.scrollCore,o),Vr(this.scrollCore,e)})});u(this,"handleResize",t=>{t.forEach(e=>{const o=this.scrollContainersMap.get(e.target);o!=null&&o.length&&this.handleResizeEntry(o)})});this.scrollCore=t,this.resizeObserver=new ResizeObserver(this.handleResize)}bind(t){var r,i;const e=xe(t),o=(r=uc(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=xe(t),o=(i=uc(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 lF="";class GB extends Wt.TypedEmitter{constructor(e){super();u(this,"containerIntersectionObserver",null);u(this,"containerResizeObserver",null);u(this,"containerScrollObserver",null);u(this,"parentContainerScrollObserver",null);u(this,"scrollWrapResizeObserve",null);u(this,"locatingContainerResizeObserver",null);u(this,"isWindowEventBind",!1);u(this,"containers",new Map);u(this,"handleScrollContainerScroll",e=>{this.emit("scroll",this,e)});u(this,"handleIntersection",e=>{const o=e.target,r=ln(o);e.isIntersecting?(this.load(),this.bindCore(o,r)):this.unbindCore(o,r)});u(this,"handleWindowEffect",()=>{var e;(e=this.getScrollContainerInViewable())==null||e.forEach(o=>{Vr(this,o)})});this.parentContainer=e}load(){this.containerResizeObserver||(this.containerResizeObserver=new FB(this)),this.containerScrollObserver||(this.containerScrollObserver=new zB(this,this.handleScrollContainerScroll)),this.parentContainerScrollObserver||(this.parentContainerScrollObserver=new UB(this)),this.scrollWrapResizeObserve||(this.scrollWrapResizeObserve=new qB(this)),this.locatingContainerResizeObserver||(this.locatingContainerResizeObserver=new WB(this)),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,h;const r=Ur(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),(h=this.locatingContainerResizeObserver)==null||h.unbind(e)}bindCore(e,o){var i,s,l,c,a,h;if(this.unbindCore(e,o),!e.closest("body"))return;const r=Ur(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),(h=this.locatingContainerResizeObserver)==null||h.bind(e)}bind(e,o){this.containers.set(e,o);const r=e.firstElementChild;this.containerIntersectionObserver||(this.containerIntersectionObserver=new NB(this,this.handleIntersection)),this.containerIntersectionObserver.bind(r)}unbind(e){var i;const o=e.firstElementChild,r=ln(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 Z0=y("scroll-container"),fc=new Map;class ZB extends Wt.TypedEmitter{constructor(){super(...arguments);u(this,"scrollListener");u(this,"options");u(this,"scrollContainerElement");u(this,"init",e=>{this.options=e;const o=b("div",[fo.CONTAINER],e.parentElement);St.isMac&&M(o,fo.MAC);const r=b("div",[fo.SCROLL_CONTAINER],o),i=b("div",[fo.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=fc.get(s),this.scrollListener||(this.scrollListener=new GB(s),fc.set(s,this.scrollListener)),this.scrollListener.unbind(o),this.scrollListener.bind(o,e),this.scrollListener.on("scroll",this.handleContainerScroll),this.scrollContainerElement=r});u(this,"handleContainerScroll",(e,o)=>{o===this.scrollContainerElement&&this.emit("scroll",this)})}get rootElement(){return this.scrollContainerElement}get contentElement(){return d(Z0,this.scrollContainerElement,"scrollContainerElement cannot be undefined"),ln(this.scrollContainerElement)}get scrollOptions(){return d(Z0,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=xe(this.contentElement);e&&fc.forEach((r,i)=>{r.unbind(e),r.containers.size===0&&(this.handleBaseListenerDestroy(r),fc.delete(i))})}}function YB(){return new ZB}const mc=100,QB=40,kh=y("column-width");function KB(n,t,e){nB(n,t).style.width=`${e}px`}function JB(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)}),kh.debug(`cellRightOffsets1: ${r.join()}`);for(let c=0;c<r.length;c++){const a=r[c];if(a===-1||c===0)continue;let h=c-1;for(;r[h]===-1&&(h--,h!==-1););const f=h===-1?0:r[h],C=(a-f)/(c-h);for(let v=h+1;v<c;v++)r[v]=f+C*(v-h)}kh.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 kh.debug(`widths: ${s.join()}`),s}function ds(n){return Array.from(n.querySelector("colgroup").children).map(o=>o.getBoundingClientRect().width||Number.parseInt(o.style.width,10)||100)}const XB=y("table-resize-gripper"),Y0=7,yh=(Y0-1)/2,tE=3;function eE(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(),h=Math.round(a.right);if(Math.abs(t-h)<=yh&&a.top<=e&&e<=a.bottom)return c}}return null}function nE(n){return!!n.rootContainer.querySelector(".table-resize-gripper")}function wh(n,t){return wn(n,t).querySelector(".table-resize-gripper")}function Q0(n,t){const e=wh(n,t);d(XB,!e,"resize gripper has already exists");const o=wn(n,t),r=b("div",["table-resize-gripper","table-indicator"],o);return b("div",["table-resize-gripper-indicator"],r),r}function K0(n,t,e){let o=wh(n,t);o||(o=Q0(n,t));const i=$t(t).getBoundingClientRect(),s=e.getBoundingClientRect(),l=0,c=i.height,a=n.getCustom(ho(t)).contentElement.getBoundingClientRect(),h=s.right-a.left;o.style.left=`${h-yh-fh-is}px`,o.style.top=`${l}px`,o.style.height=`${c}px`,o.style.width=`${Y0}px`}function Bh(n){n.rootContainer.querySelectorAll(".table-resize-gripper").forEach(t=>{t.remove()})}function oE(n,t,e){const r={...n.getBlockData(t),colsWidth:e};n.updateBlockData(t,r)}function rE(n,t,e,o){const r=t,i=et.fromTable(e),s=i.getCellByCellElement(r),l=s.col+s.colSpan-1,c=ds(e);let a=o;const h=(m,C)=>{const v=C+1,w=m.col+m.colSpan;return c.slice(v,w).reduce((D,x)=>D+x,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,w=v.getBoundingClientRect();let E=o-w.left+yh-tE;const D=os(v),x=ud(n,D)||QB*C.colSpan,A=h(C,l),O=x-A;E<O&&(E=O);const P=w.left+E;a=Math.max(a,P)}return a}const iE=y("table-resize-drag-drop");class sE{constructor(t,e,o,r){u(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,h=rE(this.editor,c,s,e.x-t.dragOffsetX)-s.getBoundingClientRect().left;d(iE,c,"no dragging cell");const m=et.fromTable(s).getCellByCellElement(c),C=m.col+m.colSpan-1,w=ds(s).slice(0,C).reduce((D,x)=>D+x,0),E=h-w;KB(s,C,E),K0(this.editor,l,c),this.editor.selection.caret.update()}onDragEnd(t,e,o,r,i){const s=ds(t.data.table);oE(this.editor,t.data.block,s),Bh(this.editor),this.onEnd&&(this.onEnd(e),this.onEnd=null)}}function lE(n,t){const e=document.elementFromPoint(t.x,t.y);if(!e)return null;const o=z(e);return!o||!n.contains(o)||!jt(o)?null:o}y("table-resize");class cE{constructor(t){u(this,"draggingRefCell",null);u(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=lE(t,i);if(!s||!S0(s)){Bh(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=$t(t),i=eE(r,e,o);if(i){if(!wh(this.editor,t)){if(nE(this.editor))return;const l=Q0(this.editor,t),c={block:t,table:r,draggingRefCell:i};qa(new sE(this.editor,l,c,a=>{this.updateGripper(t,a.x,a.y)}))}K0(this.editor,t,i)}else Bh(this.editor)}}function J0(n){n.addCustom("table-mouse-event-handler",t=>new cE(t))}const X0=y("table-insert-column");function t5(n,t,e){const o=$t(t),r=et.fromTable(o),i=r.colCount;d(X0,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],w=C[e];if(e===0||e===C.length||v!==w){const E=Cn(n.doc);C.splice(e,0,E)}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(X0,typeof v=="number"&&v>1,`no colSpan for containerId ${m}, ${v}`),c[C]=v+1});const a=c.colsWidth.concat();a.splice(e,0,mc);const h=et.virtualCellContainersGridToChildren(s),f={...c,cols:c.cols+1,children:h,colsWidth:a};Go(f),n.updateBlockData(t,f)}const gc=y("table-insert-row");function e5(n,t,e){const o=$t(t),r=et.fromTable(o),i=r.rowCount;d(gc,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(gc,C||v,"no top and bottom cell"),e===0||e===r.rowCount||C!==v){const w=Cn(n.doc);c.push(w)}else d(gc,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(gc,typeof v=="number"&&v>1,`no rowSpan for containerId ${m}, ${v}`),a[C]=v+1});const h=et.virtualCellContainersGridToChildren(s),f={...a,rows:a.rows+1,children:h};Go(f),n.updateBlockData(t,f)}const Eh=y("paste-table-in-table-block");function aE(n,t,e,o){let r=et.fromBlock(e);const i=t.blocks.root[0];d(Eh,i,"no table data"),d(Eh,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,h=l.col,f=l.row,m=h+c,C=f+a,v=[];for(let w=h;w<m&&w<r.colCount;w++)for(let E=f;E<C&&E<r.rowCount;E++){const D=r.getCell({col:w,row:E});D.virtual?D.virtual&&v.push({col:w,row:E}):(D.colSpan>1||D.rowSpan>1)&&v.push({col:w,row:E})}n.undoManager.runInGroup(()=>{if(v.forEach(x=>{const A=et.fromBlock(e).getCell(x);(A.colSpan>1||A.rowSpan>1)&&ah(n,e,x)}),m>r.colCount)for(let x=r.colCount;x<m;x++)t5(n,e,x);if(C>r.rowCount)for(let x=r.rowCount;x<C;x++)e5(n,e,x);r=et.fromBlock(e);const w=new rh(s);let E;for(let x=0;x<w.colCount;x++)for(let A=0;A<w.rowCount;A++){const O=w.getCell({col:x,row:A});if(!O.virtual){const P=Zd(n.editorBlocks,t,O.containerId),V=h+x,nt=f+A,ot={col:V,row:nt},ut=r.getCellContainer(ot);Cp(n,ut,P),E=ut}}d(Eh,E,"no last container");const D=Gt(E);n.selection.selectBlock(D,Z(n,D))})}const n5=y("paste-in-table-block");class dE{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=j(r);if(Ct(i)||!hd(t,i))return!1;const s=z(i);if(d(n5,s,"no parent block"),!jt(s)||e.blocks.root.length!==1||e.blocks.root[0].type!=="table")return!1;n5.debug("paste child table in table");const a=et.fromBlock(s).getCellByContainerId(U(i)).cell;return aE(t,e,s,a),!0}}function o5(n){n.addCustom("table-block-paste-event",t=>new dE(t))}const Ih=y("table-select-columns");function uE(n,t,e,o,r){d(Ih,jt(t),"is not a table block");const i=et.fromBlock(t);d(Ih,e>=0&&e<i.colCount,"invalid from"),d(Ih,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=bt(t,s.containerId,{colIndex:e,rowIndex:0}),a=bt(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 xh=y("table-select-columns");function hE(n,t,e,o,r){d(xh,jt(t),"is not a table block");const i=et.fromBlock(t);d(xh,e>=0&&e<i.rowCount,"invalid from"),d(xh,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=bt(t,s.containerId,{rowIndex:e,colIndex:0}),a=bt(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 cF="",r5=y("get-toolbar-reference-client");function fE(n,t){const e=n.selection.range;if(!e.isSimple()){d(r5,e.start.blockId===e.end.blockId,"invalid selection range");const s=n.getBlockById(e.start.blockId);d(r5,ct(n,s),"not a complex block");const l=kt(n,s);if(l.getTextToolbarReferenceClient){const c=l.getTextToolbarReferenceClient(n,s);if(c)return c}}const o=e.isReverse()?t.start:t.end,r=Vt(n,{anchor:o,focus:o}),i=Oo(n,t.block,r);if(i.length!==0)return i[0]}function mE(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 pc(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=ja.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=pc(r),mE(s))}),e}function Cc(n){return n.getCustom("toolbar-handler")}const aF="";class gE{constructor(){u(this,"linkPopup",null);u(this,"form",{});u(this,"onFinished",null);u(this,"onClose",null);u(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{}});u(this,"handleClose",()=>{var t;(t=this.onClose)==null||t.call(this),this._destroy()});u(this,"onShow",()=>{setTimeout(()=>{var t;(t=this.form.linkText)==null||t.getField().focus()},400)});u(this,"onChange",()=>{var e;const t=(e=this.linkPopup)==null?void 0:e.content.querySelector(".submit-button");t.disabled=!1});u(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()}});u(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(S.t("link.urlPlaceholder")),new Error(S.t("link.urlPlaceholder"))}editLink(t){var h,f;const{target:e,linkText:o,linkUrl:r,onFinished:i,onClose:s,placement:l="bottom-start"}=t;this.linkPopup=new ic(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=(h=this.linkPopup)==null?void 0:h.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=th(o,{label:S.t("link.textLabel"),required:!1,placeholder:S.t("link.textPlaceholder"),defaultValue:t,onChange:this.onChange,onKeyDown:this.handleTextKeyboard}),this.form.linkUrl=th(o,{className:"link-popup-gap",label:S.t("link.urlLabel"),required:!0,placeholder:S.t("link.urlPlaceholder"),defaultValue:e,onChange:this.onChange,onKeyDown:this.handleUrlKeyboard});const r=b("div",["link-popup-footer"],o);b("button",["cancel-button"],r,S.t("link.cancelText"));const i=b("button",["submit-button"],r,S.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 bc(n,t){n.addCustom("link-editor",()=>new gE).editLink(t)}const pE=y("link-popup");function CE(n){return lt(n,"link")}function vc(n){var t,e;return(e=(t=n.getAttribute("link"))!=null?t:n.textContent)!=null?e:""}function bE(n,t,e){var r,i,s,l;if(n.isBlockWritable(t)&&e&&Re(e)){const c=e,a=(i=(r=n.editorBoxes.getBoxClass(xi(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&&H(n,t)&&CE(e)?[{id:"link-text",name:vc(e),element:b("span",["link-href-button"],null,vc(e))},{id:"edit-link",name:"Edit",icon:Ju},{id:"remove-link",name:"Remove link",icon:fw}]:Gm(n,t,"hovering-toolbar")}function vE(n,t,e){var c;const o=Br(t,e);n.selection.selectBlock(t,o.start,o.end);const r=(c=e.textContent)!=null?c:"",i=vc(e);bc(n,{target:e,linkText:r,linkUrl:i,onFinished:(a,h)=>{try{const f=n.getBlockText(t),m=Ld(f,o.start,o.end-o.start),C=Ir(m,o.start,a,{link:h});n.setBlockText(t,C),n.selection.selectBlock(t,o.start+a.length),n.focus()}catch(f){pE.error(f)}},onClose:()=>{n.selection.selectBlock(t,o.end),n.focus()}})}function kE(n,t,e){const o=Br(t,e),r=n.getBlockText(t),i=vc(e),s=xr(o.start,o.end-o.start,r,"link",i);n.setBlockText(t,s),n.selection.selectBlock(t,o.end)}function yE(n,t,e,o){var s,l,c;if(e){if(n.isBlockWritable(t)&&Re(e)){const h=e,f=(l=(s=n.editorBoxes.getBoxClass(xi(h))).getBoxProperties)==null?void 0:l.call(s,n,h);if(f!=null&&f.boxCommands){f.boxCommands["hovering-toolbar"].executeCommand(n,t,h,o);return}return}const a=Cc(n);a.disableTextToolbar(),a.hide(),setTimeout(()=>{a.enableTextToolbar()},1e4),o.id==="edit-link"?vE(n,t,e):o.id==="remove-link"&&kE(n,t,e);return}const r=Wm(n,t);if(!r)return;const i=(c=r.blockCommands)==null?void 0:c["hovering-toolbar"];!i||i.executeCommand(n,t,o)}const wE=[zu,Uu,Vu,qu,Wu,Gu,Zu,Yu];class BE{constructor(t){u(this,"id","BlockTurnIntoCommandProvider");this.editor=t}getHeadingIndex(){return 6}getAvailableCommands(t,e,o){if(H(t,e)){const r=G(e),i=it(e),s=Ge(t,e),c=t.getBlockData(e).heading,a=[];for(let f=0;f<this.getHeadingIndex();f++)a.push({id:`heading-${f+1}`,name:S.t("commands.heading",{name:`${f+1}`}),icon:wE[f],states:c===f+1?["checked"]:[],value:`${f+1}`});return[{id:"turn-into",name:"",blockId:r,blockType:i,blockKind:s,element: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||oc,m;return m.innerHTML=oc,m},groupIndex:200,dropdown:!0,manualShowChildren:!0,childrenPlacement:"bottom-start",defaultCheckedChildren:["text"],children:[{id:"text",name:S.t("commands.text"),icon:oc,states:c?[]:["checked"]},...a],childrenType:"menu"}]}return[]}applyHeadingStyle(t,e,o){t.updateBlockData(e,{heading:o})}executeCommand(t,e,o,r){if(H(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}}const kc=y("list-block");function at(n){return it(n)==="list"}function Ht(n){d(kc,at(n),"not a list block")}function je(n){Ht(n);const t=n.getAttribute("data-list-type");return d(kc,t,"no list type"),t}function yc(n){return at(n)&&je(n)==="text-only"}function Se(n){var t,e;return Ht(n),(e=Number.parseInt((t=n.getAttribute("data-list-start"))!=null?t:"1",10))!=null?e:1}function Te(n){var t,e;return Ht(n),(e=Number.parseInt((t=n.getAttribute("data-list-level"))!=null?t:"1",10))!=null?e:1}function Qo(n){Ht(n);const t=n.getAttribute("data-list-group-id");return d(kc,t,"no group id"),t}function mo(n){var i,s,l,c,a;Ht(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(kc,r,"no group id"),{type:t,start:e,level:o,groupId:r}}function wc(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 Wn(n){Ht(n);const{level:t,groupId:e,type:o}=mo(n);let r=gt(n);for(;r;){if(!at(r))return null;const{level:i,groupId:s,type:l}=mo(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 Ko(n){Ht(n);const{level:t,groupId:e,type:o}=mo(n);let r=ht(n);for(;r;){if(at(r)){const{level:i,groupId:s,type:l}=mo(r);if(t===i&&e===s&&(l==="text-only"||o==="text-only"||o===l))return r;if(i<t)return null}r=ht(r)}return null}function i5(n){Ht(n);const t=[];let e=Wn(n);for(;e;)t.unshift(e),e=Wn(e);return t}function Bc(n){Ht(n);const t=[];let e=Ko(n);for(;e;)t.push(e),e=Ko(e);return t}function us(n){Ht(n);let t=Wn(n);for(;t;){const e=Wn(t);if(!e)return t;t=e}return n}function EE(n){Ht(n);let t=Ko(n);for(;t;){const e=Ko(t);if(!e)return t;t=e}return null}function IE(n,t){const e=i5(n),o=Bc(n);return t.withSelf?[...e,n,...o]:[...e,...o]}function Ec(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 Sh(n,t,e,o){const r=IE(t,{withSelf:!0});r.length!==0&&Ec(n,r,e,o)}function xE(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 SE="abcdefghijklmnopqrstuvwxyz";function s5(n){if(n<=0)return`${n}`;const t=(n-1)%26,e=Math.floor((n-1)/26),o=SE[t];return e?s5(e)+o:o}function TE(n){return`${n}`}const l5=[TE,s5,xE];function DE(n,t){const e=l5[(n-1)%l5.length];return e(t)}function LE(n){return["\u2022","\u25E6","\u25AA"][(n-1)%3]}class Jo{constructor(t,e,o){u(this,"listStart");u(this,"listBrother",null);this.editor=t,this.options=o;const r=us(e),i=Se(r);this.listStart=i,this.listBrother=r,o!=null&&o.resetStart&&(this.listStart=1)}fix(){!this.listBrother||Sh(this.editor,this.listBrother,this.listStart,this.options)}}function ME(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 at(o)?o:null}o=gt(o)}return null}function c5(n,t){const e=n.getAttribute("data-style-heading"),o=ME(n,e);if(o)return o;const r=gt(n);if(r&&at(r)&&je(r)===t)return r;const i=ht(n);return i&&at(i)&&je(i)===t?i:null}function RE(n,t,e){var E,D,x;const o=(E=e.data)!=null?E:{},r=1,i=(D=o.listType)!=null?D:"ordered";if(i==="text-only")return null;const s=n.getBlockData(t);let l=(x=s.text)!=null?x:[];const c=n.selection.range.focus;if(!c.isSimple())return null;let h=wt(l);const f=c.offset;f<=ce(l)&&(l=fe(l,f).right,h=h.substring(0,f));let m=1;i==="ordered"&&(m=Number.parseInt(h,10)||1);let C=N();const v=c5(t,i);if(v){if(K(t)>K(v))m=Se(v)+1;else{const A=Se(v);A>1&&(m=A-1)}C=Qo(v)}const w={id:N(),type:"list",level:r,start:m,groupId:C,ordered:!1,text:l};return s.quoted&&(w.quoted=!0),s.heading&&(w.heading=s.heading),i==="ordered"?w.ordered=!0:(i==="checked"||i==="unchecked")&&(w.checkbox=i),{blockData:w,onConverted:(A,O)=>{new Jo(A,O).fix()}}}const OE=8,Mt=y("list-block");class Ic{constructor(t,e){u(this,"listStart",0);u(this,"listBrother",null);if(this.editor=t,yc(e))return;const o=us(e),r=Se(o);this.listStart=r,o===e?this.listBrother=Ko(o):this.listBrother=o}fix(){!this.listBrother||Sh(this.editor,this.listBrother,this.listStart)}}function AE(n,t,e){n.getBlockData(t).quoted&&(e.quoted=!0)}function Th(n,t,e,o){if(Mt.debug("drag a block on a list block"),!H(n,t))return!1;d(Mt,at(e),"target is not a list block");const{type:r,start:i,level:s,groupId:l}=mo(e),c=o==="after"?i+1:i,a=n.getBlockData(t),h={id:N(),type:"list",groupId:l,level:s,start:c,text:a.text,...wc(r)};AE(n,e,h);let f=K(e);const m=j(e);o==="after"&&(f+=1);let C=null;at(t)&&(C=new Ic(n,t));const v=n.insertBlock(U(m),f,h,Tl(h.id,0));return n.deleteBlock(t),new Jo(n,v).fix(),C==null||C.fix(),!0}function _E(n,t,e,o){if(Mt.debug("drag a list between text blocks"),o==="after"){const a=ht(e);if(a&&at(a))return Th(n,t,a,"before")}if(o==="before"){const a=gt(e);if(a&&at(a))return Th(n,t,a,"after")}const i={...n.getBlockData(t),groupId:N(),start:1,level:1};let s=K(e);const l=j(e);o==="after"&&(s+=1),n.insertBlock(U(l),s,i,Tl(i.id,0));const c=new Ic(n,t);return n.deleteBlock(t),c.fix(),!0}function NE(n,t,e,o,r){if(sl(e))return!1;const{blockId:i}=e,s=n.getBlockById(i);d(Mt,s,"no dragged block");const{isSourceBlock:l,targetBlock:c}=r;return!l&&c?(d(Mt,t===c,"block !== target block"),d(Mt,at(c),"target is not a list block"),Th(n,s,c,o)):_E(n,s,c,o)}function a5(n){return n.textOnly?"text-only":n.checkbox?n.checkbox:n.ordered?"ordered":"unordered"}function PE(n){var e,o;if(n.checkbox||n.textOnly)return"";const t=(e=n.level)!=null?e:1;return n.ordered?`${DE(t,(o=n.start)!=null?o:1)}.`:LE(t)}const $E=`<?xml version="1.0" ?>
|
|
334
|
+
</svg>`;function $w(n,t){var e;if(M(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 i=b("div",["menu-item-icon"],null);n.icon&&(i.innerHTML=n.icon),t.appendChild(i)}const o=b("div",["menu-item-name"],null,n.name);t.appendChild(o);const r=l0(n);if(r&&b("div",["item-shortcut","text"],t,r),n.children&&!n.element){const i=b("div",["menu-item-sub-indicator"],null);i.innerHTML=u0,t.appendChild(i)}if((e=n.states)!=null&&e.includes("checked")){const i=b("div",["menu-item-checked-icon"],null);i.innerHTML=bw,t.appendChild(i)}}}}class Wo extends nc{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){M(t,"menu")}initItemElement(t,e){$w(t,e)}}function jw(n,t,e){var o;return new Wo((o=n.children)!=null?o:[],t,{...e,parentItem:n})}class rc extends nc{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){M(t,"toolbar")}initItemElement(t,e){e.setAttribute("data-button-id",t.id),(!t.children||t.children.length===0)&&this.options.tooltipId&&(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=Fu}t.states&&(t.states.indexOf("checked")!==-1&&M(o,"checked"),t.states.indexOf("disabled")!==-1&&(o.disabled=!0))}}function Hw(n,t,e){var o;return new rc((o=n.children)!=null?o:[],t,{...e,parentItem:n})}const oF="";Pr.registerManualCommandBar("menu",jw),Pr.registerManualCommandBar("toolbar",Hw);const y0=y("ui-base");class ic extends nc{constructor(t,e){var i;const r=[{id:(i=e==null?void 0:e.id)!=null?i:`popup-${N()}`,name:"",element:t}];super(r)}initCommandBarElement(t){M(t,"popper")}initItemElement(t,e){}get popupContent(){const t=this.items[0];d(y0,t,"no dialog item");const e=typeof t.element=="function"?t.element(t):t.element;return d(y0,e,"no item element"),e}}const rF="",w0=y("ui-base");class sc extends nc{constructor(e,o){super(sc.getCommandItems(e,o),void 0,{disablePageScroll:!0,...o});u(this,"handleDocumentMouseDown",e=>{})}initCommandBarElement(e){M(e,"dialog","manual")}initItemElement(e,o){}show(e,o){this.manualShow(e,{...o,theme:"light"})}get dialogContent(){const e=this.items[0];d(w0,e,"no dialog item");const o=e.element;return d(w0,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 Fw=[-1,6,0,1,2,3,4,5],zw=[-1,6,0,1,2,3,4,5,14,13,7,8,9,10,11,12],B0=y("color-palette");function E0(n,t,e,o){d(B0,n>0,"no color in palette");const r=t||1;d(B0,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 h=e(l*i+a);c.appendChild(h)}}return s}function Uw(n){const t=b("button",["color-button"],null),e=Fw[n];return t.setAttribute("data-color-index",`${e}`),t.innerHTML=d0,t}function Vw(n){const t=b("button",["background-color-button"],null),e=zw[n];return t.setAttribute("data-color-index",`${e}`),t}function qw(){const n=b("div",["clear-button-container"],null),t=b("button",["clear-button"],n);return t.innerText=S.t("colorPalette.reset"),n}function Ww(n){const t=b("div",["color-palette"],null);return n.color!==!1&&(b("div",["bar-desc"],t,S.t("colorPalette.colorDesc")),t.appendChild(E0(8,1,Uw,"color"))),n.backgroundColor!==!1&&(b("div",["bar-desc"],t,S.t("colorPalette.backgroundDesc")),t.appendChild(E0(16,2,Vw,"background-color"))),n.clearColorButton!==!1&&t.appendChild(qw()),t}function Gw(n,t,e){const o=t==="color"?"color":"background-color",r=n.querySelector(`.${o} button.selected`);r&&F(r,"selected"),e===null&&(e=-1);const i=n.querySelector(`.${o} button[data-color-index="${e}"]`);i&&M(i,"selected")}const iF="",Zw={};class Yw extends Wt.TypedEmitter{constructor(e=Zw){super();u(this,"root");u(this,"handleClick",e=>{const o=e.target;if(!o||!(o instanceof Element))return;const r=o.closest("button");if(!r)return;if(lt(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)||(lt(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=Ww(e),this.root.addEventListener("click",this.handleClick)}destroy(){this.removeAllListeners(),this.root.removeEventListener("click",this.handleClick)}setColor(e,o){Gw(this.root,e,o)}}class I0{constructor(t,e){u(this,"name","Color Palette");u(this,"element");u(this,"palette");u(this,"closeable",null);this.id=t,this.palette=new Yw(e),this.element=this.palette.root}setCloseable(t){this.closeable=t}destroy(){this.palette.destroy(),this.closeable=null}}function Qw(){const n=b("button",["color-button"],null);return n.innerHTML=d0,n}function Xu(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 Kw extends Wt.TypedEmitter{constructor(e){super();u(this,"id","text-color-item");u(this,"name","Text color");u(this,"dropdown",!0);u(this,"manualShowChildren",!0);u(this,"children",[]);u(this,"element");u(this,"colorPaletteItem");u(this,"latestColors",[null,null]);u(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],Xu(this.element,this.latestColors)});u(this,"beforePopup",()=>{this.emit("beforePopup")});this.editor=e,this.colorPaletteItem=new I0("text-color-palette-item"),this.colorPaletteItem.palette.addListener("onClick",this.handlePaletteClick),this.children.push(this.colorPaletteItem),this.element=Qw()}destroy(){this.colorPaletteItem.destroy()}updatePaletteColor(e){this.colorPaletteItem.palette.setColor("color",e[0]),this.colorPaletteItem.palette.setColor("backgroundColor",e[1]),this.latestColors=e,Xu(this.element,this.latestColors)}updateButtonColor(e){this.latestColors=e,Xu(this.element,this.latestColors)}}const sF="";function th(n,t){const e=b("div",["editor-input-wrap"],n);t!=null&&t.className&&M(e,t==null?void 0:t.className);const o=b("div",["editor-input-label"],e);b("span",[],o,t.label),t.required&&M(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),F(e,"error")}),i.addEventListener("keydown",l=>{var c;(c=t.onKeyDown)==null||c.call(t,l)}),{getField:()=>i,getInputValue:()=>i.value,setFieldError:l=>{M(e,"error"),s.innerText=l}}}function Jw(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 Xw=y("ui-base");class tB{constructor(t,e){u(this,"menu");u(this,"currentText","");u(this,"handleClick",(t,e)=>{this.options.onClickItem(this,e)});u(this,"handleClose",()=>{Jw(this.editor)&&this.editor.focus()});u(this,"handleKeydown",t=>{this.menu.handleDocumentKeydown(t)});this.editor=t,this.options=e,this.menu=new Wo([],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,h;if(((h=(a=this.options).onShow)==null?void 0:h.call(a,this,t,e,o))===!1)return;this.options.showLoading&&this.showLoading();const r=this.editor.getBlockByIndex(t,e);if(!vt(this.editor.rootContainer,r)||Z(this.editor,r)<o)return;const i=Oo(this.editor,r,Lt(this.editor,r,o));if(i.length===0)return;const s=i[0],l=_o(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:S.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 Ue.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)}finally{Ue.release(e)}}highlightText(t){Xw.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 h=0;for(h=0;h<=i.length-c;h){const f=i.substring(h,h+c);f.toLocaleLowerCase()===a?(l+=`<span class="highlight">${f}</span>`,h+=c):(l+=i.charAt(h),h++)}return h<i.length&&(l+=i.substring(h)),l},r=i=>{if(lt(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 eh=y("auto-suggest-menu");class nh{constructor(t,e){u(this,"menu");u(this,"anchor",null);u(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(wt(fe(we(t,i),e.offset).left).startsWith(this.anchor.leftText))return}this.menu.close()});u(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=wt(Rl(t,i,r));if(d(eh,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});u(this,"onShow",(t,e,o,r)=>{var i;if((i=this.options)!=null&&i.onShow)return this.options.onShow(this,e,o,r)});u(this,"onClickItem",(t,e)=>{!this.anchor||(this.options.autoDeleteTrigger&&this.deleteTrigger(),this.options.onClickItem(this,e,this.anchor))});u(this,"queryItems",(t,e)=>this.options.queryItems(this,e));u(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 tB(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)||Za(e.key)?!1:tm(e)&&!To(e)?(setTimeout(()=>{this.resetItems()}),!1):Ya(e)?(this.menu.close(),!0):(this.menu.handleKeydown(e),!0)}popup(t,e,o,r){this.anchor={blockId:G(t),offset:e,leftText:o,trigger:r};const i=U(j(t)),s=K(t);this.menu.popup(i,s,e)}handleAfterInsertText(t,e,o,r,i){var h;const s=t.selection.range.start;if(!s.isSimple())return!1;const{blockId:l,offset:c}=s,a=t.getBlockByIndex(e,o);if(G(a)!==l)return!1;if((h=this.menu)!=null&&h.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=wt(Rl(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 G(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=wt(Rl(t,i,r));if(d(eh,this.anchor,"no anchor"),s.startsWith(this.anchor.leftText)){const c=s.substring(this.anchor.leftText.length);eh.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()}}const yn=y("table-dom");function ho(n){return`${G(n)}_scroll`}function $t(n){const t=n.querySelector("div[data-type=table-content] >table");return d(yn,t instanceof HTMLTableElement,"invalid table"),t}function wn(n,t){const o=n.getCustom(ho(t)).contentElement.firstElementChild;d(yn,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(yn,r,"no table tools"),r}function x0(n){const t=[];return Array.from(n.rows).forEach(e=>{t.push(...Array.from(e.cells))}),t}function os(n){const t=n.querySelector(":scope div[data-type=editor-container]");return d(yn,t,"no child container in cell"),t}function eB(n){const o=x0(n).map(r=>{const i=os(r),s=U(i),l=r.colSpan,c=r.rowSpan;return`${s}/${l}/${c}`}).join();return Ci.default(o)}function jt(n){return it(n)==="table"}function oh(n){const t=j(n);if(Ct(t))return null;const e=z(t);return d(yn,e,"no parent block"),jt(e)?t:oh(e)}function Ee(n){if(jt(n))return n;const t=j(n);if(Ct(t))return null;const e=z(t);return d(yn,e,"no parent block"),jt(e)?e:Ee(e)}function nB(n,t){const e=n.querySelector("colgroup");d(yn,e,"no colgroup");const o=e.children[t];return d(yn,o,"no col"),d(yn,o instanceof HTMLTableColElement,`invalid col: ${o.tagName}`),o}function S0(n){try{return $t(n),!0}catch{return!1}}function oB(n){return At(n).querySelector(":scope > .block-helper")}function rB(n){const t=z(n.contentElement);d(yn,t,"no block");const e=oB(t);if(e){const o=Math.min(n.contentElement.offsetLeft,n.rootElement.scrollLeft),r=t.getBoundingClientRect().width;e.style.right=`${o+r}px`}}const Ie=y("doc-table-grid");class iB{constructor(t){u(this,"_cells",[]);for(let e=0;e<t;e++)this._cells.push(void 0)}cols(){return this._cells.length}setCell(t,e){d(Ie,t>=0&&t<this.cols(),`set cell, invalid col: ${t}`),this._cells[t]=e}getCell(t){d(Ie,t>=0&&t<this.cols(),`get cell, invalid col: ${t}`);const e=this._cells[t];return d(Ie,e,"get cell, no cell"),e}getCellAllowEmpty(t){return d(Ie,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 rh{constructor(t){u(this,"_data");u(this,"_rows");this._data=t,this._rows=[];for(let e=0;e<this.rowCount;e++)this._rows.push(new iB(this.colCount));this.fillGrid(),d(Ie,t.colsWidth,"no colsWidth"),d(Ie,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(Ie,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 h=0;h<s;h++)this._rows[o+a].setCell(e+h,{col:e,row:o,containerId:r,virtual:h!==0||a!==0,colSpan:s,rowSpan:l});const c=this.getNextEmptyCell(e,o);c?(e=c.col,o=c.row):d(Ie,i===t.length-1,`invalid table data, no next empty cell: ${JSON.stringify(this._data)}`)}),this._rows.forEach(r=>{r.forEach(i=>{d(Ie,i,"no cell"),d(Ie,i.containerId,"no containerId")})})}getCell(t){const{col:e,row:o}=t,r=this._rows[o];d(Ie,r,`get cell, no row: ${o}`);const i=r.getCell(e);return d(Ie,i,`get cell, no cell: ${e}`),i}getRow(t){const e=this._rows[t];return d(Ie,e,`get row, no row: ${t}`),e}forEach(t){this._rows.forEach(t)}}const lc=y("table-data");function sB(n){const t=n.firstElementChild;return d(lc,t,"no child element for cell"),d(lc,mn(t),"cell first child is not a container"),d(lc,We(t),"cell first child is not a container"),t}function lB(n){const t=z(n);d(lc,t,"no parent block for table");const e=[],o={};Array.from(n.rows).forEach(l=>{Array.from(l.cells).forEach(c=>{const a=sB(c),h=U(a);e.push(h),(c.colSpan>1||c.rowSpan>1)&&(o[`${h}_colSpan`]=c.colSpan,o[`${h}_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:G(t),type:it(t),rows:r,cols:i,children:e,colsWidth:Array(i).fill(100),...o}}function Go(n){return new rh(n)}function cB(n){return Go(lB(n))}const qt=y("table-grid"),aB=60;class dB{constructor(t,e){u(this,"containerId");u(this,"row");u(this,"col");u(this,"colSpan");u(this,"rowSpan");u(this,"virtual");u(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(qt,e,"no parent cell for child container"),e}get container(){const t=this.table.querySelectorAll(`[data-container-id=${this.containerId}]`);d(qt,t.length===1,"containers !== 1"),d(qt,mn(t[0]),"not a container");const e=t[0];return d(qt,We(e),"not a child container"),e}}class uB{constructor(t,e){u(this,"_cells",[]);e.forEach(o=>{this._cells.push(new dB(t,o))})}get cells(){return this._cells}getCell(t){return d(qt,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 rf=class{constructor(t){u(this,"_rows",[]);this.table=t,cB(t).forEach(r=>{this._rows.push(new uB(t,r))});const o=this.colCount;this._rows.forEach(r=>{d(qt,r.cells.length===o,"row.cells.length !== colCount")})}get rowCount(){return this._rows.length}get colCount(){return this._rows.length===0?0:(d(qt,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(qt,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(qt,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(qt,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(qt,!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(qt,o<=r,"min > max"),d(qt,o>=0,"min < 0"),d(qt,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(qt,o<=r,"min > max"),d(qt,o>=0,"min < 0"),d(qt,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,h=1e4,f=-1,m=-1;return c.forEach(C=>{h=Math.min(C.col,h),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:h},{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),h=Math.max(i.col,s.col);for(let f=l;f<=c;f++)for(let m=a;m<=h;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(qt,o,"cell not found"),o}getCellByCellElement(t){const e=os(t);return this.getCellByContainerId(U(e))}getCellByContainerId(t){return this.getCellById(t)}static fromTable(t){const e=eB(t),o=this.caches.getSync(e,()=>(qt.debug("create table grid"),new rf(t)));return o.table!==t?(this.caches.delete(e),this.fromTable(t)):o}static fromBlock(t){return this.fromTable($t(t))}};let et=rf;u(et,"caches",new Of(aB));function cc(n,t){Object.entries(n).forEach(([e])=>{e.startsWith(`${t}/`)&&delete n[e]})}const hB=y("table-selection-range");function sn(n,t,e){var x,O,A,P;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,h=(x=c==null?void 0:c.rowIndex)!=null?x:s.row,f=(O=c==null?void 0:c.colIndex)!=null?O:s.col,m=(A=a==null?void 0:a.rowIndex)!=null?A:l.row+l.rowSpan-1,C=(P=a==null?void 0:a.colIndex)!=null?P:l.col+l.colSpan-1,v=Math.min(h,m),w=Math.max(h,m),E=Math.min(f,C),L=Math.max(f,C);return{fromRow:v,toRow:w,fromCol:E,toCol:L}}function ih(n,t){const e=new Set,o=new Set,r=n.selection.range;if(!r.isSimple()&&r.start.blockId===G(t)){const i=et.fromBlock(t),{start:s,end:l}=r;d(hB,!s.isSimple()&&!l.isSimple(),"invalid range");const{fromCol:c,toCol:a,fromRow:h,toRow:f}=sn(t,s,l);if(h===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=h;m<=f;m++)e.add(m)}return{selectedRows:e,selectedColumns:o}}const $r=y("delete-columns");function T0(n,t,e){const{start:o,end:r}=e;if(o.blockId!==r.blockId||e.isSimple()||n.getBlockById(o.blockId)!==t||it(t)!=="table")return!1;const{fromRow:s,toRow:l}=sn(t,e.start,e.end),c=et.fromBlock(t);return s===0&&l===c.rowCount-1}function sh(n){var O;const t=n.getEditor(),e=t.getBlockById(n.start.blockId);if(!T0(t,e,n))return;if(n.isSimple()){t.deleteBlock(e);return}const{fromCol:o,toCol:r}=sn(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(A=>A.containerId);for(let A=0;A<l.length;A++){const P=l[A];for(let V=o;V<=r;V++){const nt=P[V];s.add(nt)}P.splice(o,r-o+1)}const c=new Set(l.flat()),a=new Set(Array.from(s).filter(A=>!c.has(A))),h=r-o+1,f=new Map,m=new Map;s.forEach(A=>{if(a.has(A))return;const P=i.getCellByContainerId(A);if(d($r,P.colSpan>1,"invalid effected cell, colSpan === 1"),P.col<o){d($r,c.has(A),"invalid effected cell, not exists");let Et=P.col+P.colSpan-1;Et>r&&(Et=r);const re=Et-o+1,Xn=P.colSpan-re;f.set(A,Xn);return}d($r,P.col<=r,"invalid effected cell, col > endCol");const V=P.col,nt=P.col+P.colSpan-1,ot=P.col-o,ut=nt-V+1-h+ot;d($r,ut>0,"invalid effected cell, newSpanned <= 0");const dt=Cn(t.doc);m.set(A,{newContainerId:dt,colSpan:ut})});for(let A=0;A<l.length;A++){const P=l[A];for(let V=o;V<P.length;V++){const nt=P[V],ot=m.get(nt);ot&&(P[V]=ot.newContainerId)}}const C=Y.default(t.getBlockData(e));C.colsWidth.splice(o,r-o+1),a.forEach(A=>{cc(C,A)}),f.forEach((A,P)=>{d($r,A>=1,"invalid modified colSpan, colSpan < 1"),A===1?delete C[`${P}_colSpan`]:C[`${P}_colSpan`]=A}),m.forEach((A,P)=>{cc(C,P);const{newContainerId:V,colSpan:nt}=A;d($r,nt>=1,"invalid newContainerData, colSpan < 1"),nt>1&&(C[`${V}_colSpan`]=nt);const ot=i.getCellByContainerId(P).rowSpan;ot>1&&(C[`${V}_rowSpan`]=ot)});const w=(O=l[0][o])!=null?O:l[0][o-1],E=t.getChildContainerData(w)[0],L=et.virtualCellContainersGridToChildren(l),x={...C,cols:C.cols-h,children:L};Go(x),t.updateBlockData(e,x,Lt(t,E.id,0)),t.deleteChildContainers(Array.from(a)),t.deleteChildContainers(Array.from(m.keys()))}const jr=y("delete-rows");function D0(n,t,e){const{start:o,end:r}=e;if(o.blockId!==r.blockId||e.isSimple()||n.getBlockById(o.blockId)!==t||it(t)!=="table")return!1;const{fromCol:s,toCol:l}=sn(t,e.start,e.end),c=et.fromBlock(t);return s===0&&l===c.colCount-1}function lh(n){const t=n.getEditor(),e=t.getBlockById(n.start.blockId);if(!D0(t,e,n))return;if(n.isSimple()){t.deleteBlock(e);return}const{fromRow:o,toRow:r}=sn(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(x=>x.containerId);for(let x=r;x>=o;x--)l[x].forEach(A=>s.add(A)),l.splice(x,1);const c=new Set(l.flat()),a=new Set(Array.from(s).filter(x=>!c.has(x))),h=r-o+1,f=new Map,m=new Map;s.forEach(x=>{if(a.has(x))return;const O=i.getCellByContainerId(x);if(d(jr,O.rowSpan>1,"invalid effected cell, rowSpan === 1"),O.row<o){d(jr,c.has(x),"invalid effected cell, not exists");let ut=O.row+O.rowSpan-1;ut>r&&(ut=r);const dt=ut-o+1,Et=O.rowSpan-dt;f.set(x,Et);return}d(jr,O.row<=r,"invalid effected cell, col > endCol");const A=O.row,P=O.row+O.rowSpan-1,V=O.row-o,nt=P-A+1-h+V;d(jr,nt>0,"invalid effected cell, newSpanned <= 0");const ot=Cn(t.doc);m.set(x,{newContainerId:ot,rowSpan:nt})});for(let x=o;x<l.length;x++){const O=l[x];for(let A=0;A<O.length;A++){const P=O[A],V=m.get(P);V&&(O[A]=V.newContainerId)}}const C=Y.default(t.getBlockData(e));a.forEach(x=>{cc(C,x)}),f.forEach((x,O)=>{d(jr,x>=1,"invalid modified rowSpan, rowSpan < 1"),x===1?delete C[`${O}_rowSpan`]:C[`${O}_rowSpan`]=x}),m.forEach((x,O)=>{cc(C,O);const{newContainerId:A,rowSpan:P}=x;d(jr,P>=1,"invalid newContainerData, rowSpan < 1"),P>1&&(C[`${A}_rowSpan`]=P);const V=i.getCellByContainerId(O).colSpan;V>1&&(C[`${A}_colSpan`]=V)});const v=l[o]?l[o][0]:l[o-1][0],w=t.getChildContainerData(v)[0],E=et.virtualCellContainersGridToChildren(l),L={...C,rows:C.rows-h,children:E};Go(L),t.updateBlockData(e,L,Lt(t,w.id,0)),t.deleteChildContainers(Array.from(a)),t.deleteChildContainers(Array.from(m.keys()))}const rs=y("table-range");function ac(n){d(rs,!n.isSimple(),"must be complex selection range");const{anchor:t,focus:e}=n;d(rs,!t.isSimple(),"invalid start pos type"),d(rs,!e.isSimple(),"invalid end pos type");const o=n.getEditor();d(rs,t.blockId===e.blockId,"invalid range, not same block");const r=o.getBlockById(t.blockId);d(rs,it(r)==="table","invalid block type, not a table block");const i=$t(r),s=et.fromTable(i),l=s.getCellByContainerId(t.childContainerId),c=s.getCellByContainerId(e.childContainerId),a=Math.min(l.row,c.row),h=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:h,col:m});return{editor:o,block:r,table:i,startCell:C,endCell:v,startRow:a,startCol:f,endRow:h,endCol:m}}const ch=y("split-cell");function ah(n,t,e){const o=et.fromBlock(t),r=o.getRealCell(e);d(ch,!r.virtual,"should not split virtual cell"),d(ch,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,w=Cn(n.doc);i[C][v]=w}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(ch,a,"no child block");const h=Lt(n,a.id,0);Go(l),n.updateBlockData(t,l,h)}function fB(n,t,e){e.forEach(o=>{const r=et.fromBlock(t).getCell(o);(r.virtual||r.colSpan>1||r.rowSpan>1)&&ah(n,t,o)})}function L0(n,t,e){if(e.isSimple())return!1;const{start:o,end:r}=e;if(o.blockId!==r.blockId||n.getBlockById(o.blockId)!==t||it(t)!=="table")return!1;const{startCell:s,endCell:l}=ac(e);return!(s.cell!==l.cell||s.colSpan===1&&s.rowSpan===1)}function dh(n){const{editor:t,block:e,startRow:o,startCol:r,endRow:i,endCol:s}=ac(n),l=[];for(let c=o;c<=i;c++)for(let a=r;a<=s;a++)l.push({row:c,col:a});return fB(t,e,l),!0}const Hr=y("merge-cells");function M0(n,t,e){if(e.isSimple())return!1;const{start:o,end:r}=e;if(o.blockId!==r.blockId||n.getBlockById(o.blockId)!==t||it(t)!=="table")return!1;const{startCell:s,endCell:l}=ac(e);return s.cell!==l.cell}function R0(n){const t=ac(n),e=t.endCell,o=e.row+e.rowSpan-1,r=e.col+e.colSpan-1,i=G(t.block),s=t.editor;dh(n);const l=s.getBlockById(i),c=$t(l),{startRow:a,startCol:h}=t,f=Y.default(s.getBlockData(l));d(Hr,f.children,"no table children");const m=et.fromTable(c),C=[];for(let ut=a;ut<=o;ut++)for(let dt=h;dt<=r;dt++){const Et=m.getCell({row:ut,col:dt});d(Hr,!Et.virtual,"cell is virtual"),C.push(Et)}d(Hr,C.length>0,"no selected cells");const v=C[0],w=C.slice(1),E=m.getCellByContainerId(v.containerId).container,L=[];w.forEach(ut=>{const dt=m.getCellByContainerId(ut.containerId).container,Et=U(dt);if(!hd(s,dt)){const re=tu(s,Et);s.insertDocAt(E,Ve(E),re)}L.push(Et)});const x=U(E),O=r-h+1,A=o-a+1;f[`${x}_colSpan`]=O,f[`${x}_rowSpan`]=A,L.forEach(ut=>{d(Hr,f.children,"no table children");const dt=f.children.indexOf(ut);d(Hr,dt>0,"no deleted container"),f.children.splice(dt,1)});const P=f,nt=s.getChildContainerData(x)[0];d(Hr,nt,"no child block");const ot=Lt(s,nt.id,0);Go(P),s.updateBlockData(l,P,ot),s.deleteChildContainers(L)}const uh=10,mB=["table/merge-cells","table/split-cell","table/insert-column","table/insert-row","table/delete-rows","table/delete-columns","table/delete"];class hh{constructor(){u(this,"id","TableBlockCommandProvider")}getAvailableCommands(t,e,o){if(it(e)!=="table")return[];const r={blockId:G(e),blockKind:Ge(t,e),blockType:it(e)},i=[];M0(t,e,o)&&i.push({id:"table/merge-cells",name:"merge cells",icon:nw,groupIndex:uh,...r}),L0(t,e,o)&&i.push({id:"table/split-cell",name:"split cell",icon:ow,groupIndex:uh,...r});const s=T0(t,e,o),l=D0(t,e,o);return s&&l&&i.push({id:"table/delete",name:"delete tables",icon:rw,groupIndex:uh,...r}),i}executeCommand(t,e,o,r,i,s){return it(e)!=="table"||!new Set(mB).has(r.id)?!1:r.id==="table/merge-cells"?(R0(o),!0):r.id==="table/split-cell"?(dh(o),!0):r.id==="table/delete-columns"?(sh(o),!0):r.id==="table/delete-rows"?(lh(o),!0):r.id==="table/delete"?(t.deleteBlock(e),!0):!1}}var O0=(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))(O0||{});const fh=6,is=20;function gB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasColTitle:!0};n.updateBlockData(t,o)}function pB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasColTitle:!1};n.updateBlockData(t,o)}function CB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasRowTitle:!0};n.updateBlockData(t,o)}function bB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),hasRowTitle:!1};n.updateBlockData(t,o)}function vB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),isStripeStyle:!0};n.updateBlockData(t,o)}function kB(n,t){if(!n.isBlockWritable(t))return;const o={...Y.default(n.getBlockData(t)),isStripeStyle:!1};n.updateBlockData(t,o)}function yB(n,t,e){if(!n.isBlockWritable(t))return;const r={...Y.default(n.getBlockData(t)),noBorder:!e};n.updateBlockData(t,r)}const mh=y("get-selected-containers");function gh(n,t,e,o){d(mh,e.blockId===o.blockId,"only allow select in single table block"),d(mh,G(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(E=>r.getCellContainer(E));const{fromCol:l,toCol:c,fromRow:a,toRow:h}=sn(t,e,o),f=new Set,m=[];return r.sub({row:a,col:l},{row:h,col:c}).forEach(v=>{v.forEach(w=>{const E=r.getCellByContainerId(w.containerId);E.col<l||E.row<a||E.col+E.colSpan-1>c||E.row+E.rowSpan-1>h||f.has(w.containerId)||(f.add(w.containerId),m.push(E.container))})}),m}function wB(n,t,e){d(mh,t.blockId===e.blockId,"only allow select in single table block");const o=n.getBlockById(t.blockId);return gh(n,o,t,e)}const Zo=y("table-cell-dom");function BB(n,t,e){let o=n.getBlockById(e);for(;o;){const r=o.closest("td");d(Zo,r,"no parent cell");const i=z(r);if(d(Zo,i,"no parent block"),i===t)return r;o=i}return d(Zo,!1,"filed to get cell by child block id"),null}function qn(n,t,e){if(n.getBlockById(e.blockId)===t&&!e.isSimple())return d(Zo,e.childContainerId,"block position must have childContainerId attribute"),e;const r=BB(n,t,e.blockId),i=U(os(r));return bt(t,i)}function ph(n,t){const e=n.selection.range,o=qn(n,t,e.start),r=qn(n,t,e.end);return sn(t,o,r)}function A0(n,t,e,o){d(Zo,jt(t),"invalid table block");const r=wn(n,t),i=()=>{const l=r.querySelector(".table-border-bar-container.top");d(Zo,l,"no top border bar container"),l.querySelectorAll(".table-border-bar-cell.top").forEach(a=>{const h=parseInt(a.getAttribute("data-top-index")||"0",10);o.includes(h)?M(a,"danger"):F(a,"danger")})},s=()=>{const l=r.querySelector(".table-border-bar-container.left");d(Zo,l,"no left border bar container"),l.querySelectorAll(".table-border-bar-cell.left").forEach(a=>{const h=parseInt(a.getAttribute("data-left-index")||"0",10);e.includes(h)?M(a,"danger"):F(a,"danger")})};i(),s()}function Fr(n,t,e=!0,o){const i=et.fromBlock(t).map(h=>h),{fromCol:s,toCol:l,fromRow:c,toRow:a}=ph(n,t);for(let h=0;h<i.length;h++){const f=i[h];for(let m=0;m<f.length;m++){const C=f[m],v=o?m>=s&&m+C.colSpan-1<=l:h>=c&&h+C.rowSpan-1<=a;e&&v?C.virtual||M(C.cell,"danger"):C.virtual||F(C.cell,"danger")}}}function zr(n,t,e=!0,o){const r=new Set,i=new Set;if(!e){A0(n,t,Array.from(r),Array.from(i));return}const{fromCol:s,toCol:l,fromRow:c,toRow:a}=ph(n,t);if(o)for(let h=s;h<=l;h++)i.add(h);else for(let h=c;h<=a;h++)r.add(h);A0(n,t,Array.from(r),Array.from(i))}function _0(n,t,e){const{fromCol:o,toCol:r,fromRow:i,toRow:s}=ph(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}),Vt(n,{anchor:bt(t,c.containerId,{colIndex:o,rowIndex:0}),focus:bt(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}),Vt(n,{anchor:bt(t,c.containerId,{colIndex:0,rowIndex:i}),focus:bt(t,a.containerId,{colIndex:l.colCount-1,rowIndex:s})}))}function EB(n,t){const e=n.selection.range,o=qn(n,t,e.start),r=qn(n,t,e.end);return gh(n,t,o,r)}const N0=["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 P0(n){return`style-bg-color-${n}`}function ss(n){return`${n}_background`}function IB(n,t,e){const o=$t(n),s=(e!=null?e:et.fromTable(o)).getCell(t).cell;for(let l=0;l<N0.length;l++){const c=N0[l];if(lt(s,c))return c}}function $0(n,t,e){if(!n.isBlockWritable(t))return;const o=n.selection.range,i={...Y.default(n.getBlockData(t))},s=qn(n,t,o.start),l=qn(n,t,o.end);if(o.isSimple()){const c=s.childContainerId;e===-1?i[ss(c)]=void 0:i[ss(c)]=P0(e)}else{const c=et.fromBlock(t),a=sn(t,s,l),h=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});!h.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&&(h.add(C.containerId),e===-1?i[ss(C.containerId)]=void 0:i[ss(C.containerId)]=P0(e))}}n.updateBlockData(t,i)}function xB(n,t,e){if(!n.isBlockWritable(t))return;const r={...Y.default(n.getBlockData(t)),chart:e};n.updateBlockData(t,r)}const j0=y("table-chart");function SB(n,t){const e=wn(n,t);if(e){const o=e.querySelector(".editor-table-chart");if(o){const r=o.chartObject;r&&r.destroy(),o.remove()}}}async function TB(n,t){if(!n.isBlockWritable(t))return;if(!!!n.getBlockData(t).chart){SB(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 w=1;w<i.colCount;w++)c.push(i.getCell({row:0,col:w}).container.innerText);for(let w=1;w<i.rowCount;w++){const E=i.getCell({row:w,col:0}),x=E.container.innerText,O=[];for(let re=1;re<i.colCount;re++){const Xn=i.getCell({row:w,col:re}).container.innerText,te=Number.parseFloat(Xn)||0;O.push(te)}let A;const P=IB(t,E,i);P?A=window.getComputedStyle(n.rootElement).getPropertyValue(`--${P}`).trim():A=window.getComputedStyle(n.rootElement).getPropertyValue("--background-color").trim();let[V,nt,ot,ut]=A?Pa.fromString(A).toRgbaArray():[];if(!V&&!nt&&!ot&&!ut){const re=(w-1)%n.options.colors.length;A=n.options.colors[re],[V,nt,ot,ut]=Pa.fromString(A).toRgbaArray()}const dt=A,Et=Pa.fromRgba([V,nt,ot,ut/3]).toHexString();r.push({label:x,data:O,borderColor:dt,backgroundColor:Et,borderWidth:2})}const a=wn(n,t);let h=null,f=a.querySelector(".editor-table-chart");f?h=f.chartObject:f=b("div",["editor-table-chart"],a);const m=f;d(j0,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 xo(v,"editor-chartjs"),h&&l!==h.config.type&&(h.destroy(),h=null,Array.from(f.querySelectorAll(".editor-chartjs-canvas")).forEach(L=>{L.remove()}));const w=$a.default({},{type:l,data:{datasets:r,labels:c},options:{onClick:()=>{n.selection.selectBlock(t,0,0)}}});if(h)$a.default(h.config,w),h.update();else{const L=b("canvas",["editor-chartjs-canvas"],m).getContext("2d");h=new window.Chart(L,w),f.chartObject=h}}catch(w){j0.error(`failed to resolve chart cdn: ${JSON.stringify(w)}`)}}async function H0(n,t){await Ue.lock("updateTableChart");try{await TB(n,t)}finally{Ue.release("updateTableChart")}}const F0=Qt.default(H0,1e3);let z0=null;function Ch(n,t,e){if(z0!==t&&(F0.flush(),z0=t),e.updateNow){H0(n,t);return}F0(n,t)}function bh(n,t){jt(t)&&Ch(n,t,{updateNow:!1})}function DB(n,t){jt(t)&&Ch(n,t,{updateNow:!0})}const $e={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"},dc={SCROLL_BAR:"container-scrollbar",FIXED:"fixed"},fo={SCROLL_CONTAINER:"scroll-container",TOOL:"container-scroll-tool",CONTAINER:"scroll-container-root",MAC:"mac",SCROLL_AREA:"scroll-area"};function uc(n,t){return n.containers.get(t)}function U0(n){return n.closest(`.${fo.SCROLL_CONTAINER}`)}function ln(n){return n.firstElementChild}function xe(n){return n.closest(`.${fo.CONTAINER}`)}function ls(n){const t=xe(n);let e=t.querySelector(`:scope >.${fo.TOOL}`);return e||(e=b("div",[fo.TOOL],t)),e}function LB(n){return xe(n).firstElementChild}function cs(n){const t=window.getComputedStyle(n);return{paddingBottom:parseFloat(t.paddingBottom),paddingTop:parseFloat(t.paddingTop),paddingLeft:parseFloat(t.paddingLeft),paddingRight:parseFloat(t.paddingRight)}}function vh(n,t){const e=xe(t),o=uc(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 h=Math.floor(c.left-l.left-i);h<0&&(h=0);let f=l.right;f-=r;let m=f-c.right;return m<0&&(m=0),h=Math.round(h),m=Math.round(m),{originWidth:a,maxLeft:h,maxRight:m}}function MB(n,t){const e=vh(n,t),{maxLeft:o}=e;t.style.marginLeft=`${0-o}px`,t.style.paddingLeft=`${o}px`}function RB(n,t){const e=vh(n,t);t.style.marginRight=`${0-e.maxRight}px`}function OB(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 V0=y("scroll-bar-handle"),AB=2;function Ur(n){const t=ls(n);let e=t.querySelector(`.${dc.SCROLL_BAR}`);return e||(e=b("div",[dc.SCROLL_BAR],t)),d(V0,e instanceof HTMLDivElement,"invalid child for container tools"),e.firstElementChild||b("div",[],e),e}function hc(n,t){const e=U0(t),o=Ur(e),{paddingLeft:r,paddingRight:i}=cs(t);e.style.marginLeft="",e.style.paddingLeft="",e.style.marginRight="";const s=vh(n,e),{originWidth:l,maxRight:c}=s;RB(n,e),MB(n,e);const a=e.scrollWidth-e.clientWidth;d(V0,o.firstElementChild instanceof HTMLDivElement,"invalid child for scroll bar"),o.style.width=`${l+c-r-i}px`,o.firstElementChild.style.width=`${l+c+a-r-i}px`}function _B(n,t){const e=ln(n),{paddingLeft:o}=cs(e);if(lt(t,"fixed")){const i=xe(n).getBoundingClientRect();t.style.left=`${i.left+o}px`}else t.style.left=`${o}px`}function Vr(n,t){const e=n.getParentScrollContainer(),o=OB(e),r=t.getBoundingClientRect(),i=Ur(t),s=i.getBoundingClientRect(),l=uc(n,xe(t)),c=(l==null?void 0:l.barFloatWindowBottom)||0,a=ln(t),{paddingTop:h,paddingBottom:f}=cs(a),m=document.documentElement.clientHeight-c,C=o.top+e.clientHeight-m,v=m+Math.min(0,C);if(t.scrollWidth>t.clientWidth&&r.top+h<v-s.height&&r.bottom>v-s.height+f){M(i,dc.FIXED);const E=C>0?c:0;i.style.bottom=`${Math.max(document.documentElement.clientHeight-o.bottom,0)+AB+E}px`}else F(i,dc.FIXED),i.style.bottom=`${f-s.height}px`;_B(t,i)}class NB{constructor(t,e){u(this,"intersectionObserver");u(this,"handleIntersection",t=>{t.forEach(e=>{this.containers.get(xe(e.target))?(this.handleIntersectionEntry(e),this.callback(e)):this.intersectionObserver.unobserve(e.target)})});u(this,"handleIntersectionEntry",t=>{const e=t.target;Vr(this.scrollCore,e);const o=ln(e);hc(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 Yo=y("container-scroll-shadow");function q0(n,t,e){const o=n,r=t.getBoundingClientRect(),i=e.getBoundingClientRect(),{paddingTop:s,paddingBottom:l}=cs(e);o.style.top=`${i.top-r.top+s}px`,o.style.bottom=`${r.bottom-i.bottom+l}px`}function W0(n,t){const e=n;t<24?e.style.width=`${(t/3).toFixed(2)}px`:e.style.width=""}function PB(n){const t=ls(n);d(Yo,t,"no container tools");let e=t.querySelector(`.${$e.LEFT}`);if(!e){const l=ln(n),c=[$e.COMMON,$e.LEFT];e=b("div",c,t),d(Yo,e instanceof HTMLDivElement,"invalid child for container tools"),q0(e,n,l)}d(Yo,e instanceof HTMLElement,"invalid child for container tools");const r=xe(n).getBoundingClientRect(),i=n.getBoundingClientRect();e.style.left=`${i.left-r.left}px`;const s=n.scrollLeft;d(Yo,e instanceof HTMLDivElement,"invalid child for container tools"),W0(e,s),M(e,$e.ACTIVE)}function $B(n){const t=ls(n);let e=t.querySelector(`.${$e.RIGHT}`);if(!e){const l=ln(n),c=[$e.COMMON,$e.RIGHT];e=b("div",c,t),d(Yo,e instanceof HTMLDivElement,"no div, create shadow failed"),q0(e,n,l)}d(Yo,e instanceof HTMLElement,"");const r=xe(n).getBoundingClientRect(),i=n.getBoundingClientRect();e.style.right=`${r.right-i.right}px`;const s=n.scrollWidth-n.scrollLeft-n.clientWidth;d(Yo,e instanceof HTMLDivElement,"no shadow element"),W0(e,s),M(e,$e.ACTIVE)}function jB(n){const e=ls(n).querySelector(`.${$e.LEFT}`);e&&F(e,$e.ACTIVE)}function HB(n){const e=ls(n).querySelector(`.${$e.RIGHT}`);e&&F(e,$e.ACTIVE)}function as(n){const t=Math.round(n.scrollLeft),e=ln(n),{paddingLeft:o,paddingRight:r}=cs(e);n.scrollWidth-o<=n.clientWidth-r||n.scrollWidth-o<=t+n.clientWidth-r?HB(n):$B(n),e&&n.scrollLeft>=e.offsetLeft+o?PB(n):jB(n)}class FB{constructor(t){u(this,"resizeObserver");u(this,"handleResizeEntry",t=>{const e=t.target,o=ln(e);as(e),hc(this.scrollCore,o),Vr(this.scrollCore,e)});u(this,"handleContentResize",t=>{t.forEach(e=>{this.containers.get(xe(e.target))?this.handleResizeEntry(e):this.unbind(e.target)})});this.scrollCore=t,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 G0=y("container-scroll-observer");class zB{constructor(t,e){u(this,"handleContentScroll",t=>{const e=t.target;d(G0,e instanceof Element,"invalid target for scroll event");const o=Ur(e);o.removeEventListener("scroll",this.handleScroll);const r=!0;this.fixScrollXPos(e,e.scrollLeft,r),this.bind(o),as(e),this.callback(e)});u(this,"handleScroll",t=>{const e=t.target;d(G0,e instanceof HTMLElement,"");const o=e.scrollLeft,r=!1,i=LB(e);this.unbindContentScroll(i),this.fixScrollXPos(i,o,r),this.bindContentScroll(i),as(i),this.callback(i)});u(this,"handlePrevent",t=>{t.stopPropagation()});u(this,"bindContentScrollCore",t=>{this.unbindContentScroll(t),t.addEventListener("scroll",this.handleContentScroll)});u(this,"unbindContentScroll",t=>{t.removeEventListener("scroll",this.handleContentScroll)});u(this,"bindContentScroll",Qt.default(this.bindContentScrollCore,300));u(this,"bind",Qt.default(this.bindCore,200));this.scrollCore=t,this.callback=e}fixScrollXPos(t,e,o){const r=Ur(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 UB{constructor(t){u(this,"scrollContainers",new Set);u(this,"handleParentContainerScroll",()=>{this.scrollContainers.forEach(t=>{Vr(this.scrollCore,t)})});u(this,"bindScrollContainer",t=>{const e=this.scrollContainers.size===0;this.scrollContainers.add(t),e&&this.eventTarget.addEventListener("scroll",this.handleParentContainerScroll)});u(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 VB=y("scroll-wrap-resize-observer");class qB{constructor(t){u(this,"resizeObserver");u(this,"handleScrollWrapResize",t=>{t.forEach(e=>{this.containers.get(xe(e.target))?this.handleScrollWrapResizeEntry(e):this.unbind(e.target)})});u(this,"handleScrollWrapResizeEntry",t=>{const e=t.target;d(VB,e instanceof HTMLElement,"invalid target for observer entry");const o=U0(e);hc(this.scrollCore,e),as(o),Vr(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 WB{constructor(t){u(this,"resizeObserver");u(this,"scrollContainersMap",new Map);u(this,"handleResizeEntry",t=>{t==null||t.forEach(e=>{const o=ln(e);as(e),hc(this.scrollCore,o),Vr(this.scrollCore,e)})});u(this,"handleResize",t=>{t.forEach(e=>{const o=this.scrollContainersMap.get(e.target);o!=null&&o.length&&this.handleResizeEntry(o)})});this.scrollCore=t,this.resizeObserver=new ResizeObserver(this.handleResize)}bind(t){var r,i;const e=xe(t),o=(r=uc(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=xe(t),o=(i=uc(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 lF="";class GB extends Wt.TypedEmitter{constructor(e){super();u(this,"containerIntersectionObserver",null);u(this,"containerResizeObserver",null);u(this,"containerScrollObserver",null);u(this,"parentContainerScrollObserver",null);u(this,"scrollWrapResizeObserve",null);u(this,"locatingContainerResizeObserver",null);u(this,"isWindowEventBind",!1);u(this,"containers",new Map);u(this,"handleScrollContainerScroll",e=>{this.emit("scroll",this,e)});u(this,"handleIntersection",e=>{const o=e.target,r=ln(o);e.isIntersecting?(this.load(),this.bindCore(o,r)):this.unbindCore(o,r)});u(this,"handleWindowEffect",()=>{var e;(e=this.getScrollContainerInViewable())==null||e.forEach(o=>{Vr(this,o)})});this.parentContainer=e}load(){this.containerResizeObserver||(this.containerResizeObserver=new FB(this)),this.containerScrollObserver||(this.containerScrollObserver=new zB(this,this.handleScrollContainerScroll)),this.parentContainerScrollObserver||(this.parentContainerScrollObserver=new UB(this)),this.scrollWrapResizeObserve||(this.scrollWrapResizeObserve=new qB(this)),this.locatingContainerResizeObserver||(this.locatingContainerResizeObserver=new WB(this)),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,h;const r=Ur(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),(h=this.locatingContainerResizeObserver)==null||h.unbind(e)}bindCore(e,o){var i,s,l,c,a,h;if(this.unbindCore(e,o),!e.closest("body"))return;const r=Ur(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),(h=this.locatingContainerResizeObserver)==null||h.bind(e)}bind(e,o){this.containers.set(e,o);const r=e.firstElementChild;this.containerIntersectionObserver||(this.containerIntersectionObserver=new NB(this,this.handleIntersection)),this.containerIntersectionObserver.bind(r)}unbind(e){var i;const o=e.firstElementChild,r=ln(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 Z0=y("scroll-container"),fc=new Map;class ZB extends Wt.TypedEmitter{constructor(){super(...arguments);u(this,"scrollListener");u(this,"options");u(this,"scrollContainerElement");u(this,"init",e=>{this.options=e;const o=b("div",[fo.CONTAINER],e.parentElement);St.isMac&&M(o,fo.MAC);const r=b("div",[fo.SCROLL_CONTAINER],o),i=b("div",[fo.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=fc.get(s),this.scrollListener||(this.scrollListener=new GB(s),fc.set(s,this.scrollListener)),this.scrollListener.unbind(o),this.scrollListener.bind(o,e),this.scrollListener.on("scroll",this.handleContainerScroll),this.scrollContainerElement=r});u(this,"handleContainerScroll",(e,o)=>{o===this.scrollContainerElement&&this.emit("scroll",this)})}get rootElement(){return this.scrollContainerElement}get contentElement(){return d(Z0,this.scrollContainerElement,"scrollContainerElement cannot be undefined"),ln(this.scrollContainerElement)}get scrollOptions(){return d(Z0,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=xe(this.contentElement);e&&fc.forEach((r,i)=>{r.unbind(e),r.containers.size===0&&(this.handleBaseListenerDestroy(r),fc.delete(i))})}}function YB(){return new ZB}const mc=100,QB=40,kh=y("column-width");function KB(n,t,e){nB(n,t).style.width=`${e}px`}function JB(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)}),kh.debug(`cellRightOffsets1: ${r.join()}`);for(let c=0;c<r.length;c++){const a=r[c];if(a===-1||c===0)continue;let h=c-1;for(;r[h]===-1&&(h--,h!==-1););const f=h===-1?0:r[h],C=(a-f)/(c-h);for(let v=h+1;v<c;v++)r[v]=f+C*(v-h)}kh.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 kh.debug(`widths: ${s.join()}`),s}function ds(n){return Array.from(n.querySelector("colgroup").children).map(o=>o.getBoundingClientRect().width||Number.parseInt(o.style.width,10)||100)}const XB=y("table-resize-gripper"),Y0=7,yh=(Y0-1)/2,tE=3;function eE(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(),h=Math.round(a.right);if(Math.abs(t-h)<=yh&&a.top<=e&&e<=a.bottom)return c}}return null}function nE(n){return!!n.rootContainer.querySelector(".table-resize-gripper")}function wh(n,t){return wn(n,t).querySelector(".table-resize-gripper")}function Q0(n,t){const e=wh(n,t);d(XB,!e,"resize gripper has already exists");const o=wn(n,t),r=b("div",["table-resize-gripper","table-indicator"],o);return b("div",["table-resize-gripper-indicator"],r),r}function K0(n,t,e){let o=wh(n,t);o||(o=Q0(n,t));const i=$t(t).getBoundingClientRect(),s=e.getBoundingClientRect(),l=0,c=i.height,a=n.getCustom(ho(t)).contentElement.getBoundingClientRect(),h=s.right-a.left;o.style.left=`${h-yh-fh-is}px`,o.style.top=`${l}px`,o.style.height=`${c}px`,o.style.width=`${Y0}px`}function Bh(n){n.rootContainer.querySelectorAll(".table-resize-gripper").forEach(t=>{t.remove()})}function oE(n,t,e){const r={...n.getBlockData(t),colsWidth:e};n.updateBlockData(t,r)}function rE(n,t,e,o){const r=t,i=et.fromTable(e),s=i.getCellByCellElement(r),l=s.col+s.colSpan-1,c=ds(e);let a=o;const h=(m,C)=>{const v=C+1,w=m.col+m.colSpan;return c.slice(v,w).reduce((L,x)=>L+x,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,w=v.getBoundingClientRect();let E=o-w.left+yh-tE;const L=os(v),x=ud(n,L)||QB*C.colSpan,O=h(C,l),A=x-O;E<A&&(E=A);const P=w.left+E;a=Math.max(a,P)}return a}const iE=y("table-resize-drag-drop");class sE{constructor(t,e,o,r){u(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,h=rE(this.editor,c,s,e.x-t.dragOffsetX)-s.getBoundingClientRect().left;d(iE,c,"no dragging cell");const m=et.fromTable(s).getCellByCellElement(c),C=m.col+m.colSpan-1,w=ds(s).slice(0,C).reduce((L,x)=>L+x,0),E=h-w;KB(s,C,E),K0(this.editor,l,c),this.editor.selection.caret.update()}onDragEnd(t,e,o,r,i){const s=ds(t.data.table);oE(this.editor,t.data.block,s),Bh(this.editor),this.onEnd&&(this.onEnd(e),this.onEnd=null)}}function lE(n,t){const e=document.elementFromPoint(t.x,t.y);if(!e)return null;const o=z(e);return!o||!n.contains(o)||!jt(o)?null:o}y("table-resize");class cE{constructor(t){u(this,"draggingRefCell",null);u(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=lE(t,i);if(!s||!S0(s)){Bh(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=$t(t),i=eE(r,e,o);if(i){if(!wh(this.editor,t)){if(nE(this.editor))return;const l=Q0(this.editor,t),c={block:t,table:r,draggingRefCell:i};qa(new sE(this.editor,l,c,a=>{this.updateGripper(t,a.x,a.y)}))}K0(this.editor,t,i)}else Bh(this.editor)}}function J0(n){n.addCustom("table-mouse-event-handler",t=>new cE(t))}const X0=y("table-insert-column");function t5(n,t,e){const o=$t(t),r=et.fromTable(o),i=r.colCount;d(X0,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],w=C[e];if(e===0||e===C.length||v!==w){const E=Cn(n.doc);C.splice(e,0,E)}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(X0,typeof v=="number"&&v>1,`no colSpan for containerId ${m}, ${v}`),c[C]=v+1});const a=c.colsWidth.concat();a.splice(e,0,mc);const h=et.virtualCellContainersGridToChildren(s),f={...c,cols:c.cols+1,children:h,colsWidth:a};Go(f),n.updateBlockData(t,f)}const gc=y("table-insert-row");function e5(n,t,e){const o=$t(t),r=et.fromTable(o),i=r.rowCount;d(gc,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(gc,C||v,"no top and bottom cell"),e===0||e===r.rowCount||C!==v){const w=Cn(n.doc);c.push(w)}else d(gc,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(gc,typeof v=="number"&&v>1,`no rowSpan for containerId ${m}, ${v}`),a[C]=v+1});const h=et.virtualCellContainersGridToChildren(s),f={...a,rows:a.rows+1,children:h};Go(f),n.updateBlockData(t,f)}const Eh=y("paste-table-in-table-block");function aE(n,t,e,o){let r=et.fromBlock(e);const i=t.blocks.root[0];d(Eh,i,"no table data"),d(Eh,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,h=l.col,f=l.row,m=h+c,C=f+a,v=[];for(let w=h;w<m&&w<r.colCount;w++)for(let E=f;E<C&&E<r.rowCount;E++){const L=r.getCell({col:w,row:E});L.virtual?L.virtual&&v.push({col:w,row:E}):(L.colSpan>1||L.rowSpan>1)&&v.push({col:w,row:E})}n.undoManager.runInGroup(()=>{if(v.forEach(x=>{const O=et.fromBlock(e).getCell(x);(O.colSpan>1||O.rowSpan>1)&&ah(n,e,x)}),m>r.colCount)for(let x=r.colCount;x<m;x++)t5(n,e,x);if(C>r.rowCount)for(let x=r.rowCount;x<C;x++)e5(n,e,x);r=et.fromBlock(e);const w=new rh(s);let E;for(let x=0;x<w.colCount;x++)for(let O=0;O<w.rowCount;O++){const A=w.getCell({col:x,row:O});if(!A.virtual){const P=Zd(n.editorBlocks,t,A.containerId),V=h+x,nt=f+O,ot={col:V,row:nt},ut=r.getCellContainer(ot);Cp(n,ut,P),E=ut}}d(Eh,E,"no last container");const L=Gt(E);n.selection.selectBlock(L,Z(n,L))})}const n5=y("paste-in-table-block");class dE{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=j(r);if(Ct(i)||!hd(t,i))return!1;const s=z(i);if(d(n5,s,"no parent block"),!jt(s)||e.blocks.root.length!==1||e.blocks.root[0].type!=="table")return!1;n5.debug("paste child table in table");const a=et.fromBlock(s).getCellByContainerId(U(i)).cell;return aE(t,e,s,a),!0}}function o5(n){n.addCustom("table-block-paste-event",t=>new dE(t))}const Ih=y("table-select-columns");function uE(n,t,e,o,r){d(Ih,jt(t),"is not a table block");const i=et.fromBlock(t);d(Ih,e>=0&&e<i.colCount,"invalid from"),d(Ih,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=bt(t,s.containerId,{colIndex:e,rowIndex:0}),a=bt(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 xh=y("table-select-columns");function hE(n,t,e,o,r){d(xh,jt(t),"is not a table block");const i=et.fromBlock(t);d(xh,e>=0&&e<i.rowCount,"invalid from"),d(xh,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=bt(t,s.containerId,{rowIndex:e,colIndex:0}),a=bt(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 cF="",r5=y("get-toolbar-reference-client");function fE(n,t){const e=n.selection.range;if(!e.isSimple()){d(r5,e.start.blockId===e.end.blockId,"invalid selection range");const s=n.getBlockById(e.start.blockId);d(r5,ct(n,s),"not a complex block");const l=kt(n,s);if(l.getTextToolbarReferenceClient){const c=l.getTextToolbarReferenceClient(n,s);if(c)return c}}const o=e.isReverse()?t.start:t.end,r=Vt(n,{anchor:o,focus:o}),i=Oo(n,t.block,r);if(i.length!==0)return i[0]}function mE(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 pc(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=ja.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=pc(r),mE(s))}),e}function Cc(n){return n.getCustom("toolbar-handler")}const aF="";class gE{constructor(){u(this,"linkPopup",null);u(this,"form",{});u(this,"onFinished",null);u(this,"onClose",null);u(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{}});u(this,"handleClose",()=>{var t;(t=this.onClose)==null||t.call(this),this._destroy()});u(this,"onShow",()=>{setTimeout(()=>{var t;(t=this.form.linkText)==null||t.getField().focus()},400)});u(this,"onChange",()=>{var e;const t=(e=this.linkPopup)==null?void 0:e.content.querySelector(".submit-button");t.disabled=!1});u(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()}});u(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(S.t("link.urlPlaceholder")),new Error(S.t("link.urlPlaceholder"))}editLink(t){var h,f;const{target:e,linkText:o,linkUrl:r,onFinished:i,onClose:s,placement:l="bottom-start"}=t;this.linkPopup=new ic(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=(h=this.linkPopup)==null?void 0:h.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=th(o,{label:S.t("link.textLabel"),required:!1,placeholder:S.t("link.textPlaceholder"),defaultValue:t,onChange:this.onChange,onKeyDown:this.handleTextKeyboard}),this.form.linkUrl=th(o,{className:"link-popup-gap",label:S.t("link.urlLabel"),required:!0,placeholder:S.t("link.urlPlaceholder"),defaultValue:e,onChange:this.onChange,onKeyDown:this.handleUrlKeyboard});const r=b("div",["link-popup-footer"],o);b("button",["cancel-button"],r,S.t("link.cancelText"));const i=b("button",["submit-button"],r,S.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 bc(n,t){n.addCustom("link-editor",()=>new gE).editLink(t)}const pE=y("link-popup");function CE(n){return lt(n,"link")}function vc(n){var t,e;return(e=(t=n.getAttribute("link"))!=null?t:n.textContent)!=null?e:""}function bE(n,t,e){var r,i,s,l;if(n.isBlockWritable(t)&&e&&Re(e)){const c=e,a=(i=(r=n.editorBoxes.getBoxClass(xi(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&&H(n,t)&&CE(e)?[{id:"link-text",name:vc(e),element:b("span",["link-href-button"],null,vc(e))},{id:"edit-link",name:"Edit",icon:Ju},{id:"remove-link",name:"Remove link",icon:fw}]:Gm(n,t,"hovering-toolbar")}function vE(n,t,e){var c;const o=Br(t,e);n.selection.selectBlock(t,o.start,o.end);const r=(c=e.textContent)!=null?c:"",i=vc(e);bc(n,{target:e,linkText:r,linkUrl:i,onFinished:(a,h)=>{try{const f=n.getBlockText(t),m=Ld(f,o.start,o.end-o.start),C=Ir(m,o.start,a,{link:h});n.setBlockText(t,C),n.selection.selectBlock(t,o.start+a.length),n.focus()}catch(f){pE.error(f)}},onClose:()=>{n.selection.selectBlock(t,o.end),n.focus()}})}function kE(n,t,e){const o=Br(t,e),r=n.getBlockText(t),i=vc(e),s=xr(o.start,o.end-o.start,r,"link",i);n.setBlockText(t,s),n.selection.selectBlock(t,o.end)}function yE(n,t,e,o){var s,l,c;if(e){if(n.isBlockWritable(t)&&Re(e)){const h=e,f=(l=(s=n.editorBoxes.getBoxClass(xi(h))).getBoxProperties)==null?void 0:l.call(s,n,h);if(f!=null&&f.boxCommands){f.boxCommands["hovering-toolbar"].executeCommand(n,t,h,o);return}return}const a=Cc(n);a.disableTextToolbar(),a.hide(),setTimeout(()=>{a.enableTextToolbar()},1e4),o.id==="edit-link"?vE(n,t,e):o.id==="remove-link"&&kE(n,t,e);return}const r=Wm(n,t);if(!r)return;const i=(c=r.blockCommands)==null?void 0:c["hovering-toolbar"];!i||i.executeCommand(n,t,o)}const wE=[zu,Uu,Vu,qu,Wu,Gu,Zu,Yu];class BE{constructor(t){u(this,"id","BlockTurnIntoCommandProvider");this.editor=t}getHeadingIndex(){return 6}getAvailableCommands(t,e,o){if(H(t,e)){const r=G(e),i=it(e),s=Ge(t,e),c=t.getBlockData(e).heading,a=[];for(let f=0;f<this.getHeadingIndex();f++)a.push({id:`heading-${f+1}`,name:S.t("commands.heading",{name:`${f+1}`}),icon:wE[f],states:c===f+1?["checked"]:[],value:`${f+1}`});return[{id:"turn-into",name:"",blockId:r,blockType:i,blockKind:s,element: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||oc,m;return m.innerHTML=oc,m},groupIndex:200,dropdown:!0,manualShowChildren:!0,childrenPlacement:"bottom-start",defaultCheckedChildren:["text"],children:[{id:"text",name:S.t("commands.text"),icon:oc,states:c?[]:["checked"]},...a],childrenType:"menu"}]}return[]}applyHeadingStyle(t,e,o){t.updateBlockData(e,{heading:o})}executeCommand(t,e,o,r){if(H(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}}const kc=y("list-block");function at(n){return it(n)==="list"}function Ht(n){d(kc,at(n),"not a list block")}function je(n){Ht(n);const t=n.getAttribute("data-list-type");return d(kc,t,"no list type"),t}function yc(n){return at(n)&&je(n)==="text-only"}function Se(n){var t,e;return Ht(n),(e=Number.parseInt((t=n.getAttribute("data-list-start"))!=null?t:"1",10))!=null?e:1}function Te(n){var t,e;return Ht(n),(e=Number.parseInt((t=n.getAttribute("data-list-level"))!=null?t:"1",10))!=null?e:1}function Qo(n){Ht(n);const t=n.getAttribute("data-list-group-id");return d(kc,t,"no group id"),t}function mo(n){var i,s,l,c,a;Ht(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(kc,r,"no group id"),{type:t,start:e,level:o,groupId:r}}function wc(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 Wn(n){Ht(n);const{level:t,groupId:e,type:o}=mo(n);let r=gt(n);for(;r;){if(!at(r))return null;const{level:i,groupId:s,type:l}=mo(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 Ko(n){Ht(n);const{level:t,groupId:e,type:o}=mo(n);let r=ht(n);for(;r;){if(at(r)){const{level:i,groupId:s,type:l}=mo(r);if(t===i&&e===s&&(l==="text-only"||o==="text-only"||o===l))return r;if(i<t)return null}r=ht(r)}return null}function i5(n){Ht(n);const t=[];let e=Wn(n);for(;e;)t.unshift(e),e=Wn(e);return t}function Bc(n){Ht(n);const t=[];let e=Ko(n);for(;e;)t.push(e),e=Ko(e);return t}function us(n){Ht(n);let t=Wn(n);for(;t;){const e=Wn(t);if(!e)return t;t=e}return n}function EE(n){Ht(n);let t=Ko(n);for(;t;){const e=Ko(t);if(!e)return t;t=e}return null}function IE(n,t){const e=i5(n),o=Bc(n);return t.withSelf?[...e,n,...o]:[...e,...o]}function Ec(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 Sh(n,t,e,o){const r=IE(t,{withSelf:!0});r.length!==0&&Ec(n,r,e,o)}function xE(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 SE="abcdefghijklmnopqrstuvwxyz";function s5(n){if(n<=0)return`${n}`;const t=(n-1)%26,e=Math.floor((n-1)/26),o=SE[t];return e?s5(e)+o:o}function TE(n){return`${n}`}const l5=[TE,s5,xE];function DE(n,t){const e=l5[(n-1)%l5.length];return e(t)}function LE(n){return["\u2022","\u25E6","\u25AA"][(n-1)%3]}class Jo{constructor(t,e,o){u(this,"listStart");u(this,"listBrother",null);this.editor=t,this.options=o;const r=us(e),i=Se(r);this.listStart=i,this.listBrother=r,o!=null&&o.resetStart&&(this.listStart=1)}fix(){!this.listBrother||Sh(this.editor,this.listBrother,this.listStart,this.options)}}function ME(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 at(o)?o:null}o=gt(o)}return null}function c5(n,t){const e=n.getAttribute("data-style-heading"),o=ME(n,e);if(o)return o;const r=gt(n);if(r&&at(r)&&je(r)===t)return r;const i=ht(n);return i&&at(i)&&je(i)===t?i:null}function RE(n,t,e){var E,L,x;const o=(E=e.data)!=null?E:{},r=1,i=(L=o.listType)!=null?L:"ordered";if(i==="text-only")return null;const s=n.getBlockData(t);let l=(x=s.text)!=null?x:[];const c=n.selection.range.focus;if(!c.isSimple())return null;let h=wt(l);const f=c.offset;f<=ce(l)&&(l=fe(l,f).right,h=h.substring(0,f));let m=1;i==="ordered"&&(m=Number.parseInt(h,10)||1);let C=N();const v=c5(t,i);if(v){if(K(t)>K(v))m=Se(v)+1;else{const O=Se(v);O>1&&(m=O-1)}C=Qo(v)}const w={id:N(),type:"list",level:r,start:m,groupId:C,ordered:!1,text:l};return s.quoted&&(w.quoted=!0),s.heading&&(w.heading=s.heading),i==="ordered"?w.ordered=!0:(i==="checked"||i==="unchecked")&&(w.checkbox=i),{blockData:w,onConverted:(O,A)=>{new Jo(O,A).fix()}}}const OE=8,Mt=y("list-block");class Ic{constructor(t,e){u(this,"listStart",0);u(this,"listBrother",null);if(this.editor=t,yc(e))return;const o=us(e),r=Se(o);this.listStart=r,o===e?this.listBrother=Ko(o):this.listBrother=o}fix(){!this.listBrother||Sh(this.editor,this.listBrother,this.listStart)}}function AE(n,t,e){n.getBlockData(t).quoted&&(e.quoted=!0)}function Th(n,t,e,o){if(Mt.debug("drag a block on a list block"),!H(n,t))return!1;d(Mt,at(e),"target is not a list block");const{type:r,start:i,level:s,groupId:l}=mo(e),c=o==="after"?i+1:i,a=n.getBlockData(t),h={id:N(),type:"list",groupId:l,level:s,start:c,text:a.text,...wc(r)};AE(n,e,h);let f=K(e);const m=j(e);o==="after"&&(f+=1);let C=null;at(t)&&(C=new Ic(n,t));const v=n.insertBlock(U(m),f,h,Tl(h.id,0));return n.deleteBlock(t),new Jo(n,v).fix(),C==null||C.fix(),!0}function _E(n,t,e,o){if(Mt.debug("drag a list between text blocks"),o==="after"){const a=ht(e);if(a&&at(a))return Th(n,t,a,"before")}if(o==="before"){const a=gt(e);if(a&&at(a))return Th(n,t,a,"after")}const i={...n.getBlockData(t),groupId:N(),start:1,level:1};let s=K(e);const l=j(e);o==="after"&&(s+=1),n.insertBlock(U(l),s,i,Tl(i.id,0));const c=new Ic(n,t);return n.deleteBlock(t),c.fix(),!0}function NE(n,t,e,o,r){if(sl(e))return!1;const{blockId:i}=e,s=n.getBlockById(i);d(Mt,s,"no dragged block");const{isSourceBlock:l,targetBlock:c}=r;return!l&&c?(d(Mt,t===c,"block !== target block"),d(Mt,at(c),"target is not a list block"),Th(n,s,c,o)):_E(n,s,c,o)}function a5(n){return n.textOnly?"text-only":n.checkbox?n.checkbox:n.ordered?"ordered":"unordered"}function PE(n){var e,o;if(n.checkbox||n.textOnly)return"";const t=(e=n.level)!=null?e:1;return n.ordered?`${DE(t,(o=n.start)!=null?o:1)}.`:LE(t)}const $E=`<?xml version="1.0" ?>
|
|
335
335
|
<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">
|
|
336
336
|
<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>
|
|
337
337
|
</svg>
|
|
@@ -352,18 +352,18 @@ xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
|
|
|
352
352
|
<path d="M9.99978 5.99611L14.5 1.49609" stroke="currentColor" stroke-width="2"/>
|
|
353
353
|
<path d="M1 10.0039H5.99738L5.99608 15" stroke="currentColor" stroke-width="2"/>
|
|
354
354
|
<path d="M14.9971 5.99611H9.99969L10.001 1" stroke="currentColor" stroke-width="2"/>
|
|
355
|
-
</svg>`;async function YE(n,t,e){const o=At(t),r=o.querySelector('[data-button-id="mindmap-fullscreen"]');d(Mt,r,"no full screen button");const i=()=>{setTimeout(()=>{e.toMindmap(n,t,{},{reset:!0,mindmapTools:e})},300)},s=()=>{F(o,"fullscreen"),r.innerHTML=u5,o0(r,"Full screen",n.clientId),f5(t)&&setTimeout(()=>{i()},300)};if(document.fullscreenElement===o){try{await h5()}catch(l){Mt.error(l)}s()}else{try{M(o,"fullscreen"),await WE(o),i()}catch(l){Mt.error(l)}r.innerHTML=ZE,o0(r,S.t("mindmap.exitFullscreen"),n.clientId)}o.onfullscreenchange=()=>{document.fullscreenElement||s()}}function Lh(n,t,e,o,r){if(t.querySelector(`[data-button-id="${e}"]`))return null;const s=Vn(e,o,r,[],n.clientId);return M(s,"mindmap-button"),t.appendChild(s),s}function Mh(n,t){return n.querySelector(`[data-button-id="${t}"]`)}function QE(n){return Mh(n,"mindmap-fullscreen")}function KE(n){return Mh(n,"mindmap-fit")}function JE(n){return Mh(n,"mindmap-close")}function XE(n,t,e,o){const r=Lh(n,t,"mindmap-close",S.t("mindmap.close"),VE);!r||n.domEvents.addEventListener(r,"click",()=>{o.closeMindmap(n,e)})}function tI(n,t,e,o){const r=Lh(n,t,"mindmap-fit",S.t("mindmap.autoFit"),qE);!r||n.domEvents.addEventListener(r,"click",()=>{o.fitMindmap(n,e)})}function eI(n,t,e,o){if(navigator.userAgent.includes("Mobile")&&!navigator.userAgent.includes("iPad"))return;const i=Lh(n,t,"mindmap-fullscreen",S.t("mindmap.fullScreen"),u5);!i||n.domEvents.addEventListener(i,"click",()=>{YE(n,e,o)})}function nI(n,t){const e=al(t);if(!e)return;const o=KE(e);o&&(o.remove(),n.domEvents.removeAllListeners(o));const r=JE(e);r&&(r.remove(),n.domEvents.removeAllListeners(r));const i=QE(e);i&&(i.remove(),n.domEvents.removeAllListeners(i))}const qr=new Map;function Rh(n,t,e){const o=(s,l)=>{s.forEach(c=>{l?M(c.block,"to-mindmap-highlight"):F(c.block,"to-mindmap-highlight"),o(c.children,l)})},r=d5(n,t);if(r.length===0)return;const i=r[0].block;if(e){const s=qr.get(i);s&&(s.forEach(l=>l.cancel()),qr.delete(i)),o(r,!0)}else{const s=setTimeout(()=>{o(r,!1),qr.delete(i)},300),l=()=>{clearTimeout(s),qr.delete(i)},c=qr.get(i);c?c.push({cancel:l}):qr.set(i,[{cancel:l}])}}const{Markmap:oI}=S9;function rI(n,t){Ht(t);const e=d5(n,t),o=e[0].block,r=a=>({t:"text",v:rt(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 h=a[a.length-1];return h.children&&h.children.length>0?l(h.children):h},c=l(e);return{root:i,block:o,nodes:e,last:c}}function Oh(n,t,e,o){const{root:r,block:i,last:s}=rI(n,t);o.selectBlock&&n.selection.selectBlock(i,0,0),Rh(n,i,!1),o.saveData&&n.updateBlockData(i,{viewAsMindmap:!0});const l=At(i);let c=l.querySelector(".editor-mindmap-svg");if(o.reset&&(c&&c.remove(),c=null),c)c.innerHTML="";else{const D="http://www.w3.org/2000/svg",x=l.getBoundingClientRect(),A=document.fullscreenElement===l,O=A?`${x.width}`:`${t.getBoundingClientRect().width}`,P=A?`${x.height}`:"600",V=document.createElementNS(D,"svg");V.setAttributeNS(null,"viewBox",`0 0 ${O} ${P}`),V.setAttributeNS(null,"width","100%"),V.setAttributeNS(null,"height",P),V.style.display="block",V.style.width="100%",V.style.height=`${P}px`,V.classList.add("editor-mindmap-svg"),l.appendChild(V),c=V}const a=i,f=`editor-mindmap-root-${G(i)}`;M(a,"editor-in-mindmap-first",f,"readonly"),a.contentEditable="false";const m=ht(i);m&&K(m)<=K(s.block)&&GE(m,s.block,["block-hidden",f]);const C=(D,x)=>{if(x.length>0){const A=x[0].parentElement;A&&(A.style.width="100vw",A.style.maxWidth="200px")}x.forEach(A=>{M(A,"editor-mindmap-node")})},v=new oI(c,{...e,autoFit:!0});v.viewHooks.transformHtml.tap(C),v.setData(r),v.fit();const w=At(i);let E=w.querySelector(".mindmap-toolbar");E||(E=b("div",["mindmap-toolbar"],w)),tI(n,E,a,o.mindmapTools),eI(n,E,a,o.mindmapTools),XE(n,E,a,o.mindmapTools),n.domEvents.addEventListener(c,"click",()=>{n.selection.selectBlock(i,0),n.input.focus()}),a.mindMap=v}function iI(n){const t=n.classList,e="editor-mindmap-root-";return Array.from(t).find(r=>{if(r.startsWith(e))return r})}async function m5(n,t){const e=iI(t);if(!e)return;n.updateBlockData(t,{viewAsMindmap:null});const o=j(t);Ot(o).forEach(l=>{lt(l,e)&&F(l,e,"editor-in-mindmap-first","block-hidden")});const i=At(t);document.fullscreenElement===i&&await h5();const s=i.querySelector(".editor-mindmap-svg");d(Mt,s,"no mindmap svg"),s.remove(),n.domEvents.removeAllListeners(s),t.contentEditable="inherit",nI(n,t),n.selection.selectBlock(t,0)}function sI(n,t){const e=t.mindMap;e&&e.fit()}const g5={toMindmap:Oh,closeMindmap:m5,fitMindmap:sI};function p5(n){let t=ht(n);if(!t)return null;const e=Ko(n);for(;t!==e;){if(d(Mt,t,"no next block"),at(t))return Te(t)>Te(n)?t:null;if(t=ht(t),!t)return null}return null}function Ah(n){const t=[];let e=p5(n);if(!e)return t;for(;e;){const o=Ko(e);t.push({block:e,children:Ah(e)}),e=o}return t}function lI(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 cI(n,t){return Te(t)!==1}function C5(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&&C5(n,o.children,r.groupId)})}function b5(n,t){if(!cI(n,t))return!1;const e=Te(t);if(e===1)return!1;let o=N(),r=1,i=je(t);const s=e-1,l=Dh(t);l&&(o=Qo(l),r=Se(l)+1,i!=="text-only"&&(i=je(l)));const c=Ah(t),a=n.getBlockData(t),h={...a,groupId:o,level:s,start:r,...wc(i)};n.updateBlockData(t,h),n.doc.beginBatchUpdate(),C5(n,c,a.groupId),n.doc.endBatchUpdate(),new Jo(n,t).fix();const m=p5(t);return m&&new Jo(n,m,{resetStart:!0,resetGroupId:!0}).fix(),!0}function hs(n,t){Ht(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 Ic(n,t),i=j(t),s=K(t);n.deleteBlock(t);const l=Tl(o.id,0);n.insertBlock(U(i),s,o,l),r.fix()}function aI(n){if(!n.selection.range.isCollapsed())return!1;const t=n.selection.focusedBlock;if(!at(t))return!1;const e=n.selection.range.focus;return!e.isSimple()||e.offset!==0?!1:Te(t)===1?(hs(n,t),!0):(b5(n,t),!0)}const dI=y("list-block");function uI(n,t,e){d(dI,at(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 hI(n){if(Ht(n),!yc(n))return n;let t=Wn(n);for(;t;){if(!yc(t))return t;t=Wn(t)}return null}function fI(n,t,e,o){const r=new Jo(n,o),i=Se(o)+1;Dr(n,t,e,{forceInsertAfter:!0,newBlockData:uI(n,o,{start:i})}),r.fix()}function mI(n){var s;if(n.selection.range.isCollapsed()){const l=n.selection.focusedBlock;if(at(l)&&Z(n,l)===0)return hs(n,l),!0}n.clearSelectedContents();const t=n.selection.focusedBlock;if(!at(t))return!1;const e=n.selection.range.focus;if(!e.isSimple())return!1;const o=e.offset,i=(s=o===Z(n,t)?hI(t):t)!=null?s:t;return fI(n,t,o,i),!0}function v5(n){d(Mt,at(n),"not a list block");const{level:t}=mo(n);let e=gt(n);for(;e;){if(at(e)){const{level:o}=mo(e);if(t===o)return e;if(o<t)return null}e=gt(e)}return null}function gI(n,t){return Ht(t),v5(t)?Te(t)<OE:!1}function pI(n,t,e){let o=gt(t);d(Mt,o,"no prev brother");const r=Te(e);for(;o;){if(o===e)return null;if(at(o)&&Te(o)===r+1)return o;o=gt(o)}return null}function CI(n,t){if(!gI(n,t))return!1;Ht(t);const e=v5(t);d(Mt,e,"no list prev brother");const o=e,r=pI(n,t,o),i=Te(o)+1;let s=N(),l=1,c=je(t);r&&(s=Qo(r),l=Se(r)+1,c=je(r));const a=Ah(t),f={...n.getBlockData(t),groupId:s,level:i,start:l,...wc(c)};return n.updateBlockData(t,f),n.doc.beginBatchUpdate(),lI(a).forEach(C=>{const v=n.getBlockData(C);n.updateBlockData(C,{...v,level:v.level+1})}),n.doc.endBatchUpdate(),!0}function bI(n,t){return CI(n,t)}function vI(n,t){return b5(n,t)}function kI(n){const t=n.selection.range.getSelectedBlocks();if(t.length>1)return!0;const e=t[0].block;if(!at(e))return!1;const o=new Ic(n,e);return bI(n,e)&&(o.fix(),new Jo(n,e).fix()),!0}function yI(n){const t=n.selection.range.getSelectedBlocks();if(t.length>1)return!0;const e=t[0].block;return at(e)?(vI(n,e),!0):!1}class wI{constructor(t){this.editor=t}handleBeforeKeyDown(t,e){const o=t.selection.range.getSelectedBlocks();if(o.length===0||!o.some(i=>at(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||!at(e.block)||An(t,"Shift+Enter")?!1:this.editor.undoManager.runInGroup(()=>mI(this.editor))}handleBackspace(){return this.editor.undoManager.runInGroup(()=>aI(this.editor))}handleTab(t){return An(t,"Shift+Tab")?this.editor.undoManager.runInGroup(()=>yI(this.editor)):this.editor.undoManager.runInGroup(()=>kI(this.editor))}}class BI{constructor(t){u(this,"effectedBlockIds",new Map);u(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;at(i)&&e.add(i)});const o=new Map;Array.from(e.values()).forEach(r=>{var c;const i=us(r),{start:s}=mo(i);o.set(G(i),s);const l=(c=EE(r))!=null?c:r;o.set(G(l),s)}),this.effectedBlockIds=o});u(this,"handleAfterClearSelection",()=>{Array.from(this.effectedBlockIds.entries()).forEach(([t,e])=>{const o=this.editor.findBlockById(t);!o||Sh(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 EI=y("customize-list-start-menu");class II{constructor(t){u(this,"popup");u(this,"block",null);u(this,"show",(t,e)=>{const o=e.querySelector("div.list-container");d(EI,o,"list-block mark does not exist"),this.block=e,this.popup.manualShow(o,{theme:"light"})});u(this,"createDialogContent",()=>{const t=b("div",["customize-start-panel"],null);b("span",["customize-start-panel-title"],t,S.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,S.t("list.confirm"));return this.editor.domEvents.addEventListener(t,"keydown",this.handleKeydown),this.editor.domEvents.addEventListener(o,"click",this.handleOk),t});u(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=Se(t);!o||!r||requestAnimationFrame(()=>{r.focus(),r.value=String(i)})});u(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(()=>{Ec(this.editor,[o,...Bc(o)],r,{resetGroupId:!0})}),this.popup.close())});u(this,"handleKeydown",(t,e)=>{const o=e;o.isComposing||o.key==="Escape"&&this.popup.close()});this.editor=t,this.popup=new ic(this.createDialogContent()),this.popup.on("show",this.handleDialogShow)}destroy(){this.popup.destroy()}}function xI(n,t){return Qo(n)===Qo(t)}function SI(n,t){const e=Wn(t),o=gt(t);return!e&&!o||!o||!at(o)?!1:at(o)&&xI(o,t)?Se(o)!==Se(t)-1:!0}function TI(n,t){return!!Wn(t)}function DI(n,t){Ht(t);const e=[{id:"continue-numbering",name:S.t("list.continueList")},{id:"start-new-list",name:S.t("list.restartList")},{id:"set-numbering-value",name:S.t("list.changeNumber")}];return SI(n,t)||(e[0].states=["disabled"]),TI(n,t)||(e[1].states=["disabled"]),e}function LI(n,t,e){var o,r;if(Ht(t),e.id==="continue-numbering"){const i=gt(t),s=Wn(t)||(i&&at(i)?i:null);s&&Ec(n,[t,...Bc(t)],Se(s)+1,{resetGroupId:!0,groupId:Qo(s)})}if(e.id==="start-new-list"&&n.undoManager.runInGroup(()=>{Ec(n,[t,...Bc(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 II(n)).show(n,t)}}class MI{constructor(t){u(this,"menu");u(this,"handleClick",(t,e)=>{const o=wi(e,"div.list-container");if(o&&this.editor.isWritable()){const r=z(o);d(Mt,r,"no parent block"),Ht(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)}});u(this,"handleMenuClose",()=>{var e;const t=(e=this.menu.tippyInstance)==null?void 0:e.reference;t&&this.activeList(t,!1)});u(this,"handleMenuClick",(t,e)=>{var r;const o=(r=this.menu.tippyInstance)==null?void 0:r.reference;if(o){const i=z(o);i&&LI(this.editor,i,e)}});this.editor=t,this.editor.addListener("click",this.handleClick),this.menu=new Wo([]),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 DI(this.editor,t)}activeList(t,e){const o=z(t);!o||(e?(M(t,"active"),M(o,"active")):(F(t,"active"),F(o,"active")))}}class RI{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(!at(r)||!f5(r))return!1;if(e.key==="ArrowUp"||e.key==="ArrowLeft"){const i=gr(r);return i&&t.selection.selectBlock(i,Z(t,i)),!0}if(e.key==="ArrowDown"||e.key==="ArrowRight"){const i=pr(r);return i&&t.selection.selectBlock(i,0),!0}return(e.key==="Delete"||e.key==="Backspace"||e.key==="Escape")&&m5(t,r),!0}}function OI(n,t,e,o,r){wu(n,"list-block-init",()=>{setTimeout(()=>{n.input.addHandler(new RI(n)),n.input.addHandler(new wI(n)),n.addCustom("list-clear-selection-handler",()=>new BI(n)),n.addCustom("list-marker-menu",()=>new MI(n))})});const i=Ai.createBlockContent(n,t,e,o,r),s=r,{level:l,start:c,groupId:a}=s,h=a5(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",h);const f=FE(s);return o.insertBefore(f,i),s.viewAsMindmap&&setTimeout(()=>{const m=n.getBlockById(r.id);m&&Oh(n,m,{},{mindmapTools:g5,saveData:!1})}),i}const AI=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
355
|
+
</svg>`;async function YE(n,t,e){const o=At(t),r=o.querySelector('[data-button-id="mindmap-fullscreen"]');d(Mt,r,"no full screen button");const i=()=>{setTimeout(()=>{e.toMindmap(n,t,{},{reset:!0,mindmapTools:e})},300)},s=()=>{F(o,"fullscreen"),r.innerHTML=u5,o0(r,"Full screen",n.clientId),f5(t)&&setTimeout(()=>{i()},300)};if(document.fullscreenElement===o){try{await h5()}catch(l){Mt.error(l)}s()}else{try{M(o,"fullscreen"),await WE(o),i()}catch(l){Mt.error(l)}r.innerHTML=ZE,o0(r,S.t("mindmap.exitFullscreen"),n.clientId)}o.onfullscreenchange=()=>{document.fullscreenElement||s()}}function Lh(n,t,e,o,r){if(t.querySelector(`[data-button-id="${e}"]`))return null;const s=Vn(e,o,r,[],n.clientId);return M(s,"mindmap-button"),t.appendChild(s),s}function Mh(n,t){return n.querySelector(`[data-button-id="${t}"]`)}function QE(n){return Mh(n,"mindmap-fullscreen")}function KE(n){return Mh(n,"mindmap-fit")}function JE(n){return Mh(n,"mindmap-close")}function XE(n,t,e,o){const r=Lh(n,t,"mindmap-close",S.t("mindmap.close"),VE);!r||n.domEvents.addEventListener(r,"click",()=>{o.closeMindmap(n,e)})}function tI(n,t,e,o){const r=Lh(n,t,"mindmap-fit",S.t("mindmap.autoFit"),qE);!r||n.domEvents.addEventListener(r,"click",()=>{o.fitMindmap(n,e)})}function eI(n,t,e,o){if(navigator.userAgent.includes("Mobile")&&!navigator.userAgent.includes("iPad"))return;const i=Lh(n,t,"mindmap-fullscreen",S.t("mindmap.fullScreen"),u5);!i||n.domEvents.addEventListener(i,"click",()=>{YE(n,e,o)})}function nI(n,t){const e=al(t);if(!e)return;const o=KE(e);o&&(o.remove(),n.domEvents.removeAllListeners(o));const r=JE(e);r&&(r.remove(),n.domEvents.removeAllListeners(r));const i=QE(e);i&&(i.remove(),n.domEvents.removeAllListeners(i))}const qr=new Map;function Rh(n,t,e){const o=(s,l)=>{s.forEach(c=>{l?M(c.block,"to-mindmap-highlight"):F(c.block,"to-mindmap-highlight"),o(c.children,l)})},r=d5(n,t);if(r.length===0)return;const i=r[0].block;if(e){const s=qr.get(i);s&&(s.forEach(l=>l.cancel()),qr.delete(i)),o(r,!0)}else{const s=setTimeout(()=>{o(r,!1),qr.delete(i)},300),l=()=>{clearTimeout(s),qr.delete(i)},c=qr.get(i);c?c.push({cancel:l}):qr.set(i,[{cancel:l}])}}const{Markmap:oI}=S9;function rI(n,t){Ht(t);const e=d5(n,t),o=e[0].block,r=a=>({t:"text",v:rt(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 h=a[a.length-1];return h.children&&h.children.length>0?l(h.children):h},c=l(e);return{root:i,block:o,nodes:e,last:c}}function Oh(n,t,e,o){const{root:r,block:i,last:s}=rI(n,t);o.selectBlock&&n.selection.selectBlock(i,0,0),Rh(n,i,!1),o.saveData&&n.updateBlockData(i,{viewAsMindmap:!0});const l=At(i);let c=l.querySelector(".editor-mindmap-svg");if(o.reset&&(c&&c.remove(),c=null),c)c.innerHTML="";else{const L="http://www.w3.org/2000/svg",x=l.getBoundingClientRect(),O=document.fullscreenElement===l,A=O?`${x.width}`:`${t.getBoundingClientRect().width}`,P=O?`${x.height}`:"600",V=document.createElementNS(L,"svg");V.setAttributeNS(null,"viewBox",`0 0 ${A} ${P}`),V.setAttributeNS(null,"width","100%"),V.setAttributeNS(null,"height",P),V.style.display="block",V.style.width="100%",V.style.height=`${P}px`,V.classList.add("editor-mindmap-svg"),l.appendChild(V),c=V}const a=i,f=`editor-mindmap-root-${G(i)}`;M(a,"editor-in-mindmap-first",f,"readonly"),a.contentEditable="false";const m=ht(i);m&&K(m)<=K(s.block)&&GE(m,s.block,["block-hidden",f]);const C=(L,x)=>{if(x.length>0){const O=x[0].parentElement;O&&(O.style.width="100vw",O.style.maxWidth="200px")}x.forEach(O=>{M(O,"editor-mindmap-node")})},v=new oI(c,{...e,autoFit:!0});v.viewHooks.transformHtml.tap(C),v.setData(r),v.fit();const w=At(i);let E=w.querySelector(".mindmap-toolbar");E||(E=b("div",["mindmap-toolbar"],w)),tI(n,E,a,o.mindmapTools),eI(n,E,a,o.mindmapTools),XE(n,E,a,o.mindmapTools),n.domEvents.addEventListener(c,"click",()=>{n.selection.selectBlock(i,0),n.input.focus()}),a.mindMap=v}function iI(n){const t=n.classList,e="editor-mindmap-root-";return Array.from(t).find(r=>{if(r.startsWith(e))return r})}async function m5(n,t){const e=iI(t);if(!e)return;n.updateBlockData(t,{viewAsMindmap:null});const o=j(t);Ot(o).forEach(l=>{lt(l,e)&&F(l,e,"editor-in-mindmap-first","block-hidden")});const i=At(t);document.fullscreenElement===i&&await h5();const s=i.querySelector(".editor-mindmap-svg");d(Mt,s,"no mindmap svg"),s.remove(),n.domEvents.removeAllListeners(s),t.contentEditable="inherit",nI(n,t),n.selection.selectBlock(t,0)}function sI(n,t){const e=t.mindMap;e&&e.fit()}const g5={toMindmap:Oh,closeMindmap:m5,fitMindmap:sI};function p5(n){let t=ht(n);if(!t)return null;const e=Ko(n);for(;t!==e;){if(d(Mt,t,"no next block"),at(t))return Te(t)>Te(n)?t:null;if(t=ht(t),!t)return null}return null}function Ah(n){const t=[];let e=p5(n);if(!e)return t;for(;e;){const o=Ko(e);t.push({block:e,children:Ah(e)}),e=o}return t}function lI(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 cI(n,t){return Te(t)!==1}function C5(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&&C5(n,o.children,r.groupId)})}function b5(n,t){if(!cI(n,t))return!1;const e=Te(t);if(e===1)return!1;let o=N(),r=1,i=je(t);const s=e-1,l=Dh(t);l&&(o=Qo(l),r=Se(l)+1,i!=="text-only"&&(i=je(l)));const c=Ah(t),a=n.getBlockData(t),h={...a,groupId:o,level:s,start:r,...wc(i)};n.updateBlockData(t,h),n.doc.beginBatchUpdate(),C5(n,c,a.groupId),n.doc.endBatchUpdate(),new Jo(n,t).fix();const m=p5(t);return m&&new Jo(n,m,{resetStart:!0,resetGroupId:!0}).fix(),!0}function hs(n,t){Ht(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 Ic(n,t),i=j(t),s=K(t);n.deleteBlock(t);const l=Tl(o.id,0);n.insertBlock(U(i),s,o,l),r.fix()}function aI(n){if(!n.selection.range.isCollapsed())return!1;const t=n.selection.focusedBlock;if(!at(t))return!1;const e=n.selection.range.focus;return!e.isSimple()||e.offset!==0?!1:Te(t)===1?(hs(n,t),!0):(b5(n,t),!0)}const dI=y("list-block");function uI(n,t,e){d(dI,at(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 hI(n){if(Ht(n),!yc(n))return n;let t=Wn(n);for(;t;){if(!yc(t))return t;t=Wn(t)}return null}function fI(n,t,e,o){const r=new Jo(n,o),i=Se(o)+1;Dr(n,t,e,{forceInsertAfter:!0,newBlockData:uI(n,o,{start:i})}),r.fix()}function mI(n){var s;if(n.selection.range.isCollapsed()){const l=n.selection.focusedBlock;if(at(l)&&Z(n,l)===0)return hs(n,l),!0}n.clearSelectedContents();const t=n.selection.focusedBlock;if(!at(t))return!1;const e=n.selection.range.focus;if(!e.isSimple())return!1;const o=e.offset,i=(s=o===Z(n,t)?hI(t):t)!=null?s:t;return fI(n,t,o,i),!0}function v5(n){d(Mt,at(n),"not a list block");const{level:t}=mo(n);let e=gt(n);for(;e;){if(at(e)){const{level:o}=mo(e);if(t===o)return e;if(o<t)return null}e=gt(e)}return null}function gI(n,t){return Ht(t),v5(t)?Te(t)<OE:!1}function pI(n,t,e){let o=gt(t);d(Mt,o,"no prev brother");const r=Te(e);for(;o;){if(o===e)return null;if(at(o)&&Te(o)===r+1)return o;o=gt(o)}return null}function CI(n,t){if(!gI(n,t))return!1;Ht(t);const e=v5(t);d(Mt,e,"no list prev brother");const o=e,r=pI(n,t,o),i=Te(o)+1;let s=N(),l=1,c=je(t);r&&(s=Qo(r),l=Se(r)+1,c=je(r));const a=Ah(t),f={...n.getBlockData(t),groupId:s,level:i,start:l,...wc(c)};return n.updateBlockData(t,f),n.doc.beginBatchUpdate(),lI(a).forEach(C=>{const v=n.getBlockData(C);n.updateBlockData(C,{...v,level:v.level+1})}),n.doc.endBatchUpdate(),!0}function bI(n,t){return CI(n,t)}function vI(n,t){return b5(n,t)}function kI(n){const t=n.selection.range.getSelectedBlocks();if(t.length>1)return!0;const e=t[0].block;if(!at(e))return!1;const o=new Ic(n,e);return bI(n,e)&&(o.fix(),new Jo(n,e).fix()),!0}function yI(n){const t=n.selection.range.getSelectedBlocks();if(t.length>1)return!0;const e=t[0].block;return at(e)?(vI(n,e),!0):!1}class wI{constructor(t){this.editor=t}handleBeforeKeyDown(t,e){const o=t.selection.range.getSelectedBlocks();if(o.length===0||!o.some(i=>at(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||!at(e.block)||An(t,"Shift+Enter")?!1:this.editor.undoManager.runInGroup(()=>mI(this.editor))}handleBackspace(){return this.editor.undoManager.runInGroup(()=>aI(this.editor))}handleTab(t){return An(t,"Shift+Tab")?this.editor.undoManager.runInGroup(()=>yI(this.editor)):this.editor.undoManager.runInGroup(()=>kI(this.editor))}}class BI{constructor(t){u(this,"effectedBlockIds",new Map);u(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;at(i)&&e.add(i)});const o=new Map;Array.from(e.values()).forEach(r=>{var c;const i=us(r),{start:s}=mo(i);o.set(G(i),s);const l=(c=EE(r))!=null?c:r;o.set(G(l),s)}),this.effectedBlockIds=o});u(this,"handleAfterClearSelection",()=>{Array.from(this.effectedBlockIds.entries()).forEach(([t,e])=>{const o=this.editor.findBlockById(t);!o||Sh(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 EI=y("customize-list-start-menu");class II{constructor(t){u(this,"popup");u(this,"block",null);u(this,"show",(t,e)=>{const o=e.querySelector("div.list-container");d(EI,o,"list-block mark does not exist"),this.block=e,this.popup.manualShow(o,{theme:"light"})});u(this,"createDialogContent",()=>{const t=b("div",["customize-start-panel"],null);b("span",["customize-start-panel-title"],t,S.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,S.t("list.confirm"));return this.editor.domEvents.addEventListener(t,"keydown",this.handleKeydown),this.editor.domEvents.addEventListener(o,"click",this.handleOk),t});u(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=Se(t);!o||!r||requestAnimationFrame(()=>{r.focus(),r.value=String(i)})});u(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(()=>{Ec(this.editor,[o,...Bc(o)],r,{resetGroupId:!0})}),this.popup.close())});u(this,"handleKeydown",(t,e)=>{const o=e;o.isComposing||o.key==="Escape"&&this.popup.close()});this.editor=t,this.popup=new ic(this.createDialogContent()),this.popup.on("show",this.handleDialogShow)}destroy(){this.popup.destroy()}}function xI(n,t){return Qo(n)===Qo(t)}function SI(n,t){const e=Wn(t),o=gt(t);return!e&&!o||!o||!at(o)?!1:at(o)&&xI(o,t)?Se(o)!==Se(t)-1:!0}function TI(n,t){return!!Wn(t)}function DI(n,t){Ht(t);const e=[{id:"continue-numbering",name:S.t("list.continueList")},{id:"start-new-list",name:S.t("list.restartList")},{id:"set-numbering-value",name:S.t("list.changeNumber")}];return SI(n,t)||(e[0].states=["disabled"]),TI(n,t)||(e[1].states=["disabled"]),e}function LI(n,t,e){var o,r;if(Ht(t),e.id==="continue-numbering"){const i=gt(t),s=Wn(t)||(i&&at(i)?i:null);s&&Ec(n,[t,...Bc(t)],Se(s)+1,{resetGroupId:!0,groupId:Qo(s)})}if(e.id==="start-new-list"&&n.undoManager.runInGroup(()=>{Ec(n,[t,...Bc(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 II(n)).show(n,t)}}class MI{constructor(t){u(this,"menu");u(this,"handleClick",(t,e)=>{const o=wi(e,"div.list-container");if(o&&this.editor.isWritable()){const r=z(o);d(Mt,r,"no parent block"),Ht(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)}});u(this,"handleMenuClose",()=>{var e;const t=(e=this.menu.tippyInstance)==null?void 0:e.reference;t&&this.activeList(t,!1)});u(this,"handleMenuClick",(t,e)=>{var r;const o=(r=this.menu.tippyInstance)==null?void 0:r.reference;if(o){const i=z(o);i&&LI(this.editor,i,e)}});this.editor=t,this.editor.addListener("click",this.handleClick),this.menu=new Wo([]),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 DI(this.editor,t)}activeList(t,e){const o=z(t);!o||(e?(M(t,"active"),M(o,"active")):(F(t,"active"),F(o,"active")))}}class RI{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(!at(r)||!f5(r))return!1;if(e.key==="ArrowUp"||e.key==="ArrowLeft"){const i=gr(r);return i&&t.selection.selectBlock(i,Z(t,i)),!0}if(e.key==="ArrowDown"||e.key==="ArrowRight"){const i=pr(r);return i&&t.selection.selectBlock(i,0),!0}return(e.key==="Delete"||e.key==="Backspace"||e.key==="Escape")&&m5(t,r),!0}}function OI(n,t,e,o,r){wu(n,"list-block-init",()=>{setTimeout(()=>{n.input.addHandler(new RI(n)),n.input.addHandler(new wI(n)),n.addCustom("list-clear-selection-handler",()=>new BI(n)),n.addCustom("list-marker-menu",()=>new MI(n))})});const i=Ai.createBlockContent(n,t,e,o,r),s=r,{level:l,start:c,groupId:a}=s,h=a5(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",h);const f=FE(s);return o.insertBefore(f,i),s.viewAsMindmap&&setTimeout(()=>{const m=n.getBlockById(r.id);m&&Oh(n,m,{},{mindmapTools:g5,saveData:!1})}),i}const AI=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
356
356
|
<path d="M8 8H15" stroke="currentColor" stroke-linecap="square" stroke-linejoin="round"></path>
|
|
357
357
|
<path d="M8 14H15" stroke="currentColor" stroke-linecap="square" stroke-linejoin="round"></path>
|
|
358
358
|
<path d="M8 2H15" stroke="currentColor" stroke-linecap="square" stroke-linejoin="round"></path>
|
|
359
359
|
<path d="M4 8H0C0 8 0.552283 8 1.33333 8M4 14C2 13.1429 3.33333 8 1.33333 8M4 2C2 2.85714 3.33333 8 1.33333 8" stroke="currentColor" stroke-linecap="square"></path>
|
|
360
360
|
</svg>
|
|
361
|
-
`;function _I(n){return Vn("list-to-mindmap",S.t("mindmap.viewAsMindMap"),AI,[],n.clientId)}const dF="";class xc{constructor(t){u(this,"toMindmapButton");u(this,"currentBlock",null);u(this,"handleHoveringBlock",t=>{!this.editor.isWritable()||(t&&at(t)&&je(t)!=="unchecked"&&je(t)!=="checked"?At(t).appendChild(this.toMindmapButton):this.toMindmapButton.remove())});u(this,"handleMouseEnter",()=>{const t=z(this.toMindmapButton);d(Mt,t&&at(t),"no parent list"),Rh(this.editor,t,!0),this.currentBlock=t});u(this,"handleMouseLeave",()=>{this.currentBlock&&(Rh(this.editor,this.currentBlock,!1),this.currentBlock=null)});u(this,"handleClick",()=>{const t=z(this.toMindmapButton);d(Mt,t&&at(t),"no parent list"),Oh(this.editor,t,{},{saveData:!0,selectBlock:!0,mindmapTools:g5})});this.editor=t,_t.get(this.editor).addListener("change",this.handleHoveringBlock),this.toMindmapButton=_I(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(xc)}destroy(){_t.get(this.editor).removeListener("change",this.handleHoveringBlock)}hide(){this.currentBlock&&(this.currentBlock=null),this.toMindmapButton.remove()}}const NI={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"}},PI={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"}};S.mergeLang({"zh-CN":NI,"en-US":PI});const uF="";function $I(n,t,e){var o;t==="beginDrag"&&((o=xc.get(n))==null||o.hide())}function Sc(n){const t=n.getAttribute("block-padding-level");return t?Number(t):null}function jI(n,t){let e;const o=Sc(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 k5(n,t){const e=Sc(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 _h(n){return n.readonly||!n.isWritable()}function HI(n){return n.selection.range.getSelectedBlocks().forEach(e=>{const o=e.block;H(n,o)&&jI(n,o)}),!0}function FI(n){return n.selection.range.getSelectedBlocks().forEach(e=>{const o=e.block;H(n,o)&&k5(n,o)}),!0}function zI(n){return _h(n)?!1:n.undoManager.runInGroup(()=>(HI(n),!0))}function UI(n){return _h(n)?!1:n.undoManager.runInGroup(()=>(FI(n),!0))}function VI(n){if(_h(n))return!1;if(!n.selection.range.isCollapsed())return;const t=n.selection.focusedBlock;if(!H(n,t))return;const e=n.selection.range.focus;if(!(!e.isSimple()||e.offset!==0||!Sc(t)))return k5(n,t),!0}class qI{renderBlock(t,e,o){const{padding:r}=o;return r?{attributes:{"block-padding-level":r}}:{}}}const hF="",WI={Tab:zI,"Shift+Tab":UI,Backspace:VI};function Nh(n,t,e){let o=1,r=1,i=N();if(at(t))o=Te(t);else{const a=Sc(t);a&&(o=a+1),o>8&&(o=8)}const s=c5(t,e);if(s){if(K(t)>K(s))r=Se(s)+1;else{const a=Se(s);a>1&&(r=a-1)}i=Qo(s)}const c={...n.getBlockData(t),level:o,start:r,groupId:i,type:"list",...wc(e)};n.undoManager.runInGroup(()=>{const a=K(t),h=U(j(t));n.deleteBlock(t);const f=n.insertBlock(h,a,c);new Jo(n,f).fix()})}const y5={...Ai,blockType:"list",createBlockContent:OI,convertFrom:RE,handleDrop:NE,notify:$I},Ph=y("paragraph");class GI{constructor(t){u(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":[S.t("commands.unordered"),St.isMac?S.t("commandDesc.mac.unordered"):S.t("commandDesc.window.unordered"),sw],"ordered-list":[S.t("commands.ordered"),St.isMac?S.t("commandDesc.mac.ordered"):S.t("commandDesc.window.ordered"),iw],"check-list":[S.t("commands.check"),void 0,lw],link:[S.t("commands.link"),St.isMac?S.t("commandDesc.mac.link"):S.t("commandDesc.window.link"),p0],quoted:[S.t("commands.quote"),void 0,cw]};if(H(t,e)){const i=G(e),s=it(e),l=Ge(t,e),c=t.getBlockData(e);Object.entries(r).forEach(([a,[h,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:h,desc:f,states:C,icon:m,groupIndex:600})})}return o}convertLink(t,e,o){d(Ph,vr(e.start),""),d(Ph,vr(e.start),"");const r="bottom-start",i=e.start.offset,s=e.end.offset,l=(C,v)=>{t.undoManager.runInGroup(()=>{try{let w=El(t.getBlockText(o),i,s,C);w=wl(i,C.length,w,"link",v),t.setBlockText(o,w),t.selection.selectBlock(o,i+C.length),t.focus()}catch(w){Ph.error(w)}})},c=()=>{t.focus()},a=Oo(t,o,e)[0];if(!a)return;const h=_o(t,o,"link-button-anchor",a),f=t.getBlockText(o),m=Bl(f,i);bc(t,{target:h,linkText:t.getSelectedText(),linkUrl:(m==null?void 0:m.link)||"",onFinished:l,onClose:c,placement:r})}executeCommand(t,e,o,r){var c;if(!H(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?hs(t,e):Nh(t,e,"unordered"),l=!0),i==="ordered-list"&&(s?hs(t,e):Nh(t,e,"ordered"),l=!0),i==="check-list"&&(s?hs(t,e):Nh(t,e,"unchecked"),l=!0),i==="quoted"){const h=t.getBlockData(e).quoted;t.updateBlockData(e,{quoted:h?void 0:!0}),l=!0}if(i==="link"){const a=Cc(t);a.disableTextToolbar(),a.hide(),setTimeout(()=>{a.enableTextToolbar()},1e3),this.convertLink(t,o,e),l=!0}return l}}const ZI={left:es,right:Qu,center:Ku};class YI{constructor(t){u(this,"id","BlockAlignProvider");this.editor=t}applyAlignStyle(t,e,o){Object.keys(ZI).includes(o)?t.updateBlockData(e,{align:o}):t.updateBlockData(e,{align:null})}isChecked(t,e){return t.align===e}getAvailableCommands(t,e,o){const r=G(e),i=it(e),s=Ge(t,e),l=t.getBlockData(e);return[{id:"align",name:"",blockId:r,blockType:i,blockKind:s,groupIndex:700,dropdown:!0,element:a=>{var f;const h=b("span",["toolbar-item-name-container"],null);for(const m of a.children)if((f=m.states)!=null&&f.includes("checked"))return h.innerHTML=m.icon||es,h;return h.innerHTML=es,h},manualShowChildren:!0,childrenPlacement:"bottom-start",defaultCheckedChildren:["align-left"],children:[{id:"align-left",name:S.t("commands.alignLeft"),icon:es,states:this.isChecked(l,"left")?["checked"]:[]},{id:"align-center",name:S.t("commands.alignCenter"),icon:Ku,states:this.isChecked(l,"center")?["checked"]:[]},{id:"align-right",name:S.t("commands.alignRight"),icon:Qu,states:this.isChecked(l,"right")?["checked"]:[]}],childrenType:"menu"}]}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}}const QI=y("toolbar-handler"),KI={id:"",name:"",type:"separator"};class Wr{constructor(t){u(this,"toolbar");u(this,"toolbarType","object");u(this,"mouseDown",!1);u(this,"oldRange",null);u(this,"hoveringBlock",null);u(this,"hoveringTextChild",null);u(this,"_disableTextToolbar",!1);u(this,"handleButtonClick",(t,e)=>{this.toolbarType==="text"?(this.editor.editorCommandProviders.executeCommand(this.editor.selection.range,e,{}),this.showTextToolbar()):this.hoveringBlock&&yE(this.editor,this.hoveringBlock,this.hoveringTextChild,e)});u(this,"handleClose",()=>{this.editor.focus()});u(this,"handleDocumentMouseDown",t=>{t.button===0&&(document.addEventListener("mouseup",this.handleDocumentMouseUp),this.mouseDown=!0)});u(this,"handleDocumentMouseUp",()=>{document.removeEventListener("mouseup",this.handleDocumentMouseUp),this.mouseDown=!1,this.handleSelectionChange(this.editor)});u(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()}});u(this,"handleSelectionChange",Qt.default(t=>{if(d(QI,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())},50));this.editor=t;const e=t.options.componentsOptions.popover;this.toolbar=new rc([],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),_t.get(t).addListener("childChange",this.handleHoveringBlockChildChange),_t.get(t).addFilter(this),t.editorCommandProviders.registerCommandProvider(new BE(t)),t.editorCommandProviders.registerCommandProvider(new GI(t)),t.editorCommandProviders.registerCommandProvider(new YI(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),_t.get(this.editor).removeListener("childChange",this.handleHoveringBlockChildChange)}isInBlock(t,e){return t!==this.hoveringBlock?!1:!!(e.target&&e.target instanceof Node&&this.toolbar.popper&&vt(this.toolbar.popper,e.target))}bindEvents(){document.addEventListener("mousedown",this.handleDocumentMouseDown)}unbindEvents(){document.removeEventListener("mousedown",this.handleDocumentMouseDown)}update(){this.showTextToolbar()}showTextToolbar(){if(this._disableTextToolbar||!this.editor.isWritable())return;const e=this.editor.selection.range.getSelectedBlocks();if(e.length===0)return;const o=e[0];if(!o)return;if(e.length===1&&De(o.block)){this.showObjectToolbar();return}const r=this.editor.editorCommandProviders.getCommands(this.editor.selection.range),i=new Map;r.forEach(a=>{const h=a.groupIndex,f=i.get(h);f?f.push(a):i.set(h,[a])});const s=[[]],l=Array.from(i.entries()).sort((a,h)=>a[0]-h[0]);for(let a=0;a<l.length;a++){const[,h]=l[a];if(h.length===0)continue;let f=s[s.length-1];f.length>0&&f[f.length-1].groupIndex!==h[h.length-1].groupIndex&&(f=[],s.push(f)),f.push(...pc(h))}if(s.length===0){this.toolbar.close();return}this.toolbarType="text";const c=[];if(s.forEach((a,h)=>{const f=a.sort((m,C)=>{var v,w;return((v=m.order)!=null?v:0)-((w=C.order)!=null?w:0)});c.push(...f),h!==s.length-1&&c.push(KI)}),this.toolbar.updateItems(c),!this.toolbar.isVisible){const a=e[e.length-1],h=!this.editor.selection.range.isReverse()&&a!==o,f=h?a:o,m=fE(this.editor,f),C=_o(this.editor,f.block,"editor-quick-menu",m);this.toolbar.manualShow(C,{placement:h?"bottom":"top"})}}showObjectToolbar(){if(!this.hoveringBlock)return;const t=this.hoveringBlock,e=this.hoveringTextChild,o=bE(this.editor,t,e);!o.length||(this.toolbarType="object",this.toolbar.close(),this.toolbar.updateItems(o),this.toolbar.isVisible||this.toolbar.manualShow(e||rt(t),{placement:e?"bottom":"top"}))}static register(t){return t.addCustom("toolbar-handler",e=>new Wr(e))}static get(t){return t.getCustom("toolbar-handler")}}function $h(){let n=8;for(;n>0&&!document.querySelector(`div[data-style-heading='${n}']`);)n--;return n}const JI=y("quick-menu"),XI=[zu,Uu,Vu,qu,Wu,Gu,Zu,Yu],tx={Unordered:v0,Ordered:k0,Checkbox:C0,Quote:b0};function fs(n,t){const e=n;e.blockOptions=t,e.itemType="insert-block",n.children&&n.children.forEach(o=>fs(o,t))}function ex(n,t,e){n.getBlockData(t).heading===e?n.updateBlockData(t,{heading:null}):n.updateBlockData(t,{heading:e})}async function nx(n,t){const{containerId:e,blockIndex:o,item:r}=t,{value:i,id:s}=r,l=n.getBlockByIndex(e,o);if(d(JI,yt(n,l),"not an empty block"),s.startsWith("heading-"))ex(n,l,Number.parseInt(i!=null?i:"1",10)||1);else if(i==="ordered"||i==="unordered"||i==="checkbox"){const c=n.selection.range.focus;if(!c.isSimple())return null;const a=hl(n,l,"list",{offset:c.offset,data:{listType:i==="checkbox"?"unchecked":i}});a&&(n.deleteBlock(l),n.insertBlock(e,o,a.blockData))}else i==="quote"&&n.updateBlockData(l,{quoted:!0});return null}const w5=(n,t)=>n.undoManager.runInGroup(()=>nx(n,t));function Tc(n=1){var r;const t={name:"basic",insertBlockCommandItems:[]};let e=$h();e<=4?e=5:e<8&&(e+=1);let o=n;for(;o<=e;)(r=t.insertBlockCommandItems)==null||r.push({id:`heading-${o}`,icon:XI[o-1],name:S.t("quickMenu.basic.heading.title",{heading:String(o)}),order:o,group:"basics",value:String(o)}),o++;return t}function ox(){const n={name:"basic",insertBlockCommandItems:[]};return["Unordered","Ordered","Checkbox","Quote"].forEach((e,o)=>{var r;(r=n.insertBlockCommandItems)==null||r.push({id:`insert-${e.toLocaleLowerCase()}`,name:S.t(`quickMenu.basic.${e.toLocaleLowerCase()}`),icon:tx[e],value:e.toLocaleLowerCase(),group:"basics",order:10+o})}),n}function rx(){var e;const t={name:"basic",insertBlockCommandItems:[...Tc().insertBlockCommandItems||[]],handleInsertEmptyBlock:w5};return(e=t.insertBlockCommandItems)==null||e.forEach(o=>{fs(o,t)}),t}function ix(){const n=Tc(),t=ox();return{name:"basic",insertBlockCommandItems:[...n.insertBlockCommandItems||[],...t.insertBlockCommandItems||[]],handleInsertEmptyBlock:w5}}class B5{constructor(){u(this,"dataUrl","");u(this,"error",null)}destroy(){}setDataUrl(t){this.dataUrl=t}setError(t){this.error=t}}const sx=y("mathjax-converter"),lx="MathJax-script";async function cx(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 xo(e,lx)}function ax(){try{window.MathJax&&window.MathJax.texReset()}catch{}}async function E5(n,t){const e="mathjax2Svg";try{await Ue.lock(e),ax(),await cx(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 sx.error(o),o}finally{Ue.release(e)}}async function I5(n,t){const e=await E5(n,t);return e?await om(e,"image/svg+xml"):""}async function jh(n,t){const o=await E5(n,t),r=new File([o],"math.svg");return(await n.doc.uploadResource(r)).resourceId}const x5=y("edit-mathjax");class dx{constructor(){u(this,"editMathjaxPopup",null);u(this,"onChange",null);u(this,"tex","");u(this,"handleShow",()=>{setTimeout(()=>{this.getTextarea().focus()})});u(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))}});u(this,"handleKeyup",t=>{var e;t.isComposing||(t.key==="Escape"&&((e=this.editMathjaxPopup)==null||e.close()),this.handleChange(t.target.value))});u(this,"handleChange",Qt.default(t=>{var e;(e=this.onChange)==null||e.call(this,t)},300))}editMathjax(t,e,o){if(!this.editMathjaxPopup)this.editMathjaxPopup=new ic(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(x5,this.editMathjaxPopup,"no exists mathjax editor popup");const t=this.editMathjaxPopup.content.querySelector("textarea");return d(x5,t,"no textarea"),t}destroy(){var t;this.onChange=null,(t=this.editMathjaxPopup)==null||t.removeAllListeners()}}function S5(n,t,e,o){n.addCustom("mathjax-editor",()=>new dx).editMathjax(t,e.trim(),o)}function ux(){return{insert:" ",attributes:{id:N(),box:!0,type:"math",tex:" ",src:"",created:Date.now()}}}function Hh(n,t){const e=n.getBoxData(t),o=async r=>{if(!r.trim()){n.updateBoxData({...e,tex:r,src:null});return}try{await Ue.lock("convertAndUploadMathjax");const i=await jh(n,r);n.updateBoxData({...e,tex:r,src:i})}finally{Ue.release("convertAndUploadMathjax")}};S5(n,t,e.tex,o)}const hx=y("mathjax-box");function Fh(n,t){n.selection.caret.update();const e=t.target;!e||!(e instanceof HTMLElement)||n.domEvents.removeEventListener(e,null,Fh)}async function fx(n,t,e){try{if(!t.tex.trim())return;const o=await I5(n,t.tex),r=n.findBoxById(t.id);if(!r)return;const i=id(r);i.innerHTML="";const s=b("img",["mathjax"],i);s.src=o,e.setDataUrl(o),n.domEvents.addEventListener(s,"load",Fh)}catch(o){e.setError(o)}}function mx(n,t,e,o){const r=o,i=n.addCustom(`mathjax-box-${r.id}`,()=>new B5);if(r.src||i.dataUrl){const l=b("img",["mathjax"],e);l.src=n.doc.buildResourceUrl(r.src||i.dataUrl),n.domEvents.addEventListener(l,"load",Fh);return}i.error;let s=r.tex;s.trim()||(s=S.t("mathjax.emptyText")),b("span",["mathjax-tex-text"],e,s),fx(n,r,i)}function gx(n,t){const e={id:N(),box:!0,type:"math",tex:t,src:"",created:Date.now()};return jh(n,t).then(o=>{if(!n.findBoxById(e.id))return;const i={...e,src:o};n.updateBoxData(i)}).catch(o=>{hx.error(`failed to convert and upload mathjax: ${JSON.stringify(o)}`)}),e}function px(n,t,e){Hh(n,t)}const Dc={boxType:"math",updateBoxContent:mx,convertFrom:gx,handleClickBox:px};async function Cx(n,t,e){try{const o=t.embedData,r=await I5(n,o.mathjaxText),i=n.findBlockById(t.id);if(!i)return;const s=rt(i);s.innerHTML="";const l=b("img",["mathjax"],s);l.src=r,e.setDataUrl(r)}catch(o){e.setError(o)}}function bx(n,t){if(n.readonly||!t.target||!(t.target instanceof Node))return;const e=z(t.target);if(!e||!De(e)||Le(e)!=="math")return;const o=rt(e),r=o.querySelector("img")||o.querySelector("span.mathjax-tex-text");if(!r||!vt(r,t.target))return;const s=n.getBlockData(e).embedData;S5(n,r,s.mathjaxText,async l=>{const c=await jh(n,l),a={mathjaxText:l,src:c};n.updateEmbedData(e,a)})}function vx(n,t,e){const o=e.embedData,r=n.addCustom(`mathjax-block-${e.id}`,()=>new B5);if(n.domEvents.addEventListener(t,"click",bx),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),Cx(n,e,r)}function kx(n,t,e){if(!H(n,t))return null;const o=n.getBlockString(t).trim();if(!o||!o.startsWith("$$")||!o.endsWith("$$"))return null;const r=Wa(o,"$");if(!r)return null;const i={mathjaxText:r,src:""};return{blockData:{id:N(),type:"embed",embedType:"math",embedData:i}}}function yx(n){return{name:"Mathjax"}}function wx(n,t){const e=rt(t);n.domEvents.removeAllListeners(e)}const zh={embedType:"math",createEmbedContent:vx,getOptions:yx,convertFrom:kx,handleDeleteBlock:wx},fF="",Bx={mathjax:{emptyText:"\u7A7A\u7684\u516C\u5F0F",abstract:"\u516C\u5F0F"}},Ex={mathjax:{emptyText:"Empty Tex",abstract:"TeX"}};S.mergeLang({"zh-CN":Bx,"en-US":Ex});function Ix(n,t,e,o){const r=n.getBlockByIndex(t,e),i=n.getBlockText(r),{left:s}=fe(i,o);if(!wt(s).endsWith("$$$$"))return!1;const c=o-4,a=o,h={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,h),setTimeout(()=>{const f=n.getBoxById(h.id);Hh(n,f)})}),!0}class xx{handleAfterInsertText(t,e,o,r,i){return!!(i===" "&&Ix(t,e,o,r))}}const T5=y("inline-box-items");function Sx(n,t,e){return n.undoManager.runInGroup(()=>{var s;let o=n.getBlockByIndex(t,e);yt(n,o)||(o=n.insertTextBlock([],t,e));const r=ux();n.setBlockText(o,[r]);const i=(s=r.attributes)==null?void 0:s.id;return d(T5,i,"mathjax box id is empty"),setTimeout(()=>{const l=n.getBoxById(i);Hh(n,l)},100),o})}function Tx(n,t,e){let o=n.getBlockByIndex(t,e),r="bottom-start";return yt(n,o)||(r="top-start"),bc(n,{target:o,linkText:"",linkUrl:"",onFinished:(l,c)=>{n.undoManager.runInGroup(()=>{try{yt(n,o)||(o=n.insertTextBlock([],t,e));const a=_e(l,{link:c}),h=_e(" ",null),f=[a,h];n.insertTextToBlock(o,0,f),n.selection.selectBlock(o,ce(f)),n.focus()}catch(a){T5.error(a)}})},onClose:()=>{n.focus()},placement:r}),o}async function Dx(n,t){switch(t.item.id){case"insert-math":return Sx(n,t.containerId,t.blockIndex);case"insert-link":return Tx(n,t.containerId,t.blockIndex);default:return null}}function Lx(){return{name:"text",insertBlockCommandItems:[{id:"insert-math",name:S.t("quickMenu.inlineBox.math"),icon:mw,order:900,group:"common"},{id:"insert-link",name:S.t("quickMenu.inlineBox.link"),icon:p0,order:400,group:"common"}],handleInsertEmptyBlock:Dx}}const D5={basics:100,system:200,common:300,thirdParty:400};function Mx(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.forEach(i=>{const s=i.getCommands(n);e.push(...s.map(l=>({...l,itemType:"insert-block",commandProvider:i})))}),e}function Rx(n){var r;const t=[];n.editorBlocks.forEach(i=>{if(!i.getOptions)return;const s=i.getOptions(n);!s.insertBlockCommandItems||(s.insertBlockCommandItems.forEach(l=>{fs(l,s)}),t.push(...s.insertBlockCommandItems))});const e=Lx(),o=ix();return e.insertBlockCommandItems.forEach(i=>{fs(i,e)}),(r=o.insertBlockCommandItems)==null||r.forEach(i=>{fs(i,o)}),t.push(...e.insertBlockCommandItems),t.push(...o.insertBlockCommandItems),t.push(...Mx(n)),t}function Uh(n){const t=Rx(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||D5[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=i.group||"common",a=l in D5?S.t(`blockMenu.section.${l}`):l;r.push({id:`section-${s}`,name:a,type:"section",group:i.group,itemType:"insert-block"}),r.push(...i.items.map(h=>({...h})))}),r}function Ox(n,t,e){const o=n.getFocusedBlock();if(!o)return;const r=n.getParentContainer(o),i=U(r);let l=n.getBlockIndex(o);if(yt(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 L5=y("quick-menu"),Ax={id:"quick-menu",trigger:["/"]};class Lc{constructor(t,e=Ax){u(this,"suggest");u(this,"items");u(this,"maxHeading");u(this,"queryItems",async(t,e)=>{if(this.items.length===0?this.initMenuItems():this.refreshMenuItems(),e){const o=new Set,r=e.toLocaleLowerCase();return this.items.filter(i=>{var s;return i.type==="section"?!0:i.name.toLocaleLowerCase().indexOf(r)!==-1||l0(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});u(this,"onShow",(t,e,o,r)=>{const i=this.editor.getBlockByIndex(e,o);if(!Uo(i)){const s=z(j(i));if(s&&it(s)==="code")return!1}return!0});u(this,"onClickItem",(t,e)=>{const o=e;o.itemType==="insert-block"&&(d(L5,o.blockOptions||o.commandProvider,"invalid quick item, no block options or command provider"),d(L5,this.suggest.anchor,"invalid suggest, no anchor"),Ox(this.editor,o,this.suggest.anchor))});this.editor=t,this.options=e,this.items=[],this.maxHeading=$h(),this.suggest=new nh(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=Uh(this.editor);this.items=t}refreshMenuItems(){let t=null,e=0;const o=i=>{const{id:s}=i;return s.startsWith("heading-")},r=$h();if(r!==this.maxHeading){const i=rx().insertBlockCommandItems;for(let s=0;s<this.items.length;s++){const l=this.items[s];o(l)&&(t||(t=s),e++)}t&&e&&this.items.splice(t,e,...i),this.maxHeading=r}}}class Vh{constructor(t){u(this,"instance");u(this,"mousedown",!1);u(this,"currentInstance",null);u(this,"attributeName","");u(this,"attributeDesc","");u(this,"observer",null);u(this,"observerCallback",null);u(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});u(this,"handleDocumentMouseDown",()=>{this.mousedown=!0,this.editor.domEvents.addEventListener(document,"mouseup",this.handleDocumentMouseUp)});u(this,"handleDocumentMouseUp",()=>{this.mousedown=!1,this.editor.domEvents.removeEventListener(document,"mouseup",this.handleDocumentMouseUp)});u(this,"handleShown",t=>{this.currentInstance&&this.hide(),this.currentInstance=t,this.createObserver()});u(this,"handleHidden",()=>{this.destroyObserver(),this.currentInstance=null});u(this,"handleShow",t=>{var r;const e=t.reference;if(!e||!vt(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=Na.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=Qt.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 _x={"text/style-bold":"bold","text/style-italic":"italic","text/style-underline":"underline","text/style-line-through":"line-through","text/style-code":"code","text/style-subscript":"subscript","text/style-superscript":"superscript"};function Nx(n,t){const e=new Set(Object.keys(_x)),o=t.filter(i=>e.has(i.id));return pc(o)}function Mc(n,t){if(!n.isWritable())return!1;const e=n.selection.range,o=n.editorCommandProviders.getCommands(e),i=Nx(n,o).find(s=>s.id===`text/${t}`);return i?(n.editorCommandProviders.executeCommand(e,i,{}),Wr.get(n).update(),!0):!1}const qh={"CtrlOrCmd+B":n=>Mc(n,"style-bold"),"CtrlOrCmd+I":n=>Mc(n,"style-italic"),"CtrlOrCmd+U":n=>Mc(n,"style-underline"),"CtrlOrCmd+D":n=>Mc(n,"style-line-through")},Px={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",heading:"\u6807\u9898 {name}",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"}}},$x={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",heading:"Heading {name}",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"}}};S.mergeLang({"zh-CN":Px,"en-US":$x});const mF="";function Xo(n,...t){const e=Vn(...t);return e.classList.remove("editor-button"),e.classList.add("editor-text-button"),n.append(e),e}function M5(n){Cc(n).hide();const e=n.getCustom("table-border-bar");e==null||e.closeToolbar()}function jx(n){return b("div",["insert-column-button","drop-marker"],n)}const R5=y("row-height");function O5(n){const t=et.fromTable(n),e=n.rows;d(R5,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 R5.debug("heights",o.join(", ")),o}const go=y("table-border-bar-dom");function ms(n,t){d(go,jt(t),"invalid table block");const e=$t(t),o=wn(n,t),r=(a,h,f)=>{const m=b("div",["button-root",h],a),C=b("div",["button-container",h],m);m.setAttribute(`data-${h}-index`,`${f}`),b("span",["insert-indicator"],C),jx(C)},{selectedRows:i,selectedColumns:s}=ih(n,t),l=()=>{const a=o.querySelector(".table-border-bar-container.top");d(go,a,"no top border bar container");const h=b("div",["table-border-bar-container","top"],null),f=b("div",["table-border-bar","top"],h),m=JB(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 w=0;w<v;w++){const E=w===v-1?m[w]+2:m[w],D=b("span",["table-border-bar-cell","top"],f);s.has(w)&&D.classList.add("selected"),D.setAttribute("data-top-index",`${w}`),D.style.width=`${E}px`,n.selection.range.isSimple()&&r(f,"top",w+1)}Ii(a,h)},c=()=>{const a=o.querySelector(".table-border-bar-container.left");d(go,a,"no left border bar container");const h=b("div",["table-border-bar-container","left"],null),f=b("div",["table-border-bar","left"],h),m=O5(e);n.selection.range.isSimple()&&r(f,"left",0),Array.from(e.rows).forEach((C,v,w)=>{const E=b("span",["table-border-bar-cell","left"],f);i.has(v)&&E.classList.add("selected"),E.setAttribute("data-left-index",`${v}`);const D=v===w.length-1?m[v]+2:m[v];E.style.height=`${D}px`,n.selection.range.isSimple()&&r(f,"left",v+1)}),Ii(a,h)};l(),c()}function A5(n,t){const e=t.target;if(!(e instanceof Element))return;const o=z(e);d(go,o&&jt(o),"invalid table block"),ms(n,o),n.selection.caret.update()}function Wh(n,t){const e=t.target;if(!(e instanceof Element))return;const o=z(e);d(go,o&&jt(o),"invalid table block");const r=e.closest(".button-root");if(r){if(r.classList.contains("top")){const s=parseInt(r.getAttribute("data-top-index")||"0",10);t5(n,o,s),ms(n,o)}else if(r.classList.contains("left")){const s=parseInt(r.getAttribute("data-left-index")||"0",10);e5(n,o,s),ms(n,o)}return}const i=e.closest(".table-border-bar-cell");if(i){if(i.classList.contains("top")){const s=parseInt(i.getAttribute("data-top-index")||"0",10);uE(n,o,s,1,{reverse:!0})}else if(i.classList.contains("left")){const s=parseInt(i.getAttribute("data-left-index")||"0",10);hE(n,o,s,1,{reverse:!0})}}}function Gh(n,t){M5(n),t.preventDefault(),t.stopPropagation()}function Hx(n,t){d(go,jt(t),"invalid table block");const e=wn(n,t),o=b("div",["table-border-bar-container","top"],e),r=b("div",["table-border-bar-container","left"],e);ms(n,t),n.domEvents.addEventListener(rt(t),"scroll",A5),n.domEvents.addEventListener(o,"click",Wh),n.domEvents.addEventListener(r,"click",Wh),n.domEvents.addEventListener(o,"mousedown",Gh),n.domEvents.addEventListener(r,"mousedown",Gh)}function _5(n,t){if(!n.isWritable())return;if(wn(n,t).querySelector(".table-border-bar-container")){ms(n,t);return}Hx(n,t)}function N5(n,t){d(go,jt(t),"invalid table block"),wn(n,t).querySelectorAll(".table-border-bar-container").forEach(r=>{n.domEvents.removeEventListener(r,"click",Wh),n.domEvents.removeEventListener(r,"mousedown",Gh),r.remove()}),n.domEvents.removeEventListener(rt(t),"scroll",A5)}function Fx(n,t){d(go,jt(t),"invalid table block");const o=wn(n,t).querySelector(".table-border-bar-container.top");return o?o.getBoundingClientRect().height:0}class zx{constructor(t,e){u(this,"toolbar");u(this,"handleSelectionChange",(t,e)=>{e==="delete-columns"?(Fr(this.editor,this.tableBlock,!0,!0),zr(this.editor,this.tableBlock,!0,!0)):e==="delete-rows"?(Fr(this.editor,this.tableBlock,!0,!1),zr(this.editor,this.tableBlock,!0,!1)):(Fr(this.editor,this.tableBlock,!1),zr(this.editor,this.tableBlock,!1))});u(this,"handleClick",(t,e,o)=>{e.id==="delete-columns"?sh(this.editor.selection.range):e.id==="delete-rows"&&lh(this.editor.selection.range)});this.editor=t,this.tableBlock=e;const o=t.options.componentsOptions.popover;this.toolbar=new rc([],void 0,{overflowBoundary:o==null?void 0:o.overflowBoundary,refuseOverflow:!0}),this.toolbar.addListener("selectionChange",this.handleSelectionChange),this.toolbar.addListener("click",this.handleClick)}close(){this.toolbar.close()}update(){const{selectedColumns:t,selectedRows:e}=ih(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=Oo(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:"Delete columns",icon:h0};this.toolbar.updateItems([r]);const i=_o(this.editor,this.tableBlock,"editor-quick-menu",o);this.toolbar.manualShow(i,{placement:"top"})}else{const r={id:"delete-rows",name:"Delete rows",icon:h0};this.toolbar.updateItems([r]);const i=new DOMRect(o.left-15,o.top,o.width,o.height),s=_o(this.editor,this.tableBlock,"editor-quick-menu",i);this.toolbar.manualShow(s,{placement:"left"})}}destroy(){this.toolbar.destroy(),this.toolbar.removeAllListeners()}}const Rc=y("table-border-bar");class Ux{constructor(t,e){u(this,"toolbar");u(this,"resizeObserver");u(this,"handleReadonlyChanged",t=>{t.isWritable()?this.update():N5(this.editor,this.tableBlock)});u(this,"handleBlockUpdated",()=>{this.resizeObserver.disconnect(),setTimeout(()=>{const t=this.editor.getBlockById(G(this.tableBlock));this.resizeObserver.observe($t(t))})});u(this,"handleTableResize",()=>{!this.editor.isWritable()||(console.log("resize"),this.update())});this.editor=t,this.tableBlock=e,d(Rc,this.tableBlock,"no table block"),Rc.debug("create table border bar"),_5(this.editor,this.tableBlock),this.resizeObserver=new ResizeObserver(this.handleTableResize),this.resizeObserver.observe($t(this.tableBlock)),this.toolbar=new zx(this.editor,this.tableBlock),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}close(){this.toolbar.close()}destroy(){Rc.debug("destroy table border bar"),this.resizeObserver.disconnect(),N5(this.editor,this.tableBlock),this.toolbar.destroy(),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged)}update(){Rc.debug("update table border bar"),_5(this.editor,this.tableBlock),this.toolbar.update()}}const Vx=y("table-border-bar");class qx{constructor(t){u(this,"activeTableBar",null);u(this,"handleBlockDeleted",(t,e)=>{!this.activeTableBar||(e===this.activeTableBar.tableBlock||vt(e,this.activeTableBar.tableBlock))&&(this.activeTableBar.destroy(),this.activeTableBar=null)});u(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(jt(i)){const s=j(i),l=z(s);l&&(o=Ee(l))}else o=Ee(i)}else{const i=t.getBlockById(e.start.blockId),s=Ee(i),l=t.getBlockById(e.end.blockId),c=Ee(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 Ux(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(Vx,this.activeTableBar,"no active table bar"),this.activeTableBar.destroy(),this.activeTableBar=null)}}function P5(n,t){const e=n.addCustom("table-border-bar",o=>new qx(o));t==="update"&&e.update()}const be=y("table-cell-menu"),Wx="style-bg-color-";class Gx{constructor(t){u(this,"activeTableBlock",null);u(this,"targetButton",null);u(this,"manualMenu",null);u(this,"colorPaletteItem",null);u(this,"handlePrevent",(t,e)=>{e.stopPropagation()});u(this,"handleReadonlyChanged",t=>{t.isWritable()||this.hide()});u(this,"handleSelectionChanged",t=>{const e=t.selection.range;let o=null;if(e.isCollapsed()&&e.isSimple()){const r=t.getBlockById(e.start.blockId);if(jt(r)){const i=j(r),s=z(i);s&&(o=Ee(s))}else o=Ee(r)}else{const r=t.getBlockById(e.start.blockId),i=Ee(r),s=t.getBlockById(e.end.blockId),l=Ee(s);i===l&&(o=i)}if(this.hide(),this.activeTableBlock!==o&&(this.activeTableBlock=o),this.activeTableBlock){const r=et.fromBlock(this.activeTableBlock),{end:i}=e;let s=null;e.isCollapsed()?s=this.getCellByChildBlockId(r,i.blockId):i instanceof Ye&&(t.getBlockById(i.blockId)===this.activeTableBlock?s=r.getCellByContainerId(i.childContainerId):s=this.getCellByChildBlockId(r,i.blockId)),s&&this.editor.isWritable()&&this.showCellMenuButton(s)}});u(this,"handleBeforePopupPalette",()=>{var e;const t=this.getSelectedBkgColorIndex();(e=this.colorPaletteItem)==null||e.palette.setColor("backgroundColor",t)});u(this,"createBkgColorItem",()=>{const t=b("div",["cell-background-color-item"],null);b("span",[],t,S.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=u0,t});u(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":lh(_0(this.editor,this.activeTableBlock,!1));break;case"delete-select-col":sh(_0(this.editor,this.activeTableBlock,!0));break;case"merge-cell":R0(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":yB(this.editor,this.activeTableBlock,o==="show-border");break;case"show-chart":xB(this.editor,this.activeTableBlock,o==="show-chart"),Ch(this.editor,this.activeTableBlock,{updateNow:!0});break}});u(this,"handleSelectionChange",(t,e)=>{d(be,this.activeTableBlock,"no target table block"),e==="cell-background-color"&&this.handleBeforePopupPalette(),e==="delete-select-row"?(Fr(this.editor,this.activeTableBlock,!0,!1),zr(this.editor,this.activeTableBlock,!0,!1)):e==="delete-select-col"?(Fr(this.editor,this.activeTableBlock,!0,!0),zr(this.editor,this.activeTableBlock,!0,!0)):(Fr(this.editor,this.activeTableBlock,!1),zr(this.editor,this.activeTableBlock,!1))});u(this,"handleClick",()=>{var t;d(be,this.activeTableBlock,"no target table block"),d(be,this.targetButton,"no target button"),M5(this.editor),lt(this.targetButton,"active")?(F(this.targetButton,"active"),(t=this.manualMenu)==null||t.close()):(M(this.targetButton,"active"),this.manualMenu?this.manualMenu.updateItems(this.createCommandMenu()):(this.manualMenu=new Wo(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&&F(this.targetButton,"active")})),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&&(F(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=z(r);if(d(be,i,"no parent block"),$t(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=Fu,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);ah(this.editor,this.activeTableBlock,{col:o,row:r})}else dh(this.editor.selection.range)}}getSelectedBkgColorIndex(){var r;d(be,this.activeTableBlock,"no target table block");const t=EB(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(Wx.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=M0(this.editor,this.activeTableBlock,this.editor.selection.range);let o=this.editor.selection.range;if(o.isSimple()){const h=qn(this.editor,this.activeTableBlock,o.start);o=Vt(this.editor,{anchor:h,focus:h})}const r=L0(this.editor,this.activeTableBlock,o),i=t.hasRowTitle,s=t.hasColTitle,l=t.isStripeStyle,c=t.noBorder,a=t.chart;return this.colorPaletteItem=new I0("cell-background-color",{color:!1}),this.colorPaletteItem.palette.on("onClick",(h,f)=>{var m;switch(d(be,this.activeTableBlock,"no target table block"),h){case"clearColor":$0(this.editor,this.activeTableBlock,-1);break;case"backgroundColor":$0(this.editor,this.activeTableBlock,f);break}(m=this.manualMenu)==null||m.close()}),[{id:"cell-background-color",name:S.t("table.cellBackground"),element:this.createBkgColorItem(),children:[this.colorPaletteItem]},{id:"separator",name:"",type:"separator"},{id:"merge-cell",name:S.t("table.mergeCell"),states:e?[]:["disabled"]},{id:"split-cell",name:S.t("table.splitCell"),states:r?[]:["disabled"]},{id:"separator",name:"",type:"separator"},{id:"delete-select-row",name:S.t("table.deleteSelectRow")},{id:"delete-select-col",name:S.t("table.deleteSelectCol")},{id:"separator",name:"",type:"separator"},{id:"table-config",name:S.t("table.tableConfigKey"),children:[{id:"row-title",name:S.t("table.tableConfig.rowTitle"),states:i?["checked"]:[]},{id:"col-title",name:S.t("table.tableConfig.colTitle"),states:s?["checked"]:[]},{id:"stripe-style",name:S.t("table.tableConfig.stripeStyle"),states:l?["checked"]:[]},{id:"hide-border",name:c?S.t("table.tableConfig.showBorder"):S.t("table.tableConfig.hideBorder"),value:c?"show-border":"hide-border"},{id:"show-chart",name:a?S.t("table.tableConfig.hideChart"):S.t("table.tableConfig.showChart"),value:a?"hide-chart":"show-chart"}]}]}handleRowTitle(t){d(be,this.activeTableBlock,"no target table block"),t?bB(this.editor,this.activeTableBlock):CB(this.editor,this.activeTableBlock)}handleColTitle(t){d(be,this.activeTableBlock,"no target table block"),t?pB(this.editor,this.activeTableBlock):gB(this.editor,this.activeTableBlock)}handleStripeStyle(t){d(be,this.activeTableBlock,"no target table block"),t?kB(this.editor,this.activeTableBlock):vB(this.editor,this.activeTableBlock)}}function $5(n){n.addCustom("table-cell-menu",t=>new Gx(t))}const Oc=y("table-container");function Zh(n){const t=n.closest("td");return d(Oc,t,"no parent cell for a table cell container"),t}function j5(n){const t=$t(n);return Array.from(t.querySelectorAll(':scope > tbody > tr > td > [data-type="editor-container"].child'))}function Yh(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(Oc,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(Oc,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(Oc,!1,`invalid navigation type: ${e}`)}const Zx=12,Yx=90,Ac=23,H5=2;class Qx{constructor(t){u(this,"scrollTableBlock",null);u(this,"autoScrollDir",null);u(this,"autoScrollTimer",null);u(this,"handleMouseDown",t=>{const e=document.elementFromPoint(t.clientX,t.clientY);if(e&&e instanceof HTMLElement){const o=z(e);if(o&&vt(this.editor.rootContainer,o)){const r=Ee(o);r&&(this.scrollTableBlock=r,document.addEventListener("mousemove",this.handleAutoScroll))}}});u(this,"handleAutoScroll",T9.default(t=>{if(this.scrollTableBlock){const e=this.editor.getCustom(ho(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));u(this,"handleMouseUp",()=>{document.removeEventListener("mousemove",this.handleAutoScroll),setTimeout(()=>{this.scrollTableBlock=null})});u(this,"handleSelectionChanged",t=>{const e=t.selection.range;if(e.isCollapsed()&&e.isSimple()){const o=t.getBlockById(e.start.blockId),r=Ee(o);if(r){const i=t.getCustom(ho(r)),s=i.rootElement.getBoundingClientRect(),l=Ze(t,o,e.start);if(s.left>l.left){const c=e.start.offset===0?Zx:H5;i.rootElement.scrollLeft-=s.left-l.left+c}else if(l.right>s.right){const c=e.start.offset===0?Yx:H5;i.rootElement.scrollLeft+=l.right-s.right+c}}}else{const o=t.getBlockById(e.start.blockId),r=Ee(o),i=t.getBlockById(e.end.blockId),s=Ee(i);if(r&&r===s){const l=t.getCustom(ho(r)),c=l.rootElement.getBoundingClientRect();let a=null;if(e.isSimple())a=e.isReverse()?Ze(t,o,e.start):Ze(t,i,e.end);else{const h=Zh(Cr(t,e.start.childContainerId)),f=Zh(Cr(t,e.end.childContainerId));a=e.isReverse()?h.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)}}});u(this,"handleScroll",t=>{rB(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(ho(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),h=Math.max(c.top,0);this.autoScrollDir==="left"&&(o.scrollLeft-=Ac,o.scrollLeft<=0&&this.clearAutoScroll()),this.autoScrollDir==="right"&&(o.scrollLeft+=Ac,o.scrollLeft>=o.scrollWidth-o.offsetWidth&&this.clearAutoScroll()),this.autoScrollDir==="bottom"&&(r.scrollTop+=Ac,(r.scrollTop>=r.scrollHeight-s||i.bottom<=a)&&this.clearAutoScroll()),this.autoScrollDir==="top"&&(r.scrollTop-=Ac,(r.scrollTop<=0||i.top>=h)&&this.clearAutoScroll())}},100))}destroy(){document.removeEventListener("mousedown",this.handleMouseDown),document.removeEventListener("mouseup",this.handleMouseUp),this.editor.removeListener("selectionChanged",this.handleSelectionChanged)}}function F5(n){return n.addCustom("table-scroll-events",t=>new Qx(t))}const Bn=y("create-content");function z5(n,t,e){const o=new rh(e),r=e.rows,i=e.cols;d(Bn,r>=1,`invalid rows: ${r}`),d(Bn,i>=1,`invalid cols: ${i}`),d(Bn,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]||mc}px`}const a=b("tbody",[],s);let h=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(Bn,v.colSpan>1||v.rowSpan>1,"virtual cell should have colSpan or rowSpan");else{const w=e.children[h],E=b("td",[],m);v.colSpan>1&&(E.colSpan=v.colSpan),v.rowSpan>1&&(E.rowSpan=v.rowSpan);const D=e[ss(w)];D&&M(E,D),C===0&&e.hasColTitle&&M(E,O0.COL_TITLE_ITEM),n.createChildContainer(t,E,w),h+=1}}}return d(Bn,h===e.children.length,"container count mismatch"),e.noBorder&&M(s,"no-border"),e.chart&&M(s,"editor-table-chart"),e.isStripeStyle&&M(s,"stripe"),e.hasRowTitle&&M(s,"row-title"),e.hasColTitle&&M(s,"col-title"),s}function Kx(n,t,e,o,r){d(Bn,r.type==="table","not table data"),d(Bn,U(e)===t[t.length-1].containerId,"invalid path");const i=r,s=no(o,"div");try{const l=b("div",[],null);l.setAttribute("data-type","table-content");const c=z5(n,t,i);c.classList.add("drag-preview-element"),l.appendChild(c),J0(n),o5(n),P5(n,"create"),$5(n),zy(n,bh);const a=n.getComponentOptions("table"),h=n.addCustom(ho(o),()=>YB());h.init({parentElement:s,childElement:l,safeRightSpace:80,safeLeftSpace:40,parentContainer:Ct(e)?n.scrollContainer:e,locatingContainer:Ct(e)?(a==null?void 0:a.locatingContainer)||n.parent:e,paddingLeft:fh+is,paddingTop:fh+is,paddingBottom:is/2,paddingRight:is/2});const f=F5(n);h.on("scroll",f.handleScroll),setTimeout(()=>{DB(n,o)})}catch{const c=`invalid table data: ${JSON.stringify(i)}`;Bn.error(c);const a=b("div",["error"],s);a.innerText=c}return s}function Jx(n,t,e){d(Bn,e.type==="table","not table data");const o=e,r=rt(t);try{const i=$t(t),s=Ro(t),l=z5(n,s,o);l.classList.add("drag-preview-element"),i.insertAdjacentElement("afterend",l),i.remove(),J0(n),o5(n),P5(n,"update"),$5(n),bh(n,t)}catch{const s=`invalid table data: ${JSON.stringify(o)}`;Bn.error(s);const l=b("div",["error"],r);l.innerText=s}}function Xx(n,t){let e,o,r=!1;if([...t].every(m=>m==="|")?(o=t.length,e=Array(o).fill(""),r=!0):(e=Wa(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(Cn(n.doc,m===0?C:""))});const c=Array(s).fill(mc),a=l[r?0:s],h=n.doc.getContainerBlocks(a)[0].id;return{blockData:{id:N(),type:"table",rows:i,cols:s,children:l,colsWidth:c},focusBlockId:h}}function tS(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 h=0;h<o;h++)r.push(Cn(n.doc));const i=Array(o).fill(mc),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 Qh=y("table-selection-to-doc");function U5(n,t){const{start:e,end:o,block:r}=t,i=it(r);d(Qh,i==="table",`invalid block type: ${i}`);const s=n.getBlockData(r);if(e.isSimple()&&o.isSimple()){const V=s.children;d(Qh,V,"no table children");const nt=V[0],ot=V[V.length-1],ut=bt(r,nt),dt=bt(r,ot);return U5(n,{block:t.block,start:ut,end:dt})}d(Qh,!e.isSimple()&&!o.isSimple(),"invalid block pos type");const l=et.fromBlock(r),{fromCol:c,toCol:a,fromRow:h,toRow:f}=sn(r,e,o),m={},C=[],v=n.doc.toJSON();let w={};l.sub({row:h,col:c},{row:f,col:a}).forEach((V,nt)=>{V.forEach((ot,ut)=>{const dt=ot.containerId;if(C.indexOf(dt)!==-1)return;C.push(dt);let Et;if(ot.virtual){const te=l.getCellByContainerId(ot.containerId),Fe=c+ut;let bo=te.col+te.colSpan-1;bo>a&&(bo=a);const cr=bo-Fe+1;cr>1&&(m[`${dt}_colSpan`]=cr);const ar=h+nt;let vo=te.row+te.rowSpan-1;vo>f&&(vo=f);const ha=vo-ar+1;ha>1&&(m[`${dt}_rowSpan`]=ha),Et=ro()}else{if(Et=Zd(n.editorBlocks,v,dt),ot.col+ot.colSpan>a+1){const te=a-ot.col+1;te>1&&(m[`${dt}_colSpan`]=te)}else ot.colSpan>1&&(m[`${dt}_colSpan`]=ot.colSpan);if(ot.row+ot.rowSpan>f+1){const te=f-ot.row+1;te>1&&(m[`${dt}_rowSpan`]=te)}else ot.rowSpan>1&&(m[`${dt}_rowSpan`]=ot.rowSpan)}const{root:re,...Xn}=Et.blocks;w={...w,...Xn,[dt]:re}})});const D=ds($t(r)).slice(c,a+1);return{blocks:{root:[{id:N(),type:i,children:C,colsWidth:D,rows:f-h+1,cols:a-c+1,...m}],...w},meta:{},comments:{}}}function eS(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 nS(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 oS(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 rS(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 iS(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,!eS(n,l)){l.top--,c=!0;continue}if(!nS(n,l)){l.left--,c=!0;continue}if(!oS(n,l)){l.bottom++,c=!0;continue}if(!rS(n,l)){l.right++,c=!0;continue}}while(c);return l}function sS(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(A=>A.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),h=Math.min(s.col,l.col),f=Math.max(s.col,l.col),m=iS(i,{row:c,col:h},{row:a,col:f}),C=r.getCell({row:m.top,col:m.left}),v=r.getCell({row:m.bottom,col:m.right}),w=r.getCell({row:m.top,col:m.right}),E=r.getCell({row:m.bottom,col:m.left});let D,x;return s.row<=l.row?s.col<=l.col?(D=C,x=v):(D=w,x=E):s.col<l.col?(D=E,x=w):(D=v,x=C),console.log(`move ${D.col}, ${D.row}, -> ${x.col}, ${x.row}`),{anchor:bt(t,D.containerId),focus:bt(t,x.containerId)}}function V5(n,t,e){if(e.isSimple())return[$t(t).getBoundingClientRect()];const o=$t(t),r=o.getBoundingClientRect(),{fromCol:i,fromRow:s,toCol:l,toRow:c}=sn(t,e.start,e.end),a=ds(o),h=a.slice(0,i).reduce((w,E)=>w+E,0),f=h+a.slice(i,l+1).reduce((w,E)=>w+E,0),m=O5(o);let C=m.slice(0,s).reduce((w,E)=>w+E,0);const v=C+m.slice(s,c+1).reduce((w,E)=>w+E,0);if(s===0){const w=Fx(n,t);C-=w}return[new DOMRect(r.left+h,r.top+C,f-h,v-C)]}y("table-size");const lS=40;function _c(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 cS(n,t,e){const o=ud(n,e.container);return o!==void 0?o+_c(t):lS*e.colSpan-_c(t)}function aS(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=cS(n,t,l);const a=qm(l.container,{withPadding:!0});a&&a>c&&(c=a),r+=c+_c(t)}return r}function dS(n,t){const e=$t(t),o=et.fromTable(e);let r=0;for(let s=0;s<o.rowCount;s++)r=Math.max(r,aS(n,e,o,s));const i=_c(e);return r+=i,r}const Gn=y("table-creator");async function uS(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=tS(n,{cols:o,rows:r});if(!i)return null;const{blockData:s,focusBlockId:l}=i;return n.insertBlock(t.containerId,t.blockIndex,s,Lt(n,l,0))})}class hS{constructor(){u(this,"id","insert-table");u(this,"name","Create table");u(this,"element");u(this,"closeable",null);u(this,"colCount");u(this,"rowCount");u(this,"setCloseable",t=>{this.closeable=t});u(this,"destroy",()=>{this.closeable=null});u(this,"getTableCreatorCellId",(t,e)=>`table-creator-cell-${t}-${e}`);u(this,"handleTableCreatorClick",t=>{var m,C;t.preventDefault(),t.stopPropagation();const e=t.target;d(Gn,e instanceof HTMLElement,"invalid event target");const o=e.closest(".table-creator");d(Gn,o,"no table creator");const r=o.querySelectorAll(".active");if(r.length===0)return;const s=r[r.length-1].id;d(Gn,s,"no cell id");const l="table-creator-cell-";if(!s.startsWith(l))return;const a=s.substring(l.length).split("-");d(Gn,a.length===2,"invalid cell id");const h=Number.parseInt(a[0],10)+1,f=Number.parseInt(a[1],10)+1;Gn.debug(`${h}, ${f}`),this.colCount=f,this.rowCount=h,(m=this.closeable)==null||m.click(this,this.element),(C=this.closeable)==null||C.close(),this.handleTableCreatorLeave()});u(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&&F(r,"active")}});u(this,"handleTableCreatorCellEnter",t=>{const e=t.target;d(Gn,e instanceof HTMLElement,"invalid event target");const o=e.id,r="table-creator-cell-";d(Gn,o.startsWith(r),"invalid cell id");const s=o.substring(r.length).split("-");d(Gn,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 h=0;h<9;h++){const f=this.getTableCreatorCellId(a,h),m=document.getElementById(f);d(Gn,m,"no cell"),a<=l&&h<=c?M(m,"active"):F(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 fS(n){return n.addCustom("table-creator-item",()=>new hS)}const Nc=y("table-block");function mS(n){return 1}function gS(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t))return null;if(r instanceof HTMLTableCellElement){const l=$t(t);if(x0(l).indexOf(r)!==-1){const a=os(r),h=bt(t,U(a));return new Qe(n,{anchor:h,focus:h})}}if(!mn(r))return null;const i=r;if(j5(t).indexOf(i)===-1)return null;const s=bt(t,U(i));return new Qe(n,{anchor:s,focus:s})}function pS(n,t,e,o){return null}function CS(n,t){return n.getBoundingClientRect()}function q5(n,t,e,o){if(e.isSimple()){d(Nc,o.isSimple(),"from is simple position but to is not simple position"),Nc.debug("full select table"),M(t,"full-selected");return}d(Nc,!o.isSimple(),"from is complex position but end is simple position");const r=qn(n,t,e),i=qn(n,t,o);d(Nc,r.blockId===i.blockId,"only allow update one table selection"),wB(n,r,i).forEach(l=>{const c=Zh(l);M(c,"selected")})}function bS(n){n.rootContainer.querySelectorAll('[data-type="editor-block"][data-block-type="table"]').forEach(t=>{F(t,"full-selected"),t.querySelectorAll("td.selected").forEach(e=>{F(e,"selected")})})}function vS(n,t){return S0(t)?j5(t):[]}function kS(n,t,e,o,r){return Yh(t,e,o,r)}function yS(n,t){return dS(n,t)}function wS(n,t){return H(n,t)?Xx(n,n.getBlockString(t).trim()):null}function BS(n){return{name:"TableBlock",insertBlockCommandItems:[{id:"insert-table",name:S.t("table.title"),order:200,icon:gw,children:[fS(n)],group:"common"}],handleInsertEmptyBlock:uS}}function ES(n,t,e){return Jx(n,t,e),setTimeout(()=>{const o=n.selection.range;o.isSimple()?n.selection.caret.update():q5(n,t,o.start,o.end)}),!0}function IS(n,t){let e=0;const{selectedColumns:o}=ih(n,t);if(o.size>0){const{fromCol:i,toCol:s}=sn(t,n.selection.range.start,n.selection.range.end),l=et.fromBlock(t);(i!==0||s!==l.colCount-1)&&(e=60)}const r=V5(n,t,n.selection.range)[0];return new DOMRect(r.left,r.top+e,r.width,r.height-e)}function xS(n,t){Uy(n,bh);const e=n.findCustom(ho(t));if(e){const o=F5(n);e.off("scroll",o.handleScroll),e.destroy()}}function SS(){return{abstract:`[${S.t("table.abstract")}]`}}const gs={blockType:"table",blockKind:"complex",enableKeyboardSelect:!0,createBlockContent:Kx,getBlockTextLength:mS,getRangeFromPoint:gS,moveCaret:pS,getCaretRect:CS,updateSelection:q5,clearSelection:bS,getChildContainers:vS,getNextContainer:kS,getMinWidth:yS,getSelectedContainers:gh,convertFrom:wS,adjustSelectionPos:sS,getClientRects:V5,selectionToDoc:U5,getOptions:BS,getTextToolbarReferenceClient:IS,handleUpdateBlock:ES,handleDeleteBlock:xS,getBlockProperties:SS},TS={table:{cellBackground:"\u5355\u5143\u683C\u80CC\u666F\u8272",deleteSelectRow:"\u5220\u9664\u6240\u9009\u884C",deleteSelectCol:"\u5220\u9664\u6240\u9009\u5217",mergeCell:"\u5408\u5E76\u5355\u5143\u683C",splitCell:"\u62C6\u5206\u5355\u5143\u683C",tableConfigKey:"\u8868\u683C\u8BBE\u7F6E",tableConfig:{rowTitle:"\u884C\u6807\u9898",colTitle:"\u5217\u6807\u9898",stripeStyle:"\u6761\u7EB9\u6837\u5F0F",hideBorder:"\u9690\u85CF\u8868\u683C\u7EBF",showBorder:"\u663E\u793A\u8868\u683C\u7EBF",showChart:"\u663E\u793A\u56FE\u8868",hideChart:"\u9690\u85CF\u56FE\u8868"},title:"\u8868\u683C",abstract:"\u8868\u683C"}},DS={table:{cellBackground:"Cell background",deleteSelectRow:"Delete rows",deleteSelectCol:"Delete columns",mergeCell:"Merge cells",splitCell:"Split cell",tableConfigKey:"Table setting",tableConfig:{rowTitle:"Row Title",colTitle:"Col Title",stripeStyle:"Stripe style",hideBorder:"Hide border",showBorder:"Show border",showChart:"Show chart",hideChart:"Hide chart"},title:"Table",abstract:"Table"}};S.mergeLang({"zh-CN":TS,"en-US":DS});const pF="",W5=y("table");function G5(n,t){const e=oh(t);if(!e)return;const o=z(e);d(W5,o&&jt(o),"not a table block");const r=Yh(o,e,"ArrowRight");if(!r){const s=ht(o);return s?(n.selection.selectBlock(s,0),!0):G5(n,o)}const i=Kt(r);return n.selection.selectBlock(i,0),!0}function LS(n){if(!n.isWritable())return!1;const t=n.getFocusedBlock();if(!!t)return G5(n,t)}function Z5(n,t){const e=oh(t);if(!e)return;const o=z(e);d(W5,o&&jt(o),"not a table block");const r=Yh(o,e,"ArrowLeft");if(!r){const s=gt(o);return s?(n.selection.selectBlock(s,Z(n,s)),!0):Z5(n,o)}const i=Gt(r);return n.selection.selectBlock(i,Z(n,i)),!0}function MS(n){if(!n.isWritable())return!1;const t=n.getFocusedBlock();if(!!t)return Z5(n,t)}const Kh={Tab:LS,"Shift+Tab":MS},RS=`<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
361
|
+
`;function _I(n){return Vn("list-to-mindmap",S.t("mindmap.viewAsMindMap"),AI,[],n.clientId)}const dF="";class xc{constructor(t){u(this,"toMindmapButton");u(this,"currentBlock",null);u(this,"handleHoveringBlock",t=>{!this.editor.isWritable()||(t&&at(t)&&je(t)!=="unchecked"&&je(t)!=="checked"?At(t).appendChild(this.toMindmapButton):this.toMindmapButton.remove())});u(this,"handleMouseEnter",()=>{const t=z(this.toMindmapButton);d(Mt,t&&at(t),"no parent list"),Rh(this.editor,t,!0),this.currentBlock=t});u(this,"handleMouseLeave",()=>{this.currentBlock&&(Rh(this.editor,this.currentBlock,!1),this.currentBlock=null)});u(this,"handleClick",()=>{const t=z(this.toMindmapButton);d(Mt,t&&at(t),"no parent list"),Oh(this.editor,t,{},{saveData:!0,selectBlock:!0,mindmapTools:g5})});this.editor=t,_t.get(this.editor).addListener("change",this.handleHoveringBlock),this.toMindmapButton=_I(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(xc)}destroy(){_t.get(this.editor).removeListener("change",this.handleHoveringBlock)}hide(){this.currentBlock&&(this.currentBlock=null),this.toMindmapButton.remove()}}const NI={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"}},PI={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"}};S.mergeLang({"zh-CN":NI,"en-US":PI});const uF="";function $I(n,t,e){var o;t==="beginDrag"&&((o=xc.get(n))==null||o.hide())}function Sc(n){const t=n.getAttribute("block-padding-level");return t?Number(t):null}function jI(n,t){let e;const o=Sc(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 k5(n,t){const e=Sc(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 _h(n){return n.readonly||!n.isWritable()}function HI(n){return n.selection.range.getSelectedBlocks().forEach(e=>{const o=e.block;H(n,o)&&jI(n,o)}),!0}function FI(n){return n.selection.range.getSelectedBlocks().forEach(e=>{const o=e.block;H(n,o)&&k5(n,o)}),!0}function zI(n){return _h(n)?!1:n.undoManager.runInGroup(()=>(HI(n),!0))}function UI(n){return _h(n)?!1:n.undoManager.runInGroup(()=>(FI(n),!0))}function VI(n){if(_h(n))return!1;if(!n.selection.range.isCollapsed())return;const t=n.selection.focusedBlock;if(!H(n,t))return;const e=n.selection.range.focus;if(!(!e.isSimple()||e.offset!==0||!Sc(t)))return k5(n,t),!0}class qI{renderBlock(t,e,o){const{padding:r}=o;return r?{attributes:{"block-padding-level":r}}:{}}}const hF="",WI={Tab:zI,"Shift+Tab":UI,Backspace:VI};function Nh(n,t,e){let o=1,r=1,i=N();if(at(t))o=Te(t);else{const a=Sc(t);a&&(o=a+1),o>8&&(o=8)}const s=c5(t,e);if(s){if(K(t)>K(s))r=Se(s)+1;else{const a=Se(s);a>1&&(r=a-1)}i=Qo(s)}const c={...n.getBlockData(t),level:o,start:r,groupId:i,type:"list",...wc(e)};n.undoManager.runInGroup(()=>{const a=K(t),h=U(j(t));n.deleteBlock(t);const f=n.insertBlock(h,a,c);new Jo(n,f).fix()})}const y5={...Ai,blockType:"list",createBlockContent:OI,convertFrom:RE,handleDrop:NE,notify:$I},Ph=y("paragraph");class GI{constructor(t){u(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":[S.t("commands.unordered"),St.isMac?S.t("commandDesc.mac.unordered"):S.t("commandDesc.window.unordered"),sw],"ordered-list":[S.t("commands.ordered"),St.isMac?S.t("commandDesc.mac.ordered"):S.t("commandDesc.window.ordered"),iw],"check-list":[S.t("commands.check"),void 0,lw],link:[S.t("commands.link"),St.isMac?S.t("commandDesc.mac.link"):S.t("commandDesc.window.link"),p0],quoted:[S.t("commands.quote"),void 0,cw]};if(H(t,e)){const i=G(e),s=it(e),l=Ge(t,e),c=t.getBlockData(e);Object.entries(r).forEach(([a,[h,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:h,desc:f,states:C,icon:m,groupIndex:600})})}return o}convertLink(t,e,o){d(Ph,vr(e.start),""),d(Ph,vr(e.start),"");const r="bottom-start",i=e.start.offset,s=e.end.offset,l=(C,v)=>{t.undoManager.runInGroup(()=>{try{let w=El(t.getBlockText(o),i,s,C);w=wl(i,C.length,w,"link",v),t.setBlockText(o,w),t.selection.selectBlock(o,i+C.length),t.focus()}catch(w){Ph.error(w)}})},c=()=>{t.focus()},a=Oo(t,o,e)[0];if(!a)return;const h=_o(t,o,"link-button-anchor",a),f=t.getBlockText(o),m=Bl(f,i);bc(t,{target:h,linkText:t.getSelectedText(),linkUrl:(m==null?void 0:m.link)||"",onFinished:l,onClose:c,placement:r})}executeCommand(t,e,o,r){var c;if(!H(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?hs(t,e):Nh(t,e,"unordered"),l=!0),i==="ordered-list"&&(s?hs(t,e):Nh(t,e,"ordered"),l=!0),i==="check-list"&&(s?hs(t,e):Nh(t,e,"unchecked"),l=!0),i==="quoted"){const h=t.getBlockData(e).quoted;t.updateBlockData(e,{quoted:h?void 0:!0}),l=!0}if(i==="link"){const a=Cc(t);a.disableTextToolbar(),a.hide(),setTimeout(()=>{a.enableTextToolbar()},1e3),this.convertLink(t,o,e),l=!0}return l}}const ZI={left:es,right:Qu,center:Ku};class YI{constructor(t){u(this,"id","BlockAlignProvider");this.editor=t}applyAlignStyle(t,e,o){Object.keys(ZI).includes(o)?t.updateBlockData(e,{align:o}):t.updateBlockData(e,{align:null})}isChecked(t,e){return t.align===e}getAvailableCommands(t,e,o){const r=G(e),i=it(e),s=Ge(t,e),l=t.getBlockData(e);return[{id:"align",name:"",blockId:r,blockType:i,blockKind:s,groupIndex:700,dropdown:!0,element:a=>{var f;const h=b("span",["toolbar-item-name-container"],null);for(const m of a.children)if((f=m.states)!=null&&f.includes("checked"))return h.innerHTML=m.icon||es,h;return h.innerHTML=es,h},manualShowChildren:!0,childrenPlacement:"bottom-start",defaultCheckedChildren:["align-left"],children:[{id:"align-left",name:S.t("commands.alignLeft"),icon:es,states:this.isChecked(l,"left")?["checked"]:[]},{id:"align-center",name:S.t("commands.alignCenter"),icon:Ku,states:this.isChecked(l,"center")?["checked"]:[]},{id:"align-right",name:S.t("commands.alignRight"),icon:Qu,states:this.isChecked(l,"right")?["checked"]:[]}],childrenType:"menu"}]}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}}const QI=y("toolbar-handler"),KI={id:"",name:"",type:"separator"};class Wr{constructor(t){u(this,"toolbar");u(this,"toolbarType","object");u(this,"mouseDown",!1);u(this,"oldRange",null);u(this,"hoveringBlock",null);u(this,"hoveringTextChild",null);u(this,"_disableTextToolbar",!1);u(this,"handleButtonClick",(t,e)=>{this.toolbarType==="text"?(this.editor.editorCommandProviders.executeCommand(this.editor.selection.range,e,{}),this.showTextToolbar()):this.hoveringBlock&&yE(this.editor,this.hoveringBlock,this.hoveringTextChild,e)});u(this,"handleClose",()=>{this.editor.focus()});u(this,"handleDocumentMouseDown",t=>{t.button===0&&(document.addEventListener("mouseup",this.handleDocumentMouseUp),this.mouseDown=!0)});u(this,"handleDocumentMouseUp",()=>{document.removeEventListener("mouseup",this.handleDocumentMouseUp),this.mouseDown=!1,this.handleSelectionChange(this.editor)});u(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()}});u(this,"handleSelectionChange",Qt.default(t=>{if(d(QI,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())},50));this.editor=t;const e=t.options.componentsOptions.popover;this.toolbar=new rc([],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),_t.get(t).addListener("childChange",this.handleHoveringBlockChildChange),_t.get(t).addFilter(this),t.editorCommandProviders.registerCommandProvider(new BE(t)),t.editorCommandProviders.registerCommandProvider(new GI(t)),t.editorCommandProviders.registerCommandProvider(new YI(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),_t.get(this.editor).removeListener("childChange",this.handleHoveringBlockChildChange)}isInBlock(t,e){return t!==this.hoveringBlock?!1:!!(e.target&&e.target instanceof Node&&this.toolbar.popper&&vt(this.toolbar.popper,e.target))}bindEvents(){document.addEventListener("mousedown",this.handleDocumentMouseDown)}unbindEvents(){document.removeEventListener("mousedown",this.handleDocumentMouseDown)}update(){this.showTextToolbar()}showTextToolbar(){if(this._disableTextToolbar||!this.editor.isWritable())return;const e=this.editor.selection.range.getSelectedBlocks();if(e.length===0)return;const o=e[0];if(!o)return;if(e.length===1&&De(o.block)){this.showObjectToolbar();return}const r=this.editor.editorCommandProviders.getCommands(this.editor.selection.range),i=new Map;r.forEach(a=>{const h=a.groupIndex,f=i.get(h);f?f.push(a):i.set(h,[a])});const s=[[]],l=Array.from(i.entries()).sort((a,h)=>a[0]-h[0]);for(let a=0;a<l.length;a++){const[,h]=l[a];if(h.length===0)continue;let f=s[s.length-1];f.length>0&&f[f.length-1].groupIndex!==h[h.length-1].groupIndex&&(f=[],s.push(f)),f.push(...pc(h))}if(s.length===0){this.toolbar.close();return}this.toolbarType="text";const c=[];if(s.forEach((a,h)=>{const f=a.sort((m,C)=>{var v,w;return((v=m.order)!=null?v:0)-((w=C.order)!=null?w:0)});c.push(...f),h!==s.length-1&&c.push(KI)}),this.toolbar.updateItems(c),!this.toolbar.isVisible){const a=e[e.length-1],h=!this.editor.selection.range.isReverse()&&a!==o,f=h?a:o,m=fE(this.editor,f),C=_o(this.editor,f.block,"editor-quick-menu",m);this.toolbar.manualShow(C,{placement:h?"bottom":"top"})}}showObjectToolbar(){if(!this.hoveringBlock)return;const t=this.hoveringBlock,e=this.hoveringTextChild,o=bE(this.editor,t,e);!o.length||(this.toolbarType="object",this.toolbar.close(),this.toolbar.updateItems(o),this.toolbar.isVisible||this.toolbar.manualShow(e||rt(t),{placement:e?"bottom":"top"}))}static register(t){return t.addCustom("toolbar-handler",e=>new Wr(e))}static get(t){return t.getCustom("toolbar-handler")}}function $h(){let n=8;for(;n>0&&!document.querySelector(`div[data-style-heading='${n}']`);)n--;return n}const JI=y("quick-menu"),XI=[zu,Uu,Vu,qu,Wu,Gu,Zu,Yu],tx={Unordered:v0,Ordered:k0,Checkbox:C0,Quote:b0};function fs(n,t){const e=n;e.blockOptions=t,e.itemType="insert-block",n.children&&n.children.forEach(o=>fs(o,t))}function ex(n,t,e){n.getBlockData(t).heading===e?n.updateBlockData(t,{heading:null}):n.updateBlockData(t,{heading:e})}async function nx(n,t){const{containerId:e,blockIndex:o,item:r}=t,{value:i,id:s}=r,l=n.getBlockByIndex(e,o);if(d(JI,yt(n,l),"not an empty block"),s.startsWith("heading-"))ex(n,l,Number.parseInt(i!=null?i:"1",10)||1);else if(i==="ordered"||i==="unordered"||i==="checkbox"){const c=n.selection.range.focus;if(!c.isSimple())return null;const a=hl(n,l,"list",{offset:c.offset,data:{listType:i==="checkbox"?"unchecked":i}});a&&(n.deleteBlock(l),n.insertBlock(e,o,a.blockData))}else i==="quote"&&n.updateBlockData(l,{quoted:!0});return null}const w5=(n,t)=>n.undoManager.runInGroup(()=>nx(n,t));function Tc(n=1){var r;const t={name:"basic",insertBlockCommandItems:[]};let e=$h();e<=4?e=5:e<8&&(e+=1);let o=n;for(;o<=e;)(r=t.insertBlockCommandItems)==null||r.push({id:`heading-${o}`,icon:XI[o-1],name:S.t("quickMenu.basic.heading.title",{heading:String(o)}),order:o,group:"basics",value:String(o)}),o++;return t}function ox(){const n={name:"basic",insertBlockCommandItems:[]};return["Unordered","Ordered","Checkbox","Quote"].forEach((e,o)=>{var r;(r=n.insertBlockCommandItems)==null||r.push({id:`insert-${e.toLocaleLowerCase()}`,name:S.t(`quickMenu.basic.${e.toLocaleLowerCase()}`),icon:tx[e],value:e.toLocaleLowerCase(),group:"basics",order:10+o})}),n}function rx(){var e;const t={name:"basic",insertBlockCommandItems:[...Tc().insertBlockCommandItems||[]],handleInsertEmptyBlock:w5};return(e=t.insertBlockCommandItems)==null||e.forEach(o=>{fs(o,t)}),t}function ix(){const n=Tc(),t=ox();return{name:"basic",insertBlockCommandItems:[...n.insertBlockCommandItems||[],...t.insertBlockCommandItems||[]],handleInsertEmptyBlock:w5}}class B5{constructor(){u(this,"dataUrl","");u(this,"error",null)}destroy(){}setDataUrl(t){this.dataUrl=t}setError(t){this.error=t}}const sx=y("mathjax-converter"),lx="MathJax-script";async function cx(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 xo(e,lx)}function ax(){try{window.MathJax&&window.MathJax.texReset()}catch{}}async function E5(n,t){const e="mathjax2Svg";try{await Ue.lock(e),ax(),await cx(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 sx.error(o),o}finally{Ue.release(e)}}async function I5(n,t){const e=await E5(n,t);return e?await om(e,"image/svg+xml"):""}async function jh(n,t){const o=await E5(n,t),r=new File([o],"math.svg");return(await n.doc.uploadResource(r)).resourceId}const x5=y("edit-mathjax");class dx{constructor(){u(this,"editMathjaxPopup",null);u(this,"onChange",null);u(this,"tex","");u(this,"handleShow",()=>{setTimeout(()=>{this.getTextarea().focus()})});u(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))}});u(this,"handleKeyup",t=>{var e;t.isComposing||(t.key==="Escape"&&((e=this.editMathjaxPopup)==null||e.close()),this.handleChange(t.target.value))});u(this,"handleChange",Qt.default(t=>{var e;(e=this.onChange)==null||e.call(this,t)},300))}editMathjax(t,e,o){if(!this.editMathjaxPopup)this.editMathjaxPopup=new ic(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(x5,this.editMathjaxPopup,"no exists mathjax editor popup");const t=this.editMathjaxPopup.content.querySelector("textarea");return d(x5,t,"no textarea"),t}destroy(){var t;this.onChange=null,(t=this.editMathjaxPopup)==null||t.removeAllListeners()}}function S5(n,t,e,o){n.addCustom("mathjax-editor",()=>new dx).editMathjax(t,e.trim(),o)}function ux(){return{insert:" ",attributes:{id:N(),box:!0,type:"math",tex:" ",src:"",created:Date.now()}}}function Hh(n,t){const e=n.getBoxData(t),o=async r=>{if(!r.trim()){n.updateBoxData({...e,tex:r,src:null});return}try{await Ue.lock("convertAndUploadMathjax");const i=await jh(n,r);n.updateBoxData({...e,tex:r,src:i})}finally{Ue.release("convertAndUploadMathjax")}};S5(n,t,e.tex,o)}const hx=y("mathjax-box");function Fh(n,t){n.selection.caret.update();const e=t.target;!e||!(e instanceof HTMLElement)||n.domEvents.removeEventListener(e,null,Fh)}async function fx(n,t,e){try{if(!t.tex.trim())return;const o=await I5(n,t.tex),r=n.findBoxById(t.id);if(!r)return;const i=id(r);i.innerHTML="";const s=b("img",["mathjax"],i);s.src=o,e.setDataUrl(o),n.domEvents.addEventListener(s,"load",Fh)}catch(o){e.setError(o)}}function mx(n,t,e,o){const r=o,i=n.addCustom(`mathjax-box-${r.id}`,()=>new B5);if(r.src||i.dataUrl){const l=b("img",["mathjax"],e);l.src=n.doc.buildResourceUrl(r.src||i.dataUrl),n.domEvents.addEventListener(l,"load",Fh);return}i.error;let s=r.tex;s.trim()||(s=S.t("mathjax.emptyText")),b("span",["mathjax-tex-text"],e,s),fx(n,r,i)}function gx(n,t){const e={id:N(),box:!0,type:"math",tex:t,src:"",created:Date.now()};return jh(n,t).then(o=>{if(!n.findBoxById(e.id))return;const i={...e,src:o};n.updateBoxData(i)}).catch(o=>{hx.error(`failed to convert and upload mathjax: ${JSON.stringify(o)}`)}),e}function px(n,t,e){Hh(n,t)}const Dc={boxType:"math",updateBoxContent:mx,convertFrom:gx,handleClickBox:px};async function Cx(n,t,e){try{const o=t.embedData,r=await I5(n,o.mathjaxText),i=n.findBlockById(t.id);if(!i)return;const s=rt(i);s.innerHTML="";const l=b("img",["mathjax"],s);l.src=r,e.setDataUrl(r)}catch(o){e.setError(o)}}function bx(n,t){if(n.readonly||!t.target||!(t.target instanceof Node))return;const e=z(t.target);if(!e||!De(e)||Le(e)!=="math")return;const o=rt(e),r=o.querySelector("img")||o.querySelector("span.mathjax-tex-text");if(!r||!vt(r,t.target))return;const s=n.getBlockData(e).embedData;S5(n,r,s.mathjaxText,async l=>{const c=await jh(n,l),a={mathjaxText:l,src:c};n.updateEmbedData(e,a)})}function vx(n,t,e){const o=e.embedData,r=n.addCustom(`mathjax-block-${e.id}`,()=>new B5);if(n.domEvents.addEventListener(t,"click",bx),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),Cx(n,e,r)}function kx(n,t,e){if(!H(n,t))return null;const o=n.getBlockString(t).trim();if(!o||!o.startsWith("$$")||!o.endsWith("$$"))return null;const r=Wa(o,"$");if(!r)return null;const i={mathjaxText:r,src:""};return{blockData:{id:N(),type:"embed",embedType:"math",embedData:i}}}function yx(n){return{name:"Mathjax"}}function wx(n,t){const e=rt(t);n.domEvents.removeAllListeners(e)}const zh={embedType:"math",createEmbedContent:vx,getOptions:yx,convertFrom:kx,handleDeleteBlock:wx},fF="",Bx={mathjax:{emptyText:"\u7A7A\u7684\u516C\u5F0F",abstract:"\u516C\u5F0F"}},Ex={mathjax:{emptyText:"Empty Tex",abstract:"TeX"}};S.mergeLang({"zh-CN":Bx,"en-US":Ex});function Ix(n,t,e,o){const r=n.getBlockByIndex(t,e),i=n.getBlockText(r),{left:s}=fe(i,o);if(!wt(s).endsWith("$$$$"))return!1;const c=o-4,a=o,h={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,h),setTimeout(()=>{const f=n.getBoxById(h.id);Hh(n,f)})}),!0}class xx{handleAfterInsertText(t,e,o,r,i){return!!(i===" "&&Ix(t,e,o,r))}}const T5=y("inline-box-items");function Sx(n,t,e){return n.undoManager.runInGroup(()=>{var s;let o=n.getBlockByIndex(t,e);yt(n,o)||(o=n.insertTextBlock([],t,e));const r=ux();n.setBlockText(o,[r]);const i=(s=r.attributes)==null?void 0:s.id;return d(T5,i,"mathjax box id is empty"),setTimeout(()=>{const l=n.getBoxById(i);Hh(n,l)},100),o})}function Tx(n,t,e){let o=n.getBlockByIndex(t,e),r="bottom-start";return yt(n,o)||(r="top-start"),bc(n,{target:o,linkText:"",linkUrl:"",onFinished:(l,c)=>{n.undoManager.runInGroup(()=>{try{yt(n,o)||(o=n.insertTextBlock([],t,e));const a=_e(l,{link:c}),h=_e(" ",null),f=[a,h];n.insertTextToBlock(o,0,f),n.selection.selectBlock(o,ce(f)),n.focus()}catch(a){T5.error(a)}})},onClose:()=>{n.focus()},placement:r}),o}async function Dx(n,t){switch(t.item.id){case"insert-math":return Sx(n,t.containerId,t.blockIndex);case"insert-link":return Tx(n,t.containerId,t.blockIndex);default:return null}}function Lx(){return{name:"text",insertBlockCommandItems:[{id:"insert-math",name:S.t("quickMenu.inlineBox.math"),icon:mw,order:900,group:"common"},{id:"insert-link",name:S.t("quickMenu.inlineBox.link"),icon:p0,order:400,group:"common"}],handleInsertEmptyBlock:Dx}}const D5={basics:100,system:200,common:300,thirdParty:400};function Mx(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.forEach(i=>{const s=i.getCommands(n);e.push(...s.map(l=>({...l,itemType:"insert-block",commandProvider:i})))}),e}function Rx(n){var r;const t=[];n.editorBlocks.forEach(i=>{if(!i.getOptions)return;const s=i.getOptions(n);!s.insertBlockCommandItems||(s.insertBlockCommandItems.forEach(l=>{fs(l,s)}),t.push(...s.insertBlockCommandItems))});const e=Lx(),o=ix();return e.insertBlockCommandItems.forEach(i=>{fs(i,e)}),(r=o.insertBlockCommandItems)==null||r.forEach(i=>{fs(i,o)}),t.push(...e.insertBlockCommandItems),t.push(...o.insertBlockCommandItems),t.push(...Mx(n)),t}function Uh(n){const t=Rx(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||D5[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=i.group||"common",a=l in D5?S.t(`blockMenu.section.${l}`):l;r.push({id:`section-${s}`,name:a,type:"section",group:i.group,itemType:"insert-block"}),r.push(...i.items.map(h=>({...h})))}),r}function Ox(n,t,e){const o=n.getFocusedBlock();if(!o)return;const r=n.getParentContainer(o),i=U(r);let l=n.getBlockIndex(o);if(yt(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 L5=y("quick-menu"),Ax={id:"quick-menu",trigger:["/"]};class Lc{constructor(t,e=Ax){u(this,"suggest");u(this,"items");u(this,"maxHeading");u(this,"queryItems",async(t,e)=>{if(this.items.length===0?this.initMenuItems():this.refreshMenuItems(),e){const o=new Set,r=e.toLocaleLowerCase();return this.items.filter(i=>{var s;return i.type==="section"?!0:i.name.toLocaleLowerCase().indexOf(r)!==-1||l0(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});u(this,"onShow",(t,e,o,r)=>{const i=this.editor.getBlockByIndex(e,o);if(!Uo(i)){const s=z(j(i));if(s&&it(s)==="code")return!1}return!0});u(this,"onClickItem",(t,e)=>{const o=e;o.itemType==="insert-block"&&(d(L5,o.blockOptions||o.commandProvider,"invalid quick item, no block options or command provider"),d(L5,this.suggest.anchor,"invalid suggest, no anchor"),Ox(this.editor,o,this.suggest.anchor))});this.editor=t,this.options=e,this.items=[],this.maxHeading=$h(),this.suggest=new nh(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=Uh(this.editor);this.items=t}refreshMenuItems(){let t=null,e=0;const o=i=>{const{id:s}=i;return s.startsWith("heading-")},r=$h();if(r!==this.maxHeading){const i=rx().insertBlockCommandItems;for(let s=0;s<this.items.length;s++){const l=this.items[s];o(l)&&(t||(t=s),e++)}t&&e&&this.items.splice(t,e,...i),this.maxHeading=r}}}class Vh{constructor(t){u(this,"instance");u(this,"mousedown",!1);u(this,"currentInstance",null);u(this,"attributeName","");u(this,"attributeDesc","");u(this,"observer",null);u(this,"observerCallback",null);u(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});u(this,"handleDocumentMouseDown",()=>{this.mousedown=!0,this.editor.domEvents.addEventListener(document,"mouseup",this.handleDocumentMouseUp)});u(this,"handleDocumentMouseUp",()=>{this.mousedown=!1,this.editor.domEvents.removeEventListener(document,"mouseup",this.handleDocumentMouseUp)});u(this,"handleShown",t=>{this.currentInstance&&this.hide(),this.currentInstance=t,this.createObserver()});u(this,"handleHidden",()=>{this.destroyObserver(),this.currentInstance=null});u(this,"handleShow",t=>{var r;const e=t.reference;if(!e||!vt(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=Na.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=Qt.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 _x={"text/style-bold":"bold","text/style-italic":"italic","text/style-underline":"underline","text/style-line-through":"line-through","text/style-code":"code","text/style-subscript":"subscript","text/style-superscript":"superscript"};function Nx(n,t){const e=new Set(Object.keys(_x)),o=t.filter(i=>e.has(i.id));return pc(o)}function Mc(n,t){if(!n.isWritable())return!1;const e=n.selection.range,o=n.editorCommandProviders.getCommands(e),i=Nx(n,o).find(s=>s.id===`text/${t}`);return i?(n.editorCommandProviders.executeCommand(e,i,{}),Wr.get(n).update(),!0):!1}const qh={"CtrlOrCmd+B":n=>Mc(n,"style-bold"),"CtrlOrCmd+I":n=>Mc(n,"style-italic"),"CtrlOrCmd+U":n=>Mc(n,"style-underline"),"CtrlOrCmd+D":n=>Mc(n,"style-line-through")},Px={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",heading:"\u6807\u9898 {name}",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"}}},$x={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",heading:"Heading {name}",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"}}};S.mergeLang({"zh-CN":Px,"en-US":$x});const mF="";function Xo(n,...t){const e=Vn(...t);return e.classList.remove("editor-button"),e.classList.add("editor-text-button"),n.append(e),e}function M5(n){Cc(n).hide();const e=n.getCustom("table-border-bar");e==null||e.closeToolbar()}function jx(n){return b("div",["insert-column-button","drop-marker"],n)}const R5=y("row-height");function O5(n){const t=et.fromTable(n),e=n.rows;d(R5,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 R5.debug("heights",o.join(", ")),o}const go=y("table-border-bar-dom");function ms(n,t){d(go,jt(t),"invalid table block");const e=$t(t),o=wn(n,t),r=(a,h,f)=>{const m=b("div",["button-root",h],a),C=b("div",["button-container",h],m);m.setAttribute(`data-${h}-index`,`${f}`),b("span",["insert-indicator"],C),jx(C)},{selectedRows:i,selectedColumns:s}=ih(n,t),l=()=>{const a=o.querySelector(".table-border-bar-container.top");d(go,a,"no top border bar container");const h=b("div",["table-border-bar-container","top"],null),f=b("div",["table-border-bar","top"],h),m=JB(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 w=0;w<v;w++){const E=w===v-1?m[w]+2:m[w],L=b("span",["table-border-bar-cell","top"],f);s.has(w)&&L.classList.add("selected"),L.setAttribute("data-top-index",`${w}`),L.style.width=`${E}px`,n.selection.range.isSimple()&&r(f,"top",w+1)}Ii(a,h)},c=()=>{const a=o.querySelector(".table-border-bar-container.left");d(go,a,"no left border bar container");const h=b("div",["table-border-bar-container","left"],null),f=b("div",["table-border-bar","left"],h),m=O5(e);n.selection.range.isSimple()&&r(f,"left",0),Array.from(e.rows).forEach((C,v,w)=>{const E=b("span",["table-border-bar-cell","left"],f);i.has(v)&&E.classList.add("selected"),E.setAttribute("data-left-index",`${v}`);const L=v===w.length-1?m[v]+2:m[v];E.style.height=`${L}px`,n.selection.range.isSimple()&&r(f,"left",v+1)}),Ii(a,h)};l(),c()}function A5(n,t){const e=t.target;if(!(e instanceof Element))return;const o=z(e);d(go,o&&jt(o),"invalid table block"),ms(n,o),n.selection.caret.update()}function Wh(n,t){const e=t.target;if(!(e instanceof Element))return;const o=z(e);d(go,o&&jt(o),"invalid table block");const r=e.closest(".button-root");if(r){if(r.classList.contains("top")){const s=parseInt(r.getAttribute("data-top-index")||"0",10);t5(n,o,s),ms(n,o)}else if(r.classList.contains("left")){const s=parseInt(r.getAttribute("data-left-index")||"0",10);e5(n,o,s),ms(n,o)}return}const i=e.closest(".table-border-bar-cell");if(i){if(i.classList.contains("top")){const s=parseInt(i.getAttribute("data-top-index")||"0",10);uE(n,o,s,1,{reverse:!0})}else if(i.classList.contains("left")){const s=parseInt(i.getAttribute("data-left-index")||"0",10);hE(n,o,s,1,{reverse:!0})}}}function Gh(n,t){M5(n),t.preventDefault(),t.stopPropagation()}function Hx(n,t){d(go,jt(t),"invalid table block");const e=wn(n,t),o=b("div",["table-border-bar-container","top"],e),r=b("div",["table-border-bar-container","left"],e);ms(n,t),n.domEvents.addEventListener(rt(t),"scroll",A5),n.domEvents.addEventListener(o,"click",Wh),n.domEvents.addEventListener(r,"click",Wh),n.domEvents.addEventListener(o,"mousedown",Gh),n.domEvents.addEventListener(r,"mousedown",Gh)}function _5(n,t){if(!n.isWritable())return;if(wn(n,t).querySelector(".table-border-bar-container")){ms(n,t);return}Hx(n,t)}function N5(n,t){d(go,jt(t),"invalid table block"),wn(n,t).querySelectorAll(".table-border-bar-container").forEach(r=>{n.domEvents.removeEventListener(r,"click",Wh),n.domEvents.removeEventListener(r,"mousedown",Gh),r.remove()}),n.domEvents.removeEventListener(rt(t),"scroll",A5)}function Fx(n,t){d(go,jt(t),"invalid table block");const o=wn(n,t).querySelector(".table-border-bar-container.top");return o?o.getBoundingClientRect().height:0}class zx{constructor(t,e){u(this,"toolbar");u(this,"handleSelectionChange",(t,e)=>{e==="delete-columns"?(Fr(this.editor,this.tableBlock,!0,!0),zr(this.editor,this.tableBlock,!0,!0)):e==="delete-rows"?(Fr(this.editor,this.tableBlock,!0,!1),zr(this.editor,this.tableBlock,!0,!1)):(Fr(this.editor,this.tableBlock,!1),zr(this.editor,this.tableBlock,!1))});u(this,"handleClick",(t,e,o)=>{e.id==="delete-columns"?sh(this.editor.selection.range):e.id==="delete-rows"&&lh(this.editor.selection.range)});this.editor=t,this.tableBlock=e;const o=t.options.componentsOptions.popover;this.toolbar=new rc([],void 0,{overflowBoundary:o==null?void 0:o.overflowBoundary,refuseOverflow:!0}),this.toolbar.addListener("selectionChange",this.handleSelectionChange),this.toolbar.addListener("click",this.handleClick)}close(){this.toolbar.close()}update(){const{selectedColumns:t,selectedRows:e}=ih(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=Oo(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:"Delete columns",icon:h0};this.toolbar.updateItems([r]);const i=_o(this.editor,this.tableBlock,"editor-quick-menu",o);this.toolbar.manualShow(i,{placement:"top"})}else{const r={id:"delete-rows",name:"Delete rows",icon:h0};this.toolbar.updateItems([r]);const i=new DOMRect(o.left-15,o.top,o.width,o.height),s=_o(this.editor,this.tableBlock,"editor-quick-menu",i);this.toolbar.manualShow(s,{placement:"left"})}}destroy(){this.toolbar.destroy(),this.toolbar.removeAllListeners()}}const Rc=y("table-border-bar");class Ux{constructor(t,e){u(this,"toolbar");u(this,"resizeObserver");u(this,"handleReadonlyChanged",t=>{t.isWritable()?this.update():N5(this.editor,this.tableBlock)});u(this,"handleBlockUpdated",()=>{this.resizeObserver.disconnect(),setTimeout(()=>{const t=this.editor.getBlockById(G(this.tableBlock));this.resizeObserver.observe($t(t))})});u(this,"handleTableResize",()=>{!this.editor.isWritable()||(console.log("resize"),this.update())});this.editor=t,this.tableBlock=e,d(Rc,this.tableBlock,"no table block"),Rc.debug("create table border bar"),_5(this.editor,this.tableBlock),this.resizeObserver=new ResizeObserver(this.handleTableResize),this.resizeObserver.observe($t(this.tableBlock)),this.toolbar=new zx(this.editor,this.tableBlock),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}close(){this.toolbar.close()}destroy(){Rc.debug("destroy table border bar"),this.resizeObserver.disconnect(),N5(this.editor,this.tableBlock),this.toolbar.destroy(),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged)}update(){Rc.debug("update table border bar"),_5(this.editor,this.tableBlock),this.toolbar.update()}}const Vx=y("table-border-bar");class qx{constructor(t){u(this,"activeTableBar",null);u(this,"handleBlockDeleted",(t,e)=>{!this.activeTableBar||(e===this.activeTableBar.tableBlock||vt(e,this.activeTableBar.tableBlock))&&(this.activeTableBar.destroy(),this.activeTableBar=null)});u(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(jt(i)){const s=j(i),l=z(s);l&&(o=Ee(l))}else o=Ee(i)}else{const i=t.getBlockById(e.start.blockId),s=Ee(i),l=t.getBlockById(e.end.blockId),c=Ee(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 Ux(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(Vx,this.activeTableBar,"no active table bar"),this.activeTableBar.destroy(),this.activeTableBar=null)}}function P5(n,t){const e=n.addCustom("table-border-bar",o=>new qx(o));t==="update"&&e.update()}const be=y("table-cell-menu"),Wx="style-bg-color-";class Gx{constructor(t){u(this,"activeTableBlock",null);u(this,"targetButton",null);u(this,"manualMenu",null);u(this,"colorPaletteItem",null);u(this,"handlePrevent",(t,e)=>{e.stopPropagation()});u(this,"handleReadonlyChanged",t=>{t.isWritable()||this.hide()});u(this,"handleSelectionChanged",t=>{const e=t.selection.range;let o=null;if(e.isCollapsed()&&e.isSimple()){const r=t.getBlockById(e.start.blockId);if(jt(r)){const i=j(r),s=z(i);s&&(o=Ee(s))}else o=Ee(r)}else{const r=t.getBlockById(e.start.blockId),i=Ee(r),s=t.getBlockById(e.end.blockId),l=Ee(s);i===l&&(o=i)}if(this.hide(),this.activeTableBlock!==o&&(this.activeTableBlock=o),this.activeTableBlock){const r=et.fromBlock(this.activeTableBlock),{end:i}=e;let s=null;e.isCollapsed()?s=this.getCellByChildBlockId(r,i.blockId):i instanceof Ye&&(t.getBlockById(i.blockId)===this.activeTableBlock?s=r.getCellByContainerId(i.childContainerId):s=this.getCellByChildBlockId(r,i.blockId)),s&&this.editor.isWritable()&&this.showCellMenuButton(s)}});u(this,"handleBeforePopupPalette",()=>{var e;const t=this.getSelectedBkgColorIndex();(e=this.colorPaletteItem)==null||e.palette.setColor("backgroundColor",t)});u(this,"createBkgColorItem",()=>{const t=b("div",["cell-background-color-item"],null);b("span",[],t,S.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=u0,t});u(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":lh(_0(this.editor,this.activeTableBlock,!1));break;case"delete-select-col":sh(_0(this.editor,this.activeTableBlock,!0));break;case"merge-cell":R0(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":yB(this.editor,this.activeTableBlock,o==="show-border");break;case"show-chart":xB(this.editor,this.activeTableBlock,o==="show-chart"),Ch(this.editor,this.activeTableBlock,{updateNow:!0});break}});u(this,"handleSelectionChange",(t,e)=>{d(be,this.activeTableBlock,"no target table block"),e==="cell-background-color"&&this.handleBeforePopupPalette(),e==="delete-select-row"?(Fr(this.editor,this.activeTableBlock,!0,!1),zr(this.editor,this.activeTableBlock,!0,!1)):e==="delete-select-col"?(Fr(this.editor,this.activeTableBlock,!0,!0),zr(this.editor,this.activeTableBlock,!0,!0)):(Fr(this.editor,this.activeTableBlock,!1),zr(this.editor,this.activeTableBlock,!1))});u(this,"handleClick",()=>{var t;d(be,this.activeTableBlock,"no target table block"),d(be,this.targetButton,"no target button"),M5(this.editor),lt(this.targetButton,"active")?(F(this.targetButton,"active"),(t=this.manualMenu)==null||t.close()):(M(this.targetButton,"active"),this.manualMenu?this.manualMenu.updateItems(this.createCommandMenu()):(this.manualMenu=new Wo(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&&F(this.targetButton,"active")})),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&&(F(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=z(r);if(d(be,i,"no parent block"),$t(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=Fu,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);ah(this.editor,this.activeTableBlock,{col:o,row:r})}else dh(this.editor.selection.range)}}getSelectedBkgColorIndex(){var r;d(be,this.activeTableBlock,"no target table block");const t=EB(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(Wx.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=M0(this.editor,this.activeTableBlock,this.editor.selection.range);let o=this.editor.selection.range;if(o.isSimple()){const h=qn(this.editor,this.activeTableBlock,o.start);o=Vt(this.editor,{anchor:h,focus:h})}const r=L0(this.editor,this.activeTableBlock,o),i=t.hasRowTitle,s=t.hasColTitle,l=t.isStripeStyle,c=t.noBorder,a=t.chart;return this.colorPaletteItem=new I0("cell-background-color",{color:!1}),this.colorPaletteItem.palette.on("onClick",(h,f)=>{var m;switch(d(be,this.activeTableBlock,"no target table block"),h){case"clearColor":$0(this.editor,this.activeTableBlock,-1);break;case"backgroundColor":$0(this.editor,this.activeTableBlock,f);break}(m=this.manualMenu)==null||m.close()}),[{id:"cell-background-color",name:S.t("table.cellBackground"),element:this.createBkgColorItem(),children:[this.colorPaletteItem]},{id:"separator",name:"",type:"separator"},{id:"merge-cell",name:S.t("table.mergeCell"),states:e?[]:["disabled"]},{id:"split-cell",name:S.t("table.splitCell"),states:r?[]:["disabled"]},{id:"separator",name:"",type:"separator"},{id:"delete-select-row",name:S.t("table.deleteSelectRow")},{id:"delete-select-col",name:S.t("table.deleteSelectCol")},{id:"separator",name:"",type:"separator"},{id:"table-config",name:S.t("table.tableConfigKey"),children:[{id:"row-title",name:S.t("table.tableConfig.rowTitle"),states:i?["checked"]:[]},{id:"col-title",name:S.t("table.tableConfig.colTitle"),states:s?["checked"]:[]},{id:"stripe-style",name:S.t("table.tableConfig.stripeStyle"),states:l?["checked"]:[]},{id:"hide-border",name:c?S.t("table.tableConfig.showBorder"):S.t("table.tableConfig.hideBorder"),value:c?"show-border":"hide-border"},{id:"show-chart",name:a?S.t("table.tableConfig.hideChart"):S.t("table.tableConfig.showChart"),value:a?"hide-chart":"show-chart"}]}]}handleRowTitle(t){d(be,this.activeTableBlock,"no target table block"),t?bB(this.editor,this.activeTableBlock):CB(this.editor,this.activeTableBlock)}handleColTitle(t){d(be,this.activeTableBlock,"no target table block"),t?pB(this.editor,this.activeTableBlock):gB(this.editor,this.activeTableBlock)}handleStripeStyle(t){d(be,this.activeTableBlock,"no target table block"),t?kB(this.editor,this.activeTableBlock):vB(this.editor,this.activeTableBlock)}}function $5(n){n.addCustom("table-cell-menu",t=>new Gx(t))}const Oc=y("table-container");function Zh(n){const t=n.closest("td");return d(Oc,t,"no parent cell for a table cell container"),t}function j5(n){const t=$t(n);return Array.from(t.querySelectorAll(':scope > tbody > tr > td > [data-type="editor-container"].child'))}function Yh(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(Oc,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(Oc,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(Oc,!1,`invalid navigation type: ${e}`)}const Zx=12,Yx=90,Ac=23,H5=2;class Qx{constructor(t){u(this,"scrollTableBlock",null);u(this,"autoScrollDir",null);u(this,"autoScrollTimer",null);u(this,"handleMouseDown",t=>{const e=document.elementFromPoint(t.clientX,t.clientY);if(e&&e instanceof HTMLElement){const o=z(e);if(o&&vt(this.editor.rootContainer,o)){const r=Ee(o);r&&(this.scrollTableBlock=r,document.addEventListener("mousemove",this.handleAutoScroll))}}});u(this,"handleAutoScroll",T9.default(t=>{if(this.scrollTableBlock){const e=this.editor.getCustom(ho(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));u(this,"handleMouseUp",()=>{document.removeEventListener("mousemove",this.handleAutoScroll),setTimeout(()=>{this.scrollTableBlock=null})});u(this,"handleSelectionChanged",t=>{const e=t.selection.range;if(e.isCollapsed()&&e.isSimple()){const o=t.getBlockById(e.start.blockId),r=Ee(o);if(r){const i=t.getCustom(ho(r)),s=i.rootElement.getBoundingClientRect(),l=Ze(t,o,e.start);if(s.left>l.left){const c=e.start.offset===0?Zx:H5;i.rootElement.scrollLeft-=s.left-l.left+c}else if(l.right>s.right){const c=e.start.offset===0?Yx:H5;i.rootElement.scrollLeft+=l.right-s.right+c}}}else{const o=t.getBlockById(e.start.blockId),r=Ee(o),i=t.getBlockById(e.end.blockId),s=Ee(i);if(r&&r===s){const l=t.getCustom(ho(r)),c=l.rootElement.getBoundingClientRect();let a=null;if(e.isSimple())a=e.isReverse()?Ze(t,o,e.start):Ze(t,i,e.end);else{const h=Zh(Cr(t,e.start.childContainerId)),f=Zh(Cr(t,e.end.childContainerId));a=e.isReverse()?h.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)}}});u(this,"handleScroll",t=>{rB(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(ho(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),h=Math.max(c.top,0);this.autoScrollDir==="left"&&(o.scrollLeft-=Ac,o.scrollLeft<=0&&this.clearAutoScroll()),this.autoScrollDir==="right"&&(o.scrollLeft+=Ac,o.scrollLeft>=o.scrollWidth-o.offsetWidth&&this.clearAutoScroll()),this.autoScrollDir==="bottom"&&(r.scrollTop+=Ac,(r.scrollTop>=r.scrollHeight-s||i.bottom<=a)&&this.clearAutoScroll()),this.autoScrollDir==="top"&&(r.scrollTop-=Ac,(r.scrollTop<=0||i.top>=h)&&this.clearAutoScroll())}},100))}destroy(){document.removeEventListener("mousedown",this.handleMouseDown),document.removeEventListener("mouseup",this.handleMouseUp),this.editor.removeListener("selectionChanged",this.handleSelectionChanged)}}function F5(n){return n.addCustom("table-scroll-events",t=>new Qx(t))}const Bn=y("create-content");function z5(n,t,e){const o=new rh(e),r=e.rows,i=e.cols;d(Bn,r>=1,`invalid rows: ${r}`),d(Bn,i>=1,`invalid cols: ${i}`),d(Bn,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]||mc}px`}const a=b("tbody",[],s);let h=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(Bn,v.colSpan>1||v.rowSpan>1,"virtual cell should have colSpan or rowSpan");else{const w=e.children[h],E=b("td",[],m);v.colSpan>1&&(E.colSpan=v.colSpan),v.rowSpan>1&&(E.rowSpan=v.rowSpan);const L=e[ss(w)];L&&M(E,L),C===0&&e.hasColTitle&&M(E,O0.COL_TITLE_ITEM),n.createChildContainer(t,E,w),h+=1}}}return d(Bn,h===e.children.length,"container count mismatch"),e.noBorder&&M(s,"no-border"),e.chart&&M(s,"editor-table-chart"),e.isStripeStyle&&M(s,"stripe"),e.hasRowTitle&&M(s,"row-title"),e.hasColTitle&&M(s,"col-title"),s}function Kx(n,t,e,o,r){d(Bn,r.type==="table","not table data"),d(Bn,U(e)===t[t.length-1].containerId,"invalid path");const i=r,s=no(o,"div");try{const l=b("div",[],null);l.setAttribute("data-type","table-content");const c=z5(n,t,i);c.classList.add("drag-preview-element"),l.appendChild(c),J0(n),o5(n),P5(n,"create"),$5(n),zy(n,bh);const a=n.getComponentOptions("table"),h=n.addCustom(ho(o),()=>YB());h.init({parentElement:s,childElement:l,safeRightSpace:80,safeLeftSpace:40,parentContainer:Ct(e)?n.scrollContainer:e,locatingContainer:Ct(e)?(a==null?void 0:a.locatingContainer)||n.parent:e,paddingLeft:fh+is,paddingTop:fh+is,paddingBottom:is/2,paddingRight:is/2});const f=F5(n);h.on("scroll",f.handleScroll),setTimeout(()=>{DB(n,o)})}catch{const c=`invalid table data: ${JSON.stringify(i)}`;Bn.error(c);const a=b("div",["error"],s);a.innerText=c}return s}function Jx(n,t,e){d(Bn,e.type==="table","not table data");const o=e,r=rt(t);try{const i=$t(t),s=Ro(t),l=z5(n,s,o);l.classList.add("drag-preview-element"),i.insertAdjacentElement("afterend",l),i.remove(),J0(n),o5(n),P5(n,"update"),$5(n),bh(n,t)}catch{const s=`invalid table data: ${JSON.stringify(o)}`;Bn.error(s);const l=b("div",["error"],r);l.innerText=s}}function Xx(n,t){let e,o,r=!1;if([...t].every(m=>m==="|")?(o=t.length,e=Array(o).fill(""),r=!0):(e=Wa(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(Cn(n.doc,m===0?C:""))});const c=Array(s).fill(mc),a=l[r?0:s],h=n.doc.getContainerBlocks(a)[0].id;return{blockData:{id:N(),type:"table",rows:i,cols:s,children:l,colsWidth:c},focusBlockId:h}}function tS(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 h=0;h<o;h++)r.push(Cn(n.doc));const i=Array(o).fill(mc),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 Qh=y("table-selection-to-doc");function U5(n,t){const{start:e,end:o,block:r}=t,i=it(r);d(Qh,i==="table",`invalid block type: ${i}`);const s=n.getBlockData(r);if(e.isSimple()&&o.isSimple()){const V=s.children;d(Qh,V,"no table children");const nt=V[0],ot=V[V.length-1],ut=bt(r,nt),dt=bt(r,ot);return U5(n,{block:t.block,start:ut,end:dt})}d(Qh,!e.isSimple()&&!o.isSimple(),"invalid block pos type");const l=et.fromBlock(r),{fromCol:c,toCol:a,fromRow:h,toRow:f}=sn(r,e,o),m={},C=[],v=n.doc.toJSON();let w={};l.sub({row:h,col:c},{row:f,col:a}).forEach((V,nt)=>{V.forEach((ot,ut)=>{const dt=ot.containerId;if(C.indexOf(dt)!==-1)return;C.push(dt);let Et;if(ot.virtual){const te=l.getCellByContainerId(ot.containerId),Fe=c+ut;let bo=te.col+te.colSpan-1;bo>a&&(bo=a);const cr=bo-Fe+1;cr>1&&(m[`${dt}_colSpan`]=cr);const ar=h+nt;let vo=te.row+te.rowSpan-1;vo>f&&(vo=f);const ha=vo-ar+1;ha>1&&(m[`${dt}_rowSpan`]=ha),Et=ro()}else{if(Et=Zd(n.editorBlocks,v,dt),ot.col+ot.colSpan>a+1){const te=a-ot.col+1;te>1&&(m[`${dt}_colSpan`]=te)}else ot.colSpan>1&&(m[`${dt}_colSpan`]=ot.colSpan);if(ot.row+ot.rowSpan>f+1){const te=f-ot.row+1;te>1&&(m[`${dt}_rowSpan`]=te)}else ot.rowSpan>1&&(m[`${dt}_rowSpan`]=ot.rowSpan)}const{root:re,...Xn}=Et.blocks;w={...w,...Xn,[dt]:re}})});const L=ds($t(r)).slice(c,a+1);return{blocks:{root:[{id:N(),type:i,children:C,colsWidth:L,rows:f-h+1,cols:a-c+1,...m}],...w},meta:{},comments:{}}}function eS(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 nS(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 oS(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 rS(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 iS(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,!eS(n,l)){l.top--,c=!0;continue}if(!nS(n,l)){l.left--,c=!0;continue}if(!oS(n,l)){l.bottom++,c=!0;continue}if(!rS(n,l)){l.right++,c=!0;continue}}while(c);return l}function sS(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(O=>O.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),h=Math.min(s.col,l.col),f=Math.max(s.col,l.col),m=iS(i,{row:c,col:h},{row:a,col:f}),C=r.getCell({row:m.top,col:m.left}),v=r.getCell({row:m.bottom,col:m.right}),w=r.getCell({row:m.top,col:m.right}),E=r.getCell({row:m.bottom,col:m.left});let L,x;return s.row<=l.row?s.col<=l.col?(L=C,x=v):(L=w,x=E):s.col<l.col?(L=E,x=w):(L=v,x=C),console.log(`move ${L.col}, ${L.row}, -> ${x.col}, ${x.row}`),{anchor:bt(t,L.containerId),focus:bt(t,x.containerId)}}function V5(n,t,e){if(e.isSimple())return[$t(t).getBoundingClientRect()];const o=$t(t),r=o.getBoundingClientRect(),{fromCol:i,fromRow:s,toCol:l,toRow:c}=sn(t,e.start,e.end),a=ds(o),h=a.slice(0,i).reduce((w,E)=>w+E,0),f=h+a.slice(i,l+1).reduce((w,E)=>w+E,0),m=O5(o);let C=m.slice(0,s).reduce((w,E)=>w+E,0);const v=C+m.slice(s,c+1).reduce((w,E)=>w+E,0);if(s===0){const w=Fx(n,t);C-=w}return[new DOMRect(r.left+h,r.top+C,f-h,v-C)]}y("table-size");const lS=40;function _c(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 cS(n,t,e){const o=ud(n,e.container);return o!==void 0?o+_c(t):lS*e.colSpan-_c(t)}function aS(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=cS(n,t,l);const a=qm(l.container,{withPadding:!0});a&&a>c&&(c=a),r+=c+_c(t)}return r}function dS(n,t){const e=$t(t),o=et.fromTable(e);let r=0;for(let s=0;s<o.rowCount;s++)r=Math.max(r,aS(n,e,o,s));const i=_c(e);return r+=i,r}const Gn=y("table-creator");async function uS(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=tS(n,{cols:o,rows:r});if(!i)return null;const{blockData:s,focusBlockId:l}=i;return n.insertBlock(t.containerId,t.blockIndex,s,Lt(n,l,0))})}class hS{constructor(){u(this,"id","insert-table");u(this,"name","Create table");u(this,"element");u(this,"closeable",null);u(this,"colCount");u(this,"rowCount");u(this,"setCloseable",t=>{this.closeable=t});u(this,"destroy",()=>{this.closeable=null});u(this,"getTableCreatorCellId",(t,e)=>`table-creator-cell-${t}-${e}`);u(this,"handleTableCreatorClick",t=>{var m,C;t.preventDefault(),t.stopPropagation();const e=t.target;d(Gn,e instanceof HTMLElement,"invalid event target");const o=e.closest(".table-creator");d(Gn,o,"no table creator");const r=o.querySelectorAll(".active");if(r.length===0)return;const s=r[r.length-1].id;d(Gn,s,"no cell id");const l="table-creator-cell-";if(!s.startsWith(l))return;const a=s.substring(l.length).split("-");d(Gn,a.length===2,"invalid cell id");const h=Number.parseInt(a[0],10)+1,f=Number.parseInt(a[1],10)+1;Gn.debug(`${h}, ${f}`),this.colCount=f,this.rowCount=h,(m=this.closeable)==null||m.click(this,this.element),(C=this.closeable)==null||C.close(),this.handleTableCreatorLeave()});u(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&&F(r,"active")}});u(this,"handleTableCreatorCellEnter",t=>{const e=t.target;d(Gn,e instanceof HTMLElement,"invalid event target");const o=e.id,r="table-creator-cell-";d(Gn,o.startsWith(r),"invalid cell id");const s=o.substring(r.length).split("-");d(Gn,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 h=0;h<9;h++){const f=this.getTableCreatorCellId(a,h),m=document.getElementById(f);d(Gn,m,"no cell"),a<=l&&h<=c?M(m,"active"):F(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 fS(n){return n.addCustom("table-creator-item",()=>new hS)}const Nc=y("table-block");function mS(n){return 1}function gS(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t))return null;if(r instanceof HTMLTableCellElement){const l=$t(t);if(x0(l).indexOf(r)!==-1){const a=os(r),h=bt(t,U(a));return new Qe(n,{anchor:h,focus:h})}}if(!mn(r))return null;const i=r;if(j5(t).indexOf(i)===-1)return null;const s=bt(t,U(i));return new Qe(n,{anchor:s,focus:s})}function pS(n,t,e,o){return null}function CS(n,t){return n.getBoundingClientRect()}function q5(n,t,e,o){if(e.isSimple()){d(Nc,o.isSimple(),"from is simple position but to is not simple position"),Nc.debug("full select table"),M(t,"full-selected");return}d(Nc,!o.isSimple(),"from is complex position but end is simple position");const r=qn(n,t,e),i=qn(n,t,o);d(Nc,r.blockId===i.blockId,"only allow update one table selection"),wB(n,r,i).forEach(l=>{const c=Zh(l);M(c,"selected")})}function bS(n){n.rootContainer.querySelectorAll('[data-type="editor-block"][data-block-type="table"]').forEach(t=>{F(t,"full-selected"),t.querySelectorAll("td.selected").forEach(e=>{F(e,"selected")})})}function vS(n,t){return S0(t)?j5(t):[]}function kS(n,t,e,o,r){return Yh(t,e,o,r)}function yS(n,t){return dS(n,t)}function wS(n,t){return H(n,t)?Xx(n,n.getBlockString(t).trim()):null}function BS(n){return{name:"TableBlock",insertBlockCommandItems:[{id:"insert-table",name:S.t("table.title"),order:200,icon:gw,children:[fS(n)],group:"common"}],handleInsertEmptyBlock:uS}}function ES(n,t,e){return Jx(n,t,e),setTimeout(()=>{const o=n.selection.range;o.isSimple()?n.selection.caret.update():q5(n,t,o.start,o.end)}),!0}function IS(n,t){let e=0;const{selectedColumns:o}=ih(n,t);if(o.size>0){const{fromCol:i,toCol:s}=sn(t,n.selection.range.start,n.selection.range.end),l=et.fromBlock(t);(i!==0||s!==l.colCount-1)&&(e=60)}const r=V5(n,t,n.selection.range)[0];return new DOMRect(r.left,r.top+e,r.width,r.height-e)}function xS(n,t){Uy(n,bh);const e=n.findCustom(ho(t));if(e){const o=F5(n);e.off("scroll",o.handleScroll),e.destroy()}}function SS(){return{abstract:`[${S.t("table.abstract")}]`}}const gs={blockType:"table",blockKind:"complex",enableKeyboardSelect:!0,createBlockContent:Kx,getBlockTextLength:mS,getRangeFromPoint:gS,moveCaret:pS,getCaretRect:CS,updateSelection:q5,clearSelection:bS,getChildContainers:vS,getNextContainer:kS,getMinWidth:yS,getSelectedContainers:gh,convertFrom:wS,adjustSelectionPos:sS,getClientRects:V5,selectionToDoc:U5,getOptions:BS,getTextToolbarReferenceClient:IS,handleUpdateBlock:ES,handleDeleteBlock:xS,getBlockProperties:SS},TS={table:{cellBackground:"\u5355\u5143\u683C\u80CC\u666F\u8272",deleteSelectRow:"\u5220\u9664\u6240\u9009\u884C",deleteSelectCol:"\u5220\u9664\u6240\u9009\u5217",mergeCell:"\u5408\u5E76\u5355\u5143\u683C",splitCell:"\u62C6\u5206\u5355\u5143\u683C",tableConfigKey:"\u8868\u683C\u8BBE\u7F6E",tableConfig:{rowTitle:"\u884C\u6807\u9898",colTitle:"\u5217\u6807\u9898",stripeStyle:"\u6761\u7EB9\u6837\u5F0F",hideBorder:"\u9690\u85CF\u8868\u683C\u7EBF",showBorder:"\u663E\u793A\u8868\u683C\u7EBF",showChart:"\u663E\u793A\u56FE\u8868",hideChart:"\u9690\u85CF\u56FE\u8868"},title:"\u8868\u683C",abstract:"\u8868\u683C"}},DS={table:{cellBackground:"Cell background",deleteSelectRow:"Delete rows",deleteSelectCol:"Delete columns",mergeCell:"Merge cells",splitCell:"Split cell",tableConfigKey:"Table setting",tableConfig:{rowTitle:"Row Title",colTitle:"Col Title",stripeStyle:"Stripe style",hideBorder:"Hide border",showBorder:"Show border",showChart:"Show chart",hideChart:"Hide chart"},title:"Table",abstract:"Table"}};S.mergeLang({"zh-CN":TS,"en-US":DS});const pF="",W5=y("table");function G5(n,t){const e=oh(t);if(!e)return;const o=z(e);d(W5,o&&jt(o),"not a table block");const r=Yh(o,e,"ArrowRight");if(!r){const s=ht(o);return s?(n.selection.selectBlock(s,0),!0):G5(n,o)}const i=Kt(r);return n.selection.selectBlock(i,0),!0}function LS(n){if(!n.isWritable())return!1;const t=n.getFocusedBlock();if(!!t)return G5(n,t)}function Z5(n,t){const e=oh(t);if(!e)return;const o=z(e);d(W5,o&&jt(o),"not a table block");const r=Yh(o,e,"ArrowLeft");if(!r){const s=gt(o);return s?(n.selection.selectBlock(s,Z(n,s)),!0):Z5(n,o)}const i=Gt(r);return n.selection.selectBlock(i,Z(n,i)),!0}function MS(n){if(!n.isWritable())return!1;const t=n.getFocusedBlock();if(!!t)return Z5(n,t)}const Kh={Tab:LS,"Shift+Tab":MS},RS=`<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
362
362
|
<g>
|
|
363
363
|
<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"/>
|
|
364
364
|
<animateTransform attributeType="xml" attributeName="transform" type="rotate" values="0 12 12.5;360 12 12.5" dur="2s" repeatCount="indefinite" />
|
|
365
365
|
</g>
|
|
366
|
-
</svg>`,Jh=y("webpage");class OS{constructor(t,e){u(this,"currentSrc","");u(this,"loading",null);u(this,"handleMaskMouseMove",(t,e)=>{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)});u(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(vt(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(Jh,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(Jh,this.loading,"not created"),this.currentSrc===o.src)return;const r=e.querySelector(".editor-preview-iframe");d(Jh,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=RS,{show(){t.append(e)},hide(){const r=t.querySelector(":scope > .editor-preview-iframe-loading");!r||r.remove()}}}getExistsMask(t){return At(t).querySelector(".webpage-mask")}createMask(t,e){const o=At(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 AS(n,t){b("div",["resize-gripper",t],n).setAttribute("data-resize-type",t)}function Xh(n){return At(n).querySelector(".block-resizer")}function _S(n){const t=Xh(n);t&&F(t,"active")}function Y5(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 NS(n,t,e,o){const r=Xh(n);if(r)return M(r,"active"),Y5(n,t,r),r;const i=At(n),s=b("div",["block-resizer"],i);return Y5(n,t,s),e.resize.forEach(l=>{AS(s,l)}),s.addEventListener("mousedown",o),M(s,"active"),s}function Q5(n,t){const e=Xh(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 CF="",PS=y("block-resizer");class Pc extends Wt.TypedEmitter{constructor(e,o){super();u(this,"resizableElement");u(this,"block",null);u(this,"startRect",null);u(this,"startPos",null);u(this,"resizeType",null);u(this,"enabled",!1);u(this,"handleMouseDown",e=>{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,Ei(window.getComputedStyle(r).cursor))});u(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:h}=s;(this.resizeType==="bottom"||this.resizeType==="bottom-left"||this.resizeType==="bottom-right")&&(h+=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=h>l?h-l:0,C=new DOMRect(c,l,f,m);this.emit("resizing",this,C),Q5(this.block,o)});u(this,"handleMouseUp",e=>{if(e.button!==0)return;Ei(""),this.unbindEvents(),this.emit("resized",this);const o=this.getResizableElement();!o||!this.block||Q5(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||(_S(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?rt(this.block):null}createResizer(){const e=this.getResizableElement();!e||!this.block||(d(PS,vt(this.block,e),"not a block child element"),NS(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 K5(n){return n&&De(n)&&Le(n)==="webpage"}const $S=1e3,jS=100;class HS{constructor(t){u(this,"currentBlockElement",null);u(this,"resizing",!1);u(this,"handleHoveringBlockChange",(t,e)=>{this.resizing||!this.editor.isWritable()||(e&&K5(e)&&this.disableBlockResize(e),t&&K5(t)&&this.enableBlockResize(t))});u(this,"handleResizing",(t,e)=>{this.resizing=!0;const o=t.getBlock();if(!o)return;const r=Math.max(Math.min(e.height,$S),jS);o.style.height=`${r}px`,M(o,"resizing")});u(this,"handleResized",t=>{this.resizing=!1;const e=t.getBlock();if(!e)return;F(e,"resizing");const o=this.editor.getBlockData(e),r=e.getBoundingClientRect().height;this.editor.updateBlockData(e,{...o,height:r})});this.editor=t,_t.get(t).addListener("change",this.handleHoveringBlockChange)}destroy(){this.currentBlockElement=null,_t.get(this.editor).removeListener("change",this.handleHoveringBlockChange)}disableBlockResize(t){const e=this.editor.findCustom(`${G(t)}-resizer`);e&&e.disableResize()}enableBlockResize(t){const e=this.editor.addCustom(`${G(t)}-resizer`,()=>new Pc(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 bF="",FS=y("editor-dialog");function zS(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=c0,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 US extends sc{constructor(e,o){super(zS(e,o),o);u(this,"_options");u(this,"getReferenceClientRect",()=>{const e=document.documentElement.clientHeight/2,o=document.documentElement.clientWidth/2,r=this.getCommandBarRoot();d(FS,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)});u(this,"onOk",async()=>{var e,o;try{await((o=(e=this._options).onOk)==null?void 0:o.call(e)),this.destroy()}catch{}});u(this,"onClose",()=>{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.onOk),s==null||s.addEventListener("click",this.onClose),i==null||i.addEventListener("click",this.onClose),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.onOk),o==null||o.removeEventListener("click",this.onClose),r==null||r.removeEventListener("click",this.onClose),super.destroy()}}const J5=()=>[{name:S.t("webpage.bilibili"),id:"insert-bilibili",icon:vw,group:"thirdParty"},{name:S.t("webpage.youku"),id:"insert-youku",icon:kw,group:"thirdParty"},{name:S.t("webpage.figma"),id:"insert-figma",icon:yw,group:"thirdParty"},{name:S.t("webpage.modao"),id:"insert-modao",icon:ww,group:"thirdParty"},{name:S.t("webpage.tencent"),id:"insert-tencent",icon:Bw,group:"thirdParty"},{id:"insert-webPage",name:S.t("webpage.title"),icon:Ew,group:"common",order:1e3}];function t1(n){return n==="insert-webPage"}async function VS(n,t){return n.doc.externalDoc.recognizeLink?n.doc.externalDoc.recognizeLink(t):null}function qS(n){return n&&!n.startsWith("http://")&&!n.startsWith("https://")&&!n.startsWith("//")?`//${n}`:n}async function WS(n){if(!n)throw new Error(S.t("webpage.dialog.errorEnterUrl"));let t=n;t.startsWith("//")&&(t=`http:${t}`);try{new URL(t)}catch{throw new Error(S.t("webpage.dialog.unsupportedUrl"))}}async function GS(n,t){const e=t.item.id,o=J5().find(l=>l.id===e),r=b("div",["webpage-content"],null);if(t1(e)){const l=b("div",["help-container"],r),c=b("div",["help-content"],l),a=b("span",["help-icon"],c);a.innerHTML=f0,b("span",[],c,S.t("webpage.dialog.helpContent"))}const{getInputValue:i,setFieldError:s}=th(r,{required:!0,label:S.t("webpage.dialog.label"),placeholder:S.t("webpage.dialog.placeholder")});if(!t1(e)){const l=b("div",["help-link-container"],r),c=b("a",["help-link-content"],l);b("span",[],c,S.t("webpage.dialog.helpLink"));const a=b("span",["help-link-icon"],c);a.innerHTML=g0;const h=n.getComponentOptions("webpage");c.href=(h==null?void 0:h.helpLink)||"",c.target="_blank"}try{const l=await new Promise(a=>{new US(r,{title:S.t("webpage.dialog.title",{name:(o==null?void 0:o.name)||""}),async onOk(){var m;const f=qS(i());try{await WS(f);const C=await VS(n,f);a((C==null?void 0:C.url)||"")}catch(C){if(((m=C==null?void 0:C.responseData)==null?void 0:m.statusCode)===415)if(t1(e))a(f);else throw s(S.t("webpage.dialog.unsupportedUrl")),C;else throw s(C.message||""),C}}}).show()}),c={id:N(),type:"embed",embedType:"webpage",embedData:{src:l}};return n.insertBlock(t.containerId,t.blockIndex,c)}catch{return null}}const X5=y("embed-block-properties");function e1(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 n1{constructor(t,e){u(this,"group","hovering-toolbar");u(this,"_commands",[{id:"edit",name:"Edit",icon:Ju},{id:"add-comment",name:"Add Comment",icon:ns}]);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"){e1(t,e)||X5.error("failed to add comment to block");return}X5.error(`unknown command: ${JSON.stringify(o)}`),alert(o.id)}}}function o1(n,t,e){return{blockCommands:{"hovering-toolbar":new n1(n,e)}}}function ZS(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 YS(n,t){const e=n.getBlockData(t),{embedData:o}=e,r=o.src;return window.open(r,"_blank"),!0}function QS(n,t){const e=o1(n,t,{presetIds:["add-comment"],extCommands:[{id:"refresh",name:"Refresh page",icon:pw},{id:"open-page",name:"Open the original page",icon:g0}],handleExecuteCommand:(r,i,s)=>{switch(s.id){case"refresh":return ZS(i);case"open-page":return YS(r,i)}return!1}}),o=`[${S.t("webpage.abstract")}]`;return{...e,abstract:o}}const KS=y("webpage-embed");function JS(n,t,e,o,r,i){const{embedData:s,id:l}=e,{src:c}=s,a=n.addCustom(`webpage-${l}`,()=>new OS(n,e));d(KS,c,"The src from blockData is invalid "),a.create(n,s,t,i),n.addCustom("webpage-resizer",()=>new HS(n)),e.height&&(i.style.height=`${e.height}px`)}function XS(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 tT(){return{name:"WebPage",insertEmbedCommandItems:J5(),handleInsertEmptyEmbed:GS}}const r1={embedType:"webpage",createEmbedContent:JS,getBlockProperties:QS,getOptions:tT,handleUpdateBlock:XS},eT={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"}},nT={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"}};S.mergeLang({"zh-CN":eT,"en-US":nT});const vF="";function oT(n,t,e,o){var f;const r=n.getBlockByIndex(t,e);if(Z(n,r)!==o)return!1;const i=wt(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 h=n.insertBlock(t,e,c,Lt(n,a!=null?a:c.id,0));return n.deleteBlock(r),(f=l.onConverted)==null||f.call(l,n,h),!0}const rT={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"}}},iT={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 t4(n,t,e,o,r){if(r==="enter"&&oT(n,t,e,o))return!0;const i=n.getBlockByIndex(t,e),s=wt(fe(n.getBlockText(i),o).left).trim(),l=r==="enter"?rT:iT;for(const[,c]of Object.entries(l)){if(!s.match(c.reg))continue;return!!n.undoManager.runInGroup(()=>{var v;const h=hl(n,i,c.blockType,{offset:o,data:c.data});if(!h)return null;const{blockData:f,focusBlockId:m}=h;if(!f)return null;const C=n.insertBlock(t,e,f,Lt(n,m!=null?m:f.id,0));return n.deleteBlock(i),(v=h.onConverted)==null||v.call(h,n,C),{newBlock:C,focusBlockId:m}})}return!1}function sT(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},Lt(n,r,0))}),!0)}const lT={"#":1,"##":2,"###":3,"####":4,"#####":5,"######":6,"#######":7,"########":8};function cT(n,t,e,o){const r=n.getBlockByIndex(t,e),i=n.getBlockString(r,{boxReplacement:" "}).substring(0,o);let s=lT[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},Lt(n,r,0))}),!0}function aT(n,t,e,o){return!!(cT(n,t,e,o)||sT(n,t,e,o))}const dT=y("match-text-style");function uT(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 hT(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 fT={"*":{type:"style",styles:["style-italic"],boxType:""},"**":{type:"style",styles:["style-bold"],boxType:""},"***":{type:"style",styles:["style-bold","style-italic"],boxType:""},"~~":{type:"style",styles:["style-line-through"],boxType:""},"`":{type:"style",styles:["style-code"],boxType:""},$$:{type:"box",styles:[],boxType:"math"}};function mT(n,t,e,o){var h,f;const r=n.getBlockByIndex(t,e),i=n.getBlockText(r),{left:s}=fe(i,o),l=uT(s),c=ce(s)-l.length,a=Object.entries(fT);for(const[m,C]of a){const v=hT(l,m);if(v===-1)continue;const w=c+v,E=o,D=m.length,x=wt(Jt(i,w+D,E-w-D*2).middle);if(C.type==="style"){const A={};C.styles.forEach(P=>{A[P]=!0});const O=Oi(x,A);n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,w,E-w),n.insertTextToBlock(r,w,O)})}else if(C.type==="box")try{const A=(f=(h=n.editorBoxes.getBoxClass(C.boxType)).convertFrom)==null?void 0:f.call(h,n,x);if(!A)continue;n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,w,E-w),n.insertBoxToBlock(r,w,A)})}catch(A){dT.warn(`failed to convert to box, ${A.message}`);continue}return!0}return!1}class $c{handleAfterInsertText(t,e,o,r,i){return!!(i===" "&&(aT(t,e,o,r)||mT(t,e,o,r)))}handleBeforeKeyDown(t,e){if(!t.selection.range.isSimple())return!1;const{containerId:r,blockIndex:i,offset:s}=t.getTextPosition();if(H(t,t.getBlockByIndex(r,i))){if(An(e,"Enter")){if(t4(t,r,i,s,"enter"))return!0}else if(An(e,"Space")&&t4(t,r,i,s,"space"))return!0}return!1}}const gT={"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"}}};S.mergeLang(gT);function ps(n,t){const e=io(n,t);return!!(e.text&&ce(e.text)===0&&!t.querySelector(".inputting-insertion"))}function e4(n,t){var o;rt(t).removeAttribute("data-content-placeholder"),(o=t.querySelector("[data-type=block-tools] .block-placeholder-container"))==null||o.remove()}function jc(n,t,e){var r;if(!ps(n,t)){e4(n,t);return}const o=rt(t);if(typeof e=="string")o.setAttribute("data-content-placeholder",e);else{const i=At(t),s=(r=i.querySelector(".block-placeholder-container"))!=null?r:b("div",["block-placeholder-container"],i);s.innerHTML="",s.appendChild(e)}}function pT(n){const t=n.getAttribute("data-style-heading");return t?S.t("placeholder.heading",{heading:t}):n.getAttribute("data-style-quoted")?S.t("placeholder.quote"):null}function CT(n){const t=n.getAttribute("data-list-type");return t?t==="ordered"||t==="unordered"?S.t("placeholder.list"):S.t("placeholder.mention"):null}function n4(n){switch(it(n)){case"text":return pT(n);case"list":return CT(n);default:return null}}function bT(n){if(Uo(n))return!1;const t=z(j(n));return t?it(t)==="code":!1}function vT(n,t){var h,f;const e=it(n.selection.focusedBlock),o=t.contentPlaceholder||S.t("placeholder.default");let r=o;const i=n.selection.focusedBlock;if(e&&Ti(n,e)&&i){if(bT(i))return;r=(h=n4(i))!=null?h:r}const s=n.getFirstBlock(),l=ht(s);if(!l)return;const c=ht(l);if(c&&!t.addPlaceholderToAllCurrentEmptyBlock)return;if(!c){ps(n,l)&&jc(n,l,(f=n4(l))!=null?f:o);return}const a=n.getFocusedBlock();!ps(n,a)||a!==s&&jc(n,a,r)}function kT(n,t){var r,i;const e=n.getFirstBlock(),o=rt(e);ps(n,e)?(o.setAttribute("data-title-placeholder",(r=t.titlePlaceholder)!=null?r:S.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 yT(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 wT(n,t){yT(n),n.selection.range.isCollapsed()&&(kT(n,t),vT(n,t))}const wF="",BT=y("enforce-title");class Cs{constructor(t,e={headingLevel:1}){u(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(!Cs.isDocumentTitleBlock(r,i)||!An(e,"Enter"))return!1;let l=!1,c=null;Ve(t.rootContainer)===2&&(c=fr(t.rootContainer,1),Z(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(BT,o.length>0,"root container is empty");const r=o[0];if(r.type!=="text"||r.heading!==this.options.headingLevel){const i=jn("",{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)||wT(t,this.options)}static isDocumentTitleBlock(t,e){return t==="root"&&e===0}}const o4=y("code-dom");function tr(n){return it(n)==="code"}function r4(n,t,e){e.language?t.setAttribute("data-language",e.language):t.removeAttribute("data-language"),e.nowrap?F(t,"wrap"):M(t,"wrap")}function i4(n){const t=n.closest("div[data-type=editor-block][data-block-type=code]");return d(o4,t,"no parent code block"),d(o4,tr(t),"not a code block"),t}const Hc={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 ET(n){const t=n.toLocaleLowerCase();let e="plain";return Object.entries(Hc).forEach(([o,r])=>{(o===t||r.aliases.includes(t)||r.name.toLocaleLowerCase()===t)&&(e=o)}),e}const IT=y("convert-to-code");function xT(n,t){if(!H(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(IT,r,"no text");let i=wt(r);i.startsWith("```")&&(i=i.substring(3));const s=ET(i);return{blockData:{id:N(),type:"code",language:s,children:[o]},focusBlockId:e.id}}const BF="",i1=y("code-block-child-container");function Gr(n){d(i1,tr(n),"not a code block");const e=rt(n).querySelector(":scope > div.editor-code-root > div.code-text-root [data-type=editor-container].child");return d(i1,e,"no code text container"),e}function Zr(n){d(i1,tr(n),"not a code block");const e=rt(n).querySelector(":scope > div.editor-code-root > div.code-caption-root [data-type=editor-container].child");return e||null}function Fc(n){const t=[Gr(n)],e=Zr(n);return e&&t.push(e),t}function zc(n){const t=j(n),e=z(t);return e?tr(e)?t===Gr(e):it(n)==="code":!1}const s1=y("code-caption");function ST(n,t){if(n.readonly)return;const e=Zr(t);if(e){const c=Kt(e);n.selection.selectBlock(c,0);return}const o=Cn(n.doc),r=n.getBlockData(t);d(s1,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=Kt(s);n.selection.selectBlock(l,0)}function s4(n,t){const e=j(t);if(Ct(e))return!1;const o=z(e);if(d(s1,o,"no parent block"),!tr(o))return!1;const i=Zr(o);return e===i}function TT(n,t){if(n.readonly||!Zr(t))return;const o=Gr(t),r=Gt(o);n.selection.selectBlock(r,Z(n,r));const i=n.getBlockData(t);d(s1,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 DT=y("paste-in-table-block");class LT{constructor(t){this.editor=t,setTimeout(()=>{t.input.addHandler(this)})}destroy(){}async handleBeforePaste(t,e){if(!t.selection.range.isSimple())return!1;const o=t.selection.range.start,r=t.getBlockById(o.blockId),i=j(r);if(Ct(i))return!1;const s=z(i);if(d(DT,s,"no parent block"),!tr(s)||s4(t,r))return!1;if(!e.clipboardData)return!0;const l=e.clipboardData.getData("text/plain");if(!l)return!0;const c=ro(l);return t.undoManager.runInGroup(()=>{t.clearSelectedContents(),t.insertDoc(r,o.offset,c)}),!0}}function MT(n){n.addCustom("code-block-paste-event",t=>new LT(t))}class RT{constructor(t){u(this,"id","CodeBlockCommandProvider");setTimeout(()=>{t.editorCommandProviders.registerCommandProvider(this)})}destroy(){}getAvailableCommands(){return[]}executeCommand(){return!1}filterCommands(t,e,o,r){if(zc(e))return[]}beforeExecuteCommand(t,e,o,r,i){return!!zc(e)}}function OT(n){n.addCustom("code-block-command-provider",t=>new RT(t))}const AT=y("code-caption-input-handler");function l1(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 s4(n,e)?e:null}function _T(n){const t=l1(n);if(!t)return!1;const e=i4(t),o=ht(e);return o?(n.selection.selectBlock(o,0),!0):(n.insertTextBlock("",U(j(e)),K(e)+1),!0)}function NT(n){const t=l1(n);if(!t)return!1;if(yt(n,t)){const e=i4(t);return TT(n,e),!0}return!1}class c1{constructor(t){setTimeout(()=>{t.input.addHandler(this)})}destroy(){}handleBeforeKeyDown(t,e){return e.key==="Enter"?_T(t):e.key==="Backspace"?NT(t):!1}async handleBeforePaste(t,e){const o=l1(t);if(!o)return!1;if(!e.clipboardData)return!0;const r=e.clipboardData.getData("text/plain");return r&&t.undoManager.runInGroup(()=>{t.clearSelectedContents();const i=t.selection.range.start;d(AT,i.isSimple(),"not simple position"),t.insertTextToBlock(o,i.offset,r)}),!0}static init(t){t.addCustom("code-block-caption-input-handler",e=>new c1(e))}}const PT=`
|
|
366
|
+
</svg>`,Jh=y("webpage");class OS{constructor(t,e){u(this,"currentSrc","");u(this,"loading",null);u(this,"handleMaskMouseMove",(t,e)=>{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)});u(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(vt(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(Jh,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(Jh,this.loading,"not created"),this.currentSrc===o.src)return;const r=e.querySelector(".editor-preview-iframe");d(Jh,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=RS,{show(){t.append(e)},hide(){const r=t.querySelector(":scope > .editor-preview-iframe-loading");!r||r.remove()}}}getExistsMask(t){return At(t).querySelector(".webpage-mask")}createMask(t,e){const o=At(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 AS(n,t){b("div",["resize-gripper",t],n).setAttribute("data-resize-type",t)}function Xh(n){return At(n).querySelector(".block-resizer")}function _S(n){const t=Xh(n);t&&F(t,"active")}function Y5(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 NS(n,t,e,o){const r=Xh(n);if(r)return M(r,"active"),Y5(n,t,r),r;const i=At(n),s=b("div",["block-resizer"],i);return Y5(n,t,s),e.resize.forEach(l=>{AS(s,l)}),s.addEventListener("mousedown",o),M(s,"active"),s}function Q5(n,t){const e=Xh(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 CF="",PS=y("block-resizer");class Pc extends Wt.TypedEmitter{constructor(e,o){super();u(this,"resizableElement");u(this,"block",null);u(this,"startRect",null);u(this,"startPos",null);u(this,"resizeType",null);u(this,"enabled",!1);u(this,"handleMouseDown",e=>{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,Ei(window.getComputedStyle(r).cursor))});u(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:h}=s;(this.resizeType==="bottom"||this.resizeType==="bottom-left"||this.resizeType==="bottom-right")&&(h+=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=h>l?h-l:0,C=new DOMRect(c,l,f,m);this.emit("resizing",this,C),Q5(this.block,o)});u(this,"handleMouseUp",e=>{if(e.button!==0)return;Ei(""),this.unbindEvents(),this.emit("resized",this);const o=this.getResizableElement();!o||!this.block||Q5(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||(_S(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?rt(this.block):null}createResizer(){const e=this.getResizableElement();!e||!this.block||(d(PS,vt(this.block,e),"not a block child element"),NS(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 K5(n){return n&&De(n)&&Le(n)==="webpage"}const $S=1e3,jS=100;class HS{constructor(t){u(this,"currentBlockElement",null);u(this,"resizing",!1);u(this,"handleHoveringBlockChange",(t,e)=>{this.resizing||!this.editor.isWritable()||(e&&K5(e)&&this.disableBlockResize(e),t&&K5(t)&&this.enableBlockResize(t))});u(this,"handleResizing",(t,e)=>{this.resizing=!0;const o=t.getBlock();if(!o)return;const r=Math.max(Math.min(e.height,$S),jS);o.style.height=`${r}px`,M(o,"resizing")});u(this,"handleResized",t=>{this.resizing=!1;const e=t.getBlock();if(!e)return;F(e,"resizing");const o=this.editor.getBlockData(e),r=e.getBoundingClientRect().height;this.editor.updateBlockData(e,{...o,height:r})});this.editor=t,_t.get(t).addListener("change",this.handleHoveringBlockChange)}destroy(){this.currentBlockElement=null,_t.get(this.editor).removeListener("change",this.handleHoveringBlockChange)}disableBlockResize(t){const e=this.editor.findCustom(`${G(t)}-resizer`);e&&e.disableResize()}enableBlockResize(t){const e=this.editor.addCustom(`${G(t)}-resizer`,()=>new Pc(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 bF="",FS=y("editor-dialog");function zS(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=c0,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 US extends sc{constructor(e,o){super(zS(e,o),o);u(this,"_options");u(this,"getReferenceClientRect",()=>{const e=document.documentElement.clientHeight/2,o=document.documentElement.clientWidth/2,r=this.getCommandBarRoot();d(FS,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)});u(this,"onOk",async()=>{var e,o;try{await((o=(e=this._options).onOk)==null?void 0:o.call(e)),this.destroy()}catch{}});u(this,"onClose",()=>{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.onOk),s==null||s.addEventListener("click",this.onClose),i==null||i.addEventListener("click",this.onClose),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.onOk),o==null||o.removeEventListener("click",this.onClose),r==null||r.removeEventListener("click",this.onClose),super.destroy()}}const J5=()=>[{name:S.t("webpage.bilibili"),id:"insert-bilibili",icon:vw,group:"thirdParty"},{name:S.t("webpage.youku"),id:"insert-youku",icon:kw,group:"thirdParty"},{name:S.t("webpage.figma"),id:"insert-figma",icon:yw,group:"thirdParty"},{name:S.t("webpage.modao"),id:"insert-modao",icon:ww,group:"thirdParty"},{name:S.t("webpage.tencent"),id:"insert-tencent",icon:Bw,group:"thirdParty"},{id:"insert-webPage",name:S.t("webpage.title"),icon:Ew,group:"common",order:1e3}];function t1(n){return n==="insert-webPage"}async function VS(n,t){return n.doc.externalDoc.recognizeLink?n.doc.externalDoc.recognizeLink(t):null}function qS(n){return n&&!n.startsWith("http://")&&!n.startsWith("https://")&&!n.startsWith("//")?`//${n}`:n}async function WS(n){if(!n)throw new Error(S.t("webpage.dialog.errorEnterUrl"));let t=n;t.startsWith("//")&&(t=`http:${t}`);try{new URL(t)}catch{throw new Error(S.t("webpage.dialog.unsupportedUrl"))}}async function GS(n,t){const e=t.item.id,o=J5().find(l=>l.id===e),r=b("div",["webpage-content"],null);if(t1(e)){const l=b("div",["help-container"],r),c=b("div",["help-content"],l),a=b("span",["help-icon"],c);a.innerHTML=f0,b("span",[],c,S.t("webpage.dialog.helpContent"))}const{getInputValue:i,setFieldError:s}=th(r,{required:!0,label:S.t("webpage.dialog.label"),placeholder:S.t("webpage.dialog.placeholder")});if(!t1(e)){const l=b("div",["help-link-container"],r),c=b("a",["help-link-content"],l);b("span",[],c,S.t("webpage.dialog.helpLink"));const a=b("span",["help-link-icon"],c);a.innerHTML=g0;const h=n.getComponentOptions("webpage");c.href=(h==null?void 0:h.helpLink)||"",c.target="_blank"}try{const l=await new Promise(a=>{new US(r,{title:S.t("webpage.dialog.title",{name:(o==null?void 0:o.name)||""}),async onOk(){var m;const f=qS(i());try{await WS(f);const C=await VS(n,f);a((C==null?void 0:C.url)||"")}catch(C){if(((m=C==null?void 0:C.responseData)==null?void 0:m.statusCode)===415)if(t1(e))a(f);else throw s(S.t("webpage.dialog.unsupportedUrl")),C;else throw s(C.message||""),C}}}).show()}),c={id:N(),type:"embed",embedType:"webpage",embedData:{src:l}};return n.insertBlock(t.containerId,t.blockIndex,c)}catch{return null}}const X5=y("embed-block-properties");function e1(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 n1{constructor(t,e){u(this,"group","hovering-toolbar");u(this,"_commands",[{id:"edit",name:"Edit",icon:Ju},{id:"add-comment",name:"Add Comment",icon:ns}]);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"){e1(t,e)||X5.error("failed to add comment to block");return}X5.error(`unknown command: ${JSON.stringify(o)}`),alert(o.id)}}}function o1(n,t,e){return{blockCommands:{"hovering-toolbar":new n1(n,e)}}}function ZS(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 YS(n,t){const e=n.getBlockData(t),{embedData:o}=e,r=o.src;return window.open(r,"_blank"),!0}function QS(n,t){const e=o1(n,t,{presetIds:["add-comment"],extCommands:[{id:"refresh",name:"Refresh page",icon:pw},{id:"open-page",name:"Open the original page",icon:g0}],handleExecuteCommand:(r,i,s)=>{switch(s.id){case"refresh":return ZS(i);case"open-page":return YS(r,i)}return!1}}),o=`[${S.t("webpage.abstract")}]`;return{...e,abstract:o}}const KS=y("webpage-embed");function JS(n,t,e,o,r,i){const{embedData:s,id:l}=e,{src:c}=s,a=n.addCustom(`webpage-${l}`,()=>new OS(n,e));d(KS,c,"The src from blockData is invalid "),a.create(n,s,t,i),n.addCustom("webpage-resizer",()=>new HS(n)),e.height&&(i.style.height=`${e.height}px`)}function XS(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 tT(){return{name:"WebPage",insertEmbedCommandItems:J5(),handleInsertEmptyEmbed:GS}}const r1={embedType:"webpage",createEmbedContent:JS,getBlockProperties:QS,getOptions:tT,handleUpdateBlock:XS},eT={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"}},nT={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"}};S.mergeLang({"zh-CN":eT,"en-US":nT});const vF="";function oT(n,t,e,o){var f;const r=n.getBlockByIndex(t,e);if(Z(n,r)!==o)return!1;const i=wt(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 h=n.insertBlock(t,e,c,Lt(n,a!=null?a:c.id,0));return n.deleteBlock(r),(f=l.onConverted)==null||f.call(l,n,h),!0}const rT={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"}}},iT={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 t4(n,t,e,o,r){if(r==="enter"&&oT(n,t,e,o))return!0;const i=n.getBlockByIndex(t,e),s=wt(fe(n.getBlockText(i),o).left).trim(),l=r==="enter"?rT:iT;for(const[,c]of Object.entries(l)){if(!s.match(c.reg))continue;return!!n.undoManager.runInGroup(()=>{var v;const h=hl(n,i,c.blockType,{offset:o,data:c.data});if(!h)return null;const{blockData:f,focusBlockId:m}=h;if(!f)return null;const C=n.insertBlock(t,e,f,Lt(n,m!=null?m:f.id,0));return n.deleteBlock(i),(v=h.onConverted)==null||v.call(h,n,C),{newBlock:C,focusBlockId:m}})}return!1}function sT(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},Lt(n,r,0))}),!0)}const lT={"#":1,"##":2,"###":3,"####":4,"#####":5,"######":6,"#######":7,"########":8};function cT(n,t,e,o){const r=n.getBlockByIndex(t,e),i=n.getBlockString(r,{boxReplacement:" "}).substring(0,o);let s=lT[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},Lt(n,r,0))}),!0}function aT(n,t,e,o){return!!(cT(n,t,e,o)||sT(n,t,e,o))}const dT=y("match-text-style");function uT(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 hT(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 fT={"*":{type:"style",styles:["style-italic"],boxType:""},"**":{type:"style",styles:["style-bold"],boxType:""},"***":{type:"style",styles:["style-bold","style-italic"],boxType:""},"~~":{type:"style",styles:["style-line-through"],boxType:""},"`":{type:"style",styles:["style-code"],boxType:""},$$:{type:"box",styles:[],boxType:"math"}};function mT(n,t,e,o){var h,f;const r=n.getBlockByIndex(t,e),i=n.getBlockText(r),{left:s}=fe(i,o),l=uT(s),c=ce(s)-l.length,a=Object.entries(fT);for(const[m,C]of a){const v=hT(l,m);if(v===-1)continue;const w=c+v,E=o,L=m.length,x=wt(Jt(i,w+L,E-w-L*2).middle);if(C.type==="style"){const O={};C.styles.forEach(P=>{O[P]=!0});const A=Oi(x,O);n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,w,E-w),n.insertTextToBlock(r,w,A)})}else if(C.type==="box")try{const O=(f=(h=n.editorBoxes.getBoxClass(C.boxType)).convertFrom)==null?void 0:f.call(h,n,x);if(!O)continue;n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,w,E-w),n.insertBoxToBlock(r,w,O)})}catch(O){dT.warn(`failed to convert to box, ${O.message}`);continue}return!0}return!1}class $c{handleAfterInsertText(t,e,o,r,i){return!!(i===" "&&(aT(t,e,o,r)||mT(t,e,o,r)))}handleBeforeKeyDown(t,e){if(!t.selection.range.isSimple())return!1;const{containerId:r,blockIndex:i,offset:s}=t.getTextPosition();if(H(t,t.getBlockByIndex(r,i))){if(An(e,"Enter")){if(t4(t,r,i,s,"enter"))return!0}else if(An(e,"Space")&&t4(t,r,i,s,"space"))return!0}return!1}}const gT={"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"}}};S.mergeLang(gT);function ps(n,t){const e=io(n,t);return!!(e.text&&ce(e.text)===0&&!t.querySelector(".inputting-insertion"))}function e4(n,t){var o;rt(t).removeAttribute("data-content-placeholder"),(o=t.querySelector("[data-type=block-tools] .block-placeholder-container"))==null||o.remove()}function jc(n,t,e){var r;if(!ps(n,t)){e4(n,t);return}const o=rt(t);if(typeof e=="string")o.setAttribute("data-content-placeholder",e);else{const i=At(t),s=(r=i.querySelector(".block-placeholder-container"))!=null?r:b("div",["block-placeholder-container"],i);s.innerHTML="",s.appendChild(e)}}function pT(n){const t=n.getAttribute("data-style-heading");return t?S.t("placeholder.heading",{heading:t}):n.getAttribute("data-style-quoted")?S.t("placeholder.quote"):null}function CT(n){const t=n.getAttribute("data-list-type");return t?t==="ordered"||t==="unordered"?S.t("placeholder.list"):S.t("placeholder.mention"):null}function n4(n){switch(it(n)){case"text":return pT(n);case"list":return CT(n);default:return null}}function bT(n){if(Uo(n))return!1;const t=z(j(n));return t?it(t)==="code":!1}function vT(n,t){var h,f;const e=it(n.selection.focusedBlock),o=t.contentPlaceholder||S.t("placeholder.default");let r=o;const i=n.selection.focusedBlock;if(e&&Ti(n,e)&&i){if(bT(i))return;r=(h=n4(i))!=null?h:r}const s=n.getFirstBlock(),l=ht(s);if(!l)return;const c=ht(l);if(c&&!t.addPlaceholderToAllCurrentEmptyBlock)return;if(!c){ps(n,l)&&jc(n,l,(f=n4(l))!=null?f:o);return}const a=n.getFocusedBlock();!ps(n,a)||a!==s&&jc(n,a,r)}function kT(n,t){var r,i;const e=n.getFirstBlock(),o=rt(e);ps(n,e)?(o.setAttribute("data-title-placeholder",(r=t.titlePlaceholder)!=null?r:S.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 yT(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 wT(n,t){yT(n),n.selection.range.isCollapsed()&&(kT(n,t),vT(n,t))}const wF="",BT=y("enforce-title");class Cs{constructor(t,e={headingLevel:1}){u(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(!Cs.isDocumentTitleBlock(r,i)||!An(e,"Enter"))return!1;let l=!1,c=null;Ve(t.rootContainer)===2&&(c=fr(t.rootContainer,1),Z(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(BT,o.length>0,"root container is empty");const r=o[0];if(r.type!=="text"||r.heading!==this.options.headingLevel){const i=jn("",{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)||wT(t,this.options)}static isDocumentTitleBlock(t,e){return t==="root"&&e===0}}const o4=y("code-dom");function tr(n){return it(n)==="code"}function r4(n,t,e){e.language?t.setAttribute("data-language",e.language):t.removeAttribute("data-language"),e.nowrap?F(t,"wrap"):M(t,"wrap")}function i4(n){const t=n.closest("div[data-type=editor-block][data-block-type=code]");return d(o4,t,"no parent code block"),d(o4,tr(t),"not a code block"),t}const Hc={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 ET(n){const t=n.toLocaleLowerCase();let e="plain";return Object.entries(Hc).forEach(([o,r])=>{(o===t||r.aliases.includes(t)||r.name.toLocaleLowerCase()===t)&&(e=o)}),e}const IT=y("convert-to-code");function xT(n,t){if(!H(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(IT,r,"no text");let i=wt(r);i.startsWith("```")&&(i=i.substring(3));const s=ET(i);return{blockData:{id:N(),type:"code",language:s,children:[o]},focusBlockId:e.id}}const BF="",i1=y("code-block-child-container");function Gr(n){d(i1,tr(n),"not a code block");const e=rt(n).querySelector(":scope > div.editor-code-root > div.code-text-root [data-type=editor-container].child");return d(i1,e,"no code text container"),e}function Zr(n){d(i1,tr(n),"not a code block");const e=rt(n).querySelector(":scope > div.editor-code-root > div.code-caption-root [data-type=editor-container].child");return e||null}function Fc(n){const t=[Gr(n)],e=Zr(n);return e&&t.push(e),t}function zc(n){const t=j(n),e=z(t);return e?tr(e)?t===Gr(e):it(n)==="code":!1}const s1=y("code-caption");function ST(n,t){if(n.readonly)return;const e=Zr(t);if(e){const c=Kt(e);n.selection.selectBlock(c,0);return}const o=Cn(n.doc),r=n.getBlockData(t);d(s1,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=Kt(s);n.selection.selectBlock(l,0)}function s4(n,t){const e=j(t);if(Ct(e))return!1;const o=z(e);if(d(s1,o,"no parent block"),!tr(o))return!1;const i=Zr(o);return e===i}function TT(n,t){if(n.readonly||!Zr(t))return;const o=Gr(t),r=Gt(o);n.selection.selectBlock(r,Z(n,r));const i=n.getBlockData(t);d(s1,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 DT=y("paste-in-table-block");class LT{constructor(t){this.editor=t,setTimeout(()=>{t.input.addHandler(this)})}destroy(){}async handleBeforePaste(t,e){if(!t.selection.range.isSimple())return!1;const o=t.selection.range.start,r=t.getBlockById(o.blockId),i=j(r);if(Ct(i))return!1;const s=z(i);if(d(DT,s,"no parent block"),!tr(s)||s4(t,r))return!1;if(!e.clipboardData)return!0;const l=e.clipboardData.getData("text/plain");if(!l)return!0;const c=ro(l);return t.undoManager.runInGroup(()=>{t.clearSelectedContents(),t.insertDoc(r,o.offset,c)}),!0}}function MT(n){n.addCustom("code-block-paste-event",t=>new LT(t))}class RT{constructor(t){u(this,"id","CodeBlockCommandProvider");setTimeout(()=>{t.editorCommandProviders.registerCommandProvider(this)})}destroy(){}getAvailableCommands(){return[]}executeCommand(){return!1}filterCommands(t,e,o,r){if(zc(e))return[]}beforeExecuteCommand(t,e,o,r,i){return!!zc(e)}}function OT(n){n.addCustom("code-block-command-provider",t=>new RT(t))}const AT=y("code-caption-input-handler");function l1(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 s4(n,e)?e:null}function _T(n){const t=l1(n);if(!t)return!1;const e=i4(t),o=ht(e);return o?(n.selection.selectBlock(o,0),!0):(n.insertTextBlock("",U(j(e)),K(e)+1),!0)}function NT(n){const t=l1(n);if(!t)return!1;if(yt(n,t)){const e=i4(t);return TT(n,e),!0}return!1}class c1{constructor(t){setTimeout(()=>{t.input.addHandler(this)})}destroy(){}handleBeforeKeyDown(t,e){return e.key==="Enter"?_T(t):e.key==="Backspace"?NT(t):!1}async handleBeforePaste(t,e){const o=l1(t);if(!o)return!1;if(!e.clipboardData)return!0;const r=e.clipboardData.getData("text/plain");return r&&t.undoManager.runInGroup(()=>{t.clearSelectedContents();const i=t.selection.range.start;d(AT,i.isSimple(),"not simple position"),t.insertTextToBlock(o,i.offset,r)}),!0}static init(t){t.addCustom("code-block-caption-input-handler",e=>new c1(e))}}const PT=`
|
|
367
367
|
<svg fill="currentColor" focusable="false" viewBox="0 0 24 24" aria-hidden="true" tabindex="-1">
|
|
368
368
|
<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>
|
|
369
369
|
</svg>`,$T=`
|
|
@@ -374,7 +374,7 @@ xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
|
|
|
374
374
|
<svg focusable="false" viewBox="0 0 24 24" aria-hidden="true" tabindex="-1">
|
|
375
375
|
<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>
|
|
376
376
|
</svg>
|
|
377
|
-
`;function HT(n,t,e){const r={...n.getBlockData(t),language:e};n.updateBlockData(t,r)}function FT(n,t,e){const r={...n.getBlockData(t),nowrap:e};n.updateBlockData(t,r)}const Yr=y("code-block-header"),zT=Object.entries(Hc).map(([n,t])=>({id:n,name:t.name,language:t}));function UT(n,t){if(t){const e=n,{editor:o,codeBlock:r}=e.custom;HT(o,r,t.id);const i=r.querySelector(".code-block-header .language-select .name-label");i.innerText=t.name}}function VT(n,t,e){n.addCustom("code-header-language-select-dropdown",i=>{const s=new Yy(zT,i.rootElement,{placeholder:"Search for a language..."});return s.onSelected=UT,s});const o=b("div",["language-select"],null);b("span",["name-label"],o,e);const r=b("span",["arrow-icon"],o);return r.innerHTML=PT,n.domEvents.addEventListener(o,"click",(i,s)=>{const c=s.target.closest(".language-select"),a=z(c);d(Yr,a,"no parent block"),d(Yr,it(a)==="code","not a code block");const h=i.getBlockData(a),f=i.getCustom("code-header-language-select-dropdown");f.custom={codeBlock:a,editor:i},f.setSelectedId(h.language),f.show(c),M(t,"editing-language"),f.onHide=()=>{F(t,"editing-language")}}),o}function qT(){return b("div",["code-header-spacer"],null)}function WT(n,t){const e=t.target,o=e.closest(".code-header-button");d(Yr,o,"no button");const r=z(e);d(Yr,r,"no parent block");const i=o.getAttribute("data-id");if(d(Yr,it(r)==="code","not a code block"),i==="wrap"){const s=n.getBlockData(r);FT(n,r,!s.nowrap);return}if(i==="copy"){const s=Gr(r),l=tu(n,U(s)),c=Kg(n,l);navigator.clipboard.writeText(c).then(()=>{const a=o.getBoundingClientRect();Qy("Copied to clipboard",{position:{x:a.x+a.width/2,y:a.bottom+30}})}).catch(a=>{Yr.error(a.message)});return}i==="caption"&&ST(n,r)}function a1(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",WT),r}function GT(n,t,e){const o=At(t),r=b("div",["code-block-header"],o),i=Hc[e.language]||Hc.plain;r.appendChild(VT(n,t,i.name)),r.appendChild(qT()),r.appendChild(a1(n,"copy","Copy",$T)),r.appendChild(a1(n,"wrap","Wrap",jT)),r.appendChild(a1(n,"caption","Caption",null))}function ZT(n,t,e,o){c1.init(n);const r=o.children,i=no(e,"div");i.setAttribute("data-language",o.language||"text"),r4(n,e,o);const s=b("div",["editor-code-root"],i),l=b("div",["code-text-root"],s);if(n.createChildContainer(t,l,r[0]),r.length===2){const c=b("div",["code-caption-root"],s);n.createChildContainer(t,c,r[1])}return GT(n,e,o),i}function YT(n){const t={id:N(),type:"text",text:[]},e=N();return n.doc.localInsertChildContainer(e,[t]),{blockData:{id:N(),type:"code",language:"plain",children:[e]},focusBlockId:t.id}}const En=y("list-block");function QT(n,t,e,o,r){MT(n),OT(n),d(En,r.type==="code","invalid block data type");const i=r;return d(En,i.children,"invalid block data children"),d(En,i.children.length===1||i.children.length===2,"invalid block data children length"),M(o,"drag-preview-element"),ZT(n,t,o,i)}function KT(n){return 1}function JT(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t)||!mn(r))return null;const i=Fc(t);if(!mn(r))return null;const s=r;if(i.indexOf(s)===-1||Ve(s)>1)return null;const l=bt(t,U(s));return new Qe(n,{anchor:l,focus:l})}function XT(n,t,e,o){return null}function tD(n,t){return n.getBoundingClientRect()}function eD(n,t,e,o){if(e.isSimple()){d(En,o.isSimple(),"from is simple position but to is not simple position"),En.debug("full select list"),M(t,"full-selected");return}d(En,!o.isSimple(),"from is complex position but end is simple position");const r=e,i=o;d(En,r.blockId===i.blockId,"only allow update one table selection"),Fc(t).forEach(l=>{const c=U(l);(c===r.childContainerId||c===i.childContainerId)&&M(l,"selected")})}function nD(n){n.rootContainer.querySelectorAll('[data-type="editor-block"][data-block-type="code"]').forEach(t=>{F(t,"full-selected"),t.querySelectorAll("div[data-type=editor-container].child.selected").forEach(e=>{F(e,"selected")})})}function oD(n,t){return Fc(t)}function rD(n,t,e,o,r){if(o==="ArrowDown"||o==="ArrowRight"){if(e===Gr(t))return Zr(t)}else if(e===Zr(t))return Gr(t);return null}function iD(n,t,e,o){const r=Fc(t),i=r.map(U),s=i.indexOf(e.childContainerId),l=i.indexOf(o.childContainerId);d(En,s!==-1,"invalid start pos"),d(En,l!==-1,"invalid end pos");const c=[r[s]];return s!==l&&c.push(r[l]),c}function sD(n,t,e){d(En,tr(t),"invalid block type"),r4(n,t,e)}async function lD(n,t){const e=YT(n);if(!e)return null;const{blockData:o,focusBlockId:r}=e;return n.insertBlock(t.containerId,t.blockIndex,o,Lt(n,r,0))}function cD(n){return{name:"CodeBlock",insertBlockCommandItems:[{id:"insert-code",name:S.t("code.title"),icon:Dw,order:300,group:"common"}],handleInsertEmptyBlock:lD}}function aD(){return{abstract:`[${S.t("code.abstract")}]`}}const bs={blockType:"code",blockKind:"complex",createBlockContent:QT,getBlockTextLength:KT,getRangeFromPoint:JT,moveCaret:XT,getCaretRect:tD,updateSelection:eD,clearSelection:nD,getChildContainers:oD,getNextContainer:rD,getSelectedContainers:iD,convertFrom:xT,handleBlockElementUpdated:sD,getOptions:cD,getBlockProperties:aD},d1={...Ai,blockType:"code-line"};function dD(n){if(!n.isWritable())return!1;const t=n.getFocusedBlock();if(!!zc(t)){if(n.selection.range.isCollapsed()){const e=n.selection.range.start;return n.insertTextToBlock(t,e.offset," "),!0}return n.undoManager.runInGroup(()=>{Ke(n).forEach(o=>{n.insertTextToBlock(o.block,0," ")})}),!0}}function uD(n){if(!n.isWritable())return!1;const t=n.getFocusedBlock();if(!zc(t))return;const e=[" "," "," "," "];return n.undoManager.runInGroup(()=>{Ke(n).forEach(r=>{const i=wt(n.getBlockText(r.block));for(let s=0;s<e.length;s++){const l=e[s];if(i.startsWith(l)){n.deleteTextFromBlock(r.block,0,l.length);break}}})}),!0}const hD={Tab:dD,"Shift+Tab":uD},vs=y("code-text-decorate");class ks{decorateText(t,e,o){var C;if(d(vs,e.length>0,"invalid path"),e.length===1)return{};const r=e[e.length-2];if(t.doc.getBlockData(r.containerId,r.blockIndex).type!=="code")return{};const s=o;if(s.length===0)return{};const l=wt(s),c=t.doc.getBlockData(r.containerId,r.blockIndex),a=bi.default.tokenize(l,(C=bi.default.languages[c.language])!=null?C:bi.default.languages.plain),h=(v,w)=>{if(d(vs,v,"no token"),typeof v=="string")return[{insert:v,attributes:Y.default(w)}];d(vs,v instanceof bi.default.Token,"invalid token type");const E=v.content,D=Y.default(w);return D[`style-code-${v.type}`]=!0,typeof E=="string"?[{insert:E,attributes:D}]:Array.isArray(E)?E.map(O=>h(O,D)).flat():(d(vs,E instanceof bi.default.Token,"invalid token"),h(E,D))},m=a.map(v=>h(v,{})).flat();return d(vs,ce(m)===ce(s),"failed to highlight code, text length mismatch"),{text:m}}}const fD={code:{title:"\u4EE3\u7801",abstract:"\u4EE3\u7801"}},mD={code:{title:"Code",abstract:"Code"}};S.mergeLang({"zh-CN":fD,"en-US":mD});const gD=y("image-data"),pD=1e3,CD=400,bD=10;function ys(n){return n.src.startsWith("empty:")||!n.src}function vD(n){return n.src.startsWith("http:")||n.src.startsWith("https:")}function l4(n){return`${Ci.default(n)}_width`}function c4(n){return`${Ci.default(n)}_height`}function a4(n){return`${n}_flex`}function ws(n){if(n.every(r=>typeof r.flex=="number"&&r.flex))return;const t=100,o=n.map(r=>r.width/(r.height/t)).reduce((r,i)=>r+i,0);n.forEach(r=>{const i=r.width/(r.height/t);r.flex=i/o})}function Qr(n){const t=(r,i)=>{r||(r=`empty:${i}`);const s=l4(r),l=c4(r),c=a4(i);let a=n[s],h=n[l],f=n[c];return typeof a=="string"&&(a=Number.parseInt(a,10)),typeof h=="string"&&(h=Number.parseInt(h,10)),typeof f=="string"&&(f=Number.parseInt(f,10)),a&&h?{src:r,width:a,height:h,flex:f,virtualSize:!1}:(a=pD,h=CD,{src:r,width:a,height:h,flex:f,virtualSize:!0})};let e=[];const o=n.src;return Array.isArray(o)?e=o.map(t):typeof o=="string"&&(e=o.split("|").map(t)),ws(e),e}function cn(n){var o;const t=n.embedData;return Qr(n.embedData).length>1?100:(o=t.widthPercent)!=null?o:100}function kD(n,t){if(Qr(t.embedData).length>1)return"100%";const o=cn(t);return`${n.rootContainer.getBoundingClientRect().width*o/100}px`}function de(n,t){const o={src:n.map(r=>r.src).join("|"),widthPercent:t};return n.forEach((r,i)=>{if(r.width&&r.height&&!r.virtualSize){const l=r.src||`empty:${i}`,c=l4(l);o[c]=r.width;const a=c4(l);o[a]=r.height}d(gD,r.flex,"no image flex");const s=a4(i);o[s]=r.flex}),o}function yD(n,t,e){const o=Qr(t.embedData),r=o.length===1?n.rootContainer:e,i=cn(t);let s=r.getBoundingClientRect().width*(i/100);if(s-=Number.parseFloat(window.getComputedStyle(r).paddingLeft)+Number.parseFloat(window.getComputedStyle(r).paddingRight),o.length===1){const a=o[0];return a.height/(a.width/s)}s-=(o.length-1)*bD;const l=o.reduce((a,h)=>a+h.flex,0);let c=0;for(const a of o){const f=s*a.flex/l/a.width*a.height;c=Math.max(f,c)}return c}function wD(n){return n.reduce((e,o)=>e+o.flex,0)}const BD=y("image-dom");function d4(n){return n.querySelector(".uploading-progress-mask")}function ED(n){const t=d4(n);if(t)return t;const e=b("div",["uploading-progress-mask"],n),o=b("div",["uploading-progress-bar"],e);return b("div",["uploading-progress-bar-value"],o),o}function ID(n){const e=ED(n).querySelector(".uploading-progress-bar-value");return d(BD,e,"no progress value"),e}function u4(n,t){const e=ID(n);e.style.width=`${t}%`}function xD(n){var t;(t=d4(n))==null||t.remove()}function SD(n){let t;return n.forEach((e,o)=>{o.toLocaleLowerCase()==="content-type"&&(t=e)}),t!=null?t:""}async function TD(n){try{const t=await fetch(n,{credentials:"same-origin"}),e=await t.blob(),o=SD(t.headers).toLocaleLowerCase();let r="";if(o){const s=Tf.default[o].extensions;s&&s.length>0&&(r=s[0])}return new File([e],`${Date.now()}.${r}`,{type:o})}catch{return null}}function er(n,t){const e=typeof t=="string"?t:G(t);return n.getCustom(`image-${e}`)}function Uc(n,t){if(!t||!(t instanceof Node))return null;const e=z(t);return e?er(n,e):null}function Zn(n){return Array.from(n.querySelectorAll(".image-container"))}function Vc(n,t,e,o){const r=e!=null?e:n.findBlockById(t.id);if(!r)return;const i=o||j(r),s=kD(n,t),l=yD(n,t,i),c=rt(r);c.style.width=s;const a=r.querySelector(".images");!a||(a.style.height=`${l}px`)}const u1=y("table-resize-drag-drop");class DD{constructor(t,e,o,r){u(this,"cursor","col-resize");u(this,"initWidths");this.editor=t,this.elem=e,this.data=o,this.mouseDownEvent=r;const i=this.data.block,l=er(this.editor,i).getImages(),c=this.data.splitterIndex;d(u1,c>=0&&c<l.length-1,`invalid splitter index: ${c}`);const h=Zn(i).map(f=>f.getBoundingClientRect().width);this.initWidths=h}onDragStart(t,e,o){if(!this.editor.isWritable())return;const r=this.data.block;er(this.editor,r).setResizing(!0)}onDragging(t,e,o,r,i){const s=this.data.block,l=er(this.editor,s),c=Y.default(l.getImages()),a=this.data.splitterIndex;d(u1,a>=0&&a<c.length-1,`invalid splitter index: ${a}`);const h=this.initWidths[a],f=this.initWidths[a+1];if(h+f<100)return;let m=r;h+m<50&&(m=50-h),f-m<50&&(m=f-50);const w=[...this.initWidths];w[a]+=m,w[a+1]-=m;const E=Zn(s);d(u1,E.length===c.length,"invalid image data");const D=w.reduce((O,P)=>O+P,0);for(let O=0;O<c.length;O++){const P=w[O]/D;c[O].flex=P,E[O].style.flexGrow=`${P}`}const x=Y.default(this.editor.getBlockData(s)),A=de(c,cn(x));x.embedData=A,Vc(this.editor,x,s,null)}onDragEnd(t,e,o,r,i){const s=this.data.block,l=er(this.editor,s),a=Zn(s).map(h=>Number.parseFloat(h.style.flexGrow));l.updateFlex(a),l.setResizing(!1)}}function h4(n){var t;return!n||!(n instanceof HTMLElement)?null:lt(n,"image-splitter")?n:(t=n.closest(".image-splitter"))!=null?t:null}function LD(n,t){var s;const e=h4(t.target);if(!e)return;const o=z(e);if(!o)return;er(n,o).setSelectedIndex(-1),n.selection.selectBlock(o,0);const r=Number.parseInt((s=e.getAttribute("data-index"))!=null?s:"",10);if(Number.isNaN(r)||typeof r!="number")return;const i={block:o,splitterIndex:r};qa(new DD(n,e,i,t))}function MD(n,t){t.preventDefault(),t.stopPropagation();const e=h4(t.target);if(!e)return;const o=z(e);!o||er(n,o).resetFlex()}function RD(n,t,e,o){const r=b("div",["image-splitter"],e);b("div",["image-splitter-indicator"],r),r.setAttribute("data-index",`${o}`),n.domEvents.addEventListener(r,"mousedown",LD),n.domEvents.addEventListener(r,"dblclick",MD)}const OD=y("image-item");function f4(n){return!n||!(n instanceof Node)?null:z(n)}function m4(n){const t=f4(n);return t?Zn(t):[]}function h1(n){if(!n||!(n instanceof Node))return null;const t=n instanceof Element?n:n.parentElement;if(!t)return null;const e=t.closest(".image-container");return e||null}function Bs(n){const t=h1(n);return t?m4(n).indexOf(t):-1}async function AD(n,t){const e=Uc(n,t.target);if(!e)return;const o=Bs(t.target);if(o===-1)return;const r=t.target;if(!(r instanceof HTMLImageElement))return;const i=e.getImages()[o];if(i.virtualSize&&e.fixImageSize(o,r),!i||!vD(i)||i.downloading)return;i.downloading=!0;const s=await TD(i.src);s?e.replaceImage(o,s):OD.warn(`failed to download image: ${i.src}`)}function _D(n,t,e){if(t.querySelector(".load-error"))return;const r=e.src.startsWith("http:")||e.src.startsWith("https:"),i=b("div",["load-error"],t),s=b("div",["error-icon"],i);s.innerHTML=m0;const l=b("div",["error-message"],i);r?(l.innerHTML=S.t("image.load.remote.failed"),n.domEvents.addEventListener(i,"click",(c,a)=>{a.preventDefault(),a.target instanceof HTMLElement&&a.target.tagName==="A"&&window.open(e.src,"_blank")})):(l.innerHTML=S.t("image.load.failed"),n.domEvents.addEventListener(i,"click",(c,a)=>{a.preventDefault(),a.target instanceof HTMLElement&&a.target.tagName==="A"&&jD(c,a.target)}))}function ND(n,t){const e=Uc(n,t.target);if(!e)return;const o=Bs(t.target);if(o===-1)return;const r=e.getImages()[o];if(!r)return;const i=h1(t.target);!i||(M(i,"error","error-load"),_D(n,i,r))}function PD(n,t,e){if(t.querySelector(".upload-error"))return;const r=b("div",["upload-error"],t),i=b("div",["error-icon"],r);i.innerHTML=m0;const s=b("div",["error-message"],r);s.innerHTML=S.t("image.upload.failed"),n.domEvents.addEventListener(r,"click",(l,c)=>{if(c.preventDefault(),!c.target||!(c.target instanceof Element)||c.target.tagName!=="A")return;const a=Uc(l,c.target),h=Bs(c.target);!a||h===-1||a.replaceImage(h,e)})}function g4(n,t,e,o,r){const i=Zn(t)[e];!i||(M(i,"error","error-upload"),PD(n,i,r))}function p4(n,t,e,o,r,i){const s=b("div",["image-container"],t);if(s.setAttribute("data-src",e.src),i.length>1&&(s.style.flexShrink=`${e.flex}`,s.style.flexGrow=`${e.flex}`),r===o&&M(s,"active"),ys(e)){M(s,"empty");const c=b("div",["upload-image-icon"],s);return c.innerHTML=hw,s}const l=b("img",["editor-image"],s);if(l.src=n.doc.buildResourceUrl(e.src),l.draggable=!0,!ys(e)&&!n.readonly&&n.domEvents.addEventListener(l,"load",AD),n.domEvents.addEventListener(l,"error",ND),e.src.startsWith("https:")||e.src.startsWith("http:")){const c=b("div",["image-warning"],s);c.innerHTML=f0,c.setAttribute(`data-editor-tooltip-${n.clientId}`,S.t("image.load.remote.tooltip"))}return s}function $D(n,t,e,o,r){const i=b("div",["images"],e);return o.forEach((s,l)=>{l>0&&RD(n,t,i,l-1),p4(n,i,s,l,r,o)}),o.length>1&&M(t,"multi"),i}function C4(n,t,e,o,r,i){const l=Array.from(t.querySelectorAll(".image-container"))[o];if(!l)return;const c=p4(n,null,e,o,r,i);l.insertAdjacentElement("beforebegin",c),l.remove()}function Es(n,t){return Zn(n)[t]}function jD(n,t){const e=f4(t);if(!e)return;const o=Bs(t);if(o===-1)return;const r=Uc(n,t);if(!r)return;const i=r.getImages()[o];C4(n,e,i,o,r.getSelectedIndex(),r.getImages())}function an(n){return it(n)==="embed"&&Le(n)==="image"}async function b4(n){return new Promise((t,e)=>{const o=new Image;o.onload=()=>{t({width:o.naturalWidth,height:o.naturalHeight})},o.onerror=e,o.src=n})}async function HD(n){const t=await nl(n);return b4(t)}const v4=y("image-object");class Ft{constructor(t,e){u(this,"images",[]);u(this,"selectedIndex",-1);u(this,"blockResizer");u(this,"resizing",!1);u(this,"parentContainerResizerObserver",null);u(this,"handleMouseDown",async(t,e)=>{const o=Bs(e.target);if(o===-1)return;const r=this.images[o];ys(r)||this.setSelectedIndex(o)});u(this,"handleEditorResize",()=>{if(this.isEmpty()||this.resizing)return;const t=this.editor.findBlockById(this.blockData.id);!t||Vc(this.editor,this.blockData,t,null)});u(this,"handleResizing",(t,e)=>{const o=this.editor.findBlockById(this.blockData.id);if(!o)return;const i=this.editor.rootContainer.getBoundingClientRect().width,s=o.getBoundingClientRect();let l=e.width>s.width?s.width:e.width;l<50&&(l=50);const c=l*100/i;this.blockData.embedData.widthPercent=c,Vc(this.editor,this.blockData,o,null)});u(this,"handleResized",t=>{const e=this.editor.findBlockById(this.blockData.id);if(!e)return;const o=de(this.images,cn(this.blockData));this.editor.updateEmbedData(e,o),this.blockResizer.enableResize(e)});u(this,"fixImageSizes",Qt.default(()=>{const t=this.editor.findBlockById(this.blockData.id);if(!t)return;const e=de(this.images,cn(this.blockData));this.editor.updateEmbedData(t,e)},1e3));this.editor=t,this.blockData=e,this.blockResizer=new Pc(this.editor,{resize:["top-left","top-right","bottom-left","bottom-right"]}),this.blockResizer.addListener("resizing",this.handleResizing),this.blockResizer.addListener("resized",this.handleResized),this.images=Qr(this.blockData.embedData)}destroy(){var t;this.blockResizer.removeAllListeners(),this.blockResizer.destroy(),this.editor.domEvents.removeEventListener(null,null,this.handleMouseDown),(t=this.parentContainerResizerObserver)==null||t.disconnect()}createContent(t,e,o){const r=$D(this.editor,e,o,this.images,this.selectedIndex);this.editor.domEvents.addEventListener(o,"mousedown",this.handleMouseDown),this.editor.addListener("resize",this.handleEditorResize),We(t)&&(this.parentContainerResizerObserver=new ResizeObserver(this.handleEditorResize),this.parentContainerResizerObserver.observe(t)),this.isEmpty()?M(r,"empty"):Vc(this.editor,this.blockData,e,t),setTimeout(()=>{const i=this.editor.findBlockById(this.blockData.id);i&&this.blockResizer.update(i)})}getImages(){return this.images}getWidthPercent(){return cn(this.blockData)}isEmpty(){return this.images.length===1&&ys(this.images[0])}setResizing(t){this.resizing=t}getSelectedIndex(){return this.selectedIndex}getBlock(){return this.editor.findBlockById(this.blockData.id)}setSelectedIndex(t){const e=this.getBlock();if(!e||t===this.selectedIndex)return;if(this.selectedIndex!==-1){const r=Es(e,this.selectedIndex);r&&F(r,"active")}this.selectedIndex=t;const o=Es(e,t);o&&M(o,"active")}async requestUploadImage(t){const e=this.editor.findBlockById(this.blockData.id);if(!e)return;const o=Es(e,t);if(lt(o,"error"))return;const r=await Lo("image/*");await this.replaceImage(t,r)}tryEnableResizer(){const t=this.editor.findBlockById(this.blockData.id);if(!t||!this.editor.isWritable())return;const e=Es(t,0);!this.isEmpty()&&this.images.length===1&&!lt(e,"error")&&this.blockResizer.enableResize(t)}disableResizer(){this.blockResizer.disableResize()}fixImageSize(t,e){const o=this.images[t];ys(o)||(o.width=e.naturalWidth,o.height=e.naturalHeight,o.virtualSize=!1,this.fixImageSizes())}removeImage(t){const e=this.editor.findBlockById(this.blockData.id);if(!e||t===-1||t>=this.images.length)return!1;const o=Y.default(this.images);o.splice(t,1),o[0].flex=NaN,ws(o),this.selectedIndex>=o.length&&(this.selectedIndex=o.length-1);const r=de(o,cn(this.blockData));return this.editor.updateEmbedData(e,r),!0}async replaceImage(t,e){const o=this.editor.findBlockById(this.blockData.id);if(!o)return!1;try{const i=await nl(e),s=this.images[t];if(s.virtualSize){const{width:c,height:a}=await b4(i);s.width=c,s.height=a,s.virtualSize=!1;const h=de(this.images,cn(this.blockData));this.editor.updateEmbedData(o,h)}const l={...s,src:i};C4(this.editor,o,l,t,this.selectedIndex,this.images),setTimeout(()=>{this.blockResizer.update(o)})}catch(i){return g4(this.editor,o,t,i,e),!1}const r=Es(o,t);if(!r)return!1;M(r,"uploading"),u4(r,0);try{const i=await this.editor.doc.uploadResource(e,{onProgress:c=>{u4(r,c)}});F(r,"uploading"),this.images[t].src=i.resourceId;const s=this.editor.findBlockById(this.blockData.id);if(!s)return!1;const l=de(this.images,cn(this.blockData));return this.editor.updateEmbedData(s,l),!0}catch(i){v4.error(i);const s=this.editor.findBlockById(this.blockData.id);return s&&(F(r,"uploading"),xD(r),g4(this.editor,s,t,i,e)),!1}}updateFlex(t){const e=this.editor.findBlockById(this.blockData.id);if(!e)return;d(v4,t.length===this.images.length,"invalid flex");for(let r=0;r<this.images.length;r++)this.images[r].flex=t[r];const o=de(this.images,cn(this.blockData));this.editor.updateEmbedData(e,o)}resetFlex(){const t=this.editor.findBlockById(this.blockData.id);if(!t)return;const e=Y.default(this.images);e[0].flex=NaN,ws(e);const o=de(e,cn(this.blockData));this.editor.updateEmbedData(t,o)}setData(t){this.blockData=t,this.images=Qr(t.embedData)}static create(t,e){const o=t.addCustom(`image-${e.id}`,()=>new Ft(t,e));return o.setData(e),o}static getImageObject(t,e){let o;return typeof e=="string"?o=e:o=G(e),t.getCustom(`image-${o}`)}}const EF="";function k4(n,t,e){const o=Ft.getImageObject(n,t),r=Y.default(o.getImages());if(r.length===1){n.deleteBlock(t);return}if(e===-1||e>=r.length)return;const i=wD(r);if(r.splice(e,1),r.length===1){const l=r[0],c=100*(l.flex/i);l.flex=1;const a=de([l],c);n.updateEmbedData(t,a);return}r[0].flex=NaN,ws(r);const s=de(r,o.getWidthPercent());n.updateEmbedData(t,s)}function FD(n,t,e,o){if(t.length===0||o==="after"||o==="before")return!1;let r=o.data;const i=Ft.getImageObject(n,e),s=Y.default(i.getImages());return t.forEach(l=>{const c={src:"",flex:1,width:0,height:0,virtualSize:!0};s.splice(r,0,c);const a=de(s,i.getWidthPercent());n.updateEmbedData(e,a),i.replaceImage(r,l),r+=1}),!0}function zD(n,t,e,o,r){var s,l;if(sl(e))return FD(n,e,t,o);if(e.type!=="custom"||e.customType!=="image"||!e.data)return;const i=e.data;if(r.isSourceBlock){const c=r.targetBlock,a=j(c);let h=K(c);o==="after"&&(h+=1);const m=100*(i.boundingRect.width/n.rootContainer.getBoundingClientRect().width),C=de([i.image],m),v={id:N(),type:"embed",embedType:"image",embedData:C},w=(l=(s=n.options.componentsOptions)==null?void 0:s.image)==null?void 0:l.defaultAlign;w&&(v.align=w),n.insertBlock(U(a),h,v),k4(n,t,i.index)}else{if(typeof o=="string")return;const c=t;let a=o.data;const h=Ft.getImageObject(n,c),f=Y.default(h.getImages());a>f.length&&(a=f.length),n.undoManager.runInGroup(()=>{const m=n.getBlockById(e.blockId);if(m===c){const C=i.index,v=a,w=i.image;if(C===v||v===C+1)return;let E=v;C<v?(f.splice(v,0,w),f.splice(C,1),E-=1):(f.splice(C,1),f.splice(v,0,w));const D=de(f,h.getWidthPercent());n.updateEmbedData(c,D),h.setSelectedIndex(E)}else{f.splice(a,0,i.image),f[0].flex=NaN,ws(f);const C=de(f,h.getWidthPercent());n.updateEmbedData(c,C),k4(n,m,i.index)}})}return!0}const UD=2;function qc(n,t,e){const o=Zn(t);if(e<=0){const s=o[0].getBoundingClientRect();return new DOMRect(s.left-4,s.top,2,s.height)}if(e===o.length){const s=o[e-1].getBoundingClientRect();return new DOMRect(s.right+2,s.top,2,s.height)}const r=o[e-1].getBoundingClientRect(),i=o[e].getBoundingClientRect();return new DOMRect((i.left+r.right)/2-1,r.top,UD,r.height)}function VD(n,t,e,o,r){for(let i=0;i<e.length;i++){const l=e[i].getBoundingClientRect();if(o<=l.right)return o<=l.left+l.width/2?{rect:qc(n,t,i),data:i}:{rect:qc(n,t,i+1),data:i+1}}return o>e[e.length-1].getBoundingClientRect().right?{rect:qc(n,t,e.length),data:e.length}:{rect:qc(n,t,e.length),data:0}}function qD(n,t,e,o,r){const i=Zn(t);if((e==null?void 0:e.type)!=="block"&&!(i.length>=6&&(e==null?void 0:e.blockId)!==G(t)))return VD(n,t,i,o)}const IF="";function Wc(n){const t=At(n);let e=t.querySelector(":scope > .block-helper");return e||(e=b("div",["block-helper"],t),b("span",["helper-sizer"],e,"A")),e}function f1(n,t,e){const o=Wc(n),i=Array.from(o.children).find(s=>{var c;return Number.parseInt((c=s.getAttribute("data-index"))!=null?c:"0",10)>e});o.insertBefore(t,i!=null?i:null)}const y4=40,WD=20;class GD{findTargetBlock(t,e){const o=e.target;if(o&&o instanceof Element){const c=z(o);if(c&&vt(t.rootContainer,c))return c}let r=e.clientX,i=e.clientY;const s=t.rootContainer.getBoundingClientRect().left;r<s&&s-r<y4&&(r+=y4);let l=document.elementFromPoint(r,i);if(l){const c=z(l);if(c&&vt(t.rootContainer,c))return c}if(i-=WD,l=document.elementFromPoint(r,i),l){const c=z(l);if(c&&vt(t.rootContainer,c))return c}return null}destroy(){}}class ZD extends Lc{constructor(e){super(e,{trigger:[],id:"empty-block-menu"});u(this,"currentBlock",null)}get isVisible(){return this.suggest.menu.isVisible}isInMenu(e){return this.menu.isInCommandBar(e)}show(){const o=this.editor.selection.focusedBlock;this.suggest.popup(o,0,"","")}setBlock(e){this.currentBlock=e}}function YD(n,t){const e=fd(n,t);if(!e)return[];const o=[];return Object.values(e).forEach(r=>{o.push(...r.commands.map(i=>({...i,source:"block-command",blockMenuItemCustomData:r.group})))}),o}function QD(n){const t=Uh(n),e=o=>{o.forEach(r=>{r.source="insert-block",r.children&&e(r.children)})};return e(t),t}function KD(n,t,e,o=!1){var a,h;const r=j(t),i=K(t);let s=i;yt(n,t)||o||(s+=1);const l=U(r),c=e;return c.commandProvider?c.commandProvider.executeCommand(n,e,{from:"block-menu",containerId:l,blockIndex:i}):(h=(a=c.blockOptions)==null?void 0:a.handleInsertEmptyBlock)==null?void 0:h.call(a,n,{containerId:l,blockIndex:s,item:e})}function JD(n,t){const e=Ge(n,t),o=n.getBlockData(t);return!(e!=="text"||o.heading)}function w4(n,t,e){n.getBlockData(t).heading===e?n.updateBlockData(t,{heading:null}):n.updateBlockData(t,{heading:e})}function XD(n,t,e){["left","center","right"].includes(e)?n.updateBlockData(t,{align:e}):n.updateBlockData(t,{align:null})}function tL(n,t){const o=n.getBlockData(t).quoted;n.updateBlockData(t,{quoted:o?void 0:!0})}function eL(n,t,e){const o=n.selection.range.focus;if(!o.isSimple())return;let r;switch(e){case"unordered-list":r="unordered";break;case"ordered-list":r="ordered";break;case"check-list":r="checked";break}const i=hl(n,t,"list",{offset:o.offset,data:{listType:r}});i&&n.undoManager.runInGroup(()=>{const s=K(t),l=j(t);n.deleteBlock(t),n.insertBlock(U(l),s,i.blockData)})}class nL{constructor(t,e,o){u(this,"source","text-style");u(this,"id","text-style-item");u(this,"name","Text styles");u(this,"element");u(this,"createHeadingItemElement",(t,e,o)=>{var i;const r=Tc();this.createItem("text",oc,e,JD(this.editor,t)),(i=r.insertBlockCommandItems)==null||i.forEach(s=>{s.id&&s.icon&&this.createItem(s.id,s.icon,e,o?o===Number(s.value):!1)})});u(this,"createListItemElement",(t,e,o)=>{const{checkbox:r,ordered:i}=o,l=it(t)==="list",c=l&&i===!1&&!r,a=l&&i,h=l&&!!r;this.createItem("unordered-list",v0,e,c),this.createItem("ordered-list",k0,e,a),this.createItem("check-list",C0,e,h)});u(this,"handleClick",(t,e)=>{var l,c;if(!e.target||!(e.target instanceof Node))return;const o=e.target instanceof Element?e.target:e.target.parentElement;if(!o)return;const r=o.closest(".text-style-item");if(!r)return;const i=r.id,s="heading-";if(i==="text"&&w4(t,this.block,null),i.startsWith(s)){const a=Number.parseInt(i.substring(s.length),10);a&&w4(t,this.block,a)}if(i==="blockquote"&&tL(t,this.block),i.startsWith("align")){const a=i.replace(/^align-/,"");XD(t,this.block,a)}(i==="unordered-list"||i==="ordered-list"||i==="check-list")&&eL(t,this.block,i),(c=(l=this.options).onAfterStyleItemClick)==null||c.call(l)});this.editor=t,this.block=e,this.options=o,this.element=this.createItemElement(t,e),t.domEvents.addEventListener(this.element,"click",this.handleClick)}createItemElement(t,e){const o=b("div",["text-styles"],null),r=b("div",["text-style-section"],o),i=t.getBlockData(e),s=i.heading,l=i.quoted,c=i.align||"left";return this.createHeadingItemElement(e,r,s),this.createListItemElement(e,r,i),this.createItem("blockquote",b0,r,!!l),this.createItem("align-left",es,r,c==="left"),this.createItem("align-center",Ku,r,c==="center"),this.createItem("align-right",Qu,r,c==="right"),o}createItem(t,e,o,r=!1){const i=["style-icon","text-style-item"];r&&i.push("active");const s=hr(e,i,o);s.id=t}}function B4(){return{source:"separator",type:"separator",id:`section-${N()}`,name:""}}const E4={copy:Lw,cut:Mw,delete:Rw,"lock-block":Ow,"unlock-block":Aw,comment:ns};function oL(n,t,e){const o=[],r=H(n,t);if(r&&o.push(new nL(n,t,e)),!yt(n,t)){r&&o.push(B4());const s=YD(n,t);s.sort((l,c)=>{var a,h;return((a=l.order)!=null?a:0)-((h=c.order)!=null?h:0)}),s.forEach(l=>{l.id in E4&&(l.icon=E4[l.id])}),o.push(...s)}const i=QD(n);return yt(n,t)?o.push(...i):o.push(B4(),{id:"insert-block-before",icon:_w,name:S.t("blockMenu.command.insertAbove"),children:i.map(s=>({...s,source:"insert-block-before"})),childrenMenuId:"quick-menu",source:"insert-block-before"},{id:"insert-block-after",icon:Nw,name:S.t("blockMenu.command.insertAfter"),children:i,source:"insert-block",childrenMenuId:"quick-menu"}),o}function rL(n,t,e){if(e.source==="block-command"){const o=e.blockMenuItemCustomData;Qm(n,t,o,e)}else(e.source==="insert-block"||e.source==="insert-block-before")&&KD(n,t,e,e.source==="insert-block-before")}function Gc(n,t){return n.getBlockData(t).lock}function m1(n,t){return!!Gc(n,t)}function Zc(n,t){const e=Gc(n,t);return e?e.userId===n.doc.getUser().userId:!1}function iL(n,t){const e=Gc(n,t);return e?e.userId!==n.doc.getUser().userId:!1}function sL(n,t){if(n.readonly||!n.isBlockWritable(t)||m1(n,t)&&!Zc(n,t))return;const e=n.doc.getUser(),o={userId:e.userId,displayName:e.displayName,locked:Date.now()},i={...n.getBlockData(t),lock:o};n.updateBlockData(t,i)}function lL(n,t){if(!Zc(n,t))return;const e={lock:null};n.updateBlockData(t,e)}class I4{constructor(){u(this,"executeCommand",(t,e,o)=>{const r=o.data;if(!r||!r.blockId)return;const i=t.getBlockById(r.blockId);r.type==="lock"?sL(t,i):r.type==="unlock"&&lL(t,i)})}create(t,e,o,r,i){const s=i.lock;s&&(s.userId!==t.doc.getUser().userId?M(r,"locked-by-others"):M(r,"locked-by-self"))}writable(t,e){if(iL(t,e))return!1}commands(t,e){const o=m1(t,e),r=Zc(t,e),i={blockId:G(e),type:"lock"},s={id:"lock-block",name:"",data:i,order:10};if(o)if(r)s.id="unlock-block",s.name=S.t("locker.unlock"),i.type="unlock";else{const l=Gc(t,e);s.name=S.t("locker.lockedBy",{name:(l==null?void 0:l.displayName)||""}),s.states=["disabled"]}else s.name=S.t("locker.lock");return{group:"block-locker",commands:[s],executeCommand:this.executeCommand}}}const xF="",cL={locker:{lock:"\u9501\u5B9A",unlock:"\u89E3\u9664\u9501\u5B9A",lockedBy:"\u88AB {name} \u9501\u5B9A"}},aL={locker:{lock:"Lock",unlock:"Unlock",lockedBy:"Locked by {name}"}};S.mergeLang({"zh-CN":cL,"en-US":aL});const dL=y("standard-block-actions");class uL{constructor(){u(this,"executeCommand",(t,e,o)=>{const r=o.data;try{const i=t.getBlockById(r);if(o.id==="delete"){t.deleteBlock(i);return}o.id==="copy"&&iu(t,i),o.id==="cut"&&(iu(t,i),t.deleteBlock(i))}catch(i){dL.error(`failed to execute block command: ${JSON.stringify(i)}`)}})}commands(t,e){const o=m1(t,e),r=o&&Zc(t,e),i=G(e);return{group:"standard-block-actions",commands:[{id:"copy",name:"Copy",data:i,order:1},{id:"cut",name:"Cut",data:i,order:2,states:o&&!r?["disabled"]:[]},{id:"delete",name:"Delete",data:i,order:3,states:o&&!r?["disabled"]:[]}],executeCommand:this.executeCommand}}}const x4=y("block-menu");class hL{constructor(t){u(this,"menu");u(this,"currentBlock",null);u(this,"commandBlock",null);u(this,"handleShow",()=>{d(x4,this.currentBlock,"no target block before show block menu");const t=oL(this.editor,this.currentBlock,{onAfterStyleItemClick:this.close});this.menu.updateItems(t),this.commandBlock=this.currentBlock});u(this,"handleClose",()=>{this.editor.focus()});u(this,"handleItemClick",(t,e)=>{d(x4,this.commandBlock,"no command block before show block menu"),rL(this.editor,this.commandBlock,e),!e.element&&!e.children&&this.close()});u(this,"close",()=>{this.menu.close()});this.editor=t,this.menu=new Wo([],void 0,{id:"block-menu"}),this.menu.on("show",this.handleShow),this.menu.on("close",this.handleClose),this.menu.on("click",this.handleItemClick),t.blockHooks.push(new uL)}show(t){this.menu.manualShow(t,{placement:"bottom-start"})}isInMenu(t){return this.menu.isInCommandBar(t)}setBlock(t){this.currentBlock=t}get isVisible(){return this.menu.isVisible}destroy(){this.menu.destroy()}}const S4=`<svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
377
|
+
`;function HT(n,t,e){const r={...n.getBlockData(t),language:e};n.updateBlockData(t,r)}function FT(n,t,e){const r={...n.getBlockData(t),nowrap:e};n.updateBlockData(t,r)}const Yr=y("code-block-header"),zT=Object.entries(Hc).map(([n,t])=>({id:n,name:t.name,language:t}));function UT(n,t){if(t){const e=n,{editor:o,codeBlock:r}=e.custom;HT(o,r,t.id);const i=r.querySelector(".code-block-header .language-select .name-label");i.innerText=t.name}}function VT(n,t,e){n.addCustom("code-header-language-select-dropdown",i=>{const s=new Yy(zT,i.rootElement,{placeholder:"Search for a language..."});return s.onSelected=UT,s});const o=b("div",["language-select"],null);b("span",["name-label"],o,e);const r=b("span",["arrow-icon"],o);return r.innerHTML=PT,n.domEvents.addEventListener(o,"click",(i,s)=>{const c=s.target.closest(".language-select"),a=z(c);d(Yr,a,"no parent block"),d(Yr,it(a)==="code","not a code block");const h=i.getBlockData(a),f=i.getCustom("code-header-language-select-dropdown");f.custom={codeBlock:a,editor:i},f.setSelectedId(h.language),f.show(c),M(t,"editing-language"),f.onHide=()=>{F(t,"editing-language")}}),o}function qT(){return b("div",["code-header-spacer"],null)}function WT(n,t){const e=t.target,o=e.closest(".code-header-button");d(Yr,o,"no button");const r=z(e);d(Yr,r,"no parent block");const i=o.getAttribute("data-id");if(d(Yr,it(r)==="code","not a code block"),i==="wrap"){const s=n.getBlockData(r);FT(n,r,!s.nowrap);return}if(i==="copy"){const s=Gr(r),l=tu(n,U(s)),c=Kg(n,l);navigator.clipboard.writeText(c).then(()=>{const a=o.getBoundingClientRect();Qy("Copied to clipboard",{position:{x:a.x+a.width/2,y:a.bottom+30}})}).catch(a=>{Yr.error(a.message)});return}i==="caption"&&ST(n,r)}function a1(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",WT),r}function GT(n,t,e){const o=At(t),r=b("div",["code-block-header"],o),i=Hc[e.language]||Hc.plain;r.appendChild(VT(n,t,i.name)),r.appendChild(qT()),r.appendChild(a1(n,"copy","Copy",$T)),r.appendChild(a1(n,"wrap","Wrap",jT)),r.appendChild(a1(n,"caption","Caption",null))}function ZT(n,t,e,o){c1.init(n);const r=o.children,i=no(e,"div");i.setAttribute("data-language",o.language||"text"),r4(n,e,o);const s=b("div",["editor-code-root"],i),l=b("div",["code-text-root"],s);if(n.createChildContainer(t,l,r[0]),r.length===2){const c=b("div",["code-caption-root"],s);n.createChildContainer(t,c,r[1])}return GT(n,e,o),i}function YT(n){const t={id:N(),type:"text",text:[]},e=N();return n.doc.localInsertChildContainer(e,[t]),{blockData:{id:N(),type:"code",language:"plain",children:[e]},focusBlockId:t.id}}const En=y("list-block");function QT(n,t,e,o,r){MT(n),OT(n),d(En,r.type==="code","invalid block data type");const i=r;return d(En,i.children,"invalid block data children"),d(En,i.children.length===1||i.children.length===2,"invalid block data children length"),M(o,"drag-preview-element"),ZT(n,t,o,i)}function KT(n){return 1}function JT(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t)||!mn(r))return null;const i=Fc(t);if(!mn(r))return null;const s=r;if(i.indexOf(s)===-1||Ve(s)>1)return null;const l=bt(t,U(s));return new Qe(n,{anchor:l,focus:l})}function XT(n,t,e,o){return null}function tD(n,t){return n.getBoundingClientRect()}function eD(n,t,e,o){if(e.isSimple()){d(En,o.isSimple(),"from is simple position but to is not simple position"),En.debug("full select list"),M(t,"full-selected");return}d(En,!o.isSimple(),"from is complex position but end is simple position");const r=e,i=o;d(En,r.blockId===i.blockId,"only allow update one table selection"),Fc(t).forEach(l=>{const c=U(l);(c===r.childContainerId||c===i.childContainerId)&&M(l,"selected")})}function nD(n){n.rootContainer.querySelectorAll('[data-type="editor-block"][data-block-type="code"]').forEach(t=>{F(t,"full-selected"),t.querySelectorAll("div[data-type=editor-container].child.selected").forEach(e=>{F(e,"selected")})})}function oD(n,t){return Fc(t)}function rD(n,t,e,o,r){if(o==="ArrowDown"||o==="ArrowRight"){if(e===Gr(t))return Zr(t)}else if(e===Zr(t))return Gr(t);return null}function iD(n,t,e,o){const r=Fc(t),i=r.map(U),s=i.indexOf(e.childContainerId),l=i.indexOf(o.childContainerId);d(En,s!==-1,"invalid start pos"),d(En,l!==-1,"invalid end pos");const c=[r[s]];return s!==l&&c.push(r[l]),c}function sD(n,t,e){d(En,tr(t),"invalid block type"),r4(n,t,e)}async function lD(n,t){const e=YT(n);if(!e)return null;const{blockData:o,focusBlockId:r}=e;return n.insertBlock(t.containerId,t.blockIndex,o,Lt(n,r,0))}function cD(n){return{name:"CodeBlock",insertBlockCommandItems:[{id:"insert-code",name:S.t("code.title"),icon:Dw,order:300,group:"common"}],handleInsertEmptyBlock:lD}}function aD(){return{abstract:`[${S.t("code.abstract")}]`}}const bs={blockType:"code",blockKind:"complex",createBlockContent:QT,getBlockTextLength:KT,getRangeFromPoint:JT,moveCaret:XT,getCaretRect:tD,updateSelection:eD,clearSelection:nD,getChildContainers:oD,getNextContainer:rD,getSelectedContainers:iD,convertFrom:xT,handleBlockElementUpdated:sD,getOptions:cD,getBlockProperties:aD},d1={...Ai,blockType:"code-line"};function dD(n){if(!n.isWritable())return!1;const t=n.getFocusedBlock();if(!!zc(t)){if(n.selection.range.isCollapsed()){const e=n.selection.range.start;return n.insertTextToBlock(t,e.offset," "),!0}return n.undoManager.runInGroup(()=>{Ke(n).forEach(o=>{n.insertTextToBlock(o.block,0," ")})}),!0}}function uD(n){if(!n.isWritable())return!1;const t=n.getFocusedBlock();if(!zc(t))return;const e=[" "," "," "," "];return n.undoManager.runInGroup(()=>{Ke(n).forEach(r=>{const i=wt(n.getBlockText(r.block));for(let s=0;s<e.length;s++){const l=e[s];if(i.startsWith(l)){n.deleteTextFromBlock(r.block,0,l.length);break}}})}),!0}const hD={Tab:dD,"Shift+Tab":uD},vs=y("code-text-decorate");class ks{decorateText(t,e,o){var C;if(d(vs,e.length>0,"invalid path"),e.length===1)return{};const r=e[e.length-2];if(t.doc.getBlockData(r.containerId,r.blockIndex).type!=="code")return{};const s=o;if(s.length===0)return{};const l=wt(s),c=t.doc.getBlockData(r.containerId,r.blockIndex),a=bi.default.tokenize(l,(C=bi.default.languages[c.language])!=null?C:bi.default.languages.plain),h=(v,w)=>{if(d(vs,v,"no token"),typeof v=="string")return[{insert:v,attributes:Y.default(w)}];d(vs,v instanceof bi.default.Token,"invalid token type");const E=v.content,L=Y.default(w);return L[`style-code-${v.type}`]=!0,typeof E=="string"?[{insert:E,attributes:L}]:Array.isArray(E)?E.map(A=>h(A,L)).flat():(d(vs,E instanceof bi.default.Token,"invalid token"),h(E,L))},m=a.map(v=>h(v,{})).flat();return d(vs,ce(m)===ce(s),"failed to highlight code, text length mismatch"),{text:m}}}const fD={code:{title:"\u4EE3\u7801",abstract:"\u4EE3\u7801"}},mD={code:{title:"Code",abstract:"Code"}};S.mergeLang({"zh-CN":fD,"en-US":mD});const gD=y("image-data"),pD=1e3,CD=400,bD=10;function ys(n){return n.src.startsWith("empty:")||!n.src}function vD(n){return n.src.startsWith("http:")||n.src.startsWith("https:")}function l4(n){return`${Ci.default(n)}_width`}function c4(n){return`${Ci.default(n)}_height`}function a4(n){return`${n}_flex`}function ws(n){if(n.every(r=>typeof r.flex=="number"&&r.flex))return;const t=100,o=n.map(r=>r.width/(r.height/t)).reduce((r,i)=>r+i,0);n.forEach(r=>{const i=r.width/(r.height/t);r.flex=i/o})}function Qr(n){const t=(r,i)=>{r||(r=`empty:${i}`);const s=l4(r),l=c4(r),c=a4(i);let a=n[s],h=n[l],f=n[c];return typeof a=="string"&&(a=Number.parseInt(a,10)),typeof h=="string"&&(h=Number.parseInt(h,10)),typeof f=="string"&&(f=Number.parseInt(f,10)),a&&h?{src:r,width:a,height:h,flex:f,virtualSize:!1}:(a=pD,h=CD,{src:r,width:a,height:h,flex:f,virtualSize:!0})};let e=[];const o=n.src;return Array.isArray(o)?e=o.map(t):typeof o=="string"&&(e=o.split("|").map(t)),ws(e),e}function cn(n){var o;const t=n.embedData;return Qr(n.embedData).length>1?100:(o=t.widthPercent)!=null?o:100}function kD(n,t){if(Qr(t.embedData).length>1)return"100%";const o=cn(t);return`${n.rootContainer.getBoundingClientRect().width*o/100}px`}function de(n,t){const o={src:n.map(r=>r.src).join("|"),widthPercent:t};return n.forEach((r,i)=>{if(r.width&&r.height&&!r.virtualSize){const l=r.src||`empty:${i}`,c=l4(l);o[c]=r.width;const a=c4(l);o[a]=r.height}d(gD,r.flex,"no image flex");const s=a4(i);o[s]=r.flex}),o}function yD(n,t,e){const o=Qr(t.embedData),r=o.length===1?n.rootContainer:e,i=cn(t);let s=r.getBoundingClientRect().width*(i/100);if(s-=Number.parseFloat(window.getComputedStyle(r).paddingLeft)+Number.parseFloat(window.getComputedStyle(r).paddingRight),o.length===1){const a=o[0];return a.height/(a.width/s)}s-=(o.length-1)*bD;const l=o.reduce((a,h)=>a+h.flex,0);let c=0;for(const a of o){const f=s*a.flex/l/a.width*a.height;c=Math.max(f,c)}return c}function wD(n){return n.reduce((e,o)=>e+o.flex,0)}const BD=y("image-dom");function d4(n){return n.querySelector(".uploading-progress-mask")}function ED(n){const t=d4(n);if(t)return t;const e=b("div",["uploading-progress-mask"],n),o=b("div",["uploading-progress-bar"],e);return b("div",["uploading-progress-bar-value"],o),o}function ID(n){const e=ED(n).querySelector(".uploading-progress-bar-value");return d(BD,e,"no progress value"),e}function u4(n,t){const e=ID(n);e.style.width=`${t}%`}function xD(n){var t;(t=d4(n))==null||t.remove()}function SD(n){let t;return n.forEach((e,o)=>{o.toLocaleLowerCase()==="content-type"&&(t=e)}),t!=null?t:""}async function TD(n){try{const t=await fetch(n,{credentials:"same-origin"}),e=await t.blob(),o=SD(t.headers).toLocaleLowerCase();let r="";if(o){const s=Tf.default[o].extensions;s&&s.length>0&&(r=s[0])}return new File([e],`${Date.now()}.${r}`,{type:o})}catch{return null}}function er(n,t){const e=typeof t=="string"?t:G(t);return n.getCustom(`image-${e}`)}function Uc(n,t){if(!t||!(t instanceof Node))return null;const e=z(t);return e?er(n,e):null}function Zn(n){return Array.from(n.querySelectorAll(".image-container"))}function Vc(n,t,e,o){const r=e!=null?e:n.findBlockById(t.id);if(!r)return;const i=o||j(r),s=kD(n,t),l=yD(n,t,i),c=rt(r);c.style.width=s;const a=r.querySelector(".images");!a||(a.style.height=`${l}px`)}const u1=y("table-resize-drag-drop");class DD{constructor(t,e,o,r){u(this,"cursor","col-resize");u(this,"initWidths");this.editor=t,this.elem=e,this.data=o,this.mouseDownEvent=r;const i=this.data.block,l=er(this.editor,i).getImages(),c=this.data.splitterIndex;d(u1,c>=0&&c<l.length-1,`invalid splitter index: ${c}`);const h=Zn(i).map(f=>f.getBoundingClientRect().width);this.initWidths=h}onDragStart(t,e,o){if(!this.editor.isWritable())return;const r=this.data.block;er(this.editor,r).setResizing(!0)}onDragging(t,e,o,r,i){const s=this.data.block,l=er(this.editor,s),c=Y.default(l.getImages()),a=this.data.splitterIndex;d(u1,a>=0&&a<c.length-1,`invalid splitter index: ${a}`);const h=this.initWidths[a],f=this.initWidths[a+1];if(h+f<100)return;let m=r;h+m<50&&(m=50-h),f-m<50&&(m=f-50);const w=[...this.initWidths];w[a]+=m,w[a+1]-=m;const E=Zn(s);d(u1,E.length===c.length,"invalid image data");const L=w.reduce((A,P)=>A+P,0);for(let A=0;A<c.length;A++){const P=w[A]/L;c[A].flex=P,E[A].style.flexGrow=`${P}`}const x=Y.default(this.editor.getBlockData(s)),O=de(c,cn(x));x.embedData=O,Vc(this.editor,x,s,null)}onDragEnd(t,e,o,r,i){const s=this.data.block,l=er(this.editor,s),a=Zn(s).map(h=>Number.parseFloat(h.style.flexGrow));l.updateFlex(a),l.setResizing(!1)}}function h4(n){var t;return!n||!(n instanceof HTMLElement)?null:lt(n,"image-splitter")?n:(t=n.closest(".image-splitter"))!=null?t:null}function LD(n,t){var s;const e=h4(t.target);if(!e)return;const o=z(e);if(!o)return;er(n,o).setSelectedIndex(-1),n.selection.selectBlock(o,0);const r=Number.parseInt((s=e.getAttribute("data-index"))!=null?s:"",10);if(Number.isNaN(r)||typeof r!="number")return;const i={block:o,splitterIndex:r};qa(new DD(n,e,i,t))}function MD(n,t){t.preventDefault(),t.stopPropagation();const e=h4(t.target);if(!e)return;const o=z(e);!o||er(n,o).resetFlex()}function RD(n,t,e,o){const r=b("div",["image-splitter"],e);b("div",["image-splitter-indicator"],r),r.setAttribute("data-index",`${o}`),n.domEvents.addEventListener(r,"mousedown",LD),n.domEvents.addEventListener(r,"dblclick",MD)}const OD=y("image-item");function f4(n){return!n||!(n instanceof Node)?null:z(n)}function m4(n){const t=f4(n);return t?Zn(t):[]}function h1(n){if(!n||!(n instanceof Node))return null;const t=n instanceof Element?n:n.parentElement;if(!t)return null;const e=t.closest(".image-container");return e||null}function Bs(n){const t=h1(n);return t?m4(n).indexOf(t):-1}async function AD(n,t){const e=Uc(n,t.target);if(!e)return;const o=Bs(t.target);if(o===-1)return;const r=t.target;if(!(r instanceof HTMLImageElement))return;const i=e.getImages()[o];if(i.virtualSize&&e.fixImageSize(o,r),!i||!vD(i)||i.downloading)return;i.downloading=!0;const s=await TD(i.src);s?e.replaceImage(o,s):OD.warn(`failed to download image: ${i.src}`)}function _D(n,t,e){if(t.querySelector(".load-error"))return;const r=e.src.startsWith("http:")||e.src.startsWith("https:"),i=b("div",["load-error"],t),s=b("div",["error-icon"],i);s.innerHTML=m0;const l=b("div",["error-message"],i);r?(l.innerHTML=S.t("image.load.remote.failed"),n.domEvents.addEventListener(i,"click",(c,a)=>{a.preventDefault(),a.target instanceof HTMLElement&&a.target.tagName==="A"&&window.open(e.src,"_blank")})):(l.innerHTML=S.t("image.load.failed"),n.domEvents.addEventListener(i,"click",(c,a)=>{a.preventDefault(),a.target instanceof HTMLElement&&a.target.tagName==="A"&&jD(c,a.target)}))}function ND(n,t){const e=Uc(n,t.target);if(!e)return;const o=Bs(t.target);if(o===-1)return;const r=e.getImages()[o];if(!r)return;const i=h1(t.target);!i||(M(i,"error","error-load"),_D(n,i,r))}function PD(n,t,e){if(t.querySelector(".upload-error"))return;const r=b("div",["upload-error"],t),i=b("div",["error-icon"],r);i.innerHTML=m0;const s=b("div",["error-message"],r);s.innerHTML=S.t("image.upload.failed"),n.domEvents.addEventListener(r,"click",(l,c)=>{if(c.preventDefault(),!c.target||!(c.target instanceof Element)||c.target.tagName!=="A")return;const a=Uc(l,c.target),h=Bs(c.target);!a||h===-1||a.replaceImage(h,e)})}function g4(n,t,e,o,r){const i=Zn(t)[e];!i||(M(i,"error","error-upload"),PD(n,i,r))}function p4(n,t,e,o,r,i){const s=b("div",["image-container"],t);if(s.setAttribute("data-src",e.src),i.length>1&&(s.style.flexShrink=`${e.flex}`,s.style.flexGrow=`${e.flex}`),r===o&&M(s,"active"),ys(e)){M(s,"empty");const c=b("div",["upload-image-icon"],s);return c.innerHTML=hw,s}const l=b("img",["editor-image"],s);if(l.src=n.doc.buildResourceUrl(e.src),l.draggable=!0,!ys(e)&&!n.readonly&&n.domEvents.addEventListener(l,"load",AD),n.domEvents.addEventListener(l,"error",ND),e.src.startsWith("https:")||e.src.startsWith("http:")){const c=b("div",["image-warning"],s);c.innerHTML=f0,c.setAttribute(`data-editor-tooltip-${n.clientId}`,S.t("image.load.remote.tooltip"))}return s}function $D(n,t,e,o,r){const i=b("div",["images"],e);return o.forEach((s,l)=>{l>0&&RD(n,t,i,l-1),p4(n,i,s,l,r,o)}),o.length>1&&M(t,"multi"),i}function C4(n,t,e,o,r,i){const l=Array.from(t.querySelectorAll(".image-container"))[o];if(!l)return;const c=p4(n,null,e,o,r,i);l.insertAdjacentElement("beforebegin",c),l.remove()}function Es(n,t){return Zn(n)[t]}function jD(n,t){const e=f4(t);if(!e)return;const o=Bs(t);if(o===-1)return;const r=Uc(n,t);if(!r)return;const i=r.getImages()[o];C4(n,e,i,o,r.getSelectedIndex(),r.getImages())}function an(n){return it(n)==="embed"&&Le(n)==="image"}async function b4(n){return new Promise((t,e)=>{const o=new Image;o.onload=()=>{t({width:o.naturalWidth,height:o.naturalHeight})},o.onerror=e,o.src=n})}async function HD(n){const t=await nl(n);return b4(t)}const v4=y("image-object");class Ft{constructor(t,e){u(this,"images",[]);u(this,"selectedIndex",-1);u(this,"blockResizer");u(this,"resizing",!1);u(this,"parentContainerResizerObserver",null);u(this,"handleMouseDown",async(t,e)=>{const o=Bs(e.target);if(o===-1)return;const r=this.images[o];ys(r)||this.setSelectedIndex(o)});u(this,"handleEditorResize",()=>{if(this.isEmpty()||this.resizing)return;const t=this.editor.findBlockById(this.blockData.id);!t||Vc(this.editor,this.blockData,t,null)});u(this,"handleResizing",(t,e)=>{const o=this.editor.findBlockById(this.blockData.id);if(!o)return;const i=this.editor.rootContainer.getBoundingClientRect().width,s=o.getBoundingClientRect();let l=e.width>s.width?s.width:e.width;l<50&&(l=50);const c=l*100/i;this.blockData.embedData.widthPercent=c,Vc(this.editor,this.blockData,o,null)});u(this,"handleResized",t=>{const e=this.editor.findBlockById(this.blockData.id);if(!e)return;const o=de(this.images,cn(this.blockData));this.editor.updateEmbedData(e,o),this.blockResizer.enableResize(e)});u(this,"fixImageSizes",Qt.default(()=>{const t=this.editor.findBlockById(this.blockData.id);if(!t)return;const e=de(this.images,cn(this.blockData));this.editor.updateEmbedData(t,e)},1e3));this.editor=t,this.blockData=e,this.blockResizer=new Pc(this.editor,{resize:["top-left","top-right","bottom-left","bottom-right"]}),this.blockResizer.addListener("resizing",this.handleResizing),this.blockResizer.addListener("resized",this.handleResized),this.images=Qr(this.blockData.embedData)}destroy(){var t;this.blockResizer.removeAllListeners(),this.blockResizer.destroy(),this.editor.domEvents.removeEventListener(null,null,this.handleMouseDown),(t=this.parentContainerResizerObserver)==null||t.disconnect()}createContent(t,e,o){const r=$D(this.editor,e,o,this.images,this.selectedIndex);this.editor.domEvents.addEventListener(o,"mousedown",this.handleMouseDown),this.editor.addListener("resize",this.handleEditorResize),We(t)&&(this.parentContainerResizerObserver=new ResizeObserver(this.handleEditorResize),this.parentContainerResizerObserver.observe(t)),this.isEmpty()?M(r,"empty"):Vc(this.editor,this.blockData,e,t),setTimeout(()=>{const i=this.editor.findBlockById(this.blockData.id);i&&this.blockResizer.update(i)})}getImages(){return this.images}getWidthPercent(){return cn(this.blockData)}isEmpty(){return this.images.length===1&&ys(this.images[0])}setResizing(t){this.resizing=t}getSelectedIndex(){return this.selectedIndex}getBlock(){return this.editor.findBlockById(this.blockData.id)}setSelectedIndex(t){const e=this.getBlock();if(!e||t===this.selectedIndex)return;if(this.selectedIndex!==-1){const r=Es(e,this.selectedIndex);r&&F(r,"active")}this.selectedIndex=t;const o=Es(e,t);o&&M(o,"active")}async requestUploadImage(t){const e=this.editor.findBlockById(this.blockData.id);if(!e)return;const o=Es(e,t);if(lt(o,"error"))return;const r=await Lo("image/*");await this.replaceImage(t,r)}tryEnableResizer(){const t=this.editor.findBlockById(this.blockData.id);if(!t||!this.editor.isWritable())return;const e=Es(t,0);!this.isEmpty()&&this.images.length===1&&!lt(e,"error")&&this.blockResizer.enableResize(t)}disableResizer(){this.blockResizer.disableResize()}fixImageSize(t,e){const o=this.images[t];ys(o)||(o.width=e.naturalWidth,o.height=e.naturalHeight,o.virtualSize=!1,this.fixImageSizes())}removeImage(t){const e=this.editor.findBlockById(this.blockData.id);if(!e||t===-1||t>=this.images.length)return!1;const o=Y.default(this.images);o.splice(t,1),o[0].flex=NaN,ws(o),this.selectedIndex>=o.length&&(this.selectedIndex=o.length-1);const r=de(o,cn(this.blockData));return this.editor.updateEmbedData(e,r),!0}async replaceImage(t,e){const o=this.editor.findBlockById(this.blockData.id);if(!o)return!1;try{const i=await nl(e),s=this.images[t];if(s.virtualSize){const{width:c,height:a}=await b4(i);s.width=c,s.height=a,s.virtualSize=!1;const h=de(this.images,cn(this.blockData));this.editor.updateEmbedData(o,h)}const l={...s,src:i};C4(this.editor,o,l,t,this.selectedIndex,this.images),setTimeout(()=>{this.blockResizer.update(o)})}catch(i){return g4(this.editor,o,t,i,e),!1}const r=Es(o,t);if(!r)return!1;M(r,"uploading"),u4(r,0);try{const i=await this.editor.doc.uploadResource(e,{onProgress:c=>{u4(r,c)}});F(r,"uploading"),this.images[t].src=i.resourceId;const s=this.editor.findBlockById(this.blockData.id);if(!s)return!1;const l=de(this.images,cn(this.blockData));return this.editor.updateEmbedData(s,l),!0}catch(i){v4.error(i);const s=this.editor.findBlockById(this.blockData.id);return s&&(F(r,"uploading"),xD(r),g4(this.editor,s,t,i,e)),!1}}updateFlex(t){const e=this.editor.findBlockById(this.blockData.id);if(!e)return;d(v4,t.length===this.images.length,"invalid flex");for(let r=0;r<this.images.length;r++)this.images[r].flex=t[r];const o=de(this.images,cn(this.blockData));this.editor.updateEmbedData(e,o)}resetFlex(){const t=this.editor.findBlockById(this.blockData.id);if(!t)return;const e=Y.default(this.images);e[0].flex=NaN,ws(e);const o=de(e,cn(this.blockData));this.editor.updateEmbedData(t,o)}setData(t){this.blockData=t,this.images=Qr(t.embedData)}static create(t,e){const o=t.addCustom(`image-${e.id}`,()=>new Ft(t,e));return o.setData(e),o}static getImageObject(t,e){let o;return typeof e=="string"?o=e:o=G(e),t.getCustom(`image-${o}`)}}const EF="";function k4(n,t,e){const o=Ft.getImageObject(n,t),r=Y.default(o.getImages());if(r.length===1){n.deleteBlock(t);return}if(e===-1||e>=r.length)return;const i=wD(r);if(r.splice(e,1),r.length===1){const l=r[0],c=100*(l.flex/i);l.flex=1;const a=de([l],c);n.updateEmbedData(t,a);return}r[0].flex=NaN,ws(r);const s=de(r,o.getWidthPercent());n.updateEmbedData(t,s)}function FD(n,t,e,o){if(t.length===0||o==="after"||o==="before")return!1;let r=o.data;const i=Ft.getImageObject(n,e),s=Y.default(i.getImages());return t.forEach(l=>{const c={src:"",flex:1,width:0,height:0,virtualSize:!0};s.splice(r,0,c);const a=de(s,i.getWidthPercent());n.updateEmbedData(e,a),i.replaceImage(r,l),r+=1}),!0}function zD(n,t,e,o,r){var s,l;if(sl(e))return FD(n,e,t,o);if(e.type!=="custom"||e.customType!=="image"||!e.data)return;const i=e.data;if(r.isSourceBlock){const c=r.targetBlock,a=j(c);let h=K(c);o==="after"&&(h+=1);const m=100*(i.boundingRect.width/n.rootContainer.getBoundingClientRect().width),C=de([i.image],m),v={id:N(),type:"embed",embedType:"image",embedData:C},w=(l=(s=n.options.componentsOptions)==null?void 0:s.image)==null?void 0:l.defaultAlign;w&&(v.align=w),n.insertBlock(U(a),h,v),k4(n,t,i.index)}else{if(typeof o=="string")return;const c=t;let a=o.data;const h=Ft.getImageObject(n,c),f=Y.default(h.getImages());a>f.length&&(a=f.length),n.undoManager.runInGroup(()=>{const m=n.getBlockById(e.blockId);if(m===c){const C=i.index,v=a,w=i.image;if(C===v||v===C+1)return;let E=v;C<v?(f.splice(v,0,w),f.splice(C,1),E-=1):(f.splice(C,1),f.splice(v,0,w));const L=de(f,h.getWidthPercent());n.updateEmbedData(c,L),h.setSelectedIndex(E)}else{f.splice(a,0,i.image),f[0].flex=NaN,ws(f);const C=de(f,h.getWidthPercent());n.updateEmbedData(c,C),k4(n,m,i.index)}})}return!0}const UD=2;function qc(n,t,e){const o=Zn(t);if(e<=0){const s=o[0].getBoundingClientRect();return new DOMRect(s.left-4,s.top,2,s.height)}if(e===o.length){const s=o[e-1].getBoundingClientRect();return new DOMRect(s.right+2,s.top,2,s.height)}const r=o[e-1].getBoundingClientRect(),i=o[e].getBoundingClientRect();return new DOMRect((i.left+r.right)/2-1,r.top,UD,r.height)}function VD(n,t,e,o,r){for(let i=0;i<e.length;i++){const l=e[i].getBoundingClientRect();if(o<=l.right)return o<=l.left+l.width/2?{rect:qc(n,t,i),data:i}:{rect:qc(n,t,i+1),data:i+1}}return o>e[e.length-1].getBoundingClientRect().right?{rect:qc(n,t,e.length),data:e.length}:{rect:qc(n,t,e.length),data:0}}function qD(n,t,e,o,r){const i=Zn(t);if((e==null?void 0:e.type)!=="block"&&!(i.length>=6&&(e==null?void 0:e.blockId)!==G(t)))return VD(n,t,i,o)}const IF="";function Wc(n){const t=At(n);let e=t.querySelector(":scope > .block-helper");return e||(e=b("div",["block-helper"],t),b("span",["helper-sizer"],e,"A")),e}function f1(n,t,e){const o=Wc(n),i=Array.from(o.children).find(s=>{var c;return Number.parseInt((c=s.getAttribute("data-index"))!=null?c:"0",10)>e});o.insertBefore(t,i!=null?i:null)}const y4=40,WD=20;class GD{findTargetBlock(t,e){const o=e.target;if(o&&o instanceof Element){const c=z(o);if(c&&vt(t.rootContainer,c))return c}let r=e.clientX,i=e.clientY;const s=t.rootContainer.getBoundingClientRect().left;r<s&&s-r<y4&&(r+=y4);let l=document.elementFromPoint(r,i);if(l){const c=z(l);if(c&&vt(t.rootContainer,c))return c}if(i-=WD,l=document.elementFromPoint(r,i),l){const c=z(l);if(c&&vt(t.rootContainer,c))return c}return null}destroy(){}}class ZD extends Lc{constructor(e){super(e,{trigger:[],id:"empty-block-menu"});u(this,"currentBlock",null)}get isVisible(){return this.suggest.menu.isVisible}isInMenu(e){return this.menu.isInCommandBar(e)}show(){const o=this.editor.selection.focusedBlock;this.suggest.popup(o,0,"","")}setBlock(e){this.currentBlock=e}}function YD(n,t){const e=fd(n,t);if(!e)return[];const o=[];return Object.values(e).forEach(r=>{o.push(...r.commands.map(i=>({...i,source:"block-command",blockMenuItemCustomData:r.group})))}),o}function QD(n){const t=Uh(n),e=o=>{o.forEach(r=>{r.source="insert-block",r.children&&e(r.children)})};return e(t),t}function KD(n,t,e,o=!1){var a,h;const r=j(t),i=K(t);let s=i;yt(n,t)||o||(s+=1);const l=U(r),c=e;return c.commandProvider?c.commandProvider.executeCommand(n,e,{from:"block-menu",containerId:l,blockIndex:i}):(h=(a=c.blockOptions)==null?void 0:a.handleInsertEmptyBlock)==null?void 0:h.call(a,n,{containerId:l,blockIndex:s,item:e})}function JD(n,t){const e=Ge(n,t),o=n.getBlockData(t);return!(e!=="text"||o.heading)}function w4(n,t,e){n.getBlockData(t).heading===e?n.updateBlockData(t,{heading:null}):n.updateBlockData(t,{heading:e})}function XD(n,t,e){["left","center","right"].includes(e)?n.updateBlockData(t,{align:e}):n.updateBlockData(t,{align:null})}function tL(n,t){const o=n.getBlockData(t).quoted;n.updateBlockData(t,{quoted:o?void 0:!0})}function eL(n,t,e){const o=n.selection.range.focus;if(!o.isSimple())return;let r;switch(e){case"unordered-list":r="unordered";break;case"ordered-list":r="ordered";break;case"check-list":r="checked";break}const i=hl(n,t,"list",{offset:o.offset,data:{listType:r}});i&&n.undoManager.runInGroup(()=>{const s=K(t),l=j(t);n.deleteBlock(t),n.insertBlock(U(l),s,i.blockData)})}class nL{constructor(t,e,o){u(this,"source","text-style");u(this,"id","text-style-item");u(this,"name","Text styles");u(this,"element");u(this,"createHeadingItemElement",(t,e,o)=>{var i;const r=Tc();this.createItem("text",oc,e,JD(this.editor,t)),(i=r.insertBlockCommandItems)==null||i.forEach(s=>{s.id&&s.icon&&this.createItem(s.id,s.icon,e,o?o===Number(s.value):!1)})});u(this,"createListItemElement",(t,e,o)=>{const{checkbox:r,ordered:i}=o,l=it(t)==="list",c=l&&i===!1&&!r,a=l&&i,h=l&&!!r;this.createItem("unordered-list",v0,e,c),this.createItem("ordered-list",k0,e,a),this.createItem("check-list",C0,e,h)});u(this,"handleClick",(t,e)=>{var l,c;if(!e.target||!(e.target instanceof Node))return;const o=e.target instanceof Element?e.target:e.target.parentElement;if(!o)return;const r=o.closest(".text-style-item");if(!r)return;const i=r.id,s="heading-";if(i==="text"&&w4(t,this.block,null),i.startsWith(s)){const a=Number.parseInt(i.substring(s.length),10);a&&w4(t,this.block,a)}if(i==="blockquote"&&tL(t,this.block),i.startsWith("align")){const a=i.replace(/^align-/,"");XD(t,this.block,a)}(i==="unordered-list"||i==="ordered-list"||i==="check-list")&&eL(t,this.block,i),(c=(l=this.options).onAfterStyleItemClick)==null||c.call(l)});this.editor=t,this.block=e,this.options=o,this.element=this.createItemElement(t,e),t.domEvents.addEventListener(this.element,"click",this.handleClick)}createItemElement(t,e){const o=b("div",["text-styles"],null),r=b("div",["text-style-section"],o),i=t.getBlockData(e),s=i.heading,l=i.quoted,c=i.align||"left";return this.createHeadingItemElement(e,r,s),this.createListItemElement(e,r,i),this.createItem("blockquote",b0,r,!!l),this.createItem("align-left",es,r,c==="left"),this.createItem("align-center",Ku,r,c==="center"),this.createItem("align-right",Qu,r,c==="right"),o}createItem(t,e,o,r=!1){const i=["style-icon","text-style-item"];r&&i.push("active");const s=hr(e,i,o);s.id=t}}function B4(){return{source:"separator",type:"separator",id:`section-${N()}`,name:""}}const E4={copy:Lw,cut:Mw,delete:Rw,"lock-block":Ow,"unlock-block":Aw,comment:ns};function oL(n,t,e){const o=[],r=H(n,t);if(r&&o.push(new nL(n,t,e)),!yt(n,t)){r&&o.push(B4());const s=YD(n,t);s.sort((l,c)=>{var a,h;return((a=l.order)!=null?a:0)-((h=c.order)!=null?h:0)}),s.forEach(l=>{l.id in E4&&(l.icon=E4[l.id])}),o.push(...s)}const i=QD(n);return yt(n,t)?o.push(...i):o.push(B4(),{id:"insert-block-before",icon:_w,name:S.t("blockMenu.command.insertAbove"),children:i.map(s=>({...s,source:"insert-block-before"})),childrenMenuId:"quick-menu",source:"insert-block-before"},{id:"insert-block-after",icon:Nw,name:S.t("blockMenu.command.insertAfter"),children:i,source:"insert-block",childrenMenuId:"quick-menu"}),o}function rL(n,t,e){if(e.source==="block-command"){const o=e.blockMenuItemCustomData;Qm(n,t,o,e)}else(e.source==="insert-block"||e.source==="insert-block-before")&&KD(n,t,e,e.source==="insert-block-before")}function Gc(n,t){return n.getBlockData(t).lock}function m1(n,t){return!!Gc(n,t)}function Zc(n,t){const e=Gc(n,t);return e?e.userId===n.doc.getUser().userId:!1}function iL(n,t){const e=Gc(n,t);return e?e.userId!==n.doc.getUser().userId:!1}function sL(n,t){if(n.readonly||!n.isBlockWritable(t)||m1(n,t)&&!Zc(n,t))return;const e=n.doc.getUser(),o={userId:e.userId,displayName:e.displayName,locked:Date.now()},i={...n.getBlockData(t),lock:o};n.updateBlockData(t,i)}function lL(n,t){if(!Zc(n,t))return;const e={lock:null};n.updateBlockData(t,e)}class I4{constructor(){u(this,"executeCommand",(t,e,o)=>{const r=o.data;if(!r||!r.blockId)return;const i=t.getBlockById(r.blockId);r.type==="lock"?sL(t,i):r.type==="unlock"&&lL(t,i)})}create(t,e,o,r,i){const s=i.lock;s&&(s.userId!==t.doc.getUser().userId?M(r,"locked-by-others"):M(r,"locked-by-self"))}writable(t,e){if(iL(t,e))return!1}commands(t,e){const o=m1(t,e),r=Zc(t,e),i={blockId:G(e),type:"lock"},s={id:"lock-block",name:"",data:i,order:10};if(o)if(r)s.id="unlock-block",s.name=S.t("locker.unlock"),i.type="unlock";else{const l=Gc(t,e);s.name=S.t("locker.lockedBy",{name:(l==null?void 0:l.displayName)||""}),s.states=["disabled"]}else s.name=S.t("locker.lock");return{group:"block-locker",commands:[s],executeCommand:this.executeCommand}}}const xF="",cL={locker:{lock:"\u9501\u5B9A",unlock:"\u89E3\u9664\u9501\u5B9A",lockedBy:"\u88AB {name} \u9501\u5B9A"}},aL={locker:{lock:"Lock",unlock:"Unlock",lockedBy:"Locked by {name}"}};S.mergeLang({"zh-CN":cL,"en-US":aL});const dL=y("standard-block-actions");class uL{constructor(){u(this,"executeCommand",(t,e,o)=>{const r=o.data;try{const i=t.getBlockById(r);if(o.id==="delete"){t.deleteBlock(i);return}o.id==="copy"&&iu(t,i),o.id==="cut"&&(iu(t,i),t.deleteBlock(i))}catch(i){dL.error(`failed to execute block command: ${JSON.stringify(i)}`)}})}commands(t,e){const o=m1(t,e),r=o&&Zc(t,e),i=G(e);return{group:"standard-block-actions",commands:[{id:"copy",name:"Copy",data:i,order:1},{id:"cut",name:"Cut",data:i,order:2,states:o&&!r?["disabled"]:[]},{id:"delete",name:"Delete",data:i,order:3,states:o&&!r?["disabled"]:[]}],executeCommand:this.executeCommand}}}const x4=y("block-menu");class hL{constructor(t){u(this,"menu");u(this,"currentBlock",null);u(this,"commandBlock",null);u(this,"handleShow",()=>{d(x4,this.currentBlock,"no target block before show block menu");const t=oL(this.editor,this.currentBlock,{onAfterStyleItemClick:this.close});this.menu.updateItems(t),this.commandBlock=this.currentBlock});u(this,"handleClose",()=>{this.editor.focus()});u(this,"handleItemClick",(t,e)=>{d(x4,this.commandBlock,"no command block before show block menu"),rL(this.editor,this.commandBlock,e),!e.element&&!e.children&&this.close()});u(this,"close",()=>{this.menu.close()});this.editor=t,this.menu=new Wo([],void 0,{id:"block-menu"}),this.menu.on("show",this.handleShow),this.menu.on("close",this.handleClose),this.menu.on("click",this.handleItemClick),t.blockHooks.push(new uL)}show(t){this.menu.manualShow(t,{placement:"bottom-start"})}isInMenu(t){return this.menu.isInCommandBar(t)}setBlock(t){this.currentBlock=t}get isVisible(){return this.menu.isVisible}destroy(){this.menu.destroy()}}const S4=`<svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
378
378
|
<path fill="currentColor" fill-rule="evenodd" clip-rule="evenodd" d="M6.33341 3.48568C6.33341 4.22204 5.73645 4.81901 5.00008 4.81901C4.26371 4.81901 3.66675 4.22204 3.66675 3.48568C3.66675 2.7493 4.26371 2.15234 5.00008 2.15234C5.73645 2.15234 6.33341 2.7493 6.33341 3.48568ZM5.00008 9.48568C5.73645 9.48568 6.33341 8.88871 6.33341 8.15234C6.33341 7.41598 5.73645 6.81901 5.00008 6.81901C4.26371 6.81901 3.66675 7.41598 3.66675 8.15234C3.66675 8.88871 4.26371 9.48568 5.00008 9.48568ZM5.00008 14.1523C5.73645 14.1523 6.33341 13.5554 6.33341 12.819C6.33341 12.0826 5.73645 11.4857 5.00008 11.4857C4.26371 11.4857 3.66675 12.0826 3.66675 12.819C3.66675 13.5554 4.26371 14.1523 5.00008 14.1523Z" />
|
|
379
379
|
<path fill="currentColor" fill-rule="evenodd" clip-rule="evenodd" d="M12.3334 3.48568C12.3334 4.22204 11.7364 4.81901 11.0001 4.81901C10.2637 4.81901 9.66675 4.22204 9.66675 3.48568C9.66675 2.7493 10.2637 2.15234 11.0001 2.15234C11.7364 2.15234 12.3334 2.7493 12.3334 3.48568ZM11.0001 9.48568C11.7364 9.48568 12.3334 8.88871 12.3334 8.15234C12.3334 7.41598 11.7364 6.81901 11.0001 6.81901C10.2637 6.81901 9.66675 7.41598 9.66675 8.15234C9.66675 8.88871 10.2637 9.48568 11.0001 9.48568ZM11.0001 14.1523C11.7364 14.1523 12.3334 13.5554 12.3334 12.819C12.3334 12.0826 11.7364 11.4857 11.0001 11.4857C10.2637 11.4857 9.66675 12.0826 9.66675 12.819C9.66675 13.5554 10.2637 14.1523 11.0001 14.1523Z" />
|
|
380
380
|
</svg>
|
|
@@ -502,7 +502,7 @@ xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
|
|
|
502
502
|
<add as="fillColor" value="#ffffff"/>
|
|
503
503
|
</add>
|
|
504
504
|
</mxStylesheet>
|
|
505
|
-
`,P4=0,fM=30*1e3,$4="editor-empty-drawio",j4="show-full-screen-iframe",zt=y("embed-block-drawio");function Kr(n){return n.options.componentsOptions.drawIO||{}}function mM(n){const e=Kr(n).lang||"zh-CN";return N4[e]||N4["zh-CN"]}function gM(n){var r;const e=((r=(Kr(n)||{}).cdn)==null?void 0:r.drawioIframe)||aM,o=mM(n);return Qa(e,{spin:1,proto:"json",configure:1,lang:o})}function pM(n){const t=()=>{d(zt,n,"el does not exist");const o=document.body.clientWidth||document.documentElement.clientWidth,r=document.body.clientHeight||document.documentElement.clientHeight;n.setAttribute("width",`${o-2*P4}`),n.setAttribute("height",`${r-2*P4}`)},e=()=>{window.removeEventListener("resize",t)};return t(),window.addEventListener("resize",t),{disconnect:e}}async function CM(n){const e=(Kr(n)||{}).callbacks||{},{onCreateDrawIoFrame:o,onCloseDrawIoFrame:r}=e;let i=null,s;if(o)i=await o(n),d(zt,i,"iframe create failed"),s=()=>{d(zt,i,"iframe does not exist"),d(zt,r,"missing parameters: onCloseDrawIoFrame"),r(n,i)};else{const l=b("div",["editor-drawio-iframe-container","loading"],document.body);l.setAttribute("data-placeholder",S.t("drawio.loading")),i=b("iframe",["drawio-iframe-element"],l),i.setAttribute("frameborder","0"),M(l,j4);const{disconnect:c}=pM(i);s=()=>{d(zt,i,"iframe does not exist"),c(),document.body.removeChild(l),F(l,j4)}}return{drawioIframe:i,exit:s}}async function bM(n,t,e,o){var r,i;try{o&&zt.debug("auto saving drawio data");const s=new Blob([e]),l=new File([s],"drawio.svg",{type:"image/svg+xml"});try{const c=t.parentElement;d(zt,c,"targetBlock");const a=await n.doc.uploadResource(l),{resourceId:h}=a,m={...n.getBlockData(c),embedData:{src:h}};n.updateBlockData(c,m)}catch(c){const a=`failed to upload drawio data: ${c.message}`;zt.error(a)}}catch(s){const l=`failed to save drawio data: ${s.message}`,c=Kr(n);if((r=c.callbacks)!=null&&r.onError){const a=new Error(l);a.code="SaveDrawIo",(i=c.callbacks)==null||i.onError(n,a)}}}function vM(n,t,e,o,r,i,s){const l=()=>{window.removeEventListener("message",c),i()},c=async a=>{var h,f;if(d(zt,o.contentWindow,"iframe.contentWindow does not exist"),a.data.length>0){const m=JSON.parse(a.data),C=e.xmlSvg||e.xml,v=document.querySelectorAll(".editor-drawio-iframe-container");switch(m.event){case"configure":o.contentWindow.postMessage(JSON.stringify({action:"configure",config:{defaultFonts:["Humor Sans","Helvetica","Times New Roman"]}}),"*");break;case"init":C!=null&&o.contentWindow.postMessage(JSON.stringify({action:"load",saveAndExit:1,noSaveBtn:1,noExitBtn:0,xml:C}),"*"),r(),v.forEach(E=>{F(E,"loading")});break;case"export":const w=el(m.data.substring(m.data.indexOf(",")+1));bM(n,t,w,!!((h=m.message)!=null&&h.autoSave)),(f=m.message)!=null&&f.autoSave||l();break;case"save":o.contentWindow.postMessage(JSON.stringify({action:"export",format:"xmlsvg",spin:"Saving graph"}),"*");break;case"exit":l();break}}};window.addEventListener("message",c)}async function H4(n,t,e,o){if(o)return;o=!0;const r=Kr(n)||{},{callbacks:i}=r;let s;i&&(i==null?void 0:i.onBeginInitDrawIo)&&i.onBeginInitDrawIo(n,t);const{drawioIframe:l,exit:c}=await CM(n);if(e.src){const m=await _4(n,n.doc.buildResourceUrl(e.src));m&&(e.xmlSvg=m)}vM(n,t,e,l,()=>{s=setInterval(()=>{!l||!l.contentWindow||l.contentWindow.postMessage(JSON.stringify({action:"export",format:"xmlsvg",spin:"Saving graph",autoSave:!0}),"*")},fM)},()=>{c(),s&&clearInterval(s)});const f=gM(n);l.setAttribute("src",f)}async function kM(n){var r,i;const t=Kr(n),e=((r=t.cdn)==null?void 0:r.drawio)||dM,o=((i=t.cdn)==null?void 0:i.pako)||uM;await xo(o,"editor-pako"),await xo(e,"editor-drawio"),await new Promise(s=>{setTimeout(s,100)})}function F4(n){F(n,$4)}function k1(n){n.setAttribute("data-empty-drawio-content",S.t("drawio.empty")),M(n,$4)}function y1(n,t){if(d(zt,t,"Required data is missing in setGraph"),"src"in t){n.setAttribute("data-src",t.src);return}if("xmlSvg"in t){n.setAttribute("data-xmlsvg",t.xmlSvg);return}if("graph"in t){const{xml:e,graph:o}=t;n.graph=o,n.setAttribute("data-mxfile",e)}}function yM(n,t,e){d(zt,n,"params error: src"),d(zt,e,"params error: editor");const o=t,r=e.doc.buildResourceUrl(n),i=document.createElement("img");o.innerHTML="",o.appendChild(i),i.src=r,y1(o,{src:n}),i.onload=()=>{sM(i)?k1(t):F4(t)}}function wM(n,t,e){d(zt,e,"parameter missing"),kM(e).then(()=>{const{mxUtils:o,mxGraph:r,mxCodec:i}=window;d(zt,o,"External resource loading exception: mxUtils"),d(zt,r,"External resource loading exception: MxGraph"),d(zt,i,"External resource loading exception: MxCodec");const s=o.parseXml(n);t.innerHTML="";const l=s.documentElement;d(zt,l,"Resource parsing exception"),d(zt,l.nodeName==="mxfile","Resource parsing exception");const c=l.getElementsByTagName("diagram");d(zt,c.length>0,"Resource parsing exception");let a;const h=c[0];if(h.text||h.textContent){const w=cM(h),E=atob(w),D=window.pako;d(zt,D,"External resource loading exception: pako");const x=D.inflateRaw(Uint8Array.from(E,O=>O.charCodeAt(0)),{to:"string"}),A=decodeURIComponent(x);a=o.parseXml(A)}else{const w=new XMLSerializer().serializeToString(h.firstChild);a=o.parseXml(w)}const f=new r(t);f.resetViewOnRootChange=!1,f.foldingEnabled=!1,f.setTooltips(!1),f.setEnabled(!1),f.setHtmlLabels(!0);const m=o.parseXml(hM);new i(m).decode(m.documentElement,f.getStylesheet());const v=new i(a);v.decode(v.document.documentElement,f.getModel()),f.maxFitScale=1,f.fit(),f.center(!0,!1),y1(t,{graph:f,xml:n})})}function BM(n,t){t.innerHTML=n,y1(t,{xmlSvg:n});const e=t.querySelectorAll("svg");for(let o=0;o<e.length;o++){const r=e[o];if(!lM(r))return}k1(t)}function EM(n,t){return o1(n,t,{handleExecuteCommand:(o,r,i)=>{if(i.id==="edit"){const s=o.getBlockData(r).embedData;return H4(o,rt(r),s,!1),!0}return!1}})}const Ss=y("embed-block-drawio"),IM=!1;nM();function z4(n,t,e,o){d(Ss,e,`parameter missing: ${e}`),d(Ss,n,`parameter missing: ${n}`),H4(n,t,o,IM)}function xM(n,t,e){F4(t);const o=e;o.src?yM(o.src,t,n):o.xml?wM(o.xml,t,n):o.xmlSvg?BM(o.xmlSvg,t):k1(t)}function SM(n,t,e,o={isInit:!1}){const{isInit:r}=o,s=b("div",["editor-drawio-content","editor-embed"],null);t.appendChild(s),xM(n,s,e);const l=t.parentElement;d(Ss,l,"embedContainer parentElement node does not exist"),r&&!n.readonly&&n.domEvents.addEventListener(t,"dblclick",()=>{const c=n.getBlockData(l);z4(n,t,s,c.embedData)})}function TM(n,t,e,o,r,i){const s=e.embedData,l=n.addCustom(`drawio-${e.id}`,()=>new oM),c=l.isFirstInit();c?Ss.log("create new embed block"):Ss.log("update exists embed block"),l.stamp(),SM(n,t,s,{isInit:c})}function DM(){return{name:"UML",insertEmbedCommandItems:[{id:"insert-drawio",name:S.t("drawio.title"),icon:Sw,group:"common",order:600}],handleInsertEmptyEmbed:async(n,t)=>{const e={src:"",xml:"",xmlSvg:""},o=n.insertEmbed(t.containerId,t.blockIndex,"drawio",e);return setTimeout(()=>{const r=rt(o),i=r.querySelector(":scope > .editor-drawio-content"),s=n.getBlockData(o);z4(n,r,i,s.embedData)},100),o}}}const Kc={embedType:"drawio",getOptions:DM,createEmbedContent:TM,getBlockProperties:EM},LF="",MF="",LM=500,MM=300,w1=y("code-editor");function RM(n){const t=n.closest(".embed-code-editor-container");return d(w1,t,"code-editor-container non-existent"),t}function OM(n,t,e){const o=n.target;d(w1,o,"Parameter error: textarea must be an element");const r=o.value;RM(o).remove(),F(t,"editing"),e(r),rt(t).style.removeProperty("margin-top")}function AM(n,t){d(w1,n,"Parameter Error: handleCodeUpdate[event]");const e=n.target.value;t(e)}const _M=Qt.default(AM,LM);function NM(n,t,e,o,r){n.domEvents.addEventListener(t,"blur",(i,s)=>{OM(s,e,r)}),n.domEvents.addEventListener(t,"keyup",(i,s)=>{const l=s.target;s.key==="Escape"&&l.blur()}),n.domEvents.addEventListener(t,"input",(i,s)=>{_M(s,o)})}function PM(n,t,e){const{height:o,codeValue:r,onChange:i,onEnd:s}=e,l=o||MM,c=rt(t),a=At(t),h=b("div",["embed-code-editor-container"],a),f=b("textarea",["embed-code-editor-textarea"],h);f.value=r||"",f.setAttribute("spellcheck","false"),h.style.height=`${l}px`,NM(n,f,t,i,s),c.style.marginTop=`${l}px`,M(t,"editing"),window.requestAnimationFrame(()=>{f.setSelectionRange(0,0),f.focus(),f.scrollTop=0})}const $M={mermaid:"https://mermaid-js.github.io/mermaid/",flowchart:"https://flowchart.js.org/",plantuml:"https://plantuml.com/"};class jM extends n1{constructor(e,o,r){super(e,r);u(this,"group","hovering-toolbar");u(this,"_commands",[{id:"edit",name:"Edit",icon:Ju},{id:"help",name:"Help",icon:Cw}]);this.editor=e,this.graphType=o,this.properties=r}executeCommand(e,o,r){var i,s;(s=(i=this.properties)==null?void 0:i.handleExecuteCommand)!=null&&s.call(i,e,o,r)||r.id==="edit"||r.id==="help"&&window.open($M[this.graphType])}}function HM(n,t,e){return{blockCommands:{"hovering-toolbar":new jM(n,t,e)}}}class B1{constructor(t,e,o){u(this,"editor");u(this,"logger");this.graphType=e,this.codeEmbedDataKey=o,this.editor=t,this.logger=y(`embed-block-${this.graphType}`)}i18nt(t,e){return S.t(`graph.${t}`,e||{})}getContent(t){d(this.logger,t,"embed-element does not exist");const e=t.parentElement;return d(this.logger,e,"content-element does not exist"),e}getEmbed(t){const e=t.childNodes[0];return d(this.logger,e,"embed-element does not exist"),e}async uploadResource(t){const e=new Blob([t]),o=new File([e],`${this.graphType}.svg`,{type:"image/svg+xml"});try{const r=await this.editor.doc.uploadResource(o);d(this.logger,r,"uploadResource failed");const{resourceId:i}=r;return this.editor.doc.buildResourceUrl(i)}catch(r){return this.logger.error(r),null}}createEmbedContent(t,e){const o=b("div",["graph-embed"],t);this.editor.domEvents.addEventListener(o,"dblclick",(c,a)=>{this.editGraph(t),a.preventDefault(),a.stopPropagation()});const{embedData:r}=e,i=r[`${this.codeEmbedDataKey}`],s=r.src,l=b("div",["embed-graph-img-content"],o);b("img",["graph-embed-image"],l),this.updateImage(o,i,s,null)}updateEmbedContent(t,e){const{embedData:o}=e,r=o[this.codeEmbedDataKey],i=o.src,s=t.querySelector(".graph-embed");this.updateImage(s,r,i,null)}async updateImage(t,e,o,r){const i=t.querySelector("img.graph-embed-image");let s=this.editor.doc.buildResourceUrl(o||"");if(!s&&!r&&e)try{s=await this.code2ObjectUrl(e)}catch(l){this.updateImage(t,e,o,l);return}this.updateClasses(t,e,r),s&&(i.src=s)}updateClasses(t,e,o){F(t,"empty-embed","invalid-code");const r=t.querySelector("img.graph-embed-image");if(o){r.src="",M(t,"invalid-code");const i=this.i18nt("invalid",{EmbedName:this.graphType,message:`${o.message}`||""});t.setAttribute("data-invalid-text",i);return}if(!e){r.src="";const i=this.i18nt("empty",{EmbedName:this.graphType});t.setAttribute("data-empty-tips",i),M(t,"empty-embed")}}editGraph(t){const e=z(t);d(this.logger,e,`${this.graphType} block does not exist`);const o=t.querySelector(".graph-embed"),r=l=>{this.updateImage(o,l,null,null)},i=async l=>{try{if(r(l),!this.hasChanged(e,l))return;const a={src:await this.code2ResourceId(l),[`${this.codeEmbedDataKey}`]:l};this.editor.updateEmbedData(e,a)}catch(c){this.updateClasses(o,l,c);const a={src:"",[`${this.codeEmbedDataKey}`]:l};this.editor.updateEmbedData(e,a)}},s=this.editor.getBlockData(e);PM(this.editor,e,{onChange:r,onEnd:i,codeValue:s.embedData[`${this.codeEmbedDataKey}`]})}getBlockProperties(t){return HM(this.editor,this.graphType,{handleExecuteCommand:(e,o,r)=>{if(r.id==="edit"){const i=rt(o);return this.editGraph(i),!0}return!1}})}hasChanged(t,e){return this.editor.getBlockData(t).embedData[`${this.codeEmbedDataKey}`]!==e}}const FM="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js",zM=["//cdnjs.cloudflare.com/ajax/libs/raphael/2.3.0/raphael.min.js","//cdnjs.cloudflare.com/ajax/libs/flowchart/1.15.0/flowchart.min.js"],UM="https://www.plantuml.com/plantuml/svg",VM=y("mermaid-helper"),qM="wiz-editor-mermaid";async function U4(n,t){var v;const o=((v=(n.getComponentOptions("mermaid")||{}).cdn)==null?void 0:v.mermaid)||FM;await xo(o,qM);const r=window.mermaid;d(VM,r,"Resource load failed: Mermaid javaScript resource injection failed");const i=N(),l=await new Promise((w,E)=>{try{r.mermaidAPI.render(i,t,D=>{setTimeout(()=>{w(D)})})}catch(D){D.message=D.str,E(D)}}),h=new DOMParser().parseFromString(l,"image/svg+xml").firstChild,f=h.style.maxWidth;return f&&h.setAttribute("width",f),new XMLSerializer().serializeToString(h)}async function WM(n,t){const e=await U4(n,t);return Ka(e,"image/svg+xml",`${N()}.svg`)}async function GM(n,t){const e=await U4(n,t),o=new Blob([e]),r=new File([o],`${N()}.svg`,{type:"image/svg+xml"});return(await n.doc.uploadResource(r)).resourceId}class Jr extends B1{constructor(t){super(t,"mermaid","mermaidText")}static get(t,e){return t.addCustom(`mermaid-${e.id}`,()=>new Jr(t))}code2ObjectUrl(t){return WM(this.editor,t)}code2ResourceId(t){return GM(this.editor,t)}destroy(){}}const ZM={graph:{invalid:"\u65E0\u6548\u7684 {EmbedName} \u5185\u5BB9\uFF1A{message}",empty:"\u7A7A\u7684 {EmbedName}",flowchart:{},mermaid:{},plantuml:{}}},YM={invalid:"Invalid {EmbedName} content: {message}",empty:"Empty {EmbedName}",flowchart:{},mermaid:{},plantuml:{}};S.mergeLang({"zh-CN":ZM,"en-US":YM});function QM(n,t,e){Jr.get(n,e).createEmbedContent(t,e)}function KM(n,t,e){const o=Jr.get(n,n.getBlockData(t)),r=rt(t);return o.updateEmbedContent(r,e),!0}function JM(n,t,e){const{data:o}=e,r=n.getBlockString(t).trim();if(!o||o.embedType!=="mermaid"||r!=="```mermaid"||!H(n,t))return null;const i={src:"",mermaidText:""};return{blockData:{id:N(),type:"embed",embedType:"mermaid",embedData:i},onConverted:(c,a)=>{Jr.get(c,c.getBlockData(a)).editGraph(rt(a))}}}function XM(n,t){return Jr.get(n,n.getBlockData(t)).getBlockProperties()}const E1={embedType:"mermaid",convertFrom:JM,handleUpdateBlock:KM,createEmbedContent:QM,getBlockProperties:XM},V4=y("flowchart-helper");async function tR(n){var o;const t=n.getComponentOptions("flowchart")||{},e=((o=t==null?void 0:t.cdn)==null?void 0:o.flowchart)||zM;for(let r=0;r<e.length;r+=1){const i=e[r];await xo(i,`flowchart-scripts-${r}`)}}async function q4(n,t){const e=b("div",["flowchart-chart-container"],document.body);e.id=`flowchart-${N()}`,await tR(n);const o=window.flowchart;d(V4,o,"flowchart resource does not exist"),o.parse(t).drawSVG(e.id);const i=e.firstElementChild;d(V4,i,"svg element non-existent");const l=new XMLSerializer().serializeToString(i);return e.remove(),l}async function eR(n,t){const e=await q4(n,t);return Ka(e,"image/svg+xml",`${Date.now()}.svg`)}async function nR(n,t){const e=await q4(n,t),o=new Blob([e]),r=new File([o],`${N()}.svg`,{type:"image/svg+xml"});return(await n.doc.uploadResource(r)).resourceId}class Xr extends B1{constructor(t){super(t,"flowchart","flowchartText")}static get(t,e){return t.addCustom(`flowchart-${e.id}`,()=>new Xr(t))}code2ObjectUrl(t){return eR(this.editor,t)}code2ResourceId(t){return nR(this.editor,t)}destroy(){}}function oR(n,t,e){Xr.get(n,e).createEmbedContent(t,e)}function rR(n,t,e){const o=Xr.get(n,e),r=rt(t);return o.updateEmbedContent(r,e),!0}function iR(n,t,e){const{data:o}=e,r=n.getBlockString(t).trim();if(!o||o.embedType!=="flowchart"||r!=="```flowchart"||!H(n,t))return null;const i={src:"",flowchartText:""};return{blockData:{id:N(),type:"embed",embedType:"flowchart",embedData:i},onConverted:(c,a)=>{Xr.get(c,c.getBlockData(a)).editGraph(rt(a))}}}function sR(n,t){return Xr.get(n,n.getBlockData(t)).getBlockProperties()}const I1={embedType:"flowchart",convertFrom:iR,handleUpdateBlock:rR,createEmbedContent:oR,getBlockProperties:sR},lR=y("plantuml-helper");function W4(n,t){var l;let o=((l=(n.getComponentOptions("plantuml")||{}).cdn)==null?void 0:l.plantuml)||UM;o.endsWith("/")||(o+="/");const r=L9.default.encode(t);d(lR,r,r),o+=r;const s=new URLSearchParams(document.location.search).get("doc");return Qa(o,{id:`${s}-${N()}`})}async function cR(n,t){const e=await v1(n,t);return(await n.doc.uploadResource(e)).resourceId}class ti extends B1{constructor(t){super(t,"plantuml","plantumlText")}static get(t,e){return t.addCustom(`plantuml-${e.id}`,()=>new ti(t))}code2ObjectUrl(t){return Promise.resolve(W4(this.editor,t))}code2ResourceId(t){const e=W4(this.editor,t);return cR(this.editor,e)}destroy(){}}function aR(n,t,e){ti.get(n,e).createEmbedContent(t,e)}function dR(n,t,e){const o=ti.get(n,e),r=rt(t);return o.updateEmbedContent(r,e),!0}function uR(n,t,e){const{data:o}=e,r=n.getBlockString(t).trim();if(!o||o.embedType!=="plantuml"||r!=="```plantuml"||!H(n,t))return null;const i={src:"",plantumlText:""};return{blockData:{id:N(),type:"embed",embedType:"plantuml",embedData:i},onConverted:(c,a)=>{ti.get(c,c.getBlockData(a)).editGraph(rt(a))}}}function hR(n,t){return ti.get(n,n.getBlockData(t)).getBlockProperties()}const x1={embedType:"plantuml",convertFrom:uR,handleUpdateBlock:dR,createEmbedContent:aR,getBlockProperties:hR},RF="",fR="hr",mR={dividingLine:{type:"\u5206\u5272\u7EBF"}},gR={dividingLine:{type:"dividing-line"}};S.mergeLang({"zh-CN":mR,"en-US":gR});function pR(n,t){const e=b("div",["editor-embed-container"],t);b("hr",["editor-embed-hr"],e)}function CR(n,t,e,o){return o==="html"?"<hr />":o==="markdown"?"---":"------------"}function bR(){return{name:"hr",insertEmbedCommandItems:[{id:"insert-hr",name:S.t("dividingLine.type"),icon:Tw,order:500,group:"common"}],handleInsertEmptyEmbed:async(n,t)=>{const{containerId:e,blockIndex:o}=t;return n.insertEmbed(e,o,fR,{})}}}function vR(n,t,e){const{data:o}=e;if(!o||o.embedType!=="dividing-line"||!H(n,t))return null;const r={};return{blockData:{id:N(),type:"embed",embedType:"hr",embedData:r}}}const S1={embedType:"hr",createEmbedContent:pR,convertTo:CR,getOptions:bR,convertFrom:vR},OF="";class kR{constructor(t,e){u(this,"toolbar");u(this,"anchor",null);u(this,"item");u(this,"docs",null);u(this,"checkedId");u(this,"handlePasteSpecial",(t,e)=>{!e.data||(this.checkedId===e.id?this.checkedId=void 0:this.checkedId=e.id,this.onPasteSpecial(e.data),setTimeout(()=>{this.docs&&this.show(this.docs),this.editor.focus()}))});u(this,"handleClose",()=>{this.editor.focus()});u(this,"handleSelectionChange",()=>{this.hide()});this.editor=t,this.onPasteSpecial=e,this.item={id:"paste-special",name:"Paste special",icon:uw,dropdown:!0,manualShowChildren:!0,childrenPlacement:"bottom-start",childrenOffset:[-4,4],children:[]},this.toolbar=new rc([this.item],void 0,{id:"paste-special-button",tooltipId:this.editor.clientId,refuseOverflow:!0}),this.toolbar.addListener("click",this.handlePasteSpecial),this.toolbar.addListener("close",this.handleClose),this.editor.addListener("selectionChanged",this.handleSelectionChange)}show(t){this.docs=t;const e=this.editor,o=e.selection.range;if(!o.isCollapsed())return;const r=e.getBlockById(o.start.blockId);if(!H(e,r))return;const i=Oo(e,r,o)[0];if(!i)return;this.anchor&&this.anchor.remove(),this.anchor=_o(e,r,"paste-special-button-anchor",i);const s=this.getCommandItems(t);this.item.children=s,this.toolbar.manualShow(this.anchor)}hide(){this.toolbar.close()}clearCheckedState(){this.checkedId=void 0}destroy(){this.toolbar.destroy(),this.editor.removeListener("selectionChanged",this.handleSelectionChange)}getCommandItems(t){const e=i=>({id:i,states:this.checkedId===i?["checked"]:void 0,name:"Keep origin formats",data:t[i]}),o=[];let r=!0;return t["text/x-ones-editor-doc"]?o.push(e("text/x-ones-editor-doc")):t["text/office-html"]?o.push(e("text/office-html")):t["text/html"]?o.push(e("text/html")):t["text/plain"]&&(o.push(e("text/plain")),r=!1),t["text/plain"]&&(r&&o.push({id:"text/plain",states:this.checkedId==="text/plain"?["checked"]:void 0,name:"Paste as plain text",data:t["text/plain"]}),o.push({id:"text/markdown",states:this.checkedId==="text/markdown"?["checked"]:void 0,name:"Paste as markdown",data:t["text/markdown"]})),o}}const yR=y("paste-special");class T1{constructor(t){u(this,"button");u(this,"lastUndoAction",null);u(this,"event",null);u(this,"handlePasteSpecial",t=>{this.editor.undoManager.runInGroup(()=>{this.editor.undoManager.undoTo(this.lastUndoAction),this.editor.pasteDoc(t)})});this.editor=t,this.button=new kR(t,this.handlePasteSpecial)}destroy(){this.event=null,this.button.destroy()}handleChanged(t,e){this.event=null,this.button.hide()}async handleBeforePaste(t,e){return yR.debug("before paste"),this.lastUndoAction=t.undoManager.lastAction(),!1}async handleAfterPaste(t,e,o){if(Object.keys(o).length<=1)return!1;const r=t.selection.range;if(r.isCollapsed()){const i=t.getBlockById(r.start.blockId);if(!H(t,i))return!1;this.button.clearCheckedState(),this.button.show(o),this.event=e}return!1}}const AF="",wR=y("html-to-doc");function BR(n){const t="ones-editor-doc::",e="::ones-editor-doc";let o=n.indexOf(t);if(o!==-1){o+=t.length;const r=n.indexOf(e,o);if(r!==-1){const i=n.substr(o,r-o);try{const s=el(i);return JSON.parse(s)}catch(s){wR.error(`invalid doc data: ${s}, ${i}`)}}}return null}function nr(n){const t=n.type;if(t==="link")return!!n.tokens.some(nr);switch(t){case"code":case"table":case"hr":case"blockquote":case"list":case"list_item":case"image":case"paragraph":return!0;default:return!1}}function ER(n){return!nr(n)}function IR(n){if(n.length===0)return[];if(n.length===1)return[n];const t=[];let e=[n[0]],o=nr(n[0]);for(let r=1;r<n.length;r++){const i=n[r];o===nr(i)?e.push(i):(t.push(e),e=[i],o=nr(i))}return t.push(e),t}function xR(n,t,e){const o=n.href;let r=e.tokensToText(n.tokens,t,e);return r=yl(r,"link",o),r}function SR(n,t){const e=n.text;return[_e(e,{...t,"style-code":!0})]}let Ts;function G4(n){Ts||(Ts=document.createElement("textarea")),Ts.innerHTML=n;const t=Ts.childNodes.length===0?"":Ts.childNodes[0].nodeValue;return t!=null?t:""}function TR(n,t,e){const r=n.tokens;return r?e.tokensToText(r,t,e):Td(G4(n.text),t)}const DR=y("token-to-text");function D1(n,t,e){return n.map(r=>r.type==="text"?TR(r,t,e):r.type==="strong"?e.tokensToText(r.tokens,{...t,"style-bold":!0},e):r.type==="em"?e.tokensToText(r.tokens,{...t,"style-italic":!0},e):r.type==="link"?xR(r,t,e):r.type==="codespan"?SR(r,t):r.type==="br"?[{insert:" ",attributes:{box:!0,type:"br"}}]:r.type==="escape"?Td(G4(r.text),t):(DR.warn(`unknown token in text: ${JSON.stringify(r)}`),[])).flat()}function LR(n,t){const e=D1(n.tokens,{},t);return[{id:N(),type:"text",text:e,heading:n.depth}]}function MR(n,t){const{text:e,children:o}=t.tokensToTextWithChildren(n.tokens,t),r=[];return e.length>0&&r.push({id:N(),type:"text",text:e}),r.push(...o),r}function RR(n,t){const e=typeof n.start=="number"?n.start:1,o=n.ordered,r=N(),i=[];return n.items.forEach((l,c)=>{const a={...t,listLevel:t.listLevel+1},{text:h,children:f}=t.tokensToTextWithChildren(l.tokens,a),m={id:N(),type:"list",groupId:r,ordered:o,start:e+c,text:h,level:t.listLevel};i.push(m),i.push(...f)}),i}function OR(n,t){const e=t.tokensToBlocks(n.tokens,t);return e.forEach(o=>{o.quoted=!0}),e}const Z4=100,AR=20,_R=600;function NR(n,t){const e=t.text;if(e){const o=wt(e);return Math.min(rl(o,n)+AR,_R)}return Z4}function Y4(n,t){let e=Z4;return t.forEach(o=>{e=Math.max(e,NR(n,o))}),e}function PR(n,t){var l,c;const e=n.header.length,o=n.rows.length+1,r=[],i=Array(e).fill(100);for(let a=0;a<o;a++){let h;a===0?h=n.header:h=n.rows[a-1];for(let f=0;f<e;f++){const m=h[f],C=(l=m==null?void 0:m.tokens)!=null?l:[],v=N();r.push(v);let w;if(C.length===0)w=[Il()];else if(nr(C[0]))w=t.tokensToBlocks(m.tokens,t),w.length===0&&w.push(Il());else{const{text:E,children:D}=t.tokensToTextWithChildren(m.tokens,t);w=[{id:N(),type:"text",text:E},...D]}t.doc.blocks[v]=w,i[f]=Math.max(i[f],Y4((c=t.font)!=null?c:"",w))}}return[{id:N(),type:"table",cols:e,rows:o,colsWidth:i,children:r}]}function $R(n){return[{id:N(),type:"embed",embedType:"hr",embedData:{}}]}function jR(n,t){var c;const e=n.text;if(!e)return[];try{const a=n.text,h=el(a),f=JSON.parse(h);if(f){const{root:m,...C}=f.blocks;return t.doc.blocks={...t.doc.blocks,...C},m}}catch{}const o=(c=n.lang)!=null?c:"Plain Text";if(o==="mermaid")return[{id:N(),type:"embed",embedType:"mermaid",embedData:{mermaidText:e}}];if(o==="plantuml")return[{id:N(),type:"embed",embedType:"plantuml",embedData:{plantumlText:e}}];if(o==="flow"||o==="flowchart")return[{id:N(),type:"embed",embedType:"flowchart",embedData:{flowchartText:e}}];const i=e.split(`
|
|
505
|
+
`,P4=0,fM=30*1e3,$4="editor-empty-drawio",j4="show-full-screen-iframe",zt=y("embed-block-drawio");function Kr(n){return n.options.componentsOptions.drawIO||{}}function mM(n){const e=Kr(n).lang||"zh-CN";return N4[e]||N4["zh-CN"]}function gM(n){var r;const e=((r=(Kr(n)||{}).cdn)==null?void 0:r.drawioIframe)||aM,o=mM(n);return Qa(e,{spin:1,proto:"json",configure:1,lang:o})}function pM(n){const t=()=>{d(zt,n,"el does not exist");const o=document.body.clientWidth||document.documentElement.clientWidth,r=document.body.clientHeight||document.documentElement.clientHeight;n.setAttribute("width",`${o-2*P4}`),n.setAttribute("height",`${r-2*P4}`)},e=()=>{window.removeEventListener("resize",t)};return t(),window.addEventListener("resize",t),{disconnect:e}}async function CM(n){const e=(Kr(n)||{}).callbacks||{},{onCreateDrawIoFrame:o,onCloseDrawIoFrame:r}=e;let i=null,s;if(o)i=await o(n),d(zt,i,"iframe create failed"),s=()=>{d(zt,i,"iframe does not exist"),d(zt,r,"missing parameters: onCloseDrawIoFrame"),r(n,i)};else{const l=b("div",["editor-drawio-iframe-container","loading"],document.body);l.setAttribute("data-placeholder",S.t("drawio.loading")),i=b("iframe",["drawio-iframe-element"],l),i.setAttribute("frameborder","0"),M(l,j4);const{disconnect:c}=pM(i);s=()=>{d(zt,i,"iframe does not exist"),c(),document.body.removeChild(l),F(l,j4)}}return{drawioIframe:i,exit:s}}async function bM(n,t,e,o){var r,i;try{o&&zt.debug("auto saving drawio data");const s=new Blob([e]),l=new File([s],"drawio.svg",{type:"image/svg+xml"});try{const c=t.parentElement;d(zt,c,"targetBlock");const a=await n.doc.uploadResource(l),{resourceId:h}=a,m={...n.getBlockData(c),embedData:{src:h}};n.updateBlockData(c,m)}catch(c){const a=`failed to upload drawio data: ${c.message}`;zt.error(a)}}catch(s){const l=`failed to save drawio data: ${s.message}`,c=Kr(n);if((r=c.callbacks)!=null&&r.onError){const a=new Error(l);a.code="SaveDrawIo",(i=c.callbacks)==null||i.onError(n,a)}}}function vM(n,t,e,o,r,i,s){const l=()=>{window.removeEventListener("message",c),i()},c=async a=>{var h,f;if(d(zt,o.contentWindow,"iframe.contentWindow does not exist"),a.data.length>0){const m=JSON.parse(a.data),C=e.xmlSvg||e.xml,v=document.querySelectorAll(".editor-drawio-iframe-container");switch(m.event){case"configure":o.contentWindow.postMessage(JSON.stringify({action:"configure",config:{defaultFonts:["Humor Sans","Helvetica","Times New Roman"]}}),"*");break;case"init":C!=null&&o.contentWindow.postMessage(JSON.stringify({action:"load",saveAndExit:1,noSaveBtn:1,noExitBtn:0,xml:C}),"*"),r(),v.forEach(E=>{F(E,"loading")});break;case"export":const w=el(m.data.substring(m.data.indexOf(",")+1));bM(n,t,w,!!((h=m.message)!=null&&h.autoSave)),(f=m.message)!=null&&f.autoSave||l();break;case"save":o.contentWindow.postMessage(JSON.stringify({action:"export",format:"xmlsvg",spin:"Saving graph"}),"*");break;case"exit":l();break}}};window.addEventListener("message",c)}async function H4(n,t,e,o){if(o)return;o=!0;const r=Kr(n)||{},{callbacks:i}=r;let s;i&&(i==null?void 0:i.onBeginInitDrawIo)&&i.onBeginInitDrawIo(n,t);const{drawioIframe:l,exit:c}=await CM(n);if(e.src){const m=await _4(n,n.doc.buildResourceUrl(e.src));m&&(e.xmlSvg=m)}vM(n,t,e,l,()=>{s=setInterval(()=>{!l||!l.contentWindow||l.contentWindow.postMessage(JSON.stringify({action:"export",format:"xmlsvg",spin:"Saving graph",autoSave:!0}),"*")},fM)},()=>{c(),s&&clearInterval(s)});const f=gM(n);l.setAttribute("src",f)}async function kM(n){var r,i;const t=Kr(n),e=((r=t.cdn)==null?void 0:r.drawio)||dM,o=((i=t.cdn)==null?void 0:i.pako)||uM;await xo(o,"editor-pako"),await xo(e,"editor-drawio"),await new Promise(s=>{setTimeout(s,100)})}function F4(n){F(n,$4)}function k1(n){n.setAttribute("data-empty-drawio-content",S.t("drawio.empty")),M(n,$4)}function y1(n,t){if(d(zt,t,"Required data is missing in setGraph"),"src"in t){n.setAttribute("data-src",t.src);return}if("xmlSvg"in t){n.setAttribute("data-xmlsvg",t.xmlSvg);return}if("graph"in t){const{xml:e,graph:o}=t;n.graph=o,n.setAttribute("data-mxfile",e)}}function yM(n,t,e){d(zt,n,"params error: src"),d(zt,e,"params error: editor");const o=t,r=e.doc.buildResourceUrl(n),i=document.createElement("img");o.innerHTML="",o.appendChild(i),i.src=r,y1(o,{src:n}),i.onload=()=>{sM(i)?k1(t):F4(t)}}function wM(n,t,e){d(zt,e,"parameter missing"),kM(e).then(()=>{const{mxUtils:o,mxGraph:r,mxCodec:i}=window;d(zt,o,"External resource loading exception: mxUtils"),d(zt,r,"External resource loading exception: MxGraph"),d(zt,i,"External resource loading exception: MxCodec");const s=o.parseXml(n);t.innerHTML="";const l=s.documentElement;d(zt,l,"Resource parsing exception"),d(zt,l.nodeName==="mxfile","Resource parsing exception");const c=l.getElementsByTagName("diagram");d(zt,c.length>0,"Resource parsing exception");let a;const h=c[0];if(h.text||h.textContent){const w=cM(h),E=atob(w),L=window.pako;d(zt,L,"External resource loading exception: pako");const x=L.inflateRaw(Uint8Array.from(E,A=>A.charCodeAt(0)),{to:"string"}),O=decodeURIComponent(x);a=o.parseXml(O)}else{const w=new XMLSerializer().serializeToString(h.firstChild);a=o.parseXml(w)}const f=new r(t);f.resetViewOnRootChange=!1,f.foldingEnabled=!1,f.setTooltips(!1),f.setEnabled(!1),f.setHtmlLabels(!0);const m=o.parseXml(hM);new i(m).decode(m.documentElement,f.getStylesheet());const v=new i(a);v.decode(v.document.documentElement,f.getModel()),f.maxFitScale=1,f.fit(),f.center(!0,!1),y1(t,{graph:f,xml:n})})}function BM(n,t){t.innerHTML=n,y1(t,{xmlSvg:n});const e=t.querySelectorAll("svg");for(let o=0;o<e.length;o++){const r=e[o];if(!lM(r))return}k1(t)}function EM(n,t){return o1(n,t,{handleExecuteCommand:(o,r,i)=>{if(i.id==="edit"){const s=o.getBlockData(r).embedData;return H4(o,rt(r),s,!1),!0}return!1}})}const Ss=y("embed-block-drawio"),IM=!1;nM();function z4(n,t,e,o){d(Ss,e,`parameter missing: ${e}`),d(Ss,n,`parameter missing: ${n}`),H4(n,t,o,IM)}function xM(n,t,e){F4(t);const o=e;o.src?yM(o.src,t,n):o.xml?wM(o.xml,t,n):o.xmlSvg?BM(o.xmlSvg,t):k1(t)}function SM(n,t,e,o={isInit:!1}){const{isInit:r}=o,s=b("div",["editor-drawio-content","editor-embed"],null);t.appendChild(s),xM(n,s,e);const l=t.parentElement;d(Ss,l,"embedContainer parentElement node does not exist"),r&&!n.readonly&&n.domEvents.addEventListener(t,"dblclick",()=>{const c=n.getBlockData(l);z4(n,t,s,c.embedData)})}function TM(n,t,e,o,r,i){const s=e.embedData,l=n.addCustom(`drawio-${e.id}`,()=>new oM),c=l.isFirstInit();c?Ss.log("create new embed block"):Ss.log("update exists embed block"),l.stamp(),SM(n,t,s,{isInit:c})}function DM(){return{name:"UML",insertEmbedCommandItems:[{id:"insert-drawio",name:S.t("drawio.title"),icon:Sw,group:"common",order:600}],handleInsertEmptyEmbed:async(n,t)=>{const e={src:"",xml:"",xmlSvg:""},o=n.insertEmbed(t.containerId,t.blockIndex,"drawio",e);return setTimeout(()=>{const r=rt(o),i=r.querySelector(":scope > .editor-drawio-content"),s=n.getBlockData(o);z4(n,r,i,s.embedData)},100),o}}}const Kc={embedType:"drawio",getOptions:DM,createEmbedContent:TM,getBlockProperties:EM},LF="",MF="",LM=500,MM=300,w1=y("code-editor");function RM(n){const t=n.closest(".embed-code-editor-container");return d(w1,t,"code-editor-container non-existent"),t}function OM(n,t,e){const o=n.target;d(w1,o,"Parameter error: textarea must be an element");const r=o.value;RM(o).remove(),F(t,"editing"),e(r),rt(t).style.removeProperty("margin-top")}function AM(n,t){d(w1,n,"Parameter Error: handleCodeUpdate[event]");const e=n.target.value;t(e)}const _M=Qt.default(AM,LM);function NM(n,t,e,o,r){n.domEvents.addEventListener(t,"blur",(i,s)=>{OM(s,e,r)}),n.domEvents.addEventListener(t,"keyup",(i,s)=>{const l=s.target;s.key==="Escape"&&l.blur()}),n.domEvents.addEventListener(t,"input",(i,s)=>{_M(s,o)})}function PM(n,t,e){const{height:o,codeValue:r,onChange:i,onEnd:s}=e,l=o||MM,c=rt(t),a=At(t),h=b("div",["embed-code-editor-container"],a),f=b("textarea",["embed-code-editor-textarea"],h);f.value=r||"",f.setAttribute("spellcheck","false"),h.style.height=`${l}px`,NM(n,f,t,i,s),c.style.marginTop=`${l}px`,M(t,"editing"),window.requestAnimationFrame(()=>{f.setSelectionRange(0,0),f.focus(),f.scrollTop=0})}const $M={mermaid:"https://mermaid-js.github.io/mermaid/",flowchart:"https://flowchart.js.org/",plantuml:"https://plantuml.com/"};class jM extends n1{constructor(e,o,r){super(e,r);u(this,"group","hovering-toolbar");u(this,"_commands",[{id:"edit",name:"Edit",icon:Ju},{id:"help",name:"Help",icon:Cw}]);this.editor=e,this.graphType=o,this.properties=r}executeCommand(e,o,r){var i,s;(s=(i=this.properties)==null?void 0:i.handleExecuteCommand)!=null&&s.call(i,e,o,r)||r.id==="edit"||r.id==="help"&&window.open($M[this.graphType])}}function HM(n,t,e){return{blockCommands:{"hovering-toolbar":new jM(n,t,e)}}}class B1{constructor(t,e,o){u(this,"editor");u(this,"logger");this.graphType=e,this.codeEmbedDataKey=o,this.editor=t,this.logger=y(`embed-block-${this.graphType}`)}i18nt(t,e){return S.t(`graph.${t}`,e||{})}getContent(t){d(this.logger,t,"embed-element does not exist");const e=t.parentElement;return d(this.logger,e,"content-element does not exist"),e}getEmbed(t){const e=t.childNodes[0];return d(this.logger,e,"embed-element does not exist"),e}async uploadResource(t){const e=new Blob([t]),o=new File([e],`${this.graphType}.svg`,{type:"image/svg+xml"});try{const r=await this.editor.doc.uploadResource(o);d(this.logger,r,"uploadResource failed");const{resourceId:i}=r;return this.editor.doc.buildResourceUrl(i)}catch(r){return this.logger.error(r),null}}createEmbedContent(t,e){const o=b("div",["graph-embed"],t);this.editor.domEvents.addEventListener(o,"dblclick",(c,a)=>{this.editGraph(t),a.preventDefault(),a.stopPropagation()});const{embedData:r}=e,i=r[`${this.codeEmbedDataKey}`],s=r.src,l=b("div",["embed-graph-img-content"],o);b("img",["graph-embed-image"],l),this.updateImage(o,i,s,null)}updateEmbedContent(t,e){const{embedData:o}=e,r=o[this.codeEmbedDataKey],i=o.src,s=t.querySelector(".graph-embed");this.updateImage(s,r,i,null)}async updateImage(t,e,o,r){const i=t.querySelector("img.graph-embed-image");let s=this.editor.doc.buildResourceUrl(o||"");if(!s&&!r&&e)try{s=await this.code2ObjectUrl(e)}catch(l){this.updateImage(t,e,o,l);return}this.updateClasses(t,e,r),s&&(i.src=s)}updateClasses(t,e,o){F(t,"empty-embed","invalid-code");const r=t.querySelector("img.graph-embed-image");if(o){r.src="",M(t,"invalid-code");const i=this.i18nt("invalid",{EmbedName:this.graphType,message:`${o.message}`||""});t.setAttribute("data-invalid-text",i);return}if(!e){r.src="";const i=this.i18nt("empty",{EmbedName:this.graphType});t.setAttribute("data-empty-tips",i),M(t,"empty-embed")}}editGraph(t){const e=z(t);d(this.logger,e,`${this.graphType} block does not exist`);const o=t.querySelector(".graph-embed"),r=l=>{this.updateImage(o,l,null,null)},i=async l=>{try{if(r(l),!this.hasChanged(e,l))return;const a={src:await this.code2ResourceId(l),[`${this.codeEmbedDataKey}`]:l};this.editor.updateEmbedData(e,a)}catch(c){this.updateClasses(o,l,c);const a={src:"",[`${this.codeEmbedDataKey}`]:l};this.editor.updateEmbedData(e,a)}},s=this.editor.getBlockData(e);PM(this.editor,e,{onChange:r,onEnd:i,codeValue:s.embedData[`${this.codeEmbedDataKey}`]})}getBlockProperties(t){return HM(this.editor,this.graphType,{handleExecuteCommand:(e,o,r)=>{if(r.id==="edit"){const i=rt(o);return this.editGraph(i),!0}return!1}})}hasChanged(t,e){return this.editor.getBlockData(t).embedData[`${this.codeEmbedDataKey}`]!==e}}const FM="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js",zM=["//cdnjs.cloudflare.com/ajax/libs/raphael/2.3.0/raphael.min.js","//cdnjs.cloudflare.com/ajax/libs/flowchart/1.15.0/flowchart.min.js"],UM="https://www.plantuml.com/plantuml/svg",VM=y("mermaid-helper"),qM="wiz-editor-mermaid";async function U4(n,t){var v;const o=((v=(n.getComponentOptions("mermaid")||{}).cdn)==null?void 0:v.mermaid)||FM;await xo(o,qM);const r=window.mermaid;d(VM,r,"Resource load failed: Mermaid javaScript resource injection failed");const i=N(),l=await new Promise((w,E)=>{try{r.mermaidAPI.render(i,t,L=>{setTimeout(()=>{w(L)})})}catch(L){L.message=L.str,E(L)}}),h=new DOMParser().parseFromString(l,"image/svg+xml").firstChild,f=h.style.maxWidth;return f&&h.setAttribute("width",f),new XMLSerializer().serializeToString(h)}async function WM(n,t){const e=await U4(n,t);return Ka(e,"image/svg+xml",`${N()}.svg`)}async function GM(n,t){const e=await U4(n,t),o=new Blob([e]),r=new File([o],`${N()}.svg`,{type:"image/svg+xml"});return(await n.doc.uploadResource(r)).resourceId}class Jr extends B1{constructor(t){super(t,"mermaid","mermaidText")}static get(t,e){return t.addCustom(`mermaid-${e.id}`,()=>new Jr(t))}code2ObjectUrl(t){return WM(this.editor,t)}code2ResourceId(t){return GM(this.editor,t)}destroy(){}}const ZM={graph:{invalid:"\u65E0\u6548\u7684 {EmbedName} \u5185\u5BB9\uFF1A{message}",empty:"\u7A7A\u7684 {EmbedName}",flowchart:{},mermaid:{},plantuml:{}}},YM={invalid:"Invalid {EmbedName} content: {message}",empty:"Empty {EmbedName}",flowchart:{},mermaid:{},plantuml:{}};S.mergeLang({"zh-CN":ZM,"en-US":YM});function QM(n,t,e){Jr.get(n,e).createEmbedContent(t,e)}function KM(n,t,e){const o=Jr.get(n,n.getBlockData(t)),r=rt(t);return o.updateEmbedContent(r,e),!0}function JM(n,t,e){const{data:o}=e,r=n.getBlockString(t).trim();if(!o||o.embedType!=="mermaid"||r!=="```mermaid"||!H(n,t))return null;const i={src:"",mermaidText:""};return{blockData:{id:N(),type:"embed",embedType:"mermaid",embedData:i},onConverted:(c,a)=>{Jr.get(c,c.getBlockData(a)).editGraph(rt(a))}}}function XM(n,t){return Jr.get(n,n.getBlockData(t)).getBlockProperties()}const E1={embedType:"mermaid",convertFrom:JM,handleUpdateBlock:KM,createEmbedContent:QM,getBlockProperties:XM},V4=y("flowchart-helper");async function tR(n){var o;const t=n.getComponentOptions("flowchart")||{},e=((o=t==null?void 0:t.cdn)==null?void 0:o.flowchart)||zM;for(let r=0;r<e.length;r+=1){const i=e[r];await xo(i,`flowchart-scripts-${r}`)}}async function q4(n,t){const e=b("div",["flowchart-chart-container"],document.body);e.id=`flowchart-${N()}`,await tR(n);const o=window.flowchart;d(V4,o,"flowchart resource does not exist"),o.parse(t).drawSVG(e.id);const i=e.firstElementChild;d(V4,i,"svg element non-existent");const l=new XMLSerializer().serializeToString(i);return e.remove(),l}async function eR(n,t){const e=await q4(n,t);return Ka(e,"image/svg+xml",`${Date.now()}.svg`)}async function nR(n,t){const e=await q4(n,t),o=new Blob([e]),r=new File([o],`${N()}.svg`,{type:"image/svg+xml"});return(await n.doc.uploadResource(r)).resourceId}class Xr extends B1{constructor(t){super(t,"flowchart","flowchartText")}static get(t,e){return t.addCustom(`flowchart-${e.id}`,()=>new Xr(t))}code2ObjectUrl(t){return eR(this.editor,t)}code2ResourceId(t){return nR(this.editor,t)}destroy(){}}function oR(n,t,e){Xr.get(n,e).createEmbedContent(t,e)}function rR(n,t,e){const o=Xr.get(n,e),r=rt(t);return o.updateEmbedContent(r,e),!0}function iR(n,t,e){const{data:o}=e,r=n.getBlockString(t).trim();if(!o||o.embedType!=="flowchart"||r!=="```flowchart"||!H(n,t))return null;const i={src:"",flowchartText:""};return{blockData:{id:N(),type:"embed",embedType:"flowchart",embedData:i},onConverted:(c,a)=>{Xr.get(c,c.getBlockData(a)).editGraph(rt(a))}}}function sR(n,t){return Xr.get(n,n.getBlockData(t)).getBlockProperties()}const I1={embedType:"flowchart",convertFrom:iR,handleUpdateBlock:rR,createEmbedContent:oR,getBlockProperties:sR},lR=y("plantuml-helper");function W4(n,t){var l;let o=((l=(n.getComponentOptions("plantuml")||{}).cdn)==null?void 0:l.plantuml)||UM;o.endsWith("/")||(o+="/");const r=L9.default.encode(t);d(lR,r,r),o+=r;const s=new URLSearchParams(document.location.search).get("doc");return Qa(o,{id:`${s}-${N()}`})}async function cR(n,t){const e=await v1(n,t);return(await n.doc.uploadResource(e)).resourceId}class ti extends B1{constructor(t){super(t,"plantuml","plantumlText")}static get(t,e){return t.addCustom(`plantuml-${e.id}`,()=>new ti(t))}code2ObjectUrl(t){return Promise.resolve(W4(this.editor,t))}code2ResourceId(t){const e=W4(this.editor,t);return cR(this.editor,e)}destroy(){}}function aR(n,t,e){ti.get(n,e).createEmbedContent(t,e)}function dR(n,t,e){const o=ti.get(n,e),r=rt(t);return o.updateEmbedContent(r,e),!0}function uR(n,t,e){const{data:o}=e,r=n.getBlockString(t).trim();if(!o||o.embedType!=="plantuml"||r!=="```plantuml"||!H(n,t))return null;const i={src:"",plantumlText:""};return{blockData:{id:N(),type:"embed",embedType:"plantuml",embedData:i},onConverted:(c,a)=>{ti.get(c,c.getBlockData(a)).editGraph(rt(a))}}}function hR(n,t){return ti.get(n,n.getBlockData(t)).getBlockProperties()}const x1={embedType:"plantuml",convertFrom:uR,handleUpdateBlock:dR,createEmbedContent:aR,getBlockProperties:hR},RF="",fR="hr",mR={dividingLine:{type:"\u5206\u5272\u7EBF"}},gR={dividingLine:{type:"dividing-line"}};S.mergeLang({"zh-CN":mR,"en-US":gR});function pR(n,t){const e=b("div",["editor-embed-container"],t);b("hr",["editor-embed-hr"],e)}function CR(n,t,e,o){return o==="html"?"<hr />":o==="markdown"?"---":"------------"}function bR(){return{name:"hr",insertEmbedCommandItems:[{id:"insert-hr",name:S.t("dividingLine.type"),icon:Tw,order:500,group:"common"}],handleInsertEmptyEmbed:async(n,t)=>{const{containerId:e,blockIndex:o}=t;return n.insertEmbed(e,o,fR,{})}}}function vR(n,t,e){const{data:o}=e;if(!o||o.embedType!=="dividing-line"||!H(n,t))return null;const r={};return{blockData:{id:N(),type:"embed",embedType:"hr",embedData:r}}}const S1={embedType:"hr",createEmbedContent:pR,convertTo:CR,getOptions:bR,convertFrom:vR},OF="";class kR{constructor(t,e){u(this,"toolbar");u(this,"anchor",null);u(this,"item");u(this,"docs",null);u(this,"checkedId");u(this,"handlePasteSpecial",(t,e)=>{!e.data||(this.checkedId===e.id?this.checkedId=void 0:this.checkedId=e.id,this.onPasteSpecial(e.data),setTimeout(()=>{this.docs&&this.show(this.docs),this.editor.focus()}))});u(this,"handleClose",()=>{this.editor.focus()});u(this,"handleSelectionChange",()=>{this.hide()});this.editor=t,this.onPasteSpecial=e,this.item={id:"paste-special",name:"Paste special",icon:uw,dropdown:!0,manualShowChildren:!0,childrenPlacement:"bottom-start",childrenOffset:[-4,4],children:[]},this.toolbar=new rc([this.item],void 0,{id:"paste-special-button",tooltipId:this.editor.clientId,refuseOverflow:!0}),this.toolbar.addListener("click",this.handlePasteSpecial),this.toolbar.addListener("close",this.handleClose),this.editor.addListener("selectionChanged",this.handleSelectionChange)}show(t){this.docs=t;const e=this.editor,o=e.selection.range;if(!o.isCollapsed())return;const r=e.getBlockById(o.start.blockId);if(!H(e,r))return;const i=Oo(e,r,o)[0];if(!i)return;this.anchor&&this.anchor.remove(),this.anchor=_o(e,r,"paste-special-button-anchor",i);const s=this.getCommandItems(t);this.item.children=s,this.toolbar.manualShow(this.anchor)}hide(){this.toolbar.close()}clearCheckedState(){this.checkedId=void 0}destroy(){this.toolbar.destroy(),this.editor.removeListener("selectionChanged",this.handleSelectionChange)}getCommandItems(t){const e=i=>({id:i,states:this.checkedId===i?["checked"]:void 0,name:"Keep origin formats",data:t[i]}),o=[];let r=!0;return t["text/x-ones-editor-doc"]?o.push(e("text/x-ones-editor-doc")):t["text/office-html"]?o.push(e("text/office-html")):t["text/html"]?o.push(e("text/html")):t["text/plain"]&&(o.push(e("text/plain")),r=!1),t["text/plain"]&&(r&&o.push({id:"text/plain",states:this.checkedId==="text/plain"?["checked"]:void 0,name:"Paste as plain text",data:t["text/plain"]}),o.push({id:"text/markdown",states:this.checkedId==="text/markdown"?["checked"]:void 0,name:"Paste as markdown",data:t["text/markdown"]})),o}}const yR=y("paste-special");class T1{constructor(t){u(this,"button");u(this,"lastUndoAction",null);u(this,"event",null);u(this,"handlePasteSpecial",t=>{this.editor.undoManager.runInGroup(()=>{this.editor.undoManager.undoTo(this.lastUndoAction),this.editor.pasteDoc(t)})});this.editor=t,this.button=new kR(t,this.handlePasteSpecial)}destroy(){this.event=null,this.button.destroy()}handleChanged(t,e){this.event=null,this.button.hide()}async handleBeforePaste(t,e){return yR.debug("before paste"),this.lastUndoAction=t.undoManager.lastAction(),!1}async handleAfterPaste(t,e,o){if(Object.keys(o).length<=1)return!1;const r=t.selection.range;if(r.isCollapsed()){const i=t.getBlockById(r.start.blockId);if(!H(t,i))return!1;this.button.clearCheckedState(),this.button.show(o),this.event=e}return!1}}const AF="",wR=y("html-to-doc");function BR(n){const t="ones-editor-doc::",e="::ones-editor-doc";let o=n.indexOf(t);if(o!==-1){o+=t.length;const r=n.indexOf(e,o);if(r!==-1){const i=n.substr(o,r-o);try{const s=el(i);return JSON.parse(s)}catch(s){wR.error(`invalid doc data: ${s}, ${i}`)}}}return null}function nr(n){const t=n.type;if(t==="link")return!!n.tokens.some(nr);switch(t){case"code":case"table":case"hr":case"blockquote":case"list":case"list_item":case"image":case"paragraph":return!0;default:return!1}}function ER(n){return!nr(n)}function IR(n){if(n.length===0)return[];if(n.length===1)return[n];const t=[];let e=[n[0]],o=nr(n[0]);for(let r=1;r<n.length;r++){const i=n[r];o===nr(i)?e.push(i):(t.push(e),e=[i],o=nr(i))}return t.push(e),t}function xR(n,t,e){const o=n.href;let r=e.tokensToText(n.tokens,t,e);return r=yl(r,"link",o),r}function SR(n,t){const e=n.text;return[_e(e,{...t,"style-code":!0})]}let Ts;function G4(n){Ts||(Ts=document.createElement("textarea")),Ts.innerHTML=n;const t=Ts.childNodes.length===0?"":Ts.childNodes[0].nodeValue;return t!=null?t:""}function TR(n,t,e){const r=n.tokens;return r?e.tokensToText(r,t,e):Td(G4(n.text),t)}const DR=y("token-to-text");function D1(n,t,e){return n.map(r=>r.type==="text"?TR(r,t,e):r.type==="strong"?e.tokensToText(r.tokens,{...t,"style-bold":!0},e):r.type==="em"?e.tokensToText(r.tokens,{...t,"style-italic":!0},e):r.type==="link"?xR(r,t,e):r.type==="codespan"?SR(r,t):r.type==="br"?[{insert:" ",attributes:{box:!0,type:"br"}}]:r.type==="escape"?Td(G4(r.text),t):(DR.warn(`unknown token in text: ${JSON.stringify(r)}`),[])).flat()}function LR(n,t){const e=D1(n.tokens,{},t);return[{id:N(),type:"text",text:e,heading:n.depth}]}function MR(n,t){const{text:e,children:o}=t.tokensToTextWithChildren(n.tokens,t),r=[];return e.length>0&&r.push({id:N(),type:"text",text:e}),r.push(...o),r}function RR(n,t){const e=typeof n.start=="number"?n.start:1,o=n.ordered,r=N(),i=[];return n.items.forEach((l,c)=>{const a={...t,listLevel:t.listLevel+1},{text:h,children:f}=t.tokensToTextWithChildren(l.tokens,a),m={id:N(),type:"list",groupId:r,ordered:o,start:e+c,text:h,level:t.listLevel};i.push(m),i.push(...f)}),i}function OR(n,t){const e=t.tokensToBlocks(n.tokens,t);return e.forEach(o=>{o.quoted=!0}),e}const Z4=100,AR=20,_R=600;function NR(n,t){const e=t.text;if(e){const o=wt(e);return Math.min(rl(o,n)+AR,_R)}return Z4}function Y4(n,t){let e=Z4;return t.forEach(o=>{e=Math.max(e,NR(n,o))}),e}function PR(n,t){var l,c;const e=n.header.length,o=n.rows.length+1,r=[],i=Array(e).fill(100);for(let a=0;a<o;a++){let h;a===0?h=n.header:h=n.rows[a-1];for(let f=0;f<e;f++){const m=h[f],C=(l=m==null?void 0:m.tokens)!=null?l:[],v=N();r.push(v);let w;if(C.length===0)w=[Il()];else if(nr(C[0]))w=t.tokensToBlocks(m.tokens,t),w.length===0&&w.push(Il());else{const{text:E,children:L}=t.tokensToTextWithChildren(m.tokens,t);w=[{id:N(),type:"text",text:E},...L]}t.doc.blocks[v]=w,i[f]=Math.max(i[f],Y4((c=t.font)!=null?c:"",w))}}return[{id:N(),type:"table",cols:e,rows:o,colsWidth:i,children:r}]}function $R(n){return[{id:N(),type:"embed",embedType:"hr",embedData:{}}]}function jR(n,t){var c;const e=n.text;if(!e)return[];try{const a=n.text,h=el(a),f=JSON.parse(h);if(f){const{root:m,...C}=f.blocks;return t.doc.blocks={...t.doc.blocks,...C},m}}catch{}const o=(c=n.lang)!=null?c:"Plain Text";if(o==="mermaid")return[{id:N(),type:"embed",embedType:"mermaid",embedData:{mermaidText:e}}];if(o==="plantuml")return[{id:N(),type:"embed",embedType:"plantuml",embedData:{plantumlText:e}}];if(o==="flow"||o==="flowchart")return[{id:N(),type:"embed",embedType:"flowchart",embedData:{flowchartText:e}}];const i=e.split(`
|
|
506
506
|
`).map(a=>({id:N(),type:"text",text:Oi(a)})),s=t.doc,l=N();return s.blocks[l]=i,[{id:N(),type:"code",language:o,children:[l]}]}function HR(n){return[{id:N(),type:"embed",embedType:"image",embedData:{src:n.href,title:n.title}}]}function FR(n,t){const{text:e,children:o}=t.tokensToTextWithChildren(n.tokens,t),r=[];return e.length>0&&r.push({id:N(),type:"text",text:e}),r.push(...o),r}const zR=y("markdown-to-doc");function UR(n,t){return n.type==="heading"?LR(n,t):n.type==="paragraph"?MR(n,t):n.type==="list"?RR(n,t):n.type==="blockquote"?OR(n,t):n.type==="table"?PR(n,t):n.type==="hr"?$R():n.type==="code"?jR(n,t):n.type==="image"?HR(n):n.type==="link"?FR(n,t):(zR.log(`unknown block token, ${JSON.stringify(n)}`),[])}function L1(n,t){const e=[];return n.forEach(o=>{const r=UR(o,t);e.push(...r)}),e}const VR=y("markdown-to-doc");function qR(n,t){const e={text:[],children:[]};return IR(n).forEach((r,i)=>{const s=r[0];if(i===0&&ER(s)){e.text=D1(r,{},t);return}d(VR,nr(s),`not a block token: ${JSON.stringify(s)}`),e.children.push(...L1(r,t))}),e}function Q4(n,t){const o=new b9.marked.Lexer().lex(n),r={blocks:{root:[]},meta:{},comments:{}},i={font:t==null?void 0:t.font,doc:r,tokensToText:D1,tokensToBlocks:L1,tokensToTextWithChildren:qR,htmlToDoc:t==null?void 0:t.htmlToDoc,listLevel:1},s=L1(o,i);return s.length===0?null:(r.blocks.root.push(...s),r)}function WR(n){if(n.nodeName!=="DIV")return!1;const t=n;return Array.from(t.childNodes).every(e=>e.nodeName==="SPAN"||e instanceof Text)?!!t.querySelector(":scope > .hljs-function, :scope > .hljs-params, :scope > .hljs-string, :scope > .hljs-keyword, :scope > .hljs-attr"):!1}function K4(n){if(WR(n)){const t=n,e=t.parentNode,o=document.createElement("pre");Array.from(t.childNodes).forEach(r=>o.appendChild(r)),e==null||e.insertBefore(o,t);return}n.childNodes.forEach(t=>K4(t))}function Jc(n){var t;if(n instanceof HTMLBRElement){const e=document.createTextNode(`
|
|
507
507
|
`);(t=n.parentNode)==null||t.insertBefore(e,n),n.remove();return}n.childNodes.forEach(Jc)}function GR(n){n.addRule("preOnlyBlockToCode",{filter:t=>t.nodeName!=="PRE"?!1:Array.from(t.childNodes).every(e=>e.nodeName==="SPAN"||e instanceof Text||e.nodeName==="BR"),replacement:(t,e,o)=>{var r;return Jc(e),`
|
|
508
508
|
|
|
@@ -550,13 +550,13 @@ xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
|
|
|
550
550
|
`}})}class tO{constructor(t){u(this,"_grid",[]);u(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 h=Number.parseInt(a,10);if(h)return h}return c.cell.getBoundingClientRect().width}return 1e9}),i=Math.min(...r);return i===1e9||Number.isNaN(i)||i<30?0:i}}function eO(n){return new tO(n)}function J4(n,t){var c;const e=eO(n),o=[],r={},i=e.rowCount,s=e.colCount,l=Array(s).fill(100);for(let a=0;a<i;a++)for(let h=0;h<s;h++){let f;const m=e.getCellData({row:a,col:h});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:w}=e.getCellSpan({row:a,col:h});w>1&&(r[`${C}_rowSpan`]=w),v>1&&(r[`${C}_colSpan`]=v),t.doc.blocks[C]=f,m&&!m.virtual&&(l[h]=Math.max(l[h],Y4((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 X4(n,t){var e;if(n.tagName==="TABLE"){const o={blocks:{root:[]},meta:{},comments:{}},r=J4(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=Do(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=>X4(o,t))}function t6(n){if(n instanceof HTMLStyleElement){n.remove();return}Array.from(n.children).forEach(t6)}function e6(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(e6)}function nO(n,t){const e=ol(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(e6),Array.from(e.children).forEach(r=>X4(r,t)),Array.from(e.children).forEach(t6),K4(e),lm(e)}const Yn=new M9.default;Yn.use(GR),Yn.use(ZR),Yn.use(YR),Yn.use(QR),Yn.use(KR),Yn.use(JR),Yn.use(XR),Yn.use(p9.gfm);function oO(n,t){const e=n6(n,t);if(!e)return[];const{root:o,...r}=e.blocks;return t.doc.blocks={...t.doc.blocks,...r},o}function n6(n,t){const e=Yn.turndown(n);return Q4(e,{htmlToDoc:o=>o6(o,t)})}function o6(n,t){const e=nO(n,{font:t==null?void 0:t.font,htmlToBlocks:oO});return n6(e)}function r6(n){return n.indexOf('xmlns:o="urn:schemas-microsoft-com:office:office"')!==-1}function Xc(n){return["A","B","DEL","I","U","S","SPAN","SUB","SUP"].indexOf(n.tagName)!==-1}function rO(n){return["P","H1","H2","H3","H4","H5","H6","H7","H8","LI"].indexOf(n.tagName)!==-1}function i6(n){return n.replace(/\r\n/g," ").replace(/\n/g," ").replace(/\r/g," ")}function iO(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 sO(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 s6(n){var e;return Array.from(((e=n.getAttribute("style"))!=null?e:"").split(" ")).findIndex(o=>o.startsWith("level"))!==-1}function lO(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 l6(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 cO(n,t){n.setAttribute("data-group-id",t)}function aO(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(s6(r)){const i=lO(r);o!==i&&(e(0),o=i);const s=l6(r);e(s);let l=t[`${s}`];l||(l=N(),t[`${s}`]=l),cO(r,l)}})}function c6(n){if(!s6(n))return{};const t=l6(n),e=n.getAttribute("data-group-id")||N();return{start:1,level:t,groupId:e,ordered:!0,type:"list"}}const dO=y("office-list");function a6(n){return n instanceof HTMLOListElement||n instanceof HTMLUListElement}function uO(n,t){d(dO,a6(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 h=c6(c),f=t.textElementToBlocks(c,t);l||(l=h.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 d6(n,t){if(n.nodeName==="META")return[];if(n instanceof HTMLTableElement)return J4(n,t);if(a6(n))return[...uO(n,t)];if(iO(n))return[...sO(n)];if(rO(n))return[...t.textElementToBlocks(n,t)];if(!n.children)return[];const e=[];return Array.from(n.children).forEach(o=>{const r=d6(o,t);e.push(...r)}),e}function u6(n,t){const e=[];return n.forEach(o=>{var r;if(o instanceof Element)if(Xc(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=jn(i6((r=o.textContent)!=null?r:""));e.push(i)}}),e}function hO(n){const t=Array.from(n.children);for(let e=0;e<t.length;e++){const o=t[e];if(!Xc(o))continue;let r=e+1;for(;r<t.length&&Xc(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 fO(n,t){const e=ol(n);return u6(Array.from(e.childNodes),t)}function mO(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 gO(n,t){var o;const e=i6((o=n.nodeValue)!=null?o:" ");return t&&Object.keys(t).length>0?{insert:e,attributes:t}:{insert:e}}function pO(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 h6(n,t,e){if(n instanceof HTMLSpanElement&&n.getAttribute("style")==="mso-list:Ignore")return;const o=pO(n,t);if(n instanceof Text&&n.nodeValue){e.push(gO(n,o));return}n.childNodes.length>0&&Array.from(n.childNodes).forEach(r=>{h6(r,o,e)})}function f6(n){return n instanceof Element?Xc(n):!0}function M1(n){return!f6(n)}function CO(n){if(n.length===0)return[];if(n.length===1)return[n];const t=[];let e=[n[0]],o=M1(n[0]);for(let r=1;r<n.length;r++){const i=n[r];o===M1(i)?e.push(i):(t.push(e),e=[i],o=M1(i))}return t.push(e),t}function bO(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=CO(Array.from(n.childNodes)),r=[];return o.forEach((i,s)=>{if(f6(i[0])){const l=[],c={};Array.from(n.childNodes).forEach(h=>{h6(h,c,l)});let a={};s===0&&(a=c6(n)),r.push({id:N(),type:"text",text:l,...a,...e,...mO(n)})}i.forEach(l=>{const c=t.blockElementToBlocks(l,t);r.push(...c)})}),r}function vO(n,t){const e=ol(n);aO(e),hO(e);const o={blocks:{root:[]},meta:{},comments:{}},r={font:t==null?void 0:t.font,doc:o,blockElementToBlocks:d6,textElementToBlocks:bO,htmlToBlocks:fO},i=u6(Array.from(e.children),r);if(i.length!==0)return o.blocks.root=i,o}const kO=y("html-to-doc");function m6(n,t){if(!n)return null;const e=BR(n);if(e)return e;if(r6(n)){const o=vO(n,t);if(o)return o}try{return o6(n,t)}catch(o){kO.error(o)}return null}class yO{async fromData(t,e){const o={},r=e.getData("text/html");if(r){const i=m6(r,{font:t.rootContainer});i&&(r6(r)?o["text/office-html"]=i:o["text/html"]=i)}return o}}class wO{async fromData(t,e){const o=e.getData("text/plain");if(!o)return;const r=Q4(o,{font:t.rootContainer,htmlToDoc:m6});if(!!r)return{"text/markdown":r}}}function BO(n){return/^([\d\w\u4e00-\u9fa5\s]*[\u4e00-\u9fa5\s]{1}|)((https|http|ftp)?:\/\/)[^\s]+/.test(n)}function EO(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 IO{async fromData(t,e){const o={},r=e.getData("text/plain");if(r){const l={blocks:{root:r.replace(/\r\n/g,`
|
|
551
551
|
`).replace(/\r/g,`
|
|
552
552
|
`).split(`
|
|
553
|
-
`).map(c=>{const a={id:N(),type:"text"};if(BO(c))return a.text=EO(c),a;const h=c?[_e(c,null)]:[];return a.text=h,a})},meta:{},comments:{}};o["text/plain"]=l}return o}}function xO(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 g6{constructor(t){t.dataConverter.addConverter(new yO),t.dataConverter.addConverter(new IO),t.dataConverter.addConverter(new wO)}async handleBeforePaste(t,e,o){const r=e.clipboardData;if(r){const i=xO(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=j(o),i=K(o),s=U(r);let l=i;yt(t,o)||(l+=1);for(let c=0;c<e.length;c++){const a=e[c],h=await md(t,"image",s,l+c,{file:a});h&&Ym(t,h,"image",{id:"replace-image",name:"Replace image",data:{block:h,image:a}})}}}function p6(n){return St.isSafari&&!!n&&Date.now()-n<100}const C6=y("highlight-data");class ta{constructor(t){u(this,"data",new Map);this.editor=t}add(t,e,o){const r={id:N(),blockId:G(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(C6,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 ta(t))}}function SO(n,t,e,o,r){const s=ta.getData(n).add(t,e,o);return r.setAttribute("data-highlight-id",s.id),s}function ea(n,t){const e=t.getAttribute("data-highlight-id");return d(C6,e,"invalid highlight elem, no id"),ta.getData(n).get(e)}const Ds=y("highligh-dom");function TO(n){return lt(n,"editor-highlight")}function In(n){const t=n.rootContainer.querySelectorAll(".editor-highlight");return Array.from(t)}function DO(n){const t=n.rootContainer.querySelectorAll(".editor-replace-result-highlight");return Array.from(t)}function R1(n){const t=n.querySelectorAll(".editor-highlight");return Array.from(t)}function LO(n){R1(n).forEach(t=>{t.remove()})}function ei(n){return In(n).length}function MO(n,t){d(Ds,t>=0,`invalid highlight index: ${t}`);const e=In(n);return e.length===0?null:(d(Ds,t<e.length,`invalid highlight index: ${t}/${e.length}`),e[t])}function RO(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 b6(n,t,e,o,r){d(Ds,o>0,`invalid end: ${o}`);const i=At(t),s=t.getBoundingClientRect(),l=Oo(n,t,Lt(n,t,e,o)),a=b("div",[r==="find"?"editor-highlight":"editor-replace-result-highlight"],i);l.forEach(h=>{RO(a,t,{left:h.left-s.left,width:h.width,top:h.top-s.top,height:h.height})}),SO(n,t,e,o,a)}function OO(n,t,e,o){return b6(n,t,e,o,"find")}function v6(n,t,e,o){return b6(n,t,e,o,"replace")}function na(n,t){In(n).forEach(l=>{lt(l,"active")&&F(l,"active")}),M(t,"active"),d(Ds,t.firstChild instanceof HTMLElement,"invalid highligh dom, invalid elem child");const o=t.firstChild,r=o.getBoundingClientRect(),i=_n(n.rootContainer);let s=r.y;s===0&&(s=o.getBoundingClientRect().y),Bi(i)}function Ls(n){const t=n.rootContainer.querySelector(".editor-highlight.active");return t||null}function k6(n){return d(Ds,n,"no highlight elem"),lt(n,"editor-highlight-readonly")}const ni=y("highligh-text");function AO(n){DO(n).forEach(e=>{e.remove()})}function O1(n,t){In(n).forEach(o=>{o.remove()}),t!=null&&t.keepReplaceResult||AO(n)}function y6(n){const t=Ls(n);if(!t)return-1;const o=In(n).indexOf(t);return d(ni,o!==-1,`invalid highlight index: ${o}`),o}function _O(n){const t=In(n);if(t.length===0)return 0;const e=Ls(n);let o=e?t.indexOf(e):-1;!e||o===-1||o===t.length-1?o=0:o+=1;const r=t[o];return na(n,r),o}function NO(n){const t=In(n);if(t.length===0)return 0;const e=Ls(n);let o=e?t.indexOf(e):-1;!e||o===-1||o===0?o=t.length-1:o-=1;const r=t[o];return na(n,r),o}function PO(n,t){const e=In(n);e.length>0&&t<e.length&&na(n,e[t])}function $O(n,t,e){const o=Ls(n);if(!o)return!1;const r=z(o);if(d(ni,r,"no parent block"),!n.isBlockWritable(r))return!1;const i=ei(n);let s=y6(n);if(!k6(o)&&n.isBlockWritable(r)){const a=ea(n,o),h=n.getBlockText(r),{start:f,end:m}=ea(n,o),[C,v]=oe.transformOffset(a.oldText,h,[f,m]),w=dg(h,C,v-C);if(wt(w).toLowerCase()!==t.toLowerCase())return!1;const E=El(h,C,v,e);n.setBlockText(r,E),LO(r),w6(n,r,t),e&&v6(n,r,C,C+e.length)}const l=ei(n);s>=l?s=0:l>i&&(s+=1);const c=MO(n,s);return c&&na(n,c),!0}function jO(n,t,e,o){if(!H(n,t)||!n.isBlockWritable(t))return 0;const r=n.getBlockText(t);d(ni,r,"no block text");const i={count:0},s=Og(r,e,o,i);return wt(r)===wt(s)?0:(n.setBlockText(t,s),i.count)}function HO(n,t,e){if(d(ni,TO(t),"not a highlight elem"),k6(t))return;d(ni,e>0,"invalid highlight length");const o=ea(n,t),r=z(t);d(ni,r,"no parent block"),v6(n,r,o.start,o.start+e)}function FO(n,t){In(n).forEach(o=>{HO(n,o,t)})}function zO(n,t,e){if(n.readonly)return 0;const o=i=>{let s=0;return Ot(i).forEach(c=>{ct(n,c)?Me(n,c).forEach(h=>{s+=o(h)}):s+=jO(n,c,t,e)}),s},r=o(n.rootContainer);return e.length>0&&FO(n,e.length),r}function UO(n){const t=n.selection.range.end,e=n.getBlockById(t.blockId),o=t.isSimple()?t.offset:1,r=R1(e);for(let l=0;l<r.length;l++){const c=r[l],{end:a}=ea(n,c);if(a>=o)return c}const i=yd(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=R1(c);if(a.length>0)return a[0]}return null}function VO(n){const t=In(n),e=UO(n);return e?t.indexOf(e):0}function w6(n,t,e){if(!!e&&H(n,t)){const o=n.getBlockText(t),r=Nd(o,e);r.length>0&&r.forEach(({start:i,end:s})=>{OO(n,t,i,s)})}}function qO(n,t){if(O1(n),!t)return;yd(n,{simpleBlockOnly:!0}).forEach(o=>{w6(n,o,t)})}class WO{constructor(t){u(this,"dialog",null);u(this,"root");u(this,"oldText","");u(this,"_compositionEndTime",0);u(this,"components");u(this,"handleFindChanged",()=>{this.doSearch({keepReplaceResult:!1,gotoFirstSearchResult:!0})});u(this,"handleCompositionEnd",()=>{this._compositionEndTime=Date.now(),this.handleFindChanged()});u(this,"handleInput",t=>{if(t.isComposing||p6(this._compositionEndTime)){this.doSearch.cancel();return}this.handleFindChanged()});u(this,"handleFind",()=>{this.findNext({keepSearchResult:!1})});u(this,"handleReplace",()=>{const t=this.components.findInput.value;if(!t||!Ls(this.editor))return;const o=this.components.replaceInput.value;if(t===o)return;if($O(this.editor,t,o)){const i=y6(this.editor),s=ei(this.editor);this.updateSearchStatus(i,s)}this.findNext({keepSearchResult:!0})});u(this,"handleReplaceAll",()=>{const t=this.components.findInput.value;if(!t)return;const e=this.components.replaceInput.value;if(t===e)return;zO(this.editor,t,e)>0&&(this.oldText="",this.doSearchNow({keepReplaceResult:!0,gotoFirstSearchResult:!0}),this.clearFind({keepReplaceResult:!0}))});u(this,"doSearch",Qt.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=hr(c0,["editor-find-dialog-button-close"],e),s=b("label",["editor-find-dialog-label"],r,S.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=S.t("find.findPlaceholder");const a=b("div",["editor-find-dialog-status"],l),h=hr(tw,["editor-find-dialog-icon-button"],a),f=b("div",["editor-find-dialog-curr"],a,"0/0"),m=hr(ew,["editor-find-dialog-icon-button"],a);let C;S.t("find.moreButton")?C=b("button",["editor-find-dialog-button"],r,S.t("find.moreButton")):C=hr(a0,["editor-find-dialog-icon-button-border"],r);const v=b("div",["editor-find-dialog-row"],o),w=b("label",["editor-find-dialog-label"],v,S.t("find.replaceLabel"));w.htmlFor="";const E=b("div",["editor-find-dialog-input-container"],v),D=b("input",["editor-find-dialog-input"],E);D.type="text",D.placeholder=S.t("find.replacePlaceholder");const x=b("div",["editor-find-dialog-row"],o);b("div",["editor-find-dialog-space"],x);const A=b("button",["editor-find-dialog-button"],x,S.t("find.findButton")),O=b("button",["editor-find-dialog-button"],x,S.t("find.replaceButton")),P=b("button",["editor-find-dialog-button"],x,S.t("find.replaceAllButton"));C.onclick=()=>{this.showReplace()},i.onclick=()=>{this.hide()},c.onkeydown=V=>{if(V.isComposing||p6(this._compositionEndTime)){this.doSearch.cancel();return}Xf(V)?(this.doSearch.cancel(),this.doSearchNow({keepReplaceResult:!1,gotoFirstSearchResult:!0})):Ya(V)&&this.hide()},c.oninput=this.handleInput,c.onpaste=this.handleFindChanged,c.oncut=this.handleFindChanged,c.addEventListener("compositionend",this.handleCompositionEnd),c.maxLength=50,A.onclick=this.handleFind,O.onclick=this.handleReplace,P.onclick=this.handleReplaceAll,D.maxLength=50,m.onclick=()=>{this.gotoNext()},h.onclick=()=>{this.gotoPrev()},this.components={findInput:c,findPrev:h,findCurrent:f,findNext:m,replaceInput:D,findButton:A,replaceButton:O,replaceAllButton:P,closeButton:i,showReplaceButton:C,rowReplace:v,rowActions:x,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,qO(this.editor,e);const o=ei(this.editor),r=VO(this.editor);t.gotoFirstSearchResult&&PO(this.editor,r),this.updateSearchStatus(r,o)}gotoNext(){const t=ei(this.editor),e=_O(this.editor);this.updateSearchStatus(e,t)}gotoPrev(){const t=ei(this.editor),e=NO(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){O1(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 sc(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,h=c.right-this.root.clientWidth-12;return new DOMRect(h,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(),O1(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 GO={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"}},ZO={find:{findLabel:"Find:",replaceLabel:"Replace:",findButton:"Find",replaceButton:"Replace",replaceAllButton:"Replace All",moreButton:"",findPlaceholder:"Find text in document",replacePlaceholder:"Replace to"}};S.mergeLang({"zh-CN":GO,"en-US":ZO});function B6(n){return n.addCustom("find-dialog",()=>new WO(n)).show(),!0}const E6={"CtrlOrCmd+F":B6},_F="";function YO(n){B6(n)}function A1(n,t){return t.map(e=>{var i,s;const o=kt(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 oa(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 I6(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 ra(n,t,e){const o=A1(n,[t]),r=oa({editor:n,abstract:o});I6(n,t,r);const i=ro();return e.localCreateComment(r,i),r}const QO=y("standard-block-actions");class KO{constructor(t,e){u(this,"executeCommand",(t,e,o)=>{const r=o.data;try{this.editorComments.showCommentList();const i=t.getBlockById(r);ra(t,i,this.provider)}catch(i){QO.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:G(e),order:100}],executeCommand:this.executeCommand}}}function JO(n,t){let e=t.clientX;const o=t.clientY,r=n.rootContainer.getBoundingClientRect().right;if(e<r-100||e>r+100)return null;const i=t.target;if(i&&i instanceof Element){const l=z(i);if(l&&vt(n.rootContainer,l))return l}e>r&&(e=r-100);const s=document.elementFromPoint(e,o);if(s){const l=z(s);if(l&&vt(n.rootContainer,l))return l}return null}const{t:XO}=S;class tA{constructor(t,e,o){u(this,"buttonElement");u(this,"currentBlockId","");u(this,"handleDocumentMouseMove",t=>{const e=JO(this.editor,t);if(!e){this.buttonElement.parentElement&&this.buttonElement.remove();return}const o=ul(e);if(this.editor.getBlockIndex(o)===0&&this.editor.getBlockData(o).heading===1)return;this.updateButton(o),At(e).appendChild(this.buttonElement)});u(this,"handleButtonClick",t=>{if(!this.currentBlockId)return;const e=this.editor.getBlockById(this.currentBlockId);ra(this.editor,e,this.commentProvider),this.editorComments.showCommentList()});this.editor=t,this.commentProvider=e,this.editorComments=o,this.buttonElement=this.createButton(),document.addEventListener("mousemove",this.handleDocumentMouseMove),this.buttonElement.addEventListener("click",this.handleButtonClick)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.buttonElement.removeEventListener("click",this.handleButtonClick)}createButton(){const t=Vn("block-comment-button",XO("comment.comment"),ns,void 0,this.editor.clientId);return t.classList.add("block-comment-button"),t}updateButton(t){yt(this.editor,t)||(this.currentBlockId=G(t))}}var mt=(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))(mt||{});const _1="group-item-action",x6="last-comment-item",Qn="disabled",S6=500;function or(n){return n.id!==n.groupId}function T6(n,t=".comment-item-root"){return n.querySelectorAll(t).length}function eA(n){const t=n.closest(".comment-item-root");return t?t.id:null}function Kn(n,t){n.setAttribute(_1,t)}function nA(n){return n.closest(`[${_1}]`)}function oA(n){var t;return(t=n.getAttribute(_1))!=null?t:""}function rA(n){return lt(n,Qn)}function D6(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 L6(n){return Array.from(n.attributes).map(e=>e.name).filter(e=>e.startsWith("comment-")).map(e=>e.replace("comment-",""))}const M6=y("doc-comments");function R6(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 h=a;o.has(h)||(o.add(h),e.push(h))}})}});const r=t.children;!r||r.forEach(i=>{n.blocks[i].forEach(l=>{R6(n,l,e,o)})})}function iA(n){const t=[],e=new Set;n.blocks.root.forEach(r=>{R6(n,r,t,e)});const o=new Map;return t.forEach((r,i)=>o.set(r,i)),o}function sA(n){const t=new Map;n.forEach(r=>{if(or(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(!or(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 po(n,t){const e=n.doc.toJSON(),o=iA(e);return sA(t.getComments()).filter(s=>o.has(s.groupId)).sort((s,l)=>{const c=o.get(s.groupId),a=o.get(l.groupId);return d(M6,c!==void 0,`comment not exists in doc, ${s.groupId}`),d(M6,a!==void 0,`comment not exists in doc, ${l.groupId}`),c-a})}function N1(n){const{children:t,...e}=n,o=[e];return t.forEach(r=>{o.push(r)}),o}function lA(n,t){return po(n,t).map(N1).reduce((r,i)=>i.length+r,0)}function P1(n,t){const e=[],o=n.getBlockById(t.blockId);if(H(n,o)){const i=t.blockId,s=t.offset,l=n.getBlockById(i),c=n.getBlockText(l),a=Bl(c,s);a&&Object.entries(a).forEach(([h,f])=>{h.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 cA(n){const t=n.selection.range;if(!t.isSimple())return[];if(t.start.blockId!==t.end.blockId)return[];if(t.isCollapsed())return P1(n,t.start);const{start:e,end:o}=t,r=P1(n,e),i=P1(n,o);return ja.default(r,i)}function O6(n,t){n.rootContainer.querySelectorAll(`span.text.comment[comment-${t}],[data-type=editor-block].comment[comment-${t}]`).forEach(o=>{F(o,"active")})}function A6(n,t){const e=n.rootContainer.querySelector("span.text.comment.active,[data-type=editor-block].comment.active");if(!t)e&&L6(e).forEach(r=>O6(n,r));else{const o=t.toLocaleLowerCase();if(e){const i=L6(e);if(i.length===1&&i[0]===o)return;i.forEach(s=>O6(n,s))}const r=n.rootContainer.querySelectorAll(`span.text.comment[comment-${o}],[data-type=editor-block].comment[comment-${o}]`);if(r){r.forEach(s=>{M(s,"active")});const i=r[0];Bi(i)}}}const NF="";y("comment-editor");const{t:aA}=S,$1="comment-editor-readonly",Ms="comment-editor-editing";class j1{constructor(t,e,o){u(this,"root");u(this,"components");u(this,"handleEditorBlur",()=>{this.inactiveEditor()});u(this,"handleEditorFocus",()=>{this.editor.readonly||this.activeEditor()});u(this,"activeEditor",()=>{lt(this.root,Ms)||M(this.root,Ms)});u(this,"inactiveEditor",()=>{F(this.root,Ms)});u(this,"handleInsertImg",async()=>{const{editor:t}=this.components,e=U(t.rootContainer),o=await Lo("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);Ft.getImageObject(t,a).replaceImage(0,o)});u(this,"handleReadonlyChange",t=>{t.readonly?(F(this.root,Ms),M(this.root,$1)):(M(this.root,Ms),F(this.root,$1))});u(this,"setDoc",t=>{const{components:{editor:e}}=this;e.doc.externalDoc.setDoc(t)});u(this,"getDoc",()=>{const{components:{editor:t}}=this;return t.doc.toJSON()});u(this,"isEmpty",()=>xl(this.getDoc()));u(this,"edit",()=>{const{editor:t}=this.components;t.readonly=!1,wp(t),this.activeEditor()});u(this,"clear",()=>{const t=ro();this.setDoc(t)});u(this,"readonly",()=>{const{editor:t}=this.components;t.readonly=!0});u(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",$1],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 yu(this.doc));r.readonly=!0,r.addListener("readonlyChanged",this.handleReadonlyChange),r.addListener("focus",this.handleEditorFocus),r.addListener("blur",this.handleEditorBlur);const i=Xo(this.root,"comment-editor-img",aA("comment.image"),aw,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 dA{constructor(t){u(this,"handleBeforeKeyDown",(t,e)=>{if(An(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 uA{constructor(t,e,o){u(this,"handleBeforeKeyDown",(t,e)=>{if(An(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 hA=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
553
|
+
`).map(c=>{const a={id:N(),type:"text"};if(BO(c))return a.text=EO(c),a;const h=c?[_e(c,null)]:[];return a.text=h,a})},meta:{},comments:{}};o["text/plain"]=l}return o}}function xO(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 g6{constructor(t){t.dataConverter.addConverter(new yO),t.dataConverter.addConverter(new IO),t.dataConverter.addConverter(new wO)}async handleBeforePaste(t,e,o){const r=e.clipboardData;if(r){const i=xO(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=j(o),i=K(o),s=U(r);let l=i;yt(t,o)||(l+=1);for(let c=0;c<e.length;c++){const a=e[c],h=await md(t,"image",s,l+c,{file:a});h&&Ym(t,h,"image",{id:"replace-image",name:"Replace image",data:{block:h,image:a}})}}}function p6(n){return St.isSafari&&!!n&&Date.now()-n<100}const C6=y("highlight-data");class ta{constructor(t){u(this,"data",new Map);this.editor=t}add(t,e,o){const r={id:N(),blockId:G(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(C6,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 ta(t))}}function SO(n,t,e,o,r){const s=ta.getData(n).add(t,e,o);return r.setAttribute("data-highlight-id",s.id),s}function ea(n,t){const e=t.getAttribute("data-highlight-id");return d(C6,e,"invalid highlight elem, no id"),ta.getData(n).get(e)}const Ds=y("highligh-dom");function TO(n){return lt(n,"editor-highlight")}function In(n){const t=n.rootContainer.querySelectorAll(".editor-highlight");return Array.from(t)}function DO(n){const t=n.rootContainer.querySelectorAll(".editor-replace-result-highlight");return Array.from(t)}function R1(n){const t=n.querySelectorAll(".editor-highlight");return Array.from(t)}function LO(n){R1(n).forEach(t=>{t.remove()})}function ei(n){return In(n).length}function MO(n,t){d(Ds,t>=0,`invalid highlight index: ${t}`);const e=In(n);return e.length===0?null:(d(Ds,t<e.length,`invalid highlight index: ${t}/${e.length}`),e[t])}function RO(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 b6(n,t,e,o,r){d(Ds,o>0,`invalid end: ${o}`);const i=At(t),s=t.getBoundingClientRect(),l=Oo(n,t,Lt(n,t,e,o)),a=b("div",[r==="find"?"editor-highlight":"editor-replace-result-highlight"],i);l.forEach(h=>{RO(a,t,{left:h.left-s.left,width:h.width,top:h.top-s.top,height:h.height})}),SO(n,t,e,o,a)}function OO(n,t,e,o){return b6(n,t,e,o,"find")}function v6(n,t,e,o){return b6(n,t,e,o,"replace")}function na(n,t){In(n).forEach(l=>{lt(l,"active")&&F(l,"active")}),M(t,"active"),d(Ds,t.firstChild instanceof HTMLElement,"invalid highligh dom, invalid elem child");const o=t.firstChild,r=o.getBoundingClientRect(),i=_n(n.rootContainer);let s=r.y;s===0&&(s=o.getBoundingClientRect().y),Bi(i)}function Ls(n){const t=n.rootContainer.querySelector(".editor-highlight.active");return t||null}function k6(n){return d(Ds,n,"no highlight elem"),lt(n,"editor-highlight-readonly")}const ni=y("highligh-text");function AO(n){DO(n).forEach(e=>{e.remove()})}function O1(n,t){In(n).forEach(o=>{o.remove()}),t!=null&&t.keepReplaceResult||AO(n)}function y6(n){const t=Ls(n);if(!t)return-1;const o=In(n).indexOf(t);return d(ni,o!==-1,`invalid highlight index: ${o}`),o}function _O(n){const t=In(n);if(t.length===0)return 0;const e=Ls(n);let o=e?t.indexOf(e):-1;!e||o===-1||o===t.length-1?o=0:o+=1;const r=t[o];return na(n,r),o}function NO(n){const t=In(n);if(t.length===0)return 0;const e=Ls(n);let o=e?t.indexOf(e):-1;!e||o===-1||o===0?o=t.length-1:o-=1;const r=t[o];return na(n,r),o}function PO(n,t){const e=In(n);e.length>0&&t<e.length&&na(n,e[t])}function $O(n,t,e){const o=Ls(n);if(!o)return!1;const r=z(o);if(d(ni,r,"no parent block"),!n.isBlockWritable(r))return!1;const i=ei(n);let s=y6(n);if(!k6(o)&&n.isBlockWritable(r)){const a=ea(n,o),h=n.getBlockText(r),{start:f,end:m}=ea(n,o),[C,v]=oe.transformOffset(a.oldText,h,[f,m]),w=dg(h,C,v-C);if(wt(w).toLowerCase()!==t.toLowerCase())return!1;const E=El(h,C,v,e);n.setBlockText(r,E),LO(r),w6(n,r,t),e&&v6(n,r,C,C+e.length)}const l=ei(n);s>=l?s=0:l>i&&(s+=1);const c=MO(n,s);return c&&na(n,c),!0}function jO(n,t,e,o){if(!H(n,t)||!n.isBlockWritable(t))return 0;const r=n.getBlockText(t);d(ni,r,"no block text");const i={count:0},s=Og(r,e,o,i);return wt(r)===wt(s)?0:(n.setBlockText(t,s),i.count)}function HO(n,t,e){if(d(ni,TO(t),"not a highlight elem"),k6(t))return;d(ni,e>0,"invalid highlight length");const o=ea(n,t),r=z(t);d(ni,r,"no parent block"),v6(n,r,o.start,o.start+e)}function FO(n,t){In(n).forEach(o=>{HO(n,o,t)})}function zO(n,t,e){if(n.readonly)return 0;const o=i=>{let s=0;return Ot(i).forEach(c=>{ct(n,c)?Me(n,c).forEach(h=>{s+=o(h)}):s+=jO(n,c,t,e)}),s},r=o(n.rootContainer);return e.length>0&&FO(n,e.length),r}function UO(n){const t=n.selection.range.end,e=n.getBlockById(t.blockId),o=t.isSimple()?t.offset:1,r=R1(e);for(let l=0;l<r.length;l++){const c=r[l],{end:a}=ea(n,c);if(a>=o)return c}const i=yd(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=R1(c);if(a.length>0)return a[0]}return null}function VO(n){const t=In(n),e=UO(n);return e?t.indexOf(e):0}function w6(n,t,e){if(!!e&&H(n,t)){const o=n.getBlockText(t),r=Nd(o,e);r.length>0&&r.forEach(({start:i,end:s})=>{OO(n,t,i,s)})}}function qO(n,t){if(O1(n),!t)return;yd(n,{simpleBlockOnly:!0}).forEach(o=>{w6(n,o,t)})}class WO{constructor(t){u(this,"dialog",null);u(this,"root");u(this,"oldText","");u(this,"_compositionEndTime",0);u(this,"components");u(this,"handleFindChanged",()=>{this.doSearch({keepReplaceResult:!1,gotoFirstSearchResult:!0})});u(this,"handleCompositionEnd",()=>{this._compositionEndTime=Date.now(),this.handleFindChanged()});u(this,"handleInput",t=>{if(t.isComposing||p6(this._compositionEndTime)){this.doSearch.cancel();return}this.handleFindChanged()});u(this,"handleFind",()=>{this.findNext({keepSearchResult:!1})});u(this,"handleReplace",()=>{const t=this.components.findInput.value;if(!t||!Ls(this.editor))return;const o=this.components.replaceInput.value;if(t===o)return;if($O(this.editor,t,o)){const i=y6(this.editor),s=ei(this.editor);this.updateSearchStatus(i,s)}this.findNext({keepSearchResult:!0})});u(this,"handleReplaceAll",()=>{const t=this.components.findInput.value;if(!t)return;const e=this.components.replaceInput.value;if(t===e)return;zO(this.editor,t,e)>0&&(this.oldText="",this.doSearchNow({keepReplaceResult:!0,gotoFirstSearchResult:!0}),this.clearFind({keepReplaceResult:!0}))});u(this,"doSearch",Qt.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=hr(c0,["editor-find-dialog-button-close"],e),s=b("label",["editor-find-dialog-label"],r,S.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=S.t("find.findPlaceholder");const a=b("div",["editor-find-dialog-status"],l),h=hr(tw,["editor-find-dialog-icon-button"],a),f=b("div",["editor-find-dialog-curr"],a,"0/0"),m=hr(ew,["editor-find-dialog-icon-button"],a);let C;S.t("find.moreButton")?C=b("button",["editor-find-dialog-button"],r,S.t("find.moreButton")):C=hr(a0,["editor-find-dialog-icon-button-border"],r);const v=b("div",["editor-find-dialog-row"],o),w=b("label",["editor-find-dialog-label"],v,S.t("find.replaceLabel"));w.htmlFor="";const E=b("div",["editor-find-dialog-input-container"],v),L=b("input",["editor-find-dialog-input"],E);L.type="text",L.placeholder=S.t("find.replacePlaceholder");const x=b("div",["editor-find-dialog-row"],o);b("div",["editor-find-dialog-space"],x);const O=b("button",["editor-find-dialog-button"],x,S.t("find.findButton")),A=b("button",["editor-find-dialog-button"],x,S.t("find.replaceButton")),P=b("button",["editor-find-dialog-button"],x,S.t("find.replaceAllButton"));C.onclick=()=>{this.showReplace()},i.onclick=()=>{this.hide()},c.onkeydown=V=>{if(V.isComposing||p6(this._compositionEndTime)){this.doSearch.cancel();return}Xf(V)?(this.doSearch.cancel(),this.doSearchNow({keepReplaceResult:!1,gotoFirstSearchResult:!0})):Ya(V)&&this.hide()},c.oninput=this.handleInput,c.onpaste=this.handleFindChanged,c.oncut=this.handleFindChanged,c.addEventListener("compositionend",this.handleCompositionEnd),c.maxLength=50,O.onclick=this.handleFind,A.onclick=this.handleReplace,P.onclick=this.handleReplaceAll,L.maxLength=50,m.onclick=()=>{this.gotoNext()},h.onclick=()=>{this.gotoPrev()},this.components={findInput:c,findPrev:h,findCurrent:f,findNext:m,replaceInput:L,findButton:O,replaceButton:A,replaceAllButton:P,closeButton:i,showReplaceButton:C,rowReplace:v,rowActions:x,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,qO(this.editor,e);const o=ei(this.editor),r=VO(this.editor);t.gotoFirstSearchResult&&PO(this.editor,r),this.updateSearchStatus(r,o)}gotoNext(){const t=ei(this.editor),e=_O(this.editor);this.updateSearchStatus(e,t)}gotoPrev(){const t=ei(this.editor),e=NO(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){O1(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 sc(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,h=c.right-this.root.clientWidth-12;return new DOMRect(h,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(),O1(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 GO={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"}},ZO={find:{findLabel:"Find:",replaceLabel:"Replace:",findButton:"Find",replaceButton:"Replace",replaceAllButton:"Replace All",moreButton:"",findPlaceholder:"Find text in document",replacePlaceholder:"Replace to"}};S.mergeLang({"zh-CN":GO,"en-US":ZO});function B6(n){return n.addCustom("find-dialog",()=>new WO(n)).show(),!0}const E6={"CtrlOrCmd+F":B6},_F="";function YO(n){B6(n)}function A1(n,t){return t.map(e=>{var i,s;const o=kt(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 oa(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 I6(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 ra(n,t,e){const o=A1(n,[t]),r=oa({editor:n,abstract:o});I6(n,t,r);const i=ro();return e.localCreateComment(r,i),r}const QO=y("standard-block-actions");class KO{constructor(t,e){u(this,"executeCommand",(t,e,o)=>{const r=o.data;try{this.editorComments.showCommentList();const i=t.getBlockById(r);ra(t,i,this.provider)}catch(i){QO.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:G(e),order:100}],executeCommand:this.executeCommand}}}function JO(n,t){let e=t.clientX;const o=t.clientY,r=n.rootContainer.getBoundingClientRect().right;if(e<r-100||e>r+100)return null;const i=t.target;if(i&&i instanceof Element){const l=z(i);if(l&&vt(n.rootContainer,l))return l}e>r&&(e=r-100);const s=document.elementFromPoint(e,o);if(s){const l=z(s);if(l&&vt(n.rootContainer,l))return l}return null}const{t:XO}=S;class tA{constructor(t,e,o){u(this,"buttonElement");u(this,"currentBlockId","");u(this,"handleDocumentMouseMove",t=>{const e=JO(this.editor,t);if(!e){this.buttonElement.parentElement&&this.buttonElement.remove();return}const o=ul(e);if(this.editor.getBlockIndex(o)===0&&this.editor.getBlockData(o).heading===1)return;this.updateButton(o),At(e).appendChild(this.buttonElement)});u(this,"handleButtonClick",t=>{if(!this.currentBlockId)return;const e=this.editor.getBlockById(this.currentBlockId);ra(this.editor,e,this.commentProvider),this.editorComments.showCommentList()});this.editor=t,this.commentProvider=e,this.editorComments=o,this.buttonElement=this.createButton(),document.addEventListener("mousemove",this.handleDocumentMouseMove),this.buttonElement.addEventListener("click",this.handleButtonClick)}destroy(){document.removeEventListener("mousemove",this.handleDocumentMouseMove),this.buttonElement.removeEventListener("click",this.handleButtonClick)}createButton(){const t=Vn("block-comment-button",XO("comment.comment"),ns,void 0,this.editor.clientId);return t.classList.add("block-comment-button"),t}updateButton(t){yt(this.editor,t)||(this.currentBlockId=G(t))}}var mt=(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))(mt||{});const _1="group-item-action",x6="last-comment-item",Qn="disabled",S6=500;function or(n){return n.id!==n.groupId}function T6(n,t=".comment-item-root"){return n.querySelectorAll(t).length}function eA(n){const t=n.closest(".comment-item-root");return t?t.id:null}function Kn(n,t){n.setAttribute(_1,t)}function nA(n){return n.closest(`[${_1}]`)}function oA(n){var t;return(t=n.getAttribute(_1))!=null?t:""}function rA(n){return lt(n,Qn)}function D6(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 L6(n){return Array.from(n.attributes).map(e=>e.name).filter(e=>e.startsWith("comment-")).map(e=>e.replace("comment-",""))}const M6=y("doc-comments");function R6(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 h=a;o.has(h)||(o.add(h),e.push(h))}})}});const r=t.children;!r||r.forEach(i=>{n.blocks[i].forEach(l=>{R6(n,l,e,o)})})}function iA(n){const t=[],e=new Set;n.blocks.root.forEach(r=>{R6(n,r,t,e)});const o=new Map;return t.forEach((r,i)=>o.set(r,i)),o}function sA(n){const t=new Map;n.forEach(r=>{if(or(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(!or(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 po(n,t){const e=n.doc.toJSON(),o=iA(e);return sA(t.getComments()).filter(s=>o.has(s.groupId)).sort((s,l)=>{const c=o.get(s.groupId),a=o.get(l.groupId);return d(M6,c!==void 0,`comment not exists in doc, ${s.groupId}`),d(M6,a!==void 0,`comment not exists in doc, ${l.groupId}`),c-a})}function N1(n){const{children:t,...e}=n,o=[e];return t.forEach(r=>{o.push(r)}),o}function lA(n,t){return po(n,t).map(N1).reduce((r,i)=>i.length+r,0)}function P1(n,t){const e=[],o=n.getBlockById(t.blockId);if(H(n,o)){const i=t.blockId,s=t.offset,l=n.getBlockById(i),c=n.getBlockText(l),a=Bl(c,s);a&&Object.entries(a).forEach(([h,f])=>{h.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 cA(n){const t=n.selection.range;if(!t.isSimple())return[];if(t.start.blockId!==t.end.blockId)return[];if(t.isCollapsed())return P1(n,t.start);const{start:e,end:o}=t,r=P1(n,e),i=P1(n,o);return ja.default(r,i)}function O6(n,t){n.rootContainer.querySelectorAll(`span.text.comment[comment-${t}],[data-type=editor-block].comment[comment-${t}]`).forEach(o=>{F(o,"active")})}function A6(n,t){const e=n.rootContainer.querySelector("span.text.comment.active,[data-type=editor-block].comment.active");if(!t)e&&L6(e).forEach(r=>O6(n,r));else{const o=t.toLocaleLowerCase();if(e){const i=L6(e);if(i.length===1&&i[0]===o)return;i.forEach(s=>O6(n,s))}const r=n.rootContainer.querySelectorAll(`span.text.comment[comment-${o}],[data-type=editor-block].comment[comment-${o}]`);if(r){r.forEach(s=>{M(s,"active")});const i=r[0];Bi(i)}}}const NF="";y("comment-editor");const{t:aA}=S,$1="comment-editor-readonly",Ms="comment-editor-editing";class j1{constructor(t,e,o){u(this,"root");u(this,"components");u(this,"handleEditorBlur",()=>{this.inactiveEditor()});u(this,"handleEditorFocus",()=>{this.editor.readonly||this.activeEditor()});u(this,"activeEditor",()=>{lt(this.root,Ms)||M(this.root,Ms)});u(this,"inactiveEditor",()=>{F(this.root,Ms)});u(this,"handleInsertImg",async()=>{const{editor:t}=this.components,e=U(t.rootContainer),o=await Lo("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);Ft.getImageObject(t,a).replaceImage(0,o)});u(this,"handleReadonlyChange",t=>{t.readonly?(F(this.root,Ms),M(this.root,$1)):(M(this.root,Ms),F(this.root,$1))});u(this,"setDoc",t=>{const{components:{editor:e}}=this;e.doc.externalDoc.setDoc(t)});u(this,"getDoc",()=>{const{components:{editor:t}}=this;return t.doc.toJSON()});u(this,"isEmpty",()=>xl(this.getDoc()));u(this,"edit",()=>{const{editor:t}=this.components;t.readonly=!1,wp(t),this.activeEditor()});u(this,"clear",()=>{const t=ro();this.setDoc(t)});u(this,"readonly",()=>{const{editor:t}=this.components;t.readonly=!0});u(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",$1],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 yu(this.doc));r.readonly=!0,r.addListener("readonlyChanged",this.handleReadonlyChange),r.addListener("focus",this.handleEditorFocus),r.addListener("blur",this.handleEditorBlur);const i=Xo(this.root,"comment-editor-img",aA("comment.image"),aw,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 dA{constructor(t){u(this,"handleBeforeKeyDown",(t,e)=>{if(An(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 uA{constructor(t,e,o){u(this,"handleBeforeKeyDown",(t,e)=>{if(An(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 hA=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
554
554
|
<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>
|
|
555
555
|
</svg>`,fA=`<svg
|
|
556
556
|
fill="currentColor"
|
|
557
557
|
width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
558
558
|
<path fill-rule="evenodd" clip-rule="evenodd" d="M8.63999 19.5893C8.82172 19.5893 8.9891 19.5427 9.14214 19.4494C9.29518 19.3561 9.48169 19.2115 9.70168 19.0154L12.0403 16.9422H16.2512C16.9255 16.9422 17.497 16.8191 17.9657 16.5728C18.4343 16.3265 18.7906 15.969 19.0345 15.5003C19.2784 15.0317 19.4004 14.4626 19.4004 13.793V8.55629C19.4004 7.88675 19.2784 7.31765 19.0345 6.84897C18.7906 6.38029 18.4343 6.02161 17.9657 5.77293C17.497 5.52424 16.9255 5.3999 16.2512 5.3999H7.5496C6.88007 5.3999 6.31096 5.52305 5.84228 5.76934C5.37361 6.01564 5.01612 6.37432 4.76983 6.84538C4.52354 7.31645 4.40039 7.88675 4.40039 8.55629V13.793C4.40039 14.4626 4.52354 15.0329 4.76983 15.5039C5.01612 15.975 5.37241 16.3325 5.8387 16.5764C6.30498 16.8203 6.86811 16.9422 7.52808 16.9422H7.82937V18.6639C7.82937 18.9461 7.89991 19.1708 8.04099 19.3382C8.18207 19.5056 8.38174 19.5893 8.63999 19.5893ZM8.94845 18.1976V16.2536C8.94845 16.0623 8.90541 15.9248 8.81933 15.8411C8.73325 15.7574 8.59695 15.7155 8.41043 15.7155H7.5783C6.91832 15.7155 6.42932 15.5505 6.11129 15.2206C5.79326 14.8906 5.63425 14.4076 5.63425 13.7715V8.57781C5.63425 7.94175 5.79326 7.45992 6.11129 7.13233C6.42932 6.80473 6.91832 6.64094 7.5783 6.64094H16.2225C16.8825 6.64094 17.3715 6.80473 17.6895 7.13233C18.0075 7.45992 18.1665 7.94175 18.1665 8.57781V13.7715C18.1665 14.4076 18.0075 14.8906 17.6895 15.2206C17.3715 15.5505 16.8825 15.7155 16.2225 15.7155H11.9757C11.7749 15.7155 11.6146 15.7383 11.4951 15.7837C11.3755 15.8291 11.2464 15.9212 11.1077 16.0599L8.94845 18.1976ZM15.584 9.23419C15.5027 9.3131 15.4047 9.35256 15.2899 9.35256H8.42478C8.31479 9.35256 8.22033 9.3131 8.14142 9.23419C8.06251 9.15528 8.02306 9.05844 8.02306 8.94366C8.02306 8.83367 8.06251 8.73802 8.14142 8.65672C8.22033 8.57542 8.31479 8.53477 8.42478 8.53477H15.2899C15.4047 8.53477 15.5027 8.57542 15.584 8.65672C15.6653 8.73802 15.706 8.83367 15.706 8.94366C15.706 9.05844 15.6653 9.15528 15.584 9.23419ZM15.2899 11.5333C15.4047 11.5333 15.5027 11.4939 15.584 11.415C15.6653 11.3361 15.706 11.2392 15.706 11.1244C15.706 11.0097 15.6653 10.9116 15.584 10.8303C15.5027 10.749 15.4047 10.7084 15.2899 10.7084H8.42478C8.31479 10.7084 8.22033 10.749 8.14142 10.8303C8.06251 10.9116 8.02306 11.0097 8.02306 11.1244C8.02306 11.2392 8.06251 11.3361 8.14142 11.415C8.22033 11.4939 8.31479 11.5333 8.42478 11.5333H15.2899ZM13.1845 13.5957C13.1056 13.6747 13.0111 13.7141 12.9011 13.7141H8.42478C8.31479 13.7141 8.22033 13.6747 8.14142 13.5957C8.06251 13.5168 8.02306 13.4224 8.02306 13.3124C8.02306 13.1928 8.06251 13.0924 8.14142 13.0111C8.22033 12.9298 8.31479 12.8891 8.42478 12.8891H12.9011C13.0111 12.8891 13.1056 12.9298 13.1845 13.0111C13.2634 13.0924 13.3028 13.1928 13.3028 13.3124C13.3028 13.4224 13.2634 13.5168 13.1845 13.5957Z"></path>
|
|
559
|
-
</svg>`,PF="";y("comment-item");const{t:oi}=S,_6="comment-item-editing",N6="active";class P6{constructor(t){u(this,"root");u(this,"moreMenu");u(this,"components");u(this,"createRoot",()=>{const t=b("div",["comment-item-root"],null);return t.id=this.comment.id,t});u(this,"handleMore",()=>{const{moreButton:t}=this.components;!t||this.moreMenu.manualShow(t,{placement:"bottom-start"})});u(this,"handleMoreMenuItemShow",()=>{const{headTools:t}=this.components;t.classList.add(N6)});u(this,"handleMoreMenuItemClose",()=>{const{headTools:t}=this.components;t.classList.remove(N6)});u(this,"handleMoreMenuItemClick",(t,e)=>{const o=this.options.groupList.groupItemHandlers,{id:r}=e;r==="edit"&&o.handleCommentItemEdit(this),r==="delete"&&o.handleCommentItemDelete(this)});u(this,"handleEditorReadonlyChange",t=>{const{components:{actions:e},root:o}=this;t.readonly?(o.classList.remove(_6),e.classList.add("hidden")):(o.classList.add(_6),e.classList.remove("hidden"))});u(this,"handleFocus",()=>{const{components:{commentEditor:t,okButton:e}}=this;t.isEmpty()?M(e,Qn):F(e,Qn)});u(this,"handleDocChanged",()=>{const{commentEditor:t,okButton:e}=this.components;t.isEmpty()?M(e,Qn):F(e,Qn)});u(this,"getCommentEditor",()=>this.components.commentEditor);u(this,"handleReadonlyChanged",t=>{t.readonly?M(this.root,"readonly"):F(this.root,"readonly")});this.options=t,this.root=this.createRoot(),this.components=this.createItem(),this.moreMenu=this.createMoreMenu(),t.mainEditor.on("readonlyChanged",this.handleReadonlyChanged)}get commentOptions(){return this.options.mainEditor.getComponentOptions("comment")}get comment(){return this.options.comment}get doc(){const{comment:t,commentsProvider:e}=this.options;return e.getCommentDoc(t.id)}createMoreMenu(){const t=new Wo([{id:"edit",name:oi("comment.edit")},{id:"delete",name:oi("comment.delete")}]);return t.on("click",this.handleMoreMenuItemClick),t.on("close",this.handleMoreMenuItemClose),t.on("show",this.handleMoreMenuItemShow),t}createItem(){var P,V;const{comment:t,commentsProvider:e,mainEditor:o,groupItem:r}=this.options,i=!((P=this.commentOptions)!=null&&P.disableReply)&&!o.readonly,l=!((V=this.commentOptions)!=null&&V.disableEdit)&&!o.readonly&&i,c=b("div",["item-head"],this.root),a=b("img",["item-head-avatar"],c);a.src=t.avatarUrl;const h=b("span",["item-head-username"],c);h.innerText=t.displayName;const f=b("span",["item-head-modified"],c),m=new Date(t.modified);f.innerText=ed(m);const C=b("div",["item-head-tools"],c);let v=null;i&&(v=Xo(C,mt.CommentItemReply,oi("comment.reply"),fA,void 0,o.clientId),Kn(v,mt.CommentItemReply));let w=null;l&&(w=Xo(C,mt.CommentItemMore,oi("comment.more"),hA,void 0,o.clientId),Kn(w,mt.CommentItemMore),w.onclick=this.handleMore);const E=b("div",["item-editor"],this.root),
|
|
559
|
+
</svg>`,PF="";y("comment-item");const{t:oi}=S,_6="comment-item-editing",N6="active";class P6{constructor(t){u(this,"root");u(this,"moreMenu");u(this,"components");u(this,"createRoot",()=>{const t=b("div",["comment-item-root"],null);return t.id=this.comment.id,t});u(this,"handleMore",()=>{const{moreButton:t}=this.components;!t||this.moreMenu.manualShow(t,{placement:"bottom-start"})});u(this,"handleMoreMenuItemShow",()=>{const{headTools:t}=this.components;t.classList.add(N6)});u(this,"handleMoreMenuItemClose",()=>{const{headTools:t}=this.components;t.classList.remove(N6)});u(this,"handleMoreMenuItemClick",(t,e)=>{const o=this.options.groupList.groupItemHandlers,{id:r}=e;r==="edit"&&o.handleCommentItemEdit(this),r==="delete"&&o.handleCommentItemDelete(this)});u(this,"handleEditorReadonlyChange",t=>{const{components:{actions:e},root:o}=this;t.readonly?(o.classList.remove(_6),e.classList.add("hidden")):(o.classList.add(_6),e.classList.remove("hidden"))});u(this,"handleFocus",()=>{const{components:{commentEditor:t,okButton:e}}=this;t.isEmpty()?M(e,Qn):F(e,Qn)});u(this,"handleDocChanged",()=>{const{commentEditor:t,okButton:e}=this.components;t.isEmpty()?M(e,Qn):F(e,Qn)});u(this,"getCommentEditor",()=>this.components.commentEditor);u(this,"handleReadonlyChanged",t=>{t.readonly?M(this.root,"readonly"):F(this.root,"readonly")});this.options=t,this.root=this.createRoot(),this.components=this.createItem(),this.moreMenu=this.createMoreMenu(),t.mainEditor.on("readonlyChanged",this.handleReadonlyChanged)}get commentOptions(){return this.options.mainEditor.getComponentOptions("comment")}get comment(){return this.options.comment}get doc(){const{comment:t,commentsProvider:e}=this.options;return e.getCommentDoc(t.id)}createMoreMenu(){const t=new Wo([{id:"edit",name:oi("comment.edit")},{id:"delete",name:oi("comment.delete")}]);return t.on("click",this.handleMoreMenuItemClick),t.on("close",this.handleMoreMenuItemClose),t.on("show",this.handleMoreMenuItemShow),t}createItem(){var P,V;const{comment:t,commentsProvider:e,mainEditor:o,groupItem:r}=this.options,i=!((P=this.commentOptions)!=null&&P.disableReply)&&!o.readonly,l=!((V=this.commentOptions)!=null&&V.disableEdit)&&!o.readonly&&i,c=b("div",["item-head"],this.root),a=b("img",["item-head-avatar"],c);a.src=t.avatarUrl;const h=b("span",["item-head-username"],c);h.innerText=t.displayName;const f=b("span",["item-head-modified"],c),m=new Date(t.modified);f.innerText=ed(m);const C=b("div",["item-head-tools"],c);let v=null;i&&(v=Xo(C,mt.CommentItemReply,oi("comment.reply"),fA,void 0,o.clientId),Kn(v,mt.CommentItemReply));let w=null;l&&(w=Xo(C,mt.CommentItemMore,oi("comment.more"),hA,void 0,o.clientId),Kn(w,mt.CommentItemMore),w.onclick=this.handleMore);const E=b("div",["item-editor"],this.root),L=new j1(o,e,this.doc);L.editor.addListener("readonlyChanged",this.handleEditorReadonlyChange),L.editor.addListener("docChanged",this.handleDocChanged),L.editor.addListener("focus",this.handleFocus),L.editor.input.addHandler(new uA(e,r,this)),E.append(L.root);const x=b("div",["item-actions","hidden"],this.root),O=Vn(mt.CommentItemCancel,oi("common.cancel"));Kn(O,mt.CommentItemCancel);const A=Vn(mt.CommentItemOk,oi("comment.send"));return Kn(A,mt.CommentItemOk),x.append(O,A),{head:c,replyButton:v,moreButton:w,commentEditor:L,okButton:A,cancelButton:O,actions:x,headTools:C}}reloadDoc(){const{components:{commentEditor:t}}=this;t.setDoc(this.doc)}edit(){const{components:{commentEditor:t}}=this;t.edit()}destroy(){const{replyButton:t,moreButton:e,commentEditor:o,okButton:r,cancelButton:i}=this.components;e&&(e.onclick=null),t&&(t.onclick=null),r.onclick=null,i.onclick=null,o.destroy(),this.moreMenu.removeAllListeners(),this.moreMenu.destroy(),this.root.remove(),this.options.mainEditor.removeListener("readonlyChanged",this.handleReadonlyChanged)}}const $F="";class $6{constructor(t,e,o){u(this,"root");u(this,"components");u(this,"reloadDoc",()=>{const{mobileCommentEditor:t}=this.components;t.setDoc(this.doc)});this.editor=t,this.commentsProvider=e,this.comment=o,this.root=b("div",["mobile-comment-item"],null),this.components=this.createItem()}get doc(){const{comment:t,commentsProvider:e}=this;return e.getCommentDoc(t.id)}createItem(){const{comment:t,editor:e,commentsProvider:o}=this,r=b("div",["item-head"],this.root),i=b("img",["item-head-avatar"],r);i.src=t.avatarUrl;const s=b("span",["item-head-username"],r);s.innerText=t.displayName;const l=b("span",["item-head-modified"],r),c=new Date(t.modified);l.innerText=ed(c);const a=b("div",["item-editor"],this.root),h=new j1(e,o,this.doc);return a.append(h.root),{mobileCommentEditor:h}}destroy(){this.root.remove(),this.components.mobileCommentEditor.destroy()}}const jF="";class mA{constructor(t,e){u(this,"root");u(this,"countElement");u(this,"updateCount",t=>{this.countElement.textContent=`${t}`});this.root=b("div",["mini-comment-item"],e),this.root.id=t,this.countElement=b("span",["mini-comment-item-count"],this.root)}}class Rs extends Wt.TypedEmitter{constructor(e,o,r,i,s){super();u(this,"_items");this.editor=e,this.commentsProvider=o,this.container=r,this.options=s,this._items=this.createList(i)}get items(){return this._items}createList(e){return e.map(r=>{const i=this.createItem(r,"init");return this.container.appendChild(i.root),i})}reloadList(e){this.container.innerHTML="",this.createList(e)}insertItem(e){const o=this.findInsertPos(e);if(o===-1)return null;const r=this.createItem(e,"insert");if(o===this.items.length)this.container.appendChild(r.root);else{const i=this.items[o];this.container.insertBefore(r.root,i.root)}return this.items.splice(o,0,r),r}deleteItem(e){const o=this.findItemIndex(e);if(o!==-1){const r=this.items[o];return this.items.splice(o,1),r.destroy(),!0}return!1}findItemIndex(e){return this.items.findIndex(o=>o.comment.id===e)}findItem(e){const o=this.findItemIndex(e);return o===-1?null:this.items[o]}destroy(){this._items.forEach(e=>e.destroy()),this._items=[]}}class gA extends Rs{constructor(t){const{editor:e,comments:o,commentsProvider:r,parent:i}=t;super(e,r,i,o,t)}createItem(t){const{editor:e,commentsProvider:o,groupList:r,groupItem:i}=this.options;return new P6({mainEditor:e,commentsProvider:o,comment:t,groupList:r,groupItem:i})}findInsertPos(){return this.items.length}destroy(){this.items.forEach(t=>{t.destroy()})}}const pA=`<svg width="17" height="16" viewBox="0 0 17 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
560
560
|
<path d="M2.00218 11.0005L8.00341 4.99923L14.0046 11.0005" stroke="currentColor" fill="transparent" stroke-width="1.5" stroke-linejoin="bevel"/>
|
|
561
561
|
</svg>`,CA=`<svg width="17" height="16" viewBox="0 0 17 16" xmlns="http://www.w3.org/2000/svg">
|
|
562
562
|
<path d="M14.0029 4.99933L8.00172 11.0006L2.00049 4.99933" stroke="currentColor" fill="transparent" stroke-width="1.5" stroke-linejoin="bevel"/>
|
|
@@ -656,6 +656,6 @@ width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
|
|
656
656
|
<rect width="6" height="7" fill="white" transform="translate(6 6)"/>
|
|
657
657
|
</clipPath>
|
|
658
658
|
</defs>
|
|
659
|
-
</svg>`,t3={dwg:[],rvt:[],skp:[],img:["image/png","image/jpg","image/jpeg","image/bmp","image/ico","image/icon","image/gif"],txt:["text/plain"],zip:["application/zip","application/x-rar-compressed","application/x-7z-compressed","application/x-tar","application/x-bzip2","application/java-archive"],ppt:["application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation"],excel:["application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],pdf:["application/pdf"],word:["application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document"]},V1={dwg:u_,rvt:h_,skp:f_,img:m_,txt:g_,zip:X6,rar:X6,ppt:p_,excel:C_,pdf:b_,word:v_};function y_(n,t){const e=Object.keys(t3);for(let r=0;r<e.length;r+=1){const i=e[r];if(t3[i].includes(t))return V1[i]}const o=am(n.toLowerCase());return V1[o]?V1[o]:k_}function w_(n,t){const e=b("div",["card-root","embed-selected-content"],n),o=b("div",["file-icon"],e);o.innerHTML=y_(t.fileName,t.fileType);const r=b("div",["file-details"],e);b("div",["file-name"],r,t.fileName),b("div",["file-size"],r,mm(t.fileSize));const i=b("div",["file-actions"],e),s=b("button",["download"],i);return s.innerHTML=U1,{card:e,downloadButton:s}}const UF="";function e3(n,t){const o=n.getBlockData(t).embedData,r=n.options.componentsOptions.file;if(r!=null&&r.onDownloadFile){r.onDownloadFile(n,o);return}const i=n.doc.buildResourceUrl(o.src,{downloadFileName:o.fileName});ll(i,o.fileName)}y("webpage-embed");function B_(n,t,e){const{embedData:o}=e,r=o,{card:i,downloadButton:s}=w_(t,r);n.domEvents.addEventListener(s,"click",(l,c)=>{if(!c.target)return;const a=z(c.target);!a||e3(l,a)}),n.domEvents.addEventListener(i,"click",(l,c)=>{if(!c.target)return;const a=z(c.target);if(!a||wi(c,"button"))return;const h=l.options.componentsOptions.file;if(h!=null&&h.onClick){h.onClick(l,a,c);return}const m=l.getBlockData(a).embedData,C=l.doc.buildResourceUrl(m.src,{downloadFileName:m.fileName});ll(C,m.fileName)})}class E_{constructor(){u(this,"group","file-card");u(this,"commands",[{id:"download",name:"Download",icon:U1},{id:"sep",name:"",type:"separator"},{id:"to-link",name:"To link",icon:Y6},{id:"to-card",name:"To card",icon:Q6,states:["checked"]},{id:"sep",name:"",type:"separator"},{id:"add-comment",name:"Add Comment",icon:ns}])}executeCommand(t,e,o){if(o.id==="to-link"){const r=j(e),i=U(r),s=K(e),l=t.getBlockData(e),{embedData:c}=l,a=c,h={id:N(),box:!0,type:"file",created:Date.now(),src:a.src,fileName:a.fileName,fileSize:a.fileSize,fileType:a.fileType};t.undoManager.runInGroup(()=>{t.deleteBlock(e);const f=[wg(h)];t.insertTextBlock(f,i,s)})}else o.id==="download"?e3(t,e):o.id==="add-comment"&&e1(t,e)}}function I_(n,t){const e=n.getBlockData(t),{embedData:o,id:r}=e,i=o;return{blockCommands:{"hovering-toolbar":new E_},abstract:i.fileName}}const x_={embedType:"office",createEmbedContent:B_,getBlockProperties:I_},VF="",S_={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"}}},T_={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"}}};S.mergeLang({"zh-CN":S_,"en-US":T_});var dn=(n=>(n.AUDIO="audio",n.VIDEO="video",n))(dn||{}),Os=(n=>(n.Empty="empty",n.Progress="progress",n.Error="error",n))(Os||{});const n3=10*1024*1024,D_=["wav","mp3","aac","ogg","webm","flac"],L_=["ogg","mp4","webm"],M_=()=>{};function o3(n){var h,f,m,C,v,w;const t=(h=n.getComponentOptions("media"))!=null?h:{},{allowedMedias:e,maxSize:o,callbacks:r}=t,i=(f=e==null?void 0:e.audio)!=null?f:D_,s=(m=e==null?void 0:e.video)!=null?m:L_,l=(C=o==null?void 0:o.audio)!=null?C:n3,c=(v=o==null?void 0:o.video)!=null?v:n3,a=(w=r==null?void 0:r.onError)!=null?w:M_;return{allowedMedias:{audio:i,video:s},maxSize:{audio:l,video:c},callbacks:{onError:a}}}const R_=y("file-utils");function O_(n){d(R_,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 r3(n,t){const e=i=>i.map(s=>`.${s}`).join(","),{allowedMedias:o}=o3(n),r=o[t];return r?e(r):"*"}function A_(n,t,e){const{maxSize:o,callbacks:r,allowedMedias:i}=o3(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=O_(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 __(n){return n===Os.Empty||n===Os.Error}const ue=y("media");class N_{constructor(t){u(this,"mediaContainer",null);u(this,"media",null);u(this,"abstract",null);u(this,"handleMediaLoadError",(t,e)=>{if(!e.target||!(e.target instanceof Node)||!(e.target instanceof Element?e.target:e.target.parentElement))return;const r=z(e.target);if(!r||!r.contains(this.mediaContainer))return;const i=this.renderError();this.updateMediaContent(i)});u(this,"handleRetry",async t=>{if(t.readonly)return;d(ue,this.abstract,"no abstract");const{mediaType:e}=this.abstract,o=r3(t,e),r=await Lo(o);this.handleUploadFile(r)});u(this,"handleUploadFile",async t=>{d(ue,this.abstract,"no abstract"),d(ue,this.mediaContainer,"The media element not exist");const{editor:e}=this.options,{mediaType:o}=this.abstract,r=z(this.mediaContainer);d(ue,r,"The block element not exist");const i=e.getBlockData(r);if(!!A_(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,h={...i,embedData:{...i.embedData,src:s,fileName:l,fileSize:a,fileType:c}};e.updateBlockData(r,h)}catch{this.renderRetry()}});u(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(ue,this.mediaContainer,"The media element not exist"),this.mediaContainer.innerHTML="",this.mediaContainer.append(t)}renderError(){d(ue,this.abstract,"no abstract");const{editor:t,createMediaElement:e}=this.options,{mediaIcon:o,mediaName:r}=this.abstract;d(ue,this.mediaContainer,"The media element not exist");const i=z(this.mediaContainer);d(ue,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 h=b("div",[],c);h.innerHTML=S.t("media.load.failed",{name:r}),c.appendChild(h);const f=h.querySelector("a");return d(ue,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),w=this.getResourceUrl(l),E=e(m,v,s,w);this.unbindMediaEvent(),this.media=E,this.bindMediaEvent(),this.updateMediaContent(v)}}),c}renderRetry(){d(ue,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=S.t("media.upload.failed",{name:o}),r.appendChild(s);const l=s.querySelector("a");d(ue,l,"The element not exist"),t.domEvents.addEventListener(l,"click",this.handleRetry),this.updateMediaContent(r)}renderProgress(t,e){d(ue,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(ue,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(ue,this.abstract,"no abstract"),d(ue,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)),__(o)?o===Os.Empty&&this.renderEmpty():this.renderMediaElement(t)}setAbstract(t){this.abstract=t}}y("media-embed");class i3{constructor(){u(this,"handleInsertEmptyEmbed",async(t,e)=>{var h;const{containerId:o,blockIndex:r}=e;let i;(h=e.data)!=null&&h.file&&(i=e.data.file);const s=r3(t,this.embedType);if(i=i!=null?i:await Lo(s,{}),!i)return null;const l={id:N(),type:"embed",embedType:this.embedType,embedData:{src:Os.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}],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=rt(e);return i.render(o,s),!0}handleDeleteBlock(t,e){const o=e.id;this.getMedia(t,o).destroy()}}function s3(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 l3(n,t){const e=n.querySelector(".uploading-progress-bar-value");e&&(e.style.width=`${t}%`)}const P_=y("media-audio");class $_ extends i3{constructor(){super(...arguments);u(this,"embedType",dn.AUDIO);u(this,"abstract",{mediaIcon:Iw,mediaName:S.t(`media.${dn.AUDIO}.menuItem`),menuItem:S.t(`media.${dn.AUDIO}.menuItem`),order:800,mediaType:dn.AUDIO,group:"common"});u(this,"updateProgressElement",l3)}getBlockProperties(){return{abstract:`[${S.t(`media.${dn.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(P_,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",s3(e,o)}}const q1=new $_;y("video-resizer");function c3(n){return n&&De(n)&&Le(n)==="video"}const j_=50;class H_{constructor(t){u(this,"currentResizableElement",null);u(this,"resizing",!1);u(this,"handleHoveringBlockChange",(t,e)=>{if(!this.resizing&&(e&&c3(e)&&this.disableBlockResize(e),t&&c3(t))){const o=this.getVideoElement(t);if(!o)return;this.enableBlockResize(t,o)}});u(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,j_),r);this.currentResizableElement.style.width=`${i}px`});u(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,_t.get(t).addListener("change",this.handleHoveringBlockChange)}destroy(){this.currentResizableElement=null,_t.get(this.editor).removeListener("change",this.handleHoveringBlockChange)}getVideoElement(t){return rt(t).querySelector(":scope .video-container > video")}disableBlockResize(t){const e=this.editor.findCustom(`${G(t)}-resizer`);e&&e.disableResize()}enableBlockResize(t,e){const o=this.editor.addCustom(`${G(t)}-resizer`,()=>new Pc(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 F_=y("video");class z_ extends i3{constructor(){super(...arguments);u(this,"embedType",dn.VIDEO);u(this,"abstract",{mediaName:S.t(`media.${dn.VIDEO}.menuItem`),mediaIcon:xw,menuItem:S.t(`media.${dn.VIDEO}.menuItem`),order:700,mediaType:dn.VIDEO,group:"common"});u(this,"updateProgressElement",l3);u(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,s3(e,o),nl(r).then(s=>{const l=e.querySelector(".progress-video");l&&ld(e)&&(l.src=s)})})}getBlockProperties(){return{abstract:`[${S.t(`media.${dn.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 H_(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(F_,s,"The media element not exist"),s.src!==i&&(s.src=i),s}}const W1=new z_,qF="",U_={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"}},V_={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."}};S.mergeLang({"zh-CN":U_,"en-US":V_});var a3=(n=>(n.NEW="history-new",n.NEW_CHILD="history-new-child",n.DELETED="history-deleted",n.UPDATED="history-updated",n.HISTORY="history",n))(a3||{});const ri="--op-color",ii="--op-selected-color",WF="";class q_{constructor(t){u(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:si}=S,d3=y("version-list");class W_{constructor(t){u(this,"activeVersionElement");u(this,"versionsList");u(this,"versionsListHeader");u(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=si("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];M(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(d3,this.activeVersionElement,"No active version element"),this.activeVersionElement.nextElementSibling?this.activeVersionElement.nextElementSibling.versionData:null}get beforeMajorVersion(){d(d3,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=si("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&&M(a,"child");const h=b("div",["dialog-version-list-item-title"],a);if(b("div",["dialog-version-list-item-date"],h,o(i)),c&&b("div",["dialog-version-list-item-now-ver"],h,si("version.latest")),typeof i.source=="object"&&((C=i.source)==null?void 0:C.restore)){const v=i.source.restore,w=l.find(O=>O.version==v),E=w?o(w):si("version.unknown"),D=si("version.restoreFrom",{from:E}),x=si("version.restoreInfo"),A=b("div",["dialog-version-item-from-container"],a);b("div",["dialog-version-item-from-main"],A,D),b("div",["dialog-version-item-from-info"],A,x)}const f=b("ul",["dialog-version-list-item-authors"],a),m=v=>{const w=b("li",["dialog-version-list-item-author"],f),E=b("span",["dialog-version-list-item-mark-author"],w);E.style.background=this.options.getMarkColor(v),b("span",["dialog-version-list-item-author-name"],w,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?lt(t,"dialog-version-list-item"):!1}getVersionFromElement(t){return t.versionData}get activeVersion(){return this.getVersionFromElement(this.activeVersionElement)}toggleActiveVersionElement(t){this.activeVersionElement!==t&&(F(this.activeVersionElement,"active"),M(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 G_{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 Z_(n){return new Promise(t=>{setTimeout(t,n)})}async function Y_(n,t,e,o){for(const r of e){const i=new G_(n,r.user);t.parseHistoryData(r,i),o.play&&await Z_(o.speed||150)}}const Q_=`<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
|
|
659
|
+
</svg>`,t3={dwg:[],rvt:[],skp:[],img:["image/png","image/jpg","image/jpeg","image/bmp","image/ico","image/icon","image/gif"],txt:["text/plain"],zip:["application/zip","application/x-rar-compressed","application/x-7z-compressed","application/x-tar","application/x-bzip2","application/java-archive"],ppt:["application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation"],excel:["application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],pdf:["application/pdf"],word:["application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document"]},V1={dwg:u_,rvt:h_,skp:f_,img:m_,txt:g_,zip:X6,rar:X6,ppt:p_,excel:C_,pdf:b_,word:v_};function y_(n,t){const e=Object.keys(t3);for(let r=0;r<e.length;r+=1){const i=e[r];if(t3[i].includes(t))return V1[i]}const o=am(n.toLowerCase());return V1[o]?V1[o]:k_}function w_(n,t){const e=b("div",["card-root","embed-selected-content"],n),o=b("div",["file-icon"],e);o.innerHTML=y_(t.fileName,t.fileType);const r=b("div",["file-details"],e);b("div",["file-name"],r,t.fileName),b("div",["file-size"],r,mm(t.fileSize));const i=b("div",["file-actions"],e),s=b("button",["download"],i);return s.innerHTML=U1,{card:e,downloadButton:s}}const UF="";function e3(n,t){const o=n.getBlockData(t).embedData,r=n.options.componentsOptions.file;if(r!=null&&r.onDownloadFile){r.onDownloadFile(n,o);return}const i=n.doc.buildResourceUrl(o.src,{downloadFileName:o.fileName});ll(i,o.fileName)}y("webpage-embed");function B_(n,t,e){const{embedData:o}=e,r=o,{card:i,downloadButton:s}=w_(t,r);n.domEvents.addEventListener(s,"click",(l,c)=>{if(!c.target)return;const a=z(c.target);!a||e3(l,a)}),n.domEvents.addEventListener(i,"click",(l,c)=>{if(!c.target)return;const a=z(c.target);if(!a||wi(c,"button"))return;const h=l.options.componentsOptions.file;if(h!=null&&h.onClick){h.onClick(l,a,c);return}const m=l.getBlockData(a).embedData,C=l.doc.buildResourceUrl(m.src,{downloadFileName:m.fileName});ll(C,m.fileName)})}class E_{constructor(){u(this,"group","file-card");u(this,"commands",[{id:"download",name:"Download",icon:U1},{id:"sep",name:"",type:"separator"},{id:"to-link",name:"To link",icon:Y6},{id:"to-card",name:"To card",icon:Q6,states:["checked"]},{id:"sep",name:"",type:"separator"},{id:"add-comment",name:"Add Comment",icon:ns}])}executeCommand(t,e,o){if(o.id==="to-link"){const r=j(e),i=U(r),s=K(e),l=t.getBlockData(e),{embedData:c}=l,a=c,h={id:N(),box:!0,type:"file",created:Date.now(),src:a.src,fileName:a.fileName,fileSize:a.fileSize,fileType:a.fileType};t.undoManager.runInGroup(()=>{t.deleteBlock(e);const f=[wg(h)];t.insertTextBlock(f,i,s)})}else o.id==="download"?e3(t,e):o.id==="add-comment"&&e1(t,e)}}function I_(n,t){const e=n.getBlockData(t),{embedData:o,id:r}=e,i=o;return{blockCommands:{"hovering-toolbar":new E_},abstract:i.fileName}}const x_={embedType:"office",createEmbedContent:B_,getBlockProperties:I_},VF="",S_={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"}}},T_={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"}}};S.mergeLang({"zh-CN":S_,"en-US":T_});var dn=(n=>(n.AUDIO="audio",n.VIDEO="video",n))(dn||{}),Os=(n=>(n.Empty="empty",n.Progress="progress",n.Error="error",n))(Os||{});const n3=10*1024*1024,D_=["wav","mp3","aac","ogg","webm","flac"],L_=["ogg","mp4","webm"],M_=()=>{};function o3(n){var h,f,m,C,v,w;const t=(h=n.getComponentOptions("media"))!=null?h:{},{allowedMedias:e,maxSize:o,callbacks:r}=t,i=(f=e==null?void 0:e.audio)!=null?f:D_,s=(m=e==null?void 0:e.video)!=null?m:L_,l=(C=o==null?void 0:o.audio)!=null?C:n3,c=(v=o==null?void 0:o.video)!=null?v:n3,a=(w=r==null?void 0:r.onError)!=null?w:M_;return{allowedMedias:{audio:i,video:s},maxSize:{audio:l,video:c},callbacks:{onError:a}}}const R_=y("file-utils");function O_(n){d(R_,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 r3(n,t){const e=i=>i.map(s=>`.${s}`).join(","),{allowedMedias:o}=o3(n),r=o[t];return r?e(r):"*"}function A_(n,t,e){const{maxSize:o,callbacks:r,allowedMedias:i}=o3(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=O_(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 __(n){return n===Os.Empty||n===Os.Error}const ue=y("media");class N_{constructor(t){u(this,"mediaContainer",null);u(this,"media",null);u(this,"abstract",null);u(this,"handleMediaLoadError",(t,e)=>{if(!e.target||!(e.target instanceof Node)||!(e.target instanceof Element?e.target:e.target.parentElement))return;const r=z(e.target);if(!r||!r.contains(this.mediaContainer))return;const i=this.renderError();this.updateMediaContent(i)});u(this,"handleRetry",async t=>{if(t.readonly)return;d(ue,this.abstract,"no abstract");const{mediaType:e}=this.abstract,o=r3(t,e),r=await Lo(o);this.handleUploadFile(r)});u(this,"handleUploadFile",async t=>{d(ue,this.abstract,"no abstract"),d(ue,this.mediaContainer,"The media element not exist");const{editor:e}=this.options,{mediaType:o}=this.abstract,r=z(this.mediaContainer);d(ue,r,"The block element not exist");const i=e.getBlockData(r);if(!!A_(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,h={...i,embedData:{...i.embedData,src:s,fileName:l,fileSize:a,fileType:c}};e.updateBlockData(r,h)}catch{this.renderRetry()}});u(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(ue,this.mediaContainer,"The media element not exist"),this.mediaContainer.innerHTML="",this.mediaContainer.append(t)}renderError(){d(ue,this.abstract,"no abstract");const{editor:t,createMediaElement:e}=this.options,{mediaIcon:o,mediaName:r}=this.abstract;d(ue,this.mediaContainer,"The media element not exist");const i=z(this.mediaContainer);d(ue,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 h=b("div",[],c);h.innerHTML=S.t("media.load.failed",{name:r}),c.appendChild(h);const f=h.querySelector("a");return d(ue,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),w=this.getResourceUrl(l),E=e(m,v,s,w);this.unbindMediaEvent(),this.media=E,this.bindMediaEvent(),this.updateMediaContent(v)}}),c}renderRetry(){d(ue,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=S.t("media.upload.failed",{name:o}),r.appendChild(s);const l=s.querySelector("a");d(ue,l,"The element not exist"),t.domEvents.addEventListener(l,"click",this.handleRetry),this.updateMediaContent(r)}renderProgress(t,e){d(ue,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(ue,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(ue,this.abstract,"no abstract"),d(ue,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)),__(o)?o===Os.Empty&&this.renderEmpty():this.renderMediaElement(t)}setAbstract(t){this.abstract=t}}y("media-embed");class i3{constructor(){u(this,"handleInsertEmptyEmbed",async(t,e)=>{var h;const{containerId:o,blockIndex:r}=e;let i;(h=e.data)!=null&&h.file&&(i=e.data.file);const s=r3(t,this.embedType);if(i=i!=null?i:await Lo(s,{}),!i)return null;const l={id:N(),type:"embed",embedType:this.embedType,embedData:{src:Os.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}],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=rt(e);return i.render(o,s),!0}handleDeleteBlock(t,e){const o=e.id;this.getMedia(t,o).destroy()}}function s3(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 l3(n,t){const e=n.querySelector(".uploading-progress-bar-value");e&&(e.style.width=`${t}%`)}const P_=y("media-audio");class $_ extends i3{constructor(){super(...arguments);u(this,"embedType",dn.AUDIO);u(this,"abstract",{mediaIcon:Iw,mediaName:S.t(`media.${dn.AUDIO}.menuItem`),menuItem:S.t(`media.${dn.AUDIO}.menuItem`),order:800,mediaType:dn.AUDIO,group:"common"});u(this,"updateProgressElement",l3)}getBlockProperties(){return{abstract:`[${S.t(`media.${dn.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(P_,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",s3(e,o)}}const q1=new $_;y("video-resizer");function c3(n){return n&&De(n)&&Le(n)==="video"}const j_=50;class H_{constructor(t){u(this,"currentResizableElement",null);u(this,"resizing",!1);u(this,"handleHoveringBlockChange",(t,e)=>{if(!this.resizing&&(e&&c3(e)&&this.disableBlockResize(e),t&&c3(t))){const o=this.getVideoElement(t);if(!o)return;this.enableBlockResize(t,o)}});u(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,j_),r);this.currentResizableElement.style.width=`${i}px`});u(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,_t.get(t).addListener("change",this.handleHoveringBlockChange)}destroy(){this.currentResizableElement=null,_t.get(this.editor).removeListener("change",this.handleHoveringBlockChange)}getVideoElement(t){return rt(t).querySelector(":scope .video-container > video")}disableBlockResize(t){const e=this.editor.findCustom(`${G(t)}-resizer`);e&&e.disableResize()}enableBlockResize(t,e){const o=this.editor.addCustom(`${G(t)}-resizer`,()=>new Pc(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 F_=y("video");class z_ extends i3{constructor(){super(...arguments);u(this,"embedType",dn.VIDEO);u(this,"abstract",{mediaName:S.t(`media.${dn.VIDEO}.menuItem`),mediaIcon:xw,menuItem:S.t(`media.${dn.VIDEO}.menuItem`),order:700,mediaType:dn.VIDEO,group:"common"});u(this,"updateProgressElement",l3);u(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,s3(e,o),nl(r).then(s=>{const l=e.querySelector(".progress-video");l&&ld(e)&&(l.src=s)})})}getBlockProperties(){return{abstract:`[${S.t(`media.${dn.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 H_(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(F_,s,"The media element not exist"),s.src!==i&&(s.src=i),s}}const W1=new z_,qF="",U_={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"}},V_={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."}};S.mergeLang({"zh-CN":U_,"en-US":V_});var a3=(n=>(n.NEW="history-new",n.NEW_CHILD="history-new-child",n.DELETED="history-deleted",n.UPDATED="history-updated",n.HISTORY="history",n))(a3||{});const ri="--op-color",ii="--op-selected-color",WF="";class q_{constructor(t){u(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:si}=S,d3=y("version-list");class W_{constructor(t){u(this,"activeVersionElement");u(this,"versionsList");u(this,"versionsListHeader");u(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=si("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];M(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(d3,this.activeVersionElement,"No active version element"),this.activeVersionElement.nextElementSibling?this.activeVersionElement.nextElementSibling.versionData:null}get beforeMajorVersion(){d(d3,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=si("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&&M(a,"child");const h=b("div",["dialog-version-list-item-title"],a);if(b("div",["dialog-version-list-item-date"],h,o(i)),c&&b("div",["dialog-version-list-item-now-ver"],h,si("version.latest")),typeof i.source=="object"&&((C=i.source)==null?void 0:C.restore)){const v=i.source.restore,w=l.find(A=>A.version==v),E=w?o(w):si("version.unknown"),L=si("version.restoreFrom",{from:E}),x=si("version.restoreInfo"),O=b("div",["dialog-version-item-from-container"],a);b("div",["dialog-version-item-from-main"],O,L),b("div",["dialog-version-item-from-info"],O,x)}const f=b("ul",["dialog-version-list-item-authors"],a),m=v=>{const w=b("li",["dialog-version-list-item-author"],f),E=b("span",["dialog-version-list-item-mark-author"],w);E.style.background=this.options.getMarkColor(v),b("span",["dialog-version-list-item-author-name"],w,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?lt(t,"dialog-version-list-item"):!1}getVersionFromElement(t){return t.versionData}get activeVersion(){return this.getVersionFromElement(this.activeVersionElement)}toggleActiveVersionElement(t){this.activeVersionElement!==t&&(F(this.activeVersionElement,"active"),M(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 G_{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 Z_(n){return new Promise(t=>{setTimeout(t,n)})}async function Y_(n,t,e,o){for(const r of e){const i=new G_(n,r.user);t.parseHistoryData(r,i),o.play&&await Z_(o.speed||150)}}const Q_=`<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
|
|
660
660
|
<path d="M0 0h24v24H0z" fill="none"/><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
|
|
661
|
-
</svg>`,{t:G1}=S;class K_{constructor(t){u(this,"goBackButton");u(this,"playButton");u(this,"revertButton");this.options=t;const e=b("button",["dialog-text-button"],null),o=b("span",["dialog-button-icon"],e);o.innerHTML=Q_,b("span",["dialog-button-text"],e,G1("version.goBack"));const r=b("button",["dialog-version-button"],null,G1("version.play")),i=b("button",["dialog-version-button"],null,G1("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 he=y("split-text-actions");function u3(n){return n.length>2?!1:n.length===1?n[0].insert!==void 0:(d(he,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].insert!==void 0)}function h3(n){return n.length>2?!1:n.length===1?n[0].delete!==void 0:(d(he,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].delete!==void 0)}function f3(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(he,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].attributes!==void 0)}function J_(n){const t=[],e=Y.default(n);if(e.length===0)return[];if(e.length===1)return[n];if(e.length===2&&(h3(n)||u3(n)||f3(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(he,i.retain>0,`invalid text op: ${JSON.stringify(i)}`),d(he,e.length>1,`invalid text op: ${JSON.stringify(i)}`);const s=e[1];d(he,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(he,s.attributes!==void 0,`invalid next text op: ${JSON.stringify(s)}`),d(he,s.retain!==void 0,`invalid next text op: ${JSON.stringify(s)}`),r+=s.retain),e.splice(0,2)}else d(he,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(he,i.attributes!==void 0,`invalid next text op: ${JSON.stringify(i)}`),r+=i.retain),i.insert&&(r+=i.insert.length)}return t}function m3(n){if(d(he,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(he,typeof t=="number"&&t>0,`invalid retain: ${JSON.stringify(n)}`),t}let g3=0;function X_(n,t,e){const o=g3;g3+=1;const r=wt(n);return{insert:" ",attributes:{box:!0,id:N(),type:"history-deleted-box",user:e,created:Date.now(),text:r,deletedOffset:t,deletedOrder:o}}}function tN(n,t,e){const o=m3(t),r=t.length===1?t[0].delete:t[1].delete;d(he,typeof r=="number",`not a delete op: ${JSON.stringify(t)}`);const{left:i,middle:s,right:l}=Jt(n,o,r),c=X_(s,o,e);return[...i,c,...l]}function eN(n,t,e){const o=m3(t),r=t.length===1?t[0].insert:t[1].insert;d(he,typeof r=="string",`invalid insert op: ${JSON.stringify(t)}`);const i=t.length===1?t[0].attributes:t[1].attributes,l=yl([{insert:r,attributes:i}],"insertedBy",e);return Ir(n,o,l,null)}function nN(n,t,e){const o=J_(t).reverse();let r=n;for(const i of o)h3(i)?r=tN(r,i,e):u3(i)?r=eN(r,i,e):(d(he,f3(i),`unknown op: ${JSON.stringify(i)}`),r=oe.apply(r,i));return r}const oN=y("history-update-block-text");function p3(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+=Md(r)}),t.sort((r,i)=>i.offset-r.offset),{deletedBoxes:t,newText:e}}function rN(n,t,e){let o=n;return t.forEach(r=>{const i=oe.transformCursor(r.offset,e,!1);o=Ir(o,i,[{insert:" ",attributes:r.boxData}],null)}),o}function iN(n){n.sort((t,e)=>t.boxData.deletedOffset!==e.boxData.deletedOffset?t.boxData.deletedOffset-e.boxData.deletedOffset:t.boxData.deletedOrder-e.boxData.deletedOrder)}function sN(n){if(n.length<=1)return n;const t=n[0].offset;n.forEach(e=>{d(oN,e.offset===t,`invalid boxes group, ${JSON.stringify(n)}`)}),iN(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 lN(n){let{newText:t,deletedBoxes:e}=p3(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;sN(i).reverse().forEach(l=>{t=Ir(t,s,[{insert:" ",attributes:l.boxData}],null)})}),t}function cN(n,t,e){let{newText:o,deletedBoxes:r}=p3(n);return o=nN(o,t,e),o=rN(o,r,t),o=lN(o),o}const Sn=y("history-doc");function Tn(n){d(Sn,!1,"no local actions for history doc")}class aN extends vi{constructor(e,o){super();u(this,"doc");u(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(Sn,r,`no container data: ${e}`);const i=r[o];return d(Sn,i,`no block data: ${o}`),i}localUpdateBlockText(){Tn()}localUpdateBlockData(){Tn()}localInsertBlock(){Tn()}localDeleteBlock(){Tn()}localInsertChildContainer(){Tn()}localDeleteChildContainers(){Tn()}uploadResource(){Tn()}async addResources(e){Tn()}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(){Tn()}broadcastMessage(){Tn()}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new Wl}destroy(){this.clearCallbacks()}transformBlockIndex(e,o,r){const i=this.doc.blocks[e];d(Sn,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(Sn,!1,`invalid block index: ${o}, blocks: ${JSON.stringify(i)}`),d(Sn,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(Sn,!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 h;return(h=a.onInsertBlock)==null?void 0:h.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(Sn,!c.deleted,`block has already deleted: ${e}/${o}`);const a=c.text;d(Sn,a,`no text for block: ${JSON.stringify(c)}`);const h=cN(a,r,i);c.text=h,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(Sn,!c.deleted,`block has already deleted: ${e}/${o}`);const a=Y.default(c);a.updatedBy=i,r.delete.forEach(h=>delete a[h]),Object.entries(r.insert).forEach(([h,f])=>{a[h]=f}),l[s]=a,this.callbacks.forEach(h=>{var f;return(f=h.onUpdateBlockData)==null?void 0:f.call(h,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:C3}=S;function li(n,t){return t==="insert"?C3("version.insert",{name:n.displayName}):C3("version.delete",{name:n.displayName})}function ir(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 dN{renderText(t,e,o){if(!o.box&&o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=ir(t,o.insertedBy);return{classes:["history-inserted-text"],attributes:{"history-inserted-by":r.displayName,"data-op-description":li(r,"insert")},styles:{[ri]:i,[ii]:s}}}return{}}renderBlock(t,e,o){if(o.deletedBy){const r=o.deletedBy,{flag:i,selection:s}=ir(t,r);return{classes:["history-deleted-block"],attributes:{"history-deleted-by":r.displayName,"data-op-description":li(r,"delete")},styles:{[ri]:i,[ii]:s}}}if(o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=ir(t,r);return{classes:["history-inserted-block"],attributes:{"history-inserted-by":r.displayName,"data-op-description":li(r,"insert")},styles:{[ri]:i,[ii]:s}}}return{}}updateBlock(t,e,o,r){if(r.deletedBy){const i=r.deletedBy,{flag:s,selection:l}=ir(t,i);M(o,"history-deleted-block"),Ua(o,{"history-inserted-by":i.displayName,"data-op-description":li(i,"delete")}),Va(o,{[ri]:s,[ii]:l});return}if(r.insertedBy){const i=r.insertedBy,{flag:s,selection:l}=ir(t,i);M(o,"history-inserted-block"),Ua(o,{"history-inserted-by":i.displayName,"data-op-description":li(i,"insert")}),Va(o,{[ri]:s,[ii]:l})}}}const b3=y("history-deleted-box");function uN(n,t,e,o){const r=o;d(b3,r.text,`no text for text box data: ${JSON.stringify(o)}`),d(b3,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}=ir(n,s);i.setAttribute("history-deleted-by",s.displayName),i.setAttribute("data-op-description",li(s,"delete")),i.style.setProperty(ri,l),i.style.setProperty(ii,c)}const hN={boxType:"history-deleted-box",updateBoxContent:uN},ve=y("version-dialog");class fN{constructor(t,e){u(this,"editor");u(this,"dialog",null);u(this,"oldViewer",null);u(this,"versionOptions");u(this,"versionList",null);u(this,"actionButtons",null);u(this,"provider");u(this,"components");u(this,"handleClose",()=>{var t;(t=this.dialog)==null||t.hide()});u(this,"handlePlay",()=>{var e;d(ve,this.versionList,"The versionList did not render");const t=(e=this.versionList)==null?void 0:e.activeVersion;d(ve,t,`The version: ${t} is invalid`),this.viewVersion(t,{play:!0,speed:150})});u(this,"handleRevert",async()=>{var e,o;d(ve,this.versionList,"The versionList did not render");const t=(e=this.versionList)==null?void 0:e.activeVersion;d(ve,t,`The version: ${t} is invalid`),await this.versionHelper.revertVersion(t.version),(o=this.dialog)==null||o.hide()});u(this,"handleSelectVersion",t=>{d(ve,t,`The version: ${t} is invalid`),this.viewVersion(t)});u(this,"viewVersion",async(t,e={play:!1,speed:1e3})=>{var C,v,w;this.oldViewer&&(this.oldViewer.destroy(),this.oldViewer=null),d(ve,this.versionList,"The versionList did not render"),d(ve,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 E=this.versionOptions.onWillChangeVersion(this.editor,t,i,s);E!=null&&E.hideOps&&(l=!0)}let c,a;if(l)c=await this.versionHelper.getVersion(t.version),a=[];else{const E=await this.versionHelper.getHistoryData(t.version,r);c=E.doc,a=E.historyData}const{editorElement:h}=this.components;h.innerHTML="";const f=new aN(c,this.editor),m=this.provider.createHistoryEditor(h,f);m.editorBlockRenders.registerRender(new dN),m.editorBoxes.registerBoxClass(hN),M(m.rootElement,a3.HISTORY);try{await Y_(f,this.versionHelper,a,e)}finally{this.oldViewer=m}(w=this.versionOptions)!=null&&w.onVersionChanged&&this.versionOptions.onVersionChanged(this.editor,m,t,i,s)});u(this,"setShowOps",t=>{var e;if(this.versionOptions){this.versionOptions.hideOps=!t;const o=(e=this.versionList)==null?void 0:e.activeVersion;d(ve,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(ve,this.editor.doc.getVersionHelper,"Can not get getVersionHelper from doc");const t=this.editor.doc.getVersionHelper();return d(ve,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 K_({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 W_({versions:t,useCreatedBy:(l=this.versionOptions)==null?void 0:l.useCreatedBy,onSelectVersion:this.handleSelectVersion,getMarkColor:c=>{const{flag:a}=ir(this.editor,c);return a}});i.render(o),this.versionList=i}initViewVersion(){var t;if((t=this.versionOptions)!=null&&t.initSelectedVersion){d(ve,this.versionList,"The versionList did not render");const{initSelectedVersion:e}=this.versionOptions,o=this.versionList.selectVersionByVersionNum(e);d(ve,o,`The version: ${o} is invalid`),this.viewVersion(o)}else{d(ve,this.versionList,"The versionList did not render");const e=this.versionList.activeVersion;d(ve,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 q_(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 mN(n,t,e){const o=n.addCustom("version-dialog",()=>new fN(n,t));return o.show(e),{setShowOps:o.setShowOps}}const GF="",gN=y("heading-collapse");function Z1(n){var e;const t=Number.parseInt((e=n.getAttribute("data-style-heading"))!=null?e:"",10);return d(gN,t,"not a heading block"),t}function He(n){return!!n.getAttribute("data-style-heading")}function pN(n){return!lt(n,"heading-collapsed")}function sr(n){return lt(n,"heading-collapsed")}function v3(n){if(gt(n))return!1;const e=j(n);return Ct(e)}const CN=y("heading-collapse");function Y1(n){d(CN,He(n),"not a heading block");const t=[],e=Z1(n);let o=ht(n);for(;o&&!(He(o)&&Z1(o)<=e);)t.push(o),o=ht(o);return t}function k3(n,t){if(!Uo(t))return;n.selection.selectBlock(t,0),Y1(t).forEach(o=>{vm(o)}),M(t,"heading-collapsed")}function ci(n,t){Y1(t).forEach(o=>{km(o)}),F(t,"heading-collapsed")}function bN(n,t){pN(t)?k3(n,t):ci(n,t)}const vN=[zu,Uu,Vu,qu,Wu,Gu,Zu,Yu];function kN(n){const t=b("button",["heading-collapse-button"],null);return t.setAttribute(`data-editor-tooltip-${n.clientId}`,"Collapse / Expand"),t.innerHTML=Fu,t}function y3(n){return Wc(n).querySelector("button.heading-collapse-button")}function w3(n,t){y3(t)||v3(t)||!Uo(t)||f1(t,kN(n),-1)}function yN(n){var t;(t=y3(n))==null||t.remove()}function B3(n,t){Wc(t).querySelector("button.heading-collapse-button")||w3(n,t)}function wN(n){const t=Z1(n),e=b("button",["heading-marker"],null);return e.innerHTML=vN[t-1],e}function E3(n){return Wc(n).querySelector("button.heading-marker")}function Q1(n){E3(n)||v3(n)||!Uo(n)||f1(n,wN(n),1)}function I3(n){const t=E3(n);t==null||t.remove()}function x3(n){I3(n),He(n)&&Q1(n)}class BN{handleDrop(t,e,o,r){if(sl(e)||!He(e)||!sr(e))return;const i=Y1(e);i.unshift(e);const s=i.reverse();let l=null;return t.doc.beginBatchUpdate(),s.forEach((c,a,h)=>{const f=t.getBlockData(c),m=Fo(t.editorBlocks,t.doc.toJSON(),f),C=t.insertDocAt(o,r,m)[0];a===h.length-1&&(l=C)}),t.doc.endBatchUpdate(),t.doc.beginBatchUpdate(),s.forEach(c=>{t.deleteBlock(c)}),t.doc.endBatchUpdate(),l&&k3(t,l),!0}}const EN=y("heading-collapse");class IN{constructor(t){u(this,"handleLoad",()=>{this.showCollapseButtons()});u(this,"handleHoverBlock",(t,e)=>{e&&(F(e,"hovering-heading"),He(e)&&Ct(j(e))&&(Q1(e),sr(e)||yN(e))),t&&He(t)&&Ct(j(t))&&(M(t,"hovering-heading"),I3(t),w3(this.editor,t))});u(this,"handleClick",(t,e)=>{const o=wi(e,"button.heading-collapse-button");if(!o)return;const r=z(o);!r||(d(EN,He(r),"not a heading block"),bN(this.editor,r),B3(this.editor,r))});this.editor=t,t.addListener("load",this.handleLoad),t.addListener("click",this.handleClick),_t.get(t).addListener("change",this.handleHoverBlock),this.showCollapseButtons(),setTimeout(()=>{xs.get(t).addHandler(new BN)})}showCollapseButtons(){const t=Ot(this.editor.rootContainer).filter(He);t.length!==0&&(t[0]===Kt(this.editor.rootContainer)&&t.splice(0,1),t.forEach(Q1))}destroy(){this.editor.removeListener("load",this.handleLoad),this.editor.removeListener("click",this.handleClick)}}function da(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);sr(e)&&ci(n,e),sr(o)&&ci(n,o)}function xN(n){da(n);const t=n.getFocusedBlock();!He(t)||sr(t)&&ci(n,t)}function SN(n){da(n);const t=n.getFocusedBlock();if(!He(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===Z(n,t)&&sr(t)&&ci(n,t)}function TN(n){da(n);const t=n.getFocusedBlock();if(!He(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===0&&sr(t)&&ci(n,t)}class DN{handleBeforeKeyDown(t,e){return Za(e.key)&&da(t),e.key==="Enter"?(xN(t),!1):e.key==="Delete"?(SN(t),!1):(e.key==="Backspace"&&TN(t),!1)}}class LN{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(!He(o)){e&&e.delete.includes("heading")&&x3(o);return}lt(o,"hovering-heading")&&B3(this.editor,o),x3(o)}},100)}}function MN(n){return!!n.heading}function S3(n){var e;const t=n.heading;return(e=Number.parseInt(`${t}`,10))!=null?e:1}function T3(n,t){var e;return{parentNode:t,children:[],text:wt((e=n.text)!=null?e:[]),level:S3(n),block:n}}class As{constructor(){u(this,"nodes",[])}appendBlock(t){const e=this.findParent(S3(t),this.nodes);e?e.children.push(T3(t,e)):this.nodes.push(T3(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 As,o=t.blocks.root;for(let r=0;r<o.length;r++){const i=o[r];MN(i)&&e.appendBlock(i)}return e}}class lr extends Wt.TypedEmitter{constructor(e){super();u(this,"toc",new As);u(this,"updateToc",Qt.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 lr(e))}static get(e){return e.getCustom("editor-toc")}updateTocNow(){this.toc=As.buildToc(this.editor.doc.toJSON()),this.emit("change",this.editor,this.toc)}}const ZF="";function RN(n){return n.nodes.length===0?!0:n.nodes.length>1?!1:n.nodes[0].children.length===0}function K1(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);K1(s,e.children)}})}function ON(n,t){const e=wi(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 D3(n,t,e){if(F(t,"loading"),t.innerHTML="",RN(e)){b("div",["toc-empty-message"],t,"No toc");return}e.nodes.length===1?K1(t,e.nodes[0].children):K1(t,e.nodes),wu(n,"toc-click-handler",()=>{n.addListener("click",ON)})}class AN{constructor(t){u(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&&D3(t,i,e)})});this.editor=t,lr.register(t).addListener("change",this.handleUpdateToc)}destroy(){lr.register(this.editor).removeListener("change",this.handleUpdateToc)}get toc(){return lr.register(this.editor).toc}}function _N(n,t){const e=b("div",["editor-toc-container"],t),r=n.addCustom("init-editor-toc",()=>new AN(n)).toc;r.nodes.length===0?M(e,"loading"):D3(n,e,r)}function NN(n,t,e,o){return o==="markdown"?"[toc]":""}function PN(n,t,e){const{data:o}=e;if(!o||o.embedType!=="toc"||!H(n,t))return null;const r={};return{blockData:{id:N(),type:"embed",embedType:"toc",embedData:r}}}const L3={embedType:"toc",createEmbedContent:_N,convertTo:NN,convertFrom:PN};function $N(n){return!!n.getAttribute("data-style-heading")}function J1(n,t){return $N(t)&&Z(n,t)>0}function jN(n){const t=_n(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=z(i[s]);if(l&&n.rootContainer.contains(l))return l}o+=10}return null}function X1(n,t){let e=t;for(;e&&!J1(n,e);)e=ht(e);return e}function M3(n){if(gt(n))return!1;const e=j(n);return Ct(e)}function ua(n,t){let e=t;for(;e&&!J1(n,e);)e=gt(e),e&&M3(e)&&(e=null);return e}const HN=.3;class FN extends Wt.TypedEmitter{constructor(e){super();u(this,"scrollContainer");u(this,"scrollEventTarget");u(this,"scrollStatus",{curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null});u(this,"handleScroll",Qt.default(()=>{const e={curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null};let o=jN(this.editor);if(o&&(o=ul(o)),!o||!this.scrollContainer){this.setStatus(e);return}if(M3(o)&&(o=ht(o)),!o){this.setStatus(e);return}if(J1(this.editor,o)){e.curHeadingBlock=o,e.previousHeadingBlock=ua(this.editor,o),e.nextHeadingBlock=X1(this.editor,o),this.setStatus(e);return}const r=this.scrollContainer.getBoundingClientRect(),i=X1(this.editor,o);if(i){const l=i.getBoundingClientRect();if(l.top>r.top&&l.top<r.top+r.height*HN){e.curHeadingBlock=i,e.previousHeadingBlock=ua(this.editor,i),e.nextHeadingBlock=X1(this.editor,i),this.setStatus(e);return}e.nextHeadingBlock=i}const s=ua(this.editor,o);s&&(e.curHeadingBlock=s,e.previousHeadingBlock=ua(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=_n(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 zN{constructor(t,e){u(this,"suggest");u(this,"onShow",(t,e,o,r)=>{const i=this.editor.getBlockByIndex(e,o);if(!Uo(i)){const s=z(j(i));if(s&&it(s)==="code")return!1}return!0});u(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)});u(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})));this.editor=t,this.options=e,this.suggest=new nh(t,{id:"editor-mention",trigger:["@"],autoDeleteTrigger:!0,showLoading:!0,onShow:this.onShow,onClickItem:this.onClickItem,queryItems:this.queryItems})}destroy(){}}y("mathjax-box");function UN(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 VN(n,t,e){}const R3={boxType:"mention",updateBoxContent:UN,handleClickBox:VN};function qN(n){return Vn("list-block-mention",S.t("list.mention.tooltip"),Pw,[],n.clientId)}class WN{constructor(t){u(this,"mentionButton");u(this,"handleHoveringBlock",t=>{var e;!this.editor.isWritable()||(t&&this.shouldBlockShowMention(t)?At(t).appendChild(this.mentionButton):(e=this.mentionButton)==null||e.remove())});u(this,"handleMouseDown",(t,e)=>{e.preventDefault(),e.stopPropagation();const o=z(this.mentionButton);if(!o||!H(t,o))return;const r=t.selection.range.focus;if(!r.isSimple())return;let i;t.selection.focusedBlock!==o?i=Z(t,o):i=r.offset,setTimeout(()=>{const s=t.insertTextToBlock(o,i,"@");i+=1;const l=wt(fe(s,i).left);this.editor.selection.selectBlock(o,i),this.editor.focus(),t.getCustom("mention").suggest.popup(o,i,l,"@")})});u(this,"destroy",()=>{_t.get(this.editor).removeListener("change",this.handleHoveringBlock)});this.editor=t,this.mentionButton=qN(t),_t.get(this.editor).addListener("change",this.handleHoveringBlock),t.domEvents.addEventListener(this.mentionButton,"mousedown",this.handleMouseDown)}shouldBlockShowMention(t){if(!H(this.editor,t)||!at(t))return!1;const e=je(t);return!(e==="ordered"||e==="unordered")}}const YF="",GN={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"}},ZN={templates:{title:"Choose a template",create:"New template",choose:"All templates",customizedMark:"Custom"}};S.mergeLang({"zh-CN":GN,"en-US":ZN});const QF="",YN="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjEyMCIgaGVpZ2h0PSIxMjAiIHZpZXdCb3g9IjAgMCAxMjAgMTIwIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cmVjdCB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTQ4IDU5QzQ4IDU0LjU4MTcgNTEuNTgxNyA1MSA1NiA1MUg5M0M5OC41MjI4IDUxIDEwMyA1NS40NzcyIDEwMyA2MVY4OEMxMDMgOTEuODY2IDk5Ljg2NiA5NSA5NiA5NUg1NkM1MS41ODE3IDk1IDQ4IDkxLjQxODMgNDggODdWNTlaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGQ9Ik0xOCA2NEMxOCA2Mi4zNDMxIDE5LjM0MzEgNjEgMjEgNjFINTZDNjAuNDE4MyA2MSA2NCA2NC41ODE3IDY0IDY5VjgzQzY0IDg1LjIwOTEgNjIuMjA5MSA4NyA2MCA4N0gyNkMyMS41ODE3IDg3IDE4IDgzLjQxODMgMTggNzlWNjRaIiBmaWxsPSIjRUFFNEY2Ii8+CjxyZWN0IHg9IjI0IiB5PSIzMSIgd2lkdGg9IjY1IiBoZWlnaHQ9IjUwIiByeD0iNSIgZmlsbD0iIzk5QzdGMiIvPgo8cmVjdCB4PSIzMy41IiB5PSI0MyIgd2lkdGg9IjQ2IiBoZWlnaHQ9IjUiIHJ4PSIyLjUiIGZpbGw9IndoaXRlIi8+CjxyZWN0IHg9IjMzLjUiIHk9IjU0IiB3aWR0aD0iNDYiIGhlaWdodD0iNSIgcng9IjIuNSIgZmlsbD0id2hpdGUiLz4KPHJlY3QgeD0iMjQiIHk9IjMxIiB3aWR0aD0iNjUiIGhlaWdodD0iNTAiIHJ4PSI1IiBzdHJva2U9IiNGOEY4RjgiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik01MCA4NS4yNjhDNTMuODI2MyA4My4wNTg5IDU1LjEzNzMgNzguMTY2MiA1Mi45MjgyIDc0LjMzOThMNjMuMzIwNSA2OC4zMzk4QzY4Ljg0MzMgNzcuOTA1NyA2NS41NjU4IDkwLjEzNzUgNTYgOTUuNjYwNEM0Ni40MzQxIDEwMS4xODMgMzQuMjAyMyA5Ny45MDU3IDI4LjY3OTQgODguMzM5OEwzOS4wNzE3IDgyLjMzOThDNDEuMjgwOSA4Ni4xNjYyIDQ2LjE3MzYgODcuNDc3MiA1MCA4NS4yNjhaIiBmaWxsPSIjQUI5M0RDIi8+CjxyZWN0IHg9IjU5IiB5PSI2NSIgd2lkdGg9IjQyIiBoZWlnaHQ9IjI4IiByeD0iNSIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTYzIDg4VjczLjA4MDhDNjMgNzEuNzA5NiA2My4zNjE0IDcwLjY4NjcgNjQuMDg0MSA3MC4wMTJDNjQuODI4NyA2OS4zMzczIDY1Ljg1OCA2OSA2Ny4xNzIgNjlIOTIuODYwOUM5NS42MjAzIDY5IDk3IDcwLjM2MDMgOTcgNzMuMDgwOFY4OEg5My41MTc5TDg3LjM3NDkgODAuNjIyQzg3LjA5MDIgODAuMzE3MyA4Ni43NjE3IDgwLjA4ODggODYuMzg5NCA3OS45MzY0Qzg2LjAxNzEgNzkuNzg0MSA4NS42NDQ4IDc5LjcwNzkgODUuMjcyNSA3OS43MDc5Qzg0LjkwMDIgNzkuNzA3OSA4NC41Mjc5IDc5Ljc4NDEgODQuMTU1NiA3OS45MzY0QzgzLjgwNTIgODAuMDg4OCA4My40NTQ4IDgwLjMxNzMgODMuMTA0MyA4MC42MjJMNzYuNzMxNCA4Ni4yMzcxTDc0LjIwMTkgODMuOTUxOUM3My42MzI1IDgzLjQyOTYgNzMuMDA4NCA4My4xNjg0IDcyLjMyOTUgODMuMTY4NEM3MS42NTA2IDgzLjE2ODQgNzEuMDM3NCA4My40Mjk2IDcwLjQ4OTkgODMuOTUxOUw2Ni40NDkzIDg4SDYzWk03NC40NjQ3IDgwLjYyMkM3NS4zNjI2IDgwLjYyMiA3Ni4xNDAxIDgwLjI5NTUgNzYuNzk3MSA3OS42NDI2Qzc3LjQ3NiA3OC45ODk3IDc3LjgxNTUgNzguMjE3MSA3Ny44MTU1IDc3LjMyNDdDNzcuODE1NSA3Ni40MTA3IDc3LjQ3NiA3NS42MzggNzYuNzk3MSA3NS4wMDY5Qzc2LjE0MDEgNzQuMzU0IDc1LjM2MjYgNzQuMDE2NiA3NC40NjQ3IDczLjk5NDhDNzMuNTQ0OSA3My45NTEzIDcyLjc1NjUgNzQuMjY2OSA3Mi4wOTk1IDc0Ljk0MTZDNzEuNDQyNSA3NS42MTYzIDcxLjExNCA3Ni40MTA3IDcxLjExNCA3Ny4zMjQ3QzcxLjExNCA3OC4yMTcxIDcxLjQ0MjUgNzguOTg5NyA3Mi4wOTk1IDc5LjY0MjZDNzIuNzU2NSA4MC4yOTU1IDczLjU0NDkgODAuNjIyIDc0LjQ2NDcgODAuNjIyWiIgZmlsbD0iI0Y3RDA3RiIvPgo8Y2lyY2xlIGN4PSI5NSIgY3k9IjQyIiByPSIyIiBzdHJva2U9IiM1MEMzOTgiIHN0cm9rZS13aWR0aD0iMiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTk0Ljc1MDEgMjQuNDY4N0wxMDAuNzgxIDI3LjkxNDlMOTQuNzE5IDMxLjQxNDlMOTQuNzUwMSAyNC40Njg3WiIgc3Ryb2tlPSIjNUNBNUVBIiBzdHJva2Utd2lkdGg9IjEuOCIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwNSAzOEMxMDUgMzguNTUyMyAxMDUuNDQ4IDM5IDEwNiAzOUMxMDYuNTUyIDM5IDEwNyAzOC41NTIzIDEwNyAzOFYzNkgxMDlDMTA5LjU1MiAzNiAxMTAgMzUuNTUyMyAxMTAgMzVDMTEwIDM0LjQ0NzcgMTA5LjU1MiAzNCAxMDkgMzRIMTA3VjMyQzEwNyAzMS40NDc3IDEwNi41NTIgMzEgMTA2IDMxQzEwNS40NDggMzEgMTA1IDMxLjQ0NzcgMTA1IDMyVjM0SDEwM0MxMDIuNDQ4IDM0IDEwMiAzNC40NDc3IDEwMiAzNUMxMDIgMzUuNTUyMyAxMDIuNDQ4IDM2IDEwMyAzNkgxMDVWMzhaIiBmaWxsPSIjQUI5M0RDIi8+Cjwvc3ZnPgo=",QN="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgdmlld0JveD0iMCAwIDM3MiAyNzkiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMF8xMjU2XzM3MTY4KSI+CjxyZWN0IHdpZHRoPSIzNzIiIGhlaWdodD0iMjc5IiBmaWxsPSJ3aGl0ZSIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIzOS41NzQ3IiB3aWR0aD0iMTE4LjcyMyIgaGVpZ2h0PSIxNS44Mjk4IiByeD0iNy45MTQ4OSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI3MS4yMzM5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI5MS4wMjE1IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIxMTAuODA5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSI0MC41NjM4IiB5PSIxMzUuNTQzIiB3aWR0aD0iMjkwLjg3MiIgaGVpZ2h0PSIxMDAuOTE1IiByeD0iMi45NjgwOSIgc3Ryb2tlPSIjRUFGM0ZDIiBzdHJva2Utd2lkdGg9IjEuOTc4NzIiLz4KPHBhdGggZD0iTTM5LjU3NDUgMTM4LjUxMUMzOS41NzQ1IDEzNi4zMjUgNDEuMzQ2MyAxMzQuNTUzIDQzLjUzMTkgMTM0LjU1M0gzMjguNDY4QzMzMC42NTQgMTM0LjU1MyAzMzIuNDI2IDEzNi4zMjUgMzMyLjQyNiAxMzguNTExVjE1Mi4zNjJIMzkuNTc0NVYxMzguNTExWiIgZmlsbD0iI0Q2RTlGQSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTg3LjA2MzcgMTY5LjE4MUM4Ny4wNjM3IDE2Ny41NDIgODguMzkyNiAxNjYuMjEzIDkwLjAzMTggMTY2LjIxM0gzMTcuNTg1QzMxOS4yMjQgMTY2LjIxMyAzMjAuNTUzIDE2Ny41NDIgMzIwLjU1MyAxNjkuMTgxQzMyMC41NTMgMTcwLjgyIDMxOS4yMjQgMTcyLjE0OSAzMTcuNTg1IDE3Mi4xNDlIOTAuMDMxOEM4OC4zOTI2IDE3Mi4xNDkgODcuMDYzNyAxNzAuODIgODcuMDYzNyAxNjkuMTgxWk0xMDQuODcyIDE5Mi45MjZDMTA0Ljg3MiAxOTEuMjg2IDEwNi4yMDEgMTg5Ljk1NyAxMDcuODQgMTg5Ljk1N0gzMTcuNTg1QzMxOS4yMjQgMTg5Ljk1NyAzMjAuNTUzIDE5MS4yODYgMzIwLjU1MyAxOTIuOTI2QzMyMC41NTMgMTk0LjU2NSAzMTkuMjI0IDE5NS44OTQgMzE3LjU4NSAxOTUuODk0SDEwNy44NEMxMDYuMjAxIDE5NS44OTQgMTA0Ljg3MiAxOTQuNTY1IDEwNC44NzIgMTkyLjkyNlpNMTA3Ljg0IDIxMy43MDJDMTA2LjIwMSAyMTMuNzAyIDEwNC44NzIgMjE1LjAzMSAxMDQuODcyIDIxNi42N0MxMDQuODcyIDIxOC4zMDkgMTA2LjIwMSAyMTkuNjM4IDEwNy44NCAyMTkuNjM4SDMxNy41ODVDMzE5LjIyNCAyMTkuNjM4IDMyMC41NTMgMjE4LjMwOSAzMjAuNTUzIDIxNi42N0MzMjAuNTUzIDIxNS4wMzEgMzE5LjIyNCAyMTMuNzAyIDMxNy41ODUgMjEzLjcwMkgxMDcuODRaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNTEuNDQ2OCAxNjkuMTgxQzUxLjQ0NjggMTY3LjU0MiA1Mi43NzU2IDE2Ni4yMTMgNTQuNDE0OSAxNjYuMjEzSDYwLjM1MUM2MS45OTAzIDE2Ni4yMTMgNjMuMzE5MSAxNjcuNTQyIDYzLjMxOTEgMTY5LjE4MUM2My4zMTkxIDE3MC44MiA2MS45OTAzIDE3Mi4xNDkgNjAuMzUxIDE3Mi4xNDlINTQuNDE0OUM1Mi43NzU2IDE3Mi4xNDkgNTEuNDQ2OCAxNzAuODIgNTEuNDQ2OCAxNjkuMTgxWk01MS40NDY4IDE5Mi45MjZDNTEuNDQ2OCAxOTEuMjg2IDUyLjc3NTcgMTg5Ljk1NyA1NC40MTQ5IDE4OS45NTdINjAuMzUxMUM2MS45OTAzIDE4OS45NTcgNjMuMzE5MSAxOTEuMjg2IDYzLjMxOTEgMTkyLjkyNkM2My4zMTkxIDE5NC41NjUgNjEuOTkwMyAxOTUuODk0IDYwLjM1MTEgMTk1Ljg5NEg1NC40MTQ5QzUyLjc3NTcgMTk1Ljg5NCA1MS40NDY4IDE5NC41NjUgNTEuNDQ2OCAxOTIuOTI2Wk01NC40MTQ5IDIxMy43MDJDNTIuNzc1NyAyMTMuNzAyIDUxLjQ0NjggMjE1LjAzMSA1MS40NDY4IDIxNi42N0M1MS40NDY4IDIxOC4zMDkgNTIuNzc1NyAyMTkuNjM4IDU0LjQxNDkgMjE5LjYzOEg2MC4zNTExQzYxLjk5MDMgMjE5LjYzOCA2My4zMTkxIDIxOC4zMDkgNjMuMzE5MSAyMTYuNjdDNjMuMzE5MSAyMTUuMDMxIDYxLjk5MDMgMjEzLjcwMiA2MC4zNTExIDIxMy43MDJINTQuNDE0OVoiIGZpbGw9IiM5OUM3RjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik02OS4yNTU0IDE2OS4xODFDNjkuMjU1NCAxNjcuNTQyIDcwLjU4NDMgMTY2LjIxMyA3Mi4yMjM1IDE2Ni4yMTNINzguMTU5N0M3OS43OTg5IDE2Ni4yMTMgODEuMTI3OCAxNjcuNTQyIDgxLjEyNzggMTY5LjE4MUM4MS4xMjc4IDE3MC44MiA3OS43OTg5IDE3Mi4xNDkgNzguMTU5NyAxNzIuMTQ5SDcyLjIyMzVDNzAuNTg0MyAxNzIuMTQ5IDY5LjI1NTQgMTcwLjgyIDY5LjI1NTQgMTY5LjE4MVpNNjkuMjU1NCAxOTIuOTI2QzY5LjI1NTQgMTkxLjI4NiA3MC41ODQyIDE4OS45NTcgNzIuMjIzNSAxODkuOTU3SDc4LjE1OTZDNzkuNzk4OSAxODkuOTU3IDgxLjEyNzcgMTkxLjI4NiA4MS4xMjc3IDE5Mi45MjZDODEuMTI3NyAxOTQuNTY1IDc5Ljc5ODkgMTk1Ljg5NCA3OC4xNTk2IDE5NS44OTRINzIuMjIzNUM3MC41ODQyIDE5NS44OTQgNjkuMjU1NCAxOTQuNTY1IDY5LjI1NTQgMTkyLjkyNlpNNzIuMjIzNSAyMTMuNzAyQzcwLjU4NDIgMjEzLjcwMiA2OS4yNTU0IDIxNS4wMzEgNjkuMjU1NCAyMTYuNjdDNjkuMjU1NCAyMTguMzA5IDcwLjU4NDIgMjE5LjYzOCA3Mi4yMjM1IDIxOS42MzhINzguMTU5NkM3OS43OTg5IDIxOS42MzggODEuMTI3NyAyMTguMzA5IDgxLjEyNzcgMjE2LjY3QzgxLjEyNzcgMjE1LjAzMSA3OS43OTg5IDIxMy43MDIgNzguMTU5NiAyMTMuNzAySDcyLjIyMzVaIiBmaWxsPSIjRjdEMDdGIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNOTAuMDMxOCAxODkuOTU4Qzg4LjM5MjYgMTg5Ljk1OCA4Ny4wNjM3IDE5MS4yODYgODcuMDYzNyAxOTIuOTI2Qzg3LjA2MzcgMTk0LjU2NSA4OC4zOTI2IDE5NS44OTQgOTAuMDMxOCAxOTUuODk0SDk1Ljk2OEM5Ny42MDcyIDE5NS44OTQgOTguOTM2MSAxOTQuNTY1IDk4LjkzNjEgMTkyLjkyNkM5OC45MzYxIDE5MS4yODYgOTcuNjA3MiAxODkuOTU4IDk1Ljk2OCAxODkuOTU4SDkwLjAzMThaTTkwLjAzMTkgMjEzLjcwMkM4OC4zOTI3IDIxMy43MDIgODcuMDYzOCAyMTUuMDMxIDg3LjA2MzggMjE2LjY3Qzg3LjA2MzggMjE4LjMwOSA4OC4zOTI3IDIxOS42MzggOTAuMDMxOSAyMTkuNjM4SDk1Ljk2ODFDOTcuNjA3MyAyMTkuNjM4IDk4LjkzNjIgMjE4LjMwOSA5OC45MzYyIDIxNi42N0M5OC45MzYyIDIxNS4wMzEgOTcuNjA3MyAyMTMuNzAyIDk1Ljk2ODEgMjEzLjcwMkg5MC4wMzE5WiIgZmlsbD0iIzkxRDlCRSIvPgo8L2c+CjxkZWZzPgo8Y2xpcFBhdGggaWQ9ImNsaXAwXzEyNTZfMzcxNjgiPgo8cmVjdCB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgZmlsbD0id2hpdGUiLz4KPC9jbGlwUGF0aD4KPC9kZWZzPgo8L3N2Zz4K",O3=y("templates");function tf(n){const t=n.rootElement.querySelector(":scope .editor-templates");if(!t)return null;const e=t.querySelector(":scope .editor-templates-cards");return d(O3,e,"no card container"),{root:t,cardContainer:e}}function KN(n){const t=tf(n);if(t)return t.cardContainer.innerHTML="",t;const e=b("div",["editor-templates"],n.rootElement);b("div",["editor-templates-title"],e,S.t("templates.title"));const o=b("div",["editor-templates-cards"],e);return{root:e,cardContainer:o}}function A3(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:QN;c.src!==m&&(c.src=m)},c.onload=()=>{c.style.display=""};const a=b("div",["editor-template-name"],s),h=b("span",[],a,e);return i!=null&&i.showTemplateTitleAttr&&h.setAttribute("title",e),s.onclick=()=>r(s),s}function JN(n,t){return t.thumbnailUrl?t.thumbnailUrl:n.doc.buildResourceUrl("thumbnail.png")}function XN(n,t){const e=JN(n,t);return A3(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 tP(n,t){return A3(n,t,S.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 eP(n,t){var f,m;const e=(f=n.options.componentsOptions)==null?void 0:f.templates;if(!e)return;const r=Gt(n.rootContainer).getBoundingClientRect().width;let i=1;const s=YN,l=tf(n);if(l){if(t!=null&&t.reset){const C=Array.from(l.cardContainer.children),v=l.cardContainer.firstElementChild;if(d(O3,v,"no first card"),lt(v,"new")||lt(v,"more"))return;const w=window.getComputedStyle(v),E=parseFloat(w.marginLeft),D=parseFloat(w.marginRight),x=v.getBoundingClientRect().width+E+D;i=Math.floor(r/x);const O=Math.max(1,i-1-1),P=C.length-1;C.forEach((V,nt)=>{nt>O&&nt<P?V.style.display="none":(nt>=P&<(V,"more"),V.style.display="")})}return}const c=e.templates,{cardContainer:a}=KN(n);c.forEach((C,v)=>{const w=XN(n,C);if(v>0&&v>=i&&(w.style.display="none"),a.appendChild(w),v===0){const E=window.getComputedStyle(w),D=parseFloat(E.marginLeft),x=parseFloat(E.marginRight),A=w.getBoundingClientRect().width+D+x;i=Math.floor(r/A)-1}});const h=tP(n,s);a.appendChild(h),(m=e==null?void 0:e.onTemplateChooserStatusChanged)==null||m.call(e,n,a,"visible")}const _3=Qt.default(eP,50);function nP(n){var o,r;const t=tf(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 oP(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 ef(n,t){oP(n.doc.toJSON())?_3(n,t):(_3.cancel(),nP(n))}class _s{constructor(t,e){u(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 _s(t,e))}}const KF="",Co=y("encrypted-block");function rP(n,t,e,o,r){const i=r,s=no(o,"div"),l=_s.getState(n,i);if(l.decrypted)n.createChildContainer(t,s,i.children[0]),M(o,"decrypted");else{M(o,"encrypted");const c=At(o),a=b("div",["password-container"],c),h=b("input",[],a);h.type="text",h.onkeydown=f=>{if(f.key==="Enter"){const m=h.value;if(i.password===Ci.default(`${i.owner}-${m}`)){l.setDecrypted(),n.reloadBlock(o);const C=vd(n,n.getBlockById(i.id));C&&(n.selection.selectBlock(C,0),n.focus())}}}}return s}function iP(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t)||!mn(r))return null;const i=r;if(n.getBlockData(t).children[0]!==U(i))return null;const l=bt(t,U(i));return new Qe(n,{anchor:l,focus:l})}function sP(n,t,e,o){if(_s.getState(n,n.getBlockData(t)).decrypted)return null;if(o==="ArrowDown"||o==="ArrowRight"){const s=ht(t);return s?$(s,Z(n,s),"end"):$(t,1,"end")}const i=gt(t);return $(i||t,0,"home")}function lP(n,t){return n.getBoundingClientRect()}function cP(n,t,e,o){if(e.isSimple()){d(Co,o.isSimple(),"from is simple position but to is not simple position"),Co.debug("full select table"),M(t,"full-selected");return}d(Co,!o.isSimple(),"from is complex position but end is simple position");const r=e,i=o;d(Co,r.blockId===i.blockId,"only allow update one table selection"),d(Co,r.childContainerId===i.childContainerId,"only one container");const s=n.getBlockData(t),l=n.getContainerById(s.children[0]);M(l,"selected")}function aP(n){n.rootContainer.querySelectorAll('[data-type="editor-block"][data-block-type="encrypted"]').forEach(t=>{F(t,"full-selected"),t.querySelectorAll("selected").forEach(e=>{F(e,"selected")})})}function dP(n,t){const e=n.getBlockData(t);return _s.getState(n,e).decrypted?[n.getContainerById(e.children[0])]:[]}function uP(n,t,e,o,r){return null}function hP(n,t,e,o){d(Co,e.blockId===o.blockId,"only allow select in single block"),d(Co,G(t)===e.blockId,"only allow select in single block");const r=n.getBlockData(t);return d(Co,e.childContainerId===r.children[0],"only one container"),[n.getContainerById(r.children[0])]}function fP(n){return{name:"EncryptedBlock",insertBlockCommandItems:[{id:"insert-encrypted-block",name:"Encrypted Block"}],async handleInsertEmptyBlock(t,e){const o=Cn(t.doc),r={id:N(),type:"encrypted",children:[o],owner:t.doc.getUser().userId,ownerDisplayName:t.doc.getUser().displayName,password:Ci.default(`${t.doc.getUser().userId}-1234`)},i=t.doc.getContainerBlocks(o)[0];return t.insertBlock(e.containerId,e.blockIndex,r,Lt(t,i.id,0))}}}const mP={blockType:"encrypted",blockKind:"complex",enableKeyboardSelect:!0,createBlockContent:rP,getBlockTextLength:()=>1,getRangeFromPoint:iP,moveCaret:sP,getCaretRect:lP,updateSelection:cP,clearSelection:aP,getChildContainers:dP,getNextContainer:uP,getSelectedContainers:hP,getOptions:fP};function gP(n,t,e){const o=Fi(n,t,{components:{blocks:[gs,bs,mP],decorators:[new ks],embeds:[Kc,r1,E1,I1,x1,zh,S1,W1,q1],boxes:[Dc],options:{...e.componentsOptions}}});return o.readonly=!0,o}class pP{constructor(t){this.createOptions=t}createHistoryEditor(t,e){return gP(t,e,this.createOptions)}}y("create-editor");function N3({root:n,childDoc:t,doc:e}){t.uploadResource=e.uploadResource.bind(e),t.buildResourceUrl=e.buildResourceUrl.bind(e);const o=Fi(n,t,{shortcuts:[Vl],components:{blocks:[gs,bs],decorators:[new ks],embeds:[O4,Kc,r1,E1,I1,x1,zh,S1,W1,q1],boxes:[Dc,R3],options:{}}});return o.input.addHandler(new $c),o.input.addHandler(new T1(o)),o.input.addHandler(new FA(o)),o}function CP(n,t){const e=Array.from(n.rootContainer.querySelectorAll(`[comment-${t.toLocaleLowerCase()}="${t}"]`)),o=new Set;e.forEach(r=>{const i=z(r);i&&o.add(i)}),o.forEach(r=>{zA(n,r,t)})}class bP{constructor(t){u(this,"listeners",new Set);u(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&&CP(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 N3({root:t,childDoc:e,doc:this.doc})}}class vP{constructor(t,e){u(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 $u(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 N3({root:t,childDoc:e,doc:this.localDoc})}}const kP={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"}}},yP={placeholder:{common:{title:"Enter a title",readonlyTitle:"Enter a title",content:'Click "+", or enter "/" to insert components quickly'},local:{readonlyTitle:"Untitled"}}};S.mergeLang({"zh-CN":kP,"en-US":yP});const nf=y("create-editor"),P3=[Kc,r1,E1,I1,x1,zh,S1,W1,q1,O4,L3,x_];async function wP(n,t){var s,l,c,a,h,f,m,C,v,w,E;d(nf,n,"app does not exists"),t.lang&&S.setLang(t.lang);const e=t.onReauth?async()=>{var O;const D=t.user.userId,x=t.docId,A=await((O=t.onReauth)==null?void 0:O.call(t,D,x,t.permission));return{userId:D,docId:x,permission:t.permission,appId:t.appId,token:A,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 ts.load(o),i=Fi(n,r,{id:t.id,components:{blocks:[gs,bs,d1,y5],commandProviders:[new hh,...((s=t.components)==null?void 0:s.commandProviders)||[]],decorators:[new ks,new Hu],embeds:[...P3,...((l=t.components)==null?void 0:l.embeds)||[]],boxes:[Dc,R3,J6,...((c=t.components)==null?void 0:c.boxes)||[]],insertions:[Pd],blockHooks:[new I4],textRenders:[new W6,new qI],options:{...t.componentsOptions}},shortcuts:[hD,GL,Kh,E6,WI,qh,Vl],colors:["#338FE5","#24B47E","#F0A100","#E52727","#9678D3","#2CB2AE","#EB6414","#8AAB3F"]});if(i.editorCommandProviders.registerCommandProvider(new xn(i)),i.input.addHandler(new DN),i.input.addHandler(new $c),i.input.addHandler(new xx),i.input.addHandler(new HL),i.input.addHandler(new Cs(i,{headingLevel:1,titlePlaceholder:S.t("placeholder.common.title"),contentPlaceholder:S.t("placeholder.common.content"),readonlyTitlePlaceholder:S.t("placeholder.common.readonlyTitle"),addPlaceholderToAllCurrentEmptyBlock:!0})),i.input.addHandler(new Lc(i,(a=t.componentsOptions)==null?void 0:a.quickMenu)),i.input.addHandler(new T1(i)),i.input.addHandler(new g6(i)),i.doc.registerCallback(new LN(i)),i.addCustom("remote-cursor",()=>new t0(i)),i.addCustom("block-menu",D=>new D4(D)),i.addCustom("editor-tooltip",()=>new Vh(i)),t!=null&&t.enableComments&&i.addCustom("editor-comments",D=>new q6(D,new bP(D))),i.addCustom("create-options",()=>new Mf(i,t)),i.addCustom("drop-target",()=>new xs(i)),i.addCustom("list-to-mindmap",()=>new xc(i)),i.addCustom("list-to-mention",()=>new WN(i)),(h=t.componentsOptions)!=null&&h.mention){const D=t.componentsOptions.mention;i.addCustom("mention",()=>new zN(i,D))}if(i.addCustom("heading-collapse",()=>new IN(i)),Wr.register(i),xs.register(i),lr.register(i),(m=(f=t.componentsOptions)==null?void 0:f.remoteCarets)!=null&&m.onUserChanged){const D=(v=(C=t.componentsOptions)==null?void 0:C.remoteCarets)==null?void 0:v.onUserChanged;i.doc.getRemoteUsers().on("change",x=>{D(i,x)})}return(E=(w=t.componentsOptions)==null?void 0:w.templates)!=null&&E.templates.length&&(i.addListener("docChanged",()=>{ef(i)}),i.addListener("resize",()=>{ef(i,{reset:!0})}),setTimeout(()=>{ef(i)},100)),i.doc.registerCallback({onError:async D=>{if(D.code==="ResetDoc"){nf.error(`reset doc: ${D.message}`);const x=await ts.load(o);i.doc.reset(x)}}}),i}function BP(n){return n.toJSON!==void 0}async function EP(n,t,e){var i,s;d(nf,n,"app does not exists");const o=BP(t)?t:new yu(t,{serverUrl:e.serverUrl||""});e.lang&&S.setLang(e.lang);const r=Fi(n,o,{id:e.id,components:{blocks:[gs,bs,d1,y5],commandProviders:[new hh],decorators:[new ks,new Hu],embeds:[...P3,...((i=e.components)==null?void 0:i.embeds)||[]],boxes:[Dc,J6],insertions:[Pd],blockHooks:[new I4],textRenders:[new W6],options:{...e.componentsOptions}},shortcuts:[Kh,E6,qh,Vl]});return r.editorCommandProviders.registerCommandProvider(new xn(r)),r.input.addHandler(new $c),r.input.addHandler(new Cs(r,{headingLevel:1,titlePlaceholder:S.t("placeholder.common.title"),contentPlaceholder:S.t("placeholder.common.content"),readonlyTitlePlaceholder:S.t("placeholder.local.readonlyTitle"),addPlaceholderToAllCurrentEmptyBlock:!0})),r.input.addHandler(new Lc(r,(s=e.componentsOptions)==null?void 0:s.quickMenu)),r.input.addHandler(new T1(r)),r.input.addHandler(new g6(r)),r.addCustom("block-menu",l=>new D4(l)),r.addCustom("editor-tooltip",()=>new Vh(r)),e!=null&&e.enableComments&&r.addCustom("editor-comments",l=>new q6(l,new vP(l,o))),Wr.register(r),r}function IP(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 pP(i);return mN(n,s,t)}g.tippy=x9,g.AuthError=tc,g.AuthHeader=Xi,g.AutoScroll=fm,g.BaseURLHeader=ec,g.BlockResizer=Pc,g.BrBox=zg,g.CodeBlock=bs,g.CodeLineBlock=d1,g.CodeTextDecorator=ks,g.DefaultShortcuts=Vl,g.DocIdError=Sy,g.DragDrop=qf,g.DrawioEmbed=Kc,g.EditorBlocks=Km,g.EditorBoxes=Vg,g.EditorCommandProviders=g2,g.EditorComplexBlockPosition=Ye,g.EditorComplexSelectionRange=Qe,g.EditorDecorators=Zg,g.EditorEmbeds=Xm,g.EditorInsertions=Gg,g.EditorSimpleBlockPosition=Ut,g.EditorSimpleSelectionRange=se,g.EmbedBlock=eg,g.EnforceWithDocumentTitleHandler=Cs,g.EventCallbacks=vi,g.FILL_CHAR=H8,g.FileExtError=Ty,g.HeadingBlockScrollListener=FN,g.InputtingInsertion=qg,g.LocalDoc=yu,g.Logger=ur,g.MIN_DISTANCE_THRESHOLD=Uf,g.ManualMenu=Wo,g.MarkdownInputHandler=$c,g.MaxUserError=Ou,g.OnesEditorAutoSuggest=nh,g.OnesEditorCustomDataWrapper=Mf,g.OnesEditorHoveringBlock=_t,g.OnesEditorQuickMenu=Lc,g.OnesEditorToc=As,g.OnesEditorTocProvider=lr,g.OnesEditorToolbar=Wr,g.OnesEditorTooltip=Vh,g.PermissionError=xy,g.Popup=ic,g.RemoteCarets=t0,g.RemoteCaretsDecorator=Hu,g.RemoteCaretsInsertion=Pd,g.RemoteUsers=Wl,g.RequestReloadError=Ji,g.RichText=oe,g.ShareDBDoc=ts,g.SimpleCache=Of,g.StandardEmbedBlockCommands=n1,g.TEXT_STYLE_BACKGROUND_COLOR_PREFIX=Od,g.TEXT_STYLE_COLOR_PREFIX=Rd,g.TableBlock=gs,g.TableBlockCommandProvider=hh,g.TableShortcuts=Kh,g.TextBlock=Ai,g.TextBox=Fg,g.TextStyleShortcuts=qh,g.TocEmbed=L3,g.ZERO_WIDTH_SPACE_CHAR=ki,g.addAttribute=yl,g.addClass=M,g.addCommentToBlock=e1,g.addDays=p7,g.addMonths=g7,g.animateScrollTo=Bi,g.applyPlaceholderToBlock=jc,g.assert=d,g.blockToDoc=Xd,g.blockToHtml=$d,g.blockToMarkdown=Yg,g.blockToText=Ll,g.blocksToDoc=gb,g.clearAllSelection=Fm,g.clientType=St,g.cloneBlock=Fo,g.cloneChildContainer=Zd,g.cloneDoc=Yd,g.cloneText=Mg,g.commentToShareDbComment=ju,g.compareElement=Xs,g.comparePosition=Cd,g.complexBlockAdjustSelectionPos=ml,g.complexBlockFindNearestChildBlock=ig,g.complexBlockGeFirstSimpleChild=vd,g.complexBlockGetAllChildContainers=Me,g.complexBlockGetBottomChildContainers=rg,g.complexBlockGetLastSimpleChild=yr,g.complexBlockGetSelectedContainers=kr,g.complexBlockGetTopChildContainers=og,g.containerToDoc=tu,g.continuousScroll=hm,g.convertBlockFrom=hl,g.copyBlockAttributes=rp,g.createBlockAnchor=_o,g.createBlockContentElement=no,g.createBlockElement=wm,g.createBlockSimpleDocRange=Tl,g.createBlockSimpleRange=Lt,g.createBoxContentElement=Im,g.createBoxElement=Bm,g.createBoxOp=wg,g.createChildContainer=$m,g.createComplexBlockPosition=bt,g.createComplexDocPos=$g,g.createComplexDocRange=z8,g.createContainer=Ag,g.createContainerElement=cd,g.createDeleteOps=bg,g.createEditor=Fi,g.createEditorSelectionRange=Vt,g.createElement=b,g.createEmptyContainer=Cn,g.createEmptyDoc=ro,g.createEmptyTextBlockData=Il,g.createExpandedRange=Ks,g.createIconButton=hr,g.createImage=Af,g.createInsertOps=kl,g.createInsertionContentElement=Tm,g.createInsertionElement=xm,g.createLocalEditor=EP,g.createOnesEditor=wP,g.createRange=_f,g.createRichText=Oi,g.createRootContainer=Pm,g.createSimpleBlockPosition=$,g.createSimpleDocPos=Pg,g.createTextBlockData=jn,g.createTextButton=Xo,g.createTextOp=_e,g.createTextWithReplaceSoftReturn=Td,g.daysAfter=Xa,g.deleteText=Ld,g.diffDays=C7,g.disablePageScroll=im,g.docToHtml=nb,g.docToHtmlFragment=Qg,g.docToMarkdown=ob,g.docToText=Kg,g.downloadObjectToFile=v1,g.downloadSvgToString=_4,g.editLink=bc,g.editorAddComment=VA,g.editorAddTextAttribute=bp,g.editorAutoInsertBlock=ip,g.editorBreakTextBlock=Dr,g.editorClearCompositionText=op,g.editorClearSelectedContents=Wd,g.editorCopyBlock=iu,g.editorDeleteBlock=Vd,g.editorDeleteBlockText=Fd,g.editorDeleteBlockWithoutChildren=Ud,g.editorDeleteChildContainer=db,g.editorDeleteChildContainers=ap,g.editorFocusToBlock=Gd,g.editorFocusToEnd=wp,g.editorGetBlockData=io,g.editorGetBlockText=we,g.editorGetBlockTextEx=Rl,g.editorGetBoxData=Jg,g.editorHandleKeyboardEvent=Qp,g.editorInsertBlock=Tr,g.editorInsertBoxToBlock=ep,g.editorInsertDoc=pp,g.editorInsertDocAt=Qd,g.editorInsertText=Hd,g.editorInsertTextToBlock=tp,g.editorInsertTextToBlockEx=jd,g.editorMergeTextBlock=dp,g.editorRangeClearColor=kp,g.editorRangeGetColor=Kd,g.editorRangeSetColor=vp,g.editorRemoveTextAttribute=fb,g.editorReplaceBlockText=Pl,g.editorReplaceContainer=Cp,g.editorRunOnce=wu,g.editorSelectEnd=yp,g.editorSetTextColor=Lr,g.editorShowFindDialog=YO,g.editorUpdateBlockData=$l,g.editorUpdateCompositionText=np,g.editorUpdateEmbedData=mp,g.enablePageScroll=sm,g.escapeHtmlText=Hf,g.escapeRegExp=nd,g.escapeSpace=J9,g.executeBlockCommand=Qm,g.executeEmbedBlockCommand=Ym,g.executeRangeCommand=m2,g.fileToDataUrl=nl,g.findAllText=Nd,g.findInsertionById=Sm,g.findPrevSimpleBlockBeforeChildContainer=ng,g.findTarget=wi,g.format=Ja,g.formatBytes=mm,g.formatDate=Cm,g.fragmentToHtml=lm,g.fromBase64=el,g.fromBase64ToBlob=nm,g.fromBase64ToUint8Array=d7,g.fromDocRange=oo,g.fromNowString=ed,g.genId=N,g.getAllChildBlocks=yd,g.getAllQuickMenuItems=Uh,g.getAllSelectedBlocks=Ke,g.getAttributesAt=Bl,g.getBlockBackground=ym,g.getBlockByIndex=fr,g.getBlockCaretRect=Ze,g.getBlockClass=kt,g.getBlockClassByType=br,g.getBlockClientRects=Oo,g.getBlockCommandsWithHook=fd,g.getBlockContent=rt,g.getBlockId=G,g.getBlockIndex=K,g.getBlockKind=Ge,g.getBlockMinWidth=Um,g.getBlockOptions=S7,g.getBlockPath=Ro,g.getBlockProperties=Wm,g.getBlockStyles=I7,g.getBlockTextLength=Z,g.getBlockTools=At,g.getBlockType=it,g.getBoxContent=id,g.getBoxId=Em,g.getBoxTypeFromElement=xi,g.getChildBlockCount=Ve,g.getChildBlocks=Ot,g.getChildOffset=Br,g.getColorFromAttributes=_d,g.getComplexBlockClass=ye,g.getContainerBlockPath=Am,g.getContainerBlocks=Rm,g.getContainerBlocksElement=dl,g.getContainerById=Cr,g.getContainerId=U,g.getContainerMinWidth=ud,g.getContainerToolsElement=k7,g.getContainerWidth=qm,g.getDistanceSquare=fn,g.getElementOffset=yi,g.getEmbedType=Le,g.getExistsBlockTools=al,g.getExistsContainerById=Lm,g.getFileExt=am,g.getFirstChildBlock=Kt,g.getFirstClientRect=Js,g.getHeadingMenuOptions=Tc,g.getHorizontalPadding=Fa,g.getInsertionContent=sd,g.getLastChildBlock=Gt,g.getLastClientRect=Io,g.getLogger=y,g.getNextBlock=ht,g.getNextValidOffset=Er,g.getNextVisibleBlock=pr,g.getOpAt=Eg,g.getOpLength=Md,g.getParentBlock=z,g.getParentBox=rd,g.getParentContainer=j,g.getPrevBlock=gt,g.getPrevValidOffset=Po,g.getPrevVisibleBlock=gr,g.getRangeCommands=h2,g.getRootBlock=ul,g.getScrollContainer=_n,g.getSpecialBlockCommands=Gm,g.getStandardEmbedBlockProperties=o1,g.getTextBlockChild=gl,g.getTextBlockClass=Hm,g.getTextBlockContentChildTextLength=Oe,g.getTextBlockContentChildType=sg,g.getTextBlockContentChildren=$n,g.getTextLength=ce,g.getTextOpLength=Bd,g.getTextWidth=rl,g.getToolbar=Cc,g.handleBlockElementUpdated=Vm,g.hasAltOnly=r7,g.hasClass=lt,g.hasCtrlOrCmd=Jf,g.hasCtrlOrCmdOnly=o7,g.hideBlock=vm,g.htmlToFragment=ol,g.i18n=S,g.injectStyle=zf,g.insertEmptyBlock=D7,g.insertEmptyEmbedBlock=md,g.insertText=Ir,g.intersectionCommands=kk,g.isBackspace=tm,g.isBlock=mr,g.isBox=od,g.isCJK=Yf,g.isChildContainer=We,g.isChildNode=vt,g.isCollapsedRange=Ng,g.isComplexBlockPosition=pd,g.isComplexKindBlock=ct,g.isContainer=mn,g.isControlEvent=To,g.isDelete=s7,g.isDraggingFiles=sl,g.isEmbedBlock=De,g.isEmptyContainer=hd,g.isEmptyDoc=xl,g.isEmptyTextBlock=yt,g.isEmptyTextBlockWithoutCompositionText=ps,g.isEnterOnly=Xf,g.isEscape=Ya,g.isFirefox=Ga,g.isFirstChildBlockInComplexBlock=n8,g.isHighSurrogate=W9,g.isInBlock=ld,g.isInBlockTools=Si,g.isLetter=Zf,g.isLowSurrogate=Ha,g.isMatchShortcut=An,g.isMoveForward=e7,g.isNavigationEvent=t7,g.isNavigationKey=Kf,g.isNodeRemoved=Pf,g.isNumber=Gf,g.isPrintableKey=Za,g.isRootBlock=Uo,g.isRootContainer=Ct,g.isSafari=Qf,g.isSameDay=td,g.isShiftEnter=i7,g.isShiftTab=c7,g.isShortcutEvent=n7,g.isSimpleBlock=x7,g.isSimpleBlockPosition=vr,g.isSimplePos=_g,g.isSimpleRange=Sl,g.isSpace=tl,g.isTab=l7,g.isTextBlockContentBoxChild=Re,g.isTextBlockContentChild=Di,g.isTextBlockContentInsertionChild=Pn,g.isTextBlockContentTextChild=Li,g.isTextKindBlock=H,g.isTextKindBlockType=Ti,g.isToday=gm,g.isValidOffset=me,g.isVisibleBlock=cl,g.isYesterday=pm,g.loadJs=$f,g.loadJsPromise=xo,g.lockers=Ue,g.mergeCommands=pc,g.mergeDocs=Ho,g.mergeOps=Dd,g.mergeText=N8,g.multiSplitText=ag,g.parseShortcut=em,g.patchNode=Ii,g.pointInRect=So,g.rangeAddAttribute=wl,g.rangeGetTextColor=Lg,g.rangeRemoveAttribute=xr,g.rangeSetTextColor=Sg,g.rangeTransformText=Ig,g.registerDragDrop=qa,g.removeAttribute=Ad,g.removeClass=F,g.removeLastBr=R8,g.removePlaceholderFromBlock=e4,g.removeStyle=Ff,g.replaceAll=b7,g.replaceAllCaseInsensitive=v7,g.replaceAllText=Og,g.replaceText=El,g.requestDownload=ll,g.scrollable=um,g.selectFile=Lo,g.selectedBlockToDoc=Hl,g.selectionToDoc=Fl,g.setAttributes=Ua,g.setClipboardData=il,g.setClipboardDataByEvent=m7,g.setColorToAttributes=Tg,g.setDataset=za,g.setDefaultCursor=Ei,g.setStyles=Va,g.shareDBCommentToDocObject=$u,g.shareDBDocCommentToComment=J2,g.shortcutToDisplayText=a7,g.showBlock=km,g.showDocVersions=IP,g.splitText=fe,g.splitToThree=Jt,g.stringToDataUrl=om,g.stringToObjectUrl=Ka,g.subText=dg,g.textNodeOffsetFromPoint=Nf,g.toBase64URL=Do,g.toPlainText=wt,g.trimChar=Wa,g.unicodeLength=G9,g.unicodeSubstr=Z9,g.updateBlockSelection=zm,g.updateOpAttributes=Rg,g.updateTextBlockContent=G8,g.updateUrl=Qa,Object.defineProperties(g,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
661
|
+
</svg>`,{t:G1}=S;class K_{constructor(t){u(this,"goBackButton");u(this,"playButton");u(this,"revertButton");this.options=t;const e=b("button",["dialog-text-button"],null),o=b("span",["dialog-button-icon"],e);o.innerHTML=Q_,b("span",["dialog-button-text"],e,G1("version.goBack"));const r=b("button",["dialog-version-button"],null,G1("version.play")),i=b("button",["dialog-version-button"],null,G1("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 he=y("split-text-actions");function u3(n){return n.length>2?!1:n.length===1?n[0].insert!==void 0:(d(he,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].insert!==void 0)}function h3(n){return n.length>2?!1:n.length===1?n[0].delete!==void 0:(d(he,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].delete!==void 0)}function f3(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(he,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].attributes!==void 0)}function J_(n){const t=[],e=Y.default(n);if(e.length===0)return[];if(e.length===1)return[n];if(e.length===2&&(h3(n)||u3(n)||f3(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(he,i.retain>0,`invalid text op: ${JSON.stringify(i)}`),d(he,e.length>1,`invalid text op: ${JSON.stringify(i)}`);const s=e[1];d(he,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(he,s.attributes!==void 0,`invalid next text op: ${JSON.stringify(s)}`),d(he,s.retain!==void 0,`invalid next text op: ${JSON.stringify(s)}`),r+=s.retain),e.splice(0,2)}else d(he,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(he,i.attributes!==void 0,`invalid next text op: ${JSON.stringify(i)}`),r+=i.retain),i.insert&&(r+=i.insert.length)}return t}function m3(n){if(d(he,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(he,typeof t=="number"&&t>0,`invalid retain: ${JSON.stringify(n)}`),t}let g3=0;function X_(n,t,e){const o=g3;g3+=1;const r=wt(n);return{insert:" ",attributes:{box:!0,id:N(),type:"history-deleted-box",user:e,created:Date.now(),text:r,deletedOffset:t,deletedOrder:o}}}function tN(n,t,e){const o=m3(t),r=t.length===1?t[0].delete:t[1].delete;d(he,typeof r=="number",`not a delete op: ${JSON.stringify(t)}`);const{left:i,middle:s,right:l}=Jt(n,o,r),c=X_(s,o,e);return[...i,c,...l]}function eN(n,t,e){const o=m3(t),r=t.length===1?t[0].insert:t[1].insert;d(he,typeof r=="string",`invalid insert op: ${JSON.stringify(t)}`);const i=t.length===1?t[0].attributes:t[1].attributes,l=yl([{insert:r,attributes:i}],"insertedBy",e);return Ir(n,o,l,null)}function nN(n,t,e){const o=J_(t).reverse();let r=n;for(const i of o)h3(i)?r=tN(r,i,e):u3(i)?r=eN(r,i,e):(d(he,f3(i),`unknown op: ${JSON.stringify(i)}`),r=oe.apply(r,i));return r}const oN=y("history-update-block-text");function p3(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+=Md(r)}),t.sort((r,i)=>i.offset-r.offset),{deletedBoxes:t,newText:e}}function rN(n,t,e){let o=n;return t.forEach(r=>{const i=oe.transformCursor(r.offset,e,!1);o=Ir(o,i,[{insert:" ",attributes:r.boxData}],null)}),o}function iN(n){n.sort((t,e)=>t.boxData.deletedOffset!==e.boxData.deletedOffset?t.boxData.deletedOffset-e.boxData.deletedOffset:t.boxData.deletedOrder-e.boxData.deletedOrder)}function sN(n){if(n.length<=1)return n;const t=n[0].offset;n.forEach(e=>{d(oN,e.offset===t,`invalid boxes group, ${JSON.stringify(n)}`)}),iN(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 lN(n){let{newText:t,deletedBoxes:e}=p3(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;sN(i).reverse().forEach(l=>{t=Ir(t,s,[{insert:" ",attributes:l.boxData}],null)})}),t}function cN(n,t,e){let{newText:o,deletedBoxes:r}=p3(n);return o=nN(o,t,e),o=rN(o,r,t),o=lN(o),o}const Sn=y("history-doc");function Tn(n){d(Sn,!1,"no local actions for history doc")}class aN extends vi{constructor(e,o){super();u(this,"doc");u(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(Sn,r,`no container data: ${e}`);const i=r[o];return d(Sn,i,`no block data: ${o}`),i}localUpdateBlockText(){Tn()}localUpdateBlockData(){Tn()}localInsertBlock(){Tn()}localDeleteBlock(){Tn()}localInsertChildContainer(){Tn()}localDeleteChildContainers(){Tn()}uploadResource(){Tn()}async addResources(e){Tn()}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(){Tn()}broadcastMessage(){Tn()}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new Wl}destroy(){this.clearCallbacks()}transformBlockIndex(e,o,r){const i=this.doc.blocks[e];d(Sn,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(Sn,!1,`invalid block index: ${o}, blocks: ${JSON.stringify(i)}`),d(Sn,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(Sn,!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 h;return(h=a.onInsertBlock)==null?void 0:h.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(Sn,!c.deleted,`block has already deleted: ${e}/${o}`);const a=c.text;d(Sn,a,`no text for block: ${JSON.stringify(c)}`);const h=cN(a,r,i);c.text=h,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(Sn,!c.deleted,`block has already deleted: ${e}/${o}`);const a=Y.default(c);a.updatedBy=i,r.delete.forEach(h=>delete a[h]),Object.entries(r.insert).forEach(([h,f])=>{a[h]=f}),l[s]=a,this.callbacks.forEach(h=>{var f;return(f=h.onUpdateBlockData)==null?void 0:f.call(h,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:C3}=S;function li(n,t){return t==="insert"?C3("version.insert",{name:n.displayName}):C3("version.delete",{name:n.displayName})}function ir(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 dN{renderText(t,e,o){if(!o.box&&o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=ir(t,o.insertedBy);return{classes:["history-inserted-text"],attributes:{"history-inserted-by":r.displayName,"data-op-description":li(r,"insert")},styles:{[ri]:i,[ii]:s}}}return{}}renderBlock(t,e,o){if(o.deletedBy){const r=o.deletedBy,{flag:i,selection:s}=ir(t,r);return{classes:["history-deleted-block"],attributes:{"history-deleted-by":r.displayName,"data-op-description":li(r,"delete")},styles:{[ri]:i,[ii]:s}}}if(o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=ir(t,r);return{classes:["history-inserted-block"],attributes:{"history-inserted-by":r.displayName,"data-op-description":li(r,"insert")},styles:{[ri]:i,[ii]:s}}}return{}}updateBlock(t,e,o,r){if(r.deletedBy){const i=r.deletedBy,{flag:s,selection:l}=ir(t,i);M(o,"history-deleted-block"),Ua(o,{"history-inserted-by":i.displayName,"data-op-description":li(i,"delete")}),Va(o,{[ri]:s,[ii]:l});return}if(r.insertedBy){const i=r.insertedBy,{flag:s,selection:l}=ir(t,i);M(o,"history-inserted-block"),Ua(o,{"history-inserted-by":i.displayName,"data-op-description":li(i,"insert")}),Va(o,{[ri]:s,[ii]:l})}}}const b3=y("history-deleted-box");function uN(n,t,e,o){const r=o;d(b3,r.text,`no text for text box data: ${JSON.stringify(o)}`),d(b3,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}=ir(n,s);i.setAttribute("history-deleted-by",s.displayName),i.setAttribute("data-op-description",li(s,"delete")),i.style.setProperty(ri,l),i.style.setProperty(ii,c)}const hN={boxType:"history-deleted-box",updateBoxContent:uN},ve=y("version-dialog");class fN{constructor(t,e){u(this,"editor");u(this,"dialog",null);u(this,"oldViewer",null);u(this,"versionOptions");u(this,"versionList",null);u(this,"actionButtons",null);u(this,"provider");u(this,"components");u(this,"handleClose",()=>{var t;(t=this.dialog)==null||t.hide()});u(this,"handlePlay",()=>{var e;d(ve,this.versionList,"The versionList did not render");const t=(e=this.versionList)==null?void 0:e.activeVersion;d(ve,t,`The version: ${t} is invalid`),this.viewVersion(t,{play:!0,speed:150})});u(this,"handleRevert",async()=>{var e,o;d(ve,this.versionList,"The versionList did not render");const t=(e=this.versionList)==null?void 0:e.activeVersion;d(ve,t,`The version: ${t} is invalid`),await this.versionHelper.revertVersion(t.version),(o=this.dialog)==null||o.hide()});u(this,"handleSelectVersion",t=>{d(ve,t,`The version: ${t} is invalid`),this.viewVersion(t)});u(this,"viewVersion",async(t,e={play:!1,speed:1e3})=>{var C,v,w;this.oldViewer&&(this.oldViewer.destroy(),this.oldViewer=null),d(ve,this.versionList,"The versionList did not render"),d(ve,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 E=this.versionOptions.onWillChangeVersion(this.editor,t,i,s);E!=null&&E.hideOps&&(l=!0)}let c,a;if(l)c=await this.versionHelper.getVersion(t.version),a=[];else{const E=await this.versionHelper.getHistoryData(t.version,r);c=E.doc,a=E.historyData}const{editorElement:h}=this.components;h.innerHTML="";const f=new aN(c,this.editor),m=this.provider.createHistoryEditor(h,f);m.editorBlockRenders.registerRender(new dN),m.editorBoxes.registerBoxClass(hN),M(m.rootElement,a3.HISTORY);try{await Y_(f,this.versionHelper,a,e)}finally{this.oldViewer=m}(w=this.versionOptions)!=null&&w.onVersionChanged&&this.versionOptions.onVersionChanged(this.editor,m,t,i,s)});u(this,"setShowOps",t=>{var e;if(this.versionOptions){this.versionOptions.hideOps=!t;const o=(e=this.versionList)==null?void 0:e.activeVersion;d(ve,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(ve,this.editor.doc.getVersionHelper,"Can not get getVersionHelper from doc");const t=this.editor.doc.getVersionHelper();return d(ve,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 K_({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 W_({versions:t,useCreatedBy:(l=this.versionOptions)==null?void 0:l.useCreatedBy,onSelectVersion:this.handleSelectVersion,getMarkColor:c=>{const{flag:a}=ir(this.editor,c);return a}});i.render(o),this.versionList=i}initViewVersion(){var t;if((t=this.versionOptions)!=null&&t.initSelectedVersion){d(ve,this.versionList,"The versionList did not render");const{initSelectedVersion:e}=this.versionOptions,o=this.versionList.selectVersionByVersionNum(e);d(ve,o,`The version: ${o} is invalid`),this.viewVersion(o)}else{d(ve,this.versionList,"The versionList did not render");const e=this.versionList.activeVersion;d(ve,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 q_(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 mN(n,t,e){const o=n.addCustom("version-dialog",()=>new fN(n,t));return o.show(e),{setShowOps:o.setShowOps}}const GF="",gN=y("heading-collapse");function Z1(n){var e;const t=Number.parseInt((e=n.getAttribute("data-style-heading"))!=null?e:"",10);return d(gN,t,"not a heading block"),t}function He(n){return!!n.getAttribute("data-style-heading")}function pN(n){return!lt(n,"heading-collapsed")}function sr(n){return lt(n,"heading-collapsed")}function v3(n){if(gt(n))return!1;const e=j(n);return Ct(e)}const CN=y("heading-collapse");function Y1(n){d(CN,He(n),"not a heading block");const t=[],e=Z1(n);let o=ht(n);for(;o&&!(He(o)&&Z1(o)<=e);)t.push(o),o=ht(o);return t}function k3(n,t){if(!Uo(t))return;n.selection.selectBlock(t,0),Y1(t).forEach(o=>{vm(o)}),M(t,"heading-collapsed")}function ci(n,t){Y1(t).forEach(o=>{km(o)}),F(t,"heading-collapsed")}function bN(n,t){pN(t)?k3(n,t):ci(n,t)}const vN=[zu,Uu,Vu,qu,Wu,Gu,Zu,Yu];function kN(n){const t=b("button",["heading-collapse-button"],null);return t.setAttribute(`data-editor-tooltip-${n.clientId}`,"Collapse / Expand"),t.innerHTML=Fu,t}function y3(n){return Wc(n).querySelector("button.heading-collapse-button")}function w3(n,t){y3(t)||v3(t)||!Uo(t)||f1(t,kN(n),-1)}function yN(n){var t;(t=y3(n))==null||t.remove()}function B3(n,t){Wc(t).querySelector("button.heading-collapse-button")||w3(n,t)}function wN(n){const t=Z1(n),e=b("button",["heading-marker"],null);return e.innerHTML=vN[t-1],e}function E3(n){return Wc(n).querySelector("button.heading-marker")}function Q1(n){E3(n)||v3(n)||!Uo(n)||f1(n,wN(n),1)}function I3(n){const t=E3(n);t==null||t.remove()}function x3(n){I3(n),He(n)&&Q1(n)}class BN{handleDrop(t,e,o,r){if(sl(e)||!He(e)||!sr(e))return;const i=Y1(e);i.unshift(e);const s=i.reverse();let l=null;return t.doc.beginBatchUpdate(),s.forEach((c,a,h)=>{const f=t.getBlockData(c),m=Fo(t.editorBlocks,t.doc.toJSON(),f),C=t.insertDocAt(o,r,m)[0];a===h.length-1&&(l=C)}),t.doc.endBatchUpdate(),t.doc.beginBatchUpdate(),s.forEach(c=>{t.deleteBlock(c)}),t.doc.endBatchUpdate(),l&&k3(t,l),!0}}const EN=y("heading-collapse");class IN{constructor(t){u(this,"handleLoad",()=>{this.showCollapseButtons()});u(this,"handleHoverBlock",(t,e)=>{e&&(F(e,"hovering-heading"),He(e)&&Ct(j(e))&&(Q1(e),sr(e)||yN(e))),t&&He(t)&&Ct(j(t))&&(M(t,"hovering-heading"),I3(t),w3(this.editor,t))});u(this,"handleClick",(t,e)=>{const o=wi(e,"button.heading-collapse-button");if(!o)return;const r=z(o);!r||(d(EN,He(r),"not a heading block"),bN(this.editor,r),B3(this.editor,r))});this.editor=t,t.addListener("load",this.handleLoad),t.addListener("click",this.handleClick),_t.get(t).addListener("change",this.handleHoverBlock),this.showCollapseButtons(),setTimeout(()=>{xs.get(t).addHandler(new BN)})}showCollapseButtons(){const t=Ot(this.editor.rootContainer).filter(He);t.length!==0&&(t[0]===Kt(this.editor.rootContainer)&&t.splice(0,1),t.forEach(Q1))}destroy(){this.editor.removeListener("load",this.handleLoad),this.editor.removeListener("click",this.handleClick)}}function da(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);sr(e)&&ci(n,e),sr(o)&&ci(n,o)}function xN(n){da(n);const t=n.getFocusedBlock();!He(t)||sr(t)&&ci(n,t)}function SN(n){da(n);const t=n.getFocusedBlock();if(!He(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===Z(n,t)&&sr(t)&&ci(n,t)}function TN(n){da(n);const t=n.getFocusedBlock();if(!He(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===0&&sr(t)&&ci(n,t)}class DN{handleBeforeKeyDown(t,e){return Za(e.key)&&da(t),e.key==="Enter"?(xN(t),!1):e.key==="Delete"?(SN(t),!1):(e.key==="Backspace"&&TN(t),!1)}}class LN{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(!He(o)){e&&e.delete.includes("heading")&&x3(o);return}lt(o,"hovering-heading")&&B3(this.editor,o),x3(o)}},100)}}function MN(n){return!!n.heading}function S3(n){var e;const t=n.heading;return(e=Number.parseInt(`${t}`,10))!=null?e:1}function T3(n,t){var e;return{parentNode:t,children:[],text:wt((e=n.text)!=null?e:[]),level:S3(n),block:n}}class As{constructor(){u(this,"nodes",[])}appendBlock(t){const e=this.findParent(S3(t),this.nodes);e?e.children.push(T3(t,e)):this.nodes.push(T3(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 As,o=t.blocks.root;for(let r=0;r<o.length;r++){const i=o[r];MN(i)&&e.appendBlock(i)}return e}}class lr extends Wt.TypedEmitter{constructor(e){super();u(this,"toc",new As);u(this,"updateToc",Qt.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 lr(e))}static get(e){return e.getCustom("editor-toc")}updateTocNow(){this.toc=As.buildToc(this.editor.doc.toJSON()),this.emit("change",this.editor,this.toc)}}const ZF="";function RN(n){return n.nodes.length===0?!0:n.nodes.length>1?!1:n.nodes[0].children.length===0}function K1(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);K1(s,e.children)}})}function ON(n,t){const e=wi(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 D3(n,t,e){if(F(t,"loading"),t.innerHTML="",RN(e)){b("div",["toc-empty-message"],t,"No toc");return}e.nodes.length===1?K1(t,e.nodes[0].children):K1(t,e.nodes),wu(n,"toc-click-handler",()=>{n.addListener("click",ON)})}class AN{constructor(t){u(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&&D3(t,i,e)})});this.editor=t,lr.register(t).addListener("change",this.handleUpdateToc)}destroy(){lr.register(this.editor).removeListener("change",this.handleUpdateToc)}get toc(){return lr.register(this.editor).toc}}function _N(n,t){const e=b("div",["editor-toc-container"],t),r=n.addCustom("init-editor-toc",()=>new AN(n)).toc;r.nodes.length===0?M(e,"loading"):D3(n,e,r)}function NN(n,t,e,o){return o==="markdown"?"[toc]":""}function PN(n,t,e){const{data:o}=e;if(!o||o.embedType!=="toc"||!H(n,t))return null;const r={};return{blockData:{id:N(),type:"embed",embedType:"toc",embedData:r}}}const L3={embedType:"toc",createEmbedContent:_N,convertTo:NN,convertFrom:PN};function $N(n){return!!n.getAttribute("data-style-heading")}function J1(n,t){return $N(t)&&Z(n,t)>0}function jN(n){const t=_n(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=z(i[s]);if(l&&n.rootContainer.contains(l))return l}o+=10}return null}function X1(n,t){let e=t;for(;e&&!J1(n,e);)e=ht(e);return e}function M3(n){if(gt(n))return!1;const e=j(n);return Ct(e)}function ua(n,t){let e=t;for(;e&&!J1(n,e);)e=gt(e),e&&M3(e)&&(e=null);return e}const HN=.3;class FN extends Wt.TypedEmitter{constructor(e){super();u(this,"scrollContainer");u(this,"scrollEventTarget");u(this,"scrollStatus",{curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null});u(this,"handleScroll",Qt.default(()=>{const e={curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null};let o=jN(this.editor);if(o&&(o=ul(o)),!o||!this.scrollContainer){this.setStatus(e);return}if(M3(o)&&(o=ht(o)),!o){this.setStatus(e);return}if(J1(this.editor,o)){e.curHeadingBlock=o,e.previousHeadingBlock=ua(this.editor,o),e.nextHeadingBlock=X1(this.editor,o),this.setStatus(e);return}const r=this.scrollContainer.getBoundingClientRect(),i=X1(this.editor,o);if(i){const l=i.getBoundingClientRect();if(l.top>r.top&&l.top<r.top+r.height*HN){e.curHeadingBlock=i,e.previousHeadingBlock=ua(this.editor,i),e.nextHeadingBlock=X1(this.editor,i),this.setStatus(e);return}e.nextHeadingBlock=i}const s=ua(this.editor,o);s&&(e.curHeadingBlock=s,e.previousHeadingBlock=ua(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=_n(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 zN{constructor(t,e){u(this,"suggest");u(this,"onShow",(t,e,o,r)=>{const i=this.editor.getBlockByIndex(e,o);if(!Uo(i)){const s=z(j(i));if(s&&it(s)==="code")return!1}return!0});u(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)});u(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})));this.editor=t,this.options=e,this.suggest=new nh(t,{id:"editor-mention",trigger:["@"],autoDeleteTrigger:!0,showLoading:!0,onShow:this.onShow,onClickItem:this.onClickItem,queryItems:this.queryItems})}destroy(){}}y("mathjax-box");function UN(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 VN(n,t,e){}const R3={boxType:"mention",updateBoxContent:UN,handleClickBox:VN};function qN(n){return Vn("list-block-mention",S.t("list.mention.tooltip"),Pw,[],n.clientId)}class WN{constructor(t){u(this,"mentionButton");u(this,"handleHoveringBlock",t=>{var e;!this.editor.isWritable()||(t&&this.shouldBlockShowMention(t)?At(t).appendChild(this.mentionButton):(e=this.mentionButton)==null||e.remove())});u(this,"handleMouseDown",(t,e)=>{e.preventDefault(),e.stopPropagation();const o=z(this.mentionButton);if(!o||!H(t,o))return;const r=t.selection.range.focus;if(!r.isSimple())return;let i;t.selection.focusedBlock!==o?i=Z(t,o):i=r.offset,setTimeout(()=>{const s=t.insertTextToBlock(o,i,"@");i+=1;const l=wt(fe(s,i).left);this.editor.selection.selectBlock(o,i),this.editor.focus(),t.getCustom("mention").suggest.popup(o,i,l,"@")})});u(this,"destroy",()=>{_t.get(this.editor).removeListener("change",this.handleHoveringBlock)});this.editor=t,this.mentionButton=qN(t),_t.get(this.editor).addListener("change",this.handleHoveringBlock),t.domEvents.addEventListener(this.mentionButton,"mousedown",this.handleMouseDown)}shouldBlockShowMention(t){if(!H(this.editor,t)||!at(t))return!1;const e=je(t);return!(e==="ordered"||e==="unordered")}}const YF="",GN={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"}},ZN={templates:{title:"Choose a template",create:"New template",choose:"All templates",customizedMark:"Custom"}};S.mergeLang({"zh-CN":GN,"en-US":ZN});const QF="",YN="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjEyMCIgaGVpZ2h0PSIxMjAiIHZpZXdCb3g9IjAgMCAxMjAgMTIwIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cmVjdCB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTQ4IDU5QzQ4IDU0LjU4MTcgNTEuNTgxNyA1MSA1NiA1MUg5M0M5OC41MjI4IDUxIDEwMyA1NS40NzcyIDEwMyA2MVY4OEMxMDMgOTEuODY2IDk5Ljg2NiA5NSA5NiA5NUg1NkM1MS41ODE3IDk1IDQ4IDkxLjQxODMgNDggODdWNTlaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGQ9Ik0xOCA2NEMxOCA2Mi4zNDMxIDE5LjM0MzEgNjEgMjEgNjFINTZDNjAuNDE4MyA2MSA2NCA2NC41ODE3IDY0IDY5VjgzQzY0IDg1LjIwOTEgNjIuMjA5MSA4NyA2MCA4N0gyNkMyMS41ODE3IDg3IDE4IDgzLjQxODMgMTggNzlWNjRaIiBmaWxsPSIjRUFFNEY2Ii8+CjxyZWN0IHg9IjI0IiB5PSIzMSIgd2lkdGg9IjY1IiBoZWlnaHQ9IjUwIiByeD0iNSIgZmlsbD0iIzk5QzdGMiIvPgo8cmVjdCB4PSIzMy41IiB5PSI0MyIgd2lkdGg9IjQ2IiBoZWlnaHQ9IjUiIHJ4PSIyLjUiIGZpbGw9IndoaXRlIi8+CjxyZWN0IHg9IjMzLjUiIHk9IjU0IiB3aWR0aD0iNDYiIGhlaWdodD0iNSIgcng9IjIuNSIgZmlsbD0id2hpdGUiLz4KPHJlY3QgeD0iMjQiIHk9IjMxIiB3aWR0aD0iNjUiIGhlaWdodD0iNTAiIHJ4PSI1IiBzdHJva2U9IiNGOEY4RjgiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik01MCA4NS4yNjhDNTMuODI2MyA4My4wNTg5IDU1LjEzNzMgNzguMTY2MiA1Mi45MjgyIDc0LjMzOThMNjMuMzIwNSA2OC4zMzk4QzY4Ljg0MzMgNzcuOTA1NyA2NS41NjU4IDkwLjEzNzUgNTYgOTUuNjYwNEM0Ni40MzQxIDEwMS4xODMgMzQuMjAyMyA5Ny45MDU3IDI4LjY3OTQgODguMzM5OEwzOS4wNzE3IDgyLjMzOThDNDEuMjgwOSA4Ni4xNjYyIDQ2LjE3MzYgODcuNDc3MiA1MCA4NS4yNjhaIiBmaWxsPSIjQUI5M0RDIi8+CjxyZWN0IHg9IjU5IiB5PSI2NSIgd2lkdGg9IjQyIiBoZWlnaHQ9IjI4IiByeD0iNSIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTYzIDg4VjczLjA4MDhDNjMgNzEuNzA5NiA2My4zNjE0IDcwLjY4NjcgNjQuMDg0MSA3MC4wMTJDNjQuODI4NyA2OS4zMzczIDY1Ljg1OCA2OSA2Ny4xNzIgNjlIOTIuODYwOUM5NS42MjAzIDY5IDk3IDcwLjM2MDMgOTcgNzMuMDgwOFY4OEg5My41MTc5TDg3LjM3NDkgODAuNjIyQzg3LjA5MDIgODAuMzE3MyA4Ni43NjE3IDgwLjA4ODggODYuMzg5NCA3OS45MzY0Qzg2LjAxNzEgNzkuNzg0MSA4NS42NDQ4IDc5LjcwNzkgODUuMjcyNSA3OS43MDc5Qzg0LjkwMDIgNzkuNzA3OSA4NC41Mjc5IDc5Ljc4NDEgODQuMTU1NiA3OS45MzY0QzgzLjgwNTIgODAuMDg4OCA4My40NTQ4IDgwLjMxNzMgODMuMTA0MyA4MC42MjJMNzYuNzMxNCA4Ni4yMzcxTDc0LjIwMTkgODMuOTUxOUM3My42MzI1IDgzLjQyOTYgNzMuMDA4NCA4My4xNjg0IDcyLjMyOTUgODMuMTY4NEM3MS42NTA2IDgzLjE2ODQgNzEuMDM3NCA4My40Mjk2IDcwLjQ4OTkgODMuOTUxOUw2Ni40NDkzIDg4SDYzWk03NC40NjQ3IDgwLjYyMkM3NS4zNjI2IDgwLjYyMiA3Ni4xNDAxIDgwLjI5NTUgNzYuNzk3MSA3OS42NDI2Qzc3LjQ3NiA3OC45ODk3IDc3LjgxNTUgNzguMjE3MSA3Ny44MTU1IDc3LjMyNDdDNzcuODE1NSA3Ni40MTA3IDc3LjQ3NiA3NS42MzggNzYuNzk3MSA3NS4wMDY5Qzc2LjE0MDEgNzQuMzU0IDc1LjM2MjYgNzQuMDE2NiA3NC40NjQ3IDczLjk5NDhDNzMuNTQ0OSA3My45NTEzIDcyLjc1NjUgNzQuMjY2OSA3Mi4wOTk1IDc0Ljk0MTZDNzEuNDQyNSA3NS42MTYzIDcxLjExNCA3Ni40MTA3IDcxLjExNCA3Ny4zMjQ3QzcxLjExNCA3OC4yMTcxIDcxLjQ0MjUgNzguOTg5NyA3Mi4wOTk1IDc5LjY0MjZDNzIuNzU2NSA4MC4yOTU1IDczLjU0NDkgODAuNjIyIDc0LjQ2NDcgODAuNjIyWiIgZmlsbD0iI0Y3RDA3RiIvPgo8Y2lyY2xlIGN4PSI5NSIgY3k9IjQyIiByPSIyIiBzdHJva2U9IiM1MEMzOTgiIHN0cm9rZS13aWR0aD0iMiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTk0Ljc1MDEgMjQuNDY4N0wxMDAuNzgxIDI3LjkxNDlMOTQuNzE5IDMxLjQxNDlMOTQuNzUwMSAyNC40Njg3WiIgc3Ryb2tlPSIjNUNBNUVBIiBzdHJva2Utd2lkdGg9IjEuOCIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwNSAzOEMxMDUgMzguNTUyMyAxMDUuNDQ4IDM5IDEwNiAzOUMxMDYuNTUyIDM5IDEwNyAzOC41NTIzIDEwNyAzOFYzNkgxMDlDMTA5LjU1MiAzNiAxMTAgMzUuNTUyMyAxMTAgMzVDMTEwIDM0LjQ0NzcgMTA5LjU1MiAzNCAxMDkgMzRIMTA3VjMyQzEwNyAzMS40NDc3IDEwNi41NTIgMzEgMTA2IDMxQzEwNS40NDggMzEgMTA1IDMxLjQ0NzcgMTA1IDMyVjM0SDEwM0MxMDIuNDQ4IDM0IDEwMiAzNC40NDc3IDEwMiAzNUMxMDIgMzUuNTUyMyAxMDIuNDQ4IDM2IDEwMyAzNkgxMDVWMzhaIiBmaWxsPSIjQUI5M0RDIi8+Cjwvc3ZnPgo=",QN="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgdmlld0JveD0iMCAwIDM3MiAyNzkiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMF8xMjU2XzM3MTY4KSI+CjxyZWN0IHdpZHRoPSIzNzIiIGhlaWdodD0iMjc5IiBmaWxsPSJ3aGl0ZSIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIzOS41NzQ3IiB3aWR0aD0iMTE4LjcyMyIgaGVpZ2h0PSIxNS44Mjk4IiByeD0iNy45MTQ4OSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI3MS4yMzM5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI5MS4wMjE1IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIxMTAuODA5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSI0MC41NjM4IiB5PSIxMzUuNTQzIiB3aWR0aD0iMjkwLjg3MiIgaGVpZ2h0PSIxMDAuOTE1IiByeD0iMi45NjgwOSIgc3Ryb2tlPSIjRUFGM0ZDIiBzdHJva2Utd2lkdGg9IjEuOTc4NzIiLz4KPHBhdGggZD0iTTM5LjU3NDUgMTM4LjUxMUMzOS41NzQ1IDEzNi4zMjUgNDEuMzQ2MyAxMzQuNTUzIDQzLjUzMTkgMTM0LjU1M0gzMjguNDY4QzMzMC42NTQgMTM0LjU1MyAzMzIuNDI2IDEzNi4zMjUgMzMyLjQyNiAxMzguNTExVjE1Mi4zNjJIMzkuNTc0NVYxMzguNTExWiIgZmlsbD0iI0Q2RTlGQSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTg3LjA2MzcgMTY5LjE4MUM4Ny4wNjM3IDE2Ny41NDIgODguMzkyNiAxNjYuMjEzIDkwLjAzMTggMTY2LjIxM0gzMTcuNTg1QzMxOS4yMjQgMTY2LjIxMyAzMjAuNTUzIDE2Ny41NDIgMzIwLjU1MyAxNjkuMTgxQzMyMC41NTMgMTcwLjgyIDMxOS4yMjQgMTcyLjE0OSAzMTcuNTg1IDE3Mi4xNDlIOTAuMDMxOEM4OC4zOTI2IDE3Mi4xNDkgODcuMDYzNyAxNzAuODIgODcuMDYzNyAxNjkuMTgxWk0xMDQuODcyIDE5Mi45MjZDMTA0Ljg3MiAxOTEuMjg2IDEwNi4yMDEgMTg5Ljk1NyAxMDcuODQgMTg5Ljk1N0gzMTcuNTg1QzMxOS4yMjQgMTg5Ljk1NyAzMjAuNTUzIDE5MS4yODYgMzIwLjU1MyAxOTIuOTI2QzMyMC41NTMgMTk0LjU2NSAzMTkuMjI0IDE5NS44OTQgMzE3LjU4NSAxOTUuODk0SDEwNy44NEMxMDYuMjAxIDE5NS44OTQgMTA0Ljg3MiAxOTQuNTY1IDEwNC44NzIgMTkyLjkyNlpNMTA3Ljg0IDIxMy43MDJDMTA2LjIwMSAyMTMuNzAyIDEwNC44NzIgMjE1LjAzMSAxMDQuODcyIDIxNi42N0MxMDQuODcyIDIxOC4zMDkgMTA2LjIwMSAyMTkuNjM4IDEwNy44NCAyMTkuNjM4SDMxNy41ODVDMzE5LjIyNCAyMTkuNjM4IDMyMC41NTMgMjE4LjMwOSAzMjAuNTUzIDIxNi42N0MzMjAuNTUzIDIxNS4wMzEgMzE5LjIyNCAyMTMuNzAyIDMxNy41ODUgMjEzLjcwMkgxMDcuODRaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNTEuNDQ2OCAxNjkuMTgxQzUxLjQ0NjggMTY3LjU0MiA1Mi43NzU2IDE2Ni4yMTMgNTQuNDE0OSAxNjYuMjEzSDYwLjM1MUM2MS45OTAzIDE2Ni4yMTMgNjMuMzE5MSAxNjcuNTQyIDYzLjMxOTEgMTY5LjE4MUM2My4zMTkxIDE3MC44MiA2MS45OTAzIDE3Mi4xNDkgNjAuMzUxIDE3Mi4xNDlINTQuNDE0OUM1Mi43NzU2IDE3Mi4xNDkgNTEuNDQ2OCAxNzAuODIgNTEuNDQ2OCAxNjkuMTgxWk01MS40NDY4IDE5Mi45MjZDNTEuNDQ2OCAxOTEuMjg2IDUyLjc3NTcgMTg5Ljk1NyA1NC40MTQ5IDE4OS45NTdINjAuMzUxMUM2MS45OTAzIDE4OS45NTcgNjMuMzE5MSAxOTEuMjg2IDYzLjMxOTEgMTkyLjkyNkM2My4zMTkxIDE5NC41NjUgNjEuOTkwMyAxOTUuODk0IDYwLjM1MTEgMTk1Ljg5NEg1NC40MTQ5QzUyLjc3NTcgMTk1Ljg5NCA1MS40NDY4IDE5NC41NjUgNTEuNDQ2OCAxOTIuOTI2Wk01NC40MTQ5IDIxMy43MDJDNTIuNzc1NyAyMTMuNzAyIDUxLjQ0NjggMjE1LjAzMSA1MS40NDY4IDIxNi42N0M1MS40NDY4IDIxOC4zMDkgNTIuNzc1NyAyMTkuNjM4IDU0LjQxNDkgMjE5LjYzOEg2MC4zNTExQzYxLjk5MDMgMjE5LjYzOCA2My4zMTkxIDIxOC4zMDkgNjMuMzE5MSAyMTYuNjdDNjMuMzE5MSAyMTUuMDMxIDYxLjk5MDMgMjEzLjcwMiA2MC4zNTExIDIxMy43MDJINTQuNDE0OVoiIGZpbGw9IiM5OUM3RjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik02OS4yNTU0IDE2OS4xODFDNjkuMjU1NCAxNjcuNTQyIDcwLjU4NDMgMTY2LjIxMyA3Mi4yMjM1IDE2Ni4yMTNINzguMTU5N0M3OS43OTg5IDE2Ni4yMTMgODEuMTI3OCAxNjcuNTQyIDgxLjEyNzggMTY5LjE4MUM4MS4xMjc4IDE3MC44MiA3OS43OTg5IDE3Mi4xNDkgNzguMTU5NyAxNzIuMTQ5SDcyLjIyMzVDNzAuNTg0MyAxNzIuMTQ5IDY5LjI1NTQgMTcwLjgyIDY5LjI1NTQgMTY5LjE4MVpNNjkuMjU1NCAxOTIuOTI2QzY5LjI1NTQgMTkxLjI4NiA3MC41ODQyIDE4OS45NTcgNzIuMjIzNSAxODkuOTU3SDc4LjE1OTZDNzkuNzk4OSAxODkuOTU3IDgxLjEyNzcgMTkxLjI4NiA4MS4xMjc3IDE5Mi45MjZDODEuMTI3NyAxOTQuNTY1IDc5Ljc5ODkgMTk1Ljg5NCA3OC4xNTk2IDE5NS44OTRINzIuMjIzNUM3MC41ODQyIDE5NS44OTQgNjkuMjU1NCAxOTQuNTY1IDY5LjI1NTQgMTkyLjkyNlpNNzIuMjIzNSAyMTMuNzAyQzcwLjU4NDIgMjEzLjcwMiA2OS4yNTU0IDIxNS4wMzEgNjkuMjU1NCAyMTYuNjdDNjkuMjU1NCAyMTguMzA5IDcwLjU4NDIgMjE5LjYzOCA3Mi4yMjM1IDIxOS42MzhINzguMTU5NkM3OS43OTg5IDIxOS42MzggODEuMTI3NyAyMTguMzA5IDgxLjEyNzcgMjE2LjY3QzgxLjEyNzcgMjE1LjAzMSA3OS43OTg5IDIxMy43MDIgNzguMTU5NiAyMTMuNzAySDcyLjIyMzVaIiBmaWxsPSIjRjdEMDdGIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNOTAuMDMxOCAxODkuOTU4Qzg4LjM5MjYgMTg5Ljk1OCA4Ny4wNjM3IDE5MS4yODYgODcuMDYzNyAxOTIuOTI2Qzg3LjA2MzcgMTk0LjU2NSA4OC4zOTI2IDE5NS44OTQgOTAuMDMxOCAxOTUuODk0SDk1Ljk2OEM5Ny42MDcyIDE5NS44OTQgOTguOTM2MSAxOTQuNTY1IDk4LjkzNjEgMTkyLjkyNkM5OC45MzYxIDE5MS4yODYgOTcuNjA3MiAxODkuOTU4IDk1Ljk2OCAxODkuOTU4SDkwLjAzMThaTTkwLjAzMTkgMjEzLjcwMkM4OC4zOTI3IDIxMy43MDIgODcuMDYzOCAyMTUuMDMxIDg3LjA2MzggMjE2LjY3Qzg3LjA2MzggMjE4LjMwOSA4OC4zOTI3IDIxOS42MzggOTAuMDMxOSAyMTkuNjM4SDk1Ljk2ODFDOTcuNjA3MyAyMTkuNjM4IDk4LjkzNjIgMjE4LjMwOSA5OC45MzYyIDIxNi42N0M5OC45MzYyIDIxNS4wMzEgOTcuNjA3MyAyMTMuNzAyIDk1Ljk2ODEgMjEzLjcwMkg5MC4wMzE5WiIgZmlsbD0iIzkxRDlCRSIvPgo8L2c+CjxkZWZzPgo8Y2xpcFBhdGggaWQ9ImNsaXAwXzEyNTZfMzcxNjgiPgo8cmVjdCB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgZmlsbD0id2hpdGUiLz4KPC9jbGlwUGF0aD4KPC9kZWZzPgo8L3N2Zz4K",O3=y("templates");function tf(n){const t=n.rootElement.querySelector(":scope .editor-templates");if(!t)return null;const e=t.querySelector(":scope .editor-templates-cards");return d(O3,e,"no card container"),{root:t,cardContainer:e}}function KN(n){const t=tf(n);if(t)return t.cardContainer.innerHTML="",t;const e=b("div",["editor-templates"],n.rootElement);b("div",["editor-templates-title"],e,S.t("templates.title"));const o=b("div",["editor-templates-cards"],e);return{root:e,cardContainer:o}}function A3(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:QN;c.src!==m&&(c.src=m)},c.onload=()=>{c.style.display=""};const a=b("div",["editor-template-name"],s),h=b("span",[],a,e);return i!=null&&i.showTemplateTitleAttr&&h.setAttribute("title",e),s.onclick=()=>r(s),s}function JN(n,t){return t.thumbnailUrl?t.thumbnailUrl:n.doc.buildResourceUrl("thumbnail.png")}function XN(n,t){const e=JN(n,t);return A3(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 tP(n,t){return A3(n,t,S.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 eP(n,t){var f,m;const e=(f=n.options.componentsOptions)==null?void 0:f.templates;if(!e)return;const r=Gt(n.rootContainer).getBoundingClientRect().width;let i=1;const s=YN,l=tf(n);if(l){if(t!=null&&t.reset){const C=Array.from(l.cardContainer.children),v=l.cardContainer.firstElementChild;if(d(O3,v,"no first card"),lt(v,"new")||lt(v,"more"))return;const w=window.getComputedStyle(v),E=parseFloat(w.marginLeft),L=parseFloat(w.marginRight),x=v.getBoundingClientRect().width+E+L;i=Math.floor(r/x);const A=Math.max(1,i-1-1),P=C.length-1;C.forEach((V,nt)=>{nt>A&&nt<P?V.style.display="none":(nt>=P&<(V,"more"),V.style.display="")})}return}const c=e.templates,{cardContainer:a}=KN(n);c.forEach((C,v)=>{const w=XN(n,C);if(v>0&&v>=i&&(w.style.display="none"),a.appendChild(w),v===0){const E=window.getComputedStyle(w),L=parseFloat(E.marginLeft),x=parseFloat(E.marginRight),O=w.getBoundingClientRect().width+L+x;i=Math.floor(r/O)-1}});const h=tP(n,s);a.appendChild(h),(m=e==null?void 0:e.onTemplateChooserStatusChanged)==null||m.call(e,n,a,"visible")}const _3=Qt.default(eP,50);function nP(n){var o,r;const t=tf(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 oP(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 ef(n,t){oP(n.doc.toJSON())?_3(n,t):(_3.cancel(),nP(n))}class _s{constructor(t,e){u(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 _s(t,e))}}const KF="",Co=y("encrypted-block");function rP(n,t,e,o,r){const i=r,s=no(o,"div"),l=_s.getState(n,i);if(l.decrypted)n.createChildContainer(t,s,i.children[0]),M(o,"decrypted");else{M(o,"encrypted");const c=At(o),a=b("div",["password-container"],c),h=b("input",[],a);h.type="text",h.onkeydown=f=>{if(f.key==="Enter"){const m=h.value;if(i.password===Ci.default(`${i.owner}-${m}`)){l.setDecrypted(),n.reloadBlock(o);const C=vd(n,n.getBlockById(i.id));C&&(n.selection.selectBlock(C,0),n.focus())}}}}return s}function iP(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t)||!mn(r))return null;const i=r;if(n.getBlockData(t).children[0]!==U(i))return null;const l=bt(t,U(i));return new Qe(n,{anchor:l,focus:l})}function sP(n,t,e,o){if(_s.getState(n,n.getBlockData(t)).decrypted)return null;if(o==="ArrowDown"||o==="ArrowRight"){const s=ht(t);return s?$(s,Z(n,s),"end"):$(t,1,"end")}const i=gt(t);return $(i||t,0,"home")}function lP(n,t){return n.getBoundingClientRect()}function cP(n,t,e,o){if(e.isSimple()){d(Co,o.isSimple(),"from is simple position but to is not simple position"),Co.debug("full select table"),M(t,"full-selected");return}d(Co,!o.isSimple(),"from is complex position but end is simple position");const r=e,i=o;d(Co,r.blockId===i.blockId,"only allow update one table selection"),d(Co,r.childContainerId===i.childContainerId,"only one container");const s=n.getBlockData(t),l=n.getContainerById(s.children[0]);M(l,"selected")}function aP(n){n.rootContainer.querySelectorAll('[data-type="editor-block"][data-block-type="encrypted"]').forEach(t=>{F(t,"full-selected"),t.querySelectorAll("selected").forEach(e=>{F(e,"selected")})})}function dP(n,t){const e=n.getBlockData(t);return _s.getState(n,e).decrypted?[n.getContainerById(e.children[0])]:[]}function uP(n,t,e,o,r){return null}function hP(n,t,e,o){d(Co,e.blockId===o.blockId,"only allow select in single block"),d(Co,G(t)===e.blockId,"only allow select in single block");const r=n.getBlockData(t);return d(Co,e.childContainerId===r.children[0],"only one container"),[n.getContainerById(r.children[0])]}function fP(n){return{name:"EncryptedBlock",insertBlockCommandItems:[{id:"insert-encrypted-block",name:"Encrypted Block"}],async handleInsertEmptyBlock(t,e){const o=Cn(t.doc),r={id:N(),type:"encrypted",children:[o],owner:t.doc.getUser().userId,ownerDisplayName:t.doc.getUser().displayName,password:Ci.default(`${t.doc.getUser().userId}-1234`)},i=t.doc.getContainerBlocks(o)[0];return t.insertBlock(e.containerId,e.blockIndex,r,Lt(t,i.id,0))}}}const mP={blockType:"encrypted",blockKind:"complex",enableKeyboardSelect:!0,createBlockContent:rP,getBlockTextLength:()=>1,getRangeFromPoint:iP,moveCaret:sP,getCaretRect:lP,updateSelection:cP,clearSelection:aP,getChildContainers:dP,getNextContainer:uP,getSelectedContainers:hP,getOptions:fP};function gP(n,t,e){const o=Fi(n,t,{components:{blocks:[gs,bs,mP],decorators:[new ks],embeds:[Kc,r1,E1,I1,x1,zh,S1,W1,q1],boxes:[Dc],options:{...e.componentsOptions}}});return o.readonly=!0,o}class pP{constructor(t){this.createOptions=t}createHistoryEditor(t,e){return gP(t,e,this.createOptions)}}y("create-editor");function N3({root:n,childDoc:t,doc:e}){t.uploadResource=e.uploadResource.bind(e),t.buildResourceUrl=e.buildResourceUrl.bind(e);const o=Fi(n,t,{shortcuts:[Vl],components:{blocks:[gs,bs],decorators:[new ks],embeds:[O4,Kc,r1,E1,I1,x1,zh,S1,W1,q1],boxes:[Dc,R3],options:{}}});return o.input.addHandler(new $c),o.input.addHandler(new T1(o)),o.input.addHandler(new FA(o)),o}function CP(n,t){const e=Array.from(n.rootContainer.querySelectorAll(`[comment-${t.toLocaleLowerCase()}="${t}"]`)),o=new Set;e.forEach(r=>{const i=z(r);i&&o.add(i)}),o.forEach(r=>{zA(n,r,t)})}class bP{constructor(t){u(this,"listeners",new Set);u(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&&CP(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 N3({root:t,childDoc:e,doc:this.doc})}}class vP{constructor(t,e){u(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 $u(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 N3({root:t,childDoc:e,doc:this.localDoc})}}const kP={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"}}},yP={placeholder:{common:{title:"Enter a title",readonlyTitle:"Enter a title",content:'Click "+", or enter "/" to insert components quickly'},local:{readonlyTitle:"Untitled"}}};S.mergeLang({"zh-CN":kP,"en-US":yP});const nf=y("create-editor"),P3=[Kc,r1,E1,I1,x1,zh,S1,W1,q1,O4,L3,x_];async function wP(n,t){var s,l,c,a,h,f,m,C,v,w,E,L;d(nf,n,"app does not exists"),t.lang&&S.setLang(t.lang);const e=t.onReauth?async()=>{var P;const x=t.user.userId,O=t.docId,A=await((P=t.onReauth)==null?void 0:P.call(t,x,O,t.permission));return{userId:x,docId:O,permission:t.permission,appId:t.appId,token:A,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 ts.load(o),i=Fi(n,r,{id:t.id,components:{blocks:[gs,bs,d1,y5],commandProviders:[new hh,...((s=t.components)==null?void 0:s.commandProviders)||[]],decorators:[new ks,new Hu],embeds:[...P3,...((l=t.components)==null?void 0:l.embeds)||[]],boxes:[Dc,R3,J6,...((c=t.components)==null?void 0:c.boxes)||[]],insertions:[Pd],blockHooks:[new I4,...((a=t.components)==null?void 0:a.blockHooks)||[]],textRenders:[new W6,new qI],options:{...t.componentsOptions}},shortcuts:[hD,GL,Kh,E6,WI,qh,Vl],colors:["#338FE5","#24B47E","#F0A100","#E52727","#9678D3","#2CB2AE","#EB6414","#8AAB3F"]});if(i.editorCommandProviders.registerCommandProvider(new xn(i)),i.input.addHandler(new DN),i.input.addHandler(new $c),i.input.addHandler(new xx),i.input.addHandler(new HL),i.input.addHandler(new Cs(i,{headingLevel:1,titlePlaceholder:S.t("placeholder.common.title"),contentPlaceholder:S.t("placeholder.common.content"),readonlyTitlePlaceholder:S.t("placeholder.common.readonlyTitle"),addPlaceholderToAllCurrentEmptyBlock:!0})),i.input.addHandler(new Lc(i,(h=t.componentsOptions)==null?void 0:h.quickMenu)),i.input.addHandler(new T1(i)),i.input.addHandler(new g6(i)),i.doc.registerCallback(new LN(i)),i.addCustom("remote-cursor",()=>new t0(i)),i.addCustom("block-menu",x=>new D4(x)),i.addCustom("editor-tooltip",()=>new Vh(i)),t!=null&&t.enableComments&&i.addCustom("editor-comments",x=>new q6(x,new bP(x))),i.addCustom("create-options",()=>new Mf(i,t)),i.addCustom("drop-target",()=>new xs(i)),i.addCustom("list-to-mindmap",()=>new xc(i)),i.addCustom("list-to-mention",()=>new WN(i)),(f=t.componentsOptions)!=null&&f.mention){const x=t.componentsOptions.mention;i.addCustom("mention",()=>new zN(i,x))}if(i.addCustom("heading-collapse",()=>new IN(i)),Wr.register(i),xs.register(i),lr.register(i),(C=(m=t.componentsOptions)==null?void 0:m.remoteCarets)!=null&&C.onUserChanged){const x=(w=(v=t.componentsOptions)==null?void 0:v.remoteCarets)==null?void 0:w.onUserChanged;i.doc.getRemoteUsers().on("change",O=>{x(i,O)})}return(L=(E=t.componentsOptions)==null?void 0:E.templates)!=null&&L.templates.length&&(i.addListener("docChanged",()=>{ef(i)}),i.addListener("resize",()=>{ef(i,{reset:!0})}),setTimeout(()=>{ef(i)},100)),i.doc.registerCallback({onError:async x=>{if(x.code==="ResetDoc"){nf.error(`reset doc: ${x.message}`);const O=await ts.load(o);i.doc.reset(O)}}}),i}function BP(n){return n.toJSON!==void 0}async function EP(n,t,e){var i,s;d(nf,n,"app does not exists");const o=BP(t)?t:new yu(t,{serverUrl:e.serverUrl||""});e.lang&&S.setLang(e.lang);const r=Fi(n,o,{id:e.id,components:{blocks:[gs,bs,d1,y5],commandProviders:[new hh],decorators:[new ks,new Hu],embeds:[...P3,...((i=e.components)==null?void 0:i.embeds)||[]],boxes:[Dc,J6],insertions:[Pd],blockHooks:[new I4],textRenders:[new W6],options:{...e.componentsOptions}},shortcuts:[Kh,E6,qh,Vl]});return r.editorCommandProviders.registerCommandProvider(new xn(r)),r.input.addHandler(new $c),r.input.addHandler(new Cs(r,{headingLevel:1,titlePlaceholder:S.t("placeholder.common.title"),contentPlaceholder:S.t("placeholder.common.content"),readonlyTitlePlaceholder:S.t("placeholder.local.readonlyTitle"),addPlaceholderToAllCurrentEmptyBlock:!0})),r.input.addHandler(new Lc(r,(s=e.componentsOptions)==null?void 0:s.quickMenu)),r.input.addHandler(new T1(r)),r.input.addHandler(new g6(r)),r.addCustom("block-menu",l=>new D4(l)),r.addCustom("editor-tooltip",()=>new Vh(r)),e!=null&&e.enableComments&&r.addCustom("editor-comments",l=>new q6(l,new vP(l,o))),Wr.register(r),r}function IP(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 pP(i);return mN(n,s,t)}g.tippy=x9,g.AuthError=tc,g.AuthHeader=Xi,g.AutoScroll=fm,g.BaseURLHeader=ec,g.BlockResizer=Pc,g.BrBox=zg,g.CodeBlock=bs,g.CodeLineBlock=d1,g.CodeTextDecorator=ks,g.DefaultShortcuts=Vl,g.DocIdError=Sy,g.DragDrop=qf,g.DrawioEmbed=Kc,g.EditorBlocks=Km,g.EditorBoxes=Vg,g.EditorCommandProviders=g2,g.EditorComplexBlockPosition=Ye,g.EditorComplexSelectionRange=Qe,g.EditorDecorators=Zg,g.EditorEmbeds=Xm,g.EditorInsertions=Gg,g.EditorSimpleBlockPosition=Ut,g.EditorSimpleSelectionRange=se,g.EmbedBlock=eg,g.EnforceWithDocumentTitleHandler=Cs,g.EventCallbacks=vi,g.FILL_CHAR=H8,g.FileExtError=Ty,g.HeadingBlockScrollListener=FN,g.InputtingInsertion=qg,g.LocalDoc=yu,g.Logger=ur,g.MIN_DISTANCE_THRESHOLD=Uf,g.ManualMenu=Wo,g.MarkdownInputHandler=$c,g.MaxUserError=Ou,g.OnesEditorAutoSuggest=nh,g.OnesEditorCustomDataWrapper=Mf,g.OnesEditorHoveringBlock=_t,g.OnesEditorQuickMenu=Lc,g.OnesEditorToc=As,g.OnesEditorTocProvider=lr,g.OnesEditorToolbar=Wr,g.OnesEditorTooltip=Vh,g.PermissionError=xy,g.Popup=ic,g.RemoteCarets=t0,g.RemoteCaretsDecorator=Hu,g.RemoteCaretsInsertion=Pd,g.RemoteUsers=Wl,g.RequestReloadError=Ji,g.RichText=oe,g.ShareDBDoc=ts,g.SimpleCache=Of,g.StandardEmbedBlockCommands=n1,g.TEXT_STYLE_BACKGROUND_COLOR_PREFIX=Od,g.TEXT_STYLE_COLOR_PREFIX=Rd,g.TableBlock=gs,g.TableBlockCommandProvider=hh,g.TableShortcuts=Kh,g.TextBlock=Ai,g.TextBox=Fg,g.TextStyleShortcuts=qh,g.TocEmbed=L3,g.ZERO_WIDTH_SPACE_CHAR=ki,g.addAttribute=yl,g.addClass=M,g.addCommentToBlock=e1,g.addDays=p7,g.addMonths=g7,g.animateScrollTo=Bi,g.applyPlaceholderToBlock=jc,g.assert=d,g.blockToDoc=Xd,g.blockToHtml=$d,g.blockToMarkdown=Yg,g.blockToText=Ll,g.blocksToDoc=gb,g.clearAllSelection=Fm,g.clientType=St,g.cloneBlock=Fo,g.cloneChildContainer=Zd,g.cloneDoc=Yd,g.cloneText=Mg,g.commentToShareDbComment=ju,g.compareElement=Xs,g.comparePosition=Cd,g.complexBlockAdjustSelectionPos=ml,g.complexBlockFindNearestChildBlock=ig,g.complexBlockGeFirstSimpleChild=vd,g.complexBlockGetAllChildContainers=Me,g.complexBlockGetBottomChildContainers=rg,g.complexBlockGetLastSimpleChild=yr,g.complexBlockGetSelectedContainers=kr,g.complexBlockGetTopChildContainers=og,g.containerToDoc=tu,g.continuousScroll=hm,g.convertBlockFrom=hl,g.copyBlockAttributes=rp,g.createBlockAnchor=_o,g.createBlockContentElement=no,g.createBlockElement=wm,g.createBlockSimpleDocRange=Tl,g.createBlockSimpleRange=Lt,g.createBoxContentElement=Im,g.createBoxElement=Bm,g.createBoxOp=wg,g.createChildContainer=$m,g.createComplexBlockPosition=bt,g.createComplexDocPos=$g,g.createComplexDocRange=z8,g.createContainer=Ag,g.createContainerElement=cd,g.createDeleteOps=bg,g.createEditor=Fi,g.createEditorSelectionRange=Vt,g.createElement=b,g.createEmptyContainer=Cn,g.createEmptyDoc=ro,g.createEmptyTextBlockData=Il,g.createExpandedRange=Ks,g.createIconButton=hr,g.createImage=Af,g.createInsertOps=kl,g.createInsertionContentElement=Tm,g.createInsertionElement=xm,g.createLocalEditor=EP,g.createOnesEditor=wP,g.createRange=_f,g.createRichText=Oi,g.createRootContainer=Pm,g.createSimpleBlockPosition=$,g.createSimpleDocPos=Pg,g.createTextBlockData=jn,g.createTextButton=Xo,g.createTextOp=_e,g.createTextWithReplaceSoftReturn=Td,g.daysAfter=Xa,g.deleteText=Ld,g.diffDays=C7,g.disablePageScroll=im,g.docToHtml=nb,g.docToHtmlFragment=Qg,g.docToMarkdown=ob,g.docToText=Kg,g.downloadObjectToFile=v1,g.downloadSvgToString=_4,g.editLink=bc,g.editorAddComment=VA,g.editorAddTextAttribute=bp,g.editorAutoInsertBlock=ip,g.editorBreakTextBlock=Dr,g.editorClearCompositionText=op,g.editorClearSelectedContents=Wd,g.editorCopyBlock=iu,g.editorDeleteBlock=Vd,g.editorDeleteBlockText=Fd,g.editorDeleteBlockWithoutChildren=Ud,g.editorDeleteChildContainer=db,g.editorDeleteChildContainers=ap,g.editorFocusToBlock=Gd,g.editorFocusToEnd=wp,g.editorGetBlockData=io,g.editorGetBlockText=we,g.editorGetBlockTextEx=Rl,g.editorGetBoxData=Jg,g.editorHandleKeyboardEvent=Qp,g.editorInsertBlock=Tr,g.editorInsertBoxToBlock=ep,g.editorInsertDoc=pp,g.editorInsertDocAt=Qd,g.editorInsertText=Hd,g.editorInsertTextToBlock=tp,g.editorInsertTextToBlockEx=jd,g.editorMergeTextBlock=dp,g.editorRangeClearColor=kp,g.editorRangeGetColor=Kd,g.editorRangeSetColor=vp,g.editorRemoveTextAttribute=fb,g.editorReplaceBlockText=Pl,g.editorReplaceContainer=Cp,g.editorRunOnce=wu,g.editorSelectEnd=yp,g.editorSetTextColor=Lr,g.editorShowFindDialog=YO,g.editorUpdateBlockData=$l,g.editorUpdateCompositionText=np,g.editorUpdateEmbedData=mp,g.enablePageScroll=sm,g.escapeHtmlText=Hf,g.escapeRegExp=nd,g.escapeSpace=J9,g.executeBlockCommand=Qm,g.executeEmbedBlockCommand=Ym,g.executeRangeCommand=m2,g.fileToDataUrl=nl,g.findAllText=Nd,g.findInsertionById=Sm,g.findPrevSimpleBlockBeforeChildContainer=ng,g.findTarget=wi,g.format=Ja,g.formatBytes=mm,g.formatDate=Cm,g.fragmentToHtml=lm,g.fromBase64=el,g.fromBase64ToBlob=nm,g.fromBase64ToUint8Array=d7,g.fromDocRange=oo,g.fromNowString=ed,g.genId=N,g.getAllChildBlocks=yd,g.getAllQuickMenuItems=Uh,g.getAllSelectedBlocks=Ke,g.getAttributesAt=Bl,g.getBlockBackground=ym,g.getBlockByIndex=fr,g.getBlockCaretRect=Ze,g.getBlockClass=kt,g.getBlockClassByType=br,g.getBlockClientRects=Oo,g.getBlockCommandsWithHook=fd,g.getBlockContent=rt,g.getBlockId=G,g.getBlockIndex=K,g.getBlockKind=Ge,g.getBlockMinWidth=Um,g.getBlockOptions=S7,g.getBlockPath=Ro,g.getBlockProperties=Wm,g.getBlockStyles=I7,g.getBlockTextLength=Z,g.getBlockTools=At,g.getBlockType=it,g.getBoxContent=id,g.getBoxId=Em,g.getBoxTypeFromElement=xi,g.getChildBlockCount=Ve,g.getChildBlocks=Ot,g.getChildOffset=Br,g.getColorFromAttributes=_d,g.getComplexBlockClass=ye,g.getContainerBlockPath=Am,g.getContainerBlocks=Rm,g.getContainerBlocksElement=dl,g.getContainerById=Cr,g.getContainerId=U,g.getContainerMinWidth=ud,g.getContainerToolsElement=k7,g.getContainerWidth=qm,g.getDistanceSquare=fn,g.getElementOffset=yi,g.getEmbedType=Le,g.getExistsBlockTools=al,g.getExistsContainerById=Lm,g.getFileExt=am,g.getFirstChildBlock=Kt,g.getFirstClientRect=Js,g.getHeadingMenuOptions=Tc,g.getHorizontalPadding=Fa,g.getInsertionContent=sd,g.getLastChildBlock=Gt,g.getLastClientRect=Io,g.getLogger=y,g.getNextBlock=ht,g.getNextValidOffset=Er,g.getNextVisibleBlock=pr,g.getOpAt=Eg,g.getOpLength=Md,g.getParentBlock=z,g.getParentBox=rd,g.getParentContainer=j,g.getPrevBlock=gt,g.getPrevValidOffset=Po,g.getPrevVisibleBlock=gr,g.getRangeCommands=h2,g.getRootBlock=ul,g.getScrollContainer=_n,g.getSpecialBlockCommands=Gm,g.getStandardEmbedBlockProperties=o1,g.getTextBlockChild=gl,g.getTextBlockClass=Hm,g.getTextBlockContentChildTextLength=Oe,g.getTextBlockContentChildType=sg,g.getTextBlockContentChildren=$n,g.getTextLength=ce,g.getTextOpLength=Bd,g.getTextWidth=rl,g.getToolbar=Cc,g.handleBlockElementUpdated=Vm,g.hasAltOnly=r7,g.hasClass=lt,g.hasCtrlOrCmd=Jf,g.hasCtrlOrCmdOnly=o7,g.hideBlock=vm,g.htmlToFragment=ol,g.i18n=S,g.injectStyle=zf,g.insertEmptyBlock=D7,g.insertEmptyEmbedBlock=md,g.insertText=Ir,g.intersectionCommands=kk,g.isBackspace=tm,g.isBlock=mr,g.isBox=od,g.isCJK=Yf,g.isChildContainer=We,g.isChildNode=vt,g.isCollapsedRange=Ng,g.isComplexBlockPosition=pd,g.isComplexKindBlock=ct,g.isContainer=mn,g.isControlEvent=To,g.isDelete=s7,g.isDraggingFiles=sl,g.isEmbedBlock=De,g.isEmptyContainer=hd,g.isEmptyDoc=xl,g.isEmptyTextBlock=yt,g.isEmptyTextBlockWithoutCompositionText=ps,g.isEnterOnly=Xf,g.isEscape=Ya,g.isFirefox=Ga,g.isFirstChildBlockInComplexBlock=n8,g.isHighSurrogate=W9,g.isInBlock=ld,g.isInBlockTools=Si,g.isLetter=Zf,g.isLowSurrogate=Ha,g.isMatchShortcut=An,g.isMoveForward=e7,g.isNavigationEvent=t7,g.isNavigationKey=Kf,g.isNodeRemoved=Pf,g.isNumber=Gf,g.isPrintableKey=Za,g.isRootBlock=Uo,g.isRootContainer=Ct,g.isSafari=Qf,g.isSameDay=td,g.isShiftEnter=i7,g.isShiftTab=c7,g.isShortcutEvent=n7,g.isSimpleBlock=x7,g.isSimpleBlockPosition=vr,g.isSimplePos=_g,g.isSimpleRange=Sl,g.isSpace=tl,g.isTab=l7,g.isTextBlockContentBoxChild=Re,g.isTextBlockContentChild=Di,g.isTextBlockContentInsertionChild=Pn,g.isTextBlockContentTextChild=Li,g.isTextKindBlock=H,g.isTextKindBlockType=Ti,g.isToday=gm,g.isValidOffset=me,g.isVisibleBlock=cl,g.isYesterday=pm,g.loadJs=$f,g.loadJsPromise=xo,g.lockers=Ue,g.mergeCommands=pc,g.mergeDocs=Ho,g.mergeOps=Dd,g.mergeText=N8,g.multiSplitText=ag,g.parseShortcut=em,g.patchNode=Ii,g.pointInRect=So,g.rangeAddAttribute=wl,g.rangeGetTextColor=Lg,g.rangeRemoveAttribute=xr,g.rangeSetTextColor=Sg,g.rangeTransformText=Ig,g.registerDragDrop=qa,g.removeAttribute=Ad,g.removeClass=F,g.removeLastBr=R8,g.removePlaceholderFromBlock=e4,g.removeStyle=Ff,g.replaceAll=b7,g.replaceAllCaseInsensitive=v7,g.replaceAllText=Og,g.replaceText=El,g.requestDownload=ll,g.scrollable=um,g.selectFile=Lo,g.selectedBlockToDoc=Hl,g.selectionToDoc=Fl,g.setAttributes=Ua,g.setClipboardData=il,g.setClipboardDataByEvent=m7,g.setColorToAttributes=Tg,g.setDataset=za,g.setDefaultCursor=Ei,g.setStyles=Va,g.shareDBCommentToDocObject=$u,g.shareDBDocCommentToComment=J2,g.shortcutToDisplayText=a7,g.showBlock=km,g.showDocVersions=IP,g.splitText=fe,g.splitToThree=Jt,g.stringToDataUrl=om,g.stringToObjectUrl=Ka,g.subText=dg,g.textNodeOffsetFromPoint=Nf,g.toBase64URL=Do,g.toPlainText=wt,g.trimChar=Wa,g.unicodeLength=G9,g.unicodeSubstr=Z9,g.updateBlockSelection=zm,g.updateOpAttributes=Rg,g.updateTextBlockContent=G8,g.updateUrl=Qa,Object.defineProperties(g,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|