@blocknote/core 0.39.1 → 0.40.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.
@@ -1,5 +1,5 @@
1
1
  "use strict";var Bt=Object.create;var Q=Object.defineProperty;var vt=Object.getOwnPropertyDescriptor;var Pt=Object.getOwnPropertyNames;var Tt=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var It=(n,o,e)=>o in n?Q(n,o,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[o]=e;var xt=(n,o,e,t)=>{if(o&&typeof o=="object"||typeof o=="function")for(let r of Pt(o))!Et.call(n,r)&&r!==e&&Q(n,r,{get:()=>o[r],enumerable:!(t=vt(o,r))||t.enumerable});return n};var he=(n,o,e)=>(e=n!=null?Bt(Tt(n)):{},xt(o||!n||!n.__esModule?Q(e,"default",{value:n,enumerable:!0}):e,n));var h=(n,o,e)=>It(n,typeof o!="symbol"?o+"":o,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("prosemirror-model"),z=require("prosemirror-transform"),a=require("./BlockNoteSchema-DmZ6UQfY.cjs"),S=require("@tiptap/core"),Mt=require("fast-deep-equal"),pe=require("prosemirror-history"),w=require("prosemirror-state"),Dt=require("prosemirror-dropcursor"),P=require("y-prosemirror"),N=require("prosemirror-tables"),Nt=require("rehype-parse"),Lt=require("rehype-remark"),At=require("remark-gfm"),Ot=require("remark-stringify"),Ee=require("unified"),Ht=require("hast-util-from-dom"),Rt=require("remark-parse"),Ie=require("remark-rehype"),Ut=require("rehype-stringify"),Ft=require("@tiptap/extension-gapcursor"),_t=require("@tiptap/extension-history"),Vt=require("@tiptap/extension-link"),$t=require("@tiptap/extension-text"),zt=require("yjs"),E=require("prosemirror-view"),Kt=require("uuid"),qt=require("./en-D3B48eJ7.cjs"),R=n=>n&&typeof n=="object"&&"default"in n?n:{default:n};function Gt(n){if(n&&typeof n=="object"&&"default"in n)return n;const o=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const e in n)if(e!=="default"){const t=Object.getOwnPropertyDescriptor(n,e);Object.defineProperty(o,e,t.get?t:{enumerable:!0,get:()=>n[e]})}}return o.default=n,Object.freeze(o)}const jt=R(Mt),Wt=R(Nt),Yt=R(Lt),xe=R(At),Xt=R(Ot),Jt=R(Rt),Qt=R(Ie),Zt=R(Ut),H=Gt(zt);function Me(n,o){const e=[{tag:`[data-inline-content-type="${n.type}"]`,contentElement:t=>{const r=t;return r.matches("[data-editable]")?r:r.querySelector("[data-editable]")||r}}];return o&&e.push({tag:"*",getAttrs(t){if(typeof t=="string")return!1;const r=o==null?void 0:o(t);return r===void 0?!1:r}}),e}function eo(n,o){var t;const e=S.Node.create({name:n.type,inline:!0,group:"inline",draggable:(t=o.meta)==null?void 0:t.draggable,selectable:n.content==="styled",atom:n.content==="none",content:n.content==="styled"?"inline*":"",addAttributes(){return a.propsToAttributes(n.propSchema)},addKeyboardShortcuts(){return a.addInlineContentKeyboardShortcuts(n)},parseHTML(){return Me(n,o.parse)},renderHTML({node:r}){const s=this.options.editor,i=o.render.call({renderType:"dom",props:void 0},a.nodeToCustomInlineContent(r,s.schema.inlineContentSchema,s.schema.styleSchema),()=>{},s);return a.addInlineContentAttributes(i,n.type,r.attrs,n.propSchema)},addNodeView(){return r=>{const{node:s,getPos:i}=r,l=this.options.editor,c=o.render.call({renderType:"nodeView",props:r},a.nodeToCustomInlineContent(s,l.schema.inlineContentSchema,l.schema.styleSchema),d=>{const u=a.inlineContentToNodes([d],l.pmSchema),p=i();p&&l.transact(f=>f.replaceWith(p,p+s.nodeSize,u))},l);return a.addInlineContentAttributes(c,n.type,s.attrs,n.propSchema)}}});return a.createInlineContentSpecFromTipTapNode(e,n.propSchema,{toExternalHTML:o.toExternalHTML,render(r,s,i){const l=o.render(r,s,i);return a.addInlineContentAttributes(l,n.type,r.props,n.propSchema)}})}function De(n,o,e,t="before"){const r=typeof e=="string"?e:e.id,s=a.getPmSchema(n),i=o.map(u=>a.blockToNode(u,s)),l=a.getNodeById(r,n.doc);if(!l)throw new Error(`Block with ID ${r} not found`);let c=l.posBeforeNode;return t==="after"&&(c+=l.node.nodeSize),n.step(new z.ReplaceStep(c,c,new T.Slice(T.Fragment.from(i),0,0))),i.map(u=>a.nodeToBlock(u,s))}function ee(n,o,e){const t=a.getPmSchema(n),r=e.map(u=>a.blockToNode(u,t)),s=new Set(o.map(u=>typeof u=="string"?u:u.id)),i=[],l=typeof o[0]=="string"?o[0]:o[0].id;let c=0;if(n.doc.descendants((u,p)=>{if(s.size===0)return!1;if(!u.type.isInGroup("bnBlock")||!s.has(u.attrs.id))return!0;if(i.push(a.nodeToBlock(u,t)),s.delete(u.attrs.id),e.length>0&&u.attrs.id===l){const m=n.doc.nodeSize;n.insert(p,r);const b=n.doc.nodeSize;c+=m-b}const f=n.doc.nodeSize,g=n.doc.resolve(p-c);g.node().type.name==="blockGroup"&&g.node(g.depth-1).type.name!=="doc"&&g.node().childCount===1?n.delete(g.before(),g.after()):n.delete(p-c,p-c+u.nodeSize);const k=n.doc.nodeSize;return c+=f-k,!1}),s.size>0){const u=[...s].join(`
2
2
  `);throw Error("Blocks with the following IDs could not be found in the editor: "+u)}return{insertedBlocks:r.map(u=>a.nodeToBlock(u,t)),removedBlocks:i}}function Ne(n){const o=Array.from(n.classList).filter(e=>!e.startsWith("bn-"))||[];o.length>0?n.className=o.join(" "):n.removeAttribute("class")}function Le(n,o,e,t){var l;let r;if(o)if(typeof o=="string")r=a.inlineContentToNodes([o],n.pmSchema);else if(Array.isArray(o))r=a.inlineContentToNodes(o,n.pmSchema);else if(o.type==="tableContent")r=a.tableContentToNodes(o,n.pmSchema);else throw new a.UnreachableCaseError(o.type);else throw new Error("blockContent is required");const i=((t==null?void 0:t.document)??document).createDocumentFragment();for(const c of r)if(c.type.name!=="text"&&n.schema.inlineContentSchema[c.type.name]){const d=n.schema.inlineContentSpecs[c.type.name].implementation;if(d){const u=a.nodeToCustomInlineContent(c,n.schema.inlineContentSchema,n.schema.styleSchema),p=d.toExternalHTML?d.toExternalHTML(u,n):d.render.call({renderType:"dom",props:void 0},u,()=>{},n);if(p){if(i.appendChild(p.dom),p.contentDOM){const f=e.serializeFragment(c.content,t);p.contentDOM.dataset.editable="",p.contentDOM.appendChild(f)}continue}}}else if(c.type.name==="text"){let d=document.createTextNode(c.textContent);for(const u of c.marks.toReversed())if(u.type.name in n.schema.styleSpecs){const p=(n.schema.styleSpecs[u.type.name].implementation.toExternalHTML??n.schema.styleSpecs[u.type.name].implementation.render)(u.attrs.stringValue,n);p.contentDOM.appendChild(d),d=p.dom}else{const p=u.type.spec.toDOM(u,!0),f=T.DOMSerializer.renderSpec(document,p);f.contentDOM.appendChild(d),d=f.dom}i.appendChild(d)}else{const d=e.serializeFragment(T.Fragment.from([c]),t);i.appendChild(d)}return i.childNodes.length===1&&((l=i.firstChild)==null?void 0:l.nodeType)===1&&Ne(i.firstChild),i}function to(n,o,e,t,r,s,i){var b,y,C,A,B,v,D,I,F;const l=(i==null?void 0:i.document)??document,c=o.pmSchema.nodes.blockContainer,d=e.props||{};for(const[x,M]of Object.entries(o.schema.blockSchema[e.type].propSchema))!(x in d)&&M.default!==void 0&&(d[x]=M.default);const u=(y=(b=c.spec)==null?void 0:b.toDOM)==null?void 0:y.call(b,c.create({id:e.id,...d})),p=Array.from(u.dom.attributes),f=o.blockImplementations[e.type].implementation,g=((C=f.toExternalHTML)==null?void 0:C.call({},{...e,props:d},o))||f.render.call({},{...e,props:d},o),k=l.createDocumentFragment();if(g.dom.classList.contains("bn-block-content")){const x=[...p,...Array.from(g.dom.attributes)].filter(M=>M.name.startsWith("data")&&M.name!=="data-content-type"&&M.name!=="data-file-block"&&M.name!=="data-node-view-wrapper"&&M.name!=="data-node-type"&&M.name!=="data-id"&&M.name!=="data-editable");for(const M of x)g.dom.firstChild.setAttribute(M.name,M.value);Ne(g.dom.firstChild),k.append(...Array.from(g.dom.childNodes))}else k.append(g.dom);if(g.contentDOM&&e.content){const x=Le(o,e.content,t,i);g.contentDOM.appendChild(x)}let m;if(r.has(e.type)?m="OL":s.has(e.type)&&(m="UL"),m){if(((A=n.lastChild)==null?void 0:A.nodeName)!==m){const x=l.createElement(m);m==="OL"&&"start"in d&&d.start&&(d==null?void 0:d.start)!==1&&x.setAttribute("start",d.start+""),n.append(x)}n.lastChild.appendChild(k)}else n.append(k);if(e.children&&e.children.length>0){const x=l.createDocumentFragment();if(Ae(x,o,e.children,t,r,s,i),((B=n.lastChild)==null?void 0:B.nodeName)==="UL"||((v=n.lastChild)==null?void 0:v.nodeName)==="OL")for(;((D=x.firstChild)==null?void 0:D.nodeName)==="UL"||((I=x.firstChild)==null?void 0:I.nodeName)==="OL";)n.lastChild.lastChild.appendChild(x.firstChild);o.pmSchema.nodes[e.type].isInGroup("blockContent")?n.append(x):(F=g.contentDOM)==null||F.append(x)}}const Ae=(n,o,e,t,r,s,i)=>{for(const l of e)to(n,o,l,t,r,s,i)},oo=(n,o,e,t,r,s)=>{const l=((s==null?void 0:s.document)??document).createDocumentFragment();return Ae(l,n,o,e,t,r,s),l},K=(n,o)=>{const e=T.DOMSerializer.fromSchema(n);return{exportBlocks:(t,r)=>{const s=oo(o,t,e,new Set(["numberedListItem"]),new Set(["bulletListItem","checkListItem"]),r),i=document.createElement("div");return i.append(s),i.innerHTML},exportInlineContent:(t,r)=>{const s=Le(o,t,e,r),i=document.createElement("div");return i.append(s.cloneNode(!0)),i.innerHTML}}};function no(n,o,e,t,r){let s;if(o)if(typeof o=="string")s=a.inlineContentToNodes([o],n.pmSchema,t);else if(Array.isArray(o))s=a.inlineContentToNodes(o,n.pmSchema,t);else if(o.type==="tableContent")s=a.tableContentToNodes(o,n.pmSchema);else throw new a.UnreachableCaseError(o.type);else throw new Error("blockContent is required");const l=((r==null?void 0:r.document)??document).createDocumentFragment();for(const c of s)if(c.type.name!=="text"&&n.schema.inlineContentSchema[c.type.name]){const d=n.schema.inlineContentSpecs[c.type.name].implementation;if(d){const u=a.nodeToCustomInlineContent(c,n.schema.inlineContentSchema,n.schema.styleSchema),p=d.render.call({renderType:"dom",props:void 0},u,()=>{},n);if(p){if(l.appendChild(p.dom),p.contentDOM){const f=e.serializeFragment(c.content,r);p.contentDOM.dataset.editable="",p.contentDOM.appendChild(f)}continue}}}else if(c.type.name==="text"){let d=document.createTextNode(c.textContent);for(const u of c.marks.toReversed())if(u.type.name in n.schema.styleSpecs){const p=n.schema.styleSpecs[u.type.name].implementation.render(u.attrs.stringValue,n);p.contentDOM.appendChild(d),d=p.dom}else{const p=u.type.spec.toDOM(u,!0),f=T.DOMSerializer.renderSpec(document,p);f.contentDOM.appendChild(d),d=f.dom}l.appendChild(d)}else{const d=e.serializeFragment(T.Fragment.from([c]),r);l.appendChild(d)}return l}function ro(n,o,e,t){var u,p,f,g,k;const r=n.pmSchema.nodes.blockContainer,s=o.props||{};for(const[m,b]of Object.entries(n.schema.blockSchema[o.type].propSchema))!(m in s)&&b.default!==void 0&&(s[m]=b.default);const l=n.blockImplementations[o.type].implementation.render.call({renderType:"dom",props:void 0},{...o,props:s},n);if(l.contentDOM&&o.content){const m=no(n,o.content,e,o.type,t);l.contentDOM.appendChild(m)}if(n.pmSchema.nodes[o.type].isInGroup("bnBlock")){if(o.children&&o.children.length>0){const m=Oe(n,o.children,e,t);(u=l.contentDOM)==null||u.append(m)}return l.dom}const d=(f=(p=r.spec)==null?void 0:p.toDOM)==null?void 0:f.call(p,r.create({id:o.id,...s}));return(g=d.contentDOM)==null||g.appendChild(l.dom),o.children&&o.children.length>0&&((k=d.contentDOM)==null||k.appendChild(He(n,o.children,e,t))),d.dom}function Oe(n,o,e,t){const s=((t==null?void 0:t.document)??document).createDocumentFragment();for(const i of o){const l=ro(n,i,e,t);s.appendChild(l)}return s}const He=(n,o,e,t)=>{var l;const r=n.pmSchema.nodes.blockGroup,s=r.spec.toDOM(r.create({})),i=Oe(n,o,e,t);return(l=s.contentDOM)==null||l.appendChild(i),s.dom},Re=(n,o)=>{const e=T.DOMSerializer.fromSchema(n);return{serializeBlocks:(t,r)=>He(o,t,e,r).outerHTML}};function so(n,o){if(o===0)return;const e=n.resolve(o);for(let t=e.depth;t>0;t--){const r=e.node(t);if(a.isNodeBlock(r))return r.attrs.id}}function io(n){return n.getMeta("paste")?{type:"paste"}:n.getMeta("uiEvent")==="drop"?{type:"drop"}:n.getMeta("history$")?{type:n.getMeta("history$").redo?"redo":"undo"}:n.getMeta("y-sync$")?n.getMeta("y-sync$").isUndoRedoOperation?{type:"undo-redo"}:{type:"yjs-remote"}:{type:"local"}}function me(n){const o="__root__",e={},t={},r=a.getPmSchema(n);return n.descendants((s,i)=>{if(!a.isNodeBlock(s))return!0;const l=so(n,i),c=l??o;t[c]||(t[c]=[]);const d=a.nodeToBlock(s,r);return e[s.attrs.id]={block:d,parentId:l},t[c].push(s.attrs.id),!0}),{byId:e,childrenByParent:t}}function ao(n,o){const e=new Set;if(!n||!o)return e;const t=new Set(n),r=o.filter(m=>t.has(m)),s=n.filter(m=>r.includes(m));if(s.length<=1||r.length<=1)return e;const i={};for(let m=0;m<s.length;m++)i[s[m]]=m;const l=r.map(m=>i[m]),c=l.length,d=[],u=[],p=new Array(c).fill(-1),f=(m,b)=>{let y=0,C=m.length;for(;y<C;){const A=y+C>>>1;m[A]<b?y=A+1:C=A}return y};for(let m=0;m<c;m++){const b=l[m],y=f(d,b);y>0&&(p[m]=u[y-1]),y===d.length?(d.push(b),u.push(m)):(d[y]=b,u[y]=m)}const g=new Set;let k=u[u.length-1]??-1;for(;k!==-1;)g.add(k),k=p[k];for(let m=0;m<r.length;m++)g.has(m)||e.add(r[m]);return e}function se(n,o=[]){const e=io(n),t=S.combineTransactionSteps(n.before,[n,...o]),r=me(t.before),s=me(t.doc),i=[],l=new Set;Object.keys(s.byId).filter(g=>!(g in r.byId)).forEach(g=>{i.push({type:"insert",block:s.byId[g].block,source:e,prevBlock:void 0}),l.add(g)}),Object.keys(r.byId).filter(g=>!(g in s.byId)).forEach(g=>{i.push({type:"delete",block:r.byId[g].block,source:e,prevBlock:void 0}),l.add(g)}),Object.keys(s.byId).filter(g=>g in r.byId).forEach(g=>{var y,C;const k=r.byId[g],m=s.byId[g];k.parentId!==m.parentId?(i.push({type:"move",block:m.block,prevBlock:k.block,source:e,prevParent:k.parentId?(y=r.byId[k.parentId])==null?void 0:y.block:void 0,currentParent:m.parentId?(C=s.byId[m.parentId])==null?void 0:C.block:void 0}),l.add(g)):jt.default({...k.block,children:void 0},{...m.block,children:void 0})||(i.push({type:"update",block:m.block,prevBlock:k.block,source:e}),l.add(g))});const c=r.childrenByParent,d=s.childrenByParent,u="__root__",p=new Set([...Object.keys(c),...Object.keys(d)]),f=new Set;return p.forEach(g=>{const k=ao(c[g],d[g]);k.size!==0&&k.forEach(m=>{var A,B;const b=r.byId[m],y=s.byId[m];!b||!y||b.parentId!==y.parentId||l.has(m)||(b.parentId??u)!==g||f.has(m)||(f.add(m),i.push({type:"move",block:y.block,prevBlock:b.block,source:e,prevParent:b.parentId?(A=r.byId[b.parentId])==null?void 0:A.block:void 0,currentParent:y.parentId?(B=s.byId[y.parentId])==null?void 0:B.block:void 0}),l.add(m))})}),i}function co(n){return n.transact(o=>{const e=a.getNearestBlockPos(o.doc,o.selection.anchor);if(o.selection instanceof N.CellSelection)return{type:"cell",anchorBlockId:e.node.attrs.id,anchorCellOffset:o.selection.$anchorCell.pos-e.posBeforeNode,headCellOffset:o.selection.$headCell.pos-e.posBeforeNode};if(o.selection instanceof w.NodeSelection)return{type:"node",anchorBlockId:e.node.attrs.id};{const t=a.getNearestBlockPos(o.doc,o.selection.head);return{type:"text",anchorBlockId:e.node.attrs.id,headBlockId:t.node.attrs.id,anchorOffset:o.selection.anchor-e.posBeforeNode,headOffset:o.selection.head-t.posBeforeNode}}})}function lo(n,o){var r,s;const e=(r=a.getNodeById(o.anchorBlockId,n.doc))==null?void 0:r.posBeforeNode;if(e===void 0)throw new Error(`Could not find block with ID ${o.anchorBlockId} to update selection`);let t;if(o.type==="cell")t=N.CellSelection.create(n.doc,e+o.anchorCellOffset,e+o.headCellOffset);else if(o.type==="node")t=w.NodeSelection.create(n.doc,e+1);else{const i=(s=a.getNodeById(o.headBlockId,n.doc))==null?void 0:s.posBeforeNode;if(i===void 0)throw new Error(`Could not find block with ID ${o.headBlockId} to update selection`);t=w.TextSelection.create(n.doc,e+o.anchorOffset,i+o.headOffset)}n.setSelection(t)}function te(n){return n.map(o=>o.type==="columnList"?o.children.map(e=>te(e.children)).flat():{...o,children:te(o.children)}).flat()}function Ue(n,o,e){n.transact(t=>{var i;const r=((i=n.getSelection())==null?void 0:i.blocks)||[n.getTextCursorPosition().block],s=co(n);n.removeBlocks(r),n.insertBlocks(te(r),o,e),lo(t,s)})}function Fe(n){return!n||n.type!=="columnList"}function _e(n,o,e){let t,r;if(o?o.children.length>0?(t=o.children[o.children.length-1],r="after"):(t=o,r="before"):e&&(t=e,r="before"),!t||!r)return;const s=n.getParentBlock(t);return Fe(s)?{referenceBlock:t,placement:r}:_e(n,r==="after"?t:n.getPrevBlock(t),s)}function Ve(n,o,e){let t,r;if(o?o.children.length>0?(t=o.children[0],r="before"):(t=o,r="after"):e&&(t=e,r="after"),!t||!r)return;const s=n.getParentBlock(t);return Fe(s)?{referenceBlock:t,placement:r}:Ve(n,r==="before"?t:n.getNextBlock(t),s)}function uo(n){n.transact(()=>{const o=n.getSelection(),e=(o==null?void 0:o.blocks[0])||n.getTextCursorPosition().block,t=_e(n,n.getPrevBlock(e),n.getParentBlock(e));t&&Ue(n,t.referenceBlock,t.placement)})}function ho(n){n.transact(()=>{const o=n.getSelection(),e=(o==null?void 0:o.blocks[(o==null?void 0:o.blocks.length)-1])||n.getTextCursorPosition().block,t=Ve(n,n.getNextBlock(e),n.getParentBlock(e));t&&Ue(n,t.referenceBlock,t.placement)})}function po(n,o,e){const{$from:t,$to:r}=n.selection,s=t.blockRange(r,k=>k.childCount>0&&(k.type.name==="blockGroup"||k.type.name==="column"));if(!s)return!1;const i=s.startIndex;if(i===0)return!1;const c=s.parent.child(i-1);if(c.type!==o)return!1;const d=c.lastChild&&c.lastChild.type===e,u=T.Fragment.from(d?o.create():null),p=new T.Slice(T.Fragment.from(o.create(null,T.Fragment.from(e.create(null,u)))),d?3:1,0),f=s.start,g=s.end;return n.step(new z.ReplaceAroundStep(f-(d?3:1),g,f,g,p,1,!0)).scrollIntoView(),!0}function $e(n){return n.transact(o=>po(o,n.pmSchema.nodes.blockContainer,n.pmSchema.nodes.blockGroup))}function mo(n){n._tiptapEditor.commands.liftListItem("blockContainer")}function fo(n){return n.transact(o=>{const{bnBlock:e}=a.getBlockInfoFromTransaction(o);return o.doc.resolve(e.beforePos).nodeBefore!==null})}function go(n){return n.transact(o=>{const{bnBlock:e}=a.getBlockInfoFromTransaction(o);return o.doc.resolve(e.beforePos).depth>1})}function ze(n,o){const e=typeof o=="string"?o:o.id,t=a.getPmSchema(n),r=a.getNodeById(e,n);if(r)return a.nodeToBlock(r.node,t)}function Ke(n,o){const e=typeof o=="string"?o:o.id,t=a.getNodeById(e,n),r=a.getPmSchema(n);if(!t)return;const i=n.resolve(t.posBeforeNode).nodeBefore;if(i)return a.nodeToBlock(i,r)}function qe(n,o){const e=typeof o=="string"?o:o.id,t=a.getNodeById(e,n),r=a.getPmSchema(n);if(!t)return;const i=n.resolve(t.posBeforeNode+t.node.nodeSize).nodeAfter;if(i)return a.nodeToBlock(i,r)}function Ge(n,o){const e=typeof o=="string"?o:o.id,t=a.getPmSchema(n),r=a.getNodeById(e,n);if(!r)return;const s=n.resolve(r.posBeforeNode),i=s.node(),l=s.node(-1),c=l.type.name!=="doc"?i.type.name==="blockGroup"?l:i:void 0;if(c)return a.nodeToBlock(c,t)}function ko(n,o,e,t={updateSelection:!0}){let{from:r,to:s}=typeof o=="number"?{from:o,to:o}:{from:o.from,to:o.to},i=!0,l=!0,c="";if(e.forEach(d=>{d.check(),i&&d.isText&&d.marks.length===0?c+=d.text:i=!1,l=l?d.isBlock:!1}),r===s&&l){const{parent:d}=n.doc.resolve(r);d.isTextblock&&!d.type.spec.code&&!d.childCount&&(r-=1,s+=1)}return i?n.insertText(c,r,s):n.replaceWith(r,s,e),t.updateSelection&&S.selectionToInsertionEnd(n,n.steps.length-1,-1),!0}function bo(n){const o=a.getPmSchema(n);if(n.selection.empty||"node"in n.selection)return;const e=n.doc.resolve(a.getNearestBlockPos(n.doc,n.selection.from).posBeforeNode),t=n.doc.resolve(a.getNearestBlockPos(n.doc,n.selection.to).posBeforeNode),r=(d,u)=>{const p=e.posAtIndex(d,u),f=n.doc.resolve(p).nodeAfter;if(!f)throw new Error(`Error getting selection - node not found at position ${p}`);return a.nodeToBlock(f,o)},s=[],i=e.sharedDepth(t.pos),l=e.index(i),c=t.index(i);if(e.depth>i){s.push(a.nodeToBlock(e.nodeAfter,o));for(let d=e.depth;d>i;d--)if(e.node(d).type.isInGroup("childContainer")){const p=e.index(d)+1,f=e.node(d).childCount;for(let g=p;g<f;g++)s.push(r(g,d))}}else s.push(r(l,i));for(let d=l+1;d<=c;d++)s.push(r(d,i));if(s.length===0)throw new Error(`Error getting selection - selection doesn't span any blocks (${n.selection})`);return{blocks:s}}function yo(n,o,e){const t=typeof o=="string"?o:o.id,r=typeof e=="string"?e:e.id,s=a.getPmSchema(n),i=a.getBlockNoteSchema(s);if(t===r)throw new Error(`Attempting to set selection with the same anchor and head blocks (id ${t})`);const l=a.getNodeById(t,n.doc);if(!l)throw new Error(`Block with ID ${t} not found`);const c=a.getNodeById(r,n.doc);if(!c)throw new Error(`Block with ID ${r} not found`);const d=a.getBlockInfo(l),u=a.getBlockInfo(c),p=i.blockSchema[d.blockNoteType],f=i.blockSchema[u.blockNoteType];if(!d.isBlockContainer||p.content==="none")throw new Error(`Attempting to set selection anchor in block without content (id ${t})`);if(!u.isBlockContainer||f.content==="none")throw new Error(`Attempting to set selection anchor in block without content (id ${r})`);let g,k;if(p.content==="table"){const m=N.TableMap.get(d.blockContent.node);g=d.blockContent.beforePos+m.positionAt(0,0,d.blockContent.node)+1+2}else g=d.blockContent.beforePos+1;if(f.content==="table"){const m=N.TableMap.get(u.blockContent.node),b=u.blockContent.beforePos+m.positionAt(m.height-1,m.width-1,u.blockContent.node)+1,y=n.doc.resolve(b).nodeAfter.nodeSize;k=b+y-2}else k=u.blockContent.afterPos-1;n.setSelection(w.TextSelection.create(n.doc,g,k))}function wo(n){const o=a.getPmSchema(n);let e=n.selection.$from,t=n.selection.$to;for(;t.parentOffset>=t.parent.nodeSize-2&&t.depth>0;)t=n.doc.resolve(t.pos+1);for(;t.parentOffset===0&&t.depth>0;)t=n.doc.resolve(t.pos-1);for(;e.parentOffset===0&&e.depth>0;)e=n.doc.resolve(e.pos-1);for(;e.parentOffset>=e.parent.nodeSize-2&&e.depth>0;)e=n.doc.resolve(e.pos+1);const r=a.prosemirrorSliceToSlicedBlocks(n.doc.slice(e.pos,t.pos,!0),o);return{_meta:{startPos:e.pos,endPos:t.pos},...r}}function So(n){const{bnBlock:o}=a.getBlockInfoFromTransaction(n),e=a.getPmSchema(n.doc),t=n.doc.resolve(o.beforePos),r=t.nodeBefore,s=n.doc.resolve(o.afterPos).nodeAfter;let i;return t.depth>1&&(i=t.node(),i.type.isInGroup("bnBlock")||(i=t.node(t.depth-1))),{block:a.nodeToBlock(o.node,e),prevBlock:r===null?void 0:a.nodeToBlock(r,e),nextBlock:s===null?void 0:a.nodeToBlock(s,e),parentBlock:i===void 0?void 0:a.nodeToBlock(i,e)}}function je(n,o,e="start"){const t=typeof o=="string"?o:o.id,r=a.getPmSchema(n.doc),s=a.getBlockNoteSchema(r),i=a.getNodeById(t,n.doc);if(!i)throw new Error(`Block with ID ${t} not found`);const l=a.getBlockInfo(i),c=s.blockSchema[l.blockNoteType].content;if(l.isBlockContainer){const d=l.blockContent;if(c==="none"){n.setSelection(w.NodeSelection.create(n.doc,d.beforePos));return}if(c==="inline")e==="start"?n.setSelection(w.TextSelection.create(n.doc,d.beforePos+1)):n.setSelection(w.TextSelection.create(n.doc,d.afterPos-1));else if(c==="table")e==="start"?n.setSelection(w.TextSelection.create(n.doc,d.beforePos+4)):n.setSelection(w.TextSelection.create(n.doc,d.afterPos-4));else throw new a.UnreachableCaseError(c)}else{const d=e==="start"?l.childContainer.node.firstChild:l.childContainer.node.lastChild;je(n,d.attrs.id,e)}}function Co(){const n=o=>{let e=o.children.length;for(let t=0;t<e;t++){const r=o.children[t];if(r.type==="element"&&(n(r),r.tagName==="u"))if(r.children.length>0){o.children.splice(t,1,...r.children);const s=r.children.length-1;e+=s,t+=s}else o.children.splice(t,1),e--,t--}};return n}function Bo(){const n=o=>{var e;if(o.children&&"length"in o.children&&o.children.length)for(let t=o.children.length-1;t>=0;t--){const r=o.children[t],s=t+1<o.children.length?o.children[t+1]:void 0;r.type==="element"&&r.tagName==="input"&&((e=r.properties)==null?void 0:e.type)==="checkbox"&&(s==null?void 0:s.type)==="element"&&s.tagName==="p"?(s.tagName="span",s.children.splice(0,0,Ht.fromDom(document.createTextNode(" ")))):n(r)}};return n}function J(n){return Ee.unified().use(Wt.default,{fragment:!0}).use(Co).use(Bo).use(Yt.default).use(xe.default).use(Xt.default,{handlers:{text:e=>e.value}}).processSync(n).value}function We(n,o,e,t){const s=K(o,e).exportBlocks(n,t);return J(s)}function vo(n){return Array.prototype.indexOf.call(n.parentElement.childNodes,n)}function Po(n){return n.nodeType===3&&!/\S/.test(n.nodeValue||"")}function To(n){n.querySelectorAll("li > ul, li > ol").forEach(o=>{const e=vo(o),t=o.parentElement,r=Array.from(t.childNodes).slice(e+1);o.remove(),r.forEach(s=>{s.remove()}),t.insertAdjacentElement("afterend",o),r.reverse().forEach(s=>{if(Po(s))return;const i=document.createElement("li");i.append(s),o.insertAdjacentElement("afterend",i)}),t.childNodes.length===0&&t.remove()})}function Eo(n){n.querySelectorAll("li + ul, li + ol").forEach(o=>{var s,i;const e=o.previousElementSibling,t=document.createElement("div");e.insertAdjacentElement("afterend",t),t.append(e);const r=document.createElement("div");for(r.setAttribute("data-node-type","blockGroup"),t.append(r);((s=t.nextElementSibling)==null?void 0:s.nodeName)==="UL"||((i=t.nextElementSibling)==null?void 0:i.nodeName)==="OL";)r.append(t.nextElementSibling)})}let fe=null;function Io(){return fe||(fe=document.implementation.createHTMLDocument("title"))}function xo(n){if(typeof n=="string"){const o=Io().createElement("div");o.innerHTML=n,n=o}return To(n),Eo(n),n}function ie(n,o){const e=xo(n),r=T.DOMParser.fromSchema(o).parse(e,{topNode:o.nodes.blockGroup.create()}),s=[];for(let i=0;i<r.childCount;i++)s.push(a.nodeToBlock(r.child(i),o));return s}function Mo(n,o){const e=o.value?o.value:"",t={};o.lang&&(t["data-language"]=o.lang);let r={type:"element",tagName:"code",properties:t,children:[{type:"text",value:e}]};return o.meta&&(r.data={meta:o.meta}),n.patch(o,r),r=n.applyData(o,r),r={type:"element",tagName:"pre",properties:{},children:[r]},n.patch(o,r),r}function ae(n){return Ee.unified().use(Jt.default).use(xe.default).use(Qt.default,{handlers:{...Ie.defaultHandlers,code:Mo}}).use(Zt.default).processSync(n).value}function Ye(n,o){const e=ae(n);return ie(e,o)}const ce=["vscode-editor-data","blocknote/html","text/markdown","text/html","text/plain","Files"];function Do(n,o){if(!n.startsWith(".")||!o.startsWith("."))throw new Error("The strings provided are not valid file extensions.");return n===o}function No(n,o){const e=n.split("/"),t=o.split("/");if(e.length!==2)throw new Error(`The string ${n} is not a valid MIME type.`);if(t.length!==2)throw new Error(`The string ${o} is not a valid MIME type.`);return e[1]==="*"||t[1]==="*"?e[0]===t[0]:(e[0]==="*"||t[0]==="*"||e[0]===t[0])&&e[1]===t[1]}function ge(n,o,e,t="after"){let r;return Array.isArray(o.content)&&o.content.length===0?r=n.updateBlock(o,e).id:r=n.insertBlocks([e],o,t)[0].id,r}async function Xe(n,o){var s;if(!o.uploadFile){console.warn("Attempted ot insert file, but uploadFile is not set in the BlockNote editor options");return}const e="dataTransfer"in n?n.dataTransfer:n.clipboardData;if(e===null)return;let t=null;for(const i of ce)if(e.types.includes(i)){t=i;break}if(t!=="Files")return;const r=e.items;if(r){n.preventDefault();for(let i=0;i<r.length;i++){let l="file";for(const d of Object.values(o.schema.blockSpecs))for(const u of((s=d.implementation.meta)==null?void 0:s.fileBlockAccept)||[]){const p=u.startsWith("."),f=r[i].getAsFile();if(f&&(!p&&f.type&&No(r[i].type,u)||p&&Do("."+f.name.split(".").pop(),u))){l=d.config.type;break}}const c=r[i].getAsFile();if(c){const d={type:l,props:{name:c.name}};let u;if(n.type==="paste"){const g=o.getTextCursorPosition().block;u=ge(o,g,d)}else if(n.type==="drop"){const g={left:n.clientX,top:n.clientY},k=o.prosemirrorView.posAtCoords(g);if(!k)return;u=o.transact(m=>{const b=a.getNearestBlockPos(m.doc,k.pos),y=o.prosemirrorView.dom.querySelector(`[data-id="${b.node.attrs.id}"]`),C=y==null?void 0:y.getBoundingClientRect();return ge(o,o.getBlock(b.node.attrs.id),d,C&&(C.top+C.bottom)/2>g.top?"before":"after")})}else return;const p=await o.uploadFile(c,u),f=typeof p=="string"?{props:{url:p}}:{...p};o.updateBlock(u,f)}}}}const Lo=n=>S.Extension.create({name:"dropFile",addProseMirrorPlugins(){return[new w.Plugin({props:{handleDOMEvents:{drop(o,e){if(!n.isEditable)return;let t=null;for(const r of ce)if(e.dataTransfer.types.includes(r)){t=r;break}return t===null?!0:t==="Files"?(Xe(e,n),!0):!1}}}})]}}),Ao=/(^|\n) {0,3}#{1,6} {1,8}[^\n]{1,64}\r?\n\r?\n\s{0,32}\S/,Oo=/(_|__|\*|\*\*|~~|==|\+\+)(?!\s)(?:[^\s](?:.{0,62}[^\s])?|\S)(?=\1)/,Ho=/\[[^\]]{1,128}\]\(https?:\/\/\S{1,999}\)/,Ro=/(?:\s|^)`(?!\s)(?:[^\s`](?:[^`]{0,46}[^\s`])?|[^\s`])`([^\w]|$)/,Uo=/(?:^|\n)\s{0,5}-\s{1}[^\n]+\n\s{0,15}-\s/,Fo=/(?:^|\n)\s{0,5}\d+\.\s{1}[^\n]+\n\s{0,15}\d+\.\s/,_o=/\n{2} {0,3}-{2,48}\n{2}/,Vo=/(?:\n|^)(```|~~~|\$\$)(?!`|~)[^\s]{0,64} {0,64}[^\n]{0,64}\n[\s\S]{0,9999}?\s*\1 {0,64}(?:\n+|$)/,$o=/(?:\n|^)(?!\s)\w[^\n]{0,64}\r?\n(-|=)\1{0,64}\n\n\s{0,64}(\w|$)/,zo=/(?:^|(\r?\n\r?\n))( {0,3}>[^\n]{1,333}\n){1,999}($|(\r?\n))/,Ko=/^\s*\|(.+\|)+\s*$/m,qo=/^\s*\|(\s*[-:]+[-:]\s*\|)+\s*$/m,Go=/^\s*\|(.+\|)+\s*$/m,jo=n=>Ao.test(n)||Oo.test(n)||Ho.test(n)||Ro.test(n)||Uo.test(n)||Fo.test(n)||_o.test(n)||Vo.test(n)||$o.test(n)||zo.test(n)||Ko.test(n)||qo.test(n)||Go.test(n);async function Wo(n,o){const{schema:e}=o.state;if(!n.clipboardData)return!1;const t=n.clipboardData.getData("text/plain");if(!t)return!1;if(!e.nodes.codeBlock)return o.pasteText(t),!0;const r=n.clipboardData.getData("vscode-editor-data"),s=r?JSON.parse(r):void 0,i=s==null?void 0:s.mode;return i?(o.pasteHTML(`<pre><code class="language-${i}">${t.replace(/\r\n?/g,`
3
3
  `)}</code></pre>`),!0):!1}function Yo({event:n,editor:o,prioritizeMarkdownOverHTML:e,plainTextAsMarkdown:t}){var l;if(o.transact(c=>c.selection.$from.parent.type.spec.code&&c.selection.$to.parent.type.spec.code)){const c=(l=n.clipboardData)==null?void 0:l.getData("text/plain");if(c)return o.pasteText(c),!0}let s;for(const c of ce)if(n.clipboardData.types.includes(c)){s=c;break}if(!s)return!0;if(s==="vscode-editor-data")return Wo(n,o.prosemirrorView),!0;if(s==="Files")return Xe(n,o),!0;const i=n.clipboardData.getData(s);if(s==="blocknote/html")return o.pasteHTML(i,!0),!0;if(s==="text/markdown")return o.pasteMarkdown(i),!0;if(e){const c=n.clipboardData.getData("text/plain");if(jo(c))return o.pasteMarkdown(c),!0}return s==="text/html"?(o.pasteHTML(i),!0):t?(o.pasteMarkdown(i),!0):(o.pasteText(i),!0)}const Xo=(n,o)=>S.Extension.create({name:"pasteFromClipboard",addProseMirrorPlugins(){return[new w.Plugin({props:{handleDOMEvents:{paste(e,t){if(t.preventDefault(),!!n.isEditable)return o({event:t,editor:n,defaultPasteHandler:({prioritizeMarkdownOverHTML:r=!0,plainTextAsMarkdown:s=!0}={})=>Yo({event:t,editor:n,prioritizeMarkdownOverHTML:r,plainTextAsMarkdown:s})})}}}})]}});function Je(n){const o=[];return n.descendants(e=>{var r,s;const t=a.getPmSchema(e);return e.type.name==="blockContainer"&&((r=e.firstChild)==null?void 0:r.type.name)==="blockGroup"?!0:e.type.name==="columnList"&&e.childCount===1?((s=e.firstChild)==null||s.forEach(i=>{o.push(a.nodeToBlock(i,t))}),!1):e.type.isInGroup("bnBlock")?(o.push(a.nodeToBlock(e,t)),!1):!0}),o}function Jo(n,o,e){var l;let t=!1;const r=n.state.selection instanceof N.CellSelection;if(!r){const c=n.state.doc.slice(n.state.selection.from,n.state.selection.to,!1).content,d=[];for(let u=0;u<c.childCount;u++)d.push(c.child(u));t=d.find(u=>u.type.isInGroup("bnBlock")||u.type.name==="blockGroup"||u.type.spec.group==="blockContent")===void 0,t&&(o=c)}let s;const i=K(n.state.schema,e);if(r){((l=o.firstChild)==null?void 0:l.type.name)==="table"&&(o=o.firstChild.content);const c=a.contentNodeToTableContent(o,e.schema.inlineContentSchema,e.schema.styleSchema);s=`<table>${i.exportInlineContent(c,{})}</table>`}else if(t){const c=a.contentNodeToInlineContent(o,e.schema.inlineContentSchema,e.schema.styleSchema);s=i.exportInlineContent(c,{})}else{const c=Je(o);s=i.exportBlocks(c,{})}return s}function le(n,o){"node"in n.state.selection&&n.state.selection.node.type.spec.group==="blockContent"&&o.transact(i=>i.setSelection(new w.NodeSelection(i.doc.resolve(n.state.selection.from-1))));const e=n.serializeForClipboard(n.state.selection.content()).dom.innerHTML,t=n.state.selection.content().content,r=Jo(n,t,o),s=J(r);return{clipboardHTML:e,externalHTML:r,markdown:s}}const ke=()=>{const n=window.getSelection();if(!n||n.isCollapsed)return!0;let o=n.focusNode;for(;o;){if(o instanceof HTMLElement&&o.getAttribute("contenteditable")==="false")return!0;o=o.parentElement}return!1},be=(n,o,e)=>{e.preventDefault(),e.clipboardData.clearData();const{clipboardHTML:t,externalHTML:r,markdown:s}=le(o,n);e.clipboardData.setData("blocknote/html",t),e.clipboardData.setData("text/html",r),e.clipboardData.setData("text/plain",s)},Qo=n=>S.Extension.create({name:"copyToClipboard",addProseMirrorPlugins(){return[new w.Plugin({props:{handleDOMEvents:{copy(o,e){return ke()||be(n,o,e),!0},cut(o,e){return ke()||(be(n,o,e),o.editable&&o.dispatch(o.state.tr.deleteSelection())),!0},dragstart(o,e){if(!("node"in o.state.selection)||o.state.selection.node.type.spec.group!=="blockContent")return;n.transact(i=>i.setSelection(new w.NodeSelection(i.doc.resolve(o.state.selection.from-1)))),e.preventDefault(),e.dataTransfer.clearData();const{clipboardHTML:t,externalHTML:r,markdown:s}=le(o,n);return e.dataTransfer.setData("blocknote/html",t),e.dataTransfer.setData("text/html",r),e.dataTransfer.setData("text/plain",s),!0}}}})]}}),Zo=S.Extension.create({name:"blockBackgroundColor",addGlobalAttributes(){return[{types:["tableCell","tableHeader"],attributes:{backgroundColor:a.getBackgroundColorAttribute()}}]}});class en extends a.BlockNoteExtension{constructor(){super();h(this,"beforeChangeCallbacks",[]);this.addProsemirrorPlugin(new w.Plugin({key:new w.PluginKey("blockChange"),filterTransaction:e=>{let t;return this.beforeChangeCallbacks.reduce((r,s)=>r===!1?r:s({getChanges(){return t||(t=se(e),t)},tr:e})!==!1,!0)}}))}static key(){return"blockChange"}subscribe(e){return this.beforeChangeCallbacks.push(e),()=>{this.beforeChangeCallbacks=this.beforeChangeCallbacks.filter(t=>t!==e)}}}const V=class V extends a.BlockNoteExtension{constructor(e){super();h(this,"provider");h(this,"recentlyUpdatedCursors");h(this,"renderCursor",(e,t)=>{let r=this.recentlyUpdatedCursors.get(t);if(!r){const s=(this.collaboration.renderCursor??V.defaultCursorRender)(e);this.collaboration.showCursorLabels!=="always"&&(s.addEventListener("mouseenter",()=>{const i=this.recentlyUpdatedCursors.get(t);i.element.setAttribute("data-active",""),i.hideTimeout&&(clearTimeout(i.hideTimeout),this.recentlyUpdatedCursors.set(t,{element:i.element,hideTimeout:void 0}))}),s.addEventListener("mouseleave",()=>{const i=this.recentlyUpdatedCursors.get(t);this.recentlyUpdatedCursors.set(t,{element:i.element,hideTimeout:setTimeout(()=>{i.element.removeAttribute("data-active")},2e3)})})),r={element:s,hideTimeout:void 0},this.recentlyUpdatedCursors.set(t,r)}return r.element});h(this,"updateUser",e=>{this.provider.awareness.setLocalStateField("user",e)});this.collaboration=e,this.provider=e.provider,this.recentlyUpdatedCursors=new Map,this.provider.awareness.setLocalStateField("user",e.user),e.showCursorLabels!=="always"&&this.provider.awareness.on("change",({updated:t})=>{for(const r of t){const s=this.recentlyUpdatedCursors.get(r);s&&(s.element.setAttribute("data-active",""),s.hideTimeout&&clearTimeout(s.hideTimeout),this.recentlyUpdatedCursors.set(r,{element:s.element,hideTimeout:setTimeout(()=>{s.element.removeAttribute("data-active")},2e3)}))}}),this.addProsemirrorPlugin(P.yCursorPlugin(this.provider.awareness,{selectionBuilder:P.defaultSelectionBuilder,cursorBuilder:this.renderCursor}))}static key(){return"yCursorPlugin"}get priority(){return 999}static isDarkColor(e){const t=e.charAt(0)==="#"?e.substring(1,7):e,r=parseInt(t.substring(0,2),16),s=parseInt(t.substring(2,4),16),i=parseInt(t.substring(4,6),16),c=[r/255,s/255,i/255].map(u=>u<=.03928?u/12.92:Math.pow((u+.055)/1.055,2.4));return .2126*c[0]+.7152*c[1]+.0722*c[2]<=.179}};h(V,"defaultCursorRender",e=>{const t=document.createElement("span");t.classList.add("bn-collaboration-cursor__base");const r=document.createElement("span");r.setAttribute("contentedEditable","false"),r.classList.add("bn-collaboration-cursor__caret"),r.setAttribute("style",`background-color: ${e.color}; color: ${V.isDarkColor(e.color)?"white":"black"}`);const s=document.createElement("span");return s.classList.add("bn-collaboration-cursor__label"),s.setAttribute("style",`background-color: ${e.color}; color: ${V.isDarkColor(e.color)?"white":"black"}`),s.insertBefore(document.createTextNode(e.name),null),r.insertBefore(s,null),t.insertBefore(document.createTextNode("⁠"),null),t.insertBefore(r,null),t.insertBefore(document.createTextNode("⁠"),null),t});let X=V;class oe extends a.BlockNoteExtension{static key(){return"ySyncPlugin"}constructor(o){super(),this.addProsemirrorPlugin(P.ySyncPlugin(o))}get priority(){return 1001}}class ne extends a.BlockNoteExtension{static key(){return"yUndoPlugin"}constructor({editor:o}){super(),this.addProsemirrorPlugin(P.yUndoPlugin({trackedOrigins:[o]}))}get priority(){return 1e3}}class tn extends a.BlockNoteExtension{constructor({editor:e,collaboration:t}){super(e);h(this,"editor");h(this,"collaboration");h(this,"forkedState");this.editor=e,this.collaboration=t}static key(){return"ForkYDocPlugin"}findTypeInOtherYdoc(e,t){const r=e.doc;if(e._item===null){const s=Array.from(r.share.keys()).find(i=>r.share.get(i)===e);if(s==null)throw new Error("type does not exist in other ydoc");return t.get(s,e.constructor)}else{const s=e._item,i=t.store.clients.get(s.id.client)??[],l=H.findIndexSS(i,s.id.clock);return i[l].content.type}}get isForkedFromRemote(){return this.forkedState!==void 0}fork(){var s;if(this.isForkedFromRemote)return;const e=(s=this.collaboration)==null?void 0:s.fragment;if(!e)throw new Error("No fragment to fork from");const t=new H.Doc;H.applyUpdate(t,H.encodeStateAsUpdate(e.doc));const r=this.findTypeInOtherYdoc(e,t);this.forkedState={undoStack:P.yUndoPluginKey.getState(this.editor.prosemirrorState).undoManager.undoStack,originalFragment:e,forkedFragment:r},this.editor._tiptapEditor.unregisterPlugin([P.yCursorPluginKey,P.yUndoPluginKey,P.ySyncPluginKey]),this.editor._tiptapEditor.registerPlugin(new oe(r).plugins[0]),this.editor._tiptapEditor.registerPlugin(new ne({editor:this.editor}).plugins[0]),this.emit("forked",!0)}merge({keepChanges:e}){if(!this.forkedState)return;this.editor._tiptapEditor.unregisterPlugin(P.ySyncPluginKey),this.editor._tiptapEditor.unregisterPlugin(P.yUndoPluginKey);const{originalFragment:t,forkedFragment:r,undoStack:s}=this.forkedState;if(this.editor.extensions.ySyncPlugin=new oe(t),this.editor.extensions.yCursorPlugin=new X(this.collaboration),this.editor.extensions.yUndoPlugin=new ne({editor:this.editor}),this.editor._tiptapEditor.registerPlugin(this.editor.extensions.ySyncPlugin.plugins[0]),this.editor._tiptapEditor.registerPlugin(this.editor.extensions.yCursorPlugin.plugins[0]),this.editor._tiptapEditor.registerPlugin(this.editor.extensions.yUndoPlugin.plugins[0]),P.yUndoPluginKey.getState(this.editor.prosemirrorState).undoManager.undoStack=s,e){const i=H.encodeStateAsUpdate(r.doc,H.encodeStateVector(t.doc));H.applyUpdate(t.doc,i,this.editor)}this.forkedState=void 0,this.emit("forked",!1)}}const Qe=(n,o)=>{o(n),n.forEach(e=>{e instanceof H.XmlElement&&Qe(e,o)})},on=(n,o)=>{const e={};n.forEach(t=>{t instanceof H.XmlElement&&Qe(t,r=>{if(r.nodeName==="blockContainer"&&r.hasAttribute("id")){const s={textColor:r.getAttribute("textColor"),backgroundColor:r.getAttribute("backgroundColor")};s.textColor===a.defaultProps.textColor.default&&(s.textColor=void 0),s.backgroundColor===a.defaultProps.backgroundColor.default&&(s.backgroundColor=void 0),(s.textColor||s.backgroundColor)&&(e[r.getAttribute("id")]=s)}})}),o.doc.descendants((t,r)=>{t.type.name==="blockContainer"&&e[t.attrs.id]&&(o=o.setNodeMarkup(r+1,void 0,e[t.attrs.id]))})},nn=[on];class de extends a.BlockNoteExtension{constructor(e){const t=new w.PluginKey(de.key());super();h(this,"migrationDone",!1);this.addProsemirrorPlugin(new w.Plugin({key:t,appendTransaction:(r,s,i)=>{if(this.migrationDone||r.length!==1||!r[0].getMeta(P.ySyncPluginKey))return;const l=i.tr;for(const c of nn)c(e,l);return this.migrationDone=!0,l}}))}static key(){return"schemaMigrationPlugin"}}const Ze=S.Mark.create({name:"comment",excludes:"",inclusive:!1,keepOnSplit:!0,addAttributes(){return{orphan:{parseHTML:n=>!!n.getAttribute("data-orphan"),renderHTML:n=>n.orphan?{"data-orphan":"true"}:{},default:!1},threadId:{parseHTML:n=>n.getAttribute("data-bn-thread-id"),renderHTML:n=>({"data-bn-thread-id":n.threadId}),default:""}}},renderHTML({HTMLAttributes:n}){return["span",S.mergeAttributes(n,{class:"bn-thread-mark"})]},parseHTML(){return[{tag:"span.bn-thread-mark"}]},extendMarkSchema(n){return n.name==="comment"?{blocknoteIgnore:!0}:{}}});class rn extends a.EventEmitter{constructor(e){super();h(this,"userCache",new Map);h(this,"loadingUsers",new Set);this.resolveUsers=e}async loadUsers(e){const t=e.filter(r=>!this.userCache.has(r)&&!this.loadingUsers.has(r));if(t.length!==0){for(const r of t)this.loadingUsers.add(r);try{const r=await this.resolveUsers(t);for(const s of r)this.userCache.set(s.id,s);this.emit("update",this.userCache)}finally{for(const r of t)this.loadingUsers.delete(r)}}}getUser(e){return this.userCache.get(e)}subscribe(e){return this.on("update",e)}}const q=new w.PluginKey("blocknote-comments"),sn="SET_SELECTED_THREAD_ID";function an(n,o){const e=new Map;return n.descendants((t,r)=>{t.marks.forEach(s=>{if(s.type.name===o){const i=s.attrs.threadId;if(!i)return;const l=r,c=l+t.nodeSize,d=e.get(i)??{from:1/0,to:0};e.set(i,{from:Math.min(l,d.from),to:Math.max(c,d.to)})}})}),e}class cn extends a.BlockNoteExtension{constructor(e,t,r,s){super();h(this,"userStore");h(this,"pendingComment",!1);h(this,"selectedThreadId");h(this,"threadPositions",new Map);h(this,"updateMarksFromThreads",e=>{this.editor.transact(t=>{t.doc.descendants((r,s)=>{r.marks.forEach(i=>{if(i.type.name===this.markType){const l=i.type,c=i.attrs.threadId,d=e.get(c),u=!!(!d||d.resolved||d.deletedAt);if(u!==i.attrs.orphan){const p=Math.max(s,0),f=Math.min(s+r.nodeSize,t.doc.content.size-1,t.doc.content.size-1);t.removeMark(p,f,i),t.addMark(p,f,l.create({...i.attrs,orphan:u})),u&&this.selectedThreadId===c&&(this.selectedThreadId=void 0,this.emitStateUpdate())}}})})})});if(this.editor=e,this.threadStore=t,this.markType=r,this.commentEditorSchema=s,!e.resolveUsers)throw new Error("resolveUsers is required for comments");this.userStore=new rn(e.resolveUsers),this.threadStore.subscribe(this.updateMarksFromThreads),e.onCreate(()=>{this.updateMarksFromThreads(this.threadStore.getThreads()),e.onSelectionChange(()=>{this.pendingComment&&(this.pendingComment=!1,this.emitStateUpdate())})});const i=this;this.addProsemirrorPlugin(new w.Plugin({key:q,state:{init(){return{decorations:E.DecorationSet.empty}},apply(l,c){const d=l.getMeta(q);if(!l.docChanged&&!d)return c;const u=l.docChanged?an(l.doc,i.markType):i.threadPositions;(u.size>0||i.threadPositions.size>0)&&(i.threadPositions=u,i.emitStateUpdate());const p=[];if(i.selectedThreadId){const f=u.get(i.selectedThreadId);f&&p.push(E.Decoration.inline(f.from,f.to,{class:"bn-thread-mark-selected"}))}return{decorations:E.DecorationSet.create(l.doc,p)}}},props:{decorations(l){var c;return((c=q.getState(l))==null?void 0:c.decorations)??E.DecorationSet.empty},handleClick:(l,c,d)=>{if(d.button!==0)return;const u=l.state.doc.nodeAt(c);if(!u){i.selectThread(void 0);return}const p=u.marks.find(g=>g.type.name===r&&g.attrs.orphan!==!0),f=p==null?void 0:p.attrs.threadId;i.selectThread(f,!1)}}}))}static key(){return"comments"}emitStateUpdate(){this.emit("update",{selectedThreadId:this.selectedThreadId,pendingComment:this.pendingComment,threadPositions:this.threadPositions})}onUpdate(e){return this.on("update",e)}selectThread(e,t=!0){var r,s;if(this.selectedThreadId!==e&&(this.selectedThreadId=e,this.emitStateUpdate(),this.editor.transact(i=>i.setMeta(q,{name:sn})),e&&t)){const i=this.threadPositions.get(e);if(!i)return;(s=(r=this.editor.prosemirrorView)==null?void 0:r.domAtPos(i.from).node)==null||s.scrollIntoView({behavior:"smooth",block:"center"})}}startPendingComment(){this.pendingComment=!0,this.emitStateUpdate()}stopPendingComment(){this.pendingComment=!1,this.emitStateUpdate()}async createThread(e){const t=await this.threadStore.createThread(e);if(this.threadStore.addThreadToDocument){const r=this.editor.prosemirrorView,s=r.state.selection,i=P.ySyncPluginKey.getState(r.state),l={prosemirror:{head:s.head,anchor:s.anchor},yjs:i?P.getRelativeSelection(i.binding,r.state):void 0};await this.threadStore.addThreadToDocument({threadId:t.id,selection:l})}else this.editor._tiptapEditor.commands.setMark(this.markType,{orphan:!1,threadId:t.id})}}class et{constructor(o,e,t,r){h(this,"state");h(this,"emitUpdate");h(this,"mouseDownHandler",()=>{var o;(o=this.state)!=null&&o.show&&(this.state.show=!1,this.emitUpdate())});h(this,"dragstartHandler",()=>{var o;(o=this.state)!=null&&o.show&&(this.state.show=!1,this.emitUpdate())});h(this,"scrollHandler",()=>{var o;if((o=this.state)!=null&&o.show){const e=this.pmView.root.querySelector(`[data-node-type="blockContainer"][data-id="${this.state.block.id}"]`);if(!e)return;this.state.referencePos=e.getBoundingClientRect(),this.emitUpdate()}});h(this,"closeMenu",()=>{var o;(o=this.state)!=null&&o.show&&(this.state.show=!1,this.emitUpdate())});this.editor=o,this.pluginKey=e,this.pmView=t,this.emitUpdate=()=>{if(!this.state)throw new Error("Attempting to update uninitialized file panel");r(this.state)},t.dom.addEventListener("mousedown",this.mouseDownHandler),t.dom.addEventListener("dragstart",this.dragstartHandler),t.root.addEventListener("scroll",this.scrollHandler,!0)}update(o,e){var l,c;const t=this.pluginKey.getState(o.state),r=this.pluginKey.getState(e);if(!((l=this.state)!=null&&l.show)&&(t!=null&&t.block)&&this.editor.isEditable){const d=this.pmView.root.querySelector(`[data-node-type="blockContainer"][data-id="${t.block.id}"]`);if(!d)return;this.state={show:!0,referencePos:d.getBoundingClientRect(),block:t.block},this.emitUpdate();return}const s=(t==null?void 0:t.block)&&!(r!=null&&r.block),i=!(t!=null&&t.block)&&(r==null?void 0:r.block);s&&this.state&&!this.state.show&&(this.state.show=!0,this.emitUpdate()),i&&((c=this.state)!=null&&c.show)&&(this.state.show=!1,this.emitUpdate())}destroy(){this.pmView.dom.removeEventListener("mousedown",this.mouseDownHandler),this.pmView.dom.removeEventListener("dragstart",this.dragstartHandler),this.pmView.root.removeEventListener("scroll",this.scrollHandler,!0)}}const Z=new w.PluginKey("FilePanelPlugin");class tt extends a.BlockNoteExtension{constructor(e){super();h(this,"view");h(this,"closeMenu",()=>{var e;return(e=this.view)==null?void 0:e.closeMenu()});this.addProsemirrorPlugin(new w.Plugin({key:Z,view:t=>(this.view=new et(e,Z,t,r=>{this.emit("update",r)}),this.view),props:{handleKeyDown:(t,r)=>{var s;return r.key==="Escape"&&this.shown?((s=this.view)==null||s.closeMenu(),!0):!1}},state:{init:()=>({block:void 0}),apply:(t,r)=>{const s=t.getMeta(Z);return s||(!t.getMeta(P.ySyncPluginKey)&&(t.selectionSet||t.docChanged)?{block:void 0}:r)}}}))}static key(){return"filePanel"}get shown(){var e,t;return((t=(e=this.view)==null?void 0:e.state)==null?void 0:t.show)||!1}onUpdate(e){return this.on("update",e)}}class ot{constructor(o,e,t){h(this,"state");h(this,"emitUpdate");h(this,"preventHide",!1);h(this,"preventShow",!1);h(this,"shouldShow",({view:o,state:e,from:t,to:r})=>{const{doc:s,selection:i}=e,{empty:l}=i,c=!s.textBetween(t,r).length&&S.isTextSelection(e.selection);if(i.$from.parent.type.spec.code||S.isNodeSelection(i)&&i.node.type.spec.code||l||c)return!1;const d=document.activeElement;return!(!this.isElementWithinEditorWrapper(d)&&o.editable)});h(this,"blurHandler",o=>{var t;if(this.preventHide){this.preventHide=!1;return}const e=this.pmView.dom.parentElement;o&&o.relatedTarget&&(e===o.relatedTarget||e.contains(o.relatedTarget)||o.relatedTarget.matches(".bn-ui-container, .bn-ui-container *"))||(t=this.state)!=null&&t.show&&(this.state.show=!1,this.emitUpdate())});h(this,"isElementWithinEditorWrapper",o=>{if(!o)return!1;const e=this.pmView.dom.parentElement;return e?e.contains(o):!1});h(this,"viewMousedownHandler",o=>{(!this.isElementWithinEditorWrapper(o.target)||o.button===0)&&(this.preventShow=!0)});h(this,"mouseupHandler",()=>{this.preventShow&&(this.preventShow=!1,setTimeout(()=>this.update(this.pmView)))});h(this,"dragHandler",()=>{var o;(o=this.state)!=null&&o.show&&(this.state.show=!1,this.emitUpdate())});h(this,"scrollHandler",()=>{var o;(o=this.state)!=null&&o.show&&(this.state.referencePos=this.getSelectionBoundingBox(),this.emitUpdate())});h(this,"closeMenu",()=>{var o;(o=this.state)!=null&&o.show&&(this.state.show=!1,this.emitUpdate())});this.editor=o,this.pmView=e,this.emitUpdate=()=>{if(!this.state)throw new Error("Attempting to update uninitialized formatting toolbar");t(this.state)},e.dom.addEventListener("mousedown",this.viewMousedownHandler),e.root.addEventListener("mouseup",this.mouseupHandler),e.dom.addEventListener("dragstart",this.dragHandler),e.dom.addEventListener("dragover",this.dragHandler),e.dom.addEventListener("blur",this.blurHandler),e.root.addEventListener("scroll",this.scrollHandler,!0)}update(o,e){var g,k,m;const{state:t,composing:r}=o,{doc:s,selection:i}=t,l=e&&e.doc.eq(s)&&e.selection.eq(i);if(r||l)return;const{ranges:c}=i,d=Math.min(...c.map(b=>b.$from.pos)),u=Math.max(...c.map(b=>b.$to.pos)),p=this.shouldShow({view:o,state:t,from:d,to:u}),f=typeof Range.prototype.getClientRects>"u";if(!this.preventShow&&(p||this.preventHide)&&!f){const b=this.getSelectionBoundingBox();if(b.height===0&&b.width===0){queueMicrotask(()=>{const C={show:!0,referencePos:this.getSelectionBoundingBox()};this.state=C,this.emitUpdate(),o.dispatch(o.state.tr.setSelection(w.TextSelection.create(o.state.doc,o.state.selection.from+1,o.state.selection.to))),o.dispatch(o.state.tr.setSelection(w.TextSelection.create(o.state.doc,o.state.selection.from-1,o.state.selection.to)))});return}const y={show:!0,referencePos:this.getSelectionBoundingBox()};(y.show!==((g=this.state)==null?void 0:g.show)||y.referencePos.toJSON()!==((k=this.state)==null?void 0:k.referencePos.toJSON()))&&(this.state=y,this.emitUpdate());return}if((m=this.state)!=null&&m.show&&!this.preventHide&&(!p||this.preventShow||!this.editor.isEditable)){this.state.show=!1,this.emitUpdate();return}}destroy(){this.pmView.dom.removeEventListener("mousedown",this.viewMousedownHandler),this.pmView.root.removeEventListener("mouseup",this.mouseupHandler),this.pmView.dom.removeEventListener("dragstart",this.dragHandler),this.pmView.dom.removeEventListener("dragover",this.dragHandler),this.pmView.dom.removeEventListener("blur",this.blurHandler),this.pmView.root.removeEventListener("scroll",this.scrollHandler,!0)}getSelectionBoundingBox(){const{state:o}=this.pmView,{selection:e}=o,{ranges:t}=e,r=Math.min(...t.map(i=>i.$from.pos)),s=Math.max(...t.map(i=>i.$to.pos));if(S.isNodeSelection(e)){const i=this.pmView.nodeDOM(r);if(i)return i.getBoundingClientRect()}return S.posToDOMRect(this.pmView,r,s)}}const nt=new w.PluginKey("FormattingToolbarPlugin");class rt extends a.BlockNoteExtension{constructor(e){super();h(this,"view");h(this,"closeMenu",()=>this.view.closeMenu());this.addProsemirrorPlugin(new w.Plugin({key:nt,view:t=>(this.view=new ot(e,t,r=>{this.emit("update",r)}),this.view),props:{handleKeyDown:(t,r)=>r.key==="Escape"&&this.shown?(this.view.closeMenu(),!0):!1}}))}static key(){return"formattingToolbar"}get shown(){var e,t;return((t=(e=this.view)==null?void 0:e.state)==null?void 0:t.show)||!1}onUpdate(e){return this.on("update",e)}}const ln=S.Node.create({name:"hardBreak",inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,priority:10,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:n}){return["br",S.mergeAttributes(this.options.HTMLAttributes,n)]},renderText(){return`
4
- `}}),ye=(n,o)=>{const e=n.resolve(o);if(e.depth<=1)return;const t=e.posAtIndex(e.index(e.depth-1),e.depth-1);return a.getBlockInfoFromResolvedPos(n.resolve(t))},Y=(n,o)=>{const e=n.resolve(o),t=e.index();if(t===0)return;const r=e.posAtIndex(t-1);return a.getBlockInfoFromResolvedPos(n.resolve(r))},st=(n,o)=>{for(;o.childContainer;){const e=o.childContainer.node,t=n.resolve(o.childContainer.beforePos+1).posAtIndex(e.childCount-1);o=a.getBlockInfoFromResolvedPos(n.resolve(t))}return o},dn=(n,o)=>n.isBlockContainer&&n.blockContent.node.type.spec.content==="inline*"&&n.blockContent.node.childCount>0&&o.isBlockContainer&&o.blockContent.node.type.spec.content==="inline*",un=(n,o,e,t)=>{if(!t.isBlockContainer)throw new Error(`Attempted to merge block at position ${t.bnBlock.beforePos} into previous block at position ${e.bnBlock.beforePos}, but next block is not a block container`);if(t.childContainer){const r=n.doc.resolve(t.childContainer.beforePos+1),s=n.doc.resolve(t.childContainer.afterPos-1),i=r.blockRange(s);if(o){const l=n.doc.resolve(t.bnBlock.beforePos);n.tr.lift(i,l.depth)}}if(o){if(!e.isBlockContainer)throw new Error(`Attempted to merge block at position ${t.bnBlock.beforePos} into previous block at position ${e.bnBlock.beforePos}, but previous block is not a block container`);o(n.tr.delete(e.blockContent.afterPos-1,t.blockContent.beforePos+1))}return!0},we=n=>({state:o,dispatch:e})=>{const t=o.doc.resolve(n),r=a.getBlockInfoFromResolvedPos(t),s=Y(o.doc,r.bnBlock.beforePos);if(!s)return!1;const i=st(o.doc,s);return dn(i,r)?un(o,e,i,r):!1},hn=S.Extension.create({priority:50,addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({chain:t,commands:r})=>[()=>r.deleteSelection(),()=>r.undoInputRule(),()=>r.command(({state:s})=>{const i=a.getBlockInfoFromSelection(s);if(!i.isBlockContainer)return!1;const l=s.selection.from===i.blockContent.beforePos+1,c=i.blockContent.node.type.name==="paragraph";return l&&!c?r.command(a.updateBlockCommand(i.bnBlock.beforePos,{type:"paragraph",props:{}})):!1}),()=>r.command(({state:s})=>{const i=a.getBlockInfoFromSelection(s);if(!i.isBlockContainer)return!1;const{blockContent:l}=i;return s.selection.from===l.beforePos+1?r.liftListItem("blockContainer"):!1}),()=>r.command(({state:s})=>{const i=a.getBlockInfoFromSelection(s);if(!i.isBlockContainer)return!1;const{bnBlock:l,blockContent:c}=i,d=s.selection.from===c.beforePos+1,u=s.selection.empty,p=l.beforePos;return d&&u?t().command(we(p)).scrollIntoView().run():!1}),()=>r.command(({state:s,dispatch:i})=>{const l=a.getBlockInfoFromSelection(s);if(!l.isBlockContainer||!(s.selection.from===l.blockContent.beforePos+1)||Y(s.doc,l.bnBlock.beforePos))return!1;const u=ye(s.doc,l.bnBlock.beforePos);if((u==null?void 0:u.blockNoteType)!=="column")return!1;const p=u,f=ye(s.doc,p.bnBlock.beforePos);if((f==null?void 0:f.blockNoteType)!=="columnList")throw new Error("parent of column is not a column list");const g=p.childContainer.node.childCount===1,k=g&&f.childContainer.node.childCount===2,m=f.childContainer.node.firstChild===p.bnBlock.node;if(i){const b=s.doc.slice(l.bnBlock.beforePos,l.bnBlock.afterPos,!1);if(k)if(m){s.tr.step(new z.ReplaceAroundStep(f.bnBlock.beforePos,f.bnBlock.afterPos,p.bnBlock.afterPos+1,f.bnBlock.afterPos-2,b,b.size,!1));const y=s.tr.doc.resolve(p.bnBlock.beforePos);s.tr.setSelection(w.TextSelection.between(y,y))}else{s.tr.step(new z.ReplaceAroundStep(f.bnBlock.beforePos,f.bnBlock.afterPos,f.bnBlock.beforePos+2,p.bnBlock.beforePos-1,b,0,!1));const y=s.tr.doc.resolve(s.tr.mapping.map(p.bnBlock.beforePos-1));s.tr.setSelection(w.TextSelection.between(y,y))}else if(g)if(m){s.tr.delete(p.bnBlock.beforePos,p.bnBlock.afterPos),s.tr.insert(f.bnBlock.beforePos,b.content);const y=s.tr.doc.resolve(f.bnBlock.beforePos);s.tr.setSelection(w.TextSelection.between(y,y))}else s.tr.delete(p.bnBlock.beforePos-1,p.bnBlock.beforePos+1);else{s.tr.delete(l.bnBlock.beforePos,l.bnBlock.afterPos),m?s.tr.insert(f.bnBlock.beforePos-1,b.content):s.tr.insert(p.bnBlock.beforePos-1,b.content);const y=s.tr.doc.resolve(p.bnBlock.beforePos-1);s.tr.setSelection(w.TextSelection.between(y,y))}}return!0}),()=>r.command(({state:s})=>{const i=a.getBlockInfoFromSelection(s);if(!i.isBlockContainer)return!1;if(i.blockContent.node.childCount===0&&i.blockContent.node.type.spec.content==="inline*"){const c=Y(s.doc,i.bnBlock.beforePos);if(!c||!c.isBlockContainer)return!1;let d=t();if(c.blockContent.node.type.spec.content==="tableRow+"){const k=i.bnBlock.beforePos-1-1-1-1-1;d=d.setTextSelection(k)}else if(c.blockContent.node.type.spec.content===""){const u=c.blockContent.afterPos-c.blockContent.node.nodeSize;d=d.setNodeSelection(u)}else{const u=c.blockContent.afterPos-c.blockContent.node.nodeSize;d=d.setTextSelection(u)}return d.deleteRange({from:i.bnBlock.beforePos,to:i.bnBlock.afterPos}).scrollIntoView().run()}return!1}),()=>r.command(({state:s})=>{const i=a.getBlockInfoFromSelection(s);if(!i.isBlockContainer)throw new Error("todo");const l=s.selection.from===i.blockContent.beforePos+1,c=s.selection.empty,d=Y(s.doc,i.bnBlock.beforePos);if(d&&l&&c){const u=st(s.doc,d);if(!u.isBlockContainer)throw new Error("todo");if(u.blockContent.node.type.spec.content===""||u.blockContent.node.type.spec.content==="inline*"&&u.blockContent.node.childCount===0)return t().cut({from:i.bnBlock.beforePos,to:i.bnBlock.afterPos},u.bnBlock.afterPos).deleteRange({from:u.bnBlock.beforePos,to:u.bnBlock.afterPos}).run()}return!1})]),o=()=>this.editor.commands.first(({commands:t})=>[()=>t.deleteSelection(),()=>t.command(({state:r})=>{const s=a.getBlockInfoFromSelection(r);if(!s.isBlockContainer)return!1;const{bnBlock:i,blockContent:l,childContainer:c}=s,{depth:d}=r.doc.resolve(i.beforePos),u=i.afterPos===r.doc.nodeSize-3,p=r.selection.from===l.afterPos-1,f=r.selection.empty;if(!u&&p&&f&&!(c!==void 0)){let k=d,m=i.afterPos+1,b=r.doc.resolve(m).depth;for(;b<k;)k=b,m+=2,b=r.doc.resolve(m).depth;return t.command(we(m-1))}return!1})]),e=(t=!1)=>this.editor.commands.first(({commands:r,tr:s})=>[()=>r.command(({state:i})=>{const l=a.getBlockInfoFromSelection(i);if(!l.isBlockContainer)return!1;const{bnBlock:c,blockContent:d}=l,{depth:u}=i.doc.resolve(c.beforePos),p=i.selection.$anchor.parentOffset===0,f=i.selection.anchor===i.selection.head,g=d.node.childCount===0,k=u>1;return p&&f&&g&&k?r.liftListItem("blockContainer"):!1}),()=>r.command(({state:i})=>{var d;const l=a.getBlockInfoFromSelection(i),c=((d=this.options.editor.schema.blockSchema[l.blockNoteType].meta)==null?void 0:d.hardBreakShortcut)??"shift+enter";if(c==="none")return!1;if(c==="shift+enter"&&t||c==="enter"){const u=s.storedMarks||s.selection.$head.marks().filter(p=>this.editor.extensionManager.splittableMarks.includes(p.type.name));return s.insert(s.selection.head,s.doc.type.schema.nodes.hardBreak.create()).ensureMarks(u),!0}return!1}),()=>r.command(({state:i,dispatch:l})=>{const c=a.getBlockInfoFromSelection(i);if(!c.isBlockContainer)return!1;const{bnBlock:d,blockContent:u}=c,p=i.selection.$anchor.parentOffset===0,f=i.selection.anchor===i.selection.head,g=u.node.childCount===0;if(p&&f&&g){const k=d.afterPos,m=k+2;if(l){const b=i.schema.nodes.blockContainer.createAndFill();i.tr.insert(k,b).scrollIntoView(),i.tr.setSelection(new w.TextSelection(i.doc.resolve(m)))}return!0}return!1}),()=>r.command(({state:i,chain:l})=>{const c=a.getBlockInfoFromSelection(i);if(!c.isBlockContainer)return!1;const{blockContent:d}=c,u=i.selection.$anchor.parentOffset===0;return d.node.childCount===0?!1:(l().deleteSelection().command(a.splitBlockCommand(i.selection.from,u,u)).run(),!0)})]);return{Backspace:n,Delete:o,Enter:()=>e(),"Shift-Enter":()=>e(!0),Tab:()=>{var t,r,s;return this.options.tabBehavior!=="prefer-indent"&&((t=this.options.editor.formattingToolbar)!=null&&t.shown||(r=this.options.editor.linkToolbar)!=null&&r.shown||(s=this.options.editor.filePanel)!=null&&s.shown)?!1:$e(this.options.editor)},"Shift-Tab":()=>{var t,r,s;return this.options.tabBehavior!=="prefer-indent"&&((t=this.options.editor.formattingToolbar)!=null&&t.shown||(r=this.options.editor.linkToolbar)!=null&&r.shown||(s=this.options.editor.filePanel)!=null&&s.shown)?!1:(this.editor.commands.liftListItem("blockContainer"),!0)},"Shift-Mod-ArrowUp":()=>(this.options.editor.moveBlocksUp(),!0),"Shift-Mod-ArrowDown":()=>(this.options.editor.moveBlocksDown(),!0),"Mod-z":()=>this.options.editor.undo(),"Mod-y":()=>this.options.editor.redo(),"Shift-Mod-z":()=>this.options.editor.redo()}}});class pn{constructor(o,e,t){h(this,"state");h(this,"emitUpdate");h(this,"menuUpdateTimer");h(this,"startMenuUpdateTimer");h(this,"stopMenuUpdateTimer");h(this,"mouseHoveredLinkMark");h(this,"mouseHoveredLinkMarkRange");h(this,"keyboardHoveredLinkMark");h(this,"keyboardHoveredLinkMarkRange");h(this,"linkMark");h(this,"linkMarkRange");h(this,"mouseOverHandler",o=>{if(this.mouseHoveredLinkMark=void 0,this.mouseHoveredLinkMarkRange=void 0,this.stopMenuUpdateTimer(),o.target instanceof HTMLAnchorElement&&o.target.nodeName==="A"){const e=o.target,t=this.pmView.posAtDOM(e,0)+1,r=this.pmView.state.doc.resolve(t),s=r.marks();for(const i of s)if(i.type.name===this.pmView.state.schema.mark("link").type.name){this.mouseHoveredLinkMark=i,this.mouseHoveredLinkMarkRange=S.getMarkRange(r,i.type,i.attrs)||void 0;break}}return this.startMenuUpdateTimer(),!1});h(this,"clickHandler",o=>{var t;const e=this.pmView.dom.parentElement;this.linkMark&&o&&o.target&&!(e===o.target||e.contains(o.target))&&(t=this.state)!=null&&t.show&&(this.state.show=!1,this.emitUpdate())});h(this,"scrollHandler",()=>{var o;this.linkMark!==void 0&&(o=this.state)!=null&&o.show&&(this.state.referencePos=S.posToDOMRect(this.pmView,this.linkMarkRange.from,this.linkMarkRange.to),this.emitUpdate())});h(this,"closeMenu",()=>{var o;(o=this.state)!=null&&o.show&&(this.state.show=!1,this.emitUpdate())});this.editor=o,this.pmView=e,this.emitUpdate=()=>{if(!this.state)throw new Error("Attempting to update uninitialized link toolbar");t(this.state)},this.startMenuUpdateTimer=()=>{this.menuUpdateTimer=setTimeout(()=>{this.update(this.pmView,void 0,!0)},250)},this.stopMenuUpdateTimer=()=>(this.menuUpdateTimer&&(clearTimeout(this.menuUpdateTimer),this.menuUpdateTimer=void 0),!1),this.pmView.dom.addEventListener("mouseover",this.mouseOverHandler),this.pmView.root.addEventListener("click",this.clickHandler,!0),this.pmView.root.addEventListener("scroll",this.scrollHandler,!0)}editLink(o,e){var t;this.editor.transact(r=>{const s=a.getPmSchema(r);r.insertText(e,this.linkMarkRange.from,this.linkMarkRange.to),r.addMark(this.linkMarkRange.from,this.linkMarkRange.from+e.length,s.mark("link",{href:o}))}),this.pmView.focus(),(t=this.state)!=null&&t.show&&(this.state.show=!1,this.emitUpdate())}deleteLink(){var o;this.editor.transact(e=>e.removeMark(this.linkMarkRange.from,this.linkMarkRange.to,this.linkMark.type).setMeta("preventAutolink",!0)),this.pmView.focus(),(o=this.state)!=null&&o.show&&(this.state.show=!1,this.emitUpdate())}update(o,e,t=!1){var l;const{state:r}=o;if(e&&e.selection.from===r.selection.from&&e.selection.to===r.selection.to||!this.pmView.hasFocus())return;const i=this.linkMark;if(this.linkMark=void 0,this.linkMarkRange=void 0,this.keyboardHoveredLinkMark=void 0,this.keyboardHoveredLinkMarkRange=void 0,this.pmView.state.selection.empty){const c=this.pmView.state.selection.$from.marks();for(const d of c)if(d.type.name===this.pmView.state.schema.mark("link").type.name){this.keyboardHoveredLinkMark=d,this.keyboardHoveredLinkMarkRange=S.getMarkRange(this.pmView.state.selection.$from,d.type,d.attrs)||void 0;break}}if(this.mouseHoveredLinkMark&&t&&(this.linkMark=this.mouseHoveredLinkMark,this.linkMarkRange=this.mouseHoveredLinkMarkRange),this.keyboardHoveredLinkMark&&(this.linkMark=this.keyboardHoveredLinkMark,this.linkMarkRange=this.keyboardHoveredLinkMarkRange),this.linkMark&&this.editor.isEditable){this.state={show:!0,referencePos:S.posToDOMRect(this.pmView,this.linkMarkRange.from,this.linkMarkRange.to),url:this.linkMark.attrs.href,text:this.pmView.state.doc.textBetween(this.linkMarkRange.from,this.linkMarkRange.to)},this.emitUpdate();return}if((l=this.state)!=null&&l.show&&i&&(!this.linkMark||!this.editor.isEditable)){this.state.show=!1,this.emitUpdate();return}}destroy(){this.pmView.dom.removeEventListener("mouseover",this.mouseOverHandler),this.pmView.root.removeEventListener("scroll",this.scrollHandler,!0),this.pmView.root.removeEventListener("click",this.clickHandler,!0)}}const it=new w.PluginKey("LinkToolbarPlugin");class at extends a.BlockNoteExtension{constructor(e){super();h(this,"view");h(this,"editLink",(e,t)=>{this.view.editLink(e,t)});h(this,"deleteLink",()=>{this.view.deleteLink()});h(this,"startHideTimer",()=>{this.view.startMenuUpdateTimer()});h(this,"stopHideTimer",()=>{this.view.stopMenuUpdateTimer()});h(this,"closeMenu",()=>this.view.closeMenu());this.addProsemirrorPlugin(new w.Plugin({key:it,view:t=>(this.view=new pn(e,t,r=>{this.emit("update",r)}),this.view),props:{handleKeyDown:(t,r)=>r.key==="Escape"&&this.shown?(this.view.closeMenu(),!0):!1}}))}static key(){return"linkToolbar"}onUpdate(e){return this.on("update",e)}get shown(){var e,t;return((t=(e=this.view)==null?void 0:e.state)==null?void 0:t.show)||!1}}const ct=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"],lt="https",mn=new w.PluginKey("node-selection-keyboard");class fn extends a.BlockNoteExtension{static key(){return"nodeSelectionKeyboard"}constructor(){super(),this.addProsemirrorPlugin(new w.Plugin({key:mn,props:{handleKeyDown:(o,e)=>{if("node"in o.state.selection){if(e.ctrlKey||e.metaKey)return!1;if(e.key.length===1)return e.preventDefault(),!0;if(e.key==="Enter"&&!e.shiftKey&&!e.altKey&&!e.ctrlKey&&!e.metaKey){const t=o.state.tr;return o.dispatch(t.insert(o.state.tr.selection.$to.after(),o.state.schema.nodes.paragraph.createChecked()).setSelection(new w.TextSelection(t.doc.resolve(o.state.tr.selection.$to.after()+1)))),!0}}return!1}}}))}}const gn=new w.PluginKey("blocknote-placeholder");class kn extends a.BlockNoteExtension{static key(){return"placeholder"}constructor(o,e){super(),this.addProsemirrorPlugin(new w.Plugin({key:gn,view:t=>{const r=`placeholder-selector-${Kt.v4()}`;t.dom.classList.add(r);const s=document.createElement("style"),i=o._tiptapEditor.options.injectNonce;i&&s.setAttribute("nonce",i),t.root instanceof window.ShadowRoot?t.root.append(s):t.root.head.appendChild(s);const l=s.sheet,c=(d="")=>`.${r} .bn-block-content${d} .bn-inline-content:has(> .ProseMirror-trailingBreak:only-child):before`;try{const{default:d,emptyDocument:u,...p}=e;for(const[k,m]of Object.entries(p)){const b=`[data-content-type="${k}"]`;l.insertRule(`${c(b)} { content: ${JSON.stringify(m)}; }`)}const f="[data-is-only-empty-block]",g="[data-is-empty-and-focused]";l.insertRule(`${c(f)} { content: ${JSON.stringify(u)}; }`),l.insertRule(`${c(g)} { content: ${JSON.stringify(d)}; }`)}catch(d){console.warn("Failed to insert placeholder CSS rule - this is likely due to the browser not supporting certain CSS pseudo-element selectors (:has, :only-child:, or :before)",d)}return{destroy:()=>{t.root instanceof window.ShadowRoot?t.root.removeChild(s):t.root.head.removeChild(s)}}},props:{decorations:t=>{const{doc:r,selection:s}=t;if(!o.isEditable||!s.empty||s.$from.parent.type.spec.code)return;const i=[];t.doc.content.size===6&&i.push(E.Decoration.node(2,4,{"data-is-only-empty-block":"true"}));const l=s.$anchor,c=l.parent;if(c.content.size===0){const d=l.before();i.push(E.Decoration.node(d,d+c.nodeSize,{"data-is-empty-and-focused":"true"}))}return E.DecorationSet.create(r,i)}}}))}}const Se=new w.PluginKey("previous-blocks"),bn={index:"index",level:"level",type:"type",depth:"depth","depth-change":"depth-change"};class yn extends a.BlockNoteExtension{static key(){return"previousBlockType"}constructor(){super();let o;this.addProsemirrorPlugin(new w.Plugin({key:Se,view(e){return{update:async(t,r)=>{var s;((s=this.key)==null?void 0:s.getState(t.state).updatedBlocks.size)>0&&(o=setTimeout(()=>{t.dispatch(t.state.tr.setMeta(Se,{clearUpdate:!0}))},0))},destroy:()=>{o&&clearTimeout(o)}}},state:{init(){return{prevTransactionOldBlockAttrs:{},currentTransactionOldBlockAttrs:{},updatedBlocks:new Set}},apply(e,t,r,s){if(t.currentTransactionOldBlockAttrs={},t.updatedBlocks.clear(),!e.docChanged||r.doc.eq(s.doc))return t;const i={},l=S.findChildren(r.doc,u=>u.attrs.id),c=new Map(l.map(u=>[u.node.attrs.id,u])),d=S.findChildren(s.doc,u=>u.attrs.id);for(const u of d){const p=c.get(u.node.attrs.id),f=p==null?void 0:p.node.firstChild,g=u.node.firstChild;if(p&&f&&g){const k={index:g.attrs.index,level:g.attrs.level,type:g.type.name,depth:s.doc.resolve(u.pos).depth},m={index:f.attrs.index,level:f.attrs.level,type:f.type.name,depth:r.doc.resolve(p.pos).depth};i[u.node.attrs.id]=m,t.currentTransactionOldBlockAttrs[u.node.attrs.id]=m,JSON.stringify(m)!==JSON.stringify(k)&&(m["depth-change"]=m.depth-k.depth,t.updatedBlocks.add(u.node.attrs.id))}}return t.prevTransactionOldBlockAttrs=i,t}},props:{decorations(e){const t=this.getState(e);if(t.updatedBlocks.size===0)return;const r=[];return e.doc.descendants((s,i)=>{if(!s.attrs.id||!t.updatedBlocks.has(s.attrs.id))return;const l=t.currentTransactionOldBlockAttrs[s.attrs.id],c={};for(const[u,p]of Object.entries(l))c["data-prev-"+bn[u]]=p||"none";const d=E.Decoration.node(i,i+s.nodeSize,{...c});r.push(d)}),E.DecorationSet.create(e.doc,r)}}}))}}const Ce=new w.PluginKey("blocknote-show-selection");class wn extends a.BlockNoteExtension{constructor(e){super();h(this,"enabled",!1);this.editor=e,this.addProsemirrorPlugin(new w.Plugin({key:Ce,props:{decorations:t=>{const{doc:r,selection:s}=t;if(!this.enabled)return E.DecorationSet.empty;const i=E.Decoration.inline(s.from,s.to,{"data-show-selection":"true"});return E.DecorationSet.create(r,[i])}}}))}static key(){return"showSelection"}setEnabled(e){this.enabled!==e&&(this.enabled=e,this.editor.transact(t=>t.setMeta(Ce,{})))}getEnabled(){return this.enabled}}function dt(n,o){var e,t;for(;n&&n.parentElement&&n.parentElement!==o.dom&&((e=n.getAttribute)==null?void 0:e.call(n,"data-node-type"))!=="blockContainer";)n=n.parentElement;if(((t=n.getAttribute)==null?void 0:t.call(n,"data-node-type"))==="blockContainer")return{node:n,id:n.getAttribute("data-id")}}class U extends w.Selection{constructor(e,t){super(e,t);h(this,"nodes");const r=e.node();this.nodes=[],e.doc.nodesBetween(e.pos,t.pos,(s,i,l)=>{if(l!==null&&l.eq(r))return this.nodes.push(s),!1})}static create(e,t,r=t){return new U(e.resolve(t),e.resolve(r))}content(){return new T.Slice(T.Fragment.from(this.nodes),0,0)}eq(e){if(!(e instanceof U)||this.nodes.length!==e.nodes.length||this.from!==e.from||this.to!==e.to)return!1;for(let t=0;t<this.nodes.length;t++)if(!this.nodes[t].eq(e.nodes[t]))return!1;return!0}map(e,t){const r=t.mapResult(this.from),s=t.mapResult(this.to);return s.deleted?w.Selection.near(e.resolve(r.pos)):r.deleted?w.Selection.near(e.resolve(s.pos)):new U(e.resolve(r.pos),e.resolve(s.pos))}toJSON(){return{type:"multiple-node",anchor:this.anchor,head:this.head}}}w.Selection.jsonID("multiple-node",U);let O;function Sn(n,o){let e,t;const r=o.resolve(n.from).node().type.spec.group==="blockContent",s=o.resolve(n.to).node().type.spec.group==="blockContent",i=Math.min(n.$anchor.depth,n.$head.depth);if(r&&s){const l=n.$from.start(i-1),c=n.$to.end(i-1);e=o.resolve(l-1).pos,t=o.resolve(c+1).pos}else e=n.from,t=n.to;return{from:e,to:t}}function Be(n,o,e=o){o===e&&(e+=n.state.doc.resolve(o+1).node().nodeSize);const t=n.domAtPos(o).node.cloneNode(!0),r=n.domAtPos(o).node,s=(p,f)=>Array.prototype.indexOf.call(p.children,f),i=s(r,n.domAtPos(o+1).node.parentElement),l=s(r,n.domAtPos(e-1).node.parentElement);for(let p=r.childElementCount-1;p>=0;p--)(p>l||p<i)&&t.removeChild(t.children[p]);ut(n.root),O=t;const c=O.getElementsByTagName("iframe");for(let p=0;p<c.length;p++){const f=c[p],g=f.parentElement;g&&g.removeChild(f)}const u=n.dom.className.split(" ").filter(p=>p!=="ProseMirror"&&p!=="bn-root"&&p!=="bn-editor").join(" ");O.className=O.className+" bn-drag-preview "+u,n.root instanceof ShadowRoot?n.root.appendChild(O):n.root.body.appendChild(O)}function ut(n){O!==void 0&&(n instanceof ShadowRoot?n.removeChild(O):n.body.removeChild(O),O=void 0)}function Cn(n,o,e){if(!n.dataTransfer||e.headless)return;const t=e.prosemirrorView,r=a.getNodeById(o.id,t.state.doc);if(!r)throw new Error(`Block with ID ${o.id} not found`);const s=r.posBeforeNode;if(s!=null){const i=t.state.selection,l=t.state.doc,{from:c,to:d}=Sn(i,l),u=c<=s&&s<d,p=i.$anchor.node()!==i.$head.node()||i instanceof U;u&&p?(t.dispatch(t.state.tr.setSelection(U.create(l,c,d))),Be(t,c,d)):(t.dispatch(t.state.tr.setSelection(w.NodeSelection.create(t.state.doc,s))),Be(t,s));const f=t.state.selection.content(),g=e.pmSchema,k=t.serializeForClipboard(f).dom.innerHTML,m=K(g,e),b=Je(f.content),y=m.exportBlocks(b,{}),C=J(y);n.dataTransfer.clearData(),n.dataTransfer.setData("blocknote/html",k),n.dataTransfer.setData("text/html",y),n.dataTransfer.setData("text/plain",C),n.dataTransfer.effectAllowed="move",n.dataTransfer.setDragImage(O,0,0)}}const ve=250;function re(n,o,e=!0){const t=n.root.elementsFromPoint(o.left,o.top);for(const r of t)if(n.dom.contains(r))return e&&r.closest("[data-node-type=columnList]")?re(n,{left:o.left+50,top:o.top},!1):dt(r,n)}function Bn(n,o){if(!o.dom.firstChild)return;const e=o.dom.firstChild.getBoundingClientRect(),t={left:Math.min(Math.max(e.left+10,n.x),e.right-10),top:n.y},r=re(o,t);if(!r)return;const s=r.node.getBoundingClientRect();return re(o,{left:s.right-10,top:n.y},!1)}class ht{constructor(o,e,t){h(this,"state");h(this,"emitUpdate");h(this,"mousePos");h(this,"hoveredBlock");h(this,"menuFrozen",!1);h(this,"isDragOrigin",!1);h(this,"updateState",o=>{this.state=o,this.emitUpdate(this.state)});h(this,"updateStateFromMousePos",()=>{var t,r,s,i,l;if(this.menuFrozen||!this.mousePos)return;const o=this.findClosestEditorElement({clientX:this.mousePos.x,clientY:this.mousePos.y});if((o==null?void 0:o.element)!==this.pmView.dom||o.distance>ve){(t=this.state)!=null&&t.show&&(this.state.show=!1,this.updateState(this.state));return}const e=Bn(this.mousePos,this.pmView);if(!e||!this.editor.isEditable){(r=this.state)!=null&&r.show&&(this.state.show=!1,this.updateState(this.state));return}if(!((s=this.state)!=null&&s.show&&((i=this.hoveredBlock)!=null&&i.hasAttribute("data-id"))&&((l=this.hoveredBlock)==null?void 0:l.getAttribute("data-id"))===e.id)&&(this.hoveredBlock=e.node,this.editor.isEditable)){const c=e.node.getBoundingClientRect(),d=e.node.closest("[data-node-type=column]");this.state={show:!0,referencePos:new DOMRect(d?d.firstElementChild.getBoundingClientRect().x:this.pmView.dom.firstChild.getBoundingClientRect().x,c.y,c.width,c.height),block:this.editor.getBlock(this.hoveredBlock.getAttribute("data-id"))},this.updateState(this.state)}});h(this,"onDragStart",o=>{var i;const e=(i=o.dataTransfer)==null?void 0:i.getData("blocknote/html");if(!e||this.pmView.dragging)return;const t=document.createElement("div");t.innerHTML=e;const s=T.DOMParser.fromSchema(this.pmView.state.schema).parse(t,{topNode:this.pmView.state.schema.nodes.blockGroup.create()});this.pmView.dragging={slice:new T.Slice(s.content,0,0),move:!0}});h(this,"findClosestEditorElement",o=>{const e=Array.from(this.pmView.root.querySelectorAll(".bn-editor"));if(e.length===0)return null;let t=e[0],r=Number.MAX_VALUE;return e.forEach(s=>{const i=s.querySelector(".bn-block-group").getBoundingClientRect(),l=o.clientX<i.left?i.left-o.clientX:o.clientX>i.right?o.clientX-i.right:0,c=o.clientY<i.top?i.top-o.clientY:o.clientY>i.bottom?o.clientY-i.bottom:0,d=Math.sqrt(Math.pow(l,2)+Math.pow(c,2));d<r&&(r=d,t=s)}),{element:t,distance:r}});h(this,"onDragOver",o=>{if(o.synthetic)return;const e=this.getDragEventContext(o);if(!e||!e.isDropPoint){this.closeDropCursor();return}e.isDropPoint&&!e.isDropWithinEditorBounds&&this.dispatchSyntheticEvent(o)});h(this,"closeDropCursor",()=>{const o=new Event("dragleave",{bubbles:!1});o.synthetic=!0,this.pmView.dom.dispatchEvent(o)});h(this,"getDragEventContext",o=>{var c;const e=!((c=o.dataTransfer)!=null&&c.types.includes("blocknote/html"))&&!!this.pmView.dragging,t=!!this.isDragOrigin,r=e||t,s=this.findClosestEditorElement(o);if(!s||s.distance>ve)return;const i=s.element===this.pmView.dom,l=i&&s.distance===0;if(!(!i&&!r))return{isDropPoint:i,isDropWithinEditorBounds:l,isDragOrigin:r}});h(this,"onDrop",o=>{if(o.synthetic)return;const e=this.getDragEventContext(o);if(!e){this.closeDropCursor();return}const{isDropPoint:t,isDropWithinEditorBounds:r,isDragOrigin:s}=e;if(!r&&t&&this.dispatchSyntheticEvent(o),t){if(this.pmView.dragging)return;this.pmView.dispatch(this.pmView.state.tr.setSelection(w.TextSelection.create(this.pmView.state.tr.doc,this.pmView.state.tr.selection.anchor)));return}else if(s){setTimeout(()=>this.pmView.dispatch(this.pmView.state.tr.deleteSelection()),0);return}});h(this,"onDragEnd",o=>{o.synthetic||(this.pmView.dragging=null)});h(this,"onKeyDown",o=>{var e;(e=this.state)!=null&&e.show&&this.editor.isFocused()&&(this.state.show=!1,this.emitUpdate(this.state))});h(this,"onMouseMove",o=>{var s;if(this.menuFrozen)return;this.mousePos={x:o.clientX,y:o.clientY};const e=this.pmView.dom.getBoundingClientRect(),t=this.mousePos.x>e.left&&this.mousePos.x<e.right&&this.mousePos.y>e.top&&this.mousePos.y<e.bottom,r=this.pmView.dom.parentElement;if(t&&o&&o.target&&!(r===o.target||r.contains(o.target))){(s=this.state)!=null&&s.show&&(this.state.show=!1,this.emitUpdate(this.state));return}this.updateStateFromMousePos()});h(this,"onScroll",()=>{var o;(o=this.state)!=null&&o.show&&(this.state.referencePos=this.hoveredBlock.getBoundingClientRect(),this.emitUpdate(this.state)),this.updateStateFromMousePos()});this.editor=o,this.pmView=e,this.emitUpdate=()=>{if(!this.state)throw new Error("Attempting to update uninitialized side menu");t(this.state)},this.pmView.root.addEventListener("dragstart",this.onDragStart),this.pmView.root.addEventListener("dragover",this.onDragOver),this.pmView.root.addEventListener("drop",this.onDrop,!0),this.pmView.root.addEventListener("dragend",this.onDragEnd,!0),this.pmView.root.addEventListener("mousemove",this.onMouseMove,!0),this.pmView.root.addEventListener("keydown",this.onKeyDown,!0),e.root.addEventListener("scroll",this.onScroll,!0)}dispatchSyntheticEvent(o){const e=new Event(o.type,o),t=this.pmView.dom.firstChild.getBoundingClientRect();e.clientX=o.clientX,e.clientY=o.clientY,e.clientX=Math.min(Math.max(o.clientX,t.left),t.left+t.width),e.clientY=Math.min(Math.max(o.clientY,t.top),t.top+t.height),e.dataTransfer=o.dataTransfer,e.preventDefault=()=>o.preventDefault(),e.synthetic=!0,this.pmView.dom.dispatchEvent(e)}update(o,e){var r;!e.doc.eq(this.pmView.state.doc)&&((r=this.state)!=null&&r.show)&&this.updateStateFromMousePos()}destroy(){var o;(o=this.state)!=null&&o.show&&(this.state.show=!1,this.emitUpdate(this.state)),this.pmView.root.removeEventListener("mousemove",this.onMouseMove,!0),this.pmView.root.removeEventListener("dragstart",this.onDragStart),this.pmView.root.removeEventListener("dragover",this.onDragOver),this.pmView.root.removeEventListener("drop",this.onDrop,!0),this.pmView.root.removeEventListener("dragend",this.onDragEnd,!0),this.pmView.root.removeEventListener("keydown",this.onKeyDown,!0),this.pmView.root.removeEventListener("scroll",this.onScroll,!0)}}const pt=new w.PluginKey("SideMenuPlugin");class mt extends a.BlockNoteExtension{constructor(e){super();h(this,"view");h(this,"blockDragStart",(e,t)=>{this.view&&(this.view.isDragOrigin=!0),Cn(e,t,this.editor)});h(this,"blockDragEnd",()=>{ut(this.editor.prosemirrorView.root),this.view&&(this.view.isDragOrigin=!1)});h(this,"freezeMenu",()=>{this.view.menuFrozen=!0,this.view.state.show=!0,this.view.emitUpdate(this.view.state)});h(this,"unfreezeMenu",()=>{this.view.menuFrozen=!1,this.view.state.show=!1,this.view.emitUpdate(this.view.state)});this.editor=e,this.addProsemirrorPlugin(new w.Plugin({key:pt,view:t=>(this.view=new ht(e,t,r=>{this.emit("update",r)}),this.view)}))}static key(){return"sideMenu"}onUpdate(e){return this.on("update",e)}}const G=new Map;function vn(n){if(G.has(n))return G.get(n);const o=new z.Mapping;return n._tiptapEditor.on("transaction",({transaction:e})=>{o.appendMapping(e.mapping)}),n._tiptapEditor.on("destroy",()=>{G.delete(n)}),G.set(n,o),o}function ft(n,o,e="left"){const t=P.ySyncPluginKey.getState(n.prosemirrorState);if(!t){const s=vn(n),i=s.maps.length;return()=>s.slice(i).map(o,e==="left"?-1:1)}const r=P.absolutePositionToRelativePosition(o+(e==="right"?1:-1),t.binding.type,t.binding.mapping);return()=>{const s=P.ySyncPluginKey.getState(n.prosemirrorState),i=P.relativePositionToAbsolutePosition(s.doc,s.binding.type,r,s.binding.mapping);if(i===null)throw new Error("Position not found, cannot track positions");return i+(e==="right"?-1:1)}}const Pn=S.findParentNode(n=>n.type.name==="blockContainer");class Tn{constructor(o,e,t){h(this,"state");h(this,"emitUpdate");h(this,"rootEl");h(this,"pluginState");h(this,"handleScroll",()=>{var o,e;if((o=this.state)!=null&&o.show){const t=(e=this.rootEl)==null?void 0:e.querySelector(`[data-decoration-id="${this.pluginState.decorationId}"]`);if(!t)return;this.state.referencePos=t.getBoundingClientRect(),this.emitUpdate(this.pluginState.triggerCharacter)}});h(this,"closeMenu",()=>{this.editor.transact(o=>o.setMeta($,null))});h(this,"clearQuery",()=>{this.pluginState!==void 0&&this.editor._tiptapEditor.chain().focus().deleteRange({from:this.pluginState.queryStartPos()-(this.pluginState.deleteTriggerCharacter?this.pluginState.triggerCharacter.length:0),to:this.editor.transact(o=>o.selection.from)}).run()});var r;this.editor=o,this.pluginState=void 0,this.emitUpdate=s=>{var i;if(!this.state)throw new Error("Attempting to update uninitialized suggestions menu");e(s,{...this.state,ignoreQueryLength:(i=this.pluginState)==null?void 0:i.ignoreQueryLength})},this.rootEl=t.root,(r=this.rootEl)==null||r.addEventListener("scroll",this.handleScroll,!0)}update(o,e){var d;const t=$.getState(e),r=$.getState(o.state),s=t===void 0&&r!==void 0,i=t!==void 0&&r===void 0;if(!s&&!(t!==void 0&&r!==void 0)&&!i)return;if(this.pluginState=i?t:r,i||!this.editor.isEditable){this.state&&(this.state.show=!1),this.emitUpdate(this.pluginState.triggerCharacter);return}const c=(d=this.rootEl)==null?void 0:d.querySelector(`[data-decoration-id="${this.pluginState.decorationId}"]`);this.editor.isEditable&&c&&(this.state={show:!0,referencePos:c.getBoundingClientRect(),query:this.pluginState.query},this.emitUpdate(this.pluginState.triggerCharacter))}destroy(){var o;(o=this.rootEl)==null||o.removeEventListener("scroll",this.handleScroll,!0)}}const $=new w.PluginKey("SuggestionMenuPlugin");class gt extends a.BlockNoteExtension{constructor(e){super();h(this,"view");h(this,"triggerCharacters",[]);h(this,"addTriggerCharacter",e=>{this.triggerCharacters.push(e)});h(this,"removeTriggerCharacter",e=>{this.triggerCharacters=this.triggerCharacters.filter(t=>t!==e)});h(this,"closeMenu",()=>this.view.closeMenu());h(this,"clearQuery",()=>this.view.clearQuery());const t=this.triggerCharacters;this.addProsemirrorPlugin(new w.Plugin({key:$,view:r=>(this.view=new Tn(e,(s,i)=>{this.emit(`update ${s}`,i)},r),this.view),state:{init(){},apply:(r,s,i,l)=>{if(r.selection.$from.parent.type.spec.code)return s;const c=r.getMeta($);if(typeof c=="object"&&c!==null){s&&this.closeMenu();const u=ft(e,l.selection.from-c.triggerCharacter.length);return{triggerCharacter:c.triggerCharacter,deleteTriggerCharacter:c.deleteTriggerCharacter!==!1,queryStartPos:()=>u()+c.triggerCharacter.length,query:"",decorationId:`id_${Math.floor(Math.random()*4294967295)}`,ignoreQueryLength:c==null?void 0:c.ignoreQueryLength}}if(s===void 0)return s;if(l.selection.from!==l.selection.to||c===null||r.getMeta("focus")||r.getMeta("blur")||r.getMeta("pointer")||s.triggerCharacter!==void 0&&l.selection.from<s.queryStartPos()||!l.selection.$from.sameParent(l.doc.resolve(s.queryStartPos())))return;const d={...s};return d.query=l.doc.textBetween(s.queryStartPos(),l.selection.from),d}},props:{handleTextInput(r,s,i,l){if(s===i){const c=r.state.doc;for(const d of t){const u=d.length>1?c.textBetween(s-d.length,s)+l:l;if(d===u)return r.dispatch(r.state.tr.insertText(l)),r.dispatch(r.state.tr.setMeta($,{triggerCharacter:u}).scrollIntoView()),!0}}return!1},decorations(r){const s=this.getState(r);if(s===void 0)return null;if(!s.deleteTriggerCharacter){const i=Pn(r.selection);if(i)return E.DecorationSet.create(r.doc,[E.Decoration.node(i.pos,i.pos+i.node.nodeSize,{nodeName:"span",class:"bn-suggestion-decorator","data-decoration-id":s.decorationId})])}return E.DecorationSet.create(r.doc,[E.Decoration.inline(s.queryStartPos()-s.triggerCharacter.length,s.queryStartPos(),{nodeName:"span",class:"bn-suggestion-decorator","data-decoration-id":s.decorationId})])}}}))}static key(){return"suggestionMenu"}onUpdate(e,t){return this.triggerCharacters.includes(e)||this.addTriggerCharacter(e),this.on(`update ${e}`,t)}get shown(){var e,t;return((t=(e=this.view)==null?void 0:e.state)==null?void 0:t.show)||!1}}function En(n,o){n.suggestionMenus.addTriggerCharacter(o)}const In=S.Mark.create({name:"insertion",inclusive:!1,excludes:"deletion modification insertion",addAttributes(){return{id:{default:null,validate:"number"}}},extendMarkSchema(n){return n.name!=="insertion"?{}:{blocknoteIgnore:!0,inclusive:!1,toDOM(o,e){return["ins",{"data-id":String(o.attrs.id),"data-inline":String(e),...!e&&{style:"display: contents"}},0]},parseDOM:[{tag:"ins",getAttrs(o){return o.dataset.id?{id:parseInt(o.dataset.id,10)}:!1}}]}}}),xn=S.Mark.create({name:"deletion",inclusive:!1,excludes:"insertion modification deletion",addAttributes(){return{id:{default:null,validate:"number"}}},extendMarkSchema(n){return n.name!=="deletion"?{}:{blocknoteIgnore:!0,inclusive:!1,toDOM(o,e){return["del",{"data-id":String(o.attrs.id),"data-inline":String(e),...!e&&{style:"display: contents"}},0]},parseDOM:[{tag:"del",getAttrs(o){return o.dataset.id?{id:parseInt(o.dataset.id,10)}:!1}}]}}}),Mn=S.Mark.create({name:"modification",inclusive:!1,excludes:"deletion insertion",addAttributes(){return{id:{default:null,validate:"number"},type:{validate:"string"},attrName:{default:null,validate:"string|null"},previousValue:{default:null},newValue:{default:null}}},extendMarkSchema(n){return n.name!=="modification"?{}:{blocknoteIgnore:!0,inclusive:!1,toDOM(o,e){return[e?"span":"div",{"data-type":"modification","data-id":String(o.attrs.id),"data-mod-type":o.attrs.type,"data-mod-prev-val":JSON.stringify(o.attrs.previousValue),"data-mod-new-val":JSON.stringify(o.attrs.newValue)},0]},parseDOM:[{tag:"span[data-type='modification']",getAttrs(o){return o.dataset.id?{id:parseInt(o.dataset.id,10),type:o.dataset.modType,previousValue:o.dataset.modPrevVal,newValue:o.dataset.modNewVal}:!1}},{tag:"div[data-type='modification']",getAttrs(o){return o.dataset.id?{id:parseInt(o.dataset.id,10),type:o.dataset.modType,previousValue:o.dataset.modPrevVal}:!1}}]}}});let L;function Pe(n){L||(L=document.createElement("div"),L.innerHTML="_",L.style.opacity="0",L.style.height="1px",L.style.width="1px",n instanceof Document?n.body.appendChild(L):n.appendChild(L))}function Dn(n){L&&(n instanceof Document?n.body.removeChild(L):n.removeChild(L),L=void 0)}function j(n){return Array.prototype.indexOf.call(n.parentElement.childNodes,n)}function Nn(n){let o=n;for(;o&&o.nodeName!=="TD"&&o.nodeName!=="TH"&&!o.classList.contains("tableWrapper");){if(o.classList.contains("ProseMirror"))return;const e=o.parentNode;if(!e||!(e instanceof Element))return;o=e}return o.nodeName==="TD"||o.nodeName==="TH"?{type:"cell",domNode:o,tbodyNode:o.closest("tbody")}:{type:"wrapper",domNode:o,tbodyNode:o.querySelector("tbody")}}function Ln(n,o){const e=o.querySelectorAll(n);for(let t=0;t<e.length;t++)e[t].style.visibility="hidden"}class kt{constructor(o,e,t){h(this,"state");h(this,"emitUpdate");h(this,"tableId");h(this,"tablePos");h(this,"tableElement");h(this,"menuFrozen",!1);h(this,"mouseState","up");h(this,"prevWasEditable",null);h(this,"viewMousedownHandler",()=>{this.mouseState="down"});h(this,"mouseUpHandler",o=>{this.mouseState="up",this.mouseMoveHandler(o)});h(this,"mouseMoveHandler",o=>{var d,u,p,f,g,k,m;if(this.menuFrozen||this.mouseState==="selecting"||!(o.target instanceof Element)||!this.pmView.dom.contains(o.target))return;const e=Nn(o.target);if((e==null?void 0:e.type)==="cell"&&this.mouseState==="down"&&!((d=this.state)!=null&&d.draggingState)){this.mouseState="selecting",(u=this.state)!=null&&u.show&&(this.state.show=!1,this.state.showAddOrRemoveRowsButton=!1,this.state.showAddOrRemoveColumnsButton=!1,this.emitUpdate());return}if(!e||!this.editor.isEditable){(p=this.state)!=null&&p.show&&(this.state.show=!1,this.state.showAddOrRemoveRowsButton=!1,this.state.showAddOrRemoveColumnsButton=!1,this.emitUpdate());return}if(!e.tbodyNode)return;const t=e.tbodyNode.getBoundingClientRect(),r=dt(e.domNode,this.pmView);if(!r)return;this.tableElement=r.node;let s;const i=this.editor.transact(b=>a.getNodeById(r.id,b.doc));if(!i)throw new Error(`Block with ID ${r.id} not found`);const l=a.nodeToBlock(i.node,this.editor.pmSchema,this.editor.schema.blockSchema,this.editor.schema.inlineContentSchema,this.editor.schema.styleSchema);if(a.editorHasBlockWithType(this.editor,"table")&&(this.tablePos=i.posBeforeNode+1,s=l),!s)return;this.tableId=r.id;const c=(f=e.domNode.closest(".tableWrapper"))==null?void 0:f.querySelector(".table-widgets-container");if((e==null?void 0:e.type)==="wrapper"){const b=o.clientY>=t.bottom-1&&o.clientY<t.bottom+20,y=o.clientX>=t.right-1&&o.clientX<t.right+20,C=o.clientX>t.right||o.clientY>t.bottom;this.state={...this.state,show:!0,showAddOrRemoveRowsButton:b,showAddOrRemoveColumnsButton:y,referencePosTable:t,block:s,widgetContainer:c,colIndex:C||(g=this.state)==null?void 0:g.colIndex,rowIndex:C||(k=this.state)==null?void 0:k.rowIndex,referencePosCell:C||(m=this.state)==null?void 0:m.referencePosCell}}else{const b=j(e.domNode),y=j(e.domNode.parentElement),C=e.domNode.getBoundingClientRect();if(this.state!==void 0&&this.state.show&&this.tableId===r.id&&this.state.rowIndex===y&&this.state.colIndex===b)return;this.state={show:!0,showAddOrRemoveColumnsButton:b===s.content.rows[0].cells.length-1,showAddOrRemoveRowsButton:y===s.content.rows.length-1,referencePosTable:t,block:s,draggingState:void 0,referencePosCell:C,colIndex:b,rowIndex:y,widgetContainer:c}}return this.emitUpdate(),!1});h(this,"dragOverHandler",o=>{var f;if(((f=this.state)==null?void 0:f.draggingState)===void 0)return;o.preventDefault(),o.dataTransfer.dropEffect="move",Ln(".prosemirror-dropcursor-block, .prosemirror-dropcursor-inline",this.pmView.root);const e={left:Math.min(Math.max(o.clientX,this.state.referencePosTable.left+1),this.state.referencePosTable.right-1),top:Math.min(Math.max(o.clientY,this.state.referencePosTable.top+1),this.state.referencePosTable.bottom-1)},t=this.pmView.root.elementsFromPoint(e.left,e.top).filter(g=>g.tagName==="TD"||g.tagName==="TH");if(t.length===0)return;const r=t[0];let s=!1;const i=j(r.parentElement),l=j(r),c=this.state.draggingState.draggedCellOrientation==="row"?this.state.rowIndex:this.state.colIndex,u=(this.state.draggingState.draggedCellOrientation==="row"?i:l)!==c;(this.state.rowIndex!==i||this.state.colIndex!==l)&&(this.state.rowIndex=i,this.state.colIndex=l,this.state.referencePosCell=r.getBoundingClientRect(),s=!0);const p=this.state.draggingState.draggedCellOrientation==="row"?e.top:e.left;this.state.draggingState.mousePos!==p&&(this.state.draggingState.mousePos=p,s=!0),s&&this.emitUpdate(),u&&this.editor.transact(g=>g.setMeta(_,!0))});h(this,"dropHandler",o=>{if(this.mouseState="up",this.state===void 0||this.state.draggingState===void 0)return!1;if(this.state.rowIndex===void 0||this.state.colIndex===void 0)throw new Error("Attempted to drop table row or column, but no table block was hovered prior.");o.preventDefault();const{draggingState:e,colIndex:t,rowIndex:r}=this.state,s=this.state.block.content.columnWidths;if(e.draggedCellOrientation==="row"){if(!a.canRowBeDraggedInto(this.state.block,e.originalIndex,r))return!1;const i=a.moveRow(this.state.block,e.originalIndex,r);this.editor.updateBlock(this.state.block,{type:"table",content:{...this.state.block.content,rows:i}})}else{if(!a.canColumnBeDraggedInto(this.state.block,e.originalIndex,t))return!1;const i=a.moveColumn(this.state.block,e.originalIndex,t),[l]=s.splice(e.originalIndex,1);s.splice(t,0,l),this.editor.updateBlock(this.state.block,{type:"table",content:{...this.state.block.content,columnWidths:s,rows:i}})}return this.editor.setTextCursorPosition(this.state.block.id),!0});this.editor=o,this.pmView=e,this.emitUpdate=()=>{if(!this.state)throw new Error("Attempting to update uninitialized image toolbar");t(this.state)},e.dom.addEventListener("mousemove",this.mouseMoveHandler),e.dom.addEventListener("mousedown",this.viewMousedownHandler),window.addEventListener("mouseup",this.mouseUpHandler),e.root.addEventListener("dragover",this.dragOverHandler),e.root.addEventListener("drop",this.dropHandler)}update(){var r;if(!this.state||!this.state.show)return;if(this.state.block=this.editor.getBlock(this.state.block.id),!this.state.block||this.state.block.type!=="table"||!((r=this.tableElement)!=null&&r.isConnected)){this.state.show=!1,this.state.showAddOrRemoveRowsButton=!1,this.state.showAddOrRemoveColumnsButton=!1,this.emitUpdate();return}const{height:o,width:e}=a.getDimensionsOfTable(this.state.block);this.state.rowIndex!==void 0&&this.state.colIndex!==void 0&&(this.state.rowIndex>=o&&(this.state.rowIndex=o-1),this.state.colIndex>=e&&(this.state.colIndex=e-1));const t=this.tableElement.querySelector("tbody");if(!t)throw new Error("Table block does not contain a 'tbody' HTML element. This should never happen.");if(this.state.rowIndex!==void 0&&this.state.colIndex!==void 0){const i=t.children[this.state.rowIndex].children[this.state.colIndex];i?this.state.referencePosCell=i.getBoundingClientRect():(this.state.rowIndex=void 0,this.state.colIndex=void 0)}this.state.referencePosTable=t.getBoundingClientRect(),this.emitUpdate()}destroy(){this.pmView.dom.removeEventListener("mousemove",this.mouseMoveHandler),window.removeEventListener("mouseup",this.mouseUpHandler),this.pmView.dom.removeEventListener("mousedown",this.viewMousedownHandler),this.pmView.root.removeEventListener("dragover",this.dragOverHandler),this.pmView.root.removeEventListener("drop",this.dropHandler)}}const _=new w.PluginKey("TableHandlesPlugin");class bt extends a.BlockNoteExtension{constructor(e){super();h(this,"view");h(this,"colDragStart",e=>{if(this.view.state===void 0||this.view.state.colIndex===void 0)throw new Error("Attempted to drag table column, but no table block was hovered prior.");this.view.state.draggingState={draggedCellOrientation:"col",originalIndex:this.view.state.colIndex,mousePos:e.clientX},this.view.emitUpdate(),this.editor.transact(t=>t.setMeta(_,{draggedCellOrientation:this.view.state.draggingState.draggedCellOrientation,originalIndex:this.view.state.colIndex,newIndex:this.view.state.colIndex,tablePos:this.view.tablePos})),!this.editor.headless&&(Pe(this.editor.prosemirrorView.root),e.dataTransfer.setDragImage(L,0,0),e.dataTransfer.effectAllowed="move")});h(this,"rowDragStart",e=>{if(this.view.state===void 0||this.view.state.rowIndex===void 0)throw new Error("Attempted to drag table row, but no table block was hovered prior.");this.view.state.draggingState={draggedCellOrientation:"row",originalIndex:this.view.state.rowIndex,mousePos:e.clientY},this.view.emitUpdate(),this.editor.transact(t=>t.setMeta(_,{draggedCellOrientation:this.view.state.draggingState.draggedCellOrientation,originalIndex:this.view.state.rowIndex,newIndex:this.view.state.rowIndex,tablePos:this.view.tablePos})),!this.editor.headless&&(Pe(this.editor.prosemirrorView.root),e.dataTransfer.setDragImage(L,0,0),e.dataTransfer.effectAllowed="copyMove")});h(this,"dragEnd",()=>{if(this.view.state===void 0)throw new Error("Attempted to drag table row, but no table block was hovered prior.");this.view.state.draggingState=void 0,this.view.emitUpdate(),this.editor.transact(e=>e.setMeta(_,null)),!this.editor.headless&&Dn(this.editor.prosemirrorView.root)});h(this,"freezeHandles",()=>{this.view.menuFrozen=!0});h(this,"unfreezeHandles",()=>{this.view.menuFrozen=!1});h(this,"getCellsAtRowHandle",(e,t)=>a.getCellsAtRowHandle(e,t));h(this,"getCellsAtColumnHandle",(e,t)=>a.getCellsAtColumnHandle(e,t));h(this,"setCellSelection",(e,t,r=t)=>{const s=this.view;if(!s)throw new Error("Table handles view not initialized");const i=e.doc.resolve(s.tablePos+1),l=e.doc.resolve(i.posAtIndex(t.row)+1),c=e.doc.resolve(l.posAtIndex(t.col)),d=e.doc.resolve(i.posAtIndex(r.row)+1),u=e.doc.resolve(d.posAtIndex(r.col)),p=e.tr;return p.setSelection(new N.CellSelection(c,u)),e.apply(p)});h(this,"addRowOrColumn",(e,t)=>{this.editor.exec((r,s)=>{const i=this.setCellSelection(r,t.orientation==="row"?{row:e,col:0}:{row:0,col:e});return t.orientation==="row"?t.side==="above"?N.addRowBefore(i,s):N.addRowAfter(i,s):t.side==="left"?N.addColumnBefore(i,s):N.addColumnAfter(i,s)})});h(this,"removeRowOrColumn",(e,t)=>t==="row"?this.editor.exec((r,s)=>{const i=this.setCellSelection(r,{row:e,col:0});return N.deleteRow(i,s)}):this.editor.exec((r,s)=>{const i=this.setCellSelection(r,{row:0,col:e});return N.deleteColumn(i,s)}));h(this,"mergeCells",e=>this.editor.exec((t,r)=>{const s=e?this.setCellSelection(t,e.relativeStartCell,e.relativeEndCell):t;return N.mergeCells(s,r)}));h(this,"splitCell",e=>this.editor.exec((t,r)=>{const s=e?this.setCellSelection(t,e):t;return N.splitCell(s,r)}));h(this,"getCellSelection",()=>this.editor.transact(e=>{const t=e.selection;let r=t.$from,s=t.$to;if(a.isTableCellSelection(t)){const{ranges:k}=t;k.forEach(m=>{r=m.$from.min(r??m.$from),s=m.$to.max(s??m.$to)})}else if(r=e.doc.resolve(t.$from.pos-t.$from.parentOffset-1),s=e.doc.resolve(t.$to.pos-t.$to.parentOffset-1),r.pos===0||s.pos===0)return;const i=e.doc.resolve(r.pos-r.parentOffset-1),l=e.doc.resolve(s.pos-s.parentOffset-1),c=e.doc.resolve(i.pos-i.parentOffset-1),d=r.index(i.depth),u=i.index(c.depth),p=s.index(l.depth),f=l.index(c.depth),g=[];for(let k=u;k<=f;k++)for(let m=d;m<=p;m++)g.push({row:k,col:m});return{from:{row:u,col:d},to:{row:f,col:p},cells:g}}));h(this,"getMergeDirection",e=>this.editor.transact(t=>{const r=a.isTableCellSelection(t.selection)?t.selection:void 0;if(!r||!e||r.ranges.length<=1)return;const s=this.getCellSelection();if(s)return a.areInSameColumn(s.from,s.to,e)?"vertical":"horizontal"}));h(this,"cropEmptyRowsOrColumns",(e,t)=>a.cropEmptyRowsOrColumns(e,t));h(this,"addRowsOrColumns",(e,t,r)=>a.addRowsOrColumns(e,t,r));this.editor=e,this.addProsemirrorPlugin(new w.Plugin({key:_,view:t=>(this.view=new kt(e,t,r=>{this.emit("update",r)}),this.view),props:{decorations:t=>{if(this.view===void 0||this.view.state===void 0||this.view.state.draggingState===void 0||this.view.tablePos===void 0)return;const r=this.view.state.draggingState.draggedCellOrientation==="row"?this.view.state.rowIndex:this.view.state.colIndex;if(r===void 0)return;const s=[],{block:i,draggingState:l}=this.view.state,{originalIndex:c,draggedCellOrientation:d}=l;if(r===c||!i||d==="row"&&!a.canRowBeDraggedInto(i,c,r)||d==="col"&&!a.canColumnBeDraggedInto(i,c,r))return E.DecorationSet.create(t.doc,s);const u=t.doc.resolve(this.view.tablePos+1);return this.view.state.draggingState.draggedCellOrientation==="row"?a.getCellsAtRowHandle(this.view.state.block,r).forEach(({row:f,col:g})=>{const k=t.doc.resolve(u.posAtIndex(f)+1),m=t.doc.resolve(k.posAtIndex(g)+1),b=m.node(),y=m.pos+(r>c?b.nodeSize-2:0);s.push(E.Decoration.widget(y,()=>{const C=document.createElement("div");return C.className="bn-table-drop-cursor",C.style.left="0",C.style.right="0",r>c?C.style.bottom="-2px":C.style.top="-3px",C.style.height="4px",C}))}):a.getCellsAtColumnHandle(this.view.state.block,r).forEach(({row:f,col:g})=>{const k=t.doc.resolve(u.posAtIndex(f)+1),m=t.doc.resolve(k.posAtIndex(g)+1),b=m.node(),y=m.pos+(r>c?b.nodeSize-2:0);s.push(E.Decoration.widget(y,()=>{const C=document.createElement("div");return C.className="bn-table-drop-cursor",C.style.top="0",C.style.bottom="0",r>c?C.style.right="-2px":C.style.left="-3px",C.style.width="4px",C}))}),E.DecorationSet.create(t.doc,s)}}}))}static key(){return"tableHandles"}onUpdate(e){return this.on("update",e)}}const An=S.Extension.create({name:"textAlignment",addGlobalAttributes(){return[{types:["tableCell","tableHeader"],attributes:{textAlignment:{default:"left",parseHTML:n=>n.getAttribute("data-text-alignment"),renderHTML:n=>n.textAlignment==="left"?{}:{"data-text-alignment":n.textAlignment}}}}]}}),On=S.Extension.create({name:"blockTextColor",addGlobalAttributes(){return[{types:["table","tableCell","tableHeader"],attributes:{textColor:a.getTextColorAttribute()}}]}}),Hn=S.Extension.create({name:"trailingNode",addProseMirrorPlugins(){const n=new w.PluginKey(this.name);return[new w.Plugin({key:n,appendTransaction:(o,e,t)=>{const{doc:r,tr:s,schema:i}=t,l=n.getState(t),c=r.content.size-2,d=i.nodes.blockContainer,u=i.nodes.paragraph;if(l)return s.insert(c,d.create(void 0,u.create()))},state:{init:(o,e)=>{},apply:(o,e)=>{if(!o.docChanged)return e;let t=o.doc.lastChild;if(!t||t.type.name!=="blockGroup")throw new Error("Expected blockGroup");if(t=t.lastChild,!t||t.type.name!=="blockContainer")return!0;const r=t.firstChild;if(!r)throw new Error("Expected blockContent");return t.nodeSize>4||r.type.spec.content!=="inline*"}}})]}}),Rn={blockColor:"data-block-color",blockStyle:"data-block-style",id:"data-id",depth:"data-depth",depthChange:"data-depth-change"},Un=S.Node.create({name:"blockContainer",group:"blockGroupChild bnBlock",content:"blockContent blockGroup?",priority:50,defining:!0,marks:"insertion modification deletion",parseHTML(){return[{tag:"div[data-node-type="+this.name+"]",getAttrs:n=>{if(typeof n=="string")return!1;const o={};for(const[e,t]of Object.entries(Rn))n.getAttribute(t)&&(o[e]=n.getAttribute(t));return o}},{tag:'div[data-node-type="blockOuter"]',skip:!0}]},renderHTML({HTMLAttributes:n}){var r;const o=document.createElement("div");o.className="bn-block-outer",o.setAttribute("data-node-type","blockOuter");for(const[s,i]of Object.entries(n))s!=="class"&&o.setAttribute(s,i);const e={...((r=this.options.domAttributes)==null?void 0:r.block)||{},...n},t=document.createElement("div");t.className=a.mergeCSSClasses("bn-block",e.class),t.setAttribute("data-node-type",this.name);for(const[s,i]of Object.entries(e))s!=="class"&&t.setAttribute(s,i);return o.appendChild(t),{dom:o,contentDOM:t}}}),Fn=S.Node.create({name:"blockGroup",group:"childContainer",content:"blockGroupChild+",marks:"deletion insertion modification",parseHTML(){return[{tag:"div",getAttrs:n=>typeof n=="string"?!1:n.getAttribute("data-node-type")==="blockGroup"?null:!1}]},renderHTML({HTMLAttributes:n}){var t;const o={...((t=this.options.domAttributes)==null?void 0:t.blockGroup)||{},...n},e=document.createElement("div");e.className=a.mergeCSSClasses("bn-block-group",o.class),e.setAttribute("data-node-type","blockGroup");for(const[r,s]of Object.entries(o))r!=="class"&&e.setAttribute(r,s);return{dom:e,contentDOM:e}}}),_n=S.Node.create({name:"doc",topNode:!0,content:"blockGroup",marks:"insertion modification deletion"}),yt=n=>{var r;const o={},e=Vn(n);for(const s of e)o[s.name]=s;n.collaboration&&(o.ySyncPlugin=new oe(n.collaboration.fragment),o.yUndoPlugin=new ne({editor:n.editor}),(r=n.collaboration.provider)!=null&&r.awareness&&(o.yCursorPlugin=new X(n.collaboration)),o.forkYDocPlugin=new tn({editor:n.editor,collaboration:n.collaboration}),o.schemaMigrationPlugin=new de(n.collaboration.fragment)),o.formattingToolbar=new rt(n.editor),o.linkToolbar=new at(n.editor),o.sideMenu=new mt(n.editor),o.suggestionMenus=new gt(n.editor),o.filePanel=new tt(n.editor),o.placeholder=new kn(n.editor,n.placeholders),(n.animations??!0)&&(o.animations=new yn),n.tableHandles&&(o.tableHandles=new bt(n.editor)),o.nodeSelectionKeyboard=new fn,o.blockChange=new en,o.showSelection=new wn(n.editor),n.comments&&(o.comments=new cn(n.editor,n.comments.threadStore,Ze.name,n.comments.schema));const t=n.disableExtensions||[];for(const s of t)delete o[s];return o};let Te=!1;const Vn=n=>{const o=[S.extensions.ClipboardTextSerializer,S.extensions.Commands,S.extensions.Editable,S.extensions.FocusEvents,S.extensions.Tabindex,Ft.Gapcursor,S.Extension.create({name:"dropCursor",addProseMirrorPlugins:()=>[n.dropCursor({width:5,color:"#ddeeff",editor:n.editor})]}),a.UniqueID.configure({types:["blockContainer","columnList","column"],setIdAttribute:n.setIdAttribute}),ln,$t.Text,In,xn,Mn,Vt.Link.extend({inclusive:!1}).configure({defaultProtocol:lt,protocols:Te?[]:ct}),...Object.values(n.styleSpecs).map(e=>e.implementation.mark.configure({editor:n.editor})),On,Zo,An,S.Extension.create({name:"OverrideEscape",addKeyboardShortcuts(){return{Escape:()=>n.editor.suggestionMenus.shown?!1:this.editor.commands.blur()}}}),_n,Un.configure({editor:n.editor,domAttributes:n.domAttributes}),hn.configure({editor:n.editor,tabBehavior:n.tabBehavior}),Fn.configure({domAttributes:n.domAttributes}),...Object.values(n.inlineContentSpecs).filter(e=>e.config!=="link"&&e.config!=="text").map(e=>e.implementation.node.configure({editor:n.editor})),...Object.values(n.blockSpecs).flatMap(e=>[..."node"in e.implementation?[e.implementation.node.configure({editor:n.editor,domAttributes:n.domAttributes})]:[]]),Qo(n.editor),Xo(n.editor,n.pasteHandler||(e=>e.defaultPasteHandler())),Lo(n.editor),...n.trailingBlock===void 0||n.trailingBlock?[Hn]:[],...n.comments?[Ze]:[]];return Te=!0,n.collaboration||o.push(_t.History),o};function $n(n,o){const e=[];return n.forEach((t,r,s)=>{s!==o&&e.push(t)}),T.Fragment.from(e)}function zn(n,o){const e=[];for(let t=0;t<n.childCount;t++)if(n.child(t).type.name==="tableRow")if(e.length>0&&e[e.length-1].type.name==="table"){const r=e[e.length-1],s=r.copy(r.content.addToEnd(n.child(t)));e[e.length-1]=s}else{const r=o.nodes.table.createChecked(void 0,n.child(t));e.push(r)}else e.push(n.child(t));return n=T.Fragment.from(e),n}function Kn(n,o){let e=T.Fragment.from(n.content);if(e=zn(e,o.state.schema),!qn(e,o))return new T.Slice(e,n.openStart,n.openEnd);for(let t=0;t<e.childCount;t++)if(e.child(t).type.spec.group==="blockContent"){const r=[e.child(t)];if(t+1<e.childCount&&e.child(t+1).type.name==="blockGroup"){const i=e.child(t+1).child(0).child(0);(i.type.name==="bulletListItem"||i.type.name==="numberedListItem"||i.type.name==="checkListItem")&&(r.push(e.child(t+1)),e=$n(e,t+1))}const s=o.state.schema.nodes.blockContainer.createChecked(void 0,r);e=e.replaceChild(t,s)}return new T.Slice(e,n.openStart,n.openEnd)}function qn(n,o){var s,i;const e=n.childCount===1,t=((s=n.firstChild)==null?void 0:s.type.spec.content)==="inline*",r=((i=n.firstChild)==null?void 0:i.type.spec.content)==="tableRow+";if(e){if(t)return!1;if(r){const l=a.getBlockInfoFromSelection(o.state);if(l.isBlockContainer)return!(l.blockContent.node.type.spec.content==="tableRow+")}}return!0}const Gn={enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!1};class ue extends a.EventEmitter{constructor(e){var d,u,p,f,g,k,m,b,y,C,A;super();h(this,"pmSchema");h(this,"extensions",{});h(this,"_tiptapEditor");h(this,"elementRenderer",null);h(this,"blockCache",new WeakMap);h(this,"dictionary");h(this,"schema");h(this,"blockImplementations");h(this,"inlineContentImplementations");h(this,"styleImplementations");h(this,"formattingToolbar");h(this,"linkToolbar");h(this,"sideMenu");h(this,"suggestionMenus");h(this,"filePanel");h(this,"tableHandles");h(this,"comments");h(this,"showSelectionPlugin");h(this,"forkYDocPlugin");h(this,"uploadFile");h(this,"onUploadStartCallbacks",[]);h(this,"onUploadEndCallbacks",[]);h(this,"resolveFileUrl");h(this,"resolveUsers");h(this,"settings");h(this,"activeTransaction",null);h(this,"mount",e=>{this._tiptapEditor.mount({mount:e})});h(this,"unmount",()=>{this._tiptapEditor.unmount()});this.options=e;const t=e;if(t.onEditorContentChange)throw new Error("onEditorContentChange initialization option is deprecated, use <BlockNoteView onChange={...} />, the useEditorChange(...) hook, or editor.onChange(...)");if(t.onTextCursorPositionChange)throw new Error("onTextCursorPositionChange initialization option is deprecated, use <BlockNoteView onSelectionChange={...} />, the useEditorSelectionChange(...) hook, or editor.onSelectionChange(...)");if(t.onEditorReady)throw new Error("onEditorReady is deprecated. Editor is immediately ready for use after creation.");if(t.editable)throw new Error("editable initialization option is deprecated, use <BlockNoteView editable={true/false} />, or alternatively editor.isEditable = true/false");this.dictionary=e.dictionary||qt.en,this.settings={tables:{splitCells:((d=e==null?void 0:e.tables)==null?void 0:d.splitCells)??!1,cellBackgroundColor:((u=e==null?void 0:e.tables)==null?void 0:u.cellBackgroundColor)??!1,cellTextColor:((p=e==null?void 0:e.tables)==null?void 0:p.cellTextColor)??!1,headers:((f=e==null?void 0:e.tables)==null?void 0:f.headers)??!1}};const r={defaultStyles:!0,schema:e.schema||a.BlockNoteSchema.create(),...e,placeholders:{...this.dictionary.placeholders,...e.placeholders}};if(r.comments&&!r.resolveUsers)throw new Error("resolveUsers is required when using comments");this.resolveUsers=r.resolveUsers,this.schema=r.schema,this.blockImplementations=r.schema.blockSpecs,this.inlineContentImplementations=r.schema.inlineContentSpecs,this.styleImplementations=r.schema.styleSpecs,this.extensions=yt({editor:this,domAttributes:r.domAttributes||{},blockSpecs:this.schema.blockSpecs,styleSpecs:this.schema.styleSpecs,inlineContentSpecs:this.schema.inlineContentSpecs,collaboration:r.collaboration,trailingBlock:r.trailingBlock,disableExtensions:r.disableExtensions,setIdAttribute:r.setIdAttribute,animations:r.animations??!0,tableHandles:a.editorHasBlockWithType(this,"table"),dropCursor:this.options.dropCursor??Dt.dropCursor,placeholders:r.placeholders,tabBehavior:r.tabBehavior,comments:r.comments,pasteHandler:r.pasteHandler}),(((g=r._tiptapOptions)==null?void 0:g.extensions)||[]).forEach(B=>{this.extensions[B.name]=B});for(let B of r.extensions||[]){typeof B=="function"&&(B=B(this));const v=B.key??B.constructor.key();if(!v)throw new Error(`Extension ${B.constructor.name} does not have a key method`);if(this.extensions[v])throw new Error(`Extension ${B.constructor.name} already exists with key ${v}`);this.extensions[v]=B}if(Object.entries(r._extensions||{}).forEach(([B,v])=>{const I=typeof v=="function"?v(this):v;if(!("plugin"in I)){this.extensions[B]=I;return}this.extensions[B]=new class extends a.BlockNoteExtension{static key(){return B}constructor(){super(),this.addProsemirrorPlugin(I.plugin)}get priority(){return I.priority}}}),this.formattingToolbar=this.extensions.formattingToolbar,this.linkToolbar=this.extensions.linkToolbar,this.sideMenu=this.extensions.sideMenu,this.suggestionMenus=this.extensions.suggestionMenus,this.filePanel=this.extensions.filePanel,this.tableHandles=this.extensions.tableHandles,this.comments=this.extensions.comments,this.showSelectionPlugin=this.extensions.showSelection,this.forkYDocPlugin=this.extensions.forkYDocPlugin,r.uploadFile){const B=r.uploadFile;this.uploadFile=async(v,D)=>{this.onUploadStartCallbacks.forEach(I=>I.apply(this,[D]));try{return await B(v,D)}finally{this.onUploadEndCallbacks.forEach(I=>I.apply(this,[D]))}}}this.resolveFileUrl=r.resolveFileUrl;const s="ySyncPlugin"in this.extensions||"liveblocksExtension"in this.extensions;s&&r.initialContent&&console.warn("When using Collaboration, initialContent might cause conflicts, because changes should come from the collaboration provider");const i=Object.fromEntries(Object.values(this.schema.blockSpecs).map(B=>B.extensions).filter(B=>B!==void 0).flat().map(B=>[B.key??B.constructor.key(),B])),l=[...Object.entries({...this.extensions,...i}).map(([B,v])=>{if(v instanceof S.Extension||v instanceof S.Node||v instanceof S.Mark)return v;if(v instanceof a.BlockNoteExtension)return!v.plugins.length&&!v.keyboardShortcuts&&!v.inputRules&&!v.tiptapExtensions?void 0:S.Extension.create({name:B,priority:v.priority,addProseMirrorPlugins:()=>v.plugins,addExtensions:()=>v.tiptapExtensions||[],addInputRules:v.inputRules?()=>v.inputRules.map(D=>new S.InputRule({find:D.find,handler:({range:I,match:F,state:x})=>{const M=D.replace({match:F,range:I,editor:this});if(M){const wt=this.getTextCursorPosition();if(this.schema.blockSchema[wt.block.type].content!=="inline")return;const St=a.getBlockInfoFromTransaction(x.tr),Ct=x.tr.deleteRange(I.from,I.to);a.updateBlockTr(Ct,St.bnBlock.beforePos,M);return}return null}})):void 0,addKeyboardShortcuts:v.keyboardShortcuts?()=>Object.fromEntries(Object.entries(v.keyboardShortcuts).map(([D,I])=>[D,()=>I({editor:this})])):void 0})})].filter(B=>B!==void 0),c={...Gn,...r._tiptapOptions,element:null,extensions:l,editorProps:{...(k=r._tiptapOptions)==null?void 0:k.editorProps,attributes:{tabIndex:"0",...(b=(m=r._tiptapOptions)==null?void 0:m.editorProps)==null?void 0:b.attributes,...(y=r.domAttributes)==null?void 0:y.editor,class:a.mergeCSSClasses("bn-editor",r.defaultStyles?"bn-default-styles":"",((A=(C=r.domAttributes)==null?void 0:C.editor)==null?void 0:A.class)||"")},transformPasted:Kn}};try{const B=r.initialContent||(s?[{type:"paragraph",id:"initialBlockId"}]:[{type:"paragraph",id:a.UniqueID.options.generateID()}]);if(!Array.isArray(B)||B.length===0)throw new Error("initialContent must be a non-empty array of blocks, received: "+B);const v=S.getSchema(c.extensions),D=B.map(F=>a.blockToNode(F,v,this.schema.styleSchema).toJSON()),I=S.createDocument({type:"doc",content:[{type:"blockGroup",content:D}]},v,c.parseOptions);this._tiptapEditor=new S.Editor({...c,content:I.toJSON()}),this.pmSchema=this._tiptapEditor.schema}catch(B){throw new Error("Error creating document from blocks passed as `initialContent`",{cause:B})}this.pmSchema.cached.blockNoteEditor=this,this.emit("create")}static create(e){return new ue(e??{})}exec(e){if(this.activeTransaction)throw new Error("`exec` should not be called within a `transact` call, move the `exec` call outside of the `transact` call");const t=this._tiptapEditor.state,r=this._tiptapEditor.view;return e(t,i=>r.dispatch(i),r)}canExec(e){if(this.activeTransaction)throw new Error("`canExec` should not be called within a `transact` call, move the `canExec` call outside of the `transact` call");const t=this._tiptapEditor.state,r=this._tiptapEditor.view;return e(t,void 0,r)}transact(e){if(this.activeTransaction)return e(this.activeTransaction);try{this.activeTransaction=this._tiptapEditor.state.tr;const t=e(this.activeTransaction),r=this.activeTransaction;return this.activeTransaction=null,r&&(r.docChanged||r.selectionSet||r.scrolledIntoView||r.storedMarksSet||!r.isGeneric)&&this._tiptapEditor.view.dispatch(r),t}finally{this.activeTransaction=null}}extension(e,t=e.key()){const r=this.extensions[t];if(!r)throw new Error(`Extension ${t} not found`);return r}get prosemirrorState(){if(this.activeTransaction)throw new Error("`prosemirrorState` should not be called within a `transact` call, move the `prosemirrorState` call outside of the `transact` call or use `editor.transact` to read the current editor state");return this._tiptapEditor.state}get prosemirrorView(){return this._tiptapEditor.view}get domElement(){var e;return(e=this.prosemirrorView)==null?void 0:e.dom}isFocused(){var e;return((e=this.prosemirrorView)==null?void 0:e.hasFocus())||!1}get headless(){return!this._tiptapEditor.isInitialized}focus(){this.headless||this.prosemirrorView.focus()}onUploadStart(e){return this.onUploadStartCallbacks.push(e),()=>{const t=this.onUploadStartCallbacks.indexOf(e);t>-1&&this.onUploadStartCallbacks.splice(t,1)}}onUploadEnd(e){return this.onUploadEndCallbacks.push(e),()=>{const t=this.onUploadEndCallbacks.indexOf(e);t>-1&&this.onUploadEndCallbacks.splice(t,1)}}get topLevelBlocks(){return this.document}get document(){return this.transact(e=>a.docToBlocks(e.doc,this.pmSchema))}getBlock(e){return this.transact(t=>ze(t.doc,e))}getPrevBlock(e){return this.transact(t=>Ke(t.doc,e))}getNextBlock(e){return this.transact(t=>qe(t.doc,e))}getParentBlock(e){return this.transact(t=>Ge(t.doc,e))}forEachBlock(e,t=!1){const r=this.document.slice();t&&r.reverse();function s(i){for(const l of i){if(e(l)===!1)return!1;const c=t?l.children.slice().reverse():l.children;if(!s(c))return!1}return!0}s(r)}onEditorContentChange(e){this._tiptapEditor.on("update",e)}onEditorSelectionChange(e){this._tiptapEditor.on("selectionUpdate",e)}getTextCursorPosition(){return this.transact(e=>So(e))}setTextCursorPosition(e,t="start"){return this.transact(r=>je(r,e,t))}getSelection(){return this.transact(e=>bo(e))}getSelectionCutBlocks(){return this.transact(e=>wo(e))}setSelection(e,t){return this.transact(r=>yo(r,e,t))}get isEditable(){return this._tiptapEditor.isEditable===void 0?!0:this._tiptapEditor.isEditable}set isEditable(e){this._tiptapEditor.options.editable!==e&&this._tiptapEditor.setEditable(e)}insertBlocks(e,t,r="before"){return this.transact(s=>De(s,e,t,r))}updateBlock(e,t){return this.transact(r=>a.updateBlock(r,e,t))}removeBlocks(e){return this.transact(t=>ee(t,e,[]).removedBlocks)}replaceBlocks(e,t){return this.transact(r=>ee(r,e,t))}undo(){return this.options.collaboration?this.exec(P.undoCommand):this.exec(pe.undo)}redo(){return this.options.collaboration?this.exec(P.redoCommand):this.exec(pe.redo)}insertInlineContent(e,{updateSelection:t=!1}={}){const r=a.inlineContentToNodes(e,this.pmSchema);this.transact(s=>{ko(s,{from:s.selection.from,to:s.selection.to},r,{updateSelection:t})})}getActiveStyles(){return this.transact(e=>{const t={},r=e.selection.$to.marks();for(const s of r){const i=this.schema.styleSchema[s.type.name];if(!i){s.type.name!=="link"&&!s.type.spec.blocknoteIgnore&&console.warn("mark not found in styleschema",s.type.name);continue}i.propSchema==="boolean"?t[i.type]=!0:t[i.type]=s.attrs.stringValue}return t})}addStyles(e){for(const[t,r]of Object.entries(e)){const s=this.schema.styleSchema[t];if(!s)throw new Error(`style ${t} not found in styleSchema`);if(s.propSchema==="boolean")this._tiptapEditor.commands.setMark(t);else if(s.propSchema==="string")this._tiptapEditor.commands.setMark(t,{stringValue:r});else throw new a.UnreachableCaseError(s.propSchema)}}removeStyles(e){for(const t of Object.keys(e))this._tiptapEditor.commands.unsetMark(t)}toggleStyles(e){for(const[t,r]of Object.entries(e)){const s=this.schema.styleSchema[t];if(!s)throw new Error(`style ${t} not found in styleSchema`);if(s.propSchema==="boolean")this._tiptapEditor.commands.toggleMark(t);else if(s.propSchema==="string")this._tiptapEditor.commands.toggleMark(t,{stringValue:r});else throw new a.UnreachableCaseError(s.propSchema)}}getSelectedText(){return this.transact(e=>e.doc.textBetween(e.selection.from,e.selection.to))}getSelectedLinkUrl(){return this._tiptapEditor.getAttributes("link").href}createLink(e,t){if(e==="")return;const r=this.pmSchema.mark("link",{href:e});this.transact(s=>{const{from:i,to:l}=s.selection;t?s.insertText(t,i,l).addMark(i,i+t.length,r):s.setSelection(w.TextSelection.create(s.doc,l)).addMark(i,l,r)})}canNestBlock(){return fo(this)}nestBlock(){$e(this)}canUnnestBlock(){return go(this)}unnestBlock(){mo(this)}moveBlocksUp(){return uo(this)}moveBlocksDown(){return ho(this)}blocksToHTMLLossy(e=this.document){return K(this.pmSchema,this).exportBlocks(e,{})}blocksToFullHTML(e){return Re(this.pmSchema,this).serializeBlocks(e,{})}tryParseHTMLToBlocks(e){return ie(e,this.pmSchema)}blocksToMarkdownLossy(e=this.document){return We(e,this.pmSchema,this,{})}async tryParseMarkdownToBlocks(e){return Ye(e,this.pmSchema)}updateCollaborationUserInfo(e){if(!this.options.collaboration)throw new Error("Cannot update collaboration user info when collaboration is disabled.");this.extensions.yCursorPlugin.updateUser(e)}onBeforeChange(e){return this.extensions.blockChange.subscribe(t=>e(this,t))}onChange(e){const t=({transaction:r,appendedTransactions:s})=>{e(this,{getChanges:()=>se(r,s)})};return this._tiptapEditor.on("update",t),()=>{this._tiptapEditor.off("update",t)}}onSelectionChange(e,t){const r=s=>{s.transaction.getMeta(P.ySyncPluginKey)&&!t||e(this)};return this._tiptapEditor.on("selectionUpdate",r),()=>{this._tiptapEditor.off("selectionUpdate",r)}}onCreate(e){return this.on("create",e),()=>{this.off("create",e)}}getSelectionBoundingBox(){if(!this.prosemirrorView)return;const{selection:e}=this.prosemirrorState,{ranges:t}=e,r=Math.min(...t.map(i=>i.$from.pos)),s=Math.max(...t.map(i=>i.$to.pos));if(S.isNodeSelection(e)){const i=this.prosemirrorView.nodeDOM(r);if(i)return i.getBoundingClientRect()}return S.posToDOMRect(this.prosemirrorView,r,s)}get isEmpty(){const e=this.document;return e.length===0||e.length===1&&e[0].type==="paragraph"&&e[0].content.length===0}openSuggestionMenu(e,t){this.prosemirrorView&&(this.focus(),this.transact(r=>{t!=null&&t.deleteTriggerCharacter&&r.insertText(e),r.scrollIntoView().setMeta(this.suggestionMenus.plugins[0],{triggerCharacter:e,deleteTriggerCharacter:(t==null?void 0:t.deleteTriggerCharacter)||!1,ignoreQueryLength:(t==null?void 0:t.ignoreQueryLength)||!1})}))}getForceSelectionVisible(){return this.showSelectionPlugin.getEnabled()}setForceSelectionVisible(e){this.showSelectionPlugin.setEnabled(e)}pasteHTML(e,t=!1){var s;let r=e;if(!t){const i=this.tryParseHTMLToBlocks(e);r=this.blocksToFullHTML(i)}r&&((s=this.prosemirrorView)==null||s.pasteHTML(r))}pasteText(e){var t;return(t=this.prosemirrorView)==null?void 0:t.pasteText(e)}pasteMarkdown(e){const t=ae(e);return this.pasteHTML(t)}}class jn{constructor(o,e,t){this.mappings=e,this.options=t}async resolveFile(o){var t;if(!((t=this.options)!=null&&t.resolveFileUrl))return(await fetch(o)).blob();const e=await this.options.resolveFileUrl(o);return e instanceof Blob?e:(await fetch(e)).blob()}mapStyles(o){return Object.entries(o).map(([t,r])=>this.mappings.styleMapping[t](r,this))}mapInlineContent(o){return this.mappings.inlineContentMapping[o.type](o,this)}transformInlineContent(o){return o.map(e=>this.mapInlineContent(e))}async mapBlock(o,e,t,r){return this.mappings.blockMapping[o.type](o,this,e,t,r)}}function Wn(n){return{createBlockMapping:o=>o,createInlineContentMapping:o=>o,createStyleMapping:o=>o}}let W;async function Yn(){return W||(W=(async()=>{const[n,o]=await Promise.all([import("emoji-mart"),import("@emoji-mart/data")]),e="default"in n?n.default:n,t="default"in o?o.default:o;return await e.init({data:t}),{emojiMart:e,emojiData:t}})(),W)}async function Xn(n,o){if(!("text"in n.schema.inlineContentSchema)||n.schema.inlineContentSchema.text!==a.defaultInlineContentSchema.text)return[];const{emojiData:e,emojiMart:t}=await Yn();return(o.trim()===""?Object.values(e.emojis):await t.SearchIndex.search(o)).map(s=>({id:s.skins[0].native,onItemClick:()=>n.insertInlineContent(s.skins[0].native+" ")}))}function Jn(n,...o){const e=[...n];for(const t of o)for(const r of t){const s=e.findLastIndex(i=>i.group===r.group);s===-1?e.push(r):e.splice(s+1,0,r)}return e}exports.BlockNoteExtension=a.BlockNoteExtension;exports.BlockNoteSchema=a.BlockNoteSchema;exports.COLORS_DARK_MODE_DEFAULT=a.COLORS_DARK_MODE_DEFAULT;exports.COLORS_DEFAULT=a.COLORS_DEFAULT;exports.CustomBlockNoteSchema=a.CustomBlockNoteSchema;exports.EMPTY_CELL_HEIGHT=a.EMPTY_CELL_HEIGHT;exports.EMPTY_CELL_WIDTH=a.EMPTY_CELL_WIDTH;exports.EventEmitter=a.EventEmitter;exports.FILE_AUDIO_ICON_SVG=a.FILE_AUDIO_ICON_SVG;exports.FILE_IMAGE_ICON_SVG=a.FILE_IMAGE_ICON_SVG;exports.FILE_VIDEO_ICON_SVG=a.FILE_VIDEO_ICON_SVG;exports.UniqueID=a.UniqueID;exports.UnreachableCaseError=a.UnreachableCaseError;exports.addDefaultPropsExternalHTML=a.addDefaultPropsExternalHTML;exports.addInlineContentAttributes=a.addInlineContentAttributes;exports.addInlineContentKeyboardShortcuts=a.addInlineContentKeyboardShortcuts;exports.addNodeAndExtensionsToSpec=a.addNodeAndExtensionsToSpec;exports.addStyleAttributes=a.addStyleAttributes;exports.applyNonSelectableBlockFix=a.applyNonSelectableBlockFix;exports.assertEmpty=a.assertEmpty;exports.audioParse=a.audioParse;exports.audioRender=a.audioRender;exports.audioToExternalHTML=a.audioToExternalHTML;exports.blockHasType=a.blockHasType;exports.blockToNode=a.blockToNode;exports.camelToDataKebab=a.camelToDataKebab;exports.captureCellAnchor=a.captureCellAnchor;exports.checkPageBreakBlocksInSchema=a.checkPageBreakBlocksInSchema;exports.contentNodeToInlineContent=a.contentNodeToInlineContent;exports.contentNodeToTableContent=a.contentNodeToTableContent;exports.createAudioBlockConfig=a.createAudioBlockConfig;exports.createAudioBlockSpec=a.createAudioBlockSpec;exports.createBlockConfig=a.createBlockConfig;exports.createBlockNoteExtension=a.createBlockNoteExtension;exports.createBlockSpec=a.createBlockSpec;exports.createBlockSpecFromTiptapNode=a.createBlockSpecFromTiptapNode;exports.createBulletListItemBlockConfig=a.createBulletListItemBlockConfig;exports.createBulletListItemBlockSpec=a.createBulletListItemBlockSpec;exports.createCheckListItemBlockSpec=a.createCheckListItemBlockSpec;exports.createCheckListItemConfig=a.createCheckListItemConfig;exports.createCodeBlockConfig=a.createCodeBlockConfig;exports.createCodeBlockSpec=a.createCodeBlockSpec;exports.createDefaultBlockDOMOutputSpec=a.createDefaultBlockDOMOutputSpec;exports.createFileBlockConfig=a.createFileBlockConfig;exports.createFileBlockSpec=a.createFileBlockSpec;exports.createHeadingBlockConfig=a.createHeadingBlockConfig;exports.createHeadingBlockSpec=a.createHeadingBlockSpec;exports.createImageBlockConfig=a.createImageBlockConfig;exports.createImageBlockSpec=a.createImageBlockSpec;exports.createInlineContentSpecFromTipTapNode=a.createInlineContentSpecFromTipTapNode;exports.createInternalInlineContentSpec=a.createInternalInlineContentSpec;exports.createInternalStyleSpec=a.createInternalStyleSpec;exports.createNumberedListItemBlockConfig=a.createNumberedListItemBlockConfig;exports.createNumberedListItemBlockSpec=a.createNumberedListItemBlockSpec;exports.createPageBreakBlockConfig=a.createPageBreakBlockConfig;exports.createPageBreakBlockSpec=a.createPageBreakBlockSpec;exports.createParagraphBlockConfig=a.createParagraphBlockConfig;exports.createParagraphBlockSpec=a.createParagraphBlockSpec;exports.createQuoteBlockConfig=a.createQuoteBlockConfig;exports.createQuoteBlockSpec=a.createQuoteBlockSpec;exports.createStyleSpec=a.createStyleSpec;exports.createStyleSpecFromTipTapMark=a.createStyleSpecFromTipTapMark;exports.createTableBlockSpec=a.createTableBlockSpec;exports.createToggleListItemBlockConfig=a.createToggleListItemBlockConfig;exports.createToggleListItemBlockSpec=a.createToggleListItemBlockSpec;exports.createToggleWrapper=a.createToggleWrapper;exports.createVideoBlockConfig=a.createVideoBlockConfig;exports.createVideoBlockSpec=a.createVideoBlockSpec;exports.defaultBlockSpecs=a.defaultBlockSpecs;exports.defaultBlockToHTML=a.defaultBlockToHTML;exports.defaultInlineContentSchema=a.defaultInlineContentSchema;exports.defaultInlineContentSpecs=a.defaultInlineContentSpecs;exports.defaultProps=a.defaultProps;exports.defaultStyleSchema=a.defaultStyleSchema;exports.defaultStyleSpecs=a.defaultStyleSpecs;exports.defaultToggledState=a.defaultToggledState;exports.docToBlocks=a.docToBlocks;exports.editorHasBlockWithType=a.editorHasBlockWithType;exports.fileParse=a.fileParse;exports.filenameFromURL=a.filenameFromURL;exports.filterSuggestionItems=a.filterSuggestionItems;exports.formatKeyboardShortcut=a.formatKeyboardShortcut;exports.getBackgroundColorAttribute=a.getBackgroundColorAttribute;exports.getBlockCache=a.getBlockCache;exports.getBlockFromPos=a.getBlockFromPos;exports.getBlockInfo=a.getBlockInfo;exports.getBlockInfoFromResolvedPos=a.getBlockInfoFromResolvedPos;exports.getBlockInfoFromSelection=a.getBlockInfoFromSelection;exports.getBlockInfoFromTransaction=a.getBlockInfoFromTransaction;exports.getBlockInfoWithManualOffset=a.getBlockInfoWithManualOffset;exports.getBlockNoteSchema=a.getBlockNoteSchema;exports.getBlockSchema=a.getBlockSchema;exports.getColspan=a.getColspan;exports.getDefaultSlashMenuItems=a.getDefaultSlashMenuItems;exports.getInlineContentSchema=a.getInlineContentSchema;exports.getInlineContentSchemaFromSpecs=a.getInlineContentSchemaFromSpecs;exports.getLanguageId=a.getLanguageId;exports.getNearestBlockPos=a.getNearestBlockPos;exports.getNodeById=a.getNodeById;exports.getPageBreakSlashMenuItems=a.getPageBreakSlashMenuItems;exports.getParseRules=a.getParseRules;exports.getPmSchema=a.getPmSchema;exports.getRowspan=a.getRowspan;exports.getStyleParseRules=a.getStyleParseRules;exports.getStyleSchema=a.getStyleSchema;exports.getStyleSchemaFromSpecs=a.getStyleSchemaFromSpecs;exports.getTextAlignmentAttribute=a.getTextAlignmentAttribute;exports.getTextColorAttribute=a.getTextColorAttribute;exports.imageParse=a.imageParse;exports.imageRender=a.imageRender;exports.imageToExternalHTML=a.imageToExternalHTML;exports.inlineContentToNodes=a.inlineContentToNodes;exports.insertOrUpdateBlock=a.insertOrUpdateBlock;exports.isAppleOS=a.isAppleOS;exports.isLinkInlineContent=a.isLinkInlineContent;exports.isNodeBlock=a.isNodeBlock;exports.isPartialLinkInlineContent=a.isPartialLinkInlineContent;exports.isPartialTableCell=a.isPartialTableCell;exports.isSafari=a.isSafari;exports.isStyledTextInlineContent=a.isStyledTextInlineContent;exports.isTableCell=a.isTableCell;exports.isTableCellSelection=a.isTableCellSelection;exports.mapTableCell=a.mapTableCell;exports.mergeCSSClasses=a.mergeCSSClasses;exports.mergeParagraphs=a.mergeParagraphs;exports.nodeToBlock=a.nodeToBlock;exports.nodeToCustomInlineContent=a.nodeToCustomInlineContent;exports.parseAudioElement=a.parseAudioElement;exports.parseDefaultProps=a.parseDefaultProps;exports.propsToAttributes=a.propsToAttributes;exports.prosemirrorSliceToSlicedBlocks=a.prosemirrorSliceToSlicedBlocks;exports.stylePropsToAttributes=a.stylePropsToAttributes;exports.tableContentToNodes=a.tableContentToNodes;exports.tablePropSchema=a.tablePropSchema;exports.updateBlock=a.updateBlock;exports.updateBlockCommand=a.updateBlockCommand;exports.updateBlockTr=a.updateBlockTr;exports.uploadToTmpFilesDotOrg_DEV_ONLY=a.uploadToTmpFilesDotOrg_DEV_ONLY;exports.videoParse=a.videoParse;exports.withPageBreak=a.withPageBreak;exports.wrapInBlockStructure=a.wrapInBlockStructure;exports.BlockNoteEditor=ue;exports.DEFAULT_LINK_PROTOCOL=lt;exports.Exporter=jn;exports.FilePanelProsemirrorPlugin=tt;exports.FilePanelView=et;exports.FormattingToolbarProsemirrorPlugin=rt;exports.FormattingToolbarView=ot;exports.HTMLToBlocks=ie;exports.LinkToolbarProsemirrorPlugin=at;exports.SideMenuProsemirrorPlugin=mt;exports.SideMenuView=ht;exports.SuggestionMenuProseMirrorPlugin=gt;exports.TableHandlesProsemirrorPlugin=bt;exports.TableHandlesView=kt;exports.VALID_LINK_PROTOCOLS=ct;exports.blocksToMarkdown=We;exports.cleanHTMLToMarkdown=J;exports.combineByGroup=Jn;exports.createExternalHTMLExporter=K;exports.createInlineContentSpec=eo;exports.createInternalHTMLSerializer=Re;exports.createSuggestionMenu=En;exports.formattingToolbarPluginKey=nt;exports.getBlock=ze;exports.getBlockNoteExtensions=yt;exports.getBlocksChangedByTransaction=se;exports.getDefaultEmojiPickerItems=Xn;exports.getInlineContentParseRules=Me;exports.getNextBlock=qe;exports.getParentBlock=Ge;exports.getPrevBlock=Ke;exports.insertBlocks=De;exports.linkToolbarPluginKey=it;exports.mappingFactory=Wn;exports.markdownToBlocks=Ye;exports.markdownToHTML=ae;exports.removeAndInsertBlocks=ee;exports.selectedFragmentToHTML=le;exports.sideMenuPluginKey=pt;exports.tableHandlesPluginKey=_;exports.trackPosition=ft;
4
+ `}}),ye=(n,o)=>{const e=n.resolve(o);if(e.depth<=1)return;const t=e.posAtIndex(e.index(e.depth-1),e.depth-1);return a.getBlockInfoFromResolvedPos(n.resolve(t))},Y=(n,o)=>{const e=n.resolve(o),t=e.index();if(t===0)return;const r=e.posAtIndex(t-1);return a.getBlockInfoFromResolvedPos(n.resolve(r))},st=(n,o)=>{for(;o.childContainer;){const e=o.childContainer.node,t=n.resolve(o.childContainer.beforePos+1).posAtIndex(e.childCount-1);o=a.getBlockInfoFromResolvedPos(n.resolve(t))}return o},dn=(n,o)=>n.isBlockContainer&&n.blockContent.node.type.spec.content==="inline*"&&n.blockContent.node.childCount>0&&o.isBlockContainer&&o.blockContent.node.type.spec.content==="inline*",un=(n,o,e,t)=>{if(!t.isBlockContainer)throw new Error(`Attempted to merge block at position ${t.bnBlock.beforePos} into previous block at position ${e.bnBlock.beforePos}, but next block is not a block container`);if(t.childContainer){const r=n.doc.resolve(t.childContainer.beforePos+1),s=n.doc.resolve(t.childContainer.afterPos-1),i=r.blockRange(s);if(o){const l=n.doc.resolve(t.bnBlock.beforePos);n.tr.lift(i,l.depth)}}if(o){if(!e.isBlockContainer)throw new Error(`Attempted to merge block at position ${t.bnBlock.beforePos} into previous block at position ${e.bnBlock.beforePos}, but previous block is not a block container`);o(n.tr.delete(e.blockContent.afterPos-1,t.blockContent.beforePos+1))}return!0},we=n=>({state:o,dispatch:e})=>{const t=o.doc.resolve(n),r=a.getBlockInfoFromResolvedPos(t),s=Y(o.doc,r.bnBlock.beforePos);if(!s)return!1;const i=st(o.doc,s);return dn(i,r)?un(o,e,i,r):!1},hn=S.Extension.create({priority:50,addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({chain:t,commands:r})=>[()=>r.deleteSelection(),()=>r.undoInputRule(),()=>r.command(({state:s})=>{const i=a.getBlockInfoFromSelection(s);if(!i.isBlockContainer)return!1;const l=s.selection.from===i.blockContent.beforePos+1,c=i.blockContent.node.type.name==="paragraph";return l&&!c?r.command(a.updateBlockCommand(i.bnBlock.beforePos,{type:"paragraph",props:{}})):!1}),()=>r.command(({state:s})=>{const i=a.getBlockInfoFromSelection(s);if(!i.isBlockContainer)return!1;const{blockContent:l}=i;return s.selection.from===l.beforePos+1?r.liftListItem("blockContainer"):!1}),()=>r.command(({state:s})=>{const i=a.getBlockInfoFromSelection(s);if(!i.isBlockContainer)return!1;const{bnBlock:l,blockContent:c}=i,d=s.selection.from===c.beforePos+1,u=s.selection.empty,p=l.beforePos;return d&&u?t().command(we(p)).scrollIntoView().run():!1}),()=>r.command(({state:s,dispatch:i})=>{const l=a.getBlockInfoFromSelection(s);if(!l.isBlockContainer||!(s.selection.from===l.blockContent.beforePos+1)||Y(s.doc,l.bnBlock.beforePos))return!1;const u=ye(s.doc,l.bnBlock.beforePos);if((u==null?void 0:u.blockNoteType)!=="column")return!1;const p=u,f=ye(s.doc,p.bnBlock.beforePos);if((f==null?void 0:f.blockNoteType)!=="columnList")throw new Error("parent of column is not a column list");const g=p.childContainer.node.childCount===1,k=g&&f.childContainer.node.childCount===2,m=f.childContainer.node.firstChild===p.bnBlock.node;if(i){const b=s.doc.slice(l.bnBlock.beforePos,l.bnBlock.afterPos,!1);if(k)if(m){s.tr.step(new z.ReplaceAroundStep(f.bnBlock.beforePos,f.bnBlock.afterPos,p.bnBlock.afterPos+1,f.bnBlock.afterPos-2,b,b.size,!1));const y=s.tr.doc.resolve(p.bnBlock.beforePos);s.tr.setSelection(w.TextSelection.between(y,y))}else{s.tr.step(new z.ReplaceAroundStep(f.bnBlock.beforePos,f.bnBlock.afterPos,f.bnBlock.beforePos+2,p.bnBlock.beforePos-1,b,0,!1));const y=s.tr.doc.resolve(s.tr.mapping.map(p.bnBlock.beforePos-1));s.tr.setSelection(w.TextSelection.between(y,y))}else if(g)if(m){s.tr.delete(p.bnBlock.beforePos,p.bnBlock.afterPos),s.tr.insert(f.bnBlock.beforePos,b.content);const y=s.tr.doc.resolve(f.bnBlock.beforePos);s.tr.setSelection(w.TextSelection.between(y,y))}else s.tr.delete(p.bnBlock.beforePos-1,p.bnBlock.beforePos+1);else{s.tr.delete(l.bnBlock.beforePos,l.bnBlock.afterPos),m?s.tr.insert(f.bnBlock.beforePos-1,b.content):s.tr.insert(p.bnBlock.beforePos-1,b.content);const y=s.tr.doc.resolve(p.bnBlock.beforePos-1);s.tr.setSelection(w.TextSelection.between(y,y))}}return!0}),()=>r.command(({state:s})=>{const i=a.getBlockInfoFromSelection(s);if(!i.isBlockContainer)return!1;if(i.blockContent.node.childCount===0&&i.blockContent.node.type.spec.content==="inline*"){const c=Y(s.doc,i.bnBlock.beforePos);if(!c||!c.isBlockContainer)return!1;let d=t();if(c.blockContent.node.type.spec.content==="tableRow+"){const k=i.bnBlock.beforePos-1-1-1-1-1;d=d.setTextSelection(k)}else if(c.blockContent.node.type.spec.content===""){const u=c.blockContent.afterPos-c.blockContent.node.nodeSize;d=d.setNodeSelection(u)}else{const u=c.blockContent.afterPos-c.blockContent.node.nodeSize;d=d.setTextSelection(u)}return d.deleteRange({from:i.bnBlock.beforePos,to:i.bnBlock.afterPos}).scrollIntoView().run()}return!1}),()=>r.command(({state:s})=>{const i=a.getBlockInfoFromSelection(s);if(!i.isBlockContainer)throw new Error("todo");const l=s.selection.from===i.blockContent.beforePos+1,c=s.selection.empty,d=Y(s.doc,i.bnBlock.beforePos);if(d&&l&&c){const u=st(s.doc,d);if(!u.isBlockContainer)throw new Error("todo");if(u.blockContent.node.type.spec.content===""||u.blockContent.node.type.spec.content==="inline*"&&u.blockContent.node.childCount===0)return t().cut({from:i.bnBlock.beforePos,to:i.bnBlock.afterPos},u.bnBlock.afterPos).deleteRange({from:u.bnBlock.beforePos,to:u.bnBlock.afterPos}).run()}return!1})]),o=()=>this.editor.commands.first(({commands:t})=>[()=>t.deleteSelection(),()=>t.command(({state:r})=>{const s=a.getBlockInfoFromSelection(r);if(!s.isBlockContainer)return!1;const{bnBlock:i,blockContent:l,childContainer:c}=s,{depth:d}=r.doc.resolve(i.beforePos),u=i.afterPos===r.doc.nodeSize-3,p=r.selection.from===l.afterPos-1,f=r.selection.empty;if(!u&&p&&f&&!(c!==void 0)){let k=d,m=i.afterPos+1,b=r.doc.resolve(m).depth;for(;b<k;)k=b,m+=2,b=r.doc.resolve(m).depth;return t.command(we(m-1))}return!1})]),e=(t=!1)=>this.editor.commands.first(({commands:r,tr:s})=>[()=>r.command(({state:i})=>{const l=a.getBlockInfoFromSelection(i);if(!l.isBlockContainer)return!1;const{bnBlock:c,blockContent:d}=l,{depth:u}=i.doc.resolve(c.beforePos),p=i.selection.$anchor.parentOffset===0,f=i.selection.anchor===i.selection.head,g=d.node.childCount===0,k=u>1;return p&&f&&g&&k?r.liftListItem("blockContainer"):!1}),()=>r.command(({state:i})=>{var d;const l=a.getBlockInfoFromSelection(i),c=((d=this.options.editor.schema.blockSchema[l.blockNoteType].meta)==null?void 0:d.hardBreakShortcut)??"shift+enter";if(c==="none")return!1;if(c==="shift+enter"&&t||c==="enter"){const u=s.storedMarks||s.selection.$head.marks().filter(p=>this.editor.extensionManager.splittableMarks.includes(p.type.name));return s.insert(s.selection.head,s.doc.type.schema.nodes.hardBreak.create()).ensureMarks(u),!0}return!1}),()=>r.command(({state:i,dispatch:l})=>{const c=a.getBlockInfoFromSelection(i);if(!c.isBlockContainer)return!1;const{bnBlock:d,blockContent:u}=c,p=i.selection.$anchor.parentOffset===0,f=i.selection.anchor===i.selection.head,g=u.node.childCount===0;if(p&&f&&g){const k=d.afterPos,m=k+2;if(l){const b=i.schema.nodes.blockContainer.createAndFill();i.tr.insert(k,b).scrollIntoView(),i.tr.setSelection(new w.TextSelection(i.doc.resolve(m)))}return!0}return!1}),()=>r.command(({state:i,chain:l})=>{const c=a.getBlockInfoFromSelection(i);if(!c.isBlockContainer)return!1;const{blockContent:d}=c,u=i.selection.$anchor.parentOffset===0;return d.node.childCount===0?!1:(l().deleteSelection().command(a.splitBlockCommand(i.selection.from,u,u)).run(),!0)})]);return{Backspace:n,Delete:o,Enter:()=>e(),"Shift-Enter":()=>e(!0),Tab:()=>{var t,r,s;return this.options.tabBehavior!=="prefer-indent"&&((t=this.options.editor.formattingToolbar)!=null&&t.shown||(r=this.options.editor.linkToolbar)!=null&&r.shown||(s=this.options.editor.filePanel)!=null&&s.shown)?!1:$e(this.options.editor)},"Shift-Tab":()=>{var t,r,s;return this.options.tabBehavior!=="prefer-indent"&&((t=this.options.editor.formattingToolbar)!=null&&t.shown||(r=this.options.editor.linkToolbar)!=null&&r.shown||(s=this.options.editor.filePanel)!=null&&s.shown)?!1:(this.editor.commands.liftListItem("blockContainer"),!0)},"Shift-Mod-ArrowUp":()=>(this.options.editor.moveBlocksUp(),!0),"Shift-Mod-ArrowDown":()=>(this.options.editor.moveBlocksDown(),!0),"Mod-z":()=>this.options.editor.undo(),"Mod-y":()=>this.options.editor.redo(),"Shift-Mod-z":()=>this.options.editor.redo()}}});class pn{constructor(o,e,t){h(this,"state");h(this,"emitUpdate");h(this,"menuUpdateTimer");h(this,"startMenuUpdateTimer");h(this,"stopMenuUpdateTimer");h(this,"mouseHoveredLinkMark");h(this,"mouseHoveredLinkMarkRange");h(this,"keyboardHoveredLinkMark");h(this,"keyboardHoveredLinkMarkRange");h(this,"linkMark");h(this,"linkMarkRange");h(this,"mouseOverHandler",o=>{if(this.mouseHoveredLinkMark=void 0,this.mouseHoveredLinkMarkRange=void 0,this.stopMenuUpdateTimer(),o.target instanceof HTMLAnchorElement&&o.target.nodeName==="A"){const e=o.target,t=this.pmView.posAtDOM(e,0)+1,r=this.pmView.state.doc.resolve(t),s=r.marks();for(const i of s)if(i.type.name===this.pmView.state.schema.mark("link").type.name){this.mouseHoveredLinkMark=i,this.mouseHoveredLinkMarkRange=S.getMarkRange(r,i.type,i.attrs)||void 0;break}}return this.startMenuUpdateTimer(),!1});h(this,"clickHandler",o=>{var t;const e=this.pmView.dom.parentElement;this.linkMark&&o&&o.target&&!(e===o.target||e.contains(o.target))&&(t=this.state)!=null&&t.show&&(this.state.show=!1,this.emitUpdate())});h(this,"scrollHandler",()=>{var o;this.linkMark!==void 0&&(o=this.state)!=null&&o.show&&(this.state.referencePos=S.posToDOMRect(this.pmView,this.linkMarkRange.from,this.linkMarkRange.to),this.emitUpdate())});h(this,"closeMenu",()=>{var o;(o=this.state)!=null&&o.show&&(this.state.show=!1,this.emitUpdate())});this.editor=o,this.pmView=e,this.emitUpdate=()=>{if(!this.state)throw new Error("Attempting to update uninitialized link toolbar");t(this.state)},this.startMenuUpdateTimer=()=>{this.menuUpdateTimer=setTimeout(()=>{this.update(this.pmView,void 0,!0)},250)},this.stopMenuUpdateTimer=()=>(this.menuUpdateTimer&&(clearTimeout(this.menuUpdateTimer),this.menuUpdateTimer=void 0),!1),this.pmView.dom.addEventListener("mouseover",this.mouseOverHandler),this.pmView.root.addEventListener("click",this.clickHandler,!0),this.pmView.root.addEventListener("scroll",this.scrollHandler,!0)}editLink(o,e){var t;this.editor.transact(r=>{const s=a.getPmSchema(r);r.insertText(e,this.linkMarkRange.from,this.linkMarkRange.to),r.addMark(this.linkMarkRange.from,this.linkMarkRange.from+e.length,s.mark("link",{href:o}))}),this.pmView.focus(),(t=this.state)!=null&&t.show&&(this.state.show=!1,this.emitUpdate())}deleteLink(){var o;this.editor.transact(e=>e.removeMark(this.linkMarkRange.from,this.linkMarkRange.to,this.linkMark.type).setMeta("preventAutolink",!0)),this.pmView.focus(),(o=this.state)!=null&&o.show&&(this.state.show=!1,this.emitUpdate())}update(o,e,t=!1){var l;const{state:r}=o;if(e&&e.selection.from===r.selection.from&&e.selection.to===r.selection.to||!this.pmView.hasFocus())return;const i=this.linkMark;if(this.linkMark=void 0,this.linkMarkRange=void 0,this.keyboardHoveredLinkMark=void 0,this.keyboardHoveredLinkMarkRange=void 0,this.pmView.state.selection.empty){const c=this.pmView.state.selection.$from.marks();for(const d of c)if(d.type.name===this.pmView.state.schema.mark("link").type.name){this.keyboardHoveredLinkMark=d,this.keyboardHoveredLinkMarkRange=S.getMarkRange(this.pmView.state.selection.$from,d.type,d.attrs)||void 0;break}}if(this.mouseHoveredLinkMark&&t&&(this.linkMark=this.mouseHoveredLinkMark,this.linkMarkRange=this.mouseHoveredLinkMarkRange),this.keyboardHoveredLinkMark&&(this.linkMark=this.keyboardHoveredLinkMark,this.linkMarkRange=this.keyboardHoveredLinkMarkRange),this.linkMark&&this.editor.isEditable){this.state={show:!0,referencePos:S.posToDOMRect(this.pmView,this.linkMarkRange.from,this.linkMarkRange.to),url:this.linkMark.attrs.href,text:this.pmView.state.doc.textBetween(this.linkMarkRange.from,this.linkMarkRange.to)},this.emitUpdate();return}if((l=this.state)!=null&&l.show&&i&&(!this.linkMark||!this.editor.isEditable)){this.state.show=!1,this.emitUpdate();return}}destroy(){this.pmView.dom.removeEventListener("mouseover",this.mouseOverHandler),this.pmView.root.removeEventListener("scroll",this.scrollHandler,!0),this.pmView.root.removeEventListener("click",this.clickHandler,!0)}}const it=new w.PluginKey("LinkToolbarPlugin");class at extends a.BlockNoteExtension{constructor(e){super();h(this,"view");h(this,"editLink",(e,t)=>{this.view.editLink(e,t)});h(this,"deleteLink",()=>{this.view.deleteLink()});h(this,"startHideTimer",()=>{this.view.startMenuUpdateTimer()});h(this,"stopHideTimer",()=>{this.view.stopMenuUpdateTimer()});h(this,"closeMenu",()=>this.view.closeMenu());this.addProsemirrorPlugin(new w.Plugin({key:it,view:t=>(this.view=new pn(e,t,r=>{this.emit("update",r)}),this.view),props:{handleKeyDown:(t,r)=>r.key==="Escape"&&this.shown?(this.view.closeMenu(),!0):!1}}))}static key(){return"linkToolbar"}onUpdate(e){return this.on("update",e)}get shown(){var e,t;return((t=(e=this.view)==null?void 0:e.state)==null?void 0:t.show)||!1}}const ct=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"],lt="https",mn=new w.PluginKey("node-selection-keyboard");class fn extends a.BlockNoteExtension{static key(){return"nodeSelectionKeyboard"}constructor(){super(),this.addProsemirrorPlugin(new w.Plugin({key:mn,props:{handleKeyDown:(o,e)=>{if("node"in o.state.selection){if(e.ctrlKey||e.metaKey)return!1;if(e.key.length===1)return e.preventDefault(),!0;if(e.key==="Enter"&&!e.shiftKey&&!e.altKey&&!e.ctrlKey&&!e.metaKey){const t=o.state.tr;return o.dispatch(t.insert(o.state.tr.selection.$to.after(),o.state.schema.nodes.paragraph.createChecked()).setSelection(new w.TextSelection(t.doc.resolve(o.state.tr.selection.$to.after()+1)))),!0}}return!1}}}))}}const gn=new w.PluginKey("blocknote-placeholder");class kn extends a.BlockNoteExtension{static key(){return"placeholder"}constructor(o,e){super(),this.addProsemirrorPlugin(new w.Plugin({key:gn,view:t=>{const r=`placeholder-selector-${Kt.v4()}`;t.dom.classList.add(r);const s=document.createElement("style"),i=o._tiptapEditor.options.injectNonce;i&&s.setAttribute("nonce",i),t.root instanceof window.ShadowRoot?t.root.append(s):t.root.head.appendChild(s);const l=s.sheet,c=(d="")=>`.${r} .bn-block-content${d} .bn-inline-content:has(> .ProseMirror-trailingBreak:only-child):before`;try{const{default:d,emptyDocument:u,...p}=e;for(const[k,m]of Object.entries(p)){const b=`[data-content-type="${k}"]`;l.insertRule(`${c(b)} { content: ${JSON.stringify(m)}; }`)}const f="[data-is-only-empty-block]",g="[data-is-empty-and-focused]";l.insertRule(`${c(f)} { content: ${JSON.stringify(u)}; }`),l.insertRule(`${c(g)} { content: ${JSON.stringify(d)}; }`)}catch(d){console.warn("Failed to insert placeholder CSS rule - this is likely due to the browser not supporting certain CSS pseudo-element selectors (:has, :only-child:, or :before)",d)}return{destroy:()=>{t.root instanceof window.ShadowRoot?t.root.removeChild(s):t.root.head.removeChild(s)}}},props:{decorations:t=>{const{doc:r,selection:s}=t;if(!o.isEditable||!s.empty||s.$from.parent.type.spec.code)return;const i=[];t.doc.content.size===6&&i.push(E.Decoration.node(2,4,{"data-is-only-empty-block":"true"}));const l=s.$anchor,c=l.parent;if(c.content.size===0){const d=l.before();i.push(E.Decoration.node(d,d+c.nodeSize,{"data-is-empty-and-focused":"true"}))}return E.DecorationSet.create(r,i)}}}))}}const Se=new w.PluginKey("previous-blocks"),bn={index:"index",level:"level",type:"type",depth:"depth","depth-change":"depth-change"};class yn extends a.BlockNoteExtension{static key(){return"previousBlockType"}constructor(){super();let o;this.addProsemirrorPlugin(new w.Plugin({key:Se,view(e){return{update:async(t,r)=>{var s;((s=this.key)==null?void 0:s.getState(t.state).updatedBlocks.size)>0&&(o=setTimeout(()=>{t.dispatch(t.state.tr.setMeta(Se,{clearUpdate:!0}))},0))},destroy:()=>{o&&clearTimeout(o)}}},state:{init(){return{prevTransactionOldBlockAttrs:{},currentTransactionOldBlockAttrs:{},updatedBlocks:new Set}},apply(e,t,r,s){if(t.currentTransactionOldBlockAttrs={},t.updatedBlocks.clear(),!e.docChanged||r.doc.eq(s.doc))return t;const i={},l=S.findChildren(r.doc,u=>u.attrs.id),c=new Map(l.map(u=>[u.node.attrs.id,u])),d=S.findChildren(s.doc,u=>u.attrs.id);for(const u of d){const p=c.get(u.node.attrs.id),f=p==null?void 0:p.node.firstChild,g=u.node.firstChild;if(p&&f&&g){const k={index:g.attrs.index,level:g.attrs.level,type:g.type.name,depth:s.doc.resolve(u.pos).depth},m={index:f.attrs.index,level:f.attrs.level,type:f.type.name,depth:r.doc.resolve(p.pos).depth};i[u.node.attrs.id]=m,t.currentTransactionOldBlockAttrs[u.node.attrs.id]=m,JSON.stringify(m)!==JSON.stringify(k)&&(m["depth-change"]=m.depth-k.depth,t.updatedBlocks.add(u.node.attrs.id))}}return t.prevTransactionOldBlockAttrs=i,t}},props:{decorations(e){const t=this.getState(e);if(t.updatedBlocks.size===0)return;const r=[];return e.doc.descendants((s,i)=>{if(!s.attrs.id||!t.updatedBlocks.has(s.attrs.id))return;const l=t.currentTransactionOldBlockAttrs[s.attrs.id],c={};for(const[u,p]of Object.entries(l))c["data-prev-"+bn[u]]=p||"none";const d=E.Decoration.node(i,i+s.nodeSize,{...c});r.push(d)}),E.DecorationSet.create(e.doc,r)}}}))}}const Ce=new w.PluginKey("blocknote-show-selection");class wn extends a.BlockNoteExtension{constructor(e){super();h(this,"enabled",!1);this.editor=e,this.addProsemirrorPlugin(new w.Plugin({key:Ce,props:{decorations:t=>{const{doc:r,selection:s}=t;if(!this.enabled)return E.DecorationSet.empty;const i=E.Decoration.inline(s.from,s.to,{"data-show-selection":"true"});return E.DecorationSet.create(r,[i])}}}))}static key(){return"showSelection"}setEnabled(e){this.enabled!==e&&(this.enabled=e,this.editor.transact(t=>t.setMeta(Ce,{})))}getEnabled(){return this.enabled}}function dt(n,o){var e,t;for(;n&&n.parentElement&&n.parentElement!==o.dom&&((e=n.getAttribute)==null?void 0:e.call(n,"data-node-type"))!=="blockContainer";)n=n.parentElement;if(((t=n.getAttribute)==null?void 0:t.call(n,"data-node-type"))==="blockContainer")return{node:n,id:n.getAttribute("data-id")}}class U extends w.Selection{constructor(e,t){super(e,t);h(this,"nodes");const r=e.node();this.nodes=[],e.doc.nodesBetween(e.pos,t.pos,(s,i,l)=>{if(l!==null&&l.eq(r))return this.nodes.push(s),!1})}static create(e,t,r=t){return new U(e.resolve(t),e.resolve(r))}content(){return new T.Slice(T.Fragment.from(this.nodes),0,0)}eq(e){if(!(e instanceof U)||this.nodes.length!==e.nodes.length||this.from!==e.from||this.to!==e.to)return!1;for(let t=0;t<this.nodes.length;t++)if(!this.nodes[t].eq(e.nodes[t]))return!1;return!0}map(e,t){const r=t.mapResult(this.from),s=t.mapResult(this.to);return s.deleted?w.Selection.near(e.resolve(r.pos)):r.deleted?w.Selection.near(e.resolve(s.pos)):new U(e.resolve(r.pos),e.resolve(s.pos))}toJSON(){return{type:"multiple-node",anchor:this.anchor,head:this.head}}}w.Selection.jsonID("multiple-node",U);let O;function Sn(n,o){let e,t;const r=o.resolve(n.from).node().type.spec.group==="blockContent",s=o.resolve(n.to).node().type.spec.group==="blockContent",i=Math.min(n.$anchor.depth,n.$head.depth);if(r&&s){const l=n.$from.start(i-1),c=n.$to.end(i-1);e=o.resolve(l-1).pos,t=o.resolve(c+1).pos}else e=n.from,t=n.to;return{from:e,to:t}}function Be(n,o,e=o){o===e&&(e+=n.state.doc.resolve(o+1).node().nodeSize);const t=n.domAtPos(o).node.cloneNode(!0),r=n.domAtPos(o).node,s=(p,f)=>Array.prototype.indexOf.call(p.children,f),i=s(r,n.domAtPos(o+1).node.parentElement),l=s(r,n.domAtPos(e-1).node.parentElement);for(let p=r.childElementCount-1;p>=0;p--)(p>l||p<i)&&t.removeChild(t.children[p]);ut(n.root),O=t;const c=O.getElementsByTagName("iframe");for(let p=0;p<c.length;p++){const f=c[p],g=f.parentElement;g&&g.removeChild(f)}const u=n.dom.className.split(" ").filter(p=>p!=="ProseMirror"&&p!=="bn-root"&&p!=="bn-editor").join(" ");O.className=O.className+" bn-drag-preview "+u,n.root instanceof ShadowRoot?n.root.appendChild(O):n.root.body.appendChild(O)}function ut(n){O!==void 0&&(n instanceof ShadowRoot?n.removeChild(O):n.body.removeChild(O),O=void 0)}function Cn(n,o,e){if(!n.dataTransfer||e.headless)return;const t=e.prosemirrorView,r=a.getNodeById(o.id,t.state.doc);if(!r)throw new Error(`Block with ID ${o.id} not found`);const s=r.posBeforeNode;if(s!=null){const i=t.state.selection,l=t.state.doc,{from:c,to:d}=Sn(i,l),u=c<=s&&s<d,p=i.$anchor.node()!==i.$head.node()||i instanceof U;u&&p?(t.dispatch(t.state.tr.setSelection(U.create(l,c,d))),Be(t,c,d)):(t.dispatch(t.state.tr.setSelection(w.NodeSelection.create(t.state.doc,s))),Be(t,s));const f=t.state.selection.content(),g=e.pmSchema,k=t.serializeForClipboard(f).dom.innerHTML,m=K(g,e),b=Je(f.content),y=m.exportBlocks(b,{}),C=J(y);n.dataTransfer.clearData(),n.dataTransfer.setData("blocknote/html",k),n.dataTransfer.setData("text/html",y),n.dataTransfer.setData("text/plain",C),n.dataTransfer.effectAllowed="move",n.dataTransfer.setDragImage(O,0,0)}}const ve=250;function re(n,o,e=!0){const t=n.root.elementsFromPoint(o.left,o.top);for(const r of t)if(n.dom.contains(r))return e&&r.closest("[data-node-type=columnList]")?re(n,{left:o.left+50,top:o.top},!1):dt(r,n)}function Bn(n,o){if(!o.dom.firstChild)return;const e=o.dom.firstChild.getBoundingClientRect(),t={left:Math.min(Math.max(e.left+10,n.x),e.right-10),top:n.y},r=re(o,t);if(!r)return;const s=r.node.getBoundingClientRect();return re(o,{left:s.right-10,top:n.y},!1)}class ht{constructor(o,e,t){h(this,"state");h(this,"emitUpdate");h(this,"mousePos");h(this,"hoveredBlock");h(this,"menuFrozen",!1);h(this,"isDragOrigin",!1);h(this,"updateState",o=>{this.state=o,this.emitUpdate(this.state)});h(this,"updateStateFromMousePos",()=>{var t,r,s,i,l;if(this.menuFrozen||!this.mousePos)return;const o=this.findClosestEditorElement({clientX:this.mousePos.x,clientY:this.mousePos.y});if((o==null?void 0:o.element)!==this.pmView.dom||o.distance>ve){(t=this.state)!=null&&t.show&&(this.state.show=!1,this.updateState(this.state));return}const e=Bn(this.mousePos,this.pmView);if(!e||!this.editor.isEditable){(r=this.state)!=null&&r.show&&(this.state.show=!1,this.updateState(this.state));return}if(!((s=this.state)!=null&&s.show&&((i=this.hoveredBlock)!=null&&i.hasAttribute("data-id"))&&((l=this.hoveredBlock)==null?void 0:l.getAttribute("data-id"))===e.id)&&(this.hoveredBlock=e.node,this.editor.isEditable)){const c=e.node.getBoundingClientRect(),d=e.node.closest("[data-node-type=column]");this.state={show:!0,referencePos:new DOMRect(d?d.firstElementChild.getBoundingClientRect().x:this.pmView.dom.firstChild.getBoundingClientRect().x,c.y,c.width,c.height),block:this.editor.getBlock(this.hoveredBlock.getAttribute("data-id"))},this.updateState(this.state)}});h(this,"onDragStart",o=>{var i;const e=(i=o.dataTransfer)==null?void 0:i.getData("blocknote/html");if(!e||this.pmView.dragging)return;const t=document.createElement("div");t.innerHTML=e;const s=T.DOMParser.fromSchema(this.pmView.state.schema).parse(t,{topNode:this.pmView.state.schema.nodes.blockGroup.create()});this.pmView.dragging={slice:new T.Slice(s.content,0,0),move:!0}});h(this,"findClosestEditorElement",o=>{const e=Array.from(this.pmView.root.querySelectorAll(".bn-editor"));if(e.length===0)return null;let t=e[0],r=Number.MAX_VALUE;return e.forEach(s=>{const i=s.querySelector(".bn-block-group").getBoundingClientRect(),l=o.clientX<i.left?i.left-o.clientX:o.clientX>i.right?o.clientX-i.right:0,c=o.clientY<i.top?i.top-o.clientY:o.clientY>i.bottom?o.clientY-i.bottom:0,d=Math.sqrt(Math.pow(l,2)+Math.pow(c,2));d<r&&(r=d,t=s)}),{element:t,distance:r}});h(this,"onDragOver",o=>{if(o.synthetic)return;const e=this.getDragEventContext(o);if(!e||!e.isDropPoint){this.closeDropCursor();return}e.isDropPoint&&!e.isDropWithinEditorBounds&&this.dispatchSyntheticEvent(o)});h(this,"closeDropCursor",()=>{const o=new Event("dragleave",{bubbles:!1});o.synthetic=!0,this.pmView.dom.dispatchEvent(o)});h(this,"getDragEventContext",o=>{var c;const e=!((c=o.dataTransfer)!=null&&c.types.includes("blocknote/html"))&&!!this.pmView.dragging,t=!!this.isDragOrigin,r=e||t,s=this.findClosestEditorElement(o);if(!s||s.distance>ve)return;const i=s.element===this.pmView.dom,l=i&&s.distance===0;if(!(!i&&!r))return{isDropPoint:i,isDropWithinEditorBounds:l,isDragOrigin:r}});h(this,"onDrop",o=>{if(o.synthetic)return;const e=this.getDragEventContext(o);if(!e){this.closeDropCursor();return}const{isDropPoint:t,isDropWithinEditorBounds:r,isDragOrigin:s}=e;if(!r&&t&&this.dispatchSyntheticEvent(o),t){if(this.pmView.dragging)return;this.pmView.dispatch(this.pmView.state.tr.setSelection(w.TextSelection.create(this.pmView.state.tr.doc,this.pmView.state.tr.selection.anchor)));return}else if(s){setTimeout(()=>this.pmView.dispatch(this.pmView.state.tr.deleteSelection()),0);return}});h(this,"onDragEnd",o=>{o.synthetic||(this.pmView.dragging=null)});h(this,"onKeyDown",o=>{var e;(e=this.state)!=null&&e.show&&this.editor.isFocused()&&(this.state.show=!1,this.emitUpdate(this.state))});h(this,"onMouseMove",o=>{var s;if(this.menuFrozen)return;this.mousePos={x:o.clientX,y:o.clientY};const e=this.pmView.dom.getBoundingClientRect(),t=this.mousePos.x>e.left&&this.mousePos.x<e.right&&this.mousePos.y>e.top&&this.mousePos.y<e.bottom,r=this.pmView.dom.parentElement;if(t&&o&&o.target&&!(r===o.target||r.contains(o.target))){(s=this.state)!=null&&s.show&&(this.state.show=!1,this.emitUpdate(this.state));return}this.updateStateFromMousePos()});h(this,"onScroll",()=>{var o;(o=this.state)!=null&&o.show&&(this.state.referencePos=this.hoveredBlock.getBoundingClientRect(),this.emitUpdate(this.state)),this.updateStateFromMousePos()});this.editor=o,this.pmView=e,this.emitUpdate=()=>{if(!this.state)throw new Error("Attempting to update uninitialized side menu");t(this.state)},this.pmView.root.addEventListener("dragstart",this.onDragStart),this.pmView.root.addEventListener("dragover",this.onDragOver),this.pmView.root.addEventListener("drop",this.onDrop,!0),this.pmView.root.addEventListener("dragend",this.onDragEnd,!0),this.pmView.root.addEventListener("mousemove",this.onMouseMove,!0),this.pmView.root.addEventListener("keydown",this.onKeyDown,!0),e.root.addEventListener("scroll",this.onScroll,!0)}dispatchSyntheticEvent(o){const e=new Event(o.type,o),t=this.pmView.dom.firstChild.getBoundingClientRect();e.clientX=o.clientX,e.clientY=o.clientY,e.clientX=Math.min(Math.max(o.clientX,t.left),t.left+t.width),e.clientY=Math.min(Math.max(o.clientY,t.top),t.top+t.height),e.dataTransfer=o.dataTransfer,e.preventDefault=()=>o.preventDefault(),e.synthetic=!0,this.pmView.dom.dispatchEvent(e)}update(o,e){var r;!e.doc.eq(this.pmView.state.doc)&&((r=this.state)!=null&&r.show)&&this.updateStateFromMousePos()}destroy(){var o;(o=this.state)!=null&&o.show&&(this.state.show=!1,this.emitUpdate(this.state)),this.pmView.root.removeEventListener("mousemove",this.onMouseMove,!0),this.pmView.root.removeEventListener("dragstart",this.onDragStart),this.pmView.root.removeEventListener("dragover",this.onDragOver),this.pmView.root.removeEventListener("drop",this.onDrop,!0),this.pmView.root.removeEventListener("dragend",this.onDragEnd,!0),this.pmView.root.removeEventListener("keydown",this.onKeyDown,!0),this.pmView.root.removeEventListener("scroll",this.onScroll,!0)}}const pt=new w.PluginKey("SideMenuPlugin");class mt extends a.BlockNoteExtension{constructor(e){super();h(this,"view");h(this,"blockDragStart",(e,t)=>{this.view&&(this.view.isDragOrigin=!0),Cn(e,t,this.editor)});h(this,"blockDragEnd",()=>{ut(this.editor.prosemirrorView.root),this.view&&(this.view.isDragOrigin=!1)});h(this,"freezeMenu",()=>{this.view.menuFrozen=!0,this.view.state.show=!0,this.view.emitUpdate(this.view.state)});h(this,"unfreezeMenu",()=>{this.view.menuFrozen=!1,this.view.state.show=!1,this.view.emitUpdate(this.view.state)});this.editor=e,this.addProsemirrorPlugin(new w.Plugin({key:pt,view:t=>(this.view=new ht(e,t,r=>{this.emit("update",r)}),this.view)}))}static key(){return"sideMenu"}onUpdate(e){return this.on("update",e)}}const G=new Map;function vn(n){if(G.has(n))return G.get(n);const o=new z.Mapping;return n._tiptapEditor.on("transaction",({transaction:e})=>{o.appendMapping(e.mapping)}),n._tiptapEditor.on("destroy",()=>{G.delete(n)}),G.set(n,o),o}function ft(n,o,e="left"){const t=P.ySyncPluginKey.getState(n.prosemirrorState);if(!t){const s=vn(n),i=s.maps.length;return()=>s.slice(i).map(o,e==="left"?-1:1)}const r=P.absolutePositionToRelativePosition(o+(e==="right"?1:-1),t.binding.type,t.binding.mapping);return()=>{const s=P.ySyncPluginKey.getState(n.prosemirrorState),i=P.relativePositionToAbsolutePosition(s.doc,s.binding.type,r,s.binding.mapping);if(i===null)throw new Error("Position not found, cannot track positions");return i+(e==="right"?-1:1)}}const Pn=S.findParentNode(n=>n.type.name==="blockContainer");class Tn{constructor(o,e,t){h(this,"state");h(this,"emitUpdate");h(this,"rootEl");h(this,"pluginState");h(this,"handleScroll",()=>{var o,e;if((o=this.state)!=null&&o.show){const t=(e=this.rootEl)==null?void 0:e.querySelector(`[data-decoration-id="${this.pluginState.decorationId}"]`);if(!t)return;this.state.referencePos=t.getBoundingClientRect(),this.emitUpdate(this.pluginState.triggerCharacter)}});h(this,"closeMenu",()=>{this.editor.transact(o=>o.setMeta($,null))});h(this,"clearQuery",()=>{this.pluginState!==void 0&&this.editor._tiptapEditor.chain().focus().deleteRange({from:this.pluginState.queryStartPos()-(this.pluginState.deleteTriggerCharacter?this.pluginState.triggerCharacter.length:0),to:this.editor.transact(o=>o.selection.from)}).run()});var r;this.editor=o,this.pluginState=void 0,this.emitUpdate=s=>{var i;if(!this.state)throw new Error("Attempting to update uninitialized suggestions menu");e(s,{...this.state,ignoreQueryLength:(i=this.pluginState)==null?void 0:i.ignoreQueryLength})},this.rootEl=t.root,(r=this.rootEl)==null||r.addEventListener("scroll",this.handleScroll,!0)}update(o,e){var d;const t=$.getState(e),r=$.getState(o.state),s=t===void 0&&r!==void 0,i=t!==void 0&&r===void 0;if(!s&&!(t!==void 0&&r!==void 0)&&!i)return;if(this.pluginState=i?t:r,i||!this.editor.isEditable){this.state&&(this.state.show=!1),this.emitUpdate(this.pluginState.triggerCharacter);return}const c=(d=this.rootEl)==null?void 0:d.querySelector(`[data-decoration-id="${this.pluginState.decorationId}"]`);this.editor.isEditable&&c&&(this.state={show:!0,referencePos:c.getBoundingClientRect(),query:this.pluginState.query},this.emitUpdate(this.pluginState.triggerCharacter))}destroy(){var o;(o=this.rootEl)==null||o.removeEventListener("scroll",this.handleScroll,!0)}}const $=new w.PluginKey("SuggestionMenuPlugin");class gt extends a.BlockNoteExtension{constructor(e){super();h(this,"view");h(this,"triggerCharacters",[]);h(this,"addTriggerCharacter",e=>{this.triggerCharacters.push(e)});h(this,"removeTriggerCharacter",e=>{this.triggerCharacters=this.triggerCharacters.filter(t=>t!==e)});h(this,"closeMenu",()=>this.view.closeMenu());h(this,"clearQuery",()=>this.view.clearQuery());const t=this.triggerCharacters;this.addProsemirrorPlugin(new w.Plugin({key:$,view:r=>(this.view=new Tn(e,(s,i)=>{this.emit(`update ${s}`,i)},r),this.view),state:{init(){},apply:(r,s,i,l)=>{if(r.selection.$from.parent.type.spec.code)return s;const c=r.getMeta($);if(typeof c=="object"&&c!==null){s&&this.closeMenu();const u=ft(e,l.selection.from-c.triggerCharacter.length);return{triggerCharacter:c.triggerCharacter,deleteTriggerCharacter:c.deleteTriggerCharacter!==!1,queryStartPos:()=>u()+c.triggerCharacter.length,query:"",decorationId:`id_${Math.floor(Math.random()*4294967295)}`,ignoreQueryLength:c==null?void 0:c.ignoreQueryLength}}if(s===void 0)return s;if(l.selection.from!==l.selection.to||c===null||r.getMeta("focus")||r.getMeta("blur")||r.getMeta("pointer")||s.triggerCharacter!==void 0&&l.selection.from<s.queryStartPos()||!l.selection.$from.sameParent(l.doc.resolve(s.queryStartPos())))return;const d={...s};return d.query=l.doc.textBetween(s.queryStartPos(),l.selection.from),d}},props:{handleTextInput(r,s,i,l){if(s===i){const c=r.state.doc;for(const d of t){const u=d.length>1?c.textBetween(s-d.length,s)+l:l;if(d===u)return r.dispatch(r.state.tr.insertText(l)),r.dispatch(r.state.tr.setMeta($,{triggerCharacter:u}).scrollIntoView()),!0}}return!1},decorations(r){const s=this.getState(r);if(s===void 0)return null;if(!s.deleteTriggerCharacter){const i=Pn(r.selection);if(i)return E.DecorationSet.create(r.doc,[E.Decoration.node(i.pos,i.pos+i.node.nodeSize,{nodeName:"span",class:"bn-suggestion-decorator","data-decoration-id":s.decorationId})])}return E.DecorationSet.create(r.doc,[E.Decoration.inline(s.queryStartPos()-s.triggerCharacter.length,s.queryStartPos(),{nodeName:"span",class:"bn-suggestion-decorator","data-decoration-id":s.decorationId})])}}}))}static key(){return"suggestionMenu"}onUpdate(e,t){return this.triggerCharacters.includes(e)||this.addTriggerCharacter(e),this.on(`update ${e}`,t)}get shown(){var e,t;return((t=(e=this.view)==null?void 0:e.state)==null?void 0:t.show)||!1}}function En(n,o){n.suggestionMenus.addTriggerCharacter(o)}const In=S.Mark.create({name:"insertion",inclusive:!1,excludes:"deletion modification insertion",addAttributes(){return{id:{default:null,validate:"number"}}},extendMarkSchema(n){return n.name!=="insertion"?{}:{blocknoteIgnore:!0,inclusive:!1,toDOM(o,e){return["ins",{"data-id":String(o.attrs.id),"data-inline":String(e),...!e&&{style:"display: contents"}},0]},parseDOM:[{tag:"ins",getAttrs(o){return o.dataset.id?{id:parseInt(o.dataset.id,10)}:!1}}]}}}),xn=S.Mark.create({name:"deletion",inclusive:!1,excludes:"insertion modification deletion",addAttributes(){return{id:{default:null,validate:"number"}}},extendMarkSchema(n){return n.name!=="deletion"?{}:{blocknoteIgnore:!0,inclusive:!1,toDOM(o,e){return["del",{"data-id":String(o.attrs.id),"data-inline":String(e),...!e&&{style:"display: contents"}},0]},parseDOM:[{tag:"del",getAttrs(o){return o.dataset.id?{id:parseInt(o.dataset.id,10)}:!1}}]}}}),Mn=S.Mark.create({name:"modification",inclusive:!1,excludes:"deletion insertion",addAttributes(){return{id:{default:null,validate:"number"},type:{validate:"string"},attrName:{default:null,validate:"string|null"},previousValue:{default:null},newValue:{default:null}}},extendMarkSchema(n){return n.name!=="modification"?{}:{blocknoteIgnore:!0,inclusive:!1,toDOM(o,e){return[e?"span":"div",{"data-type":"modification","data-id":String(o.attrs.id),"data-mod-type":o.attrs.type,"data-mod-prev-val":JSON.stringify(o.attrs.previousValue),"data-mod-new-val":JSON.stringify(o.attrs.newValue)},0]},parseDOM:[{tag:"span[data-type='modification']",getAttrs(o){return o.dataset.id?{id:parseInt(o.dataset.id,10),type:o.dataset.modType,previousValue:o.dataset.modPrevVal,newValue:o.dataset.modNewVal}:!1}},{tag:"div[data-type='modification']",getAttrs(o){return o.dataset.id?{id:parseInt(o.dataset.id,10),type:o.dataset.modType,previousValue:o.dataset.modPrevVal}:!1}}]}}});let L;function Pe(n){L||(L=document.createElement("div"),L.innerHTML="_",L.style.opacity="0",L.style.height="1px",L.style.width="1px",n instanceof Document?n.body.appendChild(L):n.appendChild(L))}function Dn(n){L&&(n instanceof Document?n.body.removeChild(L):n.removeChild(L),L=void 0)}function j(n){return Array.prototype.indexOf.call(n.parentElement.childNodes,n)}function Nn(n){let o=n;for(;o&&o.nodeName!=="TD"&&o.nodeName!=="TH"&&!o.classList.contains("tableWrapper");){if(o.classList.contains("ProseMirror"))return;const e=o.parentNode;if(!e||!(e instanceof Element))return;o=e}return o.nodeName==="TD"||o.nodeName==="TH"?{type:"cell",domNode:o,tbodyNode:o.closest("tbody")}:{type:"wrapper",domNode:o,tbodyNode:o.querySelector("tbody")}}function Ln(n,o){const e=o.querySelectorAll(n);for(let t=0;t<e.length;t++)e[t].style.visibility="hidden"}class kt{constructor(o,e,t){h(this,"state");h(this,"emitUpdate");h(this,"tableId");h(this,"tablePos");h(this,"tableElement");h(this,"menuFrozen",!1);h(this,"mouseState","up");h(this,"prevWasEditable",null);h(this,"viewMousedownHandler",()=>{this.mouseState="down"});h(this,"mouseUpHandler",o=>{this.mouseState="up",this.mouseMoveHandler(o)});h(this,"mouseMoveHandler",o=>{var d,u,p,f,g,k,m;if(this.menuFrozen||this.mouseState==="selecting"||!(o.target instanceof Element)||!this.pmView.dom.contains(o.target))return;const e=Nn(o.target);if((e==null?void 0:e.type)==="cell"&&this.mouseState==="down"&&!((d=this.state)!=null&&d.draggingState)){this.mouseState="selecting",(u=this.state)!=null&&u.show&&(this.state.show=!1,this.state.showAddOrRemoveRowsButton=!1,this.state.showAddOrRemoveColumnsButton=!1,this.emitUpdate());return}if(!e||!this.editor.isEditable){(p=this.state)!=null&&p.show&&(this.state.show=!1,this.state.showAddOrRemoveRowsButton=!1,this.state.showAddOrRemoveColumnsButton=!1,this.emitUpdate());return}if(!e.tbodyNode)return;const t=e.tbodyNode.getBoundingClientRect(),r=dt(e.domNode,this.pmView);if(!r)return;this.tableElement=r.node;let s;const i=this.editor.transact(b=>a.getNodeById(r.id,b.doc));if(!i)throw new Error(`Block with ID ${r.id} not found`);const l=a.nodeToBlock(i.node,this.editor.pmSchema,this.editor.schema.blockSchema,this.editor.schema.inlineContentSchema,this.editor.schema.styleSchema);if(a.editorHasBlockWithType(this.editor,"table")&&(this.tablePos=i.posBeforeNode+1,s=l),!s)return;this.tableId=r.id;const c=(f=e.domNode.closest(".tableWrapper"))==null?void 0:f.querySelector(".table-widgets-container");if((e==null?void 0:e.type)==="wrapper"){const b=o.clientY>=t.bottom-1&&o.clientY<t.bottom+20,y=o.clientX>=t.right-1&&o.clientX<t.right+20,C=o.clientX>t.right||o.clientY>t.bottom;this.state={...this.state,show:!0,showAddOrRemoveRowsButton:b,showAddOrRemoveColumnsButton:y,referencePosTable:t,block:s,widgetContainer:c,colIndex:C||(g=this.state)==null?void 0:g.colIndex,rowIndex:C||(k=this.state)==null?void 0:k.rowIndex,referencePosCell:C||(m=this.state)==null?void 0:m.referencePosCell}}else{const b=j(e.domNode),y=j(e.domNode.parentElement),C=e.domNode.getBoundingClientRect();if(this.state!==void 0&&this.state.show&&this.tableId===r.id&&this.state.rowIndex===y&&this.state.colIndex===b)return;this.state={show:!0,showAddOrRemoveColumnsButton:b===s.content.rows[0].cells.length-1,showAddOrRemoveRowsButton:y===s.content.rows.length-1,referencePosTable:t,block:s,draggingState:void 0,referencePosCell:C,colIndex:b,rowIndex:y,widgetContainer:c}}return this.emitUpdate(),!1});h(this,"dragOverHandler",o=>{var f;if(((f=this.state)==null?void 0:f.draggingState)===void 0)return;o.preventDefault(),o.dataTransfer.dropEffect="move",Ln(".prosemirror-dropcursor-block, .prosemirror-dropcursor-inline",this.pmView.root);const e={left:Math.min(Math.max(o.clientX,this.state.referencePosTable.left+1),this.state.referencePosTable.right-1),top:Math.min(Math.max(o.clientY,this.state.referencePosTable.top+1),this.state.referencePosTable.bottom-1)},t=this.pmView.root.elementsFromPoint(e.left,e.top).filter(g=>g.tagName==="TD"||g.tagName==="TH");if(t.length===0)return;const r=t[0];let s=!1;const i=j(r.parentElement),l=j(r),c=this.state.draggingState.draggedCellOrientation==="row"?this.state.rowIndex:this.state.colIndex,u=(this.state.draggingState.draggedCellOrientation==="row"?i:l)!==c;(this.state.rowIndex!==i||this.state.colIndex!==l)&&(this.state.rowIndex=i,this.state.colIndex=l,this.state.referencePosCell=r.getBoundingClientRect(),s=!0);const p=this.state.draggingState.draggedCellOrientation==="row"?e.top:e.left;this.state.draggingState.mousePos!==p&&(this.state.draggingState.mousePos=p,s=!0),s&&this.emitUpdate(),u&&this.editor.transact(g=>g.setMeta(_,!0))});h(this,"dropHandler",o=>{if(this.mouseState="up",this.state===void 0||this.state.draggingState===void 0)return!1;if(this.state.rowIndex===void 0||this.state.colIndex===void 0)throw new Error("Attempted to drop table row or column, but no table block was hovered prior.");o.preventDefault();const{draggingState:e,colIndex:t,rowIndex:r}=this.state,s=this.state.block.content.columnWidths;if(e.draggedCellOrientation==="row"){if(!a.canRowBeDraggedInto(this.state.block,e.originalIndex,r))return!1;const i=a.moveRow(this.state.block,e.originalIndex,r);this.editor.updateBlock(this.state.block,{type:"table",content:{...this.state.block.content,rows:i}})}else{if(!a.canColumnBeDraggedInto(this.state.block,e.originalIndex,t))return!1;const i=a.moveColumn(this.state.block,e.originalIndex,t),[l]=s.splice(e.originalIndex,1);s.splice(t,0,l),this.editor.updateBlock(this.state.block,{type:"table",content:{...this.state.block.content,columnWidths:s,rows:i}})}return this.editor.setTextCursorPosition(this.state.block.id),!0});this.editor=o,this.pmView=e,this.emitUpdate=()=>{if(!this.state)throw new Error("Attempting to update uninitialized image toolbar");t(this.state)},e.dom.addEventListener("mousemove",this.mouseMoveHandler),e.dom.addEventListener("mousedown",this.viewMousedownHandler),window.addEventListener("mouseup",this.mouseUpHandler),e.root.addEventListener("dragover",this.dragOverHandler),e.root.addEventListener("drop",this.dropHandler)}update(){var r;if(!this.state||!this.state.show)return;if(this.state.block=this.editor.getBlock(this.state.block.id),!this.state.block||this.state.block.type!=="table"||!((r=this.tableElement)!=null&&r.isConnected)){this.state.show=!1,this.state.showAddOrRemoveRowsButton=!1,this.state.showAddOrRemoveColumnsButton=!1,this.emitUpdate();return}const{height:o,width:e}=a.getDimensionsOfTable(this.state.block);this.state.rowIndex!==void 0&&this.state.colIndex!==void 0&&(this.state.rowIndex>=o&&(this.state.rowIndex=o-1),this.state.colIndex>=e&&(this.state.colIndex=e-1));const t=this.tableElement.querySelector("tbody");if(!t)throw new Error("Table block does not contain a 'tbody' HTML element. This should never happen.");if(this.state.rowIndex!==void 0&&this.state.colIndex!==void 0){const i=t.children[this.state.rowIndex].children[this.state.colIndex];i?this.state.referencePosCell=i.getBoundingClientRect():(this.state.rowIndex=void 0,this.state.colIndex=void 0)}this.state.referencePosTable=t.getBoundingClientRect(),this.emitUpdate()}destroy(){this.pmView.dom.removeEventListener("mousemove",this.mouseMoveHandler),window.removeEventListener("mouseup",this.mouseUpHandler),this.pmView.dom.removeEventListener("mousedown",this.viewMousedownHandler),this.pmView.root.removeEventListener("dragover",this.dragOverHandler),this.pmView.root.removeEventListener("drop",this.dropHandler)}}const _=new w.PluginKey("TableHandlesPlugin");class bt extends a.BlockNoteExtension{constructor(e){super();h(this,"view");h(this,"colDragStart",e=>{if(this.view.state===void 0||this.view.state.colIndex===void 0)throw new Error("Attempted to drag table column, but no table block was hovered prior.");this.view.state.draggingState={draggedCellOrientation:"col",originalIndex:this.view.state.colIndex,mousePos:e.clientX},this.view.emitUpdate(),this.editor.transact(t=>t.setMeta(_,{draggedCellOrientation:this.view.state.draggingState.draggedCellOrientation,originalIndex:this.view.state.colIndex,newIndex:this.view.state.colIndex,tablePos:this.view.tablePos})),!this.editor.headless&&(Pe(this.editor.prosemirrorView.root),e.dataTransfer.setDragImage(L,0,0),e.dataTransfer.effectAllowed="move")});h(this,"rowDragStart",e=>{if(this.view.state===void 0||this.view.state.rowIndex===void 0)throw new Error("Attempted to drag table row, but no table block was hovered prior.");this.view.state.draggingState={draggedCellOrientation:"row",originalIndex:this.view.state.rowIndex,mousePos:e.clientY},this.view.emitUpdate(),this.editor.transact(t=>t.setMeta(_,{draggedCellOrientation:this.view.state.draggingState.draggedCellOrientation,originalIndex:this.view.state.rowIndex,newIndex:this.view.state.rowIndex,tablePos:this.view.tablePos})),!this.editor.headless&&(Pe(this.editor.prosemirrorView.root),e.dataTransfer.setDragImage(L,0,0),e.dataTransfer.effectAllowed="copyMove")});h(this,"dragEnd",()=>{if(this.view.state===void 0)throw new Error("Attempted to drag table row, but no table block was hovered prior.");this.view.state.draggingState=void 0,this.view.emitUpdate(),this.editor.transact(e=>e.setMeta(_,null)),!this.editor.headless&&Dn(this.editor.prosemirrorView.root)});h(this,"freezeHandles",()=>{this.view.menuFrozen=!0});h(this,"unfreezeHandles",()=>{this.view.menuFrozen=!1});h(this,"getCellsAtRowHandle",(e,t)=>a.getCellsAtRowHandle(e,t));h(this,"getCellsAtColumnHandle",(e,t)=>a.getCellsAtColumnHandle(e,t));h(this,"setCellSelection",(e,t,r=t)=>{const s=this.view;if(!s)throw new Error("Table handles view not initialized");const i=e.doc.resolve(s.tablePos+1),l=e.doc.resolve(i.posAtIndex(t.row)+1),c=e.doc.resolve(l.posAtIndex(t.col)),d=e.doc.resolve(i.posAtIndex(r.row)+1),u=e.doc.resolve(d.posAtIndex(r.col)),p=e.tr;return p.setSelection(new N.CellSelection(c,u)),e.apply(p)});h(this,"addRowOrColumn",(e,t)=>{this.editor.exec((r,s)=>{const i=this.setCellSelection(r,t.orientation==="row"?{row:e,col:0}:{row:0,col:e});return t.orientation==="row"?t.side==="above"?N.addRowBefore(i,s):N.addRowAfter(i,s):t.side==="left"?N.addColumnBefore(i,s):N.addColumnAfter(i,s)})});h(this,"removeRowOrColumn",(e,t)=>t==="row"?this.editor.exec((r,s)=>{const i=this.setCellSelection(r,{row:e,col:0});return N.deleteRow(i,s)}):this.editor.exec((r,s)=>{const i=this.setCellSelection(r,{row:0,col:e});return N.deleteColumn(i,s)}));h(this,"mergeCells",e=>this.editor.exec((t,r)=>{const s=e?this.setCellSelection(t,e.relativeStartCell,e.relativeEndCell):t;return N.mergeCells(s,r)}));h(this,"splitCell",e=>this.editor.exec((t,r)=>{const s=e?this.setCellSelection(t,e):t;return N.splitCell(s,r)}));h(this,"getCellSelection",()=>this.editor.transact(e=>{const t=e.selection;let r=t.$from,s=t.$to;if(a.isTableCellSelection(t)){const{ranges:k}=t;k.forEach(m=>{r=m.$from.min(r??m.$from),s=m.$to.max(s??m.$to)})}else if(r=e.doc.resolve(t.$from.pos-t.$from.parentOffset-1),s=e.doc.resolve(t.$to.pos-t.$to.parentOffset-1),r.pos===0||s.pos===0)return;const i=e.doc.resolve(r.pos-r.parentOffset-1),l=e.doc.resolve(s.pos-s.parentOffset-1),c=e.doc.resolve(i.pos-i.parentOffset-1),d=r.index(i.depth),u=i.index(c.depth),p=s.index(l.depth),f=l.index(c.depth),g=[];for(let k=u;k<=f;k++)for(let m=d;m<=p;m++)g.push({row:k,col:m});return{from:{row:u,col:d},to:{row:f,col:p},cells:g}}));h(this,"getMergeDirection",e=>this.editor.transact(t=>{const r=a.isTableCellSelection(t.selection)?t.selection:void 0;if(!r||!e||r.ranges.length<=1)return;const s=this.getCellSelection();if(s)return a.areInSameColumn(s.from,s.to,e)?"vertical":"horizontal"}));h(this,"cropEmptyRowsOrColumns",(e,t)=>a.cropEmptyRowsOrColumns(e,t));h(this,"addRowsOrColumns",(e,t,r)=>a.addRowsOrColumns(e,t,r));this.editor=e,this.addProsemirrorPlugin(new w.Plugin({key:_,view:t=>(this.view=new kt(e,t,r=>{this.emit("update",r)}),this.view),props:{decorations:t=>{if(this.view===void 0||this.view.state===void 0||this.view.state.draggingState===void 0||this.view.tablePos===void 0)return;const r=this.view.state.draggingState.draggedCellOrientation==="row"?this.view.state.rowIndex:this.view.state.colIndex;if(r===void 0)return;const s=[],{block:i,draggingState:l}=this.view.state,{originalIndex:c,draggedCellOrientation:d}=l;if(r===c||!i||d==="row"&&!a.canRowBeDraggedInto(i,c,r)||d==="col"&&!a.canColumnBeDraggedInto(i,c,r))return E.DecorationSet.create(t.doc,s);const u=t.doc.resolve(this.view.tablePos+1);return this.view.state.draggingState.draggedCellOrientation==="row"?a.getCellsAtRowHandle(this.view.state.block,r).forEach(({row:f,col:g})=>{const k=t.doc.resolve(u.posAtIndex(f)+1),m=t.doc.resolve(k.posAtIndex(g)+1),b=m.node(),y=m.pos+(r>c?b.nodeSize-2:0);s.push(E.Decoration.widget(y,()=>{const C=document.createElement("div");return C.className="bn-table-drop-cursor",C.style.left="0",C.style.right="0",r>c?C.style.bottom="-2px":C.style.top="-3px",C.style.height="4px",C}))}):a.getCellsAtColumnHandle(this.view.state.block,r).forEach(({row:f,col:g})=>{const k=t.doc.resolve(u.posAtIndex(f)+1),m=t.doc.resolve(k.posAtIndex(g)+1),b=m.node(),y=m.pos+(r>c?b.nodeSize-2:0);s.push(E.Decoration.widget(y,()=>{const C=document.createElement("div");return C.className="bn-table-drop-cursor",C.style.top="0",C.style.bottom="0",r>c?C.style.right="-2px":C.style.left="-3px",C.style.width="4px",C}))}),E.DecorationSet.create(t.doc,s)}}}))}static key(){return"tableHandles"}onUpdate(e){return this.on("update",e)}}const An=S.Extension.create({name:"textAlignment",addGlobalAttributes(){return[{types:["tableCell","tableHeader"],attributes:{textAlignment:{default:"left",parseHTML:n=>n.getAttribute("data-text-alignment"),renderHTML:n=>n.textAlignment==="left"?{}:{"data-text-alignment":n.textAlignment}}}}]}}),On=S.Extension.create({name:"blockTextColor",addGlobalAttributes(){return[{types:["table","tableCell","tableHeader"],attributes:{textColor:a.getTextColorAttribute()}}]}}),Hn=S.Extension.create({name:"trailingNode",addProseMirrorPlugins(){const n=new w.PluginKey(this.name);return[new w.Plugin({key:n,appendTransaction:(o,e,t)=>{const{doc:r,tr:s,schema:i}=t,l=n.getState(t),c=r.content.size-2,d=i.nodes.blockContainer,u=i.nodes.paragraph;if(l)return s.insert(c,d.create(void 0,u.create()))},state:{init:(o,e)=>{},apply:(o,e)=>{if(!o.docChanged)return e;let t=o.doc.lastChild;if(!t||t.type.name!=="blockGroup")throw new Error("Expected blockGroup");if(t=t.lastChild,!t||t.type.name!=="blockContainer")return!0;const r=t.firstChild;if(!r)throw new Error("Expected blockContent");return t.nodeSize>4||r.type.spec.content!=="inline*"}}})]}}),Rn={blockColor:"data-block-color",blockStyle:"data-block-style",id:"data-id",depth:"data-depth",depthChange:"data-depth-change"},Un=S.Node.create({name:"blockContainer",group:"blockGroupChild bnBlock",content:"blockContent blockGroup?",priority:50,defining:!0,marks:"insertion modification deletion",parseHTML(){return[{tag:"div[data-node-type="+this.name+"]",getAttrs:n=>{if(typeof n=="string")return!1;const o={};for(const[e,t]of Object.entries(Rn))n.getAttribute(t)&&(o[e]=n.getAttribute(t));return o}},{tag:'div[data-node-type="blockOuter"]',skip:!0}]},renderHTML({HTMLAttributes:n}){var r;const o=document.createElement("div");o.className="bn-block-outer",o.setAttribute("data-node-type","blockOuter");for(const[s,i]of Object.entries(n))s!=="class"&&o.setAttribute(s,i);const e={...((r=this.options.domAttributes)==null?void 0:r.block)||{},...n},t=document.createElement("div");t.className=a.mergeCSSClasses("bn-block",e.class),t.setAttribute("data-node-type",this.name);for(const[s,i]of Object.entries(e))s!=="class"&&t.setAttribute(s,i);return o.appendChild(t),{dom:o,contentDOM:t}}}),Fn=S.Node.create({name:"blockGroup",group:"childContainer",content:"blockGroupChild+",marks:"deletion insertion modification",parseHTML(){return[{tag:"div",getAttrs:n=>typeof n=="string"?!1:n.getAttribute("data-node-type")==="blockGroup"?null:!1}]},renderHTML({HTMLAttributes:n}){var t;const o={...((t=this.options.domAttributes)==null?void 0:t.blockGroup)||{},...n},e=document.createElement("div");e.className=a.mergeCSSClasses("bn-block-group",o.class),e.setAttribute("data-node-type","blockGroup");for(const[r,s]of Object.entries(o))r!=="class"&&e.setAttribute(r,s);return{dom:e,contentDOM:e}}}),_n=S.Node.create({name:"doc",topNode:!0,content:"blockGroup",marks:"insertion modification deletion"}),yt=n=>{var r;const o={},e=Vn(n);for(const s of e)o[s.name]=s;n.collaboration&&(o.ySyncPlugin=new oe(n.collaboration.fragment),o.yUndoPlugin=new ne({editor:n.editor}),(r=n.collaboration.provider)!=null&&r.awareness&&(o.yCursorPlugin=new X(n.collaboration)),o.forkYDocPlugin=new tn({editor:n.editor,collaboration:n.collaboration}),o.schemaMigrationPlugin=new de(n.collaboration.fragment)),o.formattingToolbar=new rt(n.editor),o.linkToolbar=new at(n.editor),o.sideMenu=new mt(n.editor),o.suggestionMenus=new gt(n.editor),o.filePanel=new tt(n.editor),o.placeholder=new kn(n.editor,n.placeholders),(n.animations??!0)&&(o.animations=new yn),n.tableHandles&&(o.tableHandles=new bt(n.editor)),o.nodeSelectionKeyboard=new fn,o.blockChange=new en,o.showSelection=new wn(n.editor),n.comments&&(o.comments=new cn(n.editor,n.comments.threadStore,Ze.name,n.comments.schema));const t=n.disableExtensions||[];for(const s of t)delete o[s];return o};let Te=!1;const Vn=n=>{const o=[S.extensions.ClipboardTextSerializer,S.extensions.Commands,S.extensions.Editable,S.extensions.FocusEvents,S.extensions.Tabindex,Ft.Gapcursor,S.Extension.create({name:"dropCursor",addProseMirrorPlugins:()=>[n.dropCursor({width:5,color:"#ddeeff",editor:n.editor})]}),a.UniqueID.configure({types:["blockContainer","columnList","column"],setIdAttribute:n.setIdAttribute}),ln,$t.Text,In,xn,Mn,Vt.Link.extend({inclusive:!1}).configure({defaultProtocol:lt,protocols:Te?[]:ct}),...Object.values(n.styleSpecs).map(e=>e.implementation.mark.configure({editor:n.editor})),On,Zo,An,S.Extension.create({name:"OverrideEscape",addKeyboardShortcuts(){return{Escape:()=>n.editor.suggestionMenus.shown?!1:this.editor.commands.blur()}}}),_n,Un.configure({editor:n.editor,domAttributes:n.domAttributes}),hn.configure({editor:n.editor,tabBehavior:n.tabBehavior}),Fn.configure({domAttributes:n.domAttributes}),...Object.values(n.inlineContentSpecs).filter(e=>e.config!=="link"&&e.config!=="text").map(e=>e.implementation.node.configure({editor:n.editor})),...Object.values(n.blockSpecs).flatMap(e=>[..."node"in e.implementation?[e.implementation.node.configure({editor:n.editor,domAttributes:n.domAttributes})]:[]]),Qo(n.editor),Xo(n.editor,n.pasteHandler||(e=>e.defaultPasteHandler())),Lo(n.editor),...n.trailingBlock===void 0||n.trailingBlock?[Hn]:[],...n.comments?[Ze]:[]];return Te=!0,n.collaboration||o.push(_t.History),o};function $n(n,o){const e=[];return n.forEach((t,r,s)=>{s!==o&&e.push(t)}),T.Fragment.from(e)}function zn(n,o){const e=[];for(let t=0;t<n.childCount;t++)if(n.child(t).type.name==="tableRow")if(e.length>0&&e[e.length-1].type.name==="table"){const r=e[e.length-1],s=r.copy(r.content.addToEnd(n.child(t)));e[e.length-1]=s}else{const r=o.nodes.table.createChecked(void 0,n.child(t));e.push(r)}else e.push(n.child(t));return n=T.Fragment.from(e),n}function Kn(n,o){let e=T.Fragment.from(n.content);if(e=zn(e,o.state.schema),!qn(e,o))return new T.Slice(e,n.openStart,n.openEnd);for(let t=0;t<e.childCount;t++)if(e.child(t).type.spec.group==="blockContent"){const r=[e.child(t)];if(t+1<e.childCount&&e.child(t+1).type.name==="blockGroup"){const i=e.child(t+1).child(0).child(0);(i.type.name==="bulletListItem"||i.type.name==="numberedListItem"||i.type.name==="checkListItem")&&(r.push(e.child(t+1)),e=$n(e,t+1))}const s=o.state.schema.nodes.blockContainer.createChecked(void 0,r);e=e.replaceChild(t,s)}return new T.Slice(e,n.openStart,n.openEnd)}function qn(n,o){var s,i;const e=n.childCount===1,t=((s=n.firstChild)==null?void 0:s.type.spec.content)==="inline*",r=((i=n.firstChild)==null?void 0:i.type.spec.content)==="tableRow+";if(e){if(t)return!1;if(r){const l=a.getBlockInfoFromSelection(o.state);if(l.isBlockContainer)return!(l.blockContent.node.type.spec.content==="tableRow+")}}return!0}const Gn={enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!1};class ue extends a.EventEmitter{constructor(e){var d,u,p,f,g,k,m,b,y,C,A;super();h(this,"pmSchema");h(this,"extensions",{});h(this,"_tiptapEditor");h(this,"elementRenderer",null);h(this,"blockCache",new WeakMap);h(this,"dictionary");h(this,"schema");h(this,"blockImplementations");h(this,"inlineContentImplementations");h(this,"styleImplementations");h(this,"formattingToolbar");h(this,"linkToolbar");h(this,"sideMenu");h(this,"suggestionMenus");h(this,"filePanel");h(this,"tableHandles");h(this,"comments");h(this,"showSelectionPlugin");h(this,"forkYDocPlugin");h(this,"uploadFile");h(this,"onUploadStartCallbacks",[]);h(this,"onUploadEndCallbacks",[]);h(this,"resolveFileUrl");h(this,"resolveUsers");h(this,"settings");h(this,"activeTransaction",null);h(this,"mount",e=>{this._tiptapEditor.mount({mount:e})});h(this,"unmount",()=>{this._tiptapEditor.unmount()});this.options=e;const t=e;if(t.onEditorContentChange)throw new Error("onEditorContentChange initialization option is deprecated, use <BlockNoteView onChange={...} />, the useEditorChange(...) hook, or editor.onChange(...)");if(t.onTextCursorPositionChange)throw new Error("onTextCursorPositionChange initialization option is deprecated, use <BlockNoteView onSelectionChange={...} />, the useEditorSelectionChange(...) hook, or editor.onSelectionChange(...)");if(t.onEditorReady)throw new Error("onEditorReady is deprecated. Editor is immediately ready for use after creation.");if(t.editable)throw new Error("editable initialization option is deprecated, use <BlockNoteView editable={true/false} />, or alternatively editor.isEditable = true/false");this.dictionary=e.dictionary||qt.en,this.settings={tables:{splitCells:((d=e==null?void 0:e.tables)==null?void 0:d.splitCells)??!1,cellBackgroundColor:((u=e==null?void 0:e.tables)==null?void 0:u.cellBackgroundColor)??!1,cellTextColor:((p=e==null?void 0:e.tables)==null?void 0:p.cellTextColor)??!1,headers:((f=e==null?void 0:e.tables)==null?void 0:f.headers)??!1}};const r={defaultStyles:!0,schema:e.schema||a.BlockNoteSchema.create(),...e,placeholders:{...this.dictionary.placeholders,...e.placeholders}};if(r.comments&&!r.resolveUsers)throw new Error("resolveUsers is required when using comments");this.resolveUsers=r.resolveUsers,this.schema=r.schema,this.blockImplementations=r.schema.blockSpecs,this.inlineContentImplementations=r.schema.inlineContentSpecs,this.styleImplementations=r.schema.styleSpecs,this.extensions=yt({editor:this,domAttributes:r.domAttributes||{},blockSpecs:this.schema.blockSpecs,styleSpecs:this.schema.styleSpecs,inlineContentSpecs:this.schema.inlineContentSpecs,collaboration:r.collaboration,trailingBlock:r.trailingBlock,disableExtensions:r.disableExtensions,setIdAttribute:r.setIdAttribute,animations:r.animations??!0,tableHandles:a.editorHasBlockWithType(this,"table"),dropCursor:this.options.dropCursor??Dt.dropCursor,placeholders:r.placeholders,tabBehavior:r.tabBehavior,comments:r.comments,pasteHandler:r.pasteHandler}),(((g=r._tiptapOptions)==null?void 0:g.extensions)||[]).forEach(B=>{this.extensions[B.name]=B});for(let B of r.extensions||[]){typeof B=="function"&&(B=B(this));const v=B.key??B.constructor.key();if(!v)throw new Error(`Extension ${B.constructor.name} does not have a key method`);if(this.extensions[v])throw new Error(`Extension ${B.constructor.name} already exists with key ${v}`);this.extensions[v]=B}if(Object.entries(r._extensions||{}).forEach(([B,v])=>{const I=typeof v=="function"?v(this):v;if(!("plugin"in I)){this.extensions[B]=I;return}this.extensions[B]=new class extends a.BlockNoteExtension{static key(){return B}constructor(){super(),this.addProsemirrorPlugin(I.plugin)}get priority(){return I.priority}}}),this.formattingToolbar=this.extensions.formattingToolbar,this.linkToolbar=this.extensions.linkToolbar,this.sideMenu=this.extensions.sideMenu,this.suggestionMenus=this.extensions.suggestionMenus,this.filePanel=this.extensions.filePanel,this.tableHandles=this.extensions.tableHandles,this.comments=this.extensions.comments,this.showSelectionPlugin=this.extensions.showSelection,this.forkYDocPlugin=this.extensions.forkYDocPlugin,r.uploadFile){const B=r.uploadFile;this.uploadFile=async(v,D)=>{this.onUploadStartCallbacks.forEach(I=>I.apply(this,[D]));try{return await B(v,D)}finally{this.onUploadEndCallbacks.forEach(I=>I.apply(this,[D]))}}}this.resolveFileUrl=r.resolveFileUrl;const s="ySyncPlugin"in this.extensions||"liveblocksExtension"in this.extensions;s&&r.initialContent&&console.warn("When using Collaboration, initialContent might cause conflicts, because changes should come from the collaboration provider");const i=Object.fromEntries(Object.values(this.schema.blockSpecs).map(B=>B.extensions).filter(B=>B!==void 0).flat().map(B=>[B.key??B.constructor.key(),B])),l=[...Object.entries({...this.extensions,...i}).map(([B,v])=>{if(v instanceof S.Extension||v instanceof S.Node||v instanceof S.Mark)return v;if(v instanceof a.BlockNoteExtension)return!v.plugins.length&&!v.keyboardShortcuts&&!v.inputRules&&!v.tiptapExtensions?void 0:S.Extension.create({name:B,priority:v.priority,addProseMirrorPlugins:()=>v.plugins,addExtensions:()=>v.tiptapExtensions||[],addInputRules:v.inputRules?()=>v.inputRules.map(D=>new S.InputRule({find:D.find,handler:({range:I,match:F,state:x})=>{const M=D.replace({match:F,range:I,editor:this});if(M){const wt=this.getTextCursorPosition();if(this.schema.blockSchema[wt.block.type].content!=="inline")return;const St=a.getBlockInfoFromTransaction(x.tr),Ct=x.tr.deleteRange(I.from,I.to);a.updateBlockTr(Ct,St.bnBlock.beforePos,M);return}return null}})):void 0,addKeyboardShortcuts:v.keyboardShortcuts?()=>Object.fromEntries(Object.entries(v.keyboardShortcuts).map(([D,I])=>[D,()=>I({editor:this})])):void 0})})].filter(B=>B!==void 0),c={...Gn,...r._tiptapOptions,element:null,autofocus:r.autofocus??!1,extensions:l,editorProps:{...(k=r._tiptapOptions)==null?void 0:k.editorProps,attributes:{tabIndex:"0",...(b=(m=r._tiptapOptions)==null?void 0:m.editorProps)==null?void 0:b.attributes,...(y=r.domAttributes)==null?void 0:y.editor,class:a.mergeCSSClasses("bn-editor",r.defaultStyles?"bn-default-styles":"",((A=(C=r.domAttributes)==null?void 0:C.editor)==null?void 0:A.class)||"")},transformPasted:Kn}};try{const B=r.initialContent||(s?[{type:"paragraph",id:"initialBlockId"}]:[{type:"paragraph",id:a.UniqueID.options.generateID()}]);if(!Array.isArray(B)||B.length===0)throw new Error("initialContent must be a non-empty array of blocks, received: "+B);const v=S.getSchema(c.extensions),D=B.map(F=>a.blockToNode(F,v,this.schema.styleSchema).toJSON()),I=S.createDocument({type:"doc",content:[{type:"blockGroup",content:D}]},v,c.parseOptions);this._tiptapEditor=new S.Editor({...c,content:I.toJSON()}),this.pmSchema=this._tiptapEditor.schema}catch(B){throw new Error("Error creating document from blocks passed as `initialContent`",{cause:B})}this.pmSchema.cached.blockNoteEditor=this,this.emit("create")}static create(e){return new ue(e??{})}exec(e){if(this.activeTransaction)throw new Error("`exec` should not be called within a `transact` call, move the `exec` call outside of the `transact` call");const t=this._tiptapEditor.state,r=this._tiptapEditor.view;return e(t,i=>r.dispatch(i),r)}canExec(e){if(this.activeTransaction)throw new Error("`canExec` should not be called within a `transact` call, move the `canExec` call outside of the `transact` call");const t=this._tiptapEditor.state,r=this._tiptapEditor.view;return e(t,void 0,r)}transact(e){if(this.activeTransaction)return e(this.activeTransaction);try{this.activeTransaction=this._tiptapEditor.state.tr;const t=e(this.activeTransaction),r=this.activeTransaction;return this.activeTransaction=null,r&&(r.docChanged||r.selectionSet||r.scrolledIntoView||r.storedMarksSet||!r.isGeneric)&&this._tiptapEditor.view.dispatch(r),t}finally{this.activeTransaction=null}}extension(e,t=e.key()){const r=this.extensions[t];if(!r)throw new Error(`Extension ${t} not found`);return r}get prosemirrorState(){if(this.activeTransaction)throw new Error("`prosemirrorState` should not be called within a `transact` call, move the `prosemirrorState` call outside of the `transact` call or use `editor.transact` to read the current editor state");return this._tiptapEditor.state}get prosemirrorView(){return this._tiptapEditor.view}get domElement(){var e;return(e=this.prosemirrorView)==null?void 0:e.dom}isFocused(){var e;return((e=this.prosemirrorView)==null?void 0:e.hasFocus())||!1}get headless(){return!this._tiptapEditor.isInitialized}focus(){this.headless||this.prosemirrorView.focus()}onUploadStart(e){return this.onUploadStartCallbacks.push(e),()=>{const t=this.onUploadStartCallbacks.indexOf(e);t>-1&&this.onUploadStartCallbacks.splice(t,1)}}onUploadEnd(e){return this.onUploadEndCallbacks.push(e),()=>{const t=this.onUploadEndCallbacks.indexOf(e);t>-1&&this.onUploadEndCallbacks.splice(t,1)}}get topLevelBlocks(){return this.document}get document(){return this.transact(e=>a.docToBlocks(e.doc,this.pmSchema))}getBlock(e){return this.transact(t=>ze(t.doc,e))}getPrevBlock(e){return this.transact(t=>Ke(t.doc,e))}getNextBlock(e){return this.transact(t=>qe(t.doc,e))}getParentBlock(e){return this.transact(t=>Ge(t.doc,e))}forEachBlock(e,t=!1){const r=this.document.slice();t&&r.reverse();function s(i){for(const l of i){if(e(l)===!1)return!1;const c=t?l.children.slice().reverse():l.children;if(!s(c))return!1}return!0}s(r)}onEditorContentChange(e){this._tiptapEditor.on("update",e)}onEditorSelectionChange(e){this._tiptapEditor.on("selectionUpdate",e)}getTextCursorPosition(){return this.transact(e=>So(e))}setTextCursorPosition(e,t="start"){return this.transact(r=>je(r,e,t))}getSelection(){return this.transact(e=>bo(e))}getSelectionCutBlocks(){return this.transact(e=>wo(e))}setSelection(e,t){return this.transact(r=>yo(r,e,t))}get isEditable(){return this._tiptapEditor.isEditable===void 0?!0:this._tiptapEditor.isEditable}set isEditable(e){this._tiptapEditor.options.editable!==e&&this._tiptapEditor.setEditable(e)}insertBlocks(e,t,r="before"){return this.transact(s=>De(s,e,t,r))}updateBlock(e,t){return this.transact(r=>a.updateBlock(r,e,t))}removeBlocks(e){return this.transact(t=>ee(t,e,[]).removedBlocks)}replaceBlocks(e,t){return this.transact(r=>ee(r,e,t))}undo(){return this.options.collaboration?this.exec(P.undoCommand):this.exec(pe.undo)}redo(){return this.options.collaboration?this.exec(P.redoCommand):this.exec(pe.redo)}insertInlineContent(e,{updateSelection:t=!1}={}){const r=a.inlineContentToNodes(e,this.pmSchema);this.transact(s=>{ko(s,{from:s.selection.from,to:s.selection.to},r,{updateSelection:t})})}getActiveStyles(){return this.transact(e=>{const t={},r=e.selection.$to.marks();for(const s of r){const i=this.schema.styleSchema[s.type.name];if(!i){s.type.name!=="link"&&!s.type.spec.blocknoteIgnore&&console.warn("mark not found in styleschema",s.type.name);continue}i.propSchema==="boolean"?t[i.type]=!0:t[i.type]=s.attrs.stringValue}return t})}addStyles(e){for(const[t,r]of Object.entries(e)){const s=this.schema.styleSchema[t];if(!s)throw new Error(`style ${t} not found in styleSchema`);if(s.propSchema==="boolean")this._tiptapEditor.commands.setMark(t);else if(s.propSchema==="string")this._tiptapEditor.commands.setMark(t,{stringValue:r});else throw new a.UnreachableCaseError(s.propSchema)}}removeStyles(e){for(const t of Object.keys(e))this._tiptapEditor.commands.unsetMark(t)}toggleStyles(e){for(const[t,r]of Object.entries(e)){const s=this.schema.styleSchema[t];if(!s)throw new Error(`style ${t} not found in styleSchema`);if(s.propSchema==="boolean")this._tiptapEditor.commands.toggleMark(t);else if(s.propSchema==="string")this._tiptapEditor.commands.toggleMark(t,{stringValue:r});else throw new a.UnreachableCaseError(s.propSchema)}}getSelectedText(){return this.transact(e=>e.doc.textBetween(e.selection.from,e.selection.to))}getSelectedLinkUrl(){return this._tiptapEditor.getAttributes("link").href}createLink(e,t){if(e==="")return;const r=this.pmSchema.mark("link",{href:e});this.transact(s=>{const{from:i,to:l}=s.selection;t?s.insertText(t,i,l).addMark(i,i+t.length,r):s.setSelection(w.TextSelection.create(s.doc,l)).addMark(i,l,r)})}canNestBlock(){return fo(this)}nestBlock(){$e(this)}canUnnestBlock(){return go(this)}unnestBlock(){mo(this)}moveBlocksUp(){return uo(this)}moveBlocksDown(){return ho(this)}blocksToHTMLLossy(e=this.document){return K(this.pmSchema,this).exportBlocks(e,{})}blocksToFullHTML(e){return Re(this.pmSchema,this).serializeBlocks(e,{})}tryParseHTMLToBlocks(e){return ie(e,this.pmSchema)}blocksToMarkdownLossy(e=this.document){return We(e,this.pmSchema,this,{})}async tryParseMarkdownToBlocks(e){return Ye(e,this.pmSchema)}updateCollaborationUserInfo(e){if(!this.options.collaboration)throw new Error("Cannot update collaboration user info when collaboration is disabled.");this.extensions.yCursorPlugin.updateUser(e)}onBeforeChange(e){return this.extensions.blockChange.subscribe(t=>e(this,t))}onChange(e){const t=({transaction:r,appendedTransactions:s})=>{e(this,{getChanges:()=>se(r,s)})};return this._tiptapEditor.on("update",t),()=>{this._tiptapEditor.off("update",t)}}onSelectionChange(e,t){const r=s=>{s.transaction.getMeta(P.ySyncPluginKey)&&!t||e(this)};return this._tiptapEditor.on("selectionUpdate",r),()=>{this._tiptapEditor.off("selectionUpdate",r)}}onCreate(e){return this.on("create",e),()=>{this.off("create",e)}}getSelectionBoundingBox(){if(!this.prosemirrorView)return;const{selection:e}=this.prosemirrorState,{ranges:t}=e,r=Math.min(...t.map(i=>i.$from.pos)),s=Math.max(...t.map(i=>i.$to.pos));if(S.isNodeSelection(e)){const i=this.prosemirrorView.nodeDOM(r);if(i)return i.getBoundingClientRect()}return S.posToDOMRect(this.prosemirrorView,r,s)}get isEmpty(){const e=this.document;return e.length===0||e.length===1&&e[0].type==="paragraph"&&e[0].content.length===0}openSuggestionMenu(e,t){this.prosemirrorView&&(this.focus(),this.transact(r=>{t!=null&&t.deleteTriggerCharacter&&r.insertText(e),r.scrollIntoView().setMeta(this.suggestionMenus.plugins[0],{triggerCharacter:e,deleteTriggerCharacter:(t==null?void 0:t.deleteTriggerCharacter)||!1,ignoreQueryLength:(t==null?void 0:t.ignoreQueryLength)||!1})}))}getForceSelectionVisible(){return this.showSelectionPlugin.getEnabled()}setForceSelectionVisible(e){this.showSelectionPlugin.setEnabled(e)}pasteHTML(e,t=!1){var s;let r=e;if(!t){const i=this.tryParseHTMLToBlocks(e);r=this.blocksToFullHTML(i)}r&&((s=this.prosemirrorView)==null||s.pasteHTML(r))}pasteText(e){var t;return(t=this.prosemirrorView)==null?void 0:t.pasteText(e)}pasteMarkdown(e){const t=ae(e);return this.pasteHTML(t)}}class jn{constructor(o,e,t){this.mappings=e,this.options=t}async resolveFile(o){var t;if(!((t=this.options)!=null&&t.resolveFileUrl))return(await fetch(o)).blob();const e=await this.options.resolveFileUrl(o);return e instanceof Blob?e:(await fetch(e)).blob()}mapStyles(o){return Object.entries(o).map(([t,r])=>this.mappings.styleMapping[t](r,this))}mapInlineContent(o){return this.mappings.inlineContentMapping[o.type](o,this)}transformInlineContent(o){return o.map(e=>this.mapInlineContent(e))}async mapBlock(o,e,t,r){return this.mappings.blockMapping[o.type](o,this,e,t,r)}}function Wn(n){return{createBlockMapping:o=>o,createInlineContentMapping:o=>o,createStyleMapping:o=>o}}let W;async function Yn(){return W||(W=(async()=>{const[n,o]=await Promise.all([import("emoji-mart"),import("@emoji-mart/data")]),e="default"in n?n.default:n,t="default"in o?o.default:o;return await e.init({data:t}),{emojiMart:e,emojiData:t}})(),W)}async function Xn(n,o){if(!("text"in n.schema.inlineContentSchema)||n.schema.inlineContentSchema.text!==a.defaultInlineContentSchema.text)return[];const{emojiData:e,emojiMart:t}=await Yn();return(o.trim()===""?Object.values(e.emojis):await t.SearchIndex.search(o)).map(s=>({id:s.skins[0].native,onItemClick:()=>n.insertInlineContent(s.skins[0].native+" ")}))}function Jn(n,...o){const e=[...n];for(const t of o)for(const r of t){const s=e.findLastIndex(i=>i.group===r.group);s===-1?e.push(r):e.splice(s+1,0,r)}return e}exports.BlockNoteExtension=a.BlockNoteExtension;exports.BlockNoteSchema=a.BlockNoteSchema;exports.COLORS_DARK_MODE_DEFAULT=a.COLORS_DARK_MODE_DEFAULT;exports.COLORS_DEFAULT=a.COLORS_DEFAULT;exports.CustomBlockNoteSchema=a.CustomBlockNoteSchema;exports.EMPTY_CELL_HEIGHT=a.EMPTY_CELL_HEIGHT;exports.EMPTY_CELL_WIDTH=a.EMPTY_CELL_WIDTH;exports.EventEmitter=a.EventEmitter;exports.FILE_AUDIO_ICON_SVG=a.FILE_AUDIO_ICON_SVG;exports.FILE_IMAGE_ICON_SVG=a.FILE_IMAGE_ICON_SVG;exports.FILE_VIDEO_ICON_SVG=a.FILE_VIDEO_ICON_SVG;exports.UniqueID=a.UniqueID;exports.UnreachableCaseError=a.UnreachableCaseError;exports.addDefaultPropsExternalHTML=a.addDefaultPropsExternalHTML;exports.addInlineContentAttributes=a.addInlineContentAttributes;exports.addInlineContentKeyboardShortcuts=a.addInlineContentKeyboardShortcuts;exports.addNodeAndExtensionsToSpec=a.addNodeAndExtensionsToSpec;exports.addStyleAttributes=a.addStyleAttributes;exports.applyNonSelectableBlockFix=a.applyNonSelectableBlockFix;exports.assertEmpty=a.assertEmpty;exports.audioParse=a.audioParse;exports.audioRender=a.audioRender;exports.audioToExternalHTML=a.audioToExternalHTML;exports.blockHasType=a.blockHasType;exports.blockToNode=a.blockToNode;exports.camelToDataKebab=a.camelToDataKebab;exports.captureCellAnchor=a.captureCellAnchor;exports.checkPageBreakBlocksInSchema=a.checkPageBreakBlocksInSchema;exports.contentNodeToInlineContent=a.contentNodeToInlineContent;exports.contentNodeToTableContent=a.contentNodeToTableContent;exports.createAudioBlockConfig=a.createAudioBlockConfig;exports.createAudioBlockSpec=a.createAudioBlockSpec;exports.createBlockConfig=a.createBlockConfig;exports.createBlockNoteExtension=a.createBlockNoteExtension;exports.createBlockSpec=a.createBlockSpec;exports.createBlockSpecFromTiptapNode=a.createBlockSpecFromTiptapNode;exports.createBulletListItemBlockConfig=a.createBulletListItemBlockConfig;exports.createBulletListItemBlockSpec=a.createBulletListItemBlockSpec;exports.createCheckListItemBlockSpec=a.createCheckListItemBlockSpec;exports.createCheckListItemConfig=a.createCheckListItemConfig;exports.createCodeBlockConfig=a.createCodeBlockConfig;exports.createCodeBlockSpec=a.createCodeBlockSpec;exports.createDefaultBlockDOMOutputSpec=a.createDefaultBlockDOMOutputSpec;exports.createFileBlockConfig=a.createFileBlockConfig;exports.createFileBlockSpec=a.createFileBlockSpec;exports.createHeadingBlockConfig=a.createHeadingBlockConfig;exports.createHeadingBlockSpec=a.createHeadingBlockSpec;exports.createImageBlockConfig=a.createImageBlockConfig;exports.createImageBlockSpec=a.createImageBlockSpec;exports.createInlineContentSpecFromTipTapNode=a.createInlineContentSpecFromTipTapNode;exports.createInternalInlineContentSpec=a.createInternalInlineContentSpec;exports.createInternalStyleSpec=a.createInternalStyleSpec;exports.createNumberedListItemBlockConfig=a.createNumberedListItemBlockConfig;exports.createNumberedListItemBlockSpec=a.createNumberedListItemBlockSpec;exports.createPageBreakBlockConfig=a.createPageBreakBlockConfig;exports.createPageBreakBlockSpec=a.createPageBreakBlockSpec;exports.createParagraphBlockConfig=a.createParagraphBlockConfig;exports.createParagraphBlockSpec=a.createParagraphBlockSpec;exports.createQuoteBlockConfig=a.createQuoteBlockConfig;exports.createQuoteBlockSpec=a.createQuoteBlockSpec;exports.createStyleSpec=a.createStyleSpec;exports.createStyleSpecFromTipTapMark=a.createStyleSpecFromTipTapMark;exports.createTableBlockSpec=a.createTableBlockSpec;exports.createToggleListItemBlockConfig=a.createToggleListItemBlockConfig;exports.createToggleListItemBlockSpec=a.createToggleListItemBlockSpec;exports.createToggleWrapper=a.createToggleWrapper;exports.createVideoBlockConfig=a.createVideoBlockConfig;exports.createVideoBlockSpec=a.createVideoBlockSpec;exports.defaultBlockSpecs=a.defaultBlockSpecs;exports.defaultBlockToHTML=a.defaultBlockToHTML;exports.defaultInlineContentSchema=a.defaultInlineContentSchema;exports.defaultInlineContentSpecs=a.defaultInlineContentSpecs;exports.defaultProps=a.defaultProps;exports.defaultStyleSchema=a.defaultStyleSchema;exports.defaultStyleSpecs=a.defaultStyleSpecs;exports.defaultToggledState=a.defaultToggledState;exports.docToBlocks=a.docToBlocks;exports.editorHasBlockWithType=a.editorHasBlockWithType;exports.fileParse=a.fileParse;exports.filenameFromURL=a.filenameFromURL;exports.filterSuggestionItems=a.filterSuggestionItems;exports.formatKeyboardShortcut=a.formatKeyboardShortcut;exports.getBackgroundColorAttribute=a.getBackgroundColorAttribute;exports.getBlockCache=a.getBlockCache;exports.getBlockFromPos=a.getBlockFromPos;exports.getBlockInfo=a.getBlockInfo;exports.getBlockInfoFromResolvedPos=a.getBlockInfoFromResolvedPos;exports.getBlockInfoFromSelection=a.getBlockInfoFromSelection;exports.getBlockInfoFromTransaction=a.getBlockInfoFromTransaction;exports.getBlockInfoWithManualOffset=a.getBlockInfoWithManualOffset;exports.getBlockNoteSchema=a.getBlockNoteSchema;exports.getBlockSchema=a.getBlockSchema;exports.getColspan=a.getColspan;exports.getDefaultSlashMenuItems=a.getDefaultSlashMenuItems;exports.getInlineContentSchema=a.getInlineContentSchema;exports.getInlineContentSchemaFromSpecs=a.getInlineContentSchemaFromSpecs;exports.getLanguageId=a.getLanguageId;exports.getNearestBlockPos=a.getNearestBlockPos;exports.getNodeById=a.getNodeById;exports.getPageBreakSlashMenuItems=a.getPageBreakSlashMenuItems;exports.getParseRules=a.getParseRules;exports.getPmSchema=a.getPmSchema;exports.getRowspan=a.getRowspan;exports.getStyleParseRules=a.getStyleParseRules;exports.getStyleSchema=a.getStyleSchema;exports.getStyleSchemaFromSpecs=a.getStyleSchemaFromSpecs;exports.getTextAlignmentAttribute=a.getTextAlignmentAttribute;exports.getTextColorAttribute=a.getTextColorAttribute;exports.imageParse=a.imageParse;exports.imageRender=a.imageRender;exports.imageToExternalHTML=a.imageToExternalHTML;exports.inlineContentToNodes=a.inlineContentToNodes;exports.insertOrUpdateBlock=a.insertOrUpdateBlock;exports.isAppleOS=a.isAppleOS;exports.isLinkInlineContent=a.isLinkInlineContent;exports.isNodeBlock=a.isNodeBlock;exports.isPartialLinkInlineContent=a.isPartialLinkInlineContent;exports.isPartialTableCell=a.isPartialTableCell;exports.isSafari=a.isSafari;exports.isStyledTextInlineContent=a.isStyledTextInlineContent;exports.isTableCell=a.isTableCell;exports.isTableCellSelection=a.isTableCellSelection;exports.mapTableCell=a.mapTableCell;exports.mergeCSSClasses=a.mergeCSSClasses;exports.mergeParagraphs=a.mergeParagraphs;exports.nodeToBlock=a.nodeToBlock;exports.nodeToCustomInlineContent=a.nodeToCustomInlineContent;exports.parseAudioElement=a.parseAudioElement;exports.parseDefaultProps=a.parseDefaultProps;exports.propsToAttributes=a.propsToAttributes;exports.prosemirrorSliceToSlicedBlocks=a.prosemirrorSliceToSlicedBlocks;exports.stylePropsToAttributes=a.stylePropsToAttributes;exports.tableContentToNodes=a.tableContentToNodes;exports.tablePropSchema=a.tablePropSchema;exports.updateBlock=a.updateBlock;exports.updateBlockCommand=a.updateBlockCommand;exports.updateBlockTr=a.updateBlockTr;exports.uploadToTmpFilesDotOrg_DEV_ONLY=a.uploadToTmpFilesDotOrg_DEV_ONLY;exports.videoParse=a.videoParse;exports.withPageBreak=a.withPageBreak;exports.wrapInBlockStructure=a.wrapInBlockStructure;exports.BlockNoteEditor=ue;exports.DEFAULT_LINK_PROTOCOL=lt;exports.Exporter=jn;exports.FilePanelProsemirrorPlugin=tt;exports.FilePanelView=et;exports.FormattingToolbarProsemirrorPlugin=rt;exports.FormattingToolbarView=ot;exports.HTMLToBlocks=ie;exports.LinkToolbarProsemirrorPlugin=at;exports.SideMenuProsemirrorPlugin=mt;exports.SideMenuView=ht;exports.SuggestionMenuProseMirrorPlugin=gt;exports.TableHandlesProsemirrorPlugin=bt;exports.TableHandlesView=kt;exports.VALID_LINK_PROTOCOLS=ct;exports.blocksToMarkdown=We;exports.cleanHTMLToMarkdown=J;exports.combineByGroup=Jn;exports.createExternalHTMLExporter=K;exports.createInlineContentSpec=eo;exports.createInternalHTMLSerializer=Re;exports.createSuggestionMenu=En;exports.formattingToolbarPluginKey=nt;exports.getBlock=ze;exports.getBlockNoteExtensions=yt;exports.getBlocksChangedByTransaction=se;exports.getDefaultEmojiPickerItems=Xn;exports.getInlineContentParseRules=Me;exports.getNextBlock=qe;exports.getParentBlock=Ge;exports.getPrevBlock=Ke;exports.insertBlocks=De;exports.linkToolbarPluginKey=it;exports.mappingFactory=Wn;exports.markdownToBlocks=Ye;exports.markdownToHTML=ae;exports.removeAndInsertBlocks=ee;exports.selectedFragmentToHTML=le;exports.sideMenuPluginKey=pt;exports.tableHandlesPluginKey=_;exports.trackPosition=ft;
5
5
  //# sourceMappingURL=blocknote.cjs.map