@ones-editor/editor 0.0.3-beta.167 → 0.0.3-beta.169

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -24,7 +24,7 @@ Available method signatures are:
24
24
  `:""}const p6={boxType:"br",updateBoxContent:_I,convertTo:FI},C6=S("editor-boxes");class A6{constructor(t){m(this,"boxes",new Map);this.editor=t}registerBoxClass(t){const e=t.boxType,o=this.boxes.get(e);g(C6,!o,`duplicated box type: ${e}`),this.boxes.set(e,t)}getBoxClass(t){const e=this.boxes.get(t);return g(C6,e,`unknown box type: ${t}`),e}createBox(t,e){const o=qC(e),r=ZC(o);return this.getBoxClass(e.type).updateBoxContent(this.editor,o,r,e),o}}function PI(n,t,e,o){const r=o,{width:i,height:s,src:l}=r,a=["editor-box-image"];r.link&&a.push("editor-box-image-link");const d=w("img",a,e);i&&(d.style.width=`${i}px`),s&&(d.style.height=`${s}px`),d.src=n.doc.buildResourceUrl(l)}const b6={boxType:"image",updateBoxContent:PI},NI="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIGZpbGw9InJnYigxNzgsIDE4OCwgMjA1KSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0ibTE3IDE1IDEuNTUgMS41NWMtLjk2IDEuNjktMy4zMyAzLjA0LTUuNTUgMy4zN1YxMWgzVjloLTNWNy44MkMxNC4xNiA3LjQgMTUgNi4zIDE1IDVjMC0xLjY1LTEuMzUtMy0zLTNTOSAzLjM1IDkgNWMwIDEuMy44NCAyLjQgMiAyLjgyVjlIOHYyaDN2OC45MmMtMi4yMi0uMzMtNC41OS0xLjY4LTUuNTUtMy4zN0w3IDE1bC00LTN2M2MwIDMuODggNC45MiA3IDkgN3M5LTMuMTIgOS03di0zbC00IDN6TTEyIDRjLjU1IDAgMSAuNDUgMSAxcy0uNDUgMS0xIDEtMS0uNDUtMS0xIC40NS0xIDEtMXoiPjwvcGF0aD4KPC9zdmc+Cg==";function $I(n,t,e){W(e,"editor-box-anchor"),pm(NI,[],e)}const v6={boxType:"anchor",updateBoxContent:$I};function HI(n,t,e,o){w("span",[],e,o.text)}const y6={insertionType:"inputting",updateInsertionContent:HI},k6=S("editor-insertion");class w6{constructor(t){m(this,"insertions",new Map);this.editor=t}registerInsertionClass(t){const e=t.insertionType,o=this.insertions.get(e);g(k6,!o,`duplicated insertion type: ${e}`),this.insertions.set(e,t)}getInsertionClass(t){const e=this.insertions.get(t);return g(k6,e,`unknown insertion type: ${t}`),e}createInsertion(t,e){const o=QC(e.type,e.id),r=JC(o);return this.getInsertionClass(e.type).updateInsertionContent(this.editor,o,r,e),o}}class jI{constructor(t){m(this,"cursors",new Map);m(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=YC(this.editor,e);r&&et(r,"active"),this.cursors.delete(e)}})},1e3)}destroy(){clearInterval(this.timer)}}function UI(n,t,e,o){var l;const r=o;Date.now()-r.time<5*1e3&&(n.addCustom("active-cursors",d=>new jI(d)).add(r.id,r.time),W(t,"active")),w("span",[],e,"|").setAttribute("data-cursor-name",r.name),t.style.setProperty("--cursor-color",n.getColor((l=r.rainbowIndex)!=null?l:0))}const wg={insertionType:"remote-cursor",updateInsertionContent:UI};class B6{constructor(t){m(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=mt.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:a}=s;l&&Array.from(l.entries()).forEach(([d,h])=>{const p=r.get(d);p?p.push(...h):r.set(d,h)}),a&&(o=mt.default(a))}}}),{insertions:r,text:o}}}const Bg=S("editor-input");class zI{constructor(t,e){m(this,"editor");m(this,"composing",!1);m(this,"callbacks");m(this,"inputElement");m(this,"handleDocumentClick",t=>{const e=this.editor.rootContainer,o=t.target;if(o&&e.contains(o)&&!Ls(o)){this.editor.emit("focus",this.editor),this.callbacks.onFocus(),this.editor.input.focus();return}this.editor.emit("blur",this.editor),this.callbacks.onBlur()});m(this,"handleDocumentSelectionChange",()=>{setTimeout(()=>{var e;const t=(e=document.getSelection())==null?void 0:e.focusNode;t&&this.editor.contains(t)&&!Ls(t)||(this.editor.emit("blur",this.editor),this.callbacks.onBlur())},100)});m(this,"handleEditorSelectionChanged",()=>{const e=!this.editor.isWritable();this.inputElement.readOnly=e});m(this,"handleReadonlyChanged",()=>{this.handleEditorSelectionChanged()});m(this,"handleCompositionstart",t=>{!this.editor.isWritable()||(this.composing=!0,this.callbacks.onCompositionStart(t))});m(this,"handleCompositionend",t=>{this.composing=!1,this.callbacks.onUpdateCompositionText(t,this.inputElement.value,!0),this.inputElement.value=""});m(this,"handleInput",t=>{if(t instanceof InputEvent&&!!t.data){if(this.editor.readonly||!this.editor.isWritable()){this.inputElement.value="";return}this.composing?this.callbacks.onUpdateCompositionText(t,t.data,!1):(this.callbacks.onInsertText(t,t.data),this.inputElement.value="")}});m(this,"handleKeyDown",t=>{if(!this.composing){if(this.callbacks.onKeyDown(t)){t.preventDefault(),t.stopPropagation();return}!this.editor.isWritable()||setTimeout(()=>{this.composing||(this.inputElement.value="")})}});m(this,"handleCopy",t=>{this.callbacks.onCopy(t)});m(this,"handleCut",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}this.callbacks.onCut(t),Bg.debug("on cut")});m(this,"handlePaste",t=>{if(this.editor.readonly){t.stopPropagation(),t.preventDefault();return}this.callbacks.onPaste(t)});m(this,"handlePasteText",(t,e)=>{this.callbacks.onPasteText(t,e)});this.editor=t,this.callbacks=e;const o=w("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("click",this.handleDocumentClick),document.addEventListener("selectionchange",this.handleDocumentSelectionChange),this.editor.addListener("selectionChanged",this.handleEditorSelectionChanged),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}destroy(){this.callbacks.destroy(),document.removeEventListener("click",this.handleDocumentClick),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(),Ke.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){g(Bg,t===this.editor,"invalid editor"),this.callbacks.defaultInsertText(t,e,o,r,i)}defaultHandleKeydown(t,e){return g(Bg,t===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(t,e)}}function E6(n){const t=n.rootElement,e=t.getBoundingClientRect(),o=ys(t),r=window.innerWidth,i=window.innerHeight,s=e.left<0?0:e.left,l=e.top<0?0:e.top,a=e.right>r?r:e.right,d=e.bottom>i?i:e.bottom,h=(s+a)/2,p=(l+d)/2,A=0-e.left+h,v=0-e.top+p,B=n.input.inputElement;B.style.left=`${A/o}px`,B.style.top=`${v/o}px`}const Eg=S("editor-caret");class VI{constructor(t){m(this,"editor");m(this,"caretElem");m(this,"handleReadOnlyChanged",()=>{this.update()});this.editor=t,this.caretElem=w("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 je))return!1;const e=this.editor.getBlockById(t.blockId);return!!tt(this.editor,e)}update(){if(oC(this.editor.rootElement))return;const t=this.caretElem;if(this.hasCaret())t.style.display="";else{t.style.display="none",E6(this.editor);return}const{range:e}=this.editor.selection;g(Eg,e.isCollapsed,"range is not collapsed");const o=e.start;g(Eg,o instanceof je,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);g(Eg,tt(this.editor,r),"only text kind block can has caret");let i;const s=r.querySelector("span.inputting-insertion");s?(i=bs(s),i=new DOMRect(i.right,i.top,1,i.height)):i=zn(r,o);const l=this.editor.contentElement.getBoundingClientRect(),a=i.left-l.left,d=i.top-l.top;t.style.left=`${a}px`,t.style.top=`${d}px`,t.style.height=`${i.height}px`;const h=this.editor.input.inputElement;h.style.left=`${a}px`,h.style.top=`${d+i.height-24}px`,Ke.isMobileSafari&&(h.style.left=`${a-4}px`,h.style.height=`${i.height}px`);const A=oo(r,{horizontal:!0}).getBoundingClientRect(),v=A.left-l.left,B=v+A.width;a<v||a>B?(E6(this.editor),t.style.display="none"):t.style.display=""}}function WI(n){n4(n),n.selection.range.getSelectedBlocks().forEach(t=>o4(n,t.block,t.start,t.end))}const qI=S("editor-dom");function x6(n){return oo(n.rootContainer).clientHeight}function GI(n){return n.getFirstBlock().getBoundingClientRect().top}function ZI(n){return n.getLastBlock().getBoundingClientRect().bottom}function xg(n){const e=oo(n.rootContainer).getBoundingClientRect(),o=e.x<0?0:e.x,r=e.y<0?0:e.y,i=e.right>window.innerWidth?window.innerWidth:e.right,s=e.bottom>window.innerHeight?window.innerHeight:e.bottom;return new DOMRect(o,r,i-o,s-r)}function QI(n,t){const e=xg(n),o=n.getBlockById(t.blockId),i=To(n,o,t);return ks(e,i.x,i.y)&&ks(e,i.right,i.bottom)}function I6(n,t){const e=xg(n),o=t.getBoundingClientRect();return o.top>=e.top&&o.top<=e.bottom||o.bottom<=e.bottom&&o.bottom>=e.top}function YI(n,t){const e=xg(n),o=t.getBoundingClientRect();return ks(e,o.x,o.y)||ks(e,o.right,o.bottom)}function JI(n){if(!ym(n.rootContainer)){qI.warn("editorScrollIntoView: editor is not visible");return}const t=n.rootContainer.getBoundingClientRect();if(t.height<1&&t.width<1)return;const e=n.selection,o=e.range.focus;if(!o.isSimple()){const h=o,p=n.getContainerById(h.childContainerId);YI(n,p)||p.scrollIntoView();return}if(e.range.start.blockId===e.range.end.blockId){const h=n.getBlockById(e.range.start.blockId);if(Le(h)&&I6(n,h)||Lt(n,h)&&I6(n,h))return}const r=o,i=n.getBlockById(r.blockId);if(QI(n,r))return;const s=To(n,i,r),l=i.getBoundingClientRect(),a=le(i),d=w("div",["editor-block-anchor"],a);d.style.top=`${s.top-l.top}px`,km(d,{elementToScroll:oo(n.rootContainer)}),setTimeout(()=>{d.remove()},200)}function KI(n,t){if(t.isCollapsed())return!1;const e=Se(n.rootContainer),o=Ge(n.rootContainer),{start:r,end:i}=t;return r.blockId===it(e)&&r.offset===0&&i.blockId===it(o)&&i.offset===ut(n,o)}const T6=S("range-in-block");function D6(n,t){const e=t.getEditor(),o=e.getBlockById(t.start.blockId),r=e.getBlockById(t.end.blockId),i=o===n||Kt(n,o),s=r===n||Kt(n,r);return!!(i||s)}function S6(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=ce(t);if(i){for(;i&&!o.has(it(i));)i=ce(i);g(T6,i,"no prev block while deleting a block"),r=ye(n,i,ut(n,i))}else{const s=Zt(t);g(T6,s,"no prev and next block while deleting a block"),r=ye(n,s,0)}return r}const XI=S("block-to-html");function Ig(n,t,e,o){const r=Ms(n,t.type);if(r.convertTo)return r.convertTo(n,t,e,"html",o);if(r.blockKind!=="text")return`[${t.type}]`;g(XI,t.text,"no text");const i=re(t.text);return`<div>${lC(i)}</div>`}const L6=S("block-to-text");function tT(n,t,e){let o="";return t.forEach(r=>{if(g(L6,typeof r.insert=="string","invalid op"),r.attributes&&r.attributes.box===!0){const i=r.attributes,s=n.editorBoxes.getBoxClass(i.type);if(s!=null&&s.convertTo){o+=s.convertTo(n,i,e,"text");return}if(r.attributes.text){o+=r.attributes.text;return}o+=`[${i.type}]`}o+=r.insert}),o}function Ah(n,t,e,o){const r=Ms(n,t.type);return r.convertTo?r.convertTo(n,t,e,"text",o):r.blockKind!=="text"?`[${t.type}]`:(g(L6,t.text,"no text"),tT(n,t.text,e))}function Tg(n,t,e,o){const r=Ms(n,t.type);return r.convertTo?r.convertTo(n,t,e,"markdown",o):Ah(n,t,e,o)}function bh(n,t){return t.blocks.root.map((r,i)=>Ig(n,r,t,[{containerId:"root",blockIndex:i}])).join(`
25
25
  `)}function M6(n,t){return`<!doctype html><html><head><meta charset="utf8" /></head><body>${bh(n,t)}</body></html>`}function La(n,t){return t.blocks.root.map((r,i)=>Ah(n,r,t,[{containerId:"root",blockIndex:i}])).join(`
26
26
  `)}function Ma(n,t){const e=t.blocks.root.map((r,i)=>Tg(n,r,t,[{containerId:"root",blockIndex:i}]));return e[e.length-1]=e[e.length-1].trimEnd(),e.join(`
27
- `)}const eT=S("get-text-position");function Gl(n,t){const e=t!=null?t:n.selection.range.start;e instanceof je||g(eT,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=bt(r),s=nt(r),l=at(s),{offset:a}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:a}}const Zl=S("insert-text");function Dg(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(g(Zl,r,"no block data"),g(Zl,r.text,"no block text"),rn(r.text)===0)return g(Zl,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=ze(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function nT(n,t,e){const o=nt(t),r=at(o),i=bt(t);return Dg(n,r,i,e)}function R6(n,t,e,o,r){const i=nt(t),s=at(i),l=bt(t),a=nT(n,t,e),d=ch(e,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),mn(n,t)}function O6(n,t,e,o){const r=nt(t),i=at(r),s=bt(t),l=ch(e," ",o);return n.doc.localUpdateBlockText(i,s,l),mn(n,t)}function oT(n,t){let e=0;if(t===0)return!1;for(let o=0;o<n.length;o++){const r=n[o];g(Zl,typeof r.insert=="string","invalid text op, no insert");const i=e+ah(r);if(i===t)return!1;if(i>t)return!0;e=i}return!1}function Sg(n,t,e,o,r){const i=n.doc.getBlockData(e,o);g(Zl,i,"no block data"),g(Zl,i.text,"no block text");const s=Dg(n,e,o,r);s&&Object.keys(s).includes("link")&&(oT(i.text,r)||delete s.link);const l=ch(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),mn(n,n.getBlockById(i.id))}function Lg(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=Gl(n);Sg(n,t,e,o,r)}const vh=S("update-composition-text");function _6(n){const t=n.selection.range.start;t instanceof je||g(vh,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);g(vh,tt(n,o),"not a text kind block");const r=nt(o),i=at(r),s=bt(o),l=n.doc.getBlockData(i,s);g(vh,l,"no block data in doc"),g(vh,l.text,"no text data in text block");const a=Rt(o);rh(n,Di(o),e,a,l.text)}function F6(n){_x(n)}function Ql(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const Ra=S("delete-block-text");function Mg(n,t,e,o,r){if(!n.isBlockWritable(t))return Ra.error("block is not writable"),0;g(Ra,tt(n,t),"block is not a text kind block");const i=nt(t),s=at(i),l=bt(t),a=n.doc.getBlockData(s,l);g(Ra,a,"no block data in doc"),g(Ra,a.text,"no text data in text block");let d=e;sn(t,e)||(d=Ri(t,d));let h=e+o;g(Ra,h<=ut(n,t),`invalid offset and count: ${e}, ${o}`),sn(t,h)||(h=Fs(t,h));const p=h-d,A=W4(d,p);return n.doc.localUpdateBlockText(s,l,A,r),p}const Rg=S("break-text-block");function P6(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Yl(n,t,e,o){g(Rg,tt(n,t),`block is not a text kind block: ${Dt(t)}`),g(Rg,e>=0&&e<=ut(n,t),`invalid offset: ${e}`);const r=nt(t),i=at(r),s=bt(t),l=o!=null&&o.copyBlockAttributes?P6(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===ut(n,t))){const v=e===0?s:s+1,B={...sr(""),...l,...o==null?void 0:o.newBlockData},D=ye(n,t.id,0),T=Ql(n,i,v,B,D);return{block:t,newBlock:T}}g(Rg,sn(t,e),"not a valid offset");const a=mn(n,t),{right:d}=xn(a,e),h=rn(d);h>0&&Mg(n,t,e,h);const p={...sr(d),...l,...o==null?void 0:o.newBlockData},A=Ql(n,i,s+1,p,ye(n,p.id,0));return{block:t,newBlock:A}}const rT=S("prepare-insert-new-block");function iT(n,t,e){if(t&&e!==void 0&&e!==null){const d=n.getContainerById(t),h=ve(d);return g(rT,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=at(nt(r)),e=bt(r),!tt(n,r))return{containerId:t,blockIndex:e+1};const s=o.offset;if(s===0||s===ut(n,r))return{containerId:t,blockIndex:s===0?e:e+1};const a=Yl(n,r,s).newBlock;return{containerId:t,blockIndex:bt(a)}}const sT=S("auto-insert-block");function N6(n,t,e,o,r,i){const s=iT(n,e,o);g(sT,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},a={anchor:l,focus:l};return Ql(n,s.containerId,s.blockIndex,t,r!=null?r:a,i)}const lT=S("delete-block");function yh(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{yh(n,i,e)})}))}function kh(n,t,e){const o=nt(t),r=at(o),i=bt(t),s=n.doc.getBlockData(r,i);return g(lT,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Ue(n,{anchor:e.start,focus:e.end})),s}function Og(n,t,e){return n.undoManager.runInGroup(()=>{const o=nt(t);Eo(o)===1&&n.insertTextBlock("",at(o),0);let r=e?Si(n,e):null;if(!r){const l=n.selection.range;D6(t,l)?r=S6(n,t):r=l}const i=kh(n,t,r),s=[];return yh(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function cT(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{yh(n,r,e)}),n.doc.localDeleteChildContainers(e)}function $6(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{yh(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const _g=S("merge-text-block");function H6(n,t,e){g(_g,tt(n,t),"only text block can be merged"),g(_g,tt(n,e),"only text block can be merged");const o=_i(n,t),r=_i(n,e),i=o.text,s=r.text;g(_g,i&&s,"block data has no text");const l=nt(t),a=at(l),d=bt(t),h=ut(n,t),p=Sg(n,s,a,d,h),A=ye(n,t,rn(i));return Og(n,e,A),p}const lr=S("clear-selected-contents");function wh(n,t){g(lr,tt(n,t.block),"not a text kind block");const{start:e,end:o}=t;g(lr,e.isSimple(),"not a simple block position"),g(lr,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;g(lr,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function j6(n,t,e){const o=at(t),r=ve(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 aT(n,t){const{block:e,start:o,end:r}=t;if(tt(n,e)){wh(n,t);return}if(Le(e)||o.isSimple()){g(lr,r.isSimple(),"invalid range");const s=nt(e),l=bt(e),a=n.insertTextBlock("",at(s),l);n.selection.selectBlock(a,0),n.deleteBlock(e);return}g(lr,Lt(n,e),"invalid block kind"),g(lr,!o.isSimple()&&!r.isSimple(),"invalid range"),Os(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{j6(n,s,{focus:l===0})})}function uT(n){if(!n.isWritable())return;const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(g(lr,e.length>0,"no selected block"),e.length===1){aT(n,e[0]);return}const o=e[0],r=o.block,i=nt(r);g(lr,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(tt(n,r)){wh(n,o);const h=ye(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(A=>n.deleteBlock(A.block)),tt(n,l)){wh(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(tt(n,l)){wh(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===Eo(i)){j6(n,i,{focus:!0});return}const a=ce(r),d=Zt(l);g(lr,a||d,"no prev or next block"),e.forEach(h=>n.deleteBlock(h.block))}function Fg(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),uT(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const dT=S("core");function U6(n,t,e){const o=nt(t),r=at(o),i=bt(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),mn(n,t)}function z6(n,t,e){if(!n.isBlockWritable(t)){dT.error("block is not writable");return}const o=n.getBlockText(t),r=ln.diff(o,e);U6(n,t,r)}function Bh(n,t,e){const o=mn(n,t),r=typeof e=="string"?Oi(e):e,i=ln.diff(o,r);return U6(n,t,i)}const Oa=S("update-block-data");function Eh(n,t,e,o){const r=nt(t),i=at(r),s=bt(t),l=n.doc.getBlockData(i,s),a={insert:{},delete:[]},d=new Set(Object.keys(l)),h=new Set(Object.keys(e));return d.forEach(A=>{if(!h.has(A)){if(A==="id"||A==="type"||A==="text")return;Oa.debug(`delete key: ${A}`),a.delete.push(A)}}),Object.entries(e).forEach(([A,v])=>{g(Oa,A!=="id"&&A!=="type",`invalid block data delta, ${A}`);const B=l[A];if(v==null){B!=null&&(Oa.debug(`delete key: ${A}`),a.delete.push(A));return}B!==v&&(ua.default(B,v)||A==="text"&&ln.diff(B,v).length===0||(d.has(A)?(Oa.debug(`replace key: ${A}`),a.delete.push(A)):Oa.debug(`insert key: ${A}`),a.insert[A]=v))}),n.doc.localUpdateBlockData(i,s,a,o),_i(n,t)}function V6(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function Pg(n,t,e){if(!Lt(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=jn(n,t).getChildContainers(n,t)[0],i=Se(r);Pg(n,i,e)}function $s(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 _a=S("clone-block");function Fi(n,t,e,o){const r=n.getBlockClass(e.type);if(r.blockToDoc)return r.blockToDoc(t,e,(h,p)=>(g(_a,e!==p,"invalid child block"),Fi(n,h,e,o)));let i={};const s=new Map,l=mt.default(e);l.children&&(l.children=l.children.map(h=>{const p=K(),A=t.blocks[h];g(_a,Array.isArray(A),"invalid child blocks");const v=A.map(_=>Fi(n,t,_,o)),B=$s(v),{root:D,...T}=B.blocks;return i={...i,...T},i[p]=B.blocks.root,s.set(h,p),p}));const a=Array.from(s.entries()),d=h=>{for(const p of a){const[A,v]=p;{const B=`${A}/`;if(h.startsWith(B)){const D=h.substring(B.length),T=`${v}/${D}`;return _a.debug(`replace key: ${h} -> ${T}`),T}}{const B=`${A}_`;if(h.startsWith(B)){const D=h.substring(B.length),T=`${v}_${D}`;return _a.debug(`replace key: ${h} -> ${T}`),T}}}return h};return Array.from(Object.entries(l)).forEach(([h,p])=>{const A=d(h);A!==h&&delete l.key,l[A]=p}),l.id=K(),o&&(o.blockIdMap.set(e.id,l.id),s.forEach((h,p)=>o.containerIdMap.set(p,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function Ng(n,t,e,o){const r=t.blocks[e];g(_a,Array.isArray(r),"invalid child blocks");const i=r.map(l=>Fi(n,t,l,o));return $s(i)}function $g(n,t,e){const o=t.blocks.root.map(r=>Fi(n.editorBlocks,t,r,e));return mt.default($s(o))}const W6=S("insert-doc");function q6(n,t,e,o,r){if(Lt(n,t)){W6.warn("failed to insert doc into a complex block");return}const i=$g(n,o,r),s=nt(t),l=bt(t),a=at(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var M,H,z;Object.entries(i.blocks).forEach(([q,rt])=>{q!=="root"&&n.doc.localInsertChildContainer(q,rt)});const d=i.blocks.root;if(Le(t)){n.deleteBlock(t);let q;d.reverse().forEach(rt=>{const ft=n.insertBlock(a,l,rt);q||(q=ft)}),q&&n.selection.selectBlock(q,ut(n,q));return}if(g(W6,tt(n,t),"not a text block"),he(n,t)){const q=a==="root"&&n.getBlockByIndex(a,0)===t,rt=bt(t);let ft;d.forEach((Bt,jt)=>{const Ut=n.insertBlock(a,rt+jt,Bt);jt===d.length-1&&(ft=Ut)}),ft&&n.selection.selectBlock(ft,ut(n,ft)),q&&n.deleteBlock(t);return}if(d.length===1){const q=d[0];if(ya(n,q.type)){n.insertTextToBlock(t,e,(M=q.text)!=null?M:[]);return}n.breakTextBlock(t,e),n.insertBlock(a,l+1,q);return}const h=e===ut(n,t),p=e===0,A=d[0],v=d[d.length-1];let B;!h&&!p?B=n.breakTextBlock(t,e,{forceInsertAfter:!0}):B=t;const D=p?l:l+1;h?(B=n.insertBlock(a,l+1,v),n.selection.selectBlock(B,ut(n,B))):(n.selection.selectBlock(B,0),ya(n,v.type)?n.insertTextToBlock(B,0,(H=v.text)!=null?H:[]):n.insertBlock(a,D,v));const T=n.selection.range;let _=D;ya(n,A.type)?p?(n.insertBlock(a,D,A),_+=1):n.insertTextToBlock(t,e,(z=A.text)!=null?z:[]):(n.insertBlock(a,D,A),_+=1),d.slice(1,d.length-1).reverse().forEach(q=>{n.insertBlock(a,_,q)}),n.selection.setRange(T)}),n.doc.endBatchUpdate()}function Hg(n,t,e,o,r){const i=$g(n,o,r),s=at(t),l=[];return n.undoManager.runInGroup(()=>{Object.entries(i.blocks).forEach(([d,h])=>{d!=="root"&&n.doc.localInsertChildContainer(d,h)}),i.blocks.root.reverse().forEach(d=>{const h=n.insertBlock(s,e,d);l.push(h)})}),l}function G6(n,t,e){const o=Eo(t);Hg(n,t,o,e);for(let r=0;r<o;r++){const i=Se(t);n.deleteBlock(i)}}const Fa=S("add-text-attribute");function hT(n,t,e,o){const{start:r,end:i}=e;g(Fa,r.blockId===i.blockId&&r.blockId===it(t),"invalid range"),g(Fa,o,"invalid attribute name");const s=n.getBlockText(t),l=ql(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function Z6(n,t,e,o,r){const{start:i,end:s}=e;g(Fa,i.blockId===s.blockId&&i.blockId===it(t),"invalid range"),g(Fa,o,"invalid attribute name");const l=n.getBlockText(t),a=Ia(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Jl(n,t,e,o,r){const{start:i,end:s}=e;g(Fa,i.blockId===s.blockId&&i.blockId===it(t),"invalid range");const l=n.getBlockText(t),a=e6(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Q6(n,t,e,o){const r=Lo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!tt(n,s))return;if(he(n,s)){o(n,it(s),t,e);return}const d=Ue(n,{anchor:l,focus:a});t==="color"||t==="backgroundColor"?Jl(n,s,d,t,e):(Jl(n,s,d,"color",null),Jl(n,s,d,"backgroundColor",null))})})}function Y6(n,t,e){const o=Lo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!tt(n,i))return;if(he(n,i)){(t==="clearColor"||t==="clearAll")&&e(n,it(i),"color",null),(t==="clearBackground"||t==="clearAll")&&e(n,it(i),"backgroundColor",null);return}const a=Ue(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&Jl(n,i,a,"color",null),(t==="clearBackground"||t==="clearAll")&&Jl(n,i,a,"backgroundColor",null)})})}function jg(n,t){const e=Lo(n,{simpleBlockOnly:!0}).filter(s=>tt(n,s.block));if(e.length===0)return[null,null];const o=s=>{if(ut(n,s.block)===0)return t(n,it(s.block));const l=s.start,a=s.end,d=n.getBlockText(s.block);return r6(l.offset,a.offset-l.offset,d)};let[r,i]=o(e[0]);return r===null&&i===null?[r,i]:(e.forEach(s=>{const[l,a]=o(s);l===null||r===null?r=null:r=l===r?r:null,a===null||i===null?i=null:i=a===i?i:null}),[r,i])}const Vn=S("adjust-selection-pos");function J6(n){const t=[];for(;n;){const e=nt(n);if(t.unshift(e),Xt(e))return t;const o=ot(e);g(Vn,o,"child container has not parent container"),n=o}g(Vn,!1,"should not come here: getParentContainers")}function K6(n,t){for(;t;){const e=nt(t);if(e===n)return t;const o=ot(e);g(Vn,o,"could not find parent block for a child container"),t=o}g(Vn,!1,"no parent block in specified container")}function fT(n,t){const e=J6(n),o=J6(t);g(Vn,e.length>0&&o.length>0,"block has not parent container"),g(Vn,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=K6(r,n),s=K6(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function X6(n,t){let e=ot(t);for(g(Vn,e,"element is not in a block");e;){const o=nt(e);g(Vn,Do(o),"not a child container");const r=ot(o);if(g(Vn,r,"child container has not parent block"),r===n)return o;e=r}g(Vn,!1,"failed to find parent container in complex block")}function xh(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof je&&e instanceof je?{anchor:t,focus:e}:t instanceof So&&e instanceof So?nh(n,o,t,e):null;const i=nt(o),s=nt(r);if(i===s)return t instanceof So&&(t=st(o,0,"home")),e instanceof So&&(e=st(r,ut(n,r),"end")),g(Vn,t instanceof je,"not valid position type"),g(Vn,e instanceof je,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof je&&e instanceof So){const B=n.getContainerById(e.childContainerId);if(B===i)return{anchor:e,focus:e};const D=ot(i);if(D&&D===ot(B)){const T=fe(D,at(i)),_=fe(D,at(B));return nh(n,D,T,_)}}return null}const l=Hd(o,r)>0,{newBlock1:a,newBlock2:d}=fT(o,r);if(a===d){const B=a,D=X6(B,o),T=X6(B,r);return t=fe(a,at(D)),e=fe(a,at(T)),Vn.debug(`select in complex block: ${D.id}, ${T.id}`),nh(n,B,t,e)}let h=l?ut(n,a):0;a===o&&t instanceof je&&(h=t.offset);let A=l?0:ut(n,d);return d===r&&e instanceof je&&(A=e.offset),t=st(a,h,l?"end":"home"),e=st(d,A,l?"home":"end"),{anchor:t,focus:e}}const mT=S("move-complex-block-position");function gT(n,t,e){const o=n.getBlockById(t.blockId);g(mT,Lt(n,o),"is not a complex block");const r=jn(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?fe(o,at(s)):null}const Pa=S("move-simple-block-position");function tA(n,t){const e=En(n,t,{visibleOnly:!0});g(Pa,e.length>0,"complex block has not any child container");const o=e[0];return Se(o)}function eA(n,t){const e=En(n,t,{visibleOnly:!0});g(Pa,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Ge(o)}function nA(n,t,e){const o=e?tA(n,t):eA(n,t);return Lt(n,o)?nA(n,o,e):o}function pT(n,t){const e=n.getBlockById(t.blockId);return Lt(n,e)&&t.offset===0?tA(n,e):Ss(e)}function CT(n,t){const e=n.getBlockById(t.blockId);return Lt(n,e)&&t.offset===1?eA(n,e):Ds(e)}function Ug(n){return n==="ArrowLeft"||n==="ArrowUp"}function zg(n,t,e){const o=nt(t);if(Xt(o))return null;const r=ot(o);g(Pa,r,"child container has not parent block"),g(Pa,Lt(n,r),"is not a complex block");const i=jn(n,r).getNextContainer(n,r,o,e);return i?Ug(e)?Ge(i):Se(i):zg(n,r,e)}function AT(n,t,e){const o=nt(t);if(Xt(o))return null;const r=ot(o);if(g(Pa,r,"child container has not parent block"),Ug(e)){const l=ce(r);if(l)return l}else{const l=Zt(r);if(l)return l}const i=zg(n,r,e);if(i)return i;let s=r;for(;!Xt(nt(s));)s=ot(nt(s));return Ug(e)?ce(s):Zt(s)}function bT(n,t,e){return!Lt(n,t)||jn(n,t).enableKeyboardSelect?t:nA(n,t,e==="ArrowDown"||e==="ArrowRight")}function vT(n,t,e){const o=n.getBlockById(t.blockId),i=Qt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?pT(n,t):CT(n,t);if(s||(s=zg(n,o,e),s||(s=AT(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Xt(nt(o)))return null;const l=n.insertTextBlock("",at(n.rootContainer),Eo(n.rootContainer));return st(l,0,"home")}return null}if(s=bT(n,s,e),tt(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return Gx(n,s,o,t,l);if(e==="ArrowUp")return qx(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?st(s,ut(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?st(s,0,"home"):null}function yT(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(tt(n,r))return o;const i=Zt(r);if(i)return st(i,0,"home");if(!Xt(nt(r))||n.readonly)return o;const s=n.insertTextBlock("",at(n.rootContainer),Eo(n.rootContainer));return st(s,0,"home")}function kT(n,t,e){const o=n.selection.range;let r;if(o instanceof Ze)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=yT(n,t,o):r=vT(n,o.getFocusedPos(),t);else if(r=gT(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=Ge(s);r=st(l,0,"home")}else{const l=Se(s);r=st(l,ut(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:xh(n,o.anchor,r):null}function Pi(n,t,e){const o=kT(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 oA(n){return Pi(n,"ArrowLeft","move"),!0}function rA(n){return Pi(n,"ArrowRight","move"),!0}function iA(n){return Pi(n,"ArrowUp","move"),!0}function sA(n){if(Pi(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=nt(t);if(Xt(e)||Ge(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",at(o),Eo(o)),!0}function lA(n){return Pi(n,"ArrowDown","select"),!0}function cA(n){return Pi(n,"ArrowLeft","select"),!0}function aA(n){return Pi(n,"ArrowRight","select"),!0}function uA(n){return Pi(n,"ArrowUp","select"),!0}const dA=S("word-offset");function Vg(n,t){const e=n.selection.range.focus;g(dA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(he(n,o))return st(o,0,"home");if(e.offset===0||!tt(n,o)){const s=ce(o);if(!s)return null;const l=st(s,ut(n,s),"end");if(t==="select"&&tt(n,s)){const a=yg(n,s,l.offset);return st(s,a,"normal")}return l}const r=yg(n,o,e.offset);return st(o,r,"normal")}function Wg(n,t){const e=n.selection.range.focus;g(dA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(he(n,o))return st(o,0,"end");if(e.offset===ut(n,o)||!tt(n,o)){const s=Zt(o);if(!s)return null;const l=st(s,0,"home");if(t==="select"&&tt(n,s)){const a=kg(n,s,l.offset);return st(s,a,"end")}return l}const r=kg(n,o,e.offset);return st(o,r,"normal")}function hA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vg(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function fA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Wg(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function mA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vg(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function gA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Wg(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}S("find-block");function qg(n,t){if(!Lt(n,t))return t;const o=jn(n,t).getChildContainers(n,t)[0],i=ve(o)[0];return qg(n,i)}function Gg(n,t){if(!Lt(n,t))return t;const e=jn(n,t).getChildContainers(n,t),o=e[e.length-1],r=ve(o),i=r[r.length-1];return Gg(n,i)}function pA(n){const t=Gg(n,Ge(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(e),!0}function CA(n){const t=qg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(e),!0}function AA(n){const t=qg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function Zg(n){const t=Gg(n,Ge(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}const bA=S("line-offset");function vA(n){const t=n.selection.range.focus;g(bA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!tt(n,e))return st(e,0,"home");let r=H4(e,t).start;const{next:i}=Xd(e,r);return i&&io(i)&&va(i)==="br"&&(r+=1),st(e,r,"home")}function yA(n){const t=n.selection.range.focus;g(bA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===ut(n,e)||!tt(n,e))return st(e,ut(n,e),"end");const o=H4(e,t);return st(e,o.end,"end")}function kA(n){if(!n.selection.range.focus.isSimple())return!1;const e=vA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function wA(n){if(!n.selection.range.focus.isSimple())return!1;const e=yA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function BA(n){if(!n.selection.range.focus.isSimple())return!1;const e=vA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function EA(n){if(!n.selection.range.focus.isSimple())return!1;const e=yA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const xA=S("find-block-position");function wT(n,t,e,o){g(xA,Lt(n,t),"is not a complex block");const r=jn(n,t).getChildContainers(n,t);g(xA,r.length>0,"complex block has not any child container");const i=To(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,a=D4(n,t,s,l);return Qg(n,a,e,o)}function Qg(n,t,e,o){if(Lt(n,t))return wT(n,t,e,o);const r=it(t);let i=Number.MAX_SAFE_INTEGER;const s=To(n,e,o),l=s.left+s.width/2,a=s.top+s.height/2;let d=st(r,0,"home");const h=ut(n,t);for(let p=0;p<=h;p++){const A=st(r,p,"normal"),v=To(n,t,A),B=er(v,l,a);B<i&&(i=B,d=A)}return d}const IA=S("page-offset");function BT(n,t){const e=x6(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<GI(n))return n.getFirstBlock();const i=ce(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=ce(s)}return n.getFirstBlock()}function ET(n,t){const e=x6(n)*.9,o=t.getBoundingClientRect(),r=ZI(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=Zt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=Zt(l)}return n.getLastBlock()}function TA(n){const t=n.selection.range.focus;g(IA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=BT(n,e);let r;return o===n.getFirstBlock()?r=st(o,0,"home"):r=Qg(n,o,e,t),r}function DA(n){const t=n.selection.range.focus;g(IA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=ET(n,e);let r;return o===n.getLastBlock()?r=st(o,ut(n,o),"end"):r=Qg(n,o,e,t),r}function SA(n){if(!n.selection.range.focus.isSimple())return!1;const e=TA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function LA(n){if(!n.selection.range.focus.isSimple())return!1;const e=DA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function MA(n){if(!n.selection.range.focus.isSimple())return!1;const e=TA(n);if(!e)return!1;const o=xh(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 RA(n){if(!n.selection.range.focus.isSimple())return!1;const e=DA(n);if(!e)return!1;const o=xh(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 Na=S("select-all");function OA(n,t){const e=Se(n),o=Ge(n);return t.start.offset===0&&t.start.blockId===it(e)&&t.end.offset===ut(t.getEditor(),o)&&t.end.blockId===it(o)}function xT(n,t){const e=t.getEditor(),o=jn(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=it(n);return t.start.blockId===s&&t.start.childContainerId===at(r)&&t.end.blockId===s&&t.end.childContainerId===at(i)}function IT(n,t){g(Na,t,"no parent block"),g(Na,Lt(n,t),"not a complex block");const e=jn(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(Ue(n,{anchor:fe(t,at(o)),focus:fe(t,at(r))}))}function _A(n,t){const e=nt(t);Yg(n,e)}function FA(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&tt(n,t)){const r=e.start,i=e.end,s=ut(n,t);if(r.offset>0||i.offset<s)return n.selection.selectBlock(t,0,s),!1}return W(n.rootContainer,"select-all"),_A(n,Se(n.rootContainer)),!1}return g(Na,!e.isSimple(),"invalid range type"),xT(t,e)?(_A(n,t),!1):(g(Na,t,"no parent block"),g(Na,Lt(n,t),"not a complex block"),IT(n,t),!0)}function Yg(n,t){const e=ve(t),o=e[0],r=e[e.length-1],i=st(o,0,"home"),s=st(r,ut(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function PA(n){Zg(n),n.focus()}const Jg=S("selected-block-to-doc");function NA(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{NA(n,i,e)}),e.blocks[o]=mt.default(r)})}function Ih(n,t){const e=Qt(n,t.block);if(e.selectionToDoc)return e.selectionToDoc(n,t);const o=mt.default(_i(n,t.block));if(tt(n,t.block)){const i=t.start,s=t.end;if(g(Jg,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=ze(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(Le(t.block))return{blocks:{root:[o]},meta:{},comments:{}};g(Jg,Lt(n,t.block),"not complex block"),g(Jg,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return NA(n,o,r),r}function Kg(n,t){const e=st(t,0,"normal"),o=st(t,ut(n,t),"end");return Ih(n,{block:t,start:e,end:o})}const TT=S("block-to-doc");function DT(n,t){g(TT,t.length>0,"invalid params, no blocks");const e=t.map(o=>Kg(n,o));return $s(e)}function Th(n){const e=n.selection.range.getSelectedBlocks().map(o=>Ih(n,o));return $s(e)}function $A(n,t){const e=n.getContainerById(t),i=ve(e).map(s=>({start:st(s,0,"home"),end:st(s,ut(n,s),"end"),block:s})).map(s=>Ih(n,s));return $s(i)}const Dh=S("editor-selection");class ST{constructor(t){m(this,"editor");m(this,"caret");m(this,"_range");m(this,"lastCaretRect");m(this,"handleBlockDelete",(t,e,o,r)=>{if(o||r.child)return;const i=this.range;if(D6(e,i)){Dh.debug("adjust selection because remote deleted current block");const s=S6(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=it(e);this.caret=new VI(t);const r=st(o,0,"normal");this._range=Ue(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=st(t,e,"normal");let i;o&&(i=st(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=Ue(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),xt(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!KI(this.editor,r))&&et(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(),WI(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(!$r(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=To(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){JI(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=ut(this.editor,e)||g(Dh,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||g(Dh,!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&&xt(e,"focused")&&(et(e,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,e!=null?e:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(t){const e=Th(this.editor);return t==="text"?La(this.editor,e):t==="markdown"?Ma(this.editor,e):M6(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{et(t,"focused"),et(t,"child-focused")})}setBlockFocused(t){if(xt(t,"focused"))return!1;W(t,"focused");let e=nt(t);for(;Do(e);){const o=ot(e);g(Dh,o,"parent block not found"),W(o,"child-focused"),e=nt(o)}return!0}}function LT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);!e||n.selection.selectBlock(e,0,ut(n,e))}function MT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!tt(n,e))return;let o=Vg(n,"select"),r=Wg(n,"select");if(!o||!r)return;const i=t.blockId;o.blockId!==i&&(o=st(e,0,"home")),r.blockId!==i&&(r=st(e,ut(n,e),"end")),n.selection.setSelection(o,r)}class RT{constructor(t){m(this,"editor");m(this,"startPos",null);m(this,"lastCaretRect");m(this,"mouseDownEvent",null);m(this,"autoScroll",null);m(this,"handleMouseDown",(t,e)=>{var r;this.mouseDownEvent=t;const o=M4(this.editor,t.x,t.y);if(o){if(o instanceof or)return;if(!this.autoScroll&&e.autoScroll){const s=o.getSelectedBlocks(),l=oo(s[0].block);this.autoScroll=new Gd({scrollElement:l,edge:{top:50,bottom:50}})}const i=this.editor.selection.range;if(t.shiftKey&&i.isSimple()){const s=i.anchor;this.editor.selection.setSelection(s,o.focus),this.startPos=o.start}else this.editor.selection.setSelection(o.anchor,o.focus),this.startPos=o.start;this.editor.selection.updateLastCaretRect(),e.autoScroll&&((r=this.autoScroll)==null||r.active())}});m(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=oh(this.editor,t.x,t.y);if(!e)return;const o=xh(this.editor,this.startPos,e.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});m(this,"handleMouseUp",t=>{var e;(e=this.autoScroll)==null||e.inactive(),this.startPos=null});this.editor=t,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(t){MT(this.editor)}handleTripleClick(t){LT(this.editor)}}function OT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function _T(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const HA=S("delete-text");function jA(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof je||g(HA,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);g(HA,tt(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!sn(s,l-e)){const a=Ri(s,l);e=l-a}}else if(t==="forward"&&l+e>ut(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function UA(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const FT=S("handle-backspace");function Xg(n,t){if(!he(n,t))return;const e=nt(t);Eo(e)!==1&&n.deleteBlock(t)}function PT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(tt(n,o))if(e.offset===0){if(UA(n,o))return;const r=ce(o);if(r){if(!n.isBlockWritable(r))return;if(tt(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Lt(n,r)){Xg(n,o);const i=Vl(n,r);i?n.selection.selectBlock(i,ut(n,i)):n.selection.selectBlock(r,0,ut(n,r))}else Xg(n,o),g(FT,Le(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=nt(o);if(Do(i)){const s=x4(n,i);if(s){if(!n.isBlockWritable(s))return;Xg(n,o),n.selection.selectBlock(s,ut(n,s))}}}}else jA(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=bt(o),i=nt(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function NT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(tt(n,o))if(e.offset===ut(n,o)){const r=Zt(o);if(r){if(!n.isBlockWritable(r))return;tt(n,r)?n.mergeTextBlock(o,r,{focus:!0}):he(n,o)?n.deleteBlock(o,ye(n,r,0)):n.deleteBlock(r)}}else jA(n,"forward",1,null);else{const r=bt(o),i=nt(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function $T(n){const{range:t}=n.selection,{start:e,end:o}=t,r=n.getBlockById(e.blockId),i=n.getBlockById(o.blockId);if(r!==i||!Lt(n,r))return!1;if($r(e))return!0;const s=Os(n,r,e,o),l=En(n,r);return s.length===l.length}function HT(n,t){if($T(n)){const o=n.getFocusedBlock(),r=bt(o),i=at(nt(o));n.insertTextBlock("",i,r+1);return}n.selection.range.isCollapsed()||n.clearSelectedContents();const e=n.getFocusedBlock();if(tt(n,e)){if(he(n,e)&&UA(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 jT(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!tt(n,o))return!1;const r=e.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:K(),box:!0,created:Date.now()}),!0}const UT=S("input-handler-actions");function zT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(HT(n),!0))}function VT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(NT(n),!0))}function WT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(PT(n),!0))}function qT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(jT(n),!0))}function GT(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t,{toPlainText:!0})}).catch(t=>{UT.error(t)}),!0)}const Sh={ArrowDown:sA,ArrowUp:iA,ArrowLeft:oA,ArrowRight:rA,"Shift+ArrowDown":lA,"Shift+ArrowUp":uA,"Shift+ArrowLeft":cA,"Shift+ArrowRight":aA,"CtrlOrCmd+ArrowLeft":hA,"CtrlOrCmd+ArrowRight":fA,"CtrlOrCmd+Shift+ArrowLeft":mA,"CtrlOrCmd+Shift+ArrowRight":gA,"CtrlOrCmd+ArrowUp":CA,"CtrlOrCmd+ArrowDown":pA,"CtrlOrCmd+Shift+ArrowUp":AA,"CtrlOrCmd+Shift+ArrowDown":Zg,"CtrlOrCmd+A":FA,Home:BA,End:EA,"Shift+Home":kA,"Shift+End":wA,PageUp:SA,PageDown:LA,"Shift+PageUp":MA,"Shift+PageDown":RA,"CtrlOrCmd+Z":OT,"CtrlOrCmd+Shift+Z":_T,Enter:zT,Delete:VT,Backspace:WT,"Shift+Enter":qT,"CtrlOrCmd+Shift+V":GT};function zA(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function VA(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=>{VA(n,l,e)})})}function WA(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):VA(t,r,e)})}async function ZT(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 QT(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 YT(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(QT(n,t)){const s=Array.from(Object.keys(o));r=await ZT(n,s),WA(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&&WA(n,t,i)}async function JT(n,t,e){await YT(n,t),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&Le(i)){const s=nt(i),l=n.getBlockIndex(i),[a]=n.insertDocAt(s,l+1,t,e);a&&n.selection.selectBlock(a,ut(n,a))}else{n.clearSelectedContents();const{block:s,offset:l}=Gl(n);n.insertDoc(s,l,t,e)}})}const KT=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function XT(n){let t;for(const e of KT)if(t=n[e],t)break;return t||null}function qA(n,t,e){if(t.type==="embed"){const s=t.embedData.src;if(s&&typeof s=="string")for(const l of s.split("|"))e.add(l);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=>{qA(n,l,e)})})}function tD(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)}):qA(t,r,e)}),Array.from(e)}function Lh(n,t){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Bs(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Mh(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=tD(n,t),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),t.meta={...e,resources:r}}function eD(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let o=Th(n);const r=e==null?void 0:e(n,t,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Mh(n,o);const i=bh(n,o),s=Ma(n,o),l=Lh(i,o);t.clipboardData.setData("text/html",l),t.clipboardData.setData("text/plain",s),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(o))}async function Rh(n,t){const e=Kg(n,t);Mh(n,e);const o=bh(n,e),r=Ma(n,e),i=Lh(o,e);return Mm([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class nD{constructor(t){m(this,"editor");m(this,"handlers",[]);m(this,"onPasteText",async(t,e)=>{const o=new DataTransfer;o.setData("text/plain",t);const r=await this.editor.dataConverter.fromData(this.editor,o,e);r&&this.pasteDocs(r,null)});this.editor=t}onInsertText(t,e){if(!tt(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=Gl(this.editor);this.handleBeforeInsertText(o,r,i,e)||(this.defaultInsertText(this.editor,o,r,i,e),this.handleAfterInsertText(o,r,i,e),this.editor.selection.updateLastCaretRect())}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}=Gl(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}=Gl(this.editor);for(let l=0;l<this.handlers.length;l++){const a=this.handlers[l];a.handleUpdateCompositionText&&a.handleUpdateCompositionText(this.editor,r,i,s,o)}this.editor.selection.updateLastCaretRect()}onCopy(t){eD(this.editor,t,(e,o,r)=>{for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeCopy){const l=s.handleBeforeCopy(this.editor,o,r);if(l===!0)return!0;if(typeof l=="object"&&l!=null)return l}}})}onCut(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeCut&&r.handleBeforeCut(this.editor,t)===!0)return}if(this.onCopy(t),this.editor.selection.range.isCollapsed()){const o=this.editor.selection.focusedBlock;Le(o)&&this.editor.deleteBlock(o)}else Fg(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;this.editor.dataConverter.fromData(this.editor,t.clipboardData).then(async o=>{o&&this.pasteDocs(o,t)})}onFocus(){W(this.editor.rootElement,"active")}onBlur(){et(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){Lg(this.editor,i)}defaultHandleKeydown(t,e){return zA(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforePasteDoc&&await r.handleBeforePasteDoc(this.editor,t))return}const e={blockIdMap:new Map,containerIdMap:new Map};await JT(this.editor,t,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterPasteDoc&&await r.handleAfterPasteDoc(this.editor,t,e))return}}async pasteDocs(t,e){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePaste&&await i.handleBeforePaste(this.editor,e,t))return}const o=XT(t);if(!!o){await this.pasteDoc(o);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPaste&&await i.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function oD(n,t,e){const o=Or(t,e);return o.remove(),o}S("copy-dom-attributes");const GA=["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 rD(n,t){for(let l=0;l<GA.length;l++){const a=GA[l];t[a]=n[a]}const e=n.attributes,o=t.attributes,r=[],i=[];for(let l=0;l<e.length;l++){const a=e[l],d=o.getNamedItem(a.name);d?d.value!==a.value&&(d.value=a.value,i.push(a)):r.push(a)}const s=[];for(let l=0;l<o.length;l++){const a=o[l];e.getNamedItem(a.name)||s.push(a)}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 ZA(n){const t=Array.from(n.childNodes).filter(e=>!jC(e));return t.forEach(e=>{e.remove()}),t}function QA(n,t,e){var d;const o=n.getContainerById(t),r=Or(o,e),i=Di(r),s=n.doc.getBlockData(t,e),l=Qt(n,r);if((d=l==null?void 0:l.handleUpdateBlock)==null?void 0:d.call(l,n,r,s))n.editorBlockRenders.updateBlock(n,i,r,s);else{const h=n.editorBlocks.createBlock(i,o,s),p=ZA(h);ZA(r),p.forEach(v=>{r.appendChild(v)});const A=Jd(h);if(A){const v=Jd(r);v&&v.remove(),r.appendChild(A)}rD(h,r)}i4(n,r,s),n.blockHooks.forEach(h=>{var p;(p=h.update)==null||p.call(h,n,i,o,r,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const iD=S("transform-selection");function YA(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;g(iD,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const d=ln.transformCursor(i.offset,e,o);l=st(t,d,"normal")}let a=s;if(s.blockId===t){const d=ln.transformCursor(s.offset,e,o);a=st(t,d,"normal")}return Ue(n,{anchor:l,focus:a})}const sD=S("handle-block-text-changed");function lD(n,t,e,o,r){const i=n.getContainerById(t),s=Or(i,e),l=n.doc.getBlockData(t,e);if(g(sD,l.text,"no block text"),XC(n,s).setBlockText(n,s,l.text),!r){const a=YA(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function cD(n,t){const e=mt.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function JA(n,t,e,o){const r=Qt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function aD(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{JA(n,i,o,{child:!0})}),JA(n,r,o,{child:!1})}const Ro=S("editor-doc");class uD extends fa{constructor(e,o,r){super();m(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)}verifyBlockWritable(e,o){const r=this.editor.getBlockByIndex(e,o);g(Ro,this.editor.isBlockWritable(r),`block is not writable, ${e}, ${o}`)}localUpdateBlockText(e,o,r,i){g(Ro,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const s=this.getBlockData(e,o),l=s.text;g(Ro,l,`no text, ${e}, ${o}`);const a=YA(this.editor,s.id,r,!0),d=ln.apply(l,r);this.localEvents.forEach(p=>p.onBeforeUpdateBlockText(e,s.id,l,d,a.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(a,i),h}localUpdateBlockData(e,o,r,i){g(Ro,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(e,o);if(!this.editor.isBlockWritable(s)){const h=Array.from(r.delete).filter(A=>A!=="comments"),p=Object.keys(r.insert).filter(A=>A!=="comments");(h.length>0||p.length>0)&&g(Ro,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=mt.default(this.getBlockData(e,o)),a=mt.default(cD(l,r));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(e,l.id,l,a,i));const d=this.externalDoc.localUpdateBlockData(e,o,r,i);return this.editor.selection.setRange(Si(this.editor,i)),d}localInsertBlock(e,o,r,i,s){g(Ro,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(a=>a.onBeforeInsertBlock(e,o,r,i));const l=this.externalDoc.localInsertBlock(e,o,r,i);return this.editor.selection.setRange(Si(this.editor,i),s),l}localDeleteBlock(e,o,r){g(Ro,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const i=mt.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(Si(this.editor,r)),s}localDeleteChildContainers(e){return g(Ro,!this.editor.readonly,"editor is readonly"),e.forEach(o=>{const r=mt.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainer(e,o){return g(Ro,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(e,mt.default(o))),this.externalDoc.localInsertChildContainer(e,o)}onRequestReload(e){Ro.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)}),lD(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)}),QA(this.editor,e,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(e,o,r,i){this.callbacks.forEach(l=>{var a;return(a=l.onInsertBlock)==null?void 0:a.call(l,e,o,r,i)});const s=this.editor.getContainerById(e);KE(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){aD(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);oD(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){Ro.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function KA(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 tp=S("undo-action");class Kl{constructor(t,e,o){m(this,"beforeRange");m(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 g(tp,t,"no other action"),!1}combine(t){g(tp,!1,"no other")}setAfterRange(t){this.afterRange&&tp.warn("after range has already set"),this.afterRange=t}}const dD=S("block-action");class XA extends Kl{constructor(e,o,r,i,s){super(e,o,s);m(this,"blockData");m(this,"blockIndex");this.blockData=mt.default(i),this.blockIndex=r}deleteBlock(e,o){if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockData.id);return i?(g(dD,this.blockIndex===bt(i),"invalid block index"),kh(e,i,Si(e,o)),!0):!1}insertBlock(e,o){return Ql(e,this.containerId,this.blockIndex,mt.default(this.blockData),o),!0}}class hD extends XA{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class fD extends XA{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class mD extends Kl{constructor(e){super(e,at(e.rootContainer),e.selection.range.toDocRange());m(this,"actions",[])}addAction(e){KA(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 Kl&&(o.afterRange||o.setAfterRange(e))}}const Hs=S("update-block-data-action");class Oh extends Kl{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeBlockData");m(this,"afterBlockData");m(this,"blockId");this.blockId=r,g(Hs,this.blockId===i.id,"invalid block id"),g(Hs,this.blockId===s.id,"invalid block id"),this.beforeBlockData=mt.default(i),this.afterBlockData=mt.default(s),g(Hs,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){g(Hs,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hs,r,"no container"),Eh(e,o,Oh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){g(Hs,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hs,r,"no container"),Eh(e,o,Oh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=mt.default(e);return delete o.id,delete o.type,o}}const ep=S("update-block-text-action");class $a extends Kl{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeRichTextData");m(this,"afterRichTextData");m(this,"blockId");m(this,"type");this.blockId=r,this.beforeRichTextData=mt.default(i),this.afterRichTextData=mt.default(s),this.type=$a.calType(i,s)}static calType(e,o){g(ep,e,"no old data"),g(ep,o,"no new data");const i=ln.diff(e,o),s=new Set;let l=!1;const a=h=>pC(h)?`cjk_${h}`:mC(h)?"number":jd(h)?"space":gC(h)?"letter":"unknown";let d=!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,d=!0,s.add(`insert_${a(h.insert.substr(1))}`)):s.add(`insert_${a(h.insert)}`):h.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:d}}undo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Bh(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Bh(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof $a)||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){g(ep,e instanceof $a,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class tb extends Kl{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,mt.default(this.blocks)),!0}}class gD extends tb{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class pD extends tb{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Oo=S("undo");class CD{constructor(t){m(this,"editor");m(this,"actions",[]);m(this,"undoCursor");m(this,"currentGroup",null);m(this,"groupCounter",0);m(this,"undoRedoing",!1);m(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):(KA(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(g(Oo,!this.currentGroup,"current group already exists"),this.currentGroup=new mD(this.editor),this.groupCounter=1):(g(Oo,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){g(Oo,this.currentGroup,"current group not exists"),g(Oo,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Oo.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 Oo.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(Si(this.editor,t.beforeRange))}catch(e){Oo.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(Si(this.editor,e)):Oo.warn("no after range")}catch(e){Oo.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(),ln.diff(o,r).length!==0&&this.addAction(new $a(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Oh(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),g(Oo,e>=0,"invalid block index"),g(Oo,o,"no block data"),this.addAction(new hD(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new fD(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new gD(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new pD(this.editor,t,e)))}}class AD{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 bD{constructor(){m(this,"converters",[]);this.addConverter(new AD)}async fromData(t,e,o){let r={};for(const i of this.converters){const s=await i.fromData(t,e,o);s&&(r={...r,...s})}return r}addConverter(t){this.converters.push(t)}}class vD{constructor(t){m(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 pe extends be.TypedEmitter{constructor(e){super();m(this,"hoveringBlock",null);m(this,"hoveringTextChild",null);m(this,"filters",[]);m(this,"finders",[]);m(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=ot(o);if((!r||!Kt(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?it(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&&Kt(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&et(s,"hover"),e&&W(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 pe(e))}getParentTextContentChild(e,o){if(!tt(this.editor,e))return null;const r=Rt(e);return o.parentElement===r?o:$m(o)}}const eb="style-color-",nb="style-bg-color-";class yD{renderText(t,e,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(eb)?i["data-style-color"]=l.substring(eb.length):l.startsWith(nb)?i["data-style-bg-color"]=l.substring(nb.length):l.startsWith("style")&&r.push(l):typeof a=="string"&&(l==="link"&&(r.push("link"),i.link=a),l==="inline-style-color"&&(s.color=a))}),{classes:r,attributes:i,styles:s}}renderBlock(t,e,o){var l,a;const r={};Object.entries(o).filter(d=>d[0].startsWith("style-")).forEach(([d,h])=>{r[`data-${d}`]=`${h}`});const s=[];return((a=(l=t.selection)==null?void 0:l.range)==null?void 0:a.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"),pe.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(a=>{a.name.startsWith("data-style-")&&o.removeAttribute(a.name)}),Object.entries(r).filter(a=>a[0].startsWith("style-")||a[0]==="align").forEach(([a,d])=>{a==="align"&&o.setAttribute(a.startsWith("style-")?`data-${a}`:`data-style-${a}`,`${d}`)}),((l=(s=t.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&W(o,"focused"),pe.get(t).hoveringBlockId()===r.id&&W(o,"hover")}}function kD(n){n.editorBlocks.registerBlockClass(In),n.editorBlocks.registerBlockClass(E4),n.editorBoxes.registerBoxClass(g6),n.editorBoxes.registerBoxClass(p6),n.editorBoxes.registerBoxClass(b6),n.editorBoxes.registerBoxClass(v6),n.editorInsertions.registerInsertionClass(y6),n.editorBlockRenders.registerRender(new yD)}function wD(n,t){kD(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 ob=S("range-commands");function rb(n,t){n.forEach(e=>{e.source=t,e.children&&rb(e.children,t)})}function ib(n,t,e){const o=it(t);g(ob,o===e.start.blockId,"invalid start range"),g(ob,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);rb(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,i);l&&(i=l)}}),Lt(n,t)&&Os(n,t,e.start,e.end).forEach(l=>{ve(l).forEach(d=>{const h=ut(n,d),p=Ue(n,{anchor:st(d,0,"home"),focus:st(d,h,"end")}),A=ib(n,d,p);i.push(...A)})}),i}function sb(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=Ue(t,{anchor:r.start,focus:r.end});ib(t,r.block,i).forEach(l=>{o.push(l)})}),o}function lb(n,t,e,o,r,i){var h;const s=n.editorCommandProviders.getCommandProviders();for(let p=0;p<s.length;p++){const A=s[p];if(A.beforeExecuteCommand&&A.beforeExecuteCommand(n,t,e,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),a={};if((h=l.executeCommand)!=null&&h.call(l,n,t,e,o,r,{}))return i[it(t)]=a,!0;let d=!1;return Lt(n,t)&&Os(n,t,e.start,e.end).forEach(A=>{ve(A).forEach(B=>{const D=ut(n,B),T=Ue(n,{anchor:st(B,0,"home"),focus:st(B,D,"end")});lb(n,B,T,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,t,e,o,r,i)}),d}function cb(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 a=Ue(o,{anchor:l.start,focus:l.end});lb(o,l.block,a,t,e,r)}),r}const BD=S("command-providers");class ab{constructor(t){m(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 g(BD,e,`no command provider, id=${t}`),e}getCommands(t){return sb(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>cb(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 ED(n,t){const e=nt(t),o=at(e),r=bt(t);QA(n,o,r)}const xD=S("table-scroll");class ub{constructor(t,e,o,r,i){m(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 ID{constructor(t){m(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)){xD.warn(`event has already registered: ${e}`);return}i.push(new ub(this.editor,t,e,o,r))}else{const s=new ub(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 a=s[l];if(e)e===a.name&&o===a.handler&&s.splice(l,1);else if(o===a.handler){s.splice(l,1),a.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 db=S("update-block-text");function TD(n,t){const e=n.getBoxById(t.id),o=ot(e);g(db,o,"no parent block"),g(db,tt(n,o),"not a text block");const r=n.getBlockText(o),i=s6(r,"id",t.id,t);z6(n,o,i)}function DD(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 SD(n){return n.readonly?!1:!Lo(n).find(o=>!n.isBlockWritable(o.block))}class LD{constructor(t){this.editor=t}getKey(t){return`${this.editor.id}-${t}`}getItem(t){return window.localStorage.getItem(this.getKey(t))}setItem(t,e){if(!e){this.removeItem(t);return}window.localStorage.setItem(this.getKey(t),e)}removeItem(t){window.localStorage.removeItem(this.getKey(t))}}class MD{constructor(){m(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(Rr(e,s)){const a=l(t,e);if(a!==void 0)return a}}}}const zr=S("editor");class RD extends be.TypedEmitter{constructor(e,o,r){var i,s,l,a,d,h,p;super();m(this,"parent");m(this,"rootElement");m(this,"contentElement");m(this,"rootContainerObject");m(this,"rootContainer");m(this,"input");m(this,"selection");m(this,"selectionHandler");m(this,"doc");m(this,"id");m(this,"clientId");m(this,"compositingText","");m(this,"undoManager");m(this,"shortcuts",new MD);m(this,"dataConverter",new bD);m(this,"editorBlocks",new y4(this));m(this,"editorBoxes",new A6(this));m(this,"editorInsertions",new w6(this));m(this,"editorEmbeds",new w4(this));m(this,"editorDecorators",new B6(this));m(this,"editorCommandProviders",new ab(this));m(this,"editorBlockRenders",new vD(this));m(this,"blockHooks",[]);m(this,"domEvents",new ID(this));m(this,"customs",new Map);m(this,"options");m(this,"inputHandlers",new nD(this));m(this,"settingsProvider");m(this,"_readonly",!1);zr.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=(a=r==null?void 0:r.settingsProvider)!=null?a:new LD(this),wD(this,r==null?void 0:r.components),this.blockHooks.push(...(h=(d=r==null?void 0:r.components)==null?void 0:d.blockHooks)!=null?h:[]),this.id=(p=r==null?void 0:r.id)!=null?p:K(),this.clientId=K(),this.undoManager=new CD(this),this.doc=new uD(this,o,this.undoManager),this.parent=e,this.rootElement=w("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=w("div",["editor-content"],this.rootElement),this.rootContainerObject=A4(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new zI(this,this.inputHandlers),this.selection=new ST(this),this.selectionHandler=new RT(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),Ke.isMobile&&W(this.rootElement,"mobile"),Ke.isSafari&&W(this.rootElement,"safari"),this._readonly&&W(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?W(this.rootElement,"readonly"):et(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:oo(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 g(zr,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(){zr.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){Pg(this,e,o)}isWritable(){return SD(this)}isBlockWritable(e){return DD(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return g(zr,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),g(zr,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(e,o,r){return b4(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&&g(zr,xs(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(zr,Nm(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return g(zr,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return g(zr,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return Or(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return bt(o)}return bt(e)}getContainerById(e){return Nr(this,e)}getParentContainer(e){return nt(e)}reloadBlock(e){ED(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},a={anchor:l,focus:l};return Ql(this,e,o,r,i!=null?i:a,s)}insertEmbed(e,o,r,i,s){const l={id:K(),type:"embed",embedType:r,embedData:i};return this.insertBlock(e,o,l,s)}deleteBlock(e,o){Og(this,e,o)}mergeTextBlock(e,o){return H6(this,e,o)}breakTextBlock(e,o,r){return Yl(this,e,o,r).newBlock}getTextPosition(){return Gl(this)}getBlockString(e,o){const r=this.getBlockText(e);return re(r,o)}getBlockData(e){return _i(this,e)}getBoxData(e){return f6(this,e)}getBlockText(e){return mn(this,e)}setBlockText(e,o){z6(this,e,o)}deleteTextFromBlock(e,o,r,i){return Mg(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return R6(this,e,o,r,i)}insertBoxToBlock(e,o,r){return O6(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){q6(this,e,o,r,i)}insertDocAt(e,o,r,i){return Hg(this,e,o,r,i)}deleteChildContainers(e){$6(this,e)}replaceBlockText(e,o){return Bh(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...a}=i;return Eh(this,e,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return V6(this,e,o,r)}updateBoxData(e){TD(this,e)}getSelectedText(){const e=Th(this);return La(this,e)}clearSelectedContents(){Fg(this)}insertTextBlock(e,o,r,i){const s=sr(e!=null?e:"");return N6(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){F6(this);return}o?(this.compositingText="",Em()||Lg(this,e)):(this.compositingText=e,_6(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function Ha(n,t,e){return new RD(n,t,e)}function OD(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=fm.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const _D=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class _h extends be.TypedEmitter{constructor(e){super();m(this,"users",new Map);m(this,"cursors",new Map);m(this,"addingUser",!1);m(this,"colors");this.colors=e&&e.length>0?e:_D}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&ua.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&&fh(r.range)).forEach(r=>{const i=r.range.focus.offset;let s=o.get(i);s||(s=[],o.set(i,s)),s.push(r)}),o}getCursors(e){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===e||o.range.focus.blockId===e)}onUpdateBlockText(e,o,r){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(fh(l.range)){const{anchor:a,focus:d}=l.range;a.blockId===e.id&&(a.offset=ln.transformCursor(a.offset,o,r)),d.blockId===e.id&&(d.offset=ln.transformCursor(d.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 Xe=S("local-doc");class np extends fa{constructor(e,o){super();m(this,"doc");m(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[sr("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return mt.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,o){const r=this.getContainerBlocks(e);g(Xe,r,`no container data: ${e}`);const i=r[o];return g(Xe,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);g(Xe,i.text,"no text for data");const s=ln.apply(i.text,r);return i.text=s,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var a;return(a=l.onUpdateBlockText)==null?void 0:a.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}),g(Xe,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 g(Xe,i,`no container data: ${e}`),g(Xe,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),g(Xe,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);g(Xe,r,`no container data: ${e}`),g(Xe,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),g(Xe,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,g(Xe,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){Xe.debug(`delete child containers: ${e}`),e.forEach(o=>{g(Xe,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{g(Xe,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){g(Xe,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){g(Xe,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new _h}setDoc(e){this.doc=mt.default(e),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}class FD{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function op(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new FD(o)})}const hb=S("find-block");function fb(n,t){const e=Ds(t);if(!e){if(ro(t))return null;const o=Is(t);return g(hb,o,"no parent block"),fb(n,o)}return Lt(n,e)?Vl(n,e,{visibleOnly:!0}):e}function mb(n,t){const e=Ss(t);if(!e){if(ro(t))return null;const o=Is(t);return g(hb,o,"no parent block"),mb(n,o)}return Lt(n,e)?eg(n,e,{visibleOnly:!0}):e}const PD=S("remote-cursor");class ND{constructor(){m(this,"remoteUsers",new _h)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):PD.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 $D(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function HD(n){const{blocks:t,meta:e,comments:o}=n,{root:r,...i}=t;return{blocks:r,meta:e,comments:o,...i}}function ja(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=$D(mt.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function Ni(n){return n==="root"?"blocks":n}function Xl(n){return n==="blocks"?"root":n}const jD={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new on.default(n)},apply(n,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},compose(n,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},diff(n,t){const e=new on.default(n),o=new on.default(t);return e.diff(o).ops},transform(n,t,e){const o=new on.default(n);return new on.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 on.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 cr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},$i={},rp=Z5.default.EventEmitter;$i.EventEmitter=rp,$i.mixin=UD;function UD(n){for(var t in rp.prototype)n.prototype[t]=rp.prototype[t]}var gb=["info","warn","error"];function pb(){var n={};gb.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var zD=pb;pb.prototype.setMethods=function(n){n=n||{};var t=this;gb.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var VD=zD,WD=new VD,Cb=WD;function js(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,js):this.stack=new Error().stack}js.prototype=Object.create(Error.prototype),js.prototype.constructor=js,js.prototype.name="ShareDBError",js.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 Fh=js,Ua={},Ab=qD;function qD(n,t,e,o){var r=function(s,l,a,d){t(a,s,l,"left"),t(d,l,s,"right")},i=n.transformX=function(s,l){e(s),e(l);for(var a=[],d=0;d<l.length;d++){for(var h=l[d],p=[],A=0;A<s.length;){var v=[];if(r(s[A],h,p,v),A++,v.length===1)h=v[0];else if(v.length===0){for(var B=A;B<s.length;B++)o(p,s[B]);h=null;break}else{for(var D=i(s.slice(A),v),T=0;T<D[0].length;T++)o(p,D[0][T]);for(var _=0;_<D[1].length;_++)o(a,D[1][_]);h=null;break}}h!=null&&o(a,h),s=p}return[s,a]};n.transform=function(s,l,a){if(!(a==="left"||a==="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],a):a==="left"?i(s,l)[0]:i(l,s)[1]}}var bb={exports:{}},Hi=bb.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||""}},ip=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},sp=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")},Ph=function(n){for(var t=0;t<n.length;t++)sp(n[t])};Hi.apply=function(n,t){var e;Ph(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=ip(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 Vr=Hi._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:ip(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:ip(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};Hi.compose=function(n,t){Ph(n),Ph(t);for(var e=n.slice(),o=0;o<t.length;o++)Vr(e,t[o]);return e},Hi.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),Vr(t,o)}return t};var lp=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};Hi.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=lp(n,t[r],o);return n};var GD=Hi._tc=function(n,t,e,o){if(sp(t),sp(e),t.i!=null)Vr(n,{i:t.i,p:lp(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(Vr(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&Vr(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)Vr(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)Vr(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),a=t.d.slice(s-t.p,l-t.p),d=e.d.slice(s-e.p,l-e.p);if(a!==d)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=lp(i.p,e),Vr(n,i))}return n},ZD=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};Hi.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=ZD(n[t]);return n},Ab(Hi,GD,Ph,Vr);var Nh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},QD=function(n){return!!n&&n.constructor===Object},_o=function(n){return JSON.parse(JSON.stringify(n))},It={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Wr={};It.registerSubtype=function(n){Wr[n.name]=n},It.create=function(n){return n===void 0?null:_o(n)},It.invertComponent=function(n){var t={p:n.p};return n.t&&Wr[n.t]&&(t.t=n.t,t.o=Wr[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},It.invert=function(n){for(var t=n.slice().reverse(),e=[],o=0;o<t.length;o++)e.push(It.invertComponent(t[o]));return e},It.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Nh(n[t].p))throw new Error("Missing path")},It.checkList=function(n){if(!Nh(n))throw new Error("Referenced element not a list")},It.checkObj=function(n){if(!QD(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function za(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 Va(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}It.apply=function(n,t){It.checkValidOp(t),t=_o(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&za(r);for(var i=null,s=e,l="data",a=0;a<r.p.length;a++){var d=r.p[a];if(i=s,s=s[l],l=d,i==null)throw new Error("Path invalid")}if(r.t&&r.o!==void 0&&Wr[r.t])s[l]=Wr[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)It.checkList(s),s[l]=r.li;else if(r.li!==void 0)It.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)It.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(It.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)It.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)It.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},It.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},It.incrementalApply=function(n,t,e){for(var o=0;o<t.length;o++){var r=[t[o]];n=It.apply(n,r),e(r,n)}return n};var YD=It.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};It.append=function(n,t){if(t=_o(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)&&(za(t),za(e)),YD(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Wr[t.t]){if(e.o=Wr[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(),Va(t),n.push(t);Va(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)&&(Va(t),Va(e)),n.push(t)},It.compose=function(n,t){It.checkValidOp(n),It.checkValidOp(t);for(var e=_o(n),o=0;o<t.length;o++)It.append(e,t[o]);return e},It.normalize=function(n){var t=[];n=Nh(n)?n:[n];for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=[]),It.append(t,o)}return t},It.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},It.canOpAffectPath=function(n,t){return It.commonLengthForOps({p:t},n)!=null},It.transformComponent=function(n,t,e,o){t=_o(t);var r=It.commonLengthForOps(e,t),i=It.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 a=_o(e);a.p=a.p.slice(s),t.ld=It.apply(_o(t.ld),[a])}else if(t.od!==void 0){var a=_o(e);a.p=a.p.slice(s),t.od=It.apply(_o(t.od),[a])}}if(r!=null){var d=s==l,a=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(za(t),a=_o(e),za(a)),a.t&&Wr[a.t]){if(t.t&&t.t===a.t){var h=Wr[t.t].transform(t.o,a.o,o);if(t.si!=null||t.sd!=null)for(var p=t.p,A=0;A<h.length;A++)t.o=[h[A]],t.p=p.slice(),Va(t),It.append(n,t);else(!Nh(h)||h.length>0)&&(t.o=h,It.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(d){if(t.ld!==void 0)if(t.li!==void 0&&o==="left")t.ld=_o(e.li);else return n}else return n}else if(e.li!==void 0)t.li!==void 0&&t.ld===void 0&&d&&t.p[r]===e.p[r]?o==="right"&&t.p[r]++:e.p[r]<=t.p[r]&&t.p[r]++,t.lm!==void 0&&d&&e.p[r]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&d){if(e.p[r]===t.p[r])return n;var p=e.p[r],v=t.p[r],B=t.lm;(p<B||p===B&&v<B)&&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 v=t.p[r],B=t.lm,D=e.p[r],T=e.lm;if(D!==T)if(v===D)if(o==="left")t.p[r]=T,v===B&&(t.lm=T);else return n;else v>D&&t.p[r]--,v>T?t.p[r]++:v===T&&D>T&&(t.p[r]++,v===B&&t.lm++),(B>D||B===D&&B>v)&&t.lm--,B>T?t.lm++:B===T&&(T>D&&B>v||T<D&&B<v?o==="right"&&t.lm++:B>v?t.lm++:B===D&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&d){var v=e.p[r],B=e.lm;p=t.p[r],p>v&&t.p[r]--,p>B&&t.p[r]++}else{var v=e.p[r],B=e.lm;p=t.p[r],p===v?t.p[r]=B:(p>v&&t.p[r]--,(p>B||p===B&&v>B)&&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&&d){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")It.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[r]==e.p[r]){if(!d)return n;if(t.oi!==void 0)delete t.od;else return n}}}return It.append(n,t),n},Ab(It,It.transformComponent,It.checkValidOp,It.append);var JD=bb.exports;It.registerSubtype(JD);var KD=It,XD={type:KD};(function(n){n.defaultType=XD.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)})(Ua);var Fo={};(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))}})(Fo);var vb=Array.isArray,yb=Object.keys,tS=Object.prototype.hasOwnProperty,eS=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=vb(t),r=vb(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 a=t instanceof Date,d=e instanceof Date;if(a!=d)return!1;if(a&&d)return t.getTime()==e.getTime();var h=t instanceof RegExp,p=e instanceof RegExp;if(h!=p)return!1;if(h&&p)return t.toString()==e.toString();var A=yb(t);if(s=A.length,s!==yb(e).length)return!1;for(i=s;i--!==0;)if(!tS.call(e,A[i]))return!1;for(i=s;i--!==0;)if(l=A[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},kb=$i,nS=Cb,Wn=Fh,$h=Ua,Po=Fo,oS=Po.clone,rS=eS,Tn=Wn.CODES,iS=Ft;function Ft(n,t,e){kb.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}kb.mixin(Ft),Ft.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())})},Ft.prototype._setType=function(n){if(typeof n=="string"&&(n=$h.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new Wn(Tn.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},Ft.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Ft.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new Wn(Tn.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 Wn(Tn.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?$h.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()},Ft.prototype.whenNothingPending=function(n){var t=this;Po.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},Ft.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Ft.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Ft.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Ft.prototype._emitResponseError=function(n,t){if(n&&n.code===Tn.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)},Ft.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){Po.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},Ft.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){Po.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()},Ft.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===Tn.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=Hh(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=Hh(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},Ft.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))},Ft.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()},Ft.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);sS(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},Ft.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},Ft.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},Ft.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=e&&e.wantSubscribe===n;if(o){e.callback=lS([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},Ft.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;Po.nextTick(function(){n._handleSubscribe()})}}};function sS(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function lS(n){return n=n.filter(Po.truthy),n.length?function(t){Po.callEach(n,t)}:null}Ft.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function cS(n){delete n.op,delete n.create,delete n.del}function Hh(n,t){if(n.del)return cS(t);if(t.del)return new Wn(Tn.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new Wn(Tn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new Wn(Tn.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}}}Ft.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new Wn(Tn.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===$h.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=Hh(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 a=this.data;this._setType(null),this.emit("del",a,t);return}},Ft.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 Wn(Tn.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>=Po.MAX_SAFE_INTEGER)return this.emit("error",new Wn(Tn.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)}},Ft.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var o=new Wn(Tn.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;Po.nextTick(function(){r.flush()})},Ft.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)},Ft.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)}}},Ft.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!rS(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}}},Ft.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)},Ft.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=$h.defaultType.uri),this.type){var r=new Wn(Tn.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)},Ft.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new Wn(Tn.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)},Ft.prototype.pause=function(){this.paused=!0},Ft.prototype.resume=function(){this.paused=!1,this.flush()},Ft.prototype.toSnapshot=function(){return{v:this.version,data:oS(this.data),type:this.type.uri}},Ft.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return nS.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},Ft.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=Hh(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)},Ft.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=Po.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},Ft.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=Po.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var Us={};Us.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 wb=$i,Bb=Us.ACTIONS,aS=Fo,uS=Dn;function Dn(n,t,e,o,r,i,s){wb.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}wb.mixin(Dn),Dn.prototype.hasPending=function(){return!this.ready},Dn.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}},Dn.prototype.destroy=function(n){this.connection.canSend&&this.action===Bb.querySubscribe&&this.connection.send({a:Bb.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&aS.nextTick(n)},Dn.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Dn.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Dn.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Dn.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 a=t[l],d=this.connection.get(a.c||this.collection,l);d.ingestSnapshot(a,s)}s()},Dn.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},Dn.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)},Dn.prototype._handleError=function(n){this.emit("error",n)},Dn.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)},Dn.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var Eb=$i,dS=Us.ACTIONS,hS=Fo,xb=ar;function ar(n,t){if(Eb.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={}}Eb.mixin(ar),ar.prototype.submit=function(n,t){this.value=n,this.send(t)},ar.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},ar.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()})},ar.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},ar.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},ar.prototype._message=function(){return{a:dS.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},ar.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},ar.prototype._callbackOrEmit=function(n,t){if(t)return hS.nextTick(t,n);n&&this.emit("error",n)};var fS=Fo,Ib=cp;function cp(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}cp.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},cp.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&fS.nextTick(n)};var ap={exports:{}};(function(n,t){(function(e,o){o(t)})(cr,function(e){function o(k,I){I=I|0;for(var L=Math.max(k.length-I,0),F=Array(L),U=0;U<L;U++)F[U]=k[I+U];return F}var r=function(k){var I=o(arguments,1);return function(){var L=o(arguments);return k.apply(null,I.concat(L))}},i=function(k){return function(){var I=o(arguments),L=I.pop();k.call(this,I,L)}};function s(k){var I=typeof k;return k!=null&&(I=="object"||I=="function")}var l=typeof setImmediate=="function"&&setImmediate,a=typeof process=="object"&&typeof process.nextTick=="function";function d(k){setTimeout(k,0)}function h(k){return function(I){var L=o(arguments,1);k(function(){I.apply(null,L)})}}var p;l?p=setImmediate:a?p=process.nextTick:p=d;var A=h(p);function v(k){return i(function(I,L){var F;try{F=k.apply(this,I)}catch(U){return L(U)}s(F)&&typeof F.then=="function"?F.then(function(U){B(L,null,U)},function(U){B(L,U.message?U:new Error(U))}):L(null,F)})}function B(k,I,L){try{k(I,L)}catch(F){A(D,F)}}function D(k){throw k}var T=typeof Symbol=="function";function _(k){return T&&k[Symbol.toStringTag]==="AsyncFunction"}function M(k){return _(k)?v(k):k}function H(k){return function(I){var L=o(arguments,1),F=i(function(U,j){var Z=this;return k(I,function(J,lt){M(J).apply(Z,U.concat(lt))},j)});return L.length?F.apply(this,L):F}}var z=typeof cr=="object"&&cr&&cr.Object===Object&&cr,q=typeof self=="object"&&self&&self.Object===Object&&self,rt=z||q||Function("return this")(),ft=rt.Symbol,Bt=Object.prototype,jt=Bt.hasOwnProperty,Ut=Bt.toString,ee=ft?ft.toStringTag:void 0;function Ye(k){var I=jt.call(k,ee),L=k[ee];try{k[ee]=void 0;var F=!0}catch{}var U=Ut.call(k);return F&&(I?k[ee]=L:delete k[ee]),U}var Wo=Object.prototype,Ne=Wo.toString;function Ln(k){return Ne.call(k)}var vr="[object Null]",bn="[object Undefined]",an=ft?ft.toStringTag:void 0;function yr(k){return k==null?k===void 0?bn:vr:an&&an in Object(k)?Ye(k):Ln(k)}var ei="[object AsyncFunction]",mo="[object Function]",t3="[object GeneratorFunction]",e3="[object Proxy]";function n3(k){if(!s(k))return!1;var I=yr(k);return I==mo||I==t3||I==ei||I==e3}var ns=9007199254740991;function ol(k){return typeof k=="number"&&k>-1&&k%1==0&&k<=ns}function rl(k){return k!=null&&ol(k.length)&&!n3(k)}var ni={};function Nt(){}function kr(k){return function(){if(k!==null){var I=k;k=null,I.apply(this,arguments)}}}var os=typeof Symbol=="function"&&Symbol.iterator,Pc=function(k){return os&&k[os]&&k[os]()};function s1(k,I){for(var L=-1,F=Array(k);++L<k;)F[L]=I(L);return F}function un(k){return k!=null&&typeof k=="object"}var il="[object Arguments]";function l1(k){return un(k)&&yr(k)==il}var go=Object.prototype,c1=go.hasOwnProperty,o3=go.propertyIsEnumerable,sl=l1(function(){return arguments}())?l1:function(k){return un(k)&&c1.call(k,"callee")&&!o3.call(k,"callee")},Ce=Array.isArray;function ll(){return!1}var cl=typeof e=="object"&&e&&!e.nodeType&&e,a1=cl&&!0&&n&&!n.nodeType&&n,al=a1&&a1.exports===cl,u1=al?rt.Buffer:void 0,ul=u1?u1.isBuffer:void 0,rs=ul||ll,Hu=9007199254740991,ju=/^(?:0|[1-9]\d*)$/;function Uu(k,I){var L=typeof k;return I=I==null?Hu:I,!!I&&(L=="number"||L!="symbol"&&ju.test(k))&&k>-1&&k%1==0&&k<I}var zu="[object Arguments]",Vu="[object Array]",Wu="[object Boolean]",qu="[object Date]",Gu="[object Error]",Zu="[object Function]",r3="[object Map]",i3="[object Number]",s3="[object Object]",d1="[object RegExp]",h1="[object Set]",l3="[object String]",c3="[object WeakMap]",a3="[object ArrayBuffer]",u3="[object DataView]",f1="[object Float32Array]",d3="[object Float64Array]",h3="[object Int8Array]",f3="[object Int16Array]",Qu="[object Int32Array]",m3="[object Uint8Array]",Yu="[object Uint8ClampedArray]",g3="[object Uint16Array]",p3="[object Uint32Array]",ie={};ie[f1]=ie[d3]=ie[h3]=ie[f3]=ie[Qu]=ie[m3]=ie[Yu]=ie[g3]=ie[p3]=!0,ie[zu]=ie[Vu]=ie[a3]=ie[Wu]=ie[u3]=ie[qu]=ie[Gu]=ie[Zu]=ie[r3]=ie[i3]=ie[s3]=ie[d1]=ie[h1]=ie[l3]=ie[c3]=!1;function C3(k){return un(k)&&ol(k.length)&&!!ie[yr(k)]}function A3(k){return function(I){return k(I)}}var m1=typeof e=="object"&&e&&!e.nodeType&&e,dl=m1&&!0&&n&&!n.nodeType&&n,b3=dl&&dl.exports===m1,Nc=b3&&z.process,g1=function(){try{var k=dl&&dl.require&&dl.require("util").types;return k||Nc&&Nc.binding&&Nc.binding("util")}catch{}}(),p1=g1&&g1.isTypedArray,v3=p1?A3(p1):C3,y3=Object.prototype,k3=y3.hasOwnProperty;function w3(k,I){var L=Ce(k),F=!L&&sl(k),U=!L&&!F&&rs(k),j=!L&&!F&&!U&&v3(k),Z=L||F||U||j,J=Z?s1(k.length,String):[],lt=J.length;for(var pt in k)(I||k3.call(k,pt))&&!(Z&&(pt=="length"||U&&(pt=="offset"||pt=="parent")||j&&(pt=="buffer"||pt=="byteLength"||pt=="byteOffset")||Uu(pt,lt)))&&J.push(pt);return J}var $c=Object.prototype;function B3(k){var I=k&&k.constructor,L=typeof I=="function"&&I.prototype||$c;return k===L}function Hc(k,I){return function(L){return k(I(L))}}var E3=Hc(Object.keys,Object),x3=Object.prototype,I3=x3.hasOwnProperty;function C1(k){if(!B3(k))return E3(k);var I=[];for(var L in Object(k))I3.call(k,L)&&L!="constructor"&&I.push(L);return I}function jc(k){return rl(k)?w3(k):C1(k)}function A1(k){var I=-1,L=k.length;return function(){return++I<L?{value:k[I],key:I}:null}}function T3(k){var I=-1;return function(){var F=k.next();return F.done?null:(I++,{value:F.value,key:I})}}function D3(k){var I=jc(k),L=-1,F=I.length;return function U(){var j=I[++L];return j==="__proto__"?U():L<F?{value:k[j],key:j}:null}}function S3(k){if(rl(k))return A1(k);var I=Pc(k);return I?T3(I):D3(k)}function po(k){return function(){if(k===null)throw new Error("Callback was already called.");var I=k;k=null,I.apply(this,arguments)}}function hl(k){return function(I,L,F){if(F=kr(F||Nt),k<=0||!I)return F(null);var U=S3(I),j=!1,Z=0,J=!1;function lt(ct,At){if(Z-=1,ct)j=!0,F(ct);else{if(At===ni||j&&Z<=0)return j=!0,F(null);J||pt()}}function pt(){for(J=!0;Z<k&&!j;){var ct=U();if(ct===null){j=!0,Z<=0&&F(null);return}Z+=1,L(ct.value,ct.key,po(lt))}J=!1}pt()}}function wr(k,I,L,F){hl(I)(k,M(L),F)}function $e(k,I){return function(L,F,U){return k(L,I,F,U)}}function Ju(k,I,L){L=kr(L||Nt);var F=0,U=0,j=k.length;j===0&&L(null);function Z(J,lt){J?L(J):(++U===j||lt===ni)&&L(null)}for(;F<j;F++)I(k[F],F,po(Z))}var L3=$e(wr,1/0),qo=function(k,I,L){var F=rl(k)?Ju:L3;F(k,M(I),L)};function Go(k){return function(I,L,F){return k(qo,I,M(L),F)}}function Ku(k,I,L,F){F=F||Nt,I=I||[];var U=[],j=0,Z=M(L);k(I,function(J,lt,pt){var ct=j++;Z(J,function(At,Gt){U[ct]=Gt,pt(At)})},function(J){F(J,U)})}var Uc=Go(Ku),Xu=H(Uc);function oi(k){return function(I,L,F,U){return k(hl(L),I,M(F),U)}}var Br=oi(Ku),td=$e(Br,1),ed=H(td);function is(k,I){for(var L=-1,F=k==null?0:k.length;++L<F&&I(k[L],L,k)!==!1;);return k}function nd(k){return function(I,L,F){for(var U=-1,j=Object(I),Z=F(I),J=Z.length;J--;){var lt=Z[k?J:++U];if(L(j[lt],lt,j)===!1)break}return I}}var ss=nd();function ls(k,I){return k&&ss(k,I,jc)}function b1(k,I,L,F){for(var U=k.length,j=L+(F?1:-1);F?j--:++j<U;)if(I(k[j],j,k))return j;return-1}function M3(k){return k!==k}function v1(k,I,L){for(var F=L-1,U=k.length;++F<U;)if(k[F]===I)return F;return-1}function fl(k,I,L){return I===I?v1(k,I,L):b1(k,M3,L)}var zc=function(k,I,L){typeof I=="function"&&(L=I,I=null),L=kr(L||Nt);var F=jc(k),U=F.length;if(!U)return L(null);I||(I=U);var j={},Z=0,J=!1,lt=Object.create(null),pt=[],ct=[],At={};ls(k,function(de,oe){if(!Ce(de)){Gt(oe,[de]),ct.push(oe);return}var ge=de.slice(0,de.length-1),Ao=ge.length;if(Ao===0){Gt(oe,de),ct.push(oe);return}At[oe]=Ao,is(ge,function(E){if(!k[E])throw new Error("async.auto task `"+oe+"` has a non-existent dependency `"+E+"` in "+ge.join(", "));en(E,function(){Ao--,Ao===0&&Gt(oe,de)})})}),t5(),Ie();function Gt(de,oe){pt.push(function(){Co(de,oe)})}function Ie(){if(pt.length===0&&Z===0)return L(null,j);for(;pt.length&&Z<I;){var de=pt.shift();de()}}function en(de,oe){var ge=lt[de];ge||(ge=lt[de]=[]),ge.push(oe)}function On(de){var oe=lt[de]||[];is(oe,function(ge){ge()}),Ie()}function Co(de,oe){if(!J){var ge=po(function(E,Ir){if(Z--,arguments.length>2&&(Ir=o(arguments,1)),E){var ds={};ls(j,function(_n,Pt){ds[Pt]=_n}),ds[de]=Ir,J=!0,lt=Object.create(null),L(E,ds)}else j[de]=Ir,On(de)});Z++;var Ao=M(oe[oe.length-1]);oe.length>1?Ao(j,ge):Ao(ge)}}function t5(){for(var de,oe=0;ct.length;)de=ct.pop(),oe++,is(e5(de),function(ge){--At[ge]===0&&ct.push(ge)});if(oe!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function e5(de){var oe=[];return ls(k,function(ge,Ao){Ce(ge)&&fl(ge,de,0)>=0&&oe.push(Ao)}),oe}};function ri(k,I){for(var L=-1,F=k==null?0:k.length,U=Array(F);++L<F;)U[L]=I(k[L],L,k);return U}var R3="[object Symbol]";function O3(k){return typeof k=="symbol"||un(k)&&yr(k)==R3}var _3=1/0,od=ft?ft.prototype:void 0,y1=od?od.toString:void 0;function rd(k){if(typeof k=="string")return k;if(Ce(k))return ri(k,rd)+"";if(O3(k))return y1?y1.call(k):"";var I=k+"";return I=="0"&&1/k==-_3?"-0":I}function F3(k,I,L){var F=-1,U=k.length;I<0&&(I=-I>U?0:U+I),L=L>U?U:L,L<0&&(L+=U),U=I>L?0:L-I>>>0,I>>>=0;for(var j=Array(U);++F<U;)j[F]=k[F+I];return j}function P3(k,I,L){var F=k.length;return L=L===void 0?F:L,!I&&L>=F?k:F3(k,I,L)}function id(k,I){for(var L=k.length;L--&&fl(I,k[L],0)>-1;);return L}function N3(k,I){for(var L=-1,F=k.length;++L<F&&fl(I,k[L],0)>-1;);return L}function $3(k){return k.split("")}var H3="\\ud800-\\udfff",j3="\\u0300-\\u036f",U3="\\ufe20-\\ufe2f",se="\\u20d0-\\u20ff",ne=j3+U3+se,z3="\\ufe0e\\ufe0f",V3="\\u200d",W3=RegExp("["+V3+H3+ne+z3+"]");function q3(k){return W3.test(k)}var k1="\\ud800-\\udfff",G3="\\u0300-\\u036f",w1="\\ufe20-\\ufe2f",Z3="\\u20d0-\\u20ff",qe=G3+w1+Z3,sd="\\ufe0e\\ufe0f",ii="["+k1+"]",Vc="["+qe+"]",ml="\\ud83c[\\udffb-\\udfff]",Mn="(?:"+Vc+"|"+ml+")",ld="[^"+k1+"]",cd="(?:\\ud83c[\\udde6-\\uddff]){2}",ad="[\\ud800-\\udbff][\\udc00-\\udfff]",B1="\\u200d",ud=Mn+"?",dd="["+sd+"]?",vn="(?:"+B1+"(?:"+[ld,cd,ad].join("|")+")"+dd+ud+")*",Q3=dd+ud+vn,Rn="(?:"+[ld+Vc+"?",Vc,cd,ad,ii].join("|")+")",Y3=RegExp(ml+"(?="+ml+")|"+Rn+Q3,"g");function E1(k){return k.match(Y3)||[]}function Zo(k){return q3(k)?E1(k):$3(k)}function Wc(k){return k==null?"":rd(k)}var hd=/^\s+|\s+$/g;function ue(k,I,L){if(k=Wc(k),k&&(L||I===void 0))return k.replace(hd,"");if(!k||!(I=rd(I)))return k;var F=Zo(k),U=Zo(I),j=N3(F,U),Z=id(F,U)+1;return P3(F,j,Z).join("")}var Er=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,fd=/,/,J3=/(=.+)?(\s*)$/,md=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function K3(k){return k=k.toString().replace(md,""),k=k.match(Er)[2].replace(" ",""),k=k?k.split(fd):[],k=k.map(function(I){return ue(I.replace(J3,""))}),k}function x1(k,I){var L={};ls(k,function(F,U){var j,Z=_(F),J=!Z&&F.length===1||Z&&F.length===0;if(Ce(F))j=F.slice(0,-1),F=F[F.length-1],L[U]=j.concat(j.length>0?lt:F);else if(J)L[U]=F;else{if(j=K3(F),F.length===0&&!Z&&j.length===0)throw new Error("autoInject task functions require explicit parameters.");Z||j.pop(),L[U]=j.concat(lt)}function lt(pt,ct){var At=ri(j,function(Gt){return pt[Gt]});At.push(ct),M(F).apply(null,At)}}),zc(L,I)}function Yn(){this.head=this.tail=null,this.length=0}function gd(k,I){k.length=1,k.head=k.tail=I}Yn.prototype.removeLink=function(k){return k.prev?k.prev.next=k.next:this.head=k.next,k.next?k.next.prev=k.prev:this.tail=k.prev,k.prev=k.next=null,this.length-=1,k},Yn.prototype.empty=function(){for(;this.head;)this.shift();return this},Yn.prototype.insertAfter=function(k,I){I.prev=k,I.next=k.next,k.next?k.next.prev=I:this.tail=I,k.next=I,this.length+=1},Yn.prototype.insertBefore=function(k,I){I.prev=k.prev,I.next=k,k.prev?k.prev.next=I:this.head=I,k.prev=I,this.length+=1},Yn.prototype.unshift=function(k){this.head?this.insertBefore(this.head,k):gd(this,k)},Yn.prototype.push=function(k){this.tail?this.insertAfter(this.tail,k):gd(this,k)},Yn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},Yn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},Yn.prototype.toArray=function(){for(var k=Array(this.length),I=this.head,L=0;L<this.length;L++)k[L]=I.data,I=I.next;return k},Yn.prototype.remove=function(k){for(var I=this.head;I;){var L=I.next;k(I)&&this.removeLink(I),I=L}return this};function gl(k,I,L){if(I==null)I=1;else if(I===0)throw new Error("Concurrency must not be zero");var F=M(k),U=0,j=[],Z=!1;function J(At,Gt,Ie){if(Ie!=null&&typeof Ie!="function")throw new Error("task callback must be a function");if(ct.started=!0,Ce(At)||(At=[At]),At.length===0&&ct.idle())return A(function(){ct.drain()});for(var en=0,On=At.length;en<On;en++){var Co={data:At[en],callback:Ie||Nt};Gt?ct._tasks.unshift(Co):ct._tasks.push(Co)}Z||(Z=!0,A(function(){Z=!1,ct.process()}))}function lt(At){return function(Gt){U-=1;for(var Ie=0,en=At.length;Ie<en;Ie++){var On=At[Ie],Co=fl(j,On,0);Co===0?j.shift():Co>0&&j.splice(Co,1),On.callback.apply(On,arguments),Gt!=null&&ct.error(Gt,On.data)}U<=ct.concurrency-ct.buffer&&ct.unsaturated(),ct.idle()&&ct.drain(),ct.process()}}var pt=!1,ct={_tasks:new Yn,concurrency:I,payload:L,saturated:Nt,unsaturated:Nt,buffer:I/4,empty:Nt,drain:Nt,error:Nt,started:!1,paused:!1,push:function(At,Gt){J(At,!1,Gt)},kill:function(){ct.drain=Nt,ct._tasks.empty()},unshift:function(At,Gt){J(At,!0,Gt)},remove:function(At){ct._tasks.remove(At)},process:function(){if(!pt){for(pt=!0;!ct.paused&&U<ct.concurrency&&ct._tasks.length;){var At=[],Gt=[],Ie=ct._tasks.length;ct.payload&&(Ie=Math.min(Ie,ct.payload));for(var en=0;en<Ie;en++){var On=ct._tasks.shift();At.push(On),j.push(On),Gt.push(On.data)}U+=1,ct._tasks.length===0&&ct.empty(),U===ct.concurrency&&ct.saturated();var Co=po(lt(At));F(Gt,Co)}pt=!1}},length:function(){return ct._tasks.length},running:function(){return U},workersList:function(){return j},idle:function(){return ct._tasks.length+U===0},pause:function(){ct.paused=!0},resume:function(){ct.paused!==!1&&(ct.paused=!1,A(ct.process))}};return ct}function si(k,I){return gl(k,1,I)}var cs=$e(wr,1);function Qo(k,I,L,F){F=kr(F||Nt);var U=M(L);cs(k,function(j,Z,J){U(I,j,function(lt,pt){I=pt,J(lt)})},function(j){F(j,I)})}function qc(){var k=ri(arguments,M);return function(){var I=o(arguments),L=this,F=I[I.length-1];typeof F=="function"?I.pop():F=Nt,Qo(k,I,function(U,j,Z){j.apply(L,U.concat(function(J){var lt=o(arguments,1);Z(J,lt)}))},function(U,j){F.apply(L,[U].concat(j))})}}var Gc=function(){return qc.apply(null,o(arguments).reverse())},pd=Array.prototype.concat,pl=function(k,I,L,F){F=F||Nt;var U=M(L);Br(k,I,function(j,Z){U(j,function(J){return J?Z(J):Z(null,o(arguments,1))})},function(j,Z){for(var J=[],lt=0;lt<Z.length;lt++)Z[lt]&&(J=pd.apply(J,Z[lt]));return F(j,J)})},I1=$e(pl,1/0),Zc=$e(pl,1),Qc=function(){var k=o(arguments),I=[null].concat(k);return function(){var L=arguments[arguments.length-1];return L.apply(this,I)}};function Cl(k){return k}function li(k,I){return function(L,F,U,j){j=j||Nt;var Z=!1,J;L(F,function(lt,pt,ct){U(lt,function(At,Gt){At?ct(At):k(Gt)&&!J?(Z=!0,J=I(!0,lt),ct(null,ni)):ct()})},function(lt){lt?j(lt):j(null,Z?J:I(!1))})}}function dn(k,I){return I}var as=Go(li(Cl,dn)),Yo=oi(li(Cl,dn)),Al=$e(Yo,1);function Cd(k){return function(I){var L=o(arguments,1);L.push(function(F){var U=o(arguments,1);typeof console=="object"&&(F?console.error&&console.error(F):console[k]&&is(U,function(j){console[k](j)}))}),M(I).apply(null,L)}}var T1=Cd("dir");function D1(k,I,L){L=po(L||Nt);var F=M(k),U=M(I);function j(J){if(J)return L(J);var lt=o(arguments,1);lt.push(Z),U.apply(this,lt)}function Z(J,lt){if(J)return L(J);if(!lt)return L(null);F(j)}Z(null,!0)}function Ad(k,I,L){L=po(L||Nt);var F=M(k),U=function(j){if(j)return L(j);var Z=o(arguments,1);if(I.apply(this,Z))return F(U);L.apply(null,[null].concat(Z))};F(U)}function S1(k,I,L){Ad(k,function(){return!I.apply(this,arguments)},L)}function L1(k,I,L){L=po(L||Nt);var F=M(I),U=M(k);function j(J){if(J)return L(J);U(Z)}function Z(J,lt){if(J)return L(J);if(!lt)return L(null);F(j)}U(Z)}function ci(k){return function(I,L,F){return k(I,F)}}function Yc(k,I,L){qo(k,ci(M(I)),L)}function bl(k,I,L,F){hl(I)(k,ci(M(L)),F)}var ai=$e(bl,1);function Jc(k){return _(k)?k:i(function(I,L){var F=!0;I.push(function(){var U=arguments;F?A(function(){L.apply(null,U)}):L.apply(null,U)}),k.apply(this,I),F=!1})}function Jn(k){return!k}var ui=Go(li(Jn,Jn)),vl=oi(li(Jn,Jn)),Kc=$e(vl,1);function M1(k){return function(I){return I==null?void 0:I[k]}}function us(k,I,L,F){var U=new Array(I.length);k(I,function(j,Z,J){L(j,function(lt,pt){U[Z]=!!pt,J(lt)})},function(j){if(j)return F(j);for(var Z=[],J=0;J<I.length;J++)U[J]&&Z.push(I[J]);F(null,Z)})}function Kn(k,I,L,F){var U=[];k(I,function(j,Z,J){L(j,function(lt,pt){lt?J(lt):(pt&&U.push({index:Z,value:j}),J())})},function(j){j?F(j):F(null,ri(U.sort(function(Z,J){return Z.index-J.index}),M1("value")))})}function Xc(k,I,L,F){var U=rl(I)?us:Kn;U(k,I,M(L),F||Nt)}var ta=Go(Xc),yl=oi(Xc),ea=$e(yl,1);function R1(k,I){var L=po(I||Nt),F=M(Jc(k));function U(j){if(j)return L(j);F(U)}U()}var na=function(k,I,L,F){F=F||Nt;var U=M(L);Br(k,I,function(j,Z){U(j,function(J,lt){return J?Z(J):Z(null,{key:lt,val:j})})},function(j,Z){for(var J={},lt=Object.prototype.hasOwnProperty,pt=0;pt<Z.length;pt++)if(Z[pt]){var ct=Z[pt].key,At=Z[pt].val;lt.call(J,ct)?J[ct].push(At):J[ct]=[At]}return F(j,J)})},di=$e(na,1/0),N=$e(na,1),G=Cd("log");function V(k,I,L,F){F=kr(F||Nt);var U={},j=M(L);wr(k,I,function(Z,J,lt){j(Z,J,function(pt,ct){if(pt)return lt(pt);U[J]=ct,lt()})},function(Z){F(Z,U)})}var ht=$e(V,1/0),Et=$e(V,1);function Vt(k,I){return I in k}function we(k,I){var L=Object.create(null),F=Object.create(null);I=I||Cl;var U=M(k),j=i(function(J,lt){var pt=I.apply(null,J);Vt(L,pt)?A(function(){lt.apply(null,L[pt])}):Vt(F,pt)?F[pt].push(lt):(F[pt]=[lt],U.apply(null,J.concat(function(){var ct=o(arguments);L[pt]=ct;var At=F[pt];delete F[pt];for(var Gt=0,Ie=At.length;Gt<Ie;Gt++)At[Gt].apply(null,ct)})))});return j.memo=L,j.unmemoized=k,j}var qt;a?qt=process.nextTick:l?qt=setImmediate:qt=d;var oa=h(qt);function bd(k,I,L){L=L||Nt;var F=rl(I)?[]:{};k(I,function(U,j,Z){M(U)(function(J,lt){arguments.length>2&&(lt=o(arguments,1)),F[j]=lt,Z(J)})},function(U){L(U,F)})}function yn(k,I){bd(qo,k,I)}function kl(k,I,L){bd(hl(I),k,L)}var vd=function(k,I){var L=M(k);return gl(function(F,U){L(F[0],U)},I,1)},hi=function(k,I){var L=vd(k,I);return L.push=function(F,U,j){if(j==null&&(j=Nt),typeof j!="function")throw new Error("task callback must be a function");if(L.started=!0,Ce(F)||(F=[F]),F.length===0)return A(function(){L.drain()});U=U||0;for(var Z=L._tasks.head;Z&&U>=Z.priority;)Z=Z.next;for(var J=0,lt=F.length;J<lt;J++){var pt={data:F[J],priority:U,callback:j};Z?L._tasks.insertBefore(Z,pt):L._tasks.push(pt)}A(L.process)},delete L.unshift,L};function wl(k,I){if(I=kr(I||Nt),!Ce(k))return I(new TypeError("First argument to race must be an array of functions"));if(!k.length)return I();for(var L=0,F=k.length;L<F;L++)M(k[L])(I)}function fi(k,I,L,F){var U=o(k).reverse();Qo(U,I,L,F)}function Wt(k){var I=M(k);return i(function(F,U){return F.push(function(Z,J){if(Z)U(null,{error:Z});else{var lt;arguments.length<=2?lt=J:lt=o(arguments,1),U(null,{value:lt})}}),I.apply(this,F)})}function O1(k){var I;return Ce(k)?I=ri(k,Wt):(I={},ls(k,function(L,F){I[F]=Wt.call(this,L)})),I}function yd(k,I,L,F){Xc(k,I,function(U,j){L(U,function(Z,J){j(Z,!J)})},F)}var Bl=Go(yd),kd=oi(yd),_1=$e(kd,1);function F1(k){return function(){return k}}function mi(k,I,L){var F=5,U=0,j={times:F,intervalFunc:F1(U)};function Z(ct,At){if(typeof At=="object")ct.times=+At.times||F,ct.intervalFunc=typeof At.interval=="function"?At.interval:F1(+At.interval||U),ct.errorFilter=At.errorFilter;else if(typeof At=="number"||typeof At=="string")ct.times=+At||F;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof k=="function"?(L=I||Nt,I=k):(Z(j,k),L=L||Nt),typeof I!="function")throw new Error("Invalid arguments for async.retry");var J=M(I),lt=1;function pt(){J(function(ct){ct&&lt++<j.times&&(typeof j.errorFilter!="function"||j.errorFilter(ct))?setTimeout(pt,j.intervalFunc(lt)):L.apply(null,arguments)})}pt()}var Jo=function(k,I){I||(I=k,k=null);var L=M(I);return i(function(F,U){function j(Z){L.apply(null,F.concat(Z))}k?mi(k,j,U):mi(j,U)})};function El(k,I){bd(cs,k,I)}var xl=Go(li(Boolean,Cl)),xr=oi(li(Boolean,Cl)),Il=$e(xr,1);function wd(k,I,L){var F=M(I);Uc(k,function(j,Z){F(j,function(J,lt){if(J)return Z(J);Z(null,{value:j,criteria:lt})})},function(j,Z){if(j)return L(j);L(null,ri(Z.sort(U),M1("value")))});function U(j,Z){var J=j.criteria,lt=Z.criteria;return J<lt?-1:J>lt?1:0}}function Tl(k,I,L){var F=M(k);return i(function(U,j){var Z=!1,J;function lt(){var pt=k.name||"anonymous",ct=new Error('Callback function "'+pt+'" timed out.');ct.code="ETIMEDOUT",L&&(ct.info=L),Z=!0,j(ct)}U.push(function(){Z||(j.apply(null,arguments),clearTimeout(J))}),J=setTimeout(lt,I),F.apply(null,U)})}var P1=Math.ceil,Dl=Math.max;function gi(k,I,L,F){for(var U=-1,j=Dl(P1((I-k)/(L||1)),0),Z=Array(j);j--;)Z[F?j:++U]=k,k+=L;return Z}function pi(k,I,L,F){var U=M(L);Br(gi(0,k,1),I,U,F)}var N1=$e(pi,1/0),$1=$e(pi,1);function H1(k,I,L,F){arguments.length<=3&&(F=L,L=I,I=Ce(k)?[]:{}),F=kr(F||Nt);var U=M(L);qo(k,function(j,Z,J){U(I,j,Z,J)},function(j){F(j,I)})}function Sl(k,I){var L=null,F;I=I||Nt,ai(k,function(U,j){M(U)(function(Z,J){arguments.length>2?F=o(arguments,1):F=J,L=Z,j(!Z)})},function(){I(L,F)})}function Ll(k){return function(){return(k.unmemoized||k).apply(null,arguments)}}function Ml(k,I,L){L=po(L||Nt);var F=M(I);if(!k())return L(null);var U=function(j){if(j)return L(j);if(k())return F(U);var Z=o(arguments,1);L.apply(null,[null].concat(Z))};F(U)}function j1(k,I,L){Ml(function(){return!k.apply(this,arguments)},I,L)}var Bd=function(k,I){if(I=kr(I||Nt),!Ce(k))return I(new Error("First argument to waterfall must be an array of functions"));if(!k.length)return I();var L=0;function F(j){var Z=M(k[L++]);j.push(po(U)),Z.apply(null,j)}function U(j){if(j||L===k.length)return I.apply(null,arguments);F(o(arguments,1))}F([])},X3={apply:r,applyEach:Xu,applyEachSeries:ed,asyncify:v,auto:zc,autoInject:x1,cargo:si,compose:Gc,concat:I1,concatLimit:pl,concatSeries:Zc,constant:Qc,detect:as,detectLimit:Yo,detectSeries:Al,dir:T1,doDuring:D1,doUntil:S1,doWhilst:Ad,during:L1,each:Yc,eachLimit:bl,eachOf:qo,eachOfLimit:wr,eachOfSeries:cs,eachSeries:ai,ensureAsync:Jc,every:ui,everyLimit:vl,everySeries:Kc,filter:ta,filterLimit:yl,filterSeries:ea,forever:R1,groupBy:di,groupByLimit:na,groupBySeries:N,log:G,map:Uc,mapLimit:Br,mapSeries:td,mapValues:ht,mapValuesLimit:V,mapValuesSeries:Et,memoize:we,nextTick:oa,parallel:yn,parallelLimit:kl,priorityQueue:hi,queue:vd,race:wl,reduce:Qo,reduceRight:fi,reflect:Wt,reflectAll:O1,reject:Bl,rejectLimit:kd,rejectSeries:_1,retry:mi,retryable:Jo,seq:qc,series:El,setImmediate:A,some:xl,someLimit:xr,someSeries:Il,sortBy:wd,timeout:Tl,times:N1,timesLimit:pi,timesSeries:$1,transform:H1,tryEach:Sl,unmemoize:Ll,until:j1,waterfall:Bd,whilst:Ml,all:ui,allLimit:vl,allSeries:Kc,any:xl,anyLimit:xr,anySeries:Il,find:as,findLimit:Yo,findSeries:Al,forEach:Yc,forEachSeries:ai,forEachLimit:bl,forEachOf:qo,forEachOfSeries:cs,forEachOfLimit:wr,inject:Qo,foldl:Qo,foldr:fi,select:ta,selectLimit:yl,selectSeries:ea,wrapSync:v};e.default=X3,e.apply=r,e.applyEach=Xu,e.applyEachSeries=ed,e.asyncify=v,e.auto=zc,e.autoInject=x1,e.cargo=si,e.compose=Gc,e.concat=I1,e.concatLimit=pl,e.concatSeries=Zc,e.constant=Qc,e.detect=as,e.detectLimit=Yo,e.detectSeries=Al,e.dir=T1,e.doDuring=D1,e.doUntil=S1,e.doWhilst=Ad,e.during=L1,e.each=Yc,e.eachLimit=bl,e.eachOf=qo,e.eachOfLimit=wr,e.eachOfSeries=cs,e.eachSeries=ai,e.ensureAsync=Jc,e.every=ui,e.everyLimit=vl,e.everySeries=Kc,e.filter=ta,e.filterLimit=yl,e.filterSeries=ea,e.forever=R1,e.groupBy=di,e.groupByLimit=na,e.groupBySeries=N,e.log=G,e.map=Uc,e.mapLimit=Br,e.mapSeries=td,e.mapValues=ht,e.mapValuesLimit=V,e.mapValuesSeries=Et,e.memoize=we,e.nextTick=oa,e.parallel=yn,e.parallelLimit=kl,e.priorityQueue=hi,e.queue=vd,e.race=wl,e.reduce=Qo,e.reduceRight=fi,e.reflect=Wt,e.reflectAll=O1,e.reject=Bl,e.rejectLimit=kd,e.rejectSeries=_1,e.retry=mi,e.retryable=Jo,e.seq=qc,e.series=El,e.setImmediate=A,e.some=xl,e.someLimit=xr,e.someSeries=Il,e.sortBy=wd,e.timeout=Tl,e.times=N1,e.timesLimit=pi,e.timesSeries=$1,e.transform=H1,e.tryEach=Sl,e.unmemoize=Ll,e.until=j1,e.waterfall=Bd,e.whilst=Ml,e.all=ui,e.allLimit=vl,e.allSeries=Kc,e.any=xl,e.anyLimit=xr,e.anySeries=Il,e.find=as,e.findLimit=Yo,e.findSeries=Al,e.forEach=Yc,e.forEachSeries=ai,e.forEachLimit=bl,e.forEachOf=qo,e.forEachOfSeries=cs,e.forEachOfLimit=wr,e.inject=Qo,e.foldl=Qo,e.foldr=fi,e.select=ta,e.selectLimit=yl,e.selectSeries=ea,e.wrapSync=v,Object.defineProperty(e,"__esModule",{value:!0})})})(ap,ap.exports);var Tb={exports:{}},up=Tb.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 a=parseInt(i,t);return a!==1/0&&a>=Math.pow(2,n)?up(n,t):i};up.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=up(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 Db=$i,mS=xb,gS=Ib,jh=Fo,dp=ap.exports,pS=Tb.exports,Sb=Us.ACTIONS,Lb=Me;function Me(n,t){if(Db.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}Db.mixin(Me),Me.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Me.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Me.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||pS();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Me.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);dp.parallel([function(i){dp.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();dp.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)})})},Me.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?Sb.presenceSubscribe:Sb.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,o,this)},Me.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Me.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Me.prototype._receiveUpdate=function(n,t){var e=jh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=jh.digOrCreate(this._remotePresenceInstances,t.id,function(){return o._createRemotePresence(t.id)});r.receiveUpdate(t)},Me.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Me.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()}},Me.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Me.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Me.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)})},Me.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Me.prototype._callbackOrEmit=function(n,t){if(t)return jh.nextTick(t,n);n&&this.emit("error",n)},Me.prototype._createLocalPresence=function(n){return new mS(this,n)},Me.prototype._createRemotePresence=function(n){return new gS(this,n)},Me.prototype._callEachOrEmit=function(n,t){var e=jh.callEach(n,t);!e&&t&&this.emit("error",t)};var Wa=xb,Mb=Fh,CS=Fo,Rb=Mb.CODES,AS=No;function No(n,t){Wa.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()}No.prototype=Object.create(Wa.prototype),No.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:Rb.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,Wa.prototype.submit.call(this,n,t)},No.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),Wa.prototype.destroy.call(this,n)},No.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={})})}},No.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)},No.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)}},No.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},No.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},No.prototype._message=function(){var n=Wa.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},No.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!CS.supportsPresence(o))throw new Mb(Rb.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var Ob={};(function(n){var t=Ua,e=Fh,o=Fo,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 a=l.create.type;if(typeof a!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=t.map[a];if(d==null||typeof d!="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,a){if(typeof l!="object")return new e(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&a.v!=null&&l.v!==a.v)return new e(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(a.create){if(l.type)return new e(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=a.create,h=t.map[d.type];if(!h)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(A){return A}}else if(a.del)l.data=void 0,l.type=null,l.v++;else if("op"in a){var p=i(l,a.op);if(p)return p;l.v++}else l.v++};function i(l,a){if(!l.type)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(a===void 0)return new e(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=t.map[l.type];if(!d)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,a)}catch(h){return new e(r.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,a,d){if(a.v!=null&&a.v!==d.v)return new e(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(a.create||"op"in a)return new e(r.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(d.create&&("op"in a||a.create||a.del)||"op"in d&&a.create)return new e(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in a){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{a.op=l.transform(a.op,d.op,"left")}catch(h){return h}}}a.v!=null&&a.v++},n.applyOps=function(l,a,d){d=d||{};for(var h=0;h<a.length;h++){var p=a[h];if(d._normalizeLegacyJson0Ops)try{s(l,p)}catch{return new e(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=p.v;var A=n.apply(l,p);if(A)return A}},n.transformPresence=function(l,a,d){var h=this.checkOp(a);if(h)return h;var p=l.t;if(typeof p=="string"&&(p=t.map[p]),!p)return{code:r.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!o.supportsPresence(p))return{code:r.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(a.create||a.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:p.transformPresence(l.p,a.op,d)}catch(A){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:A.message||A}}l.v++};function s(l,a){if(l.type===t.defaultType.uri){var d=a.op;if(!!d){var h=l.data;d.length>1&&(h=o.clone(h));for(var p=0;p<d.length;p++){var A=d[p];typeof A.lm=="string"&&(A.lm=+A.lm);for(var v=A.p,B=h,D=0;D<v.length;D++){var T=v[D];Object.prototype.toString.call(B)=="[object Array]"?v[D]=+T:B.constructor===Object&&(v[D]=T.toString()),B=B[T]}p<d.length-1&&(h=t.defaultType.apply(h,[A]))}}}}})(Ob);var qa=Ib,bS=Ob,vS=co;function co(n,t){qa.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()}co.prototype=Object.create(qa.prototype),co.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},co.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),qa.prototype.destroy.call(this,n)},co.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)},co.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))}})}},co.prototype._handleOp=function(n,t,e){var o=e===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},qa.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},qa.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},co.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)}},co.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++):bS.transformPresence(this._pending,t,e)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},co.prototype._startCachingOps=function(){this._opCache=[]},co.prototype._stopCachingOps=function(){this._opCache=null},co.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var _b=Lb,yS=AS,kS=vS;function tc(n,t,e){var o=tc.channel(t,e);_b.call(this,n,o),this.collection=t,this.id=e}var wS=tc;tc.prototype=Object.create(_b.prototype),tc.channel=function(n,t){return n+"."+t},tc.prototype._createLocalPresence=function(n){return new yS(this,n)},tc.prototype._createRemotePresence=function(n){return new kS(this,n)};var BS=ES;function ES(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var xS=BS,Fb=$i,Pb=Ga;function Ga(n,t,e,o,r){if(Fb.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}Fb.mixin(Ga),Ga.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Ga.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Ga.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new xS(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var Nb=Pb,IS=Fo,TS=Us.ACTIONS,DS=hp;function hp(n,t,e,o,r,i){if(Nb.call(this,n,t,e,o,i),!IS.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}hp.prototype=Object.create(Nb.prototype),hp.prototype._message=function(){return{a:TS.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var $b=Pb,SS=Fo,LS=Us.ACTIONS,MS=fp;function fp(n,t,e,o,r,i){if($b.call(this,n,t,e,o,i),!SS.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}fp.prototype=Object.create($b.prototype),fp.prototype._message=function(){return{a:LS.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var RS=iS,OS=uS,_S=Lb,Hb=wS,FS=DS,PS=MS,jb=$i,ec=Fh,te=Us.ACTIONS,Ub=Ua,$o=Fo,Za=Cb,Qa=ec.CODES;function zb(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var NS=wt;function wt(n){jb.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=zb(n),this.bindToSocket(n)}jb.mixin(wt),wt.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=zb(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{Za.warn("Failed to parse message",o);return}e.debug&&Za.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){$o.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)}},wt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=Vb(n.error,n),delete n.error),n.a){case te.initLegacy:return this._handleLegacyInit(n);case te.handshake:return this._handleHandshake(t,n);case te.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case te.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case te.queryUnsubscribe:return;case te.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 te.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case te.bulkSubscribe:case te.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case te.snapshotFetch:case te.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case te.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case te.subscribe:case te.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case te.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case te.presence:return this._handlePresence(t,n);case te.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case te.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case te.presenceRequest:return this._handlePresenceRequest(t,n);case te.pingPong:return this._handlePingPong(t);default:Za.warn("Ignoring unrecognized message",n)}};function Vb(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}wt.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](Vb(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 Za.error("Invalid bulk message",t)},wt.prototype._reset=function(){this.agent=null},wt.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 ec(Qa.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 a=this._snapshotRequests[o];a._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},wt.prototype.startBulk=function(){this.bulk||(this.bulk={})},wt.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},wt.prototype._sendBulk=function(n,t,e){if(!!e){var o=[],r={},i=0,s;for(var l in e){var a=e[l];a==null?o.push(l):(r[l]=a,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 d=r[s];this.send({a:n,c:t,d:s,v:d})}else i&&this.send({a:"b"+n,c:t,b:r})}},wt.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)}},wt.prototype.sendFetch=function(n){return this._sendActions(te.fetch,n,n.version)},wt.prototype.sendSubscribe=function(n){return this._sendActions(te.subscribe,n,n.version)},wt.prototype.sendUnsubscribe=function(n){return this._sendActions(te.unsubscribe,n)},wt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:te.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)},wt.prototype.send=function(n){this.debug&&Za.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},wt.prototype.ping=function(){if(!this.canSend)throw new ec(Qa.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:te.pingPong};this.send(n)},wt.prototype.close=function(){this.socket.close()},wt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},wt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new RS(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},wt.prototype._destroyDoc=function(n){!n._wantsDestroy||($o.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},wt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},wt.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new OS(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},wt.prototype._destroyQuery=function(n){delete this.queries[n.id]},wt.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(te.queryFetch,n,t,e,o)},wt.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(te.querySubscribe,n,t,e,o)},wt.prototype.hasPending=function(){return!!(this._firstDoc(Uh)||this._firstQuery(Uh)||this._firstSnapshotRequest())};function Uh(n){return n.hasPending()}wt.prototype.hasWritePending=function(){return!!this._firstDoc($S)};function $S(n){return n.hasWritePending()}wt.prototype.whenNothingPending=function(n){var t=this._firstDoc(Uh);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Uh);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}$o.nextTick(n)},wt.prototype._nothingPendingRetry=function(n){var t=this;return function(){$o.nextTick(function(){t.whenNothingPending(n)})}},wt.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}}},wt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},wt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},wt.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new FS(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},wt.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new PS(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},wt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},wt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},wt.prototype._initializeHandshake=function(){this.send({a:te.handshake,id:this.id})},wt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},wt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},wt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new ec(Qa.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(Ub.map[n.type]!==Ub.defaultType)return this.emit("error",new ec(Qa.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new ec(Qa.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},wt.prototype.getPresence=function(n){var t=this,e=$o.digOrCreate(this._presences,n,function(){return new _S(t,n)});return e._wantsDestroy=!1,e},wt.prototype.getDocPresence=function(n,t){var e=Hb.channel(n,t),o=this,r=$o.digOrCreate(this._presences,e,function(){return new Hb(o,n,t)});return r._wantsDestroy=!1,r},wt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},wt.prototype._addPresence=function(n){$o.digOrCreate(this._presences,n.channel,function(){return n})},wt.prototype._handlePresenceSubscribe=function(n,t){var e=$o.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},wt.prototype._handlePresenceUnsubscribe=function(n,t){var e=$o.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},wt.prototype._handlePresence=function(n,t){var e=$o.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},wt.prototype._handlePresenceRequest=function(n,t){var e=$o.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var Wb=NS,HS=Ua;const zh={err:1001,msg:"user auth error",name:"AuthError"},jS={err:1002,msg:"you don't have required permission",name:"PermissionError"},mp={err:1003,msg:"Too many user connected",name:"MaxUserError"},Ya={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},US={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},zS={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},Ja="x-live-editor-token",Vh="x-live-editor-base-url",gn=S("auth-connection");function VS(n){try{n()}catch(t){gn.error(t)}}class WS{constructor(t,e){m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new q5.EventEmitter);m(this,"token",null);m(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 Bs(this.getBaseURL())}async auth(t){g(gn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[Ja]:t.token,[Vh]: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:{[Vh]:Bs(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new HB.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(Wb.prototype),g(gn,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}}},Wb.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,gn.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){gn.error(t),setTimeout(()=>this.handleAuthError(),0)}}else gn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(zh.msg);t.code=zh.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(Ya.msg);t.code=Ya.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===zh.err)gn.warn("auth error"),this.handleAuthError();else if(o===mp.err)gn.warn(mp.msg),this.emitMaxUsersError();else if(o===Ya.err){gn.warn(Ya.msg);try{this.emitRequestReloadError()}catch(r){gn.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else gn.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError()}get(t,e){return g(gn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(g(gn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){g(gn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){g(gn,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(),VS(()=>{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()}}S("utils/file");function qS(){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}qS();async function GS(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new jB.Hash;for(let s=0;s<o;s++){const l=s*102400;let a=l+102400;a>e&&(a=e);const h=await n.slice(l,a,n.type).arrayBuffer();r.update(new Uint8Array(h))}const i=r.digest();return Bs(i)}const ur=S("sharedb-doc/client");class ZS{constructor(t,e,o){m(this,"connection");m(this,"auth");m(this,"doc",null);m(this,"reauthFunc");m(this,"clientId",K());m(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});g(ur,!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),ur.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;HS.register(_d.type),this.connection=new WS(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return g(ur,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 a=l.split("|");r.push(...a)}),r=Array.from(new Set(r));const i=r.map(l=>this.getFileUrlByHash(o,l,"",0,{[Ja]: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=v=>{ur.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await GS(e),d=await this.getFileUrlByHash(t,a,e.name,e.size,o);if(d)return r(-1),d;let h=t;i!=null&&i.thumbnail&&(h+="/thumbnail");const p=new FormData;p.append("file-size",`${e.size}`),p.append("file-hash",a),p.append("file",e,e.name);const A=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return ur.info(A),r(100),Array.isArray(A.data)?A.data[0]:A.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;g(ur,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[Ja]:this.connection.token},e,o);return g(ur,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 a=e||{};a.url=t,a.headers||(a.headers={}),g(ur,o,"no token"),a.headers={...a.headers,[Ja]:o,[Vh]:this.connection.getBase64BaseURL()};try{return await NB.default(t,a)}catch(d){if(r=d,((i=d==null?void 0:d.response)==null?void 0:i.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw d;o=h.token;continue}throw(s=d.response)!=null&&s.data&&(d.responseData=d.response.data),d}}throw g(ur,r,"no error"),r}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,r=(await this.request(e)).data.versions;return r.forEach(i=>{i.extra&&(i.extra=JSON.parse(i.extra))}),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=$B.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(g(ur,a.create,"no createDoc.create"),d=a.create.data):d=JSON.parse(i.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:i.data.ops}}async updateVersionExtra(t,e,o){const i=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(i,{method:"post",data:{extra:JSON.stringify(o)}})}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/${Bs(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 QS(){return{blocks:[{id:K(),type:"text",text:[]}],comments:{},meta:{}}}const gp=S("block-ids");class YS{constructor(){m(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);g(gp,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=K();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);g(gp,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=K(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class JS{constructor(){m(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new YS,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 g(gp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class qb{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 Wh=S("op-parse-handler");class KS{constructor(t,e){m(this,"actions",[]);this.outerHandler=t,this.local=e}pushActions(t){if(!t.containerId){this.actions.push(t);return}const o={...t,containerId:(r=>r==="blocks"?"root":r)(t.containerId)};this.actions.push(o)}onDeleteBlock(t,e){this.pushActions({type:"deleteBlock",containerId:t,blockIndex:e})}onInsertBlock(t,e,o){this.pushActions({type:"insertBlock",containerId:t,blockIndex:e,data:o})}onDeleteBlockData(t,e,o){this.pushActions({type:"deleteBlockData",containerId:t,blockIndex:e,key:o})}onInsertBlockData(t,e,o,r){this.pushActions({type:"insertBlockData",containerId:t,blockIndex:e,key:o,value:r})}onUpdateBlockText(t,e,o){this.pushActions({type:"updateBlockText",containerId:t,blockIndex:e,richTextData:o})}onDeleteContainer(t){this.pushActions({type:"deleteContainer",containerId:t})}onCreateContainer(t,e){this.pushActions({type:"createContainer",containerId:t,data:e})}onDeleteComment(t){this.pushActions({type:"deleteComment",commentId:t})}onCreateComment(t){this.pushActions({type:"createComment",commentId:t})}onUpdateComment(t){this.pushActions({type:"updateComment",commentId:t})}end(){const t=this.actions,e=new Set,o=new Map,r=new JS,i=t.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of i)if(s.type==="deleteBlock"){const l=s,a=r.getBlockId(l.containerId,l.blockIndex);r.onDeleteBlock(l.containerId,l.blockIndex);const d=o.get(a);d&&(Wh.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),o.delete(a));const h=`${l.containerId}-${l.blockIndex}`;e.add(h),this.outerHandler.onDeleteBlock(l.containerId,l.blockIndex,this.local)}else if(s.type==="deleteBlockData"){const l=s,a=`${l.containerId}-${l.blockIndex}`;if(e.has(a)){Wh.warn("delete block data after delete block, ignore it");continue}const d=r.getBlockId(l.containerId,l.blockIndex);let h=o.get(d);h||(h=new qb,o.set(d,h)),h.delete(l.key)}else g(Wh,!1,`invalid action type, ${s.type}`);this.actions.forEach(s=>{if(s.type==="deleteContainer"){const l=s;this.outerHandler.onDeleteContainer(l.containerId,this.local)}else if(s.type==="deleteComment"){const l=s;this.outerHandler.onDeleteComment(l.commentId,this.local)}}),this.actions.forEach(s=>{if(s.type==="createContainer"){const l=s;this.outerHandler.onCreateContainer(l.containerId,l.data,this.local)}}),this.actions.forEach(s=>{if(s.type==="insertBlock"){const l=s;this.outerHandler.onInsertBlock(l.containerId,l.blockIndex,l.data,this.local)}else if(s.type==="insertBlockData"){const l=s,a=r.getBlockId(l.containerId,l.blockIndex);let d=o.get(a);d||(d=new qb,o.set(a,d)),d.insert(l.key,l.value)}else if(s.type==="updateBlockText"){const l=s;this.outerHandler.onUpdateBlockText(l.containerId,l.blockIndex,l.richTextData,this.local)}else if(s.type==="createComment"){const l=s;this.outerHandler.onCreateComment(l.commentId,this.local)}else if(s.type==="updateComment"){const l=s;this.outerHandler.onUpdateComment(l.commentId,this.local)}}),Array.from(o.entries()).forEach(([s,l])=>{const{containerId:a,blockIndex:d}=r.getBlockIndexById(s);Wh.debug(`update block data: ${a}, ${d}, ${JSON.stringify(l.toDocBlockDelta())}`),this.outerHandler.onUpdateBlockData(a,d,l.toDocBlockDelta(),this.local)})}}const Re=S("op-parser");class Gb{}class pp{constructor(t){m(this,"key");this.key=t}}function XS(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 a=o[l];if(!Array.isArray(a)||a.length!==2||typeof a[0]!="string")return!1;const h=a[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=i.i;g(Re,s.id,"block id is required"),g(Re,s.type,"block type is required");for(let l=1;l<o.length;l++){const a=o[l],d=a[0],h=a[1];s[d]=h.i}return e.onInsertBlock(n,r,s),!0}function Cp(n,t,e,o){if(e==="upsert"&&XS(n,t,o))return;g(Re,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 a=r[1];if(g(Re,typeof a=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),g(Re,a.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),r.splice(0,2),e==="upsert"){const h=a.e;o.onUpdateBlockText(n,i,h)}g(Re,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){g(Re,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const a=l[0];g(Re,typeof a=="string",`invalid block op: key ${JSON.stringify(a)}`);const d=l[1];if(a==="text"){if(g(Re,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&e==="upsert"&&o.onInsertBlockData(n,i,a,d.i),d.r&&e==="remove"&&o.onDeleteBlockData(n,i,a),d.et==="rich-text"&&e==="upsert"){const p=d.e;o.onUpdateBlockText(n,i,p)}}else e==="remove"&&d.r&&s.push(new pp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i);r.shift()}else if(typeof l=="object"){const a=l;e==="remove"&&a.r&&s.push(new Gb),e==="upsert"&&a.i&&o.onInsertBlock(n,i,a.i),r.shift()}else{g(Re,typeof l=="string","data is not string"),g(Re,l!=="text","data !== 'text'"),g(Re,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const a=l,d=r[1];e==="remove"&&d.r&&s.push(new pp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Gb?o.onDeleteBlock(n,i):l instanceof pp?o.onDeleteBlockData(n,i,l.key):g(Re,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function tL(n,t,e){Re.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function eL(n,t,e){const o=n[1],r=n[2];g(Re,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),g(Re,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?Re.error(`unknown comment op, ${JSON.stringify(n)}`):r.i&&r.r?t==="upsert"&&e.onUpdateComment(o):r.i?t==="upsert"&&e.onCreateComment(o):r.r?t==="remove"&&e.onDeleteComment(o):Re.error(`unknown comment op, ${JSON.stringify(n)}`)}function Ap(n,t,e){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{Ap(s,t,e)});return}const r=o;if(g(Re,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){tL(n);return}if(r==="comments"){eL(n,t,e);return}const i=r;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{Cp(i,s,t,e)}):n.slice(1).forEach(s=>{Cp(i,s,t,e)});else if(typeof n[1]=="object"){const s=n[1];s.r&&t==="remove"&&e.onDeleteContainer(i),s.i&&t==="upsert"&&e.onCreateContainer(i,s.i)}else g(Re,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Cp(i,n.slice(1),t,e)}function Zb(n,t,e){const o=new KS(t,e);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=mt.default(n),l=s[0];Array.isArray(l)?s.forEach(a=>{Ap(a,i,o)}):Ap(s,i,o)}o.end()}const nL=S("sharedb-comments");function bp(n){const t=n.blocks;g(nL,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)}),mt.default(e)}function Qb(n){const{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}=n;return{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}}function vp(n,t){const e=HD(t),{comments:o,meta:r,blocks:i,...s}=e,l={...n,blocks:i,...s},a=mt.default(l);return delete a.children,a}const ae=S("sharedb-doc/doc-container"),Yb="ot-json1";_d.type.registerSubtype(jD.type),_d.type.name=Yb,_d.type.invert=null;class Ka extends fa{constructor(e,o,r=!0){super();m(this,"doc");m(this,"client");m(this,"localPresence");m(this,"remoteCaretHandler",new ND);m(this,"batching",0);m(this,"status","clean");m(this,"disableLogout");m(this,"destroyed",!1);m(this,"handleNothingPending",()=>{this.setStatus("clean")});m(this,"handleCreate",()=>{this.handleReload("doc created")});m(this,"handleDel",()=>{});m(this,"handleReload",e=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})});m(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()});m(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});m(this,"insertObject",async(e,o,r)=>{const i=[e,o,{i:r}];return this.submitOp(i)});m(this,"deleteObject",async(e,o)=>{const r=[e,o,{r:!0}];return this.submitOp(r)});m(this,"replaceObject",async(e,o,r)=>{const i=[e,o,{r:!0,i:r}];return this.submitOp(i)});m(this,"updateObject",async(e,o,r)=>{const i=this.data()[e][o],s=[e,o];return Object.entries(r).forEach(([l,a])=>{if(!ua.default(i[l],a))if(i[l]===void 0){if(a!=null){const d={i:a};s.push([l,d])}}else if(a==null){const d={r:!0};s.push([l,d])}else{const d={r:!0,i:a};s.push([l,d])}}),Object.entries(i).forEach(([l,a])=>{if((r[l]===void 0||r[l]===null)&&a!==void 0){const d={r:!0};s.push([l,d])}}),s.length<=2?Promise.resolve():this.submitOp(s)});m(this,"broadcastMessage",async e=>{const o={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});m(this,"data",()=>this.doc.data);m(this,"submitOp",async e=>new Promise((o,r)=>{if(this.destroyed){ae.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(ae.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),ae.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(ae.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));m(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,Yb,i=>{i?r(i):o()})}));m(this,"submitInsertChildContainer",async(e,o)=>{const r=[Ni(e),{i:o}];return this.submitOp(r)});m(this,"submitDeleteChildContainer",async e=>{const o=[Ni(e),{r:!0}];return this.submitOp(o)});m(this,"submitInsertBlock",async(e,o,r)=>{const i=[Ni(e),o,{i:r}];return this.submitOp(i)});m(this,"submitDeleteBlock",async(e,o)=>{const r=[Ni(e),o,{r:!0}];return this.submitOp(r)});m(this,"submitUpdateBlockData",async(e,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[Ni(e),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a)){const h={r:!0,i:d};i.push([a,h])}});const l=new Set(Object.keys(r.insert));return r.delete.forEach(a=>{if(l.has(a))return;const d={r:!0};i.push([a,d])}),Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a))return;const h={i:d};i.push([a,h])}),this.submitOp(i)});m(this,"submitUpdateRichText",async(e,o,r)=>{const i=[Ni(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});m(this,"handleOp",(e,o,r)=>{if(this.destroyed){ae.warn("handleOp: destroyed");return}Zb(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--,g(ae,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new ZS(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new Ka(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||QS())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw ae.error(o),ae.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(K()),e())})}})}subscribe(){return new Promise((e,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return ja(this.data())}getContainerBlocks(e){const o=this.data();g(ae,o,"no doc data");const r=o[Ni(e)];return g(ae,r,`no container data: ${e}`),mt.default(r)}getBlockData(e,o){const r=this.data();g(ae,r,"no doc data");const i=r[Ni(e)];g(ae,i,`no container data: ${e}`);const s=i[o];return g(ae,s,`no block data: ${o}`),mt.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);g(ae,i.text,"no block text");const s=mt.default(i.text);this.submitUpdateRichText(e,o,r);const l=ln.apply(s,r);return g(ae,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=mt.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=>Qb(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return bp(o)}localCreateComment(e,o){const r=vp(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=vp(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){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Xl(e),o,r)})}onInsertBlock(e,o,r,i){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Xl(e),o,r,i)})}onUpdateBlockData(e,o,r,i){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Xl(e),o,r,i)})}onUpdateBlockText(e,o,r,i){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Xl(e),o,r,i)})}onDeleteContainer(e,o){g(ae,this.callbacks.length>0,"no callbacks"),g(ae,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,Xl(e),o)})}onCreateContainer(e,o,r){g(ae,this.callbacks.length>0,"no callbacks"),g(ae,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,Xl(e),o,r)})}onDeleteComment(e,o){g(ae,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){g(ae,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){g(ae,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 ja(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return ja(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:ja(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:ja(r),versionData:i}}async updateVersionExtra(e,o,r){await this.client.updateVersionExtra(e,o,r)}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){Zb(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}S("remote-cursor");class Jb{constructor(t){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",He.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));m(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 Kb=S("remote-cursor-decorator");class yp{decorateText(t,e,o){const r=t.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=e[e.length-1];g(Kb,typeof s=="string","invalid path containerId"),g(Kb,typeof l=="number","invalid path blockIndex");const a=t.doc.getBlockData(s,l),d=rn(o);return r.getSimpleCursors(a.id).forEach((p,A)=>{A>d&&(A=d);const v=p.map(D=>({id:K(),type:"remote-cursor",name:D.user.displayName,time:D.time,rainbowIndex:D.user.rainbowIndex})),B=i.get(A);B?B.push(...v):i.set(A,v)}),{insertions:i}}}class Xb extends be.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Xt(Nr(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=ot(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 oL(n,t){n.addCustom("child-block-tracker",()=>new Xb(n)).addListener("change",t)}function rL(n,t){n.addCustom("child-block-tracker",()=>new Xb(n)).removeListener("change",t)}const snt="",iL={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",name:"\u6587\u672C\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},sL={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},lL={colorPalette:{colorDesc:"\u30D5\u30A9\u30F3\u30C8\u306E\u8272",name:"\u30C6\u30AD\u30B9\u30C8\u306E\u8272",backgroundDesc:"\u80CC\u666F\u8272",reset:"\u30C7\u30D5\u30A9\u30EB\u30C8\u306B\u623B\u3059"},search:{emptyTips:"\u691C\u7D22\u7D50\u679C\u304C\u3042\u308A\u307E\u305B\u3093"}};R.mergeLang({"zh-CN":iL,"en-US":sL,"js-JP":lL});const lnt="";S("button");function ji(n,t,e,o,r){const i=w("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&&W(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0)),i}function tv(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}const cnt="",nc=S("ui-command-bar-base"),cL={itemElementTag:"div",tippyArrow:!1},K2=class extends be.TypedEmitter{constructor(e,o,r){var i,s;super();m(this,"content");m(this,"items");m(this,"subBar",null);m(this,"parentItem",null);m(this,"closeable",null);m(this,"closeReason",null);m(this,"options");m(this,"id");m(this,"header",null);m(this,"footer",null);m(this,"handleDocumentKeydown",e=>{if(!!this.isVisible&&!e.isComposing&&!Ls(e.target)){if(this.subBar){this.subBar.handleDocumentKeydown(e);return}if(this.items.length!==0){if(e.key==="Escape"){this.close("cancelBar");return}if(e.key==="ArrowUp"){const o=this.getPrevItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),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("switchItem");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)}}}});m(this,"handleDocumentMouseDown",e=>{if(e.target instanceof Element&&!this.isInCommandBar(e.target)){const o=this.listeners("closing");for(let r=0;r<o.length;r++)if(o[r](this,e)===!1)return;this.close("clickBackground")}});m(this,"handleHidden",()=>{this.closeReason!=="fromHover"&&this.emit("close",this),this.close(null),EC(this.id)});m(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&W(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&BC(this.id)});m(this,"lastEnterPauseTime",0);m(this,"startPauseMouseEnter",()=>{this.lastEnterPauseTime=Date.now()});m(this,"handleItemMouseEnter",e=>{if(Date.now()-this.lastEnterPauseTime<100)return;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)});m(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)&&(et(o,"selected"),this.emit("selectionChange",this,""))});m(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("clickItem"))}});m(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=oo(r);if(!Kt(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:K(),this.options={...cL,...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(e){this.closeReason=e,this.subBar&&this.subBar.close(e),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}click(e,o){this.emit("click",this,e,o)}createPopperOptions(){var r,i;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"]}})),this.options.padding&&((i=e==null?void 0:e.modifiers)==null||i.push({name:"preventOverflow",options:{padding:this.options.padding}})),e}destroy(){var e;this.close(null),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,a;return s.id===((a=(l=this.subBar)==null?void 0:l.parentItem)==null?void 0:a.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],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)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],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)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&&et(o,"selected")}selectItem(e){const o=this.getSelectedItem();if(o){if(o.id===e)return;const i=o.id,s=this.getItemElementById(i);s&&et(s,"selected")}const r=this.getItemElementById(e);r?(W(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("switchItem");return}this.subBar.destroy(),this.subBar=null}if(!o.children)return;const r=this.getItemElementById(o.id);if(!r)return;const i=K2.createSubCommandBar(o,(l=this.closeable)!=null?l:this,e?{id:e}:{});this.subBar=i,this.subBar.on("click",(a,d,h)=>{this.emit("click",a,d,h)}),this.subBar.on("close",()=>{var a;(a=this.subBar)==null||a.destroy(),this.subBar=null,et(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),W(r,"active")}isInCommandBar(e){if(!e||!(e instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&Kt(o,e)||Kt(this.content,e)?!0:this.subBar?this.subBar.isInCommandBar(e):!1}createCommandItem(e){var i,s,l,a;let o=(i=this.options.itemElementTag)!=null?i:"div";e.element&&(o="div");const r=w(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"),(a=e.states)!=null&&a.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 g(nc,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 g(nc,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(e){const o=e.getAttribute("data-id");return g(nc,o,"no data-id attribute"),o}getItemElementById(e){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${e}"]`);return g(nc,o,`no exists command item, id=${e}`),o}getParentCommandItemElement(e){if(!e||!(e instanceof Element))return null;if(xt(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=w("div",["editor-command-bar-root"],null);if(this.options.header){const i=w("div",["editor-command-bar-header"],null);if(this.options.header instanceof Function){const s=this.options.header();s&&i.appendChild(s)}else i.appendChild(this.options.header);this.header=i,this.header&&o.appendChild(this.header)}const r=w("div",["editor-command-bar"],o);if(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.options.footer){const i=w("div",["menu-item","editor-command-bar","footer"],null);if(this.options.footer instanceof Function){const s=this.options.footer();s&&i.appendChild(s)}else i.appendChild(this.options.footer);this.footer=i,this.footer&&o.appendChild(this.footer)}return(this.options.header||this.options.footer)&&W(o,"scrollable-bar"),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;g(nc,e.children&&e.children.length>0,"no item children");const i=(l=e.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return g(nc,s,`no creator for command type: ${i}`),s(e,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let Ui=K2;m(Ui,"commandBarCreators",new Map),S("ui-command-bar");class qh extends Ui{constructor(){super(...arguments);m(this,"tippyInstance",null)}manualShow(e,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=UB.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(e){var o;super.close(e),this.isVisible&&((o=this.tippyInstance)==null||o.hide())}destroy(){var e;(e=this.tippyInstance)==null||e.destroy(),this.tippyInstance=null,super.destroy()}getCommandBarRoot(){return this.content.closest("[data-tippy-root]")}get isVisible(){var e,o;return(o=(e=this.tippyInstance)==null?void 0:e.state.isVisible)!=null?o:!1}get popper(){return this.content.closest("[data-tippy-root]")}}const ev=S("ui-base");class Xa extends qh{constructor(t,e){var i;const r=[{id:(i=e==null?void 0:e.id)!=null?i:`popup-${K()}`,name:"",element:t}];super(r,void 0,{disablePageScroll:!0})}initCommandBarElement(t){W(t,"popper")}initItemElement(t,e){}get popupContent(){const t=this.items[0];g(ev,t,"no dialog item");const e=typeof t.element=="function"?t.element(t):t.element;return g(ev,e,"no item element"),e}}const zi=S("filterable-list");function nv(n){var e,o;const t=w("div",["list-item"],null);return t.setAttribute("data-id",n.id),t.appendChild(w("div",["list-item-text"],null,n.name)),(e=n.states)!=null&&e.includes("selected")&&W(t,"selected"),(o=n.states)!=null&&o.includes("disabled")&&W(t,"disabled"),t}function ov(n){const t=w("div",["list-root"],null);return n.forEach(e=>{t.appendChild(nv(e))}),n.length||t.appendChild(nv({id:"placeholder",states:["disabled"],name:R.t("search.emptyTips")})),t}function rv(n,t){let e=n;return t&&(e=n.map(o=>({...o,states:o.id===t?["selected"]:void 0}))),e}function aL(n,t){const e=w("div",["filterable-list"],null),o=w("div",["filter"],e),r=w("div",["filter-container"],o),i=w("input",["filter-input"],r);t&&t.placeholder&&(i.placeholder=t.placeholder);const s=w("div",["list"],e),l=ov(rv(n,t==null?void 0:t.initialSelectedId));return s.appendChild(l),e}function iv(n,t,e){const o=n.querySelector(".list");g(zi,o,"no list root");const r=ov(rv(t,e)),i=o.querySelector(".list-root");if(g(zi,i,"no exists menu"),Ca(i,r),e){const s=o.querySelector(".list-item.selected");s&&(g(zi,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class uL{constructor(t,e){m(this,"root");m(this,"visibleItems");m(this,"selectedId");m(this,"filter","");m(this,"onSelected",null);m(this,"handleKeydown",t=>{this.processKeyDown(t)});m(this,"handleInputChanged",()=>{const t=this.root.querySelector(".filter-input");g(zi,t,"no input");const e=t.value.toLocaleLowerCase();this.setFilter(e)});m(this,"handleClick",t=>{this.processClick(t)});var o;this.items=t,this.options=e,this.root=aL(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");g(zi,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");g(zi,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,iv(this.root,this.visibleItems,t)}focus(){const t=this.root.querySelector(".filter-input");g(zi,t,"no input"),t.focus()}reset(){this.setFilter("");const t=this.root.querySelector(".filter-input");g(zi,t,"no input"),t.value=""}setFilter(t){this.filter!==t&&(this.filter=t,this.visibleItems=this.items.filter(e=>e.name.toLocaleLowerCase().includes(t)),iv(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(a=>a.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 dL extends uL{constructor(e,o,r){super(e,r);m(this,"popup");m(this,"onShow",null);m(this,"onHide",null);m(this,"custom",null);m(this,"handleShow",()=>{this.onShow&&this.onShow(this)});m(this,"handleHide",()=>{this.onHide&&this.onHide(this)});m(this,"handleShown",()=>{this.focus()});this.popup=new Xa(this.root)}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(e){this.reset(),this.popup.manualShow(e,{theme:"dropdown-list"}),this.focus()}processKeyDown(e){super.processKeyDown(e),(e.key==="Esc"||e.key==="Enter")&&this.popup.close("cancelBar")}processClick(e){super.processClick(e);const o=e.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.popup.close("clickItem")}}const ant="",unt="";function hL(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 sv=`<?xml version="1.0" ?>
27
+ `)}const eT=S("get-text-position");function Gl(n,t){const e=t!=null?t:n.selection.range.start;e instanceof je||g(eT,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=bt(r),s=nt(r),l=at(s),{offset:a}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:a}}const Zl=S("insert-text");function Dg(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(g(Zl,r,"no block data"),g(Zl,r.text,"no block text"),rn(r.text)===0)return g(Zl,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=ze(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function nT(n,t,e){const o=nt(t),r=at(o),i=bt(t);return Dg(n,r,i,e)}function R6(n,t,e,o,r){const i=nt(t),s=at(i),l=bt(t),a=nT(n,t,e),d=ch(e,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),mn(n,t)}function O6(n,t,e,o){const r=nt(t),i=at(r),s=bt(t),l=ch(e," ",o);return n.doc.localUpdateBlockText(i,s,l),mn(n,t)}function oT(n,t){let e=0;if(t===0)return!1;for(let o=0;o<n.length;o++){const r=n[o];g(Zl,typeof r.insert=="string","invalid text op, no insert");const i=e+ah(r);if(i===t)return!1;if(i>t)return!0;e=i}return!1}function Sg(n,t,e,o,r){const i=n.doc.getBlockData(e,o);g(Zl,i,"no block data"),g(Zl,i.text,"no block text");const s=Dg(n,e,o,r);s&&Object.keys(s).includes("link")&&(oT(i.text,r)||delete s.link);const l=ch(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),mn(n,n.getBlockById(i.id))}function Lg(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=Gl(n);Sg(n,t,e,o,r)}const vh=S("update-composition-text");function _6(n){const t=n.selection.range.start;t instanceof je||g(vh,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);g(vh,tt(n,o),"not a text kind block");const r=nt(o),i=at(r),s=bt(o),l=n.doc.getBlockData(i,s);g(vh,l,"no block data in doc"),g(vh,l.text,"no text data in text block");const a=Rt(o);rh(n,Di(o),e,a,l.text)}function F6(n){_x(n)}function Ql(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const Ra=S("delete-block-text");function Mg(n,t,e,o,r){if(!n.isBlockWritable(t))return Ra.error("block is not writable"),0;g(Ra,tt(n,t),"block is not a text kind block");const i=nt(t),s=at(i),l=bt(t),a=n.doc.getBlockData(s,l);g(Ra,a,"no block data in doc"),g(Ra,a.text,"no text data in text block");let d=e;sn(t,e)||(d=Ri(t,d));let h=e+o;g(Ra,h<=ut(n,t),`invalid offset and count: ${e}, ${o}`),sn(t,h)||(h=Fs(t,h));const p=h-d,A=W4(d,p);return n.doc.localUpdateBlockText(s,l,A,r),p}const Rg=S("break-text-block");function P6(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function Yl(n,t,e,o){g(Rg,tt(n,t),`block is not a text kind block: ${Dt(t)}`),g(Rg,e>=0&&e<=ut(n,t),`invalid offset: ${e}`);const r=nt(t),i=at(r),s=bt(t),l=o!=null&&o.copyBlockAttributes?P6(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===ut(n,t))){const v=e===0?s:s+1,B={...sr(""),...l,...o==null?void 0:o.newBlockData},D=ye(n,t.id,0),T=Ql(n,i,v,B,D);return{block:t,newBlock:T}}g(Rg,sn(t,e),"not a valid offset");const a=mn(n,t),{right:d}=xn(a,e),h=rn(d);h>0&&Mg(n,t,e,h);const p={...sr(d),...l,...o==null?void 0:o.newBlockData},A=Ql(n,i,s+1,p,ye(n,p.id,0));return{block:t,newBlock:A}}const rT=S("prepare-insert-new-block");function iT(n,t,e){if(t&&e!==void 0&&e!==null){const d=n.getContainerById(t),h=ve(d);return g(rT,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=at(nt(r)),e=bt(r),!tt(n,r))return{containerId:t,blockIndex:e+1};const s=o.offset;if(s===0||s===ut(n,r))return{containerId:t,blockIndex:s===0?e:e+1};const a=Yl(n,r,s).newBlock;return{containerId:t,blockIndex:bt(a)}}const sT=S("auto-insert-block");function N6(n,t,e,o,r,i){const s=iT(n,e,o);g(sT,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},a={anchor:l,focus:l};return Ql(n,s.containerId,s.blockIndex,t,r!=null?r:a,i)}const lT=S("delete-block");function yh(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{yh(n,i,e)})}))}function kh(n,t,e){const o=nt(t),r=at(o),i=bt(t),s=n.doc.getBlockData(r,i);return g(lT,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,Ue(n,{anchor:e.start,focus:e.end})),s}function Og(n,t,e){return n.undoManager.runInGroup(()=>{const o=nt(t);Eo(o)===1&&n.insertTextBlock("",at(o),0);let r=e?Si(n,e):null;if(!r){const l=n.selection.range;D6(t,l)?r=S6(n,t):r=l}const i=kh(n,t,r),s=[];return yh(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function cT(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{yh(n,r,e)}),n.doc.localDeleteChildContainers(e)}function $6(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{yh(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const _g=S("merge-text-block");function H6(n,t,e){g(_g,tt(n,t),"only text block can be merged"),g(_g,tt(n,e),"only text block can be merged");const o=_i(n,t),r=_i(n,e),i=o.text,s=r.text;g(_g,i&&s,"block data has no text");const l=nt(t),a=at(l),d=bt(t),h=ut(n,t),p=Sg(n,s,a,d,h),A=ye(n,t,rn(i));return Og(n,e,A),p}const lr=S("clear-selected-contents");function wh(n,t){g(lr,tt(n,t.block),"not a text kind block");const{start:e,end:o}=t;g(lr,e.isSimple(),"not a simple block position"),g(lr,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;g(lr,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function j6(n,t,e){const o=at(t),r=ve(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 aT(n,t){const{block:e,start:o,end:r}=t;if(tt(n,e)){wh(n,t);return}if(Le(e)||o.isSimple()){g(lr,r.isSimple(),"invalid range");const s=nt(e),l=bt(e),a=n.insertTextBlock("",at(s),l);n.selection.selectBlock(a,0),n.deleteBlock(e);return}g(lr,Lt(n,e),"invalid block kind"),g(lr,!o.isSimple()&&!r.isSimple(),"invalid range"),Os(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{j6(n,s,{focus:l===0})})}function uT(n){if(!n.isWritable())return;const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(g(lr,e.length>0,"no selected block"),e.length===1){aT(n,e[0]);return}const o=e[0],r=o.block,i=nt(r);g(lr,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(tt(n,r)){wh(n,o);const h=ye(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(A=>n.deleteBlock(A.block)),tt(n,l)){wh(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(tt(n,l)){wh(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===Eo(i)){j6(n,i,{focus:!0});return}const a=ce(r),d=Zt(l);g(lr,a||d,"no prev or next block"),e.forEach(h=>n.deleteBlock(h.block))}function Fg(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),uT(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const dT=S("core");function U6(n,t,e){const o=nt(t),r=at(o),i=bt(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),mn(n,t)}function z6(n,t,e){if(!n.isBlockWritable(t)){dT.error("block is not writable");return}const o=n.getBlockText(t),r=ln.diff(o,e);U6(n,t,r)}function Bh(n,t,e){const o=mn(n,t),r=typeof e=="string"?Oi(e):e,i=ln.diff(o,r);return U6(n,t,i)}const Oa=S("update-block-data");function Eh(n,t,e,o){const r=nt(t),i=at(r),s=bt(t),l=n.doc.getBlockData(i,s),a={insert:{},delete:[]},d=new Set(Object.keys(l)),h=new Set(Object.keys(e));return d.forEach(A=>{if(!h.has(A)){if(A==="id"||A==="type"||A==="text")return;Oa.debug(`delete key: ${A}`),a.delete.push(A)}}),Object.entries(e).forEach(([A,v])=>{g(Oa,A!=="id"&&A!=="type",`invalid block data delta, ${A}`);const B=l[A];if(v==null){B!=null&&(Oa.debug(`delete key: ${A}`),a.delete.push(A));return}B!==v&&(ua.default(B,v)||A==="text"&&ln.diff(B,v).length===0||(d.has(A)?(Oa.debug(`replace key: ${A}`),a.delete.push(A)):Oa.debug(`insert key: ${A}`),a.insert[A]=v))}),n.doc.localUpdateBlockData(i,s,a,o),_i(n,t)}function V6(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function Pg(n,t,e){if(!Lt(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=jn(n,t).getChildContainers(n,t)[0],i=Se(r);Pg(n,i,e)}function $s(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 _a=S("clone-block");function Fi(n,t,e,o){const r=n.getBlockClass(e.type);if(r.blockToDoc)return r.blockToDoc(t,e,(h,p)=>(g(_a,e!==p,"invalid child block"),Fi(n,h,e,o)));let i={};const s=new Map,l=mt.default(e);l.children&&(l.children=l.children.map(h=>{const p=K(),A=t.blocks[h];g(_a,Array.isArray(A),"invalid child blocks");const v=A.map(_=>Fi(n,t,_,o)),B=$s(v),{root:D,...T}=B.blocks;return i={...i,...T},i[p]=B.blocks.root,s.set(h,p),p}));const a=Array.from(s.entries()),d=h=>{for(const p of a){const[A,v]=p;{const B=`${A}/`;if(h.startsWith(B)){const D=h.substring(B.length),T=`${v}/${D}`;return _a.debug(`replace key: ${h} -> ${T}`),T}}{const B=`${A}_`;if(h.startsWith(B)){const D=h.substring(B.length),T=`${v}_${D}`;return _a.debug(`replace key: ${h} -> ${T}`),T}}}return h};return Array.from(Object.entries(l)).forEach(([h,p])=>{const A=d(h);A!==h&&delete l.key,l[A]=p}),l.id=K(),o&&(o.blockIdMap.set(e.id,l.id),s.forEach((h,p)=>o.containerIdMap.set(p,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function Ng(n,t,e,o){const r=t.blocks[e];g(_a,Array.isArray(r),"invalid child blocks");const i=r.map(l=>Fi(n,t,l,o));return $s(i)}function $g(n,t,e){const o=t.blocks.root.map(r=>Fi(n.editorBlocks,t,r,e));return mt.default($s(o))}const W6=S("insert-doc");function q6(n,t,e,o,r){if(Lt(n,t)){W6.warn("failed to insert doc into a complex block");return}const i=$g(n,o,r),s=nt(t),l=bt(t),a=at(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var M,H,z;Object.entries(i.blocks).forEach(([q,rt])=>{q!=="root"&&n.doc.localInsertChildContainer(q,rt)});const d=i.blocks.root;if(Le(t)){n.deleteBlock(t);let q;d.reverse().forEach(rt=>{const ft=n.insertBlock(a,l,rt);q||(q=ft)}),q&&n.selection.selectBlock(q,ut(n,q));return}if(g(W6,tt(n,t),"not a text block"),he(n,t)){const q=a==="root"&&n.getBlockByIndex(a,0)===t,rt=bt(t);let ft;d.forEach((Bt,jt)=>{const Ut=n.insertBlock(a,rt+jt,Bt);jt===d.length-1&&(ft=Ut)}),ft&&n.selection.selectBlock(ft,ut(n,ft)),q&&n.deleteBlock(t);return}if(d.length===1){const q=d[0];if(ya(n,q.type)){n.insertTextToBlock(t,e,(M=q.text)!=null?M:[]);return}n.breakTextBlock(t,e),n.insertBlock(a,l+1,q);return}const h=e===ut(n,t),p=e===0,A=d[0],v=d[d.length-1];let B;!h&&!p?B=n.breakTextBlock(t,e,{forceInsertAfter:!0}):B=t;const D=p?l:l+1;h?(B=n.insertBlock(a,l+1,v),n.selection.selectBlock(B,ut(n,B))):(n.selection.selectBlock(B,0),ya(n,v.type)?n.insertTextToBlock(B,0,(H=v.text)!=null?H:[]):n.insertBlock(a,D,v));const T=n.selection.range;let _=D;ya(n,A.type)?p?(n.insertBlock(a,D,A),_+=1):n.insertTextToBlock(t,e,(z=A.text)!=null?z:[]):(n.insertBlock(a,D,A),_+=1),d.slice(1,d.length-1).reverse().forEach(q=>{n.insertBlock(a,_,q)}),n.selection.setRange(T)}),n.doc.endBatchUpdate()}function Hg(n,t,e,o,r){const i=$g(n,o,r),s=at(t),l=[];return n.undoManager.runInGroup(()=>{Object.entries(i.blocks).forEach(([d,h])=>{d!=="root"&&n.doc.localInsertChildContainer(d,h)}),i.blocks.root.reverse().forEach(d=>{const h=n.insertBlock(s,e,d);l.push(h)})}),l}function G6(n,t,e){const o=Eo(t);Hg(n,t,o,e);for(let r=0;r<o;r++){const i=Se(t);n.deleteBlock(i)}}const Fa=S("add-text-attribute");function hT(n,t,e,o){const{start:r,end:i}=e;g(Fa,r.blockId===i.blockId&&r.blockId===it(t),"invalid range"),g(Fa,o,"invalid attribute name");const s=n.getBlockText(t),l=ql(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function Z6(n,t,e,o,r){const{start:i,end:s}=e;g(Fa,i.blockId===s.blockId&&i.blockId===it(t),"invalid range"),g(Fa,o,"invalid attribute name");const l=n.getBlockText(t),a=Ia(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Jl(n,t,e,o,r){const{start:i,end:s}=e;g(Fa,i.blockId===s.blockId&&i.blockId===it(t),"invalid range");const l=n.getBlockText(t),a=e6(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Q6(n,t,e,o){const r=Lo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!tt(n,s))return;if(he(n,s)){o(n,it(s),t,e);return}const d=Ue(n,{anchor:l,focus:a});t==="color"||t==="backgroundColor"?Jl(n,s,d,t,e):(Jl(n,s,d,"color",null),Jl(n,s,d,"backgroundColor",null))})})}function Y6(n,t,e){const o=Lo(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!tt(n,i))return;if(he(n,i)){(t==="clearColor"||t==="clearAll")&&e(n,it(i),"color",null),(t==="clearBackground"||t==="clearAll")&&e(n,it(i),"backgroundColor",null);return}const a=Ue(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&Jl(n,i,a,"color",null),(t==="clearBackground"||t==="clearAll")&&Jl(n,i,a,"backgroundColor",null)})})}function jg(n,t){const e=Lo(n,{simpleBlockOnly:!0}).filter(s=>tt(n,s.block));if(e.length===0)return[null,null];const o=s=>{if(ut(n,s.block)===0)return t(n,it(s.block));const l=s.start,a=s.end,d=n.getBlockText(s.block);return r6(l.offset,a.offset-l.offset,d)};let[r,i]=o(e[0]);return r===null&&i===null?[r,i]:(e.forEach(s=>{const[l,a]=o(s);l===null||r===null?r=null:r=l===r?r:null,a===null||i===null?i=null:i=a===i?i:null}),[r,i])}const Vn=S("adjust-selection-pos");function J6(n){const t=[];for(;n;){const e=nt(n);if(t.unshift(e),Xt(e))return t;const o=ot(e);g(Vn,o,"child container has not parent container"),n=o}g(Vn,!1,"should not come here: getParentContainers")}function K6(n,t){for(;t;){const e=nt(t);if(e===n)return t;const o=ot(e);g(Vn,o,"could not find parent block for a child container"),t=o}g(Vn,!1,"no parent block in specified container")}function fT(n,t){const e=J6(n),o=J6(t);g(Vn,e.length>0&&o.length>0,"block has not parent container"),g(Vn,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=K6(r,n),s=K6(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function X6(n,t){let e=ot(t);for(g(Vn,e,"element is not in a block");e;){const o=nt(e);g(Vn,Do(o),"not a child container");const r=ot(o);if(g(Vn,r,"child container has not parent block"),r===n)return o;e=r}g(Vn,!1,"failed to find parent container in complex block")}function xh(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof je&&e instanceof je?{anchor:t,focus:e}:t instanceof So&&e instanceof So?nh(n,o,t,e):null;const i=nt(o),s=nt(r);if(i===s)return t instanceof So&&(t=st(o,0,"home")),e instanceof So&&(e=st(r,ut(n,r),"end")),g(Vn,t instanceof je,"not valid position type"),g(Vn,e instanceof je,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof je&&e instanceof So){const B=n.getContainerById(e.childContainerId);if(B===i)return{anchor:e,focus:e};const D=ot(i);if(D&&D===ot(B)){const T=fe(D,at(i)),_=fe(D,at(B));return nh(n,D,T,_)}}return null}const l=Hd(o,r)>0,{newBlock1:a,newBlock2:d}=fT(o,r);if(a===d){const B=a,D=X6(B,o),T=X6(B,r);return t=fe(a,at(D)),e=fe(a,at(T)),Vn.debug(`select in complex block: ${D.id}, ${T.id}`),nh(n,B,t,e)}let h=l?ut(n,a):0;a===o&&t instanceof je&&(h=t.offset);let A=l?0:ut(n,d);return d===r&&e instanceof je&&(A=e.offset),t=st(a,h,l?"end":"home"),e=st(d,A,l?"home":"end"),{anchor:t,focus:e}}const mT=S("move-complex-block-position");function gT(n,t,e){const o=n.getBlockById(t.blockId);g(mT,Lt(n,o),"is not a complex block");const r=jn(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?fe(o,at(s)):null}const Pa=S("move-simple-block-position");function tA(n,t){const e=En(n,t,{visibleOnly:!0});g(Pa,e.length>0,"complex block has not any child container");const o=e[0];return Se(o)}function eA(n,t){const e=En(n,t,{visibleOnly:!0});g(Pa,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Ge(o)}function nA(n,t,e){const o=e?tA(n,t):eA(n,t);return Lt(n,o)?nA(n,o,e):o}function pT(n,t){const e=n.getBlockById(t.blockId);return Lt(n,e)&&t.offset===0?tA(n,e):Ss(e)}function CT(n,t){const e=n.getBlockById(t.blockId);return Lt(n,e)&&t.offset===1?eA(n,e):Ds(e)}function Ug(n){return n==="ArrowLeft"||n==="ArrowUp"}function zg(n,t,e){const o=nt(t);if(Xt(o))return null;const r=ot(o);g(Pa,r,"child container has not parent block"),g(Pa,Lt(n,r),"is not a complex block");const i=jn(n,r).getNextContainer(n,r,o,e);return i?Ug(e)?Ge(i):Se(i):zg(n,r,e)}function AT(n,t,e){const o=nt(t);if(Xt(o))return null;const r=ot(o);if(g(Pa,r,"child container has not parent block"),Ug(e)){const l=ce(r);if(l)return l}else{const l=Zt(r);if(l)return l}const i=zg(n,r,e);if(i)return i;let s=r;for(;!Xt(nt(s));)s=ot(nt(s));return Ug(e)?ce(s):Zt(s)}function bT(n,t,e){return!Lt(n,t)||jn(n,t).enableKeyboardSelect?t:nA(n,t,e==="ArrowDown"||e==="ArrowRight")}function vT(n,t,e){const o=n.getBlockById(t.blockId),i=Qt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?pT(n,t):CT(n,t);if(s||(s=zg(n,o,e),s||(s=AT(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Xt(nt(o)))return null;const l=n.insertTextBlock("",at(n.rootContainer),Eo(n.rootContainer));return st(l,0,"home")}return null}if(s=bT(n,s,e),tt(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return Gx(n,s,o,t,l);if(e==="ArrowUp")return qx(n,s,o,t,l)}return e==="ArrowLeft"||e==="ArrowUp"?st(s,ut(n,s),"end"):e==="ArrowRight"||e==="ArrowDown"?st(s,0,"home"):null}function yT(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(tt(n,r))return o;const i=Zt(r);if(i)return st(i,0,"home");if(!Xt(nt(r))||n.readonly)return o;const s=n.insertTextBlock("",at(n.rootContainer),Eo(n.rootContainer));return st(s,0,"home")}function kT(n,t,e){const o=n.selection.range;let r;if(o instanceof Ze)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=yT(n,t,o):r=vT(n,o.getFocusedPos(),t);else if(r=gT(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=Ge(s);r=st(l,0,"home")}else{const l=Se(s);r=st(l,ut(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:xh(n,o.anchor,r):null}function Pi(n,t,e){const o=kT(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 oA(n){return Pi(n,"ArrowLeft","move"),!0}function rA(n){return Pi(n,"ArrowRight","move"),!0}function iA(n){return Pi(n,"ArrowUp","move"),!0}function sA(n){if(Pi(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=nt(t);if(Xt(e)||Ge(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",at(o),Eo(o)),!0}function lA(n){return Pi(n,"ArrowDown","select"),!0}function cA(n){return Pi(n,"ArrowLeft","select"),!0}function aA(n){return Pi(n,"ArrowRight","select"),!0}function uA(n){return Pi(n,"ArrowUp","select"),!0}const dA=S("word-offset");function Vg(n,t){const e=n.selection.range.focus;g(dA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(he(n,o))return st(o,0,"home");if(e.offset===0||!tt(n,o)){const s=ce(o);if(!s)return null;const l=st(s,ut(n,s),"end");if(t==="select"&&tt(n,s)){const a=yg(n,s,l.offset);return st(s,a,"normal")}return l}const r=yg(n,o,e.offset);return st(o,r,"normal")}function Wg(n,t){const e=n.selection.range.focus;g(dA,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(he(n,o))return st(o,0,"end");if(e.offset===ut(n,o)||!tt(n,o)){const s=Zt(o);if(!s)return null;const l=st(s,0,"home");if(t==="select"&&tt(n,s)){const a=kg(n,s,l.offset);return st(s,a,"end")}return l}const r=kg(n,o,e.offset);return st(o,r,"normal")}function hA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vg(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function fA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Wg(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function mA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Vg(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function gA(n){if(!n.selection.range.focus.isSimple())return!1;const e=Wg(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}S("find-block");function qg(n,t){if(!Lt(n,t))return t;const o=jn(n,t).getChildContainers(n,t)[0],i=ve(o)[0];return qg(n,i)}function Gg(n,t){if(!Lt(n,t))return t;const e=jn(n,t).getChildContainers(n,t),o=e[e.length-1],r=ve(o),i=r[r.length-1];return Gg(n,i)}function pA(n){const t=Gg(n,Ge(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(e),!0}function CA(n){const t=qg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(e),!0}function AA(n){const t=qg(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function Zg(n){const t=Gg(n,Ge(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}const bA=S("line-offset");function vA(n){const t=n.selection.range.focus;g(bA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!tt(n,e))return st(e,0,"home");let r=H4(e,t).start;const{next:i}=Xd(e,r);return i&&io(i)&&va(i)==="br"&&(r+=1),st(e,r,"home")}function yA(n){const t=n.selection.range.focus;g(bA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===ut(n,e)||!tt(n,e))return st(e,ut(n,e),"end");const o=H4(e,t);return st(e,o.end,"end")}function kA(n){if(!n.selection.range.focus.isSimple())return!1;const e=vA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function wA(n){if(!n.selection.range.focus.isSimple())return!1;const e=yA(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function BA(n){if(!n.selection.range.focus.isSimple())return!1;const e=vA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function EA(n){if(!n.selection.range.focus.isSimple())return!1;const e=yA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const xA=S("find-block-position");function wT(n,t,e,o){g(xA,Lt(n,t),"is not a complex block");const r=jn(n,t).getChildContainers(n,t);g(xA,r.length>0,"complex block has not any child container");const i=To(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,a=D4(n,t,s,l);return Qg(n,a,e,o)}function Qg(n,t,e,o){if(Lt(n,t))return wT(n,t,e,o);const r=it(t);let i=Number.MAX_SAFE_INTEGER;const s=To(n,e,o),l=s.left+s.width/2,a=s.top+s.height/2;let d=st(r,0,"home");const h=ut(n,t);for(let p=0;p<=h;p++){const A=st(r,p,"normal"),v=To(n,t,A),B=er(v,l,a);B<i&&(i=B,d=A)}return d}const IA=S("page-offset");function BT(n,t){const e=x6(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<GI(n))return n.getFirstBlock();const i=ce(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=ce(s)}return n.getFirstBlock()}function ET(n,t){const e=x6(n)*.9,o=t.getBoundingClientRect(),r=ZI(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=Zt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=Zt(l)}return n.getLastBlock()}function TA(n){const t=n.selection.range.focus;g(IA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=BT(n,e);let r;return o===n.getFirstBlock()?r=st(o,0,"home"):r=Qg(n,o,e,t),r}function DA(n){const t=n.selection.range.focus;g(IA,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=ET(n,e);let r;return o===n.getLastBlock()?r=st(o,ut(n,o),"end"):r=Qg(n,o,e,t),r}function SA(n){if(!n.selection.range.focus.isSimple())return!1;const e=TA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function LA(n){if(!n.selection.range.focus.isSimple())return!1;const e=DA(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function MA(n){if(!n.selection.range.focus.isSimple())return!1;const e=TA(n);if(!e)return!1;const o=xh(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 RA(n){if(!n.selection.range.focus.isSimple())return!1;const e=DA(n);if(!e)return!1;const o=xh(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 Na=S("select-all");function OA(n,t){const e=Se(n),o=Ge(n);return t.start.offset===0&&t.start.blockId===it(e)&&t.end.offset===ut(t.getEditor(),o)&&t.end.blockId===it(o)}function xT(n,t){const e=t.getEditor(),o=jn(e,n).getChildContainers(e,n),r=o[0],i=o[o.length-1],s=it(n);return t.start.blockId===s&&t.start.childContainerId===at(r)&&t.end.blockId===s&&t.end.childContainerId===at(i)}function IT(n,t){g(Na,t,"no parent block"),g(Na,Lt(n,t),"not a complex block");const e=jn(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(Ue(n,{anchor:fe(t,at(o)),focus:fe(t,at(r))}))}function _A(n,t){const e=nt(t);Yg(n,e)}function FA(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&tt(n,t)){const r=e.start,i=e.end,s=ut(n,t);if(r.offset>0||i.offset<s)return n.selection.selectBlock(t,0,s),!1}return W(n.rootContainer,"select-all"),_A(n,Se(n.rootContainer)),!1}return g(Na,!e.isSimple(),"invalid range type"),xT(t,e)?(_A(n,t),!1):(g(Na,t,"no parent block"),g(Na,Lt(n,t),"not a complex block"),IT(n,t),!0)}function Yg(n,t){const e=ve(t),o=e[0],r=e[e.length-1],i=st(o,0,"home"),s=st(r,ut(n,r),"end");n.selection.setSelection(i,s,{noScroll:!0})}function PA(n){Zg(n),n.focus()}const Jg=S("selected-block-to-doc");function NA(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{NA(n,i,e)}),e.blocks[o]=mt.default(r)})}function Ih(n,t){const e=Qt(n,t.block);if(e.selectionToDoc)return e.selectionToDoc(n,t);const o=mt.default(_i(n,t.block));if(tt(n,t.block)){const i=t.start,s=t.end;if(g(Jg,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=ze(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(Le(t.block))return{blocks:{root:[o]},meta:{},comments:{}};g(Jg,Lt(n,t.block),"not complex block"),g(Jg,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return NA(n,o,r),r}function Kg(n,t){const e=st(t,0,"normal"),o=st(t,ut(n,t),"end");return Ih(n,{block:t,start:e,end:o})}const TT=S("block-to-doc");function DT(n,t){g(TT,t.length>0,"invalid params, no blocks");const e=t.map(o=>Kg(n,o));return $s(e)}function Th(n){const e=n.selection.range.getSelectedBlocks().map(o=>Ih(n,o));return $s(e)}function $A(n,t){const e=n.getContainerById(t),i=ve(e).map(s=>({start:st(s,0,"home"),end:st(s,ut(n,s),"end"),block:s})).map(s=>Ih(n,s));return $s(i)}const Dh=S("editor-selection");class ST{constructor(t){m(this,"editor");m(this,"caret");m(this,"_range");m(this,"lastCaretRect");m(this,"handleBlockDelete",(t,e,o,r)=>{if(o||r.child)return;const i=this.range;if(D6(e,i)){Dh.debug("adjust selection because remote deleted current block");const s=S6(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=it(e);this.caret=new VI(t);const r=st(o,0,"normal");this._range=Ue(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=st(t,e,"normal");let i;o&&(i=st(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=Ue(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),xt(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!KI(this.editor,r))&&et(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(),WI(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(!$r(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=To(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){JI(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=ut(this.editor,e)||g(Dh,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||g(Dh,!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&&xt(e,"focused")&&(et(e,"focused"),r=!0),this.removeAllBlockFocusedClass(),o&&this.setBlockFocused(o)&&(r=!0),r&&this.editor.emit("focusBlockChanged",this.editor,o!=null?o:null,e!=null?e:null)}verify(){this.verifyPos(this._range.start),this.verifyPos(this._range.end)}to(t){const e=Th(this.editor);return t==="text"?La(this.editor,e):t==="markdown"?Ma(this.editor,e):M6(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{et(t,"focused"),et(t,"child-focused")})}setBlockFocused(t){if(xt(t,"focused"))return!1;W(t,"focused");let e=nt(t);for(;Do(e);){const o=ot(e);g(Dh,o,"parent block not found"),W(o,"child-focused"),e=nt(o)}return!0}}function LT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);!e||n.selection.selectBlock(e,0,ut(n,e))}function MT(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!tt(n,e))return;let o=Vg(n,"select"),r=Wg(n,"select");if(!o||!r)return;const i=t.blockId;o.blockId!==i&&(o=st(e,0,"home")),r.blockId!==i&&(r=st(e,ut(n,e),"end")),n.selection.setSelection(o,r)}class RT{constructor(t){m(this,"editor");m(this,"startPos",null);m(this,"lastCaretRect");m(this,"mouseDownEvent",null);m(this,"autoScroll",null);m(this,"handleMouseDown",(t,e)=>{var r;this.mouseDownEvent=t;const o=M4(this.editor,t.x,t.y);if(o){if(o instanceof or)return;if(!this.autoScroll&&e.autoScroll){const s=o.getSelectedBlocks(),l=oo(s[0].block);this.autoScroll=new Gd({scrollElement:l,edge:{top:50,bottom:50}})}const i=this.editor.selection.range;if(t.shiftKey&&i.isSimple()){const s=i.anchor;this.editor.selection.setSelection(s,o.focus),this.startPos=o.start}else this.editor.selection.setSelection(o.anchor,o.focus),this.startPos=o.start;this.editor.selection.updateLastCaretRect(),e.autoScroll&&((r=this.autoScroll)==null||r.active())}});m(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=oh(this.editor,t.x,t.y);if(!e)return;const o=xh(this.editor,this.startPos,e.end);if(!o)return;const{anchor:r,focus:i}=o;this.editor.selection.setSelection(r,i)});m(this,"handleMouseUp",t=>{var e;(e=this.autoScroll)==null||e.inactive(),this.startPos=null});this.editor=t,this.startPos=null,this.lastCaretRect=new DOMRect}isSelecting(){return this.startPos!==null}stopSelection(){this.startPos=null}handleDblClick(t){MT(this.editor)}handleTripleClick(t){LT(this.editor)}}function OT(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function _T(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const HA=S("delete-text");function jA(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof je||g(HA,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);g(HA,tt(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!sn(s,l-e)){const a=Ri(s,l);e=l-a}}else if(t==="forward"&&l+e>ut(n,s))return 0;return t==="backward"&&(l-=e),n.deleteTextFromBlock(s,l,e)}function UA(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const FT=S("handle-backspace");function Xg(n,t){if(!he(n,t))return;const e=nt(t);Eo(e)!==1&&n.deleteBlock(t)}function PT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(tt(n,o))if(e.offset===0){if(UA(n,o))return;const r=ce(o);if(r){if(!n.isBlockWritable(r))return;if(tt(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Lt(n,r)){Xg(n,o);const i=Vl(n,r);i?n.selection.selectBlock(i,ut(n,i)):n.selection.selectBlock(r,0,ut(n,r))}else Xg(n,o),g(FT,Le(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=nt(o);if(Do(i)){const s=x4(n,i);if(s){if(!n.isBlockWritable(s))return;Xg(n,o),n.selection.selectBlock(s,ut(n,s))}}}}else jA(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=bt(o),i=nt(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function NT(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(tt(n,o))if(e.offset===ut(n,o)){const r=Zt(o);if(r){if(!n.isBlockWritable(r))return;tt(n,r)?n.mergeTextBlock(o,r,{focus:!0}):he(n,o)?n.deleteBlock(o,ye(n,r,0)):n.deleteBlock(r)}}else jA(n,"forward",1,null);else{const r=bt(o),i=nt(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function $T(n){const{range:t}=n.selection,{start:e,end:o}=t,r=n.getBlockById(e.blockId),i=n.getBlockById(o.blockId);if(r!==i||!Lt(n,r))return!1;if($r(e))return!0;const s=Os(n,r,e,o),l=En(n,r);return s.length===l.length}function HT(n,t){if($T(n)){const o=n.getFocusedBlock(),r=bt(o),i=at(nt(o));n.insertTextBlock("",i,r+1);return}n.selection.range.isCollapsed()||n.clearSelectedContents();const e=n.getFocusedBlock();if(tt(n,e)){if(he(n,e)&&UA(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 jT(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!tt(n,o))return!1;const r=e.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:K(),box:!0,created:Date.now()}),!0}const UT=S("input-handler-actions");function zT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(HT(n),!0))}function VT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(NT(n),!0))}function WT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(PT(n),!0))}function qT(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(jT(n),!0))}function GT(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t,{toPlainText:!0})}).catch(t=>{UT.error(t)}),!0)}const Sh={ArrowDown:sA,ArrowUp:iA,ArrowLeft:oA,ArrowRight:rA,"Shift+ArrowDown":lA,"Shift+ArrowUp":uA,"Shift+ArrowLeft":cA,"Shift+ArrowRight":aA,"CtrlOrCmd+ArrowLeft":hA,"CtrlOrCmd+ArrowRight":fA,"CtrlOrCmd+Shift+ArrowLeft":mA,"CtrlOrCmd+Shift+ArrowRight":gA,"CtrlOrCmd+ArrowUp":CA,"CtrlOrCmd+ArrowDown":pA,"CtrlOrCmd+Shift+ArrowUp":AA,"CtrlOrCmd+Shift+ArrowDown":Zg,"CtrlOrCmd+A":FA,Home:BA,End:EA,"Shift+Home":kA,"Shift+End":wA,PageUp:SA,PageDown:LA,"Shift+PageUp":MA,"Shift+PageDown":RA,"CtrlOrCmd+Z":OT,"CtrlOrCmd+Shift+Z":_T,Enter:zT,Delete:VT,Backspace:WT,"Shift+Enter":qT,"CtrlOrCmd+Shift+V":GT};function zA(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function VA(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=>{VA(n,l,e)})})}function WA(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):VA(t,r,e)})}async function ZT(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 QT(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 YT(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(QT(n,t)){const s=Array.from(Object.keys(o));r=await ZT(n,s),WA(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&&WA(n,t,i)}async function JT(n,t,e){await YT(n,t),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&Le(i)){const s=nt(i),l=n.getBlockIndex(i),[a]=n.insertDocAt(s,l+1,t,e);a&&n.selection.selectBlock(a,ut(n,a))}else{n.clearSelectedContents();const{block:s,offset:l}=Gl(n);n.insertDoc(s,l,t,e)}})}const KT=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function XT(n){let t;for(const e of KT)if(t=n[e],t)break;return t||null}function qA(n,t,e){if(t.type==="embed"){const s=t.embedData.src;if(s&&typeof s=="string")for(const l of s.split("|"))e.add(l);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=>{qA(n,l,e)})})}function tD(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)}):qA(t,r,e)}),Array.from(e)}function Lh(n,t){return`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Bs(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Mh(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=tD(n,t),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),t.meta={...e,resources:r}}function eD(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let o=Th(n);const r=e==null?void 0:e(n,t,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Mh(n,o);const i=bh(n,o),s=Ma(n,o),l=Lh(i,o);t.clipboardData.setData("text/html",l),t.clipboardData.setData("text/plain",s),t.clipboardData.setData("text/x-ones-editor-doc",JSON.stringify(o))}async function Rh(n,t){const e=Kg(n,t);Mh(n,e);const o=bh(n,e),r=Ma(n,e),i=Lh(o,e);return Mm([{type:"text/plain",data:new Blob([r],{type:"text/plain"})},{type:"text/html",data:new Blob([i],{type:"text/html"})}])}class nD{constructor(t){m(this,"editor");m(this,"handlers",[]);m(this,"onPasteText",async(t,e)=>{const o=new DataTransfer;o.setData("text/plain",t);const r=await this.editor.dataConverter.fromData(this.editor,o,e);r&&this.pasteDocs(r,null)});this.editor=t}onInsertText(t,e){if(!tt(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=Gl(this.editor);this.handleBeforeInsertText(o,r,i,e)||(this.defaultInsertText(this.editor,o,r,i,e),this.handleAfterInsertText(o,r,i,e),this.editor.selection.updateLastCaretRect())}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}=Gl(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}=Gl(this.editor);for(let l=0;l<this.handlers.length;l++){const a=this.handlers[l];a.handleUpdateCompositionText&&a.handleUpdateCompositionText(this.editor,r,i,s,o)}this.editor.selection.updateLastCaretRect()}onCopy(t){eD(this.editor,t,(e,o,r)=>{for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforeCopy){const l=s.handleBeforeCopy(this.editor,o,r);if(l===!0)return!0;if(typeof l=="object"&&l!=null)return l}}})}onCut(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforeCut&&r.handleBeforeCut(this.editor,t)===!0)return}if(this.onCopy(t),this.editor.selection.range.isCollapsed()){const o=this.editor.selection.focusedBlock;Le(o)&&this.editor.deleteBlock(o)}else Fg(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;this.editor.dataConverter.fromData(this.editor,t.clipboardData).then(async o=>{o&&this.pasteDocs(o,t)})}onFocus(){W(this.editor.rootElement,"active")}onBlur(){et(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){Lg(this.editor,i)}defaultHandleKeydown(t,e){return zA(this.editor,e)?(e.preventDefault(),e.stopPropagation(),!0):!1}async pasteDoc(t){for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleBeforePasteDoc&&await r.handleBeforePasteDoc(this.editor,t))return}const e={blockIdMap:new Map,containerIdMap:new Map};await JT(this.editor,t,e);for(let o=0;o<this.handlers.length;o++){const r=this.handlers[o];if(r.handleAfterPasteDoc&&await r.handleAfterPasteDoc(this.editor,t,e))return}}async pasteDocs(t,e){for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleBeforePaste&&await i.handleBeforePaste(this.editor,e,t))return}const o=XT(t);if(!!o){await this.pasteDoc(o);for(let r=0;r<this.handlers.length;r++){const i=this.handlers[r];if(i.handleAfterPaste&&await i.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function oD(n,t,e){const o=Or(t,e);return o.remove(),o}S("copy-dom-attributes");const GA=["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 rD(n,t){for(let l=0;l<GA.length;l++){const a=GA[l];t[a]=n[a]}const e=n.attributes,o=t.attributes,r=[],i=[];for(let l=0;l<e.length;l++){const a=e[l],d=o.getNamedItem(a.name);d?d.value!==a.value&&(d.value=a.value,i.push(a)):r.push(a)}const s=[];for(let l=0;l<o.length;l++){const a=o[l];e.getNamedItem(a.name)||s.push(a)}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 ZA(n){const t=Array.from(n.childNodes).filter(e=>!jC(e));return t.forEach(e=>{e.remove()}),t}function QA(n,t,e){var d;const o=n.getContainerById(t),r=Or(o,e),i=Di(r),s=n.doc.getBlockData(t,e),l=Qt(n,r);if((d=l==null?void 0:l.handleUpdateBlock)==null?void 0:d.call(l,n,r,s))n.editorBlockRenders.updateBlock(n,i,r,s);else{const h=n.editorBlocks.createBlock(i,o,s),p=ZA(h);ZA(r),p.forEach(v=>{r.appendChild(v)});const A=Jd(h);if(A){const v=Jd(r);v&&v.remove(),r.appendChild(A)}rD(h,r)}i4(n,r,s),n.blockHooks.forEach(h=>{var p;(p=h.update)==null||p.call(h,n,i,o,r,s)}),setTimeout(()=>{n.selection.updateSelection(null)})}const iD=S("transform-selection");function YA(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;g(iD,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const d=ln.transformCursor(i.offset,e,o);l=st(t,d,"normal")}let a=s;if(s.blockId===t){const d=ln.transformCursor(s.offset,e,o);a=st(t,d,"normal")}return Ue(n,{anchor:l,focus:a})}const sD=S("handle-block-text-changed");function lD(n,t,e,o,r){const i=n.getContainerById(t),s=Or(i,e),l=n.doc.getBlockData(t,e);if(g(sD,l.text,"no block text"),XC(n,s).setBlockText(n,s,l.text),!r){const a=YA(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function cD(n,t){const e=mt.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function JA(n,t,e,o){const r=Qt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function aD(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{JA(n,i,o,{child:!0})}),JA(n,r,o,{child:!1})}const Ro=S("editor-doc");class uD extends fa{constructor(e,o,r){super();m(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)}verifyBlockWritable(e,o){const r=this.editor.getBlockByIndex(e,o);g(Ro,this.editor.isBlockWritable(r),`block is not writable, ${e}, ${o}`)}localUpdateBlockText(e,o,r,i){g(Ro,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const s=this.getBlockData(e,o),l=s.text;g(Ro,l,`no text, ${e}, ${o}`);const a=YA(this.editor,s.id,r,!0),d=ln.apply(l,r);this.localEvents.forEach(p=>p.onBeforeUpdateBlockText(e,s.id,l,d,a.toDocRange()));const h=this.externalDoc.localUpdateBlockText(e,o,r);return this.editor.selection.setRange(a,i),h}localUpdateBlockData(e,o,r,i){g(Ro,!this.editor.readonly,"editor is readonly");const s=this.editor.getBlockByIndex(e,o);if(!this.editor.isBlockWritable(s)){const h=Array.from(r.delete).filter(A=>A!=="comments"),p=Object.keys(r.insert).filter(A=>A!=="comments");(h.length>0||p.length>0)&&g(Ro,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=mt.default(this.getBlockData(e,o)),a=mt.default(cD(l,r));this.localEvents.forEach(h=>h.onBeforeUpdateBlockData(e,l.id,l,a,i));const d=this.externalDoc.localUpdateBlockData(e,o,r,i);return this.editor.selection.setRange(Si(this.editor,i)),d}localInsertBlock(e,o,r,i,s){g(Ro,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(a=>a.onBeforeInsertBlock(e,o,r,i));const l=this.externalDoc.localInsertBlock(e,o,r,i);return this.editor.selection.setRange(Si(this.editor,i),s),l}localDeleteBlock(e,o,r){g(Ro,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const i=mt.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(Si(this.editor,r)),s}localDeleteChildContainers(e){return g(Ro,!this.editor.readonly,"editor is readonly"),e.forEach(o=>{const r=mt.default(this.getContainerBlocks(o));this.localEvents.forEach(i=>i.onBeforeDeleteChildContainer(o,r))}),this.externalDoc.localDeleteChildContainers(e)}localInsertChildContainer(e,o){return g(Ro,!this.editor.readonly,"editor is readonly"),this.localEvents.forEach(r=>r.onBeforeInsertChildContainer(e,mt.default(o))),this.externalDoc.localInsertChildContainer(e,o)}onRequestReload(e){Ro.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)}),lD(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)}),QA(this.editor,e,o),this.editor.emit("docChanged",this.editor,i)}onInsertBlock(e,o,r,i){this.callbacks.forEach(l=>{var a;return(a=l.onInsertBlock)==null?void 0:a.call(l,e,o,r,i)});const s=this.editor.getContainerById(e);KE(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){aD(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);oD(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){Ro.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function KA(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 tp=S("undo-action");class Kl{constructor(t,e,o){m(this,"beforeRange");m(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 g(tp,t,"no other action"),!1}combine(t){g(tp,!1,"no other")}setAfterRange(t){this.afterRange&&tp.warn("after range has already set"),this.afterRange=t}}const dD=S("block-action");class XA extends Kl{constructor(e,o,r,i,s){super(e,o,s);m(this,"blockData");m(this,"blockIndex");this.blockData=mt.default(i),this.blockIndex=r}deleteBlock(e,o){if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockData.id);return i?(g(dD,this.blockIndex===bt(i),"invalid block index"),kh(e,i,Si(e,o)),!0):!1}insertBlock(e,o){return Ql(e,this.containerId,this.blockIndex,mt.default(this.blockData),o),!0}}class hD extends XA{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class fD extends XA{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class mD extends Kl{constructor(e){super(e,at(e.rootContainer),e.selection.range.toDocRange());m(this,"actions",[])}addAction(e){KA(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 Kl&&(o.afterRange||o.setAfterRange(e))}}const Hs=S("update-block-data-action");class Oh extends Kl{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeBlockData");m(this,"afterBlockData");m(this,"blockId");this.blockId=r,g(Hs,this.blockId===i.id,"invalid block id"),g(Hs,this.blockId===s.id,"invalid block id"),this.beforeBlockData=mt.default(i),this.afterBlockData=mt.default(s),g(Hs,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){g(Hs,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hs,r,"no container"),Eh(e,o,Oh.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){g(Hs,e,"no editor");const o=e.getBlockById(this.blockId);if(!o)return!1;const r=e.getContainerById(this.containerId);return g(Hs,r,"no container"),Eh(e,o,Oh.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=mt.default(e);return delete o.id,delete o.type,o}}const ep=S("update-block-text-action");class $a extends Kl{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeRichTextData");m(this,"afterRichTextData");m(this,"blockId");m(this,"type");this.blockId=r,this.beforeRichTextData=mt.default(i),this.afterRichTextData=mt.default(s),this.type=$a.calType(i,s)}static calType(e,o){g(ep,e,"no old data"),g(ep,o,"no new data");const i=ln.diff(e,o),s=new Set;let l=!1;const a=h=>pC(h)?`cjk_${h}`:mC(h)?"number":jd(h)?"space":gC(h)?"letter":"unknown";let d=!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,d=!0,s.add(`insert_${a(h.insert.substr(1))}`)):s.add(`insert_${a(h.insert)}`):h.delete&&(l?l=!1:s.add("delete"))}),{textType:Array.from(s).join("|"),begin:d}}undo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Bh(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Bh(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof $a)||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){g(ep,e instanceof $a,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}class tb extends Kl{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,mt.default(this.blocks)),!0}}class gD extends tb{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class pD extends tb{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Oo=S("undo");class CD{constructor(t){m(this,"editor");m(this,"actions",[]);m(this,"undoCursor");m(this,"currentGroup",null);m(this,"groupCounter",0);m(this,"undoRedoing",!1);m(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):(KA(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(g(Oo,!this.currentGroup,"current group already exists"),this.currentGroup=new mD(this.editor),this.groupCounter=1):(g(Oo,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){g(Oo,this.currentGroup,"current group not exists"),g(Oo,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Oo.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 Oo.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(Si(this.editor,t.beforeRange))}catch(e){Oo.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(Si(this.editor,e)):Oo.warn("no after range")}catch(e){Oo.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(),ln.diff(o,r).length!==0&&this.addAction(new $a(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new Oh(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),g(Oo,e>=0,"invalid block index"),g(Oo,o,"no block data"),this.addAction(new hD(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new fD(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new gD(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new pD(this.editor,t,e)))}}class AD{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 bD{constructor(){m(this,"converters",[]);this.addConverter(new AD)}async fromData(t,e,o){let r={};for(const i of this.converters){const s=await i.fromData(t,e,o);s&&(r={...r,...s})}return r}addConverter(t){this.converters.push(t)}}class vD{constructor(t){m(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 pe extends be.TypedEmitter{constructor(e){super();m(this,"hoveringBlock",null);m(this,"hoveringTextChild",null);m(this,"filters",[]);m(this,"finders",[]);m(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=ot(o);if((!r||!Kt(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?it(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&&Kt(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&et(s,"hover"),e&&W(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 pe(e))}getParentTextContentChild(e,o){if(!tt(this.editor,e))return null;const r=Rt(e);return o.parentElement===r?o:$m(o)}}const eb="style-color-",nb="style-bg-color-";class yD{renderText(t,e,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(eb)?i["data-style-color"]=l.substring(eb.length):l.startsWith(nb)?i["data-style-bg-color"]=l.substring(nb.length):l.startsWith("style")&&r.push(l):typeof a=="string"&&(l==="link"&&(r.push("link"),i.link=a),l==="inline-style-color"&&(s.color=a))}),{classes:r,attributes:i,styles:s}}renderBlock(t,e,o){var l,a;const r={};Object.entries(o).filter(d=>d[0].startsWith("style-")).forEach(([d,h])=>{r[`data-${d}`]=`${h}`});const s=[];return((a=(l=t.selection)==null?void 0:l.range)==null?void 0:a.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"),pe.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(a=>{a.name.startsWith("data-style-")&&o.removeAttribute(a.name)}),Object.entries(r).filter(a=>a[0].startsWith("style-")||a[0]==="align").forEach(([a,d])=>{a==="align"&&o.setAttribute(a.startsWith("style-")?`data-${a}`:`data-style-${a}`,`${d}`)}),((l=(s=t.selection)==null?void 0:s.range)==null?void 0:l.start.blockId)===r.id&&W(o,"focused"),pe.get(t).hoveringBlockId()===r.id&&W(o,"hover")}}function kD(n){n.editorBlocks.registerBlockClass(In),n.editorBlocks.registerBlockClass(E4),n.editorBoxes.registerBoxClass(g6),n.editorBoxes.registerBoxClass(p6),n.editorBoxes.registerBoxClass(b6),n.editorBoxes.registerBoxClass(v6),n.editorInsertions.registerInsertionClass(y6),n.editorBlockRenders.registerRender(new yD)}function wD(n,t){kD(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 ob=S("range-commands");function rb(n,t){n.forEach(e=>{e.source=t,e.children&&rb(e.children,t)})}function ib(n,t,e){const o=it(t);g(ob,o===e.start.blockId,"invalid start range"),g(ob,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);rb(l,s.id),i.push(...l)}),r.forEach(s=>{if(s.filterCommands){const l=s.filterCommands(n,t,e,i);l&&(i=l)}}),Lt(n,t)&&Os(n,t,e.start,e.end).forEach(l=>{ve(l).forEach(d=>{const h=ut(n,d),p=Ue(n,{anchor:st(d,0,"home"),focus:st(d,h,"end")}),A=ib(n,d,p);i.push(...A)})}),i}function sb(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[];return e.forEach(r=>{const i=Ue(t,{anchor:r.start,focus:r.end});ib(t,r.block,i).forEach(l=>{o.push(l)})}),o}function lb(n,t,e,o,r,i){var h;const s=n.editorCommandProviders.getCommandProviders();for(let p=0;p<s.length;p++){const A=s[p];if(A.beforeExecuteCommand&&A.beforeExecuteCommand(n,t,e,o,r))return!1}const l=n.editorCommandProviders.getCommandProvider(o.source),a={};if((h=l.executeCommand)!=null&&h.call(l,n,t,e,o,r,{}))return i[it(t)]=a,!0;let d=!1;return Lt(n,t)&&Os(n,t,e.start,e.end).forEach(A=>{ve(A).forEach(B=>{const D=ut(n,B),T=Ue(n,{anchor:st(B,0,"home"),focus:st(B,D,"end")});lb(n,B,T,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,t,e,o,r,i)}),d}function cb(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 a=Ue(o,{anchor:l.start,focus:l.end});lb(o,l.block,a,t,e,r)}),r}const BD=S("command-providers");class ab{constructor(t){m(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 g(BD,e,`no command provider, id=${t}`),e}getCommands(t){return sb(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>cb(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 ED(n,t){const e=nt(t),o=at(e),r=bt(t);QA(n,o,r)}const xD=S("table-scroll");class ub{constructor(t,e,o,r,i){m(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 ID{constructor(t){m(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)){xD.warn(`event has already registered: ${e}`);return}i.push(new ub(this.editor,t,e,o,r))}else{const s=new ub(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 a=s[l];if(e)e===a.name&&o===a.handler&&s.splice(l,1);else if(o===a.handler){s.splice(l,1),a.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 db=S("update-block-text");function TD(n,t){const e=n.getBoxById(t.id),o=ot(e);g(db,o,"no parent block"),g(db,tt(n,o),"not a text block");const r=n.getBlockText(o),i=s6(r,"id",t.id,t);z6(n,o,i)}function DD(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 SD(n){return n.readonly?!1:!Lo(n).find(o=>!n.isBlockWritable(o.block))}class LD{constructor(t){this.editor=t}getKey(t){return`${this.editor.id}-${t}`}getItem(t){return window.localStorage.getItem(this.getKey(t))}setItem(t,e){if(!e){this.removeItem(t);return}window.localStorage.setItem(this.getKey(t),e)}removeItem(t){window.localStorage.removeItem(this.getKey(t))}}class MD{constructor(){m(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(Rr(e,s)){const a=l(t,e);if(a!==void 0)return a}}}}const zr=S("editor");class RD extends be.TypedEmitter{constructor(e,o,r){var i,s,l,a,d,h,p;super();m(this,"parent");m(this,"rootElement");m(this,"contentElement");m(this,"rootContainerObject");m(this,"rootContainer");m(this,"input");m(this,"selection");m(this,"selectionHandler");m(this,"doc");m(this,"id");m(this,"clientId");m(this,"compositingText","");m(this,"undoManager");m(this,"shortcuts",new MD);m(this,"dataConverter",new bD);m(this,"editorBlocks",new y4(this));m(this,"editorBoxes",new A6(this));m(this,"editorInsertions",new w6(this));m(this,"editorEmbeds",new w4(this));m(this,"editorDecorators",new B6(this));m(this,"editorCommandProviders",new ab(this));m(this,"editorBlockRenders",new vD(this));m(this,"blockHooks",[]);m(this,"domEvents",new ID(this));m(this,"customs",new Map);m(this,"options");m(this,"inputHandlers",new nD(this));m(this,"settingsProvider");m(this,"_readonly",!1);zr.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=(a=r==null?void 0:r.settingsProvider)!=null?a:new LD(this),wD(this,r==null?void 0:r.components),this.blockHooks.push(...(h=(d=r==null?void 0:r.components)==null?void 0:d.blockHooks)!=null?h:[]),this.id=(p=r==null?void 0:r.id)!=null?p:K(),this.clientId=K(),this.undoManager=new CD(this),this.doc=new uD(this,o,this.undoManager),this.parent=e,this.rootElement=w("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=w("div",["editor-content"],this.rootElement),this.rootContainerObject=A4(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new zI(this,this.inputHandlers),this.selection=new ST(this),this.selectionHandler=new RT(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),Ke.isMobile&&W(this.rootElement,"mobile"),Ke.isSafari&&W(this.rootElement,"safari"),this._readonly&&W(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?W(this.rootElement,"readonly"):et(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:oo(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 g(zr,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(){zr.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(),setTimeout(()=>{W(this.rootElement,"active")})}focusToBlock(e,o){Pg(this,e,o)}isWritable(){return SD(this)}isBlockWritable(e){return DD(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return g(zr,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),g(zr,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`),o}createChildContainer(e,o,r){return b4(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&&g(zr,xs(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(zr,Nm(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return g(zr,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return g(zr,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return Or(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return bt(o)}return bt(e)}getContainerById(e){return Nr(this,e)}getParentContainer(e){return nt(e)}reloadBlock(e){ED(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},a={anchor:l,focus:l};return Ql(this,e,o,r,i!=null?i:a,s)}insertEmbed(e,o,r,i,s){const l={id:K(),type:"embed",embedType:r,embedData:i};return this.insertBlock(e,o,l,s)}deleteBlock(e,o){Og(this,e,o)}mergeTextBlock(e,o){return H6(this,e,o)}breakTextBlock(e,o,r){return Yl(this,e,o,r).newBlock}getTextPosition(){return Gl(this)}getBlockString(e,o){const r=this.getBlockText(e);return re(r,o)}getBlockData(e){return _i(this,e)}getBoxData(e){return f6(this,e)}getBlockText(e){return mn(this,e)}setBlockText(e,o){z6(this,e,o)}deleteTextFromBlock(e,o,r,i){return Mg(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return R6(this,e,o,r,i)}insertBoxToBlock(e,o,r){return O6(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){q6(this,e,o,r,i)}insertDocAt(e,o,r,i){return Hg(this,e,o,r,i)}deleteChildContainers(e){$6(this,e)}replaceBlockText(e,o){return Bh(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...a}=i;return Eh(this,e,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return V6(this,e,o,r)}updateBoxData(e){TD(this,e)}getSelectedText(){const e=Th(this);return La(this,e)}clearSelectedContents(){Fg(this)}insertTextBlock(e,o,r,i){const s=sr(e!=null?e:"");return N6(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){F6(this);return}o?(this.compositingText="",Em()||Lg(this,e)):(this.compositingText=e,_6(this))}getColor(e){const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]}}function Ha(n,t,e){return new RD(n,t,e)}function OD(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=fm.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const _D=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class _h extends be.TypedEmitter{constructor(e){super();m(this,"users",new Map);m(this,"cursors",new Map);m(this,"addingUser",!1);m(this,"colors");this.colors=e&&e.length>0?e:_D}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&ua.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&&fh(r.range)).forEach(r=>{const i=r.range.focus.offset;let s=o.get(i);s||(s=[],o.set(i,s)),s.push(r)}),o}getCursors(e){return Array.from(this.cursors.values()).filter(o=>o.range.anchor.blockId===e||o.range.focus.blockId===e)}onUpdateBlockText(e,o,r){if(!e.text)return;this.getCursors(e.id).forEach(l=>{if(fh(l.range)){const{anchor:a,focus:d}=l.range;a.blockId===e.id&&(a.offset=ln.transformCursor(a.offset,o,r)),d.blockId===e.id&&(d.offset=ln.transformCursor(d.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 Xe=S("local-doc");class np extends fa{constructor(e,o){super();m(this,"doc");m(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[sr("")]}},this.serviceUrl=(o==null?void 0:o.serverUrl)||""}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return mt.default(this.doc)}getContainerBlocks(e){return this.doc.blocks[e]}getBlockData(e,o){const r=this.getContainerBlocks(e);g(Xe,r,`no container data: ${e}`);const i=r[o];return g(Xe,i,`no block data: ${o}`),i}localUpdateBlockText(e,o,r){const i=this.getBlockData(e,o);g(Xe,i.text,"no text for data");const s=ln.apply(i.text,r);return i.text=s,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(l=>{var a;return(a=l.onUpdateBlockText)==null?void 0:a.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}),g(Xe,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 g(Xe,i,`no container data: ${e}`),g(Xe,o>=0&&o<=i.length,`invalid block index: ${o}, ${i.length}`),i.splice(o,0,r),g(Xe,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);g(Xe,r,`no container data: ${e}`),g(Xe,o>=0&&o<=r.length,`invalid block index: ${o}, ${r.length}`);const i=r[o];return r.splice(o,1),g(Xe,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,g(Xe,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){Xe.debug(`delete child containers: ${e}`),e.forEach(o=>{g(Xe,this.doc.blocks[o],`no child container: ${o}`),delete this.doc.blocks[o]}),e.forEach(o=>{g(Xe,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){g(Xe,!1,"not implemented")}async addResources(e){return e}buildResourceUrl(e){return e}request(e,o){g(Xe,!1,"not implemented")}broadcastMessage(e){}getServerMeta(){return{serverId:this.serviceUrl}}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new _h}setDoc(e){this.doc=mt.default(e),this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,"change doc")})}destroy(){this.clearCallbacks()}}class FD{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function op(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new FD(o)})}const hb=S("find-block");function fb(n,t){const e=Ds(t);if(!e){if(ro(t))return null;const o=Is(t);return g(hb,o,"no parent block"),fb(n,o)}return Lt(n,e)?Vl(n,e,{visibleOnly:!0}):e}function mb(n,t){const e=Ss(t);if(!e){if(ro(t))return null;const o=Is(t);return g(hb,o,"no parent block"),mb(n,o)}return Lt(n,e)?eg(n,e,{visibleOnly:!0}):e}const PD=S("remote-cursor");class ND{constructor(){m(this,"remoteUsers",new _h)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):PD.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 $D(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function HD(n){const{blocks:t,meta:e,comments:o}=n,{root:r,...i}=t;return{blocks:r,meta:e,comments:o,...i}}function ja(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=$D(mt.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function Ni(n){return n==="root"?"blocks":n}function Xl(n){return n==="blocks"?"root":n}const jD={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new on.default(n)},apply(n,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},compose(n,t){const e=new on.default(n),o=new on.default(t);return e.compose(o).ops},diff(n,t){const e=new on.default(n),o=new on.default(t);return e.diff(o).ops},transform(n,t,e){const o=new on.default(n);return new on.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 on.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 cr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},$i={},rp=Z5.default.EventEmitter;$i.EventEmitter=rp,$i.mixin=UD;function UD(n){for(var t in rp.prototype)n.prototype[t]=rp.prototype[t]}var gb=["info","warn","error"];function pb(){var n={};gb.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var zD=pb;pb.prototype.setMethods=function(n){n=n||{};var t=this;gb.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var VD=zD,WD=new VD,Cb=WD;function js(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,js):this.stack=new Error().stack}js.prototype=Object.create(Error.prototype),js.prototype.constructor=js,js.prototype.name="ShareDBError",js.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 Fh=js,Ua={},Ab=qD;function qD(n,t,e,o){var r=function(s,l,a,d){t(a,s,l,"left"),t(d,l,s,"right")},i=n.transformX=function(s,l){e(s),e(l);for(var a=[],d=0;d<l.length;d++){for(var h=l[d],p=[],A=0;A<s.length;){var v=[];if(r(s[A],h,p,v),A++,v.length===1)h=v[0];else if(v.length===0){for(var B=A;B<s.length;B++)o(p,s[B]);h=null;break}else{for(var D=i(s.slice(A),v),T=0;T<D[0].length;T++)o(p,D[0][T]);for(var _=0;_<D[1].length;_++)o(a,D[1][_]);h=null;break}}h!=null&&o(a,h),s=p}return[s,a]};n.transform=function(s,l,a){if(!(a==="left"||a==="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],a):a==="left"?i(s,l)[0]:i(l,s)[1]}}var bb={exports:{}},Hi=bb.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||""}},ip=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},sp=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")},Ph=function(n){for(var t=0;t<n.length;t++)sp(n[t])};Hi.apply=function(n,t){var e;Ph(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=ip(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 Vr=Hi._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:ip(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:ip(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};Hi.compose=function(n,t){Ph(n),Ph(t);for(var e=n.slice(),o=0;o<t.length;o++)Vr(e,t[o]);return e},Hi.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),Vr(t,o)}return t};var lp=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};Hi.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=lp(n,t[r],o);return n};var GD=Hi._tc=function(n,t,e,o){if(sp(t),sp(e),t.i!=null)Vr(n,{i:t.i,p:lp(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(Vr(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&Vr(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)Vr(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)Vr(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),a=t.d.slice(s-t.p,l-t.p),d=e.d.slice(s-e.p,l-e.p);if(a!==d)throw new Error("Delete ops delete different text in the same region of the document");i.d!==""&&(i.p=lp(i.p,e),Vr(n,i))}return n},ZD=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};Hi.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=ZD(n[t]);return n},Ab(Hi,GD,Ph,Vr);var Nh=function(n){return Object.prototype.toString.call(n)=="[object Array]"},QD=function(n){return!!n&&n.constructor===Object},_o=function(n){return JSON.parse(JSON.stringify(n))},It={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Wr={};It.registerSubtype=function(n){Wr[n.name]=n},It.create=function(n){return n===void 0?null:_o(n)},It.invertComponent=function(n){var t={p:n.p};return n.t&&Wr[n.t]&&(t.t=n.t,t.o=Wr[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},It.invert=function(n){for(var t=n.slice().reverse(),e=[],o=0;o<t.length;o++)e.push(It.invertComponent(t[o]));return e},It.checkValidOp=function(n){for(var t=0;t<n.length;t++)if(!Nh(n[t].p))throw new Error("Missing path")},It.checkList=function(n){if(!Nh(n))throw new Error("Referenced element not a list")},It.checkObj=function(n){if(!QD(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function za(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 Va(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}It.apply=function(n,t){It.checkValidOp(t),t=_o(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&za(r);for(var i=null,s=e,l="data",a=0;a<r.p.length;a++){var d=r.p[a];if(i=s,s=s[l],l=d,i==null)throw new Error("Path invalid")}if(r.t&&r.o!==void 0&&Wr[r.t])s[l]=Wr[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)It.checkList(s),s[l]=r.li;else if(r.li!==void 0)It.checkList(s),s.splice(l,0,r.li);else if(r.ld!==void 0)It.checkList(s),s.splice(l,1);else if(r.lm!==void 0){if(It.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)It.checkObj(s),s[l]=r.oi;else if(r.od!==void 0)It.checkObj(s),delete s[l];else throw new Error("invalid / missing instruction in op")}return e.data},It.shatter=function(n){for(var t=[],e=0;e<n.length;e++)t.push([n[e]]);return t},It.incrementalApply=function(n,t,e){for(var o=0;o<t.length;o++){var r=[t[o]];n=It.apply(n,r),e(r,n)}return n};var YD=It.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};It.append=function(n,t){if(t=_o(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)&&(za(t),za(e)),YD(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Wr[t.t]){if(e.o=Wr[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(),Va(t),n.push(t);Va(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)&&(Va(t),Va(e)),n.push(t)},It.compose=function(n,t){It.checkValidOp(n),It.checkValidOp(t);for(var e=_o(n),o=0;o<t.length;o++)It.append(e,t[o]);return e},It.normalize=function(n){var t=[];n=Nh(n)?n:[n];for(var e=0;e<n.length;e++){var o=n[e];o.p==null&&(o.p=[]),It.append(t,o)}return t},It.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},It.canOpAffectPath=function(n,t){return It.commonLengthForOps({p:t},n)!=null},It.transformComponent=function(n,t,e,o){t=_o(t);var r=It.commonLengthForOps(e,t),i=It.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 a=_o(e);a.p=a.p.slice(s),t.ld=It.apply(_o(t.ld),[a])}else if(t.od!==void 0){var a=_o(e);a.p=a.p.slice(s),t.od=It.apply(_o(t.od),[a])}}if(r!=null){var d=s==l,a=e;if((t.si!=null||t.sd!=null)&&(e.si!=null||e.sd!=null)&&(za(t),a=_o(e),za(a)),a.t&&Wr[a.t]){if(t.t&&t.t===a.t){var h=Wr[t.t].transform(t.o,a.o,o);if(t.si!=null||t.sd!=null)for(var p=t.p,A=0;A<h.length;A++)t.o=[h[A]],t.p=p.slice(),Va(t),It.append(n,t);else(!Nh(h)||h.length>0)&&(t.o=h,It.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(d){if(t.ld!==void 0)if(t.li!==void 0&&o==="left")t.ld=_o(e.li);else return n}else return n}else if(e.li!==void 0)t.li!==void 0&&t.ld===void 0&&d&&t.p[r]===e.p[r]?o==="right"&&t.p[r]++:e.p[r]<=t.p[r]&&t.p[r]++,t.lm!==void 0&&d&&e.p[r]<=t.lm&&t.lm++;else if(e.ld!==void 0){if(t.lm!==void 0&&d){if(e.p[r]===t.p[r])return n;var p=e.p[r],v=t.p[r],B=t.lm;(p<B||p===B&&v<B)&&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 v=t.p[r],B=t.lm,D=e.p[r],T=e.lm;if(D!==T)if(v===D)if(o==="left")t.p[r]=T,v===B&&(t.lm=T);else return n;else v>D&&t.p[r]--,v>T?t.p[r]++:v===T&&D>T&&(t.p[r]++,v===B&&t.lm++),(B>D||B===D&&B>v)&&t.lm--,B>T?t.lm++:B===T&&(T>D&&B>v||T<D&&B<v?o==="right"&&t.lm++:B>v?t.lm++:B===D&&t.lm--)}else if(t.li!==void 0&&t.ld===void 0&&d){var v=e.p[r],B=e.lm;p=t.p[r],p>v&&t.p[r]--,p>B&&t.p[r]++}else{var v=e.p[r],B=e.lm;p=t.p[r],p===v?t.p[r]=B:(p>v&&t.p[r]--,(p>B||p===B&&v>B)&&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&&d){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")It.append(n,{p:t.p,od:e.oi});else return n}else if(e.od!==void 0&&t.p[r]==e.p[r]){if(!d)return n;if(t.oi!==void 0)delete t.od;else return n}}}return It.append(n,t),n},Ab(It,It.transformComponent,It.checkValidOp,It.append);var JD=bb.exports;It.registerSubtype(JD);var KD=It,XD={type:KD};(function(n){n.defaultType=XD.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)})(Ua);var Fo={};(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))}})(Fo);var vb=Array.isArray,yb=Object.keys,tS=Object.prototype.hasOwnProperty,eS=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=vb(t),r=vb(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 a=t instanceof Date,d=e instanceof Date;if(a!=d)return!1;if(a&&d)return t.getTime()==e.getTime();var h=t instanceof RegExp,p=e instanceof RegExp;if(h!=p)return!1;if(h&&p)return t.toString()==e.toString();var A=yb(t);if(s=A.length,s!==yb(e).length)return!1;for(i=s;i--!==0;)if(!tS.call(e,A[i]))return!1;for(i=s;i--!==0;)if(l=A[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},kb=$i,nS=Cb,Wn=Fh,$h=Ua,Po=Fo,oS=Po.clone,rS=eS,Tn=Wn.CODES,iS=Ft;function Ft(n,t,e){kb.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}kb.mixin(Ft),Ft.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())})},Ft.prototype._setType=function(n){if(typeof n=="string"&&(n=$h.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new Wn(Tn.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},Ft.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Ft.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new Wn(Tn.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 Wn(Tn.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?$h.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()},Ft.prototype.whenNothingPending=function(n){var t=this;Po.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},Ft.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Ft.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Ft.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Ft.prototype._emitResponseError=function(n,t){if(n&&n.code===Tn.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)},Ft.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){Po.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},Ft.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){Po.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()},Ft.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===Tn.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=Hh(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=Hh(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},Ft.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))},Ft.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()},Ft.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);sS(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},Ft.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},Ft.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},Ft.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=e&&e.wantSubscribe===n;if(o){e.callback=lS([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},Ft.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;Po.nextTick(function(){n._handleSubscribe()})}}};function sS(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function lS(n){return n=n.filter(Po.truthy),n.length?function(t){Po.callEach(n,t)}:null}Ft.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function cS(n){delete n.op,delete n.create,delete n.del}function Hh(n,t){if(n.del)return cS(t);if(t.del)return new Wn(Tn.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new Wn(Tn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new Wn(Tn.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}}}Ft.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new Wn(Tn.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===$h.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=Hh(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 a=this.data;this._setType(null),this.emit("del",a,t);return}},Ft.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 Wn(Tn.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>=Po.MAX_SAFE_INTEGER)return this.emit("error",new Wn(Tn.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)}},Ft.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var o=new Wn(Tn.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;Po.nextTick(function(){r.flush()})},Ft.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)},Ft.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)}}},Ft.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!rS(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}}},Ft.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)},Ft.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=$h.defaultType.uri),this.type){var r=new Wn(Tn.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)},Ft.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new Wn(Tn.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)},Ft.prototype.pause=function(){this.paused=!0},Ft.prototype.resume=function(){this.paused=!1,this.flush()},Ft.prototype.toSnapshot=function(){return{v:this.version,data:oS(this.data),type:this.type.uri}},Ft.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return nS.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},Ft.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=Hh(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)},Ft.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=Po.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},Ft.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=Po.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var Us={};Us.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 wb=$i,Bb=Us.ACTIONS,aS=Fo,uS=Dn;function Dn(n,t,e,o,r,i,s){wb.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}wb.mixin(Dn),Dn.prototype.hasPending=function(){return!this.ready},Dn.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}},Dn.prototype.destroy=function(n){this.connection.canSend&&this.action===Bb.querySubscribe&&this.connection.send({a:Bb.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&aS.nextTick(n)},Dn.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Dn.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Dn.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Dn.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 a=t[l],d=this.connection.get(a.c||this.collection,l);d.ingestSnapshot(a,s)}s()},Dn.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},Dn.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)},Dn.prototype._handleError=function(n){this.emit("error",n)},Dn.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)},Dn.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var Eb=$i,dS=Us.ACTIONS,hS=Fo,xb=ar;function ar(n,t){if(Eb.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={}}Eb.mixin(ar),ar.prototype.submit=function(n,t){this.value=n,this.send(t)},ar.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},ar.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()})},ar.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},ar.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},ar.prototype._message=function(){return{a:dS.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},ar.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},ar.prototype._callbackOrEmit=function(n,t){if(t)return hS.nextTick(t,n);n&&this.emit("error",n)};var fS=Fo,Ib=cp;function cp(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}cp.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},cp.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&fS.nextTick(n)};var ap={exports:{}};(function(n,t){(function(e,o){o(t)})(cr,function(e){function o(k,I){I=I|0;for(var L=Math.max(k.length-I,0),F=Array(L),U=0;U<L;U++)F[U]=k[I+U];return F}var r=function(k){var I=o(arguments,1);return function(){var L=o(arguments);return k.apply(null,I.concat(L))}},i=function(k){return function(){var I=o(arguments),L=I.pop();k.call(this,I,L)}};function s(k){var I=typeof k;return k!=null&&(I=="object"||I=="function")}var l=typeof setImmediate=="function"&&setImmediate,a=typeof process=="object"&&typeof process.nextTick=="function";function d(k){setTimeout(k,0)}function h(k){return function(I){var L=o(arguments,1);k(function(){I.apply(null,L)})}}var p;l?p=setImmediate:a?p=process.nextTick:p=d;var A=h(p);function v(k){return i(function(I,L){var F;try{F=k.apply(this,I)}catch(U){return L(U)}s(F)&&typeof F.then=="function"?F.then(function(U){B(L,null,U)},function(U){B(L,U.message?U:new Error(U))}):L(null,F)})}function B(k,I,L){try{k(I,L)}catch(F){A(D,F)}}function D(k){throw k}var T=typeof Symbol=="function";function _(k){return T&&k[Symbol.toStringTag]==="AsyncFunction"}function M(k){return _(k)?v(k):k}function H(k){return function(I){var L=o(arguments,1),F=i(function(U,j){var Z=this;return k(I,function(J,lt){M(J).apply(Z,U.concat(lt))},j)});return L.length?F.apply(this,L):F}}var z=typeof cr=="object"&&cr&&cr.Object===Object&&cr,q=typeof self=="object"&&self&&self.Object===Object&&self,rt=z||q||Function("return this")(),ft=rt.Symbol,Bt=Object.prototype,jt=Bt.hasOwnProperty,Ut=Bt.toString,ee=ft?ft.toStringTag:void 0;function Ye(k){var I=jt.call(k,ee),L=k[ee];try{k[ee]=void 0;var F=!0}catch{}var U=Ut.call(k);return F&&(I?k[ee]=L:delete k[ee]),U}var Wo=Object.prototype,Ne=Wo.toString;function Ln(k){return Ne.call(k)}var vr="[object Null]",bn="[object Undefined]",an=ft?ft.toStringTag:void 0;function yr(k){return k==null?k===void 0?bn:vr:an&&an in Object(k)?Ye(k):Ln(k)}var ei="[object AsyncFunction]",mo="[object Function]",t3="[object GeneratorFunction]",e3="[object Proxy]";function n3(k){if(!s(k))return!1;var I=yr(k);return I==mo||I==t3||I==ei||I==e3}var ns=9007199254740991;function ol(k){return typeof k=="number"&&k>-1&&k%1==0&&k<=ns}function rl(k){return k!=null&&ol(k.length)&&!n3(k)}var ni={};function Nt(){}function kr(k){return function(){if(k!==null){var I=k;k=null,I.apply(this,arguments)}}}var os=typeof Symbol=="function"&&Symbol.iterator,Pc=function(k){return os&&k[os]&&k[os]()};function s1(k,I){for(var L=-1,F=Array(k);++L<k;)F[L]=I(L);return F}function un(k){return k!=null&&typeof k=="object"}var il="[object Arguments]";function l1(k){return un(k)&&yr(k)==il}var go=Object.prototype,c1=go.hasOwnProperty,o3=go.propertyIsEnumerable,sl=l1(function(){return arguments}())?l1:function(k){return un(k)&&c1.call(k,"callee")&&!o3.call(k,"callee")},Ce=Array.isArray;function ll(){return!1}var cl=typeof e=="object"&&e&&!e.nodeType&&e,a1=cl&&!0&&n&&!n.nodeType&&n,al=a1&&a1.exports===cl,u1=al?rt.Buffer:void 0,ul=u1?u1.isBuffer:void 0,rs=ul||ll,Hu=9007199254740991,ju=/^(?:0|[1-9]\d*)$/;function Uu(k,I){var L=typeof k;return I=I==null?Hu:I,!!I&&(L=="number"||L!="symbol"&&ju.test(k))&&k>-1&&k%1==0&&k<I}var zu="[object Arguments]",Vu="[object Array]",Wu="[object Boolean]",qu="[object Date]",Gu="[object Error]",Zu="[object Function]",r3="[object Map]",i3="[object Number]",s3="[object Object]",d1="[object RegExp]",h1="[object Set]",l3="[object String]",c3="[object WeakMap]",a3="[object ArrayBuffer]",u3="[object DataView]",f1="[object Float32Array]",d3="[object Float64Array]",h3="[object Int8Array]",f3="[object Int16Array]",Qu="[object Int32Array]",m3="[object Uint8Array]",Yu="[object Uint8ClampedArray]",g3="[object Uint16Array]",p3="[object Uint32Array]",ie={};ie[f1]=ie[d3]=ie[h3]=ie[f3]=ie[Qu]=ie[m3]=ie[Yu]=ie[g3]=ie[p3]=!0,ie[zu]=ie[Vu]=ie[a3]=ie[Wu]=ie[u3]=ie[qu]=ie[Gu]=ie[Zu]=ie[r3]=ie[i3]=ie[s3]=ie[d1]=ie[h1]=ie[l3]=ie[c3]=!1;function C3(k){return un(k)&&ol(k.length)&&!!ie[yr(k)]}function A3(k){return function(I){return k(I)}}var m1=typeof e=="object"&&e&&!e.nodeType&&e,dl=m1&&!0&&n&&!n.nodeType&&n,b3=dl&&dl.exports===m1,Nc=b3&&z.process,g1=function(){try{var k=dl&&dl.require&&dl.require("util").types;return k||Nc&&Nc.binding&&Nc.binding("util")}catch{}}(),p1=g1&&g1.isTypedArray,v3=p1?A3(p1):C3,y3=Object.prototype,k3=y3.hasOwnProperty;function w3(k,I){var L=Ce(k),F=!L&&sl(k),U=!L&&!F&&rs(k),j=!L&&!F&&!U&&v3(k),Z=L||F||U||j,J=Z?s1(k.length,String):[],lt=J.length;for(var pt in k)(I||k3.call(k,pt))&&!(Z&&(pt=="length"||U&&(pt=="offset"||pt=="parent")||j&&(pt=="buffer"||pt=="byteLength"||pt=="byteOffset")||Uu(pt,lt)))&&J.push(pt);return J}var $c=Object.prototype;function B3(k){var I=k&&k.constructor,L=typeof I=="function"&&I.prototype||$c;return k===L}function Hc(k,I){return function(L){return k(I(L))}}var E3=Hc(Object.keys,Object),x3=Object.prototype,I3=x3.hasOwnProperty;function C1(k){if(!B3(k))return E3(k);var I=[];for(var L in Object(k))I3.call(k,L)&&L!="constructor"&&I.push(L);return I}function jc(k){return rl(k)?w3(k):C1(k)}function A1(k){var I=-1,L=k.length;return function(){return++I<L?{value:k[I],key:I}:null}}function T3(k){var I=-1;return function(){var F=k.next();return F.done?null:(I++,{value:F.value,key:I})}}function D3(k){var I=jc(k),L=-1,F=I.length;return function U(){var j=I[++L];return j==="__proto__"?U():L<F?{value:k[j],key:j}:null}}function S3(k){if(rl(k))return A1(k);var I=Pc(k);return I?T3(I):D3(k)}function po(k){return function(){if(k===null)throw new Error("Callback was already called.");var I=k;k=null,I.apply(this,arguments)}}function hl(k){return function(I,L,F){if(F=kr(F||Nt),k<=0||!I)return F(null);var U=S3(I),j=!1,Z=0,J=!1;function lt(ct,At){if(Z-=1,ct)j=!0,F(ct);else{if(At===ni||j&&Z<=0)return j=!0,F(null);J||pt()}}function pt(){for(J=!0;Z<k&&!j;){var ct=U();if(ct===null){j=!0,Z<=0&&F(null);return}Z+=1,L(ct.value,ct.key,po(lt))}J=!1}pt()}}function wr(k,I,L,F){hl(I)(k,M(L),F)}function $e(k,I){return function(L,F,U){return k(L,I,F,U)}}function Ju(k,I,L){L=kr(L||Nt);var F=0,U=0,j=k.length;j===0&&L(null);function Z(J,lt){J?L(J):(++U===j||lt===ni)&&L(null)}for(;F<j;F++)I(k[F],F,po(Z))}var L3=$e(wr,1/0),qo=function(k,I,L){var F=rl(k)?Ju:L3;F(k,M(I),L)};function Go(k){return function(I,L,F){return k(qo,I,M(L),F)}}function Ku(k,I,L,F){F=F||Nt,I=I||[];var U=[],j=0,Z=M(L);k(I,function(J,lt,pt){var ct=j++;Z(J,function(At,Gt){U[ct]=Gt,pt(At)})},function(J){F(J,U)})}var Uc=Go(Ku),Xu=H(Uc);function oi(k){return function(I,L,F,U){return k(hl(L),I,M(F),U)}}var Br=oi(Ku),td=$e(Br,1),ed=H(td);function is(k,I){for(var L=-1,F=k==null?0:k.length;++L<F&&I(k[L],L,k)!==!1;);return k}function nd(k){return function(I,L,F){for(var U=-1,j=Object(I),Z=F(I),J=Z.length;J--;){var lt=Z[k?J:++U];if(L(j[lt],lt,j)===!1)break}return I}}var ss=nd();function ls(k,I){return k&&ss(k,I,jc)}function b1(k,I,L,F){for(var U=k.length,j=L+(F?1:-1);F?j--:++j<U;)if(I(k[j],j,k))return j;return-1}function M3(k){return k!==k}function v1(k,I,L){for(var F=L-1,U=k.length;++F<U;)if(k[F]===I)return F;return-1}function fl(k,I,L){return I===I?v1(k,I,L):b1(k,M3,L)}var zc=function(k,I,L){typeof I=="function"&&(L=I,I=null),L=kr(L||Nt);var F=jc(k),U=F.length;if(!U)return L(null);I||(I=U);var j={},Z=0,J=!1,lt=Object.create(null),pt=[],ct=[],At={};ls(k,function(de,oe){if(!Ce(de)){Gt(oe,[de]),ct.push(oe);return}var ge=de.slice(0,de.length-1),Ao=ge.length;if(Ao===0){Gt(oe,de),ct.push(oe);return}At[oe]=Ao,is(ge,function(E){if(!k[E])throw new Error("async.auto task `"+oe+"` has a non-existent dependency `"+E+"` in "+ge.join(", "));en(E,function(){Ao--,Ao===0&&Gt(oe,de)})})}),t5(),Ie();function Gt(de,oe){pt.push(function(){Co(de,oe)})}function Ie(){if(pt.length===0&&Z===0)return L(null,j);for(;pt.length&&Z<I;){var de=pt.shift();de()}}function en(de,oe){var ge=lt[de];ge||(ge=lt[de]=[]),ge.push(oe)}function On(de){var oe=lt[de]||[];is(oe,function(ge){ge()}),Ie()}function Co(de,oe){if(!J){var ge=po(function(E,Ir){if(Z--,arguments.length>2&&(Ir=o(arguments,1)),E){var ds={};ls(j,function(_n,Pt){ds[Pt]=_n}),ds[de]=Ir,J=!0,lt=Object.create(null),L(E,ds)}else j[de]=Ir,On(de)});Z++;var Ao=M(oe[oe.length-1]);oe.length>1?Ao(j,ge):Ao(ge)}}function t5(){for(var de,oe=0;ct.length;)de=ct.pop(),oe++,is(e5(de),function(ge){--At[ge]===0&&ct.push(ge)});if(oe!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function e5(de){var oe=[];return ls(k,function(ge,Ao){Ce(ge)&&fl(ge,de,0)>=0&&oe.push(Ao)}),oe}};function ri(k,I){for(var L=-1,F=k==null?0:k.length,U=Array(F);++L<F;)U[L]=I(k[L],L,k);return U}var R3="[object Symbol]";function O3(k){return typeof k=="symbol"||un(k)&&yr(k)==R3}var _3=1/0,od=ft?ft.prototype:void 0,y1=od?od.toString:void 0;function rd(k){if(typeof k=="string")return k;if(Ce(k))return ri(k,rd)+"";if(O3(k))return y1?y1.call(k):"";var I=k+"";return I=="0"&&1/k==-_3?"-0":I}function F3(k,I,L){var F=-1,U=k.length;I<0&&(I=-I>U?0:U+I),L=L>U?U:L,L<0&&(L+=U),U=I>L?0:L-I>>>0,I>>>=0;for(var j=Array(U);++F<U;)j[F]=k[F+I];return j}function P3(k,I,L){var F=k.length;return L=L===void 0?F:L,!I&&L>=F?k:F3(k,I,L)}function id(k,I){for(var L=k.length;L--&&fl(I,k[L],0)>-1;);return L}function N3(k,I){for(var L=-1,F=k.length;++L<F&&fl(I,k[L],0)>-1;);return L}function $3(k){return k.split("")}var H3="\\ud800-\\udfff",j3="\\u0300-\\u036f",U3="\\ufe20-\\ufe2f",se="\\u20d0-\\u20ff",ne=j3+U3+se,z3="\\ufe0e\\ufe0f",V3="\\u200d",W3=RegExp("["+V3+H3+ne+z3+"]");function q3(k){return W3.test(k)}var k1="\\ud800-\\udfff",G3="\\u0300-\\u036f",w1="\\ufe20-\\ufe2f",Z3="\\u20d0-\\u20ff",qe=G3+w1+Z3,sd="\\ufe0e\\ufe0f",ii="["+k1+"]",Vc="["+qe+"]",ml="\\ud83c[\\udffb-\\udfff]",Mn="(?:"+Vc+"|"+ml+")",ld="[^"+k1+"]",cd="(?:\\ud83c[\\udde6-\\uddff]){2}",ad="[\\ud800-\\udbff][\\udc00-\\udfff]",B1="\\u200d",ud=Mn+"?",dd="["+sd+"]?",vn="(?:"+B1+"(?:"+[ld,cd,ad].join("|")+")"+dd+ud+")*",Q3=dd+ud+vn,Rn="(?:"+[ld+Vc+"?",Vc,cd,ad,ii].join("|")+")",Y3=RegExp(ml+"(?="+ml+")|"+Rn+Q3,"g");function E1(k){return k.match(Y3)||[]}function Zo(k){return q3(k)?E1(k):$3(k)}function Wc(k){return k==null?"":rd(k)}var hd=/^\s+|\s+$/g;function ue(k,I,L){if(k=Wc(k),k&&(L||I===void 0))return k.replace(hd,"");if(!k||!(I=rd(I)))return k;var F=Zo(k),U=Zo(I),j=N3(F,U),Z=id(F,U)+1;return P3(F,j,Z).join("")}var Er=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,fd=/,/,J3=/(=.+)?(\s*)$/,md=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function K3(k){return k=k.toString().replace(md,""),k=k.match(Er)[2].replace(" ",""),k=k?k.split(fd):[],k=k.map(function(I){return ue(I.replace(J3,""))}),k}function x1(k,I){var L={};ls(k,function(F,U){var j,Z=_(F),J=!Z&&F.length===1||Z&&F.length===0;if(Ce(F))j=F.slice(0,-1),F=F[F.length-1],L[U]=j.concat(j.length>0?lt:F);else if(J)L[U]=F;else{if(j=K3(F),F.length===0&&!Z&&j.length===0)throw new Error("autoInject task functions require explicit parameters.");Z||j.pop(),L[U]=j.concat(lt)}function lt(pt,ct){var At=ri(j,function(Gt){return pt[Gt]});At.push(ct),M(F).apply(null,At)}}),zc(L,I)}function Yn(){this.head=this.tail=null,this.length=0}function gd(k,I){k.length=1,k.head=k.tail=I}Yn.prototype.removeLink=function(k){return k.prev?k.prev.next=k.next:this.head=k.next,k.next?k.next.prev=k.prev:this.tail=k.prev,k.prev=k.next=null,this.length-=1,k},Yn.prototype.empty=function(){for(;this.head;)this.shift();return this},Yn.prototype.insertAfter=function(k,I){I.prev=k,I.next=k.next,k.next?k.next.prev=I:this.tail=I,k.next=I,this.length+=1},Yn.prototype.insertBefore=function(k,I){I.prev=k.prev,I.next=k,k.prev?k.prev.next=I:this.head=I,k.prev=I,this.length+=1},Yn.prototype.unshift=function(k){this.head?this.insertBefore(this.head,k):gd(this,k)},Yn.prototype.push=function(k){this.tail?this.insertAfter(this.tail,k):gd(this,k)},Yn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},Yn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},Yn.prototype.toArray=function(){for(var k=Array(this.length),I=this.head,L=0;L<this.length;L++)k[L]=I.data,I=I.next;return k},Yn.prototype.remove=function(k){for(var I=this.head;I;){var L=I.next;k(I)&&this.removeLink(I),I=L}return this};function gl(k,I,L){if(I==null)I=1;else if(I===0)throw new Error("Concurrency must not be zero");var F=M(k),U=0,j=[],Z=!1;function J(At,Gt,Ie){if(Ie!=null&&typeof Ie!="function")throw new Error("task callback must be a function");if(ct.started=!0,Ce(At)||(At=[At]),At.length===0&&ct.idle())return A(function(){ct.drain()});for(var en=0,On=At.length;en<On;en++){var Co={data:At[en],callback:Ie||Nt};Gt?ct._tasks.unshift(Co):ct._tasks.push(Co)}Z||(Z=!0,A(function(){Z=!1,ct.process()}))}function lt(At){return function(Gt){U-=1;for(var Ie=0,en=At.length;Ie<en;Ie++){var On=At[Ie],Co=fl(j,On,0);Co===0?j.shift():Co>0&&j.splice(Co,1),On.callback.apply(On,arguments),Gt!=null&&ct.error(Gt,On.data)}U<=ct.concurrency-ct.buffer&&ct.unsaturated(),ct.idle()&&ct.drain(),ct.process()}}var pt=!1,ct={_tasks:new Yn,concurrency:I,payload:L,saturated:Nt,unsaturated:Nt,buffer:I/4,empty:Nt,drain:Nt,error:Nt,started:!1,paused:!1,push:function(At,Gt){J(At,!1,Gt)},kill:function(){ct.drain=Nt,ct._tasks.empty()},unshift:function(At,Gt){J(At,!0,Gt)},remove:function(At){ct._tasks.remove(At)},process:function(){if(!pt){for(pt=!0;!ct.paused&&U<ct.concurrency&&ct._tasks.length;){var At=[],Gt=[],Ie=ct._tasks.length;ct.payload&&(Ie=Math.min(Ie,ct.payload));for(var en=0;en<Ie;en++){var On=ct._tasks.shift();At.push(On),j.push(On),Gt.push(On.data)}U+=1,ct._tasks.length===0&&ct.empty(),U===ct.concurrency&&ct.saturated();var Co=po(lt(At));F(Gt,Co)}pt=!1}},length:function(){return ct._tasks.length},running:function(){return U},workersList:function(){return j},idle:function(){return ct._tasks.length+U===0},pause:function(){ct.paused=!0},resume:function(){ct.paused!==!1&&(ct.paused=!1,A(ct.process))}};return ct}function si(k,I){return gl(k,1,I)}var cs=$e(wr,1);function Qo(k,I,L,F){F=kr(F||Nt);var U=M(L);cs(k,function(j,Z,J){U(I,j,function(lt,pt){I=pt,J(lt)})},function(j){F(j,I)})}function qc(){var k=ri(arguments,M);return function(){var I=o(arguments),L=this,F=I[I.length-1];typeof F=="function"?I.pop():F=Nt,Qo(k,I,function(U,j,Z){j.apply(L,U.concat(function(J){var lt=o(arguments,1);Z(J,lt)}))},function(U,j){F.apply(L,[U].concat(j))})}}var Gc=function(){return qc.apply(null,o(arguments).reverse())},pd=Array.prototype.concat,pl=function(k,I,L,F){F=F||Nt;var U=M(L);Br(k,I,function(j,Z){U(j,function(J){return J?Z(J):Z(null,o(arguments,1))})},function(j,Z){for(var J=[],lt=0;lt<Z.length;lt++)Z[lt]&&(J=pd.apply(J,Z[lt]));return F(j,J)})},I1=$e(pl,1/0),Zc=$e(pl,1),Qc=function(){var k=o(arguments),I=[null].concat(k);return function(){var L=arguments[arguments.length-1];return L.apply(this,I)}};function Cl(k){return k}function li(k,I){return function(L,F,U,j){j=j||Nt;var Z=!1,J;L(F,function(lt,pt,ct){U(lt,function(At,Gt){At?ct(At):k(Gt)&&!J?(Z=!0,J=I(!0,lt),ct(null,ni)):ct()})},function(lt){lt?j(lt):j(null,Z?J:I(!1))})}}function dn(k,I){return I}var as=Go(li(Cl,dn)),Yo=oi(li(Cl,dn)),Al=$e(Yo,1);function Cd(k){return function(I){var L=o(arguments,1);L.push(function(F){var U=o(arguments,1);typeof console=="object"&&(F?console.error&&console.error(F):console[k]&&is(U,function(j){console[k](j)}))}),M(I).apply(null,L)}}var T1=Cd("dir");function D1(k,I,L){L=po(L||Nt);var F=M(k),U=M(I);function j(J){if(J)return L(J);var lt=o(arguments,1);lt.push(Z),U.apply(this,lt)}function Z(J,lt){if(J)return L(J);if(!lt)return L(null);F(j)}Z(null,!0)}function Ad(k,I,L){L=po(L||Nt);var F=M(k),U=function(j){if(j)return L(j);var Z=o(arguments,1);if(I.apply(this,Z))return F(U);L.apply(null,[null].concat(Z))};F(U)}function S1(k,I,L){Ad(k,function(){return!I.apply(this,arguments)},L)}function L1(k,I,L){L=po(L||Nt);var F=M(I),U=M(k);function j(J){if(J)return L(J);U(Z)}function Z(J,lt){if(J)return L(J);if(!lt)return L(null);F(j)}U(Z)}function ci(k){return function(I,L,F){return k(I,F)}}function Yc(k,I,L){qo(k,ci(M(I)),L)}function bl(k,I,L,F){hl(I)(k,ci(M(L)),F)}var ai=$e(bl,1);function Jc(k){return _(k)?k:i(function(I,L){var F=!0;I.push(function(){var U=arguments;F?A(function(){L.apply(null,U)}):L.apply(null,U)}),k.apply(this,I),F=!1})}function Jn(k){return!k}var ui=Go(li(Jn,Jn)),vl=oi(li(Jn,Jn)),Kc=$e(vl,1);function M1(k){return function(I){return I==null?void 0:I[k]}}function us(k,I,L,F){var U=new Array(I.length);k(I,function(j,Z,J){L(j,function(lt,pt){U[Z]=!!pt,J(lt)})},function(j){if(j)return F(j);for(var Z=[],J=0;J<I.length;J++)U[J]&&Z.push(I[J]);F(null,Z)})}function Kn(k,I,L,F){var U=[];k(I,function(j,Z,J){L(j,function(lt,pt){lt?J(lt):(pt&&U.push({index:Z,value:j}),J())})},function(j){j?F(j):F(null,ri(U.sort(function(Z,J){return Z.index-J.index}),M1("value")))})}function Xc(k,I,L,F){var U=rl(I)?us:Kn;U(k,I,M(L),F||Nt)}var ta=Go(Xc),yl=oi(Xc),ea=$e(yl,1);function R1(k,I){var L=po(I||Nt),F=M(Jc(k));function U(j){if(j)return L(j);F(U)}U()}var na=function(k,I,L,F){F=F||Nt;var U=M(L);Br(k,I,function(j,Z){U(j,function(J,lt){return J?Z(J):Z(null,{key:lt,val:j})})},function(j,Z){for(var J={},lt=Object.prototype.hasOwnProperty,pt=0;pt<Z.length;pt++)if(Z[pt]){var ct=Z[pt].key,At=Z[pt].val;lt.call(J,ct)?J[ct].push(At):J[ct]=[At]}return F(j,J)})},di=$e(na,1/0),N=$e(na,1),G=Cd("log");function V(k,I,L,F){F=kr(F||Nt);var U={},j=M(L);wr(k,I,function(Z,J,lt){j(Z,J,function(pt,ct){if(pt)return lt(pt);U[J]=ct,lt()})},function(Z){F(Z,U)})}var ht=$e(V,1/0),Et=$e(V,1);function Vt(k,I){return I in k}function we(k,I){var L=Object.create(null),F=Object.create(null);I=I||Cl;var U=M(k),j=i(function(J,lt){var pt=I.apply(null,J);Vt(L,pt)?A(function(){lt.apply(null,L[pt])}):Vt(F,pt)?F[pt].push(lt):(F[pt]=[lt],U.apply(null,J.concat(function(){var ct=o(arguments);L[pt]=ct;var At=F[pt];delete F[pt];for(var Gt=0,Ie=At.length;Gt<Ie;Gt++)At[Gt].apply(null,ct)})))});return j.memo=L,j.unmemoized=k,j}var qt;a?qt=process.nextTick:l?qt=setImmediate:qt=d;var oa=h(qt);function bd(k,I,L){L=L||Nt;var F=rl(I)?[]:{};k(I,function(U,j,Z){M(U)(function(J,lt){arguments.length>2&&(lt=o(arguments,1)),F[j]=lt,Z(J)})},function(U){L(U,F)})}function yn(k,I){bd(qo,k,I)}function kl(k,I,L){bd(hl(I),k,L)}var vd=function(k,I){var L=M(k);return gl(function(F,U){L(F[0],U)},I,1)},hi=function(k,I){var L=vd(k,I);return L.push=function(F,U,j){if(j==null&&(j=Nt),typeof j!="function")throw new Error("task callback must be a function");if(L.started=!0,Ce(F)||(F=[F]),F.length===0)return A(function(){L.drain()});U=U||0;for(var Z=L._tasks.head;Z&&U>=Z.priority;)Z=Z.next;for(var J=0,lt=F.length;J<lt;J++){var pt={data:F[J],priority:U,callback:j};Z?L._tasks.insertBefore(Z,pt):L._tasks.push(pt)}A(L.process)},delete L.unshift,L};function wl(k,I){if(I=kr(I||Nt),!Ce(k))return I(new TypeError("First argument to race must be an array of functions"));if(!k.length)return I();for(var L=0,F=k.length;L<F;L++)M(k[L])(I)}function fi(k,I,L,F){var U=o(k).reverse();Qo(U,I,L,F)}function Wt(k){var I=M(k);return i(function(F,U){return F.push(function(Z,J){if(Z)U(null,{error:Z});else{var lt;arguments.length<=2?lt=J:lt=o(arguments,1),U(null,{value:lt})}}),I.apply(this,F)})}function O1(k){var I;return Ce(k)?I=ri(k,Wt):(I={},ls(k,function(L,F){I[F]=Wt.call(this,L)})),I}function yd(k,I,L,F){Xc(k,I,function(U,j){L(U,function(Z,J){j(Z,!J)})},F)}var Bl=Go(yd),kd=oi(yd),_1=$e(kd,1);function F1(k){return function(){return k}}function mi(k,I,L){var F=5,U=0,j={times:F,intervalFunc:F1(U)};function Z(ct,At){if(typeof At=="object")ct.times=+At.times||F,ct.intervalFunc=typeof At.interval=="function"?At.interval:F1(+At.interval||U),ct.errorFilter=At.errorFilter;else if(typeof At=="number"||typeof At=="string")ct.times=+At||F;else throw new Error("Invalid arguments for async.retry")}if(arguments.length<3&&typeof k=="function"?(L=I||Nt,I=k):(Z(j,k),L=L||Nt),typeof I!="function")throw new Error("Invalid arguments for async.retry");var J=M(I),lt=1;function pt(){J(function(ct){ct&&lt++<j.times&&(typeof j.errorFilter!="function"||j.errorFilter(ct))?setTimeout(pt,j.intervalFunc(lt)):L.apply(null,arguments)})}pt()}var Jo=function(k,I){I||(I=k,k=null);var L=M(I);return i(function(F,U){function j(Z){L.apply(null,F.concat(Z))}k?mi(k,j,U):mi(j,U)})};function El(k,I){bd(cs,k,I)}var xl=Go(li(Boolean,Cl)),xr=oi(li(Boolean,Cl)),Il=$e(xr,1);function wd(k,I,L){var F=M(I);Uc(k,function(j,Z){F(j,function(J,lt){if(J)return Z(J);Z(null,{value:j,criteria:lt})})},function(j,Z){if(j)return L(j);L(null,ri(Z.sort(U),M1("value")))});function U(j,Z){var J=j.criteria,lt=Z.criteria;return J<lt?-1:J>lt?1:0}}function Tl(k,I,L){var F=M(k);return i(function(U,j){var Z=!1,J;function lt(){var pt=k.name||"anonymous",ct=new Error('Callback function "'+pt+'" timed out.');ct.code="ETIMEDOUT",L&&(ct.info=L),Z=!0,j(ct)}U.push(function(){Z||(j.apply(null,arguments),clearTimeout(J))}),J=setTimeout(lt,I),F.apply(null,U)})}var P1=Math.ceil,Dl=Math.max;function gi(k,I,L,F){for(var U=-1,j=Dl(P1((I-k)/(L||1)),0),Z=Array(j);j--;)Z[F?j:++U]=k,k+=L;return Z}function pi(k,I,L,F){var U=M(L);Br(gi(0,k,1),I,U,F)}var N1=$e(pi,1/0),$1=$e(pi,1);function H1(k,I,L,F){arguments.length<=3&&(F=L,L=I,I=Ce(k)?[]:{}),F=kr(F||Nt);var U=M(L);qo(k,function(j,Z,J){U(I,j,Z,J)},function(j){F(j,I)})}function Sl(k,I){var L=null,F;I=I||Nt,ai(k,function(U,j){M(U)(function(Z,J){arguments.length>2?F=o(arguments,1):F=J,L=Z,j(!Z)})},function(){I(L,F)})}function Ll(k){return function(){return(k.unmemoized||k).apply(null,arguments)}}function Ml(k,I,L){L=po(L||Nt);var F=M(I);if(!k())return L(null);var U=function(j){if(j)return L(j);if(k())return F(U);var Z=o(arguments,1);L.apply(null,[null].concat(Z))};F(U)}function j1(k,I,L){Ml(function(){return!k.apply(this,arguments)},I,L)}var Bd=function(k,I){if(I=kr(I||Nt),!Ce(k))return I(new Error("First argument to waterfall must be an array of functions"));if(!k.length)return I();var L=0;function F(j){var Z=M(k[L++]);j.push(po(U)),Z.apply(null,j)}function U(j){if(j||L===k.length)return I.apply(null,arguments);F(o(arguments,1))}F([])},X3={apply:r,applyEach:Xu,applyEachSeries:ed,asyncify:v,auto:zc,autoInject:x1,cargo:si,compose:Gc,concat:I1,concatLimit:pl,concatSeries:Zc,constant:Qc,detect:as,detectLimit:Yo,detectSeries:Al,dir:T1,doDuring:D1,doUntil:S1,doWhilst:Ad,during:L1,each:Yc,eachLimit:bl,eachOf:qo,eachOfLimit:wr,eachOfSeries:cs,eachSeries:ai,ensureAsync:Jc,every:ui,everyLimit:vl,everySeries:Kc,filter:ta,filterLimit:yl,filterSeries:ea,forever:R1,groupBy:di,groupByLimit:na,groupBySeries:N,log:G,map:Uc,mapLimit:Br,mapSeries:td,mapValues:ht,mapValuesLimit:V,mapValuesSeries:Et,memoize:we,nextTick:oa,parallel:yn,parallelLimit:kl,priorityQueue:hi,queue:vd,race:wl,reduce:Qo,reduceRight:fi,reflect:Wt,reflectAll:O1,reject:Bl,rejectLimit:kd,rejectSeries:_1,retry:mi,retryable:Jo,seq:qc,series:El,setImmediate:A,some:xl,someLimit:xr,someSeries:Il,sortBy:wd,timeout:Tl,times:N1,timesLimit:pi,timesSeries:$1,transform:H1,tryEach:Sl,unmemoize:Ll,until:j1,waterfall:Bd,whilst:Ml,all:ui,allLimit:vl,allSeries:Kc,any:xl,anyLimit:xr,anySeries:Il,find:as,findLimit:Yo,findSeries:Al,forEach:Yc,forEachSeries:ai,forEachLimit:bl,forEachOf:qo,forEachOfSeries:cs,forEachOfLimit:wr,inject:Qo,foldl:Qo,foldr:fi,select:ta,selectLimit:yl,selectSeries:ea,wrapSync:v};e.default=X3,e.apply=r,e.applyEach=Xu,e.applyEachSeries=ed,e.asyncify=v,e.auto=zc,e.autoInject=x1,e.cargo=si,e.compose=Gc,e.concat=I1,e.concatLimit=pl,e.concatSeries=Zc,e.constant=Qc,e.detect=as,e.detectLimit=Yo,e.detectSeries=Al,e.dir=T1,e.doDuring=D1,e.doUntil=S1,e.doWhilst=Ad,e.during=L1,e.each=Yc,e.eachLimit=bl,e.eachOf=qo,e.eachOfLimit=wr,e.eachOfSeries=cs,e.eachSeries=ai,e.ensureAsync=Jc,e.every=ui,e.everyLimit=vl,e.everySeries=Kc,e.filter=ta,e.filterLimit=yl,e.filterSeries=ea,e.forever=R1,e.groupBy=di,e.groupByLimit=na,e.groupBySeries=N,e.log=G,e.map=Uc,e.mapLimit=Br,e.mapSeries=td,e.mapValues=ht,e.mapValuesLimit=V,e.mapValuesSeries=Et,e.memoize=we,e.nextTick=oa,e.parallel=yn,e.parallelLimit=kl,e.priorityQueue=hi,e.queue=vd,e.race=wl,e.reduce=Qo,e.reduceRight=fi,e.reflect=Wt,e.reflectAll=O1,e.reject=Bl,e.rejectLimit=kd,e.rejectSeries=_1,e.retry=mi,e.retryable=Jo,e.seq=qc,e.series=El,e.setImmediate=A,e.some=xl,e.someLimit=xr,e.someSeries=Il,e.sortBy=wd,e.timeout=Tl,e.times=N1,e.timesLimit=pi,e.timesSeries=$1,e.transform=H1,e.tryEach=Sl,e.unmemoize=Ll,e.until=j1,e.waterfall=Bd,e.whilst=Ml,e.all=ui,e.allLimit=vl,e.allSeries=Kc,e.any=xl,e.anyLimit=xr,e.anySeries=Il,e.find=as,e.findLimit=Yo,e.findSeries=Al,e.forEach=Yc,e.forEachSeries=ai,e.forEachLimit=bl,e.forEachOf=qo,e.forEachOfSeries=cs,e.forEachOfLimit=wr,e.inject=Qo,e.foldl=Qo,e.foldr=fi,e.select=ta,e.selectLimit=yl,e.selectSeries=ea,e.wrapSync=v,Object.defineProperty(e,"__esModule",{value:!0})})})(ap,ap.exports);var Tb={exports:{}},up=Tb.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 a=parseInt(i,t);return a!==1/0&&a>=Math.pow(2,n)?up(n,t):i};up.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=up(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 Db=$i,mS=xb,gS=Ib,jh=Fo,dp=ap.exports,pS=Tb.exports,Sb=Us.ACTIONS,Lb=Me;function Me(n,t){if(Db.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}Db.mixin(Me),Me.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Me.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Me.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||pS();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Me.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);dp.parallel([function(i){dp.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();dp.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)})})},Me.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?Sb.presenceSubscribe:Sb.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,o,this)},Me.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Me.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Me.prototype._receiveUpdate=function(n,t){var e=jh.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=jh.digOrCreate(this._remotePresenceInstances,t.id,function(){return o._createRemotePresence(t.id)});r.receiveUpdate(t)},Me.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Me.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()}},Me.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Me.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Me.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)})},Me.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Me.prototype._callbackOrEmit=function(n,t){if(t)return jh.nextTick(t,n);n&&this.emit("error",n)},Me.prototype._createLocalPresence=function(n){return new mS(this,n)},Me.prototype._createRemotePresence=function(n){return new gS(this,n)},Me.prototype._callEachOrEmit=function(n,t){var e=jh.callEach(n,t);!e&&t&&this.emit("error",t)};var Wa=xb,Mb=Fh,CS=Fo,Rb=Mb.CODES,AS=No;function No(n,t){Wa.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()}No.prototype=Object.create(Wa.prototype),No.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:Rb.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,Wa.prototype.submit.call(this,n,t)},No.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),Wa.prototype.destroy.call(this,n)},No.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={})})}},No.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)},No.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)}},No.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},No.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},No.prototype._message=function(){var n=Wa.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},No.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!CS.supportsPresence(o))throw new Mb(Rb.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var Ob={};(function(n){var t=Ua,e=Fh,o=Fo,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 a=l.create.type;if(typeof a!="string")return new e(r.ERR_OT_OP_BADLY_FORMED,"Missing create type");var d=t.map[a];if(d==null||typeof d!="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,a){if(typeof l!="object")return new e(r.ERR_APPLY_SNAPSHOT_NOT_PROVIDED,"Missing snapshot");if(l.v!=null&&a.v!=null&&l.v!==a.v)return new e(r.ERR_APPLY_OP_VERSION_DOES_NOT_MATCH_SNAPSHOT,"Version mismatch");if(a.create){if(l.type)return new e(r.ERR_DOC_ALREADY_CREATED,"Document already exists");var d=a.create,h=t.map[d.type];if(!h)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=h.create(d.data),l.type=h.uri,l.v++}catch(A){return A}}else if(a.del)l.data=void 0,l.type=null,l.v++;else if("op"in a){var p=i(l,a.op);if(p)return p;l.v++}else l.v++};function i(l,a){if(!l.type)return new e(r.ERR_DOC_DOES_NOT_EXIST,"Document does not exist");if(a===void 0)return new e(r.ERR_OT_OP_NOT_PROVIDED,"Missing op");var d=t.map[l.type];if(!d)return new e(r.ERR_DOC_TYPE_NOT_RECOGNIZED,"Unknown type");try{l.data=d.apply(l.data,a)}catch(h){return new e(r.ERR_OT_OP_NOT_APPLIED,h.message)}}n.transform=function(l,a,d){if(a.v!=null&&a.v!==d.v)return new e(r.ERR_OP_VERSION_MISMATCH_DURING_TRANSFORM,"Version mismatch");if(d.del){if(a.create||"op"in a)return new e(r.ERR_DOC_WAS_DELETED,"Document was deleted")}else{if(d.create&&("op"in a||a.create||a.del)||"op"in d&&a.create)return new e(r.ERR_DOC_ALREADY_CREATED,"Document was created remotely");if("op"in d&&"op"in a){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{a.op=l.transform(a.op,d.op,"left")}catch(h){return h}}}a.v!=null&&a.v++},n.applyOps=function(l,a,d){d=d||{};for(var h=0;h<a.length;h++){var p=a[h];if(d._normalizeLegacyJson0Ops)try{s(l,p)}catch{return new e(r.ERR_OT_LEGACY_JSON0_OP_CANNOT_BE_NORMALIZED,"Cannot normalize legacy json0 op")}l.v=p.v;var A=n.apply(l,p);if(A)return A}},n.transformPresence=function(l,a,d){var h=this.checkOp(a);if(h)return h;var p=l.t;if(typeof p=="string"&&(p=t.map[p]),!p)return{code:r.ERR_DOC_TYPE_NOT_RECOGNIZED,message:"Unknown type"};if(!o.supportsPresence(p))return{code:r.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,message:"Type does not support presence"};if(a.create||a.del){l.p=null,l.v++;return}try{l.p=l.p===null?null:p.transformPresence(l.p,a.op,d)}catch(A){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:A.message||A}}l.v++};function s(l,a){if(l.type===t.defaultType.uri){var d=a.op;if(!!d){var h=l.data;d.length>1&&(h=o.clone(h));for(var p=0;p<d.length;p++){var A=d[p];typeof A.lm=="string"&&(A.lm=+A.lm);for(var v=A.p,B=h,D=0;D<v.length;D++){var T=v[D];Object.prototype.toString.call(B)=="[object Array]"?v[D]=+T:B.constructor===Object&&(v[D]=T.toString()),B=B[T]}p<d.length-1&&(h=t.defaultType.apply(h,[A]))}}}}})(Ob);var qa=Ib,bS=Ob,vS=co;function co(n,t){qa.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()}co.prototype=Object.create(qa.prototype),co.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},co.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),qa.prototype.destroy.call(this,n)},co.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)},co.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))}})}},co.prototype._handleOp=function(n,t,e){var o=e===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},qa.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},qa.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},co.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)}},co.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++):bS.transformPresence(this._pending,t,e)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},co.prototype._startCachingOps=function(){this._opCache=[]},co.prototype._stopCachingOps=function(){this._opCache=null},co.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var _b=Lb,yS=AS,kS=vS;function tc(n,t,e){var o=tc.channel(t,e);_b.call(this,n,o),this.collection=t,this.id=e}var wS=tc;tc.prototype=Object.create(_b.prototype),tc.channel=function(n,t){return n+"."+t},tc.prototype._createLocalPresence=function(n){return new yS(this,n)},tc.prototype._createRemotePresence=function(n){return new kS(this,n)};var BS=ES;function ES(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var xS=BS,Fb=$i,Pb=Ga;function Ga(n,t,e,o,r){if(Fb.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}Fb.mixin(Ga),Ga.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},Ga.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},Ga.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new xS(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var Nb=Pb,IS=Fo,TS=Us.ACTIONS,DS=hp;function hp(n,t,e,o,r,i){if(Nb.call(this,n,t,e,o,i),!IS.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}hp.prototype=Object.create(Nb.prototype),hp.prototype._message=function(){return{a:TS.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var $b=Pb,SS=Fo,LS=Us.ACTIONS,MS=fp;function fp(n,t,e,o,r,i){if($b.call(this,n,t,e,o,i),!SS.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}fp.prototype=Object.create($b.prototype),fp.prototype._message=function(){return{a:LS.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var RS=iS,OS=uS,_S=Lb,Hb=wS,FS=DS,PS=MS,jb=$i,ec=Fh,te=Us.ACTIONS,Ub=Ua,$o=Fo,Za=Cb,Qa=ec.CODES;function zb(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var NS=wt;function wt(n){jb.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=zb(n),this.bindToSocket(n)}jb.mixin(wt),wt.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=zb(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{Za.warn("Failed to parse message",o);return}e.debug&&Za.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){$o.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)}},wt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=Vb(n.error,n),delete n.error),n.a){case te.initLegacy:return this._handleLegacyInit(n);case te.handshake:return this._handleHandshake(t,n);case te.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case te.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case te.queryUnsubscribe:return;case te.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 te.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case te.bulkSubscribe:case te.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case te.snapshotFetch:case te.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case te.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case te.subscribe:case te.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case te.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case te.presence:return this._handlePresence(t,n);case te.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case te.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case te.presenceRequest:return this._handlePresenceRequest(t,n);case te.pingPong:return this._handlePingPong(t);default:Za.warn("Ignoring unrecognized message",n)}};function Vb(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}wt.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](Vb(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 Za.error("Invalid bulk message",t)},wt.prototype._reset=function(){this.agent=null},wt.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 ec(Qa.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 a=this._snapshotRequests[o];a._onConnectionStateChanged()}this.endBulk(),this.emit(n,t),this.emit("state",n,t)}},wt.prototype.startBulk=function(){this.bulk||(this.bulk={})},wt.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},wt.prototype._sendBulk=function(n,t,e){if(!!e){var o=[],r={},i=0,s;for(var l in e){var a=e[l];a==null?o.push(l):(r[l]=a,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 d=r[s];this.send({a:n,c:t,d:s,v:d})}else i&&this.send({a:"b"+n,c:t,b:r})}},wt.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)}},wt.prototype.sendFetch=function(n){return this._sendActions(te.fetch,n,n.version)},wt.prototype.sendSubscribe=function(n){return this._sendActions(te.subscribe,n,n.version)},wt.prototype.sendUnsubscribe=function(n){return this._sendActions(te.unsubscribe,n)},wt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:te.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)},wt.prototype.send=function(n){this.debug&&Za.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},wt.prototype.ping=function(){if(!this.canSend)throw new ec(Qa.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:te.pingPong};this.send(n)},wt.prototype.close=function(){this.socket.close()},wt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},wt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new RS(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},wt.prototype._destroyDoc=function(n){!n._wantsDestroy||($o.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},wt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},wt.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new OS(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},wt.prototype._destroyQuery=function(n){delete this.queries[n.id]},wt.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(te.queryFetch,n,t,e,o)},wt.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(te.querySubscribe,n,t,e,o)},wt.prototype.hasPending=function(){return!!(this._firstDoc(Uh)||this._firstQuery(Uh)||this._firstSnapshotRequest())};function Uh(n){return n.hasPending()}wt.prototype.hasWritePending=function(){return!!this._firstDoc($S)};function $S(n){return n.hasWritePending()}wt.prototype.whenNothingPending=function(n){var t=this._firstDoc(Uh);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(Uh);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}$o.nextTick(n)},wt.prototype._nothingPendingRetry=function(n){var t=this;return function(){$o.nextTick(function(){t.whenNothingPending(n)})}},wt.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}}},wt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},wt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},wt.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new FS(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},wt.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new PS(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},wt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},wt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},wt.prototype._initializeHandshake=function(){this.send({a:te.handshake,id:this.id})},wt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},wt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},wt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new ec(Qa.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(Ub.map[n.type]!==Ub.defaultType)return this.emit("error",new ec(Qa.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new ec(Qa.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},wt.prototype.getPresence=function(n){var t=this,e=$o.digOrCreate(this._presences,n,function(){return new _S(t,n)});return e._wantsDestroy=!1,e},wt.prototype.getDocPresence=function(n,t){var e=Hb.channel(n,t),o=this,r=$o.digOrCreate(this._presences,e,function(){return new Hb(o,n,t)});return r._wantsDestroy=!1,r},wt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},wt.prototype._addPresence=function(n){$o.digOrCreate(this._presences,n.channel,function(){return n})},wt.prototype._handlePresenceSubscribe=function(n,t){var e=$o.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},wt.prototype._handlePresenceUnsubscribe=function(n,t){var e=$o.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},wt.prototype._handlePresence=function(n,t){var e=$o.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},wt.prototype._handlePresenceRequest=function(n,t){var e=$o.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var Wb=NS,HS=Ua;const zh={err:1001,msg:"user auth error",name:"AuthError"},jS={err:1002,msg:"you don't have required permission",name:"PermissionError"},mp={err:1003,msg:"Too many user connected",name:"MaxUserError"},Ya={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},US={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},zS={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},Ja="x-live-editor-token",Vh="x-live-editor-base-url",gn=S("auth-connection");function VS(n){try{n()}catch(t){gn.error(t)}}class WS{constructor(t,e){m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new q5.EventEmitter);m(this,"token",null);m(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 Bs(this.getBaseURL())}async auth(t){g(gn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[Ja]:t.token,[Vh]: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:{[Vh]:Bs(this.getBaseURL())}})}async init(t){const e=await this.auth(t);this.resourceToken=e.read,this.ws=new HB.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(Wb.prototype),g(gn,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}}},Wb.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,gn.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){gn.error(t),setTimeout(()=>this.handleAuthError(),0)}}else gn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(zh.msg);t.code=zh.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(Ya.msg);t.code=Ya.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===zh.err)gn.warn("auth error"),this.handleAuthError();else if(o===mp.err)gn.warn(mp.msg),this.emitMaxUsersError();else if(o===Ya.err){gn.warn(Ya.msg);try{this.emitRequestReloadError()}catch(r){gn.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else gn.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError()}get(t,e){return g(gn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(g(gn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){g(gn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){g(gn,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(),VS(()=>{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()}}S("utils/file");function qS(){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}qS();async function GS(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new jB.Hash;for(let s=0;s<o;s++){const l=s*102400;let a=l+102400;a>e&&(a=e);const h=await n.slice(l,a,n.type).arrayBuffer();r.update(new Uint8Array(h))}const i=r.digest();return Bs(i)}const ur=S("sharedb-doc/client");class ZS{constructor(t,e,o){m(this,"connection");m(this,"auth");m(this,"doc",null);m(this,"reauthFunc");m(this,"clientId",K());m(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});g(ur,!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),ur.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;HS.register(_d.type),this.connection=new WS(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return g(ur,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 a=l.split("|");r.push(...a)}),r=Array.from(new Set(r));const i=r.map(l=>this.getFileUrlByHash(o,l,"",0,{[Ja]: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=v=>{ur.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await GS(e),d=await this.getFileUrlByHash(t,a,e.name,e.size,o);if(d)return r(-1),d;let h=t;i!=null&&i.thumbnail&&(h+="/thumbnail");const p=new FormData;p.append("file-size",`${e.size}`),p.append("file-hash",a),p.append("file",e,e.name);const A=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return ur.info(A),r(100),Array.isArray(A.data)?A.data[0]:A.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;g(ur,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[Ja]:this.connection.token},e,o);return g(ur,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 a=e||{};a.url=t,a.headers||(a.headers={}),g(ur,o,"no token"),a.headers={...a.headers,[Ja]:o,[Vh]:this.connection.getBase64BaseURL()};try{return await NB.default(t,a)}catch(d){if(r=d,((i=d==null?void 0:d.response)==null?void 0:i.status)===403&&this.reauthFunc){const h=await this.reauthFunc();if(await this.connection.auth(h),!h.token)throw d;o=h.token;continue}throw(s=d.response)!=null&&s.data&&(d.responseData=d.response.data),d}}throw g(ur,r,"no error"),r}async getVersions(){const e=`${this.apiServer()}/versions?withExtra=true`,r=(await this.request(e)).data.versions;return r.forEach(i=>{i.extra&&(i.extra=JSON.parse(i.extra))}),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=$B.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(g(ur,a.create,"no createDoc.create"),d=a.create.data):d=JSON.parse(i.data.data),d.blocks||(d.blocks=[]),{doc:d,ops:i.data.ops}}async updateVersionExtra(t,e,o){const i=`${this.apiServer()}/versions/${t}/tags/${e}`;await this.request(i,{method:"post",data:{extra:JSON.stringify(o)}})}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/${Bs(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 QS(){return{blocks:[{id:K(),type:"text",text:[]}],comments:{},meta:{}}}const gp=S("block-ids");class YS{constructor(){m(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);g(gp,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=K();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);g(gp,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=K(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class JS{constructor(){m(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new YS,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 g(gp,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class qb{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 Wh=S("op-parse-handler");class KS{constructor(t,e){m(this,"actions",[]);this.outerHandler=t,this.local=e}pushActions(t){if(!t.containerId){this.actions.push(t);return}const o={...t,containerId:(r=>r==="blocks"?"root":r)(t.containerId)};this.actions.push(o)}onDeleteBlock(t,e){this.pushActions({type:"deleteBlock",containerId:t,blockIndex:e})}onInsertBlock(t,e,o){this.pushActions({type:"insertBlock",containerId:t,blockIndex:e,data:o})}onDeleteBlockData(t,e,o){this.pushActions({type:"deleteBlockData",containerId:t,blockIndex:e,key:o})}onInsertBlockData(t,e,o,r){this.pushActions({type:"insertBlockData",containerId:t,blockIndex:e,key:o,value:r})}onUpdateBlockText(t,e,o){this.pushActions({type:"updateBlockText",containerId:t,blockIndex:e,richTextData:o})}onDeleteContainer(t){this.pushActions({type:"deleteContainer",containerId:t})}onCreateContainer(t,e){this.pushActions({type:"createContainer",containerId:t,data:e})}onDeleteComment(t){this.pushActions({type:"deleteComment",commentId:t})}onCreateComment(t){this.pushActions({type:"createComment",commentId:t})}onUpdateComment(t){this.pushActions({type:"updateComment",commentId:t})}end(){const t=this.actions,e=new Set,o=new Map,r=new JS,i=t.filter(s=>s.type==="deleteBlock"||s.type==="deleteBlockData");for(const s of i)if(s.type==="deleteBlock"){const l=s,a=r.getBlockId(l.containerId,l.blockIndex);r.onDeleteBlock(l.containerId,l.blockIndex);const d=o.get(a);d&&(Wh.debug(`ignore update object data before delete block: ${JSON.stringify(d)}`),o.delete(a));const h=`${l.containerId}-${l.blockIndex}`;e.add(h),this.outerHandler.onDeleteBlock(l.containerId,l.blockIndex,this.local)}else if(s.type==="deleteBlockData"){const l=s,a=`${l.containerId}-${l.blockIndex}`;if(e.has(a)){Wh.warn("delete block data after delete block, ignore it");continue}const d=r.getBlockId(l.containerId,l.blockIndex);let h=o.get(d);h||(h=new qb,o.set(d,h)),h.delete(l.key)}else g(Wh,!1,`invalid action type, ${s.type}`);this.actions.forEach(s=>{if(s.type==="deleteContainer"){const l=s;this.outerHandler.onDeleteContainer(l.containerId,this.local)}else if(s.type==="deleteComment"){const l=s;this.outerHandler.onDeleteComment(l.commentId,this.local)}}),this.actions.forEach(s=>{if(s.type==="createContainer"){const l=s;this.outerHandler.onCreateContainer(l.containerId,l.data,this.local)}}),this.actions.forEach(s=>{if(s.type==="insertBlock"){const l=s;this.outerHandler.onInsertBlock(l.containerId,l.blockIndex,l.data,this.local)}else if(s.type==="insertBlockData"){const l=s,a=r.getBlockId(l.containerId,l.blockIndex);let d=o.get(a);d||(d=new qb,o.set(a,d)),d.insert(l.key,l.value)}else if(s.type==="updateBlockText"){const l=s;this.outerHandler.onUpdateBlockText(l.containerId,l.blockIndex,l.richTextData,this.local)}else if(s.type==="createComment"){const l=s;this.outerHandler.onCreateComment(l.commentId,this.local)}else if(s.type==="updateComment"){const l=s;this.outerHandler.onUpdateComment(l.commentId,this.local)}}),Array.from(o.entries()).forEach(([s,l])=>{const{containerId:a,blockIndex:d}=r.getBlockIndexById(s);Wh.debug(`update block data: ${a}, ${d}, ${JSON.stringify(l.toDocBlockDelta())}`),this.outerHandler.onUpdateBlockData(a,d,l.toDocBlockDelta(),this.local)})}}const Re=S("op-parser");class Gb{}class pp{constructor(t){m(this,"key");this.key=t}}function XS(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 a=o[l];if(!Array.isArray(a)||a.length!==2||typeof a[0]!="string")return!1;const h=a[1];if(typeof h!="object"||h.i===void 0||Object.keys(h).length!==1)return!1}const s=i.i;g(Re,s.id,"block id is required"),g(Re,s.type,"block type is required");for(let l=1;l<o.length;l++){const a=o[l],d=a[0],h=a[1];s[d]=h.i}return e.onInsertBlock(n,r,s),!0}function Cp(n,t,e,o){if(e==="upsert"&&XS(n,t,o))return;g(Re,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 a=r[1];if(g(Re,typeof a=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),g(Re,a.et==="rich-text",`invalid block op: ${n}, ${JSON.stringify(t)}`),r.splice(0,2),e==="upsert"){const h=a.e;o.onUpdateBlockText(n,i,h)}g(Re,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){g(Re,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const a=l[0];g(Re,typeof a=="string",`invalid block op: key ${JSON.stringify(a)}`);const d=l[1];if(a==="text"){if(g(Re,typeof d=="object",`invalid opData type, ${JSON.stringify(d)}`),d.i&&e==="upsert"&&o.onInsertBlockData(n,i,a,d.i),d.r&&e==="remove"&&o.onDeleteBlockData(n,i,a),d.et==="rich-text"&&e==="upsert"){const p=d.e;o.onUpdateBlockText(n,i,p)}}else e==="remove"&&d.r&&s.push(new pp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i);r.shift()}else if(typeof l=="object"){const a=l;e==="remove"&&a.r&&s.push(new Gb),e==="upsert"&&a.i&&o.onInsertBlock(n,i,a.i),r.shift()}else{g(Re,typeof l=="string","data is not string"),g(Re,l!=="text","data !== 'text'"),g(Re,r.length===2,`invalid block op: ops.length !== 2, ${JSON.stringify(r)}`);const a=l,d=r[1];e==="remove"&&d.r&&s.push(new pp(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof Gb?o.onDeleteBlock(n,i):l instanceof pp?o.onDeleteBlockData(n,i,l.key):g(Re,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function tL(n,t,e){Re.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function eL(n,t,e){const o=n[1],r=n[2];g(Re,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),g(Re,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?Re.error(`unknown comment op, ${JSON.stringify(n)}`):r.i&&r.r?t==="upsert"&&e.onUpdateComment(o):r.i?t==="upsert"&&e.onCreateComment(o):r.r?t==="remove"&&e.onDeleteComment(o):Re.error(`unknown comment op, ${JSON.stringify(n)}`)}function Ap(n,t,e){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{Ap(s,t,e)});return}const r=o;if(g(Re,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){tL(n);return}if(r==="comments"){eL(n,t,e);return}const i=r;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{Cp(i,s,t,e)}):n.slice(1).forEach(s=>{Cp(i,s,t,e)});else if(typeof n[1]=="object"){const s=n[1];s.r&&t==="remove"&&e.onDeleteContainer(i),s.i&&t==="upsert"&&e.onCreateContainer(i,s.i)}else g(Re,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),Cp(i,n.slice(1),t,e)}function Zb(n,t,e){const o=new KS(t,e);for(let r=0;r<2;r++){const i=r===0?"remove":"upsert",s=mt.default(n),l=s[0];Array.isArray(l)?s.forEach(a=>{Ap(a,i,o)}):Ap(s,i,o)}o.end()}const nL=S("sharedb-comments");function bp(n){const t=n.blocks;g(nL,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)}),mt.default(e)}function Qb(n){const{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}=n;return{id:t,groupId:e,userId:o,displayName:r,avatarUrl:i,abstract:s,created:l,modified:a}}function vp(n,t){const e=HD(t),{comments:o,meta:r,blocks:i,...s}=e,l={...n,blocks:i,...s},a=mt.default(l);return delete a.children,a}const ae=S("sharedb-doc/doc-container"),Yb="ot-json1";_d.type.registerSubtype(jD.type),_d.type.name=Yb,_d.type.invert=null;class Ka extends fa{constructor(e,o,r=!0){super();m(this,"doc");m(this,"client");m(this,"localPresence");m(this,"remoteCaretHandler",new ND);m(this,"batching",0);m(this,"status","clean");m(this,"disableLogout");m(this,"destroyed",!1);m(this,"handleNothingPending",()=>{this.setStatus("clean")});m(this,"handleCreate",()=>{this.handleReload("doc created")});m(this,"handleDel",()=>{});m(this,"handleReload",e=>{this.callbacks.forEach(o=>{var r;return(r=o.onRequestReload)==null?void 0:r.call(o,e)})});m(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()});m(this,"handleWriteConflictError",e=>{this.handleReset(`write conflict: ${e.message}, ${JSON.stringify(e.orgMsg)}`)});m(this,"insertObject",async(e,o,r)=>{const i=[e,o,{i:r}];return this.submitOp(i)});m(this,"deleteObject",async(e,o)=>{const r=[e,o,{r:!0}];return this.submitOp(r)});m(this,"replaceObject",async(e,o,r)=>{const i=[e,o,{r:!0,i:r}];return this.submitOp(i)});m(this,"updateObject",async(e,o,r)=>{const i=this.data()[e][o],s=[e,o];return Object.entries(r).forEach(([l,a])=>{if(!ua.default(i[l],a))if(i[l]===void 0){if(a!=null){const d={i:a};s.push([l,d])}}else if(a==null){const d={r:!0};s.push([l,d])}else{const d={r:!0,i:a};s.push([l,d])}}),Object.entries(i).forEach(([l,a])=>{if((r[l]===void 0||r[l]===null)&&a!==void 0){const d={r:!0};s.push([l,d])}}),s.length<=2?Promise.resolve():this.submitOp(s)});m(this,"broadcastMessage",async e=>{const o={type:"custom",data:e,clientId:this.client.clientId};this.localPresence&&this.localPresence.submit(o)});m(this,"data",()=>this.doc.data);m(this,"submitOp",async e=>new Promise((o,r)=>{if(this.destroyed){ae.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(ae.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),ae.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(ae.error("no data after submit op, may be the submitted op is invalid"),this.handleReset(`invalid op, ${JSON.stringify(e)}`))}));m(this,"createDoc",async e=>new Promise((o,r)=>{this.doc.create(e,Yb,i=>{i?r(i):o()})}));m(this,"submitInsertChildContainer",async(e,o)=>{const r=[Ni(e),{i:o}];return this.submitOp(r)});m(this,"submitDeleteChildContainer",async e=>{const o=[Ni(e),{r:!0}];return this.submitOp(o)});m(this,"submitInsertBlock",async(e,o,r)=>{const i=[Ni(e),o,{i:r}];return this.submitOp(i)});m(this,"submitDeleteBlock",async(e,o)=>{const r=[Ni(e),o,{r:!0}];return this.submitOp(r)});m(this,"submitUpdateBlockData",async(e,o,r)=>{if(r.delete.length===0&&Object.keys(r.insert).length===0)return Promise.resolve();const i=[Ni(e),o],s=new Set(r.delete);Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a)){const h={r:!0,i:d};i.push([a,h])}});const l=new Set(Object.keys(r.insert));return r.delete.forEach(a=>{if(l.has(a))return;const d={r:!0};i.push([a,d])}),Object.entries(r.insert).forEach(([a,d])=>{if(s.has(a))return;const h={i:d};i.push([a,h])}),this.submitOp(i)});m(this,"submitUpdateRichText",async(e,o,r)=>{const i=[Ni(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});m(this,"handleOp",(e,o,r)=>{if(this.destroyed){ae.warn("handleOp: destroyed");return}Zb(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--,g(ae,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new ZS(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new Ka(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||QS())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw ae.error(o),ae.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(K()),e())})}})}subscribe(){return new Promise((e,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return ja(this.data())}getContainerBlocks(e){const o=this.data();g(ae,o,"no doc data");const r=o[Ni(e)];return g(ae,r,`no container data: ${e}`),mt.default(r)}getBlockData(e,o){const r=this.data();g(ae,r,"no doc data");const i=r[Ni(e)];g(ae,i,`no container data: ${e}`);const s=i[o];return g(ae,s,`no block data: ${o}`),mt.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);g(ae,i.text,"no block text");const s=mt.default(i.text);this.submitUpdateRichText(e,o,r);const l=ln.apply(s,r);return g(ae,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=mt.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=>Qb(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return bp(o)}localCreateComment(e,o){const r=vp(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=vp(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){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,Xl(e),o,r)})}onInsertBlock(e,o,r,i){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,Xl(e),o,r,i)})}onUpdateBlockData(e,o,r,i){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,Xl(e),o,r,i)})}onUpdateBlockText(e,o,r,i){g(ae,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,Xl(e),o,r,i)})}onDeleteContainer(e,o){g(ae,this.callbacks.length>0,"no callbacks"),g(ae,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,Xl(e),o)})}onCreateContainer(e,o,r){g(ae,this.callbacks.length>0,"no callbacks"),g(ae,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,Xl(e),o,r)})}onDeleteComment(e,o){g(ae,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){g(ae,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){g(ae,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 ja(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return ja(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:ja(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:ja(r),versionData:i}}async updateVersionExtra(e,o,r){await this.client.updateVersionExtra(e,o,r)}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){Zb(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}S("remote-cursor");class Jb{constructor(t){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",He.default(()=>{const t={type:"caret",userId:this.editor.doc.getUser().userId,range:this.editor.selection.range.toDocRange()};this.editor.doc.broadcastMessage(t)},300));m(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 Kb=S("remote-cursor-decorator");class yp{decorateText(t,e,o){const r=t.doc.getRemoteUsers();if(!r)return{};const i=new Map,{containerId:s,blockIndex:l}=e[e.length-1];g(Kb,typeof s=="string","invalid path containerId"),g(Kb,typeof l=="number","invalid path blockIndex");const a=t.doc.getBlockData(s,l),d=rn(o);return r.getSimpleCursors(a.id).forEach((p,A)=>{A>d&&(A=d);const v=p.map(D=>({id:K(),type:"remote-cursor",name:D.user.displayName,time:D.time,rainbowIndex:D.user.rainbowIndex})),B=i.get(A);B?B.push(...v):i.set(A,v)}),{insertions:i}}}class Xb extends be.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Xt(Nr(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=ot(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 oL(n,t){n.addCustom("child-block-tracker",()=>new Xb(n)).addListener("change",t)}function rL(n,t){n.addCustom("child-block-tracker",()=>new Xb(n)).removeListener("change",t)}const snt="",iL={colorPalette:{colorDesc:"\u5B57\u4F53\u989C\u8272",name:"\u6587\u672C\u989C\u8272",backgroundDesc:"\u80CC\u666F\u989C\u8272",reset:"\u6062\u590D\u9ED8\u8BA4"},search:{emptyTips:"\u6682\u65E0\u641C\u7D22\u7ED3\u679C"}},sL={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},lL={colorPalette:{colorDesc:"\u30D5\u30A9\u30F3\u30C8\u306E\u8272",name:"\u30C6\u30AD\u30B9\u30C8\u306E\u8272",backgroundDesc:"\u80CC\u666F\u8272",reset:"\u30C7\u30D5\u30A9\u30EB\u30C8\u306B\u623B\u3059"},search:{emptyTips:"\u691C\u7D22\u7D50\u679C\u304C\u3042\u308A\u307E\u305B\u3093"}};R.mergeLang({"zh-CN":iL,"en-US":sL,"js-JP":lL});const lnt="";S("button");function ji(n,t,e,o,r){const i=w("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&&W(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0)),i}function tv(n,t,e){e?n.setAttribute(`data-editor-tooltip-${e}`,t):n.innerText=t}const cnt="",nc=S("ui-command-bar-base"),cL={itemElementTag:"div",tippyArrow:!1},K2=class extends be.TypedEmitter{constructor(e,o,r){var i,s;super();m(this,"content");m(this,"items");m(this,"subBar",null);m(this,"parentItem",null);m(this,"closeable",null);m(this,"closeReason",null);m(this,"options");m(this,"id");m(this,"header",null);m(this,"footer",null);m(this,"handleDocumentKeydown",e=>{if(console.log(e,"handleDocumentKeydown"),console.log(this,"handleDocumentKeydown"),!!this.isVisible&&!e.isComposing&&!Ls(e.target)){if(this.subBar){this.subBar.handleDocumentKeydown(e);return}if(this.items.length!==0){if(e.key==="Escape"){this.close("cancelBar");return}if(e.key==="ArrowUp"){const o=this.getPrevItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),this.selectItem(this.items[o].id),e.preventDefault(),e.stopPropagation()}else if(e.key==="ArrowDown"){const o=this.getNextItemIndex(this.getSelectedItemIndex());this.startPauseMouseEnter(),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("switchItem");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)}}}});m(this,"handleDocumentMouseDown",e=>{if(e.target instanceof Element&&!this.isInCommandBar(e.target)){const o=this.listeners("closing");for(let r=0;r<o.length;r++)if(o[r](this,e)===!1)return;this.close("clickBackground")}});m(this,"handleHidden",()=>{this.closeReason!=="fromHover"&&this.emit("close",this),this.close(null),EC(this.id)});m(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&W(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&BC(this.id)});m(this,"lastEnterPauseTime",0);m(this,"startPauseMouseEnter",()=>{this.lastEnterPauseTime=Date.now()});m(this,"handleItemMouseEnter",e=>{if(Date.now()-this.lastEnterPauseTime<100)return;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)});m(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)&&(et(o,"selected"),this.emit("selectionChange",this,""))});m(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("clickItem"))}});m(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=oo(r);if(!Kt(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:K(),this.options={...cL,...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(e){this.closeReason=e,this.subBar&&this.subBar.close(e),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}click(e,o){this.emit("click",this,e,o)}createPopperOptions(){var r,i;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"]}})),this.options.padding&&((i=e==null?void 0:e.modifiers)==null||i.push({name:"preventOverflow",options:{padding:this.options.padding}})),e}destroy(){var e;this.close(null),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,a;return s.id===((a=(l=this.subBar)==null?void 0:l.parentItem)==null?void 0:a.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],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)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],i=r.type,l=!(r.states&&r.states.indexOf("disabled")!==-1);if(i!=="separator"&&i!=="section"&&l)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&&et(o,"selected")}selectItem(e){const o=this.getSelectedItem();if(o){if(o.id===e)return;const i=o.id,s=this.getItemElementById(i);s&&et(s,"selected")}const r=this.getItemElementById(e);r?(W(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("switchItem");return}this.subBar.destroy(),this.subBar=null}if(!o.children)return;const r=this.getItemElementById(o.id);if(!r)return;const i=K2.createSubCommandBar(o,(l=this.closeable)!=null?l:this,e?{id:e}:{});this.subBar=i,this.subBar.on("click",(a,d,h)=>{this.emit("click",a,d,h)}),this.subBar.on("close",()=>{var a;(a=this.subBar)==null||a.destroy(),this.subBar=null,et(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),W(r,"active")}isInCommandBar(e){if(!e||!(e instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&Kt(o,e)||Kt(this.content,e)?!0:this.subBar?this.subBar.isInCommandBar(e):!1}createCommandItem(e){var i,s,l,a;let o=(i=this.options.itemElementTag)!=null?i:"div";e.element&&(o="div");const r=w(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"),(a=e.states)!=null&&a.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 g(nc,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 g(nc,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(e){const o=e.getAttribute("data-id");return g(nc,o,"no data-id attribute"),o}getItemElementById(e){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${e}"]`);return g(nc,o,`no exists command item, id=${e}`),o}getParentCommandItemElement(e){if(!e||!(e instanceof Element))return null;if(xt(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=w("div",["editor-command-bar-root"],null);if(this.options.header){const i=w("div",["editor-command-bar-header"],null);if(this.options.header instanceof Function){const s=this.options.header();s&&i.appendChild(s)}else i.appendChild(this.options.header);this.header=i,this.header&&o.appendChild(this.header)}const r=w("div",["editor-command-bar"],o);if(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.options.footer){const i=w("div",["menu-item","editor-command-bar","footer"],null);if(this.options.footer instanceof Function){const s=this.options.footer();s&&i.appendChild(s)}else i.appendChild(this.options.footer);this.footer=i,this.footer&&o.appendChild(this.footer)}return(this.options.header||this.options.footer)&&W(o,"scrollable-bar"),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;g(nc,e.children&&e.children.length>0,"no item children");const i=(l=e.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return g(nc,s,`no creator for command type: ${i}`),s(e,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let Ui=K2;m(Ui,"commandBarCreators",new Map),S("ui-command-bar");class qh extends Ui{constructor(){super(...arguments);m(this,"tippyInstance",null)}manualShow(e,o){var r,i;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=UB.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(e){var o;super.close(e),this.isVisible&&((o=this.tippyInstance)==null||o.hide())}destroy(){var e;(e=this.tippyInstance)==null||e.destroy(),this.tippyInstance=null,super.destroy()}getCommandBarRoot(){return this.content.closest("[data-tippy-root]")}get isVisible(){var e,o;return(o=(e=this.tippyInstance)==null?void 0:e.state.isVisible)!=null?o:!1}get popper(){return this.content.closest("[data-tippy-root]")}}const ev=S("ui-base");class Xa extends qh{constructor(t,e){var i;const r=[{id:(i=e==null?void 0:e.id)!=null?i:`popup-${K()}`,name:"",element:t}];super(r,void 0,{disablePageScroll:!0})}initCommandBarElement(t){W(t,"popper")}initItemElement(t,e){}get popupContent(){const t=this.items[0];g(ev,t,"no dialog item");const e=typeof t.element=="function"?t.element(t):t.element;return g(ev,e,"no item element"),e}}const zi=S("filterable-list");function nv(n){var e,o;const t=w("div",["list-item"],null);return t.setAttribute("data-id",n.id),t.appendChild(w("div",["list-item-text"],null,n.name)),(e=n.states)!=null&&e.includes("selected")&&W(t,"selected"),(o=n.states)!=null&&o.includes("disabled")&&W(t,"disabled"),t}function ov(n){const t=w("div",["list-root"],null);return n.forEach(e=>{t.appendChild(nv(e))}),n.length||t.appendChild(nv({id:"placeholder",states:["disabled"],name:R.t("search.emptyTips")})),t}function rv(n,t){let e=n;return t&&(e=n.map(o=>({...o,states:o.id===t?["selected"]:void 0}))),e}function aL(n,t){const e=w("div",["filterable-list"],null),o=w("div",["filter"],e),r=w("div",["filter-container"],o),i=w("input",["filter-input"],r);t&&t.placeholder&&(i.placeholder=t.placeholder);const s=w("div",["list"],e),l=ov(rv(n,t==null?void 0:t.initialSelectedId));return s.appendChild(l),e}function iv(n,t,e){const o=n.querySelector(".list");g(zi,o,"no list root");const r=ov(rv(t,e)),i=o.querySelector(".list-root");if(g(zi,i,"no exists menu"),Ca(i,r),e){const s=o.querySelector(".list-item.selected");s&&(g(zi,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class uL{constructor(t,e){m(this,"root");m(this,"visibleItems");m(this,"selectedId");m(this,"filter","");m(this,"onSelected",null);m(this,"handleKeydown",t=>{this.processKeyDown(t)});m(this,"handleInputChanged",()=>{const t=this.root.querySelector(".filter-input");g(zi,t,"no input");const e=t.value.toLocaleLowerCase();this.setFilter(e)});m(this,"handleClick",t=>{this.processClick(t)});var o;this.items=t,this.options=e,this.root=aL(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");g(zi,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");g(zi,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,iv(this.root,this.visibleItems,t)}focus(){const t=this.root.querySelector(".filter-input");g(zi,t,"no input"),t.focus()}reset(){this.setFilter("");const t=this.root.querySelector(".filter-input");g(zi,t,"no input"),t.value=""}setFilter(t){this.filter!==t&&(this.filter=t,this.visibleItems=this.items.filter(e=>e.name.toLocaleLowerCase().includes(t)),iv(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(a=>a.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 dL extends uL{constructor(e,o,r){super(e,r);m(this,"popup");m(this,"onShow",null);m(this,"onHide",null);m(this,"custom",null);m(this,"handleShow",()=>{this.onShow&&this.onShow(this)});m(this,"handleHide",()=>{this.onHide&&this.onHide(this)});m(this,"handleShown",()=>{this.focus()});this.popup=new Xa(this.root)}destroy(){super.destroy(),this.onShow=null,this.onHide=null}show(e){this.reset(),this.popup.manualShow(e,{theme:"dropdown-list"}),this.focus()}processKeyDown(e){super.processKeyDown(e),(e.key==="Esc"||e.key==="Enter")&&this.popup.close("cancelBar")}processClick(e){super.processClick(e);const o=e.target;!(o instanceof HTMLElement)||!o.closest(".list-item")||this.popup.close("clickItem")}}const ant="",unt="";function hL(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 sv=`<?xml version="1.0" ?>
28
28
  <svg
29
29
  fill="currentColor"
30
30
  xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
@@ -391,7 +391,7 @@ xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
391
391
  `,PO=`<?xml version="1.0" ?>
392
392
  <svg t="1666868691722" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3301" width="16" height="16">
393
393
  <path d="M832 192v640H192V192h640m32-64H160c-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-32z" p-id="3302" fill="#dbdbdb"></path>
394
- </svg>`;function NO(n,t){const e=mc(t);if(e!=="text-only"){if(e==="checked"){n.innerHTML=FO;return}if(e==="unchecked"){n.innerHTML=PO;return}n.innerText=OO(t)}}function $O(n){const t=w("div",["list-container"],null),e=w("button",["list-marker"],t);return NO(e,n),t}function v9(n){let t=Zt(n);if(!t)return null;const e=Gs(n);for(;t!==e;){if(g(ke,t,"no next block"),Ht(t))return Cn(t)>Cn(n)?t:null;if(t=Zt(t),!t)return null}return null}function A0(n){const t=[];let e=v9(n);if(!e)return t;for(;e;){const o=Gs(e);t.push({block:e,children:A0(e)}),e=o}return t}function HO(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 y9(n,t){return Cn(t)!==1}function k9(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&&k9(n,o.children,r.groupId)})}function b0(n,t){if(!y9(n,t))return!1;const e=Cn(t);if(e===1)return!1;let o=K(),r=1,i=Zn(t);const s=e-1,l=a0(t);l&&(o=uc(l),r=ho(l)+1,i!=="text-only"&&(i=Zn(l)));const a=A0(t),d=n.getBlockData(t),h={...d,groupId:o,level:s,start:r,...c0(i)};n.updateBlockData(t,h),n.doc.beginBatchUpdate(),k9(n,a,d.groupId),n.doc.endBatchUpdate(),new Zs(n,t).fix();const A=v9(t);return A&&new Zs(n,A,{resetStart:!0,resetGroupId:!0}).fix(),!0}function gc(n,t){_e(t);const e=n.getBlockData(t),o={id:K(),type:"text",text:e.text};e.heading&&(o.heading=e.heading),e.heading&&(o.heading=e.heading);const r=new hf(n,t),i=nt(t),s=bt(t);n.deleteBlock(t);const l=mh(o.id,0);n.insertBlock(at(i),s,o,l),r.fix()}function jO(n){if(!n.selection.range.isCollapsed())return!1;const t=n.selection.focusedBlock;if(!Ht(t))return!1;const e=n.selection.range.focus;return!e.isSimple()||e.offset!==0?!1:Cn(t)===1?(gc(n,t),!0):(b0(n,t),!0)}const UO=S("list-block");function zO(n,t,e){g(UO,Ht(t),"not a list block");const o={...n.getBlockData(t),id:K()};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==null?void 0:o.checkbox)==="checked"&&(o.checkbox="unchecked"),o}function VO(n){if(_e(n),!af(n))return n;let t=Qi(n);for(;t;){if(!af(t))return t;t=Qi(t)}return null}function WO(n,t,e,o){const r=new Zs(n,o),i=ho(o)+1;Yl(n,t,e,{forceInsertAfter:!0,newBlockData:zO(n,o,{start:i})}),r.fix()}function qO(n){var s;if(n.selection.range.isCollapsed()){const l=n.selection.focusedBlock;if(Ht(l)&&ut(n,l)===0)return gc(n,l),!0}n.clearSelectedContents();const t=n.selection.focusedBlock;if(!Ht(t))return!1;const e=n.selection.range.focus;if(!e.isSimple())return!1;const o=e.offset,i=(s=o===ut(n,t)?VO(t):t)!=null?s:t;return WO(n,t,o,i),!0}function w9(n){g(ke,Ht(n),"not a list block");const{level:t}=Zi(n);let e=ce(n);for(;e;){if(Ht(e)){const{level:o}=Zi(e);if(t===o)return e;if(o<t)return null}e=ce(e)}return null}function B9(n,t){return _e(t),w9(t)?Cn(t)<qR:!1}function GO(n,t,e){let o=ce(t);g(ke,o,"no prev brother");const r=Cn(e);for(;o;){if(o===e)return null;if(Ht(o)&&Cn(o)===r+1)return o;o=ce(o)}return null}function E9(n,t){if(!B9(n,t))return!1;_e(t);const e=w9(t);g(ke,e,"no list prev brother");const o=e,r=GO(n,t,o),i=Cn(o)+1;let s=K(),l=1,a=Zn(t);r&&(s=uc(r),l=ho(r)+1,a=Zn(r));const d=A0(t),p={...n.getBlockData(t),groupId:s,level:i,start:l,...c0(a)};return n.updateBlockData(t,p),n.doc.beginBatchUpdate(),HO(d).forEach(v=>{const B=n.getBlockData(v);n.updateBlockData(v,{...B,level:B.level+1})}),n.doc.endBatchUpdate(),!0}function ZO(n,t,e){return t.length===0||!t.every(o=>Ht(o.block))?!1:e==="increase"?B9(n,t[0].block):y9(n,t[0].block)}function x9(n,t,e){if(!ZO(n,t,e))return!1;const o=t[0].block,r=Cn(o),i=t.filter(d=>Cn(d.block)<=r),s=u9(o,{withSelf:!1}),l=new Set(i.map(d=>d.block)),a=s.filter(d=>!l.has(d));return n.undoManager.runInGroup(()=>{let d=null;a.length>0&&(d=new Zs(n,a[0])),i.forEach(h=>{e==="increase"?E9(n,h.block):b0(n,h.block)}),d==null||d.fix()}),!0}function QO(n,t){return E9(n,t)}function YO(n,t){return b0(n,t)}function JO(n){const t=n.selection.range.getSelectedBlocks();if(t.length>1)return x9(n,t,"increase"),!0;const e=t[0].block;if(!Ht(e))return!1;const o=new hf(n,e);return QO(n,e)&&(o.fix(),new Zs(n,e).fix()),!0}function KO(n){const t=n.selection.range.getSelectedBlocks();if(t.length>1)return x9(n,t,"decrease"),!0;const e=t[0].block;return Ht(e)?(YO(n,e),!0):!1}class XO{constructor(t){this.editor=t}handleBeforeKeyDown(t,e){const o=t.selection.range.getSelectedBlocks();if(o.length===0||!o.some(i=>Ht(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||!Ht(e.block)||Rr(t,"Shift+Enter")?!1:this.editor.undoManager.runInGroup(()=>qO(this.editor))}handleBackspace(){return this.editor.undoManager.runInGroup(()=>jO(this.editor))}handleTab(t){return Rr(t,"Shift+Tab")?this.editor.undoManager.runInGroup(()=>KO(this.editor)):this.editor.undoManager.runInGroup(()=>JO(this.editor))}}class t_{constructor(t){m(this,"effectedBlockIds",new Map);m(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;Ht(i)&&e.add(i)});const o=new Map;Array.from(e.values()).forEach(r=>{var a;const i=gu(r),{start:s}=Zi(i);o.set(it(i),s);const l=(a=KR(r))!=null?a:r;o.set(it(l),s)}),this.effectedBlockIds=o});m(this,"handleAfterClearSelection",()=>{Array.from(this.effectedBlockIds.entries()).forEach(([t,e])=>{const o=this.editor.findBlockById(t);!o||m0(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 e_=S("customize-list-start-menu");class n_{constructor(t){m(this,"popup");m(this,"block",null);m(this,"show",(t,e)=>{const o=e.querySelector("div.list-container");g(e_,o,"list-block mark does not exist"),this.block=e,this.popup.manualShow(o,{theme:"light"})});m(this,"createDialogContent",()=>{const t=w("div",["customize-start-panel"],null);w("span",["customize-start-panel-title"],t,R.t("list.numberLabel"));const e=this.createNumericInput();t.appendChild(e);const o=w("button",["customize-start-panel-button"],t,R.t("list.confirm"));return this.editor.domEvents.addEventListener(t,"keydown",this.handleKeydown),this.editor.domEvents.addEventListener(o,"click",this.handleOk),t});m(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=ho(t);!o||!r||requestAnimationFrame(()=>{r.focus(),r.value=String(i)})});m(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(()=>{fc(this.editor,[o,...dc(o)],r,{resetGroupId:!0})}),this.popup.close("clickItem"))});m(this,"handleKeydown",(t,e)=>{const o=e;o.isComposing||(o.key==="Escape"?this.popup.close("cancelBar"):o.key==="Enter"&&this.handleOk())});this.editor=t,this.popup=new Xa(this.createDialogContent()),this.popup.on("show",this.handleDialogShow)}destroy(){this.popup.destroy()}createNumericInput(){const t=w("input",["customize-start-panel-input"],null);t.type="number",t.min="1";const e=()=>{const r=t.value.replace(/[^\d]/g,"").replace(/^0+/,""),i=parseInt(r,10);i<=0||Number.isNaN(i)?t.value="":t.value=r};return this.editor.domEvents.addEventListener(t,"input",e),t}}function o_(n,t){return uc(n)===uc(t)}function r_(n,t){const e=c9(t);return e?o_(e,t)?ho(e)!==ho(t)-1:!0:!1}function i_(n,t){return Qi(t)?!0:ho(t)!==1}function s_(n,t){return _e(t),[{id:"continue-numbering",name:R.t("list.continueList"),states:r_(n,t)?[]:["disabled"]},{id:"start-new-list",name:R.t("list.restartList"),states:i_(n,t)?[]:["disabled"]},{id:"set-numbering-value",name:R.t("list.changeNumber")}]}function l_(n,t,e){var o,r;if(_e(t),e.id==="continue-numbering"){const i=c9(t);i&&fc(n,[t,...dc(t)],ho(i)+1,{resetGroupId:!0,groupId:uc(i)})}if(e.id==="start-new-list"&&n.undoManager.runInGroup(()=>{fc(n,[t,...dc(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 n_(n)).show(n,t)}}class c_{constructor(t){m(this,"menu");m(this,"handleClick",(t,e)=>{const o=jl(e,"div.list-container");if(o&&this.editor.isWritable()){const r=ot(o);g(ke,r,"no parent block"),_e(r);const i=t.getBlockData(r);if(i&&i.checkbox){t.updateBlockData(r,{...i,checkbox:i.checkbox==="checked"?"unchecked":"checked"});return}if(Zn(r)==="unordered")return;this.menu.updateItems(this.getCommandItems(r)),this.menu.manualShow(o),this.activeList(o,!0)}});m(this,"handleMenuClose",()=>{var e;const t=(e=this.menu.tippyInstance)==null?void 0:e.reference;t&&this.activeList(t,!1)});m(this,"handleMenuClick",(t,e)=>{var r;const o=(r=this.menu.tippyInstance)==null?void 0:r.reference;if(o){const i=ot(o);i&&l_(this.editor,i,e)}});this.editor=t,this.editor.addListener("click",this.handleClick),this.menu=new zs([]),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 s_(this.editor,t)}activeList(t,e){const o=ot(t);!o||(e?(W(t,"active"),W(o,"active")):(et(t,"active"),et(o,"active")))}}class a_{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(!Ht(r)||!m9(r))return!1;if(e.key==="ArrowUp"||e.key==="ArrowLeft"){const i=Ds(r);return i&&t.selection.selectBlock(i,ut(t,i)),!0}if(e.key==="ArrowDown"||e.key==="ArrowRight"){const i=Ss(r);return i&&t.selection.selectBlock(i,0),!0}return(e.key==="Delete"||e.key==="Backspace"||e.key==="Escape")&&p9(t,r),!0}}function u_(n,t,e,o,r){op(n,"list-block-init",()=>{setTimeout(()=>{n.input.addHandler(new a_(n)),n.input.addHandler(new XO(n)),n.addCustom("list-clear-selection-handler",()=>new t_(n)),n.addCustom("list-marker-menu",()=>new c_(n))})});const i=In.createBlockContent(n,t,e,o,r),s=r,{level:l,start:a,groupId:d}=s,h=mc(s);o.setAttribute("data-list-level",`${l}`),o.setAttribute("data-list-start",`${a||1}`),o.setAttribute("data-list-group-id",`${d}`),o.setAttribute("data-list-type",h);const p=$O(s);return o.insertBefore(p,i),s.viewAsMindmap?setTimeout(()=>{const A=n.getBlockById(r.id);A&&uf(n,A,{},{mindmapTools:f0,saveData:!1})}):setTimeout(()=>{const A=n.getBlockById(r.id);A&&g9(n,A)}),i}const d_={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"}},h_={list:{confirm:"Confirm",setStart:"Set number",continueList:"Continue numbering",restartList:"Start a new list",changeNumber:"Set numbering value",numberLabel:"Numbering order",mention:{tooltip:"Mention and notify users"}},mindmap:{viewAsMindMap:"View as MindMap",autoFit:"Auto zoom",fullScreen:"Full screen",close:"Close",exitFullscreen:"Exit full screen"}},f_={list:{confirm:"OK",setStart:"\u756A\u53F7\u3092\u8A2D\u5B9A",continueList:"\u9023\u756A\u3092\u8A2D\u5B9A",restartList:"\u65B0\u3057\u3044\u30EA\u30B9\u30C8\u3092\u4F5C\u6210",changeNumber:"\u756A\u53F7\u3092\u7DE8\u96C6",numberLabel:"\u756A\u53F7",mention:{tooltip:"\u30E1\u30F3\u30B7\u30E7\u30F3\u304A\u3088\u3073\u901A\u77E5"}},mindmap:{viewAsMindMap:"\u30DE\u30A4\u30F3\u30C9\u30DE\u30C3\u30D7\u3067\u8868\u793A",autoFit:"\u81EA\u52D5\u30D5\u30A3\u30C3\u30C8",fullScreen:"\u5168\u753B\u9762\u8868\u793A\u306E\u30AA\u30F3",close:"\u9589\u3058\u308B",exitFullscreen:"\u5168\u753B\u9762\u8868\u793A\u306E\u30AA\u30D5"}};R.mergeLang({"zh-CN":d_,"en-US":h_,"ja-JP":f_});const ynt="",I9={...In,blockType:"list",createBlockContent:u_,convertFrom:RO,convertTo:_O,handleDrop:wO,notify:bO},v0=S("paragraph");class m_{constructor(t){m(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":[R.t("commands.unordered"),Bo("CtrlOrCmd+Shift+L"),yL],"ordered-list":[R.t("commands.ordered"),Bo("CtrlOrCmd+Shift+U"),vL],"check-list":[R.t("commands.check"),void 0,kL],link:[R.t("commands.link"),Bo("CtrlOrCmd+K"),mv],quoted:[R.t("commands.quote"),void 0,wL]};if(tt(t,e)){const i=it(e),s=Dt(e),l=Io(t,e),a=t.getBlockData(e);Object.entries(r).forEach(([d,[h,p,A]])=>{const v=[];if(this.isChecked(a,d)&&v.push("checked"),d==="link"){if(!t.selection.range.isSimple())return;t.selection.range.getSelectedBlocks().length!==1&&v.push("disabled")}o.push({blockId:i,blockType:s,blockKind:l,id:d,name:h,desc:p,states:v,icon:A,groupIndex:600})})}return o}convertLink(t,e,o){g(v0,$r(e.start),""),g(v0,$r(e.start),"");const r="bottom-start",i=e.start.offset,s=e.end.offset,l=(v,B)=>{t.undoManager.runInGroup(()=>{try{const D=t.selection.range.isCollapsed();let T;if(D){T=Hr(t.getBlockText(o),s,v,{link:B}),t.setBlockText(o,T);return}T=dh(t.getBlockText(o),i,s,v),T=Ia(i,v.length,T,"link",B),t.setBlockText(o,T),t.selection.selectBlock(o,i+v.length),t.focus()}catch(D){v0.error(D)}})},a=()=>{t.selection.selectBlock(o,s),t.focus()},d=Ti(t,o,e)[0];if(!d)return;const h=Li(t,o,"link-button-anchor",d),p=t.getBlockText(o),A=Ta(p,i);fu(t,{target:h,linkText:t.getSelectedText(),linkUrl:(A==null?void 0:A.link)||"",onFinished:l,onClose:a,placement:r})}convertToList(t,e,o){const r=Kd(t,e,"list",{offset:0,data:{listType:o}});r&&t.undoManager.runInGroup(()=>{const i=bt(e),s=nt(e);t.insertBlock(at(s),i,r.blockData),t.deleteBlock(e)})}executeCommand(t,e,o,r){var a;if(!tt(t,e))return!1;const i=r.id,s=(a=r.states)==null?void 0:a.includes("checked");let l=!1;if(i==="unordered-list"&&(s?gc(t,e):this.convertToList(t,e,"unordered"),l=!0),i==="ordered-list"&&(s?gc(t,e):this.convertToList(t,e,"ordered"),l=!0),i==="check-list"&&(s?gc(t,e):this.convertToList(t,e,"unchecked"),l=!0),i==="quoted"){const h=t.getBlockData(e).quoted;t.updateBlockData(e,{quoted:h?void 0:!0}),t.focus(),l=!0}if(i==="link"){const d=sf(t);d.disableTextToolbar(),d.hide(),setTimeout(()=>{d.enableTextToolbar()},1e3),this.convertLink(t,o,e),l=!0}return l}}const g_={left:tu,right:Sp,center:Lp};class p_{constructor(t){m(this,"id","BlockAlignProvider");this.editor=t}applyAlignStyle(t,e,o){Object.keys(g_).includes(o)?t.updateBlockData(e,{align:o}):t.updateBlockData(e,{align:null})}isChecked(t,e){return t.align===e}getAvailableCommands(t,e,o){if(tt(t,e)){const r=it(e),i=Dt(e),s=Io(t,e),l=t.getBlockData(e),a=d=>{var p;const h=w("span",["toolbar-item-name-container"],null);for(const A of d.children)if((p=A.states)!=null&&p.includes("checked"))return h.innerHTML=A.icon||tu,h;return h.innerHTML=tu,h};return[{id:"align",name:R.t("commands.alignGroup"),blockId:r,blockType:i,blockKind:s,groupIndex:700,dropdown:!0,element:a,manualShowChildren:!0,childrenPlacement:"bottom-start",defaultCheckedChildren:["align-left"],children:[{id:"align-left",name:R.t("commands.alignLeft"),icon:tu,states:this.isChecked(l,"left")?["checked"]:[]},{id:"align-center",name:R.t("commands.alignCenter"),icon:Lp,states:this.isChecked(l,"center")?["checked"]:[]},{id:"align-right",name:R.t("commands.alignRight"),icon:Sp,states:this.isChecked(l,"right")?["checked"]:[]}],childrenType:"menu"}]}return[]}executeCommand(t,e,o,r){if(!tt(t,e))return!1;if(r.id.startsWith("align")){const i=r.id.replace(/^align-/,"");return this.applyAlignStyle(t,e,i),this.editor.focus(),!0}return!1}}function C_(n){const e=n.selection.range;if(e.isCollapsed()||e.start.blockId!==e.end.blockId||!e.start.isSimple()||!e.end.isSimple()||e.end.offset-e.start.offset!==1)return!1;const o=n.getBlockById(e.start.blockId);return Sa(n,o,e.start.offset).charType==="box"}const A_=S("toolbar-handler"),b_={id:"",name:"",type:"separator"};class pc{constructor(t){m(this,"toolbar");m(this,"toolbarType","object");m(this,"mouseDown",!1);m(this,"oldRange",null);m(this,"hoveringBlock",null);m(this,"hoveringTextChild",null);m(this,"_disableTextToolbar",!1);m(this,"handleButtonClick",(t,e)=>{this.toolbarType==="text"?(this.editor.editorCommandProviders.executeCommand(this.editor.selection.range,e,{}),this.showTextToolbar("click")):this.hoveringBlock&&UR(this.editor,this.hoveringBlock,this.hoveringTextChild,e)});m(this,"handleClose",()=>{Fp(this.editor)&&this.editor.focus()});m(this,"handleClosing",(t,e)=>{if(this.toolbarType==="object"){const o=iC(e);if(this.hoveringBlock===o)return!1}return!0});m(this,"handleDocumentMouseDown",t=>{t.button===0&&(document.addEventListener("mouseup",this.handleDocumentMouseUp),this.mouseDown=!0)});m(this,"handleDocumentMouseUp",()=>{document.removeEventListener("mouseup",this.handleDocumentMouseUp),this.mouseDown=!1,this.handleSelectionChange(this.editor)});m(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("fromHover");return}this.showObjectToolbar(r)}});m(this,"handleSelectionChange",He.default(t=>{var o;if(g(A_,t===this.editor,"editor mismatch"),t.selection.range.isCollapsed()||this.mouseDown){if(this.toolbarType==="object"){const r=(o=this.toolbar.tippyInstance)==null?void 0:o.reference,i=this.editor.selection.focusedBlock;if(r&&Kt(r,i))return}this.toolbar.close("selectionChange"),this.oldRange=null;return}if(!this.editor.isWritable()){this.toolbar.close("selectionChange"),this.oldRange=null;return}if(t.selection.range.getSelectedBlocks().length===0){this.toolbar.close("selectionChange"),this.oldRange=null;return}this.oldRange&&this.oldRange.isEqual(t.selection.range)||(this.oldRange=t.selection.range,this.showTextToolbar("selectionChange"))},50));this.editor=t;const e=t.options.componentsOptions.popover;this.toolbar=new ou([],void 0,{tooltipId:t.clientId,id:"editor-toolbar",overflowBoundary:e==null?void 0:e.overflowBoundary,refuseOverflow:!0,padding:20}),this.toolbar.on("click",this.handleButtonClick),this.toolbar.on("close",this.handleClose),this.toolbar.on("closing",this.handleClosing),this.bindEvents(),t.addListener("selectionChanged",this.handleSelectionChange),pe.get(t).addListener("childChange",this.handleHoveringBlockChildChange),pe.get(t).addFilter(this),t.editorCommandProviders.registerCommandProvider(new VR(t)),t.editorCommandProviders.registerCommandProvider(new m_(t)),t.editorCommandProviders.registerCommandProvider(new p_(t))}disableTextToolbar(){this._disableTextToolbar=!0}enableTextToolbar(){this._disableTextToolbar=!1}hide(){this.toolbar.close("selectionChange")}destroy(){this.unbindEvents(),this.toolbar.destroy(),this.editor.removeListener("selectionChanged",this.handleSelectionChange),pe.get(this.editor).removeListener("childChange",this.handleHoveringBlockChildChange)}isInBlock(t,e){return t!==this.hoveringBlock?!1:!!(e.target&&e.target instanceof Node&&this.toolbar.popper&&Kt(this.toolbar.popper,e.target))}bindEvents(){document.addEventListener("mousedown",this.handleDocumentMouseDown)}unbindEvents(){document.removeEventListener("mousedown",this.handleDocumentMouseDown)}update(t){this.showTextToolbar(t)}showTextToolbar(t){var D,T;if(this._disableTextToolbar||!this.editor.isWritable())return;const o=this.editor.selection.range.getSelectedBlocks();if(o.length===0)return;const r=o[0];if(!r)return;if(o.length===1&&Le(r.block)){t==="click"&&this.showObjectToolbar(null);return}if(C_(this.editor))return;if(nt(r.block)===this.editor.rootContainer&&bt(r.block)===0){this.toolbar.close("selectionChange");return}const i=this.editor.editorCommandProviders.getCommands(this.editor.selection.range),s=new Map;i.forEach(_=>{const M=_.groupIndex,H=s.get(M);H?H.push(_):s.set(M,[_])});const l=[[]],a=Array.from(s.entries()).sort((_,M)=>_[0]-M[0]);for(let _=0;_<a.length;_++){const[,M]=a[_];if(M.length===0)continue;let H=l[l.length-1];H.length>0&&H[H.length-1].groupIndex!==M[M.length-1].groupIndex&&(H=[],l.push(H)),H.push(...rf(M))}if(l.length===0){this.toolbar.close("selectionChange");return}this.toolbarType="text";const d=[];if(l.forEach((_,M)=>{const H=_.sort((z,q)=>{var rt,ft;return((rt=z.order)!=null?rt:0)-((ft=q.order)!=null?ft:0)});d.push(...H),M!==l.length-1&&d.push(b_)}),d.length===0){this.toolbar.close("selectionChange");return}this.toolbar.updateItems(d);const h=o[o.length-1],p=!this.editor.selection.range.isReverse()&&h!==r,A=p?h:r,v=OR(this.editor,A),B=Li(this.editor,A.block,"editor-quick-menu",v);this.toolbar.manualShow(B,{placement:p?"bottom":"top"}),(T=(D=this.toolbar.tippyInstance)==null?void 0:D.popperInstance)==null||T.update()}showObjectToolbar(t){var l,a;if(!this.hoveringBlock||this.mouseDown)return;const e=this.hoveringBlock,o=this.hoveringTextChild,{commands:r,element:i}=$R(this.editor,e,o);if(!r.length||!i){this.toolbar.close("fromHover");return}this.toolbarType="object",this.toolbar.isVisible&&((a=(l=this.toolbar)==null?void 0:l.tippyInstance)==null?void 0:a.reference)!==i&&this.toolbar.close("fromHover");const s=()=>{let d;const h=i.getClientRects();if(h.length>1){if(d=o?h[h.length-1]:h[0],t)for(let p=0;p<h.length;p++){const A=h[p],v=new DOMRect(A.x-4,A.y-4,A.width+8,A.height+8);if(v.x<t.clientX&&t.clientX<v.right&&v.y<t.clientY&&t.clientY<v.bottom){d=A;break}}}else{if(d=i.getBoundingClientRect(),o){const p=o.getBoundingClientRect();return new DOMRect(p.x,p.y,p.width,p.height)}return new DOMRect(h[0].x,h[0].y,h[0].width,h[0].height)}if(t){const p=d.y,A=t.clientX;return new DOMRect(A,p,10,d.height)}return d};this.toolbar.updateItems(r),this.toolbar.isVisible||this.toolbar.manualShow(i,{placement:o?"bottom":"top",getReferenceClientRect:s})}static register(t){return t.addCustom("toolbar-handler",e=>new pc(e))}static get(t){return t.getCustom("toolbar-handler")}}function gf(n,t,e){n.getBlockData(t).heading===e?n.updateBlockData(t,{heading:null}):n.updateBlockData(t,{heading:e})}function T9(n,t,e){["left","center","right"].includes(e)?n.updateBlockData(t,{align:e}):n.updateBlockData(t,{align:null})}function y0(n,t){const o=n.getBlockData(t).quoted;n.updateBlockData(t,{quoted:o?void 0:!0})}function k0(n,t){return!!(n[t]||n.level&&(n.ordered===!0&&!n.checkbox&&t==="ordered-list"||n.ordered===!1&&!n.checkbox&&t==="unordered-list")||t==="check-list"&&n.checkbox)}function w0(n,t,e){if(!n.selection.range.focus.isSimple())return;const r=n.getBlockData(t);let i;switch(e){case"unordered-list":i=k0(r,"unordered-list")?void 0:"unordered";break;case"ordered-list":i=k0(r,"ordered-list")?void 0:"ordered";break;case"check-list":i=k0(r,"check-list")?void 0:"unchecked";break}if(i){const s=Kd(n,t,"list",{offset:0,data:{listType:i}});s&&n.undoManager.runInGroup(()=>{const l=bt(t),a=nt(t);n.deleteBlock(t),n.insertBlock(at(a),l,s.blockData)})}else gc(n,t)}const v_=Object.freeze(Object.defineProperty({__proto__:null,applyHeadingStyle:gf,applyAlignStyle:T9,applyQuoteStyle:y0,applyList:w0},Symbol.toStringTag,{value:"Module"})),y_=[kp,wp,Bp,Ep,xp,Ip,Tp,Dp],k_={Unordered:Cv,Ordered:Av,Checkbox:gv,Quote:pv};function D9(n,t){const e=n;e.blockOptions=t,e.itemType="insert-block",n.children&&n.children.forEach(o=>D9(o,t))}function w_(){return{name:"basic",insertBlockCommandItems:[{id:"text",icon:nu,name:R.t("commands.text"),order:0,group:"basics",value:"text"}]}}function B0(n=1){var r;const t={name:"basic",insertBlockCommandItems:[]};let e=lf();e<=4?e=5:e<8&&(e+=1);let o=n;for(;o<=e;){const i=`heading-${o}`;(r=t.insertBlockCommandItems)==null||r.push({id:i,icon:y_[o-1],name:R.t("quickMenu.basic.heading.title",{heading:String(o)}),order:o,group:"basics",value:String(o),subText:pn(i)}),o++}return t}function B_(){const n={name:"basic",insertBlockCommandItems:[]};return["Unordered","Ordered","Checkbox","Quote"].forEach((e,o)=>{var i;const r=`insert-${e.toLocaleLowerCase()}`;(i=n.insertBlockCommandItems)==null||i.push({id:r,name:R.t(`quickMenu.basic.${e.toLocaleLowerCase()}`),icon:k_[e],value:e.toLocaleLowerCase(),group:"basics",order:10+o,subText:pn(r)})}),n}class S9{constructor(t){this.withPlainText=t}getCommands(){const t=w_(),e=B0(),o=B_();return[...this.withPlainText?t.insertBlockCommandItems||[]:[],...e.insertBlockCommandItems||[],...o.insertBlockCommandItems||[]]}updateBlock(t,e,o,r){const{value:i,id:s}=r;return s.startsWith("heading-")?gf(t,o,Number.parseInt(i!=null?i:"1",10)||1):i==="ordered"||i==="unordered"||i==="checkbox"?w0(t,o,{ordered:"ordered-list",unordered:"unordered-list",checkbox:"check-list"}[i]):i==="quote"&&y0(t,o),null}async handleUpdateBlockCore(t,e){const o=t.getBlockByIndex(e.containerId,e.blockIndex);return this.updateBlock(t,e.containerId,o,e.item)}async handleInsertEmptyBlockCore(t,e){const{containerId:o,blockIndex:r}=e,i=t.insertTextBlock(void 0,o,r);return this.updateBlock(t,e.containerId,i,e.item)}async executeCommand(t,e,o){if(o.from==="quick-menu"){const r=t.getBlockById(o.blockId),i=t.getParentContainer(r),s=at(i),l=t.getBlockIndex(r);t.undoManager.runInGroup(()=>this.handleUpdateBlockCore(t,{item:e,containerId:s,blockIndex:l})),t.focus()}else o.from==="block-menu"&&(t.undoManager.runInGroup(()=>this.handleInsertEmptyBlockCore(t,{item:e,containerId:o.containerId,blockIndex:o.blockIndex})),t.focus());return null}}const L9={basics:100,system:200,common:300,thirdParty:400};class E0{constructor(){m(this,"dataUrl","");m(this,"error",null)}destroy(){}setDataUrl(t){this.error=null,this.dataUrl=t}setError(t){this.dataUrl="",this.error=t}}const E_=S("mathjax-converter"),x_="MathJax-script";async function I_(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 vs(e,x_)}function T_(){try{window.MathJax&&window.MathJax.texReset()}catch{}}async function M9(n,t){const e="mathjax2Svg";try{await wo.lock(e),T_(),await I_(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 E_.error(o),o}finally{wo.release(e)}}async function R9(n,t){const e=await M9(n,t);return e?await Sm(e,"image/svg+xml"):""}async function x0(n,t){const o=await M9(n,t),r=new File([o],"math.svg");return(await n.doc.uploadResource(r)).resourceId}const O9=S("edit-mathjax");class D_{constructor(){m(this,"editMathjaxPopup",null);m(this,"onChange",null);m(this,"tex","");m(this,"handleShow",()=>{setTimeout(()=>{this.getTextarea().focus()})});m(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,!0))}});m(this,"handleKeyup",t=>{var e;t.isComposing||(t.key==="Escape"&&((e=this.editMathjaxPopup)==null||e.close("cancelBar")),this.handleChange(t.target.value))});m(this,"handleChange",He.default(t=>{var e;(e=this.onChange)==null||e.call(this,t,!1)},300))}editMathjax(t,e,o){if(!this.editMathjaxPopup)this.editMathjaxPopup=new Xa(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=w("textarea",["mathjax-editor-textarea"],null);return e.value=t,e.addEventListener("keyup",this.handleKeyup),e}getTextarea(){g(O9,this.editMathjaxPopup,"no exists mathjax editor popup");const t=this.editMathjaxPopup.content.querySelector("textarea");return g(O9,t,"no textarea"),t}destroy(){var t;this.onChange=null,(t=this.editMathjaxPopup)==null||t.removeAllListeners()}}function _9(n,t,e,o){n.addCustom("mathjax-editor",()=>new D_).editMathjax(t,e.trim(),o)}function F9(){return{insert:" ",attributes:{id:K(),box:!0,type:"math",tex:" ",src:"",created:Date.now()}}}function pf(n,t){const e=n.getBoxData(t),o=ot(t);if(!o)return;const r=Mi(o,t);n.selection.selectBlock(o,r.start,r.end);const i=async(s,l)=>{if(!s.trim()){n.updateBoxData({...e,tex:s,src:null});return}try{await wo.lock("convertAndUploadMathjax");const a=await x0(n,s);n.updateBoxData({...e,tex:s,src:a})}catch(a){const d=n.getBoxData(t);n.addCustom(`mathjax-box-${d.id}`,()=>new E0).setError(a),n.updateBoxData({...e,tex:s,src:""})}finally{wo.release("convertAndUploadMathjax"),l&&n.focus()}};_9(n,t,e.tex,i)}const P9=S("mathjax-box");function I0(n,t){n.selection.updateSelection(null);const e=t.target;!e||!(e instanceof HTMLElement)||n.domEvents.removeEventListener(e,null,I0)}async function S_(n,t,e){try{if(!t.tex.trim())return;const o=await R9(n,t.tex),r=n.findBoxById(t.id);if(!r)return;const i=Hm(r);i.innerHTML="";const s=w("img",["mathjax"],i);s.src=o,e.setDataUrl(o),n.domEvents.addEventListener(s,"load",I0)}catch(o){e.setError(o);const r=n.findBoxById(t.id);if(!r)return;const i=r.querySelector(".mathjax-tex-text");W(i,"mathjax-error"),i.innerText=o.message,n.selection.updateSelection(null)}}function L_(n,t,e,o){const r=o,i=n.addCustom(`mathjax-box-${r.id}`,()=>new E0);if(r.src||i.dataUrl){const a=w("img",["mathjax"],e);a.src=n.doc.buildResourceUrl(r.src||i.dataUrl),n.domEvents.addEventListener(a,"load",I0);return}const s=["mathjax-tex-text"];let l=r.tex;l.trim()?i.error&&(l=i.error.message,s.push("mathjax-error")):l=R.t("mathjax.emptyText"),w("span",s,e,l),S_(n,r,i)}function M_(n,t){const e={id:K(),box:!0,type:"math",tex:t,src:"",created:Date.now()};return x0(n,t).then(o=>{if(!n.findBoxById(e.id))return;const i={...e,src:o};n.updateBoxData(i)}).catch(o=>{P9.error(`failed to convert and upload mathjax: ${JSON.stringify(o)}`)}),e}function R_(n,t,e,o){const r=t;return o==="text"?r.tex:o==="markdown"?` $${r.tex}$ `:r.src?`<img src="${n.doc.buildResourceUrl(r.src,{withToken:!0})}" />`:`<code>$${r.tex}$</code>`}function O_(n,t,e){const o=ot(t);g(P9,o,"failed to get block"),!(n.readonly||!n.isBlockWritable(o))&&pf(n,t)}function __(){return{abstract:R.t("mathjax.abstract")}}const T0={boxType:"math",updateBoxContent:L_,convertFrom:M_,convertTo:R_,handleClickBox:O_,getBoxProperties:__};async function F_(n,t,e){try{const o=t.embedData,r=await R9(n,o.mathjaxText),i=n.findBlockById(t.id);if(!i)return;const s=Rt(i);s.innerHTML="";const l=w("img",["mathjax"],s);l.src=r,e.setDataUrl(r)}catch(o){e.setError(o)}}function P_(n,t){if(n.readonly||!t.target||!(t.target instanceof Node))return;const e=ot(t.target);if(!e||!Le(e)||Un(e)!=="math")return;const o=Rt(e),r=o.querySelector("img")||o.querySelector("span.mathjax-tex-text");if(!r||!Kt(r,t.target))return;const s=n.getBlockData(e).embedData;_9(n,r,s.mathjaxText,async l=>{const a=await x0(n,l),d={mathjaxText:l,src:a};n.updateEmbedData(e,d)})}function N_(n,t,e){const o=e.embedData,r=n.addCustom(`mathjax-block-${e.id}`,()=>new E0);if(n.domEvents.addEventListener(t,"click",P_),o.src||r.dataUrl){const i=w("img",["mathjax"],t);i.src=n.doc.buildResourceUrl(o.src||r.dataUrl);return}r.error,w("span",["mathjax-tex-text"],t,o.mathjaxText),F_(n,e,r)}function $_(n,t,e){if(!tt(n,t))return null;const o=n.getBlockString(t).trim();if(!o||!o.startsWith("$$")||!o.endsWith("$$"))return null;const r=Bm(o,"$");if(!r)return null;const i={mathjaxText:r,src:""};return{blockData:{id:K(),type:"embed",embedType:"math",embedData:i}}}function H_(n){return{name:"Mathjax"}}function j_(n,t){const e=Rt(t);n.domEvents.removeAllListeners(e)}function U_(n,t,e,o){const r=t.embedData;return o==="html"?`<img src="${n.doc.buildResourceUrl(r.src,{withToken:!0})}" />`:o==="markdown"?`
394
+ </svg>`;function NO(n,t){const e=mc(t);if(e!=="text-only"){if(e==="checked"){n.innerHTML=FO;return}if(e==="unchecked"){n.innerHTML=PO;return}n.innerText=OO(t)}}function $O(n){const t=w("div",["list-container"],null),e=w("button",["list-marker"],t);return NO(e,n),t}function v9(n){let t=Zt(n);if(!t)return null;const e=Gs(n);for(;t!==e;){if(g(ke,t,"no next block"),Ht(t))return Cn(t)>Cn(n)?t:null;if(t=Zt(t),!t)return null}return null}function A0(n){const t=[];let e=v9(n);if(!e)return t;for(;e;){const o=Gs(e);t.push({block:e,children:A0(e)}),e=o}return t}function HO(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 y9(n,t){return Cn(t)!==1}function k9(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&&k9(n,o.children,r.groupId)})}function b0(n,t){if(!y9(n,t))return!1;const e=Cn(t);if(e===1)return!1;let o=K(),r=1,i=Zn(t);const s=e-1,l=a0(t);l&&(o=uc(l),r=ho(l)+1,i!=="text-only"&&(i=Zn(l)));const a=A0(t),d=n.getBlockData(t),h={...d,groupId:o,level:s,start:r,...c0(i)};n.updateBlockData(t,h),n.doc.beginBatchUpdate(),k9(n,a,d.groupId),n.doc.endBatchUpdate(),new Zs(n,t).fix();const A=v9(t);return A&&new Zs(n,A,{resetStart:!0,resetGroupId:!0}).fix(),!0}function gc(n,t){_e(t);const e=n.getBlockData(t),o={id:K(),type:"text",text:e.text};e.heading&&(o.heading=e.heading),e.heading&&(o.heading=e.heading);const r=new hf(n,t),i=nt(t),s=bt(t);n.deleteBlock(t);const l=mh(o.id,0);n.insertBlock(at(i),s,o,l),r.fix()}function jO(n){if(!n.selection.range.isCollapsed())return!1;const t=n.selection.focusedBlock;if(!Ht(t))return!1;const e=n.selection.range.focus;return!e.isSimple()||e.offset!==0?!1:Cn(t)===1?(gc(n,t),!0):(b0(n,t),!0)}const UO=S("list-block");function zO(n,t,e){g(UO,Ht(t),"not a list block");const o={...n.getBlockData(t),id:K()};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==null?void 0:o.checkbox)==="checked"&&(o.checkbox="unchecked"),o}function VO(n){if(_e(n),!af(n))return n;let t=Qi(n);for(;t;){if(!af(t))return t;t=Qi(t)}return null}function WO(n,t,e,o){const r=new Zs(n,o),i=ho(o)+1;Yl(n,t,e,{forceInsertAfter:!0,newBlockData:zO(n,o,{start:i})}),r.fix()}function qO(n){var s;if(n.selection.range.isCollapsed()){const l=n.selection.focusedBlock;if(Ht(l)&&ut(n,l)===0)return gc(n,l),!0}n.clearSelectedContents();const t=n.selection.focusedBlock;if(!Ht(t))return!1;const e=n.selection.range.focus;if(!e.isSimple())return!1;const o=e.offset,i=(s=o===ut(n,t)?VO(t):t)!=null?s:t;return WO(n,t,o,i),!0}function w9(n){g(ke,Ht(n),"not a list block");const{level:t}=Zi(n);let e=ce(n);for(;e;){if(Ht(e)){const{level:o}=Zi(e);if(t===o)return e;if(o<t)return null}e=ce(e)}return null}function B9(n,t){return _e(t),w9(t)?Cn(t)<qR:!1}function GO(n,t,e){let o=ce(t);g(ke,o,"no prev brother");const r=Cn(e);for(;o;){if(o===e)return null;if(Ht(o)&&Cn(o)===r+1)return o;o=ce(o)}return null}function E9(n,t){if(!B9(n,t))return!1;_e(t);const e=w9(t);g(ke,e,"no list prev brother");const o=e,r=GO(n,t,o),i=Cn(o)+1;let s=K(),l=1,a=Zn(t);r&&(s=uc(r),l=ho(r)+1,a=Zn(r));const d=A0(t),p={...n.getBlockData(t),groupId:s,level:i,start:l,...c0(a)};return n.updateBlockData(t,p),n.doc.beginBatchUpdate(),HO(d).forEach(v=>{const B=n.getBlockData(v);n.updateBlockData(v,{...B,level:B.level+1})}),n.doc.endBatchUpdate(),!0}function ZO(n,t,e){return t.length===0||!t.every(o=>Ht(o.block))?!1:e==="increase"?B9(n,t[0].block):y9(n,t[0].block)}function x9(n,t,e){if(!ZO(n,t,e))return!1;const o=t[0].block,r=Cn(o),i=t.filter(d=>Cn(d.block)<=r),s=u9(o,{withSelf:!1}),l=new Set(i.map(d=>d.block)),a=s.filter(d=>!l.has(d));return n.undoManager.runInGroup(()=>{let d=null;a.length>0&&(d=new Zs(n,a[0])),i.forEach(h=>{e==="increase"?E9(n,h.block):b0(n,h.block)}),d==null||d.fix()}),!0}function QO(n,t){return E9(n,t)}function YO(n,t){return b0(n,t)}function JO(n){const t=n.selection.range.getSelectedBlocks();if(t.length>1)return x9(n,t,"increase"),!0;const e=t[0].block;if(!Ht(e))return!1;const o=new hf(n,e);return QO(n,e)&&(o.fix(),new Zs(n,e).fix()),!0}function KO(n){const t=n.selection.range.getSelectedBlocks();if(t.length>1)return x9(n,t,"decrease"),!0;const e=t[0].block;return Ht(e)?(YO(n,e),!0):!1}class XO{constructor(t){this.editor=t}handleBeforeKeyDown(t,e){const o=t.selection.range.getSelectedBlocks();if(o.length===0||!o.some(i=>Ht(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||!Ht(e.block)||Rr(t,"Shift+Enter")?!1:this.editor.undoManager.runInGroup(()=>qO(this.editor))}handleBackspace(){return this.editor.undoManager.runInGroup(()=>jO(this.editor))}handleTab(t){return Rr(t,"Shift+Tab")?this.editor.undoManager.runInGroup(()=>KO(this.editor)):this.editor.undoManager.runInGroup(()=>JO(this.editor))}}class t_{constructor(t){m(this,"effectedBlockIds",new Map);m(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;Ht(i)&&e.add(i)});const o=new Map;Array.from(e.values()).forEach(r=>{var a;const i=gu(r),{start:s}=Zi(i);o.set(it(i),s);const l=(a=KR(r))!=null?a:r;o.set(it(l),s)}),this.effectedBlockIds=o});m(this,"handleAfterClearSelection",()=>{Array.from(this.effectedBlockIds.entries()).forEach(([t,e])=>{const o=this.editor.findBlockById(t);!o||m0(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 e_=S("customize-list-start-menu");class n_{constructor(t){m(this,"popup");m(this,"block",null);m(this,"show",(t,e)=>{const o=e.querySelector("div.list-container");g(e_,o,"list-block mark does not exist"),this.block=e,this.popup.manualShow(o,{theme:"light"})});m(this,"createDialogContent",()=>{const t=w("div",["customize-start-panel"],null);w("span",["customize-start-panel-title"],t,R.t("list.numberLabel"));const e=this.createNumericInput();t.appendChild(e);const o=w("button",["customize-start-panel-button"],t,R.t("list.confirm"));return this.editor.domEvents.addEventListener(t,"keydown",this.handleKeydown),this.editor.domEvents.addEventListener(o,"click",this.handleOk),t});m(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=ho(t);!o||!r||requestAnimationFrame(()=>{r.focus(),r.value=String(i)})});m(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(()=>{fc(this.editor,[o,...dc(o)],r,{resetGroupId:!0})}),this.popup.close("clickItem"))});m(this,"handleKeydown",(t,e)=>{const o=e;o.isComposing||(o.key==="Escape"?this.popup.close("cancelBar"):o.key==="Enter"&&this.handleOk())});this.editor=t,this.popup=new Xa(this.createDialogContent()),this.popup.on("show",this.handleDialogShow)}destroy(){this.popup.destroy()}createNumericInput(){const t=w("input",["customize-start-panel-input"],null);t.type="number",t.min="1";const e=()=>{const r=t.value.replace(/[^\d]/g,"").replace(/^0+/,""),i=parseInt(r,10);i<=0||Number.isNaN(i)?t.value="":t.value=r};return this.editor.domEvents.addEventListener(t,"input",e),t}}function o_(n,t){return uc(n)===uc(t)}function r_(n,t){const e=c9(t);return e?o_(e,t)?ho(e)!==ho(t)-1:!0:!1}function i_(n,t){return Qi(t)?!0:ho(t)!==1}function s_(n,t){return _e(t),[{id:"continue-numbering",name:R.t("list.continueList"),states:r_(n,t)?[]:["disabled"]},{id:"start-new-list",name:R.t("list.restartList"),states:i_(n,t)?[]:["disabled"]},{id:"set-numbering-value",name:R.t("list.changeNumber")}]}function l_(n,t,e){var o,r;if(_e(t),e.id==="continue-numbering"){const i=c9(t);i&&fc(n,[t,...dc(t)],ho(i)+1,{resetGroupId:!0,groupId:uc(i)})}if(e.id==="start-new-list"&&n.undoManager.runInGroup(()=>{fc(n,[t,...dc(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 n_(n)).show(n,t)}}class c_{constructor(t){m(this,"menu");m(this,"handleClick",(t,e)=>{const o=jl(e,"div.list-container");if(o&&this.editor.isWritable()){const r=ot(o);g(ke,r,"no parent block"),_e(r);const i=t.getBlockData(r);if(i&&i.checkbox){t.updateBlockData(r,{...i,checkbox:i.checkbox==="checked"?"unchecked":"checked"});return}if(Zn(r)==="unordered")return;this.menu.updateItems(this.getCommandItems(r)),this.menu.manualShow(o),this.activeList(o,!0)}});m(this,"handleMenuClose",()=>{var e;const t=(e=this.menu.tippyInstance)==null?void 0:e.reference;t&&this.activeList(t,!1)});m(this,"handleMenuClick",(t,e)=>{var r;const o=(r=this.menu.tippyInstance)==null?void 0:r.reference;if(o){const i=ot(o);i&&l_(this.editor,i,e)}});this.editor=t,this.editor.addListener("click",this.handleClick),this.menu=new zs([]),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 s_(this.editor,t)}activeList(t,e){const o=ot(t);!o||(e?(W(t,"active"),W(o,"active")):(et(t,"active"),et(o,"active")))}}class a_{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(!Ht(r)||!m9(r))return!1;if(e.key==="ArrowUp"||e.key==="ArrowLeft"){const i=Ds(r);return i&&t.selection.selectBlock(i,ut(t,i)),!0}if(e.key==="ArrowDown"||e.key==="ArrowRight"){const i=Ss(r);return i&&t.selection.selectBlock(i,0),!0}return(e.key==="Delete"||e.key==="Backspace"||e.key==="Escape")&&p9(t,r),!0}}function u_(n,t,e,o,r){op(n,"list-block-init",()=>{setTimeout(()=>{n.input.addHandler(new a_(n)),n.input.addHandler(new XO(n)),n.addCustom("list-clear-selection-handler",()=>new t_(n)),n.addCustom("list-marker-menu",()=>new c_(n))})});const i=In.createBlockContent(n,t,e,o,r),s=r,{level:l,start:a,groupId:d}=s,h=mc(s);o.setAttribute("data-list-level",`${l}`),o.setAttribute("data-list-start",`${a||1}`),o.setAttribute("data-list-group-id",`${d}`),o.setAttribute("data-list-type",h);const p=$O(s);return o.insertBefore(p,i),s.viewAsMindmap?setTimeout(()=>{const A=n.getBlockById(r.id);A&&uf(n,A,{},{mindmapTools:f0,saveData:!1})}):setTimeout(()=>{const A=n.getBlockById(r.id);A&&g9(n,A)}),i}const d_={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"}},h_={list:{confirm:"Confirm",setStart:"Set number",continueList:"Continue numbering",restartList:"Start a new list",changeNumber:"Set numbering value",numberLabel:"Numbering order",mention:{tooltip:"Mention and notify users"}},mindmap:{viewAsMindMap:"View as MindMap",autoFit:"Auto zoom",fullScreen:"Full screen",close:"Close",exitFullscreen:"Exit full screen"}},f_={list:{confirm:"OK",setStart:"\u756A\u53F7\u3092\u8A2D\u5B9A",continueList:"\u9023\u756A\u3092\u8A2D\u5B9A",restartList:"\u65B0\u3057\u3044\u30EA\u30B9\u30C8\u3092\u4F5C\u6210",changeNumber:"\u756A\u53F7\u3092\u7DE8\u96C6",numberLabel:"\u756A\u53F7",mention:{tooltip:"\u30E1\u30F3\u30B7\u30E7\u30F3\u304A\u3088\u3073\u901A\u77E5"}},mindmap:{viewAsMindMap:"\u30DE\u30A4\u30F3\u30C9\u30DE\u30C3\u30D7\u3067\u8868\u793A",autoFit:"\u81EA\u52D5\u30D5\u30A3\u30C3\u30C8",fullScreen:"\u5168\u753B\u9762\u8868\u793A\u306E\u30AA\u30F3",close:"\u9589\u3058\u308B",exitFullscreen:"\u5168\u753B\u9762\u8868\u793A\u306E\u30AA\u30D5"}};R.mergeLang({"zh-CN":d_,"en-US":h_,"ja-JP":f_});const ynt="",I9={...In,blockType:"list",createBlockContent:u_,convertFrom:RO,convertTo:_O,handleDrop:wO,notify:bO},v0=S("paragraph");class m_{constructor(t){m(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":[R.t("commands.unordered"),Bo("CtrlOrCmd+Shift+L"),yL],"ordered-list":[R.t("commands.ordered"),Bo("CtrlOrCmd+Shift+U"),vL],"check-list":[R.t("commands.check"),void 0,kL],link:[R.t("commands.link"),Bo("CtrlOrCmd+K"),mv],quoted:[R.t("commands.quote"),void 0,wL]};if(tt(t,e)){const i=it(e),s=Dt(e),l=Io(t,e),a=t.getBlockData(e);Object.entries(r).forEach(([d,[h,p,A]])=>{const v=[];if(this.isChecked(a,d)&&v.push("checked"),d==="link"){if(!t.selection.range.isSimple())return;t.selection.range.getSelectedBlocks().length!==1&&v.push("disabled")}o.push({blockId:i,blockType:s,blockKind:l,id:d,name:h,desc:p,states:v,icon:A,groupIndex:600})})}return o}convertLink(t,e,o){g(v0,$r(e.start),""),g(v0,$r(e.start),"");const r="bottom-start",i=e.start.offset,s=e.end.offset,l=(v,B)=>{t.undoManager.runInGroup(()=>{try{const D=t.selection.range.isCollapsed();let T;if(D){T=Hr(t.getBlockText(o),s,v,{link:B}),t.setBlockText(o,T);return}T=dh(t.getBlockText(o),i,s,v),T=Ia(i,v.length,T,"link",B),t.setBlockText(o,T),t.selection.selectBlock(o,i+v.length),t.focus()}catch(D){v0.error(D)}})},a=()=>{t.selection.selectBlock(o,s),t.focus()},d=Ti(t,o,e)[0];if(!d)return;const h=Li(t,o,"link-button-anchor",d),p=t.getBlockText(o),A=Ta(p,i);fu(t,{target:h,linkText:t.getSelectedText(),linkUrl:(A==null?void 0:A.link)||"",onFinished:l,onClose:a,placement:r})}convertToList(t,e,o){const r=Kd(t,e,"list",{offset:0,data:{listType:o}});r&&t.undoManager.runInGroup(()=>{const i=bt(e),s=nt(e);t.insertBlock(at(s),i,r.blockData),t.deleteBlock(e),t.focus()})}executeCommand(t,e,o,r){var a;if(!tt(t,e))return!1;const i=r.id,s=(a=r.states)==null?void 0:a.includes("checked");let l=!1;if(i==="unordered-list"&&(s?gc(t,e):this.convertToList(t,e,"unordered"),l=!0),i==="ordered-list"&&(s?gc(t,e):this.convertToList(t,e,"ordered"),l=!0),i==="check-list"&&(s?gc(t,e):this.convertToList(t,e,"unchecked"),l=!0),i==="quoted"){const h=t.getBlockData(e).quoted;t.updateBlockData(e,{quoted:h?void 0:!0}),t.focus(),l=!0}if(i==="link"){const d=sf(t);d.disableTextToolbar(),d.hide(),setTimeout(()=>{d.enableTextToolbar()},1e3),this.convertLink(t,o,e),l=!0}return l}}const g_={left:tu,right:Sp,center:Lp};class p_{constructor(t){m(this,"id","BlockAlignProvider");this.editor=t}applyAlignStyle(t,e,o){Object.keys(g_).includes(o)?t.updateBlockData(e,{align:o}):t.updateBlockData(e,{align:null})}isChecked(t,e){return t.align===e}getAvailableCommands(t,e,o){if(tt(t,e)){const r=it(e),i=Dt(e),s=Io(t,e),l=t.getBlockData(e),a=d=>{var p;const h=w("span",["toolbar-item-name-container"],null);for(const A of d.children)if((p=A.states)!=null&&p.includes("checked"))return h.innerHTML=A.icon||tu,h;return h.innerHTML=tu,h};return[{id:"align",name:R.t("commands.alignGroup"),blockId:r,blockType:i,blockKind:s,groupIndex:700,dropdown:!0,element:a,manualShowChildren:!0,childrenPlacement:"bottom-start",defaultCheckedChildren:["align-left"],children:[{id:"align-left",name:R.t("commands.alignLeft"),icon:tu,states:this.isChecked(l,"left")?["checked"]:[]},{id:"align-center",name:R.t("commands.alignCenter"),icon:Lp,states:this.isChecked(l,"center")?["checked"]:[]},{id:"align-right",name:R.t("commands.alignRight"),icon:Sp,states:this.isChecked(l,"right")?["checked"]:[]}],childrenType:"menu"}]}return[]}executeCommand(t,e,o,r){if(!tt(t,e))return!1;if(r.id.startsWith("align")){const i=r.id.replace(/^align-/,"");return this.applyAlignStyle(t,e,i),this.editor.focus(),!0}return!1}}function C_(n){const e=n.selection.range;if(e.isCollapsed()||e.start.blockId!==e.end.blockId||!e.start.isSimple()||!e.end.isSimple()||e.end.offset-e.start.offset!==1)return!1;const o=n.getBlockById(e.start.blockId);return Sa(n,o,e.start.offset).charType==="box"}const A_=S("toolbar-handler"),b_={id:"",name:"",type:"separator"};class pc{constructor(t){m(this,"toolbar");m(this,"toolbarType","object");m(this,"mouseDown",!1);m(this,"oldRange",null);m(this,"hoveringBlock",null);m(this,"hoveringTextChild",null);m(this,"_disableTextToolbar",!1);m(this,"handleButtonClick",(t,e)=>{this.toolbarType==="text"?(this.editor.editorCommandProviders.executeCommand(this.editor.selection.range,e,{}),this.showTextToolbar("click")):this.hoveringBlock&&UR(this.editor,this.hoveringBlock,this.hoveringTextChild,e)});m(this,"handleClose",()=>{Fp(this.editor)&&this.editor.focus()});m(this,"handleClosing",(t,e)=>{if(this.toolbarType==="object"){const o=iC(e);if(this.hoveringBlock===o)return!1}return!0});m(this,"handleDocumentMouseDown",t=>{t.button===0&&(document.addEventListener("mouseup",this.handleDocumentMouseUp),this.mouseDown=!0)});m(this,"handleDocumentMouseUp",()=>{document.removeEventListener("mouseup",this.handleDocumentMouseUp),this.mouseDown=!1,this.handleSelectionChange(this.editor)});m(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("fromHover");return}this.showObjectToolbar(r)}});m(this,"handleSelectionChange",He.default(t=>{var o;if(g(A_,t===this.editor,"editor mismatch"),t.selection.range.isCollapsed()||this.mouseDown){if(this.toolbarType==="object"){const r=(o=this.toolbar.tippyInstance)==null?void 0:o.reference,i=this.editor.selection.focusedBlock;if(r&&Kt(r,i))return}this.toolbar.close("selectionChange"),this.oldRange=null;return}if(!this.editor.isWritable()){this.toolbar.close("selectionChange"),this.oldRange=null;return}if(t.selection.range.getSelectedBlocks().length===0){this.toolbar.close("selectionChange"),this.oldRange=null;return}this.oldRange&&this.oldRange.isEqual(t.selection.range)||(this.oldRange=t.selection.range,this.showTextToolbar("selectionChange"))},50));this.editor=t;const e=t.options.componentsOptions.popover;this.toolbar=new ou([],void 0,{tooltipId:t.clientId,id:"editor-toolbar",overflowBoundary:e==null?void 0:e.overflowBoundary,refuseOverflow:!0,padding:20}),this.toolbar.on("click",this.handleButtonClick),this.toolbar.on("close",this.handleClose),this.toolbar.on("closing",this.handleClosing),this.bindEvents(),t.addListener("selectionChanged",this.handleSelectionChange),pe.get(t).addListener("childChange",this.handleHoveringBlockChildChange),pe.get(t).addFilter(this),t.editorCommandProviders.registerCommandProvider(new VR(t)),t.editorCommandProviders.registerCommandProvider(new m_(t)),t.editorCommandProviders.registerCommandProvider(new p_(t))}disableTextToolbar(){this._disableTextToolbar=!0}enableTextToolbar(){this._disableTextToolbar=!1}hide(){this.toolbar.close("selectionChange")}destroy(){this.unbindEvents(),this.toolbar.destroy(),this.editor.removeListener("selectionChanged",this.handleSelectionChange),pe.get(this.editor).removeListener("childChange",this.handleHoveringBlockChildChange)}isInBlock(t,e){return t!==this.hoveringBlock?!1:!!(e.target&&e.target instanceof Node&&this.toolbar.popper&&Kt(this.toolbar.popper,e.target))}bindEvents(){document.addEventListener("mousedown",this.handleDocumentMouseDown)}unbindEvents(){document.removeEventListener("mousedown",this.handleDocumentMouseDown)}update(t){this.showTextToolbar(t)}showTextToolbar(t){var D,T;if(this._disableTextToolbar||!this.editor.isWritable())return;const o=this.editor.selection.range.getSelectedBlocks();if(o.length===0)return;const r=o[0];if(!r)return;if(o.length===1&&Le(r.block)){t==="click"&&this.showObjectToolbar(null);return}if(C_(this.editor))return;if(nt(r.block)===this.editor.rootContainer&&bt(r.block)===0){this.toolbar.close("selectionChange");return}const i=this.editor.editorCommandProviders.getCommands(this.editor.selection.range),s=new Map;i.forEach(_=>{const M=_.groupIndex,H=s.get(M);H?H.push(_):s.set(M,[_])});const l=[[]],a=Array.from(s.entries()).sort((_,M)=>_[0]-M[0]);for(let _=0;_<a.length;_++){const[,M]=a[_];if(M.length===0)continue;let H=l[l.length-1];H.length>0&&H[H.length-1].groupIndex!==M[M.length-1].groupIndex&&(H=[],l.push(H)),H.push(...rf(M))}if(l.length===0){this.toolbar.close("selectionChange");return}this.toolbarType="text";const d=[];if(l.forEach((_,M)=>{const H=_.sort((z,q)=>{var rt,ft;return((rt=z.order)!=null?rt:0)-((ft=q.order)!=null?ft:0)});d.push(...H),M!==l.length-1&&d.push(b_)}),d.length===0){this.toolbar.close("selectionChange");return}this.toolbar.updateItems(d);const h=o[o.length-1],p=!this.editor.selection.range.isReverse()&&h!==r,A=p?h:r,v=OR(this.editor,A),B=Li(this.editor,A.block,"editor-quick-menu",v);this.toolbar.manualShow(B,{placement:p?"bottom":"top"}),(T=(D=this.toolbar.tippyInstance)==null?void 0:D.popperInstance)==null||T.update()}showObjectToolbar(t){var l,a;if(!this.hoveringBlock||this.mouseDown)return;const e=this.hoveringBlock,o=this.hoveringTextChild,{commands:r,element:i}=$R(this.editor,e,o);if(!r.length||!i){this.toolbar.close("fromHover");return}this.toolbarType="object",this.toolbar.isVisible&&((a=(l=this.toolbar)==null?void 0:l.tippyInstance)==null?void 0:a.reference)!==i&&this.toolbar.close("fromHover");const s=()=>{let d;const h=i.getClientRects();if(h.length>1){if(d=o?h[h.length-1]:h[0],t)for(let p=0;p<h.length;p++){const A=h[p],v=new DOMRect(A.x-4,A.y-4,A.width+8,A.height+8);if(v.x<t.clientX&&t.clientX<v.right&&v.y<t.clientY&&t.clientY<v.bottom){d=A;break}}}else{if(d=i.getBoundingClientRect(),o){const p=o.getBoundingClientRect();return new DOMRect(p.x,p.y,p.width,p.height)}return new DOMRect(h[0].x,h[0].y,h[0].width,h[0].height)}if(t){const p=d.y,A=t.clientX;return new DOMRect(A,p,10,d.height)}return d};this.toolbar.updateItems(r),this.toolbar.isVisible||this.toolbar.manualShow(i,{placement:o?"bottom":"top",getReferenceClientRect:s})}static register(t){return t.addCustom("toolbar-handler",e=>new pc(e))}static get(t){return t.getCustom("toolbar-handler")}}function gf(n,t,e){n.getBlockData(t).heading===e?n.updateBlockData(t,{heading:null}):n.updateBlockData(t,{heading:e})}function T9(n,t,e){["left","center","right"].includes(e)?n.updateBlockData(t,{align:e}):n.updateBlockData(t,{align:null})}function y0(n,t){const o=n.getBlockData(t).quoted;n.updateBlockData(t,{quoted:o?void 0:!0})}function k0(n,t){return!!(n[t]||n.level&&(n.ordered===!0&&!n.checkbox&&t==="ordered-list"||n.ordered===!1&&!n.checkbox&&t==="unordered-list")||t==="check-list"&&n.checkbox)}function w0(n,t,e){if(!n.selection.range.focus.isSimple())return;const r=n.getBlockData(t);let i;switch(e){case"unordered-list":i=k0(r,"unordered-list")?void 0:"unordered";break;case"ordered-list":i=k0(r,"ordered-list")?void 0:"ordered";break;case"check-list":i=k0(r,"check-list")?void 0:"unchecked";break}if(i){const s=Kd(n,t,"list",{offset:0,data:{listType:i}});s&&n.undoManager.runInGroup(()=>{const l=bt(t),a=nt(t);n.deleteBlock(t),n.insertBlock(at(a),l,s.blockData)})}else gc(n,t)}const v_=Object.freeze(Object.defineProperty({__proto__:null,applyHeadingStyle:gf,applyAlignStyle:T9,applyQuoteStyle:y0,applyList:w0},Symbol.toStringTag,{value:"Module"})),y_=[kp,wp,Bp,Ep,xp,Ip,Tp,Dp],k_={Unordered:Cv,Ordered:Av,Checkbox:gv,Quote:pv};function D9(n,t){const e=n;e.blockOptions=t,e.itemType="insert-block",n.children&&n.children.forEach(o=>D9(o,t))}function w_(){return{name:"basic",insertBlockCommandItems:[{id:"text",icon:nu,name:R.t("commands.text"),order:0,group:"basics",value:"text"}]}}function B0(n=1){var r;const t={name:"basic",insertBlockCommandItems:[]};let e=lf();e<=4?e=5:e<8&&(e+=1);let o=n;for(;o<=e;){const i=`heading-${o}`;(r=t.insertBlockCommandItems)==null||r.push({id:i,icon:y_[o-1],name:R.t("quickMenu.basic.heading.title",{heading:String(o)}),order:o,group:"basics",value:String(o),subText:pn(i)}),o++}return t}function B_(){const n={name:"basic",insertBlockCommandItems:[]};return["Unordered","Ordered","Checkbox","Quote"].forEach((e,o)=>{var i;const r=`insert-${e.toLocaleLowerCase()}`;(i=n.insertBlockCommandItems)==null||i.push({id:r,name:R.t(`quickMenu.basic.${e.toLocaleLowerCase()}`),icon:k_[e],value:e.toLocaleLowerCase(),group:"basics",order:10+o,subText:pn(r)})}),n}class S9{constructor(t){this.withPlainText=t}getCommands(){const t=w_(),e=B0(),o=B_();return[...this.withPlainText?t.insertBlockCommandItems||[]:[],...e.insertBlockCommandItems||[],...o.insertBlockCommandItems||[]]}updateBlock(t,e,o,r){const{value:i,id:s}=r;return s.startsWith("heading-")?gf(t,o,Number.parseInt(i!=null?i:"1",10)||1):i==="ordered"||i==="unordered"||i==="checkbox"?w0(t,o,{ordered:"ordered-list",unordered:"unordered-list",checkbox:"check-list"}[i]):i==="quote"&&y0(t,o),null}async handleUpdateBlockCore(t,e){const o=t.getBlockByIndex(e.containerId,e.blockIndex);return this.updateBlock(t,e.containerId,o,e.item)}async handleInsertEmptyBlockCore(t,e){const{containerId:o,blockIndex:r}=e,i=t.insertTextBlock(void 0,o,r);return this.updateBlock(t,e.containerId,i,e.item)}async executeCommand(t,e,o){if(o.from==="quick-menu"){const r=t.getBlockById(o.blockId),i=t.getParentContainer(r),s=at(i),l=t.getBlockIndex(r);t.undoManager.runInGroup(()=>this.handleUpdateBlockCore(t,{item:e,containerId:s,blockIndex:l})),t.focus()}else o.from==="block-menu"&&(t.undoManager.runInGroup(()=>this.handleInsertEmptyBlockCore(t,{item:e,containerId:o.containerId,blockIndex:o.blockIndex})),t.focus());return null}}const L9={basics:100,system:200,common:300,thirdParty:400};class E0{constructor(){m(this,"dataUrl","");m(this,"error",null)}destroy(){}setDataUrl(t){this.error=null,this.dataUrl=t}setError(t){this.dataUrl="",this.error=t}}const E_=S("mathjax-converter"),x_="MathJax-script";async function I_(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 vs(e,x_)}function T_(){try{window.MathJax&&window.MathJax.texReset()}catch{}}async function M9(n,t){const e="mathjax2Svg";try{await wo.lock(e),T_(),await I_(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 E_.error(o),o}finally{wo.release(e)}}async function R9(n,t){const e=await M9(n,t);return e?await Sm(e,"image/svg+xml"):""}async function x0(n,t){const o=await M9(n,t),r=new File([o],"math.svg");return(await n.doc.uploadResource(r)).resourceId}const O9=S("edit-mathjax");class D_{constructor(){m(this,"editMathjaxPopup",null);m(this,"onChange",null);m(this,"tex","");m(this,"handleShow",()=>{setTimeout(()=>{this.getTextarea().focus()})});m(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,!0))}});m(this,"handleKeyup",t=>{var e;t.isComposing||(t.key==="Escape"&&((e=this.editMathjaxPopup)==null||e.close("cancelBar")),this.handleChange(t.target.value))});m(this,"handleChange",He.default(t=>{var e;(e=this.onChange)==null||e.call(this,t,!1)},300))}editMathjax(t,e,o){if(!this.editMathjaxPopup)this.editMathjaxPopup=new Xa(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=w("textarea",["mathjax-editor-textarea"],null);return e.value=t,e.addEventListener("keyup",this.handleKeyup),e}getTextarea(){g(O9,this.editMathjaxPopup,"no exists mathjax editor popup");const t=this.editMathjaxPopup.content.querySelector("textarea");return g(O9,t,"no textarea"),t}destroy(){var t;this.onChange=null,(t=this.editMathjaxPopup)==null||t.removeAllListeners()}}function _9(n,t,e,o){n.addCustom("mathjax-editor",()=>new D_).editMathjax(t,e.trim(),o)}function F9(){return{insert:" ",attributes:{id:K(),box:!0,type:"math",tex:" ",src:"",created:Date.now()}}}function pf(n,t){const e=n.getBoxData(t),o=ot(t);if(!o)return;const r=Mi(o,t);n.selection.selectBlock(o,r.start,r.end);const i=async(s,l)=>{if(!s.trim()){n.updateBoxData({...e,tex:s,src:null});return}try{await wo.lock("convertAndUploadMathjax");const a=await x0(n,s);n.updateBoxData({...e,tex:s,src:a})}catch(a){const d=n.getBoxData(t);n.addCustom(`mathjax-box-${d.id}`,()=>new E0).setError(a),n.updateBoxData({...e,tex:s,src:""})}finally{wo.release("convertAndUploadMathjax"),l&&n.focus()}};_9(n,t,e.tex,i)}const P9=S("mathjax-box");function I0(n,t){n.selection.updateSelection(null);const e=t.target;!e||!(e instanceof HTMLElement)||n.domEvents.removeEventListener(e,null,I0)}async function S_(n,t,e){try{if(!t.tex.trim())return;const o=await R9(n,t.tex),r=n.findBoxById(t.id);if(!r)return;const i=Hm(r);i.innerHTML="";const s=w("img",["mathjax"],i);s.src=o,e.setDataUrl(o),n.domEvents.addEventListener(s,"load",I0)}catch(o){e.setError(o);const r=n.findBoxById(t.id);if(!r)return;const i=r.querySelector(".mathjax-tex-text");W(i,"mathjax-error"),i.innerText=o.message,n.selection.updateSelection(null)}}function L_(n,t,e,o){const r=o,i=n.addCustom(`mathjax-box-${r.id}`,()=>new E0);if(r.src||i.dataUrl){const a=w("img",["mathjax"],e);a.src=n.doc.buildResourceUrl(r.src||i.dataUrl),n.domEvents.addEventListener(a,"load",I0);return}const s=["mathjax-tex-text"];let l=r.tex;l.trim()?i.error&&(l=i.error.message,s.push("mathjax-error")):l=R.t("mathjax.emptyText"),w("span",s,e,l),S_(n,r,i)}function M_(n,t){const e={id:K(),box:!0,type:"math",tex:t,src:"",created:Date.now()};return x0(n,t).then(o=>{if(!n.findBoxById(e.id))return;const i={...e,src:o};n.updateBoxData(i)}).catch(o=>{P9.error(`failed to convert and upload mathjax: ${JSON.stringify(o)}`)}),e}function R_(n,t,e,o){const r=t;return o==="text"?r.tex:o==="markdown"?` $${r.tex}$ `:r.src?`<img src="${n.doc.buildResourceUrl(r.src,{withToken:!0})}" />`:`<code>$${r.tex}$</code>`}function O_(n,t,e){const o=ot(t);g(P9,o,"failed to get block"),!(n.readonly||!n.isBlockWritable(o))&&pf(n,t)}function __(){return{abstract:R.t("mathjax.abstract")}}const T0={boxType:"math",updateBoxContent:L_,convertFrom:M_,convertTo:R_,handleClickBox:O_,getBoxProperties:__};async function F_(n,t,e){try{const o=t.embedData,r=await R9(n,o.mathjaxText),i=n.findBlockById(t.id);if(!i)return;const s=Rt(i);s.innerHTML="";const l=w("img",["mathjax"],s);l.src=r,e.setDataUrl(r)}catch(o){e.setError(o)}}function P_(n,t){if(n.readonly||!t.target||!(t.target instanceof Node))return;const e=ot(t.target);if(!e||!Le(e)||Un(e)!=="math")return;const o=Rt(e),r=o.querySelector("img")||o.querySelector("span.mathjax-tex-text");if(!r||!Kt(r,t.target))return;const s=n.getBlockData(e).embedData;_9(n,r,s.mathjaxText,async l=>{const a=await x0(n,l),d={mathjaxText:l,src:a};n.updateEmbedData(e,d)})}function N_(n,t,e){const o=e.embedData,r=n.addCustom(`mathjax-block-${e.id}`,()=>new E0);if(n.domEvents.addEventListener(t,"click",P_),o.src||r.dataUrl){const i=w("img",["mathjax"],t);i.src=n.doc.buildResourceUrl(o.src||r.dataUrl);return}r.error,w("span",["mathjax-tex-text"],t,o.mathjaxText),F_(n,e,r)}function $_(n,t,e){if(!tt(n,t))return null;const o=n.getBlockString(t).trim();if(!o||!o.startsWith("$$")||!o.endsWith("$$"))return null;const r=Bm(o,"$");if(!r)return null;const i={mathjaxText:r,src:""};return{blockData:{id:K(),type:"embed",embedType:"math",embedData:i}}}function H_(n){return{name:"Mathjax"}}function j_(n,t){const e=Rt(t);n.domEvents.removeAllListeners(e)}function U_(n,t,e,o){const r=t.embedData;return o==="html"?`<img src="${n.doc.buildResourceUrl(r.src,{withToken:!0})}" />`:o==="markdown"?`
395
395
  $$${r.mathjaxText}$$
396
396
  `:r.mathjaxText}function z_(){return{abstract:R.t("mathjax.abstract")}}const N9={embedType:"math",createEmbedContent:N_,getOptions:H_,convertFrom:$_,handleDeleteBlock:j_,convertTo:U_,getBlockProperties:z_},knt="",V_={mathjax:{emptyText:"\u7A7A\u7684\u516C\u5F0F",abstract:"\u516C\u5F0F"}},W_={mathjax:{emptyText:"Empty formula",abstract:"Formula"}},q_={mathjax:{emptyText:"\u6570\u5F0F\u306A\u3057",abstract:"\u6570\u5F0F"}};R.mergeLang({"zh-CN":V_,"en-US":W_,"ja-JP":q_});function G_(n,t,e,o){const r=n.getBlockByIndex(t,e),i=n.getBlockText(r),{left:s}=xn(i,o);if(!re(s).endsWith("$$$$"))return!1;const a=o-4,d=o,h={id:K(),box:!0,type:"math",tex:" ",src:"",created:Date.now()};return n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,a,d-a),n.insertBoxToBlock(r,a,h),setTimeout(()=>{const p=n.getBoxById(h.id);pf(n,p)})}),!0}class Z_{handleAfterInsertText(t,e,o,r,i){return!!(i===" "&&G_(t,e,o,r))}}const Cc=S("inline-box-items");function Q_(n,t,e){return n.undoManager.runInGroup(()=>{var s;let o=n.getBlockByIndex(t,e);he(n,o)||(o=n.insertTextBlock([],t,e));const r=F9();n.setBlockText(o,[r]);const i=(s=r.attributes)==null?void 0:s.id;return g(Cc,i,"mathjax box id is empty"),setTimeout(()=>{const l=n.getBoxById(i);pf(n,l)},100),o})}function Y_(n,t,e){let o=n.getBlockByIndex(t,e),r="bottom-start";return he(n,o)||(r="top-start"),fu(n,{target:o,linkText:"",linkUrl:"",onFinished:(l,a)=>{n.undoManager.runInGroup(()=>{try{he(n,o)||(o=n.insertTextBlock([],t,e));const d=lo(l,{link:a}),h=lo(" ",null),p=[d,h];n.insertTextToBlock(o,0,p),n.selection.selectBlock(o,rn(p)),n.focus()}catch(d){Cc.error(d)}})},onClose:()=>{n.focus()},placement:r}),o}function J_(n,t,e){return n.undoManager.runInGroup(()=>{var l;const o=n.getBlockByIndex(t,e),r=n.selection.range;g(Cc,$r(r.start),"invalid block position");const i=F9();n.insertBoxToBlock(o,r.start.offset,i.attributes);const s=(l=i.attributes)==null?void 0:l.id;return g(Cc,s,"mathjax box id is empty"),setTimeout(()=>{const a=n.getBoxById(s);pf(n,a)},100),o})}function K_(n,t,e){const o=n.getBlockByIndex(t,e),r=n.selection.range;g(Cc,$r(r.start),"invalid block position");const i=Ti(n,o,r);if(i.length===0)return;const s=i[0],l=Li(n,o,"quick-menu-inline-link",s);fu(n,{target:l,linkText:"",linkUrl:"",onFinished:(h,p)=>{n.undoManager.runInGroup(()=>{try{const A=n.getBlockText(o),v=Hr(A,r.start.offset,h,{link:p});n.setBlockText(o,v),n.selection.selectBlock(o,r.start.offset+h.length),n.focus()}catch(A){Cc.error(A)}})},onClose:()=>{n.focus()},placement:"bottom-start"})}class $9{getCommands(){return[{id:"insert-math",name:R.t("quickMenu.inlineBox.math"),icon:DL,order:900,group:"common",subText:pn("insert-math")},{id:"insert-link",name:R.t("quickMenu.inlineBox.link"),icon:mv,order:400,group:"common",subText:pn("insert-link")}]}async handleUpdateBlockCore(t,e){switch(e.item.id){case"insert-math":return J_(t,e.containerId,e.blockIndex);case"insert-link":return K_(t,e.containerId,e.blockIndex);default:return null}}async handleInsertEmptyBlockCore(t,e){switch(e.item.id){case"insert-math":return Q_(t,e.containerId,e.blockIndex);case"insert-link":return Y_(t,e.containerId,e.blockIndex);default:return null}}async executeCommand(t,e,o){if(o.from==="quick-menu"){const r=t.getBlockById(o.blockId),i=t.getParentContainer(r),s=at(i),l=t.getBlockIndex(r);t.undoManager.runInGroup(()=>this.handleUpdateBlockCore(t,{item:e,containerId:s,blockIndex:l}))}else o.from==="block-menu"&&t.undoManager.runInGroup(()=>this.handleInsertEmptyBlockCore(t,{item:e,containerId:o.containerId,blockIndex:o.blockIndex}));return null}}function X_(n,t={withPlainText:!1}){var i,s;const{withPlainText:e}=t,o=(s=(i=n.options.componentsOptions)==null?void 0:i.quickMenu)==null?void 0:s.commandProviders;if(!o)return[];const r=[];return[...o,new S9(e),new $9].forEach(l=>{const a=l.getCommands(n);r.push(...a.map(d=>({...d,itemType:"insert-block",commandProvider:l})))}),r}function tF(n,t={withPlainText:!1}){const e=[];return n.editorBlocks.forEach(o=>{if(!o.getOptions)return;const r=o.getOptions(n);!r.insertBlockCommandItems||(r.insertBlockCommandItems.forEach(i=>{D9(i,r)}),e.push(...r.insertBlockCommandItems))}),e.push(...X_(n,t)),e}function D0(n,t={withPlainText:!1}){const e=tF(n,t),o=new Map;e.forEach(s=>{var d;const l=(d=s.group)!=null?d:"";let a=o.get(l);a?a.items.push(s):(a={group:l,order:s.groupOrder||L9[l]||1e3,items:[s]},o.set(l,a))});const r=Array.from(o.values());r.sort((s,l)=>s.order-l.order),r.forEach(s=>{s.items.sort((l,a)=>{var d,h;return((d=l.order)!=null?d:0)-((h=a.order)!=null?h:0)})});const i=[];return r.forEach((s,l)=>{const a=`blockMenu.section.${s.group||"common"}`,d=R.t(a),h=d===a?s.group:d;i.push({id:`section-${l}`,name:h,type:"section",group:s.group,itemType:"insert-block"}),i.push(...s.items.map(p=>({...p})))}),i}function eF(n,t,e){const o=n.getFocusedBlock();if(!o)return;const r=n.getParentContainer(o),i=at(r);let l=n.getBlockIndex(o);if(he(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 H9=S("quick-menu"),nF={id:"quick-menu",trigger:["/"]},oF=5;class Cf{constructor(t,e=nF){m(this,"suggest");m(this,"items");m(this,"maxHeading");m(this,"firstEmptyOffset",-1);m(this,"queryItems",async(t,e)=>{if(this.items.length===0?this.initMenuItems():this.refreshMenuItems(),e){const o=new Set,r=e.toLocaleLowerCase().replace(/^\s+|\s+$/g,""),i=this.items.filter(s=>{if(s.type==="section")return!0;if(s.name.toLocaleLowerCase().indexOf(r)!==-1||vM(s).toLocaleLowerCase().indexOf(r)!==-1)return o.add(s.group),!0;const l=`blockMenu.section.${s.group||"common"}`,a=R.t(l),d=a===l?s.group:a;return(d==null?void 0:d.toLocaleLowerCase().indexOf(r))!==-1?(o.add(s.group),!0):!1}).filter(s=>s.type==="section"?o.has(s.group):!0);return i.length?this.firstEmptyOffset=-1:this.handleEmptySearch(),i}return this.items});m(this,"onClose",()=>{this.firstEmptyOffset=-1});m(this,"onShow",(t,e,o,r)=>{const i=this.editor.getBlockByIndex(e,o);if(!ro(i)){const s=ot(nt(i));if(s&&Dt(s)==="code")return!1}return!0});m(this,"onClickItem",(t,e)=>{const o=e;o.itemType==="insert-block"&&(g(H9,o.blockOptions||o.commandProvider,"invalid quick item, no block options or command provider"),g(H9,this.suggest.anchor,"invalid suggest, no anchor"),this.options.id==="empty-block-menu"&&this.editor.focus(),eF(this.editor,o,this.suggest.anchor))});this.editor=t,this.options=e,this.items=[],this.maxHeading=lf(),this.suggest=new Np(t,{id:e.id||"quick-menu",trigger:e.trigger,needSpaceBeforeTrigger:!0,autoDeleteTrigger:!0,highlight:!0,onClose:this.onClose,onShow:this.onShow,onClickItem:this.onClickItem,queryItems:this.queryItems})}get menu(){return this.suggest.menu.menu}destroy(){this.suggest.destroy()}initMenuItems(){const t=D0(this.editor);this.items=t}refreshMenuItems(){let t=null,e=0;const o=lf();if(o!==this.maxHeading){const r=new S9,s=r.getCommands().map(l=>({...l,itemType:"insert-block",commandProvider:r}));for(let l=0;l<this.items.length;l++)this.items[l].group==="basics"&&(t||(t=l),t&&e++);t&&e&&this.items.splice(t,e,...s),this.maxHeading=o}}handleEmptySearch(){const t=this.editor.selection.getFocusedPos();if(this.firstEmptyOffset===-1){if(t.isSimple()){const{offset:e}=t;this.firstEmptyOffset=e-1}}else if(t.isSimple()){const{offset:e}=t;e-this.firstEmptyOffset>oF&&(this.suggest.close(),this.firstEmptyOffset=-1)}}}class Af{constructor(t){m(this,"instance");m(this,"mousedown",!1);m(this,"currentInstance",null);m(this,"attributeName",[]);m(this,"attributeDesc","");m(this,"observer",null);m(this,"observerCallback",null);m(this,"createContent",t=>{let e="",o=0;for(;o<this.attributeName.length&&!e;)t.hasAttribute(this.attributeName[o])&&(e=t.getAttribute(this.attributeName[o])||""),o++;const r=t.getAttribute(this.attributeDesc);if(!r)return e;const i=w("div",[],null);return w("span",[],i,e),r&&w("span",["editor-tooltip-desc"],i,r),i});m(this,"handleDocumentMouseDown",()=>{this.mousedown=!0,this.editor.domEvents.addEventListener(document,"mouseup",this.handleDocumentMouseUp)});m(this,"handleDocumentMouseUp",()=>{this.mousedown=!1,this.editor.domEvents.removeEventListener(document,"mouseup",this.handleDocumentMouseUp)});m(this,"handleShown",t=>{this.currentInstance&&this.hide(),this.currentInstance=t,this.createObserver()});m(this,"handleHidden",()=>{this.destroyObserver(),this.currentInstance=null});m(this,"handleShow",t=>{var r;const e=t.reference;if(!e||!Kt(document.body,e)||window.isDragging||this.mousedown)return!1;const o=Number.parseInt((r=e.getAttribute("data-tooltip-hide-at"))!=null?r:"",10);if(o&&Date.now()-o<1e3)return!1;if(t.reference){const i={};if(t.reference.hasAttribute("data-editor-tooltip-placement")&&(i.placement=t.reference.getAttribute("data-editor-tooltip-placement")||"top"),t.reference.hasAttribute("data-editor-tooltip-offset-x")||t.reference.hasAttribute("data-editor-tooltip-offset-y")){const s=t.reference.getAttribute("data-editor-tooltip-offset-x"),l=t.reference.getAttribute("data-editor-tooltip-offset-y");i.offset=[s?Number.parseInt(s,10):0,l?Number.parseInt(l,10):0]}if(t.reference.hasAttribute("data-editor-tooltip-maxwidth")&&(i.maxWidth=Number.parseInt(t.reference.getAttribute("data-editor-tooltip-maxwidth")||"350",10)),t.reference.hasAttribute("data-editor-tooltip-allow-markdown")&&(i.allowHTML=!0),Object.keys(i).length&&t.setProps(i),t.reference.hasAttribute(`data-editor-tooltip-${this.editor.clientId}-dynamic`)){const s=t.reference.getAttribute(`data-editor-tooltip-${this.editor.clientId}-dynamic`);t.setContent(s||"")}}return!0});this.editor=t;const e=t.clientId;this.attributeName=[`data-editor-tooltip-${e}`,`data-editor-tooltip-${e}-dynamic`,"data-editor-tooltip-common"],this.attributeDesc=`data-editor-tooltip-desc-${e}`,this.instance=um.delegate(document.body,{theme:"editor-tooltip",maxWidth:400,delay:200,target:this.attributeName.map(o=>`[${o}]`).join(","),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=He.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 rF={"text/style-bold":"bold","text/style-italic":"italic","text/style-underline":"underline","text/style-strikethrough":"line-through","text/style-code":"code","text/style-sub":"subscript","text/style-super":"superscript"};function iF(n,t){const e=new Set(Object.keys(rF)),o=t.filter(i=>e.has(i.id));return rf(o)}function bf(n,t){if(!n.isWritable())return!1;const e=n.selection.range,o=n.editorCommandProviders.getCommands(e),i=iF(n,o).find(s=>s.id===`text/${t}`);return i?(n.editorCommandProviders.executeCommand(e,i,{}),pc.get(n).update("selectionChange"),!0):!1}const S0={"CtrlOrCmd+B":n=>bf(n,"style-bold"),"CtrlOrCmd+I":n=>bf(n,"style-italic"),"CtrlOrCmd+U":n=>bf(n,"style-underline"),"CtrlOrCmd+D":n=>bf(n,"style-strikethrough")},sF={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",edit:"\u7F16\u8F91",remove:"\u53D6\u6D88\u94FE\u63A5"},commands:{unordered:"\u65E0\u5E8F\u5217\u8868",ordered:"\u6709\u5E8F\u5217\u8868",check:"\u5F85\u529E\u5217\u8868",link:"\u94FE\u63A5",quote:"\u5F15\u7528",alignLeft:"\u5DE6\u5BF9\u9F50",alignRight:"\u53F3\u5BF9\u9F50",alignCenter:"\u5C45\u4E2D\u5BF9\u9F50",alignGroup:"\u5BF9\u9F50\u65B9\u5F0F",heading:"\u6807\u9898 {name}",headingGroup:"\u6807\u9898\u6837\u5F0F",text:"\u6B63\u6587"}},lF={quickMenu:{basic:{heading:{title:"Title {heading}",space:"{markdown}space"},unordered:"Bulleted list",ordered:"Numbered list",checkbox:"To-do list",quote:"Quote"},inlineBox:{math:"Formula",link:"Link"}},link:{textLabel:"Text",urlLabel:"Link address",textPlaceholder:"Please enter text",urlPlaceholder:"Please enter link",submitText:"Confirm",cancelText:"Cancel",edit:"Edit",remove:"Remove link"},commands:{unordered:"Bulleted list",ordered:"Numberer list",check:"To-do list",link:"Link",quote:"Quote",alignLeft:"Align left",alignRight:"Align right",alignCenter:"Center text",alignGroup:"Alignment",heading:"Title {name}",headingGroup:"Text style",text:"Text"}},cF={quickMenu:{basic:{heading:{title:"\u898B\u51FA\u3057{heading}",space:"{markdown}\u30B9\u30DA\u30FC\u30B9"},unordered:"\u7B87\u6761\u66F8\u304D\u30EA\u30B9\u30C8",ordered:"\u756A\u53F7\u4ED8\u304D\u30EA\u30B9\u30C8",checkbox:"\u30D0\u30C3\u30AF\u30ED\u30B0",quote:"\u5F15\u7528"},inlineBox:{math:"\u6570\u5F0F",link:"URL"}},link:{textLabel:"\u30C6\u30AD\u30B9\u30C8",urlLabel:"URL",textPlaceholder:"\u30C6\u30AD\u30B9\u30C8\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044",urlPlaceholder:"URL \u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044",submitText:"OK",cancelText:"\u30AD\u30E3\u30F3\u30BB\u30EB",edit:"\u7DE8\u96C6",remove:"\u30EA\u30F3\u30AF\u3092\u89E3\u9664"},commands:{unordered:"\u7B87\u6761\u66F8\u304D\u30EA\u30B9\u30C8",ordered:"\u756A\u53F7\u4ED8\u304D\u30EA\u30B9\u30C8",check:"\u30D0\u30C3\u30AF\u30ED\u30B0",link:"URL",quote:"\u5F15\u7528",alignLeft:"\u5DE6\u63C3\u3048",alignRight:"\u53F3\u63C3\u3048",alignCenter:"\u4E2D\u592E\u63C3\u3048",alignGroup:"\u5BF9\u9F50\u65B9\u5F0F",heading:"\u898B\u51FA\u3057{name}",headingGroup:"\u30BF\u30A4\u30C8\u30EB\u30B9\u30BF\u30A4\u30EB",text:"\u672C\u6587"}};R.mergeLang({"zh-CN":sF,"en-US":lF,"ja-JP":cF});const wnt="";function Qs(n,...t){const e=ji(...t);return e.classList.remove("editor-button"),e.classList.add("editor-text-button"),n.append(e),e}function j9(n){sf(n).hide();const e=n.getCustom("table-border-bar");e==null||e.closeToolbar()}function aF(n){return w("div",["insert-column-button","drop-marker"],n)}const uF=S("row-height");function U9(n){const t=Tt.fromTable(n),e=n.rows;g(uF,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,a=r+1;for(;a<e.length;){const d=e[a];if(d.cells.length!==0)break;i++,a++,l+=d.getBoundingClientRect().height}for(let d=0;d<i;d++)o[r+d]=l/i;r=a}return o}const dF=S("table-border-bar-dom"),hF=Vi+sc+Vi;function pu(n){const t=ot(n.contentElement);g(dF,t,"no block");const o=le(t).querySelector(".table-border-bar-container.left"),r=Math.min(n.contentElement.offsetLeft+hF,n.rootElement.scrollLeft+Vi);o&&(o.style.left=`${-r}px`)}const Yi=S("table-border-bar-dom");function Ac(n,t){g(Yi,Ve(t),"invalid table block");const e=Oe(t),o=fr(n,t),r=le(t),i=(p,A,v)=>{const B=w("div",["button-root",A],p),D=w("div",["button-container",A],B);B.setAttribute(`data-${A}-index`,`${v}`),D.setAttribute(`data-editor-tooltip-${n.clientId}`,A==="left"?R.t("table.insertRow"):R.t("table.insertCol")),w("span",["insert-indicator"],D),aF(D)},{selectedRows:s,selectedColumns:l}=Hp(n,t),a=()=>{const p=o.querySelector(".table-border-bar-container.top");g(Yi,p,"no top border bar container");const A=w("div",["table-border-bar-container","top"],null),v=w("div",["table-border-bar","top"],A),B=bR(e),T=Tt.fromTable(e).colCount;n.selection.range.isSimple()&&i(v,"top",0);for(let _=0;_<T;_++){const M=_===T-1?B[_]+2:B[_],H=w("span",["table-border-bar-cell","top"],v);l.has(_)&&H.classList.add("selected"),H.setAttribute("data-top-index",`${_}`),H.style.width=`${M}px`,n.selection.range.isSimple()&&i(v,"top",_+1)}Ca(p,A)},d=()=>{const p=r.querySelector(".table-border-bar-container.left");g(Yi,p,"no left border bar container");const A=w("div",["table-border-bar-container","left"],null),v=w("div",["table-border-bar","left"],A);w("span",["table-border-bar-cell","corner"],v);const B=U9(e);n.selection.range.isSimple()&&i(v,"left",0),Array.from(e.rows).forEach((D,T,_)=>{const M=w("span",["table-border-bar-cell","left"],v);s.has(T)&&M.classList.add("selected"),M.setAttribute("data-left-index",`${T}`);const H=T===_.length-1?B[T]+2:B[T];M.style.height=`${H}px`,n.selection.range.isSimple()&&i(v,"left",T+1)}),Ca(p,A)};a(),d();const h=n.findCustom(hr(t));h&&pu(h)}function z9(n,t){const e=t.target;if(!(e instanceof Element))return;const o=ot(e);g(Yi,o&&Ve(o),"invalid table block"),Ac(n,o),n.selection.caret.update()}function vf(n,t){const e=t.target;if(!(e instanceof Element))return;const o=ot(e);g(Yi,o&&Ve(o),"invalid table block");const r=e.closest(".button-root");if(r){if(r.classList.contains("top")){const i=parseInt(r.getAttribute("data-top-index")||"0",10);e9(n,o,i),Ac(n,o)}else if(r.classList.contains("left")){const i=parseInt(r.getAttribute("data-left-index")||"0",10);n9(n,o,i),Ac(n,o)}}}function yf(n,t){var s;j9(n),t.preventDefault(),t.stopPropagation();let e=null,o,r;const i=l=>{var a;if(l.target instanceof HTMLElement&&o&&e&&r!==void 0){const d=ot(l.target),h=l.target.closest(".table-border-bar");if(d===e&&h){const p=parseInt((a=l.target.getAttribute(`data-${o}-index`))!=null?a:"0",10),A=Math.min(r,p),v=Math.abs(r-p)+1;xt(l.target,"top")&&o==="top"?MR(n,d,A,v,{reverse:!0}):xt(l.target,"left")&&o==="left"&&RR(n,d,A,v,{reverse:!0})}}l.type==="mouseup"&&(e=null,r=void 0,o=void 0,document.body.removeEventListener("mousemove",i),document.body.removeEventListener("mouseup",i))};t.target instanceof HTMLElement&&xt(t.target,"table-border-bar-cell")&&(e=ot(t.target),xt(t.target,"top")?o="top":xt(t.target,"left")&&(o="left"),o&&e&&(r=parseInt((s=t.target.getAttribute(`data-${o}-index`))!=null?s:"0",10),document.body.addEventListener("mousemove",i),document.body.addEventListener("mouseup",i)))}function V9(n){const t=n.selection.range,e=su(n,t);e&&Ac(n,e)}function fF(n,t){g(Yi,Ve(t),"invalid table block");const e=fr(n,t),o=le(t),r=w("div",["table-border-bar-container","top"],e),i=w("div",["table-border-bar-container","left"],o);Ac(n,t),n.domEvents.addEventListener(Rt(t),"scroll",z9),n.domEvents.addEventListener(r,"click",vf),n.domEvents.addEventListener(i,"click",vf),n.domEvents.addEventListener(r,"mousedown",yf),n.domEvents.addEventListener(i,"mousedown",yf),n.addListener("afterClearSelection",V9)}function W9(n,t){if(!n.isWritable())return;if(fr(n,t).querySelector(".table-border-bar-container")){Ac(n,t);return}fF(n,t)}function q9(n,t){g(Yi,Ve(t),"invalid table block");const e=fr(n,t),o=le(t),r=e.querySelectorAll(".table-border-bar-container"),i=o.querySelectorAll(".table-border-bar-container");r.forEach(s=>{n.domEvents.removeEventListener(s,"click",vf),n.domEvents.removeEventListener(s,"mousedown",yf),s.remove()}),i.forEach(s=>{n.domEvents.removeEventListener(s,"click",vf),n.domEvents.removeEventListener(s,"mousedown",yf),s.remove()}),n.domEvents.removeEventListener(Rt(t),"scroll",z9),n.addListener("afterClearSelection",V9)}function mF(n,t){g(Yi,Ve(t),"invalid table block");const o=fr(n,t).querySelector(".table-border-bar-container.top");return o?o.getBoundingClientRect().height:0}class gF{constructor(t,e){m(this,"toolbar");m(this,"handleSelectionChange",(t,e)=>{!t.isVisible||(e==="delete-columns"?(Wi(this.editor,this.tableBlock,!0,!0),qi(this.editor,this.tableBlock,!0,!0)):e==="delete-rows"?(Wi(this.editor,this.tableBlock,!0,!1),qi(this.editor,this.tableBlock,!0,!1)):(Wi(this.editor,this.tableBlock,!1),qi(this.editor,this.tableBlock,!1)))});m(this,"handleClick",(t,e,o)=>{e.id==="delete-columns"?jp(this.editor.selection.range):e.id==="delete-rows"&&Up(this.editor.selection.range)});m(this,"handleToolbarClose",()=>{this.tableBlock&&su(this.editor,this.editor.selection.range)===this.tableBlock&&(Wi(this.editor,this.tableBlock,!1),qi(this.editor,this.tableBlock,!1))});this.editor=t,this.tableBlock=e;const o=t.options.componentsOptions.popover;this.toolbar=new ou([],void 0,{overflowBoundary:o==null?void 0:o.overflowBoundary,refuseOverflow:!0,tooltipId:this.editor.clientId}),this.toolbar.addListener("selectionChange",this.handleSelectionChange),this.toolbar.addListener("click",this.handleClick),this.toolbar.addListener("close",this.handleToolbarClose)}close(){this.toolbar.close("cancelBar")}update(){var r,i;const{selectedColumns:t,selectedRows:e}=Hp(this.editor,this.tableBlock);if(!this.editor.isWritable())return;if(t.size>0&&e.size>0){this.toolbar.close("cancelBar");return}if(t.size===0&&e.size===0){this.toolbar.close("cancelBar");return}const o=Ti(this.editor,this.tableBlock,this.editor.selection.range)[0];if(!o){this.toolbar.close("cancelBar");return}if(t.size>0){const s={id:"delete-columns",name:R.t("table.deleteCol"),icon:pL};this.toolbar.updateItems([s]);const l=Li(this.editor,this.tableBlock,"table-row-column-delete",o);this.toolbar.manualShow(l,{placement:"top"})}else{const s={id:"delete-rows",name:R.t("table.deleteRow"),icon:gL};this.toolbar.updateItems([s]);const l=new DOMRect(o.left-Vi,o.top,Vi,o.height),a=Li(this.editor,this.tableBlock,"table-row-column-delete",l);this.toolbar.manualShow(a,{placement:"left"})}(i=(r=this.toolbar.tippyInstance)==null?void 0:r.popperInstance)==null||i.update()}destroy(){this.toolbar.destroy(),this.toolbar.removeAllListeners()}}const L0=S("table-border-bar");class pF{constructor(t,e){m(this,"toolbar");m(this,"resizeObserver");m(this,"handleReadonlyChanged",t=>{t.isWritable()?this.update():q9(this.editor,this.tableBlock)});m(this,"handleBlockUpdated",()=>{this.resizeObserver.disconnect(),setTimeout(()=>{const t=this.editor.getBlockById(it(this.tableBlock));this.resizeObserver.observe(Oe(t))})});m(this,"handleTableResize",()=>{!this.editor.isWritable()||(console.log("resize"),this.update())});this.editor=t,this.tableBlock=e,g(L0,this.tableBlock,"no table block"),L0.debug("create table border bar"),W9(this.editor,this.tableBlock),this.resizeObserver=new ResizeObserver(this.handleTableResize),this.resizeObserver.observe(Oe(this.tableBlock)),this.toolbar=new gF(this.editor,this.tableBlock),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}close(){this.toolbar.close()}destroy(){L0.debug("destroy table border bar"),this.resizeObserver.disconnect(),q9(this.editor,this.tableBlock),this.toolbar.destroy(),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged)}update(){W9(this.editor,this.tableBlock),this.toolbar.update()}}const CF=S("table-border-bar");class AF{constructor(t){m(this,"activeTableBar",null);m(this,"handleBlockDeleted",(t,e)=>{!this.activeTableBar||(e===this.activeTableBar.tableBlock||Kt(e,this.activeTableBar.tableBlock))&&(this.activeTableBar.destroy(),this.activeTableBar=null)});m(this,"handleSelectionChanged",t=>{var r;const e=t.selection.range,o=su(t,e);((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 pF(this.editor,t)}update(){var t;(t=this.activeTableBar)==null||t.handleBlockUpdated()}closeToolbar(){var t;(t=this.activeTableBar)==null||t.close()}hide(){!this.activeTableBar||(g(CF,this.activeTableBar,"no active table bar"),this.activeTableBar.destroy(),this.activeTableBar=null)}}function G9(n,t){const e=n.addCustom("table-border-bar",o=>new AF(o));t==="update"&&e.update()}const Sn=S("table-cell-menu"),bF="style-bg-color-";class vF{constructor(t){m(this,"activeTableBlock",null);m(this,"targetButton",null);m(this,"manualMenu",null);m(this,"colorPaletteItem",null);m(this,"handlePrevent",(t,e)=>{e.stopPropagation()});m(this,"handleReadonlyChanged",t=>{t.isWritable()||this.hide()});m(this,"handleSelectionChanged",t=>{const e=t.selection.range,o=su(t,e);if(this.hide(),this.activeTableBlock!==o&&(this.activeTableBlock=o),this.activeTableBlock){const r=Tt.fromBlock(this.activeTableBlock),i=e.isReverse()?e.start:e.end;let s=null;i instanceof So?t.getBlockById(i.blockId)===this.activeTableBlock?s=r.getCellByContainerId(i.childContainerId):s=this.getCellByChildBlockId(r,i.blockId):s=this.getCellByChildBlockId(r,i.blockId),s&&this.editor.isWritable()&&this.showCellMenuButton(s)}});m(this,"handleBeforePopupPalette",()=>{var e;const t=this.getSelectedBkgColorIndex();(e=this.colorPaletteItem)==null||e.palette.setColor("backgroundColor",t)});m(this,"createBkgColorItem",()=>{const t=w("div",["cell-background-color-item"],null);w("span",[],t,R.t("table.cellBackground"));const e=this.getSelectedBkgColorIndex();w("button",["item-button"],t).setAttribute("data-color-index",`${e}`);const r=w("span",["item-sub-indicator"],t);return r.innerHTML=av,t});m(this,"handleCommand",t=>{var r;g(Sn,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":Up(Fv(this.editor,this.activeTableBlock,!1));break;case"delete-select-col":jp(Fv(this.editor,this.activeTableBlock,!0));break;case"merge-cell":Rv(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":jM(this.editor,this.activeTableBlock,o==="show-border");break;case"show-chart":qM(this.editor,this.activeTableBlock,o==="show-chart"),Kp(this.editor,this.activeTableBlock,{updateNow:!0});break}});m(this,"handleToolbarClose",()=>{this.targetButton&&et(this.targetButton,"active"),this.activeTableBlock&&su(this.editor,this.editor.selection.range)===this.activeTableBlock&&(Wi(this.editor,this.activeTableBlock,!1),qi(this.editor,this.activeTableBlock,!1)),this.editor.focus()});m(this,"handleSelectionChange",(t,e)=>{!t.isVisible||(g(Sn,this.activeTableBlock,"no target table block"),e==="cell-background-color"&&this.handleBeforePopupPalette(),e==="delete-select-row"?(Wi(this.editor,this.activeTableBlock,!0,!1),qi(this.editor,this.activeTableBlock,!0,!1)):e==="delete-select-col"?(Wi(this.editor,this.activeTableBlock,!0,!0),qi(this.editor,this.activeTableBlock,!0,!0)):(Wi(this.editor,this.activeTableBlock,!1),qi(this.editor,this.activeTableBlock,!1)))});m(this,"handleClick",(t,e)=>{var o;g(Sn,this.activeTableBlock,"no target table block"),g(Sn,this.targetButton,"no target button"),j9(this.editor),xt(this.targetButton,"active")?(et(this.targetButton,"active"),(o=this.manualMenu)==null||o.close("clickItem")):(W(this.targetButton,"active"),this.manualMenu?this.manualMenu.updateItems(this.createCommandMenu()):(this.manualMenu=new zs(this.createCommandMenu()),this.manualMenu.on("click",(r,i)=>{var s;this.handleCommand(i),(s=this.manualMenu)==null||s.close("clickItem")}),this.manualMenu.on("selectionChange",this.handleSelectionChange),this.manualMenu.on("close",this.handleToolbarClose)),this.manualMenu.manualShow(this.targetButton,{placement:"right-start"})),e.stopPropagation()});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("cancelBar"),this.targetButton&&(et(this.targetButton,"active"),this.targetButton.style.display="none")}getCellByChildBlockId(t,e){let o=this.editor.getBlockById(e);for(;o;){const r=o.closest("td");g(Sn,r,"no parent cell");const i=ot(r);if(g(Sn,i,"no parent block"),Oe(i)===t.table)return t.getCellByCellElement(r);o=i}return g(Sn,!1,"filed to get cell by child block id"),null}createTargetButton(t){this.targetButton?t.querySelector(`:scope > .${Zp}`)||t.appendChild(this.targetButton):(this.targetButton=w("button",[Zp],t),this.targetButton.innerHTML=Gh,this.editor.domEvents.addEventListener(this.targetButton,"click",this.handleClick),this.editor.domEvents.addEventListener(this.targetButton,"mousedown",this.handlePrevent),this.editor.domEvents.addEventListener(this.targetButton,"dblclick",this.handlePrevent))}showCellMenuButton(t){this.createTargetButton(t.cell),g(Sn,this.targetButton,"no target button"),this.targetButton.style.display="inline-block"}handleSplitCell(){if(this.activeTableBlock){const t=Tt.fromBlock(this.activeTableBlock),e=this.editor.selection.range;if(e.isSimple()){const{col:o,row:r}=this.getCellByChildBlockId(t,e.start.blockId);Vp(this.editor,this.activeTableBlock,{col:o,row:r})}else Wp(this.editor.selection.range)}}getSelectedBkgColorIndex(){var r;g(Sn,this.activeTableBlock,"no target table block");const t=VM(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=at(i),l=e[`${s}_background`];if(l)o.add(Number.parseInt((r=l.substring(bF.length))!=null?r:"0",10));else{o.add(-1);break}}return o.size===1&&[...o][0]!==-1?[...o][0]:-1}createCommandMenu(){g(Sn,this.activeTableBlock,"no target table block");const t=this.editor.getBlockData(this.activeTableBlock),e=Mv(this.editor,this.activeTableBlock,this.editor.selection.range);let o=this.editor.selection.range;if(o.isSimple()){const h=Gr(this.editor,this.activeTableBlock,o.start);o=Ue(this.editor,{anchor:h,focus:h})}const r=Lv(this.editor,this.activeTableBlock,o),i=t.hasRowTitle,s=t.hasColTitle,l=t.isStripeStyle,a=t.noBorder,d=t.chart;return this.colorPaletteItem=new Ev("cell-background-color",{color:!1}),this.colorPaletteItem.palette.on("onClick",(h,p)=>{var A;switch(g(Sn,this.activeTableBlock,"no target table block"),h){case"clearColor":$v(this.editor,this.activeTableBlock,-1);break;case"backgroundColor":$v(this.editor,this.activeTableBlock,p);break}(A=this.manualMenu)==null||A.close("clickItem")}),[{id:"cell-background-color",name:R.t("table.cellBackground"),element:this.createBkgColorItem(),children:[this.colorPaletteItem]},{id:"separator",name:"",type:"separator"},{id:"merge-cell",name:R.t("table.mergeCell"),states:e?[]:["disabled"]},{id:"split-cell",name:R.t("table.splitCell"),states:r?[]:["disabled"]},{id:"separator",name:"",type:"separator"},{id:"delete-select-row",name:R.t("table.deleteSelectRow")},{id:"delete-select-col",name:R.t("table.deleteSelectCol")},{id:"separator",name:"",type:"separator"},{id:"table-config",name:R.t("table.tableConfigKey"),children:[{id:"row-title",name:R.t("table.tableConfig.rowTitle"),states:i?["checked"]:[]},{id:"col-title",name:R.t("table.tableConfig.colTitle"),states:s?["checked"]:[]},{id:"stripe-style",name:R.t("table.tableConfig.stripeStyle"),states:l?["checked"]:[]},{id:"hide-border",name:a?R.t("table.tableConfig.showBorder"):R.t("table.tableConfig.hideBorder"),value:a?"show-border":"hide-border"},{id:"show-chart",name:d?R.t("table.tableConfig.hideChart"):R.t("table.tableConfig.showChart"),value:d?"hide-chart":"show-chart"}]}]}handleRowTitle(t){g(Sn,this.activeTableBlock,"no target table block"),t?NM(this.editor,this.activeTableBlock):PM(this.editor,this.activeTableBlock)}handleColTitle(t){g(Sn,this.activeTableBlock,"no target table block"),t?FM(this.editor,this.activeTableBlock):_M(this.editor,this.activeTableBlock)}handleStripeStyle(t){g(Sn,this.activeTableBlock,"no target table block"),t?HM(this.editor,this.activeTableBlock):$M(this.editor,this.activeTableBlock)}}function Z9(n){n.addCustom("table-cell-menu",t=>new vF(t))}const kf=S("table-container");function M0(n){const t=n.closest("td");return g(kf,t,"no parent cell for a table cell container"),t}function Q9(n){const t=Oe(n);return Array.from(t.querySelectorAll(':scope > tbody > tr > td > [data-type="editor-container"].child'))}function R0(n,t,e,o){const r=Tt.fromBlock(n),i=r.getCellByContainerId(at(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(g(kf,l>=0,"not a valid child container"),l===0)return null;const a=s[l-1];return o!=null&&o.noWrap&&r.getCellByContainerId(at(a)).row!==i.row?null:a}if(e==="ArrowRight"){const s=r.getAllContainers(),l=s.indexOf(t);if(g(kf,l>=0,"not a valid child container"),l===s.length-1)return null;const a=s[l+1];return o!=null&&o.noWrap&&r.getCellByContainerId(at(a)).row!==i.row?null:a}g(kf,!1,`invalid navigation type: ${e}`)}const yF=12,kF=90,wf=23,Y9=2;class wF{constructor(t){m(this,"scrollTableBlock",null);m(this,"autoScrollDir",null);m(this,"autoScrollTimer",null);m(this,"handleMouseDown",t=>{const e=document.elementFromPoint(t.clientX,t.clientY);if(e&&e instanceof HTMLElement){const o=ot(e);if(o&&Kt(this.editor.rootContainer,o)){const r=qr(o);r&&(this.scrollTableBlock=r,document.addEventListener("mousemove",this.handleAutoScroll))}}});m(this,"handleAutoScroll",WB.default(t=>{if(this.scrollTableBlock){const e=this.editor.getCustom(hr(this.scrollTableBlock)),o=e.rootElement,r=e.scrollOptions.parentContainer,i=o.getBoundingClientRect(),s=window.innerHeight-(e.scrollOptions.barFloatWindowBottom||0),l=r.getBoundingClientRect(),a=Math.min(l.bottom,s),d=Math.max(l.top,0);i.bottom>a&&t.clientY>=a?this.setAutoScroll("bottom"):i.top<d&&t.clientY<=d?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));m(this,"handleMouseUp",()=>{document.removeEventListener("mousemove",this.handleAutoScroll),setTimeout(()=>{this.scrollTableBlock=null})});m(this,"handleSelectionChanged",t=>{const e=t.selection.range;if(e.isCollapsed()&&e.isSimple()){const o=t.getBlockById(e.start.blockId),r=qr(o);if(r){const i=t.getCustom(hr(r)),s=i.rootElement.getBoundingClientRect(),l=To(t,o,e.start);if(s.left>l.left){const a=e.start.offset===0?yF:Y9;i.rootElement.scrollLeft-=s.left-l.left+a}else if(l.right>s.right){const a=e.start.offset===0?kF:Y9;i.rootElement.scrollLeft+=l.right-s.right+a}}}else{const o=t.getBlockById(e.start.blockId),r=qr(o),i=t.getBlockById(e.end.blockId),s=qr(i);if(r&&r===s){const l=t.getCustom(hr(r)),a=l.rootElement.getBoundingClientRect();let d=null;if(e.isSimple())d=e.isReverse()?To(t,o,e.start):To(t,i,e.end);else{const h=M0(Nr(t,e.start.childContainerId)),p=M0(Nr(t,e.end.childContainerId));d=e.isReverse()?h.getBoundingClientRect():p.getBoundingClientRect()}a.left>d.left&&e.isReverse()?l.rootElement.scrollLeft-=a.left-d.left:a.right<d.right&&!e.isReverse()&&(l.rootElement.scrollLeft+=d.right-a.right)}}});m(this,"handleScroll",t=>{Tv(t),this.editor.selection.caret.update()});m(this,"handleReset",t=>{Tv(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(hr(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),a=r.getBoundingClientRect(),d=Math.min(a.bottom,l),h=Math.max(a.top,0);this.autoScrollDir==="left"&&(o.scrollLeft-=wf,o.scrollLeft<=0&&this.clearAutoScroll()),this.autoScrollDir==="right"&&(o.scrollLeft+=wf,o.scrollLeft>=o.scrollWidth-o.offsetWidth&&this.clearAutoScroll()),this.autoScrollDir==="bottom"&&(r.scrollTop+=wf,(r.scrollTop>=r.scrollHeight-s||i.bottom<=d)&&this.clearAutoScroll()),this.autoScrollDir==="top"&&(r.scrollTop-=wf,(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 J9(n){return n.addCustom("table-scroll-events",t=>new wF(t))}const mr=S("create-content");function K9(n,t,e){const o=new Zh(e),r=e.rows,i=e.cols;g(mr,r>=1,`invalid rows: ${r}`),g(mr,i>=1,`invalid cols: ${i}`),g(mr,e.children,"no table children");const s=w("table",[],null),l=e.colsWidth,a=w("colgroup",[],s);for(let p=0;p<o.colCount;p++){const A=w("col",[],a);A.style.width=`${l[p]||nf}px`}const d=w("tbody",[],s);let h=0;for(let p=0;p<r;p++){const A=w("tr",[],d);for(let v=0;v<i;v++){const B=o.getCell({col:v,row:p});if(B.virtual)g(mr,B.colSpan>1||B.rowSpan>1,"virtual cell should have colSpan or rowSpan");else{const D=e.children[h],T=w("td",[],A);B.colSpan>1&&(T.colSpan=B.colSpan),B.rowSpan>1&&(T.rowSpan=B.rowSpan);const _=e[cu(D)];_&&W(T,_),v===0&&e.hasColTitle&&W(T,Ov.COL_TITLE_ITEM),n.createChildContainer(t,T,D),h+=1}}}return g(mr,h===e.children.length,"container count mismatch"),e.noBorder&&W(s,"no-border"),e.chart&&W(s,"editor-table-chart"),e.isStripeStyle&&W(s,"stripe"),e.hasRowTitle&&W(s,"row-title"),e.hasColTitle&&W(s,"col-title"),s}function BF(n,t,e,o,r){g(mr,r.type==="table","not table data"),g(mr,at(e)===t[t.length-1].containerId,"invalid path");const i=r,s=Ts(o,"div");try{const l=w("div",[],null);l.setAttribute("data-type","table-content");const a=K9(n,t,i);a.classList.add("drag-preview-element"),l.appendChild(a),Xv(n),r9(n),G9(n,"create"),Z9(n),oL(n,Xp);const d=n.getComponentOptions("table"),h=n.addCustom(hr(o),()=>pR());h.init({parentElement:s,childElement:l,safeRightSpace:50,safeLeftSpace:40,parentContainer:Xt(e)?n.scrollContainer:e,locatingContainer:Xt(e)?(d==null?void 0:d.locatingContainer)||n.parent:e,paddingLeft:Vi+sc,paddingTop:Vi+sc,paddingBottom:sc/2,paddingRight:sc/2,barFloatWindowBottom:d==null?void 0:d.barFloatWindowBottom,isSetScale:d==null?void 0:d.isSetScale});const p=J9(n);h.on("scroll",p.handleReset),h.on("resize",p.handleReset),h.on("resize",pu),h.on("scroll",pu),setTimeout(()=>{QM(n,o)})}catch{const a=`invalid table data: ${JSON.stringify(i)}`;mr.error(a);const d=w("div",["error"],s);d.innerText=a}return s}function EF(n,t,e){g(mr,e.type==="table","not table data");const o=e,r=Rt(t);try{const i=Oe(t),s=Di(t),l=K9(n,s,o);l.classList.add("drag-preview-element"),i.insertAdjacentElement("afterend",l),i.remove(),Xv(n),r9(n),G9(n,"update"),Z9(n),Xp(n,t)}catch{const s=`invalid table data: ${JSON.stringify(o)}`;mr.error(s);const l=w("div",["error"],r);l.innerText=s}}function xF(n,t){let e,o,r=!1;if([...t].every(A=>A==="|")?(o=t.length,e=Array(o).fill(""),r=!0):(e=Bm(t,"|").split("|"),o=e.length),o<2)return null;const i=3,s=o,l=[];for(let A=0;A<3;A++)e.forEach(v=>{l.push(Ur(n.doc,A===0?v:""))});const a=Array(s).fill(nf),d=l[r?0:s],h=n.doc.getContainerBlocks(d)[0].id;return{blockData:{id:K(),type:"table",rows:i,cols:s,children:l,colsWidth:a},focusBlockId:h}}function IF(n,t){const e=t.rows,o=t.cols;if(e<1||o<1)return null;const r=[];for(let d=0;d<e;d++)for(let h=0;h<o;h++)r.push(Ur(n.doc));const i=Array(o).fill(nf),s=r[0],l=n.doc.getContainerBlocks(s)[0].id;return{blockData:{id:K(),type:"table",rows:e,cols:o,children:r,colsWidth:i},focusBlockId:l}}const X9=S("table-selection-to-doc");function TF(n,t){const{start:e,end:o,block:r}=t,i=Dt(r);g(X9,i==="table",`invalid block type: ${i}`);const s=n.getBlockData(r);if(e.isSimple()&&o.isSimple())return Fi(n.editorBlocks,n.doc.toJSON(),s);g(X9,!e.isSimple()&&!o.isSimple(),"invalid block pos type");const l=Tt.fromBlock(r),{fromCol:a,toCol:d,fromRow:h,toRow:p}=Ho(r,e,o),A={},v=[],B=n.doc.toJSON();let D={};l.sub({row:h,col:a},{row:p,col:d}).forEach((rt,ft)=>{rt.forEach((Bt,jt)=>{const Ut=Bt.containerId;if(v.indexOf(Ut)!==-1)return;v.push(Ut);let ee;if(Bt.virtual){const Ne=l.getCellByContainerId(Bt.containerId),Ln=a+jt;let vr=Ne.col+Ne.colSpan-1;vr>d&&(vr=d);const bn=vr-Ln+1;bn>1&&(A[`${Ut}_colSpan`]=bn);const an=h+ft;let yr=Ne.row+Ne.rowSpan-1;yr>p&&(yr=p);const ei=yr-an+1;ei>1&&(A[`${Ut}_rowSpan`]=ei),ee=jr()}else{if(ee=Ng(n.editorBlocks,B,Ut),Bt.col+Bt.colSpan>d+1){const Ne=d-Bt.col+1;Ne>1&&(A[`${Ut}_colSpan`]=Ne)}else Bt.colSpan>1&&(A[`${Ut}_colSpan`]=Bt.colSpan);if(Bt.row+Bt.rowSpan>p+1){const Ne=p-Bt.row+1;Ne>1&&(A[`${Ut}_rowSpan`]=Ne)}else Bt.rowSpan>1&&(A[`${Ut}_rowSpan`]=Bt.rowSpan)}const{root:Ye,...Wo}=ee.blocks;D={...D,...Wo,[Ut]:Ye}})});const _=hu(Oe(r)).slice(a,d+1);return{blocks:{root:[{id:K(),type:i,children:v,colsWidth:_,rows:p-h+1,cols:d-a+1,...A}],...D},meta:{},comments:{}}}function DF(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 SF(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 LF(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 MF(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 RF(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 a=!1;do{if(a=!1,!DF(n,l)){l.top--,a=!0;continue}if(!SF(n,l)){l.left--,a=!0;continue}if(!LF(n,l)){l.bottom++,a=!0;continue}if(!MF(n,l)){l.right++,a=!0;continue}}while(a);return l}function OF(n,t,e,o){if(e.custom!==void 0||o.custom!==void 0)return{anchor:e,focus:o};const r=Tt.fromBlock(t),i=r.map(H=>H.containerId),s=r.getCellByContainerId(e.childContainerId),l=r.getCellByContainerId(o.childContainerId),a=Math.min(s.row,l.row),d=Math.max(s.row,l.row),h=Math.min(s.col,l.col),p=Math.max(s.col,l.col),A=RF(i,{row:a,col:h},{row:d,col:p}),v=r.getCell({row:A.top,col:A.left}),B=r.getCell({row:A.bottom,col:A.right}),D=r.getCell({row:A.top,col:A.right}),T=r.getCell({row:A.bottom,col:A.left});let _,M;return s.row<=l.row?s.col<=l.col?(_=v,M=B):(_=D,M=T):s.col<l.col?(_=T,M=D):(_=B,M=v),console.log(`move ${_.col}, ${_.row}, -> ${M.col}, ${M.row}`),{anchor:fe(t,_.containerId),focus:fe(t,M.containerId)}}function t7(n,t,e){if(e.isSimple())return[Oe(t).getBoundingClientRect()];const o=Oe(t),r=o.getBoundingClientRect(),{fromCol:i,fromRow:s,toCol:l,toRow:a}=Ho(t,e.start,e.end),d=hu(o),h=d.slice(0,i).reduce((D,T)=>D+T,0),p=h+d.slice(i,l+1).reduce((D,T)=>D+T,0),A=U9(o);let v=A.slice(0,s).reduce((D,T)=>D+T,0);const B=v+A.slice(s,a+1).reduce((D,T)=>D+T,0);if(s===0){const D=mF(n,t);v-=D}return[new DOMRect(r.left+h,r.top+v,p-h,B-v)]}S("table-size");const _F=40;function Bf(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 FF(n,t,e){const o=Qm(n,e.container);return o!==void 0?o+Bf(t):_F*e.colSpan-Bf(t)}function PF(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 a=FF(n,t,l);const d=v4(l.container,{withPadding:!0});d&&d>a&&(a=d),r+=a+Bf(t)}return r}function NF(n,t){const e=Oe(t),o=Tt.fromTable(e);let r=0;for(let s=0;s<o.rowCount;s++)r=Math.max(r,PF(n,e,o,s));const i=Bf(e);return r+=i,r}const Zr=S("table-creator");async function $F(n,t){return n.undoManager.runInGroup(()=>{var a,d;const e=t.item,o=(a=e.colCount)!=null?a:5,r=(d=e.rowCount)!=null?d:3,i=IF(n,{cols:o,rows:r});if(!i)return null;const{blockData:s,focusBlockId:l}=i;return n.insertBlock(t.containerId,t.blockIndex,s,ye(n,l,0))})}class HF{constructor(){m(this,"id","insert-table");m(this,"name","Create table");m(this,"element");m(this,"closeable",null);m(this,"colCount");m(this,"rowCount");m(this,"setCloseable",t=>{this.closeable=t});m(this,"destroy",()=>{this.closeable=null});m(this,"getTableCreatorCellId",(t,e)=>`table-creator-cell-${t}-${e}`);m(this,"handleTableCreatorClick",t=>{var A,v;t.preventDefault(),t.stopPropagation();const e=t.target;g(Zr,e instanceof HTMLElement,"invalid event target");const o=e.closest(".table-creator");g(Zr,o,"no table creator");const r=o.querySelectorAll(".active");if(r.length===0)return;const s=r[r.length-1].id;g(Zr,s,"no cell id");const l="table-creator-cell-";if(!s.startsWith(l))return;const d=s.substring(l.length).split("-");g(Zr,d.length===2,"invalid cell id");const h=Number.parseInt(d[0],10)+1,p=Number.parseInt(d[1],10)+1;Zr.debug(`${h}, ${p}`),this.colCount=p,this.rowCount=h,(A=this.closeable)==null||A.click(this,this.element),(v=this.closeable)==null||v.close("clickItem"),this.handleTableCreatorLeave()});m(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&&et(r,"active")}});m(this,"handleTableCreatorCellEnter",t=>{const e=t.target;g(Zr,e instanceof HTMLElement,"invalid event target");const o=e.id,r="table-creator-cell-";g(Zr,o.startsWith(r),"invalid cell id");const s=o.substring(r.length).split("-");g(Zr,s.length===2,"invalid cell id");let l=Number.parseInt(s[0],10),a=Number.parseInt(s[1],10);l===0&&a===0&&(l=-1,a=-1);for(let d=0;d<9;d++)for(let h=0;h<9;h++){const p=this.getTableCreatorCellId(d,h),A=document.getElementById(p);g(Zr,A,"no cell"),d<=l&&h<=a?W(A,"active"):et(A,"active")}});this.element=this.createTableCreatorElement()}createTableCreatorElement(){const t=w("div",["table-creator"],null),e=(o,r,i)=>{const s=w("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=w("div",["table-creator-row"],t);for(let i=0;i<9;i++)e(r,o,i).addEventListener("mouseenter",this.handleTableCreatorCellEnter)}return t}}function jF(){return new HF}function UF(n){const t=/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g,e=n.match(t);return e?e.length:0}function e7(n){const t=UF(n);return n.length+t}function zF(n,t){const e=e7(n),o=t-e;return o>0?n+" ".repeat(o):n}function VF(n,t,e,o,r){const i=t,s=new Zh(i);if(o==="markdown"||o==="text"){const l=T=>e.blocks[T].map((H,z)=>o==="markdown"?Tg(n,H,e,[...r,{containerId:T,blockIndex:z}]):Ah(n,H,e,[...r,{containerId:T,blockIndex:z}])),a=T=>l(T).join(" ").replace(/\n/g," ").trim(),d=new Map,h=new Map;for(let T=0;T<s.colCount;T++){let _=0;for(let M=0;M<s.rowCount;M++){const H=s.getCell({row:M,col:T});let z="";H.virtual||(z=a(H.containerId)),d.set(`${M},${T}`,z),_=Math.max(_,e7(z))}h.set(T,_)}const p=T=>{const _=d.get(`${T.row},${T.col}`)||"",M=h.get(T.col)||0;return zF(_,M)},A=[];let v="|",B="|";for(let T=0;T<s.colCount;T++){const _=p({row:0,col:T});v+=` ${_} |`;const M="-".repeat((h.get(T)||0)+2);B+=`${M}|`}A.push(v),A.push(B);for(let T=1;T<s.rowCount;T++){let _="|";for(let M=0;M<s.colCount;M++){const H=p({row:T,col:M});_+=` ${H} |`}A.push(_)}return`${A.join(`
397
397
  `)}
@@ -417,7 +417,7 @@ ${s}
417
417
  <p>${l}</p>`}const Df={blockType:"code",blockKind:"complex",createBlockContent:cN,getBlockTextLength:aN,getRangeFromPoint:uN,moveCaret:dN,getCaretRect:hN,updateSelection:fN,clearSelection:mN,getChildContainers:gN,getNextContainer:pN,getSelectedContainers:CN,convertFrom:OP,handleBlockElementUpdated:AN,getOptions:vN,getBlockProperties:yN,convertTo:kN},U0={...In,blockType:"code-line"};class wN{constructor(t){m(this,"handleSelectionChange",()=>{const t=this.editor.selection;if(!t.range.isCollapsed())return;const e=t.focusedBlock;if(!yc(this.editor,e))return;const o=e,r=t.range.focus.offset,i=R4(this.editor,o,r,"code-caret");i.scrollIntoView({block:"nearest"}),setTimeout(()=>{i.remove(),this.editor.selection.caret.update()})});this.editor=t,t.addListener("selectionChanged",this.handleSelectionChange)}destroy(){this.editor.removeListener("selectionChanged",this.handleSelectionChange)}}function y7(n,t){const e=n.split(`
418
418
  `).map(s=>({id:K(),type:"text",text:Oi(s)})),o=K();return{blocks:{root:[{children:[o],type:"code",id:K(),...t}],[o]:e},meta:{},comments:{}}}class BN{handleBeforeCopy(t,e,o){const r=t.getFocusedBlock();if(!yc(t,r))return;const i=_0(r),s=t.getBlockData(i),{language:l,nowrap:a}=s;if(t.selection.range.isCollapsed()){const h=t.getBlockString(r);return y7(h,{language:l,nowrap:a})}const d=t.getSelectedText();return y7(d,{language:l,nowrap:a})}}function EN(n){if(!n.isWritable())return!1;const t=n.getFocusedBlock();if(!!yc(n,t)){if(n.selection.range.isCollapsed()){const e=n.selection.range.start;return n.insertTextToBlock(t,e.offset," "),!0}return n.undoManager.runInGroup(()=>{Lo(n).forEach(o=>{n.insertTextToBlock(o.block,0," ")})}),!0}}function xN(n){if(!n.isWritable())return!1;const t=n.getFocusedBlock();if(!yc(n,t))return;const e=[" "," "];return n.undoManager.runInGroup(()=>{Lo(n).forEach(r=>{const i=re(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}function IN(n){const t=n.getFocusedBlock(),e=nt(t);if(Xt(e))return;const o=ot(e);if(!o||Dt(o)!=="code")return;const r=n.selection.range;if(!!r.isSimple()&&!OA(e,r))return Yg(n,e),!0}const TN={Tab:EN,"Shift+Tab":xN,"CtrlOrCmd+A":IN},yu=S("code-text-decorate");class Sf{decorateText(t,e,o){var v;if(g(yu,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=re(s),a=t.doc.getBlockData(r.containerId,r.blockIndex),d=da.default.tokenize(l,(v=da.default.languages[a.language])!=null?v:da.default.languages.plain),h=(B,D)=>{if(g(yu,B,"no token"),typeof B=="string")return[{insert:B,attributes:mt.default(D)}];g(yu,B instanceof da.default.Token,"invalid token type");const T=B.content,_=mt.default(D);return _[`style-code-${B.type}`]=!0,typeof T=="string"?[{insert:T,attributes:_}]:Array.isArray(T)?T.map(z=>h(z,_)).flat():(g(yu,T instanceof da.default.Token,"invalid token"),h(T,_))},A=d.map(B=>h(B,{})).flat();return g(yu,rn(A)===rn(s),"failed to highlight code, text length mismatch"),{text:A}}}const DN={code:{title:"\u4EE3\u7801",abstract:"\u4EE3\u7801",wrap:"\u6362\u884C",copy:"\u590D\u5236",caption:"\u8BF4\u660E",search:"\u8F93\u5165\u5173\u952E\u8BCD\u641C\u7D22",copySuccess:"\u590D\u5236\u6210\u529F"}},SN={code:{title:"Code",abstract:"Code",wrap:"Wrap",copy:"Copy",caption:"Caption",search:"Search",copySuccess:"Copied successfully"}},LN={code:{title:"\u30B3\u30FC\u30C9",abstract:"\u30B3\u30FC\u30C9",wrap:"\u6298\u308A\u8FD4\u3059",copy:"\u8907\u88FD",caption:"\u4F8B\u8A3C\u3059\u308B",search:"\u30AD\u30FC\u30EF\u30FC\u30C9\u3067\u691C\u7D22",copySuccess:"\u30B3\u30D4\u30FC\u3055\u308C\u307E\u3057\u305F"}};R.mergeLang({"zh-CN":DN,"en-US":SN,"ja-JP":LN});const MN=S("image-data"),k7=1e3,z0=400,RN=10;function kc(n){return n.src.startsWith("empty:")||!n.src}function ON(n){return n.src.startsWith("http:")||n.src.startsWith("https:")}function w7(n){return`${Fd.default(n)}_width`}function B7(n){return`${Fd.default(n)}_height`}function E7(n){return`${n}_flex`}function x7(n){let t=n.getBoundingClientRect().width;return t-=Number.parseFloat(window.getComputedStyle(n).paddingLeft)+Number.parseFloat(window.getComputedStyle(n).paddingRight),t}function ku(n){if(n.every(r=>typeof r.flex=="number"&&r.flex))return;const t=100,o=n.map(r=>{const i=r.height==="auto"?r.width/t:r.height/t;return r.width/i}).reduce((r,i)=>r+i,0);n.forEach(r=>{const i=r.height==="auto"?r.width/t:r.height/t,s=r.width/i;r.flex=s/o})}function wc(n){const t=(r,i)=>{r||(r=`empty:${i}`);const s=w7(r),l=B7(r),a=E7(i);let d=n[s],h=n[l],p=n[a];return typeof d=="string"&&(d=Number.parseInt(d,10)),typeof h=="string"&&(h=Number.parseInt(h,10)),typeof p=="string"&&(p=Number.parseInt(p,10)),d&&h?{src:r,width:d,height:h,flex:p,virtualSize:!1}:d&&!h?{src:r,width:d,height:"auto",flex:p,virtualSize:!1}:(d=k7,h=z0,{src:r,width:d,height:h,flex:p,virtualSize:!0})};let e=[];const o=n.src;return Array.isArray(o)?e=o.map(t):typeof o=="string"&&(e=o.split("|").map(t)),ku(e),e}function Uo(n){const t=n.embedData;return wc(n.embedData).length>1?100:t.widthPercent}function _N(n,t,e,o){const r=wc(t.embedData);if(r.length>1||o)return"100%";const i=Uo(t),s=n.rootContainer.getBoundingClientRect().width;if(i){const l=x7(e);return`${Math.min(s*i/100,l)}px`}return r[0].width?`${r[0].width}px`:"auto"}function cn(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}`,a=w7(l);o[a]=r.width;const d=B7(l);r.height!=="auto"&&(o[d]=r.height)}g(MN,r.flex,"no image flex");const s=E7(i);o[s]=r.flex}),o}function FN(n,t,e,o){const r=wc(t.embedData),i=r.length===1?n.rootContainer:e;if(r.length===1&&o)return`${z0}px`;if(r.some(h=>h.height==="auto"))return"auto";const s=Uo(t);if(!s)return"";let l=i.getBoundingClientRect().width*(s/100);if(l-=Number.parseFloat(window.getComputedStyle(i).paddingLeft)+Number.parseFloat(window.getComputedStyle(i).paddingRight),i===n.rootContainer&&i!==e&&(l=Math.min(l,x7(e))),r.length===1){const h=r[0];return h.virtualSize?"":`${h.height/(h.width/l)}px`}l-=(r.length-1)*RN;const a=r.reduce((h,p)=>h+p.flex,0);let d=0;for(const h of r){const A=l*h.flex/a/h.width*h.height;d=Math.max(A,d)}return`${d}px`}function PN(n){return n.reduce((e,o)=>e+o.flex,0)}function NN(n,t){w("div",["resize-gripper",t],n).setAttribute("data-resize-type",t)}function V0(n){return le(n).querySelector(".block-resizer")}function $N(n){const t=V0(n);t&&et(t,"active")}function I7(n,t,e){const o=n.getBoundingClientRect(),r=t.getBoundingClientRect(),i=r.top-o.top,s=r.left-o.left,l=r.width,a=r.height;e.style.top=`${i}px`,e.style.left=`${s}px`,e.style.width=`${l}px`,e.style.height=`${a}px`}function HN(n,t,e,o){const r=V0(n);if(r)return W(r,"active"),I7(n,t,r),r;const i=le(n),s=w("div",["block-resizer"],i);return I7(n,t,s),e.resize.forEach(l=>{NN(s,l)}),s.addEventListener("mousedown",o),W(s,"active"),s}function W0(n,t){const e=V0(n);if(!e||!Kt(n,t))return;const o=n.getBoundingClientRect(),r=t.getBoundingClientRect(),i=r.top-o.top,s=r.left-o.left,l=r.width,a=r.height;e.style.top=`${i}px`,e.style.left=`${s}px`,e.style.width=`${l}px`,e.style.height=`${a}px`}const Lnt="",jN=S("block-resizer");class wu extends be.TypedEmitter{constructor(e,o){super();m(this,"resizableElement");m(this,"block",null);m(this,"startRect",null);m(this,"startPos",null);m(this,"resizeType",null);m(this,"enabled",!1);m(this,"handleMouseDown",e=>{e.preventDefault(),e.stopPropagation();const o=this.getResizableElement();if(!o||e.button!==0)return;const r=e.target;if(!r||!(r instanceof HTMLElement))return;const i=r.getAttribute("data-resize-type");!i||(this.bindEvents(),this.startRect=o.getBoundingClientRect(),this.startPos=e,this.resizeType=i,pa(window.getComputedStyle(r).cursor),this.block&&this.editor.selection.selectBlock(this.block,0))});m(this,"handleMouseMove",e=>{if(!this.startPos||!this.startRect||!this.resizeType||!this.getResizableElement()||!this.block)return;const r=e.x-this.startPos.x,i=e.y-this.startPos.y,s=this.startRect;let{top:l,left:a,right:d,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")&&(a+=r),(this.resizeType==="right"||this.resizeType==="top-right"||this.resizeType==="bottom-right")&&(d+=r);const p=d>a?d-a:0,A=h>l?h-l:0,v=new DOMRect(a,l,p,A);this.emit("resizing",this,v);const B=this.getResizableElement();B&&W0(this.block,B)});m(this,"handleMouseUp",e=>{if(e.button!==0)return;pa(""),this.unbindEvents(),this.emit("resized",this);const o=this.getResizableElement();!o||!this.block||W0(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||($N(this.block),this.enabled=!1)}update(e,o){this.block=e,this.resizableElement=o,this.getResizableElement()&&this.enabled&&this.createResizer()}updateResizer(){const e=this.getResizableElement();e&&this.block&&W0(this.block,e)}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||(g(jN,Kt(this.block,e),"not a block child element"),HN(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)}}const UN=S("image-dom");function T7(n){return n.querySelector(".uploading-progress-mask")}function zN(n){const t=T7(n);if(t)return t;const e=w("div",["uploading-progress-mask"],n),o=w("div",["uploading-progress-bar"],e);return w("div",["uploading-progress-bar-value"],o),o}function VN(n){const e=zN(n).querySelector(".uploading-progress-bar-value");return g(UN,e,"no progress value"),e}function D7(n,t){const e=VN(n);e.style.width=`${t}%`}function WN(n){var t;(t=T7(n))==null||t.remove()}function Bu(n,t,e,o){const r=e!=null?e:n.findBlockById(t.id);if(!r)return;const i=o||nt(r),s=!!r.querySelector(".images > .image-container.error, .images > .image-container.empty "),l=_N(n,t,i,s),a=FN(n,t,i,s),d=Rt(r);l==="auto"?d.style.width=l:(d.style.maxWidth=l,d.style.width="100%");const h=r.querySelector(".images");!h||(h.style.height=a||"none")}function qN(n){let t;return n.forEach((e,o)=>{o.toLocaleLowerCase()==="content-type"&&(t=e)}),t!=null?t:""}async function GN(n){try{const t=await fetch(n,{credentials:"same-origin"}),e=await t.blob(),o=qN(t.headers).toLocaleLowerCase();let r="";if(o){const s=mm.default[o].extensions;s&&s.length>0&&(r=s[0])}return new File([e],`${Date.now()}.${r}`,{type:o})}catch{return null}}function Ki(n,t){const e=typeof t=="string"?t:it(t);return n.getCustom(`image-${e}`)}function Lf(n,t){if(!t||!(t instanceof Node))return null;const e=ot(t);return e?Ki(n,e):null}function Qr(n){return Array.from(n.querySelectorAll(".image-container"))}const q0=S("table-resize-drag-drop");class ZN{constructor(t,e,o,r){m(this,"cursor","col-resize");m(this,"initWidths");this.editor=t,this.elem=e,this.data=o,this.mouseDownEvent=r;const i=this.data.block,l=Ki(this.editor,i).getImages(),a=this.data.splitterIndex;g(q0,a>=0&&a<l.length-1,`invalid splitter index: ${a}`);const h=Qr(i).map(p=>p.getBoundingClientRect().width);this.initWidths=h}onDragStart(t,e,o){if(!this.editor.isWritable())return;const r=this.data.block;Ki(this.editor,r).setResizing(!0)}onDragging(t,e,o,r,i){const s=this.data.block,l=Ki(this.editor,s),a=mt.default(l.getImages()),d=this.data.splitterIndex;g(q0,d>=0&&d<a.length-1,`invalid splitter index: ${d}`);const h=this.initWidths[d],p=this.initWidths[d+1];if(h+p<100)return;let A=r;h+A<50&&(A=50-h),p-A<50&&(A=p-50);const D=[...this.initWidths];D[d]+=A,D[d+1]-=A;const T=Qr(s);g(q0,T.length===a.length,"invalid image data");const _=D.reduce((z,q)=>z+q,0);for(let z=0;z<a.length;z++){const q=D[z]/_;a[z].flex=q,T[z].style.flexGrow=`${q}`}const M=mt.default(this.editor.getBlockData(s)),H=cn(a,Uo(M));M.embedData=H,Bu(this.editor,M,s,null)}onDragEnd(t,e,o,r,i){const s=this.data.block,l=Ki(this.editor,s),d=Qr(s).map(h=>Number.parseFloat(h.style.flexGrow));l.updateFlex(d),l.setResizing(!1)}}function S7(n){var t;return!n||!(n instanceof HTMLElement)?null:xt(n,"image-splitter")?n:(t=n.closest(".image-splitter"))!=null?t:null}function QN(n,t){var s;const e=S7(t.target);if(!e)return;const o=ot(e);if(!o)return;Ki(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};wm(new ZN(n,e,i,t))}function YN(n,t){t.preventDefault(),t.stopPropagation();const e=S7(t.target);if(!e)return;const o=ot(e);!o||Ki(n,o).resetFlex()}function JN(n,t,e,o){const r=w("div",["image-splitter"],e);w("div",["image-splitter-indicator"],r),r.setAttribute("data-index",`${o}`),n.domEvents.addEventListener(r,"mousedown",QN),n.domEvents.addEventListener(r,"dblclick",YN)}const KN=S("image-item");function L7(n){return!n||!(n instanceof Node)?null:ot(n)}function M7(n){const t=L7(n);return t?Qr(t):[]}function G0(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 Eu(n){const t=G0(n);return t?M7(n).indexOf(t):-1}async function XN(n,t){const e=Lf(n,t.target);if(!e)return;const o=Eu(t.target);if(o===-1)return;const r=t.target;if(!(r instanceof HTMLImageElement))return;const i=e.getImages()[o];if(kc(i)||n.readonly||!e.isAutoFix()||(setTimeout(()=>{e.setAutoFix(!1)},400),i.height==="auto"&&e.fixImageSize(o,r),i.virtualSize&&e.fixImageSize(o,r),!i||!ON(i)||i.downloading))return;i.downloading=!0;const s=await GN(i.src);s?e.replaceImage(o,s):KN.warn(`failed to download image: ${i.src}`)}function t$(n,t,e){if(t.querySelector(".load-error"))return;const r=e.src.startsWith("http:")||e.src.startsWith("https:"),i=w("div",["load-error"],t),s=w("div",["error-icon"],i);s.innerHTML=dv;const l=w("div",["error-message"],i);r?(l.innerHTML=R.t("image.load.remote.failed"),n.domEvents.addEventListener(i,"click",(a,d)=>{d.preventDefault(),d.target instanceof HTMLElement&&d.target.tagName==="A"&&window.open(e.src,"_blank")})):(l.innerHTML=R.t("image.load.failed"),n.domEvents.addEventListener(i,"click",(a,d)=>{d.preventDefault(),d.stopPropagation(),d.target instanceof HTMLElement&&d.target.tagName==="A"&&r$(a,d.target)}))}function Z0(n,t){setTimeout(()=>{if(Kt(n.rootContainer,t)){const e=n.getBlockData(t);Bu(n,e,null,null)}})}function e$(n,t){const e=Lf(n,t.target);if(!e)return;const o=Eu(t.target);if(o===-1)return;const r=e.getImages()[o];if(!r)return;const i=G0(t.target);if(!i)return;W(i,"error","error-load");const s=ot(i);s&&Z0(n,s),i.innerHTML="",t$(n,i,r)}function n$(n,t,e){if(t.querySelector(".upload-error"))return;const r=w("div",["upload-error"],t),i=w("div",["error-icon"],r);i.innerHTML=dv;const s=w("div",["error-message"],r);s.innerHTML=R.t("image.upload.failed"),n.domEvents.addEventListener(r,"click",(l,a)=>{if(a.preventDefault(),!a.target||!(a.target instanceof Element)||a.target.tagName!=="A")return;const d=Lf(l,a.target),h=Eu(a.target);!d||h===-1||d.replaceImage(h,e)})}function R7(n,t,e,o,r){const i=Qr(t)[e];!i||(W(i,"error","error-upload"),Z0(n,t),i.innerHTML="",n$(n,i,r))}function O7(n,t,e,o,r,i,s){const l=w("div",["image-container"],e);if(l.setAttribute("data-src",o.src),s.length>1&&(l.style.flexShrink=`${o.flex}`,l.style.flexGrow=`${o.flex}`),i===r&&W(l,"active"),kc(o)){W(l,"empty");const d=w("div",["upload-image-icon"],l);return d.innerHTML=IL,l}const a=w("img",["editor-image"],l);if(a.src=n.doc.buildResourceUrl(o.src),n.domEvents.addEventListener(a,"load",XN),n.domEvents.addEventListener(a,"error",e$),o.src.startsWith("https:")||o.src.startsWith("http:")){const d=w("div",["image-warning"],l);d.innerHTML=uv,d.setAttribute(`data-editor-tooltip-${n.clientId}`,R.t("image.load.remote.tooltip"))}return l}function o$(n,t,e,o,r){const i=w("div",["images"],e);return o.forEach((s,l)=>{l>0&&JN(n,t,i,l-1),O7(n,t,i,s,l,r,o)}),o.length>1&&W(t,"multi"),i}function _7(n,t,e,o,r,i){const l=Array.from(t.querySelectorAll(".image-container"))[o];if(!l)return;const a=O7(n,t,null,e,o,r,i);l.insertAdjacentElement("beforebegin",a),l.remove(),Z0(n,t)}function xu(n,t){return Qr(n)[t]}function r$(n,t){const e=L7(t);if(!e)return;const o=Eu(t);if(o===-1)return;const r=Lf(n,t);if(!r)return;const i=r.getImages()[o];_7(n,e,i,o,r.getSelectedIndex(),r.getImages())}function zo(n){return Dt(n)==="embed"&&Un(n)==="image"}async function F7(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 i$(n){const t=await Ul(n);return F7(t)}function P7(n){var o;let t="image/*";const e=(o=n.getComponentOptions("image"))==null?void 0:o.allowedMedias;return e&&(t=e.map(r=>`.${r}`).join(",")),t}function N7(n,t){var s;const{maxSize:e,allowedMedias:o,callbacks:r}=(s=n.getComponentOptions("image"))!=null?s:{};if(e&&t.size>e){const l=new Error("image is too large");throw l.code="MaxMediaSize",r!=null&&r.onError&&(r==null||r.onError(n,l)),l}const i=Aa(t.name);if(o&&!o.includes(i)){const l=new Error(`media file is not allowed: ${i}`);throw l.code="NotAllowedFile",r!=null&&r.onError&&(r==null||r.onError(n,l)),l}}function $7(n){return n.startsWith("image/")}const H7=S("image-object");class xe{constructor(t,e){m(this,"images",[]);m(this,"selectedIndex",-1);m(this,"blockResizer");m(this,"resizing",!1);m(this,"parentContainerResizerObserver",null);m(this,"autoFix",!1);m(this,"handleMouseDown",async(t,e)=>{const o=Eu(e.target);if(o===-1)return;const r=this.images[o];kc(r)||this.setSelectedIndex(o)});m(this,"handleRootContainerResize",()=>{this.handleEditorResize(this.editor.rootContainer)});m(this,"handleEditorResize",t=>{if(this.isEmpty()||this.resizing)return;const e=this.editor.findBlockById(this.blockData.id);!e||nt(e)===t&&Bu(this.editor,this.blockData,e,null)});m(this,"handleResizing",(t,e)=>{const o=this.editor.findBlockById(this.blockData.id);if(!o)return;this.autoFix||this.setAutoFix(!0);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 a=l*100/i;this.blockData.embedData.widthPercent=a,Bu(this.editor,this.blockData,o,null)});m(this,"handleResized",t=>{const e=this.editor.findBlockById(this.blockData.id);if(!e)return;const o=cn(this.images,Uo(this.blockData));this.editor.updateEmbedData(e,o),this.blockResizer.enableResize(e)});m(this,"fixImageSizes",He.default(()=>{const t=this.editor.findBlockById(this.blockData.id);if(!t)return;const e=cn(this.images,Uo(this.blockData));this.editor.updateEmbedData(t,e)},1e3));this.editor=t,this.blockData=e,this.blockResizer=new wu(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=wc(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()}setAutoFix(t){this.autoFix=t}isAutoFix(){return this.autoFix}createContent(t,e,o){const r=o$(this.editor,e,o,this.images,this.selectedIndex);if(this.editor.domEvents.addEventListener(o,"mousedown",this.handleMouseDown),this.editor.addListener("resize",this.handleRootContainerResize),Do(t)){const s=()=>{this.handleEditorResize(t)};this.parentContainerResizerObserver=new ResizeObserver(s),this.parentContainerResizerObserver.observe(t)}const i=()=>!!(this.images.length===1&&this.images[0].virtualSize);this.isEmpty()&&i()&&W(r,"empty"),Bu(this.editor,this.blockData,e,t),setTimeout(()=>{const s=this.editor.findBlockById(this.blockData.id);s&&this.blockResizer.update(s)})}getImages(){return this.images}getWidthPercent(){return Uo(this.blockData)}isEmpty(){return this.images.length===1&&kc(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=xu(e,this.selectedIndex);r&&et(r,"active")}this.selectedIndex=t;const o=xu(e,t);o&&W(o,"active")}async requestUploadImage(t){const e=this.editor.findBlockById(this.blockData.id);if(!e)return;const o=xu(e,t);if(xt(o,"error"))return;const r=P7(this.editor),i=await zl(r);await this.replaceImage(t,i)}tryEnableResizer(){const t=this.editor.findBlockById(this.blockData.id);if(!t||!this.editor.isWritable())return;const e=xu(t,0);!this.isEmpty()&&this.images.length===1&&!xt(e,"error")&&this.blockResizer.enableResize(t)}disableResizer(){this.blockResizer.disableResize()}fixImageSize(t,e){const o=this.images[t];kc(o)||(o.height==="auto"&&(o.height=e.height),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=mt.default(this.images);if(o.splice(t,1),o.length===0)return this.editor.deleteBlock(e),!0;o[0].flex=NaN,ku(o),this.selectedIndex>=o.length&&(this.selectedIndex=o.length-1);const r=cn(o,Uo(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 Ul(e),s=this.images[t];if(s.virtualSize){const{width:a,height:d}=await F7(i);s.width=a,s.height=d,s.virtualSize=!1;const h=cn(this.images,Uo(this.blockData));this.editor.updateEmbedData(o,h)}const l={...s,src:i};_7(this.editor,o,l,t,this.selectedIndex,this.images),setTimeout(()=>{this.blockResizer.update(o)})}catch(i){return R7(this.editor,o,t,i,e),!1}const r=xu(o,t);if(!r)return!1;W(r,"uploading"),D7(r,0),W(o,"media-block-uploading");try{const i=await this.editor.doc.uploadResource(e,{onProgress:a=>{D7(r,a)}});et(r,"uploading"),this.images[t].src=i.resourceId;const s=this.editor.findBlockById(this.blockData.id);if(!s)return!1;et(s,"media-block-uploading");const l=cn(this.images,Uo(this.blockData));return this.editor.updateEmbedData(s,l),!0}catch(i){H7.error(i);const s=this.editor.findBlockById(this.blockData.id);return s&&(et(r,"uploading"),WN(r),R7(this.editor,s,t,i,e),et(s,"media-block-uploading")),!1}}updateFlex(t){const e=this.editor.findBlockById(this.blockData.id);if(!e)return;g(H7,t.length===this.images.length,"invalid flex");for(let r=0;r<this.images.length;r++)this.images[r].flex=t[r];const o=cn(this.images,Uo(this.blockData));this.editor.updateEmbedData(e,o)}resetFlex(){const t=this.editor.findBlockById(this.blockData.id);if(!t)return;const e=mt.default(this.images);e[0].flex=NaN,ku(e);const o=cn(e,Uo(this.blockData));this.editor.updateEmbedData(t,o)}setData(t){this.blockData=t,this.images=wc(t.embedData)}static create(t,e){const o=t.addCustom(`image-${e.id}`,()=>new xe(t,e));return o.setData(e),o}static getImageObject(t,e){let o;return typeof e=="string"?o=e:o=it(e),t.getCustom(`image-${o}`)}}const Mnt="",Rnt="";function Mf(n){const t=le(n);let e=t.querySelector(":scope > .block-helper");return e||(e=w("div",["block-helper"],t),w("span",["helper-sizer"],e,"A")),e}function Q0(n,t,e){const o=Mf(n),i=Array.from(o.children).find(s=>{var a;return Number.parseInt((a=s.getAttribute("data-index"))!=null?a:"0",10)>e});o.insertBefore(t,i!=null?i:null)}const j7=40,s$=20;class l${findTargetBlock(t,e){const o=e.target;if(o&&o instanceof Element){const a=ot(o);if(a&&Kt(t.rootContainer,a))return a}let r=e.clientX,i=e.clientY;const s=t.rootContainer.getBoundingClientRect().left;r<s&&s-r<j7&&(r+=j7);let l=document.elementFromPoint(r,i);if(l){const a=ot(l);if(a&&Kt(t.rootContainer,a))return a}if(i-=s$,l=document.elementFromPoint(r,i),l){const a=ot(l);if(a&&Kt(t.rootContainer,a))return a}return null}destroy(){}}class c$ extends Cf{constructor(e){super(e,{trigger:[],id:"empty-block-menu"});m(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 a$(n,t,e){const o=Wm(n,t);if(!o)return[];const r=[];return Object.values(o).forEach(i=>{e!=null&&e.has(i.group)||r.push(...i.commands.map(s=>({...s,source:"block-command",blockMenuItemCustomData:i.group})))}),r}function Y0(n,t,e={withPlainText:!1}){const o=D0(n,e),r=i=>{i.forEach(s=>{s.source=t,s.children&&r(s.children)})};return r(o),o}function u$(n,t,e,o=!1){var d,h;const r=nt(t);let s=bt(t);he(n,t)||o||(s+=1);const l=at(r),a=e;return a.commandProvider?a.commandProvider.executeCommand(n,e,{from:"block-menu",containerId:l,blockIndex:s}):(h=(d=a.blockOptions)==null?void 0:d.handleInsertEmptyBlock)==null?void 0:h.call(d,n,{containerId:l,blockIndex:s,item:e})}function d$(n,t){const e=Io(n,t),o=n.getBlockData(t);return!(e!=="text"||o.heading)}class U7{constructor(t,e,o){m(this,"source","text-style");m(this,"id","text-style-item");m(this,"name","Text styles");m(this,"element");m(this,"createHeadingItemElement",(t,e,o)=>{var i;const r=B0();this.createItem("text",nu,e,d$(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)})});m(this,"createListItemElement",(t,e,o)=>{const{checkbox:r,ordered:i}=o,l=Dt(t)==="list",a=l&&i===!1&&!r,d=l&&i,h=l&&!!r;this.createItem("unordered-list",Cv,e,a),this.createItem("ordered-list",Av,e,d),this.createItem("check-list",gv,e,h)});m(this,"handleClick",(t,e)=>{var l,a;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"&&gf(t,this.block,null),i.startsWith(s)){const d=Number.parseInt(i.substring(s.length),10);d&&gf(t,this.block,d)}if(i==="blockquote"&&y0(t,this.block),i.startsWith("align")){const d=i.replace(/^align-/,"");T9(t,this.block,d)}(i==="unordered-list"||i==="ordered-list"||i==="check-list")&&w0(t,this.block,i),(a=(l=this.options).onAfterStyleItemClick)==null||a.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=w("div",["text-styles"],null),r=w("div",["text-style-section"],o),i=t.getBlockData(e);if(!this.options.fromEmbed){const l=i.heading,a=i.quoted;this.createHeadingItemElement(e,r,l),this.createListItemElement(e,r,i),this.createItem("blockquote",pv,r,!!a)}const s=i.align||"left";return this.createItem("align-left",tu,r,s==="left"),this.createItem("align-center",Lp,r,s==="center"),this.createItem("align-right",Sp,r,s==="right"),o}createItem(t,e,o,r=!1){const i=["style-icon","text-style-item"];r&&i.push("active");const s=Hl(e,i,o);s.id=t}}function z7(){return{source:"separator",type:"separator",id:`section-${K()}`,name:""}}const V7={copy:VL,cut:WL,delete:qL,"lock-block":GL,"unlock-block":ZL,comment:eu},h$=["image","video"];function f$(n,t,e){const o=[],r=tt(n,t),i=Le(t)&&h$.includes(Un(t));if(r?o.push(new U7(n,t,e)):i&&o.push(new U7(n,t,{...e,fromEmbed:!0})),!he(n,t)){(r||i)&&o.push(z7());const s=a$(n,t,new Set(["hovering-toolbar"]));s.sort((l,a)=>{var d,h;return((d=l.order)!=null?d:0)-((h=a.order)!=null?h:0)}),s.forEach(l=>{l.id in V7&&(l.icon=V7[l.id])}),o.push(...s)}return he(n,t)?o.push(...Y0(n,"insert-block")):o.push(z7(),{id:"insert-block-before",icon:QL,name:R.t("blockMenu.command.insertAbove"),children:Y0(n,"insert-block-before",{withPlainText:!0}),childrenMenuId:"quick-menu",source:"insert-block-before"},{id:"insert-block-after",icon:YL,name:R.t("blockMenu.command.insertAfter"),children:Y0(n,"insert-block",{withPlainText:!0}),source:"insert-block",childrenMenuId:"quick-menu"}),o}function m$(n,t,e){if(e.source==="block-command"){const o=e.blockMenuItemCustomData;d4(n,t,o,e)}else(e.source==="insert-block"||e.source==="insert-block-before")&&u$(n,t,e,e.source==="insert-block-before")}const g$=S("exclusive-block");function J0(n,t,e,o){var l;W(t,"block-exclusive");const r=Qt(n,t),i=(l=r.getBlockProperties)==null?void 0:l.call(r,n,t),{abstract:s}=i||{};t.setAttribute("data-user-name",o),t.setAttribute("data-user-id",e),t.setAttribute("data-exclusive-tips",R.t("exclusive.tips",{editor:o,embedType:s||R.t("exclusive.fallbackAbstract")}))}function W7(n){et(n,"block-exclusive"),n.removeAttribute("data-user-name"),n.removeAttribute("data-user-id"),n.removeAttribute("data-exclusive-tips")}function p$(n,t,e,o,r){g$.debug(`block ${it(t)} ${e?"exclusive":"unexclusive"}, ${o}, ${r}`),e?J0(n,t,o,r):W7(t)}function Rf(n){return n.classList.contains("block-exclusive")}function q7(n,t){t.blockIds.forEach(e=>{const o=n.findBlockById(e);o&&p$(n,o,t.exclusive,t.userId,t.displayName)})}class Xi{constructor(t){m(this,"exclusiveBlockIds",new Set);m(this,"exclusiveBlockTimer",0);m(this,"remoteExclusiveBlockIds",new Map);m(this,"handleUserChanged",t=>{const e=new Set(t.map(r=>r.userId));Array.from(this.remoteExclusiveBlockIds.entries()).forEach(([r,i])=>{if(!e.has(i.userId)){this.remoteExclusiveBlockIds.delete(r);const s={...i,exclusive:!1};q7(this.editor,s)}});const o=Array.from(this.exclusiveBlockIds).map(r=>this.editor.findBlockById(r)).filter(r=>!!r);o.length>0&&this.broadcastExclusiveBlockMessage(o,!0)});this.editor=t,t.doc.registerCallback(this),t.doc.getRemoteUsers().addListener("change",this.handleUserChanged)}destroy(){this.stopExclusiveBlockTimer(),this.editor.doc.unregisterCallback(this),this.editor.doc.getRemoteUsers().addListener("change",this.handleUserChanged)}onCustomMessage(t){if(t.type==="exclusiveBlock"){const e=t;q7(this.editor,e),e.blockIds.forEach(o=>{e.exclusive?this.remoteExclusiveBlockIds.set(o,e):this.remoteExclusiveBlockIds.delete(o)})}}getExclusiveMessage(t){return this.remoteExclusiveBlockIds.get(t)}broadcastExclusiveBlockMessage(t,e){if(this.editor.readonly||t.length===0)return;const o=this.editor.doc.getUser(),r={type:"exclusiveBlock",userId:o.userId,displayName:o.displayName,blockIds:t.map(i=>it(i)),exclusive:e};this.editor.doc.broadcastMessage(r)}exclusiveBlock(t){this.exclusiveBlockIds.has(it(t))||(this.broadcastExclusiveBlockMessage([t],!0),this.exclusiveBlockIds.add(it(t)),this.exclusiveBlockIds.size===1&&this.startExclusiveBlockTimer())}unexclusiveBlock(t){!this.exclusiveBlockIds.has(it(t))||(this.exclusiveBlockIds.delete(it(t)),this.broadcastExclusiveBlockMessage([t],!1),this.exclusiveBlockIds.size===0&&this.stopExclusiveBlockTimer())}startExclusiveBlockTimer(){this.exclusiveBlockTimer=window.setInterval(()=>{Array.from(this.exclusiveBlockIds.keys()).forEach(t=>{this.broadcastExclusiveBlockMessage([this.editor.getBlockById(t)],!0)})},30*1e3)}stopExclusiveBlockTimer(){clearInterval(this.exclusiveBlockTimer),this.exclusiveBlockTimer=0}static get(t){return t.addCustom("exclusiveBlock",()=>new Xi(t))}static register(t){return this.get(t)}}function K0(n,t){Xi.get(n).exclusiveBlock(t)}function X0(n,t){Xi.get(n).unexclusiveBlock(t)}class G7{writable(t,e){if(Rf(e))return!1}create(t,e,o,r,i){const s=Xi.get(t).getExclusiveMessage(i.id);s&&J0(t,r,s.userId,s.displayName)}update(t,e,o,r,i){const s=Xi.get(t).getExclusiveMessage(i.id);s?J0(t,r,s.userId,s.displayName):W7(r)}}const Ont="",C$={exclusive:{tips:"\u300C{editor}\u300D\u6B63\u5728\u7F16\u8F91\uFF0C\u300C{embedType}\u300D\u4E0D\u652F\u6301\u591A\u4EBA\u7F16\u8F91",fallbackAbstract:"\u8BE5 Block"}},A$={exclusive:{tips:"\u300C{editor}\u300Dis editing\uFF0C\u300C{embedType}\u300Ddoes not support multi-person editing",fallbackAbstract:"This Block"}},b$={exclusive:{tips:"\u300C{editor}\u300D\u306F\u7DE8\u96C6\u4E2D\u3067\u3059\u3002\u300C{embedType}\u300D\u306F\u8907\u6570\u4EBA\u3067\u540C\u6642\u7DE8\u96C6\u3067\u304D\u307E\u305B\u3093",fallbackAbstract:"\u3053\u306E\u8981\u7D20"}};R.mergeLang({"zh-CN":C$,"en-US":A$,"ja-JP":b$});function Iu(n,t){return n.getBlockData(t).lock}function Of(n,t){return!!Iu(n,t)}function Tu(n,t){const e=Iu(n,t);return e?e.userId===n.doc.getUser().userId:!1}function t2(n,t){const e=Iu(n,t);return e?e.userId!==n.doc.getUser().userId:!1}function v$(n,t){if(n.readonly||!n.isBlockWritable(t)||Of(n,t)&&!Tu(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 y$(n,t){if(!Tu(n,t))return;const e={lock:null};n.updateBlockData(t,e)}const k$=10,w$=80;class e2{constructor(){m(this,"executeCommand",(t,e,o)=>{const r=o.data;if(!r||!r.blockId)return;const i=t.getBlockById(r.blockId);r.type==="lock"?v$(t,i):r.type==="unlock"&&y$(t,i)})}create(t,e,o,r,i){const s=i.lock;s&&(s.userId!==t.doc.getUser().userId?W(r,"locked-by-others"):W(r,"locked-by-self"))}update(t,e,o,r,i){const s=i.lock;if(s)if(s.userId!==t.doc.getUser().userId){W(r,"locked-by-others");const l=t.selection.focusedBlock;(l===r||Kt(r,l))&&(tt(t,r)||Dt(r)==="code")&&t.insertTextBlock("",at(o),bt(r)+1)}else W(r,"locked-by-self");else et(r,"locked-by-others"),et(r,"locked-by-self")}writable(t,e){if(t2(t,e))return!1;if(ro(e))return;let o=Is(e);for(;o;){if(t2(t,o))return!1;o=Is(o)}}commands(t,e){const o=Of(t,e),r=Tu(t,e),i=Rf(e),s={blockId:it(e),type:"lock"},l={id:"lock-block",name:"",data:s,order:10};if(o)if(r)l.id="unlock-block",l.name=R.t("locker.unlock"),s.type="unlock";else{const a=Iu(t,e);let d=(a==null?void 0:a.displayName)||"";const h=OC(d,k$,w$);(h==null?void 0:h.length)!==d.length&&(l.ellipsisTooltip=a==null?void 0:a.displayName,d=h||""),l.name=R.t("locker.lockedBy",{name:d}),l.states=["disabled"]}else i?(l.name=R.t("locker.lock"),l.states=["disabled"]):l.name=R.t("locker.lock");return{group:"block-locker",commands:[l],executeCommand:this.executeCommand}}}const _nt="",B$={locker:{lock:"\u9501\u5B9A",unlock:"\u89E3\u9664\u9501\u5B9A",lockedBy:"\u88AB {name} \u9501\u5B9A"}},E$={locker:{lock:"Lock",unlock:"Unlock",lockedBy:"Locked by {name}"}},x$={locker:{lock:"\u30ED\u30C3\u30AF",unlock:"\u30ED\u30C3\u30AF\u89E3\u9664",lockedBy:"{name}\u304C\u30ED\u30C3\u30AF\u3057\u307E\u3057\u305F"}};R.mergeLang({"zh-CN":B$,"en-US":E$,"ja-JP":x$});class _f{async handleBeforePasteDoc(t,e){return Object.values(e.blocks).forEach(o=>{o.forEach(r=>{delete r.lock})}),!1}}const I$=S("standard-block-actions");class T${constructor(){m(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"&&Rh(t,i),o.id==="cut"&&(Rh(t,i),t.deleteBlock(i))}catch(i){I$.error(`failed to execute block command: ${JSON.stringify(i)}`)}})}commands(t,e){const o=Of(t,e),r=o&&Tu(t,e),i=it(e),s=j0(),l=Rf(e),a={id:"copy",name:R.t("blockMenu.command.copy"),data:i,order:1,states:s?[]:["disabled"],disableReason:s?void 0:R.t("copyCutProperty.unsafeEnvTips",{shortCut:Bo("CtrlOrCmd+C"),operation:R.t("copyCutProperty.copy")})},d={id:"cut",name:R.t("blockMenu.command.cut"),data:i,order:2,states:o&&!r||!s||l?["disabled"]:[],disableReason:s?void 0:R.t("copyCutProperty.unsafeEnvTips",{shortCut:Bo("CtrlOrCmd+X"),operation:R.t("copyCutProperty.cut")})},h={id:"delete",name:R.t("blockMenu.command.delete"),data:i,order:3,states:o&&!r||l?["disabled"]:[]};return{group:"standard-block-actions",commands:[a,d,h],executeCommand:this.executeCommand}}}const Z7=S("block-menu");class D${constructor(t){m(this,"menu");m(this,"currentBlock",null);m(this,"commandBlock",null);m(this,"handleShow",()=>{g(Z7,this.currentBlock,"no target block before show block menu");const t=f$(this.editor,this.currentBlock,{onAfterStyleItemClick:this.close});this.menu.updateItems(t),this.commandBlock=this.currentBlock});m(this,"handleClose",()=>{Fp(this.editor)&&this.editor.focus()});m(this,"handleItemClick",(t,e)=>{g(Z7,this.commandBlock,"no command block before show block menu"),m$(this.editor,this.commandBlock,e),e.element||this.close()});m(this,"close",()=>{this.menu.close("clickItem")});this.editor=t,this.menu=new zs([],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 T$)}show(t,e){this.menu.manualShow(t,{placement:"bottom-start",...e})}isInMenu(t){return this.menu.isInCommandBar(t)}setBlock(t){this.currentBlock=t}get isVisible(){return this.menu.isVisible}destroy(){this.menu.destroy()}}const S$=1e3;async function L$(n,t){const{width:e}=n.rootContainer.getBoundingClientRect(),o=t.getBoundingClientRect();return o.width>e||o.height>=S$?"":(await Q5.default.toSvg(t)).replace(/margin-block:.*?;/,"").replace(/margin:.*?;/,"")}const M$=S("drag-preview-image");class R${constructor(t){m(this,"startPosition",null);m(this,"dragContainer",null);m(this,"handleDragStart",async(t,e)=>{const o=t.target;g(M$,o instanceof Element,`Invalid Drag target:${o}`);const{x:r,y:i}=t;this.startPosition={x:r,y:i};const s=w("div",["drag-image-container"],this.editor.rootContainer),l=w("img",["drag-image"],s),a=w("span",["drag-loading"],s);a.innerHTML=tM;const{x:d,width:h,height:p,y:A}=o.getBoundingClientRect(),v=this.editor.rootContainer.getBoundingClientRect(),B=e.getBoundingClientRect();s.style.left=`${d+h}px`,s.style.top=`${A+p}px`,s.style.width=`${Math.min(v.width/2,B.width)}px`,this.dragContainer=s;const T=await L$(this.editor,e);T?l.src=T:W(s,"drag-placeholder"),Am(s,{status:"loaded"})});m(this,"handleDrag",t=>{if(this.startPosition&&this.dragContainer){const{x:e,y:o}=t;if(e===0&&o===0){this.dragContainer.style.transition="transform 0.15s, opacity .15s",this.dragContainer.style.transform="",this.dragContainer.style.opacity="0";return}const{x:r,y:i}=this.startPosition,s=e-r,l=o-i;this.dragContainer.style.transform=`translate(${s}px, ${l}px)`}});m(this,"handleDragEnd",()=>{this.dragContainer&&(this.dragContainer.remove(),this.startPosition=null,this.dragContainer=null)});this.editor=t}}const Q7="drag-preview-element";function O$(n){if(xt(n,Q7))return n;const t=n.querySelector(`.${Q7}`);return t||(Le(n)?Rt(n):n)}const Ff=S("block-menu-drag-handler");function n2(n,t){return new DragEvent(t,{bubbles:!0,cancelable:!0,view:window,screenX:n.screenX,screenY:n.screenY,dataTransfer:new DataTransfer,clientX:n.clientX,clientY:n.clientY})}class _${constructor(t,e){m(this,"dragPreview");m(this,"autoScroll");m(this,"oldPos",{x:0,y:0});m(this,"handleMouseDown",t=>{const e=this.button.blockMenu.currentBlock;if(g(Ff,e,"no dragged block"),!this.editor.isBlockWritable(e)){t.preventDefault(),t.stopPropagation();return}const{x:o,y:r}=t;this.oldPos={x:o,y:r},document.addEventListener("mouseup",this.handleDragEnd),this.editor.contentElement.addEventListener("mousemove",this.handleDrag)});m(this,"handleDragStart",t=>{var s,l;const e=oo(this.button.buttonElement);this.autoScroll||(this.autoScroll=new Gd({scrollElement:e,trackMouseEvent:"mousemove",edge:{top:50,bottom:50}}));const o=this.button.blockMenu.currentBlock;g(Ff,o,"no dragged block"),(l=(s=Qt(this.editor,o)).notify)==null||l.call(s,this.editor,"beginDrag");const r=n2(t,"dragstart");H$(this.editor,r,o),window.isDragging=!0,this.button.buttonElement.style.opacity="0";const i=O$(o);this.dragPreview.handleDragStart(t,i),this.autoScroll.active(),W(o,"dragging"),W(this.editor.contentElement,"dragging")});m(this,"handleDrag",t=>{const{target:e,x:o,y:r}=t;if(this.oldPos.x===o&&this.oldPos.y===r)return;window.isDragging||this.handleDragStart(t),this.oldPos={x:o,y:r},g(Ff,e instanceof Element,"target is invalid"),this.dragPreview.handleDrag(t);const i=n2(t,"dragover");this.editor.contentElement.dispatchEvent(i)});m(this,"handleDragEnd",t=>{var r;const e=this.button.blockMenu.currentBlock;g(Ff,e,"no dragged block"),window.isDragging=!1,this.button.buttonElement.style.opacity="1",this.dragPreview.handleDragEnd(),(r=this.autoScroll)==null||r.inactive(),et(e,"dragging"),et(this.editor.contentElement,"dragging"),document.removeEventListener("mouseup",this.handleDragEnd),this.editor.contentElement.removeEventListener("mousemove",this.handleDrag);const o=n2(t,"drop");this.editor.contentElement.dispatchEvent(o)});this.editor=t,this.button=e,this.button.buttonElement.addEventListener("mousedown",this.handleMouseDown),this.dragPreview=new R$(t)}destroy(){this.button.buttonElement.removeEventListener("mousedown",this.handleMouseDown)}}class Du{constructor(t){m(this,"highlightedBlockId","");m(this,"handleSelectionChange",()=>{this.clearHighlightedBlock()});this.editor=t,this.editor.addListener("selectionChanged",this.handleSelectionChange)}highlightBlock(t){this.clearHighlightedBlock(),this.highlightedBlockId=it(t),W(t,"highlighted")}clearHighlightedBlock(){if(this.highlightedBlockId){const t=this.editor.findBlockById(this.highlightedBlockId);t&&et(t,"highlighted"),this.highlightedBlockId=""}}destroy(){}static register(t){return t.addCustom("editor-block-highlighter",()=>new Du(t))}static get(t){return t.getCustom("editor-block-highlighter")}}class Y7{constructor(t){m(this,"buttonElement");m(this,"emptyBlockMenu");m(this,"blockMenu");m(this,"dragHandler");m(this,"handleHoverBlock",(t,e,o)=>{if(this.emptyBlockMenu.isVisible||this.blockMenu.isVisible||!this.editor.isWritable())return;const r=this.editor.getCustom("editor-tooltip");if(r&&r.visible()&&(r.hide(),this.buttonElement.setAttribute("data-tooltip-hide-at",`${Date.now()}`)),!t){this.buttonElement.parentElement&&(this.blockMenu.isInMenu(o.target)||this.buttonElement.remove());return}const i=Vm(t);this.editor.getBlockIndex(i)===0&&this.editor.getBlockData(i).heading===1||(this.updateButton(i),Q0(i,this.buttonElement,Number.MAX_SAFE_INTEGER))});m(this,"handleButtonClick",()=>{if(this.buttonElement.getAttribute("data-type")==="move"){const o=this.blockMenu.currentBlock;if(!o)return;this.editor.selection.selectBlock(o,0),this.blockMenu.show(this.buttonElement,{placement:"bottom-end"}),setTimeout(()=>{Du.get(this.editor).highlightBlock(o)});return}const e=this.emptyBlockMenu.currentBlock;!e||(this.editor.selection.selectBlock(e,0),setTimeout(()=>{this.editor.focus(),this.updatePlaceholder(e),this.emptyBlockMenu.show()}))});m(this,"updatePlaceholder",t=>{Rt(t).setAttribute("data-content-placeholder",R.t("blockMenu.button.searchPlaceholder"))});m(this,"handleChanged",()=>{const t=this.emptyBlockMenu.currentBlock;if(!t)return;const e=he(this.editor,t)?"insert":"move";this.buttonElement.getAttribute("data-type")!==e&&this.setButtonType(e)});this.editor=t,this.buttonElement=this.createButton(),this.emptyBlockMenu=new c$(t),this.blockMenu=new D$(t),this.editor.addListener("docChanged",this.handleChanged),this.buttonElement.addEventListener("click",this.handleButtonClick),this.dragHandler=new _$(this.editor,this);const e=pe.get(t);e.addListener("change",this.handleHoverBlock),e.addFinder(new l$),Du.register(this.editor)}destroy(){pe.get(this.editor).removeListener("change",this.handleHoverBlock),this.buttonElement.removeEventListener("click",this.handleButtonClick),this.editor.removeListener("docChanged",this.handleChanged),this.emptyBlockMenu.destroy(),this.blockMenu.destroy(),this.buttonElement.remove(),this.dragHandler.destroy()}createButton(){const t=w("button",["block-button"],null);return t.setAttribute(`data-editor-tooltip-${this.editor.clientId}`,R.t("blockMenu.button.tips")),t.innerHTML=bv,t}setButtonType(t){this.buttonElement.setAttribute("data-type",t);const e=`data-editor-tooltip-${this.editor.clientId}-dynamic`;this.buttonElement.hasAttribute(e)&&this.buttonElement.removeAttribute(e),t==="insert"?(this.buttonElement.innerHTML=XL,this.buttonElement.setAttribute(e,R.t("blockMenu.button.insertTips"))):(this.buttonElement.innerHTML=bv,this.buttonElement.setAttribute(e,R.t("blockMenu.button.tips")))}updateButton(t){this.emptyBlockMenu.setBlock(t),this.blockMenu.setBlock(t),he(this.editor,t)?this.setButtonType("insert"):this.setButtonType("move")}}const F$={blockMenu:{section:{basics:"\u57FA\u7840",system:"\u7CFB\u7EDF",styles:"\u6837\u5F0F",common:"\u901A\u7528",actions:"\u64CD\u4F5C",thirdParty:"\u7B2C\u4E09\u65B9\u5185\u5BB9"},command:{insertAbove:"\u5728\u4E0A\u65B9\u63D2\u5165",insertAfter:"\u5728\u4E0B\u65B9\u63D2\u5165",copy:"\u590D\u5236",cut:"\u526A\u5207",delete:"\u5220\u9664"},button:{searchPlaceholder:"\u8F93\u5165\u5173\u952E\u8BCD\u641C\u7D22",tips:`\u957F\u6309\u62D6\u62FD
419
419
  \u70B9\u51FB\u6253\u5F00\u83DC\u5355`,insertTips:"\u70B9\u51FB\u6DFB\u52A0\u533A\u5757"}}},P$={blockMenu:{section:{basics:"Basic",system:"System",styles:"Styles",common:"Common",actions:"Actions",thirdParty:"Third-party content"},command:{insertAbove:"Insert above",insertAfter:"Insert below",copy:"Copy",cut:"Cut",delete:"Delete"},button:{searchPlaceholder:"Search",tips:`Hold to drag
420
- Click to open the menu`,insertTips:"Click to add block"}}},N$={blockMenu:{section:{basics:"\u4E00\u822C",system:"\u30B7\u30B9\u30C6\u30E0",styles:"\u30B9\u30BF\u30A4\u30EB",common:"\u4E00\u822C",actions:"\u64CD\u4F5C",thirdParty:"\u5916\u90E8\u30B3\u30F3\u30C6\u30F3\u30C4"},command:{insertAbove:"\u4E0A\u306B\u633F\u5165",insertAfter:"\u4E0B\u306B\u633F\u5165",copy:"\u30B3\u30D4\u30FC",cut:"\u5207\u308B",delete:"\u524A\u9664"},button:{searchPlaceholder:"\u30AD\u30FC\u30EF\u30FC\u30C9\u3067\u691C\u7D22",tips:"\u3092\u30C9\u30E9\u30C3\u30B0\u3057\u3066\u30AF\u30EA\u30C3\u30AF\u3067\u30E1\u30CB\u30E5\u30FC\u3092\u8868\u793A",insertTips:"\u30AF\u30EA\u30C3\u30AF\u3057\u3066\u30D6\u30ED\u30C3\u30AF\u3092\u8FFD\u52A0"}}};R.mergeLang({"zh-CN":F$,"en-US":P$,"ja-JP":N$});const Fnt="";class $${constructor(){m(this,"dragObject",null)}setData(t){this.dragObject=t}getData(){return this.dragObject}clearData(){this.dragObject=null}destroy(){}}function Pf(n){return n.addCustom("drag-data",()=>new $$)}function o2(n,t){if(!t)return null;const e=Pf(n).getData();return!e||e.editorId!==n.id?null:e}function J7(n,t){const e=o2(n,t);return e?n.findBlockById(e.blockId):null}function H$(n,t,e){if(!t.dataTransfer)return;const r=nt(e),i=at(r),s=it(e),l={type:"block",editorId:n.id,containerId:i,blockId:s};Pf(n).setData(l)}function j$(n,t,e,o,r){if(!t.dataTransfer)return;const s=nt(e),l=at(s),a=it(e),d={type:"custom",customType:o,editorId:n.id,containerId:l,blockId:a,data:r};Pf(n).setData(d)}function U$(n){Pf(n).clearData()}const z$=S("drop-indicator"),Nf=2;class V${constructor(t){m(this,"indicator");m(this,"target",null);this.editor=t,this.indicator=w("div",["editor-drop-indicator"],this.editor.contentElement)}show(t,e){const o=this.getIndicatorRect(t,e),r=this.editor.rootElement.getBoundingClientRect(),i=o.top-r.top,s=o.left-r.left;this.indicator.style.top=`${i}px`,this.indicator.style.left=`${s}px`,this.indicator.style.width=`${o.width}px`,this.indicator.style.height=`${o.height}px`,this.indicator.style.display="",this.target={block:t,insertPos:e}}hide(){this.indicator.style.display="none",this.target=null}getIndicatorRect(t,e){if(typeof e!="string")return e.rect;if(e==="before"){const s=Ds(t);if(!s){g(z$,Do(nt(t)),"block does not in a child container");const d=t.getBoundingClientRect();return new DOMRect(d.x,d.y,d.width,Nf)}const l=s.getBoundingClientRect(),a=t.getBoundingClientRect();return new DOMRect(l.x,(l.bottom+a.top)/2,l.width,Nf)}const o=Ss(t);if(!o){const s=t.getBoundingClientRect();return new DOMRect(s.x,s.bottom,s.width,Nf)}const r=t.getBoundingClientRect(),i=o.getBoundingClientRect();return new DOMRect(r.x,(r.bottom+i.top)/2,r.width,Nf)}}const W$=S("find-drop-target");function q$(n,t){const e=document.elementFromPoint(n,t);if(!e)return null;if(_r(e)&&Do(e))return e;const o=e.firstElementChild;return o&&_r(o)&&Do(o)?o:null}function G$(n,t){const s=t,l=n;for(let a=0;a<2;a++){const d=l+a*50;for(let h=0;h<5;h++){const p=s+h*8,A=document.elementFromPoint(d,p);if(A){const D=ot(A);if(D)return D}if(h===0)continue;const v=s-h*8,B=document.elementFromPoint(d,v);if(B){const D=ot(B);if(D)return D}}}return null}function Z$(n,t,e){const o=document.elementFromPoint(t,e);if(o){const h=ot(o);if(h&&!Lt(n,h))return h}const r=new Set,i=q$(t,e);if(i){const h=i.getBoundingClientRect();e<h.top+h.height/2?r.add(Se(i)):r.add(Ge(i))}const s=G$(t,e);s&&r.add(s);const l=Array.from(r),a=h=>{for(let p=0;p<l.length;p++){const A=l[p];if(h!==A&&Kt(h,A))return!0}return!1},d=l.filter(h=>!a(h));return d.length>0?d[0]:null}function r2(n,t){if(n.readonly)return!1;const e=nt(t);if(Xt(e))return!0;const o=ot(e);return g(W$,o,"no parent block"),n.isBlockWritable(o)?r2(n,o):!1}const Q$=S("drop-target");function Y$(n,t){let e={};return/image/.test(t.type)?e=n.editorEmbeds.getEmbedClass("image"):/audio/.test(t.type)?e=n.editorEmbeds.getEmbedClass("audio"):/video/.test(t.type)&&(e=n.editorEmbeds.getEmbedClass("video")),g(Q$,e,`unSupport file type ${t.type}`),e}async function K7(n,t,e,o){var i,s;let r=o;for(const l of t){const a=Y$(n,l);a.getOptions&&await((s=(i=a.getOptions(n)).handleInsertEmptyEmbed)==null?void 0:s.call(i,n,{containerId:e,blockIndex:r,data:{file:l}}))&&(r+=1)}}class J${constructor(t){m(this,"handleDrop",(t,e,o,r)=>{if(Array.isArray(e)){const i=e;if(i.length>0){const s=at(o);return K7(t,i,s,r),!0}}return!1});this.editor=t}}class Su{constructor(t){m(this,"indicator");m(this,"lastDropOverResult");m(this,"handlers",[]);m(this,"handleDragOver",t=>{if(!this.editor.isWritable())return;const e=i=>{var d,h;const s=o2(this.editor,i.dataTransfer),l=J7(this.editor,i.dataTransfer),a=this.findTargetBlock(l,i.x,i.y);if(a&&Kt(this.editor.rootContainer,a)){const p=this.findInsertPos(l,a,i.x,i.y,(h=s!=null?s:(d=i.dataTransfer)==null?void 0:d.items)!=null?h:null);if(p)return this.indicator.show(a,p),"move"}return this.indicator.hide(),"none"},o=(i,s)=>{i.dataTransfer&&(i.dataTransfer.dropEffect=s),s==="move"&&i.preventDefault()};if(this.lastDropOverResult&&t.x===this.lastDropOverResult.x&&t.y===this.lastDropOverResult.y){const i=this.lastDropOverResult.dropEffect;o(t,i);return}const r=e(t);o(t,r),this.lastDropOverResult={x:t.x,y:t.y,dropEffect:r}});m(this,"handleDrop",t=>{var i,s;t.stopPropagation(),setTimeout(()=>{this.indicator.hide()});const e=o2(this.editor,t.dataTransfer),o=Array.from((s=(i=t.dataTransfer)==null?void 0:i.files)!=null?s:[]);if(!e&&o.length===0){t.dataTransfer&&(t.dataTransfer.dropEffect="none");return}const r=this.indicator.target;if(r){const{block:l,insertPos:a}=r,d=J7(this.editor,t.dataTransfer);this.editor.undoManager.runInGroup(()=>{const h=Qt(this.editor,l);if(h.handleDrop&&h.handleDrop(this.editor,l,e!=null?e:o,a,{isSourceBlock:!1,targetBlock:l})){t.preventDefault(),this.editor.focus();return}if(d){const p=Qt(this.editor,d);if(p.handleDrop&&p.handleDrop(this.editor,d,e!=null?e:o,a,{isSourceBlock:!0,targetBlock:l})){t.preventDefault(),this.editor.focus();return}}if(typeof a=="string"){const p=nt(l);let A=bt(l);a==="after"&&(A+=1),t.preventDefault();for(let v=0;v<this.handlers.length;v++)if(this.handlers[v].handleDrop(this.editor,d!=null?d:o,p,A)){this.editor.focus();return}if(d){const v=this.editor.getBlockData(d),B=Fi(this.editor.editorBlocks,this.editor.doc.toJSON(),v),[D]=this.editor.insertDocAt(p,A,B);this.editor.selection.selectBlock(D,0),Du.get(this.editor).highlightBlock(D),this.editor.deleteBlock(d),this.editor.focus()}}}),U$(this.editor)}});m(this,"handleDragLeave",()=>{this.indicator.hide()});this.editor=t,this.indicator=new V$(this.editor),this.handlers.push(new J$(this.editor)),this.editor.contentElement.addEventListener("dragover",this.handleDragOver),this.editor.contentElement.addEventListener("dragleave",this.handleDragLeave),this.editor.contentElement.addEventListener("drop",this.handleDrop)}destroy(){this.editor.contentElement.removeEventListener("dragover",this.handleDragOver),this.editor.contentElement.removeEventListener("dragleave",this.handleDragLeave),this.editor.contentElement.removeEventListener("drop",this.handleDrop),this.handlers=[]}addHandler(t){this.handlers.push(t)}static register(t){return t.addCustom("drop-target",()=>new Su(t))}static get(t){return t.getCustom("drop-target")}static find(t){return t.findCustom("drop-target")}canInsertAfter(t,e){return!(this.editor.readonly||Ss(e)===t&&t||!r2(this.editor,e))}canInsertBefore(t,e){return!(this.editor.readonly||Ds(e)===t&&t||!r2(this.editor,e)||Xt(nt(e))&&bt(e)===0)}canDrop(t,e){return t===null||t===e?!0:!Kt(t,e)}findTargetBlock(t,e,o){let r=Z$(this.editor,e,o);if(!r||!Kt(this.editor.rootContainer,r))return null;const i=nt(r),s=ot(i);return s&&Dt(s)==="code"&&(r=s),this.canDrop(t,r)?r:null}findInsertPos(t,e,o,r,i){let s=e;for(;s;){const a=Qt(this.editor,s);if(a.handleDropOver){const d=a.handleDropOver(this.editor,s,i,o,r);if(d)return d;if(d===!1)return null}s=Is(s)}if(t===e)return"";const l=e.getBoundingClientRect();if(l.top<=r&&r<=l.bottom){if(r<l.top+l.height/2){if(this.canInsertBefore(t,e))return"before";if(this.canInsertAfter(t,e))return"after"}else{if(this.canInsertAfter(t,e))return"after";if(this.canInsertBefore(t,e))return"before"}return""}return r<l.top&&this.canInsertBefore(t,e)?"before":l.bottom<r&&this.canInsertAfter(t,e)?"after":""}}function X7(n,t,e){const o=xe.getImageObject(n,t),r=mt.default(o.getImages());if(r.length===1){n.deleteBlock(t);return}if(e===-1||e>=r.length)return;const i=PN(r);if(r.splice(e,1),r.length===1){const l=r[0],a=100*(l.flex/i);l.flex=1;const d=cn([l],a);n.updateEmbedData(t,d);return}r[0].flex=NaN,ku(r);const s=cn(r,o.getWidthPercent());n.updateEmbedData(t,s)}function K$(n,t,e,o){if(t.length===0||o==="after"||o==="before")return!1;let r=o.data;const i=xe.getImageObject(n,e),s=mt.default(i.getImages()),l=[],a=[];t.forEach(p=>{$7(p.type)&&s.length+l.length<6?l.push(p):a.push(p)}),l.forEach(p=>{try{N7(n,p)}catch{return}const A={src:"",flex:1,width:0,height:0,virtualSize:!0};s.splice(r,0,A);const v=cn(s,i.getWidthPercent());n.updateEmbedData(e,v),i.replaceImage(r,p),r+=1});const d=n.getBlockIndex(e)+1,h=at(nt(e));return K7(n,a,h,d),!0}function X$(n,t,e,o,r){var s,l,a;if(Wd(e))return K$(n,e,t,o);if(e.type!=="custom"||e.customType!=="image"||!e.data)return;const i=e.data;if(r.isSourceBlock){const d=r.targetBlock,h=nt(d);let p=bt(d);o==="after"&&(p+=1);const v=100*(i.boundingRect.width/n.rootContainer.getBoundingClientRect().width),B=cn([i.image],v),D={id:K(),type:"embed",embedType:"image",embedData:B},T=(l=(s=n.options.componentsOptions)==null?void 0:s.image)==null?void 0:l.defaultAlign;T&&(D.align=T),n.insertBlock(at(h),p,D),X7(n,t,i.index),(a=n.findCustom("drag-handler"))==null||a.handleDragEnd()}else{if(typeof o=="string")return;const d=t;let h=o.data;const p=xe.getImageObject(n,d),A=mt.default(p.getImages());h>A.length&&(h=A.length),n.undoManager.runInGroup(()=>{var B,D;p.setAutoFix(!0);const v=n.getBlockById(e.blockId);if(v===d){const T=i.index,_=h,M=i.image;if(T===_||_===T+1)return;let H=_;T<_?(A.splice(_,0,M),A.splice(T,1),H-=1):(A.splice(T,1),A.splice(_,0,M));const z=cn(A,p.getWidthPercent());n.updateEmbedData(d,z),p.setSelectedIndex(H),(B=n.findCustom("drag-handler"))==null||B.handleDragEnd()}else{A.splice(h,0,i.image),A[0].flex=NaN,ku(A);const T=cn(A,p.getWidthPercent());n.updateEmbedData(d,T),X7(n,v,i.index),(D=n.findCustom("drag-handler"))==null||D.handleDragEnd(),p.setSelectedIndex(h),n.selection.selectBlock(d,0)}})}return!0}const tH=2;function $f(n,t,e){const o=Qr(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,tH,r.height)}function eH(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:$f(n,t,i),data:i}:{rect:$f(n,t,i+1),data:i+1}}return o>e[e.length-1].getBoundingClientRect().right?{rect:$f(n,t,e.length),data:e.length}:{rect:$f(n,t,e.length),data:0}}function nH(n,t,e,o,r){const i=Qr(t);if(e instanceof DataTransferItemList){if(!Array.from(e).some(s=>$7(s.type))||i.length>=6)return}else{if((e==null?void 0:e.type)==="block"||i.length>=6&&(e==null?void 0:e.blockId)!==it(t))return;const s=it(t);if(i.length===1&&s===(e==null?void 0:e.blockId))return}return eH(n,t,i,o)}async function oH(n){return await Q5.default.toSvg(n)}function i2(n,t){return new DragEvent(t,{bubbles:!0,cancelable:!0,view:window,screenX:n.screenX,screenY:n.screenY,dataTransfer:new DataTransfer,clientX:n.clientX,clientY:n.clientY})}class rH{constructor(t){m(this,"img");m(this,"dragContainer",null);m(this,"autoScroll",null);m(this,"imageContainer",null);m(this,"startPosition",null);m(this,"handleMouseDown",t=>{const e=t.target;if(!e||!(e instanceof HTMLImageElement))return;const o=ot(e);if(!o||!zo(o)||!this.editor.isBlockWritable(o)||this.editor.readonly)return;const r=xe.getImageObject(this.editor,o);if(this.imageContainer=G0(t.target),!this.imageContainer)return;const s=M7(t.target).indexOf(this.imageContainer);if(s===-1)return;const l=r.getImages()[s];if(!l)return;const{x:a,y:d}=t;this.startPosition={x:a,y:d};const h={image:l,index:s,boundingRect:this.imageContainer.getBoundingClientRect()},p=i2(t,"dragstart");j$(this.editor,p,o,"image",h),document.addEventListener("mouseup",this.handleDragEnd),this.editor.contentElement.addEventListener("mousemove",this.handleDrag),t.preventDefault()});m(this,"handleDragStart",async t=>{if(!this.imageContainer)return;const e=ot(this.imageContainer);if(!e)return;const{x:o,y:r}=t,{width:i,height:s}=t.target.getBoundingClientRect(),l=le(e),a=w("div",["drag-container"],l);a.style.left=`${o-i/4}px`,a.style.top=`${r-s/4}px`,a.style.width=`${Math.max(i/2,16)}px`,a.style.height=`${s/2}px`,this.dragContainer=a;const d=w("img",["drag-target"],a),p=await oH(this.imageContainer);p&&(d.src=p),W(this.editor.contentElement,"dragging");const A=oo(e);this.autoScroll=new Gd({scrollElement:A,trackMouseEvent:"mousemove",edge:{top:50,bottom:50}}),this.autoScroll.active()});m(this,"handleDrag",t=>{var i;const{x:e,y:o}=t;if(((i=this.startPosition)==null?void 0:i.x)===e&&this.startPosition.y===o)return;if(window.isDragging||(window.isDragging=!0,this.handleDragStart(t)),this.startPosition&&this.dragContainer){const{x:s,y:l}=t;if(s===0&&l===0){this.dragContainer.style.transform="",this.dragContainer.style.opacity="0";return}const{x:a,y:d}=this.startPosition,h=s-a,p=l-d;this.dragContainer.style.transform=`translate(${h}px, ${p}px)`,this.dragContainer.style.opacity="0.5"}const r=i2(t,"dragover");this.editor.contentElement.dispatchEvent(r)});m(this,"handleDragEnd",t=>{var e;if(window.isDragging=!1,this.dragContainer&&this.dragContainer.remove(),this.dragContainer=null,this.startPosition=null,this.imageContainer=null,(e=this.autoScroll)==null||e.inactive(),et(this.editor.contentElement,"dragging"),document.removeEventListener("mouseup",this.handleDragEnd),this.editor.contentElement.removeEventListener("mousemove",this.handleDrag),t){const o=i2(t,"drop");this.editor.contentElement.dispatchEvent(o)}});this.editor=t,this.editor.rootContainer.addEventListener("mousedown",this.handleMouseDown),this.img=new Image,this.img.src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"}destroy(){this.editor.rootContainer.removeEventListener("mousedown",this.handleMouseDown)}}class iH{constructor(t){m(this,"handleFocusBlockChanged",(t,e,o)=>{const i=this.editor.getFocusedBlock();if(i&&zo(i)){const s=xe.getImageObject(this.editor,i);s.getImages().length>0&&s.getSelectedIndex()===-1&&s.setSelectedIndex(0)}o&&zo(o)&&xe.getImageObject(this.editor,o).blockResizer.disableResize()});this.editor=t,this.editor.addListener("focusBlockChanged",this.handleFocusBlockChanged)}destroy(){this.editor.removeListener("focusBlockChanged",this.handleFocusBlockChanged)}}class sH{constructor(t){m(this,"currentResizer",null);m(this,"handleHoveringBlockChange",(t,e)=>{e&&this.disable(e),t&&(this.currentResizer=t,this.enable(t))});this.editor=t,pe.get(t).addListener("change",this.handleHoveringBlockChange)}destroy(){pe.get(this.editor).removeListener("change",this.handleHoveringBlockChange)}disable(t){zo(t)&&xe.getImageObject(this.editor,t).disableResizer()}enable(t){if(zo(t)){const e=xe.getImageObject(this.editor,t);this.editor.isBlockWritable(t)&&e.tryEnableResizer()}}}const lH={image:{title:"\u56FE\u7247",upload:{failed:'<div class="line-1">\u56FE\u7247\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">\u56FE\u7247\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>',remote:{failed:'<div class="line-1">\u56FE\u7247\u52A0\u8F7D\u5931\u8D25</div><div class="line-2">\u8BE5\u56FE\u7247\u6765\u81EA\u5916\u90E8\u94FE\u63A5\uFF0C\u5916\u90E8\u94FE\u63A5\u5DF2\u5931\u6548</div><div class="line-3">\u8BF7\u5C06\u539F\u56FE\u4FDD\u5B58\u5230\u672C\u5730\u540E\u4E0A\u4F20\uFF0C <a href="" class="retry-upload">\u6253\u5F00\u56FE\u7247\u94FE\u63A5</a></div>',tooltip:"\u8BE5\u56FE\u7247\u6765\u81EA\u5916\u90E8\u94FE\u63A5\uFF0C\u5982\u679C\u94FE\u63A5\u5931\u6548\u56FE\u7247\u5C06\u65E0\u6CD5\u67E5\u770B\uFF0C\u5EFA\u8BAE\u4FDD\u5B58\u5230\u672C\u5730\u540E\u6DFB\u52A0\u5230\u9875\u9762\u4E2D"}},abstract:"\u56FE\u7247"}},cH={image:{title:"Image",upload:{failed:'<div class="line-1">Image upload failed</div><div class="line-2">Network error, you can <a href="" class="retry-upload">Retry</a></div>'},load:{failed:'<div class="line-1">Image failed to load</div><div class="line-2">Network error, you can <a href="" class="retry-upload">Retry</a></div>',remote:{failed:'<div class="line-1">Failed to load image</div><div class="line-2">This picture is from an expired external link</div><div class="line-3">Please save the original image to local drives and upload it. <a href="" class="retry-upload">Open image link</a></div>',tooltip:"This picture is from an external link. If the link expires, the picture will not be available. It's recommended to save it to local drives and add it to the page."}},abstract:"Image"}},aH={image:{title:"\u753B\u50CF",upload:{failed:'<div class="line-1">\u753B\u50CF\u3092\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F</div><div class="line-2">\u304A\u4F7F\u3044\u306E\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u63A5\u7D9A\u306B\u554F\u984C\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002\u6B21\u306E\u64CD\u4F5C\u3092\u884C\u3063\u3066\u304F\u3060\u3055\u3044\u3002 <a href="" class="retry-upload">\u518D\u8A66\u884C</a></div>'},load:{failed:'<div class="line-1">\u753B\u50CF\u3092\u8AAD\u307F\u8FBC\u3081\u307E\u305B\u3093\u3067\u3057\u305F</div><div class="line-2">\u304A\u4F7F\u3044\u306E\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u63A5\u7D9A\u306B\u554F\u984C\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002\u6B21\u306E\u64CD\u4F5C\u3092\u884C\u3063\u3066\u304F\u3060\u3055\u3044\u3002 <a href="" class="retry-upload">\u518D\u8A66\u884C</a></div>',remote:{failed:'<div class="line-1">\u753B\u50CF\u3092\u8AAD\u307F\u8FBC\u3081\u307E\u305B\u3093\u3067\u3057\u305F</div><div class="line-2">\u3053\u306E\u753B\u50CF\u306B\u30EA\u30F3\u30AF\u3057\u3066\u3044\u308B URL \u304C\u7121\u52B9\u306B\u306A\u3063\u3066\u3044\u307E\u3059\u306E\u3067\u3001\u8868\u793A\u3067\u304D\u307E\u305B\u3093</div><div class="line-3">\u753B\u50CF\u3092\u30ED\u30FC\u30AB\u30EB\u306B\u4FDD\u5B58\u3057\u3066\u30A2\u30C3\u30D7\u30ED\u30FC\u30C0\u3057\u3066\u304F\u3060\u3055\u3044 <a href="" class="retry-upload">\u753B\u50CF\u30EA\u30F3\u30AF\u3092\u958B\u304F</a></div>',tooltip:"\u3053\u306E\u753B\u50CF\u306F\u5916\u90E8\u306B\u30EA\u30F3\u30AF\u3057\u3066\u3044\u308B\u305F\u3081\u3001\u30EA\u30F3\u30AF\u304C\u7121\u52B9\u306B\u306A\u308B\u3068\u3001\u8868\u793A\u3067\u304D\u306A\u304F\u306A\u308A\u307E\u3059\u306E\u3067\u3001\u30ED\u30FC\u30AB\u30EB\u306B\u4FDD\u5B58\u3057\u3001\u30DA\u30FC\u30B8\u306B\u633F\u5165\u3059\u308B\u3053\u3068\u3092\u304A\u52E7\u3081\u3057\u307E\u3059"}},abstract:"\u753B\u50CF"}};R.mergeLang({"zh-CN":lH,"en-US":cH,"ja-JP":aH});function uH(n,t,e,o){const r=n.getBlockByIndex(t,e),i=n.getBlockText(r),{left:s}=xn(i,o),l=re(s);let a=o;if(l.endsWith("![]()"))a-=5;else if(l.endsWith("![]"))a-=3;else return!1;const d=o;return zl("image/*").then(h=>{n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,a,d-a);let p=e+1;re(n.getBlockText(r)).trim()?(Yl(n,r,a,{forceInsertAfter:!0}),a===0&&(n.deleteBlock(r),p--)):(n.deleteBlock(r),p--),qm(n,"image",t,p,{file:h})})}),!0}class dH{handleAfterInsertText(t,e,o,r,i){return!!(i===" "&&uH(t,e,o,r))}}function hH(n){const t=n.getFocusedBlock(),e=Ss(t);if(e&&zo(e)){n.selection.selectBlock(e,0);const o=xe.getImageObject(n,e);return o.getImages().length>0&&o.setSelectedIndex(0),!0}}function fH(n){const t=n.getFocusedBlock(),e=Ds(t);if(e&&zo(e)){n.selection.selectBlock(e,0);const o=xe.getImageObject(n,e);return o.getImages().length>0&&o.setSelectedIndex(0),!0}}function mH(n){const e=n.getFocusedBlock();if(e&&zo(e)){const o=xe.getImageObject(n,e),r=o.getImages();if(r.length>0){const i=o.getSelectedIndex();if(i===-1)return o.setSelectedIndex(r.length-1),!0;if(i>0)return o.setSelectedIndex(i-1),!0}}}function gH(n){const e=n.getFocusedBlock();if(e&&zo(e)){const o=xe.getImageObject(n,e),r=o.getImages();if(r.length>0){const i=o.getSelectedIndex();if(i===-1)return o.setSelectedIndex(0),!0;if(i<r.length-1)return o.setSelectedIndex(i+1),!0}}}function s2(n){const e=n.getFocusedBlock();if(e&&zo(e)){const o=xe.getImageObject(n,e);if(o.getImages().length>0){const i=o.getSelectedIndex();if(i!==-1)return o.removeImage(i),!0}}}const pH={ArrowLeft:mH,ArrowRight:gH,ArrowUp:fH,ArrowDown:hH,Delete:s2,Backspace:s2},CH=S("copy-image");function AH(n,t,e,o){const r=e.getImages()[o],i=e.getImages().length===1?e.getWidthPercent():r.flex*100,s=cn([r],i),l={id:K(),type:"embed",embedType:"image",embedData:s},a=n.options.componentsOptions.image;a!=null&&a.defaultAlign&&(l.align=a.defaultAlign);const d={blocks:{root:[l]},comments:{},meta:{}},h=document.createElement("canvas");h.width=t.naturalWidth,h.height=t.naturalHeight;const p=h.getContext("2d");if(!p)return;const A={},v={};try{p.drawImage(t,0,0,h.width,h.height);const z=h.toDataURL("image/png").replace(/^data:image\/(png|jpg);base64,/,""),q=Dm(z),rt=new File([q],`${Date.now()}.png`,{type:"image/png"});A["image/png"]=rt}catch(H){CH.error(H)}Mh(n,d);const D=`<img src="${n.doc.buildResourceUrl(r.src,{withToken:!0})}" />`,T=Lh(D,d),_=Ma(n,d);A["text/plain"]=new Blob([_],{type:"text/plain"}),v["text/plain"]=_;const M=new Blob([T],{type:"text/html"});return A["text/html"]=M,v["text/html"]=T,[A,v]}function bH(n,t,e,o,r){const i=AH(n,t,e,o);if(!i)return;const[s,l]=i;if(s){const a=Object.entries(s).map(([d,h])=>({type:d,data:h}));return Mm(a).then(d=>{if(!d&&r){const h=r.clipboardData;h&&(h.setData("text/plain",l["text/plain"]),h.setData("text/html",l["text/html"]))}}),!0}}function t8(n,t){const e=n.selection.range;if(e.start.blockId!==e.end.blockId)return;const r=n.getFocusedBlock();if(r&&zo(r)){const i=xe.getImageObject(n,r);if(i.getImages().length>0){const l=i.getSelectedIndex();if(l!==-1){const d=Qr(r)[l].querySelector("img");if(d)return bH(n,d,i,l,t)}}}}class vH{constructor(t){this.editor=t,setTimeout(()=>{this.editor.input.addHandler(this)})}handleBeforeCopy(t,e,o){if(t8(t,e))return!0}handleBeforeCut(t,e){if(t8(t,e))return s2(t),!0}destroy(){}}class l2{constructor(t){this.editor=t,setTimeout(()=>{this.editor.input.addHandler(this)})}async handleAfterPasteDoc(t,e,o){return Object.values(e.blocks).forEach(r=>{r.forEach(i=>{if(i.type==="embed"&&i.embedType==="image"){const s=i.embedData;if(Array.isArray(s.src))return;if(s.src.startsWith("https:")||s.src.startsWith("http:")){const l=o.blockIdMap.get(i.id);l&&Ki(t,l).setAutoFix(!0)}}})}),!1}destroy(){}}const yH=S("image-embed");function kH(n,t,e,o,r,i){xe.create(n,e).createContent(r,i,t),n.addCustom("image-select-handler",()=>new iH(n)),n.addCustom("image-copy-handler",()=>new vH(n)),setTimeout(()=>{n.addCustom("drag-handler",()=>new rH(n));const l=n.addCustom("image-resizer",()=>new sH(n)),a=e.embedData;kc(a)?l.disable(i):l.currentResizer===i&&l.enable(i)})}function wH(n,t,e,o){const r=t.embedData,i=wc(r);return o==="html"?i.map(s=>`<img src="${n.doc.buildResourceUrl(s.src,{withToken:!0})}">`).join(""):o==="markdown"?`${i.map(l=>`![img](${n.doc.buildResourceUrl(l.src,{withToken:!0})})`).join(`
420
+ Click to open the menu`,insertTips:"Click to add block"}}},N$={blockMenu:{section:{basics:"\u4E00\u822C",system:"\u30B7\u30B9\u30C6\u30E0",styles:"\u30B9\u30BF\u30A4\u30EB",common:"\u4E00\u822C",actions:"\u64CD\u4F5C",thirdParty:"\u5916\u90E8\u30B3\u30F3\u30C6\u30F3\u30C4"},command:{insertAbove:"\u4E0A\u306B\u633F\u5165",insertAfter:"\u4E0B\u306B\u633F\u5165",copy:"\u8907\u88FD",cut:"\u5207\u308B",delete:"\u524A\u9664"},button:{searchPlaceholder:"\u30AD\u30FC\u30EF\u30FC\u30C9\u3067\u691C\u7D22",tips:"\u3092\u30C9\u30E9\u30C3\u30B0\u3057\u3066\u30AF\u30EA\u30C3\u30AF\u3067\u30E1\u30CB\u30E5\u30FC\u3092\u8868\u793A",insertTips:"\u30AF\u30EA\u30C3\u30AF\u3057\u3066\u30D6\u30ED\u30C3\u30AF\u3092\u8FFD\u52A0"}}};R.mergeLang({"zh-CN":F$,"en-US":P$,"ja-JP":N$});const Fnt="";class $${constructor(){m(this,"dragObject",null)}setData(t){this.dragObject=t}getData(){return this.dragObject}clearData(){this.dragObject=null}destroy(){}}function Pf(n){return n.addCustom("drag-data",()=>new $$)}function o2(n,t){if(!t)return null;const e=Pf(n).getData();return!e||e.editorId!==n.id?null:e}function J7(n,t){const e=o2(n,t);return e?n.findBlockById(e.blockId):null}function H$(n,t,e){if(!t.dataTransfer)return;const r=nt(e),i=at(r),s=it(e),l={type:"block",editorId:n.id,containerId:i,blockId:s};Pf(n).setData(l)}function j$(n,t,e,o,r){if(!t.dataTransfer)return;const s=nt(e),l=at(s),a=it(e),d={type:"custom",customType:o,editorId:n.id,containerId:l,blockId:a,data:r};Pf(n).setData(d)}function U$(n){Pf(n).clearData()}const z$=S("drop-indicator"),Nf=2;class V${constructor(t){m(this,"indicator");m(this,"target",null);this.editor=t,this.indicator=w("div",["editor-drop-indicator"],this.editor.contentElement)}show(t,e){const o=this.getIndicatorRect(t,e),r=this.editor.rootElement.getBoundingClientRect(),i=o.top-r.top,s=o.left-r.left;this.indicator.style.top=`${i}px`,this.indicator.style.left=`${s}px`,this.indicator.style.width=`${o.width}px`,this.indicator.style.height=`${o.height}px`,this.indicator.style.display="",this.target={block:t,insertPos:e}}hide(){this.indicator.style.display="none",this.target=null}getIndicatorRect(t,e){if(typeof e!="string")return e.rect;if(e==="before"){const s=Ds(t);if(!s){g(z$,Do(nt(t)),"block does not in a child container");const d=t.getBoundingClientRect();return new DOMRect(d.x,d.y,d.width,Nf)}const l=s.getBoundingClientRect(),a=t.getBoundingClientRect();return new DOMRect(l.x,(l.bottom+a.top)/2,l.width,Nf)}const o=Ss(t);if(!o){const s=t.getBoundingClientRect();return new DOMRect(s.x,s.bottom,s.width,Nf)}const r=t.getBoundingClientRect(),i=o.getBoundingClientRect();return new DOMRect(r.x,(r.bottom+i.top)/2,r.width,Nf)}}const W$=S("find-drop-target");function q$(n,t){const e=document.elementFromPoint(n,t);if(!e)return null;if(_r(e)&&Do(e))return e;const o=e.firstElementChild;return o&&_r(o)&&Do(o)?o:null}function G$(n,t){const s=t,l=n;for(let a=0;a<2;a++){const d=l+a*50;for(let h=0;h<5;h++){const p=s+h*8,A=document.elementFromPoint(d,p);if(A){const D=ot(A);if(D)return D}if(h===0)continue;const v=s-h*8,B=document.elementFromPoint(d,v);if(B){const D=ot(B);if(D)return D}}}return null}function Z$(n,t,e){const o=document.elementFromPoint(t,e);if(o){const h=ot(o);if(h&&!Lt(n,h))return h}const r=new Set,i=q$(t,e);if(i){const h=i.getBoundingClientRect();e<h.top+h.height/2?r.add(Se(i)):r.add(Ge(i))}const s=G$(t,e);s&&r.add(s);const l=Array.from(r),a=h=>{for(let p=0;p<l.length;p++){const A=l[p];if(h!==A&&Kt(h,A))return!0}return!1},d=l.filter(h=>!a(h));return d.length>0?d[0]:null}function r2(n,t){if(n.readonly)return!1;const e=nt(t);if(Xt(e))return!0;const o=ot(e);return g(W$,o,"no parent block"),n.isBlockWritable(o)?r2(n,o):!1}const Q$=S("drop-target");function Y$(n,t){let e={};return/image/.test(t.type)?e=n.editorEmbeds.getEmbedClass("image"):/audio/.test(t.type)?e=n.editorEmbeds.getEmbedClass("audio"):/video/.test(t.type)&&(e=n.editorEmbeds.getEmbedClass("video")),g(Q$,e,`unSupport file type ${t.type}`),e}async function K7(n,t,e,o){var i,s;let r=o;for(const l of t){const a=Y$(n,l);a.getOptions&&await((s=(i=a.getOptions(n)).handleInsertEmptyEmbed)==null?void 0:s.call(i,n,{containerId:e,blockIndex:r,data:{file:l}}))&&(r+=1)}}class J${constructor(t){m(this,"handleDrop",(t,e,o,r)=>{if(Array.isArray(e)){const i=e;if(i.length>0){const s=at(o);return K7(t,i,s,r),!0}}return!1});this.editor=t}}class Su{constructor(t){m(this,"indicator");m(this,"lastDropOverResult");m(this,"handlers",[]);m(this,"handleDragOver",t=>{if(!this.editor.isWritable())return;const e=i=>{var d,h;const s=o2(this.editor,i.dataTransfer),l=J7(this.editor,i.dataTransfer),a=this.findTargetBlock(l,i.x,i.y);if(a&&Kt(this.editor.rootContainer,a)){const p=this.findInsertPos(l,a,i.x,i.y,(h=s!=null?s:(d=i.dataTransfer)==null?void 0:d.items)!=null?h:null);if(p)return this.indicator.show(a,p),"move"}return this.indicator.hide(),"none"},o=(i,s)=>{i.dataTransfer&&(i.dataTransfer.dropEffect=s),s==="move"&&i.preventDefault()};if(this.lastDropOverResult&&t.x===this.lastDropOverResult.x&&t.y===this.lastDropOverResult.y){const i=this.lastDropOverResult.dropEffect;o(t,i);return}const r=e(t);o(t,r),this.lastDropOverResult={x:t.x,y:t.y,dropEffect:r}});m(this,"handleDrop",t=>{var i,s;t.stopPropagation(),setTimeout(()=>{this.indicator.hide()});const e=o2(this.editor,t.dataTransfer),o=Array.from((s=(i=t.dataTransfer)==null?void 0:i.files)!=null?s:[]);if(!e&&o.length===0){t.dataTransfer&&(t.dataTransfer.dropEffect="none");return}const r=this.indicator.target;if(r){const{block:l,insertPos:a}=r,d=J7(this.editor,t.dataTransfer);this.editor.undoManager.runInGroup(()=>{const h=Qt(this.editor,l);if(h.handleDrop&&h.handleDrop(this.editor,l,e!=null?e:o,a,{isSourceBlock:!1,targetBlock:l})){t.preventDefault(),this.editor.focus();return}if(d){const p=Qt(this.editor,d);if(p.handleDrop&&p.handleDrop(this.editor,d,e!=null?e:o,a,{isSourceBlock:!0,targetBlock:l})){t.preventDefault(),this.editor.focus();return}}if(typeof a=="string"){const p=nt(l);let A=bt(l);a==="after"&&(A+=1),t.preventDefault();for(let v=0;v<this.handlers.length;v++)if(this.handlers[v].handleDrop(this.editor,d!=null?d:o,p,A)){this.editor.focus();return}if(d){const v=this.editor.getBlockData(d),B=Fi(this.editor.editorBlocks,this.editor.doc.toJSON(),v),[D]=this.editor.insertDocAt(p,A,B);this.editor.selection.selectBlock(D,0),Du.get(this.editor).highlightBlock(D),this.editor.deleteBlock(d),this.editor.focus()}}}),U$(this.editor)}});m(this,"handleDragLeave",()=>{this.indicator.hide()});this.editor=t,this.indicator=new V$(this.editor),this.handlers.push(new J$(this.editor)),this.editor.contentElement.addEventListener("dragover",this.handleDragOver),this.editor.contentElement.addEventListener("dragleave",this.handleDragLeave),this.editor.contentElement.addEventListener("drop",this.handleDrop)}destroy(){this.editor.contentElement.removeEventListener("dragover",this.handleDragOver),this.editor.contentElement.removeEventListener("dragleave",this.handleDragLeave),this.editor.contentElement.removeEventListener("drop",this.handleDrop),this.handlers=[]}addHandler(t){this.handlers.push(t)}static register(t){return t.addCustom("drop-target",()=>new Su(t))}static get(t){return t.getCustom("drop-target")}static find(t){return t.findCustom("drop-target")}canInsertAfter(t,e){return!(this.editor.readonly||Ss(e)===t&&t||!r2(this.editor,e))}canInsertBefore(t,e){return!(this.editor.readonly||Ds(e)===t&&t||!r2(this.editor,e)||Xt(nt(e))&&bt(e)===0)}canDrop(t,e){return t===null||t===e?!0:!Kt(t,e)}findTargetBlock(t,e,o){let r=Z$(this.editor,e,o);if(!r||!Kt(this.editor.rootContainer,r))return null;const i=nt(r),s=ot(i);return s&&Dt(s)==="code"&&(r=s),this.canDrop(t,r)?r:null}findInsertPos(t,e,o,r,i){let s=e;for(;s;){const a=Qt(this.editor,s);if(a.handleDropOver){const d=a.handleDropOver(this.editor,s,i,o,r);if(d)return d;if(d===!1)return null}s=Is(s)}if(t===e)return"";const l=e.getBoundingClientRect();if(l.top<=r&&r<=l.bottom){if(r<l.top+l.height/2){if(this.canInsertBefore(t,e))return"before";if(this.canInsertAfter(t,e))return"after"}else{if(this.canInsertAfter(t,e))return"after";if(this.canInsertBefore(t,e))return"before"}return""}return r<l.top&&this.canInsertBefore(t,e)?"before":l.bottom<r&&this.canInsertAfter(t,e)?"after":""}}function X7(n,t,e){const o=xe.getImageObject(n,t),r=mt.default(o.getImages());if(r.length===1){n.deleteBlock(t);return}if(e===-1||e>=r.length)return;const i=PN(r);if(r.splice(e,1),r.length===1){const l=r[0],a=100*(l.flex/i);l.flex=1;const d=cn([l],a);n.updateEmbedData(t,d);return}r[0].flex=NaN,ku(r);const s=cn(r,o.getWidthPercent());n.updateEmbedData(t,s)}function K$(n,t,e,o){if(t.length===0||o==="after"||o==="before")return!1;let r=o.data;const i=xe.getImageObject(n,e),s=mt.default(i.getImages()),l=[],a=[];t.forEach(p=>{$7(p.type)&&s.length+l.length<6?l.push(p):a.push(p)}),l.forEach(p=>{try{N7(n,p)}catch{return}const A={src:"",flex:1,width:0,height:0,virtualSize:!0};s.splice(r,0,A);const v=cn(s,i.getWidthPercent());n.updateEmbedData(e,v),i.replaceImage(r,p),r+=1});const d=n.getBlockIndex(e)+1,h=at(nt(e));return K7(n,a,h,d),!0}function X$(n,t,e,o,r){var s,l,a;if(Wd(e))return K$(n,e,t,o);if(e.type!=="custom"||e.customType!=="image"||!e.data)return;const i=e.data;if(r.isSourceBlock){const d=r.targetBlock,h=nt(d);let p=bt(d);o==="after"&&(p+=1);const v=100*(i.boundingRect.width/n.rootContainer.getBoundingClientRect().width),B=cn([i.image],v),D={id:K(),type:"embed",embedType:"image",embedData:B},T=(l=(s=n.options.componentsOptions)==null?void 0:s.image)==null?void 0:l.defaultAlign;T&&(D.align=T),n.insertBlock(at(h),p,D),X7(n,t,i.index),(a=n.findCustom("drag-handler"))==null||a.handleDragEnd()}else{if(typeof o=="string")return;const d=t;let h=o.data;const p=xe.getImageObject(n,d),A=mt.default(p.getImages());h>A.length&&(h=A.length),n.undoManager.runInGroup(()=>{var B,D;p.setAutoFix(!0);const v=n.getBlockById(e.blockId);if(v===d){const T=i.index,_=h,M=i.image;if(T===_||_===T+1)return;let H=_;T<_?(A.splice(_,0,M),A.splice(T,1),H-=1):(A.splice(T,1),A.splice(_,0,M));const z=cn(A,p.getWidthPercent());n.updateEmbedData(d,z),p.setSelectedIndex(H),(B=n.findCustom("drag-handler"))==null||B.handleDragEnd()}else{A.splice(h,0,i.image),A[0].flex=NaN,ku(A);const T=cn(A,p.getWidthPercent());n.updateEmbedData(d,T),X7(n,v,i.index),(D=n.findCustom("drag-handler"))==null||D.handleDragEnd(),p.setSelectedIndex(h),n.selection.selectBlock(d,0)}})}return!0}const tH=2;function $f(n,t,e){const o=Qr(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,tH,r.height)}function eH(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:$f(n,t,i),data:i}:{rect:$f(n,t,i+1),data:i+1}}return o>e[e.length-1].getBoundingClientRect().right?{rect:$f(n,t,e.length),data:e.length}:{rect:$f(n,t,e.length),data:0}}function nH(n,t,e,o,r){const i=Qr(t);if(e instanceof DataTransferItemList){if(!Array.from(e).some(s=>$7(s.type))||i.length>=6)return}else{if((e==null?void 0:e.type)==="block"||i.length>=6&&(e==null?void 0:e.blockId)!==it(t))return;const s=it(t);if(i.length===1&&s===(e==null?void 0:e.blockId))return}return eH(n,t,i,o)}async function oH(n){return await Q5.default.toSvg(n)}function i2(n,t){return new DragEvent(t,{bubbles:!0,cancelable:!0,view:window,screenX:n.screenX,screenY:n.screenY,dataTransfer:new DataTransfer,clientX:n.clientX,clientY:n.clientY})}class rH{constructor(t){m(this,"img");m(this,"dragContainer",null);m(this,"autoScroll",null);m(this,"imageContainer",null);m(this,"startPosition",null);m(this,"handleMouseDown",t=>{const e=t.target;if(!e||!(e instanceof HTMLImageElement))return;const o=ot(e);if(!o||!zo(o)||!this.editor.isBlockWritable(o)||this.editor.readonly)return;const r=xe.getImageObject(this.editor,o);if(this.imageContainer=G0(t.target),!this.imageContainer)return;const s=M7(t.target).indexOf(this.imageContainer);if(s===-1)return;const l=r.getImages()[s];if(!l)return;const{x:a,y:d}=t;this.startPosition={x:a,y:d};const h={image:l,index:s,boundingRect:this.imageContainer.getBoundingClientRect()},p=i2(t,"dragstart");j$(this.editor,p,o,"image",h),document.addEventListener("mouseup",this.handleDragEnd),this.editor.contentElement.addEventListener("mousemove",this.handleDrag),t.preventDefault()});m(this,"handleDragStart",async t=>{if(!this.imageContainer)return;const e=ot(this.imageContainer);if(!e)return;const{x:o,y:r}=t,{width:i,height:s}=t.target.getBoundingClientRect(),l=le(e),a=w("div",["drag-container"],l);a.style.left=`${o-i/4}px`,a.style.top=`${r-s/4}px`,a.style.width=`${Math.max(i/2,16)}px`,a.style.height=`${s/2}px`,this.dragContainer=a;const d=w("img",["drag-target"],a),p=await oH(this.imageContainer);p&&(d.src=p),W(this.editor.contentElement,"dragging");const A=oo(e);this.autoScroll=new Gd({scrollElement:A,trackMouseEvent:"mousemove",edge:{top:50,bottom:50}}),this.autoScroll.active()});m(this,"handleDrag",t=>{var i;const{x:e,y:o}=t;if(((i=this.startPosition)==null?void 0:i.x)===e&&this.startPosition.y===o)return;if(window.isDragging||(window.isDragging=!0,this.handleDragStart(t)),this.startPosition&&this.dragContainer){const{x:s,y:l}=t;if(s===0&&l===0){this.dragContainer.style.transform="",this.dragContainer.style.opacity="0";return}const{x:a,y:d}=this.startPosition,h=s-a,p=l-d;this.dragContainer.style.transform=`translate(${h}px, ${p}px)`,this.dragContainer.style.opacity="0.5"}const r=i2(t,"dragover");this.editor.contentElement.dispatchEvent(r)});m(this,"handleDragEnd",t=>{var e;if(window.isDragging=!1,this.dragContainer&&this.dragContainer.remove(),this.dragContainer=null,this.startPosition=null,this.imageContainer=null,(e=this.autoScroll)==null||e.inactive(),et(this.editor.contentElement,"dragging"),document.removeEventListener("mouseup",this.handleDragEnd),this.editor.contentElement.removeEventListener("mousemove",this.handleDrag),t){const o=i2(t,"drop");this.editor.contentElement.dispatchEvent(o)}});this.editor=t,this.editor.rootContainer.addEventListener("mousedown",this.handleMouseDown),this.img=new Image,this.img.src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"}destroy(){this.editor.rootContainer.removeEventListener("mousedown",this.handleMouseDown)}}class iH{constructor(t){m(this,"handleFocusBlockChanged",(t,e,o)=>{const i=this.editor.getFocusedBlock();if(i&&zo(i)){const s=xe.getImageObject(this.editor,i);s.getImages().length>0&&s.getSelectedIndex()===-1&&s.setSelectedIndex(0)}o&&zo(o)&&xe.getImageObject(this.editor,o).blockResizer.disableResize()});this.editor=t,this.editor.addListener("focusBlockChanged",this.handleFocusBlockChanged)}destroy(){this.editor.removeListener("focusBlockChanged",this.handleFocusBlockChanged)}}class sH{constructor(t){m(this,"currentResizer",null);m(this,"handleHoveringBlockChange",(t,e)=>{e&&this.disable(e),t&&(this.currentResizer=t,this.enable(t))});this.editor=t,pe.get(t).addListener("change",this.handleHoveringBlockChange)}destroy(){pe.get(this.editor).removeListener("change",this.handleHoveringBlockChange)}disable(t){zo(t)&&xe.getImageObject(this.editor,t).disableResizer()}enable(t){if(zo(t)){const e=xe.getImageObject(this.editor,t);this.editor.isBlockWritable(t)&&e.tryEnableResizer()}}}const lH={image:{title:"\u56FE\u7247",upload:{failed:'<div class="line-1">\u56FE\u7247\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">\u56FE\u7247\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>',remote:{failed:'<div class="line-1">\u56FE\u7247\u52A0\u8F7D\u5931\u8D25</div><div class="line-2">\u8BE5\u56FE\u7247\u6765\u81EA\u5916\u90E8\u94FE\u63A5\uFF0C\u5916\u90E8\u94FE\u63A5\u5DF2\u5931\u6548</div><div class="line-3">\u8BF7\u5C06\u539F\u56FE\u4FDD\u5B58\u5230\u672C\u5730\u540E\u4E0A\u4F20\uFF0C <a href="" class="retry-upload">\u6253\u5F00\u56FE\u7247\u94FE\u63A5</a></div>',tooltip:"\u8BE5\u56FE\u7247\u6765\u81EA\u5916\u90E8\u94FE\u63A5\uFF0C\u5982\u679C\u94FE\u63A5\u5931\u6548\u56FE\u7247\u5C06\u65E0\u6CD5\u67E5\u770B\uFF0C\u5EFA\u8BAE\u4FDD\u5B58\u5230\u672C\u5730\u540E\u6DFB\u52A0\u5230\u9875\u9762\u4E2D"}},abstract:"\u56FE\u7247"}},cH={image:{title:"Image",upload:{failed:'<div class="line-1">Image upload failed</div><div class="line-2">Network error, you can <a href="" class="retry-upload">Retry</a></div>'},load:{failed:'<div class="line-1">Image failed to load</div><div class="line-2">Network error, you can <a href="" class="retry-upload">Retry</a></div>',remote:{failed:'<div class="line-1">Failed to load image</div><div class="line-2">This picture is from an expired external link</div><div class="line-3">Please save the original image to local drives and upload it. <a href="" class="retry-upload">Open image link</a></div>',tooltip:"This picture is from an external link. If the link expires, the picture will not be available. It's recommended to save it to local drives and add it to the page."}},abstract:"Image"}},aH={image:{title:"\u753B\u50CF",upload:{failed:'<div class="line-1">\u753B\u50CF\u3092\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F</div><div class="line-2">\u304A\u4F7F\u3044\u306E\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u63A5\u7D9A\u306B\u554F\u984C\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002\u6B21\u306E\u64CD\u4F5C\u3092\u884C\u3063\u3066\u304F\u3060\u3055\u3044\u3002 <a href="" class="retry-upload">\u518D\u8A66\u884C</a></div>'},load:{failed:'<div class="line-1">\u753B\u50CF\u3092\u8AAD\u307F\u8FBC\u3081\u307E\u305B\u3093\u3067\u3057\u305F</div><div class="line-2">\u304A\u4F7F\u3044\u306E\u30CD\u30C3\u30C8\u30EF\u30FC\u30AF\u63A5\u7D9A\u306B\u554F\u984C\u304C\u767A\u751F\u3057\u307E\u3057\u305F\u3002\u6B21\u306E\u64CD\u4F5C\u3092\u884C\u3063\u3066\u304F\u3060\u3055\u3044\u3002 <a href="" class="retry-upload">\u518D\u8A66\u884C</a></div>',remote:{failed:'<div class="line-1">\u753B\u50CF\u3092\u8AAD\u307F\u8FBC\u3081\u307E\u305B\u3093\u3067\u3057\u305F</div><div class="line-2">\u3053\u306E\u753B\u50CF\u306B\u30EA\u30F3\u30AF\u3057\u3066\u3044\u308B URL \u304C\u7121\u52B9\u306B\u306A\u3063\u3066\u3044\u307E\u3059\u306E\u3067\u3001\u8868\u793A\u3067\u304D\u307E\u305B\u3093</div><div class="line-3">\u753B\u50CF\u3092\u30ED\u30FC\u30AB\u30EB\u306B\u4FDD\u5B58\u3057\u3066\u30A2\u30C3\u30D7\u30ED\u30FC\u30C0\u3057\u3066\u304F\u3060\u3055\u3044 <a href="" class="retry-upload">\u753B\u50CF\u30EA\u30F3\u30AF\u3092\u958B\u304F</a></div>',tooltip:"\u3053\u306E\u753B\u50CF\u306F\u5916\u90E8\u306B\u30EA\u30F3\u30AF\u3057\u3066\u3044\u308B\u305F\u3081\u3001\u30EA\u30F3\u30AF\u304C\u7121\u52B9\u306B\u306A\u308B\u3068\u3001\u8868\u793A\u3067\u304D\u306A\u304F\u306A\u308A\u307E\u3059\u306E\u3067\u3001\u30ED\u30FC\u30AB\u30EB\u306B\u4FDD\u5B58\u3057\u3001\u30DA\u30FC\u30B8\u306B\u633F\u5165\u3059\u308B\u3053\u3068\u3092\u304A\u52E7\u3081\u3057\u307E\u3059"}},abstract:"\u753B\u50CF"}};R.mergeLang({"zh-CN":lH,"en-US":cH,"ja-JP":aH});function uH(n,t,e,o){const r=n.getBlockByIndex(t,e),i=n.getBlockText(r),{left:s}=xn(i,o),l=re(s);let a=o;if(l.endsWith("![]()"))a-=5;else if(l.endsWith("![]"))a-=3;else return!1;const d=o;return zl("image/*").then(h=>{n.undoManager.runInGroup(()=>{n.deleteTextFromBlock(r,a,d-a);let p=e+1;re(n.getBlockText(r)).trim()?(Yl(n,r,a,{forceInsertAfter:!0}),a===0&&(n.deleteBlock(r),p--)):(n.deleteBlock(r),p--),qm(n,"image",t,p,{file:h})})}),!0}class dH{handleAfterInsertText(t,e,o,r,i){return!!(i===" "&&uH(t,e,o,r))}}function hH(n){const t=n.getFocusedBlock(),e=Ss(t);if(e&&zo(e)){n.selection.selectBlock(e,0);const o=xe.getImageObject(n,e);return o.getImages().length>0&&o.setSelectedIndex(0),!0}}function fH(n){const t=n.getFocusedBlock(),e=Ds(t);if(e&&zo(e)){n.selection.selectBlock(e,0);const o=xe.getImageObject(n,e);return o.getImages().length>0&&o.setSelectedIndex(0),!0}}function mH(n){const e=n.getFocusedBlock();if(e&&zo(e)){const o=xe.getImageObject(n,e),r=o.getImages();if(r.length>0){const i=o.getSelectedIndex();if(i===-1)return o.setSelectedIndex(r.length-1),!0;if(i>0)return o.setSelectedIndex(i-1),!0}}}function gH(n){const e=n.getFocusedBlock();if(e&&zo(e)){const o=xe.getImageObject(n,e),r=o.getImages();if(r.length>0){const i=o.getSelectedIndex();if(i===-1)return o.setSelectedIndex(0),!0;if(i<r.length-1)return o.setSelectedIndex(i+1),!0}}}function s2(n){const e=n.getFocusedBlock();if(e&&zo(e)){const o=xe.getImageObject(n,e);if(o.getImages().length>0){const i=o.getSelectedIndex();if(i!==-1)return o.removeImage(i),!0}}}const pH={ArrowLeft:mH,ArrowRight:gH,ArrowUp:fH,ArrowDown:hH,Delete:s2,Backspace:s2},CH=S("copy-image");function AH(n,t,e,o){const r=e.getImages()[o],i=e.getImages().length===1?e.getWidthPercent():r.flex*100,s=cn([r],i),l={id:K(),type:"embed",embedType:"image",embedData:s},a=n.options.componentsOptions.image;a!=null&&a.defaultAlign&&(l.align=a.defaultAlign);const d={blocks:{root:[l]},comments:{},meta:{}},h=document.createElement("canvas");h.width=t.naturalWidth,h.height=t.naturalHeight;const p=h.getContext("2d");if(!p)return;const A={},v={};try{p.drawImage(t,0,0,h.width,h.height);const z=h.toDataURL("image/png").replace(/^data:image\/(png|jpg);base64,/,""),q=Dm(z),rt=new File([q],`${Date.now()}.png`,{type:"image/png"});A["image/png"]=rt}catch(H){CH.error(H)}Mh(n,d);const D=`<img src="${n.doc.buildResourceUrl(r.src,{withToken:!0})}" />`,T=Lh(D,d),_=Ma(n,d);A["text/plain"]=new Blob([_],{type:"text/plain"}),v["text/plain"]=_;const M=new Blob([T],{type:"text/html"});return A["text/html"]=M,v["text/html"]=T,[A,v]}function bH(n,t,e,o,r){const i=AH(n,t,e,o);if(!i)return;const[s,l]=i;if(s){const a=Object.entries(s).map(([d,h])=>({type:d,data:h}));return Mm(a).then(d=>{if(!d&&r){const h=r.clipboardData;h&&(h.setData("text/plain",l["text/plain"]),h.setData("text/html",l["text/html"]))}}),!0}}function t8(n,t){const e=n.selection.range;if(e.start.blockId!==e.end.blockId)return;const r=n.getFocusedBlock();if(r&&zo(r)){const i=xe.getImageObject(n,r);if(i.getImages().length>0){const l=i.getSelectedIndex();if(l!==-1){const d=Qr(r)[l].querySelector("img");if(d)return bH(n,d,i,l,t)}}}}class vH{constructor(t){this.editor=t,setTimeout(()=>{this.editor.input.addHandler(this)})}handleBeforeCopy(t,e,o){if(t8(t,e))return!0}handleBeforeCut(t,e){if(t8(t,e))return s2(t),!0}destroy(){}}class l2{constructor(t){this.editor=t,setTimeout(()=>{this.editor.input.addHandler(this)})}async handleAfterPasteDoc(t,e,o){return Object.values(e.blocks).forEach(r=>{r.forEach(i=>{if(i.type==="embed"&&i.embedType==="image"){const s=i.embedData;if(Array.isArray(s.src))return;if(s.src.startsWith("https:")||s.src.startsWith("http:")){const l=o.blockIdMap.get(i.id);l&&Ki(t,l).setAutoFix(!0)}}})}),!1}destroy(){}}const yH=S("image-embed");function kH(n,t,e,o,r,i){xe.create(n,e).createContent(r,i,t),n.addCustom("image-select-handler",()=>new iH(n)),n.addCustom("image-copy-handler",()=>new vH(n)),setTimeout(()=>{n.addCustom("drag-handler",()=>new rH(n));const l=n.addCustom("image-resizer",()=>new sH(n)),a=e.embedData;kc(a)?l.disable(i):l.currentResizer===i&&l.enable(i)})}function wH(n,t,e,o){const r=t.embedData,i=wc(r);return o==="html"?i.map(s=>`<img src="${n.doc.buildResourceUrl(s.src,{withToken:!0})}">`).join(""):o==="markdown"?`${i.map(l=>`![img](${n.doc.buildResourceUrl(l.src,{withToken:!0})})`).join(`
421
421
  `)}
422
422
  `:i.map(s=>n.doc.buildResourceUrl(s.src,{withToken:!0})).join(`
423
423
  `)}class BH{constructor(){m(this,"group","image");m(this,"commands",[])}executeCommand(t,e,o){if(o.id==="replace-image"){const{block:r,image:i}=o.data;xe.getImageObject(t,r).replaceImage(0,i)}}}function EH(){return{blockCommands:{image:new BH},abstract:`${R.t("image.abstract")}`}}function xH(){return{name:"Image",insertEmbedCommandItems:[{id:"insert-image",name:R.t("image.abstract"),icon:EL,group:"common",subText:"/image",order:100}],handleInsertEmptyEmbed:async(n,t)=>{var v;let e;(v=t.data)!=null&&v.file&&(e=t.data.file);const o=P7(n);if(e=e!=null?e:await zl(o),!e)return null;try{N7(n,e)}catch{return null}let r={width:k7,height:z0};try{r=await i$(e)}catch(B){yH.error(B)}const i=n.rootContainer.clientWidth,s=r.width<i?Math.min(100,r.width/i*100):100,l={src:"",width:r.width,height:r.height,flex:1,virtualSize:!1},a=cn([l],s),d={id:K(),type:"embed",embedType:"image",embedData:a},h=n.options.componentsOptions.image;h!=null&&h.defaultAlign&&(d.align=h.defaultAlign);const p=n.insertBlock(t.containerId,t.blockIndex,d);return xe.getImageObject(n,p).replaceImage(0,e),p}}}function IH(n,t,e){var h;const{data:o}=e,r=n.getBlockString(t).trim();if(!o||o.embedType!=="image"||!tt(n,t))return null;const i=r.match(/^!\[[^\]]*\]\((?<filename>.*?)(?="|\))(?<optionalPart>".*")?\)/),s=(h=i==null?void 0:i.groups)==null?void 0:h.filename;if(!s)return null;const l={src:s},a={id:K(),type:"embed",embedType:"image",embedData:l};xe.create(n,a).setAutoFix(!0);const d=n.options.componentsOptions.image.defaultAlign;return d&&(a.align=d),{blockData:a}}function TH(n,t){const e=it(t);n.destroyCustom(`image-${e}`)}const e8={embedType:"image",createEmbedContent:kH,convertTo:wH,convertFrom:IH,getBlockProperties:EH,getOptions:xH,handleDrop:X$,handleDropOver:nH,handleDeleteBlock:TH};class DH{constructor(t,e){m(this,"toolbar");m(this,"anchor",null);m(this,"item");m(this,"docs",null);m(this,"checkedId");m(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()}))});m(this,"handleClose",()=>{this.editor.focus()});m(this,"handleSelectionChange",()=>{this.hide()});this.editor=t,this.onPasteSpecial=e,this.item={id:"paste-special",name:"",icon:xL,dropdown:!0,manualShowChildren:!0,childrenPlacement:"bottom-start",childrenOffset:[-4,4],children:[]},this.toolbar=new ou([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(!tt(e,r))return;const i=Ti(e,r,o)[0];if(!i)return;this.anchor&&this.anchor.remove(),this.anchor=Li(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("selectionChange")}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:R.t("pasteSpecial.originFormats"),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:R.t("pasteSpecial.plainText"),data:t["text/plain"]}),o.push({id:"text/markdown",states:this.checkedId==="text/markdown"?["checked"]:void 0,name:R.t("pasteSpecial.markdown"),data:t["text/markdown"]})),o}}const SH=S("paste-special");class c2{constructor(t){m(this,"button");m(this,"lastUndoAction",null);m(this,"event",null);m(this,"handlePasteSpecial",t=>{this.editor.undoManager.runInGroup(()=>{this.editor.undoManager.undoTo(this.lastUndoAction),this.editor.pasteDoc(t)})});this.editor=t,this.button=new DH(t,this.handlePasteSpecial)}destroy(){this.event=null,this.button.destroy()}handleChanged(t,e){this.event=null,this.button.hide()}async handleBeforePaste(t,e){return SH.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(!tt(t,i))return!1;this.button.clearCheckedState(),this.button.show(o),this.event=e}return!1}}const LH={pasteSpecial:{originFormats:"\u4FDD\u6301\u539F\u6837\u5F0F",plainText:"\u7C98\u8D34\u7EAF\u6587\u672C",markdown:"\u7C98\u8D34\u4E3A Markdown"}},MH={pasteSpecial:{originFormats:"Keep origin formats",plainText:"Paste as plain text",markdown:"Paste as markdown"}},RH={pasteSpecial:{originFormats:"\u5143\u306E\u30B9\u30BF\u30A4\u30EB\u3092\u7DAD\u6301\u3059\u308B",plainText:"\u30D7\u30EC\u30FC\u30F3\u30C6\u30AD\u30B9\u30C8\u3092\u8CBC\u308A\u4ED8\u3051\u308B",markdown:"Markdown \u3068\u3057\u3066\u8CBC\u308A\u4ED8\u3051"}};R.mergeLang({"zh-CN":LH,"en-US":MH,"ja-JP":RH});const Pnt="",OH=S("html-to-doc");function _H(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=Ud(i);return JSON.parse(s)}catch(s){OH.error(`invalid doc data: ${s}, ${i}`)}}}return null}const n8="latex-b172fea480b",FH=n=>({name:"latex-block",level:"block",start(t){var e,o;return(o=(e=t.match(/\$\$[^\$]/))==null?void 0:e.index)!=null?o:-1},tokenizer(t,e){const o=/^\$\$([^\$]+)\$\$/.exec(t);return o?{type:"latex-block",raw:o[0],formula:o[1]}:void 0},renderer(t){return n.lazy?`<span class="${n8}" block>${t.formula}</span>`:n.render(t.formula,!0)}}),PH=n=>({name:"latex",level:"inline",start(t){var e,o;return(o=(e=t.match(/\$[^\$]/))==null?void 0:e.index)!=null?o:-1},tokenizer(t,e){const o=/^\$([^\$]+)\$/.exec(t);return o?{type:"latex",raw:o[0],formula:o[1]}:void 0},renderer(t){return n.lazy?`<span class="${n8}">${t.formula}</span>`:n.render(t.formula,!1)}});var NH=(n={})=>(n.lazy&&n.env!=="test"&&new IntersectionObserver((t,e)=>{for(const o of t){if(!o.isIntersecting)continue;const r=o.target;e.unobserve(r),Promise.resolve(n.render(r.innerText,r.hasAttribute("block"))).then(i=>{r.innerHTML=i}),r.classList.add("latex-rendered")}},{threshold:1}),{extensions:[FH(n),PH(n)]});function Bc(n){const t=n.type;if(t==="link")return!!n.tokens.some(Bc);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 $H(n){return!Bc(n)}function HH(n){if(n.length===0)return[];if(n.length===1)return[n];const t=[];let e=[n[0]],o=Bc(n[0]);for(let r=1;r<n.length;r++){const i=n[r];o===Bc(i)?e.push(i):(t.push(e),e=[i],o=Bc(i))}return t.push(e),t}function jH(n,t,e){const o=n.href;let r=e.tokensToText(n.tokens,t,e);return r.length===0&&(r=Oi(o,t)),r=uh(r,"link",o),r}let Lu;function a2(n){Lu||(Lu=document.createElement("textarea")),Lu.innerHTML=n;const t=Lu.childNodes.length===0?"":Lu.childNodes[0].nodeValue;return t!=null?t:""}function UH(n,t){const e=a2(n.text);return[lo(e,{...t,"style-code":!0})]}function zH(n,t,e){const r=n.tokens;return r?e.tokensToText(r,t,e):ag(a2(n.text),t)}const VH=S("token-to-text");function u2(n,t,e){return n.map(r=>r.type==="text"?zH(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==="del"?e.tokensToText(r.tokens,{...t,"style-strikethrough":!0},e):r.type==="link"?jH(r,t,e):r.type==="codespan"?UH(r,t):r.type==="br"?[{insert:" ",attributes:{id:K(),created:Date.now(),box:!0,type:"br"}}]:r.type==="escape"?ag(a2(r.text),t):r.type==="latex"?[{insert:" ",attributes:{id:K(),created:Date.now(),box:!0,type:"math",tex:r.formula}}]:(VH.warn(`unknown token in text: ${JSON.stringify(r)}`),[])).flat()}function WH(n,t){const e=u2(n.tokens,{},t);return[{id:K(),type:"text",text:e,heading:n.depth}]}function qH(n,t){const{text:e,children:o}=t.tokensToTextWithChildren(n.tokens,t),r=[];return e.length>0&&r.push({id:K(),type:"text",text:e}),r.push(...o),r}function GH(n,t){const{text:e,children:o}=t.tokensToTextWithChildren([n],t),r=[];return e.length>0&&r.push({id:K(),type:"text",text:e}),r.push(...o),r}function ZH(n,t){const e=typeof n.start=="number"?n.start:1,o=n.ordered,r=K(),i=[];return n.items.forEach((l,a)=>{const d={...t,listLevel:t.listLevel+1},{text:h,children:p}=t.tokensToTextWithChildren(l.tokens,d);let A;typeof l.checked=="boolean"&&(A=l.checked?"checked":"unchecked");const v={id:K(),type:"list",groupId:r,ordered:o,checkbox:A,start:e+a,text:h,level:t.listLevel};i.push(v),i.push(...p)}),i}function QH(n,t){const e=t.tokensToBlocks(n.tokens,t);return e.forEach(o=>{o.quoted=!0}),e}const o8=100,YH=20,JH=600;function KH(n,t){const e=t.text;if(e){const o=re(e);return Math.min(Vd(o,n)+YH,JH)}return o8}function r8(n,t){let e=o8;return t.forEach(o=>{e=Math.max(e,KH(n,o))}),e}function XH(n,t){var l,a;const e=n.header.length,o=n.rows.length+1,r=[],i=Array(e).fill(100);for(let d=0;d<o;d++){let h;d===0?h=n.header:h=n.rows[d-1];for(let p=0;p<e;p++){const A=h[p],v=(l=A==null?void 0:A.tokens)!=null?l:[],B=K();r.push(B);let D;if(v.length===0)D=[hh()];else if(Bc(v[0]))D=t.tokensToBlocks(A.tokens,t),D.length===0&&D.push(hh());else{const{text:T,children:_}=t.tokensToTextWithChildren(A.tokens,t);D=[{id:K(),type:"text",text:T},..._]}t.doc.blocks[B]=D,i[p]=Math.max(i[p],r8((a=t.font)!=null?a:"",D))}}return[{id:K(),type:"table",cols:e,rows:o,colsWidth:i,children:r}]}function tj(n){return[{id:K(),type:"embed",embedType:"hr",embedData:{}}]}function ej(n,t){var a;const e=n.text;if(!e)return[];try{const d=n.text,h=Ud(d),p=JSON.parse(h);if(p){const{root:A,...v}=p.blocks;return t.doc.blocks={...t.doc.blocks,...v},A}}catch{}const o=(a=n.lang)!=null?a:"Plain Text";if(o==="mermaid")return[{id:K(),type:"embed",embedType:"mermaid",embedData:{mermaidText:e}}];if(o==="plantuml")return[{id:K(),type:"embed",embedType:"plantuml",embedData:{plantumlText:e}}];if(o==="flow"||o==="flowchart")return[{id:K(),type:"embed",embedType:"flowchart",embedData:{flowchartText:e}}];const i=e.split(`
@@ -479,7 +479,7 @@ width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
479
479
  <path d="M2.00218 11.0005L8.00341 4.99923L14.0046 11.0005" stroke="currentColor" fill="transparent" stroke-width="1.5" stroke-linejoin="bevel"/>
480
480
  </svg>`,SU=`<svg width="17" height="16" viewBox="0 0 17 16" xmlns="http://www.w3.org/2000/svg">
481
481
  <path d="M14.0029 4.99933L8.00172 11.0006L2.00049 4.99933" stroke="currentColor" fill="transparent" stroke-width="1.5" stroke-linejoin="bevel"/>
482
- </svg>`,znt="",Zf="reply-editor-editing",{t:w2}=R;class LU{constructor(t,e,o,r){m(this,"root");m(this,"components");m(this,"handleFocus",()=>{const{replyEditor:t,okButton:e}=this.components;t.isEmpty()&&W(e,Kr)});m(this,"handleDocChange",()=>{const{replyEditor:t,okButton:e}=this.components,o=t.getDoc();Ag(o)?W(e,Kr):et(e,Kr)});m(this,"getReplyEditor",()=>this.components.replyEditor);m(this,"showReplyEditor",()=>{xt(this.root,Zf)||(W(this.root,Zf),this.components.replyEditor.edit())});m(this,"hideReplyEditor",()=>{!xt(this.root,Zf)||et(this.root,Zf)});m(this,"reply",()=>{const{mainEditor:t,comment:e,components:{replyEditor:o},commentsProvider:r}=this,i=o.getDoc(),s=Gf({editor:t,commentGroupId:e.groupId});r.localCreateComment(s,i),this.hideReplyEditor(),o.clear()});m(this,"cancel",()=>{const{replyEditor:t}=this.components;this.hideReplyEditor(),t.clear()});m(this,"hide",()=>{xt(this.root,"hidden")||W(this.root,"hidden")});m(this,"show",()=>{et(this.root,"hidden")});this.mainEditor=t,this.commentsProvider=e,this.comment=o,this.groupItem=r,this.root=w("div",["comment-quick-reply"],null),this.components=this.createQuickReply()}createQuickReply(){const{commentsProvider:t}=this,e=Qs(this.root,Yt.QuickReply,w2("comment.placeholder"));Xr(e,Yt.QuickReply),e.classList.add("quick-reply-button");const o=w("div",["quick-reply-editor"],this.root),r=jr(),i=new k2(this.mainEditor,t,r);i.editor.addListener("docChanged",this.handleDocChange),i.editor.addListener("focus",this.handleFocus),i.editor.input.addHandler(new wU(this.groupItem)),o.append(i.root);const s=w("div",["reply-editor-actions"],o),l=ji(Yt.QuickReplyCancel,w2("common.cancel"));Xr(l,Yt.QuickReplyCancel);const a=ji(Yt.QuickReplyOk,w2("comment.send"));return Xr(a,Yt.QuickReplyOk),W(a,Kr),s.append(l,a),this.hideReplyEditor(),{replyTextButton:e,replyEditor:i,replyEditorContainer:o,okButton:a}}}const ti=S("comment-group-item");class MU extends be.TypedEmitter{constructor(e,o,r,i){super();m(this,"root");m(this,"header");m(this,"mainItem");m(this,"childrenList");m(this,"resizeObserver");m(this,"quickReply");m(this,"createRoot",()=>w("div",["comment-group-item-root"],null));m(this,"createChildrenList",()=>{const e=w("div",["comment-children-list-container"],this.root);return new TU({editor:this.editor,commentsProvider:this.commentsProvider,comments:this.comment.children,parent:e,groupList:this.groupList,groupItem:this})});m(this,"updateLastCommentItem",()=>{const e=Array.from(this.root.querySelectorAll(":scope .comment-item-root"));g(ti,e.length!==0,"current group item not exist comment-item"),e.forEach(r=>{et(r,P8)});const o=e.at(-1);W(o,P8)});m(this,"updateSwitchButton",()=>{const e=this.root.querySelector(':scope .editor-text-button[group-item-action="switch-up"]'),o=this.root.querySelector(':scope .editor-text-button[group-item-action="switch-down"]');g(ti,e,"switchUpButton not exist"),g(ti,o,"switchDownButton not exist"),et(o,"disabled"),et(e,"disabled"),this.root.previousElementSibling===null&&W(e,"disabled"),this.root.nextElementSibling===null&&W(o,"disabled")});m(this,"handleReadonlyChanged",e=>{e.readonly?W(this.root,"readonly"):et(this.root,"readonly")});m(this,"handleResize",()=>{this.emit("resize")});this.editor=e,this.commentsProvider=o,this.comment=r,this.groupList=i,this.root=this.createRoot(),this.header=this.createHeader(),this.mainItem=this.createItem(),this.childrenList=this.createChildrenList(),this.quickReply=this.createQuickReply(),this.editor.on("readonlyChanged",this.handleReadonlyChanged),this.resizeObserver=new ResizeObserver(this.handleResize),this.resizeObserver.observe(this.root),this.updateLastCommentItem()}get commentCount(){return $8(this.root)}createQuickReply(){const{editor:e,commentsProvider:o,comment:r}=this,i=new LU(e,o,r,this);return this.root.append(i.root),i}createHeader(){const{comment:e}=this,o=w("div",["comment-item-head"],this.root),r=w("span",["item-head-quote"],o);r.innerText=e.abstract;const i=w("span",["item-head-switch"],o),s=Qs(i,Yt.SwitchUp,"up",DU),l=Qs(i,Yt.SwitchDown,"down",SU);return Xr(s,Yt.SwitchUp),Xr(l,Yt.SwitchDown),o}createItem(){const e=w("div",["comment-item-container"],this.root),{editor:o,commentsProvider:r,comment:i,groupList:s}=this,l=new Q8({mainEditor:o,commentsProvider:r,comment:i,groupList:s,groupItem:this});return e.appendChild(l.root),l}findCommentItem(e){return e?e===this.mainItem.comment.id?this.mainItem:this.childrenList.items.find(o=>o.comment.id===e):null}handleCreateComment(e){return g(ti,Js(e),"invalid comment, not a child comment"),g(ti,e.groupId===this.comment.id,"invalid comment, not a child comment"),this.childrenList.createItem(e)}handleUpdateChildComment(e){g(ti,e.groupId===this.mainItem.comment.id,"invalid child comment");const o=this.childrenList.findItem(e.id);if(!o){ti.error(`can't find child comment item: ${e.id}`);return}o.reloadDoc()}handleUpdateMainComment(e){g(ti,e.id===this.mainItem.comment.id,"invalid comment"),this.mainItem.reloadDoc()}deleteMainComment(e){g(ti,e===this.mainItem.comment.id,"invalid comment"),this.mainItem.destroy()}edit(){this.mainItem.edit()}destroy(){this.mainItem.destroy(),this.childrenList.destroy(),this.root.remove(),this.resizeObserver.disconnect(),this.removeAllListeners(),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged)}}const RU=S("arrange=items"),J8=20;function K8(n,t){const e=n.rootContainer.querySelector(`[comment-${t.toLocaleLowerCase()}=${t}`);if(!e)return-1;const o=n.scrollContainer.getBoundingClientRect(),r=n.scrollContainer.scrollTop;return e.getBoundingClientRect().top-o.top+r}function X8(n,t){return Number.parseInt(t.root.style.top,10)}function ty(n,t,e,o){let r=0;e&&(r=t.indexOf(e),r===-1&&(r=0));for(let i=r;i<t.length;i++){const s=t[i],l=s.comment,a=K8(n,l.groupId);if(s.root.setAttribute("data-target-top",a.toString()),i===r){if(o!==void 0){const p=t[0];p.root.style.top=`${o}px`}else s.root.style.top=`${a}px`;continue}const d=t[i-1],h=X8(n,d)+d.root.getBoundingClientRect().height;h>a?s.root.style.top=`${h+J8}px`:s.root.style.top=`${a}px`}for(let i=r-1;i>=0;i--){const s=t[i],l=s.comment,a=K8(n,l.groupId);s.root.setAttribute("data-target-top",a.toString());const d=s.root.getBoundingClientRect(),h=a+d.height,p=t[i+1];g(RU,p,"no next item");const A=X8(n,p);A<h?s.root.style.top=`${A-d.height-J8}px`:s.root.style.top=`${a}px`}setTimeout(()=>{n.scrollContainer.dispatchEvent(new Event("scroll"))},350)}const Qf=S("comment-group-item-handler");class OU{constructor(t,e){m(this,"handleSwitchUp",t=>{const e=Math.max(0,t-1);this.groupList.setActiveItem(e),this.groupList.updateItemsLayout()});m(this,"handleSwitchDown",t=>{const e=Math.min(t+1,this.groupList.items.length);this.groupList.setActiveItem(e),this.groupList.updateItemsLayout()});m(this,"handleQuickReply",t=>{const{quickReply:e}=t;e.showReplyEditor()});m(this,"handleQuickReplyOk",t=>{const{quickReply:e}=t;e.reply(),t.updateLastCommentItem()});m(this,"handleQuickReplyCancel",t=>{const{quickReply:e}=t;e.cancel()});m(this,"handleCommentItemReply",(t,e)=>{const o=t.findCommentItem(e);g(Qf,o,`the commentItem: ${e} not exist `);const{quickReply:r}=t;r.show(),r.showReplyEditor();const{comment:i}=o,s=r.getReplyEditor(),l=s.editor.getFocusedBlock(),a={type:"mention",id:K(),box:!0,created:Date.now(),text:i.displayName,iconUrl:i.avatarUrl,mentionId:i.userId};s.editor.insertBoxToBlock(l,0,a)});m(this,"handleCommentItemMore",t=>{const{quickReply:e}=t;e.hideReplyEditor(),e.getReplyEditor().clear()});m(this,"handleCommentItemOk",(t,e)=>{const o=t.findCommentItem(e);g(Qf,o,`the commentItem: ${e} not exist `);const{quickReply:r}=t,{comment:i,getCommentEditor:s}=o,l=s(),a=l.getDoc();this.commentsProvider.localUpdateComment(i,a),l.readonly(),r.show()});m(this,"handleCommentItemCancel",(t,e)=>{var a,d;const o=t.findCommentItem(e);g(Qf,o,`the commentItem: ${e} not exist `);const r=this.commentsProvider.getComment(o.comment.id);let i=!1;if((a=r.blocks)!=null&&a.length||(i=!0),((d=r.blocks)==null?void 0:d.length)===1){const h=r.blocks[0];i=!!h.text&&rn(h.text)===0}if(i){this.commentsProvider.localDeleteComment(o.comment.id);return}const{quickReply:s}=t,l=o.getCommentEditor();l.setDoc(o.doc),l.readonly(),s.show()});m(this,"handleCommentItemEdit",t=>{const e=this.groupList.findItem(t.comment.groupId);if(!e)return;const{quickReply:o}=e;t.getCommentEditor().edit(),o.hide()});m(this,"handleCommentItemDelete",t=>{const e=this.groupList.findItem(t.comment.groupId);if(!e)return;const{quickReply:o}=e,{comment:r}=t;this.commentsProvider.localDeleteComment(r.id),o.show()});m(this,"execute",(t,e,o,r)=>{const i=gU(t);if(!i||CU(i))return;const s=pU(i);switch(s){case Yt.SwitchUp:this.handleSwitchUp(r);break;case Yt.SwitchDown:this.handleSwitchDown(r);break;case Yt.CommentItemReply:this.handleCommentItemReply(e,o);break;case Yt.CommentItemMore:this.handleCommentItemMore(e);break;case Yt.CommentItemOk:this.handleCommentItemOk(e,o);break;case Yt.CommentItemCancel:this.handleCommentItemCancel(e,o);break;case Yt.CommentItemDelete:break;case Yt.CommentItemEdit:break;case Yt.QuickReply:this.handleQuickReply(e);break;case Yt.QuickReplyOk:this.handleQuickReplyOk(e);break;case Yt.QuickReplyCancel:this.handleQuickReplyCancel(e);break;default:const l=s;Qf.debug(`not implement handler for ${l}`)}});this.groupList=t,this.commentsProvider=e}destroy(){}}const Yf=S("comment-group-list");class _U extends _u{constructor(e,o,r){super(e,o,r,ts(e,o),{});m(this,"groupItemHandlers");m(this,"findGroupItem",e=>this.items.find(o=>o.comment.groupId===e));m(this,"handleContainerClick",e=>{if(!e.target||!(e.target instanceof Element))return;const o=e.target.closest(".comment-group-item-root");if(!o)return;const r=mU(e.target),i=this.items.findIndex(s=>s.root===o);if(i!==-1){this.setActiveItem(i);const{groupItemHandlers:s}=this;s.execute(e.target,this.items.at(i),r,i)}});m(this,"handleSelectionChanged",()=>{var o;const e=V8(this.editor);if(e.length>0){if(((o=this.activeItem)==null?void 0:o.comment.id)&&e.includes(this.activeItem.comment.id))return;const r=e[0],i=this.items.findIndex(s=>s.comment.groupId===r);this.setActiveItem(i),this.emit("selectionOnComment")}else this.setActiveItem(-1)});m(this,"handleEditorResize",()=>{this.updateItemsLayout()});m(this,"handleDocChanged",()=>{this.updateComments()});m(this,"handleItemResize",()=>{this.updateItemsLayout()});m(this,"handleScroll",e=>{if(e.deltaY>=0||this.editor.scrollContainer.scrollTop!==0)return;const o=document.elementFromPoint(e.clientX,e.clientY);if(!o||!(o instanceof HTMLElement)||!this.editor.scrollContainer.contains(o))return;const r=this.container.querySelector(".comment-group-item-root");if(!r)return;const i=Number.parseFloat(r.style.top),s=Number.parseFloat(r.getAttribute("data-target-top")||"0");!Number.isNaN(i)&&!Number.isNaN(s)&&i<s&&ty(this.editor,this.items,null,Math.min(i+(0-e.deltaY)*3,s))});m(this,"updateGroupItemSwitch",()=>{const e=this.activeItem;g(Yf,e,"invalid activeItem"),e.updateSwitchButton()});m(this,"updateComments",He.default(()=>{const e=ts(this.editor,this.commentsProvider);let o=!1;for(let r=0;r<e.length;r++){const i=e[r];if(!this.findGroupItem(i.groupId)){this.handleCreateComment(i,!1),o=!0;continue}}for(let r=this.items.length-1;r>=0;r--){const i=this.items[r];e.findIndex(s=>s.groupId===i.comment.groupId)===-1&&(this.deleteItem(i.comment.id),o=!0)}o&&(this.updateItemsLayout(),this.emit("commentCountChanged"))},100));this.updateItemsLayout(),this.bindEvents(),this.editor.addListener("selectionChanged",this.handleSelectionChanged),this.editor.addListener("resize",this.handleEditorResize),this.editor.addListener("docChanged",this.handleDocChanged),this.editor.scrollContainer.addEventListener("wheel",this.handleScroll,{passive:!1}),this.items.forEach(i=>i.addListener("resize",this.handleItemResize)),this.groupItemHandlers=new OU(this,o)}destroy(){this.editor.removeListener("selectionChanged",this.handleSelectionChanged),this.editor.removeListener("resize",this.handleEditorResize),this.editor.removeListener("docChanged",this.handleDocChanged),this.editor.scrollContainer.removeEventListener("wheel",this.handleScroll),super.destroy(),this.unbindEvents(),this.removeAllListeners()}updateItemsLayout(){ty(this.editor,this.items,this.activeItem)}bindEvents(){this.container.addEventListener("click",this.handleContainerClick)}unbindEvents(){this.container.removeEventListener("click",this.handleContainerClick)}createItem(e,o){const r=new MU(this.editor,this.commentsProvider,e,this);return o==="insert"&&(W(r.root,"no-animation"),r.root.style.opacity="0",setTimeout(()=>{et(r.root,"no-animation"),r.root.style.opacity="1"},150)),r}findInsertPos(e){const r=ts(this.editor,this.commentsProvider).findIndex(i=>i.id===e.id);return r===-1||r>this.items.length?-1:r}insertItem(e,o){const r=super.insertItem(e);return r?(o!=null&&o.active&&this.setActiveItem(this.items.indexOf(r)),this.updateItemsLayout(),r.addListener("resize",this.handleItemResize),r):null}setActiveItem(e){if(g(Yf,e>=-1&&e<this.items.length,`invalid index: ${e}`),e===this.activeIndex)return;const o=this.container.querySelector(".comment-group-item-root.active");if(o&&et(o,"active"),e!==-1){const r=this.items[e];W(r.root,"active"),this.updateItemsLayout(),this.updateGroupItemSwitch()}this.emit("activeItemChanged",e)}get activeIndex(){const e=this.container.querySelector(".comment-group-item-root.active");return e?this.items.findIndex(o=>o.root===e):-1}get activeItem(){const e=this.activeIndex;return e===-1?null:this.items[e]}handleCreateComment(e,o){if(Js(e)){const l=this.findGroupItem(e.groupId);l&&l.childrenList.insertItem(e)}const r=this.findItem(e.id);g(Yf,!r,"comment group item has already exists");const i={children:[],...e};g(Yf,i.children,"not a comment group");const s=this.insertItem(i,{active:o});!s||o&&setTimeout(()=>{const l=this.items.indexOf(s);this.setActiveItem(l),s.edit(),s.quickReply.hide()})}handleDeleteComment(e){for(let o=0;o<this.items.length;o++){const r=this.items[o];if(r.comment.id===e){r.childrenList.items.length===0?(this.deleteItem(r.comment.id),this.updateItemsLayout()):r.deleteMainComment(e);return}if(r.childrenList.deleteItem(e)){r.commentCount===0&&(this.deleteItem(r.comment.id),this.updateItemsLayout());return}}}handleUpdateComment(e){if(Js(e)){const r=this.commentsProvider.getComment(e.groupId),i=this.findItem(r.id);i&&i.handleUpdateChildComment(e);return}const o=this.findItem(e.id);o&&o.handleUpdateMainComment(e)}}const FU="comment-mini";S("comment-list");class PU extends be.TypedEmitter{constructor(e,o){super();m(this,"root");m(this,"groupsContainer");m(this,"list");m(this,"handleSelectionOnComment",()=>{this.emit("onSelectComment")});m(this,"updateCommentCount",()=>{var o,r;const e=vU(this.editor,this.commentsProvider);(r=(o=this.commentOptions)==null?void 0:o.onCommentCountChange)==null||r.call(o,e)});m(this,"handleActiveItemChanged",()=>{var o;const e=this.list.activeItem;q8(this.editor,(o=e==null?void 0:e.comment.id)!=null?o:"")});m(this,"handleItemLayoutUpdated",()=>{var o,r;const e=xt(this.root,FU);(r=(o=this.commentOptions)==null?void 0:o.onUpdateLayout)==null||r.call(o,this.editor,{expand:e})});this.editor=e,this.commentsProvider=o,this.root=w("div",["editor-web-comment-root"],null),this.groupsContainer=w("div",["comment-groups-container"],this.root),this.list=this.createList(),this.commentsProvider.addListener(this),this.list.addListener("activeItemChanged",this.handleActiveItemChanged),this.list.addListener("itemLayoutUpdated",this.handleItemLayoutUpdated),this.list.addListener("selectionOnComment",this.handleSelectionOnComment),this.list.addListener("commentCountChanged",this.updateCommentCount),this.updateCommentCount()}get commentOptions(){return this.editor.getComponentOptions("comment")}destroy(){this.list.removeAllListeners(),this.commentsProvider.removeListener(this),this.list.destroy(),this.root.remove()}onCreateComment(e,o){const r=this.commentsProvider.getComment(e);this.list.handleCreateComment(r,o),this.updateCommentCount()}onDeleteComment(e,o){this.list.handleDeleteComment(e),this.updateCommentCount()}onUpdateComment(e,o){const r=this.commentsProvider.getComment(e);this.list.handleUpdateComment(r)}createList(){return new _U(this.editor,this.commentsProvider,this.groupsContainer)}show(e){var o;if(et(this.root,"hidden"),e){const r=this.list.findItemIndex(e);this.list.setActiveItem(r)}(o=this.commentOptions)==null||o.controller.showCommentList()}hide(){W(this.root,"hidden")}}class NU extends _u{constructor({editor:t,parent:e,commentsProvider:o,comments:r}){super(t,o,e,r,{})}findInsertPos(){return this.items.length}createItem(t){const{editor:e,commentsProvider:o}=this;return new Y8(e,o,t)}destroy(){this.items.forEach(t=>{t.destroy()})}}const Jf=S("mobile-comment-group-item"),$U=20;class HU extends be.TypedEmitter{constructor(e,o,r){super();m(this,"root");m(this,"childrenList");m(this,"mainItem");m(this,"scroller");m(this,"createRoot",()=>w("div",["mobile-group-item-root"],null));m(this,"createMainItem",e=>{const{editor:o,commentsProvider:r,comment:i}=this,s=new Y8(o,r,i);return e.append(s.root),s});m(this,"createChildrenList",e=>{const{editor:o,commentsProvider:r,comment:i}=this,s=w("div",["mobile-comment-children-list-container"],e);return new NU({editor:o,commentsProvider:r,comments:i.children,parent:s})});m(this,"handleTouchEnd",()=>{var i;const{scroller:e}=this,{pullThreshold:o=$U}=(i=this.editor.getComponentOptions("comment"))!=null?i:{};let r=null;if(e.y>e.minScrollY+o?(r=this.root.previousElementSibling,r||this.emit("onReachTop")):e.y<e.maxScrollY-o&&(r=this.root.nextElementSibling,r||this.emit("onReachBottom")),r){const s=r.id;this.emit("onSwitchGroup",s,N8)}});m(this,"refreshScroller",()=>{this.scroller.refresh()});this.editor=e,this.commentsProvider=o,this.comment=r,this.root=w("div",["mobile-group-item-root"],null),this.root.id=r.groupId;const i=w("div",["mobile-group-item"],this.root),s=w("div",["mobile-group-item-space"],null),l=w("div",["mobile-group-item-abstract"],null);l.textContent=r.abstract;const a=w("div",["mobile-group-item-list-container"],null);this.mainItem=this.createMainItem(a),this.childrenList=this.createChildrenList(a),i.append(s,l,a),this.scroller=new Y5.default(this.root,{stopPropagation:!0,click:!0}),this.scroller.on("touchEnd",this.handleTouchEnd)}get commentCount(){return $8(this.root,".mobile-group-item")}handleUpdateChildComment(e){g(Jf,e.groupId===this.mainItem.comment.id,"invalid child comment");const o=this.childrenList.findItem(e.id);if(!o){Jf.error(`can't find child comment item: ${e.id}`);return}o.reloadDoc()}handleUpdateMainComment(e){g(Jf,e.id===this.mainItem.comment.id,"invalid comment"),this.mainItem.reloadDoc()}deleteMainComment(e){g(Jf,e===this.mainItem.comment.id,"invalid comment"),this.mainItem.destroy()}destroy(){this.mainItem.destroy(),this.childrenList.destroy(),this.scroller.off("touchEnd",this.handleTouchEnd),this.scroller.destroy(),this.root.remove(),this.removeAllListeners()}}const B2=S("mobile-group-list");class jU extends _u{constructor(e,o,r,i){super(e,o,r,ts(e,o),{});m(this,"scroller");m(this,"refreshScroller",()=>{this.scroller.refresh(),this.items.forEach(e=>{e.refreshScroller()})});m(this,"deleteItem",e=>{if(this.items.length<=1)return super.deleteItem(e);const o=this.findItemIndex(e);let r=null;return o===0?r=this.items[o+1].root.id:r=this.items[o-1].root.id,super.deleteItem(e)?(this.scrollToGroup(r,N8),!0):!1});m(this,"setupGroupItem",e=>{e.on("onSwitchGroup",this.scrollToGroup),e.on("onReachBottom",this.handleReachBottom),e.on("onReachTop",this.handleReachTop),e.refreshScroller()});m(this,"handleReachBottom",()=>{this.emit("onReachBottom")});m(this,"handleReachTop",()=>{this.emit("onReachTop")});m(this,"scrollToGroup",(e,o=0)=>{const r=this.findGroupItem(e);g(B2,r,"invalid scroll target"),this.scroller.scrollToElement(r.root,o,!1,!1),q8(this.editor,r.comment.id)});m(this,"findGroupItem",e=>this.items.find(o=>o.comment.groupId===e));m(this,"handleDocChanged",()=>{this.updateComments()});m(this,"updateComments",He.default(()=>{const e=ts(this.editor,this.commentsProvider);for(let o=0;o<e.length;o++){const r=e[o];if(!this.findGroupItem(r.groupId)){this.handleCreateComment(r,!1);continue}}for(let o=this.items.length-1;o>=0;o--){const r=this.items[o];e.findIndex(i=>i.groupId===r.comment.groupId)===-1&&this.deleteItem(r.comment.id)}},100));this.scroller=new Y5.default(i),this.scroller.disable(),this.editor.addListener("docChanged",this.handleDocChanged),this.items.forEach(this.setupGroupItem)}createItem(e){return new HU(this.editor,this.commentsProvider,e)}insertItem(e){const o=super.insertItem(e);return o?(this.setupGroupItem(o),o):null}findInsertPos(e){const r=ts(this.editor,this.commentsProvider).findIndex(i=>i.id===e.id);return r===-1||r>this.items.length?-1:r}setActiveItem(e){this.scrollToGroup(e)}handleCreateComment(e,o){if(Js(e)){const s=this.findGroupItem(e.groupId);s&&s.childrenList.insertItem(e)}const r=this.findItem(e.id);g(B2,!r,"comment group item has already exists");const i={children:[],...e};g(B2,i.children,"not a comment group"),this.insertItem(i),this.scroller.refresh()}handleDeleteComment(e){for(let o=0;o<this.items.length;o++){const r=this.items[o];if(r.comment.id===e){r.childrenList.items.length===0?this.deleteItem(r.comment.id):r.deleteMainComment(e);return}if(r.childrenList.deleteItem(e)){r.commentCount===0&&this.deleteItem(r.comment.id);return}}}handleUpdateComment(e){if(Js(e)){const r=this.commentsProvider.getComment(e.groupId),i=this.findItem(r.id);i&&i.handleUpdateChildComment(e);return}const o=this.findItem(e.id);o&&o.handleUpdateMainComment(e)}destroy(){this.editor.removeListener("docChanged",this.handleDocChanged),this.scroller.destroy(),this.items.forEach(e=>e.destroy())}}const UU=S("mobile-comment-list"),{t:ey}=R;class zU extends be.TypedEmitter{constructor(e,o){super();m(this,"root");m(this,"list");m(this,"mask");m(this,"pullInfoContainer");m(this,"handleRootClick",e=>{const o=e.target;g(UU,o instanceof Element,"invalid target"),!(o.closest(".mobile-group-item-abstract")||o.closest(".mobile-group-item-list-container"))&&(this.hide(),this.emit("onCommentListClose"))});m(this,"hidePullInfo",He.default(()=>{et(this.pullInfoContainer,"active")},1e3*3));m(this,"handleReachBottom",()=>{this.showPullInfo("bottom")});m(this,"handleReachTop",()=>{this.showPullInfo("top")});m(this,"show",e=>{var o;et(this.root,"hidden"),W(document.documentElement,"disabled-scroll"),(o=this.commentOptions)==null||o.controller.showCommentList(),queueMicrotask(()=>{this.list.refreshScroller(),e&&this.list.setActiveItem(e)})});m(this,"hide",()=>{W(this.root,"hidden"),et(document.documentElement,"disabled-scroll")});this.editor=e,this.commentsProvider=o,this.root=w("div",["editor-mobile-comments-root"],null),this.mask=w("div",["mobile-comment-mask"],this.root);const r=w("div",["mobile-comment-groups-container"],this.root),i=w("div",["mobile-comment-groups-scroll-container"],r);this.list=new jU(this.editor,this.commentsProvider,i,r),this.pullInfoContainer=this.createPullInfo(),this.commentsProvider.addListener(this),this.list.on("onReachBottom",this.handleReachBottom),this.list.on("onReachTop",this.handleReachTop),this.root.onclick=this.handleRootClick}onCreateComment(e,o){const r=this.commentsProvider.getComment(e);this.list.handleCreateComment(r,o)}onDeleteComment(e,o){this.list.handleDeleteComment(e)}onUpdateComment(e,o){const r=this.commentsProvider.getComment(e);this.list.handleUpdateComment(r)}get commentOptions(){return this.editor.getComponentOptions("comment")}createPullInfo(){const e=w("div",["mobile-comment-pull-info-container"],this.root);return w("div",["mobile-comment-pull-info"],e),e}showPullInfo(e){const o=ey(e==="bottom"?"comment.isLast":"comment.isFirst");this.pullInfoContainer.firstElementChild.textContent=o,W(this.pullInfoContainer,"active"),this.hidePullInfo()}destroy(){this.list.removeAllListeners(),this.list.destroy(),this.root.onclick=null}}function ny(n,t){const e=ts(n,t),o=new Map;for(const r of e){const i=H8(n,r.groupId);if(!!i)if(o.has(i)){const s=o.get(i);b2(r).forEach(a=>{s==null||s.commentIds.add(a.id)})}else{const s=b2(r),l=new Set(s.map(a=>a.id));o.set(i,{commentIds:l,firstComment:r})}}return Array.from(o.entries()).map(([r,i])=>({blockId:r,...i}))}const VU=S("mini-group-item");class WU{constructor(t,e){m(this,"root");m(this,"blockId");m(this,"comment");m(this,"miniCommentItem");m(this,"updateCommentItemCount",()=>{this.miniCommentItem.updateCount(this.commentCount)});this.editor=t,this.commentGroup=e,this.root=w("div",["mini-group-item"],null),this.comment=e.firstComment,this.miniCommentItem=new IU(this.comment.id,this.root),this.blockId=this.getBlockId(),this.alignToBlock(),this.updateCommentItemCount()}getBlockId(){return H8(this.editor,this.comment.groupId)}get commentCount(){return this.commentGroup.commentIds.size}alignToBlock(){const t=this.getBlockId(),e=this.editor.getBlockById(t);g(VU,e,`The blockId: ${t} not exist in doc`);const o=this.editor.scrollContainer.getBoundingClientRect(),r=this.editor.scrollContainer.scrollTop,s=e.getBoundingClientRect().top-o.top+r;requestAnimationFrame(()=>{this.root.style.transform=`translateY(${s}px)`})}destroy(){this.root.remove()}}class qU extends _u{constructor(e,o,r){super(e,o,r,ny(e,o),{});m(this,"fixListOps",He.default(()=>{this.items.forEach(e=>{e.alignToBlock()})},100));m(this,"handleDocChanged",He.default(()=>{this.updateMiniCommentsGroup()},100));m(this,"updateMiniCommentsGroup",()=>{const e=ny(this.editor,this.commentsProvider);this.reloadList(e)});this.editor=e,this.commentsProvider=o,this.editor.addListener("docChanged",this.handleDocChanged),this.editor.addListener("resize",this.fixListOps)}createItem(e){return new WU(this.editor,e)}findInsertPos(){return-1}handleCreateComment(e,o){this.updateMiniCommentsGroup()}handleDeleteComment(e){this.updateMiniCommentsGroup()}destroy(){this.editor.removeListener("docChanged",this.handleDocChanged),super.destroy(),this.removeAllListeners()}}const GU=S("mini-comments-list");class ZU extends be.TypedEmitter{constructor(e,o){super();m(this,"list");m(this,"root");m(this,"createList",()=>{const e=w("div",["comment-groups-container"],this.root);return this.editor.domEvents.addEventListener(e,"click",this.handleListContainerClick),new qU(this.editor,this.commentsProvider,e)});m(this,"handleListContainerClick",(e,o)=>{const r=o.target;g(GU,r instanceof HTMLElement,"The target is not a valid html element");const i=r.closest(".mini-comment-item");i&&this.emit("onItemClick",i.id)});this.editor=e,this.commentsProvider=o,this.root=w("div",["editor-mini-comment-root"],null),this.list=this.createList(),this.commentsProvider.addListener(this)}onCreateComment(e,o){const r=this.commentsProvider.getComment(e);this.list.handleCreateComment(r,o)}onDeleteComment(e,o){this.list.handleDeleteComment(e)}onUpdateComment(e,o){}show(){et(this.root,"hidden")}hide(){W(this.root,"hidden")}destroy(){this.list.destroy(),this.removeAllListeners()}}function oy(n,t,e){if(!t.start.isSimple()||!t.end.isSimple())return;const o=t.block,r=ye(n,o,t.start.offset,t.end.offset),i=`comment-${e.id.toLocaleLowerCase()}`,s=e.id;Z6(n,o,r,i,s)}function QU(n,t,e){const o=Lo(n).map(s=>s.block),r=p2(n,o),i=Gf({editor:n,abstract:r});return n.undoManager.runInGroup(()=>{Lo(n,{simpleBlockOnly:!0}).forEach(a=>{!tt(n,a.block)||oy(n,a,i)});const l=jr();e.localCreateComment(i,l)}),i}class YU{constructor(t,e){m(this,"id","CommentsCommandProvider");this.provider=t,this.editorComments=e}getAvailableCommands(t,e,o){const r=t.selection.range;if(tt(t,e)&&!o.isCollapsed()&&r.isSimple()){const i=it(e),s=Dt(e),l=Io(t,e);return[{id:"add-comment",name:R.t("comment.command"),blockId:i,blockType:s,blockKind:l,groupIndex:1e3,icon:eu}]}return[]}executeRangeCommand(t,e,o,r,i){if(o.id==="add-comment"){this.editorComments.showCommentList();const s=QU(t,e,this.provider);return i["add-comment"]=s,!0}return!1}}class ry{constructor(t,e){m(this,"commentList",null);m(this,"mobileCommentList",null);m(this,"miniCommentList");m(this,"showComment",(t,e)=>{var o,r;t==="mini"&&this.miniCommentList.show(),t==="mobile"&&((o=this.mobileCommentList)==null||o.show(e)),t==="web"&&((r=this.commentList)==null||r.show(e))});m(this,"showCommentList",t=>{this.isMobile?this.showComment("mobile",t):this.showComment("web",t)});m(this,"handleCommentListClose",()=>{this.showComment("mini")});m(this,"handleOnSelectComment",()=>{this.showComment("web")});m(this,"handleMiniCommentItemClick",t=>{this.showCommentList(t)});this.editor=t,this.provider=e,t.editorCommandProviders.registerCommandProvider(new YU(e,this)),t.blockHooks.push(new hU(this.provider,this)),this.isMobile?(this.mobileCommentList=new zU(this.editor,this.provider),this.mobileCommentList.on("onCommentListClose",this.handleCommentListClose)):(this.commentList=new PU(this.editor,this.provider),this.commentList.on("onSelectComment",this.handleOnSelectComment)),this.miniCommentList=new ZU(this.editor,this.provider),this.miniCommentList.on("onItemClick",this.handleMiniCommentItemClick),this.editor.input.addHandler(new fU)}get commentProvider(){return this.provider}get isMobile(){return Ke.isMobile}destroy(){var t,e;(t=this.commentList)==null||t.destroy(),(e=this.mobileCommentList)==null||e.destroy(),this.miniCommentList.destroy()}mount(t){var e;t.container&&this.commentList&&t.container.append((e=this.commentList)==null?void 0:e.root),t.miniContainer&&t.miniContainer.append(this.miniCommentList.root),t.mobileContainer&&this.mobileCommentList&&t.mobileContainer.append(this.mobileCommentList.root)}}const Vnt="",JU={comment:{count:"\u6279\u6CE8 ({num})",hide:"\u9690\u85CF\u6279\u6CE8",show:"\u663E\u793A\u6279\u6CE8",reply:"\u56DE\u590D",quicklyReply:"\u56DE\u590D...",send:"\u786E\u8BA4",placeholder:"\u6DFB\u52A0\u6279\u6CE8...",replyPlaceholder:"\u56DE\u590D\u6216@\u4ED6\u4EBA",edit:"\u7F16\u8F91",delete:"\u5220\u9664",image:"\u56FE\u7247",sendTitle:"\u6309Enter\u53D1\u9001\u6279\u6CE8",replyTitle:"\u6309Enter\u56DE\u590D\u6279\u6CE8",isFirst:"\u5DF2\u7ECF\u662F\u7B2C\u4E00\u6761\u6279\u6CE8",isLast:"\u5DF2\u7ECF\u662F\u6700\u540E\u4E00\u6761\u6279\u6CE8",more:"\u66F4\u591A",comment:"\u6279\u6CE8",command:"\u6279\u6CE8",quickMenuCommand:"\u6DFB\u52A0\u6279\u6CE8"}},KU={comment:{count:"Annotations ({num})",hide:"Hide Annotations",show:"Show Annotations",reply:"Reply",quicklyReply:"Reply...",send:"Confirm",placeholder:"Add a annotation...",replyPlaceholder:"Add Annotations or @ others",edit:"Edit",delete:"Delete",image:"Image",sendTitle:"Press Enter to post annotation",replyTitle:"Press Enter to reply to annotation",isFirst:"This is already the first comment",isLast:"This is already the last comment",more:"More",comment:"Annotation",command:"Annotation",quickMenuCommand:"Add annotation"}},XU={comment:{count:"\u30B3\u30E1\u30F3\u30C8 ({num})",hide:"\u30B3\u30E1\u30F3\u30C8\u3092\u975E\u8868\u793A",show:"\u30B3\u30E1\u30F3\u30C8\u3092\u8868\u793A",reply:"\u8FD4\u4FE1",quicklyReply:"\u8FD4\u4FE1...",send:"\u78BA\u8A8D",placeholder:"\u30B3\u30E1\u30F3\u30C8\u3092\u8FFD\u52A0...",replyPlaceholder:"\u8FD4\u4FE1\u307E\u305F\u306F\u30E1\u30F3\u30B7\u30E7\u30F3(@)",edit:"\u7DE8\u96C6",delete:"\u524A\u9664",image:"\u753B\u50CF",sendTitle:"Enter\u3092\u62BC\u3057\u3066\u30B3\u30E1\u30F3\u30C8\u3092\u9001\u4FE1",replyTitle:"Enter\u3092\u62BC\u3057\u3066\u30B3\u30E1\u30F3\u30C8\u3092\u8FD4\u4FE1",isFirst:"\u6700\u521D\u306E\u30B3\u30E1\u30F3\u30C8\u3067\u3059",isLast:"\u6700\u5F8C\u306E\u30B3\u30E1\u30F3\u30C8\u3067\u3059",more:"\u305D\u306E\u4ED6",comment:"\u30B3\u30E1\u30F3\u30C8\u3092",command:"\u30B3\u30E1\u30F3\u30C8\u3092",quickMenuCommand:"\u6CE8\u91C8\u3092\u8FFD\u52A0"}};R.mergeLang({"zh-CN":JU,"en-US":KU,"ja-JP":XU});class iy{renderText(t,e,o){const r=[],i={};return Object.entries(o).forEach(([s,l])=>{s.startsWith("comment-")&&(r.push("comment"),i[s]=l)}),{classes:r,attributes:i}}renderBlock(t,e,o){const r=o.comments;if(!r||r.length===0)return{};const i=["comment"],s={};return r.forEach(l=>{s[`comment-${l.toLocaleLowerCase()}`]=l}),{classes:i,attributes:s}}updateBlock(t,e,o,r){const i=r.comments;et(o,"comment"),Array.from(o.attributes).forEach(s=>{s.name.startsWith("comment-")&&o.removeAttribute(s.name)}),!(!i||i.length===0)&&(W(o,"comment"),i.forEach(s=>{o.setAttribute(`comment-${s.toLocaleLowerCase()}`,s)}))}}class tz{constructor(t){m(this,"handleUpdateCompositionText",(t,e,o,r,i)=>{const s=t.getFocusedBlock(),l=t.getFirstBlock();s===l&&this.applyPlaceholder(t)});m(this,"handleSelectionChange",t=>{this.applyPlaceholder(t)});m(this,"applyPlaceholder",t=>{const e=t.getFirstBlock();If(t,e,R.t("comment.replyPlaceholder"))});this.applyPlaceholder(t),t.addListener("selectionChanged",this.handleSelectionChange)}}function ez(n,t,e){const o=n.getBlockData(t),r=o.comments;if((r==null?void 0:r.indexOf(e))!==-1){const s=new Set(r);s.delete(e),n.updateBlockData(t,{comments:Array.from(s)})}const i=o.text;if(!!i&&tt(n,t)){const s=mg(i,`comment-${e.toLocaleLowerCase()}`,e);ua.default(i,s)||n.setBlockText(t,s)}}const nz=S("editor-comment");function oz(n){const t=n.getCustom("editor-comments");if(g(nz,t,"the editor comment not exist"),t.showCommentList(),n.selection.range.isCollapsed()){const s=n.selection.startBlock,l=Di(s);if(l.length>=2){const{containerId:a}=l.at(-1),d=ot(Nr(n,a));if(d&&Dt(d)==="code"){C2(n,d,t.commentProvider);return}}C2(n,s,t.commentProvider);return}const e=Lo(n,{simpleBlockOnly:!0}),o=e.map(s=>s.block),r=p2(n,o),i=Gf({editor:n,abstract:r});n.undoManager.runInGroup(()=>{e.forEach(l=>{tt(n,l.block)?oy(n,l,i):F8(n,l.block,i)});const s=jr();t.commentProvider.localCreateComment(i,s)})}const E2=S("text-styles");function rz(n){const t=o=>{if(!o.attributes)return new Map;const r=Object.entries(o.attributes).filter(([i])=>!!i.startsWith("style-"));return new Map(r)};if(n.length===0)return new Map;let e=t(n[0]);for(let o=1;o<n.length;o++){const r=t(n[o]);e=new Map(Array.from(e.entries()).filter(([i,s])=>r.get(i)===s))}return e}function iz(n,t,e,o,r){g(E2,e.isSimple(),"invalid range");const{start:i,end:s}=e;g(E2,i.blockId===s.blockId&&i.blockId===it(t),"invalid range"),g(E2,o.startsWith("style-"),"invalid style");let a=n.getBlockText(t);return o==="style-sub"?a=ql(i.offset,s.offset-i.offset,a,"style-super",r,{ignoreValue:!0}):o==="style-super"&&(a=ql(i.offset,s.offset-i.offset,a,"style-sub",r,{ignoreValue:!0})),r===!1||r===void 0||r===null?a=ql(i.offset,s.offset-i.offset,a,o,void 0,{ignoreValue:!0}):a=Ia(i.offset,s.offset-i.offset,a,o,r),n.setBlockText(t,a),a}const sz=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
482
+ </svg>`,znt="",Zf="reply-editor-editing",{t:w2}=R;class LU{constructor(t,e,o,r){m(this,"root");m(this,"components");m(this,"handleFocus",()=>{const{replyEditor:t,okButton:e}=this.components;t.isEmpty()&&W(e,Kr)});m(this,"handleDocChange",()=>{const{replyEditor:t,okButton:e}=this.components,o=t.getDoc();Ag(o)?W(e,Kr):et(e,Kr)});m(this,"getReplyEditor",()=>this.components.replyEditor);m(this,"showReplyEditor",()=>{xt(this.root,Zf)||(W(this.root,Zf),this.components.replyEditor.edit())});m(this,"hideReplyEditor",()=>{!xt(this.root,Zf)||et(this.root,Zf)});m(this,"reply",()=>{const{mainEditor:t,comment:e,components:{replyEditor:o},commentsProvider:r}=this,i=o.getDoc(),s=Gf({editor:t,commentGroupId:e.groupId});r.localCreateComment(s,i),this.hideReplyEditor(),o.clear()});m(this,"cancel",()=>{const{replyEditor:t}=this.components;this.hideReplyEditor(),t.clear()});m(this,"hide",()=>{xt(this.root,"hidden")||W(this.root,"hidden")});m(this,"show",()=>{et(this.root,"hidden")});this.mainEditor=t,this.commentsProvider=e,this.comment=o,this.groupItem=r,this.root=w("div",["comment-quick-reply"],null),this.components=this.createQuickReply()}createQuickReply(){const{commentsProvider:t}=this,e=Qs(this.root,Yt.QuickReply,w2("comment.placeholder"));Xr(e,Yt.QuickReply),e.classList.add("quick-reply-button");const o=w("div",["quick-reply-editor"],this.root),r=jr(),i=new k2(this.mainEditor,t,r);i.editor.addListener("docChanged",this.handleDocChange),i.editor.addListener("focus",this.handleFocus),i.editor.input.addHandler(new wU(this.groupItem)),o.append(i.root);const s=w("div",["reply-editor-actions"],o),l=ji(Yt.QuickReplyCancel,w2("common.cancel"));Xr(l,Yt.QuickReplyCancel);const a=ji(Yt.QuickReplyOk,w2("comment.send"));return Xr(a,Yt.QuickReplyOk),W(a,Kr),s.append(l,a),this.hideReplyEditor(),{replyTextButton:e,replyEditor:i,replyEditorContainer:o,okButton:a}}}const ti=S("comment-group-item");class MU extends be.TypedEmitter{constructor(e,o,r,i){super();m(this,"root");m(this,"header");m(this,"mainItem");m(this,"childrenList");m(this,"resizeObserver");m(this,"quickReply");m(this,"createRoot",()=>w("div",["comment-group-item-root"],null));m(this,"createChildrenList",()=>{const e=w("div",["comment-children-list-container"],this.root);return new TU({editor:this.editor,commentsProvider:this.commentsProvider,comments:this.comment.children,parent:e,groupList:this.groupList,groupItem:this})});m(this,"updateLastCommentItem",()=>{const e=Array.from(this.root.querySelectorAll(":scope .comment-item-root"));g(ti,e.length!==0,"current group item not exist comment-item"),e.forEach(r=>{et(r,P8)});const o=e.at(-1);W(o,P8)});m(this,"updateSwitchButton",()=>{const e=this.root.querySelector(':scope .editor-text-button[group-item-action="switch-up"]'),o=this.root.querySelector(':scope .editor-text-button[group-item-action="switch-down"]');g(ti,e,"switchUpButton not exist"),g(ti,o,"switchDownButton not exist"),et(o,"disabled"),et(e,"disabled"),this.root.previousElementSibling===null&&W(e,"disabled"),this.root.nextElementSibling===null&&W(o,"disabled")});m(this,"handleReadonlyChanged",e=>{e.readonly?W(this.root,"readonly"):et(this.root,"readonly")});m(this,"handleResize",()=>{this.emit("resize")});this.editor=e,this.commentsProvider=o,this.comment=r,this.groupList=i,this.root=this.createRoot(),this.header=this.createHeader(),this.mainItem=this.createItem(),this.childrenList=this.createChildrenList(),this.quickReply=this.createQuickReply(),this.editor.on("readonlyChanged",this.handleReadonlyChanged),this.resizeObserver=new ResizeObserver(this.handleResize),this.resizeObserver.observe(this.root),this.updateLastCommentItem()}get commentCount(){return $8(this.root)}createQuickReply(){const{editor:e,commentsProvider:o,comment:r}=this,i=new LU(e,o,r,this);return this.root.append(i.root),i}createHeader(){const{comment:e}=this,o=w("div",["comment-item-head"],this.root),r=w("span",["item-head-quote"],o);r.innerText=e.abstract;const i=w("span",["item-head-switch"],o),s=Qs(i,Yt.SwitchUp,"up",DU),l=Qs(i,Yt.SwitchDown,"down",SU);return Xr(s,Yt.SwitchUp),Xr(l,Yt.SwitchDown),o}createItem(){const e=w("div",["comment-item-container"],this.root),{editor:o,commentsProvider:r,comment:i,groupList:s}=this,l=new Q8({mainEditor:o,commentsProvider:r,comment:i,groupList:s,groupItem:this});return e.appendChild(l.root),l}findCommentItem(e){return e?e===this.mainItem.comment.id?this.mainItem:this.childrenList.items.find(o=>o.comment.id===e):null}handleCreateComment(e){return g(ti,Js(e),"invalid comment, not a child comment"),g(ti,e.groupId===this.comment.id,"invalid comment, not a child comment"),this.childrenList.createItem(e)}handleUpdateChildComment(e){g(ti,e.groupId===this.mainItem.comment.id,"invalid child comment");const o=this.childrenList.findItem(e.id);if(!o){ti.error(`can't find child comment item: ${e.id}`);return}o.reloadDoc()}handleUpdateMainComment(e){g(ti,e.id===this.mainItem.comment.id,"invalid comment"),this.mainItem.reloadDoc()}deleteMainComment(e){g(ti,e===this.mainItem.comment.id,"invalid comment"),this.mainItem.destroy()}edit(){this.mainItem.edit()}destroy(){this.mainItem.destroy(),this.childrenList.destroy(),this.root.remove(),this.resizeObserver.disconnect(),this.removeAllListeners(),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged)}}const RU=S("arrange=items"),J8=20;function K8(n,t){const e=n.rootContainer.querySelector(`[comment-${t.toLocaleLowerCase()}=${t}`);if(!e)return-1;const o=n.scrollContainer.getBoundingClientRect(),r=n.scrollContainer.scrollTop;return e.getBoundingClientRect().top-o.top+r}function X8(n,t){return Number.parseInt(t.root.style.top,10)}function ty(n,t,e,o){let r=0;e&&(r=t.indexOf(e),r===-1&&(r=0));for(let i=r;i<t.length;i++){const s=t[i],l=s.comment,a=K8(n,l.groupId);if(s.root.setAttribute("data-target-top",a.toString()),i===r){if(o!==void 0){const p=t[0];p.root.style.top=`${o}px`}else s.root.style.top=`${a}px`;continue}const d=t[i-1],h=X8(n,d)+d.root.getBoundingClientRect().height;h>a?s.root.style.top=`${h+J8}px`:s.root.style.top=`${a}px`}for(let i=r-1;i>=0;i--){const s=t[i],l=s.comment,a=K8(n,l.groupId);s.root.setAttribute("data-target-top",a.toString());const d=s.root.getBoundingClientRect(),h=a+d.height,p=t[i+1];g(RU,p,"no next item");const A=X8(n,p);A<h?s.root.style.top=`${A-d.height-J8}px`:s.root.style.top=`${a}px`}setTimeout(()=>{n.scrollContainer.dispatchEvent(new Event("scroll"))},350)}const Qf=S("comment-group-item-handler");class OU{constructor(t,e){m(this,"handleSwitchUp",t=>{const e=Math.max(0,t-1);this.groupList.setActiveItem(e),this.groupList.updateItemsLayout()});m(this,"handleSwitchDown",t=>{const e=Math.min(t+1,this.groupList.items.length);this.groupList.setActiveItem(e),this.groupList.updateItemsLayout()});m(this,"handleQuickReply",t=>{const{quickReply:e}=t;e.showReplyEditor()});m(this,"handleQuickReplyOk",t=>{const{quickReply:e}=t;e.reply(),t.updateLastCommentItem()});m(this,"handleQuickReplyCancel",t=>{const{quickReply:e}=t;e.cancel()});m(this,"handleCommentItemReply",(t,e)=>{const o=t.findCommentItem(e);g(Qf,o,`the commentItem: ${e} not exist `);const{quickReply:r}=t;r.show(),r.showReplyEditor();const{comment:i}=o,s=r.getReplyEditor(),l=s.editor.getFocusedBlock(),a={type:"mention",id:K(),box:!0,created:Date.now(),text:i.displayName,iconUrl:i.avatarUrl,mentionId:i.userId};s.editor.insertBoxToBlock(l,0,a)});m(this,"handleCommentItemMore",t=>{const{quickReply:e}=t;e.hideReplyEditor(),e.getReplyEditor().clear()});m(this,"handleCommentItemOk",(t,e)=>{const o=t.findCommentItem(e);g(Qf,o,`the commentItem: ${e} not exist `);const{quickReply:r}=t,{comment:i,getCommentEditor:s}=o,l=s(),a=l.getDoc();this.commentsProvider.localUpdateComment(i,a),l.readonly(),r.show()});m(this,"handleCommentItemCancel",(t,e)=>{var a,d;const o=t.findCommentItem(e);g(Qf,o,`the commentItem: ${e} not exist `);const r=this.commentsProvider.getComment(o.comment.id);let i=!1;if((a=r.blocks)!=null&&a.length||(i=!0),((d=r.blocks)==null?void 0:d.length)===1){const h=r.blocks[0];i=!!h.text&&rn(h.text)===0}if(i){this.commentsProvider.localDeleteComment(o.comment.id);return}const{quickReply:s}=t,l=o.getCommentEditor();l.setDoc(o.doc),l.readonly(),s.show()});m(this,"handleCommentItemEdit",t=>{const e=this.groupList.findItem(t.comment.groupId);if(!e)return;const{quickReply:o}=e;t.getCommentEditor().edit(),o.hide()});m(this,"handleCommentItemDelete",t=>{const e=this.groupList.findItem(t.comment.groupId);if(!e)return;const{quickReply:o}=e,{comment:r}=t;this.commentsProvider.localDeleteComment(r.id),o.show()});m(this,"execute",(t,e,o,r)=>{const i=gU(t);if(!i||CU(i))return;const s=pU(i);switch(s){case Yt.SwitchUp:this.handleSwitchUp(r);break;case Yt.SwitchDown:this.handleSwitchDown(r);break;case Yt.CommentItemReply:this.handleCommentItemReply(e,o);break;case Yt.CommentItemMore:this.handleCommentItemMore(e);break;case Yt.CommentItemOk:this.handleCommentItemOk(e,o);break;case Yt.CommentItemCancel:this.handleCommentItemCancel(e,o);break;case Yt.CommentItemDelete:break;case Yt.CommentItemEdit:break;case Yt.QuickReply:this.handleQuickReply(e);break;case Yt.QuickReplyOk:this.handleQuickReplyOk(e);break;case Yt.QuickReplyCancel:this.handleQuickReplyCancel(e);break;default:const l=s;Qf.debug(`not implement handler for ${l}`)}});this.groupList=t,this.commentsProvider=e}destroy(){}}const Yf=S("comment-group-list");class _U extends _u{constructor(e,o,r){super(e,o,r,ts(e,o),{});m(this,"groupItemHandlers");m(this,"findGroupItem",e=>this.items.find(o=>o.comment.groupId===e));m(this,"handleContainerClick",e=>{if(!e.target||!(e.target instanceof Element))return;const o=e.target.closest(".comment-group-item-root");if(!o)return;const r=mU(e.target),i=this.items.findIndex(s=>s.root===o);if(i!==-1){this.setActiveItem(i);const{groupItemHandlers:s}=this;s.execute(e.target,this.items.at(i),r,i)}});m(this,"handleSelectionChanged",()=>{var o;const e=V8(this.editor);if(e.length>0){if(((o=this.activeItem)==null?void 0:o.comment.id)&&e.includes(this.activeItem.comment.id))return;const r=e[0],i=this.items.findIndex(s=>s.comment.groupId===r);this.setActiveItem(i),this.emit("selectionOnComment")}else this.setActiveItem(-1)});m(this,"handleEditorResize",()=>{this.updateItemsLayout()});m(this,"handleDocChanged",()=>{this.updateComments()});m(this,"handleItemResize",()=>{this.updateItemsLayout()});m(this,"handleScroll",e=>{if(e.deltaY>=0||this.editor.scrollContainer.scrollTop!==0)return;const o=document.elementFromPoint(e.clientX,e.clientY);if(!o||!(o instanceof HTMLElement)||!this.editor.scrollContainer.contains(o))return;const r=this.container.querySelector(".comment-group-item-root");if(!r)return;const i=Number.parseFloat(r.style.top),s=Number.parseFloat(r.getAttribute("data-target-top")||"0");!Number.isNaN(i)&&!Number.isNaN(s)&&i<s&&ty(this.editor,this.items,null,Math.min(i+(0-e.deltaY)*3,s))});m(this,"updateGroupItemSwitch",()=>{const e=this.activeItem;g(Yf,e,"invalid activeItem"),e.updateSwitchButton()});m(this,"updateComments",He.default(()=>{const e=ts(this.editor,this.commentsProvider);let o=!1;for(let r=0;r<e.length;r++){const i=e[r];if(!this.findGroupItem(i.groupId)){this.handleCreateComment(i,!1),o=!0;continue}}for(let r=this.items.length-1;r>=0;r--){const i=this.items[r];e.findIndex(s=>s.groupId===i.comment.groupId)===-1&&(this.deleteItem(i.comment.id),o=!0)}o&&(this.updateItemsLayout(),this.emit("commentCountChanged"))},100));this.updateItemsLayout(),this.bindEvents(),this.editor.addListener("selectionChanged",this.handleSelectionChanged),this.editor.addListener("resize",this.handleEditorResize),this.editor.addListener("docChanged",this.handleDocChanged),this.editor.scrollContainer.addEventListener("wheel",this.handleScroll,{passive:!1}),this.items.forEach(i=>i.addListener("resize",this.handleItemResize)),this.groupItemHandlers=new OU(this,o)}destroy(){this.editor.removeListener("selectionChanged",this.handleSelectionChanged),this.editor.removeListener("resize",this.handleEditorResize),this.editor.removeListener("docChanged",this.handleDocChanged),this.editor.scrollContainer.removeEventListener("wheel",this.handleScroll),super.destroy(),this.unbindEvents(),this.removeAllListeners()}updateItemsLayout(){ty(this.editor,this.items,this.activeItem)}bindEvents(){this.container.addEventListener("click",this.handleContainerClick)}unbindEvents(){this.container.removeEventListener("click",this.handleContainerClick)}createItem(e,o){const r=new MU(this.editor,this.commentsProvider,e,this);return o==="insert"&&(W(r.root,"no-animation"),r.root.style.opacity="0",setTimeout(()=>{et(r.root,"no-animation"),r.root.style.opacity="1"},150)),r}findInsertPos(e){const r=ts(this.editor,this.commentsProvider).findIndex(i=>i.id===e.id);return r===-1||r>this.items.length?-1:r}insertItem(e,o){const r=super.insertItem(e);return r?(o!=null&&o.active&&this.setActiveItem(this.items.indexOf(r)),this.updateItemsLayout(),r.addListener("resize",this.handleItemResize),r):null}setActiveItem(e){if(g(Yf,e>=-1&&e<this.items.length,`invalid index: ${e}`),e===this.activeIndex)return;const o=this.container.querySelector(".comment-group-item-root.active");if(o&&et(o,"active"),e!==-1){const r=this.items[e];W(r.root,"active"),this.updateItemsLayout(),this.updateGroupItemSwitch()}this.emit("activeItemChanged",e)}get activeIndex(){const e=this.container.querySelector(".comment-group-item-root.active");return e?this.items.findIndex(o=>o.root===e):-1}get activeItem(){const e=this.activeIndex;return e===-1?null:this.items[e]}handleCreateComment(e,o){if(Js(e)){const l=this.findGroupItem(e.groupId);l&&l.childrenList.insertItem(e)}const r=this.findItem(e.id);g(Yf,!r,"comment group item has already exists");const i={children:[],...e};g(Yf,i.children,"not a comment group");const s=this.insertItem(i,{active:o});!s||o&&setTimeout(()=>{const l=this.items.indexOf(s);this.setActiveItem(l),s.edit(),s.quickReply.hide()})}handleDeleteComment(e){for(let o=0;o<this.items.length;o++){const r=this.items[o];if(r.comment.id===e){r.childrenList.items.length===0?(this.deleteItem(r.comment.id),this.updateItemsLayout()):r.deleteMainComment(e);return}if(r.childrenList.deleteItem(e)){r.commentCount===0&&(this.deleteItem(r.comment.id),this.updateItemsLayout());return}}}handleUpdateComment(e){if(Js(e)){const r=this.commentsProvider.getComment(e.groupId),i=this.findItem(r.id);i&&i.handleUpdateChildComment(e);return}const o=this.findItem(e.id);o&&o.handleUpdateMainComment(e)}}const FU="comment-mini";S("comment-list");class PU extends be.TypedEmitter{constructor(e,o){super();m(this,"root");m(this,"groupsContainer");m(this,"list");m(this,"handleSelectionOnComment",()=>{this.emit("onSelectComment")});m(this,"updateCommentCount",()=>{var o,r;const e=vU(this.editor,this.commentsProvider);(r=(o=this.commentOptions)==null?void 0:o.onCommentCountChange)==null||r.call(o,e)});m(this,"handleActiveItemChanged",()=>{var o;const e=this.list.activeItem;q8(this.editor,(o=e==null?void 0:e.comment.id)!=null?o:"")});m(this,"handleItemLayoutUpdated",()=>{var o,r;const e=xt(this.root,FU);(r=(o=this.commentOptions)==null?void 0:o.onUpdateLayout)==null||r.call(o,this.editor,{expand:e})});this.editor=e,this.commentsProvider=o,this.root=w("div",["editor-web-comment-root"],null),this.groupsContainer=w("div",["comment-groups-container"],this.root),this.list=this.createList(),this.commentsProvider.addListener(this),this.list.addListener("activeItemChanged",this.handleActiveItemChanged),this.list.addListener("itemLayoutUpdated",this.handleItemLayoutUpdated),this.list.addListener("selectionOnComment",this.handleSelectionOnComment),this.list.addListener("commentCountChanged",this.updateCommentCount),this.updateCommentCount()}get commentOptions(){return this.editor.getComponentOptions("comment")}destroy(){this.list.removeAllListeners(),this.commentsProvider.removeListener(this),this.list.destroy(),this.root.remove()}onCreateComment(e,o){const r=this.commentsProvider.getComment(e);this.list.handleCreateComment(r,o),this.updateCommentCount()}onDeleteComment(e,o){this.list.handleDeleteComment(e),this.updateCommentCount()}onUpdateComment(e,o){const r=this.commentsProvider.getComment(e);this.list.handleUpdateComment(r)}createList(){return new _U(this.editor,this.commentsProvider,this.groupsContainer)}show(e){var o;if(et(this.root,"hidden"),e){const r=this.list.findItemIndex(e);this.list.setActiveItem(r)}(o=this.commentOptions)==null||o.controller.showCommentList()}hide(){W(this.root,"hidden")}}class NU extends _u{constructor({editor:t,parent:e,commentsProvider:o,comments:r}){super(t,o,e,r,{})}findInsertPos(){return this.items.length}createItem(t){const{editor:e,commentsProvider:o}=this;return new Y8(e,o,t)}destroy(){this.items.forEach(t=>{t.destroy()})}}const Jf=S("mobile-comment-group-item"),$U=20;class HU extends be.TypedEmitter{constructor(e,o,r){super();m(this,"root");m(this,"childrenList");m(this,"mainItem");m(this,"scroller");m(this,"createRoot",()=>w("div",["mobile-group-item-root"],null));m(this,"createMainItem",e=>{const{editor:o,commentsProvider:r,comment:i}=this,s=new Y8(o,r,i);return e.append(s.root),s});m(this,"createChildrenList",e=>{const{editor:o,commentsProvider:r,comment:i}=this,s=w("div",["mobile-comment-children-list-container"],e);return new NU({editor:o,commentsProvider:r,comments:i.children,parent:s})});m(this,"handleTouchEnd",()=>{var i;const{scroller:e}=this,{pullThreshold:o=$U}=(i=this.editor.getComponentOptions("comment"))!=null?i:{};let r=null;if(e.y>e.minScrollY+o?(r=this.root.previousElementSibling,r||this.emit("onReachTop")):e.y<e.maxScrollY-o&&(r=this.root.nextElementSibling,r||this.emit("onReachBottom")),r){const s=r.id;this.emit("onSwitchGroup",s,N8)}});m(this,"refreshScroller",()=>{this.scroller.refresh()});this.editor=e,this.commentsProvider=o,this.comment=r,this.root=w("div",["mobile-group-item-root"],null),this.root.id=r.groupId;const i=w("div",["mobile-group-item"],this.root),s=w("div",["mobile-group-item-space"],null),l=w("div",["mobile-group-item-abstract"],null);l.textContent=r.abstract;const a=w("div",["mobile-group-item-list-container"],null);this.mainItem=this.createMainItem(a),this.childrenList=this.createChildrenList(a),i.append(s,l,a),this.scroller=new Y5.default(this.root,{stopPropagation:!0,click:!0}),this.scroller.on("touchEnd",this.handleTouchEnd)}get commentCount(){return $8(this.root,".mobile-group-item")}handleUpdateChildComment(e){g(Jf,e.groupId===this.mainItem.comment.id,"invalid child comment");const o=this.childrenList.findItem(e.id);if(!o){Jf.error(`can't find child comment item: ${e.id}`);return}o.reloadDoc()}handleUpdateMainComment(e){g(Jf,e.id===this.mainItem.comment.id,"invalid comment"),this.mainItem.reloadDoc()}deleteMainComment(e){g(Jf,e===this.mainItem.comment.id,"invalid comment"),this.mainItem.destroy()}destroy(){this.mainItem.destroy(),this.childrenList.destroy(),this.scroller.off("touchEnd",this.handleTouchEnd),this.scroller.destroy(),this.root.remove(),this.removeAllListeners()}}const B2=S("mobile-group-list");class jU extends _u{constructor(e,o,r,i){super(e,o,r,ts(e,o),{});m(this,"scroller");m(this,"refreshScroller",()=>{this.scroller.refresh(),this.items.forEach(e=>{e.refreshScroller()})});m(this,"deleteItem",e=>{if(this.items.length<=1)return super.deleteItem(e);const o=this.findItemIndex(e);let r=null;return o===0?r=this.items[o+1].root.id:r=this.items[o-1].root.id,super.deleteItem(e)?(this.scrollToGroup(r,N8),!0):!1});m(this,"setupGroupItem",e=>{e.on("onSwitchGroup",this.scrollToGroup),e.on("onReachBottom",this.handleReachBottom),e.on("onReachTop",this.handleReachTop),e.refreshScroller()});m(this,"handleReachBottom",()=>{this.emit("onReachBottom")});m(this,"handleReachTop",()=>{this.emit("onReachTop")});m(this,"scrollToGroup",(e,o=0)=>{const r=this.findGroupItem(e);g(B2,r,"invalid scroll target"),this.scroller.scrollToElement(r.root,o,!1,!1),q8(this.editor,r.comment.id)});m(this,"findGroupItem",e=>this.items.find(o=>o.comment.groupId===e));m(this,"handleDocChanged",()=>{this.updateComments()});m(this,"updateComments",He.default(()=>{const e=ts(this.editor,this.commentsProvider);for(let o=0;o<e.length;o++){const r=e[o];if(!this.findGroupItem(r.groupId)){this.handleCreateComment(r,!1);continue}}for(let o=this.items.length-1;o>=0;o--){const r=this.items[o];e.findIndex(i=>i.groupId===r.comment.groupId)===-1&&this.deleteItem(r.comment.id)}},100));this.scroller=new Y5.default(i),this.scroller.disable(),this.editor.addListener("docChanged",this.handleDocChanged),this.items.forEach(this.setupGroupItem)}createItem(e){return new HU(this.editor,this.commentsProvider,e)}insertItem(e){const o=super.insertItem(e);return o?(this.setupGroupItem(o),o):null}findInsertPos(e){const r=ts(this.editor,this.commentsProvider).findIndex(i=>i.id===e.id);return r===-1||r>this.items.length?-1:r}setActiveItem(e){this.scrollToGroup(e)}handleCreateComment(e,o){if(Js(e)){const s=this.findGroupItem(e.groupId);s&&s.childrenList.insertItem(e)}const r=this.findItem(e.id);g(B2,!r,"comment group item has already exists");const i={children:[],...e};g(B2,i.children,"not a comment group"),this.insertItem(i),this.scroller.refresh()}handleDeleteComment(e){for(let o=0;o<this.items.length;o++){const r=this.items[o];if(r.comment.id===e){r.childrenList.items.length===0?this.deleteItem(r.comment.id):r.deleteMainComment(e);return}if(r.childrenList.deleteItem(e)){r.commentCount===0&&this.deleteItem(r.comment.id);return}}}handleUpdateComment(e){if(Js(e)){const r=this.commentsProvider.getComment(e.groupId),i=this.findItem(r.id);i&&i.handleUpdateChildComment(e);return}const o=this.findItem(e.id);o&&o.handleUpdateMainComment(e)}destroy(){this.editor.removeListener("docChanged",this.handleDocChanged),this.scroller.destroy(),this.items.forEach(e=>e.destroy())}}const UU=S("mobile-comment-list"),{t:ey}=R;class zU extends be.TypedEmitter{constructor(e,o){super();m(this,"root");m(this,"list");m(this,"mask");m(this,"pullInfoContainer");m(this,"handleRootClick",e=>{const o=e.target;g(UU,o instanceof Element,"invalid target"),!(o.closest(".mobile-group-item-abstract")||o.closest(".mobile-group-item-list-container"))&&(this.hide(),this.emit("onCommentListClose"))});m(this,"hidePullInfo",He.default(()=>{et(this.pullInfoContainer,"active")},1e3*3));m(this,"handleReachBottom",()=>{this.showPullInfo("bottom")});m(this,"handleReachTop",()=>{this.showPullInfo("top")});m(this,"show",e=>{var o;et(this.root,"hidden"),W(document.documentElement,"disabled-scroll"),(o=this.commentOptions)==null||o.controller.showCommentList(),queueMicrotask(()=>{this.list.refreshScroller(),e&&this.list.setActiveItem(e)})});m(this,"hide",()=>{W(this.root,"hidden"),et(document.documentElement,"disabled-scroll")});this.editor=e,this.commentsProvider=o,this.root=w("div",["editor-mobile-comments-root"],null),this.mask=w("div",["mobile-comment-mask"],this.root);const r=w("div",["mobile-comment-groups-container"],this.root),i=w("div",["mobile-comment-groups-scroll-container"],r);this.list=new jU(this.editor,this.commentsProvider,i,r),this.pullInfoContainer=this.createPullInfo(),this.commentsProvider.addListener(this),this.list.on("onReachBottom",this.handleReachBottom),this.list.on("onReachTop",this.handleReachTop),this.root.onclick=this.handleRootClick}onCreateComment(e,o){const r=this.commentsProvider.getComment(e);this.list.handleCreateComment(r,o)}onDeleteComment(e,o){this.list.handleDeleteComment(e)}onUpdateComment(e,o){const r=this.commentsProvider.getComment(e);this.list.handleUpdateComment(r)}get commentOptions(){return this.editor.getComponentOptions("comment")}createPullInfo(){const e=w("div",["mobile-comment-pull-info-container"],this.root);return w("div",["mobile-comment-pull-info"],e),e}showPullInfo(e){const o=ey(e==="bottom"?"comment.isLast":"comment.isFirst");this.pullInfoContainer.firstElementChild.textContent=o,W(this.pullInfoContainer,"active"),this.hidePullInfo()}destroy(){this.list.removeAllListeners(),this.list.destroy(),this.root.onclick=null}}function ny(n,t){const e=ts(n,t),o=new Map;for(const r of e){const i=H8(n,r.groupId);if(!!i)if(o.has(i)){const s=o.get(i);b2(r).forEach(a=>{s==null||s.commentIds.add(a.id)})}else{const s=b2(r),l=new Set(s.map(a=>a.id));o.set(i,{commentIds:l,firstComment:r})}}return Array.from(o.entries()).map(([r,i])=>({blockId:r,...i}))}const VU=S("mini-group-item");class WU{constructor(t,e){m(this,"root");m(this,"blockId");m(this,"comment");m(this,"miniCommentItem");m(this,"updateCommentItemCount",()=>{this.miniCommentItem.updateCount(this.commentCount)});this.editor=t,this.commentGroup=e,this.root=w("div",["mini-group-item"],null),this.comment=e.firstComment,this.miniCommentItem=new IU(this.comment.id,this.root),this.blockId=this.getBlockId(),this.alignToBlock(),this.updateCommentItemCount()}getBlockId(){return H8(this.editor,this.comment.groupId)}get commentCount(){return this.commentGroup.commentIds.size}alignToBlock(){const t=this.getBlockId(),e=this.editor.getBlockById(t);g(VU,e,`The blockId: ${t} not exist in doc`);const o=this.editor.scrollContainer.getBoundingClientRect(),r=this.editor.scrollContainer.scrollTop,s=e.getBoundingClientRect().top-o.top+r;requestAnimationFrame(()=>{this.root.style.transform=`translateY(${s}px)`})}destroy(){this.root.remove()}}class qU extends _u{constructor(e,o,r){super(e,o,r,ny(e,o),{});m(this,"fixListOps",He.default(()=>{this.items.forEach(e=>{e.alignToBlock()})},100));m(this,"handleDocChanged",He.default(()=>{this.updateMiniCommentsGroup()},100));m(this,"updateMiniCommentsGroup",()=>{const e=ny(this.editor,this.commentsProvider);this.reloadList(e)});this.editor=e,this.commentsProvider=o,this.editor.addListener("docChanged",this.handleDocChanged),this.editor.addListener("resize",this.fixListOps)}createItem(e){return new WU(this.editor,e)}findInsertPos(){return-1}handleCreateComment(e,o){this.updateMiniCommentsGroup()}handleDeleteComment(e){this.updateMiniCommentsGroup()}destroy(){this.editor.removeListener("docChanged",this.handleDocChanged),super.destroy(),this.removeAllListeners()}}const GU=S("mini-comments-list");class ZU extends be.TypedEmitter{constructor(e,o){super();m(this,"list");m(this,"root");m(this,"createList",()=>{const e=w("div",["comment-groups-container"],this.root);return this.editor.domEvents.addEventListener(e,"click",this.handleListContainerClick),new qU(this.editor,this.commentsProvider,e)});m(this,"handleListContainerClick",(e,o)=>{const r=o.target;g(GU,r instanceof HTMLElement,"The target is not a valid html element");const i=r.closest(".mini-comment-item");i&&this.emit("onItemClick",i.id)});this.editor=e,this.commentsProvider=o,this.root=w("div",["editor-mini-comment-root"],null),this.list=this.createList(),this.commentsProvider.addListener(this)}onCreateComment(e,o){const r=this.commentsProvider.getComment(e);this.list.handleCreateComment(r,o)}onDeleteComment(e,o){this.list.handleDeleteComment(e)}onUpdateComment(e,o){}show(){et(this.root,"hidden")}hide(){W(this.root,"hidden")}destroy(){this.list.destroy(),this.removeAllListeners()}}function oy(n,t,e){if(!t.start.isSimple()||!t.end.isSimple())return;const o=t.block,r=ye(n,o,t.start.offset,t.end.offset),i=`comment-${e.id.toLocaleLowerCase()}`,s=e.id;Z6(n,o,r,i,s)}function QU(n,t,e){const o=Lo(n).map(s=>s.block),r=p2(n,o),i=Gf({editor:n,abstract:r});return n.undoManager.runInGroup(()=>{Lo(n,{simpleBlockOnly:!0}).forEach(a=>{!tt(n,a.block)||oy(n,a,i)});const l=jr();e.localCreateComment(i,l)}),i}class YU{constructor(t,e){m(this,"id","CommentsCommandProvider");this.provider=t,this.editorComments=e}getAvailableCommands(t,e,o){const r=t.selection.range;if(tt(t,e)&&!o.isCollapsed()&&r.isSimple()){const i=it(e),s=Dt(e),l=Io(t,e);return[{id:"add-comment",name:R.t("comment.command"),blockId:i,blockType:s,blockKind:l,groupIndex:1e3,icon:eu}]}return[]}executeRangeCommand(t,e,o,r,i){if(o.id==="add-comment"){this.editorComments.showCommentList();const s=QU(t,e,this.provider);return i["add-comment"]=s,!0}return!1}}class ry{constructor(t,e){m(this,"commentList",null);m(this,"mobileCommentList",null);m(this,"miniCommentList");m(this,"showComment",(t,e)=>{var o,r;t==="mini"&&this.miniCommentList.show(),t==="mobile"&&((o=this.mobileCommentList)==null||o.show(e)),t==="web"&&((r=this.commentList)==null||r.show(e))});m(this,"showCommentList",t=>{this.isMobile?this.showComment("mobile",t):this.showComment("web",t)});m(this,"handleCommentListClose",()=>{this.showComment("mini")});m(this,"handleOnSelectComment",()=>{this.showComment("web")});m(this,"handleMiniCommentItemClick",t=>{this.showCommentList(t)});this.editor=t,this.provider=e,t.editorCommandProviders.registerCommandProvider(new YU(e,this)),t.blockHooks.push(new hU(this.provider,this)),this.isMobile?(this.mobileCommentList=new zU(this.editor,this.provider),this.mobileCommentList.on("onCommentListClose",this.handleCommentListClose)):(this.commentList=new PU(this.editor,this.provider),this.commentList.on("onSelectComment",this.handleOnSelectComment)),this.miniCommentList=new ZU(this.editor,this.provider),this.miniCommentList.on("onItemClick",this.handleMiniCommentItemClick),this.editor.input.addHandler(new fU)}get commentProvider(){return this.provider}get isMobile(){return Ke.isMobile}destroy(){var t,e;(t=this.commentList)==null||t.destroy(),(e=this.mobileCommentList)==null||e.destroy(),this.miniCommentList.destroy()}mount(t){var e;t.container&&this.commentList&&t.container.append((e=this.commentList)==null?void 0:e.root),t.miniContainer&&t.miniContainer.append(this.miniCommentList.root),t.mobileContainer&&this.mobileCommentList&&t.mobileContainer.append(this.mobileCommentList.root)}}const Vnt="",JU={comment:{count:"\u6279\u6CE8 ({num})",hide:"\u9690\u85CF\u6279\u6CE8",show:"\u663E\u793A\u6279\u6CE8",reply:"\u56DE\u590D",quicklyReply:"\u56DE\u590D...",send:"\u786E\u8BA4",placeholder:"\u6DFB\u52A0\u6279\u6CE8...",replyPlaceholder:"\u56DE\u590D\u6216@\u4ED6\u4EBA",edit:"\u7F16\u8F91",delete:"\u5220\u9664",image:"\u56FE\u7247",sendTitle:"\u6309Enter\u53D1\u9001\u6279\u6CE8",replyTitle:"\u6309Enter\u56DE\u590D\u6279\u6CE8",isFirst:"\u5DF2\u7ECF\u662F\u7B2C\u4E00\u6761\u6279\u6CE8",isLast:"\u5DF2\u7ECF\u662F\u6700\u540E\u4E00\u6761\u6279\u6CE8",more:"\u66F4\u591A",comment:"\u6279\u6CE8",command:"\u6279\u6CE8",quickMenuCommand:"\u6DFB\u52A0\u6279\u6CE8"}},KU={comment:{count:"Annotations ({num})",hide:"Hide Annotations",show:"Show Annotations",reply:"Reply",quicklyReply:"Reply...",send:"Confirm",placeholder:"Add a annotation...",replyPlaceholder:"Add annotations or @ others",edit:"Edit",delete:"Delete",image:"Image",sendTitle:"Press Enter to post annotation",replyTitle:"Press Enter to reply to annotation",isFirst:"This is already the first comment",isLast:"This is already the last comment",more:"More",comment:"Annotation",command:"Annotation",quickMenuCommand:"Add annotation"}},XU={comment:{count:"\u6CE8\u91C8 ({num})",hide:"\u6CE8\u91C8\u3092\u975E\u8868\u793A",show:"\u6CE8\u91C8\u3092\u8868\u793A",reply:"\u8FD4\u4FE1",quicklyReply:"\u8FD4\u4FE1...",send:"\u78BA\u8A8D",placeholder:"\u6CE8\u91C8\u3092\u8FFD\u52A0...",replyPlaceholder:"\u8FD4\u4FE1\u307E\u305F\u306F\u30E1\u30F3\u30B7\u30E7\u30F3(@)",edit:"\u7DE8\u96C6",delete:"\u524A\u9664",image:"\u753B\u50CF",sendTitle:"Enter\u3092\u62BC\u3057\u3066\u6CE8\u91C8\u3092\u9001\u4FE1",replyTitle:"Enter\u3092\u62BC\u3057\u3066\u6CE8\u91C8\u3092\u8FD4\u4FE1",isFirst:"\u6700\u521D\u306E\u6CE8\u91C8\u3067\u3059",isLast:"\u6700\u5F8C\u306E\u6CE8\u91C8\u3067\u3059",more:"\u305D\u306E\u4ED6",comment:"\u6CE8\u91C8",command:"\u6CE8\u91C8",quickMenuCommand:"\u6CE8\u91C8\u3092\u8FFD\u52A0"}};R.mergeLang({"zh-CN":JU,"en-US":KU,"ja-JP":XU});class iy{renderText(t,e,o){const r=[],i={};return Object.entries(o).forEach(([s,l])=>{s.startsWith("comment-")&&(r.push("comment"),i[s]=l)}),{classes:r,attributes:i}}renderBlock(t,e,o){const r=o.comments;if(!r||r.length===0)return{};const i=["comment"],s={};return r.forEach(l=>{s[`comment-${l.toLocaleLowerCase()}`]=l}),{classes:i,attributes:s}}updateBlock(t,e,o,r){const i=r.comments;et(o,"comment"),Array.from(o.attributes).forEach(s=>{s.name.startsWith("comment-")&&o.removeAttribute(s.name)}),!(!i||i.length===0)&&(W(o,"comment"),i.forEach(s=>{o.setAttribute(`comment-${s.toLocaleLowerCase()}`,s)}))}}class tz{constructor(t){m(this,"handleUpdateCompositionText",(t,e,o,r,i)=>{const s=t.getFocusedBlock(),l=t.getFirstBlock();s===l&&this.applyPlaceholder(t)});m(this,"handleSelectionChange",t=>{this.applyPlaceholder(t)});m(this,"applyPlaceholder",t=>{const e=t.getFirstBlock();If(t,e,R.t("comment.replyPlaceholder"))});this.applyPlaceholder(t),t.addListener("selectionChanged",this.handleSelectionChange)}}function ez(n,t,e){const o=n.getBlockData(t),r=o.comments;if((r==null?void 0:r.indexOf(e))!==-1){const s=new Set(r);s.delete(e),n.updateBlockData(t,{comments:Array.from(s)})}const i=o.text;if(!!i&&tt(n,t)){const s=mg(i,`comment-${e.toLocaleLowerCase()}`,e);ua.default(i,s)||n.setBlockText(t,s)}}const nz=S("editor-comment");function oz(n){const t=n.getCustom("editor-comments");if(g(nz,t,"the editor comment not exist"),t.showCommentList(),n.selection.range.isCollapsed()){const s=n.selection.startBlock,l=Di(s);if(l.length>=2){const{containerId:a}=l.at(-1),d=ot(Nr(n,a));if(d&&Dt(d)==="code"){C2(n,d,t.commentProvider);return}}C2(n,s,t.commentProvider);return}const e=Lo(n,{simpleBlockOnly:!0}),o=e.map(s=>s.block),r=p2(n,o),i=Gf({editor:n,abstract:r});n.undoManager.runInGroup(()=>{e.forEach(l=>{tt(n,l.block)?oy(n,l,i):F8(n,l.block,i)});const s=jr();t.commentProvider.localCreateComment(i,s)})}const E2=S("text-styles");function rz(n){const t=o=>{if(!o.attributes)return new Map;const r=Object.entries(o.attributes).filter(([i])=>!!i.startsWith("style-"));return new Map(r)};if(n.length===0)return new Map;let e=t(n[0]);for(let o=1;o<n.length;o++){const r=t(n[o]);e=new Map(Array.from(e.entries()).filter(([i,s])=>r.get(i)===s))}return e}function iz(n,t,e,o,r){g(E2,e.isSimple(),"invalid range");const{start:i,end:s}=e;g(E2,i.blockId===s.blockId&&i.blockId===it(t),"invalid range"),g(E2,o.startsWith("style-"),"invalid style");let a=n.getBlockText(t);return o==="style-sub"?a=ql(i.offset,s.offset-i.offset,a,"style-super",r,{ignoreValue:!0}):o==="style-super"&&(a=ql(i.offset,s.offset-i.offset,a,"style-sub",r,{ignoreValue:!0})),r===!1||r===void 0||r===null?a=ql(i.offset,s.offset-i.offset,a,o,void 0,{ignoreValue:!0}):a=Ia(i.offset,s.offset-i.offset,a,o,r),n.setBlockText(t,a),a}const sz=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
483
483
  <line x1="3.5" y1="0.5" x2="3.5" y2="15.5" stroke="currentColor"/>
484
484
  <path d="M4 8L7.5 8C9.433 8 11 6.433 11 4.5V4.5C11 2.567 9.433 1 7.5 1L4 1" stroke="currentColor"/>
485
485
  <path d="M4 15L9.5 15C11.433 15 13 13.433 13 11.5V11.5C13 9.567 11.433 8 9.5 8L4 8" stroke="currentColor"/>
@@ -587,10 +587,10 @@ width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
587
587
  </defs>
588
588
  </svg>`,gy={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"]},D2={dwg:Rz,rvt:Oz,skp:_z,img:Fz,txt:Pz,zip:my,rar:my,ppt:Nz,excel:$z,pdf:Hz,word:jz};function py(n,t){const e=Object.keys(gy);for(let r=0;r<e.length;r+=1){const i=e[r];if(gy[i].includes(t))return D2[i]}const o=Aa(n.toLowerCase());return D2[o]?D2[o]:Uz}async function zz(n,t,e){var D;const{fileName:o,fileType:r,fileSize:i}=e,s=w("div",["card-root"],t),l=w("div",["file-icon"],s),{renderFileCardIcon:a}=((D=n.options.componentsOptions)==null?void 0:D.file)||{};if(!a)l.innerHTML=py(o,r);else{const T=a&&await a(n,e);T?l.append(T):l.innerHTML=py(o,r)}const d=w("div",["file-details"],s),h=Aa(o),p=o.length-h.length-3,A=w("div",["file-name"],d);p>0?(w("span",["file-name-pre"],A,o.slice(0,p)),w("span",[],A,o.slice(p))):A.textContent=o,w("div",["file-size"],d,LC(i));const v=w("div",["file-actions"],s),B=w("button",["download"],v);return B.innerHTML=x2,{card:s,downloadButton:B}}const qnt="";function Cy(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});qd(i,o.fileName)}async function Vz(n,t,e){const{embedData:o}=e,r=o,{card:i,downloadButton:s}=await zz(n,t,r);n.domEvents.addEventListener(s,"click",(l,a)=>{if(!a.target)return;const d=ot(a.target);!d||Cy(l,d)}),n.domEvents.addEventListener(i,"click",(l,a)=>{if(!a.target)return;const d=ot(a.target);if(!d||jl(a,"button"))return;const h=l.options.componentsOptions.file;if(h!=null&&h.onClick){h.onClick(l,d,a);return}const A=l.getBlockData(d).embedData,v=l.doc.buildResourceUrl(A.src,{downloadFileName:A.fileName});qd(v,A.fileName)})}class Wz{constructor(t){m(this,"group","hovering-toolbar");m(this,"_commands",[{id:"download",name:R.t("file.commands.download"),icon:x2},{id:"add-comment",name:R.t("file.commands.comment"),icon:eu},{id:"sep",name:"",type:"separator"},{id:"to-link",name:R.t("file.commands.toLink"),icon:ay},{id:"to-card",name:R.t("file.commands.toCard"),icon:uy,states:["checked"]}]);this.editor=t}get commands(){return this.editor.readonly?[]:this._commands}executeCommand(t,e,o){if(o.id==="to-link"){const r=nt(e),i=at(r),s=bt(e),l=t.getBlockData(e),{embedData:a}=l,d=a,h={id:K(),box:!0,type:"file",created:Date.now(),src:d.src,fileName:d.fileName,fileSize:d.fileSize,fileType:d.fileType};t.undoManager.runInGroup(()=>{t.deleteBlock(e);const p=[Q4(h)];t.insertTextBlock(p,i,s)})}else o.id==="download"?Cy(t,e):o.id==="add-comment"&&Kf(t,e)}}function qz(n,t){const e=n.getBlockData(t),{embedData:o}=e,r=o;return{blockCommands:{"hovering-toolbar":new Wz(n)},abstract:r.fileName}}function Gz(n,t,e,o){const{embedData:r}=t,i=r;return o==="html"?i.src?`<p><a href="${n.doc.buildResourceUrl(i.src,{withToken:!0})}" >${i.fileName}</a></p>`:`<p>[${i.fileName}]</p>`:o==="markdown"?i.src?`[${i.fileName}](${n.doc.buildResourceUrl(i.src,{withToken:!0})})
589
589
  `:`[${i.fileName}]
590
- `:i.src?`[${i.fileName}](${n.doc.buildResourceUrl(i.src,{withToken:!0})})`:`[${i.fileName}]`}async function Zz(n,t,e,o){const{onGetFileDownloadUrl:r}=n.getComponentOptions("file")||{},i=t.embedData,s=r?await r(n,i):void 0;return{blocks:{root:[{type:"embed",id:K(),embedType:"webpage",embedData:{src:s||i.src,title:i.fileName}}]},meta:{},comments:{}}}const Qz={embedType:"office",createEmbedContent:Vz,getBlockProperties:qz,convertTo:Gz,toStandardDoc:Zz},Yz={file:{abstract:"\u9644\u4EF6",commands:{download:"\u4E0B\u8F7D",toLink:"\u8F6C\u4E3A\u6807\u9898",toCard:"\u8F6C\u4E3A\u5361\u7247",comment:"\u6279\u6CE8"}}},Jz={file:{abstract:"Attachment",commands:{download:"Download",toLink:"To Link",toCard:"To Card",comment:"Annotation"}}},Kz={file:{abstract:"\u6DFB\u4ED8\u30D5\u30A1\u30A4\u30EB",commands:{download:"\u30C0\u30A6\u30F3\u30ED\u30FC\u30C9",toLink:"\u30BF\u30A4\u30C8\u30EB\u306B\u5909\u63DB",toCard:"\u30AB\u30FC\u30C9\u306B\u5909\u63DB",comment:"\u30B3\u30E1\u30F3\u30C8"}}};R.mergeLang({"zh-CN":Yz,"en-US":Jz,"ja-JP":Kz});function Xz(n){const t=/(\s|^)(http|https):\/\/[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?$/;return t.test(n)?n.search(t):-1}function tV(n){const t=n.selection.range;if(!t.isCollapsed()||!t.isSimple())return;const{start:e}=t,o=n.getBlockById(e.blockId);if(!tt(n,o))return;const r=n.getBlockText(o),s=pg(r).slice(0,e.offset),l=Xz(s);if(l===-1)return;const a=s.slice(l),d=s.length;let h=Ia(l,d-l,r,"link",a);return h=Hr(h,d," ",null),n.setBlockText(o,h),n.selection.selectBlock(o,d+1),!0}const eV={Space:tV},Gnt="",nV={version:{latest:"\u6700\u65B0\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\u7248\u672C ({count})",unknown:"\u672A\u77E5\u7248\u672C",restoreFrom:"\u56DE\u6EDA\u81EA\u7248\u672C\u300C{from}\u300D",restoreInfo:"\u56DE\u6EDA\u7684\u7248\u672C\u6682\u4E0D\u652F\u6301\u4E0E\u4E0A\u4E00\u7248\u672C\u5BF9\u6BD4",versionInfoLeft:'<span class="text-1">\u5F53\u524D\u7248\u672C: </span><span class="name">{versionName}</span><span class="text-2"> \u4E0E</span>',versionInfoRight:'<span class="text-3">\u5BF9\u6BD4</span>',noSelectedVersion:"\u672A\u9009\u62E9\u7248\u672C",noMemoedVersion:"\u6682\u65E0\u5DF2\u5907\u6CE8\u7684\u5386\u53F2\u7248\u672C",noFilterVersion:"\u6682\u65E0\u5339\u914D\u7ED3\u679C",memo:"\u5907\u6CE8",revert:"\u56DE\u6EDA",filter:{all:"\u5168\u90E8",memoed:"\u5DF2\u5907\u6CE8",allVersions:"\u5168\u90E8\u5386\u53F2\u7248\u672C",memoVersions:"\u5DF2\u5907\u6CE8\u7684\u5386\u53F2\u7248\u672C"},textarea:{placeholder:"\u8BF7\u8F93\u5165\u7248\u672C\u5907\u6CE8"},tooltip:{help:`1. \u56DE\u6EDA\u7248\u672C\u4E0D\u652F\u6301\u4E0E\u56DE\u6EDA\u524D\u7248\u672C\u8FDB\u884C\u5BF9\u6BD4\uFF1B
590
+ `:i.src?`[${i.fileName}](${n.doc.buildResourceUrl(i.src,{withToken:!0})})`:`[${i.fileName}]`}async function Zz(n,t,e,o){const{onGetFileDownloadUrl:r}=n.getComponentOptions("file")||{},i=t.embedData,s=r?await r(n,i):void 0;return{blocks:{root:[{type:"embed",id:K(),embedType:"webpage",embedData:{src:s||i.src,title:i.fileName}}]},meta:{},comments:{}}}const Qz={embedType:"office",createEmbedContent:Vz,getBlockProperties:qz,convertTo:Gz,toStandardDoc:Zz},Yz={file:{abstract:"\u9644\u4EF6",commands:{download:"\u4E0B\u8F7D",toLink:"\u8F6C\u4E3A\u6807\u9898",toCard:"\u8F6C\u4E3A\u5361\u7247",comment:"\u6279\u6CE8"}}},Jz={file:{abstract:"Attachment",commands:{download:"Download",toLink:"To Link",toCard:"To Card",comment:"Annotation"}}},Kz={file:{abstract:"\u6DFB\u4ED8\u30D5\u30A1\u30A4\u30EB",commands:{download:"\u30C0\u30A6\u30F3\u30ED\u30FC\u30C9",toLink:"\u30BF\u30A4\u30C8\u30EB\u306B\u5909\u63DB",toCard:"\u30AB\u30FC\u30C9\u306B\u5909\u63DB",comment:"\u6CE8\u91C8"}}};R.mergeLang({"zh-CN":Yz,"en-US":Jz,"ja-JP":Kz});function Xz(n){const t=/(\s|^)(http|https):\/\/[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?$/;return t.test(n)?n.search(t):-1}function tV(n){const t=n.selection.range;if(!t.isCollapsed()||!t.isSimple())return;const{start:e}=t,o=n.getBlockById(e.blockId);if(!tt(n,o))return;const r=n.getBlockText(o),s=pg(r).slice(0,e.offset),l=Xz(s);if(l===-1)return;const a=s.slice(l),d=s.length;let h=Ia(l,d-l,r,"link",a);return h=Hr(h,d," ",null),n.setBlockText(o,h),n.selection.selectBlock(o,d+1),!0}const eV={Space:tV},Gnt="",nV={version:{latest:"\u6700\u65B0\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\u7248\u672C ({count})",unknown:"\u672A\u77E5\u7248\u672C",restoreFrom:"\u56DE\u6EDA\u81EA\u7248\u672C\u300C{from}\u300D",restoreInfo:"\u56DE\u6EDA\u7684\u7248\u672C\u6682\u4E0D\u652F\u6301\u4E0E\u4E0A\u4E00\u7248\u672C\u5BF9\u6BD4",versionInfoLeft:'<span class="text-1">\u5F53\u524D\u7248\u672C: </span><span class="name">{versionName}</span><span class="text-2"> \u4E0E</span>',versionInfoRight:'<span class="text-3">\u5BF9\u6BD4</span>',noSelectedVersion:"\u672A\u9009\u62E9\u7248\u672C",noMemoedVersion:"\u6682\u65E0\u5DF2\u5907\u6CE8\u7684\u5386\u53F2\u7248\u672C",noFilterVersion:"\u6682\u65E0\u5339\u914D\u7ED3\u679C",memo:"\u5907\u6CE8",revert:"\u56DE\u6EDA",filter:{all:"\u5168\u90E8",memoed:"\u5DF2\u5907\u6CE8",allVersions:"\u5168\u90E8\u5386\u53F2\u7248\u672C",memoVersions:"\u5DF2\u5907\u6CE8\u7684\u5386\u53F2\u7248\u672C"},textarea:{placeholder:"\u8BF7\u8F93\u5165\u7248\u672C\u5907\u6CE8"},tooltip:{help:`1. \u56DE\u6EDA\u7248\u672C\u4E0D\u652F\u6301\u4E0E\u56DE\u6EDA\u524D\u7248\u672C\u8FDB\u884C\u5BF9\u6BD4\uFF1B
591
591
  2. \u82E5\u4E24\u4E2A\u7248\u672C\u4E4B\u95F4\u5B58\u5728\u56DE\u6EDA\u7248\u672C\uFF0C\u5219\u4E0D\u652F\u6301\u5BF9\u6BD4\u3002`,user:"\u7248\u672C\u53D1\u5E03\u8005\uFF1A{name}",auth:"\u6682\u65E0\u9875\u9762\u7F16\u8F91\u6743\u9650\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458"},dropdownHeader:"\u4EC5\u5C55\u793A\u53EF\u4E0E\u5F53\u524D\u7248\u672C\u8FDB\u884C\u5BF9\u6BD4\u7684\u5386\u53F2\u7248\u672C",dropdown:{header:"\u6240\u6709\u53EF\u5BF9\u6BD4\u7684\u7248\u672C"},noVersions:"\u6682\u65E0\u53EF\u5BF9\u6BD4\u7684\u7248\u672C",lastVersion:"\u4E0A\u4E00\u7248\u672C",filterMemoed:"\u7B5B\u9009\u5DF2\u5907\u6CE8\u7684\u7248\u672C"}},oV={version:{latest:"Latest",insert:"Added by {name}",delete:"Deleted by {name}",goBack:"Back",revertVersion:"Revert",play:"Play",versionList:"Historical versions ({count})",unknown:"Unknown version",restoreFrom:"Rolled back from version {from}",restoreInfo:"The rolled back version does not currently support comparison with the previous version.",versionInfoLeft:'<span class="text-1">Current version: </span><span class="name">{versionName}</span><span class="text-2"> Compare with</span>',versionInfoRight:'<span class="text-3"></span>',noSelectedVersion:"Not selected",noMemoedVersion:"No historical commented versions",noFilterVersion:"No result",memo:"Comment",revert:"Roll back",filter:{all:"All",memoed:"Commented",allVersions:"All historical versions",memoVersions:"Historical versions with comments"},textarea:{placeholder:"Enter comment"},tooltip:{help:`1. A rolled back version can't be compared with versions before it.
592
592
  2. Versions can't be compared if there are rolled back versions between them.`,user:"Released by {name}",auth:"No edit permission for this page. Contact the admin."},dropdownHeader:"The list below only contains historical versions that can be compared with the current version",dropdown:{header:"All historical versions that can be compared"},noVersions:"No comparable versions available",lastVersion:"Previous version",filterMemoed:"Filter versions with comments"}},rV={version:{latest:"\u6700\u65B0",insert:"{name}\u304C\u8FFD\u52A0\u3057\u307E\u3057\u305F",delete:"{name}\u304C\u524A\u9664\u3057\u307E\u3057\u305F",goBack:"\u623B\u308B",revertVersion:"\u5185\u5BB9\u3092\u5FA9\u5143",play:"\u5C65\u6B74\u3092\u518D\u751F",versionList:"\u30D0\u30FC\u30B8\u30E7\u30F3\u5C65\u6B74 {count}",unknown:"\u672A\u77E5\u306E\u30D0\u30FC\u30B8\u30E7\u30F3",restoreFrom:"\u5FA9\u5143\u3055\u308C\u305F\u30D0\u30FC\u30B8\u30E7\u30F3\uFF1A{from}",restoreInfo:"\u5C65\u6B74\u30D0\u30FC\u30B8\u30E7\u30F3\u306F\u4EE5\u524D\u306E\u30D0\u30FC\u30B8\u30E7\u30F3\u3068\u6BD4\u8F03\u3067\u304D\u307E\u305B\u3093\u3002",versionInfoLeft:'<span class="text-1">\u73FE\u5728\u306E\u30D0\u30FC\u30B8\u30E7\u30F3\uFF1A</span><span class="name">{versionName}</span><span class="text-2"> \u3068</span>',versionInfoRight:'<span class="text-3">\u3092\u6BD4\u8F03\u3059\u308B</span>',noSelectedVersion:"\u672A\u9078\u629E",noMemoedVersion:"\u5099\u8003\u306E\u3042\u308B\u30D0\u30FC\u30B8\u30E7\u30F3\u306F\u3042\u308A\u307E\u305B\u3093",noFilterVersion:"\u4E00\u81F4\u3057\u305F\u7D50\u679C\u306F\u3042\u308A\u307E\u305B\u3093",memo:"\u5099\u8003",revert:"\u5FA9\u5143",filter:{all:"\u3059\u3079\u3066",memoed:"\u5099\u8003\u3042\u308A",allVersions:"\u3059\u3079\u3066",memoVersions:"\u5099\u8003\u3042\u308A"},textarea:{placeholder:"\u8AAC\u660E\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044"},tooltip:{help:`1. \u5FA9\u5143\u3055\u308C\u305F\u30D0\u30FC\u30B8\u30E7\u30F3\u306F\u305D\u308C\u4EE5\u524D\u306E\u53E4\u3044\u30D0\u30FC\u30B8\u30E7\u30F3\u3068\u6BD4\u8F03\u3067\u304D\u307E\u305B\u3093\u3002
593
- 2. \u4E8C\u3064\u306E\u30D0\u30FC\u30B8\u30E7\u30F3\u306E\u9593\u306B\u5FA9\u5143\u3055\u308C\u305F\u30D0\u30FC\u30B8\u30E7\u30F3\u304C\u3042\u308B\u5834\u5408\u3001\u3053\u306E\u4E8C\u3064\u306E\u30D0\u30FC\u30B8\u30E7\u30F3\u306F\u6BD4\u8F03\u3067\u304D\u306A\u3044\u3053\u3068\u306B\u306A\u308A\u307E\u3059\u3002`,user:"\u30D0\u30FC\u30B8\u30E7\u30F3\u4F5C\u6210\u8005\uFF1A{name}",auth:"\u3053\u306E\u30B9\u30DA\u30FC\u30B9\u3092\u7DE8\u96C6\u3059\u308B\u6A29\u9650\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u7BA1\u7406\u8005\u306B\u3054\u9023\u7D61\u304F\u3060\u3055\u3044\u3002"},dropdownHeader:"\u73FE\u5728\u306E\u30D0\u30FC\u30B8\u30E7\u30F3\u3068\u6BD4\u8F03\u3067\u304D\u308B\u30D0\u30FC\u30B8\u30E7\u30F3\u3060\u3051\u8868\u793A\u3055\u308C\u307E\u3059",dropdown:{header:"\u6BD4\u8F03\u53EF\u80FD\u306A\u30D0\u30FC\u30B8\u30E7\u30F3"},noVersions:"\u6BD4\u8F03\u53EF\u80FD\u306A\u30D0\u30FC\u30B8\u30E7\u30F3\u306F\u3042\u308A\u307E\u305B\u3093",lastVersion:"\u524D\u306E\u30D0\u30FC\u30B8\u30E7\u30F3",filterMemoed:"\u5099\u8003\u3042\u308A"}};R.mergeLang({"zh-CN":nV,"en-US":oV,"ja-JP":rV});var Ay=(n=>(n.NEW="history-new",n.NEW_CHILD="history-new-child",n.DELETED="history-deleted",n.UPDATED="history-updated",n.HISTORY="history",n))(Ay||{});const Tc="--op-color",Dc="--op-selected-color",Znt="";class iV{constructor(t){m(this,"root");this.content=t;const e=w("div",["editor-dialog-root"],null);e.append(t),this.root=e}show(t=document.body){t.append(this.root)}hide(){this.root.remove()}destroy(){}}function Xs(n){var e;let t;if(n.version!==-1){const o=new Date((e=n.created)!=null?e:n.version);t=_m(o,"YYYY-MM-DD hh:mm")}else t=R.t("version.latest");return t}function Xf(n){return n.source&&typeof n.source=="object"&&!!n.source.restore}const Qnt="";class sV{constructor(t,e){m(this,"textArea");m(this,"warning");m(this,"end",!1);m(this,"root");m(this,"handleBlur",()=>{var t,e;this.end||(e=(t=this.options)==null?void 0:t.onend)==null||e.call(t,this.textArea.value,!1)});m(this,"handleKeyDown",t=>{var e,o,r,i;t.isComposing||(t.key==="Enter"||t.key==="Tab"?(t.preventDefault(),(o=(e=this.options)==null?void 0:e.onend)==null||o.call(e,this.textArea.value,!1),this.end=!0):t.key==="Escape"&&(t.preventDefault(),(i=(r=this.options)==null?void 0:r.onend)==null||i.call(r,this.textArea.value,!0),this.end=!0))});m(this,"handleInput",t=>{const e=t.target,{value:o}=e;o.length>this.maxLength-10?this.warning.innerText=`${o.length}/${this.maxLength}`:this.warning.innerText="",this.autoSize()});var o,r;this.maxLength=t,this.options=e,this.root=w("div",["size-limit-textarea",...(o=e==null?void 0:e.classes)!=null?o:[]],null),this.textArea=w("textarea",["size-limit-textarea-input"],this.root),this.warning=w("div",["size-limit-textarea-warning"],this.root),this.textArea.addEventListener("input",this.handleInput),this.textArea.addEventListener("blur",this.handleBlur),this.textArea.addEventListener("keydown",this.handleKeyDown),this.textArea.maxLength=t,this.textArea.placeholder=(r=e==null?void 0:e.placeholder)!=null?r:""}destroy(){this.textArea.removeEventListener("input",this.handleInput),this.textArea.removeEventListener("blur",this.handleBlur),this.textArea.removeEventListener("keydown",this.handleKeyDown)}setValue(t){this.textArea.value=t,this.autoSize()}autoSize(){const t=Math.max(this.textArea.scrollHeight,60);this.textArea.style.height="auto",this.textArea.style.height=`${t}px`}resetSize(){this.textArea.style.height="auto";const t=Math.max(this.textArea.scrollHeight,60);this.textArea.style.height=`${t}px`}focus(){this.textArea.focus(),this.end=!1}}const Ynt="",{t:Qn}=R,by=S("version-list");class lV{constructor(t){m(this,"versionsList");m(this,"versionsListHeader");m(this,"versionFilterToolbar");m(this,"memoInput",null);m(this,"selectedVersion",0);m(this,"handleClickVersionItem",t=>{const e=t.target,o=e.closest(".version-item");if(!this.isVersionElement(o))return;const r=xt(o,"active");if(r&&e.closest(".version-item-memo")&&this.options.enableEdit){this.editItemMemo(o);return}const i=this.getVersionFromElement(o);if(this.setActiveItem(o),e.closest(".add-memo-button")&&this.options.enableEdit){this.handleAddMemo(i,o);return}if(e.closest(".revert-button")&&this.options.enableEdit){this.handleRevert(i,o);return}if(r)return;const{onSelectVersion:s}=this.options;s(i)});m(this,"handleEndEditItemMemo",(t,e)=>{var r,i;const o=(r=this.memoInput)==null?void 0:r.root.closest(".version-item");if(this.isVersionElement(o)&&(et(o,"editing"),!e)){const s=this.getVersionFromElement(o),l=t.replace(/[\n\r]+/g," ");if(((i=s.extra)==null?void 0:i.memo)!==l){s.extra={memo:l},this.options.versionHelper.updateVersionExtra(s.version,s.tagId,s.extra).then(()=>{var d,h;(h=(d=this.options).onMemoChanged)==null||h.call(d,s)});const a=o.querySelector(".version-item-memo");g(by,a,"no memo element"),a.textContent=l}}setTimeout(()=>{var s;(s=this.memoInput)==null||s.root.remove()})});m(this,"handleRevert",(t,e)=>{const{onRevert:o}=this.options;o(t)});m(this,"handleFilterClick",(t,e)=>{let o=this.options.versions;e.id==="memoed"&&(o=o.filter(i=>{var s;return!!((s=i.extra)!=null&&s.memo)}));const r=this.createVersionItems(o,e.id);this.versionsList.innerHTML="",this.versionsList.append(r),this.versionFilterToolbar.updateItems(this.getFilterItems(e.id)),this.updateHeaderCount(o.length)});var d,h;this.options=t;const{versions:e}=t,o=w("div",["version-list-header"],null),r=Qn("version.versionList",{count:`${e.length}`});w("span",["version-count"],o,r);const i=w("div",["version-list-filter"],o);this.versionFilterToolbar=new rM(i,this.getFilterItems("all"),{tooltipId:"version-viewer"}),this.versionFilterToolbar.addListener("click",this.handleFilterClick),this.selectedVersion=t.selectedVersion||((d=e[0])==null?void 0:d.version)||-1;const s=w("div",["version-list-content"],null),l=this.createVersionItems(e,"all");s.append(l),this.versionsList=s,this.versionsListHeader=o,s.onclick=this.handleClickVersionItem;const a=this.activeVersion;a&&((h=this.options)==null||h.onSelectVersion(a))}getFilterItems(t){return[{id:"filter",name:Qn(t==="all"?"version.filter.all":"version.filter.memoed"),dropdown:!0,manualShowChildren:!0,childrenPlacement:"bottom-start",children:[{id:"all",states:t==="all"?["checked"]:[],name:Qn("version.filter.allVersions")},{id:"memoed",states:t==="memoed"?["checked"]:[],name:Qn("version.filter.memoVersions")}]}]}createVersionItems(t,e){const o=document.createDocumentFragment();if(t.length===0){const i=w("div",["version-list-empty"],o);return i.textContent=Qn("version.noMemoedVersion"),o}const r=(i,s,l,a=!1)=>{var T,_;const d=w("div",["version-item"],o);d.versionData=i,s&&W(d,"child"),i.version===this.selectedVersion&&W(d,"active");const h=w("div",["version-item-title"],d);w("div",["version-item-date"],h,Xs(i)),a&&w("div",["version-item-latest"],h,Qn("version.latest")),w("div",["spacer"],h);const p=w("div",["version-actions"],h),A=w("button",["add-memo-button"],p);if(A.textContent=Qn("version.memo"),this.options.enableEdit||(W(A,"disabled"),A.setAttribute("data-editor-tooltip-common",R.t("version.tooltip.auth"))),!a){const M=w("button",["revert-button"],p);M.textContent=Qn("version.revert"),this.options.enableEdit||(W(M,"disabled"),M.setAttribute("data-editor-tooltip-common",R.t("version.tooltip.auth")))}let v="";if(typeof i.source=="object"&&((T=i.source)==null?void 0:T.restore)){const M=i.source.restore,H=l.find(q=>q.version==M),z=H?Xs(H):Qn("version.unknown");v=Qn("version.restoreFrom",{from:z})}w("div",["version-item-restore-from"],d,v),w("div",["version-item-memo"],d,((_=i.extra)==null?void 0:_.memo)||"");const B=w("ul",["version-item-authors"],d),D=M=>{const H=w("li",["version-item-author"],B),z=w("span",["version-item-author-mark"],H);z.style.background=this.options.getMarkColor(M),w("span",["version-item-author-name"],H,M.displayName).setAttribute("data-editor-tooltip-common",R.t("version.tooltip.user",{name:M.displayName}))};if(this.options.useCreatedBy)if(i.createdBy){const M=i.createdBy;D(M)}else i.authors&&i.authors.length>0&&i.authors.forEach(M=>{D(M)});else if(i.authors&&i.authors.length>0)i.authors.forEach(M=>{D(M)});else if(i.createdBy){const M=i.createdBy;D(M)}};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)})}),o}isVersionElement(t){return t?xt(t,"version-item"):!1}getVersionFromElement(t){return t.versionData}get activeVersion(){return this.options.versions.find(t=>t.version===this.selectedVersion)}setActiveItem(t){if(xt(t,"active"))return;const e=this.versionsList.querySelector(".version-item.active");e&&et(e,"active"),W(t,"active"),this.selectedVersion=this.getVersionFromElement(t).version}handleAddMemo(t,e){this.editItemMemo(e)}editItemMemo(t){var o;this.memoInput||(this.memoInput=new sV(256,{onend:this.handleEndEditItemMemo,classes:["memo-input"],placeholder:Qn("version.textarea.placeholder")}));const e=t.querySelector(".version-item-restore-from");g(by,e,"no title element"),e.insertAdjacentElement("afterend",this.memoInput.root),W(t,"editing"),this.memoInput.setValue(((o=t.versionData.extra)==null?void 0:o.memo)||""),this.memoInput.resetSize(),this.memoInput.focus()}updateHeaderCount(t){const e=this.versionsListHeader.querySelector(".version-count");e&&(e.textContent=Qn("version.versionList",{count:`${t.toString()}`}))}getVersionItemByVersionNum(t){const e=Array.from(this.versionsList.children).find(o=>o.versionData.version===t);return this.isVersionElement(e)?e:null}selectVersionByVersionNum(t){const e=this.getVersionItemByVersionNum(t);return e?(this.setActiveItem(e),this.getVersionFromElement(e)):null}render(t){t.innerHTML="",t.append(this.versionsListHeader,this.versionsList)}destroy(){this.versionsList.onclick=null,this.versionFilterToolbar.destroy()}}class cV{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(){}}async function aV(n,t,e){for(const o of e){const r=new cV(n,o.user);t.parseHistoryData(o,r)}}const An=S("split-text-actions");function vy(n){return n.length>2?!1:n.length===1?n[0].insert!==void 0:(g(An,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].insert!==void 0)}function yy(n){return n.length>2?!1:n.length===1?n[0].delete!==void 0:(g(An,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].delete!==void 0)}function ky(n){return n.length>2?!1:n.length===1?n[0].insert===void 0&&n[0].delete===void 0&&n[0].attributes!==void 0:(g(An,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].attributes!==void 0)}function uV(n){const t=[],e=mt.default(n);if(e.length===0)return[];if(e.length===1)return[n];if(e.length===2&&(yy(n)||vy(n)||ky(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){g(An,i.retain>0,`invalid text op: ${JSON.stringify(i)}`),g(An,e.length>1,`invalid text op: ${JSON.stringify(i)}`);const s=e[1];g(An,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:(g(An,s.attributes!==void 0,`invalid next text op: ${JSON.stringify(s)}`),g(An,s.retain!==void 0,`invalid next text op: ${JSON.stringify(s)}`),r+=s.retain),e.splice(0,2)}else g(An,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&&(g(An,i.attributes!==void 0,`invalid next text op: ${JSON.stringify(i)}`),r+=i.retain),i.insert&&(r+=i.insert.length)}return t}function wy(n){if(g(An,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 g(An,typeof t=="number"&&t>0,`invalid retain: ${JSON.stringify(n)}`),t}let By=0;function dV(n,t,e){const o=By;By+=1;const r=re(n);return{insert:" ",attributes:{box:!0,id:K(),type:"history-deleted-box",user:e,created:Date.now(),text:r,deletedOffset:t,deletedOrder:o}}}function hV(n,t,e){const o=wy(t),r=t.length===1?t[0].delete:t[1].delete;g(An,typeof r=="number",`not a delete op: ${JSON.stringify(t)}`);const{left:i,middle:s,right:l}=ze(n,o,r),a=dV(s,o,e);return[...i,a,...l]}function fV(n,t,e){const o=wy(t),r=t.length===1?t[0].insert:t[1].insert;g(An,typeof r=="string",`invalid insert op: ${JSON.stringify(t)}`);const i=t.length===1?t[0].attributes:t[1].attributes,l=uh([{insert:r,attributes:i}],"insertedBy",e);return Hr(n,o,l,null)}function mV(n,t,e){const o=uV(t);let r=n;for(const i of o)yy(i)?r=hV(r,i,e):vy(i)?r=fV(r,i,e):(g(An,ky(i),`unknown op: ${JSON.stringify(i)}`),r=ln.apply(r,i));return r}const gV=S("history-update-block-text");function Ey(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+=ah(r)}),t.sort((r,i)=>i.offset-r.offset),{deletedBoxes:t,newText:e}}function pV(n,t,e){let o=n;return t.forEach(r=>{const i=ln.transformCursor(r.offset,e,!1);o=Hr(o,i,[{insert:" ",attributes:r.boxData}],null)}),o}function CV(n){n.sort((t,e)=>t.boxData.deletedOffset!==e.boxData.deletedOffset?t.boxData.deletedOffset-e.boxData.deletedOffset:t.boxData.deletedOrder-e.boxData.deletedOrder)}function AV(n){if(n.length<=1)return n;const t=n[0].offset;n.forEach(e=>{g(gV,e.offset===t,`invalid boxes group, ${JSON.stringify(n)}`)}),CV(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 bV(n){let{newText:t,deletedBoxes:e}=Ey(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,a)=>l.boxData.deletedOffset-a.boxData.deletedOffset)}),Array.from(o.values()).sort((i,s)=>s[0].offset-i[0].offset).forEach(i=>{const s=i[0].offset;AV(i).reverse().forEach(l=>{t=Hr(t,s,[{insert:" ",attributes:l.boxData}],null)})}),t}function vV(n,t,e){let{newText:o,deletedBoxes:r}=Ey(n);return o=mV(o,t,e),o=pV(o,r,t),o=bV(o),o}const Ar=S("history-doc");function br(n){g(Ar,!1,"no local actions for history doc")}class yV extends fa{constructor(t,e){super(),this.externalDoc=t,this.docObject=e}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return mt.default(this.docObject)}getContainerBlocks(t){return this.docObject.blocks[t]}getBlockData(t,e){const o=this.getContainerBlocks(t);g(Ar,o,`no container data: ${t}`);const r=o[e];return g(Ar,r,`no block data: ${e}`),r}localUpdateBlockText(){br()}localUpdateBlockData(){br()}localInsertBlock(){br()}localDeleteBlock(){br()}localInsertChildContainer(){br()}localDeleteChildContainers(){br()}uploadResource(){br()}async addResources(t){br()}getServerMeta(){var t,e,o;return(o=(e=(t=this.externalDoc).getServerMeta)==null?void 0:e.call(t))!=null?o:{}}buildResourceUrl(t){return this.externalDoc.buildResourceUrl(t)}request(){br()}broadcastMessage(){br()}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new _h}destroy(){this.clearCallbacks()}transformBlockIndex(t,e,o){const r=this.docObject.blocks[t];g(Ar,r,`no container blocks: ${t}`);let i=0;for(let s=0;s<r.length;s++)if(!r[s].deletedBy){if(i===e)return s;i++}return o&&g(Ar,!1,`invalid block index: ${e}, blocks: ${JSON.stringify(r)}`),g(Ar,i===e,`invalid block index: ${e}, blocks: ${JSON.stringify(r)}`),r.length}onDeleteBlock(t,e,o){const r=this.transformBlockIndex(t,e,!0),s=this.docObject.blocks[t][r];g(Ar,!s.deleted,`block has already deleted: ${t}/${e}`),s.deletedBy=o,this.callbacks.forEach(l=>{var a;return(a=l.onUpdateBlockData)==null?void 0:a.call(l,t,r,{insert:{},delete:[]},!0)})}onInsertBlock(t,e,o,r){const i=this.transformBlockIndex(t,e,!1),s=this.docObject.blocks[t],l=mt.default(o);l.insertedBy=r,s.splice(i,0,l),this.callbacks.forEach(a=>{var d;return(d=a.onInsertBlock)==null?void 0:d.call(a,t,i,l,!0)})}onUpdateBlockText(t,e,o,r){const i=this.transformBlockIndex(t,e,!0),l=this.docObject.blocks[t][i];g(Ar,!l.deleted,`block has already deleted: ${t}/${e}`);const a=l.text;g(Ar,a,`no text for block: ${JSON.stringify(l)}`);const d=vV(a,o,r);l.text=d,this.callbacks.forEach(h=>{var p;return(p=h.onUpdateBlockText)==null?void 0:p.call(h,t,i,o,!0)})}onUpdateBlockData(t,e,o,r){const i=this.transformBlockIndex(t,e,!0),s=this.docObject.blocks[t],l=s[i];g(Ar,!l.deleted,`block has already deleted: ${t}/${e}`);const a=mt.default(l);a.updatedBy=r,o.delete.forEach(d=>delete a[d]),Object.entries(o.insert).forEach(([d,h])=>{a[d]=h}),s[i]=a,this.callbacks.forEach(d=>{var h;return(h=d.onUpdateBlockData)==null?void 0:h.call(d,t,i,o,!0)})}onCreateContainer(t,e,o){this.docObject.blocks[t]=mt.default(e),this.callbacks.forEach(r=>{var i;return(i=r.onInsertChildContainer)==null?void 0:i.call(r,t,e,!0)})}}const{t:xy}=R;function Sc(n,t){return t==="insert"?xy("version.insert",{name:n.displayName}):xy("version.delete",{name:n.displayName})}function tl(n,t){const{userId:e}=t;return["flag","selection"].reduce((r,i)=>{const s=n.getRemoteUsers().getFixedUserColor(e,i);return r[i]=s,r},{})}class kV{renderText(t,e,o){if(!o.box&&o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=tl(t.doc,o.insertedBy);return{classes:["history-inserted-text"],attributes:{"history-inserted-by":r.displayName,"data-op-description":Sc(r,"insert")},styles:{[Tc]:i,[Dc]:s}}}return{}}renderBlock(t,e,o){if(o.deletedBy){const r=o.deletedBy,{flag:i,selection:s}=tl(t.doc,r);return{classes:["history-deleted-block"],attributes:{"history-deleted-by":r.displayName,"data-op-description":Sc(r,"delete")},styles:{[Tc]:i,[Dc]:s}}}if(o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=tl(t.doc,r);return{classes:["history-inserted-block"],attributes:{"history-inserted-by":r.displayName,"data-op-description":Sc(r,"insert")},styles:{[Tc]:i,[Dc]:s}}}return{}}updateBlock(t,e,o,r){if(r.deletedBy){const i=r.deletedBy,{flag:s,selection:l}=tl(t.doc,i);W(o,"history-deleted-block"),bm(o,{"history-inserted-by":i.displayName,"data-op-description":Sc(i,"delete")}),vm(o,{[Tc]:s,[Dc]:l});return}if(r.insertedBy){const i=r.insertedBy,{flag:s,selection:l}=tl(t.doc,i);W(o,"history-inserted-block"),bm(o,{"history-inserted-by":i.displayName,"data-op-description":Sc(i,"insert")}),vm(o,{[Tc]:s,[Dc]:l})}}}const Iy=S("history-deleted-box");function wV(n,t,e,o){const r=o;g(Iy,r.text,`no text for text box data: ${JSON.stringify(o)}`),g(Iy,typeof r.text=="string",`invalid text type for text box data: ${JSON.stringify(o)}`);const i=w("span",["history-deleted-box"],e,r.text),s=r.user,{flag:l,selection:a}=tl(n.doc,s);i.setAttribute("history-deleted-by",s.displayName),i.setAttribute("data-op-description",Sc(s,"delete")),i.style.setProperty(Tc,l),i.style.setProperty(Dc,a)}function BV(n,t,e,o){return t.text}const EV={boxType:"history-deleted-box",updateBoxContent:wV,convertTo:BV},Jnt="",xV=S("versions-dropdown"),Ty=(n,t)=>{if(!t)return n;let e="";const o=t.length,r=t.toLocaleLowerCase();let i=0;for(i=0;i<=n.length-o;i){let s=n.substring(i,i+o);if(s.toLocaleLowerCase()===r){i+=o;const l=n.charAt(i);let a=!1;s.endsWith(" ")&&(a=!0,s=s.trimEnd()),e+=`<span class="highlight">${s}${l===" "||a?"&nbsp":""}</span>`}else e+=n.charAt(i),i++}return i<n.length&&(e+=n.substring(i)),e};class IV{constructor(t,e){m(this,"dropdown");m(this,"versions",[]);m(this,"currentVersion",null);m(this,"compareWithVersion",null);m(this,"filterMemoed",!1);m(this,"keywords","");m(this,"createFilterMemoedFilterItem",t=>{const e=w("div",["filter-memoed-version-item"],null);t&&w("div",["filter-item-info"],e,R.t("version.dropdown.header"));const o=w("div",["filter-item-input-container"],e),r=w("input",["filter-item-input"],o);r.id="filter-item-input",r.type="checkbox";const i=w("label",["filter-item-label"],o,R.t("version.filterMemoed"));return i.htmlFor=r.id,r.onchange=this.handleInputChange,r.checked=this.filterMemoed,e});m(this,"filterItems",(t,e)=>{var i,s;if(this.keywords=e,!e)return!0;if(t.id==="section")return!1;const o=e.toLocaleLowerCase();if(t.name.toLocaleLowerCase().indexOf(o)!==-1)return!0;const r=t.data;return!!(r&&((i=r.extra)==null?void 0:i.memo)&&((s=r.extra)==null?void 0:s.memo.toLocaleLowerCase().indexOf(o))!==-1)});m(this,"handleClose",()=>{});m(this,"handleClear",()=>{this.options.onCompareWithVersion(null)});m(this,"handleClickItem",t=>{const e=t.data,o=Xs(e);this.dropdown.setText(o),this.options.onCompareWithVersion(e)});m(this,"handleInputChange",t=>{const e=t.target;this.filterMemoed=e.checked,this.resetItems()});this.options=e,this.dropdown=new Rp(t,{placeholder:R.t("version.noSelectedVersion"),emptyPlaceholder:R.t("version.noFilterVersion"),popupId:"versions-dropdown-popup",header:this.createHeader(),filter:this.filterItems,onClose:this.handleClose,onClickItem:this.handleClickItem,onClear:this.handleClear,highlight:!0})}createHeader(){const t=w("div",["versions-dropdown-header"],null),e=w("span",["versions-dropdown-header-info"],t);e.innerHTML=R.t("version.dropdownHeader");const o=w("span",["versions-dropdown-header-icon"],t);return o.setAttribute("data-editor-tooltip-common",R.t("version.tooltip.help")),o.setAttribute("data-editor-tooltip-placement","right"),o.innerHTML=fv,o.onclick=this.options.onHelp,t}setVersions(t){this.versions=t}setCurrentVersion(t,e){this.dropdown.setText(""),this.dropdown.setLabels([]),e&&(this.dropdown.setText(Xs(e)),(e.version===-1||e.version===this.versions[0].version)&&this.dropdown.setLabels([R.t("version.latest")])),this.currentVersion=t,this.compareWithVersion=e!=null?e:null,this.resetItems()}resetItems(){var A;if(this.versions.length===0)return;const t=this.currentVersion;if(!t)return;const e=t.version===-1?0:this.versions.findIndex(v=>v.version===t.version);g(xV,e!==-1,"version not found");const o=this.versions[0],r=v=>{var H;const B=v.data,D=w("div",["version-item-container"],null),T=w("div",["version-item-line1"],D),_=v.value==="last-version"?R.t("version.lastVersion"):Xs(B),M=w("div",["version-item-name"],T);if(this.keywords?M.innerHTML=Ty(_,this.keywords):M.innerText=_,B.version===o.version&&w("div",["version-item-latest"],T,R.t("version.latest")),(H=B.extra)!=null&&H.memo){const z=w("div",["version-item-line2"],D),q=w("div",["version-item-memo"],z,B.extra.memo);this.keywords?q.innerHTML=Ty(B.extra.memo,this.keywords):q.innerText=B.extra.memo,q.setAttribute("data-editor-tooltip-common",B.extra.memo),q.setAttribute("data-editor-tooltip-placement","bottom")}return D.onclick=()=>{this.handleClickItem(v),this.dropdown.close()},D},i=[],s=this.versions[e+1],l=s&&!Xf(t);if(l){const v={id:"section",value:"last-version",name:"Last version",data:s,element:r};i.push(v)}let a=e;for(let v=e-1;v>=0;v-=1){const B=this.versions[v];if(Xf(B))break;a=v}let d=e;if(!Xf(t))for(let v=e+1;v<this.versions.length;v+=1){const B=this.versions[v];if(d=v,Xf(B))break}let h=!1;const p=[];for(let v=a;v<=d;v+=1){const B=this.versions[v];if(B.version!==t.version&&B.version!==(s==null?void 0:s.version)&&(!this.filterMemoed||((A=B.extra)==null?void 0:A.memo))){h=!0;let D=Xs(B),T=`${B.version}`;v===e+1&&(D="Previous version",T="prev-version");const _={id:T,name:D,data:B,element:r};p.push(_)}}if((l||h||this.filterMemoed)&&i.push({id:"section",name:"",element:this.createFilterMemoedFilterItem(i.length>0&&l),states:["disabled"]}),i.push(...p),!h){const v={id:"section",name:"No versions",states:["disabled"],element:w("span",["version-item-empty"],null,R.t("version.noVersions"))};i.push(v)}this.dropdown.updateItems(i)}}class TV{constructor(t,e){m(this,"left");m(this,"right");m(this,"dropdown");const o=w("div",["version-info-container"],t);this.left=w("div",["version-info-left"],o),this.dropdown=new IV(o,e),this.right=w("div",["version-info-right"],o)}setVersion(t,e,o){const r=`<span class="version-item-latest">${R.t("version.latest")}</span>`,i=`${Xs(t)}${o?r:""}`;this.left.innerHTML=R.t("version.versionInfoLeft",{versionName:i}),this.right.innerHTML=R.t("version.versionInfoRight",{versionName:i}),this.dropdown.setCurrentVersion(t,e)}}const es=S("version-dialog");class Dy{constructor(t,e){m(this,"dialog",null);m(this,"oldViewer",null);m(this,"versionOptions");m(this,"versionList",null);m(this,"provider");m(this,"versions",[]);m(this,"components");m(this,"handleRevert",async t=>{var o,r,i;g(es,this.versionList,"The versionList did not render");const e=t!=null?t:(o=this.versionList)==null?void 0:o.activeVersion;g(es,e,`The version: ${e} is invalid`),!(((r=this.versionOptions)==null?void 0:r.onBeforeRevert)&&await this.versionOptions.onBeforeRevert(e))&&(await this.versionHelper.revertVersion(e.version),(i=this.dialog)==null||i.hide())});m(this,"handleSelectVersion",t=>{g(es,t,`The version: ${t} is invalid`),this.viewVersion(t)});m(this,"handleCompareWithVersion",t=>{var o;const e=(o=this.versionList)==null?void 0:o.activeVersion;g(es,e,"no active version"),this.viewVersion(e,t!=null?t:void 0)});m(this,"handleHelp",()=>{var t,e;(e=(t=this.versionOptions)==null?void 0:t.onHelp)==null||e.call(t)});m(this,"viewVersion",async(t,e)=>{var h,p;const o=this.versions[0].version===t.version;if(this.components.infoHeader.setVersion(t,e,o),this.oldViewer&&(this.oldViewer.destroy(),this.oldViewer=null),!this.versionList)return;(h=this.versionOptions)!=null&&h.onWillChangeVersion&&this.versionOptions.onWillChangeVersion(this,t);const r=e==null?void 0:e.version;let i,s;if(r){const A=Math.min(t.version,r),v=Math.max(t.version,r),B=await this.versionHelper.getHistoryData(v,A);i=B.doc,s=B.historyData}else i=await this.versionHelper.getVersion(t.version),s=[];const{editorContainer:l}=this.components;l.innerHTML="";const a=new yV(this.doc,i),d=this.provider.createHistoryEditor(l,a);d.editorBlockRenders.registerRender(new kV),d.editorBoxes.registerBoxClass(EV),W(d.rootElement,Ay.HISTORY);try{await aV(a,this.versionHelper,s)}finally{this.oldViewer=d}(p=this.versionOptions)!=null&&p.onVersionChanged&&this.versionOptions.onVersionChanged(this,d,t)});m(this,"onMemoChanged",t=>{var e,o;(o=(e=this.versionOptions)==null?void 0:e.onMemoChanged)==null||o.call(e,t),this.components.infoHeader.dropdown.resetItems(),this.components.infoHeader.dropdown.setVersions(this.versions)});this.doc=t,this.provider=e;const o=w("div",["version-dialog"],null),r=w("div",["version-viewer"],o),i=new TV(r,{onCompareWithVersion:this.handleCompareWithVersion,onHelp:this.handleHelp}),s=w("div",["version-dialog-editor"],r),l=w("div",["version-list-root"],o);this.components={root:o,editorContainer:s,listContainer:l,infoHeader:i}}get versionHelper(){g(es,this.doc.getVersionHelper,"Can not get getVersionHelper from doc");const t=this.doc.getVersionHelper();return g(es,t,"current doc does not support version"),t}get editor(){return this.oldViewer}renderContent(t){var r,i;const{listContainer:e}=this.components;e.innerHTML="";const o=new lV({enableEdit:((r=this.versionOptions)==null?void 0:r.enableEdit)||!1,versions:t,versionHelper:this.versionHelper,useCreatedBy:(i=this.versionOptions)==null?void 0:i.useCreatedBy,onSelectVersion:this.handleSelectVersion,onRevert:this.handleRevert,onMemoChanged:this.onMemoChanged,getMarkColor:s=>{const{flag:l}=tl(this.doc,s);return l}});o.render(e),this.versionList=o}initViewVersion(){var t;if(g(es,this.versionList,"no versionList"),(t=this.versionOptions)!=null&&t.initSelectedVersion){const{initSelectedVersion:e}=this.versionOptions,o=this.versionList.selectVersionByVersionNum(e);g(es,o,`version ${e} not found`),this.viewVersion(o)}else{const e=this.versionList.activeVersion;e&&this.viewVersion(e)}}async show(t){if(this.versionOptions={...this.versionOptions,...t},this.versions=await this.versionHelper.getVersions(),this.versionOptions.onVersionsLoaded&&this.versionOptions.onVersionsLoaded(this,this.versions),this.components.infoHeader.dropdown.setVersions(this.versions),this.renderContent(this.versions),this.initViewVersion(),!this.dialog){const{root:e}=this.components;this.dialog=new iV(e)}this.dialog.show(t.container)}destroy(){var t,e;(t=this.dialog)==null||t.destroy(),(e=this.versionList)==null||e.destroy()}}const DV={expandCollapseButton:{tips:"\u5C55\u5F00 / \u6536\u8D77"}},SV={expandCollapseButton:{tips:"Expand / Collapse"}},LV={expandCollapseButton:{tips:"\u5C55\u958B / \u7E2E\u5C0F"}};R.mergeLang({"zh-CN":DV,"en-US":SV,"ja-JP":LV});const Knt="",MV=S("heading-collapse");function S2(n){var e;const t=Number.parseInt((e=n.getAttribute("data-style-heading"))!=null?e:"",10);return g(MV,t,"not a heading block"),t}function fo(n){return!!n.getAttribute("data-style-heading")}function RV(n){return!xt(n,"heading-collapsed")}function el(n){return xt(n,"heading-collapsed")}function Sy(n){if(ce(n))return!1;const e=nt(n);return Xt(e)}const OV=S("heading-collapse");function L2(n){g(OV,fo(n),"not a heading block");const t=[],e=S2(n);let o=Zt(n);for(;o&&!(fo(o)&&S2(o)<=e);)t.push(o),o=Zt(o);return t}function Ly(n,t){if(!ro(t))return;n.selection.selectBlock(t,0),L2(t).forEach(o=>{UC(o)}),W(t,"heading-collapsed")}function Lc(n,t){L2(t).forEach(o=>{zC(o)}),et(t,"heading-collapsed")}function _V(n,t){RV(t)?Ly(n,t):Lc(n,t)}const FV=[kp,wp,Bp,Ep,xp,Ip,Tp,Dp];function PV(n){const t=w("button",["heading-collapse-button"],null);return t.setAttribute(`data-editor-tooltip-${n.clientId}`,R.t("expandCollapseButton.tips")),t.innerHTML=Gh,t}function My(n){return Mf(n).querySelector("button.heading-collapse-button")}function Ry(n,t){My(t)||Sy(t)||!ro(t)||Q0(t,PV(n),-1)}function NV(n){var t;(t=My(n))==null||t.remove()}function Oy(n,t){Mf(t).querySelector("button.heading-collapse-button")||Ry(n,t)}function $V(n){const t=S2(n),e=w("button",["heading-marker"],null);return e.innerHTML=FV[t-1],e}function _y(n){return Mf(n).querySelector("button.heading-marker")}function M2(n){_y(n)||Sy(n)||!ro(n)||Q0(n,$V(n),1)}function Fy(n){const t=_y(n);t==null||t.remove()}function Py(n){Fy(n),fo(n)&&M2(n)}class HV{handleDrop(t,e,o,r){if(Wd(e)||!fo(e)||!el(e))return;const i=L2(e);i.unshift(e);const s=i.reverse();let l=null;return t.doc.beginBatchUpdate(),s.forEach((a,d,h)=>{const p=t.getBlockData(a),A=Fi(t.editorBlocks,t.doc.toJSON(),p),v=t.insertDocAt(o,r,A)[0];d===h.length-1&&(l=v)}),t.doc.endBatchUpdate(),t.doc.beginBatchUpdate(),s.forEach(a=>{t.deleteBlock(a)}),t.doc.endBatchUpdate(),l&&Ly(t,l),!0}}const jV=S("heading-collapse");class R2{constructor(t){m(this,"handleLoad",()=>{this.showCollapseButtons()});m(this,"handleHoverBlock",(t,e)=>{e&&(et(e,"hovering-heading"),fo(e)&&Xt(nt(e))&&(M2(e),el(e)||NV(e))),t&&fo(t)&&Xt(nt(t))&&(W(t,"hovering-heading"),this.editor.readonly||Fy(t),Ry(this.editor,t))});m(this,"handleClick",(t,e)=>{const o=jl(e,"button.heading-collapse-button");if(!o)return;const r=ot(o);!r||(g(jV,fo(r),"not a heading block"),_V(this.editor,r),Oy(this.editor,r))});this.editor=t,t.addListener("load",this.handleLoad),t.addListener("click",this.handleClick),pe.get(t).addListener("change",this.handleHoverBlock),this.showCollapseButtons(),setTimeout(()=>{var o;(o=Su.find(t))==null||o.addHandler(new HV)})}showCollapseButtons(){const t=ve(this.editor.rootContainer).filter(fo);t.length!==0&&(t[0]===Se(this.editor.rootContainer)&&t.splice(0,1),t.forEach(M2))}destroy(){this.editor.removeListener("load",this.handleLoad),this.editor.removeListener("click",this.handleClick)}}function t1(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);el(e)&&Lc(n,e),el(o)&&Lc(n,o)}function UV(n){t1(n);const t=n.getFocusedBlock();!fo(t)||el(t)&&Lc(n,t)}function zV(n){t1(n);const t=n.getFocusedBlock();if(!fo(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===ut(n,t)&&el(t)&&Lc(n,t)}function VV(n){t1(n);const t=n.getFocusedBlock();if(!fo(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===0&&el(t)&&Lc(n,t)}class WV{handleBeforeKeyDown(t,e){return xm(e.key)&&t1(t),e.key==="Enter"?(UV(t),!1):e.key==="Delete"?(zV(t),!1):(e.key==="Backspace"&&VV(t),!1)}}class qV{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(!fo(o)){e&&e.delete.includes("heading")&&Py(o);return}xt(o,"hovering-heading")&&Oy(this.editor,o),Py(o)}},100)}}function GV(n){return!!n.heading}function Ny(n){var e;const t=n.heading;return(e=Number.parseInt(`${t}`,10))!=null?e:1}function $y(n,t,e){var i;const o=Ms(n,t.type);let r="";if(o.convertTo){const s=jr();r=o.convertTo(n,t,s,"text",[{containerId:"root",blockIndex:0}]),r=r.replace(/\n/g,"").trim()}else r=re((i=t.text)!=null?i:[]);return{parentNode:e,children:[],text:r,level:Ny(t),block:t}}class Pu{constructor(t){m(this,"nodes",[]);this.editor=t}appendBlock(t){const e=this.findParent(Ny(t),this.nodes);e?e.children.push($y(this.editor,t,e)):this.nodes.push($y(this.editor,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,e){const o=new Pu(t),r=e.blocks.root;for(let i=0;i<r.length;i++){const s=r[i];GV(s)&&o.appendBlock(s)}return o}}class nl extends be.TypedEmitter{constructor(e){super();m(this,"toc");m(this,"updateToc",He.default(()=>{this.updateTocNow()},500));this.editor=e,e.doc.registerCallback(this),this.updateToc(),this.toc=new Pu(this.editor)}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 nl(e))}static get(e){return e.getCustom("editor-toc")}updateTocNow(){this.toc=Pu.buildToc(this.editor,this.editor.doc.toJSON()),this.emit("change",this.editor,this.toc)}}const Xnt="";function ZV(n){return n.nodes.length===0?!0:n.nodes.length>1?!1:n.nodes[0].children.length===0}function Hy(n,t){t.forEach(e=>{const o=w("div",["toc-node"],n),r=w("div",["toc-title"],o);if(w("span",["toc-text"],r,e.text).setAttribute("data-block-id",e.block.id),e.children.length>0){const s=w("div",["toc-children"],o);Hy(s,e.children)}})}function QV(n,t){const e=jl(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 jy(n,t,e){if(et(t,"loading"),t.innerHTML="",ZV(e)){w("div",["toc-empty-message"],t,R.t("toc.empty"));return}if(e.nodes.length>=1){const[o,...r]=e.nodes,i=[...o.children,...r];Hy(t,i)}op(n,"toc-click-handler",()=>{n.addListener("click",QV)})}class YV{constructor(t){m(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&&jy(t,i,e)})});this.editor=t,nl.register(t).addListener("change",this.handleUpdateToc)}destroy(){nl.register(this.editor).removeListener("change",this.handleUpdateToc)}get toc(){return nl.register(this.editor).toc}}function JV(n,t){const e=w("div",["editor-toc-container"],t),r=n.addCustom("init-editor-toc",()=>new YV(n)).toc;r.nodes.length===0?W(e,"loading"):jy(n,e,r)}function KV(n,t,e,o){return o==="markdown"?"[toc]":""}function XV(n,t,e){const{data:o}=e;if(!o||o.embedType!=="toc"||!tt(n,t))return null;const r={};return{blockData:{id:K(),type:"embed",embedType:"toc",embedData:r}}}const Uy={embedType:"toc",createEmbedContent:JV,convertTo:KV,convertFrom:XV},tW={toc:{empty:"No Toc"}},eW={toc:{empty:"No Toc"}},nW={toc:{empty:"No Toc"}};R.mergeLang({"zh-CN":tW,"en-US":eW,"ja-JP":nW});function oW(n){return!!n.getAttribute("data-style-heading")}function O2(n,t){return oW(t)&&ut(n,t)>0}function rW(n){const t=oo(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=ot(i[s]);if(l&&n.rootContainer.contains(l))return l}o+=10}return null}function _2(n,t){let e=t;for(;e&&!O2(n,e);)e=Zt(e);return e}function zy(n){if(ce(n))return!1;const e=nt(n);return Xt(e)}function e1(n,t){let e=t;for(;e&&!O2(n,e);)e=ce(e),e&&zy(e)&&(e=null);return e}const iW=.3;class sW extends be.TypedEmitter{constructor(e){super();m(this,"scrollContainer");m(this,"scrollEventTarget");m(this,"scrollStatus",{curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null});m(this,"handleScroll",He.default(()=>{const e={curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null};let o=rW(this.editor);if(o&&(o=Vm(o)),!o||!this.scrollContainer){this.setStatus(e);return}if(zy(o)&&(o=Zt(o)),!o){this.setStatus(e);return}if(O2(this.editor,o)){e.curHeadingBlock=o,e.previousHeadingBlock=e1(this.editor,o),e.nextHeadingBlock=_2(this.editor,o),this.setStatus(e);return}const r=this.scrollContainer.getBoundingClientRect(),i=_2(this.editor,o);if(i){const l=i.getBoundingClientRect();if(l.top>r.top&&l.top<r.top+r.height*iW){e.curHeadingBlock=i,e.previousHeadingBlock=e1(this.editor,i),e.nextHeadingBlock=_2(this.editor,i),this.setStatus(e);return}e.nextHeadingBlock=i}const s=e1(this.editor,o);s&&(e.curHeadingBlock=s,e.previousHeadingBlock=e1(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=oo(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 F2{constructor(t,e){m(this,"suggest");m(this,"onClose",()=>{this.editor.focus()});m(this,"onShow",(t,e,o,r)=>{const i=this.editor.getBlockByIndex(e,o);if(!ro(i)){const s=ot(nt(i));if(s&&Dt(s)==="code")return!1}return!0});m(this,"onClickItem",(t,e,o)=>{const r=e.data,i={id:K(),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,a=this.editor.getBlockById(l.blockId);this.editor.insertBoxToBlock(a,l.offset,i)});m(this,"queryItems",async(t,e)=>(await this.options.queryUsers(this.editor,e)).map(i=>{const s=Qd(i.displayName);return{id:i.userId,name:i.displayName,icon:i.avatarUrl?`<img src="${i.avatarUrl}" class="mention-user-avatar">`:`<span style="background: ${s}" class="mention-user-avatar-string">${Zd(i.displayName,1)}</span>`,element:i.element,data:i,subText:i.email}}));this.editor=t,this.options=e,this.suggest=new Np(t,{id:"editor-mention",trigger:["@"],autoDeleteTrigger:!0,showLoading:!0,enableFirstBlock:e.enableFirstBlock,onShow:this.onShow,onClickItem:this.onClickItem,queryItems:this.queryItems,onClose:this.onClose})}destroy(){}}S("mathjax-box");function lW(n,t,e,o){const r=o,i=w("a",["mention-container"],e);w("span",["mention-name"],i,`@${r.text}`),i.setAttribute("data-mention-id",r.mentionId)}function cW(n,t,e){}function aW(n,t,e,o){return`@${t.text}`}function uW(){return{abstract:R.t("mention.abstract")}}const P2={boxType:"mention",updateBoxContent:lW,handleClickBox:cW,convertTo:aW,getBoxProperties:uW};function dW(n){const t=w("div",["mention-button-wrap"],null),e=ji("mention-button",R.t("list.mention.tooltip"),JL,[],n.clientId);return t.appendChild(e),t}class hW{constructor(t){m(this,"mentionButton");m(this,"handleHoveringBlock",t=>{var e;!this.editor.isWritable()||(t&&this.shouldBlockShowMention(t)?le(t).appendChild(this.mentionButton):(e=this.mentionButton)==null||e.remove())});m(this,"handleMouseDown",(t,e)=>{e.preventDefault(),e.stopPropagation();const o=ot(this.mentionButton);if(!o||!tt(t,o))return;const r=t.selection.range.focus;if(!r.isSimple())return;let i;t.selection.focusedBlock!==o?i=ut(t,o):i=r.offset,setTimeout(()=>{const s=t.insertTextToBlock(o,i,"@");i+=1;const l=re(xn(s,i).left);this.editor.selection.selectBlock(o,i),this.editor.focus(),t.getCustom("mention").suggest.popup(o,i,l,"@")})});m(this,"destroy",()=>{pe.get(this.editor).removeListener("change",this.handleHoveringBlock)});this.editor=t,this.mentionButton=dW(t),pe.get(this.editor).addListener("change",this.handleHoveringBlock),t.domEvents.addEventListener(this.mentionButton,"mousedown",this.handleMouseDown)}shouldBlockShowMention(t){if(!tt(this.editor,t)||!Ht(t))return!1;const e=Zn(t);return!(e==="ordered"||e==="unordered")}}const tot="",fW={mention:{abstract:"\u6210\u5458"}},mW={mention:{abstract:"Member"}},gW={mention:{abstract:"\u30E1\u30F3\u30D0\u30FC"}};R.mergeLang({"zh-CN":fW,"en-US":mW,"ja-JP":gW});const pW={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"}},CW={templates:{title:"Choose a template",create:"New template",choose:"All templates",customizedMark:"Custom"}},AW={templates:{title:"\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8\u3092\u9078\u629E",create:"\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8\u3092\u65B0\u898F\u4F5C\u6210",choose:"\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8\u4E00\u89A7",customizedMark:"\u30AB\u30B9\u30BF\u30E0"}};R.mergeLang({"zh-CN":pW,"en-US":CW,"ja-JP":AW});const eot="",bW="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjEyMCIgaGVpZ2h0PSIxMjAiIHZpZXdCb3g9IjAgMCAxMjAgMTIwIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cmVjdCB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTQ4IDU5QzQ4IDU0LjU4MTcgNTEuNTgxNyA1MSA1NiA1MUg5M0M5OC41MjI4IDUxIDEwMyA1NS40NzcyIDEwMyA2MVY4OEMxMDMgOTEuODY2IDk5Ljg2NiA5NSA5NiA5NUg1NkM1MS41ODE3IDk1IDQ4IDkxLjQxODMgNDggODdWNTlaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGQ9Ik0xOCA2NEMxOCA2Mi4zNDMxIDE5LjM0MzEgNjEgMjEgNjFINTZDNjAuNDE4MyA2MSA2NCA2NC41ODE3IDY0IDY5VjgzQzY0IDg1LjIwOTEgNjIuMjA5MSA4NyA2MCA4N0gyNkMyMS41ODE3IDg3IDE4IDgzLjQxODMgMTggNzlWNjRaIiBmaWxsPSIjRUFFNEY2Ii8+CjxyZWN0IHg9IjI0IiB5PSIzMSIgd2lkdGg9IjY1IiBoZWlnaHQ9IjUwIiByeD0iNSIgZmlsbD0iIzk5QzdGMiIvPgo8cmVjdCB4PSIzMy41IiB5PSI0MyIgd2lkdGg9IjQ2IiBoZWlnaHQ9IjUiIHJ4PSIyLjUiIGZpbGw9IndoaXRlIi8+CjxyZWN0IHg9IjMzLjUiIHk9IjU0IiB3aWR0aD0iNDYiIGhlaWdodD0iNSIgcng9IjIuNSIgZmlsbD0id2hpdGUiLz4KPHJlY3QgeD0iMjQiIHk9IjMxIiB3aWR0aD0iNjUiIGhlaWdodD0iNTAiIHJ4PSI1IiBzdHJva2U9IiNGOEY4RjgiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik01MCA4NS4yNjhDNTMuODI2MyA4My4wNTg5IDU1LjEzNzMgNzguMTY2MiA1Mi45MjgyIDc0LjMzOThMNjMuMzIwNSA2OC4zMzk4QzY4Ljg0MzMgNzcuOTA1NyA2NS41NjU4IDkwLjEzNzUgNTYgOTUuNjYwNEM0Ni40MzQxIDEwMS4xODMgMzQuMjAyMyA5Ny45MDU3IDI4LjY3OTQgODguMzM5OEwzOS4wNzE3IDgyLjMzOThDNDEuMjgwOSA4Ni4xNjYyIDQ2LjE3MzYgODcuNDc3MiA1MCA4NS4yNjhaIiBmaWxsPSIjQUI5M0RDIi8+CjxyZWN0IHg9IjU5IiB5PSI2NSIgd2lkdGg9IjQyIiBoZWlnaHQ9IjI4IiByeD0iNSIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTYzIDg4VjczLjA4MDhDNjMgNzEuNzA5NiA2My4zNjE0IDcwLjY4NjcgNjQuMDg0MSA3MC4wMTJDNjQuODI4NyA2OS4zMzczIDY1Ljg1OCA2OSA2Ny4xNzIgNjlIOTIuODYwOUM5NS42MjAzIDY5IDk3IDcwLjM2MDMgOTcgNzMuMDgwOFY4OEg5My41MTc5TDg3LjM3NDkgODAuNjIyQzg3LjA5MDIgODAuMzE3MyA4Ni43NjE3IDgwLjA4ODggODYuMzg5NCA3OS45MzY0Qzg2LjAxNzEgNzkuNzg0MSA4NS42NDQ4IDc5LjcwNzkgODUuMjcyNSA3OS43MDc5Qzg0LjkwMDIgNzkuNzA3OSA4NC41Mjc5IDc5Ljc4NDEgODQuMTU1NiA3OS45MzY0QzgzLjgwNTIgODAuMDg4OCA4My40NTQ4IDgwLjMxNzMgODMuMTA0MyA4MC42MjJMNzYuNzMxNCA4Ni4yMzcxTDc0LjIwMTkgODMuOTUxOUM3My42MzI1IDgzLjQyOTYgNzMuMDA4NCA4My4xNjg0IDcyLjMyOTUgODMuMTY4NEM3MS42NTA2IDgzLjE2ODQgNzEuMDM3NCA4My40Mjk2IDcwLjQ4OTkgODMuOTUxOUw2Ni40NDkzIDg4SDYzWk03NC40NjQ3IDgwLjYyMkM3NS4zNjI2IDgwLjYyMiA3Ni4xNDAxIDgwLjI5NTUgNzYuNzk3MSA3OS42NDI2Qzc3LjQ3NiA3OC45ODk3IDc3LjgxNTUgNzguMjE3MSA3Ny44MTU1IDc3LjMyNDdDNzcuODE1NSA3Ni40MTA3IDc3LjQ3NiA3NS42MzggNzYuNzk3MSA3NS4wMDY5Qzc2LjE0MDEgNzQuMzU0IDc1LjM2MjYgNzQuMDE2NiA3NC40NjQ3IDczLjk5NDhDNzMuNTQ0OSA3My45NTEzIDcyLjc1NjUgNzQuMjY2OSA3Mi4wOTk1IDc0Ljk0MTZDNzEuNDQyNSA3NS42MTYzIDcxLjExNCA3Ni40MTA3IDcxLjExNCA3Ny4zMjQ3QzcxLjExNCA3OC4yMTcxIDcxLjQ0MjUgNzguOTg5NyA3Mi4wOTk1IDc5LjY0MjZDNzIuNzU2NSA4MC4yOTU1IDczLjU0NDkgODAuNjIyIDc0LjQ2NDcgODAuNjIyWiIgZmlsbD0iI0Y3RDA3RiIvPgo8Y2lyY2xlIGN4PSI5NSIgY3k9IjQyIiByPSIyIiBzdHJva2U9IiM1MEMzOTgiIHN0cm9rZS13aWR0aD0iMiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTk0Ljc1MDEgMjQuNDY4N0wxMDAuNzgxIDI3LjkxNDlMOTQuNzE5IDMxLjQxNDlMOTQuNzUwMSAyNC40Njg3WiIgc3Ryb2tlPSIjNUNBNUVBIiBzdHJva2Utd2lkdGg9IjEuOCIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwNSAzOEMxMDUgMzguNTUyMyAxMDUuNDQ4IDM5IDEwNiAzOUMxMDYuNTUyIDM5IDEwNyAzOC41NTIzIDEwNyAzOFYzNkgxMDlDMTA5LjU1MiAzNiAxMTAgMzUuNTUyMyAxMTAgMzVDMTEwIDM0LjQ0NzcgMTA5LjU1MiAzNCAxMDkgMzRIMTA3VjMyQzEwNyAzMS40NDc3IDEwNi41NTIgMzEgMTA2IDMxQzEwNS40NDggMzEgMTA1IDMxLjQ0NzcgMTA1IDMyVjM0SDEwM0MxMDIuNDQ4IDM0IDEwMiAzNC40NDc3IDEwMiAzNUMxMDIgMzUuNTUyMyAxMDIuNDQ4IDM2IDEwMyAzNkgxMDVWMzhaIiBmaWxsPSIjQUI5M0RDIi8+Cjwvc3ZnPgo=",vW="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgdmlld0JveD0iMCAwIDM3MiAyNzkiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMF8xMjU2XzM3MTY4KSI+CjxyZWN0IHdpZHRoPSIzNzIiIGhlaWdodD0iMjc5IiBmaWxsPSJ3aGl0ZSIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIzOS41NzQ3IiB3aWR0aD0iMTE4LjcyMyIgaGVpZ2h0PSIxNS44Mjk4IiByeD0iNy45MTQ4OSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI3MS4yMzM5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI5MS4wMjE1IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIxMTAuODA5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSI0MC41NjM4IiB5PSIxMzUuNTQzIiB3aWR0aD0iMjkwLjg3MiIgaGVpZ2h0PSIxMDAuOTE1IiByeD0iMi45NjgwOSIgc3Ryb2tlPSIjRUFGM0ZDIiBzdHJva2Utd2lkdGg9IjEuOTc4NzIiLz4KPHBhdGggZD0iTTM5LjU3NDUgMTM4LjUxMUMzOS41NzQ1IDEzNi4zMjUgNDEuMzQ2MyAxMzQuNTUzIDQzLjUzMTkgMTM0LjU1M0gzMjguNDY4QzMzMC42NTQgMTM0LjU1MyAzMzIuNDI2IDEzNi4zMjUgMzMyLjQyNiAxMzguNTExVjE1Mi4zNjJIMzkuNTc0NVYxMzguNTExWiIgZmlsbD0iI0Q2RTlGQSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTg3LjA2MzcgMTY5LjE4MUM4Ny4wNjM3IDE2Ny41NDIgODguMzkyNiAxNjYuMjEzIDkwLjAzMTggMTY2LjIxM0gzMTcuNTg1QzMxOS4yMjQgMTY2LjIxMyAzMjAuNTUzIDE2Ny41NDIgMzIwLjU1MyAxNjkuMTgxQzMyMC41NTMgMTcwLjgyIDMxOS4yMjQgMTcyLjE0OSAzMTcuNTg1IDE3Mi4xNDlIOTAuMDMxOEM4OC4zOTI2IDE3Mi4xNDkgODcuMDYzNyAxNzAuODIgODcuMDYzNyAxNjkuMTgxWk0xMDQuODcyIDE5Mi45MjZDMTA0Ljg3MiAxOTEuMjg2IDEwNi4yMDEgMTg5Ljk1NyAxMDcuODQgMTg5Ljk1N0gzMTcuNTg1QzMxOS4yMjQgMTg5Ljk1NyAzMjAuNTUzIDE5MS4yODYgMzIwLjU1MyAxOTIuOTI2QzMyMC41NTMgMTk0LjU2NSAzMTkuMjI0IDE5NS44OTQgMzE3LjU4NSAxOTUuODk0SDEwNy44NEMxMDYuMjAxIDE5NS44OTQgMTA0Ljg3MiAxOTQuNTY1IDEwNC44NzIgMTkyLjkyNlpNMTA3Ljg0IDIxMy43MDJDMTA2LjIwMSAyMTMuNzAyIDEwNC44NzIgMjE1LjAzMSAxMDQuODcyIDIxNi42N0MxMDQuODcyIDIxOC4zMDkgMTA2LjIwMSAyMTkuNjM4IDEwNy44NCAyMTkuNjM4SDMxNy41ODVDMzE5LjIyNCAyMTkuNjM4IDMyMC41NTMgMjE4LjMwOSAzMjAuNTUzIDIxNi42N0MzMjAuNTUzIDIxNS4wMzEgMzE5LjIyNCAyMTMuNzAyIDMxNy41ODUgMjEzLjcwMkgxMDcuODRaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNTEuNDQ2OCAxNjkuMTgxQzUxLjQ0NjggMTY3LjU0MiA1Mi43NzU2IDE2Ni4yMTMgNTQuNDE0OSAxNjYuMjEzSDYwLjM1MUM2MS45OTAzIDE2Ni4yMTMgNjMuMzE5MSAxNjcuNTQyIDYzLjMxOTEgMTY5LjE4MUM2My4zMTkxIDE3MC44MiA2MS45OTAzIDE3Mi4xNDkgNjAuMzUxIDE3Mi4xNDlINTQuNDE0OUM1Mi43NzU2IDE3Mi4xNDkgNTEuNDQ2OCAxNzAuODIgNTEuNDQ2OCAxNjkuMTgxWk01MS40NDY4IDE5Mi45MjZDNTEuNDQ2OCAxOTEuMjg2IDUyLjc3NTcgMTg5Ljk1NyA1NC40MTQ5IDE4OS45NTdINjAuMzUxMUM2MS45OTAzIDE4OS45NTcgNjMuMzE5MSAxOTEuMjg2IDYzLjMxOTEgMTkyLjkyNkM2My4zMTkxIDE5NC41NjUgNjEuOTkwMyAxOTUuODk0IDYwLjM1MTEgMTk1Ljg5NEg1NC40MTQ5QzUyLjc3NTcgMTk1Ljg5NCA1MS40NDY4IDE5NC41NjUgNTEuNDQ2OCAxOTIuOTI2Wk01NC40MTQ5IDIxMy43MDJDNTIuNzc1NyAyMTMuNzAyIDUxLjQ0NjggMjE1LjAzMSA1MS40NDY4IDIxNi42N0M1MS40NDY4IDIxOC4zMDkgNTIuNzc1NyAyMTkuNjM4IDU0LjQxNDkgMjE5LjYzOEg2MC4zNTExQzYxLjk5MDMgMjE5LjYzOCA2My4zMTkxIDIxOC4zMDkgNjMuMzE5MSAyMTYuNjdDNjMuMzE5MSAyMTUuMDMxIDYxLjk5MDMgMjEzLjcwMiA2MC4zNTExIDIxMy43MDJINTQuNDE0OVoiIGZpbGw9IiM5OUM3RjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik02OS4yNTU0IDE2OS4xODFDNjkuMjU1NCAxNjcuNTQyIDcwLjU4NDMgMTY2LjIxMyA3Mi4yMjM1IDE2Ni4yMTNINzguMTU5N0M3OS43OTg5IDE2Ni4yMTMgODEuMTI3OCAxNjcuNTQyIDgxLjEyNzggMTY5LjE4MUM4MS4xMjc4IDE3MC44MiA3OS43OTg5IDE3Mi4xNDkgNzguMTU5NyAxNzIuMTQ5SDcyLjIyMzVDNzAuNTg0MyAxNzIuMTQ5IDY5LjI1NTQgMTcwLjgyIDY5LjI1NTQgMTY5LjE4MVpNNjkuMjU1NCAxOTIuOTI2QzY5LjI1NTQgMTkxLjI4NiA3MC41ODQyIDE4OS45NTcgNzIuMjIzNSAxODkuOTU3SDc4LjE1OTZDNzkuNzk4OSAxODkuOTU3IDgxLjEyNzcgMTkxLjI4NiA4MS4xMjc3IDE5Mi45MjZDODEuMTI3NyAxOTQuNTY1IDc5Ljc5ODkgMTk1Ljg5NCA3OC4xNTk2IDE5NS44OTRINzIuMjIzNUM3MC41ODQyIDE5NS44OTQgNjkuMjU1NCAxOTQuNTY1IDY5LjI1NTQgMTkyLjkyNlpNNzIuMjIzNSAyMTMuNzAyQzcwLjU4NDIgMjEzLjcwMiA2OS4yNTU0IDIxNS4wMzEgNjkuMjU1NCAyMTYuNjdDNjkuMjU1NCAyMTguMzA5IDcwLjU4NDIgMjE5LjYzOCA3Mi4yMjM1IDIxOS42MzhINzguMTU5NkM3OS43OTg5IDIxOS42MzggODEuMTI3NyAyMTguMzA5IDgxLjEyNzcgMjE2LjY3QzgxLjEyNzcgMjE1LjAzMSA3OS43OTg5IDIxMy43MDIgNzguMTU5NiAyMTMuNzAySDcyLjIyMzVaIiBmaWxsPSIjRjdEMDdGIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNOTAuMDMxOCAxODkuOTU4Qzg4LjM5MjYgMTg5Ljk1OCA4Ny4wNjM3IDE5MS4yODYgODcuMDYzNyAxOTIuOTI2Qzg3LjA2MzcgMTk0LjU2NSA4OC4zOTI2IDE5NS44OTQgOTAuMDMxOCAxOTUuODk0SDk1Ljk2OEM5Ny42MDcyIDE5NS44OTQgOTguOTM2MSAxOTQuNTY1IDk4LjkzNjEgMTkyLjkyNkM5OC45MzYxIDE5MS4yODYgOTcuNjA3MiAxODkuOTU4IDk1Ljk2OCAxODkuOTU4SDkwLjAzMThaTTkwLjAzMTkgMjEzLjcwMkM4OC4zOTI3IDIxMy43MDIgODcuMDYzOCAyMTUuMDMxIDg3LjA2MzggMjE2LjY3Qzg3LjA2MzggMjE4LjMwOSA4OC4zOTI3IDIxOS42MzggOTAuMDMxOSAyMTkuNjM4SDk1Ljk2ODFDOTcuNjA3MyAyMTkuNjM4IDk4LjkzNjIgMjE4LjMwOSA5OC45MzYyIDIxNi42N0M5OC45MzYyIDIxNS4wMzEgOTcuNjA3MyAyMTMuNzAyIDk1Ljk2ODEgMjEzLjcwMkg5MC4wMzE5WiIgZmlsbD0iIzkxRDlCRSIvPgo8L2c+CjxkZWZzPgo8Y2xpcFBhdGggaWQ9ImNsaXAwXzEyNTZfMzcxNjgiPgo8cmVjdCB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgZmlsbD0id2hpdGUiLz4KPC9jbGlwUGF0aD4KPC9kZWZzPgo8L3N2Zz4K",Vy=S("templates");function N2(n){const t=n.rootElement.querySelector(":scope .editor-templates");if(!t)return null;const e=t.querySelector(":scope .editor-templates-cards");return g(Vy,e,"no card container"),{root:t,cardContainer:e}}function yW(n){const t=N2(n);if(t)return t.cardContainer.innerHTML="",t;const e=w("div",["editor-templates"],n.rootElement);w("div",["editor-templates-title"],e,R.t("templates.title"));const o=w("div",["editor-templates-cards"],e);return{root:e,cardContainer:o}}function Wy(n,t,e,o,r){var p;const i=(p=n.options.componentsOptions)==null?void 0:p.templates,s=w("div",["editor-template-card",...o],null),l=w("div",["editor-template-thumb-container"],s),a=w("img",["editor-template-thumb"],l);a.src=t,a.style.display="none",a.onerror=()=>{var v;const A=(v=i==null?void 0:i.placeHolderImageSrc)!=null?v:vW;a.src!==A&&(a.src=A)},a.onload=()=>{a.style.display=""};const d=w("div",["editor-template-name"],s),h=w("span",[],d,e);return i!=null&&i.showTemplateTitleAttr&&h.setAttribute("title",e),s.onclick=()=>r(s),s}function kW(n,t){return t.thumbnailUrl?t.thumbnailUrl:n.doc.buildResourceUrl("thumbnail.png")}function wW(n,t){const e=kW(n,t);return Wy(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 BW(n,t){return Wy(n,t,R.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 EW(n,t){var p,A;const e=(p=n.options.componentsOptions)==null?void 0:p.templates;if(!e)return;const r=Ge(n.rootContainer).getBoundingClientRect().width;let i=1;const s=bW,l=N2(n);if(l){if(t!=null&&t.reset){const v=Array.from(l.cardContainer.children),B=l.cardContainer.firstElementChild;if(g(Vy,B,"no first card"),xt(B,"new")||xt(B,"more"))return;const D=window.getComputedStyle(B),T=parseFloat(D.marginLeft),_=parseFloat(D.marginRight),M=B.getBoundingClientRect().width+T+_;i=Math.floor(r/M);const z=Math.max(1,i-1-1),q=v.length-1;v.forEach((rt,ft)=>{ft>z&&ft<q?rt.style.display="none":(ft>=q&&xt(rt,"more"),rt.style.display="")})}return}const a=e.templates,{cardContainer:d}=yW(n);a.forEach((v,B)=>{const D=wW(n,v);if(B>0&&B>=i&&(D.style.display="none"),d.appendChild(D),B===0){const T=window.getComputedStyle(D),_=parseFloat(T.marginLeft),M=parseFloat(T.marginRight),H=D.getBoundingClientRect().width+_+M;i=Math.floor(r/H)-1}});const h=BW(n,s);d.appendChild(h),(A=e==null?void 0:e.onTemplateChooserStatusChanged)==null||A.call(e,n,d,"visible")}const qy=He.default(EW,50);function xW(n){var o,r;const t=N2(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 IW(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 n1(n,t){IW(n.doc.toJSON())?qy(n,t):(qy.cancel(),xW(n))}const TW=800;class DW{constructor(t){m(this,"longPressTimeout",0);m(this,"handleSelectionChange",()=>{});m(this,"handleLongPress",t=>{const e=t.touches[0],o=oh(this.editor,e.clientX,e.clientY);!o||console.log(o)});m(this,"handleTouchStart",t=>{t.touches.length===1&&(this.longPressTimeout=window.setTimeout(()=>{this.handleLongPress(t)},TW))});m(this,"handleTouchEnd",t=>{this.longPressTimeout&&(window.clearTimeout(this.longPressTimeout),this.longPressTimeout=0)});this.editor=t,this.editor.addListener("selectionChanged",this.handleSelectionChange),document.addEventListener("touchstart",this.handleTouchStart),document.addEventListener("touchend",this.handleTouchEnd)}destroy(){this.editor.removeListener("selectionChanged",this.handleSelectionChange),document.removeEventListener("touchstart",this.handleTouchStart),document.removeEventListener("touchend",this.handleTouchEnd)}}const SW=`<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg">
593
+ 2. \u4E8C\u3064\u306E\u30D0\u30FC\u30B8\u30E7\u30F3\u306E\u9593\u306B\u5FA9\u5143\u3055\u308C\u305F\u30D0\u30FC\u30B8\u30E7\u30F3\u304C\u3042\u308B\u5834\u5408\u3001\u3053\u306E\u4E8C\u3064\u306E\u30D0\u30FC\u30B8\u30E7\u30F3\u306F\u6BD4\u8F03\u3067\u304D\u306A\u3044\u3053\u3068\u306B\u306A\u308A\u307E\u3059\u3002`,user:"\u30D0\u30FC\u30B8\u30E7\u30F3\u4F5C\u6210\u8005\uFF1A{name}",auth:"\u3053\u306E\u30B9\u30DA\u30FC\u30B9\u3092\u7DE8\u96C6\u3059\u308B\u6A29\u9650\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u7BA1\u7406\u8005\u306B\u3054\u9023\u7D61\u304F\u3060\u3055\u3044\u3002"},dropdownHeader:"\u73FE\u5728\u306E\u30D0\u30FC\u30B8\u30E7\u30F3\u3068\u6BD4\u8F03\u3067\u304D\u308B\u30D0\u30FC\u30B8\u30E7\u30F3\u3060\u3051\u8868\u793A\u3055\u308C\u307E\u3059",dropdown:{header:"\u6BD4\u8F03\u53EF\u80FD\u306A\u30D0\u30FC\u30B8\u30E7\u30F3"},noVersions:"\u6BD4\u8F03\u53EF\u80FD\u306A\u30D0\u30FC\u30B8\u30E7\u30F3\u306F\u3042\u308A\u307E\u305B\u3093",lastVersion:"\u524D\u306E\u30D0\u30FC\u30B8\u30E7\u30F3",filterMemoed:"\u5099\u8003\u3042\u308A"}};R.mergeLang({"zh-CN":nV,"en-US":oV,"ja-JP":rV});var Ay=(n=>(n.NEW="history-new",n.NEW_CHILD="history-new-child",n.DELETED="history-deleted",n.UPDATED="history-updated",n.HISTORY="history",n))(Ay||{});const Tc="--op-color",Dc="--op-selected-color",Znt="";class iV{constructor(t){m(this,"root");this.content=t;const e=w("div",["editor-dialog-root"],null);e.append(t),this.root=e}show(t=document.body){t.append(this.root)}hide(){this.root.remove()}destroy(){}}function Xs(n){var e;let t;if(n.version!==-1){const o=new Date((e=n.created)!=null?e:n.version);t=_m(o,"YYYY-MM-DD hh:mm")}else t=R.t("version.latest");return t}function Xf(n){return n.source&&typeof n.source=="object"&&!!n.source.restore}const Qnt="";class sV{constructor(t,e){m(this,"textArea");m(this,"warning");m(this,"end",!1);m(this,"root");m(this,"handleBlur",()=>{var t,e;this.end||(e=(t=this.options)==null?void 0:t.onend)==null||e.call(t,this.textArea.value,!1)});m(this,"handleKeyDown",t=>{var e,o,r,i;t.isComposing||(t.key==="Enter"||t.key==="Tab"?(t.preventDefault(),(o=(e=this.options)==null?void 0:e.onend)==null||o.call(e,this.textArea.value,!1),this.end=!0):t.key==="Escape"&&(t.preventDefault(),(i=(r=this.options)==null?void 0:r.onend)==null||i.call(r,this.textArea.value,!0),this.end=!0))});m(this,"handleInput",t=>{const e=t.target,{value:o}=e;o.length>this.maxLength-10?this.warning.innerText=`${o.length}/${this.maxLength}`:this.warning.innerText="",this.autoSize()});var o,r;this.maxLength=t,this.options=e,this.root=w("div",["size-limit-textarea",...(o=e==null?void 0:e.classes)!=null?o:[]],null),this.textArea=w("textarea",["size-limit-textarea-input"],this.root),this.warning=w("div",["size-limit-textarea-warning"],this.root),this.textArea.addEventListener("input",this.handleInput),this.textArea.addEventListener("blur",this.handleBlur),this.textArea.addEventListener("keydown",this.handleKeyDown),this.textArea.maxLength=t,this.textArea.placeholder=(r=e==null?void 0:e.placeholder)!=null?r:""}destroy(){this.textArea.removeEventListener("input",this.handleInput),this.textArea.removeEventListener("blur",this.handleBlur),this.textArea.removeEventListener("keydown",this.handleKeyDown)}setValue(t){this.textArea.value=t,this.autoSize()}autoSize(){const t=Math.max(this.textArea.scrollHeight,60);this.textArea.style.height="auto",this.textArea.style.height=`${t}px`}resetSize(){this.textArea.style.height="auto";const t=Math.max(this.textArea.scrollHeight,60);this.textArea.style.height=`${t}px`}focus(){this.textArea.focus(),this.end=!1}}const Ynt="",{t:Qn}=R,by=S("version-list");class lV{constructor(t){m(this,"versionsList");m(this,"versionsListHeader");m(this,"versionFilterToolbar");m(this,"memoInput",null);m(this,"selectedVersion",0);m(this,"handleClickVersionItem",t=>{const e=t.target,o=e.closest(".version-item");if(!this.isVersionElement(o))return;const r=xt(o,"active");if(r&&e.closest(".version-item-memo")&&this.options.enableEdit){this.editItemMemo(o);return}const i=this.getVersionFromElement(o);if(this.setActiveItem(o),e.closest(".add-memo-button")&&this.options.enableEdit){this.handleAddMemo(i,o);return}if(e.closest(".revert-button")&&this.options.enableEdit){this.handleRevert(i,o);return}if(r)return;const{onSelectVersion:s}=this.options;s(i)});m(this,"handleEndEditItemMemo",(t,e)=>{var r,i;const o=(r=this.memoInput)==null?void 0:r.root.closest(".version-item");if(this.isVersionElement(o)&&(et(o,"editing"),!e)){const s=this.getVersionFromElement(o),l=t.replace(/[\n\r]+/g," ");if(((i=s.extra)==null?void 0:i.memo)!==l){s.extra={memo:l},this.options.versionHelper.updateVersionExtra(s.version,s.tagId,s.extra).then(()=>{var d,h;(h=(d=this.options).onMemoChanged)==null||h.call(d,s)});const a=o.querySelector(".version-item-memo");g(by,a,"no memo element"),a.textContent=l}}setTimeout(()=>{var s;(s=this.memoInput)==null||s.root.remove()})});m(this,"handleRevert",(t,e)=>{const{onRevert:o}=this.options;o(t)});m(this,"handleFilterClick",(t,e)=>{let o=this.options.versions;e.id==="memoed"&&(o=o.filter(i=>{var s;return!!((s=i.extra)!=null&&s.memo)}));const r=this.createVersionItems(o,e.id);this.versionsList.innerHTML="",this.versionsList.append(r),this.versionFilterToolbar.updateItems(this.getFilterItems(e.id)),this.updateHeaderCount(o.length)});var d,h;this.options=t;const{versions:e}=t,o=w("div",["version-list-header"],null),r=Qn("version.versionList",{count:`${e.length}`});w("span",["version-count"],o,r);const i=w("div",["version-list-filter"],o);this.versionFilterToolbar=new rM(i,this.getFilterItems("all"),{tooltipId:"version-viewer"}),this.versionFilterToolbar.addListener("click",this.handleFilterClick),this.selectedVersion=t.selectedVersion||((d=e[0])==null?void 0:d.version)||-1;const s=w("div",["version-list-content"],null),l=this.createVersionItems(e,"all");s.append(l),this.versionsList=s,this.versionsListHeader=o,s.onclick=this.handleClickVersionItem;const a=this.activeVersion;a&&((h=this.options)==null||h.onSelectVersion(a))}getFilterItems(t){return[{id:"filter",name:Qn(t==="all"?"version.filter.all":"version.filter.memoed"),dropdown:!0,manualShowChildren:!0,childrenPlacement:"bottom-start",children:[{id:"all",states:t==="all"?["checked"]:[],name:Qn("version.filter.allVersions")},{id:"memoed",states:t==="memoed"?["checked"]:[],name:Qn("version.filter.memoVersions")}]}]}createVersionItems(t,e){const o=document.createDocumentFragment();if(t.length===0){const i=w("div",["version-list-empty"],o);return i.textContent=Qn("version.noMemoedVersion"),o}const r=(i,s,l,a=!1)=>{var T,_;const d=w("div",["version-item"],o);d.versionData=i,s&&W(d,"child"),i.version===this.selectedVersion&&W(d,"active");const h=w("div",["version-item-title"],d);w("div",["version-item-date"],h,Xs(i)),a&&w("div",["version-item-latest"],h,Qn("version.latest")),w("div",["spacer"],h);const p=w("div",["version-actions"],h),A=w("button",["add-memo-button"],p);if(A.textContent=Qn("version.memo"),this.options.enableEdit||(W(A,"disabled"),A.setAttribute("data-editor-tooltip-common",R.t("version.tooltip.auth"))),!a){const M=w("button",["revert-button"],p);M.textContent=Qn("version.revert"),this.options.enableEdit||(W(M,"disabled"),M.setAttribute("data-editor-tooltip-common",R.t("version.tooltip.auth")))}let v="";if(typeof i.source=="object"&&((T=i.source)==null?void 0:T.restore)){const M=i.source.restore,H=this.options.versions.find(q=>q.version==M),z=H?Xs(H):Qn("version.unknown");v=Qn("version.restoreFrom",{from:z})}w("div",["version-item-restore-from"],d,v),w("div",["version-item-memo"],d,((_=i.extra)==null?void 0:_.memo)||"");const B=w("ul",["version-item-authors"],d),D=M=>{const H=w("li",["version-item-author"],B),z=w("span",["version-item-author-mark"],H);z.style.background=this.options.getMarkColor(M),w("span",["version-item-author-name"],H,M.displayName).setAttribute("data-editor-tooltip-common",R.t("version.tooltip.user",{name:M.displayName}))};if(this.options.useCreatedBy)if(i.createdBy){const M=i.createdBy;D(M)}else i.authors&&i.authors.length>0&&i.authors.forEach(M=>{D(M)});else if(i.authors&&i.authors.length>0)i.authors.forEach(M=>{D(M)});else if(i.createdBy){const M=i.createdBy;D(M)}};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)})}),o}isVersionElement(t){return t?xt(t,"version-item"):!1}getVersionFromElement(t){return t.versionData}get activeVersion(){return this.options.versions.find(t=>t.version===this.selectedVersion)}setActiveItem(t){if(xt(t,"active"))return;const e=this.versionsList.querySelector(".version-item.active");e&&et(e,"active"),W(t,"active"),this.selectedVersion=this.getVersionFromElement(t).version}handleAddMemo(t,e){this.editItemMemo(e)}editItemMemo(t){var o;this.memoInput||(this.memoInput=new sV(256,{onend:this.handleEndEditItemMemo,classes:["memo-input"],placeholder:Qn("version.textarea.placeholder")}));const e=t.querySelector(".version-item-restore-from");g(by,e,"no title element"),e.insertAdjacentElement("afterend",this.memoInput.root),W(t,"editing"),this.memoInput.setValue(((o=t.versionData.extra)==null?void 0:o.memo)||""),this.memoInput.resetSize(),this.memoInput.focus()}updateHeaderCount(t){const e=this.versionsListHeader.querySelector(".version-count");e&&(e.textContent=Qn("version.versionList",{count:`${t.toString()}`}))}getVersionItemByVersionNum(t){const e=Array.from(this.versionsList.children).find(o=>o.versionData.version===t);return this.isVersionElement(e)?e:null}selectVersionByVersionNum(t){const e=this.getVersionItemByVersionNum(t);return e?(this.setActiveItem(e),this.getVersionFromElement(e)):null}render(t){t.innerHTML="",t.append(this.versionsListHeader,this.versionsList)}destroy(){this.versionsList.onclick=null,this.versionFilterToolbar.destroy()}}class cV{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(){}}async function aV(n,t,e){for(const o of e){const r=new cV(n,o.user);t.parseHistoryData(o,r)}}const An=S("split-text-actions");function vy(n){return n.length>2?!1:n.length===1?n[0].insert!==void 0:(g(An,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].insert!==void 0)}function yy(n){return n.length>2?!1:n.length===1?n[0].delete!==void 0:(g(An,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].delete!==void 0)}function ky(n){return n.length>2?!1:n.length===1?n[0].insert===void 0&&n[0].delete===void 0&&n[0].attributes!==void 0:(g(An,n.length===2,`invalid text actions: ${JSON.stringify(n)}`),n[0].retain===void 0?!1:n[1].attributes!==void 0)}function uV(n){const t=[],e=mt.default(n);if(e.length===0)return[];if(e.length===1)return[n];if(e.length===2&&(yy(n)||vy(n)||ky(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){g(An,i.retain>0,`invalid text op: ${JSON.stringify(i)}`),g(An,e.length>1,`invalid text op: ${JSON.stringify(i)}`);const s=e[1];g(An,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:(g(An,s.attributes!==void 0,`invalid next text op: ${JSON.stringify(s)}`),g(An,s.retain!==void 0,`invalid next text op: ${JSON.stringify(s)}`),r+=s.retain),e.splice(0,2)}else g(An,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&&(g(An,i.attributes!==void 0,`invalid next text op: ${JSON.stringify(i)}`),r+=i.retain),i.insert&&(r+=i.insert.length)}return t}function wy(n){if(g(An,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 g(An,typeof t=="number"&&t>0,`invalid retain: ${JSON.stringify(n)}`),t}let By=0;function dV(n,t,e){const o=By;By+=1;const r=re(n);return{insert:" ",attributes:{box:!0,id:K(),type:"history-deleted-box",user:e,created:Date.now(),text:r,deletedOffset:t,deletedOrder:o}}}function hV(n,t,e){const o=wy(t),r=t.length===1?t[0].delete:t[1].delete;g(An,typeof r=="number",`not a delete op: ${JSON.stringify(t)}`);const{left:i,middle:s,right:l}=ze(n,o,r),a=dV(s,o,e);return[...i,a,...l]}function fV(n,t,e){const o=wy(t),r=t.length===1?t[0].insert:t[1].insert;g(An,typeof r=="string",`invalid insert op: ${JSON.stringify(t)}`);const i=t.length===1?t[0].attributes:t[1].attributes,l=uh([{insert:r,attributes:i}],"insertedBy",e);return Hr(n,o,l,null)}function mV(n,t,e){const o=uV(t);let r=n;for(const i of o)yy(i)?r=hV(r,i,e):vy(i)?r=fV(r,i,e):(g(An,ky(i),`unknown op: ${JSON.stringify(i)}`),r=ln.apply(r,i));return r}const gV=S("history-update-block-text");function Ey(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+=ah(r)}),t.sort((r,i)=>i.offset-r.offset),{deletedBoxes:t,newText:e}}function pV(n,t,e){let o=n;return t.forEach(r=>{const i=ln.transformCursor(r.offset,e,!1);o=Hr(o,i,[{insert:" ",attributes:r.boxData}],null)}),o}function CV(n){n.sort((t,e)=>t.boxData.deletedOffset!==e.boxData.deletedOffset?t.boxData.deletedOffset-e.boxData.deletedOffset:t.boxData.deletedOrder-e.boxData.deletedOrder)}function AV(n){if(n.length<=1)return n;const t=n[0].offset;n.forEach(e=>{g(gV,e.offset===t,`invalid boxes group, ${JSON.stringify(n)}`)}),CV(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 bV(n){let{newText:t,deletedBoxes:e}=Ey(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,a)=>l.boxData.deletedOffset-a.boxData.deletedOffset)}),Array.from(o.values()).sort((i,s)=>s[0].offset-i[0].offset).forEach(i=>{const s=i[0].offset;AV(i).reverse().forEach(l=>{t=Hr(t,s,[{insert:" ",attributes:l.boxData}],null)})}),t}function vV(n,t,e){let{newText:o,deletedBoxes:r}=Ey(n);return o=mV(o,t,e),o=pV(o,r,t),o=bV(o),o}const Ar=S("history-doc");function br(n){g(Ar,!1,"no local actions for history doc")}class yV extends fa{constructor(t,e){super(),this.externalDoc=t,this.docObject=e}beginBatchUpdate(){return 0}endBatchUpdate(){return 0}toJSON(){return mt.default(this.docObject)}getContainerBlocks(t){return this.docObject.blocks[t]}getBlockData(t,e){const o=this.getContainerBlocks(t);g(Ar,o,`no container data: ${t}`);const r=o[e];return g(Ar,r,`no block data: ${e}`),r}localUpdateBlockText(){br()}localUpdateBlockData(){br()}localInsertBlock(){br()}localDeleteBlock(){br()}localInsertChildContainer(){br()}localDeleteChildContainers(){br()}uploadResource(){br()}async addResources(t){br()}getServerMeta(){var t,e,o;return(o=(e=(t=this.externalDoc).getServerMeta)==null?void 0:e.call(t))!=null?o:{}}buildResourceUrl(t){return this.externalDoc.buildResourceUrl(t)}request(){br()}broadcastMessage(){br()}getUser(){return{permission:"w",userId:"-",displayName:"-",avatarUrl:"-",rainbowIndex:0}}getRemoteUsers(){return new _h}destroy(){this.clearCallbacks()}transformBlockIndex(t,e,o){const r=this.docObject.blocks[t];g(Ar,r,`no container blocks: ${t}`);let i=0;for(let s=0;s<r.length;s++)if(!r[s].deletedBy){if(i===e)return s;i++}return o&&g(Ar,!1,`invalid block index: ${e}, blocks: ${JSON.stringify(r)}`),g(Ar,i===e,`invalid block index: ${e}, blocks: ${JSON.stringify(r)}`),r.length}onDeleteBlock(t,e,o){const r=this.transformBlockIndex(t,e,!0),s=this.docObject.blocks[t][r];g(Ar,!s.deleted,`block has already deleted: ${t}/${e}`),s.deletedBy=o,this.callbacks.forEach(l=>{var a;return(a=l.onUpdateBlockData)==null?void 0:a.call(l,t,r,{insert:{},delete:[]},!0)})}onInsertBlock(t,e,o,r){const i=this.transformBlockIndex(t,e,!1),s=this.docObject.blocks[t],l=mt.default(o);l.insertedBy=r,s.splice(i,0,l),this.callbacks.forEach(a=>{var d;return(d=a.onInsertBlock)==null?void 0:d.call(a,t,i,l,!0)})}onUpdateBlockText(t,e,o,r){const i=this.transformBlockIndex(t,e,!0),l=this.docObject.blocks[t][i];g(Ar,!l.deleted,`block has already deleted: ${t}/${e}`);const a=l.text;g(Ar,a,`no text for block: ${JSON.stringify(l)}`);const d=vV(a,o,r);l.text=d,this.callbacks.forEach(h=>{var p;return(p=h.onUpdateBlockText)==null?void 0:p.call(h,t,i,o,!0)})}onUpdateBlockData(t,e,o,r){const i=this.transformBlockIndex(t,e,!0),s=this.docObject.blocks[t],l=s[i];g(Ar,!l.deleted,`block has already deleted: ${t}/${e}`);const a=mt.default(l);a.updatedBy=r,o.delete.forEach(d=>delete a[d]),Object.entries(o.insert).forEach(([d,h])=>{a[d]=h}),s[i]=a,this.callbacks.forEach(d=>{var h;return(h=d.onUpdateBlockData)==null?void 0:h.call(d,t,i,o,!0)})}onCreateContainer(t,e,o){this.docObject.blocks[t]=mt.default(e),this.callbacks.forEach(r=>{var i;return(i=r.onInsertChildContainer)==null?void 0:i.call(r,t,e,!0)})}}const{t:xy}=R;function Sc(n,t){return t==="insert"?xy("version.insert",{name:n.displayName}):xy("version.delete",{name:n.displayName})}function tl(n,t){const{userId:e}=t;return["flag","selection"].reduce((r,i)=>{const s=n.getRemoteUsers().getFixedUserColor(e,i);return r[i]=s,r},{})}class kV{renderText(t,e,o){if(!o.box&&o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=tl(t.doc,o.insertedBy);return{classes:["history-inserted-text"],attributes:{"history-inserted-by":r.displayName,"data-op-description":Sc(r,"insert")},styles:{[Tc]:i,[Dc]:s}}}return{}}renderBlock(t,e,o){if(o.deletedBy){const r=o.deletedBy,{flag:i,selection:s}=tl(t.doc,r);return{classes:["history-deleted-block"],attributes:{"history-deleted-by":r.displayName,"data-op-description":Sc(r,"delete")},styles:{[Tc]:i,[Dc]:s}}}if(o.insertedBy){const r=o.insertedBy,{flag:i,selection:s}=tl(t.doc,r);return{classes:["history-inserted-block"],attributes:{"history-inserted-by":r.displayName,"data-op-description":Sc(r,"insert")},styles:{[Tc]:i,[Dc]:s}}}return{}}updateBlock(t,e,o,r){if(r.deletedBy){const i=r.deletedBy,{flag:s,selection:l}=tl(t.doc,i);W(o,"history-deleted-block"),bm(o,{"history-inserted-by":i.displayName,"data-op-description":Sc(i,"delete")}),vm(o,{[Tc]:s,[Dc]:l});return}if(r.insertedBy){const i=r.insertedBy,{flag:s,selection:l}=tl(t.doc,i);W(o,"history-inserted-block"),bm(o,{"history-inserted-by":i.displayName,"data-op-description":Sc(i,"insert")}),vm(o,{[Tc]:s,[Dc]:l})}}}const Iy=S("history-deleted-box");function wV(n,t,e,o){const r=o;g(Iy,r.text,`no text for text box data: ${JSON.stringify(o)}`),g(Iy,typeof r.text=="string",`invalid text type for text box data: ${JSON.stringify(o)}`);const i=w("span",["history-deleted-box"],e,r.text),s=r.user,{flag:l,selection:a}=tl(n.doc,s);i.setAttribute("history-deleted-by",s.displayName),i.setAttribute("data-op-description",Sc(s,"delete")),i.style.setProperty(Tc,l),i.style.setProperty(Dc,a)}function BV(n,t,e,o){return t.text}const EV={boxType:"history-deleted-box",updateBoxContent:wV,convertTo:BV},Jnt="",xV=S("versions-dropdown"),Ty=(n,t)=>{if(!t)return n;let e="";const o=t.length,r=t.toLocaleLowerCase();let i=0;for(i=0;i<=n.length-o;i){let s=n.substring(i,i+o);if(s.toLocaleLowerCase()===r){i+=o;const l=n.charAt(i);let a=!1;s.endsWith(" ")&&(a=!0,s=s.trimEnd()),e+=`<span class="highlight">${s}${l===" "||a?"&nbsp":""}</span>`}else e+=n.charAt(i),i++}return i<n.length&&(e+=n.substring(i)),e};class IV{constructor(t,e){m(this,"dropdown");m(this,"versions",[]);m(this,"currentVersion",null);m(this,"compareWithVersion",null);m(this,"filterMemoed",!1);m(this,"keywords","");m(this,"createFilterMemoedFilterItem",t=>{const e=w("div",["filter-memoed-version-item"],null);t&&w("div",["filter-item-info"],e,R.t("version.dropdown.header"));const o=w("div",["filter-item-input-container"],e),r=w("input",["filter-item-input"],o);r.id="filter-item-input",r.type="checkbox";const i=w("label",["filter-item-label"],o,R.t("version.filterMemoed"));return i.htmlFor=r.id,r.onchange=this.handleInputChange,r.checked=this.filterMemoed,e});m(this,"filterItems",(t,e)=>{var i,s;if(this.keywords=e,!e)return!0;if(t.id==="section")return!1;const o=e.toLocaleLowerCase();if(t.name.toLocaleLowerCase().indexOf(o)!==-1)return!0;const r=t.data;return!!(r&&((i=r.extra)==null?void 0:i.memo)&&((s=r.extra)==null?void 0:s.memo.toLocaleLowerCase().indexOf(o))!==-1)});m(this,"handleClose",()=>{});m(this,"handleClear",()=>{this.options.onCompareWithVersion(null)});m(this,"handleClickItem",t=>{const e=t.data,o=Xs(e);this.dropdown.setText(o),this.options.onCompareWithVersion(e)});m(this,"handleInputChange",t=>{const e=t.target;this.filterMemoed=e.checked,this.resetItems()});this.options=e,this.dropdown=new Rp(t,{placeholder:R.t("version.noSelectedVersion"),emptyPlaceholder:R.t("version.noFilterVersion"),popupId:"versions-dropdown-popup",header:this.createHeader(),filter:this.filterItems,onClose:this.handleClose,onClickItem:this.handleClickItem,onClear:this.handleClear,highlight:!0})}createHeader(){const t=w("div",["versions-dropdown-header"],null),e=w("span",["versions-dropdown-header-info"],t);e.innerHTML=R.t("version.dropdownHeader");const o=w("span",["versions-dropdown-header-icon"],t);return o.setAttribute("data-editor-tooltip-common",R.t("version.tooltip.help")),o.setAttribute("data-editor-tooltip-placement","right"),o.innerHTML=fv,o.onclick=this.options.onHelp,t}setVersions(t){this.versions=t}setCurrentVersion(t,e){this.dropdown.setText(""),this.dropdown.setLabels([]),e&&(this.dropdown.setText(Xs(e)),(e.version===-1||e.version===this.versions[0].version)&&this.dropdown.setLabels([R.t("version.latest")])),this.currentVersion=t,this.compareWithVersion=e!=null?e:null,this.resetItems()}resetItems(){var A;if(this.versions.length===0)return;const t=this.currentVersion;if(!t)return;const e=t.version===-1?0:this.versions.findIndex(v=>v.version===t.version);g(xV,e!==-1,"version not found");const o=this.versions[0],r=v=>{var H;const B=v.data,D=w("div",["version-item-container"],null),T=w("div",["version-item-line1"],D),_=v.value==="last-version"?R.t("version.lastVersion"):Xs(B),M=w("div",["version-item-name"],T);if(this.keywords?M.innerHTML=Ty(_,this.keywords):M.innerText=_,B.version===o.version&&w("div",["version-item-latest"],T,R.t("version.latest")),(H=B.extra)!=null&&H.memo){const z=w("div",["version-item-line2"],D),q=w("div",["version-item-memo"],z,B.extra.memo);this.keywords?q.innerHTML=Ty(B.extra.memo,this.keywords):q.innerText=B.extra.memo,q.setAttribute("data-editor-tooltip-common",B.extra.memo),q.setAttribute("data-editor-tooltip-placement","bottom")}return D.onclick=()=>{this.handleClickItem(v),this.dropdown.close()},D},i=[],s=this.versions[e+1],l=s&&!Xf(t);if(l){const v={id:"section",value:"last-version",name:"Last version",data:s,element:r};i.push(v)}let a=e;for(let v=e-1;v>=0;v-=1){const B=this.versions[v];if(Xf(B))break;a=v}let d=e;if(!Xf(t))for(let v=e+1;v<this.versions.length;v+=1){const B=this.versions[v];if(d=v,Xf(B))break}let h=!1;const p=[];for(let v=a;v<=d;v+=1){const B=this.versions[v];if(B.version!==t.version&&B.version!==(s==null?void 0:s.version)&&(!this.filterMemoed||((A=B.extra)==null?void 0:A.memo))){h=!0;let D=Xs(B),T=`${B.version}`;v===e+1&&(D="Previous version",T="prev-version");const _={id:T,name:D,data:B,element:r};p.push(_)}}if((l||h||this.filterMemoed)&&i.push({id:"section",name:"",element:this.createFilterMemoedFilterItem(i.length>0&&l),states:["disabled"]}),i.push(...p),!h){const v={id:"section",name:"No versions",states:["disabled"],element:w("span",["version-item-empty"],null,R.t("version.noVersions"))};i.push(v)}this.dropdown.updateItems(i)}}class TV{constructor(t,e){m(this,"left");m(this,"right");m(this,"dropdown");const o=w("div",["version-info-container"],t);this.left=w("div",["version-info-left"],o),this.dropdown=new IV(o,e),this.right=w("div",["version-info-right"],o)}setVersion(t,e,o){const r=`<span class="version-item-latest">${R.t("version.latest")}</span>`,i=`${Xs(t)}${o?r:""}`;this.left.innerHTML=R.t("version.versionInfoLeft",{versionName:i}),this.right.innerHTML=R.t("version.versionInfoRight",{versionName:i}),this.dropdown.setCurrentVersion(t,e)}}const es=S("version-dialog");class Dy{constructor(t,e){m(this,"dialog",null);m(this,"oldViewer",null);m(this,"versionOptions");m(this,"versionList",null);m(this,"provider");m(this,"versions",[]);m(this,"components");m(this,"handleRevert",async t=>{var o,r,i;g(es,this.versionList,"The versionList did not render");const e=t!=null?t:(o=this.versionList)==null?void 0:o.activeVersion;g(es,e,`The version: ${e} is invalid`),!(((r=this.versionOptions)==null?void 0:r.onBeforeRevert)&&await this.versionOptions.onBeforeRevert(e))&&(await this.versionHelper.revertVersion(e.version),(i=this.dialog)==null||i.hide())});m(this,"handleSelectVersion",t=>{g(es,t,`The version: ${t} is invalid`),this.viewVersion(t)});m(this,"handleCompareWithVersion",t=>{var o;const e=(o=this.versionList)==null?void 0:o.activeVersion;g(es,e,"no active version"),this.viewVersion(e,t!=null?t:void 0)});m(this,"handleHelp",()=>{var t,e;(e=(t=this.versionOptions)==null?void 0:t.onHelp)==null||e.call(t)});m(this,"viewVersion",async(t,e)=>{var h,p;const o=this.versions[0].version===t.version;if(this.components.infoHeader.setVersion(t,e,o),this.oldViewer&&(this.oldViewer.destroy(),this.oldViewer=null),!this.versionList)return;(h=this.versionOptions)!=null&&h.onWillChangeVersion&&this.versionOptions.onWillChangeVersion(this,t);const r=e==null?void 0:e.version;let i,s;if(r){const A=Math.min(t.version,r),v=Math.max(t.version,r),B=await this.versionHelper.getHistoryData(v,A);i=B.doc,s=B.historyData}else i=await this.versionHelper.getVersion(t.version),s=[];const{editorContainer:l}=this.components;l.innerHTML="";const a=new yV(this.doc,i),d=this.provider.createHistoryEditor(l,a);d.editorBlockRenders.registerRender(new kV),d.editorBoxes.registerBoxClass(EV),W(d.rootElement,Ay.HISTORY);try{await aV(a,this.versionHelper,s)}finally{this.oldViewer=d}(p=this.versionOptions)!=null&&p.onVersionChanged&&this.versionOptions.onVersionChanged(this,d,t)});m(this,"onMemoChanged",t=>{var e,o;(o=(e=this.versionOptions)==null?void 0:e.onMemoChanged)==null||o.call(e,t),this.components.infoHeader.dropdown.resetItems(),this.components.infoHeader.dropdown.setVersions(this.versions)});this.doc=t,this.provider=e;const o=w("div",["version-dialog"],null),r=w("div",["version-viewer"],o),i=new TV(r,{onCompareWithVersion:this.handleCompareWithVersion,onHelp:this.handleHelp}),s=w("div",["version-dialog-editor"],r),l=w("div",["version-list-root"],o);this.components={root:o,editorContainer:s,listContainer:l,infoHeader:i}}get versionHelper(){g(es,this.doc.getVersionHelper,"Can not get getVersionHelper from doc");const t=this.doc.getVersionHelper();return g(es,t,"current doc does not support version"),t}get editor(){return this.oldViewer}renderContent(t){var r,i;const{listContainer:e}=this.components;e.innerHTML="";const o=new lV({enableEdit:((r=this.versionOptions)==null?void 0:r.enableEdit)||!1,versions:t,versionHelper:this.versionHelper,useCreatedBy:(i=this.versionOptions)==null?void 0:i.useCreatedBy,onSelectVersion:this.handleSelectVersion,onRevert:this.handleRevert,onMemoChanged:this.onMemoChanged,getMarkColor:s=>{const{flag:l}=tl(this.doc,s);return l}});o.render(e),this.versionList=o}initViewVersion(){var t;if(g(es,this.versionList,"no versionList"),(t=this.versionOptions)!=null&&t.initSelectedVersion){const{initSelectedVersion:e}=this.versionOptions,o=this.versionList.selectVersionByVersionNum(e);g(es,o,`version ${e} not found`),this.viewVersion(o)}else{const e=this.versionList.activeVersion;e&&this.viewVersion(e)}}async show(t){if(this.versionOptions={...this.versionOptions,...t},this.versions=await this.versionHelper.getVersions(),this.versionOptions.onVersionsLoaded&&this.versionOptions.onVersionsLoaded(this,this.versions),this.components.infoHeader.dropdown.setVersions(this.versions),this.renderContent(this.versions),this.initViewVersion(),!this.dialog){const{root:e}=this.components;this.dialog=new iV(e)}this.dialog.show(t.container)}destroy(){var t,e;(t=this.dialog)==null||t.destroy(),(e=this.versionList)==null||e.destroy()}}const DV={expandCollapseButton:{tips:"\u5C55\u5F00 / \u6536\u8D77"}},SV={expandCollapseButton:{tips:"Expand / Collapse"}},LV={expandCollapseButton:{tips:"\u5C55\u958B / \u7E2E\u5C0F"}};R.mergeLang({"zh-CN":DV,"en-US":SV,"ja-JP":LV});const Knt="",MV=S("heading-collapse");function S2(n){var e;const t=Number.parseInt((e=n.getAttribute("data-style-heading"))!=null?e:"",10);return g(MV,t,"not a heading block"),t}function fo(n){return!!n.getAttribute("data-style-heading")}function RV(n){return!xt(n,"heading-collapsed")}function el(n){return xt(n,"heading-collapsed")}function Sy(n){if(ce(n))return!1;const e=nt(n);return Xt(e)}const OV=S("heading-collapse");function L2(n){g(OV,fo(n),"not a heading block");const t=[],e=S2(n);let o=Zt(n);for(;o&&!(fo(o)&&S2(o)<=e);)t.push(o),o=Zt(o);return t}function Ly(n,t){if(!ro(t))return;n.selection.selectBlock(t,0),L2(t).forEach(o=>{UC(o)}),W(t,"heading-collapsed")}function Lc(n,t){L2(t).forEach(o=>{zC(o)}),et(t,"heading-collapsed")}function _V(n,t){RV(t)?Ly(n,t):Lc(n,t)}const FV=[kp,wp,Bp,Ep,xp,Ip,Tp,Dp];function PV(n){const t=w("button",["heading-collapse-button"],null);return t.setAttribute(`data-editor-tooltip-${n.clientId}`,R.t("expandCollapseButton.tips")),t.innerHTML=Gh,t}function My(n){return Mf(n).querySelector("button.heading-collapse-button")}function Ry(n,t){My(t)||Sy(t)||!ro(t)||Q0(t,PV(n),-1)}function NV(n){var t;(t=My(n))==null||t.remove()}function Oy(n,t){Mf(t).querySelector("button.heading-collapse-button")||Ry(n,t)}function $V(n){const t=S2(n),e=w("button",["heading-marker"],null);return e.innerHTML=FV[t-1],e}function _y(n){return Mf(n).querySelector("button.heading-marker")}function M2(n){_y(n)||Sy(n)||!ro(n)||Q0(n,$V(n),1)}function Fy(n){const t=_y(n);t==null||t.remove()}function Py(n){Fy(n),fo(n)&&M2(n)}class HV{handleDrop(t,e,o,r){if(Wd(e)||!fo(e)||!el(e))return;const i=L2(e);i.unshift(e);const s=i.reverse();let l=null;return t.doc.beginBatchUpdate(),s.forEach((a,d,h)=>{const p=t.getBlockData(a),A=Fi(t.editorBlocks,t.doc.toJSON(),p),v=t.insertDocAt(o,r,A)[0];d===h.length-1&&(l=v)}),t.doc.endBatchUpdate(),t.doc.beginBatchUpdate(),s.forEach(a=>{t.deleteBlock(a)}),t.doc.endBatchUpdate(),l&&Ly(t,l),!0}}const jV=S("heading-collapse");class R2{constructor(t){m(this,"handleLoad",()=>{this.showCollapseButtons()});m(this,"handleHoverBlock",(t,e)=>{e&&(et(e,"hovering-heading"),fo(e)&&Xt(nt(e))&&(M2(e),el(e)||NV(e))),t&&fo(t)&&Xt(nt(t))&&(W(t,"hovering-heading"),this.editor.readonly||Fy(t),Ry(this.editor,t))});m(this,"handleClick",(t,e)=>{const o=jl(e,"button.heading-collapse-button");if(!o)return;const r=ot(o);!r||(g(jV,fo(r),"not a heading block"),_V(this.editor,r),Oy(this.editor,r))});this.editor=t,t.addListener("load",this.handleLoad),t.addListener("click",this.handleClick),pe.get(t).addListener("change",this.handleHoverBlock),this.showCollapseButtons(),setTimeout(()=>{var o;(o=Su.find(t))==null||o.addHandler(new HV)})}showCollapseButtons(){const t=ve(this.editor.rootContainer).filter(fo);t.length!==0&&(t[0]===Se(this.editor.rootContainer)&&t.splice(0,1),t.forEach(M2))}destroy(){this.editor.removeListener("load",this.handleLoad),this.editor.removeListener("click",this.handleClick)}}function t1(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);el(e)&&Lc(n,e),el(o)&&Lc(n,o)}function UV(n){t1(n);const t=n.getFocusedBlock();!fo(t)||el(t)&&Lc(n,t)}function zV(n){t1(n);const t=n.getFocusedBlock();if(!fo(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===ut(n,t)&&el(t)&&Lc(n,t)}function VV(n){t1(n);const t=n.getFocusedBlock();if(!fo(t))return;const e=n.selection.range.focus;!e.isSimple()||e.offset===0&&el(t)&&Lc(n,t)}class WV{handleBeforeKeyDown(t,e){return xm(e.key)&&t1(t),e.key==="Enter"?(UV(t),!1):e.key==="Delete"?(zV(t),!1):(e.key==="Backspace"&&VV(t),!1)}}class qV{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(!fo(o)){e&&e.delete.includes("heading")&&Py(o);return}xt(o,"hovering-heading")&&Oy(this.editor,o),Py(o)}},100)}}function GV(n){return!!n.heading}function Ny(n){var e;const t=n.heading;return(e=Number.parseInt(`${t}`,10))!=null?e:1}function $y(n,t,e){var i;const o=Ms(n,t.type);let r="";if(o.convertTo){const s=jr();r=o.convertTo(n,t,s,"text",[{containerId:"root",blockIndex:0}]),r=r.replace(/\n/g,"").trim()}else r=re((i=t.text)!=null?i:[]);return{parentNode:e,children:[],text:r,level:Ny(t),block:t}}class Pu{constructor(t){m(this,"nodes",[]);this.editor=t}appendBlock(t){const e=this.findParent(Ny(t),this.nodes);e?e.children.push($y(this.editor,t,e)):this.nodes.push($y(this.editor,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,e){const o=new Pu(t),r=e.blocks.root;for(let i=0;i<r.length;i++){const s=r[i];GV(s)&&o.appendBlock(s)}return o}}class nl extends be.TypedEmitter{constructor(e){super();m(this,"toc");m(this,"updateToc",He.default(()=>{this.updateTocNow()},500));this.editor=e,e.doc.registerCallback(this),setTimeout(()=>{this.updateTocNow()}),this.toc=new Pu(this.editor)}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 nl(e))}static get(e){return e.getCustom("editor-toc")}updateTocNow(){this.toc=Pu.buildToc(this.editor,this.editor.doc.toJSON()),this.emit("change",this.editor,this.toc)}}const Xnt="";function ZV(n){return n.nodes.length===0?!0:n.nodes.length>1?!1:n.nodes[0].children.length===0}function Hy(n,t){t.forEach(e=>{const o=w("div",["toc-node"],n),r=w("div",["toc-title"],o);if(w("span",["toc-text"],r,e.text).setAttribute("data-block-id",e.block.id),e.children.length>0){const s=w("div",["toc-children"],o);Hy(s,e.children)}})}function QV(n,t){const e=jl(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 jy(n,t,e){if(et(t,"loading"),t.innerHTML="",ZV(e)){w("div",["toc-empty-message"],t,R.t("toc.empty"));return}if(e.nodes.length>=1){const[o,...r]=e.nodes,i=[...o.children,...r];Hy(t,i)}op(n,"toc-click-handler",()=>{n.addListener("click",QV)})}class YV{constructor(t){m(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&&jy(t,i,e)})});this.editor=t,nl.register(t).addListener("change",this.handleUpdateToc)}destroy(){nl.register(this.editor).removeListener("change",this.handleUpdateToc)}get toc(){return nl.register(this.editor).toc}}function JV(n,t){const e=w("div",["editor-toc-container"],t),r=n.addCustom("init-editor-toc",()=>new YV(n)).toc;r.nodes.length===0?W(e,"loading"):jy(n,e,r)}function KV(n,t,e,o){return o==="markdown"?"[toc]":""}function XV(n,t,e){const{data:o}=e;if(!o||o.embedType!=="toc"||!tt(n,t))return null;const r={};return{blockData:{id:K(),type:"embed",embedType:"toc",embedData:r}}}const Uy={embedType:"toc",createEmbedContent:JV,convertTo:KV,convertFrom:XV},tW={toc:{empty:"No Toc"}},eW={toc:{empty:"No Toc"}},nW={toc:{empty:"No Toc"}};R.mergeLang({"zh-CN":tW,"en-US":eW,"ja-JP":nW});function oW(n){return!!n.getAttribute("data-style-heading")}function O2(n,t){return oW(t)&&ut(n,t)>0}function rW(n){const t=oo(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=ot(i[s]);if(l&&n.rootContainer.contains(l))return l}o+=10}return null}function _2(n,t){let e=t;for(;e&&!O2(n,e);)e=Zt(e);return e}function zy(n){if(ce(n))return!1;const e=nt(n);return Xt(e)}function e1(n,t){let e=t;for(;e&&!O2(n,e);)e=ce(e),e&&zy(e)&&(e=null);return e}const iW=.3;class sW extends be.TypedEmitter{constructor(e){super();m(this,"scrollContainer");m(this,"scrollEventTarget");m(this,"scrollStatus",{curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null});m(this,"handleScroll",He.default(()=>{const e={curHeadingBlock:null,previousHeadingBlock:null,nextHeadingBlock:null};let o=rW(this.editor);if(o&&(o=Vm(o)),!o||!this.scrollContainer){this.setStatus(e);return}if(zy(o)&&(o=Zt(o)),!o){this.setStatus(e);return}if(O2(this.editor,o)){e.curHeadingBlock=o,e.previousHeadingBlock=e1(this.editor,o),e.nextHeadingBlock=_2(this.editor,o),this.setStatus(e);return}const r=this.scrollContainer.getBoundingClientRect(),i=_2(this.editor,o);if(i){const l=i.getBoundingClientRect();if(l.top>r.top&&l.top<r.top+r.height*iW){e.curHeadingBlock=i,e.previousHeadingBlock=e1(this.editor,i),e.nextHeadingBlock=_2(this.editor,i),this.setStatus(e);return}e.nextHeadingBlock=i}const s=e1(this.editor,o);s&&(e.curHeadingBlock=s,e.previousHeadingBlock=e1(this.editor,s)),this.setStatus(e)},200));this.editor=e}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=oo(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 F2{constructor(t,e){m(this,"suggest");m(this,"onClose",()=>{this.editor.focus()});m(this,"onShow",(t,e,o,r)=>{const i=this.editor.getBlockByIndex(e,o);if(!ro(i)){const s=ot(nt(i));if(s&&Dt(s)==="code")return!1}return!0});m(this,"onClickItem",(t,e,o)=>{const r=e.data,i={id:K(),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,a=this.editor.getBlockById(l.blockId);this.editor.insertBoxToBlock(a,l.offset,i)});m(this,"queryItems",async(t,e)=>(await this.options.queryUsers(this.editor,e)).map(i=>{const s=Qd(i.displayName);return{id:i.userId,name:i.displayName,icon:i.avatarUrl?`<img src="${i.avatarUrl}" class="mention-user-avatar">`:`<span style="background: ${s}" class="mention-user-avatar-string">${Zd(i.displayName,1)}</span>`,element:i.element,data:i,subText:i.email}}));this.editor=t,this.options=e,this.suggest=new Np(t,{id:"editor-mention",trigger:["@"],autoDeleteTrigger:!0,showLoading:!0,enableFirstBlock:e.enableFirstBlock,onShow:this.onShow,onClickItem:this.onClickItem,queryItems:this.queryItems,onClose:this.onClose})}destroy(){}}S("mathjax-box");function lW(n,t,e,o){const r=o,i=w("a",["mention-container"],e);w("span",["mention-name"],i,`@${r.text}`),i.setAttribute("data-mention-id",r.mentionId)}function cW(n,t,e){}function aW(n,t,e,o){return`@${t.text}`}function uW(){return{abstract:R.t("mention.abstract")}}const P2={boxType:"mention",updateBoxContent:lW,handleClickBox:cW,convertTo:aW,getBoxProperties:uW};function dW(n){const t=w("div",["mention-button-wrap"],null),e=ji("mention-button",R.t("list.mention.tooltip"),JL,[],n.clientId);return t.appendChild(e),t}class hW{constructor(t){m(this,"mentionButton");m(this,"handleHoveringBlock",t=>{var e;!this.editor.isWritable()||(t&&this.shouldBlockShowMention(t)?le(t).appendChild(this.mentionButton):(e=this.mentionButton)==null||e.remove())});m(this,"handleMouseDown",(t,e)=>{e.preventDefault(),e.stopPropagation();const o=ot(this.mentionButton);if(!o||!tt(t,o))return;const r=t.selection.range.focus;if(!r.isSimple())return;let i;t.selection.focusedBlock!==o?i=ut(t,o):i=r.offset,setTimeout(()=>{const s=t.insertTextToBlock(o,i,"@");i+=1;const l=re(xn(s,i).left);this.editor.selection.selectBlock(o,i),this.editor.focus(),t.getCustom("mention").suggest.popup(o,i,l,"@")})});m(this,"destroy",()=>{pe.get(this.editor).removeListener("change",this.handleHoveringBlock)});this.editor=t,this.mentionButton=dW(t),pe.get(this.editor).addListener("change",this.handleHoveringBlock),t.domEvents.addEventListener(this.mentionButton,"mousedown",this.handleMouseDown)}shouldBlockShowMention(t){if(!tt(this.editor,t)||!Ht(t))return!1;const e=Zn(t);return!(e==="ordered"||e==="unordered")}}const tot="",fW={mention:{abstract:"\u6210\u5458"}},mW={mention:{abstract:"Member"}},gW={mention:{abstract:"\u30E1\u30F3\u30D0\u30FC"}};R.mergeLang({"zh-CN":fW,"en-US":mW,"ja-JP":gW});const pW={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"}},CW={templates:{title:"Choose a template",create:"New template",choose:"All templates",customizedMark:"Custom"}},AW={templates:{title:"\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8\u3092\u9078\u629E",create:"\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8\u3092\u65B0\u898F\u4F5C\u6210",choose:"\u30C6\u30F3\u30D7\u30EC\u30FC\u30C8\u4E00\u89A7",customizedMark:"\u30AB\u30B9\u30BF\u30E0"}};R.mergeLang({"zh-CN":pW,"en-US":CW,"ja-JP":AW});const eot="",bW="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjEyMCIgaGVpZ2h0PSIxMjAiIHZpZXdCb3g9IjAgMCAxMjAgMTIwIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cmVjdCB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTQ4IDU5QzQ4IDU0LjU4MTcgNTEuNTgxNyA1MSA1NiA1MUg5M0M5OC41MjI4IDUxIDEwMyA1NS40NzcyIDEwMyA2MVY4OEMxMDMgOTEuODY2IDk5Ljg2NiA5NSA5NiA5NUg1NkM1MS41ODE3IDk1IDQ4IDkxLjQxODMgNDggODdWNTlaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGQ9Ik0xOCA2NEMxOCA2Mi4zNDMxIDE5LjM0MzEgNjEgMjEgNjFINTZDNjAuNDE4MyA2MSA2NCA2NC41ODE3IDY0IDY5VjgzQzY0IDg1LjIwOTEgNjIuMjA5MSA4NyA2MCA4N0gyNkMyMS41ODE3IDg3IDE4IDgzLjQxODMgMTggNzlWNjRaIiBmaWxsPSIjRUFFNEY2Ii8+CjxyZWN0IHg9IjI0IiB5PSIzMSIgd2lkdGg9IjY1IiBoZWlnaHQ9IjUwIiByeD0iNSIgZmlsbD0iIzk5QzdGMiIvPgo8cmVjdCB4PSIzMy41IiB5PSI0MyIgd2lkdGg9IjQ2IiBoZWlnaHQ9IjUiIHJ4PSIyLjUiIGZpbGw9IndoaXRlIi8+CjxyZWN0IHg9IjMzLjUiIHk9IjU0IiB3aWR0aD0iNDYiIGhlaWdodD0iNSIgcng9IjIuNSIgZmlsbD0id2hpdGUiLz4KPHJlY3QgeD0iMjQiIHk9IjMxIiB3aWR0aD0iNjUiIGhlaWdodD0iNTAiIHJ4PSI1IiBzdHJva2U9IiNGOEY4RjgiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik01MCA4NS4yNjhDNTMuODI2MyA4My4wNTg5IDU1LjEzNzMgNzguMTY2MiA1Mi45MjgyIDc0LjMzOThMNjMuMzIwNSA2OC4zMzk4QzY4Ljg0MzMgNzcuOTA1NyA2NS41NjU4IDkwLjEzNzUgNTYgOTUuNjYwNEM0Ni40MzQxIDEwMS4xODMgMzQuMjAyMyA5Ny45MDU3IDI4LjY3OTQgODguMzM5OEwzOS4wNzE3IDgyLjMzOThDNDEuMjgwOSA4Ni4xNjYyIDQ2LjE3MzYgODcuNDc3MiA1MCA4NS4yNjhaIiBmaWxsPSIjQUI5M0RDIi8+CjxyZWN0IHg9IjU5IiB5PSI2NSIgd2lkdGg9IjQyIiBoZWlnaHQ9IjI4IiByeD0iNSIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTYzIDg4VjczLjA4MDhDNjMgNzEuNzA5NiA2My4zNjE0IDcwLjY4NjcgNjQuMDg0MSA3MC4wMTJDNjQuODI4NyA2OS4zMzczIDY1Ljg1OCA2OSA2Ny4xNzIgNjlIOTIuODYwOUM5NS42MjAzIDY5IDk3IDcwLjM2MDMgOTcgNzMuMDgwOFY4OEg5My41MTc5TDg3LjM3NDkgODAuNjIyQzg3LjA5MDIgODAuMzE3MyA4Ni43NjE3IDgwLjA4ODggODYuMzg5NCA3OS45MzY0Qzg2LjAxNzEgNzkuNzg0MSA4NS42NDQ4IDc5LjcwNzkgODUuMjcyNSA3OS43MDc5Qzg0LjkwMDIgNzkuNzA3OSA4NC41Mjc5IDc5Ljc4NDEgODQuMTU1NiA3OS45MzY0QzgzLjgwNTIgODAuMDg4OCA4My40NTQ4IDgwLjMxNzMgODMuMTA0MyA4MC42MjJMNzYuNzMxNCA4Ni4yMzcxTDc0LjIwMTkgODMuOTUxOUM3My42MzI1IDgzLjQyOTYgNzMuMDA4NCA4My4xNjg0IDcyLjMyOTUgODMuMTY4NEM3MS42NTA2IDgzLjE2ODQgNzEuMDM3NCA4My40Mjk2IDcwLjQ4OTkgODMuOTUxOUw2Ni40NDkzIDg4SDYzWk03NC40NjQ3IDgwLjYyMkM3NS4zNjI2IDgwLjYyMiA3Ni4xNDAxIDgwLjI5NTUgNzYuNzk3MSA3OS42NDI2Qzc3LjQ3NiA3OC45ODk3IDc3LjgxNTUgNzguMjE3MSA3Ny44MTU1IDc3LjMyNDdDNzcuODE1NSA3Ni40MTA3IDc3LjQ3NiA3NS42MzggNzYuNzk3MSA3NS4wMDY5Qzc2LjE0MDEgNzQuMzU0IDc1LjM2MjYgNzQuMDE2NiA3NC40NjQ3IDczLjk5NDhDNzMuNTQ0OSA3My45NTEzIDcyLjc1NjUgNzQuMjY2OSA3Mi4wOTk1IDc0Ljk0MTZDNzEuNDQyNSA3NS42MTYzIDcxLjExNCA3Ni40MTA3IDcxLjExNCA3Ny4zMjQ3QzcxLjExNCA3OC4yMTcxIDcxLjQ0MjUgNzguOTg5NyA3Mi4wOTk1IDc5LjY0MjZDNzIuNzU2NSA4MC4yOTU1IDczLjU0NDkgODAuNjIyIDc0LjQ2NDcgODAuNjIyWiIgZmlsbD0iI0Y3RDA3RiIvPgo8Y2lyY2xlIGN4PSI5NSIgY3k9IjQyIiByPSIyIiBzdHJva2U9IiM1MEMzOTgiIHN0cm9rZS13aWR0aD0iMiIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTk0Ljc1MDEgMjQuNDY4N0wxMDAuNzgxIDI3LjkxNDlMOTQuNzE5IDMxLjQxNDlMOTQuNzUwMSAyNC40Njg3WiIgc3Ryb2tlPSIjNUNBNUVBIiBzdHJva2Utd2lkdGg9IjEuOCIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTEwNSAzOEMxMDUgMzguNTUyMyAxMDUuNDQ4IDM5IDEwNiAzOUMxMDYuNTUyIDM5IDEwNyAzOC41NTIzIDEwNyAzOFYzNkgxMDlDMTA5LjU1MiAzNiAxMTAgMzUuNTUyMyAxMTAgMzVDMTEwIDM0LjQ0NzcgMTA5LjU1MiAzNCAxMDkgMzRIMTA3VjMyQzEwNyAzMS40NDc3IDEwNi41NTIgMzEgMTA2IDMxQzEwNS40NDggMzEgMTA1IDMxLjQ0NzcgMTA1IDMyVjM0SDEwM0MxMDIuNDQ4IDM0IDEwMiAzNC40NDc3IDEwMiAzNUMxMDIgMzUuNTUyMyAxMDIuNDQ4IDM2IDEwMyAzNkgxMDVWMzhaIiBmaWxsPSIjQUI5M0RDIi8+Cjwvc3ZnPgo=",vW="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgdmlld0JveD0iMCAwIDM3MiAyNzkiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMF8xMjU2XzM3MTY4KSI+CjxyZWN0IHdpZHRoPSIzNzIiIGhlaWdodD0iMjc5IiBmaWxsPSJ3aGl0ZSIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIzOS41NzQ3IiB3aWR0aD0iMTE4LjcyMyIgaGVpZ2h0PSIxNS44Mjk4IiByeD0iNy45MTQ4OSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI3MS4yMzM5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSI5MS4wMjE1IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSIzOS41NzQ1IiB5PSIxMTAuODA5IiB3aWR0aD0iMjkyLjg1MSIgaGVpZ2h0PSI3LjkxNDg5IiByeD0iMy45NTc0NSIgZmlsbD0iI0VBRjNGQyIvPgo8cmVjdCB4PSI0MC41NjM4IiB5PSIxMzUuNTQzIiB3aWR0aD0iMjkwLjg3MiIgaGVpZ2h0PSIxMDAuOTE1IiByeD0iMi45NjgwOSIgc3Ryb2tlPSIjRUFGM0ZDIiBzdHJva2Utd2lkdGg9IjEuOTc4NzIiLz4KPHBhdGggZD0iTTM5LjU3NDUgMTM4LjUxMUMzOS41NzQ1IDEzNi4zMjUgNDEuMzQ2MyAxMzQuNTUzIDQzLjUzMTkgMTM0LjU1M0gzMjguNDY4QzMzMC42NTQgMTM0LjU1MyAzMzIuNDI2IDEzNi4zMjUgMzMyLjQyNiAxMzguNTExVjE1Mi4zNjJIMzkuNTc0NVYxMzguNTExWiIgZmlsbD0iI0Q2RTlGQSIvPgo8cGF0aCBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGNsaXAtcnVsZT0iZXZlbm9kZCIgZD0iTTg3LjA2MzcgMTY5LjE4MUM4Ny4wNjM3IDE2Ny41NDIgODguMzkyNiAxNjYuMjEzIDkwLjAzMTggMTY2LjIxM0gzMTcuNTg1QzMxOS4yMjQgMTY2LjIxMyAzMjAuNTUzIDE2Ny41NDIgMzIwLjU1MyAxNjkuMTgxQzMyMC41NTMgMTcwLjgyIDMxOS4yMjQgMTcyLjE0OSAzMTcuNTg1IDE3Mi4xNDlIOTAuMDMxOEM4OC4zOTI2IDE3Mi4xNDkgODcuMDYzNyAxNzAuODIgODcuMDYzNyAxNjkuMTgxWk0xMDQuODcyIDE5Mi45MjZDMTA0Ljg3MiAxOTEuMjg2IDEwNi4yMDEgMTg5Ljk1NyAxMDcuODQgMTg5Ljk1N0gzMTcuNTg1QzMxOS4yMjQgMTg5Ljk1NyAzMjAuNTUzIDE5MS4yODYgMzIwLjU1MyAxOTIuOTI2QzMyMC41NTMgMTk0LjU2NSAzMTkuMjI0IDE5NS44OTQgMzE3LjU4NSAxOTUuODk0SDEwNy44NEMxMDYuMjAxIDE5NS44OTQgMTA0Ljg3MiAxOTQuNTY1IDEwNC44NzIgMTkyLjkyNlpNMTA3Ljg0IDIxMy43MDJDMTA2LjIwMSAyMTMuNzAyIDEwNC44NzIgMjE1LjAzMSAxMDQuODcyIDIxNi42N0MxMDQuODcyIDIxOC4zMDkgMTA2LjIwMSAyMTkuNjM4IDEwNy44NCAyMTkuNjM4SDMxNy41ODVDMzE5LjIyNCAyMTkuNjM4IDMyMC41NTMgMjE4LjMwOSAzMjAuNTUzIDIxNi42N0MzMjAuNTUzIDIxNS4wMzEgMzE5LjIyNCAyMTMuNzAyIDMxNy41ODUgMjEzLjcwMkgxMDcuODRaIiBmaWxsPSIjRDZFOUZBIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNNTEuNDQ2OCAxNjkuMTgxQzUxLjQ0NjggMTY3LjU0MiA1Mi43NzU2IDE2Ni4yMTMgNTQuNDE0OSAxNjYuMjEzSDYwLjM1MUM2MS45OTAzIDE2Ni4yMTMgNjMuMzE5MSAxNjcuNTQyIDYzLjMxOTEgMTY5LjE4MUM2My4zMTkxIDE3MC44MiA2MS45OTAzIDE3Mi4xNDkgNjAuMzUxIDE3Mi4xNDlINTQuNDE0OUM1Mi43NzU2IDE3Mi4xNDkgNTEuNDQ2OCAxNzAuODIgNTEuNDQ2OCAxNjkuMTgxWk01MS40NDY4IDE5Mi45MjZDNTEuNDQ2OCAxOTEuMjg2IDUyLjc3NTcgMTg5Ljk1NyA1NC40MTQ5IDE4OS45NTdINjAuMzUxMUM2MS45OTAzIDE4OS45NTcgNjMuMzE5MSAxOTEuMjg2IDYzLjMxOTEgMTkyLjkyNkM2My4zMTkxIDE5NC41NjUgNjEuOTkwMyAxOTUuODk0IDYwLjM1MTEgMTk1Ljg5NEg1NC40MTQ5QzUyLjc3NTcgMTk1Ljg5NCA1MS40NDY4IDE5NC41NjUgNTEuNDQ2OCAxOTIuOTI2Wk01NC40MTQ5IDIxMy43MDJDNTIuNzc1NyAyMTMuNzAyIDUxLjQ0NjggMjE1LjAzMSA1MS40NDY4IDIxNi42N0M1MS40NDY4IDIxOC4zMDkgNTIuNzc1NyAyMTkuNjM4IDU0LjQxNDkgMjE5LjYzOEg2MC4zNTExQzYxLjk5MDMgMjE5LjYzOCA2My4zMTkxIDIxOC4zMDkgNjMuMzE5MSAyMTYuNjdDNjMuMzE5MSAyMTUuMDMxIDYxLjk5MDMgMjEzLjcwMiA2MC4zNTExIDIxMy43MDJINTQuNDE0OVoiIGZpbGw9IiM5OUM3RjIiLz4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik02OS4yNTU0IDE2OS4xODFDNjkuMjU1NCAxNjcuNTQyIDcwLjU4NDMgMTY2LjIxMyA3Mi4yMjM1IDE2Ni4yMTNINzguMTU5N0M3OS43OTg5IDE2Ni4yMTMgODEuMTI3OCAxNjcuNTQyIDgxLjEyNzggMTY5LjE4MUM4MS4xMjc4IDE3MC44MiA3OS43OTg5IDE3Mi4xNDkgNzguMTU5NyAxNzIuMTQ5SDcyLjIyMzVDNzAuNTg0MyAxNzIuMTQ5IDY5LjI1NTQgMTcwLjgyIDY5LjI1NTQgMTY5LjE4MVpNNjkuMjU1NCAxOTIuOTI2QzY5LjI1NTQgMTkxLjI4NiA3MC41ODQyIDE4OS45NTcgNzIuMjIzNSAxODkuOTU3SDc4LjE1OTZDNzkuNzk4OSAxODkuOTU3IDgxLjEyNzcgMTkxLjI4NiA4MS4xMjc3IDE5Mi45MjZDODEuMTI3NyAxOTQuNTY1IDc5Ljc5ODkgMTk1Ljg5NCA3OC4xNTk2IDE5NS44OTRINzIuMjIzNUM3MC41ODQyIDE5NS44OTQgNjkuMjU1NCAxOTQuNTY1IDY5LjI1NTQgMTkyLjkyNlpNNzIuMjIzNSAyMTMuNzAyQzcwLjU4NDIgMjEzLjcwMiA2OS4yNTU0IDIxNS4wMzEgNjkuMjU1NCAyMTYuNjdDNjkuMjU1NCAyMTguMzA5IDcwLjU4NDIgMjE5LjYzOCA3Mi4yMjM1IDIxOS42MzhINzguMTU5NkM3OS43OTg5IDIxOS42MzggODEuMTI3NyAyMTguMzA5IDgxLjEyNzcgMjE2LjY3QzgxLjEyNzcgMjE1LjAzMSA3OS43OTg5IDIxMy43MDIgNzguMTU5NiAyMTMuNzAySDcyLjIyMzVaIiBmaWxsPSIjRjdEMDdGIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNOTAuMDMxOCAxODkuOTU4Qzg4LjM5MjYgMTg5Ljk1OCA4Ny4wNjM3IDE5MS4yODYgODcuMDYzNyAxOTIuOTI2Qzg3LjA2MzcgMTk0LjU2NSA4OC4zOTI2IDE5NS44OTQgOTAuMDMxOCAxOTUuODk0SDk1Ljk2OEM5Ny42MDcyIDE5NS44OTQgOTguOTM2MSAxOTQuNTY1IDk4LjkzNjEgMTkyLjkyNkM5OC45MzYxIDE5MS4yODYgOTcuNjA3MiAxODkuOTU4IDk1Ljk2OCAxODkuOTU4SDkwLjAzMThaTTkwLjAzMTkgMjEzLjcwMkM4OC4zOTI3IDIxMy43MDIgODcuMDYzOCAyMTUuMDMxIDg3LjA2MzggMjE2LjY3Qzg3LjA2MzggMjE4LjMwOSA4OC4zOTI3IDIxOS42MzggOTAuMDMxOSAyMTkuNjM4SDk1Ljk2ODFDOTcuNjA3MyAyMTkuNjM4IDk4LjkzNjIgMjE4LjMwOSA5OC45MzYyIDIxNi42N0M5OC45MzYyIDIxNS4wMzEgOTcuNjA3MyAyMTMuNzAyIDk1Ljk2ODEgMjEzLjcwMkg5MC4wMzE5WiIgZmlsbD0iIzkxRDlCRSIvPgo8L2c+CjxkZWZzPgo8Y2xpcFBhdGggaWQ9ImNsaXAwXzEyNTZfMzcxNjgiPgo8cmVjdCB3aWR0aD0iMzcyIiBoZWlnaHQ9IjI3OSIgZmlsbD0id2hpdGUiLz4KPC9jbGlwUGF0aD4KPC9kZWZzPgo8L3N2Zz4K",Vy=S("templates");function N2(n){const t=n.rootElement.querySelector(":scope .editor-templates");if(!t)return null;const e=t.querySelector(":scope .editor-templates-cards");return g(Vy,e,"no card container"),{root:t,cardContainer:e}}function yW(n){const t=N2(n);if(t)return t.cardContainer.innerHTML="",t;const e=w("div",["editor-templates"],n.rootElement);w("div",["editor-templates-title"],e,R.t("templates.title"));const o=w("div",["editor-templates-cards"],e);return{root:e,cardContainer:o}}function Wy(n,t,e,o,r){var p;const i=(p=n.options.componentsOptions)==null?void 0:p.templates,s=w("div",["editor-template-card",...o],null),l=w("div",["editor-template-thumb-container"],s),a=w("img",["editor-template-thumb"],l);a.src=t,a.style.display="none",a.onerror=()=>{var v;const A=(v=i==null?void 0:i.placeHolderImageSrc)!=null?v:vW;a.src!==A&&(a.src=A)},a.onload=()=>{a.style.display=""};const d=w("div",["editor-template-name"],s),h=w("span",[],d,e);return i!=null&&i.showTemplateTitleAttr&&h.setAttribute("title",e),s.onclick=()=>r(s),s}function kW(n,t){return t.thumbnailUrl?t.thumbnailUrl:n.doc.buildResourceUrl("thumbnail.png")}function wW(n,t){const e=kW(n,t);return Wy(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 BW(n,t){return Wy(n,t,R.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 EW(n,t){var p,A;const e=(p=n.options.componentsOptions)==null?void 0:p.templates;if(!e)return;const r=Ge(n.rootContainer).getBoundingClientRect().width;let i=1;const s=bW,l=N2(n);if(l){if(t!=null&&t.reset){const v=Array.from(l.cardContainer.children),B=l.cardContainer.firstElementChild;if(g(Vy,B,"no first card"),xt(B,"new")||xt(B,"more"))return;const D=window.getComputedStyle(B),T=parseFloat(D.marginLeft),_=parseFloat(D.marginRight),M=B.getBoundingClientRect().width+T+_;i=Math.floor(r/M);const z=Math.max(1,i-1-1),q=v.length-1;v.forEach((rt,ft)=>{ft>z&&ft<q?rt.style.display="none":(ft>=q&&xt(rt,"more"),rt.style.display="")})}return}const a=e.templates,{cardContainer:d}=yW(n);a.forEach((v,B)=>{const D=wW(n,v);if(B>0&&B>=i&&(D.style.display="none"),d.appendChild(D),B===0){const T=window.getComputedStyle(D),_=parseFloat(T.marginLeft),M=parseFloat(T.marginRight),H=D.getBoundingClientRect().width+_+M;i=Math.floor(r/H)-1}});const h=BW(n,s);d.appendChild(h),(A=e==null?void 0:e.onTemplateChooserStatusChanged)==null||A.call(e,n,d,"visible")}const qy=He.default(EW,50);function xW(n){var o,r;const t=N2(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 IW(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 n1(n,t){IW(n.doc.toJSON())?qy(n,t):(qy.cancel(),xW(n))}const TW=800;class DW{constructor(t){m(this,"longPressTimeout",0);m(this,"handleSelectionChange",()=>{});m(this,"handleLongPress",t=>{const e=t.touches[0],o=oh(this.editor,e.clientX,e.clientY);!o||console.log(o)});m(this,"handleTouchStart",t=>{t.touches.length===1&&(this.longPressTimeout=window.setTimeout(()=>{this.handleLongPress(t)},TW))});m(this,"handleTouchEnd",t=>{this.longPressTimeout&&(window.clearTimeout(this.longPressTimeout),this.longPressTimeout=0)});this.editor=t,this.editor.addListener("selectionChanged",this.handleSelectionChange),document.addEventListener("touchstart",this.handleTouchStart),document.addEventListener("touchend",this.handleTouchEnd)}destroy(){this.editor.removeListener("selectionChanged",this.handleSelectionChange),document.removeEventListener("touchstart",this.handleTouchStart),document.removeEventListener("touchend",this.handleTouchEnd)}}const SW=`<svg width="24" height="25" viewBox="0 0 24 25" fill="none" xmlns="http://www.w3.org/2000/svg">
594
594
  <g>
595
595
  <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"/>
596
596
  <animateTransform attributeType="xml" attributeName="transform" type="rotate" values="0 12 12.5;360 12 12.5" dur="2s" repeatCount="indefinite" />
@@ -741,7 +741,7 @@ __p += '`),zt&&(X+=`' +
741
741
  function print() { __p += __j.call(arguments, '') }
742
742
  `:`;
743
743
  `)+X+`return __p
744
- }`;var Ot=uB(function(){return Vt(x,Ct+"return "+X).apply(e,O)});if(Ot.source=X,_5(Ot))throw Ot;return Ot}function GX(c){return Jt(c).toLowerCase()}function ZX(c){return Jt(c).toUpperCase()}function QX(c,u,f){if(c=Jt(c),c&&(f||u===e))return li(c);if(!c||!(u=Xn(u)))return c;var C=Kn(c),y=Kn(u),x=Al(C,y),O=Cd(C,y)+1;return gs(C,x,O).join("")}function YX(c,u,f){if(c=Jt(c),c&&(f||u===e))return c.slice(0,Xc(c)+1);if(!c||!(u=Xn(u)))return c;var C=Kn(c),y=Cd(C,Kn(u))+1;return gs(C,0,y).join("")}function JX(c,u,f){if(c=Jt(c),c&&(f||u===e))return c.replace(Yu,"");if(!c||!(u=Xn(u)))return c;var C=Kn(c),y=Al(C,Kn(u));return gs(C,y).join("")}function KX(c,u){var f=Ut,C=ee;if(Ae(u)){var y="separator"in u?u.separator:y;f="length"in u?Mt(u.length):f,C="omission"in u?Xn(u.omission):C}c=Jt(c);var x=c.length;if(ci(c)){var O=Kn(c);x=O.length}if(f>=x)return c;var P=f-us(C);if(P<1)return C;var $=O?gs(O,0,P).join(""):c.slice(0,P);if(y===e)return $+C;if(O&&(P+=$.length-P),F5(y)){if(c.slice(P).search(y)){var Q,Y=$;for(y.global||(y=oa(y.source,Jt(Nc.exec(y))+"g")),y.lastIndex=0;Q=y.exec(Y);)var X=Q.index;$=$.slice(0,X===e?P:X)}}else if(c.indexOf(Xn(y),P)!=P){var dt=$.lastIndexOf(y);dt>-1&&($=$.slice(0,dt))}return $+C}function XX(c){return c=Jt(c),c&&l3.test(c)?c.replace(d1,ta):c}var ttt=ia(function(c,u,f){return c+(f?" ":"")+u.toUpperCase()}),$5=dw("toUpperCase");function aB(c,u,f){return c=Jt(c),u=f?e:u,u===e?Yc(c)?R1(c):Yn(c):c.match(u)||[]}var uB=_t(function(c,u){try{return vn(c,e,u)}catch(f){return _5(f)?f:new Et(f)}}),ett=yi(function(c,u){return Rn(u,function(f){f=Sr(f),bi(c,f,R5(c[f],c))}),c});function ntt(c){var u=c==null?0:c.length,f=vt();return c=u?ue(c,function(C){if(typeof C[1]!="function")throw new yn(s);return[f(C[0]),C[1]]}):[],_t(function(C){for(var y=-1;++y<u;){var x=c[y];if(vn(x[0],this,C))return vn(x[1],this,C)}})}function ott(c){return TQ(bo(c,p))}function H5(c){return function(){return c}}function rtt(c,u){return c==null||c!==c?u:c}var itt=fw(),stt=fw(!0);function $n(c){return c}function j5(c){return zk(typeof c=="function"?c:bo(c,p))}function ltt(c){return Wk(bo(c,p))}function ctt(c,u){return qk(c,bo(u,p))}var att=_t(function(c,u){return function(f){return Id(f,c,u)}}),utt=_t(function(c,u){return function(f){return Id(c,f,u)}});function U5(c,u,f){var C=Je(u),y=V1(u,C);f==null&&!(Ae(u)&&(y.length||!C.length))&&(f=u,u=c,c=this,y=V1(u,Je(u)));var x=!(Ae(f)&&"chain"in f)||!!f.chain,O=wi(c);return Rn(y,function(P){var $=u[P];c[P]=$,O&&(c.prototype[P]=function(){var Q=this.__chain__;if(x||Q){var Y=c(this.__wrapped__),X=Y.__actions__=Fn(this.__actions__);return X.push({func:$,args:arguments,thisArg:c}),Y.__chain__=Q,Y}return $.apply(c,Er([this.value()],arguments))})}),c}function dtt(){return qe._===this&&(qe._=_1),this}function z5(){}function htt(c){return c=Mt(c),_t(function(u){return Gk(u,c)})}var ftt=v5(ue),mtt=v5(E1),gtt=v5(md);function dB(c){return I5(c)?Gc(Sr(c)):WQ(c)}function ptt(c){return function(u){return c==null?e:Fl(c,u)}}var Ctt=gw(),Att=gw(!0);function V5(){return[]}function W5(){return!1}function btt(){return{}}function vtt(){return""}function ytt(){return!0}function ktt(c,u){if(c=Mt(c),c<1||c>an)return[];var f=mo,C=L(c,mo);u=vt(u),c-=mo;for(var y=Qc(C,u);++f<c;)u(f);return y}function wtt(c){return St(c)?ue(c,Sr):to(c)?[c]:Fn(Lw(Jt(c)))}function Btt(c){var u=++O1;return Jt(c)+u}var Ett=Y1(function(c,u){return c+u},0),xtt=y5("ceil"),Itt=Y1(function(c,u){return c/u},1),Ttt=y5("floor");function Dtt(c){return c&&c.length?z1(c,$n,s5):e}function Stt(c,u){return c&&c.length?z1(c,vt(u,2),s5):e}function Ltt(c){return qc(c,$n)}function Mtt(c,u){return qc(c,vt(u,2))}function Rtt(c){return c&&c.length?z1(c,$n,u5):e}function Ott(c,u){return c&&c.length?z1(c,vt(u,2),u5):e}var _tt=Y1(function(c,u){return c*u},1),Ftt=y5("round"),Ptt=Y1(function(c,u){return c-u},0);function Ntt(c){return c&&c.length?Zc(c,$n):0}function $tt(c,u){return c&&c.length?Zc(c,vt(u,2)):0}return E.after=lK,E.ary=Uw,E.assign=ZK,E.assignIn=nB,E.assignInWith=am,E.assignWith=QK,E.at=YK,E.before=zw,E.bind=R5,E.bindAll=ett,E.bindKey=Vw,E.castArray=bK,E.chain=$w,E.chunk=TY,E.compact=DY,E.concat=SY,E.cond=ntt,E.conforms=ott,E.constant=H5,E.countBy=NJ,E.create=JK,E.curry=Ww,E.curryRight=qw,E.debounce=Gw,E.defaults=KK,E.defaultsDeep=XK,E.defer=cK,E.delay=aK,E.difference=LY,E.differenceBy=MY,E.differenceWith=RY,E.drop=OY,E.dropRight=_Y,E.dropRightWhile=FY,E.dropWhile=PY,E.fill=NY,E.filter=HJ,E.flatMap=zJ,E.flatMapDeep=VJ,E.flatMapDepth=WJ,E.flatten=_w,E.flattenDeep=$Y,E.flattenDepth=HY,E.flip=uK,E.flow=itt,E.flowRight=stt,E.fromPairs=jY,E.functions=sX,E.functionsIn=lX,E.groupBy=qJ,E.initial=zY,E.intersection=VY,E.intersectionBy=WY,E.intersectionWith=qY,E.invert=aX,E.invertBy=uX,E.invokeMap=ZJ,E.iteratee=j5,E.keyBy=QJ,E.keys=Je,E.keysIn=Nn,E.map=om,E.mapKeys=hX,E.mapValues=fX,E.matches=ltt,E.matchesProperty=ctt,E.memoize=im,E.merge=mX,E.mergeWith=oB,E.method=att,E.methodOf=utt,E.mixin=U5,E.negate=sm,E.nthArg=htt,E.omit=gX,E.omitBy=pX,E.once=dK,E.orderBy=YJ,E.over=ftt,E.overArgs=hK,E.overEvery=mtt,E.overSome=gtt,E.partial=O5,E.partialRight=Zw,E.partition=JJ,E.pick=CX,E.pickBy=rB,E.property=dB,E.propertyOf=ptt,E.pull=YY,E.pullAll=Pw,E.pullAllBy=JY,E.pullAllWith=KY,E.pullAt=XY,E.range=Ctt,E.rangeRight=Att,E.rearg=fK,E.reject=tK,E.remove=tJ,E.rest=mK,E.reverse=L5,E.sampleSize=nK,E.set=bX,E.setWith=vX,E.shuffle=oK,E.slice=eJ,E.sortBy=sK,E.sortedUniq=cJ,E.sortedUniqBy=aJ,E.split=zX,E.spread=gK,E.tail=uJ,E.take=dJ,E.takeRight=hJ,E.takeRightWhile=fJ,E.takeWhile=mJ,E.tap=DJ,E.throttle=pK,E.thru=nm,E.toArray=Xw,E.toPairs=iB,E.toPairsIn=sB,E.toPath=wtt,E.toPlainObject=eB,E.transform=yX,E.unary=CK,E.union=gJ,E.unionBy=pJ,E.unionWith=CJ,E.uniq=AJ,E.uniqBy=bJ,E.uniqWith=vJ,E.unset=kX,E.unzip=M5,E.unzipWith=Nw,E.update=wX,E.updateWith=BX,E.values=ca,E.valuesIn=EX,E.without=yJ,E.words=aB,E.wrap=AK,E.xor=kJ,E.xorBy=wJ,E.xorWith=BJ,E.zip=EJ,E.zipObject=xJ,E.zipObjectDeep=IJ,E.zipWith=TJ,E.entries=iB,E.entriesIn=sB,E.extend=nB,E.extendWith=am,U5(E,E),E.add=Ett,E.attempt=uB,E.camelCase=DX,E.capitalize=lB,E.ceil=xtt,E.clamp=xX,E.clone=vK,E.cloneDeep=kK,E.cloneDeepWith=wK,E.cloneWith=yK,E.conformsTo=BK,E.deburr=cB,E.defaultTo=rtt,E.divide=Itt,E.endsWith=SX,E.eq=Xo,E.escape=LX,E.escapeRegExp=MX,E.every=$J,E.find=jJ,E.findIndex=Rw,E.findKey=tX,E.findLast=UJ,E.findLastIndex=Ow,E.findLastKey=eX,E.floor=Ttt,E.forEach=Hw,E.forEachRight=jw,E.forIn=nX,E.forInRight=oX,E.forOwn=rX,E.forOwnRight=iX,E.get=P5,E.gt=EK,E.gte=xK,E.has=cX,E.hasIn=N5,E.head=Fw,E.identity=$n,E.includes=GJ,E.indexOf=UY,E.inRange=IX,E.invoke=dX,E.isArguments=$l,E.isArray=St,E.isArrayBuffer=IK,E.isArrayLike=Pn,E.isArrayLikeObject=Te,E.isBoolean=TK,E.isBuffer=ps,E.isDate=DK,E.isElement=SK,E.isEmpty=LK,E.isEqual=MK,E.isEqualWith=RK,E.isError=_5,E.isFinite=OK,E.isFunction=wi,E.isInteger=Qw,E.isLength=lm,E.isMap=Yw,E.isMatch=_K,E.isMatchWith=FK,E.isNaN=PK,E.isNative=NK,E.isNil=HK,E.isNull=$K,E.isNumber=Jw,E.isObject=Ae,E.isObjectLike=Be,E.isPlainObject=Rd,E.isRegExp=F5,E.isSafeInteger=jK,E.isSet=Kw,E.isString=cm,E.isSymbol=to,E.isTypedArray=la,E.isUndefined=UK,E.isWeakMap=zK,E.isWeakSet=VK,E.join=GY,E.kebabCase=RX,E.last=yo,E.lastIndexOf=ZY,E.lowerCase=OX,E.lowerFirst=_X,E.lt=WK,E.lte=qK,E.max=Dtt,E.maxBy=Stt,E.mean=Ltt,E.meanBy=Mtt,E.min=Rtt,E.minBy=Ott,E.stubArray=V5,E.stubFalse=W5,E.stubObject=btt,E.stubString=vtt,E.stubTrue=ytt,E.multiply=_tt,E.nth=QY,E.noConflict=dtt,E.noop=z5,E.now=rm,E.pad=FX,E.padEnd=PX,E.padStart=NX,E.parseInt=$X,E.random=TX,E.reduce=KJ,E.reduceRight=XJ,E.repeat=HX,E.replace=jX,E.result=AX,E.round=Ftt,E.runInContext=N,E.sample=eK,E.size=rK,E.snakeCase=UX,E.some=iK,E.sortedIndex=nJ,E.sortedIndexBy=oJ,E.sortedIndexOf=rJ,E.sortedLastIndex=iJ,E.sortedLastIndexBy=sJ,E.sortedLastIndexOf=lJ,E.startCase=VX,E.startsWith=WX,E.subtract=Ptt,E.sum=Ntt,E.sumBy=$tt,E.template=qX,E.times=ktt,E.toFinite=Bi,E.toInteger=Mt,E.toLength=tB,E.toLower=GX,E.toNumber=ko,E.toSafeInteger=GK,E.toString=Jt,E.toUpper=ZX,E.trim=QX,E.trimEnd=YX,E.trimStart=JX,E.truncate=KX,E.unescape=XX,E.uniqueId=Btt,E.upperCase=ttt,E.upperFirst=$5,E.each=Hw,E.eachRight=jw,E.first=Fw,U5(E,function(){var c={};return Tr(E,function(u,f){Wt.call(E.prototype,f)||(c[f]=u)}),c}(),{chain:!1}),E.VERSION=o,Rn(["bind","bindKey","curry","curryRight","partial","partialRight"],function(c){E[c].placeholder=E}),Rn(["drop","take"],function(c,u){Pt.prototype[c]=function(f){f=f===e?1:I(Mt(f),0);var C=this.__filtered__&&!u?new Pt(this):this.clone();return C.__filtered__?C.__takeCount__=L(f,C.__takeCount__):C.__views__.push({size:L(f,mo),type:c+(C.__dir__<0?"Right":"")}),C},Pt.prototype[c+"Right"]=function(f){return this.reverse()[c](f).reverse()}}),Rn(["filter","map","takeWhile"],function(c,u){var f=u+1,C=f==Ne||f==vr;Pt.prototype[c]=function(y){var x=this.clone();return x.__iteratees__.push({iteratee:vt(y,3),type:f}),x.__filtered__=x.__filtered__||C,x}}),Rn(["head","last"],function(c,u){var f="take"+(u?"Right":"");Pt.prototype[c]=function(){return this[f](1).value()[0]}}),Rn(["initial","tail"],function(c,u){var f="drop"+(u?"":"Right");Pt.prototype[c]=function(){return this.__filtered__?new Pt(this):this[f](1)}}),Pt.prototype.compact=function(){return this.filter($n)},Pt.prototype.find=function(c){return this.filter(c).head()},Pt.prototype.findLast=function(c){return this.reverse().find(c)},Pt.prototype.invokeMap=_t(function(c,u){return typeof c=="function"?new Pt(this):this.map(function(f){return Id(f,c,u)})}),Pt.prototype.reject=function(c){return this.filter(sm(vt(c)))},Pt.prototype.slice=function(c,u){c=Mt(c);var f=this;return f.__filtered__&&(c>0||u<0)?new Pt(f):(c<0?f=f.takeRight(-c):c&&(f=f.drop(c)),u!==e&&(u=Mt(u),f=u<0?f.dropRight(-u):f.take(u-c)),f)},Pt.prototype.takeRightWhile=function(c){return this.reverse().takeWhile(c).reverse()},Pt.prototype.toArray=function(){return this.take(mo)},Tr(Pt.prototype,function(c,u){var f=/^(?:filter|find|map|reject)|While$/.test(u),C=/^(?:head|last)$/.test(u),y=E[C?"take"+(u=="last"?"Right":""):u],x=C||/^find/.test(u);!y||(E.prototype[u]=function(){var O=this.__wrapped__,P=C?[1]:arguments,$=O instanceof Pt,Q=P[0],Y=$||St(O),X=function($t){var zt=y.apply(E,Er([$t],P));return C&&dt?zt[0]:zt};Y&&f&&typeof Q=="function"&&Q.length!=1&&($=Y=!1);var dt=this.__chain__,Ct=!!this.__actions__.length,yt=x&&!dt,Ot=$&&!Ct;if(!x&&Y){O=Ot?O:new Pt(this);var kt=c.apply(O,P);return kt.__actions__.push({func:nm,args:[X],thisArg:e}),new _n(kt,dt)}return yt&&Ot?c.apply(this,P):(kt=this.thru(X),yt?C?kt.value()[0]:kt.value():kt)})}),Rn(["pop","push","shift","sort","splice","unshift"],function(c){var u=kl[c],f=/^(?:push|sort|unshift)$/.test(c)?"tap":"thru",C=/^(?:pop|shift)$/.test(c);E.prototype[c]=function(){var y=arguments;if(C&&!this.__chain__){var x=this.value();return u.apply(St(x)?x:[],y)}return this[f](function(O){return u.apply(St(O)?O:[],y)})}}),Tr(Pt.prototype,function(c,u){var f=E[u];if(f){var C=f.name+"";Wt.call(en,C)||(en[C]=[]),en[C].push({name:u,func:f})}}),en[Q1(e,_).name]=[{name:"wrapper",func:e}],Pt.prototype.clone=XZ,Pt.prototype.reverse=tQ,Pt.prototype.value=eQ,E.prototype.at=SJ,E.prototype.chain=LJ,E.prototype.commit=MJ,E.prototype.next=RJ,E.prototype.plant=_J,E.prototype.reverse=FJ,E.prototype.toJSON=E.prototype.valueOf=E.prototype.value=PJ,E.prototype.first=E.prototype.head,Dl&&(E.prototype[Dl]=OJ),E},di=na();ii?((ii.exports=di)._=di,sd._=di):qe._=di}).call(cr)})(q2,q2.exports);const jq={mermaid:"https://mermaid-js.github.io/mermaid/",flowchart:"https://flowchart.js.org/",plantuml:"https://plantuml.com/"};class Uq extends I2{constructor(e,o,r,i){super(e,o,i);m(this,"group","hovering-toolbar");m(this,"_commands",[{id:"edit",name:R.t("graph.edit"),icon:Mp},{id:"add-comment",name:R.t("graph.comment"),icon:eu},{id:"separator",type:"separator",name:""},{id:"help",name:R.t("graph.help"),icon:fv}]);this.editor=e,this.block=o,this.graphType=r,this.properties=i}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(jq[this.graphType])}}function zq(n,t,e,o){return{blockCommands:{"hovering-toolbar":new Uq(n,t,e,o)},abstract:q2.exports.capitalize(e)}}class G2{constructor(t,e,o){m(this,"editor");m(this,"logger");m(this,"editing",!1);this.graphType=e,this.codeEmbedDataKey=o,this.editor=t,this.logger=S(`embed-block-${this.graphType}`)}i18nt(t,e){return R.t(`graph.${t}`,e||{})}getContent(t){g(this.logger,t,"embed-element does not exist");const e=t.parentElement;return g(this.logger,e,"content-element does not exist"),e}getEmbed(t){const e=t.childNodes[0];return g(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);g(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=w("div",["graph-embed"],t),{embedData:r}=e,i=r[`${this.codeEmbedDataKey}`],s=r.src,l=w("div",["embed-graph-img-content"],o),a=w("img",["graph-embed-image"],l);a.draggable=!1,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){et(t,"empty-embed","invalid-code");const r=t.querySelector("img.graph-embed-image");if(o){r.src="",W(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),W(t,"empty-embed")}}editGraph(t){this.editing=!0;const e=ot(t);g(this.logger,e,`${this.graphType} block does not exist`),K0(this.editor,e);const o=t.querySelector(".graph-embed"),r=l=>{this.updateImage(o,l,null,null)},i=async l=>{try{if(this.editing=!1,X0(this.editor,e),r(l),!this.hasChanged(e,l))return;const d={src:await this.code2ResourceId(l),[`${this.codeEmbedDataKey}`]:l};this.editor.updateEmbedData(e,d)}catch(a){this.updateClasses(o,l,a);const d={src:"",[`${this.codeEmbedDataKey}`]:l};this.editor.updateEmbedData(e,d)}},s=this.editor.getBlockData(e);Hq(this.editor,e,{onChange:r,onEnd:i,codeValue:s.embedData[`${this.codeEmbedDataKey}`]})}getBlockProperties(t,e){return this.editing?{}:zq(this.editor,t,this.graphType,{handleExecuteCommand:(o,r,i)=>{if(i.id==="edit"){if(!o.isBlockWritable(r))return!0;const s=Rt(r);return this.editGraph(s),!0}return i.id==="add-comment"?(o.readonly||Kf(o,r),!0):!1}})}hasChanged(t,e){return this.editor.getBlockData(t).embedData[`${this.codeEmbedDataKey}`]!==e}}const Vq="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js",Wq=["//cdnjs.cloudflare.com/ajax/libs/raphael/2.3.0/raphael.min.js","//cdnjs.cloudflare.com/ajax/libs/flowchart/1.15.0/flowchart.min.js"],qq="https://www.plantuml.com/plantuml/svg",Gq=S("mermaid-helper"),Zq="wiz-editor-mermaid";async function ok(n,t){var B;const o=((B=(n.getComponentOptions("mermaid")||{}).cdn)==null?void 0:B.mermaid)||Vq;await vs(o,Zq);const r=window.mermaid;g(Gq,r,"Resource load failed: Mermaid javaScript resource injection failed");const i=K(),l=await new Promise((D,T)=>{try{r.mermaidAPI.render(i,t,_=>{setTimeout(()=>{D(_)})})}catch(_){_.message=_.str,T(_)}}),h=new DOMParser().parseFromString(l,"image/svg+xml").firstChild,p=h.style.maxWidth;return p&&h.setAttribute("width",p),new XMLSerializer().serializeToString(h)}async function Qq(n,t){const e=await ok(n,t);return Lm(e,"image/svg+xml",`${K()}.svg`)}async function Yq(n,t){const e=await ok(n,t),o=new Blob([e]),r=new File([o],`${K()}.svg`,{type:"image/svg+xml"});return(await n.doc.uploadResource(r)).resourceId}class Rc extends G2{constructor(t){super(t,"mermaid","mermaidText")}static get(t,e){return t.addCustom(`mermaid-${e.id}`,()=>new Rc(t))}code2ObjectUrl(t){return Qq(this.editor,t)}code2ResourceId(t){return Yq(this.editor,t)}destroy(){}}const Jq={graph:{invalid:"\u65E0\u6548\u7684 {EmbedName} \u5185\u5BB9\uFF1A{message}",empty:"\u7A7A\u7684 {EmbedName}",edit:"\u7F16\u8F91",comment:"\u6279\u6CE8",help:"\u5E2E\u52A9"}},Kq={graph:{invalid:"Invalid {EmbedName} content: {message}",empty:"Empty {EmbedName}",edit:"Edit",comment:"Annotation",help:"Help"}},Xq={graph:{invalid:"\u7121\u52B9\u306A{EmbedName}\uFF1A{message}",empty:"\u7A7A\u306E {EmbedName}",edit:"\u7DE8\u96C6",comment:"\u30B3\u30E1\u30F3\u30C8",help:"\u30D8\u30EB\u30D7"}};R.mergeLang({"zh-CN":Jq,"en-US":Kq,"ja-JP":Xq});function tG(n,t,e){Rc.get(n,e).createEmbedContent(t,e)}function eG(n,t,e){const o=Rc.get(n,n.getBlockData(t)),r=Rt(t);return o.updateEmbedContent(r,e),!0}function nG(n,t,e){const{data:o}=e,r=n.getBlockString(t).trim();if(!o||o.embedType!=="mermaid"||r!=="```mermaid"||!tt(n,t))return null;const i={src:"",mermaidText:""};return{blockData:{id:K(),type:"embed",embedType:"mermaid",embedData:i},onConverted:(a,d)=>{Rc.get(a,a.getBlockData(d)).editGraph(Rt(d))}}}function oG(n,t){return Rc.get(n,n.getBlockData(t)).getBlockProperties(t)}function rG(n,t,e,o){const{embedData:r}=t,i=r;if(o==="html")return i.src?`<img src="${n.doc.buildResourceUrl(i.src,{withToken:!0})}" />`:i.mermaidText?`<div class="mermaid">${i.mermaidText}</div>`:"<p>[mermaid]</p>";if(o==="markdown"){if(i.src)return`![mermaid](${n.doc.buildResourceUrl(i.src,{withToken:!0})})`;if(i.mermaidText)return`\`\`\`mermaid\`\`\`
744
+ }`;var Ot=uB(function(){return Vt(x,Ct+"return "+X).apply(e,O)});if(Ot.source=X,_5(Ot))throw Ot;return Ot}function GX(c){return Jt(c).toLowerCase()}function ZX(c){return Jt(c).toUpperCase()}function QX(c,u,f){if(c=Jt(c),c&&(f||u===e))return li(c);if(!c||!(u=Xn(u)))return c;var C=Kn(c),y=Kn(u),x=Al(C,y),O=Cd(C,y)+1;return gs(C,x,O).join("")}function YX(c,u,f){if(c=Jt(c),c&&(f||u===e))return c.slice(0,Xc(c)+1);if(!c||!(u=Xn(u)))return c;var C=Kn(c),y=Cd(C,Kn(u))+1;return gs(C,0,y).join("")}function JX(c,u,f){if(c=Jt(c),c&&(f||u===e))return c.replace(Yu,"");if(!c||!(u=Xn(u)))return c;var C=Kn(c),y=Al(C,Kn(u));return gs(C,y).join("")}function KX(c,u){var f=Ut,C=ee;if(Ae(u)){var y="separator"in u?u.separator:y;f="length"in u?Mt(u.length):f,C="omission"in u?Xn(u.omission):C}c=Jt(c);var x=c.length;if(ci(c)){var O=Kn(c);x=O.length}if(f>=x)return c;var P=f-us(C);if(P<1)return C;var $=O?gs(O,0,P).join(""):c.slice(0,P);if(y===e)return $+C;if(O&&(P+=$.length-P),F5(y)){if(c.slice(P).search(y)){var Q,Y=$;for(y.global||(y=oa(y.source,Jt(Nc.exec(y))+"g")),y.lastIndex=0;Q=y.exec(Y);)var X=Q.index;$=$.slice(0,X===e?P:X)}}else if(c.indexOf(Xn(y),P)!=P){var dt=$.lastIndexOf(y);dt>-1&&($=$.slice(0,dt))}return $+C}function XX(c){return c=Jt(c),c&&l3.test(c)?c.replace(d1,ta):c}var ttt=ia(function(c,u,f){return c+(f?" ":"")+u.toUpperCase()}),$5=dw("toUpperCase");function aB(c,u,f){return c=Jt(c),u=f?e:u,u===e?Yc(c)?R1(c):Yn(c):c.match(u)||[]}var uB=_t(function(c,u){try{return vn(c,e,u)}catch(f){return _5(f)?f:new Et(f)}}),ett=yi(function(c,u){return Rn(u,function(f){f=Sr(f),bi(c,f,R5(c[f],c))}),c});function ntt(c){var u=c==null?0:c.length,f=vt();return c=u?ue(c,function(C){if(typeof C[1]!="function")throw new yn(s);return[f(C[0]),C[1]]}):[],_t(function(C){for(var y=-1;++y<u;){var x=c[y];if(vn(x[0],this,C))return vn(x[1],this,C)}})}function ott(c){return TQ(bo(c,p))}function H5(c){return function(){return c}}function rtt(c,u){return c==null||c!==c?u:c}var itt=fw(),stt=fw(!0);function $n(c){return c}function j5(c){return zk(typeof c=="function"?c:bo(c,p))}function ltt(c){return Wk(bo(c,p))}function ctt(c,u){return qk(c,bo(u,p))}var att=_t(function(c,u){return function(f){return Id(f,c,u)}}),utt=_t(function(c,u){return function(f){return Id(c,f,u)}});function U5(c,u,f){var C=Je(u),y=V1(u,C);f==null&&!(Ae(u)&&(y.length||!C.length))&&(f=u,u=c,c=this,y=V1(u,Je(u)));var x=!(Ae(f)&&"chain"in f)||!!f.chain,O=wi(c);return Rn(y,function(P){var $=u[P];c[P]=$,O&&(c.prototype[P]=function(){var Q=this.__chain__;if(x||Q){var Y=c(this.__wrapped__),X=Y.__actions__=Fn(this.__actions__);return X.push({func:$,args:arguments,thisArg:c}),Y.__chain__=Q,Y}return $.apply(c,Er([this.value()],arguments))})}),c}function dtt(){return qe._===this&&(qe._=_1),this}function z5(){}function htt(c){return c=Mt(c),_t(function(u){return Gk(u,c)})}var ftt=v5(ue),mtt=v5(E1),gtt=v5(md);function dB(c){return I5(c)?Gc(Sr(c)):WQ(c)}function ptt(c){return function(u){return c==null?e:Fl(c,u)}}var Ctt=gw(),Att=gw(!0);function V5(){return[]}function W5(){return!1}function btt(){return{}}function vtt(){return""}function ytt(){return!0}function ktt(c,u){if(c=Mt(c),c<1||c>an)return[];var f=mo,C=L(c,mo);u=vt(u),c-=mo;for(var y=Qc(C,u);++f<c;)u(f);return y}function wtt(c){return St(c)?ue(c,Sr):to(c)?[c]:Fn(Lw(Jt(c)))}function Btt(c){var u=++O1;return Jt(c)+u}var Ett=Y1(function(c,u){return c+u},0),xtt=y5("ceil"),Itt=Y1(function(c,u){return c/u},1),Ttt=y5("floor");function Dtt(c){return c&&c.length?z1(c,$n,s5):e}function Stt(c,u){return c&&c.length?z1(c,vt(u,2),s5):e}function Ltt(c){return qc(c,$n)}function Mtt(c,u){return qc(c,vt(u,2))}function Rtt(c){return c&&c.length?z1(c,$n,u5):e}function Ott(c,u){return c&&c.length?z1(c,vt(u,2),u5):e}var _tt=Y1(function(c,u){return c*u},1),Ftt=y5("round"),Ptt=Y1(function(c,u){return c-u},0);function Ntt(c){return c&&c.length?Zc(c,$n):0}function $tt(c,u){return c&&c.length?Zc(c,vt(u,2)):0}return E.after=lK,E.ary=Uw,E.assign=ZK,E.assignIn=nB,E.assignInWith=am,E.assignWith=QK,E.at=YK,E.before=zw,E.bind=R5,E.bindAll=ett,E.bindKey=Vw,E.castArray=bK,E.chain=$w,E.chunk=TY,E.compact=DY,E.concat=SY,E.cond=ntt,E.conforms=ott,E.constant=H5,E.countBy=NJ,E.create=JK,E.curry=Ww,E.curryRight=qw,E.debounce=Gw,E.defaults=KK,E.defaultsDeep=XK,E.defer=cK,E.delay=aK,E.difference=LY,E.differenceBy=MY,E.differenceWith=RY,E.drop=OY,E.dropRight=_Y,E.dropRightWhile=FY,E.dropWhile=PY,E.fill=NY,E.filter=HJ,E.flatMap=zJ,E.flatMapDeep=VJ,E.flatMapDepth=WJ,E.flatten=_w,E.flattenDeep=$Y,E.flattenDepth=HY,E.flip=uK,E.flow=itt,E.flowRight=stt,E.fromPairs=jY,E.functions=sX,E.functionsIn=lX,E.groupBy=qJ,E.initial=zY,E.intersection=VY,E.intersectionBy=WY,E.intersectionWith=qY,E.invert=aX,E.invertBy=uX,E.invokeMap=ZJ,E.iteratee=j5,E.keyBy=QJ,E.keys=Je,E.keysIn=Nn,E.map=om,E.mapKeys=hX,E.mapValues=fX,E.matches=ltt,E.matchesProperty=ctt,E.memoize=im,E.merge=mX,E.mergeWith=oB,E.method=att,E.methodOf=utt,E.mixin=U5,E.negate=sm,E.nthArg=htt,E.omit=gX,E.omitBy=pX,E.once=dK,E.orderBy=YJ,E.over=ftt,E.overArgs=hK,E.overEvery=mtt,E.overSome=gtt,E.partial=O5,E.partialRight=Zw,E.partition=JJ,E.pick=CX,E.pickBy=rB,E.property=dB,E.propertyOf=ptt,E.pull=YY,E.pullAll=Pw,E.pullAllBy=JY,E.pullAllWith=KY,E.pullAt=XY,E.range=Ctt,E.rangeRight=Att,E.rearg=fK,E.reject=tK,E.remove=tJ,E.rest=mK,E.reverse=L5,E.sampleSize=nK,E.set=bX,E.setWith=vX,E.shuffle=oK,E.slice=eJ,E.sortBy=sK,E.sortedUniq=cJ,E.sortedUniqBy=aJ,E.split=zX,E.spread=gK,E.tail=uJ,E.take=dJ,E.takeRight=hJ,E.takeRightWhile=fJ,E.takeWhile=mJ,E.tap=DJ,E.throttle=pK,E.thru=nm,E.toArray=Xw,E.toPairs=iB,E.toPairsIn=sB,E.toPath=wtt,E.toPlainObject=eB,E.transform=yX,E.unary=CK,E.union=gJ,E.unionBy=pJ,E.unionWith=CJ,E.uniq=AJ,E.uniqBy=bJ,E.uniqWith=vJ,E.unset=kX,E.unzip=M5,E.unzipWith=Nw,E.update=wX,E.updateWith=BX,E.values=ca,E.valuesIn=EX,E.without=yJ,E.words=aB,E.wrap=AK,E.xor=kJ,E.xorBy=wJ,E.xorWith=BJ,E.zip=EJ,E.zipObject=xJ,E.zipObjectDeep=IJ,E.zipWith=TJ,E.entries=iB,E.entriesIn=sB,E.extend=nB,E.extendWith=am,U5(E,E),E.add=Ett,E.attempt=uB,E.camelCase=DX,E.capitalize=lB,E.ceil=xtt,E.clamp=xX,E.clone=vK,E.cloneDeep=kK,E.cloneDeepWith=wK,E.cloneWith=yK,E.conformsTo=BK,E.deburr=cB,E.defaultTo=rtt,E.divide=Itt,E.endsWith=SX,E.eq=Xo,E.escape=LX,E.escapeRegExp=MX,E.every=$J,E.find=jJ,E.findIndex=Rw,E.findKey=tX,E.findLast=UJ,E.findLastIndex=Ow,E.findLastKey=eX,E.floor=Ttt,E.forEach=Hw,E.forEachRight=jw,E.forIn=nX,E.forInRight=oX,E.forOwn=rX,E.forOwnRight=iX,E.get=P5,E.gt=EK,E.gte=xK,E.has=cX,E.hasIn=N5,E.head=Fw,E.identity=$n,E.includes=GJ,E.indexOf=UY,E.inRange=IX,E.invoke=dX,E.isArguments=$l,E.isArray=St,E.isArrayBuffer=IK,E.isArrayLike=Pn,E.isArrayLikeObject=Te,E.isBoolean=TK,E.isBuffer=ps,E.isDate=DK,E.isElement=SK,E.isEmpty=LK,E.isEqual=MK,E.isEqualWith=RK,E.isError=_5,E.isFinite=OK,E.isFunction=wi,E.isInteger=Qw,E.isLength=lm,E.isMap=Yw,E.isMatch=_K,E.isMatchWith=FK,E.isNaN=PK,E.isNative=NK,E.isNil=HK,E.isNull=$K,E.isNumber=Jw,E.isObject=Ae,E.isObjectLike=Be,E.isPlainObject=Rd,E.isRegExp=F5,E.isSafeInteger=jK,E.isSet=Kw,E.isString=cm,E.isSymbol=to,E.isTypedArray=la,E.isUndefined=UK,E.isWeakMap=zK,E.isWeakSet=VK,E.join=GY,E.kebabCase=RX,E.last=yo,E.lastIndexOf=ZY,E.lowerCase=OX,E.lowerFirst=_X,E.lt=WK,E.lte=qK,E.max=Dtt,E.maxBy=Stt,E.mean=Ltt,E.meanBy=Mtt,E.min=Rtt,E.minBy=Ott,E.stubArray=V5,E.stubFalse=W5,E.stubObject=btt,E.stubString=vtt,E.stubTrue=ytt,E.multiply=_tt,E.nth=QY,E.noConflict=dtt,E.noop=z5,E.now=rm,E.pad=FX,E.padEnd=PX,E.padStart=NX,E.parseInt=$X,E.random=TX,E.reduce=KJ,E.reduceRight=XJ,E.repeat=HX,E.replace=jX,E.result=AX,E.round=Ftt,E.runInContext=N,E.sample=eK,E.size=rK,E.snakeCase=UX,E.some=iK,E.sortedIndex=nJ,E.sortedIndexBy=oJ,E.sortedIndexOf=rJ,E.sortedLastIndex=iJ,E.sortedLastIndexBy=sJ,E.sortedLastIndexOf=lJ,E.startCase=VX,E.startsWith=WX,E.subtract=Ptt,E.sum=Ntt,E.sumBy=$tt,E.template=qX,E.times=ktt,E.toFinite=Bi,E.toInteger=Mt,E.toLength=tB,E.toLower=GX,E.toNumber=ko,E.toSafeInteger=GK,E.toString=Jt,E.toUpper=ZX,E.trim=QX,E.trimEnd=YX,E.trimStart=JX,E.truncate=KX,E.unescape=XX,E.uniqueId=Btt,E.upperCase=ttt,E.upperFirst=$5,E.each=Hw,E.eachRight=jw,E.first=Fw,U5(E,function(){var c={};return Tr(E,function(u,f){Wt.call(E.prototype,f)||(c[f]=u)}),c}(),{chain:!1}),E.VERSION=o,Rn(["bind","bindKey","curry","curryRight","partial","partialRight"],function(c){E[c].placeholder=E}),Rn(["drop","take"],function(c,u){Pt.prototype[c]=function(f){f=f===e?1:I(Mt(f),0);var C=this.__filtered__&&!u?new Pt(this):this.clone();return C.__filtered__?C.__takeCount__=L(f,C.__takeCount__):C.__views__.push({size:L(f,mo),type:c+(C.__dir__<0?"Right":"")}),C},Pt.prototype[c+"Right"]=function(f){return this.reverse()[c](f).reverse()}}),Rn(["filter","map","takeWhile"],function(c,u){var f=u+1,C=f==Ne||f==vr;Pt.prototype[c]=function(y){var x=this.clone();return x.__iteratees__.push({iteratee:vt(y,3),type:f}),x.__filtered__=x.__filtered__||C,x}}),Rn(["head","last"],function(c,u){var f="take"+(u?"Right":"");Pt.prototype[c]=function(){return this[f](1).value()[0]}}),Rn(["initial","tail"],function(c,u){var f="drop"+(u?"":"Right");Pt.prototype[c]=function(){return this.__filtered__?new Pt(this):this[f](1)}}),Pt.prototype.compact=function(){return this.filter($n)},Pt.prototype.find=function(c){return this.filter(c).head()},Pt.prototype.findLast=function(c){return this.reverse().find(c)},Pt.prototype.invokeMap=_t(function(c,u){return typeof c=="function"?new Pt(this):this.map(function(f){return Id(f,c,u)})}),Pt.prototype.reject=function(c){return this.filter(sm(vt(c)))},Pt.prototype.slice=function(c,u){c=Mt(c);var f=this;return f.__filtered__&&(c>0||u<0)?new Pt(f):(c<0?f=f.takeRight(-c):c&&(f=f.drop(c)),u!==e&&(u=Mt(u),f=u<0?f.dropRight(-u):f.take(u-c)),f)},Pt.prototype.takeRightWhile=function(c){return this.reverse().takeWhile(c).reverse()},Pt.prototype.toArray=function(){return this.take(mo)},Tr(Pt.prototype,function(c,u){var f=/^(?:filter|find|map|reject)|While$/.test(u),C=/^(?:head|last)$/.test(u),y=E[C?"take"+(u=="last"?"Right":""):u],x=C||/^find/.test(u);!y||(E.prototype[u]=function(){var O=this.__wrapped__,P=C?[1]:arguments,$=O instanceof Pt,Q=P[0],Y=$||St(O),X=function($t){var zt=y.apply(E,Er([$t],P));return C&&dt?zt[0]:zt};Y&&f&&typeof Q=="function"&&Q.length!=1&&($=Y=!1);var dt=this.__chain__,Ct=!!this.__actions__.length,yt=x&&!dt,Ot=$&&!Ct;if(!x&&Y){O=Ot?O:new Pt(this);var kt=c.apply(O,P);return kt.__actions__.push({func:nm,args:[X],thisArg:e}),new _n(kt,dt)}return yt&&Ot?c.apply(this,P):(kt=this.thru(X),yt?C?kt.value()[0]:kt.value():kt)})}),Rn(["pop","push","shift","sort","splice","unshift"],function(c){var u=kl[c],f=/^(?:push|sort|unshift)$/.test(c)?"tap":"thru",C=/^(?:pop|shift)$/.test(c);E.prototype[c]=function(){var y=arguments;if(C&&!this.__chain__){var x=this.value();return u.apply(St(x)?x:[],y)}return this[f](function(O){return u.apply(St(O)?O:[],y)})}}),Tr(Pt.prototype,function(c,u){var f=E[u];if(f){var C=f.name+"";Wt.call(en,C)||(en[C]=[]),en[C].push({name:u,func:f})}}),en[Q1(e,_).name]=[{name:"wrapper",func:e}],Pt.prototype.clone=XZ,Pt.prototype.reverse=tQ,Pt.prototype.value=eQ,E.prototype.at=SJ,E.prototype.chain=LJ,E.prototype.commit=MJ,E.prototype.next=RJ,E.prototype.plant=_J,E.prototype.reverse=FJ,E.prototype.toJSON=E.prototype.valueOf=E.prototype.value=PJ,E.prototype.first=E.prototype.head,Dl&&(E.prototype[Dl]=OJ),E},di=na();ii?((ii.exports=di)._=di,sd._=di):qe._=di}).call(cr)})(q2,q2.exports);const jq={mermaid:"https://mermaid-js.github.io/mermaid/",flowchart:"https://flowchart.js.org/",plantuml:"https://plantuml.com/"};class Uq extends I2{constructor(e,o,r,i){super(e,o,i);m(this,"group","hovering-toolbar");m(this,"_commands",[{id:"edit",name:R.t("graph.edit"),icon:Mp},{id:"add-comment",name:R.t("graph.comment"),icon:eu},{id:"separator",type:"separator",name:""},{id:"help",name:R.t("graph.help"),icon:fv}]);this.editor=e,this.block=o,this.graphType=r,this.properties=i}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(jq[this.graphType])}}function zq(n,t,e,o){return{blockCommands:{"hovering-toolbar":new Uq(n,t,e,o)},abstract:q2.exports.capitalize(e)}}class G2{constructor(t,e,o){m(this,"editor");m(this,"logger");m(this,"editing",!1);this.graphType=e,this.codeEmbedDataKey=o,this.editor=t,this.logger=S(`embed-block-${this.graphType}`)}i18nt(t,e){return R.t(`graph.${t}`,e||{})}getContent(t){g(this.logger,t,"embed-element does not exist");const e=t.parentElement;return g(this.logger,e,"content-element does not exist"),e}getEmbed(t){const e=t.childNodes[0];return g(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);g(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=w("div",["graph-embed"],t),{embedData:r}=e,i=r[`${this.codeEmbedDataKey}`],s=r.src,l=w("div",["embed-graph-img-content"],o),a=w("img",["graph-embed-image"],l);a.draggable=!1,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){et(t,"empty-embed","invalid-code");const r=t.querySelector("img.graph-embed-image");if(o){r.src="",W(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),W(t,"empty-embed")}}editGraph(t){this.editing=!0;const e=ot(t);g(this.logger,e,`${this.graphType} block does not exist`),K0(this.editor,e);const o=t.querySelector(".graph-embed"),r=l=>{this.updateImage(o,l,null,null)},i=async l=>{try{if(this.editing=!1,X0(this.editor,e),r(l),!this.hasChanged(e,l))return;const d={src:await this.code2ResourceId(l),[`${this.codeEmbedDataKey}`]:l};this.editor.updateEmbedData(e,d)}catch(a){this.updateClasses(o,l,a);const d={src:"",[`${this.codeEmbedDataKey}`]:l};this.editor.updateEmbedData(e,d)}},s=this.editor.getBlockData(e);Hq(this.editor,e,{onChange:r,onEnd:i,codeValue:s.embedData[`${this.codeEmbedDataKey}`]})}getBlockProperties(t,e){return this.editing?{}:zq(this.editor,t,this.graphType,{handleExecuteCommand:(o,r,i)=>{if(i.id==="edit"){if(!o.isBlockWritable(r))return!0;const s=Rt(r);return this.editGraph(s),!0}return i.id==="add-comment"?(o.readonly||Kf(o,r),!0):!1}})}hasChanged(t,e){return this.editor.getBlockData(t).embedData[`${this.codeEmbedDataKey}`]!==e}}const Vq="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js",Wq=["//cdnjs.cloudflare.com/ajax/libs/raphael/2.3.0/raphael.min.js","//cdnjs.cloudflare.com/ajax/libs/flowchart/1.15.0/flowchart.min.js"],qq="https://www.plantuml.com/plantuml/svg",Gq=S("mermaid-helper"),Zq="wiz-editor-mermaid";async function ok(n,t){var B;const o=((B=(n.getComponentOptions("mermaid")||{}).cdn)==null?void 0:B.mermaid)||Vq;await vs(o,Zq);const r=window.mermaid;g(Gq,r,"Resource load failed: Mermaid javaScript resource injection failed");const i=K(),l=await new Promise((D,T)=>{try{r.mermaidAPI.render(i,t,_=>{setTimeout(()=>{D(_)})})}catch(_){_.message=_.str,T(_)}}),h=new DOMParser().parseFromString(l,"image/svg+xml").firstChild,p=h.style.maxWidth;return p&&h.setAttribute("width",p),new XMLSerializer().serializeToString(h)}async function Qq(n,t){const e=await ok(n,t);return Lm(e,"image/svg+xml",`${K()}.svg`)}async function Yq(n,t){const e=await ok(n,t),o=new Blob([e]),r=new File([o],`${K()}.svg`,{type:"image/svg+xml"});return(await n.doc.uploadResource(r)).resourceId}class Rc extends G2{constructor(t){super(t,"mermaid","mermaidText")}static get(t,e){return t.addCustom(`mermaid-${e.id}`,()=>new Rc(t))}code2ObjectUrl(t){return Qq(this.editor,t)}code2ResourceId(t){return Yq(this.editor,t)}destroy(){}}const Jq={graph:{invalid:"\u65E0\u6548\u7684 {EmbedName} \u5185\u5BB9\uFF1A{message}",empty:"\u7A7A\u7684 {EmbedName}",edit:"\u7F16\u8F91",comment:"\u6279\u6CE8",help:"\u5E2E\u52A9"}},Kq={graph:{invalid:"Invalid {EmbedName} content: {message}",empty:"Empty {EmbedName}",edit:"Edit",comment:"Annotation",help:"Help"}},Xq={graph:{invalid:"\u7121\u52B9\u306A{EmbedName}\uFF1A{message}",empty:"\u7A7A\u306E {EmbedName}",edit:"\u7DE8\u96C6",comment:"\u6CE8\u91C8",help:"\u30D8\u30EB\u30D7"}};R.mergeLang({"zh-CN":Jq,"en-US":Kq,"ja-JP":Xq});function tG(n,t,e){Rc.get(n,e).createEmbedContent(t,e)}function eG(n,t,e){const o=Rc.get(n,n.getBlockData(t)),r=Rt(t);return o.updateEmbedContent(r,e),!0}function nG(n,t,e){const{data:o}=e,r=n.getBlockString(t).trim();if(!o||o.embedType!=="mermaid"||r!=="```mermaid"||!tt(n,t))return null;const i={src:"",mermaidText:""};return{blockData:{id:K(),type:"embed",embedType:"mermaid",embedData:i},onConverted:(a,d)=>{Rc.get(a,a.getBlockData(d)).editGraph(Rt(d))}}}function oG(n,t){return Rc.get(n,n.getBlockData(t)).getBlockProperties(t)}function rG(n,t,e,o){const{embedData:r}=t,i=r;if(o==="html")return i.src?`<img src="${n.doc.buildResourceUrl(i.src,{withToken:!0})}" />`:i.mermaidText?`<div class="mermaid">${i.mermaidText}</div>`:"<p>[mermaid]</p>";if(o==="markdown"){if(i.src)return`![mermaid](${n.doc.buildResourceUrl(i.src,{withToken:!0})})`;if(i.mermaidText)return`\`\`\`mermaid\`\`\`
745
745
  ${i.mermaidText}
746
746
  \`\`\`\`\`\``}return"[mermaid]"}const rk={embedType:"mermaid",convertFrom:nG,handleUpdateBlock:eG,createEmbedContent:tG,getBlockProperties:oG,convertTo:rG},ik=S("flowchart-helper");async function iG(n){var o;const t=n.getComponentOptions("flowchart")||{},e=((o=t==null?void 0:t.cdn)==null?void 0:o.flowchart)||Wq;for(let r=0;r<e.length;r+=1){const i=e[r];await vs(i,`flowchart-scripts-${r}`)}}async function sk(n,t){const e=w("div",["flowchart-chart-container"],document.body);e.id=`flowchart-${K()}`,await iG(n);const o=window.flowchart;g(ik,o,"flowchart resource does not exist"),o.parse(t).drawSVG(e.id);const i=e.firstElementChild;g(ik,i,"svg element non-existent");const l=new XMLSerializer().serializeToString(i);return e.remove(),l}async function sG(n,t){const e=await sk(n,t);return Lm(e,"image/svg+xml",`${Date.now()}.svg`)}async function lG(n,t){const e=await sk(n,t),o=new Blob([e]),r=new File([o],`${K()}.svg`,{type:"image/svg+xml"});return(await n.doc.uploadResource(r)).resourceId}class Oc extends G2{constructor(t){super(t,"flowchart","flowchartText")}static get(t,e){return t.addCustom(`flowchart-${e.id}`,()=>new Oc(t))}code2ObjectUrl(t){return sG(this.editor,t)}code2ResourceId(t){return lG(this.editor,t)}destroy(){}}function cG(n,t,e){Oc.get(n,e).createEmbedContent(t,e)}function aG(n,t,e){const o=Oc.get(n,e),r=Rt(t);return o.updateEmbedContent(r,e),!0}function uG(n,t,e){const{data:o}=e,r=n.getBlockString(t).trim();if(!o||o.embedType!=="flowchart"||r!=="```flowchart"||!tt(n,t))return null;const i={src:"",flowchartText:""};return{blockData:{id:K(),type:"embed",embedType:"flowchart",embedData:i},onConverted:(a,d)=>{Oc.get(a,a.getBlockData(d)).editGraph(Rt(d))}}}function dG(n,t){return Oc.get(n,n.getBlockData(t)).getBlockProperties(t)}function hG(n,t,e,o){const{embedData:r}=t,i=r;if(o==="html")return i.src?`<img src="${n.doc.buildResourceUrl(i.src,{withToken:!0})}" />`:i.flowchartText?`<div>${i.flowchartText}</div>`:"<p>[flowchart]</p>";if(o==="markdown"){if(i.src)return`![flowchart](${n.doc.buildResourceUrl(i.src,{withToken:!0})})`;if(i.flowchartText)return`\`\`\`flowchart\`\`\`
747
747
  ${i.flowchartText}