Files
tolaria/patches/@blocknote__core@0.46.2.patch
2026-05-14 09:22:44 +02:00

1099 lines
346 KiB
Diff
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
diff --git a/dist/TrailingNode-CxM966vN.js b/dist/TrailingNode-CxM966vN.js
index 3ac6fe16aa9ae605a59916f8343b8440befda89e..ee009c533fa3826819df0b83a12755b6300db400 100644
--- a/dist/TrailingNode-CxM966vN.js
+++ b/dist/TrailingNode-CxM966vN.js
@@ -80,7 +80,7 @@ function be(n, e, t, o) {
let l = document.createTextNode(
c.textContent
);
- for (const u of c.marks.toReversed())
+ for (const u of Array.from(c.marks).reverse())
if (u.type.name in n.schema.styleSpecs) {
const h = (n.schema.styleSpecs[u.type.name].implementation.toExternalHTML ?? n.schema.styleSpecs[u.type.name].implementation.render)(u.attrs.stringValue, n);
h.contentDOM.appendChild(l), l = h.dom;
@@ -1183,6 +1183,10 @@ class Ft {
b(this, "updateState", (e) => {
this.state = e, this.emitUpdate(this.state);
});
+ b(this, "hideMenu", () => {
+ var e;
+ (e = this.state) != null && e.show && (this.state.show = !1, this.updateState(this.state));
+ });
b(this, "updateStateFromMousePos", () => {
var o, r, s, i, a;
if (this.menuFrozen || !this.mousePos)
@@ -1192,33 +1196,39 @@ class Ft {
clientY: this.mousePos.y
});
if ((e == null ? void 0 : e.element) !== this.pmView.dom || e.distance > se) {
- (o = this.state) != null && o.show && (this.state.show = !1, this.updateState(this.state));
+ this.hideMenu();
return;
}
const t = Ht(this.mousePos, this.pmView);
if (!t || !this.editor.isEditable) {
- (r = this.state) != null && r.show && (this.state.show = !1, this.updateState(this.state));
+ this.hideMenu();
+ return;
+ }
+ if ((s = this.state) != null && s.show && ((i = this.hoveredBlock) != null && i.hasAttribute("data-id")) && ((a = this.hoveredBlock) == null ? void 0 : a.getAttribute("data-id")) === t.id)
+ return;
+ this.hoveredBlock = t.node;
+ const c = this.hoveredBlock.getAttribute("data-id"), l = c ? this.editor.getBlock(c) : void 0;
+ if (!l) {
+ this.hideMenu();
return;
}
- if (!((s = this.state) != null && s.show && ((i = this.hoveredBlock) != null && i.hasAttribute("data-id")) && ((a = this.hoveredBlock) == null ? void 0 : a.getAttribute("data-id")) === t.id) && (this.hoveredBlock = t.node, this.editor.isEditable)) {
- const c = t.node.getBoundingClientRect(), l = t.node.closest("[data-node-type=column]");
+ if (this.editor.isEditable) {
+ const u = t.node.getBoundingClientRect(), h = t.node.closest("[data-node-type=column]");
this.state = {
show: !0,
referencePos: new DOMRect(
- l ? (
+ h ? (
// We take the first child as column elements have some default
// padding. This is a little weird since this child element will
// be the first block, but since it's always non-nested and we
// only take the x coordinate, it's ok.
- l.firstElementChild.getBoundingClientRect().x
+ h.firstElementChild.getBoundingClientRect().x
) : this.pmView.dom.firstChild.getBoundingClientRect().x,
- c.y,
- c.width,
- c.height
+ u.y,
+ u.width,
+ u.height
),
- block: this.editor.getBlock(
- this.hoveredBlock.getAttribute("data-id")
- )
+ block: l
}, this.updateState(this.state);
}
});
@@ -1522,6 +1532,30 @@ function Ut(n) {
function M(n) {
return Array.prototype.indexOf.call(n.parentElement.childNodes, n);
}
+function isValidTablePosition(n) {
+ return Number.isInteger(n) && n >= 0;
+}
+function isValidCellIndex(n) {
+ return Number.isInteger(n) && n >= 0;
+}
+function isValidRelativeCell(n) {
+ return isValidCellIndex(n.row) && isValidCellIndex(n.col);
+}
+function resolveCellPosition(n, e, t) {
+ if (!isValidTablePosition(e) || !isValidRelativeCell(t))
+ return;
+ try {
+ const o = n.doc.resolve(e + 1);
+ if (t.row >= o.node().childCount)
+ return;
+ const r = n.doc.resolve(
+ o.posAtIndex(t.row) + 1
+ );
+ return t.col >= r.node().childCount ? void 0 : n.doc.resolve(r.posAtIndex(t.col));
+ } catch {
+ return;
+ }
+}
function _t(n) {
let e = n;
for (; e && e.nodeName !== "TD" && e.nodeName !== "TH" && !e.classList.contains("tableWrapper"); ) {
@@ -1557,6 +1591,12 @@ class Kt {
b(this, "menuFrozen", !1);
b(this, "mouseState", "up");
b(this, "prevWasEditable", null);
+ b(this, "hideHandles", (e = {}) => {
+ const { resetCell: t = !1, resetDragging: o = !1 } = e;
+ if (!this.state || !this.state.show && !t && !o)
+ return;
+ this.state.show = !1, this.state.showAddOrRemoveRowsButton = !1, this.state.showAddOrRemoveColumnsButton = !1, o && (this.state.draggingState = void 0), t && (this.state.rowIndex = void 0, this.state.colIndex = void 0, this.state.referencePosCell = void 0), this.emitUpdate();
+ });
b(this, "viewMousedownHandler", () => {
this.mouseState = "down";
});
@@ -1569,11 +1609,11 @@ class Kt {
return;
const t = _t(e.target);
if ((t == null ? void 0 : t.type) === "cell" && this.mouseState === "down" && !((l = this.state) != null && l.draggingState)) {
- this.mouseState = "selecting", (u = this.state) != null && u.show && (this.state.show = !1, this.state.showAddOrRemoveRowsButton = !1, this.state.showAddOrRemoveColumnsButton = !1, this.emitUpdate());
+ this.mouseState = "selecting", this.hideHandles();
return;
}
if (!t || !this.editor.isEditable) {
- (h = this.state) != null && h.show && (this.state.show = !1, this.state.showAddOrRemoveRowsButton = !1, this.state.showAddOrRemoveColumnsButton = !1, this.emitUpdate());
+ this.hideHandles();
return;
}
if (!t.tbodyNode)
@@ -1603,7 +1643,7 @@ class Kt {
const w = e.clientY >= o.bottom - 1 && // -1 to account for fractions of pixels in "bottom"
e.clientY < o.bottom + 20, y = e.clientX >= o.right - 1 && e.clientX < o.right + 20, C = (
// always hide handles when the actively hovered table changed
- ((m = this.state) == null ? void 0 : m.block.id) !== s.id || // make sure we don't hide existing handles (keep col / row index) when
+ ((p = (m = this.state) == null ? void 0 : m.block) == null ? void 0 : p.id) !== s.id || // make sure we don't hide existing handles (keep col / row index) when
// we're hovering just above or to the right of a table
e.clientX > o.right || e.clientY > o.bottom
);
@@ -1671,9 +1711,7 @@ class Kt {
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."
- );
+ return e.preventDefault(), this.hideHandles({ resetCell: !0, resetDragging: !0 }), !1;
e.preventDefault();
const { draggingState: t, colIndex: o, rowIndex: r } = this.state, s = this.state.block.content.columnWidths;
if (t.draggedCellOrientation === "row") {
@@ -1735,26 +1773,31 @@ class Kt {
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" || // when collaborating, the table element might be replaced and out of date
+ const e = this.state.block;
+ if (!e) {
+ this.hideHandles({ resetCell: !0, resetDragging: !0 });
+ return;
+ }
+ if (this.state.block = this.editor.getBlock(e.id), !this.state.block || this.state.block.type !== "table" || // when collaborating, the table element might be replaced and out of date
// because yjs replaces the element when for example you change the color via the side menu
!((r = this.tableElement) != null && r.isConnected)) {
- this.state.show = !1, this.state.showAddOrRemoveRowsButton = !1, this.state.showAddOrRemoveColumnsButton = !1, this.emitUpdate();
+ this.hideHandles();
return;
}
- const { height: e, width: t } = Ve(
+ const { height: t, width: o } = Ve(
this.state.block
);
- this.state.rowIndex !== void 0 && this.state.colIndex !== void 0 && (this.state.rowIndex >= e && (this.state.rowIndex = e - 1), this.state.colIndex >= t && (this.state.colIndex = t - 1));
- const o = this.tableElement.querySelector("tbody");
- if (!o)
- throw new Error(
- "Table block does not contain a 'tbody' HTML element. This should never happen."
- );
+ this.state.rowIndex !== void 0 && this.state.colIndex !== void 0 && (this.state.rowIndex >= t && (this.state.rowIndex = t - 1), this.state.colIndex >= o && (this.state.colIndex = o - 1));
+ const i = this.tableElement.querySelector("tbody");
+ if (!i) {
+ this.hideHandles({ resetCell: !0 });
+ return;
+ }
if (this.state.rowIndex !== void 0 && this.state.colIndex !== void 0) {
- const i = o.children[this.state.rowIndex].children[this.state.colIndex];
- i ? this.state.referencePosCell = i.getBoundingClientRect() : (this.state.rowIndex = void 0, this.state.colIndex = void 0);
+ const a = i.children[this.state.rowIndex].children[this.state.colIndex];
+ a ? this.state.referencePosCell = a.getBoundingClientRect() : (this.state.rowIndex = void 0, this.state.colIndex = void 0);
}
- this.state.referencePosTable = o.getBoundingClientRect(), this.emitUpdate();
+ this.state.referencePosTable = i.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(
@@ -1838,10 +1881,10 @@ const D = new P("TableHandlesPlugin"), Po = k(({ editor: n }) => {
* is used as the column drag handle.
*/
colDragStart(o) {
- if (e === void 0 || e.state === void 0 || e.state.colIndex === void 0)
- throw new Error(
- "Attempted to drag table column, but no table block was hovered prior."
- );
+ if (e === void 0 || e.state === void 0 || e.state.colIndex === void 0 || e.tablePos === void 0) {
+ e == null || e.hideHandles({ resetCell: !0, resetDragging: !0 });
+ return;
+ }
e.state.draggingState = {
draggedCellOrientation: "col",
originalIndex: e.state.colIndex,
@@ -1860,10 +1903,10 @@ const D = new P("TableHandlesPlugin"), Po = k(({ editor: n }) => {
* is used as the row drag handle.
*/
rowDragStart(o) {
- if (e.state === void 0 || e.state.rowIndex === void 0)
- throw new Error(
- "Attempted to drag table row, but no table block was hovered prior."
- );
+ if (e === void 0 || e.state === void 0 || e.state.rowIndex === void 0 || e.tablePos === void 0) {
+ e == null || e.hideHandles({ resetCell: !0, resetDragging: !0 });
+ return;
+ }
e.state.draggingState = {
draggedCellOrientation: "row",
originalIndex: e.state.rowIndex,
@@ -1882,10 +1925,10 @@ const D = new P("TableHandlesPlugin"), Po = k(({ editor: n }) => {
* used as the row drag handle, and the one used as the column drag handle.
*/
dragEnd() {
- if (e.state === void 0)
- throw new Error(
- "Attempted to drag table row, but no table block was hovered prior."
- );
+ if (e === void 0 || e.state === void 0) {
+ n.headless || Ut(n.prosemirrorView.root);
+ return;
+ }
e.state.draggingState = void 0, e.emitUpdate(), n.transact((o) => o.setMeta(D, null)), !n.headless && Ut(n.prosemirrorView.root);
},
/**
@@ -1918,30 +1961,38 @@ const D = new P("TableHandlesPlugin"), Po = k(({ editor: n }) => {
setCellSelection(o, r, s = r) {
if (!e)
throw new Error("Table handles view not initialized");
- const i = o.doc.resolve(e.tablePos + 1), a = o.doc.resolve(
- i.posAtIndex(r.row) + 1
- ), c = o.doc.resolve(
- // No need for +1, since CellSelection expects the position before the cell
- a.posAtIndex(r.col)
- ), l = o.doc.resolve(
- i.posAtIndex(s.row) + 1
- ), u = o.doc.resolve(
- // No need for +1, since CellSelection expects the position before the cell
- l.posAtIndex(s.col)
- ), h = o.tr;
- return h.setSelection(
- new yt(c, u)
- ), o.apply(h);
+ const i = resolveCellPosition(
+ o,
+ e.tablePos,
+ r
+ ), a = resolveCellPosition(
+ o,
+ e.tablePos,
+ s
+ );
+ if (!i || !a)
+ return;
+ const c = o.tr;
+ return c.setSelection(
+ new yt(i, a)
+ ), o.apply(c);
},
/**
* Adds a row or column to the table using prosemirror-table commands
*/
addRowOrColumn(o, r) {
+ if (!e || !isValidTablePosition(e.tablePos) || !isValidCellIndex(o)) {
+ e == null || e.hideHandles({ resetCell: !0 });
+ return;
+ }
n.exec((s, i) => {
const a = this.setCellSelection(
s,
r.orientation === "row" ? { row: o, col: 0 } : { row: 0, col: o }
);
+ if (!a)
+ return e == null || e.hideHandles({ resetCell: !0 }), !1;
return r.orientation === "row" ? r.side === "above" ? pt(a, i) : ft(a, i) : r.side === "left" ? gt(a, i) : wt(a, i);
});
+ e == null || e.hideHandles({ resetCell: !0, resetDragging: !0 });
},
@@ -1949,17 +2000,23 @@ const D = new P("TableHandlesPlugin"), Po = k(({ editor: n }) => {
* Removes a row or column from the table using prosemirror-table commands
*/
removeRowOrColumn(o, r) {
+ if (!isValidCellIndex(o))
+ return !1;
return r === "row" ? n.exec((s, i) => {
const a = this.setCellSelection(s, {
row: o,
col: 0
});
+ if (!a)
+ return !1;
return ht(a, i);
}) : n.exec((s, i) => {
const a = this.setCellSelection(s, {
row: 0,
col: o
});
+ if (!a)
+ return !1;
return mt(a, i);
});
},
@@ -1973,6 +2029,8 @@ const D = new P("TableHandlesPlugin"), Po = k(({ editor: n }) => {
o.relativeStartCell,
o.relativeEndCell
) : r;
+ if (!i)
+ return !1;
return ut(i, s);
});
},
@@ -1983,6 +2041,8 @@ const D = new P("TableHandlesPlugin"), Po = k(({ editor: n }) => {
splitCell(o) {
return n.exec((r, s) => {
const i = o ? this.setCellSelection(r, o) : r;
+ if (!i)
+ return !1;
return dt(i, s);
});
},
diff --git a/dist/TrailingNode-D-CZ76FS.cjs b/dist/TrailingNode-D-CZ76FS.cjs
index 8406fda31f41172a823c26412698616a56800aae..2696bca794fd423b6cb6c41bf32c3a11f46e0ab6 100644
--- a/dist/TrailingNode-D-CZ76FS.cjs
+++ b/dist/TrailingNode-D-CZ76FS.cjs
@@ -1,2 +1,2 @@
-"use strict";var we=Object.defineProperty;var be=(n,e,t)=>e in n?we(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var b=(n,e,t)=>be(n,typeof e!="symbol"?e+"":e,t);const C=require("prosemirror-state"),R=require("@tiptap/core"),ke=require("fast-deep-equal"),k=require("./blockToNode-CumVjgem.cjs"),O=require("./defaultBlocks-DosClM5E.cjs"),v=require("./BlockNoteExtension-BWw0r8Gy.cjs"),M=require("y-prosemirror"),Ce=require("yjs"),V=require("@tiptap/pm/state"),ve=require("prosemirror-dropcursor"),q=require("@tiptap/pm/history"),D=require("prosemirror-view"),Se=require("uuid"),Z=require("@tiptap/pm/model"),H=require("prosemirror-model"),xe=require("rehype-parse"),Ee=require("rehype-remark"),Ie=require("remark-gfm"),Pe=require("remark-stringify"),Te=require("unified"),Be=require("hast-util-from-dom"),De=require("unist-util-visit"),T=require("prosemirror-tables"),F=n=>n&&typeof n=="object"&&"default"in n?n:{default:n};function Oe(n){if(n&&typeof n=="object"&&"default"in n)return n;const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const t in n)if(t!=="default"){const o=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,o.get?o:{enumerable:!0,get:()=>n[t]})}}return e.default=n,Object.freeze(e)}const Me=F(ke),B=Oe(Ce),Ae=F(xe),Ne=F(Ee),Le=F(Ie),Re=F(Pe);function ae(n){const e=Array.from(n.classList).filter(t=>!t.startsWith("bn-"))||[];e.length>0?n.className=e.join(" "):n.removeAttribute("class")}function le(n,e,t,o){var a;let r;if(e)if(typeof e=="string")r=k.inlineContentToNodes([e],n.pmSchema);else if(Array.isArray(e))r=k.inlineContentToNodes(e,n.pmSchema);else if(e.type==="tableContent")r=k.tableContentToNodes(e,n.pmSchema);else throw new k.UnreachableCaseError(e.type);else throw new Error("blockContent is required");const i=((o==null?void 0:o.document)??document).createDocumentFragment();for(const c of r)if(c.type.name!=="text"&&n.schema.inlineContentSchema[c.type.name]){const l=n.schema.inlineContentSpecs[c.type.name].implementation;if(l){const u=k.nodeToCustomInlineContent(c,n.schema.inlineContentSchema,n.schema.styleSchema),h=l.toExternalHTML?l.toExternalHTML(u,n):l.render.call({renderType:"dom",props:void 0},u,()=>{},n);if(h){if(i.appendChild(h.dom),h.contentDOM){const g=t.serializeFragment(c.content,o);h.contentDOM.dataset.editable="",h.contentDOM.appendChild(g)}continue}}}else if(c.type.name==="text"){let l=document.createTextNode(c.textContent);for(const u of c.marks.toReversed())if(u.type.name in n.schema.styleSpecs){const h=(n.schema.styleSpecs[u.type.name].implementation.toExternalHTML??n.schema.styleSpecs[u.type.name].implementation.render)(u.attrs.stringValue,n);h.contentDOM.appendChild(l),l=h.dom}else{const h=u.type.spec.toDOM(u,!0),g=H.DOMSerializer.renderSpec(document,h);g.contentDOM.appendChild(l),l=g.dom}i.appendChild(l)}else{const l=t.serializeFragment(H.Fragment.from([c]),o);i.appendChild(l)}return i.childNodes.length===1&&((a=i.firstChild)==null?void 0:a.nodeType)===1&&ae(i.firstChild),i}function Ve(n,e,t,o,r,s,i,a){var y,w,x,L,X,W,G,J,Q;const c=(a==null?void 0:a.document)??document,l=e.pmSchema.nodes.blockContainer,u=t.props||{};for(const[S,I]of Object.entries(e.schema.blockSchema[t.type].propSchema))!(S in u)&&I.default!==void 0&&(u[S]=I.default);const h=(w=(y=l.spec)==null?void 0:y.toDOM)==null?void 0:w.call(y,l.create({id:t.id,...u})),g=Array.from(h.dom.attributes),m=e.blockImplementations[t.type].implementation,p=((x=m.toExternalHTML)==null?void 0:x.call({},{...t,props:u},e,{nestingLevel:i}))||m.render.call({},{...t,props:u},e),d=c.createDocumentFragment();if(p.dom.classList.contains("bn-block-content")){const S=[...g,...Array.from(p.dom.attributes)].filter(I=>I.name.startsWith("data")&&I.name!=="data-content-type"&&I.name!=="data-file-block"&&I.name!=="data-node-view-wrapper"&&I.name!=="data-node-type"&&I.name!=="data-id"&&I.name!=="data-editable");for(const I of S)p.dom.firstChild.setAttribute(I.name,I.value);ae(p.dom.firstChild),i>0&&p.dom.firstChild.setAttribute("data-nesting-level",i.toString()),d.append(...Array.from(p.dom.childNodes))}else d.append(p.dom),i>0&&p.dom.setAttribute("data-nesting-level",i.toString());if(p.contentDOM&&t.content){const S=le(e,t.content,o,a);p.contentDOM.appendChild(S)}let f;if(r.has(t.type)?f="OL":s.has(t.type)&&(f="UL"),f){if(((L=n.lastChild)==null?void 0:L.nodeName)!==f){const S=c.createElement(f);f==="OL"&&"start"in u&&u.start&&(u==null?void 0:u.start)!==1&&S.setAttribute("start",u.start+""),n.append(S)}n.lastChild.appendChild(d)}else n.append(d);if(t.children&&t.children.length>0){const S=c.createDocumentFragment();if(ce(S,e,t.children,o,r,s,i+1,a),((X=n.lastChild)==null?void 0:X.nodeName)==="UL"||((W=n.lastChild)==null?void 0:W.nodeName)==="OL")for(;((G=S.firstChild)==null?void 0:G.nodeName)==="UL"||((J=S.firstChild)==null?void 0:J.nodeName)==="OL";)n.lastChild.lastChild.appendChild(S.firstChild);e.pmSchema.nodes[t.type].isInGroup("blockContent")?n.append(S):(Q=p.contentDOM)==null||Q.append(S)}}const ce=(n,e,t,o,r,s,i=0,a)=>{for(const c of t)Ve(n,e,c,o,r,s,i,a)},He=(n,e,t,o,r,s)=>{const a=((s==null?void 0:s.document)??document).createDocumentFragment();return ce(a,n,e,t,o,r,0,s),a},Y=(n,e)=>{const t=H.DOMSerializer.fromSchema(n);return{exportBlocks:(o,r)=>{const s=He(e,o,t,new Set(["numberedListItem"]),new Set(["bulletListItem","checkListItem","toggleListItem"]),r),i=document.createElement("div");return i.append(s),i.innerHTML},exportInlineContent:(o,r)=>{const s=le(e,o,t,r),i=document.createElement("div");return i.append(s.cloneNode(!0)),i.innerHTML}}};function Fe(n,e){if(e===0)return;const t=n.resolve(e);for(let o=t.depth;o>0;o--){const r=t.node(o);if(O.isNodeBlock(r))return r.attrs.id}}function _e(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 ee(n){const e="__root__",t={},o={},r=k.getPmSchema(n);return n.descendants((s,i)=>{if(!O.isNodeBlock(s))return!0;const a=Fe(n,i),c=a??e;o[c]||(o[c]=[]);const l=k.nodeToBlock(s,r);return t[s.attrs.id]={block:l,parentId:a},o[c].push(s.attrs.id),!0}),{byId:t,childrenByParent:o}}function Ue(n,e){const t=new Set;if(!n||!e)return t;const o=new Set(n),r=e.filter(d=>o.has(d)),s=n.filter(d=>r.includes(d));if(s.length<=1||r.length<=1)return t;const i={};for(let d=0;d<s.length;d++)i[s[d]]=d;const a=r.map(d=>i[d]),c=a.length,l=[],u=[],h=new Array(c).fill(-1),g=(d,f)=>{let y=0,w=d.length;for(;y<w;){const x=y+w>>>1;d[x]<f?y=x+1:w=x}return y};for(let d=0;d<c;d++){const f=a[d],y=g(l,f);y>0&&(h[d]=u[y-1]),y===l.length?(l.push(f),u.push(d)):(l[y]=f,u[y]=d)}const m=new Set;let p=u[u.length-1]??-1;for(;p!==-1;)m.add(p),p=h[p];for(let d=0;d<r.length;d++)m.has(d)||t.add(r[d]);return t}function de(n,e=[]){const t=_e(n),o=R.combineTransactionSteps(n.before,[n,...e]),r=ee(o.before),s=ee(o.doc),i=[],a=new Set;Object.keys(s.byId).filter(m=>!(m in r.byId)).forEach(m=>{i.push({type:"insert",block:s.byId[m].block,source:t,prevBlock:void 0}),a.add(m)}),Object.keys(r.byId).filter(m=>!(m in s.byId)).forEach(m=>{i.push({type:"delete",block:r.byId[m].block,source:t,prevBlock:void 0}),a.add(m)}),Object.keys(s.byId).filter(m=>m in r.byId).forEach(m=>{var y,w;const p=r.byId[m],d=s.byId[m];p.parentId!==d.parentId?(i.push({type:"move",block:d.block,prevBlock:p.block,source:t,prevParent:p.parentId?(y=r.byId[p.parentId])==null?void 0:y.block:void 0,currentParent:d.parentId?(w=s.byId[d.parentId])==null?void 0:w.block:void 0}),a.add(m)):Me.default({...p.block,children:void 0},{...d.block,children:void 0})||(i.push({type:"update",block:d.block,prevBlock:p.block,source:t}),a.add(m))});const c=r.childrenByParent,l=s.childrenByParent,u="__root__",h=new Set([...Object.keys(c),...Object.keys(l)]),g=new Set;return h.forEach(m=>{const p=Ue(c[m],l[m]);p.size!==0&&p.forEach(d=>{var x,L;const f=r.byId[d],y=s.byId[d];!f||!y||f.parentId!==y.parentId||a.has(d)||(f.parentId??u)!==m||g.has(d)||(g.add(d),i.push({type:"move",block:y.block,prevBlock:f.block,source:t,prevParent:f.parentId?(x=r.byId[f.parentId])==null?void 0:x.block:void 0,currentParent:y.parentId?(L=s.byId[y.parentId])==null?void 0:L.block:void 0}),a.add(d))})}),i}const $e=v.createExtension(()=>{const n=[];return{key:"blockChange",prosemirrorPlugins:[new C.Plugin({key:new C.PluginKey("blockChange"),filterTransaction:e=>{let t;return n.reduce((o,r)=>o===!1?o:r({getChanges(){return t||(t=de(e),t)},tr:e})!==!1,!0)}})],subscribe(e){return n.push(e),()=>{n.splice(n.indexOf(e),1)}}}});function te(n){const e=n.charAt(0)==="#"?n.substring(1,7):n,t=parseInt(e.substring(0,2),16),o=parseInt(e.substring(2,4),16),r=parseInt(e.substring(4,6),16),i=[t/255,o/255,r/255].map(c=>c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4));return .2126*i[0]+.7152*i[1]+.0722*i[2]<=.179}function qe(n){const e=document.createElement("span");e.classList.add("bn-collaboration-cursor__base");const t=document.createElement("span");t.setAttribute("contentedEditable","false"),t.classList.add("bn-collaboration-cursor__caret"),t.setAttribute("style",`background-color: ${n.color}; color: ${te(n.color)?"white":"black"}`);const o=document.createElement("span");return o.classList.add("bn-collaboration-cursor__label"),o.setAttribute("style",`background-color: ${n.color}; color: ${te(n.color)?"white":"black"}`),o.insertBefore(document.createTextNode(n.name),null),t.insertBefore(o,null),e.insertBefore(document.createTextNode(""),null),e.insertBefore(t,null),e.insertBefore(document.createTextNode(""),null),e}const z=v.createExtension(({options:n})=>{const e=new Map,t=n.provider&&"awareness"in n.provider&&typeof n.provider.awareness=="object"?n.provider.awareness:void 0;return t&&("setLocalStateField"in t&&typeof t.setLocalStateField=="function"&&t.setLocalStateField("user",n.user),"on"in t&&typeof t.on=="function"&&n.showCursorLabels!=="always"&&t.on("change",({updated:o})=>{for(const r of o){const s=e.get(r);s&&(s.element.setAttribute("data-active",""),s.hideTimeout&&clearTimeout(s.hideTimeout),e.set(r,{element:s.element,hideTimeout:setTimeout(()=>{s.element.removeAttribute("data-active")},2e3)}))}})),{key:"yCursor",prosemirrorPlugins:[t?M.yCursorPlugin(t,{selectionBuilder:M.defaultSelectionBuilder,cursorBuilder(o,r){let s=e.get(r);if(!s){const i=(n.renderCursor??qe)(o);n.showCursorLabels!=="always"&&(i.addEventListener("mouseenter",()=>{const a=e.get(r);a.element.setAttribute("data-active",""),a.hideTimeout&&(clearTimeout(a.hideTimeout),e.set(r,{element:a.element,hideTimeout:void 0}))}),i.addEventListener("mouseleave",()=>{const a=e.get(r);e.set(r,{element:a.element,hideTimeout:setTimeout(()=>{a.element.removeAttribute("data-active")},2e3)})})),s={element:i,hideTimeout:void 0},e.set(r,s)}return s.element}}):void 0].filter(Boolean),dependsOn:["ySync"],updateUser(o){t==null||t.setLocalStateField("user",o)}}}),U=v.createExtension(({options:n})=>({key:"ySync",prosemirrorPlugins:[M.ySyncPlugin(n.fragment)],runsBefore:["default"]})),$=v.createExtension(()=>({key:"yUndo",prosemirrorPlugins:[M.yUndoPlugin()],dependsOn:["yCursor","ySync"],undoCommand:M.undoCommand,redoCommand:M.redoCommand}));function ze(n,e){const t=n.doc;if(n._item===null){const o=Array.from(t.share.keys()).find(r=>t.share.get(r)===n);if(o==null)throw new Error("type does not exist in other ydoc");return e.get(o,n.constructor)}else{const o=n._item,r=e.store.clients.get(o.id.client)??[],s=B.findIndexSS(r,o.id.clock);return r[s].content.type}}const Ke=v.createExtension(({editor:n,options:e})=>{let t;const o=v.createStore({isForked:!1});return{key:"yForkDoc",store:o,fork(){if(t)return;const r=e.fragment;if(!r)throw new Error("No fragment to fork from");const s=new B.Doc;B.applyUpdate(s,B.encodeStateAsUpdate(r.doc));const i=ze(r,s);t={undoStack:M.yUndoPluginKey.getState(n.prosemirrorState).undoManager.undoStack,originalFragment:r,forkedFragment:i},n.unregisterExtension([$,z,U]);const a={...e,fragment:i};n.registerExtension([U(a),$()]),o.setState({isForked:!0})},merge({keepChanges:r}){if(!t)return;n.unregisterExtension(["ySync","yCursor","yUndo"]);const{originalFragment:s,forkedFragment:i,undoStack:a}=t;if(n.registerExtension([U(e),z(e),$()]),M.yUndoPluginKey.getState(n.prosemirrorState).undoManager.undoStack=a,r){const c=B.encodeStateAsUpdate(i.doc,B.encodeStateVector(s.doc));B.applyUpdate(s.doc,c,n)}t=void 0,o.setState({isForked:!1})}}}),ue=(n,e)=>{e(n),n.forEach(t=>{t instanceof B.XmlElement&&ue(t,e)})},Ye=(n,e)=>{const t=new Map;return n.forEach(o=>{o instanceof B.XmlElement&&ue(o,r=>{if(r.nodeName==="blockContainer"&&r.hasAttribute("id")){const s=r.getAttribute("textColor"),i=r.getAttribute("backgroundColor"),a={textColor:s===O.defaultProps.textColor.default?void 0:s,backgroundColor:i===O.defaultProps.backgroundColor.default?void 0:i};(a.textColor||a.backgroundColor)&&t.set(r.getAttribute("id"),a)}})}),t.size===0?!1:(e.doc.descendants((o,r)=>{if(o.type.name==="blockContainer"&&t.has(o.attrs.id)){const s=e.doc.nodeAt(r+1);if(!s)throw new Error("No element found");e.setNodeMarkup(r+1,void 0,{...s.attrs,...t.get(o.attrs.id)})}}),!0)},je=[Ye],Xe=v.createExtension(({options:n})=>{let e=!1;const t=new V.PluginKey("schemaMigration");return{key:"schemaMigration",prosemirrorPlugins:[new V.Plugin({key:t,appendTransaction:(o,r,s)=>{if(e||!o.some(a=>a.getMeta("y-sync$"))||o.every(a=>!a.docChanged)||!n.fragment.firstChild)return;const i=s.tr;for(const a of je)a(n.fragment,i);if(e=!0,!!i.docChanged)return i}})]}}),We=v.createExtension(({editor:n,options:e})=>({key:"dropCursor",prosemirrorPlugins:[(e.dropCursor??ve.dropCursor)({width:5,color:"#ddeeff",editor:n})]})),Ge=v.createExtension(({editor:n})=>{const e=v.createStore(!1),t=()=>n.transact(o=>{var s;if(o.selection.empty||o.selection instanceof C.NodeSelection&&(o.selection.node.type.spec.content==="inline*"||((s=o.selection.node.firstChild)==null?void 0:s.type.spec.content)==="inline*")||o.selection instanceof C.TextSelection&&o.doc.textBetween(o.selection.from,o.selection.to).length===0)return!1;let r=!1;return o.selection.content().content.descendants(i=>(i.type.spec.code&&(r=!0),!r)),!r});return{key:"formattingToolbar",store:e,mount({dom:o,signal:r}){let s=!1;const i=n.onChange(()=>{s||e.setState(t())}),a=n.onSelectionChange(()=>{s||e.setState(t())});o.addEventListener("pointerdown",()=>{s=!0,e.setState(!1)},{signal:r}),n.prosemirrorView.root.addEventListener("pointerup",()=>{s=!1,n.isFocused()&&e.setState(t())},{signal:r,capture:!0}),o.addEventListener("pointercancel",()=>{s=!1},{signal:r,capture:!0}),r.addEventListener("abort",()=>{i(),a()})}}}),Je=v.createExtension(()=>({key:"history",prosemirrorPlugins:[q.history()],undoCommand:q.undo,redoCommand:q.redo})),Qe=v.createExtension(({editor:n})=>{function e(r){let s=n.prosemirrorView.nodeDOM(r);for(;s&&s.parentElement;){if(s.nodeName==="A")return s;s=s.parentElement}return null}function t(r,s){return n.transact(i=>{const a=i.doc.resolve(r),c=a.marks().find(u=>u.type.name===s);if(!c)return;const l=R.getMarkRange(a,c.type);if(l)return{range:l,mark:c,get text(){return i.doc.textBetween(l.from,l.to)},get position(){return R.posToDOMRect(n.prosemirrorView,l.from,l.to).toJSON()}}})}function o(){return n.transact(r=>{const s=r.selection;if(s.empty)return t(s.anchor,"link")})}return{key:"linkToolbar",getLinkAtSelection:o,getLinkElementAtPos:e,getMarkAtPos:t,getLinkAtElement(r){return n.transact(()=>{const s=n.prosemirrorView.posAtDOM(r,0)+1;return t(s,"link")})},editLink(r,s,i=n.transact(a=>a.selection.anchor)){n.transact(a=>{const c=k.getPmSchema(a),{range:l}=t(i+1,"link")||{range:{from:a.selection.from,to:a.selection.to}};l&&(a.insertText(s,l.from,l.to),a.addMark(l.from,l.from+s.length,c.mark("link",{href:r})))}),n.prosemirrorView.focus()},deleteLink(r=n.transact(s=>s.selection.anchor)){n.transact(s=>{const i=k.getPmSchema(s),{range:a}=t(r+1,"link")||{range:{from:s.selection.from,to:s.selection.to}};a&&s.removeMark(a.from,a.to,i.marks.link).setMeta("preventAutolink",!0)}),n.prosemirrorView.focus()}}}),Ze=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"],et="https",tt=new C.PluginKey("node-selection-keyboard"),ot=v.createExtension(()=>({key:"nodeSelectionKeyboard",prosemirrorPlugins:[new C.Plugin({key:tt,props:{handleKeyDown:(n,e)=>{if("node"in n.state.selection){if(e.ctrlKey||e.metaKey)return!1;if(e.key.length===1)return e.preventDefault(),!0;if(e.key==="Enter"&&!e.isComposing&&!e.shiftKey&&!e.altKey&&!e.ctrlKey&&!e.metaKey){const t=n.state.tr;return n.dispatch(t.insert(n.state.tr.selection.$to.after(),n.state.schema.nodes.paragraph.createChecked()).setSelection(new C.TextSelection(t.doc.resolve(n.state.tr.selection.$to.after()+1)))),!0}}return!1}}})]})),nt=new C.PluginKey("blocknote-placeholder"),rt=v.createExtension(({editor:n,options:e})=>{const t=e.placeholders;return{key:"placeholder",prosemirrorPlugins:[new C.Plugin({key:nt,view:o=>{const r=`placeholder-selector-${Se.v4()}`;o.dom.classList.add(r);const s=document.createElement("style"),i=n._tiptapEditor.options.injectNonce;i&&s.setAttribute("nonce",i),o.root instanceof window.ShadowRoot?o.root.append(s):o.root.head.appendChild(s);const a=s.sheet,c=(l="")=>`.${r} .bn-block-content${l} .bn-inline-content:has(> .ProseMirror-trailingBreak:only-child):before`;try{const{default:l,emptyDocument:u,...h}=t||{};for(const[p,d]of Object.entries(h)){const f=`[data-content-type="${p}"]`;a.insertRule(`${c(f)} { content: ${JSON.stringify(d)}; }`)}const g="[data-is-only-empty-block]",m="[data-is-empty-and-focused]";a.insertRule(`${c(g)} { content: ${JSON.stringify(u)}; }`),a.insertRule(`${c(m)} { content: ${JSON.stringify(l)}; }`)}catch(l){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)",l)}return{destroy:()=>{o.root instanceof window.ShadowRoot?o.root.removeChild(s):o.root.head.removeChild(s)}}},props:{decorations:o=>{const{doc:r,selection:s}=o;if(!n.isEditable||!s.empty||s.$from.parent.type.spec.code)return;const i=[];o.doc.content.size===6&&i.push(D.Decoration.node(2,4,{"data-is-only-empty-block":"true"}));const a=s.$anchor,c=a.parent;if(c.content.size===0){const l=a.before();i.push(D.Decoration.node(l,l+c.nodeSize,{"data-is-empty-and-focused":"true"}))}return D.DecorationSet.create(r,i)}}})]}}),oe=new C.PluginKey("previous-blocks"),st={index:"index",level:"level",type:"type",depth:"depth","depth-change":"depth-change"},it=v.createExtension(()=>{let n;return{key:"previousBlockType",prosemirrorPlugins:[new C.Plugin({key:oe,view(e){return{update:async(t,o)=>{var r;((r=this.key)==null?void 0:r.getState(t.state).updatedBlocks.size)>0&&(n=setTimeout(()=>{t.dispatch(t.state.tr.setMeta(oe,{clearUpdate:!0}))},0))},destroy:()=>{n&&clearTimeout(n)}}},state:{init(){return{prevTransactionOldBlockAttrs:{},currentTransactionOldBlockAttrs:{},updatedBlocks:new Set}},apply(e,t,o,r){if(t.currentTransactionOldBlockAttrs={},t.updatedBlocks.clear(),!e.docChanged||o.doc.eq(r.doc))return t;const s={},i=R.findChildren(o.doc,l=>l.attrs.id),a=new Map(i.map(l=>[l.node.attrs.id,l])),c=R.findChildren(r.doc,l=>l.attrs.id);for(const l of c){const u=a.get(l.node.attrs.id),h=u==null?void 0:u.node.firstChild,g=l.node.firstChild;if(u&&h&&g){const m={index:g.attrs.index,level:g.attrs.level,type:g.type.name,depth:r.doc.resolve(l.pos).depth},p={index:h.attrs.index,level:h.attrs.level,type:h.type.name,depth:o.doc.resolve(u.pos).depth};s[l.node.attrs.id]=p,t.currentTransactionOldBlockAttrs[l.node.attrs.id]=p,JSON.stringify(p)!==JSON.stringify(m)&&(p["depth-change"]=p.depth-m.depth,t.updatedBlocks.add(l.node.attrs.id))}}return t.prevTransactionOldBlockAttrs=s,t}},props:{decorations(e){const t=this.getState(e);if(t.updatedBlocks.size===0)return;const o=[];return e.doc.descendants((r,s)=>{if(!r.attrs.id||!t.updatedBlocks.has(r.attrs.id))return;const i=t.currentTransactionOldBlockAttrs[r.attrs.id],a={};for(const[l,u]of Object.entries(i))a["data-prev-"+st[l]]=u||"none";const c=D.Decoration.node(s,s+r.nodeSize,{...a});o.push(c)}),D.DecorationSet.create(e.doc,o)}}})]}});function he(n,e){var t,o;for(;n&&n.parentElement&&n.parentElement!==e.dom&&((t=n.getAttribute)==null?void 0:t.call(n,"data-node-type"))!=="blockContainer";)n=n.parentElement;if(((o=n.getAttribute)==null?void 0:o.call(n,"data-node-type"))==="blockContainer")return{node:n,id:n.getAttribute("data-id")}}function at(){const n=e=>{let t=e.children.length;for(let o=0;o<t;o++){const r=e.children[o];if(r.type==="element"&&(n(r),r.tagName==="u"))if(r.children.length>0){e.children.splice(o,1,...r.children);const s=r.children.length-1;t+=s,o+=s}else e.children.splice(o,1),t--,o--}};return n}function lt(){const n=e=>{var t;if(e.children&&"length"in e.children&&e.children.length)for(let o=e.children.length-1;o>=0;o--){const r=e.children[o],s=o+1<e.children.length?e.children[o+1]:void 0;r.type==="element"&&r.tagName==="input"&&((t=r.properties)==null?void 0:t.type)==="checkbox"&&(s==null?void 0:s.type)==="element"&&s.tagName==="p"?(s.tagName="span",s.children.splice(0,0,Be.fromDom(document.createTextNode(" ")))):n(r)}};return n}function ct(){return n=>{De.visit(n,"element",(e,t,o)=>{var r,s,i,a;if(o&&e.tagName==="video"){const c=((r=e.properties)==null?void 0:r.src)||((s=e.properties)==null?void 0:s["data-url"])||"",l=((i=e.properties)==null?void 0:i.title)||((a=e.properties)==null?void 0:a["data-name"])||"";o.children[t]={type:"text",value:`![${l}](${c})`}}})}}function j(n){return Te.unified().use(Ae.default,{fragment:!0}).use(ct).use(at).use(lt).use(Ne.default).use(Le.default).use(Re.default,{handlers:{text:t=>t.value}}).processSync(n).value}function dt(n,e,t,o){const s=Y(e,t).exportBlocks(n,o);return j(s)}function me(n){const e=[];return n.descendants(t=>{var r,s;const o=k.getPmSchema(t);return t.type.name==="blockContainer"&&((r=t.firstChild)==null?void 0:r.type.name)==="blockGroup"?!0:t.type.name==="columnList"&&t.childCount===1?((s=t.firstChild)==null||s.forEach(i=>{e.push(k.nodeToBlock(i,o))}),!1):t.type.isInGroup("bnBlock")?(e.push(k.nodeToBlock(t,o)),!1):!0}),e}class A extends C.Selection{constructor(t,o){super(t,o);b(this,"nodes");const r=t.node();this.nodes=[],t.doc.nodesBetween(t.pos,o.pos,(s,i,a)=>{if(a!==null&&a.eq(r))return this.nodes.push(s),!1})}static create(t,o,r=o){return new A(t.resolve(o),t.resolve(r))}content(){return new H.Slice(H.Fragment.from(this.nodes),0,0)}eq(t){if(!(t instanceof A)||this.nodes.length!==t.nodes.length||this.from!==t.from||this.to!==t.to)return!1;for(let o=0;o<this.nodes.length;o++)if(!this.nodes[o].eq(t.nodes[o]))return!1;return!0}map(t,o){const r=o.mapResult(this.from),s=o.mapResult(this.to);return s.deleted?C.Selection.near(t.resolve(r.pos)):r.deleted?C.Selection.near(t.resolve(s.pos)):new A(t.resolve(r.pos),t.resolve(s.pos))}toJSON(){return{type:"multiple-node",anchor:this.anchor,head:this.head}}}C.Selection.jsonID("multiple-node",A);let P;function ut(n,e){let t,o;const r=e.resolve(n.from).node().type.spec.group==="blockContent",s=e.resolve(n.to).node().type.spec.group==="blockContent",i=Math.min(n.$anchor.depth,n.$head.depth);if(r&&s){const a=n.$from.start(i-1),c=n.$to.end(i-1);t=e.resolve(a-1).pos,o=e.resolve(c+1).pos}else t=n.from,o=n.to;return{from:t,to:o}}function ne(n,e,t=e){e===t&&(t+=n.state.doc.resolve(e+1).node().nodeSize);const o=n.domAtPos(e).node.cloneNode(!0),r=n.domAtPos(e).node,s=(h,g)=>Array.prototype.indexOf.call(h.children,g),i=s(r,n.domAtPos(e+1).node.parentElement),a=s(r,n.domAtPos(t-1).node.parentElement);for(let h=r.childElementCount-1;h>=0;h--)(h>a||h<i)&&o.removeChild(o.children[h]);pe(n.root),P=o;const c=P.getElementsByTagName("iframe");for(let h=0;h<c.length;h++){const g=c[h],m=g.parentElement;m&&m.removeChild(g)}const u=n.dom.className.split(" ").filter(h=>h!=="ProseMirror"&&h!=="bn-root"&&h!=="bn-editor").join(" ");P.className=P.className+" bn-drag-preview "+u,n.root instanceof ShadowRoot?n.root.appendChild(P):n.root.body.appendChild(P)}function pe(n){P!==void 0&&(n instanceof ShadowRoot?n.removeChild(P):n.body.removeChild(P),P=void 0)}function ht(n,e,t){if(!n.dataTransfer||t.headless)return;const o=t.prosemirrorView,r=O.getNodeById(e.id,o.state.doc);if(!r)throw new Error(`Block with ID ${e.id} not found`);const s=r.posBeforeNode;if(s!=null){const i=o.state.selection,a=o.state.doc,{from:c,to:l}=ut(i,a),u=c<=s&&s<l,h=i.$anchor.node()!==i.$head.node()||i instanceof A;u&&h?(o.dispatch(o.state.tr.setSelection(A.create(a,c,l))),ne(o,c,l)):(o.dispatch(o.state.tr.setSelection(C.NodeSelection.create(o.state.doc,s))),ne(o,s));const g=o.state.selection.content(),m=t.pmSchema,p=o.serializeForClipboard(g).dom.innerHTML,d=Y(m,t),f=me(g.content),y=d.exportBlocks(f,{}),w=j(y);n.dataTransfer.clearData(),n.dataTransfer.setData("blocknote/html",p),n.dataTransfer.setData("text/html",y),n.dataTransfer.setData("text/plain",w),n.dataTransfer.effectAllowed="move",n.dataTransfer.setDragImage(P,0,0)}}const re=250;function K(n,e,t=!0){const o=n.root.elementsFromPoint(e.left,e.top);for(const r of o)if(n.dom.contains(r))return t&&r.closest("[data-node-type=columnList]")?K(n,{left:e.left+50,top:e.top},!1):he(r,n)}function mt(n,e){if(!e.dom.firstChild)return;const t=e.dom.firstChild.getBoundingClientRect(),o={left:Math.min(Math.max(t.left+10,n.x),t.right-10),top:n.y},r=K(e,o);if(!r)return;const s=r.node.getBoundingClientRect();return K(e,{left:s.right-10,top:n.y},!1)}class fe{constructor(e,t,o){b(this,"state");b(this,"emitUpdate");b(this,"mousePos");b(this,"hoveredBlock");b(this,"menuFrozen",!1);b(this,"isDragOrigin",!1);b(this,"updateState",e=>{this.state=e,this.emitUpdate(this.state)});b(this,"updateStateFromMousePos",()=>{var o,r,s,i,a;if(this.menuFrozen||!this.mousePos)return;const e=this.findClosestEditorElement({clientX:this.mousePos.x,clientY:this.mousePos.y});if((e==null?void 0:e.element)!==this.pmView.dom||e.distance>re){(o=this.state)!=null&&o.show&&(this.state.show=!1,this.updateState(this.state));return}const t=mt(this.mousePos,this.pmView);if(!t||!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"))&&((a=this.hoveredBlock)==null?void 0:a.getAttribute("data-id"))===t.id)&&(this.hoveredBlock=t.node,this.editor.isEditable)){const c=t.node.getBoundingClientRect(),l=t.node.closest("[data-node-type=column]");this.state={show:!0,referencePos:new DOMRect(l?l.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)}});b(this,"onDragStart",e=>{var i;const t=(i=e.dataTransfer)==null?void 0:i.getData("blocknote/html");if(!t||this.pmView.dragging)return;const o=document.createElement("div");o.innerHTML=t;const s=Z.DOMParser.fromSchema(this.pmView.state.schema).parse(o,{topNode:this.pmView.state.schema.nodes.blockGroup.create()});this.pmView.dragging={slice:new Z.Slice(s.content,0,0),move:!0}});b(this,"findClosestEditorElement",e=>{const t=Array.from(this.pmView.root.querySelectorAll(".bn-editor"));if(t.length===0)return null;let o=t[0],r=Number.MAX_VALUE;return t.forEach(s=>{const i=s.querySelector(".bn-block-group").getBoundingClientRect(),a=e.clientX<i.left?i.left-e.clientX:e.clientX>i.right?e.clientX-i.right:0,c=e.clientY<i.top?i.top-e.clientY:e.clientY>i.bottom?e.clientY-i.bottom:0,l=Math.sqrt(Math.pow(a,2)+Math.pow(c,2));l<r&&(r=l,o=s)}),{element:o,distance:r}});b(this,"onDragOver",e=>{if(e.synthetic)return;const t=this.getDragEventContext(e);if(!t||!t.isDropPoint){this.closeDropCursor();return}t.isDropPoint&&!t.isDropWithinEditorBounds&&this.dispatchSyntheticEvent(e)});b(this,"closeDropCursor",()=>{const e=new Event("dragleave",{bubbles:!1});e.synthetic=!0,this.pmView.dom.dispatchEvent(e)});b(this,"getDragEventContext",e=>{var c;const t=!((c=e.dataTransfer)!=null&&c.types.includes("blocknote/html"))&&!!this.pmView.dragging,o=!!this.isDragOrigin,r=t||o,s=this.findClosestEditorElement(e);if(!s||s.distance>re)return;const i=s.element===this.pmView.dom,a=i&&s.distance===0;if(!(!i&&!r))return{isDropPoint:i,isDropWithinEditorBounds:a,isDragOrigin:r}});b(this,"onDrop",e=>{if(e.synthetic)return;const t=this.getDragEventContext(e);if(!t){this.closeDropCursor();return}const{isDropPoint:o,isDropWithinEditorBounds:r,isDragOrigin:s}=t;if(!r&&o&&this.dispatchSyntheticEvent(e),o){if(this.pmView.dragging)return;this.pmView.dispatch(this.pmView.state.tr.setSelection(V.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}});b(this,"onDragEnd",e=>{e.synthetic||(this.pmView.dragging=null)});b(this,"onKeyDown",e=>{var t;(t=this.state)!=null&&t.show&&this.editor.isFocused()&&(this.state.show=!1,this.emitUpdate(this.state))});b(this,"onMouseMove",e=>{var s;if(this.menuFrozen)return;this.mousePos={x:e.clientX,y:e.clientY};const t=this.pmView.dom.getBoundingClientRect(),o=this.mousePos.x>t.left&&this.mousePos.x<t.right&&this.mousePos.y>t.top&&this.mousePos.y<t.bottom,r=this.pmView.dom.parentElement;if(o&&e&&e.target&&!(r===e.target||r.contains(e.target))){(s=this.state)!=null&&s.show&&(this.state.show=!1,this.emitUpdate(this.state));return}this.updateStateFromMousePos()});this.editor=e,this.pmView=t,this.emitUpdate=()=>{if(!this.state)throw new Error("Attempting to update uninitialized side menu");o(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)}dispatchSyntheticEvent(e){const t=new Event(e.type,e),o=this.pmView.dom.firstChild.getBoundingClientRect();t.clientX=e.clientX,t.clientY=e.clientY,t.clientX=Math.min(Math.max(e.clientX,o.left),o.left+o.width),t.clientY=Math.min(Math.max(e.clientY,o.top),o.top+o.height),t.dataTransfer=e.dataTransfer,t.preventDefault=()=>e.preventDefault(),t.synthetic=!0,this.pmView.dom.dispatchEvent(t)}update(e,t){var r;!t.doc.eq(this.pmView.state.doc)&&((r=this.state)!=null&&r.show)&&this.updateStateFromMousePos()}destroy(){var e;(e=this.state)!=null&&e.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)}}const ge=new V.PluginKey("SideMenuPlugin"),pt=v.createExtension(({editor:n})=>{let e;const t=v.createStore(void 0);return{key:"sideMenu",store:t,prosemirrorPlugins:[new V.Plugin({key:ge,view:o=>(e=new fe(n,o,r=>{t.setState({...r})}),e)})],blockDragStart(o,r){e&&(e.isDragOrigin=!0),ht(o,r,n)},blockDragEnd(){pe(n.prosemirrorView.root),e&&(e.isDragOrigin=!1),n.blur()},freezeMenu(){e.menuFrozen=!0,e.state.show=!0,e.emitUpdate(e.state)},unfreezeMenu(){e.menuFrozen=!1,e.state.show=!1,e.emitUpdate(e.state)}}});let E;function se(n){E||(E=document.createElement("div"),E.innerHTML="_",E.style.opacity="0",E.style.height="1px",E.style.width="1px",n instanceof Document?n.body.appendChild(E):n.appendChild(E))}function ft(n){E&&(n instanceof Document?n.body.removeChild(E):n.removeChild(E),E=void 0)}function _(n){return Array.prototype.indexOf.call(n.parentElement.childNodes,n)}function gt(n){let e=n;for(;e&&e.nodeName!=="TD"&&e.nodeName!=="TH"&&!e.classList.contains("tableWrapper");){if(e.classList.contains("ProseMirror"))return;const t=e.parentNode;if(!t||!(t instanceof Element))return;e=t}return e.nodeName==="TD"||e.nodeName==="TH"?{type:"cell",domNode:e,tbodyNode:e.closest("tbody")}:{type:"wrapper",domNode:e,tbodyNode:e.querySelector("tbody")}}function yt(n,e){const t=e.querySelectorAll(n);for(let o=0;o<t.length;o++)t[o].style.visibility="hidden"}class ye{constructor(e,t,o){b(this,"state");b(this,"emitUpdate");b(this,"tableId");b(this,"tablePos");b(this,"tableElement");b(this,"menuFrozen",!1);b(this,"mouseState","up");b(this,"prevWasEditable",null);b(this,"viewMousedownHandler",()=>{this.mouseState="down"});b(this,"mouseUpHandler",e=>{this.mouseState="up",this.mouseMoveHandler(e)});b(this,"mouseMoveHandler",e=>{var l,u,h,g,m,p,d,f;if(this.menuFrozen||this.mouseState==="selecting"||!(e.target instanceof Element)||!this.pmView.dom.contains(e.target))return;const t=gt(e.target);if((t==null?void 0:t.type)==="cell"&&this.mouseState==="down"&&!((l=this.state)!=null&&l.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(!t||!this.editor.isEditable){(h=this.state)!=null&&h.show&&(this.state.show=!1,this.state.showAddOrRemoveRowsButton=!1,this.state.showAddOrRemoveColumnsButton=!1,this.emitUpdate());return}if(!t.tbodyNode)return;const o=t.tbodyNode.getBoundingClientRect(),r=he(t.domNode,this.pmView);if(!r)return;this.tableElement=r.node;let s;const i=this.editor.transact(y=>O.getNodeById(r.id,y.doc));if(!i)throw new Error(`Block with ID ${r.id} not found`);const a=k.nodeToBlock(i.node,this.editor.pmSchema,this.editor.schema.blockSchema,this.editor.schema.inlineContentSchema,this.editor.schema.styleSchema);if(O.editorHasBlockWithType(this.editor,"table")&&(this.tablePos=i.posBeforeNode+1,s=a),!s)return;this.tableId=r.id;const c=(g=t.domNode.closest(".tableWrapper"))==null?void 0:g.querySelector(".table-widgets-container");if((t==null?void 0:t.type)==="wrapper"){const y=e.clientY>=o.bottom-1&&e.clientY<o.bottom+20,w=e.clientX>=o.right-1&&e.clientX<o.right+20,x=((m=this.state)==null?void 0:m.block.id)!==s.id||e.clientX>o.right||e.clientY>o.bottom;this.state={...this.state,show:!0,showAddOrRemoveRowsButton:y,showAddOrRemoveColumnsButton:w,referencePosTable:o,block:s,widgetContainer:c,colIndex:x||(p=this.state)==null?void 0:p.colIndex,rowIndex:x||(d=this.state)==null?void 0:d.rowIndex,referencePosCell:x||(f=this.state)==null?void 0:f.referencePosCell}}else{const y=_(t.domNode),w=_(t.domNode.parentElement),x=t.domNode.getBoundingClientRect();if(this.state!==void 0&&this.state.show&&this.tableId===r.id&&this.state.rowIndex===w&&this.state.colIndex===y)return;this.state={show:!0,showAddOrRemoveColumnsButton:y===s.content.rows[0].cells.length-1,showAddOrRemoveRowsButton:w===s.content.rows.length-1,referencePosTable:o,block:s,draggingState:void 0,referencePosCell:x,colIndex:y,rowIndex:w,widgetContainer:c}}return this.emitUpdate(),!1});b(this,"dragOverHandler",e=>{var g;if(((g=this.state)==null?void 0:g.draggingState)===void 0)return;e.preventDefault(),e.dataTransfer.dropEffect="move",yt(".prosemirror-dropcursor-block, .prosemirror-dropcursor-inline",this.pmView.root);const t={left:Math.min(Math.max(e.clientX,this.state.referencePosTable.left+1),this.state.referencePosTable.right-1),top:Math.min(Math.max(e.clientY,this.state.referencePosTable.top+1),this.state.referencePosTable.bottom-1)},o=this.pmView.root.elementsFromPoint(t.left,t.top).filter(m=>m.tagName==="TD"||m.tagName==="TH");if(o.length===0)return;const r=o[0];let s=!1;const i=_(r.parentElement),a=_(r),c=this.state.draggingState.draggedCellOrientation==="row"?this.state.rowIndex:this.state.colIndex,u=(this.state.draggingState.draggedCellOrientation==="row"?i:a)!==c;(this.state.rowIndex!==i||this.state.colIndex!==a)&&(this.state.rowIndex=i,this.state.colIndex=a,this.state.referencePosCell=r.getBoundingClientRect(),s=!0);const h=this.state.draggingState.draggedCellOrientation==="row"?t.top:t.left;this.state.draggingState.mousePos!==h&&(this.state.draggingState.mousePos=h,s=!0),s&&this.emitUpdate(),u&&this.editor.transact(m=>m.setMeta(N,!0))});b(this,"dropHandler",e=>{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.");e.preventDefault();const{draggingState:t,colIndex:o,rowIndex:r}=this.state,s=this.state.block.content.columnWidths;if(t.draggedCellOrientation==="row"){if(!k.canRowBeDraggedInto(this.state.block,t.originalIndex,r))return!1;const i=k.moveRow(this.state.block,t.originalIndex,r);this.editor.updateBlock(this.state.block,{type:"table",content:{...this.state.block.content,rows:i}})}else{if(!k.canColumnBeDraggedInto(this.state.block,t.originalIndex,o))return!1;const i=k.moveColumn(this.state.block,t.originalIndex,o),[a]=s.splice(t.originalIndex,1);s.splice(o,0,a),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=e,this.pmView=t,this.emitUpdate=()=>{if(!this.state)throw new Error("Attempting to update uninitialized image toolbar");o(this.state)},t.dom.addEventListener("mousemove",this.mouseMoveHandler),t.dom.addEventListener("mousedown",this.viewMousedownHandler),window.addEventListener("mouseup",this.mouseUpHandler),t.root.addEventListener("dragover",this.dragOverHandler),t.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:e,width:t}=k.getDimensionsOfTable(this.state.block);this.state.rowIndex!==void 0&&this.state.colIndex!==void 0&&(this.state.rowIndex>=e&&(this.state.rowIndex=e-1),this.state.colIndex>=t&&(this.state.colIndex=t-1));const o=this.tableElement.querySelector("tbody");if(!o)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=o.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=o.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 N=new C.PluginKey("TableHandlesPlugin"),wt=v.createExtension(({editor:n})=>{let e;const t=v.createStore(void 0);return{key:"tableHandles",store:t,prosemirrorPlugins:[new C.Plugin({key:N,view:o=>(e=new ye(n,o,r=>{t.setState(r.block?{...r,draggingState:r.draggingState?{...r.draggingState}:void 0}:void 0)}),e),props:{decorations:o=>{if(e===void 0||e.state===void 0||e.state.draggingState===void 0||e.tablePos===void 0)return;const r=e.state.draggingState.draggedCellOrientation==="row"?e.state.rowIndex:e.state.colIndex;if(r===void 0)return;const s=[],{block:i,draggingState:a}=e.state,{originalIndex:c,draggedCellOrientation:l}=a;if(r===c||!i||l==="row"&&!k.canRowBeDraggedInto(i,c,r)||l==="col"&&!k.canColumnBeDraggedInto(i,c,r))return D.DecorationSet.create(o.doc,s);const u=o.doc.resolve(e.tablePos+1);return e.state.draggingState.draggedCellOrientation==="row"?k.getCellsAtRowHandle(e.state.block,r).forEach(({row:g,col:m})=>{const p=o.doc.resolve(u.posAtIndex(g)+1),d=o.doc.resolve(p.posAtIndex(m)+1),f=d.node(),y=d.pos+(r>c?f.nodeSize-2:0);s.push(D.Decoration.widget(y,()=>{const w=document.createElement("div");return w.className="bn-table-drop-cursor",w.style.left="0",w.style.right="0",r>c?w.style.bottom="-2px":w.style.top="-3px",w.style.height="4px",w}))}):k.getCellsAtColumnHandle(e.state.block,r).forEach(({row:g,col:m})=>{const p=o.doc.resolve(u.posAtIndex(g)+1),d=o.doc.resolve(p.posAtIndex(m)+1),f=d.node(),y=d.pos+(r>c?f.nodeSize-2:0);s.push(D.Decoration.widget(y,()=>{const w=document.createElement("div");return w.className="bn-table-drop-cursor",w.style.top="0",w.style.bottom="0",r>c?w.style.right="-2px":w.style.left="-3px",w.style.width="4px",w}))}),D.DecorationSet.create(o.doc,s)}}})],colDragStart(o){if(e===void 0||e.state===void 0||e.state.colIndex===void 0)throw new Error("Attempted to drag table column, but no table block was hovered prior.");e.state.draggingState={draggedCellOrientation:"col",originalIndex:e.state.colIndex,mousePos:o.clientX},e.emitUpdate(),n.transact(r=>r.setMeta(N,{draggedCellOrientation:e.state.draggingState.draggedCellOrientation,originalIndex:e.state.colIndex,newIndex:e.state.colIndex,tablePos:e.tablePos})),!n.headless&&(se(n.prosemirrorView.root),o.dataTransfer.setDragImage(E,0,0),o.dataTransfer.effectAllowed="move")},rowDragStart(o){if(e.state===void 0||e.state.rowIndex===void 0)throw new Error("Attempted to drag table row, but no table block was hovered prior.");e.state.draggingState={draggedCellOrientation:"row",originalIndex:e.state.rowIndex,mousePos:o.clientY},e.emitUpdate(),n.transact(r=>r.setMeta(N,{draggedCellOrientation:e.state.draggingState.draggedCellOrientation,originalIndex:e.state.rowIndex,newIndex:e.state.rowIndex,tablePos:e.tablePos})),!n.headless&&(se(n.prosemirrorView.root),o.dataTransfer.setDragImage(E,0,0),o.dataTransfer.effectAllowed="copyMove")},dragEnd(){if(e.state===void 0)throw new Error("Attempted to drag table row, but no table block was hovered prior.");e.state.draggingState=void 0,e.emitUpdate(),n.transact(o=>o.setMeta(N,null)),!n.headless&&ft(n.prosemirrorView.root)},freezeHandles(){e.menuFrozen=!0},unfreezeHandles(){e.menuFrozen=!1},getCellsAtRowHandle(o,r){return k.getCellsAtRowHandle(o,r)},getCellsAtColumnHandle(o,r){return k.getCellsAtColumnHandle(o,r)},setCellSelection(o,r,s=r){if(!e)throw new Error("Table handles view not initialized");const i=o.doc.resolve(e.tablePos+1),a=o.doc.resolve(i.posAtIndex(r.row)+1),c=o.doc.resolve(a.posAtIndex(r.col)),l=o.doc.resolve(i.posAtIndex(s.row)+1),u=o.doc.resolve(l.posAtIndex(s.col)),h=o.tr;return h.setSelection(new T.CellSelection(c,u)),o.apply(h)},addRowOrColumn(o,r){n.exec((s,i)=>{const a=this.setCellSelection(s,r.orientation==="row"?{row:o,col:0}:{row:0,col:o});return r.orientation==="row"?r.side==="above"?T.addRowBefore(a,i):T.addRowAfter(a,i):r.side==="left"?T.addColumnBefore(a,i):T.addColumnAfter(a,i)})},removeRowOrColumn(o,r){return r==="row"?n.exec((s,i)=>{const a=this.setCellSelection(s,{row:o,col:0});return T.deleteRow(a,i)}):n.exec((s,i)=>{const a=this.setCellSelection(s,{row:0,col:o});return T.deleteColumn(a,i)})},mergeCells(o){return n.exec((r,s)=>{const i=o?this.setCellSelection(r,o.relativeStartCell,o.relativeEndCell):r;return T.mergeCells(i,s)})},splitCell(o){return n.exec((r,s)=>{const i=o?this.setCellSelection(r,o):r;return T.splitCell(i,s)})},getCellSelection(){return n.transact(o=>{const r=o.selection;let s=r.$from,i=r.$to;if(O.isTableCellSelection(r)){const{ranges:d}=r;d.forEach(f=>{s=f.$from.min(s??f.$from),i=f.$to.max(i??f.$to)})}else if(s=o.doc.resolve(r.$from.pos-r.$from.parentOffset-1),i=o.doc.resolve(r.$to.pos-r.$to.parentOffset-1),s.pos===0||i.pos===0)return;const a=o.doc.resolve(s.pos-s.parentOffset-1),c=o.doc.resolve(i.pos-i.parentOffset-1),l=o.doc.resolve(a.pos-a.parentOffset-1),u=s.index(a.depth),h=a.index(l.depth),g=i.index(c.depth),m=c.index(l.depth),p=[];for(let d=h;d<=m;d++)for(let f=u;f<=g;f++)p.push({row:d,col:f});return{from:{row:h,col:u},to:{row:m,col:g},cells:p}})},getMergeDirection(o){return n.transact(r=>{const s=O.isTableCellSelection(r.selection)?r.selection:void 0;if(!s||!o||s.ranges.length<=1)return;const i=this.getCellSelection();if(i)return k.areInSameColumn(i.from,i.to,o)?"vertical":"horizontal"})},cropEmptyRowsOrColumns(o,r){return k.cropEmptyRowsOrColumns(o,r)},addRowsOrColumns(o,r,s){return k.addRowsOrColumns(o,r,s)}}}),ie=new C.PluginKey("trailingNode"),bt=v.createExtension(()=>({key:"trailingNode",prosemirrorPlugins:[new C.Plugin({key:ie,appendTransaction:(n,e,t)=>{const{doc:o,tr:r,schema:s}=t,i=ie.getState(t),a=o.content.size-2,c=s.nodes.blockContainer,l=s.nodes.paragraph;if(i)return r.insert(a,c.create(void 0,l.create()))},state:{init:(n,e)=>{},apply:(n,e)=>{if(!n.docChanged)return e;let t=n.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 o=t.firstChild;if(!o)throw new Error("Expected blockContent");return t.nodeSize>4||o.type.spec.content!=="inline*"}}})]}));exports.BlockChangeExtension=$e;exports.DEFAULT_LINK_PROTOCOL=et;exports.DropCursorExtension=We;exports.ForkYDocExtension=Ke;exports.FormattingToolbarExtension=Ge;exports.HistoryExtension=Je;exports.LinkToolbarExtension=Qe;exports.NodeSelectionKeyboardExtension=ot;exports.PlaceholderExtension=rt;exports.PreviousBlockTypeExtension=it;exports.SchemaMigration=Xe;exports.SideMenuExtension=pt;exports.SideMenuView=fe;exports.TableHandlesExtension=wt;exports.TableHandlesView=ye;exports.TrailingNodeExtension=bt;exports.VALID_LINK_PROTOCOLS=Ze;exports.YCursorExtension=z;exports.YSyncExtension=U;exports.YUndoExtension=$;exports.blocksToMarkdown=dt;exports.cleanHTMLToMarkdown=j;exports.createExternalHTMLExporter=Y;exports.fragmentToBlocks=me;exports.getBlocksChangedByTransaction=de;exports.sideMenuPluginKey=ge;exports.tableHandlesPluginKey=N;
+"use strict";var we=Object.defineProperty;var be=(n,e,t)=>e in n?we(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var b=(n,e,t)=>be(n,typeof e!="symbol"?e+"":e,t);const C=require("prosemirror-state"),R=require("@tiptap/core"),ke=require("fast-deep-equal"),k=require("./blockToNode-CumVjgem.cjs"),O=require("./defaultBlocks-DosClM5E.cjs"),v=require("./BlockNoteExtension-BWw0r8Gy.cjs"),M=require("y-prosemirror"),Ce=require("yjs"),V=require("@tiptap/pm/state"),ve=require("prosemirror-dropcursor"),q=require("@tiptap/pm/history"),D=require("prosemirror-view"),Se=require("uuid"),Z=require("@tiptap/pm/model"),H=require("prosemirror-model"),xe=require("rehype-parse"),Ee=require("rehype-remark"),Ie=require("remark-gfm"),Pe=require("remark-stringify"),Te=require("unified"),Be=require("hast-util-from-dom"),De=require("unist-util-visit"),T=require("prosemirror-tables"),F=n=>n&&typeof n=="object"&&"default"in n?n:{default:n};function Oe(n){if(n&&typeof n=="object"&&"default"in n)return n;const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const t in n)if(t!=="default"){const o=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,o.get?o:{enumerable:!0,get:()=>n[t]})}}return e.default=n,Object.freeze(e)}const Me=F(ke),B=Oe(Ce),Ae=F(xe),Ne=F(Ee),Le=F(Ie),Re=F(Pe);function ae(n){const e=Array.from(n.classList).filter(t=>!t.startsWith("bn-"))||[];e.length>0?n.className=e.join(" "):n.removeAttribute("class")}function le(n,e,t,o){var a;let r;if(e)if(typeof e=="string")r=k.inlineContentToNodes([e],n.pmSchema);else if(Array.isArray(e))r=k.inlineContentToNodes(e,n.pmSchema);else if(e.type==="tableContent")r=k.tableContentToNodes(e,n.pmSchema);else throw new k.UnreachableCaseError(e.type);else throw new Error("blockContent is required");const i=((o==null?void 0:o.document)??document).createDocumentFragment();for(const c of r)if(c.type.name!=="text"&&n.schema.inlineContentSchema[c.type.name]){const l=n.schema.inlineContentSpecs[c.type.name].implementation;if(l){const u=k.nodeToCustomInlineContent(c,n.schema.inlineContentSchema,n.schema.styleSchema),h=l.toExternalHTML?l.toExternalHTML(u,n):l.render.call({renderType:"dom",props:void 0},u,()=>{},n);if(h){if(i.appendChild(h.dom),h.contentDOM){const g=t.serializeFragment(c.content,o);h.contentDOM.dataset.editable="",h.contentDOM.appendChild(g)}continue}}}else if(c.type.name==="text"){let l=document.createTextNode(c.textContent);for(const u of Array.from(c.marks).reverse())if(u.type.name in n.schema.styleSpecs){const h=(n.schema.styleSpecs[u.type.name].implementation.toExternalHTML??n.schema.styleSpecs[u.type.name].implementation.render)(u.attrs.stringValue,n);h.contentDOM.appendChild(l),l=h.dom}else{const h=u.type.spec.toDOM(u,!0),g=H.DOMSerializer.renderSpec(document,h);g.contentDOM.appendChild(l),l=g.dom}i.appendChild(l)}else{const l=t.serializeFragment(H.Fragment.from([c]),o);i.appendChild(l)}return i.childNodes.length===1&&((a=i.firstChild)==null?void 0:a.nodeType)===1&&ae(i.firstChild),i}function Ve(n,e,t,o,r,s,i,a){var y,w,x,L,X,W,G,J,Q;const c=(a==null?void 0:a.document)??document,l=e.pmSchema.nodes.blockContainer,u=t.props||{};for(const[S,I]of Object.entries(e.schema.blockSchema[t.type].propSchema))!(S in u)&&I.default!==void 0&&(u[S]=I.default);const h=(w=(y=l.spec)==null?void 0:y.toDOM)==null?void 0:w.call(y,l.create({id:t.id,...u})),g=Array.from(h.dom.attributes),m=e.blockImplementations[t.type].implementation,p=((x=m.toExternalHTML)==null?void 0:x.call({},{...t,props:u},e,{nestingLevel:i}))||m.render.call({},{...t,props:u},e),d=c.createDocumentFragment();if(p.dom.classList.contains("bn-block-content")){const S=[...g,...Array.from(p.dom.attributes)].filter(I=>I.name.startsWith("data")&&I.name!=="data-content-type"&&I.name!=="data-file-block"&&I.name!=="data-node-view-wrapper"&&I.name!=="data-node-type"&&I.name!=="data-id"&&I.name!=="data-editable");for(const I of S)p.dom.firstChild.setAttribute(I.name,I.value);ae(p.dom.firstChild),i>0&&p.dom.firstChild.setAttribute("data-nesting-level",i.toString()),d.append(...Array.from(p.dom.childNodes))}else d.append(p.dom),i>0&&p.dom.setAttribute("data-nesting-level",i.toString());if(p.contentDOM&&t.content){const S=le(e,t.content,o,a);p.contentDOM.appendChild(S)}let f;if(r.has(t.type)?f="OL":s.has(t.type)&&(f="UL"),f){if(((L=n.lastChild)==null?void 0:L.nodeName)!==f){const S=c.createElement(f);f==="OL"&&"start"in u&&u.start&&(u==null?void 0:u.start)!==1&&S.setAttribute("start",u.start+""),n.append(S)}n.lastChild.appendChild(d)}else n.append(d);if(t.children&&t.children.length>0){const S=c.createDocumentFragment();if(ce(S,e,t.children,o,r,s,i+1,a),((X=n.lastChild)==null?void 0:X.nodeName)==="UL"||((W=n.lastChild)==null?void 0:W.nodeName)==="OL")for(;((G=S.firstChild)==null?void 0:G.nodeName)==="UL"||((J=S.firstChild)==null?void 0:J.nodeName)==="OL";)n.lastChild.lastChild.appendChild(S.firstChild);e.pmSchema.nodes[t.type].isInGroup("blockContent")?n.append(S):(Q=p.contentDOM)==null||Q.append(S)}}const ce=(n,e,t,o,r,s,i=0,a)=>{for(const c of t)Ve(n,e,c,o,r,s,i,a)},He=(n,e,t,o,r,s)=>{const a=((s==null?void 0:s.document)??document).createDocumentFragment();return ce(a,n,e,t,o,r,0,s),a},Y=(n,e)=>{const t=H.DOMSerializer.fromSchema(n);return{exportBlocks:(o,r)=>{const s=He(e,o,t,new Set(["numberedListItem"]),new Set(["bulletListItem","checkListItem","toggleListItem"]),r),i=document.createElement("div");return i.append(s),i.innerHTML},exportInlineContent:(o,r)=>{const s=le(e,o,t,r),i=document.createElement("div");return i.append(s.cloneNode(!0)),i.innerHTML}}};function Fe(n,e){if(e===0)return;const t=n.resolve(e);for(let o=t.depth;o>0;o--){const r=t.node(o);if(O.isNodeBlock(r))return r.attrs.id}}function _e(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 ee(n){const e="__root__",t={},o={},r=k.getPmSchema(n);return n.descendants((s,i)=>{if(!O.isNodeBlock(s))return!0;const a=Fe(n,i),c=a??e;o[c]||(o[c]=[]);const l=k.nodeToBlock(s,r);return t[s.attrs.id]={block:l,parentId:a},o[c].push(s.attrs.id),!0}),{byId:t,childrenByParent:o}}function Ue(n,e){const t=new Set;if(!n||!e)return t;const o=new Set(n),r=e.filter(d=>o.has(d)),s=n.filter(d=>r.includes(d));if(s.length<=1||r.length<=1)return t;const i={};for(let d=0;d<s.length;d++)i[s[d]]=d;const a=r.map(d=>i[d]),c=a.length,l=[],u=[],h=new Array(c).fill(-1),g=(d,f)=>{let y=0,w=d.length;for(;y<w;){const x=y+w>>>1;d[x]<f?y=x+1:w=x}return y};for(let d=0;d<c;d++){const f=a[d],y=g(l,f);y>0&&(h[d]=u[y-1]),y===l.length?(l.push(f),u.push(d)):(l[y]=f,u[y]=d)}const m=new Set;let p=u[u.length-1]??-1;for(;p!==-1;)m.add(p),p=h[p];for(let d=0;d<r.length;d++)m.has(d)||t.add(r[d]);return t}function de(n,e=[]){const t=_e(n),o=R.combineTransactionSteps(n.before,[n,...e]),r=ee(o.before),s=ee(o.doc),i=[],a=new Set;Object.keys(s.byId).filter(m=>!(m in r.byId)).forEach(m=>{i.push({type:"insert",block:s.byId[m].block,source:t,prevBlock:void 0}),a.add(m)}),Object.keys(r.byId).filter(m=>!(m in s.byId)).forEach(m=>{i.push({type:"delete",block:r.byId[m].block,source:t,prevBlock:void 0}),a.add(m)}),Object.keys(s.byId).filter(m=>m in r.byId).forEach(m=>{var y,w;const p=r.byId[m],d=s.byId[m];p.parentId!==d.parentId?(i.push({type:"move",block:d.block,prevBlock:p.block,source:t,prevParent:p.parentId?(y=r.byId[p.parentId])==null?void 0:y.block:void 0,currentParent:d.parentId?(w=s.byId[d.parentId])==null?void 0:w.block:void 0}),a.add(m)):Me.default({...p.block,children:void 0},{...d.block,children:void 0})||(i.push({type:"update",block:d.block,prevBlock:p.block,source:t}),a.add(m))});const c=r.childrenByParent,l=s.childrenByParent,u="__root__",h=new Set([...Object.keys(c),...Object.keys(l)]),g=new Set;return h.forEach(m=>{const p=Ue(c[m],l[m]);p.size!==0&&p.forEach(d=>{var x,L;const f=r.byId[d],y=s.byId[d];!f||!y||f.parentId!==y.parentId||a.has(d)||(f.parentId??u)!==m||g.has(d)||(g.add(d),i.push({type:"move",block:y.block,prevBlock:f.block,source:t,prevParent:f.parentId?(x=r.byId[f.parentId])==null?void 0:x.block:void 0,currentParent:y.parentId?(L=s.byId[y.parentId])==null?void 0:L.block:void 0}),a.add(d))})}),i}const $e=v.createExtension(()=>{const n=[];return{key:"blockChange",prosemirrorPlugins:[new C.Plugin({key:new C.PluginKey("blockChange"),filterTransaction:e=>{let t;return n.reduce((o,r)=>o===!1?o:r({getChanges(){return t||(t=de(e),t)},tr:e})!==!1,!0)}})],subscribe(e){return n.push(e),()=>{n.splice(n.indexOf(e),1)}}}});function te(n){const e=n.charAt(0)==="#"?n.substring(1,7):n,t=parseInt(e.substring(0,2),16),o=parseInt(e.substring(2,4),16),r=parseInt(e.substring(4,6),16),i=[t/255,o/255,r/255].map(c=>c<=.03928?c/12.92:Math.pow((c+.055)/1.055,2.4));return .2126*i[0]+.7152*i[1]+.0722*i[2]<=.179}function qe(n){const e=document.createElement("span");e.classList.add("bn-collaboration-cursor__base");const t=document.createElement("span");t.setAttribute("contentedEditable","false"),t.classList.add("bn-collaboration-cursor__caret"),t.setAttribute("style",`background-color: ${n.color}; color: ${te(n.color)?"white":"black"}`);const o=document.createElement("span");return o.classList.add("bn-collaboration-cursor__label"),o.setAttribute("style",`background-color: ${n.color}; color: ${te(n.color)?"white":"black"}`),o.insertBefore(document.createTextNode(n.name),null),t.insertBefore(o,null),e.insertBefore(document.createTextNode(""),null),e.insertBefore(t,null),e.insertBefore(document.createTextNode(""),null),e}const z=v.createExtension(({options:n})=>{const e=new Map,t=n.provider&&"awareness"in n.provider&&typeof n.provider.awareness=="object"?n.provider.awareness:void 0;return t&&("setLocalStateField"in t&&typeof t.setLocalStateField=="function"&&t.setLocalStateField("user",n.user),"on"in t&&typeof t.on=="function"&&n.showCursorLabels!=="always"&&t.on("change",({updated:o})=>{for(const r of o){const s=e.get(r);s&&(s.element.setAttribute("data-active",""),s.hideTimeout&&clearTimeout(s.hideTimeout),e.set(r,{element:s.element,hideTimeout:setTimeout(()=>{s.element.removeAttribute("data-active")},2e3)}))}})),{key:"yCursor",prosemirrorPlugins:[t?M.yCursorPlugin(t,{selectionBuilder:M.defaultSelectionBuilder,cursorBuilder(o,r){let s=e.get(r);if(!s){const i=(n.renderCursor??qe)(o);n.showCursorLabels!=="always"&&(i.addEventListener("mouseenter",()=>{const a=e.get(r);a.element.setAttribute("data-active",""),a.hideTimeout&&(clearTimeout(a.hideTimeout),e.set(r,{element:a.element,hideTimeout:void 0}))}),i.addEventListener("mouseleave",()=>{const a=e.get(r);e.set(r,{element:a.element,hideTimeout:setTimeout(()=>{a.element.removeAttribute("data-active")},2e3)})})),s={element:i,hideTimeout:void 0},e.set(r,s)}return s.element}}):void 0].filter(Boolean),dependsOn:["ySync"],updateUser(o){t==null||t.setLocalStateField("user",o)}}}),U=v.createExtension(({options:n})=>({key:"ySync",prosemirrorPlugins:[M.ySyncPlugin(n.fragment)],runsBefore:["default"]})),$=v.createExtension(()=>({key:"yUndo",prosemirrorPlugins:[M.yUndoPlugin()],dependsOn:["yCursor","ySync"],undoCommand:M.undoCommand,redoCommand:M.redoCommand}));function ze(n,e){const t=n.doc;if(n._item===null){const o=Array.from(t.share.keys()).find(r=>t.share.get(r)===n);if(o==null)throw new Error("type does not exist in other ydoc");return e.get(o,n.constructor)}else{const o=n._item,r=e.store.clients.get(o.id.client)??[],s=B.findIndexSS(r,o.id.clock);return r[s].content.type}}const Ke=v.createExtension(({editor:n,options:e})=>{let t;const o=v.createStore({isForked:!1});return{key:"yForkDoc",store:o,fork(){if(t)return;const r=e.fragment;if(!r)throw new Error("No fragment to fork from");const s=new B.Doc;B.applyUpdate(s,B.encodeStateAsUpdate(r.doc));const i=ze(r,s);t={undoStack:M.yUndoPluginKey.getState(n.prosemirrorState).undoManager.undoStack,originalFragment:r,forkedFragment:i},n.unregisterExtension([$,z,U]);const a={...e,fragment:i};n.registerExtension([U(a),$()]),o.setState({isForked:!0})},merge({keepChanges:r}){if(!t)return;n.unregisterExtension(["ySync","yCursor","yUndo"]);const{originalFragment:s,forkedFragment:i,undoStack:a}=t;if(n.registerExtension([U(e),z(e),$()]),M.yUndoPluginKey.getState(n.prosemirrorState).undoManager.undoStack=a,r){const c=B.encodeStateAsUpdate(i.doc,B.encodeStateVector(s.doc));B.applyUpdate(s.doc,c,n)}t=void 0,o.setState({isForked:!1})}}}),ue=(n,e)=>{e(n),n.forEach(t=>{t instanceof B.XmlElement&&ue(t,e)})},Ye=(n,e)=>{const t=new Map;return n.forEach(o=>{o instanceof B.XmlElement&&ue(o,r=>{if(r.nodeName==="blockContainer"&&r.hasAttribute("id")){const s=r.getAttribute("textColor"),i=r.getAttribute("backgroundColor"),a={textColor:s===O.defaultProps.textColor.default?void 0:s,backgroundColor:i===O.defaultProps.backgroundColor.default?void 0:i};(a.textColor||a.backgroundColor)&&t.set(r.getAttribute("id"),a)}})}),t.size===0?!1:(e.doc.descendants((o,r)=>{if(o.type.name==="blockContainer"&&t.has(o.attrs.id)){const s=e.doc.nodeAt(r+1);if(!s)throw new Error("No element found");e.setNodeMarkup(r+1,void 0,{...s.attrs,...t.get(o.attrs.id)})}}),!0)},je=[Ye],Xe=v.createExtension(({options:n})=>{let e=!1;const t=new V.PluginKey("schemaMigration");return{key:"schemaMigration",prosemirrorPlugins:[new V.Plugin({key:t,appendTransaction:(o,r,s)=>{if(e||!o.some(a=>a.getMeta("y-sync$"))||o.every(a=>!a.docChanged)||!n.fragment.firstChild)return;const i=s.tr;for(const a of je)a(n.fragment,i);if(e=!0,!!i.docChanged)return i}})]}}),We=v.createExtension(({editor:n,options:e})=>({key:"dropCursor",prosemirrorPlugins:[(e.dropCursor??ve.dropCursor)({width:5,color:"#ddeeff",editor:n})]})),Ge=v.createExtension(({editor:n})=>{const e=v.createStore(!1),t=()=>n.transact(o=>{var s;if(o.selection.empty||o.selection instanceof C.NodeSelection&&(o.selection.node.type.spec.content==="inline*"||((s=o.selection.node.firstChild)==null?void 0:s.type.spec.content)==="inline*")||o.selection instanceof C.TextSelection&&o.doc.textBetween(o.selection.from,o.selection.to).length===0)return!1;let r=!1;return o.selection.content().content.descendants(i=>(i.type.spec.code&&(r=!0),!r)),!r});return{key:"formattingToolbar",store:e,mount({dom:o,signal:r}){let s=!1;const i=n.onChange(()=>{s||e.setState(t())}),a=n.onSelectionChange(()=>{s||e.setState(t())});o.addEventListener("pointerdown",()=>{s=!0,e.setState(!1)},{signal:r}),n.prosemirrorView.root.addEventListener("pointerup",()=>{s=!1,n.isFocused()&&e.setState(t())},{signal:r,capture:!0}),o.addEventListener("pointercancel",()=>{s=!1},{signal:r,capture:!0}),r.addEventListener("abort",()=>{i(),a()})}}}),Je=v.createExtension(()=>({key:"history",prosemirrorPlugins:[q.history()],undoCommand:q.undo,redoCommand:q.redo})),Qe=v.createExtension(({editor:n})=>{function e(r){let s=n.prosemirrorView.nodeDOM(r);for(;s&&s.parentElement;){if(s.nodeName==="A")return s;s=s.parentElement}return null}function t(r,s){return n.transact(i=>{const a=i.doc.resolve(r),c=a.marks().find(u=>u.type.name===s);if(!c)return;const l=R.getMarkRange(a,c.type);if(l)return{range:l,mark:c,get text(){return i.doc.textBetween(l.from,l.to)},get position(){return R.posToDOMRect(n.prosemirrorView,l.from,l.to).toJSON()}}})}function o(){return n.transact(r=>{const s=r.selection;if(s.empty)return t(s.anchor,"link")})}return{key:"linkToolbar",getLinkAtSelection:o,getLinkElementAtPos:e,getMarkAtPos:t,getLinkAtElement(r){return n.transact(()=>{const s=n.prosemirrorView.posAtDOM(r,0)+1;return t(s,"link")})},editLink(r,s,i=n.transact(a=>a.selection.anchor)){n.transact(a=>{const c=k.getPmSchema(a),{range:l}=t(i+1,"link")||{range:{from:a.selection.from,to:a.selection.to}};l&&(a.insertText(s,l.from,l.to),a.addMark(l.from,l.from+s.length,c.mark("link",{href:r})))}),n.prosemirrorView.focus()},deleteLink(r=n.transact(s=>s.selection.anchor)){n.transact(s=>{const i=k.getPmSchema(s),{range:a}=t(r+1,"link")||{range:{from:s.selection.from,to:s.selection.to}};a&&s.removeMark(a.from,a.to,i.marks.link).setMeta("preventAutolink",!0)}),n.prosemirrorView.focus()}}}),Ze=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"],et="https",tt=new C.PluginKey("node-selection-keyboard"),ot=v.createExtension(()=>({key:"nodeSelectionKeyboard",prosemirrorPlugins:[new C.Plugin({key:tt,props:{handleKeyDown:(n,e)=>{if("node"in n.state.selection){if(e.ctrlKey||e.metaKey)return!1;if(e.key.length===1)return e.preventDefault(),!0;if(e.key==="Enter"&&!e.isComposing&&!e.shiftKey&&!e.altKey&&!e.ctrlKey&&!e.metaKey){const t=n.state.tr;return n.dispatch(t.insert(n.state.tr.selection.$to.after(),n.state.schema.nodes.paragraph.createChecked()).setSelection(new C.TextSelection(t.doc.resolve(n.state.tr.selection.$to.after()+1)))),!0}}return!1}}})]})),nt=new C.PluginKey("blocknote-placeholder"),rt=v.createExtension(({editor:n,options:e})=>{const t=e.placeholders;return{key:"placeholder",prosemirrorPlugins:[new C.Plugin({key:nt,view:o=>{const r=`placeholder-selector-${Se.v4()}`;o.dom.classList.add(r);const s=document.createElement("style"),i=n._tiptapEditor.options.injectNonce;i&&s.setAttribute("nonce",i),o.root instanceof window.ShadowRoot?o.root.append(s):o.root.head.appendChild(s);const a=s.sheet,c=(l="")=>`.${r} .bn-block-content${l} .bn-inline-content:has(> .ProseMirror-trailingBreak:only-child):before`;try{const{default:l,emptyDocument:u,...h}=t||{};for(const[p,d]of Object.entries(h)){const f=`[data-content-type="${p}"]`;a.insertRule(`${c(f)} { content: ${JSON.stringify(d)}; }`)}const g="[data-is-only-empty-block]",m="[data-is-empty-and-focused]";a.insertRule(`${c(g)} { content: ${JSON.stringify(u)}; }`),a.insertRule(`${c(m)} { content: ${JSON.stringify(l)}; }`)}catch(l){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)",l)}return{destroy:()=>{o.root instanceof window.ShadowRoot?o.root.removeChild(s):o.root.head.removeChild(s)}}},props:{decorations:o=>{const{doc:r,selection:s}=o;if(!n.isEditable||!s.empty||s.$from.parent.type.spec.code)return;const i=[];o.doc.content.size===6&&i.push(D.Decoration.node(2,4,{"data-is-only-empty-block":"true"}));const a=s.$anchor,c=a.parent;if(c.content.size===0){const l=a.before();i.push(D.Decoration.node(l,l+c.nodeSize,{"data-is-empty-and-focused":"true"}))}return D.DecorationSet.create(r,i)}}})]}}),oe=new C.PluginKey("previous-blocks"),st={index:"index",level:"level",type:"type",depth:"depth","depth-change":"depth-change"},it=v.createExtension(()=>{let n;return{key:"previousBlockType",prosemirrorPlugins:[new C.Plugin({key:oe,view(e){return{update:async(t,o)=>{var r;((r=this.key)==null?void 0:r.getState(t.state).updatedBlocks.size)>0&&(n=setTimeout(()=>{t.dispatch(t.state.tr.setMeta(oe,{clearUpdate:!0}))},0))},destroy:()=>{n&&clearTimeout(n)}}},state:{init(){return{prevTransactionOldBlockAttrs:{},currentTransactionOldBlockAttrs:{},updatedBlocks:new Set}},apply(e,t,o,r){if(t.currentTransactionOldBlockAttrs={},t.updatedBlocks.clear(),!e.docChanged||o.doc.eq(r.doc))return t;const s={},i=R.findChildren(o.doc,l=>l.attrs.id),a=new Map(i.map(l=>[l.node.attrs.id,l])),c=R.findChildren(r.doc,l=>l.attrs.id);for(const l of c){const u=a.get(l.node.attrs.id),h=u==null?void 0:u.node.firstChild,g=l.node.firstChild;if(u&&h&&g){const m={index:g.attrs.index,level:g.attrs.level,type:g.type.name,depth:r.doc.resolve(l.pos).depth},p={index:h.attrs.index,level:h.attrs.level,type:h.type.name,depth:o.doc.resolve(u.pos).depth};s[l.node.attrs.id]=p,t.currentTransactionOldBlockAttrs[l.node.attrs.id]=p,JSON.stringify(p)!==JSON.stringify(m)&&(p["depth-change"]=p.depth-m.depth,t.updatedBlocks.add(l.node.attrs.id))}}return t.prevTransactionOldBlockAttrs=s,t}},props:{decorations(e){const t=this.getState(e);if(t.updatedBlocks.size===0)return;const o=[];return e.doc.descendants((r,s)=>{if(!r.attrs.id||!t.updatedBlocks.has(r.attrs.id))return;const i=t.currentTransactionOldBlockAttrs[r.attrs.id],a={};for(const[l,u]of Object.entries(i))a["data-prev-"+st[l]]=u||"none";const c=D.Decoration.node(s,s+r.nodeSize,{...a});o.push(c)}),D.DecorationSet.create(e.doc,o)}}})]}});function he(n,e){var t,o;for(;n&&n.parentElement&&n.parentElement!==e.dom&&((t=n.getAttribute)==null?void 0:t.call(n,"data-node-type"))!=="blockContainer";)n=n.parentElement;if(((o=n.getAttribute)==null?void 0:o.call(n,"data-node-type"))==="blockContainer")return{node:n,id:n.getAttribute("data-id")}}function at(){const n=e=>{let t=e.children.length;for(let o=0;o<t;o++){const r=e.children[o];if(r.type==="element"&&(n(r),r.tagName==="u"))if(r.children.length>0){e.children.splice(o,1,...r.children);const s=r.children.length-1;t+=s,o+=s}else e.children.splice(o,1),t--,o--}};return n}function lt(){const n=e=>{var t;if(e.children&&"length"in e.children&&e.children.length)for(let o=e.children.length-1;o>=0;o--){const r=e.children[o],s=o+1<e.children.length?e.children[o+1]:void 0;r.type==="element"&&r.tagName==="input"&&((t=r.properties)==null?void 0:t.type)==="checkbox"&&(s==null?void 0:s.type)==="element"&&s.tagName==="p"?(s.tagName="span",s.children.splice(0,0,Be.fromDom(document.createTextNode(" ")))):n(r)}};return n}function ct(){return n=>{De.visit(n,"element",(e,t,o)=>{var r,s,i,a;if(o&&e.tagName==="video"){const c=((r=e.properties)==null?void 0:r.src)||((s=e.properties)==null?void 0:s["data-url"])||"",l=((i=e.properties)==null?void 0:i.title)||((a=e.properties)==null?void 0:a["data-name"])||"";o.children[t]={type:"text",value:`![${l}](${c})`}}})}}function j(n){return Te.unified().use(Ae.default,{fragment:!0}).use(ct).use(at).use(lt).use(Ne.default).use(Le.default).use(Re.default,{handlers:{text:t=>t.value}}).processSync(n).value}function dt(n,e,t,o){const s=Y(e,t).exportBlocks(n,o);return j(s)}function me(n){const e=[];return n.descendants(t=>{var r,s;const o=k.getPmSchema(t);return t.type.name==="blockContainer"&&((r=t.firstChild)==null?void 0:r.type.name)==="blockGroup"?!0:t.type.name==="columnList"&&t.childCount===1?((s=t.firstChild)==null||s.forEach(i=>{e.push(k.nodeToBlock(i,o))}),!1):t.type.isInGroup("bnBlock")?(e.push(k.nodeToBlock(t,o)),!1):!0}),e}class A extends C.Selection{constructor(t,o){super(t,o);b(this,"nodes");const r=t.node();this.nodes=[],t.doc.nodesBetween(t.pos,o.pos,(s,i,a)=>{if(a!==null&&a.eq(r))return this.nodes.push(s),!1})}static create(t,o,r=o){return new A(t.resolve(o),t.resolve(r))}content(){return new H.Slice(H.Fragment.from(this.nodes),0,0)}eq(t){if(!(t instanceof A)||this.nodes.length!==t.nodes.length||this.from!==t.from||this.to!==t.to)return!1;for(let o=0;o<this.nodes.length;o++)if(!this.nodes[o].eq(t.nodes[o]))return!1;return!0}map(t,o){const r=o.mapResult(this.from),s=o.mapResult(this.to);return s.deleted?C.Selection.near(t.resolve(r.pos)):r.deleted?C.Selection.near(t.resolve(s.pos)):new A(t.resolve(r.pos),t.resolve(s.pos))}toJSON(){return{type:"multiple-node",anchor:this.anchor,head:this.head}}}C.Selection.jsonID("multiple-node",A);let P;function ut(n,e){let t,o;const r=e.resolve(n.from).node().type.spec.group==="blockContent",s=e.resolve(n.to).node().type.spec.group==="blockContent",i=Math.min(n.$anchor.depth,n.$head.depth);if(r&&s){const a=n.$from.start(i-1),c=n.$to.end(i-1);t=e.resolve(a-1).pos,o=e.resolve(c+1).pos}else t=n.from,o=n.to;return{from:t,to:o}}function ne(n,e,t=e){e===t&&(t+=n.state.doc.resolve(e+1).node().nodeSize);const o=n.domAtPos(e).node.cloneNode(!0),r=n.domAtPos(e).node,s=(h,g)=>Array.prototype.indexOf.call(h.children,g),i=s(r,n.domAtPos(e+1).node.parentElement),a=s(r,n.domAtPos(t-1).node.parentElement);for(let h=r.childElementCount-1;h>=0;h--)(h>a||h<i)&&o.removeChild(o.children[h]);pe(n.root),P=o;const c=P.getElementsByTagName("iframe");for(let h=0;h<c.length;h++){const g=c[h],m=g.parentElement;m&&m.removeChild(g)}const u=n.dom.className.split(" ").filter(h=>h!=="ProseMirror"&&h!=="bn-root"&&h!=="bn-editor").join(" ");P.className=P.className+" bn-drag-preview "+u,n.root instanceof ShadowRoot?n.root.appendChild(P):n.root.body.appendChild(P)}function pe(n){P!==void 0&&(n instanceof ShadowRoot?n.removeChild(P):n.body.removeChild(P),P=void 0)}function ht(n,e,t){if(!n.dataTransfer||t.headless)return;const o=t.prosemirrorView,r=O.getNodeById(e.id,o.state.doc);if(!r)throw new Error(`Block with ID ${e.id} not found`);const s=r.posBeforeNode;if(s!=null){const i=o.state.selection,a=o.state.doc,{from:c,to:l}=ut(i,a),u=c<=s&&s<l,h=i.$anchor.node()!==i.$head.node()||i instanceof A;u&&h?(o.dispatch(o.state.tr.setSelection(A.create(a,c,l))),ne(o,c,l)):(o.dispatch(o.state.tr.setSelection(C.NodeSelection.create(o.state.doc,s))),ne(o,s));const g=o.state.selection.content(),m=t.pmSchema,p=o.serializeForClipboard(g).dom.innerHTML,d=Y(m,t),f=me(g.content),y=d.exportBlocks(f,{}),w=j(y);n.dataTransfer.clearData(),n.dataTransfer.setData("blocknote/html",p),n.dataTransfer.setData("text/html",y),n.dataTransfer.setData("text/plain",w),n.dataTransfer.effectAllowed="move",n.dataTransfer.setDragImage(P,0,0)}}const re=250;function K(n,e,t=!0){const o=n.root.elementsFromPoint(e.left,e.top);for(const r of o)if(n.dom.contains(r))return t&&r.closest("[data-node-type=columnList]")?K(n,{left:e.left+50,top:e.top},!1):he(r,n)}function mt(n,e){if(!e.dom.firstChild)return;const t=e.dom.firstChild.getBoundingClientRect(),o={left:Math.min(Math.max(t.left+10,n.x),t.right-10),top:n.y},r=K(e,o);if(!r)return;const s=r.node.getBoundingClientRect();return K(e,{left:s.right-10,top:n.y},!1)}class fe{constructor(e,t,o){b(this,"state");b(this,"emitUpdate");b(this,"mousePos");b(this,"hoveredBlock");b(this,"menuFrozen",!1);b(this,"isDragOrigin",!1);b(this,"updateState",e=>{this.state=e,this.emitUpdate(this.state)});b(this,"updateStateFromMousePos",()=>{var o,r,s,i,a;if(this.menuFrozen||!this.mousePos)return;const e=this.findClosestEditorElement({clientX:this.mousePos.x,clientY:this.mousePos.y});if((e==null?void 0:e.element)!==this.pmView.dom||e.distance>re){(o=this.state)!=null&&o.show&&(this.state.show=!1,this.updateState(this.state));return}const t=mt(this.mousePos,this.pmView);if(!t||!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"))&&((a=this.hoveredBlock)==null?void 0:a.getAttribute("data-id"))===t.id)&&(this.hoveredBlock=t.node,this.editor.isEditable)){const c=t.node.getBoundingClientRect(),l=t.node.closest("[data-node-type=column]");this.state={show:!0,referencePos:new DOMRect(l?l.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)}});b(this,"onDragStart",e=>{var i;const t=(i=e.dataTransfer)==null?void 0:i.getData("blocknote/html");if(!t||this.pmView.dragging)return;const o=document.createElement("div");o.innerHTML=t;const s=Z.DOMParser.fromSchema(this.pmView.state.schema).parse(o,{topNode:this.pmView.state.schema.nodes.blockGroup.create()});this.pmView.dragging={slice:new Z.Slice(s.content,0,0),move:!0}});b(this,"findClosestEditorElement",e=>{const t=Array.from(this.pmView.root.querySelectorAll(".bn-editor"));if(t.length===0)return null;let o=t[0],r=Number.MAX_VALUE;return t.forEach(s=>{const i=s.querySelector(".bn-block-group").getBoundingClientRect(),a=e.clientX<i.left?i.left-e.clientX:e.clientX>i.right?e.clientX-i.right:0,c=e.clientY<i.top?i.top-e.clientY:e.clientY>i.bottom?e.clientY-i.bottom:0,l=Math.sqrt(Math.pow(a,2)+Math.pow(c,2));l<r&&(r=l,o=s)}),{element:o,distance:r}});b(this,"onDragOver",e=>{if(e.synthetic)return;const t=this.getDragEventContext(e);if(!t||!t.isDropPoint){this.closeDropCursor();return}t.isDropPoint&&!t.isDropWithinEditorBounds&&this.dispatchSyntheticEvent(e)});b(this,"closeDropCursor",()=>{const e=new Event("dragleave",{bubbles:!1});e.synthetic=!0,this.pmView.dom.dispatchEvent(e)});b(this,"getDragEventContext",e=>{var c;const t=!((c=e.dataTransfer)!=null&&c.types.includes("blocknote/html"))&&!!this.pmView.dragging,o=!!this.isDragOrigin,r=t||o,s=this.findClosestEditorElement(e);if(!s||s.distance>re)return;const i=s.element===this.pmView.dom,a=i&&s.distance===0;if(!(!i&&!r))return{isDropPoint:i,isDropWithinEditorBounds:a,isDragOrigin:r}});b(this,"onDrop",e=>{if(e.synthetic)return;const t=this.getDragEventContext(e);if(!t){this.closeDropCursor();return}const{isDropPoint:o,isDropWithinEditorBounds:r,isDragOrigin:s}=t;if(!r&&o&&this.dispatchSyntheticEvent(e),o){if(this.pmView.dragging)return;this.pmView.dispatch(this.pmView.state.tr.setSelection(V.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}});b(this,"onDragEnd",e=>{e.synthetic||(this.pmView.dragging=null)});b(this,"onKeyDown",e=>{var t;(t=this.state)!=null&&t.show&&this.editor.isFocused()&&(this.state.show=!1,this.emitUpdate(this.state))});b(this,"onMouseMove",e=>{var s;if(this.menuFrozen)return;this.mousePos={x:e.clientX,y:e.clientY};const t=this.pmView.dom.getBoundingClientRect(),o=this.mousePos.x>t.left&&this.mousePos.x<t.right&&this.mousePos.y>t.top&&this.mousePos.y<t.bottom,r=this.pmView.dom.parentElement;if(o&&e&&e.target&&!(r===e.target||r.contains(e.target))){(s=this.state)!=null&&s.show&&(this.state.show=!1,this.emitUpdate(this.state));return}this.updateStateFromMousePos()});this.editor=e,this.pmView=t,this.emitUpdate=()=>{if(!this.state)throw new Error("Attempting to update uninitialized side menu");o(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)}dispatchSyntheticEvent(e){const t=new Event(e.type,e),o=this.pmView.dom.firstChild.getBoundingClientRect();t.clientX=e.clientX,t.clientY=e.clientY,t.clientX=Math.min(Math.max(e.clientX,o.left),o.left+o.width),t.clientY=Math.min(Math.max(e.clientY,o.top),o.top+o.height),t.dataTransfer=e.dataTransfer,t.preventDefault=()=>e.preventDefault(),t.synthetic=!0,this.pmView.dom.dispatchEvent(t)}update(e,t){var r;!t.doc.eq(this.pmView.state.doc)&&((r=this.state)!=null&&r.show)&&this.updateStateFromMousePos()}destroy(){var e;(e=this.state)!=null&&e.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)}}const ge=new V.PluginKey("SideMenuPlugin"),pt=v.createExtension(({editor:n})=>{let e;const t=v.createStore(void 0);return{key:"sideMenu",store:t,prosemirrorPlugins:[new V.Plugin({key:ge,view:o=>(e=new fe(n,o,r=>{t.setState({...r})}),e)})],blockDragStart(o,r){e&&(e.isDragOrigin=!0),ht(o,r,n)},blockDragEnd(){pe(n.prosemirrorView.root),e&&(e.isDragOrigin=!1),n.blur()},freezeMenu(){e.menuFrozen=!0,e.state.show=!0,e.emitUpdate(e.state)},unfreezeMenu(){e.menuFrozen=!1,e.state.show=!1,e.emitUpdate(e.state)}}});let E;function se(n){E||(E=document.createElement("div"),E.innerHTML="_",E.style.opacity="0",E.style.height="1px",E.style.width="1px",n instanceof Document?n.body.appendChild(E):n.appendChild(E))}function ft(n){E&&(n instanceof Document?n.body.removeChild(E):n.removeChild(E),E=void 0)}function _(n){return Array.prototype.indexOf.call(n.parentElement.childNodes,n)}function gt(n){let e=n;for(;e&&e.nodeName!=="TD"&&e.nodeName!=="TH"&&!e.classList.contains("tableWrapper");){if(e.classList.contains("ProseMirror"))return;const t=e.parentNode;if(!t||!(t instanceof Element))return;e=t}return e.nodeName==="TD"||e.nodeName==="TH"?{type:"cell",domNode:e,tbodyNode:e.closest("tbody")}:{type:"wrapper",domNode:e,tbodyNode:e.querySelector("tbody")}}function yt(n,e){const t=e.querySelectorAll(n);for(let o=0;o<t.length;o++)t[o].style.visibility="hidden"}class ye{constructor(e,t,o){b(this,"state");b(this,"emitUpdate");b(this,"tableId");b(this,"tablePos");b(this,"tableElement");b(this,"menuFrozen",!1);b(this,"mouseState","up");b(this,"prevWasEditable",null);b(this,"viewMousedownHandler",()=>{this.mouseState="down"});b(this,"mouseUpHandler",e=>{this.mouseState="up",this.mouseMoveHandler(e)});b(this,"mouseMoveHandler",e=>{var l,u,h,g,m,p,d,f;if(this.menuFrozen||this.mouseState==="selecting"||!(e.target instanceof Element)||!this.pmView.dom.contains(e.target))return;const t=gt(e.target);if((t==null?void 0:t.type)==="cell"&&this.mouseState==="down"&&!((l=this.state)!=null&&l.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(!t||!this.editor.isEditable){(h=this.state)!=null&&h.show&&(this.state.show=!1,this.state.showAddOrRemoveRowsButton=!1,this.state.showAddOrRemoveColumnsButton=!1,this.emitUpdate());return}if(!t.tbodyNode)return;const o=t.tbodyNode.getBoundingClientRect(),r=he(t.domNode,this.pmView);if(!r)return;this.tableElement=r.node;let s;const i=this.editor.transact(y=>O.getNodeById(r.id,y.doc));if(!i)throw new Error(`Block with ID ${r.id} not found`);const a=k.nodeToBlock(i.node,this.editor.pmSchema,this.editor.schema.blockSchema,this.editor.schema.inlineContentSchema,this.editor.schema.styleSchema);if(O.editorHasBlockWithType(this.editor,"table")&&(this.tablePos=i.posBeforeNode+1,s=a),!s)return;this.tableId=r.id;const c=(g=t.domNode.closest(".tableWrapper"))==null?void 0:g.querySelector(".table-widgets-container");if((t==null?void 0:t.type)==="wrapper"){const y=e.clientY>=o.bottom-1&&e.clientY<o.bottom+20,w=e.clientX>=o.right-1&&e.clientX<o.right+20,x=((m=this.state)==null?void 0:m.block.id)!==s.id||e.clientX>o.right||e.clientY>o.bottom;this.state={...this.state,show:!0,showAddOrRemoveRowsButton:y,showAddOrRemoveColumnsButton:w,referencePosTable:o,block:s,widgetContainer:c,colIndex:x||(p=this.state)==null?void 0:p.colIndex,rowIndex:x||(d=this.state)==null?void 0:d.rowIndex,referencePosCell:x||(f=this.state)==null?void 0:f.referencePosCell}}else{const y=_(t.domNode),w=_(t.domNode.parentElement),x=t.domNode.getBoundingClientRect();if(this.state!==void 0&&this.state.show&&this.tableId===r.id&&this.state.rowIndex===w&&this.state.colIndex===y)return;this.state={show:!0,showAddOrRemoveColumnsButton:y===s.content.rows[0].cells.length-1,showAddOrRemoveRowsButton:w===s.content.rows.length-1,referencePosTable:o,block:s,draggingState:void 0,referencePosCell:x,colIndex:y,rowIndex:w,widgetContainer:c}}return this.emitUpdate(),!1});b(this,"dragOverHandler",e=>{var g;if(((g=this.state)==null?void 0:g.draggingState)===void 0)return;e.preventDefault(),e.dataTransfer.dropEffect="move",yt(".prosemirror-dropcursor-block, .prosemirror-dropcursor-inline",this.pmView.root);const t={left:Math.min(Math.max(e.clientX,this.state.referencePosTable.left+1),this.state.referencePosTable.right-1),top:Math.min(Math.max(e.clientY,this.state.referencePosTable.top+1),this.state.referencePosTable.bottom-1)},o=this.pmView.root.elementsFromPoint(t.left,t.top).filter(m=>m.tagName==="TD"||m.tagName==="TH");if(o.length===0)return;const r=o[0];let s=!1;const i=_(r.parentElement),a=_(r),c=this.state.draggingState.draggedCellOrientation==="row"?this.state.rowIndex:this.state.colIndex,u=(this.state.draggingState.draggedCellOrientation==="row"?i:a)!==c;(this.state.rowIndex!==i||this.state.colIndex!==a)&&(this.state.rowIndex=i,this.state.colIndex=a,this.state.referencePosCell=r.getBoundingClientRect(),s=!0);const h=this.state.draggingState.draggedCellOrientation==="row"?t.top:t.left;this.state.draggingState.mousePos!==h&&(this.state.draggingState.mousePos=h,s=!0),s&&this.emitUpdate(),u&&this.editor.transact(m=>m.setMeta(N,!0))});b(this,"dropHandler",e=>{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.");e.preventDefault();const{draggingState:t,colIndex:o,rowIndex:r}=this.state,s=this.state.block.content.columnWidths;if(t.draggedCellOrientation==="row"){if(!k.canRowBeDraggedInto(this.state.block,t.originalIndex,r))return!1;const i=k.moveRow(this.state.block,t.originalIndex,r);this.editor.updateBlock(this.state.block,{type:"table",content:{...this.state.block.content,rows:i}})}else{if(!k.canColumnBeDraggedInto(this.state.block,t.originalIndex,o))return!1;const i=k.moveColumn(this.state.block,t.originalIndex,o),[a]=s.splice(t.originalIndex,1);s.splice(o,0,a),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=e,this.pmView=t,this.emitUpdate=()=>{if(!this.state)throw new Error("Attempting to update uninitialized image toolbar");o(this.state)},t.dom.addEventListener("mousemove",this.mouseMoveHandler),t.dom.addEventListener("mousedown",this.viewMousedownHandler),window.addEventListener("mouseup",this.mouseUpHandler),t.root.addEventListener("dragover",this.dragOverHandler),t.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:e,width:t}=k.getDimensionsOfTable(this.state.block);this.state.rowIndex!==void 0&&this.state.colIndex!==void 0&&(this.state.rowIndex>=e&&(this.state.rowIndex=e-1),this.state.colIndex>=t&&(this.state.colIndex=t-1));const o=this.tableElement.querySelector("tbody");if(!o)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=o.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=o.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 N=new C.PluginKey("TableHandlesPlugin"),wt=v.createExtension(({editor:n})=>{let e;const t=v.createStore(void 0);return{key:"tableHandles",store:t,prosemirrorPlugins:[new C.Plugin({key:N,view:o=>(e=new ye(n,o,r=>{t.setState(r.block?{...r,draggingState:r.draggingState?{...r.draggingState}:void 0}:void 0)}),e),props:{decorations:o=>{if(e===void 0||e.state===void 0||e.state.draggingState===void 0||e.tablePos===void 0)return;const r=e.state.draggingState.draggedCellOrientation==="row"?e.state.rowIndex:e.state.colIndex;if(r===void 0)return;const s=[],{block:i,draggingState:a}=e.state,{originalIndex:c,draggedCellOrientation:l}=a;if(r===c||!i||l==="row"&&!k.canRowBeDraggedInto(i,c,r)||l==="col"&&!k.canColumnBeDraggedInto(i,c,r))return D.DecorationSet.create(o.doc,s);const u=o.doc.resolve(e.tablePos+1);return e.state.draggingState.draggedCellOrientation==="row"?k.getCellsAtRowHandle(e.state.block,r).forEach(({row:g,col:m})=>{const p=o.doc.resolve(u.posAtIndex(g)+1),d=o.doc.resolve(p.posAtIndex(m)+1),f=d.node(),y=d.pos+(r>c?f.nodeSize-2:0);s.push(D.Decoration.widget(y,()=>{const w=document.createElement("div");return w.className="bn-table-drop-cursor",w.style.left="0",w.style.right="0",r>c?w.style.bottom="-2px":w.style.top="-3px",w.style.height="4px",w}))}):k.getCellsAtColumnHandle(e.state.block,r).forEach(({row:g,col:m})=>{const p=o.doc.resolve(u.posAtIndex(g)+1),d=o.doc.resolve(p.posAtIndex(m)+1),f=d.node(),y=d.pos+(r>c?f.nodeSize-2:0);s.push(D.Decoration.widget(y,()=>{const w=document.createElement("div");return w.className="bn-table-drop-cursor",w.style.top="0",w.style.bottom="0",r>c?w.style.right="-2px":w.style.left="-3px",w.style.width="4px",w}))}),D.DecorationSet.create(o.doc,s)}}})],colDragStart(o){if(e===void 0||e.state===void 0||e.state.colIndex===void 0)throw new Error("Attempted to drag table column, but no table block was hovered prior.");e.state.draggingState={draggedCellOrientation:"col",originalIndex:e.state.colIndex,mousePos:o.clientX},e.emitUpdate(),n.transact(r=>r.setMeta(N,{draggedCellOrientation:e.state.draggingState.draggedCellOrientation,originalIndex:e.state.colIndex,newIndex:e.state.colIndex,tablePos:e.tablePos})),!n.headless&&(se(n.prosemirrorView.root),o.dataTransfer.setDragImage(E,0,0),o.dataTransfer.effectAllowed="move")},rowDragStart(o){if(e.state===void 0||e.state.rowIndex===void 0)throw new Error("Attempted to drag table row, but no table block was hovered prior.");e.state.draggingState={draggedCellOrientation:"row",originalIndex:e.state.rowIndex,mousePos:o.clientY},e.emitUpdate(),n.transact(r=>r.setMeta(N,{draggedCellOrientation:e.state.draggingState.draggedCellOrientation,originalIndex:e.state.rowIndex,newIndex:e.state.rowIndex,tablePos:e.tablePos})),!n.headless&&(se(n.prosemirrorView.root),o.dataTransfer.setDragImage(E,0,0),o.dataTransfer.effectAllowed="copyMove")},dragEnd(){if(e.state===void 0)throw new Error("Attempted to drag table row, but no table block was hovered prior.");e.state.draggingState=void 0,e.emitUpdate(),n.transact(o=>o.setMeta(N,null)),!n.headless&&ft(n.prosemirrorView.root)},freezeHandles(){e.menuFrozen=!0},unfreezeHandles(){e.menuFrozen=!1},getCellsAtRowHandle(o,r){return k.getCellsAtRowHandle(o,r)},getCellsAtColumnHandle(o,r){return k.getCellsAtColumnHandle(o,r)},setCellSelection(o,r,s=r){if(!e)throw new Error("Table handles view not initialized");const i=o.doc.resolve(e.tablePos+1),a=o.doc.resolve(i.posAtIndex(r.row)+1),c=o.doc.resolve(a.posAtIndex(r.col)),l=o.doc.resolve(i.posAtIndex(s.row)+1),u=o.doc.resolve(l.posAtIndex(s.col)),h=o.tr;return h.setSelection(new T.CellSelection(c,u)),o.apply(h)},addRowOrColumn(o,r){n.exec((s,i)=>{const a=this.setCellSelection(s,r.orientation==="row"?{row:o,col:0}:{row:0,col:o});return r.orientation==="row"?r.side==="above"?T.addRowBefore(a,i):T.addRowAfter(a,i):r.side==="left"?T.addColumnBefore(a,i):T.addColumnAfter(a,i)})},removeRowOrColumn(o,r){return r==="row"?n.exec((s,i)=>{const a=this.setCellSelection(s,{row:o,col:0});return T.deleteRow(a,i)}):n.exec((s,i)=>{const a=this.setCellSelection(s,{row:0,col:o});return T.deleteColumn(a,i)})},mergeCells(o){return n.exec((r,s)=>{const i=o?this.setCellSelection(r,o.relativeStartCell,o.relativeEndCell):r;return T.mergeCells(i,s)})},splitCell(o){return n.exec((r,s)=>{const i=o?this.setCellSelection(r,o):r;return T.splitCell(i,s)})},getCellSelection(){return n.transact(o=>{const r=o.selection;let s=r.$from,i=r.$to;if(O.isTableCellSelection(r)){const{ranges:d}=r;d.forEach(f=>{s=f.$from.min(s??f.$from),i=f.$to.max(i??f.$to)})}else if(s=o.doc.resolve(r.$from.pos-r.$from.parentOffset-1),i=o.doc.resolve(r.$to.pos-r.$to.parentOffset-1),s.pos===0||i.pos===0)return;const a=o.doc.resolve(s.pos-s.parentOffset-1),c=o.doc.resolve(i.pos-i.parentOffset-1),l=o.doc.resolve(a.pos-a.parentOffset-1),u=s.index(a.depth),h=a.index(l.depth),g=i.index(c.depth),m=c.index(l.depth),p=[];for(let d=h;d<=m;d++)for(let f=u;f<=g;f++)p.push({row:d,col:f});return{from:{row:h,col:u},to:{row:m,col:g},cells:p}})},getMergeDirection(o){return n.transact(r=>{const s=O.isTableCellSelection(r.selection)?r.selection:void 0;if(!s||!o||s.ranges.length<=1)return;const i=this.getCellSelection();if(i)return k.areInSameColumn(i.from,i.to,o)?"vertical":"horizontal"})},cropEmptyRowsOrColumns(o,r){return k.cropEmptyRowsOrColumns(o,r)},addRowsOrColumns(o,r,s){return k.addRowsOrColumns(o,r,s)}}}),ie=new C.PluginKey("trailingNode"),bt=v.createExtension(()=>({key:"trailingNode",prosemirrorPlugins:[new C.Plugin({key:ie,appendTransaction:(n,e,t)=>{const{doc:o,tr:r,schema:s}=t,i=ie.getState(t),a=o.content.size-2,c=s.nodes.blockContainer,l=s.nodes.paragraph;if(i)return r.insert(a,c.create(void 0,l.create()))},state:{init:(n,e)=>{},apply:(n,e)=>{if(!n.docChanged)return e;let t=n.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 o=t.firstChild;if(!o)throw new Error("Expected blockContent");return t.nodeSize>4||o.type.spec.content!=="inline*"}}})]}));exports.BlockChangeExtension=$e;exports.DEFAULT_LINK_PROTOCOL=et;exports.DropCursorExtension=We;exports.ForkYDocExtension=Ke;exports.FormattingToolbarExtension=Ge;exports.HistoryExtension=Je;exports.LinkToolbarExtension=Qe;exports.NodeSelectionKeyboardExtension=ot;exports.PlaceholderExtension=rt;exports.PreviousBlockTypeExtension=it;exports.SchemaMigration=Xe;exports.SideMenuExtension=pt;exports.SideMenuView=fe;exports.TableHandlesExtension=wt;exports.TableHandlesView=ye;exports.TrailingNodeExtension=bt;exports.VALID_LINK_PROTOCOLS=Ze;exports.YCursorExtension=z;exports.YSyncExtension=U;exports.YUndoExtension=$;exports.blocksToMarkdown=dt;exports.cleanHTMLToMarkdown=j;exports.createExternalHTMLExporter=Y;exports.fragmentToBlocks=me;exports.getBlocksChangedByTransaction=de;exports.sideMenuPluginKey=ge;exports.tableHandlesPluginKey=N;
//# sourceMappingURL=TrailingNode-D-CZ76FS.cjs.map
diff --git a/dist/blocknote.cjs b/dist/blocknote.cjs
index 778ed7a4062755747312db827f920e47a5aff127..f9e34b3ceb54a976b734fd70ac7fc183e0070c2b 100644
--- a/dist/blocknote.cjs
+++ b/dist/blocknote.cjs
@@ -1,5 +1,5 @@
"use strict";var Ee=Object.defineProperty;var Te=(o,e,t)=>e in o?Ee(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var k=(o,e,t)=>Te(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x=require("prosemirror-model"),L=require("prosemirror-transform"),u=require("./blockToNode-CumVjgem.cjs"),c=require("./defaultBlocks-DosClM5E.cjs"),b=require("./TrailingNode-D-CZ76FS.cjs"),M=require("./BlockNoteSchema-DmFDeA0n.cjs"),B=require("@tiptap/core"),R=require("./EventEmitter-CLwfmbqG.cjs"),A=require("@tiptap/pm/model"),xe=require("./en-Cl87Uuyf.cjs"),K=require("@handlewithcare/prosemirror-inputrules"),Me=require("@tiptap/pm/keymap"),F=require("./BlockNoteExtension-BWw0r8Gy.cjs"),Ie=require("@tiptap/extensions/gap-cursor"),Pe=require("@tiptap/extension-link"),we=require("@tiptap/extension-text"),C=require("prosemirror-state"),N=require("prosemirror-tables"),ve=require("./ShowSelection-BxnbRvy4.cjs"),Ae=require("remark-gfm"),Ne=require("remark-parse"),H=require("remark-rehype"),Le=require("rehype-stringify"),_e=require("unified"),De=require("@tiptap/pm/state"),O=o=>o&&typeof o=="object"&&"default"in o?o:{default:o},Fe=O(Ae),Oe=O(Ne),He=O(H),$e=O(Le);function oe(o,e){const t=[{tag:`[data-inline-content-type="${o.type}"]`,contentElement:n=>{const r=n;return r.matches("[data-editable]")?r:r.querySelector("[data-editable]")||r}}];return e&&t.push({tag:"*",getAttrs(n){if(typeof n=="string")return!1;const r=e==null?void 0:e(n);return r===void 0?!1:r}}),t}function Ue(o,e){var n;const t=B.Node.create({name:o.type,inline:!0,group:"inline",draggable:(n=e.meta)==null?void 0:n.draggable,selectable:o.content==="styled",atom:o.content==="none",content:o.content==="styled"?"inline*":"",addAttributes(){return c.propsToAttributes(o.propSchema)},addKeyboardShortcuts(){return c.addInlineContentKeyboardShortcuts(o)},parseHTML(){return oe(o,e.parse)},renderHTML({node:r}){const s=this.options.editor,i=e.render.call({renderType:"dom",props:void 0},u.nodeToCustomInlineContent(r,s.schema.inlineContentSchema,s.schema.styleSchema),()=>{},s);return c.addInlineContentAttributes(i,o.type,r.attrs,o.propSchema)},addNodeView(){return r=>{const{node:s,getPos:i}=r,l=this.options.editor,a=e.render.call({renderType:"nodeView",props:r},u.nodeToCustomInlineContent(s,l.schema.inlineContentSchema,l.schema.styleSchema),d=>{const p=u.inlineContentToNodes([d],l.pmSchema),f=i();f&&l.transact(h=>h.replaceWith(f,f+s.nodeSize,p))},l);return c.addInlineContentAttributes(a,o.type,s.attrs,o.propSchema)}}});return c.createInlineContentSpecFromTipTapNode(t,o.propSchema,{...e,toExternalHTML:e.toExternalHTML,render(r,s,i){const l=e.render(r,s,i);return c.addInlineContentAttributes(l,o.type,r.props,o.propSchema)}})}function ne(o,e,t,n="before"){const r=typeof t=="string"?t:t.id,s=u.getPmSchema(o),i=e.map(p=>u.blockToNode(p,s)),l=c.getNodeById(r,o.doc);if(!l)throw new Error(`Block with ID ${r} not found`);let a=l.posBeforeNode;return n==="after"&&(a+=l.node.nodeSize),o.step(new L.ReplaceStep(a,a,new x.Slice(x.Fragment.from(i),0,0))),i.map(p=>u.nodeToBlock(p,s))}function _(o){if(!o||o.type.name!=="column")throw new Error("Invalid columnPos: does not point to column node.");const e=o.firstChild;if(!e)throw new Error("Invalid column: does not have child node.");const t=e.firstChild;if(!t)throw new Error("Invalid blockContainer: does not have child node.");return o.childCount===1&&e.childCount===1&&t.type.name==="paragraph"&&t.content.content.length===0}function re(o,e){const t=o.doc.resolve(e),n=t.nodeAfter;if(!n||n.type.name!=="columnList")throw new Error("Invalid columnListPos: does not point to columnList node.");for(let r=n.childCount-1;r>=0;r--){const s=o.doc.resolve(t.pos+1).posAtIndex(r),l=o.doc.resolve(s).nodeAfter;if(!l||l.type.name!=="column")throw new Error("Invalid columnPos: does not point to column node.");_(l)&&o.delete(s,s+l.nodeSize)}}function D(o,e){re(o,e);const n=o.doc.resolve(e).nodeAfter;if(!n||n.type.name!=="columnList")throw new Error("Invalid columnListPos: does not point to columnList node.");if(n.childCount>2)return;if(n.childCount<2)throw new Error("Invalid columnList: contains fewer than two children.");const r=e+1,i=o.doc.resolve(r).nodeAfter,l=e+n.nodeSize-1,d=o.doc.resolve(l).nodeBefore;if(!i||!d)throw new Error("Invalid columnList: does not contain children.");const p=_(i),f=_(d);if(p&&f){o.delete(e,e+n.nodeSize);return}if(p){o.step(new L.ReplaceAroundStep(e,e+n.nodeSize,l-d.nodeSize+1,l-1,x.Slice.empty,0,!1));return}if(f){o.step(new L.ReplaceAroundStep(e,e+n.nodeSize,r+1,r+i.nodeSize-1,x.Slice.empty,0,!1));return}}function $(o,e,t){const n=u.getPmSchema(o),r=t.map(f=>u.blockToNode(f,n)),s=new Set(e.map(f=>typeof f=="string"?f:f.id)),i=[],l=new Set,a=typeof e[0]=="string"?e[0]:e[0].id;let d=0;if(o.doc.descendants((f,h)=>{if(s.size===0)return!1;if(!f.type.isInGroup("bnBlock")||!s.has(f.attrs.id))return!0;if(i.push(u.nodeToBlock(f,n)),s.delete(f.attrs.id),t.length>0&&f.attrs.id===a){const y=o.doc.nodeSize;o.insert(h,r);const E=o.doc.nodeSize;d+=y-E}const g=o.doc.nodeSize,m=o.doc.resolve(h-d);m.node().type.name==="column"?l.add(m.before(-1)):m.node().type.name==="columnList"&&l.add(m.before()),m.node().type.name==="blockGroup"&&m.node(m.depth-1).type.name!=="doc"&&m.node().childCount===1?o.delete(m.before(),m.after()):o.delete(h-d,h-d+f.nodeSize);const S=o.doc.nodeSize;return d+=g-S,!1}),s.size>0){const f=[...s].join(`
-`);throw Error("Blocks with the following IDs could not be found in the editor: "+f)}return l.forEach(f=>D(o,f)),{insertedBlocks:r.map(f=>u.nodeToBlock(f,n)),removedBlocks:i}}function Ve(o,e,t,n,r){let s;if(e)if(typeof e=="string")s=u.inlineContentToNodes([e],o.pmSchema,n);else if(Array.isArray(e))s=u.inlineContentToNodes(e,o.pmSchema,n);else if(e.type==="tableContent")s=u.tableContentToNodes(e,o.pmSchema);else throw new u.UnreachableCaseError(e.type);else throw new Error("blockContent is required");const l=((r==null?void 0:r.document)??document).createDocumentFragment();for(const a of s)if(a.type.name!=="text"&&o.schema.inlineContentSchema[a.type.name]){const d=o.schema.inlineContentSpecs[a.type.name].implementation;if(d){const p=u.nodeToCustomInlineContent(a,o.schema.inlineContentSchema,o.schema.styleSchema),f=d.render.call({renderType:"dom",props:void 0},p,()=>{},o);if(f){if(l.appendChild(f.dom),f.contentDOM){const h=t.serializeFragment(a.content,r);f.contentDOM.dataset.editable="",f.contentDOM.appendChild(h)}continue}}}else if(a.type.name==="text"){let d=document.createTextNode(a.textContent);for(const p of a.marks.toReversed())if(p.type.name in o.schema.styleSpecs){const f=o.schema.styleSpecs[p.type.name].implementation.render(p.attrs.stringValue,o);f.contentDOM.appendChild(d),d=f.dom}else{const f=p.type.spec.toDOM(p,!0),h=x.DOMSerializer.renderSpec(document,f);h.contentDOM.appendChild(d),d=h.dom}l.appendChild(d)}else{const d=t.serializeFragment(x.Fragment.from([a]),r);l.appendChild(d)}return l}function Re(o,e,t,n){var f,h,g,m,S;const r=o.pmSchema.nodes.blockContainer,s=e.props||{};for(const[y,E]of Object.entries(o.schema.blockSchema[e.type].propSchema))!(y in s)&&E.default!==void 0&&(s[y]=E.default);const i=e.children||[],a=o.blockImplementations[e.type].implementation.render.call({renderType:"dom",props:void 0},{...e,props:s,children:i},o);if(a.contentDOM&&e.content){const y=Ve(o,e.content,t,e.type,n);a.contentDOM.appendChild(y)}if(o.pmSchema.nodes[e.type].isInGroup("bnBlock")){if(e.children&&e.children.length>0){const y=se(o,e.children,t,n);(f=a.contentDOM)==null||f.append(y)}return a.dom}const p=(g=(h=r.spec)==null?void 0:h.toDOM)==null?void 0:g.call(h,r.create({id:e.id,...s}));return(m=p.contentDOM)==null||m.appendChild(a.dom),e.children&&e.children.length>0&&((S=p.contentDOM)==null||S.appendChild(ie(o,e.children,t,n))),p.dom}function se(o,e,t,n){const s=((n==null?void 0:n.document)??document).createDocumentFragment();for(const i of e){const l=Re(o,i,t,n);s.appendChild(l)}return s}const ie=(o,e,t,n)=>{var l;const r=o.pmSchema.nodes.blockGroup,s=r.spec.toDOM(r.create({})),i=se(o,e,t,n);return(l=s.contentDOM)==null||l.appendChild(i),s.dom},ze=o=>(o.querySelectorAll('[data-content-type="numberedListItem"]').forEach(t=>{var r,s;const n=(s=(r=t.closest(".bn-block-outer"))==null?void 0:r.previousElementSibling)==null?void 0:s.querySelector('[data-content-type="numberedListItem"]');if(!n)t.setAttribute("data-index",t.getAttribute("data-start")||"1");else{const i=n.getAttribute("data-index");t.setAttribute("data-index",(parseInt(i||"0")+1).toString())}}),o),Ge=o=>(o.querySelectorAll('[data-content-type="checkListItem"] input').forEach(t=>{t.disabled=!0}),o),qe=o=>(o.querySelectorAll('.bn-toggle-wrapper[data-show-children="false"]').forEach(t=>{t.setAttribute("data-show-children","true")}),o),We=o=>(o.querySelectorAll('[data-content-type="table"] table').forEach(t=>{t.setAttribute("style",`--default-cell-min-width: ${c.EMPTY_CELL_WIDTH}px;`),t.setAttribute("data-show-children","true")}),o),je=o=>(o.querySelectorAll('[data-content-type="table"] table').forEach(t=>{var s;const n=document.createElement("div");n.className="tableWrapper";const r=document.createElement("div");r.className="tableWrapper-inner",n.appendChild(r),(s=t.parentElement)==null||s.appendChild(n),n.appendChild(t)}),o),Ke=o=>(o.querySelectorAll(".bn-inline-content:empty").forEach(t=>{const n=document.createElement("span");n.className="ProseMirror-trailingBreak",n.setAttribute("style","display: inline-block;"),t.appendChild(n)}),o),ce=(o,e)=>{const t=x.DOMSerializer.fromSchema(o),n=[ze,Ge,qe,We,je,Ke];return{serializeBlocks:(r,s)=>{let i=ie(e,r,t,s);for(const l of n)i=l(i);return i.outerHTML}}};function Ye(o){return o.transact(e=>{const t=u.getNearestBlockPos(e.doc,e.selection.anchor);if(e.selection instanceof N.CellSelection)return{type:"cell",anchorBlockId:t.node.attrs.id,anchorCellOffset:e.selection.$anchorCell.pos-t.posBeforeNode,headCellOffset:e.selection.$headCell.pos-t.posBeforeNode};if(e.selection instanceof C.NodeSelection)return{type:"node",anchorBlockId:t.node.attrs.id};{const n=u.getNearestBlockPos(e.doc,e.selection.head);return{type:"text",anchorBlockId:t.node.attrs.id,headBlockId:n.node.attrs.id,anchorOffset:e.selection.anchor-t.posBeforeNode,headOffset:e.selection.head-n.posBeforeNode}}})}function Je(o,e){var r,s;const t=(r=c.getNodeById(e.anchorBlockId,o.doc))==null?void 0:r.posBeforeNode;if(t===void 0)throw new Error(`Could not find block with ID ${e.anchorBlockId} to update selection`);let n;if(e.type==="cell")n=N.CellSelection.create(o.doc,t+e.anchorCellOffset,t+e.headCellOffset);else if(e.type==="node")n=C.NodeSelection.create(o.doc,t+1);else{const i=(s=c.getNodeById(e.headBlockId,o.doc))==null?void 0:s.posBeforeNode;if(i===void 0)throw new Error(`Could not find block with ID ${e.headBlockId} to update selection`);n=C.TextSelection.create(o.doc,t+e.anchorOffset,i+e.headOffset)}o.setSelection(n)}function U(o){return o.map(e=>e.type==="columnList"?e.children.map(t=>U(t.children)).flat():{...e,children:U(e.children)}).flat()}function ae(o,e,t){o.transact(n=>{var i;const r=((i=o.getSelection())==null?void 0:i.blocks)||[o.getTextCursorPosition().block],s=Ye(o);o.removeBlocks(r),o.insertBlocks(U(r),e,t),Je(n,s)})}function le(o){return!o||o.type!=="columnList"}function de(o,e,t){let n,r;if(e?e.children.length>0?(n=e.children[e.children.length-1],r="after"):(n=e,r="before"):t&&(n=t,r="before"),!n||!r)return;const s=o.getParentBlock(n);return le(s)?{referenceBlock:n,placement:r}:de(o,r==="after"?n:o.getPrevBlock(n),s)}function ue(o,e,t){let n,r;if(e?e.children.length>0?(n=e.children[0],r="before"):(n=e,r="after"):t&&(n=t,r="after"),!n||!r)return;const s=o.getParentBlock(n);return le(s)?{referenceBlock:n,placement:r}:ue(o,r==="before"?n:o.getNextBlock(n),s)}function Qe(o){o.transact(()=>{const e=o.getSelection(),t=(e==null?void 0:e.blocks[0])||o.getTextCursorPosition().block,n=de(o,o.getPrevBlock(t),o.getParentBlock(t));n&&ae(o,n.referenceBlock,n.placement)})}function Xe(o){o.transact(()=>{const e=o.getSelection(),t=(e==null?void 0:e.blocks[(e==null?void 0:e.blocks.length)-1])||o.getTextCursorPosition().block,n=ue(o,o.getNextBlock(t),o.getParentBlock(t));n&&ae(o,n.referenceBlock,n.placement)})}function Ze(o,e,t){const{$from:n,$to:r}=o.selection,s=n.blockRange(r,m=>m.childCount>0&&(m.type.name==="blockGroup"||m.type.name==="column"));if(!s)return!1;const i=s.startIndex;if(i===0)return!1;const a=s.parent.child(i-1);if(a.type!==e)return!1;const d=a.lastChild&&a.lastChild.type===t,p=x.Fragment.from(d?e.create():null),f=new x.Slice(x.Fragment.from(e.create(null,x.Fragment.from(t.create(null,p)))),d?3:1,0),h=s.start,g=s.end;return o.step(new L.ReplaceAroundStep(h-(d?3:1),g,h,g,f,1,!0)).scrollIntoView(),!0}function pe(o){return o.transact(e=>Ze(e,o.pmSchema.nodes.blockContainer,o.pmSchema.nodes.blockGroup))}function et(o){o._tiptapEditor.commands.liftListItem("blockContainer")}function tt(o){return o.transact(e=>{const{bnBlock:t}=u.getBlockInfoFromTransaction(e);return e.doc.resolve(t.beforePos).nodeBefore!==null})}function ot(o){return o.transact(e=>{const{bnBlock:t}=u.getBlockInfoFromTransaction(e);return e.doc.resolve(t.beforePos).depth>1})}function fe(o,e){const t=typeof e=="string"?e:e.id,n=u.getPmSchema(o),r=c.getNodeById(t,o);if(r)return u.nodeToBlock(r.node,n)}function he(o,e){const t=typeof e=="string"?e:e.id,n=c.getNodeById(t,o),r=u.getPmSchema(o);if(!n)return;const i=o.resolve(n.posBeforeNode).nodeBefore;if(i)return u.nodeToBlock(i,r)}function me(o,e){const t=typeof e=="string"?e:e.id,n=c.getNodeById(t,o),r=u.getPmSchema(o);if(!n)return;const i=o.resolve(n.posBeforeNode+n.node.nodeSize).nodeAfter;if(i)return u.nodeToBlock(i,r)}function ke(o,e){const t=typeof e=="string"?e:e.id,n=u.getPmSchema(o),r=c.getNodeById(t,o);if(!r)return;const s=o.resolve(r.posBeforeNode),i=s.node(),l=s.node(-1),a=l.type.name!=="doc"?i.type.name==="blockGroup"?l:i:void 0;if(a)return u.nodeToBlock(a,n)}class nt{constructor(e){this.editor=e}get document(){return this.editor.transact(e=>u.docToBlocks(e.doc,this.editor.pmSchema))}getBlock(e){return this.editor.transact(t=>fe(t.doc,e))}getPrevBlock(e){return this.editor.transact(t=>he(t.doc,e))}getNextBlock(e){return this.editor.transact(t=>me(t.doc,e))}getParentBlock(e){return this.editor.transact(t=>ke(t.doc,e))}forEachBlock(e,t=!1){const n=this.document.slice();t&&n.reverse();function r(s){for(const i of s){if(e(i)===!1)return!1;const l=t?i.children.slice().reverse():i.children;if(!r(l))return!1}return!0}r(n)}insertBlocks(e,t,n="before"){return this.editor.transact(r=>ne(r,e,t,n))}updateBlock(e,t){return this.editor.transact(n=>c.updateBlock(n,e,t))}removeBlocks(e){return this.editor.transact(t=>$(t,e,[]).removedBlocks)}replaceBlocks(e,t){return this.editor.transact(n=>$(n,e,t))}canNestBlock(){return tt(this.editor)}nestBlock(){pe(this.editor)}canUnnestBlock(){return ot(this.editor)}unnestBlock(){et(this.editor)}moveBlocksUp(){return Qe(this.editor)}moveBlocksDown(){return Xe(this.editor)}}class rt extends R.EventEmitter{constructor(e){super(),this.editor=e,e.on("create",()=>{e._tiptapEditor.on("update",({transaction:t,appendedTransactions:n})=>{this.emit("onChange",{editor:e,transaction:t,appendedTransactions:n})}),e._tiptapEditor.on("selectionUpdate",({transaction:t})=>{this.emit("onSelectionChange",{editor:e,transaction:t})}),e._tiptapEditor.on("mount",()=>{this.emit("onMount",{editor:e})}),e._tiptapEditor.on("unmount",()=>{this.emit("onUnmount",{editor:e})})})}onChange(e,t=!0){const n=({transaction:r,appendedTransactions:s})=>{!t&&Y(r)||e(this.editor,{getChanges(){return b.getBlocksChangedByTransaction(r,s)}})};return this.on("onChange",n),()=>{this.off("onChange",n)}}onSelectionChange(e,t=!1){const n=r=>{!t&&Y(r.transaction)||e(this.editor)};return this.on("onSelectionChange",n),()=>{this.off("onSelectionChange",n)}}onMount(e){return this.on("onMount",e),()=>{this.off("onMount",e)}}onUnmount(e){return this.on("onUnmount",e),()=>{this.off("onUnmount",e)}}}function Y(o){return!!o.getMeta("y-sync$")}function st(o){return Array.prototype.indexOf.call(o.parentElement.childNodes,o)}function it(o){return o.nodeType===3&&!/\S/.test(o.nodeValue||"")}function ct(o){o.querySelectorAll("li > ul, li > ol").forEach(e=>{const t=st(e),n=e.parentElement,r=Array.from(n.childNodes).slice(t+1);e.remove(),r.forEach(s=>{s.remove()}),n.insertAdjacentElement("afterend",e),r.reverse().forEach(s=>{if(it(s))return;const i=document.createElement("li");i.append(s),e.insertAdjacentElement("afterend",i)}),n.childNodes.length===0&&n.remove()})}function at(o){o.querySelectorAll("li + ul, li + ol").forEach(e=>{var s,i;const t=e.previousElementSibling,n=document.createElement("div");t.insertAdjacentElement("afterend",n),n.append(t);const r=document.createElement("div");for(r.setAttribute("data-node-type","blockGroup"),n.append(r);((s=n.nextElementSibling)==null?void 0:s.nodeName)==="UL"||((i=n.nextElementSibling)==null?void 0:i.nodeName)==="OL";)r.append(n.nextElementSibling)})}let J=null;function lt(){return J||(J=document.implementation.createHTMLDocument("title"))}function dt(o){if(typeof o=="string"){const e=lt().createElement("div");e.innerHTML=o,o=e}return ct(o),at(o),o}function z(o,e){const t=dt(o),r=x.DOMParser.fromSchema(e).parse(t,{topNode:e.nodes.blockGroup.create()}),s=[];for(let i=0;i<r.childCount;i++)s.push(u.nodeToBlock(r.child(i),e));return s}function ut(o,e){const t=e.value?e.value:"",n={};e.lang&&(n["data-language"]=e.lang);let r={type:"element",tagName:"code",properties:n,children:[{type:"text",value:t}]};return e.meta&&(r.data={meta:e.meta}),o.patch(e,r),r=o.applyData(e,r),r={type:"element",tagName:"pre",properties:{},children:[r]},o.patch(e,r),r}function pt(o,e){var s;const t=String((e==null?void 0:e.url)||""),n=e!=null&&e.title?String(e.title):void 0;let r={type:"element",tagName:"video",properties:{src:t,"data-name":n,"data-url":t,controls:!0},children:[]};return(s=o.patch)==null||s.call(o,e,r),r=o.applyData?o.applyData(e,r):r,r}function G(o){return _e.unified().use(Oe.default).use(Fe.default).use(He.default,{handlers:{...H.defaultHandlers,image:(t,n)=>{const r=String((n==null?void 0:n.url)||"");return c.isVideoUrl(r)?pt(t,n):H.defaultHandlers.image(t,n)},code:ut,blockquote:(t,n)=>{const r={type:"element",tagName:"blockquote",properties:{},children:t.wrap(t.all(n),!1)};return t.patch(n,r),t.applyData(n,r)}}}).use($e.default).processSync(o).value}function ge(o,e){const t=G(o);return z(t,e)}class ft{constructor(e){this.editor=e}blocksToHTMLLossy(e=this.editor.document){return b.createExternalHTMLExporter(this.editor.pmSchema,this.editor).exportBlocks(e,{})}blocksToFullHTML(e=this.editor.document){return ce(this.editor.pmSchema,this.editor).serializeBlocks(e,{})}tryParseHTMLToBlocks(e){return z(e,this.editor.pmSchema)}blocksToMarkdownLossy(e=this.editor.document){return b.blocksToMarkdown(e,this.editor.pmSchema,this.editor,{})}tryParseMarkdownToBlocks(e){return ge(e,this.editor.pmSchema)}pasteHTML(e,t=!1){var r;let n=e;if(!t){const s=this.tryParseHTMLToBlocks(e);n=this.blocksToFullHTML(s)}n&&((r=this.editor.prosemirrorView)==null||r.pasteHTML(n))}pasteText(e){var t;return(t=this.editor.prosemirrorView)==null?void 0:t.pasteText(e)}pasteMarkdown(e){const t=G(e);return this.pasteHTML(t)}}const q=["vscode-editor-data","blocknote/html","text/markdown","text/html","text/plain","Files"];function ht(o,e){if(!o.startsWith(".")||!e.startsWith("."))throw new Error("The strings provided are not valid file extensions.");return o===e}function mt(o,e){const t=o.split("/"),n=e.split("/");if(t.length!==2)throw new Error(`The string ${o} is not a valid MIME type.`);if(n.length!==2)throw new Error(`The string ${e} is not a valid MIME type.`);return t[1]==="*"||n[1]==="*"?t[0]===n[0]:(t[0]==="*"||n[0]==="*"||t[0]===n[0])&&t[1]===n[1]}function Q(o,e,t,n="after"){let r;return Array.isArray(e.content)&&e.content.length===0?r=o.updateBlock(e,t).id:r=o.insertBlocks([t],e,n)[0].id,r}async function be(o,e){var s;if(!e.uploadFile){console.warn("Attempted ot insert file, but uploadFile is not set in the BlockNote editor options");return}const t="dataTransfer"in o?o.dataTransfer:o.clipboardData;if(t===null)return;let n=null;for(const i of q)if(t.types.includes(i)){n=i;break}if(n!=="Files")return;const r=t.items;if(r){o.preventDefault();for(let i=0;i<r.length;i++){let l="file";for(const d of Object.values(e.schema.blockSpecs))for(const p of((s=d.implementation.meta)==null?void 0:s.fileBlockAccept)||[]){const f=p.startsWith("."),h=r[i].getAsFile();if(h&&(!f&&h.type&&mt(r[i].type,p)||f&&ht("."+h.name.split(".").pop(),p))){l=d.config.type;break}}const a=r[i].getAsFile();if(a){const d={type:l,props:{name:a.name}};let p;if(o.type==="paste"){const g=e.getTextCursorPosition().block;p=Q(e,g,d)}else if(o.type==="drop"){const g={left:o.clientX,top:o.clientY},m=e.prosemirrorView.posAtCoords(g);if(!m)return;p=e.transact(S=>{var T;const y=u.getNearestBlockPos(S.doc,m.pos),E=(T=e.domElement)==null?void 0:T.querySelector(`[data-id="${y.node.attrs.id}"]`),P=E==null?void 0:E.getBoundingClientRect();return Q(e,e.getBlock(y.node.attrs.id),d,P&&(P.top+P.bottom)/2>g.top?"before":"after")})}else return;const f=await e.uploadFile(a,p),h=typeof f=="string"?{props:{url:f}}:{...f};e.updateBlock(p,h)}}}}const kt=o=>B.Extension.create({name:"dropFile",addProseMirrorPlugins(){return[new C.Plugin({props:{handleDOMEvents:{drop(e,t){if(!o.isEditable)return;let n=null;for(const r of q)if(t.dataTransfer.types.includes(r)){n=r;break}return n===null?!0:n==="Files"?(be(t,o),!0):!1}}}})]}}),gt=/(^|\n) {0,3}#{1,6} {1,8}[^\n]{1,64}\r?\n\r?\n\s{0,32}\S/,bt=/(_|__|\*|\*\*|~~|==|\+\+)(?!\s)(?:[^\s](?:.{0,62}[^\s])?|\S)(?=\1)/,St=/\[[^\]]{1,128}\]\(https?:\/\/\S{1,999}\)/,Bt=/(?:\s|^)`(?!\s)(?:[^\s`](?:[^`]{0,46}[^\s`])?|[^\s`])`([^\w]|$)/,yt=/(?:^|\n)\s{0,5}-\s{1}[^\n]+\n\s{0,15}-\s/,Ct=/(?:^|\n)\s{0,5}\d+\.\s{1}[^\n]+\n\s{0,15}\d+\.\s/,Et=/\n{2} {0,3}-{2,48}\n{2}/,Tt=/(?:\n|^)(```|~~~|\$\$)(?!`|~)[^\s]{0,64} {0,64}[^\n]{0,64}\n[\s\S]{0,9999}?\s*\1 {0,64}(?:\n+|$)/,xt=/(?:\n|^)(?!\s)\w[^\n]{0,64}\r?\n(-|=)\1{0,64}\n\n\s{0,64}(\w|$)/,Mt=/(?:^|(\r?\n\r?\n))( {0,3}>[^\n]{1,333}\n){1,999}($|(\r?\n))/,It=/^\s*\|(.+\|)+\s*$/m,Pt=/^\s*\|(\s*[-:]+[-:]\s*\|)+\s*$/m,wt=/^\s*\|(.+\|)+\s*$/m,vt=o=>gt.test(o)||bt.test(o)||St.test(o)||Bt.test(o)||yt.test(o)||Ct.test(o)||Et.test(o)||Tt.test(o)||xt.test(o)||Mt.test(o)||It.test(o)||Pt.test(o)||wt.test(o);async function At(o,e){const{schema:t}=e.state;if(!o.clipboardData)return!1;const n=o.clipboardData.getData("text/plain");if(!n)return!1;if(!t.nodes.codeBlock)return e.pasteText(n),!0;const r=o.clipboardData.getData("vscode-editor-data"),s=r?JSON.parse(r):void 0,i=s==null?void 0:s.mode;return i?(e.pasteHTML(`<pre><code class="language-${i}">${n.replace(/\r\n?/g,`
+`);throw Error("Blocks with the following IDs could not be found in the editor: "+f)}return l.forEach(f=>D(o,f)),{insertedBlocks:r.map(f=>u.nodeToBlock(f,n)),removedBlocks:i}}function Ve(o,e,t,n,r){let s;if(e)if(typeof e=="string")s=u.inlineContentToNodes([e],o.pmSchema,n);else if(Array.isArray(e))s=u.inlineContentToNodes(e,o.pmSchema,n);else if(e.type==="tableContent")s=u.tableContentToNodes(e,o.pmSchema);else throw new u.UnreachableCaseError(e.type);else throw new Error("blockContent is required");const l=((r==null?void 0:r.document)??document).createDocumentFragment();for(const a of s)if(a.type.name!=="text"&&o.schema.inlineContentSchema[a.type.name]){const d=o.schema.inlineContentSpecs[a.type.name].implementation;if(d){const p=u.nodeToCustomInlineContent(a,o.schema.inlineContentSchema,o.schema.styleSchema),f=d.render.call({renderType:"dom",props:void 0},p,()=>{},o);if(f){if(l.appendChild(f.dom),f.contentDOM){const h=t.serializeFragment(a.content,r);f.contentDOM.dataset.editable="",f.contentDOM.appendChild(h)}continue}}}else if(a.type.name==="text"){let d=document.createTextNode(a.textContent);for(const p of Array.from(a.marks).reverse())if(p.type.name in o.schema.styleSpecs){const f=o.schema.styleSpecs[p.type.name].implementation.render(p.attrs.stringValue,o);f.contentDOM.appendChild(d),d=f.dom}else{const f=p.type.spec.toDOM(p,!0),h=x.DOMSerializer.renderSpec(document,f);h.contentDOM.appendChild(d),d=h.dom}l.appendChild(d)}else{const d=t.serializeFragment(x.Fragment.from([a]),r);l.appendChild(d)}return l}function Re(o,e,t,n){var f,h,g,m,S;const r=o.pmSchema.nodes.blockContainer,s=e.props||{};for(const[y,E]of Object.entries(o.schema.blockSchema[e.type].propSchema))!(y in s)&&E.default!==void 0&&(s[y]=E.default);const i=e.children||[],a=o.blockImplementations[e.type].implementation.render.call({renderType:"dom",props:void 0},{...e,props:s,children:i},o);if(a.contentDOM&&e.content){const y=Ve(o,e.content,t,e.type,n);a.contentDOM.appendChild(y)}if(o.pmSchema.nodes[e.type].isInGroup("bnBlock")){if(e.children&&e.children.length>0){const y=se(o,e.children,t,n);(f=a.contentDOM)==null||f.append(y)}return a.dom}const p=(g=(h=r.spec)==null?void 0:h.toDOM)==null?void 0:g.call(h,r.create({id:e.id,...s}));return(m=p.contentDOM)==null||m.appendChild(a.dom),e.children&&e.children.length>0&&((S=p.contentDOM)==null||S.appendChild(ie(o,e.children,t,n))),p.dom}function se(o,e,t,n){const s=((n==null?void 0:n.document)??document).createDocumentFragment();for(const i of e){const l=Re(o,i,t,n);s.appendChild(l)}return s}const ie=(o,e,t,n)=>{var l;const r=o.pmSchema.nodes.blockGroup,s=r.spec.toDOM(r.create({})),i=se(o,e,t,n);return(l=s.contentDOM)==null||l.appendChild(i),s.dom},ze=o=>(o.querySelectorAll('[data-content-type="numberedListItem"]').forEach(t=>{var r,s;const n=(s=(r=t.closest(".bn-block-outer"))==null?void 0:r.previousElementSibling)==null?void 0:s.querySelector('[data-content-type="numberedListItem"]');if(!n)t.setAttribute("data-index",t.getAttribute("data-start")||"1");else{const i=n.getAttribute("data-index");t.setAttribute("data-index",(parseInt(i||"0")+1).toString())}}),o),Ge=o=>(o.querySelectorAll('[data-content-type="checkListItem"] input').forEach(t=>{t.disabled=!0}),o),qe=o=>(o.querySelectorAll('.bn-toggle-wrapper[data-show-children="false"]').forEach(t=>{t.setAttribute("data-show-children","true")}),o),We=o=>(o.querySelectorAll('[data-content-type="table"] table').forEach(t=>{t.setAttribute("style",`--default-cell-min-width: ${c.EMPTY_CELL_WIDTH}px;`),t.setAttribute("data-show-children","true")}),o),je=o=>(o.querySelectorAll('[data-content-type="table"] table').forEach(t=>{var s;const n=document.createElement("div");n.className="tableWrapper";const r=document.createElement("div");r.className="tableWrapper-inner",n.appendChild(r),(s=t.parentElement)==null||s.appendChild(n),n.appendChild(t)}),o),Ke=o=>(o.querySelectorAll(".bn-inline-content:empty").forEach(t=>{const n=document.createElement("span");n.className="ProseMirror-trailingBreak",n.setAttribute("style","display: inline-block;"),t.appendChild(n)}),o),ce=(o,e)=>{const t=x.DOMSerializer.fromSchema(o),n=[ze,Ge,qe,We,je,Ke];return{serializeBlocks:(r,s)=>{let i=ie(e,r,t,s);for(const l of n)i=l(i);return i.outerHTML}}};function Ye(o){return o.transact(e=>{const t=u.getNearestBlockPos(e.doc,e.selection.anchor);if(e.selection instanceof N.CellSelection)return{type:"cell",anchorBlockId:t.node.attrs.id,anchorCellOffset:e.selection.$anchorCell.pos-t.posBeforeNode,headCellOffset:e.selection.$headCell.pos-t.posBeforeNode};if(e.selection instanceof C.NodeSelection)return{type:"node",anchorBlockId:t.node.attrs.id};{const n=u.getNearestBlockPos(e.doc,e.selection.head);return{type:"text",anchorBlockId:t.node.attrs.id,headBlockId:n.node.attrs.id,anchorOffset:e.selection.anchor-t.posBeforeNode,headOffset:e.selection.head-n.posBeforeNode}}})}function Je(o,e){var r,s;const t=(r=c.getNodeById(e.anchorBlockId,o.doc))==null?void 0:r.posBeforeNode;if(t===void 0)throw new Error(`Could not find block with ID ${e.anchorBlockId} to update selection`);let n;if(e.type==="cell")n=N.CellSelection.create(o.doc,t+e.anchorCellOffset,t+e.headCellOffset);else if(e.type==="node")n=C.NodeSelection.create(o.doc,t+1);else{const i=(s=c.getNodeById(e.headBlockId,o.doc))==null?void 0:s.posBeforeNode;if(i===void 0)throw new Error(`Could not find block with ID ${e.headBlockId} to update selection`);n=C.TextSelection.create(o.doc,t+e.anchorOffset,i+e.headOffset)}o.setSelection(n)}function U(o){return o.map(e=>e.type==="columnList"?e.children.map(t=>U(t.children)).flat():{...e,children:U(e.children)}).flat()}function ae(o,e,t){o.transact(n=>{var i;const r=((i=o.getSelection())==null?void 0:i.blocks)||[o.getTextCursorPosition().block],s=Ye(o);o.removeBlocks(r),o.insertBlocks(U(r),e,t),Je(n,s)})}function le(o){return!o||o.type!=="columnList"}function de(o,e,t){let n,r;if(e?e.children.length>0?(n=e.children[e.children.length-1],r="after"):(n=e,r="before"):t&&(n=t,r="before"),!n||!r)return;const s=o.getParentBlock(n);return le(s)?{referenceBlock:n,placement:r}:de(o,r==="after"?n:o.getPrevBlock(n),s)}function ue(o,e,t){let n,r;if(e?e.children.length>0?(n=e.children[0],r="before"):(n=e,r="after"):t&&(n=t,r="after"),!n||!r)return;const s=o.getParentBlock(n);return le(s)?{referenceBlock:n,placement:r}:ue(o,r==="before"?n:o.getNextBlock(n),s)}function Qe(o){o.transact(()=>{const e=o.getSelection(),t=(e==null?void 0:e.blocks[0])||o.getTextCursorPosition().block,n=de(o,o.getPrevBlock(t),o.getParentBlock(t));n&&ae(o,n.referenceBlock,n.placement)})}function Xe(o){o.transact(()=>{const e=o.getSelection(),t=(e==null?void 0:e.blocks[(e==null?void 0:e.blocks.length)-1])||o.getTextCursorPosition().block,n=ue(o,o.getNextBlock(t),o.getParentBlock(t));n&&ae(o,n.referenceBlock,n.placement)})}function Ze(o,e,t){const{$from:n,$to:r}=o.selection,s=n.blockRange(r,m=>m.childCount>0&&(m.type.name==="blockGroup"||m.type.name==="column"));if(!s)return!1;const i=s.startIndex;if(i===0)return!1;const a=s.parent.child(i-1);if(a.type!==e)return!1;const d=a.lastChild&&a.lastChild.type===t,p=x.Fragment.from(d?e.create():null),f=new x.Slice(x.Fragment.from(e.create(null,x.Fragment.from(t.create(null,p)))),d?3:1,0),h=s.start,g=s.end;return o.step(new L.ReplaceAroundStep(h-(d?3:1),g,h,g,f,1,!0)).scrollIntoView(),!0}function pe(o){return o.transact(e=>Ze(e,o.pmSchema.nodes.blockContainer,o.pmSchema.nodes.blockGroup))}function et(o){o._tiptapEditor.commands.liftListItem("blockContainer")}function tt(o){return o.transact(e=>{const{bnBlock:t}=u.getBlockInfoFromTransaction(e);return e.doc.resolve(t.beforePos).nodeBefore!==null})}function ot(o){return o.transact(e=>{const{bnBlock:t}=u.getBlockInfoFromTransaction(e);return e.doc.resolve(t.beforePos).depth>1})}function fe(o,e){const t=typeof e=="string"?e:e.id,n=u.getPmSchema(o),r=c.getNodeById(t,o);if(r)return u.nodeToBlock(r.node,n)}function he(o,e){const t=typeof e=="string"?e:e.id,n=c.getNodeById(t,o),r=u.getPmSchema(o);if(!n)return;const i=o.resolve(n.posBeforeNode).nodeBefore;if(i)return u.nodeToBlock(i,r)}function me(o,e){const t=typeof e=="string"?e:e.id,n=c.getNodeById(t,o),r=u.getPmSchema(o);if(!n)return;const i=o.resolve(n.posBeforeNode+n.node.nodeSize).nodeAfter;if(i)return u.nodeToBlock(i,r)}function ke(o,e){const t=typeof e=="string"?e:e.id,n=u.getPmSchema(o),r=c.getNodeById(t,o);if(!r)return;const s=o.resolve(r.posBeforeNode),i=s.node(),l=s.node(-1),a=l.type.name!=="doc"?i.type.name==="blockGroup"?l:i:void 0;if(a)return u.nodeToBlock(a,n)}class nt{constructor(e){this.editor=e}get document(){return this.editor.transact(e=>u.docToBlocks(e.doc,this.editor.pmSchema))}getBlock(e){return this.editor.transact(t=>fe(t.doc,e))}getPrevBlock(e){return this.editor.transact(t=>he(t.doc,e))}getNextBlock(e){return this.editor.transact(t=>me(t.doc,e))}getParentBlock(e){return this.editor.transact(t=>ke(t.doc,e))}forEachBlock(e,t=!1){const n=this.document.slice();t&&n.reverse();function r(s){for(const i of s){if(e(i)===!1)return!1;const l=t?i.children.slice().reverse():i.children;if(!r(l))return!1}return!0}r(n)}insertBlocks(e,t,n="before"){return this.editor.transact(r=>ne(r,e,t,n))}updateBlock(e,t){return this.editor.transact(n=>c.updateBlock(n,e,t))}removeBlocks(e){return this.editor.transact(t=>$(t,e,[]).removedBlocks)}replaceBlocks(e,t){return this.editor.transact(n=>$(n,e,t))}canNestBlock(){return tt(this.editor)}nestBlock(){pe(this.editor)}canUnnestBlock(){return ot(this.editor)}unnestBlock(){et(this.editor)}moveBlocksUp(){return Qe(this.editor)}moveBlocksDown(){return Xe(this.editor)}}class rt extends R.EventEmitter{constructor(e){super(),this.editor=e,e.on("create",()=>{e._tiptapEditor.on("update",({transaction:t,appendedTransactions:n})=>{this.emit("onChange",{editor:e,transaction:t,appendedTransactions:n})}),e._tiptapEditor.on("selectionUpdate",({transaction:t})=>{this.emit("onSelectionChange",{editor:e,transaction:t})}),e._tiptapEditor.on("mount",()=>{this.emit("onMount",{editor:e})}),e._tiptapEditor.on("unmount",()=>{this.emit("onUnmount",{editor:e})})})}onChange(e,t=!0){const n=({transaction:r,appendedTransactions:s})=>{!t&&Y(r)||e(this.editor,{getChanges(){return b.getBlocksChangedByTransaction(r,s)}})};return this.on("onChange",n),()=>{this.off("onChange",n)}}onSelectionChange(e,t=!1){const n=r=>{!t&&Y(r.transaction)||e(this.editor)};return this.on("onSelectionChange",n),()=>{this.off("onSelectionChange",n)}}onMount(e){return this.on("onMount",e),()=>{this.off("onMount",e)}}onUnmount(e){return this.on("onUnmount",e),()=>{this.off("onUnmount",e)}}}function Y(o){return!!o.getMeta("y-sync$")}function st(o){return Array.prototype.indexOf.call(o.parentElement.childNodes,o)}function it(o){return o.nodeType===3&&!/\S/.test(o.nodeValue||"")}function ct(o){o.querySelectorAll("li > ul, li > ol").forEach(e=>{const t=st(e),n=e.parentElement,r=Array.from(n.childNodes).slice(t+1);e.remove(),r.forEach(s=>{s.remove()}),n.insertAdjacentElement("afterend",e),r.reverse().forEach(s=>{if(it(s))return;const i=document.createElement("li");i.append(s),e.insertAdjacentElement("afterend",i)}),n.childNodes.length===0&&n.remove()})}function at(o){o.querySelectorAll("li + ul, li + ol").forEach(e=>{var s,i;const t=e.previousElementSibling,n=document.createElement("div");t.insertAdjacentElement("afterend",n),n.append(t);const r=document.createElement("div");for(r.setAttribute("data-node-type","blockGroup"),n.append(r);((s=n.nextElementSibling)==null?void 0:s.nodeName)==="UL"||((i=n.nextElementSibling)==null?void 0:i.nodeName)==="OL";)r.append(n.nextElementSibling)})}let J=null;function lt(){return J||(J=document.implementation.createHTMLDocument("title"))}function dt(o){if(typeof o=="string"){const e=lt().createElement("div");e.innerHTML=o,o=e}return ct(o),at(o),o}function z(o,e){const t=dt(o),r=x.DOMParser.fromSchema(e).parse(t,{topNode:e.nodes.blockGroup.create()}),s=[];for(let i=0;i<r.childCount;i++)s.push(u.nodeToBlock(r.child(i),e));return s}function ut(o,e){const t=e.value?e.value:"",n={};e.lang&&(n["data-language"]=e.lang);let r={type:"element",tagName:"code",properties:n,children:[{type:"text",value:t}]};return e.meta&&(r.data={meta:e.meta}),o.patch(e,r),r=o.applyData(e,r),r={type:"element",tagName:"pre",properties:{},children:[r]},o.patch(e,r),r}function pt(o,e){var s;const t=String((e==null?void 0:e.url)||""),n=e!=null&&e.title?String(e.title):void 0;let r={type:"element",tagName:"video",properties:{src:t,"data-name":n,"data-url":t,controls:!0},children:[]};return(s=o.patch)==null||s.call(o,e,r),r=o.applyData?o.applyData(e,r):r,r}function G(o){return _e.unified().use(Oe.default).use(Fe.default).use(He.default,{handlers:{...H.defaultHandlers,image:(t,n)=>{const r=String((n==null?void 0:n.url)||"");return c.isVideoUrl(r)?pt(t,n):H.defaultHandlers.image(t,n)},code:ut,blockquote:(t,n)=>{const r={type:"element",tagName:"blockquote",properties:{},children:t.wrap(t.all(n),!1)};return t.patch(n,r),t.applyData(n,r)}}}).use($e.default).processSync(o).value}function ge(o,e){const t=G(o);return z(t,e)}class ft{constructor(e){this.editor=e}blocksToHTMLLossy(e=this.editor.document){return b.createExternalHTMLExporter(this.editor.pmSchema,this.editor).exportBlocks(e,{})}blocksToFullHTML(e=this.editor.document){return ce(this.editor.pmSchema,this.editor).serializeBlocks(e,{})}tryParseHTMLToBlocks(e){return z(e,this.editor.pmSchema)}blocksToMarkdownLossy(e=this.editor.document){return b.blocksToMarkdown(e,this.editor.pmSchema,this.editor,{})}tryParseMarkdownToBlocks(e){return ge(e,this.editor.pmSchema)}pasteHTML(e,t=!1){var r;let n=e;if(!t){const s=this.tryParseHTMLToBlocks(e);n=this.blocksToFullHTML(s)}n&&((r=this.editor.prosemirrorView)==null||r.pasteHTML(n))}pasteText(e){var t;return(t=this.editor.prosemirrorView)==null?void 0:t.pasteText(e)}pasteMarkdown(e){const t=G(e);return this.pasteHTML(t)}}const q=["vscode-editor-data","blocknote/html","text/markdown","text/html","text/plain","Files"];function ht(o,e){if(!o.startsWith(".")||!e.startsWith("."))throw new Error("The strings provided are not valid file extensions.");return o===e}function mt(o,e){const t=o.split("/"),n=e.split("/");if(t.length!==2)throw new Error(`The string ${o} is not a valid MIME type.`);if(n.length!==2)throw new Error(`The string ${e} is not a valid MIME type.`);return t[1]==="*"||n[1]==="*"?t[0]===n[0]:(t[0]==="*"||n[0]==="*"||t[0]===n[0])&&t[1]===n[1]}function Q(o,e,t,n="after"){let r;return Array.isArray(e.content)&&e.content.length===0?r=o.updateBlock(e,t).id:r=o.insertBlocks([t],e,n)[0].id,r}async function be(o,e){var s;if(!e.uploadFile){console.warn("Attempted ot insert file, but uploadFile is not set in the BlockNote editor options");return}const t="dataTransfer"in o?o.dataTransfer:o.clipboardData;if(t===null)return;let n=null;for(const i of q)if(t.types.includes(i)){n=i;break}if(n!=="Files")return;const r=t.items;if(r){o.preventDefault();for(let i=0;i<r.length;i++){let l="file";for(const d of Object.values(e.schema.blockSpecs))for(const p of((s=d.implementation.meta)==null?void 0:s.fileBlockAccept)||[]){const f=p.startsWith("."),h=r[i].getAsFile();if(h&&(!f&&h.type&&mt(r[i].type,p)||f&&ht("."+h.name.split(".").pop(),p))){l=d.config.type;break}}const a=r[i].getAsFile();if(a){const d={type:l,props:{name:a.name}};let p;if(o.type==="paste"){const g=e.getTextCursorPosition().block;p=Q(e,g,d)}else if(o.type==="drop"){const g={left:o.clientX,top:o.clientY},m=e.prosemirrorView.posAtCoords(g);if(!m)return;p=e.transact(S=>{var T;const y=u.getNearestBlockPos(S.doc,m.pos),E=(T=e.domElement)==null?void 0:T.querySelector(`[data-id="${y.node.attrs.id}"]`),P=E==null?void 0:E.getBoundingClientRect();return Q(e,e.getBlock(y.node.attrs.id),d,P&&(P.top+P.bottom)/2>g.top?"before":"after")})}else return;const f=await e.uploadFile(a,p),h=typeof f=="string"?{props:{url:f}}:{...f};e.updateBlock(p,h)}}}}const kt=o=>B.Extension.create({name:"dropFile",addProseMirrorPlugins(){return[new C.Plugin({props:{handleDOMEvents:{drop(e,t){if(!o.isEditable)return;let n=null;for(const r of q)if(t.dataTransfer.types.includes(r)){n=r;break}return n===null?!0:n==="Files"?(be(t,o),!0):!1}}}})]}}),gt=/(^|\n) {0,3}#{1,6} {1,8}[^\n]{1,64}\r?\n\r?\n\s{0,32}\S/,bt=/(_|__|\*|\*\*|~~|==|\+\+)(?!\s)(?:[^\s](?:.{0,62}[^\s])?|\S)(?=\1)/,St=/\[[^\]]{1,128}\]\(https?:\/\/\S{1,999}\)/,Bt=/(?:\s|^)`(?!\s)(?:[^\s`](?:[^`]{0,46}[^\s`])?|[^\s`])`([^\w]|$)/,yt=/(?:^|\n)\s{0,5}-\s{1}[^\n]+\n\s{0,15}-\s/,Ct=/(?:^|\n)\s{0,5}\d+\.\s{1}[^\n]+\n\s{0,15}\d+\.\s/,Et=/\n{2} {0,3}-{2,48}\n{2}/,Tt=/(?:\n|^)(```|~~~|\$\$)(?!`|~)[^\s]{0,64} {0,64}[^\n]{0,64}\n[\s\S]{0,9999}?\s*\1 {0,64}(?:\n+|$)/,xt=/(?:\n|^)(?!\s)\w[^\n]{0,64}\r?\n(-|=)\1{0,64}\n\n\s{0,64}(\w|$)/,Mt=/(?:^|(\r?\n\r?\n))( {0,3}>[^\n]{1,333}\n){1,999}($|(\r?\n))/,It=/^\s*\|(.+\|)+\s*$/m,Pt=/^\s*\|(\s*[-:]+[-:]\s*\|)+\s*$/m,wt=/^\s*\|(.+\|)+\s*$/m,vt=o=>gt.test(o)||bt.test(o)||St.test(o)||Bt.test(o)||yt.test(o)||Ct.test(o)||Et.test(o)||Tt.test(o)||xt.test(o)||Mt.test(o)||It.test(o)||Pt.test(o)||wt.test(o);async function At(o,e){const{schema:t}=e.state;if(!o.clipboardData)return!1;const n=o.clipboardData.getData("text/plain");if(!n)return!1;if(!t.nodes.codeBlock)return e.pasteText(n),!0;const r=o.clipboardData.getData("vscode-editor-data"),s=r?JSON.parse(r):void 0,i=s==null?void 0:s.mode;return i?(e.pasteHTML(`<pre><code class="language-${i}">${n.replace(/\r\n?/g,`
`)}</code></pre>`),!0):!1}function Nt({event:o,editor:e,prioritizeMarkdownOverHTML:t,plainTextAsMarkdown:n}){var l;if(e.transact(a=>a.selection.$from.parent.type.spec.code&&a.selection.$to.parent.type.spec.code)){const a=(l=o.clipboardData)==null?void 0:l.getData("text/plain");if(a)return e.pasteText(a),!0}let s;for(const a of q)if(o.clipboardData.types.includes(a)){s=a;break}if(!s)return!0;if(s==="vscode-editor-data")return At(o,e.prosemirrorView),!0;if(s==="Files")return be(o,e),!0;const i=o.clipboardData.getData(s);if(s==="blocknote/html")return e.pasteHTML(i,!0),!0;if(s==="text/markdown")return e.pasteMarkdown(i),!0;if(t){const a=o.clipboardData.getData("text/plain");if(vt(a))return e.pasteMarkdown(a),!0}return s==="text/html"?(e.pasteHTML(i),!0):n?(e.pasteMarkdown(i),!0):(e.pasteText(i),!0)}const Lt=(o,e)=>B.Extension.create({name:"pasteFromClipboard",addProseMirrorPlugins(){return[new C.Plugin({props:{handleDOMEvents:{paste(t,n){if(n.preventDefault(),!!o.isEditable)return e({event:n,editor:o,defaultPasteHandler:({prioritizeMarkdownOverHTML:r=!0,plainTextAsMarkdown:s=!0}={})=>Nt({event:n,editor:o,prioritizeMarkdownOverHTML:r,plainTextAsMarkdown:s})})}}}})]}});function _t(o,e,t){var l;let n=!1;const r=o.state.selection instanceof N.CellSelection;if(!r){const a=o.state.doc.slice(o.state.selection.from,o.state.selection.to,!1).content,d=[];for(let p=0;p<a.childCount;p++)d.push(a.child(p));n=d.find(p=>p.type.isInGroup("bnBlock")||p.type.name==="blockGroup"||p.type.spec.group==="blockContent")===void 0,n&&(e=a)}let s;const i=b.createExternalHTMLExporter(o.state.schema,t);if(r){((l=e.firstChild)==null?void 0:l.type.name)==="table"&&(e=e.firstChild.content);const a=u.contentNodeToTableContent(e,t.schema.inlineContentSchema,t.schema.styleSchema);s=`<table>${i.exportInlineContent(a,{})}</table>`}else if(n){const a=u.contentNodeToInlineContent(e,t.schema.inlineContentSchema,t.schema.styleSchema);s=i.exportInlineContent(a,{})}else{const a=b.fragmentToBlocks(e);s=i.exportBlocks(a,{})}return s}function W(o,e){"node"in o.state.selection&&o.state.selection.node.type.spec.group==="blockContent"&&e.transact(i=>i.setSelection(new C.NodeSelection(i.doc.resolve(o.state.selection.from-1))));const t=o.serializeForClipboard(o.state.selection.content()).dom.innerHTML,n=o.state.selection.content().content,r=_t(o,n,e),s=b.cleanHTMLToMarkdown(r);return{clipboardHTML:t,externalHTML:r,markdown:s}}const X=()=>{const o=window.getSelection();if(!o||o.isCollapsed)return!0;let e=o.focusNode;for(;e;){if(e instanceof HTMLElement&&e.getAttribute("contenteditable")==="false")return!0;e=e.parentElement}return!1},Z=(o,e,t)=>{t.preventDefault(),t.clipboardData.clearData();const{clipboardHTML:n,externalHTML:r,markdown:s}=W(e,o);t.clipboardData.setData("blocknote/html",n),t.clipboardData.setData("text/html",r),t.clipboardData.setData("text/plain",s)},Dt=o=>B.Extension.create({name:"copyToClipboard",addProseMirrorPlugins(){return[new C.Plugin({props:{handleDOMEvents:{copy(e,t){return X()||Z(o,e,t),!0},cut(e,t){return X()||(Z(o,e,t),e.editable&&e.dispatch(e.state.tr.deleteSelection())),!0},dragstart(e,t){if(!("node"in e.state.selection)||e.state.selection.node.type.spec.group!=="blockContent")return;o.transact(i=>i.setSelection(new C.NodeSelection(i.doc.resolve(e.state.selection.from-1)))),t.preventDefault(),t.dataTransfer.clearData();const{clipboardHTML:n,externalHTML:r,markdown:s}=W(e,o);return t.dataTransfer.setData("blocknote/html",n),t.dataTransfer.setData("text/html",r),t.dataTransfer.setData("text/plain",s),!0}}}})]}}),Ft=B.Extension.create({name:"blockBackgroundColor",addGlobalAttributes(){return[{types:["tableCell","tableHeader"],attributes:{backgroundColor:c.getBackgroundColorAttribute()}}]}}),Ot=B.Node.create({name:"hardBreak",inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,priority:10,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:o}){return["br",B.mergeAttributes(this.options.HTMLAttributes,o)]},renderText(){return`
`}}),V=(o,e)=>{const t=o.resolve(e),n=t.index();if(n===0)return;const r=t.posAtIndex(n-1);return u.getBlockInfoFromResolvedPos(o.resolve(r))},Se=(o,e)=>{for(;e.childContainer;){const t=e.childContainer.node,n=o.resolve(e.childContainer.beforePos+1).posAtIndex(t.childCount-1);e=u.getBlockInfoFromResolvedPos(o.resolve(n))}return e},Ht=(o,e)=>o.isBlockContainer&&o.blockContent.node.type.spec.content==="inline*"&&o.blockContent.node.childCount>0&&e.isBlockContainer&&e.blockContent.node.type.spec.content==="inline*",$t=(o,e,t,n)=>{if(!n.isBlockContainer)throw new Error(`Attempted to merge block at position ${n.bnBlock.beforePos} into previous block at position ${t.bnBlock.beforePos}, but next block is not a block container`);if(n.childContainer){const r=o.doc.resolve(n.childContainer.beforePos+1),s=o.doc.resolve(n.childContainer.afterPos-1),i=r.blockRange(s);if(e){const l=o.doc.resolve(n.bnBlock.beforePos);o.tr.lift(i,l.depth)}}if(e){if(!t.isBlockContainer)throw new Error(`Attempted to merge block at position ${n.bnBlock.beforePos} into previous block at position ${t.bnBlock.beforePos}, but previous block is not a block container`);e(o.tr.delete(t.blockContent.afterPos-1,n.blockContent.beforePos+1))}return!0},ee=o=>({state:e,dispatch:t})=>{const n=e.doc.resolve(o),r=u.getBlockInfoFromResolvedPos(n),s=V(e.doc,r.bnBlock.beforePos);if(!s)return!1;const i=Se(e.doc,s);return Ht(i,r)?$t(e,t,i,r):!1},Ut=B.Extension.create({priority:50,addKeyboardShortcuts(){const o=()=>this.editor.commands.first(({chain:n,commands:r})=>[()=>r.deleteSelection(),()=>r.undoInputRule(),()=>r.command(({state:s})=>{const i=u.getBlockInfoFromSelection(s);if(!i.isBlockContainer)return!1;const l=s.selection.from===i.blockContent.beforePos+1,a=i.blockContent.node.type.name==="paragraph";return l&&!a?r.command(c.updateBlockCommand(i.bnBlock.beforePos,{type:"paragraph",props:{}})):!1}),()=>r.command(({state:s})=>{const i=u.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=u.getBlockInfoFromSelection(s);if(!i.isBlockContainer)return!1;const{bnBlock:l,blockContent:a}=i,d=s.selection.from===a.beforePos+1,p=s.selection.empty,f=l.beforePos;return d&&p?n().command(ee(f)).scrollIntoView().run():!1}),()=>r.command(({state:s,tr:i,dispatch:l})=>{const a=u.getBlockInfoFromSelection(s);if(!a.isBlockContainer||!(i.selection.from===a.blockContent.beforePos+1))return!1;const p=i.doc.resolve(a.bnBlock.beforePos);if(p.nodeBefore||p.node().type.name!=="column")return!1;const g=i.doc.resolve(a.bnBlock.beforePos),m=i.doc.resolve(g.before()),S=m.before();if(l){const y=i.doc.slice(a.bnBlock.beforePos,a.bnBlock.afterPos).content;i.delete(a.bnBlock.beforePos,a.bnBlock.afterPos),m.index()===0?(D(i,S),i.insert(S,y),i.setSelection(C.TextSelection.near(i.doc.resolve(S)))):(i.insert(m.pos-1,y),i.setSelection(C.TextSelection.near(i.doc.resolve(m.pos-1))),D(i,S))}return!0}),()=>r.command(({state:s})=>{const i=u.getBlockInfoFromSelection(s);if(!i.isBlockContainer)return!1;if(i.blockContent.node.childCount===0&&i.blockContent.node.type.spec.content==="inline*"){const a=V(s.doc,i.bnBlock.beforePos);if(!a||!a.isBlockContainer)return!1;let d=n();if(a.blockContent.node.type.spec.content==="tableRow+"){const m=i.bnBlock.beforePos-1-1-1-1-1;d=d.setTextSelection(m)}else if(a.blockContent.node.type.spec.content===""){const p=a.blockContent.afterPos-a.blockContent.node.nodeSize;d=d.setNodeSelection(p)}else{const p=a.blockContent.afterPos-a.blockContent.node.nodeSize;d=d.setTextSelection(p)}return d.deleteRange({from:i.bnBlock.beforePos,to:i.bnBlock.afterPos}).scrollIntoView().run()}return!1}),()=>r.command(({state:s})=>{const i=u.getBlockInfoFromSelection(s);if(!i.isBlockContainer)throw new Error("todo");const l=s.selection.from===i.blockContent.beforePos+1,a=s.selection.empty,d=V(s.doc,i.bnBlock.beforePos);if(d&&l&&a){const p=Se(s.doc,d);if(!p.isBlockContainer)throw new Error("todo");if(p.blockContent.node.type.spec.content===""||p.blockContent.node.type.spec.content==="inline*"&&p.blockContent.node.childCount===0)return n().cut({from:i.bnBlock.beforePos,to:i.bnBlock.afterPos},p.bnBlock.afterPos).deleteRange({from:p.bnBlock.beforePos,to:p.bnBlock.afterPos}).run()}return!1})]),e=()=>this.editor.commands.first(({commands:n})=>[()=>n.deleteSelection(),()=>n.command(({state:r})=>{const s=u.getBlockInfoFromSelection(r);if(!s.isBlockContainer)return!1;const{bnBlock:i,blockContent:l,childContainer:a}=s,{depth:d}=r.doc.resolve(i.beforePos),p=i.afterPos===r.doc.nodeSize-3,f=r.selection.from===l.afterPos-1,h=r.selection.empty;if(!p&&f&&h&&!(a!==void 0)){let m=d,S=i.afterPos+1,y=r.doc.resolve(S).depth;for(;y<m;)m=y,S+=2,y=r.doc.resolve(S).depth;return n.command(ee(S-1))}return!1})]),t=(n=!1)=>this.editor.commands.first(({commands:r,tr:s})=>[()=>r.command(({state:i})=>{const l=u.getBlockInfoFromSelection(i);if(!l.isBlockContainer)return!1;const{bnBlock:a,blockContent:d}=l,{depth:p}=i.doc.resolve(a.beforePos),f=i.selection.$anchor.parentOffset===0,h=i.selection.anchor===i.selection.head,g=d.node.childCount===0,m=p>1;return f&&h&&g&&m?r.liftListItem("blockContainer"):!1}),()=>r.command(({state:i})=>{var d;const l=u.getBlockInfoFromSelection(i),a=((d=this.options.editor.schema.blockSchema[l.blockNoteType].meta)==null?void 0:d.hardBreakShortcut)??"shift+enter";if(a==="none")return!1;if(a==="shift+enter"&&n||a==="enter"){const p=s.storedMarks||s.selection.$head.marks().filter(f=>this.editor.extensionManager.splittableMarks.includes(f.type.name));return s.insert(s.selection.head,s.doc.type.schema.nodes.hardBreak.create()).ensureMarks(p),!0}return!1}),()=>r.command(({state:i,dispatch:l})=>{const a=u.getBlockInfoFromSelection(i);if(!a.isBlockContainer)return!1;const{bnBlock:d,blockContent:p}=a,f=i.selection.$anchor.parentOffset===0,h=i.selection.anchor===i.selection.head,g=p.node.childCount===0;if(f&&h&&g){const m=d.afterPos,S=m+2;if(l){const y=i.schema.nodes.blockContainer.createAndFill();i.tr.insert(m,y).scrollIntoView(),i.tr.setSelection(new C.TextSelection(i.doc.resolve(S)))}return!0}return!1}),()=>r.command(({state:i,chain:l})=>{const a=u.getBlockInfoFromSelection(i);if(!a.isBlockContainer)return!1;const{blockContent:d}=a,p=i.selection.$anchor.parentOffset===0;return d.node.childCount===0?!1:(l().deleteSelection().command(c.splitBlockCommand(i.selection.from,p,p)).run(),!0)})]);return{Backspace:o,Delete:e,Enter:()=>t(),"Shift-Enter":()=>t(!0),Tab:()=>{var n,r;return this.options.tabBehavior!=="prefer-indent"&&((n=this.options.editor.getExtension(b.FormattingToolbarExtension))!=null&&n.store.state||((r=this.options.editor.getExtension(c.FilePanelExtension))==null?void 0:r.store.state)!==void 0)?!1:pe(this.options.editor)},"Shift-Tab":()=>{var n,r;return this.options.tabBehavior!=="prefer-indent"&&((n=this.options.editor.getExtension(b.FormattingToolbarExtension))!=null&&n.store.state||((r=this.options.editor.getExtension(c.FilePanelExtension))==null?void 0:r.store.state)!==void 0)?!1:this.editor.commands.liftListItem("blockContainer")},"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()}}}),Vt=B.Mark.create({name:"insertion",inclusive:!1,excludes:"deletion modification insertion",addAttributes(){return{id:{default:null,validate:"number"}}},extendMarkSchema(o){return o.name!=="insertion"?{}:{blocknoteIgnore:!0,inclusive:!1,toDOM(e,t){return["ins",{"data-id":String(e.attrs.id),"data-inline":String(t),...!t&&{style:"display: contents"}},0]},parseDOM:[{tag:"ins",getAttrs(e){return e.dataset.id?{id:parseInt(e.dataset.id,10)}:!1}}]}}}),Rt=B.Mark.create({name:"deletion",inclusive:!1,excludes:"insertion modification deletion",addAttributes(){return{id:{default:null,validate:"number"}}},extendMarkSchema(o){return o.name!=="deletion"?{}:{blocknoteIgnore:!0,inclusive:!1,toDOM(e,t){return["del",{"data-id":String(e.attrs.id),"data-inline":String(t),...!t&&{style:"display: contents"}},0]},parseDOM:[{tag:"del",getAttrs(e){return e.dataset.id?{id:parseInt(e.dataset.id,10)}:!1}}]}}}),zt=B.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(o){return o.name!=="modification"?{}:{blocknoteIgnore:!0,inclusive:!1,toDOM(e,t){return[t?"span":"div",{"data-type":"modification","data-id":String(e.attrs.id),"data-mod-type":e.attrs.type,"data-mod-prev-val":JSON.stringify(e.attrs.previousValue),"data-mod-new-val":JSON.stringify(e.attrs.newValue)},0]},parseDOM:[{tag:"span[data-type='modification']",getAttrs(e){return e.dataset.id?{id:parseInt(e.dataset.id,10),type:e.dataset.modType,previousValue:e.dataset.modPrevVal,newValue:e.dataset.modNewVal}:!1}},{tag:"div[data-type='modification']",getAttrs(e){return e.dataset.id?{id:parseInt(e.dataset.id,10),type:e.dataset.modType,previousValue:e.dataset.modPrevVal}:!1}}]}}}),Gt=B.Extension.create({name:"textAlignment",addGlobalAttributes(){return[{types:["tableCell","tableHeader"],attributes:{textAlignment:{default:"left",parseHTML:o=>o.getAttribute("data-text-alignment"),renderHTML:o=>o.textAlignment==="left"?{}:{"data-text-alignment":o.textAlignment}}}}]}}),qt=B.Extension.create({name:"blockTextColor",addGlobalAttributes(){return[{types:["table","tableCell","tableHeader"],attributes:{textColor:c.getTextColorAttribute()}}]}}),Wt={blockColor:"data-block-color",blockStyle:"data-block-style",id:"data-id",depth:"data-depth",depthChange:"data-depth-change"},jt=B.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:o=>{if(typeof o=="string")return!1;const e={};for(const[t,n]of Object.entries(Wt))o.getAttribute(n)&&(e[t]=o.getAttribute(n));return e}},{tag:'div[data-node-type="blockOuter"]',skip:!0}]},renderHTML({HTMLAttributes:o}){var r;const e=document.createElement("div");e.className="bn-block-outer",e.setAttribute("data-node-type","blockOuter");for(const[s,i]of Object.entries(o))s!=="class"&&e.setAttribute(s,i);const t={...((r=this.options.domAttributes)==null?void 0:r.block)||{},...o},n=document.createElement("div");n.className=c.mergeCSSClasses("bn-block",t.class),n.setAttribute("data-node-type",this.name);for(const[s,i]of Object.entries(t))s!=="class"&&n.setAttribute(s,i);return e.appendChild(n),{dom:e,contentDOM:n}}}),Kt=B.Node.create({name:"blockGroup",group:"childContainer",content:"blockGroupChild+",marks:"deletion insertion modification",parseHTML(){return[{tag:"div",getAttrs:o=>typeof o=="string"?!1:o.getAttribute("data-node-type")==="blockGroup"?null:!1}]},renderHTML({HTMLAttributes:o}){var n;const e={...((n=this.options.domAttributes)==null?void 0:n.blockGroup)||{},...o},t=document.createElement("div");t.className=c.mergeCSSClasses("bn-block-group",e.class),t.setAttribute("data-node-type","blockGroup");for(const[r,s]of Object.entries(e))r!=="class"&&t.setAttribute(r,s);return{dom:t,contentDOM:t}}}),Yt=B.Node.create({name:"doc",topNode:!0,content:"blockGroup",marks:"insertion modification deletion"}),Jt=F.createExtension(({options:o})=>({key:"collaboration",blockNoteExtensions:[b.ForkYDocExtension(o),b.YCursorExtension(o),b.YSyncExtension(o),b.YUndoExtension(),b.SchemaMigration(o)]}));let te=!1;function Qt(o,e){const t=[B.extensions.ClipboardTextSerializer,B.extensions.Commands,B.extensions.Editable,B.extensions.FocusEvents,B.extensions.Tabindex,Ie.Gapcursor,u.UniqueID.configure({types:["blockContainer","columnList","column"],setIdAttribute:e.setIdAttribute}),Ot,we.Text,Vt,Rt,zt,Pe.Link.extend({inclusive:!1}).configure({defaultProtocol:b.DEFAULT_LINK_PROTOCOL,protocols:te?[]:b.VALID_LINK_PROTOCOLS}),...Object.values(o.schema.styleSpecs).map(n=>n.implementation.mark.configure({editor:o})),qt,Ft,Gt,B.Extension.create({name:"OverrideEscape",addKeyboardShortcuts:()=>({Escape:()=>{var n;return(n=o.getExtension(c.SuggestionMenu))!=null&&n.shown()?!1:(o.blur(),!0)}})}),Yt,jt.configure({editor:o,domAttributes:e.domAttributes}),Ut.configure({editor:o,tabBehavior:e.tabBehavior}),Kt.configure({domAttributes:e.domAttributes}),...Object.values(o.schema.inlineContentSpecs).filter(n=>n.config!=="link"&&n.config!=="text").map(n=>n.implementation.node.configure({editor:o})),...Object.values(o.schema.blockSpecs).flatMap(n=>[..."node"in n.implementation?[n.implementation.node.configure({editor:o,domAttributes:e.domAttributes})]:[]]),Dt(o),Lt(o,e.pasteHandler||(n=>n.defaultPasteHandler())),kt(o)];return te=!0,t}function Xt(o,e){const t=[b.BlockChangeExtension(),b.DropCursorExtension(e),c.FilePanelExtension(e),b.FormattingToolbarExtension(e),b.LinkToolbarExtension(e),b.NodeSelectionKeyboardExtension(),b.PlaceholderExtension(e),ve.ShowSelectionExtension(e),b.SideMenuExtension(e),c.SuggestionMenu(e),...e.trailingBlock!==!1?[b.TrailingNodeExtension()]:[]];return e.collaboration?t.push(Jt(e.collaboration)):t.push(b.HistoryExtension()),"table"in o.schema.blockSpecs&&t.push(b.TableHandlesExtension(e)),e.animations!==!1&&t.push(b.PreviousBlockTypeExtension()),t}class Zt{constructor(e,t){k(this,"disabledExtensions",new Set);k(this,"extensions",[]);k(this,"abortMap",new Map);k(this,"extensionFactories",new Map);k(this,"extensionPlugins",new Map);this.editor=e,this.options=t,e.onMount(()=>{for(const n of this.extensions)if(n.mount){const r=new window.AbortController,s=n.mount({dom:e.prosemirrorView.dom,root:e.prosemirrorView.root,signal:r.signal});s&&r.signal.addEventListener("abort",()=>{s()}),this.abortMap.set(n,r)}}),e.onUnmount(()=>{for(const[n,r]of this.abortMap.entries())this.abortMap.delete(n),r.abort()}),this.disabledExtensions=new Set(t.disableExtensions||[]);for(const n of Xt(this.editor,this.options))this.addExtension(n);for(const n of this.options.extensions??[])this.addExtension(n);for(const n of Object.values(this.editor.schema.blockSpecs))for(const r of n.extensions??[])this.addExtension(r)}registerExtension(e){var s;const t=[].concat(e).filter(Boolean);if(!t.length){console.warn("No extensions found to register",e);return}const n=t.map(i=>this.addExtension(i)).filter(Boolean),r=new Set;for(const i of n)i!=null&&i.tiptapExtensions&&console.warn(`Extension ${i.key} has tiptap extensions, but these cannot be changed after initializing the editor. Please separate the extension into multiple extensions if you want to add them, or re-initialize the editor.`,i),(s=i==null?void 0:i.inputRules)!=null&&s.length&&console.warn(`Extension ${i.key} has input rules, but these cannot be changed after initializing the editor. Please separate the extension into multiple extensions if you want to add them, or re-initialize the editor.`,i),this.getProsemirrorPluginsFromExtension(i).plugins.forEach(l=>{r.add(l)});this.updatePlugins(i=>[...i,...r])}addExtension(e){let t;if(typeof e=="function"?t=e({editor:this.editor}):t=e,!(!t||this.disabledExtensions.has(t.key))){if(typeof e=="function"){const n=t[F.originalFactorySymbol];typeof n=="function"&&this.extensionFactories.set(n,t)}if(this.extensions.push(t),t.blockNoteExtensions)for(const n of t.blockNoteExtensions)this.addExtension(n);return t}}resolveExtensions(e){const t=[];if(typeof e=="function"){const n=this.extensionFactories.get(e);n&&t.push(n)}else if(Array.isArray(e))for(const n of e)t.push(...this.resolveExtensions(n));else if(typeof e=="object"&&"key"in e)t.push(e);else if(typeof e=="string"){const n=this.extensions.find(r=>r.key===e);n&&t.push(n)}return t}unregisterExtension(e){var s;const t=this.resolveExtensions(e);if(!t.length){console.warn("No extensions found to unregister",e);return}let n=!1;const r=new Set;for(const i of t){this.extensions=this.extensions.filter(a=>a!==i),this.extensionFactories.forEach((a,d)=>{a===i&&this.extensionFactories.delete(d)}),(s=this.abortMap.get(i))==null||s.abort(),this.abortMap.delete(i);const l=this.extensionPlugins.get(i);l==null||l.forEach(a=>{r.add(a)}),this.extensionPlugins.delete(i),i.tiptapExtensions&&!n&&(n=!0,console.warn(`Extension ${i.key} has tiptap extensions, but they will not be removed. Please separate the extension into multiple extensions if you want to remove them, or re-initialize the editor.`,e))}this.updatePlugins(i=>i.filter(l=>!r.has(l)))}updatePlugins(e){const t=this.editor.prosemirrorState,n=t.reconfigure({plugins:e(t.plugins.slice())});this.editor.prosemirrorView.updateState(n)}getTiptapExtensions(){var r;const e=Qt(this.editor,this.options).filter(s=>!this.disabledExtensions.has(s.name)),t=M.sortByDependencies(this.extensions),n=new Map;for(const s of this.extensions){s.tiptapExtensions&&e.push(...s.tiptapExtensions);const i=t(s.key),{plugins:l,inputRules:a}=this.getProsemirrorPluginsFromExtension(s);l.length&&e.push(B.Extension.create({name:s.key,priority:i,addProseMirrorPlugins:()=>l})),a.length&&(n.has(i)||n.set(i,[]),n.get(i).push(...a))}e.push(B.Extension.create({name:"blocknote-input-rules",addProseMirrorPlugins(){const s=[];return Array.from(n.keys()).sort().reverse().forEach(i=>{s.push(...n.get(i))}),[K.inputRules({rules:s})]}}));for(const s of((r=this.options._tiptapOptions)==null?void 0:r.extensions)??[])e.push(s);return e}getProsemirrorPluginsFromExtension(e){var r,s,i;const t=[...e.prosemirrorPlugins??[]],n=[];return!((r=e.prosemirrorPlugins)!=null&&r.length)&&!Object.keys(e.keyboardShortcuts||{}).length&&!((s=e.inputRules)!=null&&s.length)?{plugins:t,inputRules:n}:(this.extensionPlugins.set(e,t),(i=e.inputRules)!=null&&i.length&&n.push(...e.inputRules.map(l=>new K.InputRule(l.find,(a,d,p,f)=>{const h=l.replace({match:d,range:{from:p,to:f},editor:this.editor});if(h){const g=this.editor.getTextCursorPosition();if(this.editor.schema.blockSchema[g.block.type].content!=="inline")return null;const m=u.getBlockInfoFromTransaction(a.tr),S=a.tr.deleteRange(p,f);return c.updateBlockTr(S,m.bnBlock.beforePos,h),S}return null}))),Object.keys(e.keyboardShortcuts||{}).length&&t.push(Me.keymap(Object.fromEntries(Object.entries(e.keyboardShortcuts).map(([l,a])=>[l,()=>a({editor:this.editor})])))),{plugins:t,inputRules:n})}getExtensions(){return new Map(this.extensions.map(e=>[e.key,e]))}getExtension(e){if(typeof e=="string"){const t=this.extensions.find(n=>n.key===e);return t||void 0}else if(typeof e=="function"){const t=this.extensionFactories.get(e);return t||void 0}throw new Error(`Invalid extension type: ${typeof e}`)}hasExtension(e){return typeof e=="string"?this.extensions.some(t=>t.key===e):typeof e=="object"&&"key"in e?this.extensions.some(t=>t.key===e.key):typeof e=="function"?this.extensionFactories.has(e):!1}}function Be(o,e){let{$from:t,$to:n}=e;if(t.pos>t.start()&&t.pos<o.content.size){const r=o.textBetween(t.pos,t.pos+1);if(/^[\w\p{P}]$/u.test(r)){const i=o.textBetween(t.start(),t.pos).match(/[\w\p{P}]+$/u);i&&(t=o.resolve(t.pos-i[0].length))}}if(n.pos<n.end()&&n.pos>0){const r=o.textBetween(n.pos-1,n.pos);if(/^[\w\p{P}]$/u.test(r)){const i=o.textBetween(n.pos,n.end()).match(/^[\w\p{P}]+/u);i&&(n=o.resolve(n.pos+i[0].length))}}return{$from:t,$to:n,from:t.pos,to:n.pos}}function eo(o){const e=u.getPmSchema(o);if(o.selection.empty||"node"in o.selection)return;const t=o.doc.resolve(u.getNearestBlockPos(o.doc,o.selection.from).posBeforeNode),n=o.doc.resolve(u.getNearestBlockPos(o.doc,o.selection.to).posBeforeNode),r=(d,p)=>{const f=t.posAtIndex(d,p),h=o.doc.resolve(f).nodeAfter;if(!h)throw new Error(`Error getting selection - node not found at position ${f}`);return u.nodeToBlock(h,e)},s=[],i=t.sharedDepth(n.pos),l=t.index(i),a=n.index(i);if(t.depth>i){s.push(u.nodeToBlock(t.nodeAfter,e));for(let d=t.depth;d>i;d--)if(t.node(d).type.isInGroup("childContainer")){const f=t.index(d)+1,h=t.node(d).childCount;for(let g=f;g<h;g++)s.push(r(g,d))}}else s.push(r(l,i));for(let d=l+1;d<=a;d++)s.push(r(d,i));if(s.length===0)throw new Error(`Error getting selection - selection doesn't span any blocks (${o.selection})`);return{blocks:s}}function to(o,e,t){const n=typeof e=="string"?e:e.id,r=typeof t=="string"?t:t.id,s=u.getPmSchema(o),i=u.getBlockNoteSchema(s);if(n===r)throw new Error(`Attempting to set selection with the same anchor and head blocks (id ${n})`);const l=c.getNodeById(n,o.doc);if(!l)throw new Error(`Block with ID ${n} not found`);const a=c.getNodeById(r,o.doc);if(!a)throw new Error(`Block with ID ${r} not found`);const d=u.getBlockInfo(l),p=u.getBlockInfo(a),f=i.blockSchema[d.blockNoteType],h=i.blockSchema[p.blockNoteType];if(!d.isBlockContainer||f.content==="none")throw new Error(`Attempting to set selection anchor in block without content (id ${n})`);if(!p.isBlockContainer||h.content==="none")throw new Error(`Attempting to set selection anchor in block without content (id ${r})`);let g,m;if(f.content==="table"){const S=N.TableMap.get(d.blockContent.node);g=d.blockContent.beforePos+S.positionAt(0,0,d.blockContent.node)+1+2}else g=d.blockContent.beforePos+1;if(h.content==="table"){const S=N.TableMap.get(p.blockContent.node),y=p.blockContent.beforePos+S.positionAt(S.height-1,S.width-1,p.blockContent.node)+1,E=o.doc.resolve(y).nodeAfter.nodeSize;m=y+E-2}else m=p.blockContent.afterPos-1;o.setSelection(C.TextSelection.create(o.doc,g,m))}function oo(o,e=!1){const t=u.getPmSchema(o),n=e?Be(o.doc,o.selection):o.selection;let r=n.$from,s=n.$to;for(;s.parentOffset>=s.parent.nodeSize-2&&s.depth>0;)s=o.doc.resolve(s.pos+1);for(;s.parentOffset===0&&s.depth>0;)s=o.doc.resolve(s.pos-1);for(;r.parentOffset===0&&r.depth>0;)r=o.doc.resolve(r.pos-1);for(;r.parentOffset>=r.parent.nodeSize-2&&r.depth>0;)r=o.doc.resolve(r.pos+1);const i=u.prosemirrorSliceToSlicedBlocks(o.doc.slice(r.pos,s.pos,!0),t);return{_meta:{startPos:r.pos,endPos:s.pos},...i}}function no(o){const{bnBlock:e}=u.getBlockInfoFromTransaction(o),t=u.getPmSchema(o.doc),n=o.doc.resolve(e.beforePos),r=n.nodeBefore,s=o.doc.resolve(e.afterPos).nodeAfter;let i;return n.depth>1&&(i=n.node(),i.type.isInGroup("bnBlock")||(i=n.node(n.depth-1))),{block:u.nodeToBlock(e.node,t),prevBlock:r===null?void 0:u.nodeToBlock(r,t),nextBlock:s===null?void 0:u.nodeToBlock(s,t),parentBlock:i===void 0?void 0:u.nodeToBlock(i,t)}}function ye(o,e,t="start"){const n=typeof e=="string"?e:e.id,r=u.getPmSchema(o.doc),s=u.getBlockNoteSchema(r),i=c.getNodeById(n,o.doc);if(!i)throw new Error(`Block with ID ${n} not found`);const l=u.getBlockInfo(i),a=s.blockSchema[l.blockNoteType].content;if(l.isBlockContainer){const d=l.blockContent;if(a==="none"){o.setSelection(C.NodeSelection.create(o.doc,d.beforePos));return}if(a==="inline")t==="start"?o.setSelection(C.TextSelection.create(o.doc,d.beforePos+1)):o.setSelection(C.TextSelection.create(o.doc,d.afterPos-1));else if(a==="table")t==="start"?o.setSelection(C.TextSelection.create(o.doc,d.beforePos+4)):o.setSelection(C.TextSelection.create(o.doc,d.afterPos-4));else throw new u.UnreachableCaseError(a)}else{const d=t==="start"?l.childContainer.node.firstChild:l.childContainer.node.lastChild;ye(o,d.attrs.id,t)}}class ro{constructor(e){this.editor=e}getSelection(){return this.editor.transact(e=>eo(e))}getSelectionCutBlocks(e=!1){return this.editor.transact(t=>oo(t,e))}setSelection(e,t){return this.editor.transact(n=>to(n,e,t))}getTextCursorPosition(){return this.editor.transact(e=>no(e))}setTextCursorPosition(e,t="start"){return this.editor.transact(n=>ye(n,e,t))}getSelectionBoundingBox(){if(!this.editor.prosemirrorView)return;const{selection:e}=this.editor.prosemirrorState,{ranges:t}=e,n=Math.min(...t.map(s=>s.$from.pos)),r=Math.max(...t.map(s=>s.$to.pos));if(B.isNodeSelection(e)){const s=this.editor.prosemirrorView.nodeDOM(n);if(s)return s.getBoundingClientRect()}return B.posToDOMRect(this.editor.prosemirrorView,n,r).toJSON()}}class so{constructor(e){k(this,"activeTransaction",null);k(this,"isInCan",!1);this.editor=e}can(e){try{return this.isInCan=!0,e()}finally{this.isInCan=!1}}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");if(this.isInCan)return this.canExec(e);const t=this.prosemirrorState,n=this.prosemirrorView;return e(t,s=>this.prosemirrorView.dispatch(s),n)}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.prosemirrorState,n=this.prosemirrorView;return e(t,void 0,n)}transact(e){if(this.activeTransaction)return e(this.activeTransaction);try{this.activeTransaction=this.editor._tiptapEditor.state.tr;const t=e(this.activeTransaction),n=this.activeTransaction;return this.activeTransaction=null,n&&(n.docChanged||n.selectionSet||n.scrolledIntoView||n.storedMarksSet||!n.isGeneric)&&this.prosemirrorView.dispatch(n),t}finally{this.activeTransaction=null}}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.editor._tiptapEditor.state}get prosemirrorView(){return this.editor._tiptapEditor.view}isFocused(){var e;return((e=this.prosemirrorView)==null?void 0:e.hasFocus())||!1}focus(){var e;(e=this.prosemirrorView)==null||e.focus()}get isEditable(){if(!this.editor._tiptapEditor){if(!this.editor.headless)throw new Error("no editor, but also not headless?");return!1}return this.editor._tiptapEditor.isEditable===void 0?!0:this.editor._tiptapEditor.isEditable}set isEditable(e){if(!this.editor._tiptapEditor){if(!this.editor.headless)throw new Error("no editor, but also not headless?");return}this.editor._tiptapEditor.options.editable!==e&&this.editor._tiptapEditor.setEditable(e)}undo(){const e=this.editor.getExtension("yUndo");if(e)return this.exec(e.undoCommand);const t=this.editor.getExtension("history");if(t)return this.exec(t.undoCommand);throw new Error("No undo plugin found")}redo(){const e=this.editor.getExtension("yUndo");if(e)return this.exec(e.redoCommand);const t=this.editor.getExtension("history");if(t)return this.exec(t.redoCommand);throw new Error("No redo plugin found")}}function io(o,e,t,n={updateSelection:!0}){let{from:r,to:s}=typeof e=="number"?{from:e,to:e}:{from:e.from,to:e.to},i=!0,l=!0,a="";if(t.forEach(d=>{d.check(),i&&d.isText&&d.marks.length===0?a+=d.text:i=!1,l=l?d.isBlock:!1}),r===s&&l){const{parent:d}=o.doc.resolve(r);d.isTextblock&&!d.type.spec.code&&!d.childCount&&(r-=1,s+=1)}return i?o.insertText(a,r,s):o.replaceWith(r,s,t),n.updateSelection&&B.selectionToInsertionEnd(o,o.steps.length-1,-1),!0}class co{constructor(e){this.editor=e}insertInlineContent(e,{updateSelection:t=!1}={}){const n=u.inlineContentToNodes(e,this.editor.pmSchema);this.editor.transact(r=>{io(r,{from:r.selection.from,to:r.selection.to},n,{updateSelection:t})})}getActiveStyles(){return this.editor.transact(e=>{const t={},n=e.selection.$to.marks();for(const r of n){const s=this.editor.schema.styleSchema[r.type.name];if(!s){r.type.name!=="link"&&!r.type.spec.blocknoteIgnore&&console.warn("mark not found in styleschema",r.type.name);continue}s.propSchema==="boolean"?t[s.type]=!0:t[s.type]=r.attrs.stringValue}return t})}addStyles(e){for(const[t,n]of Object.entries(e)){const r=this.editor.schema.styleSchema[t];if(!r)throw new Error(`style ${t} not found in styleSchema`);if(r.propSchema==="boolean")this.editor._tiptapEditor.commands.setMark(t);else if(r.propSchema==="string")this.editor._tiptapEditor.commands.setMark(t,{stringValue:n});else throw new u.UnreachableCaseError(r.propSchema)}}removeStyles(e){for(const t of Object.keys(e))this.editor._tiptapEditor.commands.unsetMark(t)}toggleStyles(e){for(const[t,n]of Object.entries(e)){const r=this.editor.schema.styleSchema[t];if(!r)throw new Error(`style ${t} not found in styleSchema`);if(r.propSchema==="boolean")this.editor._tiptapEditor.commands.toggleMark(t);else if(r.propSchema==="string")this.editor._tiptapEditor.commands.toggleMark(t,{stringValue:n});else throw new u.UnreachableCaseError(r.propSchema)}}getSelectedText(){return this.editor.transact(e=>e.doc.textBetween(e.selection.from,e.selection.to))}getSelectedLinkUrl(){return this.editor._tiptapEditor.getAttributes("link").href}createLink(e,t){if(e==="")return;const n=this.editor.pmSchema.mark("link",{href:e});this.editor.transact(r=>{const{from:s,to:i}=r.selection;t?r.insertText(t,s,i).addMark(s,s+t.length,n):r.setSelection(De.TextSelection.create(r.doc,i)).addMark(s,i,n)})}}function ao(o,e){const t=[];return o.forEach((n,r,s)=>{s!==e&&t.push(n)}),A.Fragment.from(t)}function lo(o,e){const t=[];for(let n=0;n<o.childCount;n++)if(o.child(n).type.name==="tableRow")if(t.length>0&&t[t.length-1].type.name==="table"){const r=t[t.length-1],s=r.copy(r.content.addToEnd(o.child(n)));t[t.length-1]=s}else{const r=e.nodes.table.createChecked(void 0,o.child(n));t.push(r)}else t.push(o.child(n));return o=A.Fragment.from(t),o}function uo(o,e){let t=A.Fragment.from(o.content);if(t=lo(t,e.state.schema),!po(t,e))return new A.Slice(t,o.openStart,o.openEnd);for(let n=0;n<t.childCount;n++)if(t.child(n).type.spec.group==="blockContent"){const r=[t.child(n)];if(n+1<t.childCount&&t.child(n+1).type.name==="blockGroup"){const i=t.child(n+1).child(0).child(0);(i.type.name==="bulletListItem"||i.type.name==="numberedListItem"||i.type.name==="checkListItem")&&(r.push(t.child(n+1)),t=ao(t,n+1))}const s=e.state.schema.nodes.blockContainer.createChecked(void 0,r);t=t.replaceChild(n,s)}return new A.Slice(t,o.openStart,o.openEnd)}function po(o,e){var s,i;const t=o.childCount===1,n=((s=o.firstChild)==null?void 0:s.type.spec.content)==="inline*",r=((i=o.firstChild)==null?void 0:i.type.spec.content)==="tableRow+";if(t){if(n)return!1;if(r){const l=u.getBlockInfoFromSelection(e.state);if(l.isBlockContainer)return!(l.blockContent.node.type.spec.content==="tableRow+")}}return!0}const fo={enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!1};class j extends R.EventEmitter{constructor(t){var d,p,f,h,g,m,S,y,E,P;super();k(this,"pmSchema");k(this,"_tiptapEditor");k(this,"elementRenderer",null);k(this,"blockCache",new WeakMap);k(this,"dictionary");k(this,"schema");k(this,"blockImplementations");k(this,"inlineContentImplementations");k(this,"styleImplementations");k(this,"uploadFile");k(this,"onUploadStartCallbacks",[]);k(this,"onUploadEndCallbacks",[]);k(this,"resolveFileUrl");k(this,"settings");k(this,"_blockManager");k(this,"_eventManager");k(this,"_exportManager");k(this,"_extensionManager");k(this,"_selectionManager");k(this,"_stateManager");k(this,"_styleManager");k(this,"unregisterExtension",(...t)=>this._extensionManager.unregisterExtension(...t));k(this,"registerExtension",(...t)=>this._extensionManager.registerExtension(...t));k(this,"getExtension",(...t)=>this._extensionManager.getExtension(...t));k(this,"mount",t=>{this._tiptapEditor.mount({mount:t})});k(this,"unmount",()=>{this._tiptapEditor.unmount()});this.options=t,this.dictionary=t.dictionary||xe.en,this.settings={tables:{splitCells:((d=t==null?void 0:t.tables)==null?void 0:d.splitCells)??!1,cellBackgroundColor:((p=t==null?void 0:t.tables)==null?void 0:p.cellBackgroundColor)??!1,cellTextColor:((f=t==null?void 0:t.tables)==null?void 0:f.cellTextColor)??!1,headers:((h=t==null?void 0:t.tables)==null?void 0:h.headers)??!1}};const n={defaultStyles:!0,schema:t.schema||M.BlockNoteSchema.create(),...t,placeholders:{...this.dictionary.placeholders,...t.placeholders}};if(this.schema=n.schema,this.blockImplementations=n.schema.blockSpecs,this.inlineContentImplementations=n.schema.inlineContentSpecs,this.styleImplementations=n.schema.styleSpecs,n.uploadFile){const T=n.uploadFile;this.uploadFile=async(w,I)=>{this.onUploadStartCallbacks.forEach(v=>v.apply(this,[I]));try{return await T(w,I)}finally{this.onUploadEndCallbacks.forEach(v=>v.apply(this,[I]))}}}this.resolveFileUrl=n.resolveFileUrl,this._eventManager=new rt(this),this._extensionManager=new Zt(this,n);const r=this._extensionManager.getTiptapExtensions(),s=this._extensionManager.hasExtension("ySync")||this._extensionManager.hasExtension("liveblocksExtension");s&&n.initialContent&&console.warn("When using Collaboration, initialContent might cause conflicts, because changes should come from the collaboration provider");const i={...fo,...n._tiptapOptions,element:null,autofocus:n.autofocus??!1,extensions:r,editorProps:{...(g=n._tiptapOptions)==null?void 0:g.editorProps,attributes:{tabIndex:"0",...(S=(m=n._tiptapOptions)==null?void 0:m.editorProps)==null?void 0:S.attributes,...(y=n.domAttributes)==null?void 0:y.editor,class:c.mergeCSSClasses("bn-editor",n.defaultStyles?"bn-default-styles":"",((P=(E=n.domAttributes)==null?void 0:E.editor)==null?void 0:P.class)||"")},transformPasted:uo}};try{const T=n.initialContent||(s?[{type:"paragraph",id:"initialBlockId"}]:[{type:"paragraph",id:u.UniqueID.options.generateID()}]);if(!Array.isArray(T)||T.length===0)throw new Error("initialContent must be a non-empty array of blocks, received: "+T);const w=B.getSchema(i.extensions),I=T.map(Ce=>u.blockToNode(Ce,w,this.schema.styleSchema).toJSON()),v=B.createDocument({type:"doc",content:[{type:"blockGroup",content:I}]},w,i.parseOptions);this._tiptapEditor=new B.Editor({...i,content:v.toJSON()}),this.pmSchema=this._tiptapEditor.schema}catch(T){throw new Error("Error creating document from blocks passed as `initialContent`",{cause:T})}let l;const a=this.pmSchema.nodes.doc.createAndFill;this.pmSchema.nodes.doc.createAndFill=(...T)=>{if(l)return l;const w=a.apply(this.pmSchema.nodes.doc,T),I=JSON.parse(JSON.stringify(w.toJSON()));return I.content[0].content[0].attrs.id="initialBlockId",l=x.Node.fromJSON(this.pmSchema,I),l},this.pmSchema.cached.blockNoteEditor=this,this._blockManager=new nt(this),this._exportManager=new ft(this),this._selectionManager=new ro(this),this._stateManager=new so(this),this._styleManager=new co(this),this.emit("create")}static create(t){return new j(t??{})}get extensions(){return this._extensionManager.getExtensions()}exec(t){return this._stateManager.exec(t)}canExec(t){return this._stateManager.canExec(t)}transact(t){return this._stateManager.transact(t)}get prosemirrorState(){return this._stateManager.prosemirrorState}get prosemirrorView(){return this._stateManager.prosemirrorView}get domElement(){var t;if(!this.headless)return(t=this.prosemirrorView)==null?void 0:t.dom}isFocused(){var t;return this.headless?!1:((t=this.prosemirrorView)==null?void 0:t.hasFocus())||!1}get headless(){return!this._tiptapEditor.isInitialized}focus(){this.headless||this.prosemirrorView.focus()}blur(){var t;this.headless||(t=this.domElement)==null||t.blur()}onUploadStart(t){return this.onUploadStartCallbacks.push(t),()=>{const n=this.onUploadStartCallbacks.indexOf(t);n>-1&&this.onUploadStartCallbacks.splice(n,1)}}onUploadEnd(t){return this.onUploadEndCallbacks.push(t),()=>{const n=this.onUploadEndCallbacks.indexOf(t);n>-1&&this.onUploadEndCallbacks.splice(n,1)}}get topLevelBlocks(){return this.document}get document(){return this._blockManager.document}getBlock(t){return this._blockManager.getBlock(t)}getPrevBlock(t){return this._blockManager.getPrevBlock(t)}getNextBlock(t){return this._blockManager.getNextBlock(t)}getParentBlock(t){return this._blockManager.getParentBlock(t)}forEachBlock(t,n=!1){this._blockManager.forEachBlock(t,n)}onEditorContentChange(t){this._tiptapEditor.on("update",t)}onEditorSelectionChange(t){this._tiptapEditor.on("selectionUpdate",t)}onBeforeChange(t){return this._extensionManager.getExtension(b.BlockChangeExtension).subscribe(t)}getTextCursorPosition(){return this._selectionManager.getTextCursorPosition()}setTextCursorPosition(t,n="start"){return this._selectionManager.setTextCursorPosition(t,n)}getSelection(){return this._selectionManager.getSelection()}getSelectionCutBlocks(t=!1){return this._selectionManager.getSelectionCutBlocks(t)}setSelection(t,n){return this._selectionManager.setSelection(t,n)}get isEditable(){return this._stateManager.isEditable}set isEditable(t){this._stateManager.isEditable=t}insertBlocks(t,n,r="before"){return this._blockManager.insertBlocks(t,n,r)}updateBlock(t,n){return this._blockManager.updateBlock(t,n)}removeBlocks(t){return this._blockManager.removeBlocks(t)}replaceBlocks(t,n){return this._blockManager.replaceBlocks(t,n)}undo(){return this._stateManager.undo()}redo(){return this._stateManager.redo()}insertInlineContent(t,{updateSelection:n=!1}={}){this._styleManager.insertInlineContent(t,{updateSelection:n})}getActiveStyles(){return this._styleManager.getActiveStyles()}addStyles(t){this._styleManager.addStyles(t)}removeStyles(t){this._styleManager.removeStyles(t)}toggleStyles(t){this._styleManager.toggleStyles(t)}getSelectedText(){return this._styleManager.getSelectedText()}getSelectedLinkUrl(){return this._styleManager.getSelectedLinkUrl()}createLink(t,n){this._styleManager.createLink(t,n)}canNestBlock(){return this._blockManager.canNestBlock()}nestBlock(){this._blockManager.nestBlock()}canUnnestBlock(){return this._blockManager.canUnnestBlock()}unnestBlock(){this._blockManager.unnestBlock()}moveBlocksUp(){return this._blockManager.moveBlocksUp()}moveBlocksDown(){return this._blockManager.moveBlocksDown()}blocksToHTMLLossy(t=this.document){return this._exportManager.blocksToHTMLLossy(t)}blocksToFullHTML(t=this.document){return this._exportManager.blocksToFullHTML(t)}tryParseHTMLToBlocks(t){return this._exportManager.tryParseHTMLToBlocks(t)}blocksToMarkdownLossy(t=this.document){return this._exportManager.blocksToMarkdownLossy(t)}tryParseMarkdownToBlocks(t){return this._exportManager.tryParseMarkdownToBlocks(t)}onChange(t,n){return this._eventManager.onChange(t,n)}onSelectionChange(t,n){return this._eventManager.onSelectionChange(t,n)}onMount(t){this._eventManager.onMount(t)}onUnmount(t){this._eventManager.onUnmount(t)}getSelectionBoundingBox(){return this._selectionManager.getSelectionBoundingBox()}get isEmpty(){const t=this.document;return t.length===0||t.length===1&&t[0].type==="paragraph"&&t[0].content.length===0}pasteHTML(t,n=!1){this._exportManager.pasteHTML(t,n)}pasteText(t){return this._exportManager.pasteText(t)}pasteMarkdown(t){return this._exportManager.pasteMarkdown(t)}}class ho{constructor(e,t,n){this.mappings=t,this.options=n}async resolveFile(e){var n;if(!((n=this.options)!=null&&n.resolveFileUrl))return(await fetch(e)).blob();const t=await this.options.resolveFileUrl(e);return t instanceof Blob?t:(await fetch(t)).blob()}mapStyles(e){return Object.entries(e).map(([n,r])=>this.mappings.styleMapping[n](r,this))}mapInlineContent(e){return this.mappings.inlineContentMapping[e.type](e,this)}transformInlineContent(e){return e.map(t=>this.mapInlineContent(t))}async mapBlock(e,t,n,r){return this.mappings.blockMapping[e.type](e,this,t,n,r)}}function mo(o){return{createBlockMapping:e=>e,createInlineContentMapping:e=>e,createStyleMapping:e=>e}}function ko(o,...e){const t=[...o];for(const n of e)for(const r of n){const s=t.findLastIndex(i=>i.group===r.group);s===-1?t.push(r):t.splice(s+1,0,r)}return t}exports.UniqueID=u.UniqueID;exports.UnreachableCaseError=u.UnreachableCaseError;exports.assertEmpty=u.assertEmpty;exports.blockToNode=u.blockToNode;exports.contentNodeToInlineContent=u.contentNodeToInlineContent;exports.contentNodeToTableContent=u.contentNodeToTableContent;exports.docToBlocks=u.docToBlocks;exports.getBlockCache=u.getBlockCache;exports.getBlockInfo=u.getBlockInfo;exports.getBlockInfoFromResolvedPos=u.getBlockInfoFromResolvedPos;exports.getBlockInfoFromSelection=u.getBlockInfoFromSelection;exports.getBlockInfoFromTransaction=u.getBlockInfoFromTransaction;exports.getBlockInfoWithManualOffset=u.getBlockInfoWithManualOffset;exports.getBlockNoteSchema=u.getBlockNoteSchema;exports.getBlockSchema=u.getBlockSchema;exports.getColspan=u.getColspan;exports.getInlineContentSchema=u.getInlineContentSchema;exports.getNearestBlockPos=u.getNearestBlockPos;exports.getPmSchema=u.getPmSchema;exports.getRowspan=u.getRowspan;exports.getStyleSchema=u.getStyleSchema;exports.inlineContentToNodes=u.inlineContentToNodes;exports.isLinkInlineContent=u.isLinkInlineContent;exports.isPartialLinkInlineContent=u.isPartialLinkInlineContent;exports.isPartialTableCell=u.isPartialTableCell;exports.isStyledTextInlineContent=u.isStyledTextInlineContent;exports.isTableCell=u.isTableCell;exports.mapTableCell=u.mapTableCell;exports.nodeToBlock=u.nodeToBlock;exports.nodeToCustomInlineContent=u.nodeToCustomInlineContent;exports.prosemirrorSliceToSlicedBlocks=u.prosemirrorSliceToSlicedBlocks;exports.tableContentToNodes=u.tableContentToNodes;exports.COLORS_DARK_MODE_DEFAULT=c.COLORS_DARK_MODE_DEFAULT;exports.COLORS_DEFAULT=c.COLORS_DEFAULT;exports.EMPTY_CELL_HEIGHT=c.EMPTY_CELL_HEIGHT;exports.EMPTY_CELL_WIDTH=c.EMPTY_CELL_WIDTH;exports.FILE_AUDIO_ICON_SVG=c.FILE_AUDIO_ICON_SVG;exports.FILE_IMAGE_ICON_SVG=c.FILE_IMAGE_ICON_SVG;exports.FILE_VIDEO_ICON_SVG=c.FILE_VIDEO_ICON_SVG;exports.addDefaultPropsExternalHTML=c.addDefaultPropsExternalHTML;exports.addInlineContentAttributes=c.addInlineContentAttributes;exports.addInlineContentKeyboardShortcuts=c.addInlineContentKeyboardShortcuts;exports.addNodeAndExtensionsToSpec=c.addNodeAndExtensionsToSpec;exports.addStyleAttributes=c.addStyleAttributes;exports.applyNonSelectableBlockFix=c.applyNonSelectableBlockFix;exports.audioParse=c.audioParse;exports.audioRender=c.audioRender;exports.audioToExternalHTML=c.audioToExternalHTML;exports.blockHasType=c.blockHasType;exports.camelToDataKebab=c.camelToDataKebab;exports.captureCellAnchor=c.captureCellAnchor;exports.createAudioBlockConfig=c.createAudioBlockConfig;exports.createAudioBlockSpec=c.createAudioBlockSpec;exports.createBlockConfig=c.createBlockConfig;exports.createBlockSpec=c.createBlockSpec;exports.createBlockSpecFromTiptapNode=c.createBlockSpecFromTiptapNode;exports.createBulletListItemBlockConfig=c.createBulletListItemBlockConfig;exports.createBulletListItemBlockSpec=c.createBulletListItemBlockSpec;exports.createCheckListItemBlockSpec=c.createCheckListItemBlockSpec;exports.createCheckListItemConfig=c.createCheckListItemConfig;exports.createCodeBlockConfig=c.createCodeBlockConfig;exports.createCodeBlockSpec=c.createCodeBlockSpec;exports.createDefaultBlockDOMOutputSpec=c.createDefaultBlockDOMOutputSpec;exports.createDividerBlockConfig=c.createDividerBlockConfig;exports.createDividerBlockSpec=c.createDividerBlockSpec;exports.createFileBlockConfig=c.createFileBlockConfig;exports.createFileBlockSpec=c.createFileBlockSpec;exports.createHeadingBlockConfig=c.createHeadingBlockConfig;exports.createHeadingBlockSpec=c.createHeadingBlockSpec;exports.createImageBlockConfig=c.createImageBlockConfig;exports.createImageBlockSpec=c.createImageBlockSpec;exports.createInlineContentSpecFromTipTapNode=c.createInlineContentSpecFromTipTapNode;exports.createInternalInlineContentSpec=c.createInternalInlineContentSpec;exports.createInternalStyleSpec=c.createInternalStyleSpec;exports.createNumberedListItemBlockConfig=c.createNumberedListItemBlockConfig;exports.createNumberedListItemBlockSpec=c.createNumberedListItemBlockSpec;exports.createParagraphBlockConfig=c.createParagraphBlockConfig;exports.createParagraphBlockSpec=c.createParagraphBlockSpec;exports.createQuoteBlockConfig=c.createQuoteBlockConfig;exports.createQuoteBlockSpec=c.createQuoteBlockSpec;exports.createStyleSpec=c.createStyleSpec;exports.createStyleSpecFromTipTapMark=c.createStyleSpecFromTipTapMark;exports.createTableBlockSpec=c.createTableBlockSpec;exports.createToggleListItemBlockConfig=c.createToggleListItemBlockConfig;exports.createToggleListItemBlockSpec=c.createToggleListItemBlockSpec;exports.createToggleWrapper=c.createToggleWrapper;exports.createVideoBlockConfig=c.createVideoBlockConfig;exports.createVideoBlockSpec=c.createVideoBlockSpec;exports.defaultBlockSpecs=c.defaultBlockSpecs;exports.defaultBlockToHTML=c.defaultBlockToHTML;exports.defaultInlineContentSchema=c.defaultInlineContentSchema;exports.defaultInlineContentSpecs=c.defaultInlineContentSpecs;exports.defaultProps=c.defaultProps;exports.defaultStyleSchema=c.defaultStyleSchema;exports.defaultStyleSpecs=c.defaultStyleSpecs;exports.defaultToggledState=c.defaultToggledState;exports.editorHasBlockWithType=c.editorHasBlockWithType;exports.fileParse=c.fileParse;exports.filenameFromURL=c.filenameFromURL;exports.formatKeyboardShortcut=c.formatKeyboardShortcut;exports.getBackgroundColorAttribute=c.getBackgroundColorAttribute;exports.getBlockFromPos=c.getBlockFromPos;exports.getInlineContentSchemaFromSpecs=c.getInlineContentSchemaFromSpecs;exports.getLanguageId=c.getLanguageId;exports.getNodeById=c.getNodeById;exports.getParseRules=c.getParseRules;exports.getStyleParseRules=c.getStyleParseRules;exports.getStyleSchemaFromSpecs=c.getStyleSchemaFromSpecs;exports.getTextAlignmentAttribute=c.getTextAlignmentAttribute;exports.getTextColorAttribute=c.getTextColorAttribute;exports.imageParse=c.imageParse;exports.imageRender=c.imageRender;exports.imageToExternalHTML=c.imageToExternalHTML;exports.isAppleOS=c.isAppleOS;exports.isNodeBlock=c.isNodeBlock;exports.isSafari=c.isSafari;exports.isTableCellSelection=c.isTableCellSelection;exports.isVideoUrl=c.isVideoUrl;exports.mergeCSSClasses=c.mergeCSSClasses;exports.mergeParagraphs=c.mergeParagraphs;exports.parseAudioElement=c.parseAudioElement;exports.parseDefaultProps=c.parseDefaultProps;exports.propsToAttributes=c.propsToAttributes;exports.stylePropsToAttributes=c.stylePropsToAttributes;exports.tablePropSchema=c.tablePropSchema;exports.trackPosition=c.trackPosition;exports.updateBlock=c.updateBlock;exports.updateBlockCommand=c.updateBlockCommand;exports.updateBlockTr=c.updateBlockTr;exports.videoParse=c.videoParse;exports.wrapInBlockStructure=c.wrapInBlockStructure;exports.blocksToMarkdown=b.blocksToMarkdown;exports.cleanHTMLToMarkdown=b.cleanHTMLToMarkdown;exports.createExternalHTMLExporter=b.createExternalHTMLExporter;exports.getBlocksChangedByTransaction=b.getBlocksChangedByTransaction;exports.BlockNoteSchema=M.BlockNoteSchema;exports.CustomBlockNoteSchema=M.CustomBlockNoteSchema;exports.checkPageBreakBlocksInSchema=M.checkPageBreakBlocksInSchema;exports.createPageBreakBlockConfig=M.createPageBreakBlockConfig;exports.createPageBreakBlockSpec=M.createPageBreakBlockSpec;exports.getPageBreakSlashMenuItems=M.getPageBreakSlashMenuItems;exports.uploadToTmpFilesDotOrg_DEV_ONLY=M.uploadToTmpFilesDotOrg_DEV_ONLY;exports.withPageBreak=M.withPageBreak;exports.EventEmitter=R.EventEmitter;exports.createExtension=F.createExtension;exports.createStore=F.createStore;exports.BlockNoteEditor=j;exports.Exporter=ho;exports.HTMLToBlocks=z;exports.combineByGroup=ko;exports.createInlineContentSpec=Ue;exports.createInternalHTMLSerializer=ce;exports.expandPMRangeToWords=Be;exports.fixColumnList=D;exports.getBlock=fe;exports.getInlineContentParseRules=oe;exports.getNextBlock=me;exports.getParentBlock=ke;exports.getPrevBlock=he;exports.insertBlocks=ne;exports.isEmptyColumn=_;exports.mappingFactory=mo;exports.markdownToBlocks=ge;exports.markdownToHTML=G;exports.removeAndInsertBlocks=$;exports.removeEmptyColumns=re;exports.selectedFragmentToHTML=W;
//# sourceMappingURL=blocknote.cjs.map
diff --git a/dist/blocknote.js b/dist/blocknote.js
index 0f97dc48ddedfb9661b81c7469ce504dc974e284..e1af7dbc1e590a4cc7cdd4ec921b7b683c3ebb97 100644
--- a/dist/blocknote.js
+++ b/dist/blocknote.js
@@ -313,7 +313,7 @@ function Qt(o, e, t, n, s) {
let l = document.createTextNode(
i.textContent
);
- for (const d of i.marks.toReversed())
+ for (const d of Array.from(i.marks).reverse())
if (d.type.name in o.schema.styleSpecs) {
const u = o.schema.styleSpecs[d.type.name].implementation.render(d.attrs.stringValue, o);
u.contentDOM.appendChild(l), l = u.dom;
@@ -2037,7 +2037,9 @@ const de = () => {
]
})
);
-let fe = !1;
+const bnLinkifyProtocolFlag = "__tolariaBlockNoteLinkifyProtocolsRegistered";
+const bnGlobalObject = typeof globalThis > "u" ? void 0 : globalThis;
+let fe = Boolean(bnGlobalObject && bnGlobalObject[bnLinkifyProtocolFlag]);
function mn(o, e) {
const t = [
I.ClipboardTextSerializer,
@@ -2062,7 +2064,10 @@ function mn(o, e) {
}).configure({
defaultProtocol: Ct,
// only call this once if we have multiple editors installed. Or fix https://github.com/ueberdosis/tiptap/issues/5450
- protocols: fe ? [] : Bt
+ // Tolaria routes editor link clicks through its guarded native opener.
+ openOnClick: !1,
+ // Tolaria pre-registers BlockNote's non-native protocols before linkify initializes.
+ protocols: []
}),
...Object.values(o.schema.styleSpecs).map((n) => n.implementation.mark.configure({
editor: o
@@ -2112,7 +2117,7 @@ function mn(o, e) {
),
Do(o)
];
- return fe = !0, t;
+ return fe = !0, bnGlobalObject && (bnGlobalObject[bnLinkifyProtocolFlag] = !0), t;
}
function kn(o, e) {
const t = [
diff --git a/dist/defaultBlocks-DE5GNdJH.js b/dist/defaultBlocks-DE5GNdJH.js
index b2761001278486a8b2ac1d10c82420b4994e96d9..059837e3da55611d9c09437bcdb1014587451332 100644
--- a/dist/defaultBlocks-DE5GNdJH.js
+++ b/dist/defaultBlocks-DE5GNdJH.js
@@ -1120,6 +1120,8 @@ const Ut = ({ defaultLanguage: e = "text" }) => ({
), i.value = t.props.language || e.defaultLanguage || "text", n.isEditable) {
const l = (u) => {
const d = u.target.value;
+ if (!n.getBlock(t.id))
+ return;
n.updateBlock(t.id, { props: { language: d } });
};
i.addEventListener("change", l), s = () => i.removeEventListener("change", l);
@@ -1167,9 +1169,7 @@ const Ut = ({ defaultLanguage: e = "text" }) => ({
const { block: o, nextBlock: r } = t.getTextCursorPosition();
if (o.type !== "codeBlock")
return !1;
- const { $from: a } = n.selection, s = a.parentOffset === a.parent.nodeSize - 2, i = a.parent.textContent.endsWith(`
-
-`);
+ const { $from: a } = n.selection, s = a.parentOffset === a.parent.nodeSize - 2, i = a.parent.textContent.endsWith("\n ");
if (s && i) {
if (n.delete(a.pos - 2, a.pos), r)
return t.setTextCursorPosition(r, "start"), !0;
@@ -1801,7 +1801,10 @@ const sn = () => ({
render(e, t) {
const n = document.createDocumentFragment(), o = document.createElement("input");
o.type = "checkbox", o.checked = e.props.checked, e.props.checked && o.setAttribute("checked", ""), o.addEventListener("change", () => {
- t.updateBlock(e, { props: { checked: !e.props.checked } });
+ const r = t.getBlock(e.id);
+ if (!r)
+ return;
+ t.updateBlock(r, { props: { checked: !r.props.checked } });
});
const r = document.createElement("p"), a = document.createElement("div");
return a.contentEditable = "false", a.appendChild(o), n.appendChild(a), n.appendChild(r), {
@@ -2621,6 +2624,9 @@ class On {
this.state.referencePos = o.getBoundingClientRect().toJSON(), this.emitUpdate(this.pluginState.triggerCharacter);
}
});
+ M(this, "hideMenu", (t) => {
+ this.state && (this.state.show = !1, this.emitUpdate(t));
+ });
M(this, "closeMenu", () => {
this.editor.transact((t) => t.setMeta(B, null));
});
@@ -2634,7 +2640,7 @@ class On {
this.editor = t, this.pluginState = void 0, this.emitUpdate = (a) => {
var s;
if (!this.state)
- throw new Error("Attempting to update uninitialized suggestions menu");
+ return;
n(a, {
...this.state,
ignoreQueryLength: (s = this.pluginState) == null ? void 0 : s.ignoreQueryLength
@@ -2649,17 +2655,21 @@ class On {
if (!a && !(o !== void 0 && r !== void 0) && !s)
return;
if (this.pluginState = s ? o : r, s || !this.editor.isEditable) {
- this.state && (this.state.show = !1), this.emitUpdate(this.pluginState.triggerCharacter);
+ this.hideMenu(this.pluginState.triggerCharacter);
return;
}
const c = (l = this.rootEl) == null ? void 0 : l.querySelector(
`[data-decoration-id="${this.pluginState.decorationId}"]`
);
- this.editor.isEditable && c && (this.state = {
+ if (!c) {
+ this.hideMenu(this.pluginState.triggerCharacter);
+ return;
+ }
+ this.state = {
show: !0,
referencePos: c.getBoundingClientRect().toJSON(),
query: this.pluginState.query
- }, this.emitUpdate(this.pluginState.triggerCharacter));
+ }, this.emitUpdate(this.pluginState.triggerCharacter);
}
destroy() {
var t;
@@ -2761,7 +2771,7 @@ const B = new Ze("SuggestionMenuPlugin"), _n = k(({ editor: e }) => {
if (a === s) {
const c = r.state.doc;
for (const l of t) {
- const u = l.length > 1 ? c.textBetween(a - l.length, a) + i : i;
+ const u = l.length > 1 ? c.textBetween(a - (l.length - 1), a) + i : i;
if (l === u)
return r.dispatch(r.state.tr.insertText(i)), r.dispatch(
r.state.tr.setMeta(B, {
diff --git a/dist/defaultBlocks-DosClM5E.cjs b/dist/defaultBlocks-DosClM5E.cjs
index ea3664446059a2515aa149d10b1e1ee924388300..c6165d082fa12c83a72efbbce82da189f081ba90 100644
--- a/dist/defaultBlocks-DosClM5E.cjs
+++ b/dist/defaultBlocks-DosClM5E.cjs
@@ -1,6 +1,4 @@
"use strict";var Nt=Object.defineProperty;var It=(e,t,n)=>t in e?Nt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var P=(e,t,n)=>It(e,typeof t!="symbol"?t+"":t,n);const T=require("prosemirror-tables"),S=require("@tiptap/core"),z=require("prosemirror-state"),$=require("prosemirror-view"),ye=require("prosemirror-transform"),j=require("y-prosemirror"),y=require("./BlockNoteExtension-BWw0r8Gy.cjs"),m=require("./blockToNode-CumVjgem.cjs"),Ht=require("@tiptap/extension-bold"),Dt=require("@tiptap/extension-code"),_t=require("@tiptap/extension-italic"),Ot=require("@tiptap/extension-strike"),Vt=require("@tiptap/extension-underline"),R=require("@tiptap/pm/model"),Ft=require("prosemirror-highlight"),Rt=require("prosemirror-highlight/shiki"),N=require("prosemirror-model"),fe=require("@tiptap/pm/state"),ee=require("@tiptap/pm/view"),q=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},Wt=q(Ht),qt=q(Dt),Ut=q(_t),$t=q(Ot),jt=q(Vt),ve=()=>typeof navigator<"u"&&(/Mac/.test(navigator.platform)||/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent));function B(e,t="Ctrl"){return ve()?e.replace("Mod","⌘"):e.replace("Mod",t)}function V(...e){return[...new Set(e.filter(t=>t).join(" ").split(" "))].join(" ")}const Gt=()=>/^((?!chrome|android).)*safari/i.test(navigator.userAgent);function Se(e,t,n,o){const r=document.createElement("div");r.className=V("bn-block-content",n.class),r.setAttribute("data-content-type",e);for(const[s,i]of Object.entries(n))s!=="class"&&r.setAttribute(s,i);const a=document.createElement(t);a.className=V("bn-inline-content",o.class);for(const[s,i]of Object.entries(o))s!=="class"&&a.setAttribute(s,i);return r.appendChild(a),{dom:r,contentDOM:a}}const te=(e,t)=>{let n=m.blockToNode(e,t.pmSchema);n.type.name==="blockContainer"&&(n=n.firstChild);const o=t.pmSchema.nodes[n.type.name].spec.toDOM;if(o===void 0)throw new Error("This block has no default HTML serialization as its corresponding TipTap node doesn't implement `renderHTML`.");const r=o(n);if(typeof r!="object"||!("dom"in r))throw new Error("Cannot use this block's default HTML serialization as its corresponding TipTap node's `renderHTML` function does not return an object with the `dom` property.");return r};function Ee(e,t="<br>"){const n=e.querySelectorAll("p");if(n.length>1){const o=n[0];for(let r=1;r<n.length;r++){const a=n[r];o.innerHTML+=t+a.innerHTML,a.remove()}}}function W(e){return"data-"+e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function Zt(e){const t=e.split("/");return!t.length||t[t.length-1]===""?e:t[t.length-1]}function zt(e){var n;const t=["mp4","webm","ogg","mov","mkv","flv","avi","wmv","m4v"];try{const r=((n=new URL(e).pathname.split(".").pop())==null?void 0:n.toLowerCase())||"";return t.includes(r)}catch{return!1}}function xe(e){const t={};return Object.entries(e).forEach(([n,o])=>{t[n]={default:o.default,keepOnSplit:!0,parseHTML:r=>{const a=r.getAttribute(W(n));if(a===null)return null;if(o.default===void 0&&o.type==="boolean"||o.default!==void 0&&typeof o.default=="boolean")return a==="true"?!0:a==="false"?!1:null;if(o.default===void 0&&o.type==="number"||o.default!==void 0&&typeof o.default=="number"){const s=parseFloat(a);return!Number.isNaN(s)&&Number.isFinite(s)?s:null}return a},renderHTML:r=>r[n]!==o.default?{[W(n)]:r[n]}:{}}}),t}function Me(e,t,n,o){const r=e();if(r===void 0)throw new Error("Cannot find node position");const s=n.state.doc.resolve(r).node().attrs.id;if(!s)throw new Error("Block doesn't have id");const i=t.getBlock(s);if(i.type!==o)throw new Error("Block type does not match");return i}function Z(e,t,n,o,r=!1,a){const s=document.createElement("div");if(a!==void 0)for(const[i,c]of Object.entries(a))i!=="class"&&s.setAttribute(i,c);s.className=V("bn-block-content",(a==null?void 0:a.class)||""),s.setAttribute("data-content-type",t);for(const[i,c]of Object.entries(n)){const u=o[i].default;c!==u&&s.setAttribute(W(i),c)}return r&&s.setAttribute("data-file-block",""),s.appendChild(e.dom),e.contentDOM&&(e.contentDOM.className=V("bn-inline-content",e.contentDOM.className)),{...e,dom:s}}function Le(e,t,n){return{config:{type:e.type,content:e.content,propSchema:t},implementation:{node:e.node,render:te,toExternalHTML:te},extensions:n}}function we(e,t){e.stopEvent=n=>(n.type==="mousedown"&&setTimeout(()=>{t.view.dom.blur()},10),!0)}function Be(e,t){const n=[{tag:"[data-content-type="+e.type+"]",contentElement:".bn-inline-content"}];return t.parse&&n.push({tag:"*",getAttrs(o){var a;if(typeof o=="string")return!1;const r=(a=t.parse)==null?void 0:a.call(t,o);return r===void 0?!1:r},preserveWhitespace:!0,getContent:e.content==="inline"||e.content==="none"?(o,r)=>{var a;if(t.parseContent)return t.parseContent({el:o,schema:r});if(e.content==="inline"){const i=o.cloneNode(!0);return Ee(i,(a=t.meta)!=null&&a.code?`
-`:"<br>"),R.DOMParser.fromSchema(r).parse(i,{topNode:r.nodes.paragraph.create(),preserveWhitespace:!0}).content}return R.Fragment.empty}:void 0}),n}function Kt(e,t,n,o){var a,s,i,c;const r=t.node||S.Node.create({name:e.type,content:e.content==="inline"?"inline*":e.content==="none"?"":e.content,group:"blockContent",selectable:((a=t.meta)==null?void 0:a.selectable)??!0,isolating:((s=t.meta)==null?void 0:s.isolating)??!0,code:((i=t.meta)==null?void 0:i.code)??!1,defining:((c=t.meta)==null?void 0:c.defining)??!0,priority:o,addAttributes(){return xe(e.propSchema)},parseHTML(){return Be(e,t)},renderHTML({HTMLAttributes:l}){var d;const u=document.createElement("div");return Z({dom:u,contentDOM:e.content==="inline"?u:void 0},e.type,{},e.propSchema,((d=t.meta)==null?void 0:d.fileBlockAccept)!==void 0,l)},addNodeView(){return l=>{var f,x;const u=this.options.editor,d=Me(l.getPos,u,this.editor,e.type),p=((f=this.options.domAttributes)==null?void 0:f.blockContent)||{},h=t.render.call({blockContentDOMAttributes:p,props:l,renderType:"nodeView"},d,u);return((x=t.meta)==null?void 0:x.selectable)===!1&&we(h,this.editor),h}}});if(r.name!==e.type)throw new Error("Node name does not match block type. This is a bug in BlockNote.");return{config:e,implementation:{...t,node:r,render(l,u){var p;const d=((p=r.options.domAttributes)==null?void 0:p.blockContent)||{};return t.render.call({blockContentDOMAttributes:d,props:void 0,renderType:"dom"},l,u)},toExternalHTML:(l,u,d)=>{var h,f;const p=((h=r.options.domAttributes)==null?void 0:h.blockContent)||{};return((f=t.toExternalHTML)==null?void 0:f.call({blockContentDOMAttributes:p},l,u,d))??t.render.call({blockContentDOMAttributes:p,renderType:"dom",props:void 0},l,u)}},extensions:n}}function Xt(e){return e}function E(e,t,n){return(o={})=>{const r=typeof e=="function"?e(o):e,a=typeof t=="function"?t(o):t,s=n?typeof n=="function"?n(o):n:void 0;return{config:r,implementation:{...a,toExternalHTML(i,c,l){var d,p;const u=(d=a.toExternalHTML)==null?void 0:d.call({blockContentDOMAttributes:this.blockContentDOMAttributes},i,c,l);if(u!==void 0)return Z(u,i.type,i.props,r.propSchema,((p=a.meta)==null?void 0:p.fileBlockAccept)!==void 0)},render(i,c){var d;const l=a.render.call({blockContentDOMAttributes:this.blockContentDOMAttributes,renderType:this.renderType,props:this.props},i,c);return Z(l,i.type,i.props,r.propSchema,((d=a.meta)==null?void 0:d.fileBlockAccept)!==void 0,this.blockContentDOMAttributes)}},extensions:s}}}function Qt(e,t,n,o){return e.dom.setAttribute("data-inline-content-type",t),Object.entries(n).filter(([r,a])=>{const s=o[r];return a!==s.default}).map(([r,a])=>[W(r),a]).forEach(([r,a])=>e.dom.setAttribute(r,a)),e.contentDOM&&e.contentDOM.setAttribute("data-editable",""),e}function Yt(e){return{Backspace:({editor:t})=>{const n=t.state.selection.$from;return t.state.selection.empty&&n.node().type.name===e.type&&n.parentOffset===0}}}function Te(e,t){return{config:e,implementation:t}}function Jt(e,t,n){return Te({type:e.name,propSchema:t,content:e.config.content==="inline*"?"styled":"none"},{...n,node:e})}function Ae(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.config]))}function Pe(e){return e==="boolean"?{}:{stringValue:{default:void 0,keepOnSplit:!0,parseHTML:t=>t.getAttribute("data-value"),renderHTML:t=>t.stringValue!==void 0?{"data-value":t.stringValue}:{}}}}function F(e,t,n,o){return e.dom.setAttribute("data-style-type",t),o==="string"&&e.dom.setAttribute("data-value",n),e.contentDOM&&e.contentDOM.setAttribute("data-editable",""),e}function oe(e,t){return{config:e,implementation:t}}function _(e,t){return oe({type:e.name,propSchema:t},{mark:e,render(n,o){const r=o.pmSchema.marks[e.name].spec.toDOM;if(r===void 0)throw new Error("This block has no default HTML serialization as its corresponding TipTap node doesn't implement `renderHTML`.");const a=o.pmSchema.mark(e.name,{stringValue:n}),s=R.DOMSerializer.renderSpec(document,r(a,!0));if(typeof s!="object"||!("dom"in s))throw new Error("Cannot use this block's default HTML serialization as its corresponding TipTap mark's `renderHTML` function does not return an object with the `dom` property.");return s},toExternalHTML(n,o){const r=o.pmSchema.marks[e.name].spec.toDOM;if(r===void 0)throw new Error("This block has no default HTML serialization as its corresponding TipTap node doesn't implement `renderHTML`.");const a=o.pmSchema.mark(e.name,{stringValue:n}),s=R.DOMSerializer.renderSpec(document,r(a,!0));if(typeof s!="object"||!("dom"in s))throw new Error("Cannot use this block's default HTML serialization as its corresponding TipTap mark's `renderHTML` function does not return an object with the `dom` property.");return s}})}function Ne(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.config]))}function Ie(e,t){const n=[{tag:`[data-style-type="${e.type}"]`,contentElement:o=>{const r=o;return r.matches("[data-editable]")?r:r.querySelector("[data-editable]")||r}}];return t&&n.push({tag:"*",consuming:!1,getAttrs(o){if(typeof o=="string")return!1;const r=t==null?void 0:t(o);return r===void 0?!1:{stringValue:r}}}),n}function re(e,t){const n=S.Mark.create({name:e.type,addAttributes(){return Pe(e.propSchema)},parseHTML(){return Ie(e,t.parse)},renderHTML({mark:o}){const r=(t.toExternalHTML||t.render)(o.attrs.stringValue);return F(r,e.type,o.attrs.stringValue,e.propSchema)},addMarkView(){return({mark:o})=>{const r=t.render(o.attrs.stringValue);return F(r,e.type,o.attrs.stringValue,e.propSchema)}}});return oe(e,{...t,mark:n,render:o=>{const r=t.render(o);return F(r,e.type,o,e.propSchema)},toExternalHTML:o=>{const r=(t.toExternalHTML||t.render)(o);return F(r,e.type,o,e.propSchema)}})}function He(e,t){let n,o;if(t.firstChild.descendants((r,a)=>n?!1:!De(r)||r.attrs.id!==e?!0:(n=r,o=a+1,!1)),!(n===void 0||o===void 0))return{node:n,posBeforeNode:o}}function De(e){return e.type.isInGroup("bnBlock")}const en=(e,t)=>({tr:n,dispatch:o})=>(o&&K(n,e,t),!0);function K(e,t,n,o,r){const a=m.getBlockInfoFromResolvedPos(e.doc.resolve(t));let s=null;a.blockNoteType==="table"&&(s=_e(e));const i=m.getPmSchema(e);if(o!==void 0&&r!==void 0&&o>r)throw new Error("Invalid replaceFromPos or replaceToPos");const c=i.nodes[a.blockNoteType],l=i.nodes[n.type||a.blockNoteType],u=l.isInGroup("bnBlock")?l:i.nodes.blockContainer;if(a.isBlockContainer&&l.isInGroup("blockContent")){const d=o!==void 0&&o>a.blockContent.beforePos&&o<a.blockContent.afterPos?o-a.blockContent.beforePos-1:void 0,p=r!==void 0&&r>a.blockContent.beforePos&&r<a.blockContent.afterPos?r-a.blockContent.beforePos-1:void 0;ge(n,e,a),tn(n,e,c,l,a,d,p)}else if(!a.isBlockContainer&&l.isInGroup("bnBlock"))ge(n,e,a);else{const d=m.nodeToBlock(a.bnBlock.node,i);e.replaceWith(a.bnBlock.beforePos,a.bnBlock.afterPos,m.blockToNode({children:d.children,...n},i));return}e.setNodeMarkup(a.bnBlock.beforePos,u,{...a.bnBlock.node.attrs,...n.props}),s&&on(e,a,s)}function tn(e,t,n,o,r,a,s){const i=m.getPmSchema(t);let c="keep";if(e.content)if(typeof e.content=="string")c=m.inlineContentToNodes([e.content],i,o.name);else if(Array.isArray(e.content))c=m.inlineContentToNodes(e.content,i,o.name);else if(e.content.type==="tableContent")c=m.tableContentToNodes(e.content,i);else throw new m.UnreachableCaseError(e.content.type);else n.spec.content===""||o.spec.content!==n.spec.content&&(c=[]);if(c==="keep")t.setNodeMarkup(r.blockContent.beforePos,o,{...r.blockContent.node.attrs,...e.props});else if(a!==void 0||s!==void 0){t.setNodeMarkup(r.blockContent.beforePos,o,{...r.blockContent.node.attrs,...e.props});const l=r.blockContent.beforePos+1+(a??0),u=r.blockContent.beforePos+1+(s??r.blockContent.node.content.size),d=t.doc.resolve(r.blockContent.beforePos).depth,p=t.doc.resolve(l).depth,h=t.doc.resolve(u).depth;t.replace(l,u,new N.Slice(N.Fragment.from(c),p-d-1,h-d-1))}else t.replaceWith(r.blockContent.beforePos,r.blockContent.afterPos,o.createChecked({...r.blockContent.node.attrs,...e.props},c))}function ge(e,t,n){const o=m.getPmSchema(t);if(e.children!==void 0&&e.children.length>0){const r=e.children.map(a=>m.blockToNode(a,o));if(n.childContainer)t.step(new ye.ReplaceStep(n.childContainer.beforePos+1,n.childContainer.afterPos-1,new N.Slice(N.Fragment.from(r),0,0)));else{if(!n.isBlockContainer)throw new Error("impossible");t.insert(n.blockContent.afterPos,o.nodes.blockGroup.createChecked({},r))}}}function nn(e,t,n,o,r){const a=typeof t=="string"?t:t.id,s=He(a,e.doc);if(!s)throw new Error(`Block with ID ${a} not found`);K(e,s.posBeforeNode,n,o,r);const i=e.doc.resolve(s.posBeforeNode+1).node(),c=m.getPmSchema(e);return m.nodeToBlock(i,c)}function _e(e){const t="selection"in e?e.selection:null;if(!(t instanceof z.TextSelection))return null;const n=e.doc.resolve(t.head);let o=-1,r=-1;for(let L=n.depth;L>=0;L--){const M=n.node(L).type.name;if(o<0&&(M==="tableCell"||M==="tableHeader")&&(o=L),M==="table"){r=L;break}}if(o<0||r<0)return null;const a=n.before(o),s=n.before(r),i=e.doc.nodeAt(s);if(!i||i.type.name!=="table")return null;const c=T.TableMap.get(i),l=a-(s+1),u=c.map.indexOf(l);if(u<0)return null;const d=Math.floor(u/c.width),p=u%c.width,f=a+1+1,x=Math.max(0,t.head-f);return{row:d,col:p,offset:x}}function on(e,t,n){var L;if(t.blockNoteType!=="table")return!1;let o=-1;if(t.isBlockContainer)o=e.mapping.map(t.blockContent.beforePos);else{const M=e.mapping.map(t.bnBlock.beforePos),D=M+(((L=e.doc.nodeAt(M))==null?void 0:L.nodeSize)||0);e.doc.nodesBetween(M,D,(b,w)=>b.type.name==="table"?(o=w,!1):!0)}const r=o>=0?e.doc.nodeAt(o):null;if(!r||r.type.name!=="table")return!1;const a=T.TableMap.get(r),s=Math.max(0,Math.min(n.row,a.height-1)),i=Math.max(0,Math.min(n.col,a.width-1)),c=s*a.width+i,l=a.map[c];if(l==null)return!1;const d=o+1+l+1,p=e.doc.nodeAt(d),h=d+1,f=p?p.content.size:0,x=h+Math.max(0,Math.min(n.offset,f));return"selection"in e&&e.setSelection(z.TextSelection.create(e.doc,x)),!0}const A={gray:{text:"#9b9a97",background:"#ebeced"},brown:{text:"#64473a",background:"#e9e5e3"},red:{text:"#e03e3e",background:"#fbe4e4"},orange:{text:"#d9730d",background:"#f6e9d9"},yellow:{text:"#dfab01",background:"#fbf3db"},green:{text:"#4d6461",background:"#ddedea"},blue:{text:"#0b6e99",background:"#ddebf1"},purple:{text:"#6940a5",background:"#eae4f2"},pink:{text:"#ad1a72",background:"#f4dfeb"}},rn={gray:{text:"#bebdb8",background:"#9b9a97"},brown:{text:"#8e6552",background:"#64473a"},red:{text:"#ec4040",background:"#be3434"},orange:{text:"#e3790d",background:"#b7600a"},yellow:{text:"#dfab01",background:"#b58b00"},green:{text:"#6b8b87",background:"#4d6461"},blue:{text:"#0e87bc",background:"#0b6e99"},purple:{text:"#8552d7",background:"#6940a5"},pink:{text:"#da208f",background:"#ad1a72"}},g={backgroundColor:{default:"default"},textColor:{default:"default"},textAlignment:{default:"left",values:["left","center","right","justify"]}},v=e=>{const t={};return e.hasAttribute("data-background-color")?t.backgroundColor=e.getAttribute("data-background-color"):e.style.backgroundColor&&(t.backgroundColor=e.style.backgroundColor),e.hasAttribute("data-text-color")?t.textColor=e.getAttribute("data-text-color"):e.style.color&&(t.textColor=e.style.color),t.textAlignment=g.textAlignment.values.includes(e.style.textAlign)?e.style.textAlign:void 0,t},I=(e,t)=>{e.backgroundColor&&e.backgroundColor!==g.backgroundColor.default&&(t.style.backgroundColor=e.backgroundColor in A?A[e.backgroundColor].background:e.backgroundColor),e.textColor&&e.textColor!==g.textColor.default&&(t.style.color=e.textColor in A?A[e.textColor].text:e.textColor),e.textAlignment&&e.textAlignment!==g.textAlignment.default&&(t.style.textAlign=e.textAlignment)},an=(e="backgroundColor")=>({default:g.backgroundColor.default,parseHTML:t=>t.hasAttribute("data-background-color")?t.getAttribute("data-background-color"):t.style.backgroundColor?t.style.backgroundColor:g.backgroundColor.default,renderHTML:t=>t[e]===g.backgroundColor.default?{}:{"data-background-color":t[e]}}),sn=(e="textColor")=>({default:g.textColor.default,parseHTML:t=>t.hasAttribute("data-text-color")?t.getAttribute("data-text-color"):t.style.color?t.style.color:g.textColor.default,renderHTML:t=>t[e]===g.textColor.default?{}:{"data-text-color":t[e]}}),cn=(e="textAlignment")=>({default:g.textAlignment.default,parseHTML:t=>t.hasAttribute("data-text-alignment")?t.getAttribute("data-text-alignment"):t.style.textAlign?t.style.textAlign:g.textAlignment.default,renderHTML:t=>t[e]===g.textAlignment.default?{}:{"data-text-alignment":t[e]}}),X=(e,t)=>{const n=e.querySelector(t);if(!n)return;const o=e.querySelector("figcaption"),r=(o==null?void 0:o.textContent)??void 0;return{targetElement:n,caption:r}},O=y.createExtension(({editor:e})=>{const t=y.createStore(void 0);function n(){t.setState(void 0)}return{key:"filePanel",store:t,mount({signal:o}){const r=e.onChange(n,!1),a=e.onSelectionChange(n,!1);o.addEventListener("abort",()=>{r(),a()})},closeMenu:n,showMenu(o){t.setState(o)}}}),ln=(e,t,n)=>{const o=document.createElement("div");o.className="bn-add-file-button";const r=document.createElement("div");r.className="bn-add-file-button-icon",n?r.appendChild(n):r.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M3 8L9.00319 2H19.9978C20.5513 2 21 2.45531 21 2.9918V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8ZM10 4V9H5V20H19V4H10Z"></path></svg>',o.appendChild(r);const a=document.createElement("p");a.className="bn-add-file-button-text",a.innerHTML=e.type in t.dictionary.file_blocks.add_button_text?t.dictionary.file_blocks.add_button_text[e.type]:t.dictionary.file_blocks.add_button_text.file,o.appendChild(a);const s=c=>{c.preventDefault(),c.stopPropagation()},i=()=>{var c;t.isEditable&&((c=t.getExtension(O))==null||c.showMenu(e.id))};return o.addEventListener("mousedown",s,!0),o.addEventListener("click",i,!0),{dom:o,destroy:()=>{o.removeEventListener("mousedown",s,!0),o.removeEventListener("click",i,!0)}}},dn='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M3 8L9.00319 2H19.9978C20.5513 2 21 2.45531 21 2.9918V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8ZM10 4V9H5V20H19V4H10Z"></path></svg>',un=e=>{const t=document.createElement("div");t.className="bn-file-name-with-icon";const n=document.createElement("div");n.className="bn-file-icon",n.innerHTML=dn,t.appendChild(n);const o=document.createElement("p");return o.className="bn-file-name",o.textContent=e.props.name,t.appendChild(o),{dom:t}},ae=(e,t,n,o)=>{const r=document.createElement("div");if(r.className="bn-file-block-content-wrapper",e.props.url===""){const s=ln(e,t,o);r.appendChild(s.dom);const i=t.onUploadStart(c=>{if(c===e.id){r.removeChild(s.dom);const l=document.createElement("div");l.className="bn-file-loading-preview",l.textContent="Loading...",r.appendChild(l)}});return{dom:r,destroy:()=>{i(),s.destroy()}}}const a={dom:r};if(e.props.showPreview===!1||!n){const s=un(e);r.appendChild(s.dom),a.destroy=()=>{var i;(i=s.destroy)==null||i.call(s)}}else r.appendChild(n.dom);if(e.props.caption){const s=document.createElement("p");s.className="bn-file-caption",s.textContent=e.props.caption,r.appendChild(s)}return a},se=(e,t)=>{const n=document.createElement("figure"),o=document.createElement("figcaption");return o.textContent=t,n.appendChild(e),n.appendChild(o),{dom:n}},Q=(e,t)=>{const n=document.createElement("div"),o=document.createElement("p");return o.textContent=t,n.appendChild(e),n.appendChild(o),{dom:n}},ne=e=>({url:e.src||void 0}),Oe='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M2 16.0001H5.88889L11.1834 20.3319C11.2727 20.405 11.3846 20.4449 11.5 20.4449C11.7761 20.4449 12 20.2211 12 19.9449V4.05519C12 3.93977 11.9601 3.8279 11.887 3.73857C11.7121 3.52485 11.3971 3.49335 11.1834 3.66821L5.88889 8.00007H2C1.44772 8.00007 1 8.44778 1 9.00007V15.0001C1 15.5524 1.44772 16.0001 2 16.0001ZM23 12C23 15.292 21.5539 18.2463 19.2622 20.2622L17.8445 18.8444C19.7758 17.1937 21 14.7398 21 12C21 9.26016 19.7758 6.80629 17.8445 5.15557L19.2622 3.73779C21.5539 5.75368 23 8.70795 23 12ZM18 12C18 10.0883 17.106 8.38548 15.7133 7.28673L14.2842 8.71584C15.3213 9.43855 16 10.64 16 12C16 13.36 15.3213 14.5614 14.2842 15.2841L15.7133 16.7132C17.106 15.6145 18 13.9116 18 12Z"></path></svg>',Ve=e=>({type:"audio",propSchema:{backgroundColor:g.backgroundColor,name:{default:""},url:{default:""},caption:{default:""},showPreview:{default:!0}},content:"none"}),Fe=(e={})=>t=>{if(t.tagName==="AUDIO"){if(t.closest("figure"))return;const{backgroundColor:n}=v(t);return{...ne(t),backgroundColor:n}}if(t.tagName==="FIGURE"){const n=X(t,"audio");if(!n)return;const{targetElement:o,caption:r}=n,{backgroundColor:a}=v(t);return{...ne(o),backgroundColor:a,caption:r}}},Re=(e={})=>(t,n)=>{const o=document.createElement("div");o.innerHTML=e.icon??Oe;const r=document.createElement("audio");return r.className="bn-audio",n.resolveFileUrl?n.resolveFileUrl(t.props.url).then(a=>{r.src=a}):r.src=t.props.url,r.controls=!0,r.contentEditable="false",r.draggable=!1,ae(t,n,{dom:r},o.firstElementChild)},We=(e={})=>(t,n)=>{if(!t.props.url){const r=document.createElement("p");return r.textContent="Add audio",{dom:r}}let o;return t.props.showPreview?(o=document.createElement("audio"),o.src=t.props.url):(o=document.createElement("a"),o.href=t.props.url,o.textContent=t.props.name||t.props.url),t.props.caption?t.props.showPreview?se(o,t.props.caption):Q(o,t.props.caption):{dom:o}},qe=E(Ve,e=>({meta:{fileBlockAccept:["audio/*"]},parse:Fe(e),render:Re(e),toExternalHTML:We(e),runsBefore:["file"]})),he=Symbol.for("blocknote.shikiParser"),J=Symbol.for("blocknote.shikiHighlighterPromise");function pn(e){const t=globalThis;let n,o,r=!1;const a=s=>{if(!e.createHighlighter)return process.env.NODE_ENV==="development"&&!r&&(console.log("For syntax highlighting of code blocks, you must provide a `createCodeBlockSpec({ createHighlighter: () => ... })` function"),r=!0),[];if(!n)return t[J]=t[J]||e.createHighlighter(),t[J].then(c=>{n=c});const i=ie(e,s.language);return!i||i==="text"||i==="none"||i==="plaintext"||i==="txt"?[]:n.getLoadedLanguages().includes(i)?(o||(o=t[he]||Rt.createParser(n),t[he]=o),o(s)):n.loadLanguage(i)};return Ft.createHighlightPlugin({parser:a,languageExtractor:s=>s.attrs.language,nodeTypes:["codeBlock"]})}const Ue=({defaultLanguage:e="text"})=>({type:"codeBlock",propSchema:{language:{default:e}},content:"inline"}),$e=E(Ue,e=>({meta:{code:!0,defining:!0,isolating:!1},parse:t=>{var r,a;if(t.tagName!=="PRE"||t.childElementCount!==1||((r=t.firstElementChild)==null?void 0:r.tagName)!=="CODE")return;const n=t.firstElementChild;return{language:n.getAttribute("data-language")||((a=n.className.split(" ").find(s=>s.includes("language-")))==null?void 0:a.replace("language-",""))}},parseContent:({el:t,schema:n})=>{const o=R.DOMParser.fromSchema(n),r=t.firstElementChild;return o.parse(r,{preserveWhitespace:"full",topNode:n.nodes.codeBlock.create()}).content},render(t,n){const o=document.createDocumentFragment(),r=document.createElement("pre"),a=document.createElement("code");r.appendChild(a);let s;if(e.supportedLanguages){const i=document.createElement("select");if(Object.entries(e.supportedLanguages??{}).forEach(([l,{name:u}])=>{const d=document.createElement("option");d.value=l,d.text=u,i.appendChild(d)}),i.value=t.props.language||e.defaultLanguage||"text",n.isEditable){const l=u=>{const d=u.target.value;n.updateBlock(t.id,{props:{language:d}})};i.addEventListener("change",l),s=()=>i.removeEventListener("change",l)}else i.disabled=!0;const c=document.createElement("div");c.contentEditable="false",c.appendChild(i),o.appendChild(c)}return o.appendChild(r),{dom:o,contentDOM:a,destroy:()=>{s==null||s()}}},toExternalHTML(t){const n=document.createElement("pre"),o=document.createElement("code");return o.className=`language-${t.props.language}`,o.dataset.language=t.props.language,n.appendChild(o),{dom:n,contentDOM:o}}}),e=>[y.createExtension({key:"code-block-highlighter",prosemirrorPlugins:[pn(e)]}),y.createExtension({key:"code-block-keyboard-shortcuts",keyboardShortcuts:{Delete:({editor:t})=>t.transact(n=>{const{block:o}=t.getTextCursorPosition();if(o.type!=="codeBlock")return!1;const{$from:r}=n.selection;return r.parent.textContent?!1:(t.removeBlocks([o]),!0)}),Tab:({editor:t})=>e.indentLineWithTab===!1?!1:t.transact(n=>{const{block:o}=t.getTextCursorPosition();return o.type==="codeBlock"?(n.insertText(" "),!0):!1}),Enter:({editor:t})=>t.transact(n=>{const{block:o,nextBlock:r}=t.getTextCursorPosition();if(o.type!=="codeBlock")return!1;const{$from:a}=n.selection,s=a.parentOffset===a.parent.nodeSize-2,i=a.parent.textContent.endsWith(`
-
-`);if(s&&i){if(n.delete(a.pos-2,a.pos),r)return t.setTextCursorPosition(r,"start"),!0;const[c]=t.insertBlocks([{type:"paragraph"}],o,"after");return t.setTextCursorPosition(c,"start"),!0}return n.insertText(`
-`),!0}),"Shift-Enter":({editor:t})=>t.transact(()=>{const{block:n}=t.getTextCursorPosition();if(n.type!=="codeBlock")return!1;const[o]=t.insertBlocks([{type:"paragraph"}],n,"after");return t.setTextCursorPosition(o,"start"),!0})},inputRules:[{find:/^```(.*?)\s$/,replace:({match:t})=>{const n=t[1].trim();return{type:"codeBlock",props:{language:{language:ie(e,n)??n}.language},content:[]}}}]})]);function ie(e,t){var n;return(n=Object.entries(e.supportedLanguages??{}).find(([o,{aliases:r}])=>(r==null?void 0:r.includes(t))||o===t))==null?void 0:n[0]}const je=()=>({type:"divider",propSchema:{},content:"none"}),Ge=E(je,{meta:{isolating:!1},parse(e){if(e.tagName==="HR")return{}},render(){return{dom:document.createElement("hr")}}},[y.createExtension({key:"divider-block-shortcuts",inputRules:[{find:new RegExp("^---$"),replace(){return{type:"divider",props:{},content:[]}}}]})]),me=e=>({url:e.src||void 0}),Ze=()=>({type:"file",propSchema:{backgroundColor:g.backgroundColor,name:{default:""},url:{default:""},caption:{default:""}},content:"none"}),ze=()=>e=>{if(e.tagName==="EMBED"){if(e.closest("figure"))return;const{backgroundColor:t}=v(e);return{...me(e),backgroundColor:t}}if(e.tagName==="FIGURE"){const t=X(e,"embed");if(!t)return;const{targetElement:n,caption:o}=t,{backgroundColor:r}=v(e);return{...me(n),backgroundColor:r,caption:o}}},Ke=E(Ze,{meta:{fileBlockAccept:["*/*"]},parse:ze(),render(e,t){return ae(e,t)},toExternalHTML(e){if(!e.props.url){const n=document.createElement("p");return n.textContent="Add file",{dom:n}}const t=document.createElement("a");return t.href=e.props.url,t.textContent=e.props.name||e.props.url,e.props.caption?Q(t,e.props.caption):{dom:t}}}),Xe={set:(e,t)=>window.localStorage.setItem(`toggle-${e.id}`,t?"true":"false"),get:e=>window.localStorage.getItem(`toggle-${e.id}`)==="true"},ce=(e,t,n,o=Xe)=>{if("isToggleable"in e.props&&!e.props.isToggleable)return{dom:n};const r=document.createElement("div"),a=document.createElement("div");a.className="bn-toggle-wrapper";const s=document.createElement("button");s.className="bn-toggle-button",s.type="button",s.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="CURRENTCOLOR"><path d="M320-200v-560l440 280-440 280Z"/></svg>';const i=f=>f.preventDefault();s.addEventListener("mousedown",i);const c=()=>{var f;a.getAttribute("data-show-children")==="true"?(a.setAttribute("data-show-children","false"),o.set(t.getBlock(e),!1),r.contains(l)&&r.removeChild(l)):(a.setAttribute("data-show-children","true"),o.set(t.getBlock(e),!0),t.isEditable&&((f=t.getBlock(e))==null?void 0:f.children.length)===0&&!r.contains(l)&&r.appendChild(l))};s.addEventListener("click",c),a.appendChild(s),a.appendChild(n);const l=document.createElement("button");l.className="bn-toggle-add-block-button",l.type="button",l.textContent=t.dictionary.toggle_blocks.add_block_button;const u=f=>f.preventDefault();l.addEventListener("mousedown",u);const d=()=>{t.transact(()=>{const f=t.updateBlock(e,{children:[{}]});t.setTextCursorPosition(f.children[0].id,"end"),t.focus()})};l.addEventListener("click",d),r.appendChild(a);let p=e.children.length;const h=t.onChange(()=>{var x;const f=((x=t.getBlock(e))==null?void 0:x.children.length)??0;f>p?(a.getAttribute("data-show-children")==="false"&&(a.setAttribute("data-show-children","true"),o.set(t.getBlock(e),!0)),r.contains(l)&&r.removeChild(l)):f===0&&f<p&&(a.getAttribute("data-show-children")==="true"&&(a.setAttribute("data-show-children","false"),o.set(t.getBlock(e),!1)),r.contains(l)&&r.removeChild(l)),p=f});return o.get(e)?(a.setAttribute("data-show-children","true"),t.isEditable&&e.children.length===0&&r.appendChild(l)):a.setAttribute("data-show-children","false"),{dom:r,ignoreMutation:f=>f instanceof MutationRecord&&(f.type==="attributes"&&f.target===a&&f.attributeName==="data-show-children"||f.type==="childList"&&(f.addedNodes[0]===l||f.removedNodes[0]===l)),destroy:()=>{s.removeEventListener("mousedown",i),s.removeEventListener("click",c),l.removeEventListener("mousedown",u),l.removeEventListener("click",d),h==null||h()}}},Qe=[1,2,3,4,5,6],fn=e=>({editor:t})=>{const n=t.getTextCursorPosition();return t.schema.blockSchema[n.block.type].content!=="inline"?!1:(t.updateBlock(n.block,{type:"heading",props:{level:e}}),!0)},Ye=({defaultLevel:e=1,levels:t=Qe,allowToggleHeadings:n=!0}={})=>({type:"heading",propSchema:{...g,level:{default:e,values:t},...n?{isToggleable:{default:!1,optional:!0}}:{}},content:"inline"}),Je=E(Ye,({allowToggleHeadings:e=!0}={})=>({meta:{isolating:!1},parse(t){let n;switch(t.tagName){case"H1":n=1;break;case"H2":n=2;break;case"H3":n=3;break;case"H4":n=4;break;case"H5":n=5;break;case"H6":n=6;break;default:return}return{...v(t),level:n}},render(t,n){const o=document.createElement(`h${t.props.level}`);return e?{...ce(t,n,o),contentDOM:o}:{dom:o,contentDOM:o}},toExternalHTML(t){const n=document.createElement(`h${t.props.level}`);return I(t.props,n),{dom:n,contentDOM:n}}}),({levels:e=Qe}={})=>[y.createExtension({key:"heading-shortcuts",keyboardShortcuts:Object.fromEntries(e.map(t=>[`Mod-Alt-${t}`,fn(t)])??[]),inputRules:e.map(t=>({find:new RegExp(`^(#{${t}})\\s$`),replace({match:n}){return{type:"heading",props:{level:n[1].length}}}}))})]),et=(e,t,n,o,r)=>{const{dom:a,destroy:s}=ae(e,t,n,r),i=a;i.style.position="relative",e.props.url&&e.props.showPreview&&(e.props.previewWidth?i.style.width=`${e.props.previewWidth}px`:i.style.width="fit-content");const c=document.createElement("div");c.className="bn-resize-handle",c.style.left="4px";const l=document.createElement("div");l.className="bn-resize-handle",l.style.right="4px";const u=document.createElement("div");u.style.position="absolute",u.style.height="100%",u.style.width="100%";let d,p=e.props.previewWidth;const h=b=>{var ue,pe;if(!d){!t.isEditable&&o.contains(c)&&o.contains(l)&&(o.removeChild(c),o.removeChild(l));return}let w;const U="touches"in b?b.touches[0].clientX:b.clientX;e.props.textAlignment==="center"?d.handleUsed==="left"?w=d.initialWidth+(d.initialClientX-U)*2:w=d.initialWidth+(U-d.initialClientX)*2:d.handleUsed==="left"?w=d.initialWidth+d.initialClientX-U:w=d.initialWidth+U-d.initialClientX,p=Math.min(Math.max(w,64),((pe=(ue=t.domElement)==null?void 0:ue.firstElementChild)==null?void 0:pe.clientWidth)||Number.MAX_VALUE),i.style.width=`${p}px`},f=b=>{(!b.target||!i.contains(b.target)||!t.isEditable)&&o.contains(c)&&o.contains(l)&&(o.removeChild(c),o.removeChild(l)),d&&(d=void 0,i.contains(u)&&i.removeChild(u),t.updateBlock(e,{props:{previewWidth:p}}))},x=()=>{t.isEditable&&(o.appendChild(c),o.appendChild(l))},L=b=>{b.relatedTarget===c||b.relatedTarget===l||d||t.isEditable&&o.contains(c)&&o.contains(l)&&(o.removeChild(c),o.removeChild(l))},M=b=>{b.preventDefault(),i.contains(u)||i.appendChild(u);const w="touches"in b?b.touches[0].clientX:b.clientX;d={handleUsed:"left",initialWidth:i.clientWidth,initialClientX:w}},D=b=>{b.preventDefault(),i.contains(u)||i.appendChild(u);const w="touches"in b?b.touches[0].clientX:b.clientX;d={handleUsed:"right",initialWidth:i.clientWidth,initialClientX:w}};return window.addEventListener("mousemove",h),window.addEventListener("touchmove",h),window.addEventListener("mouseup",f),window.addEventListener("touchend",f),i.addEventListener("mouseenter",x),i.addEventListener("mouseleave",L),c.addEventListener("mousedown",M),c.addEventListener("touchstart",M),l.addEventListener("mousedown",D),l.addEventListener("touchstart",D),{dom:i,destroy:()=>{s==null||s(),window.removeEventListener("mousemove",h),window.removeEventListener("touchmove",h),window.removeEventListener("mouseup",f),window.removeEventListener("touchend",f),i.removeEventListener("mouseenter",x),i.removeEventListener("mouseleave",L),c.removeEventListener("mousedown",M),c.removeEventListener("touchstart",M),l.removeEventListener("mousedown",D),l.removeEventListener("touchstart",D)}}},be=e=>{const t=e.src||void 0,n=e.width||void 0,o=e.alt||void 0;return{url:t,previewWidth:n,name:o}},tt='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M5 11.1005L7 9.1005L12.5 14.6005L16 11.1005L19 14.1005V5H5V11.1005ZM4 3H20C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3ZM15.5 10C14.6716 10 14 9.32843 14 8.5C14 7.67157 14.6716 7 15.5 7C16.3284 7 17 7.67157 17 8.5C17 9.32843 16.3284 10 15.5 10Z"></path></svg>',nt=(e={})=>({type:"image",propSchema:{textAlignment:g.textAlignment,backgroundColor:g.backgroundColor,name:{default:""},url:{default:""},caption:{default:""},showPreview:{default:!0},previewWidth:{default:void 0,type:"number"}},content:"none"}),ot=(e={})=>t=>{if(t.tagName==="IMG"){if(t.closest("figure"))return;const{backgroundColor:n}=v(t);return{...be(t),backgroundColor:n}}if(t.tagName==="FIGURE"){const n=X(t,"img");if(!n)return;const{targetElement:o,caption:r}=n,{backgroundColor:a}=v(t);return{...be(o),backgroundColor:a,caption:r}}},rt=(e={})=>(t,n)=>{const o=document.createElement("div");o.innerHTML=e.icon??tt;const r=document.createElement("div");r.className="bn-visual-media-wrapper";const a=document.createElement("img");return a.className="bn-visual-media",n.resolveFileUrl?n.resolveFileUrl(t.props.url).then(s=>{a.src=s}):a.src=t.props.url,a.alt=t.props.name||t.props.caption||"BlockNote image",a.contentEditable="false",a.draggable=!1,r.appendChild(a),et(t,n,{dom:r},r,o.firstElementChild)},at=(e={})=>(t,n)=>{if(!t.props.url){const r=document.createElement("p");return r.textContent="Add image",{dom:r}}let o;return t.props.showPreview?(o=document.createElement("img"),o.src=t.props.url,o.alt=t.props.name||t.props.caption||"BlockNote image",t.props.previewWidth&&(o.width=t.props.previewWidth)):(o=document.createElement("a"),o.href=t.props.url,o.textContent=t.props.name||t.props.url),t.props.caption?t.props.showPreview?se(o,t.props.caption):Q(o,t.props.caption):{dom:o}},st=E(nt,e=>({meta:{fileBlockAccept:["image/*"]},parse:ot(e),render:rt(e),toExternalHTML:at(e),runsBefore:["file"]})),gn=(e,t,n)=>({state:o,dispatch:r})=>r?it(o.tr,e,t,n):!0,it=(e,t,n,o)=>{const r=m.getNearestBlockPos(e.doc,t),a=m.getBlockInfo(r);if(!a.isBlockContainer)return!1;const s=m.getPmSchema(e),i=[{type:a.bnBlock.node.type,attrs:o?{...a.bnBlock.node.attrs,id:void 0}:{}},{type:n?a.blockContent.node.type:s.nodes.paragraph,attrs:o?{...a.blockContent.node.attrs}:{}}];return e.split(t,2,i),!0},Y=(e,t)=>{const{blockInfo:n,selectionEmpty:o}=e.transact(s=>({blockInfo:m.getBlockInfoFromTransaction(s),selectionEmpty:s.selection.anchor===s.selection.head}));if(!n.isBlockContainer)return!1;const{bnBlock:r,blockContent:a}=n;return a.node.type.name!==t||!o?!1:a.node.childCount===0?(e.transact(s=>{K(s,r.beforePos,{type:"paragraph",props:{}})}),!0):a.node.childCount>0?e.transact(s=>(s.deleteSelection(),it(s,s.selection.from,!0))):!1};function le(e,t,n){var d,p,h;const o=N.DOMParser.fromSchema(t),r=e,a=document.createElement("div");a.setAttribute("data-node-type","blockGroup");for(const f of Array.from(r.childNodes))a.appendChild(f.cloneNode(!0));let s=o.parse(a,{topNode:t.nodes.blockGroup.create()});((p=(d=s.firstChild)==null?void 0:d.firstChild)==null?void 0:p.type.name)==="checkListItem"&&(s=s.copy(s.content.cut(s.firstChild.firstChild.nodeSize+2)));const i=(h=s.firstChild)==null?void 0:h.firstChild;if(!(i!=null&&i.isTextblock))return N.Fragment.from(s);const c=t.nodes[n].create({},i.content),l=s.content.cut(i.nodeSize+2);if(l.size>0){const f=s.copy(l);return c.content.addToEnd(f)}return c.content}const ct=()=>({type:"bulletListItem",propSchema:{...g},content:"inline"}),lt=E(ct,{meta:{isolating:!1},parse(e){var n;if(e.tagName!=="LI")return;const t=e.parentElement;if(t!==null&&(t.tagName==="UL"||t.tagName==="DIV"&&((n=t.parentElement)==null?void 0:n.tagName)==="UL"))return v(e)},parseContent:({el:e,schema:t})=>le(e,t,"bulletListItem"),render(){const e=document.createElement("p");return{dom:e,contentDOM:e}},toExternalHTML(e){const t=document.createElement("li"),n=document.createElement("p");return I(e.props,t),t.appendChild(n),{dom:t,contentDOM:n}}},[y.createExtension({key:"bullet-list-item-shortcuts",keyboardShortcuts:{Enter:({editor:e})=>Y(e,"bulletListItem"),"Mod-Shift-8":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"bulletListItem",props:{}}),!0)}},inputRules:[{find:/^\s?[-+*]\s$/,replace({editor:e}){if(m.getBlockInfoFromSelection(e.prosemirrorState).blockNoteType!=="heading")return{type:"bulletListItem",props:{}}}}]})]),dt=()=>({type:"checkListItem",propSchema:{...g,checked:{default:!1,type:"boolean"}},content:"inline"}),ut=E(dt,{meta:{isolating:!1},parse(e){var n;if(e.tagName==="input")return e.closest("[data-content-type]")||e.closest("li")?void 0:e.type==="checkbox"?{checked:e.checked}:void 0;if(e.tagName!=="LI")return;const t=e.parentElement;if(t!==null&&(t.tagName==="UL"||t.tagName==="DIV"&&((n=t.parentElement)==null?void 0:n.tagName)==="UL")){const o=e.querySelector("input[type=checkbox]")||null;return o===null?void 0:{...v(e),checked:o.checked}}},parseContent:({el:e,schema:t})=>le(e,t,"checkListItem"),render(e,t){const n=document.createDocumentFragment(),o=document.createElement("input");o.type="checkbox",o.checked=e.props.checked,e.props.checked&&o.setAttribute("checked",""),o.addEventListener("change",()=>{t.updateBlock(e,{props:{checked:!e.props.checked}})});const r=document.createElement("p"),a=document.createElement("div");return a.contentEditable="false",a.appendChild(o),n.appendChild(a),n.appendChild(r),{dom:n,contentDOM:r}},toExternalHTML(e){const t=document.createElement("li"),n=document.createElement("input");n.type="checkbox",n.checked=e.props.checked,e.props.checked&&n.setAttribute("checked","");const o=document.createElement("p");return I(e.props,t),t.appendChild(n),t.appendChild(o),{dom:t,contentDOM:o}},runsBefore:["bulletListItem"]},[y.createExtension({key:"check-list-item-shortcuts",keyboardShortcuts:{Enter:({editor:e})=>Y(e,"checkListItem"),"Mod-Shift-9":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"checkListItem",props:{}}),!0)}},inputRules:[{find:/^\s?\[\s*\]\s$/,replace(){return{type:"checkListItem",props:{checked:!1}}}},{find:/^\s?\[[Xx]\]\s$/,replace(){return{type:"checkListItem",props:{checked:!0}}}}]})]);function pt(e,t,n,o){let r=e.firstChild.attrs.start||1,a=!0;const s=!!e.firstChild.attrs.start,i=m.getBlockInfo({posBeforeNode:t,node:e});if(!i.isBlockContainer)throw new Error("impossible");const c=n.doc.resolve(i.bnBlock.beforePos).nodeBefore,l=c?o.get(c):void 0;return l!==void 0?(r=l+1,a=!1):c&&m.getBlockInfo({posBeforeNode:i.bnBlock.beforePos-c.nodeSize,node:c}).blockNoteType==="numberedListItem"&&(r=pt(c,i.bnBlock.beforePos-c.nodeSize,n,o).index+1,a=!1),o.set(e,r),{index:r,isFirst:a,hasStart:s}}function Ce(e,t){const n=new Map,o=t.decorations.map(e.mapping,e.doc),r=[];e.doc.nodesBetween(0,e.doc.nodeSize-2,(s,i)=>{if(s.type.name==="blockContainer"&&s.firstChild.type.name==="numberedListItem"){const{index:c,isFirst:l,hasStart:u}=pt(s,i,e,n);if(o.find(i,i+s.nodeSize,p=>p.index===c&&p.isFirst===l&&p.hasStart===u).length===0){const p=e.doc.nodeAt(i+1);r.push(ee.Decoration.node(i+1,i+1+p.nodeSize,{"data-index":c.toString()}))}}});const a=r.flatMap(s=>o.find(s.from,s.to));return{decorations:o.remove(a).add(e.doc,r)}}const hn=()=>new fe.Plugin({key:new fe.PluginKey("numbered-list-indexing-decorations"),state:{init(e,t){return Ce(t.tr,{decorations:ee.DecorationSet.empty})},apply(e,t){return!e.docChanged&&!e.selectionSet&&t.decorations?t:Ce(e,t)}},props:{decorations(e){var t;return((t=this.getState(e))==null?void 0:t.decorations)??ee.DecorationSet.empty}}}),ft=()=>({type:"numberedListItem",propSchema:{...g,start:{default:void 0,type:"number"}},content:"inline"}),gt=E(ft,{meta:{isolating:!1},parse(e){var n;if(e.tagName!=="LI")return;const t=e.parentElement;if(t!==null&&(t.tagName==="OL"||t.tagName==="DIV"&&((n=t.parentElement)==null?void 0:n.tagName)==="OL")){const o=parseInt(t.getAttribute("start")||"1"),r=v(e);return e.previousElementSibling||o===1?r:{...r,start:o}}},parseContent:({el:e,schema:t})=>le(e,t,"numberedListItem"),render(){const e=document.createElement("p");return{dom:e,contentDOM:e}},toExternalHTML(e){const t=document.createElement("li"),n=document.createElement("p");return I(e.props,t),t.appendChild(n),{dom:t,contentDOM:n}}},[y.createExtension({key:"numbered-list-item-shortcuts",inputRules:[{find:/^\s?(\d+)\.\s$/,replace({match:e,editor:t}){if(m.getBlockInfoFromSelection(t.prosemirrorState).blockNoteType==="heading")return;const o=parseInt(e[1]);return{type:"numberedListItem",props:{start:o!==1?o:void 0}}}}],keyboardShortcuts:{Enter:({editor:e})=>Y(e,"numberedListItem"),"Mod-Shift-7":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"numberedListItem",props:{}}),!0)}},prosemirrorPlugins:[hn()]})]),ht=()=>({type:"toggleListItem",propSchema:{...g},content:"inline"}),mt=E(ht,{meta:{isolating:!1},render(e,t){const n=document.createElement("p");return{...ce(e,t,n),contentDOM:n}},toExternalHTML(e){const t=document.createElement("li"),n=document.createElement("p");return I(e.props,t),t.appendChild(n),{dom:t,contentDOM:n}}},[y.createExtension({key:"toggle-list-item-shortcuts",keyboardShortcuts:{Enter:({editor:e})=>Y(e,"toggleListItem"),"Mod-Shift-6":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"toggleListItem",props:{}}),!0)}}})]),bt=()=>({type:"paragraph",propSchema:g,content:"inline"}),Ct=E(bt,{meta:{isolating:!1},parse:e=>{var t;if(e.tagName==="P"&&(t=e.textContent)!=null&&t.trim())return v(e)},render:()=>{const e=document.createElement("p");return{dom:e,contentDOM:e}},toExternalHTML:e=>{const t=document.createElement("p");return I(e.props,t),{dom:t,contentDOM:t}},runsBefore:["default"]},[y.createExtension({key:"paragraph-shortcuts",keyboardShortcuts:{"Mod-Alt-0":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"paragraph",props:{}}),!0)}}})]),kt=()=>({type:"quote",propSchema:{backgroundColor:g.backgroundColor,textColor:g.textColor},content:"inline"}),yt=E(kt,{meta:{isolating:!1},parse(e){if(e.tagName==="BLOCKQUOTE"){const{backgroundColor:t,textColor:n}=v(e);return{backgroundColor:t,textColor:n}}},render(){const e=document.createElement("blockquote");return{dom:e,contentDOM:e}},toExternalHTML(e){const t=document.createElement("blockquote");return I(e.props,t),{dom:t,contentDOM:t}}},[y.createExtension({key:"quote-block-shortcuts",keyboardShortcuts:{"Mod-Alt-q":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"quote",props:{}}),!0)}},inputRules:[{find:new RegExp("^>\\s$"),replace(){return{type:"quote",props:{}}}}]})]),mn=35,de=120,bn=31,Cn=S.Extension.create({name:"BlockNoteTableExtension",addProseMirrorPlugins:()=>[T.columnResizing({cellMinWidth:mn,defaultCellMinWidth:de,View:null}),T.tableEditing()],addKeyboardShortcuts(){return{Enter:()=>this.editor.state.selection.empty&&this.editor.state.selection.$head.parent.type.name==="tableParagraph"?(this.editor.commands.insertContent({type:"hardBreak"}),!0):!1,Backspace:()=>{const e=this.editor.state.selection,t=e.empty,n=e.$head.parentOffset===0,o=e.$head.node().type.name==="tableParagraph";return t&&n&&o},Tab:()=>this.editor.commands.command(({state:e,dispatch:t,view:n})=>T.goToNextCell(1)(e,t,n)),"Shift-Tab":()=>this.editor.commands.command(({state:e,dispatch:t,view:n})=>T.goToNextCell(-1)(e,t,n))}},extendNodeSchema(e){const t={name:e.name,options:e.options,storage:e.storage};return{tableRole:S.callOrReturn(S.getExtensionField(e,"tableRole",t))}}}),vt={textColor:g.textColor},kn=S.Node.create({name:"tableHeader",addOptions(){return{HTMLAttributes:{}}},content:"tableContent+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:e=>{const t=e.getAttribute("colwidth");return t?t.split(",").map(o=>parseInt(o,10)):null}}}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th",getContent:(e,t)=>St(e,t)}]},renderHTML({HTMLAttributes:e}){return["th",S.mergeAttributes(this.options.HTMLAttributes,e),0]}}),yn=S.Node.create({name:"tableCell",addOptions(){return{HTMLAttributes:{}}},content:"tableContent+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:e=>{const t=e.getAttribute("colwidth");return t?t.split(",").map(o=>parseInt(o,10)):null}}}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td",getContent:(e,t)=>St(e,t)}]},renderHTML({HTMLAttributes:e}){return["td",S.mergeAttributes(this.options.HTMLAttributes,e),0]}}),vn=S.Node.create({name:"table",content:"tableRow+",group:"blockContent",tableRole:"table",marks:"deletion insertion modification",isolating:!0,parseHTML(){return[{tag:"table"}]},renderHTML({node:e,HTMLAttributes:t}){var r,a,s;const n=Se(this.name,"table",{...((r=this.options.domAttributes)==null?void 0:r.blockContent)||{},...t},((a=this.options.domAttributes)==null?void 0:a.inlineContent)||{}),o=document.createElement("colgroup");for(const i of e.children[0].children)if(i.attrs.colwidth)for(const l of i.attrs.colwidth){const u=document.createElement("col");l&&(u.style=`width: ${l}px`),o.appendChild(u)}else o.appendChild(document.createElement("col"));return(s=n.dom.firstChild)==null||s.appendChild(o),n},addNodeView(){return({node:e,HTMLAttributes:t})=>{var o;class n extends T.TableView{constructor(a,s,i){super(a,s),this.node=a,this.cellMinWidth=s,this.blockContentHTMLAttributes=i;const c=document.createElement("div");c.className=V("bn-block-content",i.class),c.setAttribute("data-content-type","table");for(const[p,h]of Object.entries(i))p!=="class"&&c.setAttribute(p,h);const l=this.dom,u=document.createElement("div");u.className="tableWrapper-inner",u.appendChild(l.firstChild),l.appendChild(u),c.appendChild(l);const d=document.createElement("div");d.className="table-widgets-container",d.style.position="relative",l.appendChild(d),this.dom=c}ignoreMutation(a){return!a.target.closest(".tableWrapper-inner")||super.ignoreMutation(a)}}return new n(e,de,{...((o=this.options.domAttributes)==null?void 0:o.blockContent)||{},...t})}}}),Sn=S.Node.create({name:"tableParagraph",group:"tableContent",content:"inline*",parseHTML(){return[{tag:"p",getAttrs:e=>{if(typeof e=="string"||!e.textContent||!e.closest("[data-content-type]"))return!1;const t=e.parentElement;return t===null?!1:t.tagName==="TD"||t.tagName==="TH"?{}:!1},node:"tableParagraph"}]},renderHTML({HTMLAttributes:e}){return["p",e,0]}}),En=S.Node.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)+",tableRole:"row",marks:"deletion insertion modification",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:e}){return["tr",S.mergeAttributes(this.options.HTMLAttributes,e),0]}});function St(e,t){const o=N.DOMParser.fromSchema(t).parse(e,{topNode:t.nodes.blockGroup.create()}),r=[];return o.content.descendants(a=>{if(a.isInline)return r.push(a),!1}),N.Fragment.fromArray(r)}const Et=()=>Le({node:vn,type:"table",content:"table"},vt,[y.createExtension({key:"table-extensions",tiptapExtensions:[Cn,Sn,kn,yn,En]}),y.createExtension({key:"table-keyboard-delete",keyboardShortcuts:{Backspace:({editor:e})=>{if(!(e.prosemirrorState.selection instanceof T.CellSelection))return!1;const t=e.getTextCursorPosition().block,n=t.content;let o=0;for(const a of n.rows)for(const s of a.cells){if("type"in s&&s.content.length>0||!("type"in s)&&s.length>0)return!1;o++}let r=0;return e.prosemirrorState.selection.forEachCell(()=>{r++}),r<o?!1:(e.transact(()=>{(e.getPrevBlock(t)||e.getNextBlock(t))&&e.setTextCursorPosition(t),e.removeBlocks([t])}),!0)}}})]),ke=e=>{const t=e.src||void 0,n=e.width||void 0;return{url:t,previewWidth:n}},xt='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M2 3.9934C2 3.44476 2.45531 3 2.9918 3H21.0082C21.556 3 22 3.44495 22 3.9934V20.0066C22 20.5552 21.5447 21 21.0082 21H2.9918C2.44405 21 2 20.5551 2 20.0066V3.9934ZM8 5V19H16V5H8ZM4 5V7H6V5H4ZM18 5V7H20V5H18ZM4 9V11H6V9H4ZM18 9V11H20V9H18ZM4 13V15H6V13H4ZM18 13V15H20V13H18ZM4 17V19H6V17H4ZM18 17V19H20V17H18Z"></path></svg>',Mt=e=>({type:"video",propSchema:{textAlignment:g.textAlignment,backgroundColor:g.backgroundColor,name:{default:""},url:{default:""},caption:{default:""},showPreview:{default:!0},previewWidth:{default:void 0,type:"number"}},content:"none"}),Lt=e=>t=>{if(t.tagName==="VIDEO"){if(t.closest("figure"))return;const{backgroundColor:n}=v(t);return{...ke(t),backgroundColor:n}}if(t.tagName==="FIGURE"){const n=X(t,"video");if(!n)return;const{targetElement:o,caption:r}=n,{backgroundColor:a}=v(t);return{...ke(o),backgroundColor:a,caption:r}}},wt=E(Mt,e=>({meta:{fileBlockAccept:["video/*"]},parse:Lt(),render(t,n){const o=document.createElement("div");o.innerHTML=e.icon??xt;const r=document.createElement("div");r.className="bn-visual-media-wrapper";const a=document.createElement("video");return a.className="bn-visual-media",n.resolveFileUrl?n.resolveFileUrl(t.props.url).then(s=>{a.src=s}):a.src=t.props.url,a.controls=!0,a.contentEditable="false",a.draggable=!1,a.width=t.props.previewWidth,r.appendChild(a),et(t,n,{dom:r},r,o.firstElementChild)},toExternalHTML(t){if(!t.props.url){const o=document.createElement("p");return o.textContent="Add video",{dom:o}}let n;return t.props.showPreview?(n=document.createElement("video"),n.src=t.props.url,t.props.previewWidth&&(n.width=t.props.previewWidth)):(n=document.createElement("a"),n.href=t.props.url,n.textContent=t.props.name||t.props.url),t.props.caption?t.props.showPreview?se(n,t.props.caption):Q(n,t.props.caption):{dom:n}},runsBefore:["file"]}));function C(e,t,n){if(!(t in e.schema.blockSpecs))return!1;if(!n)return!0;for(const[o,r]of Object.entries(n)){if(!(o in e.schema.blockSpecs[t].config.propSchema))return!1;if(typeof r=="string"){if(e.schema.blockSpecs[t].config.propSchema[o].default!==void 0&&typeof e.schema.blockSpecs[t].config.propSchema[o].default!==r||e.schema.blockSpecs[t].config.propSchema[o].type!==void 0&&e.schema.blockSpecs[t].config.propSchema[o].type!==r)return!1}else{if(e.schema.blockSpecs[t].config.propSchema[o].default!==r.default||e.schema.blockSpecs[t].config.propSchema[o].default===void 0&&r.default===void 0&&e.schema.blockSpecs[t].config.propSchema[o].type!==r.type||typeof e.schema.blockSpecs[t].config.propSchema[o].values!=typeof r.values)return!1;if(typeof e.schema.blockSpecs[t].config.propSchema[o].values=="object"&&typeof r.values=="object"){for(const a of r.values)if(!e.schema.blockSpecs[t].config.propSchema[o].values.includes(a))return!1}}}return!0}function xn(e,t,n,o){return C(t,n,o)&&e.type===n}function Mn(e){return e instanceof T.CellSelection}const G=new Map;function Ln(e){if(G.has(e))return G.get(e);const t=new ye.Mapping;return e._tiptapEditor.on("transaction",({transaction:n})=>{t.appendMapping(n.mapping)}),e._tiptapEditor.on("destroy",()=>{G.delete(e)}),G.set(e,t),t}function Bt(e,t,n="left"){const o=j.ySyncPluginKey.getState(e.prosemirrorState);if(!o){const a=Ln(e),s=a.maps.length;return()=>a.slice(s).map(t,n==="left"?-1:1)}const r=j.absolutePositionToRelativePosition(t+(n==="right"?1:-1),o.binding.type,o.binding.mapping);return()=>{const a=j.ySyncPluginKey.getState(e.prosemirrorState),s=j.relativePositionToAbsolutePosition(a.doc,a.binding.type,r,a.binding.mapping);if(s===null)throw new Error("Position not found, cannot track positions");return s+(n==="right"?-1:1)}}const wn=S.findParentNode(e=>e.type.name==="blockContainer");class Bn{constructor(t,n,o){P(this,"state");P(this,"emitUpdate");P(this,"rootEl");P(this,"pluginState");P(this,"handleScroll",()=>{var t,n;if((t=this.state)!=null&&t.show){const o=(n=this.rootEl)==null?void 0:n.querySelector(`[data-decoration-id="${this.pluginState.decorationId}"]`);if(!o)return;this.state.referencePos=o.getBoundingClientRect().toJSON(),this.emitUpdate(this.pluginState.triggerCharacter)}});P(this,"closeMenu",()=>{this.editor.transact(t=>t.setMeta(H,null))});P(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(t=>t.selection.from)}).run()});var r;this.editor=t,this.pluginState=void 0,this.emitUpdate=a=>{var s;if(!this.state)throw new Error("Attempting to update uninitialized suggestions menu");n(a,{...this.state,ignoreQueryLength:(s=this.pluginState)==null?void 0:s.ignoreQueryLength})},this.rootEl=o.root,(r=this.rootEl)==null||r.addEventListener("scroll",this.handleScroll,!0)}update(t,n){var l;const o=H.getState(n),r=H.getState(t.state),a=o===void 0&&r!==void 0,s=o!==void 0&&r===void 0;if(!a&&!(o!==void 0&&r!==void 0)&&!s)return;if(this.pluginState=s?o:r,s||!this.editor.isEditable){this.state&&(this.state.show=!1),this.emitUpdate(this.pluginState.triggerCharacter);return}const c=(l=this.rootEl)==null?void 0:l.querySelector(`[data-decoration-id="${this.pluginState.decorationId}"]`);this.editor.isEditable&&c&&(this.state={show:!0,referencePos:c.getBoundingClientRect().toJSON(),query:this.pluginState.query},this.emitUpdate(this.pluginState.triggerCharacter))}destroy(){var t;(t=this.rootEl)==null||t.removeEventListener("scroll",this.handleScroll,!0)}}const H=new z.PluginKey("SuggestionMenuPlugin"),Tt=y.createExtension(({editor:e})=>{const t=[];let n;const o=y.createStore(void 0);return{key:"suggestionMenu",store:o,addTriggerCharacter:r=>{t.push(r)},removeTriggerCharacter:r=>{t.splice(t.indexOf(r),1)},closeMenu:()=>{n==null||n.closeMenu()},clearQuery:()=>{n==null||n.clearQuery()},shown:()=>{var r;return((r=n==null?void 0:n.state)==null?void 0:r.show)||!1},openSuggestionMenu:(r,a)=>{e.headless||(e.focus(),e.transact(s=>{a!=null&&a.deleteTriggerCharacter&&s.insertText(r),s.scrollIntoView().setMeta(H,{triggerCharacter:r,deleteTriggerCharacter:(a==null?void 0:a.deleteTriggerCharacter)||!1,ignoreQueryLength:(a==null?void 0:a.ignoreQueryLength)||!1})}))},prosemirrorPlugins:[new z.Plugin({key:H,view:r=>(n=new Bn(e,(a,s)=>{o.setState({...s,triggerCharacter:a})},r),n),state:{init(){},apply:(r,a,s,i)=>{if(r.selection.$from.parent.type.spec.code)return a;const c=r.getMeta(H);if(typeof c=="object"&&c!==null){a&&(n==null||n.closeMenu());const u=Bt(e,i.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(a===void 0)return a;if(i.selection.from!==i.selection.to||c===null||r.getMeta("focus")||r.getMeta("blur")||r.getMeta("pointer")||a.triggerCharacter!==void 0&&i.selection.from<a.queryStartPos()||!i.selection.$from.sameParent(i.doc.resolve(a.queryStartPos())))return;const l={...a};return l.query=i.doc.textBetween(a.queryStartPos(),i.selection.from),l}},props:{handleTextInput(r,a,s,i){if(a===s){const c=r.state.doc;for(const l of t){const u=l.length>1?c.textBetween(a-l.length,a)+i:i;if(l===u)return r.dispatch(r.state.tr.insertText(i)),r.dispatch(r.state.tr.setMeta(H,{triggerCharacter:u}).scrollIntoView()),!0}}return!1},decorations(r){const a=this.getState(r);if(a===void 0)return null;if(!a.deleteTriggerCharacter){const s=wn(r.selection);if(s)return $.DecorationSet.create(r.doc,[$.Decoration.node(s.pos,s.pos+s.node.nodeSize,{nodeName:"span",class:"bn-suggestion-decorator","data-decoration-id":a.decorationId})])}return $.DecorationSet.create(r.doc,[$.Decoration.inline(a.queryStartPos()-a.triggerCharacter.length,a.queryStartPos(),{nodeName:"span",class:"bn-suggestion-decorator","data-decoration-id":a.decorationId})])}}})]}});function Tn(e){let t=e.getTextCursorPosition().block,n=e.schema.blockSchema[t.type].content;for(;n==="none";){if(t=e.getTextCursorPosition().nextBlock,t===void 0)return;n=e.schema.blockSchema[t.type].content,e.setTextCursorPosition(t,"end")}}function k(e,t){const n=e.getTextCursorPosition().block;if(n.content===void 0)throw new Error("Slash Menu open in a block that doesn't contain content.");let o;return Array.isArray(n.content)&&(n.content.length===1&&m.isStyledTextInlineContent(n.content[0])&&n.content[0].type==="text"&&n.content[0].text==="/"||n.content.length===0)?(o=e.updateBlock(n,t),e.setTextCursorPosition(o)):(o=e.insertBlocks([t],n,"after")[0],e.setTextCursorPosition(e.getTextCursorPosition().nextBlock)),Tn(e),o}function An(e){const t=[];return C(e,"heading",{level:"number"})&&(e.schema.blockSchema.heading.propSchema.level.values||[]).filter(n=>n<=3).forEach(n=>{t.push({onItemClick:()=>{k(e,{type:"heading",props:{level:n}})},badge:B(`Mod-Alt-${n}`),key:n===1?"heading":`heading_${n}`,...e.dictionary.slash_menu[n===1?"heading":`heading_${n}`]})}),C(e,"quote")&&t.push({onItemClick:()=>{k(e,{type:"quote"})},key:"quote",...e.dictionary.slash_menu.quote}),C(e,"toggleListItem")&&t.push({onItemClick:()=>{k(e,{type:"toggleListItem"})},badge:B("Mod-Shift-6"),key:"toggle_list",...e.dictionary.slash_menu.toggle_list}),C(e,"numberedListItem")&&t.push({onItemClick:()=>{k(e,{type:"numberedListItem"})},badge:B("Mod-Shift-7"),key:"numbered_list",...e.dictionary.slash_menu.numbered_list}),C(e,"bulletListItem")&&t.push({onItemClick:()=>{k(e,{type:"bulletListItem"})},badge:B("Mod-Shift-8"),key:"bullet_list",...e.dictionary.slash_menu.bullet_list}),C(e,"checkListItem")&&t.push({onItemClick:()=>{k(e,{type:"checkListItem"})},badge:B("Mod-Shift-9"),key:"check_list",...e.dictionary.slash_menu.check_list}),C(e,"paragraph")&&t.push({onItemClick:()=>{k(e,{type:"paragraph"})},badge:B("Mod-Alt-0"),key:"paragraph",...e.dictionary.slash_menu.paragraph}),C(e,"codeBlock")&&t.push({onItemClick:()=>{k(e,{type:"codeBlock"})},badge:B("Mod-Alt-c"),key:"code_block",...e.dictionary.slash_menu.code_block}),C(e,"divider")&&t.push({onItemClick:()=>{k(e,{type:"divider"})},key:"divider",...e.dictionary.slash_menu.divider}),C(e,"table")&&t.push({onItemClick:()=>{k(e,{type:"table",content:{type:"tableContent",rows:[{cells:["","",""]},{cells:["","",""]}]}})},badge:void 0,key:"table",...e.dictionary.slash_menu.table}),C(e,"image",{url:"string"})&&t.push({onItemClick:()=>{var o;const n=k(e,{type:"image"});(o=e.getExtension(O))==null||o.showMenu(n.id)},key:"image",...e.dictionary.slash_menu.image}),C(e,"video",{url:"string"})&&t.push({onItemClick:()=>{var o;const n=k(e,{type:"video"});(o=e.getExtension(O))==null||o.showMenu(n.id)},key:"video",...e.dictionary.slash_menu.video}),C(e,"audio",{url:"string"})&&t.push({onItemClick:()=>{var o;const n=k(e,{type:"audio"});(o=e.getExtension(O))==null||o.showMenu(n.id)},key:"audio",...e.dictionary.slash_menu.audio}),C(e,"file",{url:"string"})&&t.push({onItemClick:()=>{var o;const n=k(e,{type:"file"});(o=e.getExtension(O))==null||o.showMenu(n.id)},key:"file",...e.dictionary.slash_menu.file}),C(e,"heading",{level:"number",isToggleable:"boolean"})&&(e.schema.blockSchema.heading.propSchema.level.values||[]).filter(n=>n<=3).forEach(n=>{t.push({onItemClick:()=>{k(e,{type:"heading",props:{level:n,isToggleable:!0}})},key:n===1?"toggle_heading":`toggle_heading_${n}`,...e.dictionary.slash_menu[n===1?"toggle_heading":`toggle_heading_${n}`]})}),C(e,"heading",{level:"number"})&&(e.schema.blockSchema.heading.propSchema.level.values||[]).filter(n=>n>3).forEach(n=>{t.push({onItemClick:()=>{k(e,{type:"heading",props:{level:n}})},badge:B(`Mod-Alt-${n}`),key:`heading_${n}`,...e.dictionary.slash_menu[`heading_${n}`]})}),t.push({onItemClick:()=>{var n;(n=e.getExtension(Tt))==null||n.openSuggestionMenu(":",{deleteTriggerCharacter:!0,ignoreQueryLength:!0})},key:"emoji",...e.dictionary.slash_menu.emoji}),t}function Pn(e,t){return e.filter(({title:n,aliases:o})=>n.toLowerCase().includes(t.toLowerCase())||o&&o.filter(r=>r.toLowerCase().includes(t.toLowerCase())).length!==0)}const Nn={audio:qe(),bulletListItem:lt(),checkListItem:ut(),codeBlock:$e(),divider:Ge(),file:Ke(),heading:Je(),image:st(),numberedListItem:gt(),paragraph:Ct(),quote:yt(),table:Et(),toggleListItem:mt(),video:wt()},In=re({type:"textColor",propSchema:"string"},{render:()=>{const e=document.createElement("span");return{dom:e,contentDOM:e}},toExternalHTML:e=>{const t=document.createElement("span");return e!==g.textColor.default&&(t.style.color=e in A?A[e].text:e),{dom:t,contentDOM:t}},parse:e=>{if(e.tagName==="SPAN"&&e.style.color)return e.style.color}}),Hn=re({type:"backgroundColor",propSchema:"string"},{render:()=>{const e=document.createElement("span");return{dom:e,contentDOM:e}},toExternalHTML:e=>{const t=document.createElement("span");return e!==g.backgroundColor.default&&(t.style.backgroundColor=e in A?A[e].background:e),{dom:t,contentDOM:t}},parse:e=>{if(e.tagName==="SPAN"&&e.style.backgroundColor)return e.style.backgroundColor}}),At={bold:_(Wt.default,"boolean"),italic:_(Ut.default,"boolean"),underline:_(jt.default,"boolean"),strike:_($t.default,"boolean"),code:_(qt.default,"boolean"),textColor:In,backgroundColor:Hn},Dn=Ne(At),Pt={text:{config:"text",implementation:{}},link:{config:"link",implementation:{}}},_n=Ae(Pt);exports.COLORS_DARK_MODE_DEFAULT=rn;exports.COLORS_DEFAULT=A;exports.EMPTY_CELL_HEIGHT=bn;exports.EMPTY_CELL_WIDTH=de;exports.FILE_AUDIO_ICON_SVG=Oe;exports.FILE_IMAGE_ICON_SVG=tt;exports.FILE_VIDEO_ICON_SVG=xt;exports.FilePanelExtension=O;exports.SuggestionMenu=Tt;exports.addDefaultPropsExternalHTML=I;exports.addInlineContentAttributes=Qt;exports.addInlineContentKeyboardShortcuts=Yt;exports.addNodeAndExtensionsToSpec=Kt;exports.addStyleAttributes=F;exports.applyNonSelectableBlockFix=we;exports.audioParse=Fe;exports.audioRender=Re;exports.audioToExternalHTML=We;exports.blockHasType=xn;exports.camelToDataKebab=W;exports.captureCellAnchor=_e;exports.createAudioBlockConfig=Ve;exports.createAudioBlockSpec=qe;exports.createBlockConfig=Xt;exports.createBlockSpec=E;exports.createBlockSpecFromTiptapNode=Le;exports.createBulletListItemBlockConfig=ct;exports.createBulletListItemBlockSpec=lt;exports.createCheckListItemBlockSpec=ut;exports.createCheckListItemConfig=dt;exports.createCodeBlockConfig=Ue;exports.createCodeBlockSpec=$e;exports.createDefaultBlockDOMOutputSpec=Se;exports.createDividerBlockConfig=je;exports.createDividerBlockSpec=Ge;exports.createFileBlockConfig=Ze;exports.createFileBlockSpec=Ke;exports.createHeadingBlockConfig=Ye;exports.createHeadingBlockSpec=Je;exports.createImageBlockConfig=nt;exports.createImageBlockSpec=st;exports.createInlineContentSpecFromTipTapNode=Jt;exports.createInternalInlineContentSpec=Te;exports.createInternalStyleSpec=oe;exports.createNumberedListItemBlockConfig=ft;exports.createNumberedListItemBlockSpec=gt;exports.createParagraphBlockConfig=bt;exports.createParagraphBlockSpec=Ct;exports.createQuoteBlockConfig=kt;exports.createQuoteBlockSpec=yt;exports.createStyleSpec=re;exports.createStyleSpecFromTipTapMark=_;exports.createTableBlockSpec=Et;exports.createToggleListItemBlockConfig=ht;exports.createToggleListItemBlockSpec=mt;exports.createToggleWrapper=ce;exports.createVideoBlockConfig=Mt;exports.createVideoBlockSpec=wt;exports.defaultBlockSpecs=Nn;exports.defaultBlockToHTML=te;exports.defaultInlineContentSchema=_n;exports.defaultInlineContentSpecs=Pt;exports.defaultProps=g;exports.defaultStyleSchema=Dn;exports.defaultStyleSpecs=At;exports.defaultToggledState=Xe;exports.editorHasBlockWithType=C;exports.fileParse=ze;exports.filenameFromURL=Zt;exports.filterSuggestionItems=Pn;exports.formatKeyboardShortcut=B;exports.getBackgroundColorAttribute=an;exports.getBlockFromPos=Me;exports.getDefaultSlashMenuItems=An;exports.getInlineContentSchemaFromSpecs=Ae;exports.getLanguageId=ie;exports.getNodeById=He;exports.getParseRules=Be;exports.getStyleParseRules=Ie;exports.getStyleSchemaFromSpecs=Ne;exports.getTextAlignmentAttribute=cn;exports.getTextColorAttribute=sn;exports.imageParse=ot;exports.imageRender=rt;exports.imageToExternalHTML=at;exports.insertOrUpdateBlockForSlashMenu=k;exports.isAppleOS=ve;exports.isNodeBlock=De;exports.isSafari=Gt;exports.isTableCellSelection=Mn;exports.isVideoUrl=zt;exports.mergeCSSClasses=V;exports.mergeParagraphs=Ee;exports.parseAudioElement=ne;exports.parseDefaultProps=v;exports.propsToAttributes=xe;exports.splitBlockCommand=gn;exports.stylePropsToAttributes=Pe;exports.tablePropSchema=vt;exports.trackPosition=Bt;exports.updateBlock=nn;exports.updateBlockCommand=en;exports.updateBlockTr=K;exports.videoParse=Lt;exports.wrapInBlockStructure=Z;
+`:"<br>"),R.DOMParser.fromSchema(r).parse(i,{topNode:r.nodes.paragraph.create(),preserveWhitespace:!0}).content}return R.Fragment.empty}:void 0}),n}function Kt(e,t,n,o){var a,s,i,c;const r=t.node||S.Node.create({name:e.type,content:e.content==="inline"?"inline*":e.content==="none"?"":e.content,group:"blockContent",selectable:((a=t.meta)==null?void 0:a.selectable)??!0,isolating:((s=t.meta)==null?void 0:s.isolating)??!0,code:((i=t.meta)==null?void 0:i.code)??!1,defining:((c=t.meta)==null?void 0:c.defining)??!0,priority:o,addAttributes(){return xe(e.propSchema)},parseHTML(){return Be(e,t)},renderHTML({HTMLAttributes:l}){var d;const u=document.createElement("div");return Z({dom:u,contentDOM:e.content==="inline"?u:void 0},e.type,{},e.propSchema,((d=t.meta)==null?void 0:d.fileBlockAccept)!==void 0,l)},addNodeView(){return l=>{var f,x;const u=this.options.editor,d=Me(l.getPos,u,this.editor,e.type),p=((f=this.options.domAttributes)==null?void 0:f.blockContent)||{},h=t.render.call({blockContentDOMAttributes:p,props:l,renderType:"nodeView"},d,u);return((x=t.meta)==null?void 0:x.selectable)===!1&&we(h,this.editor),h}}});if(r.name!==e.type)throw new Error("Node name does not match block type. This is a bug in BlockNote.");return{config:e,implementation:{...t,node:r,render(l,u){var p;const d=((p=r.options.domAttributes)==null?void 0:p.blockContent)||{};return t.render.call({blockContentDOMAttributes:d,props:void 0,renderType:"dom"},l,u)},toExternalHTML:(l,u,d)=>{var h,f;const p=((h=r.options.domAttributes)==null?void 0:h.blockContent)||{};return((f=t.toExternalHTML)==null?void 0:f.call({blockContentDOMAttributes:p},l,u,d))??t.render.call({blockContentDOMAttributes:p,renderType:"dom",props:void 0},l,u)}},extensions:n}}function Xt(e){return e}function E(e,t,n){return(o={})=>{const r=typeof e=="function"?e(o):e,a=typeof t=="function"?t(o):t,s=n?typeof n=="function"?n(o):n:void 0;return{config:r,implementation:{...a,toExternalHTML(i,c,l){var d,p;const u=(d=a.toExternalHTML)==null?void 0:d.call({blockContentDOMAttributes:this.blockContentDOMAttributes},i,c,l);if(u!==void 0)return Z(u,i.type,i.props,r.propSchema,((p=a.meta)==null?void 0:p.fileBlockAccept)!==void 0)},render(i,c){var d;const l=a.render.call({blockContentDOMAttributes:this.blockContentDOMAttributes,renderType:this.renderType,props:this.props},i,c);return Z(l,i.type,i.props,r.propSchema,((d=a.meta)==null?void 0:d.fileBlockAccept)!==void 0,this.blockContentDOMAttributes)}},extensions:s}}}function Qt(e,t,n,o){return e.dom.setAttribute("data-inline-content-type",t),Object.entries(n).filter(([r,a])=>{const s=o[r];return a!==s.default}).map(([r,a])=>[W(r),a]).forEach(([r,a])=>e.dom.setAttribute(r,a)),e.contentDOM&&e.contentDOM.setAttribute("data-editable",""),e}function Yt(e){return{Backspace:({editor:t})=>{const n=t.state.selection.$from;return t.state.selection.empty&&n.node().type.name===e.type&&n.parentOffset===0}}}function Te(e,t){return{config:e,implementation:t}}function Jt(e,t,n){return Te({type:e.name,propSchema:t,content:e.config.content==="inline*"?"styled":"none"},{...n,node:e})}function Ae(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.config]))}function Pe(e){return e==="boolean"?{}:{stringValue:{default:void 0,keepOnSplit:!0,parseHTML:t=>t.getAttribute("data-value"),renderHTML:t=>t.stringValue!==void 0?{"data-value":t.stringValue}:{}}}}function F(e,t,n,o){return e.dom.setAttribute("data-style-type",t),o==="string"&&e.dom.setAttribute("data-value",n),e.contentDOM&&e.contentDOM.setAttribute("data-editable",""),e}function oe(e,t){return{config:e,implementation:t}}function _(e,t){return oe({type:e.name,propSchema:t},{mark:e,render(n,o){const r=o.pmSchema.marks[e.name].spec.toDOM;if(r===void 0)throw new Error("This block has no default HTML serialization as its corresponding TipTap node doesn't implement `renderHTML`.");const a=o.pmSchema.mark(e.name,{stringValue:n}),s=R.DOMSerializer.renderSpec(document,r(a,!0));if(typeof s!="object"||!("dom"in s))throw new Error("Cannot use this block's default HTML serialization as its corresponding TipTap mark's `renderHTML` function does not return an object with the `dom` property.");return s},toExternalHTML(n,o){const r=o.pmSchema.marks[e.name].spec.toDOM;if(r===void 0)throw new Error("This block has no default HTML serialization as its corresponding TipTap node doesn't implement `renderHTML`.");const a=o.pmSchema.mark(e.name,{stringValue:n}),s=R.DOMSerializer.renderSpec(document,r(a,!0));if(typeof s!="object"||!("dom"in s))throw new Error("Cannot use this block's default HTML serialization as its corresponding TipTap mark's `renderHTML` function does not return an object with the `dom` property.");return s}})}function Ne(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,n.config]))}function Ie(e,t){const n=[{tag:`[data-style-type="${e.type}"]`,contentElement:o=>{const r=o;return r.matches("[data-editable]")?r:r.querySelector("[data-editable]")||r}}];return t&&n.push({tag:"*",consuming:!1,getAttrs(o){if(typeof o=="string")return!1;const r=t==null?void 0:t(o);return r===void 0?!1:{stringValue:r}}}),n}function re(e,t){const n=S.Mark.create({name:e.type,addAttributes(){return Pe(e.propSchema)},parseHTML(){return Ie(e,t.parse)},renderHTML({mark:o}){const r=(t.toExternalHTML||t.render)(o.attrs.stringValue);return F(r,e.type,o.attrs.stringValue,e.propSchema)},addMarkView(){return({mark:o})=>{const r=t.render(o.attrs.stringValue);return F(r,e.type,o.attrs.stringValue,e.propSchema)}}});return oe(e,{...t,mark:n,render:o=>{const r=t.render(o);return F(r,e.type,o,e.propSchema)},toExternalHTML:o=>{const r=(t.toExternalHTML||t.render)(o);return F(r,e.type,o,e.propSchema)}})}function He(e,t){let n,o;if(t.firstChild.descendants((r,a)=>n?!1:!De(r)||r.attrs.id!==e?!0:(n=r,o=a+1,!1)),!(n===void 0||o===void 0))return{node:n,posBeforeNode:o}}function De(e){return e.type.isInGroup("bnBlock")}const en=(e,t)=>({tr:n,dispatch:o})=>(o&&K(n,e,t),!0);function K(e,t,n,o,r){const a=m.getBlockInfoFromResolvedPos(e.doc.resolve(t));let s=null;a.blockNoteType==="table"&&(s=_e(e));const i=m.getPmSchema(e);if(o!==void 0&&r!==void 0&&o>r)throw new Error("Invalid replaceFromPos or replaceToPos");const c=i.nodes[a.blockNoteType],l=i.nodes[n.type||a.blockNoteType],u=l.isInGroup("bnBlock")?l:i.nodes.blockContainer;if(a.isBlockContainer&&l.isInGroup("blockContent")){const d=o!==void 0&&o>a.blockContent.beforePos&&o<a.blockContent.afterPos?o-a.blockContent.beforePos-1:void 0,p=r!==void 0&&r>a.blockContent.beforePos&&r<a.blockContent.afterPos?r-a.blockContent.beforePos-1:void 0;ge(n,e,a),tn(n,e,c,l,a,d,p)}else if(!a.isBlockContainer&&l.isInGroup("bnBlock"))ge(n,e,a);else{const d=m.nodeToBlock(a.bnBlock.node,i);e.replaceWith(a.bnBlock.beforePos,a.bnBlock.afterPos,m.blockToNode({children:d.children,...n},i));return}e.setNodeMarkup(a.bnBlock.beforePos,u,{...a.bnBlock.node.attrs,...n.props}),s&&on(e,a,s)}function tn(e,t,n,o,r,a,s){const i=m.getPmSchema(t);let c="keep";if(e.content)if(typeof e.content=="string")c=m.inlineContentToNodes([e.content],i,o.name);else if(Array.isArray(e.content))c=m.inlineContentToNodes(e.content,i,o.name);else if(e.content.type==="tableContent")c=m.tableContentToNodes(e.content,i);else throw new m.UnreachableCaseError(e.content.type);else n.spec.content===""||o.spec.content!==n.spec.content&&(c=[]);if(c==="keep")t.setNodeMarkup(r.blockContent.beforePos,o,{...r.blockContent.node.attrs,...e.props});else if(a!==void 0||s!==void 0){t.setNodeMarkup(r.blockContent.beforePos,o,{...r.blockContent.node.attrs,...e.props});const l=r.blockContent.beforePos+1+(a??0),u=r.blockContent.beforePos+1+(s??r.blockContent.node.content.size),d=t.doc.resolve(r.blockContent.beforePos).depth,p=t.doc.resolve(l).depth,h=t.doc.resolve(u).depth;t.replace(l,u,new N.Slice(N.Fragment.from(c),p-d-1,h-d-1))}else t.replaceWith(r.blockContent.beforePos,r.blockContent.afterPos,o.createChecked({...r.blockContent.node.attrs,...e.props},c))}function ge(e,t,n){const o=m.getPmSchema(t);if(e.children!==void 0&&e.children.length>0){const r=e.children.map(a=>m.blockToNode(a,o));if(n.childContainer)t.step(new ye.ReplaceStep(n.childContainer.beforePos+1,n.childContainer.afterPos-1,new N.Slice(N.Fragment.from(r),0,0)));else{if(!n.isBlockContainer)throw new Error("impossible");t.insert(n.blockContent.afterPos,o.nodes.blockGroup.createChecked({},r))}}}function nn(e,t,n,o,r){const a=typeof t=="string"?t:t.id,s=He(a,e.doc);if(!s)throw new Error(`Block with ID ${a} not found`);K(e,s.posBeforeNode,n,o,r);const i=e.doc.resolve(s.posBeforeNode+1).node(),c=m.getPmSchema(e);return m.nodeToBlock(i,c)}function _e(e){const t="selection"in e?e.selection:null;if(!(t instanceof z.TextSelection))return null;const n=e.doc.resolve(t.head);let o=-1,r=-1;for(let L=n.depth;L>=0;L--){const M=n.node(L).type.name;if(o<0&&(M==="tableCell"||M==="tableHeader")&&(o=L),M==="table"){r=L;break}}if(o<0||r<0)return null;const a=n.before(o),s=n.before(r),i=e.doc.nodeAt(s);if(!i||i.type.name!=="table")return null;const c=T.TableMap.get(i),l=a-(s+1),u=c.map.indexOf(l);if(u<0)return null;const d=Math.floor(u/c.width),p=u%c.width,f=a+1+1,x=Math.max(0,t.head-f);return{row:d,col:p,offset:x}}function on(e,t,n){var L;if(t.blockNoteType!=="table")return!1;let o=-1;if(t.isBlockContainer)o=e.mapping.map(t.blockContent.beforePos);else{const M=e.mapping.map(t.bnBlock.beforePos),D=M+(((L=e.doc.nodeAt(M))==null?void 0:L.nodeSize)||0);e.doc.nodesBetween(M,D,(b,w)=>b.type.name==="table"?(o=w,!1):!0)}const r=o>=0?e.doc.nodeAt(o):null;if(!r||r.type.name!=="table")return!1;const a=T.TableMap.get(r),s=Math.max(0,Math.min(n.row,a.height-1)),i=Math.max(0,Math.min(n.col,a.width-1)),c=s*a.width+i,l=a.map[c];if(l==null)return!1;const d=o+1+l+1,p=e.doc.nodeAt(d),h=d+1,f=p?p.content.size:0,x=h+Math.max(0,Math.min(n.offset,f));return"selection"in e&&e.setSelection(z.TextSelection.create(e.doc,x)),!0}const A={gray:{text:"#9b9a97",background:"#ebeced"},brown:{text:"#64473a",background:"#e9e5e3"},red:{text:"#e03e3e",background:"#fbe4e4"},orange:{text:"#d9730d",background:"#f6e9d9"},yellow:{text:"#dfab01",background:"#fbf3db"},green:{text:"#4d6461",background:"#ddedea"},blue:{text:"#0b6e99",background:"#ddebf1"},purple:{text:"#6940a5",background:"#eae4f2"},pink:{text:"#ad1a72",background:"#f4dfeb"}},rn={gray:{text:"#bebdb8",background:"#9b9a97"},brown:{text:"#8e6552",background:"#64473a"},red:{text:"#ec4040",background:"#be3434"},orange:{text:"#e3790d",background:"#b7600a"},yellow:{text:"#dfab01",background:"#b58b00"},green:{text:"#6b8b87",background:"#4d6461"},blue:{text:"#0e87bc",background:"#0b6e99"},purple:{text:"#8552d7",background:"#6940a5"},pink:{text:"#da208f",background:"#ad1a72"}},g={backgroundColor:{default:"default"},textColor:{default:"default"},textAlignment:{default:"left",values:["left","center","right","justify"]}},v=e=>{const t={};return e.hasAttribute("data-background-color")?t.backgroundColor=e.getAttribute("data-background-color"):e.style.backgroundColor&&(t.backgroundColor=e.style.backgroundColor),e.hasAttribute("data-text-color")?t.textColor=e.getAttribute("data-text-color"):e.style.color&&(t.textColor=e.style.color),t.textAlignment=g.textAlignment.values.includes(e.style.textAlign)?e.style.textAlign:void 0,t},I=(e,t)=>{e.backgroundColor&&e.backgroundColor!==g.backgroundColor.default&&(t.style.backgroundColor=e.backgroundColor in A?A[e.backgroundColor].background:e.backgroundColor),e.textColor&&e.textColor!==g.textColor.default&&(t.style.color=e.textColor in A?A[e.textColor].text:e.textColor),e.textAlignment&&e.textAlignment!==g.textAlignment.default&&(t.style.textAlign=e.textAlignment)},an=(e="backgroundColor")=>({default:g.backgroundColor.default,parseHTML:t=>t.hasAttribute("data-background-color")?t.getAttribute("data-background-color"):t.style.backgroundColor?t.style.backgroundColor:g.backgroundColor.default,renderHTML:t=>t[e]===g.backgroundColor.default?{}:{"data-background-color":t[e]}}),sn=(e="textColor")=>({default:g.textColor.default,parseHTML:t=>t.hasAttribute("data-text-color")?t.getAttribute("data-text-color"):t.style.color?t.style.color:g.textColor.default,renderHTML:t=>t[e]===g.textColor.default?{}:{"data-text-color":t[e]}}),cn=(e="textAlignment")=>({default:g.textAlignment.default,parseHTML:t=>t.hasAttribute("data-text-alignment")?t.getAttribute("data-text-alignment"):t.style.textAlign?t.style.textAlign:g.textAlignment.default,renderHTML:t=>t[e]===g.textAlignment.default?{}:{"data-text-alignment":t[e]}}),X=(e,t)=>{const n=e.querySelector(t);if(!n)return;const o=e.querySelector("figcaption"),r=(o==null?void 0:o.textContent)??void 0;return{targetElement:n,caption:r}},O=y.createExtension(({editor:e})=>{const t=y.createStore(void 0);function n(){t.setState(void 0)}return{key:"filePanel",store:t,mount({signal:o}){const r=e.onChange(n,!1),a=e.onSelectionChange(n,!1);o.addEventListener("abort",()=>{r(),a()})},closeMenu:n,showMenu(o){t.setState(o)}}}),ln=(e,t,n)=>{const o=document.createElement("div");o.className="bn-add-file-button";const r=document.createElement("div");r.className="bn-add-file-button-icon",n?r.appendChild(n):r.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M3 8L9.00319 2H19.9978C20.5513 2 21 2.45531 21 2.9918V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8ZM10 4V9H5V20H19V4H10Z"></path></svg>',o.appendChild(r);const a=document.createElement("p");a.className="bn-add-file-button-text",a.innerHTML=e.type in t.dictionary.file_blocks.add_button_text?t.dictionary.file_blocks.add_button_text[e.type]:t.dictionary.file_blocks.add_button_text.file,o.appendChild(a);const s=c=>{c.preventDefault(),c.stopPropagation()},i=()=>{var c;t.isEditable&&((c=t.getExtension(O))==null||c.showMenu(e.id))};return o.addEventListener("mousedown",s,!0),o.addEventListener("click",i,!0),{dom:o,destroy:()=>{o.removeEventListener("mousedown",s,!0),o.removeEventListener("click",i,!0)}}},dn='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M3 8L9.00319 2H19.9978C20.5513 2 21 2.45531 21 2.9918V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8ZM10 4V9H5V20H19V4H10Z"></path></svg>',un=e=>{const t=document.createElement("div");t.className="bn-file-name-with-icon";const n=document.createElement("div");n.className="bn-file-icon",n.innerHTML=dn,t.appendChild(n);const o=document.createElement("p");return o.className="bn-file-name",o.textContent=e.props.name,t.appendChild(o),{dom:t}},ae=(e,t,n,o)=>{const r=document.createElement("div");if(r.className="bn-file-block-content-wrapper",e.props.url===""){const s=ln(e,t,o);r.appendChild(s.dom);const i=t.onUploadStart(c=>{if(c===e.id){r.removeChild(s.dom);const l=document.createElement("div");l.className="bn-file-loading-preview",l.textContent="Loading...",r.appendChild(l)}});return{dom:r,destroy:()=>{i(),s.destroy()}}}const a={dom:r};if(e.props.showPreview===!1||!n){const s=un(e);r.appendChild(s.dom),a.destroy=()=>{var i;(i=s.destroy)==null||i.call(s)}}else r.appendChild(n.dom);if(e.props.caption){const s=document.createElement("p");s.className="bn-file-caption",s.textContent=e.props.caption,r.appendChild(s)}return a},se=(e,t)=>{const n=document.createElement("figure"),o=document.createElement("figcaption");return o.textContent=t,n.appendChild(e),n.appendChild(o),{dom:n}},Q=(e,t)=>{const n=document.createElement("div"),o=document.createElement("p");return o.textContent=t,n.appendChild(e),n.appendChild(o),{dom:n}},ne=e=>({url:e.src||void 0}),Oe='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M2 16.0001H5.88889L11.1834 20.3319C11.2727 20.405 11.3846 20.4449 11.5 20.4449C11.7761 20.4449 12 20.2211 12 19.9449V4.05519C12 3.93977 11.9601 3.8279 11.887 3.73857C11.7121 3.52485 11.3971 3.49335 11.1834 3.66821L5.88889 8.00007H2C1.44772 8.00007 1 8.44778 1 9.00007V15.0001C1 15.5524 1.44772 16.0001 2 16.0001ZM23 12C23 15.292 21.5539 18.2463 19.2622 20.2622L17.8445 18.8444C19.7758 17.1937 21 14.7398 21 12C21 9.26016 19.7758 6.80629 17.8445 5.15557L19.2622 3.73779C21.5539 5.75368 23 8.70795 23 12ZM18 12C18 10.0883 17.106 8.38548 15.7133 7.28673L14.2842 8.71584C15.3213 9.43855 16 10.64 16 12C16 13.36 15.3213 14.5614 14.2842 15.2841L15.7133 16.7132C17.106 15.6145 18 13.9116 18 12Z"></path></svg>',Ve=e=>({type:"audio",propSchema:{backgroundColor:g.backgroundColor,name:{default:""},url:{default:""},caption:{default:""},showPreview:{default:!0}},content:"none"}),Fe=(e={})=>t=>{if(t.tagName==="AUDIO"){if(t.closest("figure"))return;const{backgroundColor:n}=v(t);return{...ne(t),backgroundColor:n}}if(t.tagName==="FIGURE"){const n=X(t,"audio");if(!n)return;const{targetElement:o,caption:r}=n,{backgroundColor:a}=v(t);return{...ne(o),backgroundColor:a,caption:r}}},Re=(e={})=>(t,n)=>{const o=document.createElement("div");o.innerHTML=e.icon??Oe;const r=document.createElement("audio");return r.className="bn-audio",n.resolveFileUrl?n.resolveFileUrl(t.props.url).then(a=>{r.src=a}):r.src=t.props.url,r.controls=!0,r.contentEditable="false",r.draggable=!1,ae(t,n,{dom:r},o.firstElementChild)},We=(e={})=>(t,n)=>{if(!t.props.url){const r=document.createElement("p");return r.textContent="Add audio",{dom:r}}let o;return t.props.showPreview?(o=document.createElement("audio"),o.src=t.props.url):(o=document.createElement("a"),o.href=t.props.url,o.textContent=t.props.name||t.props.url),t.props.caption?t.props.showPreview?se(o,t.props.caption):Q(o,t.props.caption):{dom:o}},qe=E(Ve,e=>({meta:{fileBlockAccept:["audio/*"]},parse:Fe(e),render:Re(e),toExternalHTML:We(e),runsBefore:["file"]})),he=Symbol.for("blocknote.shikiParser"),J=Symbol.for("blocknote.shikiHighlighterPromise");function pn(e){const t=globalThis;let n,o,r=!1;const a=s=>{if(!e.createHighlighter)return process.env.NODE_ENV==="development"&&!r&&(console.log("For syntax highlighting of code blocks, you must provide a `createCodeBlockSpec({ createHighlighter: () => ... })` function"),r=!0),[];if(!n)return t[J]=t[J]||e.createHighlighter(),t[J].then(c=>{n=c});const i=ie(e,s.language);return!i||i==="text"||i==="none"||i==="plaintext"||i==="txt"?[]:n.getLoadedLanguages().includes(i)?(o||(o=t[he]||Rt.createParser(n),t[he]=o),o(s)):n.loadLanguage(i)};return Ft.createHighlightPlugin({parser:a,languageExtractor:s=>s.attrs.language,nodeTypes:["codeBlock"]})}const Ue=({defaultLanguage:e="text"})=>({type:"codeBlock",propSchema:{language:{default:e}},content:"inline"}),$e=E(Ue,e=>({meta:{code:!0,defining:!0,isolating:!1},parse:t=>{var r,a;if(t.tagName!=="PRE"||t.childElementCount!==1||((r=t.firstElementChild)==null?void 0:r.tagName)!=="CODE")return;const n=t.firstElementChild;return{language:n.getAttribute("data-language")||((a=n.className.split(" ").find(s=>s.includes("language-")))==null?void 0:a.replace("language-",""))}},parseContent:({el:t,schema:n})=>{const o=R.DOMParser.fromSchema(n),r=t.firstElementChild;return o.parse(r,{preserveWhitespace:"full",topNode:n.nodes.codeBlock.create()}).content},render(t,n){const o=document.createDocumentFragment(),r=document.createElement("pre"),a=document.createElement("code");r.appendChild(a);let s;if(e.supportedLanguages){const i=document.createElement("select");if(Object.entries(e.supportedLanguages??{}).forEach(([l,{name:u}])=>{const d=document.createElement("option");d.value=l,d.text=u,i.appendChild(d)}),i.value=t.props.language||e.defaultLanguage||"text",n.isEditable){const l=u=>{const d=u.target.value;n.updateBlock(t.id,{props:{language:d}})};i.addEventListener("change",l),s=()=>i.removeEventListener("change",l)}else i.disabled=!0;const c=document.createElement("div");c.contentEditable="false",c.appendChild(i),o.appendChild(c)}return o.appendChild(r),{dom:o,contentDOM:a,destroy:()=>{s==null||s()}}},toExternalHTML(t){const n=document.createElement("pre"),o=document.createElement("code");return o.className=`language-${t.props.language}`,o.dataset.language=t.props.language,n.appendChild(o),{dom:n,contentDOM:o}}}),e=>[y.createExtension({key:"code-block-highlighter",prosemirrorPlugins:[pn(e)]}),y.createExtension({key:"code-block-keyboard-shortcuts",keyboardShortcuts:{Delete:({editor:t})=>t.transact(n=>{const{block:o}=t.getTextCursorPosition();if(o.type!=="codeBlock")return!1;const{$from:r}=n.selection;return r.parent.textContent?!1:(t.removeBlocks([o]),!0)}),Tab:({editor:t})=>e.indentLineWithTab===!1?!1:t.transact(n=>{const{block:o}=t.getTextCursorPosition();return o.type==="codeBlock"?(n.insertText(" "),!0):!1}),Enter:({editor:t})=>t.transact(n=>{const{block:o,nextBlock:r}=t.getTextCursorPosition();if(o.type!=="codeBlock")return!1;const{$from:a}=n.selection,s=a.parentOffset===a.parent.nodeSize-2,i=a.parent.textContent.endsWith("\n ");if(s&&i){if(n.delete(a.pos-2,a.pos),r)return t.setTextCursorPosition(r,"start"),!0;const[c]=t.insertBlocks([{type:"paragraph"}],o,"after");return t.setTextCursorPosition(c,"start"),!0}return n.insertText(`
+`),!0}),"Shift-Enter":({editor:t})=>t.transact(()=>{const{block:n}=t.getTextCursorPosition();if(n.type!=="codeBlock")return!1;const[o]=t.insertBlocks([{type:"paragraph"}],n,"after");return t.setTextCursorPosition(o,"start"),!0})},inputRules:[{find:/^```(.*?)\s$/,replace:({match:t})=>{const n=t[1].trim();return{type:"codeBlock",props:{language:{language:ie(e,n)??n}.language},content:[]}}}]})]);function ie(e,t){var n;return(n=Object.entries(e.supportedLanguages??{}).find(([o,{aliases:r}])=>(r==null?void 0:r.includes(t))||o===t))==null?void 0:n[0]}const je=()=>({type:"divider",propSchema:{},content:"none"}),Ge=E(je,{meta:{isolating:!1},parse(e){if(e.tagName==="HR")return{}},render(){return{dom:document.createElement("hr")}}},[y.createExtension({key:"divider-block-shortcuts",inputRules:[{find:new RegExp("^---$"),replace(){return{type:"divider",props:{},content:[]}}}]})]),me=e=>({url:e.src||void 0}),Ze=()=>({type:"file",propSchema:{backgroundColor:g.backgroundColor,name:{default:""},url:{default:""},caption:{default:""}},content:"none"}),ze=()=>e=>{if(e.tagName==="EMBED"){if(e.closest("figure"))return;const{backgroundColor:t}=v(e);return{...me(e),backgroundColor:t}}if(e.tagName==="FIGURE"){const t=X(e,"embed");if(!t)return;const{targetElement:n,caption:o}=t,{backgroundColor:r}=v(e);return{...me(n),backgroundColor:r,caption:o}}},Ke=E(Ze,{meta:{fileBlockAccept:["*/*"]},parse:ze(),render(e,t){return ae(e,t)},toExternalHTML(e){if(!e.props.url){const n=document.createElement("p");return n.textContent="Add file",{dom:n}}const t=document.createElement("a");return t.href=e.props.url,t.textContent=e.props.name||e.props.url,e.props.caption?Q(t,e.props.caption):{dom:t}}}),Xe={set:(e,t)=>window.localStorage.setItem(`toggle-${e.id}`,t?"true":"false"),get:e=>window.localStorage.getItem(`toggle-${e.id}`)==="true"},ce=(e,t,n,o=Xe)=>{if("isToggleable"in e.props&&!e.props.isToggleable)return{dom:n};const r=document.createElement("div"),a=document.createElement("div");a.className="bn-toggle-wrapper";const s=document.createElement("button");s.className="bn-toggle-button",s.type="button",s.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="CURRENTCOLOR"><path d="M320-200v-560l440 280-440 280Z"/></svg>';const i=f=>f.preventDefault();s.addEventListener("mousedown",i);const c=()=>{var f;a.getAttribute("data-show-children")==="true"?(a.setAttribute("data-show-children","false"),o.set(t.getBlock(e),!1),r.contains(l)&&r.removeChild(l)):(a.setAttribute("data-show-children","true"),o.set(t.getBlock(e),!0),t.isEditable&&((f=t.getBlock(e))==null?void 0:f.children.length)===0&&!r.contains(l)&&r.appendChild(l))};s.addEventListener("click",c),a.appendChild(s),a.appendChild(n);const l=document.createElement("button");l.className="bn-toggle-add-block-button",l.type="button",l.textContent=t.dictionary.toggle_blocks.add_block_button;const u=f=>f.preventDefault();l.addEventListener("mousedown",u);const d=()=>{t.transact(()=>{const f=t.updateBlock(e,{children:[{}]});t.setTextCursorPosition(f.children[0].id,"end"),t.focus()})};l.addEventListener("click",d),r.appendChild(a);let p=e.children.length;const h=t.onChange(()=>{var x;const f=((x=t.getBlock(e))==null?void 0:x.children.length)??0;f>p?(a.getAttribute("data-show-children")==="false"&&(a.setAttribute("data-show-children","true"),o.set(t.getBlock(e),!0)),r.contains(l)&&r.removeChild(l)):f===0&&f<p&&(a.getAttribute("data-show-children")==="true"&&(a.setAttribute("data-show-children","false"),o.set(t.getBlock(e),!1)),r.contains(l)&&r.removeChild(l)),p=f});return o.get(e)?(a.setAttribute("data-show-children","true"),t.isEditable&&e.children.length===0&&r.appendChild(l)):a.setAttribute("data-show-children","false"),{dom:r,ignoreMutation:f=>f instanceof MutationRecord&&(f.type==="attributes"&&f.target===a&&f.attributeName==="data-show-children"||f.type==="childList"&&(f.addedNodes[0]===l||f.removedNodes[0]===l)),destroy:()=>{s.removeEventListener("mousedown",i),s.removeEventListener("click",c),l.removeEventListener("mousedown",u),l.removeEventListener("click",d),h==null||h()}}},Qe=[1,2,3,4,5,6],fn=e=>({editor:t})=>{const n=t.getTextCursorPosition();return t.schema.blockSchema[n.block.type].content!=="inline"?!1:(t.updateBlock(n.block,{type:"heading",props:{level:e}}),!0)},Ye=({defaultLevel:e=1,levels:t=Qe,allowToggleHeadings:n=!0}={})=>({type:"heading",propSchema:{...g,level:{default:e,values:t},...n?{isToggleable:{default:!1,optional:!0}}:{}},content:"inline"}),Je=E(Ye,({allowToggleHeadings:e=!0}={})=>({meta:{isolating:!1},parse(t){let n;switch(t.tagName){case"H1":n=1;break;case"H2":n=2;break;case"H3":n=3;break;case"H4":n=4;break;case"H5":n=5;break;case"H6":n=6;break;default:return}return{...v(t),level:n}},render(t,n){const o=document.createElement(`h${t.props.level}`);return e?{...ce(t,n,o),contentDOM:o}:{dom:o,contentDOM:o}},toExternalHTML(t){const n=document.createElement(`h${t.props.level}`);return I(t.props,n),{dom:n,contentDOM:n}}}),({levels:e=Qe}={})=>[y.createExtension({key:"heading-shortcuts",keyboardShortcuts:Object.fromEntries(e.map(t=>[`Mod-Alt-${t}`,fn(t)])??[]),inputRules:e.map(t=>({find:new RegExp(`^(#{${t}})\\s$`),replace({match:n}){return{type:"heading",props:{level:n[1].length}}}}))})]),et=(e,t,n,o,r)=>{const{dom:a,destroy:s}=ae(e,t,n,r),i=a;i.style.position="relative",e.props.url&&e.props.showPreview&&(e.props.previewWidth?i.style.width=`${e.props.previewWidth}px`:i.style.width="fit-content");const c=document.createElement("div");c.className="bn-resize-handle",c.style.left="4px";const l=document.createElement("div");l.className="bn-resize-handle",l.style.right="4px";const u=document.createElement("div");u.style.position="absolute",u.style.height="100%",u.style.width="100%";let d,p=e.props.previewWidth;const h=b=>{var ue,pe;if(!d){!t.isEditable&&o.contains(c)&&o.contains(l)&&(o.removeChild(c),o.removeChild(l));return}let w;const U="touches"in b?b.touches[0].clientX:b.clientX;e.props.textAlignment==="center"?d.handleUsed==="left"?w=d.initialWidth+(d.initialClientX-U)*2:w=d.initialWidth+(U-d.initialClientX)*2:d.handleUsed==="left"?w=d.initialWidth+d.initialClientX-U:w=d.initialWidth+U-d.initialClientX,p=Math.min(Math.max(w,64),((pe=(ue=t.domElement)==null?void 0:ue.firstElementChild)==null?void 0:pe.clientWidth)||Number.MAX_VALUE),i.style.width=`${p}px`},f=b=>{(!b.target||!i.contains(b.target)||!t.isEditable)&&o.contains(c)&&o.contains(l)&&(o.removeChild(c),o.removeChild(l)),d&&(d=void 0,i.contains(u)&&i.removeChild(u),t.updateBlock(e,{props:{previewWidth:p}}))},x=()=>{t.isEditable&&(o.appendChild(c),o.appendChild(l))},L=b=>{b.relatedTarget===c||b.relatedTarget===l||d||t.isEditable&&o.contains(c)&&o.contains(l)&&(o.removeChild(c),o.removeChild(l))},M=b=>{b.preventDefault(),i.contains(u)||i.appendChild(u);const w="touches"in b?b.touches[0].clientX:b.clientX;d={handleUsed:"left",initialWidth:i.clientWidth,initialClientX:w}},D=b=>{b.preventDefault(),i.contains(u)||i.appendChild(u);const w="touches"in b?b.touches[0].clientX:b.clientX;d={handleUsed:"right",initialWidth:i.clientWidth,initialClientX:w}};return window.addEventListener("mousemove",h),window.addEventListener("touchmove",h),window.addEventListener("mouseup",f),window.addEventListener("touchend",f),i.addEventListener("mouseenter",x),i.addEventListener("mouseleave",L),c.addEventListener("mousedown",M),c.addEventListener("touchstart",M),l.addEventListener("mousedown",D),l.addEventListener("touchstart",D),{dom:i,destroy:()=>{s==null||s(),window.removeEventListener("mousemove",h),window.removeEventListener("touchmove",h),window.removeEventListener("mouseup",f),window.removeEventListener("touchend",f),i.removeEventListener("mouseenter",x),i.removeEventListener("mouseleave",L),c.removeEventListener("mousedown",M),c.removeEventListener("touchstart",M),l.removeEventListener("mousedown",D),l.removeEventListener("touchstart",D)}}},be=e=>{const t=e.src||void 0,n=e.width||void 0,o=e.alt||void 0;return{url:t,previewWidth:n,name:o}},tt='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M5 11.1005L7 9.1005L12.5 14.6005L16 11.1005L19 14.1005V5H5V11.1005ZM4 3H20C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3ZM15.5 10C14.6716 10 14 9.32843 14 8.5C14 7.67157 14.6716 7 15.5 7C16.3284 7 17 7.67157 17 8.5C17 9.32843 16.3284 10 15.5 10Z"></path></svg>',nt=(e={})=>({type:"image",propSchema:{textAlignment:g.textAlignment,backgroundColor:g.backgroundColor,name:{default:""},url:{default:""},caption:{default:""},showPreview:{default:!0},previewWidth:{default:void 0,type:"number"}},content:"none"}),ot=(e={})=>t=>{if(t.tagName==="IMG"){if(t.closest("figure"))return;const{backgroundColor:n}=v(t);return{...be(t),backgroundColor:n}}if(t.tagName==="FIGURE"){const n=X(t,"img");if(!n)return;const{targetElement:o,caption:r}=n,{backgroundColor:a}=v(t);return{...be(o),backgroundColor:a,caption:r}}},rt=(e={})=>(t,n)=>{const o=document.createElement("div");o.innerHTML=e.icon??tt;const r=document.createElement("div");r.className="bn-visual-media-wrapper";const a=document.createElement("img");return a.className="bn-visual-media",n.resolveFileUrl?n.resolveFileUrl(t.props.url).then(s=>{a.src=s}):a.src=t.props.url,a.alt=t.props.name||t.props.caption||"BlockNote image",a.contentEditable="false",a.draggable=!1,r.appendChild(a),et(t,n,{dom:r},r,o.firstElementChild)},at=(e={})=>(t,n)=>{if(!t.props.url){const r=document.createElement("p");return r.textContent="Add image",{dom:r}}let o;return t.props.showPreview?(o=document.createElement("img"),o.src=t.props.url,o.alt=t.props.name||t.props.caption||"BlockNote image",t.props.previewWidth&&(o.width=t.props.previewWidth)):(o=document.createElement("a"),o.href=t.props.url,o.textContent=t.props.name||t.props.url),t.props.caption?t.props.showPreview?se(o,t.props.caption):Q(o,t.props.caption):{dom:o}},st=E(nt,e=>({meta:{fileBlockAccept:["image/*"]},parse:ot(e),render:rt(e),toExternalHTML:at(e),runsBefore:["file"]})),gn=(e,t,n)=>({state:o,dispatch:r})=>r?it(o.tr,e,t,n):!0,it=(e,t,n,o)=>{const r=m.getNearestBlockPos(e.doc,t),a=m.getBlockInfo(r);if(!a.isBlockContainer)return!1;const s=m.getPmSchema(e),i=[{type:a.bnBlock.node.type,attrs:o?{...a.bnBlock.node.attrs,id:void 0}:{}},{type:n?a.blockContent.node.type:s.nodes.paragraph,attrs:o?{...a.blockContent.node.attrs}:{}}];return e.split(t,2,i),!0},Y=(e,t)=>{const{blockInfo:n,selectionEmpty:o}=e.transact(s=>({blockInfo:m.getBlockInfoFromTransaction(s),selectionEmpty:s.selection.anchor===s.selection.head}));if(!n.isBlockContainer)return!1;const{bnBlock:r,blockContent:a}=n;return a.node.type.name!==t||!o?!1:a.node.childCount===0?(e.transact(s=>{K(s,r.beforePos,{type:"paragraph",props:{}})}),!0):a.node.childCount>0?e.transact(s=>(s.deleteSelection(),it(s,s.selection.from,!0))):!1};function le(e,t,n){var d,p,h;const o=N.DOMParser.fromSchema(t),r=e,a=document.createElement("div");a.setAttribute("data-node-type","blockGroup");for(const f of Array.from(r.childNodes))a.appendChild(f.cloneNode(!0));let s=o.parse(a,{topNode:t.nodes.blockGroup.create()});((p=(d=s.firstChild)==null?void 0:d.firstChild)==null?void 0:p.type.name)==="checkListItem"&&(s=s.copy(s.content.cut(s.firstChild.firstChild.nodeSize+2)));const i=(h=s.firstChild)==null?void 0:h.firstChild;if(!(i!=null&&i.isTextblock))return N.Fragment.from(s);const c=t.nodes[n].create({},i.content),l=s.content.cut(i.nodeSize+2);if(l.size>0){const f=s.copy(l);return c.content.addToEnd(f)}return c.content}const ct=()=>({type:"bulletListItem",propSchema:{...g},content:"inline"}),lt=E(ct,{meta:{isolating:!1},parse(e){var n;if(e.tagName!=="LI")return;const t=e.parentElement;if(t!==null&&(t.tagName==="UL"||t.tagName==="DIV"&&((n=t.parentElement)==null?void 0:n.tagName)==="UL"))return v(e)},parseContent:({el:e,schema:t})=>le(e,t,"bulletListItem"),render(){const e=document.createElement("p");return{dom:e,contentDOM:e}},toExternalHTML(e){const t=document.createElement("li"),n=document.createElement("p");return I(e.props,t),t.appendChild(n),{dom:t,contentDOM:n}}},[y.createExtension({key:"bullet-list-item-shortcuts",keyboardShortcuts:{Enter:({editor:e})=>Y(e,"bulletListItem"),"Mod-Shift-8":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"bulletListItem",props:{}}),!0)}},inputRules:[{find:/^\s?[-+*]\s$/,replace({editor:e}){if(m.getBlockInfoFromSelection(e.prosemirrorState).blockNoteType!=="heading")return{type:"bulletListItem",props:{}}}}]})]),dt=()=>({type:"checkListItem",propSchema:{...g,checked:{default:!1,type:"boolean"}},content:"inline"}),ut=E(dt,{meta:{isolating:!1},parse(e){var n;if(e.tagName==="input")return e.closest("[data-content-type]")||e.closest("li")?void 0:e.type==="checkbox"?{checked:e.checked}:void 0;if(e.tagName!=="LI")return;const t=e.parentElement;if(t!==null&&(t.tagName==="UL"||t.tagName==="DIV"&&((n=t.parentElement)==null?void 0:n.tagName)==="UL")){const o=e.querySelector("input[type=checkbox]")||null;return o===null?void 0:{...v(e),checked:o.checked}}},parseContent:({el:e,schema:t})=>le(e,t,"checkListItem"),render(e,t){const n=document.createDocumentFragment(),o=document.createElement("input");o.type="checkbox",o.checked=e.props.checked,e.props.checked&&o.setAttribute("checked",""),o.addEventListener("change",()=>{const r=t.getBlock(e.id);if(!r)return;t.updateBlock(r,{props:{checked:!r.props.checked}})});const r=document.createElement("p"),a=document.createElement("div");return a.contentEditable="false",a.appendChild(o),n.appendChild(a),n.appendChild(r),{dom:n,contentDOM:r}},toExternalHTML(e){const t=document.createElement("li"),n=document.createElement("input");n.type="checkbox",n.checked=e.props.checked,e.props.checked&&n.setAttribute("checked","");const o=document.createElement("p");return I(e.props,t),t.appendChild(n),t.appendChild(o),{dom:t,contentDOM:o}},runsBefore:["bulletListItem"]},[y.createExtension({key:"check-list-item-shortcuts",keyboardShortcuts:{Enter:({editor:e})=>Y(e,"checkListItem"),"Mod-Shift-9":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"checkListItem",props:{}}),!0)}},inputRules:[{find:/^\s?\[\s*\]\s$/,replace(){return{type:"checkListItem",props:{checked:!1}}}},{find:/^\s?\[[Xx]\]\s$/,replace(){return{type:"checkListItem",props:{checked:!0}}}}]})]);function pt(e,t,n,o){let r=e.firstChild.attrs.start||1,a=!0;const s=!!e.firstChild.attrs.start,i=m.getBlockInfo({posBeforeNode:t,node:e});if(!i.isBlockContainer)throw new Error("impossible");const c=n.doc.resolve(i.bnBlock.beforePos).nodeBefore,l=c?o.get(c):void 0;return l!==void 0?(r=l+1,a=!1):c&&m.getBlockInfo({posBeforeNode:i.bnBlock.beforePos-c.nodeSize,node:c}).blockNoteType==="numberedListItem"&&(r=pt(c,i.bnBlock.beforePos-c.nodeSize,n,o).index+1,a=!1),o.set(e,r),{index:r,isFirst:a,hasStart:s}}function Ce(e,t){const n=new Map,o=t.decorations.map(e.mapping,e.doc),r=[];e.doc.nodesBetween(0,e.doc.nodeSize-2,(s,i)=>{if(s.type.name==="blockContainer"&&s.firstChild.type.name==="numberedListItem"){const{index:c,isFirst:l,hasStart:u}=pt(s,i,e,n);if(o.find(i,i+s.nodeSize,p=>p.index===c&&p.isFirst===l&&p.hasStart===u).length===0){const p=e.doc.nodeAt(i+1);r.push(ee.Decoration.node(i+1,i+1+p.nodeSize,{"data-index":c.toString()}))}}});const a=r.flatMap(s=>o.find(s.from,s.to));return{decorations:o.remove(a).add(e.doc,r)}}const hn=()=>new fe.Plugin({key:new fe.PluginKey("numbered-list-indexing-decorations"),state:{init(e,t){return Ce(t.tr,{decorations:ee.DecorationSet.empty})},apply(e,t){return!e.docChanged&&!e.selectionSet&&t.decorations?t:Ce(e,t)}},props:{decorations(e){var t;return((t=this.getState(e))==null?void 0:t.decorations)??ee.DecorationSet.empty}}}),ft=()=>({type:"numberedListItem",propSchema:{...g,start:{default:void 0,type:"number"}},content:"inline"}),gt=E(ft,{meta:{isolating:!1},parse(e){var n;if(e.tagName!=="LI")return;const t=e.parentElement;if(t!==null&&(t.tagName==="OL"||t.tagName==="DIV"&&((n=t.parentElement)==null?void 0:n.tagName)==="OL")){const o=parseInt(t.getAttribute("start")||"1"),r=v(e);return e.previousElementSibling||o===1?r:{...r,start:o}}},parseContent:({el:e,schema:t})=>le(e,t,"numberedListItem"),render(){const e=document.createElement("p");return{dom:e,contentDOM:e}},toExternalHTML(e){const t=document.createElement("li"),n=document.createElement("p");return I(e.props,t),t.appendChild(n),{dom:t,contentDOM:n}}},[y.createExtension({key:"numbered-list-item-shortcuts",inputRules:[{find:/^\s?(\d+)\.\s$/,replace({match:e,editor:t}){if(m.getBlockInfoFromSelection(t.prosemirrorState).blockNoteType==="heading")return;const o=parseInt(e[1]);return{type:"numberedListItem",props:{start:o!==1?o:void 0}}}}],keyboardShortcuts:{Enter:({editor:e})=>Y(e,"numberedListItem"),"Mod-Shift-7":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"numberedListItem",props:{}}),!0)}},prosemirrorPlugins:[hn()]})]),ht=()=>({type:"toggleListItem",propSchema:{...g},content:"inline"}),mt=E(ht,{meta:{isolating:!1},render(e,t){const n=document.createElement("p");return{...ce(e,t,n),contentDOM:n}},toExternalHTML(e){const t=document.createElement("li"),n=document.createElement("p");return I(e.props,t),t.appendChild(n),{dom:t,contentDOM:n}}},[y.createExtension({key:"toggle-list-item-shortcuts",keyboardShortcuts:{Enter:({editor:e})=>Y(e,"toggleListItem"),"Mod-Shift-6":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"toggleListItem",props:{}}),!0)}}})]),bt=()=>({type:"paragraph",propSchema:g,content:"inline"}),Ct=E(bt,{meta:{isolating:!1},parse:e=>{var t;if(e.tagName==="P"&&(t=e.textContent)!=null&&t.trim())return v(e)},render:()=>{const e=document.createElement("p");return{dom:e,contentDOM:e}},toExternalHTML:e=>{const t=document.createElement("p");return I(e.props,t),{dom:t,contentDOM:t}},runsBefore:["default"]},[y.createExtension({key:"paragraph-shortcuts",keyboardShortcuts:{"Mod-Alt-0":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"paragraph",props:{}}),!0)}}})]),kt=()=>({type:"quote",propSchema:{backgroundColor:g.backgroundColor,textColor:g.textColor},content:"inline"}),yt=E(kt,{meta:{isolating:!1},parse(e){if(e.tagName==="BLOCKQUOTE"){const{backgroundColor:t,textColor:n}=v(e);return{backgroundColor:t,textColor:n}}},render(){const e=document.createElement("blockquote");return{dom:e,contentDOM:e}},toExternalHTML(e){const t=document.createElement("blockquote");return I(e.props,t),{dom:t,contentDOM:t}}},[y.createExtension({key:"quote-block-shortcuts",keyboardShortcuts:{"Mod-Alt-q":({editor:e})=>{const t=e.getTextCursorPosition();return e.schema.blockSchema[t.block.type].content!=="inline"?!1:(e.updateBlock(t.block,{type:"quote",props:{}}),!0)}},inputRules:[{find:new RegExp("^>\\s$"),replace(){return{type:"quote",props:{}}}}]})]),mn=35,de=120,bn=31,Cn=S.Extension.create({name:"BlockNoteTableExtension",addProseMirrorPlugins:()=>[T.columnResizing({cellMinWidth:mn,defaultCellMinWidth:de,View:null}),T.tableEditing()],addKeyboardShortcuts(){return{Enter:()=>this.editor.state.selection.empty&&this.editor.state.selection.$head.parent.type.name==="tableParagraph"?(this.editor.commands.insertContent({type:"hardBreak"}),!0):!1,Backspace:()=>{const e=this.editor.state.selection,t=e.empty,n=e.$head.parentOffset===0,o=e.$head.node().type.name==="tableParagraph";return t&&n&&o},Tab:()=>this.editor.commands.command(({state:e,dispatch:t,view:n})=>T.goToNextCell(1)(e,t,n)),"Shift-Tab":()=>this.editor.commands.command(({state:e,dispatch:t,view:n})=>T.goToNextCell(-1)(e,t,n))}},extendNodeSchema(e){const t={name:e.name,options:e.options,storage:e.storage};return{tableRole:S.callOrReturn(S.getExtensionField(e,"tableRole",t))}}}),vt={textColor:g.textColor},kn=S.Node.create({name:"tableHeader",addOptions(){return{HTMLAttributes:{}}},content:"tableContent+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:e=>{const t=e.getAttribute("colwidth");return t?t.split(",").map(o=>parseInt(o,10)):null}}}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th",getContent:(e,t)=>St(e,t)}]},renderHTML({HTMLAttributes:e}){return["th",S.mergeAttributes(this.options.HTMLAttributes,e),0]}}),yn=S.Node.create({name:"tableCell",addOptions(){return{HTMLAttributes:{}}},content:"tableContent+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:e=>{const t=e.getAttribute("colwidth");return t?t.split(",").map(o=>parseInt(o,10)):null}}}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td",getContent:(e,t)=>St(e,t)}]},renderHTML({HTMLAttributes:e}){return["td",S.mergeAttributes(this.options.HTMLAttributes,e),0]}}),vn=S.Node.create({name:"table",content:"tableRow+",group:"blockContent",tableRole:"table",marks:"deletion insertion modification",isolating:!0,parseHTML(){return[{tag:"table"}]},renderHTML({node:e,HTMLAttributes:t}){var r,a,s;const n=Se(this.name,"table",{...((r=this.options.domAttributes)==null?void 0:r.blockContent)||{},...t},((a=this.options.domAttributes)==null?void 0:a.inlineContent)||{}),o=document.createElement("colgroup");for(const i of e.children[0].children)if(i.attrs.colwidth)for(const l of i.attrs.colwidth){const u=document.createElement("col");l&&(u.style=`width: ${l}px`),o.appendChild(u)}else o.appendChild(document.createElement("col"));return(s=n.dom.firstChild)==null||s.appendChild(o),n},addNodeView(){return({node:e,HTMLAttributes:t})=>{var o;class n extends T.TableView{constructor(a,s,i){super(a,s),this.node=a,this.cellMinWidth=s,this.blockContentHTMLAttributes=i;const c=document.createElement("div");c.className=V("bn-block-content",i.class),c.setAttribute("data-content-type","table");for(const[p,h]of Object.entries(i))p!=="class"&&c.setAttribute(p,h);const l=this.dom,u=document.createElement("div");u.className="tableWrapper-inner",u.appendChild(l.firstChild),l.appendChild(u),c.appendChild(l);const d=document.createElement("div");d.className="table-widgets-container",d.style.position="relative",l.appendChild(d),this.dom=c}ignoreMutation(a){return!a.target.closest(".tableWrapper-inner")||super.ignoreMutation(a)}}return new n(e,de,{...((o=this.options.domAttributes)==null?void 0:o.blockContent)||{},...t})}}}),Sn=S.Node.create({name:"tableParagraph",group:"tableContent",content:"inline*",parseHTML(){return[{tag:"p",getAttrs:e=>{if(typeof e=="string"||!e.textContent||!e.closest("[data-content-type]"))return!1;const t=e.parentElement;return t===null?!1:t.tagName==="TD"||t.tagName==="TH"?{}:!1},node:"tableParagraph"}]},renderHTML({HTMLAttributes:e}){return["p",e,0]}}),En=S.Node.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)+",tableRole:"row",marks:"deletion insertion modification",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:e}){return["tr",S.mergeAttributes(this.options.HTMLAttributes,e),0]}});function St(e,t){const o=N.DOMParser.fromSchema(t).parse(e,{topNode:t.nodes.blockGroup.create()}),r=[];return o.content.descendants(a=>{if(a.isInline)return r.push(a),!1}),N.Fragment.fromArray(r)}const Et=()=>Le({node:vn,type:"table",content:"table"},vt,[y.createExtension({key:"table-extensions",tiptapExtensions:[Cn,Sn,kn,yn,En]}),y.createExtension({key:"table-keyboard-delete",keyboardShortcuts:{Backspace:({editor:e})=>{if(!(e.prosemirrorState.selection instanceof T.CellSelection))return!1;const t=e.getTextCursorPosition().block,n=t.content;let o=0;for(const a of n.rows)for(const s of a.cells){if("type"in s&&s.content.length>0||!("type"in s)&&s.length>0)return!1;o++}let r=0;return e.prosemirrorState.selection.forEachCell(()=>{r++}),r<o?!1:(e.transact(()=>{(e.getPrevBlock(t)||e.getNextBlock(t))&&e.setTextCursorPosition(t),e.removeBlocks([t])}),!0)}}})]),ke=e=>{const t=e.src||void 0,n=e.width||void 0;return{url:t,previewWidth:n}},xt='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M2 3.9934C2 3.44476 2.45531 3 2.9918 3H21.0082C21.556 3 22 3.44495 22 3.9934V20.0066C22 20.5552 21.5447 21 21.0082 21H2.9918C2.44405 21 2 20.5551 2 20.0066V3.9934ZM8 5V19H16V5H8ZM4 5V7H6V5H4ZM18 5V7H20V5H18ZM4 9V11H6V9H4ZM18 9V11H20V9H18ZM4 13V15H6V13H4ZM18 13V15H20V13H18ZM4 17V19H6V17H4ZM18 17V19H20V17H18Z"></path></svg>',Mt=e=>({type:"video",propSchema:{textAlignment:g.textAlignment,backgroundColor:g.backgroundColor,name:{default:""},url:{default:""},caption:{default:""},showPreview:{default:!0},previewWidth:{default:void 0,type:"number"}},content:"none"}),Lt=e=>t=>{if(t.tagName==="VIDEO"){if(t.closest("figure"))return;const{backgroundColor:n}=v(t);return{...ke(t),backgroundColor:n}}if(t.tagName==="FIGURE"){const n=X(t,"video");if(!n)return;const{targetElement:o,caption:r}=n,{backgroundColor:a}=v(t);return{...ke(o),backgroundColor:a,caption:r}}},wt=E(Mt,e=>({meta:{fileBlockAccept:["video/*"]},parse:Lt(),render(t,n){const o=document.createElement("div");o.innerHTML=e.icon??xt;const r=document.createElement("div");r.className="bn-visual-media-wrapper";const a=document.createElement("video");return a.className="bn-visual-media",n.resolveFileUrl?n.resolveFileUrl(t.props.url).then(s=>{a.src=s}):a.src=t.props.url,a.controls=!0,a.contentEditable="false",a.draggable=!1,a.width=t.props.previewWidth,r.appendChild(a),et(t,n,{dom:r},r,o.firstElementChild)},toExternalHTML(t){if(!t.props.url){const o=document.createElement("p");return o.textContent="Add video",{dom:o}}let n;return t.props.showPreview?(n=document.createElement("video"),n.src=t.props.url,t.props.previewWidth&&(n.width=t.props.previewWidth)):(n=document.createElement("a"),n.href=t.props.url,n.textContent=t.props.name||t.props.url),t.props.caption?t.props.showPreview?se(n,t.props.caption):Q(n,t.props.caption):{dom:n}},runsBefore:["file"]}));function C(e,t,n){if(!(t in e.schema.blockSpecs))return!1;if(!n)return!0;for(const[o,r]of Object.entries(n)){if(!(o in e.schema.blockSpecs[t].config.propSchema))return!1;if(typeof r=="string"){if(e.schema.blockSpecs[t].config.propSchema[o].default!==void 0&&typeof e.schema.blockSpecs[t].config.propSchema[o].default!==r||e.schema.blockSpecs[t].config.propSchema[o].type!==void 0&&e.schema.blockSpecs[t].config.propSchema[o].type!==r)return!1}else{if(e.schema.blockSpecs[t].config.propSchema[o].default!==r.default||e.schema.blockSpecs[t].config.propSchema[o].default===void 0&&r.default===void 0&&e.schema.blockSpecs[t].config.propSchema[o].type!==r.type||typeof e.schema.blockSpecs[t].config.propSchema[o].values!=typeof r.values)return!1;if(typeof e.schema.blockSpecs[t].config.propSchema[o].values=="object"&&typeof r.values=="object"){for(const a of r.values)if(!e.schema.blockSpecs[t].config.propSchema[o].values.includes(a))return!1}}}return!0}function xn(e,t,n,o){return C(t,n,o)&&e.type===n}function Mn(e){return e instanceof T.CellSelection}const G=new Map;function Ln(e){if(G.has(e))return G.get(e);const t=new ye.Mapping;return e._tiptapEditor.on("transaction",({transaction:n})=>{t.appendMapping(n.mapping)}),e._tiptapEditor.on("destroy",()=>{G.delete(e)}),G.set(e,t),t}function Bt(e,t,n="left"){const o=j.ySyncPluginKey.getState(e.prosemirrorState);if(!o){const a=Ln(e),s=a.maps.length;return()=>a.slice(s).map(t,n==="left"?-1:1)}const r=j.absolutePositionToRelativePosition(t+(n==="right"?1:-1),o.binding.type,o.binding.mapping);return()=>{const a=j.ySyncPluginKey.getState(e.prosemirrorState),s=j.relativePositionToAbsolutePosition(a.doc,a.binding.type,r,a.binding.mapping);if(s===null)throw new Error("Position not found, cannot track positions");return s+(n==="right"?-1:1)}}const wn=S.findParentNode(e=>e.type.name==="blockContainer");class Bn{constructor(t,n,o){P(this,"state");P(this,"emitUpdate");P(this,"rootEl");P(this,"pluginState");P(this,"handleScroll",()=>{var t,n;if((t=this.state)!=null&&t.show){const o=(n=this.rootEl)==null?void 0:n.querySelector(`[data-decoration-id="${this.pluginState.decorationId}"]`);if(!o)return;this.state.referencePos=o.getBoundingClientRect().toJSON(),this.emitUpdate(this.pluginState.triggerCharacter)}});P(this,"closeMenu",()=>{this.editor.transact(t=>t.setMeta(H,null))});P(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(t=>t.selection.from)}).run()});var r;this.editor=t,this.pluginState=void 0,this.emitUpdate=a=>{var s;if(!this.state)throw new Error("Attempting to update uninitialized suggestions menu");n(a,{...this.state,ignoreQueryLength:(s=this.pluginState)==null?void 0:s.ignoreQueryLength})},this.rootEl=o.root,(r=this.rootEl)==null||r.addEventListener("scroll",this.handleScroll,!0)}update(t,n){var l;const o=H.getState(n),r=H.getState(t.state),a=o===void 0&&r!==void 0,s=o!==void 0&&r===void 0;if(!a&&!(o!==void 0&&r!==void 0)&&!s)return;if(this.pluginState=s?o:r,s||!this.editor.isEditable){this.state&&(this.state.show=!1),this.emitUpdate(this.pluginState.triggerCharacter);return}const c=(l=this.rootEl)==null?void 0:l.querySelector(`[data-decoration-id="${this.pluginState.decorationId}"]`);this.editor.isEditable&&c&&(this.state={show:!0,referencePos:c.getBoundingClientRect().toJSON(),query:this.pluginState.query},this.emitUpdate(this.pluginState.triggerCharacter))}destroy(){var t;(t=this.rootEl)==null||t.removeEventListener("scroll",this.handleScroll,!0)}}const H=new z.PluginKey("SuggestionMenuPlugin"),Tt=y.createExtension(({editor:e})=>{const t=[];let n;const o=y.createStore(void 0);return{key:"suggestionMenu",store:o,addTriggerCharacter:r=>{t.push(r)},removeTriggerCharacter:r=>{t.splice(t.indexOf(r),1)},closeMenu:()=>{n==null||n.closeMenu()},clearQuery:()=>{n==null||n.clearQuery()},shown:()=>{var r;return((r=n==null?void 0:n.state)==null?void 0:r.show)||!1},openSuggestionMenu:(r,a)=>{e.headless||(e.focus(),e.transact(s=>{a!=null&&a.deleteTriggerCharacter&&s.insertText(r),s.scrollIntoView().setMeta(H,{triggerCharacter:r,deleteTriggerCharacter:(a==null?void 0:a.deleteTriggerCharacter)||!1,ignoreQueryLength:(a==null?void 0:a.ignoreQueryLength)||!1})}))},prosemirrorPlugins:[new z.Plugin({key:H,view:r=>(n=new Bn(e,(a,s)=>{o.setState({...s,triggerCharacter:a})},r),n),state:{init(){},apply:(r,a,s,i)=>{if(r.selection.$from.parent.type.spec.code)return a;const c=r.getMeta(H);if(typeof c=="object"&&c!==null){a&&(n==null||n.closeMenu());const u=Bt(e,i.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(a===void 0)return a;if(i.selection.from!==i.selection.to||c===null||r.getMeta("focus")||r.getMeta("blur")||r.getMeta("pointer")||a.triggerCharacter!==void 0&&i.selection.from<a.queryStartPos()||!i.selection.$from.sameParent(i.doc.resolve(a.queryStartPos())))return;const l={...a};return l.query=i.doc.textBetween(a.queryStartPos(),i.selection.from),l}},props:{handleTextInput(r,a,s,i){if(a===s){const c=r.state.doc;for(const l of t){const u=l.length>1?c.textBetween(a-l.length,a)+i:i;if(l===u)return r.dispatch(r.state.tr.insertText(i)),r.dispatch(r.state.tr.setMeta(H,{triggerCharacter:u}).scrollIntoView()),!0}}return!1},decorations(r){const a=this.getState(r);if(a===void 0)return null;if(!a.deleteTriggerCharacter){const s=wn(r.selection);if(s)return $.DecorationSet.create(r.doc,[$.Decoration.node(s.pos,s.pos+s.node.nodeSize,{nodeName:"span",class:"bn-suggestion-decorator","data-decoration-id":a.decorationId})])}return $.DecorationSet.create(r.doc,[$.Decoration.inline(a.queryStartPos()-a.triggerCharacter.length,a.queryStartPos(),{nodeName:"span",class:"bn-suggestion-decorator","data-decoration-id":a.decorationId})])}}})]}});function Tn(e){let t=e.getTextCursorPosition().block,n=e.schema.blockSchema[t.type].content;for(;n==="none";){if(t=e.getTextCursorPosition().nextBlock,t===void 0)return;n=e.schema.blockSchema[t.type].content,e.setTextCursorPosition(t,"end")}}function k(e,t){const n=e.getTextCursorPosition().block;if(n.content===void 0)throw new Error("Slash Menu open in a block that doesn't contain content.");let o;return Array.isArray(n.content)&&(n.content.length===1&&m.isStyledTextInlineContent(n.content[0])&&n.content[0].type==="text"&&n.content[0].text==="/"||n.content.length===0)?(o=e.updateBlock(n,t),e.setTextCursorPosition(o)):(o=e.insertBlocks([t],n,"after")[0],e.setTextCursorPosition(e.getTextCursorPosition().nextBlock)),Tn(e),o}function An(e){const t=[];return C(e,"heading",{level:"number"})&&(e.schema.blockSchema.heading.propSchema.level.values||[]).filter(n=>n<=3).forEach(n=>{t.push({onItemClick:()=>{k(e,{type:"heading",props:{level:n}})},badge:B(`Mod-Alt-${n}`),key:n===1?"heading":`heading_${n}`,...e.dictionary.slash_menu[n===1?"heading":`heading_${n}`]})}),C(e,"quote")&&t.push({onItemClick:()=>{k(e,{type:"quote"})},key:"quote",...e.dictionary.slash_menu.quote}),C(e,"toggleListItem")&&t.push({onItemClick:()=>{k(e,{type:"toggleListItem"})},badge:B("Mod-Shift-6"),key:"toggle_list",...e.dictionary.slash_menu.toggle_list}),C(e,"numberedListItem")&&t.push({onItemClick:()=>{k(e,{type:"numberedListItem"})},badge:B("Mod-Shift-7"),key:"numbered_list",...e.dictionary.slash_menu.numbered_list}),C(e,"bulletListItem")&&t.push({onItemClick:()=>{k(e,{type:"bulletListItem"})},badge:B("Mod-Shift-8"),key:"bullet_list",...e.dictionary.slash_menu.bullet_list}),C(e,"checkListItem")&&t.push({onItemClick:()=>{k(e,{type:"checkListItem"})},badge:B("Mod-Shift-9"),key:"check_list",...e.dictionary.slash_menu.check_list}),C(e,"paragraph")&&t.push({onItemClick:()=>{k(e,{type:"paragraph"})},badge:B("Mod-Alt-0"),key:"paragraph",...e.dictionary.slash_menu.paragraph}),C(e,"codeBlock")&&t.push({onItemClick:()=>{k(e,{type:"codeBlock"})},badge:B("Mod-Alt-c"),key:"code_block",...e.dictionary.slash_menu.code_block}),C(e,"divider")&&t.push({onItemClick:()=>{k(e,{type:"divider"})},key:"divider",...e.dictionary.slash_menu.divider}),C(e,"table")&&t.push({onItemClick:()=>{k(e,{type:"table",content:{type:"tableContent",rows:[{cells:["","",""]},{cells:["","",""]}]}})},badge:void 0,key:"table",...e.dictionary.slash_menu.table}),C(e,"image",{url:"string"})&&t.push({onItemClick:()=>{var o;const n=k(e,{type:"image"});(o=e.getExtension(O))==null||o.showMenu(n.id)},key:"image",...e.dictionary.slash_menu.image}),C(e,"video",{url:"string"})&&t.push({onItemClick:()=>{var o;const n=k(e,{type:"video"});(o=e.getExtension(O))==null||o.showMenu(n.id)},key:"video",...e.dictionary.slash_menu.video}),C(e,"audio",{url:"string"})&&t.push({onItemClick:()=>{var o;const n=k(e,{type:"audio"});(o=e.getExtension(O))==null||o.showMenu(n.id)},key:"audio",...e.dictionary.slash_menu.audio}),C(e,"file",{url:"string"})&&t.push({onItemClick:()=>{var o;const n=k(e,{type:"file"});(o=e.getExtension(O))==null||o.showMenu(n.id)},key:"file",...e.dictionary.slash_menu.file}),C(e,"heading",{level:"number",isToggleable:"boolean"})&&(e.schema.blockSchema.heading.propSchema.level.values||[]).filter(n=>n<=3).forEach(n=>{t.push({onItemClick:()=>{k(e,{type:"heading",props:{level:n,isToggleable:!0}})},key:n===1?"toggle_heading":`toggle_heading_${n}`,...e.dictionary.slash_menu[n===1?"toggle_heading":`toggle_heading_${n}`]})}),C(e,"heading",{level:"number"})&&(e.schema.blockSchema.heading.propSchema.level.values||[]).filter(n=>n>3).forEach(n=>{t.push({onItemClick:()=>{k(e,{type:"heading",props:{level:n}})},badge:B(`Mod-Alt-${n}`),key:`heading_${n}`,...e.dictionary.slash_menu[`heading_${n}`]})}),t.push({onItemClick:()=>{var n;(n=e.getExtension(Tt))==null||n.openSuggestionMenu(":",{deleteTriggerCharacter:!0,ignoreQueryLength:!0})},key:"emoji",...e.dictionary.slash_menu.emoji}),t}function Pn(e,t){return e.filter(({title:n,aliases:o})=>n.toLowerCase().includes(t.toLowerCase())||o&&o.filter(r=>r.toLowerCase().includes(t.toLowerCase())).length!==0)}const Nn={audio:qe(),bulletListItem:lt(),checkListItem:ut(),codeBlock:$e(),divider:Ge(),file:Ke(),heading:Je(),image:st(),numberedListItem:gt(),paragraph:Ct(),quote:yt(),table:Et(),toggleListItem:mt(),video:wt()},In=re({type:"textColor",propSchema:"string"},{render:()=>{const e=document.createElement("span");return{dom:e,contentDOM:e}},toExternalHTML:e=>{const t=document.createElement("span");return e!==g.textColor.default&&(t.style.color=e in A?A[e].text:e),{dom:t,contentDOM:t}},parse:e=>{if(e.tagName==="SPAN"&&e.style.color)return e.style.color}}),Hn=re({type:"backgroundColor",propSchema:"string"},{render:()=>{const e=document.createElement("span");return{dom:e,contentDOM:e}},toExternalHTML:e=>{const t=document.createElement("span");return e!==g.backgroundColor.default&&(t.style.backgroundColor=e in A?A[e].background:e),{dom:t,contentDOM:t}},parse:e=>{if(e.tagName==="SPAN"&&e.style.backgroundColor)return e.style.backgroundColor}}),At={bold:_(Wt.default,"boolean"),italic:_(Ut.default,"boolean"),underline:_(jt.default,"boolean"),strike:_($t.default,"boolean"),code:_(qt.default,"boolean"),textColor:In,backgroundColor:Hn},Dn=Ne(At),Pt={text:{config:"text",implementation:{}},link:{config:"link",implementation:{}}},_n=Ae(Pt);exports.COLORS_DARK_MODE_DEFAULT=rn;exports.COLORS_DEFAULT=A;exports.EMPTY_CELL_HEIGHT=bn;exports.EMPTY_CELL_WIDTH=de;exports.FILE_AUDIO_ICON_SVG=Oe;exports.FILE_IMAGE_ICON_SVG=tt;exports.FILE_VIDEO_ICON_SVG=xt;exports.FilePanelExtension=O;exports.SuggestionMenu=Tt;exports.addDefaultPropsExternalHTML=I;exports.addInlineContentAttributes=Qt;exports.addInlineContentKeyboardShortcuts=Yt;exports.addNodeAndExtensionsToSpec=Kt;exports.addStyleAttributes=F;exports.applyNonSelectableBlockFix=we;exports.audioParse=Fe;exports.audioRender=Re;exports.audioToExternalHTML=We;exports.blockHasType=xn;exports.camelToDataKebab=W;exports.captureCellAnchor=_e;exports.createAudioBlockConfig=Ve;exports.createAudioBlockSpec=qe;exports.createBlockConfig=Xt;exports.createBlockSpec=E;exports.createBlockSpecFromTiptapNode=Le;exports.createBulletListItemBlockConfig=ct;exports.createBulletListItemBlockSpec=lt;exports.createCheckListItemBlockSpec=ut;exports.createCheckListItemConfig=dt;exports.createCodeBlockConfig=Ue;exports.createCodeBlockSpec=$e;exports.createDefaultBlockDOMOutputSpec=Se;exports.createDividerBlockConfig=je;exports.createDividerBlockSpec=Ge;exports.createFileBlockConfig=Ze;exports.createFileBlockSpec=Ke;exports.createHeadingBlockConfig=Ye;exports.createHeadingBlockSpec=Je;exports.createImageBlockConfig=nt;exports.createImageBlockSpec=st;exports.createInlineContentSpecFromTipTapNode=Jt;exports.createInternalInlineContentSpec=Te;exports.createInternalStyleSpec=oe;exports.createNumberedListItemBlockConfig=ft;exports.createNumberedListItemBlockSpec=gt;exports.createParagraphBlockConfig=bt;exports.createParagraphBlockSpec=Ct;exports.createQuoteBlockConfig=kt;exports.createQuoteBlockSpec=yt;exports.createStyleSpec=re;exports.createStyleSpecFromTipTapMark=_;exports.createTableBlockSpec=Et;exports.createToggleListItemBlockConfig=ht;exports.createToggleListItemBlockSpec=mt;exports.createToggleWrapper=ce;exports.createVideoBlockConfig=Mt;exports.createVideoBlockSpec=wt;exports.defaultBlockSpecs=Nn;exports.defaultBlockToHTML=te;exports.defaultInlineContentSchema=_n;exports.defaultInlineContentSpecs=Pt;exports.defaultProps=g;exports.defaultStyleSchema=Dn;exports.defaultStyleSpecs=At;exports.defaultToggledState=Xe;exports.editorHasBlockWithType=C;exports.fileParse=ze;exports.filenameFromURL=Zt;exports.filterSuggestionItems=Pn;exports.formatKeyboardShortcut=B;exports.getBackgroundColorAttribute=an;exports.getBlockFromPos=Me;exports.getDefaultSlashMenuItems=An;exports.getInlineContentSchemaFromSpecs=Ae;exports.getLanguageId=ie;exports.getNodeById=He;exports.getParseRules=Be;exports.getStyleParseRules=Ie;exports.getStyleSchemaFromSpecs=Ne;exports.getTextAlignmentAttribute=cn;exports.getTextColorAttribute=sn;exports.imageParse=ot;exports.imageRender=rt;exports.imageToExternalHTML=at;exports.insertOrUpdateBlockForSlashMenu=k;exports.isAppleOS=ve;exports.isNodeBlock=De;exports.isSafari=Gt;exports.isTableCellSelection=Mn;exports.isVideoUrl=zt;exports.mergeCSSClasses=V;exports.mergeParagraphs=Ee;exports.parseAudioElement=ne;exports.parseDefaultProps=v;exports.propsToAttributes=xe;exports.splitBlockCommand=gn;exports.stylePropsToAttributes=Pe;exports.tablePropSchema=vt;exports.trackPosition=Bt;exports.updateBlock=nn;exports.updateBlockCommand=en;exports.updateBlockTr=K;exports.videoParse=Lt;exports.wrapInBlockStructure=Z;
//# sourceMappingURL=defaultBlocks-DosClM5E.cjs.map
diff --git a/src/api/exporters/html/util/serializeBlocksExternalHTML.ts b/src/api/exporters/html/util/serializeBlocksExternalHTML.ts
index fb993f8309d9509df9b2dea85456dd587157d13a..d6dc4a08714d441ccadc297189a4ff8b20bc26ad 100644
--- a/src/api/exporters/html/util/serializeBlocksExternalHTML.ts
+++ b/src/api/exporters/html/util/serializeBlocksExternalHTML.ts
@@ -116,7 +116,7 @@ export function serializeInlineContentExternalHTML<
node.textContent,
);
// Reverse the order of marks to maintain the correct priority.
- for (const mark of node.marks.toReversed()) {
+ for (const mark of Array.from(node.marks).reverse()) {
if (mark.type.name in editor.schema.styleSpecs) {
const newDom = (
editor.schema.styleSpecs[mark.type.name].implementation
diff --git a/src/api/exporters/html/util/serializeBlocksInternalHTML.ts b/src/api/exporters/html/util/serializeBlocksInternalHTML.ts
index 0f890b77abec5ec6271b1280368a0efdd1be2aa5..9f0d95e21b9758bd04fd70d7fc542d31dff58d25 100644
--- a/src/api/exporters/html/util/serializeBlocksInternalHTML.ts
+++ b/src/api/exporters/html/util/serializeBlocksInternalHTML.ts
@@ -97,7 +97,7 @@ export function serializeInlineContentInternalHTML<
node.textContent,
);
// Reverse the order of marks to maintain the correct priority.
- for (const mark of node.marks.toReversed()) {
+ for (const mark of Array.from(node.marks).reverse()) {
if (mark.type.name in editor.schema.styleSpecs) {
const newDom = editor.schema.styleSpecs[
mark.type.name
diff --git a/src/blocks/Code/block.ts b/src/blocks/Code/block.ts
index dbb7fc33a9add7a96488349876bc56ad60111a3f..58c3cf181f25467d85cd8c3788b5b73dec88175a 100644
--- a/src/blocks/Code/block.ts
+++ b/src/blocks/Code/block.ts
@@ -134,6 +134,10 @@ export const createCodeBlockSpec = createBlockSpec(
const handleLanguageChange = (event: Event) => {
const language = (event.target as HTMLSelectElement).value;
+ if (!editor.getBlock(block.id)) {
+ return;
+ }
+
editor.updateBlock(block.id, { props: { language } });
};
select.addEventListener("change", handleLanguageChange);
diff --git a/src/blocks/ListItem/CheckListItem/block.ts b/src/blocks/ListItem/CheckListItem/block.ts
index b32ee408eaf81ccbabb39e5b0f95a2fa73358b0f..92aaa7cf2ec1cec169235c59ade06f0cb4519fb7 100644
--- a/src/blocks/ListItem/CheckListItem/block.ts
+++ b/src/blocks/ListItem/CheckListItem/block.ts
@@ -83,7 +83,12 @@ export const createCheckListItemBlockSpec = createBlockSpec(
checkbox.setAttribute("checked", "");
}
checkbox.addEventListener("change", () => {
- editor.updateBlock(block, { props: { checked: !block.props.checked } });
+ const liveBlock = editor.getBlock(block.id);
+ if (!liveBlock) {
+ return;
+ }
+
+ editor.updateBlock(liveBlock, { props: { checked: !liveBlock.props.checked } });
});
// We use a <p> tag, because for <li> tags we'd need a <ul> element to put
// them in to be semantically correct, which we can't have due to the
diff --git a/src/editor/managers/ExtensionManager/extensions.ts b/src/editor/managers/ExtensionManager/extensions.ts
index 45f0acf8e5d869eb13a3c3d70e6f67059f86c598..2a4d15c8e8465181cc009ed9912cd284e0930251 100644
--- a/src/editor/managers/ExtensionManager/extensions.ts
+++ b/src/editor/managers/ExtensionManager/extensions.ts
@@ -84,7 +84,10 @@ export function getDefaultTiptapExtensions(
}).configure({
defaultProtocol: DEFAULT_LINK_PROTOCOL,
// only call this once if we have multiple editors installed. Or fix https://github.com/ueberdosis/tiptap/issues/5450
- protocols: LINKIFY_INITIALIZED ? [] : VALID_LINK_PROTOCOLS,
+ // Tolaria routes editor link clicks through its guarded native opener.
+ openOnClick: false,
+ // Tolaria pre-registers BlockNote's non-native protocols before linkify initializes.
+ protocols: [],
}),
...(Object.values(editor.schema.styleSpecs).map((styleSpec) => {
return styleSpec.implementation.mark.configure({
diff --git a/src/extensions/SideMenu/SideMenu.ts b/src/extensions/SideMenu/SideMenu.ts
index 769e4a17154db2d88472696638db96e20131dfdb..a6c7f1a76eaa4db7b58774ae71ef47ab62805f66 100644
--- a/src/extensions/SideMenu/SideMenu.ts
+++ b/src/extensions/SideMenu/SideMenu.ts
@@ -194,6 +194,15 @@ export class SideMenuView<
this.emitUpdate(this.state);
};
+ private hideMenu = () => {
+ if (!this.state?.show) {
+ return;
+ }
+
+ this.state.show = false;
+ this.updateState(this.state);
+ };
+
updateStateFromMousePos = () => {
if (this.menuFrozen || !this.mousePos) {
return;
@@ -208,10 +217,7 @@ export class SideMenuView<
closestEditor?.element !== this.pmView.dom ||
closestEditor.distance > DISTANCE_TO_CONSIDER_EDITOR_BOUNDS
) {
- if (this.state?.show) {
- this.state.show = false;
- this.updateState(this.state);
- }
+ this.hideMenu();
return;
}
@@ -219,11 +225,7 @@ export class SideMenuView<
// Closes the menu if the mouse cursor is beyond the editor vertically.
if (!block || !this.editor.isEditable) {
- if (this.state?.show) {
- this.state.show = false;
- this.updateState(this.state);
- }
-
+ this.hideMenu();
return;
}
@@ -237,6 +239,15 @@ export class SideMenuView<
}
this.hoveredBlock = block.node;
+ const hoveredBlockId = this.hoveredBlock.getAttribute("data-id");
+ const hoveredEditorBlock = hoveredBlockId
+ ? this.editor.getBlock(hoveredBlockId)
+ : undefined;
+
+ if (!hoveredEditorBlock) {
+ this.hideMenu();
+ return;
+ }
// Shows or updates elements.
if (this.editor.isEditable) {
@@ -258,9 +269,7 @@ export class SideMenuView<
blockContentBoundingBox.width,
blockContentBoundingBox.height,
),
- block: this.editor.getBlock(
- this.hoveredBlock!.getAttribute("data-id")!,
- )!,
+ block: hoveredEditorBlock,
};
this.updateState(this.state);
}
diff --git a/src/extensions/SuggestionMenu/SuggestionMenu.ts b/src/extensions/SuggestionMenu/SuggestionMenu.ts
index 029103600a98bf8ccd3054a5c43ffa2fd9115c06..d1678ed4761baca0b3495dafc8d751525d528b4e 100644
--- a/src/extensions/SuggestionMenu/SuggestionMenu.ts
+++ b/src/extensions/SuggestionMenu/SuggestionMenu.ts
@@ -32,7 +32,7 @@ class SuggestionMenuView {
this.emitUpdate = (menuName: string) => {
if (!this.state) {
- throw new Error("Attempting to update uninitialized suggestions menu");
+ return;
}
emitUpdate(menuName, {
@@ -64,6 +64,15 @@ class SuggestionMenuView {
}
};
+ private hideMenu = (menuName: string) => {
+ if (!this.state) {
+ return;
+ }
+
+ this.state.show = false;
+ this.emitUpdate(menuName);
+ };
+
update(view: EditorView, prevState: EditorState) {
const prev: SuggestionPluginState =
suggestionMenuPluginKey.getState(prevState);
@@ -84,11 +93,7 @@ class SuggestionMenuView {
this.pluginState = stopped ? prev : next;
if (stopped || !this.editor.isEditable) {
- if (this.state) {
- this.state.show = false;
- }
- this.emitUpdate(this.pluginState!.triggerCharacter);
-
+ this.hideMenu(this.pluginState!.triggerCharacter);
return;
}
@@ -96,17 +101,20 @@ class SuggestionMenuView {
`[data-decoration-id="${this.pluginState!.decorationId}"]`,
);
- if (this.editor.isEditable && decorationNode) {
- this.state = {
- show: true,
- referencePos: decorationNode
- .getBoundingClientRect()
- .toJSON() as DOMRect,
- query: this.pluginState!.query,
- };
-
- this.emitUpdate(this.pluginState!.triggerCharacter!);
+ if (!decorationNode) {
+ this.hideMenu(this.pluginState!.triggerCharacter!);
+ return;
}
+
+ this.state = {
+ show: true,
+ referencePos: decorationNode
+ .getBoundingClientRect()
+ .toJSON() as DOMRect,
+ query: this.pluginState!.query,
+ };
+
+ this.emitUpdate(this.pluginState!.triggerCharacter!);
}
destroy() {
diff --git a/src/extensions/TableHandles/TableHandles.ts b/src/extensions/TableHandles/TableHandles.ts
index 3063774..9813bed 100644
--- a/src/extensions/TableHandles/TableHandles.ts
+++ b/src/extensions/TableHandles/TableHandles.ts
@@ -99,6 +99,46 @@ function getChildIndex(node: Element) {
return Array.prototype.indexOf.call(node.parentElement!.childNodes, node);
}
+function isValidTablePosition(tablePos: number | undefined): tablePos is number {
+ return Number.isInteger(tablePos) && tablePos >= 0;
+}
+
+function isValidCellIndex(index: number | undefined): index is number {
+ return Number.isInteger(index) && index >= 0;
+}
+
+function isValidRelativeCell(cell: RelativeCellIndices) {
+ return isValidCellIndex(cell.row) && isValidCellIndex(cell.col);
+}
+
+function resolveCellPosition(
+ state: EditorState,
+ tablePos: number | undefined,
+ relativeCell: RelativeCellIndices,
+) {
+ if (!isValidTablePosition(tablePos) || !isValidRelativeCell(relativeCell)) {
+ return undefined;
+ }
+
+ try {
+ const tableResolvedPos = state.doc.resolve(tablePos + 1);
+ if (relativeCell.row >= tableResolvedPos.node().childCount) {
+ return undefined;
+ }
+
+ const rowResolvedPos = state.doc.resolve(
+ tableResolvedPos.posAtIndex(relativeCell.row) + 1,
+ );
+ if (relativeCell.col >= rowResolvedPos.node().childCount) {
+ return undefined;
+ }
+
+ return state.doc.resolve(rowResolvedPos.posAtIndex(relativeCell.col));
+ } catch {
+ return undefined;
+ }
+}
+
// Finds the DOM element corresponding to the table cell that the target element
// is currently in. If the target element is not in a table cell, returns null.
function domCellAround(target: Element) {
@@ -187,6 +227,32 @@ export class TableHandlesView implements PluginView {
);
}
+ hideHandles = ({
+ resetCell = false,
+ resetDragging = false,
+ } = {}) => {
+ if (!this.state) {
+ return;
+ }
+
+ if (!this.state.show && !resetCell && !resetDragging) {
+ return;
+ }
+
+ this.state.show = false;
+ this.state.showAddOrRemoveRowsButton = false;
+ this.state.showAddOrRemoveColumnsButton = false;
+ if (resetDragging) {
+ this.state.draggingState = undefined;
+ }
+ if (resetCell) {
+ this.state.rowIndex = undefined;
+ this.state.colIndex = undefined;
+ this.state.referencePosCell = undefined;
+ }
+ this.emitUpdate();
+ };
+
viewMousedownHandler = () => {
this.mouseState = "down";
};
@@ -222,22 +288,12 @@ export class TableHandlesView implements PluginView {
// hide draghandles when selecting text as they could be in the way of the user
this.mouseState = "selecting";
- if (this.state?.show) {
- this.state.show = false;
- this.state.showAddOrRemoveRowsButton = false;
- this.state.showAddOrRemoveColumnsButton = false;
- this.emitUpdate();
- }
+ this.hideHandles();
return;
}
if (!target || !this.editor.isEditable) {
- if (this.state?.show) {
- this.state.show = false;
- this.state.showAddOrRemoveRowsButton = false;
- this.state.showAddOrRemoveColumnsButton = false;
- this.emitUpdate();
- }
+ this.hideHandles();
return;
}
@@ -298,7 +354,7 @@ export class TableHandlesView implements PluginView {
const hideHandles =
// always hide handles when the actively hovered table changed
- this.state?.block.id !== tableBlock.id ||
+ this.state?.block?.id !== tableBlock.id ||
// make sure we don't hide existing handles (keep col / row index) when
// we're hovering just above or to the right of a table
event.clientX > tableRect.right ||
@@ -458,9 +514,9 @@ export class TableHandlesView implements PluginView {
this.state.rowIndex === undefined ||
this.state.colIndex === undefined
) {
- throw new Error(
- "Attempted to drop table row or column, but no table block was hovered prior.",
- );
+ event.preventDefault();
+ this.hideHandles({ resetCell: true, resetDragging: true });
+ return false;
}
event.preventDefault();
@@ -533,7 +589,13 @@ export class TableHandlesView implements PluginView {
}
// Hide handles if the table block has been removed.
- this.state.block = this.editor.getBlock(this.state.block.id)!;
+ const currentBlock = this.state.block;
+ if (!currentBlock) {
+ this.hideHandles({ resetCell: true, resetDragging: true });
+ return;
+ }
+
+ this.state.block = this.editor.getBlock(currentBlock.id)!;
if (
!this.state.block ||
this.state.block.type !== "table" ||
@@ -541,11 +603,7 @@ export class TableHandlesView implements PluginView {
// because yjs replaces the element when for example you change the color via the side menu
!this.tableElement?.isConnected
) {
- this.state.show = false;
- this.state.showAddOrRemoveRowsButton = false;
- this.state.showAddOrRemoveColumnsButton = false;
- this.emitUpdate();
-
+ this.hideHandles();
return;
}
@@ -572,9 +630,8 @@ export class TableHandlesView implements PluginView {
const tableBody = this.tableElement!.querySelector("tbody");
if (!tableBody) {
- throw new Error(
- "Table block does not contain a 'tbody' HTML element. This should never happen.",
- );
+ this.hideHandles({ resetCell: true });
+ return;
}
if (
@@ -796,11 +853,11 @@ export const TableHandlesExtension = createExtension(({ editor }) => {
if (
view === undefined ||
view.state === undefined ||
- view.state.colIndex === undefined
+ view.state.colIndex === undefined ||
+ view.tablePos === undefined
) {
- throw new Error(
- "Attempted to drag table column, but no table block was hovered prior.",
- );
+ view?.hideHandles({ resetCell: true, resetDragging: true });
+ return;
}
view.state.draggingState = {
@@ -837,26 +894,30 @@ export const TableHandlesExtension = createExtension(({ editor }) => {
dataTransfer: DataTransfer | null;
clientY: number;
}) {
- if (view!.state === undefined || view!.state.rowIndex === undefined) {
- throw new Error(
- "Attempted to drag table row, but no table block was hovered prior.",
- );
+ if (
+ view === undefined ||
+ view.state === undefined ||
+ view.state.rowIndex === undefined ||
+ view.tablePos === undefined
+ ) {
+ view?.hideHandles({ resetCell: true, resetDragging: true });
+ return;
}
- view!.state.draggingState = {
+ view.state.draggingState = {
draggedCellOrientation: "row",
- originalIndex: view!.state.rowIndex,
+ originalIndex: view.state.rowIndex,
mousePos: event.clientY,
};
- view!.emitUpdate();
+ view.emitUpdate();
editor.transact((tr) =>
tr.setMeta(tableHandlesPluginKey, {
draggedCellOrientation:
- view!.state!.draggingState!.draggedCellOrientation,
- originalIndex: view!.state!.rowIndex,
- newIndex: view!.state!.rowIndex,
- tablePos: view!.tablePos,
+ view.state!.draggingState!.draggedCellOrientation,
+ originalIndex: view.state!.rowIndex,
+ newIndex: view.state!.rowIndex,
+ tablePos: view.tablePos,
}),
);
@@ -874,14 +935,15 @@ export const TableHandlesExtension = createExtension(({ editor }) => {
* used as the row drag handle, and the one used as the column drag handle.
*/
dragEnd() {
- if (view!.state === undefined) {
- throw new Error(
- "Attempted to drag table row, but no table block was hovered prior.",
- );
+ if (view === undefined || view.state === undefined) {
+ if (!editor.headless) {
+ unsetHiddenDragImage(editor.prosemirrorView.root);
+ }
+ return;
}
- view!.state.draggingState = undefined;
- view!.emitUpdate();
+ view.state.draggingState = undefined;
+ view.emitUpdate();
editor.transact((tr) => tr.setMeta(tableHandlesPluginKey, null));
@@ -938,22 +1000,21 @@ export const TableHandlesExtension = createExtension(({ editor }) => {
throw new Error("Table handles view not initialized");
}
- const tableResolvedPos = state.doc.resolve(view.tablePos! + 1);
- const startRowResolvedPos = state.doc.resolve(
- tableResolvedPos.posAtIndex(relativeStartCell.row) + 1,
- );
- const startCellResolvedPos = state.doc.resolve(
- // No need for +1, since CellSelection expects the position before the cell
- startRowResolvedPos.posAtIndex(relativeStartCell.col),
+ const startCellResolvedPos = resolveCellPosition(
+ state,
+ view.tablePos,
+ relativeStartCell,
);
- const endRowResolvedPos = state.doc.resolve(
- tableResolvedPos.posAtIndex(relativeEndCell.row) + 1,
- );
- const endCellResolvedPos = state.doc.resolve(
- // No need for +1, since CellSelection expects the position before the cell
- endRowResolvedPos.posAtIndex(relativeEndCell.col),
+ const endCellResolvedPos = resolveCellPosition(
+ state,
+ view.tablePos,
+ relativeEndCell,
);
+ if (!startCellResolvedPos || !endCellResolvedPos) {
+ return undefined;
+ }
+
// Begin a new transaction to set the selection
const tr = state.tr;
@@ -975,6 +1036,15 @@ export const TableHandlesExtension = createExtension(({ editor }) => {
| { orientation: "row"; side: "above" | "below" }
| { orientation: "column"; side: "left" | "right" },
) {
+ if (
+ !view ||
+ !isValidTablePosition(view.tablePos) ||
+ !isValidCellIndex(index)
+ ) {
+ view?.hideHandles({ resetCell: true });
+ return;
+ }
+
editor.exec((beforeState, dispatch) => {
const state = this.setCellSelection(
beforeState,
@@ -983,6 +1053,11 @@ export const TableHandlesExtension = createExtension(({ editor }) => {
: { row: 0, col: index },
);
+ if (!state) {
+ view?.hideHandles({ resetCell: true });
+ return false;
+ }
+
if (direction.orientation === "row") {
if (direction.side === "above") {
return addRowBefore(state, dispatch);
@@ -997,6 +1072,7 @@ export const TableHandlesExtension = createExtension(({ editor }) => {
}
}
});
+ view?.hideHandles({ resetCell: true, resetDragging: true });
},
/**
@@ -1006,12 +1082,19 @@ export const TableHandlesExtension = createExtension(({ editor }) => {
index: RelativeCellIndices["row"] | RelativeCellIndices["col"],
direction: "row" | "column",
) {
+ if (!isValidCellIndex(index)) {
+ return false;
+ }
+
if (direction === "row") {
return editor.exec((beforeState, dispatch) => {
const state = this.setCellSelection(beforeState, {
row: index,
col: 0,
});
+ if (!state) {
+ return false;
+ }
return deleteRow(state, dispatch);
});
} else {
@@ -1020,6 +1103,9 @@ export const TableHandlesExtension = createExtension(({ editor }) => {
row: 0,
col: index,
});
+ if (!state) {
+ return false;
+ }
return deleteColumn(state, dispatch);
});
}
@@ -1041,6 +1127,10 @@ export const TableHandlesExtension = createExtension(({ editor }) => {
)
: beforeState;
+ if (!state) {
+ return false;
+ }
+
return mergeCells(state, dispatch);
});
},
@@ -1055,6 +1145,10 @@ export const TableHandlesExtension = createExtension(({ editor }) => {
? this.setCellSelection(beforeState, relativeCellToSplit)
: beforeState;
+ if (!state) {
+ return false;
+ }
+
return splitCell(state, dispatch);
});
},