@usememos/editor 26.10.30 → 26.11.0

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
@@ -116,7 +116,7 @@ ${this.message}`:"";t===this.reported&&!(e&&this.itemsChanged)||(this.reported=t
116
116
  `);return{blockId:o.id,offset:n>0?n:t.length}}var Dh=o=>typeof o?.then=="function";function ya(o){return(e,t,n,i)=>{let r=t.ownerDocument.createElement("template");r.innerHTML=e;let s=a=>{if(!a)return!1;t.replaceChildren(a)},l=o(r.content,{editor:i.editor,kind:n});return Dh(l)?l.then(s):s(l)}}function Pr(o,e){let t=o.ownerDocument,n=t.defaultView,i=e.top,r=e.bottom,s=e.left,l=e.right;for(let c=o;c&&c!==t.body&&c!==t.documentElement;c=c.parentElement){let h=n?.getComputedStyle(c),f=c.scrollHeight>c.clientHeight&&/auto|scroll|overlay/.test(h?.overflowY??""),p=c.scrollWidth>c.clientWidth&&/auto|scroll|overlay/.test(h?.overflowX??"");if(!f&&!p)continue;let m=c.getBoundingClientRect(),y=m.top+c.clientTop,g=m.left+c.clientLeft,x=f?Ko(i,r,y,y+c.clientHeight):0,b=p?Ko(s,l,g,g+c.clientWidth):0;if(!x&&!b)continue;let w=c.scrollTop,k=c.scrollLeft;c.scrollTop+=x,c.scrollLeft+=b,i-=c.scrollTop-w,r-=c.scrollTop-w,s-=c.scrollLeft-k,l-=c.scrollLeft-k}if(!n)return;let a=t.documentElement,d=Ko(i,r,0,a.clientHeight),u=Ko(s,l,0,a.clientWidth);(d||u)&&n.scrollBy(u,d)}function Ko(o,e,t,n){return o<t+8?o-t-8:e>n-8?Math.min(e-n+8,o-t-8):0}function ka(o){let e={};for(let t of o)for(let[n,i]of Object.entries(t??{}))i!==void 0&&(e[n]=typeof i=="object"?{...e[n],...i}:i);return e}var Oh={text:"--mbe-text",muted:"--mbe-muted",background:"--mbe-bg",accent:"--mbe-accent",link:"--mbe-link",codeBackground:"--mbe-code-bg",border:"--mbe-border",popupBackground:"--mbe-popup-bg",popupBorder:"--mbe-popup-border",hover:"--mbe-hover",danger:"--mbe-danger",highlight:"--mbe-highlight",calloutNote:"--mbe-callout-note",calloutTip:"--mbe-callout-tip",calloutImportant:"--mbe-callout-important",calloutWarning:"--mbe-callout-warning",calloutCaution:"--mbe-callout-caution"},An={font:"--mbe-font",mono:"--mbe-mono",sourceFont:"--mbe-source-font",fontSize:"--mbe-font-size",lineHeight:"--mbe-line-height",radius:"--mbe-radius",blockGap:"--mbe-block-gap"},va=[An.font,An.mono,An.fontSize,An.lineHeight];function $r(o){let e=new Map;if(!o)return e;for(let t of["light","dark"])for(let[n,i]of Object.entries(Oh)){let r=o[t]?.[n]??o.colors?.[n];r&&e.set(`${i}-${t}`,r)}for(let[t,n]of Object.entries(An)){let i=o[t];i!==void 0&&i!==""&&e.set(n,typeof i=="number"?`${i}px`:i)}return e}var xa=/^(?:[ \t]*>[ \t]?)*/,Ut=/[ \t]*(?:[-*+]|\d{1,9}[.)])(?=[ \t\n\r]|$)/y,Hh=/^(`{3,}|~{3,})/,Ph=/^\[[ \t\nxX]\](?=[ \t\n]|$)/;function wa(o,e){let t=he(o,e),n=pt(o),i=[],r=[],s=(g,x,b)=>{b>x&&i.push({from:x,to:b,kind:g})},l=g=>({from:n.starts[g-1]??o.length,to:n.ends[g-1]??o.length}),a=(g,x,b,w)=>{for(let k of bs(g,n,x,b))s(w,k.from,k.to)},d=(g,x)=>{for(let b=g;b<x;b++){let w=o[b];if(w===">")s("marker",b,b+1);else if(w==="-"||w==="*"||w==="+"||w>="0"&&w<="9"){Ut.lastIndex=b;let k=Ut.exec(o);k&&k.index===b&&(s("marker",b+k[0].length-k[0].trimStart().length,b+k[0].length),b+=k[0].length-1)}}},u=g=>{let x=xa.exec(o.slice(g.from,g.to))[0];d(g.from,g.from+x.length),Ut.lastIndex=g.from+x.length;let b=g.from+x.length;for(let w=Ut.exec(o);w&&w.index===b;w=Ut.exec(o))s("marker",b+w[0].length-w[0].trimStart().length,b+w[0].length),b+=w[0].length,Ut.lastIndex=b;return b},c=g=>{for(let x of g.lines){let b=n.starts[x.line-1]??o.length;d(b,b+x.offset)}},h=(g,x)=>{for(let b=g;b<x;b++)o[b]==="\\"&&b+1<x?(o[b+1]==="|"&&s("escape",b,b+2),b++):o[b]==="|"&&s("marker",b,b+1)},f=(g,x,b)=>{g&&(c(g),b&&x.length>0&&a(g,0,Math.max(...x.map(w=>w.pos?.to??0)),b),p(g,x))},p=(g,x)=>{let b=w=>{for(let k of w){let{pos:S}=k;if(S)switch(k.type){case"text":if(k.pieces){let v=S.from;for(let T of k.pieces)a(g,v,T.from,"escape"),v=T.to;a(g,v,S.to,"escape")}break;case"hardBreak":{let v=new xe(g,n).source(S.from);o[v]==="\\"&&s("marker",v,v+1);break}case"code":{for(let v of k.syntax??[])a(g,v.from,v.to,"marker");k.content&&a(g,k.content.from,k.content.to,"code");break}case"html":a(g,S.from,S.to,"html");break;case"token":a(g,S.from,S.to,"token");break;case"emphasis":case"strong":case"strike":{let v=k.syntax?.find(E=>E.kind==="open"),T=k.syntax?.find(E=>E.kind==="close");for(let E of k.syntax??[])a(g,E.from,E.to,"marker");a(g,v?.to??S.from,T?.from??S.to,k.type==="emphasis"?"em":k.type),b(k.children);break}case"link":case"image":{let v=k.syntax?.find(A=>A.kind==="open"),T=k.syntax?.find(A=>A.kind==="close"),E=k.syntax?.find(A=>A.kind==="dest");for(let A of k.syntax??[])A.kind==="dest"?a(g,A.from,A.to,"url"):A.kind==="tail"&&E&&E.from>=A.from&&E.to<=A.to?(a(g,A.from,E.from,"marker"),a(g,E.to,A.to,"marker")):A.kind!=="title"&&a(g,A.from,A.to,"marker");v&&T&&!(E&&E.from===v.to&&E.to===T.from)&&a(g,v.to,T.from,"link"),b(k.children);break}default:break}}};b(x)},m=g=>{switch(g.type){case"paragraph":case"heading":case"htmlBlock":case"raw":return g.source?.lines[0]?.line??0;case"codeBlock":case"thematicBreak":case"table":return g.lines?.start??0;case"blockQuote":case"listItem":return g.children[0]?m(g.children[0]):0;case"list":return g.items[0]?m(g.items[0]):0}},y=g=>{switch(g.type){case"paragraph":f(g.source,g.children);break;case"heading":{f(g.source,g.children,"heading");let x=g.source?.lines[0];if(!x)break;if(g.setext){let b=l(x.line+(g.source?.lines.length??1)),w=xa.exec(o.slice(b.from,b.to))[0];d(b.from,b.from+w.length),s("marker",b.from+w.length,b.to)}else{let b=l(x.line),w=o.slice(b.from,b.from+x.offset),k=/#{1,6}[ \t]*$/.exec(w);k&&s("marker",b.from+k.index,b.from+k.index+k[0].trimEnd().length);let S=o.slice(b.from+x.offset,b.to),v=/(?:^|[ \t]+)(#+)[ \t]*$/.exec(S);v&&s("marker",b.from+x.offset+v.index+v[0].indexOf("#"),b.from+x.offset+v.index+v[0].trimEnd().length)}break}case"thematicBreak":if(g.lines){let x=l(g.lines.start);s("marker",u(x),x.to)}break;case"blockQuote":g.children.forEach(y);break;case"list":for(let x of g.items){if(x.lines&&m(x)!==x.lines.start&&u(l(x.lines.start)),x.task){let b=x.children[0],k=(b?.type==="paragraph"?b.source:void 0)?.lines[0];if(k){let S=(n.starts[k.line-1]??0)+k.offset;Ph.test(o.slice(S,n.ends[k.line-1]))&&s("marker",S,S+3)}}x.children.forEach(y)}break;case"codeBlock":{if(!g.source||!g.lines)break;let x=g.source.lines;if(g.fenced){let b=l(g.lines.start),w=u(b),k=o.slice(w,b.to),S=k.trimStart(),v=w+k.length-S.length,T=Hh.exec(S);T&&(s("marker",v,v+T[1].length),s("lang",v+T[1].length,b.to));let E=x[x.length-1]?.line??g.lines.start;if(g.lines.end>E){let A=l(g.lines.end);s("marker",u(A),A.to)}}if(c(g.source),x.length>0){let b=g.value.replace(/\n$/,"").length;a(g.source,0,b,"code");let w=new xe(g.source,n);r.push({from:w.source(0),to:w.source(b),language:Bi(g.info)})}break}case"htmlBlock":case"raw":g.source&&(c(g.source),a(g.source,0,g.value.length,g.type==="raw"?"token":"html"));break;case"table":if(g.lines){for(let x=g.lines.start;x<=g.lines.end;x++){let b=l(x),w=u(b);x===g.lines.start+1?s("marker",w,b.to):h(w,b.to)}g.sources?.forEach((x,b)=>x.forEach((w,k)=>p(w,g.rows[b]?.[k]??[])))}break}};return t.children.forEach(y),i.sort((g,x)=>g.from-x.from||x.to-g.to),{ranges:i,code:r}}var Sa={marker:"mbe-src-marker",heading:"mbe-src-heading",em:"mbe-src-em",strong:"mbe-src-strong",strike:"mbe-src-strike",code:"mbe-src-code",link:"mbe-src-link",url:"mbe-src-url",html:"mbe-src-html",token:"mbe-src-token",escape:"mbe-src-escape",lang:"mbe-src-lang"},$h=new Set(["marker","code","url","html","token","escape","lang"]),Ta=2e4,Ea=1e3,Fh=80;function qh(o,e,t,n){let i=n.highlight?_h(t,n.classes):[];if(n.decorators.length>0){let r=Pn(o,La(e,t));for(let s of n.decorators)i.push(...s(r))}if(n.codeDecorators.length>0)for(let r of t.code){let s={block:o,text:e.slice(r.from,r.to),language:r.language};for(let l of n.codeDecorators.flatMap(a=>a(s))){let a=r.from+Math.max(0,l.from),d=r.from+Math.min(r.to-r.from,l.to);d>a&&i.push({...l,from:a,to:d})}}return i}var Vo=class{constructor(e,t,n){this.options=e;this.config=t;this.onReady=n}last=null;markupFor=null;spansFor=null;pending=null;markup(e){return this.markupFor?.text!==e&&(this.markupFor={text:e,markup:wa(e,this.options)}),this.markupFor.markup}spans(e){let t=this.markupFor?.text===e?this.markupFor.markup:null;if(this.spansFor?.text===e&&(!t||this.spansFor.markup===t))return this.spansFor.spans;let n=t;if(!n&&this.markupFor&&e.length>Ta){let r=Ma(this.markupFor.markup.ranges,this.markupFor.text,e);r&&(n={ranges:r,code:this.markupFor.markup.code})}n??=this.markup(e);let i=La(e,n);return this.spansFor={text:e,markup:n,spans:i},i}decorations(e){let t=I(e.content),n=this.last;if(n&&n.text===t)return n.decorations;if(n&&t.length>Ta){let i=Ma(n.decorations,n.text,t);if(i)return this.last={text:t,decorations:i},this.schedule(e),i}return this.read(e,t)}reset(){this.last=null}destroy(){this.pending!==null&&clearTimeout(this.pending),this.pending=null}read(e,t){this.destroy();let n=qh(e,t,this.markup(t),this.config());return this.last={text:t,decorations:n},n}schedule(e){this.destroy(),this.pending=setTimeout(()=>{this.pending=null;let t=this.last;if(!t)return;let n=this.read(e,t.text);$n(t.decorations,n)||this.onReady()},Fh)}};function Ma(o,e,t){let{from:n,toBefore:i,toAfter:r}=dr(e,t);if(i-n>Ea||r-n>Ea)return null;let s=t.length-e.length,l=[];for(let a of o){let d=a.from<n?a.from:a.from>=i?a.from+s:n,u=a.to<=n?a.to:a.to>=i?a.to+s:n;u>d&&l.push(d===a.from&&u===a.to?a:{...a,from:d,to:u})}return l}function _h(o,e){return o.ranges.map(t=>{let n=e?.[t.kind];return{from:t.from,to:t.to,class:n?`${Sa[t.kind]} ${n}`:Sa[t.kind]}})}var Ca=["code"],Ia=[];function La(o,e){let t=[],n=(s,l,a)=>{l>s&&t.push({text:o.slice(s,l),marks:a})},i=0,r=0;for(let s of e.ranges)$h.has(s.kind)&&(s.from>r&&(n(i,r,Ca),n(r,s.from,Ia),i=s.from),r=Math.max(r,s.to));return n(i,r,Ca),n(r,o.length,Ia),t}var Pa=["text","heading1","heading2","heading3","heading4","bulletList","numberedList","todoList","quote","callout","details","code","table","divider"],Kh=[{id:"text",aliases:["paragraph","plain"],spec:{type:"paragraph"}},{id:"heading1",aliases:["h1","title"],spec:{type:"heading",level:1}},{id:"heading2",aliases:["h2","subtitle"],spec:{type:"heading",level:2}},{id:"heading3",aliases:["h3"],spec:{type:"heading",level:3}},{id:"heading4",aliases:["h4"],spec:{type:"heading",level:4}},{id:"bulletList",aliases:["ul","unordered","bullet"],spec:{type:"listItem",listType:"bullet"}},{id:"numberedList",aliases:["ol","ordered"],spec:{type:"listItem",listType:"ordered"}},{id:"todoList",aliases:["task","checkbox","checklist"],spec:{type:"listItem",listType:"task"}},{id:"quote",aliases:["blockquote","citation"],spec:{type:"quote"}},{id:"callout",aliases:["alert","admonition","note","tip","important","warning","caution"],spec:{type:"quote",callout:"note"}},{id:"details",aliases:["toggle","collapse","collapsible","summary","spoiler","fold"],spec:{type:"details"}},{id:"code",aliases:["pre","snippet","fence"],spec:{type:"code"}},{id:"table",aliases:["grid"],spec:{type:"table"}},{id:"divider",aliases:["hr","separator","line","rule"],spec:{type:"divider"}}],Vh=[{id:"addRowAbove",action:{kind:"addRowAbove"}},{id:"addRowBelow",action:{kind:"addRowBelow"}},{id:"addColumnLeft",action:{kind:"addColumnLeft"}},{id:"addColumnRight",action:{kind:"addColumnRight"}},{id:"deleteRow",action:{kind:"deleteRow"}},{id:"deleteColumn",action:{kind:"deleteColumn"}}],Uh=[{id:"alignLeft",align:"left",image:"imageAlignLeft"},{id:"alignCenter",align:"center",image:"imageAlignCenter"},{id:"alignRight",align:"right",image:"imageAlignRight"}],zh=["/","\uFF0F"],Ba=".mbe-widget, .mbe-block-after",Aa=/^(Arrow(Up|Down|Left|Right)|Home|End|PageUp|PageDown)$/,Na=new Set(["insertCompositionText","deleteCompositionText","insertFromComposition","deleteByComposition"]),Fr=class{root;labels;commands;suggestion;current;source;markdown;history=new oo(()=>this.source);modeValue="rich";pendingMode=null;renderer;composing=!1;composition=null;compositionEndedAt=0;shortcut=null;unsettled=new Set;settleFrame=null;readOnly;wasReadOnly=!1;taskToggle;smartLists;sourceHighlighting;sourceHighlighter;options;extensions;bindings;runtime;classesKey="{}";tokenNames=[];listeners=new Map;cleanup=[];widgets=[];changeFrame=null;plainPasteNext=!1;destroyed=!1;focused=!1;pointerDown=!1;toolbarClosedFor=null;typing=0;caretKey=null;suggestions;blockMenu;toolbar;imageToolbar;inputPopover;blockHandle;collapsed=new Set;linkCard;resizeHandles;selectedImageEl=null;hintEl=null;blockSel=null;selectedEls=[];headingIdsFor=null;redecoratePending=!1;viewFrame=0;constructor(e){let t=e.element;this.root=t,this.options=e,this.runtime={},this.labels={...Mi,...e.labels},this.readOnly=e.editable===!1,this.taskToggle=e.taskToggle===!0,this.smartLists=e.smartLists!==!1,this.sourceHighlighting=e.sourceHighlighting!==!1;let n=e.extensions??[];this.extensions=n.some(c=>c.name==="defaultKeymap")?n:[...n,rr()],this.bindings=this.extensions.flatMap(c=>Object.entries(c.keymap??{}).map(([h,f])=>Wl(h,f,ie)));let i=n.flatMap(c=>c.markdown?[c.markdown]:[]);this.markdown=Ze({...e.markdown,syntax:[...e.markdown?.syntax??[],...i]});let r=Le(e.content??"",this.markdown);this.source=r.source,this.current=Hn(r.doc),this.renderer=new Ho(t,this.labels),this.renderer.collapsed=this.collapsed,this.collapseClosedSections(this.current.doc),this.renderer.widgetsAfter=c=>{if(this.widgets.length===0)return;let h=this.widgets.filter(f=>f.blockId===c).map(f=>f.element);return h.length?h:void 0};let s=[["markdown",Nr]];e.sanitizeHtml&&s.push(["html",ya(e.sanitizeHtml)]),this.renderer.views=new Map([...s,...this.extensions.flatMap(c=>Object.entries(c.views??{}).filter(([h])=>h!=="html"))]),this.renderer.viewContext={editor:this},this.renderer.blockViews=this.extensions.flatMap(c=>c.blockView?[{name:c.name,view:c.blockView}]:[]),this.renderer.markdown=this.markdown,this.renderer.onViewSettled=c=>this.viewsSettled(c);let l=this.extensions.flatMap(c=>c.codeDecorations?[c.codeDecorations]:[]);l.length>0&&(this.renderer.decorateCode=c=>{let h={block:c,text:I(c.content),language:c.language};return l.flatMap(f=>f(h))});let a=this.extensions.flatMap(c=>c.decorations?[c.decorations]:[]);a.length>0&&(this.renderer.decorate=(c,h,f)=>{let p=Pn(c,h,f);return a.flatMap(m=>m(p))}),this.sourceHighlighter=new Vo(this.markdown,()=>({highlight:this.sourceHighlighting,classes:this.renderer.classes.source,decorators:a,codeDecorators:l}),()=>this.refreshSource()),this.renderer.decorateSource=c=>this.sourceHighlighter.decorations(c),this.commands=this.createCommands(),t.classList.add("mbe-root"),t.setAttribute("role","textbox"),t.setAttribute("aria-multiline","true"),t.spellcheck=!0,t.translate=!1,t.style.setProperty("--mbe-slash-hint",JSON.stringify(this.labels.slashHint)),this.applyRuntime({placeholder:e.placeholder,attributes:e.attributes}),this.runtime={...this.runtime,resolveUrl:e.resolveUrl,onLinkClick:e.onLinkClick},this.renderer.resolveUrl=e.resolveUrl??Ln,this.renderer.referrerPolicy=e.referrerPolicy,this.renderer.codeCopy=e.codeCopy!==!1,this.renderer.icon=c=>X(t.ownerDocument,this.icon(c)),this.applyTheme(e.theme),ir(t,e.popupContainer);let d=this.extensions.flatMap(c=>c.suggestion?[c.suggestion]:[]);e.slashMenu!==!1&&d.push(this.slashSuggestion()),this.suggestions=new Co({editor:this,root:t,syncActiveDescendant:()=>this.syncActiveDescendant(),refresh:()=>this.updateUi(),endComposition:()=>this.endComposition(),changed:c=>this.emit("suggestionChange",{editor:this,state:c})},d);let u=this.suggestions;this.suggestion={get state(){return u.state},open:c=>!this.destroyed&&(this.refreshSelection(),u.open(c)),close:()=>u.dismiss(),move:c=>u.move(c),accept:c=>!this.destroyed&&u.accept(c)},this.blockMenu=new Xe(t,"mbe-block-menu","menu"),this.blockMenu.onPicked=()=>this.blockMenu.hide(),this.blockMenu.onHighlight=()=>this.syncActiveDescendant(),this.blockMenu.checkIcon=this.icon("selected"),this.blockMenu.submenuIcon=this.icon("chevronRight"),this.inputPopover=new Lo(this),this.toolbar=e.toolbar===!1?null:new Io(this,typeof e.toolbar=="object"?e.toolbar.items:void 0),this.toolbar&&(this.toolbar.onMenuChange=()=>this.syncActiveDescendant()),this.imageToolbar=e.toolbar===!1?null:new Ao(this,{align:(c,h)=>this.updateImageAt(c.pos,{align:h==="left"?null:h}),altText:c=>this.editAltText(c.pos,c.image.alt),resetSize:c=>this.updateImageAt(c.pos,{width:null}),remove:c=>this.deleteImageAt(c.pos)}),this.blockHandle=new qo(this),this.linkCard=e.linkCard===!1?null:new _o(this,{open:(c,h)=>this.openHref(c.el.getAttribute("href"),h),edit:c=>this.editLink(c),remove:c=>this.removeLink(c),targetOf:c=>this.linkTargetOf(c)}),this.resizeHandles=new Bo(this),this.renderer.onImageError=()=>{this.destroyed||(this.composing||this.syncDomSelection(),this.updateUi())},this.listen(t,"beforeinput",this.typed(c=>this.onBeforeInput(c))),this.listen(t,"input",this.typed(c=>this.onInput(c))),this.listen(t,"compositionstart",c=>this.onCompositionStart(c)),this.listen(t,"compositionend",this.typed(c=>this.onCompositionEnd(c))),this.listen(t,"keydown",this.typed(c=>this.onKeyDown(c))),this.listen(t,"copy",c=>this.onCopy(c,!1)),this.listen(t,"cut",this.typed(c=>this.onCopy(c,!0))),this.listen(t,"paste",this.typed(c=>this.onPaste(c))),this.listen(t,"dragstart",c=>c.preventDefault()),this.listen(t,"dragover",c=>{this.readOnly||c.preventDefault()}),this.listen(t,"drop",this.typed(c=>this.onDrop(c))),this.listen(t,"mousedown",c=>this.onMouseDown(c)),this.listen(t,"click",c=>this.onClick(c)),this.listen(t,"change",c=>this.onControlChange(c)),this.listen(t,"focusin",c=>this.onFocusIn(c)),this.listen(t,"focusout",c=>this.onFocusOut(c)),this.listen(t.ownerDocument,"selectionchange",()=>this.onSelectionChange()),this.listen(t.ownerDocument,"mouseup",()=>this.onMouseUp()),this.listen(t.ownerDocument,"scroll",()=>this.onScroll(),!0),this.listen(t.ownerDocument,"pointerdown",c=>this.onDocumentPointerDown(c),!0),e.mode==="source"&&this.enterSource(),this.paint(!0,!0),this.afterRender();for(let c of this.extensions){let h=c.onCreate?.({editor:this});typeof h=="function"&&this.cleanup.push(h)}e.autofocus&&this.commands.focus(e.autofocus==="end"?"end":"start")}getMarkdown(){return this.modeValue==="source"?K(this.current.doc):Pt(this.current.doc,{...this.markdown,source:this.source})}setMarkdown(e,t={}){if(this.destroyed)return;if(t.history==="keep"?this.history.record(this.current,"other"):this.history.clear(),this.modeValue==="source"){this.suggestions.reset(),this.current=Fe(e,0);for(let r of this.widgets)r.offset=Math.min(r.offset,e.length);this.paint(!0,!0),this.afterRender(),this.emit("selectionChange",{editor:this});return}let n=Le(e,this.markdown);this.source=n.source,this.blockSel=null,this.suggestions.reset();let i=Hn(n.doc);this.collapsed.clear(),this.collapseClosedSections(i.doc),this.relocateWidgets(this.current.doc,i.doc,!0),this.current=i,this.paint(!0,!0),this.afterRender(),this.emit("selectionChange",{editor:this})}get isEmpty(){return this.modeValue==="source"?K(this.current.doc)==="":this.current.doc.blocks.every(e=>e.type==="paragraph"&&B(e.content)===0)}get state(){return this.current}get isComposing(){return this.composing}get mode(){return this.pendingMode??this.modeValue}get isEditable(){return!this.readOnly&&!this.destroyed}get isDestroyed(){return this.destroyed}isActive(e,t){if(this.modeValue==="source")return!1;let n=this.current;switch(e){case"bold":case"italic":case"strike":case"code":return Vn(n,e);case"link":return Qe(n)!==null;case"image":{let s=De(n);if(!s||!t)return s!==null;let l={...s.image,block:ke(n)!==null};return Object.entries(t).every(([a,d])=>l[a]===d)}}let i=N(n.doc,n.selection.focus.blockId);if(Da(i)!==e&&!(e==="blockquote"&&M(i)))return!1;if(!t)return!0;let r=this.getAttributes(e);return Object.entries(t).every(([s,l])=>r[s]===l)}getAttributes(e){if(this.modeValue==="source")return{};let t=this.current;if(e==="link"){let r=Qe(t);return r?{href:r.href}:{}}if(e==="image"){let r=De(t);return r?{...r.image,block:ke(t)!==null}:{}}let n=N(t.doc,t.selection.focus.blockId),i=M(n);if(e==="blockquote"&&i)return i==="quote"?{}:{callout:i};if(Da(n)!==e)return{};switch(n.type){case"heading":return{level:n.level};case"code":return{language:n.language};case"listItem":return n.listType==="task"?{checked:n.checked,indent:n.indent}:{indent:n.indent};case"raw":return{syntax:n.syntax};case"quote":return n.callout?{callout:n.callout}:{};case"details":return{open:n.open,collapsed:this.collapsed.has(n.id)};default:return{}}}getSelection(){return this.current.selection}setSelection(e){if(this.destroyed)return!1;let t=jh(e)?te(this.current.doc,e):Gh(this.current.doc,e);return t?(this.dropBlockSelection(),this.current={...this.current,selection:t,storedMarks:null},this.history.breakGroup(),this.refreshRevealed(),this.syncDomSelection(),this.updateUi(),this.emit("selectionChange",{editor:this}),!0):!1}selectionToJSON(){let e=this.current.doc,t=n=>{let i=L(e,n.blockId);return n.cell?{block:i,offset:n.offset,cell:{row:n.cell.row,col:n.cell.col}}:{block:i,offset:n.offset}};return{anchor:t(this.current.selection.anchor),focus:t(this.current.selection.focus)}}hasFocus(){let e=this.root.ownerDocument.activeElement;return!!e&&this.root.contains(e)&&!(e instanceof HTMLInputElement)&&!e.closest(Ba)}addWidget(e){if(this.destroyed){let l=new kt(this.root.ownerDocument.createElement("div"),"",()=>{},()=>{});return l.remove(),l}let t=this.current.doc.blocks,n=e.at==="end"?P(t[t.length-1]):e.at,i=te(this.current.doc,{anchor:n,focus:n}).focus.blockId,r=this.root.ownerDocument.createElement("div");r.className="mbe-widget",r.contentEditable="false";let s=new kt(r,i,e.render,l=>{this.widgets=this.widgets.filter(a=>a!==l)});return this.modeValue==="source"&&(s.offset=e.at==="end"?K(this.current.doc).length:n.offset),this.widgets.push(s),this.paint(),s}relocateWidgets(e,t,n){if(this.widgets.length===0)return;let i=new Set(t.blocks.map(r=>r.id));for(let r of this.widgets){if(i.has(r.blockId))continue;let s=e.blocks.findIndex(a=>a.id===r.blockId),l;if(n)l=t.blocks[Math.max(0,Math.min(s,t.blocks.length-1))].id;else{for(let a=s-1;a>=0&&!l;a--)i.has(e.blocks[a].id)&&(l=e.blocks[a].id);for(let a=s+1;a<e.blocks.length&&!l&&s>=0;a++)i.has(e.blocks[a].id)&&(l=e.blocks[a].id)}r.blockId=l??t.blocks[0].id}}focus(){if(this.destroyed)return;let e=this.current.selection.focus,t=this.renderer.elementFor(e.blockId);((e.cell&&t?se(t,e.cell):this.root)??this.root).focus({preventScroll:!0}),this.syncDomSelection(!0)}blur(){this.hasFocus()&&this.root.ownerDocument.activeElement?.blur()}setOptions(e){if(this.destroyed)return;e.extensions&&this.suggestions.setConfigs(e.extensions.flatMap(n=>n.suggestion?[n.suggestion]:[]));let t=e.taskToggle!==void 0&&e.taskToggle!==this.taskToggle;t&&(this.taskToggle=e.taskToggle===!0),e.editable!==void 0&&e.editable===this.readOnly?(this.readOnly=!e.editable,this.renderer.views?.has("footnote")?this.paint():this.refreshRevealed(),this.applyReadOnly(),this.hideUi()):t&&this.applyReadOnly(),this.applyRuntime(e),e.mode!==void 0&&this.setMode(e.mode)}setMode(e){if(e!=="rich"&&e!=="source")return;if(this.composing||this.composition){this.pendingMode=e===this.modeValue?null:e;return}if(this.pendingMode=null,e===this.modeValue)return;let t=this.hasFocus(),n=this.caretRect()?.top;this.blockSel=null,this.shortcut=null,this.suggestions.reset(),this.hideUi(),this.closeBlockMenu(),this.history.breakGroup(),e==="source"?this.enterSource():this.leaveSource(),this.paint(!0,!1,t),this.afterRender();let i=this.caretRect()?.top;n!==void 0&&i!==void 0&&Math.abs(i-n)>1&&Xh(this.root,i-n),this.emit("selectionChange",{editor:this})}enterSource(){let{doc:e,selection:t}=this.current,n=this.getMarkdown(),i=Le(n,this.markdown),r=hr(e,t,i);for(let s of this.widgets)s.offset=Ol(e,s.blockId,i),s.blockId=xn;this.collapsed.clear(),this.current=Fe(n,r.anchor,r.focus),this.modeValue="source",this.renderer.source=!0,this.root.classList.add("mbe-source-mode")}leaveSource(){let{anchor:e,focus:t}=this.current.selection,n=this.loadSource(K(this.current.doc));for(let r of this.widgets)r.blockId=wo(r.offset,n).blockId;let i=fr(e.offset,t.offset,n);this.current={doc:n.doc,selection:te(n.doc,i),storedMarks:null},this.modeValue="rich",this.renderer.source=!1,this.root.classList.remove("mbe-source-mode")}loadSource(e){let t=Le(e,this.markdown),n=Hn(t.doc).doc;return this.source=t.source,this.collapsed.clear(),this.collapseClosedSections(n),{doc:n,source:t.source}}restore(e){let{state:t}=e,n=So(t.doc);if(this.modeValue==="source"){if(n)return t;let s=Pt(t.doc,{...this.markdown,source:e.source}),l=hr(t.doc,t.selection,Le(s,this.markdown));return Fe(s,l.anchor,l.focus)}if(!n)return this.source=e.source,t;let i=this.loadSource(K(t.doc)),r=fr(t.selection.anchor.offset,t.selection.focus.offset,i);return{doc:i.doc,selection:te(i.doc,r),storedMarks:null}}on(e,t){let n=this.listeners.get(e);return n||this.listeners.set(e,n=new Set),n.add(t),()=>void n.delete(t)}emit(e,t){let n=this.listeners.get(e);if(n)for(let i of[...n])i(t)}applyRuntime(e){let t=this.root;if("placeholder"in e&&(e.placeholder?(t.style.setProperty("--mbe-placeholder",JSON.stringify(e.placeholder)),t.setAttribute("aria-placeholder",e.placeholder)):(t.style.removeProperty("--mbe-placeholder"),t.removeAttribute("aria-placeholder")),this.runtime={...this.runtime,placeholder:e.placeholder}),"attributes"in e){for(let n of Object.keys(this.runtime.attributes??{}))t.removeAttribute(n);for(let[n,i]of Object.entries(e.attributes??{}))t.setAttribute(n,i);this.runtime={...this.runtime,attributes:e.attributes}}"resolveUrl"in e&&e.resolveUrl!==this.runtime.resolveUrl&&(this.runtime={...this.runtime,resolveUrl:e.resolveUrl},this.renderer.resolveUrl=e.resolveUrl??Ln,this.paint(!0)),"onLinkClick"in e&&(this.runtime={...this.runtime,onLinkClick:e.onLinkClick}),"theme"in e&&this.applyTheme(e.theme)&&this.paint(!0)}applyTheme(e){let t=$r(this.runtime.theme?.tokens);this.runtime={...this.runtime,theme:e};let n=this.root.style,i=$r(e?.tokens);for(let a of this.tokenNames)i.has(a)||n.removeProperty(a);for(let[a,d]of i)n.setProperty(a,d);this.tokenNames=[...i.keys()];let r=e?.colorScheme??"auto";n.colorScheme=r==="auto"?"":r,va.some(a=>t.get(a)!==i.get(a))&&this.renderBlocksAgain(this.renderer.dropViews());let s=ka([...this.extensions.map(a=>a.theme?.classes).reverse(),e?.classes]),l=JSON.stringify(s);return l===this.classesKey?!1:(this.classesKey=l,this.renderer.classes=s,!0)}run(e,t="other"){if(this.readOnly||this.destroyed)return!1;let n=e(this.current);return!n||n===this.current||(n=bi(n,this.current,this.markdown.inline),n=yi(n,this.current),n=li(n),n.doc!==this.current.doc&&Qh(n.doc,this.current.doc)&&(n={...n,doc:this.current.doc}),n.doc===this.current.doc&&n.selection===this.current.selection&&n.storedMarks===this.current.storedMarks)?!1:(this.apply(n,t),!0)}createCommands(){let e=l=>this.run(l),t=l=>e(a=>ht(a,l)),n={toggleBold:()=>e(l=>We(l,"bold")),toggleItalic:()=>e(l=>We(l,"italic")),toggleStrike:()=>e(l=>We(l,"strike")),toggleCode:()=>e(l=>We(l,"code")),setParagraph:()=>e(l=>Ge(l,{type:"paragraph"})),toggleHeading:({level:l})=>t({type:"heading",level:l}),toggleBulletList:()=>t({type:"listItem",listType:"bullet"}),toggleOrderedList:()=>t({type:"listItem",listType:"ordered"}),toggleTaskList:()=>t({type:"listItem",listType:"task"}),toggleBlockquote:()=>t({type:"quote"}),toggleCallout:(l={})=>this.markdown.callouts&&t({type:"quote",callout:l.type??"note"}),toggleDetails:()=>this.markdown.details&&t({type:"details"}),setCallout:({type:l})=>(this.markdown.callouts||l===null)&&e(a=>sn(a,a.selection.focus.blockId,l)),toggleCodeBlock:(l={})=>t({type:"code",language:l.language}),setLink:({href:l})=>e(a=>ut(a,l)),unsetLink:()=>e(l=>ut(l,null)),updateImage:l=>e(a=>{let d=De(a);return d?Un(a,d.pos,l):null}),insertText:(l,a={})=>e(d=>{let u=a.range;if(!u)return ue(d,l);let c=te(d.doc,{anchor:u.from,focus:u.to});return ue({...d,selection:c,storedMarks:null},l)}),insertToken:l=>!this.composing&&e(a=>ni(a,l)),insertMarkdown:(l,a={})=>{let d=bt(l,this.markdown).blocks,u=a.at;if(u instanceof kt){if(u.isRemoved)return!1;let c=N(this.current.doc,u.blockId);return e(h=>cn(h,d,{...a,at:P(c),block:!0}))}return e(c=>cn(c,d,a))},insertTable:(l={})=>e(a=>Rt(a,{type:"table",rows:l.rows,cols:l.cols})),insertDivider:()=>e(l=>Rt(l,{type:"divider"})),indent:()=>e(l=>Wn(l,1)),outdent:()=>e(l=>Wn(l,-1)),undo:()=>this.undo(),redo:()=>this.redo(),selectAll:()=>(this.setSelection(xi(this.current).selection),!0),selectBlocks:()=>{if(this.readOnly)return!1;this.hasFocus()||this.root.focus({preventScroll:!0});let{anchor:l,focus:a}=this.current.selection;return this.selectBlockRange(l.blockId,a.blockId),!0},focus:l=>{if(l!==void 0){let a=this.current.doc.blocks,d=l==="start"?V(a[0]):l==="end"?P(a[a.length-1]):l;this.current={...this.current,selection:te(this.current.doc,{anchor:d,focus:d})}}return this.focus(),this.emit("selectionChange",{editor:this}),!0},blur:()=>{let l=this.hasFocus();return this.blur(),l},scrollIntoView:()=>{let l=this.caretRect();return l?(Pr(this.root,l),!0):!1}},i={...n},r=(l,a)=>{let d=i[l];n[l]=(...u)=>this.modeValue==="source"?a?a(...u):!1:d(...u)},s=l=>e(a=>(this.smartLists?Rl(a,l):null)??ln(a,l));r("indent",()=>s(1)),r("outdent",()=>s(-1)),r("insertMarkdown",(l,a={})=>this.insertSourceMarkdown(l,a)),r("toggleBold",()=>e(l=>Tn(l,"**"))),r("toggleItalic",()=>e(l=>Tn(l,"*"))),r("toggleStrike",()=>e(l=>Tn(l,"~~"))),r("toggleCode",()=>e(l=>Tn(l,"`"))),r("setParagraph",()=>e(l=>pr(l,0))),r("toggleHeading",({level:l})=>e(a=>pr(a,l))),r("toggleBulletList",()=>e(l=>Eo(l,"bullet"))),r("toggleOrderedList",()=>e(l=>Eo(l,"ordered"))),r("toggleTaskList",()=>e(l=>Eo(l,"task"))),r("toggleBlockquote",()=>e(l=>Fl(l))),r("toggleCodeBlock",()=>e(l=>ql(l)));for(let l of["toggleCallout","setCallout","toggleDetails","setLink","unsetLink","updateImage","insertTable","insertDivider","selectBlocks"])r(l,null);for(let l of Object.keys(n)){let a=n[l];n[l]=(...d)=>!this.destroyed&&a(...d)}return n}insertSourceMarkdown(e,t){let n=t.at??"selection",i=t.select==="keep",r=t.block===!0;return n instanceof kt?n.isRemoved?!1:this.run(s=>To(s,n.offset,e,!0,i)):n==="selection"&&!r&&!i?this.run(s=>Ae(s,e)):this.run(s=>{let l=s,a;if(n==="selection"){let{from:d,to:u}=ne(s);d!==u&&(l=Ae(s,"")),a=d}else a=n==="end"?K(s.doc).length:n.offset;return To(l,a,e,r,i)})}undo(){if(this.readOnly)return!1;let e=this.history.undo(this.current);return e?(this.commit(this.restore(e)),!0):!1}redo(){if(this.readOnly)return!1;let e=this.history.redo(this.current);return e?(this.commit(this.restore(e)),!0):!1}selectionRect(){let e=this.root.ownerDocument.getSelection();if(!e||e.rangeCount===0)return null;let t=e.getRangeAt(0),n=t.getClientRects(),i=n.length?R(this.current.selection)?n[n.length-1]:t.getBoundingClientRect():null;return i&&(i.width>0||i.height>0)?i:this.emptyRect(this.current.selection.focus,e.focusNode)}caretRect(){let e=this.current.selection.focus,t=this.toDom(e);if(t){let n=this.root.ownerDocument.createRange();n.setStart(t.node,t.offset);let i=n.getClientRects(),r=i[i.length-1];if(r&&r.height>0)return r}return this.emptyRect(e,t?.node??null)}emptyRect(e,t){let n=this.renderer.elementFor(e.blockId),i=(n&&se(n,e.cell))??n,r=t?.nodeType===1?t:t?.parentElement??null;if(i&&r&&r!==i&&i.contains(r)){let s=r.getBoundingClientRect();if(s.height>0)return s}return i?.getBoundingClientRect()??null}textRect(e,t){let n=this.toDom(e),i=this.toDom(t);if(!n||!i)return null;let r=this.root.ownerDocument.createRange();r.setStart(n.node,n.offset),r.setEnd(i.node,i.offset);let s=r.getClientRects()[0];if(!s)return null;let l=n.node.nodeType===1?n.node:n.node.parentElement,a=!!l&&this.root.ownerDocument.defaultView.getComputedStyle(l).direction==="rtl";return{rect:s,rtl:a}}scrollCaretIntoView(){let e=this.caretRect();e&&Pr(this.root,e)}blockElement(e){return this.renderer.elementFor(e)}destroy(){if(!this.destroyed){this.destroyed=!0,this.changeFrame!==null&&cancelAnimationFrame(this.changeFrame),this.settleFrame!==null&&cancelAnimationFrame(this.settleFrame),this.sourceHighlighter.destroy();for(let e of this.cleanup)e();this.suggestions.destroy();for(let e of[...this.widgets])e.remove();this.blockMenu.destroy(),this.toolbar?.destroy(),this.imageToolbar?.destroy(),this.inputPopover.destroy(),this.blockHandle.destroy(),this.linkCard?.destroy(),this.resizeHandles.destroy(),this.renderer.destroy(),ir(this.root,void 0);for(let e of Object.keys(this.runtime.attributes??{}))this.root.removeAttribute(e);for(let e of this.tokenNames)this.root.style.removeProperty(e);this.root.style.colorScheme="",this.root.contentEditable="false",this.root.classList.remove("mbe-root"),this.root.replaceChildren(),this.listeners.clear()}}apply(e,t){e.doc!==this.state.doc&&this.history.record(this.state,t),this.commit(e)}commit(e){let t=e.doc!==this.state.doc,n=e.selection!==this.state.selection,i=this.hasFocus();if(t&&this.modeValue==="source"){let r=K(this.current.doc),s=K(e.doc);for(let l of this.widgets)l.offset=Dl(l.offset,r,s)}else t&&this.relocateWidgets(this.current.doc,e.doc,!1);if(this.current=e,this.blockSel){let r=this.blockRange();r?this.current={...e,selection:an(e.doc.blocks,r)}:this.blockSel=null}this.paint(!1,!1,i),this.afterRender(),n&&i&&this.typing>0&&this.scrollCaretIntoView(),t&&this.scheduleChange(),this.emit("selectionChange",{editor:this})}flushChange(){this.changeFrame!==null&&(cancelAnimationFrame(this.changeFrame),this.changeFrame=null,this.emitChange())}scheduleChange(){if(this.changeFrame!==null||!this.options.onChange&&!this.listeners.get("change")?.size)return;let e=()=>{this.changeFrame=null,this.destroyed||this.emitChange()};typeof requestAnimationFrame=="function"?this.changeFrame=requestAnimationFrame(e):e()}emitChange(){this.options.onChange&&this.options.onChange(this.getMarkdown(),this),this.emit("change",{editor:this})}submit(){return this.destroyed||!this.options.onSubmit&&!this.listeners.get("submit")?.size?!1:(this.flushChange(),this.options.onSubmit?.(this.getMarkdown(),this),this.emit("submit",{editor:this}),!0)}applyReadOnly(){let e=this.readOnly?"false":"true";if(this.root.contentEditable!==e&&(this.root.contentEditable=e),!this.readOnly&&!this.wasReadOnly)return;this.wasReadOnly=this.readOnly;let t=this.ticking;this.root.classList.toggle("mbe-readonly",this.readOnly),this.root.classList.toggle("mbe-tasks",t),this.root.setAttribute("aria-readonly",String(this.readOnly)),this.root.querySelectorAll("[data-row]").forEach(n=>{n.contentEditable=this.readOnly?"false":"true"}),this.root.querySelectorAll("input").forEach(n=>{let i=n.classList.contains("mbe-checkbox");n.disabled=this.readOnly&&!(i&&t),i&&(n.tabIndex=t?0:-1,t?n.setAttribute("aria-label",Zh(n,this.labels.task)):n.removeAttribute("aria-label"))})}get ticking(){return this.readOnly&&this.taskToggle}toggleTaskAt(e){let t=e.closest("[data-block-id]");if(!t)return;let n=t.dataset.blockId,i=e===this.root.ownerDocument.activeElement;if(!this.readOnly)this.run(r=>Qn(r,n));else if(this.ticking&&this.current.doc.blocks.some(r=>r.id===n))this.apply(Qn(this.current,n),"other");else return;i&&this.root.querySelector(`[data-block-id="${n}"] .mbe-checkbox`)?.focus({preventScroll:!0})}afterRender(){for(let e of this.state.doc.blocks){let t=this.renderer.elementFor(e.id);if(!t||!t.classList.contains("mbe-empty"))continue;let n="";e.type==="heading"?n=this.labels[`heading${Math.min(e.level,4)}`]:e.type==="listItem"?n=this.labels.listHint:e.type==="quote"&&!e.callout?n=this.labels.quoteHint:e.type==="details"&&(n=this.labels.detailsHint),n&&t.dataset.hint!==n&&(t.dataset.hint=n)}this.updateUi()}syncDomSelection(e=!1){let t=this.root.ownerDocument.getSelection();if(!t||!e&&!this.hasFocus())return;let n=this.parkedCaret(),i=n?{anchor:n,focus:n}:this.state.selection,r=this.toDom(i.anchor),s=R(i)?r:this.toDom(i.focus);if(!(!r||!s)&&!(t.anchorNode===r.node&&t.anchorOffset===r.offset&&t.focusNode===s.node&&t.focusOffset===s.offset)){if(i.focus.cell){let l=(s.node instanceof Element?s.node:s.node.parentElement)?.closest("[data-row]");l&&this.root.ownerDocument.activeElement!==l&&l.focus({preventScroll:!0})}else this.root.ownerDocument.activeElement!==this.root&&this.hasFocus()&&this.root.focus({preventScroll:!0});t.setBaseAndExtent(r.node,r.offset,s.node,s.offset)}}toDom(e){let t=this.renderer.elementFor(e.blockId);return t?ma(t,e):null}readDomSelection(){let e=this.root.ownerDocument.getSelection();if(!e||!e.anchorNode||!e.focusNode||!this.root.contains(e.anchorNode)||!this.root.contains(e.focusNode))return null;let t=_e(this.root,e.anchorNode,e.anchorOffset),i=e.anchorNode===e.focusNode&&e.anchorOffset===e.focusOffset?t:_e(this.root,e.focusNode,e.focusOffset);return!t||!i?null:{anchor:t,focus:i}}onSelectionChange(){if(this.composing||this.destroyed)return;let e=this.readDomSelection();if(!e){this.hasFocus()||this.updateUi();return}let t=this.caretKey;if(this.caretKey=null,this.blockSel){this.updateUi();return}let n=this.state.selection;if(be(e.anchor,n.anchor)&&be(e.focus,n.focus)){this.updateUi();return}this.shortcut=null;let i=t?.vertical?this.skippedBlock(t.from,t.vertical,t.x,e.focus):null,r=this.imageBlockAt(i?{anchor:i,focus:i}:e);r?!be(r.anchor,n.anchor)||!be(r.focus,n.focus)?this.setSelection(r):this.updateUi():i?this.setSelection({anchor:i,focus:i}):(this.current={...this.state,selection:e,storedMarks:null},this.history.breakGroup(),this.pointerDown||this.refreshRevealed(),this.updateUi(),this.emit("selectionChange",{editor:this})),t&&this.scrollCaretIntoView()}imageBlockAt(e){if(!R(e)||e.focus.cell)return null;let t=this.state.doc.blocks.find(i=>i.id===e.focus.blockId),n=t?Y(t):null;return n===null?null:{anchor:{blockId:t.id,offset:n},focus:{blockId:t.id,offset:n+1}}}skippedBlock(e,t,n,i){let r=this.state.doc.blocks,s=L(this.state.doc,i.blockId);for(let l=e+t;(s-l)*t>0;l+=t){let a=r[l];if(!this.skipsCaret(a))return this.blockEntry(a,t===1,n)}return null}blockEntry(e,t,n){let i=this.renderer.elementFor(e.id),r=this.viewBlock(e);if(r)return Bn(r,t);if(i){let s=i.ownerDocument.createRange();s.selectNodeContents(se(i)??i);let l=Array.from(s.getClientRects()).filter(u=>u.height>0),a=t?l[0]:l[l.length-1],d=a?this.positionAtPoint(n,a.top+a.height/2):null;if(d?.blockId===e.id)return d}if(e.type==="table"){let s=t?0:e.rows.length-1;return{blockId:e.id,offset:t?0:B(e.rows[s][0]),cell:{row:s,col:0}}}return t?V(e):P(e)}paint(e=!1,t=!1,n=this.hasFocus()){let i=this.renderer.views;i&&!this.pointerDown&&!this.composing&&(this.renderer.revealed=Hr(this.state,i,!this.readOnly&&n,this.hosted)),this.renderer.collectFootnotes=this.readOnly,this.renderer.render(this.state.doc,e,t),this.applyHeadingIds(),this.applyReadOnly(),this.paintBlockSelection(),this.composing||this.syncDomSelection(n)}sourceSpans(e){return this.sourceHighlighter.spans(I(e.content))}refreshSource(){if(this.destroyed||this.modeValue!=="source"||this.composing||this.composition)return;let e=this.current.doc.blocks[0];if(e?.type!=="code")return;let t=this.hasFocus();this.renderer.refreshSource(e),this.pointerDown||this.syncDomSelection(t)}applyHeadingIds(){let e=this.options.headingIds;if(!e)return;let t=this.state.doc;if(this.headingIdsFor?.doc!==t){let n=t.blocks.filter(r=>r.type==="heading"),i=e(n.map(r=>({text:I(r.content),level:r.level})));this.headingIdsFor={doc:t,ids:new Map(n.map((r,s)=>[r.id,i[s]]))}}for(let[n,i]of this.headingIdsFor.ids){let r=this.renderer.elementFor(n);r&&(i?r.id!==i&&(r.id=i):r.id&&r.removeAttribute("id"))}}redecorate(){if(!this.destroyed){if(this.composing||this.composition){this.redecoratePending=!0;return}this.redecoratePending=!1,this.sourceHighlighter.reset(),this.paint(!0),this.afterRender()}}refreshViews(e){this.destroyed||this.renderBlocksAgain(this.renderer.dropViews(e))}renderBlocksAgain(e){if(e.length!==0){if(this.composing||this.composition){for(let t of e)this.unsettled.add(t);return}for(let t of e)this.renderer.invalidate(t);this.paint(),this.afterRender()}}viewsSettled(e){if(!this.destroyed){if(this.composing||this.composition){for(let t of e)this.unsettled.add(t);return}for(let t of e)this.renderer.invalidate(t);this.viewFrame||=requestAnimationFrame(()=>{this.viewFrame=0,!(this.destroyed||this.composing||this.composition)&&(this.paint(),this.afterRender())})}}viewBlock(e){return e&&this.renderer.elementFor(e.id)?.classList.contains("mbe-view-block")?e:null}refreshRevealed(){let e=this.renderer.views;if(!e||this.pointerDown)return;let t=Hr(this.state,e,!this.readOnly&&this.hasFocus(),this.hosted);ba(t,this.renderer.revealed)||this.paint()}hosted=e=>this.renderer.isHosted(e);onMouseUp(){this.pointerDown&&(this.pointerDown=!1,!this.destroyed&&!this.composing&&this.refreshRevealed())}blockPast(e){let t=this.state.selection;if(!R(t)||t.focus.cell)return null;let n=t.focus,i=this.state.doc.blocks,r=L(this.state.doc,n.blockId),s=e==="ArrowDown"||e==="ArrowRight",l=i[r+(s?1:-1)],a=this.viewBlock(l);if(!l||!a&&l.type!=="table")return null;let d=i[r];if(!q(d)||e==="ArrowRight"&&n.offset!==P(d).offset||e==="ArrowLeft"&&n.offset!==0)return null;if(e==="ArrowDown"||e==="ArrowUp"){let u=se(this.renderer.elementFor(d.id));if(u&&!this.onEdgeLine(u,s))return null}return Bn(l,s)}imageBlockStep(e){let t=this.state.selection,n=this.state.doc.blocks,i=e==="ArrowDown"||e==="ArrowRight",r=ke(this.state);if(r){let u=L(this.state.doc,r.pos.blockId);for(let c=u+(i?1:-1);c>=0&&c<n.length;c+=i?1:-1){let h=n[c];if(this.skipsCaret(h))continue;let f=Y(h);if(f!==null)return{anchor:{blockId:h.id,offset:f},focus:{blockId:h.id,offset:f+1}};let m=e==="ArrowDown"||e==="ArrowUp"?this.blockEntry(h,i,this.selectionRect()?.left??0):i?V(h):P(h);return{anchor:m,focus:m}}return t}if(!R(t)||t.focus.cell)return null;let s=L(this.state.doc,t.focus.blockId),l=n[s],a=n[s+(i?1:-1)],d=a?Y(a):null;if(!a||d===null||!q(l)||e==="ArrowRight"&&t.focus.offset!==P(l).offset||e==="ArrowLeft"&&t.focus.offset!==0)return null;if(e==="ArrowDown"||e==="ArrowUp"){let u=se(this.renderer.elementFor(l.id));if(u&&!this.onEdgeLine(u,i))return null}return{anchor:{blockId:a.id,offset:d},focus:{blockId:a.id,offset:d+1}}}tableCellPast(e){let t=this.state.selection,n=t.focus;if(!R(t)||!n.cell)return null;let i=this.state.doc.blocks,r=L(this.state.doc,n.blockId),s=i[r];if(s?.type!=="table")return null;let l=se(this.renderer.elementFor(s.id),n.cell);if(l&&!this.onEdgeLine(l,e===1))return null;let{row:a,col:d}=n.cell,u=s.rows[a+e];if(u){let c=Math.min(n.offset,B(u[d]));return{blockId:s.id,offset:c,cell:{row:a+e,col:d}}}for(let c=r+e;c>=0&&c<i.length;c+=e){let h=i[c];if(this.skipsCaret(h))continue;if(h.type==="table"){let p=e===1?0:h.rows.length-1,m=Math.min(d,h.align.length-1);return{blockId:h.id,offset:e===1?0:B(h.rows[p][m]),cell:{row:p,col:m}}}let f=this.viewBlock(h);return f?Bn(f,e===1):e===1?V(h):P(h)}return null}onEdgeLine(e,t){let n=this.selectionRect();if(!n||n.height===0)return!0;let i=e.ownerDocument.createRange();i.selectNodeContents(e);let r=Array.from(i.getClientRects()).filter(l=>l.height>0);if(r.length===0)return!0;let s=n.height/2;return t?Math.max(...r.map(l=>l.bottom))-n.bottom<=s:n.top-Math.min(...r.map(l=>l.top))<=s}revealView(e){let t=e.hasAttribute(W)?N(this.state.doc,e.getAttribute(W)):null,n=t?Bn(t,!1):_e(this.root,e.parentNode,xt(e)+1);n&&(this.root.focus({preventScroll:!0}),this.setSelection({anchor:n,focus:n}))}refreshSelection(){if(this.blockSel)return;let e=this.readDomSelection();e&&(this.current={...this.state,selection:e})}targetRange(e){let t=e.getTargetRanges?.()[0];if(!t)return null;let n=_e(this.root,t.startContainer,t.startOffset),i=_e(this.root,t.endContainer,t.endOffset);return n&&i?{anchor:n,focus:i}:null}fromControl(e){return e.target instanceof HTMLInputElement||!!e.target?.closest?.(Ba)}onBeforeInput(e){if(this.fromControl(e)||this.composing||e.isComposing)return;let t=e.inputType;if(!Na.has(t)&&!(!e.cancelable&&this.browserApplies(e))&&(e.preventDefault(),!this.readOnly)){if(this.blockSel){t.startsWith("delete")?this.deleteSelectedBlocks():t==="historyUndo"?this.undo():t==="historyRedo"&&this.redo();return}if(this.refreshSelection(),!((t==="insertText"||t==="insertReplacementText")&&ke(this.state))&&!(this.modeValue==="source"&&this.onSourceInput(t)))switch(t){case"insertText":{let n=e.data??"",i=R(this.state.selection)?this.targetRange(e):null;i&&!R(i)&&(this.current={...this.state,selection:i}),n?this.typeText(n):i&&!R(i)&&this.run(J,"typing");return}case"insertReplacementText":{let n=e.dataTransfer?.getData("text/plain")??e.data??"",i=this.targetRange(e);this.run(r=>ue(i?{...r,selection:i}:r,n));return}case"insertParagraph":{if(this.suggestions.isOpen&&this.suggestions.accept())return;this.run(n=>this.collapsed.has(n.selection.focus.blockId)?ri(n):Kn(n));return}case"insertLineBreak":this.run(ii);return;case"deleteContentBackward":this.undoShortcut()||this.run(nn);return;case"deleteContentForward":this.run(_n);return;case"deleteWordBackward":case"deleteWordForward":case"deleteSoftLineBackward":case"deleteSoftLineForward":case"deleteHardLineBackward":case"deleteHardLineForward":case"deleteEntireSoftLine":{if(!R(this.state.selection)){this.run(J);return}let n=this.targetRange(e);n&&!R(n)&&n.anchor.blockId===n.focus.blockId?this.run(i=>J({...i,selection:n})):this.run(this.modeValue==="source"?t.endsWith("Backward")?i=>ar(i,en):i=>cr(i,tn):t.endsWith("Backward")?nn:_n);return}case"historyUndo":this.undo();return;case"historyRedo":this.redo();return;case"formatBold":this.commands.toggleBold();return;case"formatItalic":this.commands.toggleItalic();return;case"formatStrikeThrough":this.commands.toggleStrike();return;default:return}}}onSourceInput(e){switch(e){case"insertParagraph":return this.run(t=>this.smartLists?Nl(t):Ae(t,`
117
117
  `)),!0;case"insertLineBreak":return this.run(t=>Ae(t,`
118
118
  `)),!0;case"deleteContentBackward":return this.run(t=>ar(t,en)),!0;case"deleteContentForward":return this.run(t=>cr(t,tn)),!0;default:return!1}}typeText(e){this.run(t=>ue(t,e),"typing"),this.afterTyping(e)}browserApplies(e){let t=e.inputType;if(t==="insertText"||t==="insertReplacementText")return!0;if(!t.startsWith("delete"))return!1;let n=this.targetRange(e);return!!n&&!R(n)&&n.anchor.blockId===n.focus.blockId&&n.anchor.cell?.row===n.focus.cell?.row&&n.anchor.cell?.col===n.focus.cell?.col}afterTyping(e){if(this.modeValue==="source")this.shortcut=null;else{let t=this.state;(e===" "||e==="-")&&this.run(n=>fi(n,this.markdown)),e.length===1&&"*_`~".includes(e)&&this.run(n=>mi(n)),this.markdown.inline.length>0&&this.run(n=>gi(n,this.markdown.inline)??n),e===" "&&this.markdown.autolinks&&this.run(n=>ki(n)??n),this.shortcut=this.state.doc!==t.doc?{typed:t,applied:this.state}:null}e.includes(`
119
- `)||this.typedForSuggestion()}undoShortcut(){let e=this.shortcut;this.shortcut=null;let{doc:t,selection:n}=this.state;return!e||t!==e.applied.doc||!R(n)||!be(n.focus,e.applied.selection.focus)?!1:this.run(()=>e.typed)}onCompositionStart(e){this.fromControl(e)||(this.dropBlockSelection(),this.refreshSelection(),R(this.state.selection)||this.run(J),this.composing=!0,this.composition={blockId:this.state.selection.focus.blockId,marks:this.state.storedMarks,recorded:!1},this.toolbar?.hide(),this.imageToolbar?.hide())}onCompositionEnd(e){if(!this.fromControl(e)){if(!this.composition){this.composing=!1,this.reconcileFromDom("other");return}if(this.syncComposition(),this.composing=!1,bl&&(this.compositionEndedAt=Date.now()),this.unsettled.add(this.composition.blockId),this.settleFrame===null){let t=()=>{this.settleFrame=null,this.settleComposition()};typeof requestAnimationFrame=="function"?this.settleFrame=requestAnimationFrame(t):this.settleComposition()}}}settleComposition(){if(this.composing||this.destroyed)return;let e=this.composition?.recorded;this.composition=null;for(let t of this.unsettled)this.renderer.invalidate(t);this.unsettled.clear(),this.paint(this.redecoratePending),this.redecoratePending=!1,this.afterRender(),e&&this.typedForSuggestion(),this.pendingMode&&this.setMode(this.pendingMode)}onInput(e){if(this.fromControl(e))return;if(this.composing||this.composition&&Na.has(e.inputType)){let n=this.composedLength();this.syncComposition(),this.composing&&this.composedLength()>n&&this.typedForSuggestion();return}if(e.isComposing)return;let t=this.state;this.reconcileFromDom("typing"),e.inputType==="insertText"&&e.data&&this.state!==t&&this.afterTyping(e.data)}composedLength(){let e=this.state.selection.focus,t=this.state.doc.blocks.find(i=>i.id===this.composition?.blockId),n=t&&F(t,t.id===e.blockId?e.cell:void 0);return n?B(n):0}endComposition(){!this.composing||!this.composition||(this.syncComposition(),this.composing=!1,this.unsettled.add(this.composition.blockId),this.settleFrame!==null&&cancelAnimationFrame(this.settleFrame),this.settleFrame=null,this.settleComposition())}syncComposition(){let e=this.composition;if(!e||this.readOnly)return;let t=this.state,n=this.readDom(t,e.marks,e.blockId);if(!n)return;e.recorded||(this.history.record(t,"other"),e.recorded=!0);let i=n.doc.blocks.find(s=>s.id===e.blockId);i&&this.renderer.adopt(i);let r=this.readDomSelection();this.commit(r?{...n,selection:te(n.doc,r)}:n)}reconcileFromDom(e){let t=this.readDom(this.state,this.state.storedMarks);if(!t){this.paint(!0);return}for(let i of t.doc.blocks)i!==N(this.state.doc,i.id)&&this.renderer.invalidate(i.id);let n=this.readDomSelection()??t.selection;this.apply({...t,selection:te(t.doc,n)},e)}readDom(e,t,n){let i=e,r=!1;for(let s of e.doc.blocks){if(n!==void 0&&s.id!==n)continue;let l=this.renderer.elementFor(s.id);if(!l||!l.isConnected)continue;let a=s.type==="table"?s.rows.flatMap((d,u)=>d.map((c,h)=>({cell:{row:u,col:h}}))):Z(s)?[]:[{}];for(let{cell:d}of a){let u=se(l,d),c=F(N(i.doc,s.id),d);if(!u||!c)continue;let h=I(c),f=Or(u);if(h===f)continue;let p=0;for(;p<h.length&&p<f.length&&h[p]===f[p];)p++;let m=h.length,y=f.length;for(;m>p&&y>p&&h[m-1]===f[y-1];)m--,y--;let g=f.slice(p,y),x=d?{blockId:s.id,offset:p,cell:d}:{blockId:s.id,offset:p};i=ye(i,x,{...x,offset:m}),g&&(i=ue({...i,storedMarks:t},g)),r=!0}}return r?i:null}onKeyDown(e){if(this.caretKey=null,this.fromControl(e)||e.isComposing||e.keyCode===229)return;Aa.test(e.key)&&(this.shortcut=null);let t=ie?e.metaKey:e.ctrlKey,n=e.key.toLowerCase(),i=a=>{e.preventDefault(),this.refreshSelection(),a()},r=Date.now()-this.compositionEndedAt<100;if(this.compositionEndedAt=0,this.suggestions.isOpen&&!r&&(this.refreshSelection(),this.suggestions.keydown(e))){e.preventDefault();return}let s=this.blockMenu.isOpen?this.blockMenu:this.toolbar?.menu??null;if(s){let a=s.submenu;if(a){if(e.key==="ArrowLeft"||e.key==="Escape")return i(()=>s.closeSubmenu());if(e.key==="ArrowDown"||e.key==="Tab"&&!e.shiftKey)return i(()=>this.moveMenu(a,1));if(e.key==="ArrowUp"||e.key==="Tab"&&e.shiftKey)return i(()=>this.moveMenu(a,-1));if(e.key==="Enter"&&a.count>0)return i(()=>a.pick())}if(e.key==="ArrowRight"&&s.openSubmenu())return i(()=>this.syncActiveDescendant());if(e.key==="ArrowDown"||e.key==="Tab"&&!e.shiftKey)return i(()=>this.moveMenu(s,1));if(e.key==="ArrowUp"||e.key==="Tab"&&e.shiftKey)return i(()=>this.moveMenu(s,-1));if(e.key==="Enter"&&s.count>0)return i(()=>s.pick());if(e.key==="Escape")return i(()=>s===this.blockMenu?this.closeBlockMenu():this.toolbar.closeMenu())}if(e.key==="Escape"&&(this.toolbar?.isOpen||this.imageToolbar?.isOpen))return i(()=>{this.toolbarClosedFor=this.state.selection,this.toolbar?.hide(),this.imageToolbar?.hide()});if(this.readOnly)return;if(this.blockSel&&this.onBlockKey(e)){e.preventDefault();return}if(e.key==="Enter"&&!t&&!e.altKey){this.refreshSelection();let a=De(this.state);if(a){let d={...a.pos,offset:a.pos.offset+1};this.setSelection({anchor:d,focus:d})}}let l=!1;for(let a of this.bindings)if(Ql(a,e)&&(l||this.refreshSelection(),l=!0,a.handler({editor:this}))){e.preventDefault();return}if(e.key==="Backspace"&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(this.refreshSelection(),this.undoShortcut()){e.preventDefault();return}let{selection:a}=this.state;if(R(a)&&a.focus.offset===0){e.preventDefault(),this.modeValue!=="source"&&this.run(nn);return}}if(t&&!e.altKey){if(e.key==="/"&&!e.shiftKey&&this.refreshSelection(),e.key==="/"&&!e.shiftKey&&this.hasBlockMenu(this.state.selection.focus.blockId))return i(()=>this.openBlockMenu(this.state.selection.focus.blockId));if(n==="v"&&e.shiftKey){this.plainPasteNext=!0;return}}if(e.key.startsWith("Arrow")&&!t&&!e.shiftKey&&!e.altKey&&this.modeValue==="rich"){this.refreshSelection();let a=this.blockPast(e.key);if(a){e.preventDefault(),this.setSelection({anchor:a,focus:a});return}let d=this.imageBlockStep(e.key);if(d){e.preventDefault(),d!==this.state.selection?this.setSelection(d):(e.key==="ArrowDown"||e.key==="ArrowUp")&&this.run(f=>on(f,e.key==="ArrowDown"?1:-1));return}let u=e.key==="ArrowDown"?1:e.key==="ArrowUp"?-1:0,c=u?this.tableCellPast(u):null;if(c){e.preventDefault(),this.setSelection({anchor:c,focus:c});return}let h=u?on(this.state,u):this.state;if(h!==this.state){e.preventDefault(),this.run(()=>h);return}}if(Aa.test(e.key)){this.refreshSelection();let d=!t&&!e.shiftKey&&!e.altKey?e.key==="ArrowDown"?1:e.key==="ArrowUp"?-1:0:0,c={from:L(this.state.doc,this.state.selection.focus.blockId),x:this.selectionRect()?.left??0,vertical:d};this.caretKey=c,d&&this.unlessCaretMoves(c)}}unlessCaretMoves(e){let t=this.state.selection.focus;if(t.cell||!R(this.state.selection))return;let n=se(this.renderer.elementFor(t.blockId)??this.root);!n||!this.onEdgeLine(n,e.vertical===1)||setTimeout(()=>{if(this.destroyed||this.caretKey!==e)return;let i=this.readDomSelection();if(!i||!be(i.focus,t))return;let r=this.state.doc.blocks;for(let s=e.from+e.vertical;s>=0&&s<r.length;s+=e.vertical){let l=r[s];if(this.skipsCaret(l))continue;this.caretKey=null;let a=e.vertical===1?0:l.type==="table"?l.rows.length-1:0,d=l.type==="table"?{blockId:l.id,offset:e.vertical===1?0:B(l.rows[a][0]),cell:{row:a,col:0}}:this.blockEntry(l,e.vertical===1,e.x);this.setSelection({anchor:d,focus:d}),this.scrollCaretIntoView();return}e.vertical===1&&r[r.length-1].type==="detailsEnd"&&(this.caretKey=null,this.run(s=>oi(s)))})}selectBlockText(e){let t=e.closest?.(`[${W}]`);if(!t||!this.root.contains(t))return!1;let n=N(this.state.doc,t.getAttribute(W)),i=e.closest("[data-row]"),r=n.type==="table"&&i?{row:Number(i.dataset.row),col:Number(i.dataset.col)}:void 0,s=F(n,r);if(!s||t.classList.contains("mbe-view-block"))return!1;let l=a=>r?{blockId:n.id,offset:a,cell:r}:{blockId:n.id,offset:a};return this.setSelection({anchor:l(0),focus:l(B(s))}),!0}moveMenu(e,t){e.move(t),this.syncActiveDescendant()}onMouseDown(e){this.caretKey=null;let t=e.target;if(t.closest?.(".mbe-code-copy")){e.preventDefault();return}let n=e.button===0?t.closest?.(".mbe-details-toggle"):null,i=n?.closest(`[${W}]`)?.getAttribute(W);if(i&&this.root.contains(n)){e.preventDefault(),this.setSectionCollapsed(i,!this.collapsed.has(i));return}if(this.dropBlockSelection(),t===this.root&&e.button===0&&!this.readOnly&&this.modeValue==="rich"&&this.clickBelowLastBlock(e))return;let r=e.button===0&&!e.shiftKey&&!this.readOnly?t.closest?.(".mbe-image"):null,s=r&&this.root.contains(r)?this.imageTarget(r):null;if(s){e.preventDefault(),this.selectImageAt(s.pos);return}let l=e.button===0&&!this.readOnly?t.closest?.(".mbe-view, .mbe-view-block"):null;if(l&&this.root.contains(l)){e.preventDefault(),this.revealView(l);return}if(e.button===0&&e.detail===3&&!this.readOnly&&this.modeValue==="rich"&&this.selectBlockText(t)){e.preventDefault();return}let a=e.button===0&&!this.readOnly?t.closest?.(".mbe-callout-icon"):null,d=a?.parentElement?.getAttribute(W);if(a&&d&&a.parentElement.parentElement===this.root){e.preventDefault(),this.openBlockMenu(d,a.getBoundingClientRect());return}e.button===0&&(this.pointerDown=!0),t.classList?.contains("mbe-checkbox")&&(e.preventDefault(),e.button===0&&this.toggleTaskAt(t))}clickBelowLastBlock(e){let t=this.state.doc.blocks,n=t[t.length-1],i=n?Y(n):null;if(!n||n.type!=="code"&&n.type!=="table"&&!Z(n)&&i===null)return!1;let r=this.root.querySelector(`:scope > [data-block-id="${n.id}"]`);if(!r||e.clientY<=r.getBoundingClientRect().bottom)return!1;e.preventDefault(),this.root.focus({preventScroll:!0});let s=P(n),l=i!==null?{anchor:{blockId:n.id,offset:i},focus:{blockId:n.id,offset:i+1}}:{anchor:s,focus:s};return this.run(a=>on({...a,selection:l},1)),!0}onClick(e){let t=e.target;if(t.classList?.contains("mbe-checkbox")){e.preventDefault(),e.detail===0&&this.toggleTaskAt(t);return}let n=t.closest?.(".mbe-code-copy");if(n){e.preventDefault(),this.copyCode(n);return}let i=t.closest?.("a.mbe-link");i&&(e.preventDefault(),(this.readOnly||(ie?e.metaKey:e.ctrlKey))&&this.openHref(i.getAttribute("href"),e))}openHref(e,t){!e||this.runtime.onLinkClick?.({editor:this,href:e,event:t})||this.root.ownerDocument.defaultView?.open(e,"_blank","noopener,noreferrer")}copyCode(e){let t=e.closest(`[${W}]`),n=t&&this.state.doc.blocks.find(u=>u.id===t.getAttribute(W)),i=n?.type==="code"?I(n.content):e.closest(".mbe-flow .mbe-code")?.querySelector("code")?.textContent;if(i==null)return;let r=this.root.ownerDocument,s=u=>{let c=X(r,this.icon(u));e.replaceChildren(...c?[c]:[]),e.setAttribute("aria-label",this.labels[u]),e.title=this.labels[u],e.classList.toggle("mbe-copied",u==="copied")},l=()=>{s("copied"),setTimeout(()=>e.isConnected&&s("copyCode"),1500)},a=()=>{let u=r.createElement("textarea");u.value=i,u.style.cssText="position:fixed;top:0;left:0;opacity:0",r.body.appendChild(u),u.select();let c=r.execCommand("copy");u.remove(),this.syncDomSelection(this.hasFocus()),c&&l()},d=r.defaultView?.navigator.clipboard;d?.writeText?d.writeText(i).then(l,a):a()}onControlChange(e){let t=e.target;if(!(t instanceof HTMLInputElement)||!t.classList.contains("mbe-code-lang"))return;let n=t.closest("[data-block-id]");n&&this.run(i=>ci(i,n.dataset.blockId,t.value.trim()))}onFocusIn(e){this.focused||!this.hasFocus()||(this.focused=!0,this.root.classList.add("mbe-focused"),this.pointerDown||this.refreshRevealed(),this.options.onFocus?.(this),this.emit("focus",{editor:this,event:e}),this.updateUi())}onFocusOut(e){let t=e.relatedTarget;t&&(this.root.contains(t)||this.inputPopover.contains(t))||queueMicrotask(()=>{this.hasFocus()||this.inputPopover.isOpen||this.focused&&(this.focused=!1,this.root.classList.remove("mbe-focused"),this.refreshRevealed(),this.hideUi(),this.flushChange(),this.options.onBlur?.(this),this.emit("blur",{editor:this,event:e}))})}onScroll(){this.blockHandle.hide(),this.linkCard?.reposition(),this.resizeHandles.reposition(),(this.suggestions.isActive||this.toolbar?.isOpen||this.imageToolbar?.isOpen||this.blockMenu.isOpen)&&this.updateUi()}onCopy(e,t){if(this.fromControl(e))return;if(this.modeValue==="source"){if(this.refreshSelection(),R(this.state.selection)||!e.clipboardData)return;e.preventDefault();let{from:d,to:u}=ne(this.state);e.clipboardData.setData("text/plain",K(this.state.doc).slice(d,u)),t&&!this.readOnly&&this.run(c=>Ae(c,""));return}let n=this.blockRange();if(n){if(!e.clipboardData)return;e.preventDefault();let d={blocks:rn(this.state.doc.blocks.slice(n.from,n.to+1).map(dt))};Oa(e.clipboardData,d,Pe(d.blocks,this.markdown)),t&&!this.readOnly&&this.deleteSelectedBlocks();return}if(this.refreshSelection(),R(this.state.selection)||!e.clipboardData)return;e.preventDefault();let i=vi(this.state),r={blocks:rn(i)},s=Pt(r,this.markdown).replace(/\n$/,""),l=i.length===1&&i[0].type==="paragraph"?i[0]:null,a=l&&Q(N(this.state.doc,this.state.selection.focus.blockId));Oa(e.clipboardData,r,s,a?I(l.content):s),t&&!this.readOnly&&this.run(J)}onPaste(e){if(this.fromControl(e)||(e.preventDefault(),this.readOnly))return;this.refreshSelection();for(let c of this.extensions)if(c.handlePaste?.({editor:this,event:e}))return;let t=e.clipboardData;if(!t)return;let n=t.getData("text/plain"),i=t.getData("text/html"),r=t.types.includes("vscode-editor-data")||ds(i)?"":i,s=this.plainPasteNext;if(this.plainPasteNext=!1,this.modeValue==="source"){let c=this.pastedUrl(n,s);if(c!==null){this.run(f=>_l(f,c));return}let h=this.pastedMarkdown(n,r,s);h&&this.run(f=>Ae(f,h.replace(/\r\n?/g,`
119
+ `)||this.typedForSuggestion()}undoShortcut(){let e=this.shortcut;this.shortcut=null;let{doc:t,selection:n}=this.state;return!e||t!==e.applied.doc||!R(n)||!be(n.focus,e.applied.selection.focus)?!1:this.run(()=>e.typed)}onCompositionStart(e){this.fromControl(e)||(this.dropBlockSelection(),this.refreshSelection(),R(this.state.selection)||this.run(J),this.composing=!0,this.composition={blockId:this.state.selection.focus.blockId,marks:this.state.storedMarks,recorded:!1},this.toolbar?.hide(),this.imageToolbar?.hide())}onCompositionEnd(e){if(!this.fromControl(e)){if(!this.composition){this.composing=!1,this.reconcileFromDom("other");return}if(this.syncComposition(),this.composing=!1,bl&&(this.compositionEndedAt=Date.now()),this.unsettled.add(this.composition.blockId),this.settleFrame===null){let t=()=>{this.settleFrame=null,this.settleComposition()};typeof requestAnimationFrame=="function"?this.settleFrame=requestAnimationFrame(t):this.settleComposition()}}}settleComposition(){if(this.composing||this.destroyed)return;let e=this.composition?.recorded;this.composition=null;for(let t of this.unsettled)this.renderer.invalidate(t);this.unsettled.clear(),this.paint(this.redecoratePending),this.redecoratePending=!1,this.afterRender(),e&&this.typedForSuggestion(),this.pendingMode&&this.setMode(this.pendingMode)}onInput(e){if(this.fromControl(e))return;if(this.composing||this.composition&&Na.has(e.inputType)){let n=this.composedLength();this.syncComposition(),this.composing&&this.composedLength()>n&&this.typedForSuggestion();return}if(e.isComposing)return;let t=this.state;this.reconcileFromDom("typing"),e.inputType==="insertText"&&e.data&&this.state!==t&&this.afterTyping(e.data)}composedLength(){let e=this.state.selection.focus,t=this.state.doc.blocks.find(i=>i.id===this.composition?.blockId),n=t&&F(t,t.id===e.blockId?e.cell:void 0);return n?B(n):0}endComposition(){!this.composing||!this.composition||(this.syncComposition(),this.composing=!1,this.unsettled.add(this.composition.blockId),this.settleFrame!==null&&cancelAnimationFrame(this.settleFrame),this.settleFrame=null,this.settleComposition())}syncComposition(){let e=this.composition;if(!e||this.readOnly)return;let t=this.state,n=this.readDom(t,e.marks,e.blockId);if(!n)return;e.recorded||(this.history.record(t,"other"),e.recorded=!0);let i=n.doc.blocks.find(s=>s.id===e.blockId);i&&this.renderer.adopt(i);let r=this.readDomSelection()?.focus;this.commit(r?{...n,selection:te(n.doc,{anchor:r,focus:r})}:n)}reconcileFromDom(e){let t=this.readDom(this.state,this.state.storedMarks);if(!t){this.paint(!0);return}for(let i of t.doc.blocks)i!==N(this.state.doc,i.id)&&this.renderer.invalidate(i.id);let n=this.readDomSelection()??t.selection;this.apply({...t,selection:te(t.doc,n)},e)}readDom(e,t,n){let i=e,r=!1;for(let s of e.doc.blocks){if(n!==void 0&&s.id!==n)continue;let l=this.renderer.elementFor(s.id);if(!l||!l.isConnected)continue;let a=s.type==="table"?s.rows.flatMap((d,u)=>d.map((c,h)=>({cell:{row:u,col:h}}))):Z(s)?[]:[{}];for(let{cell:d}of a){let u=se(l,d),c=F(N(i.doc,s.id),d);if(!u||!c)continue;let h=I(c),f=Or(u);if(h===f)continue;let p=0;for(;p<h.length&&p<f.length&&h[p]===f[p];)p++;let m=h.length,y=f.length;for(;m>p&&y>p&&h[m-1]===f[y-1];)m--,y--;let g=f.slice(p,y),x=d?{blockId:s.id,offset:p,cell:d}:{blockId:s.id,offset:p};i=ye(i,x,{...x,offset:m}),g&&(i=ue({...i,storedMarks:t},g)),r=!0}}return r?i:null}onKeyDown(e){if(this.caretKey=null,this.fromControl(e)||e.isComposing||e.keyCode===229)return;Aa.test(e.key)&&(this.shortcut=null);let t=ie?e.metaKey:e.ctrlKey,n=e.key.toLowerCase(),i=a=>{e.preventDefault(),this.refreshSelection(),a()},r=Date.now()-this.compositionEndedAt<100;if(this.compositionEndedAt=0,this.suggestions.isOpen&&!r&&(this.refreshSelection(),this.suggestions.keydown(e))){e.preventDefault();return}let s=this.blockMenu.isOpen?this.blockMenu:this.toolbar?.menu??null;if(s){let a=s.submenu;if(a){if(e.key==="ArrowLeft"||e.key==="Escape")return i(()=>s.closeSubmenu());if(e.key==="ArrowDown"||e.key==="Tab"&&!e.shiftKey)return i(()=>this.moveMenu(a,1));if(e.key==="ArrowUp"||e.key==="Tab"&&e.shiftKey)return i(()=>this.moveMenu(a,-1));if(e.key==="Enter"&&a.count>0)return i(()=>a.pick())}if(e.key==="ArrowRight"&&s.openSubmenu())return i(()=>this.syncActiveDescendant());if(e.key==="ArrowDown"||e.key==="Tab"&&!e.shiftKey)return i(()=>this.moveMenu(s,1));if(e.key==="ArrowUp"||e.key==="Tab"&&e.shiftKey)return i(()=>this.moveMenu(s,-1));if(e.key==="Enter"&&s.count>0)return i(()=>s.pick());if(e.key==="Escape")return i(()=>s===this.blockMenu?this.closeBlockMenu():this.toolbar.closeMenu())}if(e.key==="Escape"&&(this.toolbar?.isOpen||this.imageToolbar?.isOpen))return i(()=>{this.toolbarClosedFor=this.state.selection,this.toolbar?.hide(),this.imageToolbar?.hide()});if(this.readOnly)return;if(this.blockSel&&this.onBlockKey(e)){e.preventDefault();return}if(e.key==="Enter"&&!t&&!e.altKey){this.refreshSelection();let a=De(this.state);if(a){let d={...a.pos,offset:a.pos.offset+1};this.setSelection({anchor:d,focus:d})}}let l=!1;for(let a of this.bindings)if(Ql(a,e)&&(l||this.refreshSelection(),l=!0,a.handler({editor:this}))){e.preventDefault();return}if(e.key==="Backspace"&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(this.refreshSelection(),this.undoShortcut()){e.preventDefault();return}let{selection:a}=this.state;if(R(a)&&a.focus.offset===0){e.preventDefault(),this.modeValue!=="source"&&this.run(nn);return}}if(t&&!e.altKey){if(e.key==="/"&&!e.shiftKey&&this.refreshSelection(),e.key==="/"&&!e.shiftKey&&this.hasBlockMenu(this.state.selection.focus.blockId))return i(()=>this.openBlockMenu(this.state.selection.focus.blockId));if(n==="v"&&e.shiftKey){this.plainPasteNext=!0;return}}if(e.key.startsWith("Arrow")&&!t&&!e.shiftKey&&!e.altKey&&this.modeValue==="rich"){this.refreshSelection();let a=this.blockPast(e.key);if(a){e.preventDefault(),this.setSelection({anchor:a,focus:a});return}let d=this.imageBlockStep(e.key);if(d){e.preventDefault(),d!==this.state.selection?this.setSelection(d):(e.key==="ArrowDown"||e.key==="ArrowUp")&&this.run(f=>on(f,e.key==="ArrowDown"?1:-1));return}let u=e.key==="ArrowDown"?1:e.key==="ArrowUp"?-1:0,c=u?this.tableCellPast(u):null;if(c){e.preventDefault(),this.setSelection({anchor:c,focus:c});return}let h=u?on(this.state,u):this.state;if(h!==this.state){e.preventDefault(),this.run(()=>h);return}}if(Aa.test(e.key)){this.refreshSelection();let d=!t&&!e.shiftKey&&!e.altKey?e.key==="ArrowDown"?1:e.key==="ArrowUp"?-1:0:0,c={from:L(this.state.doc,this.state.selection.focus.blockId),x:this.selectionRect()?.left??0,vertical:d};this.caretKey=c,d&&this.unlessCaretMoves(c)}}unlessCaretMoves(e){let t=this.state.selection.focus;if(t.cell||!R(this.state.selection))return;let n=se(this.renderer.elementFor(t.blockId)??this.root);!n||!this.onEdgeLine(n,e.vertical===1)||setTimeout(()=>{if(this.destroyed||this.caretKey!==e)return;let i=this.readDomSelection();if(!i||!be(i.focus,t))return;let r=this.state.doc.blocks;for(let s=e.from+e.vertical;s>=0&&s<r.length;s+=e.vertical){let l=r[s];if(this.skipsCaret(l))continue;this.caretKey=null;let a=e.vertical===1?0:l.type==="table"?l.rows.length-1:0,d=l.type==="table"?{blockId:l.id,offset:e.vertical===1?0:B(l.rows[a][0]),cell:{row:a,col:0}}:this.blockEntry(l,e.vertical===1,e.x);this.setSelection({anchor:d,focus:d}),this.scrollCaretIntoView();return}e.vertical===1&&r[r.length-1].type==="detailsEnd"&&(this.caretKey=null,this.run(s=>oi(s)))})}selectBlockText(e){let t=e.closest?.(`[${W}]`);if(!t||!this.root.contains(t))return!1;let n=N(this.state.doc,t.getAttribute(W)),i=e.closest("[data-row]"),r=n.type==="table"&&i?{row:Number(i.dataset.row),col:Number(i.dataset.col)}:void 0,s=F(n,r);if(!s||t.classList.contains("mbe-view-block"))return!1;let l=a=>r?{blockId:n.id,offset:a,cell:r}:{blockId:n.id,offset:a};return this.setSelection({anchor:l(0),focus:l(B(s))}),!0}moveMenu(e,t){e.move(t),this.syncActiveDescendant()}onMouseDown(e){this.caretKey=null;let t=e.target;if(t.closest?.(".mbe-code-copy")){e.preventDefault();return}let n=e.button===0?t.closest?.(".mbe-details-toggle"):null,i=n?.closest(`[${W}]`)?.getAttribute(W);if(i&&this.root.contains(n)){e.preventDefault(),this.setSectionCollapsed(i,!this.collapsed.has(i));return}if(this.dropBlockSelection(),t===this.root&&e.button===0&&!this.readOnly&&this.modeValue==="rich"&&this.clickBelowLastBlock(e))return;let r=e.button===0&&!e.shiftKey&&!this.readOnly?t.closest?.(".mbe-image"):null,s=r&&this.root.contains(r)?this.imageTarget(r):null;if(s){e.preventDefault(),this.selectImageAt(s.pos);return}let l=e.button===0&&!this.readOnly?t.closest?.(".mbe-view, .mbe-view-block"):null;if(l&&this.root.contains(l)){e.preventDefault(),this.revealView(l);return}if(e.button===0&&e.detail===3&&!this.readOnly&&this.modeValue==="rich"&&this.selectBlockText(t)){e.preventDefault();return}let a=e.button===0&&!this.readOnly?t.closest?.(".mbe-callout-icon"):null,d=a?.parentElement?.getAttribute(W);if(a&&d&&a.parentElement.parentElement===this.root){e.preventDefault(),this.openBlockMenu(d,a.getBoundingClientRect());return}e.button===0&&(this.pointerDown=!0),t.classList?.contains("mbe-checkbox")&&(e.preventDefault(),e.button===0&&this.toggleTaskAt(t))}clickBelowLastBlock(e){let t=this.state.doc.blocks,n=t[t.length-1],i=n?Y(n):null;if(!n||n.type!=="code"&&n.type!=="table"&&!Z(n)&&i===null)return!1;let r=this.root.querySelector(`:scope > [data-block-id="${n.id}"]`);if(!r||e.clientY<=r.getBoundingClientRect().bottom)return!1;e.preventDefault(),this.root.focus({preventScroll:!0});let s=P(n),l=i!==null?{anchor:{blockId:n.id,offset:i},focus:{blockId:n.id,offset:i+1}}:{anchor:s,focus:s};return this.run(a=>on({...a,selection:l},1)),!0}onClick(e){let t=e.target;if(t.classList?.contains("mbe-checkbox")){e.preventDefault(),e.detail===0&&this.toggleTaskAt(t);return}let n=t.closest?.(".mbe-code-copy");if(n){e.preventDefault(),this.copyCode(n);return}let i=t.closest?.("a.mbe-link");i&&(e.preventDefault(),(this.readOnly||(ie?e.metaKey:e.ctrlKey))&&this.openHref(i.getAttribute("href"),e))}openHref(e,t){!e||this.runtime.onLinkClick?.({editor:this,href:e,event:t})||this.root.ownerDocument.defaultView?.open(e,"_blank","noopener,noreferrer")}copyCode(e){let t=e.closest(`[${W}]`),n=t&&this.state.doc.blocks.find(u=>u.id===t.getAttribute(W)),i=n?.type==="code"?I(n.content):e.closest(".mbe-flow .mbe-code")?.querySelector("code")?.textContent;if(i==null)return;let r=this.root.ownerDocument,s=u=>{let c=X(r,this.icon(u));e.replaceChildren(...c?[c]:[]),e.setAttribute("aria-label",this.labels[u]),e.title=this.labels[u],e.classList.toggle("mbe-copied",u==="copied")},l=()=>{s("copied"),setTimeout(()=>e.isConnected&&s("copyCode"),1500)},a=()=>{let u=r.createElement("textarea");u.value=i,u.style.cssText="position:fixed;top:0;left:0;opacity:0",r.body.appendChild(u),u.select();let c=r.execCommand("copy");u.remove(),this.syncDomSelection(this.hasFocus()),c&&l()},d=r.defaultView?.navigator.clipboard;d?.writeText?d.writeText(i).then(l,a):a()}onControlChange(e){let t=e.target;if(!(t instanceof HTMLInputElement)||!t.classList.contains("mbe-code-lang"))return;let n=t.closest("[data-block-id]");n&&this.run(i=>ci(i,n.dataset.blockId,t.value.trim()))}onFocusIn(e){this.focused||!this.hasFocus()||(this.focused=!0,this.root.classList.add("mbe-focused"),this.pointerDown||this.refreshRevealed(),this.options.onFocus?.(this),this.emit("focus",{editor:this,event:e}),this.updateUi())}onFocusOut(e){let t=e.relatedTarget;t&&(this.root.contains(t)||this.inputPopover.contains(t))||queueMicrotask(()=>{this.hasFocus()||this.inputPopover.isOpen||this.focused&&(this.focused=!1,this.root.classList.remove("mbe-focused"),this.refreshRevealed(),this.hideUi(),this.flushChange(),this.options.onBlur?.(this),this.emit("blur",{editor:this,event:e}))})}onScroll(){this.blockHandle.hide(),this.linkCard?.reposition(),this.resizeHandles.reposition(),(this.suggestions.isActive||this.toolbar?.isOpen||this.imageToolbar?.isOpen||this.blockMenu.isOpen)&&this.updateUi()}onCopy(e,t){if(this.fromControl(e))return;if(this.modeValue==="source"){if(this.refreshSelection(),R(this.state.selection)||!e.clipboardData)return;e.preventDefault();let{from:d,to:u}=ne(this.state);e.clipboardData.setData("text/plain",K(this.state.doc).slice(d,u)),t&&!this.readOnly&&this.run(c=>Ae(c,""));return}let n=this.blockRange();if(n){if(!e.clipboardData)return;e.preventDefault();let d={blocks:rn(this.state.doc.blocks.slice(n.from,n.to+1).map(dt))};Oa(e.clipboardData,d,Pe(d.blocks,this.markdown)),t&&!this.readOnly&&this.deleteSelectedBlocks();return}if(this.refreshSelection(),R(this.state.selection)||!e.clipboardData)return;e.preventDefault();let i=vi(this.state),r={blocks:rn(i)},s=Pt(r,this.markdown).replace(/\n$/,""),l=i.length===1&&i[0].type==="paragraph"?i[0]:null,a=l&&Q(N(this.state.doc,this.state.selection.focus.blockId));Oa(e.clipboardData,r,s,a?I(l.content):s),t&&!this.readOnly&&this.run(J)}onPaste(e){if(this.fromControl(e)||(e.preventDefault(),this.readOnly))return;this.refreshSelection();for(let c of this.extensions)if(c.handlePaste?.({editor:this,event:e}))return;let t=e.clipboardData;if(!t)return;let n=t.getData("text/plain"),i=t.getData("text/html"),r=t.types.includes("vscode-editor-data")||ds(i)?"":i,s=this.plainPasteNext;if(this.plainPasteNext=!1,this.modeValue==="source"){let c=this.pastedUrl(n,s);if(c!==null){this.run(f=>_l(f,c));return}let h=this.pastedMarkdown(n,r,s);h&&this.run(f=>Ae(f,h.replace(/\r\n?/g,`
120
120
  `)));return}let l=this.blockRange();if(l){let c=this.pastedBlocks(n,r,s);this.blockSel=null,this.run(h=>Gn(h,l,c));return}let a=N(this.state.doc,this.state.selection.focus.blockId);if(Q(a)){this.run(c=>ue(c,n));return}let d=this.pastedUrl(n,s);if(d!==null){this.run(c=>ut(c,d));return}let u=this.pastedBlocks(n,r,s);this.run(c=>Xn(c,u))}pastedMarkdown(e,t,n){return n||!t||Kl(this.state)?e:Ha(t)??(Pt({blocks:no(t).blocks},this.markdown).replace(/\n$/,"")||e)}pastedUrl(e,t){let n=e.trim();return!t&&!R(this.state.selection)&&Wh.test(n)?n:null}pastedBlocks(e,t,n){if(n)return e.replace(/\r\n?/g,`
121
121
  `).split(`
122
122
  `).map(s=>O(ge(s)));let i,r=Ha(t);return r!==null?i=bt(r,this.markdown).blocks:t?i=no(t).blocks:i=bt(e,this.markdown).blocks,i.length===0&&e&&(i=bt(e,this.markdown).blocks),i}onDrop(e){if(e.preventDefault(),this.readOnly)return;let t=this.positionAtPoint(e.clientX,e.clientY);for(let r of this.extensions)if(r.handleDrop?.({editor:this,event:e,position:t}))return;let n=e.dataTransfer?.getData("text/plain");if(!n||!t)return;if(this.modeValue==="source"){this.focus(),this.run(r=>To(r,t.offset,n.replace(/\r\n?/g,`