@ones-editor/editor 0.0.7-beta.12 → 0.0.7-beta.13
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 G3={boxType:"br",updateBoxContent:pS,convertTo:CS},Q3=M("editor-boxes");class Z3{constructor(t){m(this,"boxes",new Map);this.editor=t}registerBoxClass(t){const e=t.boxType,o=this.boxes.get(e);g(Q3,!o,`duplicated box type: ${e}`),this.boxes.set(e,t)}getBoxClass(t){const e=this.boxes.get(t);return g(Q3,e,`unknown box type: ${t}`),e}createBox(t,e){const o=E5(e),r=I5(o);return this.getBoxClass(e.type).updateBoxContent(this.editor,o,r,e),o}forEach(t){this.boxes.forEach(t)}}function bS(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=k("img",a,e);i&&(d.style.width=`${i}px`),s&&(d.style.height=`${s}px`),d.src=n.doc.buildResourceUrl(l)}const Y3={boxType:"image",updateBoxContent:bS},AS="data:image/svg+xml;base64,Cjxzdmcgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiB2aWV3Qm94PSIwIDAgMjQgMjQiIGZpbGw9InJnYigxNzgsIDE4OCwgMjA1KSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0ibTE3IDE1IDEuNTUgMS41NWMtLjk2IDEuNjktMy4zMyAzLjA0LTUuNTUgMy4zN1YxMWgzVjloLTNWNy44MkMxNC4xNiA3LjQgMTUgNi4zIDE1IDVjMC0xLjY1LTEuMzUtMy0zLTNTOSAzLjM1IDkgNWMwIDEuMy44NCAyLjQgMiAyLjgyVjlIOHYyaDN2OC45MmMtMi4yMi0uMzMtNC41OS0xLjY4LTUuNTUtMy4zN0w3IDE1bC00LTN2M2MwIDMuODggNC45MiA3IDkgN3M5LTMuMTIgOS03di0zbC00IDN6TTEyIDRjLjU1IDAgMSAuNDUgMSAxcy0uNDUgMS0xIDEtMS0uNDUtMS0xIC40NS0xIDEtMXoiPjwvcGF0aD4KPC9zdmc+Cg==";function vS(n,t,e){V(e,"editor-box-anchor"),Qg(AS,[],e)}const J3={boxType:"anchor",updateBoxContent:vS};function yS(n,t,e,o){k("span",[],e,o.text)}const K3={insertionType:"inputting",updateInsertionContent:yS},X3=M("editor-insertion");class ty{constructor(t){m(this,"insertions",new Map);this.editor=t}registerInsertionClass(t){const e=t.insertionType,o=this.insertions.get(e);g(X3,!o,`duplicated insertion type: ${e}`),this.insertions.set(e,t)}getInsertionClass(t){const e=this.insertions.get(t);return g(X3,e,`unknown insertion type: ${t}`),e}createInsertion(t,e){const o=T5(e.type,e.id),r=D5(o);return this.getInsertionClass(e.type).updateInsertionContent(this.editor,o,r,e),o}}class kS{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=S5(this.editor,e);r&&rt(r,"active"),this.cursors.delete(e)}})},1e3)}destroy(){clearInterval(this.timer)}}function wS(n,t,e,o){var l;const r=o;Date.now()-r.time<5*1e3&&(n.addCustom("active-cursors",d=>new kS(d)).add(r.id,r.time),V(t,"active")),k("span",[],e,"|").setAttribute("data-cursor-name",r.name),t.style.setProperty("--cursor-color",n.getColor((l=r.rainbowIndex)!=null?l:0))}const Yp={insertionType:"remote-cursor",updateInsertionContent:wS};class ey{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 Jp=M("editor-input");class BS{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)&&!Ds(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)&&!Ds(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),Jp.debug("on cut")});m(this,"handlePaste",t=>{if(t.target instanceof HTMLInputElement&&this.inputElement===t.target){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=k("input",["editor-input"],t.contentElement);o.type="text",o.name="editor-input",o.onkeydown=this.handleKeyDown,o.oninput=this.handleInput,o.oncopy=this.handleCopy,document.addEventListener("paste",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,document.removeEventListener("paste",this.handlePaste),t.oncut=null}getInput(){return this.inputElement}focus(){this.editor.selection.caret.visible()||this.editor.selection.caret.update(),ge.isMobileSafari?(this.inputElement.focus(),V(this.editor.rootElement,"active")):setTimeout(()=>{this.inputElement.focus(),V(this.editor.rootElement,"active")})}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(Jp,t===this.editor,"invalid editor"),this.callbacks.defaultInsertText(t,e,o,r,i)}defaultHandleKeydown(t,e){return g(Jp,t===this.editor,"invalid editor"),this.callbacks.defaultHandleKeydown(t,e)}}function ny(n){const t=n.rootElement,e=t.getBoundingClientRect(),o=io(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,C=0-e.left+h,v=0-e.top+p,B=n.input.inputElement;B.style.left=`${C/o}px`,B.style.top=`${v/o}px`}const Kp=M("editor-caret");class ES{constructor(t){m(this,"editor");m(this,"caretElem");m(this,"handleReadOnlyChanged",()=>{this.update()});this.editor=t,this.caretElem=k("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 Ve))return!1;const e=this.editor.getBlockById(t.blockId);return!!et(this.editor,e)}update(){if(Pv(this.editor.rootElement))return;const t=this.caretElem;if(this.hasCaret())t.style.display="";else{t.style.display="none",ny(this.editor);return}const{range:e}=this.editor.selection;g(Kp,e.isCollapsed,"range is not collapsed");const o=e.start;g(Kp,o instanceof Ve,"only simple block position can has caret");const r=this.editor.getBlockById(o.blockId);g(Kp,et(this.editor,r),"only text kind block can has caret");let i;const s=r.querySelector("span.inputting-insertion");s?(i=vs(s),i=new DOMRect(i.right,i.top,1,i.height)):i=Vn(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`,ge.isMobileSafari&&(h.style.left=`${a-4}px`,h.style.height=`${i.height}px`);const C=lo(r,{horizontal:!0}).getBoundingClientRect(),v=C.left-l.left,B=v+C.width;a<v||a>B?(ny(this.editor),t.style.display="none"):t.style.display=""}}function xS(n){_5(n),n.selection.range.getSelectedBlocks().forEach(t=>F5(n,t.block,t.start,t.end))}const IS=M("editor-dom");function oy(n){return lo(n.rootContainer).clientHeight}function TS(n){return n.getFirstBlock().getBoundingClientRect().top}function SS(n){return n.getLastBlock().getBoundingClientRect().bottom}function Xp(n){const e=lo(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 DS(n,t){const e=Xp(n),o=n.getBlockById(t.blockId),i=Mo(n,o,t);return ks(e,i.x,i.y)&&ks(e,i.right,i.bottom)}function ry(n,t){const e=Xp(n),o=t.getBoundingClientRect();return o.top>=e.top&&o.top<=e.bottom||o.bottom<=e.bottom&&o.bottom>=e.top}function MS(n,t){const e=Xp(n),o=t.getBoundingClientRect();return ks(e,o.x,o.y)||ks(e,o.right,o.bottom)}function LS(n){if(!Kg(n.rootContainer)){IS.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 p=o,C=n.getContainerById(p.childContainerId);MS(n,C)||C.scrollIntoView();return}if(e.range.start.blockId===e.range.end.blockId){const p=n.getBlockById(e.range.start.blockId);if(Se(p)&&ry(n,p)||Lt(n,p)&&ry(n,p))return}const r=o,i=n.getBlockById(r.blockId);if(DS(n,r))return;const s=Mo(n,i,r),l=i.getBoundingClientRect(),a=te(i),d=k("div",["editor-block-anchor"],a),h=io(i);d.style.top=`${(s.top-l.top)/h}px`,lh(d,{elementToScroll:lo(n.rootContainer)}),setTimeout(()=>{d.remove()},200)}function RS(n,t){if(t.isCollapsed())return!1;const e=we(n.rootContainer),o=Ze(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 iy=M("range-in-block");function sy(n,t){const e=t.getEditor(),o=e.getBlockById(t.start.blockId),r=e.getBlockById(t.end.blockId),i=o===n||Xt(n,o),s=r===n||Xt(n,r);return!!(i||s)}function ly(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=ae(t);if(i){for(;i&&!o.has(it(i));)i=ae(i);g(iy,i,"no prev block while deleting a block"),r=be(n,i,ut(n,i))}else{const s=qt(t);g(iy,s,"no prev and next block while deleting a block"),r=be(n,s,0)}return r}const OS=M("block-to-html");function t1(n,t,e,o){const r=Ls(n,t.type);if(r.convertTo)return r.convertTo(n,t,e,"html",o);if(r.blockKind!=="text")return`[${t.type}]`;g(OS,t.text,"no text");const i=se(t.text);return`<div>${jv(i)}</div>`}const cy=M("block-to-text");function _S(n,t,e){let o="";return t.forEach(r=>{if(g(cy,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 Nh(n,t,e,o){const r=Ls(n,t.type);return r.convertTo?r.convertTo(n,t,e,"text",o):r.blockKind!=="text"?`[${t.type}]`:(g(cy,t.text,"no text"),_S(n,t.text,e))}function e1(n,t,e,o){const r=Ls(n,t.type);return r.convertTo?r.convertTo(n,t,e,"markdown",o):Nh(n,t,e,o)}function $h(n,t){return t.blocks.root.map((r,i)=>t1(n,r,t,[{containerId:"root",blockIndex:i}])).join(`
|
|
25
25
|
`)}function ay(n,t){return`<!doctype html><html><head><meta charset="utf8" /></head><body>${$h(n,t)}</body></html>`}function Hs(n,t){return t.blocks.root.map((r,i)=>Nh(n,r,t,[{containerId:"root",blockIndex:i}])).join(`
|
|
26
26
|
`)}function uy(n,t){const e=t.blocks.root.map((r,i)=>e1(n,r,t,[{containerId:"root",blockIndex:i}]));return e[e.length-1]=e[e.length-1].trimEnd(),e.join(`
|
|
27
|
-
`)}const FS=M("get-text-position");function ec(n,t){const e=t!=null?t:n.selection.range.start;e instanceof Ve||g(FS,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=vt(r),s=ot(r),l=at(s),{offset:a}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:a}}const nc=M("insert-text");function n1(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(g(nc,r,"no block data"),g(nc,r.text,"no block text"),sn(r.text)===0)return g(nc,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=qe(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function PS(n,t,e){const o=ot(t),r=at(o),i=vt(t);return n1(n,r,i,e)}function dy(n,t,e,o,r){const i=ot(t),s=at(i),l=vt(t),a=PS(n,t,e),d=Th(e,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),Cn(n,t)}function hy(n,t,e,o){const r=ot(t),i=at(r),s=vt(t),l=Th(e," ",o);return n.doc.localUpdateBlockText(i,s,l),Cn(n,t)}function NS(n,t){let e=0;if(t===0)return!1;for(let o=0;o<n.length;o++){const r=n[o];g(nc,typeof r.insert=="string","invalid text op, no insert");const i=e+Sh(r);if(i===t)return!1;if(i>t)return!0;e=i}return!1}function o1(n,t,e,o,r){const i=n.doc.getBlockData(e,o);g(nc,i,"no block data"),g(nc,i.text,"no block text");const s=n1(n,e,o,r);s&&Object.keys(s).includes("link")&&(NS(i.text,r)||delete s.link);const l=Th(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),Cn(n,n.getBlockById(i.id))}function r1(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=ec(n);o1(n,t,e,o,r)}const Hh=M("update-composition-text");function fy(n){const t=n.selection.range.start;t instanceof Ve||g(Hh,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);g(Hh,et(n,o),"not a text kind block");const r=ot(o),i=at(r),s=vt(o),l=n.doc.getBlockData(i,s);g(Hh,l,"no block data in doc"),g(Hh,l.text,"no text data in text block");const a=Mt(o);Bh(n,Ri(o),e,a,l.text)}function my(n){gT(n)}function oc(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const qa=M("delete-block-text");function i1(n,t,e,o,r){if(!n.isBlockWritable(t))return qa.error("block is not writable"),0;g(qa,et(n,t),"block is not a text kind block");const i=ot(t),s=at(i),l=vt(t),a=n.doc.getBlockData(s,l);g(qa,a,"no block data in doc"),g(qa,a.text,"no text data in text block");let d=e;ln(t,e)||(d=_i(t,d));let h=e+o;g(qa,h<=ut(n,t),`invalid offset and count: ${e}, ${o}`),ln(t,h)||(h=Fs(t,h));const p=h-d,C=w3(d,p);return n.doc.localUpdateBlockText(s,l,C,r),p}const s1=M("break-text-block");function gy(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function rc(n,t,e,o){g(s1,et(n,t),`block is not a text kind block: ${St(t)}`),g(s1,e>=0&&e<=ut(n,t),`invalid offset: ${e}`);const r=ot(t),i=at(r),s=vt(t),l=o!=null&&o.copyBlockAttributes?gy(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===ut(n,t))){const v=e===0?s:s+1,B={...ur(""),...l,...o==null?void 0:o.newBlockData},x=be(n,t.id,0),I=oc(n,i,v,B,x);return{block:t,newBlock:I}}g(s1,ln(t,e),"not a valid offset");const a=Cn(n,t),{right:d}=Tn(a,e),h=sn(d);h>0&&i1(n,t,e,h);const p={...ur(d),...l,...o==null?void 0:o.newBlockData},C=oc(n,i,s+1,p,be(n,p.id,0));return{block:t,newBlock:C}}const $S=M("prepare-insert-new-block");function HS(n,t,e){if(t&&e!==void 0&&e!==null){const d=n.getContainerById(t),h=fe(d);return g($S,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(ot(r)),e=vt(r),!et(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=rc(n,r,s).newBlock;return{containerId:t,blockIndex:vt(a)}}const jS=M("auto-insert-block");function py(n,t,e,o,r,i){const s=HS(n,e,o);g(jS,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},a={anchor:l,focus:l};return oc(n,s.containerId,s.blockIndex,t,r!=null?r:a,i)}const US=M("delete-block");function jh(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{jh(n,i,e)})}))}function Uh(n,t,e){const o=ot(t),r=at(o),i=vt(t),s=n.doc.getBlockData(r,i);return g(US,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,We(n,{anchor:e.start,focus:e.end})),s}function l1(n,t,e){return n.undoManager.runInGroup(()=>{const o=ot(t);To(o)===1&&n.insertTextBlock("",at(o),0);let r=e?Oi(n,e):null;if(!r){const l=n.selection.range;sy(t,l)?r=ly(n,t):r=l}const i=Uh(n,t,r),s=[];return jh(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function zS(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{jh(n,r,e)}),n.doc.localDeleteChildContainers(e)}function Cy(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{jh(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const c1=M("merge-text-block");function by(n,t,e){g(c1,et(n,t),"only text block can be merged"),g(c1,et(n,e),"only text block can be merged");const o=Fi(n,t),r=Fi(n,e),i=o.text,s=r.text;g(c1,i&&s,"block data has no text");const l=ot(t),a=at(l),d=vt(t),h=ut(n,t),p=o1(n,s,a,d,h),C=be(n,t,sn(i));return l1(n,e,C),p}const dr=M("clear-selected-contents");function zh(n,t){g(dr,et(n,t.block),"not a text kind block");const{start:e,end:o}=t;g(dr,e.isSimple(),"not a simple block position"),g(dr,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;g(dr,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function Ay(n,t,e){const o=at(t),r=fe(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 VS(n,t){const{block:e,start:o,end:r}=t;if(et(n,e)){zh(n,t);return}if(Se(e)||o.isSimple()){g(dr,r.isSimple(),"invalid range");const s=ot(e),l=vt(e),a=n.insertTextBlock("",at(s),l);n.selection.selectBlock(a,0),n.deleteBlock(e);return}g(dr,Lt(n,e),"invalid block kind"),g(dr,!o.isSimple()&&!r.isSimple(),"invalid range"),Jl(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{Ay(n,s,{focus:l===0})})}function WS(n){if(!n.isWritable())return;const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(g(dr,e.length>0,"no selected block"),e.length===1){VS(n,e[0]);return}const o=e[0],r=o.block,i=ot(r);g(dr,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(et(n,r)){zh(n,o);const h=be(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(C=>n.deleteBlock(C.block)),et(n,l)){zh(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(et(n,l)){zh(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===To(i)){Ay(n,i,{focus:!0});return}const a=ae(r),d=qt(l);g(dr,a||d,"no prev or next block"),e.forEach(h=>n.deleteBlock(h.block))}function a1(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),WS(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const qS=M("core");function vy(n,t,e){const o=ot(t),r=at(o),i=vt(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),Cn(n,t)}function yy(n,t,e){if(!n.isBlockWritable(t)){qS.error("block is not writable");return}const o=n.getBlockText(t),r=cn.diff(o,e);vy(n,t,r)}function Vh(n,t,e){const o=Cn(n,t),r=typeof e=="string"?$s(e):e,i=cn.diff(o,r);return vy(n,t,i)}const Ga=M("update-block-data");function Wh(n,t,e,o){const r=ot(t),i=at(r),s=vt(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(C=>{if(!h.has(C)){if(C==="id"||C==="type"||C==="text")return;Ga.debug(`delete key: ${C}`),a.delete.push(C)}}),Object.entries(e).forEach(([C,v])=>{g(Ga,C!=="id"&&C!=="type",`invalid block data delta, ${C}`);const B=l[C];if(v==null){B!=null&&(Ga.debug(`delete key: ${C}`),a.delete.push(C));return}B!==v&&(ka.default(B,v)||C==="text"&&cn.diff(B,v).length===0||(d.has(C)?(Ga.debug(`replace key: ${C}`),a.delete.push(C)):Ga.debug(`insert key: ${C}`),a.insert[C]=v))}),n.doc.localUpdateBlockData(i,s,a,o),Fi(n,t)}function ky(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function u1(n,t,e){if(!Lt(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=zn(n,t).getChildContainers(n,t)[0],i=we(r);u1(n,i,e)}function js(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 Qa=M("clone-block");function Pi(n,t,e,o){const r=n.getBlockClass(e.type);if(r.blockToDoc)return r.blockToDoc(t,e,(h,p)=>(g(Qa,e!==p,"invalid child block"),Pi(n,h,e,o)));let i={};const s=new Map,l=mt.default(e);l.children&&(l.children=l.children.map(h=>{const p=tt(),C=t.blocks[h];g(Qa,Array.isArray(C),"invalid child blocks");const v=C.map(_=>Pi(n,t,_,o)),B=js(v),{root:x,...I}=B.blocks;return i={...i,...I},i[p]=B.blocks.root,s.set(h,p),p}));const a=Array.from(s.entries()),d=h=>{for(const p of a){const[C,v]=p;{const B=`${C}/`;if(h.startsWith(B)){const x=h.substring(B.length),I=`${v}/${x}`;return Qa.debug(`replace key: ${h} -> ${I}`),I}}{const B=`${C}_`;if(h.startsWith(B)){const x=h.substring(B.length),I=`${v}_${x}`;return Qa.debug(`replace key: ${h} -> ${I}`),I}}}return h};return Array.from(Object.entries(l)).forEach(([h,p])=>{const C=d(h);C!==h&&delete l.key,l[C]=p}),l.id=tt(),o&&(o.blockIdMap.set(e.id,l.id),s.forEach((h,p)=>o.containerIdMap.set(p,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function d1(n,t,e,o){const r=t.blocks[e];g(Qa,Array.isArray(r),"invalid child blocks");const i=r.map(l=>Pi(n,t,l,o));return js(i)}function h1(n,t,e){const o=t.blocks.root.map(r=>Pi(n.editorBlocks,t,r,e));return mt.default(js(o))}const wy=M("insert-doc");function By(n,t,e,o,r){if(Lt(n,t)){wy.warn("failed to insert doc into a complex block");return}const i=h1(n,o,r),s=ot(t),l=vt(t),a=at(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var H,W,G;const d=[];Object.entries(i.blocks).forEach(([K,ht])=>{K!=="root"&&d.push({containerId:K,blocks:ht})}),d.length>0&&n.doc.localInsertChildContainers(d);const h=i.blocks.root;if(Se(t)){n.deleteBlock(t);let K;h.reverse().forEach(ht=>{const bt=n.insertBlock(a,l,ht,void 0,{noFocus:!0});K||(K=bt)}),K&&n.selection.selectBlock(K,ut(n,K));return}if(g(wy,et(n,t),"not a text block"),ue(n,t)){const K=a==="root"&&n.getBlockByIndex(a,0)===t,ht=vt(t);let bt;h.forEach((_t,Ht)=>{const oe=n.insertBlock(a,ht+Ht,_t,void 0,{noFocus:!0});Ht===h.length-1&&(bt=oe)}),bt&&n.selection.selectBlock(bt,ut(n,bt)),K&&n.deleteBlock(t);return}if(h.length===1){const K=h[0];if(_a(n,K.type)){n.insertTextToBlock(t,e,(H=K.text)!=null?H:[]);return}n.breakTextBlock(t,e),n.insertBlock(a,l+1,K);return}const p=e===ut(n,t),C=e===0,v=h[0],B=h[h.length-1];let x;!p&&!C?x=n.breakTextBlock(t,e,{forceInsertAfter:!0}):x=t;const I=C?l:l+1;p?(x=n.insertBlock(a,l+1,B),n.selection.selectBlock(x,ut(n,x))):(n.selection.selectBlock(x,0),_a(n,B.type)?n.insertTextToBlock(x,0,(W=B.text)!=null?W:[]):n.insertBlock(a,I,B));const _=n.selection.range;let D=I;_a(n,v.type)?C?(n.insertBlock(a,I,v),D+=1):n.insertTextToBlock(t,e,(G=v.text)!=null?G:[]):(n.insertBlock(a,I,v),D+=1),h.slice(1,h.length-1).reverse().forEach(K=>{n.insertBlock(a,D,K)}),n.selection.setRange(_)}),n.doc.endBatchUpdate()}function f1(n,t,e,o,r){const i=h1(n,o,r),s=at(t),l=[];return n.undoManager.runInGroup(()=>{const a=[];Object.entries(i.blocks).forEach(([h,p])=>{h!=="root"&&a.push({containerId:h,blocks:p})}),n.doc.localInsertChildContainers(a),i.blocks.root.reverse().forEach(h=>{const p=n.insertBlock(s,e,h,void 0,{noFocus:!0,noScroll:!0});l.push(p)})}),l}function Ey(n,t,e){const o=To(t);f1(n,t,o,e);for(let r=0;r<o;r++){const i=we(t);n.deleteBlock(i)}}const Za=M("add-text-attribute");function GS(n,t,e,o){const{start:r,end:i}=e;g(Za,r.blockId===i.blockId&&r.blockId===it(t),"invalid range"),g(Za,o,"invalid attribute name");const s=n.getBlockText(t),l=tc(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function xy(n,t,e,o,r){const{start:i,end:s}=e;g(Za,i.blockId===s.blockId&&i.blockId===it(t),"invalid range"),g(Za,o,"invalid attribute name");const l=n.getBlockText(t),a=Ua(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function ic(n,t,e,o,r){const{start:i,end:s}=e;g(Za,i.blockId===s.blockId&&i.blockId===it(t),"invalid range");const l=n.getBlockText(t),a=L3(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Iy(n,t,e,o){const r=lr(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!et(n,s))return;if(ue(n,s)){o(n,it(s),t,e);return}const d=We(n,{anchor:l,focus:a});t==="color"||t==="backgroundColor"?ic(n,s,d,t,e):(ic(n,s,d,"color",null),ic(n,s,d,"backgroundColor",null))})})}function Ty(n,t,e){const o=lr(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!et(n,i))return;if(ue(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=We(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&ic(n,i,a,"color",null),(t==="clearBackground"||t==="clearAll")&&ic(n,i,a,"backgroundColor",null)})})}function Sy(n,t,e){const o=t.getSelectedBlocks().filter(l=>et(n,l.block));if(o.length===0)return[null,null];const r=l=>{if(ut(n,l.block)===0)return e(n,it(l.block));const a=l.start,d=l.end,h=n.getBlockText(l.block);return _3(a.offset,d.offset-a.offset,h)};let[i,s]=r(o[0]);return i===null&&s===null?[i,s]:(o.forEach(l=>{const[a,d]=r(l);a===null||i===null?i=null:i=a===i?i:null,d===null||s===null?s=null:s=d===s?s:null}),[i,s])}const Wn=M("adjust-selection-pos");function Dy(n){const t=[];for(;n;){const e=ot(n);if(t.unshift(e),Qt(e))return t;const o=nt(e);g(Wn,o,"child container has not parent container"),n=o}g(Wn,!1,"should not come here: getParentContainers")}function My(n,t){for(;t;){const e=ot(t);if(e===n)return t;const o=nt(e);g(Wn,o,"could not find parent block for a child container"),t=o}g(Wn,!1,"no parent block in specified container")}function QS(n,t){const e=Dy(n),o=Dy(t);g(Wn,e.length>0&&o.length>0,"block has not parent container"),g(Wn,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=My(r,n),s=My(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function Ly(n,t){let e=nt(t);for(g(Wn,e,"element is not in a block");e;){const o=ot(e);g(Wn,Lo(o),"not a child container");const r=nt(o);if(g(Wn,r,"child container has not parent block"),r===n)return o;e=r}g(Wn,!1,"failed to find parent container in complex block")}function qh(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof Ve&&e instanceof Ve?{anchor:t,focus:e}:t instanceof Ro&&e instanceof Ro?kh(n,o,t,e):null;const i=ot(o),s=ot(r);if(i===s)return t instanceof Ro&&(t=st(o,0,"home")),e instanceof Ro&&(e=st(r,ut(n,r),"end")),g(Wn,t instanceof Ve,"not valid position type"),g(Wn,e instanceof Ve,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof Ve&&e instanceof Ro){const B=n.getContainerById(e.childContainerId);if(B===i)return{anchor:e,focus:e};const x=nt(i);if(x&&x===nt(B)){const I=me(x,at(i)),_=me(x,at(B));return kh(n,x,I,_)}}return null}const l=ih(o,r)>0,{newBlock1:a,newBlock2:d}=QS(o,r);if(a===d){const B=a,x=Ly(B,o),I=Ly(B,r);return t=me(a,at(x)),e=me(a,at(I)),Wn.debug(`select in complex block: ${x.id}, ${I.id}`),kh(n,B,t,e)}let h=l?ut(n,a):0;a===o&&t instanceof Ve&&(h=t.offset);let C=l?0:ut(n,d);return d===r&&e instanceof Ve&&(C=e.offset),t=st(a,h,l?"end":"home"),e=st(d,C,l?"home":"end"),{anchor:t,focus:e}}const ZS=M("move-complex-block-position");function YS(n,t,e){const o=n.getBlockById(t.blockId);g(ZS,Lt(n,o),"is not a complex block");const r=zn(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?me(o,at(s)):null}const Ya=M("move-simple-block-position");function Ry(n,t){const e=pn(n,t,{visibleOnly:!0});g(Ya,e.length>0,"complex block has not any child container");const o=e[0];return we(o)}function Oy(n,t){const e=pn(n,t,{visibleOnly:!0});g(Ya,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Ze(o)}function _y(n,t,e){const o=e?Ry(n,t):Oy(n,t);return Lt(n,o)?_y(n,o,e):o}function JS(n,t){const e=n.getBlockById(t.blockId);return Lt(n,e)&&t.offset===0?Ry(n,e):Ss(e)}function KS(n,t){const e=n.getBlockById(t.blockId);return Lt(n,e)&&t.offset===1?Oy(n,e):Ts(e)}function m1(n){return n==="ArrowLeft"||n==="ArrowUp"}function g1(n,t,e){const o=ot(t);if(Qt(o))return null;const r=nt(o);g(Ya,r,"child container has not parent block"),g(Ya,Lt(n,r),"is not a complex block");const i=zn(n,r).getNextContainer(n,r,o,e);return i?m1(e)?Ze(i):we(i):g1(n,r,e)}function XS(n,t,e){const o=ot(t);if(Qt(o))return null;const r=nt(o);if(g(Ya,r,"child container has not parent block"),m1(e)){const l=ae(r);if(l)return l}else{const l=qt(r);if(l)return l}const i=g1(n,r,e);if(i)return i;let s=r;for(;!Qt(ot(s));)s=nt(ot(s));return m1(e)?ae(s):qt(s)}function tD(n,t,e){return!Lt(n,t)||zn(n,t).enableKeyboardSelect?t:_y(n,t,e==="ArrowDown"||e==="ArrowRight")}function eD(n,t,e){const o=n.getBlockById(t.blockId),i=Yt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?JS(n,t):KS(n,t);if(s||(s=g1(n,o,e),s||(s=XS(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Qt(ot(o)))return null;const l=n.insertTextBlock("",at(n.rootContainer),To(n.rootContainer));return st(l,0,"home")}return null}if(s=tD(n,s,e),et(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return IT(n,s,o,t,l);if(e==="ArrowUp")return xT(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 nD(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(et(n,r))return o;const i=qt(r);if(i)return st(i,0,"home");if(!Qt(ot(r))||n.readonly)return o;const s=n.insertTextBlock("",at(n.rootContainer),To(n.rootContainer));return st(s,0,"home")}function oD(n,t,e){const o=n.selection.range;let r;if(o instanceof Ye)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=nD(n,t,o):r=eD(n,o.getFocusedPos(),t);else if(r=YS(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=Ze(s);r=st(l,0,"home")}else{const l=we(s);r=st(l,ut(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:qh(n,o.anchor,r):null}function Ni(n,t,e){const o=oD(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 Fy(n){return Ni(n,"ArrowLeft","move"),!0}function Py(n){return Ni(n,"ArrowRight","move"),!0}function Ny(n){return Ni(n,"ArrowUp","move"),!0}function $y(n){if(Ni(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=ot(t);if(Qt(e)||Ze(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",at(o),To(o)),!0}function Hy(n){return Ni(n,"ArrowDown","select"),!0}function jy(n){return Ni(n,"ArrowLeft","select"),!0}function Uy(n){return Ni(n,"ArrowRight","select"),!0}function zy(n){return Ni(n,"ArrowUp","select"),!0}const Vy=M("word-offset");function p1(n,t){const e=n.selection.range.focus;g(Vy,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(ue(n,o))return st(o,0,"home");if(e.offset===0||!et(n,o)){const s=ae(o);if(!s)return null;const l=st(s,ut(n,s),"end");if(t==="select"&&et(n,s)){const a=Qp(n,s,l.offset);return st(s,a,"normal")}return l}const r=Qp(n,o,e.offset);return st(o,r,"normal")}function C1(n,t){const e=n.selection.range.focus;g(Vy,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(ue(n,o))return st(o,0,"end");if(e.offset===ut(n,o)||!et(n,o)){const s=qt(o);if(!s)return null;const l=st(s,0,"home");if(t==="select"&&et(n,s)){const a=Zp(n,s,l.offset);return st(s,a,"end")}return l}const r=Zp(n,o,e.offset);return st(o,r,"normal")}function Wy(n){if(!n.selection.range.focus.isSimple())return!1;const e=p1(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function qy(n){if(!n.selection.range.focus.isSimple())return!1;const e=C1(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function Gy(n){if(!n.selection.range.focus.isSimple())return!1;const e=p1(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function Qy(n){if(!n.selection.range.focus.isSimple())return!1;const e=C1(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}M("find-block");function b1(n,t){if(!Lt(n,t))return t;const o=zn(n,t).getChildContainers(n,t)[0],i=fe(o)[0];return b1(n,i)}function A1(n,t){if(!Lt(n,t))return t;const e=zn(n,t).getChildContainers(n,t),o=e[e.length-1],r=fe(o),i=r[r.length-1];return A1(n,i)}function v1(n){const t=A1(n,Ze(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(e),!0}function Zy(n){const t=b1(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(e),!0}function Yy(n){const t=b1(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function y1(n){const t=A1(n,Ze(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}const Jy=M("line-offset");function Ky(n){const t=n.selection.range.focus;g(Jy,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!et(n,e))return st(e,0,"home");let r=b3(e,t).start;const{next:i}=bh(e,r);return i&&ao(i)&&Oa(i)==="br"&&(r+=1),st(e,r,"home")}function Xy(n){const t=n.selection.range.focus;g(Jy,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===ut(n,e)||!et(n,e))return st(e,ut(n,e),"end");const o=b3(e,t);return st(e,o.end,"end")}function tk(n){if(!n.selection.range.focus.isSimple())return!1;const e=Ky(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function ek(n){if(!n.selection.range.focus.isSimple())return!1;const e=Xy(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function nk(n){if(!n.selection.range.focus.isSimple())return!1;const e=Ky(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function ok(n){if(!n.selection.range.focus.isSimple())return!1;const e=Xy(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const rk=M("find-block-position");function rD(n,t,e,o){g(rk,Lt(n,t),"is not a complex block");const r=zn(n,t).getChildContainers(n,t);g(rk,r.length>0,"complex block has not any child container");const i=Mo(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,a=l3(n,t,s,l);return k1(n,a,e,o)}function k1(n,t,e,o){if(Lt(n,t))return rD(n,t,e,o);const r=it(t);let i=Number.MAX_SAFE_INTEGER;const s=Mo(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 C=st(r,p,"normal"),v=Mo(n,t,C),B=nr(v,l,a);B<i&&(i=B,d=C)}return d}const ik=M("page-offset");function iD(n,t){const e=oy(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<TS(n))return n.getFirstBlock();const i=ae(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=ae(s)}return n.getFirstBlock()}function sD(n,t){const e=oy(n)*.9,o=t.getBoundingClientRect(),r=SS(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=qt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=qt(l)}return n.getLastBlock()}function sk(n){const t=n.selection.range.focus;g(ik,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=iD(n,e);let r;return o===n.getFirstBlock()?r=st(o,0,"home"):r=k1(n,o,e,t),r}function lk(n){const t=n.selection.range.focus;g(ik,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=sD(n,e);let r;return o===n.getLastBlock()?r=st(o,ut(n,o),"end"):r=k1(n,o,e,t),r}function ck(n){if(!n.selection.range.focus.isSimple())return!1;const e=sk(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function ak(n){if(!n.selection.range.focus.isSimple())return!1;const e=lk(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function uk(n){if(!n.selection.range.focus.isSimple())return!1;const e=sk(n);if(!e)return!1;const o=qh(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 dk(n){if(!n.selection.range.focus.isSimple())return!1;const e=lk(n);if(!e)return!1;const o=qh(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 Ja=M("select-all");function hk(n,t){const e=we(n),o=Ze(n);return t.start.offset===0&&t.start.blockId===it(e)&&t.end.offset===ut(t.getEditor(),o)&&t.end.blockId===it(o)}function lD(n,t){const e=t.getEditor(),o=zn(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 cD(n,t){g(Ja,t,"no parent block"),g(Ja,Lt(n,t),"not a complex block");const e=zn(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(We(n,{anchor:me(t,at(o)),focus:me(t,at(r))}))}function fk(n,t){const e=ot(t);w1(n,e)}function mk(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&et(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 V(n.rootContainer,"select-all"),fk(n,we(n.rootContainer)),!1}return g(Ja,!e.isSimple(),"invalid range type"),lD(t,e)?(fk(n,t),!1):(g(Ja,t,"no parent block"),g(Ja,Lt(n,t),"not a complex block"),cD(n,t),!0)}function w1(n,t){const e=fe(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 aD(n){y1(n),n.focus()}const B1=M("selected-block-to-doc");function gk(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{gk(n,i,e)}),e.blocks[o]=mt.default(r)})}function Gh(n,t){const e=Yt(n,t.block);if(e.selectionToDoc)return e.selectionToDoc(n,t);const o=mt.default(Fi(n,t.block));if(et(n,t.block)){const i=t.start,s=t.end;if(g(B1,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=qe(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(Se(t.block))return{blocks:{root:[o]},meta:{},comments:{}};g(B1,Lt(n,t.block),"not complex block"),g(B1,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return gk(n,o,r),r}function E1(n,t){const e=st(t,0,"normal"),o=st(t,ut(n,t),"end");return Gh(n,{block:t,start:e,end:o})}const uD=M("block-to-doc");function dD(n,t){g(uD,t.length>0,"invalid params, no blocks");const e=t.map(o=>E1(n,o));return js(e)}function Qh(n){const e=n.selection.range.getSelectedBlocks().map(o=>Gh(n,o));return js(e)}function pk(n,t){const e=n.getContainerById(t),i=fe(e).map(s=>({start:st(s,0,"home"),end:st(s,ut(n,s),"end"),block:s})).map(s=>Gh(n,s));return js(i)}const Zh=M("editor-selection");class hD{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(sy(e,i)){Zh.debug("adjust selection because remote deleted current block");const s=ly(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=it(e);this.caret=new ES(t);const r=st(o,0,"normal");this._range=We(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=We(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),Et(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!RS(this.editor,r))&&rt(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(),xS(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(!Wr(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Mo(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){LS(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=ut(this.editor,e)||g(Zh,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||g(Zh,!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&&Et(e,"focused")&&(rt(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=Qh(this.editor);return t==="text"?Hs(this.editor,e):t==="markdown"?uy(this.editor,e):ay(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{rt(t,"focused"),rt(t,"child-focused")})}setBlockFocused(t){if(Et(t,"focused"))return!1;V(t,"focused");let e=ot(t);for(;Lo(e);){const o=nt(e);g(Zh,o,"parent block not found"),V(o,"child-focused"),e=ot(o)}return!0}}function fD(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 mD(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!et(n,e))return;let o=p1(n,"select"),r=C1(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 gD{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=u3(this.editor,t.x,t.y);if(o){if(o instanceof sr)return;if(!this.autoScroll&&e.autoScroll){const s=o.getSelectedBlocks(),l=lo(s[0].block);this.autoScroll=new fh({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=wh(this.editor,t.x,t.y);if(!e)return;const o=qh(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){mD(this.editor)}handleTripleClick(t){fD(this.editor)}}function pD(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function CD(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const Ck=M("delete-text");function bk(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof Ve||g(Ck,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);g(Ck,et(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!ln(s,l-e)){const a=_i(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 Ak(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const bD=M("handle-backspace");function x1(n,t){if(!ue(n,t))return;const e=ot(t);To(e)!==1&&n.deleteBlock(t)}function AD(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(et(n,o))if(e.offset===0){if(Ak(n,o))return;const r=ae(o);if(r){if(!n.isBlockWritable(r))return;if(et(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Lt(n,r)){x1(n,o);const i=Kl(n,r);i?n.selection.selectBlock(i,ut(n,i)):n.selection.selectBlock(r,0,ut(n,r))}else x1(n,o),g(bD,Se(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=ot(o);if(Lo(i)){const s=r3(n,i);if(s){if(!n.isBlockWritable(s))return;x1(n,o),n.selection.selectBlock(s,ut(n,s))}}}}else bk(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=vt(o),i=ot(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function vD(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(et(n,o))if(e.offset===ut(n,o)){const r=qt(o);if(r){if(!n.isBlockWritable(r))return;et(n,r)?n.mergeTextBlock(o,r,{focus:!0}):ue(n,o)?n.deleteBlock(o,be(n,r,0)):n.deleteBlock(r)}}else bk(n,"forward",1,null);else{const r=vt(o),i=ot(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function yD(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(Wr(e))return!0;const s=Jl(n,r,e,o),l=pn(n,r);return s.length===l.length}function kD(n,t){if(yD(n)){const s=n.getFocusedBlock(),l=vt(s),a=at(ot(s));n.insertTextBlock("",a,l+1);return}const e=n.getFocusedBlock(),{start:o,end:r}=n.selection.range,i=o.blockId===r.blockId&&Se(e);if(!n.selection.range.isCollapsed()&&!i&&n.clearSelectedContents(),et(n,e)){if(ue(n,e)&&Ak(n,e))return;const s=n.selection.range.start,l=n.breakTextBlock(e,s.offset,{copyBlockAttributes:!0});s.offset!==0?n.selection.selectBlock(l,0):n.selection.scrollIntoView()}else{const s=n.insertTextBlock();n.selection.selectBlock(s,0)}}function wD(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!et(n,o))return!1;const r=e.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:tt(),box:!0,created:Date.now()}),!0}const BD=M("input-handler-actions");function ED(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(kD(n),!0))}function xD(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(vD(n),!0))}function ID(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(AD(n),!0))}function TD(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(wD(n),!0))}function SD(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t,{toPlainText:!0})}).catch(t=>{BD.error(t)}),!0)}const Yh={ArrowDown:$y,ArrowUp:Ny,ArrowLeft:Fy,ArrowRight:Py,"Shift+ArrowDown":Hy,"Shift+ArrowUp":zy,"Shift+ArrowLeft":jy,"Shift+ArrowRight":Uy,"CtrlOrCmd+ArrowLeft":Wy,"CtrlOrCmd+ArrowRight":qy,"CtrlOrCmd+Shift+ArrowLeft":Gy,"CtrlOrCmd+Shift+ArrowRight":Qy,"CtrlOrCmd+ArrowUp":Zy,"CtrlOrCmd+ArrowDown":v1,"CtrlOrCmd+Shift+ArrowUp":Yy,"CtrlOrCmd+Shift+ArrowDown":y1,"CtrlOrCmd+A":mk,Home:nk,End:ok,"Shift+Home":tk,"Shift+End":ek,PageUp:ck,PageDown:ak,"Shift+PageUp":uk,"Shift+PageDown":dk,"CtrlOrCmd+Z":pD,"CtrlOrCmd+Shift+Z":CD,Enter:ED,Delete:xD,Backspace:ID,"Shift+Enter":TD,"CtrlOrCmd+Shift+V":SD};function vk(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function yk(n,t,e){if(t.type==="embed"){const i=t.embedData,s=i.src;if(s&&typeof s=="string"){const l=e.get(s);if(l)i.src=l;else{let a="";s.split("|").forEach(h=>{const p=e.get(h);p&&(a+=a?`|${p}`:`${p}`)}),a&&(i.src=a)}}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=>{yk(n,l,e)})})}function kk(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):yk(t,r,e)})}async function DD(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 MD(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 LD(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(MD(n,t)){const s=Array.from(Object.keys(o));r=await DD(n,s),kk(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&&kk(n,t,i)}async function RD(n,t,e){await LD(n,t),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&Se(i)){const s=ot(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}=ec(n);n.insertDoc(s,l,t,e)}})}const OD=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function _D(n){let t;for(const e of OD)if(t=n[e],t)break;return t||null}function wk(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=>{wk(n,l,e)})})}function FD(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)}):wk(t,r,e)}),Array.from(e)}function Jh(n,t){return ge.isFirefox?`<!doctype html><html><head><meta charset="utf8" /></head><body><canvas data-editor-doc="${Li(JSON.stringify(t))}" id="ones-editor-doc">${n}</body></html>`:`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Li(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Kh(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=FD(n,t),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),t.meta={...e,resources:r}}function PD(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let o=Qh(n);const r=e==null?void 0:e(n,t,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Kh(n,o);const i=$h(n,o),s=Hs(n,o),l=Jh(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 Xh(n,t){const e=E1(n,t);Kh(n,e);const o=$h(n,e),r=Hs(n,e),i=Jh(o,e);return lp([{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);if(r){const i=[];this.pasteDocs(r,null,i)}});this.editor=t}onInsertText(t,e){if(!et(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=ec(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){if(!et(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:o,offset:r}=ec(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){if(!et(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText(e,o),this.editor.selection.caret.update();const{containerId:r,blockIndex:i,offset:s}=ec(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){PD(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;Se(o)&&this.editor.deleteBlock(o)}else a1(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;const e=this.editor.dataConverter.fromData(this.editor,t.clipboardData),o=Array.from(t.clipboardData.files);e.then(async r=>{r&&this.pasteDocs(r,t,o)})}onFocus(){V(this.editor.rootElement,"active")}onBlur(){rt(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t),this.handlers=this.handlers.sort((e,o)=>{var s,l;const r=(s=e.order)!=null?s:1;return((l=o.order)!=null?l:1)-r})}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){r1(this.editor,i)}defaultHandleKeydown(t,e){return vk(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 RD(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,o){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforePaste&&await s.handleBeforePaste(this.editor,e,t,o))return}const r=_D(t);if(!!r){await this.pasteDoc(r);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterPaste&&await s.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function $D(n,t,e){const o=Hr(t,e);return o.remove(),o}M("copy-dom-attributes");const Bk=["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 HD(n,t){for(let l=0;l<Bk.length;l++){const a=Bk[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 Ek(n){const t=Array.from(n.childNodes).filter(e=>!v5(e));return t.forEach(e=>{e.remove()}),t}function xk(n,t,e){var d;const o=n.getContainerById(t),r=Hr(o,e),i=Ri(r),s=n.doc.getBlockData(t,e),l=Yt(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=Ek(h);Ek(r),p.forEach(v=>{r.appendChild(v)});const C=ph(h);if(C){const v=ph(r);v&&v.remove(),r.appendChild(C)}HD(h,r)}N5(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 jD=M("transform-selection");function Ik(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;g(jD,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const d=cn.transformCursor(i.offset,e,o);l=st(t,d,"normal")}let a=s;if(s.blockId===t){const d=cn.transformCursor(s.offset,e,o);a=st(t,d,"normal")}return We(n,{anchor:l,focus:a})}const UD=M("handle-block-text-changed");function zD(n,t,e,o,r){const i=n.getContainerById(t),s=Hr(i,e),l=n.doc.getBlockData(t,e);if(g(UD,l.text,"no block text"),L5(n,s).setBlockText(n,s,l.text),!r){const a=Ik(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function VD(n,t){const e=mt.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function Tk(n,t,e,o){const r=Yt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function WD(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{Tk(n,i,o,{child:!0})}),Tk(n,r,o,{child:!1})}const _o=M("editor-doc");class qD extends Ba{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)}findContainerBlocks(e){return this.externalDoc.findContainerBlocks(e)}getBlockData(e,o){return this.externalDoc.getBlockData(e,o)}verifyBlockWritable(e,o){const r=this.editor.getBlockByIndex(e,o);g(_o,this.editor.isBlockWritable(r),`block is not writable, ${e}, ${o}`)}localUpdateBlockText(e,o,r,i){g(_o,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const s=this.getBlockData(e,o),l=s.text;g(_o,l,`no text, ${e}, ${o}`);const a=Ik(this.editor,s.id,r,!0),d=cn.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(_o,!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(C=>C!=="comments"),p=Object.keys(r.insert).filter(C=>C!=="comments");(h.length>0||p.length>0)&&g(_o,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=mt.default(this.getBlockData(e,o)),a=mt.default(VD(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(Oi(this.editor,i)),d}localInsertBlock(e,o,r,i,s){g(_o,!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 s!=null&&s.noFocus||this.editor.selection.setRange(Oi(this.editor,i),s),l}localDeleteBlock(e,o,r){g(_o,!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(Oi(this.editor,r)),s}localDeleteChildContainers(e){return g(_o,!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)}localInsertChildContainers(e){g(_o,!this.editor.readonly,"editor is readonly");const o=mt.default(e);o.forEach(r=>{this.localEvents.forEach(i=>i.onBeforeInsertChildContainer(r.containerId,r.blocks))}),this.externalDoc.localInsertChildContainers(o)}onRequestReload(e){_o.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)}),zD(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)}),xk(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);L8(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){WD(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);$D(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){_o.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function Sk(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 tf=M("undo-action");class sc{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(tf,t,"no other action"),!1}combine(t){g(tf,!1,"no other")}setAfterRange(t){this.afterRange&&tf.warn("after range has already set"),this.afterRange=t}findContainerById(t,e){return!!t.doc.findContainerBlocks(e)}findBlockById(t,e){const o=t.doc.findContainerBlocks(this.containerId);return o?o.some(r=>r.id===e):!1}checkBlockData(t,e){if(Array.isArray(e.children)){const o=t.doc.toJSON();for(let r=0;r<e.children.length;r++){const i=e.children[r];if(!o.blocks[i])return tf.warn(`container (${i}) not found, deleted by others?`),!1}}return!0}}const lc=M("block-action");class Dk extends sc{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(!this.findContainerById(e,this.containerId))return lc.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockData.id))return lc.warn(`block (${this.blockData.id}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockData.id);if(!i)return!1;try{g(lc,this.blockIndex===vt(i),"invalid block index"),Uh(e,i,Oi(e,o))}catch(s){lc.warn(s.message),e.selection.selectBlock(i,0)}return!0}insertBlock(e,o){if(!this.findContainerById(e,this.containerId))return lc.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.checkBlockData(e,this.blockData))return!1;try{oc(e,this.containerId,this.blockIndex,mt.default(this.blockData),o)}catch(r){lc.warn(r.message);const i=e.doc.getContainerBlocks(this.containerId),s=Math.min(i.length-1,this.blockIndex),l=e.getBlockByIndex(this.containerId,s);e.selection.selectBlock(l,0)}return!0}}M("insert-block-action");class GD extends Dk{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class QD extends Dk{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class ZD extends sc{constructor(e){super(e,at(e.rootContainer),e.selection.range.toDocRange());m(this,"actions",[])}addAction(e){Sk(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 sc&&(o.afterRange||o.setAfterRange(e))}}const $i=M("update-block-data-action");class ef extends sc{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeBlockData");m(this,"afterBlockData");m(this,"blockId");this.blockId=r,g($i,this.blockId===i.id,"invalid block id"),g($i,this.blockId===s.id,"invalid block id"),this.beforeBlockData=mt.default(i),this.afterBlockData=mt.default(s),g($i,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){if(!e.findBlockById(this.blockId))return $i.warn(`block (${this.blockId}) not found, deleted by others?`),!1;const o=e.getBlockById(this.blockId);if(!o||!this.checkBlockData(e,this.beforeBlockData))return!1;const r=e.getContainerById(this.containerId);return g($i,r,"no container"),Wh(e,o,ef.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){if(!e.findBlockById(this.blockId))return $i.warn(`block (${this.blockId}) not found, deleted by others?`),!1;g($i,e,"no editor");const o=e.getBlockById(this.blockId);if(!o||!this.checkBlockData(e,this.beforeBlockData))return!1;const r=e.getContainerById(this.containerId);return g($i,r,"no container"),Wh(e,o,ef.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=mt.default(e);return delete o.id,delete o.type,o}}const Us=M("update-block-text-action");class Ka extends sc{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=Ka.calType(i,s)}static calType(e,o){g(Us,e,"no old data"),g(Us,o,"no new data");const i=cn.diff(e,o),s=new Set;let l=!1;const a=h=>Yv(h)?`cjk_${h}`:Qv(h)?"number":ch(h)?"space":Zv(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(!this.findContainerById(e,this.containerId))return Us.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return Us.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Vh(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!this.findContainerById(e,this.containerId))return Us.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return Us.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Vh(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof Ka)||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(Us,e instanceof Ka,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}const Mk=M("child-container-action");class Lk extends sc{constructor(t,e,o){super(t,e,t.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(t){return this.findContainerById(t,this.containerId)?(t.doc.localDeleteChildContainers([this.containerId]),!0):(Mk.warn(`container (${this.containerId}) not found, deleted by others?`),!1)}insertChildContainer(t){return this.findContainerById(t,this.containerId)?(Mk.warn(`container (${this.containerId}) already exists`),!1):(t.doc.localInsertChildContainers([{containerId:this.containerId,blocks:mt.default(this.blocks)}]),!0)}}class YD extends Lk{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class JD extends Lk{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Fo=M("undo");class KD{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):(Sk(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(g(Fo,!this.currentGroup,"current group already exists"),this.currentGroup=new ZD(this.editor),this.groupCounter=1):(g(Fo,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){g(Fo,this.currentGroup,"current group not exists"),g(Fo,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Fo.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 Fo.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(Oi(this.editor,t.beforeRange))}catch(e){Fo.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(Oi(this.editor,e)):Fo.warn("no after range")}catch(e){Fo.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(),cn.diff(o,r).length!==0&&this.addAction(new Ka(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new ef(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),g(Fo,e>=0,"invalid block index"),g(Fo,o,"no block data"),this.addAction(new GD(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new QD(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new YD(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new JD(this.editor,t,e)))}}class XD{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 tM{constructor(){m(this,"converters",[]);m(this,"converterTypes",["text/plain","text/markdown","text/html","text/x-ones-editor-doc"]);this.addConverter(new XD)}prepareData(t){const e=new DataTransfer;for(let o=0;o<this.converterTypes.length;o++)e.setData(this.converterTypes[o],t.getData(this.converterTypes[o]));return e}async fromData(t,e,o){let r={};const i=this.prepareData(e);for(const s of this.converters){const l=await s.fromData(t,i,o);l&&(r={...r,...l})}return r}addConverter(t){this.converters.push(t)}}class eM{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 Ae extends ke.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=nt(o);if((!r||!Xt(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&&Xt(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&rt(s,"hover"),e&&V(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 Ae(e))}getParentTextContentChild(e,o){if(!et(this.editor,e))return null;const r=Mt(e);return o.parentElement===r?o:mp(o)}}const Rk="style-color-",Ok="style-bg-color-";class nM{renderText(t,e,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(Rk)?i["data-style-color"]=l.substring(Rk.length):l.startsWith(Ok)?i["data-style-bg-color"]=l.substring(Ok.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"),Ae.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&&V(o,"focused"),Ae.get(t).hoveringBlockId()===r.id&&V(o,"hover")}}function oM(n){n.editorBlocks.registerBlockClass(Sn),n.editorBlocks.registerBlockClass(o3),n.editorBoxes.registerBoxClass(q3),n.editorBoxes.registerBoxClass(G3),n.editorBoxes.registerBoxClass(Y3),n.editorBoxes.registerBoxClass(J3),n.editorInsertions.registerInsertionClass(K3),n.editorBlockRenders.registerRender(new nM)}function rM(n,t){oM(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 nf=M("range-commands");function _k(n,t){n.forEach(e=>{e.source=t,e.children&&_k(e.children,t)})}function Fk(n,t,e){const o=it(t);g(nf,o===e.start.blockId,"invalid start range"),g(nf,o===e.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];if(r.forEach(s=>{const l=s.getAvailableCommands(n,t,e);_k(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)){if(!Yl(e.start))return i;g(nf,!e.start.isSimple(),"invalid start pos"),g(nf,!e.end.isSimple(),"invalid end pos");const s=e.start.childContainerId,l=ir(n,s),d=fe(l)[0];if(d){const h=ut(n,d),p=We(n,{anchor:st(d,0,"home"),focus:st(d,h,"end")}),C=Fk(n,d,p);i.push(...C)}}return i}function Pk(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[],r=n.isReverse()?e[0]:e[e.length-1],i=We(t,{anchor:r.start,focus:r.end});return Fk(t,r.block,i).forEach(l=>{o.push(l)}),o}function Nk(n,t,e,o,r,i){var h;const s=n.editorCommandProviders.getCommandProviders();for(let p=0;p<s.length;p++){const C=s[p];if(C.beforeExecuteCommand&&C.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)&&Jl(n,t,e.start,e.end).forEach(C=>{fe(C).forEach(B=>{const x=ut(n,B),I=We(n,{anchor:st(B,0,"home"),focus:st(B,x,"end")});Nk(n,B,I,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,t,e,o,r,i)}),d}function $k(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=We(o,{anchor:l.start,focus:l.end});Nk(o,l.block,a,t,e,r)}),o.focus()),r}const iM=M("command-providers");class Hk{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(iM,e,`no command provider, id=${t}`),e}getCommands(t){return Pk(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>$k(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 sM(n,t){const e=ot(t),o=at(e),r=vt(t);xk(n,o,r)}const lM=M("table-scroll");class jk{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 cM{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)){lM.warn(`event has already registered: ${e}`);return}i.push(new jk(this.editor,t,e,o,r))}else{const s=new jk(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 Uk=M("update-block-text");function aM(n,t){const e=n.getBoxById(t.id),o=nt(e);g(Uk,o,"no parent block"),g(Uk,et(n,o),"not a text block");const r=n.getBlockText(o),i=P3(r,"id",t.id,t);yy(n,o,i)}function uM(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 dM(n){if(n.readonly)return!1;const t=lr(n);return!!n.isBlockWritable(t.map(e=>e.block))}class hM{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 fM{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(or(e,s)){const a=l(t,e);if(a!==void 0)return a}}}}const Yr=M("editor");class mM extends ke.TypedEmitter{constructor(e,o,r){var i,s,l,a,d,h,p,C;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 fM);m(this,"dataConverter",new tM);m(this,"editorBlocks",new X5(this));m(this,"editorBoxes",new Z3(this));m(this,"editorInsertions",new ty(this));m(this,"editorEmbeds",new e3(this));m(this,"editorDecorators",new ey(this));m(this,"editorCommandProviders",new Hk(this));m(this,"editorBlockRenders",new eM(this));m(this,"blockHooks",[]);m(this,"domEvents",new cM(this));m(this,"customs",new Map);m(this,"options");m(this,"inputHandlers",new ND(this));m(this,"settingsProvider");m(this,"_readonly",!1);m(this,"getColor",e=>{const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]});Yr.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,enableComments:(a=r==null?void 0:r.enableComments)!=null?a:!0},this.settingsProvider=(d=r==null?void 0:r.settingsProvider)!=null?d:new hM(this),rM(this,r==null?void 0:r.components),this.blockHooks.push(...(p=(h=r==null?void 0:r.components)==null?void 0:h.blockHooks)!=null?p:[]),this.id=(C=r==null?void 0:r.id)!=null?C:tt(),this.clientId=tt(),this.undoManager=new KD(this),this.doc=new qD(this,o,this.undoManager),this.parent=e,this.rootElement=k("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=k("div",["editor-content"],this.rootElement),this.rootContainerObject=Y5(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new BS(this,this.inputHandlers),this.selection=new hD(this),this.selectionHandler=new gD(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),ge.isMobile&&V(this.rootElement,"mobile"),ge.isSafari&&V(this.rootElement,"safari"),this._readonly&&V(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?V(this.rootElement,"readonly"):rt(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:lo(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(Yr,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(){Yr.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){u1(this,e,o)}isWritable(){return dM(this)}isBlockWritable(e){return uM(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return(!o||!Array.isArray(o))&&(g(Yr,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),g(Yr,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`)),o}createChildContainer(e,o,r){return J5(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(Yr,Es(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(Yr,fp(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return g(Yr,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return g(Yr,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return Hr(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return vt(o)}return vt(e)}getContainerById(e){return ir(this,e)}getParentContainer(e){return ot(e)}reloadBlock(e){sM(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 oc(this,e,o,r,i!=null?i:a,s)}insertEmbed(e,o,r,i,s){const l={id:tt(),type:"embed",embedType:r,embedData:i};return this.insertBlock(e,o,l,s)}deleteBlock(e,o){l1(this,e,o)}mergeTextBlock(e,o){return by(this,e,o)}breakTextBlock(e,o,r){return rc(this,e,o,r).newBlock}getTextPosition(){return ec(this)}getBlockString(e,o){const r=this.getBlockText(e);return se(r,o)}getBlockData(e){return Fi(this,e)}getBoxData(e){return V3(this,e)}getBlockText(e){return Cn(this,e)}setBlockText(e,o){yy(this,e,o)}deleteTextFromBlock(e,o,r,i){return i1(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return dy(this,e,o,r,i)}insertBoxToBlock(e,o,r){return hy(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){By(this,e,o,r,i)}insertDocAt(e,o,r,i){return f1(this,e,o,r,i)}deleteChildContainers(e){Cy(this,e)}replaceBlockText(e,o){return Vh(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...a}=i;return Wh(this,e,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return ky(this,e,o,r)}updateBoxData(e){aM(this,e)}getSelectedText(){const e=Qh(this);return Hs(this,e)}clearSelectedContents(){a1(this)}insertTextBlock(e,o,r,i){const s=ur(e!=null?e:"");return py(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){my(this);return}o?(this.compositingText="",Ta()||r1(this,e)):(this.compositingText=e,fy(this))}}function Xa(n,t,e){return new mM(n,t,e)}function gM(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=Vg.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const pM=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class of extends ke.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:pM}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&ka.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.emit("change",Array.from(this.users.values()));const o=this.cursors.get(e);if(o){const r=new Set(new Set([o==null?void 0:o.range.anchor.blockId,o==null?void 0:o.range.focus.blockId]));this.cursors.delete(e),this.emit("remote-carets-change",[...r])}}updateUsers(e){this.users.forEach(o=>{e.find(r=>r.userId===o.userId)||this.removeUser(o.userId)}),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&&Rh(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(Rh(l.range)){const{anchor:a,focus:d}=l.range;a.blockId===e.id&&(a.offset=cn.transformCursor(a.offset,o,r)),d.blockId===e.id&&(d.offset=cn.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=M("local-doc");class I1 extends Ba{constructor(e,o){super();m(this,"doc");m(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[ur("")]}},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]}findContainerBlocks(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=cn.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}localInsertChildContainers(e){e.forEach(({containerId:o,blocks:r})=>{this.doc.blocks[o]=r,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,o,r,!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 of}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 CM{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function T1(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new CM(o)})}const zk=M("find-block");function Vk(n,t){const e=Ts(t);if(!e){if(co(t))return null;const o=xs(t);return g(zk,o,"no parent block"),Vk(n,o)}return Lt(n,e)?Kl(n,e,{visibleOnly:!0}):e}function Wk(n,t){const e=Ss(t);if(!e){if(co(t))return null;const o=xs(t);return g(zk,o,"no parent block"),Wk(n,o)}return Lt(n,e)?Tp(n,e,{visibleOnly:!0}):e}const bM=M("remote-cursor");class AM{constructor(){m(this,"remoteUsers",new of)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):bM.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 vM(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function yM(n){const{blocks:t,meta:e,comments:o}=n,{root:r,...i}=t;return{blocks:r,meta:e,comments:o,...i}}function tu(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=vM(mt.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function Jr(n){return n==="root"?"blocks":n}function cc(n){return n==="blocks"?"root":n}const kM={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new rn.default(n)},apply(n,t){const e=new rn.default(n),o=new rn.default(t);return e.compose(o).ops},compose(n,t){const e=new rn.default(n),o=new rn.default(t);return e.compose(o).ops},diff(n,t){const e=new rn.default(n),o=new rn.default(t);return e.diff(o).ops},transform(n,t,e){const o=new rn.default(n);return new rn.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 rn.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 hr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Hi={},S1=yv.default.EventEmitter;Hi.EventEmitter=S1,Hi.mixin=wM;function wM(n){for(var t in S1.prototype)n.prototype[t]=S1.prototype[t]}var qk=["info","warn","error"];function Gk(){var n={};qk.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var BM=Gk;Gk.prototype.setMethods=function(n){n=n||{};var t=this;qk.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var EM=BM,xM=new EM,Qk=xM;function zs(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,zs):this.stack=new Error().stack}zs.prototype=Object.create(Error.prototype),zs.prototype.constructor=zs,zs.prototype.name="ShareDBError",zs.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 rf=zs,eu={},Zk=IM;function IM(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=[],C=0;C<s.length;){var v=[];if(r(s[C],h,p,v),C++,v.length===1)h=v[0];else if(v.length===0){for(var B=C;B<s.length;B++)o(p,s[B]);h=null;break}else{for(var x=i(s.slice(C),v),I=0;I<x[0].length;I++)o(p,x[0][I]);for(var _=0;_<x[1].length;_++)o(a,x[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 Yk={exports:{}},ji=Yk.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||""}},D1=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},M1=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")},sf=function(n){for(var t=0;t<n.length;t++)M1(n[t])};ji.apply=function(n,t){var e;sf(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=D1(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 Kr=ji._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:D1(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:D1(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};ji.compose=function(n,t){sf(n),sf(t);for(var e=n.slice(),o=0;o<t.length;o++)Kr(e,t[o]);return e},ji.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),Kr(t,o)}return t};var L1=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};ji.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=L1(n,t[r],o);return n};var TM=ji._tc=function(n,t,e,o){if(M1(t),M1(e),t.i!=null)Kr(n,{i:t.i,p:L1(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(Kr(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&Kr(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)Kr(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)Kr(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=L1(i.p,e),Kr(n,i))}return n},SM=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};ji.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=SM(n[t]);return n},Zk(ji,TM,sf,Kr);var lf=function(n){return Object.prototype.toString.call(n)=="[object Array]"},DM=function(n){return!!n&&n.constructor===Object},Po=function(n){return JSON.parse(JSON.stringify(n))},It={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Xr={};It.registerSubtype=function(n){Xr[n.name]=n},It.create=function(n){return n===void 0?null:Po(n)},It.invertComponent=function(n){var t={p:n.p};return n.t&&Xr[n.t]&&(t.t=n.t,t.o=Xr[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(!lf(n[t].p))throw new Error("Missing path")},It.checkList=function(n){if(!lf(n))throw new Error("Referenced element not a list")},It.checkObj=function(n){if(!DM(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function nu(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 ou(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=Po(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&nu(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&&Xr[r.t])s[l]=Xr[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 MM=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=Po(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)&&(nu(t),nu(e)),MM(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Xr[t.t]){if(e.o=Xr[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(),ou(t),n.push(t);ou(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)&&(ou(t),ou(e)),n.push(t)},It.compose=function(n,t){It.checkValidOp(n),It.checkValidOp(t);for(var e=Po(n),o=0;o<t.length;o++)It.append(e,t[o]);return e},It.normalize=function(n){var t=[];n=lf(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=Po(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=Po(e);a.p=a.p.slice(s),t.ld=It.apply(Po(t.ld),[a])}else if(t.od!==void 0){var a=Po(e);a.p=a.p.slice(s),t.od=It.apply(Po(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)&&(nu(t),a=Po(e),nu(a)),a.t&&Xr[a.t]){if(t.t&&t.t===a.t){var h=Xr[t.t].transform(t.o,a.o,o);if(t.si!=null||t.sd!=null)for(var p=t.p,C=0;C<h.length;C++)t.o=[h[C]],t.p=p.slice(),ou(t),It.append(n,t);else(!lf(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=Po(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,x=e.p[r],I=e.lm;if(x!==I)if(v===x)if(o==="left")t.p[r]=I,v===B&&(t.lm=I);else return n;else v>x&&t.p[r]--,v>I?t.p[r]++:v===I&&x>I&&(t.p[r]++,v===B&&t.lm++),(B>x||B===x&&B>v)&&t.lm--,B>I?t.lm++:B===I&&(I>x&&B>v||I<x&&B<v?o==="right"&&t.lm++:B>v?t.lm++:B===x&&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},Zk(It,It.transformComponent,It.checkValidOp,It.append);var LM=Yk.exports;It.registerSubtype(LM);var RM=It,OM={type:RM};(function(n){n.defaultType=OM.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)})(eu);var No={};(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))}})(No);var Jk=Array.isArray,Kk=Object.keys,_M=Object.prototype.hasOwnProperty,FM=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=Jk(t),r=Jk(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 C=Kk(t);if(s=C.length,s!==Kk(e).length)return!1;for(i=s;i--!==0;)if(!_M.call(e,C[i]))return!1;for(i=s;i--!==0;)if(l=C[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},Xk=Hi,PM=Qk,qn=rf,cf=eu,$o=No,NM=$o.clone,$M=FM,Dn=qn.CODES,HM=Pt;function Pt(n,t,e){Xk.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}Xk.mixin(Pt),Pt.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())})},Pt.prototype._setType=function(n){if(typeof n=="string"&&(n=cf.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new qn(Dn.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},Pt.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Pt.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new qn(Dn.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 qn(Dn.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?cf.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()},Pt.prototype.whenNothingPending=function(n){var t=this;$o.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},Pt.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Pt.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Pt.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Pt.prototype._emitResponseError=function(n,t){if(n&&n.code===Dn.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)},Pt.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){$o.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},Pt.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){$o.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()},Pt.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===Dn.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=af(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=af(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},Pt.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))},Pt.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()},Pt.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);jM(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},Pt.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},Pt.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},Pt.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=e&&e.wantSubscribe===n;if(o){e.callback=UM([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},Pt.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;$o.nextTick(function(){n._handleSubscribe()})}}};function jM(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function UM(n){return n=n.filter($o.truthy),n.length?function(t){$o.callEach(n,t)}:null}Pt.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function zM(n){delete n.op,delete n.create,delete n.del}function af(n,t){if(n.del)return zM(t);if(t.del)return new qn(Dn.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new qn(Dn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new qn(Dn.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}}}Pt.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new qn(Dn.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===cf.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=af(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}},Pt.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 qn(Dn.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>=$o.MAX_SAFE_INTEGER)return this.emit("error",new qn(Dn.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)}},Pt.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var o=new qn(Dn.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;$o.nextTick(function(){r.flush()})},Pt.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)},Pt.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)}}},Pt.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!$M(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}}},Pt.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)},Pt.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=cf.defaultType.uri),this.type){var r=new qn(Dn.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)},Pt.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new qn(Dn.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)},Pt.prototype.pause=function(){this.paused=!0},Pt.prototype.resume=function(){this.paused=!1,this.flush()},Pt.prototype.toSnapshot=function(){return{v:this.version,data:NM(this.data),type:this.type.uri}},Pt.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return PM.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},Pt.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=af(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)},Pt.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=$o.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},Pt.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=$o.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var Vs={};Vs.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 t2=Hi,e2=Vs.ACTIONS,VM=No,WM=Mn;function Mn(n,t,e,o,r,i,s){t2.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}t2.mixin(Mn),Mn.prototype.hasPending=function(){return!this.ready},Mn.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}},Mn.prototype.destroy=function(n){this.connection.canSend&&this.action===e2.querySubscribe&&this.connection.send({a:e2.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&VM.nextTick(n)},Mn.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Mn.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Mn.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Mn.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()},Mn.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},Mn.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)},Mn.prototype._handleError=function(n){this.emit("error",n)},Mn.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)},Mn.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var n2=Hi,qM=Vs.ACTIONS,GM=No,o2=fr;function fr(n,t){if(n2.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={}}n2.mixin(fr),fr.prototype.submit=function(n,t){this.value=n,this.send(t)},fr.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},fr.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()})},fr.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},fr.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},fr.prototype._message=function(){return{a:qM.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},fr.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},fr.prototype._callbackOrEmit=function(n,t){if(t)return GM.nextTick(t,n);n&&this.emit("error",n)};var QM=No,r2=R1;function R1(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}R1.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},R1.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&QM.nextTick(n)};var O1={exports:{}};(function(n,t){(function(e,o){o(t)})(hr,function(e){function o(w,S){S=S|0;for(var R=Math.max(w.length-S,0),F=Array(R),U=0;U<R;U++)F[U]=w[S+U];return F}var r=function(w){var S=o(arguments,1);return function(){var R=o(arguments);return w.apply(null,S.concat(R))}},i=function(w){return function(){var S=o(arguments),R=S.pop();w.call(this,S,R)}};function s(w){var S=typeof w;return w!=null&&(S=="object"||S=="function")}var l=typeof setImmediate=="function"&&setImmediate,a=typeof process=="object"&&typeof process.nextTick=="function";function d(w){setTimeout(w,0)}function h(w){return function(S){var R=o(arguments,1);w(function(){S.apply(null,R)})}}var p;l?p=setImmediate:a?p=process.nextTick:p=d;var C=h(p);function v(w){return i(function(S,R){var F;try{F=w.apply(this,S)}catch(U){return R(U)}s(F)&&typeof F.then=="function"?F.then(function(U){B(R,null,U)},function(U){B(R,U.message?U:new Error(U))}):R(null,F)})}function B(w,S,R){try{w(S,R)}catch(F){C(x,F)}}function x(w){throw w}var I=typeof Symbol=="function";function _(w){return I&&w[Symbol.toStringTag]==="AsyncFunction"}function D(w){return _(w)?v(w):w}function H(w){return function(S){var R=o(arguments,1),F=i(function(U,j){var Q=this;return w(S,function(J,lt){D(J).apply(Q,U.concat(lt))},j)});return R.length?F.apply(this,R):F}}var W=typeof hr=="object"&&hr&&hr.Object===Object&&hr,G=typeof self=="object"&&self&&self.Object===Object&&self,K=W||G||Function("return this")(),ht=K.Symbol,bt=Object.prototype,_t=bt.hasOwnProperty,Ht=bt.toString,oe=ht?ht.toStringTag:void 0;function Le(w){var S=_t.call(w,oe),R=w[oe];try{w[oe]=void 0;var F=!0}catch{}var U=Ht.call(w);return F&&(S?w[oe]=R:delete w[oe]),U}var Jn=Object.prototype,Ee=Jn.toString;function Rn(w){return Ee.call(w)}var Ir="[object Null]",kn="[object Undefined]",un=ht?ht.toStringTag:void 0;function Tr(w){return w==null?w===void 0?kn:Ir:un&&un in Object(w)?Le(w):Rn(w)}var ii="[object AsyncFunction]",bo="[object Function]",Ib="[object GeneratorFunction]",Tb="[object Proxy]";function Sb(w){if(!s(w))return!1;var S=Tr(w);return S==bo||S==Ib||S==ii||S==Tb}var ns=9007199254740991;function sl(w){return typeof w=="number"&&w>-1&&w%1==0&&w<=ns}function ll(w){return w!=null&&sl(w.length)&&!Sb(w)}var si={};function jt(){}function Sr(w){return function(){if(w!==null){var S=w;w=null,S.apply(this,arguments)}}}var os=typeof Symbol=="function"&&Symbol.iterator,Zc=function(w){return os&&w[os]&&w[os]()};function Pm(w,S){for(var R=-1,F=Array(w);++R<w;)F[R]=S(R);return F}function dn(w){return w!=null&&typeof w=="object"}var cl="[object Arguments]";function Nm(w){return dn(w)&&Tr(w)==cl}var Ao=Object.prototype,$m=Ao.hasOwnProperty,Db=Ao.propertyIsEnumerable,al=Nm(function(){return arguments}())?Nm:function(w){return dn(w)&&$m.call(w,"callee")&&!Db.call(w,"callee")},ve=Array.isArray;function ul(){return!1}var dl=typeof e=="object"&&e&&!e.nodeType&&e,Hm=dl&&!0&&n&&!n.nodeType&&n,hl=Hm&&Hm.exports===dl,jm=hl?K.Buffer:void 0,fl=jm?jm.isBuffer:void 0,rs=fl||ul,nd=9007199254740991,od=/^(?:0|[1-9]\d*)$/;function rd(w,S){var R=typeof w;return S=S==null?nd:S,!!S&&(R=="number"||R!="symbol"&&od.test(w))&&w>-1&&w%1==0&&w<S}var id="[object Arguments]",sd="[object Array]",ld="[object Boolean]",cd="[object Date]",ad="[object Error]",ud="[object Function]",Mb="[object Map]",Lb="[object Number]",Rb="[object Object]",Um="[object RegExp]",zm="[object Set]",Ob="[object String]",_b="[object WeakMap]",Fb="[object ArrayBuffer]",Pb="[object DataView]",Vm="[object Float32Array]",Nb="[object Float64Array]",$b="[object Int8Array]",Hb="[object Int16Array]",dd="[object Int32Array]",jb="[object Uint8Array]",hd="[object Uint8ClampedArray]",Ub="[object Uint16Array]",zb="[object Uint32Array]",le={};le[Vm]=le[Nb]=le[$b]=le[Hb]=le[dd]=le[jb]=le[hd]=le[Ub]=le[zb]=!0,le[id]=le[sd]=le[Fb]=le[ld]=le[Pb]=le[cd]=le[ad]=le[ud]=le[Mb]=le[Lb]=le[Rb]=le[Um]=le[zm]=le[Ob]=le[_b]=!1;function Vb(w){return dn(w)&&sl(w.length)&&!!le[Tr(w)]}function Wb(w){return function(S){return w(S)}}var Wm=typeof e=="object"&&e&&!e.nodeType&&e,ml=Wm&&!0&&n&&!n.nodeType&&n,qb=ml&&ml.exports===Wm,Yc=qb&&W.process,qm=function(){try{var w=ml&&ml.require&&ml.require("util").types;return w||Yc&&Yc.binding&&Yc.binding("util")}catch{}}(),Gm=qm&&qm.isTypedArray,Gb=Gm?Wb(Gm):Vb,Qb=Object.prototype,Zb=Qb.hasOwnProperty;function Yb(w,S){var R=ve(w),F=!R&&al(w),U=!R&&!F&&rs(w),j=!R&&!F&&!U&&Gb(w),Q=R||F||U||j,J=Q?Pm(w.length,String):[],lt=J.length;for(var pt in w)(S||Zb.call(w,pt))&&!(Q&&(pt=="length"||U&&(pt=="offset"||pt=="parent")||j&&(pt=="buffer"||pt=="byteLength"||pt=="byteOffset")||rd(pt,lt)))&&J.push(pt);return J}var Jc=Object.prototype;function Jb(w){var S=w&&w.constructor,R=typeof S=="function"&&S.prototype||Jc;return w===R}function Kc(w,S){return function(R){return w(S(R))}}var Kb=Kc(Object.keys,Object),Xb=Object.prototype,tA=Xb.hasOwnProperty;function Qm(w){if(!Jb(w))return Kb(w);var S=[];for(var R in Object(w))tA.call(w,R)&&R!="constructor"&&S.push(R);return S}function Xc(w){return ll(w)?Yb(w):Qm(w)}function Zm(w){var S=-1,R=w.length;return function(){return++S<R?{value:w[S],key:S}:null}}function eA(w){var S=-1;return function(){var F=w.next();return F.done?null:(S++,{value:F.value,key:S})}}function nA(w){var S=Xc(w),R=-1,F=S.length;return function U(){var j=S[++R];return j==="__proto__"?U():R<F?{value:w[j],key:j}:null}}function oA(w){if(ll(w))return Zm(w);var S=Zc(w);return S?eA(S):nA(w)}function vo(w){return function(){if(w===null)throw new Error("Callback was already called.");var S=w;w=null,S.apply(this,arguments)}}function gl(w){return function(S,R,F){if(F=Sr(F||jt),w<=0||!S)return F(null);var U=oA(S),j=!1,Q=0,J=!1;function lt(ct,At){if(Q-=1,ct)j=!0,F(ct);else{if(At===si||j&&Q<=0)return j=!0,F(null);J||pt()}}function pt(){for(J=!0;Q<w&&!j;){var ct=U();if(ct===null){j=!0,Q<=0&&F(null);return}Q+=1,R(ct.value,ct.key,vo(lt))}J=!1}pt()}}function Dr(w,S,R,F){gl(S)(w,D(R),F)}function ze(w,S){return function(R,F,U){return w(R,S,F,U)}}function fd(w,S,R){R=Sr(R||jt);var F=0,U=0,j=w.length;j===0&&R(null);function Q(J,lt){J?R(J):(++U===j||lt===si)&&R(null)}for(;F<j;F++)S(w[F],F,vo(Q))}var rA=ze(Dr,1/0),Go=function(w,S,R){var F=ll(w)?fd:rA;F(w,D(S),R)};function Qo(w){return function(S,R,F){return w(Go,S,D(R),F)}}function md(w,S,R,F){F=F||jt,S=S||[];var U=[],j=0,Q=D(R);w(S,function(J,lt,pt){var ct=j++;Q(J,function(At,Zt){U[ct]=Zt,pt(At)})},function(J){F(J,U)})}var ta=Qo(md),gd=H(ta);function li(w){return function(S,R,F,U){return w(gl(R),S,D(F),U)}}var Mr=li(md),pd=ze(Mr,1),Cd=H(pd);function is(w,S){for(var R=-1,F=w==null?0:w.length;++R<F&&S(w[R],R,w)!==!1;);return w}function bd(w){return function(S,R,F){for(var U=-1,j=Object(S),Q=F(S),J=Q.length;J--;){var lt=Q[w?J:++U];if(R(j[lt],lt,j)===!1)break}return S}}var ss=bd();function ls(w,S){return w&&ss(w,S,Xc)}function Ym(w,S,R,F){for(var U=w.length,j=R+(F?1:-1);F?j--:++j<U;)if(S(w[j],j,w))return j;return-1}function iA(w){return w!==w}function Jm(w,S,R){for(var F=R-1,U=w.length;++F<U;)if(w[F]===S)return F;return-1}function pl(w,S,R){return S===S?Jm(w,S,R):Ym(w,iA,R)}var ea=function(w,S,R){typeof S=="function"&&(R=S,S=null),R=Sr(R||jt);var F=Xc(w),U=F.length;if(!U)return R(null);S||(S=U);var j={},Q=0,J=!1,lt=Object.create(null),pt=[],ct=[],At={};ls(w,function(he,ie){if(!ve(he)){Zt(ie,[he]),ct.push(ie);return}var Ce=he.slice(0,he.length-1),ko=Ce.length;if(ko===0){Zt(ie,he),ct.push(ie);return}At[ie]=ko,is(Ce,function(E){if(!w[E])throw new Error("async.auto task `"+ie+"` has a non-existent dependency `"+E+"` in "+Ce.join(", "));nn(E,function(){ko--,ko===0&&Zt(ie,he)})})}),IA(),Re();function Zt(he,ie){pt.push(function(){yo(he,ie)})}function Re(){if(pt.length===0&&Q===0)return R(null,j);for(;pt.length&&Q<S;){var he=pt.shift();he()}}function nn(he,ie){var Ce=lt[he];Ce||(Ce=lt[he]=[]),Ce.push(ie)}function Fn(he){var ie=lt[he]||[];is(ie,function(Ce){Ce()}),Re()}function yo(he,ie){if(!J){var Ce=vo(function(E,Or){if(Q--,arguments.length>2&&(Or=o(arguments,1)),E){var ds={};ls(j,function(Pn,$t){ds[$t]=Pn}),ds[he]=Or,J=!0,lt=Object.create(null),R(E,ds)}else j[he]=Or,Fn(he)});Q++;var ko=D(ie[ie.length-1]);ie.length>1?ko(j,Ce):ko(Ce)}}function IA(){for(var he,ie=0;ct.length;)he=ct.pop(),ie++,is(TA(he),function(Ce){--At[Ce]===0&&ct.push(Ce)});if(ie!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function TA(he){var ie=[];return ls(w,function(Ce,ko){ve(Ce)&&pl(Ce,he,0)>=0&&ie.push(ko)}),ie}};function ci(w,S){for(var R=-1,F=w==null?0:w.length,U=Array(F);++R<F;)U[R]=S(w[R],R,w);return U}var sA="[object Symbol]";function lA(w){return typeof w=="symbol"||dn(w)&&Tr(w)==sA}var cA=1/0,Ad=ht?ht.prototype:void 0,Km=Ad?Ad.toString:void 0;function vd(w){if(typeof w=="string")return w;if(ve(w))return ci(w,vd)+"";if(lA(w))return Km?Km.call(w):"";var S=w+"";return S=="0"&&1/w==-cA?"-0":S}function aA(w,S,R){var F=-1,U=w.length;S<0&&(S=-S>U?0:U+S),R=R>U?U:R,R<0&&(R+=U),U=S>R?0:R-S>>>0,S>>>=0;for(var j=Array(U);++F<U;)j[F]=w[F+S];return j}function uA(w,S,R){var F=w.length;return R=R===void 0?F:R,!S&&R>=F?w:aA(w,S,R)}function yd(w,S){for(var R=w.length;R--&&pl(S,w[R],0)>-1;);return R}function dA(w,S){for(var R=-1,F=w.length;++R<F&&pl(S,w[R],0)>-1;);return R}function hA(w){return w.split("")}var fA="\\ud800-\\udfff",mA="\\u0300-\\u036f",gA="\\ufe20-\\ufe2f",ce="\\u20d0-\\u20ff",re=mA+gA+ce,pA="\\ufe0e\\ufe0f",CA="\\u200d",bA=RegExp("["+CA+fA+re+pA+"]");function AA(w){return bA.test(w)}var Xm="\\ud800-\\udfff",vA="\\u0300-\\u036f",tg="\\ufe20-\\ufe2f",yA="\\u20d0-\\u20ff",Qe=vA+tg+yA,kd="\\ufe0e\\ufe0f",ai="["+Xm+"]",na="["+Qe+"]",Cl="\\ud83c[\\udffb-\\udfff]",On="(?:"+na+"|"+Cl+")",wd="[^"+Xm+"]",Bd="(?:\\ud83c[\\udde6-\\uddff]){2}",Ed="[\\ud800-\\udbff][\\udc00-\\udfff]",eg="\\u200d",xd=On+"?",Id="["+kd+"]?",wn="(?:"+eg+"(?:"+[wd,Bd,Ed].join("|")+")"+Id+xd+")*",kA=Id+xd+wn,_n="(?:"+[wd+na+"?",na,Bd,Ed,ai].join("|")+")",wA=RegExp(Cl+"(?="+Cl+")|"+_n+kA,"g");function ng(w){return w.match(wA)||[]}function Zo(w){return AA(w)?ng(w):hA(w)}function oa(w){return w==null?"":vd(w)}var Td=/^\s+|\s+$/g;function de(w,S,R){if(w=oa(w),w&&(R||S===void 0))return w.replace(Td,"");if(!w||!(S=vd(S)))return w;var F=Zo(w),U=Zo(S),j=dA(F,U),Q=yd(F,U)+1;return uA(F,j,Q).join("")}var Lr=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,Sd=/,/,BA=/(=.+)?(\s*)$/,Dd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function EA(w){return w=w.toString().replace(Dd,""),w=w.match(Lr)[2].replace(" ",""),w=w?w.split(Sd):[],w=w.map(function(S){return de(S.replace(BA,""))}),w}function og(w,S){var R={};ls(w,function(F,U){var j,Q=_(F),J=!Q&&F.length===1||Q&&F.length===0;if(ve(F))j=F.slice(0,-1),F=F[F.length-1],R[U]=j.concat(j.length>0?lt:F);else if(J)R[U]=F;else{if(j=EA(F),F.length===0&&!Q&&j.length===0)throw new Error("autoInject task functions require explicit parameters.");Q||j.pop(),R[U]=j.concat(lt)}function lt(pt,ct){var At=ci(j,function(Zt){return pt[Zt]});At.push(ct),D(F).apply(null,At)}}),ea(R,S)}function Kn(){this.head=this.tail=null,this.length=0}function Md(w,S){w.length=1,w.head=w.tail=S}Kn.prototype.removeLink=function(w){return w.prev?w.prev.next=w.next:this.head=w.next,w.next?w.next.prev=w.prev:this.tail=w.prev,w.prev=w.next=null,this.length-=1,w},Kn.prototype.empty=function(){for(;this.head;)this.shift();return this},Kn.prototype.insertAfter=function(w,S){S.prev=w,S.next=w.next,w.next?w.next.prev=S:this.tail=S,w.next=S,this.length+=1},Kn.prototype.insertBefore=function(w,S){S.prev=w.prev,S.next=w,w.prev?w.prev.next=S:this.head=S,w.prev=S,this.length+=1},Kn.prototype.unshift=function(w){this.head?this.insertBefore(this.head,w):Md(this,w)},Kn.prototype.push=function(w){this.tail?this.insertAfter(this.tail,w):Md(this,w)},Kn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},Kn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},Kn.prototype.toArray=function(){for(var w=Array(this.length),S=this.head,R=0;R<this.length;R++)w[R]=S.data,S=S.next;return w},Kn.prototype.remove=function(w){for(var S=this.head;S;){var R=S.next;w(S)&&this.removeLink(S),S=R}return this};function bl(w,S,R){if(S==null)S=1;else if(S===0)throw new Error("Concurrency must not be zero");var F=D(w),U=0,j=[],Q=!1;function J(At,Zt,Re){if(Re!=null&&typeof Re!="function")throw new Error("task callback must be a function");if(ct.started=!0,ve(At)||(At=[At]),At.length===0&&ct.idle())return C(function(){ct.drain()});for(var nn=0,Fn=At.length;nn<Fn;nn++){var yo={data:At[nn],callback:Re||jt};Zt?ct._tasks.unshift(yo):ct._tasks.push(yo)}Q||(Q=!0,C(function(){Q=!1,ct.process()}))}function lt(At){return function(Zt){U-=1;for(var Re=0,nn=At.length;Re<nn;Re++){var Fn=At[Re],yo=pl(j,Fn,0);yo===0?j.shift():yo>0&&j.splice(yo,1),Fn.callback.apply(Fn,arguments),Zt!=null&&ct.error(Zt,Fn.data)}U<=ct.concurrency-ct.buffer&&ct.unsaturated(),ct.idle()&&ct.drain(),ct.process()}}var pt=!1,ct={_tasks:new Kn,concurrency:S,payload:R,saturated:jt,unsaturated:jt,buffer:S/4,empty:jt,drain:jt,error:jt,started:!1,paused:!1,push:function(At,Zt){J(At,!1,Zt)},kill:function(){ct.drain=jt,ct._tasks.empty()},unshift:function(At,Zt){J(At,!0,Zt)},remove:function(At){ct._tasks.remove(At)},process:function(){if(!pt){for(pt=!0;!ct.paused&&U<ct.concurrency&&ct._tasks.length;){var At=[],Zt=[],Re=ct._tasks.length;ct.payload&&(Re=Math.min(Re,ct.payload));for(var nn=0;nn<Re;nn++){var Fn=ct._tasks.shift();At.push(Fn),j.push(Fn),Zt.push(Fn.data)}U+=1,ct._tasks.length===0&&ct.empty(),U===ct.concurrency&&ct.saturated();var yo=vo(lt(At));F(Zt,yo)}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,C(ct.process))}};return ct}function ui(w,S){return bl(w,1,S)}var cs=ze(Dr,1);function Yo(w,S,R,F){F=Sr(F||jt);var U=D(R);cs(w,function(j,Q,J){U(S,j,function(lt,pt){S=pt,J(lt)})},function(j){F(j,S)})}function ra(){var w=ci(arguments,D);return function(){var S=o(arguments),R=this,F=S[S.length-1];typeof F=="function"?S.pop():F=jt,Yo(w,S,function(U,j,Q){j.apply(R,U.concat(function(J){var lt=o(arguments,1);Q(J,lt)}))},function(U,j){F.apply(R,[U].concat(j))})}}var ia=function(){return ra.apply(null,o(arguments).reverse())},Ld=Array.prototype.concat,Al=function(w,S,R,F){F=F||jt;var U=D(R);Mr(w,S,function(j,Q){U(j,function(J){return J?Q(J):Q(null,o(arguments,1))})},function(j,Q){for(var J=[],lt=0;lt<Q.length;lt++)Q[lt]&&(J=Ld.apply(J,Q[lt]));return F(j,J)})},rg=ze(Al,1/0),sa=ze(Al,1),la=function(){var w=o(arguments),S=[null].concat(w);return function(){var R=arguments[arguments.length-1];return R.apply(this,S)}};function vl(w){return w}function di(w,S){return function(R,F,U,j){j=j||jt;var Q=!1,J;R(F,function(lt,pt,ct){U(lt,function(At,Zt){At?ct(At):w(Zt)&&!J?(Q=!0,J=S(!0,lt),ct(null,si)):ct()})},function(lt){lt?j(lt):j(null,Q?J:S(!1))})}}function hn(w,S){return S}var as=Qo(di(vl,hn)),Jo=li(di(vl,hn)),yl=ze(Jo,1);function Rd(w){return function(S){var R=o(arguments,1);R.push(function(F){var U=o(arguments,1);typeof console=="object"&&(F?console.error&&console.error(F):console[w]&&is(U,function(j){console[w](j)}))}),D(S).apply(null,R)}}var ig=Rd("dir");function sg(w,S,R){R=vo(R||jt);var F=D(w),U=D(S);function j(J){if(J)return R(J);var lt=o(arguments,1);lt.push(Q),U.apply(this,lt)}function Q(J,lt){if(J)return R(J);if(!lt)return R(null);F(j)}Q(null,!0)}function Od(w,S,R){R=vo(R||jt);var F=D(w),U=function(j){if(j)return R(j);var Q=o(arguments,1);if(S.apply(this,Q))return F(U);R.apply(null,[null].concat(Q))};F(U)}function lg(w,S,R){Od(w,function(){return!S.apply(this,arguments)},R)}function cg(w,S,R){R=vo(R||jt);var F=D(S),U=D(w);function j(J){if(J)return R(J);U(Q)}function Q(J,lt){if(J)return R(J);if(!lt)return R(null);F(j)}U(Q)}function hi(w){return function(S,R,F){return w(S,F)}}function ca(w,S,R){Go(w,hi(D(S)),R)}function kl(w,S,R,F){gl(S)(w,hi(D(R)),F)}var fi=ze(kl,1);function aa(w){return _(w)?w:i(function(S,R){var F=!0;S.push(function(){var U=arguments;F?C(function(){R.apply(null,U)}):R.apply(null,U)}),w.apply(this,S),F=!1})}function Xn(w){return!w}var mi=Qo(di(Xn,Xn)),wl=li(di(Xn,Xn)),ua=ze(wl,1);function ag(w){return function(S){return S==null?void 0:S[w]}}function us(w,S,R,F){var U=new Array(S.length);w(S,function(j,Q,J){R(j,function(lt,pt){U[Q]=!!pt,J(lt)})},function(j){if(j)return F(j);for(var Q=[],J=0;J<S.length;J++)U[J]&&Q.push(S[J]);F(null,Q)})}function to(w,S,R,F){var U=[];w(S,function(j,Q,J){R(j,function(lt,pt){lt?J(lt):(pt&&U.push({index:Q,value:j}),J())})},function(j){j?F(j):F(null,ci(U.sort(function(Q,J){return Q.index-J.index}),ag("value")))})}function da(w,S,R,F){var U=ll(S)?us:to;U(w,S,D(R),F||jt)}var ha=Qo(da),Bl=li(da),fa=ze(Bl,1);function ug(w,S){var R=vo(S||jt),F=D(aa(w));function U(j){if(j)return R(j);F(U)}U()}var ma=function(w,S,R,F){F=F||jt;var U=D(R);Mr(w,S,function(j,Q){U(j,function(J,lt){return J?Q(J):Q(null,{key:lt,val:j})})},function(j,Q){for(var J={},lt=Object.prototype.hasOwnProperty,pt=0;pt<Q.length;pt++)if(Q[pt]){var ct=Q[pt].key,At=Q[pt].val;lt.call(J,ct)?J[ct].push(At):J[ct]=[At]}return F(j,J)})},gi=ze(ma,1/0),N=ze(ma,1),q=Rd("log");function z(w,S,R,F){F=Sr(F||jt);var U={},j=D(R);Dr(w,S,function(Q,J,lt){j(Q,J,function(pt,ct){if(pt)return lt(pt);U[J]=ct,lt()})},function(Q){F(Q,U)})}var ft=ze(z,1/0),xt=ze(z,1);function Vt(w,S){return S in w}function xe(w,S){var R=Object.create(null),F=Object.create(null);S=S||vl;var U=D(w),j=i(function(J,lt){var pt=S.apply(null,J);Vt(R,pt)?C(function(){lt.apply(null,R[pt])}):Vt(F,pt)?F[pt].push(lt):(F[pt]=[lt],U.apply(null,J.concat(function(){var ct=o(arguments);R[pt]=ct;var At=F[pt];delete F[pt];for(var Zt=0,Re=At.length;Zt<Re;Zt++)At[Zt].apply(null,ct)})))});return j.memo=R,j.unmemoized=w,j}var Gt;a?Gt=process.nextTick:l?Gt=setImmediate:Gt=d;var ga=h(Gt);function _d(w,S,R){R=R||jt;var F=ll(S)?[]:{};w(S,function(U,j,Q){D(U)(function(J,lt){arguments.length>2&&(lt=o(arguments,1)),F[j]=lt,Q(J)})},function(U){R(U,F)})}function Bn(w,S){_d(Go,w,S)}function El(w,S,R){_d(gl(S),w,R)}var Fd=function(w,S){var R=D(w);return bl(function(F,U){R(F[0],U)},S,1)},pi=function(w,S){var R=Fd(w,S);return R.push=function(F,U,j){if(j==null&&(j=jt),typeof j!="function")throw new Error("task callback must be a function");if(R.started=!0,ve(F)||(F=[F]),F.length===0)return C(function(){R.drain()});U=U||0;for(var Q=R._tasks.head;Q&&U>=Q.priority;)Q=Q.next;for(var J=0,lt=F.length;J<lt;J++){var pt={data:F[J],priority:U,callback:j};Q?R._tasks.insertBefore(Q,pt):R._tasks.push(pt)}C(R.process)},delete R.unshift,R};function xl(w,S){if(S=Sr(S||jt),!ve(w))return S(new TypeError("First argument to race must be an array of functions"));if(!w.length)return S();for(var R=0,F=w.length;R<F;R++)D(w[R])(S)}function Ci(w,S,R,F){var U=o(w).reverse();Yo(U,S,R,F)}function Wt(w){var S=D(w);return i(function(F,U){return F.push(function(Q,J){if(Q)U(null,{error:Q});else{var lt;arguments.length<=2?lt=J:lt=o(arguments,1),U(null,{value:lt})}}),S.apply(this,F)})}function dg(w){var S;return ve(w)?S=ci(w,Wt):(S={},ls(w,function(R,F){S[F]=Wt.call(this,R)})),S}function Pd(w,S,R,F){da(w,S,function(U,j){R(U,function(Q,J){j(Q,!J)})},F)}var Il=Qo(Pd),Nd=li(Pd),hg=ze(Nd,1);function fg(w){return function(){return w}}function bi(w,S,R){var F=5,U=0,j={times:F,intervalFunc:fg(U)};function Q(ct,At){if(typeof At=="object")ct.times=+At.times||F,ct.intervalFunc=typeof At.interval=="function"?At.interval:fg(+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 w=="function"?(R=S||jt,S=w):(Q(j,w),R=R||jt),typeof S!="function")throw new Error("Invalid arguments for async.retry");var J=D(S),lt=1;function pt(){J(function(ct){ct&<++<j.times&&(typeof j.errorFilter!="function"||j.errorFilter(ct))?setTimeout(pt,j.intervalFunc(lt)):R.apply(null,arguments)})}pt()}var Ko=function(w,S){S||(S=w,w=null);var R=D(S);return i(function(F,U){function j(Q){R.apply(null,F.concat(Q))}w?bi(w,j,U):bi(j,U)})};function Tl(w,S){_d(cs,w,S)}var Sl=Qo(di(Boolean,vl)),Rr=li(di(Boolean,vl)),Dl=ze(Rr,1);function $d(w,S,R){var F=D(S);ta(w,function(j,Q){F(j,function(J,lt){if(J)return Q(J);Q(null,{value:j,criteria:lt})})},function(j,Q){if(j)return R(j);R(null,ci(Q.sort(U),ag("value")))});function U(j,Q){var J=j.criteria,lt=Q.criteria;return J<lt?-1:J>lt?1:0}}function Ml(w,S,R){var F=D(w);return i(function(U,j){var Q=!1,J;function lt(){var pt=w.name||"anonymous",ct=new Error('Callback function "'+pt+'" timed out.');ct.code="ETIMEDOUT",R&&(ct.info=R),Q=!0,j(ct)}U.push(function(){Q||(j.apply(null,arguments),clearTimeout(J))}),J=setTimeout(lt,S),F.apply(null,U)})}var mg=Math.ceil,Ll=Math.max;function Ai(w,S,R,F){for(var U=-1,j=Ll(mg((S-w)/(R||1)),0),Q=Array(j);j--;)Q[F?j:++U]=w,w+=R;return Q}function vi(w,S,R,F){var U=D(R);Mr(Ai(0,w,1),S,U,F)}var gg=ze(vi,1/0),pg=ze(vi,1);function Cg(w,S,R,F){arguments.length<=3&&(F=R,R=S,S=ve(w)?[]:{}),F=Sr(F||jt);var U=D(R);Go(w,function(j,Q,J){U(S,j,Q,J)},function(j){F(j,S)})}function Rl(w,S){var R=null,F;S=S||jt,fi(w,function(U,j){D(U)(function(Q,J){arguments.length>2?F=o(arguments,1):F=J,R=Q,j(!Q)})},function(){S(R,F)})}function Ol(w){return function(){return(w.unmemoized||w).apply(null,arguments)}}function _l(w,S,R){R=vo(R||jt);var F=D(S);if(!w())return R(null);var U=function(j){if(j)return R(j);if(w())return F(U);var Q=o(arguments,1);R.apply(null,[null].concat(Q))};F(U)}function bg(w,S,R){_l(function(){return!w.apply(this,arguments)},S,R)}var Hd=function(w,S){if(S=Sr(S||jt),!ve(w))return S(new Error("First argument to waterfall must be an array of functions"));if(!w.length)return S();var R=0;function F(j){var Q=D(w[R++]);j.push(vo(U)),Q.apply(null,j)}function U(j){if(j||R===w.length)return S.apply(null,arguments);F(o(arguments,1))}F([])},xA={apply:r,applyEach:gd,applyEachSeries:Cd,asyncify:v,auto:ea,autoInject:og,cargo:ui,compose:ia,concat:rg,concatLimit:Al,concatSeries:sa,constant:la,detect:as,detectLimit:Jo,detectSeries:yl,dir:ig,doDuring:sg,doUntil:lg,doWhilst:Od,during:cg,each:ca,eachLimit:kl,eachOf:Go,eachOfLimit:Dr,eachOfSeries:cs,eachSeries:fi,ensureAsync:aa,every:mi,everyLimit:wl,everySeries:ua,filter:ha,filterLimit:Bl,filterSeries:fa,forever:ug,groupBy:gi,groupByLimit:ma,groupBySeries:N,log:q,map:ta,mapLimit:Mr,mapSeries:pd,mapValues:ft,mapValuesLimit:z,mapValuesSeries:xt,memoize:xe,nextTick:ga,parallel:Bn,parallelLimit:El,priorityQueue:pi,queue:Fd,race:xl,reduce:Yo,reduceRight:Ci,reflect:Wt,reflectAll:dg,reject:Il,rejectLimit:Nd,rejectSeries:hg,retry:bi,retryable:Ko,seq:ra,series:Tl,setImmediate:C,some:Sl,someLimit:Rr,someSeries:Dl,sortBy:$d,timeout:Ml,times:gg,timesLimit:vi,timesSeries:pg,transform:Cg,tryEach:Rl,unmemoize:Ol,until:bg,waterfall:Hd,whilst:_l,all:mi,allLimit:wl,allSeries:ua,any:Sl,anyLimit:Rr,anySeries:Dl,find:as,findLimit:Jo,findSeries:yl,forEach:ca,forEachSeries:fi,forEachLimit:kl,forEachOf:Go,forEachOfSeries:cs,forEachOfLimit:Dr,inject:Yo,foldl:Yo,foldr:Ci,select:ha,selectLimit:Bl,selectSeries:fa,wrapSync:v};e.default=xA,e.apply=r,e.applyEach=gd,e.applyEachSeries=Cd,e.asyncify=v,e.auto=ea,e.autoInject=og,e.cargo=ui,e.compose=ia,e.concat=rg,e.concatLimit=Al,e.concatSeries=sa,e.constant=la,e.detect=as,e.detectLimit=Jo,e.detectSeries=yl,e.dir=ig,e.doDuring=sg,e.doUntil=lg,e.doWhilst=Od,e.during=cg,e.each=ca,e.eachLimit=kl,e.eachOf=Go,e.eachOfLimit=Dr,e.eachOfSeries=cs,e.eachSeries=fi,e.ensureAsync=aa,e.every=mi,e.everyLimit=wl,e.everySeries=ua,e.filter=ha,e.filterLimit=Bl,e.filterSeries=fa,e.forever=ug,e.groupBy=gi,e.groupByLimit=ma,e.groupBySeries=N,e.log=q,e.map=ta,e.mapLimit=Mr,e.mapSeries=pd,e.mapValues=ft,e.mapValuesLimit=z,e.mapValuesSeries=xt,e.memoize=xe,e.nextTick=ga,e.parallel=Bn,e.parallelLimit=El,e.priorityQueue=pi,e.queue=Fd,e.race=xl,e.reduce=Yo,e.reduceRight=Ci,e.reflect=Wt,e.reflectAll=dg,e.reject=Il,e.rejectLimit=Nd,e.rejectSeries=hg,e.retry=bi,e.retryable=Ko,e.seq=ra,e.series=Tl,e.setImmediate=C,e.some=Sl,e.someLimit=Rr,e.someSeries=Dl,e.sortBy=$d,e.timeout=Ml,e.times=gg,e.timesLimit=vi,e.timesSeries=pg,e.transform=Cg,e.tryEach=Rl,e.unmemoize=Ol,e.until=bg,e.waterfall=Hd,e.whilst=_l,e.all=mi,e.allLimit=wl,e.allSeries=ua,e.any=Sl,e.anyLimit=Rr,e.anySeries=Dl,e.find=as,e.findLimit=Jo,e.findSeries=yl,e.forEach=ca,e.forEachSeries=fi,e.forEachLimit=kl,e.forEachOf=Go,e.forEachOfSeries=cs,e.forEachOfLimit=Dr,e.inject=Yo,e.foldl=Yo,e.foldr=Ci,e.select=ha,e.selectLimit=Bl,e.selectSeries=fa,e.wrapSync=v,Object.defineProperty(e,"__esModule",{value:!0})})})(O1,O1.exports);var i2={exports:{}},_1=i2.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)?_1(n,t):i};_1.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=_1(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 s2=Hi,ZM=o2,YM=r2,uf=No,F1=O1.exports,JM=i2.exports,l2=Vs.ACTIONS,c2=Pe;function Pe(n,t){if(s2.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}s2.mixin(Pe),Pe.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Pe.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Pe.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||JM();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Pe.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);F1.parallel([function(i){F1.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();F1.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)})})},Pe.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?l2.presenceSubscribe:l2.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,o,this)},Pe.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Pe.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Pe.prototype._receiveUpdate=function(n,t){var e=uf.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=uf.digOrCreate(this._remotePresenceInstances,t.id,function(){return o._createRemotePresence(t.id)});r.receiveUpdate(t)},Pe.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Pe.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()}},Pe.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Pe.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Pe.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)})},Pe.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Pe.prototype._callbackOrEmit=function(n,t){if(t)return uf.nextTick(t,n);n&&this.emit("error",n)},Pe.prototype._createLocalPresence=function(n){return new ZM(this,n)},Pe.prototype._createRemotePresence=function(n){return new YM(this,n)},Pe.prototype._callEachOrEmit=function(n,t){var e=uf.callEach(n,t);!e&&t&&this.emit("error",t)};var ru=o2,a2=rf,KM=No,u2=a2.CODES,XM=Ho;function Ho(n,t){ru.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()}Ho.prototype=Object.create(ru.prototype),Ho.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:u2.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,ru.prototype.submit.call(this,n,t)},Ho.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),ru.prototype.destroy.call(this,n)},Ho.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={})})}},Ho.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)},Ho.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)}},Ho.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},Ho.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},Ho.prototype._message=function(){var n=ru.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},Ho.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!KM.supportsPresence(o))throw new a2(u2.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var d2={};(function(n){var t=eu,e=rf,o=No,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(C){return C}}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 C=n.apply(l,p);if(C)return C}},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(C){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:C.message||C}}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 C=d[p];typeof C.lm=="string"&&(C.lm=+C.lm);for(var v=C.p,B=h,x=0;x<v.length;x++){var I=v[x];Object.prototype.toString.call(B)=="[object Array]"?v[x]=+I:B.constructor===Object&&(v[x]=I.toString()),B=B[I]}p<d.length-1&&(h=t.defaultType.apply(h,[C]))}}}}})(d2);var iu=r2,tL=d2,eL=fo;function fo(n,t){iu.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()}fo.prototype=Object.create(iu.prototype),fo.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},fo.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),iu.prototype.destroy.call(this,n)},fo.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)},fo.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))}})}},fo.prototype._handleOp=function(n,t,e){var o=e===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},iu.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},iu.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},fo.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)}},fo.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++):tL.transformPresence(this._pending,t,e)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},fo.prototype._startCachingOps=function(){this._opCache=[]},fo.prototype._stopCachingOps=function(){this._opCache=null},fo.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var h2=c2,nL=XM,oL=eL;function ac(n,t,e){var o=ac.channel(t,e);h2.call(this,n,o),this.collection=t,this.id=e}var rL=ac;ac.prototype=Object.create(h2.prototype),ac.channel=function(n,t){return n+"."+t},ac.prototype._createLocalPresence=function(n){return new nL(this,n)},ac.prototype._createRemotePresence=function(n){return new oL(this,n)};var iL=sL;function sL(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var lL=iL,f2=Hi,m2=su;function su(n,t,e,o,r){if(f2.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}f2.mixin(su),su.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},su.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},su.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new lL(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var g2=m2,cL=No,aL=Vs.ACTIONS,uL=P1;function P1(n,t,e,o,r,i){if(g2.call(this,n,t,e,o,i),!cL.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}P1.prototype=Object.create(g2.prototype),P1.prototype._message=function(){return{a:aL.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var p2=m2,dL=No,hL=Vs.ACTIONS,fL=N1;function N1(n,t,e,o,r,i){if(p2.call(this,n,t,e,o,i),!dL.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}N1.prototype=Object.create(p2.prototype),N1.prototype._message=function(){return{a:hL.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var mL=HM,gL=WM,pL=c2,C2=rL,CL=uL,bL=fL,b2=Hi,uc=rf,ee=Vs.ACTIONS,A2=eu,jo=No,lu=Qk,cu=uc.CODES;function v2(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var AL=Bt;function Bt(n){b2.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=v2(n),this.bindToSocket(n)}b2.mixin(Bt),Bt.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=v2(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{lu.warn("Failed to parse message",o);return}e.debug&&lu.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){jo.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)}},Bt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=y2(n.error,n),delete n.error),n.a){case ee.initLegacy:return this._handleLegacyInit(n);case ee.handshake:return this._handleHandshake(t,n);case ee.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case ee.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case ee.queryUnsubscribe:return;case ee.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 ee.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case ee.bulkSubscribe:case ee.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case ee.snapshotFetch:case ee.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case ee.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case ee.subscribe:case ee.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case ee.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case ee.presence:return this._handlePresence(t,n);case ee.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case ee.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case ee.presenceRequest:return this._handlePresenceRequest(t,n);case ee.pingPong:return this._handlePingPong(t);default:lu.warn("Ignoring unrecognized message",n)}};function y2(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}Bt.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](y2(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 lu.error("Invalid bulk message",t)},Bt.prototype._reset=function(){this.agent=null},Bt.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 uc(cu.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)}},Bt.prototype.startBulk=function(){this.bulk||(this.bulk={})},Bt.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},Bt.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})}},Bt.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)}},Bt.prototype.sendFetch=function(n){return this._sendActions(ee.fetch,n,n.version)},Bt.prototype.sendSubscribe=function(n){return this._sendActions(ee.subscribe,n,n.version)},Bt.prototype.sendUnsubscribe=function(n){return this._sendActions(ee.unsubscribe,n)},Bt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:ee.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)},Bt.prototype.send=function(n){this.debug&&lu.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},Bt.prototype.ping=function(){if(!this.canSend)throw new uc(cu.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:ee.pingPong};this.send(n)},Bt.prototype.close=function(){this.socket.close()},Bt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},Bt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new mL(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},Bt.prototype._destroyDoc=function(n){!n._wantsDestroy||(jo.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},Bt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},Bt.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new gL(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},Bt.prototype._destroyQuery=function(n){delete this.queries[n.id]},Bt.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(ee.queryFetch,n,t,e,o)},Bt.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(ee.querySubscribe,n,t,e,o)},Bt.prototype.hasPending=function(){return!!(this._firstDoc(df)||this._firstQuery(df)||this._firstSnapshotRequest())};function df(n){return n.hasPending()}Bt.prototype.hasWritePending=function(){return!!this._firstDoc(vL)};function vL(n){return n.hasWritePending()}Bt.prototype.whenNothingPending=function(n){var t=this._firstDoc(df);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(df);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}jo.nextTick(n)},Bt.prototype._nothingPendingRetry=function(n){var t=this;return function(){jo.nextTick(function(){t.whenNothingPending(n)})}},Bt.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}}},Bt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},Bt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},Bt.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new CL(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},Bt.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new bL(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},Bt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},Bt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},Bt.prototype._initializeHandshake=function(){this.send({a:ee.handshake,id:this.id})},Bt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},Bt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},Bt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new uc(cu.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(A2.map[n.type]!==A2.defaultType)return this.emit("error",new uc(cu.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new uc(cu.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},Bt.prototype.getPresence=function(n){var t=this,e=jo.digOrCreate(this._presences,n,function(){return new pL(t,n)});return e._wantsDestroy=!1,e},Bt.prototype.getDocPresence=function(n,t){var e=C2.channel(n,t),o=this,r=jo.digOrCreate(this._presences,e,function(){return new C2(o,n,t)});return r._wantsDestroy=!1,r},Bt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},Bt.prototype._addPresence=function(n){jo.digOrCreate(this._presences,n.channel,function(){return n})},Bt.prototype._handlePresenceSubscribe=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},Bt.prototype._handlePresenceUnsubscribe=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},Bt.prototype._handlePresence=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},Bt.prototype._handlePresenceRequest=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var k2=AL,yL=eu;const hf={err:1001,msg:"user auth error",name:"AuthError"},kL={err:1002,msg:"you don't have required permission",name:"PermissionError"},$1={err:1003,msg:"Too many user connected",name:"MaxUserError"},au={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},wL={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},BL={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},uu="x-live-editor-token",ff="x-live-editor-base-url",bn=M("auth-connection");function EL(n){try{n()}catch(t){bn.error(t)}}class xL{constructor(t,e){m(this,"enabled",!0);m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new Av.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 Li(this.getBaseURL())}async auth(t){g(bn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[uu]:t.token,[ff]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.enabled?(this.token=t.token,await o.json()):{read:"",user:""}}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[ff]:Li(this.getBaseURL())}})}async init(t){const e=await this.auth(t);if(!this.enabled)return;this.resourceToken=e.read,this.ws=new nI.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(k2.prototype),g(bn,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}}},k2.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,bn.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();if(await this.auth(t),!this.enabled){this.retryCount=10,setTimeout(()=>this.handleAuthError(),0);return}this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){bn.error(t),setTimeout(()=>this.handleAuthError(),0)}}else bn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(hf.msg);t.code=hf.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(au.msg);t.code=au.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===hf.err)bn.warn("auth error"),this.handleAuthError();else if(o===$1.err)bn.warn($1.msg),this.emitMaxUsersError();else if(o===au.err){bn.warn(au.msg);try{this.emitRequestReloadError()}catch(r){bn.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else bn.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError()}get(t,e){return g(bn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(g(bn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){g(bn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){g(bn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.enabled=!1,this.reauthFunc=void 0,this.events.removeAllListeners(),EL(()=>{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()}}M("utils/file");function IL(){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}IL();async function TL(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new oI.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 Li(i)}const mr=M("sharedb-doc/client"),SL=tI.default.create();class DL{constructor(t,e,o){m(this,"connection");m(this,"auth");m(this,"doc",null);m(this,"reauthFunc");m(this,"clientId",tt());m(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});g(mr,!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),mr.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;yL.register(Jd.type),this.connection=new xL(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return g(mr,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,{[uu]: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=>{mr.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await TL(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 C=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return mr.info(C),r(100),Array.isArray(C.data)?C.data[0]:C.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;g(mr,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[uu]:this.connection.token},e,o);return g(mr,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(mr,o,"no token"),a.headers={...a.headers,[uu]:o,[ff]:this.connection.getBase64BaseURL()};try{return await SL(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(mr,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=eI.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(g(mr,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/${Li(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 ML(){return{blocks:[{id:tt(),type:"text",text:[]}],comments:{},meta:{}}}const H1=M("block-ids");class LL{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(H1,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=tt();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(H1,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=tt(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class RL{constructor(){m(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new LL,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(H1,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class w2{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 j1=M("op-parse-handler");class OL{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 RL,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&&(j1.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)){j1.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 w2,o.set(d,h)),h.delete(l.key)}else g(j1,!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 w2,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);this.outerHandler.onUpdateBlockData(a,d,l.toDocBlockDelta(),this.local)})}}const Ne=M("op-parser");class B2{}class U1{constructor(t){m(this,"key");this.key=t}}function _L(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(Ne,s.id,"block id is required"),g(Ne,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 z1(n,t,e,o){if(e==="upsert"&&_L(n,t,o))return;g(Ne,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(Ne,typeof a=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),g(Ne,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(Ne,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){g(Ne,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const a=l[0];g(Ne,typeof a=="string",`invalid block op: key ${JSON.stringify(a)}`);const d=l[1];if(a==="text"){if(g(Ne,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 U1(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 B2),e==="upsert"&&a.i&&o.onInsertBlock(n,i,a.i),r.shift()}else{g(Ne,typeof l=="string","data is not string"),g(Ne,l!=="text","data !== 'text'"),g(Ne,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 U1(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof B2?o.onDeleteBlock(n,i):l instanceof U1?o.onDeleteBlockData(n,i,l.key):g(Ne,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function FL(n,t,e){Ne.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function PL(n,t,e){const o=n[1],r=n[2];g(Ne,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),g(Ne,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?Ne.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):Ne.error(`unknown comment op, ${JSON.stringify(n)}`)}function V1(n,t,e){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{V1(s,t,e)});return}const r=o;if(g(Ne,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){FL(n);return}if(r==="comments"){PL(n,t,e);return}const i=r;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{z1(i,s,t,e)}):n.slice(1).forEach(s=>{z1(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(Ne,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),z1(i,n.slice(1),t,e)}function E2(n,t,e){const o=new OL(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=>{V1(a,i,o)}):V1(s,i,o)}o.end()}const NL=M("sharedb-comments");function W1(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 x2(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 q1(n,t){const e=yM(t),{comments:o,meta:r,blocks:i,...s}=e,l={...n,blocks:i,...s},a=mt.default(l);return delete a.children,a}const ne=M("sharedb-doc/doc-container"),I2="ot-json1";Jd.type.registerSubtype(kM.type),Jd.type.name=I2,Jd.type.invert=null;class du extends Ba{constructor(e,o,r=!0){super();m(this,"doc");m(this,"client");m(this,"localPresence");m(this,"remoteCaretHandler",new AM);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(!ka.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){ne.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(ne.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),ne.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(ne.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,I2,i=>{i?r(i):o()})}));m(this,"submitInsertChildContainers",async e=>{if(e.length===0)return Promise.resolve();const o=e.map(({containerId:r,blocks:i})=>[Jr(r),{i}]);return this.submitOp([o])});m(this,"submitDeleteChildContainer",async e=>{const o=[Jr(e),{r:!0}];return this.submitOp(o)});m(this,"submitInsertBlock",async(e,o,r)=>{const i=[Jr(e),o,{i:r}];return this.submitOp(i)});m(this,"submitDeleteBlock",async(e,o)=>{const r=[Jr(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=[Jr(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=[Jr(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});m(this,"handleOp",(e,o,r)=>{if(this.destroyed){ne.warn("handleOp: destroyed");return}try{E2(e,this,!!o)}catch(i){throw ne.error(i),i}});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(ne,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new DL(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new du(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||ML())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw ne.error(o),ne.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(tt()),e())})}})}subscribe(){return new Promise((e,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return tu(this.data())}getContainerBlocks(e){const o=this.data();g(ne,o,"no doc data");const r=o[Jr(e)];return g(ne,r,`no container data: ${e}`),mt.default(r)}findContainerBlocks(e){const o=this.data();g(ne,o,"no doc data");const r=o[Jr(e)];return r!=null?r:null}getBlockData(e,o){const r=this.data();g(ne,r,"no doc data");const i=r[Jr(e)];g(ne,i,`no container data: ${e}`);const s=i[o];return g(ne,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(ne,i.text,"no block text");const s=mt.default(i.text);this.submitUpdateRichText(e,o,r);const l=cn.apply(s,r);return g(ne,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=mt.default(this.getBlockData(e,o));return this.submitUpdateBlockData(e,o,r),i}localInsertChildContainers(e){this.submitInsertChildContainers(e)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>x2(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return W1(o)}localCreateComment(e,o){const r=q1(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=q1(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(ne,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,cc(e),o,r)})}onInsertBlock(e,o,r,i){g(ne,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,cc(e),o,r,i)})}onUpdateBlockData(e,o,r,i){g(ne,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,cc(e),o,r,i)})}onUpdateBlockText(e,o,r,i){g(ne,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,cc(e),o,r,i)})}onDeleteContainer(e,o){g(ne,this.callbacks.length>0,"no callbacks"),g(ne,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,cc(e),o)})}onCreateContainer(e,o,r){g(ne,this.callbacks.length>0,"no callbacks"),g(ne,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,cc(e),o,r)})}onDeleteComment(e,o){g(ne,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(ne,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(ne,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 tu(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return tu(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:tu(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:tu(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){E2(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}M("remote-cursor");class T2{constructor(t){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",Fe.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 S2=M("remote-cursor-decorator");class G1{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(S2,typeof s=="string","invalid path containerId"),g(S2,typeof l=="number","invalid path blockIndex");const a=t.doc.getBlockData(s,l),d=sn(o);return r.getSimpleCursors(a.id).forEach((p,C)=>{C>d&&(C=d);const v=p.map(x=>({id:tt(),type:"remote-cursor",name:x.user.displayName,time:x.time,rainbowIndex:x.user.rainbowIndex})),B=i.get(C);B?B.push(...v):i.set(C,v)}),{insertions:i}}}class D2 extends ke.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Qt(ir(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=nt(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 $L(n,t){n.addCustom("child-block-tracker",()=>new D2(n)).addListener("change",t)}function HL(n,t){n.addCustom("child-block-tracker",()=>new D2(n)).removeListener("change",t)}const kot="",jL={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"}},UL={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},zL={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"}};L.mergeLang({"zh-CN":jL,"en-US":UL,"ja-JP":zL});const wot="";M("button");function mo(n,t,e,o,r){const i=k("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&&V(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0),o.indexOf("primary")!==-1&&V(i,"primary")),i}const Bot="",mf=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
27
|
+
`)}const FS=M("get-text-position");function ec(n,t){const e=t!=null?t:n.selection.range.start;e instanceof Ve||g(FS,!1,`invalid insert pos type: ${typeof e}`);const{blockId:o}=e,r=n.getBlockById(o),i=vt(r),s=ot(r),l=at(s),{offset:a}=e;return{block:r,container:s,containerId:l,blockIndex:i,offset:a}}const nc=M("insert-text");function n1(n,t,e,o){var s;const r=n.doc.getBlockData(t,e);if(g(nc,r,"no block data"),g(nc,r.text,"no block text"),sn(r.text)===0)return g(nc,o===0,"invalid text offset"),n.editorCommandProviders.getEmptyBlockTextAttributes(n,r.id);if(o===0)return;const i=qe(r.text,o-1,1).middle;if(!((s=i[0].attributes)!=null&&s.box))return i[0].attributes}function PS(n,t,e){const o=ot(t),r=at(o),i=vt(t);return n1(n,r,i,e)}function dy(n,t,e,o,r){const i=ot(t),s=at(i),l=vt(t),a=PS(n,t,e),d=Th(e,o,a!=null?a:null);return n.doc.localUpdateBlockText(s,l,d,r),Cn(n,t)}function hy(n,t,e,o){const r=ot(t),i=at(r),s=vt(t),l=Th(e," ",o);return n.doc.localUpdateBlockText(i,s,l),Cn(n,t)}function NS(n,t){let e=0;if(t===0)return!1;for(let o=0;o<n.length;o++){const r=n[o];g(nc,typeof r.insert=="string","invalid text op, no insert");const i=e+Sh(r);if(i===t)return!1;if(i>t)return!0;e=i}return!1}function o1(n,t,e,o,r){const i=n.doc.getBlockData(e,o);g(nc,i,"no block data"),g(nc,i.text,"no block text");const s=n1(n,e,o,r);s&&Object.keys(s).includes("link")&&(NS(i.text,r)||delete s.link);const l=Th(r,t,s!=null?s:null);return n.doc.localUpdateBlockText(e,o,l),Cn(n,n.getBlockById(i.id))}function r1(n,t){n.selection.range.isCollapsed()||n.clearSelectedContents();const{containerId:e,blockIndex:o,offset:r}=ec(n);o1(n,t,e,o,r)}const Hh=M("update-composition-text");function fy(n){const t=n.selection.range.start;t instanceof Ve||g(Hh,!1,`invalid insert pos type: ${typeof t}`);const{blockId:e}=t,o=n.getBlockById(e);g(Hh,et(n,o),"not a text kind block");const r=ot(o),i=at(r),s=vt(o),l=n.doc.getBlockData(i,s);g(Hh,l,"no block data in doc"),g(Hh,l.text,"no text data in text block");const a=Mt(o);Bh(n,Ri(o),e,a,l.text)}function my(n){gT(n)}function oc(n,t,e,o,r,i){return n.doc.localInsertBlock(t,e,o,r,i),n.getBlockById(o.id)}const qa=M("delete-block-text");function i1(n,t,e,o,r){if(!n.isBlockWritable(t))return qa.error("block is not writable"),0;g(qa,et(n,t),"block is not a text kind block");const i=ot(t),s=at(i),l=vt(t),a=n.doc.getBlockData(s,l);g(qa,a,"no block data in doc"),g(qa,a.text,"no text data in text block");let d=e;ln(t,e)||(d=_i(t,d));let h=e+o;g(qa,h<=ut(n,t),`invalid offset and count: ${e}, ${o}`),ln(t,h)||(h=Fs(t,h));const p=h-d,C=w3(d,p);return n.doc.localUpdateBlockText(s,l,C,r),p}const s1=M("break-text-block");function gy(n,t){const o=n.getBlockData(t).quoted;return o?{quoted:o}:{}}function rc(n,t,e,o){g(s1,et(n,t),`block is not a text kind block: ${St(t)}`),g(s1,e>=0&&e<=ut(n,t),`invalid offset: ${e}`);const r=ot(t),i=at(r),s=vt(t),l=o!=null&&o.copyBlockAttributes?gy(n,t):{};if(!(o!=null&&o.forceInsertAfter)&&(e===0||e===ut(n,t))){const v=e===0?s:s+1,B={...ur(""),...l,...o==null?void 0:o.newBlockData},x=be(n,t.id,0),I=oc(n,i,v,B,x);return{block:t,newBlock:I}}g(s1,ln(t,e),"not a valid offset");const a=Cn(n,t),{right:d}=Tn(a,e),h=sn(d);h>0&&i1(n,t,e,h);const p={...ur(d),...l,...o==null?void 0:o.newBlockData},C=oc(n,i,s+1,p,be(n,p.id,0));return{block:t,newBlock:C}}const $S=M("prepare-insert-new-block");function HS(n,t,e){if(t&&e!==void 0&&e!==null){const d=n.getContainerById(t),h=fe(d);return g($S,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(ot(r)),e=vt(r),!et(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=rc(n,r,s).newBlock;return{containerId:t,blockIndex:vt(a)}}const jS=M("auto-insert-block");function py(n,t,e,o,r,i){const s=HS(n,e,o);g(jS,s,`not an valid insert position: ${n.selection.range}`);const l={blockId:t.id,offset:0},a={anchor:l,focus:l};return oc(n,s.containerId,s.blockIndex,t,r!=null?r:a,i)}const US=M("delete-block");function jh(n,t,e){t.children&&(e.push(...t.children),t.children.forEach(o=>{n.getChildContainerData(o).forEach(i=>{jh(n,i,e)})}))}function Uh(n,t,e){const o=ot(t),r=at(o),i=vt(t),s=n.doc.getBlockData(r,i);return g(US,s,"no block data in doc"),n.doc.localDeleteBlock(r,i,We(n,{anchor:e.start,focus:e.end})),s}function l1(n,t,e){return n.undoManager.runInGroup(()=>{const o=ot(t);To(o)===1&&n.insertTextBlock("",at(o),0);let r=e?Oi(n,e):null;if(!r){const l=n.selection.range;sy(t,l)?r=ly(n,t):r=l}const i=Uh(n,t,r),s=[];return jh(n,i,s),s.length>0&&n.doc.localDeleteChildContainers(s),i})}function zS(n,t){const e=[t];n.doc.getContainerBlocks(t).forEach(r=>{jh(n,r,e)}),n.doc.localDeleteChildContainers(e)}function Cy(n,t){const e=[...t];t.forEach(o=>{n.doc.getContainerBlocks(o).forEach(i=>{jh(n,i,e)})}),n.doc.localDeleteChildContainers(e)}const c1=M("merge-text-block");function by(n,t,e){g(c1,et(n,t),"only text block can be merged"),g(c1,et(n,e),"only text block can be merged");const o=Fi(n,t),r=Fi(n,e),i=o.text,s=r.text;g(c1,i&&s,"block data has no text");const l=ot(t),a=at(l),d=vt(t),h=ut(n,t),p=o1(n,s,a,d,h),C=be(n,t,sn(i));return l1(n,e,C),p}const dr=M("clear-selected-contents");function zh(n,t){g(dr,et(n,t.block),"not a text kind block");const{start:e,end:o}=t;g(dr,e.isSimple(),"not a simple block position"),g(dr,o.isSimple(),"not a simple block position");const r=e.offset,i=o.offset;g(dr,r<=i,`invalid delete text offset: ${r}, ${i}`),r!==i&&n.deleteTextFromBlock(t.block,r,i-r)}function Ay(n,t,e){const o=at(t),r=fe(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 VS(n,t){const{block:e,start:o,end:r}=t;if(et(n,e)){zh(n,t);return}if(Se(e)||o.isSimple()){g(dr,r.isSimple(),"invalid range");const s=ot(e),l=vt(e),a=n.insertTextBlock("",at(s),l);n.selection.selectBlock(a,0),n.deleteBlock(e);return}g(dr,Lt(n,e),"invalid block kind"),g(dr,!o.isSimple()&&!r.isSimple(),"invalid range"),Jl(n,e,o,r),n.selection.range.getSelectedContainers().forEach((s,l)=>{Ay(n,s,{focus:l===0})})}function WS(n){if(!n.isWritable())return;const t=n.selection.range;if(t.isCollapsed())return;const e=t.getSelectedBlocks();if(g(dr,e.length>0,"no selected block"),e.length===1){VS(n,e[0]);return}const o=e[0],r=o.block,i=ot(r);g(dr,e.length>1,"no selected block");const s=e[e.length-1],l=s.block;if(et(n,r)){zh(n,o);const h=be(n,o.block,o.start.offset);if(e.slice(1,e.length-1).reverse().forEach(C=>n.deleteBlock(C.block)),et(n,l)){zh(n,s),n.mergeTextBlock(r,l,{focus:!0}),n.selection.setRange(h);return}n.deleteBlock(l),n.selection.setRange(h);return}if(et(n,l)){zh(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===To(i)){Ay(n,i,{focus:!0});return}const a=ae(r),d=qt(l);g(dr,a||d,"no prev or next block"),e.forEach(h=>n.deleteBlock(h.block))}function a1(n){n.selection.range.isCollapsed()||n.undoManager.runInGroup(()=>{n.emit("beforeClearSelection",n);try{n.doc.beginBatchUpdate(),WS(n)}finally{n.doc.endBatchUpdate()}n.emit("afterClearSelection",n)})}const qS=M("core");function vy(n,t,e){const o=ot(t),r=at(o),i=vt(t);return n.doc.localUpdateBlockText(r,i,e),setTimeout(()=>{n.selection.updateSelection(null)}),Cn(n,t)}function yy(n,t,e){if(!n.isBlockWritable(t)){qS.error("block is not writable");return}const o=n.getBlockText(t),r=cn.diff(o,e);vy(n,t,r)}function Vh(n,t,e){const o=Cn(n,t),r=typeof e=="string"?$s(e):e,i=cn.diff(o,r);return vy(n,t,i)}const Ga=M("update-block-data");function Wh(n,t,e,o){const r=ot(t),i=at(r),s=vt(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(C=>{if(!h.has(C)){if(C==="id"||C==="type"||C==="text")return;Ga.debug(`delete key: ${C}`),a.delete.push(C)}}),Object.entries(e).forEach(([C,v])=>{g(Ga,C!=="id"&&C!=="type",`invalid block data delta, ${C}`);const B=l[C];if(v==null){B!=null&&(Ga.debug(`delete key: ${C}`),a.delete.push(C));return}B!==v&&(ka.default(B,v)||C==="text"&&cn.diff(B,v).length===0||(d.has(C)?(Ga.debug(`replace key: ${C}`),a.delete.push(C)):Ga.debug(`insert key: ${C}`),a.insert[C]=v))}),n.doc.localUpdateBlockData(i,s,a,o),Fi(n,t)}function ky(n,t,e,o){const i={...n.getBlockData(t),embedData:e};return n.updateBlockData(t,i,o)}function u1(n,t,e){if(!Lt(n,t)||!(e!=null&&e.tryFocusToChildSimpleBlock)){n.selection.selectBlock(t,0);return}const r=zn(n,t).getChildContainers(n,t)[0],i=we(r);u1(n,i,e)}function js(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 Qa=M("clone-block");function Pi(n,t,e,o){const r=n.getBlockClass(e.type);if(r.blockToDoc)return r.blockToDoc(t,e,(h,p)=>(g(Qa,e!==p,"invalid child block"),Pi(n,h,e,o)));let i={};const s=new Map,l=mt.default(e);l.children&&(l.children=l.children.map(h=>{const p=tt(),C=t.blocks[h];g(Qa,Array.isArray(C),"invalid child blocks");const v=C.map(_=>Pi(n,t,_,o)),B=js(v),{root:x,...I}=B.blocks;return i={...i,...I},i[p]=B.blocks.root,s.set(h,p),p}));const a=Array.from(s.entries()),d=h=>{for(const p of a){const[C,v]=p;{const B=`${C}/`;if(h.startsWith(B)){const x=h.substring(B.length),I=`${v}/${x}`;return Qa.debug(`replace key: ${h} -> ${I}`),I}}{const B=`${C}_`;if(h.startsWith(B)){const x=h.substring(B.length),I=`${v}_${x}`;return Qa.debug(`replace key: ${h} -> ${I}`),I}}}return h};return Array.from(Object.entries(l)).forEach(([h,p])=>{const C=d(h);C!==h&&delete l.key,l[C]=p}),l.id=tt(),o&&(o.blockIdMap.set(e.id,l.id),s.forEach((h,p)=>o.containerIdMap.set(p,h))),{blocks:{root:[l],...i},meta:{},comments:{}}}function d1(n,t,e,o){const r=t.blocks[e];g(Qa,Array.isArray(r),"invalid child blocks");const i=r.map(l=>Pi(n,t,l,o));return js(i)}function h1(n,t,e){const o=t.blocks.root.map(r=>Pi(n.editorBlocks,t,r,e));return mt.default(js(o))}const wy=M("insert-doc");function By(n,t,e,o,r){if(Lt(n,t)){wy.warn("failed to insert doc into a complex block");return}const i=h1(n,o,r),s=ot(t),l=vt(t),a=at(s);n.doc.beginBatchUpdate(),n.undoManager.runInGroup(()=>{var H,W,G;const d=[];Object.entries(i.blocks).forEach(([K,ht])=>{K!=="root"&&d.push({containerId:K,blocks:ht})}),d.length>0&&n.doc.localInsertChildContainers(d);const h=i.blocks.root;if(Se(t)){n.deleteBlock(t);let K;h.reverse().forEach(ht=>{const bt=n.insertBlock(a,l,ht,void 0,{noFocus:!0});K||(K=bt)}),K&&n.selection.selectBlock(K,ut(n,K));return}if(g(wy,et(n,t),"not a text block"),ue(n,t)){const K=a==="root"&&n.getBlockByIndex(a,0)===t,ht=vt(t);let bt;h.forEach((_t,Ht)=>{const oe=n.insertBlock(a,ht+Ht,_t,void 0,{noFocus:!0});Ht===h.length-1&&(bt=oe)}),bt&&n.selection.selectBlock(bt,ut(n,bt)),K&&n.deleteBlock(t);return}if(h.length===1){const K=h[0];if(_a(n,K.type)){n.insertTextToBlock(t,e,(H=K.text)!=null?H:[]);return}n.breakTextBlock(t,e),n.insertBlock(a,l+1,K);return}const p=e===ut(n,t),C=e===0,v=h[0],B=h[h.length-1];let x;!p&&!C?x=n.breakTextBlock(t,e,{forceInsertAfter:!0}):x=t;const I=C?l:l+1;p?(x=n.insertBlock(a,l+1,B),n.selection.selectBlock(x,ut(n,x))):(n.selection.selectBlock(x,0),_a(n,B.type)?n.insertTextToBlock(x,0,(W=B.text)!=null?W:[]):n.insertBlock(a,I,B));const _=n.selection.range;let D=I;_a(n,v.type)?C?(n.insertBlock(a,I,v),D+=1):n.insertTextToBlock(t,e,(G=v.text)!=null?G:[]):(n.insertBlock(a,I,v),D+=1),h.slice(1,h.length-1).reverse().forEach(K=>{n.insertBlock(a,D,K)}),n.selection.setRange(_)}),n.doc.endBatchUpdate()}function f1(n,t,e,o,r){const i=h1(n,o,r),s=at(t),l=[];return n.undoManager.runInGroup(()=>{const a=[];Object.entries(i.blocks).forEach(([h,p])=>{h!=="root"&&a.push({containerId:h,blocks:p})}),n.doc.localInsertChildContainers(a),i.blocks.root.reverse().forEach(h=>{const p=n.insertBlock(s,e,h,void 0,{noFocus:!0,noScroll:!0});l.push(p)})}),l}function Ey(n,t,e){const o=To(t);f1(n,t,o,e);for(let r=0;r<o;r++){const i=we(t);n.deleteBlock(i)}}const Za=M("add-text-attribute");function GS(n,t,e,o){const{start:r,end:i}=e;g(Za,r.blockId===i.blockId&&r.blockId===it(t),"invalid range"),g(Za,o,"invalid attribute name");const s=n.getBlockText(t),l=tc(r.offset,i.offset-r.offset,s,o,void 0,{ignoreValue:!0});return n.setBlockText(t,l),l}function xy(n,t,e,o,r){const{start:i,end:s}=e;g(Za,i.blockId===s.blockId&&i.blockId===it(t),"invalid range"),g(Za,o,"invalid attribute name");const l=n.getBlockText(t),a=Ua(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function ic(n,t,e,o,r){const{start:i,end:s}=e;g(Za,i.blockId===s.blockId&&i.blockId===it(t),"invalid range");const l=n.getBlockText(t),a=L3(i.offset,s.offset-i.offset,l,o,r);return n.setBlockText(t,a),a}function Iy(n,t,e,o){const r=lr(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{r.forEach(i=>{const{block:s,start:l,end:a}=i;if(!et(n,s))return;if(ue(n,s)){o(n,it(s),t,e);return}const d=We(n,{anchor:l,focus:a});t==="color"||t==="backgroundColor"?ic(n,s,d,t,e):(ic(n,s,d,"color",null),ic(n,s,d,"backgroundColor",null))})})}function Ty(n,t,e){const o=lr(n,{simpleBlockOnly:!0});n.undoManager.runInGroup(()=>{o.forEach(r=>{const{block:i,start:s,end:l}=r;if(!et(n,i))return;if(ue(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=We(n,{anchor:s,focus:l});(t==="clearColor"||t==="clearAll")&&ic(n,i,a,"color",null),(t==="clearBackground"||t==="clearAll")&&ic(n,i,a,"backgroundColor",null)})})}function Sy(n,t,e){const o=t.getSelectedBlocks().filter(l=>et(n,l.block));if(o.length===0)return[null,null];const r=l=>{if(ut(n,l.block)===0)return e(n,it(l.block));const a=l.start,d=l.end,h=n.getBlockText(l.block);return _3(a.offset,d.offset-a.offset,h)};let[i,s]=r(o[0]);return i===null&&s===null?[i,s]:(o.forEach(l=>{const[a,d]=r(l);a===null||i===null?i=null:i=a===i?i:null,d===null||s===null?s=null:s=d===s?s:null}),[i,s])}const Wn=M("adjust-selection-pos");function Dy(n){const t=[];for(;n;){const e=ot(n);if(t.unshift(e),Qt(e))return t;const o=nt(e);g(Wn,o,"child container has not parent container"),n=o}g(Wn,!1,"should not come here: getParentContainers")}function My(n,t){for(;t;){const e=ot(t);if(e===n)return t;const o=nt(e);g(Wn,o,"could not find parent block for a child container"),t=o}g(Wn,!1,"no parent block in specified container")}function QS(n,t){const e=Dy(n),o=Dy(t);g(Wn,e.length>0&&o.length>0,"block has not parent container"),g(Wn,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=My(r,n),s=My(r,t);return{parentContainer:r,newBlock1:i,newBlock2:s}}function Ly(n,t){let e=nt(t);for(g(Wn,e,"element is not in a block");e;){const o=ot(e);g(Wn,Lo(o),"not a child container");const r=nt(o);if(g(Wn,r,"child container has not parent block"),r===n)return o;e=r}g(Wn,!1,"failed to find parent container in complex block")}function qh(n,t,e){const o=n.getBlockById(t.blockId),r=n.getBlockById(e.blockId);if(o===r)return t instanceof Ve&&e instanceof Ve?{anchor:t,focus:e}:t instanceof Ro&&e instanceof Ro?kh(n,o,t,e):null;const i=ot(o),s=ot(r);if(i===s)return t instanceof Ro&&(t=st(o,0,"home")),e instanceof Ro&&(e=st(r,ut(n,r),"end")),g(Wn,t instanceof Ve,"not valid position type"),g(Wn,e instanceof Ve,"not valid position type"),{anchor:t,focus:e};if(o.contains(s))return null;if(r.contains(i)){if(t instanceof Ve&&e instanceof Ro){const B=n.getContainerById(e.childContainerId);if(B===i)return{anchor:e,focus:e};const x=nt(i);if(x&&x===nt(B)){const I=me(x,at(i)),_=me(x,at(B));return kh(n,x,I,_)}}return null}const l=ih(o,r)>0,{newBlock1:a,newBlock2:d}=QS(o,r);if(a===d){const B=a,x=Ly(B,o),I=Ly(B,r);return t=me(a,at(x)),e=me(a,at(I)),Wn.debug(`select in complex block: ${x.id}, ${I.id}`),kh(n,B,t,e)}let h=l?ut(n,a):0;a===o&&t instanceof Ve&&(h=t.offset);let C=l?0:ut(n,d);return d===r&&e instanceof Ve&&(C=e.offset),t=st(a,h,l?"end":"home"),e=st(d,C,l?"home":"end"),{anchor:t,focus:e}}const ZS=M("move-complex-block-position");function YS(n,t,e){const o=n.getBlockById(t.blockId);g(ZS,Lt(n,o),"is not a complex block");const r=zn(n,o),i=n.getContainerById(t.childContainerId),s=r.getNextContainer(n,o,i,e,{noWrap:!0});return s?me(o,at(s)):null}const Ya=M("move-simple-block-position");function Ry(n,t){const e=pn(n,t,{visibleOnly:!0});g(Ya,e.length>0,"complex block has not any child container");const o=e[0];return we(o)}function Oy(n,t){const e=pn(n,t,{visibleOnly:!0});g(Ya,e.length>0,"complex block has not any child container");const o=e[e.length-1];return Ze(o)}function _y(n,t,e){const o=e?Ry(n,t):Oy(n,t);return Lt(n,o)?_y(n,o,e):o}function JS(n,t){const e=n.getBlockById(t.blockId);return Lt(n,e)&&t.offset===0?Ry(n,e):Ss(e)}function KS(n,t){const e=n.getBlockById(t.blockId);return Lt(n,e)&&t.offset===1?Oy(n,e):Ts(e)}function m1(n){return n==="ArrowLeft"||n==="ArrowUp"}function g1(n,t,e){const o=ot(t);if(Qt(o))return null;const r=nt(o);g(Ya,r,"child container has not parent block"),g(Ya,Lt(n,r),"is not a complex block");const i=zn(n,r).getNextContainer(n,r,o,e);return i?m1(e)?Ze(i):we(i):g1(n,r,e)}function XS(n,t,e){const o=ot(t);if(Qt(o))return null;const r=nt(o);if(g(Ya,r,"child container has not parent block"),m1(e)){const l=ae(r);if(l)return l}else{const l=qt(r);if(l)return l}const i=g1(n,r,e);if(i)return i;let s=r;for(;!Qt(ot(s));)s=nt(ot(s));return m1(e)?ae(s):qt(s)}function tD(n,t,e){return!Lt(n,t)||zn(n,t).enableKeyboardSelect?t:_y(n,t,e==="ArrowDown"||e==="ArrowRight")}function eD(n,t,e){const o=n.getBlockById(t.blockId),i=Yt(n,o).moveCaret(n,o,t,e);if(i)return i;let s=e==="ArrowDown"||e==="ArrowRight"?JS(n,t):KS(n,t);if(s||(s=g1(n,o,e),s||(s=XS(n,o,e))),!s){if(e==="ArrowDown"||e==="ArrowRight"){if(n.readonly||!Qt(ot(o)))return null;const l=n.insertTextBlock("",at(n.rootContainer),To(n.rootContainer));return st(l,0,"home")}return null}if(s=tD(n,s,e),et(n,s)){const l=n.selection.getSuggestedCaretX();if(e==="ArrowDown")return IT(n,s,o,t,l);if(e==="ArrowUp")return xT(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 nD(n,t,e){if(t==="ArrowLeft")return e.start;const o=e.end,r=n.getBlockById(o.blockId);if(et(n,r))return o;const i=qt(r);if(i)return st(i,0,"home");if(!Qt(ot(r))||n.readonly)return o;const s=n.insertTextBlock("",at(n.rootContainer),To(n.rootContainer));return st(s,0,"home")}function oD(n,t,e){const o=n.selection.range;let r;if(o instanceof Ye)e==="move"&&!o.isCollapsed()&&(t==="ArrowLeft"||t==="ArrowRight")?r=nD(n,t,o):r=eD(n,o.getFocusedPos(),t);else if(r=YS(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=Ze(s);r=st(l,0,"home")}else{const l=we(s);r=st(l,ut(n,l),"end")}}return r?e==="move"?{anchor:r,focus:r}:qh(n,o.anchor,r):null}function Ni(n,t,e){const o=oD(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 Fy(n){return Ni(n,"ArrowLeft","move"),!0}function Py(n){return Ni(n,"ArrowRight","move"),!0}function Ny(n){return Ni(n,"ArrowUp","move"),!0}function $y(n){if(Ni(n,"ArrowDown","move")||n.readonly)return!0;const t=n.getFocusedBlock(),e=ot(t);if(Qt(e)||Ze(e)!==t)return!0;const o=n.rootContainer;return n.insertTextBlock("",at(o),To(o)),!0}function Hy(n){return Ni(n,"ArrowDown","select"),!0}function jy(n){return Ni(n,"ArrowLeft","select"),!0}function Uy(n){return Ni(n,"ArrowRight","select"),!0}function zy(n){return Ni(n,"ArrowUp","select"),!0}const Vy=M("word-offset");function p1(n,t){const e=n.selection.range.focus;g(Vy,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(ue(n,o))return st(o,0,"home");if(e.offset===0||!et(n,o)){const s=ae(o);if(!s)return null;const l=st(s,ut(n,s),"end");if(t==="select"&&et(n,s)){const a=Qp(n,s,l.offset);return st(s,a,"normal")}return l}const r=Qp(n,o,e.offset);return st(o,r,"normal")}function C1(n,t){const e=n.selection.range.focus;g(Vy,e.isSimple(),"invalid range type");const o=n.getBlockById(e.blockId);if(ue(n,o))return st(o,0,"end");if(e.offset===ut(n,o)||!et(n,o)){const s=qt(o);if(!s)return null;const l=st(s,0,"home");if(t==="select"&&et(n,s)){const a=Zp(n,s,l.offset);return st(s,a,"end")}return l}const r=Zp(n,o,e.offset);return st(o,r,"normal")}function Wy(n){if(!n.selection.range.focus.isSimple())return!1;const e=p1(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function qy(n){if(!n.selection.range.focus.isSimple())return!1;const e=C1(n,"move");return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function Gy(n){if(!n.selection.range.focus.isSimple())return!1;const e=p1(n,"select");return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function Qy(n){if(!n.selection.range.focus.isSimple())return!1;const e=C1(n,"select");return e?(n.selection.setSelection(n.selection.range.anchor,e),n.selection.updateLastCaretRect(),!0):!1}M("find-block");function b1(n,t){if(!Lt(n,t))return t;const o=zn(n,t).getChildContainers(n,t)[0],i=fe(o)[0];return b1(n,i)}function A1(n,t){if(!Lt(n,t))return t;const e=zn(n,t).getChildContainers(n,t),o=e[e.length-1],r=fe(o),i=r[r.length-1];return A1(n,i)}function v1(n){const t=A1(n,Ze(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(e),!0}function Zy(n){const t=b1(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(e),!0}function Yy(n){const t=b1(n,n.getFirstBlock()),e=st(t,0,"home");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}function y1(n){const t=A1(n,Ze(n.rootContainer)),e=st(t,ut(n,t),"end");return n.selection.setSelection(n.selection.getAnchorPos(),e),!0}const Jy=M("line-offset");function Ky(n){const t=n.selection.range.focus;g(Jy,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===0||!et(n,e))return st(e,0,"home");let r=b3(e,t).start;const{next:i}=bh(e,r);return i&&ao(i)&&Oa(i)==="br"&&(r+=1),st(e,r,"home")}function Xy(n){const t=n.selection.range.focus;g(Jy,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId);if(t.offset===ut(n,e)||!et(n,e))return st(e,ut(n,e),"end");const o=b3(e,t);return st(e,o.end,"end")}function tk(n){if(!n.selection.range.focus.isSimple())return!1;const e=Ky(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function ek(n){if(!n.selection.range.focus.isSimple())return!1;const e=Xy(n);return e?(n.selection.setSelection(n.selection.getAnchorPos(),e),n.selection.updateLastCaretRect(),!0):!1}function nk(n){if(!n.selection.range.focus.isSimple())return!1;const e=Ky(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function ok(n){if(!n.selection.range.focus.isSimple())return!1;const e=Xy(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}const rk=M("find-block-position");function rD(n,t,e,o){g(rk,Lt(n,t),"is not a complex block");const r=zn(n,t).getChildContainers(n,t);g(rk,r.length>0,"complex block has not any child container");const i=Mo(n,e,o),s=i.left+i.width/2,l=i.top+i.height/2,a=l3(n,t,s,l);return k1(n,a,e,o)}function k1(n,t,e,o){if(Lt(n,t))return rD(n,t,e,o);const r=it(t);let i=Number.MAX_SAFE_INTEGER;const s=Mo(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 C=st(r,p,"normal"),v=Mo(n,t,C),B=nr(v,l,a);B<i&&(i=B,d=C)}return d}const ik=M("page-offset");function iD(n,t){const e=oy(n)*.9,r=t.getBoundingClientRect().bottom-e;if(r<TS(n))return n.getFirstBlock();const i=ae(t);if(!i)return n.getFirstBlock();let s=i;for(;s;){if(s.getBoundingClientRect().y<r)return s;s=ae(s)}return n.getFirstBlock()}function sD(n,t){const e=oy(n)*.9,o=t.getBoundingClientRect(),r=SS(n),i=o.top+e;if(i>r)return n.getLastBlock();const s=qt(t);if(!s)return n.getLastBlock();let l=s;for(;l;){if(l.getBoundingClientRect().bottom>i)return l;l=qt(l)}return n.getLastBlock()}function sk(n){const t=n.selection.range.focus;g(ik,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=iD(n,e);let r;return o===n.getFirstBlock()?r=st(o,0,"home"):r=k1(n,o,e,t),r}function lk(n){const t=n.selection.range.focus;g(ik,t.isSimple(),"invalid range type");const e=n.getBlockById(t.blockId),o=sD(n,e);let r;return o===n.getLastBlock()?r=st(o,ut(n,o),"end"):r=k1(n,o,e,t),r}function ck(n){if(!n.selection.range.focus.isSimple())return!1;const e=sk(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function ak(n){if(!n.selection.range.focus.isSimple())return!1;const e=lk(n);return e?(n.selection.setSelection(e),n.selection.updateLastCaretRect(),!0):!1}function uk(n){if(!n.selection.range.focus.isSimple())return!1;const e=sk(n);if(!e)return!1;const o=qh(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 dk(n){if(!n.selection.range.focus.isSimple())return!1;const e=lk(n);if(!e)return!1;const o=qh(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 Ja=M("select-all");function hk(n,t){const e=we(n),o=Ze(n);return t.start.offset===0&&t.start.blockId===it(e)&&t.end.offset===ut(t.getEditor(),o)&&t.end.blockId===it(o)}function lD(n,t){const e=t.getEditor(),o=zn(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 cD(n,t){g(Ja,t,"no parent block"),g(Ja,Lt(n,t),"not a complex block");const e=zn(n,t).getChildContainers(n,t),o=e[0],r=e[e.length-1];n.selection.setRange(We(n,{anchor:me(t,at(o)),focus:me(t,at(r))}))}function fk(n,t){const e=ot(t);w1(n,e)}function mk(n){const t=n.getFocusedBlock(),e=n.selection.range;if(e.start.isSimple()){if(e.start.blockId===e.end.blockId&&et(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 V(n.rootContainer,"select-all"),fk(n,we(n.rootContainer)),!1}return g(Ja,!e.isSimple(),"invalid range type"),lD(t,e)?(fk(n,t),!1):(g(Ja,t,"no parent block"),g(Ja,Lt(n,t),"not a complex block"),cD(n,t),!0)}function w1(n,t){const e=fe(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 aD(n){y1(n),n.focus()}const B1=M("selected-block-to-doc");function gk(n,t,e){!t.children||t.children.forEach(o=>{const r=n.getChildContainerData(o);r.forEach(i=>{gk(n,i,e)}),e.blocks[o]=mt.default(r)})}function Gh(n,t){const e=Yt(n,t.block);if(e.selectionToDoc)return e.selectionToDoc(n,t);const o=mt.default(Fi(n,t.block));if(et(n,t.block)){const i=t.start,s=t.end;if(g(B1,o.text,"no block text"),i.offset===s.offset)return{blocks:{root:[{...o,text:[]}]},meta:{},comments:{}};const{middle:l}=qe(o.text,i.offset,s.offset-i.offset);return{blocks:{root:[{...o,text:l}]},meta:{},comments:{}}}if(Se(t.block))return{blocks:{root:[o]},meta:{},comments:{}};g(B1,Lt(n,t.block),"not complex block"),g(B1,o.children,"no children");const r={blocks:{root:[o]},meta:{},comments:{}};return gk(n,o,r),r}function E1(n,t){const e=st(t,0,"normal"),o=st(t,ut(n,t),"end");return Gh(n,{block:t,start:e,end:o})}const uD=M("block-to-doc");function dD(n,t){g(uD,t.length>0,"invalid params, no blocks");const e=t.map(o=>E1(n,o));return js(e)}function Qh(n){const e=n.selection.range.getSelectedBlocks().map(o=>Gh(n,o));return js(e)}function pk(n,t){const e=n.getContainerById(t),i=fe(e).map(s=>({start:st(s,0,"home"),end:st(s,ut(n,s),"end"),block:s})).map(s=>Gh(n,s));return js(i)}const Zh=M("editor-selection");class hD{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(sy(e,i)){Zh.debug("adjust selection because remote deleted current block");const s=ly(t,e);this.setRange(s,{noScroll:!0})}});this.editor=t;const e=t.getFirstBlock(),o=it(e);this.caret=new ES(t);const r=st(o,0,"normal");this._range=We(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=We(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),Et(this.editor.rootContainer,"select-all")&&(!r.isSimple()||!RS(this.editor,r))&&rt(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(),xS(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(!Wr(t))return;const e=this.editor.getBlockById(t.blockId);this.lastCaretRect=Mo(this.editor,e,t)}getSuggestedCaretX(){var t;return(t=this.lastCaretRect)==null?void 0:t.x}scrollIntoView(){LS(this.editor)}verifyPos(t){const e=this.editor.getBlockById(t.blockId);if(t.isSimple())t.offset>=0&&t.offset<=ut(this.editor,e)||g(Zh,!1,"invalid block position, out of range");else{const o=t.childContainerId;!!this.editor.getContainerById(o)||g(Zh,!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&&Et(e,"focused")&&(rt(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=Qh(this.editor);return t==="text"?Hs(this.editor,e):t==="markdown"?uy(this.editor,e):ay(this.editor,e)}removeAllBlockFocusedClass(){this.editor.rootContainer.querySelectorAll('div[data-type="editor-block"].focused, div[data-type="editor-block"].child-focused').forEach(t=>{rt(t,"focused"),rt(t,"child-focused")})}setBlockFocused(t){if(Et(t,"focused"))return!1;V(t,"focused");let e=ot(t);for(;Lo(e);){const o=nt(e);g(Zh,o,"parent block not found"),V(o,"child-focused"),e=ot(o)}return!0}}function fD(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 mD(n){const t=n.selection.range.focus;if(!t.isSimple())return;const e=n.findBlockById(t.blockId);if(!e||!et(n,e))return;let o=p1(n,"select"),r=C1(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 gD{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=u3(this.editor,t.x,t.y);if(o){if(o instanceof sr)return;if(!this.autoScroll&&e.autoScroll){const s=o.getSelectedBlocks(),l=lo(s[0].block);this.autoScroll=new fh({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=wh(this.editor,t.x,t.y);if(!e)return;const o=qh(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){mD(this.editor)}handleTripleClick(t){fD(this.editor)}}function pD(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.undo(),!0)}function CD(n){return n.readonly||!n.isWritable()?!1:(n.undoManager.redo(),!0)}const Ck=M("delete-text");function bk(n,t,e,o){const r=o!=null?o:n.selection.range.start;r instanceof Ve||g(Ck,!1,`invalid insert pos type: ${typeof r}`);const{blockId:i}=r,s=n.getBlockById(i);g(Ck,et(n,s),"block is not a text kind block");let{offset:l}=r;if(t==="backward"){if(l-e<0)return 0;if(!ln(s,l-e)){const a=_i(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 Ak(n,t){if(n.getBlockData(t).quoted){const e={quoted:null};return n.updateBlockData(t,e),!0}return!1}const bD=M("handle-backspace");function x1(n,t){if(!ue(n,t))return;const e=ot(t);To(e)!==1&&n.deleteBlock(t)}function AD(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(et(n,o))if(e.offset===0){if(Ak(n,o))return;const r=ae(o);if(r){if(!n.isBlockWritable(r))return;if(et(n,r))n.mergeTextBlock(r,o,{focus:!0});else if(Lt(n,r)){x1(n,o);const i=Kl(n,r);i?n.selection.selectBlock(i,ut(n,i)):n.selection.selectBlock(r,0,ut(n,r))}else x1(n,o),g(bD,Se(r),"prev block is not embed block"),n.selection.selectBlock(r,1)}else{const i=ot(o);if(Lo(i)){const s=r3(n,i);if(s){if(!n.isBlockWritable(s))return;x1(n,o),n.selection.selectBlock(s,ut(n,s))}}}}else bk(n,"backward",1,null),n.selection.updateLastCaretRect();else{const r=vt(o),i=ot(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function vD(n,t){if(!n.selection.range.isCollapsed()){n.clearSelectedContents();return}const e=n.selection.range.start,o=n.getBlockById(e.blockId);if(et(n,o))if(e.offset===ut(n,o)){const r=qt(o);if(r){if(!n.isBlockWritable(r))return;et(n,r)?n.mergeTextBlock(o,r,{focus:!0}):ue(n,o)?n.deleteBlock(o,be(n,r,0)):n.deleteBlock(r)}}else bk(n,"forward",1,null);else{const r=vt(o),i=ot(o);n.insertTextBlock("",at(i),r),n.deleteBlock(o)}}function yD(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(Wr(e))return!0;const s=Jl(n,r,e,o),l=pn(n,r);return s.length===l.length}function kD(n,t){if(yD(n)){const s=n.getFocusedBlock(),l=vt(s),a=at(ot(s));n.insertTextBlock("",a,l+1);return}const e=n.getFocusedBlock(),{start:o,end:r}=n.selection.range,i=o.blockId===r.blockId&&Se(e);if(!n.selection.range.isCollapsed()&&!i&&n.clearSelectedContents(),et(n,e)){if(ue(n,e)&&Ak(n,e))return;const s=n.selection.range.start,l=n.breakTextBlock(e,s.offset,{copyBlockAttributes:!0});s.offset!==0?n.selection.selectBlock(l,0):n.selection.scrollIntoView()}else{const s=n.insertTextBlock();n.selection.selectBlock(s,0)}}function wD(n,t){const e=n.selection.range.getSelectedBlocks()[0],{block:o}=e;if(!et(n,o))return!1;const r=e.end;return n.insertBoxToBlock(o,r.offset,{type:"br",id:tt(),box:!0,created:Date.now()}),!0}const BD=M("input-handler-actions");function ED(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(kD(n),!0))}function xD(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(vD(n),!0))}function ID(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(AD(n),!0))}function TD(n,t){return n.readonly||!n.isWritable()?!1:n.undoManager.runInGroup(()=>(wD(n),!0))}function SD(n){return n.readonly||!n.isWritable()||!window.isSecureContext?!1:(navigator.clipboard.readText().then(t=>{n.input.handlePasteText(t,{toPlainText:!0})}).catch(t=>{BD.error(t)}),!0)}const Yh={ArrowDown:$y,ArrowUp:Ny,ArrowLeft:Fy,ArrowRight:Py,"Shift+ArrowDown":Hy,"Shift+ArrowUp":zy,"Shift+ArrowLeft":jy,"Shift+ArrowRight":Uy,"CtrlOrCmd+ArrowLeft":Wy,"CtrlOrCmd+ArrowRight":qy,"CtrlOrCmd+Shift+ArrowLeft":Gy,"CtrlOrCmd+Shift+ArrowRight":Qy,"CtrlOrCmd+ArrowUp":Zy,"CtrlOrCmd+ArrowDown":v1,"CtrlOrCmd+Shift+ArrowUp":Yy,"CtrlOrCmd+Shift+ArrowDown":y1,"CtrlOrCmd+A":mk,Home:nk,End:ok,"Shift+Home":tk,"Shift+End":ek,PageUp:ck,PageDown:ak,"Shift+PageUp":uk,"Shift+PageDown":dk,"CtrlOrCmd+Z":pD,"CtrlOrCmd+Shift+Z":CD,Enter:ED,Delete:xD,Backspace:ID,"Shift+Enter":TD,"CtrlOrCmd+Shift+V":SD};function vk(n,t){return n.shortcuts.handleKeyboardEvents(n,t)!==void 0}function yk(n,t,e){if(t.type==="embed"){const i=t.embedData,s=i.src;if(s&&typeof s=="string"){const l=e.get(s);if(l)i.src=l;else{let a="";s.split("|").forEach(h=>{const p=e.get(h);p&&(a+=a?`|${p}`:`${p}`)}),a&&(i.src=a)}}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=>{yk(n,l,e)})})}function kk(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):yk(t,r,e)})}async function DD(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 MD(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 LD(n,t){const o=t.meta.resources;if(!o||Object.keys(o).length===0)return;let r=new Map;if(MD(n,t)){const s=Array.from(Object.keys(o));r=await DD(n,s),kk(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&&kk(n,t,i)}async function RD(n,t,e){await LD(n,t),n.undoManager.runInGroup(()=>{const{start:o,end:r}=n.selection.range,i=n.getBlockById(o.blockId);if(o.blockId===r.blockId&&Se(i)){const s=ot(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}=ec(n);n.insertDoc(s,l,t,e)}})}const OD=["text/x-ones-editor-doc","image/*","text/office-html","text/html","text/plain","text/markdown","*"];function _D(n){let t;for(const e of OD)if(t=n[e],t)break;return t||null}function wk(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=>{wk(n,l,e)})})}function FD(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)}):wk(t,r,e)}),Array.from(e)}function Jh(n,t){return ge.isFirefox?`<!doctype html><html><head><meta charset="utf8" /></head><body><canvas data-editor-doc="${Li(JSON.stringify(t))}" id="ones-editor-doc">${n}</body></html>`:`<!doctype html><html><head><meta charset="utf8" />${`<meta charset="utf-8"><ones-editor-doc data-source="ones-editor-doc::${Li(JSON.stringify(t))}::ones-editor-doc" />`}</head><body>${n}</body></html>`}function Kh(n,t){var i,s,l;const e=(l=(s=(i=n.doc).getServerMeta)==null?void 0:s.call(i))!=null?l:{},o=FD(n,t),r={};o.forEach(a=>{const d=n.doc.buildResourceUrl(a,{withToken:!0});r[a]=d}),t.meta={...e,resources:r}}function PD(n,t,e){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;let o=Qh(n);const r=e==null?void 0:e(n,t,o);if(r===!0)return;typeof r=="object"&&r!==null&&(o=r),Kh(n,o);const i=$h(n,o),s=Hs(n,o),l=Jh(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 Xh(n,t){if(!window.isSecureContext)throw new Error("Can't copy block in insecure context.");const e=E1(n,t);Kh(n,e);const o=$h(n,e),r=Hs(n,e),i=Jh(o,e);return lp([{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);if(r){const i=[];this.pasteDocs(r,null,i)}});this.editor=t}onInsertText(t,e){if(!et(this.editor,this.editor.getFocusedBlock()))return;const{containerId:o,blockIndex:r,offset:i}=ec(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){if(!et(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText("",!1);const{containerId:e,blockIndex:o,offset:r}=ec(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){if(!et(this.editor,this.editor.getFocusedBlock()))return;this.editor.updateCompositionText(e,o),this.editor.selection.caret.update();const{containerId:r,blockIndex:i,offset:s}=ec(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){PD(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;Se(o)&&this.editor.deleteBlock(o)}else a1(this.editor)}onPaste(t){if(t.preventDefault(),t.stopPropagation(),!t.clipboardData)return;const e=this.editor.dataConverter.fromData(this.editor,t.clipboardData),o=Array.from(t.clipboardData.files);e.then(async r=>{r&&this.pasteDocs(r,t,o)})}onFocus(){V(this.editor.rootElement,"active")}onBlur(){rt(this.editor.rootElement,"active")}addHandler(t){this.handlers.push(t),this.handlers=this.handlers.sort((e,o)=>{var s,l;const r=(s=e.order)!=null?s:1;return((l=o.order)!=null?l:1)-r})}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){r1(this.editor,i)}defaultHandleKeydown(t,e){return vk(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 RD(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,o){for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleBeforePaste&&await s.handleBeforePaste(this.editor,e,t,o))return}const r=_D(t);if(!!r){await this.pasteDoc(r);for(let i=0;i<this.handlers.length;i++){const s=this.handlers[i];if(s.handleAfterPaste&&await s.handleAfterPaste(this.editor,e,t))return}}}destroy(){this.handlers.forEach(t=>{var e;(e=t.destroy)==null||e.call(t,this.editor)}),this.handlers=[]}}function $D(n,t,e){const o=Hr(t,e);return o.remove(),o}M("copy-dom-attributes");const Bk=["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 HD(n,t){for(let l=0;l<Bk.length;l++){const a=Bk[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 Ek(n){const t=Array.from(n.childNodes).filter(e=>!v5(e));return t.forEach(e=>{e.remove()}),t}function xk(n,t,e){var d;const o=n.getContainerById(t),r=Hr(o,e),i=Ri(r),s=n.doc.getBlockData(t,e),l=Yt(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=Ek(h);Ek(r),p.forEach(v=>{r.appendChild(v)});const C=ph(h);if(C){const v=ph(r);v&&v.remove(),r.appendChild(C)}HD(h,r)}N5(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 jD=M("transform-selection");function Ik(n,t,e,o){const{range:r}=n.selection,{anchor:i,focus:s}=r;if(i.blockId!==t&&s.blockId!==t)return r;g(jD,i.isSimple()&&s.isSimple(),"invalid text pos type");let l=i;if(i.blockId===t){const d=cn.transformCursor(i.offset,e,o);l=st(t,d,"normal")}let a=s;if(s.blockId===t){const d=cn.transformCursor(s.offset,e,o);a=st(t,d,"normal")}return We(n,{anchor:l,focus:a})}const UD=M("handle-block-text-changed");function zD(n,t,e,o,r){const i=n.getContainerById(t),s=Hr(i,e),l=n.doc.getBlockData(t,e);if(g(UD,l.text,"no block text"),L5(n,s).setBlockText(n,s,l.text),!r){const a=Ik(n,l.id,o,r);n.selection.setRange(a,{noScroll:!0})}}function VD(n,t){const e=mt.default(n);return t.delete.forEach(r=>{delete e[r]}),{...e,...t.insert}}function Tk(n,t,e,o){const r=Yt(n,t);r.handleDeleteBlock&&r.handleDeleteBlock(n,t,e,o),n.emit("blockDeleted",n,t,e,o)}function WD(n,t,e,o){const r=n.getBlockByIndex(t,e);r.querySelectorAll('[data-type="editor-block"]').forEach(i=>{Tk(n,i,o,{child:!0})}),Tk(n,r,o,{child:!1})}const _o=M("editor-doc");class qD extends Ba{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)}findContainerBlocks(e){return this.externalDoc.findContainerBlocks(e)}getBlockData(e,o){return this.externalDoc.getBlockData(e,o)}verifyBlockWritable(e,o){const r=this.editor.getBlockByIndex(e,o);g(_o,this.editor.isBlockWritable(r),`block is not writable, ${e}, ${o}`)}localUpdateBlockText(e,o,r,i){g(_o,!this.editor.readonly,"editor is readonly"),this.verifyBlockWritable(e,o);const s=this.getBlockData(e,o),l=s.text;g(_o,l,`no text, ${e}, ${o}`);const a=Ik(this.editor,s.id,r,!0),d=cn.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(_o,!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(C=>C!=="comments"),p=Object.keys(r.insert).filter(C=>C!=="comments");(h.length>0||p.length>0)&&g(_o,!1,`block is not writable, comment supported only, ${JSON.stringify(r)}}`)}const l=mt.default(this.getBlockData(e,o)),a=mt.default(VD(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(Oi(this.editor,i)),d}localInsertBlock(e,o,r,i,s){g(_o,!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 s!=null&&s.noFocus||this.editor.selection.setRange(Oi(this.editor,i),s),l}localDeleteBlock(e,o,r){g(_o,!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(Oi(this.editor,r)),s}localDeleteChildContainers(e){return g(_o,!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)}localInsertChildContainers(e){g(_o,!this.editor.readonly,"editor is readonly");const o=mt.default(e);o.forEach(r=>{this.localEvents.forEach(i=>i.onBeforeInsertChildContainer(r.containerId,r.blocks))}),this.externalDoc.localInsertChildContainers(o)}onRequestReload(e){_o.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)}),zD(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)}),xk(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);L8(this.editor,s,o,r),this.editor.emit("docChanged",this.editor,i)}onDeleteBlock(e,o,r){WD(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);$D(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){_o.log("reset doc"),this.externalDoc=e,this.externalDoc.registerCallback(this),this.editor.reload()}}function Sk(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 tf=M("undo-action");class sc{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(tf,t,"no other action"),!1}combine(t){g(tf,!1,"no other")}setAfterRange(t){this.afterRange&&tf.warn("after range has already set"),this.afterRange=t}findContainerById(t,e){return!!t.doc.findContainerBlocks(e)}findBlockById(t,e){const o=t.doc.findContainerBlocks(this.containerId);return o?o.some(r=>r.id===e):!1}checkBlockData(t,e){if(Array.isArray(e.children)){const o=t.doc.toJSON();for(let r=0;r<e.children.length;r++){const i=e.children[r];if(!o.blocks[i])return tf.warn(`container (${i}) not found, deleted by others?`),!1}}return!0}}const lc=M("block-action");class Dk extends sc{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(!this.findContainerById(e,this.containerId))return lc.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockData.id))return lc.warn(`block (${this.blockData.id}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const i=e.getBlockById(this.blockData.id);if(!i)return!1;try{g(lc,this.blockIndex===vt(i),"invalid block index"),Uh(e,i,Oi(e,o))}catch(s){lc.warn(s.message),e.selection.selectBlock(i,0)}return!0}insertBlock(e,o){if(!this.findContainerById(e,this.containerId))return lc.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.checkBlockData(e,this.blockData))return!1;try{oc(e,this.containerId,this.blockIndex,mt.default(this.blockData),o)}catch(r){lc.warn(r.message);const i=e.doc.getContainerBlocks(this.containerId),s=Math.min(i.length-1,this.blockIndex),l=e.getBlockByIndex(this.containerId,s);e.selection.selectBlock(l,0)}return!0}}M("insert-block-action");class GD extends Dk{undo(t){return this.deleteBlock(t,this.beforeRange)}redo(t){return this.insertBlock(t,this.afterRange)}}class QD extends Dk{undo(t){return this.insertBlock(t,this.beforeRange)}redo(t){return this.deleteBlock(t,this.afterRange)}}class ZD extends sc{constructor(e){super(e,at(e.rootContainer),e.selection.range.toDocRange());m(this,"actions",[])}addAction(e){Sk(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 sc&&(o.afterRange||o.setAfterRange(e))}}const $i=M("update-block-data-action");class ef extends sc{constructor(e,o,r,i,s,l){super(e,o,l);m(this,"beforeBlockData");m(this,"afterBlockData");m(this,"blockId");this.blockId=r,g($i,this.blockId===i.id,"invalid block id"),g($i,this.blockId===s.id,"invalid block id"),this.beforeBlockData=mt.default(i),this.afterBlockData=mt.default(s),g($i,this.beforeBlockData.type===this.afterBlockData.type,"invalid block type")}undo(e){if(!e.findBlockById(this.blockId))return $i.warn(`block (${this.blockId}) not found, deleted by others?`),!1;const o=e.getBlockById(this.blockId);if(!o||!this.checkBlockData(e,this.beforeBlockData))return!1;const r=e.getContainerById(this.containerId);return g($i,r,"no container"),Wh(e,o,ef.toAttributes(this.beforeBlockData),this.beforeRange),!0}redo(e){if(!e.findBlockById(this.blockId))return $i.warn(`block (${this.blockId}) not found, deleted by others?`),!1;g($i,e,"no editor");const o=e.getBlockById(this.blockId);if(!o||!this.checkBlockData(e,this.beforeBlockData))return!1;const r=e.getContainerById(this.containerId);return g($i,r,"no container"),Wh(e,o,ef.toAttributes(this.afterBlockData),this.afterRange),!0}static toAttributes(e){const o=mt.default(e);return delete o.id,delete o.type,o}}const Us=M("update-block-text-action");class Ka extends sc{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=Ka.calType(i,s)}static calType(e,o){g(Us,e,"no old data"),g(Us,o,"no new data");const i=cn.diff(e,o),s=new Set;let l=!1;const a=h=>Yv(h)?`cjk_${h}`:Qv(h)?"number":ch(h)?"space":Zv(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(!this.findContainerById(e,this.containerId))return Us.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return Us.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Vh(e,r,this.beforeRichTextData),!0):!1}redo(e){if(!this.findContainerById(e,this.containerId))return Us.warn(`container (${this.containerId}) not found, deleted by others?`),!1;if(!this.findBlockById(e,this.blockId))return Us.warn(`block (${this.blockId}) not found, deleted by others?`),!1;if(!e.getContainerById(this.containerId))return!1;const r=e.getBlockById(this.blockId);return r?(Vh(e,r,this.afterRichTextData),!0):!1}combinable(e){if(!(e instanceof Ka)||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(Us,e instanceof Ka,"invalid action type");const o=e;this.afterRichTextData=o.afterRichTextData,this.afterRange=e.afterRange}}const Mk=M("child-container-action");class Lk extends sc{constructor(t,e,o){super(t,e,t.selection.range.toDocRange()),this.blocks=o}deleteChildContainer(t){return this.findContainerById(t,this.containerId)?(t.doc.localDeleteChildContainers([this.containerId]),!0):(Mk.warn(`container (${this.containerId}) not found, deleted by others?`),!1)}insertChildContainer(t){return this.findContainerById(t,this.containerId)?(Mk.warn(`container (${this.containerId}) already exists`),!1):(t.doc.localInsertChildContainers([{containerId:this.containerId,blocks:mt.default(this.blocks)}]),!0)}}class YD extends Lk{undo(t){return this.deleteChildContainer(t)}redo(t){return this.insertChildContainer(t)}}class JD extends Lk{undo(t){return this.insertChildContainer(t)}redo(t){return this.deleteChildContainer(t)}}const Fo=M("undo");class KD{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):(Sk(this.actions,t),setTimeout(()=>{this.editor.input.handleChanged(t)}))}beginGroup(){this.groupCounter===0?(g(Fo,!this.currentGroup,"current group already exists"),this.currentGroup=new ZD(this.editor),this.groupCounter=1):(g(Fo,this.currentGroup,"current group not exists"),this.groupCounter+=1)}endGroup(){g(Fo,this.currentGroup,"current group not exists"),g(Fo,this.groupCounter>0,"group counter === 0"),this.groupCounter-=1,this.groupCounter===0&&(this.currentGroup.actions.length===0?Fo.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 Fo.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(Oi(this.editor,t.beforeRange))}catch(e){Fo.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(Oi(this.editor,e)):Fo.warn("no after range")}catch(e){Fo.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(),cn.diff(o,r).length!==0&&this.addAction(new Ka(this.editor,t,e,o,r,i)))}onBeforeUpdateBlockData(t,e,o,r,i){if(this.undoRedoing)return;this.prepareSaveUndoState();const s=new ef(this.editor,t,e,o,r,i);this.addAction(s)}onBeforeInsertBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),g(Fo,e>=0,"invalid block index"),g(Fo,o,"no block data"),this.addAction(new GD(this.editor,t,e,o,r)))}onBeforeDeleteBlock(t,e,o,r){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new QD(this.editor,t,e,o,r)))}onBeforeInsertChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new YD(this.editor,t,e)))}onBeforeDeleteChildContainer(t,e){this.undoRedoing||(this.prepareSaveUndoState(),this.addAction(new JD(this.editor,t,e)))}}class XD{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 tM{constructor(){m(this,"converters",[]);m(this,"converterTypes",["text/plain","text/markdown","text/html","text/x-ones-editor-doc"]);this.addConverter(new XD)}prepareData(t){const e=new DataTransfer;for(let o=0;o<this.converterTypes.length;o++)e.setData(this.converterTypes[o],t.getData(this.converterTypes[o]));return e}async fromData(t,e,o){let r={};const i=this.prepareData(e);for(const s of this.converters){const l=await s.fromData(t,i,o);l&&(r={...r,...l})}return r}addConverter(t){this.converters.push(t)}}class eM{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 Ae extends ke.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=nt(o);if((!r||!Xt(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&&Xt(this.editor.rootContainer,this.hoveringBlock)?this.hoveringBlock:null;s&&rt(s,"hover"),e&&V(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 Ae(e))}getParentTextContentChild(e,o){if(!et(this.editor,e))return null;const r=Mt(e);return o.parentElement===r?o:mp(o)}}const Rk="style-color-",Ok="style-bg-color-";class nM{renderText(t,e,o){const r=[],i={},s={};return Object.entries(o).forEach(([l,a])=>{a===!0?l.startsWith(Rk)?i["data-style-color"]=l.substring(Rk.length):l.startsWith(Ok)?i["data-style-bg-color"]=l.substring(Ok.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"),Ae.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&&V(o,"focused"),Ae.get(t).hoveringBlockId()===r.id&&V(o,"hover")}}function oM(n){n.editorBlocks.registerBlockClass(Sn),n.editorBlocks.registerBlockClass(o3),n.editorBoxes.registerBoxClass(q3),n.editorBoxes.registerBoxClass(G3),n.editorBoxes.registerBoxClass(Y3),n.editorBoxes.registerBoxClass(J3),n.editorInsertions.registerInsertionClass(K3),n.editorBlockRenders.registerRender(new nM)}function rM(n,t){oM(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 nf=M("range-commands");function _k(n,t){n.forEach(e=>{e.source=t,e.children&&_k(e.children,t)})}function Fk(n,t,e){const o=it(t);g(nf,o===e.start.blockId,"invalid start range"),g(nf,o===e.end.blockId,"invalid end range");const r=n.editorCommandProviders.getCommandProviders();let i=[];if(r.forEach(s=>{const l=s.getAvailableCommands(n,t,e);_k(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)){if(!Yl(e.start))return i;g(nf,!e.start.isSimple(),"invalid start pos"),g(nf,!e.end.isSimple(),"invalid end pos");const s=e.start.childContainerId,l=ir(n,s),d=fe(l)[0];if(d){const h=ut(n,d),p=We(n,{anchor:st(d,0,"home"),focus:st(d,h,"end")}),C=Fk(n,d,p);i.push(...C)}}return i}function Pk(n){const t=n.getEditor(),e=n.getSelectedBlocks(),o=[],r=n.isReverse()?e[0]:e[e.length-1],i=We(t,{anchor:r.start,focus:r.end});return Fk(t,r.block,i).forEach(l=>{o.push(l)}),o}function Nk(n,t,e,o,r,i){var h;const s=n.editorCommandProviders.getCommandProviders();for(let p=0;p<s.length;p++){const C=s[p];if(C.beforeExecuteCommand&&C.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)&&Jl(n,t,e.start,e.end).forEach(C=>{fe(C).forEach(B=>{const x=ut(n,B),I=We(n,{anchor:st(B,0,"home"),focus:st(B,x,"end")});Nk(n,B,I,o,r,i)&&(d=!0)})}),s.forEach(p=>{p.afterExecuteCommand&&p.afterExecuteCommand(n,t,e,o,r,i)}),d}function $k(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=We(o,{anchor:l.start,focus:l.end});Nk(o,l.block,a,t,e,r)}),o.focus()),r}const iM=M("command-providers");class Hk{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(iM,e,`no command provider, id=${t}`),e}getCommands(t){return Pk(t)}executeCommand(t,e,o){return this.editor.undoManager.runInGroup(()=>$k(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 sM(n,t){const e=ot(t),o=at(e),r=vt(t);xk(n,o,r)}const lM=M("table-scroll");class jk{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 cM{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)){lM.warn(`event has already registered: ${e}`);return}i.push(new jk(this.editor,t,e,o,r))}else{const s=new jk(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 Uk=M("update-block-text");function aM(n,t){const e=n.getBoxById(t.id),o=nt(e);g(Uk,o,"no parent block"),g(Uk,et(n,o),"not a text block");const r=n.getBlockText(o),i=P3(r,"id",t.id,t);yy(n,o,i)}function uM(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 dM(n){if(n.readonly)return!1;const t=lr(n);return!!n.isBlockWritable(t.map(e=>e.block))}class hM{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 fM{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(or(e,s)){const a=l(t,e);if(a!==void 0)return a}}}}const Yr=M("editor");class mM extends ke.TypedEmitter{constructor(e,o,r){var i,s,l,a,d,h,p,C;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 fM);m(this,"dataConverter",new tM);m(this,"editorBlocks",new X5(this));m(this,"editorBoxes",new Z3(this));m(this,"editorInsertions",new ty(this));m(this,"editorEmbeds",new e3(this));m(this,"editorDecorators",new ey(this));m(this,"editorCommandProviders",new Hk(this));m(this,"editorBlockRenders",new eM(this));m(this,"blockHooks",[]);m(this,"domEvents",new cM(this));m(this,"customs",new Map);m(this,"options");m(this,"inputHandlers",new ND(this));m(this,"settingsProvider");m(this,"_readonly",!1);m(this,"getColor",e=>{const o=this.options.colors;return o.length===0?"#FF1A75":o[e%o.length]});Yr.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,enableComments:(a=r==null?void 0:r.enableComments)!=null?a:!0},this.settingsProvider=(d=r==null?void 0:r.settingsProvider)!=null?d:new hM(this),rM(this,r==null?void 0:r.components),this.blockHooks.push(...(p=(h=r==null?void 0:r.components)==null?void 0:h.blockHooks)!=null?p:[]),this.id=(C=r==null?void 0:r.id)!=null?C:tt(),this.clientId=tt(),this.undoManager=new KD(this),this.doc=new qD(this,o,this.undoManager),this.parent=e,this.rootElement=k("div",["editor-root"],this.parent),this.rootElement.setAttribute("data-editor-client-id",this.clientId),this.contentElement=k("div",["editor-content"],this.rootElement),this.rootContainerObject=Y5(this),this.rootContainer=this.rootContainerObject.rootContainer,this.input=new BS(this,this.inputHandlers),this.selection=new hD(this),this.selectionHandler=new gD(this),r!=null&&r.shortcuts&&this.shortcuts.shortcuts.push(...r.shortcuts),ge.isMobile&&V(this.rootElement,"mobile"),ge.isSafari&&V(this.rootElement,"safari"),this._readonly&&V(this.rootElement,"readonly"),this.emit("load",this,!1)}get readonly(){return this._readonly}set readonly(e){this._readonly=e,e?V(this.rootElement,"readonly"):rt(this.rootElement,"readonly"),this.emit("readonlyChanged",this)}get scrollContainer(){return this.options.scrollContainer?this.options.scrollContainer:lo(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(Yr,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(){Yr.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){u1(this,e,o)}isWritable(){return dM(this)}isBlockWritable(e){return uM(this,e)}getChildContainerData(e){const o=this.doc.getContainerBlocks(e);return(!o||!Array.isArray(o))&&(g(Yr,o,`no child container data: ${e}, ${JSON.stringify(this.doc)}`),g(Yr,Array.isArray(o),`container data is not an array: ${JSON.stringify(o)}`)),o}createChildContainer(e,o,r){return J5(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(Yr,Es(o),"not an valid block element"),o!=null?o:null}findBoxById(e){const o=this.rootContainer.querySelector(`#${e}`);return o&&g(Yr,fp(o),"not an valid box element"),o!=null?o:null}getBlockById(e){const o=this.findBlockById(e);return g(Yr,o,`no block, id=${e}`),o}getBoxById(e){const o=this.findBoxById(e);return g(Yr,o,`no box, id=${e}`),o}getBlockByIndex(e,o){const r=this.getContainerById(e);return Hr(r,o)}getBlockIndex(e){if(typeof e=="string"){const o=this.getBlockById(e);return vt(o)}return vt(e)}getContainerById(e){return ir(this,e)}getParentContainer(e){return ot(e)}reloadBlock(e){sM(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 oc(this,e,o,r,i!=null?i:a,s)}insertEmbed(e,o,r,i,s){const l={id:tt(),type:"embed",embedType:r,embedData:i};return this.insertBlock(e,o,l,s)}deleteBlock(e,o){l1(this,e,o)}mergeTextBlock(e,o){return by(this,e,o)}breakTextBlock(e,o,r){return rc(this,e,o,r).newBlock}getTextPosition(){return ec(this)}getBlockString(e,o){const r=this.getBlockText(e);return se(r,o)}getBlockData(e){return Fi(this,e)}getBoxData(e){return V3(this,e)}getBlockText(e){return Cn(this,e)}setBlockText(e,o){yy(this,e,o)}deleteTextFromBlock(e,o,r,i){return i1(this,e,o,r,i)}insertTextToBlock(e,o,r,i){return dy(this,e,o,r,i)}insertBoxToBlock(e,o,r){return hy(this,e,o,r)}pasteDoc(e){return this.inputHandlers.pasteDoc(e)}insertDoc(e,o,r,i){By(this,e,o,r,i)}insertDocAt(e,o,r,i){return f1(this,e,o,r,i)}deleteChildContainers(e){Cy(this,e)}replaceBlockText(e,o){return Vh(this,e,o)}updateBlockData(e,o,r){const i={...this.getBlockData(e),...o},{id:s,type:l,...a}=i;return Wh(this,e,a,(r!=null?r:this.selection.range).toDocRange())}updateEmbedData(e,o,r){return ky(this,e,o,r)}updateBoxData(e){aM(this,e)}getSelectedText(){const e=Qh(this);return Hs(this,e)}clearSelectedContents(){a1(this)}insertTextBlock(e,o,r,i){const s=ur(e!=null?e:"");return py(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){my(this);return}o?(this.compositingText="",Ta()||r1(this,e)):(this.compositingText=e,fy(this))}}function Xa(n,t,e){return new mM(n,t,e)}function gM(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=Vg.default(s.states,r.states)}},e=[];return n.forEach(o=>{o.forEach(r=>{t(e,r)})}),e}const pM=["#FBBFBD","#FFDDB6","#FFF897","#C5F0C1","#CEDDFE","#DCC9FC","#E5E6E8","#F76964","#FFA53D","#FFE928","#63D156","#A0BBFE","#C4A5FB","#BBBFC3"];class of extends ke.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:pM}setCursor(e){this.addUser(e.user);const o=this.cursors.get(e.user.userId);if(o&&ka.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.emit("change",Array.from(this.users.values()));const o=this.cursors.get(e);if(o){const r=new Set(new Set([o==null?void 0:o.range.anchor.blockId,o==null?void 0:o.range.focus.blockId]));this.cursors.delete(e),this.emit("remote-carets-change",[...r])}}updateUsers(e){this.users.forEach(o=>{e.find(r=>r.userId===o.userId)||this.removeUser(o.userId)}),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&&Rh(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(Rh(l.range)){const{anchor:a,focus:d}=l.range;a.blockId===e.id&&(a.offset=cn.transformCursor(a.offset,o,r)),d.blockId===e.id&&(d.offset=cn.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=M("local-doc");class I1 extends Ba{constructor(e,o){super();m(this,"doc");m(this,"serviceUrl");e?this.doc=e:this.doc={meta:{},comments:{},blocks:{root:[ur("")]}},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]}findContainerBlocks(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=cn.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}localInsertChildContainers(e){e.forEach(({containerId:o,blocks:r})=>{this.doc.blocks[o]=r,g(Xe,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onInsertChildContainer)==null?void 0:s.call(i,o,r,!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 of}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 CM{constructor(t){this.cleanup=t}destroy(){var t;(t=this.cleanup)==null||t.call(this)}}function T1(n,t,e){n.addCustom(t,()=>{var i;const o=(i=e())!=null?i:void 0;return new CM(o)})}const zk=M("find-block");function Vk(n,t){const e=Ts(t);if(!e){if(co(t))return null;const o=xs(t);return g(zk,o,"no parent block"),Vk(n,o)}return Lt(n,e)?Kl(n,e,{visibleOnly:!0}):e}function Wk(n,t){const e=Ss(t);if(!e){if(co(t))return null;const o=xs(t);return g(zk,o,"no parent block"),Wk(n,o)}return Lt(n,e)?Tp(n,e,{visibleOnly:!0}):e}const bM=M("remote-cursor");class AM{constructor(){m(this,"remoteUsers",new of)}onCustomMessage(t){const e=t;if(e.type==="onlineUsers"){const o=e;this.handleUpdateUsers(o.users)}else e.type==="caret"?this.handleUpdateCaret(e):bM.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 vM(n){const{blocks:t,meta:e,comments:o,...r}=n;return{rootBlocks:t,meta:e,comments:o,childBlocks:r}}function yM(n){const{blocks:t,meta:e,comments:o}=n,{root:r,...i}=t;return{blocks:r,meta:e,comments:o,...i}}function tu(n){const{childBlocks:t,meta:e,comments:o,rootBlocks:r}=vM(mt.default(n));return{blocks:{root:r,...t},meta:e,comments:o}}function Jr(n){return n==="root"?"blocks":n}function cc(n){return n==="blocks"?"root":n}const kM={type:{name:"rich-text",uri:"http://sharejs.org/types/rich-text/v1",create(n){return new rn.default(n)},apply(n,t){const e=new rn.default(n),o=new rn.default(t);return e.compose(o).ops},compose(n,t){const e=new rn.default(n),o=new rn.default(t);return e.compose(o).ops},diff(n,t){const e=new rn.default(n),o=new rn.default(t);return e.diff(o).ops},transform(n,t,e){const o=new rn.default(n);return new rn.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 rn.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 hr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Hi={},S1=yv.default.EventEmitter;Hi.EventEmitter=S1,Hi.mixin=wM;function wM(n){for(var t in S1.prototype)n.prototype[t]=S1.prototype[t]}var qk=["info","warn","error"];function Gk(){var n={};qk.forEach(function(t){n[t]=console[t].bind(console)}),this.setMethods(n)}var BM=Gk;Gk.prototype.setMethods=function(n){n=n||{};var t=this;qk.forEach(function(e){typeof n[e]=="function"&&(t[e]=n[e])})};var EM=BM,xM=new EM,Qk=xM;function zs(n,t){this.code=n,this.message=t||"",Error.captureStackTrace?Error.captureStackTrace(this,zs):this.stack=new Error().stack}zs.prototype=Object.create(Error.prototype),zs.prototype.constructor=zs,zs.prototype.name="ShareDBError",zs.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 rf=zs,eu={},Zk=IM;function IM(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=[],C=0;C<s.length;){var v=[];if(r(s[C],h,p,v),C++,v.length===1)h=v[0];else if(v.length===0){for(var B=C;B<s.length;B++)o(p,s[B]);h=null;break}else{for(var x=i(s.slice(C),v),I=0;I<x[0].length;I++)o(p,x[0][I]);for(var _=0;_<x[1].length;_++)o(a,x[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 Yk={exports:{}},ji=Yk.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||""}},D1=function(n,t,e){return n.slice(0,t)+e+n.slice(t)},M1=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")},sf=function(n){for(var t=0;t<n.length;t++)M1(n[t])};ji.apply=function(n,t){var e;sf(t);for(var o=0;o<t.length;o++){var r=t[o];if(r.i!=null)n=D1(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 Kr=ji._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:D1(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:D1(t.d,e.p-t.p,e.d),p:t.p}:n.push(t)}};ji.compose=function(n,t){sf(n),sf(t);for(var e=n.slice(),o=0;o<t.length;o++)Kr(e,t[o]);return e},ji.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),Kr(t,o)}return t};var L1=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};ji.transformCursor=function(n,t,e){for(var o=e==="right",r=0;r<t.length;r++)n=L1(n,t[r],o);return n};var TM=ji._tc=function(n,t,e,o){if(M1(t),M1(e),t.i!=null)Kr(n,{i:t.i,p:L1(t.p,e,o==="right")});else if(e.i!=null){var r=t.d;t.p<e.p&&(Kr(n,{d:r.slice(0,e.p-t.p),p:t.p}),r=r.slice(e.p-t.p)),r!==""&&Kr(n,{d:r,p:t.p+e.i.length})}else if(t.p>=e.p+e.d.length)Kr(n,{d:t.d,p:t.p-e.d.length});else if(t.p+t.d.length<=e.p)Kr(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=L1(i.p,e),Kr(n,i))}return n},SM=function(n){return n.i!=null?{d:n.i,p:n.p}:{i:n.d,p:n.p}};ji.invert=function(n){n=n.slice().reverse();for(var t=0;t<n.length;t++)n[t]=SM(n[t]);return n},Zk(ji,TM,sf,Kr);var lf=function(n){return Object.prototype.toString.call(n)=="[object Array]"},DM=function(n){return!!n&&n.constructor===Object},Po=function(n){return JSON.parse(JSON.stringify(n))},It={name:"json0",uri:"http://sharejs.org/types/JSONv0"},Xr={};It.registerSubtype=function(n){Xr[n.name]=n},It.create=function(n){return n===void 0?null:Po(n)},It.invertComponent=function(n){var t={p:n.p};return n.t&&Xr[n.t]&&(t.t=n.t,t.o=Xr[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(!lf(n[t].p))throw new Error("Missing path")},It.checkList=function(n){if(!lf(n))throw new Error("Referenced element not a list")},It.checkObj=function(n){if(!DM(n))throw new Error("Referenced element not an object (it was "+JSON.stringify(n)+")")};function nu(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 ou(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=Po(t);for(var e={data:n},o=0;o<t.length;o++){var r=t[o];(r.si!=null||r.sd!=null)&&nu(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&&Xr[r.t])s[l]=Xr[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 MM=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=Po(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)&&(nu(t),nu(e)),MM(t.p,e.p))if(t.t&&e.t&&t.t===e.t&&Xr[t.t]){if(e.o=Xr[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(),ou(t),n.push(t);ou(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)&&(ou(t),ou(e)),n.push(t)},It.compose=function(n,t){It.checkValidOp(n),It.checkValidOp(t);for(var e=Po(n),o=0;o<t.length;o++)It.append(e,t[o]);return e},It.normalize=function(n){var t=[];n=lf(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=Po(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=Po(e);a.p=a.p.slice(s),t.ld=It.apply(Po(t.ld),[a])}else if(t.od!==void 0){var a=Po(e);a.p=a.p.slice(s),t.od=It.apply(Po(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)&&(nu(t),a=Po(e),nu(a)),a.t&&Xr[a.t]){if(t.t&&t.t===a.t){var h=Xr[t.t].transform(t.o,a.o,o);if(t.si!=null||t.sd!=null)for(var p=t.p,C=0;C<h.length;C++)t.o=[h[C]],t.p=p.slice(),ou(t),It.append(n,t);else(!lf(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=Po(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,x=e.p[r],I=e.lm;if(x!==I)if(v===x)if(o==="left")t.p[r]=I,v===B&&(t.lm=I);else return n;else v>x&&t.p[r]--,v>I?t.p[r]++:v===I&&x>I&&(t.p[r]++,v===B&&t.lm++),(B>x||B===x&&B>v)&&t.lm--,B>I?t.lm++:B===I&&(I>x&&B>v||I<x&&B<v?o==="right"&&t.lm++:B>v?t.lm++:B===x&&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},Zk(It,It.transformComponent,It.checkValidOp,It.append);var LM=Yk.exports;It.registerSubtype(LM);var RM=It,OM={type:RM};(function(n){n.defaultType=OM.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)})(eu);var No={};(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))}})(No);var Jk=Array.isArray,Kk=Object.keys,_M=Object.prototype.hasOwnProperty,FM=function n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var o=Jk(t),r=Jk(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 C=Kk(t);if(s=C.length,s!==Kk(e).length)return!1;for(i=s;i--!==0;)if(!_M.call(e,C[i]))return!1;for(i=s;i--!==0;)if(l=C[i],!n(t[l],e[l]))return!1;return!0}return t!==t&&e!==e},Xk=Hi,PM=Qk,qn=rf,cf=eu,$o=No,NM=$o.clone,$M=FM,Dn=qn.CODES,HM=Pt;function Pt(n,t,e){Xk.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}Xk.mixin(Pt),Pt.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())})},Pt.prototype._setType=function(n){if(typeof n=="string"&&(n=cf.map[n]),n)this.type=n;else if(n===null)this.type=n,this._setData(void 0);else{var t=new qn(Dn.ERR_DOC_TYPE_NOT_RECOGNIZED,"Missing type "+n);return this.emit("error",t)}},Pt.prototype._setData=function(n){this.data=n,this._dataStateVersion++},Pt.prototype.ingestSnapshot=function(n,t){if(!n)return t&&t();if(typeof n.v!="number"){var e=new qn(Dn.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 qn(Dn.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?cf.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()},Pt.prototype.whenNothingPending=function(n){var t=this;$o.nextTick(function(){if(t.hasPending()){t.once("nothing pending",n);return}n()})},Pt.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe||this.pendingFetch.length||this.pendingSubscribe.length)},Pt.prototype.hasWritePending=function(){return!!(this.inflightOp||this.pendingOps.length)},Pt.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),!this.hasPending()&&this.emit("nothing pending"))},Pt.prototype._emitResponseError=function(n,t){if(n&&n.code===Dn.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)},Pt.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){$o.callEach(e,r)}),n)return this._emitResponseError(n,o);this.ingestSnapshot(t,o),this._emitNothingPending()},Pt.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){$o.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()},Pt.prototype._handleOp=function(n,t){if(n)return this.inflightOp?(n.code===Dn.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=af(this.inflightOp,t);if(e)return this._hardRollback(e)}for(var o=0;o<this.pendingOps.length;o++){var e=af(this.pendingOps[o],t);if(e)return this._hardRollback(e)}this.version++;try{this._otApply(t,!1)}catch(r){return this._hardRollback(r)}}},Pt.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))},Pt.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()},Pt.prototype.fetch=function(n){if(this.connection.canSend){var t=this.connection.sendFetch(this);jM(this.inflightFetch,t,n);return}this.pendingFetch.push(n)},Pt.prototype.subscribe=function(n){var t=!0;this._queueSubscribe(t,n)},Pt.prototype.unsubscribe=function(n){var t=!1;this._queueSubscribe(t,n)},Pt.prototype._queueSubscribe=function(n,t){var e=this.pendingSubscribe[this.pendingSubscribe.length-1]||this.inflightSubscribe,o=e&&e.wantSubscribe===n;if(o){e.callback=UM([e.callback,t]);return}this.pendingSubscribe.push({wantSubscribe:!!n,callback:t}),this._flushSubscribe()},Pt.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;$o.nextTick(function(){n._handleSubscribe()})}}};function jM(n,t,e){if(t){var o=n.pop();n.push(function(r){o&&o(r),e&&e(r)})}else n.push(e)}function UM(n){return n=n.filter($o.truthy),n.length?function(t){$o.callEach(n,t)}:null}Pt.prototype.flush=function(){!this.connection.canSend||this.inflightOp||!this.paused&&this.pendingOps.length&&this._sendOp()};function zM(n){delete n.op,delete n.create,delete n.del}function af(n,t){if(n.del)return zM(t);if(t.del)return new qn(Dn.ERR_DOC_WAS_DELETED,"Document was deleted");if(t.create)return new qn(Dn.ERR_DOC_ALREADY_CREATED,"Document already created");if("op"in t){if(n.create)return new qn(Dn.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}}}Pt.prototype._otApply=function(n,t){if("op"in n){if(!this.type)throw new qn(Dn.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===cf.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=af(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}},Pt.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 qn(Dn.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>=$o.MAX_SAFE_INTEGER)return this.emit("error",new qn(Dn.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)}},Pt.prototype._submit=function(n,t,e){if(t||(t=!0),"op"in n){if(!this.type){var o=new qn(Dn.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;$o.nextTick(function(){r.flush()})},Pt.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)},Pt.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)}}},Pt.prototype._tryCompose=function(n){if(!this.preventCompose){var t=this.pendingOps[this.pendingOps.length-1];if(!(!t||t.sentAt)&&!(this.submitSource&&!$M(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}}},Pt.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)},Pt.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=cf.defaultType.uri),this.type){var r=new qn(Dn.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)},Pt.prototype.del=function(n,t){if(typeof n=="function"&&(t=n,n=null),!this.type){var e=new qn(Dn.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)},Pt.prototype.pause=function(){this.paused=!0},Pt.prototype.resume=function(){this.paused=!1,this.flush()},Pt.prototype.toSnapshot=function(){return{v:this.version,data:NM(this.data),type:this.type.uri}},Pt.prototype._opAcknowledged=function(n){if(this.inflightOp.create)this.version=n.v;else if(n.v!==this.version)return PM.warn("Invalid version from server. Expected: "+this.version+" Received: "+n.v,n),this.fetch();this.version++,this._clearInflightOp()},Pt.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=af(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)},Pt.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=$o.callEach(t[r].callbacks,n)&&o;if(n&&!o)return e.emit("error",n)})},Pt.prototype._clearInflightOp=function(n){var t=this.inflightOp;this.inflightOp=null;var e=$o.callEach(t.callbacks,n);if(this.flush(),this._emitNothingPending(),n&&!e)return this.emit("error",n)};var Vs={};Vs.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 t2=Hi,e2=Vs.ACTIONS,VM=No,WM=Mn;function Mn(n,t,e,o,r,i,s){t2.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}t2.mixin(Mn),Mn.prototype.hasPending=function(){return!this.ready},Mn.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}},Mn.prototype.destroy=function(n){this.connection.canSend&&this.action===e2.querySubscribe&&this.connection.send({a:e2.queryUnsubscribe,id:this.id}),this.connection._destroyQuery(this),n&&VM.nextTick(n)},Mn.prototype._onConnectionStateChanged=function(){this.connection.canSend&&!this.sent?this.send():this.sent=!1},Mn.prototype._handleFetch=function(n,t,e){this.connection._destroyQuery(this),this._handleResponse(n,t,e)},Mn.prototype._handleSubscribe=function(n,t,e){this._handleResponse(n,t,e)},Mn.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()},Mn.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},Mn.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)},Mn.prototype._handleError=function(n){this.emit("error",n)},Mn.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)},Mn.prototype._handleExtra=function(n){this.extra=n,this.emit("extra",n)};var n2=Hi,qM=Vs.ACTIONS,GM=No,o2=fr;function fr(n,t){if(n2.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={}}n2.mixin(fr),fr.prototype.submit=function(n,t){this.value=n,this.send(t)},fr.prototype.send=function(n){var t=this._message();this._pendingMessages.push(t),this._callbacksByPresenceVersion[t.pv]=n,this._sendPending()},fr.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()})},fr.prototype._sendPending=function(){if(!!this.connection.canSend){var n=this;this._pendingMessages.forEach(function(t){n.connection.send(t)}),this._pendingMessages=[]}},fr.prototype._ack=function(n,t){var e=this._getCallback(t);this._callbackOrEmit(n,e)},fr.prototype._message=function(){return{a:qM.presence,ch:this.presence.channel,id:this.presenceId,p:this.value,pv:this.presenceVersion++}},fr.prototype._getCallback=function(n){var t=this._callbacksByPresenceVersion[n];return delete this._callbacksByPresenceVersion[n],t},fr.prototype._callbackOrEmit=function(n,t){if(t)return GM.nextTick(t,n);n&&this.emit("error",n)};var QM=No,r2=R1;function R1(n,t){this.presence=n,this.presenceId=t,this.connection=this.presence.connection,this.value=null,this.presenceVersion=0}R1.prototype.receiveUpdate=function(n){n.pv<this.presenceVersion||(this.value=n.p,this.presenceVersion=n.pv,this.presence._updateRemotePresence(this))},R1.prototype.destroy=function(n){delete this.presence._remotePresenceInstances[this.presenceId],delete this.presence.remotePresences[this.presenceId],n&&QM.nextTick(n)};var O1={exports:{}};(function(n,t){(function(e,o){o(t)})(hr,function(e){function o(w,S){S=S|0;for(var R=Math.max(w.length-S,0),F=Array(R),U=0;U<R;U++)F[U]=w[S+U];return F}var r=function(w){var S=o(arguments,1);return function(){var R=o(arguments);return w.apply(null,S.concat(R))}},i=function(w){return function(){var S=o(arguments),R=S.pop();w.call(this,S,R)}};function s(w){var S=typeof w;return w!=null&&(S=="object"||S=="function")}var l=typeof setImmediate=="function"&&setImmediate,a=typeof process=="object"&&typeof process.nextTick=="function";function d(w){setTimeout(w,0)}function h(w){return function(S){var R=o(arguments,1);w(function(){S.apply(null,R)})}}var p;l?p=setImmediate:a?p=process.nextTick:p=d;var C=h(p);function v(w){return i(function(S,R){var F;try{F=w.apply(this,S)}catch(U){return R(U)}s(F)&&typeof F.then=="function"?F.then(function(U){B(R,null,U)},function(U){B(R,U.message?U:new Error(U))}):R(null,F)})}function B(w,S,R){try{w(S,R)}catch(F){C(x,F)}}function x(w){throw w}var I=typeof Symbol=="function";function _(w){return I&&w[Symbol.toStringTag]==="AsyncFunction"}function D(w){return _(w)?v(w):w}function H(w){return function(S){var R=o(arguments,1),F=i(function(U,j){var Q=this;return w(S,function(J,lt){D(J).apply(Q,U.concat(lt))},j)});return R.length?F.apply(this,R):F}}var W=typeof hr=="object"&&hr&&hr.Object===Object&&hr,G=typeof self=="object"&&self&&self.Object===Object&&self,K=W||G||Function("return this")(),ht=K.Symbol,bt=Object.prototype,_t=bt.hasOwnProperty,Ht=bt.toString,oe=ht?ht.toStringTag:void 0;function Le(w){var S=_t.call(w,oe),R=w[oe];try{w[oe]=void 0;var F=!0}catch{}var U=Ht.call(w);return F&&(S?w[oe]=R:delete w[oe]),U}var Jn=Object.prototype,Ee=Jn.toString;function Rn(w){return Ee.call(w)}var Ir="[object Null]",kn="[object Undefined]",un=ht?ht.toStringTag:void 0;function Tr(w){return w==null?w===void 0?kn:Ir:un&&un in Object(w)?Le(w):Rn(w)}var ii="[object AsyncFunction]",bo="[object Function]",Ib="[object GeneratorFunction]",Tb="[object Proxy]";function Sb(w){if(!s(w))return!1;var S=Tr(w);return S==bo||S==Ib||S==ii||S==Tb}var ns=9007199254740991;function sl(w){return typeof w=="number"&&w>-1&&w%1==0&&w<=ns}function ll(w){return w!=null&&sl(w.length)&&!Sb(w)}var si={};function jt(){}function Sr(w){return function(){if(w!==null){var S=w;w=null,S.apply(this,arguments)}}}var os=typeof Symbol=="function"&&Symbol.iterator,Zc=function(w){return os&&w[os]&&w[os]()};function Pm(w,S){for(var R=-1,F=Array(w);++R<w;)F[R]=S(R);return F}function dn(w){return w!=null&&typeof w=="object"}var cl="[object Arguments]";function Nm(w){return dn(w)&&Tr(w)==cl}var Ao=Object.prototype,$m=Ao.hasOwnProperty,Db=Ao.propertyIsEnumerable,al=Nm(function(){return arguments}())?Nm:function(w){return dn(w)&&$m.call(w,"callee")&&!Db.call(w,"callee")},ve=Array.isArray;function ul(){return!1}var dl=typeof e=="object"&&e&&!e.nodeType&&e,Hm=dl&&!0&&n&&!n.nodeType&&n,hl=Hm&&Hm.exports===dl,jm=hl?K.Buffer:void 0,fl=jm?jm.isBuffer:void 0,rs=fl||ul,nd=9007199254740991,od=/^(?:0|[1-9]\d*)$/;function rd(w,S){var R=typeof w;return S=S==null?nd:S,!!S&&(R=="number"||R!="symbol"&&od.test(w))&&w>-1&&w%1==0&&w<S}var id="[object Arguments]",sd="[object Array]",ld="[object Boolean]",cd="[object Date]",ad="[object Error]",ud="[object Function]",Mb="[object Map]",Lb="[object Number]",Rb="[object Object]",Um="[object RegExp]",zm="[object Set]",Ob="[object String]",_b="[object WeakMap]",Fb="[object ArrayBuffer]",Pb="[object DataView]",Vm="[object Float32Array]",Nb="[object Float64Array]",$b="[object Int8Array]",Hb="[object Int16Array]",dd="[object Int32Array]",jb="[object Uint8Array]",hd="[object Uint8ClampedArray]",Ub="[object Uint16Array]",zb="[object Uint32Array]",le={};le[Vm]=le[Nb]=le[$b]=le[Hb]=le[dd]=le[jb]=le[hd]=le[Ub]=le[zb]=!0,le[id]=le[sd]=le[Fb]=le[ld]=le[Pb]=le[cd]=le[ad]=le[ud]=le[Mb]=le[Lb]=le[Rb]=le[Um]=le[zm]=le[Ob]=le[_b]=!1;function Vb(w){return dn(w)&&sl(w.length)&&!!le[Tr(w)]}function Wb(w){return function(S){return w(S)}}var Wm=typeof e=="object"&&e&&!e.nodeType&&e,ml=Wm&&!0&&n&&!n.nodeType&&n,qb=ml&&ml.exports===Wm,Yc=qb&&W.process,qm=function(){try{var w=ml&&ml.require&&ml.require("util").types;return w||Yc&&Yc.binding&&Yc.binding("util")}catch{}}(),Gm=qm&&qm.isTypedArray,Gb=Gm?Wb(Gm):Vb,Qb=Object.prototype,Zb=Qb.hasOwnProperty;function Yb(w,S){var R=ve(w),F=!R&&al(w),U=!R&&!F&&rs(w),j=!R&&!F&&!U&&Gb(w),Q=R||F||U||j,J=Q?Pm(w.length,String):[],lt=J.length;for(var pt in w)(S||Zb.call(w,pt))&&!(Q&&(pt=="length"||U&&(pt=="offset"||pt=="parent")||j&&(pt=="buffer"||pt=="byteLength"||pt=="byteOffset")||rd(pt,lt)))&&J.push(pt);return J}var Jc=Object.prototype;function Jb(w){var S=w&&w.constructor,R=typeof S=="function"&&S.prototype||Jc;return w===R}function Kc(w,S){return function(R){return w(S(R))}}var Kb=Kc(Object.keys,Object),Xb=Object.prototype,tA=Xb.hasOwnProperty;function Qm(w){if(!Jb(w))return Kb(w);var S=[];for(var R in Object(w))tA.call(w,R)&&R!="constructor"&&S.push(R);return S}function Xc(w){return ll(w)?Yb(w):Qm(w)}function Zm(w){var S=-1,R=w.length;return function(){return++S<R?{value:w[S],key:S}:null}}function eA(w){var S=-1;return function(){var F=w.next();return F.done?null:(S++,{value:F.value,key:S})}}function nA(w){var S=Xc(w),R=-1,F=S.length;return function U(){var j=S[++R];return j==="__proto__"?U():R<F?{value:w[j],key:j}:null}}function oA(w){if(ll(w))return Zm(w);var S=Zc(w);return S?eA(S):nA(w)}function vo(w){return function(){if(w===null)throw new Error("Callback was already called.");var S=w;w=null,S.apply(this,arguments)}}function gl(w){return function(S,R,F){if(F=Sr(F||jt),w<=0||!S)return F(null);var U=oA(S),j=!1,Q=0,J=!1;function lt(ct,At){if(Q-=1,ct)j=!0,F(ct);else{if(At===si||j&&Q<=0)return j=!0,F(null);J||pt()}}function pt(){for(J=!0;Q<w&&!j;){var ct=U();if(ct===null){j=!0,Q<=0&&F(null);return}Q+=1,R(ct.value,ct.key,vo(lt))}J=!1}pt()}}function Dr(w,S,R,F){gl(S)(w,D(R),F)}function ze(w,S){return function(R,F,U){return w(R,S,F,U)}}function fd(w,S,R){R=Sr(R||jt);var F=0,U=0,j=w.length;j===0&&R(null);function Q(J,lt){J?R(J):(++U===j||lt===si)&&R(null)}for(;F<j;F++)S(w[F],F,vo(Q))}var rA=ze(Dr,1/0),Go=function(w,S,R){var F=ll(w)?fd:rA;F(w,D(S),R)};function Qo(w){return function(S,R,F){return w(Go,S,D(R),F)}}function md(w,S,R,F){F=F||jt,S=S||[];var U=[],j=0,Q=D(R);w(S,function(J,lt,pt){var ct=j++;Q(J,function(At,Zt){U[ct]=Zt,pt(At)})},function(J){F(J,U)})}var ta=Qo(md),gd=H(ta);function li(w){return function(S,R,F,U){return w(gl(R),S,D(F),U)}}var Mr=li(md),pd=ze(Mr,1),Cd=H(pd);function is(w,S){for(var R=-1,F=w==null?0:w.length;++R<F&&S(w[R],R,w)!==!1;);return w}function bd(w){return function(S,R,F){for(var U=-1,j=Object(S),Q=F(S),J=Q.length;J--;){var lt=Q[w?J:++U];if(R(j[lt],lt,j)===!1)break}return S}}var ss=bd();function ls(w,S){return w&&ss(w,S,Xc)}function Ym(w,S,R,F){for(var U=w.length,j=R+(F?1:-1);F?j--:++j<U;)if(S(w[j],j,w))return j;return-1}function iA(w){return w!==w}function Jm(w,S,R){for(var F=R-1,U=w.length;++F<U;)if(w[F]===S)return F;return-1}function pl(w,S,R){return S===S?Jm(w,S,R):Ym(w,iA,R)}var ea=function(w,S,R){typeof S=="function"&&(R=S,S=null),R=Sr(R||jt);var F=Xc(w),U=F.length;if(!U)return R(null);S||(S=U);var j={},Q=0,J=!1,lt=Object.create(null),pt=[],ct=[],At={};ls(w,function(he,ie){if(!ve(he)){Zt(ie,[he]),ct.push(ie);return}var Ce=he.slice(0,he.length-1),ko=Ce.length;if(ko===0){Zt(ie,he),ct.push(ie);return}At[ie]=ko,is(Ce,function(E){if(!w[E])throw new Error("async.auto task `"+ie+"` has a non-existent dependency `"+E+"` in "+Ce.join(", "));nn(E,function(){ko--,ko===0&&Zt(ie,he)})})}),IA(),Re();function Zt(he,ie){pt.push(function(){yo(he,ie)})}function Re(){if(pt.length===0&&Q===0)return R(null,j);for(;pt.length&&Q<S;){var he=pt.shift();he()}}function nn(he,ie){var Ce=lt[he];Ce||(Ce=lt[he]=[]),Ce.push(ie)}function Fn(he){var ie=lt[he]||[];is(ie,function(Ce){Ce()}),Re()}function yo(he,ie){if(!J){var Ce=vo(function(E,Or){if(Q--,arguments.length>2&&(Or=o(arguments,1)),E){var ds={};ls(j,function(Pn,$t){ds[$t]=Pn}),ds[he]=Or,J=!0,lt=Object.create(null),R(E,ds)}else j[he]=Or,Fn(he)});Q++;var ko=D(ie[ie.length-1]);ie.length>1?ko(j,Ce):ko(Ce)}}function IA(){for(var he,ie=0;ct.length;)he=ct.pop(),ie++,is(TA(he),function(Ce){--At[Ce]===0&&ct.push(Ce)});if(ie!==U)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function TA(he){var ie=[];return ls(w,function(Ce,ko){ve(Ce)&&pl(Ce,he,0)>=0&&ie.push(ko)}),ie}};function ci(w,S){for(var R=-1,F=w==null?0:w.length,U=Array(F);++R<F;)U[R]=S(w[R],R,w);return U}var sA="[object Symbol]";function lA(w){return typeof w=="symbol"||dn(w)&&Tr(w)==sA}var cA=1/0,Ad=ht?ht.prototype:void 0,Km=Ad?Ad.toString:void 0;function vd(w){if(typeof w=="string")return w;if(ve(w))return ci(w,vd)+"";if(lA(w))return Km?Km.call(w):"";var S=w+"";return S=="0"&&1/w==-cA?"-0":S}function aA(w,S,R){var F=-1,U=w.length;S<0&&(S=-S>U?0:U+S),R=R>U?U:R,R<0&&(R+=U),U=S>R?0:R-S>>>0,S>>>=0;for(var j=Array(U);++F<U;)j[F]=w[F+S];return j}function uA(w,S,R){var F=w.length;return R=R===void 0?F:R,!S&&R>=F?w:aA(w,S,R)}function yd(w,S){for(var R=w.length;R--&&pl(S,w[R],0)>-1;);return R}function dA(w,S){for(var R=-1,F=w.length;++R<F&&pl(S,w[R],0)>-1;);return R}function hA(w){return w.split("")}var fA="\\ud800-\\udfff",mA="\\u0300-\\u036f",gA="\\ufe20-\\ufe2f",ce="\\u20d0-\\u20ff",re=mA+gA+ce,pA="\\ufe0e\\ufe0f",CA="\\u200d",bA=RegExp("["+CA+fA+re+pA+"]");function AA(w){return bA.test(w)}var Xm="\\ud800-\\udfff",vA="\\u0300-\\u036f",tg="\\ufe20-\\ufe2f",yA="\\u20d0-\\u20ff",Qe=vA+tg+yA,kd="\\ufe0e\\ufe0f",ai="["+Xm+"]",na="["+Qe+"]",Cl="\\ud83c[\\udffb-\\udfff]",On="(?:"+na+"|"+Cl+")",wd="[^"+Xm+"]",Bd="(?:\\ud83c[\\udde6-\\uddff]){2}",Ed="[\\ud800-\\udbff][\\udc00-\\udfff]",eg="\\u200d",xd=On+"?",Id="["+kd+"]?",wn="(?:"+eg+"(?:"+[wd,Bd,Ed].join("|")+")"+Id+xd+")*",kA=Id+xd+wn,_n="(?:"+[wd+na+"?",na,Bd,Ed,ai].join("|")+")",wA=RegExp(Cl+"(?="+Cl+")|"+_n+kA,"g");function ng(w){return w.match(wA)||[]}function Zo(w){return AA(w)?ng(w):hA(w)}function oa(w){return w==null?"":vd(w)}var Td=/^\s+|\s+$/g;function de(w,S,R){if(w=oa(w),w&&(R||S===void 0))return w.replace(Td,"");if(!w||!(S=vd(S)))return w;var F=Zo(w),U=Zo(S),j=dA(F,U),Q=yd(F,U)+1;return uA(F,j,Q).join("")}var Lr=/^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,Sd=/,/,BA=/(=.+)?(\s*)$/,Dd=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;function EA(w){return w=w.toString().replace(Dd,""),w=w.match(Lr)[2].replace(" ",""),w=w?w.split(Sd):[],w=w.map(function(S){return de(S.replace(BA,""))}),w}function og(w,S){var R={};ls(w,function(F,U){var j,Q=_(F),J=!Q&&F.length===1||Q&&F.length===0;if(ve(F))j=F.slice(0,-1),F=F[F.length-1],R[U]=j.concat(j.length>0?lt:F);else if(J)R[U]=F;else{if(j=EA(F),F.length===0&&!Q&&j.length===0)throw new Error("autoInject task functions require explicit parameters.");Q||j.pop(),R[U]=j.concat(lt)}function lt(pt,ct){var At=ci(j,function(Zt){return pt[Zt]});At.push(ct),D(F).apply(null,At)}}),ea(R,S)}function Kn(){this.head=this.tail=null,this.length=0}function Md(w,S){w.length=1,w.head=w.tail=S}Kn.prototype.removeLink=function(w){return w.prev?w.prev.next=w.next:this.head=w.next,w.next?w.next.prev=w.prev:this.tail=w.prev,w.prev=w.next=null,this.length-=1,w},Kn.prototype.empty=function(){for(;this.head;)this.shift();return this},Kn.prototype.insertAfter=function(w,S){S.prev=w,S.next=w.next,w.next?w.next.prev=S:this.tail=S,w.next=S,this.length+=1},Kn.prototype.insertBefore=function(w,S){S.prev=w.prev,S.next=w,w.prev?w.prev.next=S:this.head=S,w.prev=S,this.length+=1},Kn.prototype.unshift=function(w){this.head?this.insertBefore(this.head,w):Md(this,w)},Kn.prototype.push=function(w){this.tail?this.insertAfter(this.tail,w):Md(this,w)},Kn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},Kn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)},Kn.prototype.toArray=function(){for(var w=Array(this.length),S=this.head,R=0;R<this.length;R++)w[R]=S.data,S=S.next;return w},Kn.prototype.remove=function(w){for(var S=this.head;S;){var R=S.next;w(S)&&this.removeLink(S),S=R}return this};function bl(w,S,R){if(S==null)S=1;else if(S===0)throw new Error("Concurrency must not be zero");var F=D(w),U=0,j=[],Q=!1;function J(At,Zt,Re){if(Re!=null&&typeof Re!="function")throw new Error("task callback must be a function");if(ct.started=!0,ve(At)||(At=[At]),At.length===0&&ct.idle())return C(function(){ct.drain()});for(var nn=0,Fn=At.length;nn<Fn;nn++){var yo={data:At[nn],callback:Re||jt};Zt?ct._tasks.unshift(yo):ct._tasks.push(yo)}Q||(Q=!0,C(function(){Q=!1,ct.process()}))}function lt(At){return function(Zt){U-=1;for(var Re=0,nn=At.length;Re<nn;Re++){var Fn=At[Re],yo=pl(j,Fn,0);yo===0?j.shift():yo>0&&j.splice(yo,1),Fn.callback.apply(Fn,arguments),Zt!=null&&ct.error(Zt,Fn.data)}U<=ct.concurrency-ct.buffer&&ct.unsaturated(),ct.idle()&&ct.drain(),ct.process()}}var pt=!1,ct={_tasks:new Kn,concurrency:S,payload:R,saturated:jt,unsaturated:jt,buffer:S/4,empty:jt,drain:jt,error:jt,started:!1,paused:!1,push:function(At,Zt){J(At,!1,Zt)},kill:function(){ct.drain=jt,ct._tasks.empty()},unshift:function(At,Zt){J(At,!0,Zt)},remove:function(At){ct._tasks.remove(At)},process:function(){if(!pt){for(pt=!0;!ct.paused&&U<ct.concurrency&&ct._tasks.length;){var At=[],Zt=[],Re=ct._tasks.length;ct.payload&&(Re=Math.min(Re,ct.payload));for(var nn=0;nn<Re;nn++){var Fn=ct._tasks.shift();At.push(Fn),j.push(Fn),Zt.push(Fn.data)}U+=1,ct._tasks.length===0&&ct.empty(),U===ct.concurrency&&ct.saturated();var yo=vo(lt(At));F(Zt,yo)}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,C(ct.process))}};return ct}function ui(w,S){return bl(w,1,S)}var cs=ze(Dr,1);function Yo(w,S,R,F){F=Sr(F||jt);var U=D(R);cs(w,function(j,Q,J){U(S,j,function(lt,pt){S=pt,J(lt)})},function(j){F(j,S)})}function ra(){var w=ci(arguments,D);return function(){var S=o(arguments),R=this,F=S[S.length-1];typeof F=="function"?S.pop():F=jt,Yo(w,S,function(U,j,Q){j.apply(R,U.concat(function(J){var lt=o(arguments,1);Q(J,lt)}))},function(U,j){F.apply(R,[U].concat(j))})}}var ia=function(){return ra.apply(null,o(arguments).reverse())},Ld=Array.prototype.concat,Al=function(w,S,R,F){F=F||jt;var U=D(R);Mr(w,S,function(j,Q){U(j,function(J){return J?Q(J):Q(null,o(arguments,1))})},function(j,Q){for(var J=[],lt=0;lt<Q.length;lt++)Q[lt]&&(J=Ld.apply(J,Q[lt]));return F(j,J)})},rg=ze(Al,1/0),sa=ze(Al,1),la=function(){var w=o(arguments),S=[null].concat(w);return function(){var R=arguments[arguments.length-1];return R.apply(this,S)}};function vl(w){return w}function di(w,S){return function(R,F,U,j){j=j||jt;var Q=!1,J;R(F,function(lt,pt,ct){U(lt,function(At,Zt){At?ct(At):w(Zt)&&!J?(Q=!0,J=S(!0,lt),ct(null,si)):ct()})},function(lt){lt?j(lt):j(null,Q?J:S(!1))})}}function hn(w,S){return S}var as=Qo(di(vl,hn)),Jo=li(di(vl,hn)),yl=ze(Jo,1);function Rd(w){return function(S){var R=o(arguments,1);R.push(function(F){var U=o(arguments,1);typeof console=="object"&&(F?console.error&&console.error(F):console[w]&&is(U,function(j){console[w](j)}))}),D(S).apply(null,R)}}var ig=Rd("dir");function sg(w,S,R){R=vo(R||jt);var F=D(w),U=D(S);function j(J){if(J)return R(J);var lt=o(arguments,1);lt.push(Q),U.apply(this,lt)}function Q(J,lt){if(J)return R(J);if(!lt)return R(null);F(j)}Q(null,!0)}function Od(w,S,R){R=vo(R||jt);var F=D(w),U=function(j){if(j)return R(j);var Q=o(arguments,1);if(S.apply(this,Q))return F(U);R.apply(null,[null].concat(Q))};F(U)}function lg(w,S,R){Od(w,function(){return!S.apply(this,arguments)},R)}function cg(w,S,R){R=vo(R||jt);var F=D(S),U=D(w);function j(J){if(J)return R(J);U(Q)}function Q(J,lt){if(J)return R(J);if(!lt)return R(null);F(j)}U(Q)}function hi(w){return function(S,R,F){return w(S,F)}}function ca(w,S,R){Go(w,hi(D(S)),R)}function kl(w,S,R,F){gl(S)(w,hi(D(R)),F)}var fi=ze(kl,1);function aa(w){return _(w)?w:i(function(S,R){var F=!0;S.push(function(){var U=arguments;F?C(function(){R.apply(null,U)}):R.apply(null,U)}),w.apply(this,S),F=!1})}function Xn(w){return!w}var mi=Qo(di(Xn,Xn)),wl=li(di(Xn,Xn)),ua=ze(wl,1);function ag(w){return function(S){return S==null?void 0:S[w]}}function us(w,S,R,F){var U=new Array(S.length);w(S,function(j,Q,J){R(j,function(lt,pt){U[Q]=!!pt,J(lt)})},function(j){if(j)return F(j);for(var Q=[],J=0;J<S.length;J++)U[J]&&Q.push(S[J]);F(null,Q)})}function to(w,S,R,F){var U=[];w(S,function(j,Q,J){R(j,function(lt,pt){lt?J(lt):(pt&&U.push({index:Q,value:j}),J())})},function(j){j?F(j):F(null,ci(U.sort(function(Q,J){return Q.index-J.index}),ag("value")))})}function da(w,S,R,F){var U=ll(S)?us:to;U(w,S,D(R),F||jt)}var ha=Qo(da),Bl=li(da),fa=ze(Bl,1);function ug(w,S){var R=vo(S||jt),F=D(aa(w));function U(j){if(j)return R(j);F(U)}U()}var ma=function(w,S,R,F){F=F||jt;var U=D(R);Mr(w,S,function(j,Q){U(j,function(J,lt){return J?Q(J):Q(null,{key:lt,val:j})})},function(j,Q){for(var J={},lt=Object.prototype.hasOwnProperty,pt=0;pt<Q.length;pt++)if(Q[pt]){var ct=Q[pt].key,At=Q[pt].val;lt.call(J,ct)?J[ct].push(At):J[ct]=[At]}return F(j,J)})},gi=ze(ma,1/0),N=ze(ma,1),q=Rd("log");function z(w,S,R,F){F=Sr(F||jt);var U={},j=D(R);Dr(w,S,function(Q,J,lt){j(Q,J,function(pt,ct){if(pt)return lt(pt);U[J]=ct,lt()})},function(Q){F(Q,U)})}var ft=ze(z,1/0),xt=ze(z,1);function Vt(w,S){return S in w}function xe(w,S){var R=Object.create(null),F=Object.create(null);S=S||vl;var U=D(w),j=i(function(J,lt){var pt=S.apply(null,J);Vt(R,pt)?C(function(){lt.apply(null,R[pt])}):Vt(F,pt)?F[pt].push(lt):(F[pt]=[lt],U.apply(null,J.concat(function(){var ct=o(arguments);R[pt]=ct;var At=F[pt];delete F[pt];for(var Zt=0,Re=At.length;Zt<Re;Zt++)At[Zt].apply(null,ct)})))});return j.memo=R,j.unmemoized=w,j}var Gt;a?Gt=process.nextTick:l?Gt=setImmediate:Gt=d;var ga=h(Gt);function _d(w,S,R){R=R||jt;var F=ll(S)?[]:{};w(S,function(U,j,Q){D(U)(function(J,lt){arguments.length>2&&(lt=o(arguments,1)),F[j]=lt,Q(J)})},function(U){R(U,F)})}function Bn(w,S){_d(Go,w,S)}function El(w,S,R){_d(gl(S),w,R)}var Fd=function(w,S){var R=D(w);return bl(function(F,U){R(F[0],U)},S,1)},pi=function(w,S){var R=Fd(w,S);return R.push=function(F,U,j){if(j==null&&(j=jt),typeof j!="function")throw new Error("task callback must be a function");if(R.started=!0,ve(F)||(F=[F]),F.length===0)return C(function(){R.drain()});U=U||0;for(var Q=R._tasks.head;Q&&U>=Q.priority;)Q=Q.next;for(var J=0,lt=F.length;J<lt;J++){var pt={data:F[J],priority:U,callback:j};Q?R._tasks.insertBefore(Q,pt):R._tasks.push(pt)}C(R.process)},delete R.unshift,R};function xl(w,S){if(S=Sr(S||jt),!ve(w))return S(new TypeError("First argument to race must be an array of functions"));if(!w.length)return S();for(var R=0,F=w.length;R<F;R++)D(w[R])(S)}function Ci(w,S,R,F){var U=o(w).reverse();Yo(U,S,R,F)}function Wt(w){var S=D(w);return i(function(F,U){return F.push(function(Q,J){if(Q)U(null,{error:Q});else{var lt;arguments.length<=2?lt=J:lt=o(arguments,1),U(null,{value:lt})}}),S.apply(this,F)})}function dg(w){var S;return ve(w)?S=ci(w,Wt):(S={},ls(w,function(R,F){S[F]=Wt.call(this,R)})),S}function Pd(w,S,R,F){da(w,S,function(U,j){R(U,function(Q,J){j(Q,!J)})},F)}var Il=Qo(Pd),Nd=li(Pd),hg=ze(Nd,1);function fg(w){return function(){return w}}function bi(w,S,R){var F=5,U=0,j={times:F,intervalFunc:fg(U)};function Q(ct,At){if(typeof At=="object")ct.times=+At.times||F,ct.intervalFunc=typeof At.interval=="function"?At.interval:fg(+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 w=="function"?(R=S||jt,S=w):(Q(j,w),R=R||jt),typeof S!="function")throw new Error("Invalid arguments for async.retry");var J=D(S),lt=1;function pt(){J(function(ct){ct&<++<j.times&&(typeof j.errorFilter!="function"||j.errorFilter(ct))?setTimeout(pt,j.intervalFunc(lt)):R.apply(null,arguments)})}pt()}var Ko=function(w,S){S||(S=w,w=null);var R=D(S);return i(function(F,U){function j(Q){R.apply(null,F.concat(Q))}w?bi(w,j,U):bi(j,U)})};function Tl(w,S){_d(cs,w,S)}var Sl=Qo(di(Boolean,vl)),Rr=li(di(Boolean,vl)),Dl=ze(Rr,1);function $d(w,S,R){var F=D(S);ta(w,function(j,Q){F(j,function(J,lt){if(J)return Q(J);Q(null,{value:j,criteria:lt})})},function(j,Q){if(j)return R(j);R(null,ci(Q.sort(U),ag("value")))});function U(j,Q){var J=j.criteria,lt=Q.criteria;return J<lt?-1:J>lt?1:0}}function Ml(w,S,R){var F=D(w);return i(function(U,j){var Q=!1,J;function lt(){var pt=w.name||"anonymous",ct=new Error('Callback function "'+pt+'" timed out.');ct.code="ETIMEDOUT",R&&(ct.info=R),Q=!0,j(ct)}U.push(function(){Q||(j.apply(null,arguments),clearTimeout(J))}),J=setTimeout(lt,S),F.apply(null,U)})}var mg=Math.ceil,Ll=Math.max;function Ai(w,S,R,F){for(var U=-1,j=Ll(mg((S-w)/(R||1)),0),Q=Array(j);j--;)Q[F?j:++U]=w,w+=R;return Q}function vi(w,S,R,F){var U=D(R);Mr(Ai(0,w,1),S,U,F)}var gg=ze(vi,1/0),pg=ze(vi,1);function Cg(w,S,R,F){arguments.length<=3&&(F=R,R=S,S=ve(w)?[]:{}),F=Sr(F||jt);var U=D(R);Go(w,function(j,Q,J){U(S,j,Q,J)},function(j){F(j,S)})}function Rl(w,S){var R=null,F;S=S||jt,fi(w,function(U,j){D(U)(function(Q,J){arguments.length>2?F=o(arguments,1):F=J,R=Q,j(!Q)})},function(){S(R,F)})}function Ol(w){return function(){return(w.unmemoized||w).apply(null,arguments)}}function _l(w,S,R){R=vo(R||jt);var F=D(S);if(!w())return R(null);var U=function(j){if(j)return R(j);if(w())return F(U);var Q=o(arguments,1);R.apply(null,[null].concat(Q))};F(U)}function bg(w,S,R){_l(function(){return!w.apply(this,arguments)},S,R)}var Hd=function(w,S){if(S=Sr(S||jt),!ve(w))return S(new Error("First argument to waterfall must be an array of functions"));if(!w.length)return S();var R=0;function F(j){var Q=D(w[R++]);j.push(vo(U)),Q.apply(null,j)}function U(j){if(j||R===w.length)return S.apply(null,arguments);F(o(arguments,1))}F([])},xA={apply:r,applyEach:gd,applyEachSeries:Cd,asyncify:v,auto:ea,autoInject:og,cargo:ui,compose:ia,concat:rg,concatLimit:Al,concatSeries:sa,constant:la,detect:as,detectLimit:Jo,detectSeries:yl,dir:ig,doDuring:sg,doUntil:lg,doWhilst:Od,during:cg,each:ca,eachLimit:kl,eachOf:Go,eachOfLimit:Dr,eachOfSeries:cs,eachSeries:fi,ensureAsync:aa,every:mi,everyLimit:wl,everySeries:ua,filter:ha,filterLimit:Bl,filterSeries:fa,forever:ug,groupBy:gi,groupByLimit:ma,groupBySeries:N,log:q,map:ta,mapLimit:Mr,mapSeries:pd,mapValues:ft,mapValuesLimit:z,mapValuesSeries:xt,memoize:xe,nextTick:ga,parallel:Bn,parallelLimit:El,priorityQueue:pi,queue:Fd,race:xl,reduce:Yo,reduceRight:Ci,reflect:Wt,reflectAll:dg,reject:Il,rejectLimit:Nd,rejectSeries:hg,retry:bi,retryable:Ko,seq:ra,series:Tl,setImmediate:C,some:Sl,someLimit:Rr,someSeries:Dl,sortBy:$d,timeout:Ml,times:gg,timesLimit:vi,timesSeries:pg,transform:Cg,tryEach:Rl,unmemoize:Ol,until:bg,waterfall:Hd,whilst:_l,all:mi,allLimit:wl,allSeries:ua,any:Sl,anyLimit:Rr,anySeries:Dl,find:as,findLimit:Jo,findSeries:yl,forEach:ca,forEachSeries:fi,forEachLimit:kl,forEachOf:Go,forEachOfSeries:cs,forEachOfLimit:Dr,inject:Yo,foldl:Yo,foldr:Ci,select:ha,selectLimit:Bl,selectSeries:fa,wrapSync:v};e.default=xA,e.apply=r,e.applyEach=gd,e.applyEachSeries=Cd,e.asyncify=v,e.auto=ea,e.autoInject=og,e.cargo=ui,e.compose=ia,e.concat=rg,e.concatLimit=Al,e.concatSeries=sa,e.constant=la,e.detect=as,e.detectLimit=Jo,e.detectSeries=yl,e.dir=ig,e.doDuring=sg,e.doUntil=lg,e.doWhilst=Od,e.during=cg,e.each=ca,e.eachLimit=kl,e.eachOf=Go,e.eachOfLimit=Dr,e.eachOfSeries=cs,e.eachSeries=fi,e.ensureAsync=aa,e.every=mi,e.everyLimit=wl,e.everySeries=ua,e.filter=ha,e.filterLimit=Bl,e.filterSeries=fa,e.forever=ug,e.groupBy=gi,e.groupByLimit=ma,e.groupBySeries=N,e.log=q,e.map=ta,e.mapLimit=Mr,e.mapSeries=pd,e.mapValues=ft,e.mapValuesLimit=z,e.mapValuesSeries=xt,e.memoize=xe,e.nextTick=ga,e.parallel=Bn,e.parallelLimit=El,e.priorityQueue=pi,e.queue=Fd,e.race=xl,e.reduce=Yo,e.reduceRight=Ci,e.reflect=Wt,e.reflectAll=dg,e.reject=Il,e.rejectLimit=Nd,e.rejectSeries=hg,e.retry=bi,e.retryable=Ko,e.seq=ra,e.series=Tl,e.setImmediate=C,e.some=Sl,e.someLimit=Rr,e.someSeries=Dl,e.sortBy=$d,e.timeout=Ml,e.times=gg,e.timesLimit=vi,e.timesSeries=pg,e.transform=Cg,e.tryEach=Rl,e.unmemoize=Ol,e.until=bg,e.waterfall=Hd,e.whilst=_l,e.all=mi,e.allLimit=wl,e.allSeries=ua,e.any=Sl,e.anyLimit=Rr,e.anySeries=Dl,e.find=as,e.findLimit=Jo,e.findSeries=yl,e.forEach=ca,e.forEachSeries=fi,e.forEachLimit=kl,e.forEachOf=Go,e.forEachOfSeries=cs,e.forEachOfLimit=Dr,e.inject=Yo,e.foldl=Yo,e.foldr=Ci,e.select=ha,e.selectLimit=Bl,e.selectSeries=fa,e.wrapSync=v,Object.defineProperty(e,"__esModule",{value:!0})})})(O1,O1.exports);var i2={exports:{}},_1=i2.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)?_1(n,t):i};_1.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=_1(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 s2=Hi,ZM=o2,YM=r2,uf=No,F1=O1.exports,JM=i2.exports,l2=Vs.ACTIONS,c2=Pe;function Pe(n,t){if(s2.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}s2.mixin(Pe),Pe.prototype.subscribe=function(n){this._sendSubscriptionAction(!0,n)},Pe.prototype.unsubscribe=function(n){this._sendSubscriptionAction(!1,n)},Pe.prototype.create=function(n){if(this._wantsDestroy)throw new Error("Presence is being destroyed");n=n||JM();var t=this._createLocalPresence(n);return this.localPresences[n]=t,t},Pe.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);F1.parallel([function(i){F1.each(e,function(s,l){t.localPresences[s].destroy(l)},i)},function(i){if(!t._wantsDestroy)return i();F1.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)})})},Pe.prototype._sendSubscriptionAction=function(n,t){this.wantSubscribe=!!n;var e=this.wantSubscribe?l2.presenceSubscribe:l2.presenceUnsubscribe,o=this.connection._presenceSeq++;this._subscriptionCallbacksBySeq[o]=t,this.connection.canSend&&this.connection._sendPresenceAction(e,o,this)},Pe.prototype._handleSubscribe=function(n,t){this.wantSubscribe&&(this.subscribed=!0);var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Pe.prototype._handleUnsubscribe=function(n,t){this.subscribed=!1;var e=this._subscriptionCallback(t);this._callbackOrEmit(n,e)},Pe.prototype._receiveUpdate=function(n,t){var e=uf.dig(this.localPresences,t.id);if(e)return e._ack(n,t.pv);if(n)return this.emit("error",n);var o=this,r=uf.digOrCreate(this._remotePresenceInstances,t.id,function(){return o._createRemotePresence(t.id)});r.receiveUpdate(t)},Pe.prototype._updateRemotePresence=function(n){this.remotePresences[n.presenceId]=n.value,n.value===null&&this._removeRemotePresence(n.presenceId),this.emit("receive",n.presenceId,n.value)},Pe.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()}},Pe.prototype._removeRemotePresence=function(n){this._remotePresenceInstances[n].destroy(),delete this._remotePresenceInstances[n],delete this.remotePresences[n]},Pe.prototype._onConnectionStateChanged=function(){if(!!this.connection.canSend){this._resubscribe();for(var n in this.localPresences)this.localPresences[n]._sendPending()}},Pe.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)})},Pe.prototype._subscriptionCallback=function(n){var t=this._subscriptionCallbacksBySeq[n];return delete this._subscriptionCallbacksBySeq[n],t},Pe.prototype._callbackOrEmit=function(n,t){if(t)return uf.nextTick(t,n);n&&this.emit("error",n)},Pe.prototype._createLocalPresence=function(n){return new ZM(this,n)},Pe.prototype._createRemotePresence=function(n){return new YM(this,n)},Pe.prototype._callEachOrEmit=function(n,t){var e=uf.callEach(n,t);!e&&t&&this.emit("error",t)};var ru=o2,a2=rf,KM=No,u2=a2.CODES,XM=Ho;function Ho(n,t){ru.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()}Ho.prototype=Object.create(ru.prototype),Ho.prototype.submit=function(n,t){if(!this._doc.type){if(n===null)return this._callbackOrEmit(null,t);var e={code:u2.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,ru.prototype.submit.call(this,n,t)},Ho.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),ru.prototype.destroy.call(this,n)},Ho.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={})})}},Ho.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)},Ho.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)}},Ho.prototype._handleCreateOrDel=function(){this._pendingMessages.forEach(function(n){n.p=null}),this.value=null},Ho.prototype._handleLoad=function(){this.value=null,this._pendingMessages=[],this._docDataVersionByPresenceVersion={}},Ho.prototype._message=function(){var n=ru.prototype._message.call(this);return n.c=this.collection,n.d=this.id,n.v=null,n.t=null,n},Ho.prototype._transformPresence=function(n,t,e){var o=this._doc.type;if(!KM.supportsPresence(o))throw new a2(u2.ERR_TYPE_DOES_NOT_SUPPORT_PRESENCE,"Type does not support presence: "+o.name);return o.transformPresence(n,t,e)};var d2={};(function(n){var t=eu,e=rf,o=No,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(C){return C}}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 C=n.apply(l,p);if(C)return C}},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(C){return{code:r.ERR_PRESENCE_TRANSFORM_FAILED,message:C.message||C}}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 C=d[p];typeof C.lm=="string"&&(C.lm=+C.lm);for(var v=C.p,B=h,x=0;x<v.length;x++){var I=v[x];Object.prototype.toString.call(B)=="[object Array]"?v[x]=+I:B.constructor===Object&&(v[x]=I.toString()),B=B[I]}p<d.length-1&&(h=t.defaultType.apply(h,[C]))}}}}})(d2);var iu=r2,tL=d2,eL=fo;function fo(n,t){iu.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()}fo.prototype=Object.create(iu.prototype),fo.prototype.receiveUpdate=function(n){this._pending&&n.pv<this._pending.pv||(this.src=n.src,this._pending=n,this._setPendingPresence())},fo.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),iu.prototype.destroy.call(this,n)},fo.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)},fo.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))}})}},fo.prototype._handleOp=function(n,t,e){var o=e===this.src;this._transformAgainstOp(n,o),this._cacheOp(n,o),this._setPendingPresence()},iu.prototype._handleCreateDel=function(){this._cacheOp(null),this._setPendingPresence()},iu.prototype._handleLoad=function(){this.value=null,this._pending=null,this._opCache=null,this.presence._updateRemotePresence(this)},fo.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)}},fo.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++):tL.transformPresence(this._pending,t,e)}var o=this._pending.v>=this._doc.version;return o&&this._stopCachingOps(),o},fo.prototype._startCachingOps=function(){this._opCache=[]},fo.prototype._stopCachingOps=function(){this._opCache=null},fo.prototype._cacheOp=function(n,t){this._opCache&&(n=n?{op:n}:null,this._opCache[this._doc.version-1]={op:n,isOwnOp:t})};var h2=c2,nL=XM,oL=eL;function ac(n,t,e){var o=ac.channel(t,e);h2.call(this,n,o),this.collection=t,this.id=e}var rL=ac;ac.prototype=Object.create(h2.prototype),ac.channel=function(n,t){return n+"."+t},ac.prototype._createLocalPresence=function(n){return new nL(this,n)},ac.prototype._createRemotePresence=function(n){return new oL(this,n)};var iL=sL;function sL(n,t,e,o,r){this.id=n,this.v=t,this.type=e,this.data=o,this.m=r}var lL=iL,f2=Hi,m2=su;function su(n,t,e,o,r){if(f2.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}f2.mixin(su),su.prototype.send=function(){!this.connection.canSend||(this.connection.send(this._message()),this.sent=!0)},su.prototype._onConnectionStateChanged=function(){this.connection.canSend?this.sent||this.send():this.sent=!1},su.prototype._handleResponse=function(n,t){if(this.emit("ready"),n)return this.callback(n);var e=t.meta?t.meta:null,o=new lL(this.id,t.v,t.type,t.data,e);this.callback(null,o)};var g2=m2,cL=No,aL=Vs.ACTIONS,uL=P1;function P1(n,t,e,o,r,i){if(g2.call(this,n,t,e,o,i),!cL.isValidVersion(r))throw new Error("Snapshot version must be a positive integer or null");this.version=r}P1.prototype=Object.create(g2.prototype),P1.prototype._message=function(){return{a:aL.snapshotFetch,id:this.requestId,c:this.collection,d:this.id,v:this.version}};var p2=m2,dL=No,hL=Vs.ACTIONS,fL=N1;function N1(n,t,e,o,r,i){if(p2.call(this,n,t,e,o,i),!dL.isValidTimestamp(r))throw new Error("Snapshot timestamp must be a positive integer or null");this.timestamp=r}N1.prototype=Object.create(p2.prototype),N1.prototype._message=function(){return{a:hL.snapshotFetchByTimestamp,id:this.requestId,c:this.collection,d:this.id,ts:this.timestamp}};var mL=HM,gL=WM,pL=c2,C2=rL,CL=uL,bL=fL,b2=Hi,uc=rf,ee=Vs.ACTIONS,A2=eu,jo=No,lu=Qk,cu=uc.CODES;function v2(n){return n.readyState===0||n.readyState===1?"connecting":"disconnected"}var AL=Bt;function Bt(n){b2.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=v2(n),this.bindToSocket(n)}b2.mixin(Bt),Bt.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=v2(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{lu.warn("Failed to parse message",o);return}e.debug&&lu.info("RECV",JSON.stringify(r));var i={data:r};if(e.emit("receive",i),!!i.data)try{e.handleMessage(i.data)}catch(s){jo.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)}},Bt.prototype.handleMessage=function(n){var t=null;switch(n.error&&(t=y2(n.error,n),delete n.error),n.a){case ee.initLegacy:return this._handleLegacyInit(n);case ee.handshake:return this._handleHandshake(t,n);case ee.queryFetch:var e=this.queries[n.id];e&&e._handleFetch(t,n.data,n.extra);return;case ee.querySubscribe:var e=this.queries[n.id];e&&e._handleSubscribe(t,n.data,n.extra);return;case ee.queryUnsubscribe:return;case ee.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 ee.bulkFetch:return this._handleBulkMessage(t,n,"_handleFetch");case ee.bulkSubscribe:case ee.bulkUnsubscribe:return this._handleBulkMessage(t,n,"_handleSubscribe");case ee.snapshotFetch:case ee.snapshotFetchByTimestamp:return this._handleSnapshotFetch(t,n);case ee.fetch:var o=this.getExisting(n.c,n.d);o&&o._handleFetch(t,n.data);return;case ee.subscribe:case ee.unsubscribe:var o=this.getExisting(n.c,n.d);o&&o._handleSubscribe(t,n.data);return;case ee.op:var o=this.getExisting(n.c,n.d);o&&o._handleOp(t,n);return;case ee.presence:return this._handlePresence(t,n);case ee.presenceSubscribe:return this._handlePresenceSubscribe(t,n);case ee.presenceUnsubscribe:return this._handlePresenceUnsubscribe(t,n);case ee.presenceRequest:return this._handlePresenceRequest(t,n);case ee.pingPong:return this._handlePingPong(t);default:lu.warn("Ignoring unrecognized message",n)}};function y2(n,t){var e=new Error(n.message);return e.code=n.code,t&&(e.data=t),e}Bt.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](y2(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 lu.error("Invalid bulk message",t)},Bt.prototype._reset=function(){this.agent=null},Bt.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 uc(cu.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)}},Bt.prototype.startBulk=function(){this.bulk||(this.bulk={})},Bt.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},Bt.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})}},Bt.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)}},Bt.prototype.sendFetch=function(n){return this._sendActions(ee.fetch,n,n.version)},Bt.prototype.sendSubscribe=function(n){return this._sendActions(ee.subscribe,n,n.version)},Bt.prototype.sendUnsubscribe=function(n){return this._sendActions(ee.unsubscribe,n)},Bt.prototype.sendOp=function(n,t){this._addDoc(n);var e={a:ee.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)},Bt.prototype.send=function(n){this.debug&&lu.info("SEND",JSON.stringify(n)),this.emit("send",n),this.socket.send(JSON.stringify(n))},Bt.prototype.ping=function(){if(!this.canSend)throw new uc(cu.ERR_CANNOT_PING_OFFLINE,"Socket must be CONNECTED to ping");var n={a:ee.pingPong};this.send(n)},Bt.prototype.close=function(){this.socket.close()},Bt.prototype.getExisting=function(n,t){if(this.collections[n])return this.collections[n][t]},Bt.prototype.get=function(n,t){var e=this.collections[n]||(this.collections[n]={}),o=e[t];return o||(o=e[t]=new mL(this,n,t),this.emit("doc",o)),o._wantsDestroy=!1,o},Bt.prototype._destroyDoc=function(n){!n._wantsDestroy||(jo.digAndRemove(this.collections,n.collection,n.id),n.emit("destroy"))},Bt.prototype._addDoc=function(n){var t=this.collections[n.collection];t||(t=this.collections[n.collection]={}),t[n.id]!==n&&(t[n.id]=n)},Bt.prototype._createQuery=function(n,t,e,o,r){var i=this.nextQueryId++,s=new gL(n,this,i,t,e,o,r);return this.queries[i]=s,s.send(),s},Bt.prototype._destroyQuery=function(n){delete this.queries[n.id]},Bt.prototype.createFetchQuery=function(n,t,e,o){return this._createQuery(ee.queryFetch,n,t,e,o)},Bt.prototype.createSubscribeQuery=function(n,t,e,o){return this._createQuery(ee.querySubscribe,n,t,e,o)},Bt.prototype.hasPending=function(){return!!(this._firstDoc(df)||this._firstQuery(df)||this._firstSnapshotRequest())};function df(n){return n.hasPending()}Bt.prototype.hasWritePending=function(){return!!this._firstDoc(vL)};function vL(n){return n.hasWritePending()}Bt.prototype.whenNothingPending=function(n){var t=this._firstDoc(df);if(t){t.once("nothing pending",this._nothingPendingRetry(n));return}var e=this._firstQuery(df);if(e){e.once("ready",this._nothingPendingRetry(n));return}var o=this._firstSnapshotRequest();if(o){o.once("ready",this._nothingPendingRetry(n));return}jo.nextTick(n)},Bt.prototype._nothingPendingRetry=function(n){var t=this;return function(){jo.nextTick(function(){t.whenNothingPending(n)})}},Bt.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}}},Bt.prototype._firstQuery=function(n){for(var t in this.queries){var e=this.queries[t];if(n(e))return e}},Bt.prototype._firstSnapshotRequest=function(){for(var n in this._snapshotRequests)return this._snapshotRequests[n]},Bt.prototype.fetchSnapshot=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new CL(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},Bt.prototype.fetchSnapshotByTimestamp=function(n,t,e,o){typeof e=="function"&&(o=e,e=null);var r=this.nextSnapshotRequestId++,i=new bL(this,r,n,t,e,o);this._snapshotRequests[i.requestId]=i,i.send()},Bt.prototype._handleSnapshotFetch=function(n,t){var e=this._snapshotRequests[t.id];!e||(delete this._snapshotRequests[t.id],e._handleResponse(n,t))},Bt.prototype._handleLegacyInit=function(n){if(n.protocolMinor)return this._initializeHandshake();this._initialize(n)},Bt.prototype._initializeHandshake=function(){this.send({a:ee.handshake,id:this.id})},Bt.prototype._handleHandshake=function(n,t){if(n)return this.emit("error",n);this._initialize(t)},Bt.prototype._handlePingPong=function(n){if(n)return this.emit("error",n);this.emit("pong")},Bt.prototype._initialize=function(n){if(this.state==="connecting"){if(n.protocol!==1)return this.emit("error",new uc(cu.ERR_PROTOCOL_VERSION_NOT_SUPPORTED,"Unsupported protocol version: "+n.protocol));if(A2.map[n.type]!==A2.defaultType)return this.emit("error",new uc(cu.ERR_DEFAULT_TYPE_MISMATCH,n.type+" does not match the server default type"));if(typeof n.id!="string")return this.emit("error",new uc(cu.ERR_CLIENT_ID_BADLY_FORMED,"Client id must be a string"));this.id=n.id,this._setState("connected")}},Bt.prototype.getPresence=function(n){var t=this,e=jo.digOrCreate(this._presences,n,function(){return new pL(t,n)});return e._wantsDestroy=!1,e},Bt.prototype.getDocPresence=function(n,t){var e=C2.channel(n,t),o=this,r=jo.digOrCreate(this._presences,e,function(){return new C2(o,n,t)});return r._wantsDestroy=!1,r},Bt.prototype._sendPresenceAction=function(n,t,e){this._addPresence(e);var o={a:n,ch:e.channel,seq:t};return this.send(o),o.seq},Bt.prototype._addPresence=function(n){jo.digOrCreate(this._presences,n.channel,function(){return n})},Bt.prototype._handlePresenceSubscribe=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._handleSubscribe(n,t.seq)},Bt.prototype._handlePresenceUnsubscribe=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._handleUnsubscribe(n,t.seq)},Bt.prototype._handlePresence=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._receiveUpdate(n,t)},Bt.prototype._handlePresenceRequest=function(n,t){var e=jo.dig(this._presences,t.ch);e&&e._broadcastAllLocalPresence(n,t)};var k2=AL,yL=eu;const hf={err:1001,msg:"user auth error",name:"AuthError"},kL={err:1002,msg:"you don't have required permission",name:"PermissionError"},$1={err:1003,msg:"Too many user connected",name:"MaxUserError"},au={err:1004,msg:"document server changed, reload it",name:"RequestReloadError"},wL={err:1005,msg:"app id must be at least 2 chars, doc id must be at least 5 chars",name:"DocIdError"},BL={err:1028,msg:"upload file ext not allowed",name:"FileExtError"},uu="x-live-editor-token",ff="x-live-editor-base-url",bn=M("auth-connection");function EL(n){try{n()}catch(t){bn.error(t)}}class xL{constructor(t,e){m(this,"enabled",!0);m(this,"connection");m(this,"ws");m(this,"retryCount");m(this,"events",new Av.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 Li(this.getBaseURL())}async auth(t){g(bn,t.token,"no auth token");const e=`${this.getBaseURL()}/auth`,o=await window.fetch(e,{method:"GET",headers:{[uu]:t.token,[ff]:this.getBase64BaseURL()},credentials:"include"});if(o.status!==200)throw new Error("http auth error");return this.enabled?(this.token=t.token,await o.json()):{read:"",user:""}}async logout(){if(!this.token)return;const t=`${this.getBaseURL()}/logout`;await window.fetch(t,{method:"GET",headers:{[ff]:Li(this.getBaseURL())}})}async init(t){const e=await this.auth(t);if(!this.enabled)return;this.resourceToken=e.read,this.ws=new nI.default(this.url,void 0,{maxReconnectionDelay:2500,minReconnectionDelay:1e3}),this.connection=Object.create(k2.prototype),g(bn,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}}},k2.apply(this.connection,[this.ws])}async handleAuthError(){if(this.reauthFunc&&this.retryCount<5){this.retryCount+=1,bn.info(`retrying re-auth attempt no. ${this.retryCount}`);try{if(this.connection){const t=await this.reauthFunc();if(await this.auth(t),!this.enabled){this.retryCount=10,setTimeout(()=>this.handleAuthError(),0);return}this.connection._initializeHandshake=function(){this.send({a:"hs",id:this.id,auth:t})}}}catch(t){bn.error(t),setTimeout(()=>this.handleAuthError(),0)}}else bn.error("auth error, cannot retry anymore"),this.emitAuthError(),this.end(!1)}emitAuthError(){const t=new Error(hf.msg);t.code=hf.err,this.events.emit("error",t)}emitRequestReloadError(){const t=new Error(au.msg);t.code=au.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===hf.err)bn.warn("auth error"),this.handleAuthError();else if(o===$1.err)bn.warn($1.msg),this.emitMaxUsersError();else if(o===au.err){bn.warn(au.msg);try{this.emitRequestReloadError()}catch(r){bn.error(`error occurred while process reload error: ${JSON.stringify(r)}`)}finally{this.end(!1)}}else bn.error(`unknown message received: ${JSON.stringify(e)}`),this.emitAuthError()}get(t,e){return g(bn,this.connection,"no this.connection"),this.connection.get(t,e)}addEventListener(t,e){t==="error"?this.events.addListener(t,e):(g(bn,this.ws,"no this.ws"),this.ws.addEventListener(t,e))}onWriteConflictError(t){this.events.addListener("writeConflictError",t)}onMaxUsersError(t){g(bn,this.events.listenerCount("maxUsersError")===0,"too many maxUserError listener"),this.events.addListener("maxUsersError",t)}onRequestReloadError(t){g(bn,this.events.listenerCount("requestReloadError")===0,"to many requestReloadError listener"),this.events.addListener("requestReloadError",t)}end(t){var e;this.enabled=!1,this.reauthFunc=void 0,this.events.removeAllListeners(),EL(()=>{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()}}M("utils/file");function IL(){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}IL();async function TL(n){const e=n.size,o=Math.floor((e+102400-1)/102400),r=new oI.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 Li(i)}const mr=M("sharedb-doc/client"),SL=tI.default.create();class DL{constructor(t,e,o){m(this,"connection");m(this,"auth");m(this,"doc",null);m(this,"reauthFunc");m(this,"clientId",tt());m(this,"getDoc",async()=>{const t=o=>new Promise((r,i)=>{o.fetch(s=>{s?i(s):r()})});g(mr,!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),mr.debug(e),e});this.auth=t;const r=`${e}/${this.auth.appId}/${this.auth.docId}`;yL.register(Jd.type),this.connection=new xL(r,o),this.reauthFunc=o}editorServer(){const t=this.apiServer(),e=`/${this.auth.appId}/${this.auth.docId}`;return g(mr,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,{[uu]: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=>{mr.info(`on progress: ${v.loaded}`);let B=v.loaded*100/s;B>100&&(B=100),r(B)},a=await TL(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 C=await this.request(h,{method:"post",data:p,withCredentials:!0,headers:{...o},onUploadProgress:l});return mr.info(C),r(100),Array.isArray(C.data)?C.data[0]:C.data}async uploadResource(t,e=()=>{},o){const i=`${this.apiServer()}/resources`;g(mr,this.connection.token,"no connection token");const s=await this.uploadFile(i,t,{[uu]:this.connection.token},e,o);return g(mr,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(mr,o,"no token"),a.headers={...a.headers,[uu]:o,[ff]:this.connection.getBase64BaseURL()};try{return await SL(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(mr,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=eI.default(s,h=>!!h.create);let a=null;l!==-1&&(a=s[l],s.splice(0,l+1));let d;return a?(g(mr,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/${Li(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 ML(){return{blocks:[{id:tt(),type:"text",text:[]}],comments:{},meta:{}}}const H1=M("block-ids");class LL{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(H1,s!==void 0,"old id is not exists"),this.ids.delete(i),this.ids.set(i+1,s)}}const o=tt();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(H1,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=tt(),this.ids.set(t,e)),e}getById(t){return Array.from(this.ids.entries()).find(([,e])=>e===t)}}class RL{constructor(){m(this,"ids",new Map)}getContainerIds(t){let e=this.ids.get(t);return e||(e=new LL,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(H1,!1,"fault error: failed to get block index"),{containerId:"error",blockIndex:-1}}}class w2{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 j1=M("op-parse-handler");class OL{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 RL,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&&(j1.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)){j1.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 w2,o.set(d,h)),h.delete(l.key)}else g(j1,!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 w2,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);this.outerHandler.onUpdateBlockData(a,d,l.toDocBlockDelta(),this.local)})}}const Ne=M("op-parser");class B2{}class U1{constructor(t){m(this,"key");this.key=t}}function _L(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(Ne,s.id,"block id is required"),g(Ne,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 z1(n,t,e,o){if(e==="upsert"&&_L(n,t,o))return;g(Ne,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(Ne,typeof a=="object",`invalid block op: ${n}, ${JSON.stringify(t)}`),g(Ne,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(Ne,r.length===0,`invalid block ops.length !== 0, ${JSON.stringify(r)}`)}else if(Array.isArray(l)){g(Ne,l.length===2,`invalid block op: data.length !== 2, ${JSON.stringify(l)}`);const a=l[0];g(Ne,typeof a=="string",`invalid block op: key ${JSON.stringify(a)}`);const d=l[1];if(a==="text"){if(g(Ne,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 U1(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 B2),e==="upsert"&&a.i&&o.onInsertBlock(n,i,a.i),r.shift()}else{g(Ne,typeof l=="string","data is not string"),g(Ne,l!=="text","data !== 'text'"),g(Ne,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 U1(a)),e==="upsert"&&d.i&&o.onInsertBlockData(n,i,a,d.i),r.splice(0,2)}}s.reverse(),s.forEach(l=>{l instanceof B2?o.onDeleteBlock(n,i):l instanceof U1?o.onDeleteBlockData(n,i,l.key):g(Ne,!1,`invalid action type: ${typeof l}, ${JSON.stringify(l)}`)})}function FL(n,t,e){Ne.warn(`unsupported meta op, ${JSON.stringify(n)}`)}function PL(n,t,e){const o=n[1],r=n[2];g(Ne,o,`invalid comment op, no commentId: ${JSON.stringify(n)}`),g(Ne,r,`invalid comment op, no actions: ${JSON.stringify(n)}`),typeof r=="string"?Ne.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):Ne.error(`unknown comment op, ${JSON.stringify(n)}`)}function V1(n,t,e){const o=n[0];if(Array.isArray(o)){o.forEach(s=>{V1(s,t,e)});return}const r=o;if(g(Ne,typeof r=="string",`invalid container id: ${JSON.stringify(n)}`),r==="meta"){FL(n);return}if(r==="comments"){PL(n,t,e);return}const i=r;if(Array.isArray(n[1]))t==="remove"?n.slice(1).reverse().forEach(s=>{z1(i,s,t,e)}):n.slice(1).forEach(s=>{z1(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(Ne,typeof n[1]=="number",`invalid ops[1], not a number: ${JSON.stringify(n)}`),z1(i,n.slice(1),t,e)}function E2(n,t,e){const o=new OL(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=>{V1(a,i,o)}):V1(s,i,o)}o.end()}const NL=M("sharedb-comments");function W1(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 x2(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 q1(n,t){const e=yM(t),{comments:o,meta:r,blocks:i,...s}=e,l={...n,blocks:i,...s},a=mt.default(l);return delete a.children,a}const ne=M("sharedb-doc/doc-container"),I2="ot-json1";Jd.type.registerSubtype(kM.type),Jd.type.name=I2,Jd.type.invert=null;class du extends Ba{constructor(e,o,r=!0){super();m(this,"doc");m(this,"client");m(this,"localPresence");m(this,"remoteCaretHandler",new AM);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(!ka.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){ne.warn("submit op after destroyed");return}this.setStatus("dirty"),this.doc.submitOp(e,{},i=>{i?(ne.error(`invalid op, ${i.message}, ${JSON.stringify(e)}`),r(i),ne.error("Transform detected write conflict, reload editor"),this.handleReset("write conflict")):o()}),this.doc.data||(ne.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,I2,i=>{i?r(i):o()})}));m(this,"submitInsertChildContainers",async e=>{if(e.length===0)return Promise.resolve();const o=e.map(({containerId:r,blocks:i})=>[Jr(r),{i}]);return this.submitOp([o])});m(this,"submitDeleteChildContainer",async e=>{const o=[Jr(e),{r:!0}];return this.submitOp(o)});m(this,"submitInsertBlock",async(e,o,r)=>{const i=[Jr(e),o,{i:r}];return this.submitOp(i)});m(this,"submitDeleteBlock",async(e,o)=>{const r=[Jr(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=[Jr(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=[Jr(e),o,"text",{e:r,et:"rich-text"}];return this.submitOp(i)});m(this,"handleOp",(e,o,r)=>{if(this.destroyed){ne.warn("handleOp: destroyed");return}try{E2(e,this,!!o)}catch(i){throw ne.error(i),i}});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(ne,this.batching>=0,"invalid call beginBatchUpdate/endBatchUpdate"),this.batching===0&&(this.doc.preventCompose=!0),this.batching}static async load(e){try{const o=new DL(e.auth,e.serverUrl,e.reauthFunc),r=await o.getDoc(),i=new du(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||ML())}return await i.initPresence(),await i.subscribe(),i.initEvents(),i}catch(o){throw ne.error(o),ne.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(tt()),e())})}})}subscribe(){return new Promise((e,o)=>{this.doc.subscribe(r=>{r?o(r):(this.doc.on("op",this.handleOp),e())})})}toJSON(){return tu(this.data())}getContainerBlocks(e){const o=this.data();g(ne,o,"no doc data");const r=o[Jr(e)];return g(ne,r,`no container data: ${e}`),mt.default(r)}findContainerBlocks(e){const o=this.data();g(ne,o,"no doc data");const r=o[Jr(e)];return r!=null?r:null}getBlockData(e,o){const r=this.data();g(ne,r,"no doc data");const i=r[Jr(e)];g(ne,i,`no container data: ${e}`);const s=i[o];return g(ne,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(ne,i.text,"no block text");const s=mt.default(i.text);this.submitUpdateRichText(e,o,r);const l=cn.apply(s,r);return g(ne,l,"no block text"),l}localUpdateBlockData(e,o,r){const i=mt.default(this.getBlockData(e,o));return this.submitUpdateBlockData(e,o,r),i}localInsertChildContainers(e){this.submitInsertChildContainers(e)}localDeleteChildContainers(e){this.beginBatchUpdate(),e.forEach(o=>{this.submitDeleteChildContainer(o)}),this.endBatchUpdate()}getComments(){return Object.values(this.data().comments).map(o=>x2(o))}getComment(e){return this.data().comments[e]}getCommentDoc(e){const o=this.data().comments[e];return W1(o)}localCreateComment(e,o){const r=q1(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=q1(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(ne,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(i=>{var s;return(s=i.onDeleteBlock)==null?void 0:s.call(i,cc(e),o,r)})}onInsertBlock(e,o,r,i){g(ne,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onInsertBlock)==null?void 0:l.call(s,cc(e),o,r,i)})}onUpdateBlockData(e,o,r,i){g(ne,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockData)==null?void 0:l.call(s,cc(e),o,r,i)})}onUpdateBlockText(e,o,r,i){g(ne,this.callbacks.length>0,"no callbacks"),this.callbacks.forEach(s=>{var l;return(l=s.onUpdateBlockText)==null?void 0:l.call(s,cc(e),o,r,i)})}onDeleteContainer(e,o){g(ne,this.callbacks.length>0,"no callbacks"),g(ne,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,cc(e),o)})}onCreateContainer(e,o,r){g(ne,this.callbacks.length>0,"no callbacks"),g(ne,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,cc(e),o,r)})}onDeleteComment(e,o){g(ne,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(ne,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(ne,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 tu(o)}async getLatestVersion(){const e=await this.client.getLatestVersion();return tu(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:tu(r),historyData:s}}async getVersionData(e,o){const{doc:r,ops:i}=await this.client.getVersionOps(e,o);return{doc:tu(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){E2(e.data.op,o,!0)}getServerMeta(){return{appId:this.client.auth.appId,docId:this.client.auth.docId,serverId:this.client.apiServer()}}}M("remote-cursor");class T2{constructor(t){m(this,"handleDocSelectionChange",()=>{this.broadcastCaretPos()});m(this,"broadcastCaretPos",Fe.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 S2=M("remote-cursor-decorator");class G1{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(S2,typeof s=="string","invalid path containerId"),g(S2,typeof l=="number","invalid path blockIndex");const a=t.doc.getBlockData(s,l),d=sn(o);return r.getSimpleCursors(a.id).forEach((p,C)=>{C>d&&(C=d);const v=p.map(x=>({id:tt(),type:"remote-cursor",name:x.user.displayName,time:x.time,rainbowIndex:x.user.rainbowIndex})),B=i.get(C);B?B.push(...v):i.set(C,v)}),{insertions:i}}}class D2 extends ke.TypedEmitter{constructor(t){super(),this.editor=t,this.editor.doc.registerCallback(this)}handleChild(t,e,o){if(Qt(ir(this.editor,t)))return;const r=this.editor.getBlockByIndex(t,e),i=nt(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 $L(n,t){n.addCustom("child-block-tracker",()=>new D2(n)).addListener("change",t)}function HL(n,t){n.addCustom("child-block-tracker",()=>new D2(n)).removeListener("change",t)}const kot="",jL={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"}},UL={colorPalette:{colorDesc:"Text color",name:"Text color",backgroundDesc:"Background color",reset:"Restore default values"},search:{emptyTips:"No results found"}},zL={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"}};L.mergeLang({"zh-CN":jL,"en-US":UL,"ja-JP":zL});const wot="";M("button");function mo(n,t,e,o,r){const i=k("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&&V(i,"checked"),o.indexOf("disabled")!==-1&&(i.disabled=!0),o.indexOf("primary")!==-1&&V(i,"primary")),i}const Bot="",mf=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
28
28
|
<path d="M8.00874 7.89952L12.9497 2.94975M8.00874 7.89952L12.9497 12.8492M8.00874 7.89952L3.05025 12.8492M8.00874 7.89952L3.05025 2.94975" stroke="currentColor" stroke-linejoin="round"/>
|
|
29
29
|
</svg>
|
|
30
30
|
`,M2=`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
@@ -597,7 +597,7 @@ Available method signatures are:
|
|
|
597
597
|
`,lR=Object.freeze(Object.defineProperty({__proto__:null,ClearIcon:pw,CloseIcon:mf,PrevIcon:M2,NextIcon:L2,MoreIcon:Q1,TextColorIcon:Z1,ArrowDownIcon:gf,ArrowUpIcon:VL,ArrowLeftIcon:WL,ArrowRightIcon:Y1,DeleteRowIcon:R2,DeleteColIcon:O2,MergeCellIcon:_2,SplitCellIcon:F2,DeleteTableIcon:P2,Heading1Icon:pf,Heading2Icon:Cf,Heading3Icon:bf,Heading4Icon:Af,Heading5Icon:vf,Heading6Icon:yf,Heading7Icon:kf,Heading8Icon:wf,HeadingNIcon:qL,OrderedListIcon:N2,UnorderedListIcon:$2,CheckListIcon:H2,BlockquoteIcon:j2,AlignCenterIcon:Ef,AlignLeftIcon:dc,AlignRightIcon:Bf,ImageIcon:U2,ImageMenuIcon:z2,ImageErrorIcon:K1,ImageEmptyIcon:W2,LinkIcon:e0,LinkOffIcon:q2,WarningIcon:J1,PasteSpecialIcon:V2,LaunchIcon:X1,CodeIcon:lw,AudioIcon:ow,GraphIcon:GL,VideoIcon:rw,FileIcon:QL,MathIcon:YL,MathMenuIcon:G2,TableIcon:JL,TableMenuIcon:Q2,BilibiliIcon:J2,YoukuIcon:K2,ModaoIcon:tw,FigmaIcon:X2,EditIcon:xf,CommentIcon:Ws,RefreshIcon:Z2,HelpIcon:t0,CheckMarkIcon:Y2,TextIcon:hc,RightArrowIcon:ZL,TencentVideoIcon:ew,WebPageIcon:nw,UmlIcon:iw,DividingLineIcon:sw,HeadingH1Icon:KL,HeadingH2Icon:XL,HeadingH3Icon:tR,HeadingH4Icon:eR,HeadingH5Icon:nR,HeadingH6Icon:oR,HeadingH7Icon:rR,HeadingH8Icon:iR,CheckboxIcon:n0,QuoteIcon:o0,LinkHrefIcon:sR,OrderedIcon:i0,UnorderedIcon:r0,CopyIcon:cw,CutIcon:aw,DeleteIcon:uw,LockBlockIcon:dw,UnLockBlockIcon:hw,InsertBeforeIcon:fw,InsertAfterIcon:mw,MentionIcon:gw,CircleAddIcon:Cw,LoadingIcon:bw,DragIcon:s0,UmlBrandIcon:If,OnesLoadingIcon:Aw,BoldIcon:vw,ItalicIcon:yw,UnderlineIcon:kw,LineThroughIcon:ww,SubscriptIcon:Ew,SuperscriptIcon:xw,InlineCodeIcon:Bw,ToMindMapIcon:Iw,FitIcon:Tw,FullScreenIcon:l0,ExitFullScreenIcon:Sw,CaretDownIcon:Dw},Symbol.toStringTag,{value:"Module"}));function Mw(){const n=k("span",["editor-loading-icon"],null);return n.innerHTML=Aw,n}const Eot="";function cR(n,t){const e=k("button",["editor-checkbox-wrapper"],null);e.setAttribute("data-button-id",n),t!=null&&t.includes("checked")&&V(e,"checked"),t!=null&&t.includes("disabled")&&(e.disabled=!0);const o=k("span",["editor-checkbox"],e);return k("span",["editor-checkbox-inner"],o),e}const xot="",fc=M("ui-command-bar-base"),aR={itemElementTag:"div",tippyArrow:!1},Eb=class extends ke.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&&!Ds(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),r5(this.id)});m(this,"handleShow",()=>{this.popper&&(this.popper.setAttribute("data-command-bar-id",this.id),this.options.classes&&V(this.popper,...this.options.classes),this.options.refuseOverflow&&this.popper.classList.add("reference-hidden")),this.emit("show",this),this.options.disablePageScroll&&o5(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)&&(rt(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=lo(r);if(!Xt(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:tt(),this.options={...aR,...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&&rt(o,"selected")}selectItem(e){const o=this.getSelectedItem();if(o){if(o.id===e)return;const i=o.id,s=this.getItemElementById(i);s&&rt(s,"selected")}const r=this.getItemElementById(e);r?(V(r,"selected"),this.emit("selectionChange",this,r.getAttribute("data-id")||""),this.options.disableSelectedScroll||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=Eb.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,rt(r,"active")}),o.beforePopup&&o.beforePopup(i),this.subBar.manualShow(r,this.getSubBarOptions(o)),V(r,"active")}isInCommandBar(e){if(!e||!(e instanceof Node))return!1;const o=this.getCommandBarRoot();return o&&Xt(o,e)||Xt(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=k(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(fc,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(fc,r,`can not find command item for id: ${o}`),r}return null}getItemElementId(e){const o=e.getAttribute("data-id");return g(fc,o,"no data-id attribute"),o}getItemElementById(e){const o=this.content.querySelector(`:scope >.editor-command-bar > .command-item[data-id="${e}"]`);return g(fc,o,`no exists command item, id=${e}`),o}getParentCommandItemElement(e){if(!e||!(e instanceof Element))return null;if(Et(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=k("div",["editor-command-bar-root"],null);if(this.options.header){const i=k("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=k("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=k("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)&&V(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",offset:e.childrenOffset,arrow:e.childArrow}}static registerManualCommandBar(e,o){this.commandBarCreators.set(e,o)}static createSubCommandBar(e,o,r){var l;g(fc,e.children&&e.children.length>0,"no item children");const i=(l=e.childrenType)!=null?l:"menu",s=this.commandBarCreators.get(i);return g(fc,s,`no creator for command type: ${i}`),s(e,o,r)}static hasExistsCommandBar(){return!!document.querySelector("[data-command-bar-id]")}};let qs=Eb;m(qs,"commandBarCreators",new Map),M("ui-command-bar");class Tf extends qs{constructor(){super(...arguments);m(this,"tippyInstance",null)}manualShow(e,o){var r,i,s;if(!this.isVisible){if(this.tippyInstance&&(this.tippyInstance.destroy(),this.tippyInstance=null),this.tippyInstance=rI.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:(i=o==null?void 0:o.arrow)!=null?i: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:(s=o==null?void 0:o.offset)!=null?s:[0,0],popperOptions:this.createPopperOptions()}),o!=null&&o.point){const{x:l,y:a}=o.point;this.tippyInstance.setProps({getReferenceClientRect:()=>new DOMRect(l,a,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 Lw=M("ui-base");class hu extends Tf{constructor(t,e){var i;const r=[{id:(i=e==null?void 0:e.id)!=null?i:`popup-${tt()}`,name:"",element:t}];super(r,void 0,{disablePageScroll:!0})}initCommandBarElement(t){V(t,"popper")}initItemElement(t,e){}get popupContent(){const t=this.items[0];g(Lw,t,"no dialog item");const e=typeof t.element=="function"?t.element(t):t.element;return g(Lw,e,"no item element"),e}}const Ui=M("filterable-list");function Rw(n){var e,o;const t=k("div",["list-item"],null);return t.setAttribute("data-id",n.id),t.appendChild(k("div",["list-item-text"],null,n.name)),(e=n.states)!=null&&e.includes("selected")&&V(t,"selected"),(o=n.states)!=null&&o.includes("disabled")&&V(t,"disabled"),t}function Ow(n){const t=k("div",["list-root"],null);return n.forEach(e=>{t.appendChild(Rw(e))}),n.length||t.appendChild(Rw({id:"placeholder",states:["disabled"],name:L.t("search.emptyTips")})),t}function _w(n,t){let e=n;return t&&(e=n.map(o=>({...o,states:o.id===t?["selected"]:void 0}))),e}function uR(n,t){const e=k("div",["filterable-list"],null),o=k("div",["filter"],e),r=k("div",["filter-container"],o),i=k("input",["filter-input"],r);t&&t.placeholder&&(i.placeholder=t.placeholder);const s=k("div",["list"],e),l=Ow(_w(n,t==null?void 0:t.initialSelectedId));return s.appendChild(l),e}function Fw(n,t,e){const o=n.querySelector(".list");g(Ui,o,"no list root");const r=Ow(_w(t,e)),i=o.querySelector(".list-root");if(g(Ui,i,"no exists menu"),Da(i,r),e){const s=o.querySelector(".list-item.selected");s&&(g(Ui,s,"no selected menu item"),s.scrollIntoView({block:"nearest"}))}}class dR{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(Ui,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=uR(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(Ui,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(Ui,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,Fw(this.root,this.visibleItems,t)}focus(){const t=this.root.querySelector(".filter-input");g(Ui,t,"no input"),t.focus()}reset(){this.setFilter("");const t=this.root.querySelector(".filter-input");g(Ui,t,"no input"),t.value=""}setFilter(t){this.filter!==t&&(this.filter=t,this.visibleItems=this.items.filter(e=>e.name.toLocaleLowerCase().includes(t)),Fw(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 hR extends dR{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 hu(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 Iot="",Tot="";function fR(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)}function mR(n,t){var e,o;if(V(t,"menu-item"),!n.element){if(n.type==="section"){const r=k("div",["section-name"],null,n.name);t.appendChild(r)}else if(n.type!=="separator"){if(n.icon){const i=k("div",["menu-item-icon"],null);n.icon&&(i.innerHTML=n.icon),t.appendChild(i)}const r=k("div",["menu-item-name","text"],null);if(k("span",[],r,n.name),n.ellipsisTooltip&&(t.setAttribute("data-editor-tooltip-allow-markdown","true"),t.setAttribute("data-editor-tooltip-offset-y","25"),t.setAttribute("data-editor-tooltip-placement","right"),t.setAttribute("data-editor-tooltip-common",`<div style="word-break: break-word;">${n.ellipsisTooltip}</div>`)),((e=n.states)==null?void 0:e.includes("disabled"))&&n.disableReason&&(t.setAttribute("data-editor-tooltip-maxwidth","800"),t.setAttribute("data-editor-tooltip-placement","right"),t.setAttribute("data-editor-tooltip-common",n.disableReason)),t.appendChild(r),n.subText&&k("div",["item-subtext","text"],t,n.subText),n.children&&!n.element){const i=k("div",["menu-item-sub-indicator"],null);i.innerHTML=Y1,t.appendChild(i)}if((o=n.states)!=null&&o.includes("checked")){const i=k("div",["menu-item-checked-icon"],null);i.innerHTML=Y2,t.appendChild(i)}}}}class Gs extends Tf{constructor(t,e,o){super(t,e,{autoClose:!0,disablePageScroll:!0,...o})}manualShow(t,e){const o={theme:"menu",...e};super.manualShow(t,o)}initCommandBarElement(t){V(t,"menu")}initItemElement(t,e){mR(t,e)}}function gR(n,t,e){var o;return new Gs((o=n.children)!=null?o:[],t,{...e,parentItem:n})}function Pw(n,t,e){t.setAttribute("data-button-id",n.id),e.tooltipId&&n.name&&!n.disableTooltip&&(t.setAttribute(`data-editor-tooltip-${e.tooltipId}`,n.name),n.desc&&t.setAttribute(`data-editor-tooltip-desc-${e.tooltipId}`,n.desc));const o=t;if(!n.element)if(n.icon){const r=k("span",["toolbar-item-icon-container"],o);n.icon.trim().startsWith("<")?r.innerHTML=n.icon:r.innerText=n.icon}else{const r=k("span",["toolbar-item-name-container"],o);r.innerText=n.name}if(n.dropdown){t.setAttribute("data-dropdown","true");const r=k("span",["toolbar-item-dropdown-container"],o);r.innerHTML=gf}n.states&&(n.states.indexOf("checked")!==-1&&V(o,"checked"),n.states.indexOf("disabled")!==-1&&(o.disabled=!0))}class fu extends Tf{constructor(t,e,o){super(t,e,{itemElementTag:"button",tippyArrow:!1,...o})}getSubBarOptions(t){var r,i;const e=()=>{const s=this.getItemElementById(t.id),a=this.content.getBoundingClientRect(),d=s.getBoundingClientRect();return new DOMRect(d.left,a.top,d.width,a.height)};return{placement:(r=t.childrenPlacement)!=null?r:"top",getReferenceClientRect:e,offset:(i=t.childrenOffset)!=null?i:[0,4]}}manualShow(t,e){const o={theme:"toolbar",...e};super.manualShow(t,o)}initCommandBarElement(t){V(t,"toolbar")}initItemElement(t,e){Pw(t,e,this.options)}}function pR(n,t,e){var o;return new fu((o=n.children)!=null?o:[],t,{...e,parentItem:n})}class CR extends qs{constructor(t,e,o){super(e,void 0,o),t.appendChild(this.content),document.addEventListener("keydown",this.handleDocumentKeydown),document.addEventListener("mousedown",this.handleDocumentMouseDown)}initCommandBarElement(t){V(t,"toolbar","fixed")}initItemElement(t,e){Pw(t,e,this.options)}close(){this.clearSelectedItem(),this.subBar&&(this.subBar.close("cancelBar"),this.subBar=null)}destroy(){this.content.remove(),super.destroy(),document.removeEventListener("keydown",this.handleDocumentKeydown),document.removeEventListener("mousedown",this.handleDocumentMouseDown)}getCommandBarRoot(){return this.content.parentElement}get isVisible(){return!0}}const Sot="";qs.registerManualCommandBar("menu",gR),qs.registerManualCommandBar("toolbar",pR);const Dot="",Nw=M("ui-base");class mu extends Tf{constructor(e,o){super(mu.getCommandItems(e,o),void 0,{disablePageScroll:!0,...o});m(this,"handleDocumentMouseDown",e=>{})}initCommandBarElement(e){V(e,"dialog","manual")}initItemElement(e,o){}show(e,o){this.manualShow(e,{...o,theme:"light"})}get dialogContent(){const e=this.items[0];g(Nw,e,"no dialog item");const o=e.element;return g(Nw,o,"no item element"),o}static getCommandItems(e,o){var s;return[{id:(s=o==null?void 0:o.id)!=null?s:`manual-dialog-${tt()}`,name:"",element:e}]}}const Mot="",bR=M("ui-base");class $w{constructor(t){m(this,"menu");m(this,"currentText","");m(this,"handleSearchText");m(this,"handleClick",Fe.default((t,e)=>{this.options.onClickItem(this,e)},300,{leading:!0,trailing:!1}));m(this,"handleShow",t=>{});m(this,"handleClose",()=>{var t,e;(e=(t=this.options).onClose)==null||e.call(t)});m(this,"handleKeydown",t=>{this.menu.handleDocumentKeydown(t)});this.options=t,this.menu=new Gs([],void 0,{id:t.id,header:t.header,footer:t.footer,disableSelectedScroll:t.disableSelectedScroll}),this.menu.addListener("click",this.handleClick),this.menu.addListener("close",this.handleClose),this.menu.addListener("show",this.handleShow),this.options.wait?this.handleSearchText=Fe.default(async e=>{this.handleSearchTextPure(e)},this.options.wait):this.handleSearchText=this.handleSearchTextPure}setItems(t){if(this.menu.updateItems(t),t.length>0){const e=t.find(o=>o.type!=="section"&&o.type!=="separator");e&&this.menu.selectItem(e.id)}}async popup(t,e){var r,i;if(!(e!=null&&e.noEvent)&&((i=(r=this.options).onShow)==null?void 0:i.call(r,this))===!1)return;this.menu.manualShow(t),this.options.placeholder&&this.showPlaceholder();const o=await this.options.queryItems(this,"");this.highlightText("",o),this.setItems(o)}showLoading(){!this.options.showLoading||(this.options.loadingElement?this.setItems([{id:"loading",name:"",element:this.options.loadingElement,states:["disabled"]}]):this.setItems([{id:"loading",name:"loading",states:["disabled"]}]))}showPlaceholder(){this.setItems([{id:"placeholder",name:"enter text to search",states:["disabled"]}])}showNoResultMessage(t){if(this.options.noResultMessage){const e={name:"",id:"placeholder",states:["disabled"]};typeof this.options.noResultMessage=="string"?e.name=this.options.noResultMessage:(this.options.noResultMessage instanceof HTMLElement||typeof this.options.noResultMessage=="function")&&(e.element=this.options.noResultMessage),this.setItems([e])}else this.setItems([{id:"placeholder",name:this.options.emptyPlaceholder||L.t("search.emptyTips"),states:["disabled"]}])}close(){this.menu.close("cancelBar")}get isVisible(){return this.menu.isVisible}destroy(){this.menu.close("cancelBar"),this.menu.removeAllListeners(),this.menu.destroy()}async handleSearchTextPure(t){this.currentText=t;const e="auto-suggest";try{await Io.lock(e),this.showLoading();const o=this.currentText,r=await this.options.queryItems(this,t);if(this.currentText===o&&(this.currentText=""),r.length===0){this.showNoResultMessage(t);return}this.setItems(r),this.options.highlight&&this.highlightText(o.replace(/^\s+|\s+$/g,""),r)}finally{Io.release(e)}}highlightText(t,e){bR.debug(`highlight menu text: ${t}`);const o=this.menu.content,r=(s,l)=>{if(!l)return s;let a="";const d=l.length,h=l.toLocaleLowerCase();let p=0;for(p=0;p<=s.length-d;p){let C=s.substring(p,p+d);if(C.toLocaleLowerCase()===h){p+=d;const v=s.charAt(p);let B=!1;C.endsWith(" ")&&(B=!0,C=C.trimEnd()),a+=`<span class="highlight">${C}${v===" "||B?" ":""}</span>`}else a+=s.charAt(p),p++}return p<s.length&&(a+=s.substring(p)),a},i=s=>{if(Et(s,"text")){const l=e==null?void 0:e.find(h=>h.id===s.getAttribute("data-id"));if(l&&l.element)return;const a=s.textContent;if(!a)return;const d=r(a,t);s.innerHTML=d;return}Array.from(s.children).forEach(i)};i(o)}}class c0{constructor(t,e){m(this,"root");m(this,"input");m(this,"text");m(this,"dropdownIcon");m(this,"clearIcon");m(this,"autoSuggest");m(this,"labels");m(this,"items",[]);m(this,"handleClick",()=>{this.autoSuggest.popup(this.root),this.input.focus()});m(this,"handleClickItem",(t,e)=>{var o,r;(r=(o=this.options)==null?void 0:o.onClickItem)==null||r.call(o,e)});m(this,"handleInput",()=>{this.autoSuggest.handleSearchText(this.input.value),this.updatePlaceholder()});m(this,"handleClear",t=>{var e,o;this.clear(),this.autoSuggest.handleSearchText(""),t.preventDefault(),t.stopPropagation(),(o=(e=this.options)==null?void 0:e.onClear)==null||o.call(e)});m(this,"handleQueryItems",async(t,e)=>this.items.filter(r=>{var i;return(i=this.options)!=null&&i.filter?this.options.filter(r,e):!0}));m(this,"handleShow",()=>{V(this.root,"active"),this.input.focus()});m(this,"handleClose",()=>{var t,e;(e=(t=this.options)==null?void 0:t.onClose)==null||e.call(t),rt(this.root,"active")});var a,d,h,p,C;this.options=e,this.labels=(d=(a=this.options)==null?void 0:a.labels)!=null?d:[];const{root:o,input:r,text:i,clearIcon:s,dropdownIcon:l}=c0.createDropdown(t,this.labels);this.root=o,this.input=r,this.text=i,this.clearIcon=s,this.dropdownIcon=l,this.autoSuggest=new $w({id:(e==null?void 0:e.popupId)||"dropdown-auto-suggest",header:(h=this.options)==null?void 0:h.header,onClickItem:this.handleClickItem,queryItems:this.handleQueryItems,onClose:this.handleClose,onShow:this.handleShow,highlight:e==null?void 0:e.highlight,emptyPlaceholder:e==null?void 0:e.emptyPlaceholder,disableSelectedScroll:e==null?void 0:e.disableSelectedScroll}),this.items=(C=(p=this.options)==null?void 0:p.items)!=null?C:[],this.root.addEventListener("click",this.handleClick),this.input.addEventListener("input",this.handleInput),this.clearIcon.addEventListener("click",this.handleClear)}close(){this.autoSuggest.close()}destroy(){this.input.removeEventListener("input",this.handleInput),this.root.removeEventListener("click",this.handleClick),this.clearIcon.removeEventListener("click",this.handleClear),this.autoSuggest.destroy()}updateItems(t){this.items=t,this.autoSuggest.handleSearchText("")}setText(t){this.text.innerText=t,this.input.value=t,this.updatePlaceholder()}clear(){this.setText(""),this.setLabels([])}setLabels(t){this.labels=t,this.updateLabels()}static createDropdown(t,e){const o=k("div",["editor-dropdown","empty"],t),r=k("input",["dropdown-input"],o),i=k("div",["dropdown-text"],o),s=k("div",["dropdown-labels"],o);for(let d=0;d<e.length;d+=1){const h=e[d];k("span",["dropdown-label"],s,h)}const l=k("div",["dropdown-clear-icon"],o);l.innerHTML=pw;const a=k("div",["dropdown-icon"],o);return a.innerHTML=gf,{root:o,input:r,text:i,clearIcon:l,dropdownIcon:a}}updateLabels(){const t=this.root.querySelector(".dropdown-labels");if(t){t.innerHTML="";for(let e=0;e<this.labels.length;e+=1){const o=this.labels[e];k("span",["dropdown-label"],t,o)}}}updatePlaceholder(){var t;if(this.input.value===""){const e=(t=this.options)==null?void 0:t.placeholder;e&&(this.input.placeholder=e,this.text.textContent=e),V(this.root,"empty")}else rt(this.root,"empty")}}const AR=[-1,6,0,1,2,3,4,5],vR=[-1,6,0,1,2,3,4,5,14,13,7,8,9,10,11,12],Hw=M("color-palette");function jw(n,t,e,o){g(Hw,n>0,"no color in palette");const r=t||1;g(Hw,r>0,`invalid palette rows: ${r}`);const i=n/r,s=k("div",["palette-container",o],null);for(let l=0;l<r;l++){const a=k("div",["palette-container-row"],s);for(let d=0;d<i;d++){const h=e(l*i+d);a.appendChild(h)}}return s}function yR(n){const t=k("button",["color-button"],null),e=AR[n];return t.setAttribute("data-color-index",`${e}`),t.innerHTML=Z1,t}function kR(n){const t=k("button",["background-color-button"],null),e=vR[n];return t.setAttribute("data-color-index",`${e}`),t}function wR(){const n=k("div",["clear-button-container"],null),t=k("button",["clear-button"],n);return t.innerText=L.t("colorPalette.reset"),n}function BR(n){const t=k("div",["color-palette"],null);return n.color!==!1&&(k("div",["bar-desc"],t,L.t("colorPalette.colorDesc")),t.appendChild(jw(8,1,yR,"color"))),n.backgroundColor!==!1&&(k("div",["bar-desc"],t,L.t("colorPalette.backgroundDesc")),t.appendChild(jw(16,2,kR,"background-color"))),n.clearColorButton!==!1&&t.appendChild(wR()),t}function ER(n,t,e){const o=t==="color"?"color":"background-color",r=n.querySelector(`.${o} button.selected`);r&&rt(r,"selected"),e===null&&(e=-1);const i=n.querySelector(`.${o} button[data-color-index="${e}"]`);i&&V(i,"selected")}const Lot="",xR={};class IR extends ke.TypedEmitter{constructor(e=xR){super();m(this,"root");m(this,"handleClick",e=>{const o=e.target;if(!o||!(o instanceof Element))return;const r=o.closest("button");if(!r)return;if(Et(r,"clear-button")){this.setColor("backgroundColor",null),this.setColor("color",null),this.emit("onClick","clearColor",0);return}const i=r.getAttribute("data-color-index");if(!i)return;const s=Number.parseInt(i,10);Number.isNaN(s)||(Et(r,"color-button")?s===-1?(this.setColor("color",null),this.emit("onClick","clearColor",1)):(this.setColor("color",s),this.emit("onClick","color",s)):s===-1?(this.setColor("backgroundColor",null),this.emit("onClick","clearColor",2)):(this.setColor("backgroundColor",s),this.emit("onClick","backgroundColor",s)))});this.options=e,this.root=BR(e),this.root.addEventListener("click",this.handleClick)}destroy(){this.removeAllListeners(),this.root.removeEventListener("click",this.handleClick)}setColor(e,o){ER(this.root,e,o)}}class Uw{constructor(t,e){m(this,"name","Color Palette");m(this,"element");m(this,"palette");m(this,"closeable",null);this.id=t,this.palette=new IR(e),this.element=this.palette.root}setCloseable(t){this.closeable=t}destroy(){this.palette.destroy(),this.closeable=null}}function TR(){const n=k("button",["color-button"],null);return n.innerHTML=Z1,n}function a0(n,t){const[e,o]=t;e===null?n.removeAttribute("data-color"):n.setAttribute("data-color",`${e}`),o===null?n.removeAttribute("data-background-color"):n.setAttribute("data-background-color",`${o}`)}class SR extends ke.TypedEmitter{constructor(e){super();m(this,"id","text-color-item");m(this,"name",L.t("colorPalette.name"));m(this,"dropdown",!0);m(this,"manualShowChildren",!0);m(this,"children",[]);m(this,"element");m(this,"colorPaletteItem");m(this,"latestColors",[null,null]);m(this,"handlePaletteClick",(e,o)=>{this.emit("onClick",e,o),e==="color"||e==="backgroundColor"?e==="color"?this.latestColors[0]=o:this.latestColors[1]=o:this.latestColors=[null,null],a0(this.element,this.latestColors)});m(this,"beforePopup",()=>{this.updatePaletteColor(this.latestColors),this.emit("beforePopup")});this.editor=e,this.colorPaletteItem=new Uw("text-color-palette-item"),this.colorPaletteItem.palette.addListener("onClick",this.handlePaletteClick),this.children.push(this.colorPaletteItem),this.element=TR()}destroy(){this.colorPaletteItem.destroy()}updatePaletteColor(e){this.colorPaletteItem.palette.setColor("color",e[0]),this.colorPaletteItem.palette.setColor("backgroundColor",e[1]),this.latestColors=e,a0(this.element,this.latestColors)}updateButtonColor(e){this.latestColors=e,a0(this.element,this.latestColors)}}const Rot="";function u0(n,t){const e=k("div",["editor-input-wrap"],n);t!=null&&t.className&&V(e,t==null?void 0:t.className);const o=k("div",["editor-input-label"],e);k("span",[],o,t.label),t.required&&V(o,"required");const r=k("div",["editor-input-container"],e),i=k("input",["editor-input"],r);t.placeholder&&(i.placeholder=t.placeholder),t.defaultValue&&(i.value=t.defaultValue);const s=k("div",["editor-input-error"],e);return i.addEventListener("input",l=>{var a;(a=t.onChange)==null||a.call(t,l),rt(e,"error")}),i.addEventListener("keydown",l=>{var a;(a=t.onKeyDown)==null||a.call(t,l)}),{getField:()=>i,getInputValue:()=>i.value,setFieldError:l=>{V(e,"error"),s.innerText=l},focus:()=>{setTimeout(()=>{i.focus()})}}}function d0(n){const t=document.getSelection();if(!t)return!0;const e=t.focusNode;if(!e)return!0;const o=t.focusOffset,r=e.childNodes[o];if(!r)return!0;if(r instanceof HTMLElement){const i=r.tagName.toLowerCase();if(r===n.input.inputElement)return!0;if(i==="input"||i==="textarea")return!1}return!0}class DR extends $w{constructor(e,o){super(o);m(this,"handleClose",()=>{var e,o;d0(this.editor)&&this.editor.focus(),(o=(e=this.options).onClose)==null||o.call(e)});this.editor=e,this.editorOptions=o}async popupInEditor(e,o,r){var d,h;if(((h=(d=this.editorOptions).onShow)==null?void 0:h.call(d,this,e,o,r))===!1)return;this.options.showLoading&&this.showLoading();const i=this.editor.getBlockByIndex(e,o);if(!Xt(this.editor.rootContainer,i)||ut(this.editor,i)<r)return;const s=Ur(this.editor,i,be(this.editor,i,r));if(s.length===0)return;const l=s[0],a=qr(this.editor,i,"editor-auto-suggest-menu",l);super.popup(a,{noEvent:!0})}}const h0=M("auto-suggest-menu");class f0{constructor(t,e){m(this,"order",100);m(this,"menu");m(this,"anchor",null);m(this,"close",()=>{this.menu.close()});m(this,"handleSelectionChanged",t=>{var o,r;if(!((o=this.menu)!=null&&o.isVisible))return;const e=t.selection.range.start;if(e.isSimple()&&e.blockId===((r=this.anchor)==null?void 0:r.blockId)&&e.offset>=this.anchor.offset){const i=t.getBlockById(e.blockId);if(se(Tn(Cn(t,i),e.offset).left).startsWith(this.anchor.leftText))return}this.menu.close()});m(this,"deleteTrigger",()=>{const t=this.editor,e=t.selection.range.start;if(!e.isSimple()||!this.anchor)return!1;const{blockId:o,offset:r}=e,i=t.getBlockById(o),s=se(Fh(t,i,r));if(g(h0,this.anchor,"no anchor"),!s.startsWith(this.anchor.leftText))return!1;const l=this.anchor.offset-this.anchor.trigger.length,a=r-l;return t.selection.selectBlock(i,l),a&&(t.deleteTextFromBlock(i,l,a),this.anchor.offset-=this.anchor.trigger.length),this.anchor.trigger.length||this.menu.close(),!0});m(this,"onClose",()=>{var t,e;(e=(t=this.options).onClose)==null||e.call(t)});m(this,"onShow",(t,e,o,r)=>{var i;if((i=this.options)!=null&&i.onShow)return this.options.onShow(this,e,o,r)});m(this,"onClickItem",(t,e)=>{!this.anchor||(this.options.autoDeleteTrigger&&this.deleteTrigger(),this.options.onClickItem(this,e,this.anchor))});m(this,"queryItems",(t,e)=>this.options.queryItems(this,e));m(this,"renderMenuItem",(t,e)=>{var r,i;return(i=(r=this.options).renderMenuItem)==null?void 0:i.call(r,this,e)});m(this,"hasExistsMenuThemeCommandBar",()=>!!document.querySelector('div.tippy-box[data-theme="menu"]'));this.editor=t,this.options=e,this.menu=new DR(t,{id:e.id,showLoading:e.showLoading,loadingElement:e.loadingElement,placeholder:e.placeholder,header:e.header,footer:e.footer,wait:e.wait,noResultMessage:e.noResultMessage,highlight:e.highlight,onClose:this.onClose,onShow:this.onShow,onClickItem:this.onClickItem,queryItems:this.queryItems,renderMenuItem:this.renderMenuItem}),t.input.addHandler(this),t.addListener("selectionChanged",this.handleSelectionChanged)}handleBeforeKeyDown(t,e){var o;return!((o=this.menu)!=null&&o.isVisible)||ep(e.key)?!1:t5(e)&&!ws(e)?(setTimeout(()=>{this.resetItems()}),!1):np(e)?(this.menu.close(),!0):(this.menu.handleKeydown(e),!0)}popup(t,e,o,r){this.anchor={blockId:it(t),offset:e,leftText:o,trigger:r};const i=at(ot(t)),s=vt(t);this.menu.popupInEditor(i,s,e)}handleAfterInsertText(t,e,o,r,i){var h,p;const s=t.selection.range.start;if(!s.isSimple())return!1;const l=t.getBlockByIndex(e,o);if(Ms(l))return!1;const{blockId:a,offset:d}=s;if(it(l)!==a)return!1;if((h=this.menu)!=null&&h.isVisible)this.resetItems();else if(this.options.trigger.indexOf(i)!==-1){if(r>0&&this.options.needSpaceBeforeTrigger&&(((p=t.getBlockData(l).text)==null?void 0:p.reduce((x,I)=>x+I.insert,""))||"")[r-1]!==" "||this.hasExistsMenuThemeCommandBar())return!1;const C=se(Fh(t,l,d));this.popup(l,d,C,i)}return!1}handleUpdateCompositionText(t,e,o,r,i){var d;const s=t.selection.range.start;if(!s.isSimple())return!1;const{blockId:l}=s,a=t.getBlockByIndex(e,o);return it(a)!==l||(d=this.menu)!=null&&d.isVisible&&this.resetItems(),!1}resetItems(){var l;if(!((l=this.menu)!=null&&l.isVisible))return;const t=this.editor,e=t.selection.range.start;if(!e.isSimple())return;const{blockId:o,offset:r}=e,i=t.getBlockById(o),s=se(Fh(t,i,r));if(g(h0,this.anchor,"no anchor"),s.startsWith(this.anchor.leftText)){const a=s.substring(this.anchor.leftText.length);h0.debug(`search text: ${a}`),this.menu.handleSearchText(a)}}destroy(){var t;this.editor.input.removeHandler(this),this.editor.removeListener("selectionChanged",this.handleSelectionChanged),(t=this.menu)==null||t.destroy()}}function MR(){const n={};for(let t=1;t<=8;t++)n[`heading-${t}`]={shortcut:`/h${t}`};return n}const LR={"insert-hr":{shortcut:"/hr"},"insert-uml":{shortcut:"/uml"},"insert-table":{shortcut:"/table"},"insert-image":{shortcut:"/image"},"insert-code":{shortcut:"/code"},"insert-link":{shortcut:"/link"},"insert-drawio":{shortcut:"/uml"},"insert-video":{shortcut:"/video"},"insert-audio":{shortcut:"/audio"},"insert-math":{shortcut:"/math"},"insert-webPage":{shortcut:"/web"},"insert-bilibili":{shortcut:"/bilibili"},"insert-youku":{shortcut:"/youku"},"insert-figma":{shortcut:"/figma"},"insert-modao":{shortcut:"/modao"},"insert-tencent":{shortcut:"/tencent"},"insert-unordered":{shortcut:"/bl"},"insert-ordered":{shortcut:"/nu"},"insert-checkbox":{shortcut:"/todo"},"insert-quote":{shortcut:"/quote"},...MR()};function An(n){var t;return(t=LR[n])==null?void 0:t.shortcut}function RR(n){var t;return(t=n.subText)!=null?t:""}const gr=M("table-dom");function pr(n){return`${it(n)}_scroll`}function $e(n){const t=n.querySelector("div[data-type=table-content] >table");return g(gr,t instanceof HTMLTableElement,"invalid table"),t}function Cr(n,t){const o=n.getCustom(pr(t)).contentElement.firstElementChild;g(gr,o instanceof HTMLElement,"invalid table content");let r=o.querySelector(":scope >div[data-type=table-tools]");return r||(r=k("div",[],o),r.setAttribute("data-type","table-tools"),n.domEvents.addEventListener(r,"dblclick",(i,s)=>s.stopPropagation()),n.domEvents.addEventListener(r,"click",(i,s)=>{s.detail===3&&s.stopPropagation()})),g(gr,r,"no table tools"),r}function OR(n,t){return n.findCustom(pr(t))?Cr(n,t):null}function zw(n){const t=[];return Array.from(n.rows).forEach(e=>{t.push(...Array.from(e.cells))}),t}function gu(n){const t=n.querySelector(":scope div[data-type=editor-container]");return g(gr,t,"no child container in cell"),t}function _R(n){const o=zw(n).map(r=>{const i=gu(r),s=at(i),l=r.colSpan,a=r.rowSpan;return`${s}/${l}/${a}`}).join();return Kd.default(o)}function He(n){return St(n)==="table"}function m0(n){const t=ot(n);if(Qt(t))return null;const e=nt(t);return g(gr,e,"no parent block"),He(e)?t:m0(e)}function ti(n){if(He(n))return n;const t=ot(n);if(Qt(t))return null;const e=nt(t);return g(gr,e,"no parent block"),He(e)?e:ti(e)}function FR(n,t){const e=n.querySelector("colgroup");g(gr,e,"no colgroup");const o=e.children[t];return g(gr,o,"no col"),g(gr,o instanceof HTMLTableColElement,`invalid col: ${o.tagName}`),o}function Vw(n){try{return $e(n),!0}catch{return!1}}function PR(n){return te(n).querySelector(":scope > .block-helper")}function Ww(n){const t=nt(n.contentElement);g(gr,t,"no block");const e=PR(t);if(e){const i=Math.min(n.contentElement.offsetLeft+29,n.rootElement.scrollLeft),s=t.getBoundingClientRect().width;e.style.right=`${i+s+5}px`}}const go=M("doc-table-grid");class NR{constructor(t){m(this,"_cells",[]);for(let e=0;e<t;e++)this._cells.push(void 0)}cols(){return this._cells.length}setCell(t,e){g(go,t>=0&&t<this.cols(),`set cell, invalid col: ${t}`),this._cells[t]=e}getCell(t){g(go,t>=0&&t<this.cols(),`get cell, invalid col: ${t}`);const e=this._cells[t];return g(go,e,"get cell, no cell"),e}getCellAllowEmpty(t){return g(go,t>=0&&t<this.cols(),`get cell, invalid col, ${t}`),this._cells[t]}getNextNonVirtualCell(t){return this._cells.slice(t+1).find(e=>!e.virtual)}forEach(t){this._cells.forEach(t)}}class Sf{constructor(t){m(this,"_data");m(this,"_rows");this._data=t,this._rows=[];for(let e=0;e<this.rowCount;e++)this._rows.push(new NR(this.colCount));this.fillGrid(),t.colsWidth&&g(go,this.colCount===t.colsWidth.length,"invalid col count")}get rowCount(){return this._data.rows}get colCount(){return this._data.cols}getNextEmptyCell(t,e){let o=t,r=e;for(;;){if(o+=1,o===this.colCount&&(o=0,r+=1),r>=this.rowCount)return null;if(this._rows[r].getCellAllowEmpty(o)===void 0)return{col:o,row:r}}}fillGrid(){const t=this._data.children;g(go,t,"no children");let e=0,o=0;t.forEach((r,i)=>{const s=this._data[`${r}_colSpan`]||1,l=this._data[`${r}_rowSpan`]||1;for(let d=0;d<l;d++)for(let h=0;h<s;h++)this._rows[o+d].setCell(e+h,{col:e,row:o,containerId:r,virtual:h!==0||d!==0,colSpan:s,rowSpan:l});const a=this.getNextEmptyCell(e,o);a?(e=a.col,o=a.row):g(go,i===t.length-1,`invalid table data, no next empty cell: ${JSON.stringify(this._data)}`)}),this._rows.forEach(r=>{r.forEach(i=>{g(go,i,"no cell"),g(go,i.containerId,"no containerId")})})}getCell(t){const{col:e,row:o}=t,r=this._rows[o];g(go,r,`get cell, no row: ${o}`);const i=r.getCell(e);return g(go,i,`get cell, no cell: ${e}`),i}getRow(t){const e=this._rows[t];return g(go,e,`get row, no row: ${t}`),e}forEach(t){this._rows.forEach(t)}}const Df=M("table-data");function $R(n){const t=n.firstElementChild;return g(Df,t,"no child element for cell"),g(Df,jr(t),"cell first child is not a container"),g(Df,Lo(t),"cell first child is not a container"),t}function HR(n){const t=nt(n);g(Df,t,"no parent block for table");const e=[],o={};Array.from(n.rows).forEach(l=>{Array.from(l.cells).forEach(a=>{const d=$R(a),h=at(d);e.push(h),(a.colSpan>1||a.rowSpan>1)&&(o[`${h}_colSpan`]=a.colSpan,o[`${h}_rowSpan`]=a.rowSpan)})});const r=n.rows.length,i=Array.from(n.rows[0].cells).map(l=>l.colSpan).reduce((l,a)=>l+a,0);return{id:it(t),type:St(t),rows:r,cols:i,children:e,colsWidth:Array(i).fill(100),...o}}function Qs(n){return new Sf(n)}function jR(n){return Qs(HR(n))}const Ge=M("table-grid"),UR=60;class zR{constructor(t,e){m(this,"containerId");m(this,"row");m(this,"col");m(this,"colSpan");m(this,"rowSpan");m(this,"virtual");m(this,"table");this.table=t,this.containerId=e.containerId,this.row=e.row,this.col=e.col,this.colSpan=e.colSpan,this.rowSpan=e.rowSpan,this.virtual=e.virtual}get cell(){const e=this.container.closest("td");return g(Ge,e,"no parent cell for child container"),e}get container(){const t=this.table.querySelectorAll(`[data-container-id=${this.containerId}]`);g(Ge,t.length===1,"containers !== 1"),g(Ge,jr(t[0]),"not a container");const e=t[0];return g(Ge,Lo(e),"not a child container"),e}}class VR{constructor(t,e){m(this,"_cells",[]);e.forEach(o=>{this._cells.push(new zR(t,o))})}get cells(){return this._cells}getCell(t){return g(Ge,t<this._cells.length,"get cell, invalid col"),this._cells[t]}getNextNonVirtualCell(t){return this._cells.slice(t+1).find(e=>!e.virtual)}getSpannedCell(){return this._cells.find(t=>t.virtual||t.colSpan>1||t.rowSpan>1)}}const xb=class{constructor(t){m(this,"_rows",[]);this.table=t,jR(t).forEach(r=>{this._rows.push(new VR(t,r))});const o=this.colCount;this._rows.forEach(r=>{g(Ge,r.cells.length===o,"row.cells.length !== colCount")})}get rowCount(){return this._rows.length}get colCount(){return this._rows.length===0?0:(g(Ge,this.rowCount>0,"rowCount <= 0"),this.getRow(0).cells.length)}getRow(t){return this._rows[t]}getCell(t){const e=this.getRow(t.row);return g(Ge,e,"no row"),e.getCell(t.col)}getCellContainer(t){return this.getCell(t).container}getFirstCellContainer(){return this.getCellContainer({row:0,col:0})}getLastCellContainer(){const t=this.rowCount-1,e=this.colCount-1;return this.getCellContainer({row:t,col:e})}getColumnCells(t){g(Ge,t>=0&&t<this.colCount,"colIndex out of range");const e=this.rowCount,o=[];for(let r=0;r<e;r++){const i=this.getCell({row:r,col:t});o.push(i)}return o}toRealCells(t){const e=[];return t.forEach(o=>{const r=this.getRealCell(o);e.findIndex(i=>i.containerId===r.containerId)===-1&&e.push(r)}),e}getColumnRealCells(t){const e=this.getColumnCells(t);return this.toRealCells(e)}getRowRealCells(t){const e=this.getRow(t).cells;return this.toRealCells(e)}getFirstSpannedCell(t){g(Ge,t>=0&&t<this.colCount,"colIndex out of range");const e=this.rowCount;for(let o=0;o<e;o++){const r=this.getCell({row:o,col:t});if(r.virtual||r.colSpan>1||r.rowSpan>1)return r}}getRealCell(t){const e=this.getCell(t);if(!e.virtual)return e;const o=this.getCellById(e.containerId);return g(Ge,!o.virtual,"found a virtual cell"),o}getColumnSpannedRange(t){const e=this.getColumnRealCells(t);let o=1e5,r=-1;return e.forEach(i=>{o=Math.min(i.col,o),r=Math.max(i.col+i.colSpan-1,r)}),g(Ge,o<=r,"min > max"),g(Ge,o>=0,"min < 0"),g(Ge,r<this.colCount,"max >= colCount"),[o,r]}getRowSpannedRange(t){const e=this.getRowRealCells(t);let o=1e5,r=-1;return e.forEach(i=>{o=Math.min(i.row,o),r=Math.max(i.row+i.rowSpan-1,r)}),g(Ge,o<=r,"min > max"),g(Ge,o>=0,"min < 0"),g(Ge,r<this.rowCount,"max >= rowCount"),[o,r]}getSpannedRange(t,e){const o=Math.min(t.row,e.row),r=Math.max(t.row,e.row),i=Math.min(t.col,e.col),s=Math.max(t.col,e.col),l=[];for(let v=o;v<=r;v++)for(let B=i;B<=s;B++)l.push(this.getCell({row:v,col:B}));const a=this.toRealCells(l);let d=1e4,h=1e4,p=-1,C=-1;return a.forEach(v=>{h=Math.min(v.col,h),d=Math.min(v.row,d),C=Math.max(v.col+v.colSpan-1,C),p=Math.max(v.row+v.rowSpan-1,p)}),[{row:d,col:h},{row:p,col:C}]}getAllCells(){return this.getCells({col:0,row:0},{col:this.colCount-1,row:this.rowCount-1})}sub(t,e){const o=[];for(let r=t.row;r<=e.row;r++){const i=[];for(let s=t.col;s<=e.col;s++){const l=this.getCell({row:r,col:s});i.push(l)}o.push(i)}return o}getAllContainers(){return this.getAllCells().map(e=>e.container)}getCells(t,e){const o=[],r=this.getSpannedRange(t,e),i=r[0],s=r[1],l=Math.min(i.row,s.row),a=Math.max(i.row,s.row),d=Math.min(i.col,s.col),h=Math.max(i.col,s.col);for(let p=l;p<=a;p++)for(let C=d;C<=h;C++){const v=this.getCell({row:p,col:C});v.virtual||o.push(v)}return o}map(t){const e=[];for(let o=0;o<this.rowCount;o++){const r=[];for(let i=0;i<this.colCount;i++){const s=this.getCell({row:o,col:i});r.push(t(s))}e.push(r)}return e}getBottomCell(t){const e=this.rowCount;let o=t,r=t.row;for(;o.containerId===t.containerId;){if(r+=1,r>=e)return null;o=this.getCell({row:r,col:t.col})}return this.getRealCell(o)}getTopCell(t){let e=t,o=t.row;for(;e.containerId===t.containerId;){if(o-=1,o<0)return null;e=this.getCell({row:o,col:t.col})}return this.getRealCell(e)}get cells(){let t=[];return this._rows.forEach(e=>{t=t.concat(e.cells)}),t}getVirtualCellContainersGrid(){return this.map(t=>t.containerId)}static virtualCellContainersGridToChildren(t){const e=t,o=[];return e.forEach(r=>{r.forEach(i=>{o.indexOf(i)===-1&&o.push(i)})}),o}getCellById(t){const o=this.cells.find(r=>r.containerId===t);return g(Ge,o,"cell not found"),o}getCellByCellElement(t){const e=gu(t);return this.getCellByContainerId(at(e))}getCellByContainerId(t){return this.getCellById(t)}static fromTable(t){const e=_R(t),o=this.caches.getSync(e,()=>(Ge.debug("create table grid"),new xb(t)));return o.table!==t?(this.caches.delete(e),this.fromTable(t)):o}static fromBlock(t){return this.fromTable($e(t))}};let Tt=xb;m(Tt,"caches",new Ov(UR));function Mf(n,t){Object.entries(n).forEach(([e])=>{e.startsWith(`${t}/`)&&delete n[e]})}const WR=M("table-selection-range");function Uo(n,t,e){var D,H,W,G;const o=Tt.fromBlock(n),r=t,i=e,s=o.getCellByContainerId(r.childContainerId),l=o.getCellByContainerId(i.childContainerId),a=r.custom,d=i.custom,h=(D=a==null?void 0:a.rowIndex)!=null?D:s.row,p=(H=a==null?void 0:a.colIndex)!=null?H:s.col,C=(W=d==null?void 0:d.rowIndex)!=null?W:l.row+l.rowSpan-1,v=(G=d==null?void 0:d.colIndex)!=null?G:l.col+l.colSpan-1,B=Math.min(h,C),x=Math.max(h,C),I=Math.min(p,v),_=Math.max(p,v);return{fromRow:B,toRow:x,fromCol:I,toCol:_}}function g0(n,t){const e=new Set,o=new Set,r=n.selection.range;if(!r.isSimple()&&r.start.blockId===it(t)){const i=Tt.fromBlock(t),{start:s,end:l}=r;g(WR,!s.isSimple()&&!l.isSimple(),"invalid range");const{fromCol:a,toCol:d,fromRow:h,toRow:p}=Uo(t,s,l);if(h===0&&p===i.rowCount-1)for(let C=a;C<=d;C++)o.add(C);if(a===0&&d===i.colCount-1)for(let C=h;C<=p;C++)e.add(C)}return{selectedRows:e,selectedColumns:o}}function pu(n,t){let e=null;if(t.isCollapsed()&&t.isSimple()){const o=n.getBlockById(t.start.blockId);if(He(o)){const r=ot(o),i=nt(r);i&&(e=ti(i))}else e=ti(o)}else{const o=n.getBlockById(t.start.blockId),r=ti(o),i=n.getBlockById(t.end.blockId),s=ti(i);r===s&&(e=r)}return e}const mc=M("delete-columns");function qw(n,t,e){const{start:o,end:r}=e;if(o.blockId!==r.blockId||e.isSimple()||n.getBlockById(o.blockId)!==t||St(t)!=="table")return!1;const{fromRow:s,toRow:l}=Uo(t,e.start,e.end),a=Tt.fromBlock(t);return s===0&&l===a.rowCount-1}function p0(n){const t=n.getEditor();t.undoManager.runInGroup(()=>{var H,W;const e=t.getBlockById(n.start.blockId);if(!qw(t,e,n))return;if(n.isSimple()){t.deleteBlock(e);return}const{fromCol:o,toCol:r}=Uo(e,n.start,n.end),i=Tt.fromBlock(e);if(o===0&&r===i.colCount-1){t.deleteBlock(e);return}const s=new Set,l=i.map(G=>G.containerId);for(let G=0;G<l.length;G++){const K=l[G];for(let ht=o;ht<=r;ht++){const bt=K[ht];s.add(bt)}K.splice(o,r-o+1)}const a=new Set(l.flat()),d=new Set(Array.from(s).filter(G=>!a.has(G))),h=r-o+1,p=new Map,C=new Map;s.forEach(G=>{if(d.has(G))return;const K=i.getCellByContainerId(G);if(g(mc,K.colSpan>1,"invalid effected cell, colSpan === 1"),K.col<o){g(mc,a.has(G),"invalid effected cell, not exists");let Le=K.col+K.colSpan-1;Le>r&&(Le=r);const Jn=Le-o+1,Ee=K.colSpan-Jn;p.set(G,Ee);return}g(mc,K.col<=r,"invalid effected cell, col > endCol");const ht=K.col,bt=K.col+K.colSpan-1,_t=K.col-o,Ht=bt-ht+1-h+_t;g(mc,Ht>0,"invalid effected cell, newSpanned <= 0");const oe=Zr(t.doc);C.set(G,{newContainerId:oe,colSpan:Ht})});for(let G=0;G<l.length;G++){const K=l[G];for(let ht=o;ht<K.length;ht++){const bt=K[ht],_t=C.get(bt);_t&&(K[ht]=_t.newContainerId)}}const v=mt.default(t.getBlockData(e));((H=v.colsWidth)!=null?H:new Array(v.cols).fill(0)).splice(o,r-o+1),d.forEach(G=>{Mf(v,G)}),p.forEach((G,K)=>{g(mc,G>=1,"invalid modified colSpan, colSpan < 1"),G===1?v[`${K}_colSpan`]=void 0:v[`${K}_colSpan`]=G}),C.forEach((G,K)=>{Mf(v,K);const{newContainerId:ht,colSpan:bt}=G;g(mc,bt>=1,"invalid newContainerData, colSpan < 1"),bt>1&&(v[`${ht}_colSpan`]=bt);const _t=i.getCellByContainerId(K).rowSpan;_t>1&&(v[`${ht}_rowSpan`]=_t)});const x=(W=l[0][o])!=null?W:l[0][o-1],I=t.getChildContainerData(x)[0],_=Tt.virtualCellContainersGridToChildren(l),D={...v,cols:v.cols-h,children:_};Qs(D),t.updateBlockData(e,D,be(t,I.id,0)),t.deleteChildContainers(Array.from(d)),t.deleteChildContainers(Array.from(C.keys()))})}const gc=M("delete-rows");function Gw(n,t,e){const{start:o,end:r}=e;if(o.blockId!==r.blockId||e.isSimple()||n.getBlockById(o.blockId)!==t||St(t)!=="table")return!1;const{fromCol:s,toCol:l}=Uo(t,e.start,e.end),a=Tt.fromBlock(t);return s===0&&l===a.colCount-1}function C0(n){const t=n.getEditor();t.undoManager.runInGroup(()=>{const e=t.getBlockById(n.start.blockId);if(!Gw(t,e,n))return;if(n.isSimple()){t.deleteBlock(e);return}const{fromRow:o,toRow:r}=Uo(e,n.start,n.end),i=Tt.fromBlock(e);if(o===0&&r===i.rowCount-1){t.deleteBlock(e);return}const s=new Set,l=i.map(D=>D.containerId);for(let D=r;D>=o;D--)l[D].forEach(W=>s.add(W)),l.splice(D,1);const a=new Set(l.flat()),d=new Set(Array.from(s).filter(D=>!a.has(D))),h=r-o+1,p=new Map,C=new Map;s.forEach(D=>{if(d.has(D))return;const H=i.getCellByContainerId(D);if(g(gc,H.rowSpan>1,"invalid effected cell, rowSpan === 1"),H.row<o){g(gc,a.has(D),"invalid effected cell, not exists");let _t=H.row+H.rowSpan-1;_t>r&&(_t=r);const Ht=_t-o+1,oe=H.rowSpan-Ht;p.set(D,oe);return}g(gc,H.row<=r,"invalid effected cell, col > endCol");const W=H.row,G=H.row+H.rowSpan-1,K=H.row-o,ht=G-W+1-h+K;g(gc,ht>0,"invalid effected cell, newSpanned <= 0");const bt=Zr(t.doc);C.set(D,{newContainerId:bt,rowSpan:ht})});for(let D=o;D<l.length;D++){const H=l[D];for(let W=0;W<H.length;W++){const G=H[W],K=C.get(G);K&&(H[W]=K.newContainerId)}}const v=mt.default(t.getBlockData(e));d.forEach(D=>{Mf(v,D)}),p.forEach((D,H)=>{g(gc,D>=1,"invalid modified rowSpan, rowSpan < 1"),D===1?v[`${H}_rowSpan`]=void 0:v[`${H}_rowSpan`]=D}),C.forEach((D,H)=>{Mf(v,H);const{newContainerId:W,rowSpan:G}=D;g(gc,G>=1,"invalid newContainerData, rowSpan < 1"),G>1&&(v[`${W}_rowSpan`]=G);const K=i.getCellByContainerId(H).colSpan;K>1&&(v[`${W}_colSpan`]=K)});const B=l[o]?l[o][0]:l[o-1][0],x=t.getChildContainerData(B)[0],I=Tt.virtualCellContainersGridToChildren(l),_={...v,rows:v.rows-h,children:I};Qs(_),t.updateBlockData(e,_,be(t,x.id,0)),t.deleteChildContainers(Array.from(d)),t.deleteChildContainers(Array.from(C.keys()))})}const Cu=M("table-range");function Lf(n){g(Cu,!n.isSimple(),"must be complex selection range");const{anchor:t,focus:e}=n;g(Cu,!t.isSimple(),"invalid start pos type"),g(Cu,!e.isSimple(),"invalid end pos type");const o=n.getEditor();g(Cu,t.blockId===e.blockId,"invalid range, not same block");const r=o.getBlockById(t.blockId);g(Cu,St(r)==="table","invalid block type, not a table block");const i=$e(r),s=Tt.fromTable(i),l=s.getCellByContainerId(t.childContainerId),a=s.getCellByContainerId(e.childContainerId),d=Math.min(l.row,a.row),h=Math.max(l.row,a.row),p=Math.min(l.col,a.col),C=Math.max(l.col,a.col),v=s.getCell({row:d,col:p}),B=s.getCell({row:h,col:C});return{editor:o,block:r,table:i,startCell:v,endCell:B,startRow:d,startCol:p,endRow:h,endCol:C}}const b0=M("split-cell");function A0(n,t,e){n.undoManager.runInGroup(()=>{const o=Tt.fromBlock(t),r=o.getRealCell(e);g(b0,!r.virtual,"should not split virtual cell"),g(b0,r.colSpan>1||r.rowSpan>1,"cell does not has span data");const i=o.getVirtualCellContainersGrid();for(let p=0;p<r.rowSpan;p++)for(let C=0;C<r.colSpan;C++){if(p===0&&C===0)continue;const v=p+r.row,B=C+r.col,x=Zr(n.doc);i[v][B]=x}const s=n.getBlockData(t),l=mt.default(s);l[`${r.containerId}_colSpan`]=null,l[`${r.containerId}_rowSpan`]=null,l.children=Tt.virtualCellContainersGridToChildren(i);const d=n.getChildContainerData(r.containerId)[0];g(b0,d,"no child block");const h=be(n,d.id,0);Qs(l),n.updateBlockData(t,l,h)})}function qR(n,t,e){e.forEach(o=>{const r=Tt.fromBlock(t).getCell(o);(r.virtual||r.colSpan>1||r.rowSpan>1)&&A0(n,t,o)})}function Qw(n,t,e){if(e.isSimple())return!1;const{start:o,end:r}=e;if(o.blockId!==r.blockId||n.getBlockById(o.blockId)!==t||St(t)!=="table")return!1;const{startCell:s,endCell:l}=Lf(e);return!(s.cell!==l.cell||s.colSpan===1&&s.rowSpan===1)}function v0(n){const{editor:t,block:e,startRow:o,startCol:r,endRow:i,endCol:s}=Lf(n),l=[];for(let a=o;a<=i;a++)for(let d=r;d<=s;d++)l.push({row:a,col:d});return qR(t,e,l),!0}const pc=M("merge-cells");function Zw(n,t,e){if(e.isSimple())return!1;const{start:o,end:r}=e;if(o.blockId!==r.blockId||n.getBlockById(o.blockId)!==t||St(t)!=="table")return!1;const{startCell:s,endCell:l}=Lf(e);return s.cell!==l.cell}function Yw(n){const t=Lf(n),e=t.editor;e.undoManager.runInGroup(()=>{const o=t.endCell,r=o.row+o.rowSpan-1,i=o.col+o.colSpan-1,s=it(t.block);v0(n);const l=e.getBlockById(s),a=$e(l),{startRow:d,startCol:h}=t,p=mt.default(e.getBlockData(l));g(pc,p.children,"no table children");const C=Tt.fromTable(a),v=[];for(let _t=d;_t<=r;_t++)for(let Ht=h;Ht<=i;Ht++){const oe=C.getCell({row:_t,col:Ht});g(pc,!oe.virtual,"cell is virtual"),v.push(oe)}g(pc,v.length>0,"no selected cells");const B=v[0],x=v.slice(1),I=C.getCellByContainerId(B.containerId).container,_=[];x.forEach(_t=>{const Ht=C.getCellByContainerId(_t.containerId).container,oe=at(Ht);if(!Na(e,Ht)){const Le=pk(e,oe);if(Na(e,I)){const Jn=fe(I)[0];e.insertDocAt(I,0,Le),e.deleteBlock(Jn)}else e.insertDocAt(I,To(I),Le)}_.push(oe)});const D=at(I),H=i-h+1,W=r-d+1;p[`${D}_colSpan`]=H,p[`${D}_rowSpan`]=W,_.forEach(_t=>{g(pc,p.children,"no table children");const Ht=p.children.indexOf(_t);g(pc,Ht>0,"no deleted container"),p.children.splice(Ht,1)});const G=p,ht=e.getChildContainerData(D)[0];g(pc,ht,"no child block");const bt=be(e,ht.id,0);Qs(G),e.updateBlockData(l,G,bt),e.deleteChildContainers(_)})}const y0=10,GR=["table/merge-cells","table/split-cell","table/insert-column","table/insert-row","table/delete-rows","table/delete-columns","table/delete"];class Rf{constructor(){m(this,"id","TableBlockCommandProvider")}getAvailableCommands(t,e,o){if(St(e)!=="table")return[];const r={blockId:it(e),blockKind:Do(t,e),blockType:St(e)},i=[];Zw(t,e,o)&&i.push({id:"table/merge-cells",name:L.t("table.mergeCell"),icon:_2,groupIndex:y0,...r}),Qw(t,e,o)&&i.push({id:"table/split-cell",name:L.t("table.splitCell"),icon:F2,groupIndex:y0,...r});const s=qw(t,e,o),l=Gw(t,e,o);return s&&l&&i.push({id:"table/delete",name:L.t("table.deleteTable"),icon:P2,groupIndex:y0,...r}),i}executeCommand(t,e,o,r,i,s){return St(e)!=="table"||!new Set(GR).has(r.id)?!1:r.id==="table/merge-cells"?(Yw(o),!0):r.id==="table/split-cell"?(v0(o),!0):r.id==="table/delete-columns"?(p0(o),!0):r.id==="table/delete-rows"?(C0(o),!0):r.id==="table/delete"?(t.deleteBlock(e),!0):!1}}var Jw=(n=>(n.COL_TITLE_TABLE="col-title-table",n.COL_TITLE_ITEM="col-title-item",n.STRIPE_STYLE_TABLE="stripe-style-table",n.NO_BORDER="table-no-border",n))(Jw||{});const Cc=6,bu=20,k0="table-cell-menu-btn";function QR(n,t){if(!n.isBlockWritable(t))return;const o={...mt.default(n.getBlockData(t)),hasColTitle:!0};n.updateBlockData(t,o)}function ZR(n,t){if(!n.isBlockWritable(t))return;const o={...mt.default(n.getBlockData(t)),hasColTitle:!1};n.updateBlockData(t,o)}function YR(n,t){if(!n.isBlockWritable(t))return;const o={...mt.default(n.getBlockData(t)),hasRowTitle:!0};n.updateBlockData(t,o)}function JR(n,t){if(!n.isBlockWritable(t))return;const o={...mt.default(n.getBlockData(t)),hasRowTitle:!1};n.updateBlockData(t,o)}function KR(n,t){if(!n.isBlockWritable(t))return;const o={...mt.default(n.getBlockData(t)),isStripeStyle:!0};n.updateBlockData(t,o)}function XR(n,t){if(!n.isBlockWritable(t))return;const o={...mt.default(n.getBlockData(t)),isStripeStyle:!1};n.updateBlockData(t,o)}function tO(n,t,e){if(!n.isBlockWritable(t))return;const r={...mt.default(n.getBlockData(t)),noBorder:!e};n.updateBlockData(t,r)}const Zs=M("table-cell-dom");function eO(n,t,e){let o=n.getBlockById(e);for(;o;){const r=o.closest("td");g(Zs,r,"no parent cell");const i=nt(r);if(g(Zs,i,"no parent block"),i===t)return r;o=i}return g(Zs,!1,"filed to get cell by child block id"),null}function zi(n,t,e){if(n.getBlockById(e.blockId)===t&&!e.isSimple())return g(Zs,e.childContainerId,"block position must have childContainerId attribute"),e;const r=eO(n,t,e.blockId),i=at(gu(r));return me(t,i)}function w0(n,t){const e=n.selection.range,o=zi(n,t,e.start),r=zi(n,t,e.end);return Uo(t,o,r)}function Kw(n,t,e,o){g(Zs,He(t),"invalid table block");const r=Cr(n,t),i=te(t),s=()=>{const a=r.querySelector(".table-border-bar-container.top");g(Zs,a,"no top border bar container"),a.querySelectorAll(".table-border-bar-cell.top").forEach(h=>{const p=parseInt(h.getAttribute("data-top-index")||"0",10);o.includes(p)?V(h,"danger"):rt(h,"danger")})},l=()=>{const a=i.querySelector(".table-border-bar-container.left");g(Zs,a,"no left border bar container"),a.querySelectorAll(".table-border-bar-cell.left").forEach(h=>{const p=parseInt(h.getAttribute("data-left-index")||"0",10);e.includes(p)?V(h,"danger"):rt(h,"danger")})};s(),l()}function Vi(n,t,e=!0,o){const i=Tt.fromBlock(t).map(h=>h),{fromCol:s,toCol:l,fromRow:a,toRow:d}=w0(n,t);for(let h=0;h<i.length;h++){const p=i[h];for(let C=0;C<p.length;C++){const v=p[C],B=o?C>=s&&C+v.colSpan-1<=l:h>=a&&h+v.rowSpan-1<=d;e&&B?v.virtual||V(v.cell,"danger"):v.virtual||rt(v.cell,"danger")}}}function Wi(n,t,e=!0,o){const r=new Set,i=new Set;if(!e){Kw(n,t,Array.from(r),Array.from(i));return}const{fromCol:s,toCol:l,fromRow:a,toRow:d}=w0(n,t);if(o)for(let h=s;h<=l;h++)i.add(h);else for(let h=a;h<=d;h++)r.add(h);Kw(n,t,Array.from(r),Array.from(i))}function Xw(n,t,e){const{fromCol:o,toCol:r,fromRow:i,toRow:s}=w0(n,t),l=Tt.fromBlock(t);let a=null,d=null;return e?(a=l.getCell({col:o,row:0}),d=l.getCell({col:r,row:l.rowCount-1}),We(n,{anchor:me(t,a.containerId,{colIndex:o,rowIndex:0}),focus:me(t,d.containerId,{colIndex:r,rowIndex:l.rowCount-1})})):(a=l.getCell({col:0,row:i}),d=l.getCell({col:l.colCount-1,row:s}),We(n,{anchor:me(t,a.containerId,{colIndex:0,rowIndex:i}),focus:me(t,d.containerId,{colIndex:l.colCount-1,rowIndex:s})}))}const t4=["style-bg-color-0","style-bg-color-1","style-bg-color-2","style-bg-color-3","style-bg-color-4","style-bg-color-5","style-bg-color-6","style-bg-color-7","style-bg-color-8","style-bg-color-9","style-bg-color-10","style-bg-color-11","style-bg-color-12","style-bg-color-13"];function e4(n){return`style-bg-color-${n}`}function Au(n){return`${n}_background`}function nO(n,t,e){const o=$e(n),s=(e!=null?e:Tt.fromTable(o)).getCell(t).cell;for(let l=0;l<t4.length;l++){const a=t4[l];if(Et(s,a))return a}}function n4(n,t,e){if(!n.isBlockWritable(t))return;const o=n.selection.range,i={...mt.default(n.getBlockData(t))},s=zi(n,t,o.start),l=zi(n,t,o.end);if(o.isSimple()){const a=s.childContainerId;e===-1?i[Au(a)]=void 0:i[Au(a)]=e4(e)}else{const a=Tt.fromBlock(t),d=Uo(t,s,l),h=new Set;for(let p=d.fromRow;p<=d.toRow;p++)for(let C=d.fromCol;C<=d.toCol;C++){const v=a.getCell({row:p,col:C});!h.has(v.containerId)&&v.col>=d.fromCol&&v.row>=d.fromRow&&v.col+v.colSpan-1<=d.toCol&&v.row+v.rowSpan-1<=d.toRow&&(h.add(v.containerId),e===-1?i[Au(v.containerId)]=void 0:i[Au(v.containerId)]=e4(e))}}n.updateBlockData(t,i)}function oO(n,t,e){if(!n.isBlockWritable(t))return;const r={...mt.default(n.getBlockData(t)),chart:e};n.updateBlockData(t,r)}const o4=M("table-chart");function rO(n,t){const e=OR(n,t);if(e){const o=e.querySelector(".editor-table-chart");if(o){const r=o.chartObject;r&&r.destroy(),o.remove()}}}async function iO(n,t){if(!n.contains(t)||!n.isBlockWritable(t))return;if(!!!n.getBlockData(t).chart){rO(n,t);return}const r=[],i=Tt.fromBlock(t),s=["line","bar","pie","radar"];let l=i.getCell({row:0,col:0}).container.innerText.trim().toLowerCase();new Set(s).has(l)||(l=s[0]);const a=[];for(let x=1;x<i.colCount;x++)a.push(i.getCell({row:0,col:x}).container.innerText);for(let x=1;x<i.rowCount;x++){const I=i.getCell({row:x,col:0}),D=I.container.innerText,H=[];for(let Le=1;Le<i.colCount;Le++){const Jn=i.getCell({row:x,col:Le}).container.innerText,Ee=Number.parseFloat(Jn)||0;H.push(Ee)}let W;const G=nO(t,I,i);G?W=window.getComputedStyle(n.rootElement).getPropertyValue(`--${G}`).trim():W=window.getComputedStyle(n.rootElement).getPropertyValue("--background-color").trim();let[K,ht,bt,_t]=W?Ug.fromString(W).toRgbaArray():[];if(!K&&!ht&&!bt&&!_t){const Le=(x-1)%n.options.colors.length;W=n.options.colors[Le],[K,ht,bt,_t]=Ug.fromString(W).toRgbaArray()}const Ht=W,oe=Ug.fromRgba([K,ht,bt,_t/3]).toHexString();r.push({label:D,data:H,borderColor:Ht,backgroundColor:oe,borderWidth:2})}const d=Cr(n,t);let h=null,p=d.querySelector(".editor-table-chart");p?h=p.chartObject:p=k("div",["editor-table-chart"],d);const C=p;g(o4,C,"no chart container");const v=n.getComponentOptions("table"),B=(v==null?void 0:v.chartCdn)||"https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js";try{await ys(B,"editor-chartjs");let x=!1;(h&&h.config.data.datasets.length>r.length||h&&h.config.data.datasets[0].data.length>r[0].data.length)&&(x=!0),h&&(l!==h.config.type||x)&&(h.destroy(),h=null,Array.from(p.querySelectorAll(".editor-chartjs-canvas")).forEach(D=>{D.remove()}));const I=zg.default({},{type:l,data:{datasets:r,labels:a},options:{onClick:()=>{n.selection.selectBlock(t,0,0)}}});if(h)zg.default(h.config,I),h.update();else{const D=k("canvas",["editor-chartjs-canvas"],C).getContext("2d");h=new window.Chart(D,I),p.chartObject=h}}catch(x){o4.error(`failed to resolve chart cdn: ${JSON.stringify(x)}`)}}async function r4(n,t){await Io.lock("updateTableChart");try{await iO(n,t)}finally{Io.release("updateTableChart")}}const i4=Fe.default(r4,1e3);let s4=null;function B0(n,t,e){if(s4!==t&&(i4.flush(),s4=t),e.updateNow){r4(n,t);return}i4(n,t)}function E0(n,t){He(t)&&B0(n,t,{updateNow:!1})}function sO(n,t){He(t)&&B0(n,t,{updateNow:!0})}const po={SCROLL:"container-scroll-tool",COMMON:"container-border-shadow",RIGHT:"container-right-border-shadow",LEFT:"container-left-border-shadow",LAYOUT_SIGN:"container-layout-border-shadow",ACTIVE:"active"},Of={SCROLL_BAR:"container-scrollbar",FIXED:"fixed"},qi={SCROLL_CONTAINER:"scroll-container",TOOL:"container-scroll-tool",CONTAINER:"scroll-container-root",MAC:"mac",SCROLL_AREA:"scroll-area"};function vu(n,t){return n.containers.get(t)}function l4(n){return n.closest(`.${qi.SCROLL_CONTAINER}`)}function zo(n){return n.firstElementChild}function vn(n){return n.closest(`.${qi.CONTAINER}`)}function yu(n){const t=vn(n);let e=t.querySelector(`:scope >.${qi.TOOL}`);return e||(e=k("div",[qi.TOOL],t)),e}function lO(n){return vn(n).firstElementChild}function cO(n,t){const e=vu(n,vn(t));return e!=null&&e.barFloatWindowBottom?typeof e.barFloatWindowBottom=="function"?e.barFloatWindowBottom():e.barFloatWindowBottom:0}function Co(n,t){const e=io(n);return t/e}function ku(n){const t=window.getComputedStyle(n),e=io(n);return{paddingBottom:parseFloat(t.paddingBottom)*e,paddingTop:parseFloat(t.paddingTop)*e,paddingLeft:parseFloat(t.paddingLeft)*e,paddingRight:parseFloat(t.paddingRight)*e}}function bc(n){const t=io(n);return{scrollLeft:n.scrollLeft*t,scrollWidth:n.scrollWidth*t,clientWidth:n.clientWidth*t,clientHeight:n.clientHeight*t}}function aO(n,t){const e=io(n);return n[t]*e}function x0(n,t){const e=vn(t),o=vu(n,e),r=(o==null?void 0:o.safeRightSpace)||0,i=(o==null?void 0:o.safeLeftSpace)||0,l=(o==null?void 0:o.locatingContainer).getBoundingClientRect(),a=e.getBoundingClientRect(),d=a.width;let h=Math.floor(a.left-l.left-i);h<0&&(h=0);let p=l.right;p-=r;let C=p-a.right;return C<0&&(C=0),h=Math.round(h),C=Math.round(C),{originWidth:d,maxLeft:h,maxRight:C}}function uO(n,t){const e=x0(n,t),{maxLeft:o}=e;t.style.marginLeft=`${Co(t,0-o)}px`,t.style.paddingLeft=`${Co(t,o)}px`}function dO(n,t){const e=x0(n,t);t.style.marginRight=`${Co(t,0-e.maxRight)}px`}function hO(n){if(n!==document.documentElement&&n!==document.body)return n.getBoundingClientRect();const t=0,e=0,o=document.documentElement.clientWidth,r=document.documentElement.clientHeight;return new DOMRect(t,e,o,r)}const c4=M("scroll-bar-handle"),fO=2;function Ac(n){const t=yu(n);let e=t.querySelector(`.${Of.SCROLL_BAR}`);return e||(e=k("div",[Of.SCROLL_BAR],t)),g(c4,e instanceof HTMLDivElement,"invalid child for container tools"),e.firstElementChild||k("div",[],e),e}function _f(n,t){const e=l4(t),o=Ac(e),{scrollWidth:r,clientWidth:i}=bc(e),{paddingLeft:s,paddingRight:l}=ku(t),a=x0(n,e),{originWidth:d,maxRight:h}=a;dO(n,e),uO(n,e);const p=r-i;g(c4,o.firstElementChild instanceof HTMLDivElement,"invalid child for scroll bar"),o.style.width=`${Co(e,d+h-s-l)}px`,o.firstElementChild.style.width=`${Co(e,d+h+p-s-l)}px`}function mO(n,t){const e=zo(n),{paddingLeft:o}=ku(e);if(Et(t,"fixed")){const i=vn(n).getBoundingClientRect();t.style.left=`${Co(n,i.left+o)}px`}else t.style.left=`${Co(n,o)}px`}function vc(n,t){var D;const e=n.getParentScrollContainer(),o=hO(e),r=t.getBoundingClientRect(),i=Ac(t),s=i.getBoundingClientRect(),l=vu(n,vn(t)),a=cO(n,t),d=zo(t),{paddingTop:h,paddingBottom:p}=ku(d),{scrollWidth:C,clientWidth:v}=bc(t),B=document.documentElement.clientHeight-a,x=o.top+bc(e).clientHeight-B,I=B+Math.min(0,x);if(C>v&&r.top+h<I-s.height&&r.bottom>I-s.height+p&&!((D=l==null?void 0:l.isSetScale)!=null&&D.call(l))){l!=null&&l.allowScrollBarFixed&&V(i,Of.FIXED);const H=x>0?a:0;i.style.bottom=`${Math.max(document.documentElement.clientHeight-o.bottom,0)+fO+H}px`}else rt(i,Of.FIXED),i.style.bottom=`${Co(t,p-s.height)}px`;mO(t,i)}class gO{constructor(t,e){m(this,"intersectionObserver");m(this,"handleIntersection",t=>{t.forEach(e=>{this.containers.get(vn(e.target))?(this.handleIntersectionEntry(e),this.callback(e)):this.intersectionObserver.unobserve(e.target)})});m(this,"handleIntersectionEntry",t=>{const e=t.target;vc(this.scrollCore,e);const o=zo(e);_f(this.scrollCore,o)});this.scrollCore=t,this.callback=e;const r={root:this.scrollCore.getParentScrollContainer(),rootMargin:"20px",threshold:0};this.intersectionObserver=new IntersectionObserver(this.handleIntersection,r)}get containers(){return this.scrollCore.containers}bind(t){this.unbind(t),this.intersectionObserver.observe(t)}unbind(t){this.intersectionObserver.unobserve(t)}destroy(){this.intersectionObserver.disconnect()}}const Ys=M("container-scroll-shadow");function a4(n,t,e){const o=n,r=t.getBoundingClientRect(),i=e.getBoundingClientRect(),{paddingTop:s,paddingBottom:l}=ku(e);o.style.top=`${Co(t,i.top-r.top+s)}px`,o.style.bottom=`${Co(t,r.bottom-i.bottom+l)}px`}function u4(n,t){const e=n;t<24?e.style.width=`${(t/3).toFixed(2)}px`:e.style.width=""}function pO(n){const t=yu(n);g(Ys,t,"no container tools");let e=t.querySelector(`.${po.LEFT}`);if(!e){const l=zo(n),a=[po.COMMON,po.LEFT];e=k("div",a,t),g(Ys,e instanceof HTMLDivElement,"invalid child for container tools"),a4(e,n,l)}g(Ys,e instanceof HTMLElement,"invalid child for container tools");const r=vn(n).getBoundingClientRect(),i=n.getBoundingClientRect();e.style.left=`${Co(n,i.left-r.left)}px`;const s=bc(n).scrollLeft;g(Ys,e instanceof HTMLDivElement,"invalid child for container tools"),u4(e,s),V(e,po.ACTIVE)}function CO(n){const t=yu(n);let e=t.querySelector(`.${po.RIGHT}`);if(!e){const h=zo(n),p=[po.COMMON,po.RIGHT];e=k("div",p,t),g(Ys,e instanceof HTMLDivElement,"no div, create shadow failed"),a4(e,n,h)}g(Ys,e instanceof HTMLElement,"");const r=vn(n).getBoundingClientRect(),i=n.getBoundingClientRect();e.style.right=`${Co(n,r.right-i.right)}px`;const{scrollWidth:s,scrollLeft:l,clientWidth:a}=bc(n),d=s-l-a;g(Ys,e instanceof HTMLDivElement,"no shadow element"),u4(e,d),V(e,po.ACTIVE)}function bO(n){const e=yu(n).querySelector(`.${po.LEFT}`);e&&rt(e,po.ACTIVE)}function AO(n){const e=yu(n).querySelector(`.${po.RIGHT}`);e&&rt(e,po.ACTIVE)}function wu(n){const{scrollLeft:t,scrollWidth:e,clientWidth:o}=bc(n),r=zo(n),{paddingLeft:i,paddingRight:s}=ku(r),l=aO(r,"offsetLeft");e-i<=o-s||e-i<=t+o-s?AO(n):CO(n),r&&t>=l+i?pO(n):bO(n)}class vO{constructor(t,e){m(this,"resizeObserver");m(this,"handleResizeEntry",t=>{const e=t.target,o=zo(e);wu(e),_f(this.scrollCore,o),vc(this.scrollCore,e),this.callback(e)});m(this,"handleContentResize",t=>{t.forEach(e=>{this.containers.get(vn(e.target))?this.handleResizeEntry(e):this.unbind(e.target)})});this.scrollCore=t,this.callback=e,this.resizeObserver=new bs(this.handleContentResize)}get containers(){return this.scrollCore.containers}bind(t){this.unbind(t),this.resizeObserver.observe(t)}unbind(t){this.resizeObserver.unobserve(t)}destroy(){this.resizeObserver.disconnect()}}const d4=M("container-scroll-observer");class yO{constructor(t,e){m(this,"handleContentScroll",t=>{const e=t.target;g(d4,e instanceof Element,"invalid target for scroll event");const o=Ac(e);o.removeEventListener("scroll",this.handleScroll);const r=!0;this.fixScrollXPos(e,e.scrollLeft,r),this.bind(o),wu(e),this.callback(e)});m(this,"handleScroll",t=>{const e=t.target;g(d4,e instanceof HTMLElement,"");const o=e.scrollLeft,r=!1,i=lO(e);this.unbindContentScroll(i),this.fixScrollXPos(i,o,r),this.bindContentScroll(i),wu(i),this.callback(i)});m(this,"handlePrevent",t=>{t.stopPropagation()});m(this,"bindContentScrollCore",t=>{this.unbindContentScroll(t),t.addEventListener("scroll",this.handleContentScroll)});m(this,"unbindContentScroll",t=>{t.removeEventListener("scroll",this.handleContentScroll)});m(this,"bindContentScroll",Fe.default(this.bindContentScrollCore,300));m(this,"bind",Fe.default(this.bindCore,200));this.scrollCore=t,this.callback=e}fixScrollXPos(t,e,o){const r=Ac(t);o||(t.scrollLeft=e),o&&r.scrollLeft!==e&&(r.scrollLeft=e)}bindCore(t){this.unbind(t),t.addEventListener("scroll",this.handleScroll),t.addEventListener("mousedown",this.handlePrevent)}unbind(t){t.removeEventListener("scroll",this.handleScroll),t.removeEventListener("mousedown",this.handlePrevent)}}class kO{constructor(t){m(this,"scrollContainers",new Set);m(this,"handleParentContainerScroll",()=>{this.scrollContainers.forEach(t=>{vc(this.scrollCore,t)})});m(this,"bindScrollContainer",t=>{const e=this.scrollContainers.size===0;this.scrollContainers.add(t),e&&this.eventTarget.addEventListener("scroll",this.handleParentContainerScroll)});m(this,"unbindScrollContainer",t=>{let e=!1;this.scrollContainers.has(t)&&(this.scrollContainers.delete(t),e=this.scrollContainers.size===0),e&&this.eventTarget.removeEventListener("scroll",this.handleParentContainerScroll)});this.scrollCore=t}get eventTarget(){const t=this.scrollCore.getParentScrollContainer();return t===document.documentElement?document:t}destroy(){this.eventTarget.removeEventListener("scroll",this.handleParentContainerScroll),this.scrollContainers.clear()}}const wO=M("scroll-wrap-resize-observer");class BO{constructor(t){m(this,"resizeObserver");m(this,"handleScrollWrapResize",t=>{t.forEach(e=>{this.containers.get(vn(e.target))?this.handleScrollWrapResizeEntry(e):this.unbind(e.target)})});m(this,"handleScrollWrapResizeEntry",t=>{const e=t.target;g(wO,e instanceof HTMLElement,"invalid target for observer entry");const o=l4(e);_f(this.scrollCore,e),wu(o),vc(this.scrollCore,o)});this.scrollCore=t,this.resizeObserver=new bs(this.handleScrollWrapResize)}get containers(){return this.scrollCore.containers}bind(t){this.unbind(t),this.resizeObserver.observe(t)}unbind(t){this.resizeObserver.unobserve(t)}destroy(){this.resizeObserver.disconnect()}}class EO{constructor(t,e){m(this,"resizeObserver");m(this,"scrollContainersMap",new Map);m(this,"handleResizeEntry",t=>{t==null||t.forEach(e=>{const o=zo(e);wu(e),_f(this.scrollCore,o),vc(this.scrollCore,e),this.callback(e)})});m(this,"handleResize",t=>{t.forEach(e=>{const o=this.scrollContainersMap.get(e.target);o!=null&&o.length&&this.handleResizeEntry(o)})});this.scrollCore=t,this.callback=e,this.resizeObserver=new bs(this.handleResize)}bind(t){var r,i;const e=vn(t),o=(r=vu(this.scrollCore,e))==null?void 0:r.locatingContainer;this.scrollContainersMap.has(o)?(i=this.scrollContainersMap.get(o))==null||i.push(t):(this.scrollContainersMap.set(o,[t]),this.resizeObserver.observe(o))}unbind(t){var i,s;const e=vn(t),o=(i=vu(this.scrollCore,e))==null?void 0:i.locatingContainer;if(!o)return;const r=this.scrollContainersMap.get(o);this.scrollContainersMap.set(o,(r==null?void 0:r.filter(l=>l!==t))||[]),(s=this.scrollContainersMap.get(o))!=null&&s.length||(this.resizeObserver.unobserve(o),this.scrollContainersMap.delete(o))}destroy(){this.scrollContainersMap.clear(),this.resizeObserver.disconnect()}}const Oot="";class xO extends ke.TypedEmitter{constructor(e){super();m(this,"containerIntersectionObserver",null);m(this,"containerResizeObserver",null);m(this,"containerScrollObserver",null);m(this,"parentContainerScrollObserver",null);m(this,"scrollWrapResizeObserve",null);m(this,"locatingContainerResizeObserver",null);m(this,"isWindowEventBind",!1);m(this,"containers",new Map);m(this,"handleScrollContainerScroll",e=>{this.emit("scroll",this,e)});m(this,"handleResize",e=>{this.emit("resize",this,e)});m(this,"handleIntersection",e=>{const o=e.target,r=zo(o);e.isIntersecting?(this.load(),this.bindCore(o,r)):this.unbindCore(o,r)});m(this,"handleWindowEffect",()=>{var e;(e=this.getScrollContainerInViewable())==null||e.forEach(o=>{vc(this,o)})});this.parentContainer=e}load(){this.containerResizeObserver||(this.containerResizeObserver=new vO(this,this.handleResize)),this.containerScrollObserver||(this.containerScrollObserver=new yO(this,this.handleScrollContainerScroll)),this.parentContainerScrollObserver||(this.parentContainerScrollObserver=new kO(this)),this.scrollWrapResizeObserve||(this.scrollWrapResizeObserve=new BO(this)),this.locatingContainerResizeObserver||(this.locatingContainerResizeObserver=new EO(this,this.handleResize)),this.isWindowEventBind||(window.addEventListener("resize",this.handleWindowEffect),this.getParentScrollContainer()!==document.documentElement&&window.addEventListener("scroll",this.handleWindowEffect))}getParentScrollContainer(){return this.parentContainer}getScrollContainerInViewable(){var e;return(e=this.parentContainerScrollObserver)==null?void 0:e.scrollContainers}unbindCore(e,o){var i,s,l,a,d,h;const r=Ac(e);(i=this.containerScrollObserver)==null||i.unbindContentScroll(e),(s=this.containerScrollObserver)==null||s.unbind(r),(l=this.scrollWrapResizeObserve)==null||l.unbind(o),(a=this.containerResizeObserver)==null||a.unbind(e),(d=this.parentContainerScrollObserver)==null||d.unbindScrollContainer(e),(h=this.locatingContainerResizeObserver)==null||h.unbind(e)}bindCore(e,o){var s,l,a,d,h,p;if(this.unbindCore(e,o),!e.closest("body"))return;const r=Ac(e);(s=this.containerScrollObserver)==null||s.bindContentScrollCore(e),(l=this.containerScrollObserver)==null||l.bindCore(r),(a=this.scrollWrapResizeObserve)==null||a.bind(o),(d=this.containerResizeObserver)==null||d.bind(e);const i=this.containers.get(vn(e));i!=null&&i.allowScrollBarFixed&&((h=this.parentContainerScrollObserver)==null||h.bindScrollContainer(e)),(p=this.locatingContainerResizeObserver)==null||p.bind(e)}bind(e,o){this.containers.set(e,o);const r=e.firstElementChild;this.containerIntersectionObserver||(this.containerIntersectionObserver=new gO(this,this.handleIntersection)),this.containerIntersectionObserver.bind(r)}unbind(e){var i;const o=e.firstElementChild,r=zo(o);this.unbindCore(o,r),this.containers.delete(e),(i=this.containerIntersectionObserver)==null||i.unbind(o),this.containers.size||this.destroy()}destroy(){var e,o,r,i,s;this.containers.forEach((l,a)=>{this.unbind(a)}),this.containers.clear(),(e=this.parentContainerScrollObserver)==null||e.destroy(),(o=this.containerIntersectionObserver)==null||o.destroy(),(r=this.containerResizeObserver)==null||r.destroy(),(i=this.scrollWrapResizeObserve)==null||i.destroy(),(s=this.locatingContainerResizeObserver)==null||s.destroy(),window.removeEventListener("resize",this.handleWindowEffect),window.removeEventListener("scroll",this.handleWindowEffect)}}const h4=M("scroll-container"),Ff=new Map;class IO extends ke.TypedEmitter{constructor(){super(...arguments);m(this,"scrollListener");m(this,"options");m(this,"scrollContainerElement");m(this,"init",e=>{this.options=e;const o=k("div",[qi.CONTAINER],e.parentElement);ge.isMac&&V(o,qi.MAC);const r=k("div",[qi.SCROLL_CONTAINER],o),i=k("div",[qi.SCROLL_AREA],r);i.style.paddingLeft=e.paddingLeft?`${e.paddingLeft}px`:"",i.style.paddingTop=e.paddingTop?`${e.paddingTop}px`:"",i.style.paddingBottom=e.paddingBottom?`${e.paddingBottom}px`:"",i.style.paddingRight=e.paddingRight?`${e.paddingRight}px`:"",i.appendChild(e.childElement);const s=e.parentContainer;this.scrollListener=Ff.get(s),this.scrollListener||(this.scrollListener=new xO(s),Ff.set(s,this.scrollListener)),this.scrollListener.unbind(o),this.scrollListener.bind(o,e),this.scrollListener.on("scroll",this.handleContainerScroll),this.scrollListener.on("resize",this.handleResize),this.scrollContainerElement=r});m(this,"handleContainerScroll",(e,o)=>{o===this.scrollContainerElement&&this.emit("scroll",this)});m(this,"handleResize",(e,o)=>{o===this.scrollContainerElement&&this.emit("scroll",this)})}get rootElement(){return this.scrollContainerElement}get contentElement(){return g(h4,this.scrollContainerElement,"scrollContainerElement cannot be undefined"),zo(this.scrollContainerElement)}get scrollOptions(){return g(h4,this.options,"options cannot be undefined"),{...this.options}}handleBaseListenerDestroy(e){e.destroy()}destroy(){var o;(o=this.scrollListener)==null||o.off("scroll",this.handleContainerScroll);const e=vn(this.contentElement);e&&Ff.forEach((r,i)=>{r.unbind(e),r.containers.size===0&&(this.handleBaseListenerDestroy(r),Ff.delete(i))})}}function TO(){return new IO}const I0=M("column-width");function SO(n,t,e){FR(n,t).style.width=`${e}px`}function DO(n){const e=Array.from(n.querySelector("colgroup").children).map(a=>a.getBoundingClientRect().width);if(e[0]!==0)return e;const o=Tt.fromTable(n),r=Array(o.colCount).fill(-1),i=n.getBoundingClientRect().left;o.toRealCells(o.cells).forEach(a=>{const d=a.col+a.colSpan-1;r[d]===-1&&(r[d]=a.cell.getBoundingClientRect().right-i)}),I0.debug(`cellRightOffsets1: ${r.join()}`);for(let a=0;a<r.length;a++){const d=r[a];if(d===-1||a===0)continue;let h=a-1;for(;r[h]===-1&&(h--,h!==-1););const p=h===-1?0:r[h],v=(d-p)/(a-h);for(let B=h+1;B<a;B++)r[B]=p+v*(B-h)}I0.debug(`cellRightOffsets2: ${r.join()}`);const s=[];let l=0;for(let a=0;a<r.length;a++){const d=r[a];s.push(d-l),l=d}return I0.debug(`widths: ${s.join()}`),s}function Bu(n){return Array.from(n.querySelector("colgroup").children).map(o=>o.getBoundingClientRect().width||Number.parseInt(o.style.width,10))}const T0=200,MO=40,LO=M("table-resize-gripper"),f4=7,S0=(f4-1)/2,RO=3;function OO(n,t,e){const{rows:o}=n;for(let r=0;r<o.length;r++){const i=o[r],s=Array.from(i.cells);for(let l=0;l<s.length;l++){const a=s[l],d=a.getBoundingClientRect(),h=Math.round(d.right);if(Math.abs(t-h)<=S0&&d.top<=e&&e<=d.bottom)return a}}return null}function _O(n){return!!n.rootContainer.querySelector(".table-resize-gripper")}function D0(n,t){return Cr(n,t).querySelector(".table-resize-gripper")}function m4(n,t){const e=D0(n,t);g(LO,!e,"resize gripper has already exists");const o=Cr(n,t),r=k("div",["table-resize-gripper","table-indicator"],o);return k("div",["table-resize-gripper-indicator"],r),r}function g4(n,t,e){let o=D0(n,t);o||(o=m4(n,t));const i=$e(t).getBoundingClientRect(),s=e.getBoundingClientRect(),l=0,a=i.height,d=n.getCustom(pr(t)).contentElement.getBoundingClientRect(),h=s.right-d.left;o.style.left=`${h-S0-Cc-bu}px`,o.style.top=`${l}px`,o.style.height=`${a}px`,o.style.width=`${f4}px`}function M0(n){n.rootContainer.querySelectorAll(".table-resize-gripper").forEach(t=>{t.remove()})}function FO(n,t,e){const r={...n.getBlockData(t),colsWidth:e};n.updateBlockData(t,r)}function PO(n,t,e,o){const r=t,i=Tt.fromTable(e),s=i.getCellByCellElement(r),l=s.col+s.colSpan-1,a=Bu(e);let d=o;const h=(C,v)=>{const B=v+1,x=C.col+C.colSpan;return a.slice(B,x).reduce((_,D)=>_+D,0)},p=new Set;for(let C=0;C<i.rowCount;C++){const v=i.getCell({row:C,col:l});if(p.has(v.cell))continue;p.add(v.cell);const B=v.cell,x=B.getBoundingClientRect();let I=o-x.left+S0-RO;const _=gu(B),D=Bp(n,_)||MO*v.colSpan,H=h(v,l),W=D-H;I<W&&(I=W);const G=x.left+I;d=Math.max(d,G)}return d}const NO=M("table-resize-drag-drop");class $O{constructor(t,e,o,r){m(this,"cursor","col-resize");this.editor=t,this.elem=e,this.data=o,this.onEnd=r}onDragStart(t,e,o){}onDragging(t,e,o,r,i){const{table:s,block:l,draggingRefCell:a}=t.data,h=PO(this.editor,a,s,e.x-t.dragOffsetX)-s.getBoundingClientRect().left;g(NO,a,"no dragging cell");const C=Tt.fromTable(s).getCellByCellElement(a),v=C.col+C.colSpan-1,x=Bu(s).slice(0,v).reduce((_,D)=>_+D,0),I=h-x;SO(s,v,I),g4(this.editor,l,a),this.editor.selection.caret.update()}onDragEnd(t,e,o,r,i){const s=Bu(t.data.table);FO(this.editor,t.data.block,s),M0(this.editor),this.onEnd&&(this.onEnd(e),this.onEnd=null)}}function HO(n,t){const e=document.elementFromPoint(t.x,t.y);if(!e)return null;const o=nt(e);return!o||!n.contains(o)||!He(o)?null:o}M("table-resize");class jO{constructor(t){m(this,"draggingRefCell",null);m(this,"handleMouseMove",(t,e)=>{if(t.readonly||t.selectionHandler.isSelecting()&&!this.draggingRefCell||this.draggingRefCell)return;const o=e.target;if(!(o instanceof Element)||o.closest(".table-indicator"))return;const i=e,s=HO(t,i);if(!s||!Vw(s)||!t.isBlockWritable(s)){M0(t);return}this.updateGripper(s,i.x,i.y)});this.editor=t,t.domEvents.addEventListener(document,"mousemove",this.handleMouseMove)}destroy(){this.editor.domEvents.removeEventListener(document,"mousemove",this.handleMouseMove)}updateGripper(t,e,o){const r=$e(t),i=OO(r,e,o);if(i){if(!D0(this.editor,t)){if(_O(this.editor))return;const l=m4(this.editor,t),a={block:t,table:r,draggingRefCell:i};Xg(new $O(this.editor,l,a,d=>{this.updateGripper(t,d.x,d.y)}))}g4(this.editor,t,i)}else M0(this.editor)}}function p4(n){n.addCustom("table-mouse-event-handler",t=>new jO(t))}const C4=M("table-insert-column");function b4(n,t,e){n.undoManager.runInGroup(()=>{var C;const o=$e(t),r=Tt.fromTable(o),i=r.colCount;g(C4,e>=0&&e<=i,`insert index ${e} is out of range [0, ${i}]`);const s=r.map(v=>v.containerId),l=new Set;n.doc.beginBatchUpdate();for(let v=0;v<s.length;v++){const B=s[v],x=B[e-1],I=B[e];if(e===0||e===B.length||x!==I){const _=Zr(n.doc);B.splice(e,0,_)}else B.splice(e,0,x),l.add(x)}n.doc.endBatchUpdate();const a=mt.default(n.getBlockData(t));l.forEach(v=>{const B=`${v}_colSpan`,x=a[B];g(C4,typeof x=="number"&&x>1,`no colSpan for containerId ${v}, ${x}`),a[B]=x+1});const d=((C=a.colsWidth)==null?void 0:C.concat())||new Array(a.cols).fill(0);d.splice(e,0,T0);const h=Tt.virtualCellContainersGridToChildren(s),p={...a,cols:a.cols+1,children:h,colsWidth:d};Qs(p),n.updateBlockData(t,p)})}const Pf=M("table-insert-row");function A4(n,t,e){n.undoManager.runInGroup(()=>{const o=$e(t),r=Tt.fromTable(o),i=r.rowCount;g(Pf,e>=0&&e<=i,`insert index ${e} is out of range [0, ${i}]`);const s=r.map(C=>C.containerId),l=new Set;n.doc.beginBatchUpdate();const a=[];for(let C=0;C<r.colCount;C++){const v=e>0&&s[e-1][C],B=e<r.rowCount&&s[e][C];if(g(Pf,v||B,"no top and bottom cell"),e===0||e===r.rowCount||v!==B){const x=Zr(n.doc);a.push(x)}else g(Pf,v,"no top cell"),a.push(v),l.add(v)}n.doc.endBatchUpdate(),s.splice(e,0,a);const d=mt.default(n.getBlockData(t));l.forEach(C=>{const v=`${C}_rowSpan`,B=d[v];g(Pf,typeof B=="number"&&B>1,`no rowSpan for containerId ${C}, ${B}`),d[v]=B+1});const h=Tt.virtualCellContainersGridToChildren(s),p={...d,rows:d.rows+1,children:h};Qs(p),n.updateBlockData(t,p)})}const L0=M("paste-table-in-table-block");function UO(n,t,e,o){let r=Tt.fromBlock(e);const i=t.blocks.root[0];g(L0,i,"no table data"),g(L0,i.type==="table",`table data type is not table, but ${i.type}`);const s=i,l=r.getCellByCellElement(o),a=s.cols,d=s.rows,h=l.col,p=l.row,C=h+a,v=p+d,B=[];for(let x=h;x<C&&x<r.colCount;x++)for(let I=p;I<v&&I<r.rowCount;I++){const _=r.getCell({col:x,row:I});_.virtual?_.virtual&&B.push({col:x,row:I}):(_.colSpan>1||_.rowSpan>1)&&B.push({col:x,row:I})}n.undoManager.runInGroup(()=>{if(n.doc.beginBatchUpdate(),B.forEach(D=>{const H=Tt.fromBlock(e).getCell(D);(H.colSpan>1||H.rowSpan>1)&&A0(n,e,D)}),C>r.colCount)for(let D=r.colCount;D<C;D++)b4(n,e,D);if(v>r.rowCount)for(let D=r.rowCount;D<v;D++)A4(n,e,D);r=Tt.fromBlock(e);const x=new Sf(s);let I;for(let D=0;D<x.colCount;D++)for(let H=0;H<x.rowCount;H++){const W=x.getCell({col:D,row:H});if(!W.virtual){const G=d1(n.editorBlocks,t,W.containerId),K=h+D,ht=p+H,bt={col:K,row:ht},_t=r.getCellContainer(bt);Ey(n,_t,G),I=_t}}n.doc.endBatchUpdate(),g(L0,I,"no last container");const _=Ze(I);n.selection.selectBlock(_,ut(n,_))})}const v4=M("paste-in-table-block");class zO{constructor(t){this.editor=t,setTimeout(()=>{t.input.addHandler(this)})}destroy(){}async handleBeforePasteDoc(t,e){if(!t.selection.range.isSimple()||t.selection.range.start.offset!==0)return!1;const r=t.selection.startBlock,i=ot(r);if(Qt(i)||!Na(t,i))return!1;const s=nt(i);if(g(v4,s,"no parent block"),!He(s)||e.blocks.root.length!==1||e.blocks.root[0].type!=="table")return!1;v4.debug("paste child table in table");const d=Tt.fromBlock(s).getCellByContainerId(at(i)).cell;return UO(t,e,s,d),!0}}function y4(n){n.addCustom("table-block-paste-event",t=>new zO(t))}const R0=M("table-select-columns");function VO(n,t,e,o,r){g(R0,He(t),"is not a table block");const i=Tt.fromBlock(t);g(R0,e>=0&&e<i.colCount,"invalid from"),g(R0,o>0&&e+o<=i.colCount,"invalid count");const s=i.getCell({row:0,col:e}),l=i.getCell({row:i.rowCount-1,col:e+o-1}),a=me(t,s.containerId,{colIndex:e,rowIndex:0}),d=me(t,l.containerId,{colIndex:e+o-1,rowIndex:i.rowCount-1});r!=null&&r.reverse?n.selection.setSelection(d,a):n.selection.setSelection(a,d)}const O0=M("table-select-columns");function WO(n,t,e,o,r){g(O0,He(t),"is not a table block");const i=Tt.fromBlock(t);g(O0,e>=0&&e<i.rowCount,"invalid from"),g(O0,o>0&&e+o<=i.rowCount,"invalid count");const s=i.getCell({row:e,col:0}),l=i.getCell({row:e+o-1,col:i.colCount-1}),a=me(t,s.containerId,{rowIndex:e,colIndex:0}),d=me(t,l.containerId,{rowIndex:e+o-1,colIndex:i.colCount-1});r!=null&&r.reverse?n.selection.setSelection(d,a):n.selection.setSelection(a,d)}const _ot="",k4=M("get-toolbar-reference-client");function qO(n,t){const e=n.selection.range;if(!e.isSimple()){g(k4,e.start.blockId===e.end.blockId,"invalid selection range");const s=n.getBlockById(e.start.blockId);g(k4,Lt(n,s),"not a complex block");const l=Yt(n,s);if(l.getTextToolbarReferenceClient){const a=l.getTextToolbarReferenceClient(n,s);if(a)return a}}const o=e.isReverse()?t.start:t.end,r=We(n,{anchor:o,focus:o}),i=Ur(n,t.block,r);if(i.length!==0)return i[0]}function GO(n){var t,e;if(n.children){let o=!1;const r=[];for(const i of n.children){if((t=i.states)!=null&&t.includes("checked")){o=!0;break}(e=n.defaultCheckedChildren)!=null&&e.includes(i.id)&&r.push(i)}if(!o&&(r==null?void 0:r.length))for(const i of r)Array.isArray(i.states)?i.states.push("checked"):i.states=["checked"]}}function Nf(n){const t=(r,i)=>{const s=r.findIndex(a=>a.id===i.id);if(s===-1){r.push(i);return}const l=r[s];if(l.value!==i.value&&delete l.value,!!l.states){if(!i.states){l.states=[];return}l.states=Vg.default(l.states,i.states)}},e=[],o=new Map;return n.forEach(r=>{var i,s;(i=r.children)!=null&&i.length&&(o.has(r.id)?(s=o.get(r.id))==null||s.push(...r.children):o.set(r.id,[...r.children])),t(e,r)}),o.forEach((r,i)=>{const s=e.find(l=>l.id===i);s&&(s.children=Nf(r),GO(s))}),e}function $f(n){return n.findCustom("toolbar-handler")}const Fot="";class QO{constructor(){m(this,"linkPopup",null);m(this,"form",{});m(this,"onFinished",null);m(this,"onClose",null);m(this,"handleOk",async()=>{var t;try{await this.checkValue();const{linkText:e,linkUrl:o}=this.form,r=this.formatUrl(o.getInputValue());(t=this.onFinished)==null||t.call(this,e.getInputValue()||r,r),this._destroy()}catch{}});m(this,"handleClose",()=>{var t;(t=this.onClose)==null||t.call(this),this._destroy()});m(this,"onShow",()=>{setTimeout(()=>{var t;(t=this.form.linkText)==null||t.getField().focus()},400)});m(this,"onChange",()=>{var e;const t=(e=this.linkPopup)==null?void 0:e.content.querySelector('[data-button-id="submit-button"]');t.disabled=!1});m(this,"handleTextKeyboard",t=>{var e;if(!t.isComposing){if(t.key==="Enter"){(e=this.form.linkUrl)==null||e.getField().focus(),t.stopPropagation();return}t.key==="Escape"&&this.handleClose()}});m(this,"handleUrlKeyboard",t=>{if(!t.isComposing){if(t.key==="Enter"){this.handleOk(),t.preventDefault();return}t.key==="Escape"&&this.handleClose()}})}async checkValue(){const{linkUrl:t}=this.form;if(!t.getInputValue())throw t.setFieldError(L.t("link.urlPlaceholder")),new Error(L.t("link.urlPlaceholder"))}formatUrl(t){if(!t)return"";try{new URL(t)}catch{return`${window.location.protocol}//${t}`}return t}editLink(t){var h,p;const{target:e,linkText:o,linkUrl:r,onFinished:i,onClose:s,placement:l="bottom-start"}=t;this.linkPopup=new hu(this.createPopupContent(o,r)),this.linkPopup.addListener("show",this.onShow),this.linkPopup.manualShow(e,{theme:"light",placement:l}),this.onFinished=i,s&&(this.onClose=s);const a=(h=this.linkPopup)==null?void 0:h.content.querySelector('[data-button-id="submit-button"]'),d=(p=this.linkPopup)==null?void 0:p.content.querySelector('[data-button-id="cancel-button"]');a==null||a.addEventListener("click",this.handleOk),d==null||d.addEventListener("click",this.handleClose)}createPopupContent(t,e){const o=k("div",["link-popup-content"],null);this.form.linkText=u0(o,{label:L.t("link.textLabel"),required:!1,placeholder:L.t("link.textPlaceholder"),defaultValue:t,onChange:this.onChange,onKeyDown:this.handleTextKeyboard}),this.form.linkUrl=u0(o,{className:"link-popup-gap",label:L.t("link.urlLabel"),required:!0,placeholder:L.t("link.urlPlaceholder"),defaultValue:e,onChange:this.onChange,onKeyDown:this.handleUrlKeyboard});const r=k("div",["link-popup-footer"],o),i=mo("cancel-button",L.t("link.cancelText"));r.appendChild(i);const s=mo("submit-button",L.t("link.submitText"),void 0,["disabled","primary"]);return r.appendChild(s),o}_destroy(){var o,r,i,s;const t=(o=this.linkPopup)==null?void 0:o.content.querySelector('[data-button-id="submit-button"]'),e=(r=this.linkPopup)==null?void 0:r.content.querySelector('[data-button-id="cancel-button"]');t==null||t.removeEventListener("click",this.handleOk),e==null||e.removeEventListener("click",this.handleClose),this.onFinished=null,this.onClose=null,this.form={},(i=this.linkPopup)==null||i.removeAllListeners(),(s=this.linkPopup)==null||s.destroy()}destroy(){this._destroy()}}function Eu(n,t){n.addCustom("link-editor",()=>new QO).editLink(t)}const ZO=M("link-popup");function YO(n){return Et(n,"link")}function xu(n){var t,e;return(e=(t=n.getAttribute("link"))!=null?t:n.textContent)!=null?e:""}function JO(n,t,e){var r,i,s,l;if(n.isBlockWritable(t)&&e&&ao(e)){const a=e,d=(i=(r=n.editorBoxes.getBoxClass(Oa(a))).getBoxProperties)==null?void 0:i.call(r,n,a);if(d!=null&&d.boxCommands){const h=(l=(s=d.boxCommands["hovering-toolbar"])==null?void 0:s.commands)!=null?l:[];return{element:e,commands:h}}return{element:null,commands:[]}}if(n.isWritable()&&e&&et(n,t)&&YO(e)){const a=k("a",["link-href-button"],null,xu(e));a.href=xu(e),a.target="_blank",a.rel="noopener noreferrer";const d=[{id:"link-text",name:xu(e),disableTooltip:!0,element:a},{id:"edit-link",name:L.t("link.edit"),icon:xf},{id:"remove-link",name:L.t("link.remove"),icon:q2}];return{element:e,commands:d}}return j5(n,t,"hovering-toolbar")}function w4(n,t,e){var l;const o=_s(t,e),r=n.getBlockText(t),i={start:0,end:0};let s=(l=e.textContent)!=null?l:"";for(let a=0;a<r.length;a++){const d=r[a];if(i.end+d.insert.length>=o.end){i.end+=d.insert.length,s=d.insert;break}i.start<o.start&&(i.start+=d.insert.length,i.end=i.start)}return[i,s]}function KO(n,t,e){const[o,r]=w4(n,t,e);n.selection.selectBlock(t,o.start,o.end);const i=xu(e),s=(h,p)=>{try{const C=n.getBlockText(t),v=Np(C,o.start,o.end-o.start),B=Gr(v,o.start,h,{link:p});n.setBlockText(t,B),n.selection.selectBlock(t,o.start+h.length),n.focus()}catch(C){ZO.error(C)}},l=()=>{n.selection.selectBlock(t,o.end),n.focus()},a=Ur(n,t,n.selection.range)[0];if(!a)return;const d=qr(n,t,"link-button-anchor",a);Eu(n,{target:d,linkText:r,linkUrl:i,onFinished:s,onClose:l})}function XO(n,t,e){const[o]=w4(n,t,e),r=n.getBlockText(t),i=xu(e),s=tc(o.start,o.end-o.start,r,"link",i);n.setBlockText(t,s),n.selection.selectBlock(t,o.end)}function t_(n,t,e,o){var s,l,a;if(e){if(n.isBlockWritable(t)&&ao(e)){const h=e,p=(l=(s=n.editorBoxes.getBoxClass(Oa(h))).getBoxProperties)==null?void 0:l.call(s,n,h);if(p!=null&&p.boxCommands){p.boxCommands["hovering-toolbar"].executeCommand(n,t,h,o);return}return}const d=$f(n);d==null||d.disableTextToolbar(),d==null||d.hide(),setTimeout(()=>{d==null||d.enableTextToolbar()},400),o.id==="edit-link"?KO(n,t,e):o.id==="remove-link"&&XO(n,t,e);return}const r=H5(n,t);if(!r)return;const i=(a=r.blockCommands)==null?void 0:a["hovering-toolbar"];!i||i.executeCommand(n,t,o)}function Hf(){let n=8;for(;n>0&&!document.querySelector(`div[data-style-heading='${n}']`);)n--;return n}const e_=[pf,Cf,bf,Af,vf,yf,kf,wf];class n_{constructor(t){m(this,"id","BlockTurnIntoCommandProvider");this.editor=t}getHeadingIndex(){let t=Hf();return t<=4?t=5:t<8&&(t+=1),t}getAvailableCommands(t,e,o){if(et(t,e)){const r=it(e),i=St(e),s=Do(t,e),a=t.getBlockData(e).heading,d=[];for(let p=0;p<this.getHeadingIndex();p++)d.push({id:`heading-${p+1}`,name:L.t("commands.heading",{name:`${p+1}`}),icon:e_[p],states:a===p+1?["checked"]:[],value:`${p+1}`});const h=p=>{var v;const C=k("span",["toolbar-item-name-container"],null);for(const B of p.children)if((v=B.states)!=null&&v.includes("checked"))return C.innerHTML=B.icon||hc,C;return C.innerHTML=hc,C};return[{id:"turn-into",name:L.t("commands.headingGroup"),blockId:r,blockType:i,blockKind:s,element:h,groupIndex:200,dropdown:!0,manualShowChildren:!0,childrenPlacement:"bottom-start",defaultCheckedChildren:["text"],children:[{id:"text",name:L.t("commands.text"),icon:hc,states:a?[]:["checked"]},...d],childrenType:"menu"}]}return[]}applyHeadingStyle(t,e,o){t.updateBlockData(e,{heading:o})}executeCommand(t,e,o,r){if(et(t,e)&&(r.id.startsWith("heading-")||r.id==="text")){const i=r.value?Number(r.value):null;return this.applyHeadingStyle(t,e,i),!0}return!1}}const o_=8,Be=M("list-block"),jf=M("list-block");function Nt(n){return St(n)==="list"}function De(n){g(jf,Nt(n),"not a list block")}function Gn(n){De(n);const t=n.getAttribute("data-list-type");return g(jf,t,"no list type"),t}function Uf(n){return Nt(n)&&Gn(n)==="text-only"}function Qn(n){var t,e;return De(n),(e=Number.parseInt((t=n.getAttribute("data-list-start"))!=null?t:"1",10))!=null?e:1}function tn(n){var t,e;return De(n),(e=Number.parseInt((t=n.getAttribute("data-list-level"))!=null?t:"1",10))!=null?e:1}function yc(n){De(n);const t=n.getAttribute("data-list-group-id");return g(jf,t,"no group id"),t}function Gi(n){var i,s,l,a,d;De(n);const t=(i=n.getAttribute("data-list-type"))!=null?i:"ordered",e=(l=Number.parseInt((s=n.getAttribute("data-list-start"))!=null?s:"1",10))!=null?l:1,o=(d=Number.parseInt((a=n.getAttribute("data-list-level"))!=null?a:"1",10))!=null?d:1,r=n.getAttribute("data-list-group-id");return g(jf,r,"no group id"),{type:t,start:e,level:o,groupId:r}}function _0(n){switch(n){case"ordered":return{ordered:!0,checkbox:null,textOnly:null};case"unordered":return{ordered:!1,checkbox:null,textOnly:null};case"checked":return{checkbox:"checked",ordered:!1,textOnly:null};case"unchecked":return{checkbox:"unchecked",ordered:!1,textOnly:null};case"text-only":return{checkbox:null,ordered:!1,textOnly:!0};default:return{checkbox:null,ordered:!0,textOnly:!1}}}function r_(n){const t={M:1e3,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1};let e="",o=n;return Object.entries(t).forEach(([r,i])=>{for(;o>=i;)e+=r,o-=i}),e.toLowerCase()}const i_="abcdefghijklmnopqrstuvwxyz";function B4(n){if(n<=0)return`${n}`;const t=(n-1)%26,e=Math.floor((n-1)/26),o=i_[t];return e?B4(e)+o:o}function s_(n){return`${n}`}const E4=[s_,B4,r_];function l_(n,t){const e=E4[(n-1)%E4.length];return e(t)}function c_(n){return["\u2022","\u25E6","\u25AA"][(n-1)%3]}function Qi(n,t){De(n);const{level:e,groupId:o,type:r}=Gi(n);let i=ae(n);for(;i;){if(!Nt(i))return null;const{level:s,groupId:l,type:a}=Gi(i);if(s<e)return null;if(e===s&&((t==null?void 0:t.ignoreGroupId)||o===l)&&(a==="text-only"||r==="text-only"||r===a))return i;i=ae(i)}return null}function x4(n){return Qi(n,{ignoreGroupId:!0})}function Js(n){De(n);const{level:t,groupId:e,type:o}=Gi(n);let r=qt(n);for(;r;){if(Nt(r)){const{level:i,groupId:s,type:l}=Gi(r);if(t===i&&e===s&&(l==="text-only"||o==="text-only"||o===l))return r;if(i<t)return null}r=qt(r)}return null}function I4(n){De(n);const t=[];let e=Qi(n);for(;e;)t.unshift(e),e=Qi(e);return t}function kc(n){De(n);const t=[];let e=Js(n);for(;e;)t.push(e),e=Js(e);return t}function Iu(n){De(n);let t=Qi(n);for(;t;){const e=Qi(t);if(!e)return t;t=e}return n}function a_(n){De(n);let t=Js(n);for(;t;){const e=Js(t);if(!e)return t;t=e}return null}function T4(n,t){const e=I4(n),o=kc(n);return t.withSelf?[...e,n,...o]:[...e,...o]}function zf(n){De(n);let t=n;const e=I4(n);e.length>0&&(t=e[0]);const o=ae(t);return!o||!Nt(o)?null:tn(o)<tn(t)?o:null}function u_(n,t){De(n);let e=n;for(;e;){const o=tn(e);if(o===t)return e;if(o>t)e=zf(e);else if(o<t)return null}return null}function d_(n){let t=Iu(n);for(;;){const e=zf(t);if(!e)return t;t=Iu(e)}}class h_{constructor(){m(this,"nodeMap",new Map);m(this,"rootNodes",[])}addNode(t,e){const o={block:e,children:[]};if(this.nodeMap.set(e,o),t){const r=this.nodeMap.get(t);g(Be,r,"no parent node"),r.children.push(o)}else this.rootNodes.push(o)}}function S4(n,t){const e=d_(t),o=new h_;o.addNode(null,e);let r=qt(e);for(;r&&Nt(r);){if(Uf(r)){o.addNode(null,r),r=qt(r);continue}if(tn(r)===0&&Gn(r)!==Gn(e))break;const s=zf(r);o.addNode(s,r),r=qt(r)}return o.rootNodes}function f_(n){const t=document.fullscreenEnabled||document.mozFullScreenEnabled||document.documentElement.webkitRequestFullScreen,e=o=>{if(o.requestFullscreen)return o.requestFullscreen();if(o.mozRequestFullScreen)return o.mozRequestFullScreen();if(o.webkitRequestFullScreen){try{document.fullscreenElement=n}catch{}return o.webkitRequestFullScreen()}return Promise.resolve(0)};return t?e(n):Promise.resolve(0)}function D4(){const e=(document.exitFullscreen||document.webkitExitFullscreen).bind(document)();try{document.fullscreenElement=null}catch{}return e}function F0(n){return Et(n,"editor-in-mindmap-first")}function P0(n){if(g(Be,Nt(n),"not a list block"),Et(n,"editor-in-mindmap-first")||!Ra(n))return!0;const t=n.classList,e="editor-mindmap-root-";return!!Array.from(t).find(r=>{if(r.startsWith(e))return r})}function m_(n,t,e){const o=ot(n);if(t){const s=ot(t);g(Be,o===s,"invalid block container")}const r=vt(n);if(t){const s=vt(t);g(Be,r<=s,"invalid block index")}if(V(n,...e),!t||t===n)return;let i=qt(n);for(;i!==t;)g(Be,i,"no next button"),V(i,...e),i=qt(i);i&&V(i,...e)}function g_(n){const t=`editor-mindmap-root-${n.id}`,o=ot(n).querySelectorAll(`.${t}`);return o[o.length-1]}async function p_(n,t,e){const o=te(t),r=o.querySelector('[data-button-id="mindmap-fullscreen"]');g(Be,r,"no full screen button");const i=()=>{setTimeout(()=>{e.toMindmap(n,t,{},{reset:!0,mindmapTools:e})},300)},s=()=>{rt(o,"fullscreen"),r.innerHTML=l0,r.setAttribute(`data-editor-tooltip-${n.clientId}-dynamic`,L.t("mindmap.fullScreen")),P0(t)&&setTimeout(()=>{i()},300)};if(document.fullscreenElement===o){try{await D4()}catch(l){Be.error(l)}s()}else{try{V(o,"fullscreen"),await f_(o),i()}catch(l){Be.error(l)}r.innerHTML=Sw,r.setAttribute(`data-editor-tooltip-${n.clientId}-dynamic`,L.t("mindmap.exitFullscreen"))}o.onfullscreenchange=()=>{document.fullscreenElement||s()}}function N0(n,t,e,o,r){if(t.querySelector(`[data-button-id="${e}"]`))return null;const s=mo(e,o,r,[]);return s.setAttribute(`data-editor-tooltip-${n.clientId}-dynamic`,o),V(s,"mindmap-button"),t.appendChild(s),s}function $0(n,t){return n.querySelector(`[data-button-id="${t}"]`)}function C_(n){return $0(n,"mindmap-fullscreen")}function b_(n){return $0(n,"mindmap-fit")}function A_(n){return $0(n,"mindmap-close")}function v_(n,t,e,o){const r=N0(n,t,"mindmap-close",L.t("mindmap.close"),mf);!r||n.domEvents.addEventListener(r,"click",()=>{o.closeMindmap(n,e)})}function y_(n,t,e,o){const r=N0(n,t,"mindmap-fit",L.t("mindmap.autoFit"),Tw);!r||n.domEvents.addEventListener(r,"click",()=>{o.fitMindmap(n,e)})}function k_(n,t,e,o){if(navigator.userAgent.includes("Mobile")&&!navigator.userAgent.includes("iPad"))return;const i=N0(n,t,"mindmap-fullscreen",L.t("mindmap.fullScreen"),l0);!i||n.domEvents.addEventListener(i,"click",()=>{p_(n,e,o)})}function w_(n,t){const e=ph(t);if(!e)return;const o=b_(e);o&&(o.remove(),n.domEvents.removeAllListeners(o));const r=A_(e);r&&(r.remove(),n.domEvents.removeAllListeners(r));const i=C_(e);i&&(i.remove(),n.domEvents.removeAllListeners(i))}const wc=new Map;function H0(n,t,e){const o=(s,l)=>{s.forEach(a=>{l?V(a.block,"to-mindmap-highlight"):rt(a.block,"to-mindmap-highlight"),o(a.children,l)})},r=S4(n,t);if(r.length===0)return;const i=r[0].block;if(e){const s=wc.get(i);s&&(s.forEach(l=>l.cancel()),wc.delete(i)),o(r,!0)}else{const s=setTimeout(()=>{o(r,!1),wc.delete(i)},300),l=()=>{clearTimeout(s),wc.delete(i)},a=wc.get(i);a?a.push({cancel:l}):wc.set(i,[{cancel:l}])}}const{Markmap:B_}=sI;function E_(n,t){De(t);const e=S4(n,t),o=e[0].block,r=d=>({t:"text",v:Mt(d.block).textContent,d:1,c:d.children.length>0?d.children.map(p=>r(p)):void 0});let i=null;e.length>1?i={t:"root",v:"root",d:0,c:e.length>0?e.map(d=>r(d)):void 0}:i=r(e[0]);const l=d=>{if(d.length===0)return null;const h=d[d.length-1];return h.children&&h.children.length>0?l(h.children):h},a=l(e);return{root:i,block:o,nodes:e,last:a}}function Vf(n,t,e,o){const{root:r,block:i,last:s}=E_(n,t);o.selectBlock&&n.selection.selectBlock(i,0,0),H0(n,i,!1),o.saveData&&n.updateBlockData(i,{viewAsMindmap:!0});const l=te(i);let a=l.querySelector(".editor-mindmap-svg");if(o.reset&&(a&&a.remove(),a=null),a)a.innerHTML="";else{const _="http://www.w3.org/2000/svg",D=l.getBoundingClientRect(),H=document.fullscreenElement===l,W=H?`${D.width}`:`${t.getBoundingClientRect().width}`,G=H?`${D.height}`:"600",K=document.createElementNS(_,"svg");K.setAttributeNS(null,"viewBox",`0 0 ${W} ${G}`),K.setAttributeNS(null,"width","100%"),K.setAttributeNS(null,"height",G),K.style.display="block",K.style.width="100%",K.style.height=`${G}px`,K.classList.add("editor-mindmap-svg"),l.appendChild(K),a=K}const d=i,p=`editor-mindmap-root-${it(i)}`;V(d,"editor-in-mindmap-first",p,"readonly"),d.contentEditable="false";const C=qt(i);C&&vt(C)<=vt(s.block)&&m_(C,s.block,["block-hidden",p]);const v=(_,D)=>{if(D.length>0){const H=D[0].parentElement;H&&(H.style.width="100vw",H.style.maxWidth="200px")}D.forEach(H=>{V(H,"editor-mindmap-node")})},B=new B_(a,{...e,autoFit:!0});B.viewHooks.transformHtml.tap(v),B.setData(r),B.fit();const x=te(i);let I=x.querySelector(".mindmap-toolbar");I||(I=k("div",["mindmap-toolbar"],x)),y_(n,I,d,o.mindmapTools),k_(n,I,d,o.mindmapTools),v_(n,I,d,o.mindmapTools),n.domEvents.addEventListener(a,"click",()=>{n.selection.selectBlock(i,0),n.input.focus()}),d.mindMap=B}function x_(n){const t=k("div",["list-to-mindmap-wrap"],null),e=mo("list-to-mindmap",L.t("mindmap.viewAsMindMap"),Iw,[],n.clientId);return t.appendChild(e),t}async function M4(n,t){const e=`editor-mindmap-root-${t.id}`,o=ot(t);fe(o).forEach(l=>{Et(l,e)&&rt(l,e,"editor-in-mindmap-first","block-hidden")});const i=te(t);document.fullscreenElement===i&&await D4();const s=i.querySelector(".editor-mindmap-svg");!s||(g(Be,s,"no mindmap svg"),s.remove(),n.domEvents.removeAllListeners(s),w_(n,t))}function I_(n){const t=n.classList,e="editor-mindmap-root-";return Array.from(t).find(r=>{if(r.startsWith(e))return r})}async function L4(n,t){!I_(t)||(n.updateBlockData(t,{viewAsMindmap:null}),M4(n,t),n.selection.selectBlock(t,0))}function T_(n,t){const e=t.mindMap;e&&e.fit()}const Wf={toMindmap:Vf,closeMindmap:L4,fitMindmap:T_},Pot="";class qf{constructor(t){m(this,"toMindmapButton");m(this,"currentBlock",null);m(this,"handleHoveringBlock",t=>{t&&Nt(t)&&Gn(t)!=="unchecked"&&Gn(t)!=="checked"&&this.editor.isWritable()?te(t).appendChild(this.toMindmapButton):this.toMindmapButton.remove()});m(this,"handleMouseEnter",()=>{const t=nt(this.toMindmapButton);g(Be,t&&Nt(t),"no parent list"),H0(this.editor,t,!0),this.currentBlock=t});m(this,"handleMouseLeave",()=>{this.currentBlock&&(H0(this.editor,this.currentBlock,!1),this.currentBlock=null)});m(this,"handleClick",()=>{const t=nt(this.toMindmapButton);g(Be,t&&Nt(t),"no parent list"),Vf(this.editor,t,{},{saveData:!0,selectBlock:!0,mindmapTools:Wf})});this.editor=t,Ae.get(this.editor).addListener("change",this.handleHoveringBlock),this.toMindmapButton=x_(t),t.domEvents.addEventListener(this.toMindmapButton,"mouseenter",this.handleMouseEnter),t.domEvents.addEventListener(this.toMindmapButton,"mouseleave",this.handleMouseLeave),t.domEvents.addEventListener(this.toMindmapButton,"click",this.handleClick)}static get(t){return t.findCustomByType(qf)}destroy(){Ae.get(this.editor).removeListener("change",this.handleHoveringBlock)}hide(){this.currentBlock&&(this.currentBlock=null),this.toMindmapButton.remove()}}function S_(n,t,e){var o;t==="beginDrag"&&((o=qf.get(n))==null||o.hide())}function Bc(n,t,e,o){var i;const r=(i=o==null?void 0:o.groupId)!=null?i:tt();t.forEach(s=>{const l=n.getBlockData(s);if(l.start!==e||(o==null?void 0:o.resetGroupId)){const a={...l,start:e};o!=null&&o.resetGroupId&&(a.groupId=r),n.updateBlockData(s,a)}l.textOnly||(e+=1)})}function j0(n,t,e,o){const r=T4(t,{withSelf:!0});r.length!==0&&Bc(n,r,e,o)}class Gf{constructor(t,e){m(this,"listStart",0);m(this,"listBrother",null);if(this.editor=t,Uf(e))return;const o=Iu(e),r=Qn(o);this.listStart=r,o===e?this.listBrother=Js(o):this.listBrother=o}fix(){!this.listBrother||j0(this.editor,this.listBrother,this.listStart)}}class Ks{constructor(t,e,o){m(this,"listStart");m(this,"listBrother",null);this.editor=t,this.options=o;const r=Iu(e),i=Qn(r);this.listStart=i,this.listBrother=r,o!=null&&o.resetStart&&(this.listStart=1)}fix(){!this.listBrother||j0(this.editor,this.listBrother,this.listStart,this.options)}}class R4{constructor(t,e,o){m(this,"listStart");m(this,"listNextBrothers",[]);this.editor=t,this.listNextBrothers=kc(e);const{start:r,resetStart:i}=o||{};this.listStart=i?1:r!=null?r:1}fix(){!this.listNextBrothers.length||Bc(this.editor,this.listNextBrothers,this.listStart)}}function D_(n,t,e){n.getBlockData(t).quoted&&(e.quoted=!0)}function U0(n,t,e,o){if(Be.debug("drag a block on a list block"),!et(n,t))return!1;g(Be,Nt(e),"target is not a list block");const{type:r,start:i,level:s,groupId:l}=Gi(e),a=o==="after"?i+1:i,d=n.getBlockData(t),h={id:tt(),type:"list",groupId:l,level:s,start:a,text:d.text,..._0(r)};D_(n,e,h);let p=vt(e);const C=ot(e);o==="after"&&(p+=1);let v=null;Nt(t)&&(v=new Gf(n,t));const B=n.insertBlock(at(C),p,h,Oh(h.id,0));return n.deleteBlock(t),new Ks(n,B).fix(),v==null||v.fix(),!0}function M_(n,t,e,o){if(Be.debug("drag a list between text blocks"),o==="after"){const d=qt(e);if(d&&Nt(d))return U0(n,t,d,"before")}if(o==="before"){const d=ae(e);if(d&&Nt(d))return U0(n,t,d,"after")}const i={...n.getBlockData(t),groupId:tt(),start:1,level:1};let s=vt(e);const l=ot(e);o==="after"&&(s+=1),n.insertBlock(at(l),s,i,Oh(i.id,0));const a=new Gf(n,t);return n.deleteBlock(t),a.fix(),!0}function L_(n,t,e,o,r){if(dh(e))return!1;const{blockId:i}=e,s=n.getBlockById(i);g(Be,s,"no dragged block");const{isSourceBlock:l,targetBlock:a}=r;return!l&&a?(g(Be,t===a,"block !== target block"),g(Be,Nt(a),"target is not a list block"),U0(n,s,a,o)):M_(n,s,a,o)}function O4(n,t){if(!n.isWritable())return!1;const e=n.selection.range,r=n.editorCommandProviders.getCommands(e).find(i=>i.id===t);return r?(n.editorCommandProviders.executeCommand(e,r,{}),!0):!1}const R_={"Shift+CtrlOrCmd+L":n=>O4(n,"unordered-list"),"Shift+CtrlOrCmd+U":n=>O4(n,"ordered-list")};function Qf(n){const t=n.getAttribute("block-padding-level");return t?Number(t):null}function O_(n,t){let e;const o=Qf(t);if(!o)e=1;else{if(o>=12)return e=12,!1;e=o+1}return n.updateBlockData(t,{...n.getBlockData(t),padding:e}),!0}function _4(n,t){const e=Qf(t);if(!e)return!1;const o=n.getBlockData(t);return e>1?(n.updateBlockData(t,{...o,padding:e-1}),!0):(n.updateBlockData(t,{...o,padding:null}),!0)}function z0(n){return n.readonly||!n.isWritable()}function __(n){return n.selection.range.getSelectedBlocks().forEach(e=>{const o=e.block;et(n,o)&&O_(n,o)}),!0}function F_(n){return n.selection.range.getSelectedBlocks().forEach(e=>{const o=e.block;et(n,o)&&_4(n,o)}),!0}function P_(n){return z0(n)?!1:n.undoManager.runInGroup(()=>(__(n),!0))}function N_(n){return z0(n)?!1:n.undoManager.runInGroup(()=>(F_(n),!0))}function $_(n){if(z0(n))return!1;if(!n.selection.range.isCollapsed())return;const t=n.selection.focusedBlock;if(!et(n,t))return;const e=n.selection.range.focus;if(!(!e.isSimple()||e.offset!==0||!Qf(t)))return _4(n,t),!0}class V0{renderBlock(t,e,o){const{padding:r}=o;return r?{attributes:{"block-padding-level":r}}:{}}}const Not="",H_={Tab:P_,"Shift+Tab":N_,Backspace:$_};function j_(n,t,e=1){if(!t)return null;let o=ae(n);for(;o;){const r=o.getAttribute("data-style-heading"),i=Number(o.getAttribute("data-list-level"));if(r){if(r<t)return null;if(r===t&&i===e)return Nt(o)?o:null}o=ae(o)}return null}function U_(n,t){const e=n.getAttribute("data-style-heading"),o=j_(n,e);if(o)return o;const r=ae(n);if(r&&Nt(r)&&Gn(r)===t)return r;const i=qt(n);return i&&Nt(i)&&Gn(i)===t?i:null}function z_(n,t,e){var x,I,_;const o=(x=e.data)!=null?x:{};let r=1;if(Nt(t))r=tn(t);else{const D=Qf(t);D&&(r=D+1),r>8&&(r=8)}const i=(I=o.listType)!=null?I:"ordered";if(i==="text-only")return null;const s=n.getBlockData(t);let l=(_=s.text)!=null?_:[],d=se(l);const h=e.offset||0;h<=sn(l)&&(l=Tn(l,h).right,d=d.substring(0,h));let p=1;i==="ordered"&&(p=Number.parseInt(d,10)||1);let C=tt();const v=U_(t,i);if(v)if(tn(v)===r){if(vt(t)>vt(v))p=Qn(v)+1;else{const D=Qn(v);D>1&&(p=D-1),new R4(n,v,{start:p+1}).fix()}C=yc(v)}else{const D=u_(v,r);D&&(p=Qn(D)+1)}else Nt(t)&&new R4(n,t,{start:1}).fix();const B={id:tt(),type:"list",level:r,start:p,groupId:C,ordered:!1,text:l};return s.quoted&&(B.quoted=!0),s.heading&&(B.heading=s.heading),i==="ordered"?B.ordered=!0:(i==="checked"||i==="unchecked")&&(B.checkbox=i),{blockData:B,onConverted:(D,H)=>{new Ks(D,H).fix()}}}function Ec(n){return n.textOnly?"text-only":n.checkbox?n.checkbox:n.ordered?"ordered":"unordered"}function V_(n){var e,o;if(n.checkbox||n.textOnly)return"";const t=(e=n.level)!=null?e:1;return n.ordered?`${l_(t,(o=n.start)!=null?o:1)}.`:c_(t)}function Zf(n){return n==="checked"||n==="unchecked"}function F4(n,t,e,o){const r=t,{containerId:i,blockIndex:s}=o[o.length-1];if(s===0)return!0;const l=e.blocks[i][s-1];if(l.type!=="list")return!0;const a=Ec(r),d=Ec(l);return a!==d&&(!Zf(a)||!Zf(d))||r.level>l.level}function P4(n,t,e,o){const r=t,{containerId:i,blockIndex:s}=o[o.length-1];if(s===e.blocks[i].length-1)return!0;const l=e.blocks[i][s+1];if(l.type!=="list")return!0;const a=Ec(r),d=Ec(l);return a!==d&&(!Zf(a)||!Zf(d))||r.level>l.level}function W_(n,t,e,o,r){var s,l,a;const i=t;if(o==="text")return((s=Sn.convertTo)==null?void 0:s.call(Sn,n,t,e,"text",r))||"";if(o==="markdown"){let d=((l=Sn.convertTo)==null?void 0:l.call(Sn,n,t,e,"markdown",r))||"";i.checkbox==="checked"?d=`[x] ${d}`:i.checkbox==="unchecked"&&(d=`[ ] ${d}`),i.ordered?d=`${i.start}. ${d}`:d=`- ${d}`;const h=i.level||0;return d=(h>0?" ".repeat(h-1):"")+d,F4(n,t,e,r)&&(d=`${d}`),P4(n,t,e,r)&&(d=`${d}`,h<=1&&(d+=`
|
|
598
598
|
`)),d}if(o==="html"){let d=((a=Sn.convertTo)==null?void 0:a.call(Sn,n,t,e,"html",r))||"";d=d.replace("<p>","").replace("</p>",""),i.checkbox==="checked"?d=`<input type="checkbox" checked="checked" disabled="disabled" /> ${d}`:i.checkbox==="unchecked"&&(d=`<input type="checkbox" disabled="disabled" /> ${d}`);let h="ul";return i.ordered?(d=`<li value="${i.start}">${d}</li>`,h="ol"):d=`<li>${d}</li>`,F4(n,t,e,r)&&(d=`<${h}>${d}`),P4(n,t,e,r)&&(d=`${d}</${h}>`),d}return""}function N4(n){const t=k("label",["editor-check-list-wrapper"],null);n&&V(t,"editor-check-list-wrapper-checked");const e=k("span",["editor-check-box"],t);return k("span",["editor-check-box-inner"],e),t}function q_(n,t){const e=Ec(t);if(e!=="text-only"){if(e==="checked"){n.append(N4(!0));return}if(e==="unchecked"){n.append(N4(!1));return}n.innerText=V_(t)}}function G_(n){const t=k("div",["list-container"],null),e=k("button",["list-marker"],t);return q_(e,n),t}function xc(n,t){De(t);const e=n.getBlockData(t),o={id:tt(),type:"text",text:e.text};e.heading&&(o.heading=e.heading),e.heading&&(o.heading=e.heading);const r=new Gf(n,t),i=ot(t),s=vt(t);n.deleteBlock(t);const l=Oh(o.id,0);if(Na(n,i)&&!Qt(i)){const a=we(i);n.insertBlock(at(i),s,o,l),n.deleteBlock(a)}else n.insertBlock(at(i),s,o,l);r.fix()}function Q_(n){if(!n.selection.range.isCollapsed())return!1;const t=n.selection.focusedBlock;if(!Nt(t))return!1;const e=n.selection.range.focus;return!e.isSimple()||e.offset!==0?!1:(xc(n,t),!0)}function $4(n){let t=qt(n);if(!t)return null;const e=Js(n);for(;t!==e;){if(g(Be,t,"no next block"),Nt(t))return tn(t)>tn(n)?t:null;if(t=qt(t),!t)return null}return null}function W0(n){const t=[];let e=$4(n);if(!e)return t;for(;e;){const o=Js(e);t.push({block:e,children:W0(e)}),e=o}return t}function Z_(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 H4(n,t){return tn(t)!==1}function j4(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&&j4(n,o.children,r.groupId)})}function q0(n,t){if(!H4(n,t))return!1;const e=tn(t);if(e===1)return!1;let o=tt(),r=1,i=Gn(t);const s=e-1,l=zf(t);l&&(o=yc(l),r=Qn(l)+1,i!=="text-only"&&(i=Gn(l)));const a=W0(t),d=n.getBlockData(t),h={...d,groupId:o,level:s,start:r,..._0(i)};n.updateBlockData(t,h),n.doc.beginBatchUpdate(),j4(n,a,d.groupId),n.doc.endBatchUpdate(),new Ks(n,t).fix();const C=$4(t);return C&&new Ks(n,C,{resetStart:!0,resetGroupId:!0}).fix(),!0}const Y_=M("list-block");function J_(n,t,e){g(Y_,Nt(t),"not a list block");const o={...n.getBlockData(t),id:tt()};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 K_(n){if(De(n),!Uf(n))return n;let t=Qi(n);for(;t;){if(!Uf(t))return t;t=Qi(t)}return null}function X_(n,t,e,o){const r=new Ks(n,o),i=Qn(o)+1;rc(n,t,e,{forceInsertAfter:!0,newBlockData:J_(n,o,{start:i})}),r.fix()}function tF(n){var s;if(n.selection.range.isCollapsed()){const l=n.selection.focusedBlock;if(Nt(l)&&ut(n,l)===0)return tn(l)===1?xc(n,l):q0(n,l),!0}n.clearSelectedContents();const t=n.selection.focusedBlock;if(!Nt(t))return!1;const e=n.selection.range.focus;if(!e.isSimple())return!1;const o=e.offset,i=(s=o===ut(n,t)?K_(t):t)!=null?s:t;return X_(n,t,o,i),!0}function U4(n){g(Be,Nt(n),"not a list block");const{level:t}=Gi(n);let e=ae(n);for(;e;){if(Nt(e)){const{level:o}=Gi(e);if(t===o)return e;if(o<t)return null}e=ae(e)}return null}function z4(n,t){return De(t),U4(t)?tn(t)<o_:!1}function eF(n,t,e){let o=ae(t);g(Be,o,"no prev brother");const r=tn(e);for(;o;){if(o===e)return null;if(Nt(o)&&tn(o)===r+1)return o;o=ae(o)}return null}function V4(n,t){if(!z4(n,t))return!1;De(t);const e=U4(t);g(Be,e,"no list prev brother");const o=e,r=eF(n,t,o),i=tn(o)+1;let s=tt(),l=1,a=Gn(t);r&&(s=yc(r),l=Qn(r)+1,a=Gn(r));const d=W0(t),p={...n.getBlockData(t),groupId:s,level:i,start:l,..._0(a)};return n.updateBlockData(t,p),n.doc.beginBatchUpdate(),Z_(d).forEach(v=>{const B=n.getBlockData(v);n.updateBlockData(v,{...B,level:B.level+1})}),n.doc.endBatchUpdate(),!0}function nF(n,t,e){return t.length===0||!t.every(o=>Nt(o.block))?!1:e==="increase"?z4(n,t[0].block):H4(n,t[0].block)}function W4(n,t,e){if(!nF(n,t,e))return!1;const o=t[0].block,r=tn(o),i=t.filter(d=>tn(d.block)<=r),s=T4(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 Ks(n,a[0])),i.forEach(h=>{e==="increase"?V4(n,h.block):q0(n,h.block)}),d==null||d.fix()}),!0}function oF(n,t){return V4(n,t)}function rF(n,t){return q0(n,t)}function iF(n){const t=n.selection.range.getSelectedBlocks();if(t.length>1)return W4(n,t,"increase"),!0;const e=t[0].block;if(!Nt(e))return!1;const o=new Gf(n,e);return oF(n,e)&&(o.fix(),new Ks(n,e).fix()),!0}function sF(n){const t=n.selection.range.getSelectedBlocks();if(t.length>1)return W4(n,t,"decrease"),!0;const e=t[0].block;return Nt(e)?(rF(n,e),!0):!1}class lF{constructor(t){this.editor=t}handleBeforeKeyDown(t,e){const o=t.selection.range.getSelectedBlocks();if(o.length===0||!o.some(i=>Nt(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||!Nt(e.block)||or(t,"Shift+Enter")?!1:this.editor.undoManager.runInGroup(()=>tF(this.editor))}handleBackspace(){return this.editor.undoManager.runInGroup(()=>Q_(this.editor))}handleTab(t){return or(t,"Shift+Tab")?this.editor.undoManager.runInGroup(()=>sF(this.editor)):this.editor.undoManager.runInGroup(()=>iF(this.editor))}}class cF{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;Nt(i)&&e.add(i)});const o=new Map;Array.from(e.values()).forEach(r=>{var a;const i=Iu(r),{start:s}=Gi(i);o.set(it(i),s);const l=(a=a_(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||j0(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 aF=M("customize-list-start-menu");class uF{constructor(t){m(this,"popup");m(this,"block",null);m(this,"show",(t,e)=>{const o=e.querySelector("div.list-container");g(aF,o,"list-block mark does not exist"),this.block=e,this.popup.manualShow(o,{theme:"light"})});m(this,"createDialogContent",()=>{const t=k("div",["customize-start-panel"],null);k("span",["customize-start-panel-title"],t,L.t("list.numberLabel"));const e=this.createNumericInput();t.appendChild(e);const o=k("button",["customize-start-panel-button"],t,L.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=Qn(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(()=>{Bc(this.editor,[o,...kc(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 hu(this.createDialogContent()),this.popup.on("show",this.handleDialogShow)}destroy(){this.popup.destroy()}createNumericInput(){const t=k("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 dF(n,t){return yc(n)===yc(t)}function hF(n,t){const e=x4(t);return e?dF(e,t)?Qn(e)!==Qn(t)-1:!0:!1}function fF(n,t){return Qi(t)?!0:Qn(t)!==1}function mF(n,t){return De(t),[{id:"continue-numbering",name:L.t("list.continueList"),states:hF(n,t)?[]:["disabled"]},{id:"start-new-list",name:L.t("list.restartList"),states:fF(n,t)?[]:["disabled"]},{id:"set-numbering-value",name:L.t("list.changeNumber")}]}function gF(n,t,e){var o,r;if(De(t),e.id==="continue-numbering"){const i=x4(t);i&&Bc(n,[t,...kc(t)],Qn(i)+1,{resetGroupId:!0,groupId:yc(i)})}if(e.id==="start-new-list"&&n.undoManager.runInGroup(()=>{Bc(n,[t,...kc(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 uF(n)).show(n,t)}}class pF{constructor(t){m(this,"menu");m(this,"handleClick",(t,e)=>{const o=ql(e,"div.list-container");if(o&&this.editor.isWritable()){const r=nt(o);g(Be,r,"no parent block"),De(r);const i=t.getBlockData(r);if(i&&i.checkbox){t.updateBlockData(r,{...i,checkbox:i.checkbox==="checked"?"unchecked":"checked"});return}if(Gn(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=nt(o);i&&gF(this.editor,i,e)}});this.editor=t,this.editor.addListener("click",this.handleClick),this.menu=new Gs([]),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 mF(this.editor,t)}activeList(t,e){const o=nt(t);!o||(e?(V(t,"active"),V(o,"active")):(rt(t,"active"),rt(o,"active")))}}class CF{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(!Nt(r)||!P0(r))return!1;if(e.key==="ArrowUp"||e.key==="ArrowLeft"){const i=Ts(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")&&L4(t,r),!0}}function bF(n,t,e,o,r){T1(n,"list-block-init",()=>{setTimeout(()=>{n.input.addHandler(new CF(n)),n.input.addHandler(new lF(n)),n.addCustom("list-clear-selection-handler",()=>new cF(n)),n.addCustom("list-marker-menu",()=>new pF(n))})});const i=Sn.createBlockContent(n,t,e,o,r),s=r,{level:l,start:a,groupId:d}=s,h=Ec(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=G_(s);return o.insertBefore(p,i),s.viewAsMindmap?setTimeout(()=>{const C=n.getBlockById(r.id);C&&Vf(n,C,{},{mindmapTools:Wf,saveData:!1})}):setTimeout(()=>{const C=n.getBlockById(r.id);C&&M4(n,C)}),i}const AF={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"}},vF={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"}},yF={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"}};L.mergeLang({"zh-CN":AF,"en-US":vF,"ja-JP":yF});const $ot="",q4={...Sn,blockType:"list",createBlockContent:bF,convertFrom:z_,convertTo:W_,handleDrop:L_,notify:S_},G0=M("paragraph");class kF{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":[L.t("commands.unordered"),so("CtrlOrCmd+Shift+L"),$2],"ordered-list":[L.t("commands.ordered"),so("CtrlOrCmd+Shift+U"),N2],"check-list":[L.t("commands.check"),void 0,H2],link:[L.t("commands.link"),so("CtrlOrCmd+K"),e0],quoted:[L.t("commands.quote"),void 0,j2]};if(et(t,e)){const i=it(e),s=St(e),l=Do(t,e),a=t.getBlockData(e);Object.entries(r).forEach(([d,[h,p,C]])=>{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:C,groupIndex:600})})}return o}convertLink(t,e,o){g(G0,Wr(e.start),""),g(G0,Wr(e.start),"");const r="bottom-start",i=e.start.offset,s=e.end.offset,l=(v,B)=>{t.undoManager.runInGroup(()=>{try{const x=t.selection.range.isCollapsed();let I;if(x){I=Gr(t.getBlockText(o),s,v,{link:B}),t.setBlockText(o,I);return}I=Mh(t.getBlockText(o),i,s,v),I=Ua(i,v.length,I,"link",B),t.setBlockText(o,I),t.selection.selectBlock(o,i+v.length),t.focus()}catch(x){G0.error(x)}})},a=()=>{t.selection.selectBlock(o,s),t.focus()},d=Ur(t,o,e)[0];if(!d)return;const h=qr(t,o,"link-button-anchor",d),p=t.getBlockText(o),C=za(p,i);Eu(t,{target:h,linkText:t.getSelectedText(),linkUrl:(C==null?void 0:C.link)||"",onFinished:l,onClose:a,placement:r})}convertToList(t,e,o){const r=Ch(t,e,"list",{offset:0,data:{listType:o}});r&&t.undoManager.runInGroup(()=>{const i=vt(e),s=ot(e);t.insertBlock(at(s),i,r.blockData),t.deleteBlock(e)})}executeCommand(t,e,o,r){var a;if(!et(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?xc(t,e):this.convertToList(t,e,"unordered"),l=!0),i==="ordered-list"&&(s?xc(t,e):this.convertToList(t,e,"ordered"),l=!0),i==="check-list"&&(s?xc(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}),l=!0}if(i==="link"){const d=$f(t);d==null||d.disableTextToolbar(),d==null||d.hide(),setTimeout(()=>{d==null||d.enableTextToolbar()},1e3),this.convertLink(t,o,e),l=!0}return l}}const wF={left:dc,right:Bf,center:Ef};class BF{constructor(t){m(this,"id","BlockAlignProvider");this.editor=t}applyAlignStyle(t,e,o){Object.keys(wF).includes(o)?t.updateBlockData(e,{align:o}):t.updateBlockData(e,{align:null})}isChecked(t,e){return t.align===e}getAvailableCommands(t,e,o){if(et(t,e)){const r=it(e),i=St(e),s=Do(t,e),l=t.getBlockData(e),a=d=>{var p;const h=k("span",["toolbar-item-name-container"],null);for(const C of d.children)if((p=C.states)!=null&&p.includes("checked"))return h.innerHTML=C.icon||dc,h;return h.innerHTML=dc,h};return[{id:"align",name:L.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:L.t("commands.alignLeft"),icon:dc,states:this.isChecked(l,"left")?["checked"]:[]},{id:"align-center",name:L.t("commands.alignCenter"),icon:Ef,states:this.isChecked(l,"center")?["checked"]:[]},{id:"align-right",name:L.t("commands.alignRight"),icon:Bf,states:this.isChecked(l,"right")?["checked"]:[]}],childrenType:"menu"}]}return[]}executeCommand(t,e,o,r){if(!et(t,e))return!1;if(r.id.startsWith("align")){const i=r.id.replace(/^align-/,"");return this.applyAlignStyle(t,e,i),!0}return!1}}function EF(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 Wa(n,o,e.start.offset).charType==="box"}const xF=M("toolbar-handler"),IF={id:"",name:"",type:"separator"};class Ic{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)=>{const o=this.editor.getCustom("editor-tooltip");o.lastClickButtonId=e.id,this.toolbarType==="text"?(this.editor.editorCommandProviders.executeCommand(this.editor.selection.range,e,{}),this.showTextToolbar("click")):this.hoveringBlock&&t_(this.editor,this.hoveringBlock,this.hoveringTextChild,e)});m(this,"handleClose",()=>{d0(this.editor)&&this.editor.focus()});m(this,"handleClosing",(t,e)=>{if(this.toolbarType==="object"){const o=$v(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",Fe.default(t=>{var o;if(g(xF,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&&Xt(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 fu([],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),Ae.get(t).addListener("childChange",this.handleHoveringBlockChildChange),Ae.get(t).addFilter(this),t.editorCommandProviders.registerCommandProvider(new n_(t)),t.editorCommandProviders.registerCommandProvider(new kF(t)),t.editorCommandProviders.registerCommandProvider(new BF(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),Ae.get(this.editor).removeListener("childChange",this.handleHoveringBlockChildChange)}isInBlock(t,e){return t!==this.hoveringBlock?!1:!!(e.target&&e.target instanceof Node&&this.toolbar.popper&&Xt(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 x,I;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&&Se(r.block)){t==="click"&&this.showObjectToolbar(null);return}if(EF(this.editor))return;if(Ms(r.block)){this.toolbar.close("selectionChange");return}const i=this.editor.editorCommandProviders.getCommands(this.editor.selection.range),s=new Map;i.forEach(_=>{const D=_.groupIndex,H=s.get(D);H?H.push(_):s.set(D,[_])});const l=[[]],a=Array.from(s.entries()).sort((_,D)=>_[0]-D[0]);for(let _=0;_<a.length;_++){const[,D]=a[_];if(D.length===0)continue;let H=l[l.length-1];H.length>0&&H[H.length-1].groupIndex!==D[D.length-1].groupIndex&&(H=[],l.push(H)),H.push(...Nf(D))}if(l.length===0){this.toolbar.close("selectionChange");return}this.toolbarType="text";const d=[];if(l.forEach((_,D)=>{const H=_.sort((W,G)=>{var K,ht;return((K=W.order)!=null?K:0)-((ht=G.order)!=null?ht:0)});d.push(...H),D!==l.length-1&&d.push(IF)}),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,C=p?h:r,v=qO(this.editor,C),B=qr(this.editor,C.block,"editor-quick-menu",v);this.toolbar.manualShow(B,{placement:p?"bottom":"top",offset:[0,p?5:10]}),(I=(x=this.toolbar.tippyInstance)==null?void 0:x.popperInstance)==null||I.update()}showObjectToolbar(t){var l,a,d;if(!this.hoveringBlock||this.mouseDown)return;const e=this.hoveringBlock,o=this.hoveringTextChild,{commands:r,element:i}=JO(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 h;const p=i.getClientRects(),C=[];if(Array.from(p).forEach(v=>{const{y:B}=v;C.includes(B)||C.push(B)}),C.length>1){if(h=o?p[p.length-1]:p[0],t)for(let v=0;v<p.length;v++){const B=p[v],x=new DOMRect(B.x-4,B.y-4,B.width+8,B.height+8);if(x.x<t.clientX&&t.clientX<x.right&&x.y<t.clientY&&t.clientY<x.bottom){h=B;break}}}else{if(h=i.getBoundingClientRect(),o){const v=o.getBoundingClientRect();return new DOMRect(v.x,v.y,v.width,v.height)}return new DOMRect(p[0].x,p[0].y,p[0].width,p[0].height)}if(t){const v=h.y,B=t.clientX;return new DOMRect(B,v,10,h.height)}return h};this.toolbar.updateItems(r),this.toolbar.isVisible||(this.toolbar.manualShow(i,{placement:o?"bottom":"top",getReferenceClientRect:s}),(d=this.toolbar.tippyInstance)!=null&&d.popper&&(this.toolbar.tippyInstance.popper.style.paddingTop="10px",this.toolbar.tippyInstance.popper.style.paddingBottom="5px"))}static register(t){return t.addCustom("toolbar-handler",e=>new Ic(e))}static get(t){return t.getCustom("toolbar-handler")}}function Yf(n,t,e){n.getBlockData(t).heading===e?n.updateBlockData(t,{heading:null}):n.updateBlockData(t,{heading:e})}function G4(n,t,e){["left","center","right"].includes(e)?n.updateBlockData(t,{align:e}):n.updateBlockData(t,{align:null})}function Q0(n,t){const o=n.getBlockData(t).quoted;n.updateBlockData(t,{quoted:o?void 0:!0})}function Z0(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 Y0(n,t,e){if(!n.selection.range.focus.isSimple())return;const r=n.getBlockData(t);let i;switch(e){case"unordered-list":i=Z0(r,"unordered-list")?void 0:"unordered";break;case"ordered-list":i=Z0(r,"ordered-list")?void 0:"ordered";break;case"check-list":i=Z0(r,"check-list")?void 0:"unchecked";break}if(i){const s=Ch(n,t,"list",{offset:0,data:{listType:i}});s&&n.undoManager.runInGroup(()=>{const l=vt(t),a=ot(t);n.deleteBlock(t);const d=n.insertBlock(at(a),l,s.blockData);s.onConverted&&s.onConverted(n,d)})}else xc(n,t)}const TF=Object.freeze(Object.defineProperty({__proto__:null,applyHeadingStyle:Yf,applyAlignStyle:G4,applyQuoteStyle:Q0,applyList:Y0},Symbol.toStringTag,{value:"Module"})),SF=[pf,Cf,bf,Af,vf,yf,kf,wf],DF={Unordered:r0,Ordered:i0,Checkbox:n0,Quote:o0};function Q4(n,t){const e=n;e.blockOptions=t,e.itemType="insert-block",n.children&&n.children.forEach(o=>Q4(o,t))}function MF(){return{name:"basic",insertBlockCommandItems:[{id:"text",icon:hc,name:L.t("commands.text"),order:0,group:"basics",value:"text"}]}}function J0(n=1){var r;const t={name:"basic",insertBlockCommandItems:[]};let e=Hf();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:SF[o-1],name:L.t("quickMenu.basic.heading.title",{heading:String(o)}),order:o,group:"basics",value:String(o),subText:An(i)}),o++}return t}function LF(){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:L.t(`quickMenu.basic.${e.toLocaleLowerCase()}`),icon:DF[e],value:e.toLocaleLowerCase(),group:"basics",order:10+o,subText:An(r)})}),n}class Z4{constructor(t){this.withPlainText=t}getCommands(){const t=MF(),e=J0(),o=LF();return[...this.withPlainText?t.insertBlockCommandItems||[]:[],...e.insertBlockCommandItems||[],...o.insertBlockCommandItems||[]]}updateBlock(t,e,o,r){const{value:i,id:s}=r;return s.startsWith("heading-")?Yf(t,o,Number.parseInt(i!=null?i:"1",10)||1):i==="ordered"||i==="unordered"||i==="checkbox"?Y0(t,o,{ordered:"ordered-list",unordered:"unordered-list",checkbox:"check-list"}[i]):i==="quote"&&Q0(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 Y4={basics:100,system:200,common:300,thirdParty:400};class K0{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 RF=M("mathjax-converter"),OF="MathJax-script";async function _F(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 ys(e,OF)}function FF(){try{window.MathJax&&window.MathJax.texReset()}catch{}}async function J4(n,t){const e="mathjax2Svg";try{await Io.lock(e),FF(),await _F(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 RF.error(o),o}finally{Io.release(e)}}async function K4(n,t){const e=await J4(n,t);return e?await ip(e,"image/svg+xml"):""}async function X0(n,t){const o=await J4(n,t),r=new File([o],"math.svg");return(await n.doc.uploadResource(r)).resourceId}const X4=M("edit-mathjax");class PF{constructor(){m(this,"editMathjaxPopup",null);m(this,"onChange",null);m(this,"tex","");m(this,"observer",null);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",Fe.default(t=>{var e;(e=this.onChange)==null||e.call(this,t,!1)},300))}editMathjax(t,e,o){if(!this.editMathjaxPopup)this.editMathjaxPopup=new hu(this.createPopupContent(e));else{const r=this.getTextarea();r.value=e}this.tex=e,this.editMathjaxPopup.manualShow(t,{theme:"light"}),this.editMathjaxPopup.removeAllListeners("close"),this.editMathjaxPopup.addListener("close",this.handleClose),this.onChange=o}createPopupContent(t){const e=k("textarea",["mathjax-editor-textarea"],null);return e.value=t,e.addEventListener("keyup",this.handleKeyup),this.textareaWatcher(e),e}textareaWatcher(t){const e=t;e.onblur=()=>{var r;(r=this.editMathjaxPopup)!=null&&r.isVisible&&t.focus()};const o=()=>{setTimeout(()=>{t.focus()})};this.observer=new IntersectionObserver(o,{}),this.observer.observe(t)}getTextarea(){g(X4,this.editMathjaxPopup,"no exists mathjax editor popup");const t=this.editMathjaxPopup.content.querySelector("textarea");return g(X4,t,"no textarea"),t}destroy(){var t,e;this.onChange=null,(t=this.observer)==null||t.disconnect(),(e=this.editMathjaxPopup)==null||e.removeAllListeners()}}function t6(n,t,e,o){n.addCustom("mathjax-editor",()=>new PF).editMathjax(t,e.trim(),o)}function e6(){return{insert:" ",attributes:{id:tt(),box:!0,type:"math",tex:" ",src:"",created:Date.now()}}}function Jf(n,t){const e=n.getBoxData(t),o=nt(t);if(!o)return;const r=_s(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 Io.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 K0).setError(a),n.updateBoxData({...e,tex:s,src:""})}finally{Io.release("convertAndUploadMathjax"),l&&n.focus()}};t6(n,t,e.tex,i)}const n6=M("mathjax-box");function tC(n,t){n.selection.updateSelection(null);const e=t.target;!e||!(e instanceof HTMLElement)||n.domEvents.removeEventListener(e,null,tC)}async function NF(n,t,e){try{if(!t.tex.trim())return;const o=await K4(n,t.tex),r=n.findBoxById(t.id);if(!r)return;const i=gp(r);i.innerHTML="";const s=k("img",["mathjax"],i);s.src=o,e.setDataUrl(o),n.domEvents.addEventListener(s,"load",tC)}catch(o){e.setError(o);const r=n.findBoxById(t.id);if(!r)return;const i=r.querySelector(".mathjax-tex-text");V(i,"mathjax-error"),i.innerText=o.message,n.selection.updateSelection(null)}}function $F(n,t,e,o){const r=o,i=n.addCustom(`mathjax-box-${r.id}`,()=>new K0);if(r.src||i.dataUrl){const a=k("img",["mathjax"],e);a.src=n.doc.buildResourceUrl(r.src||i.dataUrl),n.domEvents.addEventListener(a,"load",tC);return}const s=["mathjax-tex-text"];let l=r.tex;l.trim()?i.error&&(l=i.error.message,s.push("mathjax-error")):l=L.t("mathjax.emptyText"),k("span",s,e,l),NF(n,r,i)}function HF(n,t){const e={id:tt(),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=>{n6.error(`failed to convert and upload mathjax: ${JSON.stringify(o)}`)}),e}function jF(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 UF(n,t,e){const o=nt(t);g(n6,o,"failed to get block"),!(n.readonly||!n.isBlockWritable(o))&&Jf(n,t)}function zF(){return{abstract:L.t("mathjax.abstract")}}const o6={boxType:"math",updateBoxContent:$F,convertFrom:HF,convertTo:jF,handleClickBox:UF,getBoxProperties:zF};async function VF(n,t,e){try{const o=t.embedData,r=await K4(n,o.mathjaxText),i=n.findBlockById(t.id);if(!i)return;const s=Mt(i);s.innerHTML="";const l=k("img",["mathjax"],s);l.src=r,e.setDataUrl(r)}catch(o){e.setError(o)}}function WF(n,t){if(n.readonly||!t.target||!(t.target instanceof Node))return;const e=nt(t.target);if(!e||!Se(e)||mn(e)!=="math")return;const o=Mt(e),r=o.querySelector("img")||o.querySelector("span.mathjax-tex-text");if(!r||!Xt(r,t.target))return;const s=n.getBlockData(e).embedData;t6(n,r,s.mathjaxText,async l=>{const a=await X0(n,l),d={mathjaxText:l,src:a};n.updateEmbedData(e,d)})}function qF(n,t,e){const o=e.embedData,r=n.addCustom(`mathjax-block-${e.id}`,()=>new K0);if(n.domEvents.addEventListener(t,"click",WF),!o.mathjaxText.trim()){k("span",["mathjax-tex-text"],t,L.t("mathjax.emptyText"));return}if(o.src||r.dataUrl){const i=k("img",["mathjax"],t);i.src=n.doc.buildResourceUrl(o.src||r.dataUrl);return}r.error,k("span",["mathjax-tex-text"],t,o.mathjaxText),VF(n,e,r)}function GF(n,t,e){if(!et(n,t))return null;const o=n.getBlockString(t).trim();if(!o||!o.startsWith("$$")||!o.endsWith("$$"))return null;const r=tp(o,"$");if(!r)return null;const i={mathjaxText:r,src:""};return{blockData:{id:tt(),type:"embed",embedType:"math",embedData:i}}}function QF(n){return{name:"Mathjax"}}function ZF(n,t){var o;const e=Mt(t);n.domEvents.removeAllListeners(e),n.findCustom("mathjax-editor")&&((o=n.getCustom("mathjax-editor").editMathjaxPopup)==null||o.close("cancelBar"))}function YF(n,t,e,o){const r=t.embedData;return o==="html"?`<img src="${n.doc.buildResourceUrl(r.src,{withToken:!0})}" />`:o==="markdown"?`
|
|
599
599
|
$$${r.mathjaxText}$$
|
|
600
|
-
`:r.mathjaxText}function JF(){return{abstract:L.t("mathjax.abstract")}}const KF={embedType:"math",createEmbedContent:qF,getOptions:QF,convertFrom:GF,handleDeleteBlock:ZF,convertTo:YF,getBlockProperties:JF},Hot="",XF={mathjax:{emptyText:"\u7A7A\u7684\u516C\u5F0F",abstract:"\u516C\u5F0F"}},tP={mathjax:{emptyText:"Empty formula",abstract:"Formula"}},eP={mathjax:{emptyText:"\u6570\u5F0F\u306A\u3057",abstract:"\u6570\u5F0F"}};L.mergeLang({"zh-CN":XF,"en-US":tP,"ja-JP":eP});function nP(n,t,e,o){const r=n.getBlockByIndex(t,e),i=n.getBlockText(r),{left:s}=Tn(i,o);if(!se(s).endsWith("$$$$"))return!1;const a=o-4,d=o,h={id:tt(),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);Jf(n,p)})}),!0}class oP{handleAfterInsertText(t,e,o,r,i){return!!(i===" "&&nP(t,e,o,r))}}const Tc=M("inline-box-items");function rP(n,t,e){return n.undoManager.runInGroup(()=>{var s;let o=n.getBlockByIndex(t,e);ue(n,o)||(o=n.insertTextBlock([],t,e));const r=e6();n.setBlockText(o,[r]);const i=(s=r.attributes)==null?void 0:s.id;return g(Tc,i,"mathjax box id is empty"),setTimeout(()=>{const l=n.getBoxById(i);Jf(n,l)},100),o})}function iP(n,t,e){let o=n.getBlockByIndex(t,e),r="bottom-start";return ue(n,o)||(r="top-start"),Eu(n,{target:o,linkText:"",linkUrl:"",onFinished:(l,a)=>{n.undoManager.runInGroup(()=>{try{ue(n,o)||(o=n.insertTextBlock([],t,e));const d=ho(l,{link:a}),h=ho(" ",null),p=[d,h];n.insertTextToBlock(o,0,p),n.selection.selectBlock(o,sn(p)),n.focus()}catch(d){Tc.error(d)}})},onClose:()=>{n.focus()},placement:r}),o}function sP(n,t,e){return n.undoManager.runInGroup(()=>{var l;const o=n.getBlockByIndex(t,e),r=n.selection.range;g(Tc,Wr(r.start),"invalid block position");const i=e6();n.insertBoxToBlock(o,r.start.offset,i.attributes);const s=(l=i.attributes)==null?void 0:l.id;return g(Tc,s,"mathjax box id is empty"),setTimeout(()=>{const a=n.getBoxById(s);Jf(n,a)},100),o})}function lP(n,t,e){const o=n.getBlockByIndex(t,e),r=n.selection.range;g(Tc,Wr(r.start),"invalid block position");const i=Ur(n,o,r);if(i.length===0)return;const s=i[0],l=qr(n,o,"quick-menu-inline-link",s);Eu(n,{target:l,linkText:"",linkUrl:"",onFinished:(h,p)=>{n.undoManager.runInGroup(()=>{try{const C=n.getBlockText(o),v=Gr(C,r.start.offset,h,{link:p});n.setBlockText(o,v),n.selection.selectBlock(o,r.start.offset+h.length),n.focus()}catch(C){Tc.error(C)}})},onClose:()=>{n.focus()},placement:"bottom-start"})}class r6{getCommands(){return[{id:"insert-math",name:L.t("quickMenu.inlineBox.math"),icon:G2,order:900,group:"common",subText:An("insert-math")},{id:"insert-link",name:L.t("quickMenu.inlineBox.link"),icon:e0,order:400,group:"common",subText:An("insert-link")}]}async handleUpdateBlockCore(t,e){switch(e.item.id){case"insert-math":return sP(t,e.containerId,e.blockIndex);case"insert-link":return lP(t,e.containerId,e.blockIndex);default:return null}}async handleInsertEmptyBlockCore(t,e){switch(e.item.id){case"insert-math":return rP(t,e.containerId,e.blockIndex);case"insert-link":return iP(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 cP(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 Z4(e),new r6].forEach(l=>{const a=l.getCommands(n);r.push(...a.map(d=>({...d,itemType:"insert-block",commandProvider:l})))}),r}function aP(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=>{Q4(i,r)}),e.push(...r.insertBlockCommandItems))}),e.push(...cP(n,t)),e}function eC(n,t={withPlainText:!1}){const e=aP(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||Y4[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=L.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 uP(n,t,e){const o=n.getFocusedBlock();if(!o)return;const r=n.getParentContainer(o),i=at(r);let l=n.getBlockIndex(o);if(ue(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 i6=M("quick-menu"),dP={id:"quick-menu",trigger:["/"]},hP=5;class Kf{constructor(t,e=dP){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||RR(s).toLocaleLowerCase().indexOf(r)!==-1)return o.add(s.group),!0;const l=`blockMenu.section.${s.group||"common"}`,a=L.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(!co(i)){const s=nt(ot(i));if(s&&St(s)==="code")return!1}return!0});m(this,"onClickItem",(t,e)=>{const o=e;o.itemType==="insert-block"&&(g(i6,o.blockOptions||o.commandProvider,"invalid quick item, no block options or command provider"),g(i6,this.suggest.anchor,"invalid suggest, no anchor"),this.options.id==="empty-block-menu"&&this.editor.focus(),uP(this.editor,o,this.suggest.anchor))});this.editor=t,this.options=e,this.items=[],this.maxHeading=Hf(),this.suggest=new f0(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=eC(this.editor);this.items=t}refreshMenuItems(){let t=null,e=0;const o=Hf();if(o!==this.maxHeading){const r=new Z4,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>hP&&(this.suggest.close(),this.firstEmptyOffset=-1)}}}class Xf{constructor(t){m(this,"instance");m(this,"mousedown",!1);m(this,"currentInstance",null);m(this,"attributeName",[]);m(this,"attributeDesc","");m(this,"_lastClickButtonId","");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=k("div",[],null);return k("span",[],i,e),r&&k("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||!Xt(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(this._lastClickButtonId===e.getAttribute("data-button-id"))return this._lastClickButtonId="",!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 l=t.reference.getAttribute("data-editor-tooltip-offset-x"),a=t.reference.getAttribute("data-editor-tooltip-offset-y");i.offset=[l?Number.parseInt(l,10):0,a?Number.parseInt(a,10):0]}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);const s=document.body;if(i.appendTo=this.fixContainerForFullscreen(s),Object.keys(i).length&&t.setProps(i),t.reference.hasAttribute(`data-editor-tooltip-${this.editor.clientId}-dynamic`)){const l=t.reference.getAttribute(`data-editor-tooltip-${this.editor.clientId}-dynamic`);t.setContent(l||"")}}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=jg.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,hideOnClick:!1}),t.domEvents.addEventListener(document,"mousedown",this.handleDocumentMouseDown)}set lastClickButtonId(t){this._lastClickButtonId=t,t&&setTimeout(()=>{this._lastClickButtonId===t&&(this._lastClickButtonId="")},500)}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=Fe.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)}fixContainerForFullscreen(t){return t.closest("body")&&document.fullscreenElement&&!document.fullscreenElement.contains(t)?document.fullscreenElement:t}}const fP={"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",link:"link"};function mP(n,t){const e=new Set(Object.keys(fP)),o=t.filter(i=>e.has(i.id));return Nf(o)}function Tu(n,t){if(!n.isWritable())return!1;const e=n.selection.range,o=n.editorCommandProviders.getCommands(e),i=mP(n,o).find(s=>s.id===`text/${t}`||s.id==="link");return i?(n.editorCommandProviders.executeCommand(e,i,{}),Ic.get(n).update("selectionChange"),!0):!1}function gP(n,t){const e=n.selection.focusedBlock;if(!n.isWritable()||!et(n,e))return!1;const o=n.getBlockData(e).heading,r={id:`heading-${t}`,source:"BlockTurnIntoCommandProvider",value:String(t)};return Number(o)===t&&(r.id="text",r.value=null),n.editorCommandProviders.executeCommand(n.selection.range,r,{}),!0}const nC={"CtrlOrCmd+B":n=>Tu(n,"style-bold"),"CtrlOrCmd+I":n=>Tu(n,"style-italic"),"CtrlOrCmd+U":n=>Tu(n,"style-underline"),"CtrlOrCmd+D":n=>Tu(n,"style-strikethrough"),"CtrlOrCmd+K":n=>Tu(n,"link"),...(()=>{const n={};for(let t=1;t<=8;t++)n[`CtrlOrCmd+${t}`]=e=>gP(e,t);return n})()},pP={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"}},CP={quickMenu:{basic:{heading:{title:"Heading {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:"Heading {name}",headingGroup:"Text style",text:"Text"}},bP={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"}};L.mergeLang({"zh-CN":pP,"en-US":CP,"ja-JP":bP});const Uot="";function Xs(n,...t){const e=mo(...t);return e.classList.remove("editor-button"),e.classList.add("editor-text-button"),n.append(e),e}function s6(n){const t=$f(n);t==null||t.hide();const e=n.findCustom("table-border-bar");e==null||e.closeToolbar()}function AP(n){return k("div",["insert-column-button","drop-marker"],n)}const vP=M("row-height");function l6(n){const t=Tt.fromTable(n),e=n.rows;g(vP,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 yP=M("table-border-bar-dom");function c6(n){var a;const t=nt(n.contentElement);g(yP,t,"no block");const o=te(t).querySelector(".table-border-bar-container.left"),i=Mt(t).offsetLeft-Cc,s=((a=n.scrollOptions.paddingLeft)!=null?a:0)+i,l=Math.min(n.contentElement.offsetLeft-i,n.rootElement.scrollLeft-s);o&&(o.style.left=`${-l}px`)}const Zi=M("table-border-bar-dom");function Sc(n,t){g(Zi,He(t),"invalid table block");const e=$e(t),o=Cr(n,t),r=te(t),i=(p,C,v)=>{const B=k("div",["button-root",C],p),x=k("div",["button-container",C],B);B.setAttribute(`data-${C}-index`,`${v}`),x.setAttribute(`data-editor-tooltip-${n.clientId}`,C==="left"?L.t("table.insertRow"):L.t("table.insertCol")),k("span",["insert-indicator"],x),AP(x)},{selectedRows:s,selectedColumns:l}=g0(n,t),a=()=>{const p=o.querySelector(".table-border-bar-container.top");g(Zi,p,"no top border bar container");const C=k("div",["table-border-bar-container","top"],null),v=k("div",["table-border-bar","top"],C),B=DO(e),I=Tt.fromTable(e).colCount;n.selection.range.isSimple()&&i(v,"top",0);for(let _=0;_<I;_++){const D=_===I-1?B[_]+2:B[_],H=k("span",["table-border-bar-cell","top"],v);l.has(_)&&H.classList.add("selected"),H.setAttribute("data-top-index",`${_}`),H.style.width=`${D}px`,n.selection.range.isSimple()&&i(v,"top",_+1)}Da(p,C)},d=()=>{const p=r.querySelector(".table-border-bar-container.left");g(Zi,p,"no left border bar container");const C=k("div",["table-border-bar-container","left"],null),v=k("div",["table-border-bar","left"],C);k("span",["table-border-bar-cell","corner"],v);const B=l6(e);n.selection.range.isSimple()&&i(v,"left",0),Array.from(e.rows).forEach((x,I,_)=>{const D=k("span",["table-border-bar-cell","left"],v);s.has(I)&&D.classList.add("selected"),D.setAttribute("data-left-index",`${I}`);const H=I===_.length-1?B[I]+2:B[I];D.style.height=`${H}px`,n.selection.range.isSimple()&&i(v,"left",I+1)}),Da(p,C)};a(),d();const h=n.findCustom(pr(t));h&&c6(h)}function a6(n,t){const e=t.target;if(!(e instanceof Element))return;const o=nt(e);g(Zi,o&&He(o),"invalid table block"),Sc(n,o),n.selection.caret.update()}function tm(n,t){const e=t.target;if(!(e instanceof Element))return;const o=nt(e);g(Zi,o&&He(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);b4(n,o,i),Sc(n,o)}else if(r.classList.contains("left")){const i=parseInt(r.getAttribute("data-left-index")||"0",10);A4(n,o,i),Sc(n,o)}}}function em(n,t){var s;s6(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=nt(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),C=Math.min(r,p),v=Math.abs(r-p)+1;Et(l.target,"top")&&o==="top"?VO(n,d,C,v,{reverse:!0}):Et(l.target,"left")&&o==="left"&&WO(n,d,C,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&&Et(t.target,"table-border-bar-cell")&&(e=nt(t.target),Et(t.target,"top")?o="top":Et(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 u6(n){const t=n.selection.range,e=pu(n,t);e&&Sc(n,e)}function kP(n,t){g(Zi,He(t),"invalid table block");const e=Cr(n,t),o=te(t),r=k("div",["table-border-bar-container","top"],e),i=k("div",["table-border-bar-container","left"],o);Sc(n,t),n.domEvents.addEventListener(Mt(t),"scroll",a6),n.domEvents.addEventListener(r,"click",tm),n.domEvents.addEventListener(i,"click",tm),n.domEvents.addEventListener(r,"mousedown",em),n.domEvents.addEventListener(i,"mousedown",em),n.addListener("afterClearSelection",u6)}function d6(n,t){if(!n.isWritable())return;if(Cr(n,t).querySelector(".table-border-bar-container")){Sc(n,t);return}kP(n,t)}function h6(n,t){g(Zi,He(t),"invalid table block");const e=Cr(n,t),o=te(t),r=e.querySelectorAll(".table-border-bar-container"),i=o.querySelectorAll(".table-border-bar-container");r.forEach(s=>{n.domEvents.removeEventListener(s,"click",tm),n.domEvents.removeEventListener(s,"mousedown",em),s.remove()}),i.forEach(s=>{n.domEvents.removeEventListener(s,"click",tm),n.domEvents.removeEventListener(s,"mousedown",em),s.remove()}),n.domEvents.removeEventListener(Mt(t),"scroll",a6),n.addListener("afterClearSelection",u6)}function wP(n,t){g(Zi,He(t),"invalid table block");const o=Cr(n,t).querySelector(".table-border-bar-container.top");return o?o.getBoundingClientRect().height:0}class BP{constructor(t,e){m(this,"toolbar");m(this,"handleSelectionChange",(t,e)=>{!t.isVisible||(e==="delete-columns"?(Vi(this.editor,this.tableBlock,!0,!0),Wi(this.editor,this.tableBlock,!0,!0)):e==="delete-rows"?(Vi(this.editor,this.tableBlock,!0,!1),Wi(this.editor,this.tableBlock,!0,!1)):(Vi(this.editor,this.tableBlock,!1),Wi(this.editor,this.tableBlock,!1)))});m(this,"handleClick",(t,e,o)=>{e.id==="delete-columns"?p0(this.editor.selection.range):e.id==="delete-rows"&&C0(this.editor.selection.range)});m(this,"handleToolbarClose",()=>{this.tableBlock&&pu(this.editor,this.editor.selection.range)===this.tableBlock&&(Vi(this.editor,this.tableBlock,!1),Wi(this.editor,this.tableBlock,!1))});this.editor=t,this.tableBlock=e;const o=t.options.componentsOptions.popover;this.toolbar=new fu([],void 0,{id:"table-row-column-toolbar",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,s;const{selectedColumns:t,selectedRows:e}=g0(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=Ur(this.editor,this.tableBlock,this.editor.selection.range)[0];if(!o){this.toolbar.close("cancelBar");return}if(t.size>0){const l={id:"delete-columns",name:L.t("table.deleteSelectCol"),icon:O2};this.toolbar.updateItems([l]);const a=qr(this.editor,this.tableBlock,"table-row-column-delete",o);this.toolbar.manualShow(a,{placement:"top",offset:[0,5]})}else{const l={id:"delete-rows",name:L.t("table.deleteSelectRow"),icon:R2};this.toolbar.updateItems([l]);const h=te(this.tableBlock).querySelector(".table-border-bar-container.left").getBoundingClientRect(),p=new DOMRect(Math.max(h.left,o.left-Cc),o.top,Cc,o.height),C=qr(this.editor,this.tableBlock,"table-row-column-delete",p);this.toolbar.manualShow(C,{placement:"left",offset:[0,5]});const v=this.editor.options.componentsOptions.popover;(r=this.toolbar.tippyInstance)==null||r.setProps({popperOptions:{modifiers:[{name:"flip",options:{boundary:v==null?void 0:v.overflowBoundary,fallbackPlacements:["left","right"]}}]}})}(s=(i=this.toolbar.tippyInstance)==null?void 0:i.popperInstance)==null||s.update()}destroy(){this.toolbar.destroy(),this.toolbar.removeAllListeners()}}const oC=M("table-border-bar");class EP{constructor(t,e){m(this,"toolbar");m(this,"resizeObserver",null);m(this,"handleReadonlyChanged",t=>{t.isWritable()?this.update():h6(this.editor,this.tableBlock)});m(this,"handleBlockUpdated",()=>{var t;(t=this.resizeObserver)==null||t.disconnect(),setTimeout(()=>{var o;const e=this.editor.getBlockById(it(this.tableBlock));(o=this.resizeObserver)==null||o.observe($e(e))})});m(this,"handleScroll",()=>{var t;(t=this.toolbar)==null||t.update()});m(this,"handleTableResize",()=>{!this.editor.isWritable()||this.update()});this.editor=t,this.tableBlock=e,g(oC,this.tableBlock,"no table block"),oC.debug("create table border bar"),d6(this.editor,this.tableBlock),this.resizeObserver=new bs(this.handleTableResize),this.resizeObserver.observe($e(this.tableBlock));const o=t.getComponentOptions("table");o!=null&&o.hideToolbar||(this.toolbar=new BP(this.editor,this.tableBlock)),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}close(){var t;(t=this.toolbar)==null||t.close()}destroy(){var t,e;oC.debug("destroy table border bar"),(t=this.resizeObserver)==null||t.disconnect(),this.resizeObserver=null,h6(this.editor,this.tableBlock),(e=this.toolbar)==null||e.destroy(),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged)}update(){var t;d6(this.editor,this.tableBlock),(t=this.toolbar)==null||t.update()}}const xP=M("table-border-bar");class IP{constructor(t){m(this,"activeTableBar",null);m(this,"handleBlockDeleted",(t,e)=>{!this.activeTableBar||(e===this.activeTableBar.tableBlock||Xt(e,this.activeTableBar.tableBlock))&&(this.activeTableBar.destroy(),this.activeTableBar=null)});m(this,"handleSelectionChanged",t=>{setTimeout(()=>{var r;const e=t.selection.range,o=pu(t,e);((r=this.activeTableBar)==null?void 0:r.tableBlock)!==o&&this.activeTableBar&&this.hide(),o&&this.show(o)})});m(this,"handleScroll",()=>{var t;(t=this.activeTableBar)==null||t.handleScroll()});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 EP(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(xP,this.activeTableBar,"no active table bar"),this.activeTableBar.destroy(),this.activeTableBar=null)}}function f6(n,t){const e=n.addCustom("table-border-bar",o=>new IP(o));t==="update"&&e.update()}const Ln=M("table-cell-menu"),TP="style-bg-color-";class SP{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=pu(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 Ro?t.getBlockById(i.blockId)===this.activeTableBlock?s=r.getCellByContainerId(i.childContainerId):s=this.getCellByChildBlockId(r,i.blockId):i.blockId!==this.activeTableBlock.id&&(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=k("div",["cell-background-color-item"],null);k("span",[],t,L.t("table.cellBackground"));const e=this.getSelectedBkgColorIndex();k("button",["item-button"],t).setAttribute("data-color-index",`${e}`);const r=k("span",["item-sub-indicator"],t);return r.innerHTML=Y1,t});m(this,"handleCommand",t=>{var r;g(Ln,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":C0(Xw(this.editor,this.activeTableBlock,!1));break;case"delete-select-col":p0(Xw(this.editor,this.activeTableBlock,!0));break;case"merge-cell":Yw(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":tO(this.editor,this.activeTableBlock,o==="show-border");break;case"show-chart":oO(this.editor,this.activeTableBlock,o==="show-chart"),B0(this.editor,this.activeTableBlock,{updateNow:!0});break}});m(this,"handleToolbarClose",()=>{this.targetButton&&rt(this.targetButton,"active"),this.activeTableBlock&&pu(this.editor,this.editor.selection.range)===this.activeTableBlock&&(Vi(this.editor,this.activeTableBlock,!1),Wi(this.editor,this.activeTableBlock,!1)),this.editor.focus()});m(this,"handleSelectionChange",(t,e)=>{!t.isVisible||(g(Ln,this.activeTableBlock,"no target table block"),e==="cell-background-color"&&this.handleBeforePopupPalette(),e==="delete-select-row"?(Vi(this.editor,this.activeTableBlock,!0,!1),Wi(this.editor,this.activeTableBlock,!0,!1)):e==="delete-select-col"?(Vi(this.editor,this.activeTableBlock,!0,!0),Wi(this.editor,this.activeTableBlock,!0,!0)):(Vi(this.editor,this.activeTableBlock,!1),Wi(this.editor,this.activeTableBlock,!1)))});m(this,"handleClick",(t,e)=>{var o;g(Ln,this.activeTableBlock,"no target table block"),g(Ln,this.targetButton,"no target button"),s6(this.editor),Et(this.targetButton,"active")?(rt(this.targetButton,"active"),(o=this.manualMenu)==null||o.close("clickItem")):(V(this.targetButton,"active"),this.manualMenu?this.manualMenu.updateItems(this.createCommandMenu()):(this.manualMenu=new Gs(this.createCommandMenu(),void 0,{id:"table-cell-menu"}),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&&(rt(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(Ln,r,"no parent cell");const i=nt(r);if(g(Ln,i,"no parent block"),$e(i)===t.table)return t.getCellByCellElement(r);o=i}return g(Ln,!1,"filed to get cell by child block id"),null}createTargetButton(t){this.targetButton?t.querySelector(`:scope > .${k0}`)||t.appendChild(this.targetButton):(this.targetButton=k("button",[k0],t),this.targetButton.innerHTML=gf,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(Ln,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);A0(this.editor,this.activeTableBlock,{col:o,row:r})}else v0(this.editor.selection.range)}}getSelectedBkgColorIndex(){var s;g(Ln,this.activeTableBlock,"no target table block");const t=this.editor.selection.range,e=zi(this.editor,this.activeTableBlock,t.focus),o=this.editor.getBlockData(this.activeTableBlock),r=e.childContainerId,i=o[`${r}_background`];return i?Number.parseInt((s=i.substring(TP.length))!=null?s:"0",10):-1}createCommandMenu(){g(Ln,this.activeTableBlock,"no target table block");const t=this.editor.getBlockData(this.activeTableBlock),e=Zw(this.editor,this.activeTableBlock,this.editor.selection.range);let o=this.editor.selection.range;if(o.isSimple()){const h=zi(this.editor,this.activeTableBlock,o.start);o=We(this.editor,{anchor:h,focus:h})}const r=Qw(this.editor,this.activeTableBlock,o),i=t.hasRowTitle,s=t.hasColTitle,l=t.isStripeStyle,a=t.noBorder,d=t.chart;return this.colorPaletteItem=new Uw("cell-background-color",{color:!1}),this.colorPaletteItem.palette.on("onClick",(h,p)=>{var C;switch(g(Ln,this.activeTableBlock,"no target table block"),h){case"clearColor":n4(this.editor,this.activeTableBlock,-1);break;case"backgroundColor":n4(this.editor,this.activeTableBlock,p);break}(C=this.manualMenu)==null||C.close("clickItem")}),[{id:"cell-background-color",name:L.t("table.cellBackground"),element:this.createBkgColorItem(),children:[this.colorPaletteItem]},{id:"separator",name:"",type:"separator"},{id:"merge-cell",name:L.t("table.mergeCell"),states:e?[]:["disabled"]},{id:"split-cell",name:L.t("table.splitCell"),states:r?[]:["disabled"]},{id:"separator",name:"",type:"separator"},{id:"delete-select-row",name:L.t("table.deleteSelectRow")},{id:"delete-select-col",name:L.t("table.deleteSelectCol")},{id:"separator",name:"",type:"separator"},{id:"table-config",name:L.t("table.tableConfigKey"),children:[{id:"row-title",name:L.t("table.tableConfig.rowTitle"),states:i?["checked"]:[]},{id:"col-title",name:L.t("table.tableConfig.colTitle"),states:s?["checked"]:[]},{id:"stripe-style",name:L.t("table.tableConfig.stripeStyle"),states:l?["checked"]:[]},{id:"hide-border",name:a?L.t("table.tableConfig.showBorder"):L.t("table.tableConfig.hideBorder"),value:a?"show-border":"hide-border"},{id:"show-chart",name:d?L.t("table.tableConfig.hideChart"):L.t("table.tableConfig.showChart"),value:d?"hide-chart":"show-chart"}]}]}handleRowTitle(t){g(Ln,this.activeTableBlock,"no target table block"),t?JR(this.editor,this.activeTableBlock):YR(this.editor,this.activeTableBlock)}handleColTitle(t){g(Ln,this.activeTableBlock,"no target table block"),t?ZR(this.editor,this.activeTableBlock):QR(this.editor,this.activeTableBlock)}handleStripeStyle(t){g(Ln,this.activeTableBlock,"no target table block"),t?XR(this.editor,this.activeTableBlock):KR(this.editor,this.activeTableBlock)}}function m6(n){n.addCustom("table-cell-menu",t=>new SP(t))}const nm=M("table-container");function rC(n){const t=n.closest("td");return g(nm,t,"no parent cell for a table cell container"),t}function g6(n){const t=$e(n);return Array.from(t.querySelectorAll(':scope > tbody > tr > td > [data-type="editor-container"].child'))}function iC(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(nm,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(nm,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(nm,!1,`invalid navigation type: ${e}`)}const DP=12,MP=90,om=23,p6=2;class LP{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=nt(e);if(o&&Xt(this.editor.rootContainer,o)){const r=ti(o);r&&(this.scrollTableBlock=r,document.addEventListener("mousemove",this.handleAutoScroll))}}});m(this,"handleAutoScroll",lI.default(t=>{if(this.scrollTableBlock){const e=this.editor.getCustom(pr(this.scrollTableBlock)),o=e.rootElement,r=e.scrollOptions.parentContainer,i=o.getBoundingClientRect(),s=window.innerHeight-this.getBarFloatWindowBottom(e),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=ti(o);if(r){const i=t.getCustom(pr(r)),s=i.rootElement.getBoundingClientRect(),l=Mo(t,o,e.start);if(s.left>l.left){const a=e.start.offset===0?DP:p6;i.rootElement.scrollLeft-=s.left-l.left+a}else if(l.right>s.right){const a=e.start.offset===0?MP:p6;i.rootElement.scrollLeft+=l.right-s.right+a}}}else{const o=t.getBlockById(e.start.blockId),r=ti(o),i=t.getBlockById(e.end.blockId),s=ti(i);if(r&&r===s){const l=t.getCustom(pr(r)),a=l.rootElement.getBoundingClientRect();let d=null;if(e.isSimple())d=e.isReverse()?Mo(t,o,e.start):Mo(t,i,e.end);else{const h=rC(ir(t,e.start.childContainerId)),p=rC(ir(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=>{Ww(t),this.editor.selection.caret.update()});m(this,"handleReset",t=>{Ww(t),this.editor.selection.caret.update();const e=this.editor.findCustom("table-border-bar");e&&e.handleScroll(),c6(t)});this.editor=t,this.editor.addListener("selectionChanged",this.handleSelectionChanged),document.addEventListener("mousedown",this.handleMouseDown),document.addEventListener("mouseup",this.handleMouseUp)}getBarFloatWindowBottom(t){return t.scrollOptions.barFloatWindowBottom?typeof t.scrollOptions.barFloatWindowBottom=="number"?t.scrollOptions.barFloatWindowBottom:t.scrollOptions.barFloatWindowBottom():0}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(pr(this.scrollTableBlock)),o=e.rootElement,r=e.scrollOptions.parentContainer,i=o.getBoundingClientRect(),s=r===document.documentElement?window.innerHeight:r.offsetHeight,l=window.innerHeight-this.getBarFloatWindowBottom(e),a=r.getBoundingClientRect(),d=Math.min(a.bottom,l),h=Math.max(a.top,0);this.autoScrollDir==="left"&&(o.scrollLeft-=om,o.scrollLeft<=0&&this.clearAutoScroll()),this.autoScrollDir==="right"&&(o.scrollLeft+=om,o.scrollLeft>=o.scrollWidth-o.offsetWidth&&this.clearAutoScroll()),this.autoScrollDir==="bottom"&&(r.scrollTop+=om,(r.scrollTop>=r.scrollHeight-s||i.bottom<=d)&&this.clearAutoScroll()),this.autoScrollDir==="top"&&(r.scrollTop-=om,(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 C6(n){return n.addCustom("table-scroll-events",t=>new LP(t))}const RP=M("table-doc-change-handler");class OP{constructor(t){this.editor=t,this.editor.addListener("docChanged",this.handleDocChanged)}handleDocChanged(t,e){if(!e){const{start:o,end:r}=t.selection.range;if(!t.findBlockById(o.blockId)||!t.findBlockById(r.blockId)){t.selection.selectBlock(t.getBlockByIndex("root",0),0);return}if(Yl(o)){const i=t.getBlockById(o.blockId);if(!He(i))return;if(g(RP,Yl(r),"invalid range"),!Ah(t,o.childContainerId)||!Ah(t,r.childContainerId)){t.selection.selectBlock(i,0);return}let s=null,l=null;const a=(d,h)=>{const p=h.getCellById(d.childContainerId),{colIndex:C=0,rowIndex:v=0}=d.custom;let B=-1,x=-1;return(p.col>C||p.col+p.colSpan-1<C)&&(B=p.col),(p.row>v||p.row+p.rowSpan-1<v)&&(x=p.row),B!==-1||x!==-1?me(i,d.childContainerId,{colIndex:B===-1?C:B,rowIndex:x===-1?v:x}):null};if(o.custom){const d=Tt.fromBlock(i);s=a(o,d),l=a(r,d)}(s!==null||l!==null)&&(t.selection.range.isReverse()?t.selection.setSelection(l!=null?l:r,s!=null?s:o):t.selection.setSelection(s!=null?s:o,l!=null?l:r))}}}destroy(){this.editor.removeListener("docChanged",this.handleDocChanged)}}function b6(n){n.addCustom("table-doc-change-handler",t=>new OP(t))}const br=M("create-content");function A6(n,t,e){var p;const o=new Sf(e),r=e.rows,i=e.cols;g(br,r>=1,`invalid rows: ${r}`),g(br,i>=1,`invalid cols: ${i}`),g(br,e.children,"no table children");const s=k("table",[],null),l=(p=e.colsWidth)!=null?p:new Array(e.cols).fill(0),a=k("colgroup",[],s);for(let C=0;C<o.colCount;C++){const v=k("col",[],a);l[C]&&(v.style.width=`${l[C]}px`)}const d=k("tbody",[],s);let h=0;for(let C=0;C<r;C++){const v=k("tr",[],d);for(let B=0;B<i;B++){const x=o.getCell({col:B,row:C});if(x.virtual)g(br,x.colSpan>1||x.rowSpan>1,"virtual cell should have colSpan or rowSpan");else{const I=e.children[h],_=k("td",[],v);x.colSpan>1&&(_.colSpan=x.colSpan),x.rowSpan>1&&(_.rowSpan=x.rowSpan);const D=e[Au(I)];D&&V(_,D),B===0&&e.hasColTitle&&V(_,Jw.COL_TITLE_ITEM),n.createChildContainer(t,_,I),h+=1}}}return g(br,h===e.children.length,"container count mismatch"),e.noBorder&&V(s,"no-border"),e.chart&&V(s,"editor-table-chart"),e.isStripeStyle&&V(s,"stripe"),e.hasRowTitle&&V(s,"row-title"),e.hasColTitle&&V(s,"col-title"),s}function _P(n,t,e,o,r){g(br,r.type==="table","not table data"),g(br,at(e)===t[t.length-1].containerId,"invalid path");const i=r,s=Is(o,"div");try{const l=k("div",[],null);l.setAttribute("data-type","table-content");const a=A6(n,t,i);a.classList.add("drag-preview-element"),l.appendChild(a);const d=n.getComponentOptions("table");p4(n),y4(n),f6(n,"create"),b6(n),d!=null&&d.hideCellMenu||m6(n),$L(n,E0);const h=n.addCustom(pr(o),()=>TO());h.init({parentElement:s,childElement:l,safeRightSpace:50,safeLeftSpace:40,parentContainer:Qt(e)?n.scrollContainer:e,locatingContainer:Qt(e)?(d==null?void 0:d.locatingContainer)||n.parent:e,paddingLeft:Cc+bu,paddingTop:Cc+bu,paddingBottom:bu/2,paddingRight:bu/2,barFloatWindowBottom:d==null?void 0:d.barFloatWindowBottom,allowScrollBarFixed:d==null?void 0:d.allowScrollBarFixed,isSetScale:d==null?void 0:d.isSetScale});const p=C6(n);h.on("scroll",p.handleReset),h.on("resize",p.handleReset),setTimeout(()=>{sO(n,o)})}catch{const a=`invalid table data: ${JSON.stringify(i)}`;br.error(a);const d=k("div",["error"],s);d.innerText=a}return s}function FP(n,t,e){g(br,e.type==="table","not table data");const o=e,r=Mt(t);try{const i=$e(t),s=Ri(t),l=A6(n,s,o);l.classList.add("drag-preview-element"),i.insertAdjacentElement("afterend",l),i.remove();const a=n.getComponentOptions("table");p4(n),y4(n),f6(n,"update"),b6(n),a!=null&&a.hideCellMenu||m6(n),E0(n,t)}catch{const s=`invalid table data: ${JSON.stringify(o)}`;br.error(s);const l=k("div",["error"],r);l.innerText=s}}function PP(n,t){let e,o,r=!1;if([...t].every(C=>C==="|")?(o=t.length,e=Array(o).fill(""),r=!0):(e=tp(t,"|").split("|"),o=e.length),o<2)return null;const i=3,s=o,l=[];for(let C=0;C<3;C++)e.forEach(v=>{l.push(Zr(n.doc,C===0?v:""))});const a=Array(s).fill(T0),d=l[r?0:s],h=n.doc.getContainerBlocks(d)[0].id;return{blockData:{id:tt(),type:"table",rows:i,cols:s,children:l,colsWidth:a},focusBlockId:h}}function NP(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(Zr(n.doc));const i=Array(o).fill(T0),s=r[0],l=n.doc.getContainerBlocks(s)[0].id;return{blockData:{id:tt(),type:"table",rows:e,cols:o,children:r,colsWidth:i},focusBlockId:l}}const sC=M("get-selected-containers");function v6(n,t,e,o){g(sC,e.blockId===o.blockId,"only allow select in single table block"),g(sC,it(t)===e.blockId,"only allow select in single table block");const r=Tt.fromBlock(t),i=r.getCellByContainerId(e.childContainerId),s=r.getCellByContainerId(o.childContainerId);if(e.custom===void 0||o.custom===void 0)return r.getCells(i,s).map(I=>r.getCellContainer(I));const{fromCol:l,toCol:a,fromRow:d,toRow:h}=Uo(t,e,o),p=new Set,C=[];return r.sub({row:d,col:l},{row:h,col:a}).forEach(B=>{B.forEach(x=>{const I=r.getCellByContainerId(x.containerId);I.col<l||I.row<d||I.col+I.colSpan-1>a||I.row+I.rowSpan-1>h||p.has(x.containerId)||(p.add(x.containerId),C.push(I.container))})}),C}function $P(n,t,e){g(sC,t.blockId===e.blockId,"only allow select in single table block");const o=n.getBlockById(t.blockId);return v6(n,o,t,e)}const y6=M("table-selection-to-doc");function HP(n,t){const{start:e,end:o,block:r}=t,i=St(r);g(y6,i==="table",`invalid block type: ${i}`);const s=n.getBlockData(r);if(e.isSimple()&&o.isSimple())return Pi(n.editorBlocks,n.doc.toJSON(),s);g(y6,!e.isSimple()&&!o.isSimple(),"invalid block pos type");const l=Tt.fromBlock(r),{fromCol:a,toCol:d,fromRow:h,toRow:p}=Uo(r,e,o),C={},v=[],B=n.doc.toJSON();let x={};l.sub({row:h,col:a},{row:p,col:d}).forEach((K,ht)=>{K.forEach((bt,_t)=>{const Ht=bt.containerId;if(v.indexOf(Ht)!==-1)return;v.push(Ht);let oe;if(bt.virtual){const Ee=l.getCellByContainerId(bt.containerId),Rn=a+_t;let Ir=Ee.col+Ee.colSpan-1;Ir>d&&(Ir=d);const kn=Ir-Rn+1;kn>1&&(C[`${Ht}_colSpan`]=kn);const un=h+ht;let Tr=Ee.row+Ee.rowSpan-1;Tr>p&&(Tr=p);const ii=Tr-un+1;ii>1&&(C[`${Ht}_rowSpan`]=ii),oe=Qr()}else{if(oe=d1(n.editorBlocks,B,Ht),bt.col+bt.colSpan>d+1){const Ee=d-bt.col+1;Ee>1&&(C[`${Ht}_colSpan`]=Ee)}else bt.colSpan>1&&(C[`${Ht}_colSpan`]=bt.colSpan);if(bt.row+bt.rowSpan>p+1){const Ee=p-bt.row+1;Ee>1&&(C[`${Ht}_rowSpan`]=Ee)}else bt.rowSpan>1&&(C[`${Ht}_rowSpan`]=bt.rowSpan)}const{root:Le,...Jn}=oe.blocks;x={...x,...Jn,[Ht]:Le}})});const _=Bu($e(r)).slice(a,d+1);return{blocks:{root:[{id:tt(),type:i,children:v,colsWidth:_,rows:p-h+1,cols:d-a+1,...C}],...x},meta:{},comments:{}}}function jP(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 UP(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 zP(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 VP(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 WP(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,!jP(n,l)){l.top--,a=!0;continue}if(!UP(n,l)){l.left--,a=!0;continue}if(!zP(n,l)){l.bottom++,a=!0;continue}if(!VP(n,l)){l.right++,a=!0;continue}}while(a);return l}function qP(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),C=WP(i,{row:a,col:h},{row:d,col:p}),v=r.getCell({row:C.top,col:C.left}),B=r.getCell({row:C.bottom,col:C.right}),x=r.getCell({row:C.top,col:C.right}),I=r.getCell({row:C.bottom,col:C.left});let _,D;return s.row<=l.row?s.col<=l.col?(_=v,D=B):(_=x,D=I):s.col<l.col?(_=I,D=x):(_=B,D=v),console.log(`move ${_.col}, ${_.row}, -> ${D.col}, ${D.row}`),{anchor:me(t,_.containerId),focus:me(t,D.containerId)}}function k6(n,t,e){if(e.isSimple())return[$e(t).getBoundingClientRect()];const o=$e(t),r=o.getBoundingClientRect(),{fromCol:i,fromRow:s,toCol:l,toRow:a}=Uo(t,e.start,e.end),d=Bu(o),h=d.slice(0,i).reduce((x,I)=>x+I,0),p=h+d.slice(i,l+1).reduce((x,I)=>x+I,0),C=l6(o);let v=C.slice(0,s).reduce((x,I)=>x+I,0);const B=v+C.slice(s,a+1).reduce((x,I)=>x+I,0);if(s===0){const x=wP(n,t);v-=x}return[new DOMRect(r.left+h,r.top+v,p-h,B-v)]}M("table-size");const GP=40;function rm(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 QP(n,t,e){const o=Bp(n,e.container);return o!==void 0?o+rm(t):GP*e.colSpan-rm(t)}function ZP(n,t,e,o){let r=0;const i=e.colCount;for(let s=0;s<i;s++){const l=e.getCell({col:s,row:o});if(l.virtual)continue;let a=QP(n,t,l);const d=K5(l.container,{withPadding:!0});d&&d>a&&(a=d),r+=a+rm(t)}return r}function YP(n,t){const e=$e(t),o=Tt.fromTable(e);let r=0;for(let s=0;s<o.rowCount;s++)r=Math.max(r,ZP(n,e,o,s));const i=rm(e);return r+=i,r}const ei=M("table-creator");async function JP(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=NP(n,{cols:o,rows:r});if(!i)return null;const{blockData:s,focusBlockId:l}=i;return n.insertBlock(t.containerId,t.blockIndex,s,be(n,l,0))})}class KP{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 C,v;t.preventDefault(),t.stopPropagation();const e=t.target;g(ei,e instanceof HTMLElement,"invalid event target");const o=e.closest(".table-creator");g(ei,o,"no table creator");const r=o.querySelectorAll(".active");if(r.length===0)return;const s=r[r.length-1].id;g(ei,s,"no cell id");const l="table-creator-cell-";if(!s.startsWith(l))return;const d=s.substring(l.length).split("-");g(ei,d.length===2,"invalid cell id");const h=Number.parseInt(d[0],10)+1,p=Number.parseInt(d[1],10)+1;ei.debug(`${h}, ${p}`),this.colCount=p,this.rowCount=h,(C=this.closeable)==null||C.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&&rt(r,"active")}});m(this,"handleTableCreatorCellEnter",t=>{const e=t.target;g(ei,e instanceof HTMLElement,"invalid event target");const o=e.id,r="table-creator-cell-";g(ei,o.startsWith(r),"invalid cell id");const s=o.substring(r.length).split("-");g(ei,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),C=document.getElementById(p);g(ei,C,"no cell"),d<=l&&h<=a?V(C,"active"):rt(C,"active")}});this.element=this.createTableCreatorElement()}createTableCreatorElement(){const t=k("div",["table-creator"],null),e=(o,r,i)=>{const s=k("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=k("div",["table-creator-row"],t);for(let i=0;i<9;i++)e(r,o,i).addEventListener("mouseenter",this.handleTableCreatorCellEnter)}return t}}function XP(){return new KP}function tN(n){const t=/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g,e=n.match(t);return e?e.length:0}function w6(n){const t=tN(n);return n.length+t}function eN(n,t){const e=w6(n),o=t-e;return o>0?n+" ".repeat(o):n}function nN(n,t,e,o,r){const i=t,s=new Sf(i);if(o==="markdown"||o==="text"){const l=I=>e.blocks[I].map((H,W)=>o==="markdown"?e1(n,H,e,[...r,{containerId:I,blockIndex:W}]):Nh(n,H,e,[...r,{containerId:I,blockIndex:W}])),a=I=>l(I).join(" ").replace(/\n/g," ").trim(),d=new Map,h=new Map;for(let I=0;I<s.colCount;I++){let _=0;for(let D=0;D<s.rowCount;D++){const H=s.getCell({row:D,col:I});let W="";H.virtual||(W=a(H.containerId)),d.set(`${D},${I}`,W),_=Math.max(_,w6(W))}h.set(I,_)}const p=I=>{const _=d.get(`${I.row},${I.col}`)||"",D=h.get(I.col)||0;return eN(_,D)};if(o==="text"){const I=[];for(let _=0;_<s.colCount;_++){const D=p({row:0,col:_});I.push(D)}for(let _=1;_<s.rowCount;_++)for(let D=0;D<s.colCount;D++){const H=p({row:_,col:D});I.push(H)}return I.join(`
|
|
600
|
+
`:r.mathjaxText}function JF(){return{abstract:L.t("mathjax.abstract")}}const KF={embedType:"math",createEmbedContent:qF,getOptions:QF,convertFrom:GF,handleDeleteBlock:ZF,convertTo:YF,getBlockProperties:JF},Hot="",XF={mathjax:{emptyText:"\u7A7A\u7684\u516C\u5F0F",abstract:"\u516C\u5F0F"}},tP={mathjax:{emptyText:"Empty formula",abstract:"Formula"}},eP={mathjax:{emptyText:"\u6570\u5F0F\u306A\u3057",abstract:"\u6570\u5F0F"}};L.mergeLang({"zh-CN":XF,"en-US":tP,"ja-JP":eP});function nP(n,t,e,o){const r=n.getBlockByIndex(t,e),i=n.getBlockText(r),{left:s}=Tn(i,o);if(!se(s).endsWith("$$$$"))return!1;const a=o-4,d=o,h={id:tt(),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);Jf(n,p)})}),!0}class oP{handleAfterInsertText(t,e,o,r,i){return!!(i===" "&&nP(t,e,o,r))}}const Tc=M("inline-box-items");function rP(n,t,e){return n.undoManager.runInGroup(()=>{var s;let o=n.getBlockByIndex(t,e);ue(n,o)||(o=n.insertTextBlock([],t,e));const r=e6();n.setBlockText(o,[r]);const i=(s=r.attributes)==null?void 0:s.id;return g(Tc,i,"mathjax box id is empty"),setTimeout(()=>{const l=n.getBoxById(i);Jf(n,l)},100),o})}function iP(n,t,e){let o=n.getBlockByIndex(t,e),r="bottom-start";return ue(n,o)||(r="top-start"),Eu(n,{target:o,linkText:"",linkUrl:"",onFinished:(l,a)=>{n.undoManager.runInGroup(()=>{try{ue(n,o)||(o=n.insertTextBlock([],t,e));const d=ho(l,{link:a}),h=ho(" ",null),p=[d,h];n.insertTextToBlock(o,0,p),n.selection.selectBlock(o,sn(p)),n.focus()}catch(d){Tc.error(d)}})},onClose:()=>{n.focus()},placement:r}),o}function sP(n,t,e){return n.undoManager.runInGroup(()=>{var l;const o=n.getBlockByIndex(t,e),r=n.selection.range;g(Tc,Wr(r.start),"invalid block position");const i=e6();n.insertBoxToBlock(o,r.start.offset,i.attributes);const s=(l=i.attributes)==null?void 0:l.id;return g(Tc,s,"mathjax box id is empty"),setTimeout(()=>{const a=n.getBoxById(s);Jf(n,a)},100),o})}function lP(n,t,e){const o=n.getBlockByIndex(t,e),r=n.selection.range;g(Tc,Wr(r.start),"invalid block position");const i=Ur(n,o,r);if(i.length===0)return;const s=i[0],l=qr(n,o,"quick-menu-inline-link",s);Eu(n,{target:l,linkText:"",linkUrl:"",onFinished:(h,p)=>{n.undoManager.runInGroup(()=>{try{const C=n.getBlockText(o),v=Gr(C,r.start.offset,h,{link:p});n.setBlockText(o,v),n.selection.selectBlock(o,r.start.offset+h.length),n.focus()}catch(C){Tc.error(C)}})},onClose:()=>{n.focus()},placement:"bottom-start"})}class r6{getCommands(){return[{id:"insert-math",name:L.t("quickMenu.inlineBox.math"),icon:G2,order:900,group:"common",subText:An("insert-math")},{id:"insert-link",name:L.t("quickMenu.inlineBox.link"),icon:e0,order:400,group:"common",subText:An("insert-link")}]}async handleUpdateBlockCore(t,e){switch(e.item.id){case"insert-math":return sP(t,e.containerId,e.blockIndex);case"insert-link":return lP(t,e.containerId,e.blockIndex);default:return null}}async handleInsertEmptyBlockCore(t,e){switch(e.item.id){case"insert-math":return rP(t,e.containerId,e.blockIndex);case"insert-link":return iP(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 cP(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 Z4(e),new r6].forEach(l=>{const a=l.getCommands(n);r.push(...a.map(d=>({...d,itemType:"insert-block",commandProvider:l})))}),r}function aP(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=>{Q4(i,r)}),e.push(...r.insertBlockCommandItems))}),e.push(...cP(n,t)),e}function eC(n,t={withPlainText:!1}){const e=aP(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||Y4[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=L.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 uP(n,t,e){const o=n.getFocusedBlock();if(!o)return;const r=n.getParentContainer(o),i=at(r);let l=n.getBlockIndex(o);if(ue(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 i6=M("quick-menu"),dP={id:"quick-menu",trigger:["/"]},hP=5;class Kf{constructor(t,e=dP){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||RR(s).toLocaleLowerCase().indexOf(r)!==-1)return o.add(s.group),!0;const l=`blockMenu.section.${s.group||"common"}`,a=L.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(!co(i)){const s=nt(ot(i));if(s&&St(s)==="code")return!1}return!0});m(this,"onClickItem",(t,e)=>{const o=e;o.itemType==="insert-block"&&(g(i6,o.blockOptions||o.commandProvider,"invalid quick item, no block options or command provider"),g(i6,this.suggest.anchor,"invalid suggest, no anchor"),this.options.id==="empty-block-menu"&&this.editor.focus(),uP(this.editor,o,this.suggest.anchor))});this.editor=t,this.options=e,this.items=[],this.maxHeading=Hf(),this.suggest=new f0(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=eC(this.editor);this.items=t}refreshMenuItems(){let t=null,e=0;const o=Hf();if(o!==this.maxHeading){const r=new Z4,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>hP&&(this.suggest.close(),this.firstEmptyOffset=-1)}}}class Xf{constructor(t){m(this,"instance");m(this,"mousedown",!1);m(this,"currentInstance",null);m(this,"attributeName",[]);m(this,"attributeDesc","");m(this,"_lastClickButtonId","");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=k("div",[],null);return k("span",[],i,e),r&&k("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||!Xt(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(this._lastClickButtonId===e.getAttribute("data-button-id"))return this._lastClickButtonId="",!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 l=t.reference.getAttribute("data-editor-tooltip-offset-x"),a=t.reference.getAttribute("data-editor-tooltip-offset-y");i.offset=[l?Number.parseInt(l,10):0,a?Number.parseInt(a,10):0]}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);const s=document.body;if(i.appendTo=this.fixContainerForFullscreen(s),Object.keys(i).length&&t.setProps(i),t.reference.hasAttribute(`data-editor-tooltip-${this.editor.clientId}-dynamic`)){const l=t.reference.getAttribute(`data-editor-tooltip-${this.editor.clientId}-dynamic`);t.setContent(l||"")}}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=jg.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,hideOnClick:!1}),t.domEvents.addEventListener(document,"mousedown",this.handleDocumentMouseDown)}set lastClickButtonId(t){this._lastClickButtonId=t,t&&setTimeout(()=>{this._lastClickButtonId===t&&(this._lastClickButtonId="")},500)}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=Fe.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)}fixContainerForFullscreen(t){return t.closest("body")&&document.fullscreenElement&&!document.fullscreenElement.contains(t)?document.fullscreenElement:t}}const fP={"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",link:"link"};function mP(n,t){const e=new Set(Object.keys(fP)),o=t.filter(i=>e.has(i.id));return Nf(o)}function Tu(n,t){if(!n.isWritable())return!1;const e=n.selection.range,o=n.editorCommandProviders.getCommands(e),i=mP(n,o).find(s=>s.id===`text/${t}`||s.id==="link");return i?(n.editorCommandProviders.executeCommand(e,i,{}),Ic.get(n).update("selectionChange"),!0):!1}function gP(n,t){const e=n.selection.focusedBlock;if(!n.isWritable()||!et(n,e))return!1;const o=n.getBlockData(e).heading,r={id:`heading-${t}`,source:"BlockTurnIntoCommandProvider",value:String(t)};return Number(o)===t&&(r.id="text",r.value=null),n.editorCommandProviders.executeCommand(n.selection.range,r,{}),!0}const nC={"CtrlOrCmd+B":n=>Tu(n,"style-bold"),"CtrlOrCmd+I":n=>Tu(n,"style-italic"),"CtrlOrCmd+U":n=>Tu(n,"style-underline"),"CtrlOrCmd+D":n=>Tu(n,"style-strikethrough"),"CtrlOrCmd+K":n=>Tu(n,"link"),...(()=>{const n={};for(let t=1;t<=8;t++)n[`CtrlOrCmd+${t}`]=e=>gP(e,t);return n})()},pP={quickMenu:{basic:{heading:{title:"\u6807\u9898 {heading}",space:"{markdown}\u7A7A\u683C"},unordered:"\u65E0\u5E8F\u5217\u8868",ordered:"\u6709\u5E8F\u5217\u8868",checkbox:"\u5F85\u529E\u5217\u8868",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"}},CP={quickMenu:{basic:{heading:{title:"Heading {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:"Heading {name}",headingGroup:"Text style",text:"Text"}},bP={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"}};L.mergeLang({"zh-CN":pP,"en-US":CP,"ja-JP":bP});const Uot="";function Xs(n,...t){const e=mo(...t);return e.classList.remove("editor-button"),e.classList.add("editor-text-button"),n.append(e),e}function s6(n){const t=$f(n);t==null||t.hide();const e=n.findCustom("table-border-bar");e==null||e.closeToolbar()}function AP(n){return k("div",["insert-column-button","drop-marker"],n)}const vP=M("row-height");function l6(n){const t=Tt.fromTable(n),e=n.rows;g(vP,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 yP=M("table-border-bar-dom");function c6(n){var a;const t=nt(n.contentElement);g(yP,t,"no block");const o=te(t).querySelector(".table-border-bar-container.left"),i=Mt(t).offsetLeft-Cc,s=((a=n.scrollOptions.paddingLeft)!=null?a:0)+i,l=Math.min(n.contentElement.offsetLeft-i,n.rootElement.scrollLeft-s);o&&(o.style.left=`${-l}px`)}const Zi=M("table-border-bar-dom");function Sc(n,t){g(Zi,He(t),"invalid table block");const e=$e(t),o=Cr(n,t),r=te(t),i=(p,C,v)=>{const B=k("div",["button-root",C],p),x=k("div",["button-container",C],B);B.setAttribute(`data-${C}-index`,`${v}`),x.setAttribute(`data-editor-tooltip-${n.clientId}`,C==="left"?L.t("table.insertRow"):L.t("table.insertCol")),k("span",["insert-indicator"],x),AP(x)},{selectedRows:s,selectedColumns:l}=g0(n,t),a=()=>{const p=o.querySelector(".table-border-bar-container.top");g(Zi,p,"no top border bar container");const C=k("div",["table-border-bar-container","top"],null),v=k("div",["table-border-bar","top"],C),B=DO(e),I=Tt.fromTable(e).colCount;n.selection.range.isSimple()&&i(v,"top",0);for(let _=0;_<I;_++){const D=_===I-1?B[_]+2:B[_],H=k("span",["table-border-bar-cell","top"],v);l.has(_)&&H.classList.add("selected"),H.setAttribute("data-top-index",`${_}`),H.style.width=`${D}px`,n.selection.range.isSimple()&&i(v,"top",_+1)}Da(p,C)},d=()=>{const p=r.querySelector(".table-border-bar-container.left");g(Zi,p,"no left border bar container");const C=k("div",["table-border-bar-container","left"],null),v=k("div",["table-border-bar","left"],C);k("span",["table-border-bar-cell","corner"],v);const B=l6(e);n.selection.range.isSimple()&&i(v,"left",0),Array.from(e.rows).forEach((x,I,_)=>{const D=k("span",["table-border-bar-cell","left"],v);s.has(I)&&D.classList.add("selected"),D.setAttribute("data-left-index",`${I}`);const H=I===_.length-1?B[I]+2:B[I];D.style.height=`${H}px`,n.selection.range.isSimple()&&i(v,"left",I+1)}),Da(p,C)};a(),d();const h=n.findCustom(pr(t));h&&c6(h)}function a6(n,t){const e=t.target;if(!(e instanceof Element))return;const o=nt(e);g(Zi,o&&He(o),"invalid table block"),Sc(n,o),n.selection.caret.update()}function tm(n,t){const e=t.target;if(!(e instanceof Element))return;const o=nt(e);g(Zi,o&&He(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);b4(n,o,i),Sc(n,o)}else if(r.classList.contains("left")){const i=parseInt(r.getAttribute("data-left-index")||"0",10);A4(n,o,i),Sc(n,o)}}}function em(n,t){var s;s6(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=nt(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),C=Math.min(r,p),v=Math.abs(r-p)+1;Et(l.target,"top")&&o==="top"?VO(n,d,C,v,{reverse:!0}):Et(l.target,"left")&&o==="left"&&WO(n,d,C,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&&Et(t.target,"table-border-bar-cell")&&(e=nt(t.target),Et(t.target,"top")?o="top":Et(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 u6(n){const t=n.selection.range,e=pu(n,t);e&&Sc(n,e)}function kP(n,t){g(Zi,He(t),"invalid table block");const e=Cr(n,t),o=te(t),r=k("div",["table-border-bar-container","top"],e),i=k("div",["table-border-bar-container","left"],o);Sc(n,t),n.domEvents.addEventListener(Mt(t),"scroll",a6),n.domEvents.addEventListener(r,"click",tm),n.domEvents.addEventListener(i,"click",tm),n.domEvents.addEventListener(r,"mousedown",em),n.domEvents.addEventListener(i,"mousedown",em),n.addListener("afterClearSelection",u6)}function d6(n,t){if(!n.isWritable())return;if(Cr(n,t).querySelector(".table-border-bar-container")){Sc(n,t);return}kP(n,t)}function h6(n,t){g(Zi,He(t),"invalid table block");const e=Cr(n,t),o=te(t),r=e.querySelectorAll(".table-border-bar-container"),i=o.querySelectorAll(".table-border-bar-container");r.forEach(s=>{n.domEvents.removeEventListener(s,"click",tm),n.domEvents.removeEventListener(s,"mousedown",em),s.remove()}),i.forEach(s=>{n.domEvents.removeEventListener(s,"click",tm),n.domEvents.removeEventListener(s,"mousedown",em),s.remove()}),n.domEvents.removeEventListener(Mt(t),"scroll",a6),n.addListener("afterClearSelection",u6)}function wP(n,t){g(Zi,He(t),"invalid table block");const o=Cr(n,t).querySelector(".table-border-bar-container.top");return o?o.getBoundingClientRect().height:0}class BP{constructor(t,e){m(this,"toolbar");m(this,"handleSelectionChange",(t,e)=>{!t.isVisible||(e==="delete-columns"?(Vi(this.editor,this.tableBlock,!0,!0),Wi(this.editor,this.tableBlock,!0,!0)):e==="delete-rows"?(Vi(this.editor,this.tableBlock,!0,!1),Wi(this.editor,this.tableBlock,!0,!1)):(Vi(this.editor,this.tableBlock,!1),Wi(this.editor,this.tableBlock,!1)))});m(this,"handleClick",(t,e,o)=>{e.id==="delete-columns"?p0(this.editor.selection.range):e.id==="delete-rows"&&C0(this.editor.selection.range)});m(this,"handleToolbarClose",()=>{this.tableBlock&&pu(this.editor,this.editor.selection.range)===this.tableBlock&&(Vi(this.editor,this.tableBlock,!1),Wi(this.editor,this.tableBlock,!1))});this.editor=t,this.tableBlock=e;const o=t.options.componentsOptions.popover;this.toolbar=new fu([],void 0,{id:"table-row-column-toolbar",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,s;const{selectedColumns:t,selectedRows:e}=g0(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=Ur(this.editor,this.tableBlock,this.editor.selection.range)[0];if(!o){this.toolbar.close("cancelBar");return}if(t.size>0){const l={id:"delete-columns",name:L.t("table.deleteSelectCol"),icon:O2};this.toolbar.updateItems([l]);const a=qr(this.editor,this.tableBlock,"table-row-column-delete",o);this.toolbar.manualShow(a,{placement:"top",offset:[0,5]})}else{const l={id:"delete-rows",name:L.t("table.deleteSelectRow"),icon:R2};this.toolbar.updateItems([l]);const h=te(this.tableBlock).querySelector(".table-border-bar-container.left").getBoundingClientRect(),p=new DOMRect(Math.max(h.left,o.left-Cc),o.top,Cc,o.height),C=qr(this.editor,this.tableBlock,"table-row-column-delete",p);this.toolbar.manualShow(C,{placement:"left",offset:[0,5]});const v=this.editor.options.componentsOptions.popover;(r=this.toolbar.tippyInstance)==null||r.setProps({popperOptions:{modifiers:[{name:"flip",options:{boundary:v==null?void 0:v.overflowBoundary,fallbackPlacements:["left","right"]}}]}})}(s=(i=this.toolbar.tippyInstance)==null?void 0:i.popperInstance)==null||s.update()}destroy(){this.toolbar.destroy(),this.toolbar.removeAllListeners()}}const oC=M("table-border-bar");class EP{constructor(t,e){m(this,"toolbar");m(this,"resizeObserver",null);m(this,"handleReadonlyChanged",t=>{t.isWritable()?this.update():h6(this.editor,this.tableBlock)});m(this,"handleBlockUpdated",()=>{var t;(t=this.resizeObserver)==null||t.disconnect(),setTimeout(()=>{var o;const e=this.editor.getBlockById(it(this.tableBlock));(o=this.resizeObserver)==null||o.observe($e(e))})});m(this,"handleScroll",()=>{var t;(t=this.toolbar)==null||t.update()});m(this,"handleTableResize",()=>{!this.editor.isWritable()||this.update()});this.editor=t,this.tableBlock=e,g(oC,this.tableBlock,"no table block"),oC.debug("create table border bar"),d6(this.editor,this.tableBlock),this.resizeObserver=new bs(this.handleTableResize),this.resizeObserver.observe($e(this.tableBlock));const o=t.getComponentOptions("table");o!=null&&o.hideToolbar||(this.toolbar=new BP(this.editor,this.tableBlock)),this.editor.addListener("readonlyChanged",this.handleReadonlyChanged)}close(){var t;(t=this.toolbar)==null||t.close()}destroy(){var t,e;oC.debug("destroy table border bar"),(t=this.resizeObserver)==null||t.disconnect(),this.resizeObserver=null,h6(this.editor,this.tableBlock),(e=this.toolbar)==null||e.destroy(),this.editor.removeListener("readonlyChanged",this.handleReadonlyChanged)}update(){var t;d6(this.editor,this.tableBlock),(t=this.toolbar)==null||t.update()}}const xP=M("table-border-bar");class IP{constructor(t){m(this,"activeTableBar",null);m(this,"handleBlockDeleted",(t,e)=>{!this.activeTableBar||(e===this.activeTableBar.tableBlock||Xt(e,this.activeTableBar.tableBlock))&&(this.activeTableBar.destroy(),this.activeTableBar=null)});m(this,"handleSelectionChanged",t=>{setTimeout(()=>{var r;const e=t.selection.range,o=pu(t,e);((r=this.activeTableBar)==null?void 0:r.tableBlock)!==o&&this.activeTableBar&&this.hide(),o&&this.show(o)})});m(this,"handleScroll",()=>{var t;(t=this.activeTableBar)==null||t.handleScroll()});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 EP(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(xP,this.activeTableBar,"no active table bar"),this.activeTableBar.destroy(),this.activeTableBar=null)}}function f6(n,t){const e=n.addCustom("table-border-bar",o=>new IP(o));t==="update"&&e.update()}const Ln=M("table-cell-menu"),TP="style-bg-color-";class SP{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=pu(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 Ro?t.getBlockById(i.blockId)===this.activeTableBlock?s=r.getCellByContainerId(i.childContainerId):s=this.getCellByChildBlockId(r,i.blockId):i.blockId!==this.activeTableBlock.id&&(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=k("div",["cell-background-color-item"],null);k("span",[],t,L.t("table.cellBackground"));const e=this.getSelectedBkgColorIndex();k("button",["item-button"],t).setAttribute("data-color-index",`${e}`);const r=k("span",["item-sub-indicator"],t);return r.innerHTML=Y1,t});m(this,"handleCommand",t=>{var r;g(Ln,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":C0(Xw(this.editor,this.activeTableBlock,!1));break;case"delete-select-col":p0(Xw(this.editor,this.activeTableBlock,!0));break;case"merge-cell":Yw(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":tO(this.editor,this.activeTableBlock,o==="show-border");break;case"show-chart":oO(this.editor,this.activeTableBlock,o==="show-chart"),B0(this.editor,this.activeTableBlock,{updateNow:!0});break}});m(this,"handleToolbarClose",()=>{this.targetButton&&rt(this.targetButton,"active"),this.activeTableBlock&&pu(this.editor,this.editor.selection.range)===this.activeTableBlock&&(Vi(this.editor,this.activeTableBlock,!1),Wi(this.editor,this.activeTableBlock,!1)),this.editor.focus()});m(this,"handleSelectionChange",(t,e)=>{!t.isVisible||(g(Ln,this.activeTableBlock,"no target table block"),e==="cell-background-color"&&this.handleBeforePopupPalette(),e==="delete-select-row"?(Vi(this.editor,this.activeTableBlock,!0,!1),Wi(this.editor,this.activeTableBlock,!0,!1)):e==="delete-select-col"?(Vi(this.editor,this.activeTableBlock,!0,!0),Wi(this.editor,this.activeTableBlock,!0,!0)):(Vi(this.editor,this.activeTableBlock,!1),Wi(this.editor,this.activeTableBlock,!1)))});m(this,"handleClick",(t,e)=>{var o;g(Ln,this.activeTableBlock,"no target table block"),g(Ln,this.targetButton,"no target button"),s6(this.editor),Et(this.targetButton,"active")?(rt(this.targetButton,"active"),(o=this.manualMenu)==null||o.close("clickItem")):(V(this.targetButton,"active"),this.manualMenu?this.manualMenu.updateItems(this.createCommandMenu()):(this.manualMenu=new Gs(this.createCommandMenu(),void 0,{id:"table-cell-menu"}),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&&(rt(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(Ln,r,"no parent cell");const i=nt(r);if(g(Ln,i,"no parent block"),$e(i)===t.table)return t.getCellByCellElement(r);o=i}return g(Ln,!1,"filed to get cell by child block id"),null}createTargetButton(t){this.targetButton?t.querySelector(`:scope > .${k0}`)||t.appendChild(this.targetButton):(this.targetButton=k("button",[k0],t),this.targetButton.innerHTML=gf,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(Ln,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);A0(this.editor,this.activeTableBlock,{col:o,row:r})}else v0(this.editor.selection.range)}}getSelectedBkgColorIndex(){var s;g(Ln,this.activeTableBlock,"no target table block");const t=this.editor.selection.range,e=zi(this.editor,this.activeTableBlock,t.focus),o=this.editor.getBlockData(this.activeTableBlock),r=e.childContainerId,i=o[`${r}_background`];return i?Number.parseInt((s=i.substring(TP.length))!=null?s:"0",10):-1}createCommandMenu(){g(Ln,this.activeTableBlock,"no target table block");const t=this.editor.getBlockData(this.activeTableBlock),e=Zw(this.editor,this.activeTableBlock,this.editor.selection.range);let o=this.editor.selection.range;if(o.isSimple()){const h=zi(this.editor,this.activeTableBlock,o.start);o=We(this.editor,{anchor:h,focus:h})}const r=Qw(this.editor,this.activeTableBlock,o),i=t.hasRowTitle,s=t.hasColTitle,l=t.isStripeStyle,a=t.noBorder,d=t.chart;return this.colorPaletteItem=new Uw("cell-background-color",{color:!1}),this.colorPaletteItem.palette.on("onClick",(h,p)=>{var C;switch(g(Ln,this.activeTableBlock,"no target table block"),h){case"clearColor":n4(this.editor,this.activeTableBlock,-1);break;case"backgroundColor":n4(this.editor,this.activeTableBlock,p);break}(C=this.manualMenu)==null||C.close("clickItem")}),[{id:"cell-background-color",name:L.t("table.cellBackground"),element:this.createBkgColorItem(),children:[this.colorPaletteItem]},{id:"separator",name:"",type:"separator"},{id:"merge-cell",name:L.t("table.mergeCell"),states:e?[]:["disabled"]},{id:"split-cell",name:L.t("table.splitCell"),states:r?[]:["disabled"]},{id:"separator",name:"",type:"separator"},{id:"delete-select-row",name:L.t("table.deleteSelectRow")},{id:"delete-select-col",name:L.t("table.deleteSelectCol")},{id:"separator",name:"",type:"separator"},{id:"table-config",name:L.t("table.tableConfigKey"),children:[{id:"row-title",name:L.t("table.tableConfig.rowTitle"),states:i?["checked"]:[]},{id:"col-title",name:L.t("table.tableConfig.colTitle"),states:s?["checked"]:[]},{id:"stripe-style",name:L.t("table.tableConfig.stripeStyle"),states:l?["checked"]:[]},{id:"hide-border",name:a?L.t("table.tableConfig.showBorder"):L.t("table.tableConfig.hideBorder"),value:a?"show-border":"hide-border"},{id:"show-chart",name:d?L.t("table.tableConfig.hideChart"):L.t("table.tableConfig.showChart"),value:d?"hide-chart":"show-chart"}]}]}handleRowTitle(t){g(Ln,this.activeTableBlock,"no target table block"),t?JR(this.editor,this.activeTableBlock):YR(this.editor,this.activeTableBlock)}handleColTitle(t){g(Ln,this.activeTableBlock,"no target table block"),t?ZR(this.editor,this.activeTableBlock):QR(this.editor,this.activeTableBlock)}handleStripeStyle(t){g(Ln,this.activeTableBlock,"no target table block"),t?XR(this.editor,this.activeTableBlock):KR(this.editor,this.activeTableBlock)}}function m6(n){n.addCustom("table-cell-menu",t=>new SP(t))}const nm=M("table-container");function rC(n){const t=n.closest("td");return g(nm,t,"no parent cell for a table cell container"),t}function g6(n){const t=$e(n);return Array.from(t.querySelectorAll(':scope > tbody > tr > td > [data-type="editor-container"].child'))}function iC(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(nm,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(nm,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(nm,!1,`invalid navigation type: ${e}`)}const DP=12,MP=90,om=23,p6=2;class LP{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=nt(e);if(o&&Xt(this.editor.rootContainer,o)){const r=ti(o);r&&(this.scrollTableBlock=r,document.addEventListener("mousemove",this.handleAutoScroll))}}});m(this,"handleAutoScroll",lI.default(t=>{if(this.scrollTableBlock){const e=this.editor.getCustom(pr(this.scrollTableBlock)),o=e.rootElement,r=e.scrollOptions.parentContainer,i=o.getBoundingClientRect(),s=window.innerHeight-this.getBarFloatWindowBottom(e),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=ti(o);if(r){const i=t.getCustom(pr(r)),s=i.rootElement.getBoundingClientRect(),l=Mo(t,o,e.start);if(s.left>l.left){const a=e.start.offset===0?DP:p6;i.rootElement.scrollLeft-=s.left-l.left+a}else if(l.right>s.right){const a=e.start.offset===0?MP:p6;i.rootElement.scrollLeft+=l.right-s.right+a}}}else{const o=t.getBlockById(e.start.blockId),r=ti(o),i=t.getBlockById(e.end.blockId),s=ti(i);if(r&&r===s){const l=t.getCustom(pr(r)),a=l.rootElement.getBoundingClientRect();let d=null;if(e.isSimple())d=e.isReverse()?Mo(t,o,e.start):Mo(t,i,e.end);else{const h=rC(ir(t,e.start.childContainerId)),p=rC(ir(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=>{Ww(t),this.editor.selection.caret.update()});m(this,"handleReset",t=>{Ww(t),this.editor.selection.caret.update();const e=this.editor.findCustom("table-border-bar");e&&e.handleScroll(),c6(t)});this.editor=t,this.editor.addListener("selectionChanged",this.handleSelectionChanged),document.addEventListener("mousedown",this.handleMouseDown),document.addEventListener("mouseup",this.handleMouseUp)}getBarFloatWindowBottom(t){return t.scrollOptions.barFloatWindowBottom?typeof t.scrollOptions.barFloatWindowBottom=="number"?t.scrollOptions.barFloatWindowBottom:t.scrollOptions.barFloatWindowBottom():0}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(pr(this.scrollTableBlock)),o=e.rootElement,r=e.scrollOptions.parentContainer,i=o.getBoundingClientRect(),s=r===document.documentElement?window.innerHeight:r.offsetHeight,l=window.innerHeight-this.getBarFloatWindowBottom(e),a=r.getBoundingClientRect(),d=Math.min(a.bottom,l),h=Math.max(a.top,0);this.autoScrollDir==="left"&&(o.scrollLeft-=om,o.scrollLeft<=0&&this.clearAutoScroll()),this.autoScrollDir==="right"&&(o.scrollLeft+=om,o.scrollLeft>=o.scrollWidth-o.offsetWidth&&this.clearAutoScroll()),this.autoScrollDir==="bottom"&&(r.scrollTop+=om,(r.scrollTop>=r.scrollHeight-s||i.bottom<=d)&&this.clearAutoScroll()),this.autoScrollDir==="top"&&(r.scrollTop-=om,(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 C6(n){return n.addCustom("table-scroll-events",t=>new LP(t))}const RP=M("table-doc-change-handler");class OP{constructor(t){this.editor=t,this.editor.addListener("docChanged",this.handleDocChanged)}handleDocChanged(t,e){if(!e){const{start:o,end:r}=t.selection.range;if(!t.findBlockById(o.blockId)||!t.findBlockById(r.blockId)){t.selection.selectBlock(t.getBlockByIndex("root",0),0);return}if(Yl(o)){const i=t.getBlockById(o.blockId);if(!He(i))return;if(g(RP,Yl(r),"invalid range"),!Ah(t,o.childContainerId)||!Ah(t,r.childContainerId)){t.selection.selectBlock(i,0);return}let s=null,l=null;const a=(d,h)=>{const p=h.getCellById(d.childContainerId),{colIndex:C=0,rowIndex:v=0}=d.custom;let B=-1,x=-1;return(p.col>C||p.col+p.colSpan-1<C)&&(B=p.col),(p.row>v||p.row+p.rowSpan-1<v)&&(x=p.row),B!==-1||x!==-1?me(i,d.childContainerId,{colIndex:B===-1?C:B,rowIndex:x===-1?v:x}):null};if(o.custom){const d=Tt.fromBlock(i);s=a(o,d),l=a(r,d)}(s!==null||l!==null)&&(t.selection.range.isReverse()?t.selection.setSelection(l!=null?l:r,s!=null?s:o):t.selection.setSelection(s!=null?s:o,l!=null?l:r))}}}destroy(){this.editor.removeListener("docChanged",this.handleDocChanged)}}function b6(n){n.addCustom("table-doc-change-handler",t=>new OP(t))}const br=M("create-content");function A6(n,t,e){var p;const o=new Sf(e),r=e.rows,i=e.cols;g(br,r>=1,`invalid rows: ${r}`),g(br,i>=1,`invalid cols: ${i}`),g(br,e.children,"no table children");const s=k("table",[],null),l=(p=e.colsWidth)!=null?p:new Array(e.cols).fill(0),a=k("colgroup",[],s);for(let C=0;C<o.colCount;C++){const v=k("col",[],a);l[C]&&(v.style.width=`${l[C]}px`)}const d=k("tbody",[],s);let h=0;for(let C=0;C<r;C++){const v=k("tr",[],d);for(let B=0;B<i;B++){const x=o.getCell({col:B,row:C});if(x.virtual)g(br,x.colSpan>1||x.rowSpan>1,"virtual cell should have colSpan or rowSpan");else{const I=e.children[h],_=k("td",[],v);x.colSpan>1&&(_.colSpan=x.colSpan),x.rowSpan>1&&(_.rowSpan=x.rowSpan);const D=e[Au(I)];D&&V(_,D),B===0&&e.hasColTitle&&V(_,Jw.COL_TITLE_ITEM),n.createChildContainer(t,_,I),h+=1}}}return g(br,h===e.children.length,"container count mismatch"),e.noBorder&&V(s,"no-border"),e.chart&&V(s,"editor-table-chart"),e.isStripeStyle&&V(s,"stripe"),e.hasRowTitle&&V(s,"row-title"),e.hasColTitle&&V(s,"col-title"),s}function _P(n,t,e,o,r){g(br,r.type==="table","not table data"),g(br,at(e)===t[t.length-1].containerId,"invalid path");const i=r,s=Is(o,"div");try{const l=k("div",[],null);l.setAttribute("data-type","table-content");const a=A6(n,t,i);a.classList.add("drag-preview-element"),l.appendChild(a);const d=n.getComponentOptions("table");p4(n),y4(n),f6(n,"create"),b6(n),d!=null&&d.hideCellMenu||m6(n),$L(n,E0);const h=n.addCustom(pr(o),()=>TO());h.init({parentElement:s,childElement:l,safeRightSpace:50,safeLeftSpace:40,parentContainer:Qt(e)?n.scrollContainer:e,locatingContainer:Qt(e)?(d==null?void 0:d.locatingContainer)||n.parent:e,paddingLeft:Cc+bu,paddingTop:Cc+bu,paddingBottom:bu/2,paddingRight:bu/2,barFloatWindowBottom:d==null?void 0:d.barFloatWindowBottom,allowScrollBarFixed:d==null?void 0:d.allowScrollBarFixed,isSetScale:d==null?void 0:d.isSetScale});const p=C6(n);h.on("scroll",p.handleReset),h.on("resize",p.handleReset),setTimeout(()=>{sO(n,o)})}catch{const a=`invalid table data: ${JSON.stringify(i)}`;br.error(a);const d=k("div",["error"],s);d.innerText=a}return s}function FP(n,t,e){g(br,e.type==="table","not table data");const o=e,r=Mt(t);try{const i=$e(t),s=Ri(t),l=A6(n,s,o);l.classList.add("drag-preview-element"),i.insertAdjacentElement("afterend",l),i.remove();const a=n.getComponentOptions("table");p4(n),y4(n),f6(n,"update"),b6(n),a!=null&&a.hideCellMenu||m6(n),E0(n,t)}catch{const s=`invalid table data: ${JSON.stringify(o)}`;br.error(s);const l=k("div",["error"],r);l.innerText=s}}function PP(n,t){let e,o,r=!1;if([...t].every(C=>C==="|")?(o=t.length,e=Array(o).fill(""),r=!0):(e=tp(t,"|").split("|"),o=e.length),o<2)return null;const i=3,s=o,l=[];for(let C=0;C<3;C++)e.forEach(v=>{l.push(Zr(n.doc,C===0?v:""))});const a=Array(s).fill(T0),d=l[r?0:s],h=n.doc.getContainerBlocks(d)[0].id;return{blockData:{id:tt(),type:"table",rows:i,cols:s,children:l,colsWidth:a},focusBlockId:h}}function NP(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(Zr(n.doc));const i=Array(o).fill(T0),s=r[0],l=n.doc.getContainerBlocks(s)[0].id;return{blockData:{id:tt(),type:"table",rows:e,cols:o,children:r,colsWidth:i},focusBlockId:l}}const sC=M("get-selected-containers");function v6(n,t,e,o){g(sC,e.blockId===o.blockId,"only allow select in single table block"),g(sC,it(t)===e.blockId,"only allow select in single table block");const r=Tt.fromBlock(t),i=r.getCellByContainerId(e.childContainerId),s=r.getCellByContainerId(o.childContainerId);if(e.custom===void 0||o.custom===void 0)return r.getCells(i,s).map(I=>r.getCellContainer(I));const{fromCol:l,toCol:a,fromRow:d,toRow:h}=Uo(t,e,o),p=new Set,C=[];return r.sub({row:d,col:l},{row:h,col:a}).forEach(B=>{B.forEach(x=>{const I=r.getCellByContainerId(x.containerId);I.col<l||I.row<d||I.col+I.colSpan-1>a||I.row+I.rowSpan-1>h||p.has(x.containerId)||(p.add(x.containerId),C.push(I.container))})}),C}function $P(n,t,e){g(sC,t.blockId===e.blockId,"only allow select in single table block");const o=n.getBlockById(t.blockId);return v6(n,o,t,e)}const y6=M("table-selection-to-doc");function HP(n,t){const{start:e,end:o,block:r}=t,i=St(r);g(y6,i==="table",`invalid block type: ${i}`);const s=n.getBlockData(r);if(e.isSimple()&&o.isSimple())return Pi(n.editorBlocks,n.doc.toJSON(),s);g(y6,!e.isSimple()&&!o.isSimple(),"invalid block pos type");const l=Tt.fromBlock(r),{fromCol:a,toCol:d,fromRow:h,toRow:p}=Uo(r,e,o),C={},v=[],B=n.doc.toJSON();let x={};l.sub({row:h,col:a},{row:p,col:d}).forEach((K,ht)=>{K.forEach((bt,_t)=>{const Ht=bt.containerId;if(v.indexOf(Ht)!==-1)return;v.push(Ht);let oe;if(bt.virtual){const Ee=l.getCellByContainerId(bt.containerId),Rn=a+_t;let Ir=Ee.col+Ee.colSpan-1;Ir>d&&(Ir=d);const kn=Ir-Rn+1;kn>1&&(C[`${Ht}_colSpan`]=kn);const un=h+ht;let Tr=Ee.row+Ee.rowSpan-1;Tr>p&&(Tr=p);const ii=Tr-un+1;ii>1&&(C[`${Ht}_rowSpan`]=ii),oe=Qr()}else{if(oe=d1(n.editorBlocks,B,Ht),bt.col+bt.colSpan>d+1){const Ee=d-bt.col+1;Ee>1&&(C[`${Ht}_colSpan`]=Ee)}else bt.colSpan>1&&(C[`${Ht}_colSpan`]=bt.colSpan);if(bt.row+bt.rowSpan>p+1){const Ee=p-bt.row+1;Ee>1&&(C[`${Ht}_rowSpan`]=Ee)}else bt.rowSpan>1&&(C[`${Ht}_rowSpan`]=bt.rowSpan)}const{root:Le,...Jn}=oe.blocks;x={...x,...Jn,[Ht]:Le}})});const _=Bu($e(r)).slice(a,d+1);return{blocks:{root:[{id:tt(),type:i,children:v,colsWidth:_,rows:p-h+1,cols:d-a+1,...C}],...x},meta:{},comments:{}}}function jP(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 UP(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 zP(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 VP(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 WP(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,!jP(n,l)){l.top--,a=!0;continue}if(!UP(n,l)){l.left--,a=!0;continue}if(!zP(n,l)){l.bottom++,a=!0;continue}if(!VP(n,l)){l.right++,a=!0;continue}}while(a);return l}function qP(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),C=WP(i,{row:a,col:h},{row:d,col:p}),v=r.getCell({row:C.top,col:C.left}),B=r.getCell({row:C.bottom,col:C.right}),x=r.getCell({row:C.top,col:C.right}),I=r.getCell({row:C.bottom,col:C.left});let _,D;return s.row<=l.row?s.col<=l.col?(_=v,D=B):(_=x,D=I):s.col<l.col?(_=I,D=x):(_=B,D=v),console.log(`move ${_.col}, ${_.row}, -> ${D.col}, ${D.row}`),{anchor:me(t,_.containerId),focus:me(t,D.containerId)}}function k6(n,t,e){if(e.isSimple())return[$e(t).getBoundingClientRect()];const o=$e(t),r=o.getBoundingClientRect(),{fromCol:i,fromRow:s,toCol:l,toRow:a}=Uo(t,e.start,e.end),d=Bu(o),h=d.slice(0,i).reduce((x,I)=>x+I,0),p=h+d.slice(i,l+1).reduce((x,I)=>x+I,0),C=l6(o);let v=C.slice(0,s).reduce((x,I)=>x+I,0);const B=v+C.slice(s,a+1).reduce((x,I)=>x+I,0);if(s===0){const x=wP(n,t);v-=x}return[new DOMRect(r.left+h,r.top+v,p-h,B-v)]}M("table-size");const GP=40;function rm(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 QP(n,t,e){const o=Bp(n,e.container);return o!==void 0?o+rm(t):GP*e.colSpan-rm(t)}function ZP(n,t,e,o){let r=0;const i=e.colCount;for(let s=0;s<i;s++){const l=e.getCell({col:s,row:o});if(l.virtual)continue;let a=QP(n,t,l);const d=K5(l.container,{withPadding:!0});d&&d>a&&(a=d),r+=a+rm(t)}return r}function YP(n,t){const e=$e(t),o=Tt.fromTable(e);let r=0;for(let s=0;s<o.rowCount;s++)r=Math.max(r,ZP(n,e,o,s));const i=rm(e);return r+=i,r}const ei=M("table-creator");async function JP(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=NP(n,{cols:o,rows:r});if(!i)return null;const{blockData:s,focusBlockId:l}=i;return n.insertBlock(t.containerId,t.blockIndex,s,be(n,l,0))})}class KP{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 C,v;t.preventDefault(),t.stopPropagation();const e=t.target;g(ei,e instanceof HTMLElement,"invalid event target");const o=e.closest(".table-creator");g(ei,o,"no table creator");const r=o.querySelectorAll(".active");if(r.length===0)return;const s=r[r.length-1].id;g(ei,s,"no cell id");const l="table-creator-cell-";if(!s.startsWith(l))return;const d=s.substring(l.length).split("-");g(ei,d.length===2,"invalid cell id");const h=Number.parseInt(d[0],10)+1,p=Number.parseInt(d[1],10)+1;ei.debug(`${h}, ${p}`),this.colCount=p,this.rowCount=h,(C=this.closeable)==null||C.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&&rt(r,"active")}});m(this,"handleTableCreatorCellEnter",t=>{const e=t.target;g(ei,e instanceof HTMLElement,"invalid event target");const o=e.id,r="table-creator-cell-";g(ei,o.startsWith(r),"invalid cell id");const s=o.substring(r.length).split("-");g(ei,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),C=document.getElementById(p);g(ei,C,"no cell"),d<=l&&h<=a?V(C,"active"):rt(C,"active")}});this.element=this.createTableCreatorElement()}createTableCreatorElement(){const t=k("div",["table-creator"],null),e=(o,r,i)=>{const s=k("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=k("div",["table-creator-row"],t);for(let i=0;i<9;i++)e(r,o,i).addEventListener("mouseenter",this.handleTableCreatorCellEnter)}return t}}function XP(){return new KP}function tN(n){const t=/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g,e=n.match(t);return e?e.length:0}function w6(n){const t=tN(n);return n.length+t}function eN(n,t){const e=w6(n),o=t-e;return o>0?n+" ".repeat(o):n}function nN(n,t,e,o,r){const i=t,s=new Sf(i);if(o==="markdown"||o==="text"){const l=I=>e.blocks[I].map((H,W)=>o==="markdown"?e1(n,H,e,[...r,{containerId:I,blockIndex:W}]):Nh(n,H,e,[...r,{containerId:I,blockIndex:W}])),a=I=>l(I).join(" ").replace(/\n/g," ").trim(),d=new Map,h=new Map;for(let I=0;I<s.colCount;I++){let _=0;for(let D=0;D<s.rowCount;D++){const H=s.getCell({row:D,col:I});let W="";H.virtual||(W=a(H.containerId)),d.set(`${D},${I}`,W),_=Math.max(_,w6(W))}h.set(I,_)}const p=I=>{const _=d.get(`${I.row},${I.col}`)||"",D=h.get(I.col)||0;return eN(_,D)};if(o==="text"){const I=[];for(let _=0;_<s.colCount;_++){const D=p({row:0,col:_});I.push(D)}for(let _=1;_<s.rowCount;_++)for(let D=0;D<s.colCount;D++){const H=p({row:_,col:D});I.push(H)}return I.join(`
|
|
601
601
|
`)}const C=[];let v="|",B="|";for(let I=0;I<s.colCount;I++){const _=p({row:0,col:I});v+=` ${_} |`;const D="-".repeat((h.get(I)||0)+2);B+=`${D}|`}C.push(v),C.push(B);for(let I=1;I<s.rowCount;I++){let _="|";for(let D=0;D<s.colCount;D++){const H=p({row:I,col:D});_+=` ${H} |`}C.push(_)}return`${C.join(`
|
|
602
602
|
`)}
|
|
603
603
|
`}if(o==="html"){const l=d=>e.blocks[d].map((C,v)=>t1(n,C,e,[...r,{containerId:d,blockIndex:v}])).join(`
|
|
@@ -613,7 +613,7 @@ $$${r.mathjaxText}$$
|
|
|
613
613
|
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
|
|
614
614
|
<path fill-rule="evenodd" clip-rule="evenodd" d="M18.4388 7.11504H5.55388C5.24779 7.11504 5 6.86726 5 6.55388C5 6.24779 5.24779 6 5.55388 6H18.4388C18.7522 6 19 6.24779 19 6.55388C19 6.86726 18.7449 7.11504 18.4388 7.11504ZM18.4388 10.7225H5.55388C5.24779 10.7225 5 10.4748 5 10.1687C5 9.86257 5.24779 9.61478 5.55388 9.61478H18.4388C18.7522 9.61478 19 9.85528 19 10.1687C19 10.4748 18.7449 10.7225 18.4388 10.7225ZM18.4388 14.3373H5.55388C5.24779 14.3373 5 14.0895 5 13.7834C5 13.4701 5.24779 13.2223 5.55388 13.2223H18.4388C18.7522 13.2223 19 13.4701 19 13.7834C19 14.0895 18.7449 14.3373 18.4388 14.3373ZM12.8855 17.9448H5.55388C5.24779 17.9448 5 17.697 5 17.3909C5 17.0849 5.24779 16.8371 5.55388 16.8371H12.8855C13.1989 16.8371 13.4466 17.0849 13.4466 17.3909C13.4466 17.7043 13.1989 17.9448 12.8855 17.9448ZM21 14.7344V16.3013C21 17.486 20.4268 18.0593 19.2357 18.0593L17.5159 18.0593V18.8555C17.5159 19.2631 17.1019 19.4351 16.7771 19.1803L15.2866 18.0211C14.9045 17.7217 14.9045 17.3459 15.2866 17.0465L16.7771 15.8809C17.1019 15.6262 17.5159 15.8045 17.5159 16.2121V17.0083H19.1847C19.6943 17.0083 19.9554 16.7535 19.9554 16.2121V14.7344C19.9554 14.365 20.1465 14.1548 20.4777 14.1484C20.8153 14.1421 21 14.365 21 14.7344Z"/>
|
|
615
615
|
</svg>
|
|
616
|
-
`;function VN(n,t,e){const r={...n.getBlockData(t),language:e};n.updateBlockData(t,r),pn(n,t).forEach(s=>{fe(s).forEach(l=>{n.reloadBlock(l)})})}function WN(n,t,e){const r={...n.getBlockData(t),nowrap:e};n.updateBlockData(t,r)}const el=M("code-block-header"),qN=Object.entries(Dc).map(([n,t])=>({id:n,name:t.name,language:t}));function N6(n,t,e){g(el,Ar(t),"not a code block");const o=we(Mc(t));n.selection.selectBlock(o,0),e.focusToEditor&&n.focus()}function GN(n,t){if(t){const e=n,{editor:o,codeBlock:r}=e.custom;VN(o,r,t.id);const i=r.querySelector(".code-block-header .language-select .name-label");i.innerText=t.name,wN(o,t.id),o.focus()}}function QN(n,t,e){n.addCustom("code-header-language-select-dropdown",i=>{const s=new hR(qN,i.rootElement,{placeholder:L.t("code.search")});return s.onSelected=GN,s});const o=k("div",["language-select"],null);k("span",["name-label"],o,e);const r=k("span",["arrow-icon"],o);return r.innerHTML=jN,n.domEvents.addEventListener(o,"click",(i,s)=>{if(i.readonly)return;const a=s.target.closest(".language-select"),d=nt(a);g(el,d,"no parent block"),g(el,St(d)==="code","not a code block");const h=i.getBlockData(d),p=i.getCustom("code-header-language-select-dropdown");p.custom={codeBlock:d,editor:i},p.setSelectedId(h.language),p.show(a),N6(i,d,{focusToEditor:!1}),V(t,"editing-language"),p.onHide=()=>{rt(t,"editing-language")}}),o}function ZN(){return k("div",["code-header-spacer"],null)}function YN(n,t){const e=t.target,o=e.closest(".code-header-button");g(el,o,"no button");const r=nt(e);g(el,r,"no parent block");const i=o.getAttribute("data-id");if(g(el,St(r)==="code","not a code block"),i==="wrap"){const s=n.getBlockData(r);WN(n,r,!s.nowrap);return}if(i==="copy"){N6(n,r,{focusToEditor:!0}),Xh(n,r).then(()=>{const{onCodeCopyComplete:
|
|
616
|
+
`;function VN(n,t,e){const r={...n.getBlockData(t),language:e};n.updateBlockData(t,r),pn(n,t).forEach(s=>{fe(s).forEach(l=>{n.reloadBlock(l)})})}function WN(n,t,e){const r={...n.getBlockData(t),nowrap:e};n.updateBlockData(t,r)}const el=M("code-block-header"),qN=Object.entries(Dc).map(([n,t])=>({id:n,name:t.name,language:t}));function N6(n,t,e){g(el,Ar(t),"not a code block");const o=we(Mc(t));n.selection.selectBlock(o,0),e.focusToEditor&&n.focus()}function GN(n,t){if(t){const e=n,{editor:o,codeBlock:r}=e.custom;VN(o,r,t.id);const i=r.querySelector(".code-block-header .language-select .name-label");i.innerText=t.name,wN(o,t.id),o.focus()}}function QN(n,t,e){n.addCustom("code-header-language-select-dropdown",i=>{const s=new hR(qN,i.rootElement,{placeholder:L.t("code.search")});return s.onSelected=GN,s});const o=k("div",["language-select"],null);k("span",["name-label"],o,e);const r=k("span",["arrow-icon"],o);return r.innerHTML=jN,n.domEvents.addEventListener(o,"click",(i,s)=>{if(i.readonly)return;const a=s.target.closest(".language-select"),d=nt(a);g(el,d,"no parent block"),g(el,St(d)==="code","not a code block");const h=i.getBlockData(d),p=i.getCustom("code-header-language-select-dropdown");p.custom={codeBlock:d,editor:i},p.setSelectedId(h.language),p.show(a),N6(i,d,{focusToEditor:!1}),V(t,"editing-language"),p.onHide=()=>{rt(t,"editing-language")}}),o}function ZN(){return k("div",["code-header-spacer"],null)}function YN(n,t){const e=t.target,o=e.closest(".code-header-button");g(el,o,"no button");const r=nt(e);g(el,r,"no parent block");const i=o.getAttribute("data-id");if(g(el,St(r)==="code","not a code block"),i==="wrap"){const s=n.getBlockData(r);WN(n,r,!s.nowrap);return}if(i==="copy"){const s=ot(n.selection.focusedBlock);nt(s)!==r&&N6(n,r,{focusToEditor:!0}),Xh(n,r).then(()=>{const{onCodeCopyComplete:a}=n.getComponentOptions("code")||{};if(a){a();return}const d=o.getBoundingClientRect();fR(L.t("code.copySuccess"),{position:{x:d.x+d.width/2,y:d.bottom+30}})}).catch(a=>{el.error(a.message)});return}i==="caption"&&(xN(n,r),setTimeout(()=>{n.focus()}))}function gC(n,t,e,o){const r=k("button",["code-header-button"],null);if(r.setAttribute("data-id",t),o){const i=k("span",["button-icon"],r);i.innerHTML=o,e&&r.setAttribute(`data-editor-tooltip-${n.clientId}`,e)}else if(e){const i=k("span",["button-label"],r);i.innerHTML=e}return n.domEvents.addEventListener(r,"click",YN),r}function JN(n,t,e){const o=te(t),r=k("div",["code-block-header"],o),i=e.language&&(Dc[e.language]||Dc[M6(e.language.toLocaleLowerCase())])||Dc.plain;r.appendChild(QN(n,t,i.name)),r.appendChild(ZN()),r.appendChild(gC(n,"wrap",L.t("code.wrap"),zN));const s=r.appendChild(gC(n,"copy",L.t("code.copy"),UN));mC()||(V(s,"disabled"),s.setAttribute("data-editor-tooltip-maxwidth","800"),s.setAttribute(`data-editor-tooltip-${n.clientId}`,L.t("copyCutProperty.unsafeEnvTips",{shortCut:so("CtrlOrCmd+C"),operation:L.t("copyCutProperty.copy")}))),r.appendChild(gC(n,"caption",L.t("code.caption"),null))}function KN(n,t){!t.target||setTimeout(()=>{n.selection.caret.update()})}function XN(n,t,e,o){hC.init(n);const r=o.children,i=Is(e,"div");i.setAttribute("data-language",o.language||"text"),S6(n,e,o);const s=k("div",["editor-code-root"],i),l=k("div",["code-text-root"],s),a=n.createChildContainer(t,l,r[0]);if(r.length===2){const d=k("div",["code-caption-root"],s);n.createChildContainer(t,d,r[1])}return n.domEvents.addEventListener(a,"scroll",KN),JN(n,e,o),i}async function t$(n){const t={id:tt(),type:"text",text:[]},e=tt();n.doc.localInsertChildContainers([{containerId:e,blocks:[t]}]);const o=await L6(n);return{blockData:{id:tt(),type:"code",language:o,children:[e]},focusBlockId:t.id}}const vr=M("code-block");function e$(n,t,e,o,r){DN(n),LN(n),g(vr,r.type==="code","invalid block data type");const i=r;return g(vr,i.children,"invalid block data children"),g(vr,i.children.length===1||i.children.length===2,"invalid block data children length"),XN(n,t,o,i)}function n$(n){return 1}function o$(n,t,e,o){const r=document.elementsFromPoint(e,o)[0];if(!r||!t.contains(r)||!n.contains(t)||!jr(r))return null;const i=im(t);if(!jr(r))return null;const s=r;if(i.indexOf(s)===-1||To(s)>1)return null;const l=me(t,at(s));return new sr(n,{anchor:l,focus:l})}function r$(n,t,e,o){return null}function i$(n,t){return n.getBoundingClientRect()}function s$(n,t,e,o){if(e.isSimple()){g(vr,o.isSimple(),"from is simple position but to is not simple position"),vr.debug("full select list"),V(t,"full-selected");return}g(vr,!o.isSimple(),"from is complex position but end is simple position");const r=e,i=o;g(vr,r.blockId===i.blockId,"only allow update one table selection"),im(t).forEach(l=>{const a=at(l);(a===r.childContainerId||a===i.childContainerId)&&V(l,"selected")})}function l$(n){n.rootContainer.querySelectorAll('[data-type="editor-block"][data-block-type="code"]').forEach(t=>{rt(t,"full-selected"),t.querySelectorAll("div[data-type=editor-container].child.selected").forEach(e=>{rt(e,"selected")})})}function c$(n,t){return im(t)}function a$(n,t,e,o,r){if(o==="ArrowDown"||o==="ArrowRight"){if(e===Mc(t))return tl(t)}else if(e===tl(t))return Mc(t);return null}function u$(n,t,e,o){const r=im(t),i=r.map(at),s=i.indexOf(e.childContainerId),l=i.indexOf(o.childContainerId);g(vr,s!==-1,"invalid start pos"),g(vr,l!==-1,"invalid end pos");const a=[r[s]];return s!==l&&a.push(r[l]),a}function d$(n,t,e){g(vr,Ar(t),"invalid block type"),S6(n,t,e)}async function h$(n,t){const e=await t$(n);if(!e)return null;const{blockData:o,focusBlockId:r}=e;return n.focus(),n.insertBlock(t.containerId,t.blockIndex,o,be(n,r,0))}function f$(n){return{name:"CodeBlock",insertBlockCommandItems:[{id:"insert-code",name:L.t("code.title"),icon:lw,order:300,group:"common",subText:An("insert-code")}],handleInsertEmptyBlock:h$}}function m$(){return{abstract:`${L.t("code.abstract")}`}}function g$(n,t,e,o){const r=t,i=a=>{const d=[];return e.blocks[a].forEach(p=>{var C;d.push(se((C=p.text)!=null?C:[]))}),d.join(`
|
|
617
617
|
`)},s=i(r.children[0]),l=r.children[1]?i(r.children[1]):"";return o==="text"?`${s}
|
|
618
618
|
${l}`:o==="markdown"?`\`\`\`${r.language}
|
|
619
619
|
${s}
|