@blocknote/core 0.54.0 → 0.54.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blocknote.cjs +1 -1
- package/dist/blocknote.js +6 -6
- package/dist/{blocks-CzkqclGj.cjs → blocks-CTB_5Vyj.cjs} +4 -4
- package/dist/blocks-CTB_5Vyj.cjs.map +1 -0
- package/dist/{blocks-CzQLehlc.js → blocks-Dol85hpH.js} +337 -330
- package/dist/blocks-Dol85hpH.js.map +1 -0
- package/dist/blocks.cjs +1 -1
- package/dist/blocks.js +2 -2
- package/dist/extensions-B7Rsp_Ft.cjs +58 -0
- package/dist/extensions-B7Rsp_Ft.cjs.map +1 -0
- package/dist/{extensions-DGuhtOgB.js → extensions-D6JcJCwd.js} +389 -346
- package/dist/extensions-D6JcJCwd.js.map +1 -0
- package/dist/extensions.cjs +1 -1
- package/dist/extensions.js +3 -3
- package/dist/{src-BkfZVfaO.js → src-Buuo5l7X.js} +521 -516
- package/dist/{src-BkfZVfaO.js.map → src-Buuo5l7X.js.map} +1 -1
- package/dist/{src-DM3syMdf.cjs → src-C54Ok9E0.cjs} +10 -10
- package/dist/{src-DM3syMdf.cjs.map → src-C54Ok9E0.cjs.map} +1 -1
- package/dist/webpack-stats.json +1 -1
- package/dist/y.cjs +1 -1
- package/dist/y.cjs.map +1 -1
- package/dist/y.js +205 -205
- package/dist/y.js.map +1 -1
- package/dist/yjs.cjs +1 -1
- package/dist/yjs.js +21 -21
- package/package.json +1 -1
- package/src/api/getBlocksChangedByTransaction.test.ts +211 -0
- package/src/api/getBlocksChangedByTransaction.ts +48 -12
- package/src/api/getChangedRange.ts +54 -0
- package/src/blocks/index.ts +0 -1
- package/src/editor/performance.test.ts +45 -0
- package/src/exporter/Exporter.test.ts +148 -10
- package/src/exporter/Exporter.ts +20 -2
- package/src/extensions/PreviousBlockType/PreviousBlockType.test.ts +21 -0
- package/src/extensions/PreviousBlockType/PreviousBlockType.ts +5 -3
- package/src/extensions/TableHandles/TableHandles.browser.test.ts +305 -0
- package/src/extensions/TableHandles/TableHandles.ts +82 -41
- package/src/fonts/inter.css +9 -9
- package/src/schema/blocks/createSpec.ts +4 -5
- package/src/schema/inlineContent/createSpec.ts +4 -5
- package/src/schema/nodeViewMutations.test.ts +81 -56
- package/src/schema/nodeViewMutations.ts +30 -27
- package/src/schema/schema.test.ts +110 -0
- package/src/schema/schema.ts +13 -4
- package/src/y/extensions/AttributionExtension.test.ts +8 -9
- package/src/y/versioning/__test__/yhub.test.ts +92 -59
- package/src/y/versioning/yhub.ts +35 -29
- package/types/src/api/getChangedRange.d.ts +14 -0
- package/types/src/blocks/index.d.ts +0 -1
- package/types/src/exporter/Exporter.d.ts +9 -0
- package/types/src/extensions/TableHandles/TableHandles.browser.test.d.ts +1 -0
- package/types/src/extensions/TableHandles/TableHandles.d.ts +3 -0
- package/types/src/schema/nodeViewMutations.d.ts +2 -2
- package/types/src/schema/schema.test.d.ts +1 -0
- package/types/src/y/versioning/yhub.d.ts +3 -2
- package/dist/blocks-CzQLehlc.js.map +0 -1
- package/dist/blocks-CzkqclGj.cjs.map +0 -1
- package/dist/extensions-CSB9ZvuL.cjs +0 -58
- package/dist/extensions-CSB9ZvuL.cjs.map +0 -1
- package/dist/extensions-DGuhtOgB.js.map +0 -1
- package/src/blocks/File/helpers/uploadToTmpFilesDotOrg_DEV_ONLY.ts +0 -20
- package/types/src/blocks/File/helpers/uploadToTmpFilesDotOrg_DEV_ONLY.d.ts +0 -6
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extensions-D6JcJCwd.js","names":[],"sources":["../src/api/exporters/html/util/serializeBlocksExternalHTML.ts","../src/api/exporters/html/externalHTMLExporter.ts","../src/api/getChangedRange.ts","../src/api/getBlocksChangedByTransaction.ts","../src/extensions/BlockChange/BlockChange.ts","../src/extensions/DropCursor/utils.ts","../src/extensions/DropCursor/DropCursor.ts","../src/extensions/History/History.ts","../src/extensions/InlineContentBoundaryEdit/InlineContentBoundaryEdit.ts","../src/extensions/LinkToolbar/LinkToolbar.ts","../src/extensions/LinkToolbar/protocols.ts","../src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.ts","../src/extensions/Placeholder/Placeholder.ts","../src/extensions/PositionMapping/PositionMapping.ts","../src/extensions/PreviousBlockType/PreviousBlockType.ts","../src/extensions/getDraggableBlockFromElement.ts","../src/api/exporters/markdown/htmlToMarkdown.ts","../src/api/exporters/markdown/markdownExporter.ts","../src/api/nodeConversions/fragmentToBlocks.ts","../src/extensions/SideMenu/MultipleNodeSelection.ts","../src/extensions/SideMenu/dragging.ts","../src/extensions/SideMenu/SideMenu.ts","../src/extensions/SourceBlockWithPreview/SourceBlockWithPreview.ts","../src/extensions/SourceInlineContentWithPreview/SourceInlineContentWithPreview.ts","../src/extensions/SyntaxHighlighting/shiki.ts","../src/extensions/SyntaxHighlighting/SyntaxHighlighting.ts","../src/extensions/SuggestionMenu/getDefaultEmojiPickerItems.ts","../src/extensions/TableHandles/TableHandles.ts","../src/extensions/TrailingNode/TrailingNode.ts","../src/extensions/Versioning/Versioning.ts","../src/extensions/Versioning/inMemoryVersioning.ts"],"sourcesContent":["import { DOMSerializer, Fragment, Node } from \"prosemirror-model\";\n\nimport { PartialBlock } from \"../../../../blocks/defaultBlocks.js\";\nimport type { BlockNoteEditor } from \"../../../../editor/BlockNoteEditor.js\";\nimport {\n BlockImplementation,\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../../schema/index.js\";\nimport { UnreachableCaseError } from \"../../../../util/typescript.js\";\nimport {\n inlineContentToNodes,\n tableContentToNodes,\n} from \"../../../nodeConversions/blockToNode.js\";\nimport { nodeToCustomInlineContent } from \"../../../nodeConversions/nodeToBlock.js\";\n\n/**\n * Placeholder character inserted into empty inline-content blocks when\n * exporting to external HTML. An empty block serializes to an element with no\n * children (e.g. `<p></p>`), which is dropped when the HTML is parsed back into\n * blocks. Filling it with this character keeps the block alive through the\n * round trip, and the parser strips the character again so the block ends up\n * empty (see `HTMLToBlocks`).\n *\n * The Unicode object replacement character (U+FFFC) is used because it's a\n * reserved placeholder that users don't type, so it can be safely removed on\n * import without discarding legitimate content (unlike a non-breaking space).\n */\nexport const EMPTY_BLOCK_PLACEHOLDER = \"\";\n\nfunction addAttributesAndRemoveClasses(element: HTMLElement) {\n // Removes all BlockNote specific class names.\n const className =\n Array.from(element.classList).filter(\n (className) => !className.startsWith(\"bn-\"),\n ) || [];\n\n if (className.length > 0) {\n element.className = className.join(\" \");\n } else {\n element.removeAttribute(\"class\");\n }\n}\n\nexport function serializeInlineContentExternalHTML<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n editor: BlockNoteEditor<any, I, S>,\n blockContent: PartialBlock<BSchema, I, S>[\"content\"],\n serializer: DOMSerializer,\n options?: { document?: Document; blockType?: string },\n) {\n let nodes: Node[];\n\n // TODO: reuse function from nodeconversions?\n if (!blockContent) {\n throw new Error(\"blockContent is required\");\n } else if (typeof blockContent === \"string\") {\n nodes = inlineContentToNodes(\n [blockContent],\n editor.pmSchema,\n options?.blockType,\n );\n } else if (Array.isArray(blockContent)) {\n nodes = inlineContentToNodes(\n blockContent,\n editor.pmSchema,\n options?.blockType,\n );\n } else if (blockContent.type === \"tableContent\") {\n nodes = tableContentToNodes(blockContent, editor.pmSchema);\n } else {\n throw new UnreachableCaseError(blockContent.type);\n }\n\n // Check if any of the nodes are custom inline content with toExternalHTML\n const doc = options?.document ?? document;\n const fragment = doc.createDocumentFragment();\n\n for (const node of nodes) {\n // Check if this is a custom inline content node with toExternalHTML\n if (\n node.type.name !== \"text\" &&\n editor.schema.inlineContentSchema[node.type.name]\n ) {\n const inlineContentImplementation =\n editor.schema.inlineContentSpecs[node.type.name].implementation;\n\n if (inlineContentImplementation) {\n // Convert the node to inline content format\n const inlineContent = nodeToCustomInlineContent(\n node,\n editor.schema.inlineContentSchema,\n editor.schema.styleSchema,\n );\n\n // Use the custom toExternalHTML method or fallback to `render`\n const output = inlineContentImplementation.toExternalHTML\n ? inlineContentImplementation.toExternalHTML(\n inlineContent as any,\n editor as any,\n )\n : inlineContentImplementation.render.call(\n {\n renderType: \"dom\",\n props: undefined,\n },\n inlineContent as any,\n () => {\n // No-op\n },\n editor as any,\n );\n\n if (output) {\n fragment.appendChild(output.dom);\n\n // If contentDOM exists, render the inline content into it\n if (output.contentDOM) {\n const contentFragment = serializer.serializeFragment(\n node.content,\n options,\n );\n output.contentDOM.dataset.editable = \"\";\n output.contentDOM.appendChild(contentFragment);\n }\n continue;\n }\n }\n } else if (node.type.name === \"text\") {\n // We serialize text nodes manually as we need to serialize the styles/\n // marks using `styleSpec.implementation.render`. When left up to\n // ProseMirror, it'll use `toDOM` which is incorrect.\n let dom: globalThis.Node | Text = document.createTextNode(\n node.textContent,\n );\n // Reverse the order of marks to maintain the correct priority.\n for (const mark of node.marks.toReversed()) {\n if (mark.type.name in editor.schema.styleSpecs) {\n const newDom = (\n editor.schema.styleSpecs[mark.type.name].implementation\n .toExternalHTML ??\n editor.schema.styleSpecs[mark.type.name].implementation.render\n )(mark.attrs[\"stringValue\"], editor);\n newDom.contentDOM!.appendChild(dom);\n dom = newDom.dom;\n } else {\n const domOutputSpec = mark.type.spec.toDOM!(mark, true);\n const newDom = DOMSerializer.renderSpec(document, domOutputSpec);\n newDom.contentDOM!.appendChild(dom);\n dom = newDom.dom;\n }\n }\n\n fragment.appendChild(dom);\n } else {\n // Fall back to default serialization for this node\n const nodeFragment = serializer.serializeFragment(\n Fragment.from([node]),\n options,\n );\n fragment.appendChild(nodeFragment);\n }\n }\n\n if (\n fragment.childNodes.length === 1 &&\n fragment.firstChild?.nodeType === 1 /* Node.ELEMENT_NODE */\n ) {\n addAttributesAndRemoveClasses(fragment.firstChild as HTMLElement);\n }\n\n return fragment;\n}\n\n/**\n * TODO: there's still quite some logic that handles getting and filtering properties,\n * we should make sure the `toExternalHTML` methods of default blocks actually handle this,\n * instead of the serializer.\n */\nfunction serializeBlock<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n fragment: DocumentFragment,\n editor: BlockNoteEditor<BSchema, I, S>,\n block: PartialBlock<BSchema, I, S>,\n serializer: DOMSerializer,\n orderedListItemBlockTypes: Set<string>,\n unorderedListItemBlockTypes: Set<string>,\n nestingLevel: number,\n options?: { document?: Document },\n) {\n const doc = options?.document ?? document;\n const BC_NODE = editor.pmSchema.nodes[\"blockContainer\"];\n\n // set default props in case we were passed a partial block\n const props = block.props || {};\n for (const [name, spec] of Object.entries(\n editor.schema.blockSchema[block.type as any].propSchema,\n )) {\n if (!(name in props) && spec.default !== undefined) {\n (props as any)[name] = spec.default;\n }\n }\n\n const bc = BC_NODE.spec?.toDOM?.(\n BC_NODE.create({\n id: block.id,\n ...props,\n }),\n ) as {\n dom: HTMLElement;\n contentDOM?: HTMLElement;\n };\n\n // the container node is just used as a workaround to get some block-level attributes.\n // we should change toExternalHTML so that this is not necessary\n const attrs = Array.from(bc.dom.attributes);\n\n const blockImplementation = editor.blockImplementations[block.type as any]\n .implementation as BlockImplementation;\n const ret =\n blockImplementation.toExternalHTML?.call(\n {},\n { ...block, props } as any,\n editor as any,\n {\n nestingLevel,\n },\n ) ||\n blockImplementation.render.call(\n {},\n { ...block, props } as any,\n editor as any,\n );\n\n const elementFragment = doc.createDocumentFragment();\n\n if ((ret.dom as HTMLElement).classList.contains(\"bn-block-content\")) {\n const blockContentDataAttributes = [\n ...attrs,\n ...Array.from((ret.dom as HTMLElement).attributes),\n ].filter(\n (attr) =>\n attr.name.startsWith(\"data\") &&\n attr.name !== \"data-content-type\" &&\n attr.name !== \"data-file-block\" &&\n attr.name !== \"data-node-view-wrapper\" &&\n attr.name !== \"data-node-type\" &&\n attr.name !== \"data-id\" &&\n attr.name !== \"data-editable\",\n );\n\n // ret.dom = ret.dom.firstChild! as any;\n for (const attr of blockContentDataAttributes) {\n (ret.dom.firstChild! as HTMLElement).setAttribute(attr.name, attr.value);\n }\n\n addAttributesAndRemoveClasses(ret.dom.firstChild! as HTMLElement);\n if (nestingLevel > 0) {\n (ret.dom.firstChild! as HTMLElement).setAttribute(\n \"data-nesting-level\",\n nestingLevel.toString(),\n );\n }\n elementFragment.append(...Array.from(ret.dom.childNodes));\n } else {\n elementFragment.append(ret.dom);\n if (nestingLevel > 0) {\n (ret.dom as HTMLElement).setAttribute(\n \"data-nesting-level\",\n nestingLevel.toString(),\n );\n }\n }\n\n if (ret.contentDOM) {\n if (block.content) {\n const ic = serializeInlineContentExternalHTML(\n editor,\n block.content as any, // TODO\n serializer,\n { ...options, blockType: block.type },\n );\n\n ret.contentDOM.appendChild(ic);\n }\n\n // Blocks with empty inline content (e.g. an empty paragraph) serialize to\n // an element with no children (e.g. `<p></p>`), which is ignored when the\n // HTML is parsed back into blocks. To make these blocks survive such a\n // round trip, we fill their content with a placeholder character that the\n // parser strips out again (see `EMPTY_BLOCK_PLACEHOLDER`).\n //\n // Only applies to blocks that hold inline content: containers (columns,\n // tables) fill their `contentDOM` with child blocks later on, and code\n // blocks would turn the placeholder into literal content.\n const blockNodeType = editor.pmSchema.nodes[block.type as any];\n if (\n blockNodeType?.inlineContent &&\n !blockNodeType.spec.code &&\n ret.contentDOM.childNodes.length === 0\n ) {\n ret.contentDOM.appendChild(doc.createTextNode(EMPTY_BLOCK_PLACEHOLDER));\n }\n }\n\n let listType = undefined;\n if (orderedListItemBlockTypes.has(block.type!)) {\n listType = \"OL\";\n } else if (unorderedListItemBlockTypes.has(block.type!)) {\n listType = \"UL\";\n }\n\n if (listType) {\n if (fragment.lastChild?.nodeName !== listType) {\n const list = doc.createElement(listType);\n\n if (\n listType === \"OL\" &&\n \"start\" in props &&\n props.start &&\n props?.start !== 1\n ) {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n list.setAttribute(\"start\", String(props.start));\n }\n fragment.append(list);\n }\n fragment.lastChild!.appendChild(elementFragment);\n } else {\n fragment.append(elementFragment);\n }\n\n if (block.children && block.children.length > 0) {\n const childFragment = doc.createDocumentFragment();\n serializeBlocksToFragment(\n childFragment,\n editor,\n block.children,\n serializer,\n orderedListItemBlockTypes,\n unorderedListItemBlockTypes,\n nestingLevel + 1,\n options,\n );\n if (\n fragment.lastChild?.nodeName === \"UL\" ||\n fragment.lastChild?.nodeName === \"OL\"\n ) {\n // add nested lists to the last list item\n while (\n childFragment.firstChild?.nodeName === \"UL\" ||\n childFragment.firstChild?.nodeName === \"OL\"\n ) {\n fragment.lastChild!.lastChild!.appendChild(childFragment.firstChild!);\n }\n }\n\n if (\"childrenDOM\" in ret && ret.childrenDOM) {\n // block specifies where children should go (e.g. toggle blocks\n // place children inside <details>)\n ret.childrenDOM.append(childFragment);\n } else if (\n editor.pmSchema.nodes[block.type as any].isInGroup(\"blockContent\")\n ) {\n // default \"blockContainer\" style blocks are flattened (no \"nested block\" support) for externalHTML, so append the child fragment to the outer fragment\n fragment.append(childFragment);\n } else {\n // for columns / column lists, do use nesting\n ret.contentDOM?.append(childFragment);\n }\n }\n}\n\nconst serializeBlocksToFragment = <\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n fragment: DocumentFragment,\n editor: BlockNoteEditor<BSchema, I, S>,\n blocks: PartialBlock<BSchema, I, S>[],\n serializer: DOMSerializer,\n orderedListItemBlockTypes: Set<string>,\n unorderedListItemBlockTypes: Set<string>,\n nestingLevel = 0,\n options?: { document?: Document },\n) => {\n for (const block of blocks) {\n serializeBlock(\n fragment,\n editor,\n block,\n serializer,\n orderedListItemBlockTypes,\n unorderedListItemBlockTypes,\n nestingLevel,\n options,\n );\n }\n};\n\nexport const serializeBlocksExternalHTML = <\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, I, S>,\n blocks: PartialBlock<BSchema, I, S>[],\n serializer: DOMSerializer,\n orderedListItemBlockTypes: Set<string>,\n unorderedListItemBlockTypes: Set<string>,\n options?: { document?: Document },\n) => {\n const doc = options?.document ?? document;\n const fragment = doc.createDocumentFragment();\n\n serializeBlocksToFragment(\n fragment,\n editor,\n blocks,\n serializer,\n orderedListItemBlockTypes,\n unorderedListItemBlockTypes,\n 0,\n options,\n );\n return fragment;\n};\n","import { DOMSerializer, Schema } from \"prosemirror-model\";\n\nimport { PartialBlock } from \"../../../blocks/defaultBlocks.js\";\nimport type { BlockNoteEditor } from \"../../../editor/BlockNoteEditor.js\";\nimport {\n BlockSchema,\n InlineContent,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../schema/index.js\";\nimport {\n serializeBlocksExternalHTML,\n serializeInlineContentExternalHTML,\n} from \"./util/serializeBlocksExternalHTML.js\";\n\n// Used to export BlockNote blocks and ProseMirror nodes to HTML for use outside\n// the editor. Blocks are exported using the `toExternalHTML` method in their\n// `blockSpec`, or `toInternalHTML` if `toExternalHTML` is not defined.\n//\n// The HTML created by this serializer is different to what's rendered by the\n// editor to the DOM. This also means that data is likely to be lost when\n// converting back to original blocks. The differences in the output HTML are:\n// 1. It doesn't include the `blockGroup` and `blockContainer` wrappers meaning\n// that nesting is not preserved for non-list-item blocks.\n// 2. `li` items in the output HTML are wrapped in `ul` or `ol` elements.\n// 3. While nesting for list items is preserved, other types of blocks nested\n// inside a list are un-nested and a new list is created after them.\n// 4. The HTML is wrapped in a single `div` element.\n\n// Needs to be sync because it's used in drag handler event (SideMenuPlugin)\nexport const createExternalHTMLExporter = <\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n schema: Schema,\n editor: BlockNoteEditor<BSchema, I, S>,\n) => {\n const serializer = DOMSerializer.fromSchema(schema);\n\n return {\n exportBlocks: (\n blocks: PartialBlock<BSchema, I, S>[],\n options: { document?: Document },\n ) => {\n const html = serializeBlocksExternalHTML(\n editor,\n blocks,\n serializer,\n new Set<string>([\"numberedListItem\"]),\n new Set<string>([\"bulletListItem\", \"checkListItem\", \"toggleListItem\"]),\n options,\n );\n const div = document.createElement(\"div\");\n div.append(html);\n return div.innerHTML;\n },\n\n exportInlineContent: (\n inlineContent: InlineContent<I, S>[],\n options: { document?: Document },\n ) => {\n const domFragment = serializeInlineContentExternalHTML(\n editor,\n inlineContent as any,\n serializer,\n options,\n );\n\n const parent = document.createElement(\"div\");\n parent.append(domFragment.cloneNode(true));\n\n return parent.innerHTML;\n },\n };\n};\n","import type { Transform } from \"prosemirror-transform\";\n\n/**\n * Like ProseMirror's `Transform.changedRange()`, but also accounts for\n * position-preserving steps whose `StepMap` is empty — `AttrStep` (prop-only\n * updates like a heading's `level`) and mark steps. `changedRange()` and tiptap's\n * `getChangedRanges` both miss `AttrStep`, so anything that scopes work to the\n * changed range would silently ignore prop-only updates.\n *\n * O(steps), like `changedRange()`. Returns null when nothing changed.\n */\nexport function getChangedRange(\n transform: Transform,\n): { from: number; to: number } | null {\n const { mapping, steps } = transform;\n let from = Number.POSITIVE_INFINITY;\n let to = Number.NEGATIVE_INFINITY;\n\n for (let i = 0; i < mapping.maps.length; i++) {\n const map = mapping.maps[i];\n // Advance the accumulated range into this step's coordinate space.\n if (i) {\n from = map.map(from, 1);\n to = map.map(to, -1);\n }\n\n let hadRange = false;\n map.forEach((_oldFrom, _oldTo, newFrom, newTo) => {\n hadRange = true;\n from = Math.min(from, newFrom);\n to = Math.max(to, newTo);\n });\n\n if (!hadRange) {\n // Position-preserving step: recover the affected position from the step,\n // since its map has no ranges. (DocAttrStep has none and affects no nodes.)\n const step = steps[i] as { pos?: number; from?: number; to?: number };\n if (typeof step.pos === \"number\") {\n // AttrStep\n from = Math.min(from, step.pos);\n to = Math.max(to, step.pos + 1);\n } else if (typeof step.from === \"number\" && typeof step.to === \"number\") {\n // AddMarkStep / RemoveMarkStep\n from = Math.min(from, step.from);\n to = Math.max(to, step.to);\n }\n }\n }\n\n if (from === Number.POSITIVE_INFINITY) {\n return null;\n }\n return { from, to };\n}\n","import { combineTransactionSteps } from \"@tiptap/core\";\nimport deepEqual from \"fast-deep-equal\";\nimport type { Node } from \"prosemirror-model\";\nimport type { Transaction } from \"prosemirror-state\";\nimport {\n Block,\n DefaultBlockSchema,\n DefaultInlineContentSchema,\n DefaultStyleSchema,\n} from \"../blocks/defaultBlocks.js\";\nimport type { BlockSchema } from \"../schema/index.js\";\nimport type { InlineContentSchema } from \"../schema/inlineContent/types.js\";\nimport type { StyleSchema } from \"../schema/styles/types.js\";\nimport { getChangedRange } from \"./getChangedRange.js\";\nimport { getNodeId } from \"./getBlockInfoFromPos.js\";\nimport { nodeToBlock } from \"./nodeConversions/nodeToBlock.js\";\nimport { isNodeBlock } from \"./nodeUtil.js\";\n\n/**\n * Change detection utilities for BlockNote.\n *\n * High-level algorithm used by getBlocksChangedByTransaction:\n * 1) Merge appended transactions into one document change.\n * 2) Compute the single range the transaction touched (in both the old and new\n * doc) and only snapshot blocks within it, rather than walking the whole\n * document. getChanges() runs per transaction, so a full-document snapshot\n * made typing in large documents slow: every keystroke re-converted every block.\n * 3) Snapshot blocks before and after within that range (flat map by id, and\n * per-parent child order).\n * 4) Emit inserts/deletes by diffing ids; for shared ids, emit a move (parent\n * changed) or update (block changed, ignoring children).\n * 5) Detect same-parent sibling reorders via an O(n log n) LIS in\n * detectReorderedChildren, marking only items outside the longest ordered\n * subsequence as moved.\n *\n * The range suffices because `changedRange()` spans from the first to the last\n * changed position: any inserted/deleted/moved/updated/reordered block has its\n * relevant positions inside it, and blocks outside are byte-for-byte identical in\n * the same relative order. A moved block's parent contains it, so the parent\n * overlaps the range too (and nodeToBlock converts its full subtree regardless).\n */\n/**\n * Gets the parent block of a node, if it has one.\n */\nfunction getParentBlockId(doc: Node, pos: number): string | undefined {\n if (pos === 0) {\n return undefined;\n }\n const resolvedPos = doc.resolve(pos);\n for (let i = resolvedPos.depth; i > 0; i--) {\n const parent = resolvedPos.node(i);\n if (isNodeBlock(parent)) {\n return getNodeId(parent, doc);\n }\n }\n return undefined;\n}\n\n/**\n * This attributes the changes to a specific source.\n */\nexport type BlockChangeSource =\n | { type: \"local\" }\n | { type: \"paste\" }\n | { type: \"drop\" }\n | { type: \"undo\" | \"redo\" | \"undo-redo\" }\n | { type: \"yjs-remote\" };\n\nexport type BlocksChanged<\n BSchema extends BlockSchema = DefaultBlockSchema,\n ISchema extends InlineContentSchema = DefaultInlineContentSchema,\n SSchema extends StyleSchema = DefaultStyleSchema,\n> = Array<\n {\n /**\n * The affected block.\n */\n block: Block<BSchema, ISchema, SSchema>;\n /**\n * The source of the change.\n */\n source: BlockChangeSource;\n } & (\n | {\n type: \"insert\" | \"delete\";\n /**\n * Insert and delete changes don't have a previous block.\n */\n prevBlock: undefined;\n }\n | {\n type: \"update\";\n /**\n * The previous block.\n */\n prevBlock: Block<BSchema, ISchema, SSchema>;\n }\n | {\n type: \"move\";\n /**\n * The affected block.\n */\n block: Block<BSchema, ISchema, SSchema>;\n /**\n * The block before the move.\n */\n prevBlock: Block<BSchema, ISchema, SSchema>;\n /**\n * The previous parent block (if it existed).\n */\n prevParent?: Block<BSchema, ISchema, SSchema>;\n /**\n * The current parent block (if it exists).\n */\n currentParent?: Block<BSchema, ISchema, SSchema>;\n }\n )\n>;\n\nfunction determineChangeSource(transaction: Transaction): BlockChangeSource {\n if (transaction.getMeta(\"paste\")) {\n return { type: \"paste\" };\n }\n if (transaction.getMeta(\"uiEvent\") === \"drop\") {\n return { type: \"drop\" };\n }\n if (transaction.getMeta(\"history$\")) {\n return {\n type: transaction.getMeta(\"history$\").redo ? \"redo\" : \"undo\",\n };\n }\n if (transaction.getMeta(\"y-sync$\")) {\n if (transaction.getMeta(\"y-sync$\").isUndoRedoOperation) {\n return { type: \"undo-redo\" };\n }\n return { type: \"yjs-remote\" };\n }\n return { type: \"local\" };\n}\n\ntype BlockSnapshot<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n> = {\n byId: Record<\n string,\n {\n block: Block<BSchema, ISchema, SSchema>;\n parentId: string | undefined;\n }\n >;\n childrenByParent: Record<string, string[]>;\n};\n\n/**\n * Snapshots blocks and per-parent child order for the block nodes overlapping the\n * given range (uses \"__root__\" for the root level). Traversing only the range is\n * what keeps this cheap per keystroke: nodeToBlock runs only for blocks that could\n * have changed.\n */\nfunction collectSnapshot<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n doc: Node,\n range: { from: number; to: number },\n): BlockSnapshot<BSchema, ISchema, SSchema> {\n const ROOT_KEY = \"__root__\";\n const byId: Record<\n string,\n {\n block: Block<BSchema, ISchema, SSchema>;\n parentId: string | undefined;\n }\n > = {};\n const childrenByParent: Record<string, string[]> = {};\n // Clamp to valid positions; nodesBetween throws on out-of-range ones.\n const from = Math.max(0, Math.min(range.from, doc.content.size));\n const to = Math.max(from, Math.min(range.to, doc.content.size));\n // nodesBetween visits every node overlapping [from, to] in document order,\n // including ancestor blocks that contain the range.\n doc.nodesBetween(from, to, (node, pos) => {\n if (!isNodeBlock(node)) {\n return true;\n }\n const parentId = getParentBlockId(doc, pos);\n const key = parentId ?? ROOT_KEY;\n if (!childrenByParent[key]) {\n childrenByParent[key] = [];\n }\n const block = nodeToBlock(node, doc);\n const nodeId = getNodeId(node, doc);\n byId[nodeId] = { block, parentId };\n childrenByParent[key].push(nodeId);\n return true;\n });\n return { byId, childrenByParent };\n}\n\n/**\n * Determines which child ids have been reordered (moved) within the same parent.\n * Uses LIS to keep the longest ordered subsequence and marks the rest as moved.\n */\nfunction detectReorderedChildren(\n prevOrder: string[] | undefined,\n nextOrder: string[] | undefined,\n): Set<string> {\n const moved = new Set<string>();\n if (!prevOrder || !nextOrder) {\n return moved;\n }\n // Consider only ids present in both orders (ignore inserts/deletes handled elsewhere)\n const prevIds = new Set(prevOrder);\n const commonNext: string[] = nextOrder.filter((id) => prevIds.has(id));\n const commonPrev: string[] = prevOrder.filter((id) =>\n commonNext.includes(id),\n );\n\n if (commonPrev.length <= 1 || commonNext.length <= 1) {\n return moved;\n }\n\n // Map ids to their index in previous order\n const indexInPrev: Record<string, number> = {};\n for (let i = 0; i < commonPrev.length; i++) {\n indexInPrev[commonPrev[i]] = i;\n }\n\n // Build sequence of indices representing next order in terms of previous indices\n const sequence: number[] = commonNext.map((id) => indexInPrev[id]);\n\n // Inline O(n log n) LIS with reconstruction.\n // Why LIS? We want the smallest set of siblings to label as \"moved\".\n // Keeping the longest subsequence that is already in order achieves this,\n // so only items outside the LIS are reported as moves.\n const n = sequence.length;\n const tailsValues: number[] = [];\n const tailsEndsAtIndex: number[] = [];\n const previousIndexInLis: number[] = new Array(n).fill(-1);\n\n const lowerBound = (arr: number[], target: number): number => {\n let lo = 0;\n let hi = arr.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (arr[mid] < target) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n return lo;\n };\n\n for (let i = 0; i < n; i++) {\n const value = sequence[i];\n const pos = lowerBound(tailsValues, value);\n if (pos > 0) {\n previousIndexInLis[i] = tailsEndsAtIndex[pos - 1];\n }\n if (pos === tailsValues.length) {\n tailsValues.push(value);\n tailsEndsAtIndex.push(i);\n } else {\n tailsValues[pos] = value;\n tailsEndsAtIndex[pos] = i;\n }\n }\n\n const lisIndexSet = new Set<number>();\n let k = tailsEndsAtIndex[tailsEndsAtIndex.length - 1] ?? -1;\n while (k !== -1) {\n lisIndexSet.add(k);\n k = previousIndexInLis[k];\n }\n\n // Items not part of LIS are considered moved\n for (let i = 0; i < commonNext.length; i++) {\n if (!lisIndexSet.has(i)) {\n moved.add(commonNext[i]);\n }\n }\n return moved;\n}\n\n/**\n * Get the blocks that were changed by a transaction.\n */\nexport function getBlocksChangedByTransaction<\n BSchema extends BlockSchema = DefaultBlockSchema,\n ISchema extends InlineContentSchema = DefaultInlineContentSchema,\n SSchema extends StyleSchema = DefaultStyleSchema,\n>(\n transaction: Transaction,\n appendedTransactions: Transaction[] = [],\n): BlocksChanged<BSchema, ISchema, SSchema> {\n const source = determineChangeSource(transaction);\n const combinedTransaction = combineTransactionSteps(transaction.before, [\n transaction,\n ...appendedTransactions,\n ]);\n\n // Changed range in the new doc; null means nothing changed.\n const newRange = getChangedRange(combinedTransaction);\n if (!newRange) {\n return [];\n }\n // Map it back to old-doc coordinates. The -1/+1 biases expand outwards so that\n // for pure inserts/deletes (collapsed new range) the old range still covers the\n // affected span.\n const invertedMapping = combinedTransaction.mapping.invert();\n const oldRange = {\n from: invertedMapping.map(newRange.from, -1),\n to: invertedMapping.map(newRange.to, 1),\n };\n\n const prevSnap = collectSnapshot<BSchema, ISchema, SSchema>(\n combinedTransaction.before,\n oldRange,\n );\n const nextSnap = collectSnapshot<BSchema, ISchema, SSchema>(\n combinedTransaction.doc,\n newRange,\n );\n\n const changes: BlocksChanged<BSchema, ISchema, SSchema> = [];\n const changedIds = new Set<string>();\n\n // Handle inserted blocks\n Object.keys(nextSnap.byId)\n .filter((id) => !(id in prevSnap.byId))\n .forEach((id) => {\n changes.push({\n type: \"insert\",\n block: nextSnap.byId[id].block,\n source,\n prevBlock: undefined,\n });\n changedIds.add(id);\n });\n\n // Handle deleted blocks\n Object.keys(prevSnap.byId)\n .filter((id) => !(id in nextSnap.byId))\n .forEach((id) => {\n changes.push({\n type: \"delete\",\n block: prevSnap.byId[id].block,\n source,\n prevBlock: undefined,\n });\n changedIds.add(id);\n });\n\n // Handle updated, moved to different parent, indented, outdented blocks\n Object.keys(nextSnap.byId)\n .filter((id) => id in prevSnap.byId)\n .forEach((id) => {\n const prev = prevSnap.byId[id];\n const next = nextSnap.byId[id];\n const isParentDifferent = prev.parentId !== next.parentId;\n\n if (isParentDifferent) {\n changes.push({\n type: \"move\",\n block: next.block,\n prevBlock: prev.block,\n source,\n prevParent: prev.parentId\n ? prevSnap.byId[prev.parentId]?.block\n : undefined,\n currentParent: next.parentId\n ? nextSnap.byId[next.parentId]?.block\n : undefined,\n });\n changedIds.add(id);\n } else if (\n // Compare blocks while ignoring children to avoid reporting a parent\n // update when only descendants changed.\n !deepEqual(\n { ...prev.block, children: undefined } as any,\n { ...next.block, children: undefined } as any,\n )\n ) {\n changes.push({\n type: \"update\",\n block: next.block,\n prevBlock: prev.block,\n source,\n });\n changedIds.add(id);\n }\n });\n\n // Handle sibling reorders (parent unchanged but relative order changed)\n const prevOrderByParent = prevSnap.childrenByParent;\n const nextOrderByParent = nextSnap.childrenByParent;\n\n // Use a special key for root-level siblings\n const ROOT_KEY = \"__root__\";\n const parents = new Set<string>([\n ...Object.keys(prevOrderByParent),\n ...Object.keys(nextOrderByParent),\n ]);\n\n const addedMoveForId = new Set<string>();\n\n parents.forEach((parentKey) => {\n const movedWithinParent = detectReorderedChildren(\n prevOrderByParent[parentKey],\n nextOrderByParent[parentKey],\n );\n if (movedWithinParent.size === 0) {\n return;\n }\n movedWithinParent.forEach((id) => {\n // Only consider ids that exist in both snapshots and whose parent truly did not change\n const prev = prevSnap.byId[id];\n const next = nextSnap.byId[id];\n if (!prev || !next) {\n return;\n }\n if (prev.parentId !== next.parentId) {\n return;\n }\n // Skip if already accounted for by insert/delete/update/parent move\n if (changedIds.has(id)) {\n return;\n }\n // Verify we're addressing the right parent bucket\n const bucketKey = prev.parentId ?? ROOT_KEY;\n if (bucketKey !== parentKey) {\n return;\n }\n if (addedMoveForId.has(id)) {\n return;\n }\n addedMoveForId.add(id);\n changes.push({\n type: \"move\",\n block: next.block,\n prevBlock: prev.block,\n source,\n prevParent: prev.parentId\n ? prevSnap.byId[prev.parentId]?.block\n : undefined,\n currentParent: next.parentId\n ? nextSnap.byId[next.parentId]?.block\n : undefined,\n });\n changedIds.add(id);\n });\n });\n\n return changes;\n}\n","import { Plugin, PluginKey, Transaction } from \"prosemirror-state\";\nimport {\n BlocksChanged,\n getBlocksChangedByTransaction,\n} from \"../../api/getBlocksChangedByTransaction.js\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\n/**\n * This plugin can filter transactions before they are applied to the editor, but with a higher-level API than `filterTransaction` from prosemirror.\n */\nexport const BlockChangeExtension = createExtension(() => {\n const beforeChangeCallbacks: ((context: {\n getChanges: () => BlocksChanged<any, any, any>;\n tr: Transaction;\n }) => boolean | void)[] = [];\n return {\n key: \"blockChange\",\n prosemirrorPlugins: [\n new Plugin({\n key: new PluginKey(\"blockChange\"),\n filterTransaction: (tr) => {\n let changes:\n | ReturnType<typeof getBlocksChangedByTransaction<any, any, any>>\n | undefined = undefined;\n\n return beforeChangeCallbacks.reduce((acc, cb) => {\n if (acc === false) {\n // We only care that we hit a `false` result, so we can stop iterating.\n return acc;\n }\n return (\n cb({\n getChanges() {\n if (changes) {\n return changes;\n }\n changes = getBlocksChangedByTransaction<any, any, any>(tr);\n return changes;\n },\n tr,\n }) !== false\n );\n }, true);\n },\n }),\n ],\n\n /**\n * Subscribe to the block change events.\n */\n subscribe(\n callback: (context: {\n getChanges: () => BlocksChanged<any, any, any>;\n tr: Transaction;\n }) => boolean | void,\n ) {\n beforeChangeCallbacks.push(callback);\n\n return () => {\n beforeChangeCallbacks.splice(\n beforeChangeCallbacks.indexOf(callback),\n 1,\n );\n };\n },\n } as const;\n});\n","import type { EditorView } from \"prosemirror-view\";\n\n/**\n * The orientation of the drop cursor.\n */\nexport type DropCursorOrientation =\n | \"inline\" // Vertical line within text\n | \"block-horizontal\" // Horizontal line between blocks\n | \"block-vertical-left\" // Vertical line on left edge of block\n | \"block-vertical-right\"; // Vertical line on right edge of block\n\n/**\n * The position and orientation of the drop cursor.\n */\nexport type DropCursorPosition = {\n pos: number; // Document position\n orientation: DropCursorOrientation;\n};\n/**\n * Bounding rectangle in viewport coordinates (e.g. from getBoundingClientRect).\n */\nexport type Rect = {\n left: number;\n right: number;\n top: number;\n bottom: number;\n};\n\n/**\n * Returns true if the element or any ancestor has the given CSS class.\n * Used to skip drop cursor for elements marked with the exclusion class (e.g. drag handles).\n */\nexport function hasExclusionClassname(\n element: Element | null,\n exclude: string,\n): boolean {\n if (!element || !exclude) {\n return false;\n }\n return !!element.closest(`.${exclude}`);\n}\n\n/**\n * Computes the viewport rect for a block-level drop cursor (horizontal line between blocks\n * or vertical line on left/right edge). Returns null for inline positions or when no DOM node exists.\n */\nexport function getBlockDropRect(\n view: EditorView,\n cursorPos: DropCursorPosition,\n width: number,\n scaleX: number,\n scaleY: number,\n): Rect | null {\n const $pos = view.state.doc.resolve(cursorPos.pos);\n const isBlock = !$pos.parent.inlineContent;\n\n if (!isBlock || cursorPos.orientation === \"inline\") {\n return null;\n }\n\n const before = $pos.nodeBefore;\n\n const after = $pos.nodeAfter;\n\n if (!before && !after) {\n return null;\n }\n\n const isVertical =\n cursorPos.orientation === \"block-vertical-left\" ||\n cursorPos.orientation === \"block-vertical-right\";\n // For vertical cursors, position is at the node position, for horizontal cursors, position is at the node before position\n const nodePos = isVertical\n ? cursorPos.pos\n : cursorPos.pos - (before ? before.nodeSize : 0);\n\n const node = view.nodeDOM(nodePos) as HTMLElement | null;\n if (!node) {\n return null;\n }\n\n const nodeRect = node.getBoundingClientRect();\n\n if (isVertical) {\n const halfWidth = (width / 2) * scaleX;\n const left =\n cursorPos.orientation === \"block-vertical-left\"\n ? nodeRect.left\n : nodeRect.right;\n\n return {\n left: left - halfWidth,\n right: left + halfWidth,\n top: nodeRect.top,\n bottom: nodeRect.bottom,\n };\n }\n\n let top = before ? nodeRect.bottom : nodeRect.top;\n if (before && after) {\n top =\n (top +\n (view.nodeDOM(cursorPos.pos) as HTMLElement).getBoundingClientRect()\n .top) /\n 2;\n }\n const halfHeight = (width / 2) * scaleY;\n\n return {\n left: nodeRect.left,\n right: nodeRect.right,\n top: top - halfHeight,\n bottom: top + halfHeight,\n };\n}\n\n/**\n * Computes the viewport rect for an inline drop cursor (vertical line within text).\n */\nexport function getInlineDropRect(\n view: EditorView,\n cursorPos: DropCursorPosition,\n width: number,\n scaleX: number,\n): Rect {\n const coords = view.coordsAtPos(cursorPos.pos);\n const halfWidth = (width / 2) * scaleX;\n\n return {\n left: coords.left - halfWidth,\n right: coords.left + halfWidth,\n top: coords.top,\n bottom: coords.bottom,\n };\n}\n\n/**\n * Applies orientation-specific CSS classes to the drop cursor element so it can be\n * styled correctly (e.g. horizontal vs vertical line, inline vs block).\n */\nexport function applyOrientationClasses(\n el: HTMLElement,\n orientation: DropCursorOrientation,\n) {\n el.classList.toggle(\n \"prosemirror-dropcursor-inline\",\n orientation === \"inline\",\n );\n el.classList.toggle(\n \"prosemirror-dropcursor-block-horizontal\",\n orientation === \"block-horizontal\",\n );\n el.classList.toggle(\n \"prosemirror-dropcursor-block-vertical-left\",\n orientation === \"block-vertical-left\",\n );\n el.classList.toggle(\n \"prosemirror-dropcursor-block-vertical-right\",\n orientation === \"block-vertical-right\",\n );\n el.classList.toggle(\n \"prosemirror-dropcursor-block\",\n orientation === \"block-horizontal\",\n );\n el.classList.toggle(\n \"prosemirror-dropcursor-vertical\",\n orientation === \"block-vertical-left\" ||\n orientation === \"block-vertical-right\",\n );\n}\n\n/**\n * Returns the offset of the parent element for converting viewport coordinates to\n * parent-relative coordinates. Handles document.body and static positioning.\n */\nexport function getParentOffsets(parent: HTMLElement | null) {\n if (\n !parent ||\n (parent === document.body && getComputedStyle(parent).position === \"static\")\n ) {\n return {\n parentLeft: -window.pageXOffset,\n parentTop: -window.pageYOffset,\n };\n }\n\n const parentRect = parent.getBoundingClientRect();\n const parentScaleX = parentRect.width / parent.offsetWidth;\n const parentScaleY = parentRect.height / parent.offsetHeight;\n\n return {\n parentLeft: parentRect.left - parent.scrollLeft * parentScaleX,\n parentTop: parentRect.top - parent.scrollTop * parentScaleY,\n };\n}\n","import { dropPoint } from \"prosemirror-transform\";\nimport type { EditorView } from \"prosemirror-view\";\nimport {\n applyOrientationClasses,\n getBlockDropRect,\n getInlineDropRect,\n getParentOffsets,\n hasExclusionClassname,\n type DropCursorPosition,\n} from \"./utils.js\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nexport const DRAG_EXCLUSION_CLASSNAME = \"bn-drag-exclude\";\n\n/**\n * Context passed to the computeDropPosition hook.\n */\nexport interface ComputeDropPositionContext {\n editor: BlockNoteEditor<any, any, any>;\n event: DragEvent;\n view: EditorView;\n defaultPosition: DropCursorPosition | null;\n}\n\n/**\n * Hooks for customizing drop cursor behavior.\n */\nexport interface DropCursorHooks {\n /**\n * Compute cursor position and orientation.\n * Return null to prevent dropping (no cursor shown).\n */\n computeDropPosition?: (\n context: ComputeDropPositionContext,\n ) => DropCursorPosition | null;\n}\n\n/**\n * Options for the DropCursor extension.\n */\nexport interface DropCursorOptions {\n width?: number; // Cursor width in pixels (default: 5)\n color?: string | false; // Cursor color (default: \"#ddeeff\")\n exclude?: string; // CSS class for exclusion (default: \"bn-drag-exclude\")\n hooks?: DropCursorHooks; // Optional behavior hooks\n}\n\n/**\n * Drop cursor visualization based on prosemirror-dropcursor:\n * https://github.com/ProseMirror/prosemirror-dropcursor/blob/master/src/dropcursor.ts\n *\n * Refactored to use BlockNote extension pattern with mount callback and AbortSignal\n * for lifecycle management instead of ProseMirror PluginView.\n */\nexport const DropCursorExtension = createExtension<\n any,\n {\n dropCursor?: DropCursorOptions;\n }\n>(({ editor, options }) => {\n // State\n let cursorPos: DropCursorPosition | null = null;\n let element: HTMLElement | null = null;\n let timeout = -1;\n let dragSourceElement: Element | null = null;\n\n const config = {\n width: options.dropCursor?.width ?? 5,\n color: options.dropCursor?.color ?? \"#ddeeff\",\n exclude: options.dropCursor?.exclude ?? DRAG_EXCLUSION_CLASSNAME,\n hooks: options.dropCursor?.hooks,\n } as const;\n\n // Helper functions\n const setCursor = (pos: DropCursorPosition | null) => {\n if (\n pos?.pos === cursorPos?.pos &&\n pos?.orientation === cursorPos?.orientation\n ) {\n return;\n }\n cursorPos = pos;\n\n if (pos == null) {\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n element = null;\n } else {\n updateOverlay();\n }\n };\n\n const updateOverlay = () => {\n if (!cursorPos) {\n return;\n }\n\n const view = editor.prosemirrorView;\n const editorDOM = view.dom;\n const editorRect = editorDOM.getBoundingClientRect();\n const scaleX = editorRect.width / editorDOM.offsetWidth;\n const scaleY = editorRect.height / editorDOM.offsetHeight;\n\n const blockRect = getBlockDropRect(\n view,\n cursorPos,\n config.width,\n scaleX,\n scaleY,\n );\n const rect =\n blockRect ?? getInlineDropRect(view, cursorPos, config.width, scaleX);\n\n const parent = view.dom.offsetParent as HTMLElement;\n if (!element) {\n element = parent.appendChild(document.createElement(\"div\"));\n element.style.cssText =\n \"position: absolute; z-index: 50; pointer-events: none;\";\n if (config.color) {\n element.style.backgroundColor = config.color;\n }\n }\n\n applyOrientationClasses(element, cursorPos.orientation);\n\n const { parentLeft, parentTop } = getParentOffsets(parent);\n\n element.style.left = (rect.left - parentLeft) / scaleX + \"px\";\n element.style.top = (rect.top - parentTop) / scaleY + \"px\";\n element.style.width = (rect.right - rect.left) / scaleX + \"px\";\n element.style.height = (rect.bottom - rect.top) / scaleY + \"px\";\n };\n\n const scheduleRemoval = (ms: number) => {\n clearTimeout(timeout);\n timeout = window.setTimeout(() => setCursor(null), ms);\n };\n\n // Event handlers\n const onDragStart = (event: Event) => {\n const e = event as DragEvent;\n dragSourceElement = e.target instanceof Element ? e.target : null;\n };\n\n const onDragOver = (event: Event) => {\n const e = event as DragEvent;\n\n // Check if drag source has exclusion classname\n if (\n dragSourceElement &&\n hasExclusionClassname(dragSourceElement, config.exclude)\n ) {\n return;\n }\n\n // Check if drop target has exclusion classname\n if (\n e.target instanceof Element &&\n hasExclusionClassname(e.target, config.exclude)\n ) {\n return;\n }\n\n const view = editor.prosemirrorView;\n if (!view.editable) {\n return;\n }\n\n const pos = view.posAtCoords({\n left: e.clientX,\n top: e.clientY,\n });\n\n const node = pos && pos.inside >= 0 && view.state.doc.nodeAt(pos.inside);\n const disableDropCursor = node && (node.type.spec as any).disableDropCursor;\n const disabled =\n typeof disableDropCursor === \"function\"\n ? disableDropCursor(view, pos, e)\n : disableDropCursor;\n\n if (pos && !disabled) {\n let target = pos.pos;\n if (view.dragging && view.dragging.slice) {\n const point = dropPoint(view.state.doc, target, view.dragging.slice);\n if (point != null) {\n target = point;\n }\n }\n\n // Compute default position\n const $pos = view.state.doc.resolve(target);\n const isBlock = !$pos.parent.inlineContent;\n const defaultPosition: DropCursorPosition = {\n pos: target,\n orientation: isBlock ? \"block-horizontal\" : \"inline\",\n };\n\n // Allow hook to override position\n let finalPosition = defaultPosition;\n if (config.hooks?.computeDropPosition) {\n const hookResult = config.hooks.computeDropPosition({\n editor,\n event: e,\n view,\n defaultPosition,\n });\n if (hookResult === null) {\n // Hook returned null - don't show cursor\n setCursor(null);\n return;\n }\n finalPosition = hookResult;\n }\n\n setCursor(finalPosition);\n scheduleRemoval(5000);\n }\n };\n\n const onDragLeave = (event: Event) => {\n const e = event as DragEvent;\n if (\n !(e.relatedTarget instanceof Node) ||\n !editor.prosemirrorView.dom.contains(e.relatedTarget)\n ) {\n setCursor(null);\n }\n };\n\n const onDrop = () => {\n scheduleRemoval(20);\n };\n\n const onDragEnd = () => {\n scheduleRemoval(20);\n dragSourceElement = null;\n };\n\n return {\n key: \"dropCursor\",\n mount({ signal, dom, root }) {\n // Track drag source at document level\n root.addEventListener(\"dragstart\", onDragStart, {\n capture: true,\n signal,\n });\n\n // Handle drag events on the editor\n dom.addEventListener(\"dragover\", onDragOver, { signal });\n dom.addEventListener(\"dragleave\", onDragLeave, { signal });\n dom.addEventListener(\"drop\", onDrop, { signal });\n dom.addEventListener(\"dragend\", onDragEnd, { signal });\n\n // Clean up on unmount\n signal.addEventListener(\"abort\", () => {\n clearTimeout(timeout);\n setCursor(null);\n });\n },\n } as const;\n});\n","import { history, redo, undo } from \"@tiptap/pm/history\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nexport const HistoryExtension = createExtension(() => {\n return {\n key: \"history\",\n prosemirrorPlugins: [history()],\n undoCommand: undo,\n redoCommand: redo,\n } as const;\n});\n","import { Plugin, PluginKey, Selection, TextSelection } from \"prosemirror-state\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nconst PLUGIN_KEY = new PluginKey(\"inline-content-boundary-edit\");\n\n// Whether a Backspace/Delete at `selection` would remove the entire content\n// range `[content.from, content.to)` of an inline content node.\nfunction emptiesInlineContent(\n selection: Selection,\n key: string,\n content: { from: number; to: number },\n) {\n if (!selection.empty) {\n return selection.from <= content.from && selection.to >= content.to;\n }\n\n const isSingleChar = content.to - content.from === 1;\n\n return key === \"Backspace\"\n ? isSingleChar && selection.from === content.to\n : isSingleChar && selection.from === content.from;\n}\n\n// Fixes editing at the boundary of an empty custom inline content node (i.e. an\n// inline node with editable content, like a mention or inline math).\n//\n// An empty inline node can't hold a text cursor, so ProseMirror can't reconcile\n// edits across the empty boundary from the DOM: typing into an empty node\n// inserts text next to it rather than inside, and deleting the last character\n// leaves an un-reconcilable empty node that corrupts/freezes the editor. Both\n// boundary edits are handled here via transactions so the caret stays inside\n// the node, which is kept alive and editable in its empty state.\n//\n// The cursor is inside such a node exactly when its directly-enclosing node is\n// inline (`inline: true` in the spec) - regular text blocks aren't inline, and\n// atomic inline content can't hold a cursor - so the handling applies to any\n// inline content type without needing to know it by name.\nexport const InlineContentBoundaryEditExtension = createExtension(\n () =>\n ({\n key: \"inlineContentBoundaryEdit\",\n prosemirrorPlugins: [\n new Plugin({\n key: PLUGIN_KEY,\n props: {\n handleKeyDown: (view, event) => {\n if (!view.editable) {\n return false;\n }\n\n const isTypedChar =\n event.key.length === 1 && !event.ctrlKey && !event.metaKey;\n\n if (\n !isTypedChar &&\n event.key !== \"Backspace\" &&\n event.key !== \"Delete\"\n ) {\n return false;\n }\n\n const { selection } = view.state;\n const node = selection.$from.node();\n if (!node.type.spec.inline) {\n return false;\n }\n\n const pos = selection.$from.before();\n const contentFrom = pos + 1;\n const contentTo = pos + 1 + node.content.size;\n\n // Empty content: redirect the typed character into the node.\n if (isTypedChar && node.content.size === 0) {\n const tr = view.state.tr.insert(\n contentFrom,\n view.state.schema.text(event.key),\n );\n tr.setSelection(\n TextSelection.create(tr.doc, contentFrom + event.key.length),\n );\n view.dispatch(tr);\n\n return true;\n }\n\n // Backspace/Delete that would empty the content: delete it all in\n // one transaction, keeping the now-empty node (and the caret\n // inside it) so it stays editable.\n if (\n node.content.size > 0 &&\n emptiesInlineContent(selection, event.key, {\n from: contentFrom,\n to: contentTo,\n })\n ) {\n const tr = view.state.tr.delete(contentFrom, contentTo);\n tr.setSelection(TextSelection.create(tr.doc, contentFrom));\n view.dispatch(tr);\n\n return true;\n }\n\n return false;\n },\n },\n }),\n ],\n }) as const,\n);\n","import { posToDOMRect } from \"@tiptap/core\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nexport const LinkToolbarExtension = createExtension(({ editor }) => {\n function getLinkElementAtPos(pos: number) {\n let currentNode = editor.prosemirrorView.nodeDOM(pos);\n while (currentNode && currentNode.parentElement) {\n if (currentNode.nodeName === \"A\") {\n return currentNode as HTMLAnchorElement;\n }\n currentNode = currentNode.parentElement;\n }\n return null;\n }\n\n function getLinkAtPos(pos: number) {\n const linkData = editor.getLinkMarkAtPos(pos);\n if (!linkData) {\n return undefined;\n }\n\n return {\n range: { from: linkData.from, to: linkData.to },\n // Expose mark-like attrs for backward compat with React LinkToolbarController\n mark: { attrs: { href: linkData.href } },\n get text() {\n return linkData.text;\n },\n get position() {\n return posToDOMRect(\n editor.prosemirrorView,\n linkData.from,\n linkData.to,\n ).toJSON() as DOMRect;\n },\n };\n }\n\n function getLinkAtSelection() {\n return editor.transact((tr) => {\n if (!tr.selection.empty) {\n return undefined;\n }\n return getLinkAtPos(tr.selection.anchor);\n });\n }\n\n return {\n key: \"linkToolbar\",\n\n getLinkAtSelection,\n getLinkElementAtPos,\n getMarkAtPos(pos: number, _markType: string) {\n return getLinkAtPos(pos);\n },\n\n getLinkAtElement(element: HTMLElement) {\n return editor.transact(() => {\n const posAtElement = editor.prosemirrorView.posAtDOM(element, 0) + 1;\n return getLinkAtPos(posAtElement);\n });\n },\n\n editLink(\n url: string,\n text: string,\n position = editor.transact((tr) => tr.selection.anchor),\n ) {\n editor.editLink(url, text, position);\n },\n\n deleteLink(position = editor.transact((tr) => tr.selection.anchor)) {\n editor.deleteLink(position);\n },\n } as const;\n});\n","export const VALID_LINK_PROTOCOLS = [\n \"http\",\n \"https\",\n \"ftp\",\n \"ftps\",\n \"mailto\",\n \"tel\",\n \"callto\",\n \"sms\",\n \"cid\",\n \"xmpp\",\n];\nexport const DEFAULT_LINK_PROTOCOL = \"https\";\n","import { Plugin, PluginKey, TextSelection } from \"prosemirror-state\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nconst PLUGIN_KEY = new PluginKey(\"node-selection-keyboard\");\n// By default, typing with a node selection active will cause ProseMirror to\n// replace the node with one that contains editable content. This plugin blocks\n// this behaviour without also blocking things like keyboard shortcuts:\n//\n// - Lets through key presses that do not include alphanumeric characters. This\n// includes things like backspace/delete/home/end/etc.\n// - Lets through any key presses that include ctrl/meta keys. These will be\n// shortcuts of some kind like ctrl+C/mod+C.\n// - Special case for Enter key which creates a new paragraph block below and\n// sets the selection to it. This is just to bring the UX closer to Notion\n//\n// While a more elegant solution would probably process transactions instead of\n// keystrokes, this brings us most of the way to Notion's UX without much added\n// complexity.\nexport const NodeSelectionKeyboardExtension = createExtension(\n () =>\n ({\n key: \"nodeSelectionKeyboard\",\n prosemirrorPlugins: [\n new Plugin({\n key: PLUGIN_KEY,\n props: {\n handleKeyDown: (view, event) => {\n // Checks for node selection\n if (\"node\" in view.state.selection) {\n // Checks if key press uses ctrl/meta modifier\n if (event.ctrlKey || event.metaKey) {\n return false;\n }\n // Checks if key press is alphanumeric\n if (event.key.length === 1) {\n event.preventDefault();\n\n return true;\n }\n // Checks if key press is Enter\n if (\n event.key === \"Enter\" &&\n !event.isComposing &&\n !event.shiftKey &&\n !event.altKey &&\n !event.ctrlKey &&\n !event.metaKey\n ) {\n const tr = view.state.tr;\n view.dispatch(\n tr\n .insert(\n view.state.tr.selection.$to.after(),\n view.state.schema.nodes[\"paragraph\"].createChecked(),\n )\n .setSelection(\n new TextSelection(\n tr.doc.resolve(\n view.state.tr.selection.$to.after() + 1,\n ),\n ),\n ),\n );\n\n return true;\n }\n }\n\n return false;\n },\n },\n }),\n ],\n }) as const,\n);\n","import { Plugin, PluginKey } from \"prosemirror-state\";\nimport { Decoration, DecorationSet } from \"prosemirror-view\";\nimport { uuidv4 } from \"lib0/random\";\n\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { BlockNoteEditorOptions } from \"../../editor/BlockNoteEditor.js\";\n\nconst PLUGIN_KEY = new PluginKey(`blocknote-placeholder`);\n\nexport const PlaceholderExtension = createExtension(\n ({\n editor,\n options,\n }: ExtensionOptions<\n Pick<BlockNoteEditorOptions<any, any, any>, \"placeholders\">\n >) => {\n const placeholders = options.placeholders;\n return {\n key: \"placeholder\",\n prosemirrorPlugins: [\n new Plugin({\n key: PLUGIN_KEY,\n view: (view) => {\n const uniqueEditorSelector = `placeholder-selector-${uuidv4()}`;\n view.dom.classList.add(uniqueEditorSelector);\n const styleEl = document.createElement(\"style\");\n\n const nonce = editor._tiptapEditor.options.injectNonce;\n if (nonce) {\n styleEl.setAttribute(\"nonce\", nonce);\n }\n\n if (view.root instanceof window.ShadowRoot) {\n view.root.append(styleEl);\n } else {\n view.root.head.appendChild(styleEl);\n }\n\n const styleSheet = styleEl.sheet!;\n\n const getSelector = (additionalSelectors = \"\") =>\n `.${uniqueEditorSelector} .bn-block-content${additionalSelectors}:has(.ProseMirror-trailingBreak:only-child):after`;\n\n try {\n // FIXME: the names \"default\" and \"emptyDocument\" are hardcoded\n const {\n default: defaultPlaceholder,\n emptyDocument: emptyPlaceholder,\n ...rest\n } = placeholders || {};\n\n // add block specific placeholders\n for (const [blockType, placeholder] of Object.entries(rest)) {\n const blockTypeSelector = `[data-content-type=\"${blockType}\"]`;\n\n styleSheet.insertRule(\n `${getSelector(blockTypeSelector)} { content: ${JSON.stringify(\n placeholder,\n )}; }`,\n );\n }\n\n const onlyBlockSelector = `[data-is-only-empty-block]`;\n const mustBeFocusedSelector = `[data-is-empty-and-focused]`;\n\n // placeholder for when there's only one empty block\n styleSheet.insertRule(\n `${getSelector(onlyBlockSelector)} { content: ${JSON.stringify(\n emptyPlaceholder,\n )}; }`,\n );\n\n // placeholder for default blocks, only when the cursor is in the block (mustBeFocused)\n styleSheet.insertRule(\n `${getSelector(mustBeFocusedSelector)} { content: ${JSON.stringify(\n defaultPlaceholder,\n )}; }`,\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n `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)`,\n e,\n );\n }\n\n return {\n destroy: () => {\n if (view.root instanceof window.ShadowRoot) {\n view.root.removeChild(styleEl);\n } else {\n view.root.head.removeChild(styleEl);\n }\n },\n };\n },\n props: {\n decorations: (state) => {\n const { doc, selection } = state;\n\n if (!editor.isEditable) {\n return;\n }\n\n if (!selection.empty) {\n return;\n }\n\n // Don't show placeholder when the cursor is inside a code block\n if (selection.$from.parent.type.spec.code) {\n return;\n }\n\n const decs = [];\n\n // decoration for when there's only one empty block\n // positions are hardcoded for now\n if (state.doc.content.size === 6) {\n decs.push(\n Decoration.node(2, 4, {\n \"data-is-only-empty-block\": \"true\",\n }),\n );\n }\n\n const $pos = selection.$anchor;\n const node = $pos.parent;\n\n if (node.content.size === 0) {\n const before = $pos.before();\n\n decs.push(\n Decoration.node(before, before + node.nodeSize, {\n \"data-is-empty-and-focused\": \"true\",\n }),\n );\n }\n\n return DecorationSet.create(doc, decs);\n },\n },\n }),\n ],\n } as const;\n },\n);\n","import { Mapping } from \"prosemirror-transform\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nexport const PositionMappingExtension = createExtension(({ editor }) => {\n /**\n * The mapping object which holds the position mapping across changes.\n */\n let mapping = new Mapping();\n /**\n * The number of live `mapPosition` closures.\n */\n let numInstances = 0;\n\n function reset() {\n mapping = new Mapping();\n numInstances = 0;\n }\n\n // FinalizationRegistry is kept as a non-deterministic fallback for\n // individual closure cleanup during the editor's lifetime.\n const registry =\n typeof FinalizationRegistry !== \"undefined\"\n ? new FinalizationRegistry(() => {\n numInstances--;\n if (numInstances === 0) {\n reset();\n }\n })\n : null;\n\n editor.on(\"create\", () => {\n editor._tiptapEditor.on(\"transaction\", ({ transaction }) => {\n if (numInstances === 0) {\n return;\n }\n mapping.appendMapping(transaction.mapping);\n });\n\n // Deterministic cleanup: when the editor is destroyed, reset state so\n // mapping.maps does not grow unbounded across editor lifecycles.\n editor._tiptapEditor.on(\"destroy\", () => {\n reset();\n });\n });\n\n return {\n key: \"positionMapping\",\n mapPosition: (position: number, side: \"left\" | \"right\" = \"left\") => {\n numInstances++;\n const trackedMapLength = mapping.maps.length;\n\n const getMappedPosition = () => {\n return (\n mapping\n // Only read the history of the mapping that we care about\n .slice(trackedMapLength)\n .map(position, side === \"left\" ? -1 : 1)\n );\n };\n\n if (registry) {\n registry.register(getMappedPosition, undefined);\n }\n\n return getMappedPosition;\n },\n } as const;\n});\n","import { findChildrenInRange } from \"@tiptap/core\";\nimport { Plugin, PluginKey } from \"prosemirror-state\";\nimport { Decoration, DecorationSet } from \"prosemirror-view\";\nimport { getNodeId } from \"../../api/getBlockInfoFromPos.js\";\nimport { getChangedRange } from \"../../api/getChangedRange.js\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nconst PLUGIN_KEY = new PluginKey(`previous-blocks`);\n\nconst nodeAttributes: Record<string, string> = {\n // Numbered List Items\n index: \"index\",\n // Headings\n level: \"level\",\n // All Blocks\n type: \"type\",\n depth: \"depth\",\n \"depth-change\": \"depth-change\",\n};\n\n/**\n * This plugin tracks transformation of Block node attributes, so we can support CSS transitions.\n *\n * Problem it solves: ProseMirror recreates the DOM when transactions happen. So when a transaction changes a Node attribute,\n * it results in a completely new DOM element. This means CSS transitions don't work.\n *\n * Solution: When attributes change on a node, this plugin sets a data-* attribute with the \"previous\" value. This way we can still use CSS transitions. (See block.module.css)\n */\nexport const PreviousBlockTypeExtension = createExtension(() => {\n let timeout: ReturnType<typeof setTimeout>;\n return {\n key: \"previousBlockType\",\n prosemirrorPlugins: [\n new Plugin({\n key: PLUGIN_KEY,\n view(_editorView) {\n return {\n update: async (view, _prevState) => {\n if (this.key?.getState(view.state).updatedBlocks.size > 0) {\n // use setTimeout 0 to clear the decorations so that at least\n // for one DOM-render the decorations have been applied\n timeout = setTimeout(() => {\n view.dispatch(\n view.state.tr.setMeta(PLUGIN_KEY, { clearUpdate: true }),\n );\n }, 0);\n }\n },\n destroy: () => {\n if (timeout) {\n clearTimeout(timeout);\n }\n },\n };\n },\n state: {\n init() {\n return {\n // Block attributes, by block ID, from just before the previous transaction.\n prevTransactionOldBlockAttrs: {} as any,\n // Block attributes, by block ID, from just before the current transaction.\n currentTransactionOldBlockAttrs: {} as any,\n // Set of IDs of blocks whose attributes changed from the current transaction.\n updatedBlocks: new Set<string>(),\n };\n },\n\n apply(transaction, prev, oldState, newState) {\n prev.currentTransactionOldBlockAttrs = {};\n prev.updatedBlocks.clear();\n\n if (!transaction.docChanged) {\n return prev;\n }\n\n // Only check nodes in the changed range, not the whole document.\n // getChangedRange() also covers attribute-only steps (AttrStep), so a\n // block whose `level`/`index` changes with no content edit is caught.\n const newRange = getChangedRange(transaction);\n if (!newRange) {\n return prev;\n }\n\n // Map the new-doc range back to old-doc coordinates\n const invertedMapping = transaction.mapping.invert();\n const oldRange = {\n from: invertedMapping.map(newRange.from, -1),\n to: invertedMapping.map(newRange.to, 1),\n };\n\n const currentTransactionOriginalOldBlockAttrs = {} as any;\n\n const oldNodes = findChildrenInRange(\n oldState.doc,\n oldRange,\n (node) => node.attrs.id,\n );\n const oldNodesById = new Map(\n oldNodes.map((node) => [\n getNodeId(node.node, oldState.doc),\n node,\n ]),\n );\n const newNodes = findChildrenInRange(\n newState.doc,\n newRange,\n (node) => node.attrs.id,\n );\n\n for (const node of newNodes) {\n const nodeId = getNodeId(node.node, newState.doc);\n const oldNode = oldNodesById.get(nodeId);\n\n const oldContentNode = oldNode?.node.firstChild;\n const newContentNode = node.node.firstChild;\n\n if (oldNode && oldContentNode && newContentNode) {\n const newAttrs = {\n index: newContentNode.attrs.index,\n level: newContentNode.attrs.level,\n type: newContentNode.type.name,\n depth: newState.doc.resolve(node.pos).depth,\n };\n\n const oldAttrs = {\n index: oldContentNode.attrs.index,\n level: oldContentNode.attrs.level,\n type: oldContentNode.type.name,\n depth: oldState.doc.resolve(oldNode.pos).depth,\n };\n\n currentTransactionOriginalOldBlockAttrs[nodeId] = oldAttrs;\n\n prev.currentTransactionOldBlockAttrs[nodeId] = oldAttrs;\n\n if (\n oldAttrs.index !== newAttrs.index ||\n oldAttrs.level !== newAttrs.level ||\n oldAttrs.type !== newAttrs.type ||\n oldAttrs.depth !== newAttrs.depth\n ) {\n (oldAttrs as any)[\"depth-change\"] =\n oldAttrs.depth - newAttrs.depth;\n\n prev.updatedBlocks.add(nodeId);\n }\n }\n }\n\n prev.prevTransactionOldBlockAttrs =\n currentTransactionOriginalOldBlockAttrs;\n\n return prev;\n },\n },\n props: {\n decorations(state) {\n const pluginState = (this as Plugin).getState(state);\n if (pluginState.updatedBlocks.size === 0) {\n return undefined;\n }\n\n const decorations: Decoration[] = [];\n\n state.doc.descendants((node, pos) => {\n if (!node.attrs.id) {\n return;\n }\n\n const id = getNodeId(node, state.doc);\n\n if (!pluginState.updatedBlocks.has(id)) {\n return;\n }\n\n const prevAttrs = pluginState.currentTransactionOldBlockAttrs[id];\n const decorationAttrs: any = {};\n\n for (const [nodeAttr, val] of Object.entries(prevAttrs)) {\n decorationAttrs[\"data-prev-\" + nodeAttributes[nodeAttr]] =\n val || \"none\";\n }\n\n decorations.push(\n Decoration.node(pos, pos + node.nodeSize, {\n ...decorationAttrs,\n }),\n );\n });\n\n return DecorationSet.create(state.doc, decorations);\n },\n },\n }),\n ],\n } as const;\n});\n","import { EditorView } from \"prosemirror-view\";\n\nexport function getDraggableBlockFromElement(\n element: Element,\n view: EditorView,\n) {\n while (\n element &&\n element.parentElement &&\n element.parentElement !== view.dom &&\n element.getAttribute?.(\"data-node-type\") !== \"blockContainer\"\n ) {\n element = element.parentElement;\n }\n if (element.getAttribute?.(\"data-node-type\") !== \"blockContainer\") {\n return undefined;\n }\n return { node: element as HTMLElement, id: element.getAttribute(\"data-id\")! };\n}\n","/**\n * Custom HTML-to-Markdown serializer for BlockNote.\n * Replaces the unified/rehype-remark pipeline with a direct DOM-based implementation.\n *\n * Input: HTML string from createExternalHTMLExporter\n * Output: GFM-compatible markdown string\n */\n\n/**\n * Convert an HTML string (from BlockNote's external HTML exporter) to markdown.\n */\nexport function htmlToMarkdown(html: string): string {\n // Use a temporary element to parse HTML. This works in both browser and\n // server (JSDOM) environments, unlike `new DOMParser()` which may not be\n // globally available in Node.js.\n const container = document.createElement(\"div\");\n container.innerHTML = html;\n const result = serializeChildren(container, {\n indent: \"\",\n inListItem: false,\n });\n return result.trim() + \"\\n\";\n}\n\ninterface SerializeContext {\n indent: string; // current indentation prefix for list nesting\n // True when the current node is being serialized as continuation content\n // of a parent list item. Used to suppress trailing blank lines that would\n // otherwise turn the parent list into a \"loose\" list.\n inListItem: boolean;\n}\n\n// ─── Main Serializer ─────────────────────────────────────────────────────────\n\nfunction serializeChildren(node: Node, ctx: SerializeContext): string {\n let result = \"\";\n const children = Array.from(node.childNodes);\n\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n result += serializeNode(child, ctx);\n }\n\n return result;\n}\n\nfunction serializeNode(node: Node, ctx: SerializeContext): string {\n if (node.nodeType === 3 /* Node.TEXT_NODE */) {\n return node.textContent || \"\";\n }\n\n if (node.nodeType !== 1 /* Node.ELEMENT_NODE */) {\n return \"\";\n }\n\n const el = node as HTMLElement;\n const tag = el.tagName.toLowerCase();\n\n switch (tag) {\n case \"p\":\n return serializeParagraph(el, ctx);\n case \"h1\":\n case \"h2\":\n case \"h3\":\n case \"h4\":\n case \"h5\":\n case \"h6\":\n return serializeHeading(el, ctx);\n case \"blockquote\":\n return serializeBlockquote(el, ctx);\n case \"pre\":\n return serializeCodeBlock(el, ctx);\n case \"ul\":\n return serializeUnorderedList(el, ctx);\n case \"ol\":\n return serializeOrderedList(el, ctx);\n case \"table\":\n return serializeTable(el, ctx);\n case \"hr\":\n return ctx.indent + \"***\\n\\n\";\n case \"math\":\n return serializeMathBlock(el, ctx);\n case \"img\":\n return serializeImage(el, ctx);\n case \"video\":\n return serializeVideo(el, ctx);\n case \"audio\":\n return serializeAudio(el, ctx);\n case \"embed\":\n return serializeEmbed(el, ctx);\n case \"figure\":\n return serializeFigure(el, ctx);\n case \"a\":\n // Block-level link (file block)\n return serializeBlockLink(el, ctx);\n case \"details\":\n return serializeDetails(el, ctx);\n case \"div\":\n // Page break or generic container — serialize children\n return serializeChildren(el, ctx);\n case \"br\":\n return \"\";\n default:\n return serializeChildren(el, ctx);\n }\n}\n\n// ─── Block Serializers ───────────────────────────────────────────────────────\n\nfunction serializeParagraph(el: HTMLElement, ctx: SerializeContext): string {\n const content = serializeInlineContent(el);\n // Trim leading/trailing hard breaks (matching remark behavior)\n const trimmed = trimHardBreaks(content);\n if (ctx.inListItem) {\n return trimmed;\n }\n return ctx.indent + trimmed + \"\\n\\n\";\n}\n\nfunction serializeHeading(el: HTMLElement, ctx: SerializeContext): string {\n const level = parseInt(el.tagName[1], 10);\n const prefix = \"#\".repeat(level) + \" \";\n const content = serializeInlineContent(el);\n return ctx.indent + prefix + content + \"\\n\\n\";\n}\n\nfunction serializeBlockquote(el: HTMLElement, ctx: SerializeContext): string {\n // Check if blockquote contains block-level elements (like <p>)\n const blockChildren = Array.from(el.children).filter((child) => {\n const tag = child.tagName.toLowerCase();\n return [\"p\", \"ul\", \"ol\", \"pre\", \"blockquote\", \"table\", \"hr\"].includes(tag);\n });\n\n let content: string;\n if (blockChildren.length > 0) {\n // Has block-level children — serialize each\n const parts: string[] = [];\n for (const child of blockChildren) {\n const tag = child.tagName.toLowerCase();\n if (tag === \"p\") {\n parts.push(serializeInlineContent(child as HTMLElement));\n } else {\n const innerCtx: SerializeContext = { indent: \"\", inListItem: false };\n parts.push(serializeNode(child, innerCtx).trim());\n }\n }\n content = parts.join(\"\\n\\n\");\n } else {\n // No block-level children — treat entire content as inline\n content = serializeInlineContent(el);\n }\n\n const lines = content.split(\"\\n\");\n return lines.map((line) => ctx.indent + \"> \" + line).join(\"\\n\") + \"\\n\\n\";\n}\n\nfunction serializeCodeBlock(el: HTMLElement, ctx: SerializeContext): string {\n const codeEl = el.querySelector(\"code\");\n if (!codeEl) {\n return \"\";\n }\n\n const language =\n codeEl.getAttribute(\"data-language\") ||\n extractLanguageFromClass(codeEl.className) ||\n \"\";\n\n // Extract code content, handling <br> elements as newlines\n const code = extractCodeContent(codeEl);\n\n // Use a fence longer than the longest backtick run in the code\n const longestRun = Math.max(\n 0,\n ...(code.match(/`+/g) ?? []).map((run) => run.length),\n );\n const fence = \"`\".repeat(Math.max(3, longestRun + 1));\n\n // For empty code blocks, don't add a newline between the fences\n if (!code) {\n return ctx.indent + fence + language + \"\\n\" + ctx.indent + fence + \"\\n\\n\";\n }\n\n // Every (non-blank) line carries the indent - inside a list item or\n // blockquote, an unindented line would end the parent container. Blank\n // lines stay blank: they don't terminate an indented fence, and indenting\n // them would add trailing whitespace.\n const lines = [\n fence + language,\n ...(code.endsWith(\"\\n\") ? code.slice(0, -1) : code).split(\"\\n\"),\n fence,\n ];\n return (\n lines.map((line) => (line ? ctx.indent + line : line)).join(\"\\n\") + \"\\n\\n\"\n );\n}\n\n// The LaTeX source of a MathML element, taken from the annotation KaTeX\n// embeds in its output (also what external HTML parsing reads). Falls back to\n// the element's text content for MathML from other sources.\nfunction extractMathLatexSource(el: Element): string {\n const annotation = el.querySelector(\n 'annotation[encoding=\"application/x-tex\"]',\n );\n return (annotation?.textContent ?? el.textContent ?? \"\").trim();\n}\n\nfunction serializeMathBlock(el: HTMLElement, ctx: SerializeContext): string {\n const latex = extractMathLatexSource(el);\n // Every (non-blank) line carries the indent - inside a list item or\n // blockquote, an unindented line would end the parent container.\n return (\n [\"$$\", ...latex.split(\"\\n\"), \"$$\"]\n .map((line) => (line ? ctx.indent + line : line))\n .join(\"\\n\") + \"\\n\\n\"\n );\n}\n\nfunction extractCodeContent(el: Element): string {\n let result = \"\";\n for (const child of Array.from(el.childNodes)) {\n if (child.nodeType === 3 /* Node.TEXT_NODE */) {\n result += child.textContent || \"\";\n } else if (child.nodeType === 1 /* Node.ELEMENT_NODE */) {\n const tag = (child as HTMLElement).tagName.toLowerCase();\n if (tag === \"br\") {\n result += \"\\n\";\n } else {\n result += extractCodeContent(child as Element);\n }\n }\n }\n return result;\n}\n\nfunction extractLanguageFromClass(className: string): string {\n const match = className.match(/language-(\\S+)/);\n return match ? match[1] : \"\";\n}\n\nfunction serializeUnorderedList(\n el: HTMLElement,\n ctx: SerializeContext,\n): string {\n let result = \"\";\n const items = Array.from(el.children).filter(\n (child) => child.tagName.toLowerCase() === \"li\",\n );\n\n for (const item of items) {\n result += serializeListItem(item as HTMLElement, \"bullet\", ctx);\n }\n\n // Trailing blank line separates the list from the next block. Skip when\n // this list is nested inside another list item — adding it would convert\n // the parent list into a \"loose\" list (or break tightness).\n if (!ctx.inListItem) {\n result += \"\\n\";\n }\n return result;\n}\n\nfunction serializeOrderedList(el: HTMLElement, ctx: SerializeContext): string {\n let result = \"\";\n const items = Array.from(el.children).filter(\n (child) => child.tagName.toLowerCase() === \"li\",\n );\n const startNum = parseInt(el.getAttribute(\"start\") || \"1\", 10);\n\n for (let i = 0; i < items.length; i++) {\n const num = startNum + i;\n result += serializeListItem(items[i] as HTMLElement, \"ordered\", ctx, num);\n }\n\n if (!ctx.inListItem) {\n result += \"\\n\";\n }\n return result;\n}\n\nfunction serializeListItem(\n el: HTMLElement,\n listType: \"bullet\" | \"ordered\",\n ctx: SerializeContext,\n num?: number,\n): string {\n // Check for checkbox (task list) - direct children only\n let checkbox: HTMLInputElement | null = null;\n let details: HTMLElement | null = null;\n\n for (const child of Array.from(el.children)) {\n const tag = child.tagName.toLowerCase();\n if (tag === \"input\" && (child as HTMLInputElement).type === \"checkbox\") {\n checkbox = child as HTMLInputElement;\n }\n if (tag === \"details\") {\n details = child as HTMLElement;\n }\n }\n\n let marker: string;\n let markerWidth: number;\n\n if (checkbox) {\n const state = checkbox.checked ? \"[x]\" : \"[ ]\";\n marker = `* ${state} `;\n // For child indentation, use bullet width (2), not full checkbox marker width\n markerWidth = 2;\n } else if (listType === \"ordered\") {\n marker = `${num}. `;\n markerWidth = marker.length;\n } else {\n marker = \"* \";\n markerWidth = 2;\n }\n\n // Collect the item's inline content\n let inlineContent: string;\n let firstContentEl: Element | null;\n\n if (details) {\n // Toggle item: get content from summary\n const summary = details.querySelector(\"summary\");\n const summaryP = summary?.querySelector(\"p\");\n firstContentEl = details;\n inlineContent = summaryP ? serializeInlineContent(summaryP) : \"\";\n } else {\n firstContentEl = getFirstContentElement(el, checkbox);\n inlineContent = firstContentEl\n ? serializeInlineContent(firstContentEl)\n : \"\";\n }\n\n // The marker line ends with a single `\\n` so that consecutive list items\n // produce a \"tight\" list (no blank line between markers). Continuation\n // content within the item (nested lists, continuation paragraphs, other\n // blocks) injects its own spacing as needed.\n let result = ctx.indent + marker + inlineContent + \"\\n\";\n\n // Serialize child content (nested lists, continuation paragraphs, etc.)\n const childIndent = ctx.indent + \" \".repeat(markerWidth);\n const childCtx: SerializeContext = { indent: childIndent, inListItem: true };\n\n // For toggle items, also serialize children inside the details element\n if (details) {\n const summary = details.querySelector(\"summary\");\n for (const child of Array.from(details.children)) {\n if (child === summary) {\n continue;\n }\n const childTag = child.tagName.toLowerCase();\n if (childTag === \"p\") {\n const content = serializeInlineContent(child as HTMLElement);\n // Continuation paragraph needs a blank line to separate it from the\n // previous content; CommonMark would otherwise treat it as a soft\n // wrap of that content.\n result += \"\\n\" + childIndent + content + \"\\n\";\n } else {\n result += serializeNode(child, childCtx);\n }\n }\n }\n\n const children = Array.from(el.children);\n for (const child of children) {\n const childTag = child.tagName.toLowerCase();\n\n // Skip the first content element and checkbox\n if (child === firstContentEl || (child as HTMLElement) === checkbox) {\n continue;\n }\n if (childTag === \"input\") {\n continue;\n }\n\n // Nested lists and other block content\n if (childTag === \"ul\" || childTag === \"ol\") {\n // Nested list flows directly under the parent marker — no blank line.\n result += serializeNode(child, childCtx);\n } else if (childTag === \"p\") {\n // Continuation paragraph within list item — requires blank line before\n // so it isn't read as part of the marker line's text.\n const content = serializeInlineContent(child as HTMLElement);\n result += \"\\n\" + childIndent + content + \"\\n\";\n } else {\n // Other block-level children (code blocks, blockquotes, etc.) already\n // emit their own separating newlines; prefix with a blank line so they\n // are recognized as separate blocks.\n result += \"\\n\" + serializeNode(child, childCtx);\n }\n }\n\n return result;\n}\n\nfunction getFirstContentElement(\n li: HTMLElement,\n checkbox: HTMLInputElement | null,\n): HTMLElement | null {\n for (const child of Array.from(li.children)) {\n if (child === checkbox) {\n continue;\n }\n if (child.tagName.toLowerCase() === \"input\") {\n continue;\n }\n const tag = child.tagName.toLowerCase();\n if (tag === \"p\" || tag === \"span\") {\n return child as HTMLElement;\n }\n }\n return null;\n}\n\n// ─── Table Serializer ────────────────────────────────────────────────────────\n\nfunction serializeTable(el: HTMLElement, ctx: SerializeContext): string {\n // First, determine column count from colgroup or first row\n const colgroup = el.querySelector(\"colgroup\");\n let colCount = 0;\n\n if (colgroup) {\n colCount = colgroup.querySelectorAll(\"col\").length;\n }\n\n const rows: string[][] = [];\n let hasHeader = false;\n\n // Collect all rows, handling colspan/rowspan\n const trElements = el.querySelectorAll(\"tr\");\n // Build a grid to handle colspan/rowspan\n const grid: (string | null)[][] = [];\n\n trElements.forEach((tr, rowIdx) => {\n if (!grid[rowIdx]) {\n grid[rowIdx] = [];\n }\n const cellElements = tr.querySelectorAll(\"th, td\");\n let gridCol = 0;\n\n cellElements.forEach((cell) => {\n // Find next empty column in this row\n while (grid[rowIdx][gridCol] !== undefined) {\n gridCol++;\n }\n\n if (rowIdx === 0 && cell.tagName.toLowerCase() === \"th\") {\n hasHeader = true;\n }\n\n const content = escapeTableCell(\n serializeInlineContent(cell as HTMLElement).trim(),\n );\n const colspan = parseInt(cell.getAttribute(\"colspan\") || \"1\", 10);\n const rowspan = parseInt(cell.getAttribute(\"rowspan\") || \"1\", 10);\n\n // Fill the grid\n for (let r = 0; r < rowspan; r++) {\n for (let c = 0; c < colspan; c++) {\n const ri = rowIdx + r;\n if (!grid[ri]) {\n grid[ri] = [];\n }\n grid[ri][gridCol + c] = r === 0 && c === 0 ? content : \"\";\n }\n }\n\n gridCol += colspan;\n });\n\n // Update colCount\n if (grid[rowIdx]) {\n colCount = Math.max(colCount, grid[rowIdx].length);\n }\n });\n\n // Convert grid to rows\n for (const gridRow of grid) {\n const row: string[] = [];\n for (let c = 0; c < colCount; c++) {\n row.push(gridRow && gridRow[c] !== undefined ? (gridRow[c] ?? \"\") : \"\");\n }\n rows.push(row);\n }\n\n if (rows.length === 0) {\n return \"\";\n }\n\n // Determine column widths\n const colWidths: number[] = [];\n for (let c = 0; c < colCount; c++) {\n let maxWidth = 3; // minimum width for separator \"---\"\n for (const row of rows) {\n const cellWidth = c < row.length ? row[c].length : 0;\n maxWidth = Math.max(maxWidth, cellWidth);\n }\n // Use minimum of 10 to match remark output\n colWidths.push(Math.max(maxWidth, 10));\n }\n\n let result = \"\";\n\n if (hasHeader) {\n result += ctx.indent + formatTableRow(rows[0], colWidths, colCount) + \"\\n\";\n result += ctx.indent + formatSeparatorRow(colWidths, colCount) + \"\\n\";\n for (let r = 1; r < rows.length; r++) {\n result +=\n ctx.indent + formatTableRow(rows[r], colWidths, colCount) + \"\\n\";\n }\n } else {\n // No header — emit empty header + separator\n const emptyRow = new Array(colCount).fill(\"\");\n result += ctx.indent + formatTableRow(emptyRow, colWidths, colCount) + \"\\n\";\n result += ctx.indent + formatSeparatorRow(colWidths, colCount) + \"\\n\";\n for (const row of rows) {\n result += ctx.indent + formatTableRow(row, colWidths, colCount) + \"\\n\";\n }\n }\n\n result += \"\\n\";\n return result;\n}\n\nfunction escapeTableCell(text: string): string {\n return text.replace(/\\|/g, \"\\\\|\");\n}\n\nfunction formatTableRow(\n cells: string[],\n colWidths: number[],\n colCount: number,\n): string {\n const parts: string[] = [];\n for (let c = 0; c < colCount; c++) {\n const cell = c < cells.length ? cells[c] : \"\";\n parts.push(\" \" + cell.padEnd(colWidths[c]) + \" \");\n }\n return \"|\" + parts.join(\"|\") + \"|\";\n}\n\nfunction formatSeparatorRow(colWidths: number[], colCount: number): string {\n const parts: string[] = [];\n for (let c = 0; c < colCount; c++) {\n parts.push(\" \" + \"-\".repeat(colWidths[c]) + \" \");\n }\n return \"|\" + parts.join(\"|\") + \"|\";\n}\n\n// ─── Media Serializers ───────────────────────────────────────────────────────\n\nfunction serializeImage(el: HTMLElement, ctx: SerializeContext): string {\n const src = el.getAttribute(\"src\") || \"\";\n const alt = el.getAttribute(\"alt\") || \"\";\n // Empty placeholder — preserve the block-level break, matching how\n // serializeParagraph/serializeHeading emit `\\n\\n` for empty content.\n if (!src) {\n return \"\\n\\n\";\n }\n return ctx.indent + `\\n\\n`;\n}\n\nfunction serializeVideo(el: HTMLElement, ctx: SerializeContext): string {\n const src = el.getAttribute(\"src\") || el.getAttribute(\"data-url\") || \"\";\n const name = el.getAttribute(\"data-name\") || el.getAttribute(\"title\") || \"\";\n if (!src) {\n return \"\\n\\n\";\n }\n return ctx.indent + `\\n\\n`;\n}\n\nfunction serializeAudio(el: HTMLElement, ctx: SerializeContext): string {\n const src = el.getAttribute(\"src\") || \"\";\n if (!src) {\n return \"\\n\\n\";\n }\n // Audio has no markdown syntax, so emit raw HTML. The markdown parser\n // passes <audio> blocks through verbatim and BlockNote's audio block parser\n // recognizes them, giving a clean round-trip.\n return (\n ctx.indent + `<audio src=\"${escapeHtmlAttr(src)}\" controls></audio>\\n\\n`\n );\n}\n\nfunction serializeEmbed(el: HTMLElement, ctx: SerializeContext): string {\n const src = el.getAttribute(\"src\") || \"\";\n if (!src) {\n return \"\\n\\n\";\n }\n return ctx.indent + `[](${src})\\n\\n`;\n}\n\nfunction serializeFigure(el: HTMLElement, ctx: SerializeContext): string {\n const img = el.querySelector(\"img\");\n const video = el.querySelector(\"video\");\n const audio = el.querySelector(\"audio\");\n const link = el.querySelector(\"a\");\n\n const figcaption = el.querySelector(\"figcaption\");\n const captionText = figcaption?.textContent?.trim() || \"\";\n\n if (img) {\n return serializeMediaFigure(\n \"img\",\n img.getAttribute(\"src\") || \"\",\n img.getAttribute(\"alt\") || \"\",\n captionText,\n ctx,\n );\n }\n if (video) {\n const src =\n video.getAttribute(\"src\") || video.getAttribute(\"data-url\") || \"\";\n const name =\n video.getAttribute(\"data-name\") || video.getAttribute(\"title\") || \"\";\n return serializeMediaFigure(\"video\", src, name, captionText, ctx);\n }\n if (audio) {\n return serializeMediaFigure(\n \"audio\",\n audio.getAttribute(\"src\") || \"\",\n \"\",\n captionText,\n ctx,\n );\n }\n if (link) {\n return serializeBlockLink(link as HTMLElement, ctx);\n }\n return \"\";\n}\n\nfunction serializeMediaFigure(\n kind: \"img\" | \"video\" | \"audio\",\n src: string,\n descriptor: string,\n captionText: string,\n ctx: SerializeContext,\n): string {\n if (!src) {\n return \"\";\n }\n\n // No caption + has a markdown shorthand → use it.\n if (!captionText && kind !== \"audio\") {\n return ctx.indent + `\\n\\n`;\n }\n\n // The descriptor (alt / data-name) is dropped when it duplicates the\n // caption text; otherwise on round-trip both `name` and `caption` would\n // get set to the same string (BlockNote's HTML exporter writes alt =\n // name || caption, so a caption-only image has alt === figcaption text).\n const showDescriptor = descriptor && descriptor !== captionText;\n const descAttr = !showDescriptor\n ? \"\"\n : kind === \"img\"\n ? ` alt=\"${escapeHtmlAttr(descriptor)}\"`\n : kind === \"video\"\n ? ` data-name=\"${escapeHtmlAttr(descriptor)}\"`\n : \"\";\n\n const tag =\n kind === \"img\"\n ? `<img${descAttr} src=\"${escapeHtmlAttr(src)}\">`\n : `<${kind} src=\"${escapeHtmlAttr(src)}\"${descAttr} controls></${kind}>`;\n\n const captionPart = captionText\n ? `<figcaption>${escapeHtmlText(captionText)}</figcaption>`\n : \"\";\n return ctx.indent + `<figure>${tag}${captionPart}</figure>\\n\\n`;\n}\n\nfunction escapeHtmlAttr(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/\"/g, \""\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n\nfunction escapeHtmlText(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n\nfunction serializeBlockLink(el: HTMLElement, ctx: SerializeContext): string {\n const href = el.getAttribute(\"href\") || \"\";\n const text = el.textContent?.trim() || \"\";\n if (!href) {\n return ctx.indent + text + \"\\n\\n\";\n }\n return ctx.indent + formatLink(text, href) + \"\\n\\n\";\n}\n\n/**\n * Render a link, mirroring the remark-stringify behavior from\n * TypeCellOS/BlockNote#2661: when the link label equals the URL (or is\n * empty), emit the bare URL so that pasting the link into another input\n * produces a valid href instead of `<url>`-autolink brackets or redundant\n * `[url](url)` markup. Otherwise emit `[text](url)` with the URL escaped so\n * a `)` inside the URL does not prematurely close the destination.\n */\nfunction formatLink(text: string, href: string): string {\n if (!text || text === href) {\n return href;\n }\n return `[${text}](${escapeLinkDestination(href)})`;\n}\n\nfunction escapeLinkDestination(url: string): string {\n return url.replace(/[\\\\()]/g, \"\\\\$&\");\n}\n\nfunction serializeDetails(el: HTMLElement, ctx: SerializeContext): string {\n // Toggle heading or toggle list item\n const summary = el.querySelector(\"summary\");\n if (!summary) {\n return serializeChildren(el, ctx);\n }\n\n // Check if summary contains a heading\n const heading = summary.querySelector(\"h1, h2, h3, h4, h5, h6\");\n if (heading) {\n let result = serializeHeading(heading as HTMLElement, ctx);\n // Also serialize non-summary children of details\n for (const child of Array.from(el.children)) {\n if (child !== summary) {\n result += serializeNode(child, ctx);\n }\n }\n return result;\n }\n\n // Otherwise serialize the summary content\n return serializeChildren(summary, ctx);\n}\n\n// ─── Inline Content Serializer ───────────────────────────────────────────────\n\nfunction serializeInlineContent(el: Element): string {\n let result = \"\";\n\n for (const child of Array.from(el.childNodes)) {\n if (child.nodeType === 3 /* Node.TEXT_NODE */) {\n result += child.textContent || \"\";\n } else if (child.nodeType === 1 /* Node.ELEMENT_NODE */) {\n const childEl = child as HTMLElement;\n const tag = childEl.tagName.toLowerCase();\n\n switch (tag) {\n case \"strong\":\n case \"b\": {\n const inner = serializeInlineContent(childEl);\n const { content, trailing } = extractTrailingWhitespace(inner);\n if (content) {\n result += `**${content}**${trailing}`;\n } else {\n // All whitespace — just output it without emphasis\n result += trailing;\n }\n break;\n }\n case \"em\":\n case \"i\": {\n const inner = serializeInlineContent(childEl);\n const { content, trailing } = extractTrailingWhitespace(inner);\n if (content) {\n result += `*${content}*${trailing}`;\n } else {\n result += trailing;\n }\n break;\n }\n case \"s\":\n case \"del\":\n result += `~~${serializeInlineContent(childEl)}~~`;\n break;\n case \"code\": {\n const text = childEl.textContent || \"\";\n const longestRun = Math.max(\n 0,\n ...(text.match(/`+/g) ?? []).map((run) => run.length),\n );\n const fence = \"`\".repeat(longestRun + 1);\n const needsPadding = text.startsWith(\"`\") || text.endsWith(\"`\");\n result += fence + (needsPadding ? ` ${text} ` : text) + fence;\n break;\n }\n case \"u\":\n // No markdown equivalent — strip the tag, keep content\n result += serializeInlineContent(childEl);\n break;\n case \"a\": {\n const href = childEl.getAttribute(\"href\") || \"\";\n const text = serializeInlineContent(childEl);\n result += formatLink(text, href);\n break;\n }\n case \"br\":\n result += \"\\\\\\n\";\n break;\n case \"math\": {\n // Inline math — emit its LaTeX source as a math span. Collapsed to\n // a single line, as $...$ spans cannot contain newlines.\n const latex = extractMathLatexSource(childEl)\n .split(\"\\n\")\n .map((line) => line.trim())\n .join(\" \");\n result += `$${latex}$`;\n break;\n }\n case \"span\":\n // Color spans, etc. — strip the tag, keep content\n result += serializeInlineContent(childEl);\n break;\n case \"img\": {\n const src = childEl.getAttribute(\"src\") || \"\";\n const alt = childEl.getAttribute(\"alt\") || \"\";\n result += ``;\n break;\n }\n case \"video\": {\n const src =\n childEl.getAttribute(\"src\") ||\n childEl.getAttribute(\"data-url\") ||\n \"\";\n const name =\n childEl.getAttribute(\"data-name\") ||\n childEl.getAttribute(\"title\") ||\n \"\";\n result += ``;\n break;\n }\n case \"p\":\n // Paragraph inside inline context (e.g., table cell)\n result += serializeInlineContent(childEl);\n break;\n case \"input\":\n // Checkbox in task list — handled at block level\n break;\n default:\n result += serializeInlineContent(childEl);\n break;\n }\n }\n }\n\n return result;\n}\n\n/**\n * Extract trailing whitespace from emphasis content.\n * Moves trailing spaces outside the emphasis delimiters to produce valid markdown.\n * E.g., `<strong>Bold </strong>` → `**Bold** ` instead of `**Bold **`.\n */\nfunction extractTrailingWhitespace(text: string): {\n content: string;\n trailing: string;\n} {\n const match = text.match(/^(.*?)(\\s*)$/);\n if (match) {\n return { content: match[1], trailing: match[2] };\n }\n return { content: text, trailing: \"\" };\n}\n\n/**\n * Escape leading character after emphasis if it could break parsing.\n * For example, \"Heading\" after \"**Bold **\" — the 'H' should be escaped\n * if the trailing space was escaped.\n */\n\n/**\n * Trim leading/trailing hard breaks from inline content.\n * Matches remark behavior where <br> at start/end of paragraph is dropped.\n */\nfunction trimHardBreaks(content: string): string {\n // Remove leading hard breaks\n let result = content.replace(/^(\\\\\\n)+/, \"\");\n // Remove trailing hard breaks produced by `<br>`\n result = result.replace(/(\\\\\\n)+$/, \"\");\n return result;\n}\n","import { Schema } from \"prosemirror-model\";\n\nimport { PartialBlock } from \"../../../blocks/defaultBlocks.js\";\nimport type { BlockNoteEditor } from \"../../../editor/BlockNoteEditor.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../../schema/index.js\";\nimport { createExternalHTMLExporter } from \"../html/externalHTMLExporter.js\";\nimport { EMPTY_BLOCK_PLACEHOLDER } from \"../html/util/serializeBlocksExternalHTML.js\";\nimport { htmlToMarkdown } from \"./htmlToMarkdown.js\";\n\n// Needs to be sync because it's used in drag handler event (SideMenuPlugin)\nexport function cleanHTMLToMarkdown(cleanHTMLString: string) {\n // The external HTML exporter fills empty inline-content blocks with a\n // placeholder character so they survive an HTML round trip (see\n // `EMPTY_BLOCK_PLACEHOLDER`). Markdown has no need for that placeholder, so we\n // remove it to avoid it showing up as a stray character in the output.\n const withoutPlaceholder = cleanHTMLString\n .split(EMPTY_BLOCK_PLACEHOLDER)\n .join(\"\");\n\n return htmlToMarkdown(withoutPlaceholder);\n}\n\nexport function blocksToMarkdown<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n blocks: PartialBlock<BSchema, I, S>[],\n schema: Schema,\n editor: BlockNoteEditor<BSchema, I, S>,\n options: { document?: Document },\n): string {\n const exporter = createExternalHTMLExporter(schema, editor);\n const externalHTML = exporter.exportBlocks(blocks, options);\n\n return cleanHTMLToMarkdown(externalHTML);\n}\n","import { Fragment } from \"@tiptap/pm/model\";\nimport {\n BlockNoDefaults,\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\nimport { nodeToBlock } from \"./nodeToBlock.js\";\n\n/**\n * Converts all Blocks within a fragment to BlockNote blocks.\n */\nexport function fragmentToBlocks<\n B extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(fragment: Fragment) {\n // first convert selection to blocknote-style blocks, and then\n // pass these to the exporter\n const blocks: BlockNoDefaults<B, I, S>[] = [];\n fragment.descendants((node) => {\n if (node.type.name === \"blockContainer\") {\n if (node.firstChild?.type.name === \"blockGroup\") {\n // selection started within a block group\n // in this case the fragment starts with:\n // <blockContainer>\n // <blockGroup>\n // <blockContainer ... />\n // <blockContainer ... />\n // </blockGroup>\n // </blockContainer>\n //\n // instead of:\n // <blockContainer>\n // <blockContent ... />\n // <blockGroup>\n // <blockContainer ... />\n // <blockContainer ... />\n // </blockGroup>\n // </blockContainer>\n //\n // so we don't need to serialize this block, just descend into the children of the blockGroup\n return true;\n }\n }\n\n if (node.type.name === \"columnList\" && node.childCount === 1) {\n // column lists with a single column should be flattened (not the entire column list has been selected)\n node.firstChild?.forEach((child) => {\n blocks.push(nodeToBlock(child, node));\n });\n return false;\n }\n\n if (node.type.isInGroup(\"bnBlock\")) {\n blocks.push(nodeToBlock(node, node));\n // don't descend into children, as they're already included in the block returned by nodeToBlock\n return false;\n }\n return true;\n });\n return blocks;\n}\n","import { Fragment, Node, ResolvedPos, Slice } from \"prosemirror-model\";\nimport { Selection } from \"prosemirror-state\";\nimport { Mappable } from \"prosemirror-transform\";\n\n/**\n * This class represents an editor selection which spans multiple nodes/blocks. It's currently only used to allow users\n * to drag multiple blocks at the same time. Expects the selection anchor and head to be between nodes, i.e. just before\n * the first target node and just after the last, and that anchor and head are at the same nesting level.\n *\n * Partially based on ProseMirror's NodeSelection implementation:\n * (https://github.com/ProseMirror/prosemirror-state/blob/master/src/selection.ts)\n * MultipleNodeSelection differs from NodeSelection in the following ways:\n * 1. Stores which nodes are included in the selection instead of just a single node.\n * 2. Already expects the selection to start just before the first target node and ends just after the last, while a\n * NodeSelection automatically sets both anchor and head to just before the single target node.\n */\nexport class MultipleNodeSelection extends Selection {\n nodes: Array<Node>;\n\n constructor($anchor: ResolvedPos, $head: ResolvedPos) {\n super($anchor, $head);\n\n // Parent is at the same nesting level as anchor/head since they are just before/ just after target nodes.\n const parentNode = $anchor.node();\n\n this.nodes = [];\n $anchor.doc.nodesBetween($anchor.pos, $head.pos, (node, _pos, parent) => {\n if (parent !== null && parent.eq(parentNode)) {\n this.nodes.push(node);\n return false;\n }\n return;\n });\n }\n\n static create(doc: Node, from: number, to = from): MultipleNodeSelection {\n return new MultipleNodeSelection(doc.resolve(from), doc.resolve(to));\n }\n\n content(): Slice {\n return new Slice(Fragment.from(this.nodes), 0, 0);\n }\n\n eq(selection: Selection): boolean {\n if (!(selection instanceof MultipleNodeSelection)) {\n return false;\n }\n\n if (this.nodes.length !== selection.nodes.length) {\n return false;\n }\n\n if (this.from !== selection.from || this.to !== selection.to) {\n return false;\n }\n\n for (let i = 0; i < this.nodes.length; i++) {\n if (!this.nodes[i].eq(selection.nodes[i])) {\n return false;\n }\n }\n\n return true;\n }\n\n map(doc: Node, mapping: Mappable): Selection {\n const fromResult = mapping.mapResult(this.from);\n const toResult = mapping.mapResult(this.to);\n\n if (toResult.deleted) {\n return Selection.near(doc.resolve(fromResult.pos));\n }\n\n if (fromResult.deleted) {\n return Selection.near(doc.resolve(toResult.pos));\n }\n\n return new MultipleNodeSelection(\n doc.resolve(fromResult.pos),\n doc.resolve(toResult.pos),\n );\n }\n\n toJSON(): any {\n return { type: \"multiple-node\", anchor: this.anchor, head: this.head };\n }\n}\n\nSelection.jsonID(\"multiple-node\", MultipleNodeSelection);\n","import { Node } from \"prosemirror-model\";\nimport { NodeSelection, Selection } from \"prosemirror-state\";\nimport { EditorView } from \"prosemirror-view\";\n\nimport { createExternalHTMLExporter } from \"../../api/exporters/html/externalHTMLExporter.js\";\nimport { cleanHTMLToMarkdown } from \"../../api/exporters/markdown/markdownExporter.js\";\nimport { fragmentToBlocks } from \"../../api/nodeConversions/fragmentToBlocks.js\";\nimport { getNodeById } from \"../../api/nodeUtil.js\";\nimport { Block } from \"../../blocks/defaultBlocks.js\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport { UiElementPosition } from \"../../extensions-shared/UiElementPosition.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\nimport { MultipleNodeSelection } from \"./MultipleNodeSelection.js\";\n\nlet dragImageElement: Element | undefined;\n\nexport type SideMenuState<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n> = UiElementPosition & {\n // The block that the side menu is attached to.\n block: Block<BSchema, I, S>;\n};\n\nfunction blockPositionsFromSelection(selection: Selection, doc: Node) {\n // Absolute positions just before the first block spanned by the selection, and just after the last block. Having the\n // selection start and end just before and just after the target blocks ensures no whitespace/line breaks are left\n // behind after dragging & dropping them.\n let beforeFirstBlockPos: number;\n let afterLastBlockPos: number;\n\n // Even the user starts dragging blocks but drops them in the same place, the selection will still be moved just\n // before & just after the blocks spanned by the selection, and therefore doesn't need to change if they try to drag\n // the same blocks again. If this happens, the anchor & head move out of the block content node they were originally\n // in. If the anchor should update but the head shouldn't and vice versa, it means the user selection is outside a\n // block content node, which should never happen.\n const selectionStartInBlockContent =\n doc.resolve(selection.from).node().type.spec.group === \"blockContent\";\n const selectionEndInBlockContent =\n doc.resolve(selection.to).node().type.spec.group === \"blockContent\";\n\n // Ensures that entire outermost nodes are selected if the selection spans multiple nesting levels.\n const minDepth = Math.min(selection.$anchor.depth, selection.$head.depth);\n\n if (selectionStartInBlockContent && selectionEndInBlockContent) {\n // Absolute positions at the start of the first block in the selection and at the end of the last block. User\n // selections will always start and end in block content nodes, but we want the start and end positions of their\n // parent block nodes, which is why minDepth - 1 is used.\n const startFirstBlockPos = selection.$from.start(minDepth - 1);\n const endLastBlockPos = selection.$to.end(minDepth - 1);\n\n // Shifting start and end positions by one moves them just outside the first and last selected blocks.\n beforeFirstBlockPos = doc.resolve(startFirstBlockPos - 1).pos;\n afterLastBlockPos = doc.resolve(endLastBlockPos + 1).pos;\n } else {\n beforeFirstBlockPos = selection.from;\n afterLastBlockPos = selection.to;\n }\n\n return { from: beforeFirstBlockPos, to: afterLastBlockPos };\n}\n\nfunction setDragImage(view: EditorView, from: number, to = from) {\n if (from === to) {\n // Moves to position to be just after the first (and only) selected block.\n to += view.state.doc.resolve(from + 1).node().nodeSize;\n }\n\n // Parent element is cloned to remove all unselected children without affecting the editor content.\n const parentClone = view.domAtPos(from).node.cloneNode(true) as Element;\n const parent = view.domAtPos(from).node as Element;\n\n const getElementIndex = (parentElement: Element, targetElement: Element) =>\n Array.prototype.indexOf.call(parentElement.children, targetElement);\n\n const firstSelectedBlockIndex = getElementIndex(\n parent,\n // Expects from position to be just before the first selected block.\n view.domAtPos(from + 1).node.parentElement!,\n );\n const lastSelectedBlockIndex = getElementIndex(\n parent,\n // Expects to position to be just after the last selected block.\n view.domAtPos(to - 1).node.parentElement!,\n );\n\n for (let i = parent.childElementCount - 1; i >= 0; i--) {\n if (i > lastSelectedBlockIndex || i < firstSelectedBlockIndex) {\n parentClone.removeChild(parentClone.children[i]);\n }\n }\n\n // dataTransfer.setDragImage(element) only works if element is attached to the DOM.\n unsetDragImage(view.root);\n dragImageElement = parentClone;\n\n // Browsers may have CORS policies which prevents iframes from being\n // manipulated, so better to stay on the safe side and remove them from the\n // drag preview. The drag preview doesn't work with embedded documents\n // (iframe/embed/object) anyway, and including an <embed> (e.g. a PDF)\n // can prevent the drag from initiating at all.\n const embeddedDocs = dragImageElement.querySelectorAll(\n \"iframe, embed, object\",\n );\n embeddedDocs.forEach((el) => el.parentElement?.removeChild(el));\n\n // TODO: This is hacky, need a better way of assigning classes to the editor so that they can also be applied to the\n // drag preview.\n const classes = view.dom.className.split(\" \");\n const inheritedClasses = classes\n .filter(\n (className) =>\n className !== \"ProseMirror\" &&\n className !== \"bn-root\" &&\n className !== \"bn-editor\",\n )\n .join(\" \");\n\n dragImageElement.className =\n dragImageElement.className + \" bn-drag-preview \" + inheritedClasses;\n\n if (view.root instanceof ShadowRoot) {\n view.root.appendChild(dragImageElement);\n } else {\n view.root.body.appendChild(dragImageElement);\n }\n}\n\nexport function unsetDragImage(rootEl: Document | ShadowRoot) {\n if (dragImageElement !== undefined) {\n if (rootEl instanceof ShadowRoot) {\n rootEl.removeChild(dragImageElement);\n } else {\n rootEl.body.removeChild(dragImageElement);\n }\n\n dragImageElement = undefined;\n }\n}\n\nexport function dragStart<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n e: { dataTransfer: DataTransfer | null; clientY: number },\n block: Block<BSchema, I, S>,\n editor: BlockNoteEditor<BSchema, I, S>,\n) {\n if (!e.dataTransfer) {\n return;\n }\n\n if (editor.headless) {\n return;\n }\n const view = editor.prosemirrorView;\n\n const posInfo = getNodeById(block.id, view.state.doc);\n if (!posInfo) {\n throw new Error(`Block with ID ${block.id} not found`);\n }\n const pos = posInfo.posBeforeNode;\n\n if (pos != null) {\n const selection = view.state.selection;\n const doc = view.state.doc;\n\n const { from, to } = blockPositionsFromSelection(selection, doc);\n\n const draggedBlockInSelection = from <= pos && pos < to;\n const multipleBlocksSelected =\n selection.$anchor.node() !== selection.$head.node() ||\n selection instanceof MultipleNodeSelection;\n\n if (draggedBlockInSelection && multipleBlocksSelected) {\n view.dispatch(\n view.state.tr.setSelection(MultipleNodeSelection.create(doc, from, to)),\n );\n setDragImage(view, from, to);\n } else {\n view.dispatch(\n view.state.tr.setSelection(NodeSelection.create(view.state.doc, pos)),\n );\n setDragImage(view, pos);\n }\n\n const selectedSlice = view.state.selection.content();\n const schema = editor.pmSchema;\n\n const clipboardHTML =\n view.serializeForClipboard(selectedSlice).dom.innerHTML;\n\n const externalHTMLExporter = createExternalHTMLExporter(schema, editor);\n\n const blocks = fragmentToBlocks(selectedSlice.content);\n const externalHTML = externalHTMLExporter.exportBlocks(blocks, {});\n\n const plainText = cleanHTMLToMarkdown(externalHTML);\n\n e.dataTransfer.clearData();\n e.dataTransfer.setData(\"blocknote/html\", clipboardHTML);\n e.dataTransfer.setData(\"text/html\", externalHTML);\n e.dataTransfer.setData(\"text/plain\", plainText);\n e.dataTransfer.effectAllowed = \"move\";\n e.dataTransfer.setDragImage(dragImageElement!, 0, 0);\n }\n}\n","import { DOMParser, Slice } from \"@tiptap/pm/model\";\nimport {\n EditorState,\n Plugin,\n PluginKey,\n PluginView,\n TextSelection,\n} from \"@tiptap/pm/state\";\nimport { EditorView } from \"@tiptap/pm/view\";\n\nimport { Block } from \"../../blocks/defaultBlocks.js\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport {\n createExtension,\n createStore,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { UiElementPosition } from \"../../extensions-shared/UiElementPosition.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\nimport { getDraggableBlockFromElement } from \"../getDraggableBlockFromElement.js\";\nimport { dragStart, unsetDragImage } from \"./dragging.js\";\n\nexport type SideMenuState<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n> = UiElementPosition & {\n // The block that the side menu is attached to.\n block: Block<BSchema, I, S>;\n};\n\nconst DISTANCE_TO_CONSIDER_EDITOR_BOUNDS = 250;\n\nfunction getBlockFromCoords(\n view: EditorView,\n coords: { left: number; top: number },\n adjustForColumns = true,\n) {\n const elements = view.root.elementsFromPoint(coords.left, coords.top);\n\n for (const element of elements) {\n if (!view.dom.contains(element)) {\n // probably a ui overlay like formatting toolbar etc\n continue;\n }\n if (adjustForColumns) {\n const column = element.closest(\"[data-node-type=columnList]\");\n if (column) {\n return getBlockFromCoords(\n view,\n {\n // TODO can we do better than this?\n left: coords.left + 50, // bit hacky, but if we're inside a column, offset x position to right to account for the width of sidemenu itself\n top: coords.top,\n },\n false,\n );\n }\n }\n return getDraggableBlockFromElement(element, view);\n }\n return undefined;\n}\n\nfunction getBlockFromMousePos(\n mousePos: {\n x: number;\n y: number;\n },\n view: EditorView,\n): { node: HTMLElement; id: string } | undefined {\n // Editor itself may have padding or other styling which affects\n // size/position, so we get the boundingRect of the first child (i.e. the\n // blockGroup that wraps all blocks in the editor) for more accurate side\n // menu placement.\n if (!view.dom.firstChild) {\n return;\n }\n\n const editorBoundingBox = (\n view.dom.firstChild as HTMLElement\n ).getBoundingClientRect();\n\n // Gets block at mouse cursor's position.\n const coords = {\n // Clamps the x position to the editor's bounding box.\n left: Math.min(\n Math.max(editorBoundingBox.left + 10, mousePos.x),\n editorBoundingBox.right - 10,\n ),\n top: mousePos.y,\n };\n\n const referenceBlock = getBlockFromCoords(view, coords);\n\n if (!referenceBlock) {\n // could not find the reference block\n return undefined;\n }\n\n /**\n * Because blocks may be nested, we need to check the right edge of the parent block:\n * ```\n * | BlockA |\n * x | BlockB y|\n * ```\n * Hovering at position x (left edge of BlockB) would return BlockA.\n * Instead, we check at position y (right edge of BlockA) to correctly identify BlockB.\n */\n const referenceBlocksBoundingBox =\n referenceBlock.node.getBoundingClientRect();\n return getBlockFromCoords(\n view,\n {\n left: referenceBlocksBoundingBox.right - 10,\n top: mousePos.y,\n },\n false,\n );\n}\n\n/**\n * With the sidemenu plugin we can position a menu next to a hovered block.\n */\nexport class SideMenuView<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n> implements PluginView {\n public state?: SideMenuState<BSchema, I, S>;\n public readonly emitUpdate: (state: SideMenuState<BSchema, I, S>) => void;\n\n private mousePos: { x: number; y: number } | undefined;\n\n private hoveredBlock: HTMLElement | undefined;\n\n public menuFrozen = false;\n\n public isDragOrigin = false;\n\n constructor(\n private readonly editor: BlockNoteEditor<BSchema, I, S>,\n private readonly pmView: EditorView,\n emitUpdate: (state: SideMenuState<BSchema, I, S>) => void,\n ) {\n this.emitUpdate = () => {\n if (!this.state) {\n throw new Error(\"Attempting to update uninitialized side menu\");\n }\n\n emitUpdate(this.state);\n };\n\n this.pmView.root.addEventListener(\n \"dragstart\",\n this.onDragStart as EventListener,\n );\n this.pmView.root.addEventListener(\n \"dragover\",\n this.onDragOver as EventListener,\n );\n this.pmView.root.addEventListener(\n \"drop\",\n this.onDrop as EventListener,\n true,\n );\n this.pmView.root.addEventListener(\n \"dragend\",\n this.onDragEnd as EventListener,\n true,\n );\n\n // Shows or updates menu position whenever the cursor moves, if the menu isn't frozen.\n this.pmView.root.addEventListener(\n \"mousemove\",\n this.onMouseMove as EventListener,\n true,\n );\n\n // Hides and unfreezes the menu whenever the user presses a key.\n this.pmView.root.addEventListener(\n \"keydown\",\n this.onKeyDown as EventListener,\n true,\n );\n }\n\n updateState = (state: SideMenuState<BSchema, I, S>) => {\n this.state = state;\n this.emitUpdate(this.state);\n };\n\n updateStateFromMousePos = () => {\n if (this.menuFrozen || !this.mousePos) {\n return;\n }\n\n const closestEditor = this.findClosestEditorElement({\n clientX: this.mousePos.x,\n clientY: this.mousePos.y,\n });\n\n if (\n closestEditor?.element !== this.pmView.dom ||\n closestEditor.distance > DISTANCE_TO_CONSIDER_EDITOR_BOUNDS\n ) {\n if (this.state?.show) {\n this.state.show = false;\n this.updateState(this.state);\n }\n return;\n }\n\n const block = getBlockFromMousePos(this.mousePos, this.pmView);\n\n // Closes the menu if the mouse cursor is beyond the editor vertically.\n if (!block || !this.editor.isEditable) {\n if (this.state?.show) {\n this.state.show = false;\n this.updateState(this.state);\n }\n\n return;\n }\n\n // Doesn't update if the menu is already open and the mouse cursor is still hovering the same block.\n if (\n this.state?.show &&\n this.hoveredBlock?.hasAttribute(\"data-id\") &&\n this.hoveredBlock?.getAttribute(\"data-id\") === block.id\n ) {\n return;\n }\n\n this.hoveredBlock = block.node;\n\n // Shows or updates elements.\n if (this.editor.isEditable) {\n const blockContentBoundingBox = block.node.getBoundingClientRect();\n const column = block.node.closest(\"[data-node-type=column]\");\n const sideMenuBlock = this.editor.getBlock(\n this.hoveredBlock!.getAttribute(\"data-id\")!,\n );\n if (!sideMenuBlock) {\n if (this.state?.show) {\n this.state.show = false;\n this.hoveredBlock = undefined;\n this.emitUpdate(this.state);\n }\n return;\n }\n this.state = {\n show: true,\n referencePos: new DOMRect(\n column\n ? // We take the first child as column elements have some default\n // padding. This is a little weird since this child element will\n // be the first block, but since it's always non-nested and we\n // only take the x coordinate, it's ok.\n column.firstElementChild!.getBoundingClientRect().x\n : (\n this.pmView.dom.firstChild as HTMLElement\n ).getBoundingClientRect().x,\n blockContentBoundingBox.y,\n blockContentBoundingBox.width,\n blockContentBoundingBox.height,\n ),\n block: sideMenuBlock,\n };\n this.updateState(this.state);\n }\n };\n\n /**\n * If a block is being dragged, ProseMirror usually gets the context of what's\n * being dragged from `view.dragging`, which is automatically set when a\n * `dragstart` event fires in the editor. However, if the user tries to drag\n * and drop blocks between multiple editors, only the one in which the drag\n * began has that context, so we need to set it on the others manually. This\n * ensures that PM always drops the blocks in between other blocks, and not\n * inside them.\n *\n * After the `dragstart` event fires on the drag handle, it sets\n * `blocknote/html` data on the clipboard. This handler fires right after,\n * parsing the `blocknote/html` data into nodes and setting them on\n * `view.dragging`.\n *\n * Note: Setting `view.dragging` on `dragover` would be better as the user\n * could then drag between editors in different windows, but you can only\n * access `dataTransfer` contents on `dragstart` and `drop` events.\n */\n onDragStart = (event: DragEvent) => {\n const html = event.dataTransfer?.getData(\"blocknote/html\");\n if (!html) {\n return;\n }\n\n if (this.pmView.dragging) {\n // already dragging, so no-op\n return;\n }\n\n const element = document.createElement(\"div\");\n element.innerHTML = html;\n\n const parser = DOMParser.fromSchema(this.pmView.state.schema);\n const node = parser.parse(element, {\n topNode: this.pmView.state.schema.nodes[\"blockGroup\"].create(),\n });\n\n this.pmView.dragging = {\n slice: new Slice(node.content, 0, 0),\n move: true,\n };\n };\n\n /**\n * Finds the closest editor visually to the given coordinates\n */\n private findClosestEditorElement = (coords: {\n clientX: number;\n clientY: number;\n }) => {\n // Get all editor elements in the document\n const editors = Array.from(this.pmView.root.querySelectorAll(\".bn-editor\"));\n\n if (editors.length === 0) {\n return null;\n }\n\n // Find the editor with the smallest distance to the coordinates\n let closestEditor = editors[0];\n let minDistance = Number.MAX_VALUE;\n\n editors.forEach((editor) => {\n const rect = editor\n .querySelector(\".bn-block-group\")!\n .getBoundingClientRect();\n\n const distanceX =\n coords.clientX < rect.left\n ? rect.left - coords.clientX\n : coords.clientX > rect.right\n ? coords.clientX - rect.right\n : 0;\n\n const distanceY =\n coords.clientY < rect.top\n ? rect.top - coords.clientY\n : coords.clientY > rect.bottom\n ? coords.clientY - rect.bottom\n : 0;\n\n const distance = Math.sqrt(\n Math.pow(distanceX, 2) + Math.pow(distanceY, 2),\n );\n\n if (distance < minDistance) {\n minDistance = distance;\n closestEditor = editor;\n }\n });\n\n return {\n element: closestEditor,\n distance: minDistance,\n };\n };\n\n /**\n * This dragover event handler listens at the document level,\n * and is trying to handle dragover events for all editors.\n *\n * It specifically is trying to handle the following cases:\n * - If the dragover event is within the bounds of any editor, then it does nothing\n * - If the dragover event is outside the bounds of any editor, but close enough (within DISTANCE_TO_CONSIDER_EDITOR_BOUNDS) to the closest editor,\n * then it dispatches a synthetic dragover event to the closest editor (which will trigger the drop-cursor to be shown on that editor)\n * - If the dragover event is outside the bounds of the current editor, then it will dispatch a synthetic dragleave event to the current editor\n * (which will trigger the drop-cursor to be removed from the current editor)\n *\n * The synthetic event is a necessary evil because we do not control prosemirror-dropcursor to be able to show the drop-cursor within the range we want\n */\n onDragOver = (event: DragEvent) => {\n if ((event as any).synthetic) {\n return;\n }\n\n // Relevance gate: Only handle drags that belong to BlockNote\n // This prevents interference with external drag-and-drop libraries\n // by avoiding calls to closeDropCursor() for non-BlockNote drags\n const isBlockNoteDrag =\n this.pmView.dragging !== null ||\n this.isDragOrigin ||\n event.dataTransfer?.types.includes(\"blocknote/html\") ||\n (event.target instanceof Node && this.pmView.dom.contains(event.target));\n\n if (!isBlockNoteDrag) {\n // Not a BlockNote-related drag, return early without any processing\n return;\n }\n\n const dragEventContext = this.getDragEventContext(event);\n\n if (!dragEventContext || !dragEventContext.isDropPoint) {\n // This is not a drag event that we are interested in\n // so, we close the drop-cursor\n this.closeDropCursor();\n return;\n }\n\n if (\n dragEventContext.isDropPoint &&\n !dragEventContext.isDropWithinEditorBounds\n ) {\n // we are the drop point, but the drag over event is not within the bounds of this editor instance\n // so, we need to dispatch an event that is in the bounds of this editor instance\n this.dispatchSyntheticEvent(event);\n }\n };\n\n /**\n * Closes the drop-cursor for the current editor\n */\n private closeDropCursor = () => {\n const evt = new Event(\"dragleave\", { bubbles: false });\n // It needs to be synthetic, so we don't accidentally think it is a real dragend event\n (evt as any).synthetic = true;\n // We dispatch the event to the current editor, so that the drop-cursor is removed for it\n this.pmView.dom.dispatchEvent(evt);\n };\n\n /**\n * It is surprisingly difficult to determine the information we need to know about a drag event\n *\n * This function is trying to determine the following:\n * - Whether the current editor instance is the drop point\n * - Whether the current editor instance is the drag origin\n * - Whether the drop event is within the bounds of the current editor instance\n */\n getDragEventContext = (event: DragEvent) => {\n // Relevance gate: Only handle drags that belong to BlockNote\n // Check if at least one of the following is true:\n // 1. ProseMirror drag started in an editor\n // 2. Side menu drag\n // 3. BlockNote-specific data type in the drag\n // 4. (optional stricter mode) Event target is inside this editor\n const isBlockNoteDrag =\n this.pmView.dragging !== null ||\n this.isDragOrigin ||\n event.dataTransfer?.types.includes(\"blocknote/html\") ||\n (event.target instanceof Node && this.pmView.dom.contains(event.target));\n\n if (!isBlockNoteDrag) {\n // Not a BlockNote-related drag, return early\n return undefined;\n }\n\n // We need to check if there is text content that is being dragged (select some text & just drag it)\n const textContentIsBeingDragged =\n !event.dataTransfer?.types.includes(\"blocknote/html\") &&\n !!this.pmView.dragging;\n // This is the side menu drag from this plugin\n const sideMenuIsBeingDragged = !!this.isDragOrigin;\n // Tells us that the current editor instance has a drag ongoing (either text or side menu)\n const isDragOrigin = textContentIsBeingDragged || sideMenuIsBeingDragged;\n\n // Tells us which editor instance is the closest to the drag event (whether or not it is actually reasonably close)\n const closestEditor = this.findClosestEditorElement(event);\n\n // We arbitrarily decide how far is \"too far\" from the closest editor to be considered a drop point\n if (\n !closestEditor ||\n closestEditor.distance > DISTANCE_TO_CONSIDER_EDITOR_BOUNDS\n ) {\n // we are too far from the closest editor, or no editor was found\n return undefined;\n }\n\n // We check if the closest editor is the same as the current editor instance (which is the drop point)\n const isDropPoint = closestEditor.element === this.pmView.dom;\n // We check if the current editor instance is the same as the editor instance that the drag event is happening within\n const isDropWithinEditorBounds =\n isDropPoint && closestEditor.distance === 0;\n\n // We never want to handle drop events that are not related to us\n if (!isDropPoint && !isDragOrigin) {\n // we are not the drop point or drag origin, so not relevant to us\n return undefined;\n }\n\n return {\n isDropPoint,\n isDropWithinEditorBounds,\n isDragOrigin,\n };\n };\n\n /**\n * The drop event handler listens at the document level,\n * and handles drop events for all editors.\n *\n * It specifically handles the following cases:\n * - If we are both the drag origin and drop point:\n * - Let normal drop handling take over\n * - If we are the drop point but not the drag origin:\n * - Collapse selection to prevent PM from deleting unrelated content\n * - If drop event is outside our editor bounds, dispatch synthetic drop event to our editor\n * - If we are the drag origin but not the drop point:\n * - Delete the dragged content from our editor after a delay\n */\n onDrop = (event: DragEvent) => {\n if ((event as any).synthetic) {\n return;\n }\n\n // Relevance gate: Only handle drags that belong to BlockNote\n // This prevents interference with external drag-and-drop libraries\n const isBlockNoteDrag =\n this.pmView.dragging !== null ||\n this.isDragOrigin ||\n event.dataTransfer?.types.includes(\"blocknote/html\") ||\n (event.target instanceof Node && this.pmView.dom.contains(event.target));\n\n if (!isBlockNoteDrag) {\n // Not a BlockNote-related drag, return early without any processing\n return;\n }\n\n const context = this.getDragEventContext(event);\n if (!context) {\n this.closeDropCursor();\n // This is not a drag event that we are interested in\n return;\n }\n const { isDropPoint, isDropWithinEditorBounds, isDragOrigin } = context;\n\n if (!isDropWithinEditorBounds && isDropPoint) {\n // Any time that the drop event is outside of the editor bounds (but still close to an editor instance)\n // We dispatch a synthetic event that is in the bounds of the editor instance, to have the correct drop point\n this.dispatchSyntheticEvent(event);\n }\n\n if (isDropPoint) {\n // The current instance is the drop point\n\n if (this.pmView.dragging) {\n // Do not collapse selection when text content is being dragged\n return;\n }\n // Because the editor selection is unrelated to the dragged content, we\n // don't want PM to delete its content. Therefore, we collapse the\n // selection.\n this.pmView.dispatch(\n this.pmView.state.tr.setSelection(\n TextSelection.create(\n this.pmView.state.tr.doc,\n this.pmView.state.tr.selection.anchor,\n ),\n ),\n );\n return;\n } else if (isDragOrigin) {\n // The current instance is the drag origin, but not the drop point\n // our content got dropped somewhere else\n\n // Because the editor from which the block originates doesn't get a drop\n // event on it, PM doesn't delete its selected content. Therefore, we\n // need to do so manually.\n //\n // Note: Deleting the selected content from the editor from which the\n // block originates, may change its height. This can cause the position of\n // the editor in which the block is being dropping to shift, before it\n // can handle the drop event. That in turn can cause the drop to happen\n // somewhere other than the user intended. To get around this, we delay\n // deleting the selected content until all editors have had the chance to\n // handle the event.\n setTimeout(\n () => this.pmView.dispatch(this.pmView.state.tr.deleteSelection()),\n 0,\n );\n return;\n }\n };\n\n onDragEnd = (event: DragEvent) => {\n if ((event as any).synthetic) {\n return;\n }\n // When the user starts dragging a block, `view.dragging` is set on all\n // BlockNote editors. However, when the drag ends, only the editor that the\n // drag originated in automatically clears `view.dragging`. Therefore, we\n // have to manually clear it on all editors.\n this.pmView.dragging = null;\n };\n\n onKeyDown = (_event: KeyboardEvent) => {\n if (this.state?.show && this.editor.isFocused()) {\n // Typing in editor should hide side menu\n this.state.show = false;\n this.emitUpdate(this.state);\n }\n };\n\n onMouseMove = (event: MouseEvent) => {\n if (this.menuFrozen) {\n return;\n }\n\n // Synthetic mousemove events created via `new Event(\"mousemove\")` (e.g.\n // dispatched by browser extensions) have no `clientX`/`clientY`, which\n // would make `elementsFromPoint` throw on the resulting non-finite\n // coordinates.\n if (!Number.isFinite(event.clientX) || !Number.isFinite(event.clientY)) {\n return;\n }\n\n this.mousePos = { x: event.clientX, y: event.clientY };\n\n // We want the full area of the editor to check if the cursor is hovering\n // above it though.\n const editorOuterBoundingBox = this.pmView.dom.getBoundingClientRect();\n const cursorWithinEditor =\n this.mousePos.x > editorOuterBoundingBox.left &&\n this.mousePos.x < editorOuterBoundingBox.right &&\n this.mousePos.y > editorOuterBoundingBox.top &&\n this.mousePos.y < editorOuterBoundingBox.bottom;\n\n // Doesn't update if the mouse hovers an element that's over the editor but\n // isn't a part of it or the side menu.\n if (\n // Cursor is within the editor area\n cursorWithinEditor &&\n // An element is hovered\n event &&\n event.target &&\n // Element is outside this editor and its portaled UI\n !this.editor.isWithinEditor(event.target as HTMLElement)\n ) {\n if (this.state?.show) {\n this.state.show = false;\n this.emitUpdate(this.state);\n }\n\n return;\n }\n\n this.updateStateFromMousePos();\n };\n\n private dispatchSyntheticEvent(event: DragEvent) {\n const evt = new Event(event.type as \"dragover\", event) as any;\n const dropPointBoundingBox = (\n this.pmView.dom.firstChild as HTMLElement\n ).getBoundingClientRect();\n evt.clientX = event.clientX;\n evt.clientY = event.clientY;\n\n evt.clientX = Math.min(\n Math.max(event.clientX, dropPointBoundingBox.left),\n dropPointBoundingBox.left + dropPointBoundingBox.width,\n );\n evt.clientY = Math.min(\n Math.max(event.clientY, dropPointBoundingBox.top),\n dropPointBoundingBox.top + dropPointBoundingBox.height,\n );\n\n evt.dataTransfer = event.dataTransfer;\n evt.preventDefault = () => event.preventDefault();\n evt.synthetic = true; // prevent recursion\n this.pmView.dom.dispatchEvent(evt);\n }\n\n // Needed in cases where the editor state updates without the mouse cursor\n // moving, as some state updates can require a side menu update. For example,\n // adding a button to the side menu which removes the block can cause the\n // block below to jump up into the place of the removed block when clicked,\n // allowing the user to click the button again without moving the cursor. This\n // would otherwise not update the side menu, and so clicking the button again\n // would attempt to remove the same block again, causing an error.\n update(_view: EditorView, prevState: EditorState) {\n const docChanged = !prevState.doc.eq(this.pmView.state.doc);\n if (docChanged && this.state?.show) {\n this.updateStateFromMousePos();\n }\n }\n\n destroy() {\n if (this.state?.show) {\n this.state.show = false;\n this.emitUpdate(this.state);\n }\n this.pmView.root.removeEventListener(\n \"mousemove\",\n this.onMouseMove as EventListener,\n true,\n );\n this.pmView.root.removeEventListener(\n \"dragstart\",\n this.onDragStart as EventListener,\n );\n this.pmView.root.removeEventListener(\n \"dragover\",\n this.onDragOver as EventListener,\n );\n this.pmView.root.removeEventListener(\n \"drop\",\n this.onDrop as EventListener,\n true,\n );\n this.pmView.root.removeEventListener(\n \"dragend\",\n this.onDragEnd as EventListener,\n true,\n );\n this.pmView.root.removeEventListener(\n \"keydown\",\n this.onKeyDown as EventListener,\n true,\n );\n }\n}\n\nexport const sideMenuPluginKey = new PluginKey(\"SideMenuPlugin\");\n\nexport const SideMenuExtension = createExtension(({ editor }) => {\n let view: SideMenuView<any, any, any> | undefined;\n const store = createStore<SideMenuState<any, any, any> | undefined>(\n undefined,\n );\n\n return {\n key: \"sideMenu\",\n store,\n prosemirrorPlugins: [\n new Plugin({\n key: sideMenuPluginKey,\n view: (editorView) => {\n view = new SideMenuView(editor, editorView, (state) => {\n // TODO: Without spreading the state, in some cases like toggling\n // `show`, this doesn't trigger an update.\n store.setState({ ...state });\n });\n return view;\n },\n }),\n ],\n\n /**\n * Handles drag & drop events for blocks.\n */\n blockDragStart(\n event: { dataTransfer: DataTransfer | null; clientY: number },\n block: Block<any, any, any>,\n ) {\n if (view) {\n view.isDragOrigin = true;\n }\n dragStart(event, block, editor);\n },\n\n /**\n * Handles drag & drop events for blocks.\n */\n blockDragEnd() {\n unsetDragImage(editor.prosemirrorView.root);\n if (view) {\n view.isDragOrigin = false;\n }\n\n editor.blur();\n },\n\n /**\n * Whether the side menu is currently frozen (e.g. because the drag handle\n * menu is open).\n */\n get menuFrozen() {\n return view!.menuFrozen;\n },\n\n /**\n * Freezes the side menu. When frozen, the side menu will stay\n * attached to the same block regardless of which block is hovered by the\n * mouse cursor.\n */\n freezeMenu() {\n view!.menuFrozen = true;\n view!.state!.show = true;\n view!.emitUpdate(view!.state!);\n },\n\n /**\n * Unfreezes the side menu. When frozen, the side menu will stay\n * attached to the same block regardless of which block is hovered by the\n * mouse cursor.\n */\n unfreezeMenu() {\n view!.menuFrozen = false;\n view!.state!.show = false;\n view!.emitUpdate(view!.state!);\n },\n\n /**\n * Hides the side menu unless it is currently frozen (e.g. the drag\n * handle menu is open). Used to dismiss the menu on scroll without\n * interfering with open submenus.\n */\n hideMenuIfNotFrozen() {\n if (!view!.menuFrozen && view!.state?.show) {\n view!.state.show = false;\n view!.emitUpdate(view!.state!);\n }\n },\n } as const;\n});\n","import { TextSelection } from \"prosemirror-state\";\n\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor\";\nimport {\n createExtension,\n createStore,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { Block } from \"../../blocks/index.js\";\n\n/**\n * A single editor-wide extension that drives the source popup for blocks that\n * render a preview. Which blocks it activates on is decided by each spec's\n * `meta.hasPreview` flag, so individual blocks opt in rather than the extension\n * being configured with a block type.\n *\n * The extension is registered once (it's a default extension) and is a no-op\n * when no block declares `meta.hasPreview`.\n */\nexport const SourceBlockWithPreviewExtension = createExtension(\n ({ editor }: { editor: BlockNoteEditor<any> }) => {\n const store = createStore<{\n popupOpen: string | undefined;\n selected: string | undefined;\n }>({\n popupOpen: undefined,\n selected: undefined,\n });\n\n // A block has a preview iff its spec's implementation declares\n // `meta.hasPreview` (read from the spec, like the syntax-highlighting\n // extension reads `meta.highlight`).\n const blockHasPreview = (block: Block<any, any, any>) =>\n !!editor.schema.blockSpecs[block.type]?.implementation?.meta?.hasPreview;\n\n const handleArrow =\n (direction: \"prev\" | \"next\") =>\n ({ editor }: { editor: BlockNoteEditor<any> }) => {\n const { block, prevBlock, nextBlock } = editor.getTextCursorPosition();\n if (!blockHasPreview(block) || store.state.popupOpen === block.id) {\n return false;\n }\n\n const targetBlock = direction === \"prev\" ? prevBlock : nextBlock;\n if (!targetBlock) {\n return false;\n }\n\n editor.setTextCursorPosition(\n targetBlock.id,\n direction === \"prev\" ? \"end\" : \"start\",\n );\n\n return true;\n };\n\n return {\n key: \"sourceBlockWithPreview\",\n store,\n keyboardShortcuts: {\n // Toggles the popup. This may be overridden by `hardBreakShortcut`.\n Enter: ({ editor }) => {\n const { block } = editor.getTextCursorPosition();\n if (!blockHasPreview(block)) {\n return false;\n }\n\n if (\n store.state.popupOpen === block.id &&\n editor.schema.blockSpecs[block.type]?.implementation?.meta\n ?.hardBreakShortcut === \"enter\"\n ) {\n const view = editor.prosemirrorView!;\n view.dispatch(view.state.tr.insertText(\"\\n\"));\n\n return true;\n }\n\n editor.setTextCursorPosition(block.id, \"end\");\n store.setState((state) => ({\n ...state,\n popupOpen:\n store.state.popupOpen === block.id ? undefined : block.id,\n }));\n\n return true;\n },\n // Closes the popup.\n Escape: ({ editor }) => {\n const { block } = editor.getTextCursorPosition();\n if (!blockHasPreview(block) || store.state.popupOpen !== block.id) {\n return false;\n }\n\n editor.setTextCursorPosition(block.id, \"end\");\n\n store.setState((state) => ({ ...state, popupOpen: undefined }));\n\n return true;\n },\n // While the popup is open, selects the whole source instead of the\n // whole document.\n \"Mod-a\": ({ editor }) => {\n const { block } = editor.getTextCursorPosition();\n if (!blockHasPreview(block) || store.state.popupOpen !== block.id) {\n return false;\n }\n\n const view = editor.prosemirrorView!;\n const { $from } = view.state.selection;\n if ($from.parent.type.name !== block.type) {\n return false;\n }\n\n view.dispatch(\n view.state.tr.setSelection(\n TextSelection.create(view.state.doc, $from.start(), $from.end()),\n ),\n );\n\n return true;\n },\n // While the popup is closed, moves the selection straight to the previous/next block\n // instead of into the (hidden) source.\n ArrowUp: handleArrow(\"prev\"),\n ArrowLeft: handleArrow(\"prev\"),\n ArrowDown: handleArrow(\"next\"),\n ArrowRight: handleArrow(\"next\"),\n },\n mount: ({ dom, signal }) => {\n // Closes the popup when the selection leaves the block that owns it and tracks which block\n // the selection is in.\n const unsubscribeSelectionChange = editor.onSelectionChange(() => {\n const { block } = editor.getTextCursorPosition();\n\n const selected = blockHasPreview(block) ? block.id : undefined;\n const popupOpen =\n store.state.popupOpen && store.state.popupOpen !== block.id\n ? undefined\n : store.state.popupOpen;\n\n if (\n selected === store.state.selected &&\n popupOpen === store.state.popupOpen\n ) {\n return;\n }\n\n store.setState((state) => ({ ...state, selected, popupOpen }));\n });\n signal.addEventListener(\"abort\", unsubscribeSelectionChange);\n\n // While the popup is closed, prevents editing of the (hidden) source. Handled here rather\n // than in `keyboardShortcuts` as it needs to match any text-input key, which a keymap\n // can't express.\n const handleKeyDown = (event: KeyboardEvent) => {\n if (!editor.isEditable) {\n return;\n }\n\n const { block } = editor.getTextCursorPosition();\n if (!blockHasPreview(block) || store.state.popupOpen === block.id) {\n return;\n }\n\n if (event.key === \"Backspace\" || event.key === \"Delete\") {\n event.preventDefault();\n event.stopImmediatePropagation();\n editor.removeBlocks([block.id]);\n\n return;\n }\n\n if (\n (event.key.length === 1 && !event.ctrlKey && !event.metaKey) ||\n event.key === \"Tab\"\n ) {\n event.preventDefault();\n event.stopImmediatePropagation();\n }\n };\n dom.addEventListener(\"keydown\", handleKeyDown, {\n capture: true,\n signal,\n });\n\n const handleBlur = () =>\n store.setState((state) => ({ ...state, popupOpen: undefined }));\n dom.addEventListener(\"blur\", handleBlur, { capture: true, signal });\n },\n };\n },\n);\n","import { Selection, TextSelection } from \"prosemirror-state\";\n\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor\";\nimport {\n createExtension,\n createStore,\n} from \"../../editor/BlockNoteExtension.js\";\n\n/**\n * Inline-content counterpart of {@link SourceBlockWithPreviewExtension}. A\n * single editor-wide extension that drives the source popup for inline content\n * that renders a preview. Which inline content it activates on is decided by\n * each spec's `meta.hasPreview` flag, so individual inline content opts in\n * rather than the extension being configured with a type.\n *\n * Unlike the block version, the popup isn't toggled with a separate state flag:\n * it's open exactly when the selection is inside the inline content's source.\n * The store therefore only tracks which inline content (by its position) holds\n * the selection - moving the selection in opens its popup, moving it out closes\n * it. Since the source popup is always laid out (just hidden via opacity), the\n * cursor can navigate into and out of it with the arrow keys as usual.\n *\n * The extension is registered once (it's a default extension) and is a no-op\n * when no inline content declares `meta.hasPreview`.\n */\nexport const SourceInlineContentWithPreviewExtension = createExtension(\n ({ editor }: { editor: BlockNoteEditor<any, any, any> }) => {\n const store = createStore<{\n selected: number | undefined;\n }>({\n selected: undefined,\n });\n\n // Inline content has a preview iff its spec's implementation declares\n // `meta.hasPreview`.\n const nodeHasPreview = (nodeName: string) =>\n !!editor.schema.inlineContentSpecs[nodeName]?.implementation?.meta\n ?.hasPreview;\n\n // Moves the selection out of the inline content, to just `\"before\"` or\n // `\"after\"` it, which closes the popup via the selection-change handler\n // below. Lets the keyboard commit-and-exit the source the same way arrowing\n // past its edge does, keeps Enter from splitting the block while editing the\n // source, and lets the up/down arrows step out of the source rather than\n // staying trapped inside it.\n const moveSelectionOut =\n (direction: \"before\" | \"after\") =>\n ({ editor }: { editor: BlockNoteEditor<any, any, any> }) => {\n const { $from } = editor.prosemirrorState.selection;\n const node = $from.node();\n if (!nodeHasPreview(node.type.name)) {\n return false;\n }\n\n const view = editor.prosemirrorView!;\n const selection = Selection.near(\n view.state.doc.resolve(\n direction === \"before\" ? $from.before() : $from.after(),\n ),\n direction === \"before\" ? -1 : 1,\n );\n view.dispatch(view.state.tr.setSelection(selection));\n\n return true;\n };\n\n return {\n key: \"sourceInlineContentWithPreview\",\n store,\n keyboardShortcuts: {\n Enter: moveSelectionOut(\"after\"),\n \"Shift-Enter\": moveSelectionOut(\"after\"),\n Escape: moveSelectionOut(\"after\"),\n ArrowUp: moveSelectionOut(\"before\"),\n ArrowDown: moveSelectionOut(\"after\"),\n // While editing the source, selects the whole source instead of the\n // whole document.\n \"Mod-a\": ({ editor }) => {\n const { $from } = editor.prosemirrorState.selection;\n if (!nodeHasPreview($from.node().type.name)) {\n return false;\n }\n\n const view = editor.prosemirrorView!;\n view.dispatch(\n view.state.tr.setSelection(\n TextSelection.create(view.state.doc, $from.start(), $from.end()),\n ),\n );\n\n return true;\n },\n },\n mount: ({ dom, signal }) => {\n // The popup is open exactly when the selection is inside the inline\n // content, so we just track which inline content (if any) holds it.\n const unsubscribeSelectionChange = editor.onSelectionChange(() => {\n const { $from } = editor.prosemirrorState.selection;\n const node = $from.node();\n\n store.setState({\n selected: nodeHasPreview(node.type.name)\n ? $from.before()\n : undefined,\n });\n });\n signal.addEventListener(\"abort\", unsubscribeSelectionChange);\n\n // Sets `visibility: hidden` on the popup for a single frame when pressing up/down arrow\n // keys. The popup is normally hidden through `opacity: 0`, which means it's still visible\n // to the browser for navigation. Therefore, the up/down arrows can sometimes move the\n // selection into the popup from unexpected positions, such as on the same line. Setting\n // `visibility: hidden` makes the browser ignore it when determining the new selection.\n // TODO: This is hacky, we should find a cleaner solution.\n const handleVerticalArrow = (event: KeyboardEvent) => {\n if (event.key !== \"ArrowUp\" && event.key !== \"ArrowDown\") {\n return;\n }\n\n // When the selection is already inside a source, leave navigation\n // (moving within or out of it) to the browser as usual.\n const { $from } = editor.prosemirrorState.selection;\n if (nodeHasPreview($from.node().type.name)) {\n return;\n }\n\n dom.classList.add(\"bn-suppress-source-popup-caret\");\n requestAnimationFrame(() =>\n dom.classList.remove(\"bn-suppress-source-popup-caret\"),\n );\n };\n dom.addEventListener(\"keydown\", handleVerticalArrow, {\n capture: true,\n signal,\n });\n\n const handleBlur = () => store.setState({ selected: undefined });\n dom.addEventListener(\"blur\", handleBlur, { capture: true, signal });\n },\n };\n },\n);\n","import type { HighlighterGeneric } from \"@shikijs/types\";\nimport { Parser, createHighlightPlugin } from \"prosemirror-highlight\";\nimport { createParser } from \"prosemirror-highlight/shiki\";\nimport type { SyntaxHighlightingOptions } from \"./SyntaxHighlighting.js\";\nimport { CustomBlockNoteSchema } from \"../../schema/schema.js\";\n\nexport const shikiParserSymbol = Symbol.for(\"blocknote.shikiParser\");\nexport const shikiHighlighterPromiseSymbol = Symbol.for(\n \"blocknote.shikiHighlighterPromise\",\n);\n\n// Languages that represent \"no highlighting\" - skipped without asking Shiki to\n// load a grammar for them.\nconst PLAIN_TEXT_LANGUAGES = [\"text\", \"none\", \"plaintext\", \"txt\"];\n\n/**\n * Creates the syntax highlighting plugin for the given block types, lazily\n * loading the highlighter on first use.\n *\n * Each spec's `meta.highlight` callback resolves a node to a language, which is\n * passed straight to Shiki - it resolves aliases and loads the grammar from its\n * bundle, so any language the provided highlighter bundles can be highlighted.\n */\nexport function lazyShikiPlugin(\n options: SyntaxHighlightingOptions,\n nodeTypes: string[],\n schema: CustomBlockNoteSchema<any, any, any>,\n) {\n const globalThisForShiki = globalThis as {\n [shikiHighlighterPromiseSymbol]?: Promise<HighlighterGeneric<any, any>>;\n [shikiParserSymbol]?: Parser;\n };\n\n let highlighter: HighlighterGeneric<any, any> | undefined;\n let parser: Parser | undefined;\n // Languages the highlighter failed to load (e.g. not in its bundle). Tracked\n // so we don't keep retrying - and re-triggering re-highlights - forever.\n const unsupportedLanguages = new Set<string>();\n const lazyParser: Parser = (parserOptions) => {\n if (!options.createHighlighter) {\n return [];\n }\n if (!highlighter) {\n globalThisForShiki[shikiHighlighterPromiseSymbol] =\n globalThisForShiki[shikiHighlighterPromiseSymbol] ||\n options.createHighlighter();\n\n return globalThisForShiki[shikiHighlighterPromiseSymbol].then(\n (createdHighlighter) => {\n highlighter = createdHighlighter;\n },\n );\n }\n const language = parserOptions.language;\n\n if (\n !language ||\n PLAIN_TEXT_LANGUAGES.includes(language) ||\n unsupportedLanguages.has(language)\n ) {\n return [];\n }\n\n if (!highlighter.getLoadedLanguages().includes(language)) {\n return highlighter.loadLanguage(language as any).catch(() => {\n // The highlighter doesn't bundle this language - give up on it so we\n // don't loop trying to load it on every re-highlight.\n unsupportedLanguages.add(language);\n });\n }\n\n if (!parser) {\n parser =\n globalThisForShiki[shikiParserSymbol] ||\n createParser(highlighter as any, pickThemeOptions(highlighter));\n globalThisForShiki[shikiParserSymbol] = parser;\n }\n\n return parser(parserOptions);\n };\n\n return createHighlightPlugin({\n parser: lazyParser,\n // The highlight plugin only gives us the block content node, so we can only\n // reconstruct the block's `type` and `props` (which is all a spec's\n // `meta.highlight` needs to pick a language).\n languageExtractor: (node) => {\n const nodeShape = {\n type: node.type.name,\n props: node.attrs,\n };\n // search for the node in the blockSpec or inlineContentSpecs\n const spec =\n schema.blockSpecs[nodeShape.type] ||\n schema.inlineContentSpecs[nodeShape.type];\n\n return spec?.implementation?.meta?.highlight?.(nodeShape) ?? undefined;\n },\n nodeTypes,\n });\n}\n\n// If a light and dark theme is added to the highlighter, this function specifies them in\n// `createParser`. This lets us use `--shiki-light` and `--shiki-dark` CSS variables for correct\n// styling for both light & dark editor themes.\nfunction pickThemeOptions(highlighter: HighlighterGeneric<any, any>) {\n const themes = highlighter.getLoadedThemes();\n const light = themes.find((t) => /light/i.test(t));\n const dark = themes.find((t) => /dark/i.test(t));\n\n if (light && dark) {\n return { themes: { light, dark }, defaultColor: false as const };\n }\n\n return undefined;\n}\n","import type { HighlighterGeneric } from \"@shikijs/types\";\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { lazyShikiPlugin } from \"./shiki.js\";\nimport {\n CustomInlineContentConfig,\n InlineContentSpec,\n LooseBlockSpec,\n} from \"../../schema/index.js\";\n\nexport type SyntaxHighlightingOptions = {\n /**\n * Creates the Shiki highlighter used for syntax highlighting. Can be\n * asynchronous, so the highlighter is only loaded once it's first needed.\n *\n * When omitted, content renders without syntax highlighting.\n */\n createHighlighter: () => Promise<HighlighterGeneric<any, any>>;\n};\n\n/**\n * Collects the node type names that should be syntax-highlighted from a schema's\n * block and inline-content specs.\n *\n * A spec is a candidate when it has a `meta.highlight` callback (which decides\n * the language) AND the node actually holds editable text. Block and\n * inline-content specs use different `content` value spaces, so \"editable text\"\n * means `content === \"plain\"` for both blocks (code/math blocks) and inline\n * content (inline math) - both hold plain text - hence the two are filtered\n * separately.\n *\n * Inline content (e.g. inline math) is highlighted too: `prosemirror-highlight`\n * collects nodes by `node.inlineContent` since v0.15.3\n * (https://github.com/ocavue/prosemirror-highlight/pull/137), so inline nodes\n * holding inline content are visited alongside text blocks.\n */\nexport function collectHighlightNodeTypes(schema: {\n blockSpecs: Record<string, unknown>;\n inlineContentSpecs: Record<string, unknown>;\n}): string[] {\n const blockNodeTypes = Object.values(schema.blockSpecs)\n .filter(\n (blockSpec): blockSpec is LooseBlockSpec =>\n typeof (blockSpec as LooseBlockSpec)?.config === \"object\" &&\n (blockSpec as LooseBlockSpec).config.content === \"plain\" &&\n !!(blockSpec as LooseBlockSpec).implementation?.meta?.highlight,\n )\n .map((blockSpec) => blockSpec.config.type);\n\n const inlineContentNodeTypes = Object.values(schema.inlineContentSpecs)\n .filter(\n (\n inlineContentSpec,\n ): inlineContentSpec is InlineContentSpec<CustomInlineContentConfig> =>\n typeof (\n inlineContentSpec as InlineContentSpec<CustomInlineContentConfig>\n )?.config === \"object\" &&\n (inlineContentSpec as InlineContentSpec<CustomInlineContentConfig>)\n .config.content === \"plain\" &&\n !!(inlineContentSpec as InlineContentSpec<CustomInlineContentConfig>)\n .implementation?.meta?.highlight,\n )\n .map((inlineContentSpec) => inlineContentSpec.config.type);\n\n return [...blockNodeTypes, ...inlineContentNodeTypes];\n}\n\n/**\n * A single editor-wide extension that syntax-highlights block and inline-content\n * content. Which nodes get highlighted (and as which language) is decided by\n * each spec's `meta.highlight` callback, so individual specs declare their own\n * language rather than the extension configuring them.\n *\n * Highlighting is opt-in: the user adds this extension to the editor's\n * `extensions` (configured with a `createHighlighter`) to enable it. When it's\n * absent, content renders as plain text.\n */\nexport const SyntaxHighlightingExtension = createExtension(\n ({ editor, options }: ExtensionOptions<SyntaxHighlightingOptions>) => {\n const nodeTypes = collectHighlightNodeTypes(editor.schema);\n\n return {\n key: \"syntaxHighlighting\",\n prosemirrorPlugins: [lazyShikiPlugin(options, nodeTypes, editor.schema)],\n };\n },\n);\n","import type { Emoji, EmojiMartData } from \"@emoji-mart/data\";\n\nimport { defaultInlineContentSchema } from \"../../blocks/defaultBlocks.js\";\nimport { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\nimport { DefaultGridSuggestionItem } from \"./DefaultGridSuggestionItem.js\";\n\n// Temporary fix for https://github.com/missive/emoji-mart/pull/929\nlet emojiLoadingPromise:\n | Promise<{\n emojiMart: typeof import(\"emoji-mart\");\n emojiData: EmojiMartData;\n }>\n | undefined;\n\nasync function loadEmojiMart() {\n if (emojiLoadingPromise) {\n return emojiLoadingPromise;\n }\n\n emojiLoadingPromise = (async () => {\n // load dynamically because emoji-mart doesn't specify type: module and breaks in nodejs\n const [emojiMartModule, emojiDataModule] = await Promise.all([\n import(\"emoji-mart\"),\n // use a dynamic import to encourage bundle-splitting\n // and a smaller initial client bundle size\n import(\"@emoji-mart/data\"),\n ]);\n\n const emojiMart =\n \"default\" in emojiMartModule ? emojiMartModule.default : emojiMartModule;\n const emojiData =\n \"default\" in emojiDataModule\n ? (emojiDataModule.default as EmojiMartData)\n : (emojiDataModule as EmojiMartData);\n\n await emojiMart.init({ data: emojiData });\n\n return { emojiMart, emojiData };\n })();\n\n return emojiLoadingPromise;\n}\n\nexport async function getDefaultEmojiPickerItems<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, I, S>,\n query: string,\n): Promise<DefaultGridSuggestionItem[]> {\n if (\n !(\"text\" in editor.schema.inlineContentSchema) ||\n editor.schema.inlineContentSchema[\"text\"] !==\n defaultInlineContentSchema[\"text\"]\n ) {\n return [];\n }\n\n const { emojiData, emojiMart } = await loadEmojiMart();\n\n const emojisToShow =\n query.trim() === \"\"\n ? Object.values(emojiData.emojis)\n : ((await emojiMart!.SearchIndex.search(query)) as Emoji[]);\n\n return emojisToShow.map((emoji) => ({\n id: emoji.skins[0].native,\n onItemClick: () => editor.insertInlineContent(emoji.skins[0].native + \" \"),\n }));\n}\n","import type { Node } from \"prosemirror-model\";\nimport { EditorState, Plugin, PluginKey, PluginView } from \"prosemirror-state\";\nimport {\n CellSelection,\n addColumnAfter,\n addColumnBefore,\n addRowAfter,\n addRowBefore,\n deleteColumn,\n deleteRow,\n mergeCells,\n splitCell,\n} from \"prosemirror-tables\";\nimport { Decoration, DecorationSet, EditorView } from \"prosemirror-view\";\nimport {\n RelativeCellIndices,\n addRowsOrColumns,\n areInSameColumn,\n canColumnBeDraggedInto,\n canRowBeDraggedInto,\n cropEmptyRowsOrColumns,\n getCellsAtColumnHandle,\n getCellsAtRowHandle,\n getDimensionsOfTable,\n moveColumn,\n moveRow,\n} from \"../../api/blockManipulation/tables/tables.js\";\nimport { nodeToBlock } from \"../../api/nodeConversions/nodeToBlock.js\";\nimport { getNodeById } from \"../../api/nodeUtil.js\";\nimport {\n blockHasType,\n isTableCellNode,\n isTableCellSelection,\n} from \"../../blocks/defaultBlockTypeGuards.js\";\nimport { DefaultBlockSchema } from \"../../blocks/defaultBlocks.js\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport {\n createExtension,\n createStore,\n} from \"../../editor/BlockNoteExtension.js\";\nimport {\n BlockFromConfigNoChildren,\n BlockSchemaWithBlock,\n} from \"../../schema/index.js\";\nimport { getDraggableBlockFromElement } from \"../getDraggableBlockFromElement.js\";\n\nlet dragImageElement: HTMLElement | undefined;\n\n// TODO consider switching this to jotai, it is a bit messy and noisy\nexport type TableHandlesState = {\n show: boolean;\n showAddOrRemoveRowsButton: boolean;\n showAddOrRemoveColumnsButton: boolean;\n referencePosCell: DOMRect | undefined;\n referencePosTable: DOMRect;\n\n block: BlockFromConfigNoChildren<DefaultBlockSchema[\"table\"], any, any>;\n colIndex: number | undefined;\n rowIndex: number | undefined;\n\n draggingState:\n | {\n draggedCellOrientation: \"row\" | \"col\";\n originalIndex: number;\n mousePos: number;\n }\n | undefined;\n\n widgetContainer: HTMLElement | undefined;\n};\n\nfunction setHiddenDragImage(rootEl: Document | ShadowRoot) {\n if (dragImageElement) {\n return;\n }\n\n dragImageElement = document.createElement(\"div\");\n dragImageElement.innerHTML = \"_\";\n dragImageElement.style.opacity = \"0\";\n dragImageElement.style.height = \"1px\";\n dragImageElement.style.width = \"1px\";\n if (rootEl instanceof Document) {\n rootEl.body.appendChild(dragImageElement);\n } else {\n rootEl.appendChild(dragImageElement);\n }\n}\n\nfunction unsetHiddenDragImage(rootEl: Document | ShadowRoot) {\n if (dragImageElement) {\n if (rootEl instanceof Document) {\n rootEl.body.removeChild(dragImageElement);\n } else {\n rootEl.removeChild(dragImageElement);\n }\n dragImageElement = undefined;\n }\n}\n\nfunction getChildIndex(node: Element) {\n return Array.prototype.indexOf.call(node.parentElement!.childNodes, node);\n}\n\n// Finds the DOM element corresponding to the table cell that the target element\n// is currently in. If the target element is not in a table cell, returns null.\nfunction domCellAround(target: Element) {\n let currentTarget: Element | undefined = target;\n while (\n currentTarget &&\n currentTarget.nodeName !== \"TD\" &&\n currentTarget.nodeName !== \"TH\" &&\n !currentTarget.classList.contains(\"tableWrapper\")\n ) {\n if (currentTarget.classList.contains(\"ProseMirror\")) {\n return undefined;\n }\n const parent: ParentNode | null = currentTarget.parentNode;\n\n if (!parent || !(parent instanceof Element)) {\n return undefined;\n }\n currentTarget = parent;\n }\n\n return currentTarget.nodeName === \"TD\" || currentTarget.nodeName === \"TH\"\n ? {\n type: \"cell\",\n domNode: currentTarget,\n tbodyNode: currentTarget.closest(\"tbody\"),\n }\n : {\n type: \"wrapper\",\n domNode: currentTarget,\n tbodyNode: currentTarget.querySelector(\"tbody\"),\n };\n}\n\n// Hides elements in the DOMwith the provided class names.\nfunction hideElements(selector: string, rootEl: Document | ShadowRoot) {\n const elementsToHide = rootEl.querySelectorAll(selector);\n\n for (let i = 0; i < elementsToHide.length; i++) {\n (elementsToHide[i] as HTMLElement).style.visibility = \"hidden\";\n }\n}\n\nexport class TableHandlesView implements PluginView {\n public state?: TableHandlesState;\n public emitUpdate: () => void;\n\n public tableId: string | undefined;\n public tablePos: number | undefined;\n public tableElement: HTMLElement | undefined;\n\n public menuFrozen = false;\n\n public mouseState: \"up\" | \"down\" | \"selecting\" = \"up\";\n\n public prevWasEditable: boolean | null = null;\n\n constructor(\n private readonly editor: BlockNoteEditor<\n BlockSchemaWithBlock<\"table\", DefaultBlockSchema[\"table\"]>,\n any,\n any\n >,\n private readonly pmView: EditorView,\n emitUpdate: (state: TableHandlesState | undefined) => void,\n ) {\n this.emitUpdate = () => {\n emitUpdate(this.state);\n };\n\n pmView.dom.addEventListener(\"mousemove\", this.mouseMoveHandler);\n pmView.dom.addEventListener(\"mousedown\", this.viewMousedownHandler);\n window.addEventListener(\"mouseup\", this.mouseUpHandler);\n\n pmView.root.addEventListener(\n \"dragover\",\n this.dragOverHandler as EventListener,\n );\n pmView.root.addEventListener(\n \"drop\",\n this.dropHandler as unknown as EventListener,\n );\n }\n\n viewMousedownHandler = () => {\n this.mouseState = \"down\";\n };\n\n // Hides the handles if they're currently shown. Used whenever the mouse moves\n // somewhere that shouldn't have table handles attached to it.\n hideHandles = () => {\n if (this.state?.show) {\n this.state.show = false;\n this.state.showAddOrRemoveRowsButton = false;\n this.state.showAddOrRemoveColumnsButton = false;\n this.emitUpdate();\n }\n };\n\n mouseUpHandler = (event: MouseEvent) => {\n this.mouseState = \"up\";\n this.mouseMoveHandler(event);\n };\n\n mouseMoveHandler = (event: MouseEvent) => {\n if (this.menuFrozen) {\n return;\n }\n\n if (this.mouseState === \"selecting\") {\n return;\n }\n\n if (\n !(event.target instanceof Element) ||\n !this.pmView.dom.contains(event.target)\n ) {\n return;\n }\n\n const target = domCellAround(event.target);\n\n if (\n target?.type === \"cell\" &&\n this.mouseState === \"down\" &&\n !this.state?.draggingState\n ) {\n // hide draghandles when selecting text as they could be in the way of the user\n this.mouseState = \"selecting\";\n\n this.hideHandles();\n return;\n }\n\n if (!target || !this.editor.isEditable) {\n this.hideHandles();\n return;\n }\n\n if (!target.tbodyNode) {\n return;\n }\n\n const tableRect = target.tbodyNode.getBoundingClientRect();\n\n const blockEl = getDraggableBlockFromElement(target.domNode, this.pmView);\n if (!blockEl) {\n return;\n }\n\n const { pmNodeInfo, doc } = this.editor.transact((tr) => ({\n pmNodeInfo: getNodeById(blockEl.id, tr.doc),\n doc: tr.doc,\n }));\n\n // The hovered cell may belong to a document other than this editor's, as a\n // custom block can embed a nested editor which itself contains a table. The\n // nested editor's DOM is inside this view's DOM, so its cells still reach\n // this handler, but its block IDs are unknown here.\n if (!pmNodeInfo) {\n this.hideHandles();\n return;\n }\n\n const block = nodeToBlock(pmNodeInfo.node, doc);\n\n // `domCellAround` matches any `TD`/`TH` in the DOM, so the hovered block may\n // just as well be a custom block that renders a table of its own. Checking\n // the block itself (rather than only whether the schema has a table block)\n // keeps the handles off blocks that have no table content to work with.\n if (!blockHasType(block, this.editor, \"table\")) {\n this.hideHandles();\n return;\n }\n\n const tableBlock = block as unknown as BlockFromConfigNoChildren<\n DefaultBlockSchema[\"table\"],\n any,\n any\n >;\n\n this.tablePos = pmNodeInfo.posBeforeNode + 1;\n this.tableElement = blockEl.node;\n this.tableId = blockEl.id;\n const widgetContainer = target.domNode\n .closest(\".tableWrapper\")\n ?.querySelector(\".table-widgets-container\") as HTMLElement;\n\n if (target?.type === \"wrapper\") {\n // if we're just to the right or below the table, show the extend buttons\n // (this is a bit hacky. It would probably be cleaner to render the extend buttons in the Table NodeView instead)\n const belowTable =\n event.clientY >= tableRect.bottom - 1 && // -1 to account for fractions of pixels in \"bottom\"\n event.clientY < tableRect.bottom + 20;\n const toRightOfTable =\n event.clientX >= tableRect.right - 1 &&\n event.clientX < tableRect.right + 20;\n\n const hideHandles =\n // always hide handles when the actively hovered table changed\n this.state?.block?.id !== tableBlock.id ||\n // make sure we don't hide existing handles (keep col / row index) when\n // we're hovering just above or to the right of a table\n event.clientX > tableRect.right ||\n event.clientY > tableRect.bottom;\n\n this.state = {\n ...this.state!,\n show: true,\n showAddOrRemoveRowsButton: belowTable,\n showAddOrRemoveColumnsButton: toRightOfTable,\n referencePosTable: tableRect,\n block: tableBlock,\n widgetContainer,\n colIndex: hideHandles ? undefined : this.state?.colIndex,\n rowIndex: hideHandles ? undefined : this.state?.rowIndex,\n referencePosCell: hideHandles\n ? undefined\n : this.state?.referencePosCell,\n };\n } else {\n const colIndex = getChildIndex(target.domNode);\n const rowIndex = getChildIndex(target.domNode.parentElement!);\n const cellRect = target.domNode.getBoundingClientRect();\n\n if (\n this.state !== undefined &&\n this.state.show &&\n this.tableId === blockEl.id &&\n this.state.rowIndex === rowIndex &&\n this.state.colIndex === colIndex\n ) {\n // no update needed\n return;\n }\n\n this.state = {\n show: true,\n showAddOrRemoveColumnsButton:\n colIndex === tableBlock.content.rows[0].cells.length - 1,\n showAddOrRemoveRowsButton:\n rowIndex === tableBlock.content.rows.length - 1,\n referencePosTable: tableRect,\n\n block: tableBlock,\n draggingState: undefined,\n referencePosCell: cellRect,\n colIndex: colIndex,\n rowIndex: rowIndex,\n\n widgetContainer,\n };\n }\n this.emitUpdate();\n\n return false;\n };\n\n dragOverHandler = (event: DragEvent) => {\n if (this.state?.draggingState === undefined) {\n return;\n }\n\n event.preventDefault();\n event.dataTransfer!.dropEffect = \"move\";\n\n hideElements(\n \".prosemirror-dropcursor-block, .prosemirror-dropcursor-inline\",\n this.pmView.root,\n );\n\n // The mouse cursor coordinates, bounded to the table's bounding box. The\n // bounding box is shrunk by 1px on each side to ensure that the bounded\n // coordinates are always inside a table cell.\n const boundedMouseCoords = {\n left: Math.min(\n Math.max(event.clientX, this.state.referencePosTable.left + 1),\n this.state.referencePosTable.right - 1,\n ),\n top: Math.min(\n Math.max(event.clientY, this.state.referencePosTable.top + 1),\n this.state.referencePosTable.bottom - 1,\n ),\n };\n\n // Gets the table cell element that the bounded mouse cursor coordinates lie\n // in.\n const tableCellElements = this.pmView.root\n .elementsFromPoint(boundedMouseCoords.left, boundedMouseCoords.top)\n .filter(\n (element) => element.tagName === \"TD\" || element.tagName === \"TH\",\n );\n if (tableCellElements.length === 0) {\n return;\n }\n const tableCellElement = tableCellElements[0];\n\n let emitStateUpdate = false;\n\n // Gets current row and column index.\n const rowIndex = getChildIndex(tableCellElement.parentElement!);\n const colIndex = getChildIndex(tableCellElement);\n\n // Checks if the drop cursor needs to be updated. This affects decorations\n // only so it doesn't trigger a state update.\n const oldIndex =\n this.state.draggingState.draggedCellOrientation === \"row\"\n ? this.state.rowIndex\n : this.state.colIndex;\n const newIndex =\n this.state.draggingState.draggedCellOrientation === \"row\"\n ? rowIndex\n : colIndex;\n const dispatchDecorationsTransaction = newIndex !== oldIndex;\n\n // Checks if either the hovered cell has changed and updates the row and\n // column index. Also updates the reference DOMRect.\n if (this.state.rowIndex !== rowIndex || this.state.colIndex !== colIndex) {\n this.state.rowIndex = rowIndex;\n this.state.colIndex = colIndex;\n\n this.state.referencePosCell = tableCellElement.getBoundingClientRect();\n\n emitStateUpdate = true;\n }\n\n // Checks if the mouse cursor position along the axis that the user is\n // dragging on has changed and updates it.\n const mousePos =\n this.state.draggingState.draggedCellOrientation === \"row\"\n ? boundedMouseCoords.top\n : boundedMouseCoords.left;\n if (this.state.draggingState.mousePos !== mousePos) {\n this.state.draggingState.mousePos = mousePos;\n\n emitStateUpdate = true;\n }\n\n // Emits a state update if any of the fields have changed.\n if (emitStateUpdate) {\n this.emitUpdate();\n }\n\n // Dispatches a dummy transaction to force a decorations update if\n // necessary.\n if (dispatchDecorationsTransaction) {\n this.editor.transact((tr) => tr.setMeta(tableHandlesPluginKey, true));\n }\n };\n\n dropHandler = (event: DragEvent) => {\n this.mouseState = \"up\";\n if (this.state === undefined || this.state.draggingState === undefined) {\n return false;\n }\n\n if (\n this.state.rowIndex === undefined ||\n this.state.colIndex === undefined\n ) {\n throw new Error(\n \"Attempted to drop table row or column, but no table block was hovered prior.\",\n );\n }\n\n event.preventDefault();\n\n const { draggingState, colIndex, rowIndex } = this.state;\n // Clear so a re-dispatched drop short-circuits above (issue #2691).\n this.state.draggingState = undefined;\n\n const columnWidths = this.state.block.content.columnWidths;\n\n if (draggingState.draggedCellOrientation === \"row\") {\n if (\n !canRowBeDraggedInto(\n this.state.block,\n draggingState.originalIndex,\n rowIndex,\n )\n ) {\n // If the target row is invalid, don't move the row\n return false;\n }\n const newTable = moveRow(\n this.state.block,\n draggingState.originalIndex,\n rowIndex,\n );\n this.editor.updateBlock(this.state.block, {\n type: \"table\",\n content: {\n ...this.state.block.content,\n rows: newTable as any,\n },\n });\n } else {\n if (\n !canColumnBeDraggedInto(\n this.state.block,\n draggingState.originalIndex,\n colIndex,\n )\n ) {\n // If the target column is invalid, don't move the column\n return false;\n }\n const newTable = moveColumn(\n this.state.block,\n draggingState.originalIndex,\n colIndex,\n );\n const [columnWidth] = columnWidths.splice(draggingState.originalIndex, 1);\n columnWidths.splice(colIndex, 0, columnWidth);\n this.editor.updateBlock(this.state.block, {\n type: \"table\",\n content: {\n ...this.state.block.content,\n columnWidths,\n rows: newTable as any,\n },\n });\n }\n\n // Have to reset text cursor position to the block as `updateBlock` moves\n // the existing selection out of the block.\n this.editor.setTextCursorPosition(this.state.block.id);\n\n return true;\n };\n\n // Resolves the position just inside the hovered table, within `doc`. The\n // position is looked up by ID on each use rather than read from a cached one,\n // as anything changing before the table (a collaborator inserting a block\n // above it, say) shifts it: a stale position resolves into the wrong node, or\n // past the end of the document entirely.\n getTablePos(doc: Node): number | undefined {\n if (this.tableId === undefined) {\n return undefined;\n }\n\n const pmNodeInfo = getNodeById(this.tableId, doc);\n\n return pmNodeInfo && pmNodeInfo.posBeforeNode + 1;\n }\n\n // Updates drag handles when the table is modified or removed.\n update() {\n if (!this.state || !this.state.show) {\n return;\n }\n\n // Hide handles if the table block has been removed.\n const refreshedBlock = this.editor.getBlock(this.state.block.id);\n if (\n !refreshedBlock ||\n refreshedBlock.type !== \"table\" ||\n // when collaborating, the table element might be replaced and out of date\n // because yjs replaces the element when for example you change the color via the side menu\n !this.tableElement?.isConnected\n ) {\n this.state = undefined;\n this.tableId = undefined;\n this.tablePos = undefined;\n this.tableElement = undefined;\n this.emitUpdate();\n\n return;\n }\n this.state.block = refreshedBlock as typeof this.state.block;\n\n // The table may have shifted in this update, so re-resolve its position.\n this.tablePos = this.getTablePos(this.pmView.state.doc);\n\n const { height: rowCount, width: colCount } = getDimensionsOfTable(\n this.state.block,\n );\n\n if (\n this.state.rowIndex !== undefined &&\n this.state.colIndex !== undefined\n ) {\n // If rows or columns are deleted in the update, the hovered indices for\n // those may now be out of bounds. If this is the case, they are moved to\n // the new last row or column.\n if (this.state.rowIndex >= rowCount) {\n this.state.rowIndex = rowCount - 1;\n }\n if (this.state.colIndex >= colCount) {\n this.state.colIndex = colCount - 1;\n }\n }\n\n // Update bounding boxes.\n const tableBody = this.tableElement!.querySelector(\"tbody\");\n\n if (!tableBody) {\n throw new Error(\n \"Table block does not contain a 'tbody' HTML element. This should never happen.\",\n );\n }\n\n if (\n this.state.rowIndex !== undefined &&\n this.state.colIndex !== undefined\n ) {\n const row = tableBody.children[this.state.rowIndex];\n const cell = row.children[this.state.colIndex];\n if (cell) {\n this.state.referencePosCell = cell.getBoundingClientRect();\n } else {\n this.state.rowIndex = undefined;\n this.state.colIndex = undefined;\n }\n }\n this.state.referencePosTable = tableBody.getBoundingClientRect();\n\n this.emitUpdate();\n }\n\n destroy() {\n this.pmView.dom.removeEventListener(\"mousemove\", this.mouseMoveHandler);\n window.removeEventListener(\"mouseup\", this.mouseUpHandler);\n this.pmView.dom.removeEventListener(\"mousedown\", this.viewMousedownHandler);\n this.pmView.root.removeEventListener(\n \"dragover\",\n this.dragOverHandler as EventListener,\n );\n this.pmView.root.removeEventListener(\n \"drop\",\n this.dropHandler as unknown as EventListener,\n );\n }\n}\n\nexport const tableHandlesPluginKey = new PluginKey(\"TableHandlesPlugin\");\n\nexport const TableHandlesExtension = createExtension(({ editor }) => {\n let view: TableHandlesView | undefined = undefined;\n\n const store = createStore<TableHandlesState | undefined>(undefined);\n\n return {\n key: \"tableHandles\",\n store,\n prosemirrorPlugins: [\n new Plugin({\n key: tableHandlesPluginKey,\n view: (editorView) => {\n view = new TableHandlesView(editor as any, editorView, (state) => {\n store.setState(\n state?.block\n ? {\n ...state,\n draggingState: state.draggingState\n ? { ...state.draggingState }\n : undefined,\n }\n : undefined,\n );\n });\n return view;\n },\n // We use decorations to render the drop cursor when dragging a table row\n // or column. The decorations are updated in the `dragOverHandler` method.\n props: {\n decorations: (state) => {\n if (\n view === undefined ||\n view.state === undefined ||\n view.state.draggingState === undefined\n ) {\n return;\n }\n\n // Resolved against the state being rendered rather than read from\n // `view.tablePos`, as ProseMirror computes decorations for a\n // transaction before it calls the plugin view's `update` - so the\n // cached position is still the pre-transaction one here.\n const tablePos = view.getTablePos(state.doc);\n\n if (tablePos === undefined) {\n return;\n }\n\n const newIndex =\n view.state.draggingState.draggedCellOrientation === \"row\"\n ? view.state.rowIndex\n : view.state.colIndex;\n\n if (newIndex === undefined) {\n return;\n }\n\n const decorations: Decoration[] = [];\n const { block, draggingState } = view.state;\n const { originalIndex, draggedCellOrientation } = draggingState;\n\n // Return empty decorations if:\n // - Dragging to same position\n // - No block exists\n // - Row drag not allowed\n // - Column drag not allowed\n if (\n newIndex === originalIndex ||\n !block ||\n (draggedCellOrientation === \"row\" &&\n !canRowBeDraggedInto(block, originalIndex, newIndex)) ||\n (draggedCellOrientation === \"col\" &&\n !canColumnBeDraggedInto(block, originalIndex, newIndex))\n ) {\n return DecorationSet.create(state.doc, decorations);\n }\n\n // Gets the table to show the drop cursor in.\n const tableResolvedPos = state.doc.resolve(tablePos + 1);\n\n if (view.state.draggingState.draggedCellOrientation === \"row\") {\n const cellsInRow = getCellsAtRowHandle(\n view.state.block,\n newIndex,\n );\n\n cellsInRow.forEach(({ row, col }) => {\n // Gets each row in the table.\n const rowResolvedPos = state.doc.resolve(\n tableResolvedPos.posAtIndex(row) + 1,\n );\n\n // Gets the cell within the row.\n const cellResolvedPos = state.doc.resolve(\n rowResolvedPos.posAtIndex(col) + 1,\n );\n const cellNode = cellResolvedPos.node();\n // Creates a decoration at the start or end of each cell,\n // depending on whether the new index is before or after the\n // original index.\n const decorationPos =\n cellResolvedPos.pos +\n (newIndex > originalIndex ? cellNode.nodeSize - 2 : 0);\n decorations.push(\n // The widget is a small bar which spans the width of the cell.\n Decoration.widget(decorationPos, () => {\n const widget = document.createElement(\"div\");\n widget.className = \"bn-table-drop-cursor\";\n widget.style.left = \"0\";\n widget.style.right = \"0\";\n // This is only necessary because the drop indicator's height\n // is an even number of pixels, whereas the border between\n // table cells is an odd number of pixels. So this makes the\n // positioning slightly more consistent regardless of where\n // the row is being dropped.\n if (newIndex > originalIndex) {\n widget.style.bottom = \"-2px\";\n } else {\n widget.style.top = \"-3px\";\n }\n widget.style.height = \"4px\";\n\n return widget;\n }),\n );\n });\n } else {\n const cellsInColumn = getCellsAtColumnHandle(\n view.state.block,\n newIndex,\n );\n\n cellsInColumn.forEach(({ row, col }) => {\n // Gets each row in the table.\n const rowResolvedPos = state.doc.resolve(\n tableResolvedPos.posAtIndex(row) + 1,\n );\n\n // Gets the cell within the row.\n const cellResolvedPos = state.doc.resolve(\n rowResolvedPos.posAtIndex(col) + 1,\n );\n const cellNode = cellResolvedPos.node();\n\n // Creates a decoration at the start or end of each cell,\n // depending on whether the new index is before or after the\n // original index.\n const decorationPos =\n cellResolvedPos.pos +\n (newIndex > originalIndex ? cellNode.nodeSize - 2 : 0);\n\n decorations.push(\n // The widget is a small bar which spans the height of the cell.\n Decoration.widget(decorationPos, () => {\n const widget = document.createElement(\"div\");\n widget.className = \"bn-table-drop-cursor\";\n widget.style.top = \"0\";\n widget.style.bottom = \"0\";\n // This is only necessary because the drop indicator's width\n // is an even number of pixels, whereas the border between\n // table cells is an odd number of pixels. So this makes the\n // positioning slightly more consistent regardless of where\n // the column is being dropped.\n if (newIndex > originalIndex) {\n widget.style.right = \"-2px\";\n } else {\n widget.style.left = \"-3px\";\n }\n widget.style.width = \"4px\";\n\n return widget;\n }),\n );\n });\n }\n\n return DecorationSet.create(state.doc, decorations);\n },\n },\n }),\n ],\n\n /**\n * Callback that should be set on the `dragStart` event for whichever element\n * is used as the column drag handle.\n */\n colDragStart(event: {\n dataTransfer: DataTransfer | null;\n clientX: number;\n }) {\n if (\n view === undefined ||\n view.state === undefined ||\n view.state.colIndex === undefined\n ) {\n throw new Error(\n \"Attempted to drag table column, but no table block was hovered prior.\",\n );\n }\n\n view.state.draggingState = {\n draggedCellOrientation: \"col\",\n originalIndex: view.state.colIndex,\n mousePos: event.clientX,\n };\n view.emitUpdate();\n\n editor.transact((tr) =>\n tr.setMeta(tableHandlesPluginKey, {\n draggedCellOrientation:\n view!.state!.draggingState!.draggedCellOrientation,\n originalIndex: view!.state!.colIndex,\n newIndex: view!.state!.colIndex,\n tablePos: view!.tablePos,\n }),\n );\n\n if (editor.headless) {\n return;\n }\n\n setHiddenDragImage(editor.prosemirrorView.root);\n event.dataTransfer!.setDragImage(dragImageElement!, 0, 0);\n event.dataTransfer!.effectAllowed = \"move\";\n },\n\n /**\n * Callback that should be set on the `dragStart` event for whichever element\n * is used as the row drag handle.\n */\n rowDragStart(event: {\n dataTransfer: DataTransfer | null;\n clientY: number;\n }) {\n if (view!.state === undefined || view!.state.rowIndex === undefined) {\n throw new Error(\n \"Attempted to drag table row, but no table block was hovered prior.\",\n );\n }\n\n view!.state.draggingState = {\n draggedCellOrientation: \"row\",\n originalIndex: view!.state.rowIndex,\n mousePos: event.clientY,\n };\n view!.emitUpdate();\n\n editor.transact((tr) =>\n tr.setMeta(tableHandlesPluginKey, {\n draggedCellOrientation:\n view!.state!.draggingState!.draggedCellOrientation,\n originalIndex: view!.state!.rowIndex,\n newIndex: view!.state!.rowIndex,\n tablePos: view!.tablePos,\n }),\n );\n\n if (editor.headless) {\n return;\n }\n\n setHiddenDragImage(editor.prosemirrorView.root);\n event.dataTransfer!.setDragImage(dragImageElement!, 0, 0);\n event.dataTransfer!.effectAllowed = \"copyMove\";\n },\n\n /**\n * Callback that should be set on the `dragEnd` event for both the element\n * used as the row drag handle, and the one used as the column drag handle.\n */\n dragEnd() {\n if (view!.state === undefined) {\n throw new Error(\n \"Attempted to drag table row, but no table block was hovered prior.\",\n );\n }\n\n view!.state.draggingState = undefined;\n view!.emitUpdate();\n\n editor.transact((tr) => tr.setMeta(tableHandlesPluginKey, null));\n\n if (editor.headless) {\n return;\n }\n\n unsetHiddenDragImage(editor.prosemirrorView.root);\n },\n\n /**\n * Freezes the drag handles. When frozen, they will stay attached to the same\n * cell regardless of which cell is hovered by the mouse cursor.\n */\n freezeHandles() {\n view!.menuFrozen = true;\n },\n\n /**\n * Unfreezes the drag handles. When frozen, they will stay attached to the\n * same cell regardless of which cell is hovered by the mouse cursor.\n */\n unfreezeHandles() {\n view!.menuFrozen = false;\n },\n\n /**\n * Hides the table handles unless they are currently frozen (e.g. a\n * handle menu is open). Used to dismiss the handles on scroll without\n * interfering with open submenus.\n */\n hideHandlesIfNotFrozen() {\n if (!view!.menuFrozen) {\n view!.hideHandles();\n }\n },\n\n getCellsAtRowHandle(\n block: BlockFromConfigNoChildren<DefaultBlockSchema[\"table\"], any, any>,\n relativeRowIndex: RelativeCellIndices[\"row\"],\n ) {\n return getCellsAtRowHandle(block, relativeRowIndex);\n },\n\n /**\n * Get all the cells in a column of the table block.\n */\n getCellsAtColumnHandle(\n block: BlockFromConfigNoChildren<DefaultBlockSchema[\"table\"], any, any>,\n relativeColumnIndex: RelativeCellIndices[\"col\"],\n ) {\n return getCellsAtColumnHandle(block, relativeColumnIndex);\n },\n\n /**\n * Sets the selection to the given cell or a range of cells.\n * @returns The new state after the selection has been set.\n */\n setCellSelection(\n state: EditorState,\n relativeStartCell: RelativeCellIndices,\n relativeEndCell: RelativeCellIndices = relativeStartCell,\n ) {\n if (!view) {\n throw new Error(\"Table handles view not initialized\");\n }\n\n // Resolved against `state`, which may be several transactions ahead of\n // the mouse move that attached the handles (a menu can stay open across\n // edits from elsewhere, e.g. a collaborator).\n const tablePos = view.getTablePos(state.doc);\n\n if (tablePos === undefined) {\n throw new Error(\n \"Attempted to select table cells, but the hovered table is no longer in the document.\",\n );\n }\n\n const tableResolvedPos = state.doc.resolve(tablePos + 1);\n const startRowResolvedPos = state.doc.resolve(\n tableResolvedPos.posAtIndex(relativeStartCell.row) + 1,\n );\n const startCellResolvedPos = state.doc.resolve(\n // No need for +1, since CellSelection expects the position before the cell\n startRowResolvedPos.posAtIndex(relativeStartCell.col),\n );\n const endRowResolvedPos = state.doc.resolve(\n tableResolvedPos.posAtIndex(relativeEndCell.row) + 1,\n );\n const endCellResolvedPos = state.doc.resolve(\n // No need for +1, since CellSelection expects the position before the cell\n endRowResolvedPos.posAtIndex(relativeEndCell.col),\n );\n\n // Begin a new transaction to set the selection\n const tr = state.tr;\n\n // Set the selection to the given cell or a range of cells\n tr.setSelection(\n new CellSelection(startCellResolvedPos, endCellResolvedPos),\n );\n\n // Quickly apply the transaction to get the new state to update the selection before splitting the cell\n return state.apply(tr);\n },\n\n /**\n * Adds a row or column to the table using prosemirror-table commands\n */\n addRowOrColumn(\n index: RelativeCellIndices[\"row\"],\n direction:\n | { orientation: \"row\"; side: \"above\" | \"below\" }\n | { orientation: \"column\"; side: \"left\" | \"right\" },\n ) {\n editor.exec((beforeState, dispatch) => {\n const state = this.setCellSelection(\n beforeState,\n direction.orientation === \"row\"\n ? { row: index, col: 0 }\n : { row: 0, col: index },\n );\n\n if (direction.orientation === \"row\") {\n if (direction.side === \"above\") {\n return addRowBefore(state, dispatch);\n } else {\n return addRowAfter(state, dispatch);\n }\n } else {\n if (direction.side === \"left\") {\n return addColumnBefore(state, dispatch);\n } else {\n return addColumnAfter(state, dispatch);\n }\n }\n });\n },\n\n /**\n * Removes a row or column from the table using prosemirror-table commands\n */\n removeRowOrColumn(\n index: RelativeCellIndices[\"row\"],\n direction: \"row\" | \"column\",\n ) {\n if (direction === \"row\") {\n return editor.exec((beforeState, dispatch) => {\n const state = this.setCellSelection(beforeState, {\n row: index,\n col: 0,\n });\n return deleteRow(state, dispatch);\n });\n } else {\n return editor.exec((beforeState, dispatch) => {\n const state = this.setCellSelection(beforeState, {\n row: 0,\n col: index,\n });\n return deleteColumn(state, dispatch);\n });\n }\n },\n\n /**\n * Merges the cells in the table block.\n */\n mergeCells(cellsToMerge?: {\n relativeStartCell: RelativeCellIndices;\n relativeEndCell: RelativeCellIndices;\n }) {\n return editor.exec((beforeState, dispatch) => {\n const state = cellsToMerge\n ? this.setCellSelection(\n beforeState,\n cellsToMerge.relativeStartCell,\n cellsToMerge.relativeEndCell,\n )\n : beforeState;\n\n return mergeCells(state, dispatch);\n });\n },\n\n /**\n * Splits the cell in the table block.\n * If no cell is provided, the current cell selected will be split.\n */\n splitCell(relativeCellToSplit?: RelativeCellIndices) {\n return editor.exec((beforeState, dispatch) => {\n const state = relativeCellToSplit\n ? this.setCellSelection(beforeState, relativeCellToSplit)\n : beforeState;\n\n return splitCell(state, dispatch);\n });\n },\n\n /**\n * Gets the start and end cells of the current cell selection.\n * @returns The start and end cells of the current cell selection.\n */\n getCellSelection():\n | undefined\n | {\n from: RelativeCellIndices;\n to: RelativeCellIndices;\n /**\n * All of the cells that are within the selected range.\n */\n cells: RelativeCellIndices[];\n } {\n // Based on the current selection, find the table cells that are within the selected range\n\n return editor.transact((tr) => {\n const selection = tr.selection;\n\n let $fromCell = selection.$from;\n let $toCell = selection.$to;\n if (isTableCellSelection(selection)) {\n // When the selection is a table cell selection, we can find the\n // from and to cells by iterating over the ranges in the selection\n const { ranges } = selection;\n ranges.forEach((range) => {\n $fromCell = range.$from.min($fromCell ?? range.$from);\n $toCell = range.$to.max($toCell ?? range.$to);\n });\n } else {\n // When the selection is a normal text selection\n // Assumes we are within a tableParagraph\n // And find the from and to cells by resolving the positions\n const fromCellPos =\n selection.$from.pos - selection.$from.parentOffset - 1;\n const toCellPos = selection.$to.pos - selection.$to.parentOffset - 1;\n\n // Opt-out when the selection is not pointing into cells. This happens when the selection\n // is at the start of the table's `blockContainer` node and therefore just before the\n // actual `table` node.\n if (fromCellPos < 0 || toCellPos < 0) {\n return undefined;\n }\n\n $fromCell = tr.doc.resolve(fromCellPos);\n $toCell = tr.doc.resolve(toCellPos);\n\n // Opt-out when the selection is not actually pointing into table\n // cells (e.g. a gap cursor next to a nested block).\n if (\n !isTableCellNode($fromCell.parent) ||\n !isTableCellNode($toCell.parent)\n ) {\n return undefined;\n }\n }\n\n // Find the row and table that the from and to cells are in\n const $fromRow = tr.doc.resolve(\n $fromCell.pos - $fromCell.parentOffset - 1,\n );\n const $toRow = tr.doc.resolve($toCell.pos - $toCell.parentOffset - 1);\n\n // Find the table\n const $table = tr.doc.resolve($fromRow.pos - $fromRow.parentOffset - 1);\n\n // Find the column and row indices of the from and to cells\n const fromColIndex = $fromCell.index($fromRow.depth);\n const fromRowIndex = $fromRow.index($table.depth);\n const toColIndex = $toCell.index($toRow.depth);\n const toRowIndex = $toRow.index($table.depth);\n\n const cells: RelativeCellIndices[] = [];\n for (let row = fromRowIndex; row <= toRowIndex; row++) {\n for (let col = fromColIndex; col <= toColIndex; col++) {\n cells.push({ row, col });\n }\n }\n\n return {\n from: {\n row: fromRowIndex,\n col: fromColIndex,\n },\n to: {\n row: toRowIndex,\n col: toColIndex,\n },\n cells,\n };\n });\n },\n\n /**\n * Gets the direction of the merge based on the current cell selection.\n *\n * Returns undefined when there is no cell selection, or the selection is not within a table.\n */\n getMergeDirection(\n block:\n | BlockFromConfigNoChildren<DefaultBlockSchema[\"table\"], any, any>\n | undefined,\n ) {\n return editor.transact((tr) => {\n const isSelectingTableCells = isTableCellSelection(tr.selection)\n ? tr.selection\n : undefined;\n\n if (\n !isSelectingTableCells ||\n !block ||\n // Only offer the merge button if there is more than one cell selected.\n isSelectingTableCells.ranges.length <= 1\n ) {\n return undefined;\n }\n\n const cellSelection = this.getCellSelection();\n\n if (!cellSelection) {\n return undefined;\n }\n\n if (areInSameColumn(cellSelection.from, cellSelection.to, block)) {\n return \"vertical\";\n }\n\n return \"horizontal\";\n });\n },\n\n cropEmptyRowsOrColumns(\n block: BlockFromConfigNoChildren<DefaultBlockSchema[\"table\"], any, any>,\n removeEmpty: \"columns\" | \"rows\",\n ) {\n return cropEmptyRowsOrColumns(block, removeEmpty);\n },\n\n addRowsOrColumns(\n block: BlockFromConfigNoChildren<DefaultBlockSchema[\"table\"], any, any>,\n addType: \"columns\" | \"rows\",\n numToAdd: number,\n ) {\n return addRowsOrColumns(block, addType, numToAdd);\n },\n } as const;\n});\n","import type { Node as PMNode } from \"prosemirror-model\";\nimport {\n Plugin,\n PluginKey,\n Selection,\n type Transaction,\n} from \"prosemirror-state\";\nimport { Decoration, DecorationSet } from \"prosemirror-view\";\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\n\nconst PLUGIN_KEY = new PluginKey<DecorationSet>(\"trailingNode\");\n\n// Skip the widget when the container already ends with an empty paragraph\n// block (since the user can just type into it).\nfunction containerNeedsTrailingWidget(container: PMNode): boolean {\n const lastBlock = container.lastChild;\n const lastContent = lastBlock?.firstChild;\n\n return !(\n lastBlock?.type.name === \"blockContainer\" &&\n lastContent?.type.name === \"paragraph\" &&\n lastContent.content.size === 0\n );\n}\n\n// Returns the position at the end of each container that should render a\n// trailing widget: the root blockGroup, and columns from the multi-column\n// package. Nested blockGroups (a block's children) are excluded, as they have\n// no empty space below them for a widget to occupy.\nfunction getTrailingWidgetPositions(doc: PMNode): number[] {\n // When the schema has no columns, the root blockGroup is the only possible\n // container, so traversing the doc to find others can be skipped.\n if (!doc.type.schema.nodes[\"column\"]) {\n const rootGroup = doc.lastChild;\n return rootGroup && containerNeedsTrailingWidget(rootGroup)\n ? [doc.content.size - 1]\n : [];\n }\n\n const positions: number[] = [];\n\n doc.descendants((node, pos, parent) => {\n if (node.isTextblock) {\n return false;\n }\n\n const isContainer =\n node.type.name === \"column\" ||\n (node.type.name === \"blockGroup\" && parent?.type.name === \"doc\");\n\n if (isContainer && containerNeedsTrailingWidget(node)) {\n positions.push(pos + node.nodeSize - 1);\n }\n\n return true;\n });\n\n return positions;\n}\n\n/**\n * Renders a fake trailing block as a widget decoration after the last block of\n * the document, as well as of any other container that blocks can be appended\n * to (e.g. columns). Clicking it inserts a real trailing block in the\n * container and moves the selection into it. This way the trailing block is\n * not part of the document content, so it doesn't appear when the editor is\n * read-only or when the content is exported.\n */\nexport const TrailingNodeExtension = createExtension(\n ({ editor }: ExtensionOptions) => {\n function createTrailingWidget(pos: number): Decoration {\n return Decoration.widget(\n pos,\n () => {\n const el = document.createElement(\"div\");\n el.className = \"bn-trailing-block\";\n el.contentEditable = \"false\";\n el.addEventListener(\"mousedown\", (event) => {\n // Stop ProseMirror from trying to place the selection somewhere\n // based on this click.\n event.preventDefault();\n\n const view = editor.prosemirrorView;\n if (!view) {\n return;\n }\n\n // The widget may have been remapped since it was created, so its\n // container is resolved from its current DOM position instead of\n // captured up front.\n const container = view.state.doc.resolve(\n view.posAtDOM(el, 0),\n ).parent;\n const lastBlockId = container.lastChild?.attrs[\"id\"];\n if (!lastBlockId) {\n return;\n }\n\n editor.transact((tr) => {\n const [insertedBlock] = editor.insertBlocks(\n [{ type: \"paragraph\" }],\n lastBlockId,\n \"after\",\n );\n editor.setTextCursorPosition(insertedBlock, \"start\");\n tr.scrollIntoView();\n });\n\n view.focus();\n });\n return el;\n },\n { side: 1 },\n );\n }\n\n // Maps the existing DecorationSet through the transaction, then diffs it\n // against the containers that should currently show a widget, only adding\n // and removing where the two differ. Decorations (and their rendered DOM)\n // stay reference-stable across transactions for unchanged containers.\n function nextDecorationSet(\n tr: Transaction,\n oldSet: DecorationSet,\n isEditable: boolean,\n ): DecorationSet {\n const mapped = oldSet.map(tr.mapping, tr.doc);\n const desiredPositions = new Set(\n isEditable ? getTrailingWidgetPositions(tr.doc) : [],\n );\n\n const keptPositions = new Set<number>();\n const stale: Decoration[] = [];\n for (const decoration of mapped.find()) {\n if (\n desiredPositions.has(decoration.from) &&\n !keptPositions.has(decoration.from)\n ) {\n keptPositions.add(decoration.from);\n } else {\n stale.push(decoration);\n }\n }\n const missing = [...desiredPositions].filter(\n (pos) => !keptPositions.has(pos),\n );\n\n let next = mapped;\n if (stale.length > 0) {\n next = next.remove(stale);\n }\n if (missing.length > 0) {\n next = next.add(tr.doc, missing.map(createTrailingWidget));\n }\n return next;\n }\n\n return {\n key: \"trailingNode\",\n prosemirrorPlugins: [\n new Plugin<DecorationSet>({\n key: PLUGIN_KEY,\n state: {\n init: (_, state) =>\n nextDecorationSet(\n state.tr,\n DecorationSet.empty,\n editor.isEditable,\n ),\n apply: (tr, oldSet) => {\n if (!tr.docChanged && !tr.getMeta(PLUGIN_KEY)) {\n return oldSet;\n }\n return nextDecorationSet(tr, oldSet, editor.isEditable);\n },\n },\n // Editable changes don't dispatch a transaction on their own, so the\n // plugin state can't re-evaluate on its own. Watch for the change\n // and dispatch a no-op transaction tagged with this plugin's key so\n // `apply` re-runs and adds or removes the widget.\n view(view) {\n let lastEditable = view.editable;\n return {\n update(view) {\n if (view.editable === lastEditable) {\n return;\n }\n lastEditable = view.editable;\n view.dispatch(view.state.tr.setMeta(PLUGIN_KEY, true));\n },\n };\n },\n props: {\n decorations: (state) => PLUGIN_KEY.getState(state),\n // Prevents ProseMirror from trying to move the selection into the\n // trailing block at the end of the document, which causes the text\n // caret to flicker in it before returning to its previous\n // position.\n handleKeyDown: (view, event) => {\n if (event.key !== \"ArrowRight\" && event.key !== \"ArrowDown\") {\n return false;\n }\n\n const { selection } = view.state;\n if (!selection.empty) {\n return false;\n }\n\n const docEnd = Selection.atEnd(view.state.doc);\n if (selection.$head.pos !== docEnd.$head.pos) {\n return false;\n }\n\n const rootGroup = view.state.doc.lastChild;\n if (\n !editor.isEditable ||\n !rootGroup ||\n !containerNeedsTrailingWidget(rootGroup)\n ) {\n return false;\n }\n\n event.preventDefault();\n return true;\n },\n },\n }),\n ],\n } as const;\n },\n);\n","import type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport {\n createExtension,\n createStore,\n type ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport {\n normalizeToUserStore,\n type User,\n type UserStoreOrResolver,\n} from \"../../user/index.js\";\n\n/**\n * Represents a single snapshot of a document's history, including metadata and content information.\n * Snapshots are used for versioning and can be created, listed, restored, and previewed through the\n * {@link VersioningEndpoints}.\n */\nexport interface VersionSnapshot {\n /**\n * The unique identifier for the snapshot. A plain string for real snapshots;\n * the {@link CURRENT_VERSION_ID} symbol for the synthetic \"Current version\"\n * entry (which no backend ever persists or round-trips).\n */\n id: string | typeof CURRENT_VERSION_ID;\n\n /**\n * The name of the snapshot.\n */\n name?: string;\n\n /**\n * The timestamp when the snapshot was created (unix timestamp).\n */\n createdAt: number;\n\n /**\n * The timestamp when the snapshot was last updated (unix timestamp).\n */\n updatedAt: number;\n\n /**\n * An optional secondary label for the snapshot, which can display additional information such as a custom description.\n * This is for display purposes only and is not used for any logic in the versioning system.\n *\n * For author attribution, prefer {@link by}: it holds raw user ids that the\n * view layer resolves to user info (and keeps up to date as users load).\n * When both are set, `secondaryLabel` wins.\n */\n secondaryLabel?: string;\n\n /**\n * The id(s) of the user(s) that authored this version, as raw user ids —\n * never pre-resolved to display names. The view layer resolves them via the\n * {@link VersioningExtension}'s user store (see\n * {@link VersioningExtensionOptions.resolveUsers}), reactively updating as\n * user info loads. Only used when {@link secondaryLabel} is unset.\n */\n by?: User[\"id\"] | User[\"id\"][];\n\n /**\n * The ID of the previous snapshot that this snapshot was restored from.\n */\n restoredFromSnapshotId?: string;\n}\n\n/**\n * Identifier for a single {@link VersionSnapshot}, either the bare id or the\n * whole reference. Tracks {@link VersionSnapshot.id}, so it also accepts the\n * {@link CURRENT_VERSION_ID} symbol.\n */\nexport type VersionSnapshotIdentifier =\n | VersionSnapshot[\"id\"]\n | Pick<VersionSnapshot, \"id\">;\n\n/**\n * The `id` of the synthetic \"Current version\" entry — the live document shown at\n * the top of `list()` and set as `previewedSnapshotId` while previewing it (see\n * {@link VersioningExtension.previewCurrentVersion}).\n *\n * A `unique symbol`, not a string, so it can never clash with a real snapshot id.\n * It's client-only — never fetched via `getContent` / `getAttributions` (the row\n * is previewed live) and never serialised, so no backend round-trips it. Because\n * {@link VersionSnapshot.id} is `string | typeof CURRENT_VERSION_ID`, code that\n * needs a string form for this one row (e.g. a React `key`) derives it locally.\n */\nexport const CURRENT_VERSION_ID: unique symbol = Symbol(\"bn-current-version\");\n\n/**\n * The backend contract for versioning: **where snapshot data lives** (pure\n * storage — in-memory, `localStorage`, HTTP, …). Counterpart to\n * {@link PreviewController} (*how a snapshot is rendered*) and\n * {@link VersioningExtensionOptions} (*how the live editor is bridged in*);\n * {@link VersioningExtension} orchestrates the three.\n *\n * Type params trace the data flow:\n * @typeParam Input - Live document handle passed to {@link create} / {@link restore},\n * from {@link VersioningExtensionOptions.getCurrentDocument} (e.g. `Y.Type`, `Block[]`).\n * @typeParam Output - Serialised snapshot content from {@link getContent} /\n * {@link restore}, rendered by {@link PreviewController.enterPreview} (e.g. `Uint8Array`).\n * @typeParam Attributions - Optional diff-authorship data from {@link getAttributions},\n * also consumed by {@link PreviewController.enterPreview} (e.g. `Y.ContentMap`).\n */\nexport interface VersioningEndpoints<\n Input = any,\n Output = any,\n Attributions = any,\n> {\n /**\n * List all snapshots for this document, sorted newest-first by\n * {@link VersionSnapshot.createdAt}.\n */\n list: () => Promise<VersionSnapshot[]>;\n /**\n * Create a new snapshot from the current content.\n *\n * @note omit for backends with continuous history (e.g. YHub's activity\n * timeline). Gates the extension's `canCreate` flag.\n */\n create?: (\n /** Live document to snapshot, from {@link VersioningExtensionOptions.getCurrentDocument}. */\n content: Input,\n options?: {\n /** Optional name for this snapshot. */\n name?: string;\n /** Id of the snapshot this one was restored from, if any. */\n restoredFromSnapshot?: VersionSnapshot;\n },\n ) => Promise<VersionSnapshot>;\n /**\n * Restore the document to a snapshot. Implementations should create any backup\n * snapshots they need before returning.\n *\n * @returns The restored content ({@link Output}, **not `void`**) — passed to\n * {@link PreviewController.applyRestore}.\n * @note omit to disable restore. Gates the extension's `canRestore` flag.\n */\n restore?: (\n /** Live document, from {@link VersioningExtensionOptions.getCurrentDocument} (for backup). */\n doc: Input,\n /** The snapshot to restore. */\n snapshot: VersionSnapshot,\n ) => Promise<Output>;\n /**\n * Fetch a snapshot's content ({@link Output}) for preview — same format as\n * {@link VersioningExtensionOptions.serializeCurrentContent}. Sibling of\n * {@link getAttributions}; both are the storage-side fetch that\n * {@link PreviewController.enterPreview} renders.\n */\n getContent: (snapshot: VersionSnapshot) => Promise<Output>;\n /**\n * Fetch diff-authorship data ({@link Attributions}: who/when) for the range\n * `compareTo → snapshot`, rendered by {@link PreviewController.enterPreview}\n * (its only consumer). Lives on the endpoint, not `enterPreview`, so one\n * preview controller pairs with attribution-capable (YHub) or attribution-less\n * (`localStorage`) backends — {@link Attributions} is that seam.\n *\n * @note omit and previews still render the content diff, minus attribution.\n */\n getAttributions?: (\n /** The previewed snapshot (the \"new\" side of the diff). */\n snapshot: VersionSnapshot,\n /** The baseline it's diffed against (the \"old\" side). */\n compareTo?: VersionSnapshot,\n ) => Promise<Attributions>;\n /**\n * Rename a snapshot.\n *\n * @note omit to disable rename. Gates the extension's `canRename` flag.\n */\n rename?: (snapshot: VersionSnapshot, name?: string) => Promise<void>;\n /**\n * Permanently remove a snapshot.\n *\n * @note omit for immutable-history backends (e.g. YHub). Gates the extension's\n * `canRemove` flag.\n */\n remove?: (snapshot: VersionSnapshot) => Promise<void>;\n}\n\n/**\n * A factory function for the endpoints to receive a reference to the editor.\n *\n * @typeParam Input - See {@link VersioningEndpoints}.\n * @typeParam Output - See {@link VersioningEndpoints}.\n * @typeParam Attributions - See {@link VersioningEndpoints}.\n */\nexport type VersioningEndpointsFactory<\n Input = any,\n Output = any,\n Attributions = any,\n> = (\n editor: BlockNoteEditor<any, any, any>,\n) => VersioningEndpoints<Input, Output, Attributions>;\n\n/**\n * Controls **how a snapshot is rendered** — the render-side counterpart to\n * {@link VersioningEndpoints} (storage). {@link VersioningExtension} fetches\n * content/attributions from the endpoints and delegates rendering here; keeping\n * the two separate lets one controller pair with different backends.\n *\n * @typeParam Output - Serialised snapshot content; matches the endpoints' `Output`.\n * @typeParam Attributions - Optional attribution data; matches the endpoints' `Attributions`.\n */\nexport interface PreviewController<Output = any, Attributions = any> {\n /**\n * Whether {@link enterPreview} can render a diff (uses `compareToContent`).\n * Defaults to `true`; `false` for show-one-version-only backends (e.g. the Yjs\n * v13 adapter). Surfaced as {@link VersioningExtension.canCompare}.\n */\n supportsComparison?: boolean;\n /**\n * Enter preview mode. Arguments come from the endpoints:\n * {@link VersioningEndpoints.getContent} (content) and\n * {@link VersioningEndpoints.getAttributions} (attributions).\n */\n enterPreview: (\n /** Snapshot to preview ({@link Output}, from {@link VersioningEndpoints.getContent}). */\n snapshotContent: Output,\n /** When set, diff `compareToContent` (baseline) against `snapshotContent`. */\n compareToContent?: Output,\n /**\n * Diff attributions ({@link Attributions}, from\n * {@link VersioningEndpoints.getAttributions}). Only meaningful with\n * `compareToContent`.\n */\n attributions?: Attributions,\n /**\n * The snapshot(s) this preview is for (metadata only — the content is\n * `snapshotContent` / `compareToContent`). Lets a controller label the\n * preview with e.g. the version's name, without smuggling it through the\n * {@link Attributions} channel. `snapshot` is the previewed version (the\n * {@link CURRENT_VERSION_ID} entry when previewing the live document);\n * `compareTo` is the baseline it's diffed against, if any.\n */\n context?: { snapshot: VersionSnapshot; compareTo?: VersionSnapshot },\n ) => void;\n /** Exit preview mode and resume normal editing. */\n exitPreview: () => void;\n /**\n * Apply restored content to the live document. Called with the {@link Output}\n * from {@link VersioningEndpoints.restore}, after preview mode has exited.\n */\n applyRestore: (snapshotContent: Output) => void;\n}\n\n/** Sort snapshots newest-first by creation time. */\nexport function sortSnapshotsNewestFirst(\n snapshots: VersionSnapshot[],\n): VersionSnapshot[] {\n return [...snapshots].sort((a, b) => b.createdAt - a.createdAt);\n}\n\n/**\n * Options accepted by the {@link VersioningExtension} — **how the live editor is\n * bridged in**, alongside the {@link VersioningEndpoints} (storage) and\n * {@link PreviewController} (rendering).\n *\n * @typeParam Input - See {@link VersioningEndpoints}.\n * @typeParam Output - See {@link VersioningEndpoints}.\n * @typeParam Attributions - See {@link VersioningEndpoints}.\n */\nexport type VersioningExtensionOptions<\n Input = any,\n Output = any,\n Attributions = any,\n> = {\n /**\n * Backend storage for snapshots.\n */\n endpoints:\n | VersioningEndpoints<Input, Output, Attributions>\n | VersioningEndpointsFactory<Input, Output, Attributions>;\n /**\n * Controls how snapshot previews and restores are rendered in the editor.\n */\n preview: PreviewController<Output, Attributions>;\n /**\n * The **live, mutable document handle** ({@link Input}) the backend snapshots\n * *from* / restores *into*. Passed to {@link VersioningEndpoints.create} and\n * {@link VersioningEndpoints.restore}. Cf. {@link serializeCurrentContent} (a\n * detached copy); the two coincide for some backends (in-memory:\n * `Input === Output === Block[]`) and differ for others (Yjs: `Y.Type` vs `Uint8Array`).\n */\n getCurrentDocument: () => Input;\n /**\n * The live document **serialised to snapshot format** ({@link Output}, matching\n * {@link VersioningEndpoints.getContent}), for diffing the live doc against a\n * snapshot (see {@link VersioningExtension.previewCurrentVersion}). Cf.\n * {@link getCurrentDocument} (the live handle).\n *\n * @note omit and the UI can't offer a \"Current version\" diff. Gates the\n * extension's `canPreviewCurrent` flag.\n */\n serializeCurrentContent?: () => Output | Promise<Output>;\n /**\n * Resolve user information for the author ids in {@link VersionSnapshot.by},\n * used by the view layer to render version-author labels.\n *\n * Either a resolver function (called with the ids of users that are not yet\n * cached, returning their information — a user store is built from it\n * internally) or a pre-built user store (see `createUserStore`). Pass the\n * same store you give the comments/collaboration extensions so a single\n * de-duped user cache is shared across features.\n *\n * @note omit and author ids are displayed as-is.\n */\n resolveUsers?: UserStoreOrResolver;\n};\n\nfunction snapshotNotFoundError(\n id: VersionSnapshotIdentifier | undefined,\n): never {\n const idResolved = typeof id === \"object\" ? id.id : id;\n throw new Error(`Snapshot not found: ${String(idResolved)}`);\n}\n\nexport const VersioningExtension = createExtension(\n ({\n options: optionsOrFactory,\n editor,\n }: ExtensionOptions<\n | VersioningExtensionOptions\n | ((editor: BlockNoteEditor<any, any, any>) => VersioningExtensionOptions)\n >) => {\n const {\n endpoints: endpointsRaw,\n preview,\n getCurrentDocument,\n serializeCurrentContent,\n resolveUsers,\n } = typeof optionsOrFactory === \"function\"\n ? optionsOrFactory(editor)\n : optionsOrFactory;\n\n const endpoints =\n typeof endpointsRaw === \"function\" ? endpointsRaw(editor) : endpointsRaw;\n // With no resolver this is an empty store: `getUser` always misses, so the\n // view layer falls back to showing the raw ids from `VersionSnapshot.by`.\n const userStore = normalizeToUserStore(resolveUsers);\n const store = createStore<{\n snapshots: VersionSnapshot[];\n /**\n * The id of the version currently shown in the editor (the \"new\" side of\n * a diff). `undefined` means the live, editable document. Is the\n * {@link CURRENT_VERSION_ID} symbol when previewing the live document as a\n * read-only diff against a snapshot.\n */\n previewedSnapshotId?: string | typeof CURRENT_VERSION_ID;\n /**\n * The id of the snapshot the preview is being diffed against (the\n * \"baseline\" / old side). `undefined` when not showing a diff. Always a\n * real snapshot id (never the current entry), but typed as the same union\n * as {@link VersionSnapshot.id} since it's copied from one. Used to render\n * the \"Comparing to\" indicator in the sidebar.\n */\n compareToSnapshotId?: string | typeof CURRENT_VERSION_ID;\n }>({\n snapshots: [],\n previewedSnapshotId: undefined,\n compareToSnapshotId: undefined,\n });\n\n const getSnapshot = (id: VersionSnapshotIdentifier | undefined) => {\n const idResolved = typeof id === \"object\" ? id.id : id;\n return store.state.snapshots.find(\n (snapshot) => snapshot.id === idResolved,\n );\n };\n\n const updateSnapshots = async () => {\n const snapshots = sortSnapshotsNewestFirst(await endpoints.list());\n store.setState((state) => ({\n ...state,\n snapshots,\n }));\n\n return snapshots;\n };\n\n const previewSnapshot = async (\n id: VersionSnapshotIdentifier,\n previewOptions?: {\n /**\n * When set, the preview shows a diff against this snapshot (typically the\n * chronologically previous version in the history list).\n */\n compareTo?: VersionSnapshotIdentifier;\n },\n ) => {\n const snapshot = getSnapshot(id);\n\n if (!snapshot) {\n snapshotNotFoundError(id);\n }\n\n const compareToSnapshot = previewOptions?.compareTo\n ? getSnapshot(previewOptions.compareTo)\n : undefined;\n\n store.setState((state) => ({\n ...state,\n previewedSnapshotId: snapshot.id,\n compareToSnapshotId: compareToSnapshot?.id,\n }));\n\n let compareToContent: unknown;\n let attributions: unknown;\n if (compareToSnapshot) {\n compareToContent = await endpoints.getContent(compareToSnapshot);\n // Attributions describe the diff between the baseline and this\n // snapshot, so they're only meaningful when comparing against another\n // version. Fetching them is optional: previews still render the content\n // diff without author/timestamp information when unavailable.\n if (endpoints.getAttributions) {\n attributions = await endpoints.getAttributions(\n snapshot,\n compareToSnapshot,\n );\n }\n }\n\n const snapshotContent = await endpoints.getContent(snapshot);\n preview.enterPreview(snapshotContent, compareToContent, attributions, {\n snapshot,\n compareTo: compareToSnapshot,\n });\n };\n\n /**\n * Preview the live (\"current\") document as a read-only diff against a\n * snapshot baseline. Unlike {@link previewSnapshot}, the \"new\" side of the\n * diff is the live document — serialised via `serializeCurrentContent` —\n * rather than a stored snapshot. The editor becomes non-editable while\n * previewing (editing is gated on `previewedSnapshotId === undefined`).\n */\n const previewCurrentVersion = async (previewOptions?: {\n /**\n * The snapshot to diff the live document against (the baseline). When\n * omitted, the live document is shown without a diff.\n */\n compareTo?: VersionSnapshotIdentifier;\n }) => {\n if (!serializeCurrentContent) {\n throw new Error(\n \"previewCurrentVersion requires `serializeCurrentContent` to be \" +\n \"provided to the VersioningExtension options.\",\n );\n }\n\n const compareToSnapshot = previewOptions?.compareTo\n ? getSnapshot(previewOptions.compareTo)\n : undefined;\n\n store.setState((state) => ({\n ...state,\n previewedSnapshotId: CURRENT_VERSION_ID,\n compareToSnapshotId: compareToSnapshot?.id,\n }));\n\n // Synthesise a snapshot for the live document so timestamp-based backends\n // (e.g. YHub) resolve the changeset window up to \"now\", and so the preview\n // controller gets a snapshot to key off. The id is the current-version\n // sentinel; backends ignore it and resolve the window from `createdAt`.\n const currentSnapshot: VersionSnapshot = {\n id: CURRENT_VERSION_ID,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n\n let compareToContent: unknown;\n let attributions: unknown;\n if (compareToSnapshot) {\n compareToContent = await endpoints.getContent(compareToSnapshot);\n if (endpoints.getAttributions) {\n attributions = await endpoints.getAttributions(\n currentSnapshot,\n compareToSnapshot,\n );\n }\n }\n\n const currentContent = await serializeCurrentContent();\n preview.enterPreview(currentContent, compareToContent, attributions, {\n snapshot: currentSnapshot,\n compareTo: compareToSnapshot,\n });\n };\n\n const exitPreview = () => {\n store.setState((state) => ({\n ...state,\n previewedSnapshotId: undefined,\n compareToSnapshotId: undefined,\n }));\n preview.exitPreview();\n };\n\n return {\n key: \"versioning\",\n store,\n userStore,\n list: async (): Promise<VersionSnapshot[]> => {\n return await updateSnapshots();\n },\n // Comparison is only offered when the preview controller can actually\n // render a diff (see PreviewController.supportsComparison). A getter so a\n // controller whose `supportsComparison` is itself dynamic (e.g. gated on\n // an opt-in diff extension that may be registered after this one) is read\n // lazily, not captured at init time.\n get canCompare() {\n return preview.supportsComparison !== false;\n },\n canCreate: endpoints.create !== undefined,\n create: endpoints.create\n ? async (options?: {\n /**\n * The optional name for this snapshot.\n */\n name?: string;\n /**\n * The ID of the snapshot this one was restored from, if applicable.\n */\n restoredFromSnapshot?: VersionSnapshotIdentifier;\n }): Promise<VersionSnapshot> => {\n const snapshot = await endpoints.create!(getCurrentDocument(), {\n name: options?.name,\n restoredFromSnapshot: getSnapshot(options?.restoredFromSnapshot),\n });\n // Show the new version immediately. Some backends (e.g. YHub) build\n // their version list from an activity timeline that lags a beat\n // behind the create, so waiting on a re-list would leave the UI\n // briefly stale.\n store.setState((state) => ({\n ...state,\n snapshots: sortSnapshotsNewestFirst([\n ...state.snapshots,\n snapshot,\n ]),\n }));\n // Reconcile with the backend's `list()` — it owns the \"current\n // version\" entry and any server-assigned metadata. If the refreshed\n // list doesn't include the just-created version yet (indexing lag),\n // keep the optimistic entry so it never flickers out.\n const listed = await endpoints.list();\n store.setState((state) => ({\n ...state,\n snapshots: sortSnapshotsNewestFirst(\n listed.some((s) => s.id === snapshot.id)\n ? listed\n : [...listed, snapshot],\n ),\n }));\n return snapshot;\n }\n : undefined,\n canRestore: endpoints.restore !== undefined,\n restore: endpoints.restore\n ? async (id: VersionSnapshotIdentifier) => {\n exitPreview();\n const snapshot = getSnapshot(id);\n\n if (!snapshot) {\n snapshotNotFoundError(id);\n }\n const snapshotContent = await endpoints.restore!(\n getCurrentDocument(),\n snapshot,\n );\n preview.applyRestore(snapshotContent);\n await updateSnapshots();\n return snapshotContent;\n }\n : undefined,\n canRename: endpoints.rename !== undefined,\n rename: endpoints.rename\n ? async (\n id: VersionSnapshotIdentifier,\n name?: string,\n ): Promise<void> => {\n const snapshot = getSnapshot(id);\n if (!snapshot) {\n snapshotNotFoundError(id);\n }\n await endpoints.rename!(snapshot, name);\n store.setState((state) => ({\n ...state,\n snapshots: state.snapshots.map((s) =>\n s.id === id ? { ...s, name, updatedAt: Date.now() } : s,\n ),\n }));\n }\n : undefined,\n canRemove: endpoints.remove !== undefined,\n remove: endpoints.remove\n ? async (id: VersionSnapshotIdentifier): Promise<void> => {\n const snapshot = getSnapshot(id);\n if (!snapshot) {\n snapshotNotFoundError(id);\n }\n // If the snapshot being removed is the one currently previewed, or\n // the baseline it's being diffed against, exit preview first so the\n // editor returns to the live document instead of showing (or\n // comparing against) a version that no longer exists.\n if (\n store.state.previewedSnapshotId === snapshot.id ||\n store.state.compareToSnapshotId === snapshot.id\n ) {\n exitPreview();\n }\n await endpoints.remove!(snapshot);\n // Remove it optimistically so the row disappears immediately, then\n // reconcile with the backend's authoritative list.\n store.setState((state) => ({\n ...state,\n snapshots: state.snapshots.filter((s) => s.id !== snapshot.id),\n }));\n await updateSnapshots();\n }\n : undefined,\n previewSnapshot,\n canPreviewCurrent: serializeCurrentContent !== undefined,\n previewCurrentVersion: serializeCurrentContent\n ? previewCurrentVersion\n : undefined,\n exitPreview,\n } as const;\n },\n);\n","import type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport type { Block } from \"../../blocks/defaultBlocks.js\";\nimport type { DiffVersioningExtension } from \"../../y/extensions/DiffVersioningExtension.js\";\nimport type {\n PreviewController,\n VersioningEndpoints,\n VersioningExtensionOptions,\n VersionSnapshot,\n} from \"./Versioning.js\";\nimport { CURRENT_VERSION_ID, sortSnapshotsNewestFirst } from \"./Versioning.js\";\n\n/**\n * Label shown on a diff's marks for the version that introduced the changes.\n * The previewed snapshot is the \"new\" side of the diff; the current-version\n * entry (previewing the live doc) has no name, so it reads \"Current version\".\n */\nfunction versionLabel(snapshot: VersionSnapshot): string {\n if (snapshot.id === CURRENT_VERSION_ID) {\n return \"Current version\";\n }\n return snapshot.name ?? \"Unnamed version\";\n}\n\n// ---------------------------------------------------------------------------\n// Preview Controller\n// ---------------------------------------------------------------------------\n\n/**\n * Create a {@link PreviewController} that swaps the BlockNote document in and\n * out using `editor.replaceBlocks`.\n *\n * When entering preview mode the current document is saved so it can be\n * restored on exit. Successive `enterPreview` calls without an intervening\n * `exitPreview` preserve the original saved document.\n */\nexport function createInMemoryPreviewController(\n editor: BlockNoteEditor<any, any, any>,\n): PreviewController<Block<any, any, any>[]> {\n let savedDoc: Block<any, any, any>[] | undefined;\n // True while a diff (attribution marks) is on screen, so exit/restore knows to\n // route the cleanup through the diff extension's node-view rebuild.\n let showingDiff = false;\n\n const replaceDoc = (blocks: Block<any, any, any>[]) => {\n editor.replaceBlocks(editor.document, blocks);\n };\n\n // The opt-in diff extension, if the consuming editor registered it. Looked up\n // by key so this module keeps zero runtime dependency on `@y/*`.\n const getDiff = () =>\n editor.getExtension<typeof DiffVersioningExtension>(\"diffVersioning\");\n\n return {\n // Comparison is only possible when the (opt-in) diff extension is present —\n // otherwise previewing a comparison just statically shows the snapshot, so\n // the UI shouldn't offer it. A getter (not a static `true`) so it's\n // independent of the order the extensions were registered in: the diff\n // extension is typically added after the versioning extension, and this is\n // read lazily (on render) once both are registered.\n get supportsComparison() {\n return getDiff() !== undefined;\n },\n enterPreview(\n snapshotContent: Block<any, any, any>[],\n compareToContent?: Block<any, any, any>[],\n _attributions?: unknown,\n context?: { snapshot: VersionSnapshot; compareTo?: VersionSnapshot },\n ) {\n // Save the live doc on first enter (successive enters keep the original).\n if (savedDoc === undefined) {\n savedDoc = editor.document;\n }\n\n const diff = getDiff();\n if (compareToContent && diff) {\n // Render a diff of compareTo → snapshot, labelling the changes with the\n // previewed version's name (the diff's single \"author\").\n diff.renderDiff(\n snapshotContent,\n compareToContent,\n context && versionLabel(context.snapshot),\n );\n showingDiff = true;\n return;\n }\n\n // No comparison requested, or no diff extension registered: just show the\n // snapshot content statically.\n showingDiff = false;\n replaceDoc(snapshotContent);\n },\n\n exitPreview() {\n if (savedDoc !== undefined) {\n const diff = getDiff();\n if (showingDiff && diff) {\n diff.clearDiff(savedDoc);\n } else {\n replaceDoc(savedDoc);\n }\n savedDoc = undefined;\n showingDiff = false;\n }\n },\n\n applyRestore(snapshotContent: Block<any, any, any>[]) {\n const diff = getDiff();\n if (showingDiff && diff) {\n diff.clearDiff(snapshotContent);\n } else {\n replaceDoc(snapshotContent);\n }\n // Clear saved doc — the restored content is now the live document.\n savedDoc = undefined;\n showingDiff = false;\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Endpoints (in-memory storage)\n// ---------------------------------------------------------------------------\n\n/**\n * Create a {@link VersioningEndpoints} that stores snapshots entirely in\n * memory. Useful for local-only / non-collaborative editors where you want\n * versioning without any persistence layer.\n *\n * Snapshots are stored as BlockNote document JSON (`Block[]`).\n */\nexport function createInMemoryVersioningEndpoints(): VersioningEndpoints<\n Block<any, any, any>[],\n Block<any, any, any>[]\n> {\n const snapshots: VersionSnapshot[] = [];\n const contents = new Map<string, Block<any, any, any>[]>();\n let nextId = 1;\n\n // `Date.now()` only has millisecond resolution, so two snapshots created in\n // the same tick would share a timestamp and `sortSnapshotsNewestFirst` (which\n // has nothing else to order on) could list them oldest-first. Hand out\n // strictly increasing timestamps so creation order is always preserved.\n let lastTimestamp = 0;\n function nextTimestamp() {\n lastTimestamp = Math.max(Date.now(), lastTimestamp + 1);\n return lastTimestamp;\n }\n\n return {\n async list() {\n return sortSnapshotsNewestFirst([...snapshots]);\n },\n\n async create(currentDoc, options) {\n const now = nextTimestamp();\n const id = String(nextId++);\n const snapshot: VersionSnapshot = {\n id,\n name: options?.name,\n createdAt: now,\n updatedAt: now,\n };\n snapshots.push(snapshot);\n contents.set(id, structuredClone(currentDoc));\n return snapshot;\n },\n\n async restore(currentDoc, snapshot) {\n // Stored snapshots always have string ids (only the synthetic current\n // entry carries the symbol, and it never reaches these methods).\n const id = String(snapshot.id);\n const snapshotContent = contents.get(id);\n if (!snapshotContent) {\n throw new Error(`Snapshot ${id} not found`);\n }\n\n // Create a \"Restored from …\" snapshot of the current state before\n // restoring, so the user can undo the restore.\n const now = nextTimestamp();\n const backupId = String(nextId++);\n const backup: VersionSnapshot = {\n id: backupId,\n name: \"Before restore\",\n createdAt: now,\n updatedAt: now,\n restoredFromSnapshotId: id,\n };\n snapshots.push(backup);\n contents.set(backupId, structuredClone(currentDoc));\n\n return structuredClone(snapshotContent);\n },\n\n async getContent(snapshot) {\n const id = String(snapshot.id);\n const content = contents.get(id);\n if (!content) {\n throw new Error(`Snapshot ${id} not found`);\n }\n return structuredClone(content);\n },\n\n async rename(snapshot, name) {\n const stored = snapshots.find((s) => s.id === snapshot.id);\n if (!stored) {\n throw new Error(`Snapshot ${String(snapshot.id)} not found`);\n }\n stored.name = name;\n stored.updatedAt = nextTimestamp();\n },\n\n async remove(snapshot) {\n const index = snapshots.findIndex((s) => s.id === snapshot.id);\n if (index === -1) {\n throw new Error(`Snapshot ${String(snapshot.id)} not found`);\n }\n snapshots.splice(index, 1);\n contents.delete(String(snapshot.id));\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Adapter (convenience)\n// ---------------------------------------------------------------------------\n\n/**\n * Create all the options needed to wire a {@link VersioningExtension} with\n * fully in-memory storage and BlockNote JSON-based preview.\n *\n * @example\n * ```ts\n * import { VersioningExtension } from \"@blocknote/core/extensions\";\n * import { createInMemoryVersioningAdapter } from \"@blocknote/core/extensions\";\n *\n * const editor = BlockNoteEditor.create({\n * extensions: [\n * VersioningExtension(createInMemoryVersioningAdapter(editor)),\n * ],\n * });\n * ```\n */\nexport function createInMemoryVersioningAdapter(\n editor: BlockNoteEditor<any, any, any>,\n): VersioningExtensionOptions<Block<any, any, any>[], Block<any, any, any>[]> {\n const endpoints = createInMemoryVersioningEndpoints();\n\n return {\n // The raw endpoints are pure snapshot storage. The \"current version\" is a\n // view concern owned by the adapter (it's the layer that knows about the\n // live editor), so we wrap `list()` to always surface a current entry: the\n // live document is the editable working copy, and the entry is how the user\n // returns to live editing and compares against saved snapshots. No\n // timestamp/author is tracked, so the row just reads \"Current version\"\n // (see CurrentSnapshot in @blocknote/react).\n endpoints: {\n ...endpoints,\n list: async () => {\n const current: VersionSnapshot = {\n id: CURRENT_VERSION_ID,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n return [current, ...(await endpoints.list())];\n },\n },\n preview: createInMemoryPreviewController(editor),\n getCurrentDocument: () => editor.document,\n // The live document is already in the snapshot content format (`Block[]`),\n // so previewing \"current\" as a diff just reuses the live blocks.\n serializeCurrentContent: () => editor.document,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+BA,SAAS,GAA8B,GAAsB;CAE3D,IAAM,IACJ,MAAM,KAAK,EAAQ,SAAS,CAAC,CAAC,QAC3B,MAAc,CAAC,EAAU,WAAW,KAAK,CAC5C,KAAK,CAAC;CAER,AAAI,EAAU,SAAS,IACrB,EAAQ,YAAY,EAAU,KAAK,GAAG,IAEtC,EAAQ,gBAAgB,OAAO;AAEnC;AAEA,SAAgB,GAKd,GACA,GACA,GACA,GACA;CACA,IAAI;CAGJ,IAAI,CAAC,GACH,MAAU,MAAM,0BAA0B;CACrC,IAAI,OAAO,KAAiB,UACjC,IAAQ,EACN,CAAC,CAAY,GACb,EAAO,UACP,GAAS,SACX;MACK,IAAI,MAAM,QAAQ,CAAY,GACnC,IAAQ,EACN,GACA,EAAO,UACP,GAAS,SACX;MACK,IAAI,EAAa,SAAS,gBAC/B,IAAQ,EAAoB,GAAc,EAAO,QAAQ;MAEzD,MAAM,IAAI,EAAqB,EAAa,IAAI;CAKlD,IAAM,KADM,GAAS,YAAY,SAAA,CACZ,uBAAuB;CAE5C,KAAK,IAAM,KAAQ,GAEjB,IACE,EAAK,KAAK,SAAS,UACnB,EAAO,OAAO,oBAAoB,EAAK,KAAK,OAC5C;EACA,IAAM,IACJ,EAAO,OAAO,mBAAmB,EAAK,KAAK,KAAK,CAAC;EAEnD,IAAI,GAA6B;GAE/B,IAAM,IAAgB,EACpB,GACA,EAAO,OAAO,qBACd,EAAO,OAAO,WAChB,GAGM,IAAS,EAA4B,iBACvC,EAA4B,eAC1B,GACA,CACF,IACA,EAA4B,OAAO,KACjC;IACE,YAAY;IACZ,OAAO,KAAA;GACT,GACA,SACM,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